diff --git "a/746.jsonl" "b/746.jsonl" new file mode 100644--- /dev/null +++ "b/746.jsonl" @@ -0,0 +1,645 @@ +{"seq_id":"468709016","text":"'''\n1. You are given a string str of digits. (will never start with a 0)\n2. You are required to encode the str as per following rules\n 1 -> a\n 2 -> b\n 3 -> c\n ..\n 25 -> y\n 26 -> z\n3. Complete the body of printEncodings function - without changing signature - to calculate and print all encodings of str.\n\nUse the input-output below to get more understanding on what is required\n\n123 -> abc, aw, lc\n993 -> iic\n013 -> Invalid input. A string starting with 0 will not be passed.\n103 -> jc\n303 -> No output possible. But such a string maybe passed. In this case print nothing.\n\nSample Input:\n\n655196\n\nSample Output:\n\nfeeaif\nfeesf\n\n\nhttps://www.youtube.com/watch?v=2ClSccwnq1Y&list=PL-Jc9J83PIiFxaBahjslhBD1LiJAV7nKs&index=45\n\n'''\n\ndef printEncodings(ques, asf):\n \n if(len(ques) == 0):\n print(asf)\n return\n \n elif(len(ques) == 1):\n \n if(ques[0] == '0'):\n return\n else:\n ch0 = ques[:1]\n roq0 = ques[1:]\n code0 = ord('a') + int(ch0) - 1\n printEncodings(roq0, asf + chr(code0))\n \n # if length of ques is 2 or greater than 2 \n else:\n \n if(ques[0] == '0'):\n return\n else:\n # taking only first int. i.e. out of 123, take ch0 = 1 and roq0 = 23\n ch0 = ques[:1]\n roq0 = ques[1:]\n code0 = ord('a') + int(ch0) - 1\n printEncodings(roq0, asf + chr(code0))\n \n # taking two ints. i.e. out of 123, take ch0 = 12 and roq0 = 3\n ch1 = ques[:2]\n roq1 = ques[2:]\n code1 = ord('a') + int(ch1) - 1\n if(int(ch1) <= 26):\n printEncodings(roq1, asf + chr(code1))\n \nprintEncodings(\"655196\", \"\")\n \n \n \n \n \n \n \n \n ","sub_path":"pepcoding/recursion/19_print_encodings.py","file_name":"19_print_encodings.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"184219721","text":"#!/usr/bin/env python3\n\n\"\"\"\nBX2 scanner and parser\n\"\"\"\n\nfrom ply import lex, yacc\nfrom ply_util import *\nimport ast\n\n# Reserved keywords\nreserved = {\n 'var' : 'VAR',\n 'int' : 'INT',\n 'bool' : 'BOOL',\n 'void' : 'VOID',\n 'true' : 'TRUE',\n 'false' : 'FALSE',\n 'proc' : 'PROC',\n 'if' : 'IF',\n 'else' : 'ELSE',\n 'while' : 'WHILE',\n 'break' : 'BREAK',\n 'continue': 'CONTINUE',\n 'return' : 'RETURN',\n 'print' : 'PRINT',\n}\n\n# All tokens\ntokens = (\n # Punctuation\n 'LPAREN', 'RPAREN', 'LBRACE', 'RBRACE',\n 'COMMA', 'COLON', 'SEMICOLON', 'EQ',\n # Arithmetic Operators\n 'PLUS', 'MINUS', 'STAR', 'SLASH', 'PERCENT',\n 'AMP', 'BAR', 'CARET', 'TILDE',\n 'LTLT', 'GTGT',\n 'EQEQ', 'NEQ', 'LT', 'LTEQ', 'GT', 'GTEQ',\n 'AMPAMP', 'BARBAR', 'NOT', 'UMINUS',\n # Primitives\n 'IDENT', 'NUMBER',\n) + tuple(reserved.values())\n\n# ------------------------------------------------------------------------------\n\ndef print_error_message(tok, msg):\n \"\"\"Print an error message `msg' at the location of `tok'\"\"\"\n lineno = tok.lexer.lineno\n if hasattr(tok.lexer, 'lexmatch'):\n tokstr = tok.lexer.lexmatch.group(0)\n curpos = tok.lexer.lexpos - len(tokstr)\n else:\n tokstr = tok.value[0]\n curpos = tok.lexer.lexpos\n # scan backwards from curpos for the position of the beginning of line (bol)\n bolpos = tok.lexer.lexdata.rfind('\\n', 0, curpos) + 1\n # scan forwards from curpos for the position of the end of the line (eol)\n eolpos = tok.lexer.lexdata.find('\\n', curpos)\n if eolpos == -1: eolpos = tok.lexer.lexlen\n # offset of the given token\n charpos = max(curpos - bolpos, 0) + 1\n errfile = getattr(tok.lexer, 'errfile', None)\n provenance = getattr(tok.lexer, 'provenance', None)\n if provenance:\n print(f'At {provenance}, line {lineno}, character {charpos}:', file=errfile)\n else:\n print(f'At line {lineno}, character {charpos}:', file=errfile)\n print(msg, file=errfile)\n print('>', tok.lexer.lexdata[bolpos:eolpos], file=errfile)\n print(' '*(charpos+1), '^'*len(tokstr), sep='', file=errfile)\n\n# ------------------------------------------------------------------------------\n\n# LEXER:\n\ndef create_lexer():\n t_ignore = ' \\t\\f\\v\\r'\n\n def t_newline_or_comment(t):\n r'\\n|//[^\\n]*\\n?'\n t.lexer.lineno += 1\n\n # Operators and Punctuation\n t_LPAREN = r'\\('\n t_RPAREN = r'\\)'\n t_LBRACE = r'\\{'\n t_RBRACE = r'\\}'\n t_COMMA = r'\\,'\n t_COLON = r'\\:'\n t_SEMICOLON = r'\\;'\n t_EQ = r'\\='\n t_PLUS = r'\\+'\n t_MINUS = r'\\-'\n t_STAR = r'\\*'\n t_SLASH = r'\\/'\n t_PERCENT = r'\\%'\n t_AMP = r'\\&'\n t_BAR = r'\\|'\n t_CARET = r'\\^'\n t_TILDE = r'\\~'\n t_LTLT = r'\\<\\<'\n t_GTGT = r'\\>\\>'\n t_EQEQ = r'\\=\\='\n t_NEQ = r'\\!\\='\n t_LT = r'\\<'\n t_LTEQ = r'\\<\\='\n t_GT = r'\\>'\n t_GTEQ = r'\\>\\='\n t_AMPAMP = r'\\&\\&'\n t_BARBAR = r'\\|\\|'\n t_NOT = r'\\!'\n\n # Primitives\n def t_IDENT(t):\n r'[A-Za-z_][A-Za-z0-9_]*'\n t.type = reserved.get(t.value, 'IDENT')\n # t.value == whatever the above regex matches\n return t\n\n def t_NUMBER(t):\n r'0|-?[1-9][0-9]*'\n # t.type == 'NUMBER'\n t.value = int(t.value)\n if not (t.value >= -(1<<63) and t.value < (1<<63)):\n print_error_message(t, f'Error: numerical literal {t.value} not in range(0, 1<<63)')\n raise SyntaxError('Bad number')\n return t\n\n # error messages\n def t_error(t):\n print_error_message(t, f'Warning: skipping illegal character {t.value[0]}')\n t.lexer.skip(1)\n \n return extend_lexer(lex.lex())\n\n# ------------------------------------------------------------------------------\n\nprecedence = (\n ('left', 'BARBAR'),\n ('left', 'AMPAMP'),\n ('left', 'BAR'),\n ('left', 'CARET'),\n ('left', 'AMP'),\n ('nonassoc', 'EQEQ', 'NEQ'),\n ('nonassoc', 'LT', 'LTEQ', 'GT', 'GTEQ'),\n ('left', 'LTLT', 'GTGT'),\n ('left', 'PLUS', 'MINUS'),\n ('left', 'STAR', 'SLASH', 'PERCENT'),\n ('right', 'UMINUS', 'NOT'),\n ('right', 'TILDE'),\n)\n\nclass Node:\n def __init__(self, opcode, value, *kids):\n self.opcode = opcode\n self.value = value\n self.kids = kids\n\n def __repr__(self):\n return '({} {}{}{})'\\\n .format(self.opcode, repr(self.value),\n '' if len(self.kids) == 0 else ' ',\n ' '.join(repr(kid) for kid in self.kids))\n\n def __eq__(self, other):\n return \\\n isinstance(other, Node) and \\\n self.opcode == other.opcode and \\\n self.value == other.value and \\\n self.kids == other.kids\n\ndef create_parser():\n\n def p_expr_ident(p):\n '''expr : IDENT'''\n p[0] = ast.Variable(p[1])\n\n def p_expr_number(p):\n '''expr : NUMBER'''\n p[0] = ast.Number(p[1])\n\n def p_expr_boolean(p):\n '''expr : TRUE\n | FALSE'''\n p[0] = ast.Boolean(p[1])\n\n def p_expr_call(p):\n '''expr : call'''\n p[0] = p[1]\n \n def p_call(p):\n '''call : PRINT LPAREN args RPAREN\n | IDENT LPAREN args RPAREN'''\n #p[0] = ast.Appl(p[1], *p[3])\n p[0] = ast.Call(p[1], *p[3])\n\n def p_args(p):\n '''args : e\n | args1'''\n if p[1] is None: p[0] = []\n else: p[0] = p[1]\n\n def p_args1(p):\n '''args1 : expr\n | expr COMMA args1'''\n if len(p) == 2: p[0] = [p[1]]\n else:\n p[0] = [p[1]]\n p[0].extend(p[3])\n\n def p_expr_binop(p):\n '''expr : expr PLUS expr\n | expr MINUS expr\n | expr STAR expr\n | expr SLASH expr\n | expr PERCENT expr\n | expr AMP expr\n | expr BAR expr\n | expr CARET expr\n | expr LTLT expr\n | expr GTGT expr\n | expr EQEQ expr\n | expr NEQ expr\n | expr LT expr\n | expr LTEQ expr\n | expr GT expr\n | expr GTEQ expr\n | expr AMPAMP expr\n | expr BARBAR expr'''\n p[0] = ast.Appl(p[2], p[1], p[3])\n\n def p_expr_unop(p):\n '''expr : MINUS expr %prec UMINUS\n | UMINUS expr\n | TILDE expr\n | NOT expr'''\n # if p[1] == '-': op = 'u-'\n # else: op = p[1]\n op = p[1]\n p[0] = ast.Appl(op, p[2])\n\n def p_expr_parens(p):\n '''expr : LPAREN expr RPAREN'''\n p[0] = p[2]\n\n def p_vardecl(p):\n '''vardecl : VAR varinits COLON ty SEMICOLON'''\n p[0] = ast.VarDecl(p[2], p[4])\n\n def p_varinits(p):\n '''varinits : varinit\n | varinit COMMA varinits'''\n if len(p) == 2: p[0] = [p[1]]\n else: \n p[0] = [p[1]]\n p[0].extend(p[3])\n\n def p_varinit(p):\n '''varinit : IDENT EQ expr'''\n p[0] = (p[1], p[3])\n\n def p_stmt(p):\n '''stmt : vardecl\n | assign\n | eval\n | block\n | ifelse\n | while\n | break\n | continue\n | return'''\n p[0] = p[1]\n\n def p_assign(p):\n '''assign : IDENT EQ expr SEMICOLON'''\n p[0] = ast.Assign(p[1], p[3])\n\n def p_eval(p):\n '''eval : expr SEMICOLON'''\n p[0] = ast.Eval(p[1])\n\n def p_while(p):\n '''while : WHILE LPAREN expr RPAREN block'''\n p[0] = ast.While(p[3], p[5])\n\n def p_return(p):\n '''return : RETURN SEMICOLON\n | RETURN expr SEMICOLON'''\n if len(p) == 3: p[0] = ast.Return(None)\n else: p[0] = ast.Return(p[2])\n\n def p_break(p):\n '''break : BREAK SEMICOLON'''\n p[0] = ast.Break()\n\n def p_continue(p):\n '''continue : CONTINUE SEMICOLON'''\n p[0] = ast.Continue()\n\n def p_ifelse(p):\n '''ifelse : IF LPAREN expr RPAREN block ifcont'''\n p[0] = ast.IfElse(p[3], p[5], p[6])\n\n def p_ifcont(p):\n '''ifcont : e\n | ELSE ifelse\n | ELSE block'''\n if len(p) == 2: p[0] = None\n else: p[0] = p[2]\n\n def p_block(p):\n '''block : LBRACE stmts RBRACE'''\n p[0] = ast.Block(p[2])\n\n def p_stmts(p):\n '''stmts : e\n | stmt stmts'''\n if len(p) == 2: p[0] = []\n else:\n p[0] = [p[1]]\n p[0].extend(p[2])\n\n def p_decl(p):\n '''decl : vardecl\n | proc'''\n p[0] = p[1]\n\n def p_e(p):\n '''e : '''\n pass\n\n def p_S(p):\n '''S : program'''\n p[0] = ast.Program(p[1])\n\n def p_program(p):\n '''program : e\n | decl program'''\n if len(p) == 2: p[0] = []\n else: \n p[0] = [p[1]]\n p[0].extend(p[2])\n\n def p_ty(p):\n '''ty : INT\n | BOOL\n | VOID'''\n if p[1] == 'int': p[0] = ast.Type.INT\n elif p[1] == 'bool': p[0] = ast.Type.BOOL\n else: raise ValueError(\"'void' is not a valid token\")\n\n def p_proc(p):\n '''proc : PROC IDENT LPAREN params RPAREN retty block'''\n p[0] = ast.Proc(p[2], p[4], p[6], p[7])\n\n def p_params(p):\n '''params : e\n | paramgroups'''\n if not p[1]: p[0] = []\n else: p[0] = p[1]\n\n def p_paramgroups(p):\n '''paramgroups : paramgroup\n | paramgroup COMMA paramgroups'''\n if len(p) == 2: p[0] = [p[1]]\n else: \n p[0] = [p[1]]\n p[0].extend(p[3])\n\n def p_paramgroup(p):\n '''paramgroup : paramvars COLON ty'''\n p[0] = (p[1], p[3])\n\n def p_paramvars(p):\n '''paramvars : IDENT\n | IDENT COMMA paramvars'''\n if len(p) == 2: p[0] = [p[1]]\n else: \n p[0] = [p[1]]\n p[0].extend(p[3])\n\n def p_retty(p):\n '''retty : e\n | COLON ty'''\n if len(p) == 2: p[0] = ast.Type.VOID\n else: p[0] = p[2]\n\n def p_error(p):\n if not p: return\n p.lexer.lexpos -= len(p.value)\n print_at(p, f'Error: syntax error while processing {p.type}')\n # Note: SyntaxError is a built in exception in Python\n raise SyntaxError(p.type)\n\n return yacc.yacc(start='S')\n\n# ------------------------------------------------------------------------------\n\n\n# Create the lexer and the parser\nparser = create_parser()\nlexer = create_lexer()\n\ndef set_source(text):\n \"\"\"Load some source code directly into the lexer\"\"\"\n lexer.input(text)\n lexer.lineno = 1\n lexer.provenance = None\n\ndef load_source(filename):\n \"\"\"Load a file into the lexer\"\"\"\n with open(filename, 'r') as f:\n lexer.input(f.read())\n lexer.lineno = 1\n lexer.provenance = f'file \"{filename}\"'\n\n# --------------------------------------------------------------------------------\n\nif __name__ == '__main__':\n pass\n","sub_path":"Lab4_Procedures_and_Control_Flow_Graphs/cse302_lab4/bx2_parser.py","file_name":"bx2_parser.py","file_ext":"py","file_size_in_byte":11215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"352148930","text":"# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n head = ListNode()\n head.val = l1.val + l2.val\n l1, l2 = l1.next, l2.next\n while l1 or l2:\n num = 0\n if l1:\n num += l1.val\n if l2:\n num += l2.val\n nex = ListNode()\n nex.val = num\n head.next = nex\n head = nex\n return head\n","sub_path":"LeetCode/2.两数相加.py","file_name":"2.两数相加.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"512690377","text":"import ipywidgets as widgets\nimport pandas\nimport logging\nimport ipyaggrid\nfrom Bio import SeqIO\nfrom io import StringIO\n\nimport re\nimport json\n\nfrom IPython.display import IFrame, clear_output, Image\nfrom GenDBScraper.PseudomonasDotComScraper import PseudomonasDotComScraper, pdc_query\n\nfrom GenDBScraper.StringDBScraper import StringDBScraper, stringdb_query\n\n\ndef sbw25_okm():\n clear_output()\n frame = IFrame(\"https://openknowledgemaps.org/map/4aafb7d70516de0f56190d374bf398c8&embed=true\", width=1000, height=1000)\n return frame\n #display(frame)\n \ndef feature_okm_js(locus_tag):\n okms = pandas.read_json(\"pflu_okm_urls_20190424.json\", typ='series', orient='records')\n\n if locus_tag.upper() in okms.keys():\n frame = ''''''.format(okms[locus_tag.upper()]+'''&embed=true''')\n\n else:\n frame = \"\"\n\n return frame\n\ndef feature_okm(locus_tag):\n okms = pandas.read_json(\"pflu_okm_urls_20190424.json\", typ='series', orient='records')\n\n if locus_tag.upper() in okms.keys():\n frame = IFrame(okms[locus_tag.upper()]+\"&embed=true\", width=900, height=800)\n\n else:\n frame = widgets.Label(\"No maps found for {}\".format(locus_tag))\n\n clear_output(wait=True) \n #display(frame)\n return frame\n\ndef run_pdc(strain=None, locus_tag=None):\n \n clear_output(wait=True)\n \n pdc = PseudomonasDotComScraper(query=pdc_query(strain=strain, feature=locus_tag))\n query_string = \"__\".join([pdc.query[0].strain, pdc.query[0].feature])\n pdc.connect()\n pdc.run_query()\n \n \n results = pdc.results[query_string]\n \n return results\n \n\n# Need to treat each tab and subtabs individually\ndef get_grids(data_tables):\n \"\"\" Create grid view of all data tables\"\"\"\n \n if not isinstance(data_tables, dict):\n raise TypeError(\"Input parameter 'data_tables' must be of type dict. Received type is {}\".format(type(data_tables)))\n \n tabs = widgets.Tab() \n \n children = []\n titles = []\n \n skipped = [\"Ortholog xml\"]\n \n for i, title in enumerate(data_tables.keys()):\n if title in skipped:\n logging.debug(\"Skipping %s\", title)\n continue\n \n df = data_tables[title]\n if df is None:\n logging.debug(\"Skipping %s\", title)\n continue\n\n if isinstance(df, pandas.DataFrame): \n if df.empty:\n logging.debug(\"Skipping %s\", title)\n continue\n \n df = df.rename(str, axis='columns')\n \n grid_options={'columnDefs' : [{'field': c} for c in df.columns],\n 'enableSorting': True,\n 'enableFilter': True,\n 'enableColResize': True,\n 'enableRangeSelection': True,\n }\n \n if title.lower() == \"ortholog group\": \n for column_def in grid_options['columnDefs']:\n pattern = re.compile(r\"^GI$\") \n if pattern.match(column_def['field']):\n column_def['cellRenderer'] = \"\"\"function(params) { return ''+params.value+''; }\"\"\"\n \n if title.lower() == \"ortholog cluster\": \n for column_def in grid_options['columnDefs']:\n pattern = re.compile(r\"^GI \\(Strain [1,2]\\)$\") \n if pattern.match(column_def['field']):\n column_def['cellRenderer'] = \"\"\"function(params) { return ''+params.value+''; }\"\"\"\n \n if title.lower() == \"cross-references\":\n for column_def in grid_options['columnDefs']:\n pattern = re.compile(r\"^[U,u]rl$\")\n if pattern.match(column_def['field']):\n column_def['cellRenderer'] = \"\"\"function(params) { return ''+params.value+''; }\"\"\"\n \n if title.lower() == \"individual mappings\":\n for column_def in grid_options['columnDefs']:\n pattern = re.compile(r\"^PMID$\")\n if pattern.match(column_def['field']):\n column_def['cellRenderer'] = \"\"\"function(params) { return ''+params.value+''; }\"\"\"\n \n if title.lower() == \"gene ontology\":\n for column_def in grid_options['columnDefs']:\n # GO Accession\n pattern = re.compile(r\"^Accession$\")\n if pattern.match(column_def['field']):\n column_def['cellRenderer'] = \"\"\"function(params) { return ''+params.value+''; }\"\"\"\n \n # ECO accession\n pattern = re.compile(r\"^Evidence Ontology \\(ECO\\) Code$\")\n if pattern.match(column_def['field']):\n column_def['cellRenderer'] = \"\"\"function(params) { return ''+params.value+''; }\"\"\"\n \n if title.lower() == \"functional predictions from interpro\":\n for column_def in grid_options['columnDefs']:\n \n pattern = re.compile(r\"^Interpro Accession$\")\n if pattern.match(column_def['field']):\n column_def['cellRenderer'] = \"\"\"function(params) { return ''+params.value+''; }\"\"\"\n \n if re.match(r'^transposon.*$', title.lower() ):\n for column_def in grid_options['columnDefs']:\n pattern = re.compile(r\"^Reference$\")\n if pattern.match(column_def['field']):\n column_def['cellRenderer'] = \"\"\"function(params) { return ''+params.value+''; }\"\"\"\n\n if title.lower() == 'genes':\n for column_def in grid_options['columnDefs']:\n pattern = re.compile(r\"^Unnamed: 7$\",flags=re.IGNORECASE)\n if pattern.match(column_def['field']):\n column_def['cellRenderer'] = \"\"\"function(params) { \n let v = params.value;\n function clicked(){\n let new_cell = Jupyter.notebook.insert_cell_below().set_text(\"This feature is not implemented yet.\");\n }\n\n let b = document.createElement('button');\n b.innerHTML = v;\n b.style = \"background-color:bisque; margin:1px 10px 1px 2px;\";\n b.title = \"Open gene table\";\n b.addEventListener(\"click\", function (){clicked()}, false);\n // b.addEventListener(\"click\", function (){clicked()}, false);\n\n return b;\n} \"\"\"\n \n if title.lower() == 'references':\n for column_def in grid_options['columnDefs']:\n pattern = re.compile(r\"^Pubmed_id$\",flags=re.IGNORECASE)\n if pattern.match(column_def['field']):\n column_def['cellRenderer'] = \"\"\"function(params) { return ''+params.value+''; }\"\"\"\n \n \n g = ipyaggrid.Grid(grid_data = df,\n grid_options=grid_options,\n center=False,\n theme='ag-theme-fresh',\n grid_options_multi=[],\n columns_fit='',\n index=True,\n keep_multiindex=False,\n compress_data=True,\n quick_filter=True,\n export_csv=True,\n export_excel=True,\n show_toggle_delete=False,\n show_toggle_edit=False,\n paste_from_excel=True,\n export_mode='disabled',\n export_to_df=True,\n hide_grid=False,\n menu=None,\n ) \n \n children.append(g)\n \n elif isinstance(df, dict):\n if df == {}:\n logging.debug(\"Skipping %s\", title)\n \n g = get_grids(df)\n children.append(g) \n \n elif isinstance(df, list):\n if len(df) == 0:\n logging.debug(\"Skipping %s\", title)\n continue \n \n titles.append(title) \n \n tabs.children = children\n \n assert len(children) == len(titles)\n \n for i, title in enumerate(titles):\n tabs.set_title(i, title)\n\n return tabs\n\ndef run_stdb(locus_tag):\n clear_output(wait=True)\n\n gene_sub_pattern = re.compile(r'([a-z](?=[0-9]))')\n gene=gene_sub_pattern.sub(r'\\1_', locus_tag)\n\n stdb = StringDBScraper(query=stringdb_query(taxonId=216595, features=[gene]))\n\n stdb.connect()\n\n stdb.update_features()\n\n stdb_results = dict()\n\n stdb_results['Network Image'] = stdb.network_image()\n stdb_results['Network Interactions'] = stdb.network_interactions()\n stdb_results['Interaction Partners'] = stdb.interaction_partners(required_score=300)\n stdb_results['Functional Enrichments'] = stdb.functional_enrichments()\n stdb_results['Interaction Enrichments'] = stdb.interaction_enrichments()\n\n return stdb_results\n\ndef get_stdb_grids(stdb_results):\n \n tabs = widgets.Tab() \n children = []\n titles = []\n \n skipped = []\n \n for i, key in enumerate(stdb_results.keys()):\n if key in skipped:\n logging.debug(\"Skipping %s\", key)\n continue\n \n if key == 'Network Image':\n with open(stdb_results['Network Image'], 'rb') as fp:\n image_widget = widgets.Image(value=fp.read(), format='svg')\n\n children.append(image_widget)\n titles.append(key)\n continue\n \n df = stdb_results[key]\n \n grid_options={'columnDefs' : [{'field': c} for c in df.columns],\n 'enableSorting': True,\n 'enableFilter': True,\n 'enableColResize': True,\n 'enableRangeSelection': True,\n }\n\n grid = ipyaggrid.Grid(grid_data = df,\n grid_options=grid_options,\n center=False,\n theme='ag-theme-fresh',\n grid_options_multi=[],\n columns_fit='',\n index=False,\n keep_multiindex=False,\n compress_data=True,\n quick_filter=True,\n export_csv=True,\n export_excel=True,\n show_toggle_delete=False,\n show_toggle_edit=False,\n paste_from_excel=True,\n export_mode='disabled',\n export_to_df=True,\n hide_grid=False,\n menu=None,\n )\n children.append(grid)\n \n \n titles.append(key) \n \n tabs.children = children\n \n assert len(children) == len(titles)\n \n for i, title in enumerate(titles):\n tabs.set_title(i, title)\n \n return tabs\n\n stdb_tabs = Tabs(tabs=tabs)\n \n return stdb_tabs\n\ndef html_template(strain, locus_tag):\n \n ht = \"\"\"\n\n \n\n Feature results\n\n \n \n\n \n \n \n\n \n \n \n\n \n\n

Data from pseudomonas.com

\n\n
\n \n \n
\n\n \n

Data from strings-db

\n
\n \n \n
\n \n \n

Open Knowledge Map

\n
\n {okm}\n
\n \n\n\"\"\"\n \n return ht\n","sub_path":"GenDBScraper/Utilities/nb_utilities.py","file_name":"nb_utilities.py","file_ext":"py","file_size_in_byte":13774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"110850544","text":"#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\n\r\nimport cv2\r\nimport numpy as np\r\nimport math\r\nimport random\r\nfrom sklearn.decomposition import PCA\r\nfrom sklearn.metrics import mean_squared_error\r\nimport pickle\r\npath = 'afw/'\r\n\r\n\r\nclass Model(object):\r\n\r\n \"\"\"docstring for Model\"\"\"\r\n\r\n def __init__(self):\r\n self.R = []\r\n self.errors = []\r\n self.axes = []\r\n self.mean_face = None\r\n\r\n def computerCentreG(self, x, y):\r\n (cx, cy) = (np.mean(x), np.mean(y))\r\n return (cx, cy)\r\n\r\n def loadParams(self):\r\n Rfile = open('best.r', 'rb')\r\n axesFile = open('bestAxes.axes', 'rb')\r\n self.R = pickle.load(Rfile)\r\n self.axes = pickle.load(axesFile)\r\n\r\n def loadmeanFace(self):\r\n meanfaceFile = open('meanface.face', 'rb') \r\n self.mean_face = pickle.load(meanfaceFile)\r\n\r\n def computeY(self, X):\r\n Y = np.concatenate((np.ones((X.shape[0], 1)), X), axis=1)\r\n return Y\r\n\r\n def getOptimDepalcemnt(self, pt, pt_m):\r\n return np.array(pt) - np.array(pt_m)\r\n\r\n def optimDeplacmnts(self, pt, pt_m):\r\n for i in range(len(pt)):\r\n pt[i] = self.getOptimDepalcemnt(pt[i], pt_m)\r\n return pt\r\n\r\n def debugList(self, l):\r\n print (np.array(l).shape)\r\n\r\n def computeR(self, Y, optim):\r\n return np.linalg.inv(np.transpose(Y).dot(Y)).dot(np.transpose(Y)).dot(optim)\r\n\r\n def majPoints(self, s, sstar):\r\n\r\n return s + sstar\r\n\r\n def usePCA(self, des):\r\n pca = PCA(n_components=0.98)\r\n pca.fit(des)\r\n X = pca.transform(des)\r\n return (X, pca.components_)\r\n\r\n def forward(self, Y, R):\r\n return Y.dot(R)\r\n def oneStepAlignment(\r\n self,\r\n imgs,\r\n pt,\r\n pt_mean,\r\n ):\r\n\r\n sifts = self.computeSiftAll(imgs.copy(), pt_mean.copy())\r\n\r\n s_st = self.getOptimDepalcemnt(pt, pt_mean)\r\n (X, axes) = self.usePCA(sifts)\r\n Y = self.computeY(X)\r\n\r\n R = self.computeR(Y, s_st)\r\n s_0 = self.forward(Y, R)\r\n err = mean_squared_error(s_0, s_st)\r\n print(\"Reduction from \",sifts.shape,\" to \",X.shape)\r\n print ('MSE :', err)\r\n updated_pts = self.majPoints(pt_mean, s_0)\r\n\r\n im_true = self.draw_both_points(imgs[0].copy(), updated_pts,\r\n pt, 0)\r\n cv2.imshow('train', im_true)\r\n cv2.waitKey(1000)\r\n self.i+=1\r\n return (updated_pts, R, axes, err)\r\n\r\n def reshape2D(self, pt):\r\n f = pt.copy().reshape(pt.shape[0], 68, 2)\r\n for i in range(pt.shape[0]):\r\n f[i, :, 0] = pt[i, 0:68]\r\n f[i, :, 1] = pt[i, 68:136]\r\n return f\r\n\r\n def computeLocalSift(self, image, keypoints):\r\n sift = cv2.xfeatures2d.SIFT_create()\r\n (keypoints, descriptors) = sift.compute(image,\r\n keypoints=keypoints)\r\n im = image.copy()\r\n im = cv2.drawKeypoints(im, keypoints, im)\r\n return (im, keypoints, descriptors)\r\n\r\n def computeSiftAll(self, images, keypoints):\r\n flatSifts = []\r\n print(keypoints.shape)\r\n keypoints = self.reshape2D(keypoints.copy())\r\n for (i, img) in enumerate(images):\r\n keypoint = self.generateKeypoint(keypoints[i].reshape(1,\r\n 68, 2))\r\n (ims, _, desc) = self.computeLocalSift(img, keypoint)\r\n\r\n flatSifts.append(desc.reshape(-1))\r\n return np.array(flatSifts)\r\n\r\n def generateKeypoint(self, pt):\r\n key_points = []\r\n for i in range(0, len(pt[0])):\r\n key_points.append(cv2.KeyPoint(x=pt[0, i, 0], y=pt[0, i,\r\n 1], _size=20))\r\n return key_points\r\n\r\n def drawPoints(\r\n self,\r\n img,\r\n ptx,\r\n pty,\r\n color=None,\r\n ):\r\n img = img.copy()\r\n for j in range(len(ptx)):\r\n if color == None:\r\n img = cv2.circle(img, (int(ptx[j]), int(pty[j])), 2,\r\n (255, 255, 0), 1)\r\n else:\r\n img = cv2.circle(img, (int(ptx[j]), int(pty[j])), 2,\r\n color, 1)\r\n return img\r\n\r\n def fit(\r\n self,\r\n imgs,\r\n landmarks,\r\n mean_face,\r\n iters=5,\r\n ):\r\n self.i=0\r\n self.mean_face = mean_face.copy()\r\n\r\n for i in range(iters):\r\n\r\n (pts_new, r, axes, err) = self.oneStepAlignment(imgs,\r\n landmarks, self.mean_face)\r\n print ('Iteration ', i + 1, ' done !')\r\n self.mean_face = pts_new\r\n self.R.append(r)\r\n self.errors.append(err)\r\n self.axes.append(axes)\r\n self.mean_face=mean_face\r\n self.save_params()\r\n\r\n def getBestIndex(self):\r\n if len(self.errors) == 0:\r\n return None\r\n return self.errors.index(min(self.errors))\r\n\r\n def save_params(self):\r\n i = self.getBestIndex()\r\n assert not i == None, \\\r\n 'Assertion error with fitting : You havent fitted yet '\r\n Rfile = open('best.r', 'wb')\r\n axesFile = open('bestAxes.axes', 'wb')\r\n pickle.dump(self.R[i], Rfile)\r\n pickle.dump(self.axes[i], axesFile)\r\n def save_all(self):\r\n Rfile = open('All.r', 'wb')\r\n axesFile = open('All.axes', 'wb')\r\n pickle.dump(self.R, Rfile)\r\n pickle.dump(self.axes, axesFile)\r\n def load_all(self):\r\n Rfile = open('All.r', 'rb')\r\n axesFile = open('All.axes', 'rb')\r\n self.R=pickle.load( Rfile)\r\n self.axes=pickle.load( axesFile) \r\n def draw_both_points(\r\n self,\r\n img,\r\n keypoints_alig,\r\n keypoints_orig,\r\n index,\r\n ):\r\n keypoints = self.reshape2D(keypoints_orig)\r\n img = self.drawPoints(img.copy(), keypoints[index, :, 0],\r\n keypoints[index, :, 1],(0,255,0)) # red are detected ones\r\n temp = self.reshape2D(keypoints_alig)\r\n im_true = self.drawPoints(img, temp[index, :, 0], temp[index, :\r\n , 1], (0, 0, 255)) # green points are ground truth\r\n return im_true\r\n def test_model_compute(self,R1,A1,imgs,test_pts,index=0):\r\n\r\n\r\n X_test = self.computeSiftAll(imgs, self.mean_face.copy())\r\n X_test1 = X_test.dot(A1.T) # pca reduction\r\n Y = self.computeY(X_test1)\r\n s_test1 = self.forward(Y,R1) # deplacmnts output\r\n self.mean_face+=s_test1\r\n keypoints = self.mean_face \r\n\r\n im_true = self.draw_both_points(imgs[3].copy(), keypoints,\r\n test_pts, 3)\r\n cv2.imwrite(str(index)+'___test.png', im_true)\r\n cv2.imshow('test', im_true)\r\n cv2.waitKey(1000)\r\n return s_test1\r\n def test_model(\r\n self,\r\n imgs,\r\n X_test,\r\n pre_trained=False,\r\n ):\r\n test_pts = X_test.copy()\r\n s_test = 0\r\n if(self.mean_face.shape[0]==136):\r\n self.mean_face=np.array([self.mean_face]*X_test.shape[0])\r\n\r\n for i in range(len(self.R)):\r\n\r\n R1 = self.R[i]\r\n A1 = self.axes[i]\r\n s_star = test_pts - self.mean_face\r\n s_test1=self.test_model_compute(R1,A1,imgs,test_pts,i)\r\n s_test += s_test1\r\n print ('Iteration ', str(i + 1))\r\n print(mean_squared_error(s_test1,s_star))\r\n if pre_trained:\r\n break\r\n","sub_path":"Modele.py","file_name":"Modele.py","file_ext":"py","file_size_in_byte":7455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"475169649","text":"\"\"\"\nReads in data from file containing positions of point masses.\nThe function then calculates the net gravitational force acting \non an additional point mass as an argument to the function.\n\nCreated on Tue Oct 24 20:19:40 2017\n\n@author: chancehaycock\n\"\"\"\nimport math\nimport numpy as np\n\ndef force(filename, obj):\n '''Question 3 Force function'''\n # Defining gravitational constant\n Grav = 6.67 * math.pow(10, -11)\n # Opening file and splitting into relevant lists/arrays\n data = np.genfromtxt(filename, delimiter=',')\n xCoord = data[:, 0]\n yCoord = data[:, 1]\n zCoord = data[:, 2]\n mass = data[:, 3]\n # Setting initial confidtions for 'for loop'\n forcex = 0.0\n forcey = 0.0\n forcez = 0.0\n for i in range(len(xCoord)):\n # Computing distances between obj and file, in correct direction\n xDist = xCoord[i] - obj[0]\n yDist = yCoord[i] - obj[1]\n zDist = zCoord[i] - obj[2]\n # Computing value of 'r' in Gravitational Law equation\n dist = math.sqrt(xDist**2 + yDist**2 + zDist**2)\n forcex += (Grav * obj[3] * mass[i] * xDist) / math.pow(dist, 3)\n forcey += (Grav * obj[3] * mass[i] * yDist) / math.pow(dist, 3)\n forcez += (Grav * obj[3] * mass[i] * zDist) / math.pow(dist, 3)\n # Returning numpy array with Fx , Fy and Fz components\n A = np.array([forcex, forcey, forcez])\n return A\n","sub_path":"Python/q3u1618692.py","file_name":"q3u1618692.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"140103169","text":"'''\n Created on May 31, 2018\n\n @author: Varela\n\n refs:\n https://danijar.com/structuring-your-tensorflow-models/\n'''\nimport functools\nimport tensorflow as tf\nimport sys, os\nsys.path.insert(0, os.getcwd())\n# sys.path.insert(0, os.path.abspath('datasets'))\n\n\nimport config\nfrom datasets import input_fn, get_valid, get_train\nfrom evaluator_conll import EvaluatorConll\nfrom propbank_encoder import PropbankEncoder\nfrom models.utils import get_index, get_dims\nimport numpy as np\nimport yaml\n\nINPUT_DIR = 'datasets/binaries/'\nDATASET_TRAIN_GLO50_PATH = '{:}dbtrain_glo50.tfrecords'.format(INPUT_DIR)\nDATASET_VALID_GLO50_PATH = '{:}dbvalid_glo50.tfrecords'.format(INPUT_DIR)\nDATASET_TRAIN_WAN50_PATH = '{:}dbtrain_wan50.tfrecords'.format(INPUT_DIR)\nDATASET_VALID_WAN50_PATH = '{:}dbvalid_wan50.tfrecords'.format(INPUT_DIR)\nPROPBANK_GLO50_PATH = '{:}deep_glo50.pickle'.format(INPUT_DIR)\nPROPBANK_WAN50_PATH = '{:}deep_wan50.pickle'.format(INPUT_DIR)\n\n\ndef lazy_property(function):\n '''Evaluates the function once creating a method\n\n It stores the result in a member named after the decorated function \n (prepended with a prefix) and returns this value on any subsequent calls. \n\n refs:\n https://danijar.com/structuring-your-tensorflow-models/\n\n Decorators:\n functools.wraps\n\n Arguments:\n function {[type]} -- [description]\n\n Returns:\n [type] -- [description]\n '''\n\n attribute = '_cache_' + function.__name__\n\n @property\n @functools.wraps(function)\n def decorator(self):\n if not hasattr(self, attribute):\n setattr(self, attribute, function(self))\n return getattr(self, attribute)\n\n return decorator\n\n\ndef get_unit(sz):\n return tf.nn.rnn_cell.BasicLSTMCell(sz, forget_bias=1.0, state_is_tuple=True)\n\n\nclass DBLSTM(object):\n '''Estimates a deep learning model according to Zhou and Xu, 2016\n\n Build a computation graph in tensorflow\n Updates internal graph parameters at each optimize call\n Evaluates errors\n\n '''\n\n def __init__(self, X, T, seqlens, learning_rate=5 * 1e-3, hidden_size=[32, 32], target_size=60):\n '''Sets the computation graph parameters\n\n Responsable for building computation graph\n\n refs:\n https://www.tensorflow.org/programmers_guide/graphs\n\n Arguments:\n X {object} -- A 3D float tensor in which the dimensions are\n * batch_size -- fixed sample size from examples\n * max_time -- maximum time from batch_size examples (default: None)\n * features -- features dimension\n\n T {object} -- A 3D float tensor in which the dimensions are\n * batch_size -- fixed sample size from examples\n * max_time -- maximum time from batch_size examples (default: None)\n * features -- features dimension\n\n seqlens {list} -- a python list of integers carrying the sizes of \n each proposition\n\n\n Keyword Arguments:\n learning_rate {float} -- Parameter to be used during optimization (default: {5 * 1e-3})\n hidden_size {list} -- Parameter holding the layer sizes (default: {`[32, 32]`})\n target_size {int} -- Parameter holding the layer sizes (default: {60})\n '''\n self.X = X\n self.T = T\n self.seqlens = seqlens\n\n self.learning_rate = learning_rate\n self.hidden_size = hidden_size\n self.target_size = target_size\n\n self.propagation\n self.cost\n self.optimize\n self.prediction\n self.error\n\n @lazy_property\n def propagation(self):\n '''Forward propagates the inputs X thru interlaced bilstms network\n\n The inputs X are evaluated by each hidden layer (forward propagating)\n resulting in scores to be consumed by prediction layer\n \n\n Decorators:\n lazy_property\n\n Returns:\n score {tf.Variable} -- a 3D float tensor in which\n * batch_size -- fixed sample size from examples\n * max_time -- maximum time from batch_size examples (default: None)\n * target_size -- ouputs dimension\n '''\n with tf.variable_scope('fw{:}'.format(id(self))):\n self.cell_fw = get_unit(self.hidden_size[0])\n\n outputs_fw, states = tf.nn.dynamic_rnn(\n cell=self.cell_fw,\n inputs=self.X,\n sequence_length=self.seqlens,\n dtype=tf.float32,\n time_major=False\n )\n\n with tf.variable_scope('bw{:}'.format(id(self))):\n self.cell_bw = get_unit(self.hidden_size[0])\n\n inputs_bw = tf.reverse_sequence(\n outputs_fw,\n self.seqlens,\n batch_axis=0,\n seq_axis=1\n )\n\n outputs_bw, states = tf.nn.dynamic_rnn(\n cell=self.cell_bw,\n inputs=inputs_bw,\n sequence_length=self.seqlens,\n dtype=tf.float32,\n time_major=False\n )\n outputs_bw = tf.reverse_sequence(\n outputs_bw,\n self.seqlens,\n batch_axis=0,\n seq_axis=1\n )\n\n h = outputs_bw\n h_1 = outputs_fw\n for i, sz in enumerate(self.hidden_size[1:]):\n n = id(self) + i + 1\n with tf.variable_scope('fw{:}'.format(n)):\n inputs_fw = tf.concat((h, h_1), axis=2)\n self.cell_fw = get_unit(sz)\n\n outputs_fw, states = tf.nn.dynamic_rnn(\n cell=self.cell_fw,\n inputs=inputs_fw,\n sequence_length=self.seqlens,\n dtype=tf.float32,\n time_major=False)\n\n with tf.variable_scope('bw{:}'.format(n)):\n inputs_bw = tf.concat((outputs_fw, h), axis=2)\n inputs_bw = tf.reverse_sequence(\n inputs_bw,\n self.seqlens,\n batch_axis=0,\n seq_axis=1\n )\n self.cell_bw = get_unit(sz)\n\n outputs_bw, states = tf.nn.dynamic_rnn(\n cell=self.cell_bw,\n inputs=inputs_bw,\n sequence_length=self.seqlens,\n dtype=tf.float32,\n time_major=False)\n\n outputs_bw = tf.reverse_sequence(\n outputs_bw,\n self.seqlens,\n batch_axis=0,\n seq_axis=1\n )\n\n h = outputs_bw\n h_1 = outputs_fw\n\n with tf.variable_scope('score'):\n Wo_shape = (2 * self.hidden_size[-1], self.target_size)\n bo_shape = (self.target_size,)\n\n Wo = tf.Variable(tf.random_normal(Wo_shape, name='Wo'))\n bo = tf.Variable(tf.random_normal(bo_shape, name='bo'))\n\n outputs = tf.concat((h, h_1), axis=2)\n\n # Stacking is cleaner and faster - but it's hard to use for multiple pipelines\n score = tf.scan(\n lambda a, x: tf.matmul(x, Wo),\n outputs, initializer=tf.matmul(outputs[0], Wo)) + bo\n return score\n\n\n @lazy_property\n def optimize(self):\n '''Optimize\n\n [description]\n\n Decorators:\n lazy_property\n\n Returns:\n [type] -- [description]\n '''\n with tf.variable_scope('optimize'):\n optimum = tf.train.AdamOptimizer(learning_rate=self.learning_rate).minimize(self.cost)\n return optimum\n\n @lazy_property\n def cost(self):\n '''Computes the viterbi_score after the propagation step, returns the cost.\n\n Consumes the representation coming from propagation layer, evaluates \n the log_likelihod and parameters\n\n Decorators:\n lazy_property\n\n Returns:\n cost {tf.float64} -- A scalar holding the average log_likelihood \n of the loss by estimatiof\n '''\n with tf.variable_scope('cost'):\n Tflat = tf.cast(tf.argmax(self.T, 2), tf.int32)\n log_likelihood, self.transition_params = tf.contrib.crf.crf_log_likelihood(self.propagation, Tflat, self.seqlens)\n\n return tf.reduce_mean(-log_likelihood)\n\n @lazy_property\n def prediction(self):\n '''Decodes the viterbi score for the inputs\n \n Consumes both results from propagation and and cost layers\n \n Decorators:\n lazy_property\n \n Returns:\n [type] -- [description]\n '''\n with tf.variable_scope('prediction'):\n # Compute the viterbi sequence and score.\n viterbi_sequence, viterbi_score = tf.contrib.crf.crf_decode(self.propagation, self.transition_params, self.seqlens)\n\n return tf.cast(viterbi_sequence, tf.int32)\n\n @lazy_property\n def error(self):\n '''Computes the prediction errors\n\n Compares target tags to predicted tags\n\n Decorators:\n lazy_property\n \n Returns:\n error {float} -- percentage of wrong tokens\n '''\n mistakes = tf.not_equal(self.prediction, tf.cast(tf.argmax(self.T, 2), tf.int32))\n mistakes = tf.cast(mistakes, tf.float32)\n mask = tf.sign(tf.reduce_max(tf.abs(self.T), reduction_indices=2))\n mask = tf.cast(mask, tf.float32)\n mistakes *= mask\n\n # Average over actual sequence lengths.\n mistakes = tf.reduce_sum(mistakes, reduction_indices=1)\n mistakes /= tf.cast(self.seqlens, tf.float32)\n return tf.reduce_mean(mistakes)\n\n\n\ndef main():\n '''Showcases an usage for DBLSTM\n\n Shows usage for DBLSTM\n '''\n embeddings = 'glo50'\n propbank_encoder = PropbankEncoder.recover(PROPBANK_GLO50_PATH)\n dims_dict = propbank_encoder.columns_dimensions('EMB')\n datasets_list = [DATASET_TRAIN_GLO50_PATH]\n input_list = ['ID', 'FORM', 'LEMMA', 'MARKER', 'GPOS',\n 'FORM_CTX_P-1', 'FORM_CTX_P+0', 'FORM_CTX_P+1',\n 'GPOS_CTX_P-1', 'GPOS_CTX_P+0', 'GPOS_CTX_P+1']\n TARGET = 'T'\n columns_list = input_list + [TARGET]\n\n X_train, T_train, L_train, I_train = get_train(input_list, TARGET, embeddings)\n X_valid, T_valid, L_valid, I_valid = get_valid(input_list, TARGET, embeddings)\n\n FEATURE_SIZE = get_dims(input_list, dims_dict)\n\n BATCH_SIZE = 250\n NUM_EPOCHS = 1000\n HIDDEN_SIZE = [16] * 4\n lr = 1 * 1e-3\n TARGET_SIZE = dims_dict[TARGET]\n print(BATCH_SIZE, TARGET, TARGET_SIZE, FEATURE_SIZE)\n\n evaluator = EvaluatorConll(propbank_encoder.db, propbank_encoder.idx2lex)\n params = {\n 'learning_rate': lr,\n 'hidden_size': HIDDEN_SIZE,\n 'target_size': TARGET_SIZE\n }\n\n def train_eval(Y):\n index = I_train[:, :, 0].astype(np.int32)\n evaluator.evaluate_tensor('train', index, Y, L_train, TARGET, params)\n\n return evaluator.f1\n\n def valid_eval(Y):\n index = I_valid[:, :, 0].astype(np.int32)\n evaluator.evaluate_tensor('valid', index, Y, L_valid, TARGET, params)\n\n return evaluator.f1\n\n # BUILDING the execution graph\n X_shape = (None, None, FEATURE_SIZE)\n T_shape = (None, None, TARGET_SIZE)\n X = tf.placeholder(tf.float32, shape=X_shape, name='X')\n T = tf.placeholder(tf.float32, shape=T_shape, name='T')\n seqlens = tf.placeholder(tf.int32, shape=(None,), name='seqlens')\n\n with tf.name_scope('pipeline'):\n inputs, targets, sequence_length, descriptors = input_fn(\n datasets_list, BATCH_SIZE, NUM_EPOCHS,\n input_list, TARGET, shuffle=True)\n\n dblstm = DBLSTM(X, T, seqlens, **params)\n\n init_op = tf.group(\n tf.global_variables_initializer(),\n tf.local_variables_initializer()\n )\n\n with tf.Session() as session:\n session.run(init_op)\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(coord=coord)\n # Training control variables\n step = 1\n total_loss = 0.0\n total_error = 0.0\n best_validation_rate = -1\n\n try:\n while not coord.should_stop():\n X_batch, T_batch, L_batch, I_batch = session.run([inputs, targets, sequence_length, descriptors])\n\n loss, _, Yish, error = session.run(\n [dblstm.cost, dblstm.optimize, dblstm.prediction, dblstm.error],\n feed_dict={X: X_batch, T: T_batch, seqlens: L_batch}\n )\n\n total_loss += loss\n total_error += error\n if (step) % 25 == 0:\n\n Y_train = session.run(\n dblstm.prediction,\n feed_dict={X: X_train, T: T_train, seqlens: L_train}\n )\n f1_train = train_eval(Y_train)\n\n Y_valid = session.run(\n dblstm.prediction,\n feed_dict={X: X_valid, T: T_valid, seqlens: L_valid}\n )\n f1_valid = valid_eval(Y_valid)\n\n if f1_valid is not None and f1_train is not None:\n print('Iter={:5d}'.format(step),\n '\\tavg. cost {:.6f}'.format(total_loss / 25),\n '\\tavg. error {:.6f}'.format(total_error / 25),\n '\\tf1-train {:.6f}'.format(f1_train),\n '\\tf1-valid {:.6f}'.format(f1_valid))\n else:\n print('Iter={:5d}'.format(step),\n '\\tavg. cost {:.6f}'.format(total_loss / 25),\n '\\tavg. error {:.6f}'.format(total_error / 25))\n total_loss = 0.0\n total_error = 0.0\n\n if f1_valid and best_validation_rate < f1_valid:\n best_validation_rate = f1_valid\n\n step += 1\n\n\n except tf.errors.OutOfRangeError:\n print('Done training -- epoch limit reached')\n\n finally:\n # When done, ask threads to stop\n coord.request_stop()\n coord.join(threads)\n\nif __name__ == '__main__':\n main()\n","sub_path":"models/dblstm.py","file_name":"dblstm.py","file_ext":"py","file_size_in_byte":14392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"568032806","text":"#!/usr/bin/env python3\nimport ee\nee.Initialize()\n\nimport os\nimport sys\nimport configparser\nimport pandas\nfrom src.gee_funs import reduce_HUCS, embed_date\n\n\n\n# Check if covariate assets exist in GEE\ndef covariates_exist(years, assetId):\n command = 'earthengine ls ' + assetId\n result = os.popen(command).read().split('\\n')\n assets = list(map(lambda path: path.split('/')[-1], result))\n expected_assets = list(map(lambda year: 'covariates' + str(year), years))\n\n all_accounted_for = True\n for item in expected_assets:\n if item not in assets:\n print(\"Expected asset \" + item + \" not found.\")\n all_accounted_for = False\n else:\n print(item, \" found\")\n\n if all_accounted_for:\n print(\"All required covariates found.\")\n else:\n print(\"Required covariate data missing. Please locate requred covariates and try again.\")\n sys.exit(1)\n \n\ndef main():\n config = configparser.ConfigParser()\n config.read('aisconfig.ini')\n\n state_abbrev = config[\"WHENWHERE\"][\"STATE_ABBREVIATION\"]\n start_year = int(config['WHENWHERE']['START_YEAR'])\n end_year = int(config['WHENWHERE']['END_YEAR'])\n covariate_folder = config[\"GEEPATHS\"][\"ASSETID\"]\n thinned_asset_path = config[\"GEEPATHS\"][\"AIS_THINNED_POINT_PATH\"]\n trainingdata = config[\"LOCALPATHS\"][\"TRAINING_DATA\"]\n\n HUC_clip = ee.FeatureCollection(\"USGS/WBD/2017/HUC12\").filter(ee.Filter.eq('states',state_abbrev))\n years = range(start_year, end_year)\n points_file = ee.FeatureCollection(thinned_asset_path).map(embed_date)\n\n covariates_exist(years, covariate_folder)\n\n images = list(map(lambda x: ee.Image(covariate_folder + \"covariates\" + str(x)), years))\n\n if not os.path.exists(trainingdata):\n print(\"WARNING: TRAINING_DATA variable in aisconfig.ini is set to a directory that does not exist.\")\n print(\" Please either create the direcory or specify a valid path in aisconfig.ini.\")\n print(\" Exiting\") \n sys.exit(1)\n\n for i in range(len(years)):\n current_year = start_year + i\n \n print(\"Starting \", current_year)\n \n data = reduce_HUCS(images[i], points_file, HUC_clip)\n\n my_csv = pandas.DataFrame([x['properties'] for x in data.getInfo()['features']])\n\n if my_csv.empty:\n print(\"WARNING: \" + thinned_asset_path + \" contains no data points for \" + str(current_year))\n print(\"No .csv created\")\n else:\n my_csv.to_csv((trainingdata) + str(current_year) + '.csv', index=False)\n print(\"Finished\", current_year)\n\n print(\"All files exported to \" + trainingdata)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"training_data.py","file_name":"training_data.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"180044734","text":"import logging\nimport glob\nimport os\nimport hashlib\nimport time\nimport re\n\nLOGGER = logging.getLogger(__name__)\n\nclass Test_TUXT_104:\n \"\"\"\n TUXT-104\n\n Test:\n Eine alte FW Version kann aufgespielt werden und der Vorgang wird im Systemlog protokolliert.\n Input:\n fw_bin_source - Ort an dem die FW-Binary abgelegt ist. Die FW-Binary muss an dem Ort in einem Unterordner liegt, der die Version als Namen trägt\n fw_bin_version - Version der FW-Binary\n path_fw_bin_destination - Ort an den die FW-Binary auf dem Gerät abgelegt wird\n fw_bin_rename - Dateiname, wie die FW-Binary auf dem Gerät umbenannt werden soll\n path_update - Pfad zum starten des Update Prozesses\n Preconditions:\n Man ist über eine serielle Konsole oder per SSH mit dem Gerät verbunden und als Benutzer “root” eingeloggt (ggf. erst als User “ivu” einloggen und dann mit “sudo -i” root werden). \n \"\"\"\n date = \"\"\n\n def test_tuxt_104_0(self, configuration, ssh_command, scp):\n \"\"\"\n Firmware-Datei nach /lib/firmware/ivu/ivumcu.bin auf das Gerät kopieren, beispielsweise mit Hilfe von WinSCP.\n Die Firmware-Datei kann unter \\\\\\\\ivu-ag.com\\\\storage\\\\FTP\\\\FTP_ivu.ticketbox-xl\\\\software_firmware_hardware\\\\04_MCU\\\\fw\\\\6.6.7\\\\file_6_6_6.bin abgerufen werden (muss in ivumcu.bin umbenannt werden)\n \"\"\"\n fw_bin_file = glob.glob(f\"{configuration['fw_bin_source']}/{configuration['fw_bin_version']}/*.bin\")\n assert len(fw_bin_file) == 1, \"FW binary file not found\"\n src = os.path.realpath(fw_bin_file[0])\n dst = f\"{configuration['path_fw_bin_destination']}/{configuration['fw_bin_rename']}\"\n LOGGER.info(f\"SCP put: {src} > {dst}\")\n scp.put(src, dst)\n\n output, error = ssh_command(f\"sha256sum {configuration['path_fw_bin_destination']}/{configuration['fw_bin_rename']}\")\n \n if error.strip() != \"\":\n LOGGER.error(f\"{error.strip()}\")\n\n assert len(output) >= 64, \"The output should be at least 64 characters long\"\n \n with open(src, \"rb\") as f:\n bytes = f.read()\n src_checksum = hashlib.sha256(bytes).hexdigest()\n\n assert len(src_checksum) == 64, \"The calculated checksum has to be 64 characters long\"\n\n assert output[0:64] == src_checksum, \"It is to be assumed that the file was modified or damaged during transfer\"\n\n def test_tuxt_104_1(self, configuration, ping, ping_until, ping_timeout, ssh_command):\n \"\"\"\n Sicherstellen, dass der Akku eingesteckt und geladen ist. Dann wird der Updatevorgang initiiert\n \"\"\"\n rhost_is_up = ping(configuration['rhost'], configuration['ssh_port'])\n assert rhost_is_up, \"The system is offline\"\n\n try:\n output, error = ssh_command(f\"cat {configuration['battery_status']}\")\n\n if error.strip() != \"\":\n LOGGER.error(f\"{error.strip()}\")\n\n if output.strip() == \"1\":\n LOGGER.info(\"Battery connected\")\n else:\n LOGGER.warn(\"Battery disconnected\")\n except:\n LOGGER.warn(\"Battery status unknown\")\n\n try:\n output, _ = ssh_command(\"date +\\\"%F %T\\\"\")\n Test_TUXT_104.date = output.strip()\n except:\n LOGGER.warn(\"current timestamp unknown\")\n\n output, error = ssh_command(f\"echo 1 > {configuration['path_update']}\")\n\n if error.strip() != \"\":\n assert error.strip() == \"\", \"The update could not be started for some reason\"\n\n if output.strip() != \"\":\n LOGGER.error(f\"{output.strip()}\")\n\n rhost_is_up = ping_timeout(configuration['rhost'], configuration['ssh_port'])\n assert rhost_is_up, \"The system restart for the update process failed or was delayed. The host is still up\"\n\n rhost_is_up = ping_until(configuration['rhost'], configuration['ssh_port'])\n assert rhost_is_up, \"The system should be available again by now, but it is not. The host is still down\"\n\n def test_tuxt_104_2(self, configuration, ssh_command):\n \"\"\"\n System-Protokoll überprüfen ob MCU Update erfolgreich war\n \"\"\"\n if Test_TUXT_104.date == \"\":\n LOGGER.warn(\"Kein Datum gespeichert beim FW-Update. Überprüft werden nur die letzten 5 Minuten.\")\n Test_TUXT_104.date = \"5 minutes ago\"\n\n output, error = ssh_command(f\"journalctl -t kernel -r --since=\\\"{Test_TUXT_104.date}\\\" | grep -B 1 \\\"Updating MCU firmware\\\"\")\n\n if error.strip() != \"\":\n LOGGER.error(f\"{error.strip()}\")\n\n match = re.match(r\"^(.*)(\\r\\n|\\r|\\n).*(\\d{2}:\\d{2}:\\d{2}) .* Updating MCU firmware: (.*)/(.*), size: (\\d*), blocks: (\\d*)\", output)\n\n assert match, \"There was no update entry in the system logs recently\"\n\n assert match[1] == \"-- Reboot --\", \"There was no reboot after the update was initiialized. Update not started.\"\n\n LOGGER.info(f\"Update durchgeführt um {match[3]}\")\n\n if match[5] != f\"{configuration['fw_bin_rename']}\":\n LOGGER.warn(f\"Update log entry FW-Binary filename {match[5]} does not match {configuration['fw_bin_rename']}\")\n","sub_path":"data/tests/test_mcu/test_fw_update/test_tuxt_104.py","file_name":"test_tuxt_104.py","file_ext":"py","file_size_in_byte":5252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"263272924","text":"# @Date : 2017-04-30 20:02:24\n# @Author : Jihun Yang (zhuny@kaist.ac.kr)\n# @File : parent.py\n\n\ndef get_ints():\n return list(map(int, input().split()))\n\n\ndef cycle(L):\n if len(L) > 1:\n bef = L[-1]\n for i in L:\n yield bef, i\n bef = i\n\n\ndef can_merge(st, en, li):\n if st < en:\n for ost, oen in li:\n if st < ost and oen < en:\n return False\n return True\n\n else:\n return can_merge(st-1440, en, li) and can_merge(st, en+1440, li)\n\n\ndef mergable(L1, L2):\n L1.sort()\n\n L1_total = sum([e[1]-e[0] for e in L1])\n remaind = 60*12 - L1_total\n\n term = [((aft[0]-bef[1])%1440, bef[1], aft[0]) for bef, aft in cycle(L1)]\n term.sort()\n count = 0\n\n for t, st, en in term:\n if remaind >= t:\n if can_merge(st, en, L2):\n remaind -= t\n count += 1\n else:\n break\n\n return count\n\n\n\n\ndef do_cal():\n A_c, A_j = get_ints()\n\n ac_list = [get_ints() for i in range(A_c)]\n aj_list = [get_ints() for i in range(A_j)]\n\n A_c -= mergable(ac_list, aj_list)\n A_j -= mergable(aj_list, ac_list)\n\n print (max(A_c,A_j)*2)\n\n\n\ndef main():\n n = int(input())\n\n for i in range(n):\n print (\"Case #%d: \"%(i+1), end=\"\")\n do_cal()\n\n\n\n\n\nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"solution/S/SH/ParentingPartnering/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"554524724","text":"# -*- coding: utf-8 -*-\nfrom setuptools import setup, find_packages\n\ntry:\n long_description = open(\"README.rst\").read()\nexcept IOError:\n long_description = \"\"\n\nrequires = ['requests', 'request', 'paramiko', 'lettuce']\n\nsetup(\n name=\"wp-site-updater\",\n version=\"0.1.2\",\n packages=find_packages(),\n entry_points={\n 'console_scripts': [\n 'wp-site-updater=wp_site_updater:main',\n ]\n },\n py_modules=['wp_version_checker'],\n author=\"KaptKaos\",\n author_email=\"kaptkaos@gmail.com\",\n description=\"Wordpress version checker and updater\",\n license=\"GPL\",\n keywords=\"wordpress\",\n url=\"https://github.com/ctxphc/wp-site-updater\",\n long_description=long_description,\n install_requires=requires,\n classifiers=[\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 2\",\n \"Programming Language :: Python :: 2.7\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.4\",\n \"License :: OSI Approved :: GNU General Public License v3 (GPLv3)\",\n \"Development Status :: 2 - Development/Unstable\",\n \"Topic :: Internet :: WWW/HTTP :: Site Management\",\n \"Topic :: System :: Systems Administration\",\n \"Topic :: Utilities\",\n ]\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"522847165","text":"import numpy as np\r\nimport cv2\r\n\r\n# events = [i for i in dir(cv2) if 'EVENT' in i]\r\n# print(events)\r\ndef call_back(event, x, y, flags, params):\r\n if event == cv2.EVENT_LBUTTONDOWN:\r\n cv2.circle(img, (x,y), 3, (255,23,33), -1)\r\n points.append((x, y))\r\n if len(points) >= 2:\r\n cv2.line(img, points[-1], points[-2], (255,255,255), 1)\r\n cv2.imshow('image', img)\r\n\r\n\r\n\r\nimg = np.zeros((512,512,3), np.uint8)\r\ncv2.imshow('image', img)\r\npoints = []\r\ncv2.setMouseCallback('image', call_back)\r\n\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()","sub_path":"part6.py","file_name":"part6.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"389462414","text":"import socket\nimport select\nfrom zevel import *\n\n\nPOINTS = 1\nCOLOR = 2\nSHAPE_TYPE = 0\n\nLAST_PART = -1\nBUFFER_SIZE = 1024\nMSG_TYPE = 0\n\n\n\n\n\nclass Network:\n \"\"\"\n Network class\n Handles server communication\n \"\"\"\n\n def __init__(self,parent, host, port, username, group):\n \"\"\"\n Initializes a network instance\n :param parent: A gui to communicate with\n :param host: The server to connect to\n :param port: Port of communication\n :param username: Username in server\n :param group: Group in server\n :return:\n \"\"\"\n self.events = {JOIN_EVT : [], LEAVE_EVT : [], \\\n SHAPE_EVT : [], USERS_EVT : [], ERROR_EVT : []}\n self.user_name = username\n self.connected = False\n self.group = group\n self.host = host\n self.port = port\n self.buffer = b''\n self.parent = parent\n self.socket = socket.socket()\n\n\n def get_group(self):\n \"\"\"\n returns the group the connection is communicating with\n :return: group name\n \"\"\"\n return self.group\n\n\n def get_user_name(self):\n \"\"\"\n return the username we're communicating as\n :return: user name\n \"\"\"\n return self.user_name\n\n\n def listen(self):\n \"\"\"\n The network main \"loop\", creates a connection if there's none\n Otherwise checks for new messages and handles them.\n :return:\n \"\"\"\n if self.connected:\n msg = \"\"\n r, w, x = select.select([self.socket], [], [], 0.01)\n for sock in r:\n if sock == self.socket:\n msg = self.socket.recv(BUFFER_SIZE)\n if len(msg) > 0:\n data = self.buffer + msg\n num_complete_msgs = data.count(MSGS_DELIMETER)\n parsed = data.split(MSGS_DELIMETER)\n if num_complete_msgs < len(parsed):\n self.buffer = parsed[LAST_PART]\n if (len(parsed) > 0):\n parsed.pop()\n\n if len(parsed) > 0 and num_complete_msgs > 0:\n self.__manage_msgs__(parsed)\n\n else:\n self.socket.connect((self.host, self.port))\n self.connected = True\n self.join_msg()\n self.parent.after(5, self.listen)\n\n\n\n\n def get_event(self,event_type):\n \"\"\"\n Get the first event\n from the list of this event's category\n :param event_type: Type of event to return\n :return: The first event from the type's list.\n \"\"\"\n return self.events[event_type].pop(FIRST_EVENT)\n\n def join_msg(self):\n \"\"\"\n Send a join message to the server\n :return:\n \"\"\"\n msg = JOIN_MSG + MSG_PARTS + self.user_name + MSG_PARTS + self.group + END_MSG\n msg = bytes(msg, ENCODING)\n self.socket.sendall(msg)\n\n\n def shape_msg(self, shape):\n \"\"\"\n Send a shape message to the server\n :param shape:\n :return:\n \"\"\"\n msg = SHAPE_MSG + MSG_PARTS + shape[SHAPE_TYPE] + \\\n MSG_PARTS + self.text_points(shape[POINTS]) + MSG_PARTS + shape[COLOR] + END_MSG\n\n msg = bytes(msg, ENCODING)\n self.socket.sendall(msg)\n\n\n def text_points(self, points):\n \"\"\"\n Converts tuple coordinates to string\n :param points: list of coordinates as tuples\n :return: string representation of coordinates a-la protocol\n \"\"\"\n word = ''\n for coords in points:\n word += str(coords[0]) + ',' + str(coords[1]) + ','\n word = word[:-1]\n return word\n\n def leave_msg(self):\n \"\"\"\n Send a leave message to the server\n :return:\n \"\"\"\n msg = bytes(LEAVE_MSG + END_MSG, ENCODING)\n self.socket.sendall(msg)\n\n def get_user_list(self):\n \"\"\"\n Get the list of users in group\n when you joined.\n :return: A list of pre-existing users\n \"\"\"\n lst = []\n for item in self.events[USERS_EVT]:\n lst = item\n lst.remove(self.user_name)\n return lst\n\n def __manage_msgs__(self,msg_lst):\n \"\"\"\n Manages and saves received messages\n :param msg_lst: list of messages received\n :return:\n \"\"\"\n for msg in msg_lst:\n message = msg.decode(ENCODING)\n message = message.split(MSG_PARTS)\n event = message[MSG_TYPE]\n\n if event != SHAPE_EVT:\n message.pop(MSG_TYPE)\n\n if event == USERS_MSG:\n message = message.pop().split(USER_DELI)\n event = EVENT_L + event + EVENT_R\n\n if event in self.events.keys():\n self.events[event].append(message)\n self.parent.event_generate(event, when=EVT_POS)\n\n def change_parent(self, par):\n \"\"\"\n Change networks gui\n :param par: new gui\n :return:\n \"\"\"\n self.parent = par\n\n def close_con(self):\n \"\"\"\n End connection with server\n :return:\n \"\"\"\n self.socket.close()\n","sub_path":"network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":5156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"215531383","text":"import platform\nimport pytest\nfrom selenium import webdriver\n\n\n@pytest.fixture()\ndef browser():\n\n if 'Win' in platform.platform():\n browser = webdriver.Chrome(\"../resources/chromedriver_83.exe\")\n elif 'Mac' in platform.platform():\n browser = webdriver.Chrome(\"../resources/chromedriver_mac_83.exe\")\n elif \"Linux\" in platform.platform():\n browser = webdriver.Chrome(\"../resources/chromedriver_linux_83\")\n else:\n raise Exception(\"chromedriver is not configured for your Operation System! \"\n \"Your Operating System is: {}\".format(platform.platform()))\n\n # wait 10 seconds to pull the DOM\n browser.implicitly_wait(10)\n # maximize browser window to full screen\n browser.maximize_window()\n yield browser\n # when test is done, close ALL windows of the browser\n browser.quit()","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"204378332","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('diary', '0003_remove_users_avatar'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Avatar',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('avatar', models.ImageField(upload_to=b'')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.RemoveField(\n model_name='userprofile',\n name='user',\n ),\n migrations.DeleteModel(\n name='UserProfile',\n ),\n migrations.AddField(\n model_name='users',\n name='avatar',\n field=models.ImageField(default=b'media/image_upload/user/no-img.jpg', upload_to=b'media/image_upload/user'),\n preserve_default=True,\n ),\n ]\n","sub_path":"todolist/diary/migrations/0004_auto_20150202_0230.py","file_name":"0004_auto_20150202_0230.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"193509624","text":"from flask import Flask, url_for, request, redirect, render_template, jsonify\nfrom flask_pymongo import PyMongo, ObjectId, DESCENDING\nfrom dateutil.parser import parse\nfrom datetime import datetime\nimport os\n\nfrom create_pdf import _create_pdf\n\napp = Flask(__name__, static_folder=\"./frontend/dist\", static_url_path=\"\", template_folder=\"./frontend/dist\")\n\n# mongoDBとのコネクションを作成.herokuの環境では環境変数を参考にする.\napp.config[\"MONGO_URI\"] = os.getenv(\"MONGODB_URI\", \"mongodb://localhost:27017/testdb\")\nmongo = PyMongo(app)\n\n\n@app.route(\"/\")\ndef index():\n '''\n vueにて作成したindex.htmlを表示する.\n '''\n return render_template(\"index.html\")\n\n@app.route('/api/')\ndef hello_world():\n return '''\n

Hello World!!

\n '''\n\n\n@app.route('/api/all', methods=['GET'])\ndef show_entry():\n '''\n mongoDBに登録されているuser(PDFについての情報)の一覧を習得する.\n '''\n users = mongo.db.user.find()\n entries = []\n for row in users:\n entries.append({\n \"_id\": str(row['_id']),\n \"name\": row['name'],\n \"start_date\": row['start_date'].strftime(\"%Y/%m/%d\"),\n \"create_date\": row['create_date'].strftime(\"%Y/%m/%d\"),\n \"week_journal\": row['week_journal'],\n \"journal\": row['journal']\n })\n return jsonify( entlies=entries )\n\n\n@app.route('/api/recent', methods=['GET'])\ndef show_entry_latest():\n '''\n mongoDBに登録されているuser(PDFについての情報)の最新10件を習得する.\n '''\n users = mongo.db.user.find(limit=10).sort('create_date', DESCENDING)\n entries = []\n for row in users:\n entries.append({\n \"_id\": str(row['_id']),\n \"name\": row['name'],\n \"start_date\": row['start_date'].strftime(\"%Y/%m/%d\"),\n \"create_date\": row['create_date'].strftime(\"%Y/%m/%d\"),\n \"week_journal\": row['week_journal'],\n \"journal\": row['journal']\n })\n return jsonify( entlies=entries )\n\n\n@app.route('/api/add', methods=['POST'])\ndef add_entry():\n '''\n journalの情報をmongoDBに保存する.\n '''\n name = request.form['name'] if request.form['name'] != \"\" else \"John Doe\"\n start_date = parse( request.form['start_date'] ) if request.form['start_date'] != \"\" else datetime.now()\n journal = request.form['journal'] if request.form['journal'] != \"\" else \"特になし\"\n week_journal = []\n for i in range(1,8):\n tmp = request.form[f'week{i}'] if request.form[f'week{i}'] != \"\" else \"特になし\",\n week_journal += tmp\n\n mongo.db.user.insert({\n \"name\": name,\n \"start_date\": start_date,\n \"create_date\": datetime.now(),\n \"week_journal\": week_journal,\n \"journal\": journal\n })\n return redirect(url_for('index'))\n\n\n@app.route('/api/delete/', methods=['DELETE'])\ndef delete_user(id):\n '''\n 指定したIDのjournalをテーブルから削除する.\n '''\n _id = ObjectId(id)\n user = mongo.db.user.delete_one( {\"_id\" : _id} )\n return jsonify({'message': 'delete success'}), 200\n\n\n@app.route('/api/select/', methods=[\"GET\"])\ndef select_user(id):\n _id = ObjectId(id)\n user = mongo.db.user.find_one( {\"_id\" : _id} )\n return str(user)\n\n\n@app.route('/api/create/', methods=['GET'])\ndef create_pdf_from_db(id):\n _id = ObjectId(id)\n user = mongo.db.user.find_one({\"_id\" : _id})\n content = {\n \"name\": user[\"name\"],\n \"start_date\": user[\"start_date\"],\n \"create_date\": user[\"create_date\"],\n \"week_journal\": user[\"week_journal\"],\n \"journal\": user[\"journal\"]\n }\n return _create_pdf(content)\n\n@app.route('/journal')\ndef old_journal_path():\n return redirect(url_for(\"index\"))\n\n@app.route('/search', methods=['POST'])\ndef filter_entry():\n # start = parse(request.form['start'])\n # end = parse(request.form['end'])\n # cur = mongo.db.user.find({'create': {'$lt': end, '$gte': start}})\n # results = []\n # for row in cur:\n # results.append({\"name\": row['name'], \"birthday\": row['birthday'].strftime(\"%Y/%m/%d\")})\n\n return \"success!!\"\n\n\n@app.errorhandler(404)\ndef error_handler(error):\n return \"Oops!! Something wrong...\"\n\nif __name__ == '__main__':\n # app.debug = True\n # app.run()\n print(app.url_map)\n app.run(\n host=os.getenv(\"APP_ADDRESS\", 'localhost'),\n port=os.getenv(\"APP_PORT\", 3000)\n )","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":4495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"342732805","text":"# NOTE THAT, IN THIS CASE, THE ASPECT RATIO IS HARD-CODED FOR THE HEXAGONAL SHAPE\n\n\nfrom __future__ import division\nimport numpy as np\nimport re\nimport os\nimport sys\nimport shutil\nfrom matplotlib import pyplot as plt\nfrom matplotlib import animation\nimport discretisedfield as df\nfrom subprocess import Popen\n\nWriter = animation.writers['ffmpeg']\nwriter = Writer(fps=15, metadata=dict(artist='Ross Knapman'), bitrate=1800)\n\n\ndef getTime(file):\n with open(file, \"rb\") as ovffile:\n f = ovffile.read()\n lines = f.split(b\"\\n\")\n\n mdatalines = filter(lambda s: s.startswith(bytes(\"#\", \"utf-8\")), lines)\n for line in mdatalines:\n if b\"Total simulation time\" in line:\n return float(line.split()[5])\n\n\ndef createMovie(directory, initialFile, frequency):\n\n # Extract info from file name and directory\n\n # Extract z-component of magnetisation\n mzInit = df.read(initialFile).array[:, :, 0, 2]\n mzInit[mzInit==0] = np.nan # Get correct disk shape\n\n # Extract x- and y-components of magnetisation\n mxInit = df.read(initialFile).array[:, :, 0, 0]\n myInit = df.read(initialFile).array[:, :, 0, 1]\n\n\n\n # Apply filter to mx, my to make quiver plot less dense\n skipLength = 2\n filter = np.zeros_like(mxInit)\n filter[:, :] = np.nan\n filter[::skipLength, ::skipLength] = 1\n mxInit *= filter\n myInit *= filter\n\n\n # Cut out region outside of disk\n myInit[myInit == 0] = np.nan\n mxInit[mxInit == 0] = np.nan # Get correct disk shape\n\n\n filesToScan = []\n for file in os.listdir(directory):\n if file.endswith(\".ovf\"):\n filesToScan.append(file)\n\n filesToScan = sorted(filesToScan)\n\n # For scaling the colour plot\n lowestDev = 0.\n highestDev = 0.\n\n for file in filesToScan:\n if file.endswith(\".ovf\"):\n mz = df.read(directory + \"/\" + file).array[:, :, 0, 2]\n\n if np.nanmin(mz) < lowestDev:\n lowestDev = np.nanmin(mz)\n\n if np.nanmax(mz) > highestDev:\n highestDev = np.nanmax(mz)\n\n min = lowestDev\n max = highestDev\n\n # For if we want to plot absolute values, not difference with respect to initial\n # min = -1\n # max = 0.5\n\n fig, ax = plt.subplots(1)\n ax.set_yticklabels([])\n ax.set_xticklabels([])\n ax.xaxis.set_ticks_position('none')\n ax.yaxis.set_ticks_position('none')\n\n axisRepeat = 5\n\n im = ax.imshow(np.tile(mzInit, (axisRepeat, axisRepeat)), animated=True, vmin=min, vmax=max, origin=\"lower\", aspect=0.57735026919, cmap='RdBu_r')\n # quiver = ax.quiver(myInit, mxInit, scale=30)\n\n text = plt.text(1, 1, (\"%.2f\" %(0)))\n cbar = plt.colorbar(im)\n cbar.set_label(r\"$m_z (t)$\", rotation=270, labelpad=20)\n\n def getDataIterator():\n\n filesToScan = []\n for file in os.listdir(directory):\n if file.endswith(\".ovf\"):\n filesToScan.append(file)\n\n filesToScan = sorted(filesToScan)\n\n # filesToScan = filesToScan[0:frames]\n\n for file in filesToScan:\n yield directory + file\n\n\n def updateZColour(fileIn):\n print(\"z-component\", fileIn)\n time = getTime(fileIn)\n text.set_text(\"%.2f\" %(time * float(frequency) * 1e9))\n mz = df.read(fileIn).array[:, :, 0, 2]\n mz[mz==0] = np.nan\n\n im.set_array(np.tile(mz, (axisRepeat, axisRepeat)))\n\n # mx = df.read(fileIn).array[:, :, 0, 0]\n # my = df.read(fileIn).array[:, :, 0, 1]\n # mx *= filter\n # my *= filter\n # myPlot = my + xyScalingFactor * (my - myInit)\n # mxPlot = mx + xyScalingFactor * (mx - mxInit)\n # quiver.set_UVC(myPlot, mxPlot)\n\n\n # def updateZContour(fileIn):\n # ax.clear()\n # time = getTime(fileIn)\n # plt.text(1, 1, (\"%.2f\" %(time * frequency)))\n # mz = df.read(fileIn).array[:, :, 0, 2]\n # mz[mz==0] = np.nan\n # ax.contour(mz, levels=50)\n\n colourAnim = animation.FuncAnimation(fig, updateZColour, getDataIterator, interval=25, blit=False, save_count=int(1e5))\n # contourAnim = animation.FuncAnimation(fig, updateZContour, getDataIterator, interval=25, blit=False, save_count=1e5)\n plt.gca().set_aspect('equal', adjustable='box')\n\n colourAnim.save(\"Movies/NotEnhanced/\" + str(frequency) + \".mp4\")\n\n\n\nfrequencies = np.load(\"../../Psr/HexOutPeaks.npy\")\n\n# for i in range(len(frequencies)):\n# # Run simulation\n# process = Popen('./RunSim.sh %s' %str(frequencies[i]), shell=True)\n# process.wait()\n\ntry:\n for i in range(len(frequencies)):\n # Get create animation\n createMovie(str(frequencies[i]) + '.out/', '../../Psr/HexagonalLattice.out/HexagonalAskLattice.ovf', str(frequencies[i]))\nexcept FileNotFoundError:\n pass\n","sub_path":"AskLattice/Heusler/Animations/HexOut/RunNotEnhanced.py","file_name":"RunNotEnhanced.py","file_ext":"py","file_size_in_byte":4753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"603628342","text":"import numpy as np\r\nimport tensorflow as tf\r\nimport os\r\n\r\n# GPU Run\r\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\r\nfrom keras.backend.tensorflow_backend import set_session\r\nconfig = tf.ConfigProto()\r\nconfig.gpu_options.per_process_gpu_memory_fraction = 0.1\r\nset_session(tf.Session(config=config))\r\n\r\nfrom keras.models import Model\r\nfrom keras.layers import Dense, Input, Add\r\nfrom keras.optimizers import RMSprop\r\nfrom keras.initializers import glorot_normal\r\n\r\n# DQN algorithm\r\nclass DQN:\r\n def __init__(self, state_size, n_actions, n_nodes,\r\n state_action_memory_size, memory_size=500, replace_target_iter=200, batch_size=32, learning_rate=0.01, # 学习率\r\n gamma=0.9, epsilon=1, epsilon_min=0.01, epsilon_decay=0.995):\r\n # hyper-parameters\r\n self.state_size = state_size\r\n self.n_actions = n_actions\r\n self.n_nodes = n_nodes\r\n self.state_action_memory_size = state_action_memory_size\r\n self.memory_size = memory_size\r\n self.replace_target_iter = replace_target_iter\r\n self.batch_size = batch_size\r\n self.learning_rate = learning_rate\r\n self.gamma = gamma\r\n self.epsilon = epsilon\r\n self.epsilon_min = epsilon_min\r\n self.epsilon_decay = epsilon_decay\r\n self.state_action_memory = np.zeros((self.state_action_memory_size, self.state_size + 1))\r\n self.memory = np.zeros((self.memory_size, self.state_size * 2 + 2)) # memory_size * len(s, a, r, s_)\r\n # temporary parameters\r\n self.learn_state_action_counter = 0\r\n self.learn_step_counter = 0\r\n self.memory_couter = 0\r\n\r\n # # # # # # # build mode\r\n self.model = self.build_DenseNet_model() # model: evaluate Q value\r\n self.target_model = self.build_DenseNet_model() # target_mode: target network\r\n\r\n # neural network\r\n def build_DenseNet_model(self):\r\n inputs = Input(shape=(self.state_size,))\r\n h1 = Dense(64, activation=\"relu\", kernel_initializer=glorot_normal(seed=247))(inputs) # h1\r\n h2 = Dense(64, activation=\"relu\", kernel_initializer=glorot_normal(seed=2407))(h1) # h2\r\n\r\n h3 = Dense(64, activation=\"relu\", kernel_initializer=glorot_normal(seed=2403))(h2) # h3\r\n h4 = Dense(64, activation=\"relu\", kernel_initializer=glorot_normal(seed=24457))(h3) # h4\r\n add1 = Add()([h4, h2])\r\n h5 = Dense(64, activation=\"relu\", kernel_initializer=glorot_normal(seed=24657))(add1) # h5\r\n h6 = Dense(64, activation=\"relu\", kernel_initializer=glorot_normal(seed=27567))(h5) # h6\r\n add2 = Add()([h6, add1])\r\n\r\n outputs = Dense(self.n_actions, kernel_initializer=glorot_normal(seed=242147))(add2)\r\n model = Model(inputs=inputs, outputs=outputs)\r\n model.compile(loss=\"mse\", optimizer=RMSprop(lr=self.learning_rate))\r\n return model\r\n\r\n # choose an action\r\n def choose_action(self, state):\r\n state = state[np.newaxis, :]\r\n self.epsilon *= self.epsilon_decay\r\n self.epsilon = max(self.epsilon_min, self.epsilon)\r\n if np.random.random() < self.epsilon:\r\n return np.random.randint(0, 2)\r\n action_values = self.model.predict(state)\r\n return np.argmax(action_values)\r\n\r\n # experience buffer\r\n def store_transition(self, s, a, r, s_): # s_: next_state\r\n if not hasattr(self, 'memory_couter'):\r\n self.memory_couter = 0\r\n transition = np.concatenate((s, [a, r], s_))\r\n index = self.memory_couter % self.memory_size\r\n self.memory[index, :] = transition\r\n self.memory_couter += 1\r\n\r\n # update Q-target\r\n def repalce_target_parameters(self):\r\n weights = self.model.get_weights()\r\n self.target_model.set_weights(weights)\r\n\r\n # train\r\n def learn(self):\r\n if self.learn_step_counter % self.replace_target_iter == 0:\r\n self.repalce_target_parameters() # iterative target model\r\n self.learn_step_counter += 1\r\n\r\n # sample batch memory from all memory\r\n if self.memory_couter > self.memory_size:\r\n sample_index = np.random.choice(self.memory_size, size=self.batch_size)\r\n else:\r\n sample_index = np.random.choice(self.memory_couter, size=self.batch_size)\r\n\r\n # judicious experience replay\r\n sample_index1 = []\r\n sample_index2 = []\r\n for i in sample_index:\r\n if i >= self.memory_size-(self.state_action_memory_size):\r\n if self.memory_couter > self.memory_size:\r\n a11 = np.random.randint(0, self.memory_size-(self.state_action_memory_size))\r\n sample_index1.append(a11)\r\n sample_index2.append(a11 + self.state_action_memory_size - 1)\r\n else:\r\n a12 = np.random.randint(0, self.memory_couter-(self.state_action_memory_size))\r\n sample_index1.append(a12)\r\n sample_index2.append(a12 + self.state_action_memory_size - 1)\r\n else:\r\n sample_index1.append(i)\r\n sample_index2.append(i + self.state_action_memory_size - 1)\r\n\r\n batch_memory1 = self.memory[sample_index1, :]\r\n batch_memory2 = self.memory[sample_index2, :]\r\n\r\n # batch memory row: [s, a, r1, r2, s_]\r\n # number of batch memory: batch size\r\n # extract state, action, reward, reward2, next_state from bathc memory\r\n state = batch_memory1[:, :self.state_size]\r\n action = batch_memory1[:, self.state_size].astype(int)\r\n reward = batch_memory2[:, self.state_size + 1]\r\n next_state = batch_memory2[:, -self.state_size:]\r\n\r\n q_eval = self.model.predict(state)\r\n q_next = self.target_model.predict(next_state)\r\n q_target = q_eval.copy()\r\n batch_index = np.arange(self.batch_size, dtype=np.int32)\r\n q_target[batch_index, action] = reward + self.gamma * np.max(q_next, axis=1)\r\n self.model.fit(state, q_target, self.batch_size, epochs=1, verbose=0)","sub_path":"SimulCode/Brain.py","file_name":"Brain.py","file_ext":"py","file_size_in_byte":6031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"628632256","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 24 11:14:45 2018\n\n@author: david\n\"\"\"\n\nfrom kivy.app import App\nfrom kivy.properties import ObjectProperty\nfrom kivy.uix.widget import Widget\nfrom kivy.uix.button import Button\nfrom kivy.uix.scatter import Scatter\nfrom kivy.storage.jsonstore import JsonStore\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.popup import Popup\nfrom kivy.uix.gridlayout import GridLayout\nfrom kivy.graphics import Rectangle\nfrom kivy.uix.label import Label\nfrom kivy.graphics import Line, Color\nfrom kivy.vector import Vector\nfrom kivy.graphics.transformation import Matrix\nfrom math import radians\nfrom os import listdir\n\nclass StretchScatter(Scatter):\n \n '''Original Scatter widget can only be scaled with fixed aspect ratio, we want to allow rectangles'''\n \n def get_scale_xy(self):\n p1 = Vector(*self.to_parent(0, 0))\n p2 = Vector(*self.to_parent(1, 0))\n scale_x = p1.distance(p2)\n \n p3 = Vector(*self.to_parent(0, 0))\n p4 = Vector(*self.to_parent(0, 1))\n scale_y = p3.distance(p4)\n \n return scale_x, scale_y\n \n def on_touch_down(self, touch):\n x, y = touch.x, touch.y\n \n #if double touch always propagate to children\n if touch.is_double_tap:\n return super(Scatter, self).on_touch_down(touch)\n \n # if the touch isnt on the widget we do nothing\n if not self.do_collide_after_children:\n if not self.collide_point(x, y):\n return False\n \n # let the child widgets handle the event if they want\n touch.push()\n touch.apply_transform_2d(self.to_local)\n if super(Scatter, self).on_touch_down(touch):\n touch.pop()\n self._bring_to_front(touch)\n return True\n touch.pop()\n \n # if our child didn't do anything, and if we don't have any active\n # interaction control, then don't accept the touch.\n if not self.do_translation_x and \\\n not self.do_translation_y and \\\n not self.do_rotation and \\\n not self.do_scale:\n return False\n \n if self.do_collide_after_children:\n if not self.collide_point(x, y):\n return False\n \n if 'multitouch_sim' in touch.profile:\n touch.multitouch_sim = True\n # grab the touch so we get all it later move events for sure\n self._bring_to_front(touch)\n touch.grab(self)\n self._touches.append(touch)\n self._last_touch_pos[touch] = touch.pos\n \n return True\n \n def transform_with_touch(self, touch):\n # just do a simple one finger drag\n changed = False\n if len(self._touches) == self.translation_touches:\n # _last_touch_pos has last pos in correct parent space,\n # just like incoming touch\n dx = (touch.x - self._last_touch_pos[touch][0]) \\\n * self.do_translation_x\n dy = (touch.y - self._last_touch_pos[touch][1]) \\\n * self.do_translation_y\n dx = dx / self.translation_touches\n dy = dy / self.translation_touches\n self.apply_transform(Matrix().translate(dx, dy, 0))\n changed = True\n\n if len(self._touches) == 1:\n return changed\n\n # we have more than one touch... list of last known pos\n points = [Vector(self._last_touch_pos[t]) for t in self._touches\n if t is not touch]\n # add current touch last\n points.append(Vector(touch.pos))\n\n # we only want to transform if the touch is part of the two touches\n # farthest apart! So first we find anchor, the point to transform\n # around as another touch farthest away from current touch's pos\n anchor = max(points[:-1], key=lambda p: p.distance(touch.pos))\n\n # now we find the touch farthest away from anchor, if its not the\n # same as touch. Touch is not one of the two touches used to transform\n farthest = max(points, key=anchor.distance)\n if farthest is not points[-1]:\n return changed\n\n # ok, so we have touch, and anchor, so we can actually compute the\n # transformation\n old_line = Vector(*touch.ppos) - anchor\n new_line = Vector(*touch.pos) - anchor\n if not old_line.length(): # div by zero\n return changed\n\n angle = radians(new_line.angle(old_line)) * self.do_rotation\n self.apply_transform(Matrix().rotate(angle, 0, 0, 1), anchor=anchor)\n\n if self.do_scale:\n scale_x = new_line.x/ old_line.x\n scale_y = new_line.y/ old_line.y\n \n new_scale_x = scale_x * self.scale\n if new_scale_x < self.scale_min:\n scale_x = self.scale_min / self.scale\n elif new_scale_x > self.scale_max:\n scale_x = self.scale_max / self.scale\n \n new_scale_y = scale_y * self.scale\n if new_scale_y < self.scale_min:\n scale_y = self.scale_min / self.scale\n elif new_scale_y > self.scale_max:\n scale_y = self.scale_max / self.scale\n \n self.apply_transform(Matrix().scale(scale_x, scale_y, 1),\n anchor=anchor)\n changed = True\n \n return changed\n \n\nclass AnnotationBox(Widget):\n box_size = (300, 300)\n\nclass Background(Widget):\n pass\n \nclass RootWidget(Widget):\n def __init__(self):\n super(RootWidget, self).__init__()\n self.filepop = SaveFile()\n self.filepop.open()\n \n self.img_num = 0\n self.boxes = []\n self.box_size = AnnotationBox().box_size\n \n self.file_selected = False\n self.paint = False\n \n self.stroke_num = 0\n self.pix_dict = {}\n \n def on_touch_down(self, touch):\n if self.file_selected and touch.is_double_tap and not self.paint:\n #add bounding box on touch\n self.add_bounding_box(touch)\n return True\n else:\n if self.paint:\n #draw points as a line\n with self.canvas:\n Color(.1, .1, 1, .9)\n touch.ud['line'] = Line(points=(touch.x, touch.y), width = 5.0)\n \n return super(RootWidget, self).on_touch_down(touch) #propagate touch down chain\n \n def on_touch_up(self, touch):\n #change to new object on release\n if self.paint:\n self.stroke_num += 1\n \n return super(RootWidget, self).on_touch_down(touch) #propagate touch down chain\n \n def on_touch_move(self, touch):\n if self.paint:\n #get highlighted points\n touch.ud['line'].points += [touch.x, touch.y]\n \n #add to pixel dictionary of highlighted points\n if 'Object %i: '%self.stroke_num in self.pix_dict:\n self.pix_dict['Object %i: '%self.stroke_num].append([int(touch.x), int(touch.y)])\n else:\n self.pix_dict['Object %i: '%self.stroke_num] = [int(touch.x), int(touch.y)]\n \n def add_progress_bar(self):\n with self.canvas: \n Color(0,1,0,1)\n prog_ratio = float(self.img_num)/float(len(self.all_imgs))\n Line(points = [self.size[0]*.25, self.size[1]*.925, \n self.size[0]*.25+prog_ratio*self.size[0]*.5, \n self.size[1]*.925], width = self.size[1]*.015, cap = 'none')\n \n Color(0,0,0,1)\n Line(rectangle = (self.size[0]*.25, self.size[1]*.91, \n self.size[0]*.5, self.size[1]*.03), width = 5.0)\n\n def add_bounding_box(self, touch):\n #freeze all old bounding boxes\n for box in self.boxes:\n box.do_translation_x = False\n box.do_translation_y = False\n box.do_scale = False\n \n #add a new bounding box\n BBpos = (touch.x - self.box_size[0]/2, touch.y - self.box_size[1]/2)\n scatter = StretchScatter(pos=BBpos, do_rotation=False)\n scatter.scale_x = 1.0\n scatter.scale_y = 1.0\n \n scatter.add_widget(AnnotationBox())\n self.parent.add_widget(scatter)\n \n self.boxes.append(scatter)\n \n def submit_annotation(self, bt_instance):\n \n if self.paint:\n #save highlighted points as json\n self.annotations.put(self.all_imgs[self.img_num], pixels = self.pix_dict)\n else:\n #save bounding boxes as json\n ann_dict = {}\n for n, box in enumerate(self.boxes):\n scale_x, scale_y = box.get_scale_xy()\n ann_dict['Box %i: '%n] = {\"center\": box.center, \"scale_x\": scale_x, \"scale_y\": scale_y,\n \"box_size\": self.box_size,\"img_size\": self.size}\n \n self.annotations.put(self.all_imgs[self.img_num], annotations = ann_dict)\n \n #go to next unannotated image\n self.img_num += 1\n self.canvas.clear()\n \n #show the new image\n if self.img_num List[List[int]]:\n def findAllCombinations(target: int):\n if target <= 0 or target in visited:\n return\n for c in candidates:\n t = target-c\n if t > 0:\n findAllCombinations(t)\n for e in d[t]:\n if e[-1] <= c:\n d[target].append(e+[c])\n visited.add(target)\n \n visited, d = set(), defaultdict(list)\n for c in candidates:\n d[c].append([c])\n \n findAllCombinations(target)\n return d[target]\n","sub_path":"Leetcode/Combination_Sum.py","file_name":"Combination_Sum.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"296850983","text":"\"\"\"Handle merging and spliting of DSI files.\"\"\"\nimport numpy as np\nfrom nipype.interfaces import afni\nimport os.path as op\nfrom nipype.interfaces.base import (BaseInterfaceInputSpec, TraitedSpec, File, SimpleInterface,\n InputMultiObject, traits)\nfrom nipype.utils.filemanip import fname_presuffix\nimport nibabel as nb\n\n\nclass MergeDWIsInputSpec(BaseInterfaceInputSpec):\n dwi_files = InputMultiObject(\n File(exists=True), mandatory=True, desc='list of dwi files')\n bids_dwi_files = InputMultiObject(\n File(exists=True), mandatory=True, desc='list of original (BIDS) dwi files')\n bval_files = InputMultiObject(\n File(exists=True), mandatory=True, desc='list of bval files')\n bvec_files = InputMultiObject(\n File(exists=True), mandatory=True, desc='list of bvec files')\n\n\nclass MergeDWIsOutputSpec(TraitedSpec):\n out_dwi = File(desc='the merged dwi image')\n out_bval = File(desc='the merged bvec file')\n out_bvec = File(desc='the merged bval file')\n original_images = traits.List()\n\n\nclass MergeDWIs(SimpleInterface):\n input_spec = MergeDWIsInputSpec\n output_spec = MergeDWIsOutputSpec\n\n def _run_interface(self, runtime):\n bvals = self.inputs.bval_files\n bvecs = self.inputs.bvec_files\n\n def get_nvols(img):\n shape = nb.load(img).shape\n if len(shape) < 4:\n return 1\n return shape[3]\n\n if len(self.inputs.dwi_files) > 1:\n dwimrg = afni.TCat(in_files=self.inputs.dwi_files, outputtype='NIFTI_GZ')\n merged_fname = dwimrg.run().outputs.out_file\n self._results['out_dwi'] = merged_fname\n out_bvec = fname_presuffix(merged_fname, suffix=\".bvec\", use_ext=False,\n newpath=runtime.cwd)\n out_bval = fname_presuffix(merged_fname, suffix=\".bval\", use_ext=False,\n newpath=runtime.cwd)\n self._results['out_bval'] = combine_bvals(bvals, output_file=out_bval)\n self._results['out_bvec'] = combine_bvecs(bvecs, output_file=out_bvec)\n sources = []\n for img in self.inputs.bids_dwi_files:\n sources += [img] * get_nvols(img)\n self._results['original_images'] = sources\n else:\n dwi_file = self.inputs.dwi_files[0]\n bids_dwi_file = self.inputs.bids_dwi_files[0]\n self._results['out_dwi'] = dwi_file\n self._results['out_bval'] = bvals[0]\n self._results['out_bvec'] = bvecs[0]\n self._results['original_images'] = [bids_dwi_file] * get_nvols(bids_dwi_file)\n return runtime\n\n\ndef combine_bvals(bvals, output_file=\"restacked.bval\"):\n \"\"\"Load, merge and save fsl-style bvals files.\"\"\"\n collected_vals = []\n for bval_file in bvals:\n collected_vals.append(np.atleast_1d(np.loadtxt(bval_file)))\n final_bvals = np.concatenate(collected_vals)\n np.savetxt(output_file, final_bvals, fmt=str(\"%i\"))\n return op.abspath(output_file)\n\n\ndef combine_bvecs(bvecs, output_file=\"restacked.bvec\"):\n \"\"\"Load, merge and save fsl-style bvecs files.\"\"\"\n collected_vecs = []\n for bvec_file in bvecs:\n collected_vecs.append(np.loadtxt(bvec_file))\n final_bvecs = np.column_stack(collected_vecs)\n np.savetxt(output_file, final_bvecs, fmt=str(\"%.8f\"))\n return op.abspath(output_file)\n","sub_path":"qsiprep/interfaces/dwi_merge.py","file_name":"dwi_merge.py","file_ext":"py","file_size_in_byte":3431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"506353317","text":"#!/usr/bin/env python3\n\"\"\"fs wrapper: Contains generic filesystem operations, that depend on plugins.\n\nBearable: Tolerable backup and restore.\nhttps://www.github.com/Effenberg0x0/bearable\n\nAlvaro Leal , 2019\n\"\"\"\nimport importlib\nfrom archive import Archive\n\n\nclass FS(object):\n def __init__(self, profile):\n self.profile = profile\n self.fs_engine = None\n self.load_fs_engine_plugin(profile[\"plugin\"])\n self.fs = self.fs_engine.FS(profile)\n\n def load_fs_engine_plugin(self, fs_engine):\n try:\n self.fs_engine = importlib.import_module(\"plugins.fs.\" + fs_engine)\n except ImportError as e:\n print(\"Failed to import plugin for the selected filesystem engine: {0}\" # noqa\n .format(e))\n # logging.error(\n # 'Error importing driver \"%s\", please check your --driver '\n # 'parameter:\\n%s', args.driver, e)\n return 1\n\n def archive(self, archive_settings, tmp_path):\n files = self.fs.get_files_list()\n archive = Archive(archive_settings)\n archive.create(tmp_path, files, dirname=self.profile[\"name\"])\n\n def restore_files(self, source_path):\n overwrite = self.profile.get(\"restore_overwrite\", False)\n self.fs.restore_files(source_path, overwrite=overwrite)\n","sub_path":"fs/_fs.py","file_name":"_fs.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"644107139","text":"from random import randint\nfrom table.GameMechanics import *\nfrom table.transposition_table import*\n\n\nclass MIN_MAX():\n game_mechanics = GameMechanics()\n t_table = T_table()\n player_increment={\"red\": \"blue\" , \"green\": \"blue\" , \"blue\": \"red\"}\n\n\n def alpha_beta( self, state , depth , alpha , beta , current_colour, max_colour):\n \n\n #not sure why \n alpha_original = alpha\n #lookup for transposition table\n t_score , t_flag, t_best = self.t_table.lookup_score(state, depth)\n #if an entry was found \n if(t_score != None):\n #exact value\n if t_flag == 0:\n #this state has been explored to sufficent depth\n #return \n return t_score, t_best\n #lower_bound\n elif t_flag == 1:\n alpha = max(alpha, t_score)\n elif t_flag == 2:\n alpha = min(beta, t_score)\n #if this causes a cut off return values found in table\n #ie this node has been pruned\n if alpha >=beta:\n return t_score, t_best\n\n if(depth == 0 or self.is_terminal_state(state)):\n #exit state cannot have a best child state\n return self.heuristic_value(state, max_colour), None\n # maximising player\n if(current_colour == max_colour):\n value = float(\"-inf\")\n best_child = None\n for child_state in self.game_mechanics.get_all_possible_states(state, current_colour):\n temp_value, _ = self.alpha_beta(child_state, depth -1 , alpha , beta, self.player_increment[current_colour], max_colour)\n #update value and best child\n if(temp_value > value):\n value = temp_value\n best_child = child_state\n alpha = max( alpha , value)\n\n if ( alpha >= beta ):\n break\n\n #minimising players\n else:\n value = float(\"inf\")\n best_child = None\n for child_state in self.game_mechanics.get_all_possible_states(state, current_colour):\n (temp_value, _) = self.alpha_beta(child_state, depth -1 , alpha , beta, self.player_increment[current_colour], max_colour)\n if(temp_value < value):\n value = temp_value\n best_child = child_state\n beta = min(beta, value)\n\n if(alpha >= beta):\n break\n #add to transposition table\n if value <= alpha_original:\n self.t_table.replace_entry(state, value, depth,best_child , 1)\n elif value >= beta:\n self.t_table.replace_entry(state, value, depth,best_child , 2)\n else:\n self.t_table.replace_entry(state, value, depth,best_child , 0)\n\n #print(self.t_table.match_count)\n #returns the best score and child of this current state \n return value , best_child\n\n\n def is_terminal_state(self, state):\n for colour in state.exit_counts:\n if(state.exit_counts[colour] == 4):\n return 1; \n return 0; \n\n\n\n #testing purposes\n def heuristic_value(self, state, max_colour):\n MAX_DISTANCE = 24\n weight = 0\n feature_total = 0\n distance_apart = 0 \n for colour in state.piece_nodes:\n distance_list = []\n if(colour == max_colour):\n weight = 1\n else:\n weight = -1\n\n distance = list()\n\n num_pieces = len(state.piece_nodes[colour])\n for piece in state.piece_nodes[colour]:\n distance.append((6-self.manhattan_distance(piece,colour)))\n\n distance.sort()\n closest4 = 0\n otherpieces = 0 \n for i in range(0 , min(4, num_pieces)):\n closest4+= (distance[i])\n for i in range(4 , num_pieces):\n otherpieces+= (distance[i])\n\n feature_total += weight* closest4/4\n feature_total += weight*otherpieces/8\n if num_pieces + state.exit_counts[colour] < 4: \n feature_total+= weight* - 50\n\n if(num_pieces >0):\n feature_total+= weight* state.exit_counts[colour]* (closest4/num_pieces)*(closest4/num_pieces)\n\n #feature_total+= weight* state.exit_counts[colour]* (closest4/4)*(closest4/4)\n\n if(state.exit_counts[colour]==4):\n feature_total += 100*weight\n\n return feature_total\n\n\n def manhattan_distance(self, coord, colour):\n '''returns the min possible moves from each node to any exit nodes\n Note doesn't inlcude cost of exiting board'''\n\n #coefficents for line cf[0]q + cf[1]r + cf[2] = 0 \n cf = {\"blue\" : [1,1,3] , \"red\": [1,0,-3], \"green\" : [0,1,-3]}\n \n #Shortest number of nodes between the node and any exit node\n stepCost = abs(cf[colour][0]*coord[0] + cf[colour][1]*coord[1] + cf[colour][2])\n \n\n #jumpCost = stepCost//2 + stepCost%2 +1\n return stepCost +1\n\n\n def is_adjacent(self, coord1, coord2):\n if self.get_dist(coord1, coord2) <= sqrt(2):\n return 1\n else:\n return 0\n\n def get_dist(self, node_1, node_2):\n \"\"\"\n Returns the Euclidean distance between two nodes.\n \"\"\"\n\n return sqrt((node_1[0] - node_2[0])**2 + (node_1[1] - node_2[1])**2)\n\n \n\n","sub_path":"table/min_max.py","file_name":"min_max.py","file_ext":"py","file_size_in_byte":5478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"549653120","text":"import asyncio\nfrom inspect import iscoroutine\n\nimport httpx\nimport msgpack\n\nfrom ..utils import Sentinel\n\n\nclass UNSET(Sentinel):\n pass\n\n\ndef get_content_with_cache(\n cache, offline, client, path, accept=None, timeout=UNSET, **kwargs\n):\n request = client.build_request(\"GET\", path, **kwargs)\n if accept:\n request.headers[\"Accept\"] = accept\n url = request.url.raw # URL as tuple\n if offline:\n # We must rely on the cache alone.\n reservation = cache.get_reservation(url)\n if reservation is None:\n raise NotAvailableOffline(url)\n content = reservation.load_content()\n if content is None:\n # TODO Do we ever get here?\n raise NotAvailableOffline(url)\n return content\n if cache is None:\n # No cache, so we can use the client straightforwardly.\n response = _send(client, request, timeout=timeout)\n handle_error(response)\n return response.content\n # If we get this far, we have an online client and a cache.\n reservation = cache.get_reservation(url)\n try:\n if reservation is not None:\n request.headers[\"If-None-Match\"] = reservation.etag\n response = _send(client, request, timeout=timeout)\n handle_error(response)\n if response.status_code == 304: # HTTP 304 Not Modified\n # Read from the cache\n content = reservation.load_content()\n elif response.status_code == 200:\n etag = response.headers.get(\"ETag\")\n content = response.content\n # TODO Respect Cache-control headers (e.g. \"no-store\")\n if etag is not None:\n # Write to cache.\n cache.put_etag_for_url(url, etag)\n cache.put_content(etag, content)\n else:\n raise NotImplementedError(f\"Unexpected status_code {response.status_code}\")\n finally:\n if reservation is not None:\n reservation.ensure_released()\n return content\n\n\ndef get_json_with_cache(cache, offline, client, path, **kwargs):\n return msgpack.unpackb(\n get_content_with_cache(\n cache, offline, client, path, accept=\"application/x-msgpack\", **kwargs\n )\n )\n\n\ndef _send(client, request, timeout):\n \"\"\"\n EXPERIMENTAL: Tolerate sync httpx.Client or httpx.AsyncClient.\n\n The AsyncClient is interesting because it can interface directly with FastAPI app\n in the same process via ASGI.\n \"\"\"\n if timeout is UNSET:\n result = client.send(request)\n else:\n result = client.send(request, timeout=timeout)\n if iscoroutine(result):\n return asyncio.run(result)\n return result\n\n\ndef handle_error(response):\n try:\n response.raise_for_status()\n except httpx.RequestError:\n raise # Nothing to add in this case; just raise it.\n except httpx.HTTPStatusError as exc:\n if response.status_code < 500:\n # Include more detail that httpx does by default.\n message = (\n f\"{exc.response.status_code}: \"\n f\"{exc.response.json()['detail']} \"\n f\"{exc.request.url}\"\n )\n raise ClientError(message, exc.request, exc.response) from exc\n else:\n raise\n\n\nclass ClientError(httpx.HTTPStatusError):\n def __init__(self, message, request, response):\n super().__init__(message=message, request=request, response=response)\n\n\nclass NotAvailableOffline(Exception):\n \"Item looked for in offline cache was not found.\"\n","sub_path":"tiled/client/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"157185614","text":"# encoding=utf-8\nimport os\nimport re\n\ntry:\n from http.client import HTTPConnection\nexcept ImportError as e:\n pass\n\ndef get_path(web_root, web_path):\n if web_path[0] == \"/\":\n web_path = web_path[1:]\n if os.name == \"nt\":\n web_path = web_path.replace(\"/\", \"\\\\\")\n return os.path.join(web_root, web_path)\n\n\ndef get_http_home(host):\n if not host.startswith((\"http://\", \"https://\")):\n return \"http://\" + host\n return host\n\ndef get_http_url(url):\n if not url.startswith((\"http://\", \"https://\")):\n return \"http://\" + url\n return url\n\ndef get_host(url):\n p = r\"https?://([^\\/]+)\"\n m = re.match(p, url)\n if m and m.groups():\n return m.groups()[0]\n return None\n\n# 使用低级API访问HTTP,可以任意设置header,data等\ndef do_http(method, url, headers, data=None):\n addr = get_host(url)\n cl = HTTPConnection(addr)\n cl.request(method, url, data, headers = headers)\n head = None\n buf = None\n response_headers = None\n with cl.getresponse() as resp:\n response_headers = resp.getheaders()\n content_type = resp.getheader(\"Content-Type\")\n content_encoding = resp.getheader(\"Content-Encoding\")\n buf = resp.read()\n if content_encoding == \"gzip\":\n fileobj = io.BytesIO(buf)\n gzip_f = gzip.GzipFile(fileobj=fileobj, mode=\"rb\")\n content = gzip_f.read()\n return content\n elif content_encoding != None:\n raise Exception(\"暂不支持%s编码\" % content_encoding)\n return resp.getcode(), response_headers, buf\n","sub_path":"util/netutil.py","file_name":"netutil.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"399543935","text":"\"\"\"import\"\"\"\nimport datetime\nfrom django.contrib.auth.models import User\nfrom django.http import HttpRequest\nfrom importlib import import_module\nfrom django.contrib.auth import get_user_model\nfrom django.test import TestCase\nfrom django.utils import timezone\nfrom django.urls import reverse\nfrom polls.models import Question\n\ndef create_question(question_text, days, days2):\n \"\"\"Create question.\n\n Function that create the Question.\n\n Args:\n -question_text- Text of the question to create\n -days- Publish day\n -days2- End day\n Returns:\n A Question.\n \"\"\"\n time = timezone.now() + datetime.timedelta(days=days)\n time2 = timezone.now() + datetime.timedelta(days=days2)\n return Question.objects.create(question_text=question_text, pub_date=time, end_date=time2)\n\nclass VotingTests(TestCase):\n\n def setUp(self):\n User = get_user_model()\n user = User.objects.create_user(\"Boom\", \"puva@gmaail.com\", \"bbbbbbbb\")\n user.first_name = 'Boom'\n user.last_name = \"Puvana\"\n user.save()\n\n def test_unauthenticate_vote(self):\n \"\"\"test if unauthenticate user cant vote.\"\"\"\n question = create_question(question_text='Past Question.', days=-5, days2=5)\n url = reverse('polls:vote', args=(question.id,))\n response = self.client.get(url)\n self.assertEqual(response.status_code, 302)\n\n def test_authenticate_vote(self):\n \"\"\"test if authenticate user can vote.\"\"\"\n self.client.login(username=\"Boom\", password=\"bbbbbbbb\")\n question = create_question(question_text='Past Question.', days=-5, days2=5)\n url = reverse('polls:vote', args=(question.id,))\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n","sub_path":"ku-polls/polls/test/test_voting.py","file_name":"test_voting.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"193980392","text":"from django.http import HttpResponse\nfrom django.shortcuts import render, redirect\nfrom django.views import View\nfrom contactbox.models import *\n\n\nclass PersonList(View):\n def get(self, request):\n persons = Person.objects.all()\n return render(request, \"person_list.html\", {\"persons\": persons})\n\n\nclass PersonDetail(View):\n def get(self, request, id):\n person = Person.objects.get(pk=id)\n phones = Phone.objects.filter(person=person)\n emails = Email.objects.filter(person=person)\n context = {\n \"person\": person,\n \"phones\": phones,\n \"emails\": emails,\n }\n return render(request, \"person_detail.html\", context)\n\n\nclass ModifyPerson(View):\n def get(self, request, id):\n person = Person.objects.get(pk=id)\n phones = Phone.objects.filter(person=person)\n emails = Email.objects.filter(person=person)\n context = {\n \"person\": person,\n \"phones\": phones,\n \"emails\": emails,\n }\n return render(request, \"modify_person.html\", context)\n\n def post(self, request, id):\n first_name = request.POST.get(\"first_name\")\n last_name = request.POST.get(\"last_name\")\n description = request.POST.get(\"description\")\n street = request.POST.get(\"street\")\n block_number = request.POST.get(\"block_number\")\n flat_number = request.POST.get(\"flat_number\")\n city = request.POST.get(\"city\")\n post_code = request.POST.get(\"post_code\")\n\n person = Person.objects.get(pk=id)\n if first_name and last_name:\n person.first_name = first_name\n person.last_name = last_name\n person.description = description\n if person.address:\n address = person.address\n address.street = street\n address.block_number = block_number\n address.flat_number = flat_number\n address.city = city\n address.post_code = post_code\n address.save()\n else:\n if city and street and block_number and post_code:\n address = Address.objects.create(street=street,\n block_number=block_number,\n flat_number=flat_number,\n city=city,\n post_code=post_code)\n else:\n address = None\n person.address = address\n person.save()\n\n return redirect(f\"/person/{person.id}\")\n else:\n return HttpResponse(\"modify, brak imienia lub nazwiska\")\n\n\nclass DeletePerson(View):\n def get(self, request, id):\n person = Person.objects.get(pk=id)\n return render(request, \"delete_person.html\", {\"person\": person})\n\n def post(self, request, id):\n person = Person.objects.get(pk=id)\n person.delete()\n return redirect(\"/\")\n\n\nclass NewPerson(View):\n def get(self, request):\n addresses = Address.objects.all()\n return render(request, \"new_person.html\", {\"addresses\": addresses})\n\n def post(self, request):\n first_name = request.POST.get(\"first_name\")\n last_name = request.POST.get(\"last_name\")\n description = request.POST.get(\"description\")\n address_id = request.POST.get(\"address_id\")\n address = Address.objects.get(pk=address_id)\n\n if first_name and last_name:\n person = Person.objects.create(first_name=first_name,\n last_name=last_name,\n description=description,\n address=address)\n return redirect(f\"/person/{person.id}\")\n else:\n return HttpResponse(\"newperson, brak imienia lub nazwiska\")\n\n\nclass NewAddress(View):\n def get(self, request):\n return render(request, \"new_address.html\")\n\n def post(self, request):\n city = request.POST.get(\"city\")\n street = request.POST.get(\"street\")\n block_number = request.POST.get(\"block_number\")\n flat_number = request.POST.get(\"flat_number\")\n post_code = request.POST.get(\"post_code\")\n\n if city and street and block_number and post_code:\n Address.objects.create(city=city,\n street=street,\n block_number=block_number,\n flat_number=flat_number,\n post_code=post_code)\n return redirect(\"/new-person/\")\n else:\n return HttpResponse(\"brak wszytkich danych\")\n\n\nclass NewPhone(View):\n def get(self, request, id):\n return render(request, \"new_phone.html\")\n\n def post(self, request, id):\n phone_number = request.POST.get(\"phone_number\")\n phone_type = request.POST.get(\"phone_type\")\n\n if phone_number and phone_type:\n person = Person.objects.get(pk=id)\n Phone.objects.create(phone_number=phone_number,\n phone_type=phone_type,\n person=person)\n return redirect(f\"/person/{id}\")\n else:\n return HttpResponse(\"podaj numer i typ telefonu\")\n\n\nclass DeletePhone(View):\n def get(self, request, id, id_phone):\n phone = Phone.objects.get(pk=id_phone)\n return render(request, \"delete_phone.html\", {\"phone\": phone})\n\n def post(self, request, id, id_phone):\n phone = Phone.objects.get(pk=id_phone)\n phone.delete()\n return redirect(f\"/person/{id}\")\n\nclass NewEmail(View):\n def get(self, request, id):\n return render(request, \"new_email.html\")\n\n def post(self, request, id):\n email_address = request.POST.get(\"email\")\n email_type = request.POST.get(\"email_type\")\n if email_address and email_type:\n person = Person.objects.get(pk=id)\n Email.objects.create(email=email_address,\n email_type=email_type,\n person=person)\n return redirect(f\"/person/{id}\")\n else:\n return HttpResponse(\"podaj numer i typ telefonu\")\n\n\nclass DeleteEmail(View):\n def get(self, request, id, id_email):\n email = Email.objects.get(pk=id_email)\n return render(request, \"delete_phone.html\", {\"email\": email})\n\n def post(self, request, id, id_email):\n email = Email.objects.get(pk=id_email)\n email.delete()\n return redirect(f\"/person/{id}\")\n\n\nclass GroupList(View):\n def get(self, request):\n groups = Group.objects.all()\n return render(request, \"group_list.html\", {\"groups\": groups})\n\n\nclass NewGroup(View):\n def get(self, request):\n return render(request, \"new_group.html\")\n\n def post(self, request):\n name = request.POST.get(\"name\")\n if name:\n Group.objects.create(name=name)\n return redirect(\"/groups/\")\n else:\n return HttpResponse(\"Podaj nazwę grupy!\")\n\n\nclass DeleteGroup(View):\n def get(self, request, id):\n group = Group.objects.get(pk=id)\n return render(request, \"delete_group.html\", {\"group\": group})\n\n def post(self, request, id):\n group = Group.objects.get(pk=id)\n group.delete()\n return redirect(\"/groups/\")\n\n\nclass GroupDetail(View):\n def get(self, request, id):\n group = Group.objects.get(pk=id)\n persons = group.persons.all()\n context = {\n \"group\": group,\n \"persons\": persons,\n }\n return render(request, \"group_detail.html\", context)\n\n\nclass NewPersonInGroup(View):\n def get(self, request, id):\n group = Group.objects.get(pk=id)\n persons = Person.objects.all()\n context = {\n \"group\": group,\n \"persons\": persons\n }\n return render(request, \"new_person_in_group.html\", context)\n\n def post(self, request, id):\n person_id = request.POST.get(\"person_id\")\n person = Person.objects.get(pk=person_id)\n group = Group.objects.get(pk=id)\n group.persons.add(person)\n group.save()\n return redirect(f\"/group/{id}\")\n\n\nclass DeletePersonFromGroup(View):\n def get(self, request, id, id_person):\n group = Group.objects.get(pk=id)\n person = Person.objects.get(pk=id_person)\n context = {\n \"group\": group,\n \"person\": person,\n }\n return render(request, \"delete_person_from_group.html\", context)\n\n def post(self, request, id, id_person):\n person = Person.objects.get(pk=id_person)\n group = Group.objects.get(pk=id)\n group.persons.remove(person)\n return redirect(f\"/group/{id}\")","sub_path":"Workshop_3bis/contactbox/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"256946818","text":"from subprocess import Popen, PIPE\nimport os\nimport signal\n\nmodel_path = \"/root/src/asr/static/resources/model\"\nw2l_bin = \"/root/wav2letter/build/inference/inference/examples/interactive_streaming_asr_example\"\nw2l_process = Popen(['{} --input_files_base_path={}'.format(w2l_bin, model_path)],\n stdin=PIPE, stdout=PIPE, stderr=PIPE,\n shell=True)\ndef speech2text():\n w2l_process.stdin.write(b\"endtoken=DONE\\n\")\n w2l_process.stdin.write(b\"input=/tmp/temp.wav\\n\")\n w2l_process.stdin.flush()\n trans = []\n while True:\n # read from process stdout\n output = w2l_process.stdout.readline().decode('utf-8').strip()\n if output == 'DONE':\n break\n else:\n seg = output.split(',')\n if seg[0].isnumeric() and seg[1].isnumeric() and seg[2]:\n trans.append(seg[2])\n return ' '.join(trans)","sub_path":"engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"76877225","text":"import requests\nimport json\n\n#uri = 'http://10.1.9.197:8080'\nuri = 'http://192.168.0.105:8080'\n_METER = '/stats/meterentry/add'\n_RULE= '/stats/flowentry/add'\n_GET_SW_features='/stats/desc/'\n_GET_SW_List='/stats/switches'\n_GET_BW='/stats/port/'\n_SET_=''\n\n\n\n\n# Default action is DROP Packets\n# \ndef set_meter(tx,sw_id,user_id):\n msg = '{\"dpid\":1,\"flags\":\"KBPS\",\"meter_id\":1,\"bands\":[{\"type\":\"DROP\",\"rate\":100}]}'\n jmsg = json.loads(msg) \n jmsg[\"meter_id\"]=user_id\n jmsg[\"dpid\"]= sw_id\n tmp =jmsg[\"bands\"][0]\n tmp[\"rate\"]=tx\n jmsg[\"bands\"][0]=tmp\n print (uri+_METER+str(sw_id))\n resp_1= requests.post(uri+_METER,json=jmsg)\n \n return resp_1\n\n\ndef set_rule(ip,user_id,sw_id):\n\n msg = '{\"dpid\": 1,\"cookie\": 1,\"cookie_mask\": 1,\"table_id\": 0, \"idle_timeout\": 30,\"hard_timeout\": 30,\"priority\": 11111,\"flags\": 1,\"match\":{\"ipv4_src\":\"10.0.0.1\"},\"instructions\":[{\"type\":\"GOTO_TABLE\",\"table_id:1},{\"type\":\"METER\",\"meter_id\":1}]}'\n jmsg = json.loads(msg) \n jmsg[\"dpid\"]=sw_id\n jmsg[\"match\"][\"ipv4_src\"]=ip\n jmsg[\"instructions\"][1][\"meter_id\"]=user_idt\n try:\n resp_1= requests.post(uri+_RULE,json=jmsg)\n except:\n pass\n\n msg = '{\"dpid\": 1,\"cookie\": 1,\"cookie_mask\": 1,\"table_id\": 0, \"idle_timeout\": 30,\"hard_timeout\": 30,\"priority\": 11111,\"flags\": 1,\"match\":{\"ipv4_dst\":\"10.0.0.1\"},\"instructions\":[{\"type\":\"GOTO_TABLE\",\"table_id:1},{\"type\":\"METER\",\"meter_id\":1}]}'\n jmsg = json.loads(msg) \n jmsg[\"dpid\"]=sw_id\n jmsg[\"match\"][\"ipv4_dst\"]=ip\n jmsg[\"instructions\"][1][\"meter_id\"]=user_id\n try:\n resp_1= requests.post(uri+_RULE,json=jmsg)\n except:\n pass\n\ndef get_sw_feature(sw_id):\n try:\n resq = requests.get(uri+_GET_SW_features+sw_id)\n return resq.json()\n except:\n return []\ndef get_sw_list():\n try:\n resq = requests.get(uri+_GET_SW_List)\n return resq.json()\n except:\n return []\n \ndef trafego_(sw_id):\n try:\n resq= requests.get(uri+_GET_BW+str(sw_id))\n data= resq.json()\n return data\n except:\n return []\n","sub_path":"sdn.py","file_name":"sdn.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"415944545","text":"import re\nfrom zzz.chapter03.knock20 import extract_text\nfrom zzz.chapter03.knock25 import template\n\ndef del_mark(text_dict, pattern, func):\n for key, value in text_dict.items():\n text_dict[key] = re.sub(pattern, func, value)\n return text_dict\n\nif __name__ == '__main__':\n filename = 'jawiki-country.json'\n text = extract_text(filename, 'イギリス')\n\n basic = template(text)\n\n pattern = r'(\\'{3})(.*?)(\\'{3})' # '''強調'''\n basic = del_mark(basic, pattern, lambda x: x.group(2))\n for (key, value) in basic.items():\n print(key, value)\n\n\n","sub_path":"zzz/chapter03/knock26.py","file_name":"knock26.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"46476861","text":"#!/usr/bin/env python\n# -*-coding:utf-8 -*-\nimport unittest\nimport os,sys\nos.environ['CHECK_SERVER_HOME_DIR'] = os.path.dirname(os.path.realpath(sys.argv[0]))[0:-5]\nos.environ['CHECK_SERVER_PY_PATH'] = os.path.dirname(os.path.realpath(sys.argv[0]))[0:-5]\nsys.path.append(os.environ['CHECK_SERVER_HOME_DIR'])\n\nclass HdfsClientUnitTest(unittest.TestCase):\n\n def setUp(self):\n from module.HdfsClient import HdfsClient\n self.host1 = 'hadoop001.dx.momo.com'\n self.host2 = 'hadoop002.dx.momo.com'\n self.port = 50070\n\n def tearDown(self):\n self.host1 = None\n self.hose2 = None\n self.port = None\n\n def testHdfsClientUrl(self):\n from module.HdfsClient import HdfsClient\n client = HdfsClient(self.host1,self.port)\n assert client is not None, 'HdfsClient error'\n assert client.host == self.host1, 'HdfsClient host error'\n assert client.port == self.port, 'HdfsClient port error'\n assert client.url == 'http://' + self.host2 + ':' + str(self.port) + '/webhdfs/v1','HdfsClient %s url error' % (self.host1)\n client = HdfsClient(self.host2,self.port)\n assert client.url == 'http://' + self.host2 + ':' + str(self.port) + '/webhdfs/v1','HdfsClient %s url error' % (self.host2)\n\n def testHdfsClientHasDataFunc(self):\n from module.HdfsClient import HdfsClient\n client = HdfsClient(self.host1,self.port)\n uri = '/user/hive/thirddata/tl_group_account_updates/20150113'\n rtc = client.hasData(uri)\n assert rtc == 1, 'HdfsClient HasData() error'\n uri = '/user/hive/thirddata/tl_group_account_updates/20140113'\n rtc = client.hasData(uri)\n assert rtc == 0, 'HdfsClient HasData() error'\n\ndef testSuite():\n suite = unittest.TestSuite()\n suite.addTest(HdfsClientUnitTest('testHdfsClientUrl'))\n suite.addTest(HdfsClientUnitTest('testHdfsClientHasDataFunc'))\n return suite\n\nif __name__ == '__main__':\n unittest.main(defaultTest = 'testSuite')\n\n","sub_path":"utils_updates/data_ready_checker/server/test/HdfsClientUnitTest.py","file_name":"HdfsClientUnitTest.py","file_ext":"py","file_size_in_byte":2002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"183868198","text":"from flask import Flask,render_template,session,request, redirect, url_for, g\nfrom app import webapp\nfrom app.crud import *\nfrom app.constants import *\nfrom app.public_user_info import PublicUserInfo\nfrom app.private_user_info import PrivateUserInfo\nfrom app.photo_info import PhotoInfo\nfrom app import ml_util\nimport datetime\nimport boto3\nimport os\n@webapp.route('/browse/', methods=['GET', 'POST'])\ndef browse(photo_username):\n s3=boto3.client('s3')\n print(photo_username)\n response_public=select_public_user_info(photo_username)\n response_photo=select_all_photo_info_for_user(photo_username)\n #need modification here\n post_username=response_public[USERNAME]\n post_region=response_public[REGION]\n post_email=response_public[EMAIL]\n post_bio=response_public[DESCRIPTION]\n post_birth=response_public[BIRTHDAY]\n post_interest=response_public[GENDER_AND_INTEREST]\n post_gender=[]\n post_interest=int(post_interest)\n if post_interest<=3:\n post_gender.append('male')\n if post_interest==3:\n post_gender.append('both')\n if post_interest==2:\n post_gender.append('male')\n if post_interest==1:\n post_gender.append('female')\n else:\n post_gender.append('female')\n if post_interest==6:\n post_gender.append('both')\n if post_interest==5:\n post_gender.append('male')\n if post_interest==4:\n post_gender.append('female')\n\n\n response_profile=select_profile_photo_info_for_user(photo_username)\n\n profile_location=response_profile[0]\n photo_location=profile_location[PHOTO_LOCATION]\n url_profile=s3.generate_presigned_url('get_object',\n Params={\n 'Bucket':'dongxuren1779a2',\n 'Key':photo_location,\n\n },\n ExpiresIn=3600)\n url_post_list=[]\n for index in response_photo:\n location=index[PHOTO_LOCATION]\n url=s3.generate_presigned_url('get_object',\n Params={\n 'Bucket':'dongxuren1779a2',\n 'Key':location,\n\n },\n ExpiresIn=3600)\n url_post_list.append(url)\n return render_template('browse.html',username=post_username,bio=post_bio,email=post_email,region=post_region,url_list=url_post_list,url_profile=url_profile,birthday=post_birth,post_gender=post_gender)\n","sub_path":"final_project/app/browse.py","file_name":"browse.py","file_ext":"py","file_size_in_byte":2643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"114530643","text":"\nimport numpy as np\nimport pickle\n\nvocab_size = 18794\nglove_path = \"glove.6B\\glove.6B.50d.txt\"\ntokenizer_path = \"glove_embedding/tokenizer.pkl\"\noutput_file_path = 'glove_embedding/embedding.npy'\noutput_dim = 50\n\nembeddings_index = dict()\nf = open( glove_path , encoding='utf8' )\nfor line in f:\n\tvalues = line.split()\n\tword = values[0]\n\tcoefs = np.asarray(values[1:], dtype='float32')\n\tembeddings_index[word] = coefs\nf.close()\n\ntokenizer = pickle.load( open( tokenizer_path , 'rb' ) )\n\nembedding_matrix = np.zeros((vocab_size, output_dim))\nfor word, i in tokenizer.word_index.items():\n\tembedding_vector = embeddings_index.get(word)\n\tif embedding_vector is not None:\n\t\tembedding_matrix[i] = embedding_vector\n\nnp.save( output_file_path , embedding_matrix )\n\n\n","sub_path":"GloVeProcessor.py","file_name":"GloVeProcessor.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"24344468","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom ep7.items import Ep7Item\n\n\nclass DbTop250Spider(scrapy.Spider):\n name = 'db_top250'\n allowed_domains = ['movie.douban.com']\n offset =0\n start_urls = ['https://movie.douban.com/top250?start=0&filter=']\n\n def parse(self, response):\n \n dot_list =response.xpath('//div[@class=\"item\"]')\n for each in dot_list:\n item =Ep7Item()\n item['title'] =each.xpath('.//span[@class=\"title\"][1]/text()')[0].extract().strip()\n item['rating_num'] =each.xpath('.//span[@class=\"rating_num\"]/text()')[0].extract().strip()\n item['people_num'] =each.xpath('.//span[4]/text()')[0].extract().strip()\n if len(each.xpath('.//p/span[contains(@class,\"inq\")]/text()').extract()) !=0:\n item['command'] =each.xpath('.//p/span[contains(@class,\"inq\")]/text()')[0].extract().strip()\n else:\n item['command'] =None\n item['text'] =str(each.xpath('.//div[@class=\"bd\"]/p[1]')[0].extract()).replace(' ','').replace('/','').replace('
','').replace('

','').replace('','').strip().replace('\\xa0','').replace('\\n','').replace('

','')\n \n yield item\n \n \n if self.offset<12:\n self.offset+=1\n yield(scrapy.Request('https://movie.douban.com/top250?start='+str(self.offset*25)+'&filter=',callback=self.parse))\n else:\n pass\n \n \n\n\n '''\n item['contury'] =text[-15:-10]\n item['kind'] =text[-13:]\n item['actor'] =re.findall(r'主演: [\\u4e00-\\u9fa5]+.[\\u4e00-\\u9fa5]+',text)\n item['dirctor'] =re.findall(r'导演: [\\u4e00-\\u9fa5]+.[\\u4e00-\\u9fa5]+',text)\n item['year'] =re.findall(r'\\d+',text)\n '''","sub_path":"py_scrapy_spider/ep7/ep7/spiders/db_top250.py","file_name":"db_top250.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"46419725","text":"# -*- coding: utf-8 -*-\nimport time\nimport scrapy\n\n\nclass MiddleSpider(scrapy.Spider):\n name = 'middle'\n allowed_domains = ['www.baidu.com']\n start_urls = ['https://www.baidu.com/']\n\n def parse(self, response):\n for i in range(20):\n time.sleep(0.1)\n\n print('>' * i)\n print('this is the output of parse()')\n","sub_path":"part_04.2_spider/scrapy_0/midwr_test/midwr_test/spiders/middle.py","file_name":"middle.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"306029296","text":"from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport re\n\npages=set()\ndef getlinks(url):\n html=urlopen(\"http://en.wikipedia.org\"+url)\n bsobj = BeautifulSoup(html, \"lxml\")\n try:\n print(bsobj.h1.get_text())\n print(bsobj.find(id=\"mw-content-text\").findAll(\"p\")[0])\n print(bsobj.find(id=\"ca-edit\").find(\"span\").find(\"a\").attrs[\"href\"])\n except AttributeError:\n print(\"lack few attribute\")\n for link in bsobj.find_all(\"a\",href=re.compile(\"^(/wiki/)\")): #((?!:).)*$\n if 'href' in link.attrs: # ^代表开始/wiki/ str:\n stk = []\n left = '('\n res = \"\"\n start = 0\n\n for i in range(len(S)):\n if S[i] == left:\n stk.append(left)\n else:\n stk.pop()\n\n if len(stk) == 0:\n res += S[start + 1: i]\n start = i + 1\n\n return res\n\n\nprint(removeOuterParentheses(\"(()())(())(()(()))\"))\n","sub_path":"栈/一般栈应用/1021. 删除最外层的括号.py","file_name":"1021. 删除最外层的括号.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"568169218","text":"import requests\n\n\ndef search_address(zipcode):\n response = requests.get(f'http://zipcloud.ibsnet.co.jp/api/search?zipcode={zipcode}')\n results = response.json()['results'][0]\n 都道府県名 = results['address1']\n 市区町村名 = results['address2']\n 町域名 = results['address3']\n address = f'{都道府県名}{市区町村名}{町域名}'\n return address\n\n\nif __name__ == '__main__':\n zipcode = '0287111'\n\n address = search_address(zipcode)\n\n assert '岩手県八幡平市大更' == address\n","sub_path":"surch_address.py","file_name":"surch_address.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"415024950","text":"\"\"\"OpenAPI core wrappers module\"\"\"\nfrom werkzeug.datastructures import ImmutableMultiDict\n\nfrom openapi_core.wrappers.base import BaseOpenAPIRequest, BaseOpenAPIResponse\n\n\nclass MockRequest(BaseOpenAPIRequest):\n\n def __init__(\n self, host_url, method, path, path_pattern=None, args=None,\n view_args=None, headers=None, cookies=None, data=None,\n mimetype='application/json'):\n self.host_url = host_url\n self.path = path\n self.path_pattern = path_pattern or path\n self.method = method.lower()\n\n self.parameters = {\n 'path': view_args or {},\n 'query': ImmutableMultiDict(args or []),\n 'header': headers or {},\n 'cookie': cookies or {},\n }\n\n self.body = data or ''\n\n self.mimetype = mimetype\n\n\nclass MockResponse(BaseOpenAPIResponse):\n\n def __init__(self, data, status_code=200, mimetype='application/json'):\n self.data = data\n\n self.status_code = status_code\n self.mimetype = mimetype\n","sub_path":"openapi_core/wrappers/mock.py","file_name":"mock.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"39248555","text":"import fullscreen\n\nfrom kivy.app import App\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.image import Image\nfrom kivy.uix.modalview import ModalView\nfrom kivy.uix.button import Button\nfrom kivy.uix.anchorlayout import AnchorLayout\nfrom kivy.core.window import Window\n\nfrom kivy.garden.iconfonts import *\n\nimport os\nfrom os.path import join, dirname\n\n\nclass ViewImage(ModalView):\n pass\n\n\nclass TestWindow(BoxLayout):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n self.images = self.get_imgs('img')\n self.imgs_show(self.images)\n\n def get_imgs(self, img_path):\n if not os.path.exists(img_path):\n print('invalid path')\n return -1\n else:\n all_file = os.listdir(img_path)\n imgs = []\n for f in all_file:\n if f.endswith('.png') or f.endswith('.jpg'):\n imgs.append('/'.join([img_path, f]))\n return imgs\n\n def imgs_show(self, imgs):\n base = self.ids.img_base\n base_data = []\n for img in imgs:\n im_name = img[img.rfind('/')+1:]\n if len(im_name) > 20:\n im_name = im_name[:18] + '...'\n base_data.append({'im_source': img, 'im_caption': im_name})\n base.data = base_data\n\n def get_image(self, im_path):\n self.ids.img_base.data = []\n self.images = [im_path]\n self.imgs_show(self.images)\n self.ids.scrn_mngr.current = 'scrn_media'\n self.ids.open_media.trigger = ''\n\n def get_folder(self, im_path):\n print(im_path)\n self.ids.img_base.data = []\n self.images = self.get_imgs(im_path)\n self.imgs_show(self.images)\n self.ids.scrn_mngr.current = 'scrn_media'\n\n def img_resize(self, img):\n im_size_x, im_size_y = img.texture_size\n ratio = im_size_x/im_size_y\n aspect = self.aspect_ratio(ratio, 50)\n\n while im_size_x >= Window.width or im_size_y >= Window.height:\n if im_size_x > im_size_y:\n im_size_x -= aspect[0]\n im_size_y -= aspect[1]\n else:\n im_size_y -= aspect[1]\n return [im_size_x, im_size_y]\n\n def aspect_ratio(self, val, lim):\n lower = [0, 1]\n upper = [1, 0]\n\n while True:\n mediant = [lower[0] + upper[0], lower[1] + upper[1]]\n\n if (val * mediant[1] > mediant[0]):\n if (lim < mediant[1]):\n return upper\n lower = mediant\n elif (val * mediant[1] == mediant[0]):\n if (lim >= mediant[1]):\n return mediant\n\n if (lower[1] < upper[1]):\n return lower\n\n return upper\n else:\n if (lim < mediant[1]):\n return lower\n upper = mediant\n\n def prev_im(self, inst):\n images = self.images\n cur_idx = None\n last_idx = len(images) - 1\n view_children = inst.parent.parent.parent.children\n cur_img = None\n image_container = None\n\n for child in view_children:\n if str(child).find('BoxLayout') > -1:\n image_container = child.children[0]\n cur_img = image_container.source\n for i, img in enumerate(images):\n if img == cur_img:\n cur_idx = i\n if cur_idx != 0:\n prev_img = images[cur_idx - 1]\n else:\n prev_img = images[last_idx]\n\n image_container.source = prev_img\n\n def next_im(self, inst):\n images = self.images\n cur_idx = None\n last_idx = len(images) - 1\n view_children = inst.parent.parent.parent.children\n cur_img = None\n image_container = None\n\n for child in view_children:\n if str(child).find('BoxLayout') > -1:\n image_container = child.children[0]\n cur_img = image_container.source\n\n for i, img in enumerate(images):\n if img == cur_img:\n cur_idx = i\n if cur_idx != last_idx:\n nxt_img = images[cur_idx + 1]\n else:\n nxt_img = images[0]\n\n image_container.source = nxt_img\n\n def viewimg(self, instance):\n im = Image(source=instance.im_source)\n view_size = self.img_resize(im)\n\n btn_prev = Button(text='%s'%(icon('zmdi-caret-left', 24)), markup=True)\n btn_prev.bind(on_release=self.prev_im)\n btn_rename = Button(text='%s'%(icon('zmdi-file', 24)), markup=True)\n btn_effects = Button(text='%s'%(icon('zmdi-blur-linear', 24)), markup=True)\n btn_next = Button(text='%s'%(icon('zmdi-caret-right', 24)), markup=True)\n btn_next.bind(on_release=self.next_im)\n\n image_ops = BoxLayout(size_hint=(None, None), size=(200, 30), spacing=4)\n\n image_ops.add_widget(btn_prev)\n image_ops.add_widget(btn_rename)\n image_ops.add_widget(btn_effects)\n image_ops.add_widget(btn_next)\n\n anchor = AnchorLayout(anchor_x='center', anchor_y='bottom')\n anchor.add_widget(image_ops)\n\n image_container = BoxLayout()\n\n view = ViewImage(size_hint=(None, None), size=view_size)\n image_container.add_widget(im)\n\n view.add_widget(image_container)\n view.add_widget(anchor)\n\n view.open()\n\n\nclass TestApp(App):\n def build(self):\n return TestWindow()\n\n\nif __name__ == \"__main__\":\n register('default_font', './assets/fonts/Material-Design-Iconic-Font.ttf', join(dirname(__file__), 'assets/fonts/zmd.fontd'))\n TestApp().run()\n","sub_path":"folder_test.py","file_name":"folder_test.py","file_ext":"py","file_size_in_byte":5622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"7174990","text":"#!/usr/bin/python3\nimport random\nimport urllib.request\nimport urllib.parse\nimport concurrent.futures\nfrom sys import exit\nfrom subprocess import check_call, CalledProcessError\n\nfit_home = 'http://binf1.memphis.edu/fitkids/'\nfit_tools = fit_home +'tools/'\ncache_dir = '/tmp/'\n\n# fitkids tools\nbmi_calcu = fit_tools + 'bmi_calculator/'\nassessment = fit_tools + 'fit_assessment/'\nmapit = fit_home + 'gis/'\ntagita = fit_tools + 'tagita/'\n\n# if a certain page is up\ndef ping_page(pageurl):\n try:\n response = urllib.request.urlopen(pageurl)\n return (True, None)\n except urllib.error.URLError as urlexception:\n return (False, urlexception.reason)\n\n# get a page cache\ndef curl_get(pageurl, cache_filename):\n curl_cmd = 'curl {} -s -o {}'.format(pageurl, cache_dir + cache_filename)\n try:\n check_call(curl_cmd.split())\n except CalledProcessError as curlerror:\n print (curlerror)\n exit(1)\n\ndef curl_post(pageurl, data, cache_filename):\n curl_cmd = 'curl --data {} {} -s -o {}'.format(data, pageurl, cache_filename)\n try:\n check_call(curl_cmd.split())\n except CalledProcessError as curlerror:\n print (curlerror)\n exit(1)\n\n# tool testing funcs\ndef test_bmi(tool_url):\n # entries in POST\n class bmi_POST:\n # append result generating script name\n entry_names = ['weight', 'height', 'age', 'gender', 'childname']\n def __init__(self):\n # 0+\n self.weight = 0\n # 0+\n self.height = 0\n # 3-20\n self.age = 0\n #'boy' 'girl'\n self.gender = None\n self.childname = 'binfbot'\n self.entries = {}\n\n def print_entries(self):\n print ('\\n')\n for entry in self.entries.items():\n print (entry)\n\n def fill_values(self):\n self.weight = random.randint(1, 300)\n self.height = random.randint(1, 100)\n self.age = random.randint(3, 20)\n self.gender = random.choice(['boy', 'girl'])\n self.entries = {'weight':self.weight, 'height':self.height, 'age':self.age, 'childname':self.childname}\n\n # generate post data\n post = bmi_POST()\n post.fill_values()\n post.print_entries()\n\n # post it and cache the result\n query_data = urllib.parse.urlencode(post.entries)\n result_page = tool_url + 'results.php'\n cache_name = cache_dir + 'fitkids_bmi_testcache.html'\n curl_post(result_page, query_data, cache_name)\n \n # TODO parse result and match with data posted\n\n\n\ndef test_assessment(tool_url):\n # entries in POST\n class fit_POST:\n entry_names = ['weight', 'height', 'age', 'gender', 'breakfast', 'fastfood', 'familyeat', 'childdrink', 'childdairy', 'milktype', 'fruit', 'sports', 'tv', 'active', 'bedroom', 'wakeup', 'mama_bear', 'childname']\n def __init__(self):\n self.weight = 0\n self.height = 0\n self.age = 0\n self.gender = None\n self.breakfast = 0\n self.fastfood = 0\n self.familyeat = 0\n self.childdrink = None\n self.childdairy = 0\n self.milktype = None\n self.fruit = None\n self.sports = 0\n self.tv = 0\n self.active = 0\n self.bedroom = None\n self.bedtime = 0\n self.wakeup = 0\n self.mama_bear = None\n self.childname = 'binfbot'\n self.entries = {}\n \n def fill_values(self):\n # 0+\n # 0+\n # 3-20\n #'boy' 'girl'\n # 0-7\n # 0:0-1, 1:2-4, else: 5+\n # 0+\n # 'yes' 'no'\n # 0+\n # 'skim' '1%' '2%' 'whole' 'none' else: non-dairy \n # 'yes' 'no'\n # 0:0-30, 1:30-60, else:60+\n # 0:0-2, else:3+\n # 0-7\n # 'yes' 'no'\n # -5-3\n # 5-10\n self.weight = random.randint(1, 300)\n self.height = random.randint(1, 100)\n self.age = random.randint(3, 20)\n self.gender = random.choice(['boy', 'girl'])\n self.breakfast = random.randint(0, 7)\n self.fastfood = random.randint(0, 2)\n self.familyeat = random.randint(0, 21)\n self.childdrink = random.choice(['yes','no'])\n self.childdairy = random.randint(0, 20)\n self.milktype = random.choice(['skim','1%','2%','whole','none'])\n self.fruit = random.choice(['yes', 'no'])\n self.sports = random.randint(0, 2)\n self.tv = random.randint(0, 1)\n self.active = random.randint(0, 7)\n self.bedroom = random.choice(['yes', 'no'])\n self.bedtime = random.randint(-5, 3)\n self.wakeup = random.randint(5, 10)\n self.entries = {'weight':self.weight, 'height':self.height, 'age':self.age, 'gender':self.gender, 'breakfast':self.breakfast, 'fastfood':self.fastfood, 'familyeat':self.familyeat, 'childdrink':self.childdrink, 'childdairy':self.childdairy, 'milktype':self.milktype, 'fruit':self.fruit, 'sports':self.sports, 'tv':self.tv, 'active':self.active, 'bedroom':self.bedroom, 'bedtime':self.bedtime,'wakeup':self.wakeup, 'mama_bear':self.mama_bear, 'childname':self.childname}\n\n def print_entries(self):\n print ('\\n')\n for entry in self.entries.items():\n print (entry)\n\n # generate post data\n post = fit_POST()\n post.fill_values()\n post.print_entries()\n\n # post it and cache the result\n query_data = urllib.parse.urlencode(post.entries)\n result_page = tool_url + 'results.php'\n cache_name = cache_dir + 'fitkids_assessment_testcache.html'\n curl_post(result_page, query_data, cache_name)\n \n # TODO parse result and match with data posted\n\ndef test_mapit(tool_url):\n pass\n\ndef test_tagita(tool_url):\n pass\n\n# organize tool testing funcs\nclass tool_tester:\n def __init__(self):\n self.tools = [bmi_calcu, assessment]\n self.tests = [test_bmi, test_assessment]\n # key: tool_url, value: test_func\n self.suites = { k:v for (k,v) in zip(self.tools, self.tests)}\n\n def run_test(self, tool_url):\n test_func = self.suites[tool_url]\n test_func(tool_url)\n\n def run_all_tests(self):\n with concurrent.futures.ThreadPoolExecutor(max_workers=len(self.tools)) as tester:\n # a dictionary where key: func exectution, value: func args\n futures = dict( (tester.submit(v, k), k) for k, v in self.suites.items() )\n\n for future in concurrent.futures.as_completed(futures):\n tool_url = futures[future]\n if future.exception() is not None:\n print ('Exception %s when testing %s' % (future.exception(), tool_url))\n else:\n print ('Test finish on %s' % tool_url)\n\n\n# test user register and login\nclass account_tester:\n def __init__(self):\n pass\n\nif __name__=='__main__':\n #result = ping_page(fit_home)\n #print (result)\n #curl_get(fit_home, 'fitkids_testcache.html')\n \n toolbot = tool_tester()\n toolbot.run_all_tests()\n\n #for tool in toolbot.tools:\n # toolbot.run_test(tool)\n\n #for suite in toolbot.suites.items():\n # print (suite)\n #test_bmi(bmi_calcu)\n #test_assessment(assessment)\n\n","sub_path":"test_fitkids/draft/testfitkids.py","file_name":"testfitkids.py","file_ext":"py","file_size_in_byte":7418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"123892406","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Dec 5 14:10:04 2020\n\n@author: tonedogga\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport os\nfrom pathlib import Path\nfrom p_tqdm import p_map,p_umap\n\nimport pyglet\nfrom pyglet import clock\nfrom pyglet import gl\nfrom pyglet.gl import *\n\nfrom pyglet.window import key\nfrom pyglet.window import mouse\n\nfrom pyglet import shapes\n\n\n\n#from time import time\n\nMY_DEBUG=True #False\nBUTTON_LIST=[]\n#BUTTON_COLOR=(200,100,200)\n#global batch\n\n\n#########################################################################################################################\n\n\n\n\nclass QueryWindow(pyglet.window.Window):\n def __init__(self,*args,**kwargs):\n # super(MyWindow,self).__init__(*args,**kwargs)\n super(QueryWindow,self).__init__(*args,**kwargs)\n \n #set window size\n self.set_minimum_size(700,700)\n self.set_maximum_size(2048, 2048)\n \n # get window size\n self.x_max=self.get_size()[0]\n self.y_max=self.get_size()[1]\n\n # draw_buttons_to_batch()\n \n #print(self.get_size())\n \n # get window location\n #x, y = window.get_location()\n #window.set_location(x + 20, y + 20) \n \n # button_list is global \n \n # buttons=get_button_details()\n \n \n \n def on_key_press(self, symbol, modifiers):\n if symbol == key.A:\n if MY_DEBUG:\n # print('The \"A\" key was pressed.')\n text='The \"A\" key was pressed.'\n _display_text_in_active_window(text)\n # self.window.set_visible()\n elif symbol == key.LEFT:\n if MY_DEBUG:\n text='The left arrow key was pressed.'\n# print('The left arrow key was pressed.')\n _display_text_in_active_window(text)\n elif symbol == key.ENTER:\n if MY_DEBUG:\n text='The enter key was pressed.'\n # print('The enter key was pressed.')\n _display_text_in_active_window(text)\n\n \n \n \n def on_key_release(self, symbol, modifiers):\n pass\n \n \n def on_mouse_enter(self,x, y):\n pass\n\n def on_mouse_leave(self,x, y):\n pass\n \n def on_mouse_motion(self,x, y, dx, dy):\n # fps_display.draw()\n # batch=check_for_collisions(x,y)\n move_and_draw_pointer(x,y,dx,dy)\n \n def on_mouse_press(self,x,y,button, modifiers):\n if button == mouse.LEFT:\n # canvas={}\n # print('The left mouse button was pressed. x=',x,\"y=\",y)\n # batch=_check_for_collisions(x,y,batch)\n # if MY_DEBUG:\n # text=\"the left mouse button was pressed. x=\"+str(x)+\" y=\"+str(y)\n # _display_text_in_active_window(text)\n for b in BUTTON_LIST:\n if (b.active & b.visible & (x>=b.x_start) & (x<(b.x_start+b.x_len)) & (y>=b.y_start) & (y<(b.y_start+b.y_len))):\n b.pushed=not b.pushed\n #batch=display_buttons(batch) \n\n\n\n\n elif button == mouse.RIGHT:\n # print('The right mouse button was pressed.')\n if MY_DEBUG:\n text=\"the right mouse button was pressed. x=\"+str(x)+\" y=\"+str(y)\n\n _display_text_in_active_window(text)\n \n \n \n def on_mouse_release(self,x, y, button, modifiers):\n pass\n\n\n def on_mouse_drag(self,x, y, dx, dy, buttons, modifiers):\n if buttons & mouse.LEFT:\n if MY_DEBUG:\n text=\"mouse drag left x,y,dx,dy\"+str(x)+\" \"+str(y)+\" \"+str(dx)+\" \"+str(dy)\n _display_text_in_active_window(text)\n # print(text)\n elif buttons & mouse.RIGHT:\n if MY_DEBUG:\n text=\"mouse drag right x,y,dx,dy\"+str(x)+\" \"+str(y)+\" \"+str(dx)+\" \"+str(dy)\n _display_text_in_active_window(text)\n # print(text)\n \n \n\n \n def on_mouse_scroll(self,x, y, scroll_x, scroll_y):\n if MY_DEBUG:\n text=\"mouse scroll x,y,scroll_x,scroll_y\"+str(x)+\" \"+str(y)+\" \"+str(scroll_x)+\" \"+str(scroll_y)\n _display_text_in_active_window(text)\n\n \n \n\n def on_draw(self): \n #self.clear()\n \n draw_buttons()\n # check_for_collisions(x,y)\n pass\n \n \n \n # def on_resize(self,width, height):\n # print('The window was resized to %dx%d' % (width, height))\n # display = pyglet.canvas.Display()\n # screen = display.get_default_screen()\n # self.screen_width = screen.width\n # self.screen_height = screen.height\n\n # self.clear()\n # pass\n \n def update(self,dt):\n # display_buttons()\n #draw_batch(x,y,dx,dy)\n # window.clear()\n pass\n\n \n#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\nclass sales_trans(object):\n def __init__(self):\n self.sales_df_dict={\n \"cat\":True,\n \"code\":True,\n \"costval\":False,\n \"doctype\":False,\n \"docentryno\":False,\n \"linenumber\":False,\n \"location\":True,\n \"product\":True,\n \"productgroup\":True,\n \"qty\":False,\n \"refer\":False,\n \"salesrep\":True,\n \"saleval\":False,\n \"territory\":False,\n \"date\":False,\n \"glset\":True,\n \"specialpricecat\":True,\n \"period\":False}\n \n \n def load_pickle(self,save_dir,savefile):\n # os.makedirs(save_dir, exist_ok=True)\n my_file = Path(save_dir+savefile)\n if my_file.is_file():\n return pd.read_pickle(save_dir+savefile)\n else:\n print(\"load sales_df error.\")\n return\n \n \n\n def find_uniques(self,sales_df):\n unique_dict={}\n for k,v in self.sales_df_dict.items():\n if v:\n unique_dict[k]=sorted(pd.Series(sales_df[k]).astype(str).unique())\n \n return unique_dict\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\nconfig = pyglet.gl.Config(double_buffer=True) \nwindow = QueryWindow(1200,1200,resizable=False,caption=\"Salestrans Queries\",config=config,visible=True)\n#canvas={}\n#batch = pyglet.graphics.Batch()\n\n#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# define and make live areas on window as pushable buttons\n\nclass query_window_object(object):\n def __init__():\n pass\n\n\n\nclass button_object(query_window_object):\n def __init__(self,*,name,x_start,x_len,y_start,y_len,colour,pushed_colour,title,active,visible,pushed,toggle,unique_list):\n # super().__init__()\n self.name=name\n self.x_start=x_start\n self.x_len=x_len\n self.y_start=y_start\n self.y_len=y_len\n self.colour=colour\n self.inactive_colour=(40,50,60)\n self.pushed_colour=pushed_colour\n self.title=title\n self.active=active\n self.visible=visible\n self.pushed=pushed\n self.toggle=toggle\n self.unique_list=unique_list\n # self.button_array=button_array\n # self.button_df=button_df.copy()\n \n \n \nclass buttons(object):\n def setup_buttons(self,filename,sales_df_dict,unique_dict):\n bdf=pd.read_csv(filename,index_col=False,header=0)\n \n for index, row in bdf.iterrows():\n colour=(int(row['colour1']),int(row['colour2']),int(row['colour3']))\n pushed_colour=(int(row['pcolour1']),int(row['pcolour2']),int(row['pcolour3']))\n button=button_object(name=str(row['name']),x_start=int(row['x_start']),x_len=int(row['x_len']),y_start=int(row['y_start']),y_len=int(row['y_len']),colour=colour,pushed_colour=pushed_colour,title=str(row['title']),active=bool(row['active']),visible=bool(row['visible']),pushed=bool(row['pushed']),toggle=bool(row['toggle']),unique_list=[]) \n BUTTON_LIST.append(button)\n \n x_start=0 \n y_start=990\n for fields,values in sales_df_dict.items():\n if values:\n colour=(200,200,200) #int(row['colour1']),int(row['colour2']),int(row['colour3']))\n pushed_colour=(100,100,100) #int(row['pcolour1']),int(row['pcolour2']),int(row['pcolour3']))\n button=button_object(name=str(fields),x_start=x_start,x_len=10,y_start=y_start,y_len=30,colour=colour,pushed_colour=pushed_colour,title=str(fields),active=True,visible=True,pushed=False,toggle=True,unique_list=unique_dict[fields]) \n x_start+=50\n y_start-=10\n BUTTON_LIST.append(button)\n \n self._resize_buttons(window.x_max,window.y_max)\n \n return BUTTON_LIST\n \n \n \n def _resize_buttons(self,x_max,y_max):\n # batch = pyglet.graphics.Batch()\n for button in BUTTON_LIST: \n if button.x_start<0:\n button.x_start=0\n if button.x_start>x_max:\n button.x_start=x_max\n if button.y_start<0:\n button.y_start=0\n if button.y_start>y_max:\n button.y_start=y_max\n \n \n if button.x_len<0:\n button.x_len=0\n if button.x_len>x_max:\n button.x_len=x_max\n if button.y_len<0:\n button.y_len=0\n if button.y_len>y_max:\n button.y_len=y_max\n \n \n if button.x_start+button.x_len>x_max:\n button.x_len=x_max-button.x_start\n \n if button.y_start+button.y_len>y_max:\n button.y_len=y_max-button.y_start\n\n \n \n \n \n#-------------------------------------------------------------------------------------------------------------------------\n\n\n\ndef check_for_collisions(x,y):\n # print(\"button object check for collissions\",x,y)\n # if x,y is over any button display on screen\n # button list is global\n# over_button=[]\n batch = pyglet.graphics.Batch()\n# batch=p_map(_check_button,BUTTON_LIST)\n for b in BUTTON_LIST:\n #b.active\n if (b.visible & b.active & (x>=b.x_start) & (x<(b.x_start+b.x_len)) & (y>=b.y_start) & (y<(b.y_start+b.y_len))):\n# position_text_in_active_window(b.name+\"\\nActive=\"+str(b.active)+\"\\nVisible=\"+str(b.visible)+\" Pushed=\"+str(b.pushed)+\" list=\"+str(b.unique_list),x=x,y=y)\n position_text_in_active_window(b.name+\"\\nActive=\"+str(b.active)+\"\\nVisible=\"+str(b.visible)+\" Pushed=\"+str(b.pushed),x=x,y=y)\n\n # over_button.append(True)\n # else:\n # over_button.append(False)\n # print(\"button cooll\",b.name,x,y)\n batch.draw() \n # return batch \n # return any(over_button),batch \n \n#def _check_button(b):\n# if (b.visible & b.active & (x>=b.x_start) & (x<(b.x_start+b.x_len)) & (y>=b.y_start) & (y<(b.y_start+b.y_len))):\n# position_text_in_active_window(b.name+\"\\nActive=\"+str(b.active)+\"\\nVisible=\"+str(b.visible)+\" Pushed=\"+str(b.pushed)+\" len=\"+str(b.unique_list_len),x=x,y=y)\n# return batch\n\n\n \ndef draw_buttons():\n batch = pyglet.graphics.Batch()\n for b in BUTTON_LIST:\n if b.visible:\n batch=_draw_button(b,batch)\n batch.draw() \n #return batch \n\n\n \n \n \n \ndef _draw_button(button,batch): \n if button.active:\n position_text_in_active_window(button.title,x=button.x_start+10,y=button.y_start+button.y_len-20)\n if not button.pushed:\n # batch=_draw_rect(button.x_start,button.x_len,button.y_start,button.y_len,colour=button.colour,batch=batch)\n _draw_solid_rect(button.x_start,button.y_start,button.x_len,button.y_len,colour=button.colour,batch=batch)\n\n else: \n # batch=_draw_rect(button.x_start,button.x_len,button.y_start,button.y_len,colour=button.pushed_colour,batch=batch)\n _draw_solid_rect(button.x_start,button.y_start,button.x_len,button.y_len,colour=button.pushed_colour,batch=batch)\n \n else:\n # batch=_draw_rect(button.x_start,button.x_len,button.y_start,button.y_len,colour=button.inactive_colour,batch=batch) \n _draw_solid_rect(button.x_start,button.y_start,button.x_len,button.y_len,colour=button.inactive_colour,batch=batch) \n return batch \n \n \n \n \ndef _draw_rect(x,x_len,y,y_len,colour,batch):\n final_colour=colour+colour\n # print(\"final colour=\",final_colour)\n batch.add(2, pyglet.gl.GL_LINES, None,\n ('v2i', (x, y, x+x_len, y)), \n ('c3B', final_colour)\n )\n batch.add(2, pyglet.gl.GL_LINES, None,\n ('v2i', (x+x_len, y, x+x_len, y+y_len)), \n ('c3B', final_colour)\n )\n batch.add(2, pyglet.gl.GL_LINES, None,\n ('v2i', (x+x_len, y+y_len, x, y+y_len)), \n ('c3B', final_colour)\n )\n batch.add(2, pyglet.gl.GL_LINES, None,\n ('v2i', (x, y+y_len, x, y)), \n ('c3B', final_colour)\n )\n \n # batch.add(4, GL_QUADS, None, 'v2f', 't2f')\n # batch.add(4, pyglet.gl.GL_RECTS, None,\n # ('v2i', (x, y, x+x_len, y)), \n # ('t2i', (x,y+y_len, x+x_len,y+y_len))\n \n # )\n # batch.add(2, pyglet.gl.GL_LINES, None,\n # ('v2i', (x+x_len, y, x+x_len, y+y_len)), \n # ('c3B', final_colour)\n # )\n # batch.add(2, pyglet.gl.GL_LINES, None,\n # ('v2i', (x+x_len, y+y_len, x, y+y_len)), \n # ('c3B', final_colour)\n # )\n # batch.add(2, pyglet.gl.GL_LINES, None,\n # ('v2i', (x, y+y_len, x, y)), \n # ('c3B', final_colour)\n # )\n \n return batch\n \n \n \n \n \n \ndef _draw_solid_rect(x,y,x_len,y_len,colour,batch):\n # final_colour=colour+colour\n \n \n rectangle = shapes.Rectangle(x, y, x_len, y_len, color=colour, batch=batch)\n rectangle.opacity = 128\n rectangle.rotation = 0\n \n batch.draw()\n# # print(\"final colour=\",final_colour)\n \n \n# # circle = shapes.Circle(700, 150, 100, color=(50, 225, 30), batch=batch)\n# square = shapes.Rectangle(200, 200, 200, 200, color=(55, 55, 255), batch=batch)\n# rectangle = shapes.Rectangle(250, 300, 400, 200, color=(255, 22, 20), batch=batch)\n# rectangle.opacity = 128\n# rectangle.rotation = 33\n# line = shapes.Line(100, 100, 100, 200, width=19, batch=batch)\n# line2 = shapes.Line(150, 150, 444, 111, width=4, color=(200, 20, 20), batch=batch)\n \n \n \n \n# def draw_pointers(x,y):\n# batch = pyglet.graphics.Batch()\n# batch.add(2, pyglet.gl.GL_LINES, None,\n# ('v2i', (0, 0, x, y)), \n# ('c3B', (255, 0, 0, 255, 255, 255))\n# )\n \n# batch.add(2, pyglet.gl.GL_LINES, None,\n# ('v2i', (0, window.get_size()[1], x, y)), \n# ('c3B', (0, 255, 0, 255, 255, 255))\n# )\n \n# batch.add(2, pyglet.gl.GL_LINES, None,\n# ('v2i', (window.get_size()[0],0, x, y)), \n# ('c3B', (0, 0, 255, 255, 255, 255))\n# )\n\n# batch.add(2, pyglet.gl.GL_LINES, None,\n# ('v2i', (window.get_size()[0], window.get_size()[1], x, y)), \n# ('c3B', (60, 70, 20, 255, 255, 255))\n# )\n# batch.draw() \n# # return batch \n \n \n \ndef draw_pointers(x,y,x_max,y_max):\n batch = pyglet.graphics.Batch()\n # batch.add(2, pyglet.gl.GL_LINES, None,\n # ('v2i', (0, 0, x, y,0,y_max)),\n # ('v2i', (x_max,0, x, y,x_max,y_max)), \n # ('c3B', (255, 0, 0, 255, 255, 255))\n # )\n batch.add(2, pyglet.gl.GL_LINES, None,\n ('v2i', (0, 0, x, y)), \n ('c3B', (255, 0, 0, 255, 255, 255))\n )\n\n batch.add(2, pyglet.gl.GL_LINES, None,\n ('v2i', (0, y_max, x, y)), \n ('c3B', (0, 255, 0, 255, 255, 255))\n )\n \n batch.add(2, pyglet.gl.GL_LINES, None,\n ('v2i', (x_max,0, x, y)), \n ('c3B', (0, 0, 255, 255, 255, 255))\n )\n\n batch.add(2, pyglet.gl.GL_LINES, None,\n ('v2i', (x_max, y_max, x, y)), \n ('c3B', (60, 70, 20, 255, 255, 255))\n )\n batch.draw() \n # return batch \n \n \n \n \n \n \n#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ \n\n\n \n\ndef position_text_in_active_window(text,*,x,y):\n batch = pyglet.graphics.Batch()\n # canvas={}\n # canvas[1] = pyglet.text.Label(text, x=x, y=y, batch=batch)\n pyglet.text.Label(text, x=x, y=y, batch=batch)\n batch.draw()\n # return batch\n\n\n\ndef _display_text_in_active_window(text):\n batch = pyglet.graphics.Batch()\n # canvas={}\n # canvas[1] = pyglet.text.Label(text, x=x, y=y, batch=batch)\n pyglet.text.Label(text, x=5, y=window.get_size()[1]-12, batch=batch)\n # window.clear()\n batch.draw()\n \n\n\n\ndef move_and_draw_pointer(x,y,dx,dy):\n \n # batch = pyglet.graphics.Batch()\n window.clear()\n # draw_buttons()\n draw_pointers(x,y,window.x_max,window.y_max)\n check_for_collisions(x,y)\n clock.tick()\n if MY_DEBUG:\n position_text_in_active_window(\"fps=\"+str(int(clock.get_fps()))+\" size=\"+str(window.get_size())+\" loc=\"+str(window.get_location())+\" Pos=(\"+str(x)+\",\"+str(y)+\") dx=(\"+str(dx)+\",\"+str(dy)+\")\",x=0,y=5)\n # batch=draw_buttons_to_batch(x_max=window.x_max,y_max=window.y_max,batch=batch)\n # window.clear()\n # batch.draw() \n # for index in list(canvas):\n # canvas[index].delete()\n # del(canvas[index])\n\n\n#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n\n\ndef main():\n os.chdir(\"/home/tonedogga/Documents/python_dev\")\n st=sales_trans()\n sales_df=st.load_pickle(\"./dash2_saves/\",\"raw_savefile.pkl\")\n # print(sales_df.info(),sales_df.shape)\n unique_dict=st.find_uniques(sales_df)\n # print(\"unuqie dict\",unique_dict)\n \n \n b=buttons()\n BUTTON_LIST=b.setup_buttons('./dash2/buttons.csv',st.sales_df_dict,unique_dict)\n # print(\"button_list length=\",len(BUTTON_LIST))\n # batch = pyglet.graphics.Batch()\n # batch=display_buttons(batch)\n # window.clear()\n # batch.draw()\n\n pyglet.app.run()\n window.close()\n\n\nmain()\n\n\n #x, y = window.get_location()\n #window.set_location(x + 20, y + 20)\n \n \n #window = MyWindow(1200,1200,resizable=True,caption=\"Queries\",visible=True)\n \n #pyglet.clock.schedule_interval(draw_batch, 1.0/60.0)\n #window.switch_to()\n # signify that one frame has passed\n #pyglet.clock.tick()\n # poll the operating system event queue\n #window.dispatch_events()\n \n # getting window size \n #value = window.get_size() \n #window.activate() \n \n\n \n \n ","sub_path":"pyglet_queries2.py","file_name":"pyglet_queries2.py","file_ext":"py","file_size_in_byte":19705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"383378145","text":"import os\nimport tensorflow as tf\nimport numpy as np\nimport data_helpers\nimport gensim\nfrom gensim.models.word2vec import Word2Vec\n\nprint(\"Loading data...\")\nx_text, y = data_helpers.load_data_and_labels(\"./data/rt-polaritydata/rt-polarity.pos\", \"./data/rt-polaritydata/rt-polarity.neg\")\n#w2vec_model = Word2Vec.load('./data/GoogleNews-vectors-negative300.bin')\nw2vec_model = gensim.models.KeyedVectors.load_word2vec_format('./data/GoogleNews-vectors-negative300.bin', binary=True)\nembedding_size = w2vec_model.vector_size\nsequence_length = max([len(x.split(\" \")) for x in x_text])\nnum_classes = 2\n\nx = np.zeros((len(x_text), sequence_length, embedding_size), dtype=float)\nfor i,xi in enumerate(x_text):\n tokens = xi.split(' ')\n for j,token in enumerate(tokens):\n if token in w2vec_model.vocab:\n x[i,j] = w2vec_model[token]\n\n# Randomly shuffle data\nnp.random.seed(10)\nshuffle_indices = np.random.permutation(np.arange(len(y)))\nx_shuffled = x[shuffle_indices]\ny_shuffled = y[shuffle_indices]\n\n# Split train/test set\ndev_sample_index = -1 * int(.1 * float(len(y)))\nx_train, x_dev = x_shuffled[:dev_sample_index], x_shuffled[dev_sample_index:]\ny_train, y_dev = y_shuffled[:dev_sample_index], y_shuffled[dev_sample_index:]\n\ndel x, y, x_shuffled, y_shuffled, w2vec_model\n\nprint(\"Train/Dev split: {:d}/{:d}\".format(len(y_train), len(y_dev)))\n\n\n######################## TensorFlow Graph 구성\n\n# 값 초기화\n\nfilter_sizes = [3,4,5]\nnum_filters = 8\ndropout_keep_prob = 0.5\nnum_epoch = 30\nbatch_size = 100\n\n# X, Y 정의\ninput_x = tf.placeholder(tf.float32, [None, sequence_length, embedding_size], name='input_x')\ninput_y = tf.placeholder(tf.float32, [None, num_classes], name=\"input_y\")\n\n\nextended_input_x = tf.expand_dims(input_x, -1)\n\n# Convolution and Max-Pooling\npooled_outputs = []\nfor i, filter_size in enumerate(filter_sizes):\n filter_shape = [filter_size, embedding_size, 1, num_filters]\n W_c = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name=\"W_c\")\n conv = tf.nn.conv2d(\n extended_input_x,\n W_c,\n strides=[1, 1, 1, 1],\n padding=\"VALID\",\n name=\"conv\")\n h = tf.nn.relu(conv, name=\"relu_c\")\n pooled = tf.nn.max_pool(\n h,\n ksize=[1, sequence_length - filter_size + 1, 1, 1],\n strides=[1, 1, 1, 1],\n padding='VALID',\n name=\"pool\")\n pooled_outputs.append(pooled)\n\n# Flatten and Dropout\nnum_filters_total = num_filters * len(filter_sizes)\nh_pool = tf.concat(pooled_outputs, 3)\nh_pool_flat = tf.reshape(h_pool, [-1, num_filters_total])\nh_drop = tf.nn.dropout(h_pool_flat, dropout_keep_prob)\n\n# Final Fully Connected Layer\nW_f = tf.get_variable(\n \"W_f\",\n shape=[num_filters_total, num_classes],\n initializer=tf.contrib.layers.xavier_initializer())\nb_f = tf.Variable(tf.constant(0.1, shape=[num_classes]), name=\"b_f\")\nscores = tf.nn.xw_plus_b(h_drop, W_f, b_f, name=\"scores\")\npredictions = tf.argmax(scores, 1, name=\"predictions\")\n\n#loss\nloss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=scores, labels=input_y))\n\n#accuracy\ncorrect_predictions = tf.equal(predictions, tf.argmax(input_y, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_predictions, \"float\"))\n\n#optimizer\noptimizer = tf.train.AdamOptimizer(1e-3).minimize(loss)\n\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\n\ntotal_len = len(x_train)\nfor epoch in range(num_epoch):\n avg_loss = 0\n avg_acc = 0\n total_batch = int(total_len/batch_size)\n for i in range(total_batch):\n st = i*batch_size\n en = min((i+1)*batch_size,total_len)\n\n batch_xs = x_train[st:en]\n batch_ys = y_train[st:en]\n\n feed_dict = {input_x:batch_xs, input_y:batch_ys}\n\n acc, l, _ = sess.run([accuracy,loss, optimizer], feed_dict=feed_dict)\n\n avg_loss += l / total_batch\n avg_acc += acc / total_batch\n\n print('Epoch:', '%03d' % (epoch + 1), 'loss =', '{:.6f}'.format(avg_loss), 'accuracy =', '{:.6f}'.format(avg_acc))\n\nfeed_dict = {input_x:x_dev, input_y:y_dev}\n\nacc = sess.run(accuracy, feed_dict=feed_dict)\nprint ('Test Accuraacy : ', acc)","sub_path":"simple_cnn.py","file_name":"simple_cnn.py","file_ext":"py","file_size_in_byte":4138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"86410921","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/djutils/json_utils.py\n# Compiled at: 2015-06-22 10:37:13\nimport json\nfrom collections import OrderedDict\nfrom django.forms import model_to_dict\nfrom django.core.serializers.json import DjangoJSONEncoder\n\ndef object_to_json(obj, indent=2):\n \"\"\"\n transform object to json\n \"\"\"\n instance_json = json.dumps(obj, indent=indent, ensure_ascii=False, cls=DjangoJSONEncoder)\n return instance_json\n\n\ndef model_to_json(model_instance):\n \"\"\"\n transform instance to json\n \"\"\"\n instance_dict = model_to_dict(model_instance)\n return object_to_json(instance_dict)\n\n\ndef qs_to_json(qs, fields=None):\n \"\"\"\n transform QuerySet to json\n \"\"\"\n if not fields:\n fields = [ f.name for f in qs.model._meta.fields ]\n objects = []\n for value_dict in qs.values(*fields):\n o = OrderedDict()\n for f in fields:\n o[f] = value_dict[f]\n\n objects.append(o)\n\n json_qs = json.dumps(objects, indent=2, ensure_ascii=False, cls=DjangoJSONEncoder)\n return json_qs\n\n\ndef mongoqs_to_json(qs, fields=None):\n \"\"\"\n transform mongoengine.QuerySet to json\n \"\"\"\n l = list(qs.as_pymongo())\n for element in l:\n element.pop('_cls')\n\n json_qs = json.dumps(l, indent=2, ensure_ascii=False, cls=DjangoJSONEncoder)\n return json_qs","sub_path":"pycfiles/sw_django_utils-0.0.50-py2.7/json_utils.py","file_name":"json_utils.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"448480678","text":"from setuptools import setup\n\npackage = \"pycassos\"\nversion = \"0.0.1\"\n\nsetup(name = package,\n version = version,\n description=\"Python Caviar Solutions Software suite\",\n url='https://github.com/dicaso/pycassos',\n author = 'Christophe Van Neste',\n author_email = 'christophe.vanneste@ugent.be',\n license = 'MIT',\n packages = ['pycassos'],\n python_requires='>3.6',\n install_requires = [\n # dicaso packages\n 'leopard',\n 'genairics',\n 'bidali[retro]',\n 'pyni',\n # console packages\n 'ipython',\n # server packages\n 'flask',\n 'flask-login',\n 'flask-jsonpify',\n 'flask-mongoengine',\n #'flask-sqlalchemy',\n 'flask-restful',\n 'mpld3'\n ],\n extras_require = {\n 'development': ['twine','Sphinx']\n },\n package_data = {\n },\n include_package_data = True,\n zip_safe = False,\n entry_points = {\n 'console_scripts': ['pycassos=pycassos.__main__:main'],\n },\n test_suite = 'nose.collector',\n tests_require = ['nose']\n)\n\n#To install with symlink, so that changes are immediately available:\n#pip install -e .\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"334080751","text":"#!/usr/bin/env python\nfrom flask import Flask, flash, redirect, render_template, \\\n request, url_for\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return render_template(\n 'select_menu.html',\n data=[{'name':'red'}, {'name':'green'}, {'name':'blue'}])\n\n@app.route(\"/test\" , methods=['GET', 'POST'])\ndef test():\n if request.method == 'POST':\n select = request.form.get('comp_select')\n return ' {0} '.format(str(select))\n return redirect(url_for('index'))\n \n\nif __name__=='__main__':\n app.run(debug=True, port=2745)","sub_path":"ElementsAutourDeFlask/selectmenu.py","file_name":"selectmenu.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"600205684","text":"def cfginfinite(grammar):\n for Q in [rule[0] for rule in grammar]:\n def helper(current, visited, sizexy):\n if current in visited:\n return sizexy > 0\n else:\n new_visited = visited + [current]\n for rhs in [rule[1] for rule in grammar if rule[0] == current]:\n for symbol in rhs:\n if helper(symbol, new_visited, sizexy + len(rhs) - 1):\n return True\n return False\n\n if helper(Q, [], 0):\n return True\n return False\n","sub_path":"exercise/L01-03/cfginfinite.py","file_name":"cfginfinite.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"71275285","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Feb 14 15:22:02 2019\r\n\r\n@author: kna016\r\nScript to create 'iveg' and 'patchfrac' information for OzFLUX site-level runs in CABLE\r\nFeb. 2019: extended to read C4 fraction as well and append them to sitelist\r\n\"\"\"\r\n\r\nimport pandas as pd # dataframes\r\nimport numpy as np # multi-dimensional arrays\r\n\r\n\r\n## Options\r\nuse_site_years = False # use site years (True) or long-term climatologies (False)\r\nfrac_max = True # derive forest fraction from max. forest fraction (rest is grass)?\r\n\r\n\r\nbasepath='C:/Users/kna016/Documents/CABLE/'\r\n\r\n\r\n## 1) load dataframe containing vegfract timeseries and site list\r\nfcover = pd.read_csv(basepath + 'cover_fract/ozflux28.gimms3g_fcovfperfrec.csv',index_col='PointName')\r\nC4fraction = pd.read_csv(basepath + 'cover_fract/ozflux28.c4_grass_frac_cov.csv',index_col='PointName')\r\nsitelist = pd.read_csv(basepath + 'OzFLUX_sitelist_v2.txt',sep='\\t',index_col=0) \r\n\r\n\r\n## 2) extract fcover climatology information\r\n#clims_index = [k for k, i in enumerate(fcover.index) if '9999' in i]\r\n#fcover_climatology = fcover.iloc[clims_index,:]\r\nfcov_index = [k for k, i in enumerate(fcover.index) if '9999' in i and 'fcov' in i]\r\nfper_index = [k for k, i in enumerate(fcover.index) if '9999' in i and 'fper' in i]\r\nfrec_index = [k for k, i in enumerate(fcover.index) if '9999' in i and 'frec' in i]\r\n\r\n\r\n## 3) extract vegetation cover for each site\r\nfrac_forest = []\r\nfrac_grass = []\r\nfrac_C4 = []\r\n\r\n\r\nfor s,site in enumerate(sitelist.index):\r\n \r\n print('starting site ' + site)\r\n \r\n if use_site_years:\r\n \r\n print('not yet implemented!')\r\n\r\n# startyear = sitelist.loc[site,'startyear']\r\n# endyear = sitelist.loc[site,'endyear']\r\n# \r\n# #fcover[0,site]\r\n# dates=fcover.index.tolist()\r\n# index=[]\r\n# for year in range(startyear,endyear):\r\n# index.append([k for k, i in enumerate(dates) if 'fcov' in i and str(year) in i])\r\n \r\n else: \r\n \r\n# fcov.append(round(fcover.iloc[fcov_index,s].mean(),3))\r\n# fper.append(round(fcover.iloc[fper_index,s].mean(),3))\r\n# frec.append(round(fcover.iloc[frec_index,s].mean(),3))\r\n\r\n \r\n if frac_max:\r\n \r\n frac_forest.append(fcover.iloc[fper_index,s].max())\r\n frac_grass.append(1.0 - frac_forest[-1])\r\n \r\n \r\n else:\r\n \r\n fcov_site = fcover.iloc[fcov_index,s]\r\n fper_site = fcover.iloc[fper_index,s]\r\n frec_site = fcover.iloc[frec_index,s]\r\n \r\n \r\n frac_forest.append((np.array(fper_site) / np.array(fcov_site)).mean())\r\n frac_grass.append((np.array(frec_site) / np.array(fcov_site)).mean())\r\n \r\n\r\n frac_C4.append(C4fraction.iloc[3,s])\r\n \r\n \r\n \r\n \r\n \r\n## ensure that forest and grass fractions sum up to 1\r\nif frac_max==False:\r\n diff = (np.array(frac_forest) + np.array(frac_grass)) - 1.0\r\n \r\n frac_forest = frac_forest - diff*frac_forest\r\n frac_grass = frac_grass - diff*frac_grass\r\n \r\n diff = (np.array(frac_forest) + np.array(frac_grass)) - 1.0\r\n \r\n frac_forest = frac_forest - diff*frac_forest\r\n frac_grass = frac_grass - diff*frac_grass\r\n\r\n\r\nfrac_forest = np.array(frac_forest).round(3)\r\nfrac_grass = np.array(frac_grass).round(3)\r\nfrac_C4 = np.array(frac_C4).round(3)\r\n\r\n\r\n\r\n### append to sitelist\r\nsitelist['forest_fraction'] = frac_forest\r\nsitelist['grass_fraction'] = frac_grass\r\nsitelist['C4_fraction'] = frac_C4\r\n\r\n# sitelist.to_csv('C:/Users/kna016/Documents/CABLE/OzFLUX_sitelist_v3.txt',sep=\"\\t\") # frac_max=False\r\n#sitelist.to_csv('C:/Users/kna016/Documents/CABLE/OzFLUX_sitelist_v4.txt',sep=\"\\t\") # frac_max=True\r\nsitelist.to_csv('C:/Users/kna016/Documents/CABLE/OzFLUX_sitelist_v5.txt',sep=\"\\t\") # frac_C4 included\r\n\r\n\r\n\r\n### some tests:\r\n# x = filter(lambda funs: funs[0:3] == startyear, dates) \r\n# x = filter(lambda k: str(startyear) in k, dates)\r\n \r\n# lst = ['a', 'ab', 'abc', 'bac']\r\n# filter(lambda k: 'ab' in k,lst)\r\n# \r\n# x = [k for k in lst if 'ab' in k] # 'list comprehensions'\r\n# list(map(str,range(startyear,endyear)))","sub_path":"forcing/cover_fract/OzFlux_coverfract.py","file_name":"OzFlux_coverfract.py","file_ext":"py","file_size_in_byte":4034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"639765788","text":"import hashlib, json, sys\nimport random\nrandom.seed(0)\n\ndef hashMe(msg=\"\"):\n # For convenience, this is a helper function that wraps our hashing algorithm\n if type(msg) != str:\n msg = json.dumps(msg,sort_keys=True) # if we don't sort keys, we can't guarantee repeatability!\n\n if sys.version_info.major == 2:\n return unicode(hashlib.sha256(msg).hexdigest(), 'utf-8')\n else:\n return hashlib.sha256(str(msg).encode('utf-8')).hexdigest()\n\n\ndef makeTransaction(maxValue=3):\n # This will create valid transactions in the range of (1,maxValue)\n sign = int(random.getrandbits(1))*2 - 1 # this will randomly choose -1 or 1\n amount = random.randint(1,maxValue)\n alicePays = sign * amount\n bobPays = -1 * alicePays\n # by construction, this will always return transactions that respect the conservation of tokens\n # however, note that we have not done anything to check whther these overdraft an account\n return {u'Alice':alicePays,u'Bob':bobPays}\n\ntxnBuffer = [makeTransaction() for i in range(30)]\n\ndef updateState(txn, state):\n # Inputs: txn, state: dictionaries keyed with account names, holding numeric values for the transfer amount (txn) or account balance (state)\n # Returns: Updated state, with additional users added to state if necessary\n # NOTE: This does not validate the transaction- just updates the state!\n\n # If the transaction is valid, then update the state\n state = state.copy() # As dictionaries are mutable, let's avoid any confusion by reating a vorking copy of the data.\n for key in txn:\n if key in state.keys():\n state[key] += txn[key]\n else:\n state[key] = txn[key]\n return state\n\ndef isValidTxn(txn, state):\n # assume that the transaction is a dictionary keyed by account names\n\n #check that the sum of the deposits and withdrawals is 0\n if sum(txn.values()) is not 0:\n return False\n\n # Check that the transaction does not cause an overdraft\n for key in txn.keys():\n if key in state.keys():\n acctBalance = state[key]\n else:\n acctBalance = 0\n if (acctBalance + txn[key]) < 0:\n return False\n\n return True\n\nstate = {u'Alice':5,u'Bob':5}\n\nprint(isValidTxn({u'Alice':-3,u'Bob':3},state))\nprint(isValidTxn({u'Alice':-4,u'Bob':3},state))\nprint(isValidTxn({u'Alice':-6,u'Bob':6},state))\nprint(isValidTxn({u'Alice':-4,u'Bob':2,u'Lisa':2},state))\nprint(isValidTxn({u'Alice':-4,u'Bob':3,u'Lisa':2},state))\n","sub_path":"Core.py","file_name":"Core.py","file_ext":"py","file_size_in_byte":2512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"132037630","text":"import datetime\nimport sys\nfrom collections import namedtuple\nfrom typing import Dict, List\n\nimport xlrd\n\nProductInfo = namedtuple(\n \"ProductInfo\",\n (\"name\", \"storage_type\", \"packaging\", \"weight\", \"date\"),\n defaults=(None, None, None, 0, datetime.datetime.now()),\n)\n\n\nclass BarcodeDatabase:\n def __init__(self, filepaths: List[str] = list()):\n self._codemap = {}\n self._filepaths = filepaths\n self._fill_database(filepaths)\n\n def __getitem__(self, key):\n return self._codemap[key]\n\n def __contains__(self, key):\n return key in self._codemap\n\n def clear(self):\n self._codemap.clear()\n\n def reload(self):\n self.clear()\n self._fill_database(self.filepaths)\n\n def read_db_file(self, filepath: str):\n if filepath.endswith(\".xls\"):\n self._codemap.update(BarcodeDatabase._from_xls(filepath))\n else:\n raise NotImplementedError\n\n def _from_xls(filepath: str) -> Dict[int, ProductInfo]:\n result = {}\n rb = xlrd.open_workbook(filepath)\n for sheetidx in range(rb.nsheets):\n sheet = rb.sheet_by_index(sheetidx)\n for rownum in range(1, sheet.nrows):\n values = sheet.row_values(rownum)\n result[int(values[0])] = ProductInfo(*values[1:])\n return result\n\n def _fill_database(self, filepaths: List[str]):\n for filepath in filepaths:\n self.read_db_file(filepath)\n\n\ndb = BarcodeDatabase(filepaths=sys.argv[1:])\nprint(db._codemap)\n","sub_path":"brreader/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"114466266","text":"class Solution(object):\n def hasCycle(self, head):\n i = head\n j = head.next\n while i is not None and i.next is not None:\n if i.next == head:\n return True\n i = i.next\n j.next = head\n j = i\n return False\n\n\nclass ListNode(object):\n def __init__(self, x, next=None):\n self.val = x\n self.next = next\n\nlst = ListNode(1, ListNode(2, ListNode(3, ListNode(4)))) # 1 -> 2 -> 3 -> 4\nlst.next.next.next.next = lst.next # создаём цикл 1 -> 2 -> 3 -> 4 ↘\nc = Solution() # ↖__________|\nprint(c.hasCycle(lst))\n","sub_path":"students/DariaSuslova/linked_list_cycle/linked_list_cycle_listok_2.py","file_name":"linked_list_cycle_listok_2.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"246386068","text":"#完全数を求めるプログラム\n\nvalue = int( input(\"約数を求めたい正の整数\"))\n\nsumNum = 0\nfor d in range(1, value + 1):\n if value % d == 0: sumNum += d\nprint(\"約数の総和は\",sumNum)\n\nif sumNum == 2 * value:\n print(value,\"は、完全数です\")\nelse:\n print(value,\"は、完全数ではありません。\")\n\n\nupper = 10000\nfor n in range(2, upper+1):\n sumNum = 0\n for d in range(1,n//2+1):\n if n % d == 0: sumNum += d\n if sumNum == n:\n print(n, end = ' ')\nprint()\n\n\n#2進数を使って、完全数の候補を求める\nbvalue = \"1\"\nfor n in range( 30 ):\n bvalue = \"1\" + bvalue + \"0\"\n value = int(bvalue, base = 2)\n print(value)\n\n #完全数かどうかを判定する\n sumNum = 0\n for d in range(1, value // 2 + 1):\n if value % d == 0: sumNum += d\n print(value , \":\", \"COMPLETE\" if sumNum == value else \"not\")\n","sub_path":"約数と素数/perfectNumbers.py","file_name":"perfectNumbers.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"411658272","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('cas', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Food',\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=200, verbose_name=b'\\xe4\\xb8\\xad\\xe6\\x96\\x87\\xe5\\x90\\x8d\\xe7\\xa7\\xb0')),\n ('info', models.CharField(max_length=500, null=True, verbose_name=b'\\xe6\\x8f\\x8f\\xe8\\xbf\\xb0', blank=True)),\n ('create_time', models.DateTimeField(auto_now_add=True)),\n ],\n options={\n 'ordering': ['-create_time'],\n 'verbose_name': '\\u98df\\u7269\\u5217\\u8868',\n 'verbose_name_plural': '\\u98df\\u7269\\u5217\\u8868',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Orders',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('create_time', models.DateField(auto_now_add=True)),\n ('food', models.ForeignKey(to='dinner.Food')),\n ('pro', models.ForeignKey(to='cas.Pro')),\n ],\n options={\n 'ordering': ['-create_time'],\n 'verbose_name': '\\u8ba2\\u5355\\u5217\\u8868',\n 'verbose_name_plural': '\\u8ba2\\u5355\\u5217\\u8868',\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"dinner/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"295096306","text":"# #############################################\n#\n# Smart Wardrobe for the Raspberry Pi\n#\n# Developed by the Salmons for the 2013/2014 PA Consulting\n# Raspberry Pi Competition:\n# http://www.paconsulting.com/events/pas-new-raspberry-pi-competition-for-2013-14/\n#\n\n# This file takes a list of things that describe the weather e.g. gentle breeze,\n# fairly warm etc, and picks a slot from a wardrobe, because the clothes in that\n# slot appear to match the weather best.\n\n# turn debug on or off for this module\n#wardrobeDebugOn = 1\nwardrobeDebugOn = 0\n\ndef wardrobeDebug(debugText):\n if (wardrobeDebugOn):\n print (debugText)\n\nwardrobe = [# rain or sleet -> umbrella\n {'cloudCover': ['Any'],\n 'windSpeed': ['NextToNoWind', 'GentleBreeze'],\n 'minTemp': ['FairlyWarm'],\n 'maxTemp': ['FairlyWarm'],\n 'precipitationType': ['rain', 'drizzle'],\n 'clothes': 'Umbrella, jacket, shoes, jumper, T-shirt, trousers'},\n\n # hot and sunny but cloudy\n {'cloudCover': ['AverageAmountOfCloud', 'LotsOfCloud'],\n 'windSpeed': ['NextToNoWind'],\n 'minTemp': ['Hot'],\n 'maxTemp': ['Hot'],\n 'precipitationType': ['none'],\n 'clothes': 'Sun hat, T-shirt, shorts, flip-flops'},\n\n # hot and sunny with no cloud\n {'cloudCover': ['SmallAmountOfCloud'],\n 'windSpeed': ['NextToNoWind'],\n 'minTemp': ['Hot'],\n 'maxTemp': ['Hot'],\n 'precipitationType': ['none'],\n 'clothes': 'Sun hat, long-sleeved T-shirt, lightweight trousers, sandals'},\n\n # snow -> extra warm\n {'cloudCover': ['Any'],\n 'windSpeed': ['Any'],\n 'minTemp': ['RatherCold'],\n 'maxTemp': ['RatherCold'],\n 'precipitationType': ['snow'],\n 'clothes': 'Warm coat, hat, gloves, warm jumper, trousers, warm long-sleeved top'}\n ]\n\n\n# Compares two strings' position in the list of all possible values,\n# and returns a score based on how close they are to being at the same\n# position in the list (see getBestScore for details of the score)\ndef compareTwoStrings(stringA, stringB, allValues):\n for aPos in range(len(allValues)):\n if (stringA == allValues[aPos]):\n break\n\n for bPos in range(len(allValues)):\n if (stringB == allValues[bPos]):\n break\n\n if (aPos == len(allValues)):\n print (\"Error: can't find\", stringA, \"in\", allValues)\n\n if (bPos == len(allValues)):\n print (\"Error: can't find\", stringB, \"in\", allValues)\n\n gap = abs(aPos - bPos)\n\n score = 10 - (15 * gap)\n\n return score\n\n\n\n# General purpose function for comparing a string and a list of strings, that\n# all come from a list of possible values.\n#\n# The string is compared with each member of the list, and the score from\n# the best match is returned. If a given pair of strings are identical, the\n# score is 10. If the pair of strings come from different places in the list\n# of all possible values, their score is 10 - (15 * the number of places\n# difference between them in the list of all possible values). So, next to\n# each other is -5 (10 - 15). Next but one is -20 (10 - 30) etc.\n#\ndef getBestScore(testString, stringList, allValues):\n score = -99999\n\n for stringToCheck in stringList:\n tempScore = compareTwoStrings(testString, stringToCheck, allValues)\n\n if tempScore > score:\n score = tempScore\n\n return score\n\n\ndef getCloudScore(currentCloud, slotCloud):\n if (slotCloud[0] == 'Any'):\n score = 0\n else:\n score = getBestScore(currentCloud, slotCloud,\n ['SmallAmountOfCloud', 'AverageAmountOfCloud', 'LotsOfCloud'])\n\n wardrobeDebug (\"cloud score is \" + str(score))\n return score\n\n\n# ignore min temp for now\ndef getTemperatureScore(currentMinTemp, currentMaxTemp, slotMinTemp, slotMaxTemp):\n if (slotMaxTemp[0] == 'Any'):\n score = 0\n else:\n score = getBestScore(currentMaxTemp, slotMaxTemp, ['RatherCold', 'FairlyWarm', 'Hot'])\n\n wardrobeDebug (\"temperature score is \" + str(score))\n return score\n\n\ndef getWindScore(currentWind, slotWind):\n if (slotWind[0] == 'Any'):\n score = 0\n else:\n score = getBestScore(currentWind, slotWind, ['NextToNoWind', 'GentleBreeze', 'LotsOfWind'])\n\n wardrobeDebug (\"wind score is \" + str(score))\n return score\n\n\ndef getPrecScore(currentPrec, slotPrec):\n if (slotPrec[0] == 'Any'):\n score = 0\n else:\n score = getBestScore(currentPrec, slotPrec, ['none', 'drizzle', 'rain', 'snow'])\n\n wardrobeDebug (\"precipitation score is \" + str(score))\n return score\n\n\ndef getScoreForSlot(currentWeather, slot):\n \n s1 = getCloudScore(currentWeather['cloudCover'], slot['cloudCover'])\n \n s2 = getTemperatureScore(currentWeather['minTemp'],\n currentWeather['maxTemp'],\n slot['minTemp'],\n slot['maxTemp'])\n \n s3 = getWindScore(currentWeather['windSpeed'], slot['windSpeed'])\n \n s4 = getPrecScore(currentWeather['precipitationType'], slot['precipitationType'])\n\n score = s1 + s2 + s3 + s4\n\n wardrobeDebug (\"total score is \" + str(score))\n return score\n\n\ndef getSlotForWeather(currentWeather):\n bestSlotSoFar = -1\n bestScoreSoFar = -99999\n\n for slotNum in range(len(wardrobe)):\n wardrobeDebug(\">>> processing slot \" + str(slotNum))\n currentScore = getScoreForSlot(currentWeather, wardrobe[slotNum])\n\n if (currentScore > bestScoreSoFar):\n wardrobeDebug (\"Best score so far is \" + str(currentScore) + \" from slot \" + str(slotNum))\n bestScoreSoFar = currentScore\n bestSlotSoFar = slotNum\n\n print (\"Selecting these clothes \",\n wardrobe[bestSlotSoFar]['clothes'])\n \n return bestSlotSoFar\n\n\n# ######################################################################\n# test code\n# ######################################################################\n\n# snow - should get slot 3\n#currentWeather = {'cloudCover': 'None',\n# 'windSpeed': 'GentleBreeze',\n# 'minTemp': 'RatherCold',\n# 'maxTemp': 'RatherCold',\n# 'precipitationType': 'snow'}\n\n# hot and cloudy - slot 1\n#currentWeather = {'cloudCover': 'LotsOfCloud',\n# 'windSpeed': 'GentleBreeze',\n# 'minTemp': 'Hot',\n# 'maxTemp': 'Hot',\n# 'precipitationType': 'none'}\n\n# hot and no cloud - slot 2\n#currentWeather = {'cloudCover': 'SmallAmountOfCloud',\n# 'windSpeed': 'GentleBreeze',\n# 'minTemp': 'Hot',\n# 'maxTemp': 'Hot',\n# 'precipitationType': 'none'}\n\n# rainy and not too windy - slot 0\n#currentWeather = {'cloudCover': 'LotsOfCloud',\n# 'windSpeed': 'GentleBreeze',\n# 'minTemp': 'FairlyWarm',\n# 'maxTemp': 'FairlyWarm',\n# 'precipitationType': 'rain'}\n\n\n#slot = getSlotForWeather(currentWeather)\n\n#print (\"Slot for today's weather is\", slot)\n","sub_path":"Wardrobe.py","file_name":"Wardrobe.py","file_ext":"py","file_size_in_byte":7259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"297346754","text":"\n\nfrom xai.brain.wordbase.nouns._revival import _REVIVAL\n\n#calss header\nclass _REVIVALS(_REVIVAL, ):\n\tdef __init__(self,): \n\t\t_REVIVAL.__init__(self)\n\t\tself.name = \"REVIVALS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"revival\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_revivals.py","file_name":"_revivals.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"583290936","text":"import readFile\nimport dekoder\n\n# 0 - wolne\n# 1 - sciana\n# 2 - nie podlega monitorowaniu\n# 3 - zasloniete\n# 4 - policzone\n\n\ndef J(x, y, alpha, dep):\n table = readFile.getArray()\n no_0 = seen_counter_for_0(table)\n\n n = dekoder.n() # szerokosc x\n m = dekoder.m() # szerokosc y\n is_forbidden = False\n\n for k in range(len(x)):\n\n # print(alpha[k])\n # print(m)\n\n table = angel_change(alpha[k], table)\n temp_x = x[k]\n x[k] = change_x(alpha[k], x[k], y[k], n, m)\n y[k] = change_y(alpha[k], temp_x, y[k], n, m)\n\n # print(x[k])\n # print(y[k])\n\n temp = j_for_one(x[k], y[k], dep, table)\n table = temp[0]\n if temp[1]:\n is_forbidden = True\n table = angel_change_back(alpha[k], table)\n # print_matrix(table)\n\n if is_forbidden:\n return 0.6 * round((seen_counter(table) / no_0), 4), table\n else:\n return round((seen_counter(table) / no_0), 4), table\n\n\ndef J_return_forbidden(x, y, alpha, dep):\n table = readFile.getArray()\n no_0 = seen_counter_for_0(table)\n\n n = dekoder.n() # szerokosc x\n m = dekoder.m() # szerokosc y\n is_forbidden = False\n\n for k in range(len(x)):\n\n # print(alpha[k])\n # print(m)\n\n table = angel_change(alpha[k], table)\n temp_x = x[k]\n x[k] = change_x(alpha[k], x[k], y[k], n, m)\n y[k] = change_y(alpha[k], temp_x, y[k], n, m)\n\n # print(x[k])\n # print(y[k])\n\n temp = j_for_one(x[k], y[k], dep, table)\n table = temp[0]\n if temp[1]:\n is_forbidden = True\n table = angel_change_back(alpha[k], table)\n # print_matrix(table)\n\n if is_forbidden:\n return None\n else:\n return round((seen_counter(table) / no_0), 4)\n\n\ndef j_for_one(x, y, d, matrix=readFile.getArray()):\n d += 1\n n = len(matrix[0]) # szerokosc x\n m = len(matrix) # szerokosc y\n\n blocked_ranges = []\n if_forbidden = False\n\n if matrix[y][x] == 1 or matrix[y][x] == 2:\n if_forbidden = True\n\n for i in range(d):\n\n if y-i < 0 or y-i >= m:\n break\n for ii in range(2*i + 1):\n if 0 <= x-i+ii < n and matrix[y - i][x - i + ii] == 0:\n if not if_in_ranges(blocked_ranges, get_coords(2*i + 1, ii)):\n matrix[y-i][x-i+ii] = 4\n else:\n matrix[y - i][x - i + ii] = 0\n\n elif 0 <= x-i+ii < n and matrix[y - i][x - i + ii] == 1:\n blocked_ranges = add_range(blocked_ranges, get_coords((2*i + 1), ii))\n\n return matrix, if_forbidden\n\n\ndef add_range(ranges, new):\n ranges.append(new)\n merge_ranges(ranges)\n return ranges\n\n\ndef merge_ranges(ranges):\n for i in ranges:\n for ii in ranges:\n if i[1] >= ii[0] and ii[1] >= i[0]:\n i[0] = min(i[0], ii[0])\n i[1] = max(i[1], ii[1])\n ii[0] = i[0]\n ii[1] = i[1]\n\n\ndef get_coords(length, index):\n return [index/length, (index+1)/length]\n\n\ndef if_in_ranges(ranges, coords):\n for i in ranges:\n if i[0] <= coords[0] <= i[1] and i[0] <= coords[1] <= i[1]:\n return True\n return False\n\n\ndef print_matrix(matrix1):\n for i in matrix1:\n print(str(i))\n print('')\n\n\ndef seen_counter(matrix2):\n nb = 0\n for i in matrix2:\n for ii in i:\n if ii == 4:\n nb += 1\n return nb\n\n\ndef seen_counter_for_0(matrix2):\n nb = 0\n for i in matrix2:\n for ii in i:\n if ii == 0:\n nb += 1\n return nb\n\n\ndef matrix_transpose(m):\n rez = [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]\n return rez\n\n\ndef matrix_vertical_symmetry(m):\n for i in m:\n i.reverse()\n return m\n\n\ndef matrix_horizontal_symmetry(m):\n rez = []\n for i in m:\n rez.insert(0, i)\n return rez\n\n\ndef angel_change(alpha, m):\n if alpha == 1:\n m = matrix_transpose(m)\n m = matrix_vertical_symmetry(m)\n elif alpha == 2:\n m = matrix_horizontal_symmetry(m)\n elif alpha == 3:\n m = matrix_vertical_symmetry(m)\n m = matrix_transpose(m)\n return m\n\n\ndef angel_change_back(alpha, m):\n if alpha == 1:\n m = angel_change(3, m)\n elif alpha == 2:\n m = angel_change(2, m)\n elif alpha == 3:\n m = angel_change(1, m)\n return m\n\n\ndef change_x(alpha, x, y, len_x, len_y):\n if alpha == 1:\n return len_y - y - 1\n elif alpha == 3:\n return y\n else:\n return x\n\n\ndef change_y(alpha, x, y, len_x, len_y):\n if alpha == 1: \n return x\n elif alpha == 2: \n return len_y - y - 1\n elif alpha == 3: \n return len_x - x - 1\n else: \n return y\n\n#\n# matrix22 = readFile.getArray()\n#\n# # print_matrix(matrix_vertical_symmetry(matrix22))\n# # print_matrix(matrix_horizontal_symmetry(matrix22))\n# # print_matrix(angel_change_back(0, matrix22))\n#\n#\n# print(J(matrix22, [2, 6], [7, 6], [0, 1], 3))\n","sub_path":"src2/afunction.py","file_name":"afunction.py","file_ext":"py","file_size_in_byte":5092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"518550169","text":"import collections\nimport attr\n\nfrom flask import jsonify, render_template, abort, redirect\nimport courses\n\nclass Translations:\n def __init__(self):\n self.data = courses.load_yaml('coursedata/texts.yaml')\n\n def get_translations(self, language, section):\n # Merge with English when lacking translations\n # Start from a defaultdict\n d = collections.defaultdict(lambda: '???')\n d.update(**self.data.get('en', {}).get(section, {}))\n d.update(**self.data.get(language, {}).get(section, {}))\n return d\n\n\ndef render_assignment_editor(course, assignment_number, menu, translations, version):\n assignment = course.get_assignment(assignment_number)\n if not assignment:\n abort(404)\n\n arguments_dict = {}\n\n # Meta stuff\n arguments_dict['course'] = course\n arguments_dict['assignment_nr'] = str(assignment_number)\n arguments_dict['level'] = assignment.level\n arguments_dict['lang'] = course.language\n arguments_dict['next_assignment'] = int(assignment_number) + 1 if int(assignment_number) < course.max_level() else None\n arguments_dict['menu'] = menu\n arguments_dict['latest'] = version\n arguments_dict['selected_page'] = 'code'\n arguments_dict['page_title'] = f'Level {assignment_number} – Hedy'\n arguments_dict['docs'] = [attr.asdict(d) for d in assignment.docs]\n\n # Translations\n arguments_dict.update(**translations.get_translations(course.language, 'ui'))\n\n # Actual assignment\n arguments_dict.update(**attr.asdict(assignment))\n\n return render_template(\"code-page.html\", **arguments_dict)\n\n\ndef render_assignment_docs(doc_type, course, assignment_number, menu, translations):\n assignment = course.get_assignment(assignment_number)\n if not assignment:\n abort(404)\n\n arguments_dict = {}\n\n # Meta stuff\n arguments_dict['course'] = course\n arguments_dict['assignment_nr'] = str(assignment_number)\n arguments_dict['pagetitle'] = f'Level {assignment_number}'\n arguments_dict['lang'] = course.language\n arguments_dict['selected_page'] = doc_type\n arguments_dict['docs'] = [attr.asdict(d) for d in assignment.docs]\n\n # Translations\n arguments_dict.update(**translations.get_translations(course.language, 'ui'))\n\n # print(repr(assignment_number), course.docs)\n\n doc = course.docs.get(int(assignment_number), doc_type)\n if not doc:\n # Redirect to code page. Nasty 'import' here to work around\n # cyclic imports.\n import app\n return redirect(app.hedy_link(assignment_number))\n\n arguments_dict['mkd'] = doc.markdown\n arguments_dict['menu'] = menu\n arguments_dict['page_title'] = f'Level {assignment_number} – ' + doc.front_matter.get('title', '') + ' – Hedy'\n\n return render_template(\"per-level-text.html\", **arguments_dict)","sub_path":"hedyweb.py","file_name":"hedyweb.py","file_ext":"py","file_size_in_byte":2690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"216771807","text":"import sys\nsys.path.append('../engel')\n\nfrom engel.widgets import Panel, Span\n\n\nclass FakeDispatchView(object):\n \"\"\"\n This fake view aims to help the testing of event dispatchers.\n \"\"\"\n\n def __init__(self, expected_command):\n self.expected_command = expected_command\n self.is_loaded = True\n\n self.was_dispatched = False\n\n def dispatch(self, cmd):\n self.was_dispatched = True\n assert self.expected_command == cmd\n\n def verify(self):\n assert self.was_dispatched\n\n\ndef test_event_append_child():\n\n expected = {\n 'name': 'append',\n 'html': 'oki',\n 'selector': '#main-panel'\n }\n\n verifier = FakeDispatchView(expected)\n\n parent = Panel(id=\"main-panel\")\n parent.view = verifier\n\n child = Span(id=\"my-span\", text=\"oki\")\n parent.add_child(child)\n verifier.verify()\n\ndef test_event_remove_child():\n\n expected = {\n 'name': 'remove',\n 'selector': '#my-span'\n }\n\n verifier = FakeDispatchView(expected)\n\n parent = Panel(id='main-panel')\n\n child = Span(id=\"my-span\", text='oki')\n parent.add_child(child)\n parent.view = verifier\n\n parent.remove_child(child)\n verifier.verify()\n\n\ndef test_event_replace_child():\n\n expected = {\n 'name': 'replace',\n 'html': 'hello',\n 'selector': '#my-span'\n }\n\n verifier = FakeDispatchView(expected)\n\n parent = Panel(id=\"main-panel\")\n\n child1 = Span(id=\"my-span\", text=\"oki\")\n parent.add_child(child1)\n\n parent.view = verifier\n\n child2 = Span(id=\"my-other-span\", text=\"hello\")\n\n parent.replace_child(child1, child2)\n verifier.verify()\n\n\ndef test_event_add_class():\n\n expected = {\n 'name': 'addclass',\n 'cl': 'hue',\n 'selector': '#my-span'\n }\n\n verifier = FakeDispatchView(expected)\n\n child = Span(id='my-span', text=\"oki\")\n child.view = verifier\n\n child.add_class('hue')\n verifier.verify()\n\ndef test_event_remove_class():\n\n expected = {\n 'name': 'removeclass',\n 'cl': 'hue',\n 'selector': '#my-span'\n }\n\n verifier = FakeDispatchView(expected)\n\n child = Span(id='my-span', text='oki', classname='hue')\n child.view = verifier\n\n child.remove_class('hue')\n verifier.verify()\n\n\ndef test_event_set_attr():\n\n expected = {\n 'name': 'attr',\n 'selector': '#my-span',\n 'attr': 'hello',\n 'value': 'world'\n }\n\n verifier = FakeDispatchView(expected)\n\n child = Span(id='my-span', text='oki')\n child.view = verifier\n\n child._set_attribute('hello', 'world')\n verifier.verify()\n","sub_path":"tests/test_widget_base.py","file_name":"test_widget_base.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"145852721","text":"import gym\nimport numpy as np\n\nBALL_RADIUS = 0.03\n\nBALL_OBJECT_NAME = \"object\"\nBALL_JOINT_NAME = \"object:joint\"\n\n\nclass ThrowEnvWrapper(gym.Wrapper):\n #\n #\n # Gym wrapper with features:\n # - new reward function\n # - detect ball collision with ground and reset\n #\n #\n def __init__(self, env):\n super(ThrowEnvWrapper, self).__init__(env)\n self.desired_ball_velocity = np.array([0, 0, 1])\n self.max_velocity = 0\n self.max_height = 0\n self.target_height = 0.4\n self.ball_velp = np.zeros((3,))\n self.ball_center_z = 0\n self.ball_center_vel_z = 0\n self.reached_target = False\n\n def reset(self, **kwargs):\n obs = self.env.reset(**kwargs)\n return obs[\"observation\"]\n\n def step(self, action):\n observation, reward, done, info = self.env.step(action)\n ball_center_pos = self.sim.data.get_joint_qpos(BALL_JOINT_NAME)\n self.ball_center_z = ball_center_pos[2]\n self.ball_velp = self.sim.data.get_joint_qvel(BALL_JOINT_NAME)[:3]\n self.ball_center_vel_z = self.ball_velp[2]\n\n self.ball_center_z = self.sim.data.get_joint_qpos(BALL_JOINT_NAME)[2]\n if self.ball_center_z <= BALL_RADIUS:\n print(\"Ball was dropped -> Reset Environment\")\n done = True\n\n return observation[\"observation\"], self.reward(reward), done, info\n\n def reward(self, reward):\n #return self.reward_functionA()\n return self.reward_functionB()\n #return reward\n\n def reward_functionA(self):\n reward = 1 - (self.target_height - self.ball_center_z) / self.target_height\n z_direction = np.sign(self.ball_center_vel_z)\n if z_direction > 0:\n reward += self.ball_center_vel_z * 10\n return reward\n\n def reward_functionB(self):\n reward = 1 - (self.target_height - self.ball_center_z) / self.target_height\n z_direction = np.sign(self.ball_center_vel_z)\n\n if not self.reached_target and self.ball_center_z > self.target_height:\n reward += 100\n self.reached_target = True\n\n if z_direction < 0:\n reward = 0\n\n return reward\n","sub_path":"reinforcement-learning-robohand/utils/gym_wrapper.py","file_name":"gym_wrapper.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"444641625","text":"from neural_compressor.experimental.strategy.utils.tuning_space import TuningSpace\nfrom neural_compressor.conf.dotdict import DotDict\nfrom neural_compressor.utils import logger\nfrom copy import deepcopy\nimport unittest\n\nop_cap = {\n # op1 have both weight and activation and support static/dynamic/fp32/b16\n ('op_name1', 'op_type1'): [\n {\n 'activation':\n {\n 'dtype': ['int8'],\n 'quant_mode': 'static',\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor'],\n 'algorithm': ['minmax', 'kl']\n },\n 'weight':\n {\n 'dtype': ['int8'],\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor']\n }\n },\n {\n 'activation':\n {\n 'dtype': ['int4'],\n 'quant_mode': 'static',\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor'],\n 'algorithm': ['minmax', 'kl']\n },\n 'weight':\n {\n 'dtype': ['uint4'],\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor']\n }\n },\n {\n 'activation':\n {\n 'dtype': ['int8'],\n 'quant_mode': 'dynamic',\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor'],\n 'algorithm': ['minmax', 'kl']\n },\n 'weight':\n {\n 'dtype': ['int8'],\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor']\n }\n },\n {\n 'activation':\n {\n 'dtype': 'bf16'\n },\n 'weight':\n {\n 'dtype': 'bf16'\n }\n },\n {\n 'activation':\n {\n 'dtype': 'fp32'\n },\n 'weight':\n {\n 'dtype': 'fp32'\n }\n },\n ],\n # op2 have both weight and activation and support static/dynamic/fp32\n ('op_name2', 'op_type1'): [\n {\n 'activation':\n {\n 'dtype': ['int8'],\n 'quant_mode': 'static',\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor'],\n 'algorithm': ['minmax', 'kl']\n },\n 'weight':\n {\n 'dtype': ['int8'],\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor']\n }\n },\n {\n 'activation':\n {\n 'dtype': ['int8'],\n 'quant_mode': 'dynamic',\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor'],\n 'algorithm': ['minmax', 'kl']\n },\n 'weight':\n {\n 'dtype': ['int8'],\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor']\n }\n },\n {\n 'activation':\n {\n 'dtype': 'fp32'\n },\n 'weight':\n {\n 'dtype': 'fp32'\n }\n },\n ],\n # op3 have both weight and activation and support int4\n ('op_name3', 'op_type3'): [\n {\n 'activation':\n {\n 'dtype': ['int4'],\n 'quant_mode': 'static',\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor'],\n 'algorithm': ['minmax', 'kl']\n },\n 'weight':\n {\n 'dtype': ['int4'],\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor']\n }\n },\n {\n 'activation':\n {\n 'dtype': ['int8'],\n 'quant_mode': 'static',\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor'],\n 'algorithm': ['minmax', 'kl']\n },\n 'weight':\n {\n 'dtype': ['int8'],\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor']\n }\n },\n {\n 'activation':\n {\n 'dtype': 'fp32'\n },\n 'weight':\n {\n 'dtype': 'fp32'\n }\n },\n ],\n}\n\nclass TestTuningSpaceV2(unittest.TestCase):\n def setUp(self) -> None:\n self.capability = {\n 'calib': {'calib_sampling_size': [1, 10, 50]},\n 'op': deepcopy(op_cap)\n }\n \n self.op_wise_user_cfg_for_fallback = {\n 'op_name1': {\n 'activation': {\n 'dtype': ['fp32']\n },\n 'weight': {\n 'dtype': ['fp32']\n }\n },\n }\n \n \n def test_tuning_sampler_int4(self):\n # op-wise\n conf = {'usr_cfg': { } }\n conf = DotDict(conf)\n # test space construction\n tuning_space = TuningSpace(deepcopy(self.capability), deepcopy(conf))\n logger.debug(tuning_space.root_item.get_details())\n found_int4_activation = False\n found_int4_weight = False\n op3_act_item = tuning_space.query_quant_mode_item_by_full_path(('op_name3', 'op_type3'),\\\n ('static', 'activation'))\n for dtype_item in op3_act_item.options:\n if dtype_item.name == 'int4':\n found_int4_activation = True\n self.assertTrue(found_int4_activation)\n op3_weight_item = tuning_space.query_quant_mode_item_by_full_path(('op_name3', 'op_type3'), \\\n ('static', 'weight'))\n for dtype_item in op3_weight_item.options:\n if dtype_item.name == 'int4':\n found_int4_weight = True\n self.assertTrue(found_int4_weight)\n \n def test_sampler_int4(self):\n # test sampler\n from collections import OrderedDict\n from neural_compressor.strategy.utils.tuning_structs import OpTuningConfig\n from neural_compressor.strategy.utils.tuning_sampler import OpWiseTuningSampler\n # op-wise\n conf = {'usr_cfg': { } }\n conf = DotDict(conf)\n # test space construction\n tuning_space = TuningSpace(deepcopy(self.capability), deepcopy(conf))\n logger.debug(tuning_space.root_item.get_details())\n initial_op_tuning_cfg = {}\n for item in tuning_space.root_item.options:\n if item.item_type == 'op':\n op_name, op_type = item.name\n initial_op_tuning_cfg[item.name] = OpTuningConfig(op_name, op_type, 'fp32', tuning_space)\n quant_mode_wise_items = OrderedDict()\n from neural_compressor.strategy.utils.constant import auto_query_order as query_order\n pre_items = set()\n for quant_mode in query_order:\n items = tuning_space.query_items_by_quant_mode(quant_mode)\n filtered_items = [item for item in items if item not in pre_items]\n pre_items = pre_items.union(set(items))\n quant_mode_wise_items[quant_mode] = filtered_items\n\n def initial_op_quant_mode(items_lst, target_quant_mode, op_item_dtype_dict):\n for item in items_lst:\n op_item_dtype_dict[item.name] = target_quant_mode\n\n op_item_dtype_dict = OrderedDict()\n for quant_mode, quant_mode_items in quant_mode_wise_items.items():\n initial_op_quant_mode(quant_mode_items, quant_mode, op_item_dtype_dict)\n \n op_wise_tuning_sampler = OpWiseTuningSampler(deepcopy(tuning_space), [], [],\n op_item_dtype_dict, initial_op_tuning_cfg)\n op3 = ('op_name3', 'op_type3')\n for tune_cfg in op_wise_tuning_sampler:\n op_cfg = tune_cfg[op3].get_state()\n act_dtype = op_cfg['activation']['dtype']\n weight_dtype = op_cfg['weight']['dtype']\n self.assertTrue(act_dtype == weight_dtype == 'int4')\n \n\n def test_tuning_space_merge_op_wise(self):\n # op-wise\n conf = {\n 'usr_cfg': {\n 'quantization': {\n 'op_wise': self.op_wise_user_cfg_for_fallback,\n }\n }\n\n }\n conf = DotDict(conf)\n # test fallback\n tuning_space2 = TuningSpace(deepcopy(self.capability), deepcopy(conf))\n logger.debug(tuning_space2.root_item.get_details())\n op_name1_only_fp32 = True\n for quant_mode in ['static', 'dynamic']:\n for item in tuning_space2.query_items_by_quant_mode(quant_mode):\n if item.name[0] == 'op_name1':\n op_name1_only_fp32 = False\n self.assertTrue(op_name1_only_fp32)\n\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"test/strategy/test_tuning_space_v2_1.x.py","file_name":"test_tuning_space_v2_1.x.py","file_ext":"py","file_size_in_byte":9544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"220787952","text":"__author__ = 'sophia'\nimport unittest\nimport sys\nfrom interfaceTest.Methods.BeopTools import BeopTools\nfrom interfaceTest import app\nimport datetime, time\n\nserverip = app.config['SERVERIP']\nt = 30\nsite_url = 'http://%s/v1/data/set_realtimedata_from_site' % serverip\nhistroy_url = \"http://%s/get_history_data_padded_reduce\" % serverip\nrealtime_url = \"http://%s/admin/dataPointManager/search/\" % serverip\n\n\nclass Service019(unittest.TestCase):\n testCaseID = 'Service019'\n projectName = \"不针对项目\"\n buzName = '接口v1/data/set_realtimedata_from_site测试'\n start = 0.0\n now = 0\n startTime = \"\"\n errors = []\n\n def setUp(self):\n self.start = datetime.datetime.now()\n self.startTime = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\n self.logger = BeopTools.init_log(r'%s\\log\\%s.txt' % (sys.path[0], self.testCaseID))\n\n def Test(self):\n self.errors = []\n self.beopService()\n self.raiseError()\n\n def beopService(self):\n # 验证正确的参数,周期默认是m1,同时验证更新时间对不对\n data1 = {\"projId\": \"1\", \"point\": ['test_123_456'], \"value\": ['1'],\n 'time': str(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())), 'timePeriod': 'm1',\n 'waitForFinish': '0'}\n result_120 = self.postURL(data1, site_url)\n self.checkResult(result_120, data1)\n realtime_data = {\"projectId\": 1, \"current_page\": 1, \"page_size\": \"50\", \"text\": \"test_123_456\",\n \"isAdvance\": False, \"order\": None, \"isRemark\": None, \"flag\": None}\n result_realtime = self.postURL(realtime_data, realtime_url)\n self.checkRealTime(data1, result_realtime)\n ####验证传入中文参数,返回state为1\n data123 = {\"projId\": \"214\", \"point\": [\"ztest1\", \"ztest2\"], \"value\":[\"ceshi1\",\"测试2\"]}\n result_120 = self.postURL(data123, site_url)\n self.checkResult(result_120, data123)\n # 验证空的参数\n data2 = {}\n result_120 = self.postURL(data2, site_url)\n self.checkResult(result_120, data2)\n # 验证不完整的参数\n data3 = {\"projId\": \"1\", \"point\": ['test_123_456']}\n result_120 = self.postURL(data3, site_url)\n self.checkResult(result_120, data3)\n # 验证周期m1时候的值\n time_str = str(time.strftime(\"%Y-%m-%d %H:%M:00\", time.localtime()))\n print(time_str)\n data4 = {\"projId\": \"1\", \"point\": ['test_123_data4'], \"value\": ['1'], 'time': time_str, 'timePeriod': 'm1',\n 'waitForFinish': '0'}\n result_120 = self.postURL(data4, site_url)\n self.checkResult(result_120, data4)\n histroy_data = {\"projectId\": 1, \"pointList\": [\"test_123_data4\"], \"timeStart\": time_str,\n \"timeEnd\": time_str, \"timeFormat\": \"m1\"}\n result_history = self.postURL(histroy_data, histroy_url)\n self.checkHistory(data4, result_history)\n # 验证周期为m5时候的值\n time_str = self.comHM()\n print(time_str)\n data5 = {\"projId\": \"1\", \"point\": ['test_123_data5'], \"value\": ['1'], 'time': time_str,\n 'timePeriod': 'm5', 'waitForFinish': '0'}\n result_120 = self.postURL(data5, site_url)\n self.checkResult(result_120, data5)\n histroy_data = {\"projectId\": 1, \"pointList\": [\"test_123_data5\"], \"timeStart\": time_str,\n \"timeEnd\": time_str, \"timeFormat\": \"m5\"}\n result_history = self.postURL(histroy_data, histroy_url)\n self.checkHistory(data5, result_history)\n # 验证周期为h1时候的值\n time_str = str(time.strftime(\"%Y-%m-%d %H:00:00\", time.localtime()))\n print(time_str)\n data6 = {\"projId\": \"1\", \"point\": ['test_123_data6'], \"value\": ['1'], 'time': time_str,\n 'timePeriod': 'h1', 'waitForFinish': '0'}\n result_120 = self.postURL(data6, site_url)\n self.checkResult(result_120, data6)\n histroy_data = {\"projectId\": 1, \"pointList\": [\"test_123_data6\"], \"timeStart\": time_str,\n \"timeEnd\": time_str, \"timeFormat\": \"h1\"}\n result_history = self.postURL(histroy_data, histroy_url)\n self.checkHistory(data6, result_history)\n # 验证周期为d1的值\n time_str = str(time.strftime(\"%Y-%m-%d 00:00:00\", time.localtime()))\n print(time_str)\n data7 = {\"projId\": \"1\", \"point\": ['test_123_data7'], \"value\": ['1'], 'time': time_str,\n 'timePeriod': 'd1', 'waitForFinish': '0'}\n result_120 = self.postURL(data7, site_url)\n self.checkResult(result_120, data7)\n histroy_data = {\"projectId\": 1, \"pointList\": [\"test_123_data7\"], \"timeStart\": time_str,\n \"timeEnd\": time_str, \"timeFormat\": \"d1\"}\n result_history = self.postURL(histroy_data, histroy_url)\n self.checkHistory(data7, result_history)\n # # 验证周期不为m1,h1,m5,d1..例如为m6,看是否能够插进去数据\n # data8 = {\"projId\": \"1\", \"point\": ['test_123_data8'], \"value\": ['3'], 'time': '2016-07-22 00:20:00',\n # 'timePeriod': 'm6', 'waitForFinish': '0'}\n # result_120 = self.postURL(data8, site_url)\n # self.checkPeriod(result_120, data8)\n # # 验证时间格式不对,服务器不能保存数据,并有相关提示\n # data9 = {\"projId\": \"1\", \"point\": ['test_123_data9'], \"value\": ['4'], 'time': '2016-08-22',\n # 'timePeriod': 'm5', 'waitForFinish': '0'}\n # result_120 = self.postURL(data9, site_url)\n # self.checkTime(result_120, data9)\n # # 验证时间大于目前时间,服务器不能保存数据,并有相关提示\n # data10 = {\"projId\": \"1\", \"point\": ['test_123_data10'], \"value\": ['5'], 'time': '2016-08-22 00:20:00',\n # 'timePeriod': 'm5', 'waitForFinish': '0'}\n # result_120 = self.postURL(data10, site_url)\n # self.checkTime(result_120, data10)\n\n # 验证历史接口返回的点值和预期的是否相等\n def checkHistory(self, data, result):\n tool = BeopTools()\n name = data['point'][0]\n value = data['value'][0]\n if (result is not None and result.get('data') is not None):\n result_value = int(result['data'][name][0])\n if (int(data['value'][0]) == int(result['data'][data['point'][0]][0])):\n print('%s历史接口的值和预期的一致都是%s' % (data['point'][0], data['value'][0]))\n else:\n self.errors.append(\n '错误信息[%s]%s---没有保存数据,项目中芯国际(id=1)%s接口使用参数%s返回值和预期的点值不一致.预期点值:%s,%s接口返回的点值为:%d' % (\n tool.getTime(), self.testCaseID, histroy_url, str(data), value, histroy_url, result_value))\n else:\n print(result)\n self.errors.append('错误信息[%s]%s---项目:中芯国际(id=1)%s接口使用参数%s返回的值为空或者是没有历史数据' % (\n tool.getTime(), self.testCaseID, histroy_url, str(data)))\n\n def comHM(self):\n time_str = str(time.strftime(\"%Y-%m-%d %H:%M\", time.localtime()))\n h = time_str.split(' ')[1].split(':')[1][1]\n if (int(h) >= 0 and int(h) < 5):\n h0 = 0\n elif (int(h) >= 5 and int(h) <= 9):\n h0 = 5\n else:\n h0 = int(h)\n time_str0 = str(time_str.split(' ')[0]) + \" \" + str(time_str.split(' ')[1].split(':')[0]) + \":\" + str(\n time_str.split(' ')[1].split(':')[1][0]) + str(h0) + \":00\"\n return str(time_str0)\n\n def checkTime(self, result, data):\n tool = BeopTools()\n if result is not None:\n if type(result) == type({}) and 'state' in result.keys():\n self.errors.append(\n '错误信息[%s]%s---项目中芯国际(id=1)%s接口使用参数%s返回值与期待的不一致.实际为%s,应该是有时间格式或者时间不能大于目前时间的提示,并且没有保存数据' % (\n tool.getTime(), self.testCaseID, site_url, str(data), result))\n else:\n print('%s使用正确的参数返回值正确显示为%s' % (data['point'][0], result))\n\n def checkPeriod(self, result, data):\n tool = BeopTools()\n if result is not None:\n if type(result) == type({}) and 'state' in result.keys():\n self.errors.append(\n '错误信息[%s]%s---项目中芯国际(id=1)%s接口使用参数%s返回值与期待的不一致.实际为%s,应该是周期只能是m1,m5,h1,d1的提示,并且没有保存数据' % (\n tool.getTime(), self.testCaseID, site_url, str(data), result))\n else:\n print('%s使用正确的参数返回值正确显示为%s' % (data['point'][0], result))\n\n # 检查site_url接口返回过来的结果值\n def checkResult(self, result, data):\n tool = BeopTools()\n if result is not None:\n if type(result) == type({}) and 'state' in result.keys():\n print('%s使用正确的参数返回值正确显示为%s' % (data['point'][0], result))\n elif 'none' in result:\n if data == {}:\n print('使用空的参数返回值正确返回值为%s' % (result))\n else:\n print('%s点不完整的参数返回值正确返回值为%s' % (data['point'][0], result))\n else:\n self.errors.append('错误信息[%s]%s---项目中芯国际(id=1)%s接口使用参数%s返回值与期待的不一致.实际为%s,期待值:state:1' % (\n tool.getTime(), self.testCaseID, site_url, str(data), result))\n\n # 检查实时接口admin/dataPointManager/search/和site_url接口返回值是否相等\n def checkRealTime(self, value1, value2):\n tool = BeopTools()\n name = value1['point'][0]\n if value2 is not None and value2['list'] is not None:\n v1 = value1['value'][0]\n v2 = value2['list'][0]['pointvalue']\n update_time = value2['list'][0]['time']\n if (update_time):\n now = time.strftime(\"%Y-%m-%d %H:%M\", time.localtime())\n now = datetime.datetime.strptime(now, \"%Y-%m-%d %H:%M\")\n update = datetime.datetime.strptime(update_time, \"%Y-%m-%d %H:%M\")\n second = self.doTime(now, update)\n if second > 60*60+300:\n self.errors.append('错误信息[%s]%s---项目:中芯国际(id=1)%s接口点名%s更新时间超过5分钟' % (\n tool.getTime(), self.testCaseID, realtime_url, name))\n else:\n print(\"%s点更新正常。\" % (name))\n if (int(v1) == int(v2)):\n print('实时接口的值和post的值一样均为%s' % v1)\n else:\n self.errors.append(\n '错误信息没有保存数据,项目:中芯国际(id=1)%s接口使用参数%s,点值为%s,%s接口的点值为%s,两个值不一样' % (\n site_url, str(value1), v1, realtime_url, v2))\n else:\n self.errors.append(\n '错误信息[%s]%s---项目:中芯国际(id=1)%s接口点名%s返回值为空' % (tool.getTime(), self.testCaseID, realtime_url, name))\n\n def doTime(self, now, update):\n if (now > update):\n second = (now - update).seconds\n else:\n second = (update - now).seconds\n return second\n\n # post数据\n def postURL(self, data, url):\n tool = BeopTools()\n a = BeopTools()\n try:\n result = a.postData(url=url, data=data, t=t)\n return result\n except Exception as e:\n print(e.__str__())\n self.writeLog(e.__str__())\n self.errors.append(\"错误信息[%s]%s---访问%s接口失败.\" % (tool.getTime(), self.testCaseID, url))\n\n def writeLog(self, text):\n # logger = self.init_log()\n self.logger.info('[%s]---' % time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) + '' + text)\n\n # 抛出异常值\n def raiseError(self):\n if self.errors != []:\n assert 0, \"\\n\".join(self.errors)\n else:\n pass\n\n def tearDown(self):\n use1 = str((datetime.datetime.now() - self.start).seconds)\n use = use1 + \"s\"\n self.now = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\n # info.append([self.testCaseID, use, now])\n","sub_path":"service_case/Service019realtimedataFromSiteToV1.py","file_name":"Service019realtimedataFromSiteToV1.py","file_ext":"py","file_size_in_byte":12547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"425906183","text":"import argparse\nimport os\nfrom ldcEval import bleu_script,files2eval\n\nparser = argparse.ArgumentParser(\n description='Preprocess of LDC corpus')\nparser.add_argument('-test', type=str,\n default='nist03', metavar='S')\nparser.add_argument('-pair', type=str, default='cn-en', metavar='S')\nparser.add_argument('-len', type=int, default=80, metavar='N')\nparser.add_argument('-gpuid', type=int, default=0, metavar='N')\nparser.add_argument('-token', type=str, default='word', metavar='S')\n\nif __name__ == \"__main__\":\n nistSets = ['nist02']\n nistSets = ['nist02','nist03', 'nist04', 'nist05', 'nist06', 'nist08']\n pair = 'en-cn'\n src = pair.split('-')[0]\n tgt = pair.split('-')[1]\n state_name = 'obest'\n\n models=['rnn','bing','baidu','google']\n models=['rnn']\n for nist in nistSets:\n print(50*'-'+nist +'-'*50)\n for model in models:\n ref_path1 = 'corpus/ldc_data/'+nist+'/'+nist+'.clean.pkuseg.cn'\n # ref_path2 = 'corpus/ldc_data/'+nist+'/'+nist+'.clean.jieba.cn'\n # ref_path3 = 'corpus/ldc_data/'+nist+'/'+nist+'.clean.cn'\n hyp_path = 'generation/{}/'.format(model)+nist+'/'+nist+'.{}.pkuseg.cn'.format(model)\n if model =='rnn':\n hyp_path = 'generation/{}/'.format(model)+nist+'/'+nist+'.{}.pkuseg.{}.cn'.format(model,state_name)\n # hyp_path = 'generation/{}/'.format(model)+nist+'/'+nist+'.{}.raw.{}.cn'.format(model,state_name)\n # bleu0 = bleu_script(ref_path1+' '+ ref_path2 + ' ' + ref_path3,hyp_path)\n bleu0 = bleu_script(ref_path1,hyp_path)\n # print('BLEU score of baidu for the {} is {:.2f}'.format(nist,bleu0))\n bleu1, bleu2 = files2eval(ref_path1,hyp_path)\n print('BLEU score of {} for the {} is {:.2f}/{:.2f}'.format(model,nist,bleu0,bleu1))\n","sub_path":"oracleEva.py","file_name":"oracleEva.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"266913451","text":"# coding: utf-8\n\nfrom fabkit import * # noqa\n\n\n@task\ndef setup():\n python_version = '2.7.13'\n python = 'Python-{0}'.format(python_version)\n python_tgz = '{0}.tgz'.format(python)\n\n if not filer.exists(python_tgz):\n run('wget https://www.python.org/ftp/python/{0}/{1}'.format(python_version, python_tgz))\n\n if not filer.exists(python):\n run('[ -e {0} ] || tar xzf {1}'.format(python, python_tgz))\n\n sudo('yum groupinstall -y \"Development tools\"')\n sudo('yum install -y zlib-devel bzip2-devel python-devel openssl-devel'\n 'ncurses-devel sqlite-devel readline-devel tk-devel')\n\n if not filer.exists('/tmp/python27/bin/pip'):\n with api.cd(python):\n run('./configure --prefix=/tmp/python27')\n run('make')\n run('make altinstall')\n\n run('wget https://bootstrap.pypa.io/get-pip.py')\n run('/tmp/python27/bin/python2.7 get-pip.py')\n\n sudo('rm -rf /tmp/fabkit-repo')\n run('mkdir /tmp/fabkit-repo')\n with api.cd('/tmp/fabkit-repo'):\n run('git clone https://github.com/fabrickit/fabkit.git fabfile')\n run('/tmp/python27/bin/pip install -r fabfile/requirements.txt')\n run('cp -r /tmp/python27 /tmp/fabkit-repo/.python27')\n filer.template('/tmp/fabkit-repo/.gitignore')\n run('.python27/bin/fab -l')\n run('.python27/bin/fab -e genconfig')\n run('mv fabfile.ini.sample fabfile.ini')\n run('cp fabfile/etc/local_settings.py.sample conf/local_settings.py')\n run('cd .python27/bin/; ln -s python2.7 python')\n\n with api.cd('/tmp'):\n run('tar czf fabkit-repo.tar.gz fabkit-repo')\n\n scp('/tmp/fabkit-repo.tar.gz', '/tmp/fabkit-repo.tar.gz', is_local=False, is_receive=True)\n\n return {'status': 0}\n","sub_path":"fabscript/fabrickit/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"136735396","text":"'''\nextract c3d features files,\nproduce video_lists as format: video_name(full_path) frame_num feature_num\n'''\nimport os\nimport stat\nimport subprocess\nfrom get_frame_num import get_frame_num\n\n\n# video_dir = \"/home/wyd/C3D/examples/c3d_feature_extraction/input/HMDB51\"\n# if not os.path.exists(video_dir):\n# print \"cannot find video directory: %s\" % video_dir\n#\n# # create input list\n# #

Crypto coins consolidated list

\n Сontains consolidated information from cryptoid.info and poloniex public API. Last update %s\n

Click the header to sort

'''%(time.ctime(time.time()))\n \n f.write(header)\n title=''' \n \n \n \n \n \n \n \n \n '''\n f.write(title)\n for i in data:\n if i[0]!='Verium':\n if i[4] is not False:\n str2=('')\n f.write(str2)\n else:\n str1=('')\n f.write(str1)\n f.write('
NameTagDifficultyAlgorithmTrading on PoloniexCapitalization(In BTC)
'+i[0]+''+i[1]+''+str(i[2])+''+i[3]+''+str(i[4])+''+str(round(i[5],8))+'
'+i[0]+''+i[1]+''+str(i[2])+''+i[3]+''+'No Trading'+''+str(round(i[5],8))+'
')\n \ndef get_coin():\n url='http://chainz.cryptoid.info/explorer/api.dws?q=summary'\n client = MongoClient()\n db=client.pol\n coins=db.coins\n response = requests.get(url)\n raw_coins=response.json()\n for i in raw_coins.keys():\n coins.insert_one({'tag':i,'algorithm':raw_coins[i]['PoW'],'difficulty24':raw_coins[i]['diff'],'supply':raw_coins[i]['supply'],'btcprice':raw_coins[i]['ticker'].get('btc',0),'name':raw_coins[i]['name']})\n\n\ndef init_pol_pairs():\n client = MongoClient()\n db=client.pol\n pairs=db.curinces\n url='https://poloniex.com/public?command=returnCurrencies'\n res=requests.get(url)\n raw_pairs=res.json()\n for i in raw_pairs.keys():\n pairs.insert_one({'tag':i.lower(),'state':get_pol_state(raw_pairs[i])})\n \ndef build_top():\n data=[]\n client = MongoClient()\n db=client.pol\n coins=db.coins\n curinces=db.curinces\n pipeline=[{\"$project\":{\"name\":1,\"tag\":1,\"algorithm\":1,'difficulty24':1,'market_cap':{ '$multiply': [ \"$difficulty24\", \"$btcprice\" ] }}},\n {\"$sort\":{\"difficulty24\":1}}]\n raw=coins.aggregate(pipeline)\n for i in raw:\n m=curinces.find_one({'tag': i['tag']})\n if type(m) is dict:\n data.append([i['name'],i['tag'],i['difficulty24'],i['algorithm'],m['state'],i['market_cap']])\n else:\n data.append([i['name'],i['tag'],i['difficulty24'],i['algorithm'],False,i['market_cap']])\n return data\n \n#get_coin()\n#init_pol_pairs()\ndt=build_top()\nto_html(dt)\n\n \n \n","sub_path":"clist.py","file_name":"clist.py","file_ext":"py","file_size_in_byte":3442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"125451964","text":"import genomepy\nimport os\nimport pytest\n\nfrom stat import S_IREAD, S_IRGRP, S_IROTH\nfrom genomepy.provider import ProviderBase\n\n\n# to ignore file changes\n# git update-index --assume-unchanged tests/data/small_genome.fa.gz\n# to recheck file changes\n# git update-index --no-assume-unchanged tests/data/small_genome.fa.gz\ndef test_genome__init__(genome=\"tests/data/small_genome.fa.gz\"):\n # no fasta file\n with pytest.raises(FileNotFoundError):\n genomepy.Genome(\"empty\", \"tests/data/genome\")\n\n # genome dir not found\n with pytest.raises(FileNotFoundError):\n genomepy.Genome(\"unknown\", \"unknown\")\n\n readme = \"tests/data/README.txt\"\n if os.path.exists(readme):\n os.unlink(readme)\n\n g = genomepy.Genome(genome)\n assert g.genomes_dir == genomepy.utils.get_genomes_dir(None, False)\n assert g.name == \"small_genome\"\n assert g.filename == os.path.abspath(genome)\n assert g.genome_dir == os.path.dirname(g.filename)\n assert os.path.exists(g.index_file)\n assert os.path.exists(g.sizes_file)\n assert os.path.exists(g.gaps_file)\n assert isinstance(g.sizes, dict)\n assert isinstance(g.gaps, dict)\n assert g.annotation_gtf_file is None\n assert g.annotation_bed_file is None\n assert g.tax_id == g.assembly_accession == \"na\"\n assert isinstance(g.plugin, dict)\n\n\ndef test__parse_name(genome=\"tests/data/small_genome.fa.gz\"):\n g = genomepy.Genome(genome) # unimportant\n\n # name\n name = g._parse_name(\"test\")\n assert name == \"test\"\n\n # file\n name = g._parse_name(\"/home/genomepy/genomes/test2.fa\")\n assert name == \"test2\"\n\n # url\n name = g._parse_name(\"http://ftp.xenbase.org/pub/Genomics/JGI/Xentr9.1/XT9_1.fa.gz\")\n assert name == \"XT9_1\"\n\n\ndef test__parse_filename(genome=\"tests/data/small_genome.fa.gz\"):\n g = genomepy.Genome(genome) # unimportant\n\n # file path\n filename = g._parse_filename(genome)\n assert filename == os.path.abspath(genome)\n\n # folder path\n filename = g._parse_filename(os.path.dirname(genome))\n assert filename == os.path.abspath(genome)\n\n # name of genome in genomes_dir\n os.mkdir(\"tests/data/small_genome\")\n with open(\"tests/data/small_genome/small_genome.fa.gz\", \"w\") as fa:\n fa.write(\"test\")\n g.genomes_dir = \"tests/data/\"\n filename = g._parse_filename(os.path.basename(genome))\n assert filename == \"tests/data/small_genome/small_genome.fa.gz\"\n genomepy.utils.rm_rf(\"tests/data/small_genome\")\n\n # genome not found\n with pytest.raises(FileNotFoundError):\n g._parse_filename(\"does not exist\")\n\n\ndef test_check_annotation_file(genome=\"tests/data/small_genome.fa.gz\"):\n g = genomepy.Genome(genome)\n\n # does not exist\n gtf = g.check_annotation_file(\"gtf\")\n assert gtf is None\n\n # does exist\n path = \"tests/data/small_genome.annotation.test.gz\"\n with open(path, \"w\") as fa:\n fa.write(\"test\")\n test = g.check_annotation_file(\"test\")\n assert test == os.path.abspath(path)\n os.unlink(path)\n\n\ndef test__update_provider(genome=\"tests/data/small_genome.fa.gz\"):\n g = genomepy.Genome(genome)\n\n # can't parse url\n metadata = {}\n g._update_provider(metadata)\n assert metadata.get(\"provider\") == \"Unknown\"\n\n # can parse url\n metadata = {\n \"genome url\": \"https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/000/146/465/\"\n \"GCF_000146465.1_ASM14646v1/GCF_000146465.1_ASM14646v1_genomic.fna.gz\"\n }\n g._update_provider(metadata)\n assert metadata.get(\"provider\") == \"NCBI\"\n\n\ndef test__update_tax_id(genome=\"tests/data/small_genome.fa.gz\"):\n g = genomepy.Genome(genome)\n\n # genome not found\n metadata = {}\n g._update_tax_id(metadata)\n assert metadata[\"tax_id\"] == \"na\"\n\n # genome found\n metadata = {}\n provider = ProviderBase.create(\"NCBI\")\n genome = provider.genomes.get(\"ASM14646v1\")\n\n g._update_tax_id(metadata, provider, genome)\n assert metadata[\"tax_id\"] == \"58839\"\n\n\ndef test__update_assembly_accession(genome=\"tests/data/small_genome.fa.gz\"):\n g = genomepy.Genome(genome)\n\n # genome not found\n metadata = {}\n g._update_assembly_accession(metadata)\n assert metadata[\"assembly_accession\"] == \"na\"\n\n # genome found\n metadata = {}\n provider = ProviderBase.create(\"NCBI\")\n genome = provider.genomes.get(\"ASM14646v1\")\n\n g._update_assembly_accession(metadata, provider, genome)\n assert metadata[\"assembly_accession\"] == \"GCA_000146465.1\"\n\n\ndef test__update_metadata(genome=\"tests/data/small_genome.fa.gz\"):\n g = genomepy.Genome(genome)\n\n metadata = {\"provider\": \"NCBI\", \"original name\": \"ASM14646v1\"}\n g._update_metadata(metadata)\n assert metadata[\"tax_id\"] == \"58839\"\n assert metadata[\"assembly_accession\"] == \"GCA_000146465.1\"\n\n\ndef test__read_metadata(genome=\"tests/data/small_genome.fa.gz\"):\n g = genomepy.Genome(genome)\n\n # no readme found\n readme = g.readme_file\n if os.path.exists(readme):\n os.unlink(readme)\n metadata = g._read_metadata()\n assert metadata[\"provider\"] == \"na\"\n\n # no overwrites to metadata\n with open(readme, \"w\") as f:\n f.writelines(\"provider: not_really_NCBI\\n\")\n f.writelines(\"tax_id: not_really_58839\\n\")\n f.writelines(\"assembly_accession: not_really_GCA_000146465.1\\n\")\n metadata = g._read_metadata()\n assert metadata[\"provider\"] == \"not_really_NCBI\"\n\n # updates to metadata dict and file\n with open(readme, \"w\") as f:\n f.writelines(\n \"genome url: https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/000/\"\n \"146/465/GCF_000146465.1_ASM14646v1/\"\n \"GCF_000146465.1_ASM14646v1_genomic.fna.gz\\n\"\n )\n f.writelines(\"tax_id: not_really_58839\\n\")\n f.writelines(\"assembly_accession: not_really_GCA_000146465.1\\n\")\n metadata1 = g._read_metadata()\n assert metadata1[\"provider\"] == \"NCBI\"\n metadata2, _ = genomepy.utils.read_readme(readme)\n assert metadata2[\"provider\"] == \"NCBI\"\n\n # no writing permission to file\n with open(readme, \"w\") as f:\n f.writelines(\n \"genome url: https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/000/\"\n \"146/465/GCF_000146465.1_ASM14646v1/\"\n \"GCF_000146465.1_ASM14646v1_genomic.fna.gz\\n\"\n )\n os.chmod(readme, S_IREAD | S_IRGRP | S_IROTH)\n metadata1 = g._read_metadata()\n assert metadata1[\"provider\"] == \"na\"\n os.unlink(readme)\n\n\ndef test__bed_to_seqs(\n genome=\"tests/data/small_genome.fa.gz\", track=\"tests/data/regions.bed\"\n):\n g = genomepy.Genome(genome)\n\n # extract sequences marked in regions.bed from small_genome.fa.gz\n seqs = g._bed_to_seqs(track=track, stranded=False, extend_up=0, extend_down=0)\n for i, seq in enumerate(seqs):\n assert seq.name == [\"chrI:10-20 gene_a\", \"chrII:20-30 gene_b\"][i]\n assert seq.seq == [\"CCCACACACC\", \"TCCTCCAAGC\"][i]\n\n # second sequence is on the negative strand\n seqs = g._bed_to_seqs(track=track, stranded=True, extend_up=0, extend_down=0)\n for i, seq in enumerate(seqs):\n assert seq.name == [\"chrI:10-20 gene_a\", \"chrII:20-30 gene_b\"][i]\n # original: \"CCCACACACC\", \"TCCTCCAAGC\"\n assert seq.seq == [\"CCCACACACC\", \"GCTTGGAGGA\"][i]\n\n # extend by varying amounts\n seqs = g._bed_to_seqs(track=track, stranded=True, extend_up=1, extend_down=2)\n for i, seq in enumerate(seqs):\n assert seq.name == [\"chrI:10-20 gene_a\", \"chrII:20-30 gene_b\"][i]\n # original: \"CCCACACACC\", \"GCTTGGAGGA\"\n assert seq.seq == [\"ACCCACACACCCA\", \"GGCTTGGAGGAGA\"][i]\n\n\ndef test__region_to_seq(genome=\"tests/data/small_genome.fa.gz\", region=\"chrI:10-20\"):\n g = genomepy.Genome(genome)\n\n # extract sequences marked in track from small_genome.fa.gz\n seq = g._region_to_seq(region=region, extend_up=0, extend_down=0)\n assert seq == \"CCCACACACC\"\n\n # extend by varying amounts\n seq = g._region_to_seq(region=region, extend_up=1, extend_down=2)\n # original: \"CCCACACACC\"\n assert seq == \"ACCCACACACCCA\"\n\n\ndef test__regions_to_seqs(\n genome=\"tests/data/small_genome.fa.gz\", track=\"tests/data/regions.txt\"\n):\n g = genomepy.Genome(genome)\n\n # extract sequences marked in regions.bed from small_genome.fa.gz\n seqs = g._regions_to_seqs(track=track, extend_up=0, extend_down=0)\n for i, seq in enumerate(seqs):\n assert seq.name == [\"chrI:10-20\", \"chrII:20-30\"][i]\n assert seq.seq == [\"CCCACACACC\", \"TCCTCCAAGC\"][i]\n\n # extend by varying amounts\n seqs = g._regions_to_seqs(track=track, extend_up=1, extend_down=2)\n for i, seq in enumerate(seqs):\n assert seq.name == [\"chrI:10-20\", \"chrII:20-30\"][i]\n # original: \"CCCACACACC\", \"TCCTCCAAGC\"\n assert seq.seq == [\"ACCCACACACCCA\", \"CTCCTCCAAGCCC\"][i]\n\n\ndef test_get_track_type():\n tracks = [\n ((\"chr1:10-20\", \"chr2:10-20\"), \"interval\"),\n ([\"chr1:10-20\", \"chr2:10-20\"], \"interval\"),\n (\"tests/data/regions.txt\", \"interval\"),\n (\"tests/data/regions.bed\", \"bed\"),\n (\"tests/data/regions2.bed\", \"bed\"),\n ]\n\n for track, track_type in tracks:\n result = genomepy.Genome.get_track_type(track)\n assert result == track_type\n\n\ndef test_track2fasta(genome=\"tests/data/small_genome.fa.gz\"):\n tracks = [\n (\"tests/data/regions.txt\", \"interval\"),\n (\"tests/data/regions.bed\", \"bed\"),\n ]\n g = genomepy.Genome(genome)\n\n for i, track in enumerate(tracks):\n seq = g.track2fasta(\n track=track[0],\n fastafile=None,\n stranded=False,\n extend_up=i,\n extend_down=i + 1,\n )\n\n # default sequence: CCCACACACC\n if i == 0: # extend up +0, down -1\n assert seq[0].seq == \"CCCACACACCC\"\n assert seq[1].seq == \"TCCTCCAAGCC\"\n else: # extend up +1, down -4\n assert seq[0].seq == \"ACCCACACACCCA\"\n assert seq[1].seq == \"CTCCTCCAAGCCC\"\n\n\ndef test_sizes(genome=\"tests/data/gap.fa\"):\n g = genomepy.Genome(genome)\n assert list(g.sizes.keys()) == [\"chr1\", \"chr2\", \"chr3\"]\n assert all(isinstance(g.sizes[chrom], int) for chrom in g.sizes.keys())\n assert g.sizes[\"chr1\"] == 28\n\n # does not overwrite user-set sizes\n g.sizes = {\"asd\": 1}\n assert g.sizes == {\"asd\": 1}\n\n # repopulates empty dicts\n g.sizes = {}\n assert list(g.sizes.keys()) == [\"chr1\", \"chr2\", \"chr3\"]\n\n\ndef test_gaps(genome=\"tests/data/gap.fa\"):\n g = genomepy.Genome(genome)\n assert list(g.gaps.keys()) == [\"chr1\", \"chr3\"]\n\n # does not overwrite user-set gaps\n g.gaps = {\"asd\": 1}\n assert g.gaps == {\"asd\": 1}\n\n # repopulates empty dicts\n g.gaps = {}\n assert list(g.gaps.keys()) == [\"chr1\", \"chr3\"]\n\n\ndef test__weighted_selection(n=2):\n tuples = [(1, \"one\"), (2, \"two\"), (3, \"three\")]\n ws = genomepy.Genome._weighted_selection(tuples, n)\n\n assert len(ws) == n\n assert isinstance(ws[0], str)\n assert tuples[0][1] in ws or tuples[1][1] in ws or tuples[2][1] in ws\n\n\ndef test_get_random_sequences(genome=\"tests/data/small_genome.fa.gz\"):\n g = genomepy.Genome(genome)\n n = 2\n length = 200 # default\n chroms = [\"chrI\", \"chrII\"]\n max_n = 0.1 # default\n rs = g.get_random_sequences(n=n, length=length, chroms=chroms, max_n=max_n)\n\n # check that the output has the right length, content, types, and sequence length\n assert len(rs) == n\n for i in range(n):\n assert rs[i][0] in chroms\n assert (\n isinstance(rs[i][0], str)\n and isinstance(rs[i][1], int)\n and isinstance(rs[i][2], int)\n )\n assert rs[i][2] - rs[i][1] == length\n\n # check that the max Ns are lower than the expected cutoff\n rs = g.get_random_sequences(n=1, chroms=chroms, outtype=\"string\")\n assert str(g.track2fasta(rs[0])[0].seq).upper().count(\"N\") <= length * max_n\n\n\ndef test_delete_test_files():\n for genome in [\n \"tests/data/small_genome.\",\n \"tests/data/gap.\",\n ]:\n for ext in [\"fa.fai\", \"fa.sizes\", \"gaps.bed\", \"fa.gz.fai\", \"fa.gz.sizes\"]:\n file = genome + ext\n if os.path.exists(file):\n os.unlink(file)\n","sub_path":"tests/04_genome_test.py","file_name":"04_genome_test.py","file_ext":"py","file_size_in_byte":12123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"271849232","text":"# coding=utf-8\nfrom setuptools import find_packages, setup\n\n\ndef get_version(filename):\n import ast\n version = None\n with open(filename) as f:\n for line in f:\n if line.startswith('__version__'):\n version = ast.parse(line).body[0].value.s\n break\n else:\n raise ValueError('No version found in %r.' % filename)\n if version is None:\n raise ValueError(filename)\n return version\n\n\nversion = get_version(filename='src/duckietown_mplan/__init__.py')\n\nsetup(name='duckietown_mplan',\n description='A versatile lane following algorithm for obstacle avoidance',\n version=version,\n download_url='http://github.com/duckietown/duckietown-mplan/tarball/%s' % version,\n package_dir={'': 'src'},\n packages=find_packages('src'),\n install_requires=[\n\n ],\n\n tests_require=[\n 'comptests',\n 'jupyter',\n 'nbconvert',\n ],\n\n # This avoids creating the egg file, which is a zip file, which makes our data\n # inaccessible by dir_from_package_name()\n zip_safe=False,\n\n # without this, the stuff is included but not installed\n include_package_data=True,\n\n entry_points={\n 'console_scripts': [\n 'dt-mplan-cli = duckietown_mplan.cli:cli_main',\n ]\n },\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\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 :: 2',\n 'Programming Language :: Python :: 3',\n ],\n )\n","sub_path":"lib-mplan/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"510914153","text":"from PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nimport os\nimport sys\nsys.path.append(os.path.dirname(__file__))\nfrom course_summary_widget import CourseSummaryWidget\n\nclass GradeSection(QWidget):\n\n #\n # This is the widget that goes in the tab container\n #\n\n def __init__(self, courses):\n super().__init__()\n self.courses = courses\n self.verticalLayout = QVBoxLayout()\n self.courseWidgets = []\n self.initialize_ui(courses)\n self.setLayout(self.verticalLayout)\n\n def initialize_ui(self, courses):\n '''Updates the display with all of the courses and grades.'''\n self.gradeLayout = QVBoxLayout()\n textWidget = QLabel(\" COURSE GRADE\")\n font = QFont()\n font.setBold(True)\n textWidget.setFont(font)\n self.gradeLayout.addWidget(textWidget)\n for course in courses:\n textWidget = CourseSummaryWidget(course)\n self.courseWidgets.append(textWidget)\n horizontalLayout = QHBoxLayout()\n horizontalLayout.addWidget(textWidget)\n horizontalLayout.addStretch()\n self.gradeLayout.addLayout(horizontalLayout)\n self.verticalLayout.addLayout(self.gradeLayout)\n self.setContentsMargins(4,0,0,0)\n self.setWindowTitle(\" GradeGeek™ \")","sub_path":"Source/grade_tab_section_page.py","file_name":"grade_tab_section_page.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"468977851","text":"# features\n# longo?\n# perna curta?\n# faz auau?\n\nfrom sklearn.svm import LinearSVC\nfrom sklearn.metrics import accuracy_score\n\nporco1 = [0, 1, 0]\nporco2 = [0, 1, 1]\nporco3 = [1, 1, 0]\n\ncachorro1 = [0, 1, 1]\ncachorro2 = [1, 0, 1]\ncachorro3 = [1, 1, 1]\n\ntreino_x = [porco1, porco2, porco3, cachorro1, cachorro2, cachorro3]\ntreino_y = [1, 1, 1, 0, 0, 0]\n\nmodel = LinearSVC()\nmodel.fit(treino_x, treino_y)\n\nmisterio1 = [1, 1, 1]\nmisterio2 = [1, 1, 0]\nmisterio3 = [0, 1, 1]\n\nteste_y = [0, 1, 0]\n\nteste_x = [misterio1, misterio2, misterio3]\nprevisoes = model.predict(teste_x)\n\ntaxa_de_acerto = accuracy_score(teste_y, previsoes)\nprint(\"Taxa de acerto\", taxa_de_acerto * 100)\n","sub_path":"exemplo_001.py","file_name":"exemplo_001.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"40078830","text":"'''\n\tspecfit.py - Definition of class for fitting linear combination of spectra.\n'''\n\n######################################################################\n\nimport os\nimport numpy as np\nfrom astropy.io import fits as pyfits\nfrom astropysics import spec\nimport scipy.ndimage.filters\nimport scipy.interpolate\nimport logging\nimport scipy.constants\nfrom scipy.optimize import leastsq\n\n_c_kms = scipy.constants.c / 1.e3 # Speed of light in km s^-1\nDF = -8.0\n\n\nclass SpecFit():\n ##################################################################\n\n def __init__(self, nspec):\n\n '''\nInitialize class.\n Input:\n nspec = Number of spectra that composes the observed spectra\n '''\n\n # number of componentes\n self.nspec = nspec\n\n # Store template spectra and scale factor\n self.template = [[]] * nspec\n self.templateNames = [[]] * nspec\n self.templateScale = [[]] * nspec\n self.specgrid = [[]] * nspec\n\n # velocity for each component\n self.vel = np.zeros(nspec)+1.\n\n # scale factor for each component\n self.scale = [[]] * nspec\n # self.mcscale = pm.Uniform(\"scale\", 0, 1, size=nspec)\n\n # template selected for each component\n self.ntemp = np.zeros(nspec, dtype=int)\n\n # template grid dimensions for each component\n self.grid_ndim = np.zeros(nspec, dtype=int)\n\n # Grids\n self.Grid = [[]] * nspec\n\n # store the observed spectra\n self.ospec = None\n\n self._autoprop = False\n\n ##################################################################\n\n def setAutoProp(self, value):\n self._autoprop = value\n\n ##################################################################\n\n def loadNextGenTemplate(self, ncomp, filename):\n '''\nLoads template spectra from a list of files (in filename), for\ncomponent ncomp.\n '''\n\n splist = np.loadtxt(filename, unpack=True, usecols=(0,),\n dtype='S', ndmin=1)\n\n self.template[ncomp] = [0] * len(splist)\n self.templateScale[ncomp] = [1] * len(splist)\n\n logging.debug('Loading template spectra for component %i from %s[%i]' % (ncomp, filename, len(splist)))\n\n for i in range(len(splist)):\n logging.debug('Reading %s' % (splist[i]))\n sp = np.loadtxt(splist[i], unpack=True, usecols=(0, 1),\n converters={0: lambda s: float(s.replace('D', 'e')),\n 1: lambda s: float(s.replace('D', 'e'))})\n asort = sp[0].argsort()\n self.template[ncomp][i] = spec.Spectrum(sp[0][asort],\n 10 ** (sp[1][asort]) + 8.0)\n\n return 0\n\n ##################################################################\n\n def loadPickleTemplate(self, ncomp, filename):\n '''\nLoads template spectra from a list of files (in filename), for\ncomponent ncomp.\n '''\n\n splist = np.loadtxt(filename, unpack=True,\n dtype='S', ndmin=2)\n if splist.shape[0] < self.grid_ndim[ncomp]:\n raise IOError('Grid dimensions is not consistent with expected. Expecting %i got %i.' % (\n self.grid_ndim[ncomp], splist.shape[0]))\n\n self.template[ncomp] = [0] * len(splist[0])\n self.templateNames[ncomp] = [0] * len(splist[0])\n self.templateScale[ncomp] = [1] * len(splist[0]) # np.zeros(len(splist))+1.0\n\n if self.grid_ndim[ncomp] > 0:\n grid = splist[1:self.grid_ndim[ncomp] + 1]\n gdim = np.zeros(self.grid_ndim[ncomp], dtype=np.int)\n for i in range(len(grid)):\n gdim[i] = len(np.unique(grid[i]))\n index = np.arange(len(splist[0])).reshape(gdim)\n self.Grid[ncomp] = index\n\n logging.debug('Loading template spectra for component %i from %s[%i]' % (ncomp, filename, len(splist)))\n\n for i in range(len(splist[0])):\n logging.debug('Reading %s' % (splist[0][i]))\n sp = np.load(splist[0][i])\n self.template[ncomp][i] = spec.Spectrum(sp[0], sp[1])\n self.templateNames[ncomp][i] = splist[0][i]\n\n return 0\n\n ##################################################################\n\n def loadCoelhoTemplate(self, ncomp, filename):\n '''\n Loads template spectra from a list of files (in filename), for\n component ncomp.\n '''\n\n splist = np.loadtxt(filename, unpack=True,\n dtype='S', ndmin=2)\n if splist.shape[0] < self.grid_ndim[ncomp]:\n raise IOError('Grid dimensions is not consistent with expected. Expecting %i got %i.' % (\n self.grid_ndim[ncomp], splist.shape[0]))\n\n self.template[ncomp] = [0] * len(splist[0])\n self.templateNames[ncomp] = [0] * len(splist[0])\n self.templateScale[ncomp] = [1] * len(splist[0])\n\n if self.grid_ndim[ncomp] > 0:\n grid = splist[1:self.grid_ndim[ncomp] + 1]\n index = np.arange(len(splist[0])).reshape((len(np.unique(grid[0])), len(np.unique(grid[1]))))\n self.Grid[ncomp] = index\n\n logging.debug('Loading template spectra for component %i from %s[%i]' % (ncomp, filename, len(splist)))\n\n notFound = 0\n for i in range(len(splist[0])):\n\n logging.debug('Reading %s' % (splist[0][i]))\n if os.path.exists(splist[0][i]):\n hdu = pyfits.open(splist[0][i])\n wave = hdu[0].header['CRVAL1'] + np.arange(len(hdu[0].data)) * hdu[0].header['CDELT1']\n self.template[ncomp][i] = spec.Spectrum(wave, hdu[0].data)\n self.templateNames[ncomp][i] = splist[0][i]\n else:\n logging.warning('Could not find template %s. %i/%i' % (splist[0][i], notFound, len(splist[0])))\n notFound += 1\n self.template[ncomp][i] = self.template[ncomp][i - 1]\n self.templateNames[ncomp][i] = splist[0][i] + \"NOTFOUND\"\n\n # sp = np.load(splist[0][i])\n if notFound > len(splist[0]) / 2:\n raise IOError('More than 50% of template spectra could not be loaded')\n\n return 0\n\n ##################################################################\n\n def loadPickle(self, filename, linearize=True):\n '''\nLoads observed spectra from numpy pickle file.\n '''\n\n logging.debug('Loading observed spectra for from %s' % (filename))\n\n sp = np.load(filename)\n\n self.ospec = spec.Spectrum(sp[0], sp[1])\n\n if linearize and not self.ospec.isLinear():\n logging.debug('Linearizing observed spectra')\n self.ospec.linearize()\n logging.debug('Done')\n\n return 0\n\n ##################################################################\n\n def loadtxtSpec(self, filename):\n '''\nLoad the observed spectra.\n '''\n\n logging.debug('Loading observed spectra for from %s' % (filename))\n\n sp = np.loadtxt(filename, unpack=True, usecols=(0, 1),\n converters={0: lambda s: float(s.replace('D', 'e')),\n 1: lambda s: float(s.replace('D', 'e'))})\n\n self.ospec = spec.Spectrum(sp[0], sp[1])\n\n return 0\n\n ##################################################################\n\n def loadSDSSFits(self, filename, linearize=False):\n '''\nLoad the observed spectra.\n '''\n\n logging.debug('Loading observed spectra for from %s' % (filename))\n\n sp = pyfits.open(filename)\n\n mask = np.bitwise_and(sp[1].data['and_mask'] == 0,\n sp[1].data['or_mask'] == 0)\n\n self.ospec = spec.Spectrum(x=10 ** (sp[1].data['loglam'][mask]),\n flux=sp[1].data['flux'][mask],\n ivar=sp[1].data['ivar'][mask])\n\n '''\n if linearize and not self.ospec.isLinear():\n logging.debug('Linearizing observed spectra')\n self.ospec.linearize()\n logging.debug('Done')\n '''\n\n return 0\n\n ##################################################################\n\n def gridSpec(self, ncomp=0):\n '''\n Resample and grid template spectrum.\n :return:\n '''\n\n # Use first spectrum as reference\n refspec = self.template[ncomp][0]\n\n specgrid = np.zeros((len(self.template[ncomp]), len(refspec.flux)))\n\n for i in range(len(specgrid)):\n specgrid[i] += self.template[ncomp][i].resample(refspec.x, replace=False)[1] * \\\n self.templateScale[ncomp][i]\n\n self.specgrid[ncomp] = specgrid\n self.scale[ncomp] = np.zeros(len(specgrid)).reshape(len(specgrid), -1) + 1. / len(specgrid)\n\n ##################################################################\n\n def chi2(self, p):\n '''\nCalculate chi-square of the data against model.\n '''\n\n for i in range(self.nspec):\n logging.debug('%f / %f' % (p[i], p[i + 1]))\n self.scale[i] = p[i * 2]\n self.vel[i] = p[i * 2 + 1]\n\n model = self.modelSpec()\n\n # c2 = np.mean( (self.ospec.flux - model.flux )**2.0 / self.ospec.flux)\n c2 = self.ospec.flux - model.flux\n return c2\n\n ##################################################################\n\n def modelSpec(self):\n '''\nCalculate model spectra.\n '''\n\n # _model = self.template[0][self.ntemp[0]]\n\n # logging.debug('Building model spectra')\n\n dopCor = np.sqrt((1.0 + self.vel[0] / _c_kms) / (1. - self.vel[0] / _c_kms))\n scale = self.scale[0][self.ntemp[0]] * self.templateScale[0][self.ntemp[0]]\n\n # print dopCor, scale, len(self.template[0][self.ntemp[0]].x), len(self.template[0][self.ntemp[0]].flux)\n # _model = MySpectrum(self.template[0][self.ntemp[0]].x * dopCor,\n # self.template[0][self.ntemp[0]].flux * scale)\n\n _model = MySpectrum(*MySpectrum(self.template[0][self.ntemp[0]].x * dopCor,\n self.template[0][self.ntemp[0]].flux * scale).myResample(self.ospec.x, replace=False))\n\n # logging.debug('Applying instrument signature')\n\n # kernel = self.obsRes()/np.mean(_model.x[1:]-_model.x[:-1])\n\n # _model.flux = scipy.ndimage.filters.gaussian_filter(_model.flux,kernel)\n\n\n for i in range(1, self.nspec):\n dopCor = np.sqrt((1.0 + self.vel[i] / _c_kms) / (1. - self.vel[i] / _c_kms))\n scale = self.scale[i][self.ntemp[i]] * self.templateScale[i][self.ntemp[i]]\n # print dopCor, scale, len(self.template[i][self.ntemp[i]].x), len(self.template[i][self.ntemp[i]].flux)\n # tmp = MySpectrum(self.template[i][self.ntemp[i]].x * dopCor,\n # self.template[i][self.ntemp[i]].flux * scale)\n\n # logging.debug('Applying instrument signature')\n\n # kernel = self.obsRes()/np.mean(tmp.x[1:]-tmp.x[:-1])\n\n # tmp.flux = scipy.ndimage.filters.gaussian_filter(tmp.flux,kernel)\n\n tmp = MySpectrum(*MySpectrum(self.template[i][self.ntemp[i]].x * dopCor,\n self.template[i][self.ntemp[i]].flux * scale).myResample(self.ospec.x, replace=False))\n\n _model.flux += tmp.flux\n\n '''\n if not _model.isLinear():\n logging.warning('Data must be linearized...')\n\n '''\n # kernel = self.obsRes()/tmp.getDx()/2./np.pi\n\n # _model.flux = scipy.ndimage.filters.gaussian_filter(_model.flux,kernel)\n\n # logging.debug('Resampling model spectra')\n # _model = MySpectrum(*_model.myResample(self.ospec.x, replace=False))\n if self._autoprop:\n mflux = np.mean(_model.flux)\n oflux = np.mean(self.ospec.flux)\n _model.flux *= (oflux / mflux)\n return _model\n\n ##################################################################\n\n def modelSpecThreadSafe(self, vel, scale, ntemp):\n '''\nCalculate model spectra.\n '''\n\n # _model = self.template[0][self.ntemp[0]]\n\n logging.debug('Building model spectra')\n\n dopCor = np.sqrt((1.0 + vel[0] / _c_kms) / (1. - vel[0] / _c_kms))\n scale = scale[0] * self.templateScale[0][ntemp[0]]\n\n _model = MySpectrum(self.template[0][ntemp[0]].x * dopCor,\n self.template[0][ntemp[0]].flux * scale)\n\n # logging.debug('Applying instrument signature')\n\n # kernel = self.obsRes()/np.mean(_model.x[1:]-_model.x[:-1])\n\n # _model.flux = scipy.ndimage.filters.gaussian_filter(_model.flux,kernel)\n\n\n for i in range(1, self.nspec):\n dopCor = np.sqrt((1.0 + vel[i] / _c_kms) / (1. - vel[i] / _c_kms))\n scale = scale[i] * self.templateScale[i][ntemp[i]]\n\n tmp = MySpectrum(self.template[i][ntemp[i]].x * dopCor,\n self.template[i][ntemp[i]].flux * scale)\n\n # logging.debug('Applying instrument signature')\n\n # kernel = self.obsRes()/np.mean(tmp.x[1:]-tmp.x[:-1])\n\n # tmp.flux = scipy.ndimage.filters.gaussian_filter(tmp.flux,kernel)\n\n tmp = MySpectrum(*tmp.resample(_model.x, replace=False))\n\n _model.flux += tmp.flux\n\n '''\n if not _model.isLinear():\n logging.warning('Data must be linearized...')\n\n '''\n # kernel = self.obsRes()/tmp.getDx()/2./np.pi\n\n # _model.flux = scipy.ndimage.filters.gaussian_filter(_model.flux,kernel)\n\n logging.debug('Resampling model spectra')\n _model = MySpectrum(*_model.myResample(self.ospec.x, replace=False))\n return _model\n\n ##################################################################\n\n def normTemplate(self, ncomp, w0, w1):\n '''\nNormalize spectra against data in the wavelenght regions\n '''\n\n for i in range(len(self.template[ncomp])):\n maskt = np.bitwise_and(self.template[ncomp][i].x > w0,\n self.template[ncomp][i].x < w1)\n mask0 = np.bitwise_and(self.ospec.x > w0,\n self.ospec.x < w1)\n\n scale = np.mean(self.ospec.flux[mask0]) / np.mean(self.template[ncomp][i].flux[maskt])\n\n self.templateScale[ncomp][i] = scale\n # self.template[ncomp][i].flux *= scale\n\n ##################################################################\n\n def gaussian_filter(self, ncomp, kernel):\n\n for i in range(len(self.template[ncomp])):\n if not self.template[ncomp][i].isLinear():\n logging.warning('Spectra must be linearized for gaussian filter...')\n\n self.template[ncomp][i].flux = scipy.ndimage.filters.gaussian_filter(self.template[ncomp][i].flux, kernel)\n\n ##################################################################\n\n def obsRes(self):\n return self.ospec.getDx()\n\n ##################################################################\n\n def preprocTemplate(self):\n '''\nPre-process all template spectra to have aproximate coordinates as\nthose of the observed spectrum and linearize the spectrum.\n '''\n\n logging.debug('Preprocessing all template spectra. Spectra will be trimmed and linearized')\n\n ores = self.obsRes()\n\n xmin = np.max([self.template[0][0].x[0], self.ospec.x[0] - 100.0 * ores])\n xmax = np.min([self.template[0][0].x[-1], self.ospec.x[-1] + 100.0 * ores])\n\n for i in range(self.nspec):\n for j in range(len(self.template[i])):\n # t_res = np.mean(self.template[i][j].x[1:]-self.template[i][j].x[:-1])\n # newx = np.arange(xmin,xmax,t_res)\n # self.template[i][j] = spec.Spectrum(*self.template[i][j].resample(newx,replace=False))\n\n self.template[i][j].linearize(lower=xmin, upper=xmax)\n\n tmp_spres = np.mean(self.template[i][j].x[1:] - self.template[i][j].x[:-1])\n logging.debug('Template spres = %f' % (tmp_spres))\n logging.debug('Data spres = %f' % (ores))\n\n if tmp_spres < ores / 10.:\n logging.debug('Template spectroscopic resolution too high! Resampling...')\n newx = np.arange(xmin, xmax, ores / 10.)\n self.template[i][j] = spec.Spectrum(*self.template[i][j].resample(newx, replace=False))\n\n ##################################################################\n\n def saveTemplates2Pickle(self, ncomp, filename):\n\n splist = np.loadtxt(filename, unpack=True, usecols=(0,),\n dtype='S', ndmin=1)\n\n logging.debug('Saving template spectra to pickle file...')\n\n for ntemp in range(len(self.template[ncomp])):\n logging.debug(splist[ntemp])\n sp = np.array([self.template[ncomp][ntemp].x,\n self.template[ncomp][ntemp].flux])\n np.save(splist[ntemp], sp)\n\n ##################################################################\n\n def suitableScale(self):\n '''\nFind a suitable scale values for all spectra.\n '''\n\n logging.debug('Looking for suitable scale in all spectra. Will choose the larger value.')\n\n obsmean = np.mean(self.ospec.flux)\n maxscale = 0.\n minscale = obsmean\n\n for i in range(len(self.template)):\n for j in range(len(self.template[i])):\n maskt = np.bitwise_and(self.template[i][j].x > self.ospec.x[0],\n self.template[i][j].x < self.ospec.x[-1])\n\n nscale = obsmean / np.mean(self.template[i][j].flux[maskt]) / self.templateScale[i][j]\n\n if maxscale < nscale:\n maxscale = nscale\n if minscale > nscale:\n minscale = nscale\n\n return maxscale, minscale\n\n ##################################################################\n\n def fit(self):\n '''\nFit spectra with least square fit.\n '''\n\n def score(p, x, y):\n for i in range(self.nspec):\n # self.vel[i] = p[i*self.nspec]\n # self.scale[i][self.ntemp[i]] = p[i*self.nspec+1]\n self.vel[i] = 0.\n self.scale[i][self.ntemp[i]] = p[i]\n\n return y-self.modelSpec().flux\n\n # pres, flag = leastsq(score, [self.vel[0], self.scale[0][self.ntemp[0]],\n # self.vel[1], self.scale[1][self.ntemp[1]]],\n # args=(self.ospec.x, self.ospec.flux))\n pres, flag = leastsq(score, [self.scale[0][self.ntemp[0]],\n self.scale[1][self.ntemp[1]]],\n args=(self.ospec.x, self.ospec.flux))\n\n return pres\n\n\n\n######################################################################\n\nclass MySpectrum(spec.Spectrum):\n def __init__(self, x, flux, err=None, ivar=None,\n unit='wl', name='', copy=True, sort=True):\n spec.Spectrum.__init__(self, x=x, flux=flux, err=err, ivar=ivar,\n unit=unit, name=name, copy=copy, sort=sort)\n\n ##################################################################\n\n def myResample(self, newx, replace=False):\n '''\n kernel = np.mean(newx[1:]-newx[:-1])/np.mean(self.x[1:]-self.x[:-1])\n\n dx = self.x[1:]-self.x[:-1]\n\n newy = scipy.ndimage.filters.gaussian_filter(self.flux,np.float(kernel))\n tck = scipy.interpolate.splrep(self.x,newy)\n newy2 =scipy.interpolate.splev(newx,tck)\n '''\n\n kernel = np.median(newx[1:] - newx[:-1]) / np.median(self.x[1:] - self.x[:-1]) #*4.0 #/2./np.pi\n\n newflux = scipy.ndimage.filters.gaussian_filter1d(self.flux, kernel)\n\n tck = scipy.interpolate.splrep(self.x, newflux)\n\n return newx, scipy.interpolate.splev(newx, tck)\n\n '''\n newy = np.zeros(len(newx))\n\n for i in range(len(newx)):\n xini = 0\n xend = 0\n\n if i == 0:\n xini = newx[i]-(newx[i+1]-newx[i])/2.\n else:\n xini = newx[i]-(newx[i]-newx[i-1])/2.\n\n if i == len(newx)-1:\n xend = newx[i]+(newx[i]-newx[i-1])/2.\n else:\n xend = newx[i]+(newx[i+1]-newx[i])/2.\n\n mask = np.bitwise_and(self.x > xini, self.x < xend)\n\n #newy[i] = np.sum( dx[mask[:-1]] * self.flux[mask] )\n newy[i] = np.mean(self.flux[mask])\n #print newx[i],newy[i],newy2[i],xini,xend, (xend-xini) , np.mean(self.flux[mask]),(xend-xini) * np.mean(self.flux[mask])\n #print self.x[mask],self.flux[mask],dx[mask[:-1]]\n\n\n\n return newx,newy #scipy.interpolate.splev(newx,tck)\n'''\n\n ##################################################################\n\n######################################################################\n","sub_path":"specfit/lib/specfit.py","file_name":"specfit.py","file_ext":"py","file_size_in_byte":21017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"387396563","text":"# -*- coding: utf-8 -*-\n\"\"\"Constants module.\"\"\"\n\nfrom typing import Any, Callable, Dict, List, Mapping, NamedTuple, Optional, Sequence # noqa: F401\n\nfrom xml.etree import ElementTree as ET\n\n\nNS = {\n 'soap_envelope': 'http://schemas.xmlsoap.org/soap/envelope/',\n 'device': 'urn:schemas-upnp-org:device-1-0',\n 'service': 'urn:schemas-upnp-org:service-1-0',\n 'event': 'urn:schemas-upnp-org:event-1-0',\n 'control': 'urn:schemas-upnp-org:control-1-0',\n}\n\nSTATE_VARIABLE_TYPE_MAPPING = {\n 'ui1': int,\n 'ui2': int,\n 'ui4': int,\n 'i1': int,\n 'i2': int,\n 'i4': int,\n 'int': int,\n 'r4': float,\n 'r8': float,\n 'number': float,\n 'fixed.14.4': float,\n 'float': float,\n 'char': str,\n 'string': str,\n 'boolean': bool,\n 'bin.base64': str,\n 'bin.hex': str,\n 'uri': str,\n 'uuid': str,\n} # type: Dict[str, Callable[[str], Any]]\n\nDeviceInfo = NamedTuple('DeviceInfo', [\n ('device_type', str),\n ('friendly_name', str),\n ('manufacturer', str),\n ('model_name', str),\n ('model_number', Optional[str]),\n ('model_description', Optional[str]),\n ('udn', str),\n ('url', str),\n ('xml', ET.Element),\n])\n\nServiceInfo = NamedTuple('ServiceInfo', [\n ('service_id', str),\n ('service_type', str),\n ('control_url', str),\n ('event_sub_url', str),\n ('scpd_url', str),\n ('xml', ET.Element),\n])\n\nActionArgumentInfo = NamedTuple('ActionArgumentInfo', [\n ('name', str),\n ('direction', str),\n ('state_variable_name', str),\n ('xml', ET.Element),\n])\n\nActionInfo = NamedTuple('ActionInfo', [\n ('name', str),\n ('arguments', Sequence[ActionArgumentInfo]),\n ('xml', ET.Element),\n])\n\nStateVariableTypeInfo = NamedTuple('StateVariableTypeInfo', [\n ('data_type', str),\n ('data_type_python', Callable[[str], Any]),\n ('default_value', Optional[str]),\n ('allowed_value_range', Mapping[str, Optional[str]]),\n ('allowed_values', Optional[List[str]]),\n ('xml', ET.Element),\n])\n\nStateVariableInfo = NamedTuple('StateVariableInfo', [\n ('name', str),\n ('send_events', bool),\n ('type_info', StateVariableTypeInfo),\n ('xml', ET.Element),\n])\n","sub_path":"async_upnp_client/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"455470305","text":"from configparser import ConfigParser\nfrom django.conf import settings\nfrom django.core.cache import cache\nfrom os.path import abspath, dirname, isfile, join as pjoin\nfrom os import environ\n\n\n_inis = [\n pjoin(dirname(abspath(__file__)), 'config', 'config.ini'),\n pjoin(dirname(abspath(__file__)), 'config', 'agent-profile', environ.get('AGENT_PROFILE') + '.ini')\n]\n\ndef init_config():\n global _inis\n if cache.get('config') == None:\n if all(isfile(ini) for ini in _inis):\n parser = ConfigParser()\n for ini in _inis: \n parser.read(ini)\n cache.set(\n 'config',\n {s: dict(parser[s].items()) for s in parser.sections()})\n else:\n raise FileNotFoundError('Configuration file(s) mission; check {}'.format(_inis))\n return cache.get('config')\n","sub_path":"service_wrapper_project/wrapper_api/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"548991050","text":"import os\r\nimport random\r\nimport sys\r\n\r\n\r\ndef base36encode(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'):\r\n base36 = ''\r\n sign = ''\r\n if number < 0:\r\n sign = '-'\r\n number = -number\r\n if 0 <= number < len(alphabet):\r\n return sign + alphabet[number]\r\n while number != 0:\r\n number, i = divmod(number, len(alphabet))\r\n base36 = alphabet[i] + base36\r\n return sign + base36\r\n\r\ndef generateKey():\r\n lengthOfKey = input(\"How many caracters you want to have in your key ?\")\r\n keyCache = \"\"\r\n for key in range(lengthOfKey): \r\n keyCache += random.choice('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ')\r\n return keyCache\r\n\r\n\r\ndef KeyParser(EncryptedKey):\r\n x1 = 0\r\n x2 = 0\r\n for value in range(len(EncryptedKey)):\r\n if value%2 == 0:\r\n x1 += int(EncryptedKey[value], 36)\r\n else:\r\n x2 += int(EncryptedKey[value], 36)\r\n return x1, x2\r\n\r\n\r\ndef main():\r\n choice = input(\r\n 'Do you want to decrypt or encrypt, choose \"1\" for decrypt and \"2\" for encrypt')\r\n if (choice != '1') and (choice != '2'):\r\n print(\"You didn't choose between 1 or 2...\")\r\n main()\r\n else:\r\n if choice == '1':\r\n method = 'decrypt'\r\n if choice == '2':\r\n method = 'encrypt'\r\n baseNumber = input('In which base do you want to {0} ?', format(method))\r\n print('What do you want to ' + method)\r\n textinput = input()\r\n arrayToProcess = []\r\n arrayWord = list(textinput)\r\n if method == 'encrypt':\r\n for i in range(len(arrayWord)):\r\n randomnessLenght = False\r\n lenCount = 0\r\n while(randomnessLenght != True):\r\n if random.random() > 0.5:\r\n lenCount += 1\r\n else:\r\n randomnessLenght = True\r\n charactersToArray = \"\"\r\n for ArrayMake in range(lenCount):\r\n charactersToArray += arrayWord[i]\r\n i += 1\r\n arrayToProcess.append([charactersToArray,obfuscateCount,lenCount])\r\n EncryptedKey = input(\"Tell the key you want to use for encrypting, if you want to generate a random key just press ENTER. (Enter Only AlphaNumerical Caracters, Minimum 2 caracters.)\")\r\n if EncryptedKey == \"\":\r\n EncryptedKey = generateKey()\r\n x1, x2 = KeyParser(EncryptedKey)\r\n messageEncrypted = \"\"\r\n specificLastHeader = \"\"\r\n for index, ArrayInstruction in enumerate(arrayToProcess):\r\n StartCodon = (x1 * x2 + pow(index, 2)) / pow(index, 2) # check base taille\r\n EndCodon = (x1 * x2 + pow(index + ArrayInstruction[2], 2)) / pow(index + ArrayInstruction[2], 2) # check base taille\r\n messageEncrypted += base36encode(StartCodon)\r\n for iterationToTranslate in range(ArrayInstruction[2]):\r\n MessagerAdderFirstPart = (pow((index + iterationToTranslate), 2) / (pow(index + ArrayInstruction[2], 2) + pow(index, 2)))\r\n MessagerAdderLastPart = (1 / (1 + pow((index + iterationToTranslate), 2)))\r\n DecimalValueMessageToAdd = (StartCodon * EndCodon + MessagerAdderFirstPart) * MessagerAdderLastPart\r\n messageEncrypted += base36encode(DecimalValueMessageToAdd)\r\n # check la base\r\n messageEncrypted += base36encode(EndCodon)\r\n if method == 'decrypt':\r\n print(\"Incomming\")\r\n \r\n # base à completer avec OPCODE au debut specififier ligne et Nombre de fois du maximum\r\n\r\n\r\nmain()\r\n","sub_path":"main.1.py","file_name":"main.1.py","file_ext":"py","file_size_in_byte":3562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"490065836","text":"import os\nimport re\nimport flask\nimport json\nfrom indexd.errors import AuthError, AuthzError\nfrom indexd.errors import UserError\nfrom indexd.index.errors import NoRecordFound as IndexNoRecordFound\nfrom indexd.errors import IndexdUnexpectedError\nfrom indexd.utils import reverse_url\n\nblueprint = flask.Blueprint(\"drs\", __name__)\n\nblueprint.config = dict()\nblueprint.index_driver = None\nblueprint.service_info = {}\n\n\n@blueprint.route(\"/ga4gh/drs/v1/service-info\", methods=[\"GET\"])\ndef get_drs_service_info():\n \"\"\"\n Returns DRS compliant service information\n \"\"\"\n\n reverse_domain_name = reverse_url(url=os.environ[\"HOSTNAME\"])\n\n ret = {\n \"id\": reverse_domain_name,\n \"name\": \"DRS System\",\n \"version\": \"1.0.3\",\n \"type\": {\n \"group\": \"org.ga4gh\",\n \"artifact\": \"drs\",\n \"version\": \"1.0.3\",\n },\n \"organization\": {\n \"name\": \"CTDS\",\n \"url\": \"https://\" + os.environ[\"HOSTNAME\"],\n },\n }\n\n if blueprint.service_info:\n for key, value in blueprint.service_info.items():\n if key in ret:\n if isinstance(value, dict):\n for inner_key, inner_value in value.items():\n ret[key][inner_key] = inner_value\n else:\n ret[key] = value\n\n return flask.jsonify(ret), 200\n\n\n@blueprint.route(\"/ga4gh/drs/v1/objects/\", methods=[\"GET\"])\ndef get_drs_object(object_id):\n \"\"\"\n Returns a specific DRSobject with object_id\n \"\"\"\n expand = True if flask.request.args.get(\"expand\") == \"true\" else False\n\n ret = blueprint.index_driver.get_with_nonstrict_prefix(object_id)\n\n data = indexd_to_drs(ret, expand=expand)\n\n return flask.jsonify(data), 200\n\n\n@blueprint.route(\"/ga4gh/drs/v1/objects\", methods=[\"GET\"])\ndef list_drs_records():\n limit = flask.request.args.get(\"limit\")\n start = flask.request.args.get(\"start\")\n page = flask.request.args.get(\"page\")\n\n form = flask.request.args.get(\"form\")\n\n try:\n limit = 100 if limit is None else int(limit)\n except ValueError as err:\n raise UserError(\"limit must be an integer\")\n\n if limit < 0 or limit > 1024:\n raise UserError(\"limit must be between 0 and 1024\")\n\n if page is not None:\n try:\n page = int(page)\n except ValueError as err:\n raise UserError(\"page must be an integer\")\n\n if form == \"bundle\":\n records = blueprint.index_driver.get_bundle_list(\n start=start, limit=limit, page=page\n )\n elif form == \"object\":\n records = blueprint.index_driver.ids(start=start, limit=limit, page=page)\n else:\n records = blueprint.index_driver.get_bundle_and_object_list(\n start=start, limit=limit, page=page\n )\n ret = {\n \"drs_objects\": [indexd_to_drs(record, True) for record in records],\n }\n\n return flask.jsonify(ret), 200\n\n\ndef create_drs_uri(did):\n \"\"\"\n Return ga4gh-compilant drs format uri\n\n Args:\n did(str): did of drs object\n \"\"\"\n\n default_prefix = blueprint.index_driver.config.get(\"DEFAULT_PREFIX\")\n\n if not default_prefix:\n # For env without DEFAULT_PREFIX, uri will not be drs compliant\n accession = did\n self_uri = \"drs://{}\".format(accession)\n else:\n accession = (\n did.replace(default_prefix, \"\", 1).replace(\"/\", \"\", 1).replace(\":\", \"\", 1)\n )\n\n self_uri = \"drs://{}:{}\".format(\n default_prefix.replace(\"/\", \"\", 1).replace(\":\", \"\", 1), accession\n )\n\n return self_uri\n\n\ndef indexd_to_drs(record, expand=False):\n \"\"\"\n Convert record to ga4gh-compilant format\n\n Args:\n record(dict): json object record\n expand(bool): show contents of the descendants\n \"\"\"\n\n did = (\n record[\"id\"]\n if \"id\" in record\n else record[\"did\"]\n if \"did\" in record\n else record[\"bundle_id\"]\n )\n\n self_uri = create_drs_uri(did)\n\n name = record[\"file_name\"] if \"file_name\" in record else record[\"name\"]\n\n index_created_time = (\n record[\"created_date\"] if \"created_date\" in record else record[\"created_time\"]\n )\n\n version = (\n record[\"version\"]\n if \"version\" in record\n else record[\"rev\"]\n if \"rev\" in record\n else \"\"\n )\n\n index_updated_time = (\n record[\"updated_date\"] if \"updated_date\" in record else record[\"updated_time\"]\n )\n\n content_created_date = record.get(\"content_created_date\", \"\")\n\n content_updated_date = record.get(\"content_updated_date\", \"\")\n\n form = record[\"form\"] if \"form\" in record else \"bundle\"\n\n description = record[\"description\"] if \"description\" in record else None\n\n alias = (\n record[\"alias\"]\n if \"alias\" in record\n else json.loads(record[\"aliases\"])\n if \"aliases\" in record\n else []\n )\n\n drs_object = {\n \"id\": did,\n \"mime_type\": \"application/json\",\n \"name\": name,\n \"index_created_time\": index_created_time,\n \"index_updated_time\": index_updated_time,\n \"created_time\": content_created_date,\n \"updated_time\": content_updated_date,\n \"size\": record[\"size\"],\n \"aliases\": alias,\n \"self_uri\": self_uri,\n \"version\": version,\n \"form\": form,\n \"checksums\": [],\n \"description\": description,\n }\n\n if \"description\" in record:\n drs_object[\"description\"] = record[\"description\"]\n\n if \"bundle_data\" in record:\n drs_object[\"contents\"] = []\n for bundle in record[\"bundle_data\"]:\n bundle_object = bundle_to_drs(bundle, expand=expand, is_content=True)\n if not expand:\n bundle_object.pop(\"contents\", None)\n drs_object[\"contents\"].append(bundle_object)\n\n # access_methods mapping\n if \"urls\" in record:\n drs_object[\"access_methods\"] = []\n for location in record[\"urls\"]:\n location_type = location.split(\":\")[\n 0\n ] # (s3, gs, ftp, gsiftp, globus, htsget, https, file)\n\n drs_object[\"access_methods\"].append(\n {\n \"type\": location_type,\n \"access_url\": {\"url\": location},\n \"access_id\": location_type,\n \"region\": \"\",\n }\n )\n\n # parse out checksums\n drs_object[\"checksums\"] = parse_checksums(record, drs_object)\n\n return drs_object\n\n\ndef bundle_to_drs(record, expand=False, is_content=False):\n \"\"\"\n record(dict): json object record\n expand(bool): show contents of the descendants\n is_content: is an expanded content in a bundle\n \"\"\"\n\n did = (\n record[\"id\"]\n if \"id\" in record\n else record[\"did\"]\n if \"did\" in record\n else record[\"bundle_id\"]\n )\n\n drs_uri = create_drs_uri(did)\n\n name = record[\"file_name\"] if \"file_name\" in record else record[\"name\"]\n\n drs_object = {\n \"id\": did,\n \"name\": name,\n \"drs_uri\": drs_uri,\n \"contents\": [],\n }\n\n contents = (\n record[\"contents\"]\n if \"contents\" in record\n else record[\"bundle_data\"]\n if \"bundle_data\" in record\n else []\n )\n\n if not expand and isinstance(contents, list):\n for content in contents:\n if isinstance(content, dict):\n content.pop(\"contents\", None)\n\n drs_object[\"contents\"] = contents\n\n if not is_content:\n # Show these only if its the leading bundle\n description = record[\"description\"] if \"description\" in record else \"\"\n aliases = (\n record[\"alias\"]\n if \"alias\" in record\n else json.loads(record[\"aliases\"])\n if \"aliases\" in record\n else []\n )\n version = (\n record[\"version\"]\n if \"version\" in record\n else record[\"rev\"]\n if \"rev\" in record\n else \"\"\n )\n # version = record[\"version\"] if \"version\" in record else \"\"\n drs_object[\"checksums\"] = parse_checksums(record, drs_object)\n\n created_time = (\n record[\"created_date\"]\n if \"created_date\" in record\n else record.get(\"created_time\")\n )\n\n updated_time = (\n record[\"updated_date\"]\n if \"updated_date\" in record\n else record.get(\"updated_time\")\n )\n if created_time:\n drs_object[\"created_time\"] = created_time\n if updated_time:\n drs_object[\"updated_time\"] = updated_time\n drs_object[\"size\"] = record[\"size\"]\n drs_object[\"aliases\"] = aliases\n drs_object[\"description\"] = description\n drs_object[\"version\"] = version\n\n return drs_object\n\n\ndef parse_checksums(record, drs_object):\n \"\"\"\n Create valid checksums format from a DB object -\n either a record (\"hashes\") or a bundle (\"checksum\")\n \"\"\"\n ret_checksum = []\n if \"hashes\" in record:\n for k in record[\"hashes\"]:\n ret_checksum.append({\"checksum\": record[\"hashes\"][k], \"type\": k})\n elif \"checksum\" in record:\n try:\n checksums = json.loads(record[\"checksum\"])\n except json.decoder.JSONDecodeError:\n # TODO: Remove the code after fixing the record[\"checksum\"] format\n checksums = [{\"checksum\": record[\"checksum\"], \"type\": \"md5\"}]\n for checksum in checksums:\n ret_checksum.append(\n {\"checksum\": checksum[\"checksum\"], \"type\": checksum[\"type\"]}\n )\n return ret_checksum\n\n\n@blueprint.errorhandler(UserError)\ndef handle_user_error(err):\n ret = {\"msg\": str(err), \"status_code\": 400}\n return flask.jsonify(ret), 400\n\n\n@blueprint.errorhandler(AuthzError)\ndef handle_authz_error(err):\n ret = {\"msg\": str(err), \"status_code\": 401}\n return flask.jsonify(ret), 401\n\n\n@blueprint.errorhandler(AuthError)\ndef handle_requester_auth_error(err):\n ret = {\"msg\": str(err), \"status_code\": 403}\n return flask.jsonify(ret), 403\n\n\n@blueprint.errorhandler(IndexNoRecordFound)\ndef handle_no_index_record_error(err):\n ret = {\"msg\": str(err), \"status_code\": 404}\n return flask.jsonify(ret), 404\n\n\n@blueprint.errorhandler(IndexdUnexpectedError)\ndef handle_unexpected_error(err):\n ret = {\"msg\": err.message, \"status_code\": err.code}\n return flask.jsonify(ret), err.code\n\n\n@blueprint.record\ndef get_config(setup_state):\n index_config = setup_state.app.config[\"INDEX\"]\n blueprint.index_driver = index_config[\"driver\"]\n\n\n@blueprint.record\ndef get_config(setup_state):\n if \"DRS_SERVICE_INFO\" in setup_state.app.config:\n blueprint.service_info = setup_state.app.config[\"DRS_SERVICE_INFO\"]\n","sub_path":"indexd/drs/blueprint.py","file_name":"blueprint.py","file_ext":"py","file_size_in_byte":10751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"204436721","text":"# THIS CODE ISN'T WORKING YET\n\nimport numpy as np\n\n\ndef permutation_matrix_3d (res : int = 25, other_params : int = 0, param_seperated : bool = False):\n cols = 3 + other_params\n # We'll make all other parameters vary together from 0 to 1. This will originate the animation. If other_params = 1, this creates a full view of the universe, if other_params > 1 this will no longer be the case, and will only give a slightly more detailed view of the first 3 params as the other other_params change from 0 to 1 (in unison)\n if other_params > 0:\n rows = res**4\n perm_matrix = np.zeros((res,res,res,res,cols))\n perm_matrix[:,:,:,:,0] = np.linspace(0,1,res)\n perm_matrix[:,:,:,:,1] = np.linspace(np.zeros((res,)),np.ones((res,)),res)\n perm_matrix[:,:,:,:,2] = np.linspace(np.zeros((res,res)),np.ones((res,res)),res)\n perm_matrix[:,:,:,:,3:] = np.linspace(np.zeros((res,res,res,other_params)),np.ones((res,res,res,other_params)),res)\n else:\n rows = res**3\n perm_matrix = np.zeros((res,res,res,3))\n perm_matrix[:,:,:,0] = np.linspace(0,1,res)\n perm_matrix[:,:,:,1] = np.linspace(np.zeros((res,)),np.ones((res,)),res)\n perm_matrix[:,:,:,2] = np.linspace(np.zeros((res,res)),np.ones((res,res)),res)\n #this convoluted shape was only created in order to use numpy's speed, with linspace, we can now use a shape that is actually convenient for us:\n perm_matrix = np.reshape(perm_matrix, (rows, cols))\n return perm_matrix\n\n\ndef add_radius_flag (input : np.ndarray, center : np.ndarray = None):\n \"\"\"\n For each point we want to do:\n (x-x_center)^2 + (y-y_center)^2 + (z-z_center)^2 <= r^2?\n if yes: append 'True' flag\n if no: append 'False' flag\n \"\"\"\n if center is None:\n center = np.array((0.5,0.5,0.5))\n pass\n\n flags = ((input[:,0]-center[0])**2 + (input[:,1]-center[1])**2 + (input[:,2]-center[2])**2) <= input[:,3]\n flags = np.array(flags, dtype=int)\n flags[flags==0] = -1\n flags = flags.reshape((flags.shape[0],1))\n new_arr = np.concatenate((input,flags), axis=1)\n return new_arr\n\n\ndef animate_sphere (res : int = 10, fps:int = 10) -> None:\n to_plot = add_radius_flag(permutation_matrix_3d(res, 1))\n to_plot = np.split(to_plot, res)\n\n import matplotlib.pyplot as plt\n\n fig = plt.figure()\n ax = fig.add_subplot(projection='3d')\n ln, = ax.plot_surface([],[],[],alpha=0.5)\n \n up = np.array(range(res-1))\n down = np.array(range(res))\n down = down[:0:-1]\n frames = np.concatenate((up,down))\n\n frame_text = ax.text(-0.1, -0.1, -0.1, \"\")\n params_text = ax.text(0.2, -0.1, -0.1, \"\")\n\n def init_graph():\n ax.set_xlim3d(0, 1)\n ax.set_ylim3d(0, 1)\n ax.set_zlim3d(0, 1)\n return ln,\n\n def update(frame):\n frame_text.set_text (\"Frame: \" + str((frame+1)%(len(up)+2)) + \"/\" + str(len(up)+1))\n params_text.set_text (\"Param Values: \" + str((frame+1)%(len(up)+2)) + \"/\" + str(len(up)+1))\n this_frame = to_plot[frame]\n params_text.set_text (\"Radius: \" + \"{0:.3f}\".format(this_frame[0,-2]))\n inside_sphere = this_frame[this_frame[:,4] == 1]\n\n xdata = inside_sphere[:,0]\n ydata = inside_sphere[:,1]\n zdata = inside_sphere[:,2]\n ln.set_data_3d(xdata, ydata, zdata)\n return ln,\n\n from matplotlib.animation import FuncAnimation\n anim = FuncAnimation(fig=fig,\n func=update,\n frames=frames, \n init_func=init_graph,\n interval=max(int(1000/fps),1))\n plt.show()\n pass\n\n\nif __name__ == '__main__':\n perm_matrix = animate_sphere(25, fps=10)\n","sub_path":"AnimatedPlots/my_attempt_3d_surface.py","file_name":"my_attempt_3d_surface.py","file_ext":"py","file_size_in_byte":3705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"321564921","text":"from BioLib import *\nimport optparse, os, sys, random\nimport numpy as np\n\ndef parse_options():\n '''\n Parse arguments\n @return options object\n '''\n parser = optparse.OptionParser('analyze_byprotein.py -i PPI_FILE -j JOB_PATH [-v]')\n parser.add_option(\"-i\", dest=\"ppi_file\", action=\"store\", help=\"The ppi file [MANDATORY]\", metavar=\"PPI_FILE\")\n parser.add_option(\"-j\", dest=\"job_path\", action=\"store\", help=\"Job path [MANDATORY]\", metavar=\"JOB_PATH\")\n parser.add_option(\"-v\", dest=\"verbose\", action=\"store_true\", help=\"Verbose\", metavar=\"VERBOSE\")\n\n (options, args) = parser.parse_args()\n if options.ppi_file == None or options.job_path == None:\n parser.error('Missing arguments\\n')\n return options\n\nclass AnalyzePPI(object):\n '''\n Get the scores of each decoy for each protein-protein interaction and analyze the\n diferent locations\n '''\n def __init__(self, ppi_file, job_path, verbose):\n '''\n Contructor\n '''\n self.ppi_file = ppi_file\n self.job_path = job_path\n self.verbose = verbose\n \n def run(self):\n '''\n Runs the computations\n '''\n ppi_fo = open(self.ppi_file, 'r')\n energies_print = []\n for ppi in ppi_fo:\n ppi_type = ppi.strip('\\n').split('\\t')[1]\n if ppi_type[0] != 'E' and ppi_type != 'OX':\n continue\n ppi = ppi.strip('\\n').split('\\t')[0][0:4]\n try:\n ppi_results = self.__on_interaction(ppi)\n energies_print.append(ppi_results)\n if self.verbose:\n sys.stdout.write('[\\033[92mSUCCESS\\033[0m]\\n')\n sys.stdout.flush()\n except RuntimeError as e:\n if self.verbose:\n sys.stdout.write('[\\033[91mFAIL\\033[0m] %s\\n' % str(e))\n sys.stdout.flush()\n ppi_fo.close()\n self.__print(energies_print)\n\n def __on_interaction(self, ppi):\n '''\n Computations for each ppi\n '''\n if self.verbose:\n sys.stdout.write('PPI %s --> ' % ppi)\n sys.stdout.flush()\n # Get the energies by location #\n try:\n location_decoys = self.__get_location_decoys(ppi)\n except RuntimeError as e:\n raise e\n if not location_decoys['N'] or not location_decoys['I'] or not location_decoys['P'] or not location_decoys['E']:\n raise RuntimeError('NO NATIVE, INTERFACE, PARTIAL OR EXTERNAL DECOYS')\n try:\n fiberdock_energies = self.__get_energies(ppi, location_decoys, 'fiberdock')\n sp_energies = self.__get_energies(ppi, location_decoys, 'rmsd_splitpotentials')\n except Exception as e:\n raise e\n # Compute average macrostate energies #\n macrostate_N = np.concatenate((np.mean(fiberdock_energies['N'], axis=0), \n np.mean(sp_energies['N'], axis=0),\n np.std(fiberdock_energies['N'], axis=0),\n np.std(sp_energies['N'], axis=0)))\n macrostate_I = np.concatenate((np.mean(fiberdock_energies['I'], axis=0), \n np.mean(sp_energies['I'], axis=0),\n np.std(fiberdock_energies['I'], axis=0),\n np.std(sp_energies['I'], axis=0)))\n macrostate_P = np.concatenate((np.mean(fiberdock_energies['P'], axis=0), \n np.mean(sp_energies['P'], axis=0),\n np.std(fiberdock_energies['P'], axis=0),\n np.std(sp_energies['P'], axis=0)))\n macrostate_E = np.concatenate((np.mean(fiberdock_energies['E'], axis=0), \n np.mean(sp_energies['E'], axis=0),\n np.std(fiberdock_energies['E'], axis=0),\n np.std(sp_energies['E'], axis=0)))\n return ppi, macrostate_N, macrostate_I, macrostate_P, macrostate_E\n\n def __get_rmsd(self, ppi):\n '''\n Get the RMSD for ach decoy using the sp_iLoops_energies file\n '''\n # Check if needed files exists #\n rmsd_path = os.path.join(self.job_path, ppi, 'rmsd_splitpotentials.txt')\n if not os.path.isfile(rmsd_path):\n raise RuntimeError('NO RMSD FILE FOUND')\n # Get rmsd #\n rmsd_decoys = {}\n rmsd_decoys_fo = open(rmsd_path, 'r')\n for decoy in rmsd_decoys_fo:\n decoy = decoy.strip().split('\\t')\n rmsd_decoys[decoy[0]] = float(decoy[1])\n rmsd_decoys_fo.close()\n return rmsd_decoys\n\n def __get_location_decoys(self, ppi):\n '''\n Get the decoys for each location\n '''\n # Check if needed files exists #\n decoys_location_path = os.path.join(self.job_path, ppi, 'decoys_location.txt')\n if not os.path.isfile(decoys_location_path):\n raise RuntimeError('NO DECOYS LOCATION FILE FOUND')\n # Get rmsds #\n location_decoys = {'N': [],'I': [], 'P': [], 'E': []}\n try:\n rmsd_decoys = self.__get_rmsd(ppi)\n except RuntimeError as e:\n raise e\n # Get location decoys #\n decoys_locations_fo = open(decoys_location_path, 'r')\n for decoy in decoys_locations_fo:\n decoy = decoy.strip('\\n').split('\\t')\n if not decoy[0] in rmsd_decoys:\n continue\n if rmsd_decoys[decoy[0]] < 10:\n location_decoys['N'].append(decoy[0])\n else:\n location_decoys[decoy[1]].append(decoy[0])\n decoys_locations_fo.close()\n return location_decoys\n\n def __get_energies(self, ppi, location_decoys, etype, zscores=False):\n '''\n Gets the energies for each location\n etype: fiberdock, sp or iLoops for choosing the energie type\n '''\n if etype == 'fiberdock':\n separator = '|'\n min_e = 1\n max_e = 11\n energies_path = os.path.join(self.job_path, ppi, '%s_energies.txt' % etype)\n energies_path_ref = os.path.join(self.job_path, ppi, '%s_energies.ref' % etype)\n if os.path.isfile(energies_path_ref):\n energies_path = energies_path_ref\n else:\n separator = '\\t'\n min_e = 2\n max_e = None\n energies_path = os.path.join(self.job_path, ppi, '%s.txt' % etype)\n if not os.path.isfile(energies_path):\n raise RuntimeError('NO %s ENERGIES FILE FOUND' % etype.upper())\n # Get energies #\n energies = {'N': [], 'I': [], 'P': [], 'E': []}\n energies_fo = open(energies_path, 'r')\n for decoy in energies_fo:\n decoy = decoy.strip('\\n').split(separator)\n if decoy[0].strip() in location_decoys['N']:\n energies['N'].append([float(energy.strip()) for energy in decoy[min_e:max_e]])\n if decoy[0].strip() in location_decoys['I']:\n energies['I'].append([float(energy.strip()) for energy in decoy[min_e:max_e]])\n if decoy[0].strip() in location_decoys['P']:\n energies['P'].append([float(energy.strip()) for energy in decoy[min_e:max_e]])\n if decoy[0].strip() in location_decoys['E']:\n energies['E'].append([float(energy.strip()) for energy in decoy[min_e:max_e]])\n energies_fo.close()\n if zscores:\n all_energies = energies['N']+energies['I']+energies['P']+energies['E']\n zenergies = {'N': [], 'I': [], 'P': [], 'E': []}\n zmean = np.nanmean(all_energies, axis=0)\n zstd = np.nanstd(all_energies, axis=0)\n for loc in energies:\n for decoy in energies[loc]:\n zenergies[loc].append((decoy-zmean)/zstd)\n return zenergies\n else:\n return energies\n\n def __print(self, energies):\n '''\n Print the resultant energies\n '''\n ene_fo = open('scores_locations_E+OX_std.txt' , 'w')\n for energie in energies:\n ene_fo.write('%s\\t' % energie[0])\n for x in xrange(len(energie[1])):\n ene_fo.write('%.2f\\t%.2f\\t%.2f\\t%.2f' % (energie[1][x], energie[2][x], energie[3][x], energie[4][x]))\n if x < len(energie[1])-1:\n ene_fo.write('\\t')\n ene_fo.write('\\n')\n ene_fo.close()\n\n#--------------------------#\n# MAIN #\n#--------------------------#\n\nif __name__ == \"__main__\":\n\n options = parse_options()\n\n ppi_file = os.path.abspath(options.ppi_file)\n job_path = os.path.abspath(options.job_path)\n \n analyze_ppi = AnalyzePPI(ppi_file, job_path, options.verbose) \n analyze_ppi.run()\n","sub_path":"src/Binding_Mechanism_Docking/analyze_scores.py","file_name":"analyze_scores.py","file_ext":"py","file_size_in_byte":8910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"319242429","text":"# Created by L.S. Urrea [lurreaferia@uniminuto.edu.co], J. Sanchez-Rojas [jsanchezro8@uniminuto.edu.co], & C.A.Sierra [carlos.andres.sierra.v@gmail.com] on May 2019.\n\n# Collaboration acknowlegments: María Fernanda Chaparro & Fernando Alvarez & Santiago Salazar.\n\n# Copyright (c) 2019 L.S. Urrea, J. Sanchez-Rojas, & C.A.Sierra. Research Group on Athenea. All rights reserved.\n\n#\n\n# This file is part of RaspXbee Project.\n\n#\n\n# RaspXbee Project is free software: you can redistribute it and/or modify it under the terms of the\n\n# GNU General Public License as published by the Free Software Foundation, version 3\n# Generated by Django 2.1.5 on 2019-06-08 22:15\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('appCode', '0005_auto_20190518_1633'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Cauce',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('velocidad', models.DecimalField(decimal_places=6, default=0.0, max_digits=10)),\n ('area', models.DecimalField(decimal_places=6, default=0.0, max_digits=10)),\n ('cauce', models.DecimalField(decimal_places=6, default=0.0, max_digits=10)),\n ('lluvia', models.DecimalField(decimal_places=6, default=0.0, max_digits=10)),\n ('fecha', models.DateField()),\n ('status', models.BooleanField(default='None', max_length=25)),\n ('nodo', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='appCode.Node')),\n ],\n ),\n migrations.AlterField(\n model_name='ethernet',\n name='gateway_fk',\n field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to='appCode.Gateway'),\n ),\n migrations.AlterField(\n model_name='node_gateway',\n name='gateway_fk',\n field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to='appCode.Gateway'),\n ),\n migrations.AlterField(\n model_name='simcard',\n name='gateway_fk',\n field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to='appCode.Gateway'),\n ),\n migrations.AlterField(\n model_name='wifi_gateway',\n name='gateway_fk',\n field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to='appCode.Gateway'),\n ),\n ]\n","sub_path":"appCode/migrations/0006_auto_20190608_1715.py","file_name":"0006_auto_20190608_1715.py","file_ext":"py","file_size_in_byte":2614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"15724459","text":"# -*- coding: utf-8 -*-\n# Copyright 2018 Mobicage NV\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# @@license_version:1.3@@\n\nimport datetime\nimport logging\n\nfrom google.appengine.ext import ndb\n\nfrom framework.utils import put_in_chunks, get_epoch_from_datetime\nfrom plugins.trash_calendar.consts import TrashCollector, TrashActivity, \\\n DEFAULT_COUNTRY\nfrom plugins.trash_calendar.models.common import UnconnectedStreet, Collection, Street\nfrom plugins.trash_calendar.utils import read_csv\n\n\ndef import_streets(country, collection_key, postal_code, stream):\n streets = read_csv(stream)\n logging.info(\"import_streets for %s has %s streets\", collection_key, len(streets))\n\n current_streets = {}\n for s in Street.list_by_postal_code(TrashCollector.IVLA, country, postal_code):\n for a in s.aliases:\n current_streets[a] = s.key\n\n to_put = []\n keys = [UnconnectedStreet.create_key(TrashCollector.IVLA, collection_key, s['Straat'])\n for s in streets]\n unconnected_streets = ndb.get_multi(keys)\n for s, us_key, unconnected_street in zip(streets, keys, unconnected_streets):\n if s['Straat'] in current_streets:\n continue\n if not unconnected_street:\n unconnected_street = UnconnectedStreet(key=us_key)\n unconnected_street.manual_conversion = False\n unconnected_street.country_code = DEFAULT_COUNTRY\n unconnected_street.collection_key = collection_key\n unconnected_street.name = s['Straat']\n unconnected_street.postal_code = s['Postcode']\n unconnected_street.city = s['Gemeente']\n to_put.append(unconnected_street)\n\n if to_put:\n logging.info('put %s items', len(to_put))\n put_in_chunks(to_put)\n\n\ndef import_collection_data(country, collection_key, year, stream):\n collections = read_csv(stream)\n logging.info(\"import_collection_data for %s has %s collections\", collection_key, len(collections))\n\n to_put = []\n for c in collections:\n activities = []\n for k, v in c.iteritems():\n if not v:\n continue\n activity = _get_activity_name(k)\n if not activity:\n continue\n activities.append(activity)\n\n if not activities:\n continue\n\n date = datetime.datetime.strptime(c['Datum'], '%b %d')\n epoch = get_epoch_from_datetime(datetime.date(year, date.month, date.day))\n to_put.append(Collection(\n key=Collection.create_key(TrashCollector.IVLA, country, epoch, collection_key),\n activities=activities,\n epoch=epoch,\n year=year,\n month=date.month,\n day=date.day,\n ))\n\n if to_put:\n logging.info('put %s items', len(to_put))\n put_in_chunks(to_put)\n\n\ndef _get_activity_name(name):\n if name in (u'Dag', u'Datum', u'WE - Feestdag',):\n return None\n mapping = {\n 'PMD': TrashActivity.PLASTIC_METAL_CARTONS,\n 'RESTAFVAL': TrashActivity.REST,\n 'P-K': TrashActivity.PAPER_CARDBOARD,\n 'TEXTIEL': TrashActivity.TEXTILE,\n 'SNOEIAFVAL': TrashActivity.PRUNING_WASTE,\n 'SNOEIAFVAL AFROEP': TrashActivity.PRUNING_WASTE_ON_DEMAND,\n 'GROF': TrashActivity.BULKY_WASTE,\n 'GROF AFROEP': TrashActivity.BULKY_WASTE_ON_DEMAND,\n 'KERSTBOOM': TrashActivity.CHRISTMAS_TREE,\n 'GFT': TrashActivity.VEGETABLE_FRUIT_GARDEN_WASTE,\n }\n if name not in mapping:\n raise Exception('Failed to get _get_activity_name for %s' % name)\n return mapping[name]\n","sub_path":"plugins/trash_calendar/bizz/ivla.py","file_name":"ivla.py","file_ext":"py","file_size_in_byte":4084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"644844103","text":"import pandas as pd\nimport psycopg2\nimport os\nfrom ConfigParser import SafeConfigParser\n\n\nclass DBConnection(object):\n \"\"\"\n Opens connection with database based on the development.ini credentials\n \"\"\"\n def _get_db_url(self):\n p = SafeConfigParser()\n p.read(os.path.join(os.getenv(\"HOME\"), \"development.ini\"))\n\n return p.get('Database', 'sqlalchemy.url')\n\n def __enter__(self):\n self.conn = psycopg2.connect(self._get_db_url())\n return self.conn\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.conn.close()\n\n\ndef query_by_chain(chain):\n\n query = \"\"\"select name as gene_name,\n allele as allele,\n sigpend as signal_peptide_end,\n cdna as cdna_seq,\n cds as cds_seq,\n prot as pep_seq\n from binf_germline_seq \n where release_id = '383364251'\n and name like '{}%';\"\"\".format(chain)\n\n return query\n\n\ndef create_fasta_files(chain, query_results, path, is_gapped):\n\n if len(query_results) > 0:\n with open(path + \"/\" + chain + \"_AA_new.fasta\", \"w\") as file_aa:\n with open(path + \"/\" + chain + \"_NT_new.fasta\", \"w\") as file_nt:\n for index in query_results.index:\n result = query_results.iloc[index]\n\n parsed_results = parse_germline_sequences(result[\"gene_name\"],\n result[\"allele\"],\n result[\"cds_seq\"],\n result[\"pep_seq\"],\n result[\"signal_peptide_end\"],\n is_gapped)\n\n file_aa.write(\">\" + str(index) + \"|\" + parsed_results[0] + \"|\" + \" |\" * 13 + \"\\n\" + parsed_results[1] + \"\\n\")\n file_nt.write(\">\" + str(index) + \"|\" + parsed_results[0] + \"|\" + \" |\" * 13 + \"\\n\" + parsed_results[2] + \"\\n\")\n\n file_nt.close()\n file_aa.close()\n\n\ndef parse_germline_sequences(gene_name, allele, nt_seq, aa_seq, sig_pep_end, gapped=False):\n\n # allele_name = get_proper_allele_format(allele)\n full_name = gene_name + \"*\" + allele\n\n if sig_pep_end == -1 or pd.isnull(sig_pep_end):\n sequence_aa = aa_seq\n sequence_nt = nt_seq\n elif sig_pep_end != -1 and not pd.isnull(sig_pep_end):\n sequence_aa = aa_seq[int(sig_pep_end):]\n sequence_nt = nt_seq[int(sig_pep_end)*3:]\n\n if gapped is False:\n sequence_aa = sequence_aa.replace(\".\", \"\")\n sequence_nt = sequence_nt.replace(\".\", \"\")\n\n return (full_name, sequence_aa, sequence_nt)\n\n\ndef get_germline_seqs_from_db(path):\n with DBConnection() as conn:\n query_result = pd.read_sql_query(query_by_chain(\"IGH\"), conn)\n create_fasta_files(\"IGH\", query_result, path, False)\n\n query_result = pd.read_sql_query(query_by_chain(\"IGL\"), conn)\n create_fasta_files(\"IGL\", query_result, path, False)\n\n query_result = pd.read_sql_query(query_by_chain(\"IGK\"), conn)\n create_fasta_files(\"IGK\", query_result, path, False)\n\n\nif __name__ == \"__main__\":\n get_germline_seqs_from_db(\"../data\")\n","sub_path":"src/germline_seq.py","file_name":"germline_seq.py","file_ext":"py","file_size_in_byte":3378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"539513496","text":"import tensorflow as tf\nfrom PIL import Image\nimport numpy as np\nimport cv2\nfrom tensorflow.python.ops import gen_nn_ops\nfrom tensorflow.python.framework import ops\nfrom tensorflow.contrib.graph_editor import subgraph\nfrom tensorflow.core.framework import attr_value_pb2\nfrom tensorflow.python.util import compat\n\nclass GradCAM:\n def __init__(self, instance, sample_size):\n self.instance = instance\n self.sample_size = sample_size\n self.image_size = (400, 224) # (width, height)\n self.num_classes = 2 # class 개수\n\n def normalize(self, x):\n return tf.div(x, tf.expand_dims(tf.expand_dims(tf.expand_dims(tf.sqrt(\n tf.reduce_mean(tf.square(x), axis=(1, 2, 3))) + tf.constant(1e-5), axis=-1), axis=-1), axis=-1))\n\n def build(self):\n '''\n self.instance.logits: 신경망에서 softmax 거치기 전 layer 출력 변수\n self.instance.prob: softmax 거쳐서 나온 확률 변수\n self.instance.cam_layer: CAM 을 통해 보고자 하는 layer\n self.instance.sess: 해당 신경망 모델에서 사용하는 Session Instance\n '''\n with tf.variable_scope('grad_cam'):\n # cam_layer = self.instance.cam_layer\n # top1 = tf.argmax(tf.reshape(self.instance.prob, [-1]))\n # loss = tf.reduce_sum(tf.multiply(self.instance.prob, tf.one_hot(top1, self.num_classes)), axis=1) # (B, C) -> (B, )\n # grads = tf.gradients(ys=loss, xs=cam_layer)[0] # (B, H, W, C)\n # norm_grads = self.normalize(grads)\n # # norm_grads = tf.div(grads, tf.sqrt(tf.reduce_mean(tf.square(grads))) + 1e-5) # normalize\n #\n # weights = tf.reduce_mean(input_tensor=norm_grads, axis=(1, 2))\n # weights = tf.expand_dims(tf.expand_dims(weights, axis=1), axis=1)\n # height, width = cam_layer.get_shape().as_list()[1: 3]\n # cam = tf.ones(shape=[self.sample_size, height, width], dtype=tf.float32)\n # cam = tf.add(cam, tf.reduce_sum(input_tensor=tf.multiply(weights, cam_layer), axis=-1))\n # self.cam = tf.maximum(cam, 0, name='outputs')\n\n cam_layer = self.instance.cam_layer\n loss = tf.reduce_mean(tf.multiply(self.instance.logits, self.instance.prob), axis=-1)\n grads = tf.gradients(ys=loss, xs=cam_layer)[0] # (B, H, W, C)\n norm_grads = self.normalize(grads)\n\n weights = tf.reduce_mean(input_tensor=norm_grads, axis=(1, 2))\n weights = tf.expand_dims(tf.expand_dims(weights, axis=1), axis=1)\n height, width = cam_layer.get_shape().as_list()[1: 3]\n cam = tf.ones(shape=[self.sample_size, height, width], dtype=tf.float32)\n cam = tf.add(cam, tf.reduce_sum(input_tensor=tf.multiply(weights, cam_layer), axis=-1))\n self.cam = tf.maximum(cam, 0, name='outputs')\n\n def visualize(self, x, file_names):\n cam_output = self.instance.sess.run(self.cam,\n feed_dict={self.instance.x: x})\n cam_list = []\n\n for idx in range(self.sample_size):\n cam_output[idx] = cam_output[idx] / np.max(cam_output[idx])\n cam_list.append(cv2.resize(cam_output[idx], self.image_size))\n\n outputs = []\n\n for idx in range(self.sample_size):\n img = Image.open(file_names[idx], mode='r').convert('RGB')\n img = cv2.resize(np.asarray(img), self.image_size, interpolation=cv2.INTER_NEAREST)\n img = img.astype(float)\n img /= 255.\n\n img_cam = cv2.applyColorMap(np.uint8(255 * cam_list[idx]), cv2.COLORMAP_JET)\n img_cam = cv2.cvtColor(img_cam, cv2.COLOR_BGR2RGB)\n\n '''Grad-CAM 과 원본 이미지 중첩'''\n alpha = 0.0025\n output = img + alpha * img_cam\n output /= output.max()\n outputs.append(output)\n\n return outputs\n\n# def guided_grad(grad):\n# return tf.where(0. < grad, grad, tf.zeros_like(grad))\n#\n# @ops.RegisterGradient(\"GuidedRelu6\")\n# def _guided_grad_relu6(op, grad):\n# return guided_grad(gen_nn_ops._relu6_grad(grad, op.outputs[0]))\n\n\n# @ops.RegisterGradient(\"GuideRelu\")\n# def _GuidedReluGrad(op, grad):\n# return tf.where(0. < grad, gen_nn_ops._relu_grad(grad, op.outputs[0]), tf.zeros_like(grad))\n\nclass GuidedGradCAM:\n def __init__(self, instance, sample_size):\n self.instance = instance\n self.sample_size = sample_size\n self.image_size = (224, 224) # (width, height)\n\n def replace_grad_to_guided_grad(self, g):\n sgv = subgraph.make_view(g)\n with g.gradient_override_map({'Relu6': 'GuideRelu6'}):\n for op in sgv.ops:\n self._replace_grad(g, op)\n\n def _replace_grad(self, g, op):\n # ref: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/framework/ops.py\n # tf.Graph._gradient_override_map\n try:\n op_def = op._op_def\n node_def = op._node_def\n\n if op_def is not None:\n mapped_op_type = g._gradient_override_map[op_def.name]\n node_def.attr[\"_gradient_op_type\"].CopyFrom(\n attr_value_pb2.AttrValue(s=compat.as_bytes(mapped_op_type)))\n except KeyError:\n pass\n\n def normalize(self, x):\n return tf.div(x, tf.expand_dims(tf.expand_dims(tf.expand_dims(tf.sqrt(\n tf.reduce_mean(tf.square(x), axis=(1, 2, 3))) + tf.constant(1e-5), axis=-1), axis=-1), axis=-1))\n\n def build(self):\n '''\n self.instance.y: 신경망에서 사용하는 정답 라벨 변수 (onehot-encoding 으로 변환해야함)\n self.instance.prob: softmax 거쳐서 나온 확률 변수\n '''\n # with tf.get_default_graph().gradient_override_map({'Relu6': 'GuideRelu'}):\n # self.instance.build_graph()\n cam_layer = self.instance.cam_layer\n loss = tf.reduce_mean(tf.multiply(self.instance.logits, self.instance.prob), axis=1)\n grads = tf.gradients(ys=loss, xs=cam_layer)[0] # (B, H, W, C)\n norm_grads = self.normalize(grads)\n\n max_output = tf.reduce_max(cam_layer, axis=2)\n self.saliency_map = tf.gradients(tf.reduce_sum(max_output), self.instance.x)[0]\n\n weights = tf.reduce_mean(input_tensor=norm_grads, axis=(1, 2))\n weights = tf.expand_dims(tf.expand_dims(weights, axis=1), axis=1)\n height, width = cam_layer.get_shape().as_list()[1: 3]\n cam = tf.ones(shape=[self.sample_size, height, width], dtype=tf.float32)\n cam = tf.add(cam, tf.reduce_sum(input_tensor=tf.multiply(weights, cam_layer), axis=-1))\n cam = tf.maximum(cam, 0, name='outputs')\n self.cam = tf.div(cam, tf.reduce_max(cam))\n\n def backpropagation(self, x):\n saliency_val = self.instance.sess.run(self.saliency_map, feed_dict={self.instance.x: x,\n self.instance.is_training: False})\n return saliency_val\n\n def visualize(self, x, file_names):\n '''\n self.instance.logits: 신경망에서 softmax 거치기 전 layer 출력 변수\n self.instance.prob: softmax 거쳐서 나온 확률 변수\n self.instance.cam_layer: CAM 을 통해 보고자 하는 layer\n self.instance.sess: 해당 신경망 모델에서 사용하는 Session Instance\n '''\n cam_output, saliency_val = self.instance.sess.run([self.cam, self.saliency_map],\n feed_dict={self.instance.x: x,\n self.instance.training: False})\n cam = np.maximum(cam_output, 0)\n cam_list = []\n\n for idx in range(self.sample_size):\n cam[idx] = cam[idx] / np.max(cam[idx])\n cam_list.append(cv2.resize(cam[idx], self.image_size))\n\n cam_list = np.asarray(cam_list)[..., None] * saliency_val\n\n for idx in range(self.sample_size):\n cam_list[idx] -= np.mean(cam_list[idx])\n cam_list[idx] /= (np.std(cam_list[idx]) + 1e-5)\n cam_list[idx] *= 0.1\n\n cam_list[idx] += 0.5\n cam_list[idx] = np.clip(cam_list[idx], 0, 1)\n\n cam_list[idx] *= 255\n cam_list[idx] = np.clip(cam_list[idx], 0, 255).astype('uint8')\n cam_list[idx] = cv2.cvtColor(cam_list[idx], cv2.COLOR_BGR2RGB)\n\n return cam_list","sub_path":"Projects/Hongbog/DementiaDiagnosis/mobilenet_v2/native/cam.py","file_name":"cam.py","file_ext":"py","file_size_in_byte":8497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"101140863","text":"\n# coding: utf-8\n\n# Here goes the imports\nimport csv\nimport matplotlib.pyplot as plt\n\n# Let's read the data as a list\nprint(\"Reading the document...\")\nwith open(\"chicago.csv\", \"r\") as file_read:\n data_list = [{k: v for k, v in row.items()}\n for row in csv.DictReader(file_read, skipinitialspace=True)]\nprint(\"Ok!\")\n\n# Let's check how many rows do we have\nprint(\"Number of rows:\")\nprint(len(data_list))\nprint(data_list[0]['Gender'])\n# Printing the first row of data_list to check if it worked.\nprint(\"Row 0: \")\nprint(data_list[0])\n\nprint(\"Row 1: \")\nprint(data_list[1])\n\ninput(\"Press Enter to continue...\")\n# TASK 1\n# Print the first 20 rows using a loop to identify the data.\nprint(\"\\n\\nTASK 1: Printing the first 20 samples\")\nfor i in range(20):\n print(\"Row {} : {}\".format(i+1, data_list[i]))\n\n# We can access the features through name\n# E.g. sample['Gender'] to print gender\n\ninput(\"Press Enter to continue...\")\n# TASK 2\n# Print the `gender` of the first 20 rows\nprint(\"\\nTASK 2: Printing the genders of the first 20 samples\")\nfor i in range(20):\n print(\"Row {} : {}\".format(i+1, data_list[i]['Gender']))\n\n# Cool! We can get the rows(samples) iterating with a for and the columns(features) by name.\n# But it's still hard to get a column in a list. Example: List with all genders\n\ninput(\"Press Enter to continue...\")\n# TASK 3\n# Create a function to add the columns(features) of a list in another list in the same order\ndef column_to_list(data, index):\n \"\"\"\n Creates a list with all values from a collumn\n Args:\n data: The whole csv file with the data.\n index: The collumn index in the csv.\n Returns:\n List of all values in a collumn\n \"\"\"\n key_name = list(data[0].keys())[index]\n column_list = [line[key_name] for line in data]\n # Tip: You can use a for to iterate over the samples, get the feature by index and append into a list\n return column_list\n\n\n# Let's check with the genders if it's working (only the first 20)\nprint(\"\\nTASK 3: Printing the list of genders of the first 20 samples\")\nprint(column_to_list(data_list, -2)[:20])\n\n# ------------ DO NOT CHANGE ANY CODE HERE ------------\nassert type(column_to_list(data_list, -2)) is list, \"TASK 3: Wrong type returned. It should return a list.\"\nassert len(column_to_list(data_list, -2)) == 1551505, \"TASK 3: Wrong lenght returned.\"\nassert column_to_list(data_list, -2)[0] == \"\" and column_to_list(data_list, -2)[1] == \"Male\", \"TASK 3: The list doesn't match.\"\n# -----------------------------------------------------\n\ninput(\"Press Enter to continue...\")\n# Now we know how to access the features, let's count how many Males and Females the dataset have\n# TASK 4\n# Count each gender. You should not use a function to do that.\ngender_list = column_to_list(data_list, -2)\nmale = sum(1 for gender in gender_list if gender == 'Male')\nfemale = sum(1 for gender in gender_list if gender == 'Female')\n\n\n# Checking the result\nprint(\"\\nTASK 4: Printing how many males and females we found\")\nprint(\"Male: \", male, \"\\nFemale: \", female)\n\n# ------------ DO NOT CHANGE ANY CODE HERE ------------\nassert male == 935854 and female == 298784, \"TASK 4: Count doesn't match.\"\n# -----------------------------------------------------\n\ninput(\"Press Enter to continue...\")\n# Why don't we creeate a function to do that?\n# TASK 5\n# Create a function to count the genders. Return a list\n# Should return a list with [count_male, counf_female] (e.g., [10, 15] means 10 Males, 15 Females)\ndef count_gender(data_list):\n \"\"\"\n Counts how many of each gender exists in the csv\n Args:\n data_list: A list with all gender values.\n Returns:\n The count of male and female\n \"\"\"\n male = sum(1 for row in data_list if row['Gender'] == 'Male')\n female = sum(1 for row in data_list if row['Gender'] == 'Female')\n return [male, female]\n\n\nprint(\"\\nTASK 5: Printing result of count_gender\")\nprint(count_gender(data_list))\n\n# ------------ DO NOT CHANGE ANY CODE HERE ------------\nassert type(count_gender(data_list)) is list, \"TASK 5: Wrong type returned. It should return a list.\"\nassert len(count_gender(data_list)) == 2, \"TASK 5: Wrong lenght returned.\"\nassert count_gender(data_list)[0] == 935854 and count_gender(data_list)[1] == 298784, \"TASK 5: Returning wrong result!\"\n# -----------------------------------------------------\n\ninput(\"Press Enter to continue...\")\n# Now we can count the users, which gender use it the most?\n# TASK 6\n# Create a function to get the most popular gender and print the gender as string.\n# We expect to see \"Male\", \"Female\" or \"Equal\" as answer.\ndef most_popular_gender(data_list):\n \"\"\"\n Retuns which gender is most popular in the data_list\n Args:\n data_list: A list with all gender values.\n Returns:\n A string with the most popular gender(Male or Female); if they are equals returns Equal\n \"\"\"\n male_count, female_count = count_gender(data_list)\n \n if (male_count == female_count):\n return \"Equal\"\n\n return \"Male\" if male_count > female_count else \"Female\"\n\n\nprint(\"\\nTASK 6: Which one is the most popular gender?\")\nprint(\"Most popular gender is: \", most_popular_gender(data_list))\n\n# ------------ DO NOT CHANGE ANY CODE HERE ------------\nassert type(most_popular_gender(data_list)) is str, \"TASK 6: Wrong type returned. It should return a string.\"\nassert most_popular_gender(data_list) == \"Male\", \"TASK 6: Returning wrong result!\"\n# -----------------------------------------------------\n\n# If it's everything running as expected, check this graph!\ngender_list = column_to_list(data_list, -2)\ntypes = [\"Male\", \"Female\"]\nquantity = count_gender(data_list)\ny_pos = list(range(len(types)))\nplt.bar(y_pos, quantity)\nplt.ylabel('Quantity')\nplt.xlabel('Gender')\nplt.xticks(y_pos, types)\nplt.title('Quantity by Gender')\nplt.show(block=True)\n\ninput(\"Press Enter to continue...\")\n# TASK 7\n# Plot a similar graph for user_types. Make sure the legend is correct.\nprint(\"\\nTASK 7: Check the chart!\")\ndef count_usertype(data_list):\n \"\"\"\n Counts how many of each user type exists in the csv\n Args:\n data_list: A list with all user type values.\n Returns:\n A list with the count of each user type\n \"\"\"\n customer = sum(1 for row in data_list if row['User Type'] == 'Customer')\n subscriber = sum(1 for row in data_list if row['User Type'] == 'Subscriber')\n dependent = sum(1 for row in data_list if row['User Type'] == 'Dependent')\n return [customer, subscriber, dependent]\n\ntypes = [\"Customer\", \"Subscriber\", 'Dependent']\n\nquantity = count_usertype(data_list)\ny_pos = list(range(len(types)))\n\nplt.bar(y_pos, quantity)\nplt.ylabel('Quantity')\nplt.xlabel('User Type')\nplt.xticks(y_pos, types)\nplt.title('Quantity by User Type')\nplt.show(block=True)\n\ninput(\"Press Enter to continue...\")\n# TASK 8\n# Answer the following question\nmale, female = count_gender(data_list)\nprint(\"\\nTASK 8: Why the following condition is False?\")\nprint(\"male + female == len(data_list):\", male + female == len(data_list))\nanswer = \"Some rows do not have information about gender.\"\nprint(\"Answer:\", answer)\n\n# ------------ DO NOT CHANGE ANY CODE HERE ------------\nassert answer != \"Type your answer here.\", \"TASK 8: Write your own answer!\"\n# -----------------------------------------------------\n\ninput(\"Press Enter to continue...\")\n# Let's work with the trip_duration now. We cant get some values from it.\n# TASK 9\n# Find the Minimum, Maximum, Mean and Median trip duration.\n# You should not use ready functions to do that, like max() or min().\ntrip_duration_list = sorted([int(i) for i in column_to_list(data_list, 2)])\ntrip_list_len = len(trip_duration_list)\n\nmin_trip = trip_duration_list[0]\nmax_trip = trip_duration_list[-1]\nmean_trip = sum(trip_duration_list) / trip_list_len\nif trip_list_len % 2 == 0:\n median_trip = sum(trip_duration_list[trip_list_len//2-1:trip_list_len//2+1]) / 2\nelse:\n median_trip = trip_duration_list[trip_list_len//2]\n\n\nprint(\"\\nTASK 9: Printing the min, max, mean and median\")\nprint(\"Min: \", min_trip, \"Max: \", max_trip, \"Mean: \", mean_trip, \"Median: \", median_trip)\n\n# ------------ DO NOT CHANGE ANY CODE HERE ------------\nassert round(min_trip) == 60, \"TASK 9: min_trip with wrong result!\"\nassert round(max_trip) == 86338, \"TASK 9: max_trip with wrong result!\"\nassert round(mean_trip) == 940, \"TASK 9: mean_trip with wrong result!\"\nassert round(median_trip) == 670, \"TASK 9: median_trip with wrong result!\"\n# -----------------------------------------------------\n\ninput(\"Press Enter to continue...\")\n# TASK 10\n# Gender is easy because usually only have a few options. How about start_stations? How many options does it have?\n# Check types how many start_stations do we have using set()\nuser_types = set(column_to_list(data_list, 3))\n\nprint(\"\\nTASK 10: Printing start stations:\")\nprint(len(user_types))\nprint(user_types)\n\n# ------------ DO NOT CHANGE ANY CODE HERE ------------\nassert len(user_types) == 582, \"TASK 10: Wrong len of start stations.\"\n# -----------------------------------------------------\n\ninput(\"Press Enter to continue...\")\n# TASK 11\n# Go back and make sure you documented your functions. Explain the input, output and what it do. Example:\n# # def new_function(param1: int, param2: str) -> list:\n# \"\"\"\n# Example function with annotations.\n# Args:\n# param1: The first parameter.\n# param2: The second parameter.\n# Returns:\n# List of X values\n\n# \"\"\"\n\ninput(\"Press Enter to continue...\")\n# TASK 12 - Challenge! (Optional)\n# Create a function to count user types without hardcoding the types\n# so we can use this function with a different kind of data.\nprint(\"Will you face it?\")\nanswer = \"yes\"\n\ndef count_items(column_list):\n \"\"\"\n Counts a the unique values from a column and how many itens it have\n Args:\n column_list: A list with all values from a column.\n Returns:\n Returns the unique values from a column and how many itens it have\n \"\"\"\n item_types = set(column_list)\n count_items = list(1 for i in column_list)\n return item_types, count_items\n\n\nif answer == \"yes\":\n # ------------ DO NOT CHANGE ANY CODE HERE ------------\n column_list = column_to_list(data_list, -2)\n types, counts = count_items(column_list)\n print(\"\\nTASK 11: Printing results for count_items()\")\n print(\"Types:\", types, \"Counts:\", counts)\n assert len(types) == 3, \"TASK 11: There are 3 types of gender!\"\n assert sum(counts) == 1551505, \"TASK 11: Returning wrong result!\"\n # -----------------------------------------------------","sub_path":"chicago_bikeshare_en.py","file_name":"chicago_bikeshare_en.py","file_ext":"py","file_size_in_byte":10584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"171276838","text":"import random\n\n# Define a dictionary of possible questions and answers\nquestions = {\n \"What is your computer's operating system?\": [\"Windows\", \"Mac\", \"Linux\"],\n \"What is the error message you are seeing?\": [\"Can't connect to internet\", \"Blue screen of death\", \"Program won't open\"],\n \"Have you tried restarting your computer?\": [\"Yes\", \"No\"]\n}\n\n# Define a function to handle user input and generate a response\ndef chatbot():\n # Ask the user for their name\n name = input(\"Hi! What's your name? \")\n\n # Greet the user\n print(f\"Nice to meet you, {name}! I'm here to help with your IT issue.\")\n\n # Ask questions and get answers from the user\n for question, possible_answers in questions.items():\n answer = input(question + \" \")\n while answer not in possible_answers:\n print(\"Sorry, I didn't understand your answer. Please try again.\")\n answer = input(question + \" \")\n print(\"Great, thanks for letting me know!\")\n\n # Generate a random response to the user's issue\n responses = [\n \"I think I know what's going on. Try restarting your computer and see if that fixes the issue.\",\n \"I'm not sure what the issue is, but I'll create a ticket and have someone from IT contact you soon.\",\n \"I need more information to help you with this issue. Can you provide any more details?\"\n ]\n print(random.choice(responses))\n\n# Call the chatbot function to start the conversation\nchatbot()\n","sub_path":"Chatbot/chatbot2.py","file_name":"chatbot2.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"632002145","text":"# 20-03-02\n# EX 33.6\n\ndef countdown(n):\n def onesec():\n nonlocal n\n n -= 1\n return n + 1\n return onesec\n\nn = int(input())\nc = countdown(n)\nfor i in range(n):\n print(c(), end=' ')\n","sub_path":"dojang/py33_06.py","file_name":"py33_06.py","file_ext":"py","file_size_in_byte":209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"375185103","text":"''' exercise 16. Write a function filter_long_words() that takes a list of words and an integer n and returns the list of words that are longer than n.\n'''\ndef filter_long_words(input_list, n):\n return_list = []\n for i in input_list:\n if len(i) > n:\n return_list.append(i)\n return return_list\n\n \n","sub_path":"exercise16.py","file_name":"exercise16.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"163351988","text":"import MMIDic\r\nimport MMIRevolver2\r\nimport sys\r\nimport string\r\nimport LPMaker\r\nfrom lpsolve55 import *\r\n\r\n \r\nclass ClusterCandidate:\r\n def __init__(self,cluster,ppiFilter,geneID2IRDic,gtsp,mmiDic):\r\n self.ppiFilter = ppiFilter\r\n self.protein2MotifDic={};\r\n self.mmiDic=mmiDic\r\n self.lpMaker= LPMaker.LPMaker()\r\n self.cluster = cluster\r\n\r\n self.lp=None\r\n self.ppi2mmiDic={}\r\n self.mmi2ppiDic={}\r\n self.variables2ppiOrMmi={}\r\n self.ppiOrMmi2Variables={}\r\n self.ppiVars=set()\r\n self.mmiVars=set()\r\n \r\n self.wholeProteinMotifSet=set()\r\n #print \"ClusterCandidate init id =\",cluster.clusterId\r\n self.makeProtein2MotifDic(cluster,gtsp,geneID2IRDic)\r\n \r\n def makeProtein2MotifDic(self,cluster,gtsp,geneID2IRDic):\r\n for protein in cluster.proteinList:\r\n irList=[]\r\n motifList = gtsp.geneid_to_motif(protein)\r\n if motifList:\r\n self.protein2MotifDic[protein] = motifList\r\n if protein in geneID2IRDic:\r\n irList = geneID2IRDic[protein]\r\n if irList:\r\n for ir in irList:\r\n if protein in self.protein2MotifDic:\r\n self.protein2MotifDic[protein].append(ir)\r\n else:\r\n self.protein2MotifDic[protein]=[ir]\r\n if not irList and not motifList:\r\n wholeMotif= protein+\"Whole\"\r\n self.wholeProteinMotifSet.add(wholeMotif)\r\n\r\n if protein in self.protein2MotifDic:\r\n self.protein2MotifDic[protein].append(wholeMotif)\r\n else:\r\n self.protein2MotifDic[protein]=[wholeMotif]\r\n \"\"\"\r\n if motifList or irList:\r\n sys.stderr.write(\"ClusterCandidate init \"+protein+\":\"+str(len(self.protein2MotifDic[protein]))+\"\\n\")\r\n else:\r\n sys.stderr.write(\"ClusterCandidate init \"+protein+\":\"+\"\\n\")\r\n print\r\n \"\"\" \r\n def getMaxLinks(self):\r\n score = 0\r\n for p1 in self.cluster.proteinList:\r\n for p2 in self.cluster.proteinList:\r\n if p1 !=p2 and self.ppiFilter.isExist(p1,p2):\r\n score +=1\r\n return score/2\r\n def checkMMI(self):\r\n #sys.stderr.write(\"checkMMI\\n\")\r\n keys =self.protein2MotifDic.keys()\r\n length =len(keys)\r\n ppiSet =set()\r\n for i in range(length):\r\n p1 = keys[i]\r\n for j in range(length-(i+1)):\r\n p2 = keys[j+i+1]\r\n if p1 !=p2 and self.ppiFilter.isExist(p1,p2):\r\n selfMotifs = self.protein2MotifDic[p1]\r\n for motif1 in selfMotifs:\r\n otherMotifs = self.protein2MotifDic[p2]\r\n for motif2 in otherMotifs:\r\n if self._isExist(motif1,motif2):\r\n if motif1 in self.mmiDic and motif2 in self.mmiDic:\r\n sourceID =self.mmiDic[motif1][motif2]\r\n else:\r\n sourceID = \"psuedo\"\r\n mmiPair = MMIRevolver2.MMIPair(motif1,motif2,p1,p2,sourceID)\r\n self._putPPI2MMIDic(p1,p2,motif1,motif2,str(mmiPair))\r\n self._putMMI2PPIDic(p1, p2, motif1, motif2,str(mmiPair))\r\n ppiSet.add(p1+p2)\r\n return len(ppiSet)\r\n def getDomainBasedVariables(self):\r\n\r\n for motif in self.mmi2ppiDic:\r\n if len(self.mmi2ppiDic[motif])>1:\r\n for mmiPair in self.mmi2ppiDic[motif]:\r\n self.mmiVars.add(str(mmiPair))\r\n if len(self.mmi2ppiDic[motif])>0:\r\n for mmiPair in self.mmi2ppiDic[motif]:\r\n self.mmiVars.add(str(mmiPair))\r\n def addDomainBasedConstraint(self):\r\n for motif in self.mmi2ppiDic:\r\n if len(self.mmi2ppiDic[motif])>1:\r\n params=self._getMMIParams(self.mmi2ppiDic[motif])\r\n self.lpMaker.addDomainBasedConstraints(self.lp,params)\r\n \r\n def getInteractionBasedVariables(self):\r\n\r\n for p1 in self.ppi2mmiDic:\r\n for p2 in self.ppi2mmiDic[p1]:\r\n ppi=self._getPPI(p1, p2) \r\n mmiList=self.ppi2mmiDic[p1][p2]\r\n self.ppiVars.add(ppi)\r\n\r\n \r\n def addInteractionBasedConstraints(self):\r\n for p1 in self.ppi2mmiDic:\r\n for p2 in self.ppi2mmiDic[p1]:\r\n ppi=self._getPPI(p1, p2) \r\n mmiList=self.ppi2mmiDic[p1][p2] \r\n params = self._getMMIAndPPIParams(ppi,mmiList)\r\n self.lpMaker.addInteractionsBasedConstraints(self.lp,params)\r\n self._getExclusiveParams(mmiList)\r\n params2= self._getExclusiveParams(mmiList)\r\n #self.lpMaker.addSos(self.lp,params2)\r\n def mergeVars(self):\r\n i=0\r\n for ppiVar in self.ppiVars:\r\n #print ppiVar\r\n self.ppiOrMmi2Variables[ppiVar]=i\r\n self.variables2ppiOrMmi[i]=ppiVar\r\n i+=1\r\n for mmiVar in self.mmiVars:\r\n #print mmiVar\r\n self.ppiOrMmi2Variables[mmiVar]=i\r\n self.variables2ppiOrMmi[i]=mmiVar\r\n i+=1\r\n def getProteinSet(self,vars):\r\n ppiNum = len(self.ppiVars)\r\n i=0\r\n proteinSet = set()\r\n \r\n for var in vars:\r\n if var ==1.0 and i=ppiNum:\r\n mmi=self.variables2ppiOrMmi[i]\r\n mmiSet.add(mmi)\r\n i+=1\r\n return mmiSet\r\n \r\n def printMMIs(self):\r\n for p1 in self.ppi2mmiDic:\r\n for p2 in self.ppi2mmiDic[p1]:\r\n mmiList = self.ppi2mmiDic[p1][p2]\r\n print(p1,p2,mmiList)\r\n \r\n def _parsePPI(self,ppi):\r\n return ppi.split(\"_\")\r\n def createLP(self):\r\n self.lp=self.lpMaker.createLP(self.ppiOrMmi2Variables.keys())\r\n self.lpMaker.setVarConstraint(self.lp)\r\n self.lpMaker.setObjectives(len(self.ppiVars),self.ppiOrMmi2Variables.keys(),self.lp)\r\n def _getMMIParams(self,mmiList):\r\n params=[]\r\n \r\n for i in range(len(self.variables2ppiOrMmi.keys())):\r\n \r\n if self.variables2ppiOrMmi[i] in mmiList:\r\n params.append(1)\r\n else:\r\n params.append(0)\r\n return params\r\n def _getMMIAndPPIParams(self,ppi,mmiList):\r\n params=[]\r\n \r\n for i in range(len(self.variables2ppiOrMmi.keys())):\r\n if self.variables2ppiOrMmi[i] == ppi:\r\n params.append(-1)\r\n elif self.variables2ppiOrMmi[i] in mmiList:\r\n params.append(1)\r\n else:\r\n params.append(0)\r\n return params\r\n def _getExclusiveParams(self,mmiList):\r\n params=[]\r\n \r\n for mmi in mmiList:\r\n params.append(self.ppiOrMmi2Variables[mmi]+1)\r\n \r\n return params\r\n \r\n def _putMMI2PPIDic(self,p1,p2,motif1,motif2,mmiPair):\r\n pMotif1=self._getPmotif(p1, motif1)\r\n pMotif2=self._getPmotif(p2, motif2)\r\n\r\n if pMotif1 in self.mmi2ppiDic:\r\n self.mmi2ppiDic[pMotif1].append(mmiPair)\r\n else:\r\n self.mmi2ppiDic[pMotif1]=[mmiPair]\r\n\r\n if pMotif2 in self.mmi2ppiDic:\r\n self.mmi2ppiDic[pMotif2].append(mmiPair)\r\n else:\r\n self.mmi2ppiDic[pMotif2]=[mmiPair]\r\n def _getPmotif(self,p,motif):\r\n return string.join([p,motif], \".\")\r\n def _getPPI(self,p1,p2):\r\n return string.join([p1,p2], \"_\")\r\n \r\n def _putPPI2MMIDic(self,p1,p2,motif1,motif2,mmiPair):\r\n if p1 in self.ppi2mmiDic:\r\n if p2 in self.ppi2mmiDic[p1]:\r\n self.ppi2mmiDic[p1][p2].append(mmiPair) \r\n else:\r\n self.ppi2mmiDic[p1][p2] = [mmiPair] \r\n else:\r\n self.ppi2mmiDic[p1] = {p2:[mmiPair]} \r\n \r\n\r\n def _isExist(self,motif1,motif2):\r\n flag = False\r\n if motif1 in self.mmiDic:\r\n if motif2 in self.mmiDic[motif1]:\r\n flag = True\r\n if motif1 in self.wholeProteinMotifSet or motif2 in self.wholeProteinMotifSet:\r\n flag = True\r\n \r\n return flag\r\n\r\n ","sub_path":"csplugins/trunk/ucsd/rsaito/rs_Progs/rs_Python/rs_Python_Pack/trunk/IVV_Packages/YO_IP/ClusterCandidates2IPFormat4.py","file_name":"ClusterCandidates2IPFormat4.py","file_ext":"py","file_size_in_byte":8850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"445674379","text":"#!/usr/local/bin/python\n\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom serial import Serial, SerialException\nimport math\n\ncxn = Serial('/dev/cu.usbmodem1411', baudrate=9600)\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\n\nver_pos = []\nhor_pos = []\ndist = []\nreadings = []\nrun = 1\n\ndef get_ver_pos(s):\n result = s[0:s.index(',')] \n return int(result)\n\ndef get_hor_pos(s):\n result = s[(s.index(',')+1): (s.rindex(','))]\n return int(result)\n\ndef get_dist(s):\n result = s[(s.rindex(',')+1):]\n return float(result)\n\nwhile(True):\n try:\n cmd_id = int(input(\"Please enter a command ID (1 - start, 2 - do nothing: \"))\n if int(cmd_id) > 2 or int(cmd_id) < 1:\n print(\"Values other than 1 or 2 are ignored.\")\n else:\n cxn.write([int(cmd_id)])\n while cxn.inWaiting() < 1:\n pass\n for i in range(0, 900):\n reading = cxn.readline();\n print(reading)\n readings.append(reading)\n break\n except ValueError:\n print(\"You must enter an integer value between 1 and 2.\")\n\nfor reading in readings:\n reading = reading.decode()\n reading = reading.replace(\"\\r\\n\", \"\")\n ver = get_ver_pos(reading)\n hor = get_hor_pos(reading)\n distance = get_dist(reading)\n ver_pos.append(math.radians(ver))\n hor_pos.append(math.radians(hor))\n dist.append(distance)\nx = []\ny = []\nz = []\nfor i in range(0, len(dist)-1):\n if (dist[i] >= 12 and dist[i] <= 36):\n x.append(dist[i]*math.cos(ver_pos[i])*math.cos(hor_pos[i]))\n y.append(dist[i]*math.cos(ver_pos[i])*math.sin(hor_pos[i]))\n z.append(dist[i]*math.sin(ver_pos[i]))\nprint(x)\n\nplt.scatter(x, y, z)\nax.set_xlabel('X Label')\nax.set_ylabel('Y Label')\nax.set_zlabel('Z Label')\n\nplt.show()\n","sub_path":"SendReceive3d.py","file_name":"SendReceive3d.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"114094408","text":"import pygame\nimport sys\ntry:\n from playsound import playsound\n LOCALaudioAvailable = True\n print(\"Playsound available.\")\nexcept:\n print(\"No Playsound module found!\")\n\ndef main(screen, g, font, pokImg, backImg):\n stage = 0\n if LOCALaudioAvailable == True:\n g.audioAvailable = True\n while stage == 0:\n titleTextImg, rect = font.render(\"ZIRCON\", (44, 93, 255))\n backImg = pygame.transform.scale(backImg, (g.screenWidth, g.screenHeight))\n screen.blit(backImg, (0, 0))\n screen.blit(pokImg, ((g.screenWidth/2)-(pokImg.get_size()[0]/2), (g.screenHeight/2)-(pokImg.get_size()[1]/2)-90))\n screen.blit(titleTextImg, ((g.screenWidth/2)-(titleTextImg.get_size()[0]/2), (g.screenHeight/2)-(titleTextImg.get_size()[1]/2)+90))\n pygame.display.flip()\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.MOUSEBUTTONDOWN:\n g.mouseClickX, g.mouseClickY = event.pos\n playsound(\"assets/audio/select.mp3\")\n stage = 1\n while stage == 1:\n screen.blit(backImg, (50, 50))\n pygame.display.flip()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()","sub_path":"scenes/opening.py","file_name":"opening.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"216818745","text":"import tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport os\n\n#################################################\n## BOUNDING BOX HANDLING\n#################################################\n\ndef getLocations(image_key, config, randomize=True):\n keys = image_key.split(\"/\")\n locations_file = \"{}/locations/{}-{}.csv\".format(\n keys[0], \n keys[1], \n config[\"sampling\"][\"locations_field\"]\n )\n locations_path = os.path.join(config[\"image_set\"][\"path\"], locations_file)\n if os.path.exists(locations_path):\n locations = pd.read_csv(locations_path)\n random_sample = config[\"sampling\"][\"locations\"]\n if randomize and random_sample is not None and random_sample < len(locations):\n return locations.sample(random_sample)\n else:\n return locations\n else:\n y_key = config[\"sampling\"][\"locations_field\"] + \"_Location_Center_Y\"\n x_key = config[\"sampling\"][\"locations_field\"] + \"_Location_Center_X\"\n return pd.DataFrame(columns=[x_key, y_key])\n\n\ndef prepareBoxes(locationsBatch, imageLabels, config):\n all_boxes = []\n all_indices = []\n all_labels = []\n index = 0\n y_key = config[\"sampling\"][\"locations_field\"] + \"_Location_Center_Y\"\n x_key = config[\"sampling\"][\"locations_field\"] + \"_Location_Center_X\"\n for locations in locationsBatch:\n boxes = np.zeros((len(locations), 4), np.float32)\n boxes[:,0] = locations[y_key] - config[\"sampling\"][\"box_size\"]/2\n boxes[:,1] = locations[x_key] - config[\"sampling\"][\"box_size\"]/2\n boxes[:,2] = locations[y_key] + config[\"sampling\"][\"box_size\"]/2\n boxes[:,3] = locations[x_key] + config[\"sampling\"][\"box_size\"]/2\n boxes[:,[0,2]] /= config[\"image_set\"][\"height\"]\n boxes[:,[1,3]] /= config[\"image_set\"][\"width\"]\n box_ind = index * np.ones((len(locations)), np.int32)\n labels = imageLabels[index] * np.ones((len(locations)), np.int32)\n all_boxes.append(boxes)\n all_indices.append(box_ind)\n all_labels.append(labels)\n index += 1\n return np.concatenate(all_boxes), np.concatenate(all_indices), np.concatenate(all_labels)\n\ndef loadBatch(dataset, config):\n batch = dataset.getTrainBatch(config[\"sampling\"][\"images\"])\n batch[\"locations\"] = [ getLocations(x, config) for x in batch[\"keys\"] ]\n return batch\n\n#################################################\n## CROPPING AND TRANSFORMATION OPERATIONS\n#################################################\n\ndef crop(image_ph, boxes_ph, box_ind_ph, box_size):\n with tf.variable_scope(\"cropping\"):\n crop_size_ph = tf.constant([box_size, box_size], name=\"crop_size\")\n crops = tf.image.crop_and_resize(image_ph, boxes_ph, box_ind_ph, crop_size_ph)\n return crops\n\ndef augment(crop):\n with tf.variable_scope(\"augmentation\"):\n augmented = tf.image.random_flip_left_right(crop)\n angle = tf.random_uniform([1], minval=0, maxval=3, dtype=tf.int32)\n augmented = tf.image.rot90(augmented, angle[0])\n return augmented\n\ndef aument_multiple(crops, parallel=10):\n with tf.variable_scope(\"augmentation\"):\n return tf.map_fn(augment, crops, parallel_iterations=parallel)\n","sub_path":"learning/cropping.py","file_name":"cropping.py","file_ext":"py","file_size_in_byte":3208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"402893436","text":"'''\nGiven two integer arrays A and B, return the maximum length of an subarray that appears in both arrays.\n'''\nclass Solution:\n def findLength(self, A, B):\n length1 = len(A)\n length2 = len(B)\n temp = [[0] * (length2 + 1) for k in range(length1 + 2)]\n max_num = 0\n for i in range(1, length1 + 1):\n #print(temp[i - 1])\n for j in range(1, length2 + 1):\n if A[i - 1] == B[j - 1]:\n #print(temp[i][j], temp[i - 1][j - 1], i, j)\n temp[i][j] = temp[i - 1][j - 1] + 1\n #print(temp[0])\n #print(temp[1])\n #print(temp[i - 1])\n #print(temp[i])\n #print(temp)\n for m in range(len(temp)):\n max_num = max(max_num, max(temp[m]))\n #print(max_num)\n #(temp)\n return max_num\nnums1 = [1,2,3,2,1]\nnums2 = [3,2,1,4,7]\nfunction = Solution()\nfunction.findLength(nums1, nums2)\n[0, 1, 0, 0, 0, 1]\n[1, 1, 0, 0, 1, 2]\n[0, 1, 2, 3, 1, 2]\n[0, 1, 2, 3, 1, 2]\n[1, 1, 2, 3, 1, 2]\n[1, 1, 2, 3, 4, 5]","sub_path":"Array/problem718/Maximum_Length_of_Repeated_Subarray.py","file_name":"Maximum_Length_of_Repeated_Subarray.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"233226964","text":"# \t7. Given an unsorted integer array A, find the sum of all the elements in A.\r\n\r\n\r\na = [2,9,8,5,6,6]\r\n\r\nsum = 0\r\nfor i in a:\r\n sum = sum + i\r\n\r\nprint(\"Sum of given array is : \",sum)","sub_path":"array7.py","file_name":"array7.py","file_ext":"py","file_size_in_byte":186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"638755437","text":"from __future__ import absolute_import, unicode_literals\n\nimport logging\n\nfrom django.contrib import messages\nfrom django.shortcuts import get_object_or_404\nfrom django.template import RequestContext\nfrom django.urls import reverse_lazy\nfrom django.utils.translation import ugettext_lazy as _, ungettext\n\nfrom acls.models import AccessControlList\nfrom common.views import (\n MultipleObjectFormActionView, SingleObjectCreateView,\n SingleObjectDeleteView, SingleObjectEditView, SingleObjectListView\n)\nfrom documents.permissions import permission_document_view\nfrom documents.models import Document\nfrom documents.views import DocumentListView\n\nfrom .forms import CabinetListForm\nfrom .icons import icon_cabinet\nfrom .links import (\n link_cabinet_add_document, link_cabinet_child_add, link_cabinet_create\n)\nfrom .models import Cabinet\nfrom .permissions import (\n permission_cabinet_add_document, permission_cabinet_create,\n permission_cabinet_delete, permission_cabinet_edit,\n permission_cabinet_view, permission_cabinet_remove_document\n)\nfrom .widgets import jstree_data\n\nlogger = logging.getLogger(__name__)\n\n\nclass CabinetCreateView(SingleObjectCreateView):\n fields = ('label',)\n model = Cabinet\n post_action_redirect = reverse_lazy('cabinets:cabinet_list')\n view_permission = permission_cabinet_create\n\n def get_extra_context(self):\n return {\n 'title': _('Create cabinet'),\n }\n\n\nclass CabinetChildAddView(SingleObjectCreateView):\n fields = ('label',)\n model = Cabinet\n\n def form_valid(self, form):\n \"\"\"\n If the form is valid, save the associated model.\n \"\"\"\n self.object = form.save(commit=False)\n self.object.parent = self.get_object()\n self.object.save()\n\n return super(CabinetChildAddView, self).form_valid(form)\n\n def get_object(self, *args, **kwargs):\n cabinet = super(CabinetChildAddView, self).get_object(*args, **kwargs)\n\n AccessControlList.objects.check_access(\n permissions=permission_cabinet_edit, user=self.request.user,\n obj=cabinet.get_root()\n )\n\n return cabinet\n\n def get_extra_context(self):\n return {\n 'title': _(\n 'Add new level to: %s'\n ) % self.get_object().get_full_path(),\n }\n\n\nclass CabinetDeleteView(SingleObjectDeleteView):\n model = Cabinet\n object_permission = permission_cabinet_delete\n post_action_redirect = reverse_lazy('cabinets:cabinet_list')\n\n def get_extra_context(self):\n return {\n 'object': self.get_object(),\n 'title': _('Delete the cabinet: %s?') % self.get_object(),\n }\n\n\nclass CabinetDetailView(DocumentListView):\n template_name = 'cabinets/cabinet_details.html'\n\n def get_document_queryset(self):\n queryset = AccessControlList.objects.filter_by_access(\n permission=permission_document_view, user=self.request.user,\n queryset=self.get_object().documents.all()\n )\n\n return queryset\n\n def get_context_data(self, **kwargs):\n context = super(CabinetDetailView, self).get_context_data(**kwargs)\n\n cabinet = self.get_object()\n\n context.update(\n {\n 'column_class': 'col-xs-12 col-sm-6 col-md-4 col-lg-3',\n 'hide_links': True,\n 'jstree_data': '\\n'.join(\n jstree_data(node=cabinet.get_root(), selected_node=cabinet)\n ),\n 'list_as_items': True,\n 'no_results_icon': icon_cabinet,\n 'no_results_main_link': link_cabinet_child_add.resolve(\n context=RequestContext(\n request=self.request, dict_={'object': cabinet}\n )\n ),\n 'no_results_text': _(\n 'Cabinet levels can contain documents or other '\n 'cabinet sub levels. To add documents to a cabinet, '\n 'select the cabinet view of a document view.'\n ),\n 'no_results_title': _('This cabinet level is empty'),\n 'object': cabinet,\n 'title': _('Details of cabinet: %s') % cabinet.get_full_path(),\n }\n )\n\n return context\n\n def get_object(self):\n cabinet = get_object_or_404(Cabinet, pk=self.kwargs['pk'])\n\n if cabinet.is_root_node():\n permission_object = cabinet\n else:\n permission_object = cabinet.get_root()\n\n AccessControlList.objects.check_access(\n permissions=permission_cabinet_view, user=self.request.user,\n obj=permission_object\n )\n\n return cabinet\n\n\nclass CabinetEditView(SingleObjectEditView):\n fields = ('label',)\n model = Cabinet\n object_permission = permission_cabinet_edit\n post_action_redirect = reverse_lazy('cabinets:cabinet_list')\n\n def get_extra_context(self):\n return {\n 'object': self.get_object(),\n 'title': _('Edit cabinet: %s') % self.get_object(),\n }\n\n\nclass CabinetListView(SingleObjectListView):\n object_permission = permission_cabinet_view\n\n def get_extra_context(self):\n return {\n 'hide_link': True,\n 'title': _('Cabinets'),\n 'no_results_icon': icon_cabinet,\n 'no_results_main_link': link_cabinet_create.resolve(\n context=RequestContext(request=self.request)\n ),\n 'no_results_text': _(\n 'Cabinets are a multi-level method to organize '\n 'documents. Each cabinet can contain documents as '\n 'well as other sub level cabinets.'\n ),\n 'no_results_title': _('No cabinets available'),\n }\n\n def get_object_list(self):\n # Add explicit ordering of root nodes since the queryset returned\n # is not affected by the model's order Meta option.\n return Cabinet.objects.root_nodes().order_by('label')\n\n\nclass DocumentCabinetListView(CabinetListView):\n def dispatch(self, request, *args, **kwargs):\n self.document = get_object_or_404(Document, pk=self.kwargs['pk'])\n\n AccessControlList.objects.check_access(\n permissions=permission_document_view, user=request.user,\n obj=self.document\n )\n\n return super(DocumentCabinetListView, self).dispatch(\n request, *args, **kwargs\n )\n\n def get_extra_context(self):\n return {\n 'hide_link': True,\n 'no_results_icon': icon_cabinet,\n 'no_results_main_link': link_cabinet_add_document.resolve(\n context=RequestContext(\n request=self.request, dict_={'object': self.document}\n )\n ),\n 'no_results_text': _(\n 'Documents can be added to many cabinets.'\n ),\n 'no_results_title': _(\n 'This document is not in any cabinet'\n ),\n 'object': self.document,\n 'title': _('Cabinets containing document: %s') % self.document,\n }\n\n def get_object_list(self):\n return self.document.document_cabinets().all()\n\n\nclass DocumentAddToCabinetView(MultipleObjectFormActionView):\n form_class = CabinetListForm\n model = Document\n object_permission = permission_cabinet_add_document\n success_message = _(\n 'Add to cabinet request performed on %(count)d document'\n )\n success_message_plural = _(\n 'Add to cabinet request performed on %(count)d documents'\n )\n\n def get_extra_context(self):\n queryset = self.get_queryset()\n\n result = {\n 'submit_label': _('Add'),\n 'title': ungettext(\n singular='Add %(count)d document to cabinets',\n plural='Add %(count)d documents to cabinets',\n number=queryset.count()\n ) % {\n 'count': queryset.count(),\n }\n }\n\n if queryset.count() == 1:\n result.update(\n {\n 'object': queryset.first(),\n 'title': _(\n 'Add document \"%s\" to cabinets'\n ) % queryset.first()\n }\n )\n\n return result\n\n def get_form_extra_kwargs(self):\n queryset = self.get_queryset()\n result = {\n 'help_text': _(\n 'Cabinets to which the selected documents will be added.'\n ),\n 'permission': permission_cabinet_add_document,\n 'user': self.request.user\n }\n\n if queryset.count() == 1:\n result.update(\n {\n 'queryset': Cabinet.objects.exclude(\n pk__in=queryset.first().cabinets.all()\n )\n }\n )\n\n return result\n\n def object_action(self, form, instance):\n cabinet_membership = instance.cabinets.all()\n\n for cabinet in form.cleaned_data['cabinets']:\n AccessControlList.objects.check_access(\n obj=cabinet, permissions=permission_cabinet_add_document,\n user=self.request.user\n )\n if cabinet in cabinet_membership:\n messages.warning(\n self.request, _(\n 'Document: %(document)s is already in '\n 'cabinet: %(cabinet)s.'\n ) % {\n 'document': instance, 'cabinet': cabinet\n }\n )\n else:\n cabinet.add_document(\n document=instance, user=self.request.user\n )\n messages.success(\n self.request, _(\n 'Document: %(document)s added to cabinet: '\n '%(cabinet)s successfully.'\n ) % {\n 'document': instance, 'cabinet': cabinet\n }\n )\n\n\nclass DocumentRemoveFromCabinetView(MultipleObjectFormActionView):\n form_class = CabinetListForm\n model = Document\n object_permission = permission_cabinet_remove_document\n success_message = _(\n 'Remove from cabinet request performed on %(count)d document'\n )\n success_message_plural = _(\n 'Remove from cabinet request performed on %(count)d documents'\n )\n\n def get_extra_context(self):\n queryset = self.get_queryset()\n\n result = {\n 'submit_label': _('Remove'),\n 'title': ungettext(\n singular='Remove %(count)d document from cabinets',\n plural='Remove %(count)d documents from cabinets',\n number=queryset.count()\n ) % {\n 'count': queryset.count(),\n }\n }\n\n if queryset.count() == 1:\n result.update(\n {\n 'object': queryset.first(),\n 'title': _(\n 'Remove document \"%s\" from cabinets'\n ) % queryset.first()\n }\n )\n\n return result\n\n def get_form_extra_kwargs(self):\n queryset = self.get_queryset()\n result = {\n 'help_text': _(\n 'Cabinets from which the selected documents will be removed.'\n ),\n 'permission': permission_cabinet_remove_document,\n 'user': self.request.user\n }\n\n if queryset.count() == 1:\n result.update(\n {\n 'queryset': queryset.first().cabinets.all()\n }\n )\n\n return result\n\n def object_action(self, form, instance):\n cabinet_membership = instance.cabinets.all()\n\n for cabinet in form.cleaned_data['cabinets']:\n AccessControlList.objects.check_access(\n obj=cabinet, permissions=permission_cabinet_remove_document,\n user=self.request.user\n )\n\n if cabinet not in cabinet_membership:\n messages.warning(\n self.request, _(\n 'Document: %(document)s is not in cabinet: '\n '%(cabinet)s.'\n ) % {\n 'document': instance, 'cabinet': cabinet\n }\n )\n else:\n cabinet.remove_document(\n document=instance, user=self.request.user\n )\n messages.success(\n self.request, _(\n 'Document: %(document)s removed from cabinet: '\n '%(cabinet)s.'\n ) % {\n 'document': instance, 'cabinet': cabinet\n }\n )\n","sub_path":"mayan/apps/cabinets/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"20321291","text":"import pandas as pd\nimport os\nimport numpy as np\n\n\nyears_f = ['2014', '2015', '2016', '2017', '2018', '2019']\npath_f = '/mnt/pgth04b/DATABASES_CRIS/embeddings_saliency/finalistas'\n\nyears_nf = ['2017', '2018', '2019']\npath_nf = '/mnt/pgth04b/DATABASES_CRIS/embeddings1024/no_finalistas'\n\ndef find_max(years, path):\n maxh = 0\n maxw = 0\n notempty = 0\n for y in years:\n path_to_saliency = os.path.join(path, y)\n saliency_in_year = os.listdir(path_to_saliency)\n for s in saliency_in_year:\n if s[-3:] != 'npy':\n path_df = os.path.join(path_to_saliency, s)\n saliency = pd.read_csv(path_df, index_col=0, thousands=',')\n if not saliency.empty:\n notempty += 1\n print(str(notempty))\n saliency = saliency.drop(['0', '1'], axis=1)\n salarr = saliency.to_numpy()\n sh = salarr.shape[0]\n sw = salarr.shape[1]\n if sh > maxh:\n maxh = salarr.shape[0]\n if sw > maxw:\n maxw = salarr.shape[1]\n\n size = [maxh, maxw]\n return size\n\nmax_f = find_max(years_f, path_f)\nmax_nf = find_max(years_nf, path_nf)\n\nif max_f[0] > max_nf[0]:\n print('Max h size is ' + str(max_f[0]))\nelse:\n print('Max h size is ' + str(max_nf[0]))\n\nif max_f[1] > max_nf[1]:\n print('Max w size is ' + str(max_f[1]))\nelse:\n print('Max w size is ' + str(max_nf[1]))\n","sub_path":"scripts/get_max_hw_saliency.py","file_name":"get_max_hw_saliency.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"543455916","text":"\"\"\"--------------------------------------------------------------------------------------------------------------------------------------\nMODULE\n LoanRepaymentNoticeXMLGenerator\n\nDESCRIPTION\n This module contains classes used to generate the XML that will\n be fed into the XML template through the XML hooks called. This specifically uses a constructor\n that is fed into the xml generator that returns an acmtemplate to make up the body of the xml.\n\n This is called in the XML hooks module for repayment notices called LoanRepaymentNoticeXMLHooks\n\n-----------------------------------------------------------------------------------------------------------------------------------------\nHISTORY\n=========================================================================================================================================\nDate Change no Developer Requester Description\n-----------------------------------------------------------------------------------------------------------------------------------------\n2018-11-20 Stuart Wilson Loan Ops XML generator for repayment notices\n-----------------------------------------------------------------------------------------------------------------------------------------\n\"\"\"\n\nfrom datetime import date as datef\nfrom datetime import datetime\n\nimport acm\n\nfrom DocumentXMLGenerator import GenerateDocumentXMLRequest, DocumentXMLGenerator\nimport LoanNoticeGeneral\nimport LoanRepaymentNoticeScript\n\ncalculation_space = acm.Calculations().CreateStandardCalculationsSpaceCollection()\n\n\nclass GenerateRepaymentNoticeXMLRequest(GenerateDocumentXMLRequest):\n\n def __init__(self, from_party, from_party_contact, to_party, to_party_contact, confirmation):\n \"\"\"\n Constructor class for rate notice xml generator\n \"\"\"\n super(GenerateRepaymentNoticeXMLRequest, self).__init__(from_party, from_party_contact, to_party, to_party_contact)\n self.trade = confirmation.Trade()\n self.confirmation = confirmation\n self.date = str(datef.fromtimestamp(confirmation.CreateTime()))\n self.paydate = acm.Time().DateAddDelta(self.date, 0, 0, 7)\n self.valid_trades_list = LoanRepaymentNoticeScript.get_valid_trades_per_party_acquirer_pair((to_party, from_party), self.paydate)\n self.currencies = LoanRepaymentNoticeScript.get_currencies_from_trades(self.valid_trades_list)\n\nclass RepaymentNoticeXMLGenerator(DocumentXMLGenerator):\n\n def add_redemption_to_fixed_amount(self, trade, cashflow_fixed_and_redemption):\n fixed_amount = 0\n redemption_amount = 0\n if cashflow_fixed_and_redemption[0]:\n fixed_amount = cashflow_fixed_and_redemption[0].Calculation().Projected(calculation_space, trade).Number()\n\n if cashflow_fixed_and_redemption[1]:\n redemption_amount = cashflow_fixed_and_redemption[1].Calculation().Projected(calculation_space, trade).Number()\n\n return fixed_amount + redemption_amount\n\n def get_trade_pm_facility_id(self, trade, trade_currency):\n \"\"\"\n Function to get trade additional info PM_Facility_ID and splits the value(e.g\n CORPL|AUG16|TL|A = AUG16|TL|A)\n \"\"\"\n trade_facility_id = trade.AdditionalInfo().PM_FacilityID()\n facility_id = trade_facility_id[trade_facility_id.index('|') + 1:].replace('|', ' ').replace(trade_currency, '')\n\n return facility_id\n\n def rate_notice_facility_agreement(self, confirmation):\n \"\"\"\n This Function returns the Facility agreement between counterparty and acquirer\n \"\"\"\n if confirmation.Acquirer().Name() == 'IMPUMELELO SERIES 1 ACQUIRER':\n fac_agreement = (\n \"Facility Agreement/s entered into between {0} (administered by Absa \"\n \"through its Corporate and Investment Banking division) and {1}\").format(\n confirmation.AcquirerContactRef().Fullname2(),\n confirmation.Counterparty().Fullname())\n\n else:\n fac_agreement = (\n \"Facility Agreement/s entered into between {0} (acting through \"\n \"its Corporate and Investment \"\n \"Banking division) and {1}\").format(confirmation.AcquirerContactRef().Fullname2(),\n confirmation.Counterparty().Fullname())\n return fac_agreement\n\n def get_facility_instrument_cashflow(self, trade, date):\n \"\"\"\n This function returns the trade facility cashflow details\n \"\"\"\n cashflow_fixed_and_redemption = LoanRepaymentNoticeScript.seven_days_before_pay_day_fixed_cashflow(trade, date)\n cashflow = LoanRepaymentNoticeScript.seven_days_before_pay_day_cashflow(trade, date)\n\n if cashflow_fixed_and_redemption[0] is None and cashflow_fixed_and_redemption[1] is None:\n capital_due = 0\n else:\n capital_due = self.add_redemption_to_fixed_amount(trade, cashflow_fixed_and_redemption)\n \n if cashflow is None:\n interest_due = 0\n forward_rate = 0\n\n if cashflow_fixed_and_redemption[0] is not None:\n cashflow_for_dates = cashflow_fixed_and_redemption[0]\n\n elif cashflow_fixed_and_redemption[0] is None and cashflow_fixed_and_redemption[1] is not None:\n cashflow_for_dates = cashflow_fixed_and_redemption[1]\n\n previous_cashflow = LoanNoticeGeneral.get_previous_cashflow(cashflow_for_dates)\n commencement_date = datetime.strptime(previous_cashflow.StartDate(), '%Y-%m-%d').strftime('%d/%m/%Y')\n end_date = datetime.strptime(previous_cashflow.EndDate(), '%Y-%m-%d').strftime('%d/%m/%Y')\n\n else:\n commencement_date = datetime.strptime(cashflow.StartDate(), '%Y-%m-%d').strftime('%d/%m/%Y')\n end_date = datetime.strptime(cashflow.EndDate(), '%Y-%m-%d').strftime('%d/%m/%Y')\n interest_due = cashflow.Calculation().Projected(calculation_space, trade).Number()\n forward_rate = (cashflow.Calculation().ForwardRate(calculation_space) * 100)\n for reset in cashflow.Resets():\n if reset.Day() == date:\n if LoanNoticeGeneral.match_primelinked_trades(trade):\n rate = reset.FixingValue()\n forward_rate = rate + cashflow.Spread()\n \n\n trade_currency = trade.Currency().Name()\n facility_dict = dict()\n\n facility_dict['FACILITY_ID'] = self.get_trade_pm_facility_id(trade, trade_currency)\n facility_dict['APPLICABLERATE'] = \"{:0.9g}\".format(float(forward_rate))\n facility_dict['COMMENCEMENTDATE'] = commencement_date\n facility_dict['MATURITYDATE'] = end_date\n facility_dict['NOMINAL_AMOUNT'] = LoanNoticeGeneral.sum_nominal_before_payday(trade, date)\n facility_dict['CURRENCY'] = trade_currency\n facility_dict['INTEREST_DUE'] = \"{:0.2f}\".format(float(interest_due))\n facility_dict['CAPITAL_DUE'] = \"{:0.2f}\".format(float(capital_due))\n facility_dict['RUNNING_TOTAL'] = \"{:0.2f}\".format(float(capital_due)+float(interest_due))\n return facility_dict\n\n def get_facility_cashflow_element(self, trade, date):\n \"\"\"\n Function to create facility cashflow xml child element 'FACILITY'\n \"\"\"\n facility_dict = self.get_facility_instrument_cashflow(trade, date)\n element = self._generate_element('FACILITY')\n for tag_name, value in list(facility_dict.items()):\n element.append(self._generate_element(tag_name, str(value)))\n return element\n\n def get_totals_in_facilities(self, element):\n capital_due = 0\n interest_due = 0\n for tag in element:\n for subtag in tag:\n if subtag.tag == 'CAPITAL_DUE':\n capital_due += float(subtag.text)\n elif subtag.tag == 'INTEREST_DUE':\n interest_due += float(subtag.text)\n\n return capital_due, interest_due\n\n def get_facilities_xml_element(self, xml_request, currency):\n element = self._generate_element('FACILITIES')\n date = xml_request.date\n\n if xml_request.valid_trades_list:\n\n for trade in xml_request.valid_trades_list:\n if trade.Currency() == currency:\n if abs(LoanNoticeGeneral.sum_nominal_before_payday(trade, date)) > 0.00:\n element.append(self.get_facility_cashflow_element(trade, date))\n totals = self.get_totals_in_facilities(element)\n element.append(self._generate_element('CAPITAL_DUE_TOTAL', \"{:0.2f}\".format(totals[0])))\n element.append(self._generate_element('INTEREST_DUE_TOTAL', \"{:0.2f}\".format(totals[1])))\n element.append(self._generate_element('GRAND_TOTAL', \"{:0.2f}\".format(totals[0] + totals[1])))\n\n return element\n\n def get_legalnotice_loan(self, xml_request):\n normal_disclaimer = LoanNoticeGeneral.loan_notice_get_documentation_parameter('normal_disclaimer')\n prime_disclaimer = LoanNoticeGeneral.loan_notice_get_documentation_parameter('prime_disclaimer')\n for trade in xml_request.valid_trades_list:\n if LoanNoticeGeneral.match_primelinked_trades(trade):\n disclaimer1 = '{prime}\\n\\n{normal}'.format(prime=prime_disclaimer,\n normal=normal_disclaimer)\n return self._generate_element('REPAYMENT_NOTICE_DISClAIMER', disclaimer1)\n disclaimer2 = normal_disclaimer\n return self._generate_element('REPAYMENT_NOTICE_DISClAIMER', disclaimer2)\n\n def get_account_details(self, xml_request, currency):\n date = xml_request.paydate\n element = self._generate_element('ACCOUNT')\n for trade in xml_request.valid_trades_list:\n if trade.Currency().Name() == currency:\n accounts = trade.GenerateSettlements(date, date)\n break\n\n if accounts:\n account = accounts[0].AcquirerAccountRef()\n if currency == 'ZAR':\n\n element.append(self._generate_element('NAME', xml_request.confirmation.AcquirerContactRef().Fullname2()))\n element.append(self._generate_element('NUMBER', account.Account()[7:18]))\n element.append(self._generate_element('BANK', account.CorrespondentBank().Name()))\n element.append(self._generate_element('BRANCH', account.Account()[:6]))\n element.append(self._generate_element('REFERENCE', str(xml_request.trade.Counterparty().Fullname())))\n element.append(self._generate_element('CURRENCY', str(currency)))\n else:\n element.append(self._generate_element('NAME', xml_request.confirmation.AcquirerContactRef().Fullname2()))\n element.append(self._generate_element('NUMBER', account.Account()))\n element.append(self._generate_element('BANK', account.CorrespondentBank().Name()))\n element.append(self._generate_element('BRANCH', account.Bic().Name()))\n element.append(self._generate_element('REFERENCE', str(xml_request.trade.Counterparty().Fullname())))\n element.append(self._generate_element('CURRENCY', str(currency)))\n return element\n\n def get_date_payable(self, xml_request):\n\n date = datetime.strptime(acm.Time().DateAddDelta(xml_request.date, 0, 0, 7), '%Y-%m-%d').strftime('%d %B %Y')\n\n return self._generate_element('PAY_DATE', date)\n\n def _generate_subject_element(self, xml_request):\n \"\"\"\n Generate the document SUBJECT XML element and sub-\n elements.\n \"\"\"\n return self._generate_element('SUBJECT', 'Repayment Notice')\n\n def is_last_element_curr_loop(self, currency, xml_request):\n\n return self._generate_element('LAST_ELEMENT', str(currency == xml_request.currencies[-1]))\n\n def _generate_document_specific_element(self, xml_request):\n \"\"\"\n Generate the document RATENOTICE XML element and sub-\n elements.\n \"\"\"\n main_element = self._generate_element('REPAYMENTNOTICE')\n facility_agreement = xml_request.confirmation\n facility_aggr = self.rate_notice_facility_agreement(facility_agreement)\n\n for currency in xml_request.currencies:\n element = self._generate_element('MAIN_CURRENCY')\n element.append(self._generate_element('FACIL_AGREE', facility_aggr))\n element.append(self.get_facilities_xml_element(xml_request, currency))\n element.append(self.get_legalnotice_loan(xml_request))\n element.append(self.get_account_details(xml_request, currency.Name()))\n element.append(self.get_date_payable(xml_request))\n element.append(self.is_last_element_curr_loop(currency, xml_request))\n main_element.append(element)\n\n return main_element\n\n\n\n","sub_path":"Extensions/ABSA Documentation/FPythonCode/LoanRepaymentNoticeXMLGenerator.py","file_name":"LoanRepaymentNoticeXMLGenerator.py","file_ext":"py","file_size_in_byte":13120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"349500791","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom ddpg import parse_args\nfrom cl_main import cl_run\nfrom cl_learning import Helper\nargs = parse_args()\n\nargs['rb_min_size'] = 1000\nargs['reach_return'] = 526.0\nargs['default_damage'] = 4132.00\nargs['perf_td_error'] = True\nargs['perf_l2_reg'] = True\nargs['steps'] = 300000\nargs[\"rb_max_size\"] = args['steps']\n#args[\"cl_batch_norm\"] = True\n#args['cl_structure'] = 'ffcritic:fc_relu_4;fc_relu_3;fc_relu_3'\nargs[\"cl_batch_norm\"] = False\nargs['cl_structure'] = 'rnnc:gru_tanh_6_dropout;fc_linear_3'\nargs[\"cl_stages\"] = \"balancing_tf;balancing;walking:monotonic\"\nargs['cl_depth'] = 2\nargs['cl_pt_shape'] = (args['cl_depth'],3)\nargs['test_interval'] = 30\n\n\n#args[\"cl_target\"] = True\nexport_names = \"eq_curriculum_network_depth_\" + str(args['cl_depth'])\nnn_params = (export_names, \"{}_stat.pkl\".format(export_names))\nargs[\"cl_pt_load\"] = nn_params[1]\n\n\n# Parameters\ntasks = {\n 'balancing_tf': 'cfg/leo_balancing_tf.yaml',\n 'balancing': 'cfg/leo_balancing.yaml',\n 'walking': 'cfg/leo_walking.yaml'\n }\nstarting_task = 'balancing_tf'\nhp = Helper(args, 'cl', 'ddpg', tasks, starting_task, 1, use_mp=False)\n\n# Run actual script.\nconfig, tasks, starting_task = hp.gen_cfg([None], 1)[0]\nconfig[\"cl_load\"] = nn_params[0]\ncl_run(tasks, starting_task, **config)\n","sub_path":"grl_learn_using_cl.py","file_name":"grl_learn_using_cl.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"501659566","text":"# -*- coding: utf-8 -*-\n#################################################################################\n# Author : Acespritech Solutions Pvt. Ltd. ()\n# Copyright(c): 2012-Present Acespritech Solutions Pvt. Ltd.\n# All Rights Reserved.\n#\n# This program is copyright property of the author mentioned above.\n# You can`t redistribute it and/or modify it.\n#\n#################################################################################\n\nfrom odoo import models, fields, api,_\n\n\nclass hr_employee(models.Model):\n _inherit = \"hr.employee\"\n\n weekday_ot_rate = fields.Float(string=\"Weekday OT Rate\")\n weekend_ot_rate = fields.Float(string=\"Weekend OT Rate\")\n overtime_count = fields.Integer(stirng=\"Overtime Count\", compute='get_overtime_count')\n\n @api.multi\n def get_overtime_count(self):\n for each in self:\n each.overtime_count = self.env['hr.employee.overtime'].search_count([('employee_id', '=', each.id)])\n\n @api.multi\n def related_overtime_view(self):\n return {\n 'type': 'ir.actions.act_window',\n 'name': _('Employee Overtime'),\n 'res_model': 'hr.employee.overtime',\n 'view_type': 'form',\n 'view_mode': 'tree',\n 'target': 'current',\n 'domain': [('employee_id', '=', self.id)]\n }\n\n\nclass hr_attendance(models.Model):\n _inherit = \"hr.attendance\"\n\n employee_ot_id = fields.Many2one('hr.employee.overtime', string=\"Related Overtime\", readonly=True)\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:","sub_path":"quality_control_team/flexi_hr_ee/hr_overtime/models/hr_employee 2.py","file_name":"hr_employee 2.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"261673941","text":"import tkinter as tk\nfrom tkinter import ttk\n\n\nclass UserForm(tk.Frame):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n # Declaring Variables.\n self.user_name = tk.StringVar()\n self.greetings = tk.StringVar()\n\n label_user_name = ttk.Label(self, text=\"Enter your name:\")\n text_user_name = ttk.Entry(self, textvariable=self.user_name)\n\n button_update_message = ttk.Button(self, text=\"Update\", command=self.on_name_change)\n\n label_greetings = ttk.Label(self, textvariable=self.greetings)\n\n # Form Layout\n label_user_name.grid(row=0, column=0, sticky=tk.W)\n text_user_name.grid(row=0, column=1, sticky=(tk.W + tk.E))\n button_update_message.grid(row=0, column=2, sticky=tk.E)\n\n label_greetings.grid(row=1, column=0, columnspan=3)\n\n\n def on_name_change(self):\n if self.user_name.get().strip():\n self.greetings.set(f'Hello {self.user_name.get()}')\n else:\n self.greetings.set(f'Hello No Name')\n\n\nclass UserInformationApplication(tk.Tk):\n\n def __init__(self, screenName=None, baseName=None, className=\"User Information\", useTk=1, sync=0, use=None):\n super().__init__(screenName=screenName, baseName=baseName,\n className=className, useTk=useTk, sync=sync, use=use)\n\n # Windows Properties\n self.title(\"User Information\")\n self.geometry(\"400x150\")\n\n # Creating the Form\n UserForm(self).grid(sticky=(tk.E + tk.W + tk.N + tk.S))\n\n\ndef main():\n window = UserInformationApplication()\n window.mainloop()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Intermediate/Day9/5guiinputdemo.py","file_name":"5guiinputdemo.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"30405437","text":"#!/usr/bin/env python\r\n# -- coding: utf-8 --\r\nimport sys\r\nimport json\r\nimport operator\r\nimport jieba\r\nimport os\r\n\r\njieba.load_userdict('../raw_datas/jieba_dict_lower.txt')\r\n\r\nreload(sys)\r\nsys.setdefaultencoding(\"utf-8\")\r\n\r\nclass Titleclassify():\r\n def __init__(self,title_dict_path,classify_dict_path,vocab_target_path,data_to_classify_path):\r\n self.title_dict_path=title_dict_path\r\n self.classify_dict_path=classify_dict_path\r\n self.vocab_target_path=vocab_target_path\r\n self.title_dict=self.load_title_dict()\r\n self.classify_dict = self.load_classify_dict()\r\n self.vocab_target_dict = self.load_vocab_target()\r\n self.data_to_classify_path = data_to_classify_path\r\n\r\n def load_title_dict(self):\r\n title_dict = json.load(open(self.title_dict_path, 'r'))\r\n return title_dict\r\n\r\n def load_classify_dict(self):\r\n classify_dict = json.load(open(self.classify_dict_path, 'r'))\r\n return classify_dict\r\n\r\n def load_vocab_target(self):\r\n vocab_target_dict = {line.strip().split('\\x01')[0].decode('utf-8'): line.strip().split('\\x01')[1] for line in\r\n open(self.vocab_target_path, 'r').readlines()}\r\n return vocab_target_dict\r\n\r\n def title_classify(self,line):\r\n classify_result={}\r\n title=line.strip().split('\\x01')[0].decode('utf-8')\r\n for k,v in self.title_dict.items():\r\n for t,rank in v.items():\r\n if t in title:\r\n classify_result[k]=rank\r\n break\r\n print(classify_result)\r\n sort_dict=sorted(classify_result.iteritems(),key=operator.itemgetter(1),reverse=False)\r\n subtype_num=0\r\n res={}\r\n for k, v in sort_dict:\r\n subtype_num += 1\r\n if subtype_num < 6:\r\n res[k] = v\r\n return res\r\n\r\n\r\n\r\n def content_classify(self,line,class_dict):\r\n kw_freq_dict = {}\r\n line_dict = {}\r\n job_desc = line.strip().split('\\x01')[0] + ' ' + line.strip().split('\\x01')[1]\r\n cut_list = list(jieba.cut(job_desc, cut_all=False))\r\n for kw in cut_list:\r\n line_dict.setdefault(kw, 0)\r\n line_dict[kw] += 1\r\n for kw in line_dict:\r\n if kw in self.vocab_target_dict:\r\n kw_freq_dict[kw] = line_dict[kw]\r\n classify_result_prob_dict = {}\r\n for subtype in class_dict:\r\n condition_prob = 0.0\r\n for k in kw_freq_dict:\r\n if k in class_dict[subtype][\"exist_kw_conprob\"]:\r\n condition_prob += class_dict[subtype][\"exist_kw_conprob\"][k] * kw_freq_dict[k]\r\n else:\r\n condition_prob += class_dict[subtype][\"nexist_kw_conprob\"] * kw_freq_dict[k]\r\n classify_result_prob_dict[subtype] = class_dict[subtype][\"prob_log\"] + condition_prob\r\n sort_dict = sorted(classify_result_prob_dict.iteritems(), key=operator.itemgetter(1), reverse=True)\r\n subtype_num = 0\r\n result = {}\r\n for k, v in sort_dict:\r\n subtype_num += 1\r\n if subtype_num < 6:\r\n result[k] = v\r\n return result\r\n\r\n\r\n\r\n def combine_classify(self):\r\n class_dict = self.classify_dict\r\n with open('combine_0.6_1.0_result', 'a') as fw:\r\n line_counter = 0\r\n correct_counter = 0\r\n classify_type_num = 0\r\n for filename in os.listdir(self.data_to_classify_path):\r\n print(filename)\r\n input = open(self.data_to_classify_path + filename)\r\n line = str(input.readline())\r\n line_counter_1 = 0\r\n correct_counter_1 = 0\r\n while line != None and len(line) > 1:\r\n line_counter+=1\r\n line_counter_1+=1\r\n print(line_counter_1)\r\n position_title=line.strip().split('\\x01')[0].decode('utf-8')\r\n if len(position_title) > 8:\r\n # print(position_title)\r\n result=self.content_classify(line,class_dict=class_dict)\r\n else:\r\n result=self.title_classify(line)\r\n if result=={}:\r\n result = self.content_classify(line, class_dict=class_dict)\r\n if filename.split('_')[1] in result:\r\n correct_counter_1 += 1\r\n correct_counter+=1\r\n line = str(input.readline())\r\n print(filename.split('_')[1])\r\n acc_rate_1 = float(correct_counter_1) / float(line_counter_1)\r\n classify_type_num += 1\r\n print('classified_type_num:', str(classify_type_num))\r\n with open('combine_test_result', 'a') as fw1:\r\n fw1.write(\r\n filename + '\\x01' + str(line_counter_1) + '\\x01' + str(correct_counter_1) + '\\x01' + format(\r\n acc_rate_1, '.5f') + '\\n')\r\n acc_rate = float(correct_counter) / float(line_counter)\r\n print(format(acc_rate, '.5f'))\r\n fw.write(str(len(self.vocab_target_dict)) + '\\x01' + str(line_counter) + '\\x01' + str(\r\n correct_counter) + '\\x01' + format(acc_rate, '.5f') + '\\n')\r\n\r\n\r\nif __name__ == '__main__':\r\n # title_dict_path='D:/wrokmy/position_rec/target_datas/title_dict'\r\n # data_to_classify_path='D:/wrokmy/position_rec/target_datas/'\r\n # classify_dict_path='D:/wrokmy\\position_rec/target_datas/1_plus_remove_0.6_1.0/classify_dict'\r\n # vocab_target_path='D:/wrokmy\\position_rec/target_datas/1_plus_remove_0.6_1.0/all_type_vocab_dict_target'\r\n\r\n title_dict_path='filter_title_dict'\r\n data_to_classify_path='../process_datas/test_data_files_1per/'\r\n classify_dict_path='classify_dict'\r\n vocab_target_path='all_type_vocab_dict_target'\r\n\r\n model=Titleclassify(title_dict_path=title_dict_path,data_to_classify_path=data_to_classify_path,\r\n classify_dict_path=classify_dict_path,vocab_target_path=vocab_target_path)\r\n model.combine_classify()","sub_path":"position_rec/data_position_title/filter_title_classify.py","file_name":"filter_title_classify.py","file_ext":"py","file_size_in_byte":6183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"631771175","text":"import os\nimport sys\nfrom pathlib import Path\nfrom typing import Type\n\nimport numpy as np\nfrom qtpy.QtCore import QByteArray, QEvent, Qt\nfrom qtpy.QtGui import QIcon, QKeyEvent, QKeySequence, QResizeEvent\nfrom qtpy.QtWidgets import (\n QCheckBox,\n QComboBox,\n QGridLayout,\n QHBoxLayout,\n QInputDialog,\n QLabel,\n QMessageBox,\n QPushButton,\n QVBoxLayout,\n QWidget,\n)\n\nimport PartSegData\nfrom PartSeg.common_gui.custom_load_dialog import CustomLoadDialog\nfrom PartSeg.common_gui.main_window import BaseMainMenu, BaseMainWindow\nfrom PartSeg.common_gui.stacked_widget_with_selector import StackedWidgetWithSelector\nfrom PartSeg.segmentation_analysis.measurement_widget import MeasurementWidget\nfrom PartSegCore import state_store\nfrom PartSegCore.algorithm_describe_base import SegmentationProfile\nfrom PartSegCore.analysis import ProjectTuple, algorithm_description, load_functions\nfrom PartSegCore.analysis.analysis_utils import SegmentationPipeline, SegmentationPipelineElement\nfrom PartSegCore.analysis.io_utils import create_history_element_from_project\nfrom PartSegCore.analysis.save_functions import save_dict\nfrom PartSegCore.io_utils import HistoryElement, WrongFileTypeException\nfrom PartSegCore.mask_create import calculate_mask_from_project\nfrom PartSegCore.segmentation.algorithm_base import SegmentationResult\nfrom PartSegCore.segmentation_info import SegmentationInfo\nfrom PartSegImage import TiffImageReader\n\nfrom ..common_gui.algorithms_description import AlgorithmChoose, InteractiveAlgorithmSettingsWidget\nfrom ..common_gui.channel_control import ChannelProperty\nfrom ..common_gui.custom_save_dialog import SaveDialog\nfrom ..common_gui.equal_column_layout import EqualColumnLayout\nfrom ..common_gui.mask_widget import MaskDialogBase\nfrom ..common_gui.multiple_file_widget import MultipleFileWidget\nfrom ..common_gui.stack_image_view import ColorBar\nfrom ..common_gui.universal_gui_part import TextShow\nfrom ..common_gui.waiting_dialog import ExecuteFunctionDialog, WaitingDialog\nfrom .advanced_window import SegAdvancedWindow\nfrom .batch_window import BatchWindow\nfrom .calculation_pipeline_thread import CalculatePipelineThread\nfrom .image_view import CompareImageView, ResultImageView, SynchronizeView\nfrom .partseg_settings import PartSettings\n\nCONFIG_FOLDER = os.path.join(state_store.save_folder, \"analysis\")\n\n\nclass Options(QWidget):\n def __init__(\n self,\n settings: PartSettings,\n channel_control2: ChannelProperty,\n left_image: ResultImageView,\n main_image: ResultImageView,\n synchronize: SynchronizeView,\n ):\n super().__init__()\n self._settings = settings\n self.left_panel = left_image\n self._ch_control2 = channel_control2\n self.synchronize_val = False\n self.hide_left_panel_chk = QCheckBox(\"Hide left panel\")\n self.hide_left_panel_chk.stateChanged.connect(self.hide_left_panel)\n self.synchronize_checkbox = QCheckBox(\"Synchronize view\")\n self.synchronize_checkbox.stateChanged.connect(synchronize.set_synchronize)\n self.interactive_use = QCheckBox(\"Interactive use\")\n self.execute_btn = QPushButton(\"Execute\")\n self.execute_btn.clicked.connect(self.execute_algorithm)\n self.execute_btn.setStyleSheet(\"QPushButton{font-weight: bold;}\")\n self.save_pipe_btn = QPushButton(\"Save pipeline\")\n self.save_pipe_btn.clicked.connect(self.save_pipeline)\n self.save_pipe_btn.setToolTip(\"Save current pipeline. Last element is last executed algorithm\")\n self.choose_pipe = QComboBox()\n self.choose_pipe.addItem(\"\")\n self.choose_pipe.addItems(list(self._settings.segmentation_pipelines.keys()))\n self.choose_pipe.currentTextChanged.connect(self.choose_pipeline)\n self.choose_pipe.setToolTip(\"Execute chosen pipeline\")\n self.save_profile_btn = QPushButton(\"Save profile\")\n self.save_profile_btn.setToolTip(\"Save values from current view\")\n self.save_profile_btn.clicked.connect(self.save_profile)\n self.choose_profile = QComboBox()\n self.choose_profile.addItem(\"\")\n self.choose_profile.addItems(list(self._settings.segmentation_profiles.keys()))\n self.choose_profile.setToolTip(\"Select profile to restore its settings. Execute if interactive is checked\")\n # image state\n self.compare_btn = QPushButton(\"Compare\")\n self.compare_btn.setDisabled(True)\n self.compare_btn.clicked.connect(self.compare_action)\n left_image.hide_signal.connect(self.compare_btn.setHidden)\n\n self.update_tooltips()\n self.choose_profile.currentTextChanged.connect(self.change_profile)\n self.interactive_use.stateChanged.connect(self.execute_btn.setDisabled)\n self.interactive_use.stateChanged.connect(self.interactive_change)\n self.algorithm_choose_widget = AlgorithmChoose(settings, algorithm_description.analysis_algorithm_dict)\n self.algorithm_choose_widget.result.connect(self.execution_done)\n self.algorithm_choose_widget.finished.connect(self.calculation_finished)\n self.algorithm_choose_widget.value_changed.connect(self.interactive_algorithm_execute)\n self.algorithm_choose_widget.algorithm_changed.connect(self.interactive_algorithm_execute)\n\n self.label = TextShow()\n\n # self.label.setWordWrap(True)\n # self.label.setTextInteractionFlags(Qt.TextSelectableByMouse)\n layout = QVBoxLayout()\n layout2 = QHBoxLayout()\n layout2.setSpacing(1)\n layout2.setContentsMargins(0, 0, 0, 0)\n layout3 = QHBoxLayout()\n layout3.setContentsMargins(0, 0, 0, 0)\n layout.setContentsMargins(0, 0, 0, 0)\n layout5 = QHBoxLayout()\n layout5.setContentsMargins(0, 0, 0, 0)\n layout5.addWidget(self.save_pipe_btn)\n layout5.addWidget(self.choose_pipe)\n layout4 = QHBoxLayout()\n layout4.setContentsMargins(0, 0, 0, 0)\n layout4.addWidget(self.save_profile_btn)\n layout4.addWidget(self.choose_profile)\n layout3.addWidget(self.interactive_use)\n layout3.addWidget(self.execute_btn)\n layout.addLayout(layout5)\n layout.addLayout(layout4)\n layout.addLayout(layout3)\n layout.addWidget(self.algorithm_choose_widget, 1)\n # layout.addLayout(self.stack_layout)\n layout.addWidget(self.label)\n # layout.addStretch(1)\n layout2.addWidget(self.hide_left_panel_chk)\n layout2.addWidget(self.synchronize_checkbox)\n layout.addLayout(layout2)\n layout.addWidget(self._ch_control2)\n # layout.setSpacing(0)\n self.setLayout(layout)\n\n def compare_action(self):\n if self.compare_btn.text() == \"Compare\":\n self._settings.set_segmentation_to_compare(self._settings.segmentation_info)\n self.compare_btn.setText(\"Remove\")\n else:\n self._settings.set_segmentation_to_compare(SegmentationInfo(None))\n self.compare_btn.setText(\"Compare\")\n\n def calculation_finished(self):\n self.execute_btn.setDisabled(self.interactive_use.isChecked())\n self.interactive_use.setEnabled(True)\n\n def save_pipeline(self):\n history = self._settings.get_history()\n if not history:\n QMessageBox.information(self, \"No mask created\", \"There is no new mask created\", QMessageBox.Ok)\n return\n mask_history = []\n for el in history:\n mask = el.mask_property\n segmentation = SegmentationProfile(\n name=\"Unknown\",\n algorithm=el.segmentation_parameters[\"algorithm_name\"],\n values=el.segmentation_parameters[\"values\"],\n )\n new_el = SegmentationPipelineElement(mask_property=mask, segmentation=segmentation)\n mask_history.append(new_el)\n name = self._settings.last_executed_algorithm\n if not name:\n QMessageBox.information(self, \"No segmentation\", \"No segmentation executed\", QMessageBox.Ok)\n return\n values = self._settings.get(f\"algorithms.{name}\", {})\n if len(values) == 0:\n QMessageBox.information(self, \"Some problem\", \"Pleas run execution again\", QMessageBox.Ok)\n return\n current_segmentation = SegmentationProfile(name=\"Unknown\", algorithm=name, values=values)\n\n while True:\n text, ok = QInputDialog.getText(self, \"Pipeline name\", \"Input pipeline name here\")\n if not ok:\n return\n if text in self._settings.segmentation_pipelines:\n if QMessageBox.No == QMessageBox.warning(\n self,\n \"Already exists\",\n \"Profile with this name already exist. Overwrite?\",\n QMessageBox.Yes | QMessageBox.No,\n QMessageBox.No,\n ):\n continue\n profile = SegmentationPipeline(name=text, segmentation=current_segmentation, mask_history=mask_history)\n self._settings.segmentation_pipelines[text] = profile\n self._settings.dump()\n self.choose_pipe.addItem(text)\n break\n\n def choose_pipeline(self, text):\n if text == \"\":\n return\n pipeline = self._settings.segmentation_pipelines[text]\n process_thread = CalculatePipelineThread(self._settings.image, self._settings.mask, pipeline)\n dial = WaitingDialog(process_thread)\n\n if dial.exec() and process_thread.result:\n pipeline_result = process_thread.result\n self._settings.mask = pipeline_result.mask\n self._settings.segmentation = pipeline_result.segmentation\n self._settings.full_segmentation = pipeline_result.full_segmentation\n self._settings.set_history(pipeline_result.history)\n self.label.setText(pipeline_result.description)\n self.algorithm_choose_widget.change_algorithm(pipeline.segmentation.algorithm, pipeline.segmentation.values)\n self.choose_pipe.setCurrentIndex(0)\n\n def update_tooltips(self):\n for i in range(1, self.choose_profile.count()):\n if self.choose_profile.itemData(i, Qt.ToolTipRole) is not None:\n continue\n text = self.choose_profile.itemText(i)\n profile: SegmentationProfile = self._settings.segmentation_profiles[text]\n tool_tip_text = str(profile)\n self.choose_profile.setItemData(i, tool_tip_text, Qt.ToolTipRole)\n for i in range(1, self.choose_pipe.count()):\n if self.choose_pipe.itemData(i, Qt.ToolTipRole) is not None:\n continue\n text = self.choose_pipe.itemText(i)\n profile: SegmentationPipeline = self._settings.segmentation_pipelines[text]\n tool_tip_text = str(profile)\n self.choose_pipe.setItemData(i, tool_tip_text, Qt.ToolTipRole)\n\n @staticmethod\n def update_combo_box(combo_box: QComboBox, dkt: dict):\n current_names = set(dkt.keys())\n prev_names = {combo_box.itemText(i) for i in range(1, combo_box.count())}\n new_names = current_names - prev_names\n delete_names = prev_names - current_names\n if len(delete_names) > 0:\n i = 1\n while i < combo_box.count():\n if combo_box.itemText(i) in delete_names:\n combo_box.removeItem(i)\n else:\n i += 1\n if len(new_names) > 0:\n combo_box.addItems(list(sorted(new_names)))\n\n def event(self, event: QEvent):\n if event.type() == QEvent.WindowActivate:\n # update combobox for segmentation\n self.update_combo_box(self.choose_profile, self._settings.segmentation_profiles)\n # update combobox for pipeline\n self.update_combo_box(self.choose_pipe, self._settings.segmentation_pipelines)\n self.update_tooltips()\n return super().event(event)\n\n def keyPressEvent(self, event: QKeyEvent):\n if (event.key() == Qt.Key_Enter or event.key() == Qt.Key_Return) and (event.modifiers() == Qt.ControlModifier):\n self.execute_btn.click()\n\n def save_profile(self):\n widget: InteractiveAlgorithmSettingsWidget = self.algorithm_choose_widget.current_widget()\n while True:\n text, ok = QInputDialog.getText(self, \"Profile Name\", \"Input profile name here\")\n if not ok:\n return\n if text in self._settings.segmentation_profiles:\n if QMessageBox.No == QMessageBox.warning(\n self,\n \"Already exists\",\n \"Profile with this name already exist. Overwrite?\",\n QMessageBox.Yes | QMessageBox.No,\n QMessageBox.No,\n ):\n continue\n resp = SegmentationProfile(text, widget.name, widget.get_values())\n self._settings.segmentation_profiles[text] = resp\n self._settings.dump()\n self.choose_profile.addItem(text)\n self.update_tooltips()\n break\n\n def change_profile(self, val):\n self.choose_profile.setToolTip(\"\")\n if val == \"\":\n return\n interactive = self.interactive_use.isChecked()\n self.interactive_use.setChecked(False)\n profile = self._settings.segmentation_profiles[val]\n self.algorithm_choose_widget.change_algorithm(profile.algorithm, profile.values)\n self.choose_profile.blockSignals(True)\n self.choose_profile.setCurrentIndex(0)\n self.choose_profile.blockSignals(False)\n self.interactive_use.setChecked(interactive)\n\n @property\n def segmentation(self):\n return self._settings.segmentation\n\n @property\n def interactive(self):\n return self.interactive_use.isChecked()\n\n def hide_left_panel(self, val):\n self._settings.set_in_profile(\"hide_left_panel\", val)\n if val:\n self.synchronize_val = self.synchronize_checkbox.isChecked()\n self.synchronize_checkbox.setChecked(False)\n else:\n self.synchronize_checkbox.setChecked(self.synchronize_val)\n self.synchronize_checkbox.setDisabled(val)\n self.left_panel.parent().setHidden(val)\n\n def interactive_change(self, val):\n if val:\n self.execute_algorithm()\n\n def algorithm_change(self, val):\n self._settings.set(\"current_algorithm\", val)\n if self.interactive:\n self.execute_algorithm()\n\n def interactive_algorithm_execute(self):\n if self.interactive:\n self.execute_algorithm()\n\n def execute_algorithm(self):\n widget: InteractiveAlgorithmSettingsWidget = self.algorithm_choose_widget.current_widget()\n if self._settings.image.is_time and not widget.algorithm.support_time():\n QMessageBox.information(\n self, \"Not supported\", \"This algorithm do not support time data. \" \"You can convert it in image adjust\"\n )\n return\n if self._settings.image.is_stack and not widget.algorithm.support_z():\n QMessageBox.information(\n self, \"Not supported\", \"This algorithm do not support stack data. \" \"You can convert it in image adjust\"\n )\n return\n self._settings.last_executed_algorithm = widget.name\n self.execute_btn.setDisabled(True)\n self.interactive_use.setDisabled(True)\n widget.execute()\n\n def execution_done(self, segmentation: SegmentationResult):\n if segmentation.info_text != \"\":\n QMessageBox.information(self, \"Algorithm info\", segmentation.info_text)\n self._settings.segmentation = segmentation.segmentation\n self.compare_btn.setEnabled(\n isinstance(segmentation.segmentation, np.ndarray) and np.any(segmentation.segmentation)\n )\n self._settings.additional_layers = segmentation.additional_layers\n self.label.setText(self.sender().get_info_text())\n\n def showEvent(self, _event):\n self.hide_left_panel_chk.setChecked(self._settings.get_from_profile(\"hide_left_panel\", False))\n\n\nclass MainMenu(BaseMainMenu):\n def __init__(self, settings: PartSettings, main_window):\n super().__init__(settings, main_window)\n self.settings = settings\n self.open_btn = QPushButton(\"Open\")\n self.save_btn = QPushButton(\"Save\")\n self.advanced_btn = QPushButton(\"Settings and Measurement\")\n self.mask_manager_btn = QPushButton(\"Mask manager\")\n self.batch_processing_btn = QPushButton(\"Batch Processing\")\n\n layout = QHBoxLayout()\n # layout.setSpacing(0)\n layout.setContentsMargins(0, 0, 4, 4)\n layout.addWidget(self.open_btn)\n layout.addWidget(self.save_btn)\n layout.addWidget(self.advanced_btn)\n layout.addWidget(self.mask_manager_btn)\n layout.addWidget(self.batch_processing_btn)\n self.setLayout(layout)\n\n self.open_btn.clicked.connect(self.load_data)\n self.save_btn.clicked.connect(self.save_file)\n self.advanced_btn.clicked.connect(self.advanced_window_show)\n self.mask_manager_btn.clicked.connect(self.mask_manager)\n self.batch_processing_btn.clicked.connect(self.batch_window)\n self.setFocusPolicy(Qt.StrongFocus)\n # self.test_btn.clicked.connect(self.test_fun)\n\n def resizeEvent(self, event: QResizeEvent):\n if event.size().width() < 800:\n self.batch_processing_btn.hide()\n else:\n self.batch_processing_btn.show()\n\n def keyPressEvent(self, event: QKeyEvent):\n if event.matches(QKeySequence.Save):\n self.save_file()\n elif event.matches(QKeySequence.Open):\n self.load_data()\n super().keyPressEvent(event)\n\n def save_file(self):\n base_values = self.settings.get(\"save_parameters\", dict())\n dial = SaveDialog(\n save_dict, system_widget=False, base_values=base_values, history=self.settings.get_path_history()\n )\n dial.selectFile(os.path.splitext(os.path.basename(self.settings.image_path))[0])\n dial.setDirectory(\n self.settings.get(\"io.save_directory\", self.settings.get(\"io.open_directory\", str(Path.home())))\n )\n dial.selectNameFilter(self.settings.get(\"io.save_filter\", \"\"))\n if dial.exec():\n save_location, selected_filter, save_class, values = dial.get_result()\n project_info = self.settings.get_project_info()\n self.settings.set(\"io.save_filter\", selected_filter)\n save_dir = os.path.dirname(save_location)\n self.settings.set(\"io.save_directory\", save_dir)\n self.settings.add_path_history(save_dir)\n base_values[selected_filter] = values\n\n def exception_hook(exception):\n from qtpy.QtCore import QMetaObject\n from qtpy.QtWidgets import QApplication\n\n instance = QApplication.instance()\n if isinstance(exception, ValueError):\n instance.warning = \"Save error\", f\"Error during saving\\n{exception}\"\n QMetaObject.invokeMethod(instance, \"show_warning\", Qt.QueuedConnection)\n else:\n raise exception\n\n dial2 = ExecuteFunctionDialog(\n save_class.save, [save_location, project_info, values], exception_hook=exception_hook\n )\n dial2.exec()\n\n def mask_manager(self):\n if self.settings.segmentation is None:\n QMessageBox.information(self, \"No segmentation\", \"Cannot create mask without segmentation\")\n return\n dial = MaskDialog(self.settings)\n dial.exec_()\n\n def load_data(self):\n def exception_hook(exception):\n from qtpy.QtCore import QMetaObject\n from qtpy.QtWidgets import QApplication\n\n instance = QApplication.instance()\n if isinstance(exception, ValueError) and exception.args[0] == \"Incompatible shape of mask and image\":\n instance.warning = (\n \"Open error\",\n \"Most probably you try to load mask from other image. \" \"Check selected files\",\n )\n QMetaObject.invokeMethod(instance, \"show_warning\", Qt.QueuedConnection)\n elif isinstance(exception, MemoryError):\n instance.warning = \"Open error\", f\"Not enough memory to read this image: {exception}\"\n QMetaObject.invokeMethod(instance, \"show_warning\", Qt.QueuedConnection)\n elif isinstance(exception, IOError):\n instance.warning = \"Open error\", f\"Some problem with reading from disc: {exception}\"\n QMetaObject.invokeMethod(instance, \"show_warning\", Qt.QueuedConnection)\n elif isinstance(exception, KeyError):\n instance.warning = \"Open error\", f\"Some problem project file: {exception}\"\n QMetaObject.invokeMethod(instance, \"show_warning\", Qt.QueuedConnection)\n print(exception, file=sys.stderr)\n elif isinstance(exception, WrongFileTypeException):\n instance.warning = (\n \"Open error\",\n \"No needed files inside archive. Most probably you choose file from segmentation mask\",\n )\n QMetaObject.invokeMethod(instance, \"show_warning\", Qt.QueuedConnection)\n else:\n raise exception\n\n try:\n dial = CustomLoadDialog(load_functions.load_dict, history=self.settings.get_path_history())\n dial.setDirectory(self.settings.get(\"io.open_directory\", str(Path.home())))\n dial.selectNameFilter(self.settings.get(\"io.open_filter\", next(iter(load_functions.load_dict.keys()))))\n if dial.exec_():\n result = dial.get_result()\n self.settings.set(\"io.open_filter\", result.selected_filter)\n load_dir = os.path.dirname(result.load_location[0])\n self.settings.set(\"io.open_directory\", load_dir)\n self.settings.add_path_history(load_dir)\n dial2 = ExecuteFunctionDialog(\n result.load_class.load,\n [result.load_location],\n {\"metadata\": {\"default_spacing\": self.settings.image_spacing}},\n exception_hook=exception_hook,\n )\n if dial2.exec():\n result = dial2.get_result()\n self.set_data(result)\n\n except ValueError as e:\n QMessageBox.warning(self, \"Open error\", \"{}\".format(e))\n\n def batch_window(self):\n if self.main_window.batch_window is not None:\n if self.main_window.batch_window.isVisible():\n self.main_window.batch_window.activateWindow()\n else:\n self.main_window.batch_window.show()\n else:\n self.main_window.batch_window = BatchWindow(self.settings)\n self.main_window.batch_window.show()\n\n def advanced_window_show(self):\n if self.main_window.advanced_window.isVisible():\n self.main_window.advanced_window.activateWindow()\n else:\n self.main_window.advanced_window.show()\n\n\nclass MaskDialog(MaskDialogBase):\n def next_mask(self):\n project_info: ProjectTuple = self.settings.get_project_info()\n mask_property = self.mask_widget.get_mask_property()\n self.settings.set(\"mask_manager.mask_property\", mask_property)\n mask = calculate_mask_from_project(mask_description=mask_property, project=project_info)\n self.settings.add_history_element(create_history_element_from_project(project_info, mask_property,))\n if self.settings.history_redo_size():\n history: HistoryElement = self.settings.history_next_element()\n self.settings.set(\"current_algorithm\", history.segmentation_parameters[\"algorithm_name\"])\n self.settings.set(\n f\"algorithm.{history.segmentation_parameters['algorithm_name']}\",\n history.segmentation_parameters[\"values\"],\n )\n self.settings.mask = mask\n self.close()\n\n def prev_mask(self):\n history: HistoryElement = self.settings.history_pop()\n algorithm_name = self.settings.last_executed_algorithm\n algorithm_values = self.settings.get(f\"algorithms.{algorithm_name}\")\n self.settings.fix_history(algorithm_name=algorithm_name, algorithm_values=algorithm_values)\n self.settings.set(\"current_algorithm\", history.segmentation_parameters[\"algorithm_name\"])\n self.settings.set(\n f\"algorithm.{history.segmentation_parameters['algorithm_name']}\", history.segmentation_parameters[\"values\"]\n )\n history.arrays.seek(0)\n seg = np.load(history.arrays)\n history.arrays.seek(0)\n self.settings.segmentation = seg[\"segmentation\"]\n self.settings.full_segmentation = seg[\"full_segmentation\"]\n if \"mask\" in seg:\n self.settings.mask = seg[\"mask\"]\n else:\n self.settings.mask = None\n self.close()\n\n\nclass MainWindow(BaseMainWindow):\n @classmethod\n def get_setting_class(cls) -> Type[PartSettings]:\n return PartSettings\n\n initial_image_path = PartSegData.segmentation_analysis_default_image\n\n def __init__(\n self, config_folder=CONFIG_FOLDER, title=\"PartSeg\", settings=None, signal_fun=None, initial_image=None\n ):\n super().__init__(config_folder, title, settings, signal_fun)\n self.channel_info = \"result_image\"\n self.files_num = 2\n self.setMinimumWidth(600)\n # thi isinstance is only for hinting in IDE\n assert isinstance(self.settings, PartSettings) # nosec\n self.main_menu = MainMenu(self.settings, self)\n # self.channel_control1 = ChannelControl(self.settings, name=\"raw_control\", text=\"Left panel:\")\n self.channel_control2 = ChannelProperty(self.settings, start_name=\"result_control\")\n self.raw_image = CompareImageView(self.settings, self.channel_control2, \"raw_image\")\n self.measurements = MeasurementWidget(self.settings)\n self.left_stack = StackedWidgetWithSelector()\n self.left_stack.addWidget(self.raw_image, \"Image\")\n self.left_stack.addWidget(self.measurements, \"Measurements\")\n self.result_image = ResultImageView(self.settings, self.channel_control2, \"result_image\")\n self.color_bar = ColorBar(self.settings, [self.raw_image, self.result_image])\n self.info_text = QLabel()\n self.info_text.setMinimumHeight(25)\n self.raw_image.text_info_change.connect(self.info_text.setText)\n self.result_image.text_info_change.connect(self.info_text.setText)\n self.synchronize_tool = SynchronizeView(self.raw_image, self.result_image, self)\n # image_view_control = self.image_view.get_control_view()\n self.options_panel = Options(\n self.settings, self.channel_control2, self.raw_image, self.result_image, self.synchronize_tool\n )\n # self.main_menu.image_loaded.connect(self.image_read)\n self.settings.image_changed.connect(self.image_read)\n self.advanced_window = SegAdvancedWindow(self.settings, reload_list=[self.reload])\n self.batch_window = None # BatchWindow(self.settings)\n\n self.multiple_files = MultipleFileWidget(self.settings, load_functions.load_dict, True)\n\n if initial_image is None:\n reader = TiffImageReader()\n im = reader.read(self.initial_image_path)\n im.file_path = \"\"\n self.settings.image = im\n elif initial_image is False:\n # FIXME This is for test opening\n pass\n else:\n self.settings.image = initial_image\n\n icon = QIcon(os.path.join(PartSegData.icons_dir, \"icon.png\"))\n self.setWindowIcon(icon)\n\n menu_bar = self.menuBar()\n file_menu = menu_bar.addMenu(\"File\")\n file_menu.addAction(\"&Open\").triggered.connect(self.main_menu.load_data)\n file_menu.addAction(\"&Save\").triggered.connect(self.main_menu.save_file)\n file_menu.addAction(\"Batch processing\").triggered.connect(self.main_menu.batch_window)\n view_menu = menu_bar.addMenu(\"View\")\n view_menu.addAction(\"Settings and Measurement\").triggered.connect(self.main_menu.advanced_window_show)\n view_menu.addAction(\"Additional output\").triggered.connect(self.additional_layers_show)\n view_menu.addAction(\"Additional output with data\").triggered.connect(lambda: self.additional_layers_show(True))\n view_menu.addAction(\"Napari viewer\").triggered.connect(self.napari_viewer_show)\n action = view_menu.addAction(\"Screenshot right panel\")\n action.triggered.connect(self.screenshot(self.result_image))\n action.setShortcut(QKeySequence.Print)\n view_menu.addAction(\"Screenshot left panel\").triggered.connect(self.screenshot(self.raw_image))\n image_menu = menu_bar.addMenu(\"Image operations\")\n image_menu.addAction(\"Image adjustment\").triggered.connect(self.image_adjust_exec)\n image_menu.addAction(\"Mask manager\").triggered.connect(self.main_menu.mask_manager)\n help_menu = menu_bar.addMenu(\"Help\")\n help_menu.addAction(\"State directory\").triggered.connect(self.show_settings_directory)\n help_menu.addAction(\"About\").triggered.connect(self.show_about_dialog)\n\n layout = QGridLayout()\n # layout.setContentsMargins(0, 0, 0, 0)\n layout.setSpacing(0)\n info_layout = QHBoxLayout()\n info_layout.addWidget(self.left_stack.selector)\n info_layout.addWidget(self.options_panel.compare_btn)\n info_layout.addWidget(self.info_text, 1, Qt.AlignHCenter)\n\n image_layout = EqualColumnLayout()\n image_layout.addWidget(self.left_stack)\n image_layout.addWidget(self.result_image)\n\n layout.setSpacing(0)\n layout.addWidget(self.main_menu, 0, 0, 1, 3)\n layout.addLayout(info_layout, 1, 1, 1, 2)\n layout.addWidget(self.multiple_files, 2, 0)\n layout.addWidget(self.color_bar, 2, 1)\n # layout.addWidget(self.left_stack, 2, 2)\n # layout.addWidget(self.result_image, 2, 3)\n layout.addLayout(image_layout, 2, 2, 1, 1)\n layout.addWidget(self.options_panel, 0, 3, 3, 1)\n layout.setColumnStretch(2, 1)\n widget = QWidget()\n widget.setLayout(layout)\n # self.multiple_files.setHidden(True)\n self.setCentralWidget(widget)\n try:\n geometry = self.settings.get_from_profile(\"main_window_geometry\")\n self.restoreGeometry(QByteArray.fromHex(bytes(geometry, \"ascii\")))\n except KeyError:\n pass\n\n def image_read(self):\n # self.raw_image.set_image()\n # self.raw_image.reset_image_size()\n # self.result_image.set_image()\n # self.result_image.reset_image_size()\n self.options_panel.interactive_algorithm_execute()\n self.setWindowTitle(f\"{self.title_base}: {os.path.basename(self.settings.image_path)}\")\n\n def read_drop(self, paths):\n self._read_drop(paths, load_functions)\n\n def reload(self):\n self.options_panel.algorithm_choose_widget.reload(algorithm_description.analysis_algorithm_dict)\n\n def event(self, event: QEvent):\n if event.type() == QEvent.WindowActivate:\n self.multiple_files.setVisible(self.settings.get(\"multiple_files\", False))\n return super().event(event)\n\n def closeEvent(self, event):\n # print(self.settings.dump_view_profiles())\n # print(self.settings.segmentation_dict[\"default\"].my_dict)\n self.settings.set_in_profile(\"main_window_geometry\", self.saveGeometry().toHex().data().decode(\"ascii\"))\n self.options_panel.algorithm_choose_widget.recursive_get_values()\n if self.batch_window is not None:\n if self.batch_window.is_working():\n ret = QMessageBox.warning(\n self,\n \"Batch work\",\n \"Batch work is not finished. \" \"Would you like to terminate it?\",\n QMessageBox.No | QMessageBox.Yes,\n )\n if ret == QMessageBox.Yes:\n self.batch_window.terminate()\n else:\n event.ignore()\n return\n self.batch_window.close()\n self.advanced_window.close()\n self.settings.dump()\n del self.batch_window\n del self.advanced_window\n super().closeEvent(event)\n\n @staticmethod\n def get_project_info(file_path, image):\n return ProjectTuple(file_path=file_path, image=image)\n\n def set_data(self, data):\n self.main_menu.set_data(data)\n","sub_path":"package/PartSeg/segmentation_analysis/main_window.py","file_name":"main_window.py","file_ext":"py","file_size_in_byte":32938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"18248301","text":"import tensorflow as tf\n\nEPSILON = 0.00001\n\ndef conv_wrapper(x, shape, strides, padding):\n weights = tf.get_variable(\"weights\",\n shape,\n initializer = tf.contrib.layers.xavier_initializer_conv2d())\n biases = tf.get_variable(\"biases\",\n [shape[3]],\n initializer = tf.constant_initializer(0.1))\n\n #tf.histogram_summary(\"weights_summary\", weights)\n\n conv = tf.nn.conv2d(x,\n weights,\n strides = strides,\n padding = padding)\n return conv + biases\n\ndef bn_wrapper(x, is_training):\n gamma = tf.get_variable(\"gamma\",\n [x.get_shape()[-1]],\n initializer = tf.constant_initializer(1.0))\n beta = tf.get_variable(\"beta\",\n [x.get_shape()[-1]],\n initializer = tf.constant_initializer(1.0))\n moving_mean = tf.get_variable(\"moving_mean\",\n [x.get_shape()[-1]],\n initializer = tf.constant_initializer(0.0),\n trainable = False)\n moving_variance = tf.get_variable(\"moving_variance\",\n [x.get_shape()[-1]],\n initializer = tf.constant_initializer(1.0),\n trainable = False)\n return tf.cond(is_training,\n lambda: bn_train_time(x, beta, gamma, moving_mean, moving_variance),\n lambda: bn_test_time(x, beta, gamma, moving_mean, moving_variance))\n\ndef bn_train_time(x, beta, gamma, moving_mean, moving_variance):\n mean, variance = tf.nn.moments(x, axes = [0,1,2])\n ALPHA = 0.90\n op_moving_mean = tf.assign(moving_mean,\n moving_mean * ALPHA + mean * (1-ALPHA))\n op_moving_variance = tf.assign(moving_variance,\n moving_variance * ALPHA + variance * (1-ALPHA))\n with tf.control_dependencies([op_moving_mean, op_moving_variance]):\n return tf.nn.batch_normalization(x,\n mean,\n variance,\n offset = beta,\n scale = gamma,\n variance_epsilon = EPSILON)\n\ndef bn_test_time(x, beta, gamma, moving_mean, moving_variance):\n return tf.nn.batch_normalization(x,\n moving_mean,\n moving_variance,\n offset = beta,\n scale = gamma,\n variance_epsilon = EPSILON)\n\ndef residual_block(x, C, is_training):\n with tf.variable_scope(\"h1_conv_bn\"):\n conv1 = conv_wrapper(x, shape = [3,3,C,C], strides = [1, 1, 1, 1], padding = \"SAME\")\n bn1 = bn_wrapper(conv1, is_training)\n relu1 = tf.nn.relu(bn1)\n with tf.variable_scope(\"h2_conv_bn\"):\n conv2 = conv_wrapper(relu1, shape = [3,3,C,C], strides = [1, 1, 1, 1], padding = \"SAME\")\n bn2 = bn_wrapper(conv2, is_training)\n\n res = x + bn2\n return tf.nn.relu(res)\n\ndef residual_block_reduce_size(x, C, is_training):\n last_C = x.get_shape().as_list()[-1]\n with tf.variable_scope(\"h1_conv_bn\"):\n conv1 = conv_wrapper(x, shape = [3,3,last_C,C], strides = [1, 2, 2, 1], padding = \"VALID\")\n bn1 = bn_wrapper(conv1, is_training)\n relu1 = tf.nn.relu(bn1)\n with tf.variable_scope(\"h2_conv_bn\"):\n conv2 = conv_wrapper(relu1, shape = [3,3,C,C], strides = [1, 1, 1, 1], padding = \"SAME\")\n bn2 = bn_wrapper(conv2, is_training)\n\n return tf.nn.relu(bn2)\n","sub_path":"resnet.py","file_name":"resnet.py","file_ext":"py","file_size_in_byte":3840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"35730699","text":"from rest_framework import viewsets\nfrom .models import ListModel\nfrom . import serializers\nfrom utils.page import MyPageNumberPagination\nfrom rest_framework.filters import OrderingFilter\nfrom django_filters.rest_framework import DjangoFilterBackend\nfrom rest_framework.response import Response\nfrom .filter import Filter\nfrom rest_framework.exceptions import APIException\n\nclass APIViewSet(viewsets.ModelViewSet):\n \"\"\"\n retrieve:\n Response a data list(get)\n\n list:\n Response a data list(all)\n\n create:\n Create a data line(post)\n\n delete:\n Delete a data line(delete)\n\n partial_update:\n Partial_update a data(patch:partial_update)\n\n update:\n Update a data(put:update)\n \"\"\"\n pagination_class = MyPageNumberPagination\n filter_backends = [DjangoFilterBackend, OrderingFilter, ]\n ordering_fields = ['id', \"create_time\", \"update_time\", ]\n filter_class = Filter\n\n def get_project(self):\n try:\n id = self.kwargs.get('pk')\n return id\n except:\n return None\n\n def get_queryset(self):\n id = self.get_project()\n if self.request.user:\n if id is None:\n return ListModel.objects.filter(openid=self.request.auth.openid, is_delete=False)\n else:\n return ListModel.objects.filter(openid=self.request.auth.openid, id=id, is_delete=False)\n else:\n return ListModel.objects.none()\n\n def get_serializer_class(self):\n if self.action in ['list', 'retrieve', 'destroy']:\n return serializers.GoodscolorGetSerializer\n elif self.action in ['create']:\n return serializers.GoodscolorPostSerializer\n elif self.action in ['update']:\n return serializers.GoodscolorUpdateSerializer\n elif self.action in ['partial_update']:\n return serializers.GoodscolorPartialUpdateSerializer\n else:\n return self.http_method_not_allowed(request=self.request)\n\n def create(self, request, *args, **kwargs):\n data = self.request.data\n data['openid'] = self.request.auth.openid\n if ListModel.objects.filter(openid=data['openid'], goods_color=data['goods_color'], is_delete=False).exists():\n raise APIException({\"detail\": \"Data exists\"})\n else:\n serializer = self.get_serializer(data=data)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n headers = self.get_success_headers(serializer.data)\n return Response(serializer.data, status=200, headers=headers)\n\n def update(self, request, pk):\n qs = self.get_object()\n if qs.openid != self.request.auth.openid:\n raise APIException({\"detail\": \"Cannot update data which not yours\"})\n else:\n data = self.request.data\n serializer = self.get_serializer(qs, data=data)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n headers = self.get_success_headers(serializer.data)\n return Response(serializer.data, status=200, headers=headers)\n\n def partial_update(self, request, pk):\n qs = self.get_object()\n if qs.openid != self.request.auth.openid:\n raise APIException({\"detail\": \"Cannot partial_update data which not yours\"})\n else:\n data = self.request.data\n serializer = self.get_serializer(qs, data=data, partial=True)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n headers = self.get_success_headers(serializer.data)\n return Response(serializer.data, status=200, headers=headers)\n\n def destroy(self, request, pk):\n qs = self.get_object()\n if qs.openid != self.request.auth.openid:\n raise APIException({\"detail\": \"Cannot delete data which not yours\"})\n else:\n qs.is_delete = True\n qs.save()\n serializer = self.get_serializer(qs, many=False)\n headers = self.get_success_headers(serializer.data)\n return Response(serializer.data, status=200, headers=headers)\n","sub_path":"goodscolor/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"263254108","text":"def solution(n, words):\n answer = [0, 0]\n\n turn = 1\n mem, prev = [words[0]], words[0]\n for idx, word in enumerate(words[1:]):\n if prev[-1] == word[0] and mem.count(word) == 0:\n prev = word\n mem.append(word)\n else:\n p_idx = n if (idx + 2) % n == 0 else (idx + 2) % n\n answer = [p_idx, turn]\n break\n if (idx + 2) % n == 0:\n turn += 1\n\n for turn in range(1, len(words)):\n if words[turn - 1][-1] != words[turn][0] or\\\n words[turn] in words[:turn]:\n return [(turn % n) + 1, (turn // n) + 1]\n\n # for p in range(1, len(words)):\n # if words[p][0] != words[p - 1][-1] or words[p] in words[:p]: return [(p % n) + 1, (p // n) + 1]\n # else:\n # return [0, 0]\n\n return answer\n\n\nprint(solution(3, [\"tank\", \"kick\", \"know\", \"wheel\", \"land\", \"dream\", \"mother\", \"robot\", \"tank\"]))\nprint(solution(5,\t[\"hello\", \"observe\", \"effect\", \"take\", \"either\", \"recognize\", \"encourage\", \"ensure\", \"establish\", \"hang\", \"gather\", \"refer\", \"reference\", \"estimate\", \"executive\"]))\nprint(solution(2,\t[\"hello\", \"one\", \"even\", \"never\", \"now\", \"world\", \"draw\"]))","sub_path":"prev/programmers/level2/영어_끝말잇기.py","file_name":"영어_끝말잇기.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"615601010","text":"# ----------------------------------------\n# LSM with BCM for MNIST test\n# add neurons to readout layer for multi-classification(one-versus-the-rest)\n# using softmax(logistic regression)\n# input layer is changed to 781*1 with encoding method\n# change the LSM structure according to Maass paper\n# new calculate flow as Maass_ST\n# simplify the coding method with only extend the rank\n# ----------------------------------------\n\nfrom brian2 import *\nfrom brian2tools import *\nimport scipy as sp\nimport struct\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import accuracy_score\nimport pickle\nfrom bqplot import *\nimport ipywidgets as widgets\nimport warnings\nimport os\n\n\nwarnings.filterwarnings(\"ignore\")\nprefs.codegen.target = \"numpy\"\nstart_scope()\nnp.random.seed(100)\ndata_path = '../../../Data/MNIST_data/'\n\n\n#-------define brian2 function------------\n@check_units(spike_window=1,result=1)\ndef get_rate(spike_window):\n return np.sum(spike_window, axis = 1)/spike_window.shape[1]\n\n@check_units(spike_window=1, spike = 1, result=1)\ndef get_spike_window(spike_window, spike):\n new_window = np.zeros(spike_window.shape)\n new_window[:,:-1] = spike_window[:,1:]\n new_window[:,-1] = spike\n return new_window\n\n\n#-------define general function------------\nclass Function():\n def __init__(self):\n pass\n\n def logistic(self, f):\n return 1 / (1 + np.exp(-f))\n\n def softmax(self, z):\n return np.array([(np.exp(i) / np.sum(np.exp(i))) for i in z])\n\n def gamma(self, a, size):\n return sp.stats.gamma.rvs(a, size=size)\n\n\nclass Base():\n def __init__(self, duration, dt):\n self.duration = duration\n self.dt = dt\n self.interval = duration * dt\n\n def get_states(self, input, running_time, sample, normalize=False):\n n = int(running_time / self.interval)\n step = int(self.interval / sample / defaultclock.dt)\n interval_ = int(self.interval / defaultclock.dt)\n temp = []\n for i in range(n):\n sum = np.sum(input[:, i * interval_: (i + 1) * interval_][:, ::-step], axis=1)\n temp.append(sum)\n if normalize:\n return MinMaxScaler().fit_transform(np.asarray(temp)).T\n else:\n return np.asarray(temp).T\n\n def update_states(self, type='pandas', *args, **kwargs):\n for seq, state in enumerate(kwargs):\n if type == 'pandas':\n kwargs[state] = kwargs[state].append(pd.DataFrame(args[seq]))\n elif type == 'numpy':\n kwargs[state] = self.np_extend(kwargs[state], args[seq], 1)\n return kwargs\n\n def normalization_min_max(self, arr):\n arr_n = arr\n for i in range(arr.size):\n x = float(arr[i] - np.min(arr)) / (np.max(arr) - np.min(arr))\n arr_n[i] = x\n return arr_n\n\n def mse(self, y_test, y):\n return sp.sqrt(sp.mean((y_test - y) ** 2))\n\n def classification(self, thea, data):\n data_n = self.normalization_min_max(data)\n data_class = []\n for a in data_n:\n if a >= thea:\n b = 1\n else:\n b = 0\n data_class.append(b)\n return np.asarray(data_class), data_n\n\n def allocate(self, G, X, Y, Z):\n V = np.zeros((X, Y, Z), [('x', float), ('y', float), ('z', float)])\n V['x'], V['y'], V['z'] = np.meshgrid(np.linspace(0, Y - 1, Y), np.linspace(0, X - 1, X),\n np.linspace(0, Z - 1, Z))\n V = V.reshape(X * Y * Z)\n np.random.shuffle(V)\n n = 0\n for g in G:\n for i in range(g.N):\n g.x[i], g.y[i], g.z[i] = V[n][0], V[n][1], V[n][2]\n n += 1\n return G\n\n def w_norm2(self, n_post, Synapsis):\n for i in range(n_post):\n a = Synapsis.w[np.where(Synapsis._synaptic_post == i)[0]]\n Synapsis.w[np.where(Synapsis._synaptic_post == i)[0]] = a / np.linalg.norm(a)\n\n def np_extend(self, a, b, axis=0):\n if a is None:\n shape = list(b.shape)\n shape[axis] = 0\n a = np.array([]).reshape(tuple(shape))\n return np.append(a, b, axis)\n\n def np_append(self, a, b):\n shape = list(b.shape)\n shape.insert(0, -1)\n if a is None:\n a = np.array([]).reshape(tuple(shape))\n return np.append(a, b.reshape(tuple(shape)), axis=0)\n\n def connection_matrix(self, n_pre, n_post, sources, targets, values):\n full_matrix = np.zeros((n_pre, n_post))\n full_matrix[targets, sources] = values\n return full_matrix\n\n def spectral_radius(self, S, is_norm = False):\n if isinstance(S, Synapses):\n n_pre = S.N_pre\n n_post = S.N_post\n sources = S.i[:]\n targets = S.j[:]\n values = S.w[:] - np.mean(S.variables['w'].get_value())\n if n_pre== n_post:\n ma = self.connection_matrix(n_pre, n_post, sources, targets, values)\n if is_norm :\n ma = ma /np.sqrt(np.var(ma))/np.sqrt(n_post)\n else:\n ma = ma /np.sqrt(n_post)\n else:\n return np.array(-1)\n a, b = np.linalg.eig(ma)\n return np.max(np.abs(a))\n else:\n raise ('The input need to be a object of Synapses')\n\n\nclass Readout():\n def __init__(self, function):\n self.function = function\n\n def data_init(self, M_train, M_test, label_train, label_test, rate, theta):\n self.rate = rate\n self.theta = theta\n self.iter = 0\n self.X_train = self.add_bis(M_train)\n self.X_test = self.add_bis(M_test)\n self.Y_train = self.prepare_Y(label_train)\n self.Y_test = self.prepare_Y(label_test)\n self.P = np.random.rand(self.X_train.shape[1], self.Y_train.shape[1])\n self.cost_train = 1e+100\n self.cost_test = 1e+100\n\n def predict_logistic(self, results):\n labels = (results > 0.5).astype(int).T\n return labels\n\n def calculate_score(self, label, label_predict):\n return [accuracy_score(i, j) for i, j in zip(label, label_predict)]\n\n def add_bis(self, data):\n one = np.ones((data.shape[1], 1)) # bis\n X = np.hstack((data.T, one))\n return X\n\n def prepare_Y(self, label):\n if np.asarray(label).ndim == 1:\n return np.asarray([label]).T\n else:\n return np.asarray(label).T\n\n def cost(self, X, Y, P):\n left = np.multiply(Y, np.log(self.function(X.dot(P))))\n right = np.multiply((1 - Y), np.log(1 - self.function(X.dot(P))))\n return -np.sum(np.nan_to_num(left + right), axis=0) / (len(Y))\n\n def train(self, X, Y, P):\n P_ = P + X.T.dot(Y - self.function(X.dot(P))) * self.rate\n return P_\n\n def test(self, X, p):\n return self.function(X.dot(p))\n\n def stop_condition(self):\n return ((self.cost_train - self.cost(self.X_train, self.Y_train, self.P)) > self.theta).any() and \\\n ((self.cost_test - self.cost(self.X_test, self.Y_test, self.P)) > self.theta).any() or self.iter < 100\n\n def readout(self):\n self.iter = 0\n while self.stop_condition():\n self.iter += 1\n self.cost_train = self.cost(self.X_train, self.Y_train, self.P)\n self.cost_test = self.cost(self.X_test, self.Y_test, self.P)\n self.P = self.train(self.X_train, self.Y_train, self.P)\n if self.iter % 10000 == 0:\n print(self.iter, self.cost_train, self.cost_test)\n print(self.iter, self.cost_train, self.cost_test)\n return self.test(self.X_train, self.P), self.test(self.X_test, self.P)\n\n def readout_sk(self, X_train, X_test, y_train, y_test, **kwargs):\n from sklearn.linear_model import LogisticRegression\n lr = LogisticRegression(**kwargs)\n lr.fit(X_train.T, y_train.T)\n y_train_predictions = lr.predict(X_train.T)\n y_test_predictions = lr.predict(X_test.T)\n return accuracy_score(y_train_predictions, y_train.T), accuracy_score(y_test_predictions, y_test.T)\n\n\nclass Result():\n def __init__(self):\n pass\n\n def result_save(self, path, *arg, **kwarg):\n if os.path.exists(path):\n os.remove(path)\n fw = open(path, 'wb')\n pickle.dump(kwarg, fw)\n fw.close()\n\n def result_pick(self, path):\n fr = open(path, 'rb')\n data = pickle.load(fr)\n fr.close()\n return data\n\n def animation(self, t, v, interval, duration, a_step=10, a_interval=100, a_duration=10):\n xs = LinearScale()\n ys = LinearScale()\n line = Lines(x=t[:interval], y=v[:, :interval], scales={'x': xs, 'y': ys})\n xax = Axis(scale=xs, label='x', grid_lines='solid')\n yax = Axis(scale=ys, orientation='vertical', tick_format='0.2f', label='y', grid_lines='solid')\n fig = Figure(marks=[line], axes=[xax, yax], animation_duration=a_duration)\n\n def on_value_change(change):\n line.x = t[change['new']:interval + change['new']]\n line.y = v[:, change['new']:interval + change['new']]\n\n play = widgets.Play(\n interval=a_interval,\n value=0,\n min=0,\n max=duration,\n step=a_step,\n description=\"Press play\",\n disabled=False\n )\n slider = widgets.IntSlider(min=0, max=duration)\n widgets.jslink((play, 'value'), (slider, 'value'))\n slider.observe(on_value_change, names='value')\n return play, slider, fig\n\n\nclass MNIST_classification(Base):\n def __init__(self, shape, duration, dt):\n super().__init__(duration, dt)\n self.shape = shape\n\n def load_Data_MNIST(self, n, path_value, path_label, is_norm=True):\n with open(path_value, 'rb') as f1:\n buf1 = f1.read()\n with open(path_label, 'rb') as f2:\n buf2 = f2.read()\n\n image_index = 0\n image_index += struct.calcsize('>IIII')\n im = []\n for i in range(n):\n temp = struct.unpack_from('>784B', buf1, image_index)\n im.append(np.reshape(temp, self.shape))\n image_index += struct.calcsize('>784B')\n\n label_index = 0\n label_index += struct.calcsize('>II')\n label = np.asarray(struct.unpack_from('>' + str(n) + 'B', buf2, label_index))\n if is_norm:\n f = lambda x: (x - np.min(x)) / (np.max(x) - np.min(x))\n df = pd.DataFrame({'value': pd.Series(im).apply(f), 'label': pd.Series(label)})\n else:\n df = pd.DataFrame({'value': pd.Series(im), 'label': pd.Series(label)})\n return df\n\n def load_Data_MNIST_all(self, path, is_norm=True):\n self.train = self.load_Data_MNIST(60000, path + 'train-images.idx3-ubyte',\n path + 'train-labels.idx1-ubyte', is_norm)\n self.test = self.load_Data_MNIST(10000, path + 't10k-images.idx3-ubyte',\n path + 't10k-labels.idx1-ubyte', is_norm)\n\n def select_data(self, fraction, data_frame, is_order=True, **kwargs):\n try:\n selected = kwargs['selected']\n except KeyError:\n selected = np.arange(10)\n if is_order:\n data_frame_selected = data_frame[data_frame['label'].isin(selected)].sample(\n frac=fraction).sort_index().reset_index(drop=True)\n else:\n data_frame_selected = data_frame[data_frame['label'].isin(selected)].sample(frac=fraction).reset_index(\n drop=True)\n return data_frame_selected\n\n def _encoding_cos_rank(self, x, n, A):\n encoding = np.zeros((x.shape[0] * A, n * x.shape[1]), dtype=' 0 and priority < 100\n assert assoc in (ASSOC_NONE, ASSOC_LEFT, ASSOC_RIGHT)\n self.type = type\n self.symbol = symbol\n self.priority = priority\n self.function = function\n self.assoc = assoc\n def is_left_assoc(self):\n return self.assoc == ASSOC_LEFT\n\nclass OperatorGroup:\n lengths = []\n by_symbol = {}\n def __init__(self, operators):\n self.by_symbol = { op.symbol: op for op in operators }\n length_set = set([ len(op.symbol) for op in operators ])\n self.lengths = sorted(length_set, reverse=True)\n def parse(self, s):\n for length in self.lengths:\n saved_pos = s.tell()\n op = self.by_symbol.get(s.read(length))\n if op:\n return op\n s.seek(saved_pos)\n return None\n\n# priority booster allows to raise a priority of an infix operator\n# based on types and/or values of LHS and RHS operands\nclass InfixPriorityBooster:\n # is_applicable is a function of three arguments:\n # LHS value, RHS value and an operator (the instance of Operator).\n def __init__(self, is_applicable, boost_value):\n self.is_applicable = is_applicable\n self.boost_value = boost_value\n\nclass ExpressionTraits:\n def __init__(self,\\\n operators,\n infix_boosters=[],\n parse_elementary_factor=parse_number,\n fcall=lambda name, args: 0,\n on_missing_right_paren = lambda lparen_pos: None):\n self.unary_prefix_ops = OperatorGroup(\n [ op for op in operators if op.type == UNARY_PREFIX ])\n self.binary_infix_ops = OperatorGroup(\n [ op for op in operators if op.type == BINARY_INFIX ])\n self.infix_boosters = sorted(\n infix_boosters,\n key=lambda b: b.value,\n reverse=True)\n # add the default boost with zero boost\n default_infix_booster = InfixPriorityBooster(\n lambda lhs, rhs, op: True,\n 0)\n self.infix_boosters.append(default_infix_booster)\n #\n self.parse_elementary_factor = parse_elementary_factor\n self.fcall = fcall\n self.on_missing_right_paren = on_missing_right_paren\n\nnumerical_expression_traits = ExpressionTraits(\n [\n Operator(BINARY_INFIX, '+', 10, operator.add, ASSOC_LEFT),\n Operator(BINARY_INFIX, '-', 10, operator.sub, ASSOC_LEFT),\n Operator(BINARY_INFIX, '*', 20, operator.mul, ASSOC_LEFT),\n Operator(BINARY_INFIX, '·', 20, operator.mul, ASSOC_LEFT),\n Operator(BINARY_INFIX, '/', 20, operator.truediv, ASSOC_LEFT),\n Operator(UNARY_PREFIX, '-', 30, operator.neg, ASSOC_NONE),\n Operator(UNARY_PREFIX, '+', 30, operator.pos, ASSOC_NONE),\n Operator(BINARY_INFIX, '^', 40, operator.pow, ASSOC_RIGHT),\n Operator(BINARY_INFIX, '**', 40, operator.pow, ASSOC_RIGHT)\n ])\n\n# the expression parser is based on \"precedence climbing\" algorithm\n# http://www.engr.mun.ca/~theo/Misc/exp_parsing.htm\n#\n# min_priority is a minimum allowed priority of an operator to be parsed\n# (thus we can set a barrier)\ndef parse_expression(s, traits=numerical_expression_traits, min_priority=0):\n saved_pos = s.tell()\n lhs = parse_term(s, traits)\n if not lhs:\n s.seek(saved_pos)\n return None\n while 1:\n saved_pos = s.tell()\n\n op = parse_binary_infix_op(s, traits)\n if not op:\n # no more infix operators. the result is in lhs\n break\n # allow whitespace after an infix operator\n parse_whitespace(s)\n\n # boosters are sorted in descending order;\n # the default booster (zero boost for any LHS and RHS)\n # added to the end of the sorted list\n rhs = None\n for booster in traits.infix_boosters:\n boosted_priority = op.priority + booster.boost_value\n if boosted_priority >= min_priority:\n barrier = boosted_priority + 1 if op.is_left_assoc() else boosted_priority\n pos_before_expr = s.tell()\n rhs = parse_expression(s, traits, min_priority=barrier)\n if rhs and booster.is_applicable(lhs, rhs, op):\n lhs = op.function(lhs, rhs)\n break\n else:\n s.seek(pos_before_expr)\n rhs = None\n if not rhs:\n break\n s.seek(saved_pos)\n return lhs\n\ndef parse_binary_infix_op(s, traits):\n saved_pos = s.tell()\n ws = parse_whitespace(s)\n op = traits.binary_infix_ops.parse(s)\n if op or not ws:\n return op\n # allow whitespace to be an a binary infix op\n s.seek(saved_pos)\n return traits.binary_infix_ops.parse(s)\n\ndef parse_term(s, traits):\n saved_pos = s.tell()\n op = traits.unary_prefix_ops.parse(s)\n if op:\n expr = parse_expression(s, traits, min_priority=op.priority)\n if expr:\n return op.function(expr)\n else:\n return parse_factor(s, traits)\n s.seek(saved_pos)\n return None\n\ndef parse_factor(s, traits):\n saved_pos = s.tell()\n lparen_pos = s.tell()\n if s.read(1) == '(':\n parse_whitespace(s)\n factor = parse_expression(s, traits)\n parse_whitespace(s)\n if s.read(1) == ')':\n return factor\n else:\n traits.on_missing_right_paren(lparen_pos)\n else:\n s.seek(saved_pos)\n res = parse_function(s, traits)\n if res is None:\n res = traits.parse_elementary_factor(s)\n if res is not None:\n return res\n s.seek(saved_pos)\n return None\n\n#\n# function call\n#\n\ndef parse_function(s, traits):\n saved_pos = s.tell()\n name = parse_function_name(s)\n parse_whitespace(s)\n lparen_pos = s.tell()\n if s.read(1) == '(':\n parse_whitespace(s)\n args = parse_comma_separated_list(s, traits)\n parse_whitespace(s)\n if s.read(1) == ')':\n return traits.fcall(name, args)\n else:\n traits.on_missing_right_paren(lparen_pos)\n s.seek(saved_pos)\n return None\n\ndef parse_function_name(s):\n saved_pos = s.tell()\n h = s.read(1)\n if h.isalpha() or h == '_':\n return h + (parse_while(s, lambda c: c.isalnum() or c == '_') or '')\n s.seek(saved_pos)\n return None\n\ndef parse_comma_separated_list(s, traits):\n items = []\n while 1:\n saved_pos = s.tell()\n item = None\n if items:\n parse_whitespace(s)\n item = parse_comma_separated_item(s, traits)\n else:\n item = parse_expression(s, traits)\n if not item:\n s.seek(saved_pos)\n return items\n items.append(item)\n\ndef parse_comma_separated_item(s, traits):\n saved_pos = s.tell()\n if s.read(1) == ',':\n parse_whitespace(s)\n expr = parse_expression(s, traits)\n if expr:\n return expr\n s.seek(saved_pos)\n return None\n","sub_path":"pydimensions/parser/expression.py","file_name":"expression.py","file_ext":"py","file_size_in_byte":7547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"272036381","text":"import bisect\nimport collections\n\n\nclass Solution:\n def sumOfFlooredPairs_slow(self, nums) -> int:\n mod = 10 ** 9 + 7\n d = collections.Counter(nums)\n a = sorted(d.keys())\n n = len(a)\n count = [0]\n for i in range(n):\n count.append(count[-1] + d[a[i]])\n res = 0\n\n for i in range(n - 1, -1, -1):\n x = a[i]\n up = i + 1\n s = 0\n while up > 0:\n multi = x // a[up - 1]\n j = bisect.bisect_right(a, x // (multi + 1))\n s += (count[up] - count[j]) * multi * d[x]\n up = j\n res = (res + s) % mod\n return res\n\n def sumOfFlooredPairs(self, nums) -> int:\n mod = 10 ** 9 + 7\n d = collections.Counter(nums)\n a = sorted(d.keys())\n n = len(a)\n count = [0]\n for i in range(n):\n count.append(count[-1] + d[a[i]])\n res = 0\n\n for i in range(n):\n x = a[i]\n j = i\n s = 0\n while j < n:\n multi = a[j] // x\n k = bisect.bisect_left(a, x * (multi + 1))\n s += (count[k] - count[j]) * multi * d[x]\n j = k\n res = (res + s) % mod\n return res\n\n\ns = Solution()\nprint(s.sumOfFlooredPairs([2, 5, 9]))\nprint(s.sumOfFlooredPairs([7, 7, 7, 7, 7, 7, 7]))\n","sub_path":"leetcode/2021/bicontest/bcontest-052/bContest4.py","file_name":"bContest4.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"441881085","text":"# '''\n# Please read the license file.\n# LabMate.AI was designed to help identifying optimized conditions for chemical reactions.\n# You will need the Python libraries below (NumPy, Pandas and Scikit-learn) and 10 random reactions to run LabMate.AI.\n# '''\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import KFold\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.externals.joblib import dump\nimport random\nimport time\n# pwd\nprint('Welcome! Let me work out what is the best experiment for you to run...')\n# print(\"Time: %s\", time.time())\nprint(time.strftime(\"%Y/%m/%d %H:%M:%S\"))## 带日期的12小时格式\n#\n# '''\n# The training data should be a tab separated file named 'train_data.txt'. The first column of the file is the reaction identifier and the last column is the objective variable (target). The columns in between correspond to descriptors. Otherwise please change accordingly.\n# See example files\n# '''\n# pwd\n# cd ActiveLearning-master/\nfilename = 'train_data716.txt'\ntrain = pd.read_csv(filename, sep= '\\\\t', engine='python')\nprint(train.head())#.head查看头5行\n# type(train)\n\narray = train.values\n# array\nX = array[:,:-1] #从第1列到倒数第二列,注意up to but not including\n# X\nY = array[:,-1]\n# Y #Y是最后一列数据\n\n\n\n\n\n'''\nGeneral settings below. These do not need to be changed.\nThe seed value is what makes the whole process deterministic. You may choose to change this number. #种子数很重要,决定性的\nThe possible number of estimators, max_features and max_depth is a good compromise, but may need to be adapted, if the number of features (columns) is very different.\n'''\n\nseed = 1 #随机数种子=1\nkfold = KFold(n_splits = 10, shuffle=True, random_state = seed) #10折,数据重新洗牌,随机数种子1\nscoring = 'neg_mean_absolute_error' #评分:neg_mean_absolute_error'\nmodel = RandomForestRegressor(random_state=seed) #建模,随机数种子1\nestimators = np.arange(100, 1050, 50) #估计器数量,100到1050,取50个数\n# estimators\nestimators_int = np.ndarray.tolist(estimators) #把array 变成list\n# estimators_int\nparam_grid = {'n_estimators':estimators_int, 'max_features':('auto', 'sqrt'), 'max_depth':[None, 2, 4]}\n\n\nprint('All good till now. I am figuring out the best method to analyze your data. Bear with me...')\n\n\n'''\nThis section makes LabMate.AI search for the best hyperparameters autonomously.\nIt will also save a file with the best score and store the ideal hyperparameters for future use.\n'''\n\ngrid = GridSearchCV(estimator=model, param_grid=param_grid, scoring=scoring, cv=kfold, n_jobs=6) #n_jobs要变成4核试试才行,先6核不要怕\ngrid_result = grid.fit(X, Y)\nnp.savetxt('best_score.txt', [\"best_score: %s\" % grid.best_score_], fmt ='%s')\nbest_params = pd.DataFrame([grid.best_params_], columns=grid.best_params_.keys())\n\n\nprint('... done! It is going to be lightspeed from here on out! :)')\n\n\n'''\nThis section loads all possible reactions (search space) and deletes all previously executed reactions from that file.\nThe file has the same format as the training data, but no \"Target\" column. Please check example file.\n'''\n\nfilename2 = 'all_combos.txt'\ndf_all_combos = pd.read_csv(filename2, sep= '\\\\t', engine='python')\ndf_train_corrected = train.iloc[:,:-1] #测试样本数据\nunseen = pd.concat([df_all_combos, df_train_corrected], sort = True).drop_duplicates(keep=False) #把all和train合并,去重\narray2 = unseen.values #去重后的数据传入array2\nX2 = array2[:,:] #X2的数据为: 合并后的数据,从第二列到最后一列,都是已知参数\n# X2.shape\ndf_all_combos2 = df_all_combos.iloc[:,:] #不要第一列pyridine 不知道为什么???\n\n\n\n\n\n'''\nLabMate.AI predicts the future in this section. It builds the model using the best hyperparameter set and predicts the reaction yield (numeric value) for each instance.\nFor your reference, the method creates a file with the feature importances\n'''\n\nmodel2 = RandomForestRegressor(n_estimators = grid.best_params_['n_estimators'], max_features = grid.best_params_['max_features'], max_depth = grid.best_params_['max_depth'], random_state = seed)\n#model2使用之前网格搜索得到的最优参数\nRF_fit = model2.fit(X, Y) #用X Y拟合model2\npredictions = model2.predict(X2) #预测 X2值\n# np.isnan(X2)\npredictions_df = pd.DataFrame(data=predictions, columns=['Prediction'])\nfeat_imp = pd.DataFrame(data=model2.feature_importances_, index=list(df_all_combos2.columns.values), columns=['Feature_importances'])\n#得到model2的特征重要性,构建一个dataframe\nfeat_imp = feat_imp.sort_values(by=['Feature_importances'], ascending = False)\n#排序\n\n\n\n\n\n'''\nLabMate.AI calculates variances for the predictions, which allows prioritizing the next best experiment, and creates a table with all the generated information.\n'''\n\nall_predictions = []\nfor e in model2.estimators_:\n all_predictions += [e.predict(X2)]\n #随机森林里产生了很多的estimators 用所有的估计器去预测X2的数据,返回预测值,构建一个包含所有预测值的list\n# all_predictions\nvariance = np.var(all_predictions, axis=0) #计算偏差,以横轴??\nvariance_df = pd.DataFrame(data=variance, columns=['Variance'])\n\nassert len(variance) == len(predictions) # control line\ninitial_data = pd.DataFrame(data=array2, columns = list(unseen.columns.values))\ndf = pd.concat([initial_data, predictions_df, variance_df], axis=1) #得到新的表格,包含原始值,预测值,偏差\n\n\n\n\n\n'''\nLabMate.AI now selects the next reaction to be performed.\n'''\n#看它用什么选\nfeat_imp_T = feat_imp.transpose() # creates a table with a single row stating the importance (0-1 scale) of each variable\nkeys1 = list(feat_imp_T.keys()) # collects the names of the features\nkeys2 = list(feat_imp_T.keys()) # same as above\nkeys1.insert(7,'Prediction') # Inserts \"Prediction\" in position 7 of the previously generated list\nkeys2.insert(7, 'Variance') # Inserts \"Variance\" in position 7 of the previously generated list\n\ndf_sorted = df.sort_values(by=[keys1[-1], keys1[0]], ascending=[False, False]) # Fetches the table with the predictions and variance and sorts: 1) high prediction first; 2) most important feature second (descending order) for overlapping predictions\npreliminary = df_sorted.iloc[0:5] # Collects the first five columns 最优数据\ndf_sorted2 = preliminary.sort_values(by=[keys2[-1], keys2[0]], ascending=[True, False]) # Sorts the top five rows by: 1) Low variance first; 2) most important feature second (descending order) for overlapping predictions\ntoPerform = df_sorted2.iloc[0] # First row is the selected reaction\n\n\n\n\n\n\n\n'''\nSave files\n'''\n\nfeat_imp.to_csv('feature_importances.txt', sep= '\\t')\nbest_params.to_csv('best_parameters.txt', sep= '\\t')\ntoPerform.to_csv('selected_reaction.txt', sep = '\\t', header=False)\ndf_sorted.to_csv('predictions.txt', sep = '\\t')\nfilename3 = 'random_forest_model_grid.sav'\ndump(grid, filename3)\n\nprint('You are all set! Have a good one, mate!')\n\n\n\n\n'''\nAfter performing the reaction simply edit the train_data.txt file with the reaction conditions used and target value, before running the script again. Enjoy and happy chemistry :)\n'''\nprint(time.strftime(\"%Y/%m/%d %H:%M:%S\"))## 带日期的12小时格式\n","sub_path":"continuous-variables/literature-code-in-python/LabMate-AI-changed.py","file_name":"LabMate-AI-changed.py","file_ext":"py","file_size_in_byte":7337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"449030271","text":"from flask import Flask, render_template, redirect\nfrom flask_pymongo import PyMongo\nimport scrape_mars\n\napp = Flask(__name__)\n\n\n# Use PyMongo to establish Mongo connection\nmongo = PyMongo(app, uri=\"mongodb://localhost:27017/mars_app\")\n\n\n# Set route\n@app.route(\"/\")\ndef index():\n mars_info = mongo.db.mars_info.find_one()\n \n return render_template(\"index.html\", mars_info=mars_info)\n\n@app.route(\"/scrape\")\ndef scraper():\n mars_info_collection = mongo.db.mars_info\n\n results_dict = scrape_mars.scrape()\n\n mars_info_collection.update({}, results_dict, upsert=True)\n \n return redirect(\"/\")\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"290282378","text":"import sys\nsys.stdin = open('input.txt','r')\ndef bfs(n,si,sj):\n cnt = 0\n di = [1,0,-1,0]\n dj = [0,1,0,-1]\n q = [0]*n*n*2\n\n front = -1\n rear = -1\n\n rear += 1\n q[rear] = si\n rear += 1\n q[rear] = sj\n arr[si][sj] = 0\n while(front!=rear):\n\n front += 1\n i = q[front]\n front += 1\n j = q[front]\n\n\n cnt+=1\n for k in range(4):\n ni = i + di[k]\n nj = j + dj[k]\n if(ni>=0 and ni=0 and njx:\n# a[t],a[i]=a[i],a[t]\n# t-=1\n# i-=1 #remain in the same i in this case\n# i+=1\n# return j\n# =============================================================================\ndef partition3(a,l,r):\n pivot_value=a[l]\n p_l=i=l\n p_r=r\n \n while i<=p_r:\n if a[i]= r:\n return\n k = random.randint(l, r)\n a[l], a[k] = a[k], a[l]\n #use partition3\n m = partition3(a, l, r)\n randomized_quick_sort(a, l, m[0] - 1);\n randomized_quick_sort(a, m[1] + 1, r);\n\n\nif __name__ == '__main__':\n input = sys.stdin.read()\n n, *a = list(map(int, input.split()))\n randomized_quick_sort(a, 0, n - 1)\n for x in a:\n print(x, end=' ')\n","sub_path":"week4_divide_and_conquer/quick_sort.py","file_name":"quick_sort.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"371310183","text":"# Name: Bunmi Oluwatudimu\r\n# Date: March 6th, 2020\r\n\r\n# The LinkedList class: a collection of nodes (Node: data and a link to the next node)\r\nfrom node import Node\r\n\r\nclass LinkedList():\r\n def __init__(self):\r\n self.__head = None\r\n\r\n def isEmpty(self):\r\n return self.__head == None\r\n\r\n # add a node at the end of the linked list\r\n def append(self, data):\r\n newNode = Node(data)\r\n\r\n if self.isEmpty(): # if list is empty, head will point to newNode\r\n self.__head = newNode\r\n\r\n else: # list is not empty, go to end of list and add newNode there\r\n current = self.__head\r\n while current.getNext() != None:\r\n current = current.getNext()\r\n current.setNext(newNode)\r\n\r\n # remove a node from the linked list\r\n def remove(self, item):\r\n current = self.__head\r\n previous = None\r\n found = False\r\n\r\n # first find item in the list\r\n while not found:\r\n if current.getData() == item:\r\n found = True\r\n else:\r\n previous = current\r\n current = current.getNext()\r\n\r\n if previous == None: # item was in the fist node\r\n self.__head = current.getNext()\r\n else: # item was somewhere after the first node\r\n previous.setNext(current.getNext())\r\n\r\n # search for item in linked list\r\n def search(self, item):\r\n current = self.__head\r\n found = False\r\n while current != None and not found:\r\n if current.getData() == item:\r\n found = True\r\n else:\r\n current = current.getNext()\r\n\r\n return found\r\n\r\n # overloaded operators\r\n def __getitem__(self, index): # used to suppport []\r\n current = self.__head\r\n\r\n for i in range(index):\r\n current = current.getNext()\r\n\r\n return current.getData()\r\n\r\n def __str__(self): # used to support print(myLinkedList)\r\n mystr = ''\r\n current = self.__head\r\n\r\n while current != None:\r\n mystr += str(current.getData())\r\n current = current.getNext()\r\n return mystr\r\n\r\n def __len__(self): # used to support len(myLinkedList)\r\n if self.__head == None: # if list is empty return 0\r\n return 0\r\n\r\n current = self.__head # list is not empty and has at least 1 Node\r\n counter = 1\r\n\r\n while current.getNext() != None:\r\n counter += 1\r\n current = current.getNext()\r\n return counter\r\n","sub_path":"linkedList.py","file_name":"linkedList.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"359649435","text":"# -*- coding: UTF-8 -*-\n\n\"\"\"\nThis file is part of Pondus, a personal weight manager.\nCopyright (C) 2008-10 Eike Nicklas \n\nThis program is free software licensed under the MIT license. For details\nsee LICENSE or http://www.opensource.org/licenses/mit-license.php\n\"\"\"\n\nimport os\nimport sys\n\nimport pygtk\npygtk.require('2.0')\nimport gtk\n\nfrom pondus.core import parameters\nfrom pondus.gui.dialog_message import MessageDialog\n\n\nclass FileLock(object):\n \"\"\"Implements a very simple file locking mechanism to prevent two\n instances of editing the same file.\"\"\"\n\n def __init__(self):\n \"\"\"Gets data neccessary to lock the datafile, asks for confirmation\n if the file is already locked and performs the lock if wanted.\"\"\"\n self.lockfilename = parameters.userdatafile + '.lck'\n self.pid = str(os.getpid())\n self.first_lock()\n\n def first_lock(self):\n \"\"\"Locks the datafile, asks for confirmation if the file is already\n locked and performs the lock if wanted.\"\"\"\n if not self.is_locked():\n self.lock()\n return\n elif not self.own_lock():\n title = _('Datafile locked, continue?')\n message = _('Another instance of pondus seems to be editing \\\nthe same datafile. Do you really want to continue and loose all the changes \\\nfrom the other instance?')\n response = MessageDialog('question', title, message).run()\n if response == gtk.RESPONSE_YES:\n self.take_over_lock()\n return\n elif response == gtk.RESPONSE_NO:\n sys.exit(1)\n\n def lock(self):\n \"\"\"Locks the datafile to prevent editing with a second instance.\"\"\"\n lockfile = open(self.lockfilename, 'w')\n lockfile.write(self.pid)\n lockfile.close()\n\n def unlock(self):\n \"\"\"Unlocks the datafile if the instance owns the lock.\"\"\"\n if self.own_lock():\n os.remove(self.lockfilename)\n\n def is_locked(self):\n \"\"\"Checks, whether the datafile is locked.\"\"\"\n return os.path.exists(self.lockfilename)\n\n def own_lock(self):\n \"\"\"Checks, whether the current instance owns the lock.\"\"\"\n if self.is_locked():\n lockfile = open(self.lockfilename, 'r')\n lockpid = lockfile.read()\n lockfile.close()\n return self.pid == lockpid\n\n def take_over_lock(self):\n \"\"\"Deletes the current lockfile and creates a new one.\"\"\"\n os.remove(self.lockfilename)\n self.lock()\n","sub_path":"pondus/core/filelock.py","file_name":"filelock.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"548001035","text":"# Copyright © Garima Kapila\n\nfrom scipy.optimize import curve_fit\nimport numpy as np\nimport pandas as pd\nfrom sklearn import preprocessing\nfrom sklearn.decomposition import PCA\nfrom sklearn.manifold import TSNE\nfrom DataCollector.DataParser import *\nfrom Visualizer import *\n\n\n\n# keep/delete certain columns\ndef filter_cols(features_file, include=[], exclude=[]):\n\tfeatures = pd.read_csv(features_file)\n\tcols = [\n\t\tcol for col in features.columns if\n\t\t\t(any(keyword in col for keyword in include) and\n\t\t\t all(keyword not in col for keyword in exclude))\n\t]\n\tresults = features[cols]\n\tresults_file = features_file.replace('Features', 'Reduced')\n\tresults.to_csv(results_file, index = False)\n\treturn results_file\n\n# standardize data then PCA\ndef dimensionality_reduction(file_name, scree_file_name='', graph=False):\n\tdata, labels = columns_from_data(file_name)\n\tstd_data = standardize_data(data)\n\tn_cols = len(data.columns)\n\tn, scree, log_scree = get_n_components(std_data, n_cols)\n\tscree_plots_name = file_name.replace('Features', 'Scree_Plots')\n\twrite_images_to_ppt([scree, log_scree], scree_plots_name, scree_file_name)\n\tpca = PCA(n_components = n).fit(std_data)\n\treduced = pca.transform(std_data)\n\tif graph:\n\t\tscatter_plots(file_name, reduced)\n\treduced_file = 'Reduced_' + file_name\n\tnp.savetxt(reduced_file, reduced, delimiter = ',')\n\treturn n, reduced_file, scree_file_name\n\n# scatter points using PCA and TSNE\ndef scatter_plots(data, labels):\n\tscatter_graph(data, labels)\n\n# scale features by standardization\ndef standardize_data(data):\n\tscaler = preprocessing.StandardScaler()\n\tstd_scale = scaler.fit(data)\n\tstd_data = std_scale.transform(data)\n\treturn std_data\n\n# get top principal components (# at kink in scree plot)\ndef get_n_components(data, n_cols):\n\tpca = PCA(n_components = n_cols).fit(data)\n\tdata = pca.transform(data)\n\tvariance = pca.explained_variance_\n\tlog_variance = np.log(variance)\n\tscree, log_scree = scree_plot(variance, log_variance)\n\tn = int((np.abs(log_variance)).argmin() * 1.5)\n\treturn n, scree, log_scree\n\n# visualize kink of explained variance plot\ndef scree_plot(variance, log_variance):\n\ttitle = 'Scree Plot'\n\tx_axis = 'Principal Component #'\n\ty_axis = 'Explained Variance'\n\tscree = line_graph(variance, title, x_axis, y_axis)\n\ttitle = 'Log Scree Plot'\n\ty_axis = 'Log Explained Variance'\n\tlog_scree = line_graph(log_variance, title, x_axis, y_axis)\n\treturn scree, log_scree\n\n# get number columns and labels\ndef columns_from_data(file_name):\n\tdata = pd.read_csv(file_name, sep = ',')\n\tdata = data.select_dtypes(['number'])\n\tlabels = data['Label']\n\tdata = data.drop(['Label'], axis = 1)\n\treturn data, labels\n\n# For scatter plots\n\ndef pca_2D(reduced_pca_data):\n\treturn reduced_pca_data[:, 0], reduced_pca_data[:, 1]\n\ndef tsne_2D(reduced_data):\n\treturn TSNE(n_components = 2).fit_transform(reduced_data)\n\t\n\ndef combine_features(file_path):\n\tfeatures = pd.read_csv(file_path, sep=',')\n\tfeatures = add_blosum_positives(features)\n\tfeatures = add_score_averages(features)\n\tfeatures = join_pair_columns(features)\n\tfeatures = move_col_to_end(features, 'Database')\n\tfeatures = move_col_to_end(features, 'Label')\n\tfile_name = file_path.split('/')[-1]\n\tfile_name_prefix = file_name.split('_')[0]\n\tfile_name = file_name.replace(file_name_prefix, 'Features')\n\tfeatures.fillna(value = 0)\n\tfeatures.to_csv(file_name, sep = ',', index = False)\n\treturn file_name\n\n\n# input pandas dataframe, dataframe split by labels\ndef split_by_label(dataframe, labels_col, labels=[0, 1]):\n\tlabel_name = labels_col.name\n\tdataframe[label_name] = labels_col\n\tsplits = [dataframe[dataframe[label_name] == label] for label in labels]\n\treturn [split.drop(columns=[label_name]) for split in splits]\n\n\n### Helper methods for add_features_to_interologs ###\n\n# Add blosum match + similar (non-match) to get positives column\ndef add_blosum_positives(features):\n\tfor col in features.columns.values:\n\t\tif '_Match' in col and '_Blosum' in col:\n\t\t\tcol_type = column_type(col)\n\t\t\tpr_type = pair_type(col)\n\t\t\tfor col2 in features.columns.values:\n\t\t\t\tif '_Similar' in col2 and pr_type == pair_type(col2) and \\\n\t\t\t\t\tcol_type == column_type(col2):\n\t\t\t\t\tfeatures[col_type + '_Sum_Blosum_Positive_Scores_Pair_' \\\n\t\t\t\t\t+ pr_type] = features[col] + features[col2]\n\treturn features\n\n# average # or score divided by length\ndef add_score_averages(features):\n\t\n\t# Put column names that have 'length' in a dictionary along with pair type\n\tlengths_dict = {}\n\tfor col in features.columns.values:\n\t\tif 'Length' in col:\n\t\t\tcol_type = column_type(col)\n\t\t\tpr_type = pair_type(col)\n\t\t\tlengths_dict[col_type + pr_type] = col\n\t\t\t# avoid infinite values\n\t\t\tfeatures[col] = features[col].replace(0, 1)\n\n\t# Get averages/percents using lengths\n\tfor col in features.columns.values:\n\t\tif 'Sum' in col or 'Count' in col or 'Difference' in col:\n\t\t\tlength_col = column_type(col) + pair_type(col)\n\t\t\tif length_col in lengths_dict.keys():\n\t\t\t\tlengths = features[lengths_dict[length_col]]\n\t\t\t\tfactor = 1\n\t\t\t\tif 'Count' in col:\n\t\t\t\t\tfactor = 100\n\t\t\t\tnew_col = col.replace('Sum', 'Average_Sum')\n\t\t\t\tnew_col = new_col.replace('Count', 'Percent')\n\t\t\t\tnew_col = new_col.replace('Difference', 'Average_Difference')\n\t\t\t\tfeatures[new_col] = features[col] * factor / lengths\n\t\t\t\tfeatures[new_col] = features[new_col].round(3)\n\t\n\t# Add % interface residues\n\tfor col in features.columns.values:\n\t\tif 'Interface_' in col and 'Length' in col:\n\t\t\tpr_type = pair_type(col)\n\t\t\tfasta_length = lengths_dict['Fasta' + pr_type]\n\t\t\tnew_col = col.replace('Length', 'Percent')\n\t\t\tfeatures[new_col] = 100 * features[col] / features[fasta_length]\n\t\t\tfeatures[new_col].round(3)\n\t\n\treturn features\n\n# Get joint columns for pair 1, pair 2 across features\ndef join_pair_columns(features):\n\tfor col1 in features.columns:\n\t\tif 'Pair_1' in col1:\n\t\t\tcolumn_name = col1.replace('Pair_1', 'Joint')\n\t\t\tdata1 = features[col1]\n\t\t\tcol2 = col1[:-1] + '2'\n\t\t\tdata2 = features[col2]\n\t\t\tjoint = data1 * data2\n\t\t\tfeatures[column_name] = joint\n\treturn features\n\n# first part of name is column type, types: Blast, Global, Interface, etc\ndef column_type(column):\n\treturn column.split('_')[0]\n\n# last part of name is pair type, ex. Pair_1 = 1\ndef pair_type(column):\n\treturn column.split('_')[-1]\n\ndef filter_interologs(features_file):\n\tdata = pd.read_csv(features_file)\n\tdata0 = data[data['Label'] == 0]\n\tdata1 = data[data['Label'] == 1]\n\tq0_0, q0_1, q1_0, q1_1 = 0, 0, 0, 0\n\tfor x in range(0, 10):\n\t\tx /= float(100)\n\t\tpercent_m1, percent_m2 = [\n\t\t\t'Interface_Matching_Percent_Pair_1',\n\t\t\t'Interface_Matching_Percent_Pair_2',\n\t\t]\n\t\tx0_0 = data0[percent_m1].quantile(x)\n\t\tx0_1 = data0[percent_m2].quantile(x)\n\t\tif x0_0 == 0 and x0_1 == 0:\n\t\t\tq0_0 = x0_0\n\t\t\tq0_1 = x0_1\n\t\t\tq1_0 = data1[percent_m1].quantile(x)\n\t\t\tq1_1 = data1[percent_m2].quantile(x)\n\t\telse:\n\t\t\tbreak\n","sub_path":"ML/DataParser.py","file_name":"DataParser.py","file_ext":"py","file_size_in_byte":6772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"188607069","text":"\"\"\"\n Message_parsers file contains all classes to parse a SDMX-ML Message\n\"\"\"\n\nfrom sdmxthon.model.definitions import DataStructureDefinition, \\\n DataFlowDefinition, ContentConstraint\nfrom sdmxthon.model.header import Header\nfrom sdmxthon.model.itemScheme import Codelist, AgencyScheme, ConceptScheme\nfrom sdmxthon.parsers.data_generic import DataSetType as GenericDataSet\nfrom sdmxthon.parsers.data_parser import DataParser\nfrom sdmxthon.parsers.data_structure import DataSetType as StructureDataSet\nfrom sdmxthon.parsers.footer_parser import FooterType\nfrom sdmxthon.parsers.gdscollector import GdsCollector\nfrom sdmxthon.utils.handlers import add_indent\nfrom sdmxthon.utils.mappings import messageAbbr, structureAbbr\n\n\nclass MessageType(DataParser):\n \"\"\"MessageType is an abstract dim_type which is used by all of the\n messages, to allow inheritance of common features. Every message\n consists of a mandatory header, followed by optional payload (which may\n occur multiple times), and finally an optional footer section for\n conveying error, warning, and informational messages. \"\"\"\n\n def __init__(self, header=None, Footer=None, gds_collector_=None,\n **kwargs_):\n super(MessageType, self).__init__(gds_collector_, **kwargs_)\n self._gds_collector_ = gds_collector_\n self._header = header\n self._footer = Footer\n\n @staticmethod\n def _factory(*args_, **kwargs_):\n \"\"\"Factory Method of MessageType\"\"\"\n return MessageType(**kwargs_)\n\n @property\n def header(self):\n \"\"\"Header of the Message\"\"\"\n return self._header\n\n @header.setter\n def header(self, value):\n self._header = value\n\n @property\n def footer(self):\n \"\"\"Footer of the Message\"\"\"\n return self._footer\n\n @footer.setter\n def footer(self, value):\n self._footer = value\n\n\n# end class MessageType\n\nclass GenericDataType(MessageType):\n \"\"\"GenericDataType defines the contents of a generic data message.\"\"\"\n __hash__ = DataParser.__hash__\n subclass = None\n superclass = MessageType\n\n def __init__(self, header=None, Footer=None, DataSet=None,\n gds_collector_=None, **kwargs_):\n super(GenericDataType, self).__init__(header, Footer, gds_collector_,\n **kwargs_)\n\n if DataSet is None:\n self._dataSet = []\n else:\n self._dataSet = DataSet\n\n if gds_collector_ is not None:\n self._gds_collector = gds_collector_\n else:\n self._gds_collector = GdsCollector()\n\n @staticmethod\n def _factory(*args_, **kwargs_):\n \"\"\"Factory Method of GenericDataType\"\"\"\n return GenericDataType(*args_, **kwargs_)\n\n @property\n def dataset(self):\n \"\"\"List of Datasets in a Generic Message\"\"\"\n return self._dataSet\n\n @dataset.setter\n def dataset(self, value):\n if value is None:\n self._dataSet = []\n elif isinstance(value, list):\n self._dataSet = value\n else:\n raise TypeError('Dataset must be a list')\n\n def _build_children(self, child_, node, nodeName_, fromsubclass_=False,\n gds_collector_=None):\n \"\"\"Builds the childs of the XML element\"\"\"\n if nodeName_ == 'Header':\n obj_ = Header._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._header = obj_\n obj_.original_tagname_ = 'Header'\n elif nodeName_ == 'DataSet':\n obj_ = GenericDataSet._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._dataSet.append(obj_)\n obj_.original_tag_name_ = 'DataSet'\n elif nodeName_ == 'Footer':\n obj_ = FooterType._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._footer = obj_\n obj_.original_tag_name_ = 'Footer'\n\n\n# end class GenericDataType\n\nclass CodelistsType(DataParser):\n \"\"\"CodelistsType is the parser for the Codelists XML element\"\"\"\n\n def __init__(self, codelist=None, gds_collector_=None, **kwargs_):\n super(CodelistsType, self).__init__(gds_collector_, **kwargs_)\n\n if codelist is None:\n self._codelists = {}\n else:\n self._codelists = codelist\n\n if gds_collector_ is not None:\n self._gds_collector = gds_collector_\n else:\n self._gds_collector = GdsCollector()\n\n @staticmethod\n def _factory(*args_, **kwargs_):\n \"\"\"Factory Method of CodelistsType\"\"\"\n return CodelistsType(*args_, **kwargs_)\n\n @property\n def codelists(self):\n \"\"\"Dict of Codelists\"\"\"\n return self._codelists\n\n @codelists.setter\n def codelists(self, value):\n self._codelists = value\n\n def _build_children(self, child_, node, nodeName_, fromsubclass_=False,\n gds_collector_=None):\n \"\"\"Builds the childs of the XML element\"\"\"\n if nodeName_ == 'Codelist':\n obj_ = Codelist._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._codelists[obj_.unique_id] = obj_\n\n\nclass ConceptsType(DataParser):\n \"\"\"ConceptsType is the parser for the Concepts XML element\"\"\"\n\n def __init__(self, concepts=None, gds_collector_=None, **kwargs_):\n super(ConceptsType, self).__init__(gds_collector_, **kwargs_)\n\n self._cl_references = []\n if concepts is None:\n self._concepts = {}\n else:\n self._concepts = concepts\n\n if gds_collector_ is not None:\n self._gds_collector = gds_collector_\n else:\n self._gds_collector = GdsCollector()\n\n @staticmethod\n def _factory(*args_, **kwargs_):\n \"\"\"Factory Method of ConceptsType\"\"\"\n return ConceptsType(*args_, **kwargs_)\n\n @property\n def concepts(self):\n \"\"\"Dict of Concepts\"\"\"\n return self._concepts\n\n @concepts.setter\n def concepts(self, value):\n self._concepts = value\n\n def _build_children(self, child_, node, nodeName_, fromsubclass_=False,\n gds_collector_=None):\n \"\"\"Builds the childs of the XML element\"\"\"\n if nodeName_ == 'ConceptScheme':\n obj_ = ConceptScheme._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self.concepts[obj_.unique_id] = obj_\n\n\nclass DataStructuresType(DataParser):\n \"\"\"DataStructuresType is the parser for the DataStructures XML element\"\"\"\n\n def __init__(self, dsds=None, gds_collector_=None, **kwargs_):\n super(DataStructuresType, self).__init__(gds_collector_, **kwargs_)\n\n self._cl_references = []\n self._dsds = dsds\n\n self._non_unique = None\n\n if gds_collector_ is not None:\n self._gds_collector = gds_collector_\n else:\n self._gds_collector = GdsCollector()\n\n @staticmethod\n def _factory(*args_, **kwargs_):\n \"\"\"Factory Method of DataStructuresType\"\"\"\n return DataStructuresType(*args_, **kwargs_)\n\n @property\n def dsds(self):\n \"\"\"Dict of DSDs\"\"\"\n return self._dsds\n\n @dsds.setter\n def dsds(self, value):\n self._dsds = value\n\n @property\n def non_unique(self):\n \"\"\"Dict of non-unique dsds\"\"\"\n return self._non_unique\n\n def add_non_unique(self, id_):\n \"\"\"Method to add a non-unique DSD to generate the error\"\"\"\n if self._non_unique is None:\n self._non_unique = []\n self._non_unique.append(id_)\n\n def _build_children(self, child_, node, nodeName_, fromsubclass_=False,\n gds_collector_=None):\n \"\"\"Builds the childs of the XML element\"\"\"\n if nodeName_ == 'DataStructure':\n obj_ = DataStructureDefinition._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n\n if self._dsds is None:\n self._dsds = {}\n\n if obj_.unique_id in self.dsds:\n self.add_non_unique(obj_.unique_id)\n else:\n self.dsds[obj_.unique_id] = obj_\n\n\nclass OrganisationSchemesType(DataParser):\n \"\"\"OrganisationSchemesType is the parser for the OrganisationScheme XML\n element \"\"\"\n\n def __init__(self, agency_scheme=None, gds_collector_=None, **kwargs_):\n super(OrganisationSchemesType, self).__init__(gds_collector_,\n **kwargs_)\n\n if agency_scheme is None:\n self._agency_schemes = []\n else:\n self._agency_schemes = agency_scheme\n\n if gds_collector_ is not None:\n self._gds_collector = gds_collector_\n else:\n self._gds_collector = GdsCollector()\n\n @staticmethod\n def _factory(*args_, **kwargs_):\n \"\"\"Factory Method of OrganisationSchemesType\"\"\"\n return OrganisationSchemesType(*args_, **kwargs_)\n\n @property\n def agencySchemes(self):\n \"\"\"Getter of the AgencyScheme\"\"\"\n return self._agency_schemes\n\n @agencySchemes.setter\n def agencySchemes(self, value):\n self._agency_schemes = value\n\n def _build_children(self, child_, node, nodeName_, fromsubclass_=False,\n gds_collector_=None):\n \"\"\"Builds the childs of the XML element\"\"\"\n if nodeName_ == 'AgencyScheme':\n obj_ = AgencyScheme._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._agency_schemes = obj_\n\n\nclass DataflowsType(DataParser):\n \"\"\"DataflowsType is the parser for the DataFlowDefinition XML element\"\"\"\n\n def __init__(self, dataflows=None, gds_collector_=None, **kwargs_):\n super(DataflowsType, self).__init__(gds_collector_, **kwargs_)\n\n if dataflows is None:\n self._dataflows = {}\n else:\n self._dataflows = dataflows\n\n if gds_collector_ is not None:\n self._gds_collector = gds_collector_\n else:\n self._gds_collector = GdsCollector()\n\n @staticmethod\n def _factory(*args_, **kwargs_):\n \"\"\"Factory Method of DataflowsType\"\"\"\n return DataflowsType(*args_, **kwargs_)\n\n @property\n def dataflows(self):\n \"\"\"Dict of Dataflows\"\"\"\n return self._dataflows\n\n @dataflows.setter\n def dataflows(self, value):\n self._dataflows = value\n\n def _build_children(self, child_, node, nodeName_, fromsubclass_=False,\n gds_collector_=None):\n \"\"\"Builds the childs of the XML element\"\"\"\n if nodeName_ == 'Dataflow':\n obj_ = DataFlowDefinition._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self.dataflows[obj_.unique_id] = obj_\n\n\nclass ConstraintsType(DataParser):\n \"\"\"ConstraintsType is the parser for the Constraint XML element\"\"\"\n\n def __init__(self, constraints=None, gds_collector_=None):\n super(ConstraintsType, self).__init__(gds_collector_)\n\n if constraints is None:\n self._constraints = {}\n else:\n self._constraints = constraints\n\n if gds_collector_ is not None:\n self._gds_collector = gds_collector_\n else:\n self._gds_collector = GdsCollector()\n\n @staticmethod\n def _factory(*args_, **kwargs_):\n \"\"\"Factory Method of ConstraintsType\"\"\"\n return ConstraintsType(*args_, **kwargs_)\n\n @property\n def constraints(self):\n \"\"\"Dict of Dataflows\"\"\"\n return self._constraints\n\n @constraints.setter\n def constraints(self, value):\n self._constraints = value\n\n def _build_children(self, child_, node, nodeName_, fromsubclass_=False,\n gds_collector_=None):\n \"\"\"Builds the childs of the XML element\"\"\"\n if nodeName_ == 'ContentConstraint':\n obj_ = ContentConstraint._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self.constraints[obj_.unique_id] = obj_\n\n\nclass Structures(DataParser):\n \"\"\"Structures class is the Metadata holder to access all elements in a\n Structures SDMX_ML file \"\"\"\n __hash__ = DataParser.__hash__\n\n def __init__(self, codelists=None, concepts=None, dsds=None,\n organisations=None, dataflows=None, constraints=None,\n gds_collector_=None):\n super(Structures, self).__init__(gds_collector_)\n\n self._dataflows = dataflows\n\n self._dsds = dsds\n\n self._codelists = codelists\n\n self._organisations = organisations\n\n self._concepts = concepts\n\n self._constraints = constraints\n\n self._errors = None\n\n if gds_collector_ is not None:\n self._gds_collector = gds_collector_\n else:\n self._gds_collector = GdsCollector()\n\n def __eq__(self, other):\n if isinstance(other, Structures):\n if self.codelists is not None:\n for e in self.codelists.values():\n e._checked = False\n\n if self.concepts is not None:\n for e in self.concepts.values():\n e._checked = False\n\n return (self._dataflows == other._dataflows and\n self._dsds == other._dsds and\n self._codelists == other._codelists and\n self._organisations == other._organisations and\n self._concepts == other._concepts and\n self._errors == other._errors)\n\n @staticmethod\n def _factory(*args_, **kwargs_):\n \"\"\"Factory Method of Structures\"\"\"\n return Structures(*args_, **kwargs_)\n\n @property\n def dataflows(self):\n \"\"\"Dict of dataflows\"\"\"\n return self._dataflows\n\n @dataflows.setter\n def dataflows(self, value):\n self._dataflows = value\n\n @property\n def organisations(self):\n \"\"\"Dict of OrganisationScheme\"\"\"\n return self._organisations\n\n @organisations.setter\n def organisations(self, value):\n self._organisations = value\n\n @property\n def dsds(self):\n \"\"\"Dict of DataStructureDefinition\"\"\"\n return self._dsds\n\n @dsds.setter\n def dsds(self, value):\n self._dsds = value\n\n @property\n def codelists(self):\n \"\"\"Dict of Codelists\"\"\"\n return self._codelists\n\n @codelists.setter\n def codelists(self, value):\n self._codelists = value\n\n @property\n def concepts(self):\n \"\"\"Dict of Concepts\"\"\"\n return self._concepts\n\n @concepts.setter\n def concepts(self, value):\n self._concepts = value\n\n @property\n def constraints(self):\n return self._constraints\n\n @constraints.setter\n def constraints(self, value):\n self._constraints = value\n\n @property\n def errors(self):\n \"\"\"List of Errors\"\"\"\n return self._errors\n\n def add_error(self, error):\n \"\"\"Method to add an error in the Structures\"\"\"\n if self._errors is None:\n self._errors = []\n self._errors.append(error)\n\n def _build_children(self, child_, node, nodeName_, fromsubclass_=False,\n gds_collector_=None):\n \"\"\"Builds the childs of the XML element\"\"\"\n if nodeName_ == 'OrganisationSchemes':\n obj_ = OrganisationSchemesType._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._organisations = obj_.agencySchemes\n elif nodeName_ == 'Codelists':\n obj_ = CodelistsType._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._codelists = obj_.codelists\n elif nodeName_ == 'Concepts':\n obj_ = ConceptsType._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._concepts = obj_.concepts\n elif nodeName_ == 'DataStructures':\n obj_ = DataStructuresType._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n if obj_.non_unique is not None:\n for e in obj_.non_unique:\n self.add_error({'Code': 'MS06', 'ErrorLevel': 'CRITICAL',\n 'ObjectID': f'{e}', 'ObjectType': 'DSD',\n 'Message': f'DSD {e} is not unique'})\n self._dsds = obj_.dsds\n\n elif nodeName_ == 'Dataflows':\n obj_ = DataflowsType._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._dataflows = obj_.dataflows\n\n elif nodeName_ == 'Constraints':\n obj_ = ConstraintsType._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._constraints = obj_.constraints\n\n def to_XML(self, prettyprint=True):\n\n if prettyprint:\n indent = '\\t'\n newline = '\\n'\n else:\n indent = newline = ''\n\n outfile = f'{indent}<{messageAbbr}:Structures>'\n if self.organisations is not None:\n indent_child = newline + add_indent(indent)\n outfile += f'{indent_child}<{structureAbbr}:OrganisationSchemes>'\n outfile += self.organisations. \\\n _parse_XML(indent_child, f'{structureAbbr}:AgencyScheme')\n outfile += f'{indent_child}'\n\n if self.dataflows is not None:\n indent_child = newline + add_indent(indent)\n outfile += f'{indent_child}<{structureAbbr}:Dataflows>'\n for e in self.dataflows.values():\n outfile += e._parse_XML(indent_child,\n f'{structureAbbr}:Dataflow')\n outfile += f'{indent_child}'\n\n if self.codelists is not None:\n indent_child = newline + add_indent(indent)\n outfile += f'{indent_child}<{structureAbbr}:Codelists>'\n for e in self.codelists.values():\n outfile += e._parse_XML(indent_child,\n f'{structureAbbr}:Codelist')\n outfile += f'{indent_child}'\n\n if self.concepts is not None:\n indent_child = newline + add_indent(indent)\n outfile += f'{indent_child}<{structureAbbr}:Concepts>'\n for e in self.concepts.values():\n outfile += e._parse_XML(indent_child,\n f'{structureAbbr}:ConceptScheme')\n outfile += f'{indent_child}'\n\n if self.dsds is not None:\n indent_child = newline + add_indent(indent)\n outfile += f'{indent_child}<{structureAbbr}:DataStructures>'\n for e in self.dsds.values():\n outfile += e._parse_XML(indent_child,\n f'{structureAbbr}:DataStructure')\n outfile += f'{indent_child}'\n\n if self.constraints is not None:\n indent_child = newline + add_indent(indent)\n outfile += f'{indent_child}<{structureAbbr}:Constraints>'\n for e in self.constraints.values():\n outfile += e._parse_XML(indent_child,\n f'{structureAbbr}:ContentConstraint')\n outfile += f'{indent_child}'\n\n outfile += f'{newline}{indent}{newline}'\n\n return outfile\n\n\nclass MetadataType(MessageType):\n \"\"\"MetadataType is a type of Message that starts with the tag Structure\n and contains the Metadata information \"\"\"\n __hash__ = DataParser.__hash__\n superclass = MessageType\n\n def __init__(self, header=None, footer=None, structures=None,\n gds_collector_=None, **kwargs_):\n super(MetadataType, self).__init__(header, footer, gds_collector_,\n **kwargs_)\n\n self._structures = structures\n\n if gds_collector_ is not None:\n self._gds_collector = gds_collector_\n else:\n self._gds_collector = GdsCollector()\n\n @staticmethod\n def _factory(*args_, **kwargs_):\n \"\"\"Factory Method of MetadataType\"\"\"\n return MetadataType(*args_, **kwargs_)\n\n @property\n def structures(self):\n \"\"\"Reference to the Structure in the Message\"\"\"\n return self._structures\n\n @structures.setter\n def structures(self, value):\n self._structures = value\n\n def _build_children(self, child_, node, nodeName_, fromsubclass_=False,\n gds_collector_=None):\n \"\"\"Builds the childs of the XML element\"\"\"\n if nodeName_ == 'Header':\n obj_ = Header._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._header = obj_\n elif nodeName_ == 'Structures':\n obj_ = Structures._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._structures = obj_\n elif nodeName_ == 'Footer':\n obj_ = FooterType._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._footer = obj_\n\n\nclass StructureSpecificDataType(MessageType):\n \"\"\"StructureSpecificDataType defines the structure of the structure\n specific data message. Note that the data set payload dim_type is\n abstract, and therefore it will have to be assigned a dim_type in an\n instance. This dim_type must be derived from the base dim_type\n referenced. This base dim_type defines a general structure which can be\n followed to allow for generic processing of the data even if the exact\n details of the data structure specific format are not known. \"\"\"\n __hash__ = MessageType.__hash__\n subclass = None\n superclass = MessageType\n\n def __init__(self, header=None, Footer=None, DataSet=None,\n gds_collector_=None, **kwargs_):\n super(StructureSpecificDataType, self).__init__(header, Footer,\n gds_collector_,\n **kwargs_)\n\n if DataSet is None:\n self._dataSet = []\n else:\n self._dataSet = DataSet\n self._name = 'StructureSpecificDataType'\n\n if gds_collector_ is not None:\n self.gds_collector_ = gds_collector_\n else:\n self.gds_collector_ = GdsCollector()\n\n @staticmethod\n def _factory(*args_, **kwargs_):\n \"\"\"Factory Method of StructureSpecificDataType\"\"\"\n return StructureSpecificDataType(*args_, **kwargs_)\n\n @property\n def dataset(self):\n \"\"\"List of Datasets in a Structure Specific Message\"\"\"\n return self._dataSet\n\n @dataset.setter\n def dataset(self, value):\n if value is None:\n self._dataSet = []\n elif isinstance(value, list):\n self._dataSet = value\n else:\n raise TypeError('Dataset must be a list')\n\n def _build_children(self, child_, node, nodeName_, fromsubclass_=False,\n gds_collector_=None):\n \"\"\"Builds the childs of the XML element\"\"\"\n if nodeName_ == 'Header':\n obj_ = Header._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._header = obj_\n obj_.original_tagname_ = 'Header'\n elif nodeName_ == 'DataSet':\n obj_ = StructureDataSet._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._dataSet.append(obj_)\n obj_.original_tag_name_ = 'DataSet'\n elif nodeName_ == 'Footer':\n obj_ = FooterType._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._footer = obj_\n obj_.original_tag_name_ = 'Footer'\n\n\n# end class StructureSpecificDataType\n","sub_path":"sdmxthon/parsers/message_parsers.py","file_name":"message_parsers.py","file_ext":"py","file_size_in_byte":23911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"18174995","text":"import FWCore.ParameterSet.Config as cms\n\nfrom FWCore.ParameterSet.VarParsing import VarParsing\n\n###############################\n####### Parameters ############\n###############################\n\noptions = VarParsing ('python')\n\noptions.register('reportEvery', 10,\n VarParsing.multiplicity.singleton,\n VarParsing.varType.int,\n \"Report every N events (default is N=10)\"\n)\noptions.register('wantSummary', False,\n VarParsing.multiplicity.singleton,\n VarParsing.varType.bool,\n \"Print out trigger and timing summary\"\n)\n\n## 'maxEvents' is already registered by the Framework, changing default value\noptions.setDefault('maxEvents', 100)\n\noptions.parseArguments()\n\nprocess = cms.Process(\"USER\")\n\nprocess.load(\"Configuration.StandardSequences.MagneticField_AutoFromDBCurrent_cff\")\nprocess.load(\"Configuration.Geometry.GeometryRecoDB_cff\")\nprocess.load(\"Configuration.StandardSequences.FrontierConditions_GlobalTag_cff\")\nfrom Configuration.AlCa.GlobalTag import GlobalTag\nprocess.GlobalTag = GlobalTag(process.GlobalTag, 'auto:run2_mc')\n\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\nprocess.MessageLogger.cerr.FwkReport.reportEvery = options.reportEvery\n\n## Events to process\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(options.maxEvents) )\n\n## Input files\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring(\n # /TTJets_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v2/MINIAODSIM\n '/store/mc/RunIISpring15DR74/TTJets_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/MINIAODSIM/Asympt25ns_MCRUN2_74_V9-v2/00000/06B5178E-F008-E511-A2CF-00261894390B.root'\n )\n)\n\n## Options and Output Report\nprocess.options = cms.untracked.PSet(\n wantSummary = cms.untracked.bool(options.wantSummary),\n allowUnscheduled = cms.untracked.bool(True)\n)\n\n#################################################\n## Make jets\n#################################################\n\n## Filter out neutrinos from packed GenParticles\nprocess.packedGenParticlesForJetsNoNu = cms.EDFilter(\"CandPtrSelector\", src = cms.InputTag(\"packedGenParticles\"), cut = cms.string(\"abs(pdgId) != 12 && abs(pdgId) != 14 && abs(pdgId) != 16\"))\n## Fat GenJets\nfrom RecoJets.JetProducers.ak4GenJets_cfi import ak4GenJets\nprocess.ak8GenJetsNoNu = ak4GenJets.clone(\n rParam = cms.double(0.8),\n src = cms.InputTag(\"packedGenParticlesForJetsNoNu\")\n)\n## Pruned fat GenJets (two jet collections are produced, fat jets and subjets)\nfrom RecoJets.JetProducers.SubJetParameters_cfi import SubJetParameters\nfrom RecoJets.JetProducers.ak4GenJets_cfi import ak4GenJets\nprocess.ak8GenJetsNoNuPruned = ak4GenJets.clone(\n SubJetParameters,\n rParam = cms.double(0.8),\n src = cms.InputTag(\"packedGenParticlesForJetsNoNu\"),\n usePruning = cms.bool(True),\n writeCompound = cms.bool(True),\n jetCollInstanceName=cms.string(\"SubJets\")\n)\n\n## Select charged hadron subtracted packed PF candidates\nprocess.pfCHS = cms.EDFilter(\"CandPtrSelector\", src = cms.InputTag(\"packedPFCandidates\"), cut = cms.string(\"fromPV\"))\nfrom RecoJets.JetProducers.ak4PFJets_cfi import ak4PFJets\n## Fat PFJets\nfrom RecoJets.JetProducers.ak4PFJets_cfi import ak4PFJets\nprocess.ak8PFJetsCHS = ak4PFJets.clone(\n rParam = cms.double(0.8),\n src = cms.InputTag(\"pfCHS\"),\n doAreaFastjet = cms.bool(True),\n jetPtMin = cms.double(50.)\n)\n## Pruned fat PFJets (two jet collections are produced, fat jets and subjets)\nfrom RecoJets.JetProducers.ak5PFJetsPruned_cfi import ak5PFJetsPruned\nprocess.ak8PFJetsCHSPruned = ak5PFJetsPruned.clone(\n rParam = cms.double(0.8),\n src = cms.InputTag(\"pfCHS\"),\n doAreaFastjet = cms.bool(True),\n writeCompound = cms.bool(True),\n jetCollInstanceName=cms.string(\"SubJets\"),\n jetPtMin = cms.double(50.)\n)\n\n#################################################\n## Make PAT jets\n#################################################\n\n## b-tag discriminators\nbTagDiscriminators = [\n 'pfTrackCountingHighEffBJetTags',\n 'pfTrackCountingHighPurBJetTags',\n 'pfJetProbabilityBJetTags',\n 'pfJetBProbabilityBJetTags',\n 'pfSimpleSecondaryVertexHighEffBJetTags',\n 'pfSimpleSecondaryVertexHighPurBJetTags',\n 'pfCombinedSecondaryVertexV2BJetTags',\n 'pfCombinedInclusiveSecondaryVertexV2BJetTags',\n 'pfCombinedMVABJetTags',\n 'pfDeepCSVJetTags:probb',\n 'pfDeepCSVJetTags:probbb'\n]\n\nfrom PhysicsTools.PatAlgos.tools.jetTools import *\n## PATify fat jets\naddJetCollection(\n process,\n labelName = 'AK8PFCHS',\n jetSource = cms.InputTag('ak8PFJetsCHS'),\n algo = 'ak', # needed for jet flavor clustering\n rParam = 0.8, # needed for jet flavor clustering\n pvSource = cms.InputTag('offlineSlimmedPrimaryVertices'),\n pfCandidates = cms.InputTag('packedPFCandidates'),\n svSource = cms.InputTag('slimmedSecondaryVertices'),\n muSource = cms.InputTag('slimmedMuons'),\n elSource = cms.InputTag('slimmedElectrons'),\n btagDiscriminators = bTagDiscriminators,\n jetCorrections = ('AK8PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute'], 'None'),\n genJetCollection = cms.InputTag('ak8GenJetsNoNu'),\n genParticles = cms.InputTag('prunedGenParticles')\n)\n## PATify pruned fat jets\naddJetCollection(\n process,\n labelName = 'AK8PFCHSPruned',\n jetSource = cms.InputTag('ak8PFJetsCHSPruned'),\n btagDiscriminators = ['None'],\n jetCorrections = ('AK8PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute'], 'None'),\n genJetCollection = cms.InputTag('ak8GenJetsNoNu'),\n genParticles = cms.InputTag('prunedGenParticles'),\n getJetMCFlavour = False # jet flavor disabled\n)\n## PATify pruned subjets\naddJetCollection(\n process,\n labelName = 'AK8PFCHSPrunedSubjets',\n jetSource = cms.InputTag('ak8PFJetsCHSPruned','SubJets'),\n algo = 'ak', # needed for subjet flavor clustering\n rParam = 0.8, # needed for subjet flavor clustering\n pvSource = cms.InputTag('offlineSlimmedPrimaryVertices'),\n pfCandidates = cms.InputTag('packedPFCandidates'),\n svSource = cms.InputTag('slimmedSecondaryVertices'),\n muSource = cms.InputTag('slimmedMuons'),\n elSource = cms.InputTag('slimmedElectrons'),\n btagDiscriminators = bTagDiscriminators,\n jetCorrections = ('AK4PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute'], 'None'),\n genJetCollection = cms.InputTag('ak8GenJetsNoNuPruned','SubJets'),\n genParticles = cms.InputTag('prunedGenParticles'),\n explicitJTA = True, # needed for subjet b tagging\n svClustering = True, # needed for subjet b tagging\n fatJets=cms.InputTag('ak8PFJetsCHS'), # needed for subjet flavor clustering\n groomedFatJets=cms.InputTag('ak8PFJetsCHSPruned') # needed for subjet flavor clustering\n)\n\n## Establish references between PATified fat jets and subjets using the BoostedJetMerger\nprocess.selectedPatJetsAK8PFCHSPrunedPacked = cms.EDProducer(\"BoostedJetMerger\",\n jetSrc=cms.InputTag(\"selectedPatJetsAK8PFCHSPruned\"),\n subjetSrc=cms.InputTag(\"selectedPatJetsAK8PFCHSPrunedSubjets\")\n)\n\n## Pack fat jets with subjets\nprocess.packedPatJetsAK8PFCHS = cms.EDProducer(\"JetSubstructurePacker\",\n jetSrc = cms.InputTag('selectedPatJetsAK8PFCHS'),\n distMax = cms.double(0.8),\n algoTags = cms.VInputTag( cms.InputTag('selectedPatJetsAK8PFCHSPrunedPacked') ),\n algoLabels = cms.vstring( 'Pruned' ),\n fixDaughters = cms.bool(False)\n)\n\nfrom PhysicsTools.PatAlgos.tools.pfTools import *\n## Adapt primary vertex collection\nadaptPVs(process, pvCollection=cms.InputTag('offlineSlimmedPrimaryVertices'))\n\n#################################################\n\n## Let it run\nprocess.p = cms.Path(process.selectedPatJetsAK8PFCHS + process.selectedPatJetsAK8PFCHSPrunedPacked)\n","sub_path":"test/BTagSubJet_cfg.py","file_name":"BTagSubJet_cfg.py","file_ext":"py","file_size_in_byte":7685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"600894225","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nimport os\nimport re\n\npipelinename = \"pipeline\"\npipelineurl = \"pipelineurl\"\n\nresults = {}\nversion_files = [x for x in os.listdir('.') if x.endswith('.version.txt')]\nfor version_file in version_files:\n\n software = version_file.replace('.version.txt','')\n\n with open(version_file) as fin:\n version = fin.read().strip()\n \n if software == 'pipelinename':\n pipelinename = version\n elif software == 'pipelineurl':\n pipelineurl = version\n else:\n results[software] = version\n\nresults[pipelinename] = results.pop(\"pipeline\")\n\n# Dump to YAML\nprint ('''\nid: 'software_versions'\nsection_name: '%s Software Versions'\nsection_href: '%s'\nplot_type: 'html'\ndescription: 'are collected at run time from the software output.'\ndata: |\n

\n''' % (pipelinename, pipelineurl))\nfor k,v in sorted(results.items()):\n print(\"
{}
{}
\".format(k,v))\nprint (\"
\")\n\n# Write out regexes as csv file:\nwith open('software_versions.csv', 'w') as f:\n for k,v in sorted(results.items()):\n f.write(\"{}\\t{}\\n\".format(k,v))\n","sub_path":"bin/scrape_software_versions.py","file_name":"scrape_software_versions.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"380480147","text":"from django.db import models\nfrom django.conf import settings\nfrom accounts.models import CustomUser\n# Create your models here.\n\n# jenis surat: keterangan kuliah, cuti kuliah\nJENIS_SURAT_CHOISES = (\n ('KK', 'Keterangan Kuliah'),\n ('CK', 'Cuti Kuliah')\n)\n\n\nclass Agenda(models.Model):\n no_surat = models.AutoField(primary_key=True, )\n tgl_surat = models.DateField(auto_now=True)\n jenis_surat = models.CharField(choices=JENIS_SURAT_CHOISES, max_length=2)\n user = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n to_field='nim',\n related_name='surats',\n on_delete=models.CASCADE\n )\n","sub_path":"cuti/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"375748171","text":"# Copyright 2015 Mirantis, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport time\n\nfrom proboscis import test\nfrom proboscis.asserts import assert_equal\n\nfrom fuelweb_test import settings\nfrom fuelweb_test.helpers.decorators import log_snapshot_after_test\nfrom fuelweb_test.tests.base_test_case import TestBasic\n\n\n@test(groups=['failover_group_mongo'])\nclass FailoverGroupMongo(TestBasic):\n \"\"\" FailoverGroupMongo \"\"\" # TODO documentation\n\n @test(depends_on_groups=[\"prepare_slaves_9\"],\n groups=['deploy_mongo_cluster'])\n @log_snapshot_after_test\n def deploy_mongo_cluster(self):\n \"\"\"Deploy cluster with MongoDB nodes\n\n Scenario:\n 1. Create environment with enabled Ceilometer and Neutron VLAN\n 2. Add 3 controller, 3 mongodb, 1 compute and 1 cinder nodes\n 3. Verify networks\n 4. Deploy environment\n 5. Verify networks\n 6. Run OSTF tests\n\n Duration 200m\n Snapshot deploy_mongo_cluster\n \"\"\"\n\n self.env.revert_snapshot('ready_with_9_slaves')\n\n self.show_step(1, initialize=True)\n data = {\n 'ceilometer': True,\n 'tenant': 'mongo',\n 'user': 'mongo',\n 'password': 'mongo',\n \"net_provider\": 'neutron',\n \"net_segment_type\": settings.NEUTRON_SEGMENT['vlan'],\n }\n cluster_id = self.fuel_web.create_cluster(\n name=self.__class__.__name__,\n settings=data\n )\n\n self.show_step(2)\n self.fuel_web.update_nodes(\n cluster_id,\n {\n 'slave-01': ['controller'],\n 'slave-02': ['controller'],\n 'slave-03': ['controller'],\n 'slave-04': ['mongo'],\n 'slave-05': ['mongo'],\n 'slave-06': ['mongo'],\n 'slave-07': ['compute'],\n 'slave-08': ['cinder'],\n }\n )\n\n self.show_step(3)\n self.fuel_web.verify_network(cluster_id)\n\n self.show_step(4)\n self.fuel_web.deploy_cluster_wait(cluster_id)\n\n self.show_step(5)\n self.fuel_web.verify_network(cluster_id)\n\n self.show_step(6)\n self.fuel_web.run_ostf(cluster_id,\n test_sets=['smoke', 'sanity',\n 'ha', 'tests_platform'],\n timeout=50 * 60)\n self.env.make_snapshot('deploy_mongo_cluster', is_make=True)\n\n @test(depends_on_groups=[\"deploy_mongo_cluster\"],\n groups=['kill_mongo_processes'])\n @log_snapshot_after_test\n def kill_mongo_processes(self):\n \"\"\"Kill mongo processes\n\n Scenario:\n 1. Pre-condition - do steps from 'deploy_mongo_cluster' test\n 2. Kill mongo processes on 1st node\n 3. Wait 1 minute\n 4. Check new mongo processes exist on 1st node\n 5. Kill mongo processes on 2nd node\n 6. Wait 1 minute\n 7. Check new mongo processes exist on 2nd node\n 8. Kill mongo processes on 3rd node\n 9. Wait 1 minute\n 10. Check new mongo processes exist on 3rd node\n 11. Run OSTF tests\n\n Duration 60m\n Snapshot kill_mongo_processes\n \"\"\"\n\n self.show_step(1, initialize=True)\n self.env.revert_snapshot('deploy_mongo_cluster')\n\n cluster_id = self.fuel_web.get_last_created_cluster()\n mongodb = self.fuel_web.get_nailgun_cluster_nodes_by_roles(cluster_id,\n ['mongo'])\n assert_equal(len(mongodb), 3,\n \"Environment doesn't have 3 MongoDB nodes, \"\n \"found {} nodes!\".format(len(mongodb)))\n step = 2\n for node in mongodb:\n old_pids = self.ssh_manager.execute(\n ip=node['ip'], cmd='pgrep -f mongo')['stdout']\n self.show_step(step)\n self.ssh_manager.execute_on_remote(\n ip=node['ip'], cmd='pkill -9 -f mongo')\n\n self.show_step(step + 1)\n time.sleep(60)\n\n self.show_step(step + 2)\n new_pids = self.ssh_manager.execute(\n ip=node['ip'], cmd='pgrep -f mongo')['stdout']\n bad_pids = set(old_pids) & set(new_pids)\n assert_equal(len(bad_pids), 0,\n 'MongoDB processes with PIDs {} '\n 'were not killed!'.format(bad_pids))\n step += 3\n\n self.show_step(11)\n self.fuel_web.run_ostf(cluster_id,\n test_sets=['smoke', 'sanity',\n 'ha', 'tests_platform'],\n timeout=50 * 60)\n\n self.env.make_snapshot('kill_mongo_processes')\n\n @test(depends_on_groups=['deploy_mongo_cluster'],\n groups=['close_connections_for_mongo'])\n @log_snapshot_after_test\n def close_connections_for_mongo(self):\n \"\"\"Close connection for Mongo node\n\n Scenario:\n 1. Pre-condition - do steps from 'deploy_mongo_cluster' test\n 2. Close management network for 1 Mongo node\n 3. Run OSTF tests\n\n Duration 60m\n Snapshot close_connections_for_mongo\n \"\"\"\n\n self.show_step(1, initialize=True)\n self.env.revert_snapshot('deploy_mongo_cluster')\n\n cluster_id = self.fuel_web.get_last_created_cluster()\n mongodb = self.fuel_web.get_nailgun_cluster_nodes_by_roles(cluster_id,\n ['mongo'])\n assert_equal(len(mongodb), 3,\n \"Environment doesn't have 3 MongoDB nodes, \"\n \"found {} nodes!\".format(len(mongodb)))\n\n self.show_step(2)\n self.ssh_manager.execute_on_remote(\n ip=mongodb[0]['ip'],\n cmd='iptables -I INPUT -i br-mgmt -j DROP && '\n 'iptables -I OUTPUT -o br-mgmt -j DROP')\n\n self.show_step(3)\n self.fuel_web.run_ostf(cluster_id,\n test_sets=['smoke', 'sanity',\n 'ha', 'tests_platform'],\n timeout=50 * 60)\n\n self.env.make_snapshot('close_connections_for_mongo')\n\n @test(depends_on_groups=['deploy_mongo_cluster'],\n groups=['shut_down_mongo_node'])\n @log_snapshot_after_test\n def shut_down_mongo_node(self):\n \"\"\"Shut down Mongo node for Neutron\n\n Scenario:\n 1. Pre-condition - do steps from 'deploy_mongo_cluster' test\n 2. Shut down 1 Mongo node\n 3. Verify networks\n 4. Run OSTF tests\n 5. Turn on Mongo node\n 6. Verify networks\n 7. Run OSTF tests\n\n Duration: 60 min\n Snapshot: shut_down_mongo_node\n \"\"\"\n\n self.show_step(1, initialize=True)\n self.env.revert_snapshot('deploy_mongo_cluster')\n cluster_id = self.fuel_web.get_last_created_cluster()\n mongodb = self.fuel_web.get_nailgun_cluster_nodes_by_roles(cluster_id,\n ['mongo'])\n assert_equal(len(mongodb), 3,\n \"Environment doesn't have 3 MongoDB nodes, \"\n \"found {} nodes!\".format(len(mongodb)))\n\n target_node = self.fuel_web.get_devops_node_by_nailgun_node(mongodb[0])\n\n self.show_step(2)\n self.fuel_web.warm_shutdown_nodes([target_node])\n\n self.show_step(3)\n self.fuel_web.verify_network(cluster_id)\n\n self.show_step(4)\n self.fuel_web.run_ostf(cluster_id=cluster_id, should_fail=1)\n\n self.show_step(5)\n self.fuel_web.warm_start_nodes([target_node])\n\n self.show_step(6)\n self.fuel_web.verify_network(cluster_id)\n\n self.show_step(7)\n self.fuel_web.run_ostf(cluster_id,\n should_fail=1,\n test_sets=['smoke', 'sanity',\n 'ha', 'tests_platform'],\n timeout=50 * 60)\n\n self.env.make_snapshot('shut_down_mongo_node')\n","sub_path":"fuelweb_test/tests/tests_strength/test_failover_mongo.py","file_name":"test_failover_mongo.py","file_ext":"py","file_size_in_byte":8770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"651261967","text":"# -*- coding: utf-8 -\r\nfrom aceproxy import Playlist, Channel\r\nimport requests, json\r\nimport logging, re\r\n\r\nreplacements = [ (u'\\s+Резерв\\s+\\d+',u'') ]\r\n\r\nclass TorrentTelikPlaylist(Playlist):\r\n def load(self):\r\n self.logger = logging.getLogger('torrent-telik')\r\n headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1' }\r\n data = requests.get( 'http://torrent-telik.com/channels/torrent-tv.json', headers=headers ).json()\r\n self.clear()\r\n for ch in data['channels']:\r\n for rep in replacements:\r\n ch['name'] = re.sub( rep[0], rep[1], ch['name'], re.U+re.I )\r\n\r\n channel = Channel( \r\n id = self.uuid( ch['name'].encode('utf-8') ),\r\n name = ch['name'], \r\n url = ch['url'].replace(\"acestream://\",\"\"),\r\n tags = [ch['cat'].lower()],\r\n hd = ' HD' in ch['name'],\r\n logo = None\r\n )\r\n self.add(channel)\r\n self.logger.info('Loaded %d channels', len(self.items) )\r\n pass\r\n","sub_path":"playlists/torrenttelik.py","file_name":"torrenttelik.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"51702326","text":"from __future__ import division\nimport os\nimport io\nimport sys\nimport datetime\nimport numpy as np\nimport numpy.random as nr\nimport tensorflow as tf\n\nsentiment = dict()\nsentiment[\"postive\"] = np.array([1, 0]) # Is mispelled in the data file.\nsentiment[\"negative\"] = np.array([0, 1])\n\ndef read_word_vectors(filename):\n if os.path.isfile(filename):\n word_to_index = dict()\n index_to_word = list()\n word_vectors = list()\n counter = 0\n with open(filename,'r') as infile:\n for line in infile:\n parts = [x.strip() for x in line.split(\",\", 1)]\n word_to_index[parts[0]] = counter\n index_to_word.append(parts[0])\n word_vectors.append(np.genfromtxt(io.StringIO(unicode(parts[1], \"utf-8\")), delimiter=\",\"))\n counter += 1\n return word_to_index, index_to_word, word_vectors\n else:\n raise Exception(\"Word vector file does not exist\")\n\ndef read_data(filename):\n if os.path.isfile(filename):\n labels = []\n data = []\n maxsenlen = 0\n minsenlen = sys.maxsize\n with open(filename, 'r') as infile:\n for line in infile:\n parts = [x.strip() for x in line.split(\",\", 1)]\n labels.append(sentiment[parts[0]])\n data.append(parts[1])\n maxsenlen = np.max([maxsenlen, len(parts[1].split())])\n minsenlen = np.min([minsenlen, len(parts[1].split())])\n return data, labels, maxsenlen, minsenlen\n else:\n pass\n\ndef get_sentence_in_word_indices(sentence, word_to_index, max_sentence_length = 100):\n sentence_in_word_indices = np.zeros(max_sentence_length, dtype=np.int32)\n words_in_sentence = sentence.split()\n for i, word in enumerate(words_in_sentence):\n # Left pad with zero vectors\n sentence_in_word_indices[i + (max_sentence_length - len(words_in_sentence))] = word_to_index[word]\n return sentence_in_word_indices\n\ndef main(wordvecfile = \"sentiment-data/word-vectors-refine.txt\",\n trainfile = \"sentiment-data/train.csv\",\n testfile = \"sentiment-data/test.csv\"):\n word_to_index, index_to_word, word_vectors = read_word_vectors(wordvecfile)\n word_vectors = np.array(word_vectors, dtype=np.float32)\n \n train_data, train_labels, maxsenlen, minsenlen = read_data(trainfile)\n train_labels = np.array(train_labels)\n no_train_sentences = len(train_data)\n train_data_ints = np.zeros((no_train_sentences, maxsenlen), dtype=np.int32)\n print(\"Maximum sentence length in training data: \", maxsenlen)\n print(\"Minimum sentence length in training data: \", minsenlen)\n print(\"Total no. of sentences in training data : \", no_train_sentences)\n\n # convert each sentence into integer sequence\n for i, sentence in enumerate(train_data):\n train_data_ints[i, :] = get_sentence_in_word_indices(train_data[i], word_to_index, maxsenlen)\n \n test_data, test_labels, maxsenlen_test, minsenlen_test = read_data(testfile)\n test_labels = np.array(test_labels)\n no_test_sentences = len(test_data)\n test_data_ints = np.zeros((no_test_sentences, maxsenlen), dtype=np.int32)\n\n assert(maxsenlen_test <= maxsenlen)\n\n print(\"Maximum sentence length in testing data: \", maxsenlen_test)\n print(\"Minimum sentence length in testing data: \", minsenlen_test)\n print(\"Total no. of sentences in testing data : \", no_test_sentences)\n \n # convert each test sentence into integer sequence\n for i, sentence in enumerate(test_data):\n test_data_ints[i, :] = get_sentence_in_word_indices(test_data[i], word_to_index, maxsenlen)\n \n # RNN Parameters\n batch_size = 100\n n_tr_batches = np.int(np.ceil(no_train_sentences/batch_size))\n\n # Split the training data into different batches\n train_data_indices = np.arange(no_train_sentences)\n nr.shuffle(train_data_indices)\n train_data_indices = np.array_split(train_data_indices, n_tr_batches)\n batched_train_data = [train_data_ints[indices] for indices in train_data_indices]\n batched_train_labels = [train_labels[indices] for indices in train_data_indices] \n \n n_lstm_cell = 64\n n_classes = 2\n maxiter = 10\n wordvecdim = 50\n\n # reset the default graph\n tf.reset_default_graph()\n\n # Create placeholder for labels\n t_labels = tf.placeholder(tf.float32, [None, n_classes]) # labels\n t_data = tf.placeholder(tf.int32, [None, maxsenlen]) # training or test data\n\n \n # Create variables to hold the 3D tensor data of examples, words in sentences, word vectors\n indata = tf.nn.embedding_lookup(word_vectors, t_data)\n \n # Setup LSTM\n lstm_cell = tf.nn.rnn_cell.LSTMCell(n_lstm_cell)\n outputs, state = tf.nn.dynamic_rnn(lstm_cell, indata, dtype=tf.float32)\n\n # weights for last softmax\n W = tf.Variable(tf.random_uniform([n_lstm_cell, n_classes]))\n b = tf.Variable(tf.constant(0.1, shape=[n_classes]))\n\n H = tf.transpose(outputs, [1, 0, 2])\n h_final = tf.gather(H, int(H.get_shape()[0]) - 1)\n prediction = tf.matmul(h_final, W) + b\n\n correct_prediction = tf.equal(tf.argmax(prediction,1), tf.argmax(t_labels,1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=t_labels))\n optimizer = tf.train.AdamOptimizer().minimize(loss)\n\n sess = tf.Session()\n saver = tf.train.Saver()\n\n sess.run(tf.global_variables_initializer())\n\n for epoch in xrange(maxiter):\n for i in xrange(n_tr_batches):\n sess.run(optimizer, {t_data: batched_train_data[i],\n t_labels: batched_train_labels[i]})\n \n if ((epoch + 1) % 2 == 0):\n save_path = saver.save(sess, \"models/pretrained_lstm.ckpt\", global_step=epoch)\n print(\"Saved checkpoint to %s\" % save_path)\n \n print(\"Accuracy: \", sess.run(accuracy, feed_dict={t_data: test_data_ints,\n t_labels: test_labels}))\n \nif __name__ == \"__main__\":\n main()\n","sub_path":"homework2/homework2qrnn_lstm.py","file_name":"homework2qrnn_lstm.py","file_ext":"py","file_size_in_byte":6402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"637959671","text":"import numpy as np \n\ndef to_homogeneous(A):\n \"\"\" \n converts (Nxd) matrix to homogeneous coordinates \n \"\"\"\n N, d = A.shape\n out = np.ones(shape=(N,d+1))\n out[:,:-1] = A \n\n return out\n\n\ndef quat_rot(q):\n \"\"\" \n rotation matrix in terms of quaternions \n \"\"\"\n [q0, q1, q2, q3] = q.tolist()\n\n R = np.zeros(shape=(3,3))\n\n R[0][0] = q0**2 + q1**2 - q2**2 - q3**2\n R[0][1] = 2*(q1*q2 - q0*q3)\n R[0][2] = 2*(q1*q3 + q0*q2)\n\n R[1][0] = 2*(q1*q2 + q0*q3)\n R[1][1] = q0**2 + q2**2 - q1**2 - q3**2\n R[1][2] = 2*(q2*q3 - q0*q1)\n\n R[2][0] = 2*(q1*q3 - q0*q2)\n R[2][1] = 2*(q2*q3 + q0*q1)\n R[2][2] = q0**2 + q3**2 - q1**2 - q2**2\n\n return R\n\n\ndef quat_to_euler(q):\n \"\"\" \n transform quaternion to euler angles, based on wikipedia formuas\n \"\"\"\n [q0, q1, q2, q3] = q.tolist()\n\n phi = np.arctan2(\n (2*(q0*q1+q2*q3)),\n (1 - 2*(q1**2 + q2**2))\n )\n\n theta = np.arcsin(\n 2*(q0*q2 + q3*q1)\n )\n\n psi = np.arctan2(\n (2*(q0*q3 + q1*q2)),\n (1 - 2*(q2**2 + q3**2))\n )\n\n return np.array([phi, theta, psi])\n\n\ndef affine(A, angles, translation, inverse=False):\n \"\"\" \n affine transform\n phi, theta, psi = euler angles\n x, y, z = translations\n assumes A is in homogeneous coordinates\n \"\"\"\n phi = angles[0]\n theta = angles[1]\n psi = angles[2]\n\n x = translation[0]\n y = translation[1]\n z = translation[2]\n\n N = A.shape[0]\n out = np.zeros(shape=(N,3))\n\n R = np.array([\n [np.cos(theta) * np.cos(psi), \n np.cos(theta) * np.sin(psi), \n -np.sin(theta), \n x],\n \n [np.sin(phi) * np.sin(theta) * np.cos(psi) - np.cos(phi) * np.sin(psi), \n np.sin(phi) * np.sin(theta) * np.sin(psi) + np.cos(phi) * np.cos(psi), \n np.sin(phi) * np.cos(theta), \n y],\n\n [np.cos(phi) * np.sin(theta) * np.cos(psi) + np.sin(phi) * np.sin(psi), \n np.cos(phi) * np.sin(theta) * np.sin(psi) - np.sin(phi) * np.cos(psi), \n np.cos(phi) * np.cos(theta), \n z] ])\n\n # for inverse affine transform\n R_T = np.zeros(shape=(3,4))\n R_T[:,:3] = np.linalg.inv(R[:,:3])\n R_T[0][3] = x\n R_T[1][3] = y\n R_T[2][3] = z\n\n if inverse:\n out = np.dot(R_T, A.T)\n return out.T, R_T\n else:\n out = np.dot(R, A.T)\n return out.T, R\n\n return\n\n\ndef cube_points(N, add_noise=False):\n \"\"\" make a numpy cube array, assumes N divisible by 12 \"\"\"\n Y = np.zeros(shape=(N,3))\n seg = np.linspace(0,1,N/12)\n Y[:int(N/12),0] = seg\n Y[int(N/12):2*int(N/12),1] = seg\n Y[2*int(N/12):3*int(N/12),2] = seg\n\n Y[3*int(N/12):4*int(N/12),0] = seg\n Y[3*int(N/12):4*int(N/12),1] = 1\n\n Y[4*int(N/12):5*int(N/12),0] = seg\n Y[4*int(N/12):5*int(N/12),2] = 1\n\n Y[5*int(N/12):6*int(N/12),1] = seg\n Y[5*int(N/12):6*int(N/12),2] = 1\n\n Y[6*int(N/12):7*int(N/12),2] = seg\n Y[6*int(N/12):7*int(N/12),1] = 1\n\n Y[7*int(N/12):8*int(N/12),1] = seg\n Y[7*int(N/12):8*int(N/12),0] = 1\n\n Y[8*int(N/12):9*int(N/12),2] = seg\n Y[8*int(N/12):9*int(N/12),0] = 1\n\n Y[9*int(N/12):10*int(N/12),0] = seg\n Y[9*int(N/12):10*int(N/12),1] = 1\n Y[9*int(N/12):10*int(N/12),2] = 1\n\n Y[10*int(N/12):11*int(N/12),1] = seg\n Y[10*int(N/12):11*int(N/12),0] = 1\n Y[10*int(N/12):11*int(N/12),2] = 1\n\n Y[11*int(N/12):12*int(N/12),2] = seg\n Y[11*int(N/12):12*int(N/12),0] = 1\n Y[11*int(N/12):12*int(N/12),1] = 1\n\n if add_noise:\n noise = np.random.randn(N, 3) / 100\n Y += noise\n\n return Y\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"ros_node/src/icp_node/nodes/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"192840573","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nFile initial creation on Sun Nov 18 2018\n\n@author: Kenneth E. Carlton\n\nThis program compares two BOMs: one originating from SolidWorks (SW) and the\nother from SyteLine (SL). The structure of the BOMs (headings, structure,\netc.) are very unique to my company. Therefore this program, unaltered, will\nfail to function at another company.\n\nRun this program from the command line like this: python bomcheck.py '*'\n\nWithout any arguments help info is shown: python bomcheck.py\n\nRun from a python console terminal like this: bomcheck('*')\n\nTo see how to create an EXE file from this program, see the file named\nhowtocompile.md.\n\"\"\"\n\n__version__ = '1.8.1'\n__author__ = 'Kenneth E. Carlton'\n\nimport glob, argparse, sys, warnings\nimport pandas as pd\nimport os.path\nimport os\nimport tempfile\nimport re\nfrom datetime import datetime\nimport fnmatch\nimport ast\nwarnings.filterwarnings('ignore') # the program has its own error checking.\npd.set_option('display.max_rows', 150)\npd.set_option('display.max_columns', 10)\npd.set_option('display.max_colwidth', 100)\npd.set_option('display.width', 200)\nfrom IPython.core.display import display, HTML\ndisplay(HTML(\"\"))\n\n\ndef get_version():\n return __version__\n\n\ndef getcfg():\n ''' Return the value of \"cfg\". cfg shows configuration\n variables and values thereof that are applied to\n bomcheck when it is run. For example, the variable \n \"accuracy\" is the no. of decimal places that length\n values are rounded to. (See the function \"setcfg\")\n \n Returns\n =======\n \n out: dictionary\n \n Examples\n ========\n \n getcfg()\n '''\n return cfg\n\n\ndef setcfg(**kwargs):\n ''' Set configuration variables that effect how bomcheck\n operates. For example, set the unit of measure that\n length values are calculated to. Run the function \n getcfg() to see the names of variables that can be set. \n Open the file bc_config.py to see an explanation of the\n variables. \n \n The object type that a variable holds (list, string, \n etc.) should be like that seen via the getcfg()\n function, else bomcheck could crash (correcting is just\n a matter rerunning setcfg with the correct values). \n \n Values can be set to something more permanent by \n altering the file bc_config.py.\n \n Examples\n ========\n \n setcfg(drop=[\"3*-025\", \"3*-008\"], accuracy=4) \n '''\n global cfg\n if not kwargs:\n print(\"You did not set any configuration values. Do so like this:\")\n print(\"setcfg(drop=['3886-*'], from_um='IN', to_um='FT')\")\n print(\"Do help(setcfg) for more info\")\n else:\n cfg.update(kwargs)\n\n \ndef set_globals():\n ''' Create a global variables including the primary one named cfg.\n cfg is a dictionary containing settings used by this program.\n\n set_globals() is ran when bomcheck first starts up.\n\n set_globals() tries to derive settings from the file named bc_bomcheck.py\n if it can be located and if values have been established there.\n Otherwise set_globals() creates its on settings for cfg.\n\n (see the function named create_bc_config to find where the file bc_check.py\n is located on you disk drive.)\n '''\n global cfg, printStrs, excelTitle\n\n cfg = {}\n printStrs = []\n excelTitle = []\n\n try:\n import bc_config\n except ModuleNotFoundError:\n def bc_config(): # do this so that doing \"dir(bc_config)\" just below doesn't fail\n pass\n\n cfg = {}\n def insert_into_cfg(var, default):\n ''' Function to insert key/value pairs into the dictionary named cfg.\n Use values set in the file named bc_config.py when available.'''\n global cfg\n cfg[var] = bc_config.__dict__[var] if (var in dir(bc_config)) else default\n\n # default settings for bomcheck. See bc_config.py are explanations about variables.\n list1 = [('accuracy', 2), ('ignore', ['3086-*']),\n ('drop', ['3*-025']), ('exceptions', []),\n ('from_um', 'IN'), ('to_um', 'FT'),\n ('toL_um', 'GAL'), ('toA_um', 'SQF')]\n # Give to bomcheck names of columns that it can expect to see in BOMs. If\n # one of the names, except length names, in each group shown in brackets\n # below is not found, then bomcheck will fail.\n list2 = [('part_num', [\"PARTNUMBER\", \"PART NUMBER\", \"Part Number\", \"Item\", \"Material\"]),\n ('qty', [\"QTY\", \"QTY.\", \"Qty\", \"Quantity\", \"Qty Per\"]),\n ('descrip', [\"DESCRIPTION\", \"Material Description\", \"Description\"]),\n ('um_sl', [\"UM\", \"U/M\"]), # not required in a SW BOM\n ('level_sl', [\"Level\"]), # not required in a SW BOM\n ('itm_sw', [\"ITEM NO.\"]), # not required in a SL BOM\n ('length_sw', [\"LENGTH\", \"Length\", \"L\", \"SIZE\", \"AMT\", \"AMOUNT\", \"MEAS\"])] # not required in a SL or SW BOM\n\n # The function \"insert_into_cfg\" is called upon below. It will fill the\n # dictionary named cfg with values from the bc_config.py file, that is if\n # the values can be found there, otherwise the \"default\" values shown in\n # the two lists above will be used.\n for k, v in list1:\n insert_into_cfg(k, v)\n cfg['accuracy'] = int(cfg['accuracy']) # make sure is an int and not a float\n for k, v in list2:\n insert_into_cfg(k, v)\n\n\ndef getresults(i=1):\n ''' If i = 0, return a dataframe containing SW's BOMs for which no matching\n SL BOMs were found. If i = 1, return a dataframe containing compared\n SW/SL BOMs. If i = 2, return a tuple of two items:\n (getresults(0), getresults(1))'''\n r = []\n r.append(None) if not results[0] else r.append(results[0][0][1])\n r.append(None) if not results[1] else r.append(results[1][0][1])\n if i == 0 or i == 1:\n return r[i]\n elif i == 2:\n return getresults(0), getresults(1)\n else:\n print('i = 0, 1, or 2 only')\n return None\n\n\ndef main():\n '''This fuction allows this bomcheck.py program to be run from the command\n line. It is started automatically (via the \"if __name__=='__main__'\"\n command at the bottom of this file) when bomecheck.py is run.\n\n calls: bomcheck\n\n Examples\n ========\n\n $ python bomcheck.py \"078551*\"\n\n $ python bomcheck.py \"C:/pathtomyfile/6890-*\"\n\n $ python bomcheck.py \"*\"\n\n $ python bomcheck.py --help\n\n '''\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n description='Program compares SolidWorks BOMs to SyteLine BOMs. ' +\n 'Output is sent to a Microsoft Excel spreadsheet.')\n parser.add_argument('filename', help='Name of file containing a BOM. Name ' +\n 'must end with _sw.xlsx, _sl.xlsx. _sw.csv, or ' +\n '_sl.csv. Enclose filename in quotes! An asterisk, *, ' +\n 'caputures multiple files. Examples: \"6890-*\", \"*\". ' +\n 'Or if filename is instead a directory, all _sw and _sl files ' +\n 'in that directory and subdirectories thereof will be ' +\n 'gathered. BOMs gathered from _sl files without ' +\n 'corresponding SolidWorks BOMs found are ignored.')\n parser.add_argument('-a', '--accuracy', help='Decimal place accuracy applied ' +\n 'to lengths in a SolidWorks BOM', default=cfg['accuracy'],\n metavar='value')\n parser.add_argument('-c', '--sheets', action='store_true', default=False,\n help='Break up results across multiple sheets in the ' +\n 'Excel file that is output.') \n parser.add_argument('-d', '--drop_bool', action='store_true', default=False,\n help='Ignore 3*-025 pns, i.e. do not use in the bom check')\n parser.add_argument('-f', '--followlinks', action='store_false', default=False,\n help='Follow symbolic links when searching for files to process. ' +\n \" (MS Windows doesn't honor this option.)\")\n parser.add_argument('--from_um', default=cfg['from_um'], help='The unit of measure ' +\n 'to apply to lengths in a SolidWorks BOM unless otherwise ' +\n 'specified', metavar='value')\n parser.add_argument('--to_um', default=cfg['to_um'], help='The unit of measure ' +\n 'to convert SolidWorks lengths to', metavar='value')\n parser.add_argument('-p', '--pause', help='Pause the program just before the program ' +\n 'the program would normally close after completing its work.',\n default=False, action='store_true')\n parser.add_argument('-v', '--version', action='version', version=__version__,\n help=\"Show program's version number and exit\")\n parser.add_argument('-x', '--excel', help='Create Excel file showing check results.',\n default=False, action='store_true')\n\n if len(sys.argv)==1:\n parser.print_help(sys.stderr)\n sys.exit(1)\n args = parser.parse_args()\n\n bomcheck(args.filename, vars(args))\n\n\ndef bomcheck(fn, dic={}, **kwargs):\n '''\n This is the primary function of the bomcheck program\n and acts as a hub for other functions within the \n bomcheck module.\n\n This function will handle single and multilevel BOMs \n that are derived from SW and/or SL. For multilevel \n BOMs, subassemblies will automatically be extracted \n from the top level BOM.\n\n Any BOMs from SW files found for which no matching SL \n file is found will be converted into a SyteLine like\n BOM format. If a SL BOM is present for which no \n corresponding SW BOM is found, the SW file is ignored;\n that is, no output is shown for this SW file.\n \n See the function setcfg for controlling other\n variables in bomcheck. Do: help(setcfg)\n\n This fuction calls these functions: \n gatherBOMs_from_fnames, collect_checked_boms, \n concat_boms, export2excel, get_fnames\n\n Parmeters\n =========\n\n fn: string or list\n * Files constaining BOMs from SolidWorks and/or \n SyteLine. Files from Solidworks must end with \n _sw.xlsx or _sw.csv. Files from SyteLine must\n end with _sl.xlsx or _sl.csv.\n * An asterisk, *, matches any characters. E.g. \n 6890-083544-* will match 6890-083544-1_sw.xlsx, \n 6890-083544-2_sw.xlsx, etc. \n * fn can be a directory name, in which case\n files in that directory, and subdirectories\n thereof, will be analized.\n * If a list is given, then it is a list of \n filenames and/or directories.\n * PNs shown in filenames must correspond, e.g. \n 099238_sw.xlsx and 099238_sl.xlsx. Exception: \n BOM from SyteLine is a multilevel BOM.\n\n dic: dictionary\n default: {} (i.e. an empty dictionary). This \n variable is only used if the function \"main\" is\n used to run the bomcheck program... that is, the\n bomcheck program was inititiated from the command\n line. If so, keys named \"drop\", \"sheets\", \n \"from_um\", and \"to_um\" and corresponding values \n thereof will have been put into dic.\n\n kwargs: dictionary\n Unlike dic, no values in kwargs are derived from the \n \"main\" function; i.e. bomcheck was not run from the\n command line. I.e., was from from Jupyter Notebook. \n The dictionary key/value items that this function\n looks for are:\n\n c: bool\n Break up results across multiple sheets within\n the Excel bomcheck.xlsx file. Default: False\n\n d: bool\n If True, employ the list named drop which will\n have been created by the function named \n \"set_globals\". (E.g. ignore pt. nos. from a \n SW BOM like 3*-025) Default: False\n \n f: bool\n If True, follow symbolic links when searching \n for files to process. Default: False\n \n l: bool\n Export a list of errors, if any, that occured \n during the bomcheck. Default: False\n \n m: int\n Max no. of rows to display when results are \n output. (This does not effect results that are\n exported an Excel file.) Default: None (That \n is, all rows are output. Nothing is truncated.)\n\n u: str\n Username. This will be fed to the export2exel \n function so that a username will be placed\n into the footer of the bomcheck.xlsx file. \n Default: 'unknown'\n\n x: bool\n Export results to an Excel file named \n bomcheck.xlsx. (If bomcheckgui is used, name \n can be changed.) Default: False\n\n Returns\n =======\n\n out: list|tuple\n\n If argument l is set to True:\n return a list of strings. Each string describes \n an error that occurred during the bomcheck. If\n no errors occurred, return [], i.e. an empty \n string. (bomcheckgui automatically sets \n l = True).\n Else:\n Return a tuple of two items that contains \n bomcheck results. Each of the two items of the \n tuple is a Pandas dataframe object.\n * The first dataframe shows SolidWorks BOMs for\n which no SyteLine BOMs were found to compare\n them to. \n * The second dataframe is SW to SL BOM \n comparisons.\n\n Examples\n ========\n\n >>> # files names starting with 6890\n >>> bomcheck(\"folder1/6890*\", d=True, u=\"John Doe\") \n\n >>> # all files in 'folder1' and in subfolders thereof\n >>> bomcheck(\"folder1\")\n\n >>> # all files, one level deep\n >>> bomcheck(\"folder1/*\") \n\n >>> bomcheck([\"folder1/*\", \"folder2/*\"], d=True)\n\n '''\n global printStrs, cfg, results\n printStrs = []\n results = [None, None]\n # Set settings depending on 1. if input was derived from running this\n # program from the command line (i.e. values from dic), 2. if from\n # excecuting the bomcheck() function within a python console or called by\n # some other python function (i.e. from kwargs), or 3. if the settings were\n # imported from bc_config.py. Many default values (e.g. cfg['from_um'])\n # were initially establisd by the set_globals() function.\n cfg['from_um'] = (dic.get('from_um') if dic.get('from_um')\n else kwargs.get('from_um', cfg['from_um']))\n cfg['to_um'] = (dic.get('to_um') if dic.get('to_um')\n else kwargs.get('to_um', cfg['to_um']))\n cfg['accuracy'] = (dic.get('accuracy') if dic.get('accuracy')\n else kwargs.get('a', cfg['accuracy']))\n cfg['drop_bool'] = (dic.get('drop_bool') if dic.get('drop_bool')\n else kwargs.get('d', False))\n c = (dic.get('sheets') if dic.get('sheets') else kwargs.get('c', False))\n u = kwargs.get('u', 'unknown')\n x = kwargs.get('x', False)\n f = kwargs.get('f', False)\n l = kwargs.get('l', False)\n m = kwargs.get('m', None)\n p = dic.get('pause', False)\n x = dic.get('excel', x)\n\n # If dbdic is in kwargs, it comes from bomcheckgui.\n # Variables thereof take precedence.\n if 'dbdic' in kwargs:\n dbdic = kwargs['dbdic']\n udrop = dbdic.get('udrop', '')\n uexceptions = dbdic.get('uexceptions', '')\n udrop = udrop.replace(',', ' ')\n uexceptions = uexceptions.replace(',', ' ')\n if udrop:\n cfg['drop'] = udrop.split()\n if uexceptions:\n cfg['exceptions'] = uexceptions.split()\n cfg['file2save2'] = dbdic.get('file2save2', 'bomcheck')\n cfg['overwrite'] = dbdic.get('overwrite', False)\n cfg['accuracy'] = dbdic.get('accuracy', 2)\n cfg['from_um'] = dbdic.get('from_um', 'in')\n cfg['to_um'] = dbdic.get('to_um', 'FT')\n u = dbdic.get('author', 'unknown')\n else:\n cfg['file2save2'] = 'bomcheck'\n cfg['overwrite'] = False\n\n if isinstance(fn, str) and fn.startswith('[') and fn.endswith(']'):\n # fn = eval(fn) # change a string to a list\n fn = ast.literal_eval(fn) # change a string to a list\n elif isinstance(fn, str):\n fn = [fn]\n \n pd.set_option('display.max_rows', m)\n\n fn = get_fnames(fn, followlinks=f) # get filenames with any extension.\n\n dirname, swfiles, slfiles = gatherBOMs_from_fnames(fn)\n\n # lone_sw is a dic; Keys are assy nos; Values are DataFrame objects (SW\n # BOMs only). merged_sw2sl is a dic; Keys are assys nos; Values are\n # Dataframe objects (merged SW and SL BOMs).\n lone_sw, merged_sw2sl = collect_checked_boms(swfiles, slfiles)\n\n title_dfsw = [] # Create a list of tuples: [(title, swbom)... ]\n for k, v in lone_sw.items(): # where \"title\" is is the title of the BOM,\n title_dfsw.append((k, v)) # usually the part no. of the BOM.\n\n title_dfmerged = [] # Create a list of tuples: [(title, mergedbom)... ]\n for k, v in merged_sw2sl.items():\n title_dfmerged.append((k, v))\n\n if title_dfsw:\n printStr = '\\nNo matching SyteLine BOMs found for these SolidWorks files:\\n'\n printStr += '\\n'.join(list(map(lambda x: ' ' + x[0], title_dfsw))) + '\\n'\n printStrs.append(printStr)\n print(printStr)\n\n if c == False: # concat_boms is a bomcheck function\n title_dfsw, title_dfmerged = concat_boms(title_dfsw, title_dfmerged)\n results = title_dfsw, title_dfmerged\n\n if x:\n try:\n if title_dfsw or title_dfmerged:\n export2excel(dirname, cfg['file2save2'], title_dfsw + title_dfmerged, u)\n else:\n printStr = ('\\nNotice 203\\n\\n' +\n 'No SolidWorks files found to process. (Lone SyteLine\\n' +\n 'BOMs will be ignored.) Make sure file names end with\\n' +\n '_sw.xlsx, _sw.csv, _sl.xlsx, or _sl.csv.\\n')\n printStrs.append(printStr)\n print(printStr)\n except PermissionError:\n printStr = ('\\nError 202:\\n\\nFailed to write to bomcheck.xlsx\\n'\n 'Cause unknown')\n printStrs.append(printStr)\n print(printStr)\n\n if p == True:\n input(\"Press enter to exit\")\n\n if title_dfsw or title_dfmerged:\n print('calculation done')\n else:\n print('program produced no results')\n\n if l:\n return printStrs\n else:\n return getresults(2)\n\n\ndef get_fnames(fn, followlinks=False):\n ''' Interpret fn to get a list of filenames based on fn's value.\n\n Parameters\n ----------\n fn: str or list\n fn is a filename or a list of filenames. A filename can also be a\n directory name. Example 1, strings: \"C:/myfile_.xlsx\", \"C:/dirname\",\n or \"['filename1', 'filename2', 'dirname1' ...]\". Example 2, list:\n [\"filename1\", \"filename2\", \"dirname1\", \"dirname2\"]. When a a directory\n name is given, filenames are gathered from that directory and from\n subdirectories thereof.\n followlinks: Boolean, optional\n If True, follow symbolic links. If a link is to a direcory, then\n filenames are gathered from that directory and from subdirectories\n thereof. The default is False.\n\n Returns\n -------\n _fn: list\n A list of filenames, e.g. [\"filename1\", \"filename2\", ...]. Each value\n in the list is a string. Each string is the name of a file. The\n filename can be a pathname, e.g. \"C:/dir1/dir2/filename\". The\n filenames can have any type of extension.\n '''\n if isinstance(fn, str) and fn.startswith('[') and fn.endswith(']'):\n #fn = eval(fn) # if fn a string like \"['fname1', 'fname2', ...]\", convert to a list\n fn = ast.literal_eval(fn) # if fn a string like \"['fname1', 'fname2', ...]\", convert to a list\n elif isinstance(fn, str):\n fn = [fn] # fn a string like \"fname1\", convert to a list like [fname1]\n\n _fn1 = []\n for f in fn:\n _fn1 += glob.glob(f)\n\n _fn2 = [] # temporary holder\n for f in _fn1:\n if followlinks==True and os.path.islink(f) and os.path.exists(f):\n _fn2 += get_fnames(os.readlink(f))\n elif os.path.isdir(f): # if a dir, gather all filenames in dirs and subdirs thereof\n for root, dirs, files in os.walk(f, followlinks=followlinks):\n for filename in files:\n _fn2.append(os.path.join(root, filename))\n else:\n _fn2.append(f)\n\n return _fn2\n\n\ndef make_csv_file_stable(filename):\n ''' Except for any commas in a parts DESCRIPTION, replace all commas\n in a csv file with a $ character. Commas will sometimes exist in a\n DESCRIPTION field, e.g, \"TANK, 60GAL\". But commas are intended to be field\n delimeters; commas in a DESCRIPTION field are not. Excess commas in\n a line from a csv file will cause a program crash. Remedy: change those\n commas meant to be delimiters to a dollor sign character, $.\n\n Parmeters\n =========\n\n filename: string\n Name of SolidWorks csv file to process.\n\n Returns\n =======\n\n out: list\n A list of all the lines (rows) in filename is returned. Commas in each\n line are changed to dollar signs except for any commas in the\n DESCRIPTION field.\n '''\n with open(filename, encoding=\"ISO-8859-1\") as f:\n data1 = f.readlines()\n # n1 = number of commas in 2nd line of filename (i.e. where column header\n # names located). This is the no. of commas that should be in each row.\n n1 = data1[1].count(',')\n n2 = data1[1].upper().find('DESCRIPTION') # locaton of the word DESCRIPTION within the row.\n n3 = data1[1][:n2].count(',') # number of commas before the word DESCRIPTION\n data2 = list(map(lambda x: x.replace(',', '$') , data1)) # replace ALL commas with $\n data = []\n for row in data2:\n n4 = row.count('$')\n if n4 != n1:\n # n5 = location of 1st ; character within the DESCRIPTION field\n # that should be a , character\n n5 = row.replace('$', '?', n3).find('$')\n # replace those ; chars that should be , chars in the DESCRIPTION field:\n data.append(row[:n5] + row[n5:].replace('$', ',', (n4-n1))) # n4-n1: no. commas needed\n else:\n data.append(row)\n return data\n\n\ndef common_data(list1, list2):\n ''' function to determine if two lists have at least one common element'''\n result = False\n for x in list1:\n for y in list2:\n if x == y:\n result = True\n return result\n\n\ndef gatherBOMs_from_fnames(filename):\n ''' Gather all SolidWorks and SyteLine BOMs derived from \"filename\".\n \"filename\" can be a string containing wildcards, e.g. 6890-085555-*, which\n allows the capture of multiple files; or \"filename\" can be a list of such\n strings. These files (BOMs) will be converted to Pandas DataFrame objects.\n\n Only files prefixed with _sw.xlsx, _sw.csv, _sl.xlsx, or _sl.csv will be\n chosen; others are discarded. These files will then be converted into two\n python dictionaries. One dictionary will contain SolidWorks BOMs only, and\n the other will contain only SyteLine BOMs.\n\n If a filename has a BOM containing a multiple level BOM, then the\n subassembly BOMs will be extracted from that BOM and be added to the\n dictionaries.\n\n calls: make_csv_file_stable, deconstructMultilevelBOM, test_for_missing_columns\n\n Parmeters\n =========\n\n filename: list\n List of filenames to be analyzed.\n\n Returns\n =======\n\n out: tuple\n The output tuple contains three items. The first is the directory\n corresponding to the first file in the filename list. If this\n directory is an empty string, then it refers to the current working\n directory. The remainder of the tuple items are two python\n dictionaries. The first dictionary contains SolidWorks BOMs, and the\n second contains SyteLine BOMs. The keys for these two dictionaries\n are part nos. of assemblies derived from the filenames (e.g. 085952\n from 085953_sw.xlsx), or derived from subassembly part numbers of a\n file containing multilevel BOM.\n '''\n dirname = '.' # to this will assign the name of 1st directory a _sw is found in\n global printStrs\n def fixcolnames(df):\n '''rid any column names of '\\n' char if exists'''\n colnames = []\n for colname in df.columns:\n colnames.append(str(colname).replace('\\n', ''))\n return colnames\n swfilesdic = {}\n slfilesdic = {}\n for f in filename: # from filename extract all _sw & _sl files and put into swfilesdic & slfilesdic\n i = f.rfind('_')\n if f[i:i+4].lower() == '_sw.' or f[i:i+4].lower() == '_sl.':\n dname, fname = os.path.split(f)\n k = fname.rfind('_')\n fntrunc = fname[:k] # Name of the sw file, excluding path, and excluding _sw.xlsx\n if f[i:i+4].lower() == '_sw.' and '~' not in fname: # Ignore names like ~$085637_sw.xlsx\n swfilesdic.update({fntrunc: f})\n if dirname == '.':\n dirname = os.path.dirname(os.path.abspath(f)) # use 1st dir where a _sw file is found to put bomcheck.xlsx\n elif f[i:i+4].lower() == '_sl.' and '~' not in fname:\n slfilesdic.update({fntrunc: f})\n swdfsdic = {} # for collecting SW BOMs to a dic\n for k, v in swfilesdic.items():\n try:\n _, file_extension = os.path.splitext(v)\n if file_extension.lower() == '.csv' or file_extension.lower() == '.txt':\n data = make_csv_file_stable(v)\n temp = tempfile.TemporaryFile(mode='w+t')\n for d in data:\n temp.write(d)\n temp.seek(0)\n df = pd.read_csv(temp, na_values=[' '], skiprows=1, sep='$',\n encoding='iso8859_1', engine='python',\n dtype = dict.fromkeys(cfg['itm_sw'], 'str'))\n df.columns = fixcolnames(df)\n if test_for_missing_columns('sw', df, '', printerror=False):\n df = pd.read_csv(temp, na_values=[' '], sep='$',\n encoding='iso8859_1', engine='python',\n dtype = dict.fromkeys(cfg['itm_sw'], 'str'))\n df.columns = fixcolnames(df)\n temp.close()\n elif file_extension.lower() == '.xlsx' or file_extension.lower() == '.xls':\n df = pd.read_excel(v, na_values=[' '], skiprows=1)\n df.columns = fixcolnames(df)\n if test_for_missing_columns('sw', df, '', printerror=False):\n df = pd.read_excel(v, na_values=[' '])\n df.columns = fixcolnames(df)\n\n if not test_for_missing_columns('sw', df, k):\n swdfsdic.update(deconstructMultilevelBOM(df, 'sw', k))\n except:\n printStr = '\\nError processing file: ' + v + '\\nIt has been excluded from the BOM check.\\n'\n printStrs.append(printStr)\n print(printStr)\n sldfsdic = {} # for collecting SL BOMs to a dic\n for k, v in slfilesdic.items():\n try:\n _, file_extension = os.path.splitext(v)\n if file_extension.lower() == '.csv' or file_extension.lower() == '.txt':\n try:\n df = pd.read_csv(v, na_values=[' '], engine='python',\n #skiprows=cfg['skiprows_sl'],\n encoding='utf-16', sep='\\t')\n except UnicodeError:\n printStr = (\"\\nError 204.\\n\\n.\"\n \"Probable cause: This program expects Unicode text encoding from\\n\"\n \"a csv file. The file \" + v + \" does not have this. The\\n\"\n \"correct way to achieve a functional csv file is:\\n\\n\"\n ' From Excel, save the file as type “Unicode Text (*.txt)”, and then\\n'\n ' change the file extension from txt to csv.\\n\\n'\n \"On the other hand, easiest solution: use an Excel file instead.\\n\")\n printStrs.append(printStr)\n print(printStr)\n sys.exit(1)\n elif file_extension.lower() == '.xlsx' or file_extension.lower == '.xls':\n df = pd.read_excel(v, na_values=[' ']) #, skiprows=cfg['skiprows_sl'])\n\n if (not (test_for_missing_columns('sl', df, k)) and\n common_data(cfg['level_sl'], df.columns)):\n sldfsdic.update(deconstructMultilevelBOM(df, 'sl', 'TOPLEVEL'))\n elif not test_for_missing_columns('sl', df, k):\n sldfsdic.update(deconstructMultilevelBOM(df, 'sl', k))\n\n except:\n printStr = ('\\nError 201.\\n\\n' + ' processing file: ' + v +\n '\\nIt has been excluded from the BOM check.\\n')\n printStrs.append(printStr)\n print(printStr)\n try:\n df = pd.read_clipboard(engine='python', na_values=[' '])\n if not test_for_missing_columns('sl', df, 'BOMfromClipboard', printerror=False):\n sldfsdic.update(deconstructMultilevelBOM(df, 'sl', 'TOPLEVEL'))\n except:\n pass\n if os.path.islink(dirname):\n dirname = os.readlink(dirname)\n return dirname, swdfsdic, sldfsdic\n\n\ndef test_for_missing_columns(bomtype, df, pn, printerror=True):\n ''' SolidWorks and SyteLine BOMs require certain essential columns to be\n present. This function looks at those BOMs that are within df to see if\n any required columns are missing. If found, print to screen.\n\n calls: test_alternative_column_names\n\n Parameters\n ==========\n\n bomtype: string\n \"sw\" or \"sl\"\n\n df: Pandas DataFRame\n A SW or SL BOM\n\n pn: string\n Part number of the BOM\n\n Returns\n =======\n\n out: bool\n True if BOM afoul. Otherwise False.\n '''\n global printStrs\n if bomtype == 'sw':\n required_columns = [cfg['qty'], cfg['descrip'],\n cfg['part_num'], cfg['itm_sw']]\n else: # 'for sl bom'\n required_columns = [cfg['qty'], cfg['descrip'],\n cfg['part_num'], cfg['um_sl']]\n\n missing = []\n for r in required_columns:\n if isinstance(r, str) and r not in df.columns:\n missing.append(r)\n elif isinstance(r, list) and test_alternative_column_names(r, df.columns):\n missing.append(' or '.join(test_alternative_column_names(r, df.columns)))\n if missing and bomtype=='sw' and printerror:\n printStr = ('\\nEssential BOM columns missing. SolidWorks requires a BOM header\\n' +\n 'to be in place. This BOM will not be processed:\\n\\n' +\n ' missing: ' + ' ,'.join(missing) + '\\n' +\n ' missing in: ' + pn + '\\n')\n printStrs.append(printStr)\n print(printStr)\n return True\n elif missing and printerror:\n printStr = ('\\nEssential BOM columns missing. This BOM will not be processed:\\n' +\n ' missing: ' + ' ,'.join(missing) + '\\n\\n' +\n ' missing in: ' + pn + '\\n')\n printStrs.append(printStr)\n print(printStr)\n return True\n elif missing:\n return True\n else:\n return False\n\n\ndef test_alternative_column_names(tpl, lst):\n ''' tpl contains alternative names for a required column in a bom. If\n none of the names in tpl match a name in lst, return tpl so that the\n user can be notified that one of those alternative names should have been\n present. On the other hand, if a match was found, return None.\n\n Parameters\n ==========\n tpl: tuple or list\n Each item of tpl is a string. Each item is an alternative column name,\n e.g. (\"Qty\", \"Quantity\")\n\n lst: list\n A list of the required columns that a bom must have in order for a bom\n check to be correctly completed.\n\n Returns\n =======\n out: tpl|None\n If no match found, return the same tuple, tpl, that was an input\n parameter. Else return None\n '''\n flag = True\n for t in tpl:\n if t in lst:\n flag = False # A required column name was found in the tuple, so good to proceed with bom check\n if flag:\n return tpl # one of the tuple items is a required column. Report that one or the other is missing\n\n\ndef col_name(df, col):\n '''\n Parameters\n ----------\n df: Pandas DataFrame\n\n col: list\n List of column names that will be compared to the list of column\n names from df (i.e. from df.columns)\n\n Returns\n -------\n out: string\n Name of column that is common to both df.columns and col\n '''\n try:\n df_cols_as_set = set(list(df.columns))\n intersect = df_cols_as_set.intersection(col)\n return list(intersect)[0]\n except IndexError:\n return \"\"\n\n\ndef deconstructMultilevelBOM(df, source, top='TOPLEVEL'):\n ''' If the BOM is a multilevel BOM, pull out the BOMs thereof; that is,\n pull out the main assembly and the subassemblies thereof. These\n assys/subassys are placed in a python dictionary and returned. If df is\n a single level BOM, a dictionary with one item is returned.\n\n For this function to pull out subassembly BOMs from a SyteLine BOM, the\n column named Level must exist in the SyteLine BOM. It contains integers\n indicating the level of a subassemby within the BOM; e.g. 1, 2, 3, 2, 3,\n 3, 3, 4, 4, 2. Only multilevel SyteLine BOMs contain this column.\n On the other hand for this function to pull out subassemblies from a\n SolidWorks BOM, the column ITEM NO. (see set_globals() for other optional\n names) must exist and contain values that indicate which values are\n subassemblies; e.g, with item numbers like \"1, 2, 2.1, 2.2, 3, 4, etc.,\n items 2.1 and 2.2 are members of the item number 2 subassembly.\n\n Parmeters\n =========\n\n df: Pandas DataFrame\n The DataFrame is that of a SolidWorks or SyteLine BOM.\n\n source: string\n Choices for source are \"sw\" or \"sl\". That is, is the BOM being\n deconstructed from SolidWorks or SyteLine.\n\n top: string\n Top level part number. This number is automatically generated by the\n bomcheck program in two ways: 1. If df originated from a SolidWorks\n BOM or from a single level SyteLine BOM, then “top” is derived from\n the filename; e.g. 091828 from the filename 091828_sw.xlsx. 2. If df\n originated from a multilevel BOM, then it has a column named “Level”\n (i.e. the level of subassemblies and parts within subassemblies\n relative to the main, top, assembly part number). In this case the\n part number associated with level \"0\" is assigned to \"top\".\n\n Returns\n =======\n\n out: python dictionary\n The dictionary has the form {assypn1: BOM1, assypn2: BOM2, ...},\n where assypn1, assypn2, etc. are string objects and are the part\n numbers for BOMs; and BOM1, BOM2, etc. are pandas DataFrame objects\n that pertain to those part numbers.\n '''\n __lvl = col_name(df, cfg['level_sl'])\n __itm = col_name(df, cfg['itm_sw'])\n __pn = col_name(df, cfg['part_num']) # get the column name for pns\n\n p = None\n df[__pn] = df[__pn].astype('str').str.strip() # make sure pt nos. are \"clean\"\n df[__pn].replace('', 'no pn from BOM!', inplace=True)\n\n # https://stackoverflow.com/questions/2974022/is-it-possible-to-assign-the-same-value-to-multiple-keys-in-a-dict-object-at-onc\n values = dict.fromkeys((cfg['qty'] + cfg['length_sw']), 0)\n values.update(dict.fromkeys(cfg['descrip'], 'no descrip from BOM!'))\n values.update(dict.fromkeys(cfg['part_num'], 'no pn from BOM!'))\n df.fillna(value=values, inplace=True)\n\n # Generate a column named __Level which contains integers based based upon\n # the level of a part within within an assembly or within subassembly of\n # an assembly. 0 is the top level assembly, 1 is a part or subassembly one\n # level deep, and 2, 3, etc. are levels within subassemblies.\n if source=='sw' and __itm and __itm in df.columns:\n __itm = df[__itm].astype('str')\n __itm = __itm.str.replace('.0', '') # stop something like 5.0 from slipping through\n df['__Level'] = __itm.str.count('\\.') # level is the number of periods (.) in the string\n elif source=='sl' and __lvl and __lvl in df.columns:\n df['__Level'] = df[__lvl]\n else:\n df['__Level'] = 0\n\n # Take the the column named \"__Level\" and create a new column: \"Level_pn\".\n # Instead of the level at which a part exists within an assembly, like\n # \"__Level\" which contains integers like [0, 1, 2, 2, 1], \"Level_pn\" contains\n # the parent part no. of the part at a particular level, e.g.\n # ['TOPLEVEL', '068278', '2648-0300-001', '2648-0300-001', '068278']\n lvl = 0\n level_pn = [] # storage of pns of parent assy/subassy of the part at rows 0, 1, 2, 3, ...\n assys = [] # storage of all assys/subassys found (stand alone parts ignored)\n for item, row in df.iterrows():\n if row['__Level'] == 0:\n poplist = []\n level_pn.append(top)\n if top != \"TOPLEVEL\":\n assys.append(top)\n elif 'Description' in df.columns and lvl == 0:\n excelTitle.append((row[__pn], row['Description'])) # info for a global variable\n elif row['__Level'] > lvl:\n if p in assys:\n poplist.append('repeat')\n else:\n assys.append(p)\n poplist.append(p)\n level_pn.append(poplist[-1])\n elif row['__Level'] == lvl:\n level_pn.append(poplist[-1])\n elif row['__Level'] < lvl:\n i = row['__Level'] - lvl # how much to pop. i is a negative number.\n poplist = poplist[:i] # remove, i.e. pop, i items from end of list\n level_pn.append(poplist[-1])\n p = row[__pn]\n lvl = row['__Level']\n df['Level_pn'] = level_pn\n # collect all assys/subassys within df and return a dictionary. keys\n # of the dictionary are pt. numbers of assys/subassys.\n dic_assys = {}\n for k in assys:\n dic_assys[k.upper()] = df[df['Level_pn'] == k]\n return dic_assys\n\n\ndef is_in(find, series, xcept):\n '''Argument \"find\" is a list of strings that are glob expressions. The\n Pandas Series \"series\" will be evaluated to see if any members of find\n exists as substrings within each member of series. Glob expressions are\n strings like '3086-*-025' or *2020*. '3086-*-025' for example will match\n '3086-0050-025' and '3086-0215-025'.\n\n The output of the is_in function is a Pandas Series. Each member of the\n Series is True or False depending on whether a substring has been found\n or not.\n\n xcept is a list of exceptions to those in the find list. For example, if\n '3086-*-025' is in the find list and '3086-3*-025' is in the xcept list,\n then series members like '3086-0515-025' or '3086-0560-025' will return\n a True, and '3086-3050-025' or '3086-3060-025' will return a False.\n\n For reference, glob expressions are explained at:\n https://en.wikipedia.org/wiki/Glob_(programming)\n\n Parmeters\n =========\n\n find: string or list of strings\n Items to search for\n\n series: Pandas Series\n Series to search\n\n xcept: string or list of strings\n Exceptions to items to search for\n\n Returns\n =======\n\n out: Pandas Series, dtype: bool\n Each item is True or False depending on whether a match was found or not\n '''\n if not isinstance(find, list):\n find = [find]\n if not isinstance(xcept, list) and xcept:\n xcept = [xcept]\n elif isinstance(xcept, list):\n pass\n else:\n xcept = []\n series = series.astype(str).str.strip() # ensure that all elements are strings & strip whitespace from ends\n find2 = []\n for f in find:\n find2.append('^' + fnmatch.translate(str(f)) + '$') # reinterpret user input with a regex expression\n xcept2 = []\n for x in xcept: # exceptions is also a global variable\n xcept2.append('^' + fnmatch.translate(str(x)) + '$')\n if find2 and xcept2:\n filtr = (series.str.contains('|'.join(find2)) & ~series.str.contains('|'.join(xcept2)))\n elif find2:\n filtr = series.str.contains('|'.join(find2))\n else:\n filtr = pd.Series([False]*series.size)\n return filtr\n\n\ndef convert_sw_bom_to_sl_format(df):\n '''Take a SolidWorks BOM and restructure it to be like that of a SyteLine\n BOM. That is, the following is done:\n\n - For parts with a length provided, the length is converted from from_um to\n to_um (see the function main for a definition of these variables).\n Typically the unit of measure in a SolidWorks BOM is inches, and in\n SyteLine, feet.\n - If the part is a pipe or beam and it is listed multiple times in the BOM,\n the BOM is updated so that only one listing is shown and the lengths\n of the removed listings are added to the remaining listing.\n - Similar to above, parts such as pipe nipples will show up more that\n once on a BOM. Remove the excess listings and add the quantities of\n the removed listings to the remaining listing.\n - If global variable cfg['drop'] is set to True, off the shelf parts, which\n are usually pipe fittings, are removed from the SolidWorks BOM. (As a\n general rule, off-the-shelf parts are not shown on SyteLine BOMs.) The\n list that governs this rule is in a file named drop.py. Other part nos.\n may be added to this list as required. (see the function set_globals\n for more information)\n - Column titles are changed to match those of SyteLine and thus will allow\n merging to a SyteLine BOM.\n\n calls: create_um_factors\n\n Parmeters\n =========\n\n df: Pandas DataFrame\n SolidWorks DataFrame object to process.\n\n Returns\n =======\n\n out: pandas DataFrame\n A SolidWorks BOM with a structure like that of SyteLine.\n\n \\u2009\n '''\n\n values = dict.fromkeys(cfg['part_num'], 'Item')\n values.update(dict.fromkeys(cfg['length_sw'], 'LENGTH'))\n values.update(dict.fromkeys(cfg['descrip'], 'Description'))\n values.update(dict.fromkeys(cfg['qty'], 'Q'))\n df.rename(columns=values, inplace=True)\n\n if 'LENGTH' in df.columns: # convert lengths to other unit of measure, i.e. to_um\n ser = df['LENGTH']\n value = ser.replace('[^\\d.]', '', regex=True).apply(str).str.strip('.').astype(float) # \"3.5MM\" -> 3.5\n from_um = ser.apply(str).replace('[\\d.]', '', regex=True) # e.g. \"3.5MM\" -> \"mm\"\n from_um.replace('', cfg['from_um'].lower(), inplace=True) # e.g. \"\" -> \"ft\"\n from_um = from_um.str.strip().str.lower() # e.g. \"SQI\\n\" -> \"sqi\"\n to_um = from_um.apply(lambda x: cfg['toL_um'].lower() if x.lower() in liquidUMs else\n (cfg['toA_um'].lower() if x.lower() in areaUMs else cfg['to_um'].lower()))\n ignore_filter = ~is_in(cfg['ignore'], df['Item'], [])\n df['U'] = to_um.str.upper().mask(value <= 0.0001, 'EA').mask(~ignore_filter, 'EA')\n factors = (from_um.map(factorpool) * 1/to_um.map(factorpool)).fillna(-1)\n q = df['Q'].replace('[^\\d]', '', regex=True).apply(str).str.strip('.') # strip away any text\n q = q.replace('', '0').astype(float) # if any empty strings, set to '0'\n value2 = value * q * factors * ignore_filter\n df['Q'] = q*(value2<.0001) + value2 # move lengths to the Qty column\n else:\n df['U'] = 'EA' # if no length colunm exists then set all units of measure to EA\n\n df = df.reindex(['Op', 'WC','Item', 'Q', 'Description', 'U'], axis=1) # rename and/or remove columns\n dd = {'Q': 'sum', 'Description': 'first', 'U': 'first'} # funtions to apply to next line\n df = df.groupby('Item', as_index=False).aggregate(dd).reindex(columns=df.columns)\n\n if cfg['drop_bool']==True:\n filtr3 = is_in(cfg['drop'], df['Item'], cfg['exceptions'])\n df.drop(df[filtr3].index, inplace=True)\n\n df['WC'] = 'PICK' # WC is a standard column shown in a SL BOM.\n df['Op'] = 10 # Op is a standard column shown in a SL BOM, usually set to 10\n df.set_index('Op', inplace=True)\n\n return df\n\n\ndef compare_a_sw_bom_to_a_sl_bom(dfsw, dfsl):\n '''This function takes in one SW BOM and one SL BOM and then merges them.\n This merged BOM shows the BOM check allowing differences between the\n SW and SL BOMs to be easily seen.\n\n A set of columns in the output are labeled i, q, d, and u. Xs at a row in\n any of these columns indicate something didn't match up between the SW\n and SL BOMs. An X in the i column means the SW and SL Items (i.e. pns)\n don't match. q means quantity, d means description, u means unit of\n measure.\n\n Parmeters\n =========\n\n dfsw: Pandas DataFrame\n A DataFrame of a SolidWorks BOM\n\n dfsl: Pandas DataFrame\n A DataFrame of a SyteLine BOM\n\n Returns\n =======\n\n df_merged: Pandas DataFrame\n df_merged is a DataFrame that shows a side-by-side comparison of a\n SolidWorks BOM to a SyteLine BOM.\n\n \\u2009\n '''\n global printStrs\n if not str(type(dfsw))[-11:-2] == 'DataFrame':\n printStr = '\\nProgram halted. A fault with SolidWorks DataFrame occurred.\\n'\n printStrs.append(printStr)\n print(printStr)\n sys.exit()\n\n # A BOM can be derived from different locations within SL. From one location\n # the `Item` is the part number. From another `Material` is the part number.\n # When `Material` is the part number, a useless 'Item' column is also present.\n # It causes the bomcheck program confusion and the program crashes. Thus a fix:\n if 'Item' in dfsl.columns and 'Material' in dfsl.columns:\n dfsl.drop(['Item'], axis=1, inplace=True) # the \"drop\" here is not that in the cfg dictionary\n if 'Description' in dfsl.columns and 'Material Description' in dfsl.columns:\n dfsl.drop(['Description'], axis=1, inplace=True)\n\n values = dict.fromkeys(cfg['part_num'], 'Item')\n values.update(dict.fromkeys(cfg['um_sl'], 'U'))\n values.update(dict.fromkeys(cfg['descrip'], 'Description'))\n values.update(dict.fromkeys(cfg['qty'], 'Q'))\n values.update({'Obsolete Date': 'Obsolete'})\n dfsl.rename(columns=values, inplace=True)\n\n if 'Obsolete' in dfsl.columns: # Don't use any obsolete pns (even though shown in the SL BOM)\n filtr4 = dfsl['Obsolete'].notnull()\n dfsl.drop(dfsl[filtr4].index, inplace=True) # https://stackoverflow.com/questions/13851535/how-to-delete-rows-from-a-pandas-dataframe-based-on-a-conditional-expression\n\n # When pns are input into SyteLine, all the characters of pns should\n # be upper case. But on occasion people have mistakently used lower case.\n # Correct this and report what pns have been in error.\n x = dfsl['Item'].copy()\n dfsl['Item'] = dfsl['Item'].str.upper() # make characters upper case\n x_bool = x != dfsl['Item']\n x_lst = [i for i in list(x*x_bool) if i]\n if x_lst:\n printStr = (\"\\nLower case part nos. in SyteLine's BOM have been converted \" +\n \"to upper case for \\nthis BOM check:\\n\")\n printStrs.append(printStr)\n print(printStr)\n for y in x_lst:\n printStr = ' ' + y + ' changed to ' + y.upper() + '\\n'\n printStrs.append(printStr)\n print(printStr)\n\n dfmerged = pd.merge(dfsw, dfsl, on='Item', how='outer', suffixes=('_sw', '_sl') ,indicator=True)\n dfmerged.Q_sw.fillna(0, inplace=True)\n dfmerged.U_sl.fillna('', inplace=True)\n\n ###########################################################################\n # If U/M in SW isn't the same as that in SL, adjust SW's length values #\n # so that lengths are per SL's U/M. Then replace the U/M in the column #\n # named U_sw with the updated U/M that matches that in SL. #\n from_um = dfmerged.U_sw.str.lower().fillna('') #\n to_um = dfmerged.U_sl.str.lower().fillna('') #\n factors = (from_um.map(factorpool) * 1/to_um.map(factorpool)).fillna(1) #\n dfmerged.Q_sw = dfmerged.Q_sw * factors #\n dfmerged.Q_sw = round(dfmerged.Q_sw, cfg['accuracy']) #\n func = lambda x1, x2: x1 if (x1 and x2) else x2 #\n dfmerged.U_sw = to_um.combine(from_um, func, fill_value='').str.upper() #\n ###########################################################################\n\n dfmerged.sort_values(by=['Item'], inplace=True)\n filtrI = dfmerged['_merge'].str.contains('both') # this filter determines if pn in both SW and SL\n maxdiff = .51 / (10**cfg['accuracy'])\n filtrQ = abs(dfmerged['Q_sw'] - dfmerged['Q_sl']) < maxdiff # If diff in qty greater than this value, show X\n filtrM = dfmerged['Description_sw'].str.split() == dfmerged['Description_sl'].str.split()\n filtrU = dfmerged['U_sw'].astype('str').str.upper().str.strip() == dfmerged['U_sl'].astype('str').str.upper().str.strip()\n chkmark = '-'\n err = 'X'\n\n dfmerged['i'] = filtrI.apply(lambda x: chkmark if x else err) # X = Item not in SW or SL\n dfmerged['q'] = filtrQ.apply(lambda x: chkmark if x else err) # X = Qty differs btwn SW and SL\n dfmerged['d'] = filtrM.apply(lambda x: chkmark if x else err) # X = Mtl differs btwn SW & SL\n dfmerged['u'] = filtrU.apply(lambda x: chkmark if x else err) # X = U differs btwn SW & SL\n dfmerged['i'] = ~dfmerged['Item'].duplicated(keep=False) * dfmerged['i'] # duplicate in SL? i-> blank\n dfmerged['q'] = ~dfmerged['Item'].duplicated(keep=False) * dfmerged['q'] # duplicate in SL? q-> blank\n dfmerged['d'] = ~dfmerged['Item'].duplicated(keep=False) * dfmerged['d'] # duplicate in SL? d-> blank\n dfmerged['u'] = ~dfmerged['Item'].duplicated(keep=False) * dfmerged['u'] # duplicate in SL? u-> blank\n\n dfmerged = dfmerged[['Item', 'i', 'q', 'd', 'u', 'Q_sw', 'Q_sl',\n 'Description_sw', 'Description_sl', 'U_sw', 'U_sl']]\n dfmerged.fillna('', inplace=True)\n dfmerged.set_index('Item', inplace=True)\n dfmerged.Q_sw.replace(0, '', inplace=True)\n\n return dfmerged\n\n\ndef collect_checked_boms(swdic, sldic):\n ''' Match SolidWorks assembly nos. to those from SyteLine and then merge\n their BOMs to create a BOM check. For any SolidWorks BOMs for which no\n SyteLine BOM was found, put those in a separate dictionary for output.\n\n calls: convert_sw_bom_to_sl_format, compare_a_sw_bom_to_a_sl_bom\n\n Parameters\n ==========\n\n swdic: dictionary\n Dictinary of SolidWorks BOMs. Dictionary keys are strings and they\n are of assembly part numbers. Dictionary values are pandas DataFrame\n objects which are BOMs for those assembly pns.\n\n sldic: dictionary\n Dictinary of SyteLine BOMs. Dictionary keys are strings and they\n are of assembly part numbers. Dictionary values are pandas DataFrame\n objects which are BOMs for those assembly pns.\n\n Returns\n =======\n\n out: tuple\n The output tuple contains two values: 1. Dictionary containing\n SolidWorks BOMs for which no matching SyteLine BOM was found. The\n BOMs have been converted to a SyteLine like format. Keys of the\n dictionary are assembly part numbers. 2. Dictionary of merged\n SolidWorks and SyteLine BOMs, thus creating a BOM check. Keys for the\n dictionary are assembly part numbers.\n '''\n lone_sw_dic = {} # sw boms with no matching sl bom found\n combined_dic = {} # sl bom found for given sw bom. Then merged\n for key, dfsw in swdic.items():\n if key in sldic:\n combined_dic[key] = compare_a_sw_bom_to_a_sl_bom(\n convert_sw_bom_to_sl_format(dfsw), sldic[key])\n else:\n df = convert_sw_bom_to_sl_format(dfsw)\n df['Q'] = round(df['Q'], cfg['accuracy'])\n #lone_sw_dic[key + '_sw'] = df\n lone_sw_dic[key] = df\n return lone_sw_dic, combined_dic\n\n\ndef concat_boms(title_dfsw, title_dfmerged):\n ''' Concatenate all the SW BOMs into one long list (if there are any SW\n BOMs without a matching SL BOM being found), and concatenate all the\n merged SW/SL BOMs into another long list.\n\n Each BOM, before concatenation, will get a new column added: assy. Values\n for assy will all be the same for a given BOM: the pn (a string) of the BOM.\n BOMs are then concatenated. Finally Pandas set_index function will applied\n to the assy column resulting in the ouput being categorized by the assy pn.\n\n\n Parameters\n ==========\n\n title_dfsw: list\n A list of tuples, each tuple has two items: a string and a DataFrame.\n The string is the assy pn for the DataFrame. The DataFrame is that\n derived from a SW BOM.\n\n title_dfmerged: list\n A list of tuples, each tuple has two items: a string and a DataFrame.\n The string is the assy pn for the DataFrame. The DataFrame is that\n derived from a merged SW/SL BOM.\n\n Returns\n =======\n\n out: tuple\n The output is a tuple comprised of two items. Each item is a list.\n Each list contains one item: a tuple. The structure has the form:\n\n ``out = ([(\"SW BOMS\", DataFrame1)], [(\"BOM Check\", DataFrame2)])``\n\n Where...\n \"SW BOMS\" is the title. (when c=True in the bomcheck function, the\n title will be an assembly part no.).\n DataFrame1 = SW BOMs that have been concatenated together.\n\n \"BOM Check\" is another title.\n DataFrame2 = Merged SW/SL BOMs that have been concatenated together.\n '''\n dfswDFrames = []\n dfmergedDFrames = []\n swresults = []\n mrgresults = []\n for t in title_dfsw:\n t[1]['assy'] = t[0]\n dfswDFrames.append(t[1])\n for t in title_dfmerged:\n t[1]['assy'] = t[0]\n dfmergedDFrames.append(t[1])\n if dfswDFrames:\n dfswCCat = pd.concat(dfswDFrames).reset_index()\n swresults.append(('SW BOMs', dfswCCat.set_index(['assy', 'Op']).sort_index(axis=0)))\n if dfmergedDFrames:\n dfmergedCCat = pd.concat(dfmergedDFrames).reset_index()\n mrgresults.append(('BOM Check', dfmergedCCat.set_index(['assy', 'Item']).sort_index(axis=0)))\n return swresults, mrgresults\n\n\ndef export2excel(dirname, filename, results2export, uname):\n '''Export to an Excel file the results of all the BOM checks.\n\n calls: len2, autosize_excel_columns, autosize_excel_column_df, definefn...\n (these functions are defined internally within the export2exel function)\n\n Parmeters\n =========\n\n dirname: string\n The directory to which the Excel file that this function generates\n will be sent.\n\n filename: string\n The name of the Excel file.\n\n results2export: list\n List of tuples. The number of tuples in the list varies according to\n the number of BOMs analyzed, and if bomcheck's c (sheets) option was\n invoked or not. Each tuple has two items. The first item of a tuple\n is a string and is the name to be assigned to the tab of the Excel\n worksheet. It is typically an assembly part number. The second item\n is a BOM (a DataFrame object). The list of tuples consists of:\n\n *1* SolidWorks BOMs that have been converted to SyteLine format. SW\n BOMs will only occur if no corresponding SL BOM was found.\n\n *2* Merged SW/SL BOMs.\n\n That is, if c=1, the form will be:\n\n - [('2730-2019-544_sw', df1), ('080955', df2),\n ('6890-080955-1', df3), ('0300-2019-533', df4), ...]\n\n and if c=0, the form will be:\n\n - [('SW BOMs', dfForSWboms), ('BOM Check', dfForMergedBoms)]\n\n\n uname : string\n Username to attach to the footer of the Excel file.\n\n Returns\n =======\n\n out: None\n An Excel file will result named bomcheck.xlsx.\n\n \\u2009\n '''\n global printStrs\n\n def len2(s):\n ''' Extract from within a string either a decimal number truncated to two\n decimal places, or an int value; then return the length of that substring.\n Why used? Q_sw, Q_sl, Q, converted to string, are on ocasion something\n like 3.1799999999999997. This leads to wrong length calc using len.'''\n match = re.search(r\"\\d*\\.\\d\\d|\\d+\", s)\n if match:\n return len(match.group())\n else:\n return 0\n\n def autosize_excel_columns(worksheet, df):\n ''' Adjust column width of an Excel worksheet (ref.: https://stackoverflow.com/questions/\n 17326973/is-there-a-way-to-auto-adjust-excel-column-widths-with-pandas-excelwriter)'''\n autosize_excel_columns_df(worksheet, df.index.to_frame())\n autosize_excel_columns_df(worksheet, df, offset=df.index.nlevels)\n\n def autosize_excel_columns_df(worksheet, df, offset=0):\n for idx, col in enumerate(df):\n x = 1 # add a little extra width to the Excel column\n if df.columns[idx] in ['i', 'q', 'd', 'u']:\n x = 0\n series = df[col]\n if df.columns[idx][0] == 'Q':\n max_len = max((\n series.astype(str).map(len2).max(),\n len(str(series.name))\n )) + x\n else:\n max_len = max((\n series.astype(str).map(len).max(),\n len(str(series.name))\n )) + x\n worksheet.set_column(idx+offset, idx+offset, max_len)\n\n def definefn(dirname, filename, i=0):\n ''' If bomcheck.xlsx slready exists, return bomcheck(1).xlsx. If that\n exists, return bomcheck(2).xlsx... and so forth.'''\n global printStrs\n d, f = os.path.split(filename)\n f, e = os.path.splitext(f)\n if d:\n dirname = d # if user specified a directory, use it instead\n if e and not e.lower()=='.xlsx':\n printStr = '\\n(Output filename extension needs to be .xlsx' + '\\nProgram aborted.\\n'\n printStrs.append(printStr)\n print(printStr)\n sys.exit(0)\n else:\n e = '.xlsx'\n if i == 0:\n fn = os.path.join(dirname, f+e)\n else:\n fn = os.path.join(dirname, f+ '(' + str(i) + ')'+e)\n if os.path.exists(fn):\n return definefn(dirname, filename, i+1)\n else:\n return fn\n\n ok2go = True\n if cfg['overwrite']:\n fn = os.path.join(dirname, filename + '.xlsx')\n if os.path.exists(fn):\n try:\n os.remove(fn)\n except Exception as e:\n printStr = ('\\nOverwrite of output file failed.' +\n '\\nPossibly the current file is open in Excel.' +\n '\\n' + str(e) + '\\n')\n printStrs.append(printStr)\n ok2go = False\n else:\n fn = definefn(dirname, filename)\n\n if uname != 'unknown':\n username = uname\n elif os.getenv('USERNAME'):\n username = os.getenv('USERNAME') # Works only on MS Windows\n else:\n username = 'unknown'\n\n localtime_now = datetime.now()\n time = localtime_now.strftime(\"%m-%d-%Y %I:%M %p\")\n\n comment1 = 'This workbook created ' + time + ' by ' + username + '. '\n comment2 = 'The drop list was NOT employed for this BOM check. '\n bomfooter = '&LCreated ' + time + ' by ' + username + '&CPage &P of &N'\n if cfg['drop_bool']:\n comment2 = ('The drop list was employed for this BOM check: '\n + 'drop = ' + str(cfg['drop']) + ', exceptions = ' + str(cfg['exceptions']))\n bomfooter = bomfooter + '&Rdrop: yes'\n\n if excelTitle and len(excelTitle) == 1:\n bomheader = '&C&A: ' + excelTitle[0][0] + ', ' + excelTitle[0][1]\n else:\n bomheader = '&C&A'\n\n\n if ok2go:\n try:\n with pd.ExcelWriter(fn) as writer:\n for r in results2export:\n sheetname = r[0]\n df = r[1]\n if not df.empty: #TODO: some test code\n df.to_excel(writer, sheet_name=sheetname)\n try:\n worksheet = writer.sheets[sheetname] # pull worksheet object\n autosize_excel_columns(worksheet, df) #<<<\n worksheet.set_header(bomheader) #<<< see: https://xlsxwriter.readthedocs.io/page_setup.html\n worksheet.set_footer(bomfooter) #<<<\n worksheet.set_landscape() #<<<\n worksheet.fit_to_pages(1, 0) #<<<\n worksheet.hide_gridlines(2) #<<<\n worksheet.write_comment('A1', comment1 + comment2, {'x_scale': 3}) #<<<\n except Exception as e:\n msg = (str(e) + '. (Minor error caused by Colab. Can be ignored.)')\n #print(msg)\n try:\n workbook = writer.book\n workbook.set_properties({'title': 'BOM Check', 'author': username, #<<<\n 'subject': 'Compares a SolidWorks BOM to a SyteLine BOM',\n 'company': 'Dekker Vacuum Technologies, Inc.',\n 'comments': comment1 + comment2})\n except Exception as e:\n msg = (str(e) + '. (Minor error caused by Colab. Can be ignored.)')\n #print(msg)\n writer.save()\n printStr = \"\\nCreated file: \" + fn + '\\n'\n printStrs.append(printStr)\n print(printStr)\n\n if sys.platform[:3] == 'win': # Open bomcheck.xlsx in Excel when on Windows platform\n try:\n os.startfile(os.path.abspath(fn))\n except:\n printStr = '\\nAttempt to open bomcheck.xlsx in Excel failed.\\n'\n printStrs.append(printStr)\n print(printStr)\n except Exception as e:\n printStr = ('\\nOverwrite of output file failed.' +\n '\\nPossibly the current file is open in Excel.' +\n '\\n' + str(e) + '\\n')\n printStrs.append(printStr)\n\n\n# before program begins, create global variables\nset_globals()\n\n# An example of how the factorpool is used: to convert 29mm to inch:\n# 1/(25.4*12) = 0.00328 (inches to feet)\n# 1/12 = .08333, (foot to inches)\n# Then: 29 * factorpool['mm'] / factorpool['in'] = 0.00328 / .08333 = 1.141\n# Only lower case keys are acceptable. No digits allowed in keys (like \"2\" in \"ft2\")\nfactorpool = {'in':1/12, '\"':1/12, 'inch':1/12, chr(8221):1/12,\n 'ft':1.0, \"'\":1.0, 'feet':1.0, 'foot':1.0, chr(8217):1.0,\n 'yrd':3.0, 'yd':3.0, 'yard':3.0,\n 'mm': 1/(25.4*12), 'millimeter':1/(25.4*12),\n 'cm':10/(25.4*12), 'centimeter':10/(25.4*12),\n 'm':1000/(25.4*12), 'meter':1000/(25.4*12), 'mtr':1000/(25.4*12),\n 'sqin':1/144, 'sqi':1/144,\n 'sqft':1, 'sqf':1, 'sqyd':3, 'sqy':3,\n 'sqmm':1/92903.04, 'sqcm':1/929.0304, 'sqm':1/(.09290304),\n 'pint':1/8, 'pt':1/8, 'qt':1/4, 'quart':1/4,\n 'gal':1.0, 'g':1.0, 'gallon':1.0,\n 'ltr':0.2641720524, 'liter':0.2641720524, 'l':0.2641720524}\nareaUMs = set(['sqi', 'sqin','sqf', 'sqft', 'sqyd', 'sqy', 'sqmm', 'sqcm', 'sqm'])\nliquidUMs = set(['pint', 'pt', 'quart', 'qt', 'gallon', 'g', 'gal' 'ltr', 'liter', 'l'])\n\n\nif __name__=='__main__':\n main() # comment out this line for testing -.- . -.-.\n #bomcheck('*') # use for testing\n\n\n\n","sub_path":"bomcheck.py","file_name":"bomcheck.py","file_ext":"py","file_size_in_byte":64884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"155483801","text":"\"\"\"\r\nClass for the Proof of Retrievability according to Shacham and Waters. The variables are\r\nnamed according to the paper.\r\n\"Compact Proofs of Retrievability\"\r\nJ. Cryptology, 26(3):442–83, Jul. 2013.\r\nhttp://cseweb.ucsd.edu/~hovav/papers/sw13.html\r\n\r\nAll the numbers are currently numbers. When stuff in this class\r\nbecomes a bottleneck, a starting point could be to convert all those\r\nnumbers to bytes.\r\n\"\"\"\r\n\r\nfrom koppercoin.crypto.AbstractProofOfRetrievability import AbstractProofOfRetrievability\r\nfrom pypbc import *\r\nfrom Crypto.Random import random as srandom\r\nfrom Crypto.PublicKey import DSA\r\nimport hashlib\r\nimport os\r\nimport random\r\n\r\n\r\ndef hash(message):\r\n \"\"\"computes a hash\"\"\"\r\n return hashlib.sha512(message).digest()\r\n\r\n\r\ndef str_to_bytes(string):\r\n \"\"\"Takes a string and returns a byte-representation\"\"\"\r\n return str.encode(string)\r\n\r\n\r\ndef int_to_bytes(n):\r\n \"\"\"Takes an integer and returns a byte-representation\"\"\"\r\n return n.to_bytes((n.bit_length() + 7) // 8, 'little') or b'\\0'\r\n # http://stackoverflow.com/questions/846038/convert-a-python-int-into-a-big-endian-string-of-bytes\r\n\r\n\r\ndef bytes_to_int(byte):\r\n \"\"\"Takes some Bytes and returns an Integer.\"\"\"\r\n return int.from_bytes(byte, 'little')\r\n\r\n\r\n# The SW-scheme needs a signing algorithm. We will pick DSA for\r\n# this. Since PyCrypto exposes too much stuff, we have implemented a\r\n# wrapper class\r\nclass SignatureScheme:\r\n def keygen(self):\r\n \"\"\"Key generation. Returns a (public, private)-keypair\"\"\"\r\n key = DSA.generate(1024)\r\n return (key.publickey(), key)\r\n\r\n def sign(self, privkey, message):\r\n \"\"\"Signs a message\"\"\"\r\n h = hash(message)\r\n k = srandom.StrongRandom().randint(1, privkey.q-1)\r\n return privkey.sign(h, k)\r\n\r\n def verify(self, pubkey, message, signature):\r\n \"\"\"Verifies a signature\r\n\r\n >>> SigScheme=SignatureScheme()\r\n >>> (pub, priv) = SigScheme.keygen()\r\n >>> message = str.encode(\"abcdef\")\r\n >>> sig = SigScheme.sign(priv, message)\r\n >>> SigScheme.verify(pub, message, sig)\r\n True\r\n \"\"\"\r\n h = hash(message)\r\n return pubkey.verify(h, signature)\r\n\r\n\r\nclass SWProofOfRetrievability(AbstractProofOfRetrievability):\r\n _s = 2\r\n # In the Shacham-Waters scheme the file is split into blocks. Each\r\n # block is s sectors long. Each sector is in Z/pZ.\r\n # The storage overhead of the encoded file is 1+1/s times the filesize\r\n _sectorsize_prime = 730750818665451621361119245571504901405976559617\r\n # _sectorsize_prime is the prime number p\r\n _sectorsize = 20\r\n # since splitting the file in parts of exactly p involves division\r\n # with remainder of big numbers, which is too slow (yes, I had it\r\n # implemented) we split the file in parts of multiple bytes.\r\n # How many bytes should we take? The biggest amount of bytes where the\r\n # numbers which can be represented are smaller than _sectorsize_prime\r\n # this number is _sectorsize\r\n _stored_params = \"\"\"type a\r\n q 8780710799663312522437781984754049815806883199414208211028653399266475630880222957078625179422662221423155858769582317459277713367317481324925129998224791\r\n h 12016012264891146079388821366740534204802954401251311822919615131047207289359704531102844802183906537786776\r\n r 730750818665451621361119245571504901405976559617\r\n exp2 159\r\n exp1 107\r\n sign1 1\r\n sign0 1\r\n \"\"\"\r\n _params = Parameters(param_string=_stored_params)\r\n _pairing = Pairing(_params)\r\n # these parameters are from test_bls from pypbc\r\n\r\n @staticmethod\r\n def keygen():\r\n \"\"\"returns a (public, private)-keypair\r\n\r\n >>> (publick, secretk) = SWProofOfRetrievability.keygen()\r\n \"\"\"\r\n sigscheme = SignatureScheme()\r\n (spk, ssk) = sigscheme.keygen()\r\n # signing public key, signing secret key\r\n alpha = Element.random(SWProofOfRetrievability._pairing, Zr)\r\n sk = (alpha, ssk)\r\n # secret key\r\n generator_G2 = Element.random(SWProofOfRetrievability._pairing, G2)\r\n v = generator_G2**alpha\r\n pk = (generator_G2, v, spk)\r\n return (pk, sk)\r\n\r\n @staticmethod\r\n def _split_data(data):\r\n \"\"\"splits the data in blocks and sectors. The result looks\r\n like this: [[1,..],[2,..],..]. We also apply a padding.\"\"\"\r\n # split the file in sectors\r\n sectorsize = SWProofOfRetrievability._sectorsize\r\n sectors = []\r\n # Each sector consists of sectorsize bytes\r\n for pointerpos in range(0, len(data), sectorsize):\r\n mi = data[pointerpos: pointerpos + sectorsize]\r\n sectors.append(mi)\r\n # Each block has s sectors\r\n s = SWProofOfRetrievability._s\r\n mij = []\r\n for j in range(0, len(sectors), s):\r\n mi = sectors[j: j+s]\r\n mij.append(mi)\r\n # if the last block does not have s elements, then include as\r\n # many ones as needed. Note that one is the multiplicative\r\n # neutral in Z/pZ\r\n # In fact it is not a padding, in the sense that it can be\r\n # inverted. We just fill up the blocks in a well-defined way.\r\n while len(mij[-1]) != SWProofOfRetrievability._s:\r\n mij[-1] = mij[-1] + [int_to_bytes(1)]\r\n return mij\r\n\r\n @staticmethod\r\n def encode(privatekey, publickey, data):\r\n \"\"\"encodes the data into chunks and generates the\r\n authenticators and the filehandle.\r\n\r\n >>> message = \"abcdefghijklmnopqrstuvwxyz\"*5\r\n >>> data = bytes(message, 'utf-8')\r\n >>> (pk, sk) = SWProofOfRetrievability.keygen()\r\n >>> (mij, authenticators, filehandle) = SWProofOfRetrievability.encode(sk, pk, data)\r\n >>> SWProofOfRetrievability.encode(sk, pk, data) # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS\r\n ([[b'abcdefghijklmnopqrst', b'uvwxyzabcdefghijklmn'],\r\n [b'opqrstuvwxyzabcdefgh', b'ijklmnopqrstuvwxyzab'],\r\n [b'cdefghijklmnopqrstuv', b'wxyzabcdefghijklmnop'],\r\n [b'qrstuvwxyz', b'...']],\r\n [[..., ...],\r\n [..., ...],\r\n [..., ...],\r\n [..., ...]],\r\n [[b..., 4,\r\n [[..., ...],\r\n [..., ...]]],\r\n (..., ...)])\r\n \"\"\"\r\n # split the file\r\n mij = SWProofOfRetrievability._split_data(data)\r\n # generate the filehandle\r\n s = SWProofOfRetrievability._s\r\n u = [Element.random(SWProofOfRetrievability._pairing, G1) for i in range(0, s)]\r\n # Filename chosen at random from some sufficiently large domain, compare with paper\r\n filename = os.urandom(32)\r\n t0 = [filename] + [len(mij)] + [u]\r\n (alpha, ssk) = privatekey\r\n sigscheme = SignatureScheme()\r\n t = [t0] + [sigscheme.sign(ssk, str.encode(str(t0)))]\r\n filehandle = t\r\n # filehandle t = [ [filename, #blocks, u1, ..., us], sig]\r\n # generate one authenticator per block\r\n authenticators = []\r\n for i in range(len(mij)):\r\n # compute H(filename|i) * prod_j u_j^mij\r\n prod = Element.one(SWProofOfRetrievability._pairing, G1)\r\n for j in range(s):\r\n prod *= u[j] ** bytes_to_int(mij[i][j])\r\n hashval = Element.from_hash(SWProofOfRetrievability._pairing, G1, hash(filename+str_to_bytes(str(i))))\r\n authenticators.append((hashval * prod) ** alpha)\r\n return (mij, authenticators, filehandle)\r\n\r\n @staticmethod\r\n def genChallenge(nonce):\r\n \"\"\"Generates a challenge.\r\n In the Shacham-Waters scheme one needs to know the filelength\r\n for creating challenges. We are using a nonce and will derive\r\n the set Q={(i,v_i)} from the nonce in the function\r\n _expandChallenge.\"\"\"\r\n return nonce\r\n\r\n @staticmethod\r\n def _expandChallenge(nonce, num_of_blocks):\r\n \"\"\"takes a nonce and generates a challenge Q={(i,v_i)}\r\n according to the SW-paper. See also the documentation for\r\n genChallenge.\"\"\"\r\n random.seed(nonce)\r\n # if this is not generated deterministically we have a huge\r\n # problem\r\n indices = random.sample(range(num_of_blocks), num_of_blocks//2)\r\n indices.sort()\r\n # coefficients are chosen mod p\r\n p = SWProofOfRetrievability._sectorsize_prime\r\n coefficients = [random.randint(1, p-1) for i in indices]\r\n challenge = list(zip(indices, coefficients))\r\n return challenge\r\n\r\n @staticmethod\r\n def genproof(publickey, data, authenticators, challenge, filehandle):\r\n \"\"\"generates a proof of retrievability.\r\n\r\n >>> message = \"abcdefghijklmnopqrstuvwxyz\"*100\r\n >>> data = bytes(message, 'utf-8')\r\n >>> (pk, sk) = SWProofOfRetrievability.keygen()\r\n >>> (mij, authenticators, filehandle) = SWProofOfRetrievability.encode(sk, pk, data)\r\n >>> challenge = os.urandom(32)\r\n >>> (sigma, mu) = SWProofOfRetrievability.genproof(pk, data, authenticators, challenge, filehandle)\r\n \"\"\"\r\n # split the file\r\n mij = SWProofOfRetrievability._split_data(data)\r\n # recover all values\r\n (generator, v, spk) = publickey\r\n [t0, sig] = filehandle\r\n [filename, len_mij, u] = t0\r\n if len(mij) != len_mij:\r\n raise InvalidInputError(\"Stated number of blocks does not match real number of blocks\")\r\n sigscheme = SignatureScheme()\r\n if not sigscheme.verify(spk, str.encode(str(t0)), sig):\r\n raise InvalidInputError(\"Signature contained in filehandle does not verify\")\r\n # generate the challenge set\r\n Q_chal = SWProofOfRetrievability._expandChallenge(challenge, len_mij)\r\n # compute sigma, the aggregated authenticators\r\n sigma = Element.one(SWProofOfRetrievability._pairing, G1)\r\n for (index, coeff) in Q_chal:\r\n sigma *= authenticators[index]**coeff\r\n # compute mu, the list of the aggregated blocks\r\n mu = []\r\n p = SWProofOfRetrievability._sectorsize_prime\r\n for j in range(SWProofOfRetrievability._s):\r\n mu_j = 0\r\n for (index, coeff) in Q_chal:\r\n mu_j = (mu_j + coeff * bytes_to_int(mij[index][j])) % p\r\n mu.append(mu_j)\r\n return (sigma, mu)\r\n\r\n @staticmethod\r\n def verify(proof, publickey, challenge, filehandle):\r\n \"\"\"verifies a proof of retrievability.\r\n\r\n >>> message = \"abcdefghijklmnopqrstuvwxyz\"*100\r\n >>> data = bytes(message, 'utf-8')\r\n >>> (pk, sk) = SWProofOfRetrievability.keygen()\r\n >>> (mij, authenticators, filehandle) = SWProofOfRetrievability.encode(sk, pk, data)\r\n >>> challenge = os.urandom(32)\r\n >>> proof = SWProofOfRetrievability.genproof(pk, data, authenticators, challenge, filehandle)\r\n >>> SWProofOfRetrievability.verify(proof, pk, challenge, filehandle)\r\n True\r\n \"\"\"\r\n # parse all the data\r\n (generator, v, spk) = publickey\r\n [t0, sig] = filehandle\r\n [filename, len_mij, u] = t0\r\n (sigma, mu) = proof\r\n Q_chal = SWProofOfRetrievability._expandChallenge(challenge, len_mij)\r\n sigscheme = SignatureScheme()\r\n # check if signature in filehandle is correct\r\n if not sigscheme.verify(spk, str.encode(str(t0)), sig):\r\n return False\r\n # for verification we need to check if RHS = LHS\r\n # compute LHS = e[ H(filename|i)^coeff * prod_j u_j^muj , v ]\r\n # prodhash = H(filename|i)^coeff\r\n # produ = prod_j u_j^muj\r\n prodhash = Element.one(SWProofOfRetrievability._pairing, G1)\r\n for (i, coeff) in Q_chal:\r\n hashval = Element.from_hash(SWProofOfRetrievability._pairing, G1, hash(filename+str_to_bytes(str(i))))\r\n prodhash *= hashval ** coeff\r\n produ = Element.one(SWProofOfRetrievability._pairing, G1)\r\n for j in range(SWProofOfRetrievability._s):\r\n produ *= u[j] ** mu[j]\r\n pairing = SWProofOfRetrievability._pairing\r\n LHS = pairing.apply(prodhash*produ, v)\r\n # RHS = e(sigma, generator)\r\n RHS = pairing.apply(sigma, generator)\r\n if RHS == LHS:\r\n return True\r\n return False\r\n\r\n\r\nclass InvalidInputError(Exception):\r\n pass\r\n","sub_path":"koppercoin/crypto/SWProofOfRetrievability.py","file_name":"SWProofOfRetrievability.py","file_ext":"py","file_size_in_byte":12308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"327712421","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 26 18:32:28 2018\n\n@author: Figo\n\"\"\"\n\nimport string\nimport numpy as np\n\nsamples = ['The cat sat on the mat.', 'The dog ate my homework.']\ncharacters = string.printable\n# 将可打印字符进行编号\ntoken_index = dict(zip(characters, range(1, len(characters) + 1)))\n\n# 分词只考虑前 50 个字符\nmax_length = 50\nresults = np.zeros((len(samples), max_length, max(token_index.values()) + 1))\nfor i, sample in enumerate(samples):\n for j, character in enumerate(sample[:max_length]):\n index = token_index.get(character)\n results[i, j, index] = 1.","sub_path":"deep_learning_code/deep_learning_2018/6-2Character_level_one-hot_encoding.py","file_name":"6-2Character_level_one-hot_encoding.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"221406649","text":"\"\"\"empty message\n\nRevision ID: df1692a0837\nRevises: 4164f6638019\nCreate Date: 2018-01-31 01:05:16.206689\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = 'df1692a0837'\ndown_revision = '4164f6638019'\n\nfrom alembic import op\nimport sqlalchemy as sa\nimport geoalchemy2\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.add_column('project', sa.Column('completion', sa.SmallInteger(), nullable=False))\n op.add_column('property', sa.Column('completion', sa.SmallInteger(), nullable=False))\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('property', 'completion')\n op.drop_column('project', 'completion')\n ### end Alembic commands ###\n","sub_path":"migrations/versions/df1692a0837_.py","file_name":"df1692a0837_.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"217745836","text":"import json\nimport requests\nimport random\nimport string\nfrom faker import Faker\nfrom json.decoder import JSONDecodeError\nfrom user import User\n\nGET_POSTS_URL = \"http://api:8000/posts\"\n\nclass Bot:\n def __init__(self, config):\n self.__dict__.update(config)\n self.faker = Faker()\n self.old_users = get_users()\n self.new_users = []\n\n\n def write_users(self):\n with open(\"users.json\", \"w\") as file:\n new_users = [user.to_dict() for user in self.new_users]\n old_users = [user.to_dict() for user in self.old_users]\n json.dump(old_users + new_users, file, indent=4)\n\n def generate_user(self):\n rand_chars = get_random_string(3, only_lowercase=True)\n name = self.faker.name()\n email = name.replace(\" \", \"\").lower() + rand_chars + \"@mail.com\"\n password = get_random_string(12)\n return User({\"username\": name, \"email\": email, \"password\": password})\n\n def generate_post(self):\n title = self.faker.sentence()\n content = self.faker.paragraph(random.randint(5, 15))\n return {\"title\": title, \"content\": content}\n\n def _signup_users(self):\n print(\"Sign up users({}): \".format(self.number_of_users), end=\"\")\n for _ in range(self.number_of_users):\n user = self.generate_user()\n result = user.signup()\n if result:\n self.new_users.append(user)\n print(\"+\", end=\"\")\n else:\n print(\"\\nUnable to signup user {}.\".format(user.username), end=\"\")\n print()\n\n def _delete_new_users(self):\n for _ in range(len(self.new_users)):\n user = self.new_users.pop()\n user.delete(silent=False)\n\n def _create_posts(self):\n print(\"Creating posts for every new user: \", end=\"\")\n for user in self.new_users:\n number_of_posts = random.randint(1, self.max_posts_per_user)\n for _ in range(number_of_posts):\n post = self.generate_post()\n result = user.create_post(post)\n if result:\n print(\"+\", end=\"\")\n print()\n\n def get_all_posts(self):\n resp = requests.get(GET_POSTS_URL)\n return resp.json()[\"posts\"] if resp.status_code == 200 else []\n\n def _like_posts(self):\n posts = self.get_all_posts()\n if not posts:\n print(\"No post comes for likes\")\n return False\n print(\"Like posts for every new user: \", end=\"\")\n for user in self.new_users:\n for _ in range(random.randint(1, self.max_likes_per_user)):\n post = random.choice(posts)\n result = user.like_post(post)\n if result:\n print(\"+\", end=\"\")\n print()\n\n\n def create_activity(self):\n self._signup_users()\n self._create_posts()\n self._like_posts()\n\n resp = input(\"Should I delete created users from the service? (y/n):\")\n if resp in [\"Y\", \"y\", \"yes\", \"yes\"]:\n self._delete_new_users()\n else:\n self.write_users()\n\n\ndef get_users():\n with open(\"users.json\", \"r\") as file:\n try:\n users = json.load(file)\n except JSONDecodeError:\n return []\n return [User(user) for user in users]\n\n\ndef get_random_string(length, only_lowercase=False):\n letters = string.ascii_lowercase if only_lowercase else string.ascii_letters\n return \"\".join(random.choice(letters + string.digits) for _ in range(length))\n\n\ndef read_config(path):\n with open(path, \"r\") as file:\n return json.load(file)\n\nif __name__ == \"__main__\":\n config = read_config(\"config.json\")\n bot = Bot(config)\n bot.create_activity()\n","sub_path":"bot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":3744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"642684451","text":"import lxml\r\nimport requests\r\nimport time\r\nimport sys\r\nimport progress_bar as PB\r\nimport json\r\n\r\nYOUTUBE_IN_LINK = 'https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&maxResults=100&order=relevance&pageToken={pageToken}&videoId={videoId}&key={key}'\r\nYOUTUBE_LINK = 'https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&maxResults=100&order=relevance&videoId={videoId}&key={key}'\r\nkey = '' #Change to your Google API\r\n\r\ndef commentExtract(videoId, count = -1,leastlikes=300):\r\n\tprint (\"\\nComments downloading\")\r\n\t#Close the HTTP connection and increase the number of reconnections\r\n\r\n\r\n\r\n\tpage_info = requests.get(YOUTUBE_LINK.format(videoId = videoId, key = key))\r\n\twhile page_info.status_code != 200:\r\n\t\tif page_info.status_code != 429:\r\n\t\t\tprint (\"Comments disabled\")\r\n\t\t\tsys.exit()\r\n\r\n\t\ttime.sleep(20)\r\n\t\tpage_info = requests.get(YOUTUBE_LINK.format(videoId = videoId, key = key))\r\n\r\n\tpage_info = page_info.json()\r\n\t#test\r\n\t# print(page_info)\r\n\r\n\tcomments = []\r\n\tlikes=[]\r\n\tco = 0\r\n\tfor i in range(len(page_info['items'])):\r\n\t\t#The comments above like Leastlike are reserved, which can be changed as needed\r\n\t\tif page_info['items'][i]['snippet']['topLevelComment']['snippet']['likeCount']>=leastlikes:\r\n\t\t\tcomments.append(page_info['items'][i]['snippet']['topLevelComment']['snippet']['textOriginal'])\r\n\t\t\tlikes.append(page_info['items'][i]['snippet']['topLevelComment']['snippet']['likeCount'])\r\n\t\t\tco += 1\r\n\t\tif co == count:\r\n\t\t\tPB.progress(co, count, cond = True)\r\n\t\t\treturn comments,likes\r\n\r\n\tPB.progress(co, count)\r\n\t# INFINTE SCROLLING\r\n\twhile 'nextPageToken' in page_info:\r\n\t\ttemp = page_info\r\n\t\tpage_info = requests.get(YOUTUBE_IN_LINK.format(videoId = videoId, key = key, pageToken = page_info['nextPageToken']))\r\n\r\n\t\twhile page_info.status_code != 200:\r\n\t\t\ttime.sleep(20)\r\n\t\t\tpage_info = requests.get(YOUTUBE_IN_LINK.format(videoId = videoId, key = key, pageToken = temp['nextPageToken']))\r\n\t\tpage_info = page_info.json()\r\n\r\n\t\tfor i in range(len(page_info['items'])):\r\n\t\t\tif page_info['items'][i]['snippet']['topLevelComment']['snippet']['likeCount']>=leastlikes:\r\n\t\t\t\tcomments.append(page_info['items'][i]['snippet']['topLevelComment']['snippet']['textOriginal'])\r\n\t\t\t\tlikes.append(page_info['items'][i]['snippet']['topLevelComment']['snippet']['likeCount'])\r\n\t\t\t\tco += 1\r\n\t\t\tif co == count:\r\n\t\t\t\tPB.progress(co, count, cond = True)\r\n\t\t\t\treturn comments,likes\r\n\t\tPB.progress(co, count)\r\n\tPB.progress(count, count, cond = True)\r\n\tprint ()\r\n\r\n\treturn comments,likes\r\n\r\n","sub_path":"comment_downloader.py","file_name":"comment_downloader.py","file_ext":"py","file_size_in_byte":2511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"246747419","text":"def dep():\n \"\"\"dep.csv와 member.csv를 조인하여 depmember.csv를 만든다. dep-result.csv 참고\"\"\"\n fdep = open(\"dep.csv\")\n fmember = open(\"member.csv\")\n\n # dep dictionary\n header_dep = fdep.readline().strip().split(\",\")\n list_dep = []\n for row in fdep:\n data = row.strip().split(\",\")\n zipped = zip(header_dep, data)\n list_dep.append(dict(zipped))\n\n # member dictionary\n header_member = fmember.readline().strip().split(\",\")\n list_member = []\n for row in fmember:\n data = row.strip().split(\",\")\n zipped = zip(header_member, data)\n list_member.append(dict(zipped))\n\n # result list\n result = []\n result.append([\"DEPNO\", \"DEPNM\", \"EMPNO\", \"EMPNAME\"]) # insert header\n for dep in list_dep:\n depno = dep[\"DEPNO\"]\n depnm = dep[\"DEPNM\"]\n for member in list_member:\n if member[\"DEPNO\"] == depno:\n row = [depno, depnm, member[\"EMPNO\"], member[\"EMPNAME\"]]\n result.append(row)\n\n # write csv file\n fw = open(\"dep-result.csv\", \"w\")\n for line in result:\n fw.write(\",\".join(line)+\"\\n\")\n\n # close file handler\n fdep.close()\n fmember.close()\n fw.close()\n\n\nif __name__ == \"__main__\":\n dep()\n","sub_path":"src/dep.py","file_name":"dep.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"635701606","text":"# coding = utf-8\r\nimport os\r\nimport cv2\r\nimport time\r\nimport pandas as pd\r\n\r\nif __name__ == '__main__':\r\n data_dir = \"data\"\r\n save_path_name = \"image_classification.csv\"\r\n out_dir = \"out\"\r\n if not os.path.exists(out_dir):\r\n os.makedirs(out_dir)\r\n width = 256\r\n height = 256\r\n path_list = []\r\n label_index_list = []\r\n label_name_list = []\r\n time1 = time.time()\r\n file_lists = os.listdir(data_dir)\r\n print(\"file_lists\",file_lists)\r\n for filename in file_lists:\r\n img_dir = data_dir + '/' + filename\r\n img_lists = os.listdir(img_dir)\r\n img_lists = [i for i in img_lists\r\n if (i.startswith(\"Meter\")) and (i.endswith(\".jpg\"))]\r\n print(\"img_lists\", img_lists)\r\n for imgname in img_lists:\r\n if filename == \"Meter1\" :\r\n label_index = 1\r\n label_name = \"meter1\"\r\n elif filename == \"Meter2\" :\r\n label_index = 2\r\n label_name = \"meter2\"\r\n elif filename == \"Meter3\" :\r\n label_index = 3\r\n label_name = \"meter3\"\r\n elif filename == \"Meter4\" :\r\n label_index = 4\r\n label_name = \"meter4\"\r\n path_list.append(\"./\" + str(label_index) + \"/\" + imgname)\r\n label_name_list.append(label_name)\r\n label_index_list.append(label_index)\r\n\r\n ####################读入图像###############################\r\n img_path = img_dir + '/' + imgname\r\n image = cv2.imread(img_path, cv2.IMREAD_COLOR)\r\n res = cv2.resize(image, (width, height), interpolation=cv2.INTER_LINEAR)\r\n ####################写入图像########################\r\n save_img_dir = out_dir + '/' + str(label_index)\r\n if not os.path.exists(save_img_dir):\r\n os.makedirs(save_img_dir)\r\n cv2.imwrite(save_img_dir + '/' + imgname, res)\r\n print(\"%s has been resized!\" % imgname)\r\n\r\n df_dict = {\r\n \"path\": path_list,\r\n \"label_name\": label_name_list,\r\n \"label_index\": label_index_list\r\n }\r\n df = pd.DataFrame(data=df_dict)\r\n df.to_csv(save_path_name, header=False, index=False)\r\n time2=time.time()\r\n print (u'总共耗时:' + str(time2 - time1) + 's')\r\n","sub_path":"0203_图像分类分拣1预处理python/resize_save_path_csv.py","file_name":"resize_save_path_csv.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"141340880","text":"import urllib3, re\nimport pandas as pd\nimport numpy as np\n\n#setting up urllib\nhttp = urllib3.PoolManager()\n\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\ndef gender(name):\n\n #get data from gender prediction API\n genderAPI = \"https://api.bundle.io/v1/nametogender?name=\"+name+\"&api_key=KgXjmD0kETqhUmZJv4zMb1ORs\"\n\n response = http.request('GET', genderAPI)\n\n #get gender field\n array = re.split(':|,|\\n',response.data.decode('utf-8'))\n\n #printing gender\n return array[3].replace(\"\\\"\", '')\n\ndef getListOfNames(df):\n full_names = df['Student name'].tolist()\n\n first_names = {}\n for full_name in full_names:\n if (len(full_name.split(\", \")) > 1):\n first_names[full_name.split(\", \")[1].split()[0]] = 1\n else:\n first_names[full_name] = 1\n return list(first_names)\n\n\n# Loads our stored dictionary with associated genders for names in our dataset.\n# Sometimes this function may crash, this is usually caused by either an Unexpected\n# special character in the name we're passing that doesn't fit in unicode8 OR\n# the API messed up in some way.\n# Just restart and resume from where i left off. Alter the listOfName entries left to process.\ndef load_genders(year):\n\n df = pd.read_csv(year+\".csv\")\n listOfNames = getListOfNames(df)\n print(len(listOfNames))\n\n i = 0\n for name in listOfNames:\n print(str(i)+'\\t'+name)\n genders = np.load('all_genders.npy').item()\n if name not in genders:\n genders[name] = gender(name)\n np.save('all_genders.npy', genders)\n\n i += 1\n\n print(genders)\n","sub_path":"data/gender.py","file_name":"gender.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"373012327","text":"#\n# Config Handler Class\n#\nimport json\nfrom src.ConfigSettings import ConfigSettings\n\n\nclass ConfigHandler:\n \"\"\" Class to handle config files \"\"\"\n\n def __init__(self):\n \"\"\" class constructor \"\"\"\n self.config_contents = {}\n\n def read_config(self, file_path):\n \"\"\" parses config file in json format\"\"\"\n\n config_file = open(file_path)\n self.config_contents = json.load(config_file)\n config_file.close()\n\n return self.config_contents\n\n def create_config_settings(self, file_path):\n \"\"\" returns a ConfigSettings object constructed from config_contents\"\"\"\n self.config_contents = self.read_config(file_path)\n # create empty config file object\n cs = ConfigSettings()\n\n # populate logfile related config settings\n logfile_config = self.config_contents.get('logfile')\n cs.logfile_file_name = logfile_config.get('file_name')\n cs.logfile_date_stamp_file_name = logfile_config.get('date_stamp_file_name')\n cs.logfile_time_stamp_file_name = logfile_config.get('time_stamp_file_name')\n cs.logfile_save_location = logfile_config.get('save_location')\n\n # populate sccs related config settings\n sccs_config = self.config_contents.get('sccs')\n cs.sccs_check_in_message = sccs_config.get('check_in_message')\n\n # populate version history related config settings\n version_config = self.config_contents.get('version_history')\n cs.version_history_clear_history = version_config.get('clear_message')\n cs.version_history_message = version_config.get('clear_history')\n\n # return populated Config Settings file.\n return cs\n","sub_path":"v2_0_0_alpha/src/ConfigHandler.py","file_name":"ConfigHandler.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"450596384","text":"import pandas as pd\nimport numpy as np\n\n\ndef reduce_memory(df):\n \"\"\" iterate through all the columns of a dataframe and modify the data type\n to reduce memory usage.\n \"\"\"\n start_mem = df.memory_usage().sum() / 1024 ** 2\n print('Memory usage of dataframe was {:.2f} MB'.format(start_mem))\n\n for col in df.columns:\n col_type = df[col].dtype\n\n if col_type != object:\n c_min = df[col].min()\n c_max = df[col].max()\n if str(col_type)[:3] == 'int':\n if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n df[col] = df[col].astype(np.int8)\n elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n df[col] = df[col].astype(np.int16)\n elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n df[col] = df[col].astype(np.int32)\n elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n df[col] = df[col].astype(np.int64)\n else:\n if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n df[col] = df[col].astype(np.float16)\n elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n df[col] = df[col].astype(np.float32)\n else:\n df[col] = df[col].astype(np.float64)\n else:\n df[col] = df[col].astype('category')\n\n end_mem = df.memory_usage().sum() / 1024 ** 2\n print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))\n print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))\n\n return df\n\n\ndef df_basic_info(df):\n print(\"Basic summary : \\n\")\n print(\"Features : \",df.shape[1])\n print(\"\\nPCA Features :\", len(df.columns[1:29]),\"--\", df.iloc[:,1:29].dtypes[0])\n print(\"Other Features : Time --\",df.Time.dtype,\"Amount --\",df.Amount.dtype)\n print(\"Labels :\",df.columns[-1], df.Class.unique(),\"--\", df.Class.dtype)\n print(\"\\nRows : \",df.shape[0])\n print(\"\\nClass normal : \", len(df[df.Class == 0]))\n print(\"Fraud : \",len(df[df.Class == 1]))\n print(\"Fraud cases percentage : \",round(len(df[df.Class == 1])/len(df[df.Class == 0])*100,4),\"%\")\n print(\"\\nMissing values : \",df.isnull().sum().sum())\n\n\ndef print_best_corelations(df):\n df_corr = df.corr().unstack().sort_values().drop_duplicates()\n print(\"Top five positive corelation : \\n\")\n print(df_corr.tail().sort_values(ascending=False))\n\n print(\"\\nTop five negative corelation : \\n\")\n print(df_corr.head())\n\n\ndef ecdf(data):\n \"\"\"Compute ECDF for a one-dimensional array of measurements.\"\"\"\n # Number of data points: n\n n = len(data)\n\n # x-data for the ECDF: x\n x = np.sort(data)\n\n # y-data for the ECDF: y\n y = np.arange(1, n+1) / n\n\n return x, y","sub_path":"src/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"195811596","text":"from __future__ import unicode_literals\r\nfrom __future__ import print_function\r\nfrom __future__ import unicode_literals\r\n\r\nimport telnetlib\r\nimport textwrap, re, io, paramiko,hashlib,copy,threading, socket,getopt,os, sys, time\r\nfrom os import path\r\nfrom collections import deque\r\nfrom paramiko.pkey import PKey\r\nfrom paramiko import file\r\n\r\nfrom paramiko.ssh_exception import (\r\n SSHException,\r\n PasswordRequiredException,\r\n BadAuthenticationType,\r\n ChannelException,\r\n BadHostKeyException,\r\n AuthenticationException,\r\n )\r\nfrom paramiko.client import (\r\n SSHClient,\r\n MissingHostKeyPolicy,\r\n AutoAddPolicy,\r\n RejectPolicy,\r\n WarningPolicy,\r\n)\r\n\r\nimport logging\r\n\r\nunicode = str\r\n\r\n# Log\r\nlog = logging.getLogger(__name__) # noqa\r\nlog.addHandler(logging.NullHandler()) # noqa\r\n\r\n# Variables\r\n\r\nSGR = {\r\n 'reset': 0,\r\n 'bold': 1,\r\n 'underline': 4,\r\n 'blink': 5,\r\n 'negative': 7,\r\n 'underline_off': 24,\r\n 'blink_off': 25,\r\n 'positive': 27,\r\n 'black': 30,\r\n 'red': 31,\r\n 'green': 32,\r\n 'yellow': 33,\r\n 'blue': 34,\r\n 'magenta': 35,\r\n 'cyan': 36,\r\n 'white': 37,\r\n 'fg_reset': 39,\r\n 'bg_black': 40,\r\n 'bg_red': 41,\r\n 'bg_green': 42,\r\n 'bg_yellow': 43,\r\n 'bg_blue': 44,\r\n 'bg_magenta': 45,\r\n 'bg_cyan': 46,\r\n 'bg_white': 47,\r\n 'bg_reset': 49,\r\n }\r\n\r\n# Provide a familar descriptive word for some ansi sequences.\r\nFG_COLOR_WORDS = {'black': ['black'],\r\n 'dark_gray': ['bold', 'black'],\r\n 'blue': ['blue'],\r\n 'light_blue': ['bold', 'blue'],\r\n 'green': ['green'],\r\n 'light_green': ['bold', 'green'],\r\n 'cyan': ['cyan'],\r\n 'light_cyan': ['bold', 'cyan'],\r\n 'red': ['red'],\r\n 'light_red': ['bold', 'red'],\r\n 'purple': ['magenta'],\r\n 'light_purple': ['bold', 'magenta'],\r\n 'brown': ['yellow'],\r\n 'yellow': ['bold', 'yellow'],\r\n 'light_gray': ['white'],\r\n 'white': ['bold', 'white']}\r\n\r\nBG_COLOR_WORDS = {'black': ['bg_black'],\r\n 'red': ['bg_red'],\r\n 'green': ['bg_green'],\r\n 'yellow': ['bg_yellow'],\r\n 'dark_blue': ['bg_blue'],\r\n 'purple': ['bg_magenta'],\r\n 'light_blue': ['bg_cyan'],\r\n 'grey': ['bg_white']}\r\n\r\nANSI_START = '\\001'\r\nANSI_END = '\\002'\r\n\r\n\r\nsgr_re = re.compile(r'(%s?\\033\\[\\d+(?:;\\d+)*m%s?)' % (\r\n ANSI_START, ANSI_END))\r\n\r\n\r\nunicode = str\r\nPY2 = sys.version_info.major == 2\r\nPY3 = sys.version_info.major == 3\r\nif PY3:\r\n string_types = (str,)\r\n text_type = str\r\n bufferedio_types = io.BufferedIOBase\r\nelse:\r\n string_types = (str,) # noqa\r\n text_type = unicode # noqa\r\n bufferedio_types = (io.BufferedIOBase, file) # noqa # paramiko\r\n\r\nMAX_BUFFER = 65535\r\nBACKSPACE_CHAR = \"\\x08\"\r\n\r\nLINUX_PROMPT_PRI = os.getenv(\"Net_Connect_LINUX_PROMPT_PRI\", \"$\")\r\nLINUX_PROMPT_ALT = os.getenv(\"Net_Connect_LINUX_PROMPT_ALT\", \"#\")\r\nLINUX_PROMPT_ROOT = os.getenv(\"Net_Connect_LINUX_PROMPT_ROOT\", \"#\")\r\n\r\n\r\n# Network Base Connection\r\nclass BaseConnection(object):\r\n \"\"\"\r\n Defines vendor independent methods.\r\n\r\n Otherwise method left as a stub method.\r\n \"\"\"\r\n def __init__(\r\n self,\r\n ip=\"\",\r\n host=\"\",\r\n username=\"\",\r\n password=None,\r\n secret=\"\",\r\n port=None,\r\n device_type=\"\",\r\n verbose=False,\r\n global_delay_factor=5,\r\n use_keys=False,\r\n key_file=None,\r\n pkey=None,\r\n passphrase=None,\r\n allow_agent=False,\r\n ssh_strict=False,\r\n system_host_keys=False,\r\n alt_host_keys=False,\r\n alt_key_file=\"\",\r\n ssh_config_file=None,\r\n timeout=100,\r\n session_timeout=60,\r\n auth_timeout=None,\r\n blocking_timeout=8,\r\n banner_timeout=5,\r\n keepalive=0,\r\n default_enter=None,\r\n response_return=None,\r\n serial_settings=None,\r\n fast_cli=False,\r\n session_log=None,\r\n session_log_record_writes=False,\r\n session_log_file_mode=\"write\",\r\n allow_auto_change=False,\r\n encoding=\"ascii\",\r\n ):\r\n\r\n self.remote_conn = None\r\n\r\n self.TELNET_RETURN = \"\\r\\n\"\r\n if default_enter is None:\r\n if \"telnet\" not in device_type:\r\n self.RETURN = \"\\n\"\r\n else:\r\n self.RETURN = self.TELNET_RETURN\r\n else:\r\n self.RETURN = default_enter\r\n\r\n # Line Separator in response lines\r\n self.RESPONSE_RETURN = \"\\n\" if response_return is None else response_return\r\n if ip:\r\n self.host = ip.strip()\r\n elif host:\r\n self.host = host.strip()\r\n if port is None:\r\n if \"telnet\" in device_type:\r\n port = 23\r\n else:\r\n port = 22\r\n self.port = int(port)\r\n\r\n self.username = username\r\n self.password = password\r\n self.secret = secret\r\n self.device_type = device_type\r\n self.ansi_escape_codes = False\r\n self.verbose = verbose\r\n self.timeout = timeout\r\n self.auth_timeout = auth_timeout\r\n self.banner_timeout = banner_timeout\r\n self.session_timeout = session_timeout\r\n self.blocking_timeout = blocking_timeout\r\n self.keepalive = keepalive\r\n self.allow_auto_change = allow_auto_change\r\n self.encoding = encoding\r\n\r\n # Net_Connect will close the session_log if we open the file\r\n self.session_log = None\r\n self.session_log_record_writes = session_log_record_writes\r\n self._session_log_close = False\r\n # Ensures last write operations prior to disconnect are recorded.\r\n self._session_log_fin = False\r\n if session_log is not None:\r\n if isinstance(session_log, string_types):\r\n # If session_log is a string, open a file corresponding to string name.\r\n self.open_session_log(filename=session_log, mode=session_log_file_mode)\r\n elif isinstance(session_log, bufferedio_types):\r\n # In-memory buffer or an already open file handle\r\n self.session_log = session_log\r\n else:\r\n raise ValueError(\r\n \"session_log must be a path to a file, a file handle, \"\r\n \"or a BufferedIOBase subclass.\"\r\n )\r\n\r\n self.fast_cli = fast_cli\r\n self.global_delay_factor = global_delay_factor\r\n if self.fast_cli and self.global_delay_factor == 5:\r\n self.global_delay_factor = 0.1\r\n\r\n # set in set_base_prompt method\r\n self.base_prompt = \"\"\r\n self._session_locker = threading.Lock()\r\n\r\n # determine if telnet or SSH\r\n if \"_telnet\" in device_type:\r\n self.protocol = \"telnet\"\r\n self.password = password or \"\"\r\n else:\r\n self.protocol = \"ssh\"\r\n\r\n if not ssh_strict:\r\n self.key_policy = AutoAddPolicy()\r\n else:\r\n self.key_policy = paramiko.RejectPolicy()\r\n\r\n # Options for SSH host_keys\r\n self.use_keys = use_keys\r\n self.key_file = key_file\r\n self.pkey = pkey\r\n self.passphrase = passphrase\r\n self.allow_agent = allow_agent\r\n self.system_host_keys = system_host_keys\r\n self.alt_host_keys = alt_host_keys\r\n self.alt_key_file = alt_key_file\r\n\r\n # For SSH proxy support\r\n self.ssh_config_file = ssh_config_file\r\n\r\n # Establish the remote connection\r\n self._open()\r\n\r\n def _open(self):\r\n \"\"\"Decouple connection creation from __init__ for mocking.\"\"\"\r\n self._modify_connection_params()\r\n self.establish_connection()\r\n self._try_session_preparation()\r\n\r\n def __enter__(self):\r\n \"\"\"Establish a session using a Context Manager.\"\"\"\r\n return self\r\n\r\n def __exit__(self, exc_type, exc_value, traceback):\r\n \"\"\"Gracefully close connection on Context Manager exit.\"\"\"\r\n self.disconnect()\r\n\r\n def _modify_connection_params(self):\r\n \"\"\"Modify connection parameters prior to SSH connection.\"\"\"\r\n pass\r\n\r\n def _timeout_exceeded(self, start, msg=\"Timeout exceeded!\"):\r\n \"\"\"Raise Net_ConnectTimeoutException if waiting too much in the serving queue.\r\n\r\n :param start: Initial start time to see if session lock timeout has been exceeded\r\n :type start: float (from time.time() call i.e. epoch time)\r\n\r\n :param msg: Exception message if timeout was exceeded\r\n :type msg: str\r\n \"\"\"\r\n if not start:\r\n # Must provide a comparison time\r\n return False\r\n if time.time() - start > self.session_timeout:\r\n # session_timeout exceeded\r\n raise Net_ConnectTimeoutException(msg)\r\n return False\r\n\r\n def _lock_Net_Connect_session(self, start=None):\r\n \"\"\"Try to acquire the Net_Connect session lock. If not available, wait in the queue until\r\n the channel is available again.\r\n\r\n :param start: Initial start time to measure the session timeout\r\n :type start: float (from time.time() call i.e. epoch time)\r\n \"\"\"\r\n if not start:\r\n start = time.time()\r\n # Wait here until the SSH channel lock is acquired or until session_timeout exceeded\r\n while not self._session_locker.acquire(False) and not self._timeout_exceeded(\r\n start, \"The Net_Connect channel is not available!\"\r\n ):\r\n time.sleep(0.1)\r\n return True\r\n\r\n def _unlock_Net_Connect_session(self):\r\n \"\"\"\r\n Release the channel at the end of the task.\r\n \"\"\"\r\n if self._session_locker.locked():\r\n self._session_locker.release()\r\n\r\n def _write_channel(self, out_data):\r\n \"\"\"Generic handler that will write to both SSH and telnet channel.\r\n\r\n :param out_data: data to be written to the channel\r\n :type out_data: str (can be either unicode/byte string)\r\n \"\"\"\r\n if self.protocol == \"ssh\":\r\n self.remote_conn.sendall(write_bytes(out_data, encoding=self.encoding))\r\n elif self.protocol == \"telnet\":\r\n self.remote_conn.write(write_bytes(out_data, encoding=self.encoding))\r\n else:\r\n raise ValueError(\"Invalid protocol specified\")\r\n try:\r\n log.debug(\r\n \"write_channel: {}\".format(\r\n write_bytes(out_data, encoding=self.encoding)\r\n )\r\n )\r\n if self._session_log_fin or self.session_log_record_writes:\r\n self._write_session_log(out_data)\r\n except UnicodeDecodeError:\r\n # Don't log non-ASCII characters; this is null characters and telnet IAC (PY2)\r\n pass\r\n\r\n def _write_session_log(self, data):\r\n if self.session_log is not None and len(data) > 0:\r\n # Hide the password and secret in the session_log\r\n if self.password:\r\n data = data.replace(self.password, \"********\")\r\n if self.secret:\r\n data = data.replace(self.secret, \"********\")\r\n self.session_log.write(write_bytes(data, encoding=self.encoding))\r\n self.session_log.flush()\r\n\r\n def write_channel(self, out_data):\r\n \"\"\"Generic handler that will write to both SSH and telnet channel.\r\n\r\n :param out_data: data to be written to the channel\r\n :type out_data: str (can be either unicode/byte string)\r\n \"\"\"\r\n self._lock_Net_Connect_session()\r\n try:\r\n self._write_channel(out_data)\r\n finally:\r\n # Always unlock the SSH channel, even on exception.\r\n self._unlock_Net_Connect_session()\r\n\r\n def is_alive(self):\r\n \"\"\"Returns a boolean flag with the state of the connection.\"\"\"\r\n null = chr(0)\r\n if self.remote_conn is None:\r\n log.error(\"Connection is not initialised, is_alive returns False\")\r\n return False\r\n if self.protocol == \"telnet\":\r\n try:\r\n # Try sending IAC + NOP (IAC is telnet way of sending command)\r\n # IAC = Interpret as Command; it comes before the NOP.\r\n log.debug(\"Sending IAC + NOP\")\r\n # Need to send multiple times to test connection\r\n self.remote_conn.sock.sendall(telnetlib.IAC + telnetlib.NOP)\r\n self.remote_conn.sock.sendall(telnetlib.IAC + telnetlib.NOP)\r\n self.remote_conn.sock.sendall(telnetlib.IAC + telnetlib.NOP)\r\n return True\r\n except AttributeError:\r\n return False\r\n else:\r\n # SSH\r\n try:\r\n # Try sending ASCII null byte to maintain the connection alive\r\n log.debug(\"Sending the NULL byte\")\r\n self.write_channel(null)\r\n return self.remote_conn.transport.is_active()\r\n except (socket.error, EOFError):\r\n log.error(\"Unable to send\", exc_info=True)\r\n # If unable to send, we can tell for sure that the connection is unusable\r\n return False\r\n return False\r\n\r\n def _read_channel(self):\r\n \"\"\"Generic handler that will read all the data from an SSH or telnet channel.\"\"\"\r\n if self.protocol == \"ssh\":\r\n output = \"\"\r\n while True:\r\n if self.remote_conn.recv_ready():\r\n outbuf = self.remote_conn.recv(MAX_BUFFER)\r\n if len(outbuf) == 0:\r\n raise EOFError(\"Channel stream closed by remote device.\")\r\n output += outbuf.decode(\"utf-8\", \"ignore\")\r\n else:\r\n break\r\n elif self.protocol == \"telnet\":\r\n output = self.remote_conn.read_very_eager().decode(\"utf-8\", \"ignore\")\r\n log.debug(\"read_channel: {}\".format(output))\r\n self._write_session_log(output)\r\n return output\r\n\r\n def read_channel(self):\r\n \"\"\"Generic handler that will read all the data from an SSH or telnet channel.\"\"\"\r\n output = \"\"\r\n self._lock_Net_Connect_session()\r\n try:\r\n output = self._read_channel()\r\n finally:\r\n # Always unlock the SSH channel, even on exception.\r\n self._unlock_Net_Connect_session()\r\n return output\r\n\r\n def _read_channel_expect(self, pattern=\"\", re_flags=0, max_loops=500):\r\n output = \"\"\r\n if not pattern:\r\n pattern = re.escape(self.base_prompt)\r\n log.debug(\"Pattern is: {}\".format(pattern))\r\n\r\n i = 1\r\n loop_delay = 0.1\r\n # Default to making loop time be roughly equivalent to self.timeout (support old max_loops\r\n # argument for backwards compatibility).\r\n if max_loops == 500:\r\n max_loops = int(self.timeout / loop_delay)\r\n while i < max_loops:\r\n if self.protocol == \"ssh\":\r\n try:\r\n # If no data available will wait timeout seconds trying to read\r\n self._lock_Net_Connect_session()\r\n new_data = self.remote_conn.recv(MAX_BUFFER)\r\n if len(new_data) == 0:\r\n raise EOFError(\"Channel stream closed by remote device.\")\r\n new_data = new_data.decode(\"utf-8\", \"ignore\")\r\n log.debug(\"_read_channel_expect read_data: {}\".format(new_data))\r\n output += new_data\r\n self._write_session_log(new_data)\r\n except socket.timeout:\r\n raise Net_ConnectTimeoutException(\r\n \"Timed-out reading channel, data not available.\"\r\n )\r\n finally:\r\n self._unlock_Net_Connect_session()\r\n if re.search(pattern, output, flags=re_flags):\r\n log.debug(\"Pattern found: {} {}\".format(pattern, output))\r\n return output\r\n time.sleep(loop_delay * self.global_delay_factor)\r\n i += 1\r\n raise Net_ConnectTimeoutException(\r\n \"Timed-out reading channel, pattern not found in output: {}\".format(pattern)\r\n )\r\n\r\n def _read_channel_timing(self, delay_factor=1, max_loops=500):\r\n # Time to delay in each read loop\r\n loop_delay = 0.1\r\n final_delay = 2\r\n\r\n # Default to making loop time be roughly equivalent to self.timeout (support old max_loops\r\n # and delay_factor arguments for backwards compatibility).\r\n delay_factor = self.select_delay_factor(delay_factor)\r\n if delay_factor == 1 and max_loops == 150:\r\n max_loops = int(self.timeout / loop_delay)\r\n\r\n channel_data = \"\"\r\n i = 0\r\n while i <= max_loops:\r\n time.sleep(loop_delay * delay_factor)\r\n new_data = self.read_channel()\r\n if new_data:\r\n channel_data += new_data\r\n else:\r\n # Safeguard to make sure really done\r\n time.sleep(final_delay * delay_factor)\r\n new_data = self.read_channel()\r\n if not new_data:\r\n break\r\n else:\r\n channel_data += new_data\r\n i += 1\r\n return channel_data\r\n\r\n def read_until_prompt(self, *args, **kwargs):\r\n \"\"\"Read channel until self.base_prompt detected. Return ALL data available.\"\"\"\r\n return self._read_channel_expect(*args, **kwargs)\r\n\r\n def read_until_pattern(self, *args, **kwargs):\r\n \"\"\"Read channel until pattern detected. Return ALL data available.\"\"\"\r\n return self._read_channel_expect(*args, **kwargs)\r\n\r\n def read_until_prompt_or_pattern(self, pattern=\"\", re_flags=0):\r\n combined_pattern = re.escape(self.base_prompt)\r\n if pattern:\r\n combined_pattern = r\"({}|{})\".format(combined_pattern, pattern)\r\n return self._read_channel_expect(combined_pattern, re_flags=re_flags)\r\n\r\n\r\n def telnet_login(\r\n self,\r\n pri_prompt_terminator=r\"#\\s*$\",\r\n alt_prompt_terminator=r\">\\s*$\",\r\n username_pattern=r\"(?:user:|username|login|user name)\",\r\n pwd_pattern=r\"assword\",\r\n delay_factor=1,\r\n max_loops=20,\r\n ):\r\n\r\n delay_factor = self.select_delay_factor(delay_factor)\r\n time.sleep(1 * delay_factor)\r\n\r\n output = \"\"\r\n return_msg = \"\"\r\n i = 1\r\n while i <= max_loops:\r\n try:\r\n output = self.read_channel()\r\n return_msg += output\r\n\r\n # Search for username pattern / send username\r\n if re.search(username_pattern, output, flags=re.I):\r\n self.write_channel(self.username + self.TELNET_RETURN)\r\n time.sleep(1 * delay_factor)\r\n output = self.read_channel()\r\n return_msg += output\r\n\r\n # Search for password pattern / send password\r\n if re.search(pwd_pattern, output, flags=re.I):\r\n self.write_channel(self.password + self.TELNET_RETURN)\r\n time.sleep(0.5 * delay_factor)\r\n output = self.read_channel()\r\n return_msg += output\r\n if re.search(\r\n pri_prompt_terminator, output, flags=re.M\r\n ) or re.search(alt_prompt_terminator, output, flags=re.M):\r\n return return_msg\r\n\r\n # Check if proper data received\r\n if re.search(pri_prompt_terminator, output, flags=re.M) or re.search(\r\n alt_prompt_terminator, output, flags=re.M\r\n ):\r\n return return_msg\r\n\r\n self.write_channel(self.TELNET_RETURN)\r\n time.sleep(0.5 * delay_factor)\r\n i += 1\r\n except EOFError:\r\n self.remote_conn.close()\r\n msg = \"Login failed: {}\".format(self.host)\r\n raise Net_ConnectAuthenticationException(msg)\r\n\r\n # Last try to see if we already logged in\r\n self.write_channel(self.TELNET_RETURN)\r\n time.sleep(0.5 * delay_factor)\r\n output = self.read_channel()\r\n return_msg += output\r\n if re.search(pri_prompt_terminator, output, flags=re.M) or re.search(\r\n alt_prompt_terminator, output, flags=re.M\r\n ):\r\n return return_msg\r\n\r\n msg = \"Login failed: {}\".format(self.host)\r\n self.remote_conn.close()\r\n raise Net_ConnectAuthenticationException(msg)\r\n\r\n def _try_session_preparation(self):\r\n try:\r\n self.session_preparation()\r\n except Exception:\r\n self.disconnect()\r\n raise\r\n\r\n def session_preparation(self):\r\n self._test_channel_read()\r\n self.set_base_prompt()\r\n self.disable_paging()\r\n self.set_terminal_width()\r\n\r\n # Clear the read buffer\r\n time.sleep(0.3 * self.global_delay_factor)\r\n self.clear_buffer()\r\n\r\n def _use_ssh_config(self, dict_arg):\r\n connect_dict = dict_arg.copy()\r\n\r\n # Use SSHConfig to generate source content.\r\n full_path = path.abspath(path.expanduser(self.ssh_config_file))\r\n if path.exists(full_path):\r\n ssh_config_instance = paramiko.SSHConfig()\r\n with io.open(full_path, \"rt\", encoding=\"utf-8\") as f:\r\n ssh_config_instance.parse(f)\r\n source = ssh_config_instance.lookup(self.host)\r\n else:\r\n source = {}\r\n\r\n # Keys get normalized to lower-case\r\n if \"proxycommand\" in source:\r\n proxy = paramiko.ProxyCommand(source[\"proxycommand\"])\r\n elif \"proxyjump\" in source:\r\n hops = list(reversed(source[\"proxyjump\"].split(\",\")))\r\n if len(hops) > 1:\r\n raise ValueError(\r\n \"ProxyJump with more than one proxy server is not supported.\"\r\n )\r\n port = source.get(\"port\", self.port)\r\n host = source.get(\"hostname\", self.host)\r\n # -F {full_path} forces the continued use of the same SSH config file\r\n cmd = \"ssh -F {} -W {}:{} {}\".format(full_path, host, port, hops[0])\r\n proxy = paramiko.ProxyCommand(cmd)\r\n else:\r\n proxy = None\r\n\r\n # Only update 'hostname', 'sock', 'port', and 'username'\r\n # For 'port' and 'username' only update if using object defaults\r\n if connect_dict[\"port\"] == 22:\r\n connect_dict[\"port\"] = int(source.get(\"port\", self.port))\r\n if connect_dict[\"username\"] == \"\":\r\n connect_dict[\"username\"] = source.get(\"user\", self.username)\r\n if proxy:\r\n connect_dict[\"sock\"] = proxy\r\n connect_dict[\"hostname\"] = source.get(\"hostname\", self.host)\r\n\r\n return connect_dict\r\n\r\n def _connect_params_dict(self):\r\n \"\"\"Generate dictionary of Paramiko connection parameters.\"\"\"\r\n conn_dict = {\r\n \"hostname\": self.host,\r\n \"port\": self.port,\r\n \"username\": self.username,\r\n \"password\": self.password,\r\n \"look_for_keys\": self.use_keys,\r\n \"allow_agent\": self.allow_agent,\r\n \"key_filename\": self.key_file,\r\n \"pkey\": self.pkey,\r\n \"passphrase\": self.passphrase,\r\n \"timeout\": self.timeout,\r\n \"auth_timeout\": self.auth_timeout,\r\n \"banner_timeout\": self.banner_timeout,\r\n }\r\n\r\n # Check if using SSH 'config' file mainly for SSH proxy support\r\n if self.ssh_config_file:\r\n conn_dict = self._use_ssh_config(conn_dict)\r\n return conn_dict\r\n\r\n def _sanitize_output(\r\n self, output, strip_command=False, command_string=None, strip_prompt=False\r\n ):\r\n\r\n if self.ansi_escape_codes:\r\n output = self.strip_ansi_escape_codes(output)\r\n output = self.normalize_linefeeds(output)\r\n if strip_command and command_string:\r\n command_string = self.normalize_linefeeds(command_string)\r\n output = self.strip_command(command_string, output)\r\n if strip_prompt:\r\n output = self.strip_prompt(output)\r\n return output\r\n\r\n def establish_connection(self, width=None, height=None):\r\n\r\n if self.protocol == \"telnet\":\r\n self.remote_conn = telnetlib.Telnet(\r\n self.host, port=self.port, timeout=self.timeout\r\n )\r\n self.telnet_login()\r\n elif self.protocol == \"ssh\":\r\n ssh_connect_params = self._connect_params_dict()\r\n self.remote_conn_pre = self._build_ssh_client()\r\n\r\n # initiate SSH connection\r\n try:\r\n self.remote_conn_pre.connect(**ssh_connect_params)\r\n except socket.error:\r\n self.paramiko_cleanup()\r\n msg = \"Connection to device timed-out: {device_type} {ip}:{port}\".format(\r\n device_type=self.device_type, ip=self.host, port=self.port\r\n )\r\n raise Net_ConnectTimeoutException(msg)\r\n except paramiko.ssh_exception.AuthenticationException as auth_err:\r\n self.paramiko_cleanup()\r\n msg = \"Authentication failure: unable to connect {device_type} {ip}:{port}\".format(\r\n device_type=self.device_type, ip=self.host, port=self.port\r\n )\r\n msg += self.RETURN + text_type(auth_err)\r\n raise Net_ConnectAuthenticationException(msg)\r\n\r\n if self.verbose:\r\n print(\r\n \"SSH connection established to {}:{}\".format(self.host, self.port)\r\n )\r\n\r\n # Use invoke_shell to establish an 'interactive session'\r\n if width and height:\r\n self.remote_conn = self.remote_conn_pre.invoke_shell(\r\n term=\"vt100\", width=width, height=height\r\n )\r\n else:\r\n self.remote_conn = self.remote_conn_pre.invoke_shell()\r\n\r\n self.remote_conn.settimeout(self.blocking_timeout)\r\n if self.keepalive:\r\n self.remote_conn.transport.set_keepalive(self.keepalive)\r\n self.special_login_handler()\r\n if self.verbose:\r\n print(\"Interactive SSH session established\")\r\n return \"\"\r\n\r\n def _test_channel_read(self, count=40, pattern=\"\"):\r\n\r\n def _increment_delay(main_delay, increment=1.1, maximum=8):\r\n \"\"\"Increment sleep time to a maximum value.\"\"\"\r\n main_delay = main_delay * increment\r\n if main_delay >= maximum:\r\n main_delay = maximum\r\n return main_delay\r\n\r\n i = 0\r\n delay_factor = self.select_delay_factor(delay_factor=0)\r\n main_delay = delay_factor * 0.1\r\n time.sleep(main_delay * 10)\r\n new_data = \"\"\r\n while i <= count:\r\n new_data += self._read_channel_timing()\r\n if new_data and pattern:\r\n if re.search(pattern, new_data):\r\n break\r\n elif new_data:\r\n break\r\n else:\r\n self.write_channel(self.RETURN)\r\n main_delay = _increment_delay(main_delay)\r\n time.sleep(main_delay)\r\n i += 1\r\n\r\n # check if data was ever present\r\n if new_data:\r\n return new_data\r\n else:\r\n raise Net_ConnectTimeoutException(\"Timed out waiting for data\")\r\n\r\n def _build_ssh_client(self):\r\n \"\"\"Prepare for Paramiko SSH connection.\"\"\"\r\n # Create instance of SSHClient object\r\n remote_conn_pre = paramiko.SSHClient()\r\n\r\n # Load host_keys for better SSH security\r\n if self.system_host_keys:\r\n remote_conn_pre.load_system_host_keys()\r\n if self.alt_host_keys and path.isfile(self.alt_key_file):\r\n remote_conn_pre.load_host_keys(self.alt_key_file)\r\n\r\n # Default is to automatically add untrusted hosts (make sure appropriate for your env)\r\n remote_conn_pre.set_missing_host_key_policy(self.key_policy)\r\n return remote_conn_pre\r\n\r\n def select_delay_factor(self, delay_factor):\r\n if self.fast_cli:\r\n if delay_factor <= self.global_delay_factor:\r\n return delay_factor\r\n else:\r\n return self.global_delay_factor\r\n else:\r\n if delay_factor >= self.global_delay_factor:\r\n return delay_factor\r\n else:\r\n return self.global_delay_factor\r\n\r\n def special_login_handler(self, delay_factor=5):\r\n \"\"\"Handler for devices like WLC, Extreme ERS that throw up characters prior to login.\"\"\"\r\n pass\r\n\r\n def disable_paging(self, command=\"terminal length 0\", delay_factor=5):\r\n\r\n delay_factor = self.select_delay_factor(delay_factor)\r\n time.sleep(delay_factor * 0.1)\r\n self.clear_buffer()\r\n command = self.normalize_cmd(command)\r\n log.debug(\"In disable_paging\")\r\n log.debug(\"Command: {0}\".format(command))\r\n self.write_channel(command)\r\n output = self.read_until_prompt()\r\n if self.ansi_escape_codes:\r\n output = self.strip_ansi_escape_codes(output)\r\n log.debug(\"{0}\".format(output))\r\n log.debug(\"Exiting disable_paging\")\r\n return output\r\n\r\n def set_terminal_width(self, command=\"\", delay_factor=5):\r\n if not command:\r\n return \"\"\r\n delay_factor = self.select_delay_factor(delay_factor)\r\n command = self.normalize_cmd(command)\r\n self.write_channel(command)\r\n output = self.read_until_prompt()\r\n if self.ansi_escape_codes:\r\n output = self.strip_ansi_escape_codes(output)\r\n return output\r\n\r\n def set_base_prompt(\r\n self, pri_prompt_terminator=\"#\", alt_prompt_terminator=\">\", delay_factor=5\r\n ):\r\n\r\n prompt = self.find_prompt(delay_factor=delay_factor)\r\n if not prompt[-1] in (pri_prompt_terminator, alt_prompt_terminator):\r\n raise ValueError(\"Router prompt not found: {0}\".format(repr(prompt)))\r\n # Strip off trailing terminator\r\n self.base_prompt = prompt[:-1]\r\n return self.base_prompt\r\n\r\n def find_prompt(self, delay_factor=5):\r\n delay_factor = self.select_delay_factor(delay_factor)\r\n self.clear_buffer()\r\n self.write_channel(self.RETURN)\r\n time.sleep(delay_factor * 0.1)\r\n\r\n # Initial attempt to get prompt\r\n prompt = self.read_channel()\r\n if self.ansi_escape_codes:\r\n prompt = self.strip_ansi_escape_codes(prompt)\r\n\r\n # Check if the only thing you received was a newline\r\n count = 0\r\n prompt = prompt.strip()\r\n while count <= 10 and not prompt:\r\n prompt = self.read_channel().strip()\r\n if prompt:\r\n if self.ansi_escape_codes:\r\n prompt = self.strip_ansi_escape_codes(prompt).strip()\r\n else:\r\n self.write_channel(self.RETURN)\r\n time.sleep(delay_factor * 0.1)\r\n count += 1\r\n\r\n # If multiple lines in the output take the last line\r\n prompt = self.normalize_linefeeds(prompt)\r\n prompt = prompt.split(self.RESPONSE_RETURN)[-1]\r\n prompt = prompt.strip()\r\n if not prompt:\r\n raise ValueError(\"Unable to find prompt: {}\".format(prompt))\r\n time.sleep(delay_factor * 0.1)\r\n self.clear_buffer()\r\n return prompt\r\n\r\n def clear_buffer(self):\r\n \"\"\"Read any data available in the channel.\"\"\"\r\n self.read_channel()\r\n\r\n def send_command_timing(\r\n self,\r\n command_string,\r\n delay_factor=5,\r\n max_loops=150,\r\n strip_prompt=True,\r\n strip_command=True,\r\n normalize=True,\r\n use_textfsm=False,\r\n use_genie=False,\r\n ):\r\n\r\n output = \"\"\r\n delay_factor = self.select_delay_factor(delay_factor)\r\n self.clear_buffer()\r\n if normalize:\r\n command_string = self.normalize_cmd(command_string)\r\n\r\n self.write_channel(command_string)\r\n output = self._read_channel_timing(\r\n delay_factor=delay_factor, max_loops=max_loops\r\n )\r\n output = self._sanitize_output(\r\n output,\r\n strip_command=strip_command,\r\n command_string=command_string,\r\n strip_prompt=strip_prompt,\r\n )\r\n # If both TextFSM and Genie are set, try TextFSM then Genie\r\n for parser_flag, parser_func in (\r\n (use_textfsm, get_structured_data),\r\n (use_genie, get_structured_data_genie),\r\n ):\r\n if parser_flag:\r\n structured_output = parser_func(\r\n output, platform=self.device_type, command=command_string.strip()\r\n )\r\n # If we have structured data; return it.\r\n if not isinstance(structured_output, string_types):\r\n return structured_output\r\n return output\r\n\r\n def strip_prompt(self, a_string):\r\n\r\n response_list = a_string.split(self.RESPONSE_RETURN)\r\n last_line = response_list[-1]\r\n if self.base_prompt in last_line:\r\n return self.RESPONSE_RETURN.join(response_list[:-1])\r\n else:\r\n return a_string\r\n\r\n def _first_line_handler(self, data, search_pattern):\r\n\r\n try:\r\n # First line is the echo line containing the command. In certain situations\r\n # it gets repainted and needs filtered\r\n lines = data.split(self.RETURN)\r\n first_line = lines[0]\r\n if BACKSPACE_CHAR in first_line:\r\n pattern = search_pattern + r\".*$\"\r\n first_line = re.sub(pattern, repl=\"\", string=first_line)\r\n lines[0] = first_line\r\n data = self.RETURN.join(lines)\r\n return (data, True)\r\n except IndexError:\r\n return (data, False)\r\n\r\n def send_command(\r\n self,\r\n command_string,\r\n expect_string=None,\r\n delay_factor=5,\r\n max_loops=500,\r\n auto_find_prompt=True,\r\n strip_prompt=True,\r\n strip_command=True,\r\n normalize=True,\r\n use_textfsm=False,\r\n use_genie=False,\r\n ):\r\n\r\n # Time to delay in each read loop\r\n loop_delay = 0.2\r\n\r\n # Default to making loop time be roughly equivalent to self.timeout (support old max_loops\r\n # and delay_factor arguments for backwards compatibility).\r\n delay_factor = self.select_delay_factor(delay_factor)\r\n if delay_factor == 1 and max_loops == 500:\r\n # Default arguments are being used; use self.timeout instead\r\n max_loops = int(self.timeout / loop_delay)\r\n\r\n # Find the current router prompt\r\n if expect_string is None:\r\n if auto_find_prompt:\r\n try:\r\n prompt = self.find_prompt(delay_factor=delay_factor)\r\n except ValueError:\r\n prompt = self.base_prompt\r\n else:\r\n prompt = self.base_prompt\r\n search_pattern = re.escape(prompt.strip())\r\n else:\r\n search_pattern = expect_string\r\n\r\n if normalize:\r\n command_string = self.normalize_cmd(command_string)\r\n\r\n time.sleep(delay_factor * loop_delay)\r\n self.clear_buffer()\r\n self.write_channel(command_string)\r\n\r\n i = 1\r\n output = \"\"\r\n past_three_reads = deque(maxlen=3)\r\n first_line_processed = False\r\n\r\n # Keep reading data until search_pattern is found or until max_loops is reached.\r\n while i <= max_loops:\r\n new_data = self.read_channel()\r\n if new_data:\r\n if self.ansi_escape_codes:\r\n new_data = self.strip_ansi_escape_codes(new_data)\r\n\r\n output += new_data\r\n past_three_reads.append(new_data)\r\n\r\n # Case where we haven't processed the first_line yet (there is a potential issue\r\n # in the first line (in cases where the line is repainted).\r\n if not first_line_processed:\r\n output, first_line_processed = self._first_line_handler(\r\n output, search_pattern\r\n )\r\n # Check if we have already found our pattern\r\n if re.search(search_pattern, output):\r\n break\r\n\r\n else:\r\n # Check if pattern is in the past three reads\r\n if re.search(search_pattern, \"\".join(past_three_reads)):\r\n break\r\n\r\n time.sleep(delay_factor * loop_delay)\r\n i += 1\r\n else: # nobreak\r\n raise IOError(\r\n \"Search pattern never detected in send_command_expect: {}\".format(\r\n search_pattern\r\n )\r\n )\r\n\r\n output = self._sanitize_output(\r\n output,\r\n strip_command=strip_command,\r\n command_string=command_string,\r\n strip_prompt=strip_prompt,\r\n )\r\n\r\n # If both TextFSM and Genie are set, try TextFSM then Genie\r\n for parser_flag, parser_func in (\r\n (use_textfsm, get_structured_data),\r\n (use_genie, get_structured_data_genie),\r\n ):\r\n if parser_flag:\r\n structured_output = parser_func(\r\n output, platform=self.device_type, command=command_string.strip()\r\n )\r\n # If we have structured data; return it.\r\n if not isinstance(structured_output, string_types):\r\n return structured_output\r\n return output\r\n\r\n def send_command_expect(self, *args, **kwargs):\r\n\r\n return self.send_command(*args, **kwargs)\r\n\r\n @staticmethod\r\n def strip_backspaces(output):\r\n backspace_char = \"\\x08\"\r\n return output.replace(backspace_char, \"\")\r\n\r\n def strip_command(self, command_string, output):\r\n backspace_char = \"\\x08\"\r\n\r\n # Check for line wrap (remove backspaces)\r\n if backspace_char in output:\r\n output = output.replace(backspace_char, \"\")\r\n output_lines = output.split(self.RESPONSE_RETURN)\r\n new_output = output_lines[1:]\r\n return self.RESPONSE_RETURN.join(new_output)\r\n else:\r\n command_length = len(command_string)\r\n return output[command_length:]\r\n\r\n def normalize_linefeeds(self, a_string):\r\n newline = re.compile(\"(\\r\\r\\r\\n|\\r\\r\\n|\\r\\n|\\n\\r)\")\r\n a_string = newline.sub(self.RESPONSE_RETURN, a_string)\r\n if self.RESPONSE_RETURN == \"\\n\":\r\n # Convert any remaining \\r to \\n\r\n return re.sub(\"\\r\", self.RESPONSE_RETURN, a_string)\r\n else:\r\n return a_string\r\n\r\n def normalize_cmd(self, command):\r\n command = command.rstrip()\r\n command += self.RETURN\r\n return command\r\n\r\n def check_enable_mode(self, check_string=\"\"):\r\n self.write_channel(self.RETURN)\r\n output = self.read_until_prompt()\r\n return check_string in output\r\n\r\n def enable(self, cmd=\"\", pattern=\"ssword\", re_flags=re.IGNORECASE):\r\n output = \"\"\r\n msg = (\r\n \"Failed to enter enable mode. Please ensure you pass \"\r\n \"the 'secret' argument to ConnectHandler.\"\r\n )\r\n if not self.check_enable_mode():\r\n self.write_channel(self.normalize_cmd(cmd))\r\n try:\r\n output += self.read_until_prompt_or_pattern(\r\n pattern=pattern, re_flags=re_flags\r\n )\r\n self.write_channel(self.normalize_cmd(self.secret))\r\n output += self.read_until_prompt()\r\n except Net_ConnectTimeoutException:\r\n raise ValueError(msg)\r\n if not self.check_enable_mode():\r\n raise ValueError(msg)\r\n return output\r\n\r\n def exit_enable_mode(self, exit_command=\"\"):\r\n output = \"\"\r\n if self.check_enable_mode():\r\n self.write_channel(self.normalize_cmd(exit_command))\r\n output += self.read_until_prompt()\r\n if self.check_enable_mode():\r\n raise ValueError(\"Failed to exit enable mode.\")\r\n return output\r\n\r\n def check_config_mode(self, check_string=\"\", pattern=\"\"):\r\n self.write_channel(self.RETURN)\r\n # You can encounter an issue here (on router name changes) prefer delay-based solution\r\n if not pattern:\r\n output = self._read_channel_timing()\r\n else:\r\n output = self.read_until_pattern(pattern=pattern)\r\n return check_string in output\r\n\r\n def config_mode(self, config_command=\"\", pattern=\"\"):\r\n output = \"\"\r\n if not self.check_config_mode():\r\n self.write_channel(self.normalize_cmd(config_command))\r\n output = self.read_until_pattern(pattern=pattern)\r\n if not self.check_config_mode():\r\n raise ValueError(\"Failed to enter configuration mode.\")\r\n return output\r\n\r\n def exit_config_mode(self, exit_config=\"\", pattern=\"\"):\r\n output = \"\"\r\n if self.check_config_mode():\r\n self.write_channel(self.normalize_cmd(exit_config))\r\n output = self.read_until_pattern(pattern=pattern)\r\n if self.check_config_mode():\r\n raise ValueError(\"Failed to exit configuration mode\")\r\n log.debug(\"exit_config_mode: {}\".format(output))\r\n return output\r\n\r\n def send_config_from_file(self, config_file=None, **kwargs):\r\n with io.open(config_file, \"rt\", encoding=\"utf-8\") as cfg_file:\r\n return self.send_config_set(cfg_file, **kwargs)\r\n\r\n def send_config_set(\r\n self,\r\n config_commands=None,\r\n exit_config_mode=True,\r\n delay_factor=1,\r\n max_loops=150,\r\n strip_prompt=False,\r\n strip_command=False,\r\n config_mode_command=None,\r\n ):\r\n\r\n delay_factor = self.select_delay_factor(delay_factor)\r\n if config_commands is None:\r\n return \"\"\r\n elif isinstance(config_commands, string_types):\r\n config_commands = (config_commands,)\r\n\r\n if not hasattr(config_commands, \"__iter__\"):\r\n raise ValueError(\"Invalid argument passed into send_config_set\")\r\n\r\n # Send config commands\r\n cfg_mode_args = (config_mode_command,) if config_mode_command else tuple()\r\n output = self.config_mode(*cfg_mode_args)\r\n for cmd in config_commands:\r\n self.write_channel(self.normalize_cmd(cmd))\r\n if self.fast_cli:\r\n pass\r\n else:\r\n time.sleep(delay_factor * 0.05)\r\n\r\n # Gather output\r\n output += self._read_channel_timing(\r\n delay_factor=delay_factor, max_loops=max_loops\r\n )\r\n if exit_config_mode:\r\n output += self.exit_config_mode()\r\n output = self._sanitize_output(output)\r\n log.debug(\"{}\".format(output))\r\n return output\r\n\r\n def strip_ansi_escape_codes(self, string_buffer):\r\n log.debug(\"In strip_ansi_escape_codes\")\r\n log.debug(\"repr = {}\".format(repr(string_buffer)))\r\n\r\n code_position_cursor = chr(27) + r\"\\[\\d+;\\d+H\"\r\n code_show_cursor = chr(27) + r\"\\[\\?25h\"\r\n code_next_line = chr(27) + r\"E\"\r\n code_erase_line_end = chr(27) + r\"\\[K\"\r\n code_erase_line = chr(27) + r\"\\[2K\"\r\n code_erase_start_line = chr(27) + r\"\\[K\"\r\n code_enable_scroll = chr(27) + r\"\\[\\d+;\\d+r\"\r\n code_form_feed = chr(27) + r\"\\[1L\"\r\n code_carriage_return = chr(27) + r\"\\[1M\"\r\n code_disable_line_wrapping = chr(27) + r\"\\[\\?7l\"\r\n code_reset_mode_screen_options = chr(27) + r\"\\[\\?\\d+l\"\r\n code_reset_graphics_mode = chr(27) + r\"\\[00m\"\r\n code_erase_display = chr(27) + r\"\\[2J\"\r\n code_graphics_mode = chr(27) + r\"\\[\\d\\d;\\d\\dm\"\r\n code_graphics_mode2 = chr(27) + r\"\\[\\d\\d;\\d\\d;\\d\\dm\"\r\n code_graphics_mode3 = chr(27) + r\"\\[(3|4)\\dm\"\r\n code_graphics_mode4 = chr(27) + r\"\\[(9|10)[0-7]m\"\r\n code_get_cursor_position = chr(27) + r\"\\[6n\"\r\n code_cursor_position = chr(27) + r\"\\[m\"\r\n code_erase_display = chr(27) + r\"\\[J\"\r\n code_attrs_off = chr(27) + r\"\\[0m\"\r\n code_reverse = chr(27) + r\"\\[7m\"\r\n\r\n code_set = [\r\n code_position_cursor,\r\n code_show_cursor,\r\n code_erase_line,\r\n code_enable_scroll,\r\n code_erase_start_line,\r\n code_form_feed,\r\n code_carriage_return,\r\n code_disable_line_wrapping,\r\n code_erase_line_end,\r\n code_reset_mode_screen_options,\r\n code_reset_graphics_mode,\r\n code_erase_display,\r\n code_graphics_mode,\r\n code_graphics_mode2,\r\n code_graphics_mode3,\r\n code_graphics_mode4,\r\n code_get_cursor_position,\r\n code_cursor_position,\r\n code_erase_display,\r\n code_attrs_off,\r\n code_reverse,\r\n ]\r\n\r\n output = string_buffer\r\n for ansi_esc_code in code_set:\r\n output = re.sub(ansi_esc_code, \"\", output)\r\n\r\n # CODE_NEXT_LINE must substitute with return\r\n output = re.sub(code_next_line, self.RETURN, output)\r\n\r\n log.debug(\"new_output = {0}\".format(output))\r\n log.debug(\"repr = {0}\".format(repr(output)))\r\n\r\n return output\r\n\r\n def cleanup(self):\r\n \"\"\"Any needed cleanup before closing connection.\"\"\"\r\n pass\r\n\r\n def paramiko_cleanup(self):\r\n \"\"\"Cleanup Paramiko to try to gracefully handle SSH session ending.\"\"\"\r\n self.remote_conn_pre.close()\r\n del self.remote_conn_pre\r\n\r\n def disconnect(self):\r\n \"\"\"Try to gracefully close the SSH connection.\"\"\"\r\n try:\r\n self.cleanup()\r\n if self.protocol == \"ssh\":\r\n self.paramiko_cleanup()\r\n elif self.protocol == \"telnet\":\r\n self.remote_conn.close()\r\n except Exception:\r\n # There have been race conditions observed on disconnect.\r\n pass\r\n finally:\r\n self.remote_conn_pre = None\r\n self.remote_conn = None\r\n self.close_session_log()\r\n\r\n def commit(self):\r\n \"\"\"Commit method for platforms that support this.\"\"\"\r\n raise AttributeError(\"Network device does not support 'commit()' method\")\r\n\r\n def save_config(self, *args, **kwargs):\r\n \"\"\"Not Implemented\"\"\"\r\n raise NotImplementedError\r\n\r\n def open_session_log(self, filename, mode=\"write\"):\r\n \"\"\"Open the session_log file.\"\"\"\r\n if mode == \"append\":\r\n self.session_log = open(filename, mode=\"ab\")\r\n else:\r\n self.session_log = open(filename, mode=\"wb\")\r\n self._session_log_close = True\r\n\r\n def close_session_log(self):\r\n \"\"\"Close the session_log file (if it is a file that we opened).\"\"\"\r\n if self.session_log is not None and self._session_log_close:\r\n self.session_log.close()\r\n self.session_log = None\r\n\r\nclass TerminalServer(BaseConnection):\r\n \"\"\"Generic Terminal Server driver.\r\n\r\n Allow direct write_channel / read_channel operations without session_preparation causing\r\n an exception.\r\n \"\"\"\r\n\r\n def session_preparation(self):\r\n \"\"\"Do nothing here; base_prompt is not set; paging is not disabled.\"\"\"\r\n pass\r\n\r\nclass TerminalServerSSH(TerminalServer):\r\n \"\"\"Generic Terminal Server driver SSH.\"\"\"\r\n pass\r\n\r\nclass BaseFileTransfer(object):\r\n \"\"\"Class to manage SCP file transfer and associated SSH control channel.\"\"\"\r\n def __init__(\r\n self, ssh_conn, source_file, dest_file, file_system=None, direction=\"put\"\r\n ):\r\n self.ssh_ctl_chan = ssh_conn\r\n self.source_file = source_file\r\n self.dest_file = dest_file\r\n self.direction = direction\r\n\r\n auto_flag = (\r\n \"cisco_ios\" in ssh_conn.device_type\r\n or \"cisco_xe\" in ssh_conn.device_type\r\n or \"cisco_xr\" in ssh_conn.device_type\r\n )\r\n if not file_system:\r\n if auto_flag:\r\n self.file_system = self.ssh_ctl_chan._autodetect_fs()\r\n else:\r\n raise ValueError(\"Destination file system not specified\")\r\n else:\r\n self.file_system = file_system\r\n\r\n if direction == \"put\":\r\n self.source_md5 = self.file_md5(source_file)\r\n self.file_size = os.stat(source_file).st_size\r\n elif direction == \"get\":\r\n self.source_md5 = self.remote_md5(remote_file=source_file)\r\n self.file_size = self.remote_file_size(remote_file=source_file)\r\n else:\r\n raise ValueError(\"Invalid direction specified\")\r\n\r\n def __enter__(self):\r\n \"\"\"Context manager setup\"\"\"\r\n self.establish_scp_conn()\r\n return self\r\n\r\n def __exit__(self, exc_type, exc_value, traceback):\r\n \"\"\"Context manager cleanup.\"\"\"\r\n self.close_scp_chan()\r\n\r\n def establish_scp_conn(self):\r\n \"\"\"Establish SCP connection.\"\"\"\r\n self.scp_conn = SCPConn(self.ssh_ctl_chan)\r\n\r\n def close_scp_chan(self):\r\n \"\"\"Close the SCP connection to the remote network device.\"\"\"\r\n self.scp_conn.close()\r\n self.scp_conn = None\r\n\r\n def remote_space_available(self, search_pattern=r\"(\\d+) \\w+ free\"):\r\n \"\"\"Return space available on remote device.\"\"\"\r\n remote_cmd = \"dir {}\".format(self.file_system)\r\n remote_output = self.ssh_ctl_chan.send_command_expect(remote_cmd)\r\n match = re.search(search_pattern, remote_output)\r\n if \"kbytes\" in match.group(0) or \"Kbytes\" in match.group(0):\r\n return int(match.group(1)) * 1000\r\n return int(match.group(1))\r\n\r\n def _remote_space_available_unix(self, search_pattern=\"\"):\r\n \"\"\"Return space available on *nix system (BSD/Linux).\"\"\"\r\n self.ssh_ctl_chan._enter_shell()\r\n remote_cmd = \"/bin/df -k {}\".format(self.file_system)\r\n remote_output = self.ssh_ctl_chan.send_command(\r\n remote_cmd, expect_string=r\"[\\$#]\"\r\n )\r\n\r\n # Try to ensure parsing is correct:\r\n # Filesystem 1K-blocks Used Avail Capacity Mounted on\r\n # /dev/bo0s3f 1264808 16376 1147248 1% /cf/var\r\n remote_output = remote_output.strip()\r\n output_lines = remote_output.splitlines()\r\n\r\n # First line is the header; second is the actual file system info\r\n header_line = output_lines[0]\r\n filesystem_line = output_lines[1]\r\n\r\n if \"Filesystem\" not in header_line or \"Avail\" not in header_line.split()[3]:\r\n # Filesystem 1K-blocks Used Avail Capacity Mounted on\r\n msg = \"Parsing error, unexpected output from {}:\\n{}\".format(\r\n remote_cmd, remote_output\r\n )\r\n raise ValueError(msg)\r\n\r\n space_available = filesystem_line.split()[3]\r\n if not re.search(r\"^\\d+$\", space_available):\r\n msg = \"Parsing error, unexpected output from {}:\\n{}\".format(\r\n remote_cmd, remote_output\r\n )\r\n raise ValueError(msg)\r\n\r\n self.ssh_ctl_chan._return_cli()\r\n return int(space_available) * 1024\r\n\r\n def local_space_available(self):\r\n \"\"\"Return space available on local filesystem.\"\"\"\r\n destination_stats = os.statvfs(\".\")\r\n return destination_stats.f_bsize * destination_stats.f_bavail\r\n\r\n def verify_space_available(self, search_pattern=r\"(\\d+) \\w+ free\"):\r\n \"\"\"Verify sufficient space is available on destination file system (return boolean).\"\"\"\r\n if self.direction == \"put\":\r\n space_avail = self.remote_space_available(search_pattern=search_pattern)\r\n elif self.direction == \"get\":\r\n space_avail = self.local_space_available()\r\n if space_avail > self.file_size:\r\n return True\r\n return False\r\n\r\n def check_file_exists(self, remote_cmd=\"\"):\r\n \"\"\"Check if the dest_file already exists on the file system (return boolean).\"\"\"\r\n if self.direction == \"put\":\r\n if not remote_cmd:\r\n remote_cmd = \"dir {}/{}\".format(self.file_system, self.dest_file)\r\n remote_out = self.ssh_ctl_chan.send_command_expect(remote_cmd)\r\n search_string = r\"Directory of .*{0}\".format(self.dest_file)\r\n if (\r\n \"Error opening\" in remote_out\r\n or \"No such file or directory\" in remote_out\r\n or \"Path does not exist\" in remote_out\r\n ):\r\n return False\r\n elif re.search(search_string, remote_out, flags=re.DOTALL):\r\n return True\r\n else:\r\n raise ValueError(\"Unexpected output from check_file_exists\")\r\n elif self.direction == \"get\":\r\n return os.path.exists(self.dest_file)\r\n\r\n def _check_file_exists_unix(self, remote_cmd=\"\"):\r\n \"\"\"Check if the dest_file already exists on the file system (return boolean).\"\"\"\r\n if self.direction == \"put\":\r\n self.ssh_ctl_chan._enter_shell()\r\n remote_cmd = \"ls {}\".format(self.file_system)\r\n remote_out = self.ssh_ctl_chan.send_command(\r\n remote_cmd, expect_string=r\"[\\$#]\"\r\n )\r\n self.ssh_ctl_chan._return_cli()\r\n return self.dest_file in remote_out\r\n elif self.direction == \"get\":\r\n return os.path.exists(self.dest_file)\r\n\r\n def remote_file_size(self, remote_cmd=\"\", remote_file=None):\r\n \"\"\"Get the file size of the remote file.\"\"\"\r\n if remote_file is None:\r\n if self.direction == \"put\":\r\n remote_file = self.dest_file\r\n elif self.direction == \"get\":\r\n remote_file = self.source_file\r\n if not remote_cmd:\r\n remote_cmd = \"dir {}/{}\".format(self.file_system, remote_file)\r\n remote_out = self.ssh_ctl_chan.send_command(remote_cmd)\r\n # Strip out \"Directory of flash:/filename line\r\n remote_out = re.split(r\"Directory of .*\", remote_out)\r\n remote_out = \"\".join(remote_out)\r\n # Match line containing file name\r\n escape_file_name = re.escape(remote_file)\r\n pattern = r\".*({}).*\".format(escape_file_name)\r\n match = re.search(pattern, remote_out)\r\n if match:\r\n line = match.group(0)\r\n # Format will be 26 -rw- 6738 Jul 30 2016 19:49:50 -07:00 filename\r\n file_size = line.split()[2]\r\n if \"Error opening\" in remote_out or \"No such file or directory\" in remote_out:\r\n raise IOError(\"Unable to find file on remote system\")\r\n else:\r\n return int(file_size)\r\n\r\n def _remote_file_size_unix(self, remote_cmd=\"\", remote_file=None):\r\n \"\"\"Get the file size of the remote file.\"\"\"\r\n if remote_file is None:\r\n if self.direction == \"put\":\r\n remote_file = self.dest_file\r\n elif self.direction == \"get\":\r\n remote_file = self.source_file\r\n remote_file = \"{}/{}\".format(self.file_system, remote_file)\r\n if not remote_cmd:\r\n remote_cmd = \"ls -l {}\".format(remote_file)\r\n\r\n self.ssh_ctl_chan._enter_shell()\r\n remote_out = self.ssh_ctl_chan.send_command(remote_cmd, expect_string=r\"[\\$#]\")\r\n self.ssh_ctl_chan._return_cli()\r\n\r\n if \"No such file or directory\" in remote_out:\r\n raise IOError(\"Unable to find file on remote system\")\r\n\r\n escape_file_name = re.escape(remote_file)\r\n pattern = r\"^.* ({}).*$\".format(escape_file_name)\r\n match = re.search(pattern, remote_out, flags=re.M)\r\n if match:\r\n # Format: -rw-r--r-- 1 pyclass wheel 12 Nov 5 19:07 /var/tmp/test3.txt\r\n line = match.group(0)\r\n file_size = line.split()[4]\r\n return int(file_size)\r\n\r\n raise ValueError(\r\n \"Search pattern not found for remote file size during SCP transfer.\"\r\n )\r\n\r\n def file_md5(self, file_name):\r\n \"\"\"Compute MD5 hash of file.\"\"\"\r\n with open(file_name, \"rb\") as f:\r\n file_contents = f.read()\r\n file_hash = hashlib.md5(file_contents).hexdigest()\r\n return file_hash\r\n\r\n @staticmethod\r\n def process_md5(md5_output, pattern=r\"=\\s+(\\S+)\"):\r\n match = re.search(pattern, md5_output)\r\n if match:\r\n return match.group(1)\r\n else:\r\n raise ValueError(\"Invalid output from MD5 command: {}\".format(md5_output))\r\n\r\n def compare_md5(self):\r\n \"\"\"Compare md5 of file on network device to md5 of local file.\"\"\"\r\n if self.direction == \"put\":\r\n remote_md5 = self.remote_md5()\r\n return self.source_md5 == remote_md5\r\n elif self.direction == \"get\":\r\n local_md5 = self.file_md5(self.dest_file)\r\n return self.source_md5 == local_md5\r\n\r\n def remote_md5(self, base_cmd=\"verify /md5\", remote_file=None):\r\n \"\"\"Calculate remote MD5 and returns the hash.\r\n\r\n This command can be CPU intensive on the remote device.\r\n \"\"\"\r\n if remote_file is None:\r\n if self.direction == \"put\":\r\n remote_file = self.dest_file\r\n elif self.direction == \"get\":\r\n remote_file = self.source_file\r\n remote_md5_cmd = \"{} {}/{}\".format(base_cmd, self.file_system, remote_file)\r\n dest_md5 = self.ssh_ctl_chan.send_command(remote_md5_cmd, max_loops=1500)\r\n dest_md5 = self.process_md5(dest_md5)\r\n return dest_md5\r\n\r\n def transfer_file(self):\r\n \"\"\"SCP transfer file.\"\"\"\r\n if self.direction == \"put\":\r\n self.put_file()\r\n elif self.direction == \"get\":\r\n self.get_file()\r\n\r\n def get_file(self):\r\n \"\"\"SCP copy the file from the remote device to local system.\"\"\"\r\n source_file = \"{}/{}\".format(self.file_system, self.source_file)\r\n self.scp_conn.scp_get_file(source_file, self.dest_file)\r\n self.scp_conn.close()\r\n\r\n def put_file(self):\r\n \"\"\"SCP copy the file from the local system to the remote device.\"\"\"\r\n destination = \"{}/{}\".format(self.file_system, self.dest_file)\r\n self.scp_conn.scp_transfer_file(self.source_file, destination)\r\n # Must close the SCP connection to get the file written (flush)\r\n self.scp_conn.close()\r\n\r\n def verify_file(self):\r\n \"\"\"Verify the file has been transferred correctly.\"\"\"\r\n return self.compare_md5()\r\n\r\n def enable_scp(self, cmd=None):\r\n \"\"\"\r\n Enable SCP on remote device.\r\n\r\n Defaults to Cisco IOS command\r\n \"\"\"\r\n if cmd is None:\r\n cmd = [\"ip scp server enable\"]\r\n elif not hasattr(cmd, \"__iter__\"):\r\n cmd = [cmd]\r\n self.ssh_ctl_chan.send_config_set(cmd)\r\n\r\n def disable_scp(self, cmd=None):\r\n \"\"\"\r\n Disable SCP on remote device.\r\n\r\n Defaults to Cisco IOS command\r\n \"\"\"\r\n if cmd is None:\r\n cmd = [\"no ip scp server enable\"]\r\n elif not hasattr(cmd, \"__iter__\"):\r\n cmd = [cmd]\r\n self.ssh_ctl_chan.send_config_set(cmd)\r\n\r\nclass CiscoFileTransfer(BaseFileTransfer):\r\n pass\r\n\r\nclass LinuxFileTransfer(CiscoFileTransfer):\r\n \"\"\"\r\n Linux SCP File Transfer driver.\r\n\r\n Mostly for testing purposes.\r\n \"\"\"\r\n def __init__(\r\n self, ssh_conn, source_file, dest_file, file_system=\"/var/tmp\", direction=\"put\"\r\n ):\r\n return super(LinuxFileTransfer, self).__init__(\r\n ssh_conn=ssh_conn,\r\n source_file=source_file,\r\n dest_file=dest_file,\r\n file_system=file_system,\r\n direction=direction,\r\n )\r\n\r\n def remote_space_available(self, search_pattern=\"\"):\r\n \"\"\"Return space available on remote device.\"\"\"\r\n return self._remote_space_available_unix(search_pattern=search_pattern)\r\n\r\n def check_file_exists(self, remote_cmd=\"\"):\r\n \"\"\"Check if the dest_file already exists on the file system (return boolean).\"\"\"\r\n return self._check_file_exists_unix(remote_cmd=remote_cmd)\r\n\r\n def remote_file_size(self, remote_cmd=\"\", remote_file=None):\r\n \"\"\"Get the file size of the remote file.\"\"\"\r\n return self._remote_file_size_unix(\r\n remote_cmd=remote_cmd, remote_file=remote_file\r\n )\r\n\r\n def remote_md5(self, base_cmd=\"md5sum\", remote_file=None):\r\n if remote_file is None:\r\n if self.direction == \"put\":\r\n remote_file = self.dest_file\r\n elif self.direction == \"get\":\r\n remote_file = self.source_file\r\n remote_md5_cmd = \"{} {}/{}\".format(base_cmd, self.file_system, remote_file)\r\n dest_md5 = self.ssh_ctl_chan.send_command(\r\n remote_md5_cmd, max_loops=750, delay_factor=5\r\n )\r\n dest_md5 = self.process_md5(dest_md5)\r\n return dest_md5\r\n\r\n @staticmethod\r\n def process_md5(md5_output, pattern=r\"^(\\S+)\\s+\"):\r\n return super(LinuxFileTransfer, LinuxFileTransfer).process_md5(\r\n md5_output, pattern=pattern\r\n )\r\n\r\n def enable_scp(self, cmd=None):\r\n raise NotImplementedError\r\n\r\n def disable_scp(self, cmd=None):\r\n raise NotImplementedError\r\n\r\nclass CiscoBaseConnection(BaseConnection):\r\n \"\"\"Base Class for cisco-like behavior.\"\"\"\r\n def check_enable_mode(self, check_string=\"#\"):\r\n \"\"\"Check if in enable mode. Return boolean.\"\"\"\r\n return super(CiscoBaseConnection, self).check_enable_mode(\r\n check_string=check_string\r\n )\r\n\r\n def enable(self, cmd=\"enable\", pattern=\"ssword\", re_flags=re.IGNORECASE):\r\n \"\"\"Enter enable mode.\"\"\"\r\n return super(CiscoBaseConnection, self).enable(\r\n cmd=cmd, pattern=pattern, re_flags=re_flags\r\n )\r\n\r\n def exit_enable_mode(self, exit_command=\"disable\"):\r\n \"\"\"Exits enable (privileged exec) mode.\"\"\"\r\n return super(CiscoBaseConnection, self).exit_enable_mode(\r\n exit_command=exit_command\r\n )\r\n\r\n def check_config_mode(self, check_string=\")#\", pattern=\"\"):\r\n \"\"\"\r\n Checks if the device is in configuration mode or not.\r\n\r\n Cisco IOS devices abbreviate the prompt at 20 chars in config mode\r\n \"\"\"\r\n return super(CiscoBaseConnection, self).check_config_mode(\r\n check_string=check_string, pattern=pattern\r\n )\r\n\r\n def config_mode(self, config_command=\"config term\", pattern=\"\"):\r\n \"\"\"\r\n Enter into configuration mode on remote device.\r\n\r\n Cisco IOS devices abbreviate the prompt at 20 chars in config mode\r\n \"\"\"\r\n if not pattern:\r\n pattern = re.escape(self.base_prompt[:16])\r\n return super(CiscoBaseConnection, self).config_mode(\r\n config_command=config_command, pattern=pattern\r\n )\r\n\r\n def exit_config_mode(self, exit_config=\"end\", pattern=\"#\"):\r\n \"\"\"Exit from configuration mode.\"\"\"\r\n return super(CiscoBaseConnection, self).exit_config_mode(\r\n exit_config=exit_config, pattern=pattern\r\n )\r\n\r\n\r\n def telnet_login(\r\n self,\r\n pri_prompt_terminator=r\"#\\s*$\",\r\n alt_prompt_terminator=r\">\\s*$\",\r\n username_pattern=r\"(?:user:|username|login|user name)\",\r\n pwd_pattern=r\"assword\",\r\n delay_factor=5,\r\n max_loops=20,\r\n ):\r\n \"\"\"Telnet login. Can be username/password or just password.\"\"\"\r\n delay_factor = self.select_delay_factor(delay_factor)\r\n time.sleep(1 * delay_factor)\r\n\r\n output = \"\"\r\n return_msg = \"\"\r\n i = 1\r\n while i <= max_loops:\r\n try:\r\n output = self.read_channel()\r\n return_msg += output\r\n\r\n # Search for username pattern / send username\r\n if re.search(username_pattern, output, flags=re.I):\r\n self.write_channel(self.username + self.TELNET_RETURN)\r\n time.sleep(1 * delay_factor)\r\n output = self.read_channel()\r\n return_msg += output\r\n\r\n # Search for password pattern / send password\r\n if re.search(pwd_pattern, output, flags=re.I):\r\n self.write_channel(self.password + self.TELNET_RETURN)\r\n time.sleep(0.5 * delay_factor)\r\n output = self.read_channel()\r\n return_msg += output\r\n if re.search(\r\n pri_prompt_terminator, output, flags=re.M\r\n ) or re.search(alt_prompt_terminator, output, flags=re.M):\r\n return return_msg\r\n\r\n # Support direct telnet through terminal server\r\n if re.search(r\"initial configuration dialog\\? \\[yes/no\\]: \", output):\r\n self.write_channel(\"no\" + self.TELNET_RETURN)\r\n time.sleep(0.5 * delay_factor)\r\n count = 0\r\n while count < 15:\r\n output = self.read_channel()\r\n return_msg += output\r\n if re.search(r\"ress RETURN to get started\", output):\r\n output = \"\"\r\n break\r\n time.sleep(2 * delay_factor)\r\n count += 1\r\n\r\n # Check for device with no password configured\r\n if re.search(r\"assword required, but none set\", output):\r\n self.remote_conn.close()\r\n msg = \"Login failed - Password required, but none set: {}\".format(\r\n self.host\r\n )\r\n raise Net_ConnectAuthenticationException(msg)\r\n\r\n # Check if proper data received\r\n if re.search(pri_prompt_terminator, output, flags=re.M) or re.search(\r\n alt_prompt_terminator, output, flags=re.M\r\n ):\r\n return return_msg\r\n\r\n self.write_channel(self.TELNET_RETURN)\r\n time.sleep(0.5 * delay_factor)\r\n i += 1\r\n except EOFError:\r\n self.remote_conn.close()\r\n msg = \"Login failed: {}\".format(self.host)\r\n raise Net_ConnectAuthenticationException(msg)\r\n\r\n # Last try to see if we already logged in\r\n self.write_channel(self.TELNET_RETURN)\r\n time.sleep(0.5 * delay_factor)\r\n output = self.read_channel()\r\n return_msg += output\r\n if re.search(pri_prompt_terminator, output, flags=re.M) or re.search(\r\n alt_prompt_terminator, output, flags=re.M\r\n ):\r\n return return_msg\r\n\r\n self.remote_conn.close()\r\n msg = \"Login failed: {}\".format(self.host)\r\n raise Net_ConnectAuthenticationException(msg)\r\n\r\n def cleanup(self):\r\n \"\"\"Gracefully exit the SSH session.\"\"\"\r\n try:\r\n self.exit_config_mode()\r\n except Exception:\r\n pass\r\n # Always try to send final 'exit' regardless of whether exit_config_mode works or not.\r\n self._session_log_fin = True\r\n self.write_channel(\"exit\" + self.RETURN)\r\n\r\n def _autodetect_fs(self, cmd=\"dir\", pattern=r\"Directory of (.*)/\"):\r\n \"\"\"Autodetect the file system on the remote device. Used by SCP operations.\"\"\"\r\n if not self.check_enable_mode():\r\n raise ValueError(\"Must be in enable mode to auto-detect the file-system.\")\r\n output = self.send_command_expect(cmd)\r\n match = re.search(pattern, output)\r\n if match:\r\n file_system = match.group(1)\r\n # Test file_system\r\n cmd = \"dir {}\".format(file_system)\r\n output = self.send_command_expect(cmd)\r\n if \"% Invalid\" in output or \"%Error:\" in output:\r\n raise ValueError(\r\n \"An error occurred in dynamically determining remote file \"\r\n \"system: {} {}\".format(cmd, output)\r\n )\r\n else:\r\n return file_system\r\n\r\n raise ValueError(\r\n \"An error occurred in dynamically determining remote file \"\r\n \"system: {} {}\".format(cmd, output)\r\n )\r\n\r\n def save_config(\r\n self,\r\n cmd=\"copy running-config startup-config\",\r\n confirm=False,\r\n confirm_response=\"\",\r\n ):\r\n \"\"\"Saves Config.\"\"\"\r\n self.enable()\r\n if confirm:\r\n output = self.send_command_timing(command_string=cmd)\r\n if confirm_response:\r\n output += self.send_command_timing(confirm_response)\r\n else:\r\n # Send enter by default\r\n output += self.send_command_timing(self.RETURN)\r\n else:\r\n # Some devices are slow so match on trailing-prompt if you can\r\n output = self.send_command(command_string=cmd)\r\n return output\r\n\r\nclass CiscoSSHConnection(CiscoBaseConnection):\r\n pass\r\n\r\nclass Net_ConnectTimeoutException(SSHException):\r\n \"\"\"SSH session timed trying to connect to the device.\"\"\"\r\n pass\r\n\r\nclass LinuxSSH(CiscoSSHConnection):\r\n\r\n def session_preparation(self):\r\n \"\"\"Prepare the session after the connection has been established.\"\"\"\r\n self.ansi_escape_codes = True\r\n return super(LinuxSSH, self).session_preparation()\r\n\r\n def _enter_shell(self):\r\n \"\"\"Already in shell.\"\"\"\r\n return \"\"\r\n\r\n def _return_cli(self):\r\n \"\"\"The shell is the CLI.\"\"\"\r\n return \"\"\r\n\r\n def disable_paging(self, *args, **kwargs):\r\n \"\"\"Linux doesn't have paging by default.\"\"\"\r\n return \"\"\r\n\r\n def set_base_prompt(\r\n self,\r\n pri_prompt_terminator=LINUX_PROMPT_PRI,\r\n alt_prompt_terminator=LINUX_PROMPT_ALT,\r\n delay_factor=1,\r\n ):\r\n \"\"\"Determine base prompt.\"\"\"\r\n return super(LinuxSSH, self).set_base_prompt(\r\n pri_prompt_terminator=pri_prompt_terminator,\r\n alt_prompt_terminator=alt_prompt_terminator,\r\n delay_factor=delay_factor,\r\n )\r\n\r\n def send_config_set(self, config_commands=None, exit_config_mode=True, **kwargs):\r\n \"\"\"Can't exit from root (if root)\"\"\"\r\n if self.username == \"root\":\r\n exit_config_mode = False\r\n return super(LinuxSSH, self).send_config_set(\r\n config_commands=config_commands, exit_config_mode=exit_config_mode, **kwargs\r\n )\r\n\r\n def check_config_mode(self, check_string=LINUX_PROMPT_ROOT):\r\n \"\"\"Verify root\"\"\"\r\n return self.check_enable_mode(check_string=check_string)\r\n\r\n def config_mode(self, config_command=\"sudo su\"):\r\n \"\"\"Attempt to become root.\"\"\"\r\n return self.enable(cmd=config_command)\r\n\r\n def exit_config_mode(self, exit_config=\"exit\"):\r\n return self.exit_enable_mode(exit_command=exit_config)\r\n\r\n def check_enable_mode(self, check_string=LINUX_PROMPT_ROOT):\r\n \"\"\"Verify root\"\"\"\r\n return super(LinuxSSH, self).check_enable_mode(check_string=check_string)\r\n\r\n def exit_enable_mode(self, exit_command=\"exit\"):\r\n \"\"\"Exit enable mode.\"\"\"\r\n delay_factor = self.select_delay_factor(delay_factor=0)\r\n output = \"\"\r\n if self.check_enable_mode():\r\n self.write_channel(self.normalize_cmd(exit_command))\r\n time.sleep(0.3 * delay_factor)\r\n self.set_base_prompt()\r\n if self.check_enable_mode():\r\n raise ValueError(\"Failed to exit enable mode.\")\r\n return output\r\n\r\n def enable(self, cmd=\"sudo su\", pattern=\"ssword\", re_flags=re.IGNORECASE):\r\n \"\"\"Attempt to become root.\"\"\"\r\n delay_factor = self.select_delay_factor(delay_factor=0)\r\n output = \"\"\r\n if not self.check_enable_mode():\r\n self.write_channel(self.normalize_cmd(cmd))\r\n time.sleep(0.3 * delay_factor)\r\n try:\r\n output += self.read_channel()\r\n if re.search(pattern, output, flags=re_flags):\r\n self.write_channel(self.normalize_cmd(self.secret))\r\n self.set_base_prompt()\r\n except socket.timeout:\r\n raise Net_ConnectTimeoutException(\r\n \"Timed-out reading channel, data not available.\"\r\n )\r\n if not self.check_enable_mode():\r\n msg = (\r\n \"Failed to enter enable mode. Please ensure you pass \"\r\n \"the 'secret' argument to ConnectHandler.\"\r\n )\r\n raise ValueError(msg)\r\n return output\r\n\r\n def cleanup(self):\r\n \"\"\"Try to Gracefully exit the SSH session.\"\"\"\r\n self._session_log_fin = True\r\n self.write_channel(\"exit\" + self.RETURN)\r\n\r\n def save_config(self, *args, **kwargs):\r\n \"\"\"Not Implemented\"\"\"\r\n raise NotImplementedError\r\n\r\n\r\n########################################################################################################################\r\n# Text Format Syntaxes\r\n########################################################################################################################\r\n\r\n\r\ndef write_bytes(out_data, encoding=\"ascii\"):\r\n \"\"\"Write Python2 and Python3 compatible byte stream.\"\"\"\r\n if sys.version_info[0] >= 3:\r\n if isinstance(out_data, type(\"\")):\r\n if encoding == \"utf-8\":\r\n return out_data.encode(\"utf-8\")\r\n else:\r\n return out_data.encode(\"ascii\", \"ignore\")\r\n elif isinstance(out_data, type(b\"\")):\r\n return out_data\r\n else:\r\n if isinstance(out_data, type(\"\")):\r\n if encoding == \"utf-8\":\r\n return out_data.encode(\"utf-8\")\r\n else:\r\n return out_data.encode(\"ascii\", \"ignore\")\r\n elif isinstance(out_data, type(str(\"\"))):\r\n return out_data\r\n msg = \"Invalid value for out_data neither unicode nor byte string: {}\".format(\r\n out_data\r\n )\r\n raise ValueError(msg)\r\n\r\nclass CopyableRegexObject(object):\r\n \"\"\"Like a re.RegexObject, but can be copied.\"\"\"\r\n\r\n def __init__(self, pattern):\r\n self.pattern = pattern\r\n self.regex = re.compile(pattern)\r\n\r\n def match(self, *args, **kwargs):\r\n return self.regex.match(*args, **kwargs)\r\n\r\n def sub(self, *args, **kwargs):\r\n return self.regex.sub(*args, **kwargs)\r\n\r\n def __copy__(self):\r\n return CopyableRegexObject(self.pattern)\r\n\r\n def __deepcopy__(self, unused_memo):\r\n return self.__copy__()\r\n\r\nclass Error(Exception):\r\n \"\"\"The base error class.\"\"\"\r\n\r\nclass Usage(Error):\r\n \"\"\"Command line format error.\"\"\"\r\n\r\ndef EncloseAnsiText(text):\r\n \"\"\"Enclose ANSI/SGR escape sequences with ANSI_START and ANSI_END.\"\"\"\r\n return sgr_re.sub(lambda x: ANSI_START + x.group(1) + ANSI_END, text)\r\n\r\ndef clitable_to_dict(cli_table):\r\n \"\"\"Converts TextFSM cli_table object to list of dictionaries.\"\"\"\r\n objs = []\r\n for row in cli_table:\r\n temp_dict = {}\r\n for index, element in enumerate(row):\r\n temp_dict[cli_table.header[index].lower()] = element\r\n objs.append(temp_dict)\r\n return objs\r\n\r\ndef get_template_dir():\r\n \"\"\"Find and return the ntc-templates/templates dir.\"\"\"\r\n try:\r\n template_dir = os.path.expanduser(os.environ[\"NET_TEXTFSM\"])\r\n index = os.path.join(template_dir, \"index\")\r\n if not os.path.isfile(index):\r\n # Assume only base ./ntc-templates specified\r\n template_dir = os.path.join(template_dir, \"templates\")\r\n except KeyError:\r\n # Construct path ~/ntc-templates/templates\r\n home_dir = os.path.expanduser(\"~\")\r\n template_dir = os.path.join(home_dir, \"ntc-templates\", \"templates\")\r\n\r\n index = os.path.join(template_dir, \"index\")\r\n if not os.path.isdir(template_dir) or not os.path.isfile(index):\r\n msg = \"\"\"\r\nValid ntc-templates not found, please install https://github.com/networktocode/ntc-templates\r\nand then set the NET_TEXTFSM environment variable to point to the ./ntc-templates/templates\r\ndirectory.\"\"\"\r\n raise ValueError(msg)\r\n return os.path.abspath(template_dir)\r\n\r\ndef get_structured_data(raw_output, platform, command):\r\n \"\"\"Convert raw CLI output to structured data using TextFSM template.\"\"\"\r\n template_dir = get_template_dir()\r\n index_file = os.path.join(template_dir, \"index\")\r\n textfsm_obj = clitable.CliTable(index_file, template_dir)\r\n attrs = {\"Command\": command, \"Platform\": platform}\r\n try:\r\n # Parse output through template\r\n textfsm_obj.ParseCmd(raw_output, attrs)\r\n structured_data = clitable_to_dict(textfsm_obj)\r\n output = raw_output if structured_data == [] else structured_data\r\n return output\r\n except CliTableError:\r\n return raw_output\r\n\r\ndef get_structured_data_genie(raw_output, platform, command):\r\n if not sys.version_info >= (3, 4):\r\n raise ValueError(\"Genie requires Python >= 3.4\")\r\n\r\n if not GENIE_INSTALLED:\r\n msg = (\r\n \"\\nGenie and PyATS are not installed. Please PIP install both Genie and PyATS:\\n\"\r\n \"pip install genie\\npip install pyats\\n\"\r\n )\r\n raise ValueError(msg)\r\n\r\n if \"cisco\" not in platform:\r\n return raw_output\r\n\r\n genie_device_mapper = {\r\n \"cisco_ios\": \"ios\",\r\n \"cisco_xe\": \"iosxe\",\r\n \"cisco_xr\": \"iosxr\",\r\n \"cisco_nxos\": \"nxos\",\r\n \"cisco_asa\": \"asa\",\r\n }\r\n\r\n os = None\r\n # platform might be _ssh, _telnet, _serial strip that off\r\n if platform.count(\"_\") > 1:\r\n base_platform = platform.split(\"_\")[:-1]\r\n base_platform = \"_\".join(base_platform)\r\n else:\r\n base_platform = platform\r\n\r\n os = genie_device_mapper.get(base_platform)\r\n if os is None:\r\n return raw_output\r\n\r\n # Genie specific construct for doing parsing (based on Genie in Ansible)\r\n device = Device(\"new_device\", os=os)\r\n device.custom.setdefault(\"abstraction\", {})\r\n device.custom[\"abstraction\"][\"order\"] = [\"os\"]\r\n device.cli = AttrDict({\"execute\": None})\r\n try:\r\n # Test of whether their is a parser for the given command (will return Exception if fails)\r\n get_parser(command, device)\r\n parsed_output = device.parse(command, output=raw_output)\r\n return parsed_output\r\n except Exception:\r\n return raw_output\r\n\r\nclass Error(Exception):\r\n \"\"\"Base class for errors.\"\"\"\r\n\r\nclass IndexTableError(Error):\r\n \"\"\"General INdexTable error.\"\"\"\r\n\r\nclass CliTableError(Error):\r\n \"\"\"General CliTable error.\"\"\"\r\n\r\n# Net_Connect Modules\r\nclass SSHException(Exception):\r\n \"\"\"\r\n Exception raised by failures in SSH2 protocol negotiation or logic errors.\r\n \"\"\"\r\n pass\r\n\r\nclass AuthenticationException(SSHException):\r\n \"\"\"\r\n Exception raised when authentication failed for some reason. It may be\r\n possible to retry with different credentials. (Other classes specify more\r\n specific reasons.)\r\n .. versionadded:: 1.6\r\n \"\"\"\r\n pass\r\n\r\nclass PasswordRequiredException(AuthenticationException):\r\n \"\"\"\r\n Exception raised when a password is needed to unlock a private key file.\r\n \"\"\"\r\n pass\r\n\r\nclass BadAuthenticationType(AuthenticationException):\r\n \"\"\"\r\n Exception raised when an authentication type (like password) is used, but\r\n the server isn't allowing that type. (It may only allow public-key, for\r\n example.)\r\n .. versionadded:: 1.1\r\n \"\"\"\r\n allowed_types = []\r\n\r\n # TODO 3.0: remove explanation kwarg\r\n def __init__(self, explanation, types):\r\n # TODO 3.0: remove this supercall unless it's actually required for\r\n # pickling (after fixing pickling)\r\n AuthenticationException.__init__(self, explanation, types)\r\n self.explanation = explanation\r\n self.allowed_types = types\r\n\r\n def __str__(self):\r\n return \"{}; allowed types: {!r}\".format(\r\n self.explanation, self.allowed_types\r\n )\r\n\r\nclass PartialAuthentication(AuthenticationException):\r\n \"\"\"\r\n An internal exception thrown in the case of partial authentication.\r\n \"\"\"\r\n\r\n allowed_types = []\r\n\r\n def __init__(self, types):\r\n AuthenticationException.__init__(self, types)\r\n self.allowed_types = types\r\n\r\n def __str__(self):\r\n return \"Partial authentication; allowed types: {!r}\".format(\r\n self.allowed_types\r\n )\r\n\r\nclass ChannelException(SSHException):\r\n \"\"\"\r\n Exception raised when an attempt to open a new `.Channel` fails.\r\n\r\n :param int code: the error code returned by the server\r\n\r\n .. versionadded:: 1.6\r\n \"\"\"\r\n def __init__(self, code, text):\r\n SSHException.__init__(self, code, text)\r\n self.code = code\r\n self.text = text\r\n\r\n def __str__(self):\r\n return \"ChannelException({!r}, {!r})\".format(self.code, self.text)\r\n\r\nclass BadHostKeyException(SSHException):\r\n def __init__(self, hostname, got_key, expected_key):\r\n SSHException.__init__(self, hostname, got_key, expected_key)\r\n self.hostname = hostname\r\n self.key = got_key\r\n self.expected_key = expected_key\r\n\r\n def __str__(self):\r\n msg = (\r\n \"Host key for server '{}' does not match: got '{}', expected '{}'\"\r\n ) # noqa\r\n return msg.format(\r\n self.hostname,\r\n self.key.get_base64(),\r\n self.expected_key.get_base64(),\r\n )\r\n\r\nclass ProxyCommandFailure(SSHException):\r\n def __init__(self, command, error):\r\n SSHException.__init__(self, command, error)\r\n self.command = command\r\n self.error = error\r\n\r\n def __str__(self):\r\n return 'ProxyCommand(\"{}\") returned nonzero exit status: {}'.format(\r\n self.command, self.error\r\n )\r\n\r\nclass NoValidConnectionsError(socket.error):\r\n def __init__(self, errors):\r\n \"\"\"\r\n :param dict errors:\r\n The errors dict to store, as described by class docstring.\r\n \"\"\"\r\n addrs = sorted(errors.keys())\r\n body = \", \".join([x[0] for x in addrs[:-1]])\r\n tail = addrs[-1][0]\r\n if body:\r\n msg = \"Unable to connect to port {0} on {1} or {2}\"\r\n else:\r\n msg = \"Unable to connect to port {0} on {2}\"\r\n super(NoValidConnectionsError, self).__init__(\r\n None, msg.format(addrs[0][1], body, tail) # stand-in for errno\r\n )\r\n self.errors = errors\r\n\r\n def __reduce__(self):\r\n return (self.__class__, (self.errors,))\r\n\r\nclass Error(Exception):\r\n \"\"\"Base class for errors.\"\"\"\r\n\r\nclass IndexTableError(Error):\r\n \"\"\"General INdexTable error.\"\"\"\r\n\r\nclass CliTableError(Error):\r\n \"\"\"General CliTable error.\"\"\"\r\n\r\nclass IndexTable(object):\r\n def __init__(self, preread=None, precompile=None, file_path=None):\r\n self.index = None\r\n self.compiled = None\r\n if file_path:\r\n self._index_file = file_path\r\n self._index_handle = open(self._index_file, \"r\")\r\n self._ParseIndex(preread, precompile)\r\n\r\n def __del__(self):\r\n \"\"\"Close index handle.\"\"\"\r\n if hasattr(self, \"_index_handle\"):\r\n self._index_handle.close()\r\n\r\n def __len__(self):\r\n \"\"\"Returns number of rows in table.\"\"\"\r\n return self.index.size\r\n\r\n def __copy__(self):\r\n \"\"\"Returns a copy of an IndexTable object.\"\"\"\r\n clone = IndexTable()\r\n if hasattr(self, \"_index_file\"):\r\n # pylint: disable=protected-access\r\n clone._index_file = self._index_file\r\n clone._index_handle = self._index_handle\r\n\r\n clone.index = self.index\r\n clone.compiled = self.compiled\r\n return clone\r\n\r\n def __deepcopy__(self, memodict=None):\r\n \"\"\"Returns a deepcopy of an IndexTable object.\"\"\"\r\n clone = IndexTable()\r\n if hasattr(self, \"_index_file\"):\r\n # pylint: disable=protected-access\r\n clone._index_file = copy.deepcopy(self._index_file)\r\n clone._index_handle = open(clone._index_file, \"r\")\r\n\r\n clone.index = copy.deepcopy(self.index)\r\n clone.compiled = copy.deepcopy(self.compiled)\r\n return clone\r\n\r\n def _ParseIndex(self, preread, precompile):\r\n self.index = texttable.TextTable()\r\n self.index.CsvToTable(self._index_handle)\r\n\r\n if preread:\r\n for row in self.index:\r\n for col in row.header:\r\n row[col] = preread(col, row[col])\r\n\r\n self.compiled = copy.deepcopy(self.index)\r\n\r\n for row in self.compiled:\r\n for col in row.header:\r\n if precompile:\r\n row[col] = precompile(col, row[col])\r\n if row[col]:\r\n row[col] = copyable_regex_object.CopyableRegexObject(row[col])\r\n\r\n def GetRowMatch(self, attributes):\r\n \"\"\"Returns the row number that matches the supplied attributes.\"\"\"\r\n for row in self.compiled:\r\n try:\r\n for key in attributes:\r\n # Silently skip attributes not present in the index file.\r\n # pylint: disable=E1103\r\n if (\r\n key in row.header\r\n and row[key]\r\n and not row[key].match(attributes[key])\r\n ):\r\n # This line does not match, so break and try next row.\r\n raise StopIteration()\r\n return row.row\r\n except StopIteration:\r\n pass\r\n return 0\r\n\r\nclass SCPConn(object):\r\n \"\"\"\r\n Establish a secure copy channel to the remote network device.\r\n\r\n Must close the SCP connection to get the file to write to the remote filesystem\r\n \"\"\"\r\n def __init__(self, ssh_conn):\r\n self.ssh_ctl_chan = ssh_conn\r\n self.establish_scp_conn()\r\n\r\n def establish_scp_conn(self):\r\n \"\"\"Establish the secure copy connection.\"\"\"\r\n ssh_connect_params = self.ssh_ctl_chan._connect_params_dict()\r\n self.scp_conn = self.ssh_ctl_chan._build_ssh_client()\r\n self.scp_conn.connect(**ssh_connect_params)\r\n self.scp_client = scp.SCPClient(self.scp_conn.get_transport())\r\n\r\n def scp_transfer_file(self, source_file, dest_file):\r\n \"\"\"Put file using SCP (for backwards compatibility).\"\"\"\r\n self.scp_client.put(source_file, dest_file)\r\n\r\n def scp_get_file(self, source_file, dest_file):\r\n \"\"\"Get file using SCP.\"\"\"\r\n self.scp_client.get(source_file, dest_file)\r\n\r\n def scp_put_file(self, source_file, dest_file):\r\n \"\"\"Put file using SCP.\"\"\"\r\n self.scp_client.put(source_file, dest_file)\r\n\r\n def close(self):\r\n \"\"\"Close the SCP connection.\"\"\"\r\n self.scp_conn.close()\r\n\r\nclass Net_ConnectAuthenticationException(AuthenticationException):\r\n \"\"\"SSH authentication exception based on Paramiko AuthenticationException.\"\"\"\r\n pass\r\n\r\nclass TelnetConnection(BaseConnection):\r\n pass\r\n\r\nclass TerminalServerTelnet(TerminalServer):\r\n \"\"\"Generic Terminal Server driver telnet.\"\"\"\r\n def telnet_login(self, *args, **kwargs):\r\n # Disable automatic handling of username and password when using terminal server driver\r\n pass\r\n\r\n def std_login(self, *args, **kwargs):\r\n return super(TerminalServerTelnet, self).telnet_login(*args, **kwargs)\r\n\r\n","sub_path":"F5_Volume_Utilization_V6/roles/f5_Volume_Utlilization/packages/Modules_Frame.py","file_name":"Modules_Frame.py","file_ext":"py","file_size_in_byte":88241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"82745208","text":"import numpy as np\nimport os\nimport sys\nimport math\nimport copy\nfrom skimage.exposure import adjust_gamma\nfrom skimage import io\nfrom scipy.ndimage import gaussian_filter\nfrom scipy import ndimage as ndi\nfrom skimage.morphology import disk, closing, watershed\nfrom skimage.filters import median, rank, threshold_otsu, gaussian\nfrom skimage.segmentation import random_walker\nfrom skimage.restoration import denoise_bilateral, estimate_sigma\nfrom skimage.feature import peak_local_max\nfrom skimage.transform import hough_circle, hough_circle_peaks\nfrom skimage.draw import circle_perimeter\nfrom skimage import measure\nfrom scipy.stats import iqr\nfrom scipy.ndimage.morphology import binary_fill_holes\nfrom skimage.segmentation import active_contour\nfrom skimage import measure\n\nfrom lib.math_funcs import *\nfrom lib.render import *\n\n\ndtype2bits = {'uint8': 8,\n\t\t\t 'uint16': 16,\n\t\t\t 'uint32': 32}\n\ndtype2range = { 'uint8': 255,\n\t\t\t\t'uint16': 65535,\n\t\t\t\t'uint32': 4294967295,\n\t\t\t\t'uint64': 18446744073709551615}\n\ndef gamma_stabilize(image, alpha_clean = 5, floor_method = 'min'):\n\t\"\"\"Normalizes the luma curve. floor intensity becomes 0 and max allowed by the bit number - 1\n\tBorrowed from Andrei's Imagepipe\n\n\t:param image: [np.ndarray]\n\t:param alpha_clean: [int] size of features that would be removed if surrounded by a majority of\n\t:param floor_method: [str] ['min', '1q', '5p', 'median'] method of setting the floor intensity. 1q is first quartile, 1p is the first percentile\n\t:return: [np.ndarray]\n\t\"\"\"\n\tbits = dtype2bits[image.dtype.name]\n\tif floor_method == 'min':\n\t\tinner_min = np.min(image)\n\telif floor_method == '1q':\n\t\tinner_min = np.percentile(image, 25)\n\telif floor_method == '5p':\n\t\tinner_min = np.percentile(image, 5)\n\telif floor_method == 'median':\n\t\tinner_min = np.median(image)\n\telse:\n\t\traise PipeArgError('floor_method can only be one of the three types: min, 1q, 5p or median')\n\tstabilized = (image - inner_min) / (float(2 ** bits) - inner_min)\n\tstabilized[stabilized < alpha_clean*np.median(stabilized)] = 0\n\treturn stabilized\n\n\ndef sum_projection(image, axis = 0):\n\t'''Axis is defined as the index of the image.shape output.\n\tBy default it is the Z axis (z,x,y)\n\tTakes a 3d image, and sums it along a defined axis to form a 2d Image\n\n\t:param image: [np.ndarray] 3d stack image in [np.ndarray] format\n\t:param axis: [int] axis to sum along, z = 0, x = 1, y = 2\n\t:return: [np.ndarray] returns 2d image in the shape x,y summed along z axis (by default)\n\t'''\n\ttry:\n\t\treturn np.sum(image, axis)\n\texcept ValueError:\n\t\tif not((axis >= 0 or axis <= 2) and isinstance(axis, int)):\n\t\t\tprint(\"Axis value invalid\")\n\t\telse:\n\t\t\tprint(\"Image input faulty\")\n\t\traise Exception\n\n\ndef max_projection(image, axis = 0):\n\t'''Axis is defined as the index of the image.shape output.\n\tBy default it is the Z axis (z,x,y)\n\tTakes a 3d image, and projects it along a defined axis to form a 2d Image\n\tTakes the max value for each pixel along (default) x,y plane, and projects it\n\tto one plane\n\n\t:param image: [np.ndarray] 3d stack image in format\n\t:param axis: [int] axis to sum along, z = 0, x = 1, y = 2\n\t:return: [np.ndarray] returns 2d image in the shape x,y\n\t'''\n\ttry:\n\t\treturn np.amax(image, axis)\n\texcept ValueError:\n\t\tif not((axis >= 0 or axis <= 2) and isinstance(axis, int)):\n\t\t\tprint(\"Axis value invalid\")\n\t\telse:\n\t\t\tprint(\"Image input faulty\")\n\t\traise Exception\n\n\ndef avg_projection(image, axis = 0):\n\t'''Axis is defined as the index of the image.shape output.\n\tBy default it is the Z axis (z,x,y)\n\tTakes a 3d image, and projects it along a defined axis to form a 2d Image\n\tTakes the average value for each pixel in the (default) x,y plane along the\n\tz axis\n\n\t:param image: [np.ndarray] 3d stack image in format\n\t:param axis: [int] axis to sum along, z = 0, x = 1, y = 2\n\t:return: [np.ndarray] returns 2d image in the shape x,y\n\t'''\n\ttry:\n\t\t# print axis\n\t\tz, x, y = image.shape\n\t\treturn np.sum(image, axis)//z\n\texcept ValueError:\n\t\tif not((axis >= 0 or axis <= 2) and isinstance(axis, int)):\n\t\t\tprint(\"Axis value invalid\")\n\t\telse:\n\t\t\tprint(\"Image input faulty\")\n\t\traise Exception\n\n\ndef disk_hole(image, radius, pinhole = False):\n\t'''Returns either an image of a pinhole or a circle in the\n\tmiddle for removing high frequency/ low frequency noise using FFT\n\tsame dimensions as input image\n\tPinhole = True : pinhole filter, or high pass filter. Filters out low frequency\n\tcontent to yield edges\n\tPinhole = False: single dot filter, preserves low frequency content\n\n\t:param image: [np.ndarray] 2d input image (filter will be applied eventually), used to get dims\n\t:param radius: [int] radius of pinhole/pinpoint\n\t:param pinhole: [bool] determines whether the filter will be a pinhole or pinpoint\n\t:return: [np.ndarray] 2d filter of same size of 2d image input\n\t'''\n\tx, y = image.shape\n\tstructuring_element = np.zeros((x, y), dtype = long)\n\tcenter = x//2\n\n\tfor rows in xrange(x):\n\t\tfor cols in xrange(y):\n\t\t\tif (rows - center + 0.5) ** 2 + (cols - center + 0.5) ** 2 <= radius ** 2:\n\t\t\t\tstructuring_element[rows, cols] = 1\n\tif pinhole:\n\t\treturn 1 - structuring_element\n\telse:\n\t\treturn structuring_element\n\n\ndef smooth(image, smoothing_px = 0.5, threshold = 1):\n\t\"\"\"Gaussian smoothing of the image\n\tBorrowed from Andrei's Imagepipe\n\n\t:param image: [np.ndarray] Input image\n\t:param smoothing_px: [float] size of smoothing pixel\n\t:param threshold: [int] threshold to filter image intensity\n\t:return: [np.ndarray]\n\t\"\"\"\n\t# print \"> Filtering image with Gaussian filter\"\n\tif len(image.shape) > 2:\n\t\tfor i in range(0, image.shape[0]):\n\t\t\timage[i, :, :] = gaussian_filter(image[i, :, :],\n\t\t\t\t\t\t\t\t\t\t\t smoothing_px, mode='constant')\n\t\t\timage[image < threshold * np.mean(image)] = 0\n\telse:\n\t\timage = gaussian_filter(image, smoothing_px, mode='constant')\n\t\timage[image < threshold * np.mean(image)] = 0\n\treturn image\n\n\ndef smooth_tripleD(image, smoothing_px = 0.5, stdevs = 1):\n\t\"\"\"Gaussian smoothing of the image\n\tBorrowed from Andrei's Imagepipe\n\n\t:param image: [np.ndarray] 3d Input image\n\t:param smoothing_px: [float] size of smoothing pixel\n\t:param threshold: [float] threshold to filter image intensity\n\t:return: [np.ndarray]\n\t\"\"\"\n\t# print \"> Filtering image with Gaussian filter\"\n\tif len(image.shape) > 2:\n\t\tfor i in range(0, image.shape[0]):\n\t\t\timage[i, :, :] = gaussian_filter(image[i, :, :],\n\t\t\t\t\t\t\t\t\t\t\t smoothing_px, mode='constant')\n\t\t\timage[image < mean + stdev * stdevs] = 0\n\telse:\n\t\timage = gaussian_filter(image, smoothing_px, mode='constant')\n\t\tmean, stdev = px_hist_stats_n0(image)\n\t\timage[image < mean + stdev * stdevs] = 0\n\treturn image\n\n\ndef fft_ifft(image, struct_element):\n\t'''Performs a fast fourier transform, removes certain frequencies highlighted by\n\tthe structuring element, and returns the inverse fourier transform back.\n\tHelper function disk_hole\n\n\t:param image: [np.ndarray] Image to be filtered\n\t:param struct_element: [np.ndarray] filter to be applied to image in frequency space, should be same dimension as input image\n\t:return: [np.ndarray] filtered image\n\t'''\n\t# print \"> Performing FFT>filter>IFFT transform\"\n\n\tfft_transform = np.fft.fft2(image)\n\tf_shift = np.fft.fftshift(fft_transform)\n\n\t# magnitude_spectrum = 20*np.log(np.abs(f_shift))\n\t# view_2d_img(magnitude_spectrum)\n\t# view_2d_img(struct_element)\n\n\tf_shift_filtered = f_shift * struct_element\n\n\t# magnitude_spectrum_filtered = 20*np.log(np.abs(f_shift_filtered))\n\t# view_2d_img(magnitude_spectrum_filtered)\n\n\tf_inv_shift = np.fft.ifftshift(f_shift_filtered)\n\trecovered_img = np.fft.ifft2(f_inv_shift)\n\trecovered_img = np.abs(recovered_img)\n\treturn recovered_img\n\n\ndef bandpass_disk(image, r_range = (10, 200), pinhole = False):\n\t'''\n\tCreates a bandpass disk for filtering FFT images, creates either a solid\n\ttorus filter or negative image of that\n\n\t:param image: [np.ndarray] image that filter will be applied to\n\t:param r_range: [tuple] (inner, outer) radius of bandpass filter\n\t:param pinhole: [bool] torus (true) or inverse torus (false) filter\n\t:return: [np.ndarray] bandpass filter structuring element\n\t'''\n\touter = disk_hole(image, r_range[1], pinhole)\n\tinner = disk_hole(image, r_range[0], pinhole)\n\tstructuring_element = outer - inner\n\treturn structuring_element\n\n\ndef median_layers(image, struct_disk_r = 5):\n\t'''\n\tApplies median filter over multiple layer of a 3d stack image\n\n\t:param image: [np.ndarray] input image\n\t:param struct_disk_r: [float] size of median filter kernel\n\t:return: [np.ndarray] de-noised median filtered image\n\t'''\n\tfor i in range(0, image.shape[0]):\n\t\timage[i, :, :] = median(image[i, :, :], disk(struct_disk_r))\n\treturn image\n\n\ndef img_type_2uint8(base_image, func = 'floor'):\n\t'''\n\tConverts a given image type to a uint8 image\n\tRounding is done either via 'floor', 'ceiling', or 'fix' functions in numpy\n\n\t:param base_image: [np.ndarray] input image\n\t:param func: [str] function used for scaling image pixel intensity\n\t:return: [np.ndarray] uint8 image\n\t'''\n\t# print \"> Converting Image to uin8\"\n\ttry:\n\t\tbi_max_val = global_max(base_image)\n\t\tbi_min_val = global_min(base_image)\n\t\tdt_max = dtype2range['uint8']\n\t\tdt_min = 0\n\n\t\t# scaled = dt_min * (1 - ((base_image - bi_min_val) / (bi_max_val - bi_min_val))) + dt_max * ((base_image - bi_min_val)/(bi_max_val - bi_min_val))\n\t\tscaled = (base_image - bi_min_val) * ((dt_max - dt_min) / (bi_max_val - bi_min_val)) + dt_min\n\n\t\tif func == 'floor':\n\t\t\tpre_int = np.floor(scaled)\n\t\telif func == 'ceiling':\n\t\t\tpre_int = np.ceil(scaled)\n\t\telif func == 'fix':\n\t\t\tpre_int = np.fix(scaled)\n\t\telse:\n\t\t\traise IOError\n\n\t\treturn np.uint8(pre_int)\n\texcept IOError:\n\t\tprint(\"Function '{}' not recognized \".format(func))\n\t\traise Exception\n\n\ndef binarize_image(base_image, _dilation = 0, feature_size = 2):\n\t'''\n\tBinarizes an image using local otsu and random walker\n\tBorrowed from Andrei's Imagepipe\n\n\t:param base_image: [np.ndarray] input image\n\t:param _dilation: [float] amount of dilation to implement in Binarization\n\t:param feature_size: [float] size of the structuring disk for random Walker\n\t:return: [np.ndarray] binarized image\n\t'''\n\tprint(\"> Binarizing Image...\")\n\tif np.percentile(base_image, 99) < 0.20:\n\t\tif np.percentile(base_image, 99) > 0:\n\t\t\tmult = 0.20 / np.percentile(base_image, 99) # poissonean background assumptions\n\t\telse:\n\t\t\tmult = 1000. / np.sum(base_image)\n\t\tbase_image = base_image * mult\n\t\tbase_image[base_image > 1] = 1\n\n\tclustering_markers = np.zeros(base_image.shape, dtype=np.uint8)\n\tselem2 = disk(feature_size)\n\tprint('> Performing Local Otsu')\n\tlocal_otsu = rank.otsu(base_image, selem2)\n\t# view_2d_img(local_otsu)\n\tclustering_markers[base_image < local_otsu * 0.9] = 1\n\tclustering_markers[base_image > local_otsu * 1.1] = 2\n\tprint(\"> Performing Random Walker Binarization\")\n\tbinary_labels = random_walker(base_image, clustering_markers, beta = 10, mode = 'bf') - 1\n\n\tif _dilation:\n\t\tselem = disk(_dilation)\n\t\tbinary_labels = dilation(binary_labels, selem)\n\treturn binary_labels\n\n# Depreciated\ndef hough_num_circles(input_binary_img, min_r = 15, max_r = 35, step = 2):\n\t'''\n\tHelper function for cell_split\n\tRuns hough transform on a cell cluster in a binary image to determine where\n\tindividual cells may lie. Does not take in a whole binary image, only takes in a contour converted\n\tto a binary image for a single cluster\n\n\t:param input_binary_img: [np.ndarray] Input binary image of the single cell group\n\t:param min_r: [float] minimum radius acceptable for a cell\n\t:param max_r: [float] maximum radius acceptable for a cell\n\t:param step: [float] rate at which minimum radius will be stepped up to maximum radius size\n\t:return: [np.ndarray] cropped and split version of input binary image\n\t'''\n\tprint(\"> Performing Hough cell splitting\")\n\t# Create a list of radii to test and perform hough transform to recover circle centers (x,y) and radii\n\though_radii = np.arange(min_r, max_r, 2)\n\though_res = hough_circle(input_binary_img, hough_radii)\n\taccums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii, total_num_peaks = 3)\n\tcircles = zip(cy, cx, radii);\n\t# remove any circles too close to each other\n\n\tno_duplicates = crop_close(circles, max_sep = 10)\n\n\t# HYPOTHETICAL # of cells\n\tN_cells = len(no_duplicates)\n\t# view_2d_img(input_binary_img)\n\tprint(\"\\t> Number cells in subsection: {}\".format(N_cells))\n\t# print no_duplicates\n\tif N_cells > 1:\n\t\t# Set initial radius to 1\n\t\tfor rows in no_duplicates:\n\t\t\trows[-1] == 1\n\t\t# Create mask to divide both cells\n\t\t# Grow circle size until there is a collision followed by no more collisions\n\t\tactual_mask = np.zeros_like(input_binary_img)\n\t\t# Create Conditions for Whileloop\n\t\tcollision = False\n\t\tend_collision = False\n\t\tstop_condition = False\n\t\tn = 0\n\t\tmax_iter = 100\n\n\t\t# while end_collision == False or n < 10:\n\t\twhile (n < max_iter and stop_condition == False):\n\t\t\t# Create empty mask to grow\n\t\t\tmask = np.zeros_like(input_binary_img)\n\t\t\tfor center_y, center_x, radius in no_duplicates:\n\t\t\t\t# Create mask for each circle in no_duplicates\n\t\t\t\tsub_mask = np.zeros_like(input_binary_img)\n\t\t\t\t# List of coodinates for perimeter of a circle and remove any negative points to prevent edge looparound\n\t\t\t\tcircy, circx = circle_perimeter(center_y, center_x, radius)\n\t\t\t\tno_negs = remove_neg_pts(zip(circy, circx))\n\t\t\t\tfor y, x in no_negs:\n\t\t\t\t\t# for each circle point, if it falls within the dimensions of the submask, plot it.\n\t\t\t\t\tif y < sub_mask.shape[0] and x < sub_mask.shape[1]:\n\t\t\t\t\t\tsub_mask[y, x] = 1\n\t\t\t\t# Append submask to growing mask after dilation (aka making the circle boundaries wide as fuck)\n\t\t\t\tmask += dilation(sub_mask, disk(2))\n\t\t\t# Determine if there is a collision between circles (max element in grow mask is more than just one submask)\n\t\t\t# montage_n_x((actual_mask, mask))\n\t\t\t# print np.amax(mask.flatten())\n\t\t\tif np.amax(mask.flatten()) > 1:\n\t\t\t\tcollision = True\n\t\t\t\t# collision_pt = np.where(mask >= 2)\n\t\t\t\tmask[mask < 2] = 0\n\t\t\t\t# view_2d_img(mask)\n\t\t\t\tactual_mask += mask\n\t\t\t\tactual_mask[actual_mask != 0 ] = 1\n\t\t\t# montage_n_x((actual_mask, mask))\n\t\t\tif collision == True and np.amax(mask.flatten()) <= 1:\n\t\t\t\tend_collision = True\n\t\t\t\tstop_condition = True\n\n\t\t\t# Grow circle radius by 8% per\n\t\t\tfor rows in no_duplicates:\n\t\t\t\trows[-1] *= 1.08\n\t\t\t\trows[-1] = np.int(rows[-1])\n\t\t\tn += 1\n\t\t\t# print n, collision, end_collision, stop_condition\n\t\tif stop_condition == False:\n\t\t\t# montage_n_x((actual_mask, actual_mask + input_binary_img, filled_cells, filled_cells * (1 - actual_mask)))\n\t\t\treturn np.ones_like(input_binary_img)\n\t\t\t# return binary_fill_holes(input_binary_img).astype(int)\n\t\telse:\n\t\t\t# Fill edges to create mask\n\t\t\t# filled_cells = binary_fill_holes(input_binary_img).astype(int)\n\t\t\t# montage_n_x((actual_mask, actual_mask + input_binary_img, filled_cells, filled_cells * (1 - actual_mask)))\n\t\t\t# view_2d_img(filled_cells * (1 - dm))\n\t\t\t# return filled_cells * (1 - actual_mask)\n\t\t\treturn actual_mask\n\telse:\n\t\t# view_2d_img(input_binary_img)\n\t\treturn np.ones_like(input_binary_img)\n\t\t# return binary_fill_holes(input_binary_img).astype(int)\n\n\t# Uncomment for visualization\n\t# montage_n_x((input_binary_img, filled_cells, dm, filled_cells * (1 - dm)))\n\t# for center_y, center_x, radius in no_duplicates:\n\t# \tcircy, circx = circle_perimeter(center_y, center_x, radius)\n\t# \tinput_binary_img[circy, circx] = 10\n\t# view_2d_img(input_binary_img)\n\n\ndef just_label(binary_image):\n\t'''\n\tJust labels a binary image (segments everything)\n\n\t:params binary_image: [np.ndarray] input image\n\t:return: [np.ndarray] segmented image\n\t'''\n\tlabeled_field, object_no = ndi.label(binary_image, structure = np.ones((3, 3)))\n\treturn labeled_field\n\n\ndef label_and_correct(binary_channel, pre_binary, min_px_radius = 10, max_px_radius = 100, min_intensity = 0, mean_diff = 10):\n\t\"\"\"\n\tLabelling of a binary image, with constraints on minimal feature size, minimal intensity of area\n\t covered by a binary label or minimal mean difference from background\n\n\t:param binary_channel: [np.ndarray] input image\n\t:param pre_binary: [np.ndarray] used to compute total intensity\n\t:param min_px_radius: [float] minimal feature size\n\t:param min_intensity: [float] minimal total intensity\n\t:param mean_diff: [float] minimal (multiplicative) difference from the background\n\t:return: [np.ndarray]\n\t\"\"\"\n\tlabeled_field, object_no = ndi.label(binary_channel, structure = np.ones((3, 3)))\n\n\t# prebinary_px = pre_binary.flatten()\n\t# n_bins = int(2 * iqr(prebinary_px) * (len(prebinary_px) ** (1/3)))\n\t# n, bin_edge = np.histogram(prebinary_px, n_bins)\n\t# peak_max_indx = np.argmax(n)\n\t# background_val = (bin_edge[peak_max_indx] + bin_edge[peak_max_indx + 1]) / 2\n\tbackground_mean = np.mean(pre_binary[labeled_field == 0])\n\tfor label in range(1, object_no+1):\n\t\tmask = labeled_field == label\n\t\tpx_radius = np.sqrt(np.sum((mask).astype(np.int8)))\n\t\ttotal_intensity = np.sum(pre_binary[mask])\n\t\tlabel_mean = np.mean(pre_binary[labeled_field == label])\n\t\tif px_radius < min_px_radius or total_intensity < min_intensity or label_mean < mean_diff * background_mean or px_radius > max_px_radius:\n\t\t\tlabeled_field[labeled_field == label] = 0\n\t# dbg.label_and_correct_debug(labeled_field)\n\treturn labeled_field\n\n\ndef cell_split(input_img, contours, min_area = 100, max_area = 3500, min_peri = 100, max_peri = 1500):\n\t'''\n\tFunction finds individual cluster of cells that have a contour fall within the bounds of area and perimeter\n\tand attempts to divide them by their constituents\n\n\t:param input_img: [np.ndarray] binary input image containing all segmented cells\n\t:param contours: [list] of [lists] a list of list of points for each of the contours for each cell\n\t:param min_area: [float] minimum acceptable area for a cell\n\t:param max_area: [float] max acceptable area for a cell\n\t:param min_peri: [float] minimum acceptable perimeter for a cell\n\t:param max_peri: [float] maximum acceptable perimeter for a cell\n\t:return: [np.ndarray] full image with cell clusters split\n\t'''\n\tprint(\"> Starting Cell Split\")\n\toutput = np.zeros_like(input_img)\n\toutput[input_img > 0] = 1\n\tfor item_contour in contours:\n\t\t# remove cells that have a low circumference or too high circumference\n\t\tcontour_len = item_contour.shape[0]\n\t\tcontour_img = binary_fill_holes(points2img(item_contour)).astype(int)\n\t\tcontour_area = sum(contour_img.flatten())\n\t\tif contour_len >= min_peri and contour_len <= max_peri and contour_area >= min_area and contour_area <= max_area:\n\t\t# if item_contour.shape[0] >= 100 and item_contour.shape[0] <= 350:\n\t\t\t# holding = points2img(item_contour)\n\t\t\t# holding_fill = binary_fill_holes(holding).astype(int)\n\t\t\t# if sum(holding_fill.flatten()) > 100:\n\t\t\tsplit_cells_mask = hough_num_circles(contour_img)\n\n\t\t\ttlx, tly, brx, bry = location(item_contour)\n\t\t\tif array_all_ones(split_cells_mask):\n\t\t\t\tfor x in xrange(tlx, brx + 1):\n\t\t\t\t\tfor y in xrange(tly, bry + 1):\n\t\t\t\t\t\toutput[y, x] = output[y, x] * split_cells_mask[y - tly, x - tlx]\n\t\t\t\t# output[tly - 1:bry + 1, tlx - 1:brx + 1] = output[tly - 1:bry + 1, tlx - 1:brx + 1] * split_cells_mask\n\t\t\t\t# montage_n_x((output,output[tly-1:bry+1,tlx-1:brx+1], split_cells_mask, output[tly-1:bry+1,tlx-1:brx+1] * split_cells_mask))\n\t\t\telse:\n\t\t\t\td_contour_img = dilation(contour_img, disk(1))\n\t\t\t\tspecific_mask = split_cells_mask + d_contour_img\n\t\t\t\tspecific_mask[specific_mask < 2] = 0\n\t\t\t\tspecific_mask[specific_mask >= 2] = 1\n\t\t\t\tfor x in xrange(tlx, brx + 1):\n\t\t\t\t\tfor y in xrange(tly, bry + 1):\n\t\t\t\t\t\toutput[y, x] = output[y, x] * (1- specific_mask[y - tly, x - tlx])\n\n\n\treturn label_and_correct(output, input_img)\n\n\ndef rm_eccentric(input_img, min_eccentricity, max_ecc, min_area, max_area):\n\t'''Evaluates the eccentricity of single cells within an image with multiple cells, and throws away any cells that exhibit odd eccentricity\n\tAlso chucks any cells that have an area larger than max_area\n\n\t:param input_img: [np.ndarray] segmented binary image\n\t:param min_eccentricity: [float] minimum acceptable eccentricity\n\t:param max_area: [float] maximum area acceptable for a cell\n\t'''\n\n\tmax_cells = np.amax(input_img.flatten())\n\toutput_img = copy.deepcopy(input_img)\n\tfor x in xrange(max_cells):\n\t\tmask = np.zeros_like(input_img)\n\t\tmask[output_img == x + 1] = 1\n\n\t\t_, area, _, eccentricity = get_contour_details(mask)\n\n\t\tif eccentricity < min_eccentricity or eccentricity > max_ecc and area < min_area or area > max_area:\n\t\t\toutput_img[output_img == x + 1] = 0\n\treturn output_img\n\n\ndef improved_watershed(binary_base, intensity, expected_separation = 10):\n\t\"\"\"\n\tImproved watershed method that takes in account minimum intensity as well as minimal size of\n\tseparation between the elements\n\tBorrowed from Andrei's Imagepipe\n\n\t:param binary_base: [np.ndarray] support for watershedding\n\t:param intensity: [np.ndarray] intensity value used to exclude watershed points with too low of intensity\n\t:param expected_separation: [float] expected minimal separation (in pixels) between watershed centers\n\t:return: [np.ndarray]\n\t\"\"\"\n\tprint(\"> Performing Improved Watershed\")\n\t# sel_elem = disk(2)\n\t#\n\t# # changed variable name for \"labels\"\n\t# post_closing_labels = closing(binary_base, sel_elem)\n\n\tdistance = ndi.distance_transform_edt(binary_base)\n\tlocal_maxi = peak_local_max(distance,\n\t\t\t\t\t\t\t\tindices = False, # we want the image mask, not peak position\n\t\t\t\t\t\t\t\tmin_distance = expected_separation, # about half of a bud with our size\n\t\t\t\t\t\t\t\tthreshold_abs = 10, # allows to clear the noise\n\t\t\t\t\t\t\t\tlabels = binary_base)\n\t# we fuse the labels that are close together that escaped the min distance in local_maxi\n\tlocal_maxi = ndi.convolve(local_maxi, np.ones((5, 5)), mode = 'constant', cval = 0.0)\n\t# finish the watershed\n\tstruct = np.ones((3, 3))\n\tstruct[0,0] = 0\n\tstruct[0,2] = 0\n\tstruct[2,0] = 0\n\tstruct[2,2] = 0\n\texpanded_maxi_markers = ndi.label(local_maxi, structure = struct)[0]\n\tsegmented_cells_labels = watershed(-distance, expanded_maxi_markers, mask = binary_base)\n\n\tunique_segmented_cells_labels = np.unique(segmented_cells_labels)\n\tunique_segmented_cells_labels = unique_segmented_cells_labels[1:]\n\taverage_apply_mask_list = []\n\t# Gimick fix\n\t# intensity_array = intensity * np.ones_like(segmented_cells_labels)\n\tfor cell_label in unique_segmented_cells_labels:\n\t\tmy_mask = segmented_cells_labels == cell_label\n\t\tapply_mask = segmented_cells_labels[my_mask]\n\t\taverage_apply_mask = np.mean(intensity[my_mask])\n\t\tif average_apply_mask < 0.005:\n\t\t\taverage_apply_mask = 0\n\t\t\tsegmented_cells_labels[segmented_cells_labels == cell_label] = 0\n\t\taverage_apply_mask_list.append(average_apply_mask)\n\t# x_labels = ['cell13', 'cell1', 'cell7', 'cell2', 'cell14', 'cell6', 'cell3', 'cell5', 'cell4', 'cell11', 'cell12', 'cell8', 'cell10', 'cell9']\n\t# dbg.improved_watershed_debug(segmented_cells_labels, intensity)\n\t# dbg.improved_watershed_plot_intensities(x_labels, average_apply_mask_list.sort())\n\treturn segmented_cells_labels\n\n\ndef get_contour_details(input_img):\n\t'''\n\tInput image must have only one cell in it with one contour, function extracts\n\tarea, perimeter, radius, eccentricity from a given cell. radius is an\n\tapproximation, assuming the cell is circular\n\t:param input_img: input image (binary) of just a single cell. Cannot contain\n\t\t\t\t\t\tmultiple cells or multiple contours\n\t:return: radius, area, perimeter, and eccentricity in that order\n\t'''\n\tcontours = measure.find_contours(input_img,\n\t\t\t\t\t\t\t\t\t\tlevel = 0.5,\n\t\t\t\t\t\t\t\t\t\tfully_connected = 'low',\n\t\t\t\t\t\t\t\t\t\tpositive_orientation = 'low')\n\tPoint_set = Point_set2D(contours[0])\n\tradius = (Point_set.shoelace() / math.pi) ** 0.5\n\teccentricity = (4 * math.pi * Point_set.shoelace()) / (Point_set.perimeter() ** 2)\n\treturn radius, Point_set.shoelace(), Point_set.perimeter(), eccentricity\n\n\ndef hist_peak(image):\n\t'''\n\tReturns the peak histogram count for a given image\n\n\t:param image: 2d-3d image for generating histogram map\n\t:return: peak histogram value\n\t'''\n\tpx_dataset = image.flatten()\n\tn_bins = int(2 * iqr(px_dataset) * (len(px_dataset)) ** (1/3))\n\tn, bin_edges = np.histogram(px_dataset, n_bins)\n\tpeak_max_indx = np.argmax(n)\n\treturn (bin_edges[peak_max_indx] + bin_edges[peak_max_indx]) / 2\n\n\ndef get_bounding_img(binary_img, condition):\n\t'''\n\tGiven a binary image, reduces the image down to the size where it only isolates the binary elements.\n\tBinary features must be presented as greater than 0 in a numpy array (2d and 3d compatible)\n\t:param binary_img: [np.ndarray] Image before reduction\n\t:return: [np.ndarray] reduced minimum bounding box image\n\t'''\n\tdims = len(binary_img.shape)\n\tpos_coord = np.where(binary_img == condition)\n\tmins = np.amin(pos_coord, axis = 1)\n\tmaxs = np.amax(pos_coord, axis = 1) + 1\n\n\tif dims == 3:\n\t\tz_min = mins[0]\n\t\tz_max = maxs[0]\n\t\tx_min = mins[1]\n\t\tx_max = maxs[1]\n\t\ty_min = mins[2]\n\t\ty_max = maxs[2]\n\t\treturn binary_img[z_min:z_max, x_min:x_max, y_min:y_max]\n\telif dims == 2:\n\t\tx_min = mins[1]\n\t\tx_max = maxs[1]\n\t\ty_min = mins[2]\n\t\ty_max = maxs[2]\n\t\treturn binary_img[x_min:x_max, y_min:y_max]\t\n\telse:\n\t\traise ValueError\n\n\ndef write_stats(before_image, after_image, UID, filename, read_path, write_path, img_type = \"cell\"):\n\t'''\n\tGiven two segmented binary images, determine the difference between the\n\tcells present on both images and save differences and cell stats to a file\n\t:param before_image: [np.ndarray] Image before cell deletion or addition\n\t:param after_image: [np.ndarray] Image after cell deletion or addition\n\t:param UID: [str] unique UID for the image, should be the same between the two Images\n\t:param filename: [str] name of the datafile to be written to\n\t:param write_path: [str] location of the datafile containing data\n\t'''\n\twrite_file = open(os.path.join(write_path, filename),'a')\n\t# write_file.write(\"cell\\tUID\\tcell_num\\tcell_updated_num\\tdeleted\\tRadius\\tArea\\tPerimeter\\tEccentricity\\tread_path\\n\")\n\tdeletion = True\n\tbefore_cells = np.amax(before_image.flatten())\n\tafter_cells = np.amax(after_image.flatten())\n\tif after_cells > before_cells:\n\t\tdeletion = False\n\tmax_cells = np.maximum(before_cells, after_cells)\n\tfor cell_index in xrange(max_cells):\n\t\tcurrent_label = cell_index + 1\n\t\tafter_label = current_label\n\t\tif deletion:\n\t\t\tmask = np.zeros_like(before_image)\n\t\t\tmask[before_image == current_label] = current_label\n\t\telse:\n\t\t\tmask = np.zeros_like(after_image)\n\t\t\tmask[after_image == current_label] = current_label\n\t\tradius, area, perimeter, E = get_contour_details(mask)\n\t\tcell_isolation = after_image * mask\n\n\t\tcell_delete = False\n\t\tif np.amax(cell_isolation.flatten()) != current_label:\n\t\t\tif np.amax(cell_isolation.flatten()) == 0:\n\t\t\t\tafter_label = 0\n\t\t\t\tcell_delete = True\n\t\t\telse:\n\t\t\t\tafter_label = int(np.amax(cell_isolation.flatten()) / current_label)\n\t\twrite_file.write(\"{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n\".format(img_type,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUID,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurrent_label,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tafter_label,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcell_delete,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tradius,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tarea,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tperimeter,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tE,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tread_path))\n\twrite_file.close()\n\n\ndef global_max(img_2d):\n\t'''Returns the maximum pixel value within a 2-3d image'''\n\treturn np.amax(img_2d.flatten())\n\n\ndef global_min(img_2d):\n\t'''\n\tReturns the minimum pixel value within a 2-3d image\n\t'''\n\treturn np.amin(img_2d.flatten())\n\n\ndef properties(image):\n\t'''Prints some of an image's properties into the console directly'''\n\tprint(\">Image Properties\")\n\tprint(\"Dimensions: {}\".format(image.shape))\n\tprint(\"Format: {}\".format(image.dtype.name))\n\tprint(\"Global Max: {}\\tGlobal Min: {}\".format(global_max(image), global_min(image)))\n\n\ndef euclid_dist_nD(p0, p1):\n\treturn np.sum((p1 - p0) ** 2) ** 0.5\n\n\nclass Point_set2D(object):\n\tdef __init__(self, point_list):\n\t\tself.point_list = np.array([[float(coordinate) for coordinate in point] for point in point_list])\n\n\n\tdef num_pts(self):\n\t\treturn len(self.point_list)\n\n\n\tdef center_mass(self):\n\t\treturn np.sum(self.point_list, 0) / self.num_pts()\n\n\n\tdef perimeter(self):\n\t\tperi_distance = 0\n\t\tfor pt_indx in xrange(self.num_pts()):\n\t\t\tperi_distance += euclid_dist_nD(self.point_list[pt_indx],\n\t\t\t\t\t\t\t\t\t\t\tself.point_list[pt_indx - 1])\n\t\treturn peri_distance\n\n\n\tdef shoelace(self):\n\t\tarea = 0\n\t\tfor pt in xrange(len(self.point_list)):\n\t\t\tarea += self.point_list[pt - 1][0] * self.point_list[pt][1]\n\t\t\tarea -= self.point_list[pt - 1][1] * self.point_list[pt][0]\n\t\treturn abs(area) / 2.0\n","sub_path":"lib/processing.py","file_name":"processing.py","file_ext":"py","file_size_in_byte":28190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"481823284","text":"## Data Extraction ##\n\nimport numpy as np\nimport h5py\n\n# Finding Specific Tissue\ndef findSpecificTissue(folder_name,tissue,testing_label):\n\n data = h5py.File(folder_name + tissue + '.mat')\n label_map = np.array(data[testing_label])\n RamanMap = np.array(data['map_t' + tissue])\n\n return label_map,RamanMap\n\n# Finding the unique keys for all the tissue files - to identify callable keys when pre-processing data\ndef findUniqueKeys(folder_name):\n\n unique_keys = []\n\n for x in range(3,72):\n\n # For the tissues with only a single task\n try:\n mat = h5py.File(folder_name + str(x) + '.mat')\n\n for item in list(mat.keys()):\n unique_keys.append(item)\n\n except OSError:\n print(x, 'OSError')\n\n except KeyError:\n print(x, 'KeyError')\n\n # For the tissues with multiple task\n try:\n\n for y in range(1,3):\n mat = h5py.File(folder_name + str(x) + '.mat')\n\n for item in list(mat.keys()):\n unique_keys.append(item)\n\n except OSError:\n print(x, y, 'OSError')\n\n except KeyError:\n print(x, y, 'KeyError')\n\n return np.unique(unique_keys)\n\n# Given an input key, this function will return the tissues which contain that key\ndef findTissue(folder_name,key):\n\n tissue = []\n\n for x in range(3,72):\n\n try:\n mat = h5py.File(folder_name + str(x) + '.mat')\n\n if key in list(mat.keys()):\n tissue.append()\n\n except OSError:\n print(x, 'OSError')\n\n except KeyError:\n print(x, 'KeyError')\n\n return tissue\n\n# This function converts the ones in the matrix to the index - to be one hot encoded later\ndef convert(matrix,index):\n\n for x in range(matrix.shape[0]):\n for y in range(matrix.shape[1]):\n if matrix[x,y] == 1:\n matrix[x,y] = index\n\n return matrix\n\n# Returns 3 lists - Map of labels indicated , Raman Data, Tissues Used\n# Map of label - in the form of a list of 2D matrices\n# Raman Data - in the form of a list of 3D matrices\ndef preProcessAllLabels(folder_name):\n\n # Initializing variables\n known_labels = ['bcc','dermis','epi']\n label = []\n RamanData = []\n tissues_used = []\n\n for x in range(3, 72):\n\n for y in range(0,3):\n\n if y == 0:\n folder_number = str(x)\n\n else:\n folder_number = str(x) + '_' + str(y)\n\n try:\n # Opening file and obtaining keys\n mat = h5py.File(folder_name + folder_number + '.mat')\n keys = list(mat.keys())\n\n # Checking just for aforementioned keys in all the files\n present_labels = [item for item in keys if item in known_labels]\n\n # # Only if bcc is within the image do we take the rest of the data\n # if 'bcc' in present_labels:\n\n label_map = np.zeros(mat[present_labels[0]].shape)\n\n for key in present_labels:\n\n if key == 'bcc':\n\n temp = convert(np.array(mat[key]), 1)\n label_map = label_map + temp\n\n elif key == 'dermis':\n\n temp = convert(np.array(mat[key]),2)\n label_map = label_map + temp\n\n elif key == 'epi':\n\n temp = convert(np.array(mat[key]),3)\n label_map = label_map + temp\n\n\n RamanMap = np.array(mat['map_t' + folder_number])\n\n # Cheking for dimension mismatch\n # If there is no dimension mismatch organise data to be raman input and BCC/NonBCC cell output\n if label_map.shape[0] == RamanMap.shape[1] and label_map.shape[1] == RamanMap.shape[2]:\n label.append(label_map)\n RamanData.append(RamanMap)\n tissues_used.append(folder_number)\n\n except OSError:\n print(x, OSError)\n\n # This is due to the tissue not having any of the keys\n except KeyError:\n print(x, KeyError)\n\n except IndexError:\n print(x, IndexError)\n\n # This error is due to different keys having different shapes\n except ValueError:\n print(x, ValueError)\n\n return label, RamanData, tissues_used\n\n\n# This is for the tissues with multiple tasks\n# Returns 3 lists - Map of Label, Raman Data, Tissues Used\n# Map of Label - in the form of a list of 2D matrices\n# Raman Data - in the form of a list of 3D matrices\ndef preProcessBCC(folder_name,testing_label):\n\n # Initializing variables\n label = []\n RamanData = []\n tissues_used = []\n\n for x in range(3, 72):\n\n for y in range(0,3):\n\n if y == 0:\n folder_number = str(x)\n\n else:\n folder_number = str(x) + '_' + str(y)\n\n try:\n # Opening file and obtaining keys\n mat = h5py.File(folder_name + folder_number +'.mat')\n keys = list(mat.keys())\n\n # Checking just for BCC data in all the files\n if testing_label in keys:\n label_map = np.array(mat[testing_label])\n RamanMap = np.array(mat['map_t' + folder_number])\n\n else:\n continue\n\n # Cheking for dimension mismatch\n # If there is no dimension mismatch organise data to be raman input and BCC/NonBCC cell output\n if label_map.shape[0] == RamanMap.shape[1] and label_map.shape[1] == RamanMap.shape[2]:\n label.append(label_map)\n RamanData.append(RamanMap)\n tissues_used.append(folder_number)\n\n except OSError:\n print(x, 'OSError')\n\n except KeyError:\n print(x, 'KeyError')\n\n except IndexError:\n print(x, 'IndexError')\n\n return label, RamanData, tissues_used","sub_path":"Algorithms/process_data/obtaining_data.py","file_name":"obtaining_data.py","file_ext":"py","file_size_in_byte":6131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"639976605","text":"from generator import random_handler as ran\nimport sympy as sym\nimport math\nimport random\nfrom generator import constants_conversions as c\nfrom mathsub import differential_calculus_engine as engine\nfrom mathsub import algebra_engine\n\nx, y, z, t = sym.symbols('x y z t', real = True)#generic variables\n\ndef ask():\n ask_words = ['Find', 'Determine', 'Calculate', 'Compute', 'Evaluate']\n return random.choice(ask_words)\n\ndef parse(string_input):\n string_input = str(string_input)\n return string_input.replace('**', '^').replace('*', ' ') \n\n\n\nclass continuity_piecewise_function_linear_linear():\n def __init__(self):\n\n piecewise = engine.ContinuousPiecewise()\n piecewise.init_random(parts = 2, type = 'line.line')\n\n self.question = f\"\"\"The piecewise function {piecewise.function} is continuous. Determine the values inside the function that makes the function continuous.\"\"\"\n self.answer = f\"\"\"ANSWERS GENERATED ABOVE\"\"\"\n\nclass continuity_piecewise_function_parabola_linear():\n def __init__(self):\n\n piecewise = engine.ContinuousPiecewise()\n piecewise.init_random(parts = 2, type = 'parabola.line')\n\n self.question = f\"\"\"The piecewise function {piecewise.function} is continuous. Determine the values inside the function that makes the function continuous.\"\"\"\n self.answer = f\"\"\"ANSWERS GENERATED ABOVE\"\"\"\n\nclass discontinuity_piecewise_function_point():\n def __init__(self):\n\n piecewise = engine.PointDiscontinuity()\n piecewise.init_random()\n\n self.question = f\"\"\"Identify what type of discontinuity the function {piecewise.function} has.\"\"\"\n self.answer = f\"\"\"{piecewise.type}, discontinuous at x = {piecewise.point_of_discontinuity}\"\"\"\n\nclass discontinuity_piecewise_function_jump():\n def __init__(self):\n\n piecewise = engine.JumpDiscontinuity()\n piecewise.init_random()\n\n self.question = f\"\"\"Identify what type of discontinuity the function {piecewise.function} has.\"\"\"\n self.answer = f\"\"\"{piecewise.type}, discontinuous at x = {piecewise.point_of_discontinuity} with a magnitude of {piecewise.magnitude}.\"\"\"\n\n# class first_derivative_explicit():\n# def __init__(self):\n\n# problem = engine.DerivativeExplicit()\n# problem.init_random()\n\n# self.question = f\"\"\"Differentiate {problem.function_string}.\"\"\"\n# self.answer = f\"\"\"{problem.derivative()}\"\"\"\n\nclass Derivative_explicit():\n def __init__(self):\n BATTERIES = []\n CHOICES = []\n suffix = ''\n prefix = ''\n for i in range(4):\n #battery = engine.Some_class_from_engine\n battery = engine.Derivative_explicit()\n #data = battery.Some_attribute_from_battery \n data = parse(battery.derivative())\n BATTERIES.append(battery)\n CHOICES.append(prefix + str(data) + suffix) \n main = BATTERIES[0]\n CHOICES[0] = str(CHOICES[0]) + ' #'\n random.shuffle(CHOICES)\n #edit below\n self.question = f\"\"\"{ask()} the first derivative of the function f(x) = {parse(main.function)}.\"\"\"\n\n self.answer = f\"\"\"A. {CHOICES[0]}\nB. {CHOICES[1]}\nC. {CHOICES[2]}\nD. {CHOICES[3]}\"\"\" \n\nclass first_derivative_explicit_yofx_xoft_dydt():\n def __init__(self):\n\n problem = engine.DerivativeExplicit_yofx_xoft_dydt()\n problem.init_random()\n\n self.question = f\"\"\"If y(x) = {problem.y_of_x} and x(t) = {problem.x_of_t}, determine the value of dy/dt at t = {problem.t}.\"\"\"\n self.answer = f\"\"\"{problem.dydt_at_t}\"\"\"\n\nclass first_derivative_explicit_xoft_yoft_dydx():\n def __init__(self):\n\n problem = engine.DerivativeExplicit_xoft_yoft_dydx()\n problem.init_random()\n\n self.question = f\"\"\"If x(t) = {problem.x_of_t}, and y(t) = {problem.y_of_t}, determine the value of dy/dx at t = {problem.t}.\"\"\"\n self.answer = f\"\"\"{problem.dydx_at_t}\"\"\"\n\nclass first_derivative_implicit():\n def __init__(self):\n\n problem = engine.DerivativeImplicit_Bivariable()\n problem.init_random()\n\n self.question = f\"\"\"For the function {problem.expression} = 0, determine the value of dy/dx.\"\"\"\n self.answer = f\"\"\"{problem.dydx}\"\"\"\n\nclass second_derivative_implicit():\n def __init__(self):\n\n problem = engine.DerivativeImplicit_Bivariable()\n problem.init_random()\n\n self.question = f\"\"\"For the function {problem.expression} = 0, determine the value of d^2y/dx^2.\"\"\"\n self.answer = f\"\"\"{problem.dydx}\"\"\"\n\nclass tangent_line_from_conic_section():\n def __init__(self):\n\n problem = engine.TangentLine_from_ConicSection()\n problem.init_random()\n\n self.question = f\"\"\"For the graph of the function {problem.general_string}, determine the equation of the line tangent to the curve at the point {problem.point_of_tangency.string}.\"\"\"\n self.answer = f\"\"\"{problem.tangent_line.string}\"\"\"\n\nclass normal_line_from_conic_section():\n def __init__(self):\n\n problem = engine.NormalLine_from_ConicSection()\n problem.init_random()\n\n self.question = f\"\"\"For the graph of the function {problem.general_string}, determine the equation of the line normal to the curve at the point {problem.point_of_tangency.string}.\"\"\"\n self.answer = f\"\"\"{problem.normal_line.string}\"\"\"\n\nclass polynomial_critical_numbers():\n def __init__(self):\n tryagain = True\n while tryagain:\n try:\n problem = engine.RelativeExtrema_Polynomials()\n problem.init_random()\n\n WORDING_LIST = ['critical points', 'relative extrema']\n\n self.question = f\"\"\"Determine the {random.choice(WORDING_LIST)} of the function f(x) = {problem.polynomial.expression}.\"\"\"\n \n points_string = \"\"\n\n for i in range(len(problem.critical_points)):\n points_string = points_string + problem.critical_points[i].string + ' '\n\n self.answer = f\"\"\"{points_string}\"\"\"\n tryagain = False\n except:\n pass\n\nclass polynomial_relative_maxima():\n def __init__(self):\n tryagain = True\n while tryagain:\n try:\n problem = engine.RelativeExtrema_Polynomials()\n problem.init_random()\n\n\n self.question = f\"\"\"Determine the relative maxima of the function f(x) = {problem.polynomial.expression}.\"\"\"\n \n points_string = \"\"\n\n for i in range(len(problem.relative_maxima)):\n points_string = points_string + problem.relative_maxima[i].string + ' '\n\n self.answer = f\"\"\"{points_string}\"\"\" \n tryagain = False\n except:\n tryagain = True \n\nclass polynomial_relative_minima():\n def __init__(self):\n\n problem = engine.RelativeExtrema_Polynomials()\n problem.init_random()\n\n\n self.question = f\"\"\"Determine the relative minima of the function f(x) = {problem.polynomial.expression}.\"\"\"\n \n points_string = \"\"\n\n for i in range(len(problem.relative_minima)):\n points_string = points_string + problem.relative_minima[i].string + ' '\n\n self.answer = f\"\"\"{points_string}\"\"\" \n\nclass polynomial_increasing_interval():\n def __init__(self):\n\n problem = engine.RelativeExtrema_Polynomials()\n problem.init_random()\n\n\n self.question = f\"\"\"Determine the interval that the function f(x) = {problem.polynomial.expression} is increasing\"\"\"\n \n self.answer = f\"\"\"{problem.interval_increasing}\"\"\"\n\nclass polynomial_decreasing_interval():\n def __init__(self):\n\n problem = engine.RelativeExtrema_Polynomials()\n problem.init_random()\n\n\n self.question = f\"\"\"Determine the interval that the function f(x) = {problem.polynomial.expression} is decreasing\"\"\"\n \n self.answer = f\"\"\"{problem.interval_decreasing}\"\"\"\n\nclass product_of_two_numbers_x_y():\n def __init__(self):\n\n problem = engine.ProductOfTwoNumbers_x_y()\n problem.init_random()\n\n\n self.question = f\"\"\"Among those positive real numbers u and v whose sum is {problem.sum_of_numbers}, find the choice of u and v that makes their product P as much as possible\"\"\"\n \n self.answer = f\"\"\"{problem.number1}, {problem.number2}\"\"\" \n\nclass product_of_two_numbers_xsquared_y():\n def __init__(self):\n\n problem = engine.ProductOfTwoNumbers_xsquared_y()\n problem.init_random()\n\n\n self.question = f\"\"\"Divide the number {problem.sum_of_numbers} into two parts such that the product P of one part and the square of the other is a maximum.\"\"\"\n \n self.answer = f\"\"\"{problem.number1}, {problem.number2}\"\"\" \n\nclass paper_with_margins():\n def __init__(self):\n\n paper = engine.PaperWithMargins()\n paper.init_random()\n\n self.question = f\"\"\"A sheet of paper for a poster is to be {paper.area} cm^2 in area. The margins at the top and bottom are to be {paper.margin_length_one_side} cm and at the sides to be {paper.margin_width_one_side} cm. What should be the dimensions of the sheet to maximize the printed area?\"\"\"\n self.answer = f\"\"\"{paper.length} cm x {paper.width} cm\"\"\"\n\nclass ships_moving_at_axis():\n def __init__(self):\n\n ships = engine.MovingAtAxis()\n ships.init_random()\n\n self.question = f\"\"\"At t = 0, Ship B is {ships.B_initial_distance_from_A} miles due east of another ship A. Ship B is then sailing due west at {ships.B_velocity} miles per hpour, and A is sailing due south at {ships.A_velocity} miles per hour. If they continue on their respective courses, when will they be nearest one another, and how near?\"\"\"\n self.answer = f\"\"\"{ships.time_nearest} hours, {ships.distance_nearest} miles\"\"\"\n\nclass can_with_minimum_area_open():\n def __init__(self):\n\n can = engine.CanWithMinimumArea_Open()\n can.init_random()\n\n self.question = f\"\"\"A cylinder container with circular base is to hold {can.volume} cm^3. Find its dimensions so that the amount (surface area) of metal required is minimum when the container is an open can.\"\"\"\n self.answer = f\"\"\"radius: {can.radius} cm, height: {can.height} cm\"\"\"\n\n\nclass can_with_minimum_area_closed():\n def __init__(self):\n\n can = engine.CanWithMinimumArea_Closed()\n can.init_random()\n\n self.question = f\"\"\"A cylinder container with circular base is to hold {can.volume} cm^3. Find its dimensions so that the amount (surface area) of metal required is minimum when the container is an closed can.\"\"\"\n self.answer = f\"\"\"radius: {can.radius} cm, height: {can.height} cm\"\"\"\n \nclass manufacturing_items():\n def __init__(self):\n\n plant = engine.Manufacturing()\n plant.init_random()\n\n self.question = f\"\"\"The total cost of producing x radio sets per day is PHP {plant.cost_function}, and the price per set at which they may be sold is PHP {plant.price_function}. What should be the daily output to obtain a maximum total profit?\"\"\"\n\n self.answer = f\"\"\"{plant.items_at_profit_max} items\"\"\"\n\n\nclass man_in_rowboat():\n def __init__(self):\n\n boat = engine.ManInRowBoat()\n boat.init_random()\n\n self.question = f\"\"\"A man in a rowboat at P, {boat.PA_distance} miles from the nearest point A on a straight shorem wishes to reach a point B, {boat.AB_distance} miles from A along the shore, in shortest time. Where should he land if he can row {boat.row_speed} miles per hour and walk {boat.walk_speed} miles per hour?\"\"\"\n\n self.answer = f\"\"\"{boat.distance_at_time_smallest} miles from point A, {boat.time_smallest} hours\"\"\"\n\nclass rectangular_fence():\n def __init__(self):\n\n fence = engine.RectangularFence()\n fence.init_random()\n\n self.question = f\"\"\"A given rectangular area that is {fence.area} m^2 is to be fenced off in a field that lies along a stright river. If no fencing is need along the river, determine the least amount of fencing required.\"\"\"\n self.answer = f\"\"\"{fence.perimeter} m\"\"\"\n\nclass wall_and_beam_and_building():\n def __init__(self):\n\n structure = engine.WallAndBuilding()\n structure.init_random()\n\n self.question = f\"\"\"A wall of a building is to be braced by a beam that must pass over parallel wall {structure.wall_height} ft high and {structure.wall_distance} ft from the building. Find the length of the shortest beam that can be used.\"\"\"\n self.answer = f\"\"\"{structure.beam_length} ft\"\"\"\n\n\n\n#some new codes -----\nclass Constructor():\n def __init__(self, engine_class_instances):\n #Battery - a single instance of a set of givens, and an answer for a certain problem\n\n BATTERIES = []\n CHOICES = []\n suffix = ''\n prefix = ''\n for i in range(4):\n\n #battery = engine.Some_class_from_engine\n battery = engine_class_instances[i]\n\n #data = battery.Some_attribute_from_battery \n data = parse(battery.answer)\n\n BATTERIES.append(battery)\n CHOICES.append(prefix + str(data) + suffix) \n main = BATTERIES[0]\n CHOICES[0] = str(CHOICES[0]) + ' #'\n random.shuffle(CHOICES)\n #edit below\n self.question = main.question\n self.answer = f\"\"\"A. {CHOICES[0]}\nB. {CHOICES[1]}\nC. {CHOICES[2]}\nD. {CHOICES[3]}\"\"\" \n\nclass first_derivative():\n def __init__(self):\n instance_list = [\n engine.first_derivative(), \n engine.first_derivative(),\n engine.first_derivative(),\n engine.first_derivative() \n ]\n constructed = Constructor(instance_list)\n self.question = constructed.question\n self.answer = constructed.answer \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"mathsub/differential_calculus.py","file_name":"differential_calculus.py","file_ext":"py","file_size_in_byte":14089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"521463828","text":"from pi_trees_ros.pi_trees_ros import *\nfrom pi_trees_lib.task_setup import *\n\nimport GlobalData\nimport CheckRefboxCommand\nimport SkillBook\nimport InPlay\n\n\nclass KickoffEnemy(Selector):\n def __init__(self, name):\n super(KickoffEnemy , self).__init__(name)\n\n self.prepare = Prepare('Prepare enemy kickoff')\n self.execute = Execute('Execute enemy kickoff')\n\n # add parent tasks\n self.add_child(self.prepare)\n self.add_child(self.execute)\n\nclass Prepare(ParallelAll):\n def __init__(self, name):\n super(Prepare, self).__init__(name)\n\n self.is_kickoff_enemy = CheckRefboxCommand.IsKICKOFF_ENEMY('Is Kickoff enemy')\n self.defence = SkillBook.StayAroundBall('Stay Around Ball')\n\n self.add_child(self.is_kickoff_enemy)\n self.add_child(self.defence)\n\nclass Execute(ParallelAll):\n def __init__(self, name):\n super(Execute, self).__init__(name)\n\n self.is_normal_start = CheckRefboxCommand.IsNORMAL_START('is_normal_start')\n self.move = Move('Move')\n\n self.add_child(self.is_normal_start)\n self.add_child(self.move)\n\nclass Move(Sequence):\n def __init__(self, name):\n super(Move, self).__init__(name)\n\n self.wait_inplay = SkillBook.WaitInplay('wait inplay')\n self.stay = SkillBook.StayAroundBall('StayAroundBall')\n\n self.positioning = ParallelSelector('positioning')\n self.positioning.add_child(self.wait_inplay)\n self.positioning.add_child(self.stay)\n\n self.inplay = InPlay.InPlay('inplay')\n\n self.add_child(self.positioning)\n self.add_child(self.inplay)\n","sub_path":"roots_decision_making/scripts/KickoffEnemy.py","file_name":"KickoffEnemy.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"132220515","text":"from django.conf.urls import url\nfrom .views import (CreateBlogAPIView, UpdateBlogStatusAPIView, SelfBlogListView, BlogListView, GetBlogDetailsAPIView)\n\nurlpatterns = [\n url('createBlog', CreateBlogAPIView.as_view()),\n url('updateBlog/(?P.+)', UpdateBlogStatusAPIView.as_view()),\n url('getSelfBlogList', SelfBlogListView.as_view()),\n url('getBlogList', BlogListView.as_view()),\n url('getBlogDetails/(?P.+)', GetBlogDetailsAPIView.as_view())\n]\n","sub_path":"django_blog_session/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"290384566","text":"__author__ = 'Igor Maculan '\nimport logging\n\nfrom pushbullet import Listener, PushBullet\n\n\nlogging.basicConfig(level=logging.DEBUG)\n\nAPI_KEY = '' # YOUR API KEY\n\nHTTP_PROXY_HOST = None\nHTTP_PROXY_PORT = None\n\n\ndef on_push(message):\n print ('received push:' + str(message))\n\ndef main():\n\tpb = PushBullet(API_KEY)\n\ts = Listener(pb,on_push = on_push, http_proxy_host=HTTP_PROXY_HOST, http_proxy_port=HTTP_PROXY_PORT)\n\ttry:\n\t\ts.run_forever()\n\texcept KeyboardInterrupt:\n\t\ts.close()\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"example/listener_example.py","file_name":"listener_example.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"574625933","text":"from tkinter import *\r\nfrom tkinter import font, colorchooser, filedialog, messagebox, ttk\r\nimport os\r\nfrom fpdf import FPDF\r\n\r\nmain_application=Tk()\r\nmain_application.geometry('1200x800')\r\nmain_application.title('Vinayak Text Editor')\r\nmain_application.iconbitmap('icons2/v.ico')\r\n\r\n\r\n#*********************Main Menu****************************\r\nmain_menu=Menu()\r\n\r\n#Code for printing File icons\r\nnew_icon=PhotoImage(file='icons2/new.png')\r\nopen_icon=PhotoImage(file='icons2/open.png')\r\nsave_icon=PhotoImage(file='icons2/save.png')\r\nsave_as_icon=PhotoImage(file='icons2/save_as.png')\r\npdf_icon=PhotoImage(file='icons2/pdf.png')\r\nexit_icon=PhotoImage(file='icons2/exit.png')\r\n\r\n#Write as many terms as to be shown in the main menu bar\r\nfile=Menu(main_menu, tearoff=False) #iF tearoff flase not used, then it can be make apart from the text editor by clicking on the line shown in GUI\r\n\r\n\r\n\r\n#Code for adding edit icons\r\ncut_icon=PhotoImage(file='icons2/cut.png')\r\ncopy_icon=PhotoImage(file='icons2/copy.png')\r\npaste_icon=PhotoImage(file='icons2/paste.png')\r\nclear_all_icon=PhotoImage(file='icons2/clear_all.png')\r\nfind_icon=PhotoImage(file='icons2/find.png') #Can add undo, redoo later on\r\n\r\n\r\nedit=Menu(main_menu, tearoff=False)\r\n\r\n#Code for adding view icons\r\ntoolbar_icon=PhotoImage(file='icons2/tool_bar.png')\r\nstatusbar_icon=PhotoImage(file='icons2/status_bar.png')\r\n\r\nview=Menu(main_menu, tearoff=False)\r\n\r\n#Code for adding theme icons\r\nlight_default_icon=PhotoImage(file='icons2/light_default.png')\r\nlight_plus_icon=PhotoImage(file='icons2/light_plus.png')\r\ndark_icon=PhotoImage(file='icons2/dark.png')\r\nred_icon=PhotoImage(file='icons2/red.png')\r\nmonokai_icon=PhotoImage(file='icons2/monokai.png')\r\nnight_blue_icon=PhotoImage(file='icons2/night_blue.png')\r\nyellow_icon=PhotoImage(file='icons2/yellow.png')\r\n\r\ncolor_theme=Menu(main_menu, tearoff=False)\r\ntheme_choice=StringVar()\r\n\r\n#Code for adding color commands\r\ncolor_icons=(light_default_icon, light_plus_icon, dark_icon, red_icon, monokai_icon, night_blue_icon, yellow_icon)\r\n\r\ncolor_dict={\r\n 'Light Default':('#000000', '#ffffff'),\r\n 'Light Plus': ('#474747', '#e0e0e0'),\r\n 'Dark': ('#c4c4c4', '2d2d2d'),\r\n 'Red': ('#2d2d2d', '#ffe8e8'),\r\n 'Monokai': ('#d3b774', '#474747'),\r\n 'Night Blue': ('#ededed', '#6b9dc2'),\r\n 'Yellow': ('#ffff00', '#000000')\r\n}\r\n\r\n#Cascade all these (for displaying it on GUI)\r\nmain_menu.add_cascade(label='File', menu=file)\r\nmain_menu.add_cascade(label='Edit', menu=edit)\r\nmain_menu.add_cascade(label='View', menu=view)\r\nmain_menu.add_cascade(label='Color Theme', menu=color_theme)\r\n\r\n#*********************Main Menu End************************\r\n\r\n#*********************Toolbar****************************\r\n\r\ntool_bar=Label(main_application)\r\ntool_bar.pack(side=TOP, fill=X) #For filling screen horizontally, fill=X, filling vertically, fill=Y, filling both, fill=both\r\n\r\n#Setting font style\r\nfont_tuples=font.families()\r\nfont_family=StringVar()\r\nfont_box=ttk.Combobox(tool_bar, width=30, textvariable=font_family, state='readonly')\r\nfont_box['values']=font_tuples\r\nfont_box.current(font_tuples.index('Arial'))\r\nfont_box.grid(row=0, column=0, padx=5)\r\n\r\n#Setting size box\r\nsize_var=IntVar()\r\nfont_size=ttk.Combobox(tool_bar, width=14, textvariable=size_var, state='readonly')\r\nfont_size['values']=tuple(range(8, 81)) # (8, 81, 2) -> Size range starts from 8 and goes till 81 with the margin of 2\r\nfont_size.current(4)\r\nfont_size.grid(row=0, column=1, padx=5)\r\n\r\n#Taking Toolbar Icons\r\nbold_icon=PhotoImage(file='icons2/bold.png')\r\nitalic_icon=PhotoImage(file='icons2/italic.png')\r\nunderline_icon=PhotoImage(file='icons2/underline.png')\r\nfont_color_icon=PhotoImage(file='icons2/font_color.png')\r\nalign_left_icon=PhotoImage(file='icons2/align_left.png')\r\nalign_right_icon=PhotoImage(file='icons2/align_right.png')\r\nalign_center_icon=PhotoImage(file='icons2/align_center.png')\r\n\r\n#Creating Bold button\r\nbold_btn=ttk.Button(tool_bar, image=bold_icon)\r\nbold_btn.grid(row=0, column=2, padx=5)\r\n\r\n#Creating Italic Button\r\nitalic_btn=ttk.Button(tool_bar, image=italic_icon)\r\nitalic_btn.grid(row=0, column=3, padx=5)\r\n\r\n#Creating underline Button\r\nunderline_btn=ttk.Button(tool_bar, image=underline_icon)\r\nunderline_btn.grid(row=0, column=4, padx=5)\r\n\r\n#Creating font color button\r\nfont_color_btn=ttk.Button(tool_bar, image=font_color_icon)\r\nfont_color_btn.grid(row=0, column=5, padx=5)\r\n\r\n#Creating align left button\r\nalign_left_btn=ttk.Button(tool_bar, image=align_left_icon)\r\nalign_left_btn.grid(row=0, column=6, padx=5)\r\n\r\n#Creating align right button\r\nalign_right_btn=ttk.Button(tool_bar, image=align_right_icon)\r\nalign_right_btn.grid(row=0, column=7, padx=5)\r\n\r\n#Creating align left button\r\nalign_center_btn=ttk.Button(tool_bar, image=align_center_icon)\r\nalign_center_btn.grid(row=0, column=8, padx=5)\r\n\r\n#*********************Toolbar End************************\r\n\r\n#*********************Text Editor****************************\r\n\r\ntext_editor=Text(main_application)\r\ntext_editor.config(wrap='word', relief=FLAT)\r\n\r\n#Craeting scrollbar\r\nscroll_bar=Scrollbar(main_application)\r\nscroll_bar.config(command=text_editor.yview)\r\nscroll_bar.pack(side=RIGHT, fill=Y)\r\n\r\n#Setting focus so that the user starts writing directly in the editor\r\ntext_editor.focus_set()\r\ntext_editor.pack(fill=BOTH, expand=True)\r\ntext_editor.config(yscrollcommand=scroll_bar.set)\r\n\r\n#Font Family & Font Size Functionality\r\ncurrent_font_family='Arial'\r\ncurrent_font_size=12\r\ntext_editor.configure(font=('Arial', '12'))\r\n\r\n#Creating function for changing font\r\ndef change_font(event=None):\r\n global current_font_family\r\n current_font_family=font_family.get() #What user selects goes in font_family\r\n text_editor.configure(font=(current_font_family, current_font_size))\r\n\r\n#Creating function for font size\r\ndef change_font_size(event=None): #Writing event as None so that if no value is passed, ten also it shows no error\r\n global current_font_size\r\n current_font_size = size_var.get() # What user selects goes in font_family\r\n text_editor.configure(font=(current_font_family, current_font_size))\r\n\r\nfont_size.bind(\"<>\", change_font_size) #Binding font size\r\nfont_box.bind(\"<>\", change_font) #Binding font style\r\n\r\n##Buttons Functionalities\r\n\r\n#Bold Button function\r\ndef change_bold():\r\n text_property=font.Font(font=text_editor['font'])\r\n text_property.bind('', bold_btn)\r\n if text_property.actual()['weight']=='normal':\r\n text_editor.configure(font=(current_font_family, current_font_size, 'bold'))\r\n if text_property.actual()['weight']=='bold':\r\n text_editor.configure(font=(current_font_family, current_font_size, 'normal'))\r\n\r\n#italic button function\r\ndef change_italic():\r\n text_property=font.Font(font=text_editor['font'])\r\n if text_property.actual()['slant']=='italic':\r\n text_editor.configure(font=(current_font_family, current_font_size, 'roman'))\r\n if text_property.actual()['slant']=='roman':\r\n text_editor.configure(font=(current_font_family, current_font_size, 'italic'))\r\n\r\n\r\n#Underline button function\r\ndef change_underline():\r\n text_property = font.Font(font=text_editor['font'])\r\n if text_property.actual()['underline'] == 0:\r\n text_editor.configure(font=(current_font_family, current_font_size, 'underline'))\r\n if text_property.actual()['underline'] == 1:\r\n text_editor.configure(font=(current_font_family, current_font_size, 'normal'))\r\n\r\n#Binding Bold, italic, underline functions with app\r\nunderline_btn.configure(command=change_underline)\r\nitalic_btn.configure(command=change_italic)\r\nbold_btn.configure(command=change_bold)\r\n\r\n#Font Color functionality\r\ndef change_font_color():\r\n color_var=colorchooser.askcolor()\r\n text_editor.configure(fg=color_var[1])\r\n\r\nfont_color_btn.configure(command=change_font_color)\r\n\r\n#Align functionality\r\ndef align_left():\r\n text_content=text_editor.get(1.0, 'end') #Select all written text\r\n text_editor.tag_config('left', justify=LEFT)\r\n text_editor.delete(1.0, END)\r\n text_editor.insert(INSERT, text_content, 'left')\r\n\r\ndef align_center():\r\n text_content=text_editor.get(1.0, 'end') #Select all written text\r\n text_editor.tag_config('center', justify=CENTER)\r\n text_editor.delete(1.0, END)\r\n text_editor.insert(INSERT, text_content, 'center')\r\n\r\ndef align_right():\r\n text_content=text_editor.get(1.0, 'end') #Select all written text\r\n text_editor.tag_config('right', justify=RIGHT)\r\n text_editor.delete(1.0, END)\r\n text_editor.insert(INSERT, text_content, 'right')\r\n\r\nalign_left_btn.configure(command=align_left)\r\nalign_right_btn.configure(command=align_right)\r\nalign_center_btn.configure(command=align_center)\r\n#*********************Text Editor End************************\r\n\r\n#*********************Status Bar****************************\r\n\r\nstatus_bar=ttk.Label(main_application, text='Status Bar')\r\nstatus_bar.pack(side=BOTTOM)\r\n\r\n#Printing character and words\r\ntext_changed=False\r\ndef changed(event=None):\r\n global text_changed\r\n if text_editor.edit_modified():\r\n text_changed=True\r\n words=len(text_editor.get(1.0, 'end-1c').split())\r\n characters=len(text_editor.get(1.0, 'end-1c').replace(' ', '')) #Replace used for not counting space as character\r\n status_bar.config(text=f'Characters: {characters} Words: {words}')\r\n text_editor.edit_modified(False)\r\n\r\ntext_editor.bind('<>', changed)\r\n#*********************Status Bar End************************\r\n\r\n#*********************Main Menu Functionality****************************\r\n\r\n#Variable\r\nurl=''\r\n\r\n#New Functionality\r\ndef new_file(event=None):\r\n global url\r\n url=''\r\n MsgBox = messagebox.askquestion('Exit Application', 'Are you sure you want to create new file?', icon='warning')\r\n if MsgBox == 'yes':\r\n text_editor.delete(1.0, END)\r\n else:\r\n text_editor.delete(1.0, 1.0)\r\n\r\n#Open Functionality\r\ndef open_file(event=None):\r\n global url\r\n url=filedialog.askopenfilename(initialdir=os.getcwd(), title='Select File', filetypes=(('Text File', '*.txt'), ('All files', '*.*')))\r\n\r\n #url1=docx2txt.process()\r\n\r\n try:\r\n with open(url, 'r') as fr:\r\n text_editor.delete(1., END)\r\n text_editor.insert(1.0, fr.read())\r\n except FileNotFoundError:\r\n return text_editor.delete(1.0, 1.0)\r\n except:\r\n return text_editor.delete(1.0, 1.0)\r\n main_application.title(os.path.basename(url))\r\n\r\npdf=FPDF()\r\ndef pdf_create():\r\n global url, text_changed\r\n try:\r\n mbox = messagebox.askyesno('Confirmation', 'Do you want to make pdf of same file?')\r\n if mbox is True:\r\n if url:\r\n f = text_editor.get(1.0, END)\r\n for x in f:\r\n pdf.cell(200, 10, txt=x, ln=1, align='C')\r\n pdf.output(url + '.pdf')\r\n else:\r\n content2 = str(text_editor.get(1.0, END))\r\n url = filedialog.asksaveasfile(mode='w', defaultextension='.txt',\r\n filetypes=(('Text File', '*.txt'), ('All files', '*.*')))\r\n url.write(content2)\r\n f = text_editor.get(1.0, END)\r\n for x in f:\r\n pdf.cell(200, 10, txt=x, ln=1, align='C')\r\n pdf.output(url+'.pdf')\r\n elif mbox is False:\r\n url = filedialog.askopenfilename(initialdir=os.getcwd(), title='Select File',\r\n filetypes=(('Text File', '*.txt'), ('All files', '*.*')))\r\n try:\r\n with open(url, 'r') as fr:\r\n text_editor.delete(1., END)\r\n text_editor.insert(1.0, fr.read())\r\n f = text_editor.get(1.0, END)\r\n for x in f:\r\n pdf.cell(200, 10, txt=x, ln=1, align='C')\r\n pdf.output(url + '.pdf')\r\n except FileNotFoundError:\r\n return text_editor.delete(1.0, 1.0)\r\n except:\r\n return\r\n\r\n #global url\r\n #MsgBox = messagebox.askquestion('Exit Application', 'Are you sure you want to create new file?', icon='warning')\r\n #if MsgBox == 'yes':\r\n #f = open_file('')\r\n #else:\r\n #text_editor.delete(1.0, 1.0)\r\n f= text_editor.get(1.0, 'end-1c')\r\n for x in f:\r\n pdf.cell(200, 10, txt=x, ln=1, align='C')\r\n pdf.output(\"name.pdf\")\r\n\r\n#Save Functionality\r\ndef save_file(event=None):\r\n global url\r\n try:\r\n if url:\r\n content=str(text_editor.get(1.0, END))\r\n with open(url, 'w', encoding='utf-8') as fw:\r\n fw.write(content)\r\n else:\r\n url=filedialog.asksaveasfile(mode='w', defaultextension='.txt', filetypes=(('Text File', '*.txt'), ('All files', '*.*')))\r\n content2=text_editor.get(1.0, END)\r\n url.write(content2)\r\n url.close()\r\n except:\r\n return\r\n\r\n#Save As Functionality\r\ndef save_as_file(event=None):\r\n global url\r\n try:\r\n content=text_editor.get(1.0, END)\r\n url = filedialog.asksaveasfile(mode='w', defaultextension='.txt', filetypes=(('Text File', '*.txt'), ('All files', '*.*')))\r\n url.write(content)\r\n url.close()\r\n except:\r\n return\r\n\r\n#Exit Functionality\r\ndef exit_file(event=None):\r\n global url, text_changed\r\n try:\r\n if text_changed:\r\n mbox=messagebox.askyesnocancel('Warning', 'Do you want to save the file?')\r\n if mbox is True:\r\n if url:\r\n content=text_editor.get(1.0, END)\r\n with open(url, 'w', encoding='utf-8') as fw:\r\n fw.write(content)\r\n main_application.destroy()\r\n else:\r\n content2=str(text_editor.get(1.0, END))\r\n url = filedialog.asksaveasfile(mode='w', defaultextension='.txt', filetypes=(('Text File', '*.txt'), ('All files', '*.*')))\r\n url.write(content2)\r\n url.close()\r\n main_application.destroy()\r\n elif mbox is False:\r\n main_application.destroy()\r\n else:\r\n main_application.destroy()\r\n except:\r\n return\r\n\r\n#Code for adding file commands\r\nfile.add_command(label='New', image=new_icon, compound=LEFT, accelerator='Ctrl+N', command=new_file)\r\nfile.add_command(label='Open', image=open_icon, compound=LEFT, accelerator='Ctrl+O', command=open_file)\r\nfile.add_command(label='Save', image=save_icon, compound=LEFT, accelerator='Ctrl+S', command=save_file)\r\nfile.add_command(label='Save As', image=save_as_icon, compound=LEFT, accelerator='Ctrl+Alt+S', command=save_as_file)\r\nfile.add_command(label='Export to PDF', image=pdf_icon, compound=LEFT, accelerator='Ctrl+R', command=pdf_create)\r\nfile.add_command(label='Exit', image=exit_icon, compound=LEFT, accelerator='Ctrl+Q', command=exit_file)\r\n\r\n#Find functionaity\r\ndef find_file(event=None):\r\n def find():\r\n word=find_input.get()\r\n text_editor.tag_remove('match', '1.0', END)\r\n matches=0\r\n if word:\r\n start_pos='1.0'\r\n while True:\r\n start_pos=text_editor.search(word, start_pos, stopindex=END)\r\n if not start_pos:\r\n break\r\n end_pos=f'{start_pos}+{len(word)}c'\r\n text_editor.tag_add('match', start_pos, end_pos)\r\n matches+=1\r\n start_pos=end_pos\r\n text_editor.tag_config('match', foreground='red', background='yellow')\r\n\r\n def replace():\r\n word=find_input.get()\r\n replace_txt=replace_input.get()\r\n content=text_editor.get(1.0, END)\r\n new_content=content.replace(word, replace_txt)\r\n text_editor.delete(1.0, END)\r\n text_editor.insert(1.0, new_content)\r\n\r\n def exit():\r\n find_dialog.destroy()\r\n\r\n find_dialog=Toplevel()\r\n find_dialog.geometry('400x200+500+200')\r\n find_dialog.resizable(0,0) #So that it can't be resized\r\n find_frame=ttk.LabelFrame(find_dialog, text='Find/Replace')\r\n find_frame.pack(pady=20)\r\n text_find_label=ttk.Label(find_frame, text='Find: ')\r\n text_replace_label=ttk.Label(find_frame, text='Replace: ')\r\n find_input=ttk.Entry(find_frame, width=30)\r\n replace_input=ttk.Entry(find_frame, width=30)\r\n find_btn=ttk.Button(find_frame, text='Find', command=find)\r\n replace_btn=ttk.Button(find_frame, text='Replace', command=replace)\r\n exit_btn=ttk.Button(find_frame, text='Exit', command=exit)\r\n text_find_label.grid(row=0, column=0, padx=4, pady=8)\r\n text_replace_label.grid(row=1, column=0, padx=4, pady=8)\r\n find_input.grid(row=0, column=1, padx=4, pady=8)\r\n replace_input.grid(row=1, column=1, padx=4, pady=8)\r\n replace_btn.grid(row=2, column=0, padx=3, pady=8)\r\n find_btn.grid(row=2, column=1, padx=3, pady=8)\r\n exit_btn.grid(row=2, column=2, padx=3, pady=8)\r\n find_dialog.mainloop()\r\n\r\n#Code for adding edit commands\r\nedit.add_command(label='Cut', image=cut_icon, compound=LEFT, accelerator='Ctrl+X', command=lambda :text_editor.event_generate(\"\"))\r\nedit.add_command(label='Copy', image=copy_icon, compound=LEFT, accelerator='Ctrl+C', command=lambda :text_editor.event_generate(\"\"))\r\nedit.add_command(label='Paste', image=paste_icon, compound=LEFT, accelerator='Ctrl+V', command=lambda :text_editor.event_generate(\"\"))\r\nedit.add_command(label='Clear All', image=clear_all_icon, compound=LEFT, command=lambda :text_editor.delete(1.0, END))\r\nedit.add_command(label='Find', image=find_icon, compound=LEFT, accelerator='Ctrl+F', command=find_file)\r\n\r\n#View check button\r\nshow_statusbar=BooleanVar()\r\nshow_statusbar.set(True)\r\nshow_toolbar=BooleanVar()\r\nshow_toolbar.set(True)\r\n\r\ndef hide_toolbar():\r\n global show_toolbar\r\n if show_toolbar:\r\n tool_bar.pack_forget()\r\n show_toolbar=False\r\n else:\r\n text_editor.pack_forget()\r\n status_bar.pack_forget()\r\n tool_bar.pack(side=TOP, fill=X)\r\n text_editor.pack(fill=BOTH, expand=True)\r\n status_bar.pack(side=BOTTOM)\r\n show_toolbar=True\r\n\r\ndef hide_statusbar():\r\n global show_statusbar\r\n if show_statusbar:\r\n status_bar.pack_forget()\r\n show_statusbar=False\r\n else:\r\n status_bar.pack(side=BOTTOM)\r\n show_statusbar=True\r\n\r\n#Code for adding view check boxes\r\nview.add_checkbutton(label='Toolbar', onvalue=True, offvalue=0, variable=show_toolbar, image=toolbar_icon, compound=LEFT, command=hide_toolbar)\r\nview.add_checkbutton(label='Satus Bar', onvalue=1, offvalue=False, variable=show_statusbar, image=statusbar_icon, compound=LEFT, command=hide_statusbar)\r\n\r\n#Color theme\r\ndef change_theme():\r\n chosen_theme=theme_choice.get()\r\n color_tuple=color_dict.get(chosen_theme)\r\n fg_color, bg_color=color_tuple[0], color_tuple[1]\r\n text_editor.config(background=bg_color, fg=fg_color)\r\n\r\ncount=0\r\nfor i in color_dict:\r\n color_theme.add_radiobutton(label=i, image=color_icons[count], variable=theme_choice, compound=LEFT, command=change_theme)\r\n count+=1\r\n\r\n#**********************Bind shortcut Keys*****************************\r\nmain_application.bind(\"\", new_file)\r\nmain_application.bind(\"\", open_file)\r\nmain_application.bind(\"\", save_file)\r\nmain_application.bind(\"\", save_as_file)\r\nmain_application.bind(\"\", pdf_create)\r\nmain_application.bind(\"\", exit_file)\r\nmain_application.bind(\"\", find_file)\r\n\r\n#*********************Main Menu Functionality End************************\r\nmain_application.config(menu=main_menu)\r\nmain_application.mainloop()","sub_path":"texteditor.py","file_name":"texteditor.py","file_ext":"py","file_size_in_byte":19771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"491125252","text":"import TransportEquation1DCenteredImplicit\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom math import log10, sqrt\nimport sys\nimport time, json\n\n \ndef test_validation1DTransportEquationCenteredImplicit(cfl,isSmooth):\n start = time.time()\n #### 1D regular grid\n meshList=[50,100,200,400,800]\n meshType=\"1D regular grid\"\n testColor=\"Green\"\n nbMeshes=len(meshList)\n mesh_size_tab=meshList\n mesh_name='RegularGrid'\n\n a=0. ; b=1.\n error_u_tab=[0]*nbMeshes\n sol_u=[0]*nbMeshes\n total_var_u=[0]*nbMeshes\n min_u=[0]*nbMeshes\n max_u=[0]*nbMeshes\n time_tab=[0]*nbMeshes\n\n plt.close('all')\n i=0\n\n # Storing of numerical errors, mesh sizes and solution\n for nx in meshList:\n min_u[i], max_u[i], sol_u[i], total_var_u[i], error_u_tab[i], time_tab[i] = TransportEquation1DCenteredImplicit.solve(nx,cfl,a,b,isSmooth)\n assert max_u[i]>-1e-5 and max_u[i]<1+1e-5\n error_u_tab[i]=log10(error_u_tab[i])\n time_tab[i]=log10(time_tab[i])\n i=i+1\n \n end = time.time()\n\n # Plot of solution\n plt.close()\n for i in range(nbMeshes):\n plt.plot(np.linspace(a,b,meshList[i]), sol_u[i], label= str(mesh_size_tab[i]) + ' cells')\n plt.legend()\n plt.xlabel('x')\n plt.ylabel('u')\n plt.title('Plot of the numerical solution of the transport equation \\n with implicit centered scheme on a 1D regular grid')\n if(isSmooth):\n plt.savefig(mesh_name+\"_1DTransportEquationCenteredImplicit_CFL\"+str(cfl)+\"_Smooth_PlotOfSolution.png\") \n else:\n plt.savefig(mesh_name+\"_1DTransportEquationCenteredImplicit_CFL\"+str(cfl)+\"_Stiff_PlotOfSolution.png\") \n plt.close()\n\n # Plot of maximal value\n plt.close()\n plt.plot(mesh_size_tab, max_u, label='Maximum value')\n plt.legend()\n plt.xlabel('Number of cells')\n plt.ylabel('Max |u|')\n plt.title('Maximum velocity norm of the transport equation \\n with implicit centered scheme on a 1D regular grid')\n if(isSmooth):\n plt.savefig(mesh_name+\"_1DTransportEquationCenteredImplicit_CFL\"+str(cfl)+\"_Smooth_MaxSolution.png\")\n else:\n plt.savefig(mesh_name+\"_1DTransportEquationCenteredImplicit_CFL\"+str(cfl)+\"_Stiff_MaxSolution.png\")\n \n # Plot of total variation\n plt.close()\n plt.plot(mesh_size_tab, total_var_u, label='Total variation')\n plt.legend()\n plt.xlabel('Number of cells')\n plt.ylabel('Var(u)')\n plt.title('Total variation for the transport equation \\n with implicit centered scheme on a 1D regular grid')\n if(isSmooth):\n plt.savefig(mesh_name+\"_1DTransportEquationCenteredImplicit_CFL\"+str(cfl)+\"_Smooth_TotalVariation.png\")\n else:\n plt.savefig(mesh_name+\"_1DTransportEquationCenteredImplicit_CFL\"+str(cfl)+\"_Stiff_TotalVariation.png\")\n \n for i in range(nbMeshes):\n mesh_size_tab[i]=log10(mesh_size_tab[i])\n \n # Least square linear regression\n # Find the best a,b such that f(x)=ax+b best approximates the convergence curve\n # The vector X=(a,b) solves a symmetric linear system AX=B with A=(a1,a2\\\\a2,a3), B=(b1,b2)\n a1=np.dot(mesh_size_tab,mesh_size_tab)\n a2=np.sum(mesh_size_tab)\n a3=nbMeshes\n \n det=a1*a3-a2*a2\n assert det!=0, 'test_validation1DTransportEquationCenteredImplicit() : Make sure you use distinct meshes and at least two meshes'\n\n b1u=np.dot(error_u_tab,mesh_size_tab) \n b2u=np.sum(error_u_tab)\n au=( a3*b1u-a2*b2u)/det\n bu=(-a2*b1u+a1*b2u)/det\n \n print(\"Implicit Centered scheme for Transport Equation on 1D regular grid : scheme order is \", -au)\n \n # Plot of convergence curve\n plt.close()\n plt.plot(mesh_size_tab, error_u_tab, label='log(|error|)')\n plt.plot(mesh_size_tab, a*np.array(mesh_size_tab)+b,label='least square slope : '+'%.3f' % a)\n plt.legend()\n plt.xlabel('log(Number of cells)')\n plt.ylabel('log(|error u|)')\n plt.title('Convergence of finite volumes for the transport equation \\n with implicit centered scheme on a 1D regular grid')\n if(isSmooth):\n plt.savefig(mesh_name+\"1DTransportEquationCenteredImplicit_CFL\"+str(cfl)+\"_Smooth_ConvergenceCurve.png\")\n else:\n plt.savefig(mesh_name+\"1DTransportEquationCenteredImplicit_CFL\"+str(cfl)+\"_Stiff_ConvergenceCurve.png\")\n \n # Plot of computational time\n plt.close()\n plt.plot(mesh_size_tab, time_tab, label='log(cpu time)')\n plt.legend()\n plt.xlabel('log(Number of cells)')\n plt.ylabel('log(cpu time)')\n plt.title('Computational time of finite volumes for the transport equation \\n with implicit centered scheme on a 1D regular grid')\n if(isSmooth):\n plt.savefig(mesh_name+\"1DTransportEquationCenteredImplicit_CFL\"+str(cfl)+\"_Smooth_ComputationalTime.png\")\n else:\n plt.savefig(mesh_name+\"1DTransportEquationCenteredImplicit_CFL\"+str(cfl)+\"_Stiff_ComputationalTime.png\")\n\n plt.close('all')\n\n convergence_synthesis={}\n\n convergence_synthesis[\"PDE_model\"]=\"Transport_Equation\"\n convergence_synthesis[\"PDE_is_stationary\"]=False\n convergence_synthesis[\"PDE_search_for_stationary_solution\"]=True\n convergence_synthesis[\"Numerical_method_name\"]=\"Centered scheme\"\n convergence_synthesis[\"Numerical_method_space_discretization\"]=\"Finite volumes\"\n convergence_synthesis[\"Numerical_method_time_discretization\"]=\"Implicit\"\n convergence_synthesis[\"Initial_data\"]=\"sine\"\n convergence_synthesis[\"Boundary_conditions\"]=\"Periodic\"\n convergence_synthesis[\"Numerical_parameter_cfl\"]=cfl\n convergence_synthesis[\"Space_dimension\"]=2\n convergence_synthesis[\"Mesh_dimension\"]=2\n convergence_synthesis[\"Mesh_names\"]=meshList\n convergence_synthesis[\"Mesh_type\"]=meshType\n convergence_synthesis[\"Mesh_description\"]=mesh_name\n convergence_synthesis[\"Mesh_sizes\"]=mesh_size_tab\n convergence_synthesis[\"Mesh_cell_type\"]=\"1D regular grid\"\n convergence_synthesis[\"Numerical_ersolution\"]=max_u\n convergence_synthesis[\"Scheme_order\"]=-au\n convergence_synthesis[\"Test_color\"]=testColor\n convergence_synthesis[\"Computational_time\"]=end-start\n\n with open('Convergence_1DTransportEquationCenteredImplicit_'+mesh_name+'.json', 'w') as outfile: \n json.dump(convergence_synthesis, outfile)\n\nif __name__ == \"\"\"__main__\"\"\":\n if len(sys.argv) >2 :\n cfl = float(sys.argv[1])\n isSmooth = bool(int(sys.argv[2]))\n test_validation1DTransportEquationCenteredImplicit(cfl,isSmooth)\n else :\n test_validation1DTransportEquationCenteredImplicit(0.99,True)\n\n","sub_path":"tests/validation/TransportEquation1D/1DTransportCenteredImplicit/test_validation1DTransportEquationCenteredImplicit.py","file_name":"test_validation1DTransportEquationCenteredImplicit.py","file_ext":"py","file_size_in_byte":6504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"264677598","text":"\n\nfrom xai.brain.wordbase.nouns._making import _MAKING\n\n#calss header\nclass _MAKINGS(_MAKING, ):\n\tdef __init__(self,): \n\t\t_MAKING.__init__(self)\n\t\tself.name = \"MAKINGS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"making\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_makings.py","file_name":"_makings.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"187401315","text":"from psychopy import core, visual, event, data, gui # basic psychopy stuff\nimport numpy as np # for math stuff\n\n##############################################\n# settings\n##############################################\n\ncondfile = \"conditions.csv\" # replace with absolute path\ndur_fix = 0.5\ndur_stim = 0.125\ndur_mask = None # random\ndur_iti = 0.5\n\n##############################################\n# pre-experiment dialog\n##############################################\n\n# define questions for prompt\nsession_data = {\n 'sub_initials': 'abc',\n 'sub_number': 0\n}\n# display dialog; data is stored in session_data\n\n# *****************\n# task: create a pre-experiment dialog\n# *****************\n\n##############################################\n# load conditions file and initialize handlers\n##############################################\n\n# import formatted file containing info for each trial\nconditions = data.importConditions(condfile)\n# this lets us loop through all conditions\ntrial_handler = data.TrialHandler(conditions, name='horsezeb',\n nReps=1, method='random')\n# this handles behavioral data\nexp_handler = data.ExperimentHandler(name='horsezeb',\n dataFileName='data/{}'.format(session_data['sub_initials']))\n# allow exp_handler to retrieve trial information from trial_handler\nexp_handler.addLoop(trial_handler)\n\n##############################################\n# initialize window\n##############################################\n\n# create the main window using a normed coordinate system\nwin = visual.Window((1280,1024), fullscr=False, units='height')\n\n##############################################\n# prepare + present instructions\n##############################################\n\ninstructions_message = \"\"\"this is the world-famous zebra-horse discrimination task.\nin each trial, press A if you saw a zebra, L if you saw a horse.\"\"\"\n\nmessage = visual.TextStim(win, text=instructions_message, height=0.03)\n\nmessage.draw()\nwin.flip()\nevent.waitKeys() # press any key to continue\nwin.flip() # clear screen\n\n##############################################\n# initialize stimuli/messages\n##############################################\n\nfix = visual.TextStim(win, text=\"+\", height=0.1)\nstim = None # ************** task: initialize\nprobe1 = visual.TextStim(win, text='zebra or horse?', pos=(0,0), height=0.05)\nprobe2 = visual.TextStim(win, text='press A for zebra, L for horse',\n pos=(0,-0.15), height=0.03)\n\nresp_clock = core.Clock() # for measuring response times\n\n##############################################\n# main loop\n##############################################\n\nwhile trial_handler.getFutureTrial(): # loop through all conditions\n trial = trial_handler.next() # retrieve info for current trial\n print(trial)\n\n ### whatever happens each trial goes here ###\n\n # *****************\n # task: implement the trial sequence here\n # *****************\n\n exp_handler.nextEntry() # next row in results csv\n\n##############################################\n# exp finished\n##############################################\n\n# *****************\n# task: create a finish message\n# *****************\n\nevent.waitKeys() # close after any key press\ncore.quit()\n","sub_path":"experiment1/exp1Base.py","file_name":"exp1Base.py","file_ext":"py","file_size_in_byte":3194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"387277178","text":"import re\nimport string\nfrom pymorphy2.tokenizers import simple_word_tokenize\nfrom pymorphy2 import MorphAnalyzer\n\n\nstopwoards = set(string.punctuation) | {'_','—','–','−','_tem'}\nmorph= MorphAnalyzer()\nsent_tokenize = re.compile(\"[.,?!'\\'\\n]\").split\n\ndef best_parser(token,parses):\n for p in parses:\n if token.istitle() and {'Geox', 'Name', 'Surn', 'Patr'} & p.tag.grammemes:#если с большой буквы и входит в теги одушевл.: #Geox-георгрифия,Name-имя,Surn-фамилия\n return p#оставляем в той же форме #Patr-отчество\n if p.tag.POS == 'NPRO': #если местоимение(NPRO-местоимение)\n return p\n return parses[0]\n\n\n#приведение в нормальную форму\ndef normal_form(p):\n if {'Patr', 'Surn'} & p.tag.grammemes:#если это Фамилия или отчество\n #print(p.word)\n #print(p.inflect({'sing', 'nomn'}).word)\n return p.inflect({'sing', 'nomn'}).word #склоняет в sign-единственное число,nomn-именительный падеж и возвращает\n return p.normal_form #слово приводит в нормальную\n\n#ф-ия нормализации слова:\ndef normalized(tokens):\n #нормализуем каждый токен в зависимости от надобности\n parser = [\n #print(morph.parse(w))\n best_parser(w, morph.parse(w))\n for w in tokens\n if w.lower() not in stopwoards\n ]\n\n #убирает токены,которые не соответсвуют частям речи\n parser = [\n p for p in parser\n #if p.tag.POS not in {'PNCT', 'LATN', 'CONJ', 'NUMB', 'PREP'}#CONJ-союз,#PNCT-пунктуация,NUMB-число,LATN-токен состоит из лат.букв\n #if not {'PNCT', 'CONJ', 'NUMB,real', 'NUMB', 'NUMB,intg', 'PREP', 'UNKN'} & p.tag.grammemes\n if not {'PNCT', 'CONJ', 'NUMB,real', 'NUMB', 'NUMB,intg', 'PREP'} & p.tag.grammemes\n ]\n #возвращает нормальную форму слова,приведенного в нижний регистр\n #print(normal_form(p).lower() for p in parser)\n return [normal_form(p).lower() for p in parser]\n\n\n#Ф-ИЯ ДЛЯ РАЗБИЕНИЯ СТРОКИ НА ТОКЕНЫ И ПЕРЕДАЧА В Ф-ИЮ НОРМАЛИЗАЦИИ\n#делит единую строку на отдельные строки,а так же\n#убирает из строки разделители,которые заданы регулярным выражением sent_tokenize с помощью библиотеки re.\n#После чего убирает из начала и конца строки пробелы(sent.strip()) с пом. библиотеки string и ее метода strip\n#и передает в ф-ию нормализации список из токенов с пом. библиотеки pymorphy2 и метода simple_word_tokenize\n# пример:\n#вход(book)-\" Я ничего не понимаю, может быть\"\n#параметр передаваем в ф-ию normalized: ['Я', 'ничего', 'не', 'понимаю'],['может', 'быть']\n''''\ndef get_sents(book):\n return [\n normalized(simple_word_tokenize(sent.strip()))\n for sent in sent_tokenize(book) if sent.strip()\n #normalized(simple_word_tokenize(book))\n ]\n'''\n\ndef get_sents(input_data):\n return [\n normalized(simple_word_tokenize(sent))\n for sent in input_data\n ]\n\n\n\nif __name__ == \"__main__\":\n while 1:\n print(\"Введите текстр\")\n text = input()\n print(get_sents([text]))","sub_path":"Classificator/Learn_neiro/lemmatization.py","file_name":"lemmatization.py","file_ext":"py","file_size_in_byte":3914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"127227281","text":"#!/usr/bin/env python3\n\"\"\"\nTakes a cifti map ('dscalar.nii') and outputs a csv of results\n\nUsage:\n ciftify_statclust_report [options] \n\nArguments:\n Input map.\n\nOptions:\n --min-threshold MIN the largest value [default: -2.85] to consider for being a minimum\n --max-threshold MAX the smallest value [default: 2.85] to consider for being a maximum\n --area-threshold MIN threshold [default: 20] for surface cluster area, in mm^2\n --surface-distance MM minimum distance in mm [default: 20] between extrema of the same type.\n --volume-distance MM minimum distance in mm [default: 20] between extrema of the same type.\n\n --outputbase prefix Output prefix (with path) to output documents\n --no-cluster-dlabel Do not output a dlabel map of the clusters\n --output-peaks Also output an additional output of peak locations\n\n --left-surface GII Left surface file (default is HCP S1200 Group Average)\n --right-surface GII Right surface file (default is HCP S1200 Group Average)\n --left-surf-area GII Left surface vertex areas file (default is HCP S1200 Group Average)\n --right-surf-area GII Right surface vertex areas file (default is HCP S1200 Group Average)\n\n --debug Debug logging\n -n,--dry-run Dry run\n -h, --help Prints this message\n\nDETAILS\nNote: at the moment generates separate outputs for surface.\nUses -cifti-separate in combination with FSL's clusterize to get information from\nthe subcortical space.\n\nOutputs a cluster report csv with the following headings:\n + clusterID: Integer for the cluster this peak is from (corresponds to dlabel.nii)\n + cluster_name: the cluster label\n + by default this will be \"LABEL_\" but this be changed\n in the .dlabel.nii file using connectome-workbench\n + mean_value: the average value for this cluster within the input dscalar.nii map\n + area: the surface area of the cluster (on the specified surface)\n + DKT_overlap: a list of DKT freesurfer anatomical atlas (aparc) atlas labels\n that overlap with this cluster and the percent overlap of each label\n + Yeo7_overlap: a list of the Yeo et al 2011 7 network labels that overlap\n with this cluster and the percent overlap of each label\n + MMP_overlap: The labels from the Glasser et al (2016) Multi-Modal Parcellation\n that overlap with this cluster and the percent overlap of each label\n\nIf the '--output-peaks' flag is indicated, an addtional table will be output\nwith several headings:\n + clusterID: Integer for the cluster this peak is from (corresponds to dlabel.nii)\n + hemisphere: Hemisphere the peak is in (L or R)\n + vertex: The vertex id\n + x,y,z: The nearest x,y,z coordinates to the vertex\n + value: The intensity (value) at that vertex in the func.dscalar.nii\n + DKT: The label from the freesurfer anatomical atlas (aparc) at the vertex\n + DKT_overlap: The proportion of the cluster (clusterID) that overlaps with the DKT atlas label\n + Yeo7: The label from the Yeo et al 2011 7 network atlas at this peak vertex\n + Yeo7_overlap: The proportion of the cluster (clusterID) that overlaps with this Yeo7 network label\n + MMP: The label from the Glasser et al (2016) Multi-Modal Parcellation\n + MMP_overlap: The proportion of the cluster (clusterID) that overlaps with the MMP atlas label\n\nIf no surfaces of surface area files are given. The midthickness surfaces from\nthe HCP S1200 Group Mean will be used, as well as it's vertex-wise\nsurface area infomation.\n\nDefault name for the output csv taken from the input file.\ni.e. func.dscalar.nii --> func_peaks.csv\n\nUnless the '--no-cluster-dlabel' flag is given, a map of the clusters with be\nbe written to the same folder as the outputcsv to aid in visualication of the results.\nThis dlable map with have a name ending in '_clust.dlabel.nii'.\n(i.e. func_peaks.csv & func_clust.dlabel.nii)\n\nAtlas References:\nYeo, BT. et al. 2011. 'The Organization of the Human Cerebral Cortex\nEstimated by Intrinsic Functional Connectivity.' Journal of Neurophysiology\n106 (3): 1125-65.\n\nDesikan, RS.et al. 2006. 'An Automated Labeling System for Subdividing the\nHuman Cerebral Cortex on MRI Scans into Gyral Based Regions of Interest.'\nNeuroImage 31 (3): 968-80.\n\nGlasser, MF. et al. 2016. 'A Multi-Modal Parcellation of Human Cerebral Cortex.'\nNature 536 (7615): 171-78.\n\nWritten by Erin W Dickie, Last updated August 27, 2017\n\"\"\"\nfrom docopt import docopt\nimport os, sys\nimport numpy as np\nimport pandas as pd\nimport logging\nimport logging.config\nimport ciftify.niio\nimport ciftify.report\nimport ciftify.utils\nfrom ciftify.meants import NibInput\n\nconfig_path = os.path.join(os.path.dirname(ciftify.config.find_ciftify_global()), 'bin', \"logging.conf\")\nlogging.config.fileConfig(config_path, disable_existing_loggers=False)\nlogger = logging.getLogger(os.path.basename(__file__))\n\ndef load_LR_vertex_areas(surf_settings):\n ''' loads the vertex areas and stacks the dataframes'''\n surf_va_L = ciftify.niio.load_gii_data(surf_settings.L.vertex_areas)\n surf_va_R = ciftify.niio.load_gii_data(surf_settings.R.vertex_areas)\n surf_va_LR = np.vstack((surf_va_L, surf_va_R))\n return(surf_va_LR)\n\n\ndef report_atlas_overlap(df, label_data, atlas, surf_va_LR, min_percent_overlap = 5):\n # read the atlas\n atlas_data, atlas_dict = ciftify.niio.load_LR_label(atlas['path'],\n int(atlas['map_number']))\n # write an overlap report to the outputfile\n o_col = '{}_overlap'.format(atlas['name'])\n df[o_col] = \"\"\n for pd_idx in df.index.get_values():\n df.loc[pd_idx, o_col] = ciftify.report.get_label_overlap_summary(\n pd_idx, label_data, atlas_data, atlas_dict, surf_va_LR,\n min_percent_overlap = min_percent_overlap)\n return(df)\n\n\ndef run_ciftify_dlabel_report(arguments, tmpdir):\n\n dscalar_in = NibInput(arguments[''])\n surf_distance = arguments['--surface-distance']\n\n outputbase = arguments['--outputbase']\n dont_output_clusters = arguments['--no-cluster-dlabel']\n output_peaktable = arguments['--output-peaks']\n\n surf_settings = ciftify.report.CombinedSurfaceSettings(arguments, tmpdir)\n atlas_settings = ciftify.report.define_atlas_settings()\n\n ## if not outputname is given, create it from the input dscalar map\n if not outputbase:\n outputbase = os.path.join(os.path.dirname(dscalar_in.path), dscalar_in.base)\n ciftify.utils.check_output_writable(outputbase, exit_on_error = True)\n\n clusters_dscalar = clusterise_dscalar_input(dscalar_in.path,\n arguments,\n surf_settings,\n tmpdir)\n\n if dont_output_clusters:\n cluster_dlabel = os.path.join(tmpdir, 'clust.dlabel.nii')\n else:\n cluster_dlabel = '{}_clust.dlabel.nii'.format(outputbase)\n empty_labels = os.path.join(tmpdir, 'empty_labels.txt')\n ciftify.utils.run('touch {}'.format(empty_labels))\n ciftify.utils.run(['wb_command', '-cifti-label-import',\n clusters_dscalar, empty_labels, cluster_dlabel])\n\n ## load the data\n label_data, label_dict = ciftify.niio.load_LR_label(cluster_dlabel, map_number = 1)\n\n ## define the outputcsv\n outputcsv = '{}_statclust_report.csv'.format(outputbase)\n logger.info('Output table: {}'.format(outputcsv))\n\n ## load the vertex areas\n surf_va_LR = load_LR_vertex_areas(surf_settings)\n\n ## assert that the dimensions match\n if not (label_data.shape[0] == surf_va_LR.shape[0]):\n logger.error('label file vertices {} not equal to vertex areas {}'\n ''.format(label_data.shape[0], surf_va_LR.shape[0]))\n sys.exit(1)\n\n ## use the label dict to start the report dataframe\n df = pd.DataFrame.from_dict(label_dict, orient = \"index\")\n df['label_idx'] = df.index\n df = df.rename(index=str, columns={0: \"label_name\"})\n\n\n # calculate a column of the surface area for row ROIs\n df['area'] = -999\n for pd_idx in df.index.get_values():\n df.loc[pd_idx, 'area'] = ciftify.report.calc_cluster_area(pd_idx,\n label_data, surf_va_LR)\n\n for atlas in atlas_settings.values():\n df = report_atlas_overlap(df, label_data, atlas,\n surf_va_LR, min_percent_overlap = 5)\n\n df.to_csv(outputcsv)\n\n if output_peaktable:\n write_statclust_peaktable(dscalar_in.path, clusters_dscalar, outputbase,\n arguments, surf_settings, atlas_settings)\n\nclass ThresholdArgs:\n '''little class that holds the user aguments about thresholds'''\n def __init__(self, arguments):\n self.max = arguments([])\n area_threshold = arguments['--area-threshold']\n self.volume_distance = arguments['--volume-distance']\n min_threshold = arguments['--min-threshold']\n max_threshold = arguments['--max-threshold']\n area_threshold = arguments['--area-thratlas_settingseshold']\n\ndef clusterise_dscalar_input(data_file, arguments, surf_settings, tmpdir):\n '''runs wb_command -cifti-find-clusters twice\n returns the path to the output\n '''\n ## also run clusterize with the same settings to get clusters\n pcluster_dscalar = os.path.join(tmpdir,'pclusters.dscalar.nii')\n\n wb_cifti_clusters(data_file, pcluster_dscalar, surf_settings,\n arguments['--max-threshold'],\n arguments['--area-threshold'],\n less_than = False, starting_label=1)\n\n ## load both cluster files to determine the max value\n pos_clust_data = ciftify.niio.load_concat_cifti_surfaces(pcluster_dscalar)\n max_pos = int(np.max(pos_clust_data))\n\n ## now get the negative clusters\n ncluster_dscalar = os.path.join(tmpdir,'nclusters.dscalar.nii')\n wb_cifti_clusters(data_file, ncluster_dscalar, surf_settings,\n arguments['--min-threshold'],\n arguments['--area-threshold'],\n less_than = True, starting_label=max_pos + 1)\n\n ## add the positive and negative together to make one cluster map\n clusters_out = os.path.join(tmpdir,'clusters.dscalar.nii')\n ciftify.utils.run(['wb_command', '-cifti-math \"(x+y)\"',\n clusters_out,\n '-var','x',pcluster_dscalar, '-var','y',ncluster_dscalar])\n return clusters_out\n\ndef wb_cifti_clusters(input_cifti, output_cifti, surf_settings,\n value_threshold, minimun_size,less_than, starting_label=1):\n '''runs wb_command -cifti-find-clusters'''\n wb_arglist = ['wb_command', '-cifti-find-clusters',\n input_cifti,\n str(value_threshold), str(minimun_size),\n str(value_threshold), str(minimun_size),\n 'COLUMN',\n output_cifti,\n '-left-surface', surf_settings.L.surface,\n '-corrected-areas', surf_settings.L.vertex_areas,\n '-right-surface', surf_settings.R.surface,\n '-corrected-areas', surf_settings.R.vertex_areas,\n '-start', str(starting_label)]\n if less_than : wb_arglist.append('-less-than')\n cinfo = ciftify.niio.cifti_info(input_cifti)\n if cinfo['maps_to_volume']: wb_arglist.append('-merged-volume')\n ciftify.utils.run(wb_arglist)\n\ndef write_statclust_peaktable(data_file, clusters_dscalar, outputbase,\n arguments, surf_settings, atlas_settings):\n '''runs the old peak table functionality\n\n Parameters\n ----------\n data_file : filepath\n path to the dscalar map input\n clusters_dscalar : filepath\n path to the cluster file created with same settings\n outputbase :\n the prefix for the outputfile\n arguments : dict\n the user args dictionary to pull the thresholds from\n surf_settings : dict\n the dictionary of paths to the surface files,\n created by ciftify.report.CombinedSurfaceSettings\n altas_settings : dict\n dictionary of paths and settings related to the atlases to use for overlaps\n comparison. Created by ciftify.report.define_atlas_settings()\n\n Outputs\n -------\n writes a csv to _cortex_peaks.csv\n '''\n with ciftify.utils.TempDir() as ex_tmpdir:\n ## run FSL's cluster on the subcortical bits\n ## now to run FSL's cluster on the subcortical bits\n cinfo = ciftify.niio.cifti_info(data_file)\n if cinfo['maps_to_volume']:\n subcortical_vol = os.path.join(ex_tmpdir, 'subcortical.nii.gz')\n ciftify.utils.run(['wb_command', '-cifti-separate', data_file, 'COLUMN', '-volume-all', subcortical_vol])\n fslcluster_cmd = ['cluster',\n '--in={}'.format(subcortical_vol),\n '--thresh={}'.format(arguments['--max-threshold']),\n '--peakdist={}'.format(arguments['--volume-distance'])]\n peak_table = ciftify.utils.get_stdout(fslcluster_cmd)\n with open(\"{}_subcortical_peaks.csv\".format(outputbase), \"w\") as text_file:\n text_file.write(peak_table.replace('/t',','))\n else:\n logger.info('No subcortical volume data in {}'.format(data_file))\n\n ## run wb_command -cifti-extrema to find the peak locations\n extrema_dscalar = os.path.join(ex_tmpdir,'extrema.dscalar.nii')\n ciftify.utils.run(['wb_command','-cifti-extrema',\n data_file,\n str(arguments['--surface-distance']),\n str(arguments['--volume-distance']),\n 'COLUMN',\n extrema_dscalar,\n '-left-surface', surf_settings.L.surface,\n '-right-surface', surf_settings.R.surface,\n '-threshold',\n str(arguments['--min-threshold']),\n str(arguments['--max-threshold'])])\n\n ## multiply the cluster labels by the extrema to get the labeled exteama\n lab_extrema_dscalar = os.path.join(ex_tmpdir,'lab_extrema.dscalar.nii')\n ciftify.utils.run(['wb_command', '-cifti-math \"(abs(x*y))\"',\n lab_extrema_dscalar,\n '-var','x',clusters_dscalar, '-var','y',extrema_dscalar])\n\n ## run left and right dfs... then concatenate them\n dfL = build_hemi_results_df(surf_settings.L, atlas_settings,\n data_file, lab_extrema_dscalar, clusters_dscalar)\n dfR = build_hemi_results_df(surf_settings.R, atlas_settings,\n data_file, lab_extrema_dscalar, clusters_dscalar)\n df = dfL.append(dfR, ignore_index = True)\n\n ## write the table out to the outputcsv\n output_columns = ['clusterID','hemisphere','vertex', 'peak_value', 'area']\n decimals_out = {\"clusterID\":0, 'peak_value':3, 'area':0}\n for atlas in atlas_settings.keys():\n atlas_name = atlas_settings[atlas]['name']\n output_columns.append(atlas_name)\n output_columns.append('{}_overlap'.format(atlas_name))\n decimals_out['{}_overlap'.format(atlas_name)] = 3\n\n df = df.round(decimals_out)\n df.to_csv(\"{}_cortex_peaks.csv\".format(outputbase),\n columns = output_columns,index=False)\n\n\n\ndef build_hemi_results_df(surf_settings, atlas_settings,\n input_dscalar, extreama_dscalar, clusters_dscalar):\n\n ## read in the extrema file from above\n extrema_array = ciftify.niio.load_hemisphere_data(extreama_dscalar, surf_settings.wb_structure)\n vertices = np.nonzero(extrema_array)[0] # indices - vertex id for peaks in hemisphere\n\n ## read in the original data for the value column\n input_data_array = ciftify.niio.load_hemisphere_data(input_dscalar, surf_settings.wb_structure)\n\n ## load both cluster indices\n clust_array = ciftify.niio.load_hemisphere_data(clusters_dscalar, surf_settings.wb_structure)\n\n ## load the coordinates\n coords = ciftify.niio.load_surf_coords(surf_settings.surface)\n surf_va = ciftify.niio.load_gii_data(surf_settings.vertex_areas)\n\n ## put all this info together into one pandas dataframe\n df = pd.DataFrame({\"clusterID\": np.reshape(extrema_array[vertices],(len(vertices),)),\n \"hemisphere\": surf_settings.hemi,\n \"vertex\": vertices,\n 'peak_value': [round(x,3) for x in np.reshape(input_data_array[vertices],(len(vertices),))]})\n\n ## look at atlas overlap\n for atlas in atlas_settings.keys():\n df = calc_atlas_overlap(df, surf_settings.wb_structure, clust_array, surf_va, atlas_settings[atlas])\n\n return(df)\n\ndef calc_atlas_overlap(df, wb_structure, clust_label_array, surf_va, atlas_settings):\n '''\n calculates the surface area column of the peaks table\n needs hemisphere specific inputs\n '''\n\n ## load atlas\n atlas_label_array, atlas_dict = ciftify.niio.load_hemisphere_labels(atlas_settings['path'],\n wb_structure,\n map_number = atlas_settings['map_number'])\n\n atlas_prefix = atlas_settings['name']\n\n ## create new cols to hold the data\n df[atlas_prefix] = pd.Series('not_calculated', index = df.index)\n overlap_col = '{}_overlap'.format(atlas_prefix)\n df[overlap_col] = pd.Series(-99.0, index = df.index)\n\n for pd_idx in df.index.tolist():\n ## atlas interger label is the integer at the vertex\n atlas_label = atlas_label_array[df.loc[pd_idx, 'vertex']]\n\n ## the atlas column holds the labelname for this label\n df.loc[pd_idx, atlas_prefix] = atlas_dict[atlas_label]\n\n overlap_area = ciftify.report.calc_overlapping_area(\n df.loc[pd_idx, 'clusterID'], clust_label_array,\n atlas_label, atlas_label_array,\n surf_va)\n\n ## overlap area is the area of the overlaping region over the total cluster area\n clust_area = ciftify.report.calc_cluster_area(\n df.loc[pd_idx, 'clusterID'],\n clust_label_array,\n surf_va)\n\n df.loc[pd_idx, overlap_col] = overlap_area/clust_area\n\n return(df)\n\ndef main():\n arguments = docopt(__doc__)\n\n logger.setLevel(logging.WARNING)\n\n if arguments['--debug']:\n logger.setLevel(logging.DEBUG)\n logging.getLogger('ciftify').setLevel(logging.DEBUG)\n\n ## set up the top of the log\n logger.info('{}{}'.format(ciftify.utils.ciftify_logo(),\n ciftify.utils.section_header('Starting ciftify_statclust_report')))\n\n ciftify.utils.log_arguments(arguments)\n\n with ciftify.utils.TempDir() as tmpdir:\n logger.info('Creating tempdir:{} on host:{}'.format(tmpdir,\n os.uname()[1]))\n ret = run_ciftify_dlabel_report(arguments, tmpdir)\n\nif __name__ == '__main__':\n main()\n","sub_path":"ciftify/bin/ciftify_statclust_report.py","file_name":"ciftify_statclust_report.py","file_ext":"py","file_size_in_byte":18720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"418175493","text":"import copy\nimport os\n\nimport numpy as np\nimport pytest\nimport scipy.sparse as sp\nfrom scipy.spatial.distance import cdist as scipy_cdist\n\nfrom jina import Document, DocumentArray\nfrom jina.math.dimensionality_reduction import PCA\nfrom jina.types.arrays.memmap import DocumentArrayMemmap\n\n\n@pytest.fixture()\ndef doc_lists():\n d1 = Document(embedding=np.array([0, 0, 0]))\n d2 = Document(embedding=np.array([3, 0, 0]))\n d3 = Document(embedding=np.array([1, 0, 0]))\n d4 = Document(embedding=np.array([2, 0, 0]))\n\n d1_m = Document(embedding=np.array([1, 0, 0]))\n d2_m = Document(embedding=np.array([2, 0, 0]))\n d3_m = Document(embedding=np.array([0, 0, 1]))\n d4_m = Document(embedding=np.array([0, 0, 2]))\n d5_m = Document(embedding=np.array([0, 0, 3]))\n\n return [d1, d2, d3, d4], [d1_m, d2_m, d3_m, d4_m, d5_m]\n\n\n@pytest.fixture\ndef docarrays_for_embedding_distance_computation(doc_lists):\n D1, D2 = doc_lists\n da1 = DocumentArray(D1)\n da2 = DocumentArray(D2)\n return da1, da2\n\n\n@pytest.fixture\ndef docarrays_for_embedding_distance_computation_sparse():\n d1 = Document(embedding=sp.csr_matrix([0, 0, 0]))\n d2 = Document(embedding=sp.csr_matrix([3, 0, 0]))\n d3 = Document(embedding=sp.csr_matrix([1, 0, 0]))\n d4 = Document(embedding=sp.csr_matrix([2, 0, 0]))\n\n d1_m = Document(embedding=sp.csr_matrix([1, 0, 0]))\n d2_m = Document(embedding=sp.csr_matrix([2, 0, 0]))\n d3_m = Document(embedding=sp.csr_matrix([0, 0, 1]))\n d4_m = Document(embedding=sp.csr_matrix([0, 0, 2]))\n d5_m = Document(embedding=sp.csr_matrix([0, 0, 3]))\n\n D1 = DocumentArray([d1, d2, d3, d4])\n D2 = DocumentArray([d1_m, d2_m, d3_m, d4_m, d5_m])\n return D1, D2\n\n\n@pytest.fixture\ndef embeddings():\n return np.array([[1, 0, 0], [2, 0, 0], [3, 0, 0]])\n\n\ndef doc_lists_to_doc_arrays(\n doc_lists, tmpdir, first_memmap, second_memmap, buffer_pool_size\n):\n doc_list1, doc_list2 = doc_lists\n\n tmpdir1, tmpdir2 = tmpdir / '1', tmpdir / '2'\n\n D1 = (\n DocumentArray()\n if not first_memmap\n else DocumentArrayMemmap(tmpdir1, buffer_pool_size=buffer_pool_size)\n )\n D1.extend(doc_list1)\n D2 = (\n DocumentArray()\n if not second_memmap\n else DocumentArrayMemmap(tmpdir2, buffer_pool_size=buffer_pool_size)\n )\n D2.extend(doc_list2)\n return D1, D2\n\n\n@pytest.mark.parametrize('buffer_pool_size', [1000, 3])\n@pytest.mark.parametrize('first_memmap', [True, False])\n@pytest.mark.parametrize('second_memmap', [True, False])\n@pytest.mark.parametrize(\n 'limit, batch_size', [(1, None), (2, None), (None, None), (1, 1), (1, 2), (2, 1)]\n)\ndef test_matching_retrieves_correct_number(\n doc_lists, limit, batch_size, first_memmap, second_memmap, tmpdir, buffer_pool_size\n):\n D1, D2 = doc_lists_to_doc_arrays(\n doc_lists,\n tmpdir,\n first_memmap,\n second_memmap,\n buffer_pool_size=buffer_pool_size,\n )\n D1.match(D2, metric='sqeuclidean', limit=limit, batch_size=batch_size)\n for m in D1.get_attributes('matches'):\n if limit is None:\n assert len(m) == len(D2)\n else:\n assert len(m) == limit\n\n\n@pytest.mark.parametrize('metric', ['sqeuclidean', 'cosine'])\ndef test_matching_same_results_with_sparse(\n docarrays_for_embedding_distance_computation,\n docarrays_for_embedding_distance_computation_sparse,\n metric,\n):\n D1, D2 = docarrays_for_embedding_distance_computation\n D1_sp, D2_sp = docarrays_for_embedding_distance_computation_sparse\n\n # use match with numpy arrays\n D1.match(D2, metric=metric)\n distances = []\n for m in D1.get_attributes('matches'):\n for d in m:\n distances.extend([d.scores[metric].value])\n\n # use match with sparse arrays\n D1_sp.match(D2_sp, metric=metric)\n distances_sparse = []\n for m in D1.get_attributes('matches'):\n for d in m:\n distances_sparse.extend([d.scores[metric].value])\n\n np.testing.assert_equal(distances, distances_sparse)\n\n\n@pytest.mark.parametrize('metric', ['sqeuclidean', 'cosine'])\ndef test_matching_same_results_with_batch(\n docarrays_for_embedding_distance_computation,\n metric,\n):\n D1, D2 = docarrays_for_embedding_distance_computation\n D1_batch = copy.deepcopy(D1)\n D2_batch = copy.deepcopy(D2)\n\n # use match without batches\n D1.match(D2, metric=metric)\n distances = []\n for m in D1.get_attributes('matches'):\n for d in m:\n distances.extend([d.scores[metric].value])\n\n # use match with batches\n D1_batch.match(D2_batch, metric=metric, batch_size=10)\n\n distances_batch = []\n for m in D1.get_attributes('matches'):\n for d in m:\n distances_batch.extend([d.scores[metric].value])\n\n np.testing.assert_equal(distances, distances_batch)\n\n\n@pytest.mark.parametrize('metric', ['euclidean', 'cosine'])\ndef test_matching_scipy_cdist(\n docarrays_for_embedding_distance_computation,\n metric,\n):\n def scipy_cdist_metric(X, Y, *args):\n return scipy_cdist(X, Y, metric=metric)\n\n D1, D2 = docarrays_for_embedding_distance_computation\n D1_scipy = copy.deepcopy(D1)\n\n # match with our custom metric\n D1.match(D2, metric=metric)\n distances = []\n for m in D1.get_attributes('matches'):\n for d in m:\n distances.extend([d.scores[metric].value])\n\n # match with callable cdist function from scipy\n D1_scipy.match(D2, metric=scipy_cdist_metric)\n distances_scipy = []\n for m in D1.get_attributes('matches'):\n for d in m:\n distances_scipy.extend([d.scores[metric].value])\n\n np.testing.assert_equal(distances, distances_scipy)\n\n\n@pytest.mark.parametrize('buffer_pool_size', [1000, 3])\n@pytest.mark.parametrize('first_memmap', [True, False])\n@pytest.mark.parametrize('second_memmap', [True, False])\n@pytest.mark.parametrize(\n 'normalization, metric',\n [\n (None, 'sqeuclidean'),\n ((0, 1), 'sqeuclidean'),\n (None, 'euclidean'),\n ((0, 1), 'euclidean'),\n (None, 'cosine'),\n ((0, 1), 'cosine'),\n ],\n)\n@pytest.mark.parametrize('use_scipy', [True, False])\ndef test_matching_retrieves_closest_matches(\n doc_lists,\n tmpdir,\n normalization,\n metric,\n use_scipy,\n first_memmap,\n second_memmap,\n buffer_pool_size,\n):\n \"\"\"\n Tests if match.values are returned 'low to high' if normalization is True or 'high to low' otherwise\n \"\"\"\n D1, D2 = doc_lists_to_doc_arrays(\n doc_lists,\n tmpdir,\n first_memmap,\n second_memmap,\n buffer_pool_size=buffer_pool_size,\n )\n D1.match(\n D2, metric=metric, limit=3, normalization=normalization, use_scipy=use_scipy\n )\n expected_sorted_values = [\n D1[0].matches[i].scores['sqeuclidean'].value for i in range(3)\n ]\n if normalization:\n assert min(expected_sorted_values) >= 0\n assert max(expected_sorted_values) <= 1\n else:\n assert expected_sorted_values == sorted(expected_sorted_values)\n\n\n@pytest.mark.parametrize(\n 'normalization, metric',\n [\n (None, 'sqeuclidean'),\n ((0, 1), 'sqeuclidean'),\n (None, 'euclidean'),\n ((0, 1), 'euclidean'),\n (None, 'cosine'),\n ((0, 1), 'cosine'),\n ],\n)\n@pytest.mark.parametrize('use_scipy', [True, False])\ndef test_docarray_match_docarraymemmap(\n docarrays_for_embedding_distance_computation,\n normalization,\n metric,\n tmpdir,\n use_scipy,\n):\n D1, D2 = docarrays_for_embedding_distance_computation\n D1_ = copy.deepcopy(D1)\n D2_ = copy.deepcopy(D2)\n D1.match(\n D2, metric=metric, limit=3, normalization=normalization, use_scipy=use_scipy\n )\n values_docarray = [m.scores[metric].value for d in D1 for m in d.matches]\n\n D2memmap = DocumentArrayMemmap(tmpdir)\n D2memmap.extend(D2_)\n D1_.match(\n D2memmap,\n metric=metric,\n limit=3,\n normalization=normalization,\n use_scipy=use_scipy,\n )\n values_docarraymemmap = [m.scores[metric].value for d in D1_ for m in d.matches]\n\n np.testing.assert_equal(values_docarray, values_docarraymemmap)\n\n\n@pytest.mark.parametrize(\n 'normalization, metric',\n [\n (None, 'hamming'),\n ((0, 1), 'hamming'),\n (None, 'minkowski'),\n ((0, 1), 'minkowski'),\n (None, 'jaccard'),\n ((0, 1), 'jaccard'),\n ],\n)\ndef test_scipy_dist(\n docarrays_for_embedding_distance_computation, normalization, metric, tmpdir\n):\n D1, D2 = docarrays_for_embedding_distance_computation\n D1_ = copy.deepcopy(D1)\n D2_ = copy.deepcopy(D2)\n D1.match(D2, metric=metric, limit=3, normalization=normalization, use_scipy=True)\n values_docarray = [m.scores[metric].value for d in D1 for m in d.matches]\n\n D2memmap = DocumentArrayMemmap(tmpdir)\n D2memmap.extend(D2_)\n D1_.match(\n D2memmap, metric=metric, limit=3, normalization=normalization, use_scipy=True\n )\n values_docarraymemmap = [m.scores[metric].value for d in D1_ for m in d.matches]\n\n np.testing.assert_equal(values_docarray, values_docarraymemmap)\n\n\n@pytest.mark.parametrize('buffer_pool_size', [1000, 3])\n@pytest.mark.parametrize('first_memmap', [True, False])\n@pytest.mark.parametrize('second_memmap', [True, False])\ndef test_2arity_function(\n first_memmap, second_memmap, doc_lists, tmpdir, buffer_pool_size\n):\n def dotp(x, y, *args):\n return np.dot(x, np.transpose(y))\n\n D1, D2 = doc_lists_to_doc_arrays(\n doc_lists,\n tmpdir,\n first_memmap,\n second_memmap,\n buffer_pool_size=buffer_pool_size,\n )\n D1.match(D2, metric=dotp, use_scipy=True)\n\n for d in D1:\n for m in d.matches:\n assert 'dotp' in m.scores\n\n\n@pytest.mark.parametrize('whiten', [True, False])\ndef test_pca_projection(embeddings, whiten):\n n_components = 2\n n_features = embeddings.shape[1]\n pca = PCA(n_components=n_components, whiten=whiten)\n assert pca.e_values is None\n assert pca.w is None\n embeddings_transformed = pca.fit_transform(embeddings)\n assert len(pca.e_values) == n_features\n assert pca.w.shape[0] == n_features\n assert embeddings_transformed.shape[1] == n_components\n\n\ndef test_pca_plot_generated(embeddings, tmpdir):\n doc_array = DocumentArray([Document(embedding=x) for x in embeddings])\n file_path = os.path.join(tmpdir, 'pca_plot.png')\n doc_array.visualize(output=file_path)\n assert os.path.exists(file_path)\n\n\ndef test_match_inclusive():\n \"\"\"Call match function, while the other :class:`DocumentArray` is itself\n or have same :class:`Document`.\n \"\"\"\n # The document array da1 match with itself.\n da1 = DocumentArray(\n [\n Document(embedding=np.array([1, 2, 3])),\n Document(embedding=np.array([1, 0, 1])),\n Document(embedding=np.array([1, 1, 2])),\n ]\n )\n\n da1.match(da1)\n assert len(da1) == 3\n traversed = da1.traverse_flat(traversal_paths=['m', 'mm', 'mmm'])\n assert len(traversed) == 9\n # The document array da2 shares same documents with da1\n da2 = DocumentArray([Document(embedding=np.array([4, 1, 3])), da1[0], da1[1]])\n da1.match(da2)\n assert len(da2) == 3\n traversed = da1.traverse_flat(traversal_paths=['m', 'mm', 'mmm'])\n assert len(traversed) == 9\n\n\ndef test_match_inclusive_dam(tmpdir):\n \"\"\"Call match function, while the other :class:`DocumentArray` is itself\n or have same :class:`Document`.\n \"\"\"\n # The document array da1 match with itself.\n dam = DocumentArrayMemmap(tmpdir)\n dam.extend(\n [\n Document(embedding=np.array([1, 2, 3])),\n Document(embedding=np.array([1, 0, 1])),\n Document(embedding=np.array([1, 1, 2])),\n ]\n )\n\n dam.match(dam)\n assert len(dam) == 3\n traversed = dam.traverse_flat(traversal_paths=['m', 'mm', 'mmm'])\n assert len(list(traversed)) == 9\n # The document array da2 shares same documents with da1\n da2 = DocumentArray([Document(embedding=np.array([4, 1, 3])), dam[0], dam[1]])\n dam.match(da2)\n assert len(da2) == 3\n traversed = dam.traverse_flat(traversal_paths=['m', 'mm', 'mmm'])\n assert len(list(traversed)) == 9\n\n\n@pytest.mark.parametrize('exclude_self, num_matches', [(True, 1), (False, 2)])\ndef test_match_exclude_self(exclude_self, num_matches):\n da1 = DocumentArray(\n [\n Document(id='1', embedding=np.array([1, 2])),\n Document(id='2', embedding=np.array([3, 4])),\n ]\n )\n da2 = DocumentArray(\n [\n Document(id='1', embedding=np.array([1, 2])),\n Document(id='2', embedding=np.array([3, 4])),\n ]\n )\n da1.match(da2, exclude_self=exclude_self)\n for d in da1:\n assert len(d.matches) == num_matches\n\n\n@pytest.fixture()\ndef get_pair_document_array():\n da1 = DocumentArray(\n [\n Document(id='1', embedding=np.array([1, 2])),\n Document(id='2', embedding=np.array([3, 4])),\n ]\n )\n da2 = DocumentArray(\n [\n Document(id='1', embedding=np.array([1, 2])),\n Document(id='2', embedding=np.array([3, 4])),\n Document(id='3', embedding=np.array([4, 5])),\n ]\n )\n yield da1, da2\n\n\n@pytest.mark.parametrize(\n 'limit, expect_len, exclude_self',\n [\n (2, 2, True),\n (1, 1, True),\n (3, 2, True),\n (2, 2, False),\n (1, 1, False),\n (3, 3, False),\n ],\n)\ndef test_match_exclude_self_limit_2(\n get_pair_document_array, exclude_self, limit, expect_len\n):\n da1, da2 = get_pair_document_array\n da1.match(da2, exclude_self=exclude_self, limit=limit)\n for d in da1:\n assert len(d.matches) == expect_len\n\n\n@pytest.mark.parametrize(\n 'lhs, rhs',\n [\n (DocumentArray(), DocumentArray()),\n (\n DocumentArray(\n [\n Document(embedding=np.array([3, 4])),\n Document(embedding=np.array([4, 5])),\n ]\n ),\n DocumentArray(\n [\n Document(embedding=np.array([3, 4])),\n Document(embedding=np.array([4, 5])),\n ]\n ),\n ),\n (\n DocumentArray(),\n DocumentArray(\n [\n Document(embedding=np.array([3, 4])),\n Document(embedding=np.array([4, 5])),\n ]\n ),\n ),\n (\n (\n DocumentArray(\n [\n Document(embedding=np.array([3, 4])),\n Document(embedding=np.array([4, 5])),\n ]\n )\n ),\n DocumentArray(),\n ),\n (None, DocumentArray()),\n (DocumentArray(), None),\n ],\n)\ndef test_match_none(lhs, rhs):\n if lhs is not None:\n lhs.match(rhs)\n if rhs is not None:\n rhs.match(lhs)\n\n\n@pytest.fixture()\ndef get_two_docarray():\n d1 = Document(embedding=np.array([0, 0, 0]))\n d1c1 = Document(embedding=np.array([0, 1, 0]))\n\n d2 = Document(embedding=np.array([1, 0, 0]))\n d2c1 = Document(embedding=np.array([1, 1, 0]))\n d2c2 = Document(embedding=np.array([1, 0, 1]))\n\n d3 = Document(embedding=np.array([2, 1, 1]))\n d3c1 = Document(embedding=np.array([2, 1, 0]))\n d3c2 = Document(embedding=np.array([2, 0, 1]))\n d3c3 = Document(embedding=np.array([2, 0, 0]))\n\n d4 = Document(embedding=np.array([3, 1, 1]))\n d4c1 = Document(embedding=np.array([3, 1, 0]))\n d4c2 = Document(embedding=np.array([3, 0, 1]))\n d4c3 = Document(embedding=np.array([3, 0, 0]))\n d4c4 = Document(embedding=np.array([3, 1, 1]))\n\n d1.chunks.extend([d1c1])\n d2.chunks.extend([d2c1, d2c2])\n d3.chunks.extend([d3c1, d3c2, d3c3])\n d4.chunks.extend([d4c1, d4c2, d4c3, d4c4])\n\n da1 = DocumentArray([d1, d2])\n da2 = DocumentArray([d3, d4])\n yield da1, da2\n\n\ndef test_match_with_traversal_path(get_two_docarray):\n da1, da2 = get_two_docarray\n da1.match(da2, traversal_rdarray=['c'])\n assert len(da1[0].matches) == len(da2[0].chunks) + len(da2[1].chunks)\n\n da2.match(da1, traversal_rdarray=['c'])\n assert len(da2[0].matches) == len(da1[0].chunks) + len(da1[1].chunks)\n\n\ndef test_match_on_two_sides_chunks(get_two_docarray):\n da1, da2 = get_two_docarray\n da2.match(da1, traversal_ldarray=['c'], traversal_rdarray=['c'])\n assert len(da2[0].matches) == 0\n assert len(da2[0].chunks[0].matches) == len(da1[0].chunks) + len(da1[1].chunks)\n\n da1.match(da2, traversal_ldarray=['c'], traversal_rdarray=['c'])\n assert len(da1[0].matches) == 0\n assert len(da1[0].chunks[0].matches) == len(da2[0].chunks) + len(da2[1].chunks)\n","sub_path":"tests/unit/types/arrays/test_neural_ops.py","file_name":"test_neural_ops.py","file_ext":"py","file_size_in_byte":16736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"491189538","text":"from os import listdir\nfrom PIL import Image\nimport os.path\nimport numpy as np\nimport glob\nimport tensorflow.keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Activation, Flatten\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D\n\npath_new_benign = r'/home/shah/PycharmProjects/FYP-Part1/dataset/benign'\npath_new_malware = r'/home/shah/PycharmProjects/FYP-Part1/dataset/malware'\n\nh = 256 #height of image\nw = 256 #width of image\n\n#be careful with using this function, it will consume memory, access to disk and time for Benign\nimages = []\nfor f in listdir(path_new_benign):\n with open(os.path.join(path_new_benign, f), 'rb') as img_set:\n img_arr = img_set.read(h*w)\n while img_arr:\n if len(img_arr) == h*w and img_arr not in images:\n images.append(img_arr)\n img_arr = img_set.read(h*w)\n\n#be careful with using this function, it will consume memory, access to disk and time for Malware\nimages2 = []\nfor f in listdir(path_new_malware):\n with open(os.path.join(path_new_malware, f), 'rb') as img_set2:\n img_arr2 = img_set2.read(h*w)\n while img_arr2:\n if len(img_arr2) == h*w and img_arr2 not in images2:\n images2.append(img_arr2)\n img_arr2 = img_set2.read(h*w)\n\n#And you can save them into png files for Benign\ncount = 0\nfor img in images:\n png = Image.fromarray(np.reshape(list(img), (h,w)).astype('float32'), mode='L')\n png.save('images/benign/image_l%d.png'%count)\n count += 1\n\n#And you can save them into png files for Malware\ncount2 = 0\nfor img2 in images2:\n png = Image.fromarray(np.reshape(list(img2), (h,w)).astype('float32'), mode='L')\n png.save('images/malware/image_l%d.png'%count)\n count += 1\n\n\n# reshape images to fit into the CNN model for Benign\nimg_list = np.zeros(shape=(len(images), h, w, 1), dtype=np.uint8)\nfor j in range(len(images)):\n img_list[j, :, :, 0] = np.reshape(list(images[j]), (h, w))\n\nimg_list = img_list.astype('float32')\nimg_list /= 255\n\n# reshape images2 to fit into the CNN model for Malware\nimg_list2 = np.zeros(shape=(len(images2), h, w, 1), dtype=np.uint8)\nfor j in range(len(images2)):\n img_list2[j, :, :, 0] = np.reshape(list(images2[j]), (h, w))\n\nimg_list2 = img_list2.astype('float32')\nimg_list2 /= 255\n\n\n\nmodel = Sequential()\n#Conv2D Layers\nmodel.add(Conv2D(12, (25, 25), padding='same',input_shape=img_list.shape[1:], activation = 'relu'))\nmodel.add(Conv2D(12, (25, 25), activation = 'relu'))\n#Max Pooling Layer\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n#Conv2D Layer\nmodel.add(Conv2D(12, (13, 13), padding='same', activation = 'relu'))\nmodel.add(Conv2D(12, (13, 13), activation = 'relu'))\n#Max Pooling\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n#Flattening Layer\nmodel.add(Flatten())\n#Dense Layer\nmodel.add(Dense(1024, activation = 'relu'))\nmodel.add(Dense(1, activation = 'sigmoid'))\n\nmodel.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['binary_accuracy'])\nmodel.summary()\n\n\n\n#\n#\n#Change the parameters to whatever suits you\nbenign_images = r'images/benign'\nmalicious_images = r'images/malware'\n\n\nbatch_size = 5\nepochs = 100\nlabels = [0 for _ in benign_images] + [1 for _ in malicious_images]\nmodel.fit(benign_images + malicious_images, labels, batch_size = batch_size, epochs = epochs,\n validation_split = 0.25,\n shuffle = True)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"368217506","text":"\"\"\"Scraps NY Times website and sends interesting news to my Telegram, based on keyworks\"\"\"\nimport urllib.request\nimport http.cookiejar\nimport os.path as PATH\nfrom telegram import Telegram\nfrom bs4 import BeautifulSoup\n\nCJ = http.cookiejar.CookieJar()\n\nURL = \"https://www.nytimes.com\"\nPAGE = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(CJ)).open(URL)\nSOUP = BeautifulSoup(PAGE.read())\nALLNEWS = SOUP.find_all('h2', class_='story-heading')\nALLNEWS += SOUP.find_all('h3', class_='story-heading')\nALLNEWS += SOUP.find_all('a', class_='story-link')\nTOKEN = '284151617:AAHrYeAUdA-MJW2D9aTJsn5643356Kkwe18'\nBOT_ID = 284151617\nMY_ID = 71247486\nBOT = Telegram(TOKEN, BOT_ID, MY_ID)\nKEYWORDS = ('mets', 'giants', 'cern', 'knicks', 'boxing', 'mma', 'ufc',\n 'portugal', 'physics', 'chess', 'nasa', 'health',\n 'literature', 'science', 'math', 'linux', 'tech',\n 'snowden', 'manning','photography')\n\nCACHE = []\n\nFILENAME = '/home/pi/Scripts/.news_cache'\nif not PATH.exists(FILENAME):\n NEWFILE = open(FILENAME, 'w+').close()\nSHOWN = open(FILENAME, 'r+')\n\ndef to_write(link):\n \"\"\"Function to determine if a news is new or not\"\"\"\n SHOWN.seek(0)\n new = True\n for line in SHOWN:\n if link in line:\n new = False\n break\n return new\n\ndef fetcher():\n \"\"\"This functions checks if a particular news is in the keywords and sends it in case it is\"\"\"\n news = [str(new).lower() for new in ALLNEWS]\n for story in news:\n for word in KEYWORDS:\n if word in story:\n news_list = str(story).split('\"')\n for item in news_list:\n item = str(item)\n if 'www.nytimes.com/' in item:\n if item not in CACHE and to_write(item):\n BOT.message(item)\n CACHE.append(item)\n SHOWN.write(item + '\\n')\n\nfetcher()\nSHOWN.close()\n","sub_path":"nyt.py","file_name":"nyt.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"356067577","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[5]:\n\n\nimport numpy as np\ndef puntodos(i,j,k): \n if k>=int(n/2)**2+2*int(n/2)+2:#caso base\n return z\n elif j=0):#SUBIENDO\n z[i][j]=k\n if(j>0):\n k=k+1\n z[n-1-i-j][j]=k\n if(i>0):\n puntodos(i-1,j+1,k+1)\n elif j>=int(n/2) and (i<=int(n/2)):#BAJANDO\n z[i][j]=k\n k=k+1\n if j-i==i and k= 0:\n for optimizer in six.itervalues(self._optimizers):\n optimizer.target.to_gpu(device)\n\n self.converter = converter\n self.loss_func = loss_func\n self.device = device\n self.iteration = 0\n\n self.loss_scale = loss_scale\n if loss_scale is not None:\n for optimizer in six.itervalues(self._optimizers):\n optimizer.set_loss_scale(loss_scale)\n\n self.auto_new_epoch = auto_new_epoch\n if auto_new_epoch:\n for o in six.itervalues(self._optimizers):\n o.use_auto_new_epoch = True\n\n def first_iter(self):\n self.f_val=True\n\n def update(self):\n #print(\"#1:{0}\".format(self._iterators['main'].next()))\n '''\n if(self._iterators['main'].is_new_epoch is True or self.f_val is True):\n self.update_core()\n self.f_val=False\n else:\n self.update_vat()\n '''\n #1\n #print(\"#1:{0}\".format(self._iterators['main'].current_position))\n #self.update_core()\n #print(\"#2:{0}\".format(self._iterators['main'].current_position))\n #iterator=self._iterators['main']\n\n self.update_vat()\n #print(\"#3:{0}\".format(self._iterators['main'].current_position))\n #print(self.iteration)\n #print(iterator.epoch)\n #print(iterator.epoch_detail)\n #print(iterator.previous_epoch_detail)\n self.iteration += 1\n #print(self._iterators['main'].is_new_epoch)\n\n\n def update_vat(self):\n iterator=self._iterators['main']\n batch = iterator.next()\n\n iterator_ul=self._iterators_ul['main']\n batch_ul = iterator_ul.next()\n #print(batch)\n in_arrays = self.converter(batch, self.device)\n in_arrays_ul = self.converter(batch_ul, self.device)\n #print(in_arrays)\n optimizer = self._optimizers['main']\n loss_func = optimizer.target\n #print(in_arrays[0] )\n #optimizer.zero_grads()\n #optimizer.cleargrad()\n #optimizer.update(loss_func, in_arrays[0])\n\n\n #print(np.sum(in_arrays[0][0]))\n #print(in_arrays_ul[0].shape)\n\n if isinstance(in_arrays, tuple):\n #optimizer.update(loss_func, *in_arrays)\n loss_l=loss_func(*in_arrays)\n elif isinstance(in_arrays, dict):\n #optimizer.update(loss_func, **in_arrays)\n loss_l=loss_func(**in_arrays)\n else:\n #optimizer.update(loss_func, in_arrays)\n loss_l=loss_func(in_arrays)\n\n #print(in_arrays_ul[0])\n #optimizer.update(loss_func, in_arrays_ul[0])\n loss_ul=loss_func(in_arrays_ul[0])\n loss_total=loss_l+loss_ul\n loss_func.cleargrads()\n loss_total.backward()\n #print(self.iteration)\n #print(optimizer.alpha)\n\n if(self.iteration >= 500 and self.iteration % 500 == 0):\n #print(\"alpha change\")\n optimizer.alpha *= 0.9\n\n optimizer.update()\n\n #print(iterator.is_new_epoch)\n if self.auto_new_epoch and iterator.is_new_epoch:\n optimizer.new_epoch(auto=True)\n #optimizer.zero_grads()\n #optimizer.cleargrad()\n\n\ndef vat_loss_function(\n x, t, normalize=True, cache_score=True, class_weight=None,\n ignore_label=-1, reduce='mean', enable_double_backprop=False):\n '''\n if enable_double_backprop:\n return _double_backward_softmax_cross_entropy(\n x, t, normalize, class_weight, ignore_label, reduce)\n else:\n return SoftmaxCrossEntropy(\n normalize, cache_score, class_weight, ignore_label, reduce)(x, t)\n '''\n if t is not None:\n #h = self.predict(x)\n loss = F.softmax_cross_entropy(x, t)\n chainer.report({'loss': loss, 'accuracy': F.accuracy(x, t)}, self)\n return loss\n else:\n #return vat(self, distance, x, self.eps)\n return vat(self,distance, x, 1.0)\n","sub_path":"lib/vat.py","file_name":"vat.py","file_ext":"py","file_size_in_byte":9982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"480812158","text":"#! /bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 6 11:20:44 2017\n\n@author: tipputa\n\"\"\"\n\nimport pandas as pd\nimport sys, os\nimport createOrthologousGenes as createOrtho\nimport createCircos as createCircos\nimport timeRecord as recorder\n\nuseage = \"\"\"\n\nError: please input the absolute PATH of output and genbank directories .\n\nUsage: \n python runAllProcess.py \n e.g: python runAllProcess.py ~/study/ ~/study/gb/\n\"\"\"\n\nif __name__ == '__main__':\n timeRecorder = []\n recordAll = recorder.timeRecord()\n\n if len(sys.argv)==3:\n RootDir = sys.argv[1] + \"/\"\n gbDir = sys.argv[2] + \"/\"\n \n else: \n print(useage)\n quit()\n \n os.chdir(RootDir)\n createOrtho.runs(timeRecorder, RootDir, gbDir)\n df = pd.read_csv(RootDir + '/data/all_blast_results.tsv', delimiter = \"\\t\")\n createCircos.runs(df, timeRecorder, RootDir, gbDir)\n recordAll.fin(\"All process\", timeRecorder)\n print(\"\\n\\nFin.\")\n pd.Series(timeRecorder).to_csv(RootDir + \"Calculation_times.txt\", header = None, index = None)\n","sub_path":"bin_singularity/runAllProcess.py","file_name":"runAllProcess.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"329600619","text":"import os\r\nfrom collections import Counter\r\nfrom typing import Optional, Any\r\n\r\nimport numpy as np\r\nfrom PIL import Image\r\nfrom matplotlib import pyplot as plt\r\nfrom sklearn.cluster import KMeans\r\n\r\n\r\ndef rgb2hex(rgb):\r\n hex = \"#{:02x}{:02x}{:02x}\".format(int(rgb[0]), int(rgb[1]), int(rgb[2]))\r\n # hex = f\"#{rgb[0]}{}{}\"\r\n return hex\r\n\r\n\r\nrgb = [0, 1, 2]\r\nhex = [\"#\"]\r\n[hex.append(f\"{c:}\") for c in rgb]\r\n''.join(hex)\r\n\r\nPATH = \"./SOLO1.jpg\"\r\nWIDTH = 128\r\nHEIGHT = 128\r\nCLUSTERS = 6\r\n\r\nimage: Optional[Any] = Image.open(PATH)\r\n\r\nvar = image.size\r\n\r\nprint(\"Loaded {f} image. Size: {s:.2f} KB. Dimensions: ({d})\".format(\r\n f=image.format, s=os.path.getsize(PATH) / 1024, d=image.size))\r\n\r\nimage\r\n\r\n\r\n# DADOS E DIMENSÕES DA IMAGEM FOI APRESENTADA NA TELA\r\n# EM SEGUIDA A FUNÇÃO VAI CALCULAR OS DADOS - MINERAR\r\n\r\ndef calculate_new_size(image):\r\n if image.width >= image.height:\r\n wpercent = (WIDTH / float(image.width))\r\n hsize = int((float(image.height) * float(wpercent)))\r\n new_width, new_height = WIDTH, hsize\r\n else:\r\n hpercent = (HEIGHT / float(image.height))\r\n wsize = int((float(image.width) * float(hpercent)))\r\n new_width, new_height = wsize, HEIGHT\r\n\r\n image.resize((new_width, new_height), Image.ANTIALIAS)\r\n return image, new_width, new_height\r\n\r\n\r\n# AGORA A APRENDIZAGEM DE MAQUINA (MACHINE LEARNING) A FUNÇÃO DEVE AGRUPAR SIMILARES\r\n\r\nnew_image, new_width, new_height = calculate_new_size(image)\r\nprint(f\"New dimensions: {new_width}x{new_height}\")\r\nimg_array = np.array(new_image)\r\nimg_vector = img_array.reshape((img_array.shape[0] * img_array.shape[1], 3))\r\nnew_image\r\n\r\nmodel = KMeans(n_clusters=CLUSTERS)\r\nlabels = model.fit_predict(img_vector)\r\nlabel_counts = Counter(labels)\r\nmodel.cluster_centers_\r\n\r\ntotal_count = sum(label_counts.values())\r\ntotal_count\r\n\r\nhex_colors = [rgb2hex(center) for center in model.cluster_centers_]\r\nhex_colors\r\n\r\nhex_colors\r\n\r\n# AGRUPOU NAS CORES ACIMA EM FORMATO HEX - '#a89679', '#968468', '#c7c4c7', '#645c53', '#827158', '#afabab' \r\n# PRECISO QUE DÊ EM MUNSELL TIPO - colour.xyY_to_munsell_colour([0.38736945, 0.35751656, 0.59362000]) DANDO ISSO '4.2YR 8.1/5.3'\r\n\r\nlist(zip(hex_colors, list(label_counts.values())))\r\n\r\n# FEZ UMA LISTA ASSOCIANDO A QUANTIDADE DE PIXEL, ACREDITO QUE SEJA ISSO. / DE SIMILARES PREDOMINANTES\r\n\r\nplt.figure(figsize=(14, 8))\r\n\r\nplt.subplot(221)\r\n\r\nplt.imshow(image)\r\n\r\nplt.axis('off')\r\n\r\nplt.subplot(222)\r\n\r\nplt.pie(label_counts.values(), labels=hex_colors, colors=[color / 255 for color in model.cluster_centers_],\r\n autopct='%1.1f%%',\r\n shadow=True, startangle=90)\r\n\r\nplt.axis('equal')\r\n\r\nplt.title('CORES DO SOLO')\r\n\r\nplt.show()","sub_path":"detector de cor ML.py","file_name":"detector de cor ML.py","file_ext":"py","file_size_in_byte":2697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"381537865","text":"#!/usr/bin/python3\n# coding: utf-8\n\nimport os\nimport smtplib\nfrom email import encoders\nfrom email.header import Header\nfrom email.mime.text import MIMEText\nfrom email.utils import parseaddr\nfrom email.utils import formataddr\n\n\ndef format_addr(s):\n name, addr = parseaddr(s)\n return formataddr((Header(name, \"utf-8\").encode(), addr))\n\n\ndef send_mail(to_list, content):\n from_email = \"newsmonitor@126.com\"\n from_email_pwd = os.getenv('email_pass')\n smtp_server = \"smtp.126.com\"\n msg = MIMEText(\n content,\n \"html\", \"utf-8\")\n msg[\"From\"] = format_addr(\"%s\" % (from_email))\n msg[\"To\"] = ','.join([format_addr(\"%s\" % (to_email))\n for to_email in to_list])\n msg[\"Subject\"] = Header(\"python email\", \"utf-8\").encode()\n\n server = smtplib.SMTP(smtp_server, 25)\n server.set_debuglevel(1)\n server.login(from_email, from_email_pwd)\n server.sendmail(from_email, to_list, msg.as_string())\n server.close()\n\n\nif __name__ == '__main__':\n content = '

hello

hello, send by python

'\n send_mail(['newsmonitor@126.com'], content)\n","sub_path":"__mail.py","file_name":"__mail.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"412054162","text":"# Character recognition software is\n# widely used to digitise printed texts.\n# Thus the texts can be edited, searched\n# and stored on a computer.\n#\n# When documents (especially pretty old\n# ones written with a typewriter), are\n# digitised character recognition softwares\n# often make mistakes.\n#\n# Your task is correct the errors in the\n# digitised text. You only have to handle\n# the following mistakes:\n#\n# S is misinterpreted as 5\n# O is misinterpreted as 0\n# I is misinterpreted as 1\n# The test cases contain numbers only by mistake.\n\ndef correct(string):\n\n mapping = {\n \"0\": \"O\",\n \"1\": \"I\",\n \"5\": \"S\"\n }\n\n new_string = \"\"\n\n for c in string:\n if c in mapping:\n c = mapping[c]\n new_string += c\n else:\n new_string += c\n\n return new_string\n\nprint(correct(\"L0ND0N\"),\"LONDON\");\nprint(correct(\"DUBL1N\"),\"DUBLIN\");\nprint(correct(\"51NGAP0RE\"),\"SINGAPORE\");\nprint(correct(\"BUDAPE5T\"),\"BUDAPEST\");\nprint(correct(\"PAR15\"),\"PARIS\");\n","sub_path":"8 kyu/18_09_20_correct_the_mistakes_of_the_character_recognition_software.py","file_name":"18_09_20_correct_the_mistakes_of_the_character_recognition_software.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"462236548","text":"import json\n\nimport arrow\nimport dateutil\nimport dateutil.parser\n\n\nclass Tick:\n def __init__(self, time, price, volume=0, bids=None, asks=None, contract=None,\n source=None,\n exchange_time=None,\n amount=None,\n **kwargs):\n\n # internally use python3's datetime\n if isinstance(time, arrow.Arrow):\n time = time.datetime\n assert time.tzinfo\n self.contract = contract\n self.source = source\n self.time = time\n self.price = price\n self.volume = volume\n self.amount = amount\n self.bids = []\n self.asks = []\n self.exchange_time = exchange_time\n if bids:\n self.bids = sorted(bids, key=lambda x: -x['price'])\n if asks:\n self.asks = sorted(asks, key=lambda x: x['price'])\n for item in self.bids:\n assert 'price' in item and 'volume' in item and len(item) == 2\n for item in self.asks:\n assert 'price' in item and 'volume' in item and len(item) == 2\n # self.asks = asks\n\n # last as an candidate of last\n @property\n def last(self):\n return self.price\n\n @last.setter\n def last(self, value):\n self.price = value\n\n @property\n def bid1(self):\n if self.bids:\n return self.bids[0]['price']\n return None\n\n @property\n def ask1(self):\n if self.asks:\n return self.asks[0]['price']\n return None\n\n @property\n def weighted_middle(self):\n a = self.bids[0]['price'] * self.asks[0]['volume']\n b = self.asks[0]['price'] * self.bids[0]['volume']\n return (a + b) / (self.asks[0]['volume'] + self.bids[0]['volume'])\n\n def get_interest_side(self, bs):\n if bs == 's':\n return self.bids\n if bs == 'b':\n return self.asks\n\n def __str__(self):\n return '<{} {}.{:03d} {}/{} {} {}>'.format(self.contract,\n self.time.strftime('%H:%M:%S'),\n self.time.microsecond // 1000,\n self.bid1,\n self.ask1,\n self.last,\n self.volume)\n\n def __repr__(self):\n return str(self)\n\n @staticmethod\n def init_with_dict(dct):\n return Tick(dct['time'], dct['price'], dct['volume'], dct['bids'], dct['asks'])\n\n def to_dict(self):\n dct = {'time': self.time.isoformat(), 'price': self.price, 'volume': self.volume, 'asks': self.asks,\n 'bids': self.bids}\n if self.exchange_time:\n dct['exchange_time'] = self.exchange_time.isoformat()\n if self.contract:\n dct['symbol'] = self.contract\n return dct\n\n # @staticmethod\n # def from_dct(dct):\n # # con = ContractApi.get_by_symbol(dct['symbol'])\n # con = dct['symbol']\n # return Tick(time=dateutil.parser.parse(dct['time']), price=dct['price'], bids=dct['bids'], asks=dct['asks'],\n # contract=con, volume=dct['volume'])\n\n def to_mongo_dict(self):\n dct = {'time': self.time, 'price': self.price, 'volume': self.volume, 'asks': self.asks, 'bids': self.bids}\n if self.contract:\n dct['contract'] = self.contract\n return dct\n\n def to_short_list(self):\n b = ','.join(['{},{}'.format(x['price'], x['volume']) for x in self.bids])\n a = ','.join(['{},{}'.format(x['price'], x['volume']) for x in self.asks])\n lst = [self.contract, self.time.timestamp(), self.price, self.volume, b, a]\n return lst\n\n @staticmethod\n def from_short_list(lst):\n if isinstance(lst[0], str):\n # convert string to contract\n # lst[0] = ContractApi.get_by_symbol(lst[0])\n lst[0] = lst[0]\n bids, asks = lst[4], lst[5]\n bids = [{'price': float(p), 'volume': float(v)} for p, v in zip(bids.split(',')[::2], bids.split(',')[1::2])]\n asks = [{'price': float(p), 'volume': float(v)} for p, v in zip(asks.split(',')[::2], asks.split(',')[1::2])]\n\n time = arrow.Arrow.fromtimestamp(lst[1]).datetime\n return Tick(contract=lst[0], time=time, price=lst[2], volume=lst[3], bids=bids, asks=asks)\n\n def to_ws_str(self):\n lst = self.to_short_list()\n return json.dumps(lst)\n\n @classmethod\n def from_dict(cls, dict_or_str):\n if isinstance(dict_or_str, str):\n return cls.from_dict(json.loads(dict_or_str))\n d = dict_or_str\n t = Tick(time=arrow.get(d['time']),\n # contract=ContractApi.get_by_symbol(d['contract']),\n contract=d['contract'],\n volume=d['volume'],\n asks=d['asks'],\n bids=d['bids'],\n price=d['last'],\n source=d.get('source', None),\n )\n return t\n\n def bs1(self, bs):\n if bs == 'b':\n return self.bid1\n else:\n return self.ask1\n","sub_path":"onetoken/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"30864710","text":"# each method in class takes instance as the first argument\n# below is converting regular method to class method\nclass Employee :\n\t\n\tnum_of_employees = 0\n\traise_amount = 1.4\n\n\tdef __init__(self,first,last,pay):\n\t\tself.first = first\n\t\tself.last = last\n\t\tself.pay = pay\n\t\tself.email = first+'.'+last+'@company.com'\n\t\tEmployee.num_of_employees += 1\n\n\n\tdef fullname(self) :\n\t\treturn '{} {}'.format(self.first,self.last)\n\n\tdef apply_raise(self):\n\t\tself.pay = int(self.pay * self.raise_amount)\n\t\t# we can also access self.raise_amount\n\n\t@classmethod\n\tdef set_raise_amt(cls,amount):\n\t\tcls.raise_amount = amount\n\n\t\n\nemp_1 = Employee('Pranav','Kamat',60000)\nemp_2 = Employee('Gayatri','Kamat',50000)\nprint(\"total number of employees is \")\nprint(Employee.num_of_employees)\n\nEmployee.set_raise_amt(1.5)\nprint(Employee.raise_amount)\nprint(emp_1.raise_amount)\nprint(emp_2.raise_amount)\n\n# even emp_1.set_raise_amt(1.6) works same unexpectadly\n\n","sub_path":"OOPS/methods.py","file_name":"methods.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"208210897","text":"from copy import deepcopy\nfrom scipy import linalg as spla\nimport numpy as np\nimport pycufsm.analysis\n\n# Originally developed for MATLAB by Benjamin Schafer PhD et al\n# Ported to Python by Brooks Smith MEng, PE, CPEng\n#\n# Each function within this file was originally its own separate file.\n# Original MATLAB comments, especially those retaining to authorship or\n# change history, have been generally retained unaltered\n\n\ndef base_column(\n nodes_base, elements, props, length, b_c, m_a, el_props, node_props, n_main_nodes,\n n_corner_nodes, n_sub_nodes, n_global_modes, n_dist_modes, n_local_modes, dof_perm, r_x, r_z,\n r_ys, d_y\n):\n # this routine creates base vectors for a column with length length for all the\n # specified longitudinal terms in m_a\n\n # assumptions\n # orthogonalization is not performed unless the user wants\n # orthogonalization is done by solving the eigen-value problem within each sub-space\n # normalization is not done\n\n # input data\n # nodes, elements, props - basic data\n # b_c: ['S-S'] a string specifying boundary conditions to be analyzed:\n #'S-S' simply-pimply supported boundary condition at loaded edges\n #'C-C' clamped-clamped boundary condition at loaded edges\n #'S-C' simply-clamped supported boundary condition at loaded edges\n #'C-F' clamped-free supported boundary condition at loaded edges\n #'C-bulk' clamped-guided supported boundary condition at loaded edges\n # m_a - longitudinal terms (half-wave numbers)\n\n # output data\n # b_v_l - base vectors (each column corresponds to a certain mode)\n # assemble for each half-wave number m_i on its diagonal\n # b_v_l = diag(b_v_m)\n # for each half-wave number m_i, b_v_m\n # columns 1..n_global_modes: global modes\n # columns (n_global_modes+1)..(n_global_modes+n_dist_modes): dist. modes\n # columns (n_global_modes+n_dist_modes+1)\n # ..(n_global_modes+n_dist_modes+n_local_modes): local modes\n # columns (n_global_modes+n_dist_modes+n_local_modes+1)..n_dof: other modes\n # n_global_modes, n_dist_modes, n_local_modes - number of bulk, D, L modes, respectively\n #\n\n # S. Adany, Aug 28, 2006\n # B. Schafer, Aug 29, 2006\n # Z. Li, Dec 22, 2009\n # Z. Li, June 2010\n\n # construct the base for all the longitudinal terms\n n_nodes = len(nodes_base)\n n_dof_m = 4*n_nodes\n total_m = len(m_a)\n b_v_l = np.zeros((n_dof_m*total_m, n_dof_m*total_m))\n for i, m_i in enumerate(m_a):\n # to create r_p constraint matrix for the rest of planar DOFs\n r_p = constr_planar_xz(\n nodes_base, elements, props, node_props, dof_perm, m_i, length, b_c, el_props\n )\n b_v_m = base_vectors(\n d_y=d_y,\n elements=elements,\n el_props=el_props,\n length=length,\n m_i=m_i,\n node_props=node_props,\n n_main_nodes=n_main_nodes,\n n_corner_nodes=n_corner_nodes,\n n_sub_nodes=n_sub_nodes,\n n_global_modes=n_global_modes,\n n_dist_modes=n_dist_modes,\n n_local_modes=n_local_modes,\n r_x=r_x,\n r_z=r_z,\n r_p=r_p,\n r_ys=r_ys,\n dof_perm=dof_perm\n )\n b_v_l[(n_dof_m*i):n_dof_m*(i + 1), (n_dof_m*i):n_dof_m*(i + 1)] = b_v_m\n\n return b_v_l\n\n\ndef base_update(\n gbt_con, b_v_l, length, m_a, nodes, elements, props, n_global_modes, n_dist_modes,\n n_local_modes, b_c, el_props\n):\n # this routine optionally makes orthogonalization and normalization of base vectors\n\n # assumptions\n # orthogonalization is done by solving the EV problem for each sub-space\n # three options for normalization is possible, set by 'gbt_con['norm']' parameter\n\n # input data\n # gbt_con['o_space'] - by gbt_con, choices of ST/O mode\n # 1: ST basis\n # 2: O space (null space of GDL) with respect to k_global\n # 3: O space (null space of GDL) with respect to kg_global\n # 4: O space (null space of GDL) in vector sense\n # gbt_con['norm'] - by gbt_con, code for normalization (if normalization is done at all)\n # 0: no normalization,\n # 1: vector norm\n # 2: strain energy norm\n # 3: work norm\n # b_v_l - natural base vectors for length (each column corresponds to a certain mode)\n # for each half-wave number m_i\n # columns 1..n_global_modes: global modes\n # columns (n_global_modes+1)..(n_global_modes+n_dist_modes): dist. modes\n # columns (n_global_modes+n_dist_modes+1)\n # ..(n_global_modes+n_dist_modes+n_local_modes): local modes\n # columns (n_global_modes+n_dist_modes+n_local_modes+1)..n_dof_m: other modes\n # length - length\n # m_a, nodes, elements, props - as usual\n # n_global_modes, n_dist_modes, n_local_modes - nr of modes\n # b_c - boundary condition, 'S-S','C-C',...etc., as usual\n # gbt_con['couple'] - by gbt_con, coupled basis vs uncoupled basis for general B.C.\n # especially for non-simply supported B.C.\n # 1: uncoupled basis, the basis will be block diagonal\n # 2: coupled basis, the basis is fully spanned\n # gbt_con['orth'] - by gbt_con, natural basis vs modal basis\n # 1: natural basis\n # 2: modal basis, axial orthogonality\n # 3: modal basis, load dependent orthogonality\n\n # output data\n # b_v - output base vectors (maybe natural, orthogonal or normalized,\n # depending on the selected options)\n\n # S. Adany, Oct 11, 2006\n # Z. Li modified on Jul 10, 2009\n # Z. Li, June 2010\n\n n_nodes = len(nodes[:, 1])\n n_dof_m = 4*n_nodes\n total_m = len(m_a) # Total number of longitudinal terms m_i\n b_v = np.zeros((n_dof_m*total_m, n_dof_m*total_m))\n\n if gbt_con['couple'] == 1:\n # uncoupled basis\n for i, m_i in enumerate(m_a):\n b_v_m = b_v_l[n_dof_m*i:n_dof_m*(i + 1), n_dof_m*i:n_dof_m*(i + 1)]\n # k_global/kg_global\n if gbt_con['norm'] == 2 or gbt_con['norm'] == 3 \\\n or gbt_con['o_space'] == 2 or gbt_con['o_space'] == 3 \\\n or gbt_con['orth'] == 2 or gbt_con['orth'] == 3:\n # axial loading or real loading by either gbt_con['orth'] = 2 or gbt_con['orth'] = 3\n if gbt_con['orth'] == 1 or gbt_con['orth'] == 2:\n nodes_base = deepcopy(nodes)\n nodes_base[:, 7] = np.ones_like(nodes[:, 7]) # set u_p stress to 1.0 (axial)\n [k_global, kg_global] = create_k_globals(\n m_i=m_i,\n nodes=nodes_base,\n elements=elements,\n el_props=el_props,\n props=props,\n length=length,\n b_c=b_c\n )\n else:\n [k_global, kg_global] = create_k_globals(\n m_i=m_i,\n nodes=nodes,\n elements=elements,\n el_props=el_props,\n props=props,\n length=length,\n b_c=b_c\n )\n\n # orthogonalization/normalization begins\n #\n if gbt_con['orth'] == 2 or gbt_con['orth'] == 3 \\\n or gbt_con['o_space'] == 2 or gbt_con['o_space'] == 3 or gbt_con['o_space'] == 4:\n # indices\n if gbt_con['o_space'] == 1:\n dof_index = np.zeros((5, 2))\n dof_index[3, 0] = n_global_modes + n_dist_modes + n_local_modes\n dof_index[3, 1] = n_global_modes + n_dist_modes + n_local_modes + n_nodes - 1\n dof_index[4, 0] = n_global_modes + n_dist_modes + n_local_modes + n_nodes - 1\n dof_index[4, 1] = n_dof_m\n else:\n dof_index = np.zeros((4, 2))\n dof_index[3, 0] = n_global_modes + n_dist_modes + n_local_modes\n dof_index[3, 1] = n_dof_m\n dof_index[0, 0] = 0\n dof_index[0, 1] = n_global_modes\n dof_index[1, 0] = n_global_modes\n dof_index[1, 1] = n_global_modes + n_dist_modes\n dof_index[2, 0] = n_global_modes + n_dist_modes\n dof_index[2, 1] = n_global_modes + n_dist_modes + n_local_modes\n\n # define vectors for other modes, gbt_con['o_space'] = 2, 3, 4\n if gbt_con['o_space'] == 2:\n a_matrix = spla.null_space(b_v_m[:, dof_index[0, 0]:dof_index[2, 1]].conj().T)\n b_v_m[:, dof_index[3, 0]:dof_index[3, 1]] = np.linalg.solve(k_global, a_matrix)\n if gbt_con['o_space'] == 3:\n a_matrix = spla.null_space(b_v_m[:, dof_index[0, 0]:dof_index[2, 1]].conj().T)\n b_v_m[:, dof_index[3, 0]:dof_index[3, 1]] = np.linalg.solve(kg_global, a_matrix)\n if gbt_con['o_space'] == 4:\n a_matrix = spla.null_space(b_v_m[:, dof_index[0, 0]:dof_index[2, 1]].conj().T)\n b_v_m[:, dof_index[3, 0]:dof_index[3, 1]] = a_matrix\n\n # orthogonalization for modal basis 2/3 + normalization for normals 2/3\n for dof_sub in dof_index:\n dof_sub1 = int(dof_sub[1])\n dof_sub0 = int(dof_sub[0])\n if dof_sub[1] >= dof_sub[0]:\n k_global_sub \\\n = b_v_m[:, dof_sub0:dof_sub1].conj().T @ \\\n k_global @ b_v_m[:, dof_sub0:dof_sub1]\n kg_global_sub \\\n = b_v_m[:, dof_sub0:dof_sub1].conj().T @ \\\n kg_global @ b_v_m[:, dof_sub0:dof_sub1]\n [eigenvalues, eigenvectors] = spla.eig(a=k_global_sub, b=kg_global_sub)\n lf_sub = np.real(eigenvalues)\n indexsub = np.argsort(lf_sub)\n lf_sub = lf_sub[indexsub]\n eigenvectors = np.real(eigenvectors[:, indexsub])\n if gbt_con['norm'] == 2 or gbt_con['norm'] == 3:\n if gbt_con['norm'] == 2:\n s_matrix = eigenvectors.conj().T @ k_global_sub @ eigenvectors\n\n if gbt_con['norm'] == 3:\n s_matrix = eigenvectors.conj().T @ kg_global_sub @ eigenvectors\n\n s_matrix = np.diag(s_matrix)\n for j in range(0, int(dof_sub[1] - dof_sub[0])):\n eigenvectors[:, j] = np.transpose(\n np.conj(\n np.linalg.lstsq(\n eigenvectors[:, j].conj().T,\n np.sqrt(s_matrix).conj().T\n )\n )\n )\n\n b_v_m[:, dof_sub0:dof_sub1] \\\n = b_v_m[:, dof_sub0:dof_sub1] @ eigenvectors\n\n # normalization for gbt_con['o_space'] = 1\n if (gbt_con['norm'] == 2 or gbt_con['norm'] == 3) and gbt_con['o_space'] == 1:\n for j in range(0, n_dof_m):\n if gbt_con['norm'] == 2:\n b_v_m[:, j] = np.transpose(\n np.conj(\n np.linalg.lstsq(\n b_v_m[:, j].conj().T,\n np.sqrt(b_v_m[:, j].conj().T @ k_global @ b_v_m[:, j]).conj().T\n )\n )\n )\n\n if gbt_con['norm'] == 3:\n b_v_m[:, j] = np.transpose(\n np.conj(\n np.linalg.lstsq(\n b_v_m[:, j].conj().T,\n np.sqrt(b_v_m[:, j].conj().T @ kg_global @ b_v_m[:, j]).conj().T\n )\n )\n )\n\n # normalization for gbt_con['norm'] 1\n if gbt_con['norm'] == 1:\n for j in range(0, n_dof_m):\n b_v_m[:, j] = b_v_m[:, j]/np.sqrt(b_v_m[:, j].conj().T @ b_v_m[:, j])\n\n b_v[n_dof_m*i:n_dof_m*(i + 1), n_dof_m*i:n_dof_m*(i + 1)] = b_v_m\n\n else:\n # coupled basis\n # k_global/kg_global\n if gbt_con['norm'] == 2 or gbt_con['norm'] == 3 \\\n or gbt_con['o_space'] == 2 or gbt_con['o_space'] == 3 \\\n or gbt_con['orth'] == 2 or gbt_con['orth'] == 3:\n # axial loading or real loading by either gbt_con['orth'] = 2 or gbt_con['orth'] = 3\n if gbt_con['orth'] == 1 or gbt_con['orth'] == 2:\n nodes_base = deepcopy(nodes)\n nodes_base[:, 7] = np.ones_like(nodes[:, 7]) # set u_p stress to 1.0 (axial)\n else:\n nodes_base = nodes\n\n # ZERO OUT THE GLOBAL MATRICES\n k_global = np.zeros((4*n_nodes*total_m, 4*n_nodes*total_m))\n kg_global = np.zeros((4*n_nodes*total_m, 4*n_nodes*total_m))\n\n # ASSEMBLE THE GLOBAL STIFFNESS MATRICES\n for i, elem in enumerate(elements):\n # Generate element stiffness matrix (k_local) in local coordinates\n thick = elem[3]\n b_strip = el_props[i, 1]\n mat_num = int(elem[4])\n row = int((np.argwhere(props[:, 0] == mat_num)).reshape(1))\n mat = props[row]\n stiff_x = mat[1]\n stiff_y = mat[2]\n nu_x = mat[3]\n nu_y = mat[4]\n bulk = mat[5]\n k_l = pycufsm.analysis.klocal(\n stiff_x=stiff_x,\n stiff_y=stiff_y,\n nu_x=nu_x,\n nu_y=nu_y,\n bulk=bulk,\n thick=thick,\n length=length,\n b_strip=b_strip,\n b_c=b_c,\n m_a=m_a\n )\n # Generate geometric stiffness matrix (kg_local) in local coordinates\n node_i = int(elem[1])\n node_j = int(elem[2])\n ty_1 = nodes_base[node_i][7]*thick\n ty_2 = nodes_base[node_j][7]*thick\n kg_l = pycufsm.analysis.kglocal(\n length=length, b_strip=b_strip, ty_1=ty_1, ty_2=ty_2, b_c=b_c, m_a=m_a\n )\n # Transform k_local and kg_local into global coordinates\n alpha = el_props[i, 2]\n [k_local, kg_local] = pycufsm.analysis.trans(\n alpha=alpha, k_local=k_l, kg_local=kg_l, m_a=m_a\n )\n\n # Add element contribution of k_local to full matrix k_global\n # and kg_local to kg_global\n [k_global, kg_global] = pycufsm.analysis.assemble(\n k_global=k_global,\n kg_global=kg_global,\n k_local=k_local,\n kg_local=kg_local,\n node_i=node_i,\n node_j=node_j,\n n_nodes=n_nodes,\n m_a=m_a\n )\n\n # orthogonalization/normalization begins\n if gbt_con['orth'] == 2 or gbt_con['orth'] == 3 \\\n or gbt_con['o_space'] == 2 or gbt_con['o_space'] == 3 or gbt_con['o_space'] == 4:\n # indices\n dof_index[0, 0] = 0\n dof_index[0, 1] = n_global_modes\n dof_index[1, 0] = n_global_modes\n dof_index[1, 1] = n_global_modes + n_dist_modes\n dof_index[2, 0] = n_global_modes + n_dist_modes\n dof_index[2, 1] = n_global_modes + n_dist_modes + n_local_modes\n dof_index[3, 0] = n_global_modes + n_dist_modes + n_local_modes\n dof_index[3, 1] = n_dof_m\n\n n_other_modes = n_dof_m - (n_global_modes + n_dist_modes + n_local_modes)\n\n b_v_gdl = np.zeros(((len(m_a) + 1)*(n_global_modes + n_dist_modes + n_local_modes), 1))\n b_v_g = np.zeros(((len(m_a) + 1)*n_global_modes, 1))\n b_v_d = np.zeros(((len(m_a) + 1)*n_dist_modes, 1))\n b_v_l = np.zeros(((len(m_a) + 1)*n_local_modes, 1))\n b_v_o = np.zeros(((len(m_a) + 1)*n_other_modes, 1))\n for i, m_i in enumerate(m_a):\n # considering length-dependency on base vectors\n b_v_m = b_v_l[:, n_dof_m*i:n_dof_m*(i + 1)] # n_dof_m*i:n_dof_m*(i+1)\n b_v_gdl[:, i * (n_global_modes + n_dist_modes + n_local_modes):(i + 1) *\n (n_global_modes+n_dist_modes+n_local_modes)] \\\n = b_v_m[:, dof_index[1, 1]:dof_index[3, 2]]\n b_v_g[:, i*n_global_modes:(i + 1)*n_global_modes] = b_v_m[:,\n dof_index[1,\n 1]:dof_index[1,\n 2]]\n b_v_d[:, i*n_dist_modes:(i + 1)*n_dist_modes] = b_v_m[:, dof_index[2,\n 1]:dof_index[2,\n 2]]\n b_v_l[:, i*n_local_modes:(i + 1)*n_local_modes] = b_v_m[:,\n dof_index[3,\n 1]:dof_index[3,\n 2]]\n b_v_o[:, i*n_other_modes:(i + 1)*n_other_modes] = b_v_m[:,\n dof_index[4,\n 1]:dof_index[4,\n 2]]\n #\n\n # define vectors for other modes, gbt_con['o_space'] = 3 only\n if gbt_con['o_space'] == 3:\n a_matrix = spla.null_space(b_v_gdl.conj().T)\n b_v_o = np.linalg.solve(k_global, a_matrix)\n for i, m_i in enumerate(m_a):\n b_v[:, i*n_dof_m+dof_index[3, 0]:i*n_dof_m+dof_index[3, 1]] \\\n = b_v_o[:, i*n_other_modes+1:(i+1)*n_other_modes]\n\n # define vectors for other modes, gbt_con['o_space'] = 4 only\n if gbt_con['o_space'] == 4:\n a_matrix = spla.null_space(b_v_gdl.conj().T)\n b_v_o = np.linalg.solve(kg_global, a_matrix)\n for i, m_i in enumerate(m_a):\n b_v[:, i*n_dof_m+dof_index[3, 0]:i*n_dof_m+dof_index[3, 1]] \\\n = b_v_o[:, i*n_other_modes+1:(i+1)*n_other_modes]\n\n # define vectors for other modes, gbt_con['o_space'] = 5 only\n if gbt_con['o_space'] == 5:\n a_matrix = spla.null_space(b_v_gdl.conj().T)\n for i, m_i in enumerate(m_a):\n b_v[:, i*n_dof_m+dof_index[3, 0]:i*n_dof_m+dof_index[3, 1]] \\\n = a_matrix[:, i*n_other_modes+1:(i+1)*n_other_modes]\n\n # orthogonalization + normalization for normals 2/3\n for i_sub, dof_sub in enumerate(dof_index):\n if dof_sub[2] >= dof_sub[1]:\n if i_sub == 1:\n k_global_sub = b_v_g.conj().T*k_global*b_v_g\n kg_global_sub = b_v_g.conj().T*kg_global*b_v_g\n elif i_sub == 2:\n k_global_sub = b_v_d.conj().T*k_global*b_v_d\n kg_global_sub = b_v_d.conj().T*kg_global*b_v_d\n elif i_sub == 3:\n k_global_sub = b_v_l.conj().T*k_global*b_v_l\n kg_global_sub = b_v_l.conj().T*kg_global*b_v_l\n elif i_sub == 4:\n k_global_sub = b_v_o.conj().T*k_global*b_v_o\n kg_global_sub = b_v_o.conj().T*kg_global*b_v_o\n\n [eigenvalues, eigenvectors] = spla.eig(a=k_global_sub, b=kg_global_sub)\n lf_sub = np.real(eigenvalues)\n indexsub = np.argsort(lf_sub)\n lf_sub = lf_sub[indexsub]\n eigenvectors = np.real(eigenvectors[:, indexsub])\n if gbt_con['norm'] == 2 or gbt_con['norm'] == 3:\n if gbt_con['norm'] == 2:\n s_matrix = eigenvectors.conj().T @ k_global_sub @ eigenvectors\n if gbt_con['norm'] == 3:\n s_matrix = eigenvectors.conj().T @ kg_global_sub @ eigenvectors\n s_matrix = np.diag(s_matrix)\n for i in range(0, (dof_sub[1] - dof_sub[0])*total_m):\n eigenvectors[:, i] = np.transpose(\n np.conj(\n np.linalg.lstsq(\n eigenvectors[:, i].conj().T,\n np.sqrt(s_matrix).conj().T\n )\n )\n )\n\n if i_sub == 1:\n b_v_orth = b_v_g @ eigenvectors\n elif i_sub == 2:\n b_v_orth = b_v_d @ eigenvectors\n elif i_sub == 3:\n b_v_orth = b_v_l @ eigenvectors\n elif i_sub == 4:\n b_v_orth = b_v_o @ eigenvectors\n\n for i, m_i in enumerate(m_a):\n if i_sub == 1:\n b_v[:, i*n_dof_m+dof_sub[1]:i*n_dof_m+dof_sub[2]] \\\n = b_v_orth[:, i*n_global_modes+1:(i+1)*n_global_modes]\n elif i_sub == 2:\n b_v[:, i*n_dof_m+dof_sub[1]:i*n_dof_m+dof_sub[2]] \\\n = b_v_orth[:, i*n_dist_modes+1:(i+1)*n_dist_modes]\n elif i_sub == 3:\n b_v[:, i*n_dof_m+dof_sub[1]:i*n_dof_m+dof_sub[2]] \\\n = b_v_orth[:, i*n_local_modes+1:(i+1)*n_local_modes]\n elif i_sub == 4:\n b_v[:, i*n_dof_m+dof_sub[1]:i*n_dof_m+dof_sub[2]] \\\n = b_v_orth[:, i*n_other_modes+1:(i+1)*n_other_modes]\n\n # normalization for gbt_con['o_space'] = 1\n if (gbt_con['norm'] == 2 or gbt_con['norm'] == 3) and (gbt_con['o_space'] == 1):\n for i in range(0, n_dof_m*total_m):\n if gbt_con['norm'] == 2:\n b_v[:, i] = np.transpose(\n np.conj(\n np.linalg.lstsq(\n b_v[:, i].conj().T,\n np.sqrt(b_v[:, i].conj().T @ k_global @ b_v[:, i]).conj().T\n )\n )\n )\n\n if gbt_con['norm'] == 3:\n b_v[:, i] = np.transpose(\n np.conj(\n np.linalg.lstsq(\n b_v[:, i].conj().T,\n np.sqrt(b_v[:, i].conj().T @ kg_global @ b_v[:, i]).conj().T\n )\n )\n )\n\n # normalization for gbt_con['norm'] 1\n if gbt_con['norm'] == 1:\n for i in range(0, n_dof_m*total_m):\n b_v[:, i] = np.transpose(\n np.conj(\n np.linalg.lstsq(\n b_v[:, i].conj().T,\n np.sqrt(b_v[:, i].conj().T @ b_v[:, i]).conj().T\n )\n )\n )\n # b_v[n_dof_m*i:n_dof_m*(i+1),n_dof_m*i:n_dof_m*(i+1)] = b_v_m\n return b_v\n\n\ndef mode_select(b_v, n_global_modes, n_dist_modes, n_local_modes, gbt_con, n_dof_m, m_a):\n # this routine selects the required base vectors\n # b_v_red forms a reduced space for the calculation, including the\n # selected modes only\n # b_v_red itself is the final constraint matrix for the selected modes\n #\n #\n # input data\n # b_v - base vectors (each column corresponds to a certain mode)\n # columns 1..n_global_modes: global modes\n # columns (n_global_modes+1)..(n_global_modes+n_dist_modes): dist. modes\n # columns (n_global_modes+n_dist_modes+1)\n # ..(n_global_modes+n_dist_modes+n_local_modes): local modes\n # columns (n_global_modes+n_dist_modes+n_local_modes+1)..n_dof: other modes\n # n_global_modes, n_dist_modes, n_local_modes - number of global, distortional\n # and local buckling modes, respectively\n # gbt_con['glob'] - indicator which global modes are selected\n # gbt_con['dist'] - indicator which dist. modes are selected\n # gbt_con['local'] - indicator whether local modes are selected\n # gbt_con['other'] - indicator whether other modes are selected\n # n_dof_m: 4*n_nodes, total DOF for a singal longitudinal term\n\n # output data\n # b_v_red - reduced base vectors (each column corresponds to a certain mode)\n\n #\n # note:\n # for all if_* indicator: 1 if selected, 0 if eliminated\n #\n #\n # S. Adany, Mar 22, 2004\n # BWS May 2004\n # modifed on Jul 10, 2009 by Z. Li for general b_c\n # Z. Li, June 2010\n\n n_m = int(\n sum(gbt_con['glob']) + sum(gbt_con['dist']) + sum(gbt_con['local']) + sum(gbt_con['other'])\n )\n b_v_red = np.zeros((len(b_v), (len(m_a) + 1)*n_m))\n for i in range(0, len(m_a)):\n # b_v_m = b_v[n_dof_m*i:n_dof_m*(i+1),n_dof_m*i:n_dof_m*(i+1)]\n n_other_modes = n_dof_m - n_global_modes - n_dist_modes - n_local_modes # nr of other modes\n #\n nmo = 0\n b_v_red_m = np.zeros((len(b_v), n_m))\n for j in range(0, n_global_modes):\n if gbt_con['glob'][j] == 1:\n b_v_red_m[:, nmo] = b_v[:, n_dof_m*i + j]\n nmo = nmo + 1\n\n for j in range(0, n_dist_modes):\n if gbt_con['dist'][j] == 1:\n b_v_red_m[:, nmo] = b_v[:, n_dof_m*i + n_global_modes + j]\n nmo = nmo + 1\n\n # if gbt_con['local'] == 1\n # b_v_red[:,(nmo+1):(nmo+n_local_modes)]\n # = b_v[:,(n_global_modes+n_dist_modes+1):(n_global_modes+\n # n_dist_modes+n_local_modes)]\n # nmo = nmo+n_local_modes\n # end\n for j in range(0, n_local_modes):\n if gbt_con['local'][j] == 1:\n b_v_red_m[:, nmo] = b_v[:, n_dof_m*i + n_global_modes + n_dist_modes + j]\n nmo = nmo + 1\n\n for j in range(0, n_other_modes):\n if gbt_con['other'][j] == 1:\n b_v_red_m[:,\n nmo] = b_v[:,\n n_dof_m*i + n_global_modes + n_dist_modes + n_local_modes + j]\n nmo = nmo + 1\n\n # if gbt_con['other'] == 1\n # n_other_modes = len(b_v[:, 1])-n_global_modes - n_dist_modes - n_local_modes\n # # nr of other modes\n # b_v_red[:,(nmo+1):(nmo+n_other_modes)]\n # = b_v[:,(n_global_modes+n_dist_modes+n_local_modes+1):(n_global_modes+\n # n_dist_modes+n_local_modes+n_other_modes)]\n # # b_v_red[:,(nmo+1)] = b_v[:,(n_global_modes+n_dist_modes+n_local_modes+1)]\n # end\n b_v_red[:, nmo*i:nmo*(i + 1)] = b_v_red_m\n\n return b_v_red\n\n\ndef constr_user(nodes, constraints, m_a):\n #\n # this routine creates the constraints matrix, r_user_matrix, as defined by the user\n #\n #\n # input/output data\n # nodes - same as elsewhere throughout this program\n # constraints - same as 'constraints' throughout this program\n # m_a - longitudinal terms to be included for this length\n\n # r_user_matrix - the constraints matrix (in other words: base vectors) so that\n # displ_orig = r_user_matrix * displ_new\n\n # S. Adany, Feb 26, 2004\n # Z. Li, Aug 18, 2009 for general b.c.\n # Z. Li, June 2010\n\n n_nodes = len(nodes[:, 1])\n n_dof_m = 4*n_nodes\n dof_reg = np.ones((n_dof_m, 1))\n r_user_matrix = np.eye(n_dof_m*len(m_a))\n for i in range(0, len(m_a)):\n #\n r_user_m_matrix = np.eye(n_dof_m)\n # to consider free DOFs\n for j in range(0, n_nodes):\n for k in range(3, 7):\n if nodes[j, k] == 0:\n if k == 3:\n dof_e = j*2 + 1 - 1\n elif k == 5:\n dof_e = (j + 1)*2 - 1\n elif k == 4:\n dof_e = n_nodes*2 + j*2 + 1 - 1\n elif k == 6:\n dof_e = n_nodes*2 + (j + 1)*2 - 1\n\n dof_reg[dof_e, 0] = 0\n\n # to consider master-slave constraints\n for j in range(0, len(constraints)):\n if len(constraints[j, :]) >= 5:\n # nr of eliminated DOF\n node_e = constraints[j, 0]\n if constraints[j, 1] == 0:\n dof_e = node_e*2 + 1 - 1\n elif constraints[j, 1] == 2:\n dof_e = (node_e + 1)*2 - 1\n elif constraints[j, 1] == 1:\n dof_e = n_nodes*2 + node_e*2 + 1 - 1\n elif constraints[j, 1] == 3:\n dof_e = n_nodes*2 + (node_e + 1)*2 - 1\n\n # nr of kept DOF\n node_k = constraints[j, 3]\n if constraints[j, 4] == 0:\n dof_k = node_k*2 + 1 - 1\n elif constraints[j, 4] == 2:\n dof_k = (node_k + 1)*2 - 1\n elif constraints[j, 4] == 1:\n dof_k = n_nodes*2 + node_k*2 + 1 - 1\n elif constraints[j, 4] == 3:\n dof_k = n_nodes*2 + (node_k + 1)*2 - 1\n\n # to modify r_user_matrix\n r_user_m_matrix[:, dof_k] = r_user_m_matrix[:, dof_k] \\\n + constraints[j, 2]*r_user_m_matrix[:, dof_e]\n dof_reg[dof_e, 0] = 0\n\n # to eliminate columns from r_user_matrix\n k = -1\n r_u_matrix = np.zeros_like(r_user_m_matrix)\n for j in range(0, n_dof_m):\n if dof_reg[j, 0] == 1:\n k = k + 1\n r_u_matrix[:, k] = r_user_m_matrix[:, j]\n\n r_user_m_matrix = r_u_matrix[:, 0:k]\n r_user_matrix[i*n_dof_m:(i + 1)*n_dof_m, i*k:(i + 1)*k] = r_user_m_matrix\n\n return r_user_matrix\n\n\ndef mode_constr(nodes, elements, node_props, main_nodes, meta_elements):\n #\n # this routine creates the constraint matrices necessary for mode\n # separation/classification for each specified half-wave number m_i\n #\n # assumptions\n # GBT-like assumptions are used\n # the cross-section must not be closed and must not contain closed parts\n #\n # must check whether 'Warp' works well for any open section !!!\n #\n #\n # input/output data\n # nodes, elements, props - same as elsewhere throughout this program\n # main_nodes [main nodes] - array of\n # [nr, x, z, orig nodes nr, nr of adj meta-elements, m_i-el_i-1, m_i-el_i-2, ...]\n # meta_elements [meta-elements] - array of\n # [nr, main-nodes-1, main-nodes-2, nr of sub-nodes, sub-no-1, sub-nod-2, ...]\n # node_props - array of [original nodes nr, new nodes nr, nr of adj elements, nodes type]\n #\n #\n # notes:\n # m-el_i-? is positive if the starting nodes of m-el_i-? coincides with\n # the given m-nodes, otherwise negative\n # nodes types: 1-corner, 2-edge, 3-sub\n # sub-nodes numbers are the original one, of course\n #\n # S. Adany, Mar 10, 2004\n # Z. Li, Jul 10, 2009\n\n # to create r_x and r_z constraint matrices\n [r_x, r_z] = constr_xz_y(main_nodes, meta_elements)\n #\n # to create r_ys constraint matrix for the y DOFs of sub-nodes\n r_ys = constr_ys_ym(nodes, main_nodes, meta_elements, node_props)\n #\n # to create r_yd for y DOFs of main nodes for distortional buckling\n r_yd = constr_yd_yg(nodes, elements, node_props, r_ys, len(main_nodes))\n #\n # to create r_ud for y DOFs of indefinite main nodes\n r_ud = constr_yu_yd(main_nodes, meta_elements)\n\n return r_x, r_z, r_yd, r_ys, r_ud\n\n\ndef y_dofs(\n nodes, elements, main_nodes, n_main_nodes, n_dist_modes, r_yd, r_ud, sect_props, el_props\n):\n\n # this routine creates y-DOFs of main nodes for global buckling and\n # distortional buckling, however:\n # only involves single half-wave number m_i\n #\n # assumptions\n # GBT-like assumptions are used\n # the cross-section must not be closed and must not contain closed parts\n\n # input data\n # nodes, elements - same as elsewhere throughout this program\n # main_nodes [main nodes] - nodes of 'meta' cross-section\n # n_main_nodes, n_corner_nodes, n_sub_nodes\n # - number of main nodes, corner nodes and sub-nodes, respectively\n # n_dist_modes, n_local_modes - number of distortional and local buckling modes, respectively\n # r_yd, r_ud - constraint matrices\n #\n # output data\n # d_y - y-DOFs of main nodes for global buckling and distortional buckling\n # (each column corresponds to a certain mode)\n #\n #\n # S. Adany, Mar 10, 2004, modified Aug 29, 2006\n # Z. Li, Dec 22, 2009\n\n w_o = np.zeros((len(nodes), 2))\n w_o[int(elements[0, 1]), 0] = int(elements[0, 1])\n w_no = 0\n\n # compute the unit warping\n # code from cutwp_prop2:232-249\n for _ in range(0, len(elements)):\n i = 0\n while (np.any(w_o[:, 0] == elements[i, 1]) and np.any(w_o[:, 0] == elements[i, 2])) \\\n or (not np.any(w_o[:, 0] == elements[i, 1]) \\\n and not np.any(w_o[:, 0] == elements[i, 2])):\n i = i + 1\n s_n = int(elements[i, 1])\n f_n = int(elements[i, 2])\n p_o = ((nodes[s_n, 1] - sect_props['x0']) \\\n * (nodes[f_n, 2] - sect_props['y0']) \\\n - (nodes[f_n, 1] - sect_props['x0']) \\\n * (nodes[s_n, 2] - sect_props['y0'])) \\\n / el_props[i, 1]\n if w_o[s_n, 0] == 0:\n w_o[s_n, 0] = s_n\n w_o[s_n, 1] = w_o[f_n, 1] - p_o*el_props[i, 1]\n elif w_o[int(elements[i, 2]), 1] == 0:\n w_o[f_n, 0] = f_n\n w_o[f_n, 1] = w_o[s_n, 1] + p_o*el_props[i, 1]\n w_no = w_no + 1 / (2*sect_props['A']) * (w_o[s_n, 1] + w_o[f_n, 1]) \\\n * elements[i, 3] * el_props[i, 1]\n w_n = w_no - w_o[:, 1]\n # coord. transform. to the principal axes\n phi = sect_props['phi']\n rot = np.array([\n [np.cos(phi), -np.sin(phi)],\n [np.sin(phi), np.cos(phi)],\n ])\n centre_of_gravity = [\n sect_props['cx'],\n sect_props['cy'],\n ] @ rot\n\n # CALCULATION FOR GLOBAL AND DISTORTIONAL BUCKLING MODES\n #\n # to create y-DOFs of main nodes for global buckling\n d_y = np.zeros((n_main_nodes, 4))\n for i, m_node in enumerate(main_nodes):\n xz_i = [m_node[1], m_node[2]] @ rot\n d_y[i, 0] = 1\n d_y[i, 1] = xz_i[1] - centre_of_gravity[1]\n d_y[i, 2] = xz_i[0] - centre_of_gravity[0]\n d_y[i, 3] = w_n[int(m_node[3])]\n\n # for i = 1:4\n # d_y[:, i] = d_y[:, i]/norm(d_y[:, i])\n # end\n # to count the nr of existing global modes\n n_global_modes = 4\n ind = np.ones(4)\n for i in range(0, 4):\n if np.nonzero(d_y[:, i]) == []:\n ind[i] = 0\n n_global_modes = n_global_modes - 1\n\n # to eliminate zero columns from d_y\n sdy = d_y\n d_y = np.zeros((len(sdy), int(sum(ind))))\n k = 0\n for i in range(0, 4):\n if ind[i] == 1:\n d_y[:, k] = sdy[:, i]\n k = k + 1\n\n # to create y-DOFs of main nodes for distortional buckling\n if n_dist_modes > 0:\n d_y = np.concatenate((d_y, np.zeros((len(d_y), n_dist_modes))), axis=1)\n # junk = spla.null_space((r_yd*d_y(:, 1:(n_global_modes+1))).conj().T)\n # junk3 = junk.conj().T*r_yd*junk\n r_chol = np.linalg.cholesky(r_yd).T\n junk = spla.null_space((r_chol @ d_y[:, 0:n_global_modes]).conj().T)\n junk2 = np.linalg.solve(r_chol, junk)\n\n j_junk1 = spla.null_space(junk2.conj().T)\n j_junk2 = spla.null_space(r_ud.conj().T)\n nj1 = len(j_junk1[0])\n nj2 = len(j_junk2[0])\n j_junk3 = j_junk1\n j_junk3[:, nj1:nj1 + nj2] = j_junk2\n j_junk4 = spla.null_space(j_junk3.conj().T)\n\n # d_y(:,(n_global_modes+2):(n_global_modes+1+n_dist_modes)) = j_junk4\n junk3 = j_junk4.conj().T @ r_yd @ j_junk4\n # junk3 = junk2.conj().T*junk2\n #\n [_, eigenvectors] = spla.eig(junk3)\n # eigenvalues = diag(eigenvalues)\n # [eigenvalues, index] = sort(eigenvalues)\n # eigenvectors = eigenvectors[:, index]\n d_y[:, n_global_modes:n_global_modes + n_dist_modes] = j_junk4 @ eigenvectors\n\n return d_y, n_global_modes\n\n\ndef base_vectors(\n d_y, elements, el_props, length, m_i, node_props, n_main_nodes, n_corner_nodes, n_sub_nodes,\n n_global_modes, n_dist_modes, n_local_modes, r_x, r_z, r_p, r_ys, dof_perm\n):\n #\n # this routine creates the base vectors for global, dist., local and other modes\n #\n # assumptions\n # GBT-like assumptions are used\n # the cross-section must not be closed and must not contain closed parts\n #\n # must check whether 'Warp' works well for any open section !!!\n #\n #\n # input data\n # elements, el_props - same as elsewhere throughout this program\n # length, m_i - member length and number of half-waves, respectively\n # main_nodes [main nodes] - nodes of 'meta' cross-section\n # meta_elements [meta-elements] - elements of 'meta' cross-section\n # node_props - some properties of the nodes\n # n_main_nodes, n_corner_nodes, n_sub_nodes\n # - number of main nodes, corner nodes and sub-nodes, respectively\n # n_dist_modes, n_local_modes - number of distortional and local buckling modes, respectively\n # r_x, r_z, r_p, r_ys, - constraint matrices\n # dof_perm - permutation matrix to re-order the DOFs\n #\n # output data\n # n_other_modes - nr of other modes\n # b_v_m - base vectors for single half-wave number m_i\n # (each column corresponds to a certain mode)\n # columns 1..n_global_modes: global modes\n # columns (n_global_modes+1)..(n_global_modes+n_dist_modes): dist. modes\n # columns (n_global_modes+n_dist_modes+1)\n # ..(n_global_modes+n_dist_modes+n_local_modes): local modes\n # columns (n_global_modes+n_dist_modes+n_local_modes+1)..n_dof: other modes\n #\n # note:\n # more details on the input variables can be found in the routines called\n # in this routine\n #\n\n # S. Adany, Mar 10, 2004, modified Aug 29, 2006\n # Z. Li, Dec 22, 2009\n\n # DATA PREPARATION\n k_m = m_i*np.pi/length\n n_node_props = len(node_props)\n n_dof = 4*n_node_props # nro of DOFs\n n_edge_nodes = n_main_nodes - n_corner_nodes\n # zero out\n b_v_m = np.zeros((n_dof, n_dof))\n\n # CALCULATION FOR GLOBAL AND DISTORTIONAL BUCKLING MODES\n # to add global and dist y DOFs to base vectors\n b_v_m = d_y[:, 0:n_global_modes + n_dist_modes]\n b_v_m = np.concatenate((b_v_m, np.zeros((n_dof - len(b_v_m), len(b_v_m[0])))), axis=0)\n #\n # to add x DOFs of corner nodes to the base vectors\n # r_x = r_x/k_m\n b_v_m[n_main_nodes:n_main_nodes + n_corner_nodes, 0:n_global_modes\n + n_dist_modes] = r_x @ b_v_m[0:n_main_nodes, 0:n_global_modes + n_dist_modes]\n #\n # to add z DOFs of corner nodes to the base vectors\n # r_z = r_z/k_m\n b_v_m[n_main_nodes + n_corner_nodes:n_main_nodes + 2*n_corner_nodes, 0:n_global_modes\n + n_dist_modes] = r_z @ b_v_m[0:n_main_nodes, 0:n_global_modes + n_dist_modes]\n #\n # to add other planar DOFs to the base vectors\n b_v_m[n_main_nodes + 2*n_corner_nodes:n_dof - n_sub_nodes, 0:n_global_modes\n + n_dist_modes] = r_p @ b_v_m[n_main_nodes:n_main_nodes + 2*n_corner_nodes,\n 0:n_global_modes + n_dist_modes]\n #\n # to add y DOFs of sub-nodes to the base vector\n b_v_m[n_dof - n_sub_nodes:n_dof, 0:n_global_modes\n + n_dist_modes] = r_ys @ b_v_m[0:n_main_nodes, 0:n_global_modes + n_dist_modes]\n #\n # division by k_m\n b_v_m[n_main_nodes:n_dof - n_sub_nodes,\n 0:n_global_modes + n_dist_modes] = b_v_m[n_main_nodes:n_dof - n_sub_nodes,\n 0:n_global_modes + n_dist_modes]/k_m\n #\n # norm base vectors\n for i in range(0, n_global_modes + n_dist_modes):\n b_v_m[:, i] = b_v_m[:, i]/np.linalg.norm(b_v_m[:, i])\n\n # CALCULATION FOR LOCAL BUCKLING MODES\n n_globdist_modes = n_global_modes + n_dist_modes # nr of global and dist. modes\n b_v_m = np.concatenate((b_v_m, np.zeros((len(b_v_m), n_local_modes))), axis=1)\n # np.zeros\n b_v_m[0:n_dof,\n n_globdist_modes:n_globdist_modes + n_local_modes] = np.zeros((n_dof, n_local_modes))\n\n # rot DOFs for main nodes\n b_v_m[3*n_main_nodes:4*n_main_nodes,\n n_globdist_modes:n_globdist_modes + n_main_nodes] = np.eye(n_main_nodes)\n #\n # rot DOFs for sub nodes\n if n_sub_nodes > 0:\n b_v_m[4*n_main_nodes + 2*n_sub_nodes:4*n_main_nodes + 3*n_sub_nodes, n_globdist_modes\n + n_main_nodes:n_globdist_modes + n_main_nodes + n_sub_nodes] = np.eye(n_sub_nodes)\n\n # x, z DOFs for edge nodes\n k = 0\n for i in range(0, n_node_props):\n if node_props[i, 3] == 2:\n el_i = np.nonzero(\n np.any(elements[:, 1] == i) or np.any(elements[:, 2] == i)\n ) # adjacent element\n alfa = el_props[el_i, 2]\n b_v_m[n_main_nodes + 2*n_corner_nodes + k,\n n_globdist_modes + n_main_nodes + n_sub_nodes + k] = -np.sin(alfa) # x\n b_v_m[n_main_nodes + 2*n_corner_nodes + n_edge_nodes + k,\n n_globdist_modes + n_main_nodes + n_sub_nodes + k] = np.cos(alfa) # z\n k = k + 1\n\n # x, z DOFs for sub-nodes\n if n_sub_nodes > 0:\n k = 0\n for i in range(0, n_node_props):\n if node_props[i, 3] == 3:\n el_i = np.nonzero(\n np.any(elements[:, 1] == i) or np.any(elements[:, 2] == i)\n ) # adjacent element\n alfa = el_props[el_i[0], 2]\n b_v_m[4*n_main_nodes + k, n_globdist_modes + n_main_nodes + n_sub_nodes\n + n_edge_nodes + k] = -np.sin(alfa) # x\n b_v_m[4*n_main_nodes + n_sub_nodes + k, n_globdist_modes + n_main_nodes\n + n_sub_nodes + n_edge_nodes + k] = np.cos(alfa) # z\n k = k + 1\n\n # CALCULATION FOR OTHER BUCKLING MODES\n #\n # # first among the \"others\": uniform y\n # b_v_m[1:n_main_nodes,(n_globdist_modes+n_local_modes+1)]\n # = np.zeros(n_main_nodes, 1)+np.sqrt(1 / (n_main_nodes+n_sub_nodes))\n # b_v_m[(n_dof-n_sub_nodes+1):n_dof,(n_globdist_modes+n_local_modes+1)]\n # = np.zeros(n_sub_nodes, 1)+np.sqrt(1 / (n_main_nodes+n_sub_nodes))\n #\n ## old way\n # n_other_modes = n_dof - n_globdist_modes - n_local_modes\n # n_elements = len(elements[:, 1])\n # b_v_m[1:n_dof,(n_globdist_modes+n_local_modes+1):(n_globdist_modes+\n # n_local_modes+2*n_elements)] = np.zeros(n_dof, 2*n_elements)\n # temp_elem = elements[:, 2:3]\n # for i = 1:n_elements\n # #\n # alfa = el_props[i, 3]\n # #\n # # find nodes on the one side of the current element\n # n_nod = 1\n # nods=[]\n # nods(1) = elements[i, 2]\n # temp_elem = elements[:, 2:3]\n # temp_elem[i, 1] = 0\n # temp_elem[i, 2] = 0\n # new = 1\n # while new>0\n # new = 0\n # for j = 1:n_elements\n # for k_local = 1:len(nods)\n # if (nods(k_local) == temp_elem[j, 1])\n # n_nod = n_nod+1\n # new = new+1\n # nods(n_nod) = temp_elem[j, 2]\n # temp_elem[j, 1] = 0\n # temp_elem[j, 2] = 0\n #\n # if (nods(k_local) == temp_elem[j, 2])\n # n_nod = n_nod+1\n # new = new+1\n # nods(n_nod) = temp_elem[j, 1]\n # temp_elem[j, 1] = 0\n # temp_elem[j, 2] = 0\n #\n # #\n # # create the base-vectors for membrane SHEAR modes\n # s = np.sqrt(1/n_nod)\n # for j = 1:n_nod\n # old_dof_y = 2 * (nods[j])\n # b_v_m[old_dof_y,(n_globdist_modes+n_local_modes+i)] = s\n #\n # # create the base-vectors for membrane TRANSVERSE modes\n # for j = 1:n_nod\n # old_dof_x = 2 * (nods[j])-1\n # old_dof_z = 2*n_node_props+2 * (nods[j])-1\n # b_v_m[old_dof_x,(n_globdist_modes+n_local_modes+n_elements+i)] = s*np.cos(alfa)\n # b_v_m[old_dof_z,(n_globdist_modes+n_local_modes+n_elements+i)] = s*np.sin(alfa)\n #\n #\n # end\n ## new way\n n_elements = len(elements)\n b_v_m = np.concatenate((b_v_m, np.zeros((len(b_v_m), 2*n_elements))), axis=1)\n for i, elem in enumerate(elements):\n alfa = el_props[i, 2]\n\n # find nodes on the one side of the current element\n n_nod1 = int(elem[1])\n n_nod2 = int(elem[2])\n\n # create the base-vectors for membrane SHEAR modes\n b_v_m[(n_nod1 - 1)*2, n_globdist_modes + n_local_modes + i] = 0.5\n b_v_m[(n_nod2 - 1)*2, n_globdist_modes + n_local_modes + i] = -0.5\n\n # create the base-vectors for membrane TRANSVERSE modes\n b_v_m[(n_nod1 - 1)*2, n_globdist_modes + n_local_modes + n_elements + i] = -0.5*np.cos(alfa)\n b_v_m[(n_nod2 - 1)*2, n_globdist_modes + n_local_modes + n_elements + i] = 0.5*np.cos(alfa)\n b_v_m[2*n_node_props + (n_nod1 - 1)*2,\n n_globdist_modes + n_local_modes + n_elements + i] = 0.5*np.sin(alfa)\n b_v_m[2*n_node_props + (n_nod2 - 1)*2,\n n_globdist_modes + n_local_modes + n_elements + i] = -0.5*np.sin(alfa)\n\n # RE_ORDERING DOFS\n b_v_m[:, 0:n_globdist_modes\n + n_local_modes] = dof_perm @ b_v_m[:, 0:n_globdist_modes + n_local_modes]\n\n return b_v_m\n\n\ndef constr_xz_y(main_nodes, meta_elements):\n # this routine creates the constraint matrix, Rxz, that defines relationship\n # between x, z displacements DOFs [for internal main nodes, referred also as corner nodes]\n # and the longitudinal y displacements DOFs [for all the main nodes]\n # if GBT-like assumptions are used\n #\n # to make this routine length-independent, Rxz is not multiplied here by\n # (1/k_m), thus it has to be multiplied outside of this routine!\n #\n # additional assumption: cross section is opened!\n #\n #\n # input/output data\n # main_nodes [main nodes] - array of\n # [nr, x, z, orig nodes nr, nr of adj meta-elements, m-el_i-1, m-el_i-2, ...]\n # meta_elements [meta-elements] - array of\n # [nr, main-nodes-1, main-nodes-2, nr of sub-nodes, sub-no-1, sub-nod-2, ...]\n #\n # note:\n # m-el_i-? is positive if the starting nodes of m-el_i-? coincides with\n # the given m-nodes, otherwise negative\n #\n # S. Adany, Feb 05, 2004\n #\n #\n # to calculate some data of main elements (stored in meta_elements_data)\n meta_elements_data = np.zeros((len(meta_elements), 5))\n for i, m_elem in enumerate(meta_elements):\n node1 = int(m_elem[1])\n node2 = int(m_elem[2])\n x_1 = main_nodes[node1, 1]\n x_2 = main_nodes[node2, 1]\n z_1 = main_nodes[node1, 2]\n z_2 = main_nodes[node2, 2]\n b_i = np.sqrt((x_2 - x_1)**2 + (z_2 - z_1)**2)\n a_i = np.arctan2(z_2 - z_1, x_2 - x_1)\n s_i = (z_2 - z_1)/b_i\n c_i = (x_2 - x_1)/b_i\n meta_elements_data[i, 0] = b_i # elements width, b_strip\n meta_elements_data[i, 1] = 1/meta_elements_data[i, 0] # 1/b_strip\n meta_elements_data[i, 2] = a_i # elements inclination\n meta_elements_data[i, 3] = s_i # np.sin\n meta_elements_data[i, 4] = c_i # np.cos\n # meta_elements_data[i, 5] = s_i/b_i # np.sin/b_strip\n # meta_elements_data[i, 6] = c_i/b_i # np.cos/b_strip\n\n # to count the number of corner nodes, and of main nodes\n n_main_nodes = len(main_nodes[:, 0])\n n_corner_nodes = 0\n for m_node in main_nodes:\n if m_node[4] > 1:\n n_corner_nodes = n_corner_nodes + 1\n\n r_x = np.zeros((n_corner_nodes, n_main_nodes))\n r_z = np.zeros((n_corner_nodes, n_main_nodes))\n k = 0\n for i, m_node in enumerate(main_nodes):\n if m_node[4] > 1:\n # to select two non-parallel meta-elements (elem1, elem2)\n elem1 = int(m_node[5])\n elem1_flag = int(round((m_node[5] - elem1)*10))\n j = 6\n while np.sin(meta_elements_data[int(np.real(m_node[j])), 2]\n - meta_elements_data[elem1, 2]) == 0:\n j = j + 1\n\n elem2 = int(m_node[j])\n elem2_flag = int(round((m_node[j] - elem2)*10))\n\n # to define main-nodes that play (order: main_nodes1, main_nodes2, main_nodes3)\n main_nodes2 = int(i)\n main_nodes1 = int(meta_elements[elem1, elem1_flag])\n main_nodes3 = int(meta_elements[elem2, elem2_flag])\n\n # to calculate elements of Rxz matrix\n r_1 = meta_elements_data[elem1, 1]\n alfa1 = meta_elements_data[elem1, 2]\n sin1 = meta_elements_data[elem1, 3]\n cos1 = meta_elements_data[elem1, 4]\n if elem1_flag == 2:\n alfa1 = alfa1 - np.pi\n sin1 = -sin1\n cos1 = -cos1\n\n r_2 = meta_elements_data[elem2, 1]\n alfa2 = meta_elements_data[elem2, 2]\n sin2 = meta_elements_data[elem2, 3]\n cos2 = meta_elements_data[elem2, 4]\n if elem2 == 1:\n alfa2 = alfa2 - np.pi\n sin2 = -sin2\n cos2 = -cos2\n\n det = np.sin(alfa2 - alfa1)\n\n # to form Rxz matrix\n r_x[k, main_nodes1] = sin2*r_1/det\n r_x[k, main_nodes2] = (-sin1*r_2 - sin2*r_1)/det\n r_x[k, main_nodes3] = sin1*r_2/det\n\n r_z[k, main_nodes1] = -cos2*r_1/det\n r_z[k, main_nodes2] = (cos1*r_2 + cos2*r_1)/det\n r_z[k, main_nodes3] = -cos1*r_2/det\n\n k = k + 1\n\n return r_x, r_z\n\n\ndef constr_planar_xz(nodes, elements, props, node_props, dof_perm, m_i, length, b_c, el_props):\n #\n # this routine creates the constraint matrix, r_p, that defines relationship\n # between x, z DOFs of any non-corner nodes + teta DOFs of all nodes,\n # and the x, z displacements DOFs of corner nodes\n # if GBT-like assumptions are used\n #\n #\n # input/output data\n # nodes, elements, props - same as elsewhere throughout this program\n # node_props - array of [original nodes nr, new nodes nr, nr of adj elements, nodes type]\n # dof_perm - permutation matrix, so that\n # (orig-displacements-vect) = (dof_perm) � (new-displacements - vector)\n #\n # S. Adany, Feb 06, 2004\n # Z. Li, Jul 10, 2009\n #\n # to count corner-, edge- and sub-nodes\n n_node_props = len(node_props)\n n_corner_nodes = 0\n n_edge_nodes = 0\n n_sub_nodes = 0\n for n_prop in node_props:\n if n_prop[3] == 1:\n n_corner_nodes = n_corner_nodes + 1\n\n if n_prop[3] == 2:\n n_edge_nodes = n_edge_nodes + 1\n\n if n_prop[3] == 3:\n n_sub_nodes = n_sub_nodes + 1\n\n n_main_nodes = n_corner_nodes + n_edge_nodes # nr of main nodes\n\n n_dof = 4*n_node_props # nro of DOFs\n\n # to create the full global stiffness matrix (for transverse bending)\n k_global = kglobal_transv(nodes, elements, props, m_i, length, b_c, el_props)\n\n # to re-order the DOFs\n k_global = dof_perm.conj().T @ k_global @ dof_perm\n\n # to have partitions of k_global\n k_global_pp = k_global[n_main_nodes + 2*n_corner_nodes:n_dof - n_sub_nodes,\n n_main_nodes + 2*n_corner_nodes:n_dof - n_sub_nodes]\n k_global_pc = k_global[n_main_nodes + 2*n_corner_nodes:n_dof - n_sub_nodes,\n n_main_nodes:n_main_nodes + 2*n_corner_nodes]\n\n # to form the constraint matrix\n #[r_p]=-inv(k_global_pp) * k_global_pc\n\n r_p = -np.linalg.solve(k_global_pp, k_global_pc)\n\n return r_p\n\n\ndef constr_yd_yg(nodes, elements, node_props, r_ys, n_main_nodes):\n #\n # this routine creates the constraint matrix, r_yd, that defines relationship\n # between base vectors for distortional buckling,\n # and base vectors for global buckling,\n # but for y DOFs of main nodes only\n #\n #\n # input/output data\n # nodes, elements - same as elsewhere throughout this program\n # node_props - array of [original nodes nr, new nodes nr, nr of adj elements, nodes type]\n # r_ys - constrain matrix, see function 'constr_ys_ym'\n # n_main_nodes - nr of main nodes\n #\n # S. Adany, Mar 04, 2004\n #\n n_nodes = len(nodes)\n a_matrix = np.zeros((n_nodes, n_nodes))\n for elem in elements:\n node1 = int(elem[1])\n node2 = int(elem[2])\n d_x = nodes[node2, 1] - nodes[node1, 1]\n d_z = nodes[node2, 2] - nodes[node1, 2]\n d_area = np.sqrt(d_x*d_x + d_z*d_z)*elem[3]\n ind = np.nonzero(node_props[:, 0] == node1)\n node1 = int(node_props[ind, 1])\n ind = np.nonzero(node_props[:, 0] == node2)\n node2 = int(node_props[ind, 1])\n a_matrix[node1, node1] = a_matrix[node1, node1] + 2*d_area\n a_matrix[node2, node2] = a_matrix[node2, node2] + 2*d_area\n a_matrix[node1, node2] = a_matrix[node1, node2] + d_area\n a_matrix[node2, node1] = a_matrix[node2, node1] + d_area\n\n r_ysm = np.zeros((n_nodes, n_main_nodes))\n r_ysm[0:n_main_nodes, 0:n_main_nodes] = np.eye(n_main_nodes)\n r_ysm[n_main_nodes:n_nodes, 0:n_main_nodes] = r_ys\n r_yd = r_ysm.conj().T @ a_matrix @ r_ysm\n\n return r_yd\n\n\ndef constr_ys_ym(nodes, main_nodes, meta_elements, node_props):\n # this routine creates the constraint matrix, r_ys, that defines relationship\n # between y DOFs of sub-nodes,\n # and the y displacements DOFs of main nodes\n # by linear interpolation\n #\n #\n # input/output data\n # nodes - same as elsewhere throughout this program\n # main_nodes [main nodes] - array of\n # [nr, x, z, orig nodes nr, nr of adj meta-elements, m-el_i-1, m-el_i-2, ...]\n # meta_elements [meta-elements] - array of\n # [nr, main-nodes-1, main-nodes-2, nr of sub-nodes, sub-no-1, sub-nod-2, ...]\n # node_props - array of [original nodes nr, new nodes nr, nr of adj elements, nodes type]\n #\n # S. Adany, Feb 06, 2004\n #\n n_sub_nodes = 0\n for n_prop in node_props:\n if n_prop[3] == 3:\n n_sub_nodes = n_sub_nodes + 1\n\n n_main_nodes = len(main_nodes)\n\n r_ys = np.zeros((n_sub_nodes, n_main_nodes))\n\n for m_elem in meta_elements:\n if m_elem[3] > 0:\n nod1 = int(main_nodes[int(m_elem[1]), 3])\n nod3 = int(main_nodes[int(m_elem[2]), 3])\n x_1 = nodes[nod1, 1]\n x_3 = nodes[nod3, 1]\n z_1 = nodes[nod1, 2]\n z_3 = nodes[nod3, 2]\n b_m = np.sqrt((x_3 - x_1)**2 + (z_3 - z_1)**2)\n n_new1 = int(node_props[nod1, 1])\n n_new3 = int(node_props[nod3, 1])\n for j in range(0, int(m_elem[3])):\n nod2 = int(m_elem[j + 4])\n x_2 = nodes[nod2, 1]\n z_2 = nodes[nod2, 2]\n b_s = np.sqrt((x_2 - x_1)**2 + (z_2 - z_1)**2)\n n_new2 = int(node_props[nod2, 1])\n r_ys[n_new2 - n_main_nodes, n_new1] = (b_m - b_s)/b_m\n r_ys[n_new2 - n_main_nodes, n_new3] = b_s/b_m\n\n return r_ys\n\n\ndef constr_yu_yd(main_nodes, meta_elements):\n #\n # this routine creates the constraint matrix, r_ud, that defines relationship\n # between y displacements DOFs of indefinite main nodes\n # and the y displacements DOFs of definite main nodes\n # (definite main nodes = those main nodes which unambiguously define the y displacements pattern\n # indefinite main nodes = those nodes the y DOF of which can be calculated\n # from the y DOF of definite main nodes\n # note: for open sections with one single branch only there are no indefinite nodes)\n #\n # important assumption: cross section is opened!\n #\n #\n # input/output data\n # main_nodes [main nodes] - array of\n # [nr, x, z, orig nodes nr, nr of adj meta-elements, m-el_i-1, m-el_i-2, ...]\n # meta_elements [meta-elements] - array of\n # [nr, main-nodes-1, main-nodes-2, nr of sub-nodes, sub-no-1, sub-nod-2, ...]\n #\n # note:\n # m-el_i-? is positive if the starting nodes of m-el_i-? coincides with\n # the given m-nodes, otherwise negative\n #\n # S. Adany, Mar 10, 2004\n #\n #\n # to calculate some data of main elements (stored in meta_elements_data)\n meta_elements_data = np.zeros((len(meta_elements), 5))\n for i, m_elem in enumerate(meta_elements):\n node1 = int(m_elem[1])\n node2 = int(m_elem[2])\n x_1 = main_nodes[node1, 1]\n x_2 = main_nodes[node2, 1]\n z_1 = main_nodes[node1, 2]\n z_2 = main_nodes[node2, 2]\n b_i = np.sqrt((x_2 - x_1)**2 + (z_2 - z_1)**2)\n a_i = np.arctan2(z_2 - z_1, x_2 - x_1)\n s_i = (z_2 - z_1)/b_i\n c_i = (x_2 - x_1)/b_i\n meta_elements_data[i, 0] = b_i # elements width, b_strip\n meta_elements_data[i, 1] = 1/meta_elements_data[i, 0] # 1/b_strip\n meta_elements_data[i, 2] = a_i # elements inclination\n meta_elements_data[i, 3] = s_i # np.sin\n meta_elements_data[i, 4] = c_i # np.cos\n # meta_elements_data[i, 5] = s_i/b_i # np.sin/b_strip\n # meta_elements_data[i, 6] = c_i/b_i # np.cos/b_strip\n\n # to count the number of corner nodes, and of main nodes\n n_main_nodes = len(main_nodes)\n n_corner_nodes = 0\n for m_node in main_nodes:\n if m_node[4] > 1:\n n_corner_nodes = n_corner_nodes + 1\n\n # to register definite and indefinite nodes\n node_reg = np.ones((n_main_nodes, 1))\n for i, m_node in enumerate(main_nodes):\n if m_node[4] > 2:\n # to select two non-parallel meta-elements (elem1, elem2)\n elem1 = int(np.real(m_node[5]))\n j = 6\n while np.sin(meta_elements_data[int(np.real(m_node[j])), 2]\n - meta_elements_data[elem1, 2]) == 0:\n j = j + 1\n\n elem2 = int(np.real(m_node[j]))\n\n # to set far nodes of adjacent unselected elements to indefinite (node_reg == 0)\n for j in range(1, m_node[4]):\n elem3 = int(np.real(m_node[j + 5]))\n if elem3 != elem2:\n if meta_elements[elem3, 1] != i:\n node_reg[int(meta_elements[elem3, 1])] = 0\n else:\n node_reg[int(meta_elements[elem3, 2])] = 0\n\n # to create r_ud matrix\n r_ud = np.zeros((n_main_nodes, n_main_nodes))\n\n # for definite nodes\n for i in range(0, n_main_nodes):\n if node_reg[i] == 1:\n r_ud[i, i] = 1\n\n # for indefinite nodes\n for i, m_node in enumerate(main_nodes):\n if m_node[4] > 2:\n # to select the two meta-elements that play (elem1, elem2)\n elem1 = int(m_node[5])\n elem1_flag = m_node[5] - elem1\n j = 6\n while np.sin(meta_elements_data[int(np.real(m_node[j])), 2]\n - meta_elements_data[elem1, 2]) == 0:\n j = j + 1\n\n elem2 = int(m_node[j])\n elem2_flag = m_node[j] - elem2\n\n # to define main-nodes that play (order: main_nodes1, main_nodes2, main_nodes3)\n main_nodes2 = int(i)\n if elem1_flag == 0.1:\n main_nodes1 = int(meta_elements[elem1, 2])\n else:\n main_nodes1 = int(meta_elements[elem1, 1])\n\n if elem2_flag == 0.1:\n main_nodes3 = int(meta_elements[elem2, 2])\n else:\n main_nodes3 = int(meta_elements[elem2, 1])\n\n # to calculate data necessary for r_ud\n r_1 = meta_elements_data[elem1, 1]\n alfa1 = meta_elements_data[elem1, 2]\n sin1 = meta_elements_data[elem1, 3]\n cos1 = meta_elements_data[elem1, 4]\n if elem1 > 0:\n alfa1 = alfa1 - np.pi\n sin1 = -sin1\n cos1 = -cos1\n\n r_2 = meta_elements_data[elem2, 1]\n alfa2 = meta_elements_data[elem2, 2]\n sin2 = meta_elements_data[elem2, 3]\n cos2 = meta_elements_data[elem2, 4]\n if elem2 < 0:\n alfa2 = alfa2 - np.pi\n sin2 = -sin2\n cos2 = -cos2\n\n det = np.sin(alfa2 - alfa1)\n\n r_mat = np.array([[r_1, -r_1, 0], [0, r_2, -r_2]])\n c_s = np.array([[sin2, -sin1], [-cos2, cos1]])\n csr = c_s @ r_mat/det\n\n for j in range(1, main_nodes[i, 4]):\n elem3 = int(m_node[j + 5])\n elem3_flag = m_node[j + 5] - elem3\n if elem3 != elem2:\n if meta_elements[elem3, 1] != i:\n main_nodes4 = int(meta_elements[elem3, 1])\n else:\n main_nodes4 = int(meta_elements[elem3, 2])\n\n r_3 = meta_elements_data[elem3, 1]\n alfa3 = meta_elements_data[elem3, 2]\n sin3 = meta_elements_data[elem3, 3]\n cos3 = meta_elements_data[elem3, 4]\n if elem3_flag == 0.2:\n alfa3 = alfa3 - np.pi\n sin3 = -sin3\n cos3 = -cos3\n\n rud = -1/r_3*np.array([cos3, sin3]) @ csr\n rud[0, 1] = rud[0, 1] + 1\n r_ud[main_nodes4, main_nodes1] = rud[0, 0]\n r_ud[main_nodes4, main_nodes2] = rud[0, 1]\n r_ud[main_nodes4, main_nodes3] = rud[0, 2]\n\n # to completely eliminate indefinite nodes from r_ud (if necessary)\n k = 1\n while k == 1:\n k = 0\n for i in range(0, n_main_nodes):\n if node_reg[i] == 0:\n if np.nonzero(r_ud[:, i]):\n k = 1\n indices = np.nonzero(r_ud[:, i])\n for ind in indices:\n r_ud[ind, :] = r_ud[ind, :] + r_ud[i, :]*r_ud[ind, i]\n r_ud[ind, i] = 0\n\n return r_ud\n\n\ndef base_properties(nodes, elements):\n # this routine creates all the data for defining the base vectors from the\n # cross section properties\n #\n # input data\n # nodes, elements- basic data#\n # output data\n # main_nodes
- array of\n # [nr, x, z, orig nodes nr, nr of adj meta-elements, m-el_i-1, m-el_i-2, ...]\n # meta_elements - array of\n # [nr, main-nodes-1, main-nodes-2, nr of sub-nodes, sub-no-1, sub-nod-2, ...]\n # node_props - array of [original nodes nr, new nodes nr, nr of adj elements,\n # nodes type]\n # n_global_modes, n_dist_modes, n_local_modes, n_other_modes\n # - number of bulk, D, L, O modes, respectively\n # n_main_nodes, n_corner_nodes, n_sub_nodes\n # - number of main nodes, corner nodes and sub-nodes, respectively\n # dof_perm - permutation matrix, so that\n # (orig-displacements-vect) = (dof_perm) � (new-displacements-vector)\n #\n # S. Adany, Aug 28, 2006\n # B. Schafer, Aug 29, 2006\n # Z. Li, Dec 22, 2009\n\n [main_nodes, meta_elements, node_props] = meta_elems(nodes=nodes, elements=elements)\n [n_main_nodes, n_corner_nodes, n_sub_nodes] = node_class(node_props=node_props)\n [n_dist_modes, n_local_modes] = mode_nr(n_main_nodes, n_corner_nodes, n_sub_nodes, main_nodes)\n dof_perm = dof_ordering(node_props)\n\n return main_nodes, meta_elements, node_props, n_main_nodes, \\\n n_corner_nodes, n_sub_nodes, n_dist_modes, n_local_modes, dof_perm\n\n\ndef meta_elems(nodes, elements):\n # this routine re-organises the basic input data\n # to eliminate internal subdividing nodes\n # to form meta-elements (corner-to-corner or corner-to-free edge)\n # to identify main nodes (corner nodes and free edge nodes)\n #\n # important assumption: cross section is opened!\n #\n # input/output data\n # nodes, elements - same as elsewhere throughout this program\n # main_nodes
- array of\n # [nr, x, z, orig nodes nr, nr of adj meta-elements, m-el_i-1, m-el_i-2, ...]\n # meta_elements - array of\n # [nr, main-nodes-1, main-nodes-2, nr of sub-nodes, sub-no-1, sub-nod-2, ...]\n # node_props - array of [original nodes nr, new nodes nr, nr of adj elements, nodes type]\n #\n # note:\n # m-el_i-? is positive if the starting nodes of m-el_i-? coincides with\n # the given m-nodes, otherwise negative\n # nodes types: 1-corner, 2-edge, 3-sub\n # sub-nodes numbers are the original ones, of course\n #\n # S. Adany, Feb 06, 2004\n #\n n_nodes = len(nodes)\n #\n # to count nr of elements connecting to each nodes\n # + register internal nodes to be eliminated\n # + set nodes type (node_props[:, 4])\n node_props = np.zeros((n_nodes, 4))\n node_props[:, 0] = nodes[:, 0]\n for i in range(0, n_nodes):\n els = []\n for j, elem in enumerate(elements):\n if elem[1] == i or elem[2] == i:\n els.append(j) # zli: element no. containing this nodes\n\n node_props[i, 2] = len(els)\n if len(els) == 1:\n node_props[i, 3] = 2\n\n if len(els) >= 2:\n node_props[i, 3] = 1\n\n if len(els) == 2:\n n_1 = i\n n_2 = int(elements[els[0], 1])\n # zli: the first nodes of the first elements containing this nodes\n if n_2 == n_1:\n n_2 = int(elements[els[0], 2])\n\n n_3 = int(elements[els[1], 1])\n if n_3 == n_1:\n n_3 = int(elements[els[1], 2])\n\n a_1 = np.arctan2(nodes[n_2, 2] - nodes[n_1, 2], nodes[n_2, 1] - nodes[n_1, 1]) #?\n a_2 = np.arctan2(nodes[n_1, 2] - nodes[n_3, 2], nodes[n_1, 1] - nodes[n_3, 1])\n if abs(a_1 - a_2) < 1E-7:\n node_props[i, 2] = 0\n node_props[i, 3] = 3\n\n # to create meta-elements (with the original nodes numbers)\n meta_elements_temp = np.zeros((len(elements), 5))\n meta_elements_temp[:, 0:3] = elements[:, 0:3]\n for i in range(0, n_nodes):\n if node_props[i, 2] == 0:\n els = []\n for j, m_elem in enumerate(meta_elements_temp):\n if m_elem[1] == i or m_elem[2] == i:\n els.append(j)\n\n node1 = int(meta_elements_temp[els[0], 1])\n if node1 == i:\n node1 = int(meta_elements_temp[els[0], 2])\n\n node2 = int(meta_elements_temp[els[1], 1])\n if node2 == i:\n node2 = int(meta_elements_temp[els[1], 2])\n\n meta_elements_temp[els[0], 1] = node1\n meta_elements_temp[els[0], 2] = node2\n meta_elements_temp[els[1], 1] = -1\n meta_elements_temp[els[1], 2] = -1\n meta_elements_temp[els[0], 3] = meta_elements_temp[els[0], 3] + 1 # zli:\n if 3 + meta_elements_temp[els[0], 3] >= len(meta_elements_temp[0]):\n meta_elements_temp = np.c_[meta_elements_temp, np.zeros(len(meta_elements_temp))]\n meta_elements_temp[els[0],\n int(3\n + meta_elements_temp[els[0], 3])] = i # zli:deleted elements no.\n\n # to eliminate disappearing elements (nodes numbers are still the original ones!)\n n_meta_elements = 0 # nr of meta-elements\n meta_elements = []\n for m_elem_t in meta_elements_temp:\n if m_elem_t[1] != -1 and m_elem_t[2] != -1:\n meta_elements.append(m_elem_t)\n meta_elements[-1][0] = n_meta_elements\n n_meta_elements = n_meta_elements + 1\n meta_elements = np.array(meta_elements)\n\n # to create array of main-nodes\n #(first and fourth columns assign the new vs. original numbering,\n # + node_assign tells the original vs. new numbering)\n n_main_nodes = 0 # nr of main nodes\n main_nodes = []\n for i, node in enumerate(nodes):\n if node_props[i, 2] != 0:\n main_nodes.append([n_main_nodes, node[1], node[2], i, node_props[i, 2]])\n node_props[i, 1] = n_main_nodes\n n_main_nodes = n_main_nodes + 1\n main_nodes = np.array(main_nodes)\n\n # to re-number nodes in the array meta_elements (only for main nodes, of course)\n for i, n_props in enumerate(node_props):\n if node_props[i, 2] != 0:\n for m_elem in meta_elements:\n if m_elem[1] == i:\n m_elem[1] = n_props[1]\n\n if m_elem[2] == i:\n m_elem[2] = n_props[1]\n\n # to assign meta-elements to main-nodes\n for i in range(0, n_main_nodes):\n k = 5\n for j, m_elem in enumerate(meta_elements):\n if m_elem[1] == i:\n if len(main_nodes[0]) <= k:\n main_nodes = np.c_[main_nodes, np.zeros(n_main_nodes)]\n main_nodes[i, k] = j + 0.2\n k = k + 1\n\n if m_elem[2] == i:\n if len(main_nodes[0]) <= k:\n main_nodes = np.c_[main_nodes, np.zeros(n_main_nodes)]\n main_nodes[i, k] = j + 0.1\n k = k + 1\n\n # to finish node_assign with the new numbers of subdividing nodes\n n_sub_nodes = 0 # nr of subdividing nodes\n for n_prop in node_props:\n if n_prop[2] == 0:\n n_prop[1] = n_main_nodes + n_sub_nodes\n n_sub_nodes = n_sub_nodes + 1\n\n return main_nodes, meta_elements, node_props\n\n\ndef mode_nr(n_main_nodes, n_corner_nodes, n_sub_nodes, main_nodes):\n #\n # this routine determines the number of distortional and local buckling modes\n # if GBT-like assumptions are used\n #\n #\n # input/output data\n # n_main_nodes, n_sub_nodes - number of main nodes and sub_nodes, respectively\n # main_nodes [main nodes] - array of\n # [nr, x, z, orig nodes nr, nr of adj meta-elements, m-el_i-1, m-el_i-2, ...]\n # n_dist_modes, n_local_modes - number of distortional and local buckling modes, respectively\n #\n # S. Adany, Feb 09, 2004\n #\n #\n # to count the number of distortional modes\n n_dist_modes = n_main_nodes - 4\n for i in range(0, n_main_nodes):\n if main_nodes[i, 4] > 2:\n n_dist_modes = n_dist_modes - (main_nodes[i, 4] - 2)\n\n if n_dist_modes < 0:\n n_dist_modes = 0\n\n # to count the number of local modes\n n_edge_nodes = n_main_nodes - n_corner_nodes # nr of edge nodes\n n_local_modes = n_main_nodes + 2*n_sub_nodes + n_edge_nodes\n\n return n_dist_modes, n_local_modes\n\n\ndef dof_ordering(node_props):\n # this routine re-orders the DOFs,\n # according to the need of forming shape vectors for various buckling modes\n #\n # input/output data\n # node_props - array of [original nodes nr, new nodes nr, nr of adj elements, nodes type]\n # dof_perm - permutation matrix, so that\n # (orig-displacements-vect) = (dof_perm) � (new-displacements-vector)\n #\n # notes:\n # (1) nodes types: 1-corner, 2-edge, 3-sub\n # (2) the re-numbering of long. displacements. DOFs of main nodes, which may be\n # necessary for dist. buckling, is not included here but handled\n # separately when forming Ry constraint matrix\n #\n # S. Adany, Feb 06, 2004\n #\n #\n # to count corner-, edge- and sub-nodes\n n_node_props = len(node_props)\n n_corner_nodes = 0\n n_edge_nodes = 0\n n_sub_nodes = 0\n for n_prop in node_props:\n if n_prop[3] == 1:\n n_corner_nodes = n_corner_nodes + 1\n if n_prop[3] == 2:\n n_edge_nodes = n_edge_nodes + 1\n if n_prop[3] == 3:\n n_sub_nodes = n_sub_nodes + 1\n\n n_main_nodes = n_corner_nodes + n_edge_nodes # nr of main nodes\n\n # to form permutation matrix\n dof_perm = np.zeros((4*n_node_props, 4*n_node_props))\n\n # x DOFs\n i_c = 0\n i_e = 0\n i_s = 0\n for i, n_prop in enumerate(node_props):\n if n_prop[3] == 1: # corner nodes\n dof_perm[2*i, n_main_nodes + i_c] = 1\n i_c = i_c + 1\n if n_prop[3] == 2: # edge nodes\n dof_perm[2*i, n_main_nodes + 2*n_corner_nodes + i_e] = 1\n i_e = i_e + 1\n if n_prop[3] == 3: # sub nodes\n dof_perm[2*i, 4*n_main_nodes + i_s] = 1\n i_s = i_s + 1\n\n # y DOFs\n i_c = 0\n i_s = 0\n for i, n_prop in enumerate(node_props):\n if n_prop[3] == 1 or n_prop[3] == 2: # corner or edge nodes\n dof_perm[2*i + 1, i_c] = 1\n i_c = i_c + 1\n if n_prop[3] == 3: # sub nodes\n dof_perm[2*i + 1, 4*n_main_nodes + 3*n_sub_nodes + i_s] = 1\n i_s = i_s + 1\n\n # z DOFs\n i_c = 0\n i_e = 0\n i_s = 0\n for i, n_prop in enumerate(node_props):\n if n_prop[3] == 1: # corner nodes\n dof_perm[2*n_node_props + 2*i, n_main_nodes + n_corner_nodes + i_c] = 1\n i_c = i_c + 1\n if n_prop[3] == 2: # edge nodes\n dof_perm[2*n_node_props + 2*i, n_main_nodes + 2*n_corner_nodes + n_edge_nodes + i_e] = 1\n i_e = i_e + 1\n if n_prop[3] == 3: # sub nodes\n dof_perm[2*n_node_props + 2*i, 4*n_main_nodes + n_sub_nodes + i_s] = 1\n i_s = i_s + 1\n\n # teta DOFs\n i_c = 0\n i_s = 0\n for i, n_prop in enumerate(node_props):\n if n_prop[3] == 1 or n_prop[3] == 2: # corner or edge nodes\n dof_perm[2*n_node_props + 2*i + 1, 3*n_main_nodes + i_c] = 1\n i_c = i_c + 1\n if n_prop[3] == 3: # sub nodes\n dof_perm[2*n_node_props + 2*i + 1, 4*n_main_nodes + 2*n_sub_nodes + i_s] = 1\n i_s = i_s + 1\n\n return dof_perm\n\n\ndef create_k_globals(m_i, nodes, elements, el_props, props, length, b_c):\n # called from base_update, while only single longitudinal term m_i involved\n #\n # created on Aug 28, 2006, by S. Adany\n # modified on Jul 10, 2009 by Z. Li\n\n # MATRIX SIZES\n n_nodes = len(nodes)\n\n # ZERO OUT THE GLOBAL MATRICES\n k_global = np.zeros((n_nodes*4, n_nodes*4))\n kg_global = np.zeros((n_nodes*4, n_nodes*4))\n\n # ASSEMBLE THE GLOBAL STIFFNESS MATRICES\n for i, elem in enumerate(elements):\n thick = elem[3]\n b_strip = el_props[i, 1]\n mat_num = int(elem[4])\n row = int((np.argwhere(props[:, 0] == mat_num)).reshape(1))\n mat = props[row]\n stiff_x = mat[1]\n stiff_y = mat[2]\n nu_x = mat[3]\n nu_y = mat[4]\n bulk = mat[5]\n k_l = klocal_m(\n stiff_x=stiff_x,\n stiff_y=stiff_y,\n nu_x=nu_x,\n nu_y=nu_y,\n bulk=bulk,\n thick=thick,\n length=length,\n b_strip=b_strip,\n b_c=b_c,\n m_i=m_i\n )\n # Generate geometric stiffness matrix (kg_local) in local coordinates\n node_i = int(elem[1])\n node_j = int(elem[2])\n ty_1 = nodes[node_i, 7]*thick\n ty_2 = nodes[node_j, 7]*thick\n kg_l = kglocal_m(length=length, b_strip=b_strip, ty_1=ty_1, ty_2=ty_2, b_c=b_c, m_i=m_i)\n # Transform k_local and kg_local into global coordinates\n alpha = el_props[i, 2]\n [k_local, kg_local] = trans_m(alpha, k_l, kg_l)\n\n # Add element contribution of k_local to full matrix k_global and kg_local to kg_global\n [k_global, kg_global] = assemble_m(\n k_global=k_global,\n kg_global=kg_global,\n k_local=k_local,\n kg_local=kg_local,\n node_i=node_i,\n node_j=node_j,\n n_nodes=n_nodes\n )\n\n return k_global, kg_global\n\n\ndef klocal_m(stiff_x, stiff_y, nu_x, nu_y, bulk, thick, length, b_strip, m_i, b_c):\n # assemble local elastic stiffness matrix for a single longitudinal term m_i\n #\n # created on Jul 10, 2009 by Z. Li\n\n # Generate element stiffness matrix (k_local) in local coordinates\n e_1 = stiff_x/(1 - nu_x*nu_y)\n e_2 = stiff_y/(1 - nu_x*nu_y)\n d_x = stiff_x*thick**3/(12*(1 - nu_x*nu_y))\n d_y = stiff_y*thick**3/(12*(1 - nu_x*nu_y))\n d_1 = nu_x*stiff_y*thick**3/(12*(1 - nu_x*nu_y))\n d_xy = bulk*thick**3/12\n #\n # k_local = sparse(np.zeros(8*m_i, 8*m_i))\n z_0 = np.zeros((4, 4))\n i = m_i\n j = m_i\n km_mp = np.zeros((4, 4))\n kf_mp = np.zeros((4, 4))\n u_m = i*np.pi\n u_p = j*np.pi\n c_1 = u_m/length\n c_2 = u_p/length\n #\n [i_1, i_2, i_3, i_4, i_5] = pycufsm.analysis.bc_i1_5(b_c, i, j, length)\n #\n # assemble the matrix of Km_mp\n km_mp[0, 0] = e_1*i_1/b_strip + bulk*b_strip*i_5/3\n km_mp[0, 1] = e_2*nu_x*(-1/2/c_2)*i_3 - bulk*i_5/2/c_2\n km_mp[0, 2] = -e_1*i_1/b_strip + bulk*b_strip*i_5/6\n km_mp[0, 3] = e_2*nu_x*(-1/2/c_2)*i_3 + bulk*i_5/2/c_2\n\n km_mp[1, 0] = e_2*nu_x*(-1/2/c_1)*i_2 - bulk*i_5/2/c_1\n km_mp[1, 1] = e_2*b_strip*i_4/3/c_1/c_2 + bulk*i_5/b_strip/c_1/c_2\n km_mp[1, 2] = e_2*nu_x*(1/2/c_1)*i_2 - bulk*i_5/2/c_1\n km_mp[1, 3] = e_2*b_strip*i_4/6/c_1/c_2 - bulk*i_5/b_strip/c_1/c_2\n\n km_mp[2, 0] = -e_1*i_1/b_strip + bulk*b_strip*i_5/6\n km_mp[2, 1] = e_2*nu_x*(1/2/c_2)*i_3 - bulk*i_5/2/c_2\n km_mp[2, 2] = e_1*i_1/b_strip + bulk*b_strip*i_5/3\n km_mp[2, 3] = e_2*nu_x*(1/2/c_2)*i_3 + bulk*i_5/2/c_2\n\n km_mp[3, 0] = e_2*nu_x*(-1/2/c_1)*i_2 + bulk*i_5/2/c_1\n km_mp[3, 1] = e_2*b_strip*i_4/6/c_1/c_2 - bulk*i_5/b_strip/c_1/c_2\n km_mp[3, 2] = e_2*nu_x*(1/2/c_1)*i_2 + bulk*i_5/2/c_1\n km_mp[3, 3] = e_2*b_strip*i_4/3/c_1/c_2 + bulk*i_5/b_strip/c_1/c_2\n km_mp = km_mp*thick\n #\n #\n # assemble the matrix of Kf_mp\n kf_mp[0, 0] = (5040*d_x*i_1 - 504*b_strip**2*d_1*i_2 - 504*b_strip**2*d_1*i_3 \\\n + 156*b_strip**4*d_y*i_4 + 2016*b_strip**2*d_xy*i_5) / 420/b_strip**3\n kf_mp[0, 1] = (2520*b_strip*d_x*i_1 - 462*b_strip**3*d_1*i_2 - 42*b_strip**3*d_1*i_3 \\\n + 22*b_strip**5*d_y*i_4 + 168*b_strip**3*d_xy*i_5) / 420/b_strip**3\n kf_mp[0, 2] = (-5040*d_x*i_1 + 504*b_strip**2*d_1*i_2 + 504*b_strip**2*d_1*i_3 \\\n + 54*b_strip**4*d_y*i_4 - 2016*b_strip**2*d_xy*i_5) / 420/b_strip**3\n kf_mp[0, 3] = (2520*b_strip*d_x*i_1 - 42*b_strip**3*d_1*i_2 - 42*b_strip**3*d_1*i_3 \\\n - 13*b_strip**5*d_y*i_4 + 168*b_strip**3*d_xy*i_5) / 420/b_strip**3\n\n kf_mp[1, 0] = (2520*b_strip*d_x*i_1 - 462*b_strip**3*d_1*i_3 - 42*b_strip**3*d_1*i_2 \\\n + 22*b_strip**5*d_y*i_4 + 168*b_strip**3*d_xy*i_5) / 420/b_strip**3\n kf_mp[1, 1] = (1680*b_strip**2*d_x*i_1 - 56*b_strip**4*d_1*i_2 - 56*b_strip**4*d_1*i_3 \\\n + 4*b_strip**6*d_y*i_4 + 224*b_strip**4*d_xy*i_5) / 420/b_strip**3\n kf_mp[1, 2] = (-2520*b_strip*d_x*i_1 + 42*b_strip**3*d_1*i_2 + 42*b_strip**3*d_1*i_3 \\\n + 13*b_strip**5*d_y*i_4 - 168*b_strip**3*d_xy*i_5) / 420/b_strip**3\n kf_mp[1, 3] = (840*b_strip**2*d_x*i_1 + 14*b_strip**4*d_1*i_2 + 14*b_strip**4*d_1*i_3 \\\n - 3*b_strip**6*d_y*i_4 - 56*b_strip**4*d_xy*i_5) / 420/b_strip**3\n\n kf_mp[2, 0] = kf_mp[0, 2]\n kf_mp[2, 1] = kf_mp[1, 2]\n kf_mp[2, 2] = (5040*d_x*i_1 - 504*b_strip**2*d_1*i_2 - 504*b_strip**2*d_1*i_3 \\\n + 156*b_strip**4*d_y*i_4 + 2016*b_strip**2*d_xy*i_5) / 420/b_strip**3\n kf_mp[2, 3] = (-2520*b_strip*d_x*i_1 + 462*b_strip**3*d_1*i_2 + 42*b_strip**3*d_1*i_3 \\\n - 22*b_strip**5*d_y*i_4 - 168*b_strip**3*d_xy*i_5) / 420/b_strip**3\n\n kf_mp[3, 0] = kf_mp[0, 3]\n kf_mp[3, 1] = kf_mp[1, 3]\n kf_mp[3, 2] = (-2520*b_strip*d_x*i_1 + 462*b_strip**3*d_1*i_3 + 42*b_strip**3*d_1*i_2 \\\n - 22*b_strip**5*d_y*i_4 - 168*b_strip**3*d_xy*i_5) / 420/b_strip**3 # not symmetric\n kf_mp[3, 3] = (1680*b_strip**2*d_x*i_1 - 56*b_strip**4*d_1*i_2 - 56*b_strip**4*d_1*i_3 \\\n + 4*b_strip**6*d_y*i_4 + 224*b_strip**4*d_xy*i_5) / 420/b_strip**3\n\n # assemble the membrane and flexural stiffness matrices\n kmp = np.concatenate(\n (np.concatenate((km_mp, z_0), axis=1), np.concatenate((z_0, kf_mp), axis=1))\n )\n # add it into local element stiffness matrix by corresponding to m_i\n k_local = kmp\n\n return k_local\n\n\ndef kglocal_m(length, b_strip, m_i, ty_1, ty_2, b_c):\n # assemble local geometric stiffness matrix for a single longitudinal term m_i\n\n # created on Jul 10, 2009 by Z. Li\n\n # Generate geometric stiffness matrix (kg_local) in local coordinates\n # kg_local = sparse(np.zeros(8*m_i, 8*m_i))\n i = m_i\n j = m_i\n gm_mp = np.zeros((4, 4))\n z_0 = np.zeros((4, 4))\n gf_mp = np.zeros((4, 4))\n u_m = i*np.pi\n u_p = j*np.pi\n #\n [_, _, _, i_4, i_5] = pycufsm.analysis.bc_i1_5(b_c, i, j, length)\n #\n # assemble the matrix of gm_mp (symmetric membrane stability matrix)\n gm_mp[0, 0] = b_strip*(3*ty_1 + ty_2)*i_5/12\n gm_mp[0, 2] = b_strip*(ty_1 + ty_2)*i_5/12\n gm_mp[2, 0] = gm_mp[0, 2]\n gm_mp[1, 1] = b_strip*length**2*(3*ty_1 + ty_2)*i_4/12/u_m/u_p\n gm_mp[1, 3] = b_strip*length**2*(ty_1 + ty_2)*i_4/12/u_m/u_p\n gm_mp[3, 1] = gm_mp[1, 3]\n gm_mp[2, 2] = b_strip*(ty_1 + 3*ty_2)*i_5/12\n gm_mp[3, 3] = b_strip*length**2*(ty_1 + 3*ty_2)*i_4/12/u_m/u_p\n #\n # assemble the matrix of gf_mp (symmetric flexural stability matrix)\n gf_mp[0, 0] = (10*ty_1 + 3*ty_2)*b_strip*i_5/35\n gf_mp[0, 1] = (15*ty_1 + 7*ty_2)*b_strip**2*i_5/210/2\n gf_mp[1, 0] = gf_mp[0, 1]\n gf_mp[0, 2] = 9*(ty_1 + ty_2)*b_strip*i_5/140\n gf_mp[2, 0] = gf_mp[0, 2]\n gf_mp[0, 3] = -(7*ty_1 + 6*ty_2)*b_strip**2*i_5/420\n gf_mp[3, 0] = gf_mp[0, 3]\n gf_mp[1, 1] = (5*ty_1 + 3*ty_2)*b_strip**3*i_5/2/420\n gf_mp[1, 2] = (6*ty_1 + 7*ty_2)*b_strip**2*i_5/420\n gf_mp[2, 1] = gf_mp[1, 2]\n gf_mp[1, 3] = -(ty_1 + ty_2)*b_strip**3*i_5/140/2\n gf_mp[3, 1] = gf_mp[1, 3]\n gf_mp[2, 2] = (3*ty_1 + 10*ty_2)*b_strip*i_5/35\n gf_mp[2, 3] = -(7*ty_1 + 15*ty_2)*b_strip**2*i_5/420\n gf_mp[3, 2] = gf_mp[2, 3]\n gf_mp[3, 3] = (3*ty_1 + 5*ty_2)*b_strip**3*i_5/420/2\n # assemble the membrane and flexural stiffness matrices\n kg_mp = np.concatenate(\n (np.concatenate((gm_mp, z_0), axis=1), np.concatenate((z_0, gf_mp), axis=1))\n )\n # add it into local geometric stiffness matrix by corresponding to m_i\n kg_local = kg_mp\n return kg_local\n\n\ndef trans_m(alpha, k_local, kg_local):\n # transfer the local stiffness into global stiffness\n\n # created on Jul 10, 2009 by Z. Li\n gamma = np.array([[np.cos(alpha), 0, 0, 0, -np.sin(alpha), 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0],\n [0, 0, np.cos(alpha), 0, 0, 0, -np.sin(alpha), 0], [0, 0, 0, 1, 0, 0, 0, 0],\n [np.sin(alpha), 0, 0, 0, np.cos(alpha), 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0],\n [0, 0, np.sin(alpha), 0, 0, 0, np.cos(alpha), 0], [0, 0, 0, 0, 0, 0, 0, 1]])\n # extend to multi-m\n # for i = 1:m_i\n # gamma(8*(i-1)+1:8*i, 8*(i-1)+1:8*i) = gam\n # end\n #\n k_global = gamma @ k_local @ gamma.conj().T\n kg_global = gamma @ kg_local @ gamma.conj().T\n\n return k_global, kg_global\n\n\ndef assemble_m(k_global, kg_global, k_local, kg_local, node_i, node_j, n_nodes):\n # BWS\n # 1997\n # Add the element contribution to the global stiffness matrix for single\n # longitudinal term m_i\n\n # modifed on Jul 10, 2009 by Z. Li\n\n # Submatrices for the initial stiffness\n k11 = k_local[0:2, 0:2]\n k12 = k_local[0:2, 2:4]\n k13 = k_local[0:2, 4:6]\n k14 = k_local[0:2, 6:8]\n k21 = k_local[2:4, 0:2]\n k22 = k_local[2:4, 2:4]\n k23 = k_local[2:4, 4:6]\n k24 = k_local[2:4, 6:8]\n k31 = k_local[4:6, 0:2]\n k32 = k_local[4:6, 2:4]\n k33 = k_local[4:6, 4:6]\n k34 = k_local[4:6, 6:8]\n k41 = k_local[6:8, 0:2]\n k42 = k_local[6:8, 2:4]\n k43 = k_local[6:8, 4:6]\n k44 = k_local[6:8, 6:8]\n #\n # Submatrices for the geometric stiffness\n kg11 = kg_local[0:2, 0:2]\n kg12 = kg_local[0:2, 2:4]\n kg13 = kg_local[0:2, 4:6]\n kg14 = kg_local[0:2, 6:8]\n kg21 = kg_local[2:4, 0:2]\n kg22 = kg_local[2:4, 2:4]\n kg23 = kg_local[2:4, 4:6]\n kg24 = kg_local[2:4, 6:8]\n kg31 = kg_local[4:6, 0:2]\n kg32 = kg_local[4:6, 2:4]\n kg33 = kg_local[4:6, 4:6]\n kg34 = kg_local[4:6, 6:8]\n kg41 = kg_local[6:8, 0:2]\n kg42 = kg_local[6:8, 2:4]\n kg43 = kg_local[6:8, 4:6]\n kg44 = kg_local[6:8, 6:8]\n #\n k_2_matrix = np.zeros((4*n_nodes, 4*n_nodes))\n k_3_matrix = np.zeros((4*n_nodes, 4*n_nodes))\n #\n # The additional terms for k_global are stored in k_2_matrix\n skip = 2*n_nodes\n k_2_matrix[node_i*2:node_i*2 + 2, node_i*2:node_i*2 + 2] = k11\n k_2_matrix[node_i*2:node_i*2 + 2, node_j*2:node_j*2 + 2] = k12\n k_2_matrix[node_j*2:node_j*2 + 2, node_i*2:node_i*2 + 2] = k21\n k_2_matrix[node_j*2:node_j*2 + 2, node_j*2:node_j*2 + 2] = k22\n #\n k_2_matrix[skip + node_i*2:skip + node_i*2 + 2, skip + node_i*2:skip + node_i*2 + 2] = k33\n k_2_matrix[skip + node_i*2:skip + node_i*2 + 2, skip + node_j*2:skip + node_j*2 + 2] = k34\n k_2_matrix[skip + node_j*2:skip + node_j*2 + 2, skip + node_i*2:skip + node_i*2 + 2] = k43\n k_2_matrix[skip + node_j*2:skip + node_j*2 + 2, skip + node_j*2:skip + node_j*2 + 2] = k44\n #\n k_2_matrix[node_i*2:node_i*2 + 2, skip + node_i*2:skip + node_i*2 + 2] = k13\n k_2_matrix[node_i*2:node_i*2 + 2, skip + node_j*2:skip + node_j*2 + 2] = k14\n k_2_matrix[node_j*2:node_j*2 + 2, skip + node_i*2:skip + node_i*2 + 2] = k23\n k_2_matrix[node_j*2:node_j*2 + 2, skip + node_j*2:skip + node_j*2 + 2] = k24\n #\n k_2_matrix[skip + node_i*2:skip + node_i*2 + 2, node_i*2:node_i*2 + 2] = k31\n k_2_matrix[skip + node_i*2:skip + node_i*2 + 2, node_j*2:node_j*2 + 2] = k32\n k_2_matrix[skip + node_j*2:skip + node_j*2 + 2, node_i*2:node_i*2 + 2] = k41\n k_2_matrix[skip + node_j*2:skip + node_j*2 + 2, node_j*2:node_j*2 + 2] = k42\n k_global = k_global + k_2_matrix\n #\n # The additional terms for kg_global are stored in k_3_matrix\n k_3_matrix[node_i*2:node_i*2 + 2, node_i*2:node_i*2 + 2] = kg11\n k_3_matrix[node_i*2:node_i*2 + 2, node_j*2:node_j*2 + 2] = kg12\n k_3_matrix[node_j*2:node_j*2 + 2, node_i*2:node_i*2 + 2] = kg21\n k_3_matrix[node_j*2:node_j*2 + 2, node_j*2:node_j*2 + 2] = kg22\n #\n k_3_matrix[skip + node_i*2:skip + node_i*2 + 2, skip + node_i*2:skip + node_i*2 + 2] = kg33\n k_3_matrix[skip + node_i*2:skip + node_i*2 + 2, skip + node_j*2:skip + node_j*2 + 2] = kg34\n k_3_matrix[skip + node_j*2:skip + node_j*2 + 2, skip + node_i*2:skip + node_i*2 + 2] = kg43\n k_3_matrix[skip + node_j*2:skip + node_j*2 + 2, skip + node_j*2:skip + node_j*2 + 2] = kg44\n #\n k_3_matrix[node_i*2:node_i*2 + 2, skip + node_i*2:skip + node_i*2 + 2] = kg13\n k_3_matrix[node_i*2:node_i*2 + 2, skip + node_j*2:skip + node_j*2 + 2] = kg14\n k_3_matrix[node_j*2:node_j*2 + 2, skip + node_i*2:skip + node_i*2 + 2] = kg23\n k_3_matrix[node_j*2:node_j*2 + 2, skip + node_j*2:skip + node_j*2 + 2] = kg24\n #\n k_3_matrix[skip + node_i*2:skip + node_i*2 + 2, node_i*2:node_i*2 + 2] = kg31\n k_3_matrix[skip + node_i*2:skip + node_i*2 + 2, node_j*2:node_j*2 + 2] = kg32\n k_3_matrix[skip + node_j*2:skip + node_j*2 + 2, node_i*2:node_i*2 + 2] = kg41\n k_3_matrix[skip + node_j*2:skip + node_j*2 + 2, node_j*2:node_j*2 + 2] = kg42\n #\n kg_global = kg_global + k_3_matrix\n return k_global, kg_global\n\n\ndef kglobal_transv(nodes, elements, props, m_i, length, b_c, el_props):\n #\n # this routine creates the global stiffness matrix for planar displacements\n # basically the same way as in the main program, however:\n # only one half-wave number m_i is considered,\n # only w, teta terms are considered,\n # plus stiff_y = nu_x = nu_y = 0 is assumed\n # plus the longitudinal displacements. DOFs are explicitely eliminated\n # the multiplication by 'length' (member length) is not done here, must be done\n # outside of this routine\n #\n # input/output data\n # nodes, elements, props - same as elsewhere throughout this program\n # m_i - number of half waves\n # k_global_transv - global stiffness matrix (geometric not included)\n #\n # S. Adany, Feb 08, 2004\n # Z. Li, Jul 10, 2009\n #\n n_nodes = len(nodes)\n k_global_transv = np.zeros((4*n_nodes, 4*n_nodes))\n #\n for i, elem in enumerate(elements):\n thick = elem[3]\n b_strip = el_props[i, 1]\n mat_num = int(elem[4])\n row = int((np.argwhere(props[:, 0] == mat_num)).reshape(1))\n mat = props[row]\n stiff_x = mat[1]\n stiff_y = mat[2]\n nu_x = mat[3]\n nu_y = mat[4]\n bulk = mat[5]\n k_l = klocal_transv(\n stiff_x=stiff_x,\n stiff_y=stiff_y,\n nu_x=nu_x,\n nu_y=nu_y,\n bulk=bulk,\n thick=thick,\n length=length,\n b_strip=b_strip,\n b_c=b_c,\n m_i=m_i\n )\n\n # Transform k_local and kg_local into global coordinates\n alpha = el_props[i, 2]\n k_local = trans_single(alpha, k_l)\n\n # Add element contribution of k_local to full matrix k_global and kg_local to kg_global\n node_i = int(elem[1])\n node_j = int(elem[2])\n k_global_transv = assemble_single(\n k_global=k_global_transv,\n k_local=k_local,\n node_i=node_i,\n node_j=node_j,\n n_nodes=n_nodes\n )\n\n return k_global_transv\n\n\ndef klocal_transv(stiff_x, stiff_y, nu_x, nu_y, bulk, thick, length, b_strip, m_i, b_c):\n #\n # this routine creates the local stiffness matrix for bending terms\n # basically the same way as in the main program, however:\n # only for single half-wave number m_i\n # membrane strains practically zero, (membrane moduli are enlarged)\n # for bending, only transverse terms are considered, (practically: only\n # keeps the i_1 term, set i_2 through i_5 to be zero)\n # also different from the main program, here only involves one single\n # longitudinal term m_i.\n #\n # input/output data\n # nodes, elements, props - same as elsewhere throughout this program\n # k_global_transv - global stiffness matrix (geometric included)\n #\n # Z. Li, Jul 10, 2009\n\n e_1 = stiff_x/(1 - nu_x*nu_y)*100000000\n e_2 = stiff_y/(1 - nu_x*nu_y)\n d_x = stiff_x*thick**3/(12*(1 - nu_x*nu_y))\n d_y = stiff_y*thick**3/(12*(1 - nu_x*nu_y))\n d_1 = nu_x*stiff_y*thick**3/(12*(1 - nu_x*nu_y))\n d_xy = bulk*thick**3/12\n\n z_0 = np.zeros((4, 4))\n i = m_i\n j = m_i\n km_mp = np.zeros((4, 4))\n kf_mp = np.zeros((4, 4))\n u_m = i*np.pi\n u_p = j*np.pi\n c_1 = u_m/length\n c_2 = u_p/length\n\n [i_1, _, _, _, _] = pycufsm.analysis.bc_i1_5(b_c, i, j, length)\n i_2 = 0\n i_3 = 0\n i_4 = 0\n i_5 = 0\n\n # assemble in-plane stiffness matrix of Km_mp\n km_mp[0, 0] = e_1*i_1/b_strip + bulk*b_strip*i_5/3\n km_mp[0, 1] = e_2*nu_x*(-1/2/c_2)*i_3 - bulk*i_5/2/c_2\n km_mp[0, 2] = -e_1*i_1/b_strip + bulk*b_strip*i_5/6\n km_mp[0, 3] = e_2*nu_x*(-1/2/c_2)*i_3 + bulk*i_5/2/c_2\n\n km_mp[1, 0] = e_2*nu_x*(-1/2/c_1)*i_2 - bulk*i_5/2/c_1\n km_mp[1, 1] = e_2*b_strip*i_4/3/c_1/c_2 + bulk*i_5/b_strip/c_1/c_2\n km_mp[1, 2] = e_2*nu_x*(1/2/c_1)*i_2 - bulk*i_5/2/c_1\n km_mp[1, 3] = e_2*b_strip*i_4/6/c_1/c_2 - bulk*i_5/b_strip/c_1/c_2\n\n km_mp[2, 0] = -e_1*i_1/b_strip + bulk*b_strip*i_5/6\n km_mp[2, 1] = e_2*nu_x*(1/2/c_2)*i_3 - bulk*i_5/2/c_2\n km_mp[2, 2] = e_1*i_1/b_strip + bulk*b_strip*i_5/3\n km_mp[2, 3] = e_2*nu_x*(1/2/c_2)*i_3 + bulk*i_5/2/c_2\n\n km_mp[3, 0] = e_2*nu_x*(-1/2/c_1)*i_2 + bulk*i_5/2/c_1\n km_mp[3, 1] = e_2*b_strip*i_4/6/c_1/c_2 - bulk*i_5/b_strip/c_1/c_2\n km_mp[3, 2] = e_2*nu_x*(1/2/c_1)*i_2 + bulk*i_5/2/c_1\n km_mp[3, 3] = e_2*b_strip*i_4/3/c_1/c_2 + bulk*i_5/b_strip/c_1/c_2\n km_mp = km_mp*thick\n\n # assemble the bending stiffness matrix of Kf_mp\n kf_mp[0, 0] = (5040*d_x*i_1 - 504*b_strip**2*d_1*i_2 - 504*b_strip**2*d_1*i_3 \\\n + 156*b_strip**4*d_y*i_4 + 2016*b_strip**2*d_xy*i_5) / 420/b_strip**3\n kf_mp[0, 1] = (2520*b_strip*d_x*i_1 - 462*b_strip**3*d_1*i_2 - 42*b_strip**3*d_1*i_3 \\\n + 22*b_strip**5*d_y*i_4 + 168*b_strip**3*d_xy*i_5) / 420/b_strip**3\n kf_mp[0, 2] = (-5040*d_x*i_1 + 504*b_strip**2*d_1*i_2 + 504*b_strip**2*d_1*i_3 \\\n + 54*b_strip**4*d_y*i_4 - 2016*b_strip**2*d_xy*i_5) / 420/b_strip**3\n kf_mp[0, 3] = (2520*b_strip*d_x*i_1 - 42*b_strip**3*d_1*i_2 - 42*b_strip**3*d_1*i_3 \\\n - 13*b_strip**5*d_y*i_4 + 168*b_strip**3*d_xy*i_5) / 420/b_strip**3\n\n kf_mp[1, 0] = (2520*b_strip*d_x*i_1 - 462*b_strip**3*d_1*i_3 - 42*b_strip**3*d_1*i_2 \\\n + 22*b_strip**5*d_y*i_4 + 168*b_strip**3*d_xy*i_5) / 420/b_strip**3\n kf_mp[1, 1] = (1680*b_strip**2*d_x*i_1 - 56*b_strip**4*d_1*i_2 - 56*b_strip**4*d_1*i_3 \\\n + 4*b_strip**6*d_y*i_4 + 224*b_strip**4*d_xy*i_5) / 420/b_strip**3\n kf_mp[1, 2] = (-2520*b_strip*d_x*i_1 + 42*b_strip**3*d_1*i_2 + 42*b_strip**3*d_1*i_3 \\\n + 13*b_strip**5*d_y*i_4 - 168*b_strip**3*d_xy*i_5) / 420/b_strip**3\n kf_mp[1, 3] = (840*b_strip**2*d_x*i_1 + 14*b_strip**4*d_1*i_2 + 14*b_strip**4*d_1*i_3 \\\n - 3*b_strip**6*d_y*i_4 - 56*b_strip**4*d_xy*i_5) / 420/b_strip**3\n\n kf_mp[2, 0] = kf_mp[0, 2]\n kf_mp[2, 1] = kf_mp[1, 2]\n kf_mp[2, 2] = (5040*d_x*i_1 - 504*b_strip**2*d_1*i_2 - 504*b_strip**2*d_1*i_3 \\\n + 156*b_strip**4*d_y*i_4 + 2016*b_strip**2*d_xy*i_5) / 420/b_strip**3\n kf_mp[2, 3] = (-2520*b_strip*d_x*i_1 + 462*b_strip**3*d_1*i_2 + 42*b_strip**3*d_1*i_3 \\\n - 22*b_strip**5*d_y*i_4 - 168*b_strip**3*d_xy*i_5) / 420/b_strip**3\n\n kf_mp[3, 0] = kf_mp[0, 3]\n kf_mp[3, 1] = kf_mp[1, 3]\n kf_mp[3, 2] = (-2520*b_strip*d_x*i_1 + 462*b_strip**3*d_1*i_3 + 42*b_strip**3*d_1*i_2 \\\n - 22*b_strip**5*d_y*i_4 - 168*b_strip**3*d_xy*i_5) / 420/b_strip**3 # not symmetric\n kf_mp[3, 3] = (1680*b_strip**2*d_x*i_1 - 56*b_strip**4*d_1*i_2 - 56*b_strip**4*d_1*i_3 \\\n + 4*b_strip**6*d_y*i_4 + 224*b_strip**4*d_xy*i_5) / 420/b_strip**3\n\n # assemble the membrane and flexural stiffness matrices\n kmp = np.concatenate(\n (np.concatenate((km_mp, z_0), axis=1), np.concatenate((z_0, kf_mp), axis=1))\n )\n\n # local stiffness matrix:\n k_local = kmp\n return k_local\n\n\ndef assemble_single(k_global, k_local, node_i, node_j, n_nodes):\n #\n # this routine adds the element contribution to the global stiffness matrix\n # basically it does the same as routine 'assemble', however:\n # it does not care about kg_global (geom stiff matrix)\n # only involves single half-wave number m_i\n\n # S. Adany, Feb 06, 2004\n # Z. Li, Jul 10, 2009\n #\n # submatrices for the initial stiffness\n k11 = k_local[0:2, 0:2]\n k12 = k_local[0:2, 2:4]\n k13 = k_local[0:2, 4:6]\n k14 = k_local[0:2, 6:8]\n k21 = k_local[2:4, 0:2]\n k22 = k_local[2:4, 2:4]\n k23 = k_local[2:4, 4:6]\n k24 = k_local[2:4, 6:8]\n k31 = k_local[4:6, 0:2]\n k32 = k_local[4:6, 2:4]\n k33 = k_local[4:6, 4:6]\n k34 = k_local[4:6, 6:8]\n k41 = k_local[6:8, 0:2]\n k42 = k_local[6:8, 2:4]\n k43 = k_local[6:8, 4:6]\n k44 = k_local[6:8, 6:8]\n\n k_2_matrix = np.zeros((4*n_nodes, 4*n_nodes))\n\n # the additional terms for k_global are stored in k_2_matrix\n skip = 2*n_nodes\n k_2_matrix[node_i*2:node_i*2 + 2, node_i*2:node_i*2 + 2] = k11\n k_2_matrix[node_i*2:node_i*2 + 2, node_j*2:node_j*2 + 2] = k12\n k_2_matrix[node_j*2:node_j*2 + 2, node_i*2:node_i*2 + 2] = k21\n k_2_matrix[node_j*2:node_j*2 + 2, node_j*2:node_j*2 + 2] = k22\n\n k_2_matrix[skip + node_i*2:skip + node_i*2 + 2, skip + node_i*2:skip + node_i*2 + 2] = k33\n k_2_matrix[skip + node_i*2:skip + node_i*2 + 2, skip + node_j*2:skip + node_j*2 + 2] = k34\n k_2_matrix[skip + node_j*2:skip + node_j*2 + 2, skip + node_i*2:skip + node_i*2 + 2] = k43\n k_2_matrix[skip + node_j*2:skip + node_j*2 + 2, skip + node_j*2:skip + node_j*2 + 2] = k44\n\n k_2_matrix[node_i*2:node_i*2 + 2, skip + node_i*2:skip + node_i*2 + 2] = k13\n k_2_matrix[node_i*2:node_i*2 + 2, skip + node_j*2:skip + node_j*2 + 2] = k14\n k_2_matrix[node_j*2:node_j*2 + 2, skip + node_i*2:skip + node_i*2 + 2] = k23\n k_2_matrix[node_j*2:node_j*2 + 2, skip + node_j*2:skip + node_j*2 + 2] = k24\n\n k_2_matrix[skip + node_i*2:skip + node_i*2 + 2, node_i*2:node_i*2 + 2] = k31\n k_2_matrix[skip + node_i*2:skip + node_i*2 + 2, node_j*2:node_j*2 + 2] = k32\n k_2_matrix[skip + node_j*2:skip + node_j*2 + 2, node_i*2:node_i*2 + 2] = k41\n k_2_matrix[skip + node_j*2:skip + node_j*2 + 2, node_j*2:node_j*2 + 2] = k42\n k_global = k_global + k_2_matrix\n\n return k_global\n\n\ndef classify(props, nodes, elements, lengths, shapes, gbt_con, b_c, m_all, sect_props):\n # , clas_GDLO\n # MODAL CLASSIFICATION\n\n # input\n # props: [mat_num stiff_x stiff_y nu_x nu_y bulk] 6 x nmats\n # nodes: [nodes# x z dof_x dof_z dof_y dofrot stress] n_nodes x 8\n # elements: [elements# node_i node_j thick mat_num] n_elements x 5\n # lengths: lengths to be analyzed\n # shapes: array of mode shapes dof x lengths x mode\n # method:\n # method = 1 = vector norm\n # method = 2 = strain energy norm\n # method = 3 = work norm\n #\n #\n # output\n # clas: array or # classification\n\n # BWS August 29, 2006\n # modified SA, Oct 10, 2006\n # Z.Li, June 2010\n n_nodes = len(nodes)\n n_dof_m = 4*n_nodes\n\n # CLEAN UP INPUT\n # clean u_p 0's, multiple terms. or out-of-order terms in m_all\n m_all = pycufsm.analysis.m_sort(m_all)\n\n # FIND BASE PROPERTIES\n el_props = pycufsm.analysis.elem_prop(nodes=nodes, elements=elements)\n # set u_p stress to 1.0 for finding kg_global and k_global for axial modes\n nodes_base = deepcopy(nodes)\n nodes_base[:, 7] = np.ones_like(nodes[:, 7])\n\n # natural base first\n # properties all the longitudinal terms share\n [main_nodes, meta_elements, node_props, n_main_nodes, \\\n n_corner_nodes, n_sub_nodes, n_dist_modes, n_local_modes, dof_perm] \\\n = base_properties(nodes=nodes_base, elements=elements)\n [r_x, r_z, r_yd, r_ys, r_ud] = mode_constr(\n nodes=nodes_base,\n elements=elements,\n node_props=node_props,\n main_nodes=main_nodes,\n meta_elements=meta_elements\n )\n [d_y, n_global_modes] = y_dofs(\n nodes=nodes_base,\n elements=elements,\n main_nodes=main_nodes,\n n_main_nodes=n_main_nodes,\n n_dist_modes=n_dist_modes,\n r_yd=r_yd,\n r_ud=r_ud,\n sect_props=sect_props,\n el_props=el_props\n )\n\n # loop for the lengths\n n_lengths = len(lengths)\n l_i = 0 # length_index = one\n clas = []\n while l_i < n_lengths:\n length = lengths(l_i)\n # longitudinal terms included in the analysis for this length\n m_a = m_all[l_i]\n b_v_l = base_column(\n nodes_base=nodes_base,\n elements=elements,\n props=props,\n length=length,\n b_c=b_c,\n m_a=m_a,\n el_props=el_props,\n node_props=node_props,\n n_main_nodes=n_main_nodes,\n n_corner_nodes=n_corner_nodes,\n n_sub_nodes=n_sub_nodes,\n n_global_modes=n_global_modes,\n n_dist_modes=n_dist_modes,\n n_local_modes=n_local_modes,\n dof_perm=dof_perm,\n r_x=r_x,\n r_z=r_z,\n r_ys=r_ys,\n d_y=d_y\n )\n # orthonormal vectors\n b_v = base_update(\n gbt_con=gbt_con,\n b_v_l=b_v_l,\n length=length,\n m_a=m_a,\n nodes=nodes,\n elements=elements,\n props=props,\n n_global_modes=n_global_modes,\n n_dist_modes=n_dist_modes,\n n_local_modes=n_local_modes,\n b_c=b_c,\n el_props=el_props\n )\n\n # classification\n clas_modes = np.zeros((len(shapes([l_i][0])), 4))\n for mod in range(0, len(shapes[l_i][0])):\n clas_modes[mod, 0:4] = mode_class(\n b_v=b_v,\n displacements=shapes[l_i][:, mod],\n n_global_modes=n_global_modes,\n n_dist_modes=n_dist_modes,\n n_local_modes=n_local_modes,\n m_a=m_a,\n n_dof_m=n_dof_m,\n gbt_con=gbt_con\n )\n clas.append(clas_modes)\n l_i = l_i + 1 # length index = length index + one\n\n return clas\n\n\ndef mode_class(\n b_v, displacements, n_global_modes, n_dist_modes, n_local_modes, m_a, n_dof_m, gbt_con\n):\n #\n # to determine mode contribution in the current displacement\n\n # input data\n # b_v - base vectors (each column corresponds to a certain mode)\n # columns 1..n_global_modes: global modes\n # columns (n_global_modes+1)..(n_global_modes+n_dist_modes): dist. modes\n # columns (n_global_modes+n_dist_modes+1)\n # ..(n_global_modes+n_dist_modes+n_local_modes): local modes\n # columns (n_global_modes+n_dist_modes+n_local_modes+1)..n_dof: other modes\n # displacements - vector of nodal displacements\n # n_global_modes, n_dist_modes, n_local_modes\n # - number of global, distortional and local buckling modes, respectively\n # gbt_con['couple'] - by gbt_con, coupled basis vs uncoupled basis for general B.C.\n # especially for non-simply supported B.C.\n # 1: uncoupled basis, the basis will be block diagonal\n # 2: coupled basis, the basis is fully spanned\n\n # output data\n # clas_gdlo - array with the contributions of the modes in percentage\n # elem1: global, elem2: dist, elem3: local, elem4: other\n\n # S. Adany, Mar 10, 2004\n # Z. Li, June 2010\n\n total_m = len(m_a) # Total number of longitudinal terms m_i\n # indices\n dof_index = np.zeros((4, 2))\n dof_index[0, 0] = 0\n dof_index[0, 1] = n_global_modes\n dof_index[1, 0] = n_global_modes\n dof_index[1, 1] = n_global_modes + n_dist_modes\n dof_index[2, 0] = n_global_modes + n_dist_modes\n dof_index[2, 1] = n_global_modes + n_dist_modes + n_local_modes\n dof_index[3, 0] = n_global_modes + n_dist_modes + n_local_modes\n dof_index[3, 1] = n_dof_m\n\n if gbt_con['couple'] == 1:\n # uncoupled basis\n for i in range(0, len(m_a)):\n b_v_m = b_v[n_dof_m*i:n_dof_m*(i + 1), n_dof_m*i:n_dof_m*(i + 1)]\n\n # classification\n clas = np.linalg.lstsq(\n b_v_m[:, dof_index[0, 0]:dof_index[3, 1]], displacements[n_dof_m*i:n_dof_m*(i + 1)]\n )\n\n cl_gdlo = np.zeros((4, 5*n_modes))\n for j in range(0, 4):\n n_modes = dof_index[j, 1] - dof_index[i, 0]\n cl_gdlo[i, j*n_modes:j*n_modes + n_modes] = clas[dof_index[j, 0]:dof_index[j, 1]]\n\n # # L1 norm\n # for m_n = 1:4\n # clas_gdlo1(m_n) = sum(abs(cl_gdlo(m_n,:)))\n #\n # norm_sum = sum(clas_gdlo1)\n # clas_gdlo1 = clas_gdlo1/norm_sum*100\n\n # L2 norm\n for m_n in range(0, 4):\n clas_gdlo[m_n] = np.linalg.norm(cl_gdlo[m_n, :])\n\n norm_sum = sum(clas_gdlo)\n clas_gdlo = clas_gdlo/norm_sum*100\n else:\n # coupled basis\n # classification\n clas = np.linalg.lstsq(b_v, displacements)\n v_gdlo = np.zeros((4, (total_m + 1)*n_modes))\n for i in range(0, 4):\n for j in range(0, total_m):\n n_modes = dof_index[i, 2] - dof_index[i, 1] + 1\n v_gdlo[i, j*n_modes:j*n_modes+n_modes] \\\n = clas[j*n_dof_m + dof_index[i, 1]:j*n_dof_m + dof_index[i, 2]]\n\n # # L1 norm\n # clas_gdlo1(i) = sum(abs(v_gdlo(i,:)))\n # L2 norm\n clas_gdlo[i] = np.linalg.norm(v_gdlo[i, :])\n\n # # L1 norm\n # NormSum1 = sum(clas_gdlo1)\n # clas_gdlo1 = clas_gdlo1/NormSum1*100\n # L2 norm\n norm_sum = sum(clas_gdlo)\n clas_gdlo = clas_gdlo/norm_sum*100\n\n return clas_gdlo\n\n\ndef trans_single(alpha, k_local):\n #\n # this routine make the local-to-global co-ordinate transformation\n # basically it does the same as routine 'trans', however:\n # it does not care about kg_local (geom stiff matrix)\n # only involve one half-wave number m_i\n\n # S. Adany, Feb 06, 2004\n # Z. Li, Jul 10, 2009\n #\n gamma = np.array([[np.cos(alpha), 0, 0, 0, -np.sin(alpha), 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0],\n [0, 0, np.cos(alpha), 0, 0, 0, -np.sin(alpha), 0], [0, 0, 0, 1, 0, 0, 0, 0],\n [np.sin(alpha), 0, 0, 0, np.cos(alpha), 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0],\n [0, 0, np.sin(alpha), 0, 0, 0, np.cos(alpha), 0], [0, 0, 0, 0, 0, 0, 0, 1]])\n\n k_global = gamma @ k_local @ gamma.conj().T\n\n return k_global\n\n\ndef node_class(node_props):\n #this routine determines how many nodes of the various types exist\n #\n #input/output data\n # node_props - array of [original node nr, new node nr, nr of adj elems, node type]\n # nmno,ncno,nsno - number of main nodes, corner nodes and sub-nodes, respectively\n #\n #notes:\n # node types in node_props: 1-corner, 2-edge, 3-sub\n # sub-node numbers are the original one, of course\n #\n # S. Adany, Feb 09, 2004\n\n #to count corner-, edge- and sub-nodes\n n_corner_nodes = 0\n n_edge_nodes = 0\n n_sub_nodes = 0\n for n_prop in node_props:\n if n_prop[3] == 1:\n n_corner_nodes = n_corner_nodes + 1\n elif n_prop[3] == 2:\n n_edge_nodes = n_edge_nodes + 1\n elif n_prop[3] == 3:\n n_sub_nodes = n_sub_nodes + 1\n\n n_main_nodes = n_corner_nodes + n_edge_nodes #nr of main nodes\n\n return n_main_nodes, n_corner_nodes, n_sub_nodes\n","sub_path":"pycufsm/cfsm.py","file_name":"cfsm.py","file_ext":"py","file_size_in_byte":107704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"69435132","text":"\n\nfrom xai.brain.wordbase.nouns._sanctuary import _SANCTUARY\n\n#calss header\nclass _SANCTUARIES(_SANCTUARY, ):\n\tdef __init__(self,): \n\t\t_SANCTUARY.__init__(self)\n\t\tself.name = \"SANCTUARIES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"sanctuary\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_sanctuaries.py","file_name":"_sanctuaries.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"411276058","text":"from keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.layers import Activation, Dropout, Flatten, Dense\nfrom keras import backend as K\n\n\nclasses = 5\nepochs = 50\nbatch_size = 32\nimg_width, img_height = 200,200\nnb_train_samples = 500 # 5 classes\nnb_validation_samples = 150 # 5 classes\n\nmodel = Sequential()\nmodel.add(Conv2D(32, (3, 3), activation='relu', input_shape=(200, 200, 3)))\nmodel.add(Conv2D(32, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(128, (3, 3), activation='relu'))\nmodel.add(Conv2D(128, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu', name='fc1'))\nmodel.add(Dense(64, activation='relu', name='fc2'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(5, activation='softmax'))\nmodel.summary()\n\nmodel.compile(loss='categorical_crossentropy',\n optimizer='rmsprop',\n metrics=['accuracy'])\n\n\ntrain_data_dir = './data/train'\nvalidation_data_dir = './data/validation'\n\ntrain_datagen = ImageDataGenerator(\n rescale=2. / 255, #\n shear_range=0.2, #Shear angle in counter-clockwise direction as radians\n zoom_range=0.3, #[lower, upper] = [1-zoom_range, 1+zoom_range]\n rotation_range = 30,\n horizontal_flip=True)\n\ntest_datagen = ImageDataGenerator(\n zoom_range=0.3,\n rotation_range = 30,\n rescale=1. / 255)\n\n\ntrain_generator = train_datagen.flow_from_directory(\n\ttrain_data_dir,\n\ttarget_size=(img_width, img_height),\n\tbatch_size=batch_size,\n\t#save_to_dir='./data/new_data/train',\n\tclass_mode='categorical')\n\nvalidation_generator = test_datagen.flow_from_directory(\n\tvalidation_data_dir,\n\ttarget_size=(img_width, img_height),\n\tbatch_size=batch_size ,\n\t#save_to_dir='./data/new_data/test',\n\tclass_mode='categorical')\n\nmodel.fit_generator(\n\ttrain_generator,\n\tsteps_per_epoch= batch_size,\n\tepochs=epochs,\n\tvalidation_data=validation_generator,\n\tvalidation_steps=batch_size) \n\nmodel.save('multi-vgg.h5')\n","sub_path":"multi-vgg.py","file_name":"multi-vgg.py","file_ext":"py","file_size_in_byte":2204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"370318729","text":"# -*- coding: utf-8 -*-\n\nimport logging\nfrom datetime import datetime\n\nfrom shipane_sdk.market_utils import MarketUtils\n\n\nclass OnlineQuantFollowingJob(object):\n def __init__(self, shipane_client, quant_client, name=None):\n self._log = logging.getLogger()\n self._shipane_client = shipane_client\n self._quant_client = quant_client\n self._name = name\n self._start_datatime = datetime.now()\n self._processed_transactions = []\n\n def __call__(self):\n if MarketUtils.is_closed():\n self._log.warning(\"********** 休市期间不跟单 **********\")\n if self._processed_transactions:\n del self._processed_transactions[:]\n return\n\n if not self._quant_client.is_login():\n self._log.info(\"登录 {}\".format(self._quant_client.name))\n self._quant_client.login()\n\n self._log.info(\"********** 开始跟单 **********\")\n try:\n all_transactions = self._quant_client.query()\n self._log.info(\"获取到 {} 条委托\".format(len(all_transactions)))\n\n transactions = []\n for transaction in all_transactions:\n if self._is_expired(transaction):\n continue\n transactions.append(transaction)\n \n self._log.info(\"获取到 {} 条有效委托\".format(len(transactions)))\n\n for tx in transactions:\n self._processed_transactions.append(tx)\n self._log.info(\"开始以 {}元 {} {}股 {}\".format(tx.price, tx.get_cn_action(), tx.amount, tx.symbol))\n response = self._shipane_client.execute(None,\n action=tx.action,\n symbol=tx.symbol,\n type='LIMIT',\n price=tx.price,\n amount=tx.amount)\n if response is not None:\n self._log.info(u'实盘易回复:\\nstatus_code: %d\\ntext: %s', response.status_code, response.text)\n else:\n self._log.error('实盘易未回复')\n except Exception as e:\n self._log.exception(\"跟单异常\")\n self._log.info(\"********** 结束跟单 **********\\n\")\n\n @property\n def name(self):\n return self._name\n\n def _is_expired(self, transaction):\n if transaction.completed_at < self._start_datatime:\n return True\n if transaction in self._processed_transactions:\n return True\n return False\n","sub_path":"shipane_sdk/jobs/online_quant_following.py","file_name":"online_quant_following.py","file_ext":"py","file_size_in_byte":2714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"172668871","text":"'''\n\nYou are given n pairs of numbers.\nIn every pair, the first number is always smaller than the second number.\n\nNow, we define a pair (c, d) can follow another pair (a, b) if and only if b < c.\nChain of pairs can be formed in this fashion.\n\nGiven a set of pairs, find the length longest chain which can be formed.\nYou needn't use up all the given pairs. You can select pairs in any order.\n\nExample 1:\nInput: [[1,2], [2,3], [3,4]]\nOutput: 2\nExplanation: The longest chain is [1,2] -> [3,4]\nNote:\nThe number of given pairs will be in the range [1, 1000].\n'''\nimport operator\nclass Solution:\n def findLongestChain(self, pairs):\n \"\"\"\n :type pairs: List[List[int]]\n :rtype: int\n \"\"\"\n\n # pairs.sort()\n # dp = [1] * len(pairs)\n #\n # for j in range(len(pairs)):\n # for i in range(j):\n # if pairs[i][1] < pairs[j][0]:\n # dp[j] = max(dp[j], dp[i] + 1)\n #\n # return max(dp)\n\n cur, ans = float('-inf'), 0\n for x, y in sorted(pairs, key=operator.itemgetter(1)):\n if cur < x:\n cur = y\n ans += 1\n return ans\n\ns = Solution()\n\npairs = [[1,2], [2,3], [3,4], [5,18], [7,8], [9, 10]]\n\ns.findLongestChain(pairs)\n\n\n\n'''\nApproach #1: Dynamic Programming [Accepted]\nIntuition\n\nIf a chain of length k ends at some pairs[i], and pairs[i][1] < pairs[j][0], we can extend this chain to a chain of length k+1.\n\nAlgorithm\n\nSort the pairs by first coordinate, and let dp[i] be the length of the longest chain ending at pairs[i]. When i < j and pairs[i][1] < pairs[j][0], we can extend the chain, and so we have the candidate answer dp[j] = max(dp[j], dp[i] + 1).\n\n\nclass Solution(object): #Time Limit Exceeded\n def findLongestChain(self, pairs):\n pairs.sort()\n dp = [1] * len(pairs)\n\n for j in xrange(len(pairs)):\n for i in xrange(j):\n if pairs[i][1] < pairs[j][0]:\n dp[j] = max(dp[j], dp[i] + 1)\n\n return max(dp)\n\n\nComplexity Analysis\n\nTime Complexity: O(N^2)O(N\n​2\n​​ ) where NN is the length of pairs. There are two for loops, and N^2N\n​2\n​​ dominates the sorting step.\n\nSpace Complexity: O(N)O(N) for sorting and to store dp.\n\nApproach #2: Greedy [Accepted]\nIntuition\n\nWe can greedily add to our chain. Choosing the next addition to be the one with the lowest second coordinate is at least better than a choice with a larger second coordinate.\n\nAlgorithm\n\nConsider the pairs in increasing order of their second coordinate. We'll try to add them to our chain. If we can, by the above argument we know that it is correct to do so.\n\nclass Solution(object):\n def findLongestChain(self, pairs):\n cur, ans = float('-inf'), 0\n for x, y in sorted(pairs, key = operator.itemgetter(1)):\n if cur < x:\n cur = y\n ans += 1\n return ans\n\n\nComplexity Analysis\n\nTime Complexity: O(N \\log N)O(NlogN) where NN is the length of S. The complexity comes from the sorting step, but the rest of the solution does linear work.\n\nSpace Complexity: O(N)O(N). The additional space complexity of storing cur and ans, but sorting uses O(N)O(N) space. Depending on the implementation of the language used, sorting can sometimes use less space.\n\n'''","sub_path":"leetcode/646. Maximum Length of Pair Chain.py","file_name":"646. Maximum Length of Pair Chain.py","file_ext":"py","file_size_in_byte":3324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"42543726","text":"sample_input = \"\"\"5\n-\n-+\n+-\n+++\n--+-\n\"\"\"\n\nsample_output = \"\"\"Case #1: 1\nCase #2: 1\nCase #3: 2\nCase #4: 0\nCase #5: 3\n\"\"\"\n\n\ndef do_one(line):\n def process_one(prev_data, pancake):\n count, prev_pancake = prev_data\n if ((prev_pancake == '' and pancake == '+') or\n pancake == prev_pancake):\n return prev_data\n return (count + 1, pancake)\n\n return reduce(process_one, line[::-1], (0, ''))[0]\n","sub_path":"codes/CodeJamCrawler/16_0_2_neat/16_0_2_maxpblum_problem2.py","file_name":"16_0_2_maxpblum_problem2.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"445278905","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @File: _config.py\n# @Author: eswizardry\n# @Date: 2016-09-21 11:42:39\n# @Last Modified by: Bancha Rajainthong\n# @Last Modified time: 2016-09-25 15:54:52\n\nimport os\n\n# grab the folder where this scripts lives\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\nDATABASE = 'flasktaskr.db'\nCSRF_ENABLED = True\nSECRET_KEY = 'my_precious'\n\n# define the full path for the database\nDATABASE_PATH = os.path.join(basedir, DATABASE)\n\n# the database uri\nSQLALCHEMY_DATABASE_URI = 'sqlite:///' + DATABASE_PATH\n","sub_path":"project/_config.py","file_name":"_config.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"30832240","text":"from functools import wraps\nimport json\n\nfrom .elasticsearch5.exceptions import RequestError, NotFoundError\n\n\ndef getkv(d):\n return list(d.items())[0]\n\n\ndef error_handle(func):\n @wraps(func)\n def wrapped(*args, **kwargs):\n try:\n result = func(*args, **kwargs)\n\n if 'deleted' in result and result['total'] == result['deleted']:\n return {'status_code': 200}\n\n if 'acknowledged' in result or '_id' in result:\n return {'status_code': 200}\n\n # bulk\n if isinstance(result, tuple):\n if not result[1]:\n return {'status_code': 200}\n else:\n return {'error_msg': result[1]}\n\n return result\n except (RequestError, NotFoundError) as e:\n error_msg = e.error\n error_code = e.status_code\n\n try:\n # 处理根据id删除文档错误\n error_msg = json.loads(error_msg)\n if not error_msg['found'] and '_id' in error_msg:\n error_msg = 'document_missing_exception'\n except:\n pass\n\n return {'status_code': error_code, 'error_msg': error_msg}\n except:\n raise\n\n return wrapped\n","sub_path":"es_sql5/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"45062739","text":"import sys\nimport sqlalchemy as sql\nimport pandas as pd\n\nfrom schools3.config import base_config\nfrom schools3.config.data import db_config, db_tables\n\n\nconfig = base_config.Config()\n\ndef get_years_for_grade(grade):\n engine = sql.create_engine(db_config.engine_url)\n all_snapshots = db_tables.clean_all_snapshots_table\n\n query = sql.select([\n sql.distinct(all_snapshots.c.school_year)\n ]).where(\n all_snapshots.c.grade == grade\n ).order_by(\n all_snapshots.c.school_year\n )\n\n return pd.read_sql(query, engine).school_year.to_list()\n\n\nconfig.label_windows = {\n 9: 3,\n 10: 2,\n 11: 1\n}\n\nconfig.update_frequency = 1\n\nconfig.years_per_grade = {k: get_years_for_grade(k) for k in range(9, 12)}\n\nsys.modules[__name__] = config\n","sub_path":"schools3/config/data/datasets/datasets_generator_config.py","file_name":"datasets_generator_config.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"114218907","text":"\n\ndef main():\n argument_spec = purefa_argument_spec()\n argument_spec.update(dict(host=dict(type='str', required=True), state=dict(type='str', default='present', choices=['absent', 'present']), protocol=dict(type='str', default='iscsi', choices=['fc', 'iscsi', 'nvme', 'mixed']), nqn=dict(type='list'), iqn=dict(type='list'), wwns=dict(type='list'), volume=dict(type='str'), lun=dict(type='int'), personality=dict(type='str', default='', choices=['hpux', 'vms', 'aix', 'esxi', 'solaris', 'hitachi-vsp', 'oracle-vm-server', 'delete', '']), preferred_array=dict(type='list')))\n module = AnsibleModule(argument_spec, supports_check_mode=True)\n array = get_system(module)\n if ((_is_cbs(module, array) and module.params['wwns']) or module.params['nqn']):\n module.fail_json(msg='Cloud block Store only support iSCSI as a protocol')\n api_version = array._list_available_rest_versions()\n if ((module.params['nqn'] is not None) and (NVME_API_VERSION not in api_version)):\n module.fail_json(msg='NVMe protocol not supported. Please upgrade your array.')\n state = module.params['state']\n host = get_host(module, array)\n if (module.params['lun'] and (not (1 <= module.params['lun'] <= 4095))):\n module.fail_json(msg='LUN ID of {0} is out of range (1 to 4095)'.format(module.params['lun']))\n if module.params['volume']:\n try:\n array.get_volume(module.params['volume'])\n except Exception:\n module.fail_json(msg='Volume {0} not found'.format(module.params['volume']))\n if module.params['preferred_array']:\n try:\n if (module.params['preferred_array'] != ['delete']):\n all_connected_arrays = array.list_array_connections()\n if (not all_connected_arrays):\n module.fail_json(msg='No target arrays connected to source array. Setting preferred arrays not possible.')\n else:\n current_arrays = [array.get()['array_name']]\n for current_array in range(0, len(all_connected_arrays)):\n if (all_connected_arrays[current_array]['type'] == 'sync-replication'):\n current_arrays.append(all_connected_arrays[current_array]['array_name'])\n for array_to_connect in range(0, len(module.params['preferred_array'])):\n if (module.params['preferred_array'][array_to_connect] not in current_arrays):\n module.fail_json(msg='Array {0} is not a synchronously connected array.'.format(module.params['preferred_array'][array_to_connect]))\n except Exception:\n module.fail_json(msg='Failed to get existing array connections.')\n if ((host is None) and (state == 'present')):\n make_host(module, array)\n elif (host and (state == 'present')):\n update_host(module, array)\n elif (host and (state == 'absent')):\n delete_host(module, array)\n elif ((host is None) and (state == 'absent')):\n module.exit_json(changed=False)\n","sub_path":"Data Set/bug-fixing-1/42144204f3ba83c4ce68c049a34fb15554718057-
-fix.py","file_name":"42144204f3ba83c4ce68c049a34fb15554718057-
-fix.py","file_ext":"py","file_size_in_byte":3043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"83050145","text":"class Solution:\n def longestCommonSubsequence(self, text1: str, text2: str) -> int:\n if len(text1) == 0 or len(text2) == 0:\n return 0\n lcs = [[-1 for _ in range(len(text2)+1)] for _ in range(len(text1)+1)]\n for i in range(len(text1)+1):\n for j in range(len(text2)+1):\n if i==0 or j==0:\n lcs[i][j] = 0\n elif text1[i-1] == text2[j-1]:\n lcs[i][j] = lcs[i-1][j-1]+1\n else:\n lcs[i][j] = max(lcs[i][j-1], lcs[i-1][j])\n \n\n \n return lcs[len(text1)][len(text2)]\n \n ","sub_path":"leetcode/30-day-challenge/April_2020/26-Longest-Common-Subsequence.py","file_name":"26-Longest-Common-Subsequence.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"544532950","text":"# location/admin.py\nfrom django.contrib import admin\nfrom location.models import Location\n\n\nclass LocationAdmin(admin.ModelAdmin):\n list_display = ('name_location', 'modified_by', 'modified', 'created_by', 'created', 'is_active')\n search_fields = ('name_location',)\n# list_filter = ('modified', 'created')\n# date_hierarchy = 'modified'\n ordering = ['name_location']\n\nadmin.site.register(Location, LocationAdmin)\n\n","sub_path":"location/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"425103203","text":"\n\ndef ecritureFichier(htmlText, fileNameOutput):\n try: \n FileReport = open(fileNameOutput,\"w\")\n FileReport.write(\" \".join(htmlText))\n FileReport.close()\n except IOError:\n print(\"error while writing scan repport\")\n\n\n#creation d un rapport au format html\n\ndef generateReport(result, fileNameOutput):\n head = \" Scan Report

Scan Report

Total hosts : totalhosts Up hosts : uphosts


\"\n bottom = \"\t
\t
\t
\t
\t
\"\n templateMachine = \"

\t

Nmap scan report for NameMachine (IpMachine)

\t

Host is MachineState

Mac address : MacAdress

\t

PORT STATE SERVICE VERSION

\t
    \t#ici\t

\"\n templatePortText = \"
  • PortNumber PortState PortService PortSVersion
  • \"\n \n\n \n \n htmlText = list()\n \n uphosts=0\n totalhosts=0\n \n \n #on regarde dans le dictionnaire result les ips scannees et on complete les templates htmls\n try:\n for host in result:\n\n \n uphosts+=int(result[host]['res']['nmap']['scanstats']['uphosts'] )\n totalhosts+=int(result[host]['res']['nmap']['scanstats']['totalhosts'] ) \n \n for sousHost in result[host][\"res\"][\"scan\"]:\n \n \n temptemplateMachine = templateMachine.replace(\"NameMachine\", result[host][\"res\"][\"scan\"][sousHost][\"hostnames\"][0][\"name\"]+\" \"+result[host][\"res\"][\"scan\"][sousHost][\"hostnames\"][0][\"type\"] )\n temptemplateMachine = temptemplateMachine.replace(\"IpMachine\", sousHost)\n temptemplateMachine = temptemplateMachine.replace(\"MachineState\",result[host][\"res\"][\"scan\"][sousHost][\"status\"][\"state\"] + \" reason : \" + result[host][\"res\"][\"scan\"][sousHost][\"status\"][\"reason\"])\n if \"mac\" in result[host][\"res\"][\"scan\"][sousHost][\"addresses\"] and result[host][\"res\"][\"scan\"][sousHost][\"addresses\"][\"mac\"] != '':\n temptemplateMachine = temptemplateMachine.replace(\"MacAdress\", result[host][\"res\"][\"scan\"][sousHost][\"addresses\"][\"mac\"])\n else:\n temptemplateMachine = temptemplateMachine.replace(\"MacAdress\", \"Not found\")\n try:\n for port in result[host][\"res\"][\"scan\"][sousHost][\"tcp\"]: \n temptemplatePortText = templatePortText.replace(\"PortNumber\",str(port))\n temptemplatePortText=temptemplatePortText.replace(\"PortState\",result[host][\"res\"][\"scan\"][sousHost][\"tcp\"][port][\"state\"])\n temptemplatePortText=temptemplatePortText.replace(\"PortService\",result[host][\"res\"][\"scan\"][sousHost][\"tcp\"][port][\"name\"] + \" \" +result[host][\"res\"][\"scan\"][sousHost][\"tcp\"][port][\"product\"])\n temptemplatePortText=temptemplatePortText.replace(\"PortSVersion\",result[host][\"res\"][\"scan\"][sousHost][\"tcp\"][port][\"version\"]+\" \"+result[host][\"res\"][\"scan\"][sousHost][\"tcp\"][port][\"extrainfo\"])\n temptemplateMachine = temptemplateMachine.replace(\"#ici\t\", temptemplatePortText + \"#ici\t\")\n except Exception as ex:\n if 'tcp' not in result[host][\"res\"][\"scan\"][sousHost]:\n temptemplateMachine = temptemplateMachine.replace(\"#ici\t\", \"No open Ports\" ) \n # pas de ports ouverts pour un scan, c est normal \n pass\n temptemplateMachine = temptemplateMachine.replace(\"#ici\t\", \"\") \n htmlText.append(temptemplateMachine)\n \n except Exception as ex:\n print(\"error while reading scan results\") \n print(ex)\n\n htmlText.insert(0,head.replace(\"totalhosts\",str(totalhosts) ).replace(\"uphosts\",str(uphosts) ) )\n htmlText.append(bottom)\n ecritureFichier(htmlText, fileNameOutput)\n \n\n\n\n","sub_path":"report_generator.py","file_name":"report_generator.py","file_ext":"py","file_size_in_byte":4197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"392560304","text":"# Definition for a binary tree node.\nclass TreeNode(object):\n\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution(object):\n\n def DFS(self, node, pv, d):\n if not node:\n return\n\n if node.val - pv == 1:\n d += 1\n self.longest = max(self.longest, d)\n else:\n d = 1\n\n self.DFS(node.left, node.val, d)\n self.DFS(node.right, node.val, d)\n\n def longestConsecutive(self, root):\n self.longest = 1\n if not root:\n return 0\n self.DFS(root.left, root.val, 1)\n self.DFS(root.right, root.val, 1)\n return self.longest\n\n\ntestClass = Solution()\n\n\nHead = TreeNode(1)\nHead.right = TreeNode(3)\nHead.right.right = TreeNode(4)\nHead.right.right.right = TreeNode(5)\nHead.right.left = TreeNode(2)\n\n\nprint(testClass.longestConsecutive(Head))\n","sub_path":"298-binary-tree-longest-consecutive-sequence/298.py","file_name":"298.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"577492243","text":"#With GUI Support. Input the Image and enter the value to rescale the image.\r\nfrom tkinter import *\r\nfrom tkinter.filedialog import *\r\nfrom tkinter import messagebox\r\nfrom PIL import Image\r\n\r\n#-------------------------------------------------------------------------------------------------\r\nroot = Tk()\r\nroot.title(\"Image Size Reducer\")\r\n\r\n#List to hold the list of Images\r\nimage_list = []\r\nstrScaleValue = StringVar()\r\n#Global variable to hold the output directory\r\nglobal_outputFolder = \"\"\r\n#-------------------------------------------------------------------------------------------------\r\ndef browseImage():\r\n imageFiles = askopenfilenames(filetypes=(('Image File ', '*.JPEG *.JPG *.PNG *.GIF'), ('Other formats', '*.TIFF *.BMP')))\r\n for image in imageFiles:\r\n image_list.append(image)\r\n listbox.insert(END, image.split('/')[-1])\r\n\r\ndef setOutDir():\r\n global global_outputFolder\r\n global_outputFolder = askdirectory()\r\n\r\ndef resizeImage():\r\n try:\r\n if len(image_list) == 0:\r\n messagebox.showerror(\"Error\", \"No Image file found!\")\r\n elif (strScaleValue.get() == \"\" or int(strScaleValue.get()) < 5 or int(strScaleValue.get()) > 100):\r\n messagebox.showerror(\"Error\", \"Enter the Resize value between 5 and 100\")\r\n else:\r\n global global_outputFolder\r\n if global_outputFolder == \"\":\r\n messagebox.showerror(\"Error\", \"Output Folder not Set!\")\r\n else:\r\n fun_Resize()\r\n except:\r\n messagebox.showerror(\"Exception\", \"Error:{0} and {1}\".format(sys.exc_info()[0].__name__, sys.exc_info()[1]))\r\n\r\ndef fun_Resize():\r\n for image in image_list:\r\n outputImagefile = global_outputFolder + '/'+ \"Resize_\" + image.split('/')[-1]\r\n #Image below is imported from PIL library\r\n imagePath = Image.open(image)\r\n imagePath.save(outputImagefile,optimize=True,quality=int(strScaleValue.get()))\r\n imagePath.close()\r\n messagebox.showinfo(\"Files Saved\",\"All the scaled files are saved at : \"+global_outputFolder )\r\n root.quit()\r\n#-------------------------------------------------------------------------------------------------\r\nLabel(root, width= \"20\", text=\"IMAGE SCALER\").grid(row=0, column=1, columnspan=4)\r\nButton(root, width=\"25\", height=\"2\",text=\"Browse and Add Image file\", command = browseImage, bg=\"lightblue\").grid(row=1,column=0,columnspan=2)\r\n\r\nlistbox = Listbox(root, width=\"30\", height=\"20\")\r\nlistbox.bind('<>')\r\nlistbox.grid(row=2, rowspan=4, column=0, columnspan=2)\r\n\r\nButton(root, width=\"20\", height=\"2\",text=\"Set Output Folder\", command = setOutDir).grid(row=1,column=3,columnspan=4)\r\nLabel(root, width=\"40\", wraplength=\"150\",text=\"Enter Value to Resize.\\n (Between 5 & 100).\\n\"\r\n \"5-> Lesser Size/Poor Quality.\\n 100-> Higher size/Good Quality.\").grid(row=2, rowspan=2,column=3, columnspan=4, sticky=\"n,s,e,w\")\r\n\r\nEntry(root, textvariable = strScaleValue, width=\"23\").grid(row=3, column = 3, columnspan=5, sticky=\"s\")\r\n\r\nButton(root, width=\"20\", height=\"2\", text=\"Resize Images\", command= resizeImage, bg=\"lightblue\").grid(row=5, column = 3, columnspan=5)\r\n#-------------------------------------------------------------------------------------------------\r\n\r\nfor child in root.winfo_children():\r\n child.grid_configure(padx=5, pady=5)\r\nmainloop()\r\n","sub_path":"ImageResizer/MultipleImageScaler.py","file_name":"MultipleImageScaler.py","file_ext":"py","file_size_in_byte":3353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"593679310","text":"from array import array\nfrom random import random\n\n# write 10 million numbers to the binary file\nfloats = array('d', (random() for i in range(10 ** 7)))\nfloats[-1] # 0.07802343889111107\nfp = open('floats.bin', 'wb')\nfloats.tofile(fp)\nfp.close()\n\n# read 10 million numbers from the binary file\nfloats2 = array('d')\nfp = open('floats.bin', 'rb')\nfloats2.fromfile(fp, 10 ** 7)\nfp.close()\n\nfloats2[-1] # 0.07802343889111107 # the content is matched\nfloats2 == floats # True\n\n\"\"\"\nAs you can see, array.tofile and array.fromfile are easy to use.\nIf you try the example, you’ll notice they are also very fast. A quick experiment show that it takes about 0.1s for array.fromfile to load 10 million double-precision floats from a binary file created with array.tofile. That is nearly 60 times faster than reading the numbers from a text file, which also involves parsing each line with the float built-in.\nSaving with array.tofile is about 7 times faster than writing one float per line in a text file.\nIn addition, the size of the binary file with 10 million doubles is 80,000,000 bytes (8 bytes per double, zero overhead), while the text file has 181,515,739 bytes, for the same data.\n\"\"\"\n","sub_path":"src/library_ref/data_type/array/array_basic.py","file_name":"array_basic.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"2280816","text":"# -------------------------------------------------------------------------- #\n# Copyright 2010-2011, University of Chicago #\n# #\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may #\n# not use this file except in compliance with the License. You may obtain #\n# a copy of the License at #\n# #\n# http://www.apache.org/licenses/LICENSE-2.0 #\n# #\n# Unless required by applicable law or agreed to in writing, software #\n# distributed under the License is distributed on an \"AS IS\" BASIS, #\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #\n# See the License for the specific language governing permissions and #\n# limitations under the License. #\n# -------------------------------------------------------------------------- #\n\n\"\"\"\nContains the parsers for the two configuration files used in Globus Provision:\n\n* The instance configuration file (GPConfig): This is the configuration file\n that specifies options related to an instance's deploymenr.\n \n* The simple topology file: This is a simple format for specifying topologies\n (which internally translated to the topology JSON format). It has the\n format of a configuration file although, strictly speaking, it is *not*\n a configuration file. \n\n\"\"\"\n\nfrom globus.provision.core.topology import Domain, User, Node, Topology,\\\n DeployData, EC2DeployData, GridMapEntry, GOEndpoint\nfrom globus.provision.common.config import Config, Section, Option, OPTTYPE_INT, OPTTYPE_FLOAT, OPTTYPE_STRING, OPTTYPE_BOOLEAN, OPTTYPE_FILE\nimport os.path\nimport getpass\n\nclass GPConfig(Config):\n \"\"\"\n The instance configuration file.\n \"\"\"\n\n sections = [] \n \n # ============================= #\n # #\n # GENERAL OPTIONS #\n # #\n # ============================= # \n \n general = Section(\"general\", required=True,\n doc = \"This section is used for general options affecting Globus Provision as a whole.\")\n general.options = \\\n [\n Option(name = \"ca-cert\",\n getter = \"ca-cert\",\n type = OPTTYPE_FILE,\n required = False,\n doc = \"\"\"\n Location of CA certificate (PEM-encoded) used to generate user\n and host certificates. If blank, Globus Provision will generate a self-signed\n certificate from scratch. \n \"\"\"), \n Option(name = \"ca-key\",\n getter = \"ca-key\",\n type = OPTTYPE_FILE,\n required = False,\n doc = \"\"\"\n Location of the private key (PEM-encoded) for the certificate\n specified in ``ca-cert``.\n \"\"\"),\n Option(name = \"ca-dn\",\n getter = \"ca-dn\",\n type = OPTTYPE_STRING,\n required = False,\n doc = \"\"\"\n Distinguished Name of the certificates that will be signed with \n the CA certificate specified in ``ca-cert``. \n \n For example, if you set this value to ``O=Foo, OU=Bar``, the certificates\n will have subjects like ``/O=Foo/OU=Bar/CN=borja``, ``/O=Foo/OU=Bar/CN=host/foo.example.org``, etc.\n \"\"\"), \n Option(name = \"scratch-dir\",\n getter = \"scratch-dir\",\n type = OPTTYPE_STRING,\n required = False,\n default = \"/var/tmp\",\n doc = \"\"\"\n Scratch directory that Chef will use (on the provisioned machines)\n while configuring them.\n \"\"\"),\n Option(name = \"deploy\",\n getter = \"deploy\",\n type = OPTTYPE_STRING,\n required = True,\n valid = [\"ec2\", \"dummy\"],\n doc = \"\"\"\n Globus Provision can support various \"deployers\" that are used to\n deploy the hosts in a topology. Two deployers are currently supported:\n \n * ``ec2``: Hosts are deployed as Amazon EC2 instances.\n * ``dummy``: Hosts are not actually deployed and are assigned dummy\n hostnames and IP addresses.\n \n See the Globus Provision documentation for more details on the\n available deployers.\n \"\"\") \n ]\n\n sections.append(general)\n\n # ====================== #\n # #\n # EC2 OPTIONS #\n # #\n # ====================== #\n\n ec2 = Section(\"ec2\", required=False,\n required_if = [((\"general\",\"deploy\"),\"ec2\")],\n doc = \"\"\"\n When the EC2 deployer is selected, Globus Provision will need certain information about\n your EC2 account to be able to request EC2 instances on which to deploy your topology. This account\n information is specified in this section of the configuration file. If you are unclear on what values\n you need to specify here, see :ref:`chap_ec2` for more detailed instructions (including how to set up\n an Amazon EC2 account)\"\"\")\n ec2.options = \\\n [ \n Option(name = \"keypair\",\n getter = \"ec2-keypair\",\n type = OPTTYPE_STRING,\n required = True,\n doc = \"\"\"\n The *name* of the Amazon EC2 keypair you will use to log into the VMs.\n See :ref:`chap_ec2` for instructions on how to obtain this keypair.\n \"\"\"),\n Option(name = \"keyfile\",\n getter = \"ec2-keyfile\",\n type = OPTTYPE_FILE,\n required = True,\n doc = \"\"\"\n The actual location of the keypair on your local filesystem.\n See :ref:`chap_ec2` for instructions on how to obtain this keypair.\n \"\"\"),\n Option(name = \"username\",\n getter = \"ec2-username\",\n type = OPTTYPE_STRING,\n required = True,\n doc = \"\"\"\n The username that Globus Provision will use to connect to the EC2 instances,\n using the keypair specified in ``keypair``. If you are using one of the\n Globus Provision AMIs, you need to set this value to ``ubuntu``.\n \"\"\"), \n Option(name = \"server-hostname\",\n getter = \"ec2-server-hostname\",\n type = OPTTYPE_STRING,\n required = False,\n doc = \"\"\"\n The hostname of the EC2 server. If you are using Amazon AWS, leave this option\n unspecified. If you are using an EC2-compatible system, such as OpenNebula, Nimbus,\n Eucalyptus, etc. set this to the server running that system's EC2 interface.\n \"\"\"),\n Option(name = \"server-port\",\n getter = \"ec2-server-port\",\n type = OPTTYPE_INT,\n required = False,\n doc = \"\"\"\n The TCP port of the EC2 server. If you are using Amazon AWS, leave this option\n unspecified. If you are using an EC2-compatible system, such as OpenNebula, Nimbus,\n Eucalyptus, etc. set this to the port on which that system's EC2 interface is listening on.\n \"\"\"),\n Option(name = \"server-path\",\n getter = \"ec2-server-path\",\n type = OPTTYPE_STRING,\n required = False,\n doc = \"\"\"\n The path portion of the EC2 server. If you are using Amazon AWS, leave this option\n unspecified. If you are using an EC2-compatible system, such as OpenNebula, OpenStack,\n Eucalyptus, etc. set this to the path (in the host specified in ``server-hostname``)\n that the system's EC2 interface is available on.\n \"\"\") \n ] \n sections.append(ec2)\n\n # ================================ #\n # #\n # GLOBUS ONLINE OPTIONS #\n # #\n # ================================ #\n\n go = Section(\"globusonline\", required=False,\n doc = \"\"\"\n When a topology includes Globus Online transfer endpoints, Globus Provision will\n use GO's API to set up those endpoints. To do so, it will need some information\n about your GO account. If you are unclear on what values you need to specify here, \n see :ref:`chap_go` for more detailed instructions.\n \"\"\")\n go.options = \\\n [ \n Option(name = \"ssh-key\",\n getter = \"go-ssh-key\",\n type = OPTTYPE_FILE,\n default = \"~/.ssh/id_rsa\", \n required = False,\n doc = \"\"\"\n SSH key to use when connecting to the Globus Online CLI. The public key\n for this SSH key must have been previously added to your Globus Online\n profile.\n \"\"\"), \n Option(name = \"cert-file\",\n getter = \"go-cert-file\",\n type = OPTTYPE_FILE,\n required = False,\n doc = \"\"\"\n When this option is specified, Globus Provision will access your GO\n account using Globus Online's Transfer API (instead of sending commands\n to Globus Online's CLI via SSH). To do so, Globus Provision needs the\n location of a user certificate (PEM-encoded) that is authorized to access \n the accounts specified in your topology's endpoints.\n \n See :ref:`chap_go` for more details on the differences between using the\n Transfer API, instead of the CLI via SSH.\n \"\"\"), \n Option(name = \"key-file\",\n getter = \"go-key-file\",\n type = OPTTYPE_FILE,\n required = False,\n doc = \"\"\"\n Location of the private key (PEM-encoded) for the certificate\n specified in ``cert-file``.\n \"\"\"), \n Option(name = \"server-ca-file\",\n getter = \"go-server-ca-file\",\n type = OPTTYPE_STRING,\n required = False,\n doc = \"\"\"\n To verify the server certificate of the Globus Online Transfer API server,\n Globus Provision needs the certificate of the CA that signed that certificate.\n This file is already bundled with Globus Provision. The only reason for using\n this option to specify a different CA certificate is in the unlikely case that\n the API server decides to switch to a different CA (and the file bundled\n with Globus Provision has not been updated to that CA yet).\n \"\"\")\n ] \n sections.append(go)\n \n def __init__(self, config_file):\n Config.__init__(self, config_file, self.sections)\n\n\nclass SimpleTopologyConfig(Config):\n \"\"\"\n The simple topology file\n \"\"\" \n \n sections = [] \n \n # ============================= #\n # #\n # GENERAL OPTIONS #\n # #\n # ============================= # \n \n general = Section(\"general\", required=True,\n doc = \"This section is used for general options affecting all the topology.\")\n general.options = \\\n [ \n Option(name = \"domains\",\n getter = \"domains\",\n type = OPTTYPE_STRING,\n required = True,\n doc = \"\"\"\n The names of the domains you are defining in this topology. They must each be separated by\n a single space. \n \"\"\"), \n Option(name = \"deploy\",\n getter = \"deploy\",\n type = OPTTYPE_STRING,\n required = True,\n valid = [\"ec2\", \"dummy\"],\n doc = \"\"\"\n See the :ref:`deploy option ` in :ref:`chap_config_ref` \n \"\"\"),\n Option(name = \"ssh-pubkey\",\n getter = \"ssh-pubkey\",\n type = OPTTYPE_FILE,\n required = False,\n default = \"~/.ssh/id_rsa.pub\",\n doc = \"\"\"\n When creating users, an SSH public key must be added to their ``authorized_keys`` file\n to allow the creator of the topology to log in as those users. When using a topology file,\n each SSH key is specified separately for each user; in a simple topology, you can specify\n a single SSH public key for all the users (by default, the SSH key of the topology's creator \n will be used)\n \n Take into account that you *can* specify per-user SSH keys in a simple topology by using the\n :ref:`users-file option`.\n \"\"\") \n ] \n \n sections.append(general)\n \n domain = Section(\"domain\", required=False, multiple=(\"general\", \"domains\"),\n doc = \"\"\"\n For each domain specified in the ``domains`` option, you will need to specify a section\n titled ``[domain-DDD]`` where ``DD`` is the name of the domain. For example, if you specify the following::\n \n [general]\n domains: foo bar\n \n You will need to specify the following sections::\n \n [domain-foo]\n ...\n \n [domain-bar]\n ...\n \n Each section provides a few high-level options about each domain.\n This provides a simple, but constrained, way of specifying what services and users\n should be created in each domain. For more complex topologies, you may have\n to write a regular :ref:`topology file `. \n \"\"\")\n domain.options = \\\n [ \n Option(name = \"users\",\n getter = \"users\",\n type = OPTTYPE_STRING,\n required = False,\n default = \"0\",\n doc = \"\"\"\n This option can be either a number, or a list of usernames separated by spaces.\n \n If a number is specified, the users will be named ``D-userN``, where ``D`` is the\n domain name and ``N`` is a number between 1 and the number specified in this option.\n \n If a list of usernames is specified, users with those login names will be created.\n \n These users will be created with corresponding user certificates. To create users without user certificates\n use option ``users-no-cert``. \n \"\"\"), \n Option(name = \"users-no-cert\",\n getter = \"users-no-cert\",\n type = OPTTYPE_STRING,\n default = \"0\",\n required = False,\n doc = \"\"\"\n Same as ``users`` but creating users without certificates.\n \n Note that if you specify a number for *both* the ``users`` and ``users-no-cert`` option \n (with values N and M, respectively), the first N users will have certificates, and the \n remaining M will not. \n \"\"\"), \n Option(name = \"users-file\",\n getter = \"users-file\",\n type = OPTTYPE_FILE,\n required = False,\n doc = \"\"\"\n The path to a file with a specification of the users to create in this domain. This file will have one line\n per user, each with three fields (separated by whitespace):\n \n #. A single character, ``C`` or ``N``. If ``C`` is specified, the user will have a user certificate created\n for it. Otherwise, it will nor.\n #. The user's UNIX login name.\n #. (Optional) An SSH public key to add to the user's ``authorized_keys`` file. If not specified, the public\n key specified in :ref:`option ssh-pubkey` will be used.\n \n For example::\n \n C borja ssh-rsa FOOFOOFOO...BARBARBAR borja@example.org\n C childers ssh-rsa FOOFOOFOO...BARBARBAR childers@example.org\n N foster\n N madduri\n \n \"\"\"), \n Option(name = \"nfs-nis\",\n getter = \"nfs-nis\",\n type = OPTTYPE_BOOLEAN,\n required = False,\n default = False,\n doc = \"\"\"\n Specifies whether an NFS/NIS server should be setup in this domain. When ``True``, there will be a global\n filesystem and global user account space in the domain. Most notably, the users' home directories will be on an\n NFS directory, which means they will be able to access the same home directory from any host in the domain\n (as opposed to having separate home directories in each host).\n \n When ``False``, user accounts and home directories will be created on every individual host. This option can\n be useful if you are creating a single-host domain. \n \"\"\"), \n Option(name = \"login\",\n getter = \"login\",\n type = OPTTYPE_BOOLEAN,\n required = False,\n default = False,\n doc = \"\"\"\n Specifies whether a separate \"login node\" should be created in the topology. This option can be useful if you\n want a distinct node that users can log into but that does not host one of the topology's servers (like the NFS\n server, a GridFTP server, etc.) \n \"\"\"),\n Option(name = \"myproxy\",\n getter = \"myproxy\",\n type = OPTTYPE_BOOLEAN,\n required = False,\n default = False,\n doc = \"\"\"\n Specifies whether to set up a MyProxy server on this domain. \n \"\"\"), \n Option(name = \"gram\",\n getter = \"gram\",\n type = OPTTYPE_BOOLEAN,\n required = False,\n default = False,\n doc = \"\"\"\n Specifies whether to set up a GRAM5 server on this domain. \n \"\"\"), \n Option(name = \"gridftp\",\n getter = \"gridftp\",\n type = OPTTYPE_BOOLEAN,\n required = False,\n default = False,\n doc = \"\"\"\n Specifies whether to set up a GridFTP server on this domain. \n \"\"\"), \n Option(name = \"lrm\",\n getter = \"lrm\",\n type = OPTTYPE_STRING,\n valid = [\"none\", \"condor\"],\n default = \"none\",\n required = False,\n doc = \"\"\"\n Specifies whether to set up an LRM (Local Resource Manager) on this domain. Currently, only \n `Condor `_ is supported. \n \"\"\"), \n Option(name = \"cluster-nodes\",\n getter = \"cluster-nodes\",\n type = OPTTYPE_INT,\n required = False,\n doc = \"\"\"\n The number of worker nodes to create for the LRM. \n \"\"\"), \n Option(name = \"galaxy\",\n getter = \"galaxy\",\n type = OPTTYPE_BOOLEAN,\n required = False,\n default = False,\n doc = \"\"\"\n Specifies whether to set up a Galaxy server on this domain. \n \"\"\"), \n Option(name = \"go-endpoint\",\n getter = \"go-endpoint\",\n type = OPTTYPE_STRING,\n required = False,\n doc = \"\"\"\n If this domain has a GridFTP server, it can be configured as a GO endpoint.\n The format for this option is # (e.g., johnsmith#test-ep).\n Take into account that you must be authorized to use the GO account for ,\n and that you must specify the appropriate credentials in the \n :ref:`[globusonline] section` of the configuration file.\n \n See :ref:`chap_go` for more details. \n \"\"\")\n, \n Option(name = \"go-auth\",\n getter = \"go-auth\",\n type = OPTTYPE_STRING,\n required = False,\n valid = [\"myproxy\", \"go\"], \n doc = \"\"\"\n The authentication method that Globus Online will use when contacting the endpoint on\n behalf of a user. The valid options are:\n \n * ``myproxy``: Contact the MyProxy server specified in the topology. Note that \n the :ref:`myproxy option` must be set to ``true`` \n for this to work\n * ``go``: Use Globus Online authentication.\n \n See :ref:`chap_go`, and specifically :ref:`Globus Online Authentication Methods `,\n for more details on the implications of each authentication method. \n \"\"\") \n ] \n sections.append(domain)\n \n ec2 = Section(\"ec2\", required=False,\n required_if = [((\"general\",\"deploy\"),\"ec2\")],\n doc = \"\"\"\n When the EC2 deployer is selected, this section will allow you to\n specify EC2 deployment options that are specific to this topology.\"\"\") \n ec2.options = \\\n [ \n Option(name = \"ami\",\n getter = \"ec2-ami\",\n type = OPTTYPE_STRING,\n required = True,\n doc = \"\"\"\n This is the AMI (`Amazon Machine Image `_) \n that Globus Provision will use to create each host in the domani. Any recent Ubuntu or Debian\n AMI should work. Nonetheless, take into account that we provide an AMI that has most of the\n necessary software pre-installed in it, considerably speeding up the setup of the machines. \n The latest Globus Provision AMI is always listed in the Globus Provision website.\n \"\"\"),\n Option(name = \"instance-type\",\n getter = \"ec2-instance-type\",\n type = OPTTYPE_STRING,\n required = True,\n default = \"t1.micro\",\n doc = \"\"\"\n This is the `EC2 instance type `_ that will\n be used to launch the machines in this domain. The default is to use micro-instances (t1.micro),\n which tend to be enough if you are just tinkering around.\n \"\"\"), \n Option(name = \"availability-zone\",\n getter = \"ec2-availability-zone\",\n type = OPTTYPE_STRING,\n required = False,\n default = None,\n doc = \"\"\"\n The `availability zone `_ \n you want the VMs to be deployed in. \n Unless you have a good reason for choosing a specific availability zone,\n you should let Globus Provision choose a default zone for you.\n \"\"\") \n ] \n sections.append(ec2) \n \n def __init__(self, configfile):\n Config.__init__(self, configfile, self.sections)\n\n def to_topology(self):\n ssh_pubkeyf = os.path.expanduser(self.get(\"ssh-pubkey\"))\n ssh_pubkeyf = open(ssh_pubkeyf)\n ssh_pubkey = ssh_pubkeyf.read().strip()\n ssh_pubkeyf.close() \n \n topology = Topology()\n \n if self.get(\"deploy\") == \"dummy\":\n # No default deploy data\n pass\n elif self.get(\"deploy\") == \"ec2\":\n deploy_data = DeployData()\n ec2_deploy_data = EC2DeployData()\n \n ec2_deploy_data.set_property(\"ami\", self.get(\"ec2-ami\"))\n ec2_deploy_data.set_property(\"instance_type\", self.get(\"ec2-instance-type\"))\n \n deploy_data.set_property(\"ec2\", ec2_deploy_data)\n topology.set_property(\"default_deploy_data\", deploy_data)\n \n domains = self.get(\"domains\").split()\n for domain_name in domains:\n domain = Domain()\n domain.set_property(\"id\", domain_name)\n topology.add_to_array(\"domains\", domain)\n\n user = User()\n user.set_property(\"id\", getpass.getuser())\n user.set_property(\"password_hash\", \"!\")\n user.set_property(\"certificate\", \"generated\")\n user.set_property(\"admin\", True)\n user.set_property(\"ssh_pkey\", ssh_pubkey)\n domain.add_user(user) \n\n usersfile = self.get((domain_name, \"users-file\"))\n \n if usersfile != None:\n usersfile = open(usersfile, \"r\")\n \n for line in usersfile:\n fields = line.split()\n type = fields[0]\n username = fields[1]\n if len(fields) >= 3:\n user_ssh_pubkey = \" \".join(fields[2:])\n else:\n user_ssh_pubkey = ssh_pubkey\n \n user = User()\n user.set_property(\"id\", username)\n user.set_property(\"password_hash\", \"!\")\n user.set_property(\"ssh_pkey\", user_ssh_pubkey)\n if type == \"C\":\n user.set_property(\"certificate\", \"generated\")\n else:\n user.set_property(\"certificate\", \"none\")\n \n domain.add_user(user)\n \n usersfile.close()\n else:\n users = self.get((domain_name, \"users\"))\n users_nocert = self.get((domain_name, \"users-no-cert\"))\n \n if users.isdigit():\n num_users = int(users)\n usernames = [(\"%s-user%i\" % (domain_name, i), True) for i in range(1,num_users + 1)]\n else:\n num_users = 0\n usernames = [(u, True) for u in users.split() if u != getpass.getuser()]\n \n if users_nocert.isdigit():\n usernames += [(\"%s-user%i\" % (domain_name, i), False) for i in range(num_users + 1,num_users + int(users_nocert) + 1)]\n else:\n usernames += [(u, False) for u in users_nocert.split() if u != getpass.getuser()] \n\n for username, cert in usernames:\n user = User()\n user.set_property(\"id\", username)\n user.set_property(\"password_hash\", \"!\")\n user.set_property(\"ssh_pkey\", ssh_pubkey)\n if cert:\n user.set_property(\"certificate\", \"generated\")\n else:\n user.set_property(\"certificate\", \"none\")\n domain.add_user(user)\n \n for user in domain.users.values():\n gme = GridMapEntry()\n gme.set_property(\"dn\", \"/O=Grid/OU=Globus Provision (generated)/CN=%s\" % user.id)\n gme.set_property(\"login\", user.id)\n domain.add_to_array(\"gridmap\", gme) \n if self.get((domain_name,\"go-auth\")) == \"go\":\n gme = GridMapEntry()\n gme.set_property(\"dn\", \"/C=US/O=Globus Consortium/OU=Globus Connect User/CN=%s\" % user.id)\n gme.set_property(\"login\", user.id)\n domain.add_to_array(\"gridmap\", gme) \n \n \n if self.get((domain_name,\"nfs-nis\")): \n server_node = Node()\n server_name = \"%s-server\" % domain_name\n server_node.set_property(\"id\", server_name)\n server_node.add_to_array(\"run_list\", \"role[domain-nfsnis]\")\n if not self.get((domain_name,\"login\")):\n # If there is no login node, the NFS/NIS server will\n # effectively act as one. \n server_node.add_to_array(\"run_list\", \"role[globus]\")\n if self.get((domain_name,\"galaxy\")):\n # If there is a Galaxy server in the domain, the \"common\"\n # recipe has to be installed on the NFS/NIS server\n server_node.add_to_array(\"run_list\", \"recipe[galaxy::galaxy-globus-common]\")\n \n domain.add_node(server_node)\n\n if self.get((domain_name,\"login\")): \n login_node = Node()\n login_node.set_property(\"id\", \"%s-login\" % domain_name)\n if self.get((domain_name,\"nfs-nis\")): \n login_node.set_property(\"depends\", \"node:%s\" % server_name)\n login_node.add_to_array(\"run_list\", \"role[domain-nfsnis-client]\")\n else:\n login_node.add_to_array(\"run_list\", \"recipe[provision::domain_users]\")\n login_node.add_to_array(\"run_list\", \"role[globus]\")\n domain.add_node(login_node) \n\n if self.get((domain_name,\"myproxy\")):\n myproxy_node = Node()\n myproxy_node.set_property(\"id\", \"%s-myproxy\" % domain_name)\n if self.get((domain_name,\"nfs-nis\")): \n myproxy_node.set_property(\"depends\", \"node:%s\" % server_name)\n myproxy_node.add_to_array(\"run_list\", \"role[domain-nfsnis-client]\")\n else:\n myproxy_node.add_to_array(\"run_list\", \"recipe[provision::domain_users]\")\n myproxy_node.add_to_array(\"run_list\", \"role[domain-myproxy]\")\n domain.add_node(myproxy_node)\n\n if self.get((domain_name,\"gridftp\")):\n gridftp_node = Node()\n gridftp_node.set_property(\"id\", \"%s-gridftp\" % domain_name)\n if self.get((domain_name,\"nfs-nis\")): \n gridftp_node.set_property(\"depends\", \"node:%s\" % server_name)\n gridftp_node.add_to_array(\"run_list\", \"role[domain-nfsnis-client]\")\n else:\n gridftp_node.add_to_array(\"run_list\", \"recipe[provision::domain_users]\") \n if self.get((domain_name,\"go-endpoint\")) != None:\n gridftp_node.add_to_array(\"run_list\", \"recipe[globus::go_cert]\")\n gridftp_node.add_to_array(\"run_list\", \"role[domain-gridftp]\")\n domain.add_node(gridftp_node) \n \n if self.get((domain_name,\"galaxy\")):\n galaxy_node = Node()\n galaxy_node.set_property(\"id\", \"%s-galaxy\" % domain_name)\n\n if self.get((domain_name,\"nfs-nis\")): \n galaxy_node.set_property(\"depends\", \"node:%s\" % server_name)\n galaxy_node.add_to_array(\"run_list\", \"role[domain-nfsnis-client]\")\n else:\n galaxy_node.add_to_array(\"run_list\", \"recipe[provision::domain_users]\") \n galaxy_node.add_to_array(\"run_list\", \"recipe[galaxy::galaxy-globus-common]\") \n\n if self.get((domain_name,\"go-endpoint\")) != None:\n galaxy_node.add_to_array(\"run_list\", \"recipe[globus::go_cert]\")\n galaxy_node.add_to_array(\"run_list\", \"recipe[galaxy::galaxy-globus]\")\n domain.add_node(galaxy_node) \n \n \n lrm = self.get((domain_name,\"lrm\"))\n if lrm != \"none\":\n gram = self.get((domain_name,\"gram\"))\n if lrm == \"condor\":\n if gram:\n node_name = \"%s-gram-condor\" % domain_name\n role = \"role[domain-gram-condor]\"\n else:\n node_name = \"%s-condor\" % domain_name\n role = \"role[domain-condor]\"\n workernode_role = \"role[domain-clusternode-condor]\"\n\n lrm_node = Node()\n lrm_node.set_property(\"id\", node_name)\n if self.get((domain_name,\"nfs-nis\")): \n lrm_node.set_property(\"depends\", \"node:%s\" % server_name)\n lrm_node.add_to_array(\"run_list\", \"role[domain-nfsnis-client]\")\n else:\n lrm_node.add_to_array(\"run_list\", \"recipe[provision::domain_users]\") \n lrm_node.add_to_array(\"run_list\", role)\n domain.add_node(lrm_node)\n\n clusternode_host = 1\n for i in range(self.get((domain_name,\"cluster-nodes\"))):\n wn_name = \"%s-condor-wn%i\" % (domain_name, i+1)\n\n wn_node = Node()\n wn_node.set_property(\"id\", wn_name)\n wn_node.set_property(\"depends\", \"node:%s\" % node_name)\n if self.get((domain_name,\"nfs-nis\")):\n wn_node.add_to_array(\"run_list\", \"role[domain-nfsnis-client]\") \n else:\n wn_node.add_to_array(\"run_list\", \"recipe[provision::domain_users]\") \n wn_node.add_to_array(\"run_list\", workernode_role)\n domain.add_node(wn_node)\n\n clusternode_host += 1\n \n if self.get((domain_name,\"go-endpoint\")) != None:\n goep = GOEndpoint()\n gouser, goname = self.get((domain_name,\"go-endpoint\")).split(\"#\")\n goep.set_property(\"user\", gouser)\n goep.set_property(\"name\", goname)\n goep.set_property(\"gridftp\", \"node:%s-gridftp\" % domain_name)\n \n if self.get((domain_name,\"go-auth\")) == \"myproxy\":\n goep.set_property(\"myproxy\", \"node:%s-myproxy\" % domain_name)\n else:\n goep.set_property(\"myproxy\", \"myproxy.globusonline.org\")\n \n domain.add_to_array(\"go_endpoints\", goep)\n \n return topology\n\n\n","sub_path":"src/globus/provision/core/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":36068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"101375933","text":"import matplotlib.pyplot as plt \nfrom matplotlib.animation import FuncAnimation\n\nclass Animate():\n\n # These will hold all the required values for the simulation\n def __init__(self, marsArray, phobosArray, totalKArray):\n self.numFrames = len(marsArray)\n self.marsPos = marsArray\n self.phobosPos = phobosArray\n self.totalKArray = totalKArray\n\n # This will update both circle positions as the simulation goes on \n def animate(self, i):\n self.patchMars.center = (self.marsPos[i][0], self.marsPos[i][1])\n self.patchPhobos.center = (self.phobosPos[i][0], self.phobosPos[i][1])\n\n return self.patchMars, self.patchPhobos, \n\n def display(self):\n fig = plt.figure()\n ax = plt.axes()\n\n # Creates 2 circles to represent the moon phobos and planet mars, also size of the circles are added and\n # then added to the plot at the starting postions. \n self.patchMars = plt.Circle((self.marsPos[0][0], self.marsPos[0][1]), 0.1, color='r', animated=True)\n self.patchPhobos = plt.Circle((self.phobosPos[0][0], self.phobosPos[0][1]), 0.1, color='b', animated=True)\n self.patchMars.set_radius(1605000)\n self.patchPhobos.set_radius(850000)\n ax.add_patch(self.patchMars)\n ax.add_patch(self.patchPhobos)\n\n ax.axis('scaled')\n ax.set_ylim(-1.5e7, 1.5e7)\n ax.set_xlim(-1.5e7, 1.5e7)\n\n # Animate the plot\n anim = FuncAnimation(fig, self.animate, self.numFrames, repeat=False, interval=1, blit=True)\n # This prints the total Kinetic Energy just before the animation is shown.\n self.showTotalK()\n plt.show() \n\n \n # Displaying the total Kinetic energy at regualar intervals to the command line. \n def showTotalK(self):\n print(\"TOTAL KINETIC ENERGY: \", '{:0.4e}'.format(self.totalKArray[0]))\n for i in range(self.numFrames):\n if i % (self.numFrames/50) == 0:\n print(\"TOTAL KINETIC ENERGY: \", '{:0.4e}'.format(self.totalKArray[i]))","sub_path":"Checkpoint 5/src/Animate.py","file_name":"Animate.py","file_ext":"py","file_size_in_byte":2043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"615864504","text":"class ImageProcessor:\n\tdef __init__(self, frames, k_size):\n\t\tself.frames = frames\n\t\tself.k_size = k_size\n\t\t#\n\tdef analyse_frames(self):\n\t\tif len(self.frames) == 0:\n\t\t\tboxes = []\n\t\telse:\n\t\t\tboxes = []\n\t\t\tconverted_frames = self.convert_frames(self.frames)\n\t\t\taverage = self.get_average(converted_frames)\n\t\t\timage_diffs = self.get_diffs(converted_frames, average)\n\t\t\tdiff_masks = self.diffs_to_masks(image_diffs, self.k_size)\n\t\t\tboxes, _ = self.get_bounding_boxes(diff_masks)\n\t\treturn boxes\n\t\t#\n\tdef get_frames(self, video, no_frames):\n\t\tframes = self.calculate_frames(video, no_frames)\n\t\timages = []\n\t\tfor frame in frames:\n\t\t\tvideo.set(cv2.CAP_PROP_POS_FRAMES, frame)\n\t\t\t_, image = video.read()\n\t\t\tgauss_blur = cv2.GaussianBlur(image, (7, 7), 0)\n\t\t\timages.append(gauss_blur)\n\t\tprint(f\"Extracted {len(frames)} frames\")\n\t\treturn images\n\t\t#\n\tdef convert_frames(self, frames):\n\t\tfloat_frames = []\n\t\tfor frame in frames:\n\t\t\tgauss_blur = cv2.GaussianBlur(frame, (self.k_size, self.k_size), 0)\n\t\t\tfloat_frame = gauss_blur.astype(np.float32) / 255\n\t\t\tfloat_frames.append(float_frame)\n\t\treturn float_frames\n\t\t#\n\tdef get_average(self, frames):\n\t\tframes_shape = frames[0].shape\n\t\theight = frames_shape[0]\n\t\twidth = frames_shape[1]\n\t\tif len(frames_shape) < 3:\n\t\t\taverage_image = np.full((height, width), 0, np.float32)\n\t\telse:\n\t\t\taverage_image = np.full((height, width, 3), 0, np.float32)\n\t\tno_frames = len(frames)\n\t\tfor frame in frames:\n\t\t\taverage_image += frame / no_frames\n\t\tprint(f\"Calculated mean: {average_image.shape}\")\n\t\treturn average_image\n\t\t#\n\tdef get_diffs(self, frames, average_image):\n\t\tcolour = True if len(average_image.shape) > 1 else False\n\t\tdifferences = []\n\t\tif colour:\n\t\t\tfor frame in frames:\n\t\t\t\t_, image_diff = compare_ssim(frame, average_image, multichannel=True, full=True)\n\t\t\t\tabs_diff = cv2.convertScaleAbs(image_diff)\n\t\t\t\tdifferences.append(image_diff)\n\t\telse:\n\t\t\tfor frame in frames:\n\t\t\t\timage_diff = frame - average_image\n\t\t\t\tdifferences.append(abs_diff)\n\t\tprint(f\"Calculated differences: {len(differences)} frames, {differences[0].shape}\")\n\t\treturn differences\n\t\t#\n\tdef diffs_to_masks(self, frames, k_size):\n\t\tcolour = len(frames[0].shape) > 2\n\t\tmasks = []\n\t\tkernel = cv2.getGaussianKernel(k_size, 0)\n\t\tmask_type = \"\"\n\t\tif colour:\n\t\t\tmask_type = \"colour\"\n\t\t\tfor frame in frames:\n\t\t\t\tbw_frame = cv2.cvtColor((frame * 255).astype('uint8'), cv2.COLOR_BGR2GRAY)\n\t\t\t\t_, binary = cv2.threshold(bw_frame, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n\t\t\t\tmask = cv2.erode(binary, kernel, iterations = 1)\n\t\t\t\tmasks.append(mask.astype('uint8'))\n\t\tprint(f\"Calculated {len(masks)} {mask_type} masks, {masks[0].shape}, {len(masks)} frames\")\n\t\treturn masks\n\t\t#\n\tdef get_bounding_boxes(self, frames):\n\t\tboxes = []\n\t\tmax_in_one_frame = 0\n\t\tfor frame in frames:\n\t\t\tframe_boxes = self.get_bounding_boxes_for_single_frame(frame)\n\t\t\tboxes.append(frame_boxes)\n\t\t# print(f\"Extracted boxes for {len(boxes)} frames, max in one frame: {max_in_one_frame}\")\n\t\treturn boxes, max_in_one_frame\n\t\t#\n\tdef get_bounding_boxes_for_single_frame(self, frame):\n\t\tcontours, hierarchy = cv2.findContours(~frame, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\t\tbounding_boxes = []\n\t\tfor contour in contours:\n\t\t\tcontour_area = cv2.contourArea(contour)\n\t\t\tif 1750 < contour_area < 450000:\n\t\t\t\tx,y,w,h = cv2.boundingRect(contour)\n\t\t\t\tbounding_boxes.append([x, y, w, h])\n\t\tif len(bounding_boxes) > 1:\n\t\t\tbounding_boxes = self.group_boxes(bounding_boxes)\n\t\treturn bounding_boxes\n\t\t#\n\tdef group_boxes(self, bounding_boxes):\n\t\tmax_grouped = False\n\t\twhile len(bounding_boxes) > 1 and max_grouped == False:\n\t\t\tmax_grouped = True\n\t\t\ti = 0\n\t\t\twhile i < len(bounding_boxes):\n\t\t\t\tj = i + 1\n\t\t\t\tbox_1 = bounding_boxes[i]\n\t\t\t\twhile j < len(bounding_boxes):\n\t\t\t\t\tbox_2 = bounding_boxes[j]\n\t\t\t\t\tif self.boxes_overlap(box_1, box_2):\n\t\t\t\t\t\t# print(\"boxes overlap\")\n\t\t\t\t\t\tbounding_boxes[i] = self.combine_boxes(box_1, box_2)\n\t\t\t\t\t\tbounding_boxes.remove(box_2)\n\t\t\t\t\t\tmax_grouped = False\n\t\t\t\t\telse:\n\t\t\t\t\t\t# print(\"boxes do not overlap\")\n\t\t\t\t\t\tj += 1\n\t\t\t\ti += 1\n\t\treturn bounding_boxes\n\t\t#\n\tdef boxes_overlap(self, box_1, box_2):\n\t\tif box_2[0] < box_1[0] < (box_2[0] + box_2[2]) or box_2[0] < box_1[0] + box_1[2] < (box_2[0] + box_2[2]):\n\t\t\tif box_2[1] < box_1[1] < (box_2[1] + box_2[3]) or box_2[1] < box_1[1] + box_1[3] < (box_2[1] + box_2[3]):\n\t\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\t\t\t#\n\tdef combine_boxes(self, box_1, box_2):\n\t\tx = min(box_1[0], box_2[0])\n\t\tmax_x = max((box_1[0] + box_1[2]), (box_2[0] + box_2[2]))\n\t\ty = min(box_1[1], box_2[1])\n\t\tmax_y = max((box_1[1] + box_1[3]), (box_2[1] + box_2[3]))\n\t\tw = max_x - x\n\t\th = max_y - y\n\t\treturn [x, y, w, h]\n\n\t# def export_all_bounding_boxes_for_frames(self, save_directory, bounding_boxes, frames):\n\t# \tglobal id\n\t# \tfor i, frame in enumerate(frames):\n\t# \t\tfor box in bounding_boxes[i]:\n\t# \t\t\tclipped_image = clip_image_by_bounding_box(frame, box)\n\t# \t\t\tsave_image(save_directory, clipped_image)\n\t# \t\t\tid += 1\n\n\t# def clip_image_by_bounding_box(image, box):\n\t# \tclip = image[box[1]:(box[1] + box[3]), box[0]:(box[0] + box[2])]\n\t# \treturn clip\n\n\t# def save_image(save_directory, image):\n\t# \tcv2.imwrite(f\"{save_directory}/{id}.png\", image)\n\t# \tprint(f\"image {id} saved to {save_directory}/{id}.png\")\n\n\n","sub_path":"image_processing/image_processor.py","file_name":"image_processor.py","file_ext":"py","file_size_in_byte":5210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"71975047","text":"\"\"\"\nClassifying sentiments of a tweet\n\"\"\"\n\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport official.nlp.bert.tokenization as tokenization\nimport official.nlp.optimization as opti\nimport tensorflow as tf\nimport tensorflow_hub as hub\nfrom sklearn.preprocessing import LabelEncoder\n\nfrom reading_offensive_tweet import get_offensive_data\n\ntf.get_logger().setLevel('ERROR')\n\n\ndef encode_names(tokenizer, n):\n tokens = list(tokenizer.tokenize(n))\n tokens.append('[SEP]')\n return tokenizer.convert_tokens_to_ids(tokens)\n\n\ndef bert_encode(string_list, tokenizer, max_seq_length):\n string_tokens = tf.ragged.constant([\n encode_names(tokenizer, n) for n in np.array(string_list)])\n cls = [tokenizer.convert_tokens_to_ids(['[CLS]'])] * string_tokens.shape[0]\n input_word_ids = tf.concat([cls, string_tokens], axis=-1)\n input_mask = tf.ones_like(input_word_ids).to_tensor(\n shape=(None, max_seq_length))\n type_cls = tf.zeros_like(cls)\n type_tokens = tf.ones_like(string_tokens)\n input_type_ids = tf.concat([type_cls, type_tokens], axis=-1).to_tensor(shape=(None, max_seq_length))\n inputs = {\n 'input_word_ids': input_word_ids.to_tensor(shape=(None, max_seq_length)),\n 'input_mask': input_mask,\n 'input_type_ids': input_type_ids\n }\n return inputs\n\n\nif __name__ == \"__main__\":\n train_data, test_data, val_data, mappings = get_offensive_data()\n\n # Cleaning tweets.\n train_data.tweets = train_data.tweets.transform(\n lambda x: x.lower().replace(\"@user\", \"\").strip())\n test_data.tweets = test_data.tweets.transform(\n lambda x: x.lower().replace(\"@user\", \"\").strip())\n val_data.tweets = val_data.tweets.transform(\n lambda x: x.lower().replace(\"@user\", \"\").strip())\n\n # Creating labels.\n label_encoder = LabelEncoder()\n train_data.labels = label_encoder.fit_transform(train_data.labels)\n test_data.labels = label_encoder.transform(test_data.labels)\n val_data.labels = label_encoder.transform(val_data.labels)\n\n y_train = tf.keras.utils.to_categorical(train_data.labels)\n y_test = tf.keras.utils.to_categorical(test_data.labels)\n y_val = tf.keras.utils.to_categorical(val_data.labels)\n\n print(\"Fetching BERT model\")\n bert_layer = hub.KerasLayer(\"https://tfhub.dev/tensorflow/bert_multi_cased_L-12_H-768_A-12/2\", trainable=True)\n print(\"Model is fetched\")\n # bert_layer = hub.KerasLayer(\"https://tfhub.dev/tensorflow/small_bert/\n # bert_en_uncased_L-8_H-512_A-8/2\", trainable=True)\n\n vocab_file = bert_layer.resolved_object.vocab_file.asset_path.numpy()\n do_lower_case = bert_layer.resolved_object.do_lower_case.numpy()\n tokenizer = tokenization.FullTokenizer(vocab_file, do_lower_case)\n\n tokenizer.convert_tokens_to_ids(['[CLS]', '[SEP]'])\n tweets = tf.ragged.constant([encode_names(tokenizer, n) for n in train_data.tweets])\n\n cls = [tokenizer.convert_tokens_to_ids(['[CLS]'])] * tweets.shape[0]\n input_word_ids = tf.concat([cls, tweets], axis=1)\n\n input_mask = tf.ones_like(input_word_ids).to_tensor()\n\n type_cls = tf.zeros_like(cls)\n type_tweet = tf.ones_like(tweets)\n input_type_ids = tf.concat([type_cls, type_tweet], axis=1).to_tensor()\n\n max_seq_len = max([len(i) for i in input_word_ids])\n max_seq_len = int(1.5 * max_seq_len)\n\n X_train = bert_encode(train_data.tweets, tokenizer, max_seq_len)\n X_test = bert_encode(test_data.tweets, tokenizer, max_seq_len)\n X_val = bert_encode(val_data.tweets, tokenizer, max_seq_len)\n\n num_class = len(label_encoder.classes_)\n max_seq_length = max_seq_len\n\n input_word_ids = tf.keras.layers.Input(shape=(max_seq_length,), dtype=tf.int32, name=\"input_word_ids\")\n input_mask = tf.keras.layers.Input(shape=(max_seq_length,), dtype=tf.int32, name=\"input_mask\")\n segment_ids = tf.keras.layers.Input(shape=(max_seq_length,), dtype=tf.int32, name=\"segment_ids\")\n\n pooled_output, sequence_output = bert_layer([input_word_ids, input_mask, segment_ids])\n output = tf.keras.layers.Dropout(rate=0.1)(pooled_output)\n output = tf.keras.layers.Dense(num_class, activation='softmax', name='output')(output)\n\n model = tf.keras.Model(\n inputs={\n 'input_word_ids': input_word_ids,\n 'input_mask': input_mask,\n 'input_type_ids': segment_ids\n },\n outputs=output)\n\n epochs = 3\n batch_size = 4\n eval_batch_size = batch_size\n\n train_data_size = len(y_train)\n steps_per_epoch = int(train_data_size / batch_size)\n num_train_steps = steps_per_epoch * epochs\n warmup_steps = int(epochs * train_data_size * 0.1 / batch_size)\n\n optimizer = opti.create_optimizer(1e-3, num_train_steps=num_train_steps, num_warmup_steps=warmup_steps)\n\n model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])\n model.summary()\n history = model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size, validation_data=(X_val, y_val), verbose=1)\n model.save(os.path.join(\".\", \"offensive_model_final\"))\n print(model.evaluate(X_test, y_test))\n\n acc = history.history['accuracy']\n val_acc = history.history['val_accuracy']\n loss = history.history['loss']\n val_loss = history.history['val_loss']\n x = range(1, len(acc) + 1)\n\n plt.figure(figsize=(12, 5))\n plt.subplot(1, 2, 1)\n plt.plot(x, acc, 'b', label='Training acc')\n plt.plot(x, val_acc, 'r', label='Validation acc')\n plt.title('Training and validation accuracy')\n plt.legend()\n plt.subplot(1, 2, 2)\n plt.plot(x, loss, 'b', label='Training loss')\n plt.plot(x, val_loss, 'r', label='Validation loss')\n plt.title('Training and validation loss')\n plt.legend()\n plt.show()\n\n","sub_path":"offensive_analysis.py","file_name":"offensive_analysis.py","file_ext":"py","file_size_in_byte":5719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"47034291","text":"#!/usr/bin/python3 -B\n\n# Copyright 2015-2020 Josh Pieper, jjp@pobox.com. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n'''%prog [options]\n\nInteractively display and update values from an embedded device.\n'''\n\nimport binascii\nimport io\nimport numpy\nimport optparse\nimport os\nimport re\nimport serial\nimport socket\nimport struct\nimport sys\nimport time\nimport matplotlib\nimport matplotlib.figure\n\ntry:\n import PySide2\n\n os.environ['QT_API'] = 'pyside2'\n\n from matplotlib.backends import backend_qt5agg\n from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\n qt_backend = matplotlib.backends.backend_qt5agg\n\n from PySide2 import QtUiTools\n\nexcept:\n print(\"Falling back to PySide1\")\n # Fall back to pyside1\n matplotlib.use('Qt4Agg')\n matplotlib.rcParams['backend.qt4'] = 'PySide'\n\n from matplotlib.backends import backend_qt4agg\n from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas\n os.environ['QT_API'] = 'pyside'\n from PySide import QtUiTools\n qt_backend = matplotlib.backends.backend_qt4agg\n\n\nfrom qtconsole.history_console_widget import HistoryConsoleWidget\nfrom qtconsole.qt import QtCore, QtGui\n\nfrom bazel_tools.tools.python.runfiles import runfiles\nimport mjlib.telemetry.reader as reader\n\n\nLEFT_LEGEND_LOC = 3\nRIGHT_LEGEND_LOC = 2\n\nDEFAULT_RATE = 100\nMAX_HISTORY_SIZE = 100\n\ndef readline(stream):\n result = b''\n while True:\n c = stream.read(1)\n if len(c) == 0:\n return result\n result += c\n if c == b'\\n':\n return result\n\ndef dehexify(data):\n result = b''\n for i in range(0, len(data), 2):\n result += bytes([int(data[i:i+2], 16)])\n return result\n\n\ndef read_varuint(data, offset):\n '''Return (varuint, next_offset)'''\n\n result = 0\n shift = 0\n for i in range(5):\n if offset >= len(data):\n return None, offset\n this_byte, = struct.unpack('> 8) & 0xff\n\n if dest != 0x00:\n return\n\n if source != self._destination_id:\n return\n\n payload = dehexify(fields[2])\n\n sbo = 0\n subframe_id, sbo = read_varuint(payload, sbo)\n channel, sbo = read_varuint(payload, sbo)\n server_len, sbo = read_varuint(payload, sbo)\n\n if subframe_id is None or channel is None or server_len is None:\n return\n\n if subframe_id != 0x41:\n return\n\n if channel != 1:\n return\n\n payload_rest = payload[sbo:]\n to_add = payload_rest[0:server_len]\n self._read_buffer += to_add\n\n\nclass MultiplexStream(StreamBase):\n def __init__(self, *args, **kwargs):\n super(FdcanUsbStream, self).__init__(*args, **kwargs)\n\n def poll(self):\n # We only ask for a response if we're not writing immediately.\n # That way we can get multiple writes out nearly\n # simultaneously.\n wait_for_response = len(self._write_buffer) == 0\n\n header = struct.pack(' 0:\n _set_tree_widget_data(child, field)\n elif isinstance(field, list):\n _set_tree_widget_data(child, field,\n getter=lambda x, y: x[int(y)],\n required_size=len(field))\n else:\n child.setText(1, repr(field))\n\n\nclass RecordSignal(object):\n def __init__(self):\n self._index = 0\n self._callbacks = {}\n\n def connect(self, handler):\n result = self._index\n self._index += 1\n self._callbacks[result] = handler\n\n class Connection(object):\n def __init__(self, parent, index):\n self.parent = parent\n self.index = index\n\n def remove(self):\n del self.parent._callbacks[self.index]\n\n return Connection(self, result)\n\n def update(self, value):\n for handler in self._callbacks.values():\n handler(value)\n return len(self._callbacks) != 0\n\n\nclass PlotItem(object):\n def __init__(self, axis, plot_widget, name, signal):\n self.axis = axis\n self.plot_widget = plot_widget\n self.name = name\n self.line = None\n self.xdata = []\n self.ydata = []\n self.connection = signal.connect(self._handle_update)\n\n def _make_line(self):\n line = matplotlib.lines.Line2D([], [])\n line.set_label(self.name)\n line.set_color(self.plot_widget.COLORS[self.plot_widget.next_color])\n self.plot_widget.next_color = (\n self.plot_widget.next_color + 1) % len(self.plot_widget.COLORS)\n\n self.axis.add_line(line)\n self.axis.legend(loc=self.axis.legend_loc)\n\n self.line = line\n\n def remove(self):\n self.line.remove()\n self.connection.remove()\n # NOTE jpieper: matplotlib gives us no better way to remove a\n # legend.\n if len(self.axis.lines) == 0:\n self.axis.legend_ = None\n else:\n self.axis.legend(loc=self.axis.legend_loc)\n self.plot_widget.canvas.draw()\n\n def _handle_update(self, value):\n if self.plot_widget.paused:\n return\n\n if self.line is None:\n self._make_line()\n\n now = time.time()\n self.xdata.append(now)\n self.ydata.append(value)\n\n # Remove elements from the beginning until there is at most\n # one before the window.\n oldest_time = now - self.plot_widget.history_s\n oldest_index = None\n for i in range(len(self.xdata)):\n if self.xdata[i] >= oldest_time:\n oldest_index = i - 1\n break\n\n if oldest_index and oldest_index > 1:\n self.xdata = self.xdata[oldest_index:]\n self.ydata = self.ydata[oldest_index:]\n\n self.line.set_data(self.xdata, self.ydata)\n\n self.axis.relim()\n self.axis.autoscale()\n\n self.plot_widget.data_update()\n\n\nclass PlotWidget(QtGui.QWidget):\n COLORS = 'rbgcmyk'\n\n def __init__(self, parent=None):\n QtGui.QWidget.__init__(self, parent)\n\n self.history_s = 20.0\n self.next_color = 0\n self.paused = False\n\n self.last_draw_time = 0.0\n\n self.figure = matplotlib.figure.Figure()\n self.canvas = FigureCanvas(self.figure)\n\n self.canvas.mpl_connect('key_press_event', self.handle_key_press)\n self.canvas.mpl_connect('key_release_event', self.handle_key_release)\n\n self.left_axis = self.figure.add_subplot(111)\n self.left_axis.grid()\n self.left_axis.fmt_xdata = lambda x: '%.3f' % x\n\n self.left_axis.legend_loc = LEFT_LEGEND_LOC\n\n self.right_axis = None\n\n self.toolbar = qt_backend.NavigationToolbar2QT(self.canvas, self)\n self.pause_action = QtGui.QAction(u'Pause', self)\n self.pause_action.setCheckable(True)\n self.pause_action.toggled.connect(self._handle_pause)\n self.toolbar.addAction(self.pause_action)\n\n layout = QtGui.QVBoxLayout(self)\n layout.addWidget(self.toolbar, 0)\n layout.addWidget(self.canvas, 1)\n\n self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus)\n\n def _handle_pause(self, value):\n self.paused = value\n\n def add_plot(self, name, signal, axis_number):\n axis = self.left_axis\n if axis_number == 1:\n if self.right_axis is None:\n self.right_axis = self.left_axis.twinx()\n self.right_axis.legend_loc = RIGHT_LEGEND_LOC\n axis = self.right_axis\n item = PlotItem(axis, self, name, signal)\n return item\n\n def remove_plot(self, item):\n item.remove()\n\n def data_update(self):\n now = time.time()\n elapsed = now - self.last_draw_time\n if elapsed > 0.1:\n self.last_draw_time = now\n self.canvas.draw()\n\n def _get_axes_keys(self):\n result = []\n result.append(('1', self.left_axis))\n if self.right_axis:\n result.append(('2', self.right_axis))\n return result\n\n def handle_key_press(self, event):\n if event.key not in ['1', '2']:\n return\n for key, axis in self._get_axes_keys():\n if key == event.key:\n axis.set_navigate(True)\n else:\n axis.set_navigate(False)\n\n def handle_key_release(self, event):\n if event.key not in ['1', '2']:\n return\n for key, axis in self._get_axes_keys():\n axis.set_navigate(True)\n\n\nclass SizedTreeWidget(QtGui.QTreeWidget):\n def __init__(self, parent=None):\n QtGui.QTreeWidget.__init__(self, parent)\n self.setColumnCount(2)\n self.headerItem().setText(0, 'Name')\n self.headerItem().setText(1, 'Value')\n\n def sizeHint(self):\n return QtCore.QSize(350, 500)\n\n\nclass TviewConsoleWidget(HistoryConsoleWidget):\n line_input = QtCore.Signal(str)\n\n def __init__(self, *args, **kw):\n super(TviewConsoleWidget, self).__init__(*args, **kw)\n\n self.execute_on_complete_input = False\n self._prompt = '>>> '\n self.clear()\n\n # The bionic version of ConsoleWidget seems to get the cursor\n # position screwed up after a clear. Let's just fix it up\n # here.\n self._append_before_prompt_cursor.setPosition(0)\n\n def sizeHint(self):\n return QtCore.QSize(600, 200)\n\n def add_text(self, data):\n assert data.endswith('\\n') or data.endswith('\\r')\n self._append_plain_text(data, before_prompt=True)\n self._control.moveCursor(QtGui.QTextCursor.End)\n\n def _handle_timeout(self):\n self._append_plain_text('%s\\r\\n' % time.time(),\n before_prompt=True)\n self._control.moveCursor(QtGui.QTextCursor.End)\n\n def _is_complete(self, source, interactive):\n return True, False\n\n def _execute(self, source, hidden):\n self.line_input.emit(source)\n self._show_prompt(self._prompt)\n return True\n\n\nclass Record:\n def __init__(self, archive):\n self.archive = archive\n self.tree_item = None\n self.signals = {}\n self.history = []\n\n def get_signal(self, name):\n if name not in self.signals:\n self.signals[name] = RecordSignal()\n\n return self.signals[name]\n\n def update(self, struct):\n count = 0\n self.history.append(struct)\n if len(self.history) > MAX_HISTORY_SIZE:\n self.history = self.history[1:]\n\n for key, signal in self.signals.items():\n if key.startswith('__STDDEV_'):\n remaining = key.split('__STDDEV_')[1]\n values = [_get_data(x, remaining) for x in self.history]\n value = numpy.std(values)\n elif key.startswith('__MEAN_'):\n remaining = key.split('__MEAN_')[1]\n values = [_get_data(x, remaining) for x in self.history]\n value = numpy.mean(values)\n else:\n value = _get_data(struct, key)\n if signal.update(value):\n count += 1\n return count != 0\n\n\nclass NoEditDelegate(QtGui.QStyledItemDelegate):\n def __init__(self, parent=None):\n QtGui.QStyledItemDelegate.__init__(self, parent=parent)\n\n def createEditor(self, parent, option, index):\n return None\n\n\ndef _get_item_name(item):\n name = item.text(0)\n while item.parent() and item.parent().parent():\n name = item.parent().text(0) + '.' + name\n item = item.parent()\n\n return name\n\n\ndef _get_item_root(item):\n while item.parent().parent():\n item = item.parent()\n return item.text(0)\n\n\nclass Device:\n STATE_LINE = 0\n STATE_CONFIG = 1\n STATE_TELEMETRY = 2\n STATE_SCHEMA = 3\n STATE_DATA = 4\n\n def __init__(self, number, stream, console, prefix,\n config_tree_item, data_tree_item):\n self.number = number\n self._stream = stream\n self._console = console\n self._prefix = prefix\n self._config_tree_item = config_tree_item\n self._data_tree_item = data_tree_item\n\n self._buffer = b''\n self._serial_state = self.STATE_LINE\n self._telemetry_records = {}\n self._schema_name = None\n self._config_tree_items = {}\n self._config_callback = None\n\n self._start_time = None\n\n def start(self):\n # Stop the spew.\n self._stream.write('\\r\\n'.encode('latin1'))\n self._stream.write('tel stop\\r\\n'.encode('latin1'))\n\n # We want to wait a little bit, discard everything we have\n # received, and then initialize the device.\n self._start_time = time.time()\n\n def _setup_device(self, callback):\n # When we start, get a listing of all configuration options\n # and all available telemetry channels.\n def after_config():\n self.update_telemetry(callback)\n self.update_config(after_config)\n\n def poll(self):\n self._stream.poll()\n\n if self._start_time is not None:\n now = time.time()\n if now - self._start_time < 0.2:\n return\n # Discard any junk that may be there.\n self._stream.read(8192)\n self._start_time = None\n\n self._setup_device(None)\n\n\n data = self._stream.read(8192)\n\n self._buffer += data\n\n while True:\n old_len = len(self._buffer)\n self._handle_serial_data()\n if len(self._buffer) == old_len:\n break\n\n self._stream.flush()\n\n def write(self, data):\n self._stream.write(data)\n\n def config_item_changed(self, name, value):\n if self._serial_state == self.STATE_CONFIG:\n return\n\n self.write_line('conf set %s %s\\r\\n' % (name, value))\n\n def _handle_serial_data(self):\n if self._serial_state == self.STATE_LINE:\n self._handle_serial_line()\n elif self._serial_state == self.STATE_CONFIG:\n self._handle_config()\n elif self._serial_state == self.STATE_TELEMETRY:\n self._handle_telemetry()\n elif self._serial_state == self.STATE_SCHEMA:\n self._handle_schema()\n elif self._serial_state == self.STATE_DATA:\n self._handle_data()\n else:\n assert False\n\n def _handle_serial_line(self):\n line = self._get_serial_line()\n if line is None:\n return\n\n line = line.decode('latin1')\n\n display = True\n if line == '':\n display = False\n\n if line.startswith('schema '):\n self._serial_state = self.STATE_SCHEMA\n self._schema_name = line.split(' ', 1)[1].strip()\n elif line.startswith('emit '):\n self._serial_state = self.STATE_DATA\n self._schema_name = line.split(' ', 1)[1].strip()\n display = False\n\n if display:\n self._console.add_text(self._prefix + line + '\\n')\n\n def _get_serial_line(self):\n # Consume any newlines at the start of our buffer.\n pos = 0\n while pos < len(self._buffer) and self._buffer[pos] in b'\\r\\n':\n pos += 1\n self._buffer = self._buffer[pos:]\n\n # Look for a trailing newline\n end = 0\n while end < len(self._buffer) and self._buffer[end] not in b'\\r\\n':\n end += 1\n\n if end >= len(self._buffer):\n return\n\n line, self._buffer = self._buffer[:end], self._buffer[end+1:]\n\n return line\n\n def update_config(self, callback):\n # Clear out our config tree.\n self._config_tree_item.takeChildren()\n self._config_tree_items = {}\n\n self._config_callback = callback\n self.write_line('conf enumerate\\r\\n')\n\n # TODO jpieper: In the current protocol this is racy, as there\n # is no header on the config enumeration. I should probably\n # add one.\n self._serial_state = self.STATE_CONFIG\n\n def _handle_config(self):\n line = self._get_serial_line()\n if not line:\n return\n\n line = line.decode('latin1')\n self._console.add_text(self._prefix + line + '\\n')\n\n if line.startswith('OK'):\n # We're done with config now.\n self._serial_state = self.STATE_LINE\n cbk, self._config_callback = self._config_callback, None\n if cbk:\n cbk()\n else:\n # Add it into our tree view.\n key, value = line.split(' ', 1)\n name, rest = key.split('.', 1)\n if name not in self._config_tree_items:\n item = QtGui.QTreeWidgetItem(self._config_tree_item)\n item.setText(0, name)\n self._config_tree_items[name] = item\n\n def add_config(item, key, value):\n if key == '':\n item.setText(1, value)\n item.setFlags(QtCore.Qt.ItemIsEditable |\n QtCore.Qt.ItemIsSelectable |\n QtCore.Qt.ItemIsEnabled)\n return\n\n fields = key.split('.', 1)\n this_field = fields[0]\n next_key = ''\n if len(fields) > 1:\n next_key = fields[1]\n\n child = None\n # See if we already have an appropriate child.\n for i in range(item.childCount()):\n if item.child(i).text(0) == this_field:\n child = item.child(i)\n break\n if child is None:\n child = QtGui.QTreeWidgetItem(item)\n child.setText(0, this_field)\n add_config(child, next_key, value)\n\n add_config(self._config_tree_items[name], rest, value)\n\n # TODO(jpieper)\n # self.ui.configTreeWidget.resizeColumnToContents(0)\n\n def update_telemetry(self, callback):\n self._data_tree_item.takeChildren()\n self._telemetry_records = {}\n\n self._telemetry_callback = callback\n self.write_line('tel list\\r\\n')\n\n self._serial_state = self.STATE_TELEMETRY\n\n def write_line(self, line):\n self._console.add_text(self._prefix + line)\n self._stream.write(line.encode('latin1'))\n\n def _handle_telemetry(self):\n line = self._get_serial_line()\n if not line:\n return\n\n line = line.decode('latin1')\n self._console.add_text(self._prefix + line + '\\n')\n\n if line.startswith('OK'):\n # Now we need to start getting schemas.\n self._serial_state = self.STATE_LINE\n self._update_schema()\n else:\n name = line.strip()\n self._telemetry_records[name] = None\n\n def _update_schema(self):\n # Find a channel we don't have a schema for and request it.\n for name in self._telemetry_records.keys():\n if self._telemetry_records[name] is None:\n self.write_line('tel schema %s\\r\\n' % name)\n self._serial_state = self.STATE_LINE\n return\n\n self._serial_state = self.STATE_LINE\n # Guess we are done. Update our tree view.\n\n # TODO(jpieper)\n # self.ui.telemetryTreeWidget.resizeColumnToContents(0)\n\n cbk, self._telemetry_callback = self._telemetry_callback, None\n if cbk:\n cbk()\n\n def _handle_schema(self):\n schema = self._handle_sized_block()\n if not schema:\n return\n\n name, self._schema_name = self._schema_name, None\n\n if name in self._telemetry_records:\n if self._telemetry_records[name]:\n return\n\n archive = reader.Type.from_binary(io.BytesIO(schema), name=name)\n\n record = Record(archive)\n self._telemetry_records[name] = record\n record.tree_item = self._add_schema_to_tree(name, archive, record)\n\n self._console.add_text(self._prefix + '\\n' % name)\n\n # Now look to see if there are any more we should request.\n self._update_schema()\n\n def _handle_data(self):\n data = self._handle_sized_block()\n if not data:\n return\n\n name, self._schema_name = self._schema_name, None\n\n if name not in self._telemetry_records:\n return\n\n record = self._telemetry_records[name]\n if record:\n struct = record.archive.read(reader.Stream(io.BytesIO(data)))\n record.update(struct)\n _set_tree_widget_data(record.tree_item, struct)\n\n self._serial_state = self.STATE_LINE\n\n def _handle_sized_block(self):\n # Wait until we have the complete schema in the buffer. It\n # will start with the final newline from the first line.\n if len(self._buffer) < 5:\n return\n\n size = struct.unpack(' 2 ** 24:\n # Whoops, probably bogus.\n print('Invalid schema size, skipping whatever we were doing.')\n self._serial_state = self.STATE_LINE\n return\n\n if len(self._buffer) < 5 + size:\n return\n\n block = self._buffer[5:5+size]\n self._buffer = self._buffer[5+size:]\n return block\n\n class Schema:\n def __init__(self, name, parent, record):\n self._name = name\n self._parent = parent\n self.record = record\n\n def expand(self):\n self._parent.write_line('tel fmt %s 0\\r\\n' % self._name)\n self._parent.write_line('tel rate %s %d\\r\\n' %\n (self._name, DEFAULT_RATE))\n\n def collapse(self):\n self._parent.write_line('tel rate %s 0\\r\\n' % self._name)\n\n\n def _add_schema_to_tree(self, name, schema_data, record):\n item = QtGui.QTreeWidgetItem(self._data_tree_item)\n item.setText(0, name)\n\n schema = Device.Schema(name, self, record)\n item.setData(0, QtCore.Qt.UserRole, schema)\n\n def add_item(parent, element):\n if isinstance(element, reader.ObjectType):\n for field in element.fields:\n name = field.name\n\n item = QtGui.QTreeWidgetItem(parent)\n item.setText(0, name)\n\n add_item(item, field.type_class)\n\n add_item(item, schema_data)\n return item\n\n\nclass TviewMainWindow():\n def __init__(self, options, parent=None):\n self.options = options\n self.port = None\n self.devices = []\n self.default_rate = 100\n\n self._serial_timer = QtCore.QTimer()\n self._serial_timer.timeout.connect(self._poll_serial)\n self._serial_timer.start(10)\n\n r = runfiles.Create()\n uifilename = r.Rlocation(\n \"com_github_mjbots_moteus/utils/tview_main_window.ui\")\n loader = QtUiTools.QUiLoader()\n uifile = QtCore.QFile(uifilename)\n uifile.open(QtCore.QFile.ReadOnly)\n self.ui = loader.load(uifile, parent)\n uifile.close()\n\n self.ui.configTreeWidget = SizedTreeWidget()\n self.ui.configDock.setWidget(self.ui.configTreeWidget)\n\n self.ui.telemetryTreeWidget = SizedTreeWidget()\n self.ui.telemetryDock.setWidget(self.ui.telemetryTreeWidget)\n\n self.ui.telemetryTreeWidget.itemExpanded.connect(\n self._handle_tree_expanded)\n self.ui.telemetryTreeWidget.itemCollapsed.connect(\n self._handle_tree_collapsed)\n self.ui.telemetryTreeWidget.setContextMenuPolicy(\n QtCore.Qt.CustomContextMenu)\n self.ui.telemetryTreeWidget.customContextMenuRequested.connect(\n self._handle_telemetry_context_menu)\n\n self.ui.configTreeWidget.setItemDelegateForColumn(\n 0, NoEditDelegate(self.ui))\n self.ui.configTreeWidget.itemExpanded.connect(\n self._handle_config_expanded)\n self.ui.configTreeWidget.itemChanged.connect(\n self._handle_config_item_changed)\n\n self.ui.plotItemRemoveButton.clicked.connect(\n self._handle_plot_item_remove)\n\n self.console = TviewConsoleWidget()\n self.console.ansi_codes = False\n self.console.line_input.connect(self._handle_user_input)\n self.ui.consoleDock.setWidget(self.console)\n\n self.ui.tabifyDockWidget(self.ui.configDock, self.ui.telemetryDock)\n\n layout = QtGui.QVBoxLayout(self.ui.plotHolderWidget)\n layout.setContentsMargins(0, 0, 0, 0)\n layout.setSpacing(0)\n self.ui.plotHolderWidget.setLayout(layout)\n self.ui.plotWidget = PlotWidget(self.ui.plotHolderWidget)\n layout.addWidget(self.ui.plotWidget)\n\n def update_plotwidget(value):\n self.ui.plotWidget.history_s = value\n self.ui.historySpin.valueChanged.connect(update_plotwidget)\n\n QtCore.QTimer.singleShot(0, self._handle_startup)\n\n def show(self):\n self.ui.show()\n\n def _open(self):\n if self.options.target:\n target_fields = self.options.target.split(':')\n try:\n port = NetworkPort(socket.create_connection(\n (target_fields[0], int(target_fields[1])), timeout=2.0))\n except OSError:\n print(\"could not connect to: \", self.options.target)\n exit(1)\n self.port = BufferedSerial(port)\n else:\n self.port = BufferedSerial(serial.Serial(\n port=self.options.serial,\n baudrate=self.options.baudrate,\n timeout=0.0))\n\n self.devices = []\n self.ui.configTreeWidget.clear()\n self.ui.telemetryTreeWidget.clear()\n\n for device_id in [int(x) for x in self.options.devices.split(',')]:\n if self.options.rs485:\n stream = MultiplexStream(\n self.port, device_id, self.options.max_receive_bytes)\n else:\n stream = FdcanUsbStream(\n self.port, device_id, self.options.max_receive_bytes)\n\n config_item = QtGui.QTreeWidgetItem()\n config_item.setText(0, str(device_id))\n self.ui.configTreeWidget.addTopLevelItem(config_item)\n\n data_item = QtGui.QTreeWidgetItem()\n data_item.setText(0, str(device_id))\n self.ui.telemetryTreeWidget.addTopLevelItem(data_item)\n\n device = Device(device_id, stream,\n self.console, '{}>'.format(device_id),\n config_item,\n data_item)\n\n config_item.setData(0, QtCore.Qt.UserRole, device)\n device.start()\n\n self.devices.append(device)\n\n def _handle_startup(self):\n self.console._control.setFocus()\n\n def _poll_serial(self):\n if self.port is None:\n if os.path.exists(self.options.serial) or self.options.target:\n self._open()\n else:\n return\n else:\n [x.poll() for x in self.devices]\n\n def make_writer(self, devices, line):\n def write():\n for device in devices:\n device.write((line + '\\n').encode('latin1'))\n\n return write\n\n def _handle_user_input(self, line):\n device_lines = [x.strip() for x in line.split('&&')]\n now = time.time()\n current_delay_ms = 0\n for line in device_lines:\n delay_re = re.search(r\"^:(\\d+)$\", line)\n device_re = re.search(r\"^(A|\\d+)>(.*)$\", line)\n if delay_re:\n current_delay_ms += int(delay_re.group(1))\n continue\n elif device_re:\n if device_re.group(1) == 'A':\n device_nums = [x.number for x in self.devices]\n else:\n device_nums = [int(device_re.group(1))]\n line = device_re.group(2)\n else:\n device_nums = [self.devices[0].number]\n devices = [x for x in self.devices if x.number in device_nums]\n writer = self.make_writer(devices, line)\n\n if current_delay_ms > 0:\n QtCore.QTimer.singleShot(current_delay_ms, writer)\n else:\n writer()\n\n def _handle_tree_expanded(self, item):\n self.ui.telemetryTreeWidget.resizeColumnToContents(0)\n user_data = item.data(0, QtCore.Qt.UserRole)\n if user_data:\n user_data.expand()\n\n def _handle_tree_collapsed(self, item):\n user_data = item.data(0, QtCore.Qt.UserRole)\n if user_data:\n user_data.collapse()\n\n def _handle_telemetry_context_menu(self, pos):\n item = self.ui.telemetryTreeWidget.itemAt(pos)\n if item.childCount() > 0:\n return\n\n menu = QtGui.QMenu(self.ui)\n left_action = menu.addAction('Plot Left')\n right_action = menu.addAction('Plot Right')\n left_std_action = menu.addAction('Plot StdDev Left')\n right_std_action = menu.addAction('Plot StdDev Right')\n left_mean_action = menu.addAction('Plot Mean Left')\n right_mean_action = menu.addAction('Plot Mean Right')\n\n plot_actions = [\n left_action,\n right_action,\n left_std_action,\n right_std_action,\n left_mean_action,\n right_mean_action,\n ]\n\n right_actions = [right_action, right_std_action, right_mean_action]\n std_actions = [left_std_action, right_std_action]\n mean_actions = [left_mean_action, right_mean_action]\n\n menu.addSeparator()\n copy_name = menu.addAction('Copy Name')\n copy_value = menu.addAction('Copy Value')\n\n requested = menu.exec_(self.ui.telemetryTreeWidget.mapToGlobal(pos))\n\n if requested in plot_actions:\n top = item\n while top.parent().parent():\n top = top.parent()\n\n schema = top.data(0, QtCore.Qt.UserRole)\n record = schema.record\n\n name = _get_item_name(item)\n root = _get_item_root(item)\n\n leaf = name.split('.', 1)[1]\n axis = 0\n if requested in right_actions:\n axis = 1\n\n if requested in std_actions:\n leaf = '__STDDEV_' + leaf\n name = 'stddev ' + name\n\n if requested in mean_actions:\n leaf = '__MEAN_' + leaf\n name = 'mean ' + name\n\n plot_item = self.ui.plotWidget.add_plot(\n name, record.get_signal(leaf), axis)\n self.ui.plotItemCombo.addItem(name, plot_item)\n elif requested == copy_name:\n QtGui.QApplication.clipboard().setText(item.text(0))\n elif requested == copy_value:\n QtGui.QApplication.clipboard().setText(item.text(1))\n else:\n # The user cancelled.\n pass\n\n def _handle_config_expanded(self, item):\n self.ui.configTreeWidget.resizeColumnToContents(0)\n\n def _handle_config_item_changed(self, item, column):\n if not item.parent():\n return\n\n top = item\n while top.parent():\n top = top.parent()\n\n device = top.data(0, QtCore.Qt.UserRole)\n device.config_item_changed(_get_item_name(item), item.text(1))\n\n def _handle_plot_item_remove(self):\n index = self.ui.plotItemCombo.currentIndex()\n\n if index < 0:\n return\n\n item = self.ui.plotItemCombo.itemData(index)\n self.ui.plotWidget.remove_plot(item)\n self.ui.plotItemCombo.removeItem(index)\n\n\ndef main():\n usage, description = __doc__.split('\\n\\n', 1)\n parser = optparse.OptionParser(usage=usage, description=description)\n\n parser.add_option('--serial', '-s', default='/dev/ttyACM0')\n parser.add_option('--baudrate', '-b', type='int', default=115200)\n parser.add_option('--devices', '-d', type='str', default='1')\n parser.add_option('--target', '-t', default=None)\n parser.add_option('--rs485', '-c', action='store_true')\n parser.add_option('--max-receive-bytes', default=127, type=int)\n\n options, args = parser.parse_args()\n assert len(args) == 0\n\n app = QtGui.QApplication(sys.argv)\n\n # To work around https://bugreports.qt.io/browse/PYSIDE-88\n app.aboutToQuit.connect(lambda: os._exit(0))\n\n tv = TviewMainWindow(options)\n tv.show()\n\n app.exec_()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"utils/tview.py","file_name":"tview.py","file_ext":"py","file_size_in_byte":39735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"122517743","text":"from flask import Flask, jsonify, request\nfrom flask_cors import CORS\n\n\nTA = [\n {\n 'id': 1,\n 'name': 'Rishabh',\n 'time': 'Monday 9 am - 11 am EST'\n },\n {\n 'id': 2,\n 'name': 'Goutham',\n 'time': 'Friday 4 pm - 6 pm EST'\n },\n {\n 'id': 3,\n 'name': 'Hyun',\n 'time': 'Thursday 3 pm - 5 pm EST'\n },\n {\n 'id': 4,\n 'name': 'Reshma',\n 'time': 'Tuesday 2 pm to 4 pm EST '\n }\n]\n\n# configuration\nDEBUG = True\n\n# instantiate the app\napplication = Flask(__name__)\napplication.config.from_object(__name__)\n\n# enable CORS\nCORS(application, resources={r'/*': {'origins': '*'}})\n\n\n@application.route('/', methods=['GET'])\ndef hello_world():\n return jsonify('hello_world!')\n\n\n@application.route('/ta', methods=['GET'])\ndef all_tas():\n response_object = {'status': 'success'}\n if request.method == 'GET':\n response_object['ta'] = TA\n \n return jsonify(response_object)\n\n@application.route('/ta/', methods=['GET'])\ndef ta(ta_id):\n response_object = {'status': 'success'}\n if request.method == 'GET':\n found_ta = False\n for ta in TA:\n try:\n if int(ta['id']) == int(ta_id):\n response_object['ta'] = ta\n found_ta = True\n except:\n found_ta = False \n\n if not found_ta:\n response_message = 'No TA present with TA ID ' + str(ta_id)\n response_object = {'status': 'success', 'message': response_message}\n \n return jsonify(response_object)\n\n\n\nif __name__ == '__main__':\n application.debug = True\n application.run()","sub_path":"server/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"74632905","text":"def ease_array(nums):\n\tll = len(nums)\n\n\tfor k in range(ll-1):\n\t\tif nums[k+1]!=0 and nums[k]==nums[k+1]:\n\t\t\tnums[k]=nums[k]*2\n\t\t\tnums[k+1]=0\n\n\ti,j = 0, 0\n\tfor k in range(ll):\n\t\tif nums[k]==0:\n\t\t\tj+=1\n\t\telse:\n\t\t\tnums[i]=nums[j]\n\t\t\tj+=1 \n\t\t\ti+=1\n\t\t\n\twhile(i 0\n\n api_users = list(api_client.users)\n assert sorted(api_users) == sorted(real_users)\n\n\ndef test_get_user(api_client): # noqa: F811\n user = api_client.users.get(\"cbguder@a.co\")\n assert sorted(user.groups) == [\"group-admins\", \"permission-admins\", \"user-admins\"]\n assert user.passwords == []\n assert user.public_keys == []\n assert user.enabled\n assert user.service_account is None\n\n perms = [(p.permission, p.argument) for p in user.permissions]\n assert sorted(perms) == [(GROUP_ADMIN, \"\"), (PERMISSION_ADMIN, \"\"), (USER_ADMIN, \"\")]\n\n assert user.metadata == {}\n","sub_path":"itests/api/users_test.py","file_name":"users_test.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"564424604","text":"from __future__ import division\n\nimport uuid\nimport torch\nfrom torch.nn import Linear\nfrom torch.optim import SGD\nfrom torch.autograd import Variable\nfrom torch.nn.functional import mse_loss\nimport numpy as np\nfrom mock import call, MagicMock, Mock\nfrom pytest import raises, approx\n\nfrom ignite.trainer import Trainer, TrainingEvents, create_supervised\n\n\nclass _PicklableMagicMock(object):\n def __init__(self):\n self.uuid = str(uuid.uuid4())\n self.mock = MagicMock()\n\n def __getstate__(self):\n return {key: self.__dict__[key] for key in self.__dict__ if key != \"mock\"}\n\n def __setstate__(self, state):\n self.__dict__.update(state)\n\n def __getattr__(self, item):\n return _PicklableMagicMock()\n\n def __call__(self, *args, **kwargs):\n return _PicklableMagicMock()\n\n def __iter__(self):\n return iter([_PicklableMagicMock()])\n\n def __eq__(self, other):\n return other.uuid == self.uuid\n\n def __repr__(self):\n return self.uuid\n\n\ndef test_adding_handler_for_non_existent_event_throws_error():\n trainer = Trainer(MagicMock(), MagicMock())\n\n event_name = uuid.uuid4()\n while event_name in TrainingEvents.__members__.values():\n event_name = uuid.uuid4()\n\n with raises(ValueError):\n trainer.add_event_handler(event_name, lambda x: x)\n\n\ndef test_exception_handler_called_on_error():\n training_update_function = MagicMock(side_effect=ValueError())\n\n trainer = Trainer(training_update_function, MagicMock())\n exception_handler = MagicMock()\n trainer.add_event_handler(TrainingEvents.EXCEPTION_RAISED, exception_handler)\n\n with raises(ValueError):\n trainer.run([1])\n\n exception_handler.assert_called_once_with(trainer)\n\n\ndef test_adding_multiple_event_handlers():\n trainer = Trainer(MagicMock(return_value=1), MagicMock())\n handlers = [MagicMock(), MagicMock()]\n for handler in handlers:\n trainer.add_event_handler(TrainingEvents.TRAINING_STARTED, handler)\n\n trainer.run([1])\n for handler in handlers:\n handler.assert_called_once_with(trainer)\n\n\ndef test_args_and_kwargs_are_passed_to_event():\n trainer = Trainer(MagicMock(return_value=1), MagicMock())\n kwargs = {'a': 'a', 'b': 'b'}\n args = (1, 2, 3)\n handlers = []\n for event in TrainingEvents:\n handler = MagicMock()\n trainer.add_event_handler(event, handler, *args, **kwargs)\n handlers.append(handler)\n\n trainer.run([1], max_epochs=1)\n called_handlers = [handle for handle in handlers if handle.called]\n assert len(called_handlers) > 0\n\n for handler in called_handlers:\n handler_args, handler_kwargs = handler.call_args\n assert handler_args[0] == trainer\n assert handler_args[1::] == args\n assert handler_kwargs == kwargs\n\n\ndef test_current_epoch_counter_increases_every_epoch():\n trainer = Trainer(MagicMock(return_value=1), MagicMock())\n max_epochs = 5\n\n class EpochCounter(object):\n def __init__(self):\n self.current_epoch_count = 0\n\n def __call__(self, trainer):\n assert trainer.current_epoch == self.current_epoch_count\n self.current_epoch_count += 1\n\n trainer.add_event_handler(TrainingEvents.EPOCH_STARTED, EpochCounter())\n\n trainer.run([1], max_epochs=max_epochs)\n\n assert trainer.current_epoch == max_epochs\n\n\ndef test_current_iteration_counter_increases_every_iteration():\n training_batches = [1, 2, 3]\n trainer = Trainer(MagicMock(return_value=1), MagicMock())\n max_epochs = 5\n\n class IterationCounter(object):\n def __init__(self):\n self.current_iteration_count = 0\n\n def __call__(self, trainer):\n assert trainer.current_iteration == self.current_iteration_count\n self.current_iteration_count += 1\n\n trainer.add_event_handler(TrainingEvents.TRAINING_ITERATION_STARTED, IterationCounter())\n\n trainer.run(training_batches, max_epochs=max_epochs)\n\n assert trainer.current_iteration == max_epochs * len(training_batches)\n\n\ndef _validate(trainer, validation_data):\n trainer.validate(validation_data)\n\n\ndef test_current_validation_iteration_counter_increases_every_iteration():\n validation_batches = [1, 2, 3]\n trainer = Trainer(MagicMock(return_value=1), MagicMock(return_value=1))\n max_epochs = 5\n\n class IterationCounter(object):\n def __init__(self):\n self.current_iteration_count = 0\n self.total_count = 0\n\n def __call__(self, trainer):\n assert trainer.current_validation_iteration == self.current_iteration_count\n self.current_iteration_count += 1\n self.total_count += 1\n\n def clear(self):\n self.current_iteration_count = 0\n\n iteration_counter = IterationCounter()\n\n def clear_counter(trainer, counter):\n counter.clear()\n\n trainer.add_event_handler(TrainingEvents.TRAINING_EPOCH_COMPLETED, _validate, validation_batches)\n trainer.add_event_handler(TrainingEvents.VALIDATION_STARTING, clear_counter, iteration_counter)\n trainer.add_event_handler(TrainingEvents.VALIDATION_ITERATION_STARTED, iteration_counter)\n\n trainer.run([1], max_epochs=max_epochs)\n assert iteration_counter.total_count == max_epochs * len(validation_batches)\n\n\ndef test_validate_is_not_called_by_default():\n trainer = Trainer(MagicMock(return_value=1), MagicMock())\n trainer.validate = MagicMock()\n\n max_epochs = 5\n trainer.run([1], max_epochs=max_epochs)\n assert trainer.validate.call_count == 0\n\n\ndef test_stopping_criterion_is_max_epochs():\n trainer = Trainer(MagicMock(return_value=1), MagicMock())\n max_epochs = 5\n trainer.run([1], max_epochs=max_epochs)\n assert trainer.current_epoch == max_epochs\n\n\ndef test_terminate_at_end_of_epoch_stops_training():\n max_epochs = 5\n last_epoch_to_run = 3\n\n def end_of_epoch_handler(trainer):\n if trainer.current_epoch == last_epoch_to_run:\n trainer.terminate()\n\n trainer = Trainer(MagicMock(return_value=1), MagicMock())\n trainer.add_event_handler(TrainingEvents.EPOCH_COMPLETED, end_of_epoch_handler)\n\n assert not trainer.should_terminate\n\n trainer.run([1], max_epochs=max_epochs)\n\n assert trainer.current_epoch == last_epoch_to_run + 1 # counter is incremented at end of loop\n assert trainer.should_terminate\n\n\ndef test_terminate_at_start_of_epoch_stops_training_after_completing_iteration():\n max_epochs = 5\n epoch_to_terminate_on = 3\n batches_per_epoch = [1, 2, 3]\n\n def start_of_epoch_handler(trainer):\n if trainer.current_epoch == epoch_to_terminate_on:\n trainer.terminate()\n\n trainer = Trainer(MagicMock(return_value=1), MagicMock())\n trainer.add_event_handler(TrainingEvents.EPOCH_STARTED, start_of_epoch_handler)\n\n assert not trainer.should_terminate\n\n trainer.run(batches_per_epoch, max_epochs=max_epochs)\n\n # epoch is not completed so counter is not incremented\n assert trainer.current_epoch == epoch_to_terminate_on\n assert trainer.should_terminate\n # completes first iteration\n assert trainer.current_iteration == (epoch_to_terminate_on * len(batches_per_epoch)) + 1\n\n\ndef test_terminate_stops_training_mid_epoch():\n num_iterations_per_epoch = 10\n iteration_to_stop = num_iterations_per_epoch + 3 # i.e. part way through the 2nd epoch\n trainer = Trainer(MagicMock(return_value=1), MagicMock())\n\n def end_of_iteration_handler(trainer):\n if trainer.current_iteration == iteration_to_stop:\n trainer.terminate()\n\n trainer.add_event_handler(TrainingEvents.TRAINING_ITERATION_STARTED, end_of_iteration_handler)\n trainer.run(training_data=[None] * num_iterations_per_epoch, max_epochs=3)\n assert (trainer.current_iteration == iteration_to_stop +\n 1) # completes the iteration when terminate called\n assert trainer.current_epoch == np.ceil(\n iteration_to_stop / num_iterations_per_epoch) - 1 # it starts from 0\n\n\ndef test_terminate_stops_trainer_when_called_during_validation():\n num_iterations_per_epoch = 10\n iteration_to_stop = 3 # i.e. part way through the 2nd validation run\n epoch_to_stop = 2\n trainer = Trainer(MagicMock(return_value=1), MagicMock(return_value=1))\n\n def end_of_iteration_handler(trainer):\n if (trainer.current_epoch == epoch_to_stop and trainer.current_validation_iteration == iteration_to_stop):\n\n trainer.terminate()\n\n trainer.add_event_handler(TrainingEvents.TRAINING_EPOCH_COMPLETED, _validate, [None] * num_iterations_per_epoch)\n trainer.add_event_handler(TrainingEvents.VALIDATION_ITERATION_STARTED, end_of_iteration_handler)\n trainer.run([None] * num_iterations_per_epoch, max_epochs=4)\n\n assert trainer.current_epoch == epoch_to_stop\n # should complete the iteration when terminate called\n assert trainer.current_validation_iteration == iteration_to_stop + 1\n assert trainer.current_iteration == (epoch_to_stop + 1) * num_iterations_per_epoch\n\n\ndef test_terminate_after_training_iteration_skips_validation_run():\n num_iterations_per_epoch = 10\n iteration_to_stop = num_iterations_per_epoch - 1\n trainer = Trainer(MagicMock(return_value=1), MagicMock())\n\n def end_of_iteration_handler(trainer):\n if trainer.current_iteration == iteration_to_stop:\n trainer.terminate()\n\n trainer.validate = MagicMock()\n\n trainer.add_event_handler(TrainingEvents.TRAINING_EPOCH_COMPLETED, _validate, MagicMock())\n trainer.add_event_handler(TrainingEvents.TRAINING_ITERATION_STARTED, end_of_iteration_handler)\n trainer.run([None] * num_iterations_per_epoch, max_epochs=3)\n assert trainer.validate.call_count == 0\n\n\ndef _create_mock_data_loader(epochs, batches_per_epoch):\n batches = [MagicMock()] * batches_per_epoch\n data_loader_manager = MagicMock()\n batch_iterators = [iter(batches) for _ in range(epochs)]\n\n data_loader_manager.__iter__.side_effect = batch_iterators\n\n return data_loader_manager\n\n\ndef test_training_iteration_events_are_fired():\n max_epochs = 5\n num_batches = 3\n training_data = _create_mock_data_loader(max_epochs, num_batches)\n\n trainer = Trainer(MagicMock(return_value=1), MagicMock())\n\n mock_manager = Mock()\n iteration_started = Mock()\n trainer.add_event_handler(TrainingEvents.TRAINING_ITERATION_STARTED, iteration_started)\n\n iteration_complete = Mock()\n trainer.add_event_handler(TrainingEvents.TRAINING_ITERATION_COMPLETED, iteration_complete)\n\n mock_manager.attach_mock(iteration_started, 'iteration_started')\n mock_manager.attach_mock(iteration_complete, 'iteration_complete')\n\n trainer.run(training_data, max_epochs=max_epochs)\n\n assert iteration_started.call_count == num_batches * max_epochs\n assert iteration_complete.call_count == num_batches * max_epochs\n\n expected_calls = []\n for i in range(max_epochs * num_batches):\n expected_calls.append(call.iteration_started(trainer))\n expected_calls.append(call.iteration_complete(trainer))\n\n assert mock_manager.mock_calls == expected_calls\n\n\ndef test_validation_iteration_events_are_fired():\n max_epochs = 5\n num_batches = 3\n validation_data = _create_mock_data_loader(max_epochs, num_batches)\n\n trainer = Trainer(MagicMock(return_value=1), MagicMock(return_value=1))\n\n mock_manager = Mock()\n iteration_started = Mock()\n trainer.add_event_handler(TrainingEvents.VALIDATION_ITERATION_STARTED, iteration_started)\n\n iteration_complete = Mock()\n trainer.add_event_handler(TrainingEvents.TRAINING_EPOCH_COMPLETED, _validate, validation_data)\n trainer.add_event_handler(TrainingEvents.VALIDATION_ITERATION_COMPLETED, iteration_complete)\n\n mock_manager.attach_mock(iteration_started, 'iteration_started')\n mock_manager.attach_mock(iteration_complete, 'iteration_complete')\n\n trainer.run([None], max_epochs=max_epochs)\n\n assert iteration_started.call_count == num_batches * max_epochs\n assert iteration_complete.call_count == num_batches * max_epochs\n\n expected_calls = []\n for i in range(max_epochs * num_batches):\n expected_calls.append(call.iteration_started(trainer))\n expected_calls.append(call.iteration_complete(trainer))\n\n assert mock_manager.mock_calls == expected_calls\n\n\ndef test_validation_iteration_events_are_fired_when_validate_is_called_explicitly():\n max_epochs = 5\n num_batches = 3\n validation_data = _create_mock_data_loader(max_epochs, num_batches)\n\n trainer = Trainer(MagicMock(), MagicMock(return_value=1))\n\n mock_manager = Mock()\n iteration_started = Mock()\n trainer.add_event_handler(TrainingEvents.VALIDATION_ITERATION_STARTED, iteration_started)\n\n iteration_complete = Mock()\n trainer.add_event_handler(TrainingEvents.VALIDATION_ITERATION_COMPLETED, iteration_complete)\n\n mock_manager.attach_mock(iteration_started, 'iteration_started')\n mock_manager.attach_mock(iteration_complete, 'iteration_complete')\n\n assert iteration_started.call_count == 0\n assert iteration_complete.call_count == 0\n\n trainer.validate(validation_data)\n\n assert iteration_started.call_count == num_batches\n assert iteration_complete.call_count == num_batches\n\n # TODO add test to assure history is written to from trainer\n\n\ndef test_create_supervised():\n model = Linear(1, 1)\n model.weight.data.zero_()\n model.bias.data.zero_()\n optimizer = SGD(model.parameters(), 0.1)\n trainer = create_supervised(model, optimizer, mse_loss)\n\n x = torch.FloatTensor([[1.0], [2.0]])\n y = torch.FloatTensor([[3.0], [5.0]])\n data = [(x, y)]\n\n trainer.validate(data)\n y_pred, y = trainer.validation_history[0]\n\n assert y_pred[0, 0] == approx(0.0)\n assert y_pred[1, 0] == approx(0.0)\n assert y[0, 0] == approx(3.0)\n assert y[1, 0] == approx(5.0)\n\n assert model.weight.data[0, 0] == approx(0.0)\n assert model.bias.data[0] == approx(0.0)\n\n trainer.run(data)\n loss = trainer.training_history[0]\n\n assert loss == approx(17.0)\n assert model.weight.data[0, 0] == approx(1.3)\n assert model.bias.data[0] == approx(0.8)\n\n\ndef test_on_decorator():\n max_epochs = 5\n num_batches = 3\n training_data = _create_mock_data_loader(max_epochs, num_batches)\n\n trainer = Trainer(MagicMock(return_value=1), MagicMock())\n\n class Counter(object):\n def __init__(self, count=0):\n self.count = count\n\n started_counter = Counter()\n\n @trainer.on(TrainingEvents.TRAINING_ITERATION_STARTED, started_counter)\n def handle_training_iteration_started(trainer, started_counter):\n started_counter.count += 1\n\n completed_counter = Counter()\n\n @trainer.on(TrainingEvents.TRAINING_ITERATION_COMPLETED, completed_counter)\n def handle_training_iteration_completed(trainer, completed_counter):\n completed_counter.count += 1\n\n trainer.run(training_data, max_epochs=max_epochs)\n\n assert started_counter.count == 15\n assert completed_counter.count == 15\n","sub_path":"tests/ignite/trainer/test_trainer.py","file_name":"test_trainer.py","file_ext":"py","file_size_in_byte":14974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"449919675","text":"import flask_restful\nfrom database import engine\nfrom flask import Response, request\nfrom api.models.m_ph import PHMeasuredValM\nfrom database import engine, db_session\nfrom api.models.m_projezd import ZakladniProjezd\nfrom flask import Response, request, make_response, jsonify\nimport pandas as pd\nfrom datetime import datetime\nimport time\n\n'''\nNáhrada tabulky vyhodnocení provoz\n'''\n\nclass PhNote(flask_restful.Resource):\n def put(self, id):\n ph = PHMeasuredValM.query.filter_by(id = id).first()\n ph.note = request.get_json()['note']\n db_session.commit()\n return make_response()\n\n# GET http://localhost:5000/api/ph/seznam//\nclass PhVyhodnoceniProvoz(flask_restful.Resource):\n def get(self, rok, kgjId = None):\n\n\n sql = \"select kmmv.id_kgj as id_kgj, \" \\\n \"nazev, \" \\\n \"year(from_unixtime(kmmv.date_record)) as year, \" \\\n \"month(from_unixtime(kmmv.date_record)) as month, \" \\\n \"mth_poc, \" \\\n \"v_tep_so, \" \\\n \"v_tep_to, \" \\\n \"v_el_celkem, \" \\\n \"ph_m_ote_el.ote_el_dodavka, \" \\\n \"ph_m_ote_el.ote_el_odber, \" \\\n \"s_el_vskjchod, \" \\\n \"ifnull(spaltep_distrib, 10.67) as spaltep_distrib, \" \\\n \"s_ply_mer_kgj_m3 \" \\\n \"from ph_m_measured_val kmmv \" \\\n \"left outer join kgj_cons as kk on kmmv.id_kgj = kk.id \" \\\n \"left outer join ph_m_ote_el on kmmv.id_kgj = ph_m_ote_el.id_kgj and kmmv.date_record = ph_m_ote_el.date_record \" \\\n \"left join ph_m_spal_tep on kk.id_distrib_obl_ply = ph_m_spal_tep.id_distrib_obl and ph_m_spal_tep.date_record = kmmv.date_record\"\n\n\n if kgjId != None and kgjId != 0:\n sql += \" where kmmv.id_kgj = %s order by year desc\" % (kgjId)\n else:\n sql += \" where year(from_unixtime(kmmv.date_record)) = %s order by nazev collate utf8_czech_ci\" % (rok)\n\n df = pd.read_sql(sql, engine)\n\n response = Response(response=df.to_json(orient='records'), status=200, mimetype=\"application/json\")\n # response = Response(status=200, mimetype=\"application/json\")\n return response\n\n\n'''\nTabulka přehled PH, zobrazování kopletní tabulky s daty exportovanými z PH do DB\n'''\n# GET http://localhost:5000/api/ph/dataview\nclass PhDataView(flask_restful.Resource):\n def get(self, year, month):\n global param\n kgj_id = str(request.args.get('id'))\n pwr_category = str(request.args.get('vykon'))\n rv_user_id = str(request.args.get('regVed'))\n\n print(year, month)\n if not kgj_id:\n kgj_id = '0'\n\n # Selecting power category\n if pwr_category != '0':\n pwr_cat_f = pwr_category_select(int(pwr_category))[0]\n pwr_cat_l = pwr_category_select(int(pwr_category))[1]\n else:\n pwr_cat_f = 0\n pwr_cat_l = 0\n\n # Main decision script for Select boxes\n \"\"\" When month = 13 (all) select data from all year\"\"\"\n if month == '13':\n month = None\n if kgj_id == '0':\n if pwr_category == '0':\n if rv_user_id == '0':\n param = 0\n else:\n param = 2\n else:\n if rv_user_id == '0':\n param = 3\n else:\n param = 4\n else:\n param = 1\n\n if (month != '13' and month!= None):\n if kgj_id == '0':\n if pwr_category == '0':\n if rv_user_id == '0':\n param = 0\n else:\n param = 2\n else:\n if rv_user_id == '0':\n param = 3\n else:\n param = 4\n else:\n param = 1\n\n # SQL Builder\n sql = build_sql_query(kgj_id, year, month, rv_user_id, pwr_cat_f, pwr_cat_l, param)\n df = pd.read_sql(sql, engine)\n\n df['v_tep_celkem'] = df['v_tep_so'] + df['v_tep_to']\n try:\n df['n_ply_fakt_kgj_kwh'] = round(df['n_ply_fakt_kgj_m3'] * df['spaltep'] * 0.9, 0)\n except:\n try:\n df['n_ply_fakt_kgj_kwh'] = round(df['n_ply_fakt_kgj_m3'] * df['spaltep_distr'] * 0.9, 0)\n except:\n df['n_ply_fakt_kgj_kwh'] = df['n_ply_fakt_kgj_m3'].astype(float).round(0) * 0.9 * 10.67\n\n df['mth_ote'] = df['v_el_celkem'] / df['lic_el']\n df['mth_ote'] = df['mth_ote'].apply(pd.np.ceil)\n try:\n df['s_ply_mer_kgj_kwh'] = round(df['s_ply_mer_kgj_m3'] * df['spaltep'] * 0.9, 0)\n except:\n try:\n df['s_ply_mer_kgj_kwh'] = round(df['s_ply_mer_kgj_m3'] * df['spaltep_distr'] * 0.9, 0)\n except:\n df['s_ply_mer_kgj_kwh'] = df['s_ply_mer_kgj_m3'].astype(float).round(0) * 0.9 * 10.67\n\n response = Response(response=df.to_json(orient='records'), status=200, mimetype=\"application/json\")\n return response\n\n\n# Build SQL query based on selected parameter.\ndef build_sql_query(kgj_id, year, month, rv_id, pwr_cat_f, pwr_cat_l, param):\n global where_param\n sql = \"\"\"select ph_m_measured_val.*, \n concat_ws('-',\n LPAD(day(FROM_UNIXTIME(ph_m_measured_val.date_record)),2,0),\n LPAD(month(FROM_UNIXTIME(ph_m_measured_val.date_record)),2,0),\n year(FROM_UNIXTIME(ph_m_measured_val.date_record))) as date_record_r,\n concat(concat_ws('-',\n LPAD(day(FROM_UNIXTIME(ph_m_measured_val.timestamp)),2,0),\n LPAD(month(FROM_UNIXTIME(ph_m_measured_val.timestamp)),2,0),\n year(FROM_UNIXTIME(ph_m_measured_val.timestamp))),' ',\n concat_ws(':',\n LPAD(hour(FROM_UNIXTIME(ph_m_measured_val.timestamp)),2,0),\n LPAD(minute(FROM_UNIXTIME(ph_m_measured_val.timestamp)),2,0))) as timestamp_r, \n kk.nazev,\n kk.lic_el,\n ph_m_fakt_gas.f_plyn as n_ply_fakt_kgj_m3,\n ph_m_fakt_gas.f_spaltep as spaltep,\n ph_m_ote_el.ote_el_dodavka as p_el_ote,\n ph_m_ote_el.ote_el_odber as n_el_ote\n FROM ph_m_measured_val\n left join kgj_cons kk on kk.id = ph_m_measured_val.id_kgj\n left join ph_m_fakt_gas on ph_m_fakt_gas.id_kgj = ph_m_measured_val.id_kgj and ph_m_fakt_gas.date_record = ph_m_measured_val.date_record \n left join ph_m_ote_el on ph_m_ote_el.id_kgj = ph_m_measured_val.id_kgj and ph_m_ote_el.date_record = ph_m_measured_val.date_record\n left join ph_m_spal_tep on ph_m_spal_tep.id_distrib_obl = kk.id_distrib_obl_ply and ph_m_spal_tep.date_record = ph_m_measured_val.date_record \"\"\"\n\n # Sorting param\n sorting = ' order by kk.nazev collate utf8_czech_ci'\n\n # Date WHERE param selector\n if month == None:\n time_param = \"where year(FROM_UNIXTIME(ph_m_measured_val.date_record)) = {} \".format(year)\n\n else:\n time_param = \"where year(FROM_UNIXTIME(ph_m_measured_val.date_record)) = {} and month(FROM_UNIXTIME(ph_m_measured_val.date_record)) = {} \".format(\n year, month)\n\n\n # Selecting where param\n if param == 0:\n where_param = \"\"\n\n if param == 1:\n where_param = \"and kk.id = {}\".format(kgj_id)\n\n if param == 2:\n where_param = \"and kk.id_regio_vedouci = {}\".format(rv_id)\n\n if param == 3:\n where_param = \"and kk.inst_vykon >{} and kk.inst_vykon <= {}\".format(pwr_cat_f, pwr_cat_l)\n\n if param == 4:\n where_param = \"and kk.id_regio_vedouci = {} and kk.inst_vykon > {} and kk.inst_vykon <= {}\".format(\n rv_id, pwr_cat_f, pwr_cat_l)\n\n return sql + time_param + where_param + sorting\n\n\ndef pwr_category_select(pwr_cat_id):\n # <100\n if pwr_cat_id == 1:\n return [0, 99]\n\n # 100-200\n if pwr_cat_id == 2:\n return [100, 200]\n\n # 400\n if pwr_cat_id == 3:\n return [201, 400]\n\n # 600\n if pwr_cat_id == 4:\n return [401, 600]\n\n # 800\n if pwr_cat_id == 5:\n return [601, 800]\n\n # 1000\n if pwr_cat_id == 6:\n return [801, 1000]\n\n # 1600\n if pwr_cat_id == 7:\n return [1001, 1600]\n\n # 2000\n if pwr_cat_id == 8:\n return [1601, 2014]\n\n","sub_path":"api/ph/c_ph.py","file_name":"c_ph.py","file_ext":"py","file_size_in_byte":8728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"226393727","text":"from tkinter import *\nfrom tkinter import ttk\n\nimport displaytable as disp\nimport SISdatabase\n\n\nclass DashboardGUI:\n def __init__(self, frame):\n self.dashboard_cont_frame = frame\n\n self.student_dshbrd_img = PhotoImage(file=r\"images\\dashboardstud.png\")\n student_count_dash = Label(self.dashboard_cont_frame, image=self.student_dshbrd_img)\n student_count_dash.photo = self.student_dshbrd_img\n student_count_dash.place(x=20, y=20, width=250, height=120)\n self.student_count = Label(self.dashboard_cont_frame, text=\"1000\", font=(\"Blinker\", 40, \"bold\"),\n fg=\"#A51d23\", bg=\"#FA9412\")\n self.student_count.place(x=20, y=20, width=140, height=77)\n\n self.course_dshbrd_img = PhotoImage(file=r\"images\\dashboardcourse.png\")\n course_count_dash = Label(self.dashboard_cont_frame, image=self.course_dshbrd_img)\n course_count_dash.photo = self.course_dshbrd_img\n course_count_dash.place(x=290, y=20, width=250, height=120)\n self.course_count = Label(self.dashboard_cont_frame, text=\"0\", font=(\"Blinker\", 40, \"bold\"),\n bg=\"#A51d23\", fg=\"#FA9412\")\n self.course_count.place(x=290, y=20, width=140, height=77)\n\n self.bg_frame = Frame(self.dashboard_cont_frame, bg=\"white\")\n\n self.stud_list_label = Label(self.dashboard_cont_frame, bg=\"#A51d23\", fg=\"white\",\n text=\" LIST OF STUDENTS\", font=(\"Blinker\", 15, \"bold\"), anchor=\"w\")\n self.stud_list_frame = Frame(self.dashboard_cont_frame, bg=\"white\", highlightbackground=\"#A51d23\",\n highlightthickness=2)\n\n self.course_label = Label(self.dashboard_cont_frame, bg=\"#A51d23\", fg=\"white\",\n text=\" LIST OF COURSES\", font=(\"Blinker\", 15, \"bold\"), anchor=\"w\")\n self.course_list_frame = Frame(self.dashboard_cont_frame, bg=\"white\", highlightbackground=\"#A51d23\",\n highlightthickness=2)\n\n scroll_x_stud_list = Scrollbar(self.stud_list_frame, orient=HORIZONTAL)\n scroll_y_stud_list = Scrollbar(self.stud_list_frame, orient=VERTICAL)\n\n scroll_x_course_list = Scrollbar(self.course_list_frame, orient=HORIZONTAL)\n scroll_y_course_list = Scrollbar(self.course_list_frame, orient=VERTICAL)\n self.student_table = ttk.Treeview(self.stud_list_frame, xscrollcommand=scroll_x_stud_list.set,\n yscrollcommand=scroll_y_stud_list.set, columns=(\"id_no\", \"name\",\n \"course_code\", \"year\",\n \"gender\"))\n scroll_x_stud_list.pack(side=BOTTOM, fill=X)\n scroll_y_stud_list.pack(side=RIGHT, fill=Y)\n scroll_x_stud_list.config(command=self.student_table.xview)\n scroll_y_stud_list.config(command=self.student_table.yview)\n self.student_table.heading(\"id_no\", text=\"ID Number\")\n self.student_table.heading(\"name\", text=\"Name\")\n self.student_table.heading(\"course_code\", text=\"Course Code\")\n self.student_table.heading(\"year\", text=\"Year\")\n self.student_table.heading(\"gender\", text=\"Gender\")\n self.student_table['show'] = 'headings'\n self.student_table.column(\"id_no\", width=70)\n self.student_table.column(\"name\", width=190)\n self.student_table.column(\"course_code\", width=100)\n self.student_table.column(\"year\", width=70)\n self.student_table.column(\"gender\", width=70)\n\n self.student_table.pack(fill=BOTH, expand=1)\n\n self.course_table = ttk.Treeview(self.course_list_frame, xscrollcommand=scroll_x_course_list.set,\n yscrollcommand=scroll_y_course_list.set, columns=(\"course_code\",\n \"course\"))\n scroll_x_course_list.pack(side=BOTTOM, fill=X)\n scroll_y_course_list.pack(side=RIGHT, fill=Y)\n scroll_x_course_list.config(command=self.course_table.xview)\n scroll_y_course_list.config(command=self.course_table.yview)\n self.course_table.heading(\"course_code\", text=\"Course Code\")\n self.course_table.heading(\"course\", text=\"Course\")\n self.course_table['show'] = 'headings'\n self.course_table.column(\"course_code\", width=50)\n self.course_table.column(\"course\", width=200)\n\n self.course_table.pack(fill=BOTH, expand=1)\n\n self.max_student_img = PhotoImage(file=r\"images\\max.png\").subsample(5, 5)\n self.max_course_img = PhotoImage(file=r\"images\\max.png\").subsample(5, 5)\n self.max_student_button = Button(self.dashboard_cont_frame, command=self.max_student_table, relief=FLAT,\n bg=\"#A51d23\", activebackground=\"#A51d23\", image=self.max_student_img)\n self.max_course_button = Button(self.dashboard_cont_frame, command=self.max_course_table, relief=FLAT,\n bg=\"#A51d23\", activebackground=\"#A51d23\", image=self.max_course_img)\n\n self.min_image = PhotoImage(file=r\"images\\min.png\").subsample(5, 5)\n self.min_button = Button(self.dashboard_cont_frame, command=self.default_layout, relief=FLAT,\n fg=\"white\", bg=\"#A51d23\", activeforeground=\"white\", activebackground=\"#A51d23\",\n image=self.min_image)\n self.min_button.photo = self.min_image\n\n self.default_layout()\n self.count_data()\n disp.display_student_table(self.student_table)\n disp.display_course_table(self.course_table)\n\n def default_layout(self):\n self.min_button.place_forget()\n self.max_student_button.place(x=530, y=190, height=30, width=30)\n self.max_course_button.place(x=840, y=190, height=30, width=30)\n self.bg_frame.place(x=10, y=190, height=350, width=880)\n self.stud_list_label.place_configure(x=20, y=190, width=550, height=30)\n self.stud_list_frame.place_configure(x=20, y=220, width=550, height=320)\n self.course_label.place_configure(x=580, y=190, width=300, height=30)\n self.course_list_frame.place_configure(x=580, y=220, width=300, height=320)\n\n def count_data(self):\n self.student_count.config(text=len(SISdatabase.view_student_rec()))\n self.course_count.config(text=len(SISdatabase.view_course_rec()))\n\n def max_student_table(self):\n self.hide_widgets()\n self.stud_list_label.place_configure(x=20, y=190, width=860, height=30)\n self.stud_list_frame.place_configure(x=20, y=220, width=860, height=320)\n self.min_button.place(x=840, y=190, height=30, width=30)\n\n def max_course_table(self):\n self.hide_widgets()\n self.course_label.place_configure(x=20, y=190, width=860, height=30)\n self.course_list_frame.place_configure(x=20, y=220, width=860, height=320)\n self.min_button.place(x=840, y=190, height=30, width=30)\n\n def hide_widgets(self):\n self.stud_list_label.place_forget()\n self.stud_list_frame.place_forget()\n self.max_student_button.place_forget()\n self.max_course_button.place_forget()\n self.course_list_frame.place_forget()\n self.course_label.place_forget()\n","sub_path":"DashboardGUI.py","file_name":"DashboardGUI.py","file_ext":"py","file_size_in_byte":7432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"367696169","text":"import configparser\nfrom src.Service.Networks.load_model import buildModels\nfrom src.Controller.DealRequest.DealRequest import dealInput1, dealInput2\n\nconfig=configparser.ConfigParser()\nconfig.read(\"ServerConfig.ini\")\nModels = buildModels()\n\n\ndef test1():\n\tdata = {}\n\tdata['sf'] = 10.6\n\tdata['hf'] = 2.32\n\tdata['hff'] = 78.98\n\tdata['gdt'] = 14.43\n\tdata['C'] = 46.5\n\tdata['H'] = 5.54\n\tdata['O'] = 41.4\n\tdata['lj'] = 2.0\n\tdata['lg'] = 800.0\n\tdata['nj'] = 500.0\n\tdata['dlb'] = 0.3\n\tprint(dealInput1(data, config, Models))\n\ndef test2():\n\tdata = {}\n\tdata['sf'] = 10.6\n\tdata['hf'] = 2.32\n\tdata['hff'] = 70.8\n\tdata['gdt'] = 16.28\n\tdata['C'] = 54.4\n\tdata['H'] = 5.78\n\tdata['O'] = 39.4\n\tdata['rlxhsl'] = 70\n\t#data['var1'] = 1\n\t#data['var1Value'] = 50.0\n\t'''\n\tdata['var0'] = 1\n\tdata['var1'] = 1\n\tdata['var2'] = 1\n\tdata['var0Value'] = 800.0\n\tdata['var1Value'] = 50.0\n\tdata['var2Value'] = 8.0\n\t'''\n\tdata['prefer0'] = 1\n\tdata['prefer0Value'] = 20\n\tdata['prefer0-level'] = 1\n\tdata['prefer1'] = 1\n\tdata['prefer1Value'] = 60\n\tdata['prefer1-level'] = 2\n\tprint(dealInput2(data, config, Models))\n\n#test1()\ntest2()","sub_path":"src/back-end/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"24904619","text":"\"\"\"core pyvger objects.\"\"\"\nfrom decimal import Decimal\nimport warnings\n\nimport arrow\n\nimport cx_Oracle as cx\n\nimport pymarc\n\nimport six.moves.configparser as configparser\n\nimport sqlalchemy as sqla\n\nfrom pyvger.constants import RELATIONS, TABLE_NAMES\nfrom pyvger.exceptions import (\n BatchCatNotAvailableError,\n NoSuchItemException,\n PyVgerException,\n)\n\ntry:\n from pyvger import batchcat\nexcept BatchCatNotAvailableError:\n batchcat = None\n\n\nclass Voy(object):\n \"\"\"\n Interface to Voyager system.\n\n :param oracle_database: database name prefix\n :param config: configuration file path\n :param oracleuser: user name for Voyager Oracle account\n :param oraclepass: password for oracleuser account\n :param oracledsn: DSN used to connect to Oracle\n :param voy_username: Voyager username to login via BatchCat\n :param voy_password: Voyager password to login via BatchCat\n :param voy_path: path to directory containing Voyager.ini for BatchCat\n :param cat_location: location name of cataloging location\n :param library_id: library ID number\n \"\"\"\n\n def __init__(self, oracle_database=\"pittdb\", config=None, **kwargs):\n self.connection = None\n self.oracle_database = oracle_database\n cfg = {}\n if config is not None:\n cf = configparser.ConfigParser()\n cf.read(config)\n config_keys = [\n \"oracleuser\",\n \"oraclepass\",\n \"oracledsn\",\n \"voy_username\",\n \"voy_password\",\n \"voy_path\",\n \"cat_location\",\n \"library_id\",\n ]\n for item in config_keys:\n val = cf.get(\"Voyager\", item, fallback=\"\", raw=True).strip('\"')\n if val:\n cfg[item] = val\n if cf.get(\"Voyager\", \"connectstring\") and \"oracledsn\" not in cfg:\n cfg[\"oracledsn\"] = cf.get(\"Voyager\", \"connectstring\", raw=True).strip(\n '\"'\n )\n\n cfg.update(kwargs)\n\n if all(arg in cfg for arg in [\"oracleuser\", \"oraclepass\", \"oracledsn\"]):\n self.connection = cx.connect(\n cfg[\"oracleuser\"], cfg[\"oraclepass\"], cfg[\"oracledsn\"]\n )\n self.engine = sqla.create_engine(\n \"oracle://\", creator=lambda: self.connection\n )\n metadata = sqla.MetaData()\n tables_to_load = TABLE_NAMES\n\n self.tables = {}\n for table_name in tables_to_load:\n self.tables[table_name] = sqla.Table(\n table_name,\n metadata,\n schema=oracle_database,\n autoload=True,\n autoload_with=self.engine,\n )\n\n for parent, foreign in RELATIONS:\n parent_column = getattr(self.tables[parent[0]].c, parent[1])\n foreign_key = getattr(self.tables[foreign[0]].c, foreign[1])\n parent_column.append_foreign_key(sqla.ForeignKey(foreign_key))\n\n self.cat_location = cfg.get(\"cat_location\")\n self.library_id = cfg.get(\"library_id\")\n\n if \"voy_path\" not in cfg:\n cfg[\"voy_path\"] = r\"C:\\Voyager\"\n\n if batchcat is not None and all(\n arg in cfg for arg in [\"voy_username\", \"voy_password\"]\n ):\n self.batchcat = batchcat.BatchCatClient(\n username=cfg[\"voy_username\"],\n password=cfg[\"voy_password\"],\n voy_interface=self,\n apppath=cfg[\"voy_path\"],\n )\n else:\n self.batchcat = None\n\n def get_raw_bib(self, bibid):\n \"\"\"Get raw MARC for a bibliographic record.\n\n :param bibid:\n :return: bytes of bib record\n \"\"\"\n if self.connection:\n curs = self.connection.cursor()\n res = curs.execute(\n \"\"\"SELECT\n utl_i18n.string_to_raw(bib_data.record_segment)\n as record_segment\n FROM %(db)s.bib_data\n WHERE bib_data.bib_id=:bib ORDER BY seqnum\"\"\"\n % {\"db\": self.oracle_database},\n {\"bib\": bibid},\n )\n marc_segments = []\n for data in res:\n marc_segments.append(data[0])\n return b\"\".join(marc_segments)\n\n def get_bib(self, bibid):\n \"\"\"Get a bibliographic record.\n\n :param bibid: Voyager bibliographic record ID\n :return: pyvger.core.BibRecord object\n \"\"\"\n if self.connection:\n curs = self.connection.cursor()\n try:\n res = curs.execute(\n \"\"\"SELECT DISTINCT utl_i18n.string_to_raw(bib_data.record_segment) as record_segment,\n bib_master.suppress_in_opac, MAX(action_date) over (partition by bib_history.bib_id) maxdate,\n bib_data.seqnum FROM %(db)s.BIB_HISTORY JOIN %(db)s.bib_master\n on bib_history.bib_id = bib_master.bib_id JOIN %(db)s.bib_data\n ON bib_master.bib_id = bib_data.bib_id WHERE bib_history.BIB_ID = :bib\n ORDER BY seqnum\"\"\"\n % {\"db\": self.oracle_database},\n {\"bib\": bibid},\n )\n marc_segments = []\n data = None\n for data in res:\n marc_segments.append(data[0])\n marc = b\"\".join(marc_segments)\n if not marc:\n raise PyVgerException(\"No MARC data for bib %s\" % bibid)\n rec = next(pymarc.MARCReader(marc))\n if data[1] == \"Y\":\n suppress = True\n elif data[1] == \"N\":\n suppress = False\n else:\n raise PyVgerException(\n \"Bad suppression value %r for bib %s\" % (data[1], bibid)\n )\n last_date = arrow.get(data[2]).datetime\n return BibRecord(rec, suppress, bibid, self, last_date)\n\n except Exception:\n print(\"error for bibid |%r|\" % bibid)\n raise\n\n def get_mfhd(self, mfhdid):\n \"\"\"Get a HoldingsRecord object for the given Voyager mfhd number.\n\n :param mfhdid: Voyager holdings ID to fetch\n :return:\n \"\"\"\n if self.connection:\n curs = self.connection.cursor()\n res = curs.execute(\n \"\"\"SELECT DISTINCT utl_i18n.string_to_raw(record_segment)\n as record_segment,\n mfhd_master.suppress_in_opac,\n location.location_code,\n location.location_display_name,\n MAX(action_date) over (partition by mfhd_history.mfhd_id) maxdate,\n mfhd_data.seqnum\n FROM %(db)s.mfhd_data, %(db)s.mfhd_master, %(db)s.location, %(db)s.mfhd_history\n WHERE mfhd_data.mfhd_id=:mfhd\n AND mfhd_data.mfhd_id = mfhd_master.mfhd_id\n AND location.location_id = mfhd_master.location_id\n AND mfhd_history.mfhd_id = mfhd_master.mfhd_id\n ORDER BY seqnum\"\"\"\n % {\"db\": self.oracle_database},\n {\"mfhd\": mfhdid},\n )\n marc_segments = []\n data = None\n for data in res:\n marc_segments.append(data[0])\n marc = b\"\".join(marc_segments)\n if not marc:\n raise PyVgerException(\"No MARC data for MFHD %s\" % mfhdid)\n try:\n rec = next(pymarc.MARCReader(marc))\n except Exception as e:\n raise PyVgerException from e\n\n if data[1] == \"Y\":\n suppress = True\n elif data[1] == \"N\":\n suppress = False\n else:\n raise PyVgerException(\n \"Bad suppression value %r for mfhd %s\" % (data[1], mfhdid)\n )\n last_date = arrow.get(data[4]).datetime\n return HoldingsRecord(\n rec, suppress, mfhdid, self, data[2], data[3], last_date\n )\n\n def iter_mfhds(self, locations=None, lib_id=None, include_suppressed=False, last=None):\n \"\"\"Iterate over all of the holdings in the given locations.\n\n You must provide exactly one of locations or lib_id\n\n :param locations: list of locations to iterate over\n :param lib_id: library ID to iterate over instead of using locations\n :param include_suppressed: whether suppressed records should be included\n :param last: last record number processed, to skip ahead\n :return: iterator of HoldingsRecord objects\n\n \"\"\"\n mm = self.tables[\"mfhd_master\"]\n if locations and lib_id is None:\n where_clause = mm.c.location_id.in_(locations)\n elif lib_id:\n where_clause = sqla.and_(\n self.tables[\"location\"].c.library_id == lib_id,\n mm.c.location_id == self.tables[\"location\"].c.location_id,\n )\n else:\n raise ValueError(\"must provide locations or lib_id, and not both\")\n if not include_suppressed:\n where_clause = sqla.and_(mm.c.suppress_in_opac == \"N\", where_clause)\n if last is not None:\n where_clause = sqla.and_(mm.c.mfhd_id > last, where_clause)\n q = sqla.select([mm.c.mfhd_id], whereclause=where_clause).order_by(mm.c.mfhd_id)\n r = self.engine.execute(q)\n for row in r:\n try:\n yield self.get_mfhd(row[0])\n except PyVgerException:\n warnings.warn(\"Skipping record %s\" % row[0])\n\n def iter_bibs(self, locations=None, lib_id=None, include_suppressed=False):\n \"\"\"Iterate over all of the bibs in the given locations.\n\n You must provide exactly one of locations or lib_id.\n\n :param locations: list of locations to iterate over\n :param lib_id: library ID to iterate over instead of using locations\n :param include_suppressed: whether suppressed records should be included\n :return: iterator of BibRecord objects\n\n \"\"\"\n bl = self.tables[\"bib_location\"]\n bm = self.tables[\"bib_master\"]\n if locations and lib_id is None:\n q = bl.select(bl.c.location_id.in_(locations))\n elif lib_id:\n q = bm.select(bm.c.library_id == lib_id)\n else:\n raise ValueError(\"must provide locations or lib_id, and not both\")\n if not include_suppressed:\n q = q.where(\n sqla.and_(bm.c.suppress_in_opac == \"N\", bm.c.bib_id == bl.c.bib_id)\n )\n r = self.engine.execute(q)\n for row in r:\n try:\n yield self.get_bib(row[0])\n except UnicodeDecodeError:\n continue\n\n def iter_items(\n self, locations, include_temporary=False, include_suppressed_mfhd=False\n ):\n \"\"\"Iterate over the item records in one or more locations.\n\n :param locations: list of locations to iterate over\n :param include_temporary: bool whether to include items with temporary locations in locations list\n :param include_suppressed_mfhd: bool, whether to include items attached to a suppressed MFHD\n \"\"\"\n item_table = self.tables[\"item\"]\n where_clause = item_table.c.perm_location.in_(locations)\n if include_temporary:\n where_clause = sqla.or_(\n where_clause, item_table.c.temp_location.in_(locations)\n )\n if not include_suppressed_mfhd:\n where_clause = sqla.and_(\n self.tables[\"mfhd_master\"].c.suppress_in_opac == \"N\", where_clause\n )\n q = sqla.select(\n [item_table.c.item_id],\n whereclause=where_clause,\n from_obj=[\n item_table.join(self.tables[\"mfhd_item\"]).join(\n self.tables[\"mfhd_master\"]\n )\n ],\n )\n r = self.engine.execute(q)\n for row in r:\n yield self.get_item(row[0])\n\n def get_item(self, item_id=None, barcode=None):\n \"\"\"\n Get an item record from Voyager.\n\n :param int item_id:\n :param str barcode:\n :return: ItemRecord -- the item\n \"\"\"\n if item_id is not None:\n return ItemRecord.from_id(item_id, self)\n else:\n return ItemRecord.from_barcode(barcode, self)\n\n def get_item_statuses(self, item_id):\n \"\"\"\n Get the statuses from a single item.\n\n :param int item_id:\n :return: list(str) -- statuses\n \"\"\"\n query = (\n sqla.sql.select([self.tables[\"item_status_type\"].c.item_status_desc])\n .select_from(\n self.tables[\"item_status\"].join(self.tables[\"item_status_type\"])\n )\n .where(self.tables[\"item_status\"].c.item_id == item_id)\n )\n r = self.engine.execute(query)\n return [row[0] for row in r]\n\n def bib_id_for_item(self, item_id):\n \"\"\"\n Get the bibliographic record ID associated with an item record.\n\n :param int item_id: the Voyager item ID\n :return: int: the bib ID\n \"\"\"\n query = (\n sqla.sql.select([self.tables[\"bib_mfhd\"].c.bib_id])\n .select_from(self.tables[\"mfhd_item\"].join(self.tables[\"bib_mfhd\"]))\n .where(self.tables[\"mfhd_item\"].c.item_id == item_id)\n )\n\n result = self.engine.execute(query)\n (row,) = result\n return row[0]\n\n def get_bib_create_datetime(self, bib_id):\n \"\"\"Get date when a record was added.\n\n :param int bib_id: the Voyager bib id\n :return: datetime.datetime: when the record was added\n \"\"\"\n bmt = self.tables[\"bib_master\"]\n query = bmt.select().where(bmt.c.bib_id == bib_id)\n result = self.engine.execute(query)\n (row,) = result\n return row.create_date\n\n def get_location_id(self, location):\n \"\"\"Get numeric ID for location.\n\n :param location: Voyager location code\n :return: int: numeric location id\n \"\"\"\n query = (\n self.tables[\"location\"]\n .select()\n .where(self.tables[\"location\"].c.location_code == location)\n )\n result = self.engine.execute(query)\n (row,) = result\n return int(row.location_id)\n\n\nclass BibRecord(object):\n \"\"\"\n A voyager bibliographic record.\n\n :param record: a valid MARC bibliographic record\n :param suppressed: boolean; whether the record is suppressed in OPAC\n :param bibid: bibliographic record ID\n :param voyager_interface: Voy object to which this record belongs\n :param last_date: datetime.datetime of last update from BIB_HISTORY table\n\n WARNING: last_date should have its tzinfo set to UTC even if the naive time in the database is \"really\"\n from another timezone. The Voyager database doesn't know what timezone is being used, and the\n win32com methods used for BatchCat will convert non-UTC datetimes to UTC, then the server\n will ignore the TZ and fail because it thinks your datetime is off by your local offset.\n \"\"\"\n\n def __init__(self, record, suppressed, bibid, voyager_interface, last_date=None):\n self.record = record\n self.suppressed = suppressed\n self.bibid = bibid\n self.last_date = last_date\n self.interface = voyager_interface\n\n def __getattr__(self, item):\n \"\"\"Pass on attributes of the pymarc record.\"\"\"\n if hasattr(self.record, item):\n return getattr(self.record, item)\n\n def __getitem__(self, item):\n \"\"\"Pass on item access for the pymarc record.\"\"\"\n return self.record[item]\n\n def holdings(self):\n \"\"\"Get the holdings for this bibliographic record.\n\n :return: a list of HoldingsRecord objects\n \"\"\"\n curs = self.interface.connection.cursor()\n result = curs.execute(\n \"\"\"SELECT mfhd_id\n FROM %(db)s.bib_mfhd\n WHERE bib_mfhd.bib_id=:bib\"\"\"\n % {\"db\": self.interface.oracle_database},\n {\"bib\": self.bibid},\n )\n\n rv = []\n for rec in result:\n rv.append(self.interface.get_mfhd(rec[0]))\n\n return rv\n\n\nclass HoldingsRecord(object):\n \"\"\"\n A single Voyager holding.\n\n :param record: a valid MARC-encoded holdings record\n :param suppressed: boolean; whether record is suppressed in OPAC\n :param mfhdid: holdings ID in database\n :param voyager_interface: the Voy instance to which this record belongs\n :param location: textual code for the holding's location\n :param location_display_name: display name for the holding's location\n :param last_date: datetime.datetime of last update from BIB_HISTORY table\n\n WARNING: last_date should have its tzinfo set to UTC even if the naive time in the database is \"really\"\n from another timezone. The Voyager database doesn't know what timezone is being used, and the\n win32com methods used for BatchCat will convert non-UTC datetimes to UTC, then the server\n will ignore the TZ and fail because it thinks your datetime is off by your local offset.\n \"\"\"\n\n def __init__(\n self,\n record,\n suppressed,\n mfhdid,\n voyager_interface,\n location,\n location_display_name,\n last_date,\n ):\n self.record = record\n self.suppressed = suppressed\n self.mfhdid = mfhdid\n self.interface = voyager_interface\n self.location = location\n self.location_display_name = location_display_name\n self.last_date = last_date\n\n def __getattr__(self, item):\n \"\"\"Pass on attributes of the pymarc record.\"\"\"\n if hasattr(self.record, item):\n return getattr(self.record, item)\n\n def __getitem__(self, item):\n \"\"\"Pass on item access for the pymarc record.\"\"\"\n return self.record[item]\n\n def get_items(self):\n \"\"\"Return a list of ItemRecords for the holding's items.\"\"\"\n mi_table = self.interface.tables[\"mfhd_item\"]\n query = sqla.select([mi_table.c.item_id]).where(\n mi_table.c.mfhd_id == self.mfhdid\n )\n res = self.interface.engine.execute(query)\n try:\n return [self.interface.get_item(i[0]) for i in res]\n except NoSuchItemException:\n print(\"failed for mfhd %s\" % self.mfhdid)\n raise\n\n def get_bib(self):\n \"\"\"Return the bib record to which this holding is attached.\"\"\"\n return self.interface.get_bib(self.record[\"004\"].data)\n\n\nclass ItemRecord(object):\n \"\"\"A Voyager item.\n\n :param int holding_id: indicates MFHD number for an item being added\n :param int item_id: indicates Voyager number of item record being updated\n :param int item_type_id: indicates valid item type ID from item_type table\n :param int perm_location_id: indicates valid Voyager location of an item\n :param bool add_item_to_top:\n :param str caption:\n :param str chron:\n :param int copy_number:\n :param str enumeration:\n :param str free_text:\n :param int media_type_id:\n :param int piece_count:\n :param str price:\n :param str spine_label:\n :param int temp_location_id:\n :param int temp_type_id:\n :param str year:\n :param Voy voyager_interface:\n :param str note:\n \"\"\"\n\n def __init__(\n self,\n holding_id=None,\n item_id=None,\n item_type_id=None,\n perm_location_id=None,\n add_item_to_top=False,\n caption=\"\",\n chron=\"\",\n copy_number=0,\n enumeration=\"\",\n free_text=\"\",\n media_type_id=None,\n piece_count=1,\n price=\"0\",\n spine_label=\"\",\n temp_location_id=None,\n temp_type_id=None,\n year=\"\",\n voyager_interface=None,\n note=\"\",\n ):\n self.holding_id = holding_id\n self.item_id = item_id\n self.item_type_id = item_type_id\n self.perm_location_id = perm_location_id\n self.add_item_to_top = add_item_to_top\n self.caption = caption\n self.chron = chron\n self.copy_number = copy_number\n self.enumeration = enumeration\n self.free_text = free_text\n self.media_type_id = media_type_id\n self.piece_count = piece_count\n self.price = price\n self.spine_label = spine_label\n self.temp_location_id = temp_location_id\n self.temp_type_id = temp_type_id\n self.year = year\n self.voyager_interface = voyager_interface\n self.note = note\n\n def get_mfhd(self):\n \"\"\"Retrieve the holdings record to which this item is attached.\"\"\"\n mi = self.voyager_interface.tables[\"mfhd_item\"]\n q = mi.select(mi.c.item_id == self.item_id)\n r = self.voyager_interface.engine.execute(q)\n rows = list(r)\n if len(rows) > 1:\n raise PyVgerException(\"Multiple MFHDs attached to item %s\", self.item_id)\n return self.voyager_interface.get_mfhd(rows[0][\"mfhd_id\"])\n\n @classmethod\n def from_id(cls, item_id, voyager_interface):\n \"\"\"Get item given ID.\"\"\"\n it = voyager_interface.tables[\"item\"]\n mit = voyager_interface.tables[\"mfhd_item\"]\n item_note_table = voyager_interface.tables[\"item_note\"]\n\n columns = [\n it.c.item_id,\n it.c.perm_location,\n mit.c.item_enum,\n item_note_table.c.item_note,\n mit.c.chron,\n mit.c.mfhd_id,\n it.c.item_type_id,\n mit.c.caption,\n it.c.copy_number,\n mit.c.freetext,\n it.c.media_type_id,\n it.c.pieces,\n it.c.price,\n it.c.spine_label,\n it.c.temp_location,\n it.c.temp_item_type_id,\n mit.c.year,\n ]\n\n q = sqla.select(\n columns,\n it.c.item_id == item_id,\n from_obj=[it.join(mit).outerjoin(item_note_table)],\n use_labels=False,\n )\n result = voyager_interface.engine.execute(q)\n rows = [x for x in result]\n if not rows:\n raise NoSuchItemException(\"item %s not found\" % item_id)\n if len(rows) != 1:\n print(\"many notes on item %s\" % item_id)\n print(rows)\n\n data = rows[0]\n\n price = f'{Decimal(data[\"price\"]) / 100:.2f}'\n\n return cls(\n item_id=data[\"item_id\"],\n perm_location_id=data[\"perm_location\"],\n enumeration=data[\"item_enum\"],\n chron=data[\"chron\"],\n note=data[\"item_note\"],\n holding_id=data[\"mfhd_id\"],\n item_type_id=data[\"item_type_id\"],\n caption=data[\"caption\"],\n copy_number=data[\"copy_number\"],\n free_text=data[\"freetext\"],\n media_type_id=data[\"media_type_id\"],\n piece_count=data[\"pieces\"],\n price=price,\n spine_label=data[\"spine_label\"],\n temp_location_id=data[\"temp_location\"],\n temp_type_id=data[\"temp_item_type_id\"],\n year=data[\"year\"],\n voyager_interface=voyager_interface,\n )\n\n @classmethod\n def from_barcode(cls, barcode, voyager_interface):\n \"\"\"Get an item record given its barcode.\"\"\"\n ib = voyager_interface.tables[\"item_barcode\"]\n q = sqla.select([ib.c.item_id], ib.c.item_barcode == barcode)\n result = voyager_interface.engine.execute(q)\n rows = [x for x in result]\n if not rows:\n raise NoSuchItemException(\"item for barcode %s not found\" % barcode)\n if len(rows) != 1:\n print(\"many items attached to barcode %s\" % barcode)\n print(rows)\n\n item_id = rows[0][0]\n return cls.from_id(item_id, voyager_interface)\n\n def get_barcode(self):\n \"\"\"Look up the active bacode for this item.\"\"\"\n ib = self.voyager_interface.tables[\"item_barcode\"]\n q = sqla.select(\n [ib.c.item_barcode],\n sqla.and_(ib.c.item_id == self.item_id, ib.c.barcode_status == \"1\"),\n )\n result = self.voyager_interface.engine.execute(q)\n rows = [x for x in result]\n if not rows:\n raise NoSuchItemException(\"barcode for item %s not found\" % self.item_id)\n if len(rows) != 1:\n print(\"many active barcodes attached to item %s\" % self.item_id)\n print(rows)\n\n return rows[0][0]\n\n def save(self):\n \"\"\"Save the item record back to the database.\"\"\"\n batchcat = self.voyager_interface.batchcat\n if batchcat is None:\n raise BatchCatNotAvailableError\n bc = batchcat.bc\n bc.cItem.HoldingId = self.holding_id\n bc.cItem.ItemID = self.item_id\n bc.cItem.ItemTypeID = self.item_type_id\n bc.cItem.PermLocationID = self.perm_location_id\n bc.cItem.Caption = self.caption or \"\"\n bc.cItem.Chron = self.chron or \"\"\n bc.cItem.CopyNumber = self.copy_number\n bc.cItem.Enumeration = self.enumeration or \"\"\n bc.cItem.FreeText = self.free_text or \"\"\n bc.cItem.MediaTypeID = self.media_type_id\n bc.cItem.PieceCount = self.piece_count\n bc.cItem.Price = self.price\n bc.cItem.SpineLabel = self.spine_label or \"\"\n bc.cItem.TempLocationID = self.temp_location_id\n bc.cItem.TempTypeID = self.temp_type_id\n bc.cItem.Year = self.year or \"\"\n result = bc.UpdateItemData(\n CatLocationID=self.voyager_interface.get_location_id(\n self.voyager_interface.cat_location\n )\n )\n if result[0]:\n raise PyVgerException(\"UpdateItemData error: {}\".format(result))\n","sub_path":"pyvger/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":25803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"139532599","text":"#!/usr/bin/env python3\n\"\"\"\nGradient Descent with L2 Regularization\n\"\"\"\n\nimport numpy as np\n\n\ndef l2_reg_gradient_descent(Y, weights, cache, alpha, lambtha, L):\n \"\"\"\n Function that updates the weights and biases of a NN using gradient descent\n with L2 regularization\n Arguments:\n - Y is a one-hot numpy.ndarray of shape (classes, m) that contains the\n correct labels for the data\n * classes is the number of classes\n * m is the number of data points\n - weights is a dictionary of the weights and biases of the NN\n - cache is a dictionary of the outputs of each layer of the NN\n - alpha is the learning rate\n - lambtha is the L2 regularization parameter\n - L is the number of layers of the network\n \"\"\"\n\n weights_copy = weights.copy()\n dz = cache[\"A\" + str(L)] - Y\n for i in range(L, 0, -1):\n A = cache[\"A\" + str(i - 1)]\n w = \"W\" + str(i)\n b = \"b\" + str(i)\n dw = (1 / len(Y[0])) * np.matmul(dz, A.T) + (\n lambtha * weights[w]) / len(Y[0])\n db = (1 / len(Y[0])) * np.sum(dz, axis=1, keepdims=True)\n weights[w] = weights[w] - alpha * dw\n weights[b] = weights[b] - alpha * db\n dz = np.matmul(weights_copy[\"W\" + str(i)].T, dz) * (1 - A * A)\n","sub_path":"supervised_learning/0x05-regularization/1-l2_reg_gradient_descent.py","file_name":"1-l2_reg_gradient_descent.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"80557900","text":"'''\nPlan:\n Split the paths on the backslashes\n Use the last item as the key, the entire path as the value\n\n Use the queries to search if the key exists\n If it does, return the corresponding value (the path) in an output array\n\n # There can be multiple different file paths that have the ending, \n # we need to return them all, append to lists at each key\n'''\n'PASSES ALL TESTS'\n\ndef finder(files, queries):\n # Dictionary to store filepath info\n file_path = {}\n\n # Iterate through each file path\n for path in files:\n # Split the file paths on the backslash\n split_path = path.split(\"/\")\n # Use the last split as the key and the whole file path as the value\n file_end = split_path[-1]\n # Store data in dictionary\n # If the key doesn't exist add it with an empty list\n if file_end not in file_path:\n file_path[file_end] = []\n # Add the ending as the key and the file path as the value\n file_path[file_end].append(path)\n \n # Create outout array\n output_array = []\n\n # Search to see if the query is in the dictionary\n for query in queries:\n # If the query is in the path dictionary, append the full file path\n if query in file_path:\n output_array.append(file_path[query])\n\n result = []\n\n # Output array is a nested list, need to return a 2-D list\n for inner_list in output_array:\n for item in inner_list:\n result.append(item)\n\n # Return result\n return result\n\n\nif __name__ == \"__main__\":\n files = [\n '/bin/foo',\n '/bin/bar',\n '/usr/bin/baz'\n ]\n queries = [\n \"foo\",\n \"qux\",\n \"baz\"\n ]\n print(finder(files, queries))\n","sub_path":"hashtables/ex5/ex5.py","file_name":"ex5.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"375387513","text":"# %load q07_extras/build.py\n# Default Imports\nfrom greyatomlib.python_getting_started.q01_read_data.build import read_data\ndata = read_data()\n\n# Your Solution\ndef extras_runs(data=data):\n\n # Write your code here\n innings1,innings2 = 0,0\n extra1 = data['innings'][0]['1st innings']['deliveries']\n for m in extra1:\n for x, y in m.items():\n if 'extras' in y:\n if 'wides' in y['extras']:\n innings1 += y['extras']['wides']\n elif 'legbyes' in y['extras']:\n innings1 += y['extras']['legbyes']\n \n extra2 = data['innings'][1]['2nd innings']['deliveries']\n for m in extra2:\n for x, y in m.items():\n if 'extras' in y:\n if 'wides' in y['extras']:\n innings2 += y['extras']['wides']\n elif 'legbyes' in y['extras']:\n innings2 += y['extras']['legbyes']\n \n print(innings2)\n print(innings1)\n difference = innings2-innings1\n\n\n return difference\nextras_runs()\n\n","sub_path":"q07_extras/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"86601981","text":"\"\"\"\nCopy and adjust data in preparation for run_cal_plotter.py\n\nThis should not be needed routinely, but is here to document\nthe provenance of the calibration data in the repository.\n\"\"\"\nfrom __future__ import print_function\nimport logging\nimport numpy as np\nimport glob\nimport os\nimport pandas as pd\nimport shutil\nfrom stompy import utils\nfrom stompy.io.local import cdec\nfrom stompy.io.local import usgs_nwis\n\ncache_dir=\"../cache\"\n\ndownload_period=[np.datetime64(\"2014-03-01\"),\n np.datetime64(\"2018-10-01\")]\n\n##\n\ncsc_stations_dir=\"/home/rusty/mirrors/Ed/Sync/UCD/Projects/CDFW_Arc/dflowfm/27-comp_bedlevtyp_2_3_4/stations\"\n\ndef any_x_in_y(x,y):\n \"\"\" true if any of the elements of list x are found in y\"\"\"\n for an_x in x:\n if an_x in y:\n return True\n return False\n\nfor fn in glob.glob(os.path.join( csc_stations_dir,\"wsel\",\"*.csv\")):\n base_fn=os.path.basename(fn)\n print(fn)\n if base_fn in ['GES_STAGE_april2014.csv']:\n print(\" Copying without modification\")\n shutil.copyfile(fn,base_fn)\n elif base_fn.startswith('HecDssExcel'):\n if any_x_in_y( ('UL1','DOP','HAAS'),base_fn): # no correction\n # unsure of status of UL1\n print(\" CWS station with no time offset\")\n shutil.copyfile(fn,base_fn)\n elif any_x_in_y( ('HS1','LN2','SG1','CCS'), base_fn):\n # Not positive about CCS, though. Will apply 1 hour shift anyway\n print(\" CWS station with assumed 1 hour offset\")\n df=pd.read_csv(fn,parse_dates=['Time'],infer_datetime_format=True)\n df.Time -= np.timedelta64(3600,'s')\n # Transition to ISO date formats\n df.to_csv(base_fn,index=False,date_format=\"%Y-%m-%d %H:%M\")\n else:\n raise Exception(\"No match for %s\"%base_fn)\n\n\n##\n\n# USGS gauges with Flow and Stage:\nfor usgs_name,usgs_station in [ (\"SRV\",\"11455420\"), # Sac River at Rio Vista\n (\"FPX\",\"11447650\"), # Sac River at Freeport\n (\"RYI\",\"11455350\"), # Cache Slough at Ryer Island\n (\"HWB\",\"11455165\"), # Miner Slough at HWY 84 Bridge\n (\"SSS\",\"11447850\"), # Steamboat Slough Btw Sac R And Sutter Sl, aka Steamboat Slough nr Walnut\n (\"SUT\",\"11447830\"), # Sutter Slough at Courtland\n (\"DWS\",\"11455335\"), # Sacramento R Deep Water Ship Channel Nr Rio Vista\n (\"GES\",\"11447905\"), # Sacramento R below Georgiana Slough\n (\"GSS\",\"11447903\"), # Georgiana Slough at Sac River\n (\"DCC\",\"11336600\"), # Delta Cross channel (used as BC, too)\n (\"SDC\",\"11447890\"), # Sac above Delta Cross Channel\n (\"CourtToe\",\"11455167\"), # Prospect Slough at Toe Drain near Courtland\n (\"LibertyToe\",\"11455140\"), # Toe Drain at Liberty Island\n (\"HNB\",\"11455143\"), # Little Holland North Breach, 2016-01 -- 2018-11\n (\"LIC\",\"382006121401601\"), # Liberty Isl at Liberty Isl. Cut\n (\"LIH\",\"11455146\"), # Liberty Cut at Little Holland\n (\"WildlandsUpMarsh\",\"381934121403201\"), # Liberty Island, Wildlands, Up Marsh\n # no physical data until 2015-07:\n (\"LIB\",\"11455315\"), # Cache Slough A S Liberty Island Nr Rio Vista CA\n (\"TSL\",\"11337080\"), # Threemile slough near Rio Vista\n (\"SDI\",\"11455478\"), # Sac River at Decker Island\n]:\n stage_fn='%s-stage.csv'%usgs_name\n flow_fn ='%s-flow.csv'%usgs_name\n if os.path.exists(stage_fn) and os.path.exists(flow_fn):\n continue # or force.\n print(\"Downloading %s\"%usgs_name)\n\n ds=usgs_nwis.nwis_dataset(usgs_station,\n download_period[0],download_period[1],\n [60,65], # Discharge and Stage\n days_per_request='M',cache_dir=cache_dir)\n # nwis_dataset() returns UTC data. Convert to PST:\n ds['time'] = ds.time - np.timedelta64(8,'h')\n\n # Match the names up with existing csv files:\n ds=ds.rename({'time':'Time'})\n if 'stream_flow_mean_daily' in ds:\n ds=ds.rename({'stream_flow_mean_daily':'Flow'})\n if 'height_gage' in ds:\n ds=ds.rename({'height_gage':'Stage'})\n df=ds.to_dataframe()\n\n if 'Stage' in df:\n df.Stage.to_csv(stage_fn,index=True,date_format=\"%Y-%m-%d %H:%M\",header=True)\n if 'Flow' in df:\n df.Flow.to_csv(flow_fn,index=True,date_format=\"%Y-%m-%d %H:%M\",header=True)\n\n##\n\nfor cdec_station in ['LIS','LIY','MIR']:\n for quant in ['flow','stage']:\n fn=\"%s-%s.csv\"%(cdec_station,quant)\n if os.path.exists(fn): continue\n if quant=='flow':\n sensor=20\n column='Flow'\n elif quant=='stage':\n sensor=1\n column='Stage'\n ds=cdec.cdec_dataset(cdec_station,\n start_date=download_period[0],\n end_date=download_period[1],\n sensor=sensor,cache_dir=cache_dir)\n if ds is None:\n print(\"No %s for %s\"%(quant,cdec_station))\n continue\n # cdec module tries to output UTC, so go back to PST here.\n ds.time.values -= np.timedelta64(8,'h')\n ds=ds.rename({'sensor%04d'%sensor:column,\n 'time':'Time'})\n \n df=ds.to_dataframe().reset_index()\n df.to_csv(fn,columns=[\"Time\",column],date_format=\"%Y-%m-%d %H:%M\",index=False)\n\n##\n\nif 0: \n # Fetch a year of stage data for Yolo Bypass near Lisbon.\n # the original file is put in cache_dir, from which\n lis_fn=\"LIS-stage-WY2014.csv\"\n lis_orig_fn=os.path.join(cache_dir,'LIS-WY2014-STAGE_15-MINUTE_DATA_DATA.CSV')\n url=\"http://wdl.water.ca.gov/waterdatalibrary/docs/Hydstra/docs/B91560/2014/STAGE_15-MINUTE_DATA_DATA.CSV\"\n\n # only fetch when necessary.\n if not os.path.exists(lis_fn):\n if not os.path.exists(lis_orig_fn):\n utils.download_url(url,lis_orig_fn,log=logging)\n df=pd.read_csv(lis_orig_fn,skiprows=3,parse_dates=['Time'],infer_datetime_format=True,\n names=[\"Time\",\"Stage\",\"Quality\",\"Comment\"])\n df.to_csv(lis_fn,columns=[\"Time\",\"Stage\"],date_format=\"%Y-%m-%d %H:%M\",index=False)\n\n\n##\n\nif 0: # Verified that these are the same vertical datum, same timezone\n # Compare datums between USGS GES, and the CSV already around\n ges_orig=pd.read_csv('GES_STAGE_april2014.csv',parse_dates=['Time'],infer_datetime_format=True)\n ges_usgs=pd.read_csv('GES-2014-04-stage.csv',parse_dates=['Time'],infer_datetime_format=True)\n\n import matplotlib.pyplot as plt\n plt.ion()\n plt.show()\n fig,ax=plt.subplots(num=1)\n ax.cla()\n ax.plot(ges_orig.Time,ges_orig.Stage,label='orig')\n ax.plot(ges_usgs.Time,ges_usgs.Stage,label='usgs')\n\n\n\n\n\n","sub_path":"dflowfm/calibration_data/collate_cal_data.py","file_name":"collate_cal_data.py","file_ext":"py","file_size_in_byte":7160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"539060959","text":"#!/usr/bin/env python\n# -*- coding: iso-8859-15 -*-\n\n### This module creates the central structure of the L2A_Product and calls the L2A_Schedule module\n\nfrom numpy import *\nfrom tables import *\nimport sys, os, logging, fnmatch, warnings, platform, multiprocessing\nfrom shutil import copyfile\nfrom datetime import datetime\nfrom time import time\nfrom L2A_Logger import L2A_Logger,getLevel\nfrom L2A_Config import L2A_Config, getScriptDir\nfrom L2A_XmlParser import L2A_XmlParser\nfrom L2A_ProcessTileToolbox import SUCCESS, FAILURE, ALREADY_PROCESSED\nfrom multiprocessing import Lock\nl = Lock()\n\n\ndef readNamingConvention(input_dir, mode, logger = None):\n # step 1 test the standard naming format:\n if mode == 'generate_datastrip':\n userProduct = os.path.basename(input_dir)\n S2A_L1C_mask_safe_standard = 'S2?_OPER_MSI_L1C_DS*'\n S2A_L1C_mask_safe_compact = 'DS_MPS*'\n elif mode == 'process_tile':\n userProduct = os.path.basename(input_dir)\n S2A_L1C_mask_safe_standard = 'S2?_OPER_MSI_L1C_TL*'\n S2A_L1C_mask_safe_compact = 'L1C_T*'\n else:\n userProduct = input_dir\n S2A_L1C_mask_safe_standard = 'S2?_OPER_PRD_MSIL1C*.SAFE'\n S2A_L1C_mask_safe_compact = 'S2?_MSIL1C*.SAFE'\n\n if (fnmatch.fnmatch(userProduct, S2A_L1C_mask_safe_standard) == True):\n nc = 'SAFE_STANDARD'\n elif(fnmatch.fnmatch(userProduct, S2A_L1C_mask_safe_compact) == True):\n nc = 'SAFE_COMPACT'\n else:\n nc = 'UNKNOWN'\n if logger:\n logger.error('L1C user product directory must match the following mask: %s' % S2A_L1C_mask_safe_compact)\n logger.error('but is: %s' % userProduct)\n\n return nc\n\n\ndef parseCommandLine(args):\n\n config = L2A_Config(None)\n logger = L2A_Logger('sen2cor',operation_mode = args.mode)\n selectedTile = None\n\n try:\n test = args.input_dir\n input_dir = os.path.normpath(test)\n if not (os.path.isabs(input_dir)):\n cwd = os.getcwd()\n input_dir = os.path.join(cwd, input_dir)\n if os.path.exists(input_dir):\n # check if input_dir argument contains a tile. If yes, split the tile from path,\n # put the tile in the config object created below as selected tile,\n # create the new path for the user directory.\n if 'GRANULE' in input_dir:\n dirname, dummy = os.path.split(input_dir)\n input_dir = dirname\n userProduct = os.path.basename(input_dir)\n config = L2A_Config(None, input_dir)\n config.operationMode = 'TOOLBOX'\n config.namingConvention = readNamingConvention(userProduct, args.mode, logger = config.logger)\n if config.namingConvention == 'UNKNOWN':\n return config\n else:\n logger.error('Input user product does not exist.')\n return config\n except:\n pass\n\n if (args.mode != 'generate_datastrip' and \\\n args.mode != 'process_tile') and \\\n config.operationMode != 'TOOLBOX':\n logger.error('wrong operation mode: %s' % args.mode)\n config.operationMode = 'INVALID'\n return config\n\n if args.mode == 'generate_datastrip':\n work_dir = os.path.normpath(args.work_dir)\n if not os.path.exists(work_dir):\n os.mkdir(work_dir)\n if args.datastrip == None:\n logger.error('No argument for datastrip present.')\n return config\n elif args.processing_centre == None:\n logger.error('No argument for processing centre present.')\n return config\n elif args.archiving_centre == None:\n logger.error('No argument for archiving centre present.')\n return config\n datastrip = os.path.normpath(args.datastrip)\n if os.path.exists(datastrip):\n input_dir = os.path.dirname(datastrip)\n config = L2A_Config(None, input_dir)\n config.datastrip = os.path.basename(datastrip)\n config.datastrip_root_folder = datastrip\n config.processing_centre = args.processing_centre\n config.archiving_centre = args.archiving_centre\n config.work_dir = work_dir\n config.operationMode = 'GENERATE_DATASTRIP'\n config.namingConvention = readNamingConvention(config.datastrip, args.mode, logger = config.logger)\n else:\n logger.error('Input datastrip does not exist.')\n return config\n # end generate_datastrip\n\n elif args.mode == 'process_tile':\n work_dir = os.path.normpath(args.work_dir)\n if not os.path.exists(work_dir):\n os.mkdir(work_dir)\n if args.datastrip == None:\n logger.error('No argument for datastrip present.')\n return config \n elif args.tile == None:\n logger.error('No argument for tile present.')\n return config\n elif args.work_dir == None:\n logger.error('No argument for work directory present.')\n return config\n datastrip = os.path.normpath(args.datastrip)\n if not os.path.exists(datastrip):\n logger.error('Input datastrip does not exist.')\n return config\n tile = os.path.normpath(args.tile)\n if os.path.exists(tile):\n input_dir = os.path.dirname(tile)\n config = L2A_Config(None, input_dir)\n config.datastrip = os.path.basename(datastrip)\n config.datastrip_root_folder = datastrip\n config.L2A_DS_ID = config.datastrip\n config.L2A_DS_DIR = datastrip\n config.L2A_DS_MTD_XML = os.path.join(datastrip, 'MTD_DS.xml')\n config.tile = os.path.basename(tile)\n config.selectedTile = tile\n config.nrTiles = 1\n config.L1C_TILE_ID = os.path.basename(tile)\n config.work_dir = work_dir\n config.operationMode = 'PROCESS_TILE'\n config.namingConvention = readNamingConvention(config.tile, args.mode, logger = logger)\n else:\n logger.error('Input tile does not exist.')\n return config\n # end process_tile\n\n if config.operationMode != 'TOOLBOX':\n if args.output_dir == None:\n logger.error('No argument for output directory present.')\n config.operationMode = 'INVALID'\n return config\n output_dir = os.path.normpath(args.output_dir)\n if not os.path.exists(output_dir):\n os.mkdir(output_dir)\n config.output_dir = output_dir\n # SIIMPC-1327:\n if args.img_database_dir == None:\n img_database_dir = config.work_dir\n else:\n img_database_dir = os.path.normpath(args.img_database_dir)\n if args.res_database_dir == None:\n res_database_dir = config.work_dir\n else:\n res_database_dir = os.path.normpath(args.res_database_dir)\n if img_database_dir == None:\n logger.error('No argument for image database directory present.')\n config.operationMode = 'INVALID'\n return config\n if not os.path.exists(img_database_dir):\n os.mkdir(img_database_dir)\n if not os.path.exists(res_database_dir):\n os.mkdir(res_database_dir)\n if res_database_dir == None:\n logger.error('No argument for result database directory present.')\n config.operationMode = 'INVALID'\n return config\n config.img_database_dir = img_database_dir\n config.res_database_dir = res_database_dir\n # end ! TOOLBOX\n\n else: # TOOLBOX:\n directory = os.path.normpath(args.input_dir)\n if not (os.path.isabs(directory)):\n cwd = os.getcwd()\n directory = os.path.join(cwd, directory)\n else:\n cwd = os.path.dirname(directory)\n\n config.work_dir = directory\n if args.output_dir:\n output_dir = os.path.normpath(args.output_dir)\n if not os.path.exists(output_dir):\n os.mkdir(output_dir)\n config.output_dir = output_dir\n else:\n config.output_dir = cwd\n\n if args.processing_centre:\n config.processing_centre = args.processing_centre\n\n if args.processing_baseline:\n config.processingBaseline = float32(args.processing_baseline)\n\n # check if directory argument contains a tile. If yes, split the tile from path,\n # put the tile in the config object created below as selected tile,\n # create the new path for the user directory.\n if 'GRANULE' in config.work_dir:\n dirname, selectedTile = os.path.split(config.work_dir)\n directory = os.path.dirname(config.work_dir)\n\n test = os.path.basename(directory)\n # step 1 test the standard naming format:\n S2A_L1C_mask = 'S2?_OPER_PRD_MSIL1C*.SAFE'\n if (fnmatch.fnmatch(test, S2A_L1C_mask) == True):\n nc = 'SAFE_STANDARD'\n else:\n S2A_L1C_mask = 'S2?_MSIL1C*.SAFE'\n if (fnmatch.fnmatch(test, S2A_L1C_mask) == True):\n nc = 'SAFE_COMPACT'\n else:\n logger.error('L1C user product directory must match the following mask: %s, but is %s' % [S2A_L1C_mask, test])\n return FAILURE\n # end TOOLBOX\n\n # common args:\n CFG = 'cfg'\n if args.GIP_L2A:\n # is it an absolute path?\n isFile = False\n test = os.path.normpath(args.GIP_L2A)\n if os.path.isfile(test):\n config.configFn = test\n isFile = True\n else: # is it located in the config home dir?\n test = os.path.join(config.home, CFG, args.GIP_L2A)\n if os.path.isfile(test):\n config.configFn = test\n isFile = True\n if not isFile:\n logger.error('File does not exist: %s' % test)\n config.operationMode = 'INVALID'\n return config\n # same procedure for GIP_SC:\n if args.GIP_L2A_SC:\n isFile = False\n test = os.path.normpath(args.GIP_L2A_SC)\n if os.path.isfile(test):\n config.configSC = test\n isFile = True\n else:\n test = os.path.join(config.home, CFG, args.GIP_L2A_SC)\n if os.path.isfile(test):\n config.configSC = test\n isFile = True\n if not isFile:\n logger.error('File does not exist: %s' % test)\n config.operationMode = 'INVALID'\n return config\n # same procedure for GIP_AC:\n if args.GIP_L2A_AC:\n isFile = False\n test = os.path.normpath(args.GIP_L2A_AC)\n if os.path.isfile(test):\n config.configAC = test\n isFile = True\n else:\n test = os.path.join(config.home, CFG, args.GIP_L2A_AC)\n if os.path.isfile(test):\n config.configAC = test\n isFile = True\n if not isFile:\n logger.error('File does not exist: %s' % test)\n config.operationMode = 'INVALID'\n return config\n # same procedure for GIP_L2A_PB:\n if args.GIP_L2A_PB:\n isFile = False\n test = os.path.normpath(args.GIP_L2A_PB)\n if os.path.isfile(test):\n config.configPB = test\n isFile = True\n else:\n test = os.path.join(config.home, CFG, args.GIP_L2A_PB)\n if os.path.isfile(test):\n config.configPB = test\n isFile = True\n if not isFile:\n logger.error('File does not exist: %s' % test)\n config.operationMode = 'INVALID'\n return config\n\n if args.resolution == None:\n config.resolution = 0\n else:\n config.resolution = args.resolution\n\n config.scOnly = args.sc_only\n config.crOnly = args.cr_only\n config.raw = args.raw\n config.tif = args.tif\n config.logger = logger\n return config\n\n\ndef postprocess(config):\n # SIMPC-1152, third remark: report file is unwanted.\n return True\n # fix for SIIMPC-555.1, UMW\n fnLogBase = os.path.basename(config.fnLog)\n try:\n fnLogIn = config.fnLog\n f = open(fnLogIn, 'a')\n f.write('')\n f.flush()\n f.close()\n fnLogOut = os.path.join(config.L2A_UP_DIR, fnLogBase)\n copyfile(fnLogIn, fnLogOut)\n return True\n except:\n config.logger.error('cannot copy report file: %s' % fnLogIn)\n return False\n\ndef main(args=None):\n import argparse\n config = L2A_Config(None)\n processorId = config.processorName +'. Version: '+ config.processorVersion + ', created: '+ config.processorDate + \\\n ', supporting Level-1C product version 14.2 - ' + str(config.productVersion)\n \n parserPDGS = argparse.ArgumentParser(description=processorId + '.',add_help=False)\n parserPDGS.add_argument('--mode', help='Mode: generate_datastrip, process_user_product, process_tile')\n namespace,dummy = parserPDGS.parse_known_args()\n parser = argparse.ArgumentParser(description=processorId + '.',add_help=True)\n if namespace.mode == 'TOOLBOX' or namespace.mode is None:\n parser.add_argument('input_dir', help='Directory of Level-1C input')\n\n parser.add_argument('--mode', help='Mode: generate_datastrip, process_tile')\n parser.add_argument('--resolution', type=int, choices=[10, 20, 60], help='Target resolution, can be 10, 20 or 60m. If omitted, only 20 and 10m resolutions will be processed')\n parser.add_argument('--datastrip', help='Datastrip folder')\n parser.add_argument('--tile', help='Tile folder')\n parser.add_argument('--output_dir', help='Output directory')\n parser.add_argument('--work_dir', help='Work directory')\n parser.add_argument('--img_database_dir', help='Database directory for L1C input images')\n parser.add_argument('--res_database_dir', help='Database directory for results and temporary products')\n parser.add_argument('--processing_centre', help='Processing centre as regex: ^[A-Z_]{4}$, e.g \"SGS_\"')\n parser.add_argument('--archiving_centre', help='Archiving centre as regex: ^[A-Z_]{4}$, e.g. \"SGS_\"')\n parser.add_argument('--processing_baseline', help='Processing baseline in the format: \"dd.dd\", where d=[0:9]')\n parser.add_argument('--raw', action='store_true', help='Export raw images in rawl format with ENVI hdr')\n parser.add_argument('--tif', action='store_true', help='Export raw images in TIFF format instead of JPEG-2000')\n parser.add_argument('--sc_only', action='store_true', help='Performs only the scene classification at 60 or 20m resolution')\n parser.add_argument('--cr_only', action='store_true', help='Performs only the creation of the L2A product tree, no processing')\n parser.add_argument('--debug', action='store_true', help='Performs in debug mode')\n #parser.add_argument('--profile', action='store_true', help='Profiles the processor\\'s performance')\n parser.add_argument('--GIP_L2A', help='Select the user GIPP')\n parser.add_argument('--GIP_L2A_SC', help='Select the scene classification GIPP')\n parser.add_argument('--GIP_L2A_AC', help='Select the atmospheric correction GIPP')\n parser.add_argument('--GIP_L2A_PB', help='Select the processing baseline GIPP')\n args = parser.parse_args()\n config = parseCommandLine(args)\n if args.debug:\n config.logLevel = 'DEBUG'\n \n if config.operationMode == 'INVALID':\n return FAILURE\n\n dt = datetime.utcnow().strftime('%Y%m%dT%H%M%S')\n config.setSchemes()\n\n # this is to set the version info from the L1C User Product:\n if not config.setProductVersion():\n return FAILURE\n\n if config.operationMode == 'TOOLBOX':\n if not config.readPreferences():\n return FAILURE\n if config.create_L2A_UserProduct():\n config.configure_L2A_UP_metadata()\n L2A_UP_ID = os.path.join(config.logDir, config.L2A_UP_ID)\n logName = L2A_UP_ID + '_' + dt + '_report.xml'\n logDir = config.logDir\n if not os.path.exists(logDir):\n os.mkdir(logDir)\n config.fnLog = os.path.join(logDir, logName)\n\n elif config.operationMode == 'PROCESS_TILE':\n config.create_L2A_Tile()\n L2A_TILE_ID = os.path.join(config.work_dir, config.L2A_TILE_ID)\n logName = L2A_TILE_ID + '_' + dt + '_report.xml'\n config.fnLog = os.path.join(config.work_dir, logName)\n \n elif config.operationMode == 'GENERATE_DATASTRIP':\n L2A_DS_ID = os.path.join(config.work_dir, config.datastrip.replace('L1C', 'L2A'))\n logName = L2A_DS_ID + '_'+ dt + '_report.xml'\n config.fnLog = os.path.join(config.work_dir, logName)\n if not config.readPreferences():\n return FAILURE\n \n # create and initialize the base log system:\n logger = L2A_Logger('sen2cor', fnLog = config.fnLog\\\n , logLevel = config.logLevel\\\n , operation_mode = config.operationMode)\n config.logger = logger\n config.logger.stream('%s started ...' % processorId)\n if float32(config.productVersion) < 14.5:\n config.logger.stream('Old product version %2.1f detected, - will be updated to 14.5' % config.productVersion)\n config.logger.stream('Processing baseline will also be updated')\n else:\n config.logger.stream('Product version: %2.1f' % (config.productVersion))\n config.logger.stream('Operation mode: %s' % (config.operationMode))\n\n try:\n f = open(config.processingStatusFn, 'w')\n f.write('0.0\\n')\n f.close()\n except:\n config.logger.error('cannot create process status file: %s' % config.processingStatusFn)\n return FAILURE\n\n if config.processingBaseline:\n config.logger.stream('Processing baseline: %05.2f' % config.processingBaseline)\n else:\n config.logger.error('No Processing baseline found.') \n config.tStart = time()\n try:\n f = open(config.fnLog, 'w')\n f.write('\\n')\n f.write('\\n')\n f.close()\n except:\n config.logger.error('cannot update the report file: %s' % config.fnLog)\n return FAILURE\n \n if config.operationMode == 'GENERATE_DATASTRIP':\n from L2A_ProcessDataStrip import L2A_ProcessDataStrip\n ds = L2A_ProcessDataStrip(config)\n if ds.generate():\n result = SUCCESS\n else:\n result = FAILURE\n else:\n # prepare the processing:\n if args.resolution == None:\n resolution = 0\n else:\n resolution = args.resolution\n config.setTimeEstimation(resolution)\n try:\n f = open(config.processingStatusFn, 'w')\n f.write('0.0\\n')\n f.close() \n except:\n config.logger.error('cannot create process status file: %s' % config.processingStatusFn) \n return FAILURE\n \n if config.operationMode == 'PROCESS_TILE':\n from L2A_ProcessTilePdgs import L2A_ProcessTile\n config.resolution = resolution\n try:\n tile = L2A_ProcessTile(config)\n if tile.process() == True:\n result = SUCCESS\n else:\n result = FAILURE\n except Exception as e:\n if e.args[0] == 2:\n if 'pic' in e.filename:\n result = ALREADY_PROCESSED\n else:\n logger = L2A_Logger('sen2cor', operation_mode=config.operationMode)\n logger.stream(e, exc_info=True)\n sys.exit(1)\n\n elif config.operationMode == 'TOOLBOX':\n from L2A_ProcessTileToolbox import L2A_ProcessTile\n config.resolution = resolution\n config.create_L2A_Datastrip()\n L2A_TILES = config.updateTiles()\n if not L2A_TILES:\n config.logger.error('no tile in GRANULE folder found')\n result = FAILURE\n else:\n S2A_mask = '*L2A_T*'\n for tile in L2A_TILES:\n if (fnmatch.fnmatch(tile, S2A_mask) == False):\n continue\n\n config.L2A_TILE_ID = tile\n try:\n tile = L2A_ProcessTile(config)\n if tile.process() == True:\n result = SUCCESS\n else:\n result = FAILURE\n if not postprocess(config):\n result = FAILURE\n except Exception as e:\n logger = L2A_Logger('sen2cor', operation_mode=config.operationMode)\n logger.stream(e, exc_info=True)\n result = FAILURE\n\n # final cleanup in Toolbox mode:\n import glob\n try:\n files = glob.glob(os.path.join(config.L2A_UP_DIR, 'GRANULE', 'L2A_*', '*.h5'))\n for f in files:\n os.remove(f)\n except:\n pass\n try:\n os.remove(config.picFn)\n except:\n pass\n\n if not config.logger:\n logger = L2A_Logger('sen2cor',operation_mode = config.operationMode)\n config.logger = logger\n\n if result == FAILURE:\n config.logger.stream('Progress[%]: 100.00 : Application terminated with at least one error.\\n')\n elif result == ALREADY_PROCESSED:\n config.logger.stream('Progress[%]: 100.00 : Product already processed.\\n')\n result = SUCCESS\n else:\n config.logger.stream('Progress[%]: 100.00 : Application terminated successfully.\\n')\n \n return result\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"L2A_Process.py","file_name":"L2A_Process.py","file_ext":"py","file_size_in_byte":21965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"456515069","text":"import string\nimport random\nimport datetime\nimport time\n\nfrom psych_app.models import PsychDiagnosis, MedicalDiagnosis, Medication, Subject\nfrom psych_app.forms import GetTestForm\nfrom .models import Question, Response, Test \nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.core import serializers\nfrom django.db.models import Count\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.template import RequestContext, Context, loader\nfrom django.urls import reverse\nimport pdb\nimport os\nimport urllib.request\n\n# Create your views here.\ndef test_home(request):\n context = {}\n if request.method == 'POST':\n get_test_form = GetTestForm(request.POST)\n if get_test_form.is_valid():\n get_test_form = get_test_form.clean()\n potential_test_code = get_test_form['test_code'] \n test_exists = get_object_or_404(Test, test_code=potential_test_code)\n print(test_exists)\n context['test'] = test_exists\n return redirect('/test/test_page/{0}'.format(test_exists)) \n else:\n return redirect('/test')\n else:\n template = \"test_app/test_home.html\"\n get_test_form = GetTestForm()\n context['get_test_form'] = get_test_form\n return render(request, template, context)\n\ndef code_generator(size, chars):\n return ''.join(random.choice(chars) for _ in range(size))\n\ndef generate_test(subject, user):\n code = code_generator(8, string.ascii_uppercase + string.digits)\n return Test(test_code=code, subject=subject, user=user)\n \ndef test_prestart(request, test_code):\n context = {}\n template = \"test_app/test_start_page.html\"\n context['test_code'] = test_code\n return render(request, template, context)\n \ndef question(request, test_code, question):\n question_current = Question.objects.get(id=question)\n if request.method == 'POST':\n question_current = Question.objects.get(id=question)\n seq = int(question_current.seq)\n\n answer = request.POST['answer']\n\n if answer == \"-1\":\n print(\"no answer selected\")\n start_time = str(datetime.datetime.now())\n context = {'test_code':test_code, 'question':question_current, 'start_time': start_time, 'error_message': 'Make sure to select an answer before continuing'}\n template = \"test_app/question_page.html\"\n return render(request, template, context)\n else:\n test = Test.objects.get(pk=test_code)\n\n #delete old test responses if they exist\n old_responses = test.responses.filter(question=question)\n if old_responses.exists():\n old_responses.delete()\n\n #save new response\n start_time = request.POST['start_time']\n now = str(datetime.datetime.now())\n response = Response(question=question_current, response=answer, start_time=start_time, submit_time=now)\n response.save()\n test.responses.add(response)\n\n seq = int(question_current.seq)\n next_seq = seq +1\n\n #if test is complete\n if next_seq > Question.objects.all().count():\n template = 'test_app/test_completed.html'\n context = {}\n context['test'] = test\n context['score'] = test.is_finished\n return render(request, template, context)\n else:\n #get next question in seqence\n next_question = Question.objects.get(seq=next_seq) \n \n return redirect('/test/test_page/{0}/{1}'.format(test_code, next_question.id))\n else:\n start_time = str(datetime.datetime.now())\n context = {'test_code':test_code, 'question':question_current, 'start_time': start_time}\n template = \"test_app/question_page.html\"\n return render(request, template, context)\n\n# @login_required\n# def generate_test_code(request, subject):\n# test = generate_test(user=request.user, subject=Subject.objects.get(id=subject)) \n# test.save()\n\n# #blogs = Blog.objects.filter(author=author).values_list('id', flat=True)\n# path = \"http://3.16.130.76:8000/test/test_page/\"\n# context = {'test': test, 'path':path}\n# template = \"test_app/generated_code.html\"\n# return render(request, template, context)\n\n@login_required\ndef get_user_tests(request, subject):\n request.session['selected_subject_id'] = subject\n\n if request.method == 'POST':\n test = generate_test(user=request.user, subject=Subject.objects.get(id=subject)) \n test.save()\n return HttpResponseRedirect(request.path_info)\n\n tests = Test.objects.filter(subject=subject)\n context = {'tests': tests}\n\n #Get public IP\n external_ip = urllib.request.urlopen('https://ident.me').read().decode('utf8')\n context['path'] = external_ip + \":8000/test/test_page/\"\n\n context['subject'] = subject\n template = \"test_app/generated_code.html\"\n\n return render(request, template, context)\n\n@login_required\ndef delete_test(request, test_code):\n test = get_object_or_404(Test, test_code=test_code)\n subject = test.subject.id\n test.delete()\n return redirect('/test/gen_test/' + subject)\n\n","sub_path":"test_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"135988232","text":"import uuid\n\nfrom django.conf import settings\nfrom django.db import models\n# from django.db.models.signals import pre_save, post_save, m2m_changed\n\nfrom products.models import Product\n\n\nUser = settings.AUTH_USER_MODEL\n\nclass Viewed_Product_Manager(models.Manager):\n def new_or_get(self, request):\n viewed_product_id = request.session.get(\"viewed_product_id\", None)\n qs = self.get_queryset().filter(id=viewed_product_id)\n if qs.count() == 1:\n new_obj = False\n viewed_product_obj = qs.first()\n if request.user.is_authenticated and viewed_product_obj.user is None:\n viewed_product_obj.user = request.user\n viewed_product_obj.save()\n else:\n viewed_product_obj = Viewed_Product.objects.new(user=request.user)\n new_obj = True\n request.session['viewed_product_id'] = viewed_product_obj.id\n return viewed_product_obj, new_obj\n\n def new(self, user=None):\n user_obj = None\n if user is not None:\n if user.is_authenticated:\n user_obj = user\n return self.model.objects.create(user=user_obj)\n\n def foo():\n \tprint('this is from the Viewed_Product model!!')\n\nclass Viewed_Product(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)\n # products = models.SlugField(Product, blank=True)\n # products = models.CharField(max_length=200)\n # products = models.SlugField(Product, blank=True)\n\n \n\n\t# slug \t\t= models.SlugField(blank=True, unique=True)\n\n # subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)\n # total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)\n # updated = models.DateTimeField(auto_now=True)\n # timestamp = models.DateTimeField(auto_now_add=True)\n\n objects = Viewed_Product_Manager()\n\n # def __str__(self):\n # return str(self.id)\n\nclass Viewed_Product_Object(models.Model):\n # id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n user = models.ForeignKey(Viewed_Product, on_delete=models.CASCADE)\n products = models.CharField(max_length=200)\n\n # def __str__(self):\n # return '%s %s' % (self.user, self.products)\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"viewed_products/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"506380454","text":"\"\"\"\nA function to get the action list corresponding to an indicated program.\n\n@author: Andrew Curry\n\"\"\"\nfrom elasticsearch import Elasticsearch\n\n\ndef get_action_list(program_name: str) -> str:\n \"\"\"\n A function to get the action list corresponding to an indicated program.\n Returns \"\" if there is no matching program.\n Input should be in the format 'Program:n'\n \"\"\"\n short_name = int(program_name[8:])\n es = Elasticsearch([{'host': 'localhost', 'port': 9200}])\n res = es.search(\n index='actions-index', \n params= {'size': 1}, \n body={\"query\": {\"match\": {'name' : short_name}}})\n for hit in res['hits']['hits']:\n return hit['_source']['actions']\n return \"\"","sub_path":"action_retrieval.py","file_name":"action_retrieval.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"506667352","text":"import pygame\nimport pygame.draw\nimport pygame.event\nimport pygame.font\nfrom PyQt5.QtCore import pyqtSignal,QObject\n\nfrom model.logic.gui_registration_operation.operation_gui_registrator import RegistratorGuiOperation\nfrom veiw.view_on_desctop_screen import VeiwOnDesctop\n\n\nclass Registrator_GUI(QObject):\n\n log_in_signal = pyqtSignal(str,str,str)\n next_step_signal = pyqtSignal()\n add_new_record_signal = pyqtSignal(str)\n guest_mode_signal = pyqtSignal()\n\n def __init__(self):\n super(Registrator_GUI, self).__init__()\n\n pygame.font.init()\n pygame.init()\n\n self.user_name = []\n self.password = []\n\n # списки словарей с координатами и размерами клавиш\n self.buttons_to_show = []\n RegistratorGuiOperation.creating_list_of_buttons_to_show(self.buttons_to_show)\n self.buttons_to_hide = []\n RegistratorGuiOperation.creating_list_of_buttons_to_hide(self.buttons_to_hide)\n\n # списки словарей с координатами и самими надписями\n self.captions_to_show = []\n RegistratorGuiOperation.create_list_of_captures_to_show(self.captions_to_show)\n\n self.captions_to_hide = []\n RegistratorGuiOperation.create_list_of_captures_to_hide(self.captions_to_hide)\n\n self.dinamical_captions_to_show = []\n RegistratorGuiOperation.create_list_of_dinamical_captions_to_show(self.dinamical_captions_to_show,\n [self.user_name,self.password])\n self.dinamical_captions_to_hide = []\n\n self.information_show_info_screen = []\n\n self.field_to_add = None\n self.showing_dinamicals_captions = True\n self.create_objects_and_screens()\n\n\n def check_permisions(self):\n self.registrator.gui.log_in_signal.connect(self.client.write_to_db_socket)\n self.registrator.gui.add_new_record_signal.connect(self.client.write_to_db_socket)\n\n def change_info_on_info_screen_from_db(self,info_to_scow_on_info_screen):\n self.information_show_info_screen = list(info_to_scow_on_info_screen)\n\n def create_objects_and_screens(self):\n\n self.window = pygame.display.set_mode((800, 300))\n pygame.display.set_caption('Registration')\n self.screen = pygame.Surface((800, 270))\n self.info_screen = pygame.Surface((800,30))\n self.fontobject = pygame.font.Font(None, 18)\n\n def show_buttons(self):\n color = (150,20,255)\n for i in self.buttons_to_show:\n val = list(i.values())[0]\n btn = pygame.Surface((val[0], val[1]))\n btn.fill(color)\n position = (val[2], val[3])\n VeiwOnDesctop.blitting_button_on_screen(self.screen,((30,54,128)),position,btn)\n\n def show_captions(self):\n for i in self.captions_to_show:\n position = list(i.values())[0]\n caption = list(i.keys())[0]\n VeiwOnDesctop.blitting_font_on_screen(self.screen,self.fontobject,caption,(255, 255, 255),position)\n\n def show_dinamicals_captions(self):\n cap,pos = '',(0,0)\n for i in self.dinamical_captions_to_show:\n if len(list(i.values())[0]) == 2:\n cap = ''.join(list(i.values())[0][0])\n\n elif len(list(i.values())[0]) == 3:\n cap = '*' * len(list(i.values())[0][0])\n\n pos = list(i.values())[0][1]\n VeiwOnDesctop.blitting_font_on_screen(self.screen, self.fontobject, cap, (255, 255, 255), pos)\n\n def show_info_on_info_screen(self):\n VeiwOnDesctop.blitting_font_on_screen(self.info_screen, self.fontobject, ''.join(self.information_show_info_screen),\n (255, 255, 255),(5, 5))\n\n def show_all_components(self):\n self.screen.fill((90, 60, 90))\n self.info_screen.fill((60, 90, 60))\n self.show_buttons()\n self.show_captions()\n self.show_dinamicals_captions()\n self.show_info_on_info_screen()\n VeiwOnDesctop.blitting_screen_on_window(self.window, self.screen, (0, 0))\n VeiwOnDesctop.blitting_screen_on_window(self.window, self.info_screen, (0, 270))\n\n pygame.display.flip()\n\n","sub_path":"model/entity/registrator_entity/registrator_gui.py","file_name":"registrator_gui.py","file_ext":"py","file_size_in_byte":4271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"480777915","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 15 13:57:14 2016\n\n@author: austen\n\"\"\"\n#Thermodenuder Heat Tape Coverage Calculations\n#Import packages\nimport math as math\nimport pandas as pd\n\n#Import heat tape specifications file\nFilePath='/home/austen/Documents/Thermodenuder/Data/Initial Tests/12-20-16/OmegaHeatTapes.csv'\nHeatTapeSpecs=pd.read_csv(FilePath,header=0,sep=',')\n\n#Define constants for calculations\nPipeLength=1000.00\nPipeDiameter=0.5*2.54*10\nLengthPerCoil=2*math.pi*(PipeDiameter/2)\n\n#Write function to output calculations\ndef Equations(HeatTapeModel,TapeLength, TapeWidth, Gap, Voltage, Cost):\n MaxNumCoils=(TapeLength*12.0*2.54*10)/LengthPerCoil\n NumCoilsRequired=PipeLength/((TapeWidth*2.54*10)+Gap)\n MinCoilSpanwGap=PipeLength/MaxNumCoils\n CoilSpanwGap=PipeLength/NumCoilsRequired\n RequiredLessThanMax=MaxNumCoils>=NumCoilsRequired\n CalculationOutput=pd.Series(data={'Model':HeatTapeModel,'Cost (USD)':Cost,'Volts':Voltage,'Tape Length (Feet)':TapeLength,'Tape Width (Inches)':TapeWidth,'Max Coil #':MaxNumCoils,'Required Coil #':NumCoilsRequired,'Minimum Pipe Length Per Coil':MinCoilSpanwGap,'Nominal Pipe Length Per Coil (Gap Included)':CoilSpanwGap,'Nominal Less Than Maximum Coils':RequiredLessThanMax})\n CalculationOutput=pd.DataFrame(CalculationOutput).T\n return(CalculationOutput)\n \n#Perform calulations via looping over rows in the file\nResults=pd.DataFrame()\nfor i in range(len(HeatTapeSpecs.index)):\n OutputArray=Equations(HeatTapeModel=HeatTapeSpecs.loc[i,'Heat Tape Model Number'],Voltage=HeatTapeSpecs.loc[i,'Volts'],Cost=HeatTapeSpecs.loc[i,'Cost (USD)'],TapeLength=HeatTapeSpecs.loc[i,'Length (Feet)'],TapeWidth=HeatTapeSpecs.loc[i,'Width (Inches)'],Gap=5.0)\n# must be results=results.append(blah) to store the looped over data\n# ignore index is important, it basically returns the index as the row number of the particular dataframe you made\n Results=Results.append(OutputArray, ignore_index=True)\n#This is the proper way to sort through a data frame and drop rows\nfor index, row in Results.iterrows():\n if row['Nominal Less Than Maximum Coils']==False:\n Results.drop(index, inplace=True)\nfor index, row in Results.iterrows():\n if row['Volts']==240:\n Results.drop(index, inplace=True)\ncsv_filepath='/home/austen/Documents/Thermodenuder/CompatibleOmegaHeatTapes.csv'\nResults.to_csv(csv_filepath, sep=',')","sub_path":"src/HeatTapeSpecsEval.py","file_name":"HeatTapeSpecsEval.py","file_ext":"py","file_size_in_byte":2395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"602330294","text":"# Given two already-sorted lists:\n\n# Write a function that returns a new list that is the sorted merge of both of \n# them. For the above lists, our result would be:\n\n\n# It would be easy to do this by just using Python’s built-in sort method, \n# like this:\n# >>> out = a + b\n# >>> out.sort()\n\n# However, this would have the runtime of O(n log n), where n is the combined \n# length of a and b. You can get a much better runtime by exploiting the fact \n# that both of the input lists are already sorted.\n\n# Your challenge is to implement sort_ab where the runtime is O(a + b) (where a \n# and b are the lengths of those lists, respectively).\n\n\n\ndef sort_ab(a, b):\n \"\"\"Given already-sorted lists, `a` and `b`, return sorted list of both.\n\n You may not use sorted() or .sort().\n\n >>> a = [1, 3, 5, 7]\n >>> b = [2, 6, 8, 10]\n >>> sort_ab(a, b)\n [1, 2, 3, 5, 6, 7, 8, 10]\n\n \"\"\"\n\n a_ctr = 0 \n b_ctr = 0 \n sorted_ab = []\n\n # print(a, len(a))\n # print(b, len(b))\n\n while ( (a_ctr < len(a)) and (b_ctr < len(b)) ) : \n # print(a_ctr)\n # print(b_ctr)\n # print(sorted_ab)\n if a[a_ctr] < b[b_ctr] : \n # print(\"A\")\n sorted_ab.append(a[a_ctr])\n # print(sorted_ab)\n # print(a_ctr)\n a_ctr += 1 \n elif b[b_ctr] < a[a_ctr] : \n # print(\"B\")\n sorted_ab.append(b[b_ctr])\n b_ctr += 1\n elif a[a_ctr] == b[b_ctr] : \n # print(\"C\")\n sorted_ab.append(a[a_ctr])\n sorted_ab.append(b[b_ctr])\n a_ctr += 1 \n b_ctr += 1\n \n\n sorted_ab.extend(a[a_ctr:])\n sorted_ab.extend(b[b_ctr:])\n\n return sorted_ab\n\n\nif __name__ == '__main__': \n\n import doctest \n\n results = doctest.testmod()\n\n if results.failed == 0: \n print(\"ALL TESTS PASSED\")\n\n\n","sub_path":"sort_sorted_list.py","file_name":"sort_sorted_list.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"521680334","text":"import torch as tr\nimport numpy as np\nimport pickle as pk\nGame2048State = __import__('2048_game').Game2048State\nimport expectimax_ai as expect_ai\n\n# #1\n# Encode a 2048_game.Game2048State\n# Will be called by get_batch\n# return a tensor\ndef encode(state):\n return tr.from_numpy(state.board).float()\n \n# #2\n# Generate training data for NN\n# Needs to call encode function to encode state\n# return: (input, output)\n# input: stacked list of encoded states\n# output: stacked list of correspond utilities\ndef get_batch(board_size, num_games):\n inputs = []\n outputs = []\n\n # Perform 25 games\n for _ in range(0, 25):\n # Start new game\n state = Game2048State(board_size)\n state = state.initialState()\n\n # Iterate num_games times\n for i in range(0, num_games):\n # Game ended\n if state.isGameEnded()[0]: break\n\n # Record state\n inputs.append(encode(state))\n\n # Tree search next state\n state = expect_ai.getNextState(state)\n\n # Utility of tree searched state\n node = expect_ai.Node(state, None)\n outputs.append(tr.tensor([node.getUtility()]))\n\n # Add new tile to the game\n state = state.addNewTile()\n \n # Stack tensor\n inputs = tr.stack(inputs)\n outputs = tr.stack(outputs)\n\n # Result\n return (inputs, outputs)\n\n# #3\n# Generate training data file\n# Call get_batch function, save training data as a \".pkl\" file\nif __name__ == \"__main__\":\n for board_size in [2,4,6,8,10]:\n print(\"Working on data%d.pkl...\" % board_size)\n num_games = 50\n with open(\"data%d.pkl\" % board_size, \"wb\") as f: pk.dump(get_batch(board_size, num_games), f)\n print(\"data%d.pkl generated\" % board_size)","sub_path":"game-tree+NN-based-AI/expectimax_NN_data.py","file_name":"expectimax_NN_data.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"493457658","text":"\"\"\"\nModule for running ARIMA on players\n\"\"\"\nimport time\nimport streamlit as st\nimport numpy as np\nimport pandas as pd\nimport pmdarima as pm\nfrom sklearn.preprocessing import PowerTransformer\n\ndef calculate_errors(residuals):\n \"\"\" Calculates errors based on residuals \"\"\"\n num_residuals = len(residuals)\n mfe = (residuals.sum() / num_residuals).tolist()[0]\n mae = (residuals.abs().sum() / num_residuals).tolist()[0]\n rmse = (residuals.pow(2).sum().pow(0.5)).tolist()[0]\n residuals = residuals.values\n residuals = [value.item() for value in residuals]\n return mfe, mae, rmse\n\ndef calculate_test_residuals(prediction_array, test_data):\n \"\"\" Calculates test residuals based on prediction and test data \"\"\"\n prediction_array = prediction_array.reshape(len(test_data), 1)\n test_data = test_data.values\n residuals = np.subtract(test_data, prediction_array)\n residuals = residuals.tolist()\n residuals = pd.DataFrame(residuals)\n return residuals\n\ndef player_arima(data,\n player_name,\n index='date',\n feature='cumStatpoints',\n forecast_from='2018-10-03',\n transform='none',\n player_id=None,\n roster=None,\n summary=False):\n \"\"\" performs Auto-ARIMA on a single player \"\"\"\n # TODO: add logic for if the player ID is given but not a roster (use function in package)\n if player_id and roster:\n player_name = roster[roster['Unnamed: 0'] == player_id]\n player_df = data[data['name'] == player_name]\n player_df.drop_duplicates(subset='date', keep='first', inplace=True)\n player_train_df = player_df[player_df['date'] < forecast_from]\n player_test_df = player_df[player_df['date'] >= forecast_from]\n player_train_df = player_train_df.loc[:, [index, feature]]\n player_train_df = player_train_df.set_index(index, drop=True)\n if player_train_df.shape[0] == 0:\n st.write('{} is a rookie!'.format(player_name))\n return None\n if transform == 'log':\n # TODO: make this stat agnostic\n player_train_df.loc[:, 'logValues'] = np.log(player_train_df['cumStatpoints'])\n elif transform == 'yj':\n transformer = PowerTransformer()\n transformer.fit(player_train_df.values.reshape(-1, 1))\n player_train_df.loc[:, 'transformedValues'] = transformer \\\n .transform(\n player_train_df['cumStatpoints'] \\\n .values.reshape(-1, 1))\n player_train_df.drop('cumStatpoints', axis=1, inplace=True)\n player_test_df = player_test_df.loc[:, [index, feature]]\n player_test_df = player_test_df.set_index(index, drop=True)\n # player_train_df = player_train_df[:'2018-10-03']\n # player_test_df = player_test_df['2018-10-03':]\n if player_test_df.shape[0] == 0:\n st.write('{} retired!'.format(player_name))\n return None\n start_time = time.time()\n st.write('Searching ARIMA parameters for {}...'.format(player_name))\n try:\n model = pm.auto_arima(player_train_df,\n start_p=1,\n start_q=1,\n max_p=5,\n max_q=5,\n max_d=3,\n m=3,\n start_P=0,\n start_Q=0,\n seasonal=True,\n information_criterion='aicc',\n error_action='ignore',\n suppress_warnings=True,\n stepwise=True)\n st.write('Model built, fitting...')\n model.fit(player_train_df)\n except ValueError:\n st.write(\"{} doesn't have enough data!\".format(player_name))\n return None\n except IndexError:\n st.write('Index error for {}'.format(player_name))\n return None\n except:\n st.write('Unhandled error for {}'.format(player_name))\n return None\n predictions, intervals = model.predict(n_periods=player_test_df.shape[0], return_conf_int=True)\n if transform == 'log':\n predictions = np.exp(predictions)\n intervals = np.exp(intervals)\n elif transform == 'yj':\n predictions = transformer.inverse_transform(predictions.reshape(-1, 1))\n low_intervals = transformer.inverse_transform(intervals[:, 0].reshape(-1, 1))\n high_intervals = transformer.inverse_transform(intervals[:, 1].reshape(-1, 1))\n end_time = time.time()\n if transform != 'yj':\n low_intervals = []\n high_intervals = []\n for low, high in intervals:\n low_intervals.append(low)\n high_intervals.append(high)\n prediction_residuals = calculate_test_residuals(predictions, player_test_df)\n if summary:\n st.text(model.summary())\n train_residuals = pd.DataFrame(model.resid())\n train_mfe, train_mae, train_rmse = calculate_errors(train_residuals)\n test_mfe, test_mae, test_rmse = calculate_errors(prediction_residuals)\n model_params = model.get_params()\n p, d, q = model_params['order']\n try:\n P, D, Q, m = model_params['seasonal_order']\n except TypeError:\n st.write('Search failed to find valid options.')\n return None\n st.write(\"{0}'s Auto-ARIMA({1},{2},{3})({4},{5},{6},{7}) took {8:.3f} seconds.\" \\\n .format(player_name, p, d, q, P, D, Q, m, end_time-start_time))\n results_df = pd.DataFrame({'forecastStart':forecast_from,\n 'aic':model.aic(),\n 'p':p,\n 'd':d,\n 'q':q,\n 'P':P,\n 'D':D,\n 'Q':Q,\n 'm':m,\n 'trainMfe':train_mfe,\n 'trainMae':train_mae,\n 'trainRmse':train_rmse,\n 'trainResiduals':[train_residuals],\n 'testMfe':test_mfe,\n 'testMae':test_mae,\n 'testRmse':test_rmse,\n 'testResiduals':[prediction_residuals],\n 'intervalLow':[low_intervals],\n 'intervalHigh':[high_intervals]},\n index=[player_name])\n return results_df\n\ndef all_player_arima(data, roster, save_loc, transform='none', print_status=False):\n \"\"\" performs Auto_ARIMA on all players in a given roster \"\"\"\n if print_status:\n print('Running Auto-ARIMAs...')\n results = pd.DataFrame()\n for index, player in roster.iterrows():\n if print_status:\n print('Player {}'.format(index))\n player_name = player['name']\n player_results = player_arima(data, player_name=player_name, transform=transform)\n if isinstance(player_results, type(None)):\n st.write('Skipping {}'.format(player_name))\n continue\n st.dataframe(player_results)\n results = pd.concat([results, player_results])\n results.to_pickle(save_loc)\n if print_status:\n print('Done!')\n return results\n","sub_path":"AutoDraft/autodraft/arima.py","file_name":"arima.py","file_ext":"py","file_size_in_byte":7415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"425527095","text":"\n'''\nYou will receive a list of the cutomers (numbers seperated by comma and space \", \")\nand list of your taxis (numbers seperated by comma and space \", \").\n -- Each number from the customer list represents how much time it takes to drive the customer to his/her destination.\n -- Each number from the taxis list represents how much time they can drive, before they need to refill their tanks.\n -- Keep track of the total time passed to drive all the customers to their destinations (values of all customers).\n -- Each time you tend customers you should put the first customer in the last taxi until there are no customers left.\n\n - If the taxi can drive the customer to his/her destination, he does and\n - You must add the time passed to drive the customer to his/her destination to the total time.\n - Remove both the customer and the taxi.\n - If the taxi cannot drive the customer to his/her destination,\n leave the customer at the beginning of the queue and remove the taxi.\n\nAt the end if you have successfully driven all the customers to their destinations,\n print \"All customers were driven to their destinations Total time: {total_time} minutes\"\n\nOtherwise, if you ran out of taxis and there are still some customers left print \n \"Not all customers were driven to their destinations Customers left: {left_customers joined by \", \"}\"\"\n'''\n\nfrom collections import deque\n\ncustomers = deque([int(i) for i in input().split(\", \")])\ntaxis = [int(i) for i in input().split(\", \")]\n\n#print(customers)\n#print(taxis)\n\ntotal_drive = 0\ntaxis_left = True\n\nwhile customers:\n if len(taxis) > 0:\n customer = customers[0]\n taxi = taxis[-1]\n\n if taxi >= customer:\n total_drive += customer\n customers.popleft()\n taxis.pop()\n\n else:\n taxis.pop()\n else:\n taxis_left = False\n break\n\nif len(customers) == 0:\n print(\"All customers were driven to their destinations\")\n print(f'Total time: {total_drive} minutes')\nelse:\n print('Not all customers were driven to their destinations')\n print(f'Customers left: {\", \".join([str(c) for c in customers])}')\n","sub_path":"2_advanced/exam_prep/2020-08-19-01_taxi_express.py","file_name":"2020-08-19-01_taxi_express.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"233490000","text":"import itertools\nimport sys\n\nmain_grid = [[] for x in range(9)]\ncandidates_grid = [[set() for y in range(9)] for x in range(9)]\ncol_set = [set() for x in range(9)] # Access: col_set[x]\nrow_set = [set() for x in range(9)] # Access: row_set[y]\nsub_grid_set = [[set() for y in range(3)] for x in range(3)]\nfull_set = {1, 2, 3, 4, 5, 6, 7, 8, 9}\ncoordinates_set = {0, 1, 2, 3, 4, 5, 6, 7, 8}\n\ndef init():\n with open(\"../puzzles/extreme3.txt\") as puzzle:\n for y in range(9):\n next_line = puzzle.readline()\n for x in range(9):\n main_grid[x].append(int(next_line[x]))\n if next_line[x] != '0':\n col_set[x].add(int(next_line[x]))\n row_set[y].add(int(next_line[x]))\n sub_grid_set[x // 3][y // 3].add(int(next_line[x]))\n\n for y in range(9):\n for x in range(9):\n if main_grid[x][y] == 0:\n candidate_set = set.union(row_set[y], col_set[x], sub_grid_set[x // 3][y // 3])\n candidates_grid[x][y] = full_set.difference(candidate_set)\n\ndef iter_over_subgrids(func, *args):\n for sub_grid_y in range(3):\n for sub_grid_x in range(3):\n func(sub_grid_x, sub_grid_y, *args)\n\ndef iter_over_line(func, *args):\n for square in range(9):\n func(square, *args)\n\ndef print_main_grid():\n for y in range(9):\n for x in range(9):\n print(main_grid[x][y], end=\"\")\n if x % 3 == 2:\n print(\" \", end=\"\")\n print(\"\")\n\ndef is_solved():\n for y in range(9):\n if len(row_set[y]) != 9:\n return False\n return True\n\ndef pencil_in(solution, x, y, func):\n sub_grid_x = x // 3\n sub_grid_y = y // 3\n main_grid[x][y] = solution\n row_set[y].add(solution)\n col_set[x].add(solution)\n sub_grid_set[sub_grid_x][sub_grid_y].add(solution)\n candidates_grid[x][y].clear()\n for sg_y in range(sub_grid_y * 3, sub_grid_y * 3 + 3):\n for sg_x in range(sub_grid_x * 3, sub_grid_x * 3 + 3):\n candidates_grid[sg_x][sg_y].discard(solution)\n for i in range(9):\n candidates_grid[x][i].discard(solution)\n candidates_grid[i][y].discard(solution)\n\ndef single_candidate_square(y):\n for x in range(9):\n if len(candidates_grid[x][y]) == 1:\n pencil_in(candidates_grid[x][y].pop(), x, y, single_candidate_square)\n \ndef disjoint_subsets_row(y, n):\n sets = []\n for x in range(9):\n if 1 < len(candidates_grid[x][y]) <= n:\n sets.append(candidates_grid[x][y])\n for d in get_disjoint_subsets(sets, n):\n for x in range(9):\n if not candidates_grid[x][y].issubset(d):\n candidates_grid[x][y] = candidates_grid[x][y].difference(d)\n\ndef disjoint_subsets_col(x, n):\n sets = []\n for y in range(9):\n if 1 < len(candidates_grid[x][y]) <= n:\n sets.append(candidates_grid[x][y])\n for d in get_disjoint_subsets(sets, n):\n for y in range(9):\n if not candidates_grid[x][y].issubset(d):\n candidates_grid[x][y] = candidates_grid[x][y].difference(d)\n\ndef disjoint_subsets_subgrid(sub_grid_x, sub_grid_y, n):\n sets = []\n for y in range(sub_grid_y * 3, sub_grid_y * 3 + 3):\n for x in range(sub_grid_x * 3, sub_grid_x * 3 + 3):\n if 1 < len(candidates_grid[x][y]) <= n:\n sets.append(candidates_grid[x][y])\n for d in get_disjoint_subsets(sets, n):\n for y in range(sub_grid_y * 3, sub_grid_y * 3 + 3):\n for x in range(sub_grid_x * 3, sub_grid_x * 3 + 3):\n if not candidates_grid[x][y].issubset(d):\n candidates_grid[x][y] = candidates_grid[x][y].difference(d)\n\ndef get_disjoint_subsets(sets, n):\n disjoint_subsets = set()\n for combination in itertools.combinations(sets, n):\n superset = set()\n for c in combination:\n superset = superset.union(c)\n if len(superset) == n:\n disjoint_subsets.add(frozenset(superset))\n return disjoint_subsets\n\ndef solve():\n for x in range(100):\n iter_over_line(single_candidate_square)\n for n in range(2, 5):\n iter_over_line(disjoint_subsets_row, n)\n iter_over_line(disjoint_subsets_col, n)\n iter_over_subgrids(disjoint_subsets_subgrid, n)\n if is_solved() == 1:\n print_main_grid()\n break\n\ninit()\nsolve()","sub_path":"src/sudoku-minimal.py","file_name":"sudoku-minimal.py","file_ext":"py","file_size_in_byte":4446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"605368879","text":"def judge(q,m):\n for i in range(m):\n for j in range(i):\n if q[i] == q[j]:\n return 0\n elif q[i] == q[j] + i - j:\n return 0\n elif q[i] == q[j] + j - i:\n return 0\n\n return 1\n\ndef backtracking(q,i):\n global m2\n k = 1\n for j in range(8):\n q[i]=j\n if i != 0: #不为第一行,则判断当前可行性,不可行则回溯到上一层\n k = judge(q,i+1)\n if k == 1:\n if (i+1 != 8): #可行,则继续往下填充皇后\n backtracking(q,i+1)\n else: #若为最后一行,则计数+1\n m2+=1\n print(q)\n\n\nm2 = 0\nq = [[]]*8\nbacktracking(q,0)\nprint(m2)\n\n","sub_path":"8queen1.py","file_name":"8queen1.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"506809106","text":"import argparse\nimport random\nimport subprocess\nimport sys\nimport xmlrpc.client\n\nfrom transformers import GPT2Tokenizer\n\nserver = xmlrpc.client.ServerProxy('http://localhost:8000')\n\ntokenizer = GPT2Tokenizer.from_pretrained('distilgpt2')\n\nPROMPT='''NOUNS: cheetah lion seal mosquito dog cat\nOUTLIERS: none\nCLASS: animal\n\nNOUNS: shirt pants computer skirt dress slacks suit tie jacket\nOUTLIERS: computer\nCLASS: clothing\n\nNOUNS: computer candle controller lighter cup paper\nOUTLIERS: none\nCLASS: object\n\nNOUNS: monitor tv display\nOUTLIERS: none\nCLASS: screen\n\nNOUNS: google dog amazon yahoo netflix\nOUTLIERS: dog\nCLASS: website\n\nNOUNS: %s\nOUTLIERS:'''\n\ndef gen_nouns(nouns):\n\tinp = PROMPT % (nouns,)\n\tinput_ids = tokenizer(inp, return_tensors='pt').input_ids\n\n\tresp = server.gen(inp, args.temp, args.rep_pen, min(2048, len(input_ids.squeeze())+args.resp_length))\n\n\treturn resp.split('\\n')[:len(inp.split('\\n'))+1][-1].split(': ')[-1]\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser(description='Complete text with GPT')\n\n\tparser.add_argument('nouns', type=str)\n\n\tparser.add_argument('--temp', type=float, default=0.2, help='Completion temperature')\n\n\tparser.add_argument('--rep_pen', type=float, default=1.1, help='Completion repetition penalty')\n\n\tparser.add_argument('--resp_length', type=int, default=128, help='Completion length, in tokens')\n\n\tparser.add_argument('--prompt_limit', type=int, default=512, help='The maximum number of tokens to use for the story generation prompt')\n\n\tparser.add_argument('--num_stories', type=int, default=5, help='The number of stories to generate')\n\n\tparser.add_argument('--num_similar', type=int, default=3, help='The number of similar stories to generate for each story, to help refine schemas')\n\n\tparser.add_argument('--similar_temp', type=float, default=0.4, help='Completion temperature for similar story generation')\n\n\tparser.add_argument('--similar_rep_pen', type=float, default=1.12, help='Completion repetition penalty for similar story generation')\n\n\tparser.add_argument('--output_dir', type=str, default='.', help='The directory to store the output story files in AFTER tokenization')\n\n\tparser.add_argument('--orig_story_dir', type=str, default='.', help='The directory to store the output story files in BEFORE tokenization')\n\n\targs = parser.parse_args()\n\n\tprint(gen_nouns(args.nouns))\n","sub_path":"pyschemas/noun_generalizer/gpt_gen.py","file_name":"gpt_gen.py","file_ext":"py","file_size_in_byte":2348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"59970153","text":"import copy\nimport itertools\n\n# 데이터 구성\nn, m, k = list(map(int, input().split(\" \")))\nmat = []\nfor _ in range(n):\n row = list(map(int, input().split(\" \")))\n mat.append(row)\ncases = []\nfor _ in range(k):\n row = list(map(int, input().split(\" \")))\n cases.append(row)\ncomb_cases = itertools.permutations(cases, k) # 순서를 바꿔서도 진행해봐야 함\n\n# 시계방향으로 회전시켜주는 함수\ndef rotate(mat, case):\n # 각 인덱스가 +1 되어 있기 때문에 빼준다.\n left_top = (case[0] - case[2] - 1, case[1] - case[2] - 1)\n right_down = (case[0] + case[2] - 1, case[1] + case[2] - 1)\n tmp_mat = copy.deepcopy(mat) # 돌릴 행렬을 copy해준다\n while left_top != right_down:\n tmp_col = left_top[1] # 좌표\n tmp_row = left_top[0] # 좌표\n max_col = right_down[1] # max\n max_row = right_down[0] # max\n min_col = left_top[1] # min\n min_row = left_top[0] # min\n # 시계방향으로 돌려주기\n while True: # 오른쪽 끝으로 가는 케이스\n if tmp_col == max_col:\n break\n tmp_col += 1\n tmp_mat[tmp_row][tmp_col] = mat[tmp_row][tmp_col - 1]\n while True: # 오른쪽의 밑 끝으로 가는 케이스\n if tmp_row == max_row:\n break\n tmp_row += 1\n tmp_mat[tmp_row][tmp_col] = mat[tmp_row - 1][tmp_col]\n while True: # 왼쪽 끝으로 가는 케이스\n if tmp_col == min_col:\n break\n tmp_col -= 1\n tmp_mat[tmp_row][tmp_col] = mat[tmp_row][tmp_col + 1]\n while True: # 왼쪽 윗 끝으로 가는 케이스\n if tmp_row == min_row:\n break\n tmp_row -= 1\n tmp_mat[tmp_row][tmp_col] = mat[tmp_row + 1][tmp_col]\n # 중앙으로 둘의 간격을 좁혀준다.\n left_top = (left_top[0] + 1, left_top[1] + 1) # 얘는 하나씩 올리기\n right_down = (right_down[0] - 1, right_down[1] - 1) # 얘는 하나씩 줄이기\n return tmp_mat\n\n\nfin_min = 1000000\nfor comb_case in comb_cases: # 각 케이스별로 진행한다.\n tmp_mat = mat # matrix 복사해주기\n for case in comb_case: # 돌려주기\n tmp_mat = rotate(tmp_mat, case)\n for row in tmp_mat: # 최소 행렬값 구하기\n val = sum(row)\n if fin_min > val:\n fin_min = val\nprint(fin_min)\n","sub_path":"백준/백준_17406번.py","file_name":"백준_17406번.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"346299639","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nimport numpy as np\nimport math\n\n# Import scikit-learn metrics module for accuracy calculation\nfrom sklearn import metrics\n# preprossing is what we do with the data before we run the learning algorithm\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import chi2\n\n\n# In[2]:\n\n\ncol_names = ['pregnant', 'glucose', 'bp', 'skin', 'insulin', 'bmi', 'pedigree', 'age', 'label']\n# load dataset\npima = pd.read_csv(\"diabetes.csv\")\npima.columns = col_names\npima.head()\n\nfeature_cols = ['pregnant', 'glucose', 'bp', 'skin', 'insulin', 'bmi', 'pedigree', 'age']\nX = pima[feature_cols] # Features\ny = pima.label # Target variable\nX = X.to_numpy()\ny = y.to_numpy()\n\nX_train, X_test, y_train, y_test = train_test_split(X, y)\nscaler = preprocessing.StandardScaler().fit(X_train)\nX_train = scaler.transform(X_train)\nX_test = scaler.transform(X_test)\n\n# Append a column of ones to x_train\n# Step 1: Create a column vector of ones (i.e. a vector of shape N',1)\nones = np.ones(X_train.shape[0]).reshape((X_train.shape[0], 1))\n# Step 2: Append a column of ones in the beginning of x_train\nX_train = np.hstack((ones, X_train))\n\n# Now do the same for the test data\n# Step 1: Create a column vector of ones (i.e. a vector of shape N\",1)\nones = np.ones(X_test.shape[0]).reshape((X_test.shape[0], 1))\n# Stemp 2: Append a column of ones in the beginning of x_test\nX_test = np.hstack((ones, X_test))\n\n\n# In[3]:\n\n\n# Logistic Regression using sklearn feature selection\nclf = LogisticRegression(random_state=0,tol=0.001).fit(X_train, y_train)\nbase_train = clf.score(X_train, y_train)\nbase_test = clf.score(X_test, y_test)\nprint(\"Logistic Regression:\")\nprint(\"train Accuracy:\",base_train)\nprint(\"test Accuracy:\",base_test,\"\\n\")\n\n# feature extraction\nfor i in range(9):\n tmp = np.delete(X_train, i, axis = 1)\n tmp1 = np.delete(X_test, i, axis = 1)\n clf = LogisticRegression(random_state=0,tol=0.001).fit(tmp, y_train)\n fs_train = clf.score(tmp, y_train)\n fs_test = clf.score(tmp1, y_test)\n if fs_train > base_train:\n if fs_test >= base_test:\n print(\"Feature Selection:\")\n print(\"remove\",i)\n print(\"train Accuracy:\",fs_train)\n print(\"test Accuracy:\",fs_test,\"\\n\")\n\n\n# In[4]:\n\n\n# logistic Regression from scratch\ndef sigmoid(z):\n return 1 / (1 + math.exp(-z))\n\nw = np.zeros((X_train.shape[1], 1))\nprint(w.shape)\n\ndef hypothesis(X, w):\n h = np.ones((X.shape[0],1))\n for i in range(0,X.shape[0]):\n z = np.matmul(X[i], w)\n h[i] = sigmoid(z)\n return h\n\n# Compute y_hat using our training examples and w (w is still set to zero).\n# This is just a preliminary test of the hypotheis function\nyhat = hypothesis(X_train, w)\n\n# print the sizes of yhat and y as a first check that the function performed correctly\nprint(yhat.shape)\nprint(y_train.shape)\n\ndef log_likelihood(X, y, w):\n log_likelihood = 0\n for i in range(0,X.shape[0]):\n z = np.matmul(X[i], w)\n log_likelihood += y[i] * np.log(sigmoid(z)) + (1 - y[i]) * np.log((1 - sigmoid(z))) \n return log_likelihood\n\ndef Logistic_Regresion_Gradient_Ascent(X, y, learning_rate, num_iters):\n # For every 100 iterations, store the log_likelihood for the current w\n # Initializing log_likelihood to be an empty list\n log_likelihood_values = []\n # Initialize w to be a zero vector of shape x_train.shape[1],1\n w = np.zeros((X.shape[1], 1))\n # Initialize N to the number of training examples\n N = X.shape[0]\n \n for i in range (num_iters):\n y_hat = hypothesis(X, w)\n temp = 0\n for j in range (0,N):\n temp += (y[j] - y_hat[j]) * X[j]\n for k in range (0,w.shape[0]):\n w[k] = w[k] + (learning_rate / N) * temp[k]\n if (i % 100) == 0:\n log_likelihood_values.append(log_likelihood(X,y,w))\n \n return w, log_likelihood_values\n\nlearning_rate = 0.1\nnum_iters = 100 # The number of iteratins to run the gradient ascent algorithm\nw, log_likelihood_values = Logistic_Regresion_Gradient_Ascent(X_train, y_train, learning_rate, num_iters)\n\n\n# In[5]:\n\n\ndef predict(X_test, w):\n pred = hypothesis(X_test, w)\n res = []\n for i in range(0,len(pred)):\n if pred[i] >= 0.5:\n res.append(1)\n else:\n res.append(0)\n return res\n\ntrain_pred = predict(X_train, w)\ntest_pred = predict(X_test, w)\nprint(\"Logistic Regression:\")\nprint(\"train Accuracy:\",metrics.accuracy_score(y_train, train_pred))\nprint(\"test Accuracy:\",metrics.accuracy_score(y_test, test_pred),\"\\n\")\n\n# feature extraction\nfor i in range(9):\n tmp = np.delete(X_train, i, axis = 1)\n tmp1 = np.delete(X_test, i, axis = 1)\n clf = LogisticRegression(random_state=0,tol=0.001).fit(tmp, y_train)\n fs_train = clf.score(tmp, y_train)\n fs_test = clf.score(tmp1, y_test)\n if fs_train > base_train:\n if fs_test >= base_test:\n print(\"Feature Selection:\")\n print(\"remove\",i)\n print(\"train Accuracy:\",fs_train)\n print(\"test Accuracy:\",fs_test,\"\\n\")\n\n\n# In[6]:\n\n\n# Random forest sklearn\ncol_names = ['pregnant', 'glucose', 'bp', 'skin', 'insulin', 'bmi', 'pedigree', 'age', 'label']\n# load dataset\npima = pd.read_csv(\"diabetes.csv\")\npima.columns = col_names\npima.head()\n\nfeature_cols = ['pregnant', 'glucose', 'bp', 'skin', 'insulin', 'bmi', 'pedigree', 'age']\nX = pima[feature_cols] # Features\ny = pima.label # Target variable\n\n# Split dataset into training set and test set\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1) # 80% training and 20% test\n\n# default (criterion=”gini”)\nclf = RandomForestClassifier(max_depth=4, random_state=2)\nclf = clf.fit(X_train,y_train)\ntrain_pred = clf.predict(X_train)\ntest_pred = clf.predict(X_test)\nprint(\"Random Forest:\")\nprint(\"train Accuracy:\",metrics.accuracy_score(y_train, train_pred))\nprint(\"test Accuracy:\",metrics.accuracy_score(y_test, test_pred),\"\\n\")\n\n\n# In[7]:\n\n\n# Random Forest Algorithm on diabetes.csv from scratch\nfrom random import randrange\nfrom csv import reader\nfrom math import sqrt\n\n# Load a CSV file\ndef load_csv(filename):\n dataset = list()\n with open(filename, 'r') as file:\n csv_reader = reader(file)\n for row in csv_reader:\n if not row:\n continue\n dataset.append(row)\n return dataset\n\n# Convert string column to integer\ndef str_column_to_int(dataset, column):\n class_values = [row[column] for row in dataset]\n unique = set(class_values)\n lookup = dict()\n for i, value in enumerate(unique):\n lookup[value] = i\n for row in dataset:\n row[column] = lookup[row[column]]\n return lookup\n\n# Split a dataset into k folds\ndef cross_validation_split(dataset, n_folds):\n dataset_split = list()\n dataset_copy = list(dataset)\n fold_size = int(len(dataset) / n_folds)\n for i in range(n_folds):\n fold = list()\n while len(fold) < fold_size:\n index = randrange(len(dataset_copy))\n fold.append(dataset_copy.pop(index))\n dataset_split.append(fold)\n return dataset_split\n\n# Calculate accuracy percentage\ndef accuracy_metric(actual, predicted):\n correct = 0\n for i in range(len(actual)):\n if actual[i] == predicted[i]:\n correct += 1\n return correct / float(len(actual)) * 100.0\n\n# Evaluate an algorithm using a cross validation split\ndef evaluate_algorithm(dataset, algorithm, n_folds, *args):\n folds = cross_validation_split(dataset, n_folds)\n scores = list()\n for fold in folds:\n train_set = list(folds)\n train_set.remove(fold)\n train_set = sum(train_set, [])\n test_set = list()\n for row in fold:\n row_copy = list(row)\n test_set.append(row_copy)\n row_copy[-1] = None\n predicted = algorithm(train_set, test_set, *args)\n actual = [row[-1] for row in fold]\n accuracy = accuracy_metric(actual, predicted)\n scores.append(accuracy)\n return scores\n\n# Split a dataset based on an attribute and an attribute value\ndef test_split(index, value, dataset):\n left, right = list(), list()\n for row in dataset:\n if row[index] < value:\n left.append(row)\n else:\n right.append(row)\n return left, right\n\n# Calculate the Gini index for a split dataset\ndef gini_index(groups, classes):\n # count all samples at split point\n n_instances = float(sum([len(group) for group in groups]))\n # sum weighted Gini index for each group\n gini = 0.0\n for group in groups:\n size = float(len(group))\n # avoid divide by zero\n if size == 0:\n continue\n score = 0.0\n # score the group based on the score for each class\n for class_val in classes:\n p = [row[-1] for row in group].count(class_val) / size\n score += p * p\n # weight the group score by its relative size\n gini += (1.0 - score) * (size / n_instances)\n return gini\n\n# Select the best split point for a dataset\ndef get_split(dataset, n_features):\n class_values = list(set(row[-1] for row in dataset))\n b_index, b_value, b_score, b_groups = 999, 999, 999, None\n features = list()\n while len(features) < n_features:\n index = randrange(len(dataset[0])-1)\n if index not in features:\n features.append(index)\n for index in features:\n for row in dataset:\n groups = test_split(index, row[index], dataset)\n gini = gini_index(groups, class_values)\n if gini < b_score:\n b_index, b_value, b_score, b_groups = index, row[index], gini, groups\n return {'index':b_index, 'value':b_value, 'groups':b_groups}\n\n# Create a terminal node value\ndef to_terminal(group):\n outcomes = [row[-1] for row in group]\n return max(set(outcomes), key=outcomes.count)\n\n# Create child splits for a node or make terminal\ndef split(node, max_depth, min_size, n_features, depth):\n left, right = node['groups']\n del(node['groups'])\n # check for a no split\n if not left or not right:\n node['left'] = node['right'] = to_terminal(left + right)\n return\n # check for max depth\n if depth >= max_depth:\n node['left'], node['right'] = to_terminal(left), to_terminal(right)\n return\n # process left child\n if len(left) <= min_size:\n node['left'] = to_terminal(left)\n else:\n node['left'] = get_split(left, n_features)\n split(node['left'], max_depth, min_size, n_features, depth+1)\n # process right child\n if len(right) <= min_size:\n node['right'] = to_terminal(right)\n else:\n node['right'] = get_split(right, n_features)\n split(node['right'], max_depth, min_size, n_features, depth+1)\n\n# Build a decision tree\ndef build_tree(train, max_depth, min_size, n_features):\n root = get_split(train, n_features)\n split(root, max_depth, min_size, n_features, 1)\n return root\n\n# Make a prediction with a decision tree\ndef predict(node, row):\n if row[node['index']] < node['value']:\n if isinstance(node['left'], dict):\n return predict(node['left'], row)\n else:\n return node['left']\n else:\n if isinstance(node['right'], dict):\n return predict(node['right'], row)\n else:\n return node['right']\n\n# Create a random subsample from the dataset with replacement\ndef subsample(dataset, ratio):\n sample = list()\n n_sample = round(len(dataset) * ratio)\n while len(sample) < n_sample:\n index = randrange(len(dataset))\n sample.append(dataset[index])\n return sample\n\n# Make a prediction with a list of bagged trees\ndef bagging_predict(trees, row):\n predictions = [predict(tree, row) for tree in trees]\n return max(set(predictions), key=predictions.count)\n\n# Random Forest Algorithm\ndef random_forest(train, test, max_depth, min_size, sample_size, n_trees, n_features):\n trees = list()\n for i in range(n_trees):\n sample = subsample(train, sample_size)\n tree = build_tree(sample, max_depth, min_size, n_features)\n trees.append(tree)\n predictions = [bagging_predict(trees, row) for row in test]\n return(predictions)\n\n# load and prepare data\nfilename = 'diabetes.csv'\ndataset = load_csv(filename)\n# convert class column to integers\nstr_column_to_int(dataset, len(dataset[0])-1)\n# evaluate algorithm\nn_folds = 5\nmax_depth = 4\nmin_size = 1\nsample_size = 1.0\nn_features = int(sqrt(len(dataset[0])-1))\nprint(\"Random Forest:\")\nfor n_trees in [5, 10, 15]:\n scores = evaluate_algorithm(dataset, random_forest, n_folds, max_depth, min_size, sample_size, n_trees, n_features)\n print('Trees: %d' % n_trees)\n print('Scores: %s' % scores)\n print('Mean Accuracy: %.3f%%' % (sum(scores)/float(len(scores))))\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Project/diabetes-dataset.py","file_name":"diabetes-dataset.py","file_ext":"py","file_size_in_byte":13146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"84794","text":"import logging\n\nimport requests\nfrom flask import request, jsonify\nfrom flask_restful import Resource\n\nfrom db import db\nfrom models import ReposInfo\n\n\nclass GetReposFromGithubResources(Resource):\n def get(self):\n args = request.args\n name_of_repo = args['name']\n logging.info(f\"requested to get all repos from acc '{name_of_repo}'\")\n try:\n logging.info(\"Send request to github\")\n response = requests.get(f'https://api.github.com/orgs/{name_of_repo}/repos')\n logging.info(\"Response obtained. Starting to add data to DB \")\n result = response.json()\n counter = 0\n for item in result:\n logging.info(f\"Create {counter} instance of repo\")\n db.session.add(\n ReposInfo(\n repo_id=item['id'],\n name=item['name'],\n html_url=item['html_url'],\n description=item['description'],\n private=item['private'],\n created_at=item['created_at'],\n watchers=item['watchers_count'],\n )\n )\n counter += 1\n logging.info(f\"Commit all instances to DB\")\n db.session.commit()\n return result\n except Exception as e:\n logging.error(f'Error in getting data from github. Error: {e}')\n return f'something went wrong while getting repo info from github, {e}'\n\n\nclass AllReposResources(Resource):\n def get(self):\n logging.info(\"requested to get all repos from db\")\n try:\n logging.info(\"Getting all repos from db\")\n all_repos = ReposInfo.query.all()\n return jsonify([e.serialize() for e in all_repos])\n except Exception as e:\n logging.error(f'Error in getting data from db. Error: {e}')\n return 'something went wrong while getting info from db'\n\n\nclass GetRepoResources(Resource):\n def get(self):\n logging.info(\"requested to get specific repo from db\")\n try:\n args = request.args\n repo_id = args['repo_id']\n logging.info(f\"Getting repo with id {repo_id} from db\")\n repo = ReposInfo.query.filter(ReposInfo.repo_id == repo_id).first()\n return jsonify(repo.serialize())\n except Exception as e:\n logging.error(f'Error in getting simple record from db. Error: {e}')\n return 'something went wrong while getting simple repo info from db'\n","sub_path":"api/app/worker/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"198404326","text":"'''\nCreated on Apr 13, 2011\n\n@author: christian\n'''\n\nimport logging\n\nfrom matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas\nfrom matplotlib.figure import Figure\n\nimport wx\n\nfrom eelbrain.psyphys import visualizers\n\nimport ID\n\n\n\n##### Events ##### ##### ##### ##### ##### ##### ####\nmyEVT_FIGURE_POS = wx.NewEventType()\nEVT_FIGURE_POS = wx.PyEventBinder(myEVT_FIGURE_POS, 1)\n\nclass FigurePosEvent(wx.PyCommandEvent):\n \"\"\"\n Event that is sent every time the user adjusts the view on a plot.\n \n \"\"\"\n def __init__(self, t0, t1, id=-1):\n wx.PyCommandEvent.__init__(self, myEVT_FIGURE_POS, id)\n self.t0 = t0\n self.t1 = t1\n\n\n\n##### Frames to test individual panels ##### ##### ##### #####\nclass OverviewFrame(wx.Frame):\n def __init__(self, parent, dataset):\n visualizer = visualizers.default(dataset)\n wx.Frame.__init__(self, parent)\n \n self.panel = OverviewPanel(self) \n self.panel.plot_overview([visualizer])\n\nclass ZoomFrame(wx.Frame):\n def __init__(self, parent, dataset):\n visualizer = visualizers.default(dataset)\n wx.Frame.__init__(self, parent)\n \n self.panel = ZoomPanel(self) \n self.panel.plot([visualizer])\n\n\n##### the Panels ##### ##### ##### #####\nclass CanvasPanel(wx.Panel):\n def __init__(self, parent, id=wx.ID_ANY):\n wx.Panel.__init__(self, parent, id=id)\n \n self.SetBackgroundColour(wx.NamedColour(\"WHITE\"))\n \n self.figure = Figure()\n self.canvas = FigureCanvas(self, -1, self.figure)\n self.canvas.Bind(wx.EVT_ENTER_WINDOW, self.OnEnterWindow)\n \n self.sizer = wx.BoxSizer(wx.VERTICAL)\n self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)\n self.SetSizer(self.sizer)\n self.Fit()\n \n self.Bind(wx.EVT_PAINT, self.OnPaint)\n def OnEnterWindow(self, event):\n \"http://matplotlib.sourceforge.net/examples/user_interfaces/wxcursor_demo.html\"\n self.canvas.SetCursor(wx.StockCursor(wx.CURSOR_CROSS))\n def OnPaint(self, event):\n logging.debug('%s: OnPaint!!!' % self.__class__.__name__)\n self.canvas.draw()\n def SendFigurePosEvent(self, t0, t1):\n # issue event\n logging.debug(\"EVENT sent!!\")\n evt = FigurePosEvent(t0, t1, id=self.GetId())\n self.GetEventHandler().ProcessEvent(evt)\n def OnFigurePosEvent(self, event):\n# logging.debug(\"EVENT received!!\")\n self.zoom(event.t0, event.t1, send_event=False)\n\n\n\n\nclass ZoomPanel(CanvasPanel):\n def __init__(self, parent, id=ID.CANVAS_PANEL_ZOOM):\n CanvasPanel.__init__(self, parent, id=id)\n \n # User interaction\n# self._dragging = 0\n# self._dt = 10\n self.canvas.mpl_connect('motion_notify_event', self.OnCanvasMotion)\n self.canvas.mpl_connect('button_press_event', self.OnCanvasMouseDown)\n self.canvas.mpl_connect('button_release_event', self.OnCanvasMouseUp)\n \n def plot(self, visualizers):\n self.figure.clf()\n \n ax = self.ax = self.figure.add_axes([0, .1, 1, .9], frame_on=False)\n for v in visualizers:\n v.toax(ax, None, None)\n \n self._tmin = self._t0 = t0 = v.tstart\n self._tmax = self._t1 = t1 = v.tend\n ax.set_xlim(t0, t1)\n \n def relative_zoom(self, factor):\n t0 = self._t0\n t1 = self._t1\n diff = ((t1 - t0) * (factor - 1)) / 2.\n self.zoom(t0 + diff, t1 - diff)\n def relative_move(self, factor):\n t0 = self._t0\n t1 = self._t1\n diff = (t1 - t0) * factor\n self.zoom(t0 + diff, t1 + diff)\n \n def zoom(self, t0, t1, send_event=True):\n t0 = self._t0 = max(self._tmin, t0)\n t1 = self._t1 = min(self._tmax, t1)\n self.ax.set_xlim(t0, t1)\n self.canvas.draw()\n \n if send_event:\n self.SendFigurePosEvent(t0, t1)\n \n def move(self, dt):\n t0 = self._t0 + dt\n t1 = self._t1 + dt\n if t0 < self._tmin:\n t1 += self._tmin - t0\n t0 = self._tmin\n elif t1 > self._tmax:\n t0 -= t1 - self._tmax\n t1 = self._tmax\n self.zoom(t0, t1)\n \n def move_t_to_x(self, t, x, send_event=True):\n # event.x is position within renderer\n width = self.canvas.get_renderer().width\n x_ratio = x / width\n dt = self._t1 - self._t0\n# t_rel = t - self._t0\n# t_ratio = t_rel / dt\n t0 = t - x_ratio * dt\n t1 = t0 + dt\n self.zoom(t0, t1, send_event=send_event)\n \n def OnCanvasMouseDown(self, event):\n if event.inaxes:\n self._t_grip = event.xdata\n self._xlim_grip = self._t0, self._t1\n self._grip_dt = 0\n# self._x_grip = event.x\n# self._r_width = self.canvas.get_renderer().width\n if wx.__version__ >= '2.9':\n CursorId = wx.CURSOR_CLOSED_HAND\n else:\n CursorId = wx.CURSOR_BULLSEYE\n self.canvas.SetCursor(wx.StockCursor(CursorId))\n def OnCanvasMouseUp(self, event):\n self.canvas.SetCursor(wx.StockCursor(wx.CURSOR_CROSS))\n def OnCanvasMotion(self, event):\n# logging.debug('x=%.2f, xdata=%.2f'%(event.x, event.xdata))\n if event.button and event.inaxes:\n self.move_t_to_x(self._t_grip, event.x, send_event=True)\n\n\nclass OverviewPanel(CanvasPanel):\n def __init__(self, parent, id=ID.CANVAS_PANEL_OVERVIEW):\n CanvasPanel.__init__(self, parent, id=id)\n \n # User interaction\n# self._dragging = False\n self._dt = 10\n self.canvas.mpl_connect('motion_notify_event', self.OnCanvasMotion)\n self.canvas.mpl_connect('button_press_event', self.OnCanvasMouseDown)\n self.canvas.mpl_connect('button_release_event', self.OnCanvasMouseUp)\n \n # Mouse Events\n def OnCanvasMotion(self, event):\n if event.inaxes and hasattr(self, '_t0'):\n self.set_marker_t1(event.xdata) \n def OnCanvasMouseDown(self, event):\n# logging.debug('mouse down t=%.2f'%event.xdata)\n if event.inaxes:\n self._t0 = event.xdata\n# self._dragging = True\n def OnCanvasMouseUp(self, event):\n# logging.debug('mouse up t=%.2f'%event.xdata)\n if hasattr(self, '_t0'):\n logging.debug('has t0')\n if event.inaxes:\n if self._t0 == event.xdata:\n self.set_marker_pos(event.xdata)\n else:\n self.set_marker_t1(event.xdata)\n del self._t0\n \n def OnPaint(self, event):\n logging.debug('%s: OnPaint!!!' % self.__class__.__name__)\n if self.marker:\n self.marker.remove()\n# self.figure.remove(self.marker)\n# self.ax.remove(self.marker)\n self.canvas.draw()\n self._background = self.canvas.copy_from_bbox(self.ax.bbox)\n self._ylim = self.ax.get_ylim()\n if self.marker:\n self.ax.add_artist(self.marker)\n self.draw_marker()\n event.Skip()\n \n def plot_overview(self, visualizers):\n self.figure.clf()\n \n ax = self.ax = self.figure.add_axes([0, .1, 1, .9], frame_on=False)\n for v in visualizers:\n v.toax(ax, None, None)\n \n self.marker = None\n self._tmin = t0 = v.tstart\n self._tmax = t1 = v.tend\n ax.set_xlim(t0, t1)\n \n def set_marker_pos(self, t):\n dt = self._dt / 2\n t1 = t - dt\n t2 = t + dt\n if t1 < self._tmin:\n t2 = min(t2 + (self._tmin - t1), self._tmax)\n t1 = self._tmin\n elif t2 > self._tmax:\n t1 = max(t1 - (t2 - self._tmax), self._tmin)\n t2 = self._tmax\n self.zoom(t1, t2)\n \n def set_marker_t1(self, t1):\n \"assumes that self._t0 is set\"\n self.zoom(self._t0, t1)\n \n def zoom(self, t1, t2, send_event=True):\n if t1 == t2:\n self.set_marker_pos(t1)\n return\n t_start = min(t1, t2)\n t_end = max(t1, t2)\n \n self.canvas.restore_region(self._background)\n \n if self.marker:\n# logging.debug('marker: just updating')\n xy = self.marker.get_xy()\n xy[0,0] = t1\n xy[1,0] = t1\n xy[2,0] = t2\n xy[3,0] = t2\n xy[4,0] = t1\n# logging.debug(xy)\n else:\n self.marker = self.ax.axvspan(t_start, t_end, edgecolor='r', \n hatch='/', fill=False, aa=False,\n zorder=0) #, alpha=.1)# fill=False)\n self._dt = t_end - t_start\n self.ax.set_xlim(self._tmin, self._tmax)\n self.ax.set_ylim(*self._ylim)\n self.draw_marker()\n \n if send_event:\n self.SendFigurePosEvent(t1, t2)\n# ax.set_xlim(*self.viewer.t_lim)\n def draw_marker(self):\n try:\n self.ax.draw_artist(self.marker)\n except Exception:\n logging.debug('DRAW exception: %s'%Exception)\n else:\n pass\n self.canvas.blit(self.ax.bbox)\n def del_marker(self):\n if self.marker:\n self.figure.remove(self.marker)\n self.marker = None\n self.canvas.draw()\n \n","sub_path":"eelbrain/wxgui/psyphys/view_panels.py","file_name":"view_panels.py","file_ext":"py","file_size_in_byte":9446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"483939477","text":"# Cards\r\n# Sebastian Puerta Hincapie\r\n\r\nclass Card(object):\r\n def __init__(self,suit=1,rank=2):\r\n if suit < 1 or suit > 4:\r\n print(\"invalid suit, setting to 1\")\r\n suit = 1\r\n self.suit = suit\r\n self.rank = rank\r\n\r\n def value(self):\r\n \"\"\" we want things order primarily by rank then suit \"\"\"\r\n return self.suit + (self.rank-1)*14\r\n\r\n #if we include this to allow for comparisons with < and > between cards\r\n def __lt__(self,other):\r\n return self.value() < other.value()\r\n\r\n # Python 2 by default uses ASCII, Python 3 uses Unicode\r\n def __unicode__(self):\r\n suit = [u\"\\u2668\", #spade\r\n u\"\\u2665\", #heart\r\n u\"\\u2666\", #diamond\r\n u\"\\u2777\"] #club\r\n r = str(self.rank)\r\n if self.rank == 11: r = \"J\"\r\n elif self.rank == 12: r = \"Q\"\r\n elif self.rank == 13: r = \"K\"\r\n elif self.rank == 14: r = \"A\"\r\n\r\n return r + ':' + suit[self.suit-1]\r\n\r\n def __str__(self):\r\n return self.__unicode__() # .encode(\"utf-8\")\r\n\r\nclass Deck(object):\r\n \"\"\" the deck is a collection of cards \"\"\"\r\n def __init__(self):\r\n self.nsuits = 4\r\n self.nranks = 13\r\n self.minrank = 2\r\n self.maxrank = self.minrank + self.nranks - 1\r\n\r\n self.cards = []\r\n\r\n for rank in range(self.minrank,self.maxrank+1):\r\n for suit in range(1,self.nsuits+1):\r\n self.cards.append(Card(rank=rank,suit=suit))\r\n\r\n def shuffle(self):\r\n random.shuffle(self.cards)\r\n\r\n def get_cards(self,num=1):\r\n hand = []\r\n for n in range(num):\r\n hand.append(self.cards.pop())\r\n return hand\r\n\r\n def __str__(self):\r\n string = \"\"\r\n for c in self.cards:\r\n string += str(c) + \" \"\r\n return string\r\n \r\ndef main():\r\n # test Card class\r\n c1 = Card()\r\n print(c1)\r\n c2 = Card(3,4)\r\n print(c2)\r\n c3 = Card(17,12)\r\n print(c1 < c2)\r\n print(c2 > c1)\r\n c1.value()\r\n\r\n # test Deck class\r\n mydeck = Deck()\r\n print(\"This is my deck\")\r\n print(mydeck)\r\n print(\"The length of the deck is: \")\r\n print(len(mydeck.cards))\r\n input(\"Press a key to continue with dealing a hand...\")\r\n print(\"Shuffling the deck...\")\r\n mydeck.shuffle()\r\n print(\"this is your hand\")\r\n hand = mydeck.get_cards(5)\r\n for c in sorted(hand) : print(c)\r\n\r\nmain()\r\n","sub_path":"Cards_SPH.py","file_name":"Cards_SPH.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"493023790","text":"import pyodbc\n\nclass SQLDatabaseAPI:\n def __init__(self):\n self.start_connection()\n\n \n def start_connection(self, server = \"databases1.spartaglobal.academy\", database = \"Northwind\", username = \"**\", password = \"**\"):\n \n try:\n print(\"Establishing Connection\")\n # connect to server with pyodbc.connect()\n self.db_connection = pyodbc.connect(f\"DRIVER=ODBC Driver 17 for SQL Server;SERVER={server};DATABASE={database};UID={username};PWD={password}\")\n # init cursor to execute queries\n self.cursor = self.db_connection.cursor()\n except:\n print(\"Something went wrong\")\n \n else:\n # if no errors occurs prints following message\n print(\"Connection Successfully Made\")\n \n\n def create_table(self, table_name, **column_info):\n '''\n Creates a new table in current working Database\n table_name (str): Name of table to be created\n Specify column names and datatypes in key=value format\n E.g. name = VARCHAR(16)\n '''\n self.table_name = table_name\n self.table_column_info = column_info\n\n # creates string containing the column information, formatted correctly to be added to the query\n column_info_str = ',\\n'.join([f\"{column_name} {datatype}\" for column_name, datatype in self.table_column_info.items()])\n \n # final string formatted correctly for SQL query\n query = f\"CREATE TABLE {table_name}(\\n{column_info_str});\"\n\n # execute query\n self.cursor.execute(query) \n\n\n def insert_data(self):\n '''\n Insert Data into table, will prompt user to input data in correct format\n '''\n if not hasattr(self, 'table_name'):\n self.table_name = input(\"\\nPlease enter a table name to insert data into.\\n=> \")\n \n # Empty list of data values which will then be filled with user input\n data_values = []\n \n # Iterate through columns\n for column_name, datatype in self.table_column_info.items():\n # For each column prompt user to input data\n user_data = input(f\"\\nPlease enter Data for {column_name}\\nDATATYPE: {datatype}\\n=> \")\n\n # If datatype is VARCHAR, add extra quotes around data value before appending\n if \"VARCHAR\" in datatype:\n data_values.append(\"'\" + user_data + \"'\")\n elif \"INT\" in datatype:\n data_values.append(user_data)\n\n # create string for data values, and column names, formatted correctly\n insert_data_str = ', '.join(data_values)\n column_names = ', '.join(self.table_column_info.keys())\n \n # final SQL query string formatted correctly\n query = f\"INSERT INTO {self.table_name}\\n({column_names})\\nVALUES({insert_data_str});\"\n\n # execute query\n self.cursor.execute(query)\n \n\n def display_table(self):\n # display everything from table\n print(self.cursor.execute(f\"SELECT * FROM {self.table_name};\").fetchall())\n\n\n\nif __name__ == \"__main__\":\n python_sql_obj = SQLDatabaseAPI()\n python_sql_obj.create_table(\"ldaijiw_table\", name = \"VARCHAR(16)\" , age = \"INT\", address = \"VARCHAR(32)\")\n python_sql_obj.insert_data()\n python_sql_obj.insert_data()\n python_sql_obj.display_table()","sub_path":"03_python/python_sql/pyodbc_task/python_sql_task.py","file_name":"python_sql_task.py","file_ext":"py","file_size_in_byte":3374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"363182117","text":"\"\"\"\n给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。\n\n示例 1:\n\n输入:\n[\n [ 1, 2, 3 ],\n [ 4, 5, 6 ],\n [ 7, 8, 9 ]\n]\n输出: [1,2,3,6,9,8,7,4,5]\n示例 2:\n\n输入:\n[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9,10,11,12]\n]\n输出: [1,2,3,4,8,12,11,10,9,5,6,7]\n\n\"\"\"\n\n\nclass Solution:\n def spiralOrder(self, matrix):\n # 特判\n if not matrix:\n return []\n\n R, C = len(matrix), len(matrix[0])\n # 表示之前已经访问过的元素\n seen = [[False] * C for _ in matrix]\n # 存储答案\n ans = []\n dr = [0, 1, 0, -1]\n dc = [1, 0, -1, 0]\n # di表示前进方向\n r = c = di = 0\n for _ in range(R * C):\n ans.append(matrix[r][c])\n seen[r][c] = True\n cr, cc = r + dr[di], c + dc[di]\n if 0 <= cr < R and 0 <= cc < C and not seen[cr][cc]:\n r, c = cr, cc\n else:\n di = (di + 1) % 4\n r, c = r + dr[di], c + dc[di]\n return ans\n\n\nclass Solution2:\n \"\"\"按层模拟\"\"\"\n def spiralOrder(self, matrix):\n def spiral_coords(r1, c1, r2, c2):\n # 遍历上面\n for c in range(c1, c2 + 1):\n yield r1, c\n # 遍历右边\n for r in range(r1 + 1, r2 + 1):\n yield r, c2\n if r1 < r2 and c1 < c2:\n # 遍历下面\n for c in range(c2 - 1, c1, -1):\n yield r2, c\n # 遍历左边\n for r in range(r2, r1, -1):\n yield r, c1\n # 特判\n if not matrix:\n return []\n\n ans = []\n r1, r2 = 0, len(matrix) - 1\n c1, c2 = 0, len(matrix[0]) - 1\n while r1 <= r2 and c1 <= c2:\n for r, c in spiral_coords(r1, c1, r2, c2):\n ans.append(matrix[r][c])\n # 从最外层向里层遍历\n r1 += 1\n r2 -= 1\n c1 += 1\n c2 -= 1\n return ans\n","sub_path":"数组/54-螺旋矩阵.py","file_name":"54-螺旋矩阵.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"222270950","text":"#!/usr/bin/env python\n# coding:utf-8\nimport base64\nimport logging\nimport os\nfrom urlparse import urlparse\n\nimport fakeredis\n\nr = fakeredis.FakeStrictRedis()\ninvalid_chars = '-_.!?~/\\\\/!#$%^&**)_=Il1O0o'\n\n\ndef invalid(text):\n \"\"\"\n Checks if shortened text contains invalid characters\n :param text:\n :return:\n \"\"\"\n return any((c in invalid_chars) for c in text)\n\n\ndef generator():\n \"\"\"\n Generates random shortened char-sets until does not contain invalid characters\n :return:\n \"\"\"\n step = 0\n text = invalid_chars\n\n while invalid(text):\n text = base64.urlsafe_b64encode(os.urandom(3)).lower()\n step += 1\n if step >= 10:\n msg = '{1} in {0} step'.format(step, text)\n logging.debug(msg=msg)\n\n return text\n\n\ndef available(key):\n return not r.exists(key)\n\n\ndef shorten(url):\n step = 0\n\n while True:\n name = generator()\n if not available(key=name):\n step += 1\n continue\n if step >= 1:\n msg = '{0} shortened to in {1} in {2} step'.format(url, name, step)\n logging.info(msg=msg)\n return dict(key=name, url=url)\n\n\ndef expand(key):\n if available(key=key):\n raise KeyError(\"{0} not found\".format(key))\n return dict(name=key, value=r.get(key))\n\n\ndef save(shortened_data):\n return r.set(name=shortened_data['key'], value=shortened_data['url'])\n\n\ndef isvalid(url):\n \"\"\"\n 1. Must be only http(s)\n 2. Query parameters ? (I think it shoul be exists)\n 3. Unicode domains [ok]\n :param url:\n :return:\n \"\"\"\n parsed = urlparse(url.__str__())\n return \\\n '.' in parsed.netloc and \\\n ':' not in parsed.netloc and \\\n not parsed.netloc.endswith('.') and \\\n parsed.scheme in ['http', 'https']\n","sub_path":"bonsai/core/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"308823184","text":"def isSame(src, dst, idx):\r\n for i in range(len(dst)):\r\n if (src[idx+i] != dst[i]):\r\n return False\r\n return True\r\n\r\ndef replacePart(src, num, idx):\r\n strTmp = hex(num).split('x')[1]\r\n while (len(strTmp) < 16):\r\n strTmp = '0'+strTmp\r\n rp = bytearray.fromhex(strTmp)\r\n for i in range(8):\r\n src[idx+i] = rp[i]\r\n \r\ndef reverseByte(x):\r\n y = 0\r\n for i in range(8):\r\n y = ((y << 8) | (x & 0xFF));\r\n x = (x >> 8)\r\n return y\r\n\r\nnum = 0x8d976e1283c0f33f\r\nmmTag = memoryview(bytearray.fromhex(hex(num).split('x')[1]))\r\nprint(len(mmTag))\r\nwith open(\"src.xls\", \"rb\") as srcFile :\r\n dd = bytearray(srcFile.read())\r\n mm = memoryview(dd)\r\n\r\n i = 0\r\n while i < len(mm):\r\n if (isSame(mm, mmTag, i)):\r\n replacePart(mm, num, i)\r\n num = reverseByte(reverseByte(num) + 1);\r\n i = i + 7\r\n i = i + 1\r\n\r\n with open(\"dst.xls\", \"wb\") as dstFile:\r\n dstFile.write(dd)\r\n","sub_path":"double_15/parse_change.py","file_name":"parse_change.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"509364467","text":"from commands.base_command import BaseCommand\nfrom util.file_utils import extract_filename\nfrom util.math_utils import cosine_similarity\n\nclass PrintSimilaritiesCommand(BaseCommand):\n def __init__(self):\n self.filevectors = []\n\n def execute(self, clusters, mapped_vectors, files):\n self.init_filevectors(mapped_vectors, files)\n self.print_similiarities()\n\n def init_filevectors(self, mapped_vectors, files):\n for i in range(0, len(files)):\n vector = mapped_vectors[i][0]\n file = files[i]\n self.filevectors.append(FileVector(file, vector))\n\n def print_similiarities(self):\n filenames = []\n max_len = 0\n for file in self.filevectors:\n filename = file.file\n filename = extract_filename(filename)\n filenames.append(filename)\n if len(filename) > max_len:\n max_len = len(filename)\n print(\"Близость документов по косинусной мере:\")\n print(''.ljust(max_len), end=' ')\n for document in filenames:\n print(document.ljust(max_len), end=' ')\n print()\n for first_filevector in self.filevectors:\n print(filenames[self.filevectors.index(first_filevector)].ljust(max_len), end=' ')\n for second_filevector in self.filevectors:\n a = first_filevector.vector\n b = second_filevector.vector\n print('{0:.3f}'.format(cosine_similarity(a, b)).ljust(max_len), end=' ')\n print()\n\nclass FileVector:\n def __init__(self, file, vector):\n self.file = file\n self.vector = vector","sub_path":"commands/print_similarities_command.py","file_name":"print_similarities_command.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"290203371","text":"expression = input()\npow = expression.replace('**', ' ** ')\nmult = pow.replace('*', ' * ')\nadd = mult.replace('+', ' + ')\nsub = add.replace('-', ' - ')\ndiv = sub.replace('/', ' / ')\ns = div.split(' ')\nfor i in range(len(s)):\n s.remove('')\n print(s)\n \n\n\n\n\n\n\n\n\n","sub_path":"venv/Functions/Calc.py","file_name":"Calc.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"503772027","text":"import time\nimport subprocess\n\nfrom utils import repo\nfrom discord.ext import commands\n\n\nclass Admin:\n def __init__(self, bot):\n self.bot = bot\n self._last_result = None\n\n @commands.command()\n async def amiadmin(self, ctx):\n \"\"\" Are you admin? \"\"\"\n if ctx.author.id in repo.owners:\n return await ctx.send(f\"Yes **{ctx.author.name}** you are admin! ✅\")\n\n # Please do not remove this part :( #\n if ctx.author.id == 86477779717066752:\n return await ctx.send(f\"Well kinda **{ctx.author.name}**.. you still own the source code\")\n\n await ctx.send(f\"no, heck off {ctx.author.name}\")\n\n @commands.command()\n @commands.check(repo.is_owner)\n async def reload(self, ctx, name: str):\n \"\"\" Reloads an extension. \"\"\"\n try:\n self.bot.unload_extension(f\"cogs.{name}\")\n self.bot.load_extension(f\"cogs.{name}\")\n except Exception as e:\n await ctx.send(f\"```\\n{e}```\")\n return\n await ctx.send(f\"Reloaded extension **{name}.py**\")\n\n @commands.command()\n @commands.check(repo.is_owner)\n async def reboot(self, ctx):\n \"\"\" Reboot the bot \"\"\"\n await ctx.send('Rebooting now...')\n time.sleep(1)\n await self.bot.logout()\n\n @commands.command()\n @commands.check(repo.is_owner)\n async def load(self, ctx, name: str):\n \"\"\" Reloads an extension. \"\"\"\n try:\n self.bot.load_extension(f\"cogs.{name}\")\n except Exception as e:\n await ctx.send(f\"```diff\\n- {e}```\")\n return\n await ctx.send(f\"Loaded extension **{name}.py**\")\n\n @commands.command()\n @commands.check(repo.is_owner)\n async def unload(self, ctx, name: str):\n \"\"\" Reloads an extension. \"\"\"\n try:\n self.bot.unload_extension(f\"cogs.{name}\")\n except Exception as e:\n await ctx.send(f\"```diff\\n- {e}```\")\n return\n await ctx.send(f\"Unloaded extension **{name}.py**\")\n\n @commands.command(aliases=['exec'])\n @commands.check(repo.is_owner)\n async def execute(self, ctx, *, text: str):\n \"\"\" Do a shell command. \"\"\"\n text_parsed = list(filter(None, text.split(\" \")))\n output = subprocess.check_output(text_parsed).decode()\n await ctx.send(f\"```fix\\n{output}\\n```\")\n\n\ndef setup(bot):\n bot.add_cog(Admin(bot))\n","sub_path":"cogs/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"422402219","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# =============================================================================\n# Created By : luis-eduardo@dsv.su.se\n# Created Date: 2020/06/30\n# =============================================================================\n\"\"\"\nCreation of HTML webpage with Dash and visualization with Plotly.\nThis file is called from the `dash_example_web.py`, and its main goal\nis to make the main code more readable.\n\"\"\"\n# =============================================================================\n# Imports\n# =============================================================================\n\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\n\nimport plotly.express as px\n\nfrom pathlib import Path\nimport pandas as pd\n\n\n# =============================================================================\n# Functions\n# =============================================================================\n\ndef update_histogram(colname = None, sample=None):\n#def update_histogram(colname, sample=None):\n \"\"\"\n Draws a histogram plot from the original dataset and puts the value\n from the `sample` that the user has input in the website.\n \"\"\"\n fig = px.histogram(data,\n x=colname,\n color=\"Outcome\",\n labels={k:v for k,v in zip(colnames,column_labels)},\n template=\"ggplot2\")\n fig.update_layout(\n legend = dict(title=\"Class\",\n orientation=\"h\",\n y=1, yanchor=\"bottom\",\n x=0.5, xanchor=\"center\"\n )\n )\n # Show a black line with the current value of the sample\n if (sample is not None):\n fig.add_shape(type=\"line\", line_color=\"black\",\n line_width = 3, \n xref='x', yref='paper',\n x0 = float(sample[colname]), x1 = float(sample[colname]),\n y0 = 0, y1 = 1)\n return fig\n\ndef update_scatter(col1=None, col2=None, sample=None):\n#def update_scatter(col1, col2, sample=None):\n \"\"\"\n Draws a scatter plot from the original dataset and puts the value\n from the `sample` that the user has input in the website.\n \"\"\"\n fig = px.scatter(data,\n x=col1, \n y=col2, \n color=\"Outcome\",\n labels={k:v for k,v in zip(colnames,column_labels)},\n template=\"simple_white\")\n\n fig.update_layout(\n legend = dict(\n title=\"Class\",\n )\n )\n \n if (sample is not None):\n fig.add_annotation( # add a text callout with arrow\n text=\"SAMPLE!\", x=float(sample[col1]), y=float(sample[col2]),\n arrowhead=3, showarrow=True, startarrowsize=3\n )\n return fig\n\n# =============================================================================\n# Main\n# =============================================================================\n\n\n#############\n\"\"\"\nLoad and simple processing of the original dataset for visualization\npurposes in the web application.\n\"\"\"\n\n# Relative paths respect to current file\n# DO NOT MODIFY: Relative path prefix to be able to find the dataset\nTHIS_FILE_PATH = str(Path(__file__).parent.absolute())+\"/\"\nFOLDER_PATH = THIS_FILE_PATH + \"../datasets/\"\n\n# Load original dataset file\ndataset_filename = FOLDER_PATH + \"diabetes.csv\"\ndata = pd.read_csv(dataset_filename)\n\n# Structure to map df column names to meaningful labels\ncolnames = data.columns\ncolnames = colnames.drop('Outcome').values\ncolumn_labels = ['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness','Insulin','BMI', 'DiabetesPedigreeFunction', 'Age']\n\n# Initialization of plots when the website is loaded the first time\n# [P,G,BP,S,I,BMI,D,A]\nfig_histogram = update_histogram(\"Pregnancies\")\nfig_scatter = update_scatter(\"Pregnancies\",\"BloodPressure\")\n\n#############\n\"\"\"\nStructure of the HTML webpage using Dash library\n\"\"\"\napp_html_layout = html.Div([\n\n html.Center(html.H1(\"DAMI HW3 - DIABETES\")),\n\n html.Div(\"This app classifies two variaties of diabetes from eight real-value attributes\"),\n\n #html.Div(['More information about dataset:', \n #html.A('https://archive.ics.uci.edu/ml/datasets/seeds')\n #]),\n\n html.H3('Classification with Trained Model'),\n\n\n #['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness','Insulin','BMI', 'DiabetesPedigreeFunction', 'Age']\n # [P,G,BP,S,I,BMI,D,A]\n\n # Create the table to put input values\n html.Table([ html.Tbody([\n # Pregnancies\n html.Tr([\n html.Td( html.B('Pregnancies (P):', style={'font-size':'9pt'}), style={'width':'25%'} ),\n html.Td( dcc.Slider(id='slider-P',\n min=0,\n max=17,\n step=1,\n value=6,\n ), style={'width':'55%'} ),\n html.Td( html.P(id='value-slider-P',children=''), style={'width':'10%'} ),\n ]),\n # Glucose\n html.Tr([\n html.Td( html.B('Glucose (G):', style={'font-size':'9pt'}), style={'width':'25%'} ),\n html.Td( dcc.Slider(id='slider-G',\n min=44,\n max=199,\n step=1,\n value=88,\n ), style={'width':'55%'} ),\n html.Td( html.P(id='value-slider-G',children=''), style={'width':'20%'} ),\n ]),\n # BloodPressure\n html.Tr([\n html.Td( html.B('BloodPressure (BP):', style={'font-size':'9pt'}), style={'width':'25%'} ),\n html.Td( dcc.Slider(id='slider-BP',\n min=24,\n max=122,\n step=1,\n value=67,\n ), style={'width':'55%'} ),\n html.Td( html.P(id='value-slider-BP',children=''), style={'width':'20%'} ),\n ]),\n # SkinThickness\n html.Tr([\n html.Td( html.B('SkinThickness (S):', style={'font-size':'9pt'}), style={'width':'25%'} ),\n html.Td( dcc.Slider(id='slider-S',\n min=7,\n max=99,\n step=1,\n value=55,\n ), style={'width':'55%'} ),\n html.Td( html.P(id='value-slider-S',children=''), style={'width':'20%'} ),\n ]),\n # Insulin\n html.Tr([\n html.Td( html.B('Insulin (I):', style={'font-size':'9pt'}), style={'width':'25%'} ),\n html.Td( dcc.Slider(id='slider-I',\n min=10,\n max=846,\n step=1,\n value=130,\n ), style={'width':'55%'} ),\n html.Td( html.P(id='value-slider-I',children=''), style={'width':'20%'} ),\n ]),\n # BMI\n html.Tr([\n html.Td( html.B('BMI (BMI):', style={'font-size':'9pt'}), style={'width':'25%'} ),\n html.Td( dcc.Slider(id='slider-BMI',\n min=18,\n max=67,\n step=1,\n value=35,\n ), style={'width':'55%'} ),\n html.Td( html.P(id='value-slider-BMI',children=''), style={'width':'20%'} ),\n ]),\n # 'DiabetesPedigreeFunction'\n html.Tr([\n html.Td( html.B('DiabetesPedigreeFunction (D):', style={'font-size':'9pt'}), style={'width':'25%'} ),\n html.Td( dcc.Slider(id='slider-D',\n min=0.05,\n max=2.5,\n step=0.01,\n value=1.13,\n ), style={'width':'55%'} ),\n html.Td( html.P(id='value-slider-D',children=''), style={'width':'20%'} ),\n ]), \n\n # 'Age'\n html.Tr([\n html.Td( html.B('Age (A):', style={'font-size':'9pt'}), style={'width':'25%'} ),\n html.Td( dcc.Slider(id='slider-A',\n min=1,\n max=90,\n step=1,\n value=50,\n ), style={'width':'55%'} ),\n html.Td( html.P(id='value-slider-A',children=''), style={'width':'20%'} ),\n ]),\n ]), \n ], style={'width':'100%', 'padding':'0', 'margin':'0'}),\n\n \n html.Center( \n html.Div([\n html.Br(),\n html.H4(html.B('Classification result', id='classification-result', style={'color':'#983e0f'})),\n html.Button('Execute Classification', id='submit', style={'margin':'0 auto', 'width':'30%'}),\n ])\n ),\n\n html.Br(),\n\n html.Center(html.B('Possible classes: [0:Negative], [1:Positive]', style={'color':'blue'})),\n\n html.Hr(),\n\n html.H3('Dataset Visualization'),\n\n html.Div('The next plots show some characteristics of the original dataset. Note that the values from the SAMPLE that was input above will be highlighted in the plot according to the selected variables.'),\n\n# #['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness','Insulin','BMI', 'DiabetesPedigreeFunction', 'Age']\n \n # Layout for plots\n html.Table([\n html.Tbody([\n # Create the cell for the first plot\n html.Tr([\n html.Td([\n \n html.H5('Histogram per class of a variable'),\n\n html.Label(\"Choose a variable:\"),\n\n dcc.Dropdown(id='dropdown-histogram',\n options=[{\"label\":l, 'value':v} for l,v in zip(column_labels,colnames)],\n value='Pregnancies'\n ),\n\n dcc.Graph(\n id='graph-histogram',\n figure = fig_histogram\n ),\n ], style={'width':'40%'} ),\n\n html.Td([\n \n html.H5('Scatter plot of two variables'),\n\n html.Label(\"Choose two variables to plot:\"),\n\n dcc.Dropdown(id='dropdown-scatter-1',\n options=[{\"label\":l, 'value':v} for l,v in zip(column_labels,colnames)],\n value='Pregnancies'\n ),\n\n dcc.Dropdown(id='dropdown-scatter-2',\n options=[{\"label\":l, 'value':v} for l,v in zip(column_labels,colnames)],\n value='BloodPressure'\n ),\n\n dcc.Graph(\n id='graph-scatter',\n figure = fig_scatter\n ),\n ], style={'width':'60%'} )\n ])\n ])\n ], style={'width': '100%'}),\n \n], style={'columnCount': 1})","sub_path":"HW3/backup/backup10142225/helper_dash_example.py","file_name":"helper_dash_example.py","file_ext":"py","file_size_in_byte":10631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"586143216","text":"class Problem019:\n\n def solution(self):\n currentDay = 1 + (365 % 7)\n totalNumberOfSundays = 0\n monthsWith31Days = [0, 2, 4, 6, 7, 9, 11]\n monthsWith30Days = [3, 5, 8, 10]\n\n for year in xrange(1901, 2001):\n for month in xrange(12):\n if currentDay == 0:\n totalNumberOfSundays += 1\n if month in monthsWith31Days:\n currentDay += 31\n elif month in monthsWith30Days:\n currentDay += 30\n elif year % 4 == 0:\n currentDay += 29\n else:\n currentDay += 28\n currentDay %= 7\n\n return totalNumberOfSundays\n\n def test(self):\n return\n\nSolver = Problem019\n","sub_path":"Solutions/Problems 001-025/Problem019.py","file_name":"Problem019.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"139350416","text":"\"\"\"backend URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\n\nfrom rest_framework import routers\n\nfrom songs import views\n\nfrom rest_framework_simplejwt.views import (\n TokenObtainPairView,\n TokenRefreshView,\n TokenVerifyView,\n)\n\nrouter = routers.DefaultRouter()\nrouter.register(r'song', views.SongView, 'song')\nrouter.register(r'book', views.BookView, 'book')\nrouter.register(r'printer', views.PrintPageView, 'printpage')\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n\n path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),\n path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),\n path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'),\n path('api/song//edit', views.edit_song, name=\"edit_song\"),\n path('api/book//edit', views.edit_book, name=\"edit_book\"),\n path('api/update/', views.get_status, name=\"update\"),\n path('api/', include(router.urls)),\n\n]\n","sub_path":"backend/backend/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"225983507","text":"#This class defines an object for reading and containing a GRAINEX sounding.\n#It reads both the ASCII and NetCDF files available on the GRAINEX NCAR page.\n#Note that it does not handle any missing data values, but retains the\n#value read from the file.\n#There are 2 broad categories of attributes:\n# Metadata\n# time - Sonde time\n# date - Date of sonde launch\n# elv - Balloon elevation\n# lat - Balloon latitude\n# lon - Balloon longitude\n# units - Wind speed units\n#\n# Atmosphere\n# pres - Level pressure\n# height - Level Height\n# temp - Level temperature\n# dewp - Level dewpoint\n# wdir - Level wind direction\n# wspd - Level wind speed\n# pblh() - Function to Estimate height of the boundary layer (returns pblh)\n# cape_cin() - Function to calculate amount of CAPE in sounding (returns [cape, cin])\n# lcl() - Function to calculate lifting condensation level\n# lfc() - Function to calculate level of free convection\n# bulk_shear() - Function to calculate bulk shear in a user-defined layer\n#\n#Additionally, there is an \"attributes\" attribute that lists the\n#object's attributes. (Say that three times fast.)\n#\n#Usage:\n# To creating a sounding object, simply run\n#\n# from grainex_sounding.py import Sounding\n# my_sounding_object = Sounding(path_to_file, ASCII) for an ASCII file\n#\n# -or-\n#\n# my_sounding_object = Sounding(path_to_file, NETCDF) for a NetCDF file\n#\n#Written by Chris Phillips, August 2019\n#University of Alabama\n#Department of Atmospheric and Earth Science\n#\n#Requirements:\n#Python 3+\n#Atmos (Available at github.com/sodoesaburningbus)\n#Metpy\n#NetCDF4 (If reading netcdf files)\n#Numpy\n\nclass Sounding():\n #Initializing sounding object with sounding information\n def __init__(self, filepath, flag):\n #Importing numpy\n import numpy\n\n #Reading an ASCII sounding file\n if (flag.lower() == \"ascii\"):\n #Creating lists to hold data\n pres = []\n elv = []\n temp = []\n dewp = []\n rh = []\n wdir = []\n wspd = []\n lat = []\n lon = []\n \n #Opening sounding file and reading\n fn = open(filepath)\n data_flag = False #Flag for whether in metadata or observations portion of sounding\n for line in fn:\n #Skipping blank lines\n if (len(line) < 2):\n continue\n \n dummy = line.split() #Splitting line on whitespace\n \n if (data_flag): #Reading observations from sounding\n if ((len(dummy) <= 4) or (dummy[4] == -999)): #Skip bad pressure levels\n continue\n pres.append(dummy[4])\n elv.append(dummy[13])\n temp.append(dummy[5])\n dewp.append(dummy[6])\n rh.append(dummy[7])\n wdir.append(dummy[11])\n wspd.append(dummy[10])\n lat.append(dummy[15])\n lon.append(dummy[14])\n \n #elif (dummy[0]+dummy[1] == \"ReleaseSite\"):\n # self.id = dummy[4]\n \n #elif (dummy[0] == \"UTC\"): #Pulling time and date from metadata\n # self.time = dummy[7]\n # self.date = dummy[4][:-1]+dummy[5][:-1]+dummy[6][:-1]\n \n elif (dummy[0] == \"sec\"): #Pulling wind speed unit\n self.units = dummy[10] \n \n elif (dummy[0][0] == \"-\"): #Detecting if starting data portion of sounding\n data_flag = True\n\n #Closing file\n fn.close()\n \n #Assigning numpy arrays to class attributes\n #Also eliminating bad pressure levels\n self.pres = numpy.array(pres, dtype=\"float\")\n self.elv = numpy.array(elv, dtype=\"float\")\n self.temp = numpy.array(temp, dtype=\"float\")\n self.dewp = numpy.array(dewp, dtype=\"float\")\n self.rh = numpy.array(rh, dtype=\"float\")\n self.wdir = numpy.array(wdir, dtype=\"float\")\n self.wspd = numpy.array(wspd, dtype=\"float\")\n self.lat = numpy.array(lat, dtype=\"float\")\n self.lon = numpy.array(lon, dtype=\"float\")\n \n #Reading a NetCDF sounding file\n elif(flag.lower() == \"netcdf\"):\n import netCDF4 as nc\n \n #Opening netcdf file and pulling in variables\n fn = nc.Dataset(filepath, \"r\")\n self.pres = fn.variables[\"pres\"][:]\n self.elv = fn.variables[\"alt\"][:]\n self.temp = fn.variables[\"tdry\"][:]\n self.dewp = fn.variables[\"dp\"][:]\n self.rh = fn.variables[\"rh\"][:]\n self.wdir = fn.variables[\"wdir\"][:]\n self.wspd = fn.variables[\"wspd\"][:]\n self.lat = fn.variables[\"lat\"][:]\n self.lon = fn.variables[\"lon\"][:]\n self.time = fn.__dict__[\"BalloonReleaseTime\"]\n self.date = fn.__dict__[\"BalloonReleaseDate\"]\n self.id = fn.__dict__[\"StationName\"]\n self.units = fn.variables[\"wspd\"].units\n \n #Handling an unrecognized flag\n else:\n print(\"ERROR - Unrecognized flag for sounding file, exiting\")\n exit()\n\n #Creating list of attributes associated with sounding object\n self.attributes = self.__dict__.keys()\n\n #Function to calculate bulk wind shear in a layer\n #Inputs:\n # low, float, lower boundary of layer in meters\n # high, float, upper boundary of layer in meters\n #Returns bulk wind shear in same units as sounding wind\n def bulk_shear(self,low,high):\n #Importing numpy\n import numpy\n \n #Correcting altitude to be AGL\n heights = self.elv-self.elv[0]\n \n #Calculating wind components\n #Not correcting for meteorological direction because only need bulk quantity at end\n u = self.wspd*numpy.cos(self.wdir*numpy.pi/180.0)\n v = self.wspd*numpy.sin(self.wdir*numpy.pi/180.0)\n \n #Calculating difference in u and v between 10m and 1km.\n du = u[numpy.where(abs(heights-high)==abs(heights-high).min())]-u[numpy.where(abs(heights-low)==abs(heights-low).min())]\n dv = v[numpy.where(abs(heights-high)==abs(heights-high).min())]-v[numpy.where(abs(heights-low)==abs(heights-low).min())]\n\n #Returning bulk shear in layer\n #Subscripting because result from above produces an array\n try:\n return numpy.sqrt(du**2+dv**2)[0]\n except: #In case above is actually a number\n return numpy.sqrt(du**2+dv**2)\n\n #Function to calculate CAPE and CIN\n #Returns [CAPE, CIN] as metpy unit aware values.\n def cape_cin(self):\n #Importing metpy\n import metpy.calc as mc\n from metpy.units import units as mu\n\n #Calculating parcel path\n parcel_path = mc.parcel_profile(self.pres*mu.hectopascal, self.temp[0]*mu.celsius, self.dewp[0]*mu.celsius)\n\n #Calculating CAPE and CIN\n return mc.cape_cin(self.pres*mu.hectopascal, self.temp*mu.celsius, self.dewp*mu.celsius, parcel_path)\n\n #Function to calculate Lifting Condensation Level (LCL)\n #Returns pressure and temperature of LCL as unit aware values\n def lcl(self):\n #Import metpy\n import metpy.calc as mc\n from metpy.units import units as mu\n \n #Calculating LCL from parcel starting point\n return mc.lcl(self.pres[0]*mu.hectopascal, self.temp[0]*mu.celsius, self.dewp[0]*mu.celsius)\n \n #Function to calculate Level of Free Convection (LFC)\n #Returns pressure and temperature of LFC as unit aware values\n def lfc(self):\n #Import metpy\n import metpy.calc as mc\n from metpy.units import units as mu\n \n #Calculating LCL from parcel starting point\n return mc.lfc(self.pres*mu.hectopascal, self.temp*mu.celsius, self.dewp*mu.celsius)\n\n #Function to calculate Planetary Boundary Layer Height (PBLH)\n #Returns PBLH as a float or NAN if not found in sounding.\n #Height is AGL\n def pblh(self):\n #Importing numpy\n import numpy\n\n #Finding PBLH by searching for minimum dewpoint gradient\n #Calculating vertical gradient of dewpoint\n ddewp = self.dewp[2:]-self.dewp[:-2]\n dheights = self.elv[2:]-self.elv[:-2]\n del_dewp = ddewp/dheights\n \n #Constructing heights at gradient levels\n heights = (self.elv[2:]+self.elv[:-2])/2-self.elv[0] #Also converting to AGL\n \n #Limiting everything to less than 4km AGL\n del_dewp = del_dewp[numpy.where(heights < 4000)]\n heights = heights[numpy.where(heights < 4000)]\n \n #Finding minimum gradient in dewpoint and calling it the boundary layer top\n pblh = heights[numpy.where(del_dewp == numpy.nanmin(del_dewp))]\n try: #making sure that only a value is returned, not an array.\n return pblh[0]\n except:\n return pblh","sub_path":"grainex_sounding.py","file_name":"grainex_sounding.py","file_ext":"py","file_size_in_byte":9158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"214167627","text":"from django.forms import Form, ModelForm, Select, DateInput, FloatField, NumberInput, Textarea, CharField, FileField\nfrom django.db import models\n\nfrom catalog.models import Vulnerability\n\nclass DateInput(DateInput):\n input_type = 'date'\n\nclass VulnerabilityForm(ModelForm):\n class Meta:\n model = Vulnerability\n fields = '__all__'\n\n cvss_value = FloatField(min_value=0, max_value=10)\n report_page = FloatField(min_value=0)\n\n widgets = {\n 'perimeter': Select(),\n 'synopsis': Textarea(attrs={'cols':30,'rows':5,'wrap':\"hard\"}),\n 'identification_date': DateInput(),\n 'remediation_deadline': DateInput(),\n 'remediation': Textarea(attrs={'cols':30,'rows':5,'wrap':\"hard\"}),\n 'observation': Textarea(attrs={'cols':30,'rows':5,'wrap':\"hard\"}),\n 'cvss_value': NumberInput(attrs={'min':0, 'max':10}),\n 'report_page': NumberInput(attrs={'min':0})\n }\n\nclass FastUpdateForm(ModelForm):\n class Meta:\n model = Vulnerability\n fields =['status', 'risk', 'remediation_deadline']\n\n widgets = {\n 'remediation_deadline': DateInput()\n }\n\nclass UploadFileForm(Form):\n title = CharField(max_length=50)\n file = FileField()","sub_path":"metadata/forms/catalog/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"489668432","text":"import numpy as np\n\nfrom keras.models import Sequential\nfrom keras.layers import LSTM, Dense, Dropout\nfrom keras.utils.visualize_util import plot\n\ndata_dim = 4\ntimesteps = 1\nnb_classes = 4\n\n\n\ndef Jarvis():\n\n\n model = Sequential()\n model.add(LSTM(128,return_sequences=True ,input_shape=(timesteps, data_dim)))\n model.add(Dropout(0.2))\n model.add(LSTM(32, init='uniform',activation = 'tanh'))\n model.add(Dropout(0.2))\n model.add(Dense(nb_classes, init='normal', activation='sigmoid'))\n\n model.compile(loss = 'mse', optimizer='rmsprop', metrics=['accuracy'])\n\n return model\n\ndef test():\n x_train = np.random.random((1000, timesteps, data_dim))\n y_train = np.random.random((1000, nb_classes))\n\n # generate dummy validation data\n x_val = np.random.random((100, timesteps, data_dim))\n y_val = np.random.random((100, nb_classes))\n\n model = Jarvis()\n\n model.fit(x_train, y_train,\n batch_size=16, nb_epoch=5,\n validation_data=(x_val, y_val))\n\n plot(model, \"jarvis.png\", show_shapes=True, show_layer_names=True)\n\n print(\"FINISHED!!\")\n\n\n","sub_path":"neural_nets/jarvis.py","file_name":"jarvis.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"512132632","text":"def quickSort(S, low, high):\n if (high > low):\n mid = partition(S, low, high)\n quickSort(S, low, mid)\n quickSort(S, mid + 1, high)\n\n\ndef partition(S, low, high):\n pivotitem = S[low]\n j = low\n for i in range(low + 1, high + 1):\n print(i, j, S)\n if (S[i] < pivotitem):\n j += 1\n S[i], S[j] = S[j], S[i]\n pivotpoint = j\n S[low], S[pivotpoint] = S[pivotpoint], S[low]\n return pivotpoint\n\n\nS = [15, 22, 13, 27, 12, 10, 20, 25]\nprint('Before=', S)\nquickSort(S, 0, len(S) - 1)\nprint('After=', S)\n","sub_path":"AlgorithmList/DivideConquer/QuickSort.py","file_name":"QuickSort.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"328156457","text":"# -*- coding: utf-8 -*-\nfrom typing import Tuple, Union\n\nimport numpy as np\nimport torch\nfrom torch import Tensor\n\n\"\"\"\nHint: To use on packed sequences:\n\n # Unpacking\n inputs_tensor = inputs.data\n\n result = embedding(inputs_tensor)\n\n # Packing back\n # Not using pack_sequence because we want to keep the same info as\n # the inputs (nb of feature has changed, but not the number of inputs\n # -- i.e. streamlines)\n result = PackedSequence(result, inputs.batch_sizes,\n inputs.sorted_indices,\n inputs.unsorted_indices)\n\"\"\"\n\n\nclass EmbeddingAbstract(torch.nn.Module):\n def __init__(self, nb_features_in: int, nb_features_out: int,\n key: str = ''):\n \"\"\"\n Params\n -------\n input_size: int\n Size of each data point.\n Ex: MRI features * nb neighbors for flattened MRI data.\n Ex: 3D coordinates [x,y,z] for streamlines.\n output_size: int\n Size of each output data point.\n \"\"\"\n super().__init__()\n self.nb_features_in = nb_features_in\n self.nb_features_out = nb_features_out\n self.key = key\n\n @property\n def params_for_checkpoint(self):\n \"\"\"All parameters necessary to create again the same model. Will be\n used in the trainer, when saving the checkpoint state. Params here\n will be used to re-create the model when starting an experiment from\n checkpoint. You should be able to re-create an instance of your\n model with those params.\"\"\"\n # We need real int types, not numpy.int64, not recognized by json\n # dumps.\n params = {\n 'nb_features_in': int(self.nb_features_in),\n 'nb_features_out': int(self.nb_features_out),\n 'key': self.key\n }\n return params\n\n def forward(self, inputs):\n raise NotImplementedError\n\n\nclass NNEmbedding(EmbeddingAbstract):\n def __init__(self, nb_features_in, nb_features_out: int):\n super().__init__(nb_features_in, nb_features_out, key='nn_embedding')\n self.linear = torch.nn.Linear(self.nb_features_in, self.nb_features_out)\n self.relu = torch.nn.ReLU()\n\n def forward(self, inputs: Tensor):\n # Calling forward.\n result = self.linear(inputs)\n result = self.relu(result)\n return result\n\n\nclass NoEmbedding(EmbeddingAbstract):\n def __init__(self, nb_features_in, nb_features_out: int = None):\n if nb_features_out is None:\n nb_features_out = nb_features_in\n if nb_features_in != nb_features_out:\n raise ValueError(\"Identity embedding should have input_size == \"\n \"output_size but you gave {} and {}\"\n .format(nb_features_in, nb_features_out))\n\n super().__init__(nb_features_in, nb_features_out, key='no_embedding')\n self.identity = torch.nn.Identity()\n\n def forward(self, inputs: Tensor = None):\n # Should check that input size = self.input_size but we don't\n # know how the data is organized. Letting user be responsible.\n result = self.identity(inputs)\n return result\n\n\nclass CNNEmbedding(EmbeddingAbstract):\n def __init__(self, nb_features_in: int, nb_features_out: int,\n kernel_size: Union[int, Tuple[int, int, int]],\n image_shape: Tuple[int, int, int]):\n \"\"\"\n Applies a 3D convolution. For now: a single layer.\n\n Parameters\n ----------\n nb_features_in: int\n Size should refer to the number of features per voxel. (Contrary to\n other embeddings, where data in each neighborhood is flattened and\n input_size is thus nb_features * nb_neighboors).\n nb_features_out: int\n Size of the output = number of out_channels = number of filters.\n kernel_size: int, or a tuple of 3 ints\n Size of the kernel (will be a 3D [k, k, k] kernel).\n image_shape: (int, int, int)\n Size of the image.\n \"\"\"\n super().__init__(nb_features_in, nb_features_out, key='cnn_embedding')\n\n if not isinstance(kernel_size, int):\n raise NotImplementedError(\"Need to verify order of the 3D kernel \"\n \"size.\")\n self.in_image_shape = np.asarray(image_shape)\n self.cnn_layer = torch.nn.Conv3d(\n nb_features_in, nb_features_out, kernel_size=kernel_size)\n\n # Computing values, just to help user.\n padding = 0\n stride = 1\n dilation = 1\n # Using default stride=1, padding=0, dilation=1, etc.\n # Output size formula is given here:\n # https://pytorch.org/docs/stable/generated/torch.nn.Conv3d.html\n numerator = \\\n self.in_image_shape + 2 * padding - dilation * (kernel_size - 1) - 1\n self.out_image_shape = np.floor(numerator / stride + 1)\n self.out_flattened_size = int(np.prod(self.out_image_shape) * nb_features_out)\n\n def forward(self, inputs: Tensor):\n \"\"\"\n Expected inputs shape: (batch size, x, y, z, channels)\n (We will reorder to torch's input shape.)\n Outputs shape: (batch size, x2, y2, x2, c2)\n \"\"\"\n # Torch:\n # Note that depth is first, but we can pretend it is (N, C, X, Y, Z).\n # 3D operation is the same.\n # Input size = (N, C1, D1, H1, W1) --> (B, C1, X1, Y1, Z1)\n # Output size = (N, C2, D2, H2, W2) --> (B, C2, X2, Y2, Z2)\n # N = Batch size.\n # C = Number of channels\n # D = Depth of image\n # H = Height of image\n # W = Width of image\n assert inputs.shape[-1] == self.nb_features_in\n assert np.array_equal(inputs.shape[1:4], self.in_image_shape), \\\n \"Expecting inputs of shape {} ({} channels per voxel), but \"\\\n \"received {}.\".format(self.in_image_shape, self.nb_features_in,\n inputs.shape[2:])\n\n inputs = torch.permute(inputs, (0, 4, 1, 2, 3))\n outputs = self.cnn_layer(inputs)\n outputs = torch.permute(outputs, (0, 2, 3, 4, 1))\n # Current shape = (B, X2, Y2, Z2, C2)\n outputs = torch.flatten(outputs, start_dim=1, end_dim=4)\n\n # Final shape: (B, X2*Y2*Z2*C2)\n return outputs\n\n\nkeys_to_embeddings = {'no_embedding': NoEmbedding,\n 'nn_embedding': NNEmbedding,\n 'cnn_embedding': CNNEmbedding}\n","sub_path":"dwi_ml/models/embeddings.py","file_name":"embeddings.py","file_ext":"py","file_size_in_byte":6536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"264864021","text":"#!/usr/bin/env python3\n# coding: utf8\n__author__ = \"Juan Manuel Fernández Nácher\"\n\n# Clase que maneja la api de telegram\nfrom TelegramBot import TelegramBot\n\ndef main():\n\tTOKEN = open('token', 'r').read().strip()\n\ttelegramBot = TelegramBot(TOKEN)\n\ttelegramBot.startBot()\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"223639765","text":"from Token import Token\n\n\nclass Gem(Token):\n \n def __init__ (self, color, name):\n super().__init__(color, name)\n \n \n#test\nif __name__ == '__main__':\n gem = Gem(\"red\", \"Ruby\")\n print(\"Name: {}\".format(gem.get_name()));\n print(\"Color: {}\".format(gem.get_color()));","sub_path":"Gem.py","file_name":"Gem.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"551886198","text":"from flask_wtf import FlaskForm\nfrom wtforms import SubmitField, StringField, SelectField, TextAreaField\nfrom wtforms.fields.html5 import DateField\nfrom wtforms.validators import DataRequired\n\n\nclass addDailyAttendanceForm(FlaskForm):\n studentID = StringField(\"Student ID\")\n chattStateANumber = StringField(\"Chatt State A Number\")\n attendanceCode = SelectField(\n \"Attendance Code\",\n choices=[\n (\"Missed Swipe\", \"Missed Swipe\"),\n (\"W/D Use Only\", \"W/D Use Only\"),\n (\"P (Present)\", \"P (Present)\"),\n (\"UNX (Unexcused)\", \"UNX (Unexcused)\"),\n (\"EXC (Excused)\", \"EXC (Excused)\"),\n (\"UTY (Unexcused Tardy)\", \"UTY (Unexcused Tardy)\"),\n (\"TDY (Tardy)\", \"TDY (Tardy)\"),\n (\"ACT (Activity)\", \"ACT (Activity)\"),\n (\"ALT (Alt_Remanded)\", \"ALT (Alt_Remanded)\"),\n (\"DTH (Death in Family)\", \"DTH (Death in Family)\"),\n (\"CRT (Court)\", \"CRT (Court)\"),\n (\"EVS (Evening School)\", \"EVS (Evening School)\"),\n (\"FLU (Flu)\", \"FLU (Flu)\"),\n (\"HBD (Homebound)\", \"HBD (Homebound)\"),\n (\"ISS (In-School Suspension)\", \"ISS (In-School Suspension)\"),\n (\"MED (Medical)\", \"MED (Medical)\"),\n (\"PEX (Parent Excuse)\", \"PEX (Parent Excuse)\"),\n (\"REL (Religious)\", \"REL (Religious)\"),\n (\"SUS (Suspended)\", \"SUS (Suspended)\"),\n (\"TNT (Unexcused Trans)\", \"TNT (Unexcused Trans)\"),\n (\"TXT (Excused Trans)\", \"TXT (Excused Trans)\"),\n (\"Z (Expelled)\", \"Z (Expelled)\"),\n ],\n validators=[DataRequired()],\n )\n absenceDate = DateField(\"Absence Date\", validators=[DataRequired()])\n comment = TextAreaField(\"Comment\")\n submitDailyAttendance = SubmitField(\"Submit New Daily Attendance\")\n","sub_path":"P2MT_App/dailyAttendance/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"371042054","text":"# coding=utf-8\n\npirate = {}\npirate['sir'] = 'matey'\npirate['hotel'] = 'fleabag inn'\npirate['student'] = 'swabbie'\npirate['boy'] = 'matey'\npirate['madam'] = 'proud beauty'\npirate['professor']='foul blaggart'\npirate['restaurant'] = 'galley'\npirate['your']='yer'\npirate['excuse']='arr'\npirate['students']='swabbies'\npirate['are']='be'\npirate['lawyer']='foul blaggart'\npirate['the']='th’'\npirate['restroom']='head'\npirate['my']='me'\npirate['hello']='avast'\npirate['is']='be'\npirate['man']='matey'\n\n\nsentence = input(\"Please enter a sentence in English\")\n\npsentence = []\nwords = sentence.split()\nfor aword in words:\n if aword in pirate:\n psentence.append(pirate[aword])\n else:\n psentence.append(aword)\n\nprint(\" \".join(psentence))\n","sub_path":"19.py","file_name":"19.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"425899150","text":"A, B, K = map(int, input().split())\n\ndef main():\n cnt = 0\n for x in range(min(A, B), 0, -1):\n if A%x==0 and B%x==0:\n cnt += 1\n if cnt == K:\n print(x)\n \n\nif __name__ == '__main__':\n main()\n","sub_path":"atcoder_problems/atcoder_begginer_contest/120/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"627452394","text":"# from transform import ReLabel, ToLabel, ToSP, Scale\nfrom gan_model_time import ConvGenTime\nfrom gan_model import ConvDis\nfrom gan_model_time import PatchDis\nfrom utils import *\nimport gan_model_time\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.autograd import Variable\nfrom torch.utils import data\nimport torch.nn.init as init\nimport torch.nn.functional as F\nimport torchvision\nfrom torchvision import datasets, models, transforms\nfrom skimage import color\nfrom movie_time_data_loader import *\n\nimport time\nimport os\nimport sys\nfrom PIL import Image\nimport argparse\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime\n\nimport matplotlib\n\n\nparser = argparse.ArgumentParser(description='Colorization using GAN')\nparser.add_argument('--path', type=str,\n help='Root path for dataset')\nparser.add_argument('--large', action=\"store_true\",\n help='Use larger images?')\nparser.add_argument('--batch_size', default=4, type=int,\n help='Batch size: default 4')\nparser.add_argument('--lr', default=1e-4, type=float,\n help='Learning rate for optimizer')\nparser.add_argument('--weight_decay', default=0, type=float,\n help='Weight decay for optimizer')\nparser.add_argument('--num_epoch', default=20, type=int,\n help='Number of epochs')\nparser.add_argument('--lamb', default=100, type=int,\n help='Lambda for L1 Loss')\nparser.add_argument('--test', default='', type=str,\n help='Path to the model, for testing')\nparser.add_argument('--model_G', default='', type=str,\n help='Path to resume for Generator model')\nparser.add_argument('--model_D', default='', type=str,\n help='Path to resume for Discriminator model')\nparser.add_argument('--ngf', default=32, type=int,\n help='# of gen filters in first conv layer')\nparser.add_argument('--ndf', default=32, type=int,\n help='# of discrim filters in first conv layer')\n\nparser.add_argument('--numG', default=1, type=int, help='G trains numG times when D trains per time')\nparser.add_argument('--numD', default=1, type=int, help='D trains numD times when G trains per time')\nparser.add_argument('--patchGAN', action='store_true', help='Use patchGAN in Discriminator')\nparser.add_argument('--use_lsgan', action='store_true', help='Use LSGAN in loss criterion')\nparser.add_argument('--use_self_attn', action='store_true', help='Use self attention in both G and D')\n\n# parser.add_argument('-p', '--plot', action=\"store_true\",\n# help='Plot accuracy and loss diagram?')\nparser.add_argument('-s','--save', action=\"store_true\",\n help='Save model?')\nparser.add_argument('--gpu', default=0, type=int,\n help='Which GPU to use?')\n\n\ndef main():\n global args, date\n args = parser.parse_args()\n date = str(datetime.datetime.now()).replace(':', '_').replace(' ', '_').replace('.', '_')\n\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(args.gpu)\n\n model_G = ConvGenTime(args.ngf, args.use_self_attn)\n if args.patchGAN:\n model_D = PatchDis(large=args.large, ndf=args.ndf, use_self_attn=args.use_self_attn)\n else:\n model_D = ConvDis(large=args.large, ndf=args.ndf, use_self_attn=args.use_self_attn)\n\n start_epoch_G = start_epoch_D = 0\n if args.model_G:\n print('Resume model G: %s' % args.model_G)\n checkpoint_G = torch.load(resume)\n model_G.load_state_dict(checkpoint_G['state_dict'])\n start_epoch_G = checkpoint_G['epoch']\n if args.model_D:\n print('Resume model D: %s' % args.model_D)\n checkpoint_D = torch.load(resume)\n model_D.load_state_dict(checkpoint_D['state_dict'])\n start_epoch_D = checkpoint_D['epoch']\n assert start_epoch_G == start_epoch_D\n if args.model_G == '' and args.model_D == '':\n print('No Resume')\n start_epoch = 0\n\n model_G.cuda()\n model_D.cuda()\n\n # optimizer\n optimizer_G = optim.Adam(model_G.parameters(),\n lr=args.lr, betas=(0.5, 0.999),\n eps=1e-8, weight_decay=args.weight_decay)\n optimizer_D = optim.Adam(model_D.parameters(),\n lr=args.lr, betas=(0.5, 0.999),\n eps=1e-8, weight_decay=args.weight_decay)\n if args.model_G:\n optimizer_G.load_state_dict(checkpoint_G['optimizer'])\n if args.model_D:\n optimizer_D.load_state_dict(checkpoint_D['optimizer'])\n\n # loss function\n global criterionGAN\n #criterion = nn.BCELoss()\n criterionGAN = gan_model_time.GANLoss(use_lsgan=args.use_lsgan, tensor =torch.cuda.FloatTensor)\n\n global L1\n L1 = nn.L1Loss()\n\n # dataset\n data_root = args.path\n\n train_loader = get_movie_time_loader(os.path.join(data_root, 'train/'),\n batch_size=args.batch_size,\n large=args.large,\n mode='train',\n start_index = 1,\n num_workers=4,\n shuffle=True\n )\n\n val_loader = get_movie_time_loader(os.path.join(data_root, 'val/'),\n batch_size=args.batch_size,\n large=args.large,\n mode='val',\n start_index = 10000,\n num_workers=4,\n shuffle=True\n )\n\n global val_bs\n val_bs = val_loader.batch_size\n\n # set up plotter, path, etc.\n global iteration, print_interval, plotter, plotter_basic\n iteration = 0\n print_interval = args.numG * 5\n plotter = Plotter_GAN_TV()\n plotter_basic = Plotter_GAN()\n\n global img_path\n size = ''\n if args.large: size = 'Large'\n img_path = 'img/model_time/%s/GAN_%s_L1%d_bs%d_%s_lr%s_ngf%d_ndf%d_numG%d_numD%d/' \\\n % (date, size, args.lamb, args.batch_size, 'Adam', str(args.lr), args.ngf, args.ndf, args.numG, args.numD)\n model_path = 'model/model_time/%s/GAN_%s_L1%d_bs%d_%s_lr%s_ngf%d_ndf%d_numG%d_numD%d/' \\\n % (date, size, args.lamb, args.batch_size, 'Adam', str(args.lr), args.ngf, args.ndf, args.numG, args.numD)\n if not os.path.exists(img_path):\n os.makedirs(img_path)\n if not os.path.exists(model_path):\n os.makedirs(model_path)\n\n # start loop\n start_epoch = 0\n\n for epoch in range(start_epoch, args.num_epoch):\n print('Epoch {}/{}'.format(epoch, args.num_epoch - 1))\n print('-' * 20)\n\n if epoch == 0:\n val_lerrG, val_errD = validate(val_loader, model_G, model_D, optimizer_G, optimizer_D, epoch=-1)\n # train\n train_errG, train_errD = train(train_loader, model_G, model_D, optimizer_G, optimizer_D, epoch, iteration)\n # validate\n val_lerrG, val_errD = validate(val_loader, model_G, model_D, optimizer_G, optimizer_D, epoch)\n\n plotter.train_update(train_errG, train_errD)\n plotter.val_update(val_lerrG, val_errD)\n plotter.draw(img_path + 'train_val.png')\n\n if args.save and (epoch % 10 == 1):\n print('Saving check point')\n save_checkpoint({'epoch': epoch + 1,\n 'state_dict': model_G.state_dict(),\n 'optimizer': optimizer_G.state_dict(),\n 'Large': args.large,\n 'ngf': args.ngf,\n 'batch_size': args.batch_size,\n 'ndf': args.ndf,\n 'numG': args.numG,\n 'numD': args.numD,\n 'use_self_attn': args.use_self_attn,\n },\n filename=model_path+'G_epoch%d.pth.tar' \\\n % epoch)\n\n # Save the latest model\n print('Save the lastest model')\n save_checkpoint({'epoch': epoch + 1,\n 'state_dict': model_G.state_dict(),\n 'optimizer': optimizer_G.state_dict(),\n 'Large': args.large,\n 'ngf': args.ngf,\n 'batch_size': args.batch_size,\n 'ndf': args.ndf,\n 'numG': args.numG,\n 'numD': args.numD,\n 'use_self_attn': args.use_self_attn,\n },\n filename=model_path+'Last_G_epoch%d.pth.tar' \\\n % epoch)\n\n\n save_checkpoint({'epoch': epoch + 1,\n 'state_dict': model_D.state_dict(),\n 'optimizer': optimizer_D.state_dict(),\n 'Large': args.large,\n 'ngf': args.ngf,\n 'batch_size': args.batch_size,\n 'ndf': args.ndf,\n 'numG': args.numG,\n 'numD': args.numD,\n 'use_self_attn': args.use_self_attn,\n },\n filename=model_path+'Last_D_epoch%d.pth.tar' \\\n % epoch)\n\n\n\ndef train(train_loader, model_G, model_D, optimizer_G, optimizer_D, epoch, iteration):\n errorG = AverageMeter() # will be reset after each epoch\n errorD = AverageMeter() # will be reset after each epoch\n errorG_basic = AverageMeter() # basic will be reset after each print\n errorD_basic = AverageMeter() # basic will be reset after each print\n errorD_real = AverageMeter()\n errorD_fake = AverageMeter()\n errorG_GAN = AverageMeter()\n #errorG_L1_lab = AverageMeter()\n errorG_R = AverageMeter()\n\n model_G.train()\n model_D.train()\n\n real_label = 1\n fake_label = 0\n\n #for i, (_now, _prev, _next, target, target_lab) in enumerate(train_loader):\n for i, (_now, _prev, _next, target) in enumerate(train_loader):\n\n #_now, _prev, _next, target, target_lab = Variable(_now.cuda()), Variable(_prev.cuda()), Variable(_next.cuda()), Variable(target.cuda()), Variable(target_lab.cuda())\n _now, _prev, _next, target = Variable(_now.cuda()), Variable(_prev.cuda()), Variable(_next.cuda()), Variable(target.cuda())\n\n ########################\n # update D network\n ########################\n # train with real\n if (i % args.numG) == 0:\n # dr1, dr2, df1, df2, gf1, gf2 are attention scores\n model_D.zero_grad()\n output = model_D(target)\n #label = torch.FloatTensor(target.size(0)).fill_(real_label).cuda()\n #labelv = Variable(label)\n #errD_real = criterion(torch.squeeze(output), labelv)\n errD_real = criterionGAN(output, True)\n errD_real.backward()\n D_x = output.data.mean()\n\n # train with fake\n #fake, _ = model_G(_now, _prev, _next)\n fake = model_G(_now, _prev, _next)\n #labelv = Variable(label.fill_(fake_label))\n output = model_D(fake.detach())\n #errD_fake = criterion(torch.squeeze(output), labelv)\n errD_fake = criterionGAN(output, False)\n errD_fake.backward()\n D_G_x1 = output.data.mean()\n\n errD = errD_real + errD_fake\n optimizer_D.step()\n\n ########################\n # update G network\n ########################\n\n if (i % args.numD) == 0:\n #labelv = Variable(label.fill_(real_label))\n #fake, fake_lab = model_G(_now, _prev, _next)\n fake = model_G(_now, _prev, _next)\n model_G.zero_grad()\n output = model_D(fake)\n #errG_GAN = criterion(torch.squeeze(output), labelv)\n errG_GAN = criterionGAN(output, True)\n errG_L1 = L1(fake.view(fake.size(0),-1), target.view(target.size(0),-1))\n #errG_L1_lab = L1(fake_lab.view(fake_lab.size(0),-1), target_lab.view(target_lab.size(0),-1))\n\n #errG = errG_GAN + args.lamb * (0.7 * errG_L1 + 0.3 * errG_L1_lab)\n errG = errG_GAN + args.lamb * errG_L1\n errG.backward()\n D_G_x2 = output.data.mean()\n optimizer_G.step()\n\n # store error values\n if (i % max(args.numG, args.numD)) == 0:\n errorG.update(errG, target.size(0), history=1)\n errorD.update(errD, target.size(0), history=1)\n errorG_basic.update(errG, target.size(0), history=1)\n errorD_basic.update(errD, target.size(0), history=1)\n errorD_real.update(errD_real, target.size(0), history=1)\n errorD_fake.update(errD_fake, target.size(0), history=1)\n #errorG_L1_lab.update(errG_L1_lab, target.size(0), history=1)\n\n errorD_real.update(errD_real, target.size(0), history=1)\n errorD_fake.update(errD_fake, target.size(0), history=1)\n errorG_GAN.update(errG_GAN, target.size(0), history=1)\n errorG_R.update(errG_L1, target.size(0), history=1)\n\n if i == 0:\n vis_result(_now.data, target.data, fake.data, epoch, mode = 'train')\n\n if iteration % print_interval == 0:\n print('Epoch%d[%d/%d]: Loss_D: %.4f(R%0.4f+F%0.4f) Loss_G: %0.4f(GAN%.4f+RGB%0.4f) D(x): %.3f D(G(z)): %.3f / %.3f' \\\n % (epoch, i, len(train_loader),\n errorD_basic.avg, errorD_real.avg, errorD_fake.avg,\n errorG_basic.avg, errorG_GAN.avg, errorG_R.avg * args.lamb,\n D_x, D_G_x1, D_G_x2\n ))\n # plot image\n plotter_basic.g_update(errorG_basic.avg)\n plotter_basic.d_update(errorD_basic.avg)\n plotter_basic.draw(img_path + 'train_basic.png')\n # reset AverageMeter\n errorG_basic.reset()\n errorD_basic.reset()\n errorD_real.reset()\n errorD_fake.reset()\n errorG_GAN.reset()\n errorG_R.reset()\n #errorG_L1_lab.reset()\n\n iteration += 1\n\n return errorG.avg, errorD.avg\n\n\ndef validate(val_loader, model_G, model_D, optimizer_G, optimizer_D, epoch):\n errorG = AverageMeter()\n errorD = AverageMeter()\n\n model_G.eval()\n model_D.eval()\n\n real_label = 1\n fake_label = 0\n\n with torch.no_grad(): # Fuck torch.no_grad!! Gradient will accumalte if you don't set torch.no_grad()!!\n #for i, (_now, _prev, _next, target, target_lab) in enumerate(val_loader):\n for i, (_now, _prev, _next, target) in enumerate(val_loader):\n #_now, _prev, _next, target, target_lab = Variable(_now.cuda()), Variable(_prev.cuda()), Variable(_next.cuda()), Variable(target.cuda()), Variable(target_lab.cuda())\n _now, _prev, _next, target = Variable(_now.cuda()), Variable(_prev.cuda()), Variable(_next.cuda()), Variable(target.cuda())\n ########################\n # D network\n ########################\n # validate with real\n output = model_D(target)\n #label = torch.FloatTensor(target.size(0)).fill_(real_label).cuda()\n #labelv = Variable(label)\n \n errD_real = criterionGAN(output, True)\n\n # validate with fake\n #fake, fake_lab = model_G(_now, _prev, _next)\n fake = model_G(_now, _prev, _next)\n #labelv = Variable(label.fill_(fake_label))\n output = model_D(fake.detach())\n errD_fake = criterionGAN(output, False)\n\n errD = errD_real + errD_fake\n\n ########################\n # G network\n ########################\n #labelv = Variable(label.fill_(real_label))\n output = model_D(fake)\n errG_GAN = criterionGAN(output, True)\n errG_L1 = L1(fake.view(fake.size(0),-1), target.view(target.size(0),-1))\n #errG_L1_lab = L1(fake_lab.view(fake_lab.size(0),-1), target_lab.view(target_lab.size(0),-1))\n\n #errG = errG_GAN + args.lamb * (0.8 * errG_L1 + 0.2 * errG_L1_lab)\n errG = errG_GAN + args.lamb * errG_L1 \n\n errorG.update(errG, target.size(0), history=1)\n errorD.update(errD, target.size(0), history=1)\n\n if i == 0:\n vis_result(_now.data, target.data, fake.data, epoch, mode = 'val')\n\n if i % 50 == 0:\n print('Validating Epoch %d: [%d/%d]' \\\n % (epoch, i, len(val_loader)))\n\n print('Validation: Loss_D: %.4f Loss_G: %.4f '\\\n % (errorD.avg, errorG.avg))\n\n return errorG.avg, errorD.avg\n\ndef vis_result(data, target, output, epoch, mode='val'):\n '''visualize images for GAN'''\n img_list = []\n for i in range(min(32, val_bs)):\n l = torch.unsqueeze(torch.squeeze(data[i]), 0).cpu().numpy()\n # from IPython import embed; embed()\n raw = target[i].cpu().numpy()\n pred = output[i].cpu().numpy()\n\n raw_rgb = (np.transpose(raw, (1,2,0)).astype(np.float64) + 1) / 2.\n pred_rgb = (np.transpose(pred, (1,2,0)).astype(np.float64) + 1) / 2.\n\n # denormalize the grey image for visualization \n grey = l * 0.5 + 0.5 \n grey = np.transpose(grey, (1,2,0))\n grey = np.repeat(grey, 3, axis=2).astype(np.float64)\n img_list.append(np.concatenate((grey, raw_rgb, pred_rgb), 1))\n display_len = 4 if len(img_list) >= 4 else 2\n img_list = [np.concatenate(img_list[display_len*i:display_len*(i+1)], axis=1) for i in range(len(img_list) // display_len)]\n img_list = np.concatenate(img_list, axis=0)\n\n if mode=='val':\n matplotlib.image.imsave(img_path + 'epoch%d_val.png' % epoch, img_list)\n else:\n matplotlib.image.imsave(img_path + 'epoch%d_train.png' % epoch, img_list)\n\nif __name__ == '__main__':\n main()\n","sub_path":"gan_main_time.py","file_name":"gan_main_time.py","file_ext":"py","file_size_in_byte":17838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"445889183","text":"import numbers\nimport warnings\n\nimport numpy as np\n\n\"\"\"\nPixel coordinate conversion\n\nThe phantom_base.py module creates raster volumes from vector\nrepresentations using CELL_BASED coordinates. That is, each pixel is referred to\nby the coordinate of the pixel center.\n+---+---\n| x |\n+---+-\n| |\n\nwhere the center `x` is numerically represented as (0, 0), and\nthe top left `+` is (-0.5, -0.5). This cell-based coordinate system is useful\nwhen the volume is numerically represented between [-1, 1] across all cube dimensions.\n\nArrays are typically numerically represented in EDGE-BASED coordinates, where\nthe top left `+` is numerically represented as (0, 0) and the center\n`x` is (0.5, 0.5).\n\nIf a volume's raster shape is (32, 32, 32), we will want to refer to a point in\nthat shape via pixel coordinate. The coordinate system used is undefined, i.e.\ndoes the pixel (31, 31, 31) map to (1, 1, 1), or 1-eps (where eps is the raster\nconversion factor)?\n\"\"\"\nCAP_TYPES = [\"flat\", \"sphere\", \"none\"]\n\n\ndef to_basecoord(x: int, shape: int):\n \"\"\"\n Scale a single coordinate from pixel-based edge coordinate to numerical\n cell-based coordinate for vector-to-raster.\n\n Inputs:\n x -- integer coordinate, must be < shape\n shape -- the size of the dimension we are scaling from\n\n Output:\n the coordinate in base [-1, 1] coordinate space, to be used directly with\n phantom_base methods\n\n Raises:\n AssertionError when x is not within range [0, shape)\n\n Eg:\n >>> s = 32 # the shape of the raster dimension we are scaling to\n >>> x = 0 # the coordinate of the pixel we are scaling\n >>> to_basecoord(x, s)\n -1.0\n >>> to_basecoord(31, s)\n 1.0\n \"\"\"\n assert shape > 0, \"Shape must be positive integer, found {}\".format(shape)\n assert 0 <= x < shape, \"point `{}` is not within shape `{}`\".format(x, shape)\n if shape == 1:\n shape = 2 # make sure that we can still have a single dimension and dont divide by zero\n return -1 + (x * 2) / (shape - 1)\n\n\ndef scale_point_to_basecoord(point: (int, int, int), shape: (int, int, int)):\n \"\"\"\n Take an n-tuple `point` within a volume's `shape`, and scale to coordinate in a -1:1 unit volume\n \"\"\"\n return tuple(to_basecoord(p, s) for p, s in zip(point, shape))\n\n\ndef scale_radius_to_basecoord(radius: int, shape: tuple):\n \"\"\"\n Scale a radius from pixel space to base space [-1, 1]\n\n We divide by the minimum of the XY dimension. Since we may want to have a single z\n face, we scale by the minimum of the XY coordinates, which are also likely to be\n the same shape.\n\n Inputs:\n radius -- integer radius\n shape -- the size of the dimension we are scaling from\n\n Returns:\n radius scaled to base coordinate space, between [-1, 1],\n scaled by the minimum of the XY shape\n\n Raises an AssertionError if radius is a negative value\n \"\"\"\n assert radius > 0, \"Radius must be a positive integer, given {}\".format(radius)\n return (radius * 2) / min(shape[:2])\n\n\ndef to_pixelcoord(base: float, shape: int):\n \"\"\"\n Scale the coordinate from base coordinate (in -1:1 unit volume) to pixel coordinate (0:shape)\n \"\"\"\n assert -1.0 <= base <= 1.0, \"point base dimension coordinate is not within [-1, 1]\"\n return int(np.round((base + 1) * (shape - 1) / 2))\n\n\ndef scale_point_to_pixelcoord(point: (float, float, float), shape: (int, int, int)):\n \"\"\"\n Scale a 3-tuple point to its coordinate in pixel space defined by `shape`\n \"\"\"\n return tuple(to_pixelcoord(p, s) for p, s in zip(point, shape))\n\n\ndef scale_radius_to_pixelcoord(radius: float, shape: tuple):\n \"\"\"\n Scale the cylinder radius from base space [-1, 1] to pixel space\n We scale by the minimum of the XY dimension, as in `scale_radius_to_basecoord`\n \"\"\"\n assert radius > 0.0, \"Radius must be positive, given {}\".format(radius)\n return int(np.round((radius * min(shape[:2])) / 2))\n\n\ndef create_coordinate_block(shape: (int, int, int)):\n \"\"\"\n Create three blocks where the indices key to the\n normalized (-1 to 1) coordinate in three space.\n\n This can be used to construct more complex objects\n in three dimensions.\n\n Keyword Arguments:\n shape {tuple} -- Shape of the coordinate grid\n \"\"\"\n return np.mgrid[-1.0:1.0:1.0j * shape[0],\n -1.0:1.0:1.0j * shape[1],\n -1.0:1.0:1.0j * shape[2]]\n\n\ndef trace_function(xyzr_callable,\n shape: (int, int, int)=(256, 256, 256),\n isotropy: tuple=(1, 1, 1),\n step_count: int=100):\n '''\n This is a tool to turn a parameterized function into a\n 3d raster feature. It outputs an array with shape specified\n where points \"inside\" the feature are masked to 255. All other\n values will be 0.\n\n xyzr_callable is a function which must take a single floating\n point argument, and produce a tuple with 4 floating point elements\n the elements are representative of a ball (x, y, z, r) which will\n be considered as 'within' the raster.\n\n xyzr_callable will be called \"step_count\" times with values ranging\n from 0 to 1. This allows the user to select their perferred parametric\n mapping for output.\n\n This way complex rasters can be constructed from simple parametric\n functions. This is used as a workhorse in several simple phantoms\n generated below.\n\n Input parameters:\n xyzr_callable: a method object that takes in a value t between [0, 1],\n and returns (x, y, z, r)\n\n shape: a 3-tuple defining the shape of the returned raster (voxel) volume\n\n isotropy: a 3-tuple that indicates the scaling per dimension\n Since the parameterization is created in a normalized space [-1, 1],\n any non-cubic volumes will need to be scaled appropriately to have\n the correct sphere radius in that direction. That is, if isotropy\n isn't adjusted correctly for a non-cubic volume, a sphere would become\n a squashed ellipsoid.\n\n To appropriately scale isotropy, the target axis isotropy value\n should be scaled by the size of the target axis shape and\n the unary axis shape\n shape = (64, 64, 128)\n isotropy = (1, 1, 0.5) == (1, 1, shape[0] / shape[2]))\n\n step_count: how many steps to iterate across the parameterization\n\n Returns:\n ndarray, dtype uint8, of input shape. Values are 0 and 255.\n\n '''\n output = np.zeros(shape, dtype=np.uint8)\n xi, yi, zi = create_coordinate_block(shape)\n\n # Accrue the steps first, and unique them\n for t in np.linspace(0.0, 1.0, step_count):\n xc, yc, zc, r = xyzr_callable(t)\n mask = np.sqrt((xc - xi) ** 2 / isotropy[0] ** 2 +\n (yc - yi) ** 2 / isotropy[1] ** 2 +\n (zc - zi) ** 2 / isotropy[2] ** 2) < r\n\n nd_spacing = 1.0 / min(shape)\n if r < nd_spacing:\n warnings.warn(\"Radius of phantom is approaching grid rez. {} v. {}\".format(r, nd_spacing))\n output[mask] = 255\n\n return output\n\n\ndef cylinder_in_x(r, shape: (int, int, int)=(256, 256, 256), step_count=512):\n def cylinder(t):\n return -1 + (t * 2), 0, 0, r\n\n return trace_function(cylinder, shape=shape, step_count=step_count)\n\n\ndef cylinder_in_xy(r, shape: (int, int, int)=(256, 256, 256), step_count=512):\n def cylinder(t):\n return -1 + (t * 2), -1 + (t * 2), 0, r\n\n return trace_function(cylinder, shape=shape, step_count=step_count)\n\n\ndef cylinder_in_xyz(r, shape: (int, int, int)=(256, 256, 256), step_count=512):\n def cylinder(t):\n return -1 + (t * 2), -1 + (t * 2), -1 + (t * 2), r\n\n return trace_function(cylinder, shape=shape, step_count=step_count)\n\n\ndef torus_xy(r1, r2, shape: (int, int, int)=(256, 256, 256), step_count=101):\n \"\"\"\n Create a raster of a torus with radii r1, r2.\n - r1 is the small radius (donut cross section)\n - r2 is the large radius.\n\n (r2 - r1) is the center hole size\n \"\"\"\n # NOTE(meawoppl) - This is technically valid,\n # but unlikey to be what is intended.\n assert r2 > r1, \"Degenerate torus\"\n\n # NOTE(meawoppl) even step count might fail to\n # come out with full D4 symmetry\n def torus(t):\n theta = 2 * np.pi * t\n return r2 * np.cos(theta), r2 * np.sin(theta), 0, r1\n\n return trace_function(torus, shape=shape, step_count=step_count)\n\n\ndef contiguous_elements(arr: np.array):\n \"\"\"\n Finds contiguous True regions of the boolean array \"arr\".\n\n :param array: 1D boolean ndarray\n :returns array: 2d with first column as the (inclusive) start index of the matching\n regions, and second column is the (exclusive) end index.\n\n :Example:\n\n >>> kmath.contiguous_elements(np.array([0, 1, 1, 1, 2]) == 1)\n ... array([[1, 4]])\n\n \"\"\"\n d = np.diff(arr) # Find the indices of changes in \"array\"\n idx, = d.nonzero()\n # the start index is the next element after the change, so shift by 1\n idx += 1\n\n # deal with edges of diff\n if arr[0]: # If the start of arr is True prepend a 0\n idx = np.r_[0, idx]\n if arr[-1]: # If the end of arr is True, append the length\n idx = np.r_[idx, arr.size]\n\n idx.shape = (-1, 2) # Reshape the result into two columns\n return idx\n\n\ndef nonzero_bounds(arr: np.array):\n \"\"\"\n Return a tuple of the indices (inclusive, exclusive) that bracket nonzero values of `arr`.\n\n Useful for identifying the max and min bins of a histogram,\n or rising and falling edges of an object\n\n :param arr: 1D ndarray\n :returns tuple: first and last index of non-zero values.\n The last index is one greater than the last nonzero value (exclusive)\n\n :raises ValueError: if no nonzero elements found\n :raises AssertionError: if not a 1D array\n \"\"\"\n np.testing.assert_array_equal(arr.ndim, 1)\n nonzeros = np.nonzero(arr)[0]\n if nonzeros.size == 0:\n raise ValueError(\"No nonzero elements found in array\")\n return min(nonzeros), max(nonzeros) + 1\n\n\ndef normalized(arr: np.array, axis: int=-1, order: int=2):\n \"\"\"\n Normalize vector using 2-norm, across arbitrary axes,\n\n Deals with length 0 vectors well; avoids dividing by zero\n\n :param arr: ndarray, will be normalized along given `axis`\n :param axis: axis to normalize against (default=-1), same guidelines as np.linalg.norm\n :param order: the order of the normalization factor, default L2 (default=2)\n follows same guidelines as np.linalg.norm\n\n :returns: ndarray of same dimensions as `arr`\n \"\"\"\n norm_length = np.atleast_1d(np.linalg.norm(arr, order, axis))\n # set any zero elements to be 1, avoiding divide by zero errors\n norm_length[norm_length == 0] = 1\n if arr.ndim == 1:\n # single dimensions are speyshul\n return arr / norm_length\n return arr / np.expand_dims(norm_length, axis) # use array broadcasting\n\n\ndef cylinder(shape,\n p1: (numbers.Number, numbers.Number, numbers.Number),\n p2: (numbers.Number, numbers.Number, numbers.Number),\n r: numbers.Number,\n cap=\"flat\",\n dtype=np.uint8):\n \"\"\"\n Create a boolean right circular cylinder between two points, p1 and p2, with radius r\n\n Inputs:\n shape: shape of the volume to allocate\n p1: 3-tuple with coordinates of endpoint of cylinder, in base coordinates [-1, 1]\n p2: 3-tuple with coordinates of endpoint of cylinder, in base coordinates [-1, 1]\n r: uniform radius of the cylinder, in base coordinates\n Anything larger than 2 will be outside of the shape of the volume\n cap: str, or None.\n Use one of the types available in base.CAP_TYPES (Default=\"flat\")\n \"flat\" -- cuts the cylinder at each cylinder point (p1 & p2), leaving\n a circular plane cut normal to the line\n between (p2 - p1), at points p1 and p2. The resulting plane\n should have radius `r`.\n \"sphere\" -- adds a spherical end at each of the points given.\n The sphere will have the same radius as the cylinder at that point.\n \"none\" -- Leaves a cylinder along the given line between the two points, but\n does not terminate at the point; it is fully expanded to fill\n the line across the full volume\n\n foreground: the value to use in voxels inside the cylinder, default=1\n dtype: data type of the returned array, default=np.uint8\n\n Returns:\n ndarray, boolean, shape=`shape`\n\n Displays warnings.warn if radius is close to grid resolution\n Displays warnings.warn if radius is larger than the volume grid (>2)\n Raises AssertionError if cap is not in base.CAP_TYPES\n \"\"\"\n assert cap in CAP_TYPES\n nd_spacing = 1.0 / min(shape)\n if r < nd_spacing:\n warnings.warn(\n \"Radius of phantom is approaching grid rez. {} v. {}\".format(r, nd_spacing))\n if r >= 2:\n warnings.warn(\n \"Radius of cylinder is larger than the base volume: {} >= 2\".format(r))\n # allocate the output array\n output = np.zeros(shape, dtype=bool)\n\n # get the volume's coordinates in R^3 [-1, 1] inclusive\n xi, yi, zi = create_coordinate_block(shape)\n x1, y1, z1 = p1\n x2, y2, z2 = p2\n # wrap input tuples as arrays\n p1 = np.array(p1)\n p2 = np.array(p2)\n\n # first create the infinite cylinder\n cyl_length = np.linalg.norm(p2 - p1) # length of cylinder\n\n # This is essentially the cross product of the difference between a given point\n # p and the two points that define our line, squared and normalized\n # distances_vec ?= np.cross((points - p1), (points - p2)) ** 2 / (cyl_length ** 2)\n # This gives us the distance from all points to our cylinder center line\n # We aren't using the full vectorized form yet because we may need to have\n # a space to put in the isotropy vector for each component, and I wanted\n # to confirm this method works first.\n # We will somehow need to add isotropy to this equation\n distances = (((yi - y1) * (zi - z2) - (zi - z1) * (yi - y2)) ** 2 +\n ((zi - z1) * (xi - x2) - (xi - x1) * (zi - z2)) ** 2 +\n ((xi - x1) * (yi - y2) - (yi - y1) * (xi - x2)) ** 2) / (cyl_length ** 2)\n output[distances <= r ** 2] = 1\n # we have an infinite cylinder in our volume now\n\n # create set of vectorized points\n points = np.vstack((xi, yi, zi)).reshape(3, -1).T\n # Set the plane equation as the normalized vector, defined by the line between p2 and p1,\n # with p1 as the reference point\n normal = normalized(p2 - p1)\n\n # Find the correct sign by seeing which side the other point is on\n # sign will be zero if the two points are the same\n # We use p1 as reference, since thats what we did with the `normal` above\n sign = np.sign((p2 - p1).dot(normal))\n\n if cap != \"none\":\n # always trim the infinite cylinder here\n # any use of points could be masked to only the vectors that are already on\n # this would make the math a lot faster.\n # would need to figure out how to reallocate back into output array\n\n # first point\n plane_distance = distance_point_from_plane(points, normal, p1, -sign).reshape(shape)\n output[plane_distance > 0] = 0\n # second point\n plane_distance = distance_point_from_plane(points, normal, p2, sign).reshape(shape)\n output[plane_distance > 0] = 0\n\n if cap == \"sphere\":\n # requires that we have already cropped to \"flat\"\n # add a sphere on the cap after we chop the infinite cylinder\n sphere_distance = distance_point_from_point(points, p1).reshape(shape)\n output[sphere_distance < r] = 1\n sphere_distance = distance_point_from_point(points, p2).reshape(shape)\n output[sphere_distance < r] = 1\n\n return output\n\n\ndef distance_point_from_plane(points: np.array,\n plane_normal: np.array,\n ref_point: np.array,\n sign=1):\n \"\"\"\n Returns distance of all input points from a given plane\n\n Inputs:\n points: NxM ndarray, with N points of dimension M\n eg: a (200, 3) array of 200 3D point coordinates\n plane_normal: A length M 1D ndarray that defines the normal of a plane\n (a, b, c) would define the plane at ax + by + cz = 0\n ref_point: A length M ndarray, the point we use to offset the plane from the origin\n sign: integer, decides the negative or positive value of the returned distance\n One way to get the target sign is to Find a point that is on the side\n of the plane that you want, and use the sign of that point to decide\n the correct distance sign for the volume you want to mask.\n Default=1, or\n A positive `sign` will give positive distances on the associated target side\n You can get the correct target sign via:\n >>> target_sign = np.sign((selection_point - ref_point).dot(plane_normal))\n\n Returns:\n Nx1 ndarray of the distance from the input vectors to the plane\n\n Raises AssertionError if sign is anything other than -1 or 1\n\n TODO: sanity check that these are actual vector distances\n This doesnt matter when we are just using the sign, but it does if we actually want distance\n \"\"\"\n assert sign == 1 or sign == -1, \\\n \"'sign' must be positive or negative 1, got {}\".format(sign)\n return sign * (points - ref_point).dot(plane_normal)\n\n\ndef distance_point_from_point(points: np.array,\n ref_point: np.array):\n \"\"\"\n Distance of all input points from a given point\n Can be used to create a spherical mask around a point\n\n Inputs:\n points: NxM ndarray, with N points of dimension M\n eg: a (200, 3) array of 200 3D point coordinates\n ref_point: A length M ndarray, the relative origin\n\n Returns:\n Nx1 ndarray of the distance from the input vectors to the point\n \"\"\"\n return np.linalg.norm(points - ref_point, axis=-1)\n","sub_path":"skeletonization/skeleton/phantom_base.py","file_name":"phantom_base.py","file_ext":"py","file_size_in_byte":18238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"549732299","text":"from pydantic import BaseModel\n\n\nclass DefaultDarwin(BaseModel):\n \"\"\"Default Darwin-Py pydantic settings for meta information.\n Default settings include:\n - auto validating variables on setting/assignment\n - underscore attributes are private\n - objects are passed by reference to prevent unnecesary data copying\n \"\"\"\n\n class Config:\n validate_assignment = True\n underscore_attrs_are_private = True\n copy_on_model_validation = \"none\"\n","sub_path":"darwin/future/pydantic_base.py","file_name":"pydantic_base.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"473233122","text":"import numpy as np\n# ============================================================\n# Defining my own functions here\n# ============================================================\n\ndef dist_conv(amt,inp_unit,out_unit):\n meter=1.0\n feet=3.28084\n inches=39.3701\n miles=0.000621371\n if inp_unit==\"feet\":\n amt=amt/feet\n if inp_unit==\"inches\":\n amt=amt/inches\n if inp_unit==\"miles\":\n amt=amt/miles\n if out_unit==\"feet\":\n amt=amt*feet\n if out_unit==\"inches\":\n amt=amt*inches\n if out_unit==\"miles\":\n amt=amt*miles\n return amt\n\n\ndef weight_conv(amt,inp_unit,out_unit):\n kilogram=1.0\n ounces=35.274\n pounds=2.20462\n if inp_unit==\"ounces\":\n amt=amt/ounces\n if inp_unit==\"pounds\":\n amt=amt/pounds\n if out_unit==\"ounces\":\n amt=amt*ounces\n if out_unit==\"pounds\":\n amt=amt*pounds\n return amt\n\ndef temp_conv(amt,inp_unit,out_unit):\n fahrenheit=(9/5)*amt+32\n celcius=(amt-32)/1.8\n if out_unit==\"fahrenheit\":\n return fahrenheit\n if out_unit==\"celcius\":\n return celcius\n\ndef find_units(request):\n unit1=\"\"\n unit2=\"\"\n unit_type=\"\"\n flag=0\n signal=0\n hold=9223372036854775807\n hold2=0\n distance=[[\"eter\",\" m \"],[\"eet\",\"ft\",\"oot\"],[\"nch\",\"in\"],[\"mi\",\"ile\"]]\n dist=[\"meters\",\"feet\",\"inches\",\"miles\"]\n weight=[[\"ilogram\",\"Kg\",\"kg\"],[\"unce\",\"oz\"],[\"lb\",\"pound\"]]\n wght=[\"kilograms\",\"ounces\",\"pounds\"]\n temperature=[[\"elcius\",\" C \"],[\"ahrenheit\",\" F \"]]\n temp=[\"celcius\",\"fahrenheit\"]\n unit_type=\"\"\n for b in range(len(distance)):\n u=distance[b]\n\n for x in u:\n if -1hold2:\n hold2=request.find(y)\n unit_type=\"distance\"\n unit2=dist[b]\n\n for b in range(len(weight)):\n u=weight[b]\n\n for x in u:\n for x in u:\n if -1hold2:\n hold2=request.find(y)\n unit_type=\"weight\"\n unit2=wght[b]\n\n for b in range(len(temperature)):\n u=temperature[b]\n\n for x in u:\n for x in u:\n if -1hold2:\n hold2=request.find(y)\n unit_type=\"temperature\"\n unit2=temp[b]\n\n return [unit1,unit2,unit_type]\n\ndef myParser(txt):\n\n units=find_units(txt)\n input_u=units[0]\n output_u=units[1]\n un_type=units[2]\n myflag=0\n num1=0\n num2=0\n for i in range(len(txt)):\n if txt[i].isdigit() and myflag==0:\n num1=i\n myflag=1\n if txt[i].isdigit() and myflag==1:\n num2=i\n final_num=float(txt[num1:num2+1])\n des_out=0\n if un_type == \"distance\":\n des_out=dist_conv(final_num,input_u,output_u)\n if un_type == \"weight\":\n des_out=weight_conv(final_num,input_u,output_u)\n if un_type == \"temperature\":\n des_out=temp_conv(final_num,input_u,output_u)\n if (input_u is output_u):\n return \"ERROR: You have entered incorrect units\"\n else:\n return (str(round(des_out,1))+\" \"+output_u)\n","sub_path":"UnitConverter.py","file_name":"UnitConverter.py","file_ext":"py","file_size_in_byte":3548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"379674674","text":"# Copyright 2019 Atalaya Tech, Inc.\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport click\n\nfrom bentoml.utils.lazy_loader import LazyLoader\nfrom bentoml.cli.utils import Spinner\nfrom bentoml.utils import get_default_yatai_client\nfrom bentoml.cli.click_utils import (\n BentoMLCommandGroup,\n parse_bento_tag_callback,\n _echo,\n CLI_COLOR_SUCCESS,\n parse_labels_callback,\n)\nfrom bentoml.cli.deployment import (\n _print_deployment_info,\n _print_deployments_info,\n)\nfrom bentoml.yatai.deployment import ALL_NAMESPACE_TAG\nfrom bentoml.exceptions import CLIException\nfrom bentoml.utils import status_pb_to_error_code_and_message\n\nyatai_proto = LazyLoader('yatai_proto', globals(), 'bentoml.yatai.proto')\n\n\nDEFAULT_SAGEMAKER_INSTANCE_TYPE = 'ml.m4.xlarge'\nDEFAULT_SAGEMAKER_INSTANCE_COUNT = 1\n\n\ndef get_aws_sagemaker_sub_command():\n # pylint: disable=unused-variable\n\n @click.group(\n name='sagemaker',\n help='Commands for AWS Sagemaker BentoService deployments',\n cls=BentoMLCommandGroup,\n )\n def aws_sagemaker():\n pass\n\n @aws_sagemaker.command(help='Deploy BentoService to AWS Sagemaker')\n @click.argument('name', type=click.STRING)\n @click.option(\n '-b',\n '--bento',\n '--bento-service-bundle',\n type=click.STRING,\n required=True,\n callback=parse_bento_tag_callback,\n help='Target BentoService to be deployed, referenced by its name and version '\n 'in format of name:version. For example: \"iris_classifier:v1.2.0\"',\n )\n @click.option(\n '-n',\n '--namespace',\n type=click.STRING,\n help='Deployment namespace managed by BentoML, default value is \"dev\" which '\n 'can be changed in BentoML configuration yatai_service/default_namespace',\n )\n @click.option(\n '-l',\n '--labels',\n type=click.STRING,\n callback=parse_labels_callback,\n help='Key:value pairs that are attached to deployments and intended to be used '\n 'to specify identifying attributes of the deployments that are meaningful to '\n 'users. Multiple labels are separated with `,`',\n )\n @click.option('--region', help='AWS region name for deployment')\n @click.option(\n '--api-name',\n help='User defined API function will be used for inference.',\n required=True,\n )\n @click.option(\n '--instance-type',\n help='Type of instance will be used for inference. Default to \"m1.m4.xlarge\"',\n type=click.STRING,\n default=DEFAULT_SAGEMAKER_INSTANCE_TYPE,\n )\n @click.option(\n '--instance-count',\n help='Number of instance will be used. Default value is 1',\n type=click.INT,\n default=DEFAULT_SAGEMAKER_INSTANCE_COUNT,\n )\n @click.option(\n '--num-of-gunicorn-workers-per-instance',\n help='Number of gunicorn worker will be used per instance. Default value for '\n 'gunicorn worker is based on the instance\\' cpu core counts. '\n 'The formula is num_of_cpu/2 + 1',\n type=click.INT,\n )\n @click.option(\n '--timeout',\n help=\"The amount of time Sagemaker will wait before return response\",\n type=click.INT,\n default=60,\n )\n @click.option('-o', '--output', type=click.Choice(['json', 'yaml']), default='json')\n @click.option(\n '--wait/--no-wait',\n default=True,\n help='Wait for apply action to complete or encounter an error.'\n 'If set to no-wait, CLI will return immediately. The default value is wait',\n )\n @click.option(\n '--data-capture-s3-prefix',\n help=\"To enable data capture (input and output), \"\n \"provide a destination s3 prefix \"\n \"(of the format `s3://bucket-name/optional/prefix`)\"\n \" for the captured data. To disable data capture, leave this blank.\",\n type=click.STRING,\n default=None,\n )\n @click.option(\n '--data-capture-sample-percent',\n help=\"When data capture is enabled, the sampling percentage. Default 100%. \"\n \"No effect without data-capture-s3-prefix.\",\n type=click.IntRange(1, 100),\n default=100,\n )\n def deploy(\n name,\n bento,\n namespace,\n labels,\n region,\n instance_type,\n instance_count,\n num_of_gunicorn_workers_per_instance,\n api_name,\n timeout,\n output,\n wait,\n data_capture_s3_prefix,\n data_capture_sample_percent,\n ):\n # use the DeploymentOperator name in proto to be consistent with amplitude\n bento_name, bento_version = bento.split(':')\n yatai_client = get_default_yatai_client()\n with Spinner('Deploying Sagemaker deployment '):\n result = yatai_client.deployment.create_sagemaker_deployment(\n name=name,\n namespace=namespace,\n labels=labels,\n bento_name=bento_name,\n bento_version=bento_version,\n instance_count=instance_count,\n instance_type=instance_type,\n num_of_gunicorn_workers_per_instance=num_of_gunicorn_workers_per_instance, # noqa E501\n api_name=api_name,\n timeout=timeout,\n region=region,\n wait=wait,\n data_capture_s3_prefix=data_capture_s3_prefix,\n data_capture_sample_percent=data_capture_sample_percent,\n )\n if result.status.status_code != yatai_proto.status_pb2.Status.OK:\n error_code, error_message = status_pb_to_error_code_and_message(\n result.status\n )\n raise CLIException(f'{error_code}:{error_message}')\n _echo(\n f'Successfully created AWS Sagemaker deployment {name}', CLI_COLOR_SUCCESS,\n )\n _print_deployment_info(result.deployment, output)\n\n @aws_sagemaker.command(help='Update existing AWS Sagemaker deployment')\n @click.argument('name', type=click.STRING)\n @click.option(\n '-b',\n '--bento',\n '--bento-service-bundle',\n type=click.STRING,\n callback=parse_bento_tag_callback,\n help='Target BentoService to be deployed, referenced by its name and version '\n 'in format of name:version. For example: \"iris_classifier:v1.2.0\"',\n )\n @click.option(\n '-n',\n '--namespace',\n type=click.STRING,\n help='Deployment namespace managed by BentoML, default value is \"dev\" which '\n 'can be changed in BentoML configuration file',\n )\n @click.option(\n '--instance-type',\n help='Type of instance will be used for inference. Default to \"m1.m4.xlarge\"',\n type=click.STRING,\n )\n @click.option(\n '--instance-count',\n help='Number of instance will be used. Default value is 1',\n type=click.INT,\n )\n @click.option(\n '--num-of-gunicorn-workers-per-instance',\n help='Number of gunicorn worker will be used per instance. Default value for '\n 'gunicorn worker is based on the instance\\' cpu core counts. '\n 'The formula is num_of_cpu/2 + 1',\n type=click.INT,\n )\n @click.option(\n '--api-name', help='User defined API function will be used for inference.',\n )\n @click.option(\n '--timeout',\n help=\"The amount of time Sagemaker will wait before return response\",\n type=click.INT,\n default=60,\n )\n @click.option('-o', '--output', type=click.Choice(['json', 'yaml']), default='json')\n @click.option(\n '--wait/--no-wait',\n default=True,\n help='Wait for apply action to complete or encounter an error.'\n 'If set to no-wait, CLI will return immediately. The default value is wait',\n )\n @click.option(\n '--data-capture-s3-prefix',\n help=\"To enable data capture (input and output), \"\n \"provide a destination s3 prefix \"\n \"(of the format `s3://bucket-name/optional/prefix`)\"\n \" for the captured data. To disable data capture, leave this blank.\",\n type=click.STRING,\n default=None,\n )\n @click.option(\n '--data-capture-sample-percent',\n help=\"When data capture is enabled, the sampling percentage. Default 100%. \"\n \"No effect without data-capture-s3-prefix.\",\n type=click.IntRange(1, 100),\n default=100,\n )\n def update(\n name,\n namespace,\n bento,\n api_name,\n instance_type,\n instance_count,\n num_of_gunicorn_workers_per_instance,\n timeout,\n output,\n wait,\n data_capture_s3_prefix,\n data_capture_sample_percent,\n ):\n yatai_client = get_default_yatai_client()\n if bento:\n bento_name, bento_version = bento.split(':')\n else:\n bento_name = None\n bento_version = None\n with Spinner('Updating Sagemaker deployment '):\n result = yatai_client.deployment.update_sagemaker_deployment(\n namespace=namespace,\n deployment_name=name,\n bento_name=bento_name,\n bento_version=bento_version,\n instance_count=instance_count,\n instance_type=instance_type,\n num_of_gunicorn_workers_per_instance=num_of_gunicorn_workers_per_instance, # noqa E501\n timeout=timeout,\n api_name=api_name,\n wait=wait,\n data_capture_s3_prefix=data_capture_s3_prefix,\n data_capture_sample_percent=data_capture_sample_percent,\n )\n if result.status.status_code != yatai_proto.status_pb2.Status.OK:\n error_code, error_message = status_pb_to_error_code_and_message(\n result.status\n )\n raise CLIException(f'{error_code}:{error_message}')\n _echo(\n f'Successfully updated AWS Sagemaker deployment {name}', CLI_COLOR_SUCCESS,\n )\n _print_deployment_info(result.deployment, output)\n\n @aws_sagemaker.command(help='Delete AWS Sagemaker deployment')\n @click.argument('name', type=click.STRING)\n @click.option(\n '-n',\n '--namespace',\n type=click.STRING,\n help='Deployment namespace managed by BentoML, default value is \"dev\" which '\n 'can be changed in BentoML configuration yatai_service/default_namespace',\n )\n @click.option(\n '--force',\n is_flag=True,\n help='force delete the deployment record in database and '\n 'ignore errors when deleting cloud resources',\n )\n def delete(name, namespace, force):\n yatai_client = get_default_yatai_client()\n get_deployment_result = yatai_client.deployment.get(namespace, name)\n if get_deployment_result.status.status_code != yatai_proto.status_pb2.Status.OK:\n error_code, error_message = status_pb_to_error_code_and_message(\n get_deployment_result.status\n )\n raise CLIException(f'{error_code}:{error_message}')\n result = yatai_client.deployment.delete(name, namespace, force)\n if result.status.status_code != yatai_proto.status_pb2.Status.OK:\n error_code, error_message = status_pb_to_error_code_and_message(\n result.status\n )\n raise CLIException(f'{error_code}:{error_message}')\n _echo(\n f'Successfully deleted AWS Sagemaker deployment \"{name}\"',\n CLI_COLOR_SUCCESS,\n )\n\n @aws_sagemaker.command(help='Get AWS Sagemaker deployment information')\n @click.argument('name', type=click.STRING)\n @click.option(\n '-n',\n '--namespace',\n type=click.STRING,\n help='Deployment namespace managed by BentoML, default value is \"dev\" which '\n 'can be changed in BentoML configuration yatai_service/default_namespace',\n )\n @click.option(\n '-o', '--output', type=click.Choice(['json', 'yaml', 'table']), default='json'\n )\n def get(name, namespace, output):\n yatai_client = get_default_yatai_client()\n get_result = yatai_client.deployment.get(namespace, name)\n if get_result.status.status_code != yatai_proto.status_pb2.Status.OK:\n error_code, error_message = status_pb_to_error_code_and_message(\n get_result.status\n )\n raise CLIException(f'{error_code}:{error_message}')\n describe_result = yatai_client.deployment.describe(namespace, name)\n if describe_result.status.status_code != yatai_proto.status_pb2.Status.OK:\n error_code, error_message = status_pb_to_error_code_and_message(\n describe_result.status\n )\n raise CLIException(f'{error_code}:{error_message}')\n get_result.deployment.state.CopyFrom(describe_result.state)\n _print_deployment_info(get_result.deployment, output)\n\n @aws_sagemaker.command(\n name='list', help='List AWS Sagemaker deployment information'\n )\n @click.option(\n '-n',\n '--namespace',\n type=click.STRING,\n help='Deployment namespace managed by BentoML, default value is \"dev\" which '\n 'can be changed in BentoML configuration yatai_service/default_namespace',\n default=ALL_NAMESPACE_TAG,\n )\n @click.option(\n '--limit',\n type=click.INT,\n help='The maximum amount of AWS Sagemaker deployments to be listed at once',\n )\n @click.option(\n '-l',\n '--labels',\n type=click.STRING,\n help=\"Label query to filter Sagemaker deployments, supports '=', '!=', 'IN', \"\n \"'NotIn', 'Exists', and 'DoesNotExist'. (e.g. key1=value1, \"\n \"key2!=value2, key3 In (value3, value3a), key4 DoesNotExist)\",\n )\n @click.option(\n '--order-by', type=click.Choice(['created_at', 'name']), default='created_at',\n )\n @click.option(\n '--asc/--desc',\n default=False,\n help='Ascending or descending order for list deployments',\n )\n @click.option(\n '-o',\n '--output',\n type=click.Choice(['json', 'yaml', 'table', 'wide']),\n default='table',\n )\n def list_deployment(namespace, limit, labels, order_by, asc, output):\n yatai_client = get_default_yatai_client()\n list_result = yatai_client.deployment.list_sagemaker_deployments(\n limit=limit,\n labels=labels,\n namespace=namespace,\n order_by=order_by,\n ascending_order=asc,\n )\n if list_result.status.status_code != yatai_proto.status_pb2.Status.OK:\n error_code, error_message = status_pb_to_error_code_and_message(\n list_result.status\n )\n raise CLIException(f'{error_code}:{error_message}')\n _print_deployments_info(list_result.deployments, output)\n\n return aws_sagemaker\n","sub_path":"bentoml/cli/aws_sagemaker.py","file_name":"aws_sagemaker.py","file_ext":"py","file_size_in_byte":15420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"312712268","text":"from urllib import request\n\n\nAPI_ENDPOINT = 'http://www.nbp.pl/kursy/xml/'\nTABLE_LIST_ENDPOINT = API_ENDPOINT + 'dir.txt'\nDATE_FORMAT = '%y%m%d'\nTABLE_NAME_PREFIX = 'a'\n\n\ndef get_tables():\n stream = request.urlopen(TABLE_LIST_ENDPOINT)\n bytes = stream.read()\n text = bytes.decode('utf-8-sig')\n tables = text.splitlines()\n return tables\n\n\ndef get_table_name(date):\n tables = get_tables()\n for table_name in tables:\n if is_right_table(table_name, date):\n return table_name\n return None\n\n\ndef is_right_table(table_name, date):\n right_prefix = table_name.startswith(TABLE_NAME_PREFIX)\n date_as_str = date.strftime(DATE_FORMAT)\n right_date = table_name.endswith(date_as_str)\n return right_prefix and right_date\n","sub_path":"nbpapi-mocking/nbpapi.py","file_name":"nbpapi.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"626914777","text":"import asyncio\nimport aiohttp\nfrom .db import RedisClient\nimport time\nimport sys\nfrom .settings import *\nfrom .logger_proxy import mylogger\nlogger=mylogger.get_logger('test')\ntry:\n from aiohttp import ClientError\nexcept:\n from aiohttp import ClientProxyConnectionError as ProxyConnectionError\n\nclass tester(object):\n def __init__(self):\n self.redis=RedisClient()\n async def test_single_proxy(self,proxy):\n conn = aiohttp.TCPConnector(verify_ssl=False) #下一句with as session:前后文管理器,with结束,session会话结束\n async with aiohttp.ClientSession(connector=conn) as session:#aiohttp则是基于asyncio实现的HTTP框架;这里要引入一个类,aiohttp.ClientSession.\n # 首先要建立一个session对象,然后用该session对象去打开网页\n try:\n if isinstance(proxy,bytes):\n proxy=proxy.decode('utf-8')#将bytes对象解码成字符串,默认使用utf-8进行解码。防止数据库提取的proxy是bytes格式。\n real_proxy = 'http://' + proxy\n logger.info('正在测试代理')\n async with session.get(Test_url,proxy=real_proxy,timeout=15,allow_redirects=False) as response:\n if response.status in VALID_STATUS_CODES:\n self.redis.max(proxy)# 将可用代理分值设为100\n logger.info('proxy is enable %s' %proxy)\n else:\n self.redis.decrease(proxy)\n logger.info('请求响应码不合适 %s %s'%(response.status,proxy))\n except (ConnectionError,ClientError,TimeoutError,ArithmeticError):\n self.redis.decrease(proxy)\n logger.info('代理请求失败 %s'%proxy)\n def run(self):\n \"\"\"\n 测试主函数\n :return:\n \"\"\"\n logger.info('测试器开始运行')\n try:\n count=self.redis.count()\n logger.info('当前剩余 %d 个代理'%count)\n for i in range(0,count,Batch_test_size):#所有代理,按照批次检测的个数,分段\n start = i\n stop=min(i+Batch_test_size,count)\n logger.info('正在检测第 %s 到%s之间的代理'%(start + 1,stop))\n test_proxies = self.redis.batch(start=start,stop=stop)\n loop = asyncio.get_event_loop()#asyncio实现并发,就需要多个协程组成列表来完成任务【创建多个协程的列表,然后将这些协程注册到事件循环中】,\n # 每当有任务阻塞的时候就await,然后其他协程继续工作,所以下面是协程列表;\n # 所谓的并发:多个任务需要同时进行;\n tasks=[self.test_single_proxy(proxy) for proxy in test_proxies]\n loop.run_until_complete(asyncio.wait(tasks))#asyncio.wait(tasks)接受一个列表\n sys.stdout.flush()\n time.sleep(5)\n except Exception as e:\n logger.exception('测试发生错误 %s'%e)\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"proxy_pool_new/proxy_pool_new/tester.py","file_name":"tester.py","file_ext":"py","file_size_in_byte":3287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"247660952","text":"# 종이의 개수\n\n# def solve(y, x):\n# global paper, visited, N\n# number = paper[y][x]\n# checkList = ((y - 1, x), (y + 1, x), (y, x - 1), (y, x + 1))\n# for check in checkList:\n# if 0 <= check[0] < N and 0 <= check[1] < N:\n# if number == paper[check[0]][check[1]] and not visited[check[0]][check[1]]:\n# visited[check[0]][check[1]] = True\n# solve(check[0], check[1])\n\n# for x in range(N):\n# for y in range(N):\n# if not visited[y][x]:\n# solve(y, x)\n# countList[paper[y][x] + 1] += 1\n\nimport sys\n\npaper = []\nN = int(sys.stdin.readline())\nfor _ in range(N):\n paper.append(list(map(int, sys.stdin.readline().split())))\n\ncountList = [0, 0, 0]\n\n\ndef nine_range(part_paper):\n n = len(part_paper[0])\n three = n // 3\n three_list = [range(three), range(three, n - three), range(n - three, n)]\n nine_paper = []\n for x in three_list:\n for y in three_list:\n nine_paper.append([[part_paper[i][j] for i in y] for j in x])\n return nine_paper\n\n\ndef solve(part_paper):\n flat_paper = [item for sub in part_paper for item in sub]\n if len(set(flat_paper)) <= 1:\n countList[flat_paper[0] + 1] += 1\n else:\n for part_part_paper in nine_range(part_paper):\n solve(part_part_paper)\n\n\nsolve(paper)\nfor count in countList:\n print(count)\n","sub_path":"SsangWoo/python/baekjoon/1780.py","file_name":"1780.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"14696431","text":"\"\"\"Convert zim wiki syntax to markdown\n\nStripped and modified from markdown2.py\n\nSyntax converted:\n\n type Markdown <- Zim\n ----------------------------------------------------\n Heading1 # heading ===== heading =====\n Heading2 ## heading ==== heading ====\n Heading3 ### heading === heading ===\n Heading4 #### heading == heading ==\n Heading5 ##### heading = heading =\n Heading6 ###### heading = heading =\n ----------------------------------------------------\n unordered list -/+/* *\n ordered list 1. 2. 3. 1. 2. 3.\n ----------------------------------------------------\n bold **bold** **bold**\n __bold__ __bold__\n italic *italic* //italic//\n _italic_ //italic//\n strike ~~strike~~ ~~strike~~\n ----------------------------------------------------\n quote > '''\n texts... texts...\n '''\n code ``` ```\n texts... texts...\n ``` ```\n ----------------------------------------------------\n inline link [text](url) [[url|text]]\n ----------------------------------------------------\n ref link [text](url)\n [[url|text]]\n ----------------------------------------------------\n image ![img](url) {{url}}\n ----------------------------------------------------\n\n\n\nSyntax not supported:\n - footnote\n - tables\n\n\nUpdate time: 2019-09-27 19:59:00.\n\"\"\"\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\n\nfrom builtins import bytes\nfrom builtins import str\nfrom builtins import range\nfrom past.builtins import basestring\nfrom builtins import object\nimport re\nimport sys,os\nimport argparse\nfrom lib import tools\ntry:\n from hashlib import md5\nexcept ImportError:\n from md5 import md5\nfrom random import random, randint\n\n# Use `bytes` for byte strings and `unicode` for unicode strings (str in Py3).\nif sys.version_info[0] <= 2:\n py3 = False\n try:\n bytes\n except NameError:\n bytes = str\n base_string_type = basestring\nelif sys.version_info[0] >= 3:\n py3 = True\n base_string_type = str\n\n\n\n#---- globals\nDEBUG = False\n\nDEFAULT_TAB_WIDTH = 4\n\n\nSECRET_SALT = bytes(randint(0, 1000000))\ndef _hash_text(s):\n return 'md5-' + md5(SECRET_SALT + s.encode(\"utf-8\")).hexdigest()\n\n\n\ng_escape_table = dict([(ch, _hash_text(ch))\n for ch in '\\\\`*_{}[]()>#+-.!'])\n\n\n_home_re=re.compile('^(~)(.+)$')\n\ndef _home_re_sub(match):\n return os.path.expanduser(match.group(1))+match.group(2)\n\ndef findBaseDir(curdir):\n target_file='notebook.zim'\n\n if os.path.exists(os.path.join(curdir,target_file)):\n return curdir\n else:\n return findBaseDir(os.path.split(curdir)[0])\n\ndef parseLink(link_text, dec, file_path):\n\n if file_path is None:\n if dec in [':', '+', '']:\n return '%s%s' %(dec, link_text)\n else:\n return dec\n\n file_path=_home_re.sub(_home_re_sub,file_path)\n curdir, curfile=os.path.split(file_path)\n link_file='%s.txt' %link_text\n\n if dec=='':\n result=os.path.join(curdir,link_file)\n if os.path.exists(result):\n return result\n else:\n parentdir=os.path.split(curdir)[0]\n result=os.path.join(parentdir,link_file)\n if os.path.exists(result):\n return result\n else:\n return link_text\n\n elif dec==':':\n try:\n basedir=findBaseDir(curdir)\n except:\n return '%s%s' %(dec,link_text)\n\n result=os.path.join(basedir,link_file)\n if os.path.exists(result):\n return result\n else:\n return '%s%s' %(dec,link_text)\n\n elif dec=='+':\n subdir=os.path.join(curdir,os.path.splitext(curfile)[0])\n result=os.path.join(subdir,link_file)\n if os.path.isdir(subdir) and os.path.exists(result):\n return result\n else:\n return '%s%s' %(dec,link_text)\n\n else:\n return dec\n\n\n\nclass Zim2Markdown(object):\n urls = None\n titles = None\n\n # Used to track when we're inside an ordered or unordered list\n # (see _ProcessListItems() for details):\n list_level = 0\n\n _ws_only_line_re = re.compile(r\"^[ \\t]+$\", re.M)\n\n def __init__(self, html4tags=False, tab_width=4, file=None):\n\n self.tab_width = tab_width\n self.file=file\n self._outdent_re = re.compile(r'^(\\t|[ ]{1,%d})' % tab_width, re.M)\n self._escape_table = g_escape_table.copy()\n\n def reset(self):\n self.urls = {}\n self.titles = {}\n self.list_level = 0\n self.footnotes = {}\n self.footnote_ids = []\n\n\n def convert(self, text):\n \"\"\"Convert the given text.\"\"\"\n # Main function. The order in which other subs are called here is\n # essential. Link and image substitutions need to happen before\n # _EscapeSpecialChars(), so that any *'s or _'s in the
    \n # and tags get encoded.\n\n # Clear the global hashes. If we don't clear these, you get conflicts\n # from other articles when generating a page which contains more than\n # one article (e.g. an index page that shows the N most recent\n # articles):\n self.reset()\n\n # Standardize line endings:\n text = re.sub(\"\\r\\n|\\r\", \"\\n\", text)\n\n # Make sure $text ends with a couple of newlines:\n text += \"\\n\\n\"\n\n # Convert all tabs to spaces.\n #text = self._detab(text)\n\n # Strip any lines consisting only of spaces and tabs.\n # This makes subsequent regexen easier to write, because we can\n # match consecutive blank lines with /\\n+/ instead of something\n # contorted like /[ \\t]*\\n+/ .\n text = self._ws_only_line_re.sub(\"\", text)\n\n text = self._do_fenced_code_blocks(text)\n\n # Strip link definitions, store in hashes.\n # Must do footnotes first because an unlucky footnote defn\n # looks like a link defn:\n # [^4]: this \"looks like a link defn\"\n text = self._strip_footnote_definitions(text)\n\n text = self._strip_link_definitions(text)\n\n text = self._run_block_gamut(text)\n\n #text = self._add_footnotes(text)\n\n text += \"\\n\"\n\n return text\n\n\n\n _detab_re = re.compile(r'(.*?)\\t', re.M)\n def _detab_sub(self, match):\n g1 = match.group(1)\n return g1 + (' ' * (self.tab_width - len(g1) % self.tab_width))\n\n def _detab(self, text):\n r\"\"\"Remove (leading?) tabs from a file.\n\n >>> m = Markdown()\n >>> m._detab(\"\\tfoo\")\n ' foo'\n >>> m._detab(\" \\tfoo\")\n ' foo'\n >>> m._detab(\"\\t foo\")\n ' foo'\n >>> m._detab(\" foo\")\n ' foo'\n >>> m._detab(\" foo\\n\\tbar\\tblam\")\n ' foo\\n bar blam'\n \"\"\"\n if '\\t' not in text:\n return text\n return self._detab_re.subn(self._detab_sub, text)[0]\n\n\n\n def _strip_link_definitions(self, text):\n # Strips link definitions from text, stores the URLs and titles in\n # hash references.\n less_than_tab = self.tab_width - 1\n\n # Link defs are in the form:\n # [id]: url \"optional title\"\n _link_def_re = re.compile(r\"\"\"\n ^[ ]{0,%d}\\[(.+)\\]: # id = \\1\n [ \\t]*\n \\n? # maybe *one* newline\n [ \\t]*\n ? # url = \\2\n [ \\t]*\n (?:\n \\n? # maybe one newline\n [ \\t]*\n (?<=\\s) # lookbehind for whitespace\n ['\"(]\n ([^\\n]*) # title = \\3\n ['\")]\n [ \\t]*\n )? # title is optional\n (?:\\n+|\\Z)\n \"\"\" % less_than_tab, re.X | re.M | re.U)\n return _link_def_re.sub(self._extract_link_def_sub, text)\n\n # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:\n # http://bumppo.net/projects/amputator/\n _ampersand_re = re.compile(r'&(?!#?[xX]?(?:[0-9a-fA-F]+|\\w+);)')\n _naked_lt_re = re.compile(r'<(?![a-z/?\\$!])', re.I)\n _naked_gt_re = re.compile(r'''(?''', re.I)\n\n def _encode_amps_and_angles(self, text):\n # Smart processing for ampersands and angle brackets that need\n # to be encoded.\n text = self._ampersand_re.sub('&', text)\n\n # Encode naked <'s\n text = self._naked_lt_re.sub('<', text)\n\n # Encode naked >'s\n # Note: Other markdown implementations (e.g. Markdown.pl, PHP\n # Markdown) don't do this.\n text = self._naked_gt_re.sub('>', text)\n return text\n\n\n\n\n def _extract_link_def_sub(self, match):\n id, url, title = match.groups()\n key = id.lower() # Link IDs are case-insensitive\n self.urls[key] = self._encode_amps_and_angles(url)\n if title:\n self.titles[key] = title\n return \"\"\n\n\n def _extract_footnote_def_sub(self, match):\n id, text = match.groups()\n text = _dedent(text, skip_first_line=not text.startswith('\\n')).strip()\n normed_id = re.sub(r'\\W', '-', id)\n # Ensure footnote text ends with a couple newlines (for some\n # block gamut matches).\n self.footnotes[normed_id] = text + \"\\n\\n\"\n return \"\"\n\n def _strip_footnote_definitions(self, text):\n \"\"\"A footnote definition looks like this:\n\n [^note-id]: Text of the note.\n\n May include one or more indented paragraphs.\n\n Where,\n - The 'note-id' can be pretty much anything, though typically it\n is the number of the footnote.\n - The first paragraph may start on the next line, like so:\n\n [^note-id]:\n Text of the note.\n \"\"\"\n less_than_tab = self.tab_width - 1\n footnote_def_re = re.compile(r'''\n ^[ ]{0,%d}\\[\\^(.+)\\]: # id = \\1\n [ \\t]*\n ( # footnote text = \\2\n # First line need not start with the spaces.\n (?:\\s*.*\\n+)\n (?:\n (?:[ ]{%d} | \\t) # Subsequent lines must be indented.\n .*\\n+\n )*\n )\n # Lookahead for non-space at line-start, or end of doc.\n (?:(?=^[ ]{0,%d}\\S)|\\Z)\n ''' % (less_than_tab, self.tab_width, self.tab_width),\n re.X | re.M)\n return footnote_def_re.sub(self._extract_footnote_def_sub, text)\n\n\n def _run_block_gamut(self, text):\n # These are all the transformations that form block-level\n # tags like paragraphs, headers, and list items.\n\n text = self._do_fenced_code_blocks(text)\n\n text = self._do_headers(text)\n\n # Do Horizontal Rules:\n # On the number of spaces in horizontal rules: The spec is fuzzy: \"If\n # you wish, you may use spaces between the hyphens or asterisks.\"\n # Markdown.pl 1.0.1's hr regexes limit the number of spaces between the\n # hr chars to one or two. We'll reproduce that limit here.\n\n text = self._do_lists(text)\n\n text = self._do_code_blocks(text)\n\n text = self._do_block_quotes(text)\n\n # We already ran _HashHTMLBlocks() before, in Markdown(), but that\n # was to escape raw HTML in the original Markdown source. This time,\n # we're escaping the markup we've just created, so that we don't wrap\n #

    tags around block-level tags.\n #text = self._hash_html_blocks(text)\n\n text = self._form_paragraphs(text)\n\n return text\n\n\n\n\n\n\n def _run_span_gamut(self, text):\n # These are all the transformations that occur *within* block-level\n # tags like paragraphs, headers, and list items.\n\n text = self._do_code_spans(text)\n\n text = self._do_links(text)\n\n text = self._do_strike(text)\n\n text = self._do_italics_and_bold(text)\n\n return text\n\n\n\n _inline_link_title = re.compile(r'''\n ( # \\1\n [ \\t]+\n (['\"]) # quote char = \\2\n (?P.*?)\n \\2\n )? # title is optional\n \\)$\n ''', re.X | re.S)\n _tail_of_reference_link_re = re.compile(r'''\n # Match tail of: [text][id]\n [ ]? # one optional space\n (?:\\n[ ]*)? # one optional newline followed by spaces\n \\[\n (?P<id>.*?)\n \\]\n ''', re.X | re.S)\n\n _whitespace = re.compile(r'\\s*')\n\n _strip_anglebrackets = re.compile(r'<(.*)>.*')\n\n def _find_non_whitespace(self, text, start):\n \"\"\"Returns the index of the first non-whitespace character in text\n after (and including) start\n \"\"\"\n match = self._whitespace.match(text, start)\n return match.end()\n\n def _find_balanced(self, text, start, open_c, close_c):\n \"\"\"Returns the index where the open_c and close_c characters balance\n out - the same number of open_c and close_c are encountered - or the\n end of string if it's reached before the balance point is found.\n \"\"\"\n i = start\n l = len(text)\n count = 1\n while count > 0 and i < l:\n if text[i] == open_c:\n count += 1\n elif text[i] == close_c:\n count -= 1\n i += 1\n return i\n\n def _extract_url_and_title(self, text, start):\n \"\"\"Extracts the url and (optional) title from the tail of a link\"\"\"\n # text[start] equals the opening parenthesis\n idx = self._find_non_whitespace(text, start+1)\n if idx == len(text):\n return None, None, None\n end_idx = idx\n has_anglebrackets = text[idx] == \"<\"\n if has_anglebrackets:\n end_idx = self._find_balanced(text, end_idx+1, \"<\", \">\")\n end_idx = self._find_balanced(text, end_idx, \"(\", \")\")\n match = self._inline_link_title.search(text, idx, end_idx)\n if not match:\n return None, None, None\n url, title = text[idx:match.start()], match.group(\"title\")\n if has_anglebrackets:\n url = self._strip_anglebrackets.sub(r'\\1', url)\n return url, title, end_idx\n\n\n\n\n def _do_links(self, text):\n \"\"\"Turn Markdown link shortcuts into XHTML <a> and <img> tags.\n\n This is a combination of Markdown.pl's _DoAnchors() and\n _DoImages(). They are done together because that simplified the\n approach. It was necessary to use a different approach than\n Markdown.pl because of the lack of atomic matching support in\n Python's regex engine used in $g_nested_brackets.\n \"\"\"\n MAX_LINK_TEXT_SENTINEL = 3000 # markdown2 issue 24\n\n # `anchor_allowed_pos` is used to support img links inside\n # anchors, but not anchors inside anchors. An anchor's start\n # pos must be `>= anchor_allowed_pos`.\n anchor_allowed_pos = 0\n\n curr_pos = 0\n while True: # Handle the next link.\n # The next '[' is the start of:\n # - an inline anchor: [text](url \"title\")\n # - a reference anchor: [text][id]\n # - an inline img: ![text](url \"title\")\n # - a reference img: ![text][id]\n # - a footnote ref: [^id]\n # (Only if 'footnotes' extra enabled)\n # - a footnote defn: [^id]: ...\n # (Only if 'footnotes' extra enabled) These have already\n # been stripped in _strip_footnote_definitions() so no\n # need to watch for them.\n # - a link definition: [id]: url \"title\"\n # These have already been stripped in\n # _strip_link_definitions() so no need to watch for them.\n # - not markup: [...anything else...\n try:\n try:\n start_idx = text.index('[[', curr_pos)\n is_img=False\n except:\n start_idx = text.index('{{', curr_pos)\n is_img=True\n except ValueError:\n break\n\n text_length = len(text)\n\n # Find the matching closing ']]' or '}}'.\n bracket_depth = 0\n for p in range(start_idx+1, min(start_idx+MAX_LINK_TEXT_SENTINEL,\n text_length)):\n ch = text[p:p+2]\n if ch in [']]', '}}']:\n bracket_depth -= 1\n if bracket_depth < 0:\n break\n elif ch in ['[[', '{{']:\n bracket_depth += 1\n else:\n # Closing bracket not found within sentinel length.\n # This isn't markup.\n curr_pos = start_idx + 1\n continue\n link_text = text[start_idx+2:p]\n\n # Now determine what this is by the remainder.\n p += 1\n if p == text_length:\n return text\n\n if is_img:\n\n ########## syntax: link ##############\n result_head = '![%s]' % link_text\n result = '%s(%s)' % (result_head, link_text)\n text = text[:start_idx] + result + text[p+1:]\n ########## syntax: link END ##############\n\n elif start_idx >= anchor_allowed_pos:\n\n if '|' in link_text:\n link_re=re.compile('(.+)\\\\|(.+)',re.X | re.M)\n else:\n link_re=re.compile('(:|\\\\+|\\\\b)(.+)',re.X | re.M)\n\n m1=link_re.match(link_text)\n if m1 == None:\n url = \"\"\n link = link_text\n else:\n url,link=m1.groups()\n\n ########## syntax: link ##############\n result_head = '[%s]' % link\n url=parseLink(link, url, self.file)\n result = '%s(%s)' % (result_head, url)\n text = text[:start_idx] + result + text[p+1:]\n ########## syntax: link END ##############\n else:\n # Anchor not allowed here.\n curr_pos = start_idx + 1\n continue\n\n\n return text\n\n\n _h_re_base = r'''\n ^(\\={1,6}) # \\1 = string of ='s\n [ \\t]%s\n (.+?) # \\2 = Header text\n [ \\t]*\n \\1\n \\n+\n '''\n _h_re = re.compile(_h_re_base % '*', re.X | re.M)\n\n def _h_sub(self, match):\n n = len(match.group(1))\n n = max(1,6-n)\n text=match.group(2)\n return \"%s %s\\n\\n\" % (n*'#', text)\n\n\n def _do_headers(self, text):\n # Setext-style headers:\n # Header 1\n # ========\n #\n # Header 2\n # --------\n\n # atx-style headers:\n # # Header 1\n # ## Header 2\n # ## Header 2 with closing hashes ##\n # ...\n # ###### Header 6\n\n return self._h_re.sub(self._h_sub, text)\n\n _marker_ul_chars = '*+-'\n _marker_any = r'(?:[%s]|\\d+\\.)' % _marker_ul_chars\n _marker_ul = '(?:[%s])' % _marker_ul_chars\n _marker_ol = r'(?:\\d+\\.)'\n\n def _list_sub(self, match):\n lst = match.group(1)\n #lst_type = match.group(3) in self._marker_ul_chars and \"ul\" or \"ol\"\n result = self._process_list_items(lst)\n if self.list_level:\n\n ########## syntax: list item (ordered) ##############\n return \"\\n%s\\n\" % result\n else:\n return \"\\n%s\\n\\n\" % result\n ########## syntax: list item (ordered) END ##############\n\n def _do_lists(self, text):\n # Form HTML ordered (numbered) and unordered (bulleted) lists.\n\n # Iterate over each *non-overlapping* list match.\n pos = 0\n while True:\n # Find the *first* hit for either list style (ul or ol). We\n # match ul and ol separately to avoid adjacent lists of different\n # types running into each other (see issue #16).\n hits = []\n for marker_pat in (self._marker_ul, self._marker_ol):\n less_than_tab = self.tab_width - 1\n whole_list = r'''\n ( # \\1 = whole list\n ( # \\2\n [ ]{0,%d}\n (%s) # \\3 = first list item marker\n [ \\t]+\n (?!\\ *\\3\\ ) # '- - - ...' isn't a list. See 'not_quite_a_list' test case.\n )\n (?:.+?)\n ( # \\4\n \\Z\n |\n \\n{2,}\n (?=\\S)\n (?! # Negative lookahead for another list item marker\n [ \\t]*\n %s[ \\t]+\n )\n )\n )\n ''' % (less_than_tab, marker_pat, marker_pat)\n if self.list_level: # sub-list\n list_re = re.compile(\"^\"+whole_list, re.X | re.M | re.S)\n else:\n list_re = re.compile(r\"(?:(?<=\\n\\n)|\\A\\n?)\"+whole_list,\n re.X | re.M | re.S)\n match = list_re.search(text, pos)\n if match:\n hits.append((match.start(), match))\n if not hits:\n break\n hits.sort()\n match = hits[0][1]\n start, end = match.span()\n middle = self._list_sub(match)\n text = text[:start] + middle + text[end:]\n pos = start + len(middle) # start pos for next attempted match\n\n return text\n\n _list_item_re = re.compile(r'''\n (\\n)? # leading line = \\1\n (^[ \\t]*) # leading whitespace = \\2\n (?P<marker>%s) [ \\t]+ # list marker = \\3\n ((?:.+?) # list item text = \\4\n (\\n{1,2})) # eols = \\5\n (?= \\n* (\\Z | \\2 (?P<next_marker>%s) [ \\t]+))\n ''' % (_marker_any, _marker_any),\n re.M | re.X | re.S)\n\n _last_li_endswith_two_eols = False\n\n def _list_item_sub(self, match):\n item = match.group(4)\n leading_line = match.group(1)\n if leading_line or \"\\n\\n\" in item or self._last_li_endswith_two_eols:\n item = self._run_block_gamut(self._outdent(item))\n else:\n # Recursion for sub-lists:\n item = self._do_lists(self._outdent(item))\n if item.endswith('\\n'):\n item = item[:-1]\n item = self._run_span_gamut(item)\n self._last_li_endswith_two_eols = (len(match.group(5)) == 2)\n\n ########## syntax: list item (unordered) ##############\n bul=match.group(3)\n if bul in self._marker_ul_chars:\n bul=u'*'\n return \"%s %s\\n\" % (bul,item)\n ########## syntax: list item (unordered) END ##############\n\n\n\n def _process_list_items(self, list_str):\n # Process the contents of a single ordered or unordered list,\n # splitting it into individual list items.\n\n # The $g_list_level global keeps track of when we're inside a list.\n # Each time we enter a list, we increment it; when we leave a list,\n # we decrement. If it's zero, we're not in a list anymore.\n #\n # We do this because when we're not inside a list, we want to treat\n # something like this:\n #\n # I recommend upgrading to version\n # 8. Oops, now this line is treated\n # as a sub-list.\n #\n # As a single paragraph, despite the fact that the second line starts\n # with a digit-period-space sequence.\n #\n # Whereas when we're inside a list (or sub-list), that line will be\n # treated as the start of a sub-list. What a kludge, huh? This is\n # an aspect of Markdown's syntax that's hard to parse perfectly\n # without resorting to mind-reading. Perhaps the solution is to\n # change the syntax rules such that sub-lists must start with a\n # starting cardinal number; e.g. \"1.\" or \"a.\".\n self.list_level += 1\n self._last_li_endswith_two_eols = False\n list_str = list_str.rstrip('\\n') + '\\n'\n list_str = self._list_item_re.sub(self._list_item_sub, list_str)\n self.list_level -= 1\n return list_str\n\n\n\n def _code_block_sub(self, match, is_fenced_code_block=False):\n if is_fenced_code_block:\n codeblock = match.group(2)\n codeblock = codeblock[:-1] # drop one trailing newline\n else:\n codeblock = match.group(1)\n codeblock = self._outdent(codeblock)\n codeblock = self._detab(codeblock)\n codeblock = codeblock.lstrip('\\n') # trim leading newlines\n codeblock = codeblock.rstrip() # trim trailing whitespace\n\n return \"\\n\\n```%s\\n```\\n\\n\" % codeblock\n\n\n\n\n def _do_code_blocks(self, text):\n return text\n\n _fenced_code_block_re = re.compile(r'''\n (?:\\n\\n|\\A\\n?)\n ^```([\\w+-]+)?[ \\t]*\\n # opening fence, $1 = optional lang\n (.*?) # $2 = code block content\n ^```[ \\t]*\\n # closing fence\n ''', re.M | re.X | re.S)\n\n def _fenced_code_block_sub(self, match):\n return self._code_block_sub(match, is_fenced_code_block=True);\n\n def _do_fenced_code_blocks(self, text):\n \"\"\"Process ```-fenced unindented code blocks ('fenced-code-blocks' extra).\"\"\"\n return self._fenced_code_block_re.sub(self._fenced_code_block_sub, text)\n\n # Rules for a code span:\n # - backslash escapes are not interpreted in a code span\n # - to include one or or a run of more backticks the delimiters must\n # be a longer run of backticks\n # - cannot start or end a code span with a backtick; pad with a\n # space and that space will be removed in the emitted HTML\n # See `test/tm-cases/escapes.text` for a number of edge-case\n # examples.\n _code_span_re = re.compile(r'''\n (?<!\\\\)\n (`+) # \\1 = Opening run of `\n (?!`) # See Note A test/tm-cases/escapes.text\n (.+?) # \\2 = The code block\n (?<!`)\n \\1 # Matching closer\n (?!`)\n ''', re.X | re.S)\n\n '''\n def _code_span_sub(self, match):\n c = match.group(2).strip(\" \\t\")\n c = self._encode_code(c)\n return \"<code>%s</code>\" % c\n '''\n\n def _code_span_sub(self, match):\n c = match.group(2).strip(\" \\t\")\n #c = self._encode_code(c)\n\n ########## syntax: code block ##############\n #return \"<code>%s</code>\" % c\n codesym=match.group(1)\n if codesym=='```':\n return \"%s\\n%s\\n%s\" % (codesym,c,codesym)\n elif codesym=='`':\n return \"%s%s%s\" % (codesym,c,codesym)\n ########## syntax: code block END ##############\n\n def _do_code_spans(self, text):\n # * Backtick quotes are used for <code></code> spans.\n #\n # * You can use multiple backticks as the delimiters if you want to\n # include literal backticks in the code span. So, this input:\n #\n # Just type ``foo `bar` baz`` at the prompt.\n #\n # Will translate to:\n #\n # <p>Just type <code>foo `bar` baz</code> at the prompt.</p>\n #\n # There's no arbitrary limit to the number of backticks you\n # can use as delimters. If you need three consecutive backticks\n # in your code, use four for delimiters, etc.\n #\n # * You can use spaces to get literal backticks at the edges:\n #\n # ... type `` `bar` `` ...\n #\n # Turns to:\n #\n # ... type <code>`bar`</code> ...\n return self._code_span_re.sub(self._code_span_sub, text)\n\n def _encode_code(self, text):\n \"\"\"Encode/escape certain characters inside Markdown code runs.\n The point is that in code, these characters are literals,\n and lose their special Markdown meanings.\n \"\"\"\n replacements = [\n # Encode all ampersands; HTML entities are not\n # entities within a Markdown code span.\n ('&', '&'),\n # Do the angle bracket song and dance:\n ('<', '<'),\n ('>', '>'),\n ]\n for before, after in replacements:\n text = text.replace(before, after)\n hashed = _hash_text(text)\n self._escape_table[text] = hashed\n return hashed\n\n _strike_re = re.compile(r\"~~(?=\\S)(.+?)(?<=\\S)~~\", re.S)\n def _do_strike(self, text):\n text = self._strike_re.sub(r\"~~\\1~~\", text)\n return text\n\n _strong_re = re.compile(r\"(\\*\\*|__)(?=\\S)(.+?[*_]*)(?<=\\S)\\1\", re.S)\n _em_re = re.compile(r\"(//)(?=\\S)(.+?)(?<=\\S)\\1\", re.S)\n\n\n def _do_italics_and_bold(self, text):\n # <strong> must go first:\n ########## syntax: italic and bold ##############\n text = self._strong_re.sub(r\"**\\2**\", text)\n text = self._em_re.sub(r\"*\\2*\", text)\n ########## syntax: italic and bold END ##############\n return text\n\n\n\n _block_quote_base = r\"\"\"\n ( # Wrap whole match in \\1\n ^'''[ \\t]*\\n # ''' at the start of a line\n (\n (.+\\n)* # subsequent consecutive lines\n \\n* # blanks\n )\n ^'''[ \\t]*\\n\n )\n \"\"\"\n\n _block_quote_re = re.compile(_block_quote_base, re.M | re.X)\n _bq_one_level_re = re.compile('^[ \\t]*>[ \\t]?', re.M);\n _bq_one_level_re_spoiler = re.compile('^[ \\t]*>[ \\t]*?![ \\t]?', re.M);\n _bq_all_lines_spoilers = re.compile(r'\\A(?:^[ \\t]*>[ \\t]*?!.*[\\n\\r]*)+\\Z', re.M)\n _html_pre_block_re = re.compile(r'(\\s*.+?)', re.S)\n def _dedent_two_spaces_sub(self, match):\n return re.sub(r'(?m)^ ', '', match.group(1))\n\n\n\n def _block_quote_sub(self, match):\n bq = match.group(2)\n\n bq = self._bq_one_level_re.sub('', bq)\n # trim whitespace-only lines\n bq = self._ws_only_line_re.sub('', bq)\n bq = self._run_block_gamut(bq) # recurse\n\n bq = re.sub('(?m)^', ' ', bq)\n # These leading spaces screw with <pre> content, so we need to fix that:\n bq = self._html_pre_block_re.sub(self._dedent_two_spaces_sub, bq)\n\n return '> %s\\n\\n' % bq\n\n\n\n\n\n def _do_block_quotes(self, text):\n if \"'''\" not in text:\n return text\n return self._block_quote_re.sub(self._block_quote_sub, text)\n\n def _form_paragraphs(self, text):\n # Strip leading and trailing lines:\n text = text.strip('\\n')\n\n # Wrap <p> tags.\n grafs = []\n for i, graf in enumerate(re.split(r\"\\n{2,}\", text)):\n graf = self._run_span_gamut(graf)\n grafs.append(graf.lstrip(\" \\t\"))\n\n return \"\\n\\n\".join(grafs)\n\n\n\n\n def _add_footnotes(self, text):\n if self.footnotes:\n footer = [\n '<div class=\"footnotes\">',\n '<hr />'\n '<ol>',\n ]\n for i, id in enumerate(self.footnote_ids):\n if i != 0:\n footer.append('')\n footer.append('<li id=\"fn-%s\">' % id)\n footer.append(self._run_block_gamut(self.footnotes[id]))\n backlink = ('<a href=\"#fnref-%s\" '\n 'class=\"footnoteBackLink\" '\n 'title=\"Jump back to footnote %d in the text.\">'\n '↩</a>' % (id, i+1))\n if footer[-1].endswith(\"</p>\"):\n footer[-1] = footer[-1][:-len(\"</p>\")] \\\n + ' ' + backlink + \"</p>\"\n else:\n footer.append(\"\\n<p>%s</p>\" % backlink)\n footer.append('</li>')\n footer.append('</ol>')\n footer.append('</div>')\n return text + '\\n\\n' + '\\n'.join(footer)\n else:\n return text\n\n\n\n def _outdent(self, text):\n # Remove one level of line-leading tabs or spaces\n return text\n #return self._outdent_re.sub('', text)\n\n\n\n\ndef _dedent(text, tabsize=8, skip_first_line=False):\n \"\"\"_dedent(text, tabsize=8, skip_first_line=False) -> dedented text\n\n \"text\" is the text to dedent.\n \"tabsize\" is the tab width to use for indent width calculations.\n \"skip_first_line\" is a boolean indicating if the first line should\n be skipped for calculating the indent width and for dedenting.\n This is sometimes useful for docstrings and similar.\n\n textwrap.dedent(s), but don't expand tabs to spaces\n \"\"\"\n lines = text.splitlines(1)\n _dedentlines(lines, tabsize=tabsize, skip_first_line=skip_first_line)\n return ''.join(lines)\n\ndef _xml_escape_attr(attr, skip_single_quote=True):\n \"\"\"Escape the given string for use in an HTML/XML tag attribute.\n\n By default this doesn't bother with escaping `'` to `'`, presuming that\n the tag attribute is surrounded by double quotes.\n \"\"\"\n escaped = (attr\n .replace('&', '&')\n .replace('\"', '"')\n .replace('<', '<')\n .replace('>', '>'))\n if not skip_single_quote:\n escaped = escaped.replace(\"'\", \"'\")\n return escaped\n\n\ndef _dedentlines(lines, tabsize=8, skip_first_line=False):\n \"\"\"_dedentlines(lines, tabsize=8, skip_first_line=False) -> dedented lines\n\n \"lines\" is a list of lines to dedent.\n \"tabsize\" is the tab width to use for indent width calculations.\n \"skip_first_line\" is a boolean indicating if the first line should\n be skipped for calculating the indent width and for dedenting.\n This is sometimes useful for docstrings and similar.\n\n Same as dedent() except operates on a sequence of lines. Note: the\n lines list is modified **in-place**.\n \"\"\"\n DEBUG = False\n if DEBUG:\n print(\"dedent: dedent(..., tabsize=%d, skip_first_line=%r)\"\\\n % (tabsize, skip_first_line))\n margin = None\n for i, line in enumerate(lines):\n if i == 0 and skip_first_line: continue\n indent = 0\n for ch in line:\n if ch == ' ':\n indent += 1\n elif ch == '\\t':\n indent += tabsize - (indent % tabsize)\n elif ch in '\\r\\n':\n continue # skip all-whitespace lines\n else:\n break\n else:\n continue # skip all-whitespace lines\n if DEBUG: print(\"dedent: indent=%d: %r\" % (indent, line))\n if margin is None:\n margin = indent\n else:\n margin = min(margin, indent)\n if DEBUG: print(\"dedent: margin=%r\" % margin)\n\n if margin is not None and margin > 0:\n for i, line in enumerate(lines):\n if i == 0 and skip_first_line: continue\n removed = 0\n for j, ch in enumerate(line):\n if ch == ' ':\n removed += 1\n elif ch == '\\t':\n removed += tabsize - (removed % tabsize)\n elif ch in '\\r\\n':\n if DEBUG: print(\"dedent: %r: EOL -> strip up to EOL\" % line)\n lines[i] = lines[i][j:]\n break\n else:\n raise ValueError(\"unexpected non-whitespace char %r in \"\n \"line %r while removing %d-space margin\"\n % (ch, line, margin))\n if DEBUG:\n print(\"dedent: %r: %r -> removed %d/%d\"\\\n % (line, ch, removed, margin))\n if removed == margin:\n lines[i] = lines[i][j+1:]\n break\n elif removed > margin:\n lines[i] = ' '*(removed-margin) + lines[i][j+1:]\n break\n else:\n if removed:\n lines[i] = lines[i][removed:]\n return lines\n\n\n\n\n\n\n\n\ndef main(filein,fileout,verbose=True):\n\n text=tools.readFile(filein,verbose)\n if verbose:\n print('# <markdown2zim>: Converting to zim...')\n newtext=Zim2Markdown(file=filein).convert(text)\n tools.saveFile(fileout,newtext,verbose)\n\n return\n\n\n\n#-----------------------Main-----------------------\nif __name__=='__main__':\n\n\n parser=argparse.ArgumentParser(description=\\\n 'Convert zim wiki note files to markdown syntax.')\n\n parser.add_argument('file',type=str,\\\n help='Input zim note text file.')\n parser.add_argument('-o','--out',type=str,\\\n help='Output file name.')\n parser.add_argument('-v','--verbose',action='store_true',\\\n default=True)\n\n try:\n args=parser.parse_args()\n except:\n sys.exit(1)\n\n FILEIN=os.path.abspath(args.file)\n if not args.out:\n FILEOUT='%s_%s.md' %(os.path.splitext(args.file)[0], 'zim2md')\n else:\n FILEOUT=args.out\n FILEOUT=os.path.abspath(FILEOUT)\n\n main(FILEIN,FILEOUT,args.verbose)\n\n\n","sub_path":"zim2markdown.py","file_name":"zim2markdown.py","file_ext":"py","file_size_in_byte":37891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"82233053","text":"# Copyright 2014 - Rackspace\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nMistral DSL and Heat Template parsing and representation routines.\n\nThis code does not import the original YAML representations of the Mistral DSL\nand Heat Templates as the data may be in memory instead of file. PyYAML is a\ngood library to load the YAML and translate into a Python dictionary with code\nlike:\n\nimport yaml\n\nwith open(\"mistral_dsl.yaml\", \"r\") as fptr\n data = yaml.safe_load(fptr)\n\nImportant note:\nThis code expects that the loading code performs some basic YAML validation\n* Mistral DSLs must include a \"Workflow\" section with a \"tasks\" subsection\n* Mistral DSLs must have one task with no on-success (last task)\n* Heat Templates must include a \"requirements\" section\n\"\"\"\n\n\ndef get_mistral_tasks(data, start_task_name=None):\n \"\"\"Returns an ordered Mistral task list from a DSL.\"\"\"\n task_list = []\n task_dict = data[\"Workflow\"][\"tasks\"]\n for key, task in task_dict.items():\n on_success = task.get(\"on-finish\", task.get(\"on-success\"))\n on_error = task.get(\"on-finish\", task.get(\"on-error\"))\n task_list.append([key, on_success, on_error])\n curr_task_name = None\n sorted_task_list = []\n no_suc_list = ([[name, on_suc, on_err] for (name, on_suc, on_err) in\n task_list if on_suc is None])\n sorted_task_list.insert(0, no_suc_list[0])\n curr_task_name = no_suc_list[0][0]\n for count in range(len(task_list) - 1):\n for task in task_list:\n task_name, on_success, on_error = task\n if on_success == curr_task_name:\n curr_task_name = task_name\n sorted_task_list.insert(0, task)\n break\n if start_task_name:\n if start_task_name == task_name:\n break\n return sorted_task_list\n\n\ndef create_svg_mistral_tasks(task_list, radius=45):\n \"\"\"Create an SVG UI diagram of Mistral task flow.\n\n This takes the output of get_mistral_tasks() and generates an SVG-based\n graphical diagram of the ordered Mistral tasks. The code automatically\n scales the SVG based on the circle radius value. Note that SVG circles\n don't scale radius by percentages very well which is why this is still\n pixel math. The circle radius is the diagonal length of the viewport\n which is not very useful in this case.\n \"\"\"\n indent = radius * 1.1\n diameter = radius * 2\n num_tasks = len(task_list)\n if num_tasks < 1:\n return \"[No Tasks Found]\"\n svg_output = (\"<svg height=\\\"%d\\\" width=\\\"%d\\\">\\n\" %\n ((diameter * 1.10), ((num_tasks-1) * diameter * 1.3) +\n indent * 2))\n svg_output += (\" <line x1=\\\"%d\\\" y1=\\\"50%%\\\" x2=\\\"%d\\\" y2=\\\"50%%\\\" style=\"\n \"\\\"stroke:rgb(0,0,0);stroke-width:3\\\"/>\\n\" %\n (indent, ((num_tasks-1) * diameter * 1.2) + indent))\n svg_output += (\" <g stroke=\\\"black\\\" stroke-width=\\\"3\\\" fill=\"\n \"\\\"lightgrey\\\">\\n\")\n for counter in range(num_tasks):\n svg_output += (\" <circle cx=\\\"%d\\\" cy=\\\"50%%\\\" r=\\\"%d\\\"/>\\n\" %\n ((counter * diameter * 1.2 + indent), radius))\n svg_output += \" </g>\\n\"\n svg_output += \" <g style=\\\"text-anchor: middle; font-size: 13px\\\">\\n\"\n for counter in range(num_tasks):\n svg_output += (\" <text x=\\\"%d\\\" y=\\\"55%%\\\">%s</text>\\n\" %\n ((counter * diameter * 1.2 + indent),\n task_list[counter][0]))\n svg_output += \" </g>\\n\"\n svg_output += \"</svg>\\n\"\n return svg_output\n\n\ndef get_mistral_required_input(data, start_task_name=None):\n \"\"\"Returns required Mistral DSL user input field information.\n\n Note that this code ignores Mistral DSL values that are enumerated in the\n ignore_list list below which are under the \"parameters:\" label. The\n recommendation is to not nest sections under a \"parameters:\" label and\n just list name/value pairs in the parameters section.\n \"\"\"\n input_dict = {}\n task_list = get_mistral_tasks(data, start_task_name)\n task_key_list = [item[0] for item in task_list]\n task_dict = data[\"Workflow\"][\"tasks\"]\n ignore_list = [\"params\", \"settings\", \"arguments\"]\n publish_list = []\n for task in task_key_list:\n param_list = task_dict[task].get(\"parameters\", [])\n publish_list.extend(task_dict[task].get(\"publish\", []))\n for param in param_list:\n if param not in ignore_list and param not in publish_list:\n if param not in input_dict:\n input_dict[param] = [task]\n else:\n input_dict[param].append(task)\n return input_dict\n\n\ndef get_heat_required_input(data):\n \"\"\"Returns Heat required user input fields.\"\"\"\n heat_params = []\n heat_param_dict = data[\"parameters\"]\n for key, heat_param in heat_param_dict.items():\n heat_params.append([key,\n heat_param.get(\"type\"),\n heat_param.get(\"default\"),\n heat_param.get(\"description\")])\n return sorted(heat_params)\n\n\nif __name__ == \"__main__\":\n # This code is left for example and basic testing purposes; it is not\n # intended for production use.\n\n import yaml\n\n with open(\"dsl.yaml\", \"r\") as FPTR:\n DATA = yaml.safe_load(FPTR)\n print(\"\\nMistral Task workflow:\")\n RET_DICT = get_mistral_tasks(DATA)\n for VAL in RET_DICT:\n print(\"%s - success: %s, error: %s\" % (VAL[0], VAL[1], VAL[2]))\n\n SVG_TEXT = create_svg_mistral_tasks(RET_DICT, 45)\n print(\"\\nSVG task output:\\n\" + SVG_TEXT)\n\n # Mistral required input\n print(\"\\nMistral required inputs:\")\n RET_DICT = get_mistral_required_input(DATA)\n for KEY, VAL in RET_DICT.items():\n print(KEY, \"\", VAL)\n\n # Heat required input\n print(\"\\nHeat required inputs:\")\n with open(\"hot.yaml\", \"r\") as FPTR:\n DATA = yaml.safe_load(FPTR)\n RET_DICT = get_heat_required_input(DATA)\n for VAL in RET_DICT:\n print(\"%s - %s, %s, %s\" % (VAL[0], VAL[1], VAL[2], VAL[3]))\n","sub_path":"solumdashboard/common/workflow_parsers.py","file_name":"workflow_parsers.py","file_ext":"py","file_size_in_byte":6587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"512832040","text":"#!/usr/bin/env python\n\nwith open('input/day_1') as infile:\n data = infile.read()\n\nfloor = 0\nfor c in data:\n if c == '(':\n floor += 1\n elif c == ')':\n floor -= 1\n\nprint(floor)\n","sub_path":"2015/dec1a.py","file_name":"dec1a.py","file_ext":"py","file_size_in_byte":198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"600224439","text":"#!/usr/bin/python3\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom scipy import linspace, polyval, polyfit, sqrt, stats, randn\nsns.set_palette(\"deep\", desat=.6)\nsns.set_context(rc={\"figure.figsize\": (8, 7)})\ndef head(data,num):\n i = 0 \n for each in data:\n print( each)\n if i == num:\n return()\n i += 1\ndef get_plot(data,ax,c,l):\n\tml=data[:,0]\n\tbin_num = (max(ml)-min(ml)) / 0.01\n\tax.hist(ml, bins=bin_num, color=c, alpha=0.3, label=l)\n\t#ax.plot(ml,xr)\n\tax.legend()\nf, (ax1, ax2, ax3) = plt.subplots(3, sharex=True, sharey=True)\nfile_CG = 'S_total.CG.dict.genemethylv.txt'\nfile_CHG = 'S_total.CHG.dict.genemethylv.txt'\nfile_CHH = 'S_total.CHH.dict.genemethylv.txt'\ndata_CG = np.loadtxt(file_CG,skiprows=1,usecols = (3,4))\ndata_CHG = np.loadtxt(file_CHG,skiprows=1,usecols = (3,4))\ndata_CHH = np.loadtxt(file_CHH,skiprows=1,usecols = (3,4))\nplt.ylim(0,1000)\nplt.xlim(0,1)\nget_plot(data_CG,ax1,'r','CG')\nget_plot(data_CHG,ax2,'b','CHG')\nget_plot(data_CHH,ax3,'g','CHH')\n\n#f.set_size_inches(18.5,10.5)\nplt.savefig('mungbean_methyl_sup_fig_7.png',dpi=300)\nplt.show()\n","sub_path":"py/sunhwa/4_gene_met_plot_hist.py","file_name":"4_gene_met_plot_hist.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"623050739","text":"#\n# Explicit model for potential drop across a lithium metal electrode\n#\nfrom .base_ohm import BaseModel\n\n\nclass LithiumMetalExplicit(BaseModel):\n \"\"\"Explicit model for potential drop across a lithium metal electrode.\n\n Parameters\n ----------\n param : parameter class\n The parameters to use for this submodel\n options : dict, optional\n A dictionary of options to be passed to the model.\n\n **Extends:** :class:`pybamm.electrode.ohm.BaseModel`\n \"\"\"\n\n def __init__(self, param, options=None):\n super().__init__(param, \"Negative\", options=options)\n\n def get_coupled_variables(self, variables):\n param = self.param\n\n i_boundary_cc = variables[\"Current collector current density\"]\n T_n = variables[\"Negative current collector temperature\"]\n l_n = param.l_n\n delta_phi_s = i_boundary_cc * l_n / param.sigma_n(T_n)\n delta_phi_s_dim = param.potential_scale * delta_phi_s\n\n variables.update(\n {\n \"Negative electrode potential drop\": delta_phi_s,\n \"Negative electrode potential drop [V]\": delta_phi_s_dim,\n \"X-averaged negative electrode ohmic losses\": delta_phi_s / 2,\n \"X-averaged negative electrode ohmic losses [V]\": delta_phi_s_dim / 2,\n }\n )\n\n return variables\n\n def set_boundary_conditions(self, variables):\n pass\n","sub_path":"pybamm/models/submodels/electrode/ohm/li_metal_explicit.py","file_name":"li_metal_explicit.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"63306706","text":"from player import *\nfrom game import *\n\n\nGAME_COUNT = 1000\n\n\nhistorian = HistoricalPlayer(1)\nrandom_player = RandomPlayer()\nsequential_player = SequentialPlayer()\nfrequency_player = FrequencyPlayer()\ntournament = SeveralGames(historian, frequency_player, GAME_COUNT)\n\ntournament.play_tournament()","sub_path":"rock_paper_scissors/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"132636008","text":"\nimport selenium, pandas\nimport pandas as pd\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import WebDriverWait\nimport time\nimport matplotlib.pyplot as plt\nimport os\nfrom tkinter import *\nfrom PIL import ImageTk, Image\nfrom AnimatedGif import *\nimport datetime\n\n\n\n\n\ndef scrapNmatch(name):\n\n driver = webdriver.Chrome('script/chromedriver')\n df=[]\n driver.get(\"https://ecdms.energy.ca.gov/elecbycounty.aspx\")\n\n country=driver.find_elements_by_tag_name(\"option\")\n for k in country:\n if k.text==name:\n k.click()\n\n\n #country=driver.find_element_by_xpath(\"//option[@value=k]\")\n #country.click()\n sector=driver.find_element_by_xpath(\"//img[@alt='Select All Sectors']\")\n sector.click()\n\n year=driver.find_element_by_xpath(\"//img[@alt='Select All Years']\")\n year.click()\n\n report=driver.find_element_by_xpath(\"//input[@value='Create Report']\")\n report.click()\n\n csv=driver.find_element_by_xpath(\"//input[@value='Export to CSV']\")\n csv.click()\n\n time.sleep(2)\n\n df = pd.read_csv(r\"C:\\Users\\RAMD\\Downloads\\ElectricityByCounty.csv\")\n del df['County']\n del df['Total Usage']\n df2 = df.T\n export_csv = df2.to_csv(r'C:\\Users\\export_dataframedf2.csv', index=True, header=None)\n df4 = pd.read_csv(r'C:\\Users\\export_dataframedf2.csv')\n df4 = df4.rename(columns={'Sector': 'Year'})\n fig = plt.figure()\n plt.plot(df4['Year'], df4['Non-Residential'], label='Non-Residential')\n plt.plot(df4['Year'], df4['Residential'], label='Residential')\n plt.plot(df4['Year'], df4['Total'], label='Total')\n plt.legend()\n plt.xlabel('Year', fontsize=16)\n plt.ylabel(' Millions of kWh (GWh)', fontsize=16)\n plt.show()\n\n time.sleep(2)\n\n if os.path.exists(r\"C:\\Users\\ElectricityByCounty.csv\"):\n os.remove(r\"C:\\Users\\ElectricityByCounty.csv\")\n","sub_path":"usfile.py","file_name":"usfile.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"45172567","text":"import os\nimport shutil\nimport json\n\nimport paraFilehandle\n\n\ndef get_project_name(project_dir):\n project_name = os.path.basename(project_dir)\n return project_name\n\n\ndef get_para_dir(project_dir):\n project_name = get_project_name(project_dir)\n para_dir = project_dir + \"/\" + project_name + \".para\"\n return para_dir\n\n\ndef get_vehicle_PlateNumber(project_dir):\n vehicle_plate_number = get_project_name(project_dir).split(\"_\")[3]\n return vehicle_plate_number\n\n\n# pointcloudDir\n# /media/yanzhe/SHCJ01/1205/20201205115519_WYT_SHANGHAI_AFA1119/03_LiDAR_RAW/01_POINTCLOUD/LiDAR_2\ndef get_pointcloudDir(project_dir, lidar_name):\n pointcloudDir = project_dir + \"/03_LiDAR_RAW/01_POINTCLOUD/LiDAR_1\"\n return pointcloudDir\n\n\n# trajectoryFile\n# /media/yanzhe/SHCJ01/1205/20201205115519_WYT_SHANGHAI_AFA1119/06_INS_PROC/20201205115519_WYT_SHANGHAI_AFA1119_Proc.nav\ndef get_trajectoryFile(project_dir):\n trajectoryFile = project_dir + \\\n \"/06_INS_PROC/\" + get_project_name(project_dir) + \".nav\"\n return trajectoryFile\n # print(\"trajectoryFile:\" + trajectoryFile)\n\n\ndef get_all_scanfolder_name(project_dir):\n # todo.............\n scan_paths = os.listdir(project_dir + \"/03_LiDAR_RAW/01_POINTCLOUD\")\n\n return scan_paths\n\n\ndef get_sigle_scanfolder_path(project_dir, lidar_name):\n # todo.............\n\n # scan_paths = {}\n for scan_folder in os.listdir(project_dir + \"/03_LiDAR_RAW/01_POINTCLOUD\"):\n if scan_folder == lidar_name:\n return project_dir + \"/03_LiDAR_RAW/01_POINTCLOUD/\" + scan_folder\n\n\ndef create_11_pointcloud_dir(project_dir, lidar_name):\n\n POINTCLOUD_dir = project_dir + \"/11_POINTCLOUD/\"\n if os.path.exists(POINTCLOUD_dir) is False:\n os.mkdir(POINTCLOUD_dir)\n\n outputDir = project_dir + \"/11_POINTCLOUD/\" + lidar_name + \"_POINTCLOUD\"\n if os.path.exists(outputDir):\n os.removedirs(outputDir)\n\n # os.mkdir(project_dir + \"/11_POINTCLOUD/\" + lidar_name)\n os.mkdir(outputDir)\n\n return outputDir\n\n\ndef get_lidar_type(project_dir, lidar_name):\n # 1#CAR and LiDAR_1\n if str(project_dir).find(\"DSX116\") != -1 and str(lidar_name).find(\n \"1\") != -1:\n return str(128)\n # 1#CAR and not LiDAR_1\n elif str(project_dir).find(\"DSX116\") != -1 and str(lidar_name).find(\n \"1\") == -1:\n return 32\n\n # not 1#CAR and LiDAR_1\n elif str(project_dir).find(\n \"DSX116\") == -1 and str(lidar_name).find(\"1\") != -1:\n return 64\n\n # not 1# car and not LiDAR_1\n elif str(project_dir).find(\"DSX116\") == -1 and str(lidar_name).find(\n \"1\") == -1:\n return 32\n\n # def get_outputDir(project_dir, lidar_name):\n # return project_dir + \"/11_POINTCLOUD/\"+lidar_name\n\n\ndef createProcNavFile(project_dir):\n ProcNavFile = project_dir + \"/06_INS_PROC/\" + get_project_name(\n project_dir) + \"_Proc.nav\"\n\n if os.path.exists(ProcNavFile):\n os.remove(ProcNavFile)\n\n # cloudParaFile = open(ProcNavFile, \"w+\")\n # cloudParaFile.writelines(\"1tesdfsdst....test\")\n # cloudParaFile.close\n\n shutil.copy(get_trajectoryFile(project_dir), ProcNavFile)\n\n return ProcNavFile\n\n\ndef createCloudParaFile(project_dir):\n cloudParaPath = project_dir + \"/\" + get_project_name(\n project_dir) + \"_cloud.para\"\n\n if os.path.exists(cloudParaPath):\n os.remove(cloudParaPath)\n\n vehiclePara = paraFilehandle.getVehiclePara(project_dir)\n\n cloudParaDictionary = json.dumps(vehiclePara)\n\n cloudParaFile = open(cloudParaPath, \"w+\")\n cloudParaFile.writelines(cloudParaDictionary)\n cloudParaFile.close\n\n return cloudParaPath\n\n\n# TEST...........\n# project_dir = \"/home/slam/WM-20201006/learn_python_202012/point_cloud_join/2020120511551119_WYT_SHANGHAI_AFA1119\"\n# # create_11_pointcloud_dir(project_dir, \"LiDAR_1\")\n\n# print(get_sigle_scanfolder_path(project_dir, \"LiDAR_2\"))\n# print(get_lidar_type(project_dir, \"LiDAR_3\"))\n# print(createProcNavFile(project_dir))\n","sub_path":"learn_python_202012/datamapping_pointcloud/projectPathHandle.py","file_name":"projectPathHandle.py","file_ext":"py","file_size_in_byte":3964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"351150686","text":"from django.http import *\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.shortcuts import render_to_response\nfrom django.newforms import *\nfrom django import oldforms\nfrom django.conf import settings\nfrom django.template import RequestContext\n\nfrom datetime import date, timedelta\nimport datetime\n\nfrom tic_tac_toe.board.models import *\nfrom tic_tac_toe.settings import *\nfrom tic_tac_toe.board.forms import *\n\ndef index(request):\n \n if request.POST:\n g=GameForm(request.POST)\n g.is_bound\n\n #validate the blog, save, and redirect to the blog entry\n if g.is_valid():\n new_game = Game()\n \n if 'block1' in request.POST:\n new_game.block1 = request.POST['block1']\n if new_game.block1 == \"X\":\n new_game.block3 = \"O\"\n \n if 'block2' in request.POST:\n new_game.block2 = request.POST['block2']\n if new_game.block2 == \"X\":\n new_game.block1 = \"O\"\n \n if 'block3' in request.POST:\n new_game.block3 = request.POST['block3']\n if new_game.block3 == \"X\":\n new_game.block1 = \"O\"\n \n if 'block4' in request.POST:\n new_game.block4 = request.POST['block4']\n if new_game.block4 == \"X\":\n new_game.block1 = \"O\"\n \n if 'block5' in request.POST:\n new_game.block5 = request.POST['block5']\n if new_game.block5 == \"X\":\n new_game.block1 = \"O\"\n \n if 'block6' in request.POST:\n new_game.block6 = request.POST['block6']\n if new_game.block6 == \"X\":\n new_game.block1 = \"O\"\n \n if 'block7' in request.POST:\n new_game.block7 = request.POST['block7']\n if new_game.block7 == \"X\":\n new_game.block1 = \"O\"\n \n if 'block8' in request.POST:\n new_game.block8 = request.POST['block8']\n if new_game.block8 == \"X\":\n new_game.block1 = \"O\"\n \n if 'block9' in request.POST:\n new_game.block9 = request.POST['block9']\n if new_game.block9 == \"X\":\n new_game.block1 = \"O\" \n \n new_game.save() \n \n return HttpResponseRedirect(\"/game/\")\n else:\n errors = g.errors\n return render_to_response('errors.html',\n {\n \n })\n else:\n g=GameForm()\n \n \n return render_to_response('index.html',\n {\n \n }) \n \ndef game(request):\n \n try:\n curr_game = Game.objects.filter().order_by('-id')[:1].get()\n except ObjectDoesNotExist:\n curr_game = {}\n \n GameInstanceForm = form_for_instance(curr_game, fields=GAME_FIELDS)\n \n if request.POST: \n g=GameInstanceForm(request.POST)\n \n if g.is_valid(): \n \n if 'block2' in request.POST:\n curr_game.block2 = request.POST['block2']\n if curr_game.block9 == None:\n curr_game.block9 = \"O\"\n \n if 'block4' in request.POST:\n curr_game.block4 = request.POST['block4']\n \n if curr_game.block5:\n curr_game.block6 = \"O\"\n \n if curr_game.block1:\n if curr_game.block9:\n curr_game.block6 = \"O\"\n else: \n curr_game.block7 = \"O\"\n \n if 'block5' in request.POST:\n curr_game.block5 = request.POST['block5']\n \n if curr_game.block9:\n curr_game.block8 = \"O\"\n elif curr_game.block4:\n curr_game.block6 = \"O\" \n \n if curr_game.block1 == \"X\":\n curr_game.block9 = \"O\"\n \n if curr_game.block3 == \"X\":\n curr_game.block7 = \"O\"\n \n \n if 'block6' in request.POST:\n curr_game.block6 = request.POST['block6']\n if curr_game.block7 == None:\n curr_game.block7 = \"O\"\n \n if 'block7' in request.POST:\n curr_game.block7 = request.POST['block7']\n \n if curr_game.block1 == \"X\":\n curr_game.block4 = \"O\" \n \n if curr_game.block3:\n curr_game.block5 = \"O\" \n \n if 'block8' in request.POST:\n curr_game.block8 = request.POST['block8']\n \n if curr_game.block9:\n if curr_game.block7:\n curr_game.block8 = \"O\" \n else: \n curr_game.block5 = \"O\"\n \n if curr_game.block7 == \"X\":\n if curr_game.block9 == \"X\":\n curr_game.block8 = \"X\"\n \n \n if 'block9' in request.POST:\n curr_game.block9 = request.POST['block9']\n \n if curr_game.block3:\n if curr_game.block7:\n curr_game.block8 = \"O\"\n \n if curr_game.block1:\n curr_game.block5 = \"O\"\n \n \n curr_game.save()\n return HttpResponseRedirect(\"/game/\") \n \n else:\n g = GameInstanceForm()\n \n \n return render_to_response('game.html',\n {\n 'curr_game':curr_game,\n }) ","sub_path":"tic_tac_toe/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"192720158","text":"# -*- coding: utf-8 -*-\r\nimport os\r\nfrom datetime import datetime, timedelta\r\n\r\nfrom airflow import DAG\r\nfrom airflow.models import Variable\r\nfrom airflow.operators.bash_operator import BashOperator\r\nfrom airflow.operators.dummy_operator import DummyOperator\r\n\r\nu\"\"\"\r\nAirflow script for calc_08\r\n\"\"\"\r\n\r\nALERT_MAILS = Variable.get(\"gv_ic_admin_lst\")\r\nDAG_NAME = str(os.path.basename(__file__).split('.')[0])\r\nOWNER = 'User Airflow'\r\nDEPENDS_ON_PAST = True\r\nEMAIL_ON_FAILURE = True\r\nEMAIL_ON_RETRY = False\r\nRETRIES = int(Variable.get('gv_dag_retries'))\r\nPOOL = 'data_pool'\r\nMAIN_VAR_NAME = 'gv_' + DAG_NAME\r\n\r\nSRV_LIST = Variable.get('gv_psg_kafka_srv_list')\r\nQUEUE_NAME = Variable.get('gv_psg_kafka_queue_name')\r\nPARTITIONS = Variable.get('gv_psg_kafka_partitions')\r\nLOADDTTM=str(datetime.now()).replace(\" \",\"_\")\r\nWAIT_HRS = 1\r\n\r\nstart_dt = datetime(2018, 11, 15)\r\n\r\n# setting default arguments of dag\r\ndefault_args = {\r\n 'owner': OWNER,\r\n 'depends_on_past': DEPENDS_ON_PAST,\r\n 'start_date': start_dt,\r\n 'email': ALERT_MAILS,\r\n 'email_on_failure': EMAIL_ON_FAILURE,\r\n 'email_on_retry': EMAIL_ON_RETRY,\r\n 'retries': RETRIES,\r\n 'pool': POOL\r\n}\r\n\r\n# Creating DAG with parameters\r\ndag = DAG(DAG_NAME, default_args=default_args, schedule_interval=\"0 */4 * * *\")\r\ndag.doc_md = __doc__\r\n\r\ndag_start = DummyOperator(\r\n task_id='dag_start',\r\n dag=dag\r\n)\r\n\r\ndag_end = DummyOperator(\r\n task_id='dag_end',\r\n dag=dag\r\n)\r\n\r\nalgo_bash_cmd = \"\"\"\r\nkinit airflow/airflow@HOME.LOCAL -kt /opt/airflow/airflow_home/kt/airflow.keytab\r\nspark-submit --master yarn \\\r\n--num-executors {{ params.partitions }} \\\r\n--executor-cores 3 \\\r\n--executor-memory 6G \\\r\n--driver-cores 5 \\\r\n--driver-memory 10G \\\r\n--conf 'spark.driver.extraJavaOptions=-Djava.security.auth.login.config={{ params.home }}/kt/kafka_client.conf' \\\r\n--conf 'spark.executor.extraJavaOptions=-Djava.security.auth.login.config={{ params.home }}/kt/kafka_client.conf' \\\r\n--packages org.apache.spark:spark-sql-kafka-0-10_2.11:2.1.1 \\\r\n--jars \"\"\"+\"/opt/airflow/airflow-home/utils/HiveHomeUDF-0.0.1.jar\"+\"\"\" \\\r\n{{ params.home }}/dags/pyspark/prod_data/calc_08.py {{ params.srv_list }} {{ params.queue_name }} {{ params.partitions }} {{ params.loaddttm }}\r\n\"\"\"\r\n\r\nalgo_bash_load = BashOperator(\r\n task_id='prod_data_algo_calc_08',\r\n bash_command=algo_bash_cmd,\r\n execution_timeout=timedelta(hours=WAIT_HRS),\r\n params={\r\n 'home': '/opt/airflow/airflow_home',\r\n 'srv_list': SRV_LIST,\r\n 'queue_name': QUEUE_NAME,\r\n 'partitions': PARTITIONS,\r\n 'loaddttm': LOADDTTM\r\n },\r\n wait_for_downstream=True,\r\n dag=dag\r\n)\r\n\r\ndag_start.set_downstream(algo_bash_load)\r\nalgo_bash_load.set_downstream(dag_end)\r\n","sub_path":"Raif/pyspark/run_calc_08.py","file_name":"run_calc_08.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"277158789","text":"from Post import Post\nfrom Photo import Photo\nfrom config import telegram_token\nimport requests\nimport urllib\nimport json\nimport time\nimport os\nimport logging\n\nLOGGER = logging.getLogger(__name__)\nLOGGER.setLevel(\"DEBUG\")\n\n\nclass TelegramPost(Post):\n def __init__(self, photo: Photo, chatIdFilePath):\n super().__init__(photo)\n self.chatIdFilePath = chatIdFilePath\n self.chatIds = self.updateAndGetRecipientList(self.chatIdFilePath)\n self.closureText = \"TelegramBot (GitHub: http://bit.ly/PotDGithub)\"\n self.locationName = None\n self.telegramPostText = self.composeTelegramPostText()\n\n def composeTelegramPostText(self):\n if self.locationName is not None:\n locationSection = f\"Shot in {self.locationName} \"\n else:\n locationSection = \"\"\n\n return (\n f\"{self.introText} \"\n f\"{self.exifSection} {self.closureText} \"\n f\"{self.photo.tensorFlowHashtags} \"\n f\"{locationSection}\"\n f\"| Sent with ❤️\"\n )\n\n def updateAndGetRecipientList(self, chatIdFilePath):\n # Download updated from the Telegram's bot API\n # See: https://core.telegram.org/bots/api\n\n updatesUrl = f\"https://api.telegram.org/bot{telegram_token}/getUpdates\"\n response = urllib.request.urlopen(updatesUrl)\n data = json.loads(response.read().decode())\n\n # get chatIds from the getUpdates endpoint, extract chatIds of private\n # conversations only ~ a private message sent from users asking bot\n # to be subscribed to the daily delivery\n chatIds = set(\n [\n message[\"message\"][\"chat\"][\"id\"]\n for message in data[\"result\"]\n if message[\"message\"][\"chat\"][\"type\"] == \"private\"\n ]\n )\n\n # Retrieve preserved chatIds from the existing json file\n if os.path.isfile(chatIdFilePath):\n with open(chatIdFilePath) as jsonData:\n jsonContent = json.load(jsonData)\n # Put chatIds into the existing chatIds set\n list(map(lambda x: chatIds.add(x), jsonContent[\"chatIds\"]))\n\n # Save all chatIds to the JSON file\n with open(chatIdFilePath, \"w\") as jsonData:\n jsonData.write(json.dumps({\"chatIds\": list(chatIds)}))\n\n return chatIds\n\n def setLocation(self, locationName):\n self.locationName = locationName\n\n def postTelegramPost(self):\n # refresh telegram's message\n self.telegramPostText = self.composeTelegramPostText()\n result = 0\n try:\n #\n # https://core.telegram.org/bots/faq#how-can-i-message-all-of-my-bot-39s-subscribers-at-once\n # How can I message all of my bot's subscribers at once?\n # Unfortunately, at this moment we don't have methods for sending bulk\n # messages, e.g. notifications. We may add something along these lines in the future.\n\n # In order to avoid hitting our limits when sending out mass notifications, consider\n # spreading them over longer intervals, e.g. 8-12 hours. The API will not allow more than ~30 messages\n # to different users per second, if you go over that, you'll start getting 429 errors.\n\n # push the message to every chatId\n for chatId in self.chatIds:\n url = f\"https://api.telegram.org/bot{telegram_token}/sendPhoto\"\n files = {\"photo\": open(self.photo.photoPath, \"rb\")}\n data = {\"chat_id\": chatId, \"caption\": self.telegramPostText}\n response = requests.post(url, files=files, data=data)\n if response.status_code != 200:\n raise Exception(f\"{response.status_code} {response.reason}\")\n # being nice to the Telegram's api\n time.sleep(0.05)\n except Exception as e:\n LOGGER.error(e)\n result = -1\n\n return result\n","sub_path":"app/src/TelegramPost.py","file_name":"TelegramPost.py","file_ext":"py","file_size_in_byte":3992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}