diff --git "a/234.jsonl" "b/234.jsonl" new file mode 100644--- /dev/null +++ "b/234.jsonl" @@ -0,0 +1,748 @@ +{"seq_id":"643285570","text":"\nimport yaml\nimport arrow\n\ninfile = 'jobcentre-uc-rollout.yaml'\n\ndatemap = {}\n\ndef toDate(s):\n (year, month) = s.split('-')\n d = arrow.get(s)\n e = d.ceil('month')\n return e\n\nwith open(infile, 'r') as f:\n doc = yaml.load(f)\n\n for item in doc:\n datemap[item] = toDate(item) \n\n\nn = arrow.now()\n\ntotal_authorities_live = 0\ntotal_authorities_pending_go_live = 0\n\njcs_live = 0\njcs_to_go_live = 0\n\n\nfor item in datemap:\n to_be_live_authorities = len(doc[item])\n c = 0\n for k in doc[item]:\n for z in k:\n num_jcs = len(k[z])\n print('{},{},{}'.format(datemap[item], z, num_jcs))\n","sub_path":"y.py","file_name":"y.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"432105020","text":"from typing import List\r\n\r\nclass Solution:\r\n def searchRange(self, nums: List[int], target: int) -> List[int]:\r\n arr_len = len(nums)\r\n if arr_len == 0:\r\n return [-1, -1]\r\n if arr_len == 1:\r\n if target == nums[0]:\r\n return [0, 0]\r\n else:\r\n return [-1, -1]\r\n \r\n l, r = 0, arr_len - 1\r\n while l < r:\r\n mid = (l + r) // 2\r\n if nums[mid] >= target:\r\n r = mid\r\n else:\r\n l = mid + 1\r\n if l >= arr_len or nums[l] != target:\r\n return [-1, -1]\r\n left_index = l\r\n\r\n l, r = 0, arr_len - 1\r\n while l < r:\r\n mid = (l + r) // 2\r\n if nums[mid] > target:\r\n r = mid\r\n else:\r\n l = mid + 1\r\n \r\n right_index = l\r\n if l >= arr_len or nums[l] != target:\r\n right_index -= 1\r\n\r\n return [left_index, right_index]\r\n\r\n\r\nif __name__ == \"__main__\":\r\n solveObj = Solution()\r\n print(solveObj.searchRange([2,2], 2))","sub_path":"34 Find First and Last Position of Element in Sorted Array.py","file_name":"34 Find First and Last Position of Element in Sorted Array.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"235416321","text":"class SlabDb:\n \"\"\"\n Pandas DataFrame of graph nodes, representing vascular junctions.\n \"\"\"\n def __init__(self, dataframe, dx, dy):\n \"\"\"\n Constructor; allows user interaction with database.\n\n :param dataframe: Pandas DataFrame of slab data from CSV txt file.\n :param dx: scaling factor for slab x position, in um/pixel\n :param dy: scaling factor for slab y position, in um/pixel\n\n :type dataframe: pandas.DataFrame\n :type dx: float\n :type dy: float\n \"\"\"\n self.dframe = dataframe\n self.dx = dx\n self.dy = dy\n","sub_path":"PyQt_Stackbrowser/slabdb.py","file_name":"slabdb.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"164567060","text":"import sys\nimport zmq\n\nif __name__ == '__main__':\n\n context = zmq.Context()\n\n HOST = sys.argv[1] if len(sys.argv) > 1 else \"localhost\"\n PORT = sys.argv[2] if len(sys.argv) > 2 else \"50007\"\n\n p1 = \"tcp://\"+ HOST +\":\"+ PORT # how and where to connect\n\n s = context.socket(zmq.REQ) # create request socket\n s.connect(p1) # block until connected\n s.send(b\"Hello world\") # send message\n\n message = s.recv() # block until response\n s.send(b\"STOP\") # tell server to stop\n\n print(\"Reply {}\".format(message)) # print result","sub_path":"FILA_MSG_LAB/REQ_REP/cliente01.py","file_name":"cliente01.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"152912855","text":"import openpyxl, os\r\n\r\nos.chdir('12 - planilhas excel')\r\nwb = openpyxl.load_workbook('example.xlsx')\r\nsheet = wb['Sheet1']\r\n\r\nprint(tuple(sheet['A1':'C3']))\r\n\r\nfor rowOfCellObjects in sheet['A1':'C3']:\r\n for cellObj in rowOfCellObjects:\r\n print(cellObj.coordinate, cellObj.value)\r\n print('--END OF ROW--')\r\n\r\nsheet = wb.active\r\n\r\ni = 1\r\nwhile True:\r\n resultado = sheet.cell(row=i, column=2).value\r\n if resultado == None:\r\n break\r\n print(resultado)\r\n i += 1","sub_path":"12 - planilhas excel/obtendo-linhas-e-colunas-das-planilhas.py","file_name":"obtendo-linhas-e-colunas-das-planilhas.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"143148253","text":"#importing packages\nimport os\nimport csv\n\n#loading in csv file\nbudget_data = os.path.join(\"budget_data.csv\")\n\n#creating lists\nprofits = []\nnet_change = []\nmonths =[]\n\n# Read in the CSV file\nwith open(budget_data, 'r') as csvfile:\n\n# Split the data on commas\n csvreader = csv.reader(csvfile, delimiter=',')\n\n header = next(csvreader)\n for row in csvreader:\n \n#Count the number of months \n months.append(row[0])\n each_month = len(set(months))\n #months = months + 1\n\n#Calculate total profits\n profits.append(int(row[1]))\n total_profits = sum(profits)\n\n#for loop appending the net change list for each month \n\n for i in range(0,len(profits) -1): \n\n net_change.append(int(profits[i+1]) - int(profits[i]))\n#calculate the averae\n average_profits = sum(net_change)/len(net_change)\n#append max n min \n #max_min_dates.append(row[0])\n\n#find the increase and decrease\n greatest_increase = max(profits)\n greatest_decrease = min(profits)\n \n#dates of max and min\n max_profit_date = months[profits.index(greatest_increase)]\n min_profit_date = months[profits.index(greatest_decrease)]\n\n#print statements\n print(\"Financial Analysis\")\n print(\"---------------------------------\")\n print(f\"Total Number of Months: {str(each_month)}\")\n print(f\"Total: ${str(int(total_profits))}\")\n print(f\"Average Change: $ {str(int(average_profits))}\" )\n print(\"Greatest Increase in Profits: \" + str(max_profit_date) + \" ($\" + str(greatest_increase) + \")\")\n print(\"Greatest Decrease in Profits: \" + str(min_profit_date) + \" ($\" + str(greatest_decrease)+ \")\")\n \n#will output the program to a text file\nwith open(\"output.txt\", \"w\") as x: \n print(\"Financial Analysis \\n\", file = x)\n print(\"-----------------------------------\\n\", file=x)\n print(f\"Total Number of Months: {str(months)}\\n\", file = x) \n print(f\"Total: ${str(int(total_profits))}\\n\", file = x)\n print(f\"Average Change: $ {str(int(average_profits))}\\n\", file = x )\n print(\"Greatest Increase in Profits: \" + str(max_profit_date) + \" ($\" + str(greatest_increase) + \")\\n\", file = x)\n print(\"Greatest Decrease in Profits: \" + str(min_profit_date) + \" ($\" + str(greatest_decrease)+ \")\\n\", file = x)\n\n\n\n","sub_path":"PyBank/Resources/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"157884816","text":" # -*- coding: utf-8 -*-\n\n\"\"\"\nThis file contains functions for reading input (training) data.\nThere are functions for dealing specifically with CoNLL format data \nand others for simpler formats.\n\"\"\"\n\nimport re\nfrom itertools import izip\n\nimport utils\nimport logging\nfrom attributes import Token\n\nPRE_CONTRACTIONS = ['em', 'a', 'para', 'por', 'de', 'por', 'com', 'lhe']\nPOS_CONTRACTIONS = ['o', 'a', 'os', 'as', 'um', 'uma', 'uns', 'umas', \n 'me', 'te', 'se', 'nos', 'vos', \n 'esse', 'essa', 'isso', 'este', 'esta', 'isto',\n 'esses', 'essas', 'estes', 'estas', \n 'aquele', 'aquela', 'aquilo',\n 'aqueles', 'aquelas']\n\nclass ConllPos(object):\n \"\"\"\n Dummy class for storing the position of each field in a\n CoNLL data file.\n \"\"\"\n id = 0\n word = 1\n lemma = 2\n pos = 3\n morph = 4\n parse = 7\n pred = 8\n\nchunks = ['NP', 'VP', 'ADVP', 'PP', 'ADJP', 'CL']\n\ndef read_plain_srl(filename):\n \"\"\"\n Reads an SRL file and returns the training data. The file\n should be divided in columns, separated by tabs and/or whitespace.\n First column: tokens\n Second column: - (hyphen) for non-predicates, anything else for predicates.\n Third and next columns: the SRL IOBES tags for each token concerning\n each predicate (3rd column for 1st predicate, 4th for the 2nd, and\n so on).\n \n :returns: a list of tuples in the format (tokens, tags, predicates)\n \"\"\"\n sentences = []\n \n with open(filename, 'rb') as f:\n token_num = 0\n sentence = []\n tags = []\n predicates = []\n \n for line in f:\n line = unicode(line, 'utf-8').strip()\n \n if line == '':\n # last sentence ended\n sentences.append((sentence, tags, predicates))\n sentence = []\n tags = []\n predicates = []\n token_num = 0\n continue\n \n parts = line.split('\\t') # was split(), Attardi\n token = Token(parts[0].strip())\n sentence.append(token)\n \n # check if this is a predicate\n if parts[1].strip() != '-':\n predicates.append(token_num)\n \n # initialize the expected roles\n if tags == []:\n num_preds = len(parts) - 2\n tags = [[] for _ in range(num_preds)]\n \n for i, role in enumerate(parts[2:]):\n # the SRL tags\n tags[i].append(role)\n \n token_num += 1\n \n if sentence != []:\n sentences.append((sentence, tags, predicates))\n \n return sentences\n\n\ndef verify_chunk_tag(new_tag, expected_tag):\n \"\"\"\n Compares the expected chunk tag with the new found one, and \n returns the correct tag.\n \"\"\"\n \n # new clause chunks are very rare, we collapse them into a single chunk\n if new_tag in ('FCL', 'ACL', 'ICL'):\n new_tag = 'CL'\n \n if new_tag == expected_tag:\n return expected_tag\n \n # NP's inside a PP don't get an own chunk, nor adjectives or adverbs\n # a coordination may appear inside an NP\n if expected_tag == 'PP' and new_tag in ('NP', 'ADJP', 'ADVP', 'CU'):\n return expected_tag\n \n # adjectives inside NPs don't get an own chunk, nor adverbs that may be inside it\n # a coordination may appear inside an NP\n if expected_tag == 'NP' and new_tag in ('ADJP', 'ADVP', 'CU'):\n return expected_tag\n \n if new_tag not in chunks:\n return 'O'\n \n # same for adverbs inside ADJPs\n if expected_tag == 'ADJP' and new_tag == 'ADVP':\n return expected_tag\n \n return new_tag\n\ndef get_chunk_tag(word, parse, expected_block): \n \"\"\"\n Examines a given entry in the CoNLL format and returns a tuple\n (chunk_tag, expected_chunk_block). Note that the chunk tag is already \n encoded in IOB, while the expected block is not.\n \"\"\"\n if not re.search('[\\w%]', word):\n # punctuation\n chunk_tag = 'O'\n expected_block = 'O'\n elif parse[0] == '*':\n # continue inside the block\n chunk_tag = expected_block\n if chunk_tag != 'O':\n chunk_tag = 'I-%s' % chunk_tag\n else:\n # find all tags starting here\n new_levels = re.findall('\\w+', parse)\n a_priori_expected_block = expected_block\n \n # I believe it is safer to check every tag transition in the new levels\n for new_tag in new_levels:\n chunk_tag = verify_chunk_tag(new_tag, expected_block)\n expected_block = chunk_tag\n \n if chunk_tag != 'O':\n if chunk_tag == a_priori_expected_block:\n chunk_tag = 'I-%s' % chunk_tag\n else:\n chunk_tag = 'B-%s' % chunk_tag\n \n # reached the end of a constituent\n if ')' in parse:\n expected_block = 'O'\n \n return (chunk_tag, expected_block)\n\n\ndef get_chunks(tree, previous_node='', dominating_node='', new_block=False):\n \"\"\"\n Traverses a tree extracting chunk information.\n \n :param tree: A syntactic tree.\n :param previous_node: the parent of the subtree passed as \n first argument.\n :param dominating_node: the label of the chunk dominating\n the subtree so far.\n :param new_block: whether a new block (a new chunk) must \n start if the new tag is the same as the previous dominating one.\n :returns: a list of (tag, chunk_tag) tuples.\n \"\"\"\n new_node = tree.node\n node = verify_chunk_tag(new_node, dominating_node)\n \n # a new block starts here, with different tags\n new_block = (new_block and node == dominating_node) or (node != dominating_node)\n \n # or a new block starts with the same tag (except in coordinations)\n new_block = new_block or (new_node == dominating_node and \n new_node != previous_node and previous_node != 'CU')\n \n tokens_tags = []\n \n for subtree in tree:\n \n try:\n subtree.node\n \n except AttributeError:\n # this is a leaf\n if not re.search('(?u)\\w', subtree) and (node == 'CL' or new_block):\n # punctuation connected with the head or starting a new block\n tokens = [subtree]\n tags = ['O']\n new_block = True\n \n else:\n # split multiwords\n tokens = subtree.split('_')\n if node == 'O':\n tags = ['O'] * len(tokens) \n else: \n if new_block:\n tags = ['B-%s' % node] + ['I-%s' % node] * (len(tokens) - 1) \n new_block = False\n else:\n tags = ['I-%s' % node] * len(tokens)\n \n for token, tag in izip(tokens, tags):\n tokens_tags.append((token, tag))\n \n else:\n subtree_tokens = get_chunks(subtree, new_node, node, new_block)\n \n # if the subtree was a PP, it must be clear that a PP ended.\n # Elsewise, if we are on a child of a PP that \n # has a PP child, things get messy. \n for _, tag in subtree_tokens:\n if tag == 'B-PP':\n new_block = True\n node = verify_chunk_tag(new_node, 'O')\n break \n tokens_tags.extend(subtree_tokens)\n \n return tokens_tags\n\ndef read_trees(iterable):\n \"\"\"Reads an iterable in order to mount a syntactic tree.\"\"\"\n from nltk import Tree\n tree_strings = []\n trees = []\n \n for line in iterable:\n uline = unicode(line, 'utf-8')\n data = uline.split()\n \n if len(data) <= 1:\n tree = Tree.parse(' '.join(tree_strings), brackets='[]')\n trees.append(tree)\n tree_strings = []\n continue\n \n word = data[ConllPos.word]\n pos = data[ConllPos.pos]\n parse = data[ConllPos.parse]\n \n # a little workaround.\n # to avoid messing nltk.Tree string parser, we use [] as tree brackets\n # instead of the default (). This is done because \"(\" and \")\" appear as \n # separate tokens, while \"[\"and \"]\" do not.\n tree_string = parse.replace('(', '[').replace(')', ']')\n # treat \"broken\" constituents like VP- and -VP as normal VPs\n tree_string = tree_string.replace('-', '')\n \n # treat multiwords and concatenate their POS with #\n words = [' %s#%s ' % (part, pos) for part in word.split('_')]\n words_string = ' '.join(words)\n tree_string = tree_string.replace('*', words_string)\n \n tree_strings.append(tree_string)\n \n return trees\n\ndef read_conll(iterable, read_srl=True):\n \"\"\"\n Reads a sentence from a sequence of lines in a CoNLL format file.\n \n :returns: if read_srl is True, returns a list of tuples, where each\n one has the format:\n ([token1, token2, ...], [[tag-for-pred1, tag-for-pred1, ...],\n [tag-for-pred2, tag-for-pred2, ...]],\n [index-of-pred1, index-of-pred2, ...])\n \n Tags are repeated, NOT in IOBES format.\n If read_srl is False, returns a list of sentences.\n \"\"\"\n from nltk import Tree\n \n sentences = []\n sentence = []\n instances = None\n num_preds = None\n predicates = []\n token_number = 0\n \n # used to build syntactic trees\n tree_strings = []\n \n for line in iterable:\n uline = unicode(line, 'utf-8') \n data = uline.split()\n if len(data) <= 1:\n # this is an empty line after a sentence\n \n # build the syntactic tree and attribute each token's chunk\n tree = Tree.parse(' '.join(tree_strings), brackets='[]')\n token_chunks = get_chunks(tree)\n for j, (token, (word, chunk)) in enumerate(izip(sentence, token_chunks)):\n assert token.word == word, \\\n \"Syntactic and semantic analyses got different words: %s and %s\" % (token.word, word)\n \n token.chunk = chunk\n sentence[j] = token\n \n if read_srl:\n sentences.append((sentence, instances, predicates))\n instances = None\n predicates = []\n token_number = 0\n else:\n sentences.append(sentence)\n \n num_preds = None\n tree_strings = []\n sentence = []\n continue\n \n if instances is None and read_srl:\n # initializes each instance as an empty list\n num_preds = len(data) - ConllPos.pred - 1\n instances = [[] for _ in xrange(num_preds)]\n expected_role = ['O'] * num_preds\n \n word = data[ConllPos.word]\n lemma = data[ConllPos.lemma].lower()\n pos = data[ConllPos.pos].lower()\n parse = data[ConllPos.parse]\n is_predicate = data[ConllPos.pred] != '-'\n \n # lemmas for punctuation are listed as -\n if lemma == '-':\n lemma = word\n \n # Syntactic tree\n \n # to avoid messing nltk.Tree string parser, we use [] as tree brackets\n # instead of the default (). This is done because \"(\" and \")\" appear as \n # separate tokens, while \"[\"and \"]\" do not.\n tree_string = parse.replace('(', '[').replace(')', ']')\n # treat \"broken\" constituents like VP- and -VP as normal VPs\n tree_string = tree_string.replace('-', '')\n tree_string = tree_string.replace('*', ' %s ' % word)\n tree_strings.append(tree_string)\n \n # if it's a predicate, add to the list of predicates\n # we must check it before appending the tokens\n # because multiword tokens may mess up the count\n if read_srl and is_predicate:\n predicates.append(token_number)\n \n # split multiwords\n splitted = zip(word.split('_'), lemma.split('_'))\n num_parts = len(splitted)\n for word_part, lemma_part in splitted:\n token = Token(word_part, pos=pos, lemma=lemma_part)\n sentence.append(token)\n token_number += 1\n \n # SRL\n if read_srl:\n \n # read the roles for each predicate\n for i, role in enumerate(data[ConllPos.pred + 1:]):\n role, expected_role[i] = read_role(role, expected_role[i])\n \n # repeat the tag if the word was splitted\n for _ in range(num_parts):\n instances[i].append(role)\n \n assert instances is None\n \n return sentences\n\ndef read_role(role, expected_role):\n \"\"\"\n Reads the next semantic role from a CoNLL-style file.\n :return a tuple (role, expected next role)\n \"\"\"\n if role == '*':\n # signals continuation of the last block\n role = expected_role\n elif role == '*)':\n # finishes block\n role = expected_role\n expected_role = 'O'\n else:\n # verifies if it is a single argument\n match = re.search('\\(([-\\w]+)\\*\\)', role)\n if match:\n role = match.group(1)\n expected_role = 'O'\n else:\n # verifies if it opens an argument\n match = re.search('\\(([-\\w]+)\\*', role)\n if match:\n role = match.group(1)\n expected_role = role\n else:\n raise ValueError('Unexpected role data: %s' % role)\n \n if role.startswith('C-'):\n # removes C-\n role = role[2:]\n \n return (role, expected_role)\n\ndef read_chunks(iterable):\n \"\"\"Test function. It will read word tokens and their corresponding chunk.\"\"\"\n sents = []\n sent = []\n expected_tag = 'O'\n \n for line in iterable:\n uline = unicode(line, 'utf-8')\n data = uline.split()\n if len(data) <= 1:\n sents.append(sent)\n sent = []\n continue\n \n word = data[ConllPos.word]\n parse = data[ConllPos.parse]\n \n if not re.search('[\\w%]', word):\n # punctuation\n tag = 'O'\n expected_tag = 'O'\n elif parse[0] == '*':\n # continue inside the block\n tag = expected_tag\n else:\n # find all tags starting here\n new_levels = re.findall('\\w+', parse)\n \n # I believe it is safer to check every tag transition in the new levels\n for new_tag in new_levels:\n tag, expected_tag = verify_chunk_tag(new_tag, expected_tag)\n \n # reached the end of a constituent\n if ')' in parse:\n expected_tag = 'O'\n \n sent.append((word, tag))\n \n return sents\n\n\ndef valid_sentence(sentence, tags):\n \"\"\"\n Checks whether a sentence and its tags are valid or not.\n The check includes verifying if the sentence ends with an article\n or preposition, has a verb after an article, etc.\n \"\"\"\n if len(sentence) == 1:\n return True\n \n # first, check if the sentence ends with some punctuation sign\n # as some seem to be missing it\n last_tag = tags[-2] if tags[-1] == 'PU' else tags[-1]\n \n if last_tag in ('PREP', 'ART', 'PREP+ART', 'KC', 'KS'):\n # sentence ending with article, preposition or conjunction\n return False\n \n # checking impossible sequences\n for token1, token2, tag1, tag2 in izip(sentence, sentence[1:], tags, tags[1:]):\n if tag1 in ('ART', 'PREP+ART'):\n if (token1 != 'ao' and tag2 in ('V', 'VAUX')) or token2 in '.,!?:;' \\\n or tag2 in ('PREP', 'PREP+ART', 'KC', 'KS'):\n # allow sequences like \"ao ver\"\n return False\n \n if token1 == ',' and token2 in '.,!?:;':\n return False\n \n if tag1 == tag2 == 'PU' and token1 == token2 and token1 not in '!?':\n # repeated punctuation\n return False\n \n return True\n\ndef read_pos_file(filename):\n \"\"\"\n Reads a file from a POS tagged corpus and returns it as a list\n of sentences, where each sentence element is composed of a \n tuple (token, tag).\n The file must have one sentence per line, and sentences must have\n tokens in the format token_tag. \n \"\"\"\n \n tokens = []\n tags = []\n pre_token = ''\n pre_tag = ''\n waiting_contraction = False\n invalid = 0\n sents = []\n \n logger = logging.getLogger(\"Logger\")\n \n with open(filename) as f:\n for i, line in enumerate(f, 1):\n uline = unicode(line, 'utf-8').strip()\n \n if uline.strip() == '':\n # a sentence ended here \n sents.append((tokens, tags))\n tokens = []\n tags = []\n continue\n \n token, tag = uline.rsplit('_')\n \n if waiting_contraction:\n if tag.endswith('|+'):\n if tag[:-2] == pre_tag:\n # the first part of the contraction continues. This happens\n # in cases such as \"Em frente de a\", where Em, frente e de are \n # prepositions\n tokens.append(pre_token)\n tags.append(pre_tag)\n pre_token = token\n continue\n elif token == \"'\" :\n # contractions such as d'ele\n pre_token = pre_token + token\n else:\n raise ValueError('Expected contraction between (%s, %s) and (%s, %s)'\n % (pre_token, pre_tag, token, tag))\n \n else:\n # the contraction should be made now\n \n # I found there is one case of PREP+PREP which is dentre(de + entre)\n # I think it's better to treat it as a simple prepostion\n try:\n token = utils.contract(pre_token, token)\n except:\n logger.error('Error in line %d of the input file %s' % (i, filename))\n raise\n \n if not re.match('(?i)dentre', token):\n tag = '%s+%s' % (pre_tag, tag)\n waiting_contraction = False\n tokens.append(token)\n tags.append(tag)\n continue\n \n if token == '$':\n # all cases of a single $ I found are mistakes\n continue\n elif re.match('\\$\\W', token):\n # there are some cases where a punctuation sign is preceded by $\n token = token[1:]\n \n if re.match('\\W', tag):\n # normalize all punctuation tags\n tag = 'PU'\n \n elif re.match('V.*\\|\\+', tag):\n # append trailing hyphen to verbs with ênclise\n token += '-'\n tag = tag[:-2]\n \n elif tag == 'PREP|+':\n # wait for next token to contract\n waiting_contraction = True\n pre_tag = 'PREP'\n pre_token = token\n continue\n \n elif tag == 'NPROP|+':\n # cases too rare to care\n tag = 'NPROP'\n \n elif '|' in tag:\n # we will only use the complementar info after | for contractions\n # and ênclises, which are treated in other if blocks.\n # any other will be removed (including EST, DAT, HOR, etc.)\n tag = tag[:tag.find('|')]\n \n tokens.append(token)\n tags.append(tag)\n \n \n # if sentences were not previously delimited, do it now\n if sents == []:\n # This looks horrible but I haven't figured out a better way.\n # Join all the tokens as a string and have the sentence tokenizer \n # split it into sentences. Then, align the sentences with the tags.\n # Then, verify weird sentences that should be put off along with\n # their tags.\n import nltk.data\n st = nltk.data.load('tokenizers/punkt/portuguese.pickle')\n sents = st.tokenize(' '.join(tokens), realign_boundaries=False)\n sents = [sent.split() for sent in sents]\n tags = align_tags(sents, tags)\n \n else:\n assert tokens == [], \\\n \"Stray tokens at the end of the file. Probably missed a line break. Tokens: %s\" % str(tokens)\n sents, tags = zip(*sents)\n \n tagged_sents = []\n valid_sents = []\n for sent, sent_tags in izip(sents, tags):\n \n valid = valid_sentence(sent, sent_tags)\n repeated = sent in valid_sents\n \n # remove invalid and repeated sentences\n if valid and not repeated:\n valid_sents.append(sent)\n tagged_sents.append(zip(sent, sent_tags))\n \n else:\n invalid += 1\n \n if not valid:\n logger.debug(\"Discarded (invalid): %s\" % (' '.join(sent).encode('utf-8')))\n else:\n logger.debug(\"Discarded (repeated): %s\" % (' '.join(sent).encode('utf-8')))\n \n logger.debug('%d invalid sentence(s) discarded' % invalid)\n return tagged_sents\n\n\ndef align_tags(sentences, tags):\n \"\"\"\n Align a sequence of tags into a sequence of sequences, corresponding \n to the sentences.\n \"\"\"\n new_tags = []\n for sentence in sentences:\n sent_tags = []\n for _ in sentence:\n sent_tags.append(tags.pop(0))\n new_tags.append(sent_tags)\n \n return new_tags\n\n\nif __name__ == '__main__':\n pass\n \n","sub_path":"nlpnet/read_data.py","file_name":"read_data.py","file_ext":"py","file_size_in_byte":22165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"429715358","text":"# -*- coding: utf-8 -*-\nimport signal\nimport platform\n\nTTW_SLOW = [0.5, 1.5]\nTTW_FAST = [0.0, 0.1]\n\n\nclass SignalManager(object):\n \"\"\"Manages POSIX signals.\"\"\"\n\n kill_now = False\n time_to_wait = TTW_FAST\n\n def __init__(self):\n # Temporary workaround for signals not available on Windows\n if platform.system() == 'Windows':\n signal.signal(signal.SIGTERM, self.exit_gracefully)\n else:\n signal.signal(signal.SIGTSTP, self.exit_gracefully)\n\n # A Deck-specific tweak...\n # We want it to handle SIGTERM like it handles SIGTSTP, and do a graceful shutdown\n # where it finishes any in-progress tasks, but doesn't grab any new ones.\n # This allows for graceful shutdowns during Kubernetes redeployments.\n signal.signal(signal.SIGTERM, self.exit_gracefully)\n\n signal.signal(signal.SIGUSR1, self.speed_up)\n signal.signal(signal.SIGUSR2, self.slow_down)\n\n def exit_gracefully(self, signum, frame):\n self.kill_now = True\n\n def speed_up(self, signum, frame):\n self.time_to_wait = TTW_FAST\n\n def slow_down(self, signum, frame):\n self.time_to_wait = TTW_SLOW\n","sub_path":"background_task/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"351808228","text":"\n#Q.1- Write a Python program to read n lines of a file\nf=open('test.txt','r')\nlines=f.readlines()\n#print(lines)\nfor i in range(0,len(lines)):\n print(\"line\",i,\":\",lines[i])\n#Q.2- Write a Python program to count the frequency of words in a file.\nfrom collections import Counter\nfile1=open('Q2.txt','r')\ncount = Counter(file1.read().split())\nprint(count)\n#Q.3- Write a Python program to copy the contents of a file to another file\nfile1=open('test4.txt','r')\ndata=file1.read()\nfile1.close()\nfile2=open('test5.txt','w')\nfile2.write(data)\nfile2.close()\n\n#Q.4- Write a Python program to combine each line from first file with the corresponding line in second file.\n\nf=open('test9.txt')\ng=open('test10.txt')\nm=open('text11.txt','w')\ndata=f.read()\nty=g.read()\na=data.split()\nb=ty.split()\nfor i in range(len(a)):\n x=a[i]+\" \"+b[i]\n m.write(x+\"\\n\")\ng.close()\nf.close()\nm.close()\n\n#Q.5- Write a Python program to write 10 random numbers into a file. Read the file and then sort the numbers and then store it to another file.\nimport random\nfile=open('test1.txt','w')\nfor i in range(10):\n x=random.randint(1,100) \n file.write(str(x))\n file.write(' ')\nfile.close()\nfile=open('test1.txt','r+')\nline=file.read()\nline=line.split()\nfor i in range(0,len(line)):\n line[i]=int(line[i]) \nline=sorted(line)\nfor i in range(0,len(line)):\n line[i]=str(line[i]) \nfile.close()\nfile=open('test2.txt','w')\nfor i in line:\n file.write(i)\n file.write(\" \")\nfile.close()\n","sub_path":"ASSIGNMENT10.py","file_name":"ASSIGNMENT10.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"252612716","text":"#!/usr/bin/env python\n\n# Copyright (c) 2017, DIANA-HEP\n# All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# \n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n# \n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n# \n# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n# \n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Substitutions for parts of fastparquet that we need to do differently.\n\nThis file (only one in the _fastparquet directory) is under OAMap's license.\n\"\"\"\n\nimport os\n\nimport numpy\n\nfrom oamap.util import OrderedDict\n\ntry:\n import thriftpy\n import thriftpy.protocol\nexcept ImportError:\n thriftpy = None\n parquet_thrift = None\nelse:\n THRIFT_FILE = os.path.join(os.path.dirname(__file__), \"parquet.thrift\")\n parquet_thrift = thriftpy.load(THRIFT_FILE, module_name=\"parquet_thrift\")\n\ndef unpack_byte_array(array, count):\n data = numpy.empty(len(array) - 4*count, numpy.uint8)\n size = numpy.empty(count, numpy.int32)\n\n i = 0\n datai = 0\n sizei = 0\n while sizei < count:\n if i + 4 > len(array):\n raise RuntimeError(\"ran out of input\")\n itemlen = array[i] + (array[i + 1] << 8) + (array[i + 2] << 16) + (array[i + 3] << 24)\n i += 4\n\n if i + itemlen > len(array):\n raise RuntimeError(\"ran out of input\")\n data[datai : datai + itemlen] = array[i : i + itemlen]\n size[sizei] = itemlen\n\n i += itemlen\n datai += itemlen\n sizei += 1\n\n return data, size\n\ntry:\n import numba\nexcept ImportError:\n pass\nelse:\n njit = numba.jit(nopython=True, nogil=True)\n unpack_byte_array = njit(unpack_byte_array)\n","sub_path":"oamap/source/_fastparquet/extra.py","file_name":"extra.py","file_ext":"py","file_size_in_byte":2883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"579539537","text":"#!/usr/bin/env python\n\n\"\"\"\nCreated by: Lee Bergstrand (2017)\n\nDescription: A simple unittest for testing the step module.\n\"\"\"\n\nimport unittest\n\nfrom modules.step import parse_steps\n\n\nclass TestStep(unittest.TestCase):\n \"\"\"A unit testing class for testing the step.py module. To be called by nosetests.\"\"\"\n\n def test_parse_step(self):\n \"\"\"Test that step rows can be parsed.\"\"\"\n step = [\n ('--', ''),\n ('SN', '1'),\n ('ID', 'Aferr subtype specific proteins'),\n ('DN', 'Crispy Proteins'),\n ('RQ', '0'),\n ('EV', 'IPR017545; TIGR03114; sufficient;'),\n ('TG', 'GO:0043571;GO:0043579;')\n ]\n\n parsed_step = parse_steps(step)\n\n self.assertEqual(len(parsed_step), 1)\n first_step = parsed_step[0]\n self.assertEqual(first_step.number, 1)\n self.assertEqual(first_step.required, False)\n\n def test_parse_step_required(self):\n \"\"\"Test that the step rows can be properly parsed if the step is required.\"\"\"\n step = [\n ('--', ''),\n ('SN', '1'),\n ('ID', 'Aferr subtype specific proteins'),\n ('DN', 'Crispy Proteins'),\n ('RQ', '1'),\n ('EV', 'IPR017545; TIGR03114; sufficient;'),\n ('TG', 'GO:0043571; GO:0043579;')\n ]\n\n parsed_step = parse_steps(step)\n first_step = parsed_step[0]\n self.assertEqual(first_step.required, True)\n\n def test_parse_missing_rows(self):\n \"\"\"Test that steps can be parsed if they are missing non essential rows.\"\"\"\n step = [\n ('--', ''),\n ('SN', '2'),\n ('ID', 'Apern subtype specific proteins')\n ]\n\n parsed_steps = parse_steps(step)\n\n second_step = parsed_steps[0]\n self.assertEqual(second_step.required, False)\n self.assertEqual(len(second_step.functional_elements), 1)\n\n def test_parse_multiple_steps(self):\n \"\"\"Test that steps rows consisting of multiple references can be parsed.\"\"\"\n\n steps = [\n ('--', ''),\n ('SN', '1'),\n ('ID', 'Aferr subtype specific proteins'),\n ('RQ', '0'),\n ('EV', 'IPR017545; TIGR03114; sufficient;'),\n ('TG', 'GO:0043571;'),\n ('--', ''),\n ('SN', '2'),\n ('ID', 'Yolo subtype specific proteins'),\n ('RQ', '1'),\n ('EV', 'IPR017545; TIGR03114;'),\n ('TG', 'GO:0043571;')\n ]\n\n parsed_steps = parse_steps(steps)\n step_one = parsed_steps[0]\n step_two = parsed_steps[1]\n\n self.assertEqual(len(parsed_steps), 2)\n self.assertEqual(step_one.number, 1)\n self.assertEqual(step_two.number, 2)\n self.assertEqual(len(step_two.functional_elements), 1)\n self.assertEqual(len(step_two.functional_elements[0].evidence), 1)\n","sub_path":"testing/test_step.py","file_name":"test_step.py","file_ext":"py","file_size_in_byte":2891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"105132526","text":"# Read and Process Input Files\n\nclass File:\n\n def __init__(self, filename):\n self.fileName = filename\n self.graph = []\n self.homes = []\n\n '''\n Extract graph from input file\n Replace all 'x' with 0\n Generate list of home indices\n '''\n def readFile(self):\n # read file, change every x to 0, save to graph\n count = 0\n location_names = []\n home_names = []\n with open(self.fileName, 'r') as f:\n for i in f:\n count += 1\n if count == 3:\n location_names = i.split(\" \")[:-1]\n elif count == 4:\n home_names = i.split(\" \")[:-1]\n elif count >= 6:\n s = i.split(\" \")[:-1]\n for j in range(len(s)):\n if s[j] == 'x':\n s[j] = 0\n s[j] = float(s[j])\n self.graph.append(s)\n\n # save home indices\n for i in range(len(location_names)):\n if location_names[i] in home_names:\n self.homes.append(i)\n\n def getGraph(self):\n return self.graph\n\n def getHomes(self):\n return self.homes","sub_path":"read_file.py","file_name":"read_file.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"211669948","text":"import os\nimport openpyxl\n\n\nclass ExcelIO:\n def __init__(self):\n self.workbook = None\n self.current_worksheet = None\n # used for testing\n self._force_project_name_on_read = None\n self._force_experiment_name_on_read = None\n\n def read_entire_data_from_current_sheet(self):\n sheet = self.current_worksheet\n data = []\n max_last_data_col = 0\n for row in sheet.iter_rows():\n empty_row = True\n values = []\n for cell in row:\n empty_row = empty_row and (not cell.value)\n if empty_row:\n print(\"encountered empty row at row_index = \" + str(len(data)) + \". \" +\n \"Assuming end of data at this location\")\n break\n for cell in row:\n value = cell.value\n try:\n if str(value).strip() == \"\" or (\"n/a\" in str(value).strip()):\n value = None\n except UnicodeEncodeError:\n pass\n if value and len(values) >= max_last_data_col:\n max_last_data_col = len(values) + 1\n values.append(value)\n data.append(values)\n if len(data[0]) > max_last_data_col:\n print(\"encountered empty col at col_index = \" + str(max_last_data_col) + \". \" +\n \"Assuming end of data at this location\")\n remake_data = []\n for row in range(0, len(data)):\n values = []\n data_row = data[row]\n for col in range(0, max_last_data_col):\n value = data_row[col]\n values.append(value)\n remake_data.append(values)\n data = remake_data\n if self._force_project_name_on_read:\n data[0][0] = \"PROJ: \" + self._force_project_name_on_read\n if self._force_experiment_name_on_read:\n data[1][0] = \"EXP: \" + self._force_experiment_name_on_read\n return data\n\n def write_data(self, path, data_row_list, worksheet_name=None):\n self.workbook = openpyxl.Workbook()\n self.current_worksheet = self.workbook.worksheets[0]\n if worksheet_name:\n self.current_worksheet.name = worksheet_name\n for row in range(0, len(data_row_list)):\n data_row = data_row_list[row]\n for col in range(0, len(data_row)):\n data_item = data_row[col]\n self.current_worksheet.cell(column=col + 1, row=row + 1, value=data_item)\n self.workbook.save(filename=path)\n\n def read_workbook(self, path):\n if not os.path.isfile(path):\n raise FileNotFoundError(path)\n self.workbook = openpyxl.load_workbook(filename=path)\n\n def sheet_name_list(self):\n return self.workbook.sheetnames\n\n def set_current_worksheet_by_index(self, index):\n sheet_name = self.workbook.sheetnames[index]\n self.current_worksheet = self.workbook[sheet_name]\n return self.current_worksheet\n\n def close(self):\n self.workbook.close()\n\n # these methods used for testing\n def force_project_name_for_testing(self, project_name):\n self._force_project_name_on_read = project_name\n\n # these methods used for testing\n def force_experiment_name_for_testing(self, experiment_name):\n self._force_experiment_name_on_read = experiment_name\n","sub_path":"mcetl/common/worksheet_data.py","file_name":"worksheet_data.py","file_ext":"py","file_size_in_byte":3435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"553767249","text":"from setuptools import setup, find_packages\nimport sys\n\nextra = {}\nif sys.version_info >= (3,):\n extra['use_2to3'] = True\n\nsetup(name=\"Panacea\",\n version=\"0.8.0\",\n description=\"Declarative Mapper for SQLAlchemy (Forked from Elixir)\", \n author=\"Juan Manuel Garcia\",\n author_email=\"jmg.utn@gmail.com\",\n url=\"https://github.com/jmg/Panacea/\",\n license = \"MIT License\",\n install_requires = [\n \"SQLAlchemy >= 0.5.0\"\n ],\n packages=find_packages(exclude=['ez_setup', 'tests', 'examples']),\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n \"Topic :: Database :: Front-Ends\",\n \"Topic :: Software Development :: Libraries :: Python Modules\"\n ],\n test_suite = 'nose.collector',\n **extra)\n","sub_path":"pypi_install_script/Panacea-0.8.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"233881714","text":"def copy(l1,l2=[]):\r\n\tif l1==[]:\r\n\t\treturn l2\r\n\telse:\r\n\t\tprint(type(l2))\r\n\t\tl2.append(l1[0])\r\n\t\tcopy(l1[1:],l2)\r\n\treturn l2\r\ndef main():\r\n\tl1=eval(input('Enter the list: '))\r\n\tprint(copy(l1))\r\n\r\nif __name__=='__main__':\r\n\tmain()\t\t\t\t","sub_path":"copy.py","file_name":"copy.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"613892684","text":"import re\nfrom io import BytesIO\nimport requests\nfrom PIL import Image\n\nfrom pytesseract import pytesseract\n\n\ndef get_code_text():\n r = session.get(url=img_url)\n img = Image.open(BytesIO(r.content))\n if is_save:\n img.save(\"D:\\\\data\\\\code{}.PNG\".format(mobile_no))\n image = img.convert('L')\n if is_save:\n image.save(\"D:\\\\data\\\\code_black{}.PNG\".format(mobile_no))\n pixels = image.load()\n # 【二值化】阀值:standard\n standard1, standard2 = (100, 170)\n # 【描边邻域降噪】阀值:standard\n for x in range(image.width):\n for y in range(image.height):\n if x >= image.width - 1 or y >= image.height - 1:\n # 边缘过滤\n pixels[x, y] = 255\n elif pixels[x, y] < standard2 and pixels[x + 1, y] < standard2 and pixels[x, y + 1] < standard2:\n # 深色并且粗线保留\n # 浅色加深\n pixels[x, y] = 0\n else:\n # 细线过滤\n pixels[x, y] = 255\n if is_save:\n image.save(\"D:\\\\data\\\\code_scan{}.PNG\".format(mobile_no))\n testdata_dir_config = '--tessdata-dir \"D:/Program Files (x86)/Tesseract-OCR/tessdata\"'\n text_code = pytesseract.image_to_string(image, lang='eng', config=testdata_dir_config)\n # 去掉非法字符,只保留字母数字\n return re.sub(\"\\W\", \"\", text_code)\n\n\ndef send_msg():\n mobile_params['imgVcode'] = text_code\n mobile_params['mobile'] = mobile_no\n r = session.post(mobile_url, params=mobile_params, timeout=10000)\n return r.text.strip()\n\n\ndef replace_host(headers):\n if type(headers) == str:\n return headers.replace(\"ptest.jinhui365.cn\", \"www.jinhui365.com\")\n else:\n for k in headers:\n headers[k] = headers[k].replace(\"ptest.jinhui365.cn\", \"www.jinhui365.com\")\n return headers\n\n\nif __name__ == '__main__':\n proxy = {\n 'https': '119.147.137.79:8008'\n }\n headers = {'Accept': 'application/json, text/javascript, */*; q=0.01',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',\n 'Connection': 'keep-alive',\n 'Content-Length': '90',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Host': 'ptest.jinhui365.cn',\n 'Origin': 'https://ptest.jinhui365.cn',\n 'Referer': 'https://ptest.jinhui365.cn/register/index',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36',\n 'X-Requested-With': 'XMLHttpRequest'}\n img_url = \"https://ptest.jinhui365.cn/kaptcha?action=kaptcha_register&35\"\n mobile_url = \"https://ptest.jinhui365.cn/vcode/mobile\"\n mobile_params = {'mobile': '11120190203',\n 'type': 'register',\n 'is_web_a': '2020',\n 'imgVcode': 'dhc8to',\n 'isCheckDup': 'true',\n 'isImgVcode': '1'}\n img_url = replace_host(img_url)\n mobile_url = replace_host(mobile_url)\n headers = replace_host(headers)\n\n mobile_base = 11120200001\n is_save = False\n session = requests.Session()\n session.headers = headers\n # session.verify = False\n session.proxies = proxy\n mobile_no = None\n text_code = None\n for i in range(10000):\n try:\n mobile_no = mobile_base + i\n text_code = get_code_text()\n # result = send_msg()\n print(mobile_no, text_code)\n except:\n print(\"继续\", mobile_no, text_code)\n","sub_path":"01_Python基础/爬虫/7发短信IP代理.py","file_name":"7发短信IP代理.py","file_ext":"py","file_size_in_byte":3646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"157684207","text":"import sys\nfrom naive_bayes_classifier import NaiveBayesClassifier\n\nif __name__ == \"__main__\":\n print(\"================ Classifying ============================\")\n print(\" \".join(sys.argv))\n if len(sys.argv) == 2:\n path = sys.argv[1]\n nbc = NaiveBayesClassifier()\n nbc.load(\"nbmodel.txt\")\n nbc.classify(path)\n elif len(sys.argv) == 3 and sys.argv[2] == \"-labeled\":\n path = sys.argv[1]\n nbc = NaiveBayesClassifier()\n nbc.load(\"nbmodel.txt\")\n nbc.classify(path, labeled=True)\n else:\n raise ValueError(\"Usage: nbclassify /path/to/data [-labeled]\")","sub_path":"HW1/nbclassify.py","file_name":"nbclassify.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"315065767","text":"#!/usr/bin/env python3\r\nfrom control import matlab\r\nimport control\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n\r\ndef bode_diagram():\r\n a=[]\r\n b=[]\r\n print(\"分子の最高次は?\")\r\n bunshi = int(input(\"入力:\"))\r\n print(\"分子の高次の項の係数を入れてください\")\r\n for i in range(bunshi+1):\r\n print(\"s^\",(bunshi-i),\"の係数を入力してください\",sep='')\r\n a.append(float(input(\"入力:\")))\r\n print('\\n') \r\n print(\"分母の最高次は?\")\r\n bunbo = int(input(\"入力:\"))\r\n print(\"分母の高次の項の係数を入れてください\")\r\n for i in range(bunbo+1):\r\n print(\"s^\",(bunbo-i),\"の係数を入力してください\",sep='')\r\n b.append(float(input(\"入力:\")))\r\n print('\\n') \r\n\r\n Ga=matlab.tf(a,b)\r\n print(Ga)\r\n fig=plt.figure()\r\n matlab.bode(Ga)\r\n plt.show()\r\n fig.savefig(\"ボード線図.jpg\")\r\n fig = plt.figure()\r\n matlab.nyquist(Ga)\r\n plt.show()\r\n fig.savefig(\"ナエキスト線図\")\r\n\r\ndef oresen():\r\n print(\"第13回の配布資料のボード線図の基本形にわけてください\\n何個基本形はありますか\")\r\n n=int(input())\r\n x=np.arange(0.001,100.0,0.01)\r\n x1=np.arange(0.001,100.0,0.01)\r\n q1=np.array([0.001,0.01,1,10,100])\r\n q=np.ones((n,4))\r\n w=np.ones((n,4))\r\n y=np.ones((n,10000))\r\n fig=plt.figure()\r\n ax=plt.subplot()\r\n ax.set_xscale('log')\r\n for i in range(n):\r\n print(i+1,\"個目の基本形はどれですか.以下の番号を入れてください.\\n0:G(s)=K, 1:G(s)=s, 2:G(s)=1/s,\\n3:Ts+1, 4:G(s)=1/(Ts+1)\")\r\n kihonkei=int(input(\"入力:\"))\r\n if kihonkei==0:\r\n print(\"Kの値は?\")\r\n k=float(input(\"入力:\"))\r\n q[i] = np.array([0.001, 0.01, 1, 10, 100])\r\n\r\n y[i]=np.ones(10000)\r\n y[i]=20*np.log10(np.abs(k))*y[i]\r\n w[i]=np.log10(w[i])\r\n #y[i]=(np.abs(k))*y[i]\r\n\r\n if kihonkei==1:\r\n q[i] = np.array([0.001, 0.01, 1, 10, 100])\r\n y[i]=20*np.log10(x)\r\n w[i]=90*np.log10(w[i]*10)\r\n\r\n if kihonkei==2:\r\n q [i]= np.array([0.001, 0.01,10, 100])\r\n y[i]=-20*np.log10(x)\r\n w[i]-90*np.log10(w[i]*10)\r\n\r\n if kihonkei ==3:\r\n print(\"Tの値は?\")\r\n T=float(input(\"入力:\"))\r\n num=np.count_nonzero(x < 1/T)\r\n num02=np.count_nonzero(x<0.2/T)\r\n num5=np.count_nonzero(x<5/T)\r\n a=np.zeros(num)\r\n a1=20*np.log10(x[num:10000])-20*np.log10(1/T)\r\n q[i] = np.array([0.01, 0.2/T, 5/T, 100])\r\n iso02=np.zeros(2)\r\n iso=45*np.log10(10)\r\n iso5=90*np.log10(10*np.ones(2))\r\n y[i]=np.hstack((a,a1))\r\n w[i]=np.hstack((iso02,iso5))\r\n print(\"1/T:\",1/T)\r\n print(\"0.2/T\",0.2/T)\r\n print(\"5/T\",5/T)\r\n \r\n if kihonkei==4:\r\n print(\"Tの値は?\")\r\n T=float(input())\r\n num=np.count_nonzero(x<=1/T)\r\n num=np.count_nonzero(x < 1/T)\r\n num02=np.count_nonzero(x<0.2/T)\r\n num5=np.count_nonzero(x<5/T)\r\n a=np.log10(np.ones(num))\r\n #a1=-20*np.log10(x[num:1000]-1/T)\r\n a1=-20*np.log10(x[num:10000])+20*np.log10(1/T)\r\n q[i] = np.array([0.01, 0.2/T, 5/T, 100])\r\n iso02=np.zeros(2)\r\n iso5=-90*np.log10(10*np.ones(2))\r\n y[i]=np.hstack((a,a1))\r\n w[i]=np.hstack((iso02,iso5))\r\n print(\"1/T:\",1/T)\r\n print(\"0.2/T\",0.2/T)\r\n print(\"5/T\",5/T)\r\n for i in range(n):\r\n ax.plot(x,y[i])\r\n z=np.zeros(10000)\r\n for i in range(n):\r\n z+=y[i]\r\n ax.plot(x,z,color='red')\r\n print('赤色が回答です')\r\n plt.show()\r\n fig.savefig(\"ボード線図手書き.jpg\")\r\n fig = plt.figure()\r\n ax = plt.subplot()\r\n ax.set_xscale('log')\r\n for i in range(n):\r\n ax.plot(q[i],w[i])\r\n z=np.zeros(4)\r\n #for i in range(n):\r\n # z+=w[i]\r\n #ax.plot(q1,z,color='red')\r\n plt.show()\r\n fig.savefig(\"位相図.jpg\")\r\n print(\"合成するのがめんどくさいので後は気を付けて合成してください.\\n例えば重なり合ってるとわからないためボード線図(曲線)と比較してください.\")\r\n\r\ndef hurwitz():\r\n \r\n print(\"分母の最高次は?\")\r\n saikouzi=int(input(\"入力:\"))\r\n a=np.ones(saikouzi+1)\r\n delta=np.ones(saikouzi)\r\n for i in range(saikouzi+1):\r\n print(saikouzi-i,\"次の係数は?\")\r\n a[saikouzi-i]=float(input(\"入力:\"))\r\n for i in range(saikouzi):\r\n if i==0:\r\n delta[i]=a[saikouzi-1]\r\n if i==1:\r\n if saikouzi==2:\r\n matrix=[[a[saikouzi-1],0],[a[saikouzi],a[saikouzi-2]]]\r\n else:\r\n matrix=[[a[saikouzi-1],a[saikouzi-3]],[a[saikouzi],a[saikouzi-2]]]\r\n delta[i]=np.linalg.det(matrix)\r\n if i==2:\r\n if saikouzi==3:\r\n matrix=[[a[saikouzi-1],a[saikouzi-3],0],[a[saikouzi],a[saikouzi-2],0],[0,a[saikouzi-1],a[saikouzi-3]]]\r\n if saikouzi==4:\r\n matrix=[[a[saikouzi-1],a[saikouzi-3],0],[a[saikouzi],a[saikouzi-2],a[saikouzi-4]],[0,a[saikouzi-1],a[saikouzi-3]]]\r\n delta[i]=np.linalg.det(matrix)\r\n if i==3:\r\n matrix=matrix=[[a[saikouzi-1],a[saikouzi-3],0,0],[a[saikouzi],a[saikouzi-2],a[saikouzi-4],0],[0,a[saikouzi-1],a[saikouzi-3],0],[0,a[saikouzi],a[saikouzi-2],a[saikouzi-4]]]\r\n delta[i]=np.linalg.det(matrix)\r\n print(\"左から順にΔ1 , Δ2 , Δ3 , ...\",delta)\r\n \r\n\r\n \r\n\r\n \r\nwhile 1:\r\n print(\"行いたい処理を以下から選んでください\")\r\n print(\"0:終了 1:ボード線図を描く 2:ボード線図を折れ線で書く 3:フルビッツの方法(4次まで)\")\r\n select=int(input())\r\n if select==0:\r\n exit(0)\r\n if select==1:\r\n print(\"分子と分母について以下に従って入力してください.分解する必要はないですが,分子と分母はそれぞれ展開してください.\")\r\n bode_diagram()\r\n print(\"\\n\")\r\n if select==2:\r\n print(\"分子と分母について以下に従って入力してください.分解して基本形が複数掛け算されている状態にしてください\")\r\n oresen()\r\n print(\"\\n\")\r\n \r\n if select==3:\r\n print(\"4次までにしてください.例外処理してないため,5次以降は計算がおかしくなります.\")\r\n hurwitz()\r\n print(\"\\n\")\r\n else:\r\n pass\r\n\r\n\r\n\r\n \r\n","sub_path":"controlengineering.py","file_name":"controlengineering.py","file_ext":"py","file_size_in_byte":6805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"437443959","text":"from txxx.model.user import User\n\n\ndef test_login(app):\n app.start_test({'name': '', 'build': '', 'project': \"\", 'browserstack.debug': True})\n app.go_to_menu()\n app.login(User.admin())\n app.go_to_menu()\n assert app.is_logged_in()\n app.quit_test()","sub_path":"txxx_mob/test_case/memberzone/test_login.py","file_name":"test_login.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"261349284","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n#Import the necessary modules \nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas\nimport math\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import mean_squared_error\nimport datetime\nfrom keras.layers import Embedding\nfrom keras.models import load_model\n\n\n# In[33]:\n\n\n# Tolerance Limit for computing the accuracy\ntolerance_limit = 5\n# Device count for determining the number of devices to extract the data \ndeviceCount = 4\n# Metric count for determining the count of the metric to perform the model computations \nmetricCount = 2\n# Device Ids to extract the data \ndevice_ids = ['2421540','1640315','1833973','1478336']\n\n\n# In[3]:\n\n\n#Read the csv file as the input \ndf = pandas.read_csv('combined0917-1001.csv', engine='python')\n# Delete the unknown columns\ndel df['unknown']\n# Get the metric name column from the pandas dataframe \ndf['metric_name'] = pandas.Categorical(df.metric_name)\n\n\n# In[4]:\n\n\n# Get all the rows whose metric name is utilization \ndf = df[df['metric_name']=='utilization']\n# Convert the time from the linux epoch time to date time format \ndf['poller_time']=df['poller_time'].apply(lambda x :datetime.datetime.fromtimestamp(x).strftime('%c'))\n\n\n# In[34]:\n\n\n# Define a dictionary with all the metric names to defined \ndata = {'poller_time':[],'metric_name':[]} \n# Add the devices to the dictionaries \nfor device in device_ids:\n data[device] = []\n\n\n# In[6]:\n\n\n# Createa a data frame from the created dictionary\ndf1 = pandas.DataFrame(data) \n\nrow_count = 0\ncol = 0\n\n# ITterate over the rows in the existing dataframe by getting the metrics for a device count\nfor row in range(0,df.count()[0],deviceCount):\n new_row = []\n new_row.append(df.iloc[row,0])\n # Iterate over each device Count \n for i in range(deviceCount):\n new_row.append(df.iloc[row,2])\n row = row + 1\n new_row.append('utilization')\n # Convert the pandas data frame to a pandas series\n ps = pandas.Series(new_row, index=['poller_time','2421540.0','1640315.0','1833973.0','1478336.0','metric_name'])\n # Append the pandas series to a data frame \n df1 = df1.append(ps, ignore_index=True)\n\n\n# In[7]:\n\n\n# Ignore the dataframe indexes \ndataset = df1.values\n\n\n# In[8]:\n\n\ndef plotData(dataset):\n \"\"\"\n Function to plot the data to identify the graph trends \n : param : dataset - pandas dataframe \n \"\"\"\n # Create a list to store the data set for the devices \n poller_time = []\n device_1 = []\n device_2 = []\n device_3 = []\n device_4 = []\n timeStep = []\n \n # Add the values to a list to display the graph \n var = 0\n # Iterate over all the rows in the dataset \n for row in dataset:\n # Var to print the timestep \n var += 1\n # Append the timestep\n timeStep.append(var)\n # Append the poller time \n poller_time.append(row[0])\n # Append the corresponding devices \n device_1.append(row[1])\n device_2.append(row[2])\n device_3.append(row[3])\n device_4.append(row[4])\n # Plot the data \n plt.figure(1)\n plt.plot(timeStep,device_1)\n plt.show()\n\n# Invoke the function\nplotData(dataset)\n\n\n# In[9]:\n\n\n# split into train and test sets\ntrain_size = int(len(dataset) * 0.99)\n\n# Determine the testsize \ntest_size = len(dataset) - train_size\n\n# Obtain the train and the test size \ntrain, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:]\nprint(len(train), len(test))\n\n\n# In[10]:\n\n\n# convert an array of values into a dataset matrix\ndef create_dataset(dataset, look_back=1):\n \"\"\"\n Function to create a dataset based on the look back \n :dataset - Input dataset with the necessary metrics \n :lookback - how many data points to view back \n \"\"\"\n # Create the list to store the input data point and the output labels \n dataX, dataY = [], []\n # Iterate over the dataset with the lookback \n for i in range(len(dataset)-look_back-1):\n a = dataset[i:(i+look_back)]\n a = a[0][1:-1]\n # Append the input data set \n dataX.append(a)\n # Append the label \n dataY.append(dataset[i + look_back][1:-1])\n # Return the numpy array of the result \n return np.array(dataX, dtype='float'), np.array(dataY)\n\n\n# In[11]:\n\n\ndef split_sequences(sequences, n_steps):\n \"\"\"\n Function to split the sequences \n \"\"\"\n X, y, y_2, y_3 = list(), list(), list(), list()\n for i in range(len(sequences)):\n # find the end of this pattern\n end_ix = i + n_steps\n # check if we are beyond the dataset\n if end_ix+2 >= len(sequences):\n break\n # gather input and output parts of the pattern\n seq_x, seq_y = sequences[i:end_ix, -5:-1], sequences[end_ix, -5:-1]\n # Get the sequence 2 timestep \n seq_y_time_step_2 = sequences[end_ix+1,-5:-1]\n #Get the sequence 3 timestep \n seq_y_time_step_3 = sequences[end_ix+2,-5:-1]\n # Append the datasets into the corresponding values \n X.append(seq_x)\n y.append(seq_y)\n y_2.append(seq_y_time_step_2)\n y_3.append(seq_y_time_step_3)\n # Return the numpy arrays\n return np.array(X), np.array(y), np.array(y_2), np.array(y_3)\n\n\n# In[12]:\n\n\n# Lookback = 1, hyperparameter to tune for\nlook_back = 1\n# Invoke create dataset function for the train dataset \ntrainX, trainY = create_dataset(train, look_back)\n# Invoke the create dataset function for the test dataset \ntestX, testY = create_dataset(test, look_back)\nprint(np.shape(trainX))\n# Append the train dataset horizontally \ntrain_up = np.hstack((trainX,trainY))\nprint(np.shape(train_up))\n# Append the test dataset horizontally\ntest_up = np.hstack((testX,testY))\nprint(np.shape(test_up))\n\n\n# In[13]:\n\n\n# Invoke the split sequences function on the train dataset \ntrainX_updated = split_sequences(train_up,10)\nprint(np.shape(trainX_updated[0]))\n# Invoke the split sequences on the test dataset \ntestX_updated = split_sequences(test_up,10)\nprint(np.shape(testX_updated[0]))\n# For the 3 time steps get the train and the test dataset separately \ntrainX_data = trainX_updated[0]\ntrainY_data = trainX_updated[1]\ntrainY_data_1 = trainX_updated[2]\ntrainY_data_2 = trainX_updated[3]\ntestX_data = testX_updated[0]\ntestY_data = testX_updated[1]\ntestY_data_1 = testX_updated[2]\ntestY_data_2 = testX_updated[3]\n\n\n# In[14]:\n\n\n# Printing the values \nprint(testX_data[0])\nprint(testY_data[0])\nprint(testY_data_1[0])\nprint(testY_data_2[0])\n\n\n# In[15]:\n\n\n# create and fit the LSTM network using the Keras library \nmodel = Sequential()\n# Add an LSTM layer with 100 hidden layer LSTMs, activation as Relu , return sequence = True - indicates the addition of another layer \nmodel.add(LSTM(100, input_shape=(10,4), return_sequences=True, activation='relu'))\n# Add an LSTM layer with 100 hidden layer LSTMs, activation as Relu , return sequence = True - indicates the addition of another layer \nmodel.add(LSTM(100, input_shape=(10,4), return_sequences=True, activation='relu'))\n# Add an LSTM layer with 100 hidden layer LSTMs, activation as Relu , the output of which will be passed to a dense fully connected layer \nmodel.add(LSTM(100, input_shape=(10,4), activation='relu'))\n# Add a fully connected layer at the end of the LSTM\nmodel.add(Dense(4))\n# Use the MSE loss and adam optimizer \nmodel.compile(loss='mse', optimizer='adam', metrics=['accuracy'])\nprint(model.summary())\nmax_eval = 100\ncount = 0\n# Train the model for 150 epochs \nfor ep in range(150):\n print(\"Epoch Number : %s\" %count)\n count = count + 1\n # For every epoch fit the train data \n model.fit(trainX_data, trainY_data, epochs=1,batch_size=32, verbose=2)\n print(model.evaluate(testX_data,testY_data))\n # Determine the test mse \n eval = model.evaluate(testX_data,testY_data)[0]\n # If the test mse is less than the previous mse\n if(eval < max_eval):\n # Save the model parameters \n print(\"Saving Model Parameter\")\n model.save('model_params.hd5')\n max_eval = eval\n\n\n# In[16]:\n\n\nprint(\"Loading Model Parameters\")\nmodel = load_model('model_params.hd5')\n# Evaluvate the model on the test data \nmodel.evaluate(testX_data,testY_data)\n\n\n# In[17]:\n\n\n#Update the font size in the matplot lib\nplt.rcParams.update({'font.size': 8})\n# Predict the output for the test data at time step 1 \noutput = model.predict(testX_data)\nprint(output[0])\nprint(testX_data[0].shape)\n# Iterate over the test data 3D tensor\nfor count in range(len(testX_data)):\n # Stack the output to the test data\n testX_data_temp = np.vstack([testX_data[count],output[count]])\n testX_data[count] = testX_data_temp[1:,:]\nprint(testX_data.shape)\n\n# Predict the output for the test data at time step 2 \noutput_1 = model.predict(testX_data)\n# Iterate over the test data 3D tensor\nfor count in range(len(testX_data)):\n # Stack the output to the test data\n testX_data_temp = np.vstack([testX_data[count],output_1[count]])\n testX_data[count] = testX_data_temp[1:,:]\n# Predict the output model for the time step 3 \noutput_2 = model.predict(testX_data)\nprint(output[0])\nprint(testY_data[0])\nprint(output_1[0])\nprint(testY_data_1[0])\nprint(output_2[0])\nprint(testY_data_2[0])\n\n# Define the list to print the data \ntimeStep = []\nvarCount = 0\ndevice_1_out = []\ndevice_1_true_label = []\ndevice_1_out_1 = []\ndevice_1_true_label_1 = []\ndevice_1_out_2 = []\ndevice_1_true_label_2 = []\n\n# Iterate over the predicted output to actual values \nfor out in range(output.shape[0]):\n timeStep.append(varCount)\n varCount += 1\n device_1_out.append(output[out,3])\n device_1_true_label.append(testY_data[out,3])\n device_1_out_1.append(output_1[out,3])\n device_1_true_label_1.append(testY_data_1[out,3])\n device_1_out_2.append(output_2[out,3])\n device_1_true_label_2.append(testY_data_2[out,3])\n \n# Plot the output using matplot lib \n# Plot the actual and the predicted label \n# Save the figure in the plot.png\n\nplt.figure(1)\nplt.plot(timeStep,device_1_out, color = 'blue', label='Predicted CPU Utilization')\nplt.plot(timeStep,device_1_true_label, color='red', label='Actual CPU Utilization')\nplt.ylabel(\"CPU Utilization\")\nplt.xlabel(\"Time step 1\")\nplt.title(\"CPU Utlization vs Time\")\nplt.legend()\nplt.savefig(\"plot.png\")\n\nplt.figure(2)\nplt.plot(timeStep,device_1_out_1, color = 'blue', label='Predicted CPU Utilization')\nplt.plot(timeStep,device_1_true_label_1, color='red', label='Actual CPU Utilization')\nplt.ylabel(\"CPU Utilization\")\nplt.xlabel(\"Time step 2\")\nplt.title(\"CPU Utlization vs Time\")\nplt.legend()\nplt.savefig(\"plot_1.png\")\n\nplt.figure(3)\nplt.plot(timeStep,device_1_out_2, color = 'blue', label='Predicted CPU Utilization')\nplt.plot(timeStep,device_1_true_label_2, color='red', label='Actual CPU Utilization')\nplt.ylabel(\"CPU Utilization\")\nplt.xlabel(\"Time step 3\")\nplt.title(\"CPU Utlization vs Time\")\nplt.legend()\nplt.savefig(\"plot_2.png\")\n\nplt.show()\n\n\n# In[31]:\n\n\n# Compute the Accuracy of the model \nmse_list = []\nacc_1 = 0\nacc_2 = 0\nacc_3 = 0\n\n# Iterate over the predicted and the actual values to determing the accuracies\n# Accuracy for time step 1\nfor predicted,actual_values in zip(device_1_out,device_1_true_label):\n if(abs(predicted - actual_values) <= tolerance_limit):\n acc_1 += 1\n \n# Accuracy for time step 2 \nfor predicted,actual_values in zip(device_1_out_1,device_1_true_label_1):\n if(abs(predicted - actual_values) <= tolerance_limit):\n acc_2 += 1 \n\n# Accuracy for time step 3\nfor predicted,actual_values in zip(device_1_out_2,device_1_true_label_2):\n if(abs(predicted - actual_values) <= tolerance_limit):\n acc_3 += 1 \n\nprint(\"TimeStep 1 Accuracy: %.2f\"%(acc_1/len(device_1_out)))\nprint(\"TimeStep 2 Accuracy: %.2f\"%(acc_2/len(device_1_out_1)))\nprint(\"TimeStep 3 Accuracy: %.2f\"%(acc_3/len(device_1_out_2)))\n\n","sub_path":"rdx-project-2019-fall/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":11913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"61882146","text":"from pathlib import Path\nimport os\nimport stat # it is actually in use as a part of the eval function: exec_permission = eval(set_perm_value.strip())\nimport traceback\nimport time\nimport xlrd\nfrom utils import global_const as gc\nfrom utils import common as cm\nfrom utils import common2 as cm2\nfrom utils import setup_logger_common\nfrom utils import ConfigData\nfrom file_load import File\nfrom file_load.file_error import RequestError\nfrom data_retrieval import DataSource, DataSourceDB, DBAccess\nfrom data_retrieval import Attachment\nfrom forms import SubmissionPackage\nimport xlwt\n\n\nclass Request(File):\n\n def __init__(self, filepath, main_cfg, file_type=2, sheet_name=''):\n\n # load_configuration (main_cfg_obj) # load global and local configureations\n\n File.__init__(self, filepath, file_type)\n\n if main_cfg:\n self.conf_main = main_cfg\n else:\n self.conf_main = ConfigData(gc.CONFIG_FILE_MAIN)\n # if cfg_path=='':\n # self.conf_main = ConfigData(gc.CONFIG_FILE_MAIN)\n # else:\n # self.conf_main = ConfigData(cfg_path)\n\n self.error = RequestError(self)\n\n self.log_handler = None\n self.logger = self.setup_logger(self.wrkdir, self.filename)\n self.logger.info('Start working with Submission request file {}'.format(filepath))\n\n # self.file_dict = OrderedDict()\n # self.rows = OrderedDict()\n\n self.columnlist = []\n self.samples = []\n self.sub_aliquots = []\n self.disqualified_sub_aliquots = {}\n self.aliquots_to_subaliquots_map = {} # holds the map of aliquots to sub-aliquots for interpreting DB responses\n self.disqualified_request_path = '' # will store path to a request file with disqualified sub-aliquots\n self.project = ''\n self.bulk_location = ''\n self.assay = ''\n self.center = ''\n self.center_id = None\n self.center_code = None\n self.experiment_id = ''\n self.data_source_names = ''\n self.data_source_objects = {} # dictionary to store all collected data sources for the request\n\n self.aliquots = None\n self.qualified_aliquots = None\n self.raw_data = None\n self.assay_data = None\n self.attachments = None\n self.submission_forms = None\n self.submission_package = None\n self.data_source_names = None\n # will hold value corresponding to the type of data source being used (attachments are not ignored)\n # possible value 'db' and 'file'. The value of the variable being set based on the first data source being used\n self.data_source_forms_assignment = None\n\n # self.sheet_name = ''\n self.sheet_name = sheet_name.strip()\n if not self.sheet_name or len(self.sheet_name) == 0:\n # if sheet name was not passed as a parameter, try to get it from config file\n self.sheet_name = gc.REQUEST_EXCEL_WK_SHEET_NAME # 'wk_sheet_name'\n # print (self.sheet_name)\n self.logger.info('Data will be loaded from worksheet: \"{}\"'.format(self.sheet_name))\n\n self.conf_assay = None\n\n self.get_file_content()\n\n def get_file_content(self):\n if not self.columnlist:\n if cm.file_exists(self.filepath):\n self.logger.debug('Loading file content of \"{}\"'.format(self.filepath))\n\n with xlrd.open_workbook(self.filepath) as wb:\n if not self.sheet_name or len(self.sheet_name) == 0:\n # by default retrieve the first sheet in the excel file\n sheet = wb.sheet_by_index(0)\n else:\n # if sheet name was provided\n sheets = wb.sheet_names() # get list of all sheets\n if self.sheet_name in sheets:\n # if given sheet name in the list of available sheets, load the sheet\n sheet = wb.sheet_by_name(self.sheet_name)\n else:\n # report an error if given sheet name not in the list of available sheets\n _str = ('Given worksheet name \"{}\" was not found in the file \"{}\". '\n 'Verify that the worksheet name exists in the file.').format(\n self.sheet_name, self.filepath)\n self.error.add_error(_str)\n self.logger.error(_str)\n\n self.lineList = None\n self.loaded = False\n return self.lineList\n\n sheet.cell_value(0, 0)\n\n lines = [] # will hold content of the request file as an array of arrays (rows)\n for i in range(sheet.ncols):\n column = []\n for j in range(sheet.nrows):\n if i == 0:\n lines.append([]) # adds an array for each new row in the request file\n\n # print(sheet.cell_value(i, j))\n cell = sheet.cell(j, i)\n cell_value = cell.value\n # take care of number and dates received from Excel and converted to float by default\n if cell.ctype == 2 and int(cell_value) == cell_value:\n # the key is integer\n cell_value = str(int(cell_value))\n elif cell.ctype == 2:\n # the key is float\n cell_value = str(cell_value)\n # convert date back to human readable date format\n # print ('cell_value = {}'.format(cell_value))\n if cell.ctype == 3:\n cell_value_date = xlrd.xldate_as_datetime(cell_value, wb.datemode)\n cell_value = cell_value_date.strftime(\"%Y-%m-%directory\")\n column.append(cell_value) # adds value to the current column array\n lines[j].append('\"' + str(cell_value) + '\"') # adds value in \"csv\" format for a current row\n\n # self.columnlist.append(','.join(column))\n self.columnlist.append (column) # adds a column to a list of columns\n\n # populate lineList property\n self.lineList = []\n for ln in lines:\n self.lineList.append(','.join(ln))\n\n wb.unload_sheet(sheet.name)\n\n # load passed request parameters (by columns)\n self.get_request_parameters()\n\n # validate provided information\n self.logger.info('Validating provided request parameters. project: \"{}\", bulk location: \"{}\", '\n 'assay: \"{}\", db_center_code_or_id: \"{}\",'\n 'Sub-Aliquots: \"{}\"'\n .format(self.project, self.bulk_location, self.assay, self.center,\n self.sub_aliquots))\n self.validate_request_params()\n\n if self.error.exist():\n # report that errors exist\n self.loaded = False\n # print(self.error.count)\n # print(self.error.get_errors_to_str())\n _str = 'Errors ({}) were identified during validating of the request. \\nError(s): {}'.format(\n self.error.count, self.error.get_errors_to_str())\n else:\n self.loaded = True\n _str = 'Request parameters were successfully validated - no errors found.'\n self.logger.info(_str)\n\n # combine Experiment_id out of request parameters\n if self.center_code and len(self.center_code.strip()) > 0:\n # use center code if available\n self.experiment_id = \"_\".join([self.project, self.center_code, self.assay])\n else:\n # use provided value for the center column from request, if center_code is not available\n self.experiment_id = \"_\".join([self.project, self.center, self.assay])\n\n else:\n _str = 'Loading content of the file \"{}\" failed since the file does not appear to exist\".'.format(\n self.filepath)\n self.error.add_error(_str)\n self.logger.error(_str)\n\n self.columnlist = None\n self.lineList = None\n self.loaded = False\n return self.lineList\n\n # get all values provided in the request file\n def get_request_parameters(self):\n self.project = self.columnlist[0][1]\n self.bulk_location = self.columnlist[1][1]\n self.assay = self.columnlist[2][1].lower()\n self.center = self.columnlist[3][1] # center code (if alpha numeric) or center id (if numeric)\n self.sub_aliquots = self.columnlist[4]\n if self.sub_aliquots and len(self.sub_aliquots) > 0:\n self.sub_aliquots.pop(0) # get rid of the column header\n # self.samples = self.columnlist[5]\n # if self.samples and len(self.samples) > 0:\n # self.samples.pop(0) # get rid of the column header\n\n # validates provided parameters (loaded from the submission request file)\n def validate_request_params(self):\n _str_err = ''\n _str_warn = ''\n if len(self.sub_aliquots) == 0:\n _str_err = '\\n'.join([_str_err, 'List of provided sub-samples is empty. '\n 'Aborting processing of the submission request.'])\n # Check if empty sub-samples were provided\n if '' in self.sub_aliquots:\n i = 0\n cleaned_cnt = 0\n for s in self.sub_aliquots:\n # check for any empty sub-aliquot values and remove them\n if len(s.strip()) == 0:\n self.sub_aliquots.pop(i)\n cleaned_cnt += 1\n else:\n i += 1\n if cleaned_cnt > 0:\n _str_warn = '\\n'.join([_str_warn, 'Empty sub-aliqouts (count = {}) were removed from the list. '\n 'Here is the list of sub-aliqouts after cleaning (count = {}): \"{}\" '\n .format(cleaned_cnt, len(self.sub_aliquots), self.sub_aliquots)])\n # check for empty values\n if len(self.project) == 0:\n _str_err = '\\n'.join(\n [_str_err, 'No Program name was provided. Aborting processing of the submission request.'])\n if len(self.bulk_location) == 0:\n _str_err = '\\n'.join([_str_err,\n 'No Bulk Location was provided. Aborting processing of the submission request.'])\n if len(self.assay) == 0:\n _str_err = '\\n'.join([_str_err, 'No Assay was provided. Aborting processing of the submission request.'])\n if len(self.center) == 0:\n _str_err = '\\n'.join(\n [_str_err, 'No DB Center information was provided. Aborting processing of the submission request.'])\n\n # check for values that should match some predefined values from a dictionary\n # check assay value\n if not cm2.key_exists_in_dict(self.assay, 'assay'):\n _str_err = '\\n'.join([_str_err, 'Provided Assay name \"{}\" is not matching a list of expected assay names '\n '(as stored in \"{}\" dictionary file). '\n 'Aborting processing of the submission request.'\n .format(self.assay, gc.CONFIG_FILE_DICTIONARY)])\n else:\n # if provided assay name is expected, convert it to the name expected by the Submission logic\n self.assay = cm2.get_dict_value(self.assay, 'assay')\n\n # check project value\n if not cm2.key_exists_in_dict(self.project.lower(), 'project'):\n _str_err = '\\n'.join(\n [_str_err, 'Provided Program name \"{}\" is not matching a list of expected names '\n '(as stored in \"{}\" dictionary file). '\n 'Aborting processing of the submission request.'\n .format(self.project, gc.CONFIG_FILE_DICTIONARY)])\n else:\n # if provided assay name is expected, convert it to the name expected by the Submission logic\n self.project = cm2.get_dict_value(self.project.lower(), 'project')\n\n # validate center_code or center_id value\n self.logger.info ('Start validation of center value \"{}\" provided in the request'.format(self.center))\n db = DBAccess (self.logger, self.error, self.conf_main) # create DBAccess object\n db.open_connection()\n # test center value assuming center code was provided\n dataset = db.validate_center_code(self.center, self.project, 'code', 'code')\n _str_err_out1, center_id_out1 = self.check_validation_dataset_outcome(dataset, 'center_id', 'center_code')\n if center_id_out1:\n # center id was returned, meaning center was validated fine\n self.center_id = center_id_out1\n # get center code value from the current DB dataset\n _str_err_out3, center_code = self.get_field_value_from_dataset(dataset, 'center_code')\n if center_code:\n # center code retrieved OK\n self.center_code = center_code\n else:\n # report an error during retrieving center_code\n _str_err = '\\n'.join([_str_err, _str_err_out3])\n else:\n # if center code was not validated at first attempt, validate it assuming the center id was given\n dataset = db.validate_center_code(self.center, self.project, 'id', 'code')\n _str_err_out2, center_id_out2 = self.check_validation_dataset_outcome(dataset, 'center_id', 'center_id')\n if center_id_out2:\n # center id was validated at the 2nd attempt, ignore the 1st failed center code validation\n self.center_id = center_id_out2\n # get center code value from the current DB dataset\n _str_err_out3, center_code = self.get_field_value_from_dataset(dataset, 'center_code')\n if center_code:\n # center code retrieved OK\n self.center_code = center_code\n else:\n # report an error during retrieving center_code\n _str_err = '\\n'.join([_str_err, _str_err_out3])\n else:\n # center validation attempts failed, report both failures\n _str_err = '\\n'.join([_str_err, _str_err_out1, _str_err_out2])\n\n # get list of aliquots from list of sub-aliquots\n self.aliquots = [cm2.convert_sub_aliq_to_aliquot(al, self.assay) for al in self.sub_aliquots]\n\n # create a map to convert aliquot value to sub_aliquot value (for processing DB responses given for aliquots)\n for sa, a in zip(self.sub_aliquots, self.aliquots):\n self.aliquots_to_subaliquots_map[a] = sa\n\n if self.center_id:\n self.logger.info('Start validation of aliquot ids vs DB')\n # if center id was validated in the above code, validate received aliquots vs manifest dataset in DB\n dataset = db.validate_aliquot_ids(self.center_id, self.aliquots)\n if dataset:\n # create dictionary of received aliquots/sample ids\n aliquots_to_samples_map = {}\n for row in dataset:\n if '_aliquot_id' in row and '_sample_id' in row:\n aliquots_to_samples_map[row['_aliquot_id']] = row['_sample_id']\n # check if each aliquot id was returned from a database and get the sample id from the dataset\n for sa, a in zip(self.sub_aliquots, self.aliquots):\n if a in aliquots_to_samples_map:\n if len(str(aliquots_to_samples_map[a]).strip()) > 0:\n self.samples.append(aliquots_to_samples_map[a])\n else:\n _str = 'Blank Sample Id value was returned from DB for the sub-aliquot id \"{}\". ' \\\n 'The sub-aliquot was disqualified'.format(sa)\n self.disqualify_sub_aliquot(sa, _str)\n _str_warn = '\\n'.join([_str_warn, _str])\n else:\n _str = 'Sub-aliquot id \"{}\" was not found in the database and was disqualified'.format(sa)\n self.disqualify_sub_aliquot(sa, _str)\n _str_warn = '\\n'.join([_str_warn, _str])\n else:\n _str_err = '\\n'.join(\n [_str_err, 'Aliquot ids cannot be validated since no data was returned from DB for '\n 'center_id = \"{}\" and aliquot ids as following: {} '\n .format(self.center_id, self.aliquots)])\n db = None\n\n # report any collected errors\n if len(_str_err) > 0:\n _str_err = 'Validation of request parameters:' + _str_err\n self.error.add_error(_str_err)\n self.logger.error(_str_err)\n # report any collected warnings\n if len(_str_warn) > 0:\n _str_warn = 'Validation of request parameters:' + _str_warn\n self.logger.warning(_str_warn)\n\n def check_validation_dataset_outcome(self, dataset, validation_id_column, validation_id_name):\n _str_err = ''\n row_num = 1\n validation_id_out = None\n if dataset:\n if len(dataset) >= row_num:\n row = dataset[row_num - 1] # get the first row of the dataset\n if 'status' in row:\n status = row['status']\n if 'description' in row:\n description = row['description']\n if validation_id_column in row: # center_id\n validation_id = row[validation_id_column]\n if status == 'OK': # validation was successful\n validation_id_out = validation_id\n elif status == 'Failed': # validation has failed\n _str_err = '\\n'.join(\n [_str_err, 'Validation of the provided {} value vs DB has Failed, description: {}'\n .format(validation_id_name, description)])\n else: # unexpected status value was returned\n _str_err = '\\n'.join(\n [_str_err, 'Validation of the provided {} value vs DB returned unexpected status {}'\n .format(validation_id_name, status)])\n else:\n _str_err = '\\n'.join(\n [_str_err, 'Unexpected error was reported during validating {} in the DB. '\n 'Check earlier entries in the log file.'.format(validation_id_name)])\n\n return _str_err, validation_id_out\n\n def get_field_value_from_dataset(self, dataset, field_name, row_num = None):\n # set default values\n if row_num is None:\n row_num = 1 # default row is #1\n\n _str_err = ''\n value_out = None\n if dataset:\n if len(dataset) >= row_num:\n row = dataset[row_num - 1]\n if field_name in row:\n value_out = row[field_name]\n else:\n _str_err = '\\n'.join(\n [_str_err, 'Unexpected error was reported during retrieving value of \"{}\" (row #{})from the dataset. '\n .format(field_name, row_num)])\n\n return _str_err, value_out\n\n def setup_logger(self, wrkdir, filename):\n\n # m_cfg = ConfigData(gc.CONFIG_FILE_MAIN)\n\n log_folder_name = gc.REQ_LOG_DIR # gc.LOG_FOLDER_NAME\n\n # m_logger_name = gc.MAIN_LOG_NAME\n # m_logger = logging.getLogger(m_logger_name)\n\n logger_name = gc.REQUEST_LOG_NAME\n logging_level = self.conf_main.get_value('Logging/request_log_level')\n\n # if a relative path provided, convert it to the absolute address based on the application working dir\n if not os.path.isabs(log_folder_name):\n log_folder_path = Path(wrkdir) / log_folder_name\n else:\n log_folder_path = Path(log_folder_name)\n\n lg = setup_logger_common(logger_name, logging_level,\n log_folder_path, # Path(wrkdir) / log_folder_name,\n str(filename) + '_' + time.strftime(\"%Y%m%d_%H%M%S\", time.localtime()) + '.log')\n\n self.log_handler = lg['handler']\n return lg['logger']\n\n def load_request_configuration(self):\n # update main config file with the project/environmetn specific details from additional config files\n self.load_project_config_into_main(self.project) # loads project specific config and merges it into main config\n # load project specific assay config file\n self.conf_assay = self.load_assay_conf(self.assay, self.project)\n if self.conf_assay:\n # update loaded assay config file with project/environment specific config assay_locatoin_config.yaml\n self.conf_assay = self.update_cfg_dictionary_with_location_details(gc.CONFIG_FILE_ASSAY_LOCATION,\n self.project, self.conf_assay)\n\n def process_request(self):\n self.data_source_names = cm.get_value_from_dictionary('data_sources', self.conf_assay) # self.conf_assay['data_sources']\n\n # path to the folder where created submission packages will be located.\n # since this location can be provided in the project config file, this assignment is happening\n # after loading the project config\n gc.OUTPUT_PACKAGES_DIR = self.conf_main.get_value('Submission_location/output_packages')\n\n for data_source_name in self.data_source_names:\n # if isinstance(data_source_name, tuple)\n if isinstance(data_source_name, str):\n if data_source_name == 'attachment':\n self.attachments = Attachment(self)\n elif data_source_name[-3:] == \"_db\":\n self.data_source_objects[data_source_name] = DataSourceDB(self, data_source_name, data_source_name)\n if not self.data_source_forms_assignment:\n self.data_source_forms_assignment = 'db'\n else:\n self.data_source_objects[data_source_name] = DataSource(self, data_source_name, data_source_name)\n if not self.data_source_forms_assignment:\n self.data_source_forms_assignment = 'file'\n elif isinstance(data_source_name, tuple):\n if data_source_name[0][-3:] == \"_db\":\n self.data_source_objects[data_source_name[0]] = DataSourceDB(self, data_source_name[0],\n data_source_name[1])\n else:\n self.data_source_objects[data_source_name[0]] = DataSource(self, data_source_name[0],\n data_source_name[1])\n else:\n self.logger.error('Provided data source name ({}) is of unexpected format and cannot be processed.'\n .format(data_source_name))\n\n # if data_source_forms_assignment was not assigned with any value in code before, assign a default to it\n # this a case when an assay submits only attachments and do not use any assay or QC data\n if not self.data_source_forms_assignment:\n self.data_source_forms_assignment = gc.DEFAULT_DATA_SOURCE_FORMS_ASSIGNMENT\n\n self.submission_package = SubmissionPackage(self)\n\n self.create_request_for_disqualified_sub_aliquots()\n\n self.create_trasfer_script_file()\n\n # check for errors and put final log entry for the request.\n if self.error.exist():\n _str = 'Processing of the current request was finished with the following errors: {}\\n'.format(\n self.error.get_errors_to_str())\n self.logger.error(_str)\n else:\n _str = 'Processing of the current request was finished successfully.\\n'\n self.logger.info(_str)\n\n def load_assay_conf(self, assay, project):\n assay_cfg_path = gc.CONFIG_FILE_ASSAY.replace('{project}', project)\n cfg_assay = ConfigData(assay_cfg_path)\n assay_config = cfg_assay.get_value(assay.upper())\n if assay_config:\n self.logger.info (\"Configuration for the {} assay was loaded from the assay config file: {}. \"\n .format(assay.upper(), assay_cfg_path))\n else:\n _str = \"Configuration for the {} assay CANNOT be loaded from the assay config file: {}. \" \\\n \"Aborting execution.\".format(assay.upper(), assay_cfg_path)\n self.logger.error(_str)\n self.error.add_error(_str)\n\n return assay_config\n\n # def update_cfg_assay_with_location_details(self, project, cfg_assay):\n # cfg_assay_location = ConfigData(gc.CONFIG_FILE_ASSAY_LOCATION.replace('{project}', project))\n # if cfg_assay_location.loaded:\n # self.logger.info('Local config file \"{}\" was loaded and being used.'.format(cfg_assay_location.cfg_path))\n # cfg_assay = cm.update_dictionary_matching_keys(cfg_assay, cfg_assay_location.get_whole_dictionary())\n # else:\n # _str = 'Local config file \"{}\" was NOT loaded. Aborting processing of the current request file.'\\\n # .format(cfg_assay_location.cfg_path)\n # self.logger.error(_str)\n # self.error.add_error(_str)\n # return cfg_assay\n\n def update_cfg_dictionary_with_location_details(self, location_path, project, cfg_to_update):\n cfg_location = ConfigData(location_path.replace('{project}', project))\n if cfg_location.loaded:\n self.logger.info('Local config file \"{}\" was loaded and being used.'.format(cfg_location.cfg_path))\n cfg_to_update = cm.update_dictionary_matching_keys(cfg_to_update, cfg_location.get_whole_dictionary())\n else:\n _str = 'Local config file \"{}\" was NOT loaded. Aborting processing of the current request file.'\\\n .format(cfg_location.cfg_path)\n self.logger.error(_str)\n self.error.add_error(_str)\n return cfg_to_update\n\n def load_project_config_into_main (self, project):\n # load project specific \"project_config\" config file\n cfg_project = ConfigData(gc.CONFIG_FILE_PROJECT.replace('{project}', project))\n if cfg_project.loaded:\n # if cfg_project was loaded, update it with the environment specific settings (from project_location config)\n cfg_project_updated = self.update_cfg_dictionary_with_location_details(gc.CONFIG_FILE_PROJECT_LOCATION,\n self.project,\n cfg_project.get_whole_dictionary())\n # update main config with the outcome of the previous updates\n self.conf_main.update(cfg_project_updated)\n\n def create_trasfer_script_file(self):\n self.logger.info(\"Start preparing transfer_script.sh file.\")\n # path for the script file being created\n sf_path = Path(self.submission_package.submission_dir + \"/transfer_script.sh\")\n\n # get script file template\n with open('scripts/' + self.project + '/transfer_script.sh', 'r') as ft:\n scr_tmpl = ft.read()\n\n # update placeholders in the script with the actual values\n smtp_server = cm.get_environment_variable(self.conf_main.get_item_by_key('Email/smtp_server_env_name'))\n smtp_port = cm.get_environment_variable(self.conf_main.get_item_by_key('Email/smtp_server_port_env_name'))\n scr_tmpl = cm.replace_value_in_string(scr_tmpl, \"{!smtp!}\", smtp_server + \":\" + str(smtp_port))\n scr_tmpl = cm.replace_value_in_string(scr_tmpl, \"{!to_email!}\",\n ','.join(self.conf_main.get_value(\"Email/sent_to_emails\")))\n scr_tmpl = cm.replace_value_in_string(scr_tmpl, \"{!from_email!}\",\n self.conf_main.get_value(\"Email/default_from_email\"))\n scr_tmpl = cm.replace_value_in_string(scr_tmpl, \"{!send_email_flag!}\",\n str(self.conf_main.get_value(\"Email/send_emails\")))\n scr_tmpl = cm.replace_value_in_string(scr_tmpl, \"{!cmd!}\",\n self.conf_main.get_value(\"DataTransfer/transfer_command\"))\n\n # the following will be utilized if mount point is being used by the transfer script (i.e. for Peerless)\n scr_tmpl = cm.replace_value_in_string(scr_tmpl, \"{!mp_cmd!}\",\n self.conf_main.get_value(\"DataTransfer/mount_point_command\"))\n scr_tmpl = cm.replace_value_in_string(scr_tmpl, \"{!mount_local_dir!}\",\n self.conf_main.get_value(\"DataTransfer/mount_local_dir\"))\n scr_tmpl = cm.replace_value_in_string(scr_tmpl, \"{!mount_remote_dir!}\",\n self.conf_main.get_value(\"DataTransfer/mount_remote_dir\"))\n\n scr_tmpl = cm.replace_value_in_string(scr_tmpl, \"{!source_dir!}\", self.submission_package.submission_dir)\n scr_tmpl = cm.replace_value_in_string(scr_tmpl, \"{!target_dir!}\",\n self.conf_main.get_value(\"DataTransfer/remote_target_dir\"))\n\n ssh_server = cm.get_environment_variable(self.conf_main.get_item_by_key('DataTransfer/ssh_server_env_name'))\n scr_tmpl = cm.replace_value_in_string(scr_tmpl, \"{!ssh_server!}\", str(ssh_server))\n # apply user name as the very last replacement statement, since it can be used as part of previous replacements\n ssh_user = cm.get_environment_variable(self.conf_main.get_item_by_key('DataTransfer/ssh_user_env_name'))\n scr_tmpl = cm.replace_value_in_string(scr_tmpl, \"{!ssh_user!}\", str(ssh_user))\n\n set_permissions = False\n set_perm_value = self.conf_main.get_value(\"DataTransfer/exec_permis\")\n if set_perm_value:\n try:\n exec_permission = eval(set_perm_value.strip())\n set_permissions = True\n except Exception as ex:\n _str = 'Unexpected error Error \"{}\" occurred during evaluating of \"DataTransfer/exec_permis\" value ' \\\n '\"{}\" retrieved from the main config file. Permission setup operation will be skipped. \\n{} '\\\n .format(ex, set_perm_value, traceback.format_exc())\n self.logger.warning(_str)\n # self.error.add_error(_str)\n set_permissions = False\n\n with open(sf_path, \"w\") as sf:\n sf.write(scr_tmpl)\n\n if set_permissions:\n try:\n # if permissions to be set were retrieved from config file, set them here\n st = os.stat(sf_path)\n os.chmod(sf_path, st.st_mode | exec_permission) #stat.S_IXUSR\n except Exception as ex:\n _str = 'Unexpected error Error \"{}\" occurred during setting up permissions \"{}\" for the script file ' \\\n '\"{}\". \\n{} '\\\n .format(ex, set_perm_value, sf_path, traceback.format_exc())\n self.logger.warning(_str)\n self.error.add_error(_str)\n else:\n _str = 'Permission setup was skipped for the transfer script file. ' \\\n 'Note: value of \"DataTransfer/exec_permis\" from main config was set to \"{}\".'\\\n .format(set_perm_value)\n self.logger.warning(_str)\n\n self.logger.info(\"Finish preparing '{}' file.\".format(sf_path))\n\n def disqualify_sub_aliquot(self, sa, details):\n # adds a sub aliquots to the disctionary of disqualified sub_aliquots\n # key = sub-aliquot, value = array of details for disqualification; 1 entry can have multiple detail reasons\n if sa in self.disqualified_sub_aliquots.keys():\n self.disqualified_sub_aliquots[sa].append(details)\n else:\n arr_details = [details]\n self.disqualified_sub_aliquots[sa]= arr_details\n self.logger.warning('Sub-aliquot \"{}\" was disqualified with the following details: \"{}\"'.format(sa, details))\n\n def populate_qualified_aliquots(self):\n # reset self.qualified_aliquots array\n self.qualified_aliquots = []\n #select only aliquots that were not disqualified\n for sa, a in zip(self.sub_aliquots, self.aliquots):\n if not sa in self.disqualified_sub_aliquots.keys():\n self.qualified_aliquots.append(a)\n\n def create_request_for_disqualified_sub_aliquots(self):\n\n # proceed only if some disqualified sub-aliquots are present\n if self.disqualified_sub_aliquots:\n\n self.logger.info(\"Start preparing a request file for disqualified sub-aliquots '{}'.\"\n .format([val for val in self.disqualified_sub_aliquots.keys()]))\n\n wb = xlwt.Workbook() # create empty workbook object\n sh = wb.add_sheet('Submission_Request') # sheet name can not be longer than 32 characters\n\n cur_row = 0 # first row for 0-based array\n cur_col = 0 # first col for 0-based array\n #write headers to the file\n headers = self.get_headers()\n for val in headers:\n sh.write (cur_row, cur_col, val)\n cur_col += 1\n\n cur_row += 1\n\n for sa in self.sub_aliquots:\n if sa in self.disqualified_sub_aliquots.keys():\n sh.write(cur_row, 0, self.project)\n sh.write(cur_row, 1, self.bulk_location)\n sh.write(cur_row, 2, self.assay)\n sh.write(cur_row, 3, self.center)\n sh.write(cur_row, 4, sa)\n cur_row += 1\n\n self.disqualified_request_path = Path(gc.DISQUALIFIED_REQUESTS + '/' +\n time.strftime(\"%Y%m%d_%H%M%S\", time.localtime()) + '_reprocess_disqualified _' +\n Path(self.filename).stem + '.xls')\n\n # if DISQUALIFIED_REQUESTS folder does not exist, it will be created\n os.makedirs(gc.DISQUALIFIED_REQUESTS, exist_ok=True)\n\n wb.save(str(self.disqualified_request_path))\n\n self.logger.info(\"Successfully prepared the request file for disqualified sub-aliquots and saved in '{}'.\"\n .format(str(self.disqualified_request_path)))","sub_path":"file_load/request_file.py","file_name":"request_file.py","file_ext":"py","file_size_in_byte":35328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"211103321","text":"# -*- coding: utf-8 -*-\n\"\"\"\nTencent is pleased to support the open source community by making BK-LOG 蓝鲸日志平台 available.\nCopyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.\nBK-LOG 蓝鲸日志平台 is licensed under the MIT License.\nLicense for BK-LOG 蓝鲸日志平台:\n--------------------------------------------------------------------\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\ndocumentation files (the \"Software\"), to deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,\nand to permit persons to whom the Software is furnished to do so, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all copies or substantial\nportions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT\nLIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\nNO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\nURL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.8/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', 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: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\n\nfrom django.conf.urls import include, url\nfrom django.contrib import admin\nfrom version_log import config\n\nurlpatterns = [\n url(r\"^bklog_manage/\", admin.site.urls),\n url(r\"^account/\", include(\"blueapps.account.urls\")),\n # 接口\n url(r\"^api/v1/iam/\", include(\"apps.iam.urls\")),\n url(r\"^api/v1/databus/\", include(\"apps.log_databus.urls\")),\n # trace\n url(r\"^api/v1/trace/\", include(\"apps.log_trace.urls\")),\n url(r\"^api/v1/\", include(\"apps.log_search.urls\")),\n url(r\"^api/v1/\", include(\"apps.log_esquery.urls\")),\n url(r\"^api/v1/\", include(\"apps.esb.urls\")),\n url(r\"^api/v1/\", include(\"apps.bk_log_admin.urls\")),\n url(r\"^\", include(\"apps.grafana.urls\")),\n # 前端页面\n url(r\"^\", include(\"home_application.urls\")),\n # celery flower\n url(r\"^flower/\", include(\"flower_proxy.urls\")),\n url(r\"^{}\".format(config.ENTRANCE_URL), include(\"version_log.urls\")),\n url(r\"^api/v1/log_extract/\", include(\"apps.log_extract.urls\")),\n]\n","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"524078825","text":"#!/usr/bin/python3\n\n#imports\nimport conf\nimport requests\nimport json\nfrom datetime import datetime, timedelta\nimport pytz\n\n#conf\nconf.load(\"config.json\")\n\n#constants\nUP_API_ENDPOINT = \"https://api.up.com.au/api/v1\"\nTIME_NOW = pytz.timezone(conf.get(\"TIMEZONE\")).localize(datetime.now())\n\n#creds\nUP_CREDS_HEADER = {\"Authorization\": \"Bearer {}\".format(conf.get(\"UP_API_KEY\"))}\n\ndef main():\n #Main function ran on script startup\n if not testUpbankApi():\n print(\"YNAB API connection failed, please check your config file\")\n exit(1)\n\n bankAccounts = getUpAccounts()\n\n #Get cheque account\n for account in bankAccounts:\n if account[\"attributes\"][\"accountType\"] == \"TRANSACTIONAL\":\n chequeAccount = account\n break\n\n printCsv(getTransactions(chequeAccount, -1),bankAccounts)\n \n\ndef printCsv(transactions,bankAccounts):\n print(\"id,accountId,accountName,description,rawText,createdAt,value,parentCategory,category,transferAccountId,transferAccount\")\n for transaction in transactions:\n print(\"{},{},{},{},{},{},{}\".format(\n transaction[\"id\"],\n transaction['relationships']['account']['data']['id'],\n getAccountName(bankAccounts,transaction['relationships']['account']['data']['id']),\n transaction[\"attributes\"][\"description\"],\n transaction['attributes']['rawText'],\n transaction[\"attributes\"][\"createdAt\"],\n transaction[\"attributes\"][\"amount\"][\"value\"],\n ),\n end=\"\")\n\n if(transaction['relationships']['category']['data']):\n print(\",{},{}\".format(\n transaction['relationships']['parentCategory']['data']['id'],\n transaction['relationships']['category']['data']['id'],\n ),\n end=\"\")\n else:\n if(transaction['relationships']['transferAccount']['data']):\n print(\",transfer,transfer\",end=\"\")\n else:\n print(\",,\",end=\"\")\n\n if(transaction['relationships']['transferAccount']['data']):\n print(\",{},{}\".format(\n transaction['relationships']['transferAccount']['data']['id'],\n getAccountName(bankAccounts,transaction['relationships']['transferAccount']['data']['id']),\n ),\n end=\"\")\n else:\n print(\",,\",end=\"\")\n\n print()\n\ndef testUpbankApi():\n #Make a call to up bank's API and parse result to determine if key is correct\n apiStatus = False\n\n resp = requests.get(\"{}/util/ping\".format(UP_API_ENDPOINT),headers=UP_CREDS_HEADER)\n\n if resp.status_code == 200:\n print(\"Up Bank Connected: {}\".format(json.loads(resp.content)[\"meta\"][\"statusEmoji\"]))\n apiStatus = True\n if resp.status_code != 200:\n print(\"Up Bank connection failed: GET /util/ping {}\".format(resp.status_code))\n return apiStatus\n\ndef getUpAccounts():\n #Get a list of all up bank accounts aka savers\n resp = requests.get(\"{}/accounts\".format(UP_API_ENDPOINT),headers=UP_CREDS_HEADER)\n accounts = []\n\n if resp.status_code == 200:\n print(\"Found Up Bank Accounts: \")\n for account in json.loads(resp.content)[\"data\"]:\n print(\"\\t{}\".format(account[\"attributes\"][\"displayName\"]))\n accounts.append(account)\n if resp.status_code != 200:\n print(\"Up Bank connection failed: GET /accounts {}\".format(resp.status_code))\n \n return accounts\n\ndef getTransactions(account, daysFrom):\n #Get past x days of transactions from the cheque account, -1 gets all\n transactions = []\n\n nextTransactionPage = account[\"relationships\"][\"transactions\"][\"links\"][\"related\"]\n while True:\n resp = requests.get(nextTransactionPage,headers=UP_CREDS_HEADER)\n\n for transaction in json.loads(resp.content)[\"data\"]:\n transactions.append(transaction)\n \n #If the transactions list has no more items, stop getting more transactions\n if json.loads(resp.content)[\"links\"][\"next\"] is None:\n break\n\n #If the first transaction in the list is before a certain date, stop getting more transactions\n if daysFrom != -1:\n if datetime.fromisoformat(json.loads(resp.content)[\"data\"][0][\"attributes\"][\"createdAt\"]) < TIME_NOW + timedelta(days=-daysFrom):\n break\n\n nextTransactionPage = json.loads(resp.content)[\"links\"][\"next\"]\n\n return removeOldTransactions(transactions, daysFrom)\n\ndef removeOldTransactions(transactions, daysFrom):\n filteredTransactions = []\n\n if daysFrom == -1:\n filteredTransactions = transactions\n else:\n for transaction in transactions:\n if datetime.fromisoformat(transaction[\"attributes\"][\"createdAt\"]) >= TIME_NOW + timedelta(days=-daysFrom):\n filteredTransactions.append(transaction)\n\n return filteredTransactions\n\ndef getAccountName(bankAccounts,accountId):\n for account in bankAccounts:\n if account[\"id\"] == accountId:\n return account[\"attributes\"][\"displayName\"]\n\nif __name__ == \"__main__\":\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"525236917","text":"def counting_sort(A, R): #A:array, R: range\n B=[0] * R\n for i in A:\n B[i] +=1\n\n ans= []\n for k,v in enumerate(B):\n if v > 0:\n ans += [k] * v\n\n return ans","sub_path":"mylib/counting_sort.py","file_name":"counting_sort.py","file_ext":"py","file_size_in_byte":193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"213997882","text":"#encoding: UTF-8\n#Nombre de el Alumno: Manuel Alejandro Bracho Mendoza\n#Mátricula: A01378897\n#Tarea 6\n\nfrom math import *\n\ndef contarInsectos():\n dias = 1\n insectos = (int(input(\"Insectos recolectados hoy\")))\n while insectos < 30 :\n restante = 30-insectos\n print (\"Después de\" ,dias,\"día(s) de recolección has acumulado\", insectos)\n print (\"Te hace falta recolectar\",restante,\"insectos\")\n dias+=1\n insectosSegundoDia = (int(input(\"Insectos recolectados hoy\")))\n insectos=insectosSegundoDia + insectos\n if insectos == 30:\n print (\"Despues de\" ,dias,\"día(s) de recolección has acumulado\", insectos)\n print (\"te hace falta recolectar 0 insectos \\nFelicidades has llegado a la meta\")\n if insectos >= 31:\n print (\"Despues de\",dias,\"día(s) de recolección has acumulado\", insectos)\n print (\"Te has padado con\", insectos - 30 ,\"insectos \\nFelicidades has llegado a la meta\")\ndef calcularNumero():\n numero = (int(input(\"Ingrese los numeros, para salir de el colector de números escriba -1\")))\n if numero <= -1:\n print(\"no hay datos para encontrar el número mayor.\")\n else:\n acumulador = 0 \n \n while numero != -1:\n if acumulador < numero:\n acumulador = numero\n numero = (int(input(\"ingrese el número, recuerda que tecleando -1 indicas que terminas de escribir\"))) \n print(\"El mayor es\", acumulador) \ndef main():\n opcion = 0\n while opcion != 3:\n opcion = (int(input(\"1°.- Contador de Insectos \\n2°.- Encontrar el número mayor \\n3°.- Salir\")))\n if opcion == 1:\n contarInsectos()\n elif opcion == 2:\n calcularNumero()\n elif opcion == 3:\n print(\"hasta pronto\")\n else:\n print(\"teclea una opción válida\")\nmain() \n \n \n \n \n \n ","sub_path":"Tarea_6.py","file_name":"Tarea_6.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"401502387","text":"import bisect\n\ntop_jaccard_items_candidate = 10\n\n\ndef edit_distance(str1, str2):\n dis = [[0 for _ in range(len(str2) + 1)] for _ in range(len(str1) + 1)]\n for i in range(len(str1) + 1):\n for j in range(len(str2) + 1):\n if min(i, j) == 0:\n dis[i][j] = max(i, j)\n else:\n dis[i][j] = min(min(dis[i - 1][j], dis[i][j - 1]) + 1,\n dis[i - 1][j - 1] + (1 if str1[i - 1] != str2[j - 1] else 0))\n return dis[len(str1)][len(str2)]\n\n\ndef get_token_bi_words(token):\n token = \"$\" + token + \"$\"\n return sorted(set([token[i] + token[i + 1] for i in range(len(token) - 1)]))\n\n\ndef correct(query, index, stop_words, lang):\n cleaned_query = lang.clean_raw(query)\n corrected_query = []\n edit_distance_value = 0\n jaccard_distance_value = 0\n for token in cleaned_query:\n if not token in index.all_tokens and not token in stop_words:\n bi_words = get_token_bi_words(token)\n jaccard_candidates = []\n for bi_word in bi_words:\n if bi_word in index.bigram:\n for token_id in index.bigram[bi_word]:\n intersection = 0\n sum_of_subset_sizes = len(bi_words) + len(get_token_bi_words(index.all_tokens[token_id]))\n for bi_word_2 in bi_words:\n if bi_word_2 in index.bigram:\n idx = bisect.bisect_left(index.bigram[bi_word_2], token_id)\n if idx < len(index.bigram[bi_word_2]) and index.bigram[bi_word_2][idx] == token_id:\n intersection += 1\n jaccard_candidates.append((1.0 - intersection / (sum_of_subset_sizes - intersection), token_id))\n jaccard_candidates = sorted(jaccard_candidates)[:top_jaccard_items_candidate]\n edit_distance_candidates = []\n for candidate in jaccard_candidates:\n org_str = index.all_tokens[candidate[1]]\n edit_distance_candidates.append((edit_distance(token, org_str), -len(org_str), org_str, candidate[0]))\n e, _, corrected_token, j = sorted(edit_distance_candidates)[0]\n edit_distance_value += e\n corrected_query.append(corrected_token)\n jaccard_distance_value += j\n else:\n corrected_query.append(token)\n return ' '.join(cleaned_query), ' '.join(corrected_query), jaccard_distance_value, edit_distance_value\n","sub_path":"index/spell_checker.py","file_name":"spell_checker.py","file_ext":"py","file_size_in_byte":2535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"345904885","text":"from math import tau\nfrom scipy import optimize # Optimize Thetas\nimport pandas as pd\nimport numpy as np\n\nfrom helpers import load_estimated_densities, load_dict\nfrom functools import reduce # To merge list of data frames\nimport matplotlib.pyplot as plt\n\n# R\nfrom rpy2 import robjects\nimport rpy2.robjects.packages as rpackages\n\nclass KernelSmoother:\n \"\"\"\n Maria Grith Style\n M contains spd, hd, moneyness\n\n\n def update_parameters(self):\n for i in range(4): # Update each of the four parameters\n # Integrate the following expression\n theta_vary = self.theta2 * u + self.theta3\n K_t(theta_vary) - self.theta1 * #...\n\n\n def K_t(self, theta_vary):\n '''\n Return Linear Combination of Pricing Kernel PK \n Thetas are updated iteratively, they vary. NOT self.theta1 and so on\n '''\n pk = self.M.spd / self.M.hd\n pk_lin = self.theta1 * pk + self.theta4\n return pk_lin\n\n def initialize_K0(self):\n '''\n u is the same for every PK\n PK list of pricing Kernels, all evaluated at common moneyness u,\n e.g. interval [0.7, 1.3]\n There are T pricing kernels\n '''\n PK_lin = self.theta2 * self.PK[0] + self.theta3 # linearly moved u\n #k_out = []\n #for i in range(len(u)):\n # k_out.append(self.PK[0](u_lin))\n #return sum(k_out) * (1/T)\n return PK_lin\n\n\n \"\"\"\n def __init__(self, taurange):\n x, z, s, pk, date, tau, maturitydate = load_estimated_densities(fname='out/estimated_densities.csv', allowed_taurange=taurange)#load_estimated_densities(allowed_taurange=[0.0163, 0.0165])#load_estimated_densities(allowed_taurange=[0.018, 0.02])\n self.M = x\n self.T = len(x)\n self.t = list(range(self.T)) # Discrete Time Steps\n self.K0 = None\n self.PK = pk #List of Pricing Kernels for each Point in Time\n self.tau = tau\n self.tau_in_days = np.unique([round(float(t) * 365) for t in self.tau])[0]\n self.maturitydate = maturitydate\n if self.tau_in_days == 1:\n self.day_str = ' Day'\n else:\n self.day_str = ' Days'\n #self.d = load_dict('out/estimated_densities.csv')\n\n self.base = rpackages.importr(\"base\") \n self.sm = rpackages.importr(\"sm\")\n self.r = robjects.r\n\n # Parameter Initialization\n self.theta1 = [0] * self.T # Vector over length of T\n self.theta2 = [0] * self.T\n self.theta3 = [0] * self.T\n self.theta4 = [0] * self.T\n\n # Theta1 and Theta2 are initially 1, the others are 0 as in\n # Haerdle and Marron 1990\n self.theta1[0] = 1 \n self.theta2[0] = 1\n\n # @ Todo: Filter input for similar taus!\n\n def _normalize_parameters(self):\n #Normalization: Mean of all Parameters Theta_ti must be 1\n self.theta1 = self.theta1/sum(self.theta1)\n self.theta2 = self.theta2/sum(self.theta2)\n self.theta3 = self.theta3/sum(self.theta3)\n self.theta4 = self.theta4/sum(self.theta4)\n\n def _w(self, u, a, b, i, theta2, theta3):\n \"\"\"\n Calculates Integral Weights\n Boundary Interval [a,b]\n u Moneyness\n t is Point in Time T \n \"\"\"\n #out = []\n #for _u in u[i]:#range(len(u)):\n prel = (u[i] - theta3)/theta2\n \n # Indicator Function\n if prel > a and prel < b:\n out = 0\n #out.append(prel)\n else:\n # Append one so that the product does not vanish\n #out.append(1)\n out = 1 \n return out\n # Take product of all constituents\n #p = 1\n #for i in range(len(out)):\n # p = p * i\n \n #return p\n\n def initialize_K0(self, theta2, theta3):\n '''\n u is the same for every PK\n PK list of pricing Kernels, all evaluated at common moneyness u,\n e.g. interval [0.7, 1.3]\n\n '''\n smoothened_dfs = []\n est_dfs = []\n for i in range(len(self.PK)):\n df = pd.DataFrame({'PK' : self.PK[i], 'M' : self.M[i]})\n\n # Shift the domain\n # For the initialization, this is 1 * u + 0\n lin_shift = (theta2[i] * df['M'] + theta3[i])\n\n # Smoothen up\n kt = df['PK'].tolist()\n t = df['M'].tolist()\n # How to use h.select from r?\n h_bw = self.sm.h_select(robjects.FloatVector(t), robjects.FloatVector(kt))\n sm_reg = self.sm.sm_regression(**{'x' : robjects.FloatVector(t),\n 'y' : robjects.FloatVector(kt),\n 'h' : robjects.FloatVector(h_bw),\n 'eval.points' : robjects.FloatVector(lin_shift),\n 'model' : \"none\",\n 'poly_index' : 1,\n 'display' : \"none\"})\n\n\n # Assign Y hat\n df['sm_estimate'] = sm_reg.rx2('estimate') #sm_reg['estimate']\n df['lin_shift'] = lin_shift\n smoothened_dfs.append(df)\n est_dfs.append(df[['M', 'sm_estimate']])\n \n # Mean Kt Curve is initial Reference Curve K0\n # names are still missing\n # and still got to calculate the mean!\n K0 = reduce(lambda x, y: pd.merge(x, y, on = 'M', how = 'outer'), est_dfs)\n \n # Rowwise Mean\n # @Todo exclude irrelevant columns for the mean calculation!!\n df['mean'] = df.drop(['M'], axis = 1).mean(axis = 1)\n #lt.plot(df['M'], df['mean'])\n #plt.show()\n out_df = df[['M', 'mean']]\n return out_df\n\n def mse(self, thetas, K0, i):\n \"\"\"\n K0 is initialized reference curve, \n or updated one in the following steps j\n\n get K_hat_t(theta_2 * u + theta_3)\n\n Then calculate MSE between the two.\n \"\"\"\n df = pd.DataFrame({'PK' : self.PK[i], 'M' : self.M[i]})\n\n # Unpack to-be-optimized argument\n theta1 = thetas[0]\n theta2 = thetas[1]\n theta3 = thetas[2]\n theta4 = thetas[3]\n\n # Ensure restrictions\n theta1 = abs(theta1)\n theta3 = abs(theta3)\n #theta2 = theta2\n #theta4 = theta4\n\n #sm.t = (t.reference - theta2)/theta3 # time adjustment\n lin_shift = theta2 * self.M[i] + theta3\n kt = self.PK[i].tolist()\n t = self.M[i].tolist()\n h_bw = self.sm.h_select(robjects.FloatVector(t), robjects.FloatVector(kt))\n sm_reg = self.sm.sm_regression(**{'x' : robjects.FloatVector(lin_shift),\n 'y' : robjects.FloatVector(kt),\n 'h' : robjects.FloatVector(h_bw),\n 'eval.points' : robjects.FloatVector(lin_shift),\n 'model' : \"none\",\n 'poly_index' : 1,\n 'display' : \"none\"})\n df['sm_estimate'] = sm_reg.rx2('estimate')\n df['lin_shift'] = lin_shift\n\n\n # Get The Difference to K0**(r-1)\n # @Todo check if mean is correct here\n df['ref_point'] = theta1 * K0['mean'] - theta4\n \n # Mean Squared Error\n df['mse'] = (df['sm_estimate'] - df['ref_point']) ** 2\n\n w = self._w(t, 0, 10, i, theta2, theta3)\n #du = df['M'].diff()# impute NAs! #np.diff().tolist()\n\n df['integral'] = df['mse'] #* w #* du # (du) missing here\n\n return sum(df['integral'])\n\n\n def optimize_theta(self, thetas, K0, i):\n # Minimize MSE with respect to Thetas\n\n theta1 = thetas[0][i]\n theta2 = thetas[1][i]\n theta3 = thetas[2][i]\n theta4 = thetas[3][i]\n\n theta_candidates = [theta1, theta2, theta3, theta4] # initial guess\n _args = (K0, i) # , theta1, theta2, theta3, theta4; initial guess proabbaly excluded from rest of the arguments\n theta_est = optimize.minimize(self.mse, x0 = theta_candidates, args = _args)\n\n print(theta_est.message)\n print(theta_est.x)\n\n # Before vs afterwards \n print(self.mse(theta_candidates, K0, i), self.mse(theta_est.x, K0, i))\n\n return theta_est.x\n\n\n # 2D Stuff: Use to show different SPDs/EPKs on a single day\n def pricingkernel_plot(self):\n '''\n Plots all the Pks on a single day\n self.pricingkernel_plot()\n '''\n\n fig=plt.figure()\n ax=fig.add_subplot(111)\n\n for i in range(self.T):\n if i == 0:\n lab = str('Maturity \\n') + str(self.maturitydate[i])\n else:\n lab = str(self.maturitydate[i])\n plt.plot(self.M[i], self.PK[i], label = lab)\n #pdb.set_trace()\n #currdate = date[i]\n #currtau = self.tau[i]\n #currmaturity = maturitydate[i]\n \n plt.xlabel('Moneyness')\n plt.ylabel('Pricing Kernel')\n plt.title(str('Pricing Kernels for different Maturities \\nTime to Maturity in ') + str(self.tau_in_days) + str(self.day_str))\n\n # Shrink current axis by 20%\n box = ax.get_position()\n ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])\n # Put a legend to the right of the current axis\n ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n plt.savefig('pricingkernel/plots/pricingkernel' + str(self.tau_in_days) + str('long') + '.png', transparent = True)\n plt.draw()\n #plt.show()\n\n def ara(self, K):\n \"\"\"\n ara(u) = d log K(u) / du\n 􏰀 ARA(u)>0, risk averseness\n 􏰀 ARA(u)=0, risk neutrality\n 􏰀 ARA(u)<0, risk proclivity\n\n Check if this yields the same results as\n\n −θt1 K′ 􏰅u−θt3 􏰆 θt2 0 θt2\n ARAt(u) = 􏰅u−θt3 􏰆 . θt1K0 θt2 + θt4\n \"\"\"\n k_inv = K.iloc[::-1]\n u = k_inv.iloc[1:]['M'] # first observation is lost due to diff function\n ara = (-1) * np.diff(np.log(k_inv['mean'])) / np.diff(k_inv['M'])\n\n plt.plot(u, ara)\n plt.show()\n\n\n\n\n\n def _run(self):\n \n # If there are only two curves, just subtract the Kernel from the interpolation\n if len(self.M) == 2:\n print('use 2.1 estimation of SIM equation (4)')\n\n # Output Collection\n K0_tracker = []\n theta_tracker = []\n\n # Initial K0 must be looped over all PKs and M, \n # basically Mean Kernel\n theta1, theta2, theta3, theta4 = [1]*self.T, [1]*self.T, [0]*self.T, [0]*self.T\n K0 = self.initialize_K0(theta2, theta3) \n self.pricingkernel_plot()\n\n for j in range(4):\n for i in range(self.T):\n \n print(j, i)\n\n # Optimize Parameters\n thetas = [theta1, theta2, theta3, theta4]\n thetas_est = self.optimize_theta(\n thetas,\n K0,\n i)\n\n # Collect Parameters\n theta1[i] = thetas_est[0]\n theta2[i] = thetas_est[1]\n theta3[i] = thetas_est[2]\n theta4[i] = thetas_est[3]\n\n # Normalize Parameters\n theta1 = theta1/sum(theta1)\n theta2 = theta2/sum(theta2)\n theta3 = theta3 - np.mean(theta3) #theta3/sum(theta3)\n theta4 = theta4 - np.mean(theta4) #theta4/sum(theta4)#\n \n # Collect Output\n K0_tracker.append(K0)\n theta_tracker.append([theta1, theta2, theta3, theta4])\n\n # Restart\n # Update K0**(j-1)\n # like initialize_K0, but with updated thetas\n K0 = self.initialize_K0(theta2, theta3)\n\n # Absolute Risk Aversion\n #self.ara(K0_tracker[-1])\n\n # Check K0tracker\n if np.mean(abs(K0_tracker[-1]['mean'] - K0_tracker[-2]['mean'])) < 0.001:\n print('K0s are very close, only plotting last one!')\n K0_tracker = [K0_tracker[-1]]\n\n\n # Plot Convergence of PKs\n fig=plt.figure()\n ax=fig.add_subplot(111)\n for k in range(len(K0_tracker)):\n KX = K0_tracker[k]\n if len(K0_tracker) > 1:\n lab = str('Iteration ') + str(k)\n else:\n #lab = str('Tau: ') + str(np.unique(self.tau)[0])\n lab = ''\n\n plt.plot(KX['M'], KX['mean'], label = lab)\n\n ptitle = 'Shape Invariant Pricing Kernel \\nTime to Maturity in ' + str(self.tau_in_days) + str(self.day_str)\n plt.title(ptitle)\n plt.xlabel('Moneyness')\n plt.ylabel('Pricing Kernel')\n\n # Shrink current axis by 20%\n box = ax.get_position()\n ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])\n # Put a legend to the right of the current axis\n ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n plt.savefig('pricingkernel/plots/pricingkernel_nth_iteration' + str(self.tau_in_days) + str('long') + '.png', transparent = True)\n plt.draw()\n\n\n\nif __name__ == '__main__':\n errors = []\n taus = load_estimated_densities(allowed_taurange = [0, 1], only_taus = True)\n unique_taus = np.sort(np.unique(taus))\n for tau in unique_taus:\n try:\n KS = KernelSmoother([float(tau)-0.0001, float(tau)+0.0001])\n KS._run()\n except Exception as e:\n errors.append(e)\n print(e)\n print('done')","sub_path":"BitcoinPricingKernels/src/KernelSmoother.py","file_name":"KernelSmoother.py","file_ext":"py","file_size_in_byte":13565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"157825252","text":"# In order to run each file in this project, we need to open cmd, then, type name_file.py in cmd.\nimport socket\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\nhostname = \"localhost\"\n\nipAddress = socket.gethostbyname(hostname)\nprint(\"IP Address of localhost is: {}\".format(ipAddress))\n\nport = 9999\n\ns.bind((ipAddress, port))\n\nprint(\"Waiting for connection ...\")\ns.listen(5)\n\nwhile True:\n conn, addr = s.accept()\n print(\"Got connection from \", addr)\n conn.send(b'Server saying Hi') # We have to transfer data by using binary mode, not using string.\n conn.close()\n\n\ninput(\"Press Enter to continue...\")\n","sub_path":"Python/src/network/simple-server/tcp_server.py","file_name":"tcp_server.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"320478799","text":"from django.core.management.base import BaseCommand\nfrom customerservice.models import Contact, Message, CLOSED, OPEN, PENDING\nfrom twitter import Api, TwitterError\nimport time\nfrom datetime import datetime\nfrom django.conf import settings\n\n\napi = Api(consumer_key=settings.CONSUMER_KEY,\n consumer_secret=settings.CONSUMER_SECRET,\n access_token_key=settings.ACCESS_TOKEN_KEY,\n access_token_secret=settings.ACCESS_TOKEN_SECRET)\n\n\nclass Command(BaseCommand):\n\n def handle(self, *args, **options):\n\n\n self.screen_name = settings.APPS_TWITTER_USERNAME\n #TwitterAPI jamas trae tus propios DirectMessages, trae solo incoming.\n for msg in api.GetDirectMessages(self.screen_name):\n if msg.sender_screen_name != self.screen_name:\n date_created = datetime.strptime(\n msg.created_at,\n '%a %b %d %H:%M:%S %z %Y'\n )\n contact, created = Contact.objects.get_or_create(\n user_id=msg.sender_id,\n screen_name=msg.sender_screen_name,\n type=Contact.THREAD,\n defaults={\n 'created': date_created\n })\n if created or contact.status == Contact.CLOSED:\n try:\n own_msg = api.PostDirectMessage(\n settings.ANSWER_TO_DIRECT_MESSAGE % msg.sender_screen_name, msg.sender_id\n )\n msg_data = {\n \"creator\": True,\n \"contact\": contact,\n \"message_id\": own_msg.id,\n \"sender\": own_msg.sender_id,\n \"message\": own_msg.text\n }\n message, created = Message.objects.get_or_create(**msg_data)\n contact.status = Contact.OPEN\n contact.save()\n except (TwitterError) as e:\n pass\n msg_data = {\n \"creator\": True,\n \"contact\": contact,\n \"message_id\": msg.id,\n \"sender\": msg.sender_id,\n \"message\": msg.text\n }\n message, created = Message.objects.get_or_create(**msg_data)\n","sub_path":"twcustserv/customerservice/management/commands/get_dms.py","file_name":"get_dms.py","file_ext":"py","file_size_in_byte":2417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"108976187","text":"\"\"\"Visualize DataFrame columns x,y on the notebook, allowing refreshing.\"\"\"\nfrom __future__ import print_function\n\nfrom progressivis import SlotDescriptor, Select, RangeQuery\nfrom progressivis.core.dataframe import DataFrameModule\nfrom progressivis.stats import Histogram2D, Sample\nfrom progressivis.vis import Heatmap\n\n# from bokeh.plotting import show\n# from bokeh.models.mappers import LinearColorMapper\n# from bokeh.palettes import YlOrRd9\n# from bokeh.models import ColumnDataSource, Range1d\n\n# from ipywidgets import widgets\n# from IPython.display import display\n#output_notebook()\n\nimport numpy as np\nimport pandas as pd\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n\nclass ScatterPlot(DataFrameModule):\n parameters = [('xmin', np.dtype(float), 0),\n ('xmax', np.dtype(float), 1),\n ('ymin', np.dtype(float), 0),\n ('ymax', np.dtype(float), 1) ]\n \n def __init__(self, x_column, y_column, **kwds):\n self._add_slots(kwds,'input_descriptors',\n [SlotDescriptor('heatmap', type=pd.DataFrame),\n SlotDescriptor('df', type=pd.DataFrame) ])\n super(ScatterPlot, self).__init__(quantum=0.1, **kwds)\n self.x_column = x_column\n self.y_column = y_column\n self._auto_update = False\n self.image_source = None\n self.scatter_source = None\n self.image = None\n# self.bounds_source = None\n\n def df(self):\n return self.get_input_slot('df').data()\n\n def is_visualization(self):\n return True\n\n def get_visualization(self):\n return \"scatterplot\";\n\n def create_dependent_modules(self, input_module, input_slot, range_query=None, select=None, histogram2d=None,heatmap=None,sample=None, **kwds):\n if hasattr(self, 'input_module'): # test if already called\n return self\n \n s=self.scheduler()\n self.input_module = input_module\n self.input_slot = input_slot\n \n if range_query is None:\n range_query = RangeQuery(group=self.id,scheduler=s)\n range_query.create_dependent_modules(input_module, input_slot, **kwds)\n if select is None:\n select = Select(group=self.id,scheduler=s)\n select.input.df = input_module.output[input_slot]\n select.input.query = range_query.output.query\n if histogram2d is None:\n histogram2d = Histogram2D(self.x_column, self.y_column,group=self.id,scheduler=s);\n histogram2d.input.df = select.output.df\n histogram2d.input.min = range_query.output.min\n histogram2d.input.max = range_query.output.max\n if heatmap is None:\n heatmap = Heatmap(group=self.id,filename='heatmap%d.png', history=100, scheduler=s)\n heatmap.input.array = histogram2d.output.df\n if sample is None:\n sample = Sample(n=50,group=self.id,scheduler=s)\n sample.input.df = select.output.df\n\n scatterplot=self\n scatterplot.input.heatmap = heatmap.output.heatmap\n scatterplot.input.df = sample.output.df\n\n self.range_query = range_query\n self.min = range_query.min\n self.max = range_query.max\n self.min_value = range_query.min_value\n self.max_value = range_query.max_value\n self.select = select\n self.histogram2d = histogram2d\n self.heatmap = heatmap\n self.sample = sample\n\n return scatterplot\n\n def predict_step_size(self, duration):\n return 1\n\n def run_step(self,run_number,step_size,howlong):\n return self._return_run_step(self.state_blocked, steps_run=1, reads=1, updates=1)\n\n def to_json(self, short=False):\n self.image = None\n json = super(ScatterPlot, self).to_json(short)\n if short:\n return json\n return self.scatterplot_to_json(json, short)\n\n def scatterplot_to_json(self, json, short):\n with self.lock:\n df = self.df()\n if df is not None:\n json['scatterplot'] = self.remove_nan(df[[self.x_column,self.y_column]]\n .to_dict(orient='split'))\n\n heatmap = self.get_input_module('heatmap')\n return heatmap.heatmap_to_json(json, short)\n\n def get_image(self, run_number=None):\n heatmap = self.get_input_module('heatmap')\n return heatmap.get_image(run_number)\n\n # # For Bokeh, but not ready for prime time yet...\n # x = np.array([0, 10, 50, 90, 100], np.dtype(float))\n # y = np.array([0, 50, 90, 10, 100], np.dtype(float))\n # img = np.zeros((3, 3), np.float)\n\n # def show(self, p):\n # self.figure = p\n # self.image_source = ColumnDataSource(data={\n # 'image': [self.img],\n # 'x': [0],\n # 'y': [0],\n # 'dw': [100],\n # 'dh': [100]})\n # self.palette = YlOrRd9[::-1]\n # p.image(image='image', x='x', y='y', dw='dw', dh='dh',\n # color_mapper=LinearColorMapper(self.palette), source=self.image_source)\n # self.scatter_source = ColumnDataSource(data={'x': self.x, 'y': self.y})\n # p.scatter('x','y',source=self.scatter_source)\n # show(self.figure)\n # button = widgets.Button(description=\"Refresh!\")\n # display(button)\n # button.on_click(self.update)\n\n # def update(self, b):\n # if self.image_source is None:\n # return\n # logger.info(\"Updating module '%s.%s'\", self.pretty_typename(), self.id)\n # #TODO use data from the same run\n # histo_df = self.histogram2d.df()\n # row = None\n # df = self.df()\n # if df is not None:\n # self.scatter_source.data['x'] = df[self.x_column]\n # self.scatter_source.data['y'] = df[self.y_column]\n # self.scatter_source.push_notebook()\n\n # if histo_df is not None and histo_df.index[-1] is not None:\n # idx = histo_df.index[-1]\n # row = histo_df.loc[idx]\n # if not (np.isnan(row.xmin) or np.isnan(row.xmax)\n # or np.isnan(row.ymin) or np.isnan(row.ymax)\n # or row.array is None):\n # self.image_source.data['image'] = [row.array]\n # self.image_source.data['x'] = [row.xmin]\n # self.image_source.data['y'] = [row.ymin]\n # self.image_source.data['dw'] = [row.xmax-row.xmin]\n # self.image_source.data['dh'] = [row.ymax-row.ymin]\n # self.image_source.push_notebook()\n # self.figure.set(x_range=Range1d(row.xmin, row.xmax),\n # y_range=Range1d(row.ymin, row.ymax))\n # logger.debug('Bounds: %g,%g,%g,%g', row.xmin, row.xmax, row.ymin, row.ymax)\n # else:\n # logger.debug('Cannot compute bounds from image')\n\n # @property\n # def auto_update(self):\n # return self._auto_update\n # @auto_update.setter\n # def auto_update(self, value):\n # self._auto_update = value\n\n # def cleanup_run(self, run_number):\n # super(ScatterPlot, self).cleanup_run(run_number)\n # if self._auto_update:\n # self.update(None)\n\n","sub_path":"progressivis/vis/scatterplot.py","file_name":"scatterplot.py","file_ext":"py","file_size_in_byte":7236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"220423289","text":"import tensorflow as tf\nimport numpy as np\n\n## Save to file\n# remember to define the same dtype and shape when restore\nW = tf.Variable([[2,5,7],[11,13,19]], dtype=tf.float32, name='weights')\nb = tf.Variable([[23,29,31]], dtype=tf.float32, name='biases')\n# initialization\ninit = tf.global_variables_initializer()\nsaver = tf.train.Saver()\nwith tf.Session() as sess:\n sess.run(init)\n save_path = saver.save(sess, \"folder_for_nn/save_net.ckpt\")\n print(\"Save to path: \", save_path)\n","sub_path":"pythonw/tensor/saver.py","file_name":"saver.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"76527826","text":"\n\"\"\"Search bizlogic\n\"\"\"\n\nfrom app.usrlib import common, consts\nfrom app.models import Post\nfrom django.db.models import Q\nfrom app.bizlogic import tag_bizlogic\nfrom app.usrlib import date_utils\n\n\ndef get_posts_by_search_words(lang, word):\n \"\"\"Search posts by words.\"\"\"\n posts = __search_posts_by_title_and_body(lang, word)\n return len(posts), tag_bizlogic.__sort_by_year(lang, posts)\n\n\ndef search_posts_by_get_query(request):\n \"\"\"Search posts by GET queries and get them.\n t: Search title only.\n \"\"\"\n\n # Get t key from GET query.\n keywords = set(\n filter(lambda t: t != '', request.GET.get(key='t', default='').split(' '))\n )\n\n # Get lang key from GET query.\n lang = request.GET.get(key='lang', default=consts.Lang.JA)\n\n # Search posts by the keywords.\n posts = __search_posts_by_title(lang, keywords)\n\n # Format posts, ramaining necessary information.\n formatted_posts = []\n for post in posts:\n # Change UTC time in DB to Japanese time.\n post.publish_at = date_utils.convert_timezone_to_local(post.publish_at)\n formatted_posts.append({\n 'publish_at': date_utils.format_by_lang_Ymd(lang, post.publish_at),\n 'code': post.code,\n 'title': common.dp_lang(lang, post.title_ja, post.title_en),\n 'tag': {\n 'name': common.dp_lang(lang, post.tag.name_ja, post.tag.name_en),\n 'code': post.tag.code,\n },\n })\n\n return formatted_posts\n\n\ndef __search_posts_by_title(lang, words):\n \"\"\"Search title by words and get posts of search result.\"\"\"\n if not words:\n return []\n # When search words are 'a b c', try to get posts that have title contains a, b and c all.\n q = Q()\n for w in words:\n # 'icontains' searches case insensitively.\n q &= common.dp_lang(lang, Q(title_ja__icontains=w), Q(title_en__icontains=w))\n return Post.available().filter(q).order_by('publish_at').reverse()\n\n\ndef __search_posts_by_title_and_body(lang, word):\n \"\"\"So far it doesn't adapt multipul keywords.\"\"\"\n if word == '':\n return []\n q = common.dp_lang(\n lang,\n Q(title_ja__contains=word) | Q(html__contains=word) | (Q(html='') & Q(body_ja__contains=word)),\n Q(title_en__contains=word) | Q(html__contains=word) | (Q(html='') & Q(body_en__contains=word)),\n )\n return Post.available().filter(q).order_by('publish_at').reverse()\n","sub_path":"app/bizlogic/search_bizlogic.py","file_name":"search_bizlogic.py","file_ext":"py","file_size_in_byte":2437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"305960550","text":"#!/usr/bin/env python3\n# coding: utf-8\n# pylint: disable=bare-except\n\"\"\"Delete Vessel\"\"\"\nimport sys\nimport time\nimport json\nimport requests\n\nfrom library.couch_database import CouchDatabase\nfrom library.postgresql_queries import PostgreSQL\n\nCOUCHDB = CouchDatabase()\nPOSTGRES = PostgreSQL()\n\n# couch_query = COUCHDB.couch_db_link()\n\ndef single_delete(doc_id, rev):\n \"\"\"Single Delete\"\"\"\n url = COUCHDB.couch_db_link()\n url += '/' + doc_id + '?' + 'rev=' + rev\n headers = {\"Content-Type\" : \"application/json\"}\n response = requests.delete(url, headers=headers)\n response = response.json()\n\n return response\n\ndef bulk_delete(query):\n \"\"\"Bulk Delete\"\"\"\n count = 1\n\n while True:\n\n req = requests.get(query)\n\n rows = json.loads(req.text)['rows']\n\n if not rows:\n\n break\n\n todelete = []\n\n for doc in rows:\n\n count += 1\n\n todelete.append({\"_deleted\": True,\n \"_id\": doc[\"doc\"][\"_id\"],\n \"_rev\": doc[\"doc\"][\"_rev\"]\n })\n\n url = COUCHDB.couch_db_link()\n url += \"/_bulk_docs\"\n\n requests.post(url, json={\"docs\": todelete})\n\ndef delete_query(vessel_id, dsgn):\n \"\"\"Delete Query\"\"\"\n view = \"get_\" + dsgn\n\n query = COUCHDB.couch_db_link()\n query += \"/_design/{0}/_view/{1}?\".format(dsgn, view)\n query += \"startkey=[\\\"{0}\\\"]&endkey=[\\\"{0}\\\",\".format(vessel_id)\n query += \"{}]&include_docs=true&limit=1000\"\n\n return query\n\ndef delete_vssl(vessel_id):\n \"\"\"Delete Vessel\"\"\"\n conditions = []\n\n conditions.append({\n \"col\": \"vessel_id\",\n \"con\": \"=\",\n \"val\": vessel_id\n })\n\n if POSTGRES.delete('vessel', conditions):\n # print(\"Vessel {0} deleted!\".format(vessel_id))\n return 1\n\n # print(\"Vessel {0} not deleted!\".format(vessel_id))\n return 0\n\n\ndef delete_alarm_vessel(vessel_id):\n \"\"\"Delete Alarm Vessel\"\"\"\n # OPEN CONNECTION\n POSTGRES.connection()\n\n # DATA\n sql_str = \"SELECT * FROM alarm_value\"\n sql_str += \" WHERE vessel LIKE '%{0}%'\".format(vessel_id)\n datas = POSTGRES.query_fetch_all(sql_str)\n\n if datas:\n\n for data in datas:\n\n vessel = []\n\n for vssl in data['vessel'].split(\",\"):\n vessel.append(vssl)\n\n ves = vessel.index(vessel_id)\n\n condition = []\n\n condition.append({\n \"col\": \"alarm_value_id\",\n \"con\": \"=\",\n \"val\": data['alarm_value_id']\n })\n\n if len(vessel) > 1:\n\n #DELETE VESSEL ON VESSEL LIST\n del vessel[ves]\n\n alarm_data = {}\n alarm_data['vessel'] = \",\".join(vessel)\n alarm_data['update_on'] = time.time()\n\n # UPDATE ALARM VALUE\n if POSTGRES.update('alarm_value', alarm_data, condition):\n pass\n # print(\"Alarm Value has been successfully updated.\")\n\n else:\n # print(\"Failed to update alarm value\")\n pass\n\n else:\n\n #IF ONLY ONE VESSEL DELETE ALARM VALUE ROW\n if POSTGRES.delete('alarm_value', condition):\n # print(\"Alarm Value has been successfully deleted!\")\n pass\n\n else:\n # print(\"Failed to delete alarm value.\")\n pass\n\n # CLOSE CONNECTION\n POSTGRES.close_connection()\n\n return 1\n\nDESIGNS = [\"device\", \"module\", \"option\", \"system\", \"value\"]\n\ntry:\n\n VESSEL_ID = sys.argv[1]\n VESSEL_REV = sys.argv[2]\n\n\nexcept:\n\n VESSEL_ID = \"a62784ebf1791db5d8ba89e7f2000a95\"\n\n VESSEL_REV = \"1-c347a5c4bc4a87046cb15864267711a2\"\n\n # print(\"No parameters!\")\n # print(\"ex: python3 delete_vessel.py {0} {1}\".format(VESSEL_ID, VESSEL_REV))\n\n sys.exit(0)\n\nRES = single_delete(VESSEL_ID, VESSEL_REV)\n\n# print (\"response: \", RES)\n\ndelete_vssl(VESSEL_ID)\n\ndelete_alarm_vessel(VESSEL_ID)\n\nfor design in DESIGNS:\n\n q = delete_query(VESSEL_ID, design)\n bulk_delete(q)\n\n # print(\" All {0} are deleted!\".format(design))\n\n# BEFORE RUN THIS\n# sudo service uwsgi stop && sudo service nginx stop\n","sub_path":"delete_vessel.py","file_name":"delete_vessel.py","file_ext":"py","file_size_in_byte":4265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"480635324","text":"class Solution:\n VALID_IP = set(str(i) for i in range(256))\n # @param s, a string\n # @return a list of strings\n def restoreIpAddresses(self, s):\n ans = []\n if len(s) > 12 or len(s) < 4:\n return ans\n for i in range(1, 4):\n for j in range(1, 4):\n for k in range(1, 4):\n candidate = [s[:i], s[i:i+j], s[i+j: i+j+k], s[i+j+k:]]\n if all(x in self.VALID_IP for x in candidate):\n ans.append('.'.join(candidate))\n return ans\n","sub_path":"leetcode/Restore IP Addresses.py","file_name":"Restore IP Addresses.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"413050564","text":"import sys\n\nfrom colorama import init\n\n# Init colors\ninit(autoreset=True)\n\n\ndef to_color(string, status=None, bold=False):\n if sys.stdout.isatty():\n attr = []\n if status is None:\n # yellow\n attr.append('33')\n elif status:\n # green\n attr.append('32')\n else:\n # red\n attr.append('31')\n if bold:\n attr.append('1')\n return '\\x1b[%sm%s\\x1b[0m' % (';'.join(attr), string)\n return string\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"624829585","text":"lst: list = input().split()\nnum: str = input()\nis_nan: bool = True\n\nfor i, elm in enumerate(lst):\n if elm == num:\n print(i, end=' ')\n is_nan = False\n\nif is_nan:\n print(None)\n","sub_path":"Multiple list index search.py","file_name":"Multiple list index search.py","file_ext":"py","file_size_in_byte":194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"2722672","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\nfrom selenium import webdriver\nimport win32gui\nimport win32con\nimport time\n\nchrome = webdriver.Chrome(r'E:\\chromedriver.exe')\nchrome.get('http://sahitest.com/demo/php/fileUpload.htm')\nupload = chrome.find_element_by_id('file')\nupload.click()\n#等待上传框打开\ntime.sleep(1)\n\n# win32gui\n#找到windows对话框,参数是(className,title),注意title并修改\ndialog = win32gui.FindWindow('#32770', u'打开') \n#下面三句依次寻找对象,直到找到输入框Edit对象的句柄 \nComboBoxEx32 = win32gui.FindWindowEx(dialog, 0, 'ComboBoxEx32', None) \nComboBox = win32gui.FindWindowEx(ComboBoxEx32, 0, 'ComboBox', None)\nEdit = win32gui.FindWindowEx(ComboBox, 0, 'Edit', None)\n#确定按钮Button\nbutton = win32gui.FindWindowEx(dialog, 0, 'Button', None) \n\n#往输入框输入绝对地址\nwin32gui.SendMessage(Edit, win32con.WM_SETTEXT, None, r'E:\\123.txt')\n#按button \nwin32gui.SendMessage(dialog, win32con.WM_COMMAND, 1, button) \n#等待上传完成\ntime.sleep(5)\n\nprint(upload.get_attribute('value'))\nchrome.quit()\n","sub_path":"selenium_upload_files.py","file_name":"selenium_upload_files.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"382381600","text":"import pickle\n\nfrom game import Board\nfrom mcts_alphaZero import MCTSPlayer\nfrom policy_value_net_numpy_pytorch import PolicyValueNetNumpy\n\nmodel_file=\"C:/APP/AlphaZero/exe/exe02/best_policy_8_8_5_new.model\"\n\ntry:\n policy_param = pickle.load(open(model_file, 'rb'))\nexcept:\n policy_param = pickle.load(open(model_file, 'rb'), encoding='bytes') # To support python3\n\n#把模型参数类型转为numpy类型\nfor k, v in policy_param.items():\n policy_param[k] = v.numpy() # v.cpu().numpy() 当模型是gup模型时候\n\ndef py_callback(board_state, currentPlayer, lastMove):\n \"\"\"\n :param board_state: 当前棋盘状态\n :param currentPlayer: 当前玩家\n :param lastMove: 棋盘中最后一步落子位置\n :return: 当前玩家的下一步落子位置\n \"\"\"\n states, sensible_moves = dealwithData(board_state)\n #计算下一步的落子位置\n move = run(states, sensible_moves, currentPlayer, lastMove)\n return move\n\n\ndef dealwithData(board_state):\n \"\"\"\n :param board_state: 当前棋盘转态,例如\"1212120000000000000000000000000000000000000000000000000000000000\"\n :return:states(已经落子的{位置:玩家}棋盘状态),sensible_moves(没有落子的位置)\n \"\"\"\n sensible_moves = []\n states = {}\n for i in range(len(board_state)):\n if not int(board_state[i]) == 0:\n states[i] = int(board_state[i])\n else:\n sensible_moves.append(i)\n return states, sensible_moves\n\n\ndef run(states, sensible_moves, currentPlayer, lastMove):\n n = 5\n width, height = 8, 8\n board = Board(width=width, height=height, n_in_row=n)\n board.init_board()\n\n board.states = states\n board.availables = sensible_moves\n board.current_player = currentPlayer\n board.last_move = lastMove\n\n best_policy = PolicyValueNetNumpy(width, height, policy_param)\n mcts_player = MCTSPlayer(best_policy.policy_value_fn, c_puct=5, n_playout=400)\n\n nextmove = mcts_player.get_action(board)\n\n return nextmove\n\n\nif __name__ == '__main__':\n py_callback(\"12121202000000000000000000000000000000000000000000000000000000000\", 1, 0)\n","sub_path":"alpha_zeroII.py","file_name":"alpha_zeroII.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"359489944","text":"# -*- coding: utf-8 -*-\n\n# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2020.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"GroverMinimumFinder module\"\"\"\n\nimport logging\nfrom typing import Optional, Dict, Union\nimport random\nimport math\nimport numpy as np\nfrom qiskit.aqua import QuantumInstance\nfrom qiskit.optimization.algorithms import OptimizationAlgorithm\nfrom qiskit.optimization.problems import OptimizationProblem\nfrom qiskit.optimization.converters import (OptimizationProblemToQubo,\n OptimizationProblemToNegativeValueOracle)\nfrom qiskit.optimization.results import GroverOptimizationResults\nfrom qiskit.optimization.results import OptimizationResult\nfrom qiskit.optimization.util import get_qubo_solutions\nfrom qiskit.aqua.algorithms.amplitude_amplifiers.grover import Grover\nfrom qiskit import Aer, QuantumCircuit\nfrom qiskit.providers import BaseBackend\n\n\nclass GroverMinimumFinder(OptimizationAlgorithm):\n \"\"\"Uses Grover Adaptive Search (GAS) to find the minimum of a QUBO function.\"\"\"\n\n def __init__(self, num_iterations: int = 3,\n quantum_instance: Optional[Union[BaseBackend, QuantumInstance]] = None) -> None:\n \"\"\"\n Args:\n num_iterations: The number of iterations the algorithm will search with\n no improvement.\n quantum_instance: Instance of selected backend, defaults to Aer's statevector simulator.\n \"\"\"\n self._n_iterations = num_iterations\n if quantum_instance is None or isinstance(quantum_instance, BaseBackend):\n backend = quantum_instance or Aer.get_backend('statevector_simulator')\n quantum_instance = QuantumInstance(backend)\n self._quantum_instance = quantum_instance\n self._logger = logging.getLogger(__name__)\n\n def is_compatible(self, problem: OptimizationProblem) -> Optional[str]:\n \"\"\"Checks whether a given problem can be solved with this optimizer.\n\n Checks whether the given problem is compatible, i.e., whether the problem can be converted\n to a QUBO, and otherwise, returns a message explaining the incompatibility.\n\n Args:\n problem: The optization problem to check compatibility.\n\n Returns:\n Returns ``None`` if the problem is compatible and else a string with the error message.\n \"\"\"\n return OptimizationProblemToQubo.is_compatible(problem)\n\n def solve(self, problem: OptimizationProblem) -> OptimizationResult:\n \"\"\"Tries to solves the given problem using the optimizer.\n\n Runs the optimizer to try to solve the optimization problem. If problem is not convex,\n this optimizer may raise an exception due to incompatibility, depending on the settings.\n\n Args:\n problem: The problem to be solved.\n\n Returns:\n The result of the optimizer applied to the problem.\n\n Raises:\n QiskitOptimizationError: If the problem is incompatible with the optimizer.\n \"\"\"\n\n # convert problem to QUBO\n qubo_converter = OptimizationProblemToQubo()\n problem_ = qubo_converter.encode(problem)\n\n # TODO: How to get from Optimization Problem?\n num_output_qubits = 6\n\n # Variables for tracking the optimum.\n optimum_found = False\n optimum_key = math.inf\n optimum_value = math.inf\n threshold = 0\n n_key = problem_.variables.get_num()\n n_value = num_output_qubits\n\n # Variables for tracking the solutions encountered.\n num_solutions = 2**n_key\n keys_measured = []\n\n # Variables for result object.\n func_dict = {}\n operation_count = {}\n iteration = 0\n\n # Variables for stopping if we've hit the rotation max.\n rotations = 0\n max_rotations = int(np.ceil(100*np.pi/4))\n\n # Initialize oracle helper object.\n orig_constant = problem_.objective.get_offset()\n measurement = not self._quantum_instance.is_statevector\n opt_prob_converter = OptimizationProblemToNegativeValueOracle(n_value,\n measurement)\n\n while not optimum_found:\n m = 1\n improvement_found = False\n\n # Get oracle O and the state preparation operator A for the current threshold.\n problem_.objective.set_offset(orig_constant - threshold)\n a_operator, oracle, func_dict = opt_prob_converter.encode(problem_)\n\n # Iterate until we measure a negative.\n loops_with_no_improvement = 0\n while not improvement_found:\n # Determine the number of rotations.\n loops_with_no_improvement += 1\n rotation_count = int(np.ceil(random.uniform(0, m-1)))\n rotations += rotation_count\n\n # Apply Grover's Algorithm to find values below the threshold.\n if rotation_count > 0:\n grover = Grover(oracle, init_state=a_operator, num_iterations=rotation_count)\n circuit = grover.construct_circuit(\n measurement=self._quantum_instance.is_statevector\n )\n\n else:\n circuit = a_operator._circuit\n\n # Get the next outcome.\n outcome = self._measure(circuit, n_key, n_value)\n k = int(outcome[0:n_key], 2)\n v = outcome[n_key:n_key + n_value]\n\n # Convert the binary string to integer.\n int_v = self._bin_to_int(v, n_value) + threshold\n v = self._twos_complement(int_v, n_value)\n\n self._logger.info('Iterations: %s', rotation_count)\n self._logger.info('Outcome: %s', outcome)\n self._logger.info('Value: %s = %s', v, int_v)\n\n # If the value is an improvement, we update the iteration parameters (e.g. oracle).\n if int_v < optimum_value:\n optimum_key = k\n optimum_value = int_v\n self._logger.info('Current Optimum Key: %s', optimum_key)\n self._logger.info('Current Optimum Value: %s', optimum_value)\n if v.startswith('1'):\n improvement_found = True\n threshold = optimum_value\n else:\n # No better number after the max number of iterations, so we assume the optimal.\n if loops_with_no_improvement >= self._n_iterations:\n improvement_found = True\n optimum_found = True\n\n # Using Durr and Hoyer method, increase m.\n # TODO: Give option for a rotation schedule, or for different lambda's.\n m = int(np.ceil(min(m * 8/7, 2**(n_key / 2))))\n self._logger.info('No Improvement. M: %s', m)\n\n # Check if we've already seen this value.\n if k not in keys_measured:\n keys_measured.append(k)\n\n # Stop if we've seen all the keys or hit the rotation max.\n if len(keys_measured) == num_solutions or rotations >= max_rotations:\n improvement_found = True\n optimum_found = True\n\n # Track the operation count.\n operations = circuit.count_ops()\n operation_count[iteration] = operations\n iteration += 1\n self._logger.info('Operation Count: %s\\n', operations)\n\n # Get original key and value pairs.\n func_dict[-1] = orig_constant\n solutions = get_qubo_solutions(func_dict, n_key)\n\n # If the constant is 0 and we didn't find a negative, the answer is likely 0.\n if optimum_value >= 0 and orig_constant == 0:\n optimum_key = 0\n opt_x = [1 if s == '1' else 0 for s in ('{0:%sb}' % n_key).format(optimum_key)]\n\n # Build the results object.\n grover_results = GroverOptimizationResults(operation_count, rotations, n_key, n_value,\n func_dict)\n result = OptimizationResult(x=opt_x, fval=solutions[optimum_key],\n results={\"grover_results\": grover_results,\n \"qubo_converter\": qubo_converter})\n\n # cast binaries back to integers\n result = qubo_converter.decode(result)\n\n return result\n\n def _measure(self, circuit: QuantumCircuit, n_key: int, n_value: int) -> str:\n \"\"\"Get probabilities from the given backend, and picks a random outcome.\"\"\"\n probs = self._get_probs(n_key, n_value, circuit)\n freq = sorted(probs.items(), key=lambda x: x[1], reverse=True)\n\n # Pick a random outcome.\n freq[len(freq)-1] = (freq[len(freq)-1][0], 1 - sum([x[1] for x in freq[0:len(freq)-1]]))\n idx = np.random.choice(len(freq), 1, p=[x[1] for x in freq])[0]\n self._logger.info('Frequencies: %s', freq)\n\n return freq[idx][0]\n\n def _get_probs(self, n_key: int, n_value: int, qc: QuantumCircuit) -> Dict[str, float]:\n \"\"\"Gets probabilities from a given backend.\"\"\"\n # Execute job and filter results.\n result = self._quantum_instance.execute(qc)\n if self._quantum_instance.is_statevector:\n state = np.round(result.get_statevector(qc), 5)\n keys = [bin(i)[2::].rjust(int(np.log2(len(state))), '0')[::-1]\n for i in range(0, len(state))]\n probs = [np.round(abs(a)*abs(a), 5) for a in state]\n f_hist = dict(zip(keys, probs))\n hist = {}\n for key in f_hist:\n new_key = key[:n_key] + key[n_key:n_key+n_value][::-1] + key[n_key+n_value:]\n hist[new_key] = f_hist[key]\n else:\n state = result.get_counts(qc)\n shots = self._quantum_instance.run_config.shots\n hist = {}\n for key in state:\n hist[key[:n_key] + key[n_key:n_key+n_value][::-1] + key[n_key+n_value:]] = \\\n state[key] / shots\n hist = dict(filter(lambda p: p[1] > 0, hist.items()))\n\n return hist\n\n @staticmethod\n def _twos_complement(v: int, n_bits: int) -> str:\n \"\"\"Converts an integer into a binary string of n bits using two's complement.\"\"\"\n assert -2**n_bits <= v < 2**n_bits\n\n if v < 0:\n v += 2**n_bits\n bin_v = bin(v)[2:]\n else:\n format_string = '{0:0'+str(n_bits)+'b}'\n bin_v = format_string.format(v)\n\n return bin_v\n\n @staticmethod\n def _bin_to_int(v: str, num_value_bits: int) -> int:\n \"\"\"Converts a binary string of n bits using two's complement to an integer.\"\"\"\n if v.startswith(\"1\"):\n int_v = int(v, 2) - 2 ** num_value_bits\n else:\n int_v = int(v, 2)\n\n return int_v\n","sub_path":"qiskit/optimization/algorithms/grover_minimum_finder.py","file_name":"grover_minimum_finder.py","file_ext":"py","file_size_in_byte":11412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"248262786","text":"import os\nimport shutil\n\n\"\"\"\n百变主题 辅助生成工具\n\"\"\"\n\n\n# 纯汉字 检查\n# 检验是否含有中文字符\ndef isContainChinese(s):\n for c in s:\n if ('\\u4e00' <= c <= '\\u9fa5'):\n return True\n return False\n\n\n# 检验是否全是中文字符\ndef is_all_chinese(s):\n for c in s:\n if not ('\\u4e00' <= c <= '\\u9fa5'):\n return False\n return True\n\n\n# 全是英文\ndef is_english(msg):\n is_english_str = False\n for uchar in msg:\n \"\"\"判断一个unicode是否是英文字母\"\"\"\n if (u'\\u0041' <= uchar <= u'\\u005a') or (u'\\u0061' <= uchar <= u'\\u007a'):\n is_english_str = True\n else:\n is_english_str = False\n break\n return is_english_str\n\n\ndef write_single_row(f_name, app_icon_text):\n with open('single_row.xml', 'r') as f:\n manifest_text = f.read().replace('name', app_icon_text.lower())\n # print(\"保存配置文件……\")\n file = open(f_name, 'w+', encoding='utf-8')\n file.write(manifest_text)\n file.close()\n\n\ndef write_double_row(f_name, first_line_name, second_line_name):\n with open('double_row.xml', 'r') as f:\n manifest_text = f.read().replace('name1', first_line_name).replace('name2', second_line_name)\n # print(\"保存配置文件……\")\n file = open(f_name, 'w+', encoding='utf-8')\n file.write(manifest_text)\n file.close()\n\n\nif __name__ == '__main__':\n # 百变主题的根目录\n dir_fancy_icons = \"fancy_icons/\"\n # 百变主题背景icon所在路径\n dir_icon_background = \"transparent.png\"\n app_map = {'浏览器': 'com.android.browser',\n '日历': 'com.android.calendar',\n '相机': 'com.android.camera',\n '联系人': 'com.android.contacts',\n '电话': 'com.android.contacts',\n '时钟': 'com.android.deskclock',\n '电子邮件': 'com.android.email',\n '文件管理': 'com.android.fileexplorer',\n '短信': 'com.android.mms',\n '设置': 'com.android.settings',\n '个性主题': 'com.android.thememanager',\n '小米钱包': 'com.mipay.wallet',\n '计算器': 'com.miui.calculator',\n '相册': 'com.miui.gallery',\n '便签': 'com.miui.notes',\n '天气': 'com.miui.weather2',\n '应用商店': 'com.xiaomi.market',\n '扫一扫': 'com.xiaomi.scanner',\n '酷我音乐': 'cn.kuwo.player',\n '最右': 'cn.xiaochuankeji.tieba',\n '币快报': 'com.link.beenews',\n '英语流利说': 'com.liulishuo.engzo',\n '爱壁纸': 'com.lovebizhi.wallpaper',\n ' 360手机助手': 'com.qihoo.appstore',\n '小米贷款': 'com.xiaomi.loan',\n '网易有道词典': 'com.youdao.dict',\n '饿了么': 'me.ele',\n '下载管理': 'com.android.providers.downloads.ui',\n '录音机': 'com.android.soundrecorder',\n 'USIM卡应用': 'com.android.stk',\n '用户反馈': 'com.miui.bugreport',\n '指南针': 'com.miui.compass',\n '音乐': 'com.miui.player',\n '屏幕录制': 'com.miui.screenrecorder',\n '��全中心': 'com.miui.securitycenter',\n '小米视频': 'com.miui.video',\n '全球上网': 'com.miui.virtualsim',\n '小爱同学': 'com.miui.voiceassist',\n '游戏中心': 'com.xiaomi.gamecenter',\n '我的小米': 'com.xiaomi.vipaccount',\n '招商银行': 'cmb.pb',\n '慕课网': 'cn.com.open.mooc',\n '新华字典': 'cn.dictcn.android.digitize.swg_xhzd_21003',\n '个人所得税': 'cn.gov.tax.its',\n '车友头条': 'cn.mucang.android.qichetoutiao',\n 'WPS Office': 'cn.wps.moffice_eng',\n '皮皮搞笑': 'cn.xiaochuankeji.zuiyouLite',\n '铁路12306': 'com.MobileTicket',\n 'UC浏览器': 'com.UCMobile',\n '中国农业银行': 'com.android.bankabc',\n 'Metro大都会': 'com.app.shanghai.metro',\n '高德地图': 'com.autonavi.minimap',\n '小学语文同步辅导': 'com.babybar.primchinese',\n '百词斩爱阅读': 'com.baicizhan.ireading',\n '百度网盘': 'com.baidu.netdisk',\n '聚合新闻': 'com.binny.openapi',\n '多开分身': 'com.bly.dkplat',\n '菜鸟裹裹': 'com.cainiao.wireless',\n '中华会计网校': 'com.cdel.accmobile',\n '唱吧': 'com.changba',\n '中国建设银行': 'com.chinamworld.main',\n '和飞信': 'com.chinasofti.rcs',\n '掌上生活': 'com.cmbchina.ccd.pluto.cmbActivity',\n '电信营业厅': 'com.ct.client',\n '掘金': 'com.daimajia.gold',\n '大众点评': 'com.dianping.v1',\n '万能遥控': 'com.duokan.phone.remotecontroller',\n '阅读': 'com.duokan.reader',\n '虎牙直播': 'com.duowan.kiwi',\n '支付宝': 'com.eg.android.AlipayGphone',\n '考研万题库': 'com.exam8.KYzhengzhi',\n '福昕PDF阅读器': 'com.foxit.mobile.pdf.lite',\n 'Keep': 'com.gotokeep.keep',\n '驾考宝典': 'com.handsgo.jiakao.android',\n 'Boss直聘': 'com.hpbr.bosszhipin',\n '虎扑': 'com.hupu.games',\n '中国工商银行': 'com.icbc',\n '考研英语': 'com.ikaoshi.english.kaoyanreading',\n '考研政治题库宝典': 'com.ikaoshi.kaoyan.politics',\n '小学语文': 'com.itfirer.primaryschoolchinese',\n '京东金融': 'com.jd.jrapp',\n '简书': 'com.jianshu.haruki',\n '世纪佳缘': 'com.jiayuan',\n '京东': 'com.jingdong.app.mall',\n '百词斩': 'com.jiongji.andriod.card',\n '前程无忧51job': 'com.job.android',\n '表情广场': 'com.kk.biaoqing',\n '古诗词典': 'com.kk.poem',\n 'Vysor': 'com.koushikdutta.vysor',\n '酷狗音乐': 'com.kugou.android',\n '来分期': 'com.laifenqi.android.app',\n '乐学高考': 'com.lexue.courser',\n '贝壳找房': 'com.lianjia.beike',\n '高中知识点大全': 'com.ljy.gzzsddq',\n '得到': 'com.luojilab.player',\n '摩拜单车': 'com.mobike.mobikeapp',\n '高考化学通': 'com.moyun365.android.gkchemistrytong',\n '网商银行': 'com.mybank.android.phone',\n 'ZAKER新闻': 'com.myzaker.ZAKER_Phone',\n '网易邮箱': 'com.netease.mobimail',\n '花生地铁': 'com.nfyg.hsbb',\n '物理大师-初高中版': 'com.physicmaster',\n '平安金管家': 'com.pingan.lifeinsurance',\n '平安口袋银行': 'com.pingan.paces.ccms',\n '爱奇艺': 'com.qiyi.video',\n 'QQ空间': 'com.qzone',\n '即刻': 'com.ruguoapp.jike',\n '美团': 'com.sankuai.meituan',\n '名人朋友圈': 'com.sencent.mm',\n '微博': 'com.sina.weibo',\n '手机营业厅': 'com.sinovatech.unicom.ui',\n '今日头条': 'com.ss.android.article.news',\n '抖音短视频': 'com.ss.android.ugc.aweme',\n '考研帮': 'com.tal.kaoyan',\n '闲鱼': 'com.taobao.idlefish',\n '手机淘宝': 'com.taobao.taobao',\n '飞猪': 'com.taobao.trip',\n '脉脉': 'com.taou.maimai',\n 'QQ邮箱': 'com.tencent.androidqqmail',\n '微信': 'com.tencent.mm',\n 'QQ': 'com.tencent.mobileqq',\n '腾讯视频': 'com.tencent.qqlive',\n 'QQ同步助手': 'com.tencent.qqpim',\n '掌上英雄联盟': 'com.tencent.qt.qtl',\n 'QQ影音': 'com.tencent.research.drop',\n '绝地求生 刺激战场': 'com.tencent.tmgp.pubgmhd',\n '王者荣耀': 'com.tencent.tmgp.sgame',\n 'QQ安全中心': 'com.tencent.token',\n '微信读书': 'com.tencent.weread',\n '企业微信': 'com.tencent.wework',\n '天眼查企业查询': 'com.tianyancha.skyeye',\n '云闪付': 'com.unionpay',\n '下厨房': 'com.xiachufang',\n '高中语文': 'com.xiangqi.gzchinese',\n '小米社区': 'com.xiaomi.bbslite',\n '小爱音箱': 'com.xiaomi.mico',\n '小米省钱购': 'com.xiaomi.o2o',\n '小米商城': 'com.xiaomi.shop',\n '喜马拉雅': 'com.ximalaya.ting.android',\n '高中数学': 'com.xlink.gaozhongshuxuebibei',\n '高中物理知识大全': 'com.xlink.gaozhongwulizhishidaquan',\n '拼多多': 'com.xunmeng.pinduoduo',\n '优酷视频': 'com.youku.phone',\n '考研派': 'com.yuekao.kaoyanquestion',\n '高考蜂背': 'com.zhouyue.Bee',\n '招联金融': 'com.zl.fqbao',\n '携程旅行': 'ctrip.android.view',\n '企业微信分身': 'dkplugin.lse.ptf',\n '虾米音乐': 'fm.xiami.main',\n 'imToken': 'im.token.app',\n '多闪': 'my.maya.android',\n '二年级语文下册': 'org.cocos2dx.yuwenbubian3014',\n '小学语文五年级下': 'org.cocos2dx.yuwenbubian3018',\n '小学语文四年级下': 'org.cocos2dx.yuwenbubian3020',\n 'IONC Token': 'org.ionchain.wallet',\n '肖秀荣政治': 'xxrzz.hskaoyan'\n }\n\n for key, value in app_map.items():\n # print(key + \":\" + value)\n\n # 拼接一个新文件夹的路径\n icon_pkg_name_folder_path = os.path.join(dir_fancy_icons, value)\n\n # print(\"即将创建的文件夹的路径=\" + os.path.join(dir_fancy_icons, value))\n\n \"\"\"\n 判断是不是日历和天气\n 如果是,跳过读写\n\n \"\"\"\n\n # 创建百变图标的文件目录\n \"\"\"\n 1 判断文件是否存在\n 文件夹不存在,则创建文件夹\n \"\"\"\n if key == \"日历\" or key == \"天气\":\n print(\"跳过 :\" + key)\n continue\n if not os.path.exists(icon_pkg_name_folder_path):\n # 创建一个新目录\n os.makedirs(icon_pkg_name_folder_path)\n # print(\"文件夹已存在:\" + icon_pkg_name_folder_path)\n # 创建完成之后,拷贝背景icon\n \"\"\"\n 2 判断背景图标是否存在,不存在则拷贝过去\n \"\"\"\n icon_bg_path = os.path.join(icon_pkg_name_folder_path, \"bg.png\")\n print(icon_bg_path)\n if not os.path.exists(icon_bg_path):\n shutil.copyfile(dir_icon_background, icon_pkg_name_folder_path + \"/bg.png\")\n # print(\"背景图标存在\")\n\n # 文件读写\n # 纯汉字\n file_name = os.path.join(icon_pkg_name_folder_path, \"manifest.xml\")\n # print(key+\" \"+str(len(key)))\n key = key.replace(' ', '')\n count = len(key)\n if count <= 3 or is_english(key): # 单行,居中模板\n # print(key)\n write_single_row(file_name, key)\n elif count == 4: # 双行,居中 王者荣耀\n first_name = key[0:2] # 王者\n second_name = key[2:4] # 荣耀\n # print(first_name)\n # print(second_name)\n write_double_row(file_name, first_name, second_name)\n # print(\"保存配置文件……Done!\")\n elif count == 5: # 双行,居中 王者荣耀啊\n first_name = key[0:2] # 王者\n second_name = key[2:5] # 荣耀啊\n # print(first_name)\n # print(second_name)\n if key.isdecimal():\n write_single_row(file_name, key)\n else:\n write_double_row(file_name, first_name, second_name)\n # print(\"保存配置文件……Done!\")\n elif count == 6: # 双行,居中 王者荣耀啊\n first_name = key[0:3] # 王者\n second_name = key[3:6] # 荣耀啊\n write_double_row(file_name, first_name, second_name)\n elif count == 7:\n index = int(len(key) / 2 + 1)\n first_name = key[0:index] # 王者\n second_name = key[index:len(key)] # 荣耀啊\n write_double_row(file_name, first_name, second_name)\n elif count == 8:\n index = int(len(key) / 2)\n first_name = key[0:index] # 王者\n second_name = key[index:len(key)] # 荣耀啊\n write_double_row(file_name, first_name, second_name)\n","sub_path":"themes/script/fancyicon/mkfancyicons.py","file_name":"mkfancyicons.py","file_ext":"py","file_size_in_byte":13128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"25506216","text":"import re\n\nfrom oelint_adv.cls_item import Function\nfrom oelint_adv.cls_item import Variable\nfrom oelint_adv.cls_rule import Rule\n\n\nclass VarPnBpnUsage(Rule):\n def __init__(self):\n super().__init__(id=\"oelint.func.machinespecific\",\n severity=\"error\",\n message=\"'{}' is set machine specific ['{}'], but a matching COMPATIBLE_MACHINE entry is missing\")\n\n def check(self, _file, stash):\n res = []\n items = stash.GetItemsFor(filename=_file, classifier=Function.CLASSIFIER,\n attribute=Function.ATTR_FUNCNAME)\n for i in items:\n _machine = i.GetMachineEntry()\n if not _machine:\n continue\n if i.FuncName in ['pkg_preinst', 'pkg_postinst', 'pkg_prerm', 'pkg_postrm'] and _machine.startswith(\"${PN}\"):\n continue\n if _machine in [\"ptest\"]:\n # known exceptions\n continue\n _comp = stash.GetItemsFor(filename=_file, classifier=Variable.CLASSIFIER,\n attribute=Variable.ATTR_VAR, attributeValue=\"COMPATIBLE_MACHINE\")\n if not any(_comp):\n res += self.finding(i.Origin, i.InFileLine,\n override_msg=self.Msg.format(i.FuncName, _machine))\n continue\n _vals = [x.VarValueStripped.lstrip(\n \"|\") for x in _comp if x.VarValueStripped]\n if not any(re.match(v, _machine) or (_machine == \"qemuall\" and \"qemu\" in v) for v in _vals):\n res += self.finding(i.Origin, i.InFileLine,\n override_msg=self.Msg.format(i.FuncName, _machine))\n return res\n","sub_path":"oelint_adv/rule_base/rule_func_machinespec.py","file_name":"rule_func_machinespec.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"167569630","text":"import newspaper\nimport argparse\nimport csv\n\ndef scrape(url, outfile):\n with open (outfile, mode='w') as file:\n file_writer = csv.writer(file, delimiter=',')\n\n print('Building paper from: ' + url)\n paper = newspaper.build(url, memoize_articles=False, fetch_images=False)\n for article in paper.articles:\n try:\n article.download()\n article.parse()\n article.nlp()\n print('Wrote to file: ' + article.url)\n file_writer.writerow([article.text, article.summary, article.url])\n except Exception as e:\n print('Skipped: ' + article.url + ' with exception ' + str(e))\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('url')\n parser.add_argument('outfile')\n args = parser.parse_args()\n scrape(args.url, args.outfile)\n\nif __name__ == '__main__':\n main()","sub_path":"summarization/scripts/news-scraper/news-scraper.py","file_name":"news-scraper.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"115613139","text":"\"\"\"Util functions for the vision datasets.\"\"\"\nfrom typing import Any, List\n\nfrom torch.utils.data import Dataset, Subset, random_split\n\n__all__ = [\"set_transform\", \"train_test_split\"]\n\n\ndef set_transform(dataset: Dataset, transform: Any) -> None:\n \"\"\"Set the transform of a dataset to the specified transform.\"\"\"\n if hasattr(dataset, \"dataset\"):\n set_transform(dataset.dataset, transform) # type: ignore[attr-defined]\n elif isinstance(dataset, Dataset):\n if hasattr(dataset, \"transform\"):\n dataset.transform = transform # type: ignore[attr-defined]\n elif hasattr(dataset, \"datasets\"):\n for dtst in dataset.datasets: # type: ignore[attr-defined]\n set_transform(dtst, transform)\n\n\ndef train_test_split(dataset: Dataset, train_pcnt: float) -> List[Subset]:\n \"\"\"Split a dataset into train and test splits, of sizes dictated by the train percentage.\"\"\"\n assert 0 < train_pcnt <= 1\n curr_len = len(dataset)\n train_len = round(train_pcnt * curr_len)\n test_len = curr_len - train_len\n\n return random_split(dataset, lengths=[train_len, test_len])\n","sub_path":"ethicml/vision/data/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"215105017","text":"from cryptography.hazmat.primitives import serialization\r\nfrom cryptography.hazmat.backends import default_backend\r\nfrom cryptography.hazmat.primitives.asymmetric import rsa\r\n\r\nprivate_key = rsa.generate_private_key(\r\n public_exponent=65537,\r\n key_size=2048,\r\n backend=default_backend()\r\n )\r\n\r\nprint(private_key)\r\n\r\npem = private_key.private_bytes(\r\nencoding=serialization.Encoding.PEM,\r\nformat=serialization.PrivateFormat.TraditionalOpenSSL,\r\nencryption_algorithm=serialization.NoEncryption()\r\n)\r\npem.splitlines()[0]\r\nprint(pem)\r\n\r\nprik=pem\r\nfh = open(\"C:/Users/123/Desktop/rsakey/A/private_key.pem\", \"wb\")\r\nfh.write(prik)\r\nfh.close()\r\n\r\npublic_key = private_key.public_key()\r\npem = public_key.public_bytes(\r\nencoding=serialization.Encoding.PEM,\r\nformat=serialization.PublicFormat.SubjectPublicKeyInfo\r\n)\r\npem.splitlines()[0]\r\npubk=pem\r\nfh1 = open(\"C:/Users/123/Desktop/rsakey/A/public_key.pem\", \"wb\")\r\nfh1.write(pubk)\r\nfh1.close()\r\n\r\n","sub_path":"rsaKeyGen.py","file_name":"rsaKeyGen.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"538727049","text":"\"\"\"\n\"\"\"\nimport numpy as np\n\n\nclass View:\n\n def __init__(self, fig, ax, data, mark, x_axis, y_axis, marks=[],\n display_options={}):\n \"\"\"\n \"\"\"\n # XXX: do value checking\n\n self.fig = fig\n self.ax = ax\n self.canvas = ax.figure.canvas\n # Create a convenient view for the data\n self.layers = []\n self.ims = []\n self.mark = mark\n self.marks = marks\n self.x_axis = x_axis\n self.y_axis = y_axis\n self.x_marks = []\n self.y_marks = []\n self.active = False\n self.active_x = None\n self.active_y = None\n self.callbacks = []\n self.add_layer(data, display_options)\n ax.invert_yaxis()\n ax.axis('off')\n self.background = None\n self.canvas.mpl_connect('motion_notify_event',\n self.motion_notify_event)\n self.canvas.mpl_connect('button_press_event',\n self.button_press_event)\n self.canvas.mpl_connect('button_release_event',\n self.button_release_event)\n self.canvas.mpl_connect('draw_event',\n self.clear)\n\n def clear(self, event):\n self.background = self.canvas.copy_from_bbox(self.ax.bbox)\n self._update()\n\n def add_layer(self, data, display_options={}):\n # split options\n pl_options = {}\n pn_options = {}\n for k, v in display_options.items():\n if k.startswith('pynax'):\n pn_options[k] = v\n else:\n pl_options[k] = v\n\n axis_id = [mark.axis.id for mark in self.marks]\n data = data.transpose(axis_id + [self.mark.axis.id,\n self.y_axis.id,\n self.x_axis.id])\n if len(self.layers) != 0:\n if self.layers[0][0].shape != data.shape:\n raise ValueError(\"All layers must have the same \"\n \"shape as the data\")\n if not 'vmin' in pl_options:\n pl_options['vmin'] = np.min(data)\n if not 'vmax' in pl_options:\n pl_options['vmax'] = np.max(data)\n data_ = data\n for mark_ in self.marks:\n data_ = data[mark_.value]\n\n im = self.ax.imshow(data_[self.mark.value], **pl_options)\n if 'pynax_colorbar' in pn_options \\\n and pn_options['pynax_colorbar']:\n self.ax.figure.colorbar(im, ax=self.ax)\n self.layers.append((data, pl_options))\n self.ims.append(im)\n\n def redraw_layers(self):\n # Remove all images\n for im in self.ims:\n im.remove()\n self.ims = []\n for data, options in self.layers:\n data_ = data\n for mark_ in self.marks:\n data_ = data_[mark_.value]\n im = self.ax.imshow(data_[self.mark.value], **options)\n self.ims.append(im)\n self.canvas.draw()\n self._update()\n\n def add_mark(self, mark):\n if mark.axis == self.x_axis:\n line = self.ax.axvline(mark.value, animated=True,\n **mark.display_options)\n self.x_marks.append((mark, line))\n elif mark.axis == self.y_axis:\n line = self.ax.axhline(mark.value, animated=True,\n **mark.display_options)\n self.y_marks.append((mark, line))\n else:\n raise ValueError('This mark does not correspond to any axis')\n\n def button_press_event(self, event):\n # Left mouse button\n if event.button != 1 or event.inaxes is None \\\n or event.inaxes != self.ax:\n return\n self.active = True\n # Find closest marks\n if len(self.x_marks) != 0:\n dist = np.inf\n for x, l in self.x_marks:\n if abs(event.xdata - x.value) < dist:\n dist = abs(event.xdata - x.value)\n self.active_x = x, l\n if len(self.y_marks) != 0:\n dist = np.inf\n for y, l in self.y_marks:\n if abs(event.ydata - y.value) < dist:\n dist = abs(event.ydata - y.value)\n self.active_y = y, l\n\n def add_callback(self, callback):\n self.callbacks.append(callback)\n\n def button_release_event(self, event):\n if self.active:\n self.motion_notify_event(event)\n self.active = False\n self.active_x = None\n self.active_y = None\n if event.button != 1 and event.inaxes == self.ax:\n # Get the value of the clicked pixel\n data_ = self.layers[-1][0]\n for mark_ in self.marks:\n data_ = data_[mark_.value]\n data_ = data_[self.mark.value]\n value = data_[event.ydata, event.xdata]\n # print value\n for callback in self.callbacks:\n try:\n callback(self, value)\n except:\n continue\n\n def motion_notify_event(self, event):\n if not self.active or event.inaxes != self.ax:\n return\n changes = []\n if self.active_x is not None and \\\n int(self.active_x[0].value) != int(event.xdata):\n self.active_x[0].value = int(event.xdata)\n changes.append(self.active_x[0])\n if self.active_y is not None and \\\n int(self.active_y[0].value) != int(event.ydata):\n self.active_y[0].value = int(event.ydata)\n changes.append(self.active_y[0])\n if len(changes) != 0:\n # propagate_changes will be called by the figure\n self.fig.propagate_changes(changes)\n\n def _update(self):\n if self.background is not None:\n self.canvas.restore_region(self.background)\n for _, line in self.x_marks:\n self.ax.draw_artist(line)\n for _, line in self.y_marks:\n self.ax.draw_artist(line)\n self.canvas.blit(self.ax.bbox)\n\n def propagate_changes(self, changes):\n redraw = False\n update = False\n for mark in changes:\n # Check main image\n if mark == self.mark:\n self.mark.value = mark.value\n redraw = True\n else:\n for mark_ in self.marks:\n if mark.axis == mark_.axis:\n mark_.value = mark.value\n redraw = True\n if mark.axis == self.x_axis:\n for x_mark, line in self.x_marks:\n if mark == x_mark:\n x_mark.value = mark.value\n line.set_xdata((mark.value, mark.value))\n update = True\n if mark.axis == self.y_axis:\n for y_mark, line in self.y_marks:\n if mark == y_mark:\n y_mark.value = mark.value\n line.set_ydata((mark.value, mark.value))\n update = True\n if redraw:\n self.redraw_layers()\n elif update:\n self._update()\n","sub_path":"pynax/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":7270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"483304154","text":"\"\"\" Wibed command-api functionality. \"\"\"\nimport logging\n\nfrom flask import Blueprint, jsonify\nfrom models.node import Node\n\nbpNodeInfoAPI = Blueprint(\"userAPI.nodeinfo\", __name__, template_folder=\"../templates\")\n\ndef getInfo(node):\n logging.debug(\"The node model is: %s\",node.model)\n output = {\"status\": str(node.status),\n\t \"model\": node.model,\n \"firmware\": node.installedFirmware.version,\n\t \"description\": node.description\n\t }\n logging.debug(output)\n return output\n\n@bpNodeInfoAPI.route(\"/nodeinfo/\", methods=[\"GET\"])\ndef nodeInfo(id):\n node = Node.query.get(id)\n if node:\n output = getInfo(node)\n return jsonify(output)\n else:\n return jsonify({\"error\": \"wrong ID\"})\n","sub_path":"blueprints/userapi/nodeinfoapi.py","file_name":"nodeinfoapi.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"592815432","text":"\r\n\r\nimport os\r\nimport re\r\n\r\nINPUT_DIR = './files'\r\nOUTPUT_DIR = './final'\r\n\r\ndef get_texts():\r\n names = []\r\n for name in os.listdir(INPUT_DIR):\r\n name = os.path.join('files', name)\r\n names.append(name)\r\n return names\r\n\r\ndef parcer(names):\r\n for i in names:\r\n with open(i, encoding='utf-8') as fh:\r\n text = fh.read()\r\n match = re.findall(r'# newdoc id = (\\S+)\\n((:?(?!# newdoc).*\\n)+)', text, flags=re.DOTALL)\r\n \r\n\r\n\r\ndef main():\r\n names = get_texts()\r\n print(names)\r\n matcher = parcer(names)\r\n \r\n\r\nmain()\r\n","sub_path":"python.py","file_name":"python.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"304362121","text":"from selenium.webdriver import Chrome\nfrom selenium.webdriver import Firefox\nfrom Library import ConfigReader\n\ndef startBrowser():\n global driver\n if ((ConfigReader.readConfigData('Details', 'Browser')) == 'chrome'):\n path = \"D:\\\\pythonpr\\\\pythonProject1\\\\chromedriver\"\n driver = Chrome(executable_path=path)\n elif ((ConfigReader.readConfigData('Details', 'Browser')) == 'firefox'):\n # path = \"D:\\\\pythonpr\\\\pythonProject1\\\\geckodriver\"\n path = \"./Driver/geckodriver.exe\"\n driver = Firefox(executable_path=path)\n else:\n # path = \"D:\\\\pythonpr\\\\pythonProject1\\\\chromedriver\"\n path = \"./Driver/chromedriver.exe\"\n driver = Chrome(executable_path=path)\n\n driver.get(ConfigReader.readConfigData('Details', 'Application_URL'))\n\n driver.maximize_window()\n return driver\n\ndef closeBrowser():\n driver.close()","sub_path":"Base/InitiateDriver.py","file_name":"InitiateDriver.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"636462358","text":"\"\"\"A module for representing Fenc files.\"\"\"\nfrom . parser import FencParser\n\n\nclass Fenc(object):\n \"\"\"A class that represents a fenc file.\"\"\"\n\n def from_data(data):\n \"\"\"Construct a Fenc from an array of characters.\"\"\"\n return Fenc(FencParser(data).parse())\n\n def from_file(filename):\n \"\"\"Construct a Fenc from a file.\"\"\"\n with open(filename) as f:\n # Read all to data\n data = f.read()\n # defer to parser\n return Fenc.from_data(data)\n\n def __init__(self, tree):\n \"\"\"Initialise new Fenc object.\"\"\"\n self.__tree = tree\n\n def to_dict(self, *, lower_keys=False):\n \"\"\"Convert contained tree to nested dicts.\n\n This does not preserve multiple equal section headers nor\n multiple definitions with the same key under one header. Use\n to_pairs for that!\n\n If lower_keys is true, all keys are converted to lower-case\n \"\"\"\n ret = {}\n try:\n sections = self.__tree._children\n for section in sections:\n # All children of this node are FencSections\n key = section.header()\n if lower_keys:\n key = key.lower()\n val = {}\n try:\n definitions = section._children[1:]\n for definition in definitions:\n def_key = definition._children[0].get_data()\n if lower_keys:\n def_key = def_key.lower()\n def_val = definition._children[1].get_data()\n val[def_key] = def_val\n except AttributeError:\n val = {}\n ret[key] = val\n except AttributeError:\n return {}\n return ret\n\n def to_pairs(self, *, lower_keys=False):\n \"\"\"Convert contained tree to nested pairs of tuples and lists.\n\n If lower_keys is true, all keys are converted to lower-case\n \"\"\"\n ret = []\n try:\n sections = self.__tree._children\n for section in sections:\n # All children of this node are FencSections\n key = section.header()\n if lower_keys:\n key = key.lower()\n val = []\n try:\n definitions = section._children[1:]\n for definition in definitions:\n def_key = definition._children[0].get_data()\n if lower_keys:\n def_key = def_key.lower()\n def_val = definition._children[1].get_data()\n val.append((def_key, def_val))\n except AttributeError:\n val = []\n ret.append((key, val))\n except AttributeError:\n return []\n return ret\n","sub_path":"snugglery/fenc/fenc.py","file_name":"fenc.py","file_ext":"py","file_size_in_byte":2934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"445649460","text":"from flask_restful import Resource, reqparse\nfrom server.models.lobby import LobbyModel\nfrom server.models.user import UserModel\n\nclass LobbyJoin(Resource):\n parser = reqparse.RequestParser()\n parser.add_argument('lobby_id',\n type=str,\n required=True,\n help=\"Lobby ID must be supplied.\"\n )\n parser.add_argument('user_id',\n type=str,\n required=True,\n help=\"User ID must be supplied.\"\n )\n \n def put(self):\n data = LobbyJoin.parser.parse_args()\n\n lobby_id = data['lobby_id']\n user_id = data['user_id']\n\n lobby = LobbyModel.find_by_lobby_id(lobby_id)\n\n if lobby is None:\n return {\n \"message\": \"Lobby ID not found.\",\n \"error\": 1\n }, 404\n\n if len(lobby.users) > 1:\n return {\n \"message\": \"Lobby is already full.\",\n \"error\": 1\n }, 400\n if len(lobby.users) == 0:\n return {\n \"message\": \"Lobby does not have a host.\",\n \"error\": 2\n }, 400\n if any(user.user_id == user_id for user in lobby.users):\n return {\n \"message\": \"User has already joined the lobby.\",\n \"error\": 3\n }, 400\n\n user = UserModel.find_by_user_id(user_id)\n if user is None:\n return {\n \"message\": \"User ID not found.\",\n \"error\": 4\n }, 404\n\n user.save_lobby_id(lobby_id)\n try:\n user.save_to_db()\n except:\n return {\n \"message\": \"An error occurred saving the user to the database.\",\n \"error\": 5\n }, 500\n\n return lobby.json_me()","sub_path":"server/resources/lobby_join.py","file_name":"lobby_join.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"478440528","text":"# Copyright 2020 Google LLC\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\"\"\"Miscellaneous helper functions.\"\"\"\n\nimport itertools\nimport queue\nimport threading\nimport time\nfrom typing import Any, Callable, Dict, Iterable, Iterator, List, Sequence, TypeVar, Union\nimport uuid\nimport numpy as np\n\nT = TypeVar('T')\nK = TypeVar('K')\nV = TypeVar('V')\n\n\ndef coerce_bool(value) -> bool:\n if isinstance(value, (bool, int, float, list, dict)):\n return bool(value)\n elif value is None:\n return False\n elif str(value).lower() in ['', '0', 'false']:\n return False\n else:\n return True\n\n\ndef find_keys(d: Dict[K, V], predicate: Callable[[V], bool]) -> List[K]:\n \"\"\"Find keys where values match predicate.\"\"\"\n return [k for k, v in d.items() if predicate(v)]\n\n\ndef find_spec_keys(d: Dict[K, Any], types) -> List[K]:\n \"\"\"Find keys where values match one or more types.\"\"\"\n return find_keys(d, lambda v: isinstance(v, types))\n\n\ndef filter_by_keys(d: Dict[K, V], predicate: Callable[[K], bool]) -> Dict[K, V]:\n \"\"\"Filter to keys matching predicate.\"\"\"\n return {k: v for k, v in d.items() if predicate(k)}\n\n\ndef spec_contains(d: dict[str, Any], types) -> bool:\n \"\"\"Returns true if the spec contains any field with one of these types.\"\"\"\n return bool(find_spec_keys(d, types))\n\n\ndef remap_dict(d: Dict[K, V], keymap: Dict[K, K]) -> Dict[K, V]:\n \"\"\"Return a (shallow) copy of d with some fields renamed.\n\n Keys which are not in keymap are left alone.\n\n Args:\n d: dict to rename\n keymap: map of old key -> new key\n\n Returns:\n new dict with fields renamed\n \"\"\"\n return {keymap.get(k, k): d[k] for k in d}\n\n\ndef rate_limit(iterable, qps: Union[int, float]):\n \"\"\"Rate limit an iterator.\"\"\"\n for item in iterable:\n yield item\n time.sleep(1.0 / qps)\n\n\ndef batch_iterator(items: Iterable[T],\n max_batch_size: int) -> Iterator[List[T]]:\n \"\"\"Create batches from an input stream.\n\n Use this to create batches, e.g. to feed to a model.\n The output can be easily flattened again using itertools.chain.from_iterable.\n\n Args:\n items: stream of items\n max_batch_size: maximum size of resulting batches\n\n Yields:\n batches of size <= max_batch_size\n \"\"\"\n minibatch = []\n for item in items:\n if len(minibatch) < max_batch_size:\n minibatch.append(item)\n if len(minibatch) >= max_batch_size:\n yield minibatch\n minibatch = []\n if len(minibatch) > 0: # pylint: disable=g-explicit-length-test\n yield minibatch\n\n\ndef batch_inputs(input_records: Sequence[Dict[K, V]]) -> Dict[K, List[V]]:\n \"\"\"Batch inputs from list-of-dicts to dict-of-lists.\"\"\"\n assert input_records, 'Must have non-empty batch!'\n ret = {}\n for k in input_records[0]:\n ret[k] = [r[k] for r in input_records]\n return ret\n\n\ndef _extract_batch_length(preds):\n \"\"\"Extracts batch length of predictions.\"\"\"\n batch_length = None\n for key, value in preds.items():\n this_length = (\n len(value) if isinstance(value, (list, tuple)) else value.shape[0])\n batch_length = batch_length or this_length\n if this_length != batch_length:\n raise ValueError('Batch length of predictions should be same. %s has '\n 'different batch length than others.' % key)\n return batch_length\n\n\ndef unbatch_preds(preds):\n \"\"\"Unbatch predictions, as in estimator.predict().\n\n Args:\n preds: Dict[str, np.ndarray], where all arrays have the same first\n dimension.\n\n Yields:\n sequence of Dict[str, np.ndarray], with the same keys as preds.\n \"\"\"\n if not isinstance(preds, dict):\n for pred in preds:\n yield pred\n else:\n for i in range(_extract_batch_length(preds)):\n yield {key: value[i] for key, value in preds.items()}\n\n\ndef find_all_combinations(l: List[Any], min_element_count: int,\n max_element_count: int) -> List[List[Any]]:\n \"\"\"Finds all possible ways how elements of a list can be combined.\n\n E.g., all combinations of list [1, 2, 3] are\n [[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]].\n\n Args:\n l: a list of arbitrary elements.\n min_element_count: the minimum number of elements that every combination\n should contain.\n max_element_count: the maximum number of elements that every combination\n should contain.\n\n Returns:\n The list of all possible combinations given the constraints.\n \"\"\"\n result: List[List[Any]] = []\n min_element_count = max(1, min_element_count)\n max_element_count = min(max_element_count, len(l))\n for element_count in range(min_element_count, max_element_count + 1):\n result.extend(list(x) for x in itertools.combinations(l, element_count))\n return result\n\n\ndef coerce_real(vals: np.ndarray, limit=0.0001):\n \"\"\"Return a copy of the array with only the real numbers, with a check.\n\n If any of the imaginary part of a value is greater than the provided limit,\n then assert an error.\n\n Args:\n vals: The array to convert\n limit: The limit above which any imaginary part of a value causes an error.\n\n Returns:\n The array with only the real portions of the numbers.\n \"\"\"\n assert np.all(np.imag(vals) < limit), (\n 'Array contains imaginary part out of acceptable limits.')\n return np.real(vals)\n\n\ndef get_uuid():\n \"\"\"Return a randomly-generated UUID hex string.\"\"\"\n return uuid.uuid4().hex\n\n\nclass TaskQueue(queue.Queue):\n \"\"\"A simple task queue for processing jobs in a thread pool.\"\"\"\n\n def __init__(self, num_workers=1):\n # TODO(lit-dev): Could use QueueHandler and QueueListener for this.\n queue.Queue.__init__(self)\n self.num_workers = num_workers\n self.start_workers()\n\n def add_task(self, task, *args, **kwargs):\n args = args or ()\n kwargs = kwargs or {}\n self.put((task, args, kwargs))\n\n def start_workers(self):\n for _ in range(self.num_workers):\n t = threading.Thread(target=self.worker)\n t.daemon = True\n t.start()\n\n def worker(self):\n while True:\n item, args, kwargs = self.get()\n item(*args, **kwargs)\n self.task_done()\n","sub_path":"lit_nlp/lib/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"372637233","text":"from portfolio.settings.base import *\nALLOWED_HOSTS = []\nDEBUG = True\n\nSTATICFILES_DIRS = [\n\n #\"F:/Projects/web apps/junk/secondProject/portfolio - project/static\"\n os.path.join(BASE_DIR, 'portfolio/static')\n\n]\nSTATIC_ROOT = os.path.join(BASE_DIR, 'static')\nSTATIC_URL = '/static/'\n\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')\n#MEDIA_ROOT = \"F:/Projects/web apps/junk/secondProject/portfolio - project/media\"\nMEDIA_URL = '/media/'\n\n","sub_path":"portfolio/settings/development.py","file_name":"development.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"265956293","text":"# Convert multiple csv files into one big file\nimport json\nimport csv\nimport os\nimport re\nfrom datetime import datetime\nimport pandas as pd\n\nfiles = [f for f in os.listdir('.') if os.path.isfile(f) and '.csv' in f]\nexplored_countries = []\n\ncountries = dict()\n\n\nfor index, value in enumerate(files):\n country_name = value.split('_')[0] # country name is the first part\n\n if country_name in countries:\n countries[country_name].append(index)\n else:\n countries[country_name] = [index]\n\n\nfor country in countries:\n df = pd.DataFrame()\n for c in countries[country]:\n temp_df = pd.read_csv(files[c])\n df = pd.concat([df, temp_df])\n res_file_name = country + '.csv'\n df.to_csv(res_file_name, index=False)\nprint(\"done\")\n","sub_path":"asia/2- collect_multiples_to_one.py","file_name":"2- collect_multiples_to_one.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"242772851","text":"import AO3\nimport time\nfrom classes import Fic\nfrom reader import Reader\nimport pickle\n\ndef get_works_from_bookmarks(username, mine=False, works_not_bookmarks=False):\n '''\n Returns list of Works, one per bookmark\n '''\n if mine:\n pw = str(input(\"Please input password: \"))\n session = AO3.Session(\"starrybouquet\", pw)\n bookmarks = session.get_bookmarks()\n elif works_not_bookmarks:\n author = AO3.User(username)\n bookmarks = author.get_works()\n else:\n reader = Reader(username)\n bookmarks = reader.get_bookmarks()\n\n bookmarked_works = []\n broken_ids = []\n for work in bookmarks:\n if len(bookmarked_works) % 20 == 0 and len(bookmarked_works) != 0:\n print('Pausing for 2 min; we have been through {} bookmarks'.format(len(bookmarked_works)))\n time.sleep(120)\n try:\n work.reload()\n try:\n if work.fandoms[0] == \"Stargate SG-1\":\n bookmarked_works.append(Fic(work.url, username, existingAO3Work=work))\n print('Added work {}'.format(work.title))\n except:\n broken_ids.append(\"{0} (id {1})\".format(work.title, work.workid))\n print(\"Work had no fandom, id was {}\".format(work.workid))\n except:\n broken_ids.append(work.workid)\n print(\"Work was restricted, skipping. Work id was {}\".format(work.workid))\n return bookmarked_works, broken_ids\n\ndef write_bookmarks_to_file(username, works_not_bookmarks=False):\n bookmarks, please_check_these_works = get_works_from_bookmarks(username, works_not_bookmarks=works_not_bookmarks)\n for work in bookmarks:\n print(work.get_title())\n pickle.dump(bookmarks, open('bookmark_data_{}.p'.format(username), 'wb'))\n errorlog = open('works_with_errors.txt', 'w')\n errorlog.write(str(please_check_these_works))\n errorlog.close()\n\nusr = str(input('AO3 username: '))\nworks = str(input('Enter works if you would like works from author instead of bookmarks: '))\nif works == 'works':\n write_bookmarks_to_file(usr, works_not_bookmarks=True)\nelse:\n write_bookmarks_to_file(usr)\n","sub_path":"data/bookmarks_from_ao3.py","file_name":"bookmarks_from_ao3.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"258992768","text":"# coding utf-8\nimport csv, copy, itertools\n\n# 科目名の配列\nsubjects = ['language', 'mathmatics', 'english', 'society', 'science']\n\n# 科目別のスコア結果を格納する辞書\nrecords = dict(\n language = [],\n mathmatics = [],\n english = [],\n society = [],\n science = [],\n total = []\n)\n\n# 科目別のランキング結果を格納する辞書\nranking_list = copy.deepcopy(records)\n\n# 生徒名を格納する配列\nname_list = []\n\n# CSVの読み込み\nf = open('class_3c_input.csv', 'r')\ndataReader = csv.reader(f)\n\n# ヘッダを取り出してカーソル移動\nheader = next(dataReader)\n\n# 各生徒の合計変数\ntotal_score = 0\n\n'''\n入力CSV1行ごとに(\"並び順\", \"生徒名\", \"スコア\")のタプルを作成し、科目別(合計含む)にスコア辞書に格納\n\nCSV出力用に生徒名リストも作成\n'''\nfor sort_num, row in enumerate(dataReader):\n\n # 生徒名リストに生徒名を格納\n name_list.append(row[0])\n\n # 各生徒の合計を格納\n total_score = sum(map(int, row[1:]))\n\n for i, subject in enumerate(subjects):\n\n # (\"並び順\", \"生徒名\", \"スコア\")のタプルを科目別リストに格納\n records[subject].append((sort_num + 1, row[0], row[i + 1]))\n\n # 合計リストにタプルを格納\n records['total'].append((sort_num + 1, row[0], total_score))\n\nf.close()\n\n'''\nスコア辞書から科目別に結果を取り出し、スコア順にソートしてランキングを計算しランキング辞書に格納\n'''\nfor subject in records:\n \n # ランキングカウント\n ranking = 1\n \n # 前の生徒のスコア\n pre_score = 0\n \n # 同スコアカウント\n same_count = 0\n\n # スコア配列をスコアでソートしてランキングを計算\n for sort_num, name, score in sorted(records[subject], key = lambda x: int(x[2]), reverse = True):\n \n # 前の生徒の点数と今の生徒の点数が同じ場合\n if pre_score == score:\n \n # ランキングカウントをマイナス\n ranking -= 1\n \n # 同スコアカウントをプラス\n same_count += 1\n\n # 前の生徒の点数と今の生徒の点数が違う場合\n else:\n\n # ランキングスコアに同スコアカウントをプラス\n ranking += same_count\n\n # 同スコアカウントを初期化\n same_count = 0\n\n # (並び順, ランキング, 生徒名, スコア)のタプルをランキング配列に格納\n ranking_list[subject].append((sort_num, ranking, name, score))\n \n # 前の生徒のスコアに今の生徒の点数をセット\n pre_score = score\n\n # ランキングスコアをインクリ\n ranking += 1\n\n'''\n各科目のスコア配列を並び順にソートし直して、itertoolsを使ってランキング辞書の縦横を入れ替える\n\n国語のリスト\n(並び順, ランキング, 生徒A, スコア)\n(並び順, ランキング, 生徒B, スコア)\n...\n数学のリスト\n(並び順, ランキング, 生徒A, スコア)\n(並び順, ランキング, 生徒B, スコア)\n...\nから\n\n(国語(並び順, ランキング, 生徒A, スコア), 数学(並び順, ランキング, 生徒A, スコア), 英語(...), 社会(...), 理科(...), 合計(...))\n(国語(並び順, ランキング, 生徒B, スコア), 数学(並び順, ランキング, 生徒B, スコア), 英語(...), 社会(...), 理科(...), 合計(...))\n...\nへ変更\n\n'''\nranking_list = itertools.zip_longest(\n sorted(ranking_list['language'], key = lambda x: int(x[0])),\n sorted(ranking_list['mathmatics'], key = lambda x: int(x[0])),\n sorted(ranking_list['english'], key = lambda x: int(x[0])),\n sorted(ranking_list['society'], key = lambda x: int(x[0])),\n sorted(ranking_list['science'], key = lambda x: int(x[0])),\n sorted(ranking_list['total'], key = lambda x: int(x[0])),\n fillvalue=\"\")\n\n# 出力用CSVを準備\nnf = open('class_3c_output_2.csv', 'w', newline='')\ndataWriter = csv.writer(nf)\n\n# ヘッダーを書き込み\nheader.append('合計')\ndataWriter.writerow(header)\n\n'''\n[生徒名, 国語, 数学, 英語, 社会, 理科, 合計]の順でCSVに書き込み\n'''\nfor i, record in enumerate(ranking_list):\n # 1行分の配列\n row = []\n\n # 配列に生徒名を格納\n row.append(name_list[i])\n\n # 国語, 数学, 英語, 社会, 理科, 合計の順で配列に格納\n for r in record:\n row.append(r[1])\n\n # 1行分の配列をCSVに書き込み\n dataWriter.writerow(row)\n\nnf.close()","sub_path":"codeiq/seiseki/record_ranking_2.py","file_name":"record_ranking_2.py","file_ext":"py","file_size_in_byte":4651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"266764499","text":"# coding: utf8\n\nfrom requests import Request, Session\nimport json\n\n\nurl = 'https://www.clickavia.ru/api/trips/'\n\ndata = {\n # \"return\": {\n # \"adults\": 1,\n # \"infants\": 0,\n # \"children\": 0,\n # \"flight_class\": 1,\n # \"depart_date\": \"20-05-2015\",\n # \"return_date\": \"01-06-2015\",\n # \"location_to_iata\": \"MOW\",\n # \"location_to_type\": \"city\",\n # \"location_from_iata\": \"BOJ\",\n # \"location_from_type\": \"city\",\n # \"get_nearby\": 0\n # },\n \"one_way\": {\n \"adults\": 1,\n \"infants\": 0,\n \"children\": 0,\n \"flight_class\": 1,\n \"depart_date\": \"20-05-2015\",\n \"location_to_iata\": \"BOJ\",\n \"location_to_type\": \"city\",\n \"location_from_iata\": \"MOW\",\n \"location_from_type\": \"city\",\n \"get_nearby\": 0\n }\n}\n\n# proxies = {\n# 'http': 'http://localhost:8888',\n# 'https': 'https://localhost:8888'\n# }\n\n\nparams = []\nfor direction, payload in data.items():\n params.append((direction, json.dumps(payload)))\n\nfor param in params:\n headers = {\n 'content-type': 'application/json',\n 'Accept': 'text/plain',\n 'Content-Length': len(param),\n }\n req = Request('GET',\n url,\n data=param[1],\n headers=headers\n )\n\n print(req.url)\n\n prepped = req.prepare()\n\n s = Session()\n resp = s.send(prepped, verify=False)\n out = 'status code : {} direction : {}'.format(resp.status_code, param[0])\n print(out)\n with open(str(param[0]) + '.json', 'w') as f:\n f.write(resp.content)\n # print(resp.json())\n\nclka = [\n {\n \"adults\": 1,\n \"children\": 0,\n \"infants\": 0,\n \"type_search\": \"return_trip\",\n \"id\": 651965651966,\n \"seats_status\": true,\n \"link\": \"http://www.clickavia.ru/orders/to/651965/back/651966/referer/direct/adults/1/children/0/infants/0\",\n \"price\": 19688,\n \"price_ye\": 263,\n \"infant_price\": 7500,\n \"infant_price_ye\": 100,\n \"matching\": \"exact\",\n \"is_special\": false,\n \"min_valid_passport_date\": \"2015-02-11\",\n \"flight_to\": {\n \"id\": 651965,\n \"depart_date\": \"2015-01-14\",\n \"arrive_date\": \"2015-01-14\",\n \"code\": \"S7 923\",\n \"travel_time\": \"02:00\",\n \"flight_class\": \"econom\",\n \"child_flights\": [],\n \"depart_airport\": \"DME\",\n \"depart_airport_iata\": \"DME\",\n \"depart_airport_title\": \"Domodedovo\",\n \"depart_city_title\": \"Москва\",\n \"arrive_airport\": \"BOJ\",\n \"arrive_airport_iata\": \"BOJ\",\n \"arrive_airport_title\": \"Sarafovo\",\n \"arrive_city_title\": \"Бургас\",\n \"airline_title\": \"S7 Airlines\",\n \"airline_int_title\": \"S7 Airlines\",\n \"airline_logo\": \"/images/airlines/s7.png\",\n \"airline_link\": \"www.s7.ru\",\n \"depart_time\": \"13:40\",\n \"arrive_time\": \"14:40\",\n \"seats\": \"есть\",\n \"segments\": [\n {\n \"id\": 651965,\n \"code\": \"S7 923\",\n \"airline_title\": \"S7 Airlines\",\n \"airline_int_title\": \"S7 Airlines\",\n \"depart_date\": \"2015-01-14\",\n \"depart_time\": \"13:40\",\n \"depart_airport_iata\": \"DME\",\n \"depart_airport_title\": \"Domodedovo\",\n \"arrive_date\": \"2015-01-14\",\n \"arrive_time\": \"14:40\",\n \"arrive_airport_iata\": \"BOJ\",\n \"arrive_airport_title\": \"Sarafovo\",\n \"travel_time\": \"02:00\"\n }\n ]\n },\n \"flight_return\": {\n \"id\": 651966,\n \"depart_date\": \"2015-02-11\",\n \"arrive_date\": \"2015-02-11\",\n \"code\": \"S7 924\",\n \"travel_time\": \"03:50\",\n \"flight_class\": \"econom\",\n \"child_flights\": [],\n \"depart_airport\": \"BOJ\",\n \"depart_airport_iata\": \"BOJ\",\n \"depart_airport_title\": \"Sarafovo\",\n \"depart_city_title\": \"Бургас\",\n \"arrive_airport\": \"DME\",\n \"arrive_airport_iata\": \"DME\",\n \"arrive_airport_title\": \"Domodedovo\",\n \"arrive_city_title\": \"Москва\",\n \"airline_title\": \"S7 Airlines\",\n \"airline_int_title\": \"S7 Airlines\",\n \"airline_logo\": \"/images/airlines/s7.png\",\n \"airline_link\": \"www.s7.ru\",\n \"depart_time\": \"16:20\",\n \"arrive_time\": \"21:10\",\n \"seats\": \"есть\",\n \"segments\": [\n {\n \"id\": 651966,\n \"code\": \"S7 924\",\n \"airline_title\": \"S7 Airlines\",\n \"airline_int_title\": \"S7 Airlines\",\n \"depart_date\": \"2015-02-11\",\n \"depart_time\": \"16:20\",\n \"depart_airport_iata\": \"BOJ\",\n \"depart_airport_title\": \"Sarafovo\",\n \"depart_city_title\": \"Бургас\",\n \"arrive_date\": \"2015-02-11\",\n \"arrive_time\": \"21:10\",\n \"arrive_airport_iata\": \"DME\",\n \"arrive_airport_title\": \"Domodedovo\",\n \"arrive_city_title\": \"Москва\",\n \"travel_time\": \"03:50\"\n }\n ]\n }\n }\n]","sub_path":"clka.py","file_name":"clka.py","file_ext":"py","file_size_in_byte":5525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"617230757","text":"from scipy.stats import kendalltau, norm, t\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pickle\nimport scipy.io as sio\n\ndef kendall(Y, true, df=None, subsample=None):\n # X is torch.tensor N by p\n X = Y.cpu().numpy()\n # scaling factor\n medX = np.median(X, axis=0)\n X = X - medX\n # median absolute deviation\n s = np.median(np.abs(X), axis=0)\n # scatter = k * MAD with k = 1/F^{-1}(3/4), where F is dist of real\n if true == 'Gaussian':\n k = 1/norm.ppf(3/4)\n elif true == 'Student':\n assert df is not None\n k = 1/t.ppf(3/4, df=df)\n s = k * s\n # sub-sampling\n if subsample is not None:\n assert subsample <= len(X)\n indices = np.random.choice(len(X), size=subsample, replace=False)\n X = X[indices]\n _, p = X.shape\n corr = np.zeros((p, p))\n for i in range(p):\n for j in range(i + 1):\n corr[i, j] = np.sin(np.pi / 2 * kendalltau(Y[:, i], Y[:, j])[0])\n corr[j, i] = corr[i, j]\n cov = s.reshape(p, 1) * corr * s.reshape(1, p)\n return cov\n\n# snpdict = sio.loadmat('/home/wzhuai/Robust/SNP500/dataset/snp452.mat')\n# copinfo = snpdict['stock'][0]\n# copname = [copinfo[i][0][0][1][0][1:-1] for i in range(len(copinfo))]\n# copctg = [copinfo[i][0][0][2][0][1:-1] for i in range(len(copinfo))]\n# prc = snpdict['X']\n# logdiff = np.log(prc[1:]/prc[0:-1])\n\n# # Top\n# select_top = ['Microsoft', 'Apple', 'Amazon', 'Facebook', 'Berkshire',\n# 'Alphabet', 'Johnson', 'JPMorgan', 'Exxon', 'Visa',\n# 'Bank of America', 'Procter', 'Intel', 'Cisco', 'Verizon',\n# 'AT&T', 'Home Depot', 'Chevron', 'Walt Disney', 'Pfizer',\n# 'Mastercard', 'UnitedHealth', 'Boeing', 'Merck', 'Wells Fargo',\n# 'Coca-Cola']\n\n# select_lv = ['Microsoft', 'Apple', 'Amazon', 'JPMorgan',\n# 'NIKE', 'Texas Ins', 'Costco',\n# 'Charles', 'Southern Company', 'Deere',\n# 'Equinix', 'Aflac', 'Valero',\n# 'Halliburt', 'Ingersoll', 'Corning',\n# 'Tyson', 'Realty', 'Edison',\n# 'Keysight', 'Hess', 'Maxim Integrated',\n# 'Hormel', 'Cboe Global', 'Alliant',\n# 'Western Union', 'Interpublic', 'Mohawk',\n# 'Discovery', 'Mattel', 'Macerich']\n# selectcop_top = {}\n# for name in select_top:\n# s = [name in copname[i] for i in range(len(copname))]\n# try:\n# idx = s.index(True)\n# except:\n# continue\n# selectcop_top[copname[idx]] = idx\n\n# selectcop_lv = {}\n# for name in select_lv:\n# s = [name in copname[i] for i in range(len(copname))]\n# try:\n# idx = s.index(True)\n# except:\n# continue\n# selectcop_lv[copname[idx]] = idx\n\n# snp500 = {'logdiff':logdiff, 'copname':copname, 'copctg':copctg,\n# 'topcop':selectcop_top, 'lvcop':selectcop_lv}\n# with open('/home/wzhuai/Robust/SNP500/dataset/snp500.pkl', 'wb') as outF:\n# pickle.dump(snp500, outF)\n","sub_path":"data/RobustGAN/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"44464947","text":"#!/usr/bin/env python2\n\"\"\"2017/Sep/03 @ Zdenek Styblik \nDesc: Fetch RSS and post it to slack channel.\n\"\"\"\nimport argparse\nimport logging\nimport os\nimport sys\nimport time\nimport traceback\n\nfrom slackclient import SlackClient\nimport rss2irc\n\n\ndef get_slack_token():\n \"\"\"Get slack token from ENV variable.\n\n :rtype: str\n :raises: `ValueError`\n \"\"\"\n slack_token = os.environ.get('SLACK_TOKEN', None)\n if slack_token:\n return slack_token\n\n raise ValueError('SLACK_TOKEN must be set.')\n\n\ndef main():\n \"\"\"Main.\"\"\"\n logging.basicConfig(stream=sys.stdout, level=logging.ERROR)\n logger = logging.getLogger('rss2slack')\n args = parse_args()\n if args.verbosity:\n logger.setLevel(logging.DEBUG)\n\n if args.cache_expiration < 0:\n logger.error(\"Cache expiration can't be less than 0.\")\n sys.exit(1)\n\n slack_token = get_slack_token()\n news = {}\n for rss_url in args.rss_urls:\n data = rss2irc.get_rss(logger, rss_url, args.rss_http_timeout)\n if not data:\n logger.error('Failed to get RSS from %s', rss_url)\n sys.exit(1)\n\n rss2irc.parse_news(data, news)\n\n if not news:\n logger.info('No news?')\n sys.exit(0)\n\n cache = rss2irc.read_cache(logger, args.cache)\n rss2irc.scrub_cache(logger, cache)\n\n for key in news.keys():\n if key in cache:\n logger.debug('Key %s found in cache', key)\n cache[key] = int(time.time()) + args.cache_expiration\n news.pop(key)\n\n slack_client = SlackClient(slack_token)\n if not args.cache_init:\n for url in news.keys():\n message = rss2irc.format_message(url, news[url], args.handle)\n try:\n post_to_slack(\n logger, message, slack_client, args.slack_channel,\n args.slack_timeout\n )\n except ValueError:\n news.pop(url)\n finally:\n time.sleep(args.sleep)\n\n expiration = int(time.time()) + args.cache_expiration\n for key in news.keys():\n cache[key] = expiration\n\n rss2irc.write_cache(cache, args.cache)\n\n\ndef parse_args():\n \"\"\"Return parsed CLI args.\n\n :rtype: `argparse.Namespace`\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--cache',\n dest='cache', type=str, default=None,\n help='Path to cache file.')\n parser.add_argument('--cache-expiration',\n dest='cache_expiration', type=int,\n default=rss2irc.EXPIRATION,\n help='Time, in seconds, for how long to keep items '\n 'in cache.')\n parser.add_argument('--cache-init',\n dest='cache_init', action='store_true', default=False,\n help='Prevents posting news to IRC. This is useful '\n 'when bootstrapping new RSS feed.')\n parser.add_argument('--handle',\n dest='handle', type=str, default=None,\n help='Handle/callsign of this feed.')\n parser.add_argument('--rss-url',\n dest='rss_urls', action='append', required=True,\n help='URL of RSS Feed.')\n parser.add_argument('--rss-http-timeout',\n dest='rss_http_timeout', type=int,\n default=rss2irc.HTTP_TIMEOUT,\n help=('HTTP Timeout. Defaults to %i seconds.'\n % rss2irc.HTTP_TIMEOUT))\n parser.add_argument('--slack-channel',\n dest='slack_channel', type=str, required=True,\n help='Name of slack channel to send formatted news '\n 'to.')\n parser.add_argument('--slack-timeout',\n dest='slack_timeout', type=int,\n default=rss2irc.HTTP_TIMEOUT,\n help=('slack API Timeout. Defaults to %i seconds.'\n % rss2irc.HTTP_TIMEOUT))\n parser.add_argument('--sleep',\n dest='sleep', type=int, default=2,\n help='Sleep between messages in order to avoid '\n 'possible excess flood/API call rate limit.')\n parser.add_argument('-v', '--verbose',\n dest='verbosity', action='store_true', default=False,\n help='Increase logging verbosity.')\n return parser.parse_args()\n\n\ndef post_to_slack(\n logger, message, slack_client, slack_channel, slack_timeout\n):\n \"\"\"Post news to slack channel.\n\n :type logger: `logging.Logger`\n :type message: str\n :type slack_client: `slackclient.SlackClient`\n :type slack_channel: str\n :type slack_timeout: int\n \"\"\"\n try:\n logger.debug('Will post %s', repr(message))\n slack_client.api_call(\n 'chat.postMessage', channel=slack_channel,\n text=message.encode('utf-8'), timeout=slack_timeout\n )\n except ValueError:\n logger.debug(traceback.format_exc())\n raise\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"rss2slack.py","file_name":"rss2slack.py","file_ext":"py","file_size_in_byte":5209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"143012444","text":"from __future__ import print_function\nimport sys\nimport os\nimport pickle\nimport time\nimport argparse\nimport torch\nimport torch.nn as nn\nimport torch.backends.cudnn as cudnn\nimport torchvision.transforms as transforms\nimport numpy as np\nfrom torch.autograd import Variable\nfrom data import VOCroot\nfrom data import AnnotationTransform,VOCDetection, BaseTransform, VOC_Config\nfrom models.RFB_Net_vgg import build_net\nimport torch.utils.data as data\nfrom layers.functions import Detect,PriorBox\nfrom utils.nms_wrapper import nms\nfrom utils.timer import Timer\nimport cv2\nfrom torchscope import scope\nfrom compute_speed import compute_speed\n\nfrom sort import *\nimport copy\n\n# weights/epoches_022.pth\n# Finished loading model!\n# 100%|██████████| 3746/3746 [01:35<00:00, 44.04it/s]\n# Evaluating detections\n# Writing person VOC results file\n# VOC07 metric? Yes\n# AP for person = 0.6455\n# Mean AP = 0.6455\n# ~~~~~~~~\n# Results:\n# 0.646\n# 0.646\n# ~~~~~~~~\nparser = argparse.ArgumentParser(description='Receptive Field Block Net')\nparser.add_argument('--video_dir', default='video', type=str,\n help='Dir to save results')\nparser.add_argument('-m', '--trained_model', default='weights/646.pth',\n type=str, help='Trained state_dict file path to open')\nparser.add_argument('--cuda', default=True, type=bool,\n help='Use cuda to train model')\nparser.add_argument('--cpu', default=False, type=bool,\n help='Use cpu nms')\nargs = parser.parse_args()\n\n\ncfg = VOC_Config\nimg_dim = 300\nnum_classes = 2\nrgb_means = (104, 117, 123)\n\npriorbox = PriorBox(cfg)\nwith torch.no_grad():\n priors = priorbox.forward()\n if args.cuda:\n priors = priors.cuda()\n\n\nclass ObjectDetector:\n def __init__(self, net, detection, transform, num_classes=2, thresh=0.1, cuda=True):\n self.net = net\n self.detection = detection\n self.transform = transform\n self.num_classes = num_classes\n self.thresh = thresh\n self.cuda = cuda\n\n def predict(self, img):\n _t = {'im_detect': Timer(), 'misc': Timer()}\n scale = torch.Tensor([img.shape[1], img.shape[0],\n img.shape[1], img.shape[0]])\n\n with torch.no_grad():\n x = self.transform(img).unsqueeze(0)\n if self.cuda:\n x = x.cuda()\n scale = scale.cuda()\n\n _t['im_detect'].tic()\n out = net(x) # forward pass\n boxes, scores = self.detection.forward(out, priors)\n detect_time = _t['im_detect'].toc()\n boxes = boxes[0]\n scores = scores[0]\n\n # scale each detection back up to the image\n boxes *= scale\n boxes = boxes.cpu().numpy()\n scores = scores.cpu().numpy()\n _t['misc'].tic()\n all_boxes = [[] for _ in range(num_classes)]\n\n for j in range(1, num_classes):\n inds = np.where(scores[:, j] > self.thresh)[0]\n if len(inds) == 0:\n all_boxes[j] = np.zeros([0, 5], dtype=np.float32)\n continue\n c_bboxes = boxes[inds]\n c_scores = scores[inds, j]\n #print(scores[:, j])\n c_dets = np.hstack((c_bboxes, c_scores[:, np.newaxis])).astype(\n np.float32, copy=False)\n # keep = nms(c_bboxes,c_scores)\n\n keep = nms(c_dets, 0.4, force_cpu=args.cpu)\n c_dets = c_dets[keep, :]\n all_boxes[j] = c_dets\n\n nms_time = _t['misc'].toc()\n total_time = detect_time+nms_time\n\n #print('total time: ', total_time)\n return all_boxes, total_time\n\nif __name__ == '__main__':\n # load net\n net = build_net('test', img_dim, num_classes) # initialize detector\n state_dict = torch.load(args.trained_model)\n # create new OrderedDict that does not contain `module.`\n\n from collections import OrderedDict\n new_state_dict = OrderedDict()\n for k, v in state_dict.items():\n head = k[:7]\n if head == 'module.':\n name = k[7:] # remove `module.`\n else:\n name = k\n new_state_dict[name] = v\n net.load_state_dict(new_state_dict)\n net.eval()\n print('Finished loading model!')\n\n # scope(net, input_size=(3,300,300))\n if args.cuda:\n net = net.cuda()\n cudnn.benchmark = True\n else:\n net = net.cpu()\n #scope(net, input_size=(3,300,300))\n device=torch.device('cuda:0' if torch.cuda.is_available() else \"cpu\")\n print(device)\n # compute_speed(net, (1,3,300,300), device, 1000)\n detector = Detect(num_classes,0,cfg)\n\n transform = BaseTransform(img_dim, rgb_means, (2, 0, 1))\n object_detector = ObjectDetector(net, detector, transform)\n\n # vdo=cv2.VideoCapture()\n assert os.path.isfile(args.video_dir), \"Error: path error\"\n videopath = \"/home/lyf/git-repo/RFSong-multidata/\"+args.video_dir\n print(videopath)\n vdo=cv2.VideoCapture(videopath)\n im_width = int(vdo.get(cv2.CAP_PROP_FRAME_WIDTH))\n im_height = int(vdo.get(cv2.CAP_PROP_FRAME_HEIGHT))\n rate = float(vdo.get(cv2.CAP_PROP_FPS))\n print(\"rate: \", rate)\n assert vdo.isOpened()\n fourcc = cv2.VideoWriter_fourcc(*'MJPG')\n out = cv2.VideoWriter('output.avi', fourcc, rate, (im_width, im_height))\n\n mot_tracker = Sort() \n startt=time.time()\n fps=0.0\n cnt=0\n while True:\n ret, frame = vdo.read() \n if ret != True:\n break\n\n # img_list = os.listdir(args.img_dir)\n # for i, img in enumerate(img_list):\n st=time.time()\n # img_name = img\n # img = os.path.join(args.img_dir, img)\n image=frame\n # print(frame.size)\n # image = cv2.imread(frame)\n detect_bboxes, tim = object_detector.predict(image)\n detect_thred=0.32\n detect_bboxes_copy = copy.deepcopy(detect_bboxes)\n class_id,bboxes = detect_bboxes_copy\n bboxes = bboxes[bboxes[:,len(bboxes[0])-1]>=detect_thred, :]\n \n # t0=time.time()\n # print(t0-st)\n trackers = mot_tracker.update(bboxes)\n # t3=time.time()\n # print(t3-t0)\n for d in trackers:\n d = d.astype(np.int32)\n cv2.rectangle(image, (int(d[0]), int(d[1])), (int(d[2]), int(d[3])), (0, 255, 0), 2)\n cv2.putText(image, str(d[4]), (int(d[0]), int(d[1])), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 0, 0), 2)\n # print('%d,%.2f,%.2f,%.2f,%.2f'%(d[4],d[0],d[1],d[2]-d[0],d[3]-d[1]))\n # ax1.add_patch(patches.Rectangle((d[0],d[1]),d[2]-d[0],d[3]-d[1],fill=False,lw=3,ec=colours[d[4]%32,:]))\n\n # for class_id,class_collection in enumerate(detect_bboxes):\n # if len(class_collection)>0:\n # for i in range(class_collection.shape[0]):\n # if class_collection[i,-1]>0.32:\n # pt = class_collection[i]\n # cv2.rectangle(image, (int(pt[0]), int(pt[1])), (int(pt[2]), int(pt[3])), (0, 255, 0), 2)\n # cv2.putText(image, str(class_collection[i,-1]), (int(pt[0]), int(pt[1])), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 0, 0), 2)\n # t4=time.time()\n # print(t4-t3)\n # sec=(time.time()-st)*1000\n # print(sec)\n # cv2.imwrite('output/' + img_name, image)\n #cv2.imshow('result',image)\n #cv2.waitKey()\n # fps = ( fps + (1./(time.time()-st)) ) / 2\n # print(\"fps= %f\"%(fps))\n # out.write(image)\n cnt+=1\n\n print(time.time()-startt, cnt)\n print(\"fps: \", cnt/(time.time()-startt) )\n print(\"t_per_frame: \", (time.time()-startt)/cnt )\n\n vdo.release()\n out.release()\n","sub_path":"pedestrian-detection-track/videosort.py","file_name":"videosort.py","file_ext":"py","file_size_in_byte":7636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"334074106","text":"from emulator.adressing import AbsoluteY\nfrom emulator.cpu import CPU\nfrom emulator.memory import Memory, MemoryPositions\n\n\ndef test_read_AbsoluteY():\n address_mode = AbsoluteY\n cpu = CPU()\n memory = Memory(rom=[0x32, 0x02, 0x7F, 0x01, 0x00, 0x20], ram=list(map(lambda x: x % 256, range(Memory.ram_size()))))\n\n cpu.inc_cycle_by(-cpu.cycle)\n cpu.inc_pc_by(-cpu.pc + MemoryPositions.PRG_ROM_START.start)\n cpu.y = 0x0A\n address = address_mode.fetch_address(cpu, memory)\n value = address_mode.read_from(cpu, memory, address)\n assert address == 0x023C\n assert value == (0x023C % 256)\n\n cpu.inc_cycle_by(-cpu.cycle)\n cpu.y = 0xA1\n address = address_mode.fetch_address(cpu, memory)\n value = address_mode.read_from(cpu, memory, address)\n\n assert address == 0x0220\n assert value == (0x0220 % 256)\n\n cpu.inc_cycle_by(-cpu.cycle)\n cpu.y = 0x07\n address = address_mode.fetch_address(cpu, memory)\n\n assert address == 0x2007\n # PPU do not assert value for now\n\n\ndef test_write_AbsoluteY():\n address_mode = AbsoluteY\n cpu = CPU()\n memory = Memory(rom=[0x30, 0x01, 0xFF, 0x02, 0x0A, 0x05], ram=list(map(lambda x: x % 256, range(Memory.ram_size()))))\n\n cpu.inc_cycle_by(-cpu.cycle)\n cpu.inc_pc_by(-cpu.pc + MemoryPositions.PRG_ROM_START.start)\n cpu.y = 0x25\n address = address_mode.fetch_address(cpu, memory)\n address_mode.write_to(cpu, memory, address, 20)\n assert address == 0x0155\n assert memory.ram[address] == 20\n\n cpu.inc_cycle_by(-cpu.cycle)\n cpu.y = 0x30\n address = address_mode.fetch_address(cpu, memory)\n address_mode.write_to(cpu, memory, address, 100)\n assert address == 0x032F\n assert memory.ram[address] == 100\n\n cpu.inc_cycle_by(-cpu.cycle)\n cpu.y = 0x20\n address = address_mode.fetch_address(cpu, memory)\n address_mode.write_to(cpu, memory, address, 67)\n assert address == 0x052A\n assert memory.ram[address] == 67","sub_path":"emulator/src/emulator/test/test_addressing_modes/test_absolute_y.py","file_name":"test_absolute_y.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"55938931","text":"# Copyright (c) 2019, NVIDIA CORPORATION.\n\nfrom cudf import DataFrame, Series\n\nfrom cuspatial._lib.shapefile_reader import (\n read_polygon_shapefile as cpp_read_polygon_shapefile,\n)\n\n\ndef read_polygon_shapefile(filename):\n \"\"\"\n Reads polygon geometry from an ESRI shapefile into GPU memory.\n\n Parameters\n ----------\n filename : str, pathlike\n ESRI Shapefile file path (usually ends in ``.shp``)\n\n Returns\n -------\n result : tuple (cudf.Series, cudf.Series, cudf.DataFrame)\n poly_offsets : cudf.Series(dtype=np.int32)\n Offsets of the first ring in each polygon\n ring_offsets : cudf.Series(dtype=np.int32)\n Offsets of the first point in each ring\n points : cudf.DataFrame\n DataFrame of all points in the shapefile\n x : cudf.Series(dtype=np.float64)\n x-components of each polygon's points\n y : cudf.Series(dtype=np.float64)\n y-components of each polygon's points\n \"\"\"\n result = cpp_read_polygon_shapefile(filename)\n f_pos = Series(result[0], name=\"f_pos\")\n r_pos = Series(result[1], name=\"r_pos\")\n return (f_pos, r_pos, DataFrame({\"x\": result[2], \"y\": result[3]}))\n","sub_path":"python/cuspatial/cuspatial/io/shapefile.py","file_name":"shapefile.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"654141709","text":"import time\n\nstart_time = time.time()\n\nf = open('names_1.txt', 'r')\nnames_1 = f.read().split(\"\\n\") # List containing 10000 names\nf.close()\n\nf = open('names_2.txt', 'r')\nnames_2 = f.read().split(\"\\n\") # List containing 10000 names\nf.close()\n\n# Create dictionary to check names against\ncheck = {}\n# create list to store duplicates\nduplicates = []\n# Loop through first list and add to check\nfor name_1 in names_1:\n check[name_1] = True\n\n# Loop through second list and get name out of check dict\n# If in check add to duplicates\nfor name_2 in names_2:\n if check.get(name_2, None):\n duplicates.append(name_2)\n\n\nend_time = time.time()\nprint(f\"{len(duplicates)} duplicates:\\n\\n{', '.join(duplicates)}\\n\\n\")\nprint(f\"runtime: {end_time - start_time} seconds\")\n","sub_path":"names/names.py","file_name":"names.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"87815715","text":"# f1/s/core/sqlite.py\n\nimport uuid\nimport json\nimport records\nimport sqlite3\nimport os\n\n\nclass SQlite:\n def __init__(self):\n pass\n\n def write(self, path, data, table, credentials=None):\n path = path\n # table = data['table']\n table = table\n # payload = data['data']\n payload = data\n values = []\n\n assert os.path.exists(path) is True\n\n payload['_id'] = self.uuid()\n\n for key in payload:\n if type(payload[key]) == str:\n values.append('{!r}'.format(payload[key]))\n elif type(payload[key]) == int:\n values.append('{!s}'.format(payload[key]))\n\n columns = ', '.join(payload.keys())\n value_string = ', '.join(values)\n\n # TODO use '?' not string formatting\n query = 'INSERT INTO {}({}) VALUES ({})'.format(table, columns, value_string)\n\n try:\n connection = sqlite3.connect(path)\n cursor = connection.cursor()\n cursor.execute(query)\n\n if connection.total_changes == 1:\n result = True\n elif connection.total_changes == 0:\n result = False\n else:\n result = connection.total_changes\n\n connection.commit()\n\n # TODO check write success?\n # cursor.execute('SELECT * FROM {} WHERE _id = {!r}'.format(table, payload['_id']))\n # print('inserted:', cursor.fetchall())\n\n connection.close()\n return result\n\n except Exception as exc:\n return 'sqlite.Exception', exc\n\n def read(self, path, data, table, credentials=None):\n assert table is not None\n assert len(data['column_lookup']) > 0\n assert len(data['column_result']) > 0\n\n res = data['column_result']\n\n column_result = []\n column_lookup = []\n column_lookup_value = []\n query = 'no query'\n\n if type(res) == str:\n column_result = res\n elif type(res) == list:\n for v in res:\n column_result.append(v)\n else:\n raise TypeError('column_result is not string nor list')\n\n for key, value in data['column_lookup'].items():\n column_lookup.append(key)\n column_lookup_value.append(value)\n\n # TODO lookup entries > 1 (WHERE x AND y)\n if len(column_lookup) == 2:\n query = 'SELECT {} FROM {} WHERE {} = {!r} AND {} = {!r}'.format(\n column_result, table,\n column_lookup[0], column_lookup_value[0],\n column_lookup[1], column_lookup_value[1])\n elif len(column_lookup) == 1:\n query = 'SELECT {} FROM {} WHERE {} = {!r}'.format(column_result, table, column_lookup, column_lookup_value)\n\n # print(query)\n\n try:\n connection = sqlite3.connect(path)\n cursor = connection.cursor()\n cursor.execute(query)\n # print('sqlite.read.result', result)\n\n # TODO rows\n if cursor.rowcount == 0:\n return None\n else:\n rows = cursor.fetchall()\n\n connection.close()\n\n result = []\n for row in rows:\n result.append(row)\n return result\n\n except Exception as exc:\n return 'sqlite.Exception', exc\n\n def uuid(self):\n uid = str(uuid.uuid4())\n return uid\n\n def test(self, path, data):\n path = path\n table = data['table']\n payload = data['data']\n columns = {}\n values = []\n\n payload['_id'] = self.uuid()\n\n for key in payload:\n if type(payload[key]) == str:\n values.append('{!r}'.format(payload[key]))\n elif type(payload[key]) == int:\n values.append('{!s}'.format(payload[key]))\n\n columns = ', '.join(payload.keys())\n value_string = ', '.join(values)\n\n query = 'INSERT INTO {}({}) VALUES ({})'.format(table, columns, value_string)\n\n # print(self.__file__)\n # print(columns)\n # print(value_string)\n # print(query)\n\n # TODO check for sqlite file\n path_exists = '{} {}'.format(path, os.path.exists(path))\n print(path_exists)\n\n # '''python3.sqlite3'''\n try:\n connection = sqlite3.connect(path)\n cursor = connection.cursor()\n cursor.execute(query)\n result = connection.total_changes\n connection.commit()\n cursor.execute('SELECT * FROM {} WHERE _id = {!r}'.format(table, payload['_id']))\n print(cursor.fetchall())\n connection.close()\n return result\n\n except Exception as exc:\n return 'Exception', exc\n\n # '''kennethreitz.records'''\n # try:\n # self.db = records.Database('sqlite:///{}'.format(path))\n # print('get table names: ', self.db.get_table_names())\n # result = self.db.query(query)\n # select = self.db.query('SELECT * FROM {}'.format(table))\n # print(select)\n # # print('SELECT * :', self.db.query('SELECT * FROM {}'.format(table)))\n # self.db.close()\n # return result\n #\n # except Exception as exc:\n # return exc\n","sub_path":"f1/s/io/sqlite.py","file_name":"sqlite.py","file_ext":"py","file_size_in_byte":5394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"463564784","text":"# -*- coding: utf-8 -*-\r\n\r\nimport pytest\r\nimport yaml\r\nimport os\r\nfrom homework.pytest_firstclass.code.calculator import Calculator\r\n\r\n\r\n@pytest.fixture(scope=\"module\")\r\ndef get_calc():\r\n calc = Calculator()\r\n return calc\r\n\r\n# 获取conftest.py文件的绝对路径\r\nyaml_filepath = os.path.dirname(__file__) + '/testdata.yml'\r\n\r\nwith open(yaml_filepath, encoding=\"utf-8\") as f:\r\n datas = yaml.safe_load(f)\r\n print(datas)\r\n add_datas = datas['add_datas']\r\n sub_datas = datas['sub_datas']\r\n mul_datas = datas['mul_datas']\r\n div_datas = datas['div_datas']\r\n ids = datas['caseid']\r\n\r\n@pytest.fixture(scope=\"module\")\r\ndef start_end_perform():\r\n print(\"开始计算\")\r\n yield\r\n print(\"结束计算\")\r\n\r\n@pytest.fixture(params=add_datas, ids=ids)\r\ndef get_adddatas(request):\r\n data = request.param\r\n yield data\r\n\r\n@pytest.fixture(params=sub_datas, ids=ids)\r\ndef get_subdatas(request):\r\n data = request.param\r\n yield data\r\n\r\n@pytest.fixture(params=mul_datas, ids=ids)\r\ndef get_muldatas(request):\r\n data = request.param\r\n yield data\r\n\r\n@pytest.fixture(params=div_datas, ids=ids)\r\ndef get_divdatas(request):\r\n data = request.param\r\n yield data","sub_path":"homework/pytest_secondclass/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"311550477","text":"\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport time\nimport os\nimport sys\nimport requests\n\noptions = webdriver.ChromeOptions()\noptions.add_argument(\"--disable-infobars\")\n# options.add_argument(\"--headless\")\n# Uncoment to enable Headless version\noptions.add_argument(\"--start-maximized\")\noptions.add_argument(\n \"user-agent='User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36'\"\n)\ndef main():\n pincode = [str(sys.argv[1])]\n\n while True:\n browser = webdriver.Chrome(options=options)\n\n for pin in pincode:\n browser.get(\"https://www.cowin.gov.in/\")\n browser.implicitly_wait(10)\n browser.find_element_by_id('mat-input-0').send_keys(pin)\n browser.implicitly_wait(10)\n time.sleep(10)\n browser.find_element_by_xpath(\n \"//*[@id=\\\"mat-tab-content-0-0\\\"]/div/div[1]/div/div/button\").click()\n time.sleep(10)\n browser.find_element_by_xpath(\n \"//*[@id=\\\"Search-Vaccination-Center\\\"]/appointment-table/div/div/div/div/div/div/div/div/div/div/div[2]/form/div/div/div[2]/div[3]/ul/li[2]/div/div[2]/label\").click()\n time.sleep(10)\n\n browser.find_element_by_xpath(\n \"//*[@id=\\\"Search-Vaccination-Center\\\"]/appointment-table/div/div/div/div/div/div/div/div/div/div/div[2]/form/div/div/div[5]/div[3]/div/div/div[1]/p\")\n # No slots\n \n\n response = requests.get(\n \n )\n response.raise_for_status()\n centers = {}\n result = response.json()\n for i in result[\"centers\"]:\n centers[i[\"center_id\"]] = i\n count = 0\n\n flag = False\n for id, center in centers.items():\n flag1 = False\n sessions = center[\"sessions\"]\n for session in sessions:\n if session['min_age_limit'] < 45:\n if flag1 == False:\n print(\n f\"{center['state_name']}, {center['district_name']}, {center['name']}, from: {center['from']}, to: {center['to']}, fee_type: {center['fee_type']}\")\n flag1 = True\n flag = True\n if session['available_capacity'] > 0:\n count += 1\n print(f\"{session['date']}, capacity: {session['available_capacity']}, age limit: {session['min_age_limit']}, vaccine: {session['vaccine']}, slots: {session['slots']}\")\n print('````````````````````````````````````````')\n if flag == False:\n print(\"No vaccines available!\")\n else:\n print(f\"{count} sessions available.\")\n \n \n \n print(\"Vaccine Not Available. Checing Again in 5 mins.\")\n time.sleep(300)\n\n","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":2790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"168067519","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom pygame import *\nimport pyganim\nCOLOR = \"#888888\"\nMOVE_SPEED = 5\nWIDTH = 32\nHEIGHT = 32\nJUMP_POWER = 10\nGRAVITY = 0.3\nANIMATION_DELAY = 0.12\nwalk_right_1 = (transform.scale(image.load('assets/Characters/platformChar_walk1.png'), (32, 32)))\nwalk_right_2 = (transform.scale(image.load('assets/Characters/platformChar_walk2.png'), (32, 32)))\nwalk_left_1 = (transform.scale(image.load('assets/Characters/platformChar_walk_left1.png'), (32, 32)))\nwalk_left_2 = (transform.scale(image.load('assets/Characters/platformChar_walk_left2.png'), (32, 32)))\njump_left = (transform.scale(image.load('assets/Characters/platformChar_jump_left.png'), (32, 32)))\njump_right = (transform.scale(image.load('assets/Characters/platformChar_jump.png'), (32, 32)))\nstay = (transform.scale(image.load('assets/Characters/platformChar_idle.png'), (32, 32)))\n\nANIMATION_RIGHT = [walk_right_1, walk_right_2]\nANIMATION_LEFT = [walk_left_1, walk_left_2]\nANIMATION_JUMP = [(jump_right, 0.12)]\nANIMATION_JUMP_LEFT = [(jump_left, 0.12)]\nANIMATION_JUMP_RIGHT = [(jump_right, 0.12)]\nANIMATION_STAY = [(stay, 0.12)]\n\n\nclass Person(sprite.Sprite):\n def __init__(self, x, y):\n sprite.Sprite.__init__(self)\n self.xvel = 0\n self.yvel = 0\n self.start_x = x\n self.start_y = y\n self.on_groung = False\n self.image = Surface((WIDTH, HEIGHT))\n self.image.fill(Color(COLOR))\n self.rect = Rect(x, y, WIDTH, HEIGHT)\n self.image.set_colorkey(Color(COLOR))\n\n bolt_anim = []\n for anim in ANIMATION_RIGHT:\n bolt_anim.append((anim, ANIMATION_DELAY))\n self.bolt_anim_right = pyganim.PygAnimation(bolt_anim, (0, 0))\n self.bolt_anim_right.play()\n\n bolt_anim = []\n for anim in ANIMATION_LEFT:\n bolt_anim.append((anim, ANIMATION_DELAY))\n self.bolt_anim_left = pyganim.PygAnimation(bolt_anim, (0, 0))\n self.bolt_anim_left.play()\n\n self.bolt_anim_stay = pyganim.PygAnimation(ANIMATION_STAY)\n self.bolt_anim_stay.play()\n self.bolt_anim_stay.blit(self.image, (0, 0))\n\n self.bolt_anim_jump_left = pyganim.PygAnimation(ANIMATION_JUMP_LEFT)\n self.bolt_anim_jump_left.play()\n\n self.bolt_anim_jump_right = pyganim.PygAnimation(ANIMATION_JUMP_RIGHT)\n self.bolt_anim_jump_right.play()\n\n self.bolt_anim_jump = pyganim.PygAnimation(ANIMATION_JUMP)\n self.bolt_anim_jump.play()\n\n def update(self, left, right, up, platforms):\n if up:\n if self.on_groung:\n self.yvel = -JUMP_POWER\n self.image.fill(Color(COLOR))\n self.bolt_anim_jump.blit(self.image, (0, 0))\n\n if left:\n self.xvel = - MOVE_SPEED\n self.image.fill(Color(COLOR))\n if up:\n self.bolt_anim_jump_left.blit(self.image, (0, 0))\n else:\n self.bolt_anim_left.blit(self.image, (0, 0))\n\n if right:\n self.xvel = MOVE_SPEED\n self.image.fill(Color(COLOR))\n if up:\n self.bolt_anim_jump_right.blit(self.image, (0, 0))\n else:\n self.bolt_anim_right.blit(self.image, (0, 0))\n\n if not (left or right):\n self.xvel = 0\n if not up:\n self.image.fill(Color(COLOR))\n self.bolt_anim_stay.blit(self.image, (0, 0))\n\n if not self.on_groung:\n self.yvel += GRAVITY\n self.on_groung = False\n self.rect.y += self.yvel\n self.collide(0, self.yvel, platforms)\n self.rect.x += self.xvel\n self.collide(self.xvel, 0, platforms)\n\n def collide(self, xvel, yvel, platforms):\n for p in platforms:\n if sprite.collide_rect(self, p):\n if xvel > 0:\n self.rect.right = p.rect.left\n if xvel < 0:\n self.rect.left = p.rect.right\n if yvel > 0:\n self.rect.bottom = p.rect.top\n self.on_groung = True\n self.yvel = 0\n if yvel < 0:\n self.rect.top = p.rect.bottom\n self.yvel = 0\n\n\nclass Camera():\n def __init__(self, camera_func, width, height):\n self.camera_func = camera_func\n self.state = Rect(0, 0, width, height)\n\n def apply(self, target):\n return target.rect.move(self.state.topleft)\n\n def update(self, target):\n self.state = self.camera_func(self.state, target.rect)\n","sub_path":"person.py","file_name":"person.py","file_ext":"py","file_size_in_byte":4555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"548723907","text":"from sudoku_utils.sudoku_utils import sudoku_parser, prepare_sudoku, energy_sudoku, sudoku_done\nfrom sim_ann.sim_ann import AnnealingSimulator\nfrom numpy import inf\nconfig = (\n (800, lambda t: 0.99985 * t),\n (900, lambda t: 0.9998 * t)\n)\n\n\ndef main():\n results_done = []\n results_not_done = []\n for file in range(75, 21, -5):\n best_done = False\n best_iterations = inf\n for initial_temp, next_temp_f in config:\n file = str(file)\n parsed_sudoku = sudoku_parser('./sudoku_benchmarks/'+ file)\n initial_sudoku, next_sudoku_f, emptys_qty = prepare_sudoku(parsed_sudoku, 'row_swap')\n iterations = 0\n print(\"Number of emptys: \", emptys_qty)\n\n simulator = AnnealingSimulator(energy_sudoku, initial_sudoku,\n next_sudoku_f, initial_temp,\n next_temp_f, stop_cond=sudoku_done, min_temp=0.1)\n\n simulator.anneal()\n done = sudoku_done(simulator.best_state)\n iterations += simulator.iters_done\n for _ in range(3):\n if done:\n break\n initial_temp *= 1/2\n initial_temp = int(initial_temp)\n simulator = AnnealingSimulator(energy_sudoku, simulator.best_state,\n next_sudoku_f, initial_temp,\n next_temp_f, stop_cond=sudoku_done, min_temp=0.1)\n\n simulator.anneal()\n done = sudoku_done(simulator.best_state)\n iterations += simulator.iters_done\n best_done = best_done or done\n best_iterations = min(best_iterations, iterations)\n\n if best_done:\n results_done.append((emptys_qty, best_iterations))\n else:\n results_not_done.append((emptys_qty, energy_sudoku(simulator.best_state)))\n\n print(\"Done: \", results_done)\n print(\"Not done: \", results_not_done)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"simulated_annealing/sudoku.py","file_name":"sudoku.py","file_ext":"py","file_size_in_byte":2073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"549744118","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom reddressboutique.items import ReddressboutiqueItem1\n\n\nclass GetmetadatafromproductSpider(scrapy.Spider):\n name = 'getmetadatafromproduct'\n allowed_domains = []\n start_urls = []\n read_urls = open('producturls.csv', 'r')\n for url in read_urls.readlines():\n url = url.strip()\n allowed_domains = allowed_domains = [url[4:]]\n start_urls = start_urls + [url]\n\n read_urls.close\n def parse(self, response):\n items = ReddressboutiqueItem1()\n producturl = response.request.url\n productname = response.xpath('//h1[@class=\"product_title\"]/text()').extract()\n price = response.xpath('//h5[@class=\"price\"]/text()').extract()\n invcount = response.xpath('//script[@id=\"back-in-stock-helper\"]/text()').re_first(r'\"inventory_quantity\":([\\d]+)')\n prodcategory = response.xpath('//script[@class=\"analytics\"]/text()').re(r'\"category\":([\\\"a-zA-Z]+)')\n productcolor = response.xpath('//div[@class=\"options colors color_radios_group hide\"]//@value').extract()\n productsizes = response.xpath('//script[@id=\"back-in-stock-helper\"]/text()').re(r'\"option1\":([\\.\"a-z-A-Z0-9]+)')\n items['producturl'] = ''.join(producturl).strip() if producturl else None\n items['productname'] = ''.join(productname).strip() if productname else None\n items['price'] = ''.join(price).strip() if price else None\n items['invcount'] = ''.join(invcount).strip() if invcount else None\n items['prodcategory'] = ''.join(prodcategory).strip() if prodcategory else None\n items['productcolor'] = ''.join(productcolor).strip() if productcolor else None\n items['productsizes'] = ''.join(productsizes).strip() if productsizes else None\n\n yield items","sub_path":"projectscrappers/reddressboutique/reddressboutique/spiders/getmetadatafromproduct.py","file_name":"getmetadatafromproduct.py","file_ext":"py","file_size_in_byte":1787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"636407775","text":"from pyglet.window import key\nfrom pprint import pprint\nfrom burl.language import Context, EvaluationError, Value\nfrom burl.parser import ParseNode\n\n\nclass CommandCard():\n\t# rmf todo: configurable keys, common keyboard layouts\n\tcard_keys = [\n\t\t[key._1, key._2, key._3, key._4, key._5,],\n\t\t[key.Q, key.W, key.E, key.R, key.T,],\n\t\t[key.A, key.S, key.D, key.F, key.G,],\n\t\t[key.Z, key.X, key.C, key.V, key.B,],\n\t]\n\n\tdef __init__(self, tab_indexes, tabs, tab_buttons, element_buttons, command_label, prefs):\n\t\tself.tab_indexes = tab_indexes\n\t\tself.tabs = tabs\n\t\tself.tab_buttons = tab_buttons\n\t\tself.element_buttons = element_buttons\n\t\tself.active_type = None\n\t\tself.command_label = command_label\n\t\tself.command_label.label.width = 100\n\t\tself.command_label.label.multiline = True\n\t\tself.prefs = prefs\n\t\thotkey_index = 0\n\t\tself.hotkeys={}\n\t\tself.burl_context = Context()\n\t\tself.burl_context.parse_eval(\"LoadModule composition\")\n\t\tfor module in self.prefs.modules:\n\t\t\tself.burl_context.parse_eval(\"LoadModule \" + module)\n\t\tself.burl_cursor = None\n\n\t\tfor row in range(min(self.prefs.card_rows, len(CommandCard.card_keys))):\n\t\t\tfor column in range(min(self.prefs.card_columns, len(CommandCard.card_keys[row]))):\n\t\t\t\tself.hotkeys[CommandCard.card_keys[row][column]] = hotkey_index\n\t\t\t\thotkey_index += 1\n\n\t\tfor element_type, index in self.tab_indexes.items():\n\t\t\tif index == 0:\n\t\t\t\tself.change_tab(element_type)\n\t\t\t\tbreak\n\n\t\tself.update_cursor()\n\t\tself.command_label.label.text = str(self.burl_cursor)\n\t\tself.command_label.label.font_size = self.command_label.label.font_size\n\n\tdef change_tab(self, element_type):\n\t\tself.tabs.set_active_tab(self.tab_indexes[element_type])\n\t\tself.active_type = element_type\n\t\t# disable element_buttons that aren't allowed\n\n\tdef append_element(self, element, element_type):\n\t\tself.element_buttons['Meta']['Skip'].enable()\n\t\tif element_type == 'Meta':\n\t\t\tif element == 'Execute':\n\t\t\t\tresult = self.burl_context.parse_eval(\"Evaluate Cursor.GetEvalNode Get cursor\")\n\t\t\t\tprint(result)\n\t\t\t\tself.burl_cursor = None\n\t\t\telif element == 'Skip':\n\t\t\t\tsuccess = self.burl_cursor.value.increment_path_to_open_parameter(force_one=True)\n\t\t\t\tif not success:\n\t\t\t\t\tself.element_buttons['Meta']['Skip'].disable()\n\t\t\telif element == 'Cancel':\n\t\t\t\tself.burl_cursor = None\n\t\telse:\n\t\t\tself.burl_context.parse_eval(\"Cursor.InsertArgument Get cursor Quote \" + element)\n\t\tself.update_cursor()\n\n\t\tself.command_label.label.text = str(self.burl_cursor)\n\t\tself.command_label.label.font_size = self.command_label.label.font_size\n\t\t\n\n\tdef on_key_press(self, symbol, modifiers):\n\t\tif modifiers:\n\t\t\treturn False\n\t\tif symbol not in self.hotkeys:\n\t\t\treturn False\n\t\tif self.active_type not in self.prefs.exposed_elements:\n\t\t\treturn False\n\t\tindex = self.hotkeys[symbol]\n\t\tif index >= len(self.prefs.exposed_elements[self.active_type]):\n\t\t\treturn False\n\t\telement = self.prefs.exposed_elements[self.active_type][index]\n\t\telement_button = self.element_buttons[self.active_type][element]\n\t\telement_button.try_press()\n\t\treturn True\n\n\tdef update_cursor(self):\n\t\tif self.burl_cursor is None:\n\t\t\tself.burl_cursor = self.burl_context.parse_eval(\"Set cursor Cursor.Make Quote \" + self.prefs.root_node)\n\t\t\n\t\toptions = self.burl_context.parse_eval(\"Cursor.GetAllowedArgumentTypes Get cursor\")\n\t\tif not options.value:\n\t\t\t# rmf todo: reset cursor\n\t\t\treturn\n\n\t\tmin_type = None\n\t\tallowed_types = {o.value for o in options.value}\n\t\tfor element_type, type_button in self.tab_buttons.items():\n\t\t\tif element_type in allowed_types or element_type == 'Meta':\n\t\t\t\ttype_button.enable()\n\t\t\t\tif element_type != 'Meta' and (min_type is None\n\t\t\t\t\t\tor self.tab_indexes[element_type] < self.tab_indexes[min_type]):\n\t\t\t\t\tmin_type = element_type\n\t\t\telse:\n\t\t\t\ttype_button.disable()\n\t\t\t\t\n\t\tif min_type is None:\n\t\t\tmin_type = 'Meta'\n\t\tself.change_tab(min_type)\n","sub_path":"python/app/command_card.py","file_name":"command_card.py","file_ext":"py","file_size_in_byte":3809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"462167005","text":"# HOW TO USE THIS MODULE:\n# make sure this script is in the same directory as whatever thing is trying to import it\n# `from bird_classifier import *`\n# to get a dataframe with probabilities assigned to all 198 bird categories, call the function classify_bird_image, which takes three parameters:\n# file_name <= path to file of bird image to classify\n# model_file <= path to file of model to use (this can be either the model with all 198 categories, or the \"bird vs not-bird\" binary classification model... which doesn't exist yet)\n# label_file <= path to text file of labels, which will either be the 198 bird categories or \"Bird / Not-Bird\"\n# not to mansplain filesystems, but be mindful of what directory your files are in, since you might need to do some ..s to get around\n# the function returns a dataframe with the labels and probabilities, so you can call it like\n# df = classify_bird_image(x,y,z) where x, y, and z are the parameters specified above\n# then you can use those labels and probabilities to do whatever gives you the greatest joy\n\n\n#BORING COPYRIGHT INFO:\n# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport sys\nimport time\n\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\n\ndef load_graph(model_file):\n graph = tf.Graph()\n graph_def = tf.GraphDef()\n\n with open(model_file, \"rb\") as f:\n graph_def.ParseFromString(f.read())\n with graph.as_default():\n tf.import_graph_def(graph_def)\n\n return graph\n\ndef read_tensor_from_image_file(file_name, input_height=299, input_width=299,\n\t\t\t\tinput_mean=0, input_std=255):\n input_name = \"file_reader\"\n output_name = \"normalized\"\n file_reader = tf.read_file(file_name, input_name)\n if file_name.endswith(\".png\"):\n image_reader = tf.image.decode_png(file_reader, channels = 3,\n name='png_reader')\n elif file_name.endswith(\".gif\"):\n image_reader = tf.squeeze(tf.image.decode_gif(file_reader,\n name='gif_reader'))\n elif file_name.endswith(\".bmp\"):\n image_reader = tf.image.decode_bmp(file_reader, name='bmp_reader')\n else:\n image_reader = tf.image.decode_jpeg(file_reader, channels = 3,\n name='jpeg_reader')\n float_caster = tf.cast(image_reader, tf.float32)\n dims_expander = tf.expand_dims(float_caster, 0);\n resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width])\n normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])\n sess = tf.Session()\n result = sess.run(normalized)\n\n return result\n\ndef load_labels(label_file):\n label = []\n proto_as_ascii_lines = tf.gfile.GFile(label_file).readlines()\n for l in proto_as_ascii_lines:\n label.append(l.rstrip())\n return label\n\n# CLASSIFY A BIRD IMAGE\n# example parameter values:\n# file_name = \"../test_image_examples/ew.jpg\"\n# model_file = \"../tf_files/retrained_graph.pb\"\n# label_file = \"../tf_files/retrained_labels.txt\"\ndef classify_bird_image(file_name,model_file,label_file):\n input_height = 299\n input_width = 299\n input_mean = 0\n input_std = 255\n input_layer = \"Mul\"\n output_layer = \"final_result\"\n\n\n graph = load_graph(model_file)\n t = read_tensor_from_image_file(file_name,\n input_height=input_height,\n input_width=input_width,\n input_mean=input_mean,\n input_std=input_std)\n\n input_name = \"import/\" + input_layer\n output_name = \"import/\" + output_layer\n input_operation = graph.get_operation_by_name(input_name);\n output_operation = graph.get_operation_by_name(output_name);\n\n with tf.Session(graph=graph) as sess:\n start = time.time()\n results = sess.run(output_operation.outputs[0],\n {input_operation.outputs[0]: t})\n end=time.time()\n results = np.squeeze(results)\n labels = load_labels(label_file)\n\n #top_k = results.argsort()[-5:][::-1]\n sorted_results = results.argsort()[:][::-1]\n\n labels_output=[]\n results_output=[]\n\n #print('\\nEvaluation time (1-image): {:.3f}s\\n'.format(end-start))\n\n for i in sorted_results:\n #print(labels[i], results[i])\n labels_output.append(labels[i])\n results_output.append(results[i])\n\n df = pd.DataFrame({'category': labels_output,\n 'probability': results_output})\n\n return df","sub_path":"bird_classifier/bird_classifier.py","file_name":"bird_classifier.py","file_ext":"py","file_size_in_byte":5202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"228013524","text":"#!/usr/bin/env python3\n\nimport os\nimport random\nimport argparse\nfrom collections import defaultdict\nfrom datetime import datetime\nimport gc\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--outfile', help='output file with walks', required=True)\nparser.add_argument('--cat', help='process categories',\n default=False, action='store_true')\nparser.add_argument('--length', help='length of walks', default=10, type=int)\nparser.add_argument('--walks', help='walks per root', default=100, type=int)\nargs = parser.parse_args()\n\ngraph_path = os.path.join('data', 'graph.tsv')\n\noutents = {}\noutlits = {}\n\ndef process_node(subj, out_file):\n for _ in range(args.walks):\n walk = [subj]\n l = 1\n visited = {subj}\n obj = subj\n\n while obj in outents and l < args.length:\n pred, obj2 = random.choice(outents[obj])\n tried = set()\n while obj2 in visited:\n tried.add((pred, obj2))\n if len(tried) == len(outents[obj]):\n break\n pred, obj2 = random.choice(outents[obj])\n else:\n obj = obj2\n walk.extend([pred, obj])\n l += 1\n visited.add(obj)\n continue\n break\n\n if obj in outlits:\n walk.extend(random.choice(outlits[obj]))\n\n print(*walk, sep='\\t', file=out_file)\n\ndef main():\n outents_set = defaultdict(set)\n outlits_set = defaultdict(set)\n i = 0\n with open(graph_path) as in_file:\n for line in in_file:\n subj, pred, obj = line.rstrip().split('\\t')\n if obj.startswith('<') and (args.cat or pred != ''):\n outents_set[subj].add((pred, obj))\n outents_set[obj].add((pred, subj))\n else:\n outlits_set[subj].add((pred, obj))\n i += 1\n if i % 10000000 == 0:\n print('Read {} lines'.format(i))\n\n\n start_nodes = []\n for subj, onodes in outents_set.items():\n outents[subj] = list(onodes)\n if not subj.startswith(' A.shape[1]:\n m = A.shape[1]\n\n n = A.shape[1]\n\n beta = zeros(m+1);\n alpha = zeros(m)\n\n V = zeros((n, m))\n v = [zeros(n), Normalize(ones(n))]\n\n for i in range(0, m):\n w = dot(A, v[1]).squeeze()\n\n alpha[i] = dot(w, v[1])\n w -= alpha[i] * v[1] - beta[i] * v[0]\n\n w = OrthogonalizeVector(w, V[:, :i])\n\n beta[i+1] = Norm(w)\n\n v[0] = v[1]\n v[1] = Normalize(w)\n\n V[:, i] = v[0]\n\n T = diags([beta[1:-1], alpha, beta[1:-1]], [-1, 0, 1]).toarray();\n\n return V, T\n\n\ndef OrthogonalizeVector(w, V):\n for t in range(V.shape[1]):\n tmpa = dot(w, V[:, t])\n if tmpa == 0.0:\n continue\n w -= tmpa * V[:, t]\n\n return w\n\n\ndef EigenSolve(A, m):\n\n V, T = Lanczos(A, m)\n d, v = eig(T)\n\n sortedIndex = argsort(absolute(d))[::-1]\n d = d[sortedIndex]\n v = v[:, sortedIndex]\n\n s = dot(V, v)\n\n return d[0:m], s[:, 0:m]\n","sub_path":"SuPyModes/Special.py","file_name":"Special.py","file_ext":"py","file_size_in_byte":7709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"475725921","text":"from . import provider_conf\nfrom .models import User, AccessKey\nimport boto3\nfrom botocore.exceptions import ClientError\n\n\ndef _ec2user_to_user(ec2user):\n u = User()\n u.name = ec2user.get('UserName')\n u.id = ec2user.get('UserId')\n u.create_date = ec2user.get('CreateDate')\n u.keys = []\n return u\n\n\ndef _user_add_keys(user):\n iam = boto3.client('iam', aws_access_key_id=provider_conf.EC2['key'],\n aws_secret_access_key=provider_conf.EC2['secret'])\n for response in iam.get_paginator('list_access_keys').paginate(\n UserName=user.name):\n for key in response.get('AccessKeyMetadata'):\n k = AccessKey()\n k.create_date = key.get('CreateDate')\n k.key_id = key.get('AccessKeyId')\n k.status = key.get('Status').lower()\n user.keys.append(k)\n return user\n\n\ndef get_users(name=None):\n '''\n See for more details on boto iam api.\n https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/iam.html\n '''\n iam = boto3.client('iam', aws_access_key_id=provider_conf.EC2['key'],\n aws_secret_access_key=provider_conf.EC2['secret'])\n users = []\n if name:\n try:\n response = iam.get_user(UserName=name)\n user = response.get('User')\n u = _ec2user_to_user(user)\n _user_add_keys(u)\n users.append(u)\n except ClientError as ex:\n print(ex)\n else:\n for response in iam.get_paginator('list_users').paginate():\n for user in response.get('Users'):\n u = _ec2user_to_user(user)\n _user_add_keys(u)\n users.append(u)\n\n return users\n\n\ndef get_user_by_key(key_id):\n users = get_users()\n\n for user in users:\n for key in user.keys:\n if key_id == key.key_id:\n return user\n return None\n\n\ndef get_key(key_id):\n users = get_users()\n for user in users:\n for key in user.keys:\n if key_id == key.key_id:\n return key\n return None\n\n\ndef delete_key(key_id):\n user = get_user_by_key(key_id)\n if user is None:\n return False\n if len(user.keys) == 1:\n delete_user(user.name)\n return True\n else:\n iam_res = boto3.resource(\n 'iam', aws_access_key_id=provider_conf.EC2['key'],\n aws_secret_access_key=provider_conf.EC2['secret'])\n key = iam_res.AccessKey(user.name, key_id)\n key.delete()\n return True\n\n\ndef delete_user(username):\n iam = boto3.client('iam', aws_access_key_id=provider_conf.EC2['key'],\n aws_secret_access_key=provider_conf.EC2['secret'])\n iam_res = boto3.resource('iam', aws_access_key_id=provider_conf.EC2['key'],\n aws_secret_access_key=provider_conf.EC2['secret'])\n\n try:\n user = iam_res.User(username)\n user.load()\n except iam.meta.client.exceptions.NoSuchEntityException:\n return False\n\n for key in user.access_keys.all():\n key.delete()\n\n for response in iam.get_paginator('list_attached_user_policies').paginate(\n UserName=username):\n for policy in response.get('AttachedPolicies'):\n user.detach_policy(PolicyArn=policy.get('PolicyArn'))\n user.delete()\n return True\n\n\ndef create_user(username):\n iam_res = boto3.resource('iam', aws_access_key_id=provider_conf.EC2['key'],\n aws_secret_access_key=provider_conf.EC2['secret'])\n user = iam_res.User(username)\n try:\n user.load()\n except iam_res.meta.client.exceptions.NoSuchEntityException:\n try:\n user.create(Path=\"/pcw/auto-generated/\")\n except ClientError:\n return None\n\n user.attach_policy(\n PolicyArn='arn:aws:iam::aws:policy/AmazonEC2FullAccess'\n )\n\n try:\n key = user.create_access_key_pair()\n except ClientError:\n return None\n\n u = User()\n u.name = user.user_name\n u.id = user.user_id\n u.create_date = user.create_date\n k = AccessKey()\n k.create_date = key.create_date\n k.key_id = key.id\n k.status = key.status.lower()\n k.secret = key.secret\n u.keys = [k]\n return u\n","sub_path":"webui/ec2/EC2.py","file_name":"EC2.py","file_ext":"py","file_size_in_byte":4274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"170393360","text":"from torchsummary import summary\nimport logging\nlogging.propagate = False \nlogging.getLogger().setLevel(logging.ERROR)\n\nfrom argparse import ArgumentParser\nfrom tqdm import tqdm\nimport os\nimport random\n\n# from ignite.engine import Events, create_supervised_trainer, create_supervised_evaluator\n# from ignite.metrics import Accuracy, Loss\n# from torch.utils.data import DataLoader\n# from ignite.handlers import Checkpoint, DiskSaver\n\nimport wandb\n\n\ndef get_wandb_dataframes(run_list=None, project=None):\n api = wandb.Api()\n delta_dataframes = []\n for run_key in run_list:\n delta_dataframes.append(api.run(run_key).history())\n return delta_dataframes\n\ndef get_wandb_dataframes_proj(project=None, count=1):\n api = wandb.Api()\n delta_dataframes = []\n if project is None:\n return\n current_runs = api.runs(project, order='-created_at')\n #print(current_runs[0].history()['Train Accuracy'])\n for run_key in range(count):\n print(current_runs[run_key].name)\n delta_dataframes.append(current_runs[run_key].history())\n return delta_dataframes","sub_path":"miniRekog/utils/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"116536024","text":"from tkinter import *\r\nfrom tkinter.ttk import Combobox\r\n\r\nclass Ui(Frame):\r\n def __init__ (self, master = None):\r\n Frame.__init__(self, master)\r\n self.master.title('四则运算')\r\n self.master.geometry('320x240')\r\n self.createWidgets()\r\n def createWidgets(self):\r\n self.top = self.winfo_toplevel()\r\n self.entry1 = Entry(self.top)\r\n self.entry1.place(relx = 0.1, rely = 0.1, relwidth = 0.3, relheight = 0.1)\r\n self.entry2 = Entry(self.top)\r\n self.entry2.place(relx = 0.5, rely = 0.1, relwidth = 0.3, relheight = 0.1)\r\n self.combo1List = ['加', '减', '乘', '除']\r\n self.combo1Var = StringVar(value = '加')\r\n self.combo1 = Combobox(self.top, textvariable = self.combo1Var, \\\r\n values = self.combo1List)\r\n self.combo1.place(relx = 0.5, rely = 0.5, relwidth = 0.4)\r\n self.combo1.bind('<>', self.calc)\r\n self.label = Label(self.top)\r\n self.label.place(relx = 0.5, rely = 0.6, relwidth = 0.4, relheight = 0.2)\r\nclass App(Ui):\r\n def __init__ (self, master = None):\r\n Ui.__init__(self, master)\r\n def calc(self, event):\r\n a = float(self.entry1.get())\r\n b = float(self.entry2.get())\r\n dic = {0:a+b, 1:a-b, 2:a*b, 3:a/b if b != 0 else '0不能作为除数'}\r\n c = dic[self.combo1.current()]\r\n self.label.config(text = c if c == '0不能作为除数' else f'{c:.4f}')\r\n\r\nif __name__ == '__main__':\r\n top = Tk()\r\n App(top).mainloop()\r\n\r\n","sub_path":"界面设计与业务逻辑.py","file_name":"界面设计与业务逻辑.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"606377241","text":"import json\r\nfrom gensim.models.doc2vec import Doc2Vec, TaggedDocument\r\nimport numpy as np\r\n\r\n\r\ndef readData(url):\r\n with open(url, 'r') as f:\r\n # data=json.load(f)\r\n data = f.readlines()\r\n # print(data)\r\n data = json.loads(data[0].replace('\\'', '\\\"'))\r\n return data\r\n\r\n\r\ndef read_json(add):\r\n with open(add, 'rt', encoding=\"utf-8\") as f:\r\n cr = json.load(f)\r\n f.close()\r\n return cr\r\n\r\n\r\ndef write_json(add, arr):\r\n with open(add, 'a', encoding='utf-8', newline='') as f:\r\n json.dump(arr, f)\r\n f.close()\r\n return\r\n\r\n\r\ndef do_doc2vec(data):\r\n documents = []\r\n id = []\r\n index = 0\r\n for i in data:\r\n id.append(index)\r\n print(TaggedDocument(i, [index]))\r\n documents.append(TaggedDocument(i, [index]))\r\n index += 1\r\n model = Doc2Vec(documents,\r\n dm=1,\r\n vector_size=100,\r\n window=8,\r\n min_count=1,\r\n workers=4,\r\n epochs=400)\r\n model.train(documents, total_examples=model.corpus_count, epochs=400)\r\n model.save('doc2vec.model')\r\n # corpus = model.docvecs\r\n # for i in corpus:\r\n # print(i)\r\n # np.savetxt(url,np.asarray(corpus))\r\n # fw = open(url, 'w', encoding=\"utf-8\")\r\n # fw.write(str(len(documents)) + \" 100 \\n\")\r\n # for i in range(len(documents)):\r\n # if i % 100 == 0:\r\n # print(i)\r\n # model = Doc2Vec.load('doc2vec.model')\r\n # fw.write(\r\n # str(id[i]) + \" \" +\r\n # str(model.infer_vector(data[i])).replace('\\n', \"\") + \"\\n\")\r\n # fw.close()\r\n ls = []\r\n for i in range(len(documents)):\r\n if i % 100 == 0:\r\n print(i)\r\n model = Doc2Vec.load('doc2vec.model')\r\n ls.append(list(map(float, model.infer_vector(data[i]))))\r\n # print(ls)\r\n # write_json(url, ls)\r\n print('Finish Doc2Vec')\r\n return ls\r\n\r\n# if __name__ == \"__main__\":\r\n# # for i in range(1, 2):\r\n# i = 'alldriving'\r\n# url = \"D:\\\\EcoVisual\\\\Doc2Vec\\\\\" + i + \".json\"\r\n# saveuUrl = \"D:\\\\EcoVisual\\\\Doc2Vec\\\\dx\\\\\" + i + \".json\"\r\n# data = read_json(url)\r\n# print(\"Read\" + str(i) + \"Finish\")\r\n# do_doc2vec(data, saveuUrl)\r\n\r\n","sub_path":"getDoc/getdoc2vec.py","file_name":"getdoc2vec.py","file_ext":"py","file_size_in_byte":2259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"259890443","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('photos', '0005_auto_20170817_1255'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='gallery',\n name='date',\n field=models.DateField(verbose_name='Date', blank=True, null=True, default=django.utils.timezone.now, help_text='Date format: YYYY-MM-DD (optional).'),\n ),\n ]\n","sub_path":"my_site/photos/migrations/0006_auto_20170817_1302.py","file_name":"0006_auto_20170817_1302.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"606915280","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom .models import DoubanMovie\n\ndef movie_short(request):\n shorts=DoubanMovie.objects.all()\n counter=DoubanMovie.objects.all().count()\n\n\n queryset=DoubanMovie.objects.values('rate')\n conditons={'rate__gte':3}\n plus=queryset.filter(**conditons).count()\n\n return render(request,'result.html',locals())\n\n","sub_path":"week06/DouBanMovie/DouBan/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"105903937","text":"# Your code here\nimport pathlib\n\n\ndef finder(files, queries):\n \"\"\"\n YOUR CODE HERE\n \"\"\"\n \n # Your code here\n result = []\n pathsDict = {}\n\n\n # fill in pathsDict with every item in array\n for value in files:\n path = value.split(\"/\")[-1]\n # value = \"home/david/foo.txt\"\n # path = \"foo.txt\"\n\n # if key DOESN'T exist yet\n if path not in pathsDict:\n pathsDict[path] = [value]\n\n # else, key is already present, so just add value to it's value arra\n else:\n # print(f\"path dupe {value}\")\n pathsDict[path].append(value)\n \n for query in queries:\n if query in pathsDict:\n result += pathsDict[query]\n\n return result\n\n\nif __name__ == \"__main__\":\n # files = [\n # '/bin/foo',\n # '/bin/bar',\n # '/usr/bin/baz'\n # ]\n files = [\n \"/usr/local/share/foo.txt\",\n \"/usr/bin/ls\",\n \"/home/davidlightman/foo.txt\",\n \"/bin/su\"\n ]\n # queries = [\n # \"foo\",\n # \"qux\",\n # \"baz\"\n # ]\n queries = [\n \"ls\",\n \"foo.txt\",\n \"nosuchfile.txt\"\n ]\n print(finder(files, queries))\n\n# Given a list of full paths to files, and a list of filenames to query,\n# report all the full paths that match that filename.\n\n# Example input:\n\n# ```python\n# paths = [\n# \"/usr/local/share/foo.txt\",\n# \"/usr/bin/ls\",\n# \"/home/davidlightman/foo.txt\",\n# \"/bin/su\"\n# ]\n\n# queries = [\n# \"ls\",\n# \"foo.txt\",\n# \"nosuchfile.txt\"\n# ]\n# ```\n\n# Example return value:\n\n# ```\n# [ \"/usr/local/share/foo.txt\", \"/usr/bin/ls\", \"/home/davidlightman/foo.txt\" ]\n# ```\n\n# because that's where the `foo.txt` and `ls` files are. \n\n# The file `\"nosuchfile.txt\"` is ignored because it's not in the `paths`.","sub_path":"hashtables/ex5/ex5.py","file_name":"ex5.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"462017509","text":"import numpy as np\nfrom scanorama import *\nfrom sklearn.manifold import TSNE\nfrom sklearn.preprocessing import normalize\nimport sys\nfrom time import time\n\nfrom process import load_names\n\nNAMESPACE = 'different3'\n\ndata_names = [\n 'data/brain/neuron_9k',\n 'data/hsc/hsc_mars',\n 'data/macrophage/uninfected',\n]\n\nif __name__ == '__main__':\n datasets, genes_list, n_cells = load_names(data_names)\n\n datasets_dimred, datasets, genes = correct(\n datasets, genes_list, ds_names=data_names,\n return_dimred=True\n )\n\n labels = []\n names = []\n curr_label = 0\n for i, a in enumerate(datasets):\n labels += list(np.zeros(a.shape[0]) + curr_label)\n names.append(data_names[i])\n curr_label += 1\n labels = np.array(labels, dtype=int)\n \n visualize(datasets_dimred, labels, NAMESPACE, data_names,\n perplexity=100)\n","sub_path":"bin/different3.py","file_name":"different3.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"598561355","text":"import os\nimport cv2\nimport csv\nimport time\nimport pandas as pd\n# import kalman\n# import numpy as np\n# import minpy.numpy as np\nimport matplotlib.pyplot as plt\n\ndef get_data_from_video(path):\n # draw the picture\n ax = [] # 定义一个 x 轴的空列表用来接收动态的数据\n ay = [] # 定义一个 y 轴的空列表用来接收动态的数据\n rate_w_h = []\n rate_speed = []\n area_motion = []\n timestamps = []\n plt.ion() # 开启一个画图的窗口\n\n def timestamp(convert_to_utc=False):\n t = time.time()\n return int(round(t * 1000))\n\n # plt.clf()\n # count = 0\n cap = cv2.VideoCapture(path)\n # cap.set(cv2.CAP_PROP_FRAME_WIDTH, 320)\n # cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 240)\n\n cap.set(cv2.CAP_PROP_FPS, 25)\n\n fps_c = cap.get(7)\n print('FPS >>>', fps_c)\n # Check if camera opened successfully\n if (cap.isOpened() == False):\n print(\"Error opening video stream or file\")\n\n frameNum = 0\n x,y,w,h = 0, 0, 0, 0\n tempSpeed = [0.0, 0.0]\n currentSpeed = [0.0, 0.0]\n a, tempa, area = 0, 0, 0\n tempY = 0\n # Read until video is completed\n while cap.isOpened():\n # Capture frame-by-frame\n ret, frame = cap.read()\n # if (cap.get())\n if ret == True:\n frameNum += 1\n frame = cv2.resize(frame, (320,240))\n tempframe = frame.copy()\n if (frameNum == 1):\n previousframe = cv2.cvtColor(tempframe, cv2.COLOR_BGR2GRAY)\n # print(\"Origin\")\n if (frameNum >= 2):\n currentframe = cv2.cvtColor(tempframe, cv2.COLOR_BGR2GRAY)\n currentframe = cv2.absdiff(currentframe, previousframe)\n currentframe = cv2.dilate(currentframe, None, iterations = 7)\n currentframe = cv2.erode(currentframe, None, iterations = 5)\n\n # currentframe = cv2.morphologyEx(currentframe, cv2.MORPH_GRADIENT, kernel)\n\n ret, threshold_frame = cv2.threshold(currentframe, 20, 255, cv2.THRESH_BINARY)\n # gauss_image = cv2.GaussianBlur(threshold_frame, (7, 7), 0)\n cnts, hierarchy = cv2.findContours(threshold_frame, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n for c in cnts:\n if cv2.contourArea(c) < 1300 or cv2.contourArea(c) > 19200:\n continue\n # c是一个二值图,boundingRect是矩形边框函数,用一个最小的矩形,把找到的形状包起来;\n # x,y是矩形左上点的坐标;w,h是矩阵的宽和高\n (x,y,w,h) = cv2.boundingRect(c) # update the rectangle\n hull = cv2.convexHull(c)\n # cv2.drawContours(frame, [hull], 0, (0, 0, 255), 2)\n area = cv2.contourArea(hull)\n\n if (w*h==0):\n continue\n\n # if (frameNum % 2 == 0):\n # currentSpeed = [x+w/2, y+h/2]\n # a = ((currentSpeed[0]-tempSpeed[0])**2 + (currentSpeed[1]-tempSpeed[1])**2)**0.5\n # # print(a)\n # if (a > 30):\n # a = tempa\n # tempSpeed = currentSpeed\n # tempa = a\n\n # plt.clf()\n # plt.title('Fall Analysis')\n ax.append(frameNum)\n ay.append(y-30) # y of mid-point\n\n ys = y-tempY\n if (ys<16):\n ys = ys\n else:\n ys = 1\n tempY = y\n motion_speed = area/500*ys\n\n if (abs(motion_speed) < 120):\n area_motion.append(motion_speed)\n else:\n area_motion.append(0)\n\n rate_w_h.append((w/h - 0.5)*100) # rate of w/h\n # rate_speed.append(a* 3)\n # factor.append(a*area/100)\n timestamps.append(str(timestamp())+\"{0:04d}\".format(frameNum))\n\n # plt.plot(ax, ay, color='blue', label='X: y of start-point')\n # plt.plot(ax, rate_w_h, color='green', label='Y: w/h')\n # plt.plot(ax, area_motion, color='orange', label='Z: area of motion')\n # plt.plot(ax, rate_speed, color='red', label='acc')\n # plt.plot(ax,factor, color='skyblue', label='factor')\n\n # plt.legend() # 显示图例\n # plt.xlabel('Frames')\n\n # plt.draw() # for ubuntu\n # plt.pause(0.1) # for windows\n\n # rectangle画出矩形,frame是原图,(x,y)是矩阵的左上点坐标,(x+w,y+h)是矩阵右下点坐标\n cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,0), 2)\n # Display the resulting frame\n # cv2.imshow('frame', frame)\n # cv2.imshow('threshold', currentframe)\n # cv2.imshow('gauss', gauss_image)\n\n # Press Q on keyboard to exit\n if cv2.waitKey(33) & 0xFF == ord('q'):\n break\n previousframe = cv2.cvtColor(tempframe, cv2.COLOR_BGR2GRAY)\n # Break the loop\n else:\n break\n\n data = {\n 'action': 'notfall',\n 'timestamp': timestamps,\n 'x_axis': ay,\n 'y_axis': rate_w_h,\n 'z_axis': area_motion # speed of motion area\n }\n\n # print('frameNum', frameNum)\n\n df = pd.DataFrame(data)\n\n fileName = path.split('.')[0].split('/')[-1]\n df.to_csv(\"F:/ds/{}.csv\".format(fileName), mode='w',index=False, header=['action', 'timestamp', 'x_axis', 'y_axis', 'z_axis'])\n # print(df)\n # kalman.show_data(df)\n\n # plt.pause(5)\n plt.ioff()\n # When everything done, release the video capture object\n cap.release()\n\n # Closes all the frames\n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n video_path = 'F:/video/videoplayback.mp4'\n get_data_from_video(video_path)\n","sub_path":"RGB_difference_draw.py","file_name":"RGB_difference_draw.py","file_ext":"py","file_size_in_byte":6147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"297251119","text":"from scrapy.spiders import SitemapSpider\n\nfrom locations.linked_data_parser import LinkedDataParser\nfrom locations.microdata_parser import MicrodataParser\n\n\nclass CentralEnglandCooperativeSpider(SitemapSpider):\n name = \"central_england_cooperative\"\n item_attributes = {\n \"brand\": \"Central England Co-operative\",\n \"brand_wikidata\": \"Q16986583\",\n \"country\": \"GB\",\n }\n sitemap_urls = [\"https://stores.centralengland.coop/sitemap.xml\"]\n sitemap_rules = [\n (\n r\"https:\\/\\/stores\\.centralengland\\.coop\\/[-\\w]+\\/.*$\",\n \"parse_item\",\n )\n ]\n\n def parse_item(self, response):\n MicrodataParser.convert_to_json_ld(response)\n return LinkedDataParser.parse(response, \"LocalBusiness\")\n","sub_path":"locations/spiders/central_england_cooperative.py","file_name":"central_england_cooperative.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"553649884","text":"import sys, os, argparse, random, cv2, math, PIL\nfrom torchvision import transforms\n\nFileDirPath = os.path.dirname(os.path.realpath(__file__))\nsys.path.append(os.path.join(FileDirPath, '..'))\nsys.path.append(os.path.join(FileDirPath, '../..'))\n\nfrom tk3dv.ptTools import ptUtils\n\nclass nxm_config():\n def __init__(self, InputArgs=None):\n self.Parser = argparse.ArgumentParser(description='NOXRay maps prediction.', fromfile_prefix_chars='@')\n InputGroup = self.Parser.add_mutually_exclusive_group(required=True)\n InputGroup.add_argument('--mode', help='Operation mode.', choices=['train', 'val', 'test'])\n ArgGroup = self.Parser.add_argument_group()\n\n # Experiment control\n ArgGroup.add_argument('--dataset', help='Choose dataset.', choices=['ShapeNetCOCODataset'], default='ShapeNetCOCODataset')\n ArgGroup.add_argument('--category', help='For ShapeNetCOCODataset choose one or all categories.', choices=['cars', 'airplanes', 'chairs', 'all'], default='cars')\n ArgGroup.add_argument('--arch', help='Choose architecture.', choices=['SegNet', 'SegNetSkip'], default='SegNet')\n ArgGroup.add_argument('--no-mask', help='Choose to train and test without mask.', action='store_true')\n self.Parser.set_defaults(no_mask=False)\n ArgGroup.add_argument('--no-color-hallucinate', help='Choose to not hallucinate peeled color.', action='store_true')\n self.Parser.set_defaults(no_color_hallucinate=False)\n\n # Machine control\n ArgGroup.add_argument('--gpu', help='GPU ID(s) to use for training. Default is cuda:0, or cpu if no GPU is available. -1 will use all available GPUs.', default=[0], type=int, choices=range(-1,8), nargs='+')\n ArgGroup.add_argument('--seed', help='Select random seed to initialize torch, np.random, and random. Default is auto seed.', type=int)\n\n # DEBUG purposes\n ArgGroup.add_argument('--data-limit', help='Select how many samples to load from data. Default is all.', type=int, required=False, default=-1)\n ArgGroup.add_argument('--val-data-limit', help='Select how many samples to load from data for validation. Default is all.', type=int, required=False, default=-1)\n ArgGroup.add_argument('--force-test-on-train', help='Choose to test on the training data. CAUTION: Use this for debugging only.', action='store_true')\n self.Parser.set_defaults(force_test_on_train=False)\n ArgGroup.add_argument('--test-samples', help='Number of samples to test on.', default=30, type=int)\n\n # Loss function\n ArgGroup.add_argument('--loss', help='When using mask, what loss to use?', choices=['l2', 'chamfer'], default='l2')\n ArgGroup.add_argument('--use-small-dataset', help='Use a small dataset for testing purposes. CAUTION: Use this for debugging only.', action='store_true')\n self.Parser.set_defaults(use_small_dataset=False)\n\n self.InputSize = (320, 240, 3)\n self.ImageSize = (self.InputSize[0], self.InputSize[1])\n # self.DatasetInputTrans = transforms.Compose([\n # transforms.ToPILImage(),\n # transforms.Resize((self.InputSize[1], self.InputSize[0]), interpolation=PIL.Image.NEAREST),\n # transforms.ToTensor(),\n # ])\n # self.DatasetNOXTrans = transforms.Compose([\n # transforms.ToPILImage(),\n # transforms.Resize((self.InputSize[1], self.InputSize[0]), interpolation=PIL.Image.NEAREST),\n # transforms.ToTensor(),\n # ])\n\n self.Args, _ = self.Parser.parse_known_args(InputArgs)\n if len(sys.argv) <= 1:\n self.Parser.print_help()\n exit()\n\n self.WithMask = not self.Args.no_mask\n self.HallucinatePeeledColor = not self.Args.no_color_hallucinate\n if self.HallucinatePeeledColor == False:\n if self.WithMask:\n self.nOutChannels = 8 # (3 NOX + 1 mask) * 2\n else:\n self.nOutChannels = 6 # (3 NOX) * 2\n else:\n if self.WithMask:\n self.nOutChannels = 11 # (3 NOX + 1 mask) * 2 + 3 Peeled Color\n else:\n self.nOutChannels = 9 # (3 NOX) * 2 + 3 Peeled Color\n\n ptUtils.printArgs(self.Args)\n\n def serialize(self, FilePath, isAppend=True):\n ptUtils.configSerialize(self.Args, FilePath, isAppend)","sub_path":"noxray/nxm/configs/nxm_config.py","file_name":"nxm_config.py","file_ext":"py","file_size_in_byte":4642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"282771320","text":"import os\nimport sys\nimport time\nimport requests\nfrom urlparse import urlparse\nfrom slackclient import SlackClient\nfrom PIL import Image\nfrom geocoder import google\nimport argparse\n\n# metabot's ID as an environment variable\nBOT_ID = os.environ.get(\"SLACK_BOT_ID\")\n\n# constants\nAT_BOT = \"<@metabot>\"\nEXAMPLE_COMMAND = \"do\"\n\n# instantiate Slack & Twilio clients\nslack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))\n\n\nget_float = lambda x: float(x[0]) / float(x[1])\n\n\ndef convert_to_degrees(value):\n d = get_float(value[0])\n m = get_float(value[1])\n s = get_float(value[2])\n return d + (m / 60.0) + (s / 3600.0)\n\n\ndef get_lat_lon(info):\n try:\n gps_latitude = info[34853][2]\n gps_latitude_ref = info[34853][1]\n gps_longitude = info[34853][4]\n gps_longitude_ref = info[34853][3]\n lat = convert_to_degrees(gps_latitude)\n if gps_latitude_ref != \"N\":\n lat *= -1\n\n lon = convert_to_degrees(gps_longitude)\n if gps_longitude_ref != \"E\":\n lon *= -1\n return lat, lon\n except KeyError:\n return None\n\n\ndef parse_gps(url):\n \"\"\"\n Extract available GPS coordinates data from image EXIF data and attempt to geocode them with the Google API,\n and return a message for the channel/user if found.\n\n :param url: URL to Slack-hosted image\n :return: String to be returned to chat\n \"\"\"\n\n # We send a Bearer token to the URL we receive, so here we make sure it's Slack via HTTPS only #justsecuritythings\n try:\n parsedurl = urlparse(url)\n if not (parsedurl.hostname == 'files.slack.com' and parsedurl.scheme == 'https'):\n return None\n except Exception:\n raise\n\n try:\n # Fetch only the headers to check the file size and not waste time with large files\n response = requests.head(url, timeout=30,\n headers={'Authorization': 'Bearer {}'.format(os.environ.get('SLACK_BOT_TOKEN'))})\n\n if int(response.headers.get('Content-Length')) > 16000000:\n if args.verbose: sys.stderr.write('Skipped large file\\n')\n return None\n\n # Fetch the URL and use request's raw method to create a file object to give to Image\n response = requests.get(url, stream=True, timeout=10,\n headers={'Authorization': 'Bearer {}'.format(os.environ.get('SLACK_BOT_TOKEN'))})\n\n if not response.status_code == 200:\n if args.verbose: sys.stderr.write('Status code {}\\n'.format(response.status_code))\n return None\n\n # We don't make any assumptions about the file type from the URL in case there's no extension or it's inaccurate\n if response: img = Image.open(response.raw)\n\n # Attempt to get EXIF data from the image object\n if img: exif = img._getexif()\n\n # Attempt to find GPS coordinates and decode them to a tuple in degrees\n if exif: lat_lon = get_lat_lon(exif)\n\n # If we think we were successful, try to geocode the coordinates. If it fails, return only the coordinates\n if lat_lon and len(lat_lon) == 2:\n try:\n geocode = google(lat_lon, method='reverse')\n # Returns City, State and Country\n return '{}, {} ({}) - {:.4f}, {:.4f}'.format(geocode.city, geocode.state, geocode.country, lat_lon[0],\n lat_lon[1])\n except:\n # Coordinates only\n return '{:.4f}, {:.4f}'.format(lat_lon[0], lat_lon[1])\n else:\n if args.verbose: sys.stderr.write('No GPS data in EXIF\\n')\n except AttributeError:\n if args.verbose: sys.stderr.write('No EXIF data in file\\n')\n pass\n except Exception:\n raise\n\n return None\n\n\n# For future use\ndef handle_command(command, channel):\n \"\"\"\n Receives commands directed at the bot and determines if they\n are valid commands. If so, then acts on the commands. If not,\n returns back what it needs for clarification.\n \"\"\"\n response = \"Not sure what you mean. Use the *\" + EXAMPLE_COMMAND + \\\n \"* command with numbers, delimited by spaces.\"\n if command.startswith(EXAMPLE_COMMAND):\n response = \"Sure...write some more code then I can do that!\"\n slack_client.api_call('chat.postMessage', channel=channel,\n text=response, as_user=True)\n\n\ndef parse_slack_output(slack_rtm_output):\n \"\"\"\n The Slack Real Time Messaging API is an events firehose.\n this parsing function returns None unless a message is\n directed at the Bot, based on its ID.\n \"\"\"\n output_list = slack_rtm_output\n if output_list and len(output_list) > 0:\n for output in output_list:\n if output and 'file' in output and 'upload' in output and 'channel' in output:\n if 'url_private' in output['file'] and output['upload'] == True:\n if args.verbose: print('URL: {}'.format(output['file']['url_private']))\n try:\n buffer = parse_gps(output['file']['url_private'])\n\n if (buffer):\n if args.verbose: print(buffer)\n send_message(output['channel'], buffer)\n\n except Exception as e:\n sys.stderr.write('{}\\n'.format(str(e)))\n\n return None, None\n\ndef send_message(channel_id, message):\n slack_client.api_call('chat.postMessage', channel=channel_id, text=message, username='metabot',\n icon_emoji=':robot_face:')\n\nif __name__ == \"__main__\":\n READ_WEBSOCKET_DELAY = 1 # 1 second delay between reading from firehose\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-v', dest='verbose', action='store_true',\n help='Verbosity')\n args = parser.parse_args()\n\n\n if slack_client.rtm_connect():\n print('Metabot connected and running!')\n while True:\n command, channel = parse_slack_output(slack_client.rtm_read())\n #if command and channel:\n # handle_command(command, channel)\n time.sleep(READ_WEBSOCKET_DELAY)\n else:\n print('Connection failed. Invalid Slack token or bot ID?')","sub_path":"slack-metabot.py","file_name":"slack-metabot.py","file_ext":"py","file_size_in_byte":6339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"135499036","text":"from flask import Flask,render_template,request\r\nfrom log_file.logger import Logs\r\nimport pandas as pd\r\nimport joblib\r\nimport numpy as np\r\nimport pymongo\r\nimport ssl\r\n\r\nfrom sklearn.preprocessing import StandardScaler\r\nscaler = StandardScaler()\r\ndata=pd.read_csv(\"data/incomeData.csv\")\r\ndata=data.apply(lambda x: x.str.strip() if x.dtype == \"object\" else x)\r\ndata.replace('?',np.NaN,inplace=True)\r\ncolumns_with_nan = ['workclass', 'occupation', 'native-country']\r\nfor col in columns_with_nan:\r\n data[col].fillna(data[col].mode()[0], inplace=True)\r\nfrom sklearn.preprocessing import LabelEncoder\r\nencoder = LabelEncoder()\r\nfor col in data.columns:\r\n if data[col].dtypes == 'object':\r\n data[col] = encoder.fit_transform(data[col])\r\nX=data.drop(['Income'],axis=1)\r\ny=data['Income']\r\nX = X.drop(['workclass', 'education', 'race', 'sex',\r\n 'capital-loss', 'native-country'], axis=1)\r\nX_scaled=scaler.fit_transform(X)\r\n\r\nlog = Logs(\"log_file/log_data.log\")\r\nlog.addLog(\"INFO\", \"Execution started Successfully !\")\r\n\r\n# configuring logging method\r\npickle_in = open(\"model_rf.pkl\",\"rb\")\r\nmodel=joblib.load(pickle_in)\r\n\r\napp = Flask(__name__)\r\n# route for main page\r\n@app.route('/')\r\ndef index():\r\n return render_template(\"index.html\")\r\n\r\ndef prediction1(age, fnlwgt, education_num, marital_status, occupation, relationship, capital_gain, hours_per_week):\r\n dct_marital_status={'Never-married':4,'Married-civ-spouse':2 ,'Divorced':0, 'Married-spouse-absent':3,\r\n 'Separated':5 ,'Married-AF-spouse':1, 'Widowed':6}\r\n dct_occupation ={'Adm-clerical':0 ,'Exec-managerial':3 ,'Handlers-cleaners':5 ,'Prof-specialty':9,\r\n 'Other-service':7, 'Sales':11, 'Craft-repair':2, 'Transport-moving':13,\r\n 'Farming-fishing':4, 'Machine-op-inspct':6 ,'Tech-support':12 ,'Protective-serv':10,\r\n 'Armed-Forces':1, 'Priv-house-serv':8}\r\n dct_relationship= {'Not-in-family':1 ,'Husband':0, 'Wife':5 ,'Own-child':3 ,'Unmarried':4, 'Other-relative':2}\r\n \r\n #cols=['age', 'fnlwgt', 'education_num','marital_status', 'occupation','relationship','capital_gain', 'hours_per_week']\r\n X=[age,fnlwgt,education_num,dct_marital_status[marital_status],dct_occupation[occupation],dct_relationship[relationship],capital_gain,hours_per_week]\r\n final_features = [np.array(X)]\r\n print(final_features)\r\n print(scaler.transform(final_features))\r\n result = model.predict(scaler.transform(final_features))\r\n return result\r\n \r\n\r\n# route for prediction \r\n@app.route('/predict', methods=['POST','GET'])\r\ndef predict():\r\n if request.method == \"POST\":\r\n age = request.form.get(\"age\")\r\n fnlwgt = request.form.get(\"fnlwgt\")\r\n education_num = request.form.get(\"education_num\") \r\n marital_status =request.form.get(\"marital_status\")\r\n occupation =request.form.get(\"occupation\")\r\n relationship =request.form.get(\"relationship\")\r\n capital_gain =request.form.get(\"capital_gain\")\r\n hours_per_week = request.form.get(\"hours_per_week\")\r\n log.addLog(\"INFO\", \"Successfully retrieved information from the user... !\")\r\n input1=[age, fnlwgt, education_num, marital_status, occupation, relationship, capital_gain, hours_per_week]\r\n print(input1)\r\n print(model)\r\n result = prediction1(age, fnlwgt, education_num, marital_status, occupation, relationship, capital_gain, hours_per_week)\r\n print(result)\r\n \r\n #Data Ingestion\r\n # database connections\r\n try:\r\n default_connection_url =\"mongodb+srv://mafia123:mafia123@cluster0.j7nj9.mongodb.net/visibility_prediction?retryWrites=true&w=majority\"\r\n client = pymongo.MongoClient(default_connection_url,ssl_cert_reqs=ssl.CERT_NONE)\r\n print(\"Database connection established.\")\r\n log.addLog(\"INFO\", \"Database connection established..! !\")\r\n except Exception as e:\r\n log.addLog(\"ERROR\", \"Error while connecting to Database :{}\".format(e))\r\n\r\n #creation of collection \r\n try:\r\n db_name = \"Income_prediction\"\r\n database = client[db_name]\r\n log.addLog(\"INFO\", \"Database Created !\")\r\n print(\"Collection Created\")\r\n collection_name = \"user_data\"\r\n collection = database[collection_name]\r\n log.addLog(\"INFO\", \"Collection Created!\")\r\n except Exception as e:\r\n log.addLog(\"ERROR\", \"Found error in DB or Collection : {}\".format(e))\r\n \r\n #insertion in collection\r\n try:\r\n info = {\r\n 'age' :age ,\r\n 'fnlwgt':fnlwgt ,\r\n 'education_num' :education_num ,\r\n 'marital_status' :marital_status,\r\n 'occupation' : occupation ,\r\n 'relationship':relationship,\r\n 'capital_gain' : capital_gain ,\r\n 'hours_per_week' : hours_per_week \r\n }\r\n collection.insert_one(info)\r\n log.addLog(\"INFO\", \"Data Inserted in the Collection Successfully !!\")\r\n client.close()\r\n log.addLog(\"INFO\", \"Database connection closed Successfully !!\")\r\n except Exception as e:\r\n log.addLog(\"ERROR\", \"found error in info json :{}\".format(e))\r\n return render_template('index.html')\r\n log.addLog(\"INFO\", \"Prediction done Successfully !\")\r\n\r\n if result == 1:\r\n output = \"Income is more than 50K\"\r\n elif result == 0:\r\n output = \"Income is less than 50K\"\r\n \r\n return render_template('index.html', prediction_text='{}'.format(output))\r\n\r\n else:\r\n log.addLog(\"INFO\", \"Return from the Predict Route!!\")\r\n return render_template('index.html')\r\n \r\n\r\n@app.route(\"/database\")\r\ndef database():\r\n \r\n heading = ('age', 'fnlwgt', 'education_num','marital_status', 'occupation','relationship','capital_gain', 'hours_per_week')\r\n all_data = \"\"\r\n try:\r\n default_connection_url =\"mongodb+srv://mafia123:mafia123@cluster0.j7nj9.mongodb.net/visibility_prediction?retryWrites=true&w=majority\"\r\n client = pymongo.MongoClient(default_connection_url,ssl_cert_reqs=ssl.CERT_NONE)\r\n log.addLog(\"INFO\", \"Database connection established..! !\")\r\n database = client[\"Income_prediction\"]\r\n collection = database[\"user_data\"]\r\n all_data = collection.find()\r\n log.addLog(\"INFO\", \"Retriviwed all data from Collection user_data !\")\r\n ele=[]\r\n for data in collection.find():\r\n ele.append([data['age'],data['fnlwgt'],data['education_num'],data['marital_status'],data['occupation'],data['relationship'],data['capital_gain'],data['hours_per_week']])\r\n client.close()\r\n log.addLog(\"INFO\", \"Closing the Connection !\")\r\n\r\n except Exception as error:\r\n print(\"Error occured while fetching all data from Database !\", error)\r\n log.addLog(\"ERROR\", \"Error occured while fetching all data from Database : {} !\" .format(error))\r\n\r\n\r\n\r\n log.addLog(\"INFO\", \"Rendering tamplate with all Data !\")\r\n return render_template('database.html', heading = heading, data = ele)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n #app.run(host='0.0.0.0',port=8080)\r\n app.run(debug=True)\r\n","sub_path":"Income Prediction/app1.py","file_name":"app1.py","file_ext":"py","file_size_in_byte":7298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"429210037","text":"import pandas as pd\nimport numpy as np\nfrom windrose import WindroseAxes\nfrom matplotlib import pyplot as plt\nimport matplotlib\nimport matplotlib.cm as cm\nfrom matplotlib import dates\nimport matplotlib.dates as mdates\nimport matplotlib.patches as mpatches\n#from matplotlib.backends.backend_pdf import PdfPages\n\nfont = {'size': 22}\nmatplotlib.rc('font', **font)\n\nplt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签\nplt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号\n# plt.rcParams['figure.figsize'] = 30,20\n\n\ndef paint_windrose(data, title):\n '''\n 绘制风玫瑰图\n '''\n for i in range(3):\n WS_Avg = data['WS_Avg' + str(i + 1)] # 风速\n WD_SD = data['WD_SD' + str(i + 1)] # 风向\n\n ax1 = WindroseAxes.from_ax()\n ax1.bar(WD_SD, WS_Avg, normed=True, opening=1.0, edgecolor='white')\n title_last = title + \"WS_Avg\" + str(i + 1) + \"_and_WD_SD\" + str(i + 1)\n ax1.set_title(title_last)\n ax1.set_legend()\n # ax1.show()\n new_title = title_last + '_fig1.png'\n new_title = '-'.join(new_title.split())\n new_title = new_title.replace(\":\", '-')\n ax1.figure.savefig(new_title)\n\n '''\n ax2 = WindroseAxes.from_ax()\n ax2.contourf(WD_SD, WS_Avg, bins=np.arange(0, 8, 1), cmap=cm.hot)\n #ax2.show()\n '''\n '''\n ax2.set_title(title_last)\n ax2.set_legend()\n ax2.figure.savefig(title_last+'_fig2.png')\n \n '''\n\n '''\n ax1.bar(WD_SD, WS_Avg, normed=True, nsector=16)\n table = ax1._info['table']\n\n direction = ax1._info['dir']\n wd_freq = np.sum(table, axis=0)\n plt.bar(np.arange(16),wd_freq, align='center')\n xlabels = ('N','','N-E','','E','','S-E','','S','','S-O','','O','','N-O','')\n xticks=np.arange(16)\n plt.gca().set_xticks(xticks)\n plt.draw()\n plt.gca().set_xticklabels(xlabels)\n plt.draw()\n '''\ndef paint_windrose_floor3(data, title, save=True):\n '''\n 绘制风玫瑰图\n '''\n WS_Avg = data['WS_Avg3'] # 风速\n WD_SD = data['WD_SD3'] # 风向\n\n ax1 = WindroseAxes.from_ax()\n ax1.bar(WD_SD, WS_Avg, normed=True, opening=1.0, edgecolor='white')\n title_last = title + \"WS_Avg3\" + \"_and_WD_SD3\"\n ax1.set_title(title_last)\n ax1.set_legend()\n if save is False:\n pass\n else:\n new_title = title_last + '_fig1.png'\n new_title = '-'.join(new_title.split())\n new_title = new_title.replace(\":\", '-')\n ax1.figure.savefig(new_title)\n\ndef speed_direction_plot(data, title, interval=None, save=True):\n '''\n paint wind speed and direction with time\n '''\n # for i in range(3):\n # plt.close()\n # WS_Avg = data['WS_Avg' + str(i + 1)] # 风速\n # WD_SD = data['WD_SD' + str(i + 1)] # 风向\n\n # only paint floor 3\n WS_Avg = data['WS_Avg3'] # 风速\n WD_SD = data['WD_SD3'] # 风向\n TIMESTAMP = pd.to_datetime(data['TIMESTAMP']) # time\n\n fig, ax1 = plt.subplots()\n hfmt = dates.DateFormatter('%m/%d %H:%M')\n ax1.plot(TIMESTAMP, WS_Avg, 'b-')\n ax1.set_xlabel('time (s)')\n # Make the y-axis label, ticks and tick labels match the line color.\n ax1.set_ylabel('wind speed', color='b')\n ax1.tick_params('y', colors='b')\n ax1.xaxis.set_major_formatter(hfmt)\n if interval != None:\n ax1.xaxis.set_major_locator(mdates.HourLocator(interval=interval))\n\n ax2 = ax1.twinx()\n ax2.plot(TIMESTAMP, WD_SD, 'r.')\n ax2.set_ylabel('wind direction', color='r')\n ax2.tick_params('y', colors='r')\n ax2.set_ylim(0, 360)\n\n legend_speed = mpatches.Patch(color='b', label='wind_speed')\n legend_direction = mpatches.Patch(color='r', label='wind_direction')\n plt.legend(handles=[legend_speed, legend_direction], bbox_to_anchor=(\n 1, 1), bbox_transform=plt.gcf().transFigure, fontsize='x-small')\n new_title = title + \"-WS_Avg3\" + \"-and-WD_SD3\"\n plt.title(new_title)\n fig.autofmt_xdate()\n fig.tight_layout()\n \n if save is False:\n fig.set_size_inches(13, 9, forward=True)\n plt.show()\n else:\n fig.set_size_inches(30, 14, forward=True)\n new_title = new_title.replace(':', '-')\n new_filename = new_title + 'wind' + '.png'\n plt.savefig(new_filename, bbox_inches='tight')\n\n\ndef paint_temperature_humidity(data, title, interval=None, save=True):\n '''\n paint temperature and humidity relationship with time\n '''\n TIMESTAMP = pd.to_datetime(data['TIMESTAMP'])\n Ta_2m_Avg = data.Ta_2m_Avg\n Ta_5m_Avg = data.Ta_5m_Avg\n Ta_10m_Avg = data.Ta_10m_Avg\n RH_2m_Avg = data.RH_2m_Avg\n RH_5m_Avg = data.RH_5m_Avg\n RH_10m_Avg = data.RH_10m_Avg\n e_2m_Avg = data.e_2m_Avg\n e_5m_Avg = data.e_5m_Avg\n e_10m_Avg = data.e_10m_Avg\n\n fig, (ax1, ax3) = plt.subplots(2, 1, sharex=True)\n hfmt = dates.DateFormatter('%m/%d %H:%M')\n ax3.plot(TIMESTAMP, Ta_2m_Avg, 'b',\n TIMESTAMP, Ta_5m_Avg, 'r',\n TIMESTAMP, Ta_10m_Avg, 'c',\n )\n ax3.set_ylabel('temperature/℃', color='b')\n ax3.tick_params('y', colors='b')\n ax3.xaxis.set_major_formatter(hfmt)\n\n ax2 = ax3.twinx()\n ax2.plot(TIMESTAMP, RH_2m_Avg, 'm-',\n TIMESTAMP, RH_5m_Avg, 'g-',\n TIMESTAMP, RH_10m_Avg, 'y-',\n )\n ax2.set_ylabel('humidity/%', color='m')\n ax2.tick_params('y', colors='m')\n ax2.set_ylim(0, 100)\n\n ax1.plot(TIMESTAMP, e_2m_Avg, 'b',\n TIMESTAMP, e_5m_Avg, 'r',\n TIMESTAMP, e_10m_Avg, 'c',\n )\n ax1.set_ylabel('air pressure/KPa')\n\n label_b = mpatches.Patch(color='b', label='Ta_2m_Avg')\n label_r = mpatches.Patch(color='r', label='Ta_5m_Avg')\n label_c = mpatches.Patch(color='c', label='Ta_10m_Avg')\n label_m = mpatches.Patch(color='m', label='RH_2m_Avg')\n label_g = mpatches.Patch(color='g', label='RH_5m_Avg')\n label_y = mpatches.Patch(color='y', label='RH_10m_Avg')\n label_b_1 = mpatches.Patch(color='b', label='e_2m_Avg')\n label_r_1 = mpatches.Patch(color='r', label='e_5m_Avg')\n label_c_1 = mpatches.Patch(color='c', label='e_10m_Avg')\n plt.legend(handles=[label_b, label_r, label_c, label_m, label_g, label_y, label_b_1, label_r_1, label_c_1], bbox_to_anchor=(1, 1),\n bbox_transform=plt.gcf().transFigure, fontsize='x-small')\n\n fig.autofmt_xdate()\n fig.tight_layout()\n ax3.set_xlabel('Time')\n if interval != None:\n ax3.xaxis.set_major_locator(mdates.HourLocator(interval=interval))\n plt.suptitle(\n title + \"-difference of change of height's temperature,humidity,air pressure\")\n\n if save is False:\n fig.set_size_inches(13, 9, forward=True)\n plt.show()\n else:\n new_filename = title + 'THP' + '.png'\n fig.set_size_inches(30, 14, forward=True)\n plt.savefig(new_filename, bbox_inches='tight')\n\ndef paint_temperature_gradient(data, title, interval=None, save=True):\n '''\n paint temperature gradient\n '''\n TIMESTAMP = pd.to_datetime(data['TIMESTAMP'])\n Ta_2m_Avg = data.Ta_2m_Avg\n Ta_5m_Avg = data.Ta_5m_Avg\n Ta_10m_Avg = data.Ta_10m_Avg\n\n temperature_gradient = pd.DataFrame(\n columns=['TIMESTAMP', 'dt1', 'dt2', 'dt1/dx1', 'dt2/dx2', 'dt/dx'])\n temperature_gradient.TIMESTAMP = TIMESTAMP\n temperature_gradient.dt1 = Ta_5m_Avg - Ta_2m_Avg\n temperature_gradient.dt2 = Ta_10m_Avg - Ta_5m_Avg\n temperature_gradient['dt1/dx1'] = temperature_gradient.dt1 / 3\n temperature_gradient['dt2/dx2'] = temperature_gradient.dt2 / 5\n temperature_gradient['dt/dx'] = (temperature_gradient['dt1/dx1'] +\n temperature_gradient['dt2/dx2']) / 2\n fig0, ax0 = plt.subplots()\n hfmt = dates.DateFormatter('%m/%d %H:%M')\n ax0.xaxis.set_major_formatter(hfmt)\n ax0.plot(temperature_gradient.TIMESTAMP,\n temperature_gradient['dt/dx'], label='temperature gradient')\n ax0.plot(temperature_gradient.TIMESTAMP, [\n 0 for i in range(len(TIMESTAMP))], label='zero')\n if interval != None:\n ax0.xaxis.set_major_locator(mdates.HourLocator(interval=interval))\n plt.title(title + 'The temperature gradient in ')\n plt.xlabel('Time')\n plt.ylabel('temperature gradient')\n handles, labels = ax0.get_legend_handles_labels()\n ax0.legend(handles, labels, bbox_to_anchor=(1, 1),\n bbox_transform=plt.gcf().transFigure, fontsize='x-small')\n fig0.autofmt_xdate()\n\n if save is False:\n fig0.set_size_inches(13, 9, forward=True)\n plt.show()\n else:\n fig0.set_size_inches(30, 14, forward=True)\n new_filename = title + 't_grad' + '.png'\n plt.savefig(new_filename, bbox_inches='tight')\n plt.close()","sub_path":"pyCR3000/paint.py","file_name":"paint.py","file_ext":"py","file_size_in_byte":8778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"422992520","text":"import matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom sklearn import decomposition, manifold\nimport numpy as np\nimport sys\nimport csv\nimport json\n\n\nbaseline_data = []\nwith open('baseline.csv', 'r') as baseline_csv:\n reader = csv.reader(baseline_csv)\n for row in reader:\n baseline_data.append([item for sublist in row for item in json.loads(sublist)])\n\nconcentration_data = []\nwith open('concentration.csv', 'r') as concentration_csv:\n reader = csv.reader(concentration_csv)\n for row in reader:\n concentration_data.append([item for sublist in row for item in json.loads(sublist)])\n\n# baseline = np.array(baseline_data).T\n# concentration = np.array(concentration_data).T\n\n# baseline = np.flip(baseline, axis=0)\n# concentration = np.flip(concentration, axis=0)\n#\n# comparison = np.append(baseline[:, 5000:6000], concentration[:, 5000:6000], axis=0)\n\n# plt.set_cmap('magma') #https://matplotlib.org/examples/color/colormaps_reference.html\n\nbaseline = np.array(baseline_data)\nconcentration = np.array(concentration_data)\nX = np.append(baseline, concentration, axis=0)\ny = np.append(np.zeros(len(baseline)), np.ones(len(concentration)))\n\n\n\n# pca = decomposition.PCA(n_components=3, whiten=True, svd_solver='auto')\n# pca.fit(X)\n# X = pca.transform(X)\nX = manifold.TSNE(n_components=3, init='pca').fit_transform(X)\n\nfig = plt.figure(1, figsize=(4, 3))\nplt.clf()\nax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134)\nplt.cla()\n\nfor name, label in [('baseline', 0), ('concentration', 1)]:\n ax.text3D(X[y == label, 0].mean(),\n X[y == label, 1].mean() + 1.5,\n X[y == label, 2].mean(), name,\n horizontalalignment='center',\n bbox=dict(alpha=.5, edgecolor='w', facecolor='w'))\n\nax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y, cmap=plt.cm.spectral)\n\nax.w_xaxis.set_ticklabels([])\nax.w_yaxis.set_ticklabels([])\nax.w_zaxis.set_ticklabels([])\n\nplt.show()\n\n\n\n# X = decomposition.PCA(n_components=2, whiten=False, svd_solver='auto').fit_transform(X)\n# X = manifold.TSNE(n_components=2, init='pca').fit_transform(X)\n# X = manifold.Isomap(n_neighbors=30, n_components=2).fit_transform(X)\n\n# plt.figure()\n# colors = ['navy', 'darkorange']\n# for color, i, target_name in zip(colors, [0, 1], ['baseline', 'concentration']):\n# plt.scatter(X[y == i, 0], X[y == i, 1], color=color, alpha=.8, lw=2, label=target_name)\n#\n# plt.show()\n","sub_path":"exploration.py","file_name":"exploration.py","file_ext":"py","file_size_in_byte":2409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"51554946","text":"#!/usr/bin/python3\n#\n# Copyright (c) 2020 Foundries.io\n# SPDX-License-Identifier: Apache-2.0\n#\nimport subprocess\nimport os\nimport json\nimport argparse\nimport logging\nimport shutil\nfrom math import ceil\nfrom tempfile import TemporaryDirectory\n\nfrom helpers import cmd, Progress\nfrom apps.target_apps_fetcher import TargetAppsFetcher\nfrom apps.target_apps_store import ArchiveTargetAppsStore\nfrom apps.ostree_store import ArchOSTreeTargetAppsStore, OSTreeRepo\nfrom factory_client import FactoryClient\n\nlogger = logging.getLogger(\"System Image Assembler\")\n\n\nclass WicImage:\n ComposeAppsRootDir = 'ostree/deploy/lmp/var/sota/compose-apps/'\n DockerDataRootDir = 'ostree/deploy/lmp/var/lib/docker/'\n ComposeAppsRoot = 'ostree/deploy/lmp/var/sota/compose-apps'\n ComposeAppsTree = 'ostree/deploy/lmp/var/sota/compose-apps-tree'\n InstalledTargetFile = 'ostree/deploy/lmp/var/sota/import/installed_versions'\n\n def __init__(self, wic_image_path: str, increase_bytes=None, extra_space=0.2):\n self._path = wic_image_path\n self._mnt_dir = os.path.join('/mnt', 'wic_image_p2')\n self._resized_image = False\n if increase_bytes:\n self._resize_wic_file(increase_bytes, extra_space)\n self._resized_image = True\n self.compose_apps_root = os.path.join(self._mnt_dir, self.ComposeAppsRootDir)\n self.docker_data_root = os.path.join(self._mnt_dir, self.DockerDataRootDir)\n self.compose_apps_root = os.path.join(self._mnt_dir, self.ComposeAppsRoot)\n self.compose_apps_tree = os.path.join(self._mnt_dir, self.ComposeAppsTree)\n self.installed_target_filepath = os.path.join(self._mnt_dir, self.InstalledTargetFile)\n\n def __enter__(self):\n cmd('losetup', '-P', '-f', self._path)\n out = cmd('losetup', '-a', capture=True).decode()\n for line in out.splitlines():\n if self._path in line:\n self._loop_device = line.split(':', 1)[0]\n self._wic_device = line.split(':', 1)[0] + 'p2'\n break\n else:\n raise RuntimeError('Unable to find loop device for wic image')\n\n # containers don't see changes to /dev, so we have to hack around\n # this by basically mounting a new /dev. The idea was inspired by\n # this comment:\n # https://github.com/moby/moby/issues/27886#issuecomment-257244027\n cmd('mount', '-t', 'devtmpfs', 'devtmpfs', '/dev')\n cmd('e2fsck', '-y', '-f', self._wic_device)\n\n if self._resized_image:\n cmd('resize2fs', self._wic_device)\n\n os.mkdir(self._mnt_dir)\n cmd('mount', self._wic_device, self._mnt_dir)\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n cmd('umount', self._mnt_dir)\n os.rmdir(self._mnt_dir)\n cmd('umount', '/dev')\n cmd('losetup', '-d', self._loop_device)\n\n def update_target(self, target):\n logger.info('Updating installed Target (aka `installed_versions`) for the given system image\\n')\n # make sure installed target dir path exists (e.g. wic-based installers)\n os.makedirs(os.path.dirname(self.installed_target_filepath), exist_ok=True)\n with open(self.installed_target_filepath, 'w') as installed_target_file:\n target.json['is_current'] = True\n json.dump({target.name: target.json}, installed_target_file, indent=2)\n\n def _resize_wic_file(self, increase_bytes: int, extra_space=0.2):\n bs = 1024\n increase_k = ceil((increase_bytes + increase_bytes * extra_space) / bs) + 1\n wic_k = ceil(os.stat(self._path).st_size / bs)\n logger.info('Extending the wic image; adding: {} bytes, asked {}'.format(increase_k * bs, increase_bytes))\n cmd('dd', 'if=/dev/zero', 'bs=' + str(bs), 'of=' + self._path,\n 'conv=notrunc', 'oflag=append', 'count=' + str(increase_k),\n 'seek=' + str(wic_k))\n\n fdsik_out = str(subprocess.check_output(['fdisk', '-l', self._path]))\n if fdsik_out.find('using GPT') != -1:\n subprocess.check_call(['sgdisk', '-e', self._path])\n subprocess.check_call(['parted', self._path, 'resizepart', '2', '100%'])\n\n\ndef copy_container_images_to_wic(target: FactoryClient.Target, factory: str, ostree_repo_archive_dir: str,\n app_repo_dir, app_fetch_dir: str, wic_image: str, token: str, apps_shortlist: list,\n progress: Progress):\n\n p = Progress(2, progress)\n target_app_store = ArchOSTreeTargetAppsStore(factory, ostree_repo_archive_dir, app_repo_dir)\n target.shortlist = apps_shortlist\n if not target_app_store.exist(target):\n logger.info('Compose Apps haven\\'t been found, fetching them...')\n apps_fetcher = TargetAppsFetcher(token, app_fetch_dir)\n if target_app_store.exist_branch(target):\n target_app_store.checkout(target, apps_fetcher.target_dir(target.name))\n apps_fetcher.fetch_target(target, force=True)\n target.apps_uri = target_app_store.store(target, apps_fetcher.target_dir(target.name))\n p.tick()\n\n with TemporaryDirectory(dir=os.getenv('HOME', '/root')) as tmp_tree_dir:\n # TODO: make use of the commit size generation functionality to determine a size to extend a wic image for\n logger.info('Building an ostree repo for the given Target...')\n os.makedirs(tmp_tree_dir, exist_ok=True)\n tmp_tree_repo = OSTreeRepo(tmp_tree_dir, 'bare', create=True)\n p.tick()\n target_app_store.copy(target, tmp_tree_repo)\n p.tick()\n\n with WicImage(wic_image, tmp_tree_repo.size_in_kbs() * 1024) as wic_image:\n logger.info('Removing previously preloaded Apps if any...')\n\n shutil.rmtree(wic_image.docker_data_root, ignore_errors=True)\n shutil.rmtree(wic_image.compose_apps_root, ignore_errors=True)\n shutil.rmtree(wic_image.compose_apps_tree, ignore_errors=True)\n p.tick()\n target_app_store.copy_and_checkout(target, wic_image.compose_apps_tree,\n wic_image.compose_apps_root, wic_image.docker_data_root)\n wic_image.update_target(target)\n p.tick()\n\n\ndef copy_container_images_from_archive_to_wic(target: FactoryClient.Target, app_image_dir: str, app_preload_dir: str,\n wic_image: str, token: str, apps_shortlist: list, progress: Progress):\n\n p = Progress(2, progress)\n target_app_store = ArchiveTargetAppsStore(app_image_dir)\n target.shortlist = apps_shortlist\n if not target_app_store.exist(target):\n logger.info('Container images have not been found, trying to obtain them...')\n apps_fetcher = TargetAppsFetcher(token, app_preload_dir)\n apps_fetcher.fetch_target_apps(target, apps_shortlist)\n apps_fetcher.fetch_apps_images()\n target_app_store.store(target, apps_fetcher.target_dir(target.name))\n p.tick()\n\n # in kilobytes\n image_data_size = target_app_store.images_size(target)\n with WicImage(wic_image, image_data_size * 1024) as wic_image:\n target_app_store.copy(target, wic_image.docker_data_root, wic_image.compose_apps_root)\n wic_image.update_target(target)\n p.tick()\n\n\ndef archive_and_output_assembled_wic(wic_image: str, out_image_dir: str):\n logger.info('Gzip and move resultant WIC image to the specified destination folder: {}'.format(out_image_dir))\n os.makedirs(out_image_dir, exist_ok=True)\n subprocess.check_call(['gzip', wic_image])\n subprocess.check_call(['mv', '-f', wic_image + '.gz', out_image_dir])\n\n\ndef get_args():\n parser = argparse.ArgumentParser('''Add container images to a system image''')\n\n parser.add_argument('-f', '--factory', help='Factory')\n parser.add_argument('-v', '--target-version', help='Target(s) version, aka build number')\n parser.add_argument('-t', '--token', help='A token')\n parser.add_argument('-ar', '--ostree-repo-archive-dir',\n help='Path to a dir that contains an ostree repo archive with apps')\n parser.add_argument('-o', '--out-image-dir', help='A path to directory to put a resultant image to')\n parser.add_argument('-rd', '--repo-dir', help='Directory to extract an apps ostree repo to')\n parser.add_argument('-d', '--fetch-dir', help='Directory to fetch/preload/output apps and images')\n parser.add_argument('-T', '--targets', help='A coma separated list of Targets to assemble system image for')\n parser.add_argument('-s', '--app-shortlist', help='A coma separated list of Target Apps'\n ' to include into a system image', default=None)\n parser.add_argument('-u', '--use-ostree', help='Enables an ostree repo usage for compose apps', default=None)\n args = parser.parse_args()\n\n if args.targets:\n args.targets = args.targets.split(',')\n\n if args.app_shortlist:\n args.app_shortlist = args.app_shortlist.split(',')\n\n return args\n\n\nif __name__ == '__main__':\n exit_code = 0\n\n try:\n logging.basicConfig(format='%(asctime)s %(levelname)s: %(module)s: %(message)s', level=logging.INFO)\n args = get_args()\n\n factory_client = FactoryClient(args.factory, args.token)\n if args.targets:\n logger.info('Getting Targets for {}'.format(args.targets))\n targets = factory_client.get_targets(args.targets)\n err_msg = 'No Targets found; Factory: {}, input Target list: {}'.format(args.factory, args.targets)\n else:\n logger.info('Getting Targets of version {}'.format(args.target_version))\n targets = factory_client.get_targets_by_version(args.target_version)\n err_msg = 'No Targets found; Factory: {}, Version/Build Number: {}'.format(args.factory, args.target_version)\n\n found_targets_number = len(targets)\n if found_targets_number == 0:\n logger.warning(err_msg)\n exit(1)\n\n p = Progress(len(targets))\n logger.info('Found {} Targets to assemble image for'.format(found_targets_number))\n for target in targets:\n logger.info('Assembling image for {}, shortlist: {}'.format(target.name, args.app_shortlist))\n subprog = Progress(3, p)\n image_file_path = factory_client.get_target_system_image(target, args.out_image_dir, subprog)\n\n if args.use_ostree and args.use_ostree == '1':\n copy_container_images_to_wic(target, args.factory, args.ostree_repo_archive_dir, args.repo_dir,\n args.fetch_dir, image_file_path, args.token, args.app_shortlist, subprog)\n else:\n copy_container_images_from_archive_to_wic(target, args.ostree_repo_archive_dir, args.fetch_dir,\n image_file_path, args.token, args.app_shortlist, subprog)\n\n archive_and_output_assembled_wic(image_file_path, args.out_image_dir)\n subprog.tick(complete=True)\n\n except Exception as exc:\n logger.error('Failed to assemble a system image: {}'.format(exc))\n exit_code = 1\n\n exit(exit_code)\n","sub_path":"assemble.py","file_name":"assemble.py","file_ext":"py","file_size_in_byte":11207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"95633961","text":"from django.shortcuts import render\nfrom rest_framework import viewsets, generics\nfrom .models import Room\nfrom reservation.models import Reservation\nfrom .serializers import RoomSerializer\nfrom rest_framework import permissions\nimport datetime\n# Create your views here.\n\n\nclass RoomViewSet(viewsets.ModelViewSet):\n queryset = Room.objects.all()\n serializer_class = RoomSerializer\n permission_classes = (permissions.IsAdminUser, )\n\nclass AvailableDatesView(generics.ListAPIView):\n serializer_class = RoomSerializer\n queryset = Room.objects.all()\n\n def get_queryset(self):\n start_date = self.request.query_params.get('from', datetime.date.today()+datetime.timedelta(days=1))\n end_date = self.request.query_params.get('to', datetime.date.today()+datetime.timedelta(days=2))\n if type(start_date) == str:\n start_date = start_date.split('-')\n start_date = datetime.date(year=int(start_date[0]), month=int(start_date[1]), day=int(start_date[2]))\n if type(end_date) == str:\n end_date = end_date.split('-')\n end_date = datetime.date(year=int(end_date[0]), month=int(end_date[1]), day=int(end_date[2]))\n\n unavaliblerooms = []\n for reservation in Reservation.objects.all():\n if reservation.start_date <= end_date:\n if reservation.start_date >= start_date:\n unavaliblerooms.append(reservation.res_room.id)\n if reservation.start_date >= start_date:\n if reservation.start_date <= end_date:\n unavaliblerooms.append(reservation.res_room.id)\n queryset = Room.objects.all().filter().exclude(id__in=unavaliblerooms)\n\n return queryset\n","sub_path":"Hotel/room/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"501858896","text":"import setuptools\n\nNAME = 'tf2-trainer'\nVERSION = '1.2.1'\nAUTHOR = 'Bastian Schoettner'\nEMAIL = 'bastian_schoettner@web.de'\nURL = 'https://github.com/schoettner/tf2-resnet'\n\n# add packages that are missing on the ai-platform training vm\nREQUIRED_PACKAGES = [\n 'pillow', # required for the food 101 dataset\n 'tensorflow_datasets>=2.1.0',\n]\n\nif __name__ == '__main__':\n setuptools.setup(name=NAME,\n version=VERSION,\n author=AUTHOR,\n author_email=EMAIL,\n url=URL,\n install_requires=REQUIRED_PACKAGES,\n packages=setuptools.find_packages(),\n include_package_data=True,\n python_requires='>=3.6'\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"573524810","text":"#!/usr/bin/env python\n#Use lsc() to see the available tools in Scapy\n\nimport scapy.all as scapy\n\ndef scan(ip):\n\t#Below wants more information about the request\n\tarp_request = scapy.ARP()\n\tarp_request.pdst=ip # Will be put in where the IPs are\n\tprint(arp_request.summary())\n\tscapy.ls(scapy.ARP())\n\n#This is the gateway IP found using route -n\nscan(\"10.128.102.0/24\")\n# ^ Changes it to a range \n","sub_path":"09_NetworkingExtended/Practice/netscan1.py","file_name":"netscan1.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"13282116","text":"'''publish batches of HITs on MTurk'''\nimport time\nimport json\nimport configparser\nimport os\n\nimport aws_config\nfrom slurk_link_generator import insert_names_and_tokens\n\nRESULTS = []\n\nSLIDES = ['https://raw.githubusercontent.com/luise-strietzel/slurk-bots/master/dito/instruction_slides/dito_instr_001.jpg',\n 'https://raw.githubusercontent.com/luise-strietzel/slurk-bots/master/dito/instruction_slides/dito_instr_002.jpg',\n 'https://raw.githubusercontent.com/luise-strietzel/slurk-bots/master/dito/instruction_slides/dito_instr_003.jpg',\n 'https://raw.githubusercontent.com/luise-strietzel/slurk-bots/master/dito/instruction_slides/dito_instr_004.jpg',\n 'https://raw.githubusercontent.com/luise-strietzel/slurk-bots/master/dito/instruction_slides/dito_instr_005.jpg',\n 'https://raw.githubusercontent.com/luise-strietzel/slurk-bots/master/dito/instruction_slides/dito_instr_006.jpg',\n 'https://raw.githubusercontent.com/luise-strietzel/slurk-bots/master/dito/instruction_slides/dito_instr_007.jpg']\n\n\nHTML = open('./dito.html', 'r').read()\nQUESTION_XML = \"\"\"\n \n \n 650\n \"\"\"\nQUESTION = QUESTION_XML.format(HTML)\nQ_ATTR = {\n # Amount of assignments per HIT\n 'MaxAssignments': 1,\n # How long the task is available on MTurk (1 day)\n 'LifetimeInSeconds': 60*60*1,\n # How much time Workers have in order to complete each task (10 minutes)\n 'AssignmentDurationInSeconds': 60*10,\n # the HIT is automatically approved after this number of minutes (0.5 day)\n 'AutoApprovalDelayInSeconds': 60*720,\n # The reward we offer Workers for each task\n 'Reward': '0.10',\n 'Title': 'Play our Chat Game for 2 workers and earn up to 0.85$ in 3 minutes!',\n 'Keywords': 'dialogue, game',\n 'Description': 'You and your partner need to discuss and reason,\\\n togther. It is important in this game that both,\\\n of you must reach a common agreement.'\n}\n\ndef publish(number_of_hits):\n '''publish HITs with creates URLs in predefined HTML template'''\n link = insert_names_and_tokens(number_of_hits)\n for login_url in link:\n create(login_url)\n\ndef create(login_url):\n '''defining HITs' template for MTurk'''\n print(login_url)\n question = QUESTION.replace('${Link}', login_url).\\\n replace('${Image1}', SLIDES[0]).\\\n replace('${Image2}', SLIDES[1]).\\\n replace('${Image3}', SLIDES[2]).\\\n replace('${Image4}', SLIDES[3]).\\\n replace('${Image5}', SLIDES[4]).\\\n replace('${Image6}', SLIDES[5]).\\\n replace('${Image7}', SLIDES[6]).\\\n replace('${Image8}', SLIDES[7])\n #print(question)\n mturk_connector = aws_config.ConnectToMTurk()\n #mturk_connector.create_command_qualification()\n mturk = mturk_connector.mturk\n\n new_hit = mturk.create_hit(\n **Q_ATTR,\n Question=question,\n QualificationRequirements=[\n #{\n # 'QualificationTypeId' : '3ETJLUMS0DM8X13DGYGLAJ6V7SNU3X',\n # 'Comparator' : 'NotIn',\n # 'IntegerValues' :\n # [\n # 6, 7, 8, 9, 10\n # ],\n # 'ActionsGuarded' : 'PreviewAndAccept'\n #},\n {\n 'QualificationTypeId' : '00000000000000000071',\n 'Comparator' : 'In',\n 'LocaleValues' : [\n {'Country':'GB'}, {'Country':'US'},\n {'Country':'AU'}, {'Country':'CA'},\n {'Country':'IE'}, {'Country':'DE'}\n ],\n 'ActionsGuarded': 'PreviewAndAccept'\n },\n {\n 'QualificationTypeId' : '00000000000000000040',\n 'Comparator' : 'GreaterThanOrEqualTo',\n 'IntegerValues' : [\n 2000\n ],\n 'ActionsGuarded': 'PreviewAndAccept'\n }\n #{\n # 'QualificationTypeId': '3X8OU3XHWD1ZRF1SJZ3XJDGXPEXDUV',\n # 'Comparator': 'EqualTo',\n # 'IntegerValues': [100]\n #}\n ]\n )\n\n RESULTS.append({\n 'link': login_url,\n 'hit_id': new_hit['HIT']['HITId']\n })\n\n print('A new HIT has been created. You can preview it here:')\n print('https://worker.mturk.com/mturk/preview?groupId=' + new_hit['HIT']['HITGroupId'])\n print('HITID = ' + new_hit['HIT']['HITId'] + ' (Use to Get Results)')\n\nif __name__ == \"__main__\":\n CONFIG = configparser.ConfigParser()\n CONFIG.read('config.ini')\n SESSION = CONFIG['session']['name']\n HITS = CONFIG['session']['hits']\n\n publish(HITS)\n\n if not os.path.isdir('./published/' + SESSION):\n os.mkdir('./published/' + SESSION)\n\n MOMENT = time.strftime(\"%Y-%b-%d__%H_%M_%S\", time.localtime())\n with open('./published/' + SESSION + '/data_'+ MOMENT +'.json', 'w') as outfile:\n json.dump(RESULTS, outfile)\n","sub_path":"dito/amt_connector/publish_hits.py","file_name":"publish_hits.py","file_ext":"py","file_size_in_byte":5308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"234325640","text":"\n\nclass MyConfig:\n\n\n def go(self,appPath,commonLib,templatesLib,theXml):\n self.commonLib = commonLib\n self.templatesLib = templatesLib\n \n print ('lib.MyConfig.go')\n \n \n # html = self.writeConfigTabs(theXml.find('configTabs'))\n# html = self.getVideoSettings(theXml.find('video_folders'))\n# return html\n \n\n# \n# def getVideoSettings(self,xml):\n# wrapper = ET.Element('div')\n# \n# it = xml.getiterator('folder')\n# for folder in it:\n# profileLabel = folder.attrib['profile']\n# profilePath = folder.text\n# n = str(it.index(folder))\n# \n# profile = ET.SubElement(wrapper, \"div\")\n#\n# label = ET.SubElement(profile, \"label\")\n# label.attrib['for'] = 'vid_'+n\n# label.text = profileLabel\n#\n# input = ET.SubElement(profile, \"input\")\n# input.attrib['id'] = 'vid_'+n\n# input.attrib['type'] = 'text'\n# input.attrib['value'] = profilePath\n# \n# button = ET.SubElement(profile, \"button\")\n# button.text = 'remove'\n#\n# return ET.tostring(wrapper) \n# \n# \n# \n# def writeConfigTabs(self,xml):\n# wrapper = ET.Element('div')\n# wrapper.attrib['id'] = 'config_tabs_wrapper'\n# \n# it = xml.getiterator('tab')\n# for tab in it:\n# profileLabel = tab.attrib['label']\n# profile = tab.attrib['profile']\n\n\n\n","sub_path":"lib/myconfig.py","file_name":"myconfig.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"641586866","text":"import sys\nsys.stdin = open('줄세우기_input.txt')\n\nN = int(input())\norder = [1] # 1은 이미 넣어놈\n\norder_num = list(map(int, list(input().split())))\n\n# insert를 활용하자!\n# order의 idx + 1 은 학생의 번호이다.\n# 최종적으로 어떻게 줄을 섰는지 학생의 번호로 출력\n# idx + 1 번째 학생이 뽑은 번호표는 order_num[idx] 이다.\n# insert로 넣고 뒤집으면 끝 !\n\n\nfor i in range(1, len(order_num)):\n order.insert(order_num[i], i+1)\nfor num in order[::-1]:\n print(num, end=\" \")\nprint()","sub_path":"0226알고리즘/줄세우기.py","file_name":"줄세우기.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"149553972","text":"import os\nimport pandas as pd\n\nfrom flask import Flask, request, abort, json, jsonify, render_template\nfrom werkzeug.exceptions import HTTPException\n\nfrom backend.ML.PolyReg import get_trend_pred\nfrom backend.ML.RNN import RNN\n\nfrom bokeh.client import pull_session\nfrom bokeh.embed import server_session\n\ntemplate_dir = os.path.abspath('frontend/templates')\nstatic_dir = os.path.abspath('frontend/static')\n\n\ndef create_app():\n app = Flask(__name__,\n template_folder=template_dir,\n static_folder=static_dir)\n\n @app.route('/codes')\n def get_country_names_codes():\n \"\"\"\n Loads a file to be served in JS in the frontend.\n\n Contains Access-Control-Allow-Origin, because otherwise\n requests are blocked by the frontend.\n\n :return: JSON\n \"\"\"\n\n try:\n df = pd.read_csv('backend/datasets/countryCodesNames.txt')\n except Exception as e:\n abort(404) # not found\n\n try:\n records = json.loads(df.to_json(orient='records'))\n response = {\n 'results': records\n }\n\n response = jsonify(response)\n response.headers.add('Access-Control-Allow-Origin', '*')\n except Exception as e:\n abort(422) # unprocessable entity\n\n return response\n\n @app.route('/survey', methods=['POST'])\n def post_survey():\n \"\"\"\n Captures user's request for a prediction with a date,\n a number of days to look forward\n and a country code.\n\n Returns a predicted number of new COVID-19 cases into the future,\n and its trend direction.\n\n :return: application/json\n \"\"\"\n\n response_data = {}\n\n if len(request.form) == 0:\n abort(400) # bad request\n\n data = request.form.to_dict()\n data['look_forward_days'] = int(data['look_forward_days'])\n\n try:\n rnn = RNN(country_code=data['country_region_code'],\n look_forward=data['look_forward_days'])\n\n requested_day = data['requested_date']\n prediction_info, samples = rnn.predict(requested_day)\n trend = get_trend_pred(samples, data['look_forward_days'])\n\n response_data['prediction_new_cases'] = \\\n str(prediction_info['prediction_new_cases'])\n response_data['prediction_date'] = \\\n str(prediction_info['prediction_date'])\n response_data['starting_date'] = \\\n str(prediction_info['starting_date'])\n\n response_data['country_region_code'] = data['country_region_code']\n response_data['trend'] = trend\n response_data['success'] = True\n\n except Exception as e:\n abort(422) # unprocessable entity\n\n return jsonify(response_data)\n\n @app.route('/')\n # def present():\n # return render_template(\"world.html\")\n def dkapp_page():\n session = pull_session(url=\"https://coprevent-bokeh.herokuapp.com/main\")\n script = server_session(None, session.id,\n url='https://coprevent-bokeh.herokuapp.com/main')\n return render_template(\"world.html\", script=script, template=\"Flask\")\n\n @app.errorhandler(HTTPException)\n def handle_exception(e):\n \"\"\"Return JSON instead of HTML for HTTP errors.\"\"\"\n response = e.get_response()\n\n response.data = json.dumps({\n \"code\": e.code,\n \"name\": e.name,\n \"description\": e.description,\n })\n response.content_type = \"application/json\"\n return response\n\n return app\n\n\napp = create_app()\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=8080, debug=True, threaded=False)\n","sub_path":"backend/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"354937565","text":"import pygame\r\nfrom rotatingMenu import *\r\nfrom configroutines import *\r\n\r\ndef setminutesmenu(displayWidth,displayHeight,configfile):\r\n pygame.init()\r\n pygame.display.set_caption('One Minute')\r\n somedisplay = pygame.display.set_mode((displayWidth, displayHeight))\r\n someclock = pygame.time.Clock()\r\n somemenu = RotatingMenu(x=320, y=240, radius=220, arc=(1.8*pi), defaultAngle=pi/2.0, wrap=False)\r\n for kounter in range(1,11):\r\n somemenu.addItem(MenuItem(str(kounter)))\r\n current_meditation_time=int(get_config(\"meditation_time\",configfile))\r\n somemenu.selectItem(current_meditation_time-1) \r\n return somedisplay,someclock,somemenu\r\n\r\ndef minutes_menu(ison,background_dark,displayWidth,displayHeight,configfile):\r\n display,clock,menustats = setminutesmenu(displayWidth,displayHeight,configfile)\r\n global configmessagearray\r\n configmessagearray=[]\r\n while ison:\r\n # Handle events\r\n eventstats = pygame.event.get()\r\n for newevent in eventstats:\r\n if newevent.type == pygame.QUIT:\r\n sys.exit()\r\n if newevent.type == pygame.MOUSEBUTTONDOWN:\r\n checkrun,menustats = handlemousescroll(newevent,menustats)\r\n if newevent.button == 1: # Mouse is clicking\r\n minutes_long=int(menustats.selectedItemNumber+1)\r\n set_config(\"meditation_time\",str(minutes_long),configfile)\r\n if minutes_long == 1:\r\n minute_string = \"minute\"\r\n else:\r\n minute_string = \"minutes\"\r\n configmessagearray=[\"%s %s\" % (str(minutes_long),minute_string)]\r\n ison=False\r\n if newevent.type == pygame.KEYDOWN:\r\n if newevent.key == pygame.K_LEFT:\r\n menustats.selectItem(menustats.selectedItemNumber + 1)\r\n if newevent.key == pygame.K_RIGHT:\r\n menustats.selectItem(menustats.selectedItemNumber - 1)\r\n if newevent.key == pygame.K_RETURN:\r\n minutes_long=int(menustats.selectedItemNumber+1)\r\n set_config(\"meditation_time\",str(minutes_long),configfile)\r\n if minutes_long == 1:\r\n minute_string = \"minute\"\r\n else:\r\n minute_string = \"minutes\"\r\n configmessagearray=[\"%s %s\" % (str(minutes_long),minute_string)]\r\n ison=False\r\n # Update menu\r\n menustats.update()\r\n # Display background\r\n display.fill((0,0,0))\r\n img=pygame.image.load(background_dark)\r\n display.blit(img,(0,0))\r\n # Display menu\r\n menustats.draw(display)\r\n pygame.display.update()\r\n clock.tick(fpsLimit)\r\n return ison","sub_path":"mylibs/configminutesmenu.py","file_name":"configminutesmenu.py","file_ext":"py","file_size_in_byte":2844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"430591340","text":"import json\r\nimport os\r\nimport sys\r\n\r\nimport requests\r\n\r\n\r\ndef data_reader(name):\r\n resp = requests.get(\r\n \"https://raw.githubusercontent.com/v2fly/domain-list-community/master/data/\"+name).content.decode('utf-8')\r\n domain_list = resp.split(\"\\n\")\r\n\r\n # 删除空白行\r\n domain_list = [x for x in domain_list if x != '']\r\n # 删除注释行\r\n domain_list = [x for x in domain_list if x[0] != '#']\r\n # 忽略空格后的内容\r\n domain_list = [x.split(\" \")[0] for x in domain_list]\r\n # 递归读取 include 指向的文件\r\n for item in domain_list:\r\n if item[0:8] == \"include:\":\r\n domain_list = domain_list + data_reader(item[8:])\r\n # 删除 include 行\r\n domain_list = [x for x in domain_list if x[0:8] != \"include:\"]\r\n\r\n return domain_list\r\n\r\n\r\ndef data_parser_qx(domain_list, name):\r\n print(name)\r\n try:\r\n os.mkdir(\"quantumult-x\")\r\n os.chdir(\"quantumult-x\")\r\n except FileExistsError:\r\n os.chdir(\"quantumult-x\")\r\n domain_list = [x for x in domain_list if x[0:6] != \"regex:\"]\r\n filter_list = []\r\n for item in domain_list:\r\n if item[0:5] == \"full:\":\r\n filter_list.append(\"host, \" + item[5:] + \", \" + name)\r\n elif item[0:] == \"keyword:\":\r\n filter_list.append(\"host-keyword, \" + item[8:] + \", \" + name)\r\n else:\r\n filter_list.append(\"host-suffix, \" + item + \", \" + name)\r\n with open(name, \"w\", encoding=\"utf-8\") as e:\r\n for item in filter_list:\r\n print(item)\r\n e.write(item+\"\\n\")\r\n os.chdir('../')\r\n\r\n\r\ndef data_parser_clash_prem(domain_list, name):\r\n print(name)\r\n try:\r\n os.mkdir(\"clash-premium\")\r\n os.chdir(\"clash-premium\")\r\n except FileExistsError:\r\n os.chdir(\"clash-premium\")\r\n domain_list = [x for x in domain_list if x[0:6] != \"regex:\"]\r\n filter_list = []\r\n for item in domain_list:\r\n if item[0:5] == \"full:\":\r\n filter_list.append(\"DOMAIN,\" + item[5:])\r\n elif item[0:] == \"keyword:\":\r\n filter_list.append(\"DOMAIN-KEYWORD,\" + item[8:])\r\n else:\r\n filter_list.append(\"DOMAIN-SUFFIX,\" + item)\r\n with open(name + \".yaml\", \"w\", encoding=\"utf-8\") as e:\r\n e.write(\"payload:\\n\")\r\n for item in filter_list:\r\n print(item)\r\n e.write(\" - \"+item+\"\\n\")\r\n os.chdir('../')\r\n\r\n\r\nif __name__ == '__main__':\r\n app_name = sys.argv[1]\r\n if app_name == \"qx\":\r\n path_name = \"quantumult-x/\"\r\n if os.path.exists(path_name):\r\n [os.remove(path_name+x) for x in os.listdir(path_name)]\r\n elif app_name == \"clash-prem\":\r\n path_name = \"clash-premium/\"\r\n if os.path.exists(path_name):\r\n [os.remove(path_name+x) for x in os.listdir(path_name)]\r\n for domain_file in json.loads(requests.get(\"https://api.github.com/repos/v2fly/domain-list-community/contents/data/\").content.decode(\"utf-8\")):\r\n domain_list = data_reader(domain_file[\"name\"])\r\n if app_name == \"qx\":\r\n data_parser_qx(domain_list, domain_file[\"name\"])\r\n elif app_name == \"clash-prem\":\r\n data_parser_clash_prem(domain_list, domain_file[\"name\"])\r\n","sub_path":"generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":3209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"480209816","text":"#!/usr/bin/python\n\n\"\"\"\nFor creating a matplotlib canvas within a PyQt GUI. \nPlots figures from columns in an instance of Table class (table.py).\n\n\"\"\"\n\n\nfrom PyQt4 import QtGui\nfrom matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as \\\n FigureCanvas\nfrom matplotlib.figure import Figure\n\n\nclass Canvas(FigureCanvas):\n\n \"\"\"\n Class for graph tab. Creates Figure instance for matplotlib, and \n plotFigure function creates and draws a line or scatter graph\n \n \"\"\"\n\n def __init__(self, mainWindow, dataTab,\n width=4, height=4, dpi=100):\n \"\"\"Create Figure instance for matplotlib plotting.\"\"\"\n self.mainWindow = mainWindow\n self.dataTab = dataTab\n\n # init figure\n self.fig = Figure(figsize=(width, height), dpi=dpi)\n\n super(Canvas, self).__init__(self.fig)\n self.setSizePolicy(QtGui.QSizePolicy.Expanding,\n QtGui.QSizePolicy.Expanding)\n\n self.axes = self.fig.add_subplot(111)\n self.updateGeometry()\n \n def plotFigure(self, plotType):\n \"\"\"Create new plot and draw on canvas. \n Also shift x and y axes by half of tick distance \n so points/line don't get cut off by axes.\n \n plotType = 'scatter' or 'line' \n (Could easily add functionality for more options)\n\n \"\"\"\n # Get which columns to plot and get list of values\n columns = self.promptForColumns()\n if columns is None:\n return\n x,y = self.dataTab.getColumnData(columns)\n\n # Make new plot\n self.axes.hold(False) # Draw new graph in place of old\n if plotType == \"line\":\n self.axes.plot(x, y)\n elif plotType == \"scatter\":\n self.axes.plot(x, y, 'o')\n else:\n return\n self.draw()\n\n self.axes = self.shiftAxes(self.axes)\n \n # Title and axis labels\n self.axes.set_title(\"Column %d vs. Column %d\" %\n (columns[1],columns[0]))\n self.axes.set_xlabel(\"Column %d\" % columns[0])\n self.axes.set_ylabel(\"Column %d\" % columns[1])\n\n self.mainWindow.tabs.setCurrentWidget(self)\n\n def promptForColumns(self):\n \"\"\"Return indices of columns to be plotted based on user input. \n QInputDialog.getInt is always sanitzed, \n so no need for exception handling.\n\n \"\"\"\n x_col, x_ok = QtGui.QInputDialog.getInt(\n self, \"Choose columns\",\n \"Enter column for independent variable\\n(0 for row indices):\",\n 1, 0, self.dataTab.model.columnCount(), 1\n )\n if not x_ok: # User pressed cancel\n return\n\n y_col, y_ok = QtGui.QInputDialog.getInt(\n self, \"Choose columns\", \"Enter column for dependent variable:\",\n 2, 0, self.dataTab.model.columnCount(), 1\n )\n if not y_ok:\n return\n\n return (x_col, y_col)\n\n def shiftAxes(self, ax):\n \"\"\"Return axes shifted by 0.5*(tickmark distance) \n so points/lines don't get cut off.\n \n \"\"\"\n xticks = ax.get_xticks()\n yticks = ax.get_yticks()\n xmin = xticks[0] - 0.5*(xticks[1]-xticks[0])\n xmax = xticks[-1] + 0.5*(xticks[-1]-xticks[-2])\n ymin = yticks[0] - 0.5*(yticks[1]-yticks[0])\n ymax = yticks[-1] + 0.5*(yticks[-1]-yticks[-2])\n ax.set_xlim(xmin, xmax)\n ax.set_ylim(ymin, ymax)\n \n return ax\n","sub_path":"mplcanvas.py","file_name":"mplcanvas.py","file_ext":"py","file_size_in_byte":3495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"640533200","text":"from InformationRetriever import InformationRetriever\nfrom Sender import Sender\n# from sklearn import linear_model\nfrom sklearn import ensemble\nimport numpy as np\n\n\ndef getPrices(data):\n\treturn float(data.split(\"|\")[2].split(\"=\")[1]),float(data.split(\"|\")[4].split(\"=\")[1])\n\n\ndef bestLine(prices):\n\tsumX = (len(prices)*(len(prices)+1))/2\n\txAverage = sumX/len(prices)\n\n\tsumY = sum(prices)\n\tyAverage = sumX / len(prices)\n\n\tsumXSquared = 0\n\tsumMul = 0\n\n\tfor i in range(len(prices)):\n\t\tsumMul += ((i+1)-xAverage)*(prices[i]-yAverage)\n\t\tsumXSquared += ((i+1)-xAverage)*((i+1)-xAverage)\n\n\tb = sumMul/sumXSquared\n\ta = (sumY - b*sumX)/len(prices)\n\n\treturn a,b\n\n\npod = 10\n# clf = linear_model.LinearRegression()\nclf = ensemble.GradientBoostingRegressor(n_estimators = 500, max_depth = 10, min_samples_split = 2,\n\tlearning_rate = 0.2, loss = 'ls')\n\t\nold_hist_SP_Ask = []\nold_hist_SP_Bid = []\ntrade_hist_SP_Ask = []\ntrade_hist_SP_Bid = []\n\nold_hist_ESX_Ask = []\nold_hist_ESX_Bid = []\ntrade_hist_ESX_Ask = []\ntrade_hist_ESX_Bid = []\n\npred_ask_ESX = -1\npred_bid_ESX = -1\npred_ask_SP = -1\npred_bid_SP = -1\n\nesx_last_bought = -1\nsp_last_bought = -1\n\nesx_last_bid = -1\nsp_last_bid = -1\n\nesx_bidPrice = 0\nesx_askPrice = 0\n\nsp_bidPrice = 0\nsp_askPrice = 0\n\ndef gradientBoosting(pair, old_list, trade_list, biddi): \n\tif len(old_list) < pod+1 or len(trade_list) < pod: \n\t\ttrade_list.append(pair)\n\t\treturn -1 \n\n\tX = [[old_list[i-1], trade_list[i][0], trade_list[i][1]] for i in range(-1*pod, 0)]\n\task_X_train = np.array(X).astype(np.float64)\n\tY = old_list[len(old_list) - pod:]\n\task_Y_train = np.array(Y).astype(np.float64)\n\n\tclf.fit(ask_X_train, ask_Y_train)\n\ttrade_list.append(pair)\n\ty_pred = clf.predict([[old_list[-1], pair[0], pair[1]]])\n\n\tif biddi: \n\t\tprint(\"PREDICT BID \", y_pred)\n\t\treturn y_pred\n\t\n\telse: \n\t\tprint(\"PREDICT ASK \", y_pred)\n\t\treturn y_pred\n\n\nTHRESHHOLD = 0.24\nAMOUNT = 0.3\ninformationRetriever = InformationRetriever(\"35.179.45.135\",7001)\nsender = Sender()\n\n\nwhile True:\n\tdata = informationRetriever.receivePrices().decode(\"utf-8\")\n\tprint(data)\n\tif(\"TYPE=TRADE|FEEDCODE=ESX-FUTURE|SIDE=BID\" in data):\n\t\tinstrument = 'ESX-FUTURE'\n\t\tprice, volume = float(data.split(\"|\")[3].split(\"=\")[1]),float(data.split(\"|\")[4].split(\"=\")[1])\n\t\tpred_bid_ESX = gradientBoosting([price, volume], old_hist_ESX_Bid, trade_hist_ESX_Bid, True)\n\t\tesx_last_bid = esx_bidPrice\n\n\t\tif (pred_bid_ESX > 0 and pred_bid_ESX + THRESHHOLD < esx_bidPrice and esx_bidPrice > esx_last_bought):\n\t\t\t#Sell\n\t\t\tprint(\"Selling 50 ESX at \",esx_bidPrice)\n\t\t\tsender.send_order(instrument,\"SELL\",esx_bidPrice,round(volume*AMOUNT))\n\n\telif(\"TYPE=TRADE|FEEDCODE=ESX-FUTURE|SIDE=ASK\" in data):\n\t\tinstrument = 'ESX-FUTURE'\n\t\tprice, volume = float(data.split(\"|\")[3].split(\"=\")[1]),float(data.split(\"|\")[4].split(\"=\")[1])\n\t\tpred_ask_ESX = gradientBoosting([price, volume], old_hist_ESX_Ask, trade_hist_ESX_Ask, False)\n\t\tif (pred_ask_ESX > 0 and pred_ask_ESX - THRESHHOLD >= esx_askPrice and esx_askPrice < esx_last_bid):\n\t\t\t#Buy\n\t\t\tesx_last_bought = esx_askPrice\n\t\t\tprint(\"Buying 50 ESX at \",esx_askPrice)\n\t\t\tsender.send_order(instrument,\"BUY\",esx_askPrice,round(volume*AMOUNT))\n\n\n\telif(\"TYPE=TRADE|FEEDCODE=SP-FUTURE|SIDE=BID\" in data):\n\t\tinstrument = 'SP-FUTURE'\n\t\tprice, volume = float(data.split(\"|\")[3].split(\"=\")[1]),float(data.split(\"|\")[4].split(\"=\")[1])\n\t\tpred_bid_SP = gradientBoosting([price, volume], old_hist_SP_Bid, trade_hist_SP_Bid, True)\n\n\t\tsp_last_bid = sp_bidPrice\n\t\tif (pred_bid_SP > 0 and pred_bid_SP + THRESHHOLD < sp_bidPrice and sp_bidPrice > sp_last_bought):\n\t\t\t#print(bidPrice,(a+(len(bidPrices)+1)*b))\n\t\t\t#Sell\n\t\t\tprint(\"Selling 50 SP at \",sp_bidPrice)\n\t\t\tsender.send_order(instrument,\"SELL\",sp_bidPrice,round(volume*AMOUNT))\n\n \n\telif(\"TYPE=TRADE|FEEDCODE=SP-FUTURE|SIDE=ASK\" in data):\n\t\tinstrument = 'SP-FUTURE'\n\t\tprice, volume = float(data.split(\"|\")[3].split(\"=\")[1]),float(data.split(\"|\")[4].split(\"=\")[1])\n\t\tpred_ask_SP = gradientBoosting([price, volume], old_hist_SP_Ask, trade_hist_SP_Ask, False)\n\n\t\tif (pred_ask_SP > 0 and pred_ask_SP - THRESHHOLD > sp_askPrice and sp_askPrice < sp_last_bid):\n\t\t\t#Buy\n\t\t\tsp_last_bought = sp_askPrice\n\t\t\tprint(\"Buying 50 SP at \",sp_askPrice)\n\t\t\tsender.send_order(instrument,\"BUY\",sp_askPrice,round(volume*AMOUNT))\n\n\n\telif(\"TYPE=PRICE|FEEDCODE=SP-FUTURE\" in data):\n\t\tinstrument = 'SP-FUTURE'\n\t\tsp_bidPrice, sp_askPrice = getPrices(data)\n\t\told_hist_SP_Bid.append(sp_bidPrice)\n\t\told_hist_SP_Ask.append(sp_askPrice)\n\n\n\telif(\"TYPE=PRICE|FEEDCODE=ESX-FUTURE\" in data):\n\t\tinstrument = 'ESX-FUTURE'\n\t\tesx_bidPrice, esx_askPrice = getPrices(data)\n\t\told_hist_ESX_Bid.append(esx_bidPrice)\n\t\told_hist_ESX_Ask.append(esx_askPrice)\n\n\n\n\n\n","sub_path":"SimpleTrader.py","file_name":"SimpleTrader.py","file_ext":"py","file_size_in_byte":4644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"395819684","text":"\"\"\"processor\"\"\"\nimport logging\nimport haversine\n\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass CarState: # pylint: disable=too-few-public-methods\n \"\"\"Holds the state of a car\"\"\"\n\n def __init__(self, car_id: int, location: tuple, timestamp: int):\n \"\"\"\n Constructor\n\n :param int car_id: the id of the car\n :param tuple location: the car's location\n :param int timestamp: the timestamp of the metric\n \"\"\"\n self.car_id = car_id\n self.location = location\n self.timestamp = timestamp\n self.position = None\n self.speed = None\n self.distance = 0\n\n def __str__(self):\n return str(self.__dict__)\n\n\nclass Processor:\n \"\"\"The processor class\"\"\"\n def __init__(self):\n \"\"\"\n Constructor\n \"\"\"\n self._state = {}\n\n def get_state(self):\n \"\"\"\n Returns the processor state\n\n :return: the state\n :rtype: dict\n \"\"\"\n return self._state\n\n def add_car_coordinates(self, data: dict):\n \"\"\"\n Syncs the processor with the given car coordinates\n\n :param dict data: the message's data\n \"\"\"\n LOGGER.debug('Processing car coordinates: %s', data)\n\n ret = []\n\n ret.extend(self._sync_car_state(data))\n ret.extend(self._sync_cars_positions())\n\n return ret\n\n def _sync_car_state(self, data: dict):\n \"\"\"\n Syncs the car's state\n\n :param dict data: the data to use\n \"\"\"\n car_id = int(data['carIndex'])\n\n new_timestamp = int(data['timestamp'])\n new_location = (data['location']['lat'], data['location']['long'])\n\n # New car found\n if car_id not in self._state:\n self._state[car_id] = CarState(car_id, new_location, new_timestamp)\n LOGGER.debug('New car found: %s', self._state[car_id])\n return []\n\n # Existing car. We need to check the timestamp of the message and accept only newer\n if new_timestamp <= self._state[car_id].timestamp:\n LOGGER.debug('Dropping data because of timestamp: %s', self._state[car_id])\n return []\n\n # Based on the distance difference between the 2 measurements, we can calculate the speed\n old_location = self._state[car_id].location\n\n step_distance = haversine.haversine(old_location, new_location, haversine.Unit.MILES)\n new_distance = self._state[car_id].distance + step_distance\n\n old_timestamp = self._state[car_id].timestamp\n new_speed = (step_distance / (new_timestamp - old_timestamp)) * 3600000.0\n\n self._state[car_id].location = new_location\n self._state[car_id].distance = new_distance\n self._state[car_id].speed = new_speed\n self._state[car_id].timestamp = new_timestamp\n\n LOGGER.debug('New car state: %s', self._state[car_id])\n\n # Make speed update\n return [self._make_car_speed_message(car_id)]\n\n def _sync_cars_positions(self):\n \"\"\"\n Syncs the cars positions\n\n We can calculate the car positions only if all cars are synced to the same timestamp\n If the cars are not in the same timestamp, we have to skip,\n as the calculate may lead to wrong events and positions\n \"\"\"\n LOGGER.debug('Calculating new car positions')\n\n if not self._state:\n LOGGER.debug('Not cars yet. Skipping')\n return []\n\n # Check timestamp condition\n timestamp = None\n for car_id, car_state in self._state.items():\n if timestamp is None:\n timestamp = car_state.timestamp\n continue\n\n if timestamp != car_state.timestamp:\n LOGGER.debug('Not all cars are in the same timestamp. Skipping')\n return []\n\n # Calculate new positions\n ret = []\n\n LOGGER.debug('All cars are in the same timestamp. Calculating positions')\n\n distances = sorted(\n [(car_state.distance, car_id) for car_id, car_state in self._state.items()],\n reverse=True\n )\n LOGGER.debug('Cars distances order: %s', distances)\n\n new_positions = {distance_data[1]:index for index, distance_data in enumerate(distances)}\n LOGGER.debug('Cars new positions: %s', new_positions)\n\n new_positions_index = {position:car_id for car_id, position in new_positions.items()}\n\n for car_id, new_position in new_positions.items():\n old_position = self._state[car_id].position\n self._state[car_id].position = new_position\n\n if old_position is None or old_position <= new_position:\n continue\n\n LOGGER.debug('Car %s position: old %s, new %s', car_id, old_position, new_position)\n\n ret.append(self._make_events_message(\n timestamp,\n 'Car {} races ahead of Car {} at position {} in a dramatic overtake'.format(\n car_id, new_positions_index[old_position], new_position + 1\n )\n ))\n\n if new_position == 0:\n ret.append(self._make_events_message(\n timestamp,\n 'Car {} is now leading the race!'.format(car_id)\n ))\n\n for car_id, car_state in self._state.items():\n ret.append(self._make_car_position_message(car_id))\n\n return ret\n\n def _make_car_position_message(self, car_id: int):\n \"\"\"\n Helper function to make a car position message\n\n :param int car_id: the id of the car\n \"\"\"\n return {\n 'topic': 'car_status',\n 'timestamp': self._state[car_id].timestamp,\n 'carIndex': car_id,\n 'type': 'POSITION',\n 'value': self._state[car_id].position + 1\n }\n\n def _make_car_speed_message(self, car_id: int):\n \"\"\"\n Helper function to make a car speed message\n\n :param int car_id: the id of the car\n \"\"\"\n return {\n 'topic': 'car_status',\n 'timestamp': self._state[car_id].timestamp,\n 'carIndex': car_id,\n 'type': 'SPEED',\n 'value': self._state[car_id].speed\n }\n\n @staticmethod\n def _make_events_message(timestamp: int, text: str):\n \"\"\"\n Helper function to make an events message\n\n :param int timestamp: the message's timestamp\n :param str text: the message's text\n \"\"\"\n return {\n 'topic': 'events',\n 'timestamp': timestamp,\n 'text': text\n }\n","sub_path":"matapp/matapp/processor.py","file_name":"processor.py","file_ext":"py","file_size_in_byte":6604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"358197937","text":"from datetime import datetime, time\nimport heapq\nimport math\n\nimport random\n\n\nclass Solution:\n\n def __init__(self, rects):\n self.rects = rects\n self.weight = [0] * len(rects)\n for i in range(len(rects)):\n [x1, y1, x2, y2] = rects[i]\n w = (x2 - x1 + 1) * (y2 - y1 + 1)\n self.weight[i] = self.weight[i - 1] + w if i > 0 else w\n\n def pick(self) -> 'List[int]':\n area = random.randrange(0, self.weight[-1] + 1)\n\n def findCeil(s, f):\n if s == f or self.weight[s] >= area:\n return s\n mid = (s + f) // 2\n if self.weight[mid] < area:\n return findCeil(mid + 1, f)\n else:\n return findCeil(s, mid)\n\n [x1, y1, x2, y2] = self.rects[findCeil(0, len(self.rects) - 1)]\n x = random.randrange(x1, x2 + 1)\n y = random.randrange(y1, y2 + 1)\n return [x, y]\n\n\ns = Solution([[82918473, -57180867, 82918476, -57180863],\n [83793579, 18088559, 83793580, 18088560],\n [66574245, 26243152, 66574246, 26243153],\n [72983930, 11921716, 72983934, 11921720]])\nstartTime = datetime.now()\nprint(s.pick())\nprint(datetime.now() - startTime)\n","sub_path":"leetcode/2020/random-point-in-non-overlapping-rectangles.py","file_name":"random-point-in-non-overlapping-rectangles.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"148119780","text":"from keystone.manage2 import base\nfrom keystone.manage2 import common\n\n\n@common.arg('--where-id',\n required=True,\n help='identifies the tenant to update by ID')\n@common.arg('--name',\n required=False,\n help=\"change the tenant's name\")\n@common.arg('--enable',\n action='store_true',\n required=False,\n default=False,\n help=\"enable the tenant\")\n@common.arg('--disable',\n action='store_true',\n required=False,\n default=False,\n help=\"disable the tenant\")\nclass Command(base.BaseBackendCommand):\n \"\"\"Updates the specified tenant.\"\"\"\n\n # pylint: disable=E1101\n def update_tenant(self, id, name=None, enabled=None):\n tenant = self.get_tenant(id)\n\n if name is not None:\n tenant.name = name\n\n if enabled is not None:\n tenant.enabled = enabled\n\n self.tenant_manager.update(tenant)\n\n def run(self, args):\n \"\"\"Process argparse args, and print results to stdout\"\"\"\n enabled = self.true_or_false(args, 'enable', 'disable')\n\n self.update_tenant(id=args.where_id, name=args.name, enabled=enabled)\n","sub_path":"keystone/manage2/commands/update_tenant.py","file_name":"update_tenant.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"225107725","text":"#!/usr/bin/env python3\n###############################################################################\n#\n# Manages installed software using Homebrew.\n# \n# Usage: python3 brewmaster.py /path/to/config.yaml\n#\n# Homepage: https://github.com/bjschafer/brewmaster\n#\n# Author: Braxton Schafer (bjs)\n#\n# Changelog:\n# \n###############################################################################\n\nimport subprocess\nimport sys\nimport yaml\n\ndef get_config():\n\ttry:\n\t\tconfig_file = sys.argv[1]\n\texcept IndexError:\n\t\tprint(\"Please give me a config file path!\")\n\t\tsys.exit(0)\n\n\twith open(config_file, 'r') as conf:\n\t\treturn yaml.load(conf)\n\ndef check_setup(conf):\n\tpass # We'll need you later.\n\ndef call_brew(args):\n\ttry:\n\t\targs = args.split(' ')\n\texcept AttributeError:\n\t\tpass # it's already how we expect it to be\n\tstatus = subprocess.call((['brew'] + args))\n\tif status != 0: # Something done goofed.\n\t\tprint(\"Something went wrong with brew. Here are the args:\\n\" + args)\n\n\nif __name__ == '__main__':\n\tconf = get_config()\n\tcheck_setup(conf)\n\n\tcall_brew('update')\n\n\t# Update out of date packages that may be updated.\n\tcall_brew('upgrade')\n\n\t# Let's install what we came here for\n\n\tfor formula in get_config()['formulae']:\n\t\tname = formula['name']\n\t\tversion = formula['name']\n\t\targs = []\n\t\ttry:\n\t\t\targs = formula['args']\n\t\texcept:\n\t\t\targs = []\n\n\t\tif version == 'current':\n\t\t\tcall_brew(['install', name, ' '.join(args)])\n\t\t\t\n\t\t\tcall_brew(['pin', name])\n\n\t\telif version == 'latest':\n\t\t\tcall_brew(['install', name, ' '.join(args)])\n\n\t\telse:\n\t\t\tcall_brew(['install', name, ' '.join(args)])\n\t\t\t\n\t\t\tcall_brew(['pin', name])","sub_path":"bin/brewmaster.py","file_name":"brewmaster.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"248561893","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 30 19:46:47 2018\n\n@author: nicolasnicolas\n\"\"\"\nimport random\nimport string\nimport numpy as np\n\ndef key(nb_lettre): \n return(''.join([random.choice(string.ascii_lowercase) for i in range(6)]))\n\n\n\n\ndef arabic2roman(nb):\n lettre =['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I']\n chiffre=[1000,900,500,400,100,90,50,40,10,9,5,4,1]\n romain = ''\n for i in range(len(lettre)):\n romain = romain + int(((nb-(nb%chiffre[i]))/chiffre[i]))*lettre[i]\n nb = nb%chiffre[i]\n return(romain)\n\n \nnumerals = [\n {'letter': 'M', 'value': 1000},\n {'letter': 'D', 'value': 500},\n {'letter': 'C', 'value': 100},\n {'letter': 'L', 'value': 50},\n {'letter': 'X', 'value': 10},\n {'letter': 'V', 'value': 5},\n {'letter': 'I', 'value': 1},\n ]\n\ndef roman_to_arabic(number):\n index_by_letter = {}\n for index in range(len(numerals)):\n index_by_letter[numerals[index]['letter']] = index\n\n result = 0\n previous_value = None\n for letter in reversed(number):\n index = index_by_letter[letter]\n value = numerals[index]['value']\n if (previous_value is None) or (previous_value <= value):\n result += value\n else:\n result -= value\n previous_value = value\n\n return result\n\n\n\ndef ROT13(phrase, n=13,way= 0):\n if( n<1 or n>26):\n print('Chiffrement en rotation sur {} caractères impossible.'.format(n))\n print('La valeur de n doit être inférieure ou égale à 26.')\n return('none')\n \n \n minus = list(string.ascii_lowercase)\n maj = list(string.ascii_uppercase) \n \n minuscry = list(string.ascii_lowercase)[n::]+list(string.ascii_lowercase)[0:n]\n majcry = list(string.ascii_uppercase)[n::]+list(string.ascii_uppercase)[0:n]\n \n phrase = list(phrase)\n phrasecry = []\n \n if(way == 'decrypt'):\n for j in range(len(phrase)):\n for i in range(len(minus)): \n if(phrase[j] == minuscry[i]):\n phrasecry.append(minus[i]) \n if(phrase[j]== majcry[i]):\n phrasecry.append(maj[i]) \n if(phrase[j]==' '):\n phrasecry.append(' ')\n \n return(''.join(phrasecry))\n else: \n for j in range(len(phrase)):\n for i in range(len(minus)): \n if(phrase[j] == minus[i]): \n phrasecry.append(minuscry[i])\n if(phrase[j]== maj[i]):\n phrasecry.append(majcry[i])\n if(phrase[j]==' '):\n phrasecry.append(' ')\n return(''.join(phrasecry)) \n \n\nclass Vernam:\n \n def __init__(self, cle='toto'):\n self.cle = list(cle)\n self.maj = np.append(np.linspace(65,90,26,dtype=int),np.linspace(65,90,26,dtype=int))\n self.minus = np.append(np.linspace(97,122,26,dtype=int),np.linspace(97,122,26,dtype=int))\n \n def encrypt(self, message, keygen = True):\n cle = self.cle\n message = list(message)\n if(keygen == True):\n cle=[random.choice(string.ascii_lowercase) for i in range(len(message))]\n #print('haha')\n #print(self.cle) \n \n messagecry = []\n \n \n if(len(str(message))==len(str(self.cle))): \n for i in range(len(message)):\n if(ord(message[i])<91 and ord(message[i])>64):\n ajout=ord(cle[i])-65\n lettre = ord(message[i])-65\n messagecry.append(chr(self.maj[lettre+ajout]))\n \n elif(ord(message[i])>96 and ord(message[i])<123):\n ajout=ord(cle[i])-97\n lettre = ord(message[i])-97\n messagecry.append(chr(self.minus[lettre+ajout]))\n else:\n messagecry.append(message[i])\n \n return('message crypté : '+''.join(messagecry),'clé de cryptage : '+''.join(self.cle)) \n \n else:\n return('Erreur la cle et le message ont une taille différente')\n \n def decrypt(self,message):\n message = list(message)\n messagecry = []\n \n \n if(len(str(message))==len(str(self.cle))): \n for i in range(len(message)):\n if(ord(message[i])<91 and ord(message[i])>64):\n ajout=ord(self.cle[i])-65\n lettre = ord(message[i])-65\n messagecry.append(chr(self.maj[26+lettre-ajout]))\n \n elif(ord(message[i])>96 and ord(message[i])<123):\n ajout=ord(self.cle[i])-97\n lettre = ord(message[i])-97\n messagecry.append(chr(self.minus[26+lettre-ajout]))\n else:\n messagecry.append(message[i])\n \n return('message décrypté : '+''.join(messagecry)) \n \n else:\n return('Erreur la cle et le message ont une taille différente')\n\n \n \n\n\n\nif __name__=='__main__': \n print(key(10))\n \n a = arabic2roman(808)\n b = roman_to_arabic(\"IV\")\n print(a)\n print(b)\n print(ROT13('Ceci est une phrase secrete',n=10))\n print(ROT13('Prpv rfg har cuenfr frpergr',way ='decrypt'))\n test = Vernam('ooaq')\n res = test.encrypt('momo')\n\n\n res1 = test.decrypt('acme')\n print(res1)\n print(res)","sub_path":"crypto.py","file_name":"crypto.py","file_ext":"py","file_size_in_byte":5609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"173159443","text":"\r\nimport numpy as np\r\nfrom helper_scripts import shuffle\r\n#import cPickle as pickle\r\nimport _pickle as pickle\r\nimport regex as re\r\n# from util import load_dict\r\n\r\n# import data_utils\r\n\r\n\r\nclass CLIDecodeProcessor:\r\n def __init__(self, source_dict, target_dict, maxlen_enc=100):\r\n\r\n self.source_word2id = self._load_dict(source_dict, flag='source')\r\n self.target_id2word = self._load_dict(target_dict, flag='target')\r\n\r\n self.maxlen_enc = maxlen_enc\r\n\r\n self._WORD_SPLIT = re.compile(b\"([.,!?\\\"':;)(])\")\r\n self.PAD_ID = 0\r\n self.EOS_ID = 1\r\n self.UNK_ID = 2\r\n self.GO_ID = 3\r\n\r\n\r\n def _load_dict(self, file_name, flag):\r\n\r\n if flag == 'source':\r\n _, word_dict, _ = pickle.load(open(file_name, 'r'))\r\n elif flag == 'target':\r\n _, _, word_dict = pickle.load(open(file_name, 'r'))\r\n\r\n return word_dict\r\n\r\n def word2seq(self, txt, tokenizer=None):\r\n\r\n word_tokens = tokenizer(txt) if tokenizer else self._basic_tokenizer(txt)\r\n id_tokens = [self.source_word2id.get(w, self.UNK_ID) for w in word_tokens]\r\n\r\n return id_tokens\r\n\r\n\r\n def _basic_tokenizer(self, sentence):\r\n words = []\r\n for space_separated_fragment in sentence.strip().split():\r\n words.extend(self._WORD_SPLIT.split(space_separated_fragment))\r\n return [w for w in words if w]\r\n\r\n\r\n def get_cli_decode_data(self, vis_input):\r\n vis_input = vis_input.strip()\r\n\r\n seq_cmd_line = []\r\n\r\n id_tokens_cmd_line = self.word2seq(vis_input)\r\n num_words = len(id_tokens_cmd_line)\r\n len_cmd_line = [num_words]\r\n if num_words > self.maxlen_enc:\r\n id_tokens_cmd_line = id_tokens_cmd_line[:self.maxlen_enc]\r\n len_cmd_line = [self.maxlen_enc]\r\n\r\n seq_cmd_line.append(id_tokens_cmd_line)\r\n\r\n return np.array(seq_cmd_line), np.array(len_cmd_line)\r\n\r\n def seq2words(self, seq):\r\n words = []\r\n for idx in seq:\r\n if idx == self.EOS_ID:\r\n break\r\n if idx in self.target_id2word:\r\n words.append(self.target_id2word[idx])\r\n else:\r\n words.append('UNK_ID')\r\n\r\n return ' '.join(words)\r\n\r\n\r\n#Train Iterator has been made so that we can process the text in batches.\r\nclass TrainIterator:\r\n \"\"\"Simple Bitext iterator.\"\"\"\r\n def __init__(self, source,\r\n source_dict, target_dict,\r\n batch_size=128,\r\n maxlen_enc=100,\r\n maxlen_dec=100,\r\n skip_empty=True,\r\n shuffle_each_epoch=False,\r\n delimiter=' +++$+++ ',\r\n # sort_by_length=True,\r\n maxibatch_size=20):\r\n \r\n #If you want to shuffle at each epoch then use this.(Works only in Python2.7)\r\n if shuffle_each_epoch:\r\n self.source_orig = source\r\n self.source = shuffle.main([self.source_orig], temporary=True)\r\n else:\r\n self.source = open(source, 'r')\r\n\r\n #Lets intialise our source and target dictinary.\r\n self.source_dict = self._load_dict(source_dict)\r\n self.target_dict = self._load_dict(target_dict)\r\n\r\n self.batch_size = batch_size\r\n self.maxlen_enc = maxlen_enc\r\n self.maxlen_dec = maxlen_dec\r\n self.skip_empty = skip_empty\r\n\r\n self._WORD_SPLIT = re.compile(b\"([.,!?\\\"':;)(])\")\r\n self.PAD_ID = 0\r\n self.EOS_ID = 1\r\n self.UNK_ID = 2\r\n self.GO_ID = 3\r\n self.delimiter = delimiter\r\n self.source_buffer = []\r\n self.k = batch_size\r\n\r\n self.end_of_data = False\r\n\r\n def _load_dict(self, file_name):\r\n _, word2id_dict, _ = pickle.load(open(file_name, 'rb'))\r\n return word2id_dict\r\n\r\n def _basic_tokenizer(self, sentence):\r\n words = []\r\n for space_separated_fragment in sentence.strip().split():\r\n words.extend(self._WORD_SPLIT.split(space_separated_fragment.encode()))\r\n return [w for w in words if w]\r\n\r\n def word2seq(self, txt, flag='source', tokenizer=None):\r\n word_tokens = tokenizer(txt) if tokenizer else self._basic_tokenizer(txt)\r\n if flag == 'source':\r\n id_tokens = [self.source_dict.get(w, self.UNK_ID) for w in word_tokens]\r\n elif flag == 'target':\r\n id_tokens = [self.target_dict.get(w, self.UNK_ID) for w in word_tokens]\r\n\r\n return id_tokens\r\n \r\n def __iter__(self):\r\n return self\r\n\r\n def __len__(self):\r\n return sum([1 for _ in self])\r\n\r\n def reset(self):\r\n # if self.shuffle:\r\n # self.source = shuffle.main([self.source_orig], temporary=True)\r\n # else:\r\n # self.source.seek(0)\r\n\r\n self.source.seek(0)\r\n\r\n def __next__(self):\r\n if self.end_of_data:\r\n self.end_of_data = False\r\n self.reset()\r\n raise StopIteration\r\n\r\n source = []\r\n target = []\r\n\r\n if len(self.source_buffer) == 0:\r\n for k_ in range(self.k):\r\n line = self.source.readline()\r\n if line == \"\":\r\n break\r\n self.source_buffer.append(line)\r\n\r\n self.source_buffer.reverse()\r\n\r\n if len(self.source_buffer) == 0:\r\n self.end_of_data = False\r\n self.reset()\r\n raise StopIteration\r\n\r\n try:\r\n\r\n # actual work here\r\n while True:\r\n\r\n # read from source file and map to word index\r\n try:\r\n line = self.source_buffer.pop()\r\n except IndexError:\r\n break\r\n\r\n line = line.strip().split(self.delimiter)\r\n\r\n ss = str(line[2])\r\n tt = str(line[3])\r\n\r\n ss_word_index = self.word2seq(ss, flag='source')\r\n tt_word_index = self.word2seq(tt, flag='target')\r\n\r\n if self.skip_empty and (not ss):\r\n continue\r\n\r\n source.append(ss_word_index)\r\n target.append(tt_word_index)\r\n\r\n #An Extra Check to ensure source length equal to batch_size\r\n if len(source) >= self.batch_size:\r\n break\r\n except IOError:\r\n self.end_of_data = True\r\n\r\n\r\n source_lengths = np.array([len(s) if len(s) \"'.format(name) + \\\r\n current_dir + '\\\\{}.wav\"'.format(name)\r\n return args\r\n\r\nprint(make_ffmpeg_arg('1'))\r\n\r\ns1 = subprocess.call(make_ffmpeg_arg('1'), shell=True)\r\nprint('sub1:', s1)\r\ns2 = subprocess.call(make_ffmpeg_arg('2'), shell=True)\r\nprint('sub1:', s2)\r\n\r\np1 = os.path.isfile('./'+file_wav_1)\r\np2 = os.path.isfile('./'+file_wav_2)\r\n\r\nif not p1 or not p2:\r\n sys.exit()\r\n\r\n\r\nargs = current_dir + '\\\\bin\\\\fr \"' + current_dir + '\\\\1.wav\" \"' + current_dir + '\\\\2.wav\" ' + current_dir + '\\\\result\\\\result.wav'\r\n\r\nsubprocess.call(args)\r\n\r\n# Clear garbage\r\ndelete = []\r\ndelete.append(current_dir + '\\\\1.wav')\r\ndelete.append(current_dir + '\\\\2.wav')\r\ndelete.append(current_dir + '\\\\t.txt')\r\n\r\nctrl = input(\"Delete source files? y/n\\n\")\r\nif ctrl == 'y':\r\n delete.append(current_dir + '\\\\1.mp3')\r\n delete.append(current_dir + '\\\\2.mp3')\r\n \r\nfor item in delete:\r\n os.remove(item)","sub_path":"ors/make.py","file_name":"make.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"118869177","text":"#作者:老杜\n#2020/7/10\n#导入模块\nfrom selenium import webdriver\n#创建浏览器驱动对象\ndriver = webdriver.Chrome(\"D:\\\\ruanjian\\chromedriver\\chromedriver.exe\")\n#访问网址\ndriver.get(\"https://www.baidu.com/\")\n#找到搜索框\ninpEle =driver.find_element_by_id(\"kw\")\ninpEle.send_keys(\"测试\")\n#找到搜索按钮\nsEle = driver.find_element_by_id(\"su\")\nsEle.click()\n\n\n#退出浏览器\n# driver.quit()","sub_path":"test/selenium_class/day1/hello_selenium.py","file_name":"hello_selenium.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"623037532","text":"'''\n회사에서 출발하여 N명의 고객을 모두 방문하고 집으로 돌아가는 경로중 가장 짧은 것을 찾으려 한다.\n가장 짧은 경로를 '효율적으로 찾는 것'이 목적이 아니다.\n모든 가능한 경로를 살펴서 해를 찾아도 좋다 #완전검색+가지치기\n[제약]\n회사의 좌표, 집의 좌표를 포함한 모든 N*2개의 좌표는 서로 다른 위치에 있으며 좌표의 값은 0이상100이하의 정수로 이뤄진다.\n[입력]\n첫째줄에는 고객의 수 N\n둘째줄에는 회사의 좌표, 집의좌표, N명의 고객의 좌표.\n좌표는 (x,y) 쌍으로 구성되는데 입력에서는 x와 y가 공백으로..\n#순열\n'''\nimport sys\nsys.stdin = open(\"1247.txt\",\"r\")\n\ndef findway(bx, by, c,s):\n global minway\n if s > minway:\n return\n if c == L-1:\n for i in range(L):\n if V[i] == 0:\n x,y = my_lst[i]\n s += abs(bx-x)+abs(by-y)\n s += abs(x-company[0])+abs(y-company[1])\n break\n if minway > s:\n minway = s\n return\n else:\n for i in range(L):\n if V[i] == 0:\n V[i] = 1\n x,y = my_lst[i]\n findway(x,y,c+1,s+abs(bx-x)+abs(by-y))\n V[i] = 0\n\nT=int(input())\nfor tc in range(1, T+1):\n N=int(input())\n zapyo_lst=list(map(int,input().split()))\n my_lst = []\n for n in range(N):\n my_lst.append([zapyo_lst[2*(n+2)],zapyo_lst[(2*(n+2))+1]])\n home = [zapyo_lst[0],zapyo_lst[1]]\n company = [zapyo_lst[2], zapyo_lst[3]]\n minway = 100000\n L = len(my_lst)\n V = [0]*L\n findway(home[0], home[1], 0, 0)\n print('#{} {}'.format(tc, minway))\n","sub_path":"Problem Solving/SWEA/D5/1247.최적경로.py","file_name":"1247.최적경로.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"295880030","text":"\"\"\"\nA simple method to make tensorflo LSTM stateful\n\nhttps://stackoverflow.com/questions/37969065/tensorflow-best-way-to-save-state-in-rnns\n\"\"\"\n\nimport tensorflow as tf\n\ndef get_state_variables(batch_size, cell):\n # For each layer, get the initial state and make a variable out of it\n # to enable updating its value.\n state_variables = []\n for state_c, state_h in cell.zero_state(batch_size, tf.float32):\n state_variables.append(tf.contrib.rnn.LSTMStateTuple(\n tf.Variable(state_c, trainable=False),\n tf.Variable(state_h, trainable=False)))\n # Return as a tuple, so that it can be fed to dynamic_rnn as an initial state\n return tuple(state_variables)\n\n\ndef get_state_update_op(state_variables, new_states):\n # Add an operation to update the train states with the last state tensors\n update_ops = []\n for state_variable, new_state in zip(state_variables, new_states):\n # Assign the new state to the state variables on this layer\n update_ops.extend([state_variable[0].assign(new_state[0]),\n state_variable[1].assign(new_state[1])])\n # Return a tuple in order to combine all update_ops into a single operation.\n # The tuple's actual value should not be used.\n return tf.tuple(update_ops)\n\ndef get_state_reset_op(state_variables, cell, batch_size):\n # Return an operation to set each variable in a list of LSTMStateTuples to zero\n zero_states = cell.zero_state(batch_size, tf.float32)\n return get_state_update_op(state_variables, zero_states)","sub_path":"stateful_lstm.py","file_name":"stateful_lstm.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"76477093","text":"__author__ = 'Administrator'\n\n#!/usr/bin/env python\n#coding:utf-8\nimport os,time,random,sys#,threadpool,sys\n#from progressbar import *\n\nCOUNT=0\ntit=1000\nPINGIP=[]\n\ndef main():\n ipd=None\n if len(sys.argv)==2:\n ipd=sys.argv[1]\n\n a=os.popen(\"ipconfig\").read()\n s=a.split('.')\n del s[-1]\n ips='.'.join(s)\n ipl=\"\"\n if ipd==None:\n ipl=ips\n else:\n ipl=ipd\n print(\"搜索网段:\"+ipl)\n List=myIpPool(ipl)\n #pool=threadpool.ThreadPool(100)\n #req=threadpool.makeRequests(ping,List,print_result)\n #for r in req:\n # pool.putRequest(r)\n #pool.wait()\n #print()\n print(PINGIP)\n\ndef myIpPool(ipPrefix):\n List=[]\n for i in range(1,255):\n List.append(\"%s.%d\" %(ipPrefix,i))\n return List\n\ndef print_result(request, result):\n global COUNT\n global PINGIP\n global pbar\n COUNT+=1\n List=[]\n if result!=None:\n #print \"the result is %s %r\" % (request.requestID, result)\n PINGIP.append(result)\n aa=int(COUNT/256.00*100)\n\n #print(COUNT,aa)\n pbar.update(aa)\n\ndef ping(ip):\n #print(\"ip:\"+ip)\n ret=os.popen(\"ping -c 2 -W 2 \"+ip).readlines()\n bak=\"|\".join(ret)\n pp=\"min/avg/max/stddev\" #匹配结果,不同操作系统可能不一样\n '''\n print(\"长度:\"+str(len(ret)))\n print(bak)\n print(bak.find(pp))\n '''\n if(bak.find(pp)!=-1):\n return ip\n\nif __name__=='__main__':\n #pbar = ProgressBar().start()\n main()\n input = input('please input the ip address you wanted.\\n')\n ping(input)","sub_path":"src/fundamental/basic/pingHost.py","file_name":"pingHost.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"1781915","text":"import timeit\nstart = timeit.default_timer()\nimport matplotlib\nimport matplotlib\nmatplotlib.use('qt5agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom backtest import Strategy,Portfolio\nfrom Risk_Parity_v1 import _get_risk_parity_weights\n\nimport extract_data_from_web as ext\n\n\nclass RiskParity(Strategy):\n\n def __init__(self,names,df,date_list):\n self.names = names\n self.df = df\n self.date_list = date_list\n\n def generate_signals(self):\n self.df = self.df.resample('BM').last()\n self.sig = pd.DataFrame(index = self.date_list)\n\n for index,x in enumerate(self.names):\n self.sig[x] = 1\n\n return self.sig\n\n\nclass MarketOnClosePortfolio(Portfolio):\n\n def __init__(self,df,names,sig,date_list,date_list_returns):\n self.df = df\n self.names = names\n self.sig = sig\n self.date_list = date_list\n self.date_list_returns = date_list_returns\n self.positions = self.generate_positions()\n\n\n def generate_positions(self):\n pos = pd.DataFrame(index=self.sig.index)\n weights = self.generate_risk_parity_positions()\n pos = weights.mul(self.sig.values)\n return pos\n\n def generate_risk_parity_positions(self):\n df_m = self.df.resample('BM').last()\n\n import datetime\n from dateutil.relativedelta import relativedelta\n\n weights_all = []\n # cov\n for dts in self.date_list:\n dts = dts + relativedelta(months=-1)\n lb_startdate = dts + relativedelta(months=-6)\n covariances = 252 * self.df[lb_startdate:dts].pct_change(1).dropna().cov().values\n assets_risk_budget = [1.0 / self.df.shape[1]] * self.df.shape[1]\n init_weights = [1.0 / self.df.shape[1]] * self.df.shape[1]\n weights = _get_risk_parity_weights(covariances, assets_risk_budget, init_weights)\n weights_all.append(weights)\n\n df = pd.DataFrame(weights_all, index=date_list)\n return df\n\n def backtest_portfolio(self):\n self.df = self.df.resample('BM').last()\n self.df = self.df.reindex(self.date_list_returns)\n pct_chg = self.df.pct_change().dropna()\n\n rtns = pd.DataFrame(index=self.sig.index)\n rtns = pct_chg.mul(self.positions.values)\n rtns_comb = rtns.sum(axis=1)\n return rtns_comb\n\nif __name__ == '__main__':\n\n df = pd.read_csv('all_asset_class.csv', index_col='Date', parse_dates=True)\n df.drop(['dollar', 'yc', 'senti', '7yTR', '10yTR', '30yTR'], axis=1, inplace=True)\n df.ffill(inplace=True)\n df.columns = ['Crude', 'Gold', 'DM Equity', 'EM Corp', 'EM Equity', 'TSY', '$Corp', '$HY', '$BBB']\n\n stocks = ['Crude', 'Gold', 'DM Equity', 'EM Corp', 'EM Equity', 'TSY', '$Corp', '$HY', '$BBB']\n\n df = df[stocks]\n all_list = []\n for i,x in enumerate(stocks):\n al = str(stocks[i])\n all_list.append(al)\n\n\n df_m = df.resample('BM').last()\n\n # Get the start date\n lookbackperiod = 6 #months\n start_date = pd.date_range(df_m.index[0], periods=lookbackperiod+2, freq='BM')[lookbackperiod+1]\n date_list = df_m[start_date:].index.tolist()\n\n #get separate startdate to calculate returns\n start_date = pd.date_range(df_m.index[0], periods=lookbackperiod + 1, freq='BM')[lookbackperiod]\n date_list_returns = df_m[start_date:].index.tolist()\n\n rp = RiskParity(stocks,df,date_list)\n sig = rp.generate_signals()\n\n port = MarketOnClosePortfolio(df,stocks,sig,date_list,date_list_returns)\n returns = port.backtest_portfolio()\n\n #####Claculate risk adjusted returns\n #get libor index\n lib = ext.convert_libor_to_index()\n lib = lib.reindex(returns.index).pct_change()\n lib.replace(np.nan, 0, inplace=True)\n\n #deduct lib from risk parity returns\n returns = pd.DataFrame(returns - lib)\n returns.columns = ['RiskParity']\n\n #get cummulative product\n cum_returns = np.cumproduct(returns+1)-1\n cum_returns = pd.DataFrame(cum_returns)\n cum_returns.columns = [str(all_list)+str('Risk Parity')]\n\n #reindex all assets\n dfri = df.reindex(cum_returns.index)\n df_chg = dfri.resample('BM').last().pct_change()\n df_chg.replace(np.nan, 0, inplace=True)\n\n #adjust for libor\n for x in df_chg.columns:\n df_chg[x] -= lib\n\n\n df_chg_cum = np.cumproduct(df_chg + 1) - 1\n\n #combine cummulative and monthly returns\n returns = pd.concat([returns,df_chg],axis=1)\n cum_returns = pd.concat([cum_returns, df_chg_cum], axis=1)\n\n #calculate sharpe ratios\n vol = np.std(returns)*np.sqrt(12)\n ann_returns = returns.mean() * 12\n sr = ann_returns.divide(vol.values)\n sr.sort_values(inplace=True)\n print('\\nSharpe ratios')\n print(sr)\n sr.plot(kind='barh')\n\n print('\\nAverage annulised returns')\n ann_returns*=100\n ann_returns.sort_values(inplace=True)\n print(ann_returns)\n\n #print(cum_returns)\n cum_returns.plot()\n plt.title('Allocation returns')\n stop = timeit.default_timer()\n print('Time: ', stop - start)\n\n plt.show()","sub_path":"BT_multiperiod_riskparityAA.py","file_name":"BT_multiperiod_riskparityAA.py","file_ext":"py","file_size_in_byte":5062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"133303649","text":"import argparse\nimport curses\nimport time\nfrom random import randint\nfrom whosnext3000.lib import load_config, get_candidates, draw, increment_student, display_history, display_lists, change_active_list\nfrom whosnext3000.templates import welcome_screen, spin_wheel, selected_screen\n\n\ndef draw_menu(stdscr):\n k = 0\n cursor_x = 0\n cursor_y = 0\n\n # Clear and refresh the screen for a blank canvas\n stdscr.clear()\n stdscr.refresh()\n\n # Start colors in curses\n curses.start_color()\n curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK)\n curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)\n curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_WHITE)\n\n # Hide cursor\n curses.curs_set(0)\n\n start_y = 1\n\n # Loop where k is the last character pressed\n while (k not in [ord('q'), 27]):\n height, width = stdscr.getmaxyx()\n\n keystr = \"Last key pressed: {}\".format(k)[:width-1]\n start_x_keystr = int(\n (width // 2) - (len(keystr) // 2) - len(keystr) % 2)\n\n # Turning on attributes for title\n stdscr.attron(curses.color_pair(1))\n\n if k in [curses.KEY_ENTER, 10, 13]:\n candidates = get_candidates()\n selected_idx = randint(0, len(candidates) - 1)\n stdscr.clear()\n if len(candidates) > 1:\n for wheel_cursor in range(50 - 50 % len(candidates) + selected_idx + 1):\n # stdscr.addstr(0, start_x_keystr, str(selected_idx))\n time.sleep(0.03 * (wheel_cursor // 10))\n draw(stdscr, spin_wheel(\n candidates, wheel_cursor), start_y, width)\n draw(stdscr, selected_screen(\n candidates, selected_idx), start_y, width)\n k = None\n while k not in [curses.KEY_ENTER, 10, 13, 127, 27, ord('q')]:\n k = stdscr.getch()\n if k in [curses.KEY_ENTER, 10, 13]:\n increment_student(candidates[selected_idx])\n k = 0\n elif k == 0:\n stdscr.clear()\n candidates = get_candidates()\n draw(stdscr, welcome_screen(candidates), start_y, width)\n # Wait for next input\n k = stdscr.getch()\n else:\n k = stdscr.getch()\n\n\ndef main():\n config = load_config()\n curses.wrapper(draw_menu)\n\n\ndef run():\n parser = argparse.ArgumentParser(description='Manage students lists')\n parser.add_argument('names', metavar='name', type=str, nargs='*',\n help='student name')\n parser.add_argument('--new-list', dest='new_list', action='store',\n help='name of the list')\n parser.add_argument('--active-list', dest='active_list', action='store',\n help='name of active list')\n parser.add_argument('--lists', action='store_true',\n help='view lists')\n parser.add_argument('--students', action='store_true',\n help='view students in active list')\n\n args = parser.parse_args()\n\n if args.lists:\n display_lists()\n elif args.new_list:\n display_lists()\n elif args.students:\n config = load_config()\n active_list = config['active_list']\n students = config['lists'][active_list]\n display_history(students)\n elif args.active_list:\n change_active_list(args.active_list)\n else:\n return main()\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"whosnext3000/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"2504448","text":"#!/usr/bin/env python\n__all__ = [\n \"tab\",\n \"repos\",\n \"examples\",\n \"apps\",\n \"cli\",\n \"style\",\n \"tests\"]\nimport os\nimport plistlib\n\ndef read(path,default=None):\n if os.path.exists(path):\n return open(path).read().rstrip()\n return default\n\ntab = \"index\"\nHOME=os.environ[\"HOME\"]\n\nsearchpath = []\ncwd = os.getcwd()\n\nclass Repo(object):\n fullname = None\n description = None\n\n def __init__(self, fullname,description):\n self.fullname = fullname\n self.description = description\n\n @property\n def owner(self):\n return self.fullname.split(\"/\")[0]\n\n @property\n def repo(self):\n return self.fullname.split(\"/\")[1]\n\n @property\n def ext(self):\n return self.repo.split(\".\")[-1:][0]\n\n @property\n def ssh_url(self):\n url = \"git@github.com:%s/%s.git\" (user, name)\n if self.org:\n url = \"git@github.com:%s/%s.git\" (self.owner, name)\n return url\n\n @property\n def pypiname(self):\n pkgname = self.repo.split(\".\")[0].lower()\n return pkgname\n\n @property\n def npmname(self):\n if \".py\" in self.repo:\n return\n npmname = self.repo.split(\".\")[0].lower()\n return npmname\n\n def __str__(self):\n return self.repo\n\n def __repr__(self):\n return self.repo\n\nrepos = []\nif \"REPOSLIST\" not in os.environ:\n raise OSError(\"REPOSLIST environment variable NOT DEFINED\")\npath = os.environ[\"REPOSLIST\"]\nif not os.path.exists(path):\n raise OSError(\"%s NOT EXISTS\" % path)\nfor l in read(path).splitlines():\n fullname = l.split(\",\")[0]\n description = l.split(\",\")[1:]\n r = Repo(fullname=fullname,description=description)\n repos.append(r)\n\nrepos = sorted(repos, key=lambda r: r.repo.lower())\n\n# examples = list(filter(lambda org: org.name.find(\"examples\") >= 0, orgs))\nexamples = []\ntests = []\n# Python\npython = list(filter(lambda r: r.ext == \"py\", repos))\n# Apps\napps = list(filter(lambda r: r.ext == \"app\", repos))\ncli = list(filter(lambda r: r.ext == \"cli\", repos))\nstyle = list(filter(lambda r: \".py\" in r.repo, repos))\n\nif __name__ == \"__main__\":\n print(\"repos: %s\" % len(repos))\n print(\"examples: %s\" % len(examples))\n # for e in examples:\n # print(\"%s (%s)\" % (e.name, e.count))\n print(\"%s cli\" % len(cli))\n print(\"%s python\" % len(python))\n print(\"%s style\" % len(style))\n print(\"%s apps\" % len(apps))\n","sub_path":"jinja/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"581933015","text":"__author__ = 'alexandre'\n\nimport os.path as op\nfrom datetime import datetime, timedelta\nfrom collections import Counter\n\nimport dataset\nimport sqlalchemy\n\n\nclass VoterAlreadyVoted(Exception):\n pass\n\n\nclass VoteRoundNotFound(Exception):\n pass\n\n\nclass VoteRoundIsFinished(Exception):\n pass\n\n\nclass VoteRoundAlreadyDone(Exception):\n pass\n\n\nclass VoteRounds(object):\n \"\"\" A class that saves different voting rounds in SQLite. \"\"\"\n\n def __init__(self, db_file_path):\n if not op.exists(db_file_path):\n self._init_database(db_file_path)\n\n self._db = self.get_db_connection(db_file_path)\n\n @staticmethod\n def get_db_connection(db_file_path):\n try:\n db = dataset.connect('sqlite:///{}'.format(db_file_path))\n except:\n raise\n else:\n return db\n\n def _init_database(self, db_file_path):\n db = self.get_db_connection(db_file_path)\n\n vote = db.create_table('vote')\n vote.create_column('round_code', sqlalchemy.String(10))\n vote.create_column('voter', sqlalchemy.String(50))\n vote.create_column('value', sqlalchemy.SmallInteger)\n vote.create_index ('round_code', 'round_code_idx')\n\n vote_round = db.create_table('vote_round', primary_id='code', primary_type='String(10)')\n vote_round.create_column('topic', sqlalchemy.String(200))\n vote_round.create_column('start_date', sqlalchemy.DateTime)\n vote_round.create_column('end_date', sqlalchemy.DateTime)\n vote_round.create_column('is_finished', sqlalchemy.Boolean)\n vote_round.create_column('has_deadline', sqlalchemy.Boolean)\n vote_round.create_column('manager', sqlalchemy.String(50))\n\n # ------------------------------------------------------------------------\n # VOTE ROUNDS\n # ------------------------------------------------------------------------\n def get_all_vote_rounds(self):\n return self._db['vote_round'].all()\n\n def get_all_open_vote_rounds(self):\n vote_rounds = []\n polls = self.get_all_vote_rounds()\n for poll in polls:\n if not self.is_round_finished(poll['code']):\n vote_rounds.append(poll)\n\n return vote_rounds\n\n def find_vote_round(self, round_code):\n vote_round = self._db['vote_round'].find_one(code=round_code)\n if vote_round is None:\n raise VoteRoundNotFound('Could not find a vote round with code {}.'.format(round_code))\n\n return vote_round\n\n def close_vote_round(self, round_code, user_id):\n vote_round = self.find_vote_round(round_code)\n\n if vote_round['manager'] != user_id:\n raise PermissionError('The user {} is not the manager for the vote round {}.'.format(user_id, round_code))\n\n vote_round['is_finished'] = True\n vote_round['end_date'] = datetime.now()\n self._db['vote_round'].upsert(vote_round, ['code'])\n\n def is_round_finished(self, round_code):\n vote_round = self.find_vote_round(round_code)\n\n if vote_round['is_finished']:\n return True\n\n if vote_round['has_deadline']:\n is_late = vote_round['end_date'] < datetime.now()\n if is_late:\n # self.close_vote_round(round_code, user_id)\n return True\n\n return False\n\n def set_round_deadline(self, round_code, hours):\n vote_round = self.find_vote_round(round_code)\n\n vote_round['end_date'] = datetime.now() + timedelta(hours=hours)\n vote_round['has_deadline'] = True\n self._db ['vote_round'].upsert(vote_round, ['code'])\n\n def start_vote_round(self, topic, code, user_id, start_date, end_date=None):\n try:\n _ = self.find_vote_round(code)\n except:\n pass\n else:\n raise VoteRoundAlreadyDone('The vote round with code {} has been already done.'.format(code))\n\n has_deadline = True\n if end_date is None:\n end_date = start_date + timedelta(hours=24)\n has_deadline = False\n\n try:\n result = self._db['vote_round'].insert(dict(topic=topic, code=code, manager=user_id,\n start_date=start_date, end_date=end_date,\n is_finished=False, has_deadline=has_deadline))\n except Exception as exc:\n self._db.rollback()\n raise Exception('Error inserting new vote round `{}`.'.format(code)) from exc\n else:\n return result\n\n def get_round_manager(self, round_code):\n vote_round = self.find_vote_round(round_code)\n return vote_round['manager']\n\n # ------------------------------------------------------------------------\n # VOTES\n # ------------------------------------------------------------------------\n def _check_vote(self, round_code, vote_value):\n if self.is_round_finished(round_code):\n raise VoteRoundIsFinished('The vote round with code {} is already finished.'.format(round_code))\n\n try:\n if int(vote_value) not in (+1, -1, 0):\n raise Exception()\n except:\n raise ValueError('Could not transform vote value `{}` into one of (+1, -1, 0).'.format(vote_value))\n\n def find_vote(self, round_code, voter_name):\n return self._db['vote'].find_one(round_code=round_code, voter=voter_name)\n\n def _insert_new_vote(self, round_code, voter_name, vote_value):\n try:\n result = self._db['vote'].insert(dict(round_code=round_code, voter=voter_name, value=int(vote_value)))\n except Exception as exc:\n self._db.rollback()\n raise Exception('Error inserting new vote for `{}` in round `{}`.'.format(voter_name,\n round_code)) from exc\n else:\n return result\n\n def _update_vote(self, vote, vote_value):\n try:\n vote['value'] = int(vote_value)\n result = self._db['vote'].upsert(vote, ['id'])\n except Exception as exc:\n self._db.rollback()\n raise Exception('Error updating vote for `{}` in round `{}`.'.format(vote['voter'],\n vote['round_code'])) from exc\n else:\n return result\n\n def insert_vote(self, round_code, voter_name, vote_value):\n self._check_vote(round_code, vote_value)\n vote = self.find_vote(round_code, voter_name)\n if vote is None:\n return self._insert_new_vote(round_code, voter_name, int(vote_value))\n else:\n return self._update_vote(vote, int(vote_value))\n\n def get_all_votes(self, round_code):\n return self._db['vote'].find(round_code=round_code)\n\n def get_round_result(self, round_code):\n votes = self.get_all_votes(round_code)\n values = [vote['value'] for vote in votes]\n return Counter(values)","sub_path":"implants/vote_rounds.py","file_name":"vote_rounds.py","file_ext":"py","file_size_in_byte":7092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"633312996","text":"import pandas as pd\nimport matplotlib.pyplot as plt\n\ndataframeTiemposEspera=pd.read_csv(\"schedwaits.dat\", sep=\" \",header=None)\ndataframeTiemposEspera=dataframeTiemposEspera.drop(4, 1)\ndataframeTiemposEspera=dataframeTiemposEspera.T\nprint(\"DataFrame Tiempos Espera\\n\")\nprint(dataframeTiemposEspera)\ndataframeTiemposRetorno=pd.read_csv(\"schedturns.dat\", sep=\" \", header=None)\ndataframeTiemposRetorno=dataframeTiemposRetorno.drop(4, 1)\ndataframeTiemposRetorno=dataframeTiemposRetorno.T\nprint(\"DataFrame Tiempos Retorno\\n\")\nprint(dataframeTiemposRetorno)\ndataframeTiemposRetornoNormalizado=pd.read_csv(\"schednturns.dat\", sep=\" \", header=None)\ndataframeTiemposRetornoNormalizado=dataframeTiemposRetornoNormalizado.drop(4, 1)\nprint(\"DataFrame Tiempos Retorno Normalizado\\n\")\ndataframeTiemposRetornoNormalizado=dataframeTiemposRetornoNormalizado.T\nprint(dataframeTiemposRetornoNormalizado)\naxEspera = plt.gca()\naxEspera.set_title('Tiempos de Espera')\naxEspera.set_ylabel('Promedio Tiempos de espera')\ndataframeTiemposEspera.plot(kind='line',x=0,y=1,ax=axEspera,label=\"FCFS\")\ndataframeTiemposEspera.plot(kind='line',x=0,y=2, color='red', ax=axEspera,label=\"SJF\")\ndataframeTiemposEspera.plot(kind='line',x=0,y=3, color='green',ax=axEspera,label=\"RR1\")\ndataframeTiemposEspera.plot(kind='line',x=0,y=4, color='yellow', ax=axEspera,label=\"RR4\")\naxEspera.set_xlabel('Tiempos de ráfaga')\nplt.show()\naxRetorno = plt.gca()\naxRetorno.set_title('Tiempos de Retorno')\naxRetorno.set_ylabel('Promedio Tiempos de retorno')\ndataframeTiemposRetorno.plot(kind='line', x=0, y=1, ax=axRetorno, label=\"FCFS\")\ndataframeTiemposRetorno.plot(kind='line', x=0, y=2, color='red', ax=axRetorno, label=\"SJF\")\ndataframeTiemposRetorno.plot(kind='line', x=0, y=3, color='green', ax=axRetorno, label=\"RR1\")\ndataframeTiemposRetorno.plot(kind='line', x=0, y=4, color='yellow', ax=axRetorno, label=\"RR4\")\naxRetorno.set_xlabel('Tiempos de ráfaga')\nplt.show()\naxRetornoNormalizado = plt.gca()\naxRetornoNormalizado.set_title('Tiempos de Retorno Normalizado')\naxRetornoNormalizado.set_ylabel('Promedio Tiempos de retorno normalizado')\ndataframeTiemposRetornoNormalizado.plot(kind='line', x=0, y=1, ax=axRetornoNormalizado, label=\"FCFS\")\ndataframeTiemposRetornoNormalizado.plot(kind='line', x=0, y=2, color='red', ax=axRetornoNormalizado, label=\"SJF\")\ndataframeTiemposRetornoNormalizado.plot(kind='line', x=0, y=3, color='green', ax=axRetornoNormalizado, label=\"RR1\")\ndataframeTiemposRetornoNormalizado.plot(kind='line', x=0, y=4, color='yellow', ax=axRetornoNormalizado, label=\"RR4\")\naxRetornoNormalizado.set_xlabel('Tiempos de ráfaga')\nplt.show()\n\n\n\n","sub_path":"schedgraphs.py","file_name":"schedgraphs.py","file_ext":"py","file_size_in_byte":2607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"643804196","text":"from src.solver import solve, equations\n\nnames = list(equations.keys())\n\nprint('Welcome!')\n\nfor number, name in enumerate(names, start=1):\n print('\\t%d: %s' % (number, name))\n\nwhile True:\n choice = input('Tenliyi sec >>> ')\n\n try:\n choice = int(choice)\n except ValueError:\n print('Reqem daxil et')\n continue\n\n try:\n x = solve(names[choice - 1])\n except IndexError:\n print('Sece bilersen %d den %d ye kimi' % (1, len(names)))\n continue\n\n print(x)\n","sub_path":"bin/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"249073739","text":"# ===============================================================================\n#\n# Copyright (C) 2003 Martin Furter \n#\n# This file is part of SvnDumpTool\n#\n# SvnDumpTool is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2, or (at your option)\n# any later version.\n#\n# SvnDumpTool is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with SvnDumpTool; see the file COPYING. If not, write to\n# the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.\n#\n# ===============================================================================\n\nfrom __future__ import print_function\n\nfrom common import *\nfrom node import SvnDumpNode\n\n__doc__ = \"\"\"SvnDumpFile class.\"\"\"\n\n\nclass SvnDumpFile:\n \"\"\"\n A class for reading and writing svn dump files.\n \"\"\"\n\n def __init__(self):\n # states\n self.ST_NONE = 0\n self.ST_READ = 10\n self.ST_EOF = 11\n self.ST_CREATE = 20\n self.ST_WRITE = 21\n\n # state of this SvnDumpFile\n self.__state = self.ST_NONE\n # name of the dump file\n self.__filename = \"\"\n # the file object to read from/write to\n self.__file = None\n # end of file\n self.__file_eof = 0\n # UUID of the repository\n self.__uuid = None\n # curent revision number\n self.__rev_nr = 0\n # date of the revision\n self.__rev_date = (0, 0)\n # start offset of the next revision\n self.__rev_start_offset = 0\n # revision properties\n self.__rev_props = {}\n # nodes of the revision (files, dirs)\n self.__nodes = ListDict()\n # offset of a tag list\n self.__tag_start_offset = 0\n # count lines for debugging\n self.__line__counting = 1\n self.__line_nr = 0\n self.__tag_start_line_nr = 0\n\n def __read_line(self, raiseEof):\n \"\"\"\n Read one line from teh dump file.\n\n @type raiseEof: bool\n @param raiseEof: Raise SvnDumpException when True and EOF occured.\n @rtype: bool, string\n @return: (eof, line), line without LF.\n \"\"\"\n\n line = self.__file.readline()\n if self.__line__counting != 0:\n self.__line_nr = self.__line_nr + 1\n if len(line) != 0:\n return False, line[:-1]\n self.__file_eof = 1\n if not raiseEof:\n return True, \"\"\n raise SvnDumpException(\"unexpected end of file\")\n\n def __read_bin(self, length):\n \"\"\"\n Read some bytes.\n\n @type length: integer\n @param length: Count of bytes to read.\n @rtype: string\n @return: The data read.\n \"\"\"\n\n data = self.__file.read(length)\n if self.__line__counting != 0:\n self.__line_nr = self.__line_nr + data.count(\"\\n\")\n return data\n\n def __skip_bin(self, length):\n \"\"\"\n Skip some bytes.\n\n @type length: integer\n @param length: Count of bytes to skip.\n \"\"\"\n\n if self.__line__counting == 0:\n self.__file.seek(self.__file.tell() + length)\n return\n nBytes = 4096\n while length > 0:\n if length < 4096:\n nBytes = length\n data = self.__file.read(nBytes)\n self.__line_nr = self.__line_nr + data.count(\"\\n\")\n length = length - nBytes\n\n def __skip_empty_line(self):\n \"\"\"\n Read one line from the dump file and check that it is empty.\n \"\"\"\n\n eof, line = self.__read_line(False)\n if eof or len(line) != 0:\n raise SvnDumpException(\"expected empty line, found '%s'\" % line)\n return\n\n def __get_tag(self, raiseEof):\n \"\"\"\n Read a Tag line (name: value).\n\n @type raiseEof: bool\n @param raiseEof: Raise SvnDumpException when True and EOF occured.\n @rtype: list( string )\n @return: A list containing the tag name and value.\n \"\"\"\n\n eof, line = self.__read_line(raiseEof)\n if len(line) == 0:\n return []\n words = line.split(\" \", 1)\n if len(words) != 2:\n raise SvnDumpException(\"illegal Tag line '%s'\" % line)\n return words\n\n def __get_tag_list(self):\n \"\"\"\n Get a list of tags, end is an empty line.\n\n @rtype: dict( string -> string )\n @return: A dict containing the tags.\n \"\"\"\n\n tags = {}\n self.__tag_start_offset = self.__file.tell()\n self.__tag_start_line_nr = self.__line_nr\n tag = self.__get_tag(False)\n while len(tag) == 0:\n if self.__file_eof:\n return tags\n self.__tag_start_offset = self.__file.tell()\n self.__tag_start_line_nr = self.__line_nr\n tag = self.__get_tag(False)\n while len(tag) == 2:\n tags[tag[0]] = tag[1]\n tag = self.__get_tag(True)\n return tags\n\n def __get_prop_list(self):\n \"\"\"\n Get a list of properties.\n\n @rtype: dict( string -> string )\n @return: A dict containing the properties.\n \"\"\"\n\n props = ListDict()\n eof, line = self.__read_line(True)\n while line != \"PROPS-END\":\n # key\n words = line.split()\n if len(words) != 2 or (words[0] != \"K\" and words[0] != \"D\"):\n raise SvnDumpException(\"illegal proprty key ???\")\n key = self.__read_bin(int(words[1]))\n self.__skip_empty_line()\n # value\n value = None\n if words[0] == \"K\":\n eof, line = self.__read_line(True)\n words = line.split()\n if len(words) != 2 or words[0] != \"V\":\n raise SvnDumpException(\"illegal proprty value ???\")\n value = self.__read_bin(int(words[1]))\n self.__skip_empty_line()\n # set property\n props[key] = value\n # next line...\n eof, line = self.__read_line(True)\n return props\n\n def __create_prop_string(self, properties):\n \"\"\"\n Create a string from a dict containing properties.\n\n @type properties: dict( string -> string )\n @param properties: A dict containing the properties.\n @rtype: string\n @return: A string containing the properties.\n \"\"\"\n\n propStr = \"\"\n if properties is not None:\n for key, val in properties.items():\n if val is not None:\n # add/change property\n propStr = propStr + (\"K %d\" % len(key)) + \"\\n\" + key + \"\\n\"\n propStr = propStr + (\"V %d\" % len(val)) + \"\\n\" + val + \"\\n\"\n else:\n # delete property\n propStr = propStr + (\"D %d\" % len(key)) + \"\\n\" + key + \"\\n\"\n propStr = propStr + \"PROPS-END\\n\"\n return propStr\n\n # ------------------------------------------------------------\n # open / create / close\n\n def open(self, filename):\n \"\"\"\n Open a dump file for reading and read the header.\n @type filename: string\n @param filename: Name of an existing dump file.\n \"\"\"\n\n # check state\n if self.__state != self.ST_NONE:\n raise SvnDumpException(\"invalid state %d (should be %d)\" % \\\n (self.__state, self.ST_NONE))\n\n # set parameters\n self.__filename = filename\n\n # open the file for reading\n self.__file = open(filename, \"rb\")\n\n # check that it is a svn dump file\n tag = self.__get_tag(True)\n if tag[0] != \"SVN-fs-dump-format-version:\":\n raise SvnDumpException(\"not a svn dump file ???\")\n if tag[1] != \"2\":\n raise SvnDumpException(\"wrong svn dump file version (expected 2 found %s)\" % (tag[1]))\n self.__skip_empty_line()\n\n # get UUID\n fileoffset = self.__file.tell()\n tag = self.__get_tag(True)\n if len(tag) < 1 or tag[0] != \"UUID:\":\n # back to start of revision\n self.__file.seek(fileoffset)\n self.__uuid = None\n else:\n # set UUID\n self.__uuid = tag[1]\n self.__skip_empty_line()\n\n # done initializing\n self.__rev_start_offset = self.__file.tell()\n self.__state = self.ST_READ\n\n def create_with_rev_0(self, filename, uuid, rev0date):\n \"\"\"\n Create a new dump file starting with revision 0.\n\n @type filename: string\n @param filename: Name of the new dump file.\n @type uuid: string\n @param uuid: UUID of the new dump file or None.\n @type rev0date: string\n @param rev0date: Svn date string for revision 0.\n \"\"\"\n\n # check state\n if self.__state != self.ST_NONE:\n raise SvnDumpException(\"invalid state %d (should be %d)\" % \\\n (self.__state, self.ST_NONE))\n\n # set parameters\n self.__filename = filename\n self.__uuid = uuid\n\n # check rev0date\n rev0date = self.set_rev_date(rev0date)\n\n # open file for writing\n self.__file = open(filename, \"wb\")\n\n # write header and uuid\n self.__file.writelines([\"SVN-fs-dump-format-version: 2\\n\", \"\\n\"])\n if self.__uuid is not None:\n self.__file.writelines([\"UUID: \" + self.__uuid + \"\\n\", \"\\n\"])\n\n # write header and uuid\n self.__file.writelines([\"Revision-number: 0\\n\",\n \"Prop-content-length: 56\\n\",\n \"Content-length: 56\\n\",\n \"\\n\",\n \"K 8\\n\",\n \"svn:date\\n\",\n \"V 27\\n\",\n rev0date + \"\\n\",\n \"PROPS-END\\n\",\n \"\\n\"])\n\n # done initializing\n self.__state = self.ST_CREATE\n\n def create_with_rev_n(self, filename, uuid, firstRevNr):\n \"\"\"\n Create a new dump file.\n\n @type filename: string\n @param filename: Name of the new dump file.\n @type uuid: string\n @param uuid: UUID of the new dump file or None.\n @type firstRevNr: integer\n @param firstRevNr: First revision number (>0).\n \"\"\"\n\n # check state\n if self.__state != self.ST_NONE:\n raise SvnDumpException(\"invalid state %d (should be %d)\" % \\\n (self.__state, self.ST_NONE))\n\n # check firstRevNr\n if firstRevNr < 1:\n raise SvnDumpException(\"invalid firstRevNr %d (should be >= 1)\" % firstRevNr)\n\n # set parameters\n self.__filename = filename\n self.__uuid = uuid\n self.__rev_nr = firstRevNr - 1\n\n # open file for writing\n self.__file = open(filename, \"wb\")\n\n # write header and uuid\n self.__file.writelines([\"SVN-fs-dump-format-version: 2\\n\", \"\\n\"])\n if self.__uuid is not None:\n self.__file.writelines([\"UUID: \" + self.__uuid + \"\\n\", \"\\n\"])\n\n # done initializing\n self.__state = self.ST_CREATE\n\n def create_like(self, filename, srcfile):\n \"\"\"\n Creates this dump file like srcfile.\n\n If the current revision number of srcfile is zero create_with_rev_0()\n is called on this dump file and read_next_rev() is called on srcfile.\n\n If the current revision number of srcdump is greater than zero\n create_with_rev_n() is called.\n\n In both cases True is returned if srcdump contains a revision and\n False if srcdump reached EOF.\n\n @type filename: string\n @param filename: Name of the new dump file.\n @type srcfile: SvnDumpFile\n @param srcfile: A dump file.\n @rtype: bool\n @return: False if EOF occured on srcfile.\n \"\"\"\n\n hasrev = srcfile.has_revision()\n if srcfile.get_rev_nr() == 0:\n # create new dump with revision 0\n self.create_with_rev_0(filename, srcfile.get_uuid(),\n srcfile.get_rev_date_str())\n srcfile.read_next_rev()\n else:\n # create new dump starting with the same revNr as srcdump\n self.create_with_rev_n(filename, srcfile.get_uuid(),\n srcfile.get_rev_nr())\n return srcfile.has_revision()\n\n def close(self):\n \"\"\"\n Close this svn dump file.\n \"\"\"\n\n # close only if state != ST_NONE\n if self.__state != self.ST_NONE:\n self.__file.close()\n self.__line_nr = 0\n self.__file_eof = 0\n self.__filename = None\n self.__uuid = None\n self.__file = None\n self.__rev_props = None\n self.__nodes.clear()\n self.__state = self.ST_NONE\n\n # ------------------------------------------------------------\n # read methods\n\n def read_next_rev(self):\n \"\"\"\n Read the next revision.\n\n @rtype: bool\n @return: False if EOF occured.\n \"\"\"\n\n # check state\n if self.__state != self.ST_READ:\n raise SvnDumpException(\"invalid state %d (should be %d)\" % \\\n (self.__state, self.ST_READ))\n\n # check for end of file\n if self.__file_eof:\n self.__state = self.ST_EOF\n return False\n\n # go to start of revision\n if self.__rev_start_offset != self.__file.tell():\n self.__file.seek(self.__rev_start_offset)\n\n # get rev tags\n tags = self.__get_tag_list()\n self.__rev_nr = int(tags[\"Revision-number:\"])\n\n # read revision properties\n self.__rev_props = self.__get_prop_list()\n self.__skip_empty_line()\n if not self.__rev_props.has_key(\"svn:log\"):\n self.__rev_props[\"svn:log\"] = \"\"\n if not self.__rev_props.has_key(\"svn:author\"):\n self.__rev_props[\"svn:author\"] = \"\"\n if self.__rev_props.has_key(\"svn:date\"):\n self.set_rev_date(self.__rev_props[\"svn:date\"])\n else:\n self.set_rev_date(\"\")\n\n # read nodes (files, dirs)\n self.__nodes.clear()\n # self.nodeList = []\n tags = self.__get_tag_list()\n while len(tags) != 0:\n # check that it's not the next revision\n if tags.has_key(\"Revision-number:\"):\n # go back to start of tag list\n self.__file.seek(self.__tag_start_offset)\n self.__line_nr = self.__tag_start_line_nr\n break\n # get node properties\n if tags.has_key(\"Prop-content-length:\"):\n properties = self.__get_prop_list()\n else:\n properties = None\n # skip node data\n if tags.has_key(\"Text-content-length:\"):\n tags[\"Text-content-length:\"] = int(tags[\"Text-content-length:\"])\n offset = self.__file.tell()\n self.__skip_bin(tags[\"Text-content-length:\"])\n self.__skip_empty_line()\n else:\n offset = 0\n # add node\n path = tags[\"Node-path:\"].lstrip('/')\n action = tags[\"Node-action:\"]\n kind = \"\"\n if tags.has_key(\"Node-kind:\"):\n kind = tags[\"Node-kind:\"]\n node = SvnDumpNode(path, action, kind)\n if properties is not None:\n node.set_properties(properties)\n if tags.has_key(\"Node-copyfrom-path:\"):\n node.set_copy_from(tags[\"Node-copyfrom-path:\"].lstrip('/'),\n int(tags[\"Node-copyfrom-rev:\"]))\n if tags.has_key(\"Text-content-md5:\"):\n md5 = tags[\"Text-content-md5:\"]\n else:\n md5 = \"\"\n if tags.has_key(\"Text-content-length:\"):\n node.set_text_fileobj(self.__file, offset,\n int(tags[\"Text-content-length:\"]),\n md5)\n upath = (action[0].upper(), path)\n self.__nodes[upath] = node\n # next one...\n tags = self.__get_tag_list()\n\n self.__rev_start_offset = self.__file.tell()\n return True\n\n def has_revision(self):\n \"\"\"\n Returns false when EOF occured.\n\n @rtype: bool\n @return: False if EOF occured.\n \"\"\"\n return self.__state == self.ST_READ or self.__state == self.ST_WRITE\n\n def get_uuid(self):\n \"\"\"\n Returns the UUID of this dump file.\n\n @rtype: string\n @return: UUID of this dump file or None if it doesn't have one.\n \"\"\"\n return self.__uuid\n\n def get_rev_nr(self):\n \"\"\"\n Returns the current revision number.\n\n @rtype: integer\n @return: The current revision number.\n \"\"\"\n return self.__rev_nr\n\n def get_rev_date(self):\n \"\"\"\n Returns the date of the current revision as ( time_t, micros ).\n\n @rtype: list( integer )\n @return: The revision date.\n \"\"\"\n return self.__rev_date\n\n def get_rev_date_str(self):\n \"\"\"\n Returns the date of the current revision as string.\n\n @rtype: string\n @return: The revision date.\n \"\"\"\n return self.__rev_props[\"svn:date\"]\n\n def get_rev_author(self):\n \"\"\"\n Returns the author of the current revision.\n\n @rtype: string\n @return: Author of the current revision.\n \"\"\"\n return self.__rev_props[\"svn:author\"]\n\n def get_rev_log(self):\n \"\"\"\n Returns the log message of the current revision.\n\n @rtype: string\n @return: The log message.\n \"\"\"\n return self.__rev_props[\"svn:log\"]\n\n def get_rev_prop_names(self):\n \"\"\"\n Returns a list of revision property names of the current revision.\n\n @rtype: list( string )\n @return: A list of revision property names.\n \"\"\"\n return self.__rev_props.keys()\n\n def has_rev_prop(self, name):\n \"\"\"\n Returns true if the revision has a property with the specified name.\n\n @rtype: bool\n @return: True if the revision has that property.\n \"\"\"\n return self.__rev_props.has_key(name)\n\n def get_rev_props(self):\n \"\"\"\n Returns a dict containing the revision properties.\n\n @rtype: dict( string -> string )\n @return: The revision properties.\n \"\"\"\n return self.__rev_props\n\n def get_rev_prop_value(self, name):\n \"\"\"\n Returns the value of the revision property with the specified name.\n\n @type name: string\n @param name: Name of the property.\n @rtype: string\n @return: The value of the revision property.\n \"\"\"\n return self.__rev_props[name]\n\n def get_node_count(self):\n \"\"\"\n Returns the count of nodes of the current revision.\n\n @rtype: integer\n @return: Node count of the curent revision.\n \"\"\"\n return len(self.__nodes)\n\n def get_node(self, index):\n \"\"\"\n Returns the node at the given index.\n\n @type index: integer\n @param index: Index of the node to return.\n @rtype: SvnDumpNode\n @return: The node at the given index.\n \"\"\"\n return self.__nodes[index]\n\n def get_nodes_by_path(self, path, actions=\"ACDR\"):\n \"\"\"\n Returns a list of nodes matching path and actions.\n\n Actions is a string that may contain one or more of the letters\n A, C, D and R which are the first letters of the actions Add, Change,\n Delete and Replace.\n\n @type path: string\n @param path: Path of the node.\n @type actions: string\n @param actions: Actions to search for.\n \"\"\"\n\n nodes = []\n for a in actions:\n upath = (a, path)\n if self.__nodes.has_key(upath):\n nodes.append(self.__nodes[upath])\n return nodes\n\n def get_nodes_iter(self):\n \"\"\"\n Returns an iterator returning the nodes.\n \"\"\"\n\n return self.__nodes.values()\n\n # ------------------------------------------------------------\n # write methods\n\n def set_rev_date(self, dateStr):\n \"\"\"\n Check a date string, set and return a valid one.\n\n @type dateStr: string\n @param dateStr: A svn date string.\n @rtype: string\n @return: A svn date string.\n \"\"\"\n self.__rev_date = parse_svn_date_str(dateStr)\n self.__rev_props[\"svn:date\"] = create_svn_date_str(self.__rev_date)\n return self.__rev_props[\"svn:date\"]\n\n def set_rev_author(self, author):\n \"\"\"\n Set the author of this revision.\n\n @type author: string\n @param author: The author to set for this revision.\n \"\"\"\n self.__rev_props[\"svn:author\"] = author\n\n def set_rev_log(self, logMsg):\n \"\"\"\n Set the log message of this revision.\n\n @type logMsg: string\n @param logMsg: The log message to set for this revision.\n \"\"\"\n self.__rev_props[\"svn:log\"] = logMsg\n\n def set_rev_prop_value(self, name, value):\n \"\"\"\n Set the value of the revision property with the specified name to the given value.\n\n @type name: string\n @param name: Name of the property.\n @type value: string\n @param value: Value of the property.\n \"\"\"\n if name == \"svn:date\":\n self.set_rev_date(value)\n else:\n self.__rev_props[name] = value\n\n def set_uuid(self, uuid):\n \"\"\"\n Returns the UUID of this dump file.\n\n @type uuid: string\n @param uuid: UUID to set for this dump file (may be None).\n \"\"\"\n self.__uuid = uuid\n\n def add_rev_from_dump(self, dump):\n \"\"\"\n Add the current revision of the specified SvnDumpFile to this one.\n \n @type dump: SvnDumpFile\n @param dump: A dump file.\n \"\"\"\n\n # check of state is done in add_rev\n # add revision and revprops\n self.add_rev(dump.get_rev_props())\n\n # add nodes\n index = 0\n nodeCount = dump.get_node_count()\n while index < nodeCount:\n self.add_node(dump.get_node(index))\n index = index + 1\n\n def add_rev(self, revProps):\n \"\"\"\n Add a new revision to this dump file.\n\n @type revProps: dict( string -> string )\n @param revProps: A dict with revision properties.\n \"\"\"\n\n # check state\n if self.__state != self.ST_WRITE and self.__state != self.ST_CREATE:\n raise SvnDumpException(\"invalid state %d (should be %d or %d)\" % (\n self.__state, self.ST_CREATE, self.ST_WRITE))\n\n # set rev nr and check rev props\n self.__rev_nr = self.__rev_nr + 1\n if not revProps.has_key(\"svn:date\"):\n revProps[\"svn:date\"] = self.set_rev_date(\"\")\n else:\n revProps[\"svn:date\"] = self.set_rev_date(revProps[\"svn:date\"])\n if not revProps.has_key(\"svn:author\"):\n revProps[\"svn:author\"] = \"\"\n if not revProps.has_key(\"svn:log\"):\n revProps[\"svn:log\"] = \"\"\n self.__rev_props = revProps\n\n propStr = self.__create_prop_string(revProps)\n # write revision\n self.__file.writelines([\"Revision-number: %d\\n\" % self.__rev_nr,\n \"Prop-content-length: %d\\n\" % len(propStr),\n \"Content-length: %d\\n\" % len(propStr),\n \"\\n\",\n propStr,\n \"\\n\"])\n\n # we have a revision now\n self.__state = self.ST_WRITE\n\n def add_node(self, node):\n \"\"\"\n Add a node to the current revision.\n\n This method uses SvnDumpNode.write_text_to_file().\n\n @type node: SvnDumpNode\n @param node: The node to add.\n \"\"\"\n\n # check state\n if self.__state != self.ST_WRITE:\n raise SvnDumpException(\"invalid state %d (should be %d)\" % \\\n (self.__state, self.ST_WRITE))\n\n # write the node\n self.__file.write(\"Node-path: \" + node.get_path() + \"\\n\")\n\n # write kind if we know it (cvs2svn emits add's with copy-from\n # without kind so we do this here independent of the action)\n kind = node.get_kind()\n if len(kind) > 0:\n self.__file.write(\"Node-kind: %s\\n\" % kind)\n\n action = node.get_action()\n self.__file.write(\"Node-action: \" + action + \"\\n\")\n if action != \"delete\":\n # copied ?\n if node.get_copy_from_rev() != 0:\n self.__file.write(\"Node-copyfrom-rev: %d\\n\" % \\\n node.get_copy_from_rev())\n self.__file.write(\"Node-copyfrom-path: \" + \\\n node.get_copy_from_path() + \"\\n\")\n # calculate length's of properties text and total\n propstr = self.__create_prop_string(node.get_properties())\n proplen = len(propstr)\n textlen = node.get_text_length()\n if node.has_text():\n totlen = proplen + textlen\n else:\n totlen = proplen\n # write length's of properties text and total\n if proplen > 0:\n self.__file.write(\"Prop-content-length: %d\\n\" % proplen)\n if node.has_text():\n self.__file.write(\"Text-content-length: %d\\n\" % textlen)\n if node.has_md5():\n self.__file.write(\"Text-content-md5: %s\\n\" % node.get_text_md5())\n if proplen > 0 or node.has_text():\n self.__file.write(\"Content-length: %d\\n\" % totlen)\n self.__file.write(\"\\n\")\n # write properties\n if proplen > 0:\n self.__file.write(propstr)\n # write text\n if node.has_text():\n node.write_text_to_file(self.__file)\n self.__file.write(\"\\n\")\n # CR after each node\n self.__file.write(\"\\n\")\n\n\nclass SvnDumpFileWithHistory(SvnDumpFile):\n def __init__(self):\n SvnDumpFile.__init__(self)\n # errors\n self.ERR_REV_DATE_OLDER = 1\n self.ERR_NODE_MD5_FAIL = 2\n self.ERR_NODE_EXISTS = 3\n self.ERR_NODE_NO_PARENT = 4\n self.ERR_NODE_PARENT_NOT_DIR = 5\n self.ERR_NODE_NO_COPY_SRC = 6\n self.ERR_NODE_GONE = 7\n # node history for this\n self.__enable_nodehist = False\n self.__nodehist = {}\n # check actions\n self.__enable_check_node_actions = False\n # check dates\n self.__enable_check_rev_dates = False\n self.__prev_date = (0, 0)\n # check md5 sums\n self.__enable_check_node_md5 = False\n # revision errors\n self.__rev_errors = {}\n\n def set_enable_node_history(self, enable):\n \"\"\"\n Set the check md5 sums flag to the given value.\n\n @type docheck: bool\n @param docheck: New value for the flag.\n \"\"\"\n\n self.__enable_nodehist = enable\n\n def set_check_actions(self, docheck):\n \"\"\"\n Set the check actions flag to the given value.\n\n @type docheck: bool\n @param docheck: New value for the flag.\n \"\"\"\n\n self.__enable_check_node_actions = docheck\n # checking node actions requires keeping node history,\n # but it can also be enabled otherwise, so don't disable\n # it if not checking node actions\n if self.__enable_check_node_actions:\n self.set_enable_node_history(True)\n\n def set_check_dates(self, docheck):\n \"\"\"\n Set the check dates flag to the given value.\n\n @type docheck: bool\n @param docheck: New value for the flag.\n \"\"\"\n\n self.__enable_check_rev_dates = docheck\n\n def set_check_md5(self, docheck):\n \"\"\"\n Set the check md5 sums flag to the given value.\n\n @type docheck: bool\n @param docheck: New value for the flag.\n \"\"\"\n\n self.__enable_check_node_md5 = docheck\n\n def get_rev_errors(self, revnr=None):\n \"\"\"\n Returns a list of the dump errors for the given revision. (Obviously)\n It will only report errors enabled by set_check_xxxx.\n\n @type revnr: int\n @param revnr: (Optional) Number of desired revision\n @rtype: list of lists (of lists)\n @return: Each element in the list is a list representing one error,\n with the following members:\n - The error type (SvnDumpFile.ERR_XXXX)\n - A list of error information:\n - for ERR_REV_DATE_OLDER: [ revdatestr, prevdatestr ]\n - for ERR_NODE_MD5_FAIL: [ path, md5calc, md5node ]\n - for ERR_NODE_XXXX: [ path, action, ... ]\n - for ERR_NODE_NO_PARENT: [ path, action, parentpath ]\n - for ERR_NODE_PARENT_NOT_DIR: [ path, action, parentpath ]\n - for ERR_NODE_NO_COPY_SRC: [ path, action, cfrev, cfpath ]\n Errors in this list are guaranteed to be in order of revision\n errors, then node errors in the same order as when iterated via\n get_nodes_iter().\n \"\"\"\n\n # use the current rev number if not gien\n if revnr is None:\n revnr = self.get_rev_nr()\n if self.__rev_errors.has_key(revnr):\n return self.__rev_errors[revnr]\n else:\n return None\n\n def __add_rev_error(self, revnr, errinfo):\n \"\"\"\n Adds the given error information to the ListDict for the given revision\n\n @type revnr: int\n @param revnr: (Optional) Number of desired revision\n @type errinfo: list\n @param errinfo: Information about the error\n \"\"\"\n\n if self.__rev_errors.has_key(revnr):\n self.__rev_errors[revnr].append(errinfo)\n else:\n self.__rev_errors[revnr] = [errinfo]\n\n def __check_rev_dates(self):\n \"\"\"\n Check the date for the current revision\n \"\"\"\n if self.__enable_check_rev_dates:\n date = self.get_rev_date()\n if date < self.__prev_date:\n self.__add_rev_error(self.get_rev_nr(),\n [self.ERR_REV_DATE_OLDER, [self.get_rev_date_str(),\n create_svn_date_str(self.__prev_date)]], )\n self.__prev_date = date\n\n def __check_node_md5(self, node):\n \"\"\"\n Check the md5sum for the current node\n\n @type node: SvnDumpNode\n @param node: Current node\n \"\"\"\n if self.__enable_check_node_md5 and node.has_text():\n md = sdt_md5()\n handle = node.text_open()\n data = node.text_read(handle)\n n = 0\n while len(data) > 0:\n n = n + len(data)\n md.update(data)\n data = node.text_read(handle)\n node.text_close(handle)\n md5sum = md.hexdigest()\n if node.get_text_md5() != md5sum:\n self.__add_rev_error(self.get_rev_nr(),\n [self.ERR_NODE_MD5_FAIL,\n [node.get_path(), md5sum, node.get_text_md5()]], )\n\n def __nodehist_init(self):\n \"\"\"\n Initialize the node history\n \"\"\"\n\n # the root always exists and is a directory\n self.__nodehist = {\"\": [\"D\", [0, 999999999]]}\n self.__rev_errors.clear()\n\n def nodehist_get_kind(self, revnr, path):\n \"\"\"\n Returns the kind of a node if it exists, else None.\n\n @type revnr: int\n @param revnr: Current revision number.\n @type path: string\n @param path: Path of a node.\n @rtype: string\n @return: \"D\" for dirs, \"F\" for files or None.\n \"\"\"\n return self.__nodehist_get_kind(revnr, path)\n\n def __nodehist_get_kind(self, revnr, path):\n \"\"\"\n Returns the kind of a node if it exists, else None.\n\n @type revnr: int\n @param revnr: Current revision number.\n @type path: string\n @param path: Path of a node.\n @rtype: string\n @return: \"D\" for dirs, \"F\" for files or None.\n \"\"\"\n if not self.__nodehist.has_key(path):\n return None\n nodehist = self.__nodehist[path]\n i = self.__nodehist_get_rev_index(nodehist, revnr)\n if i is None:\n return None\n return nodehist[0][0]\n\n def __nodehist_get_rev_index(self, nodehist, revnr):\n \"\"\"\n Returns the index into the node history or None.\n\n @type nodehist: list\n @param nodehist: History of a node.\n @type revnr: int\n @param revnr: Current revision number.\n \"\"\"\n i = len(nodehist) - 1\n while i > 0 and revnr < nodehist[i][0]:\n i -= 1\n if i == 0:\n return None\n if revnr > nodehist[i][1] >= 0:\n return None\n return i\n\n def __nodehist_add_node(self, revnr, node):\n \"\"\"\n Adds a node to the history, recursively if it has copy-from path/rev.\n\n @type revnr: int\n @param revnr: Current revision number.\n @type node: SvnDumpNode\n @param node: Node to add.\n \"\"\"\n path = node.get_path()\n if not self.__nodehist.has_key(path):\n # create revision list for path\n kind = \"D\"\n if node.get_kind() == \"file\":\n kind = \"F\"\n self.__nodehist[path] = [kind]\n # add revision range\n self.__nodehist[path].append([revnr, -1])\n kind = self.__nodehist[path][0][0]\n # continue only if it's a dir with copy-from\n if kind == \"F\" or not node.has_copy_from():\n return\n # recursive copy\n cfpath = node.get_copy_from_path() + \"/\"\n cfpathlen = len(cfpath)\n cfrev = node.get_copy_from_rev()\n path += \"/\"\n for cfnodepath in self.__nodehist.keys()[:]:\n if cfnodepath.startswith(cfpath):\n cfnodehist = self.__nodehist[cfnodepath]\n i = self.__nodehist_get_rev_index(cfnodehist, cfrev)\n if i is not None:\n npath = path + cfnodepath[cfpathlen:]\n # add new path\n if not self.__nodehist.has_key(npath):\n # create revision list for npath\n kind = \"D\"\n if node.get_kind() == \"file\":\n kind = \"F\"\n self.__nodehist[npath] = [cfnodehist[0]]\n # add revision range\n self.__nodehist[npath].append([revnr, -1])\n\n def __nodehist_delete_node(self, revnr, node):\n \"\"\"\n Deletes a node from the history, recursively if it is a directory.\n\n @type revnr: int\n @param revnr: Current revision number.\n @type node: SvnDumpNode\n @param node: Node to add.\n \"\"\"\n # set end revision\n path = node.get_path()\n self.__nodehist[path][-1][1] = revnr - 1\n kind = self.__nodehist[path][0][0]\n # continue only if it's a dir\n if kind == \"F\":\n return\n # recursive delete\n path += \"/\"\n for nodepath in self.__nodehist.keys()[:]:\n if nodepath.startswith(path):\n nodehist = self.__nodehist[nodepath]\n if nodehist[-1][1] == -1:\n nodehist[-1][1] = revnr - 1\n\n def __nodehist_process_node(self, node):\n \"\"\"\n Checks the action of a node and keeps it's history.\n\n @type node: SvnDumpNode\n @param node: Current node.\n \"\"\"\n if not self.__enable_nodehist:\n return\n revnr = self.get_rev_nr()\n path = node.get_path()\n action = node.get_action()\n kind = self.__nodehist_get_kind(revnr, path)\n err = False\n if action == \"add\":\n if self.__enable_check_node_actions:\n # path must not exist\n if kind is not None:\n self.__add_rev_error(revnr, [self.ERR_NODE_EXISTS,\n [path, action]], )\n err = True\n else:\n # parent must be a dir\n slash = path.rfind(\"/\")\n if slash > 0:\n ppath = path[:slash]\n pkind = self.__nodehist_get_kind(revnr, ppath)\n if pkind is None:\n self.__add_rev_error(revnr,\n [self.ERR_NODE_NO_PARENT,\n [path, action, ppath]], )\n err = True\n elif pkind != \"D\":\n self.__add_rev_error(revnr,\n [self.ERR_NODE_PARENT_NOT_DIR,\n [path, action, ppath]], )\n err = True\n # copy-from must exist\n if node.has_copy_from():\n cfrev = node.get_copy_from_rev()\n cfpath = node.get_copy_from_path()\n if self.__nodehist_get_kind(cfrev, cfpath) is None:\n self.__add_rev_error(revnr,\n [self.ERR_NODE_NO_COPY_SRC,\n [path, action, cfrev, cfpath]], )\n err = True\n if not err or self.__state == self.ST_WRITE:\n self.__nodehist_add_node(revnr, node)\n elif action == \"delete\":\n if self.__enable_check_node_actions:\n # path must exist\n if kind is None:\n self.__add_rev_error(revnr,\n [self.ERR_NODE_GONE, [path, action]], )\n err = True\n if not err or self.__state == self.ST_WRITE:\n self.__nodehist_delete_node(revnr, node)\n else:\n if self.__enable_check_node_actions:\n # path must exist\n if kind is None:\n self.__add_rev_error(revnr,\n [self.ERR_NODE_GONE, [path, action]], )\n err = True\n # replace = delete & add; changes can be ignored\n if action == \"replace\" and node.has_copy_from():\n if not err or self.__state == self.ST_WRITE:\n self.__nodehist_delete_node(revnr, node)\n self.__nodehist_add_node(revnr, node)\n\n def open(self, filename):\n \"\"\"\n Open a dump file for reading and read the header.\n @type filename: string\n @param filename: Name of an existing dump file.\n \"\"\"\n\n SvnDumpFile.open(self, filename)\n self.__nodehist_init()\n\n def create_with_rev_0(self, filename, uuid, rev0date):\n \"\"\"\n Create a new dump file starting with revision 0.\n\n @type filename: string\n @param filename: Name of the new dump file.\n @type uuid: string\n @param uuid: UUID of the new dump file or None.\n @type rev0date: string\n @param rev0date: Svn date string for revision 0.\n \"\"\"\n\n SvnDumpFile.create_with_rev_0(self, filename, uuid, rev0date)\n self.__nodehist_init()\n\n def create_with_rev_n(self, filename, uuid, firstRevNr):\n \"\"\"\n Create a new dump file.\n\n @type filename: string\n @param filename: Name of the new dump file.\n @type uuid: string\n @param uuid: UUID of the new dump file or None.\n @type firstRevNr: integer\n @param firstRevNr: First revision number (>0).\n \"\"\"\n\n SvnDumpFile.create_with_rev_n(self, filename, uuid, firstRevNr)\n self.__nodehist_init()\n\n def close(self):\n \"\"\"\n Close this svn dump file.\n \"\"\"\n\n SvnDumpFile.close(self)\n # +++ maybe close should call a protected _close() function which\n # does this here? (clearing things too often doesn't hurt too much)\n self.__nodehist = {}\n self.__rev_errors.clear()\n self.__prev_date = (0, 0)\n\n def read_next_rev(self):\n \"\"\"\n Read the next revision.\n\n @rtype: bool\n @return: False if EOF occured.\n \"\"\"\n\n SvnDumpFile.read_next_rev(self)\n self.__check_rev_dates()\n for node in self.get_nodes_iter():\n self.__check_node_md5(node)\n self.__nodehist_process_node(node)\n\n def add_rev(self, revProps):\n \"\"\"\n Add a new revision to this dump file.\n\n @type revProps: dict( string -> string )\n @param revProps: A dict with revision properties.\n \"\"\"\n\n SvnDumpFile.add_rev(self, revProps)\n self.__check_rev_dates()\n\n def add_node(self, node):\n \"\"\"\n Add a node to the current revision.\n\n This method uses SvnDumpNode.write_text_to_file().\n\n @type node: SvnDumpNode\n @param node: The node to add.\n \"\"\"\n\n SvnDumpFile.add_node(self, node)\n # self.__check_node_md5() # here for completeness, but redundant!\n self.__nodehist_process_node(node)\n","sub_path":"svndump/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":42066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"70798804","text":"'''\r\n\tIBM data :\r\n\t\t1 1 0\r\n\t\t1 1 9\r\n\t\t1 1 4\r\n\t\t2 2 3\r\n\t\t2 2 5\r\n\t\t .\r\n\t\t .\r\n\t\t .\r\n\tconvert it into:\r\n\t\t0 9 4\r\n\t\t3 5\r\n\t\t .\r\n\t\t .\r\n\t\t .\r\n\tusage:\r\n\t\t>>python convert_forfp.py (input file)\r\n\r\n\t\tinput file:IBM data\r\n'''\r\nimport sys\r\nimport writefile\r\n\r\n#init\r\ndata=[]\r\ntemp = []\r\ndout = []\r\nout = []\r\n\r\n#check argument\r\nif len(sys.argv) != 2:\r\n\tprint('usage:python convert_forfp.py (input file)')\r\n\tsys.exit()\r\n\r\n#open input file and store in data as [['1','1','4'],['1','1','3'],...]\r\nwith open(sys.argv[1]) as f:\r\n\tfor line in f:\r\n\t\tdata.append([row for row in line.strip().split()])\r\n\r\n#convert [['1','1','4'],['1','1','3'],...] into [[1,4],[1,3],...]\r\nfor x in range(len(data)):\r\n\tfor y in range(1,3):\r\n\t\ttemp.append(int(data[x][y]))\r\n\tdout.append(temp)\r\n\ttemp=[]\r\n\r\n#combine the same id in one list\r\nid=dout[0][0]\r\nfor i in range(len(dout)):\r\n\tif dout[i][0] == id:\r\n\t\ttemp.append(dout[i][1])\r\n\telse:\r\n\t\tid=dout[i][0] #next id\r\n\t\tout.append(temp)\r\n\t\ttemp=[]\r\n\t\ttemp.append(dout[i][1])\r\nout.append(temp)\r\n\r\nwritefile.WF(out,'IBM_FPtransaction2')\r\n","sub_path":"project1/convert_forfp.py","file_name":"convert_forfp.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"640668242","text":"import random\r\n# genero una lista con los valores del 0 al 250\r\na = range(0,251)\r\nprint(a)\r\n#reordeno lista aleatoriamente para obtener los nuevos indices\r\nrandom.shuffle(a)\r\nprint(a)\r\n#abro el archivo que contiene los datos a ser ordenados\r\narchi = open(\"C:/Users/Casa/Desktop/datos.txt\",\"r\")\r\n#lista = range(1,251)\r\ni = 0\r\nfor linea in archi.readlines():\r\n lista[a[i]] = linea\r\n i = i + 1\r\n\r\narchi.close()\r\n\r\n#gusdo la lista con los datos ordenadas en un nuevo archivo datosAleatorios.txt\r\narchivo = open(\"C:/Users/Casa/Desktop/datosAleatorios.txt\",\"wb\")\r\n\r\nfinal_de_archivo = archivo.tell()\r\narchivo.writelines(lista)\r\narchivo.seek(final_de_archivo)\r\narchivo.close()","sub_path":"aleatorios.py","file_name":"aleatorios.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"229962206","text":"from collections import Counter\n\nfrom qualifier.input_data import InputData\nfrom qualifier.output_data import OutputData\nfrom qualifier.schedule import Schedule\nfrom qualifier.strategy import Strategy\n\n\nclass Eliot(Strategy):\n name = 'Eliot'\n\n def solve(self, input: InputData) -> OutputData:\n all_streets = [car.path for car in input.cars]\n all_streets = [item for sublist in all_streets for item in sublist]\n counted = Counter(all_streets)\n priority = {k: v for k, v in sorted(counted.items(), key=lambda item: item[1], reverse=True)}\n\n instersections = dict()\n\n for street, count in priority.items():\n if street.end not in instersections:\n instersections[street.end] = [(street.name, min(input.duration, count))]\n else:\n if street.name not in instersections[street.end]:\n instersections[street.end] = instersections[street.end] + [\n (street.name, min(input.duration, count))]\n\n schedules = []\n for intersection, streets in instersections.items():\n schedule = Schedule(intersection, [(street[0], street[1]) for street in streets])\n schedules.append(schedule)\n return OutputData(tuple(schedules))\n","sub_path":"qualifier/strategies/Eliot.py","file_name":"Eliot.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"373004946","text":"# -*- coding: utf-8 -*-\n\"\"\"\n得到一个指数下面所有的股票信息\n\"\"\"\nimport futuquant as ft\nfrom pymongo import MongoClient\nimport datetime\n\n\ndef enum_all_index(ip, port):\n quote_ctx = ft.OpenQuoteContext(ip, port)\n\n ret, data_frame = quote_ctx.get_stock_basicinfo(market=ft.Market.SH, stock_type=ft.SecurityType.IDX)\n data_frame.to_csv(\"index_sh.txt\", index=True, sep=' ', columns=['code', 'name'])\n print('market SH index data saved!')\n\n ret, data_frame = quote_ctx.get_stock_basicinfo(market=ft.Market.SZ, stock_type=ft.SecurityType.IDX)\n data_frame.to_csv(\"index_sz.txt\", index=True, sep=' ', columns=['code', 'name'])\n print('market SZ index data saved!')\n\n ret, data_frame = quote_ctx.get_stock_basicinfo(market=ft.Market.HK, stock_type=ft.SecurityType.IDX)\n data_frame.to_csv(\"index_hk.txt\", index=True, sep=' ', columns=['code', 'name'])\n print('market HK index data saved!')\n\n ret, data_frame = quote_ctx.get_stock_basicinfo(market=ft.Market.US, stock_type=ft.SecurityType.IDX)\n data_frame.to_csv(\"index_us.txt\", index=True, sep=' ', columns=['code', 'name'])\n print('market US index data saved!')\n\n quote_ctx.close()\n\n\ndef get_index_stocks(ip, port, code):\n quote_ctx = ft.OpenQuoteContext(ip, port)\n ret, data_frame = quote_ctx.get_plate_stock(code)\n quote_ctx.close()\n return ret, data_frame\n\ndef insert_stock_list(market_each_zhishu_list,stock_list,db):\n\t#print(\"type stock_list['stock_name']:\",type(stock_list[0]))\n\t#print(\"type stock_list['stock_name']:\",stock_list[0])\n\t#print(\"type stock_list['stock_name']:\",type(stock_list[1]) )\n\t#print(\"type stock_list['stock_name']:\",stock_list[2])\n\tmarket_each_zhishu_list.remove({})\n\tfor cur,k in stock_list[1]['stock_name'].items():\n\t\tif market_each_zhishu_list.find_one({\"stock_name\":stock_list[1]['stock_name'][cur]}) == None:\n\t\t\tprint(\"**** not exist stock_name:\",stock_list[1]['stock_name'][cur])\n\t\t\t#print(\"not exist:\",market_each_zhishu_list.find_one({\"stock_name\":stock_list[1]['stock_name'][cur]}))\n\t\t\tmarket_each_zhishu_list.insert({\"code\":stock_list[1]['code'][cur],\"lot_size\":str(stock_list[1]['lot_size'][cur]),\"stock_name\":stock_list[1]['stock_name'][cur],\"stock_owner\":stock_list[1]['stock_owner'][cur],\"stock_child_type\":stock_list[1]['stock_child_type'][cur],\"stock_type\":stock_list[1]['stock_type'][cur],\"list_time\":stock_list[1]['list_time'][cur],\"stock_id\":str(stock_list[1]['stock_id'][cur])})\n\t\telse:\n\t\t\tprint(\"exitst stock_name:\",stock_list[1]['stock_name'][cur])\n\n\tprint(\"sucess insert_stock_list success get stock data \")\n\ndef diff_type_of_zhishu(code_name,db,type):\n\thead = \"code\"\n\tif type == 1:\n\t\thead = head + \"_50_\"\n\telif type ==2:\n\t\thead = head + \"_100_\"\n\telif type ==3:\n\t\thead = head + \"_300_\"\n\telif type ==4:\n\t\thead = head + \"_500_\"\n\telif type ==5:\n\t\thead = head + \"_chuangye_\"\n\telif type==6:\n\t\thead = head + \"_shanghai_xiaofei\"\n\telif type==7:\n\t\thead = head + \"_hk_zhishu\"\n\telif type==8:\n\t\thead = head + \"_usa_biaopu500\"\n\telif type==9:\n\t\thead = head + \"_1000\"\n\telif type==10:\n\t\thead = head + \"_hk_china_company\"\n\n\tnowTime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n\tprint(\"head:\",head,\" code_name:\",code_name,\" nowTime:\",nowTime)\n\tstocklist_50 = get_index_stocks(api_ip, api_port, code_name)\n\tnew_stock_50 = head + code_name.replace(\".\",\"\")\n\tmarket_each_zhishu_list = db[new_stock_50]\n\tinsert_stock_list(market_each_zhishu_list,stocklist_50,db)\n\nif __name__ == \"__main__\":\n\tapi_ip = '127.0.0.1' #''119.29.141.202'\n\tapi_port = 11111\n\t# enum_all_index(api_ip, api_port)\n\tconn = MongoClient('127.0.0.1', 27017)\n\tdb = conn.market\n\n\tprint(\"上证50指数======start=======\")\n\tstock_50 = 'SH.000016'\n\tdiff_type_of_zhishu(stock_50,db,1)\n\tprint(\"上证50指数======end=======\")\n\n\tprint(\"中证100指数======start=======\")\n\tstock_100 = 'SH.000903'\n\tdiff_type_of_zhishu(stock_100,db,2)\n\n\tprint(\"沪深300指数======start=======\")\n\tstock_300 = 'SZ.399300'\n\tdiff_type_of_zhishu(stock_300,db,3)\n\n\tprint(\"中证500指数======start=======\")\n\tstock_500 = 'SH.000905'\n\tdiff_type_of_zhishu(stock_500,db,4)\n\n\tprint(\"创业板======start=======\")\n\tstock_chuangye = 'SZ.399006'\n\tdiff_type_of_zhishu(stock_chuangye,db,5)\n\n\tprint(\"上海消费======start=======\")\n\tstock_shanghai_xiaofei = 'SH.000036'\n\tdiff_type_of_zhishu(stock_shanghai_xiaofei,db,6)\n\n\tprint(\"香港恒生指数======start=======\")\n\tstock_hk_zhishu = 'HK.800000'\n\tdiff_type_of_zhishu(stock_hk_zhishu,db,7)\n\n\tprint(\"香港中国企业指数======start=======\")\n\tstock_hk_zhishu = 'HK.800100'\n\tdiff_type_of_zhishu(stock_hk_zhishu,db,10)\n\n\tprint(\"标普500指数======start=======\")\n\tstock_usa_zhishu = 'US..INX'\n\tdiff_type_of_zhishu(stock_usa_zhishu,db,8)\n\n\tprint(\"中证1000指数======start=======\")\n\tstock_1000_zhishu = 'SH.000852'\n\tdiff_type_of_zhishu(stock_1000_zhishu,db,9)\n\tprint(\"====cacl end =====\")\n\n\t'''\n\t#上证50\n\tstock_50 = 'SH.000016'\n\tstocklist_50 = get_index_stocks(api_ip, api_port, stock_50)\n\tnew_stock_50 = \"stock_list_50_\" + stock_50.replace(\".\",\"\")\n\tmarket_list_coll = db[new_stock_50]\n\tinsert_stock_list(market_list_coll,stocklist_50)\n\n\t#创业板\n\t#get stock list\n\tchuanye_stock = 'SZ.399006'\n\tchuangye_stocklist = get_index_stocks(api_ip, api_port, chuanye_stock)\n\t#choose coll\n\tchuanye_new_stock = \"stock_list_chuanye_\" +chuanye_stock.replace(\".\",\"\")\n\tchuanye_market_list_coll = db[chuanye_new_stock]\n\t#insert into mongo\n\tinsert_stock_list(chuanye_market_list_coll,chuangye_stocklist)\n\n\t#SZ.399300 沪深300\n\thusheng_stock = 'SZ.399300'\n\thusheng_stocklist = get_index_stocks(api_ip, api_port, husheng_stock)\n\n\thusheng_new_stock = \"stock_list_husheng300_\" +husheng_stock.replace(\".\",\"\")\n\thusheng_market_list_coll = db[husheng_new_stock]\n\n\tinsert_stock_list(husheng_market_list_coll,husheng_stocklist)\n\t\n\t#SH.000905 中证500\n\tstock_500 ='SH.000905'\n\tstocklist_500 = get_index_stocks(api_ip, api_port, stock_500)\n\n\tnew_stock_500 = \"stock_list_500_\" +stock_500.replace(\".\",\"\")\n\tmarket_list_coll_500 = db[new_stock_500]\n\n\tinsert_stock_list(market_list_coll_500,stocklist_500)\n\t\n\t#SH.000903 中证100\n\tstock_100 ='SH.000903'\n\tstocklist_100 = get_index_stocks(api_ip, api_port, stock_100)\n\t\n\tnew_stock_100 = \"stock_list_100_\" +stock_100.replace(\".\",\"\")\n\tmarket_list_coll_100 = db[new_stock_100]\n\n\tinsert_stock_list(market_list_coll_100,stocklist_100)\n\t'''\n\n\n\n #print('SZ.399006 创业板指\\n')\n #print(get_index_stocks(api_ip, api_port, 'SZ.399006'))\n\n #print('HK.800000 恒生指数 \\n')\n #print(get_index_stocks(api_ip, api_port, 'HK.800000'))\n\n #print('US..DJI 道琼斯指数\\n')\n #print(get_index_stocks(api_ip, api_port, 'US..DJI'))\n","sub_path":"src/marcket_stock_list/market_list.py","file_name":"market_list.py","file_ext":"py","file_size_in_byte":6588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"343942238","text":"#!/usr/bin/env python\nimport rospy\nfrom styx_msgs.msg import TrafficLight\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport cv2\n\nclass TLClassifier(object):\n def __init__(self, site):\n self.is_site = site # Gets value from config file\n # Load classifier\n self.current_light = TrafficLight.UNKNOWN\n file_path = os.path.dirname(os.path.abspath(__file__))\n if self.is_site:\n model_path = os.path.join(file_path, 'models', 'ssd_mobilenet_real.pb')\n else:\n model_path = os.path.join(file_path, 'models', 'ssd_mobilenet_sim.pb')\n rospy.logwarn(\"model_path={}\".format(model_path))\n \n self.detection_graph = tf.Graph()\n with self.detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(model_path, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n self.image_tensor = self.detection_graph.get_tensor_by_name('image_tensor:0')\n self.d_boxes = self.detection_graph.get_tensor_by_name('detection_boxes:0')\n self.d_scores = self.detection_graph.get_tensor_by_name('detection_scores:0')\n self.d_classes = self.detection_graph.get_tensor_by_name('detection_classes:0')\n self.num_d = self.detection_graph.get_tensor_by_name('num_detections:0')\n \n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n self.sess = tf.Session(graph=self.detection_graph, config=config)\n \n def get_classification(self, image):\n \"\"\"Determines the color of the traffic light in the image\n\n Args:\n image (cv::Mat): image containing the traffic light\n\n Returns:\n int: ID of traffic light color (specified in styx_msgs/TrafficLight)\n\n \"\"\"\n # Implement light color prediction\n image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n image_rescale = cv2.resize(src=image_rgb, dsize=(256, 256))\n # Expand dimension since the model expects image to have shape [1, None, None, 3].\n img_expanded = np.expand_dims(image_rescale, axis=0) \n with self.detection_graph.as_default():\n (boxes, scores, classes, num) = self.sess.run(\n [self.d_boxes, self.d_scores, self.d_classes, self.num_d],\n feed_dict={self.image_tensor: img_expanded})\n\n # boxes = np.squeeze(boxes)\n scores = np.squeeze(scores)\n classes = np.squeeze(classes).astype(np.int32)\n \n if scores[0] > 0.6: \n if classes[0] == 1:\n #rospy.loginfo(str(scores[0])+' : GREEN Light')\n return TrafficLight.GREEN\n elif classes[0] == 2:\n #rospy.loginfo(str(scores[0])+' : RED Light')\n return TrafficLight.RED\n elif classes[0] == 3:\n #rospy.loginfo(str(scores[0])+' : YELLOW Light')\n return TrafficLight.YELLOW\n else:\n return TrafficLight.UNKNOWN\n","sub_path":"ros/src/tl_detector/light_classification/tl_classifier.py","file_name":"tl_classifier.py","file_ext":"py","file_size_in_byte":3142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"281740383","text":"import timeit\nimport numpy as np\nfrom time import time as now\nimport sys\n\n\ndef time_once(code, n=1):\n ''' Measures execution time of code (best of 3).\n\n :param code: Code string or callable.\n :param n: Number of times to repeat execution (n x 3).\n\n :returns: The best execution time.\n '''\n times = min(timeit.Timer(code).repeat(3, n))\n\n return np.array(times)/n\n\n\nclass LRUCache():\n ''' Given a function and LRU caching implementation,\n caches the results of the function.\n\n :ivar impl: LRU cache implementation, for instance \\\n `functools.lru_cache`.\n :ivar func: The function to cache.\n :ivar maxsize: The size of the cache.\n :ivar typed: Determines whether a distinction is \\\n made between arguments of different types.\n :ivar cached: The cached function.\n\n >>> from dautils import perf\n >>> from functools import lru_cache\n >>> cache = perf.LRUCache(lru_cache, lambda x: x)\n >>> cache.cache()\n >>> cache.cached(1)\n 1\n >>> cache.cached(1)\n 1\n >>> cache.hits_miss()\n 1.0\n '''\n def __init__(self, impl, func,\n maxsize=128, typed=False):\n '''\n\n :param impl: LRU cache implementation, for instance \\\n functools.lru_cache.\n :param func: The function to cache.\n :param maxsize: The size of the cache.\n :param typed: Determines whether a distinction is \\\n made between arguments of different types.\n '''\n self.impl = impl\n self.func = func\n self.maxsize = maxsize\n self.typed = typed\n self.cached = None\n self.info = None\n\n def cache(self):\n ''' Caches the function. '''\n self.cached = self.impl(self.maxsize,\n self.typed)(self.func)\n\n def clear(self):\n ''' Clears the cache. '''\n if self.cached:\n self.cached.cache_clear()\n self.info = None\n\n def get_info(self):\n ''' Gets cache info. '''\n if self.cached:\n self.info = self.cached.cache_info()\n\n def hits_miss(self):\n ''' Calculates hits/miss ratio.\n In a muti-threaded environment, the calculation is approximate.\n\n :returns: The hits/miss ratio.\n '''\n if self.info is None:\n self.get_info()\n\n if self.info.misses == 0:\n return None\n\n return self.info.hits/self.info.misses\n\n\nclass StopWatch():\n ''' A simple stopwatch, which has a context manager.\n\n :ivar elapsed: Elapsed time in seconds.\n\n >>> from dautils import perf\n >>> with perf.StopWatch() as sw:\n ... pass\n ...\n >>> sw.elapsed\n 7.867813110351562e-06\n '''\n def __enter__(self):\n self.begin = now()\n self.elapsed = 0\n return self\n\n def __exit__(self, *args):\n self.elapsed = now() - self.begin\n\n\nclass CountMinSketch():\n ''' CountMin sketch implementation.\n\n :ivar depth: Depth of the CountMin sketch table.\n :ivar width: Width of the CountMin sketch table.\n :ivar table: The CountMin sketch table.\n '''\n def __init__(self, depth=5, width=20, seed=28):\n self.depth = depth\n self.width = width\n np.random.seed(seed)\n self.table = np.zeros((depth, width))\n self.hashes = np.random.random_integers(0, sys.maxsize - 1, depth)\n self.PRIME_MODULUS = (1 << 31) - 1\n\n def hash(self, item, i):\n ''' Calculates the hash for a given item.\n\n :param item: An item.\n :param i: The index for which to compute the hash.\n\n :returns: The hash for the item.\n '''\n hval = self.hashes[i] * item\n hval += hval >> 32\n hval &= self.PRIME_MODULUS\n\n return int(hval) % self.width\n\n def add(self, item):\n ''' Adds an item.\n\n :param item: An item.\n '''\n for i in range(self.depth):\n self.table[i][self.hash(item, i)] += 1\n\n def estimate_count(self, item):\n ''' Estimates the count for an item.\n\n :param item: An item.\n\n :returns: The estimated count.\n '''\n res = sys.maxsize\n\n for i in range(self.depth):\n res = min(res, self.table[i][self.hash(item, i)])\n\n return res\n","sub_path":"dautils/perf.py","file_name":"perf.py","file_ext":"py","file_size_in_byte":4323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"512168476","text":"from core.advbase import *\n\ndef module():\n return Sophie\n\nclass Sophie(Adv):\n conf = {}\n conf['slots.a'] = [\n 'Resounding_Rendition',\n 'Flash_of_Genius',\n 'Moonlight_Party',\n 'The_Plaguebringer',\n 'Dueling_Dancers'\n ]\n conf['acl'] = \"\"\"\n `dragon(c3-s-end), s4.check() and buff(s1)\n `s3, not buff(s3)\n `s4\n `s2, cancel\n `s1, not buff(s1) and x=5\n \"\"\"\n conf['coabs'] = ['Blade', 'Dragonyule_Xainfried', 'Akasha']\n conf['share.base'] = ['Rodrigo']\n conf['share.poison'] = ['Curran']\n\n\nif __name__ == '__main__':\n from core.simulate import test_with_argv\n test_with_argv(None, *sys.argv)\n","sub_path":"adv/sophie.py","file_name":"sophie.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"406295266","text":"import sys, boto3, random, os, time, datetime\nfrom datetime import timedelta\nfrom sqlalchemy import asc, desc \nfrom flask import render_template, url_for, flash, redirect, request, abort, jsonify \nfrom app import app, db, bcrypt, mail\nfrom flask_login import login_user, current_user, logout_user, login_required\nfrom forms import * \nfrom models import *\n\ntry:\n from aws import Settings \n s3_resource = Settings.s3_resource \n s3_client = Settings.s3_client \n S3_LOCATION = Settings.S3_LOCATION\n S3_BUCKET_NAME = Settings.S3_BUCKET_NAME \nexcept:\n s3_client = boto3.client('s3')\n s3_resource = boto3.resource('s3')\n S3_LOCATION = os.environ['S3_LOCATION'] \n S3_BUCKET_NAME = os.environ['S3_BUCKET_NAME'] \n\n\n##### midterm FUNCTIONS ////////////////////////\ndef controls(): \n try:\n controls = MidTerm.query.filter_by(teamMemOne='100000000').order_by(asc(MidTerm.id)).all() \n ##SET CONTROL ##\n ## If control = None ==> don't show extra features ##\n control = controls[0].extraInt # set extraInt to 1 and open the exam prep\n exOneID=controls[0].id \n exTwoID=controls[1].id \n except: \n control = None\n exOneID=0\n exTwoID=0\n print('Controls Unsuccessful')\n\n return [control, exOneID, exTwoID]\n\ndef mtDictMaker(idNum): \n model = MidTerm \n mids = model.query.all()\n \n stids = []\n names = []\n images =[] \n studentDict = {} \n \n if mids: \n for mid in mids:\n one = User.query.filter_by(studentID=mid.teamMemOne).first()\n two = User.query.filter_by(studentID=mid.teamMemTwo).first()\n thr = User.query.filter_by(studentID=mid.teamMemThr).first()\n a = [mid.teamMemOne, one.username, S3_LOCATION + one.image_file] \n b = [mid.teamMemTwo, two.username, S3_LOCATION + two.image_file]\n if thr: \n c = [mid.teamMemThr, thr.username, S3_LOCATION + thr.image_file]\n studentDict[mid.id] = [a,b,c]\n else: \n studentDict[mid.id] = [a,b] \n if idNum:\n for dictList in studentDict[idNum]:\n names.append(dictList[1]) \n images.append(dictList[2]) \n studentDict.pop(idNum) \n for item in studentDict:\n for i in studentDict[item]: \n stids.append(i[0]) \n \n print('NAMES: ', names, 'IMAGES: ', images)\n print ('stids= ', stids) \n print ('studentDict= ', studentDict) \n return [studentDict, stids, names, images]\n\ndef fieldsChecker():\n # query the midterms and return the fields which the students is working on\n model = MidTerm\n fieldsCheck1 = model.query.filter_by(teamMemOne=current_user.studentID).first()\n fieldsCheck2 = model.query.filter_by(teamMemTwo=current_user.studentID).first()\n fieldsCheck3 = model.query.filter_by(teamMemThr=current_user.studentID).first() \n\n if fieldsCheck1:\n fields = fieldsCheck1\n elif fieldsCheck2:\n fields = fieldsCheck2\n elif fieldsCheck3:\n fields = fieldsCheck3\n else:\n fields = None\n\n return fields\n\ndef embedMaker(link):\n # embedMaker handles various kinds of links uploaded from drive or youtube\n # link.find(x) = -1 means no index found\n if link.find('you') != -1: \n youLink = link.split(\"/\")\n preCode = youLink[len(youLink)-1]\n if preCode.find(\"watch\") != -1:\n watchSplit = ((preCode.split(\"=\"))[1]).split(\"&\")\n code = watchSplit[0]\n else:\n code = preCode\n embedSource = 'https://www.youtube.com/embed/' + code\n \n \n elif link.find('drive') != -1: \n if link.find('open') != -1: \n driveLink = link.split(\"=\")\n code = driveLink[1]\n print('IF') \n else:\n print('ELSE')\n driveLink = link.split(\"/\")\n code = max(driveLink, key=len)\n\n embedSource = 'https://drive.google.com/file/d/' + code + '/preview' \n \n else: \n embedSource = link\n\n print('EMBED:', embedSource) \n # https://drive.google.com/file/d/13qoP_5wPYHguCUB8qNXCGUtI136rHfCB/view?usp=sharing \n # https://drive.google.com/open?id=13qoP_5wPYHguCUB8qNXCGUtI136rHfCB\n # https://drive.google.com/file/d/1pdvh_mEnkXPKA3jivYIpYKTaoukxH5p3Yg/preview\n\n # https://www.youtube.com/watch?v=gV7z7U_3uZc&feature=youtu.be\n # https://www.youtube.com/embed/gV7z7U_3uZc?list=PLur_sUvPELY70T8NveIVMqQWCKESfiP6u\n # https://youtu.be/gd-UV92rNPw\n # https://www.youtube.com/embed/gV7z7U_3uZc \n \n return embedSource\n\n\n##### midterm PAGES ////////////////////////\n\n\n@app.route(\"/MTexample/\", methods = ['GET', 'POST']) \n@login_required\ndef MTexample(idMarker): \n \n if fieldsChecker():\n Uid = fieldsChecker().id\n else:\n Uid = None\n\n # only allow user and examples to be accessed \n ex1 = controls()[1]\n ex2 = controls()[2]\n allowedID = [ex1, ex2, Uid]\n\n if 'Exam' in MidTerm.query.filter_by(id=1).first().extraStr or current_user.id == 1:\n allowed = MidTerm.query.all()\n for mod in allowed:\n allowedID.append(mod.id) \n print ('allowedID', allowedID)\n\n\n if idMarker not in allowedID:\n flash('THIS EXAM IS NOT AVAILABLE AT THE MOMENT', 'primary')\n return redirect(url_for('mid_term'))\n \n form = MidtermExample()\n formList = [\n form.A01, \n form.A02, \n form.A03, \n form.A04\n ]\n \n # models \n fields = MidTerm.query.filter_by(id=idMarker).first()\n user = User.query.filter_by(username=current_user.username).first()\n \n #print(\"Fields: \", fields)\n #print(\"User: \", user)\n \n # embedMaker\n link = fields.vidLink\n embedSource = embedMaker(link)\n\n # details\n mDM = mtDictMaker(idMarker) \n names = mDM[2]\n images = mDM[3] \n \n ansFields= [fields.qOne, fields.qTwo, fields.qThr, fields.qFor]\n \n ansCheck = MidAnswers.query.filter_by(username=current_user.username).all()\n # check if form has been done before \n for ans in ansCheck:\n if ans.examID == idMarker:\n ansFields = ansFields + [ans.A01, ans.A02, ans.A03, ans.A04, fields.aOne, fields.aTwo, fields.aThr, fields.aFor]\n \n #print('ANSF', ansFields)\n \n #start exam grading\n #if user.exam == None:\n #user.exam = 0 \n #db.session.commit() \n \n if form.validate_on_submit(): \n response = MidAnswers(A01=form.A01.data, A02=form.A02.data, \n A03=form.A03.data, A04=form.A04.data, username=current_user.username, \n grade=1, examID=idMarker) # add the id marker \n db.session.add(response) \n db.session.commit() \n\n flash('Your answer has been submitted', 'success') \n return redirect(request.url)\n \n \n\n return render_template('student/midterm_example.html', names=names, images=images, \n fields=fields, form=form, formList=formList, embedSource=embedSource, ansFields=ansFields)\n\n\n@app.route(\"/midterm_update\", methods = ['GET' , 'POST'])\n@login_required\ndef MTedit():\n form = MidtermSetUp()\n formList = [\n form.MT01,\n form.MT02,\n form.MT03,\n form.MT04,\n form.MT05 \n ]\n\n fields = fieldsChecker()\n model = MidTerm\n\n \n if fields == None: \n if form.validate_on_submit(): \n mDM = mtDictMaker(None) \n stids = mDM[1]\n duplicate = []\n if form.MT04.data in stids:\n duplicate.append(form.MT04.data)\n if form.MT05.data in stids: \n duplicate.append(form.MT05.data) \n response = model(teamNum=form.MT01.data, vidOption=form.MT02.data, \n teamMemOne=form.MT03.data, teamMemTwo=form.MT04.data, teamMemThr=form.MT05.data, duplicate=duplicate, checkQue=0)\n db.session.add(response)\n db.session.commit() \n \n flash('Your project has been set up', 'success') \n return redirect(url_for('MTbuild')) \n elif request.method == 'GET':\n form.MT03.data = current_user.studentID\n return render_template('student/midterm_start.html', formList=formList, form=form, fields=None) \n else:\n print('FORM ERROR', form.errors)\n\n mDM = mtDictMaker(fields.id) \n stids = mDM[1]\n names = mDM[2]\n images = mDM[3] \n \n \n if form.validate_on_submit(): \n fields.teamNum = form.MT01.data\n fields.vidOption = form.MT02.data\n fields.teamMemOne = form.MT03.data\n fields.teamMemTwo = form.MT04.data\n fields.teamMemThr = form.MT05.data \n fields.names = None\n\n mDM = mtDictMaker(fields.id) \n stids = mDM[1]\n duplicate = []\n if form.MT04.data in stids:\n duplicate.append(form.MT04.data)\n if form.MT05.data in stids: \n duplicate.append(form.MT05.data) \n fields.duplicate = duplicate\n db.session.commit() \n\n flash('Your project has been set up', 'success') \n return redirect(url_for('MTbuild')) \n elif request.method == 'GET':\n if fields.teamNum == None:\n form.MT03.data = current_user.studentID\n else: \n form.MT01.data = fields.teamNum\n form.MT02.data = fields.vidOption\n form.MT03.data = current_user.studentID\n form.MT04.data = fields.teamMemTwo \n form.MT05.data = fields.teamMemThr\n\n return render_template('student/midterm_start.html', formList=formList, form=form, fields=fields)\n\n\n@app.route(\"/midterm_build\", methods = ['GET', 'POST'])\n@login_required\ndef MTbuild(): \n\n model = MidTerm \n fields = fieldsChecker()\n \n if fields == None:\n return redirect(url_for('MTedit'))\n\n form = MidtermDetails()\n formList = [ \n form.MT06, \n form.MT07,\n form.MT08, \n form.MT12,\n form.MT09,\n form.MT13,\n form.MT10, \n form.MT14,\n form.MT11,\n form.MT15\n ] \n \n fieldsList = [ \n fields.scrLink,\n fields.vidLink,\n fields.qOne,\n fields.aOne,\n fields.qTwo, \n fields.aTwo, \n fields.qThr,\n fields.aThr,\n fields.qFor,\n fields.aFor \n ] \n\n mDM = mtDictMaker(fields.id) \n stids = mDM[1]\n names = mDM[2]\n images = mDM[3] \n\n #add names\n if fields.names == None: \n fields.names = names \n db.session.commit() \n for name in names:\n User.query.filter_by(username=name).first().midterm = 1\n db.session.commit() \n MidGrades.query.filter_by(username=name).first().midterm = 1\n db.session.commit() \n\n\n # form in update mode\n if form.validate_on_submit(): \n fields.vidLink = form.MT07.data\n fields.qOne = form.MT08.data\n fields.qTwo = form.MT09.data \n fields.qThr = form.MT10.data\n fields.qFor = form.MT11.data \n fields.aOne = form.MT12.data\n fields.aTwo = form.MT13.data \n fields.aThr = form.MT14.data\n fields.aFor = form.MT15.data\n \n count = 0\n for i in formList:\n if i.data == \"\":\n count = count + 1 \n if count > 0:\n fields.checkQue = 0\n else:\n if fields.checkQue > 0:\n pass\n else:\n fields.checkQue = 1 \n db.session.commit()\n \n if fields.checkQue == 1:\n for name in names:\n User.query.filter_by(username=name).first().midterm = 2\n db.session.commit() \n MidGrades.query.filter_by(username=name).first().extraInt = 2\n db.session.commit() \n\n flash('Your project has been updated', 'success') \n return redirect(request.url) \n elif request.method == 'GET':\n for k in range(0,10):\n formList[k].data = fieldsList[k] \n else:\n print(form.errors) \n\n return render_template('student/midterm_build.html', formList=formList, form=form, fields=fields, names=names, images=images)\n\n\n@app.route(\"/midterm\", methods = ['GET', 'POST'])\n@login_required\ndef mid_term():\n # grades saved in User table, but also in MidGrades \n # need to reorganize grading system \n # show students how many listenings they should do\n # or show their grade on the home page \n user = User.query.filter_by(username=current_user.username).first() \n \n midExams = MidTerm.query.all()\n modAnswers = MidAnswers.query.filter_by(username=current_user.username).all()\n\n control = controls()[0]\n exOneID = controls()[1]\n exTwoID = controls()[2] \n exTestOne=0\n exTestTwo=0\n testProj=0\n\n \n #find id of user's project (if they have one) \n if fieldsChecker() == None: \n userID = 0\n else:\n userID = fieldsChecker().id\n #is id in the MidAnswers = projTest completed \n\n #make list of completed exams\n idList = [] \n for mod in modAnswers: \n ansID = mod.examID\n #project is finished and it's been tested \n if ansID == userID: \n testProj = 1 \n if ansID == exOneID:\n exTestOne = 1 \n if ansID == exTwoID:\n exTestTwo = 1 \n idList.append(ansID)\n\n print('ID_LIST', idList)\n\n examList = [] \n #generate random exam \n for exam in midExams:\n if exam.id in idList:\n print ('pass1', exam.id)\n pass\n elif exam.checkQue == 1: \n examList.append(exam.id)\n else:\n print ('pass2', exam.id)\n pass\n \n print ('available', examList) \n \n try:\n randID = random.choice(examList)\n except:\n randID = 0\n \n \n context = {\n 'user' : user, \n 'userID': userID,\n 'randID' : randID, \n 'idList' : idList, \n 'examList' : examList,\n 'testProj' : testProj, \n 'exOneID' : exOneID, \n 'exTestOne' : exTestOne, \n 'exTwoID' : exTwoID, \n 'exTestTwo' : exTestTwo, \n 'control' : control \n }\n\n return render_template('student/midterm.html', **context)\n\n\n","sub_path":"routesMidterm.py","file_name":"routesMidterm.py","file_ext":"py","file_size_in_byte":14664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"379880781","text":"import time\nimport threading\n\n#why it uses the all four cores?\n\ndef hayda1(x):\n #print(\"Calculating square\")\n while(True):\n x = x+1\n print(\"hayda1:\"+str(x))\n time.sleep(0.2)\n\ndef hayda2(x):\n #print(\"Calculating square\")\n while(True):\n x = x+1\n print(\"hayda2:\"+str(x))\n time.sleep(0.2)\n\nif __name__ == \"__main__\" :\n x = int(input())\n p1 = threading.Thread(target=hayda1,args=(x,))\n p2 = threading.Thread(target=hayda2,args=(x,))\n\n p1.start()\n p2.start()\n\n p1.join()\n p2.join()\n\n print(x)","sub_path":"def.py","file_name":"def.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"142557309","text":"from flask import Flask, request, render_template, redirect\nfrom flask_sslify import SSLify\nfrom tinydb import TinyDB, Query\nfrom tinydb.storages import MemoryStorage\nfrom uuid import uuid4\nfrom werkzeug.contrib.fixers import ProxyFix\nfrom os import getenv\n\ndb = TinyDB(storage=MemoryStorage)\napp = Flask(__name__)\napp.wsgi_app = ProxyFix(app.wsgi_app)\nsslify = SSLify(app, skips=['health'], age=300, permanent=True)\n\napp.debug = getenv('DEBUG', False)\napp.config['theme'] = getenv('THEME', 'light')\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef default():\n if request.method == 'POST':\n return render_template('index.html', error=True)\n else:\n return render_template('index.html')\n\n\n@app.route('/create/', methods=['POST'])\ndef create():\n key = uuid4().hex\n secret = request.form['secret'].encode('utf-8')\n if not secret:\n return redirect('/', 307)\n else:\n db.insert({'key': key, 'secret': secret})\n secret_url = request.url_root + 'get/' + key\n\n return render_template('create.html', url=secret_url)\n\n\n@app.after_request\ndef add_header(r):\n r.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'\n r.headers['Pragma'] = 'no-cache'\n r.headers['Expires'] = '0'\n r.headers['Cache-Control'] = 'public, max-age=0'\n return r\n\n\n@app.route('/get/')\ndef retrieve(key=None):\n try:\n result = db.search(Query().key == key)[0]\n secret = result['secret'].decode('utf-8')\n # set secret to an empty string\n db.update({'secret': ''.encode('utf-8')}, Query().key == key)\n except:\n secret = False\n\n return render_template('get.html', secret=secret)\n\n\n@app.route('/health', methods=['GET'])\ndef health():\n return 'OK'\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0')\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"568893887","text":"#!/usr/bin/env python3.3\n\nfrom matplotlib.pyplot import *\nfrom numpy import *\n\ndata = genfromtxt(\"emission.dat\").transpose()\nx = data[1]\ny = array([(-i+0.57) for i in data[0]])\n\n# Rescale and calibrate our data.\nfor k in range(0,len(x)):\n x[k] = 800 - 0.77 - x[k]*4.999/60000\n\nfigure(figsize=(10,3))\nsemilogy(x,y,'-',label=\"PMT Voltage curve\")\nxlabel(\"$\\lambda$ [nm]\")\nylabel(\"V [V]\")\nsubplots_adjust(left=0.1,right=0.9,top=0.95,bottom=0.2)\nlegend()\n#xlim([510,630])\nsavefig(\"emission_spectrum.pdf\",format='PDF')\nshow()\nclf()\n\n# Convert to cm^{-1} and plot.\nnu = array([1/(1e-7*i) for i in x])\nfigure(figsize=(10,3))\nsemilogy(nu,y,'-',label=\"PMT Voltage curve\")\nxlabel(r'$\\nu$ [cm$^{-1}$]')\nylabel(\"V [V]\")\n#xlim([16000,19500])\n#ylim([-0.5,1.2])\nsubplots_adjust(left=0.1,right=0.9,top=0.95,bottom=0.2)\nlegend(loc='best')\nsavefig(\"emnu_spectrum.pdf\",format='PDF')\nshow()\nclf()\n","sub_path":"iodine/data/emission.py","file_name":"emission.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"254017991","text":"# Copyright 2014 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nfrom recipe_engine.types import freeze\n\nDEPS = [\n 'archive',\n 'chromium',\n 'pgo',\n 'recipe_engine/platform',\n 'recipe_engine/properties',\n 'recipe_engine/step',\n]\n\n\nPGO_BUILDERS = freeze({\n 'chromium.fyi': {\n 'Chromium Win PGO Builder': {\n 'recipe_config': 'chromium',\n 'chromium_config_instrument': 'chromium_pgo_instrument',\n 'chromium_config_optimize': 'chromium_pgo_optimize',\n 'gclient_config': 'chromium',\n 'clobber': True,\n 'chromium_config_kwargs': {\n 'BUILD_CONFIG': 'Release',\n 'TARGET_BITS': 32,\n },\n 'testing': {\n 'platform': 'win',\n },\n },\n 'Chromium Win x64 PGO Builder': {\n 'recipe_config': 'chromium',\n 'chromium_config_instrument': 'chromium_pgo_instrument',\n 'chromium_config_optimize': 'chromium_pgo_optimize',\n 'gclient_config': 'chromium',\n 'clobber': True,\n 'chromium_config_kwargs': {\n 'BUILD_CONFIG': 'Release',\n 'TARGET_BITS': 64,\n },\n },\n },\n 'tryserver.chromium.win': {\n 'win_pgo': {\n 'recipe_config': 'chromium',\n 'chromium_config_instrument': 'chromium_pgo_instrument',\n 'chromium_config_optimize': 'chromium_pgo_optimize',\n 'gclient_config': 'chromium',\n 'chromium_config_kwargs': {\n 'BUILD_CONFIG': 'Release',\n 'TARGET_BITS': 32,\n },\n 'testing': {\n 'platform': 'win',\n },\n },\n },\n})\n\n\ndef RunSteps(api):\n buildername = api.properties['buildername']\n mastername = api.properties['mastername']\n bot_config = PGO_BUILDERS.get(mastername, {}).get(buildername)\n\n api.pgo.compile_pgo(bot_config)\n api.archive.zip_and_upload_build(\n 'package build',\n api.chromium.c.build_config_fs,\n 'gs://chromium-fyi-archive/win_pgo_builds')\n\n\ndef GenTests(api):\n def _sanitize_nonalpha(text):\n return ''.join(c if c.isalnum() else '_' for c in text)\n\n for mastername, builders in PGO_BUILDERS.iteritems():\n for buildername in builders:\n yield (\n api.test('full_%s_%s' % (_sanitize_nonalpha(mastername),\n _sanitize_nonalpha(buildername))) +\n api.properties.generic(mastername=mastername, buildername=buildername) +\n api.platform('win', 64)\n )\n","sub_path":"scripts/slave/recipes/chromium_pgo.py","file_name":"chromium_pgo.py","file_ext":"py","file_size_in_byte":2411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"632032344","text":"from threading import Thread\nimport requests\nfrom queue import SimpleQueue, Empty\nfrom time import sleep\n\n\nclass HttpSyncedDictionary:\n \"\"\"\n Contains a dictionary that can be updated and queried locally.\n The updates are sent to a HTTP server, as reply, the current dictionary\n known to the HTTP server is expected. This is used to update the\n local dictionary.\n\n In effect, the dictionary can be synchronized across multiple instances\n all using the same server.\n\n The synchronization happens in a separate thread and is limited by the\n time needed for HTTP POST send/receive.\n \"\"\"\n\n def __init__(self, server_url, keys_to_filter=[]):\n \"\"\"\n :param keys_to_filter: Iterable of keys in the synchronized dictionary.\n In order to not overwrite the values which are produced locally and\n thus more accurate locally than on the server, provide the keys to\n those values here. Values from the remote server for those keys will\n be ignored.\n \"\"\"\n self.data = {}\n self.inbox = SimpleQueue()\n\n self.server_url = server_url\n self.keys_to_filter = keys_to_filter\n\n self.thread = Thread(target=self._thread_function)\n self.daemon = True\n self.is_thread_running = False\n\n def _thread_function(self):\n while self.is_thread_running:\n new_data = {}\n while not self.inbox.empty(): # only use latest queue element\n new_data = self.inbox.get_nowait()\n response = requests.post(self.server_url, json=new_data)\n if response.ok:\n remote_status = response.json()\n for key in self.keys_to_filter:\n remote_status.pop(key, None)\n self.data.update(remote_status)\n\n def start(self):\n if not self.is_thread_running:\n self.is_thread_running = True\n self.thread.start()\n\n def stop(self):\n self.is_thread_running = False\n self.thread.join()\n\n def update(self, dictionary):\n self.data.update(dictionary)\n self.inbox.put(dictionary)\n\n def get(self, key=None, default_value=None):\n if key is not None:\n return self.data.get(key, default_value)\n else:\n return self.data\n\n\nif __name__ == \"__main__\":\n\n import pprint\n import os\n identifier = \"game-{}\".format(os.getpid())\n\n status = HttpSyncedDictionary(\"http://localhost:5000/update\", keys_to_filter=[identifier])\n status.start()\n\n print(\"This is game {}\".format(identifier))\n for i in range(10):\n status.update(\n {\n identifier: {\n \"value\": i,\n },\n },\n )\n sleep(1)\n pprint.pprint(status.get())\n\n status.stop()","sub_path":"http_synced_dictionary.py","file_name":"http_synced_dictionary.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"575261785","text":"import time\nfrom typing import Union, Optional\n\nfrom .exceptions import ConnectionTestException\n\n\nclass MetricsBuilder:\n def __init__(\n self,\n plugin_name: str,\n plugin_version: str,\n plugin_vendor: str,\n input_message: dict,\n exception_: Union[ConnectionTestException, Exception],\n workflow_id: Optional[str] = None,\n org_id: Optional[str] = None,\n ):\n self.plugin_name = plugin_name\n self.plugin_version = plugin_version\n self.plugin_vendor = plugin_vendor\n self.input_message = input_message.get(\"body\", {}).get(\"input\", {})\n self.exception_ = exception_\n self.workflow_id = workflow_id\n self.org_id = org_id\n\n def build(self) -> dict:\n \"\"\"\n Build a plugin metrics payload\n :return: Dictionary representing a payload containing various plugin metrics\n \"\"\"\n payload = self._create_metrics_payload()\n payload[\"workflow\"][\"step\"][\"error\"] = self._build_error_blob()\n\n return payload\n\n def _create_metrics_payload(self) -> dict:\n \"\"\"\n Update a plugin output payload with metrics information\n :return: Dictionary containing metrics\n \"\"\"\n\n # Sanitize input message\n provided_input = self._sanitize_input()\n\n payload = {\n \"plugin\": {\n \"name\": self.plugin_name,\n \"version\": self.plugin_version,\n \"vendor\": self.plugin_vendor,\n },\n \"workflow\": {\n \"step\": {\n \"inputs\": provided_input,\n \"error\": None,\n },\n \"id\": self.workflow_id,\n },\n \"organization_id\": self.org_id,\n \"measurement_time\": self._get_timestamp(),\n }\n\n return payload\n\n def _build_error_blob(self) -> dict:\n \"\"\"\n Builds an error blob by extracting information from an exception\n :return: Dictionary containing error information\n \"\"\"\n\n error = {}\n if isinstance(self.exception_, ConnectionTestException):\n error[\"cause\"] = (\n self.exception_.preset\n if self.exception_.preset\n else self.exception_.cause\n )\n error[\"known\"] = True\n else:\n error[\"cause\"] = type(self.exception_).__name__ # Get type as a string\n\n # False, since this is not an error we explicitly handled in the plugin, eg. IndexError\n error[\"known\"] = False\n error[\"message\"] = str(self.exception_)\n\n return error\n\n @staticmethod\n def _get_timestamp() -> str:\n \"\"\"\n Gets the current unix timestamp in seconds\n :return: Unix timestamp for 'now' in seconds\n \"\"\"\n return str(int(time.time()))\n\n def _sanitize_input(self) -> [str]:\n \"\"\"\n Strips input values from an input message to ensure sensitive data is not collected\n :return: List of input fields that were present in the input message, without values\n \"\"\"\n input_fields = list(self.input_message.keys())\n\n return input_fields\n","sub_path":"insightconnect_plugin_runtime/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":3186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"195553208","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Jun 28 12:00:29 2022\n\n@author: sandypashikanti\n\"\"\"\nimport os\nimport re\nfrom datetime import date\nfrom pickle import dump, load\n\nimport config\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom sklearn.preprocessing import MinMaxScaler\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.layers import BatchNormalization, Dense, Dropout, Input\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.optimizers import Adam\n\n\ndef extract_end_digit(var_value: str):\n \"\"\"\n extracts digits at the end of alphanumeric string\n\n Returns: str\n\n \"\"\"\n\n end_digit = re.compile(r\"(\\d+)$\").search(var_value)\n assert end_digit is not None\n return end_digit.group(1)\n\n\ndef export_table(data: pd.DataFrame, dw_table: str):\n\n config.cdp_conn.insert_complete_df(\n dw_table,\n data,\n batch_size=5000,\n upsert=False,\n cast_types={},\n column_float_precision={},\n default_float_precision=5,\n )\n\n return None\n\n\ndef model_train_fn(forecast_days_dict: dict, models_dir: str, model_params: dict):\n \"\"\"\n retrain model for different seasons\n\n \"\"\"\n\n # classification model - predict if the volume of a warehouse on a particular day is greater than 0 or not\n if os.path.isdir(models_dir + f\"class/{config.current_year - 1}/\") is False:\n os.makedirs(models_dir + f\"class/{config.current_year - 1}/\")\n\n for n in range(config.forecast_days):\n\n print(\"\\x1b[1;31m\" + f\"DAY {n}\" + \"\\x1b[0m\")\n\n tf.random.set_seed(config.seed_value)\n\n data = forecast_days_dict[f\"data_day{n}\"]\n data.rename(columns={\"vol\": \"vol_next0\"}, inplace=True)\n excluded_vars = config.id_vars.copy()\n\n for i in range(n + 1):\n data[f\"vol_next{i}_class\"] = np.where(data[f\"vol_next{i}\"] > 0, 1, 0)\n excluded_vars.append(f\"vol_next{n}\")\n excluded_vars.append(f\"vol_next{n}_class\")\n\n X = data.drop(excluded_vars, axis=1)\n y = data.loc[:, [f\"vol_next{n}_class\"]]\n\n # scaling\n input_scaler = MinMaxScaler()\n X_scaled = pd.DataFrame(input_scaler.fit_transform(X), columns=X.columns)\n\n # Creating model using the Sequential in tensorflow\n def build_model():\n\n input_layer = Input(shape=(len(X_scaled.columns),))\n\n x1 = Dense(\n model_params[\"class\"][f\"day{n}\"][\"neurons\"],\n activation=model_params[\"class\"][f\"day{n}\"][\"activation\"],\n )(input_layer)\n x1 = BatchNormalization()(x1)\n x1 = Dropout(model_params[\"class\"][f\"day{n}\"][\"dropout\"])(x1)\n\n output_layer = Dense(1, activation=\"sigmoid\")(x1)\n\n train_model = Model(inputs=input_layer, outputs=output_layer)\n\n return train_model\n\n # build the model\n class_model = build_model()\n\n class_model.compile(\n loss=\"binary_crossentropy\",\n optimizer=Adam(learning_rate=model_params[\"class\"][f\"day{n}\"][\"lr\"]),\n metrics=[\n tf.keras.metrics.AUC(name=\"auc\", curve=\"ROC\"),\n tf.keras.metrics.AUC(name=\"pr_auc\", curve=\"PR\"),\n tf.keras.metrics.Precision(name=\"precision\"),\n tf.keras.metrics.Recall(name=\"recall\"),\n ],\n )\n\n # train the model\n class_model.fit(\n x=X_scaled.values,\n y=y.values,\n epochs=model_params[\"class\"][f\"day{n}\"][\"epochs\"],\n batch_size=128,\n shuffle=True,\n verbose=True,\n )\n\n # save the order of columns\n cols = list(X)\n dump(\n cols,\n open(\n models_dir + f\"class/{config.current_year - 1}/cols_class_{n}.pkl\", \"wb\"\n ),\n )\n\n # save the scaler\n dump(\n input_scaler,\n open(\n models_dir\n + f\"class/{config.current_year - 1}/input_scaler_class_{n}.pkl\",\n \"wb\",\n ),\n )\n\n # save model\n class_model.save(\n models_dir + f\"class/{config.current_year - 1}/model_class_{n}.h5\"\n )\n\n # regression model 1 - predict actual volume of a warehouse on a particular day\n if os.path.isdir(models_dir + f\"reg1/{config.current_year - 1}/\") is False:\n os.makedirs(models_dir + f\"reg1/{config.current_year - 1}/\")\n\n for n in range(config.forecast_days):\n\n print(\"\\x1b[1;31m\" + f\"DAY {n}\" + \"\\x1b[0m\")\n\n tf.random.set_seed(config.seed_value)\n\n data = forecast_days_dict[f\"data_day{n}\"]\n data.rename(columns={\"vol\": \"vol_next0\"}, inplace=True)\n excluded_vars = config.id_vars.copy()\n excluded_vars.append(f\"vol_next{n}\")\n\n X = data.drop(excluded_vars, axis=1)\n y = data.loc[:, [f\"vol_next{n}\"]]\n\n # scaling\n input_scaler = MinMaxScaler()\n X_scaled = pd.DataFrame(input_scaler.fit_transform(X), columns=X.columns)\n\n output_scaler = MinMaxScaler()\n y_scaled = pd.DataFrame(output_scaler.fit_transform(y), columns=y.columns)\n\n # Creating model using the Sequential in tensorflow\n def build_model():\n input_layer = Input(shape=(len(X_scaled.columns),))\n\n x1 = Dense(\n model_params[\"reg1\"][f\"day{n}\"][\"neurons\"],\n activation=model_params[\"reg1\"][f\"day{n}\"][\"activation\"],\n )(input_layer)\n x1 = Dropout(model_params[\"reg1\"][f\"day{n}\"][\"dropout\"])(x1)\n\n output_layer = Dense(\n 1, activation=model_params[\"reg1\"][f\"day{n}\"][\"activation\"]\n )(x1)\n\n train_model = Model(inputs=input_layer, outputs=output_layer)\n\n return train_model\n\n # build the model\n reg1_model = build_model()\n\n reg1_model.compile(\n loss=model_params[\"reg1\"][f\"day{n}\"][\"loss\"],\n optimizer=Adam(learning_rate=model_params[\"reg1\"][f\"day{n}\"][\"lr\"]),\n metrics=[\"mse\", \"msle\"],\n )\n\n # train the model\n reg1_model.fit(\n x=X_scaled.values,\n y=y_scaled.values,\n epochs=model_params[\"reg1\"][f\"day{n}\"][\"epochs\"],\n batch_size=128,\n shuffle=True,\n verbose=True,\n )\n\n # save the order of columns\n cols = list(X)\n dump(\n cols,\n open(\n models_dir + f\"reg1/{config.current_year - 1}/cols_reg1_{n}.pkl\", \"wb\"\n ),\n )\n\n # save the scaler\n dump(\n input_scaler,\n open(\n models_dir\n + f\"reg1/{config.current_year - 1}/input_scaler_reg1_{n}.pkl\",\n \"wb\",\n ),\n )\n dump(\n output_scaler,\n open(\n models_dir\n + f\"reg1/{config.current_year - 1}/output_scaler_reg1_{n}.pkl\",\n \"wb\",\n ),\n )\n\n # save model\n reg1_model.save(\n models_dir + f\"reg1/{config.current_year - 1}/model_reg1_{n}.h5\"\n )\n\n # regression model 2 is trained on the data that have volume greater than 0\n # so to improve recall, outcome of the classification model is added to\n # predict actual volume of a warehouse on a particular day\n if os.path.isdir(models_dir + f\"reg2/{config.current_year - 1}/\") is False:\n os.makedirs(models_dir + f\"reg2/{config.current_year - 1}/\")\n\n for n in range(config.forecast_days):\n\n print(\"\\x1b[1;31m\" + f\"DAY {n}\" + \"\\x1b[0m\")\n\n tf.random.set_seed(config.seed_value)\n\n data = forecast_days_dict[f\"data_day{n}\"]\n data.rename(columns={\"vol\": \"vol_next0\"}, inplace=True)\n data = data[data[f\"vol_next{n}\"] > 0]\n excluded_vars = config.id_vars.copy()\n excluded_vars.append(f\"vol_next{n}\")\n\n for i in range(n + 1):\n data[f\"vol_next{i}_class\"] = np.where(data[f\"vol_next{i}\"] > 0, 1, 0)\n\n X = data.drop(excluded_vars, axis=1)\n y = data.loc[:, [f\"vol_next{n}\"]]\n\n # scaling\n input_scaler = MinMaxScaler()\n X_scaled = pd.DataFrame(input_scaler.fit_transform(X), columns=X.columns)\n\n output_scaler = MinMaxScaler()\n y_scaled = pd.DataFrame(output_scaler.fit_transform(y), columns=y.columns)\n\n # Creating model using the Sequential in tensorflow\n def build_model():\n input_layer = Input(shape=(len(X_scaled.columns),))\n\n x1 = Dense(\n model_params[\"reg2\"][f\"day{n}\"][\"neurons\"],\n activation=model_params[\"reg2\"][f\"day{n}\"][\"activation\"],\n )(input_layer)\n x1 = Dropout(model_params[\"reg2\"][f\"day{n}\"][\"dropout\"])(x1)\n\n output_layer = Dense(\n 1, activation=model_params[\"reg2\"][f\"day{n}\"][\"activation\"]\n )(x1)\n\n train_model = Model(inputs=input_layer, outputs=output_layer)\n\n return train_model\n\n # build the model\n reg2_model = build_model()\n\n reg2_model.compile(\n loss=model_params[\"reg2\"][f\"day{n}\"][\"loss\"],\n optimizer=Adam(learning_rate=model_params[\"reg2\"][f\"day{n}\"][\"lr\"]),\n metrics=[\"mse\", \"msle\"],\n )\n\n # train the model\n reg2_model.fit(\n x=X_scaled.values,\n y=y_scaled.values,\n epochs=model_params[\"reg2\"][f\"day{n}\"][\"epochs\"],\n batch_size=128,\n shuffle=True,\n verbose=True,\n )\n\n # save the order of columns\n cols = list(X)\n dump(\n cols,\n open(\n models_dir + f\"reg2/{config.current_year - 1}/cols_reg2_{n}.pkl\", \"wb\"\n ),\n )\n\n # save the scaler\n dump(\n input_scaler,\n open(\n models_dir\n + f\"reg2/{config.current_year - 1}/input_scaler_reg2_{n}.pkl\",\n \"wb\",\n ),\n )\n dump(\n output_scaler,\n open(\n models_dir\n + f\"reg2/{config.current_year - 1}/output_scaler_reg2_{n}.pkl\",\n \"wb\",\n ),\n )\n\n # save model\n reg2_model.save(\n models_dir + f\"reg2/{config.current_year - 1}/model_reg2_{n}.h5\"\n )\n\n return None\n\n\ndef model_predict_fn(\n crop_data_frame: pd.DataFrame, models_dir: str, model_params: dict, dw_table: str\n):\n \"\"\"\n function to create predictions\n\n \"\"\"\n\n excluded_vars = config.id_vars + [\"vol\"]\n\n # drop vars that have 'next' or 'forecast' in the variable names\n for var in [\"next\", \"avg_forecast\"]:\n excluded_vars.extend(crop_data_frame.filter(regex=rf\"(\\w+){var}\").columns)\n\n for n in range(config.forecast_days):\n\n tf.random.set_seed(config.seed_value)\n\n # load trained models\n\n # classification model - predict if the volume of a warehouse on a particular day is greater than 0 or not\n model_class = load_model(\n models_dir + f\"class/{config.current_year - 1}/\" + f\"model_class_{n}.h5\"\n )\n input_scaler_class = load(\n open(\n models_dir\n + f\"class/{config.current_year - 1}/\"\n + f\"input_scaler_class_{n}.pkl\",\n \"rb\",\n )\n )\n cols_class = load(\n open(\n models_dir\n + f\"class/{config.current_year - 1}/\"\n + f\"cols_class_{n}.pkl\",\n \"rb\",\n )\n )\n\n # regression model 1 - predict actual volume of a warehouse on a particular day\n model_reg1 = load_model(\n models_dir + f\"reg1/{config.current_year - 1}/\" + f\"model_reg1_{n}.h5\"\n )\n input_scaler_reg1 = load(\n open(\n models_dir\n + f\"reg1/{config.current_year - 1}/\"\n + f\"input_scaler_reg1_{n}.pkl\",\n \"rb\",\n )\n )\n output_scaler_reg1 = load(\n open(\n models_dir\n + f\"reg1/{config.current_year - 1}/\"\n + f\"output_scaler_reg1_{n}.pkl\",\n \"rb\",\n )\n )\n cols_reg1 = load(\n open(\n models_dir + f\"reg1/{config.current_year - 1}/\" + f\"cols_reg1_{n}.pkl\",\n \"rb\",\n )\n )\n\n # regression model 2 - to improve recall, outcome of the classification model is added to\n # predict actual volume of a warehouse on a particular day\n model_reg2 = load_model(\n models_dir + f\"reg2/{config.current_year - 1}/\" + f\"model_reg2_{n}.h5\"\n )\n input_scaler_reg2 = load(\n open(\n models_dir\n + f\"reg2/{config.current_year - 1}/\"\n + f\"input_scaler_reg2_{n}.pkl\",\n \"rb\",\n )\n )\n output_scaler_reg2 = load(\n open(\n models_dir\n + f\"reg2/{config.current_year - 1}/\"\n + f\"output_scaler_reg2_{n}.pkl\",\n \"rb\",\n )\n )\n cols_reg2 = load(\n open(\n models_dir + f\"reg2/{config.current_year - 1}/\" + f\"cols_reg2_{n}.pkl\",\n \"rb\",\n )\n )\n\n if n == 0:\n data = crop_data_frame.drop(excluded_vars, axis=1)\n\n data = data[cols_class]\n\n data_scaled_class = pd.DataFrame(\n input_scaler_class.transform(data), columns=data.columns\n )\n\n data_scaled_reg1 = data[cols_reg1]\n data_scaled_reg1 = pd.DataFrame(\n input_scaler_reg1.transform(data_scaled_reg1),\n columns=data_scaled_reg1.columns,\n )\n\n data_scaled_reg2 = data.copy()\n data_scaled_reg2[f\"vol_next{n}_class\"] = model_class.predict(\n data_scaled_class, verbose=0\n )\n data_scaled_reg2[f\"vol_next{n}_class\"] = np.where(\n data_scaled_reg2[f\"vol_next{n}_class\"]\n > (\n model_params[\"class\"][f\"day{n}\"][\"threshold\"]\n - config.threshold_reduction_factor\n ),\n 1,\n 0,\n )\n data_scaled_reg2 = data_scaled_reg2[cols_reg2]\n data_scaled_reg2 = pd.DataFrame(\n input_scaler_reg2.transform(data_scaled_reg2),\n columns=data_scaled_reg2.columns,\n )\n\n # classification, regression1, & regression2 models are applied in sequential order\n data[f\"vol_next{n}_class\"] = model_class.predict(data_scaled_class, verbose=0)\n data[f\"vol_next{n}_class\"] = np.where(\n data[f\"vol_next{n}_class\"]\n > (\n model_params[\"class\"][f\"day{n}\"][\"threshold\"]\n - config.threshold_reduction_factor\n ),\n 1,\n 0,\n )\n data[f\"vol_next{n}_reg1\"] = output_scaler_reg1.inverse_transform(\n model_reg1.predict(data_scaled_reg1, verbose=0)\n )\n data[f\"vol_next{n}_reg2\"] = output_scaler_reg2.inverse_transform(\n model_reg2.predict(data_scaled_reg2, verbose=0)\n )\n\n # recall is given more importance as it is better for a warehouse to be over-prepared regarding the\n # volume of grain it will receive to process than being under-prepared\n # In order to be over-prepared, even if reg1 model predicts approximately no volume, but classification\n # model predicts that the warehouse will receive grain, reg2 model trained on data with vol>0 is applied again\n # final volume predicted is calculated from classification, regression1, & regression2 models\n # if regression1 models predicts volume <= 0, but classification prediction is 1 then\n # output from regression2 model is considered, otherwise regression1 model is the final volume\n data[f\"vol_next{n}_reg\"] = np.where(\n ((data[f\"vol_next{n}_reg1\"] <= 0) & (data[f\"vol_next{n}_class\"] == 1)),\n data[f\"vol_next{n}_reg2\"],\n data[f\"vol_next{n}_reg1\"],\n )\n data[f\"vol_next{n}\"] = np.where(\n data[f\"vol_next{n}_reg\"] <= 10, 0, data[f\"vol_next{n}_reg\"]\n )\n data[f\"vol_next{n}_class\"] = np.where(data[f\"vol_next{n}\"] == 0, 0, 1)\n\n data = data.drop(\n [f\"vol_next{n}_reg1\", f\"vol_next{n}_reg2\", f\"vol_next{n}_reg\"], axis=1\n )\n\n inclusion = []\n if n >= 1:\n data[f\"vol_avg_forecast{n}\"] = data[\n [f\"vol_next{day}\" for day in range(n + 1)]\n ].mean(axis=1)\n\n for metric in [\"prec\", \"tmax\", \"tmin\"]:\n for var in [\"next\", \"avg_forecast\"]:\n inclusion.extend(\n list(crop_data_frame.filter(regex=f\"{metric}_{var}{n + 1}$\"))\n )\n excluded_vars = list(set(excluded_vars).difference(set(inclusion)))\n\n data = pd.merge(\n data, crop_data_frame[inclusion], left_index=True, right_index=True\n )\n\n # id variables that are excluded before prediction should be added back and joined using index\n data = pd.merge(\n data, crop_data_frame[config.id_vars], left_index=True, right_index=True\n )\n\n # create date time column using columns - crop_day, crop_month & config.current_year\n data[\"forecast_date_of_execution\"] = pd.to_datetime(\n dict(year=config.current_year, month=data.crop_month, day=data.crop_day)\n )\n\n # convert vol-next columns from wide to long format and create dates based on n in vol_next{n}\n data = pd.melt(\n data,\n id_vars=[\"unit_id\", \"unit_name\", \"sub_regional\", \"forecast_date_of_execution\"],\n value_vars=list(data.filter(regex=r\"vol_next(\\d+)$\").columns),\n )\n\n # create dates for next 15 days from date_of_execution\n data[\"forecast_day\"] = data[\"variable\"].apply(lambda x: extract_end_digit(x))\n data[\"forecast_day\"] = data[\"forecast_day\"].astype(np.int64)\n data[\"forecast_date\"] = (data[\"forecast_date_of_execution\"]) + pd.to_timedelta(\n data.forecast_day, unit=\"d\"\n )\n data.rename(columns={\"value\": \"volume\"}, inplace=True)\n data = data[\n [\n \"unit_id\",\n \"unit_name\",\n \"sub_regional\",\n \"forecast_date\",\n \"forecast_date_of_execution\",\n \"volume\",\n ]\n ]\n\n # export data\n export_table(data, dw_table)\n\n return None\n\n\ndef off_season(dw_table):\n\n # extract warehouse attributes from the dictionary\n data = pd.DataFrame(config.warehouse_dict)\n data = data.transpose()\n data = data[[8, 9, 10]].rename(\n columns={8: \"unit_id\", 9: \"unit_name\", 10: \"sub_regional\"}\n )\n data[\"forecast_date_of_execution\"] = date.today() # date(2022, 1, 21)\n data[\"key\"] = 1\n\n # generate day numbers to forecast\n days_15 = pd.DataFrame()\n days_15[\"forecast_day\"] = range(config.forecast_days)\n days_15[\"key\"] = 1\n\n # cross join of data & days_15 to generate forecast dates for all the warehouses\n data = pd.merge(data, days_15, on=\"key\").drop(\"key\", 1)\n data[\"forecast_day\"] = data[\"forecast_day\"].astype(np.int64)\n data[\"forecast_date\"] = (data[\"forecast_date_of_execution\"]) + pd.to_timedelta(\n data.forecast_day, unit=\"d\"\n )\n data[\"volume\"] = 0\n data = data[\n [\n \"unit_id\",\n \"unit_name\",\n \"sub_regional\",\n \"forecast_date\",\n \"forecast_date_of_execution\",\n \"volume\",\n ]\n ]\n\n # export data\n export_table(data, dw_table)\n\n return None\n","sub_path":"Docker/Files/src/modeling.py","file_name":"modeling.py","file_ext":"py","file_size_in_byte":19636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"70839588","text":"import logging\nimport sys\n\nimport numpy as np\nimport pandas as pd\nimport xgboost as xgb\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import train_test_split\n\nsys.path.append('..')\n\nfrom utility import constants\nfrom utility import utils\nfrom resultFunctions import callFunctionByName\n\n# Log time-level and message for getting a running estimate\nlogging.basicConfig(stream=sys.stdout, format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO)\n\ndef trainXGBModel(data_input, training_filepath):\n\t# Init a variable to keep the best Model\n\txgb_model = {}\n\totherValues = {\n\t\t'accuracy_value': 0\n\t}\n\n\t# Initialize the range to test the different parameters\n\tlearning_rate_vals = np.arange (0.1, 0.5, 0.02)\n\tmax_depth_vals = np.arange (8, 12, 1) # High Depth Tress are fit to that dataset\n\t# Minimum loss reduction required to make a further partition on a leaf node of the tree.\n\t# The larger min_split_loss/gamma is, the more conservative the algorithm will be.\n\tmin_split_loss_vals = np.arange(0, 1, 1)\n\n\tcolsample_bytree_vals = np.arange(0.1, 0.8, 0.1)\n\n\t# Predication will be always on 1 result col\n\tYColumns = [data_input[constants.IRESULT_COL_KEY]]\n\tnumericalCols = data_input[constants.INUMERICAL_COLS]\n\tcategoricalCols = data_input[constants.ICATEGORICAL_COLS]\n\n\tcolumns_to_keep = YColumns + numericalCols + categoricalCols\n\tone_hot_encoder, shapeTuple = utils.buildOneHotEncoder(training_filepath, categoricalCols)\n\n\tdf = pd.read_csv(training_filepath, skiprows=0, header=0)\n\tdf[data_input[constants.IRESULT_COL_KEY]] = df.apply(\n\t\tlambda row: callFunctionByName (row, data_input[constants.IRESULT_FUNCTION]), axis=1)\n\n\tdf['metrics_day'] = pd.to_datetime(df['metrics_day'], format='%Y-%m-%d')\n\tdf['start_date'] = pd.to_datetime(df['start_date'], format='%Y %m %d %H:%M:%S')\n\tdf['days'] = (df['metrics_day'] - df['start_date']).dt.days\n\n\tdf = df.where(df['weblab'] == \"missing\").dropna()\n\tdf = df[columns_to_keep]\n\tY, X = df.iloc[:, 0], df.iloc[:, 1:]\n\n\tlearning_parameters = data_input[constants.IPARAMS_KEY]\n\tfor learning_rate in learning_rate_vals:\n\t\tfor max_depth in max_depth_vals:\n\t\t\tfor min_split_loss in min_split_loss_vals:\n\t\t\t\tfor colsample_bytree in colsample_bytree_vals:\n\t\t\t\t\t# Set the params and tune the job\n\t\t\t\t\tlearning_parameters['max_depth'] = max_depth\n\t\t\t\t\tlearning_parameters['learning_rate'] = learning_rate\n\t\t\t\t\tlearning_parameters['min_split_loss'] = min_split_loss\n\t\t\t\t\tlearning_parameters['colsample_bytree'] = colsample_bytree\n\n\t\t\t\t\tdata_input[constants.IPARAMS_KEY] = learning_parameters\n\n\t\t\t\t\tX_train, X_test, y_train, y_test = train_test_split (X, Y, test_size=0.2, random_state=123)\n\n\t\t\t\t\tnumeric_data = X_train.iloc[:,0:len(numericalCols)]\n\t\t\t\t\tone_hot_encoded = one_hot_encoder.transform(X_train.iloc[:,len(numericalCols):])\n\t\t\t\t\td_train = xgb.DMatrix (np.column_stack ((numeric_data, one_hot_encoded)), label=y_train)\n\n\t\t\t\t\txg_reg = xgb.train(data_input[constants.IPARAMS_KEY], d_train, data_input[constants.ITRAIN_ITERATIONS])\n\n\t\t\t\t\tnumeric_data = X_test.iloc[:,0:len(numericalCols)]\n\t\t\t\t\tone_hot_encoded = one_hot_encoder.transform(X_test.iloc[:,len(numericalCols):])\n\t\t\t\t\td_test = xgb.DMatrix(np.column_stack ((numeric_data, one_hot_encoded)))\n\t\t\t\t\tpreds = xg_reg.predict(d_test)\n\n\t\t\t\t\taccuracy = accuracy_score(y_test, np.around(preds))\n\t\t\t\t\tmatrix = confusion_matrix(y_test, np.around (preds))\n\n\t\t\t\t\tlogging.info(str(data_input[constants.IPARAMS_KEY]) +\" : \" + str(accuracy))\n\t\t\t\t\tif(otherValues['accuracy_value'] 0:\n self.i -= 1\n self.label.setPixmap(QPixmap(self.file + '/' + self.fileList[self.i]))\n self.counter.setText(str(self.i + 1) + ' of ' + str(len(self.fileList)))\n\n\napp = QApplication(sys.argv)\nw = Window()\nsys.exit(app.exec())\n","sub_path":"Assignment4/Assignment4.py","file_name":"Assignment4.py","file_ext":"py","file_size_in_byte":3295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"490522689","text":"#This is a script for making a linelist in a given wavelength range. This function pulls lines from the master linelist located at \"/Users/richardseifert/Desktop/BSS_Research/lines/master_lines.txt\", which was produced by Joining_Linelists.py\nimport sys\n\nhomePath = \"/Users/richardseifert/Desktop/BSS_Research/\"\nlinePath = homePath + 'lines/'\n\nmaster_path=homePath+\"lines/master_lines.txt\"\ndef linelist(lower, upper, master_path=master_path, path='', use_linePath= True):\n #Get the lines with wavelengths between 'lower' and 'upper' from a master linelist\n master = open(master_path, 'r')\n lines = []\n tmp = 0\n for line in master:\n wvl = float(filter(None, line.split(\" \"))[0])\n if wvl >= lower and wvl <= upper:\n if tmp == 0: min_wvl = wvl; tmp+=1\n lines.append(line)\n max_wvl = wvl\n master.close()\n\n #Write the new linelist\n start = str(int(min_wvl))\n length = str(int(round((max_wvl-min_wvl)/5)*5))\n filename = 'lines_'+start+'_'+length\n\n savepath = ''\n if use_linePath:\n savepath += linePath\n savepath += path\n newLineList = open(savepath+filename, 'w')\n for line in lines:\n newLineList.write(line)\n newLineList.close()\n\n#If this is run as a script, determine wavelength limits and generate linelist\nif __name__ == '__main__': \n #Figure out what the wavelength limits are\n if len(sys.argv) >= 3:\n lower, upper = float(sys.argv[1]), float(sys.argv[2])\n elif len(sys.argv) == 2:\n lower = float(sys.argv[1])\n upper = float(raw_input(\"Upper Wavelength Limit:\\n\\t\"))\n else:\n lower = float(raw_input(\"Lower Wavelength Limit:\\n\\t\"))\n upper = float(raw_input(\"Upper Wavelength Limit:\\n\\t\"))\n\n linelist(lower, upper)\n","sub_path":"short_scripts/Make_Linelist.py","file_name":"Make_Linelist.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"151861024","text":"#!/usr/bin/python3\n\"\"\" \"\"\"\nimport unittest\nfrom io import StringIO\nfrom unittest.mock import patch\nfrom console import HBNBCommand\n\n\nclass TestConsole(unittest.TestCase):\n \"\"\" \"\"\"\n\n def test_do_create(self):\n with patch('sys.stdout', new=StringIO()) as f:\n HBNBCommand().onecmd(\"create State name=\\\"vane\\\"\")\n state_id = f.getvalue()\n self.assertTrue(len(state_id) >= 1)\n\n with patch('sys.stdout', new=StringIO()) as f2:\n HBNBCommand().onecmd(\"show State \" + state_id)\n string = f2.getvalue()\n param = \"'name': 'vane'\"\n self.assertTrue(param in string)\n","sub_path":"tests/test_console.py","file_name":"test_console.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"65006918","text":"def notas(lst, sit=False):\n \"\"\"\n Returns dictionary with info about group grades:\n quantity of grades, max grade of list, min grade of list,\n average grade of the list, and if sit = True, it shows\n group situation: GOOD, REASONABLE or BAD.\n :param lst: float list with grades\n :param sit: boolean\n :return: dictionary\n \"\"\"\n turma = dict()\n turma['total'] = len(lst)\n turma['maior'] = max(lst)\n turma['menor'] = min(lst)\n media = sum(lst) / len(lst)\n turma['média'] = f'{media:.1f}'\n if sit:\n if media < 5.0:\n turma['situação'] = 'RUÍM'\n elif media < 7.5:\n turma['situação'] = 'RAZOÁVEL'\n else:\n turma['situação'] = 'BOA'\n return f'{turma}'\n\n\n# Programa Principal\nnum = []\nwhile True:\n n = float(input('Nota: '))\n num.append(n)\n resp = ' '\n while resp not in 'NS':\n resp = str(input('Cadastrar outra nota [S/N]? ')).strip().upper()[0]\n if resp == 'N':\n break\nopt = ' '\nwhile opt not in 'NS':\n opt = str(input('Quer ver a situação da turma? ')).strip().upper()[0]\n if opt == 'S':\n print(notas(num, sit=True))\n else:\n print(notas(num))","sub_path":"Revisao_Funcoes/rev_105.py","file_name":"rev_105.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"163355474","text":"from django.test import TestCase\nfrom django.urls import reverse_lazy\nfrom django.core.exceptions import ValidationError\n\nfrom boarding_visit.models import BoardingVisit\nfrom old.tests import OLD_TEST_DATA, Old\n\nfrom datetime import date, timedelta\n\n# Create your tests here.\n\n\nclass BoardingVisitFormTest(TestCase):\n \"\"\"\n The test case for BoardingVisitForm\n \"\"\"\n TEST_DATE = date(year=2016, month=10, day=5)\n VALID_DATA = [\n {'old_id': 1, 'start_date': TEST_DATE, 'end_date': TEST_DATE + timedelta(days=3)},\n {'old_id': 2, 'start_date': TEST_DATE, 'end_date': TEST_DATE + timedelta(days=5)},\n ]\n\n def setUp(self):\n self.valid_data = self.VALID_DATA\n self.fail_data = self.valid_data\n\n for data in OLD_TEST_DATA:\n Old.objects.create(\n **data\n )\n\n def test_create__boardingvisit_objects__must_2(self):\n \"\"\"\n Simple test for successful create the new BoardingVisit objects\n \"\"\"\n\n for data in self.valid_data:\n visit = BoardingVisit.objects.create(\n **data\n )\n self.assertIsInstance(visit, BoardingVisit)\n self.assertEqual(self.valid_data.__len__(), BoardingVisit.objects.count())\n\n def test_create__the_same_boardingvisits_objects__must_2_errors(self):\n \"\"\"\n Test error with start and end dates\n \"\"\"\n\n for data in self.valid_data:\n BoardingVisit.objects.create(\n **data\n )\n\n fails = 0\n for data in self.fail_data:\n try:\n BoardingVisit.objects.create(\n **data\n )\n except ValidationError:\n fails += 1\n\n self.assertEqual(BoardingVisit.objects.count(), fails)\n\n\nclass BoardingVisitViewTest(TestCase):\n \"\"\"\n The few tests for views with BoardingVisit and Old logic\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Create the Olds objects for the test\n \"\"\"\n for data in OLD_TEST_DATA:\n Old.objects.create(\n **data\n )\n\n def test_simple_get_homepage__check_header(self):\n \"\"\"\n Simple test with GET request\n and check the 'Happy Olds' header is exist\n \"\"\"\n response = self.client.get('/')\n self.assertEqual(200, response.status_code)\n self.assertIn(\"Happy Olds\", response.content.__str__())\n\n def test_send_dates_to_homepage(self):\n \"\"\"\n Simple check the weekdays header when dates are sent\n \"\"\"\n response = self.client.get('/',\n data={\n 'start_date': '2016-09-18',\n 'end_date': '2016-09-20'\n })\n self.assertEqual(200, response.status_code)\n self.assertIn(\"weekdays\", response.content.__str__())\n\n def test_show_olds(self):\n \"\"\"\n Test with creating the olds, visits and check\n them on the homepage with sent parameters\n \"\"\"\n visit_data = BoardingVisitFormTest.VALID_DATA\n\n for data in visit_data:\n BoardingVisit.objects.create(\n **data\n )\n\n response = self.client.get('/', data={\n 'start_date': visit_data[0]['start_date'],\n 'end_date': visit_data[1]['start_date']\n })\n self.assertIn(OLD_TEST_DATA[0]['first_name'], response.content.__str__())\n self.assertIn(\n \"{0} {1}\".format(\n OLD_TEST_DATA[0]['first_name'],\n OLD_TEST_DATA[0]['last_name']),\n response.content.__str__()\n )\n self.assertNotIn(\n \"{0} {1}\".format(\n OLD_TEST_DATA[2]['first_name'],\n OLD_TEST_DATA[2]['last_name']),\n response.content.__str__()\n )\n\n def test_generate_data(self):\n \"\"\"\n Test for generate data form\n \"\"\"\n data = {\n 'olds_start': 5,\n 'olds_end': 10,\n 'visits_start': 5,\n 'visits_end': 10\n }\n\n response = self.client.get(reverse_lazy('generate_fake_date'), data=data)\n self.assertEqual(302, response.status_code)\n self.assertNotEqual(0, Old.objects.count())\n self.assertNotEqual(0, BoardingVisit.objects.count())\n","sub_path":"boarding_visit/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"417412823","text":"import time\nimport unittest\n\nimport redis\n\nfrom tonggong.generator import Generator\nfrom tonggong.hash import Hash\nfrom tonggong.redis import (\n RedisLock,\n safe_delete_hash,\n safe_delete_list,\n safe_delete_set,\n safe_delete_sorted_set,\n)\n\n\nclass RedisTestCase(unittest.TestCase):\n def setUp(self) -> None:\n self.conn = redis.Redis()\n\n def test_safe_delete_hash(self):\n key = Generator.uuid4()\n mapping = {format(i): i for i in range(10000)}\n self.conn.hset(key, mapping=mapping)\n self.assertEqual(self.conn.hlen(key), 10000)\n safe_delete_hash(self.conn, key)\n self.assertFalse(self.conn.exists(key))\n self.assertFalse(self.conn.exists(\"gc:hash:{}\".format(Hash.md5(key))))\n\n def test_safe_delete_list(self):\n key = Generator.uuid4()\n self.conn.lpush(key, *range(10000))\n self.assertEqual(self.conn.llen(key), 10000)\n safe_delete_list(self.conn, key)\n self.assertFalse(self.conn.exists(key))\n self.assertFalse(self.conn.exists(\"gc:list:{}\".format(Hash.md5(key))))\n\n def test_safe_delete_set(self):\n key = Generator.uuid4()\n self.conn.sadd(key, *range(10000))\n self.assertEqual(self.conn.scard(key), 10000)\n safe_delete_set(self.conn, key)\n self.assertFalse(self.conn.exists(key))\n self.assertFalse(self.conn.exists(\"gc:set:{}\".format(Hash.md5(key))))\n\n def test_safe_delete_sorted_set(self):\n key = Generator.uuid4()\n mapping = {i: \"{}\".format(i) for i in range(10000)}\n self.conn.zadd(key, mapping)\n self.assertEqual(self.conn.zcard(key), 10000)\n safe_delete_sorted_set(self.conn, key)\n self.assertFalse(self.conn.exists(key))\n self.assertFalse(self.conn.exists(\"gc:zset:{}\".format(Hash.md5(key))))\n\n def test_redis_lock(self):\n lock_key = Generator.uuid4()\n\n # test non blocking\n with RedisLock(self.conn, lock_key) as one:\n self.assertTrue(one.acquired)\n self.assertTrue(isinstance(one.local.token.decode(), str))\n self.assertEqual(one.local.token, self.conn.get(RedisLock.get_key_name(lock_key)))\n with RedisLock(self.conn, lock_key, blocking=False) as two:\n self.assertFalse(two.acquired)\n with RedisLock(self.conn, lock_key, blocking=False) as two:\n self.assertFalse(two.acquired)\n\n # test timeout\n with RedisLock(self.conn, lock_key, timeout=1) as one:\n self.assertTrue(one.acquired)\n time.sleep(1.00001)\n with RedisLock(self.conn, lock_key, blocking=False) as two:\n self.assertTrue(two.acquired)\n","sub_path":"tests/test_redis.py","file_name":"test_redis.py","file_ext":"py","file_size_in_byte":2693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"647256616","text":"class Solution:\n def numOfStrings(self, patterns: List[str], word: str) -> int:\n count = 0\n for pattern in patterns:\n if self.checkPattern(pattern, word): count += 1\n return count\n \n def checkPattern(self, pattern, word:str) -> bool:\n found = False\n for i in range(len(word)):\n char_mismatch = False\n if i + len(pattern) > len(word):\n found = False\n break\n for j in range(len(pattern)):\n if pattern[j] != word[i + j]:\n char_mismatch = True\n break\n if not char_mismatch:\n found = True\n break\n \n return found","sub_path":"leetcode/1967.number-of-strings-that-appear-as-substrings-in-word/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"506487523","text":"from migen import *\n\nclass wb_interface(Module):\n def __init__(self):\n\n\n FirstAdress = Signal(16)\n SecondAdress = Signal(16)\n ThirdAdress = Signal(16)\n FourthAdress = Signal(16)\n #inputs:\n self.RESET_i = RESET_i = Signal() #active for returing back to the retset state \n self.ADR_i = ADR_i = Signal(16)\n self.DAT_i = DAT_i = Signal(16)\n self.WE_i = WE_i = Signal() #write enable\n self.STB_i = STB_i = Signal() #active to indicate bus transaction request \n self.CYC_i = CYC_i = Signal() #wishbone transaction, true on (or before) the first i_wb_stb clock, stays true until the last o_wb_ack\n\n #outputs\n self.STALL_o = STALL_o = Signal() # false when the transaction happens\n self.ACK_o = ACK_o = Signal() #active for indicating the end of the transaction \n self.DAT_o = DAT_o = Signal(16)\n\n\n #imported_modules\n fsm = FSM(reset_state=\"RESET\")\n self.submodules += fsm\n # self.memory_storage = mem = mem()\n\n #slave_module\n\n \n\n fsm.act(\"INACTIVE\",\n STALL_o.eq(1),\n\t NextValue(ACK_o,0),\n If((STB_i == 1) ,\n \n NextState(\"READING\")),\n If((STB_i == 1) & (WE_i == 1),\n \n NextState(\"WRITING\"))\n )\n\n fsm.act(\"READING\",\n \n STALL_o.eq(0),\n If(ADR_i == 1,\n NextValue(DAT_o,FirstAdress)\n ).Elif(ADR_i == 2,\n NextValue(DAT_o,SecondAdress)\n ).Elif(ADR_i == 3,\n NextValue(DAT_o,ThirdAdress)\n ).Else(\n NextValue(DAT_o,FourthAdress),\n ),\n \n\n If((RESET_i == 1),\n NextState(\"RESET\")\n ),\n\n\n If((CYC_i == 0),\n NextValue(ACK_o,1),\n NextState(\"INACTIVE\"),\n )\n\n\n )\n\n fsm.act(\"WRITING\",\n STALL_o.eq(0),\n If(ADR_i == 1,\n NextValue(FirstAdress,DAT_i)\n ).Elif(ADR_i == 2,\n NextValue(SecondAdress,DAT_i)\n ).Elif(ADR_i == 3,\n NextValue(ThirdAdress,DAT_i)\n ).Else(\n NextValue(FourthAdress,DAT_i),\n ),\n \t\n\n If((RESET_i == 1),\n NextState(\"RESET\")\n ),\n\n If((CYC_i == 0),\n NextValue(ACK_o,1),\n NextState(\"INACTIVE\")\n )\n\n )\n fsm.act(\"RESET\",\n NextState(\"INACTIVE\")\n )\n\ndef tick():\n global t\n t=t+1\n yield\n\ndef simulation_story(dut):\n\n global t\n t = 0\n\n for i in range(5):\n yield from tick()\n\n # writing\n yield dut.CYC_i.eq(1)\n yield dut.ADR_i.eq(1)\n yield dut.DAT_i.eq(0x1111)\n yield dut.WE_i.eq(1)\n yield dut.STB_i.eq(1)\n \n yield\n yield dut.WE_i.eq(0)\n yield dut.STB_i.eq(0)\n yield\n yield\n \n\n yield from tick()\n\n yield dut.CYC_i.eq(0)\n\n yield from tick()\n\n # waiting for writing\n\n\n\n\n\n # store another number in storage 2\n yield dut.CYC_i.eq(1)\n yield dut.ADR_i.eq(2)\n yield dut.DAT_i.eq(0x2222)\n yield dut.WE_i.eq(1)\n yield dut.STB_i.eq(1)\n \n \n yield\n yield dut.WE_i.eq(0)\n yield dut.STB_i.eq(0)\n yield from tick()\n yield from tick()\n yield dut.CYC_i.eq(0)\n # waiting for writing\n yield from tick()\n\n\n\n # Reading\n yield dut.CYC_i.eq(1)\n yield dut.ADR_i.eq(1)\n\n\n yield dut.STB_i.eq(1)\n \n yield\n yield dut.STB_i.eq(0)\n yield from tick()\n yield from tick()\n yield from tick()\t\n yield dut.CYC_i.eq(0)\n\n yield from tick()\n\n print(\"Red number is \",(yield dut.DAT_o))\n assert( 0x1111 == (yield dut.DAT_o))\n\n\n \n\n\n\n # Reading Vol2\n yield dut.CYC_i.eq(1)\n yield dut.ADR_i.eq(2)\n\n\n yield dut.STB_i.eq(1)\n \n \n yield\n yield dut.STB_i.eq(0)\n yield from tick()\n yield from tick()\n\n yield dut.CYC_i.eq(0)\n\n print(\"Red number is \",(yield dut.DAT_o))\n assert( 0x2222 == (yield dut.DAT_o))\n\n\n\n \n\n\n #writing to the third adress\n yield dut.ADR_i.eq(3)\n yield dut.DAT_i.eq(0x3333)\n yield dut.WE_i.eq(1)\n yield dut.STB_i.eq(1)\n \n yield dut.CYC_i.eq(1)\n yield dut.WE_i.eq(0)\n yield dut.STB_i.eq(0)\n yield\n yield from tick()\n yield from tick()\n\n yield dut.CYC_i.eq(0)\n\n yield from tick()\n \n\n\n yield dut.ADR_i.eq(2)\n\n\n yield dut.STB_i.eq(1)\n \n yield dut.CYC_i.eq(1)\n yield\n yield dut.STB_i.eq(0)\n yield from tick()\n yield from tick()\n\n yield dut.CYC_i.eq(0)\n\n\n print(\"Red number is \",(yield dut.DAT_o))\n assert( 0x2222 == (yield dut.DAT_o))\n\n\n\n\n\n \n yield dut.ADR_i.eq(1)\n yield dut.CYC_i.eq(1)\n\n yield dut.STB_i.eq(1)\n \n \n yield \n yield dut.STB_i.eq(0)\n yield from tick()\n yield from tick()\n\n yield dut.CYC_i.eq(0)\n \n\n\n\n\n # writing to the 4th adress\n\n\n \n yield dut.ADR_i.eq(4)\n yield dut.DAT_i.eq(0x4444)\n yield dut.WE_i.eq(1)\n yield dut.STB_i.eq(1)\n \n yield\n yield\n yield dut.CYC_i.eq(1)\n yield dut.WE_i.eq(0)\n yield dut.STB_i.eq(0)\n \n yield from tick()\n yield from tick()\n yield dut.CYC_i.eq(0)\n yield from tick()\n\n #reading the 4th adress\n\n \n yield dut.ADR_i.eq(4)\n\n yield dut.STB_i.eq(1)\n yield \n yield \n \n yield dut.CYC_i.eq(1)\n yield dut.STB_i.eq(0)\n yield from tick()\n yield from tick()\n yield dut.CYC_i.eq(0)\n \n print(\"Red number is \",(yield dut.DAT_o))\n assert( 0x4444 == (yield dut.DAT_o))\n\n\n print(\"Simulation finished\")\n yield from [None] * 4095\nif __name__ == \"__main__\":\n dut = wb_interface()\n run_simulation(dut, simulation_story(dut), vcd_name=\"test.vcd\")\n","sub_path":"wishbone_interface.py","file_name":"wishbone_interface.py","file_ext":"py","file_size_in_byte":5819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"277250300","text":"# -*- coding: utf-8 -*-\nfrom .basicanalyzer import BasicAnalyzer\n\n\nclass WordAnalyzer(BasicAnalyzer):\n \"\"\"Analyzer to match the content of a paste via regular expressions\"\"\"\n name = \"WordAnalyzer\"\n\n def __init__(self, actions, word, blacklist=None, case_sensitive=False):\n super().__init__(actions, \"{0} ({1})\".format(self.name, word))\n self.word = word\n self.blacklist = blacklist or []\n self.case_sensitive = case_sensitive\n\n def _blacklist_word_found(self, text):\n if self.case_sensitive:\n text = text.lower()\n self.blacklist = [x.lower() for x in self.blacklist]\n\n for word in self.blacklist:\n if word in text:\n return True\n\n return False\n\n def match(self, paste):\n \"\"\"Check if the specified word is part of the paste text\"\"\"\n paste_content = paste.body\n\n if self._blacklist_word_found(paste_content):\n return False\n\n if self.case_sensitive:\n return self.word in paste_content\n else:\n return self.word.lower() in paste_content.lower()\n","sub_path":"pastepwn/analyzers/wordanalyzer.py","file_name":"wordanalyzer.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"460946291","text":"import unittest\nimport json\nimport decimal\nfrom boxoffice import app, init_for\nfrom boxoffice.models import *\nfrom fixtures import init_data\n\n\nclass TestOrder(unittest.TestCase):\n\n def setUp(self):\n self.ctx = app.test_request_context()\n self.ctx.push()\n init_for('test')\n db.create_all()\n init_data()\n self.client = app.test_client()\n\n def test_basic(self):\n item = Item.query.filter_by(name='conference-ticket').first()\n data = {\n 'line_items': [{'item_id': unicode(item.id), 'quantity': 2}],\n 'buyer': {\n 'fullname': 'Testing',\n 'phone': '9814141414',\n 'email': 'test@hasgeek.com',\n }\n }\n ic = ItemCollection.query.first()\n resp = self.client.post('/ic/{ic}/order'.format(ic=ic.id), data=json.dumps(data), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])])\n data = json.loads(resp.data)\n self.assertEquals(resp.status_code, 201)\n order = Order.query.get(data.get('order_id'))\n self.assertEquals(order.status, ORDER_STATUS.PURCHASE_ORDER)\n # 3500*2 = 7000\n self.assertEquals(data['final_amount'], 7000)\n\n def test_order_with_invalid_quantity(self):\n item = Item.query.filter_by(name='conference-ticket').first()\n data = {\n 'line_items': [{'item_id': unicode(item.id), 'quantity': 1001}],\n 'buyer': {\n 'fullname': 'Testing',\n 'phone': '9814141414',\n 'email': 'test@hasgeek.com',\n }\n }\n ic = ItemCollection.query.first()\n resp = self.client.post('/ic/{ic}/order'.format(ic=ic.id), data=json.dumps(data), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])])\n self.assertEquals(resp.status_code, 400)\n\n def test_simple_discounted_item(self):\n discounted_item = Item.query.filter_by(name='t-shirt').first()\n data = {\n 'line_items': [{'item_id': unicode(discounted_item.id), 'quantity': 5}],\n 'buyer': {\n 'fullname': 'Testing',\n 'phone': '9814141414',\n 'email': 'test@hasgeek.com',\n }\n }\n ic = ItemCollection.query.first()\n resp = self.client.post('/ic/{ic}/order'.format(ic=ic.id), data=json.dumps(data), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])])\n data = json.loads(resp.data)\n self.assertEquals(resp.status_code, 201)\n self.assertEquals(data['final_amount'], 2375)\n\n def test_complex_discounted_item(self):\n discounted_item1 = Item.query.filter_by(name='t-shirt').first()\n discounted_item2 = Item.query.filter_by(name='conference-ticket').first()\n data = {\n 'line_items': [{\n 'item_id': unicode(discounted_item1.id),\n 'quantity': 5\n },\n {\n 'item_id': unicode(discounted_item2.id),\n 'quantity': 10\n }\n ],\n 'buyer': {\n 'fullname': 'Testing',\n 'phone': '9814141414',\n 'email': 'test@hasgeek.com',\n }\n }\n ic = ItemCollection.query.first()\n resp = self.client.post('/ic/{ic}/order'.format(ic=ic.id), data=json.dumps(data), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])])\n data = json.loads(resp.data)\n self.assertEquals(resp.status_code, 201)\n # 10*3500@90% + 5*500*@95 = 33875\n self.assertEquals(data['final_amount'], 33875)\n\n def test_discounted_complex_order(self):\n conf = Item.query.filter_by(name='conference-ticket').first()\n tshirt = Item.query.filter_by(name='t-shirt').first()\n conf_price = conf.current_price().amount\n tshirt_price = tshirt.current_price().amount\n conf_quantity = 12\n tshirt_quantity = 5\n coupon2 = DiscountCoupon.query.filter_by(code='coupon2').first()\n coupon3 = DiscountCoupon.query.filter_by(code='coupon3').first()\n data = {\n 'line_items': [{\n 'item_id': unicode(tshirt.id),\n 'quantity': tshirt_quantity\n },\n {\n 'item_id': unicode(conf.id),\n 'quantity': conf_quantity\n }\n ],\n 'discount_coupons': [coupon2.code, coupon3.code],\n 'buyer': {\n 'fullname': 'Testing',\n 'phone': '9814141414',\n 'email': 'test@hasgeek.com',\n }\n }\n ic = ItemCollection.query.first()\n resp = self.client.post('/ic/{ic}/order'.format(ic=ic.id), data=json.dumps(data), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])])\n data = json.loads(resp.data)\n self.assertEquals(resp.status_code, 201)\n resp_json = json.loads(resp.get_data())\n order = Order.query.get(resp_json.get('order_id'))\n tshirt_policy = DiscountPolicy.query.filter_by(title='5% discount on 5 t-shirts').first()\n tshirt_final_amount = (tshirt_price * tshirt_quantity) - (tshirt_quantity * (tshirt_policy.percentage * tshirt_price)/decimal.Decimal(100))\n conf_policy = DiscountPolicy.query.filter_by(title='10% discount on rootconf').first()\n conf_final_amount = (conf_price * (conf_quantity-2)) - ((conf_quantity-2) * (conf_policy.percentage * conf_price)/decimal.Decimal(100))\n self.assertEquals(tshirt_final_amount+conf_final_amount, order.get_amounts().final_amount)\n\n def test_free_order(self):\n item = Item.query.filter_by(name='conference-ticket').first()\n data = {\n 'line_items': [{'item_id': unicode(item.id), 'quantity': 1}],\n 'buyer': {\n 'fullname': 'Testing',\n 'phone': '9814141414',\n 'email': 'test@hasgeek.com',\n },\n 'discount_coupons': ['coupon2']\n }\n ic = ItemCollection.query.first()\n resp = self.client.post('/ic/{ic}/order'.format(ic=ic.id), data=json.dumps(data), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])])\n data = json.loads(resp.data)\n self.assertEquals(resp.status_code, 201)\n order = Order.query.get(data.get('order_id'))\n self.assertEquals(order.status, ORDER_STATUS.PURCHASE_ORDER)\n self.assertEquals(order.line_items[0].status, LINE_ITEM_STATUS.PURCHASE_ORDER)\n self.assertEquals(data['final_amount'], 0)\n resp = self.client.post('/order/{order_id}/free'.format(order_id=order.id), content_type='application/json', headers=[('X-Requested-With', 'XMLHttpRequest'), ('Origin', app.config['BASE_URL'])])\n self.assertEquals(resp.status_code, 201)\n coupon = DiscountCoupon.query.filter_by(code='coupon2').first()\n self.assertEquals(coupon.used_count, 1)\n self.assertEquals(order.status, ORDER_STATUS.SALES_ORDER)\n self.assertEquals(order.line_items[0].status, LINE_ITEM_STATUS.CONFIRMED)\n\n def tearDown(self):\n db.session.rollback()\n db.drop_all()\n self.ctx.pop()\n","sub_path":"tests/test_order.py","file_name":"test_order.py","file_ext":"py","file_size_in_byte":7604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"242347295","text":"import random\nfrom copy import deepcopy\n\nclass Block():\n\n def __init__(self,number):\n self.block_number = number\n self.clear = False\n self.table = False\n\n def set_clear(self):\n self.clear = True\n \n def set_onTable(self):\n self.table = True\n\n def __repr__(self):\n return \"b\"+self.block_number\n\nclass Tower():\n\n def __init__(self,number):\n self.tower_number = number\n self.block_stack = [Block(self.tower_number+str(i)) for i in range(1)]\n top_block = Block(self.tower_number+str(len(self.block_stack)+1))\n top_block.set_clear()\n bottom_block = self.block_stack[0]\n bottom_block.set_onTable()\n self.block_stack.append(top_block)\n \n def remove_blocks(self):\n self.block_stack = []\n\n def pop_block(self):\n top_block = self.get_top_block()\n top_block.set_onTable()\n self.block_stack = self.block_stack[:-1]\n N = len(self.block_stack)\n if N:\n self.block_stack[N-1].set_clear()\n \n def add_block(self,block):\n self.block_stack.append(block)\n\n def get_blocks(self):\n return self.block_stack\n\n def get_top_block(self):\n N = len(self.block_stack)\n return self.block_stack[N-1]\n\n def contains(self,block):\n for b in self.block_stack:\n if block.block_number == b.block_number:\n return True\n return False\n\n def too_high(self):\n if len(self.block_stack) > 1:\n return True\n return False\n\n def __repr__(self):\n return \"t\"+str(self.tower_number)\n \nclass Blocks_world():\n\n bk = [\"clear(+state,-tower,+block)\",\n \"maxtower(+state,+tower)\",\n \"putDown(state,tower,block)\",\n \"stack(state,tower,block)\"]\n\n def __init__(self,number=1,start=False):\n if start:\n self.state_number = number\n self.towers = [Tower(str(i+1)) for i in range(2)]\n self.all_actions = []\n \n def valid(self,action):\n \n pred = action[0]\n tower = action[1]\n block = action[2]\n if pred == \"putDown\":\n if not block.clear:\n return False\n if block.table:\n return False\n if tower.tower_number != str(block.block_number)[0]:\n return False\n if pred == \"stack\":\n if tower.tower_number == str(block.block_number)[0]:\n return False\n if not block.clear:\n return False\n return True\n\n def get_all_actions(self):\n self.all_actions = []\n for action in [\"putDown\",\"stack\"]:\n blocks = []\n for tower in self.towers:\n for block in tower.get_blocks():\n blocks.append(block)\n for tower in self.towers:\n for block in blocks:\n if self.valid((action,tower,block)):\n self.all_actions.append((action,tower,block))\n def max_tower(self):\n '''returns maximum height tower'''\n max_tower = self.towers[0]\n for tower in self.towers:\n if len(tower.get_blocks()) >= len(max_tower.get_blocks()):\n max_tower = tower\n return (max_tower)\n \n def add_tower(self,tower):\n self.towers.append(tower)\n\n def goal(self):\n #print \"length of towers\", len(self.towers)\n blocks = []\n for tower in self.towers:\n blocks += tower.get_blocks()\n blocks = list(set(blocks))\n for tower in self.towers:\n if len(tower.get_blocks()) == len(blocks):\n #print (\"goal checking single block\",tower.block_stack)\n #raw_input()\n #self.get_state_facts()\n #raw_input(\"goal\")\n return True\n #print (\"goal checking greater than 1 block\", tower.block_stack)\n return False\n\n def print_world(self):\n for tower in self.towers:\n print (tower)\n \n\n def execute_action(self,action):\n \n self.state_number += 1\n pred = action[0]\n tower = action[1]\n block = action[2]\n tower_blocks = tower.get_blocks()\n no_of_blocks = len(tower_blocks)\n last_but_one_block_index = no_of_blocks-2 #because indexing starts at 0\n last_but_one_block = tower_blocks[last_but_one_block_index]\n if pred == \"putDown\":\n if not block.clear:\n return self\n if block.table:\n return self\n if tower.tower_number != str(block.block_number)[:-1]:\n return self\n no_of_towers = len(self.towers)\n max_tower_number = max([int(t5.tower_number) for t5 in self.towers])\n new_tower_id = max_tower_number + 1\n new_tower = Tower(str(new_tower_id))\n new_tower.remove_blocks()\n block.set_onTable()\n block.block_number = new_tower.tower_number+str(0)\n new_tower.add_block(block)\n self.add_tower(new_tower)\n last_but_one_block.set_clear()\n tower.pop_block()\n elif pred == \"stack\":\n block_tower_number = 0\n if not block.clear:\n return self\n if tower.tower_number == str(block.block_number)[:-1]:\n return self\n if block.table:\n block_tower_number = str(block.block_number)[:-1]\n #tower_to_pop_off = 't'+str(block.block_number)[0]\n for t in self.towers:\n if t.tower_number == str(block.block_number)[:-1]:\n t.pop_block()\n prev_top_block = tower.get_top_block()\n prev_top_block.clear = False\n block.block_number = tower.tower_number+str(no_of_blocks+1)\n tower.add_block(block)\n if block.table:\n for t2 in self.towers:\n if t2.tower_number == block_tower_number:\n self.towers.remove(t2)\n block.table = False\n return self\n\n def get_state_facts(self):\n facts = []\n max_height = 0\n max_tower = None\n for tower in self.towers:\n blocks = tower.get_blocks()\n n_blocks = len(blocks)\n if n_blocks >= max_height:\n max_height = n_blocks\n max_tower = tower\n '''\n if n_blocks == 2:\n facts.append(\"heighttwo(s\"+str(self.state_number)+\",t\"+tower.tower_number+\")\")\n elif n_blocks > 2:\n facts.append(\"heightgreaterthantwo(s\"+str(self.state_number)+\",t\"+tower.tower_number+\")\")\n '''\n last_block_in_tower = tower.get_top_block()\n for i in range(n_blocks-1):\n if blocks[i].clear:\n facts.append(\"clear(s\"+str(self.state_number)+\",t\"+str(tower.tower_number)+\",b\"+blocks[i].block_number+\")\")\n if blocks[i].table:\n facts.append(\"onTable(s\"+str(self.state_number)+\",t\"+str(tower.tower_number)+\",b\"+blocks[i].block_number+\")\")\n facts.append(\"on(s\"+str(self.state_number)+\",t\"+tower.tower_number+\",b\"+blocks[i].block_number+\",b\"+blocks[i+1].block_number+\")\")\n facts.append(\"clear(s\"+str(self.state_number)+\",t\"+str(tower.tower_number)+\",b\"+last_block_in_tower.block_number+\")\")\n if n_blocks == 1:\n facts.append(\"onTable(s\"+str(self.state_number)+\",t\"+str(tower.tower_number)+\",b\"+last_block_in_tower.block_number+\")\")\n facts.append(\"maxtower(s\"+str(self.state_number)+\",t\"+str(max_tower.tower_number)+\")\")\n \n '''\n for tower in self.towers:\n blocks = tower.get_blocks()\n n_blocks = len(blocks)\n if n_blocks == 1:\n only_block = blocks[0]\n facts.append(\"onTable(s\"+str(self.state_number)+\",b\"+only_block.block_number+\")\")\n for i in range(n_blocks-1):\n #block i+1 is on block i on(S,A,B) means B is on A in stat S\n if i == 0:\n facts.append(\"onTable(s\"+str(self.state_number)+\",b\"+blocks[i].block_number+\")\")\n facts.append(\"on(s\"+str(self.state_number)+\",t\"+tower.tower_number+\",b\"+blocks[i].block_number+\",b\"+blocks[i+1].block_number+\")\")\n for i in range(n_blocks):\n if blocks[i].table:\n facts.append(\"onTable(s\"+str(self.state_number)+\",b\"+blocks[i].block_number+\")\")\n '''\n return facts\n \n def get_top_block_from_other_tower(self):\n '''gets top block from not max tower'''\n for tower in self.towers:\n if tower.tower_number != self.max_tower().tower_number:\n return tower.get_top_block()\n\n def sample(self,pdf):\n cdf = [(i, sum(p for j,p in pdf if j < i)) for i,_ in pdf]\n R = max(i for r in [random.random()] for i,c in cdf if c <= r)\n return R\n\n def execute_random_action(self,actn_dist=0.5):\n self.get_all_actions()\n if random.random() > actn_dist:\n #random_actions = []\n #action_potentials = []\n '''\n for i in range(N):\n random_action = choice(self.all_actions)\n random_actions.append(random_action)\n action_potentials.append(randint(1, 9))\n '''\n N = len(self.all_actions)\n action_potentials = [1 for i in range(N)]\n action_probabilities = [potential/float(sum(action_potentials)) for potential in action_potentials]\n probability_distribution_function = zip(self.all_actions, action_probabilities)\n sampled_action = self.sample(probability_distribution_function)\n sampled_action_predicate = sampled_action[0]\n #sampled_action_string = sampled_action_predicate+\"(s\"+str(self.state_number)+\",\"+str(sampled_action[2])+\")\"\n sampled_action_string = sampled_action_predicate+\"(s\"+str(self.state_number)+\",\"+str(sampled_action[1])+\",\"+str(sampled_action[2])+\").\"\n #sampled_action_string = \"putDown(s\"+str(self.state_number)+\",\"+str(sampled_action[0])+\",\"+str(sampled_action[1])+\").\"\n #print (self.get_state_facts())\n #print (sampled_action_string)\n new_state = self.execute_action(sampled_action)\n #print (new_state.get_state_facts())\n #print (\"state_number incremented when executing action: \",new_state.state_number)\n #print (\"new_state facts\",new_state.get_state_facts())\n actions_not_executed = [action for action in self.all_actions if action != sampled_action]\n return (new_state, [sampled_action_string], actions_not_executed)\n else:\n for tower in self.towers:\n block = self.get_top_block_from_other_tower()\n action = (\"stack\",self.max_tower(),block)\n action_string = \"stack(s\"+str(self.state_number)+\",\"+str(action[1])+\",\"+str(action[2])+\").\"\n new_state = self.execute_action(action)\n actions_not_executed = [item for item in self.all_actions if item != action]\n return (new_state, [action_string], actions_not_executed)\n '''\n N = len(self.all_actions)\n action_potentials = [1 for i in range(N)]\n action_probabilities = [potential/float(sum(action_potentials)) for potential in action_potentials]\n probability_distribution_function = zip(self.all_actions, action_probabilities)\n sampled_action = self.sample(probability_distribution_function)\n sampled_action_predicate = sampled_action[0]\n sampled_action_string = sampled_action_predicate+\"(s\"+str(self.state_number)+\",\"+str(sampled_action[1])+\",\"+str(sampled_action[2])+\").\"\n new_state = self.execute_action(sampled_action)\n actions_not_executed = [action for action in self.all_actions if action != sampled_action]\n return (new_state, [sampled_action_string], actions_not_executed)\n '''\n \n\n'''\nwith open(\"blocks_world_out.txt\",\"a\") as f:\n i = 0\n while i < 2:\n state = Blocks_world(start=True)\n state.print_world()\n f.write(\"start state: \"+str(state.get_state_facts())+\"\\n\")\n while not state.goal():\n f.write(\"=\"*80+\"\\n\")\n state_action_pair = state.execute_random_action()\n state = state_action_pair[0]\n f.write(str(state.get_state_facts())+\"\\n\")\n i += 1\n'''\n","sub_path":"GBFVI/blocks.py","file_name":"blocks.py","file_ext":"py","file_size_in_byte":12679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"554334356","text":"import asyncio\nfrom client_async3 import Client , change_simulator_parameters , get_total_online_users , get_tasks_done , get_total_signedup_users , get_all_clients\nimport time , random\nfrom enum import Enum\n\n\nclient_start_number = 500\nclient_count = 2\n# buffer_size = client_count\nbuffer_size = 20\napi_id = 928742\napi_hash = \"ea831917724660d6f3809349b0c3277f\"\n\ndef start_a_client(index):\n order_number = client_start_number + index\n if str(order_number).find(\"89\") >= 0:\n return False\n phone_number = \"+899\" + '0'*(9-len(str(order_number))) + str(order_number)\n client = Client(f\"Client{order_number}\",api_id,api_hash,phone_number,f\"amin{order_number}\",order_number)\n asyncio.create_task(client.start())\n return True\n\ndef ping_for_current_users():\n all_clients = get_all_clients()\n for client in all_clients:\n client.ping_server()\n print(\"pinging\" , client.first_name)\n # receiver = client.contacts[random.randint(0,len(client.contacts)-1)]\n # client.send_message(receiver, f'Hi, I\\'m {client.first_name}.')\n\nasync def run_server(client_start_number,client_count,buffer_size):\n change_simulator_parameters(new_is_simulator_running=True)\n\n i = 0\n k = 0\n round_number = 0 \n last_round_total_sign_up = 0\n while i 5:\n print(f\"---Round {round_number} encountered a problem---\")\n break\n print(f\" Round {round_number}\")\n print(f\" Waiting for clients to authenticate\")\n print(f\" Number of this round successfull clients={curr_round_signed_up_users}\")\n await asyncio.sleep(1) \n total_signedup_users = get_total_signedup_users() \n curr_round_signed_up_users = total_signedup_users - last_round_total_sign_up\n number_of_tries+=1\n else:\n print(f\"---Round {round_number} finished with {curr_round_signed_up_users} successfulll clients---\\n\")\n i+=buffer_size\n\n last_round_total_sign_up = get_total_signedup_users()\n\n ping_for_current_users()\n\n \n print(\"---All rounds finished---\\n\")\n pinging_counter = time.time()\n while total_signedup_users < client_count*0.9:\n print(f\"Waiting for remaining clients to authenticate\")\n print(f\"---> Total number of successfull clients={total_signedup_users}\\n\")\n await asyncio.sleep(1) \n total_signedup_users = get_total_signedup_users()\n if time.time() - pinging_counter > 40:\n ping_for_current_users()\n pinging_counter = time.time() \n \n print(f\"---Simulator has enough signed up users with:{total_signedup_users} Clients----\\n\")\n change_simulator_parameters(new_simulator_signup_finished_received =True)\n\n\n total_online_users = get_total_online_users()\n\n while total_online_users < client_count*0.9:\n print(f\"Waiting for clients. Number of online clients={total_online_users}\\n\")\n await asyncio.sleep(1) \n total_online_users = get_total_online_users()\n\n if time.time() - pinging_counter > 40:\n ping_for_current_users()\n pinging_counter = time.time() \n\n print(f\"\\n---Simulator started with:{total_online_users} Clients---\\n\")\n change_simulator_parameters(new_simulator_run_signal_received=True)\n\n while True:\n number_of_tasks_done = get_tasks_done()\n total_online_users = get_total_online_users()\n start_round_time = time.time()\n\n await asyncio.sleep(1)\n\n print(f\"Simulator Total Online Users={total_online_users}\")\n if number_of_tasks_done != 0:\n average_time = (time.time() - start_round_time)/number_of_tasks_done\n print(f\"----Tasks average time in last round : {round(average_time,10)} seconds per task\")\n else:\n print(\"----No task done in last round\")\n\n\nasyncio.run(run_server(client_start_number,client_count,buffer_size))","sub_path":"old_files/amin_async_test.py","file_name":"amin_async_test.py","file_ext":"py","file_size_in_byte":4794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"171903342","text":"# Copyright (c) MONAI Consortium\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# http://www.apache.org/licenses/LICENSE-2.0\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import annotations\n\nimport unittest\n\nimport torch\nfrom parameterized import parameterized\n\nfrom monai.transforms.post.dictionary import LabelFilterd\nfrom tests.utils import TEST_NDARRAYS, assert_allclose\n\ngrid_1 = torch.tensor([[[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]])\n\nVALID_TESTS = []\nfor p in TEST_NDARRAYS:\n VALID_TESTS.append(\n [\n \"filter_single_label\",\n {\"applied_labels\": 3},\n p(grid_1),\n p(torch.tensor([[[[0, 0, 3], [0, 0, 0], [0, 0, 0]]]])),\n ]\n )\n\n VALID_TESTS.append(\n [\n \"filter_single_label_list\",\n {\"applied_labels\": [3]},\n p(grid_1),\n p(torch.tensor([[[[0, 0, 3], [0, 0, 0], [0, 0, 0]]]])),\n ]\n )\n\n VALID_TESTS.append(\n [\n \"filter_multi_label\",\n {\"applied_labels\": [3, 5, 8]},\n p(grid_1),\n p(torch.tensor([[[[0, 0, 3], [0, 5, 0], [0, 8, 0]]]])),\n ]\n )\n\n VALID_TESTS.append([\"filter_all\", {\"applied_labels\": [1, 2, 3, 4, 5, 6, 7, 8, 9]}, p(grid_1), p(grid_1)])\n\nITEST_CASE_1 = [\"invalid_image_data_type\", {\"applied_labels\": 1}, [[[[1, 1, 1]]]], NotImplementedError]\n\nINVALID_CASES = [ITEST_CASE_1]\n\n\nclass TestLabelFilter(unittest.TestCase):\n @parameterized.expand(VALID_TESTS)\n def test_correct_results(self, _, args, input_image, expected):\n converter = LabelFilterd(keys=\"image\", **args)\n result = converter({\"image\": input_image})[\"image\"]\n assert_allclose(result, expected)\n\n @parameterized.expand(INVALID_CASES)\n def test_raise_exception(self, _, args, input_image, expected_error):\n with self.assertRaises(expected_error):\n converter = LabelFilterd(keys=\"image\", **args)\n if isinstance(input_image, torch.Tensor) and torch.cuda.is_available():\n _ = converter({\"image\": input_image.cuda()})\n else:\n _ = converter({\"image\": input_image})\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_label_filterd.py","file_name":"test_label_filterd.py","file_ext":"py","file_size_in_byte":2592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"426178748","text":"import argparse\n\nfrom yoyo import read_migrations\nfrom yoyo.connections import connect\nfrom app.db.seeds import seeds\n\n#get config info\nfrom app.config import config\nenv = config.get_env()\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--migrate\", action='store_true')\nparser.add_argument(\"--populate\", action='store_true')\nargs = parser.parse_args()\n\ndef migrate_db():\n conn, paramstyle = connect('postgres://%s:%s@%s/%s' % (env.database_user, env.database_password, env.database_host, env.database_name))\n migrations = read_migrations(conn, paramstyle, 'app/db/migrations/')\n migrations.to_apply().apply()\n conn.commit()\n\ndef populate_db():\n for seed in seeds:\n seed()\n\ndef main(args):\n if args.migrate:\n migrate_db()\n if args.populate:\n populate_db()\n\nif __name__ == '__main__':\n main(args)\n","sub_path":"db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"135811743","text":"from NumericalMethods import Matrix\nfrom NumericalMethods.util.sympy_init import *\n\n\ndef canonical_polynomial(x_list_of_values, y_list_of_values):\n if len(x_list_of_values) != len(y_list_of_values):\n raise IndexError(\"Количество занчений X не совпадает с количеством значений Y\")\n matrix = []\n for row_no in range(len(x_list_of_values)):\n row = []\n for i in range(len(x_list_of_values) - 1, 0, -1):\n row.append(x_list_of_values[row_no] ** i)\n row.append(1)\n matrix.append(row)\n matrix = Matrix(matrix)\n # решение СЛАУ относительно сгененрированной матрицы и столбца свободных членов\n koefs = matrix.slau_solve(y_list_of_values)\n polynomial = 0\n for koef_no in range(len(koefs)):\n polynomial += koefs[::-1][koef_no] * x ** koef_no\n return {\n 'Матрица': matrix,\n 'Столбец свободных членов': y_list_of_values,\n 'Решение СЛАУ': koefs,\n 'Полином': polynomial,\n 'Функция python': lambdify(x, polynomial)\n }\n","sub_path":"NumericalMethods/interpolation/_canonical.py","file_name":"_canonical.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"338778748","text":"from tkinter import *\n\nwindow = Tk()\nwindow.title('Amount Book')\n\nna = {}\n\n\ndef save():\n n = e1.get()\n a = e2.get()\n na[n] = a\n e1.delete(0, END)\n e2.delete(0, END)\n\n\ndef check():\n print(na)\n\n\nl1 = Label(window, text='Name:')\nl1.place(x=10, y=10)\ne1 = Entry(window, width=25)\ne1.place(x=70, y=10)\nl2 = Label(window, text='Amount:')\nl2.place(x=10, y=40)\ne2 = Entry(window, width=25)\ne2.place(x=70, y=40)\nbu1 = Button(window, text='Save', command=save)\nbu1.place(x=70, y=80)\nbu2 = Button(window, text='Check', command=check)\nbu2.place(x=70, y=120)\n\nwindow.mainloop()\n","sub_path":"Basics Pythons/Amount book.py","file_name":"Amount book.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"470125884","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Author : Bhishan Poudel; Physics PhD Student, Ohio University\n# Date : Oct 04, 2016\n# Last update :\n#\n# Ref: http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.linalg.solve.html\n#\n# Imports\nfrom __future__ import division, unicode_literals, print_function\nimport numpy as np\n\n\na = np.array([ [3, 1, 0, 0], [4, 1, 0, 1], [0, 1, -1, 19.9], [4, 0, -1, 4] ])\nb = np.array([1,2,-1,1])\nx = np.linalg.solve(a, b)\n\nprint (x)\n\n# [ 0.82532751 -1.47598253 3. 0.17467249]\n\n##======================================================================\n# checking\nlogic = np.allclose(np.dot(a, x), b)\nprint(logic)\n","sub_path":"Python/science/sympy/solve_system_of_lin_eqns_using_numpy_linalg_solve.py","file_name":"solve_system_of_lin_eqns_using_numpy_linalg_solve.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"287163986","text":"import copy\nimport os\nimport unittest\nfrom pathlib import Path\n\nimport numpy as np\nfrom ray.data import read_json\nfrom ray.rllib.algorithms.dqn import DQNConfig\nfrom ray.rllib.examples.env.cliff_walking_wall_env import CliffWalkingWallEnv\nfrom ray.rllib.examples.policy.cliff_walking_wall_policy import CliffWalkingWallPolicy\nfrom ray.rllib.offline.dataset_reader import DatasetReader\nfrom ray.rllib.offline.estimators import (\n DirectMethod,\n DoublyRobust,\n ImportanceSampling,\n WeightedImportanceSampling,\n)\nfrom ray.rllib.offline.estimators.fqe_torch_model import FQETorchModel\nfrom ray.rllib.policy.sample_batch import SampleBatch, concat_samples\nfrom ray.rllib.utils.framework import try_import_torch\nfrom ray.rllib.utils.numpy import convert_to_numpy\nfrom ray.rllib.utils.test_utils import check\n\nimport ray\n\ntorch, _ = try_import_torch()\n\n\nclass TestOPE(unittest.TestCase):\n \"\"\"Compilation tests for using OPE both standalone and in an RLlib Algorithm\"\"\"\n\n @classmethod\n def setUpClass(cls):\n ray.init()\n rllib_dir = Path(__file__).parent.parent.parent.parent\n train_data = os.path.join(rllib_dir, \"tests/data/cartpole/small.json\")\n\n env_name = \"CartPole-v0\"\n cls.gamma = 0.99\n n_episodes = 3\n cls.q_model_config = {\"n_iters\": 160}\n\n config = (\n DQNConfig()\n .environment(env=env_name)\n .rollouts(batch_mode=\"complete_episodes\")\n .framework(\"torch\")\n .resources(num_gpus=int(os.environ.get(\"RLLIB_NUM_GPUS\", 0)))\n .offline_data(\n input_=\"dataset\", input_config={\"format\": \"json\", \"paths\": train_data}\n )\n .evaluation(\n evaluation_interval=1,\n evaluation_duration=n_episodes,\n evaluation_num_workers=1,\n evaluation_duration_unit=\"episodes\",\n off_policy_estimation_methods={\n \"is\": {\"type\": ImportanceSampling},\n \"wis\": {\"type\": WeightedImportanceSampling},\n \"dm_fqe\": {\"type\": DirectMethod},\n \"dr_fqe\": {\"type\": DoublyRobust},\n },\n )\n )\n cls.algo = config.build()\n\n # Read n_episodes of data, assuming that one line is one episode\n reader = DatasetReader(read_json(train_data))\n batches = [reader.next() for _ in range(n_episodes)]\n cls.batch = concat_samples(batches)\n cls.n_episodes = len(cls.batch.split_by_episode())\n print(\"Episodes:\", cls.n_episodes, \"Steps:\", cls.batch.count)\n\n @classmethod\n def tearDownClass(cls):\n ray.shutdown()\n\n def test_ope_standalone(self):\n # Test all OPE methods standalone\n estimator_outputs = {\n \"v_behavior\",\n \"v_behavior_std\",\n \"v_target\",\n \"v_target_std\",\n \"v_gain\",\n \"v_gain_std\",\n }\n estimator = ImportanceSampling(\n policy=self.algo.get_policy(),\n gamma=self.gamma,\n )\n estimates = estimator.estimate(self.batch)\n self.assertEqual(estimates.keys(), estimator_outputs)\n\n estimator = WeightedImportanceSampling(\n policy=self.algo.get_policy(),\n gamma=self.gamma,\n )\n estimates = estimator.estimate(self.batch)\n self.assertEqual(estimates.keys(), estimator_outputs)\n\n estimator = DirectMethod(\n policy=self.algo.get_policy(),\n gamma=self.gamma,\n q_model_config=self.q_model_config,\n )\n losses = estimator.train(self.batch)\n assert losses, \"DM estimator did not return mean loss\"\n estimates = estimator.estimate(self.batch)\n self.assertEqual(estimates.keys(), estimator_outputs)\n\n estimator = DoublyRobust(\n policy=self.algo.get_policy(),\n gamma=self.gamma,\n q_model_config=self.q_model_config,\n )\n losses = estimator.train(self.batch)\n assert losses, \"DM estimator did not return mean loss\"\n estimates = estimator.estimate(self.batch)\n self.assertEqual(estimates.keys(), estimator_outputs)\n\n def test_ope_in_algo(self):\n # Test OPE in DQN, during training as well as by calling evaluate()\n results = self.algo.train()\n ope_results = results[\"evaluation\"][\"off_policy_estimator\"]\n # Check that key exists AND is not {}\n self.assertEqual(set(ope_results.keys()), {\"is\", \"wis\", \"dm_fqe\", \"dr_fqe\"})\n\n # Check algo.evaluate() manually as well\n results = self.algo.evaluate()\n ope_results = results[\"evaluation\"][\"off_policy_estimator\"]\n self.assertEqual(set(ope_results.keys()), {\"is\", \"wis\", \"dm_fqe\", \"dr_fqe\"})\n\n\nclass TestFQE(unittest.TestCase):\n \"\"\"Compilation and learning tests for the Fitted-Q Evaluation model\"\"\"\n\n @classmethod\n def setUpClass(cls) -> None:\n ray.init()\n env = CliffWalkingWallEnv()\n cls.policy = CliffWalkingWallPolicy(\n observation_space=env.observation_space,\n action_space=env.action_space,\n config={},\n )\n cls.gamma = 0.99\n # Collect single episode under optimal policy\n obs_batch = []\n new_obs = []\n actions = []\n action_prob = []\n rewards = []\n dones = []\n obs = env.reset()\n done = False\n while not done:\n obs_batch.append(obs)\n act, _, extra = cls.policy.compute_single_action(obs)\n actions.append(act)\n action_prob.append(extra[\"action_prob\"])\n obs, rew, done, _ = env.step(act)\n new_obs.append(obs)\n rewards.append(rew)\n dones.append(done)\n cls.batch = SampleBatch(\n obs=obs_batch,\n actions=actions,\n action_prob=action_prob,\n rewards=rewards,\n dones=dones,\n new_obs=new_obs,\n )\n\n @classmethod\n def tearDownClass(cls) -> None:\n ray.shutdown()\n\n def test_fqe_compilation_and_stopping(self):\n \"\"\"Compilation tests for FQETorchModel.\n\n (1) Check that it does not modify the underlying batch during training\n (2) Check that the stopping criteria from FQE are working correctly\n (3) Check that using fqe._compute_action_probs equals brute force\n iterating over all actions with policy.compute_log_likelihoods\n \"\"\"\n fqe = FQETorchModel(\n policy=self.policy,\n gamma=self.gamma,\n )\n tmp_batch = copy.deepcopy(self.batch)\n losses = fqe.train(self.batch)\n\n # Make sure FQETorchModel.train() does not modify the batch\n check(tmp_batch, self.batch)\n\n # Make sure FQE stopping criteria are respected\n assert len(losses) == fqe.n_iters or losses[-1] < fqe.min_loss_threshold, (\n f\"FQE.train() terminated early in {len(losses)} steps with final loss\"\n f\"{losses[-1]} for n_iters: {fqe.n_iters} and \"\n f\"min_loss_threshold: {fqe.min_loss_threshold}\"\n )\n\n # Test fqe._compute_action_probs against \"brute force\" method\n # of computing log_prob for each possible action individually\n # using policy.compute_log_likelihoods\n obs = torch.tensor(self.batch[\"obs\"], device=fqe.device)\n action_probs = fqe._compute_action_probs(obs)\n action_probs = convert_to_numpy(action_probs)\n\n tmp_probs = []\n for act in range(fqe.policy.action_space.n):\n tmp_actions = np.zeros_like(self.batch[\"actions\"]) + act\n log_probs = self.policy.compute_log_likelihoods(\n actions=tmp_actions,\n obs_batch=self.batch[\"obs\"],\n )\n tmp_probs.append(np.exp(log_probs))\n tmp_probs = np.stack(tmp_probs).T\n check(action_probs, tmp_probs, decimals=3)\n\n def test_fqe_optimal_convergence(self):\n \"\"\"Test that FQE converges to the true Q-values for an optimal trajectory\n\n self.batch is deterministic since it is collected under a CliffWalkingWallPolicy\n with epsilon = 0.0; check that FQE converges to the true Q-values for self.batch\n \"\"\"\n\n # If self.batch[\"rewards\"] =\n # [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10],\n # and gamma = 0.99, the discounted returns i.e. optimal Q-values are as follows:\n\n q_values = np.zeros(len(self.batch[\"rewards\"]), dtype=float)\n q_values[-1] = self.batch[\"rewards\"][-1]\n for t in range(len(self.batch[\"rewards\"]) - 2, -1, -1):\n q_values[t] = self.batch[\"rewards\"][t] + self.gamma * q_values[t + 1]\n\n print(q_values)\n\n q_model_config = {\n \"polyak_coef\": 1.0,\n \"model\": {\n \"fcnet_hiddens\": [],\n \"activation\": \"linear\",\n },\n \"lr\": 0.01,\n \"n_iters\": 5000,\n }\n\n fqe = FQETorchModel(\n policy=self.policy,\n gamma=self.gamma,\n **q_model_config,\n )\n losses = fqe.train(self.batch)\n print(losses[-10:])\n estimates = fqe.estimate_v(self.batch)\n print(estimates)\n check(estimates, q_values, decimals=1)\n\n\nif __name__ == \"__main__\":\n import pytest\n import sys\n\n sys.exit(pytest.main([\"-v\", __file__]))\n","sub_path":"rllib/offline/estimators/tests/test_ope.py","file_name":"test_ope.py","file_ext":"py","file_size_in_byte":9406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"423468181","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport edward as ed\nimport numpy as np\nimport tensorflow as tf\n\nfrom edward.models import Normal\nfrom tensorflow.contrib import slim\n\n\ndef next_batch(M):\n samples = np.random.normal(4.0, 0.1, M)\n samples.sort()\n return samples\n\n\ndef discriminative_network(x):\n \"\"\"Outputs probability in logits.\"\"\"\n h0 = slim.fully_connected(x, 10, activation_fn=tf.nn.relu)\n return slim.fully_connected(h0, 1, activation_fn=None)\n\n\nclass test_gan_class(tf.test.TestCase):\n\n def test_normal(self):\n with self.test_session() as sess:\n # DATA\n M = 12 # batch size during training\n x_ph = tf.placeholder(tf.float32, [M, 1])\n\n # MODEL\n with tf.variable_scope(\"Gen\"):\n theta = tf.Variable(0.0)\n x = Normal(theta, 0.1, sample_shape=[M, 1])\n\n # INFERENCE\n inference = ed.GANInference(\n data={x: x_ph}, discriminator=discriminative_network)\n inference.initialize(n_iter=1000)\n tf.global_variables_initializer().run()\n\n for _ in range(inference.n_iter):\n x_data = next_batch(M).reshape([M, 1])\n inference.update(feed_dict={x_ph: x_data})\n\n # CRITICISM\n self.assertAllClose(theta.eval(), 4.0, rtol=1.0, atol=1.0)\n\nif __name__ == '__main__':\n ed.set_seed(54432132)\n tf.test.main()\n","sub_path":"tests/inferences/gan_inference_test.py","file_name":"gan_inference_test.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"421686374","text":"from jinja2 import StrictUndefined\nfrom flask import Flask, jsonify, render_template, redirect, request, flash, session\nfrom flask_debugtoolbar import DebugToolbarExtension\n\napp = Flask(__name__)\n\n# Required to use Flask sessions and the debug toolbar\napp.secret_key = \"D$ [batch_size=1, num_vertices, XYZ]\n faces = faces[None, :, :] # [num_faces, 3] -> [batch_size=1, num_faces, 3]\n\n # create texture [batch_size=1, num_faces, texture_size, texture_size, texture_size, RGB]\n textures = torch.ones(1, faces.shape[1], texture_size, texture_size, texture_size, 3, dtype=torch.float32).cuda()\n\n # to gpu\n# ---------------------------------------------------------------------------------\n# extrinsic parameter, link world/object coordinate to camera coordinate\n# ---------------------------------------------------------------------------------\n alpha = 0\n beta = 30\n gamma = 30\n\n tx = 2\n ty = 1\n tz = -5\n \n resolutionX = 512 # in pixel\n resolutionY = 512\n scale = 1\n f = 35 # focal on lens\n sensor_width = 32 # in mm given in blender , camera sensor type\n pixels_in_u_per_mm = (resolutionX*scale)/sensor_width\n pixels_in_v_per_mm = (resolutionY*scale)/sensor_width\n pix_sizeX = 1/pixels_in_u_per_mm\n pix_sizeY = 1/pixels_in_v_per_mm\n \n Cam_centerX = resolutionX/2\n Cam_centerY = resolutionY/2\n\n batch = vertices.shape[0]\n\n t, R = AxisBlend2Rend(tx, ty, tz, m.radians(alpha), m.radians(beta), m.radians(gamma))\n \n t_1 = t # object position [x,y, z] 0 0 5\n t_2 = np.array([-1, 2, 5])\n\n R = np.repeat(R[np.newaxis, :, :], batch, axis=0) # shape of [batch=1, 3, 3]\n t_1 = np.repeat(t_1[np.newaxis, :], 1, axis=0) # shape of [1, 3]\n t_2 = np.repeat(t_2[np.newaxis, :], 1, axis=0)\n\n# ---------------------------------------------------------------------------------\n# intrinsic parameter, link camera coordinate to image plane\n# ---------------------------------------------------------------------------------\n \n K = np.array([[f/pix_sizeX,0,Cam_centerX],\n [0,f/pix_sizeY,Cam_centerY],\n [0,0,1]]) # shape of [nb_vertice, 3, 3]\n \n K = np.repeat(K[np.newaxis, :, :], batch, axis=0) # shape of [batch=1, 3, 3]\n \n # create renderer\n# renderer = nr.Renderer(image_size=512, camera_mode='projection')\n renderer = nr.Renderer(image_size=512, camera_mode='projection',dist_coeffs=None, K=K, R=R, t=t_1, near=0.1, far=1000, orig_size=512)\n renderer2 = nr.Renderer(image_size=512, camera_mode='projection', dist_coeffs=None, K=K, R=R, t=t_2, near=0.1,far=1000, orig_size=512)\n\n# ---------------------------------------------------------------------------------\n# Render object\n# ---------------------------------------------------------------------------------\n\n nb_obj2render = 1\n\n loop = tqdm.tqdm(range(0, 1, 1))\n writer = imageio.get_writer(args.filename_output, mode='i')\n\n for num, obj in enumerate(loop):\n loop.set_description('Rendering objects')\n\n if nb_obj2render == 1: # render 1 3d object\n images_1 = renderer(vertices, faces, textures) # [batch_size, RGB, image_size, image_size]\n image = images_1[0].detach().cpu().numpy()[0].transpose((1, 2, 0))\n\n else: # render 2 3d objects\n images_1 = renderer(vertices, faces, textures)\n images_2 = renderer2(vertices, faces, textures)\n\n image = np.minimum(images_1[0].detach().cpu().numpy()[0].transpose((1, 2, 0)),\n images_2[0].detach().cpu().numpy()[0].transpose((1, 2, 0)))\n\n image[np.int(resolutionX/2), np.int(resolutionY/2)] = [1, 1, 1] # draw middle point camera center\n writer.append_data((255*image).astype(np.uint8))\n\n writer.close()\n\n# ---------------------------------------------------------------------------------\n# Render object silhouette\n# ---------------------------------------------------------------------------------\n\n loop = tqdm.tqdm(range(0, 1, 1))\n writer = imageio.get_writer(args.filename_output2, mode='i')\n for num, azimuth in enumerate(loop):\n loop.set_description('Rendering objects silhouettes')\n\n if nb_obj2render == 1: # render 1 3d object\n images_1 = renderer(vertices, faces, textures, mode='silhouettes') # [batch_size, RGB, image_size, image_size]\n image = images_1.detach().cpu().numpy().transpose((1, 2, 0))\n\n else: # render 2 3d objects\n images_1 = renderer(vertices, faces, textures, mode='silhouettes')\n images_2 = renderer2(vertices, faces, textures, mode='silhouettes')\n image = np.maximum(images_1.detach().cpu().numpy().transpose((1, 2, 0)),\n images_2.detach().cpu().numpy().transpose((1, 2, 0)))\n\n writer.append_data((255*image).astype(np.uint8))\n writer.close()\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"3)render_Axis_problem.py","file_name":"3)render_Axis_problem.py","file_ext":"py","file_size_in_byte":6627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"229801718","text":"def myfunction():\n '''this dfunction is to print helloworld\n\n and validate dco string'''\n print(\"hello world\")\n mystr = \"sandeep\"\n help(mystr.lstrip)\n print(dir(mystr))\n\nmyfunction()\n\n# print(myfunction.__doc__)\n#\n# help(myfunction)\n# dir(myfunction())","sub_path":"doc_string.py","file_name":"doc_string.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"421037118","text":"from __future__ import annotations\nfrom typing import List, Tuple\nfrom main import *\nfrom scipy.stats import ttest_ind_from_stats\nfrom scipy.stats import bartlett\nimport cca_core\n\n\n# %% Similarity between Feature Vectors\n# FUNCTION: Cosine Similarity\ndef cosine_similarity(input1, input2):\n \"\"\"Calculating the cosine similarity of two inputs.\n The return values lies in [-1, 1]. `-1` denotes two features are the most unlike,\n `1` denotes they are the most similar.\n Args:\n input1, input2: two input numpy arrays.\n Returns:\n Element-wise cosine similarity of two inputs.\n \"\"\"\n similarity = 1 - scipy.spatial.distance.cosine(input1, input2)\n rounded_similarity = int((similarity * 10000)) / 10000.0\n return rounded_similarity\n\n\ndef check_train_similarity(df_train_data):\n train_similarities = np.array([])\n for i, j in itertools.combinations(df_train_data.index.tolist(), 2):\n train_similarities = np.append(train_similarities, cosine_similarity(\n df_train_data.loc[i, :], df_train_data.loc[j, :]))\n return train_similarities\n\n\ndef check_test_similarity(df_test_data):\n test_similarities = np.array([])\n for i, j in itertools.combinations(df_test_data.index.tolist(), 2):\n test_similarities = np.append(test_similarities,\n cosine_similarity(df_test_data.loc[i, :],\n df_test_data.loc[j, :]))\n return test_similarities\n\n\ndef check_train_test_similarity(df_train_data, df_test_data, n_iter=100):\n train_test_similarities = np.array([])\n for i in range(n_iter):\n train_idx = random.choice(df_train_data.index.tolist())\n test_idx = random.choice(df_test_data.index.tolist())\n train_test_similarities = np.append(train_test_similarities,\n cosine_similarity(\n df_train_data.loc[train_idx, :],\n df_test_data.loc[test_idx, :]))\n return train_test_similarities\n\n\n# %%FUNCTION: Return Mean Squared Error between Original Features and PCA-Transformed Features for Each Observation\ndef compare_pca_inverse(df_train_data, df_test_data, pca_model: PCA,\n num_features: int, split=False):\n if split == False:\n df_untrans = pd.concat([df_train_data, df_test_data])\n pca_transformed_df = pd.concat([pca_train, pca_test])\n df_inverse_trans = pca_model.train_scaler.inverse_transform(\n pca_model.inverse_transform(pca_transformed_df))\n df_diff = pd.DataFrame(df_untrans.to_numpy() - df_inverse_trans)\n return df_diff.apply(abs).mean(axis=1)\n else:\n df_train_inverse_trans = get_pca_inverse(pca_model, pca_model.pcs_train,\n num_features)\n df_test_inverse_trans = get_pca_inverse(pca_model, pca_model.pcs_test,\n num_features)\n df_diff_train = pd.DataFrame(df_train_data - df_train_inverse_trans)\n df_diff_test = pd.DataFrame(df_test_data - df_test_inverse_trans)\n return (df_diff_train ** 2).mean(axis=1), (df_diff_test ** 2).mean(\n axis=1)\n\n\ndef get_pca_inverse(pca_model: PCA, df_transformed: pd.DataFrame,\n num_features: int) -> pd.DataFrame:\n \"\"\"\n Parameters\n ----------\n pca_model : PCA\n Fitted PCA object.\n df_loadings : pd.DataFrame\n Dataframe containing projected loadings from PCA transformation.\n num_features : int\n The number of principal components to keep.\n\n Returns\n -------\n pd.DataFrame\n Return df_loadings PCA inverse transformed back to original space,\n given principal components kept.\n\n NOTE: Dropped principal components are replaced with sparse columns.\n \"\"\"\n sparse_df = pd.DataFrame(0.0, index=np.arange(len(df_transformed)),\n columns=range(num_features,\n df_transformed.shape[1]))\n pcs_filled = pd.concat([df_transformed.loc[:, :num_features - 1],\n sparse_df], axis=1)\n\n return pd.DataFrame(pca_model.train_scaler.inverse_transform(\n pca_model.inverse_transform(pcs_filled)))\n\n\ndef get_reconstruction_errors(pca_model: PCA,\n inputs: Inputs,\n train_or_test: str = \"train\",\n num_features: int = 10) -> pd.DataFrame:\n \"\"\"\n Parameters\n ----------\n pca_model : PCA\n Fitted PCA object.\n inputs: Inputs\n Contains attributes\n train_or_test: str\n Must be \"train\" or \"test\"\n num_features : int\n The number of principal components to keep.\n\n Returns\n -------\n pd.DataFrame\n Contains the residual reconstruction errors.\n \"\"\"\n if train_or_test == \"train\":\n df_transformed = pca_model.pcs_test\n df_original = inputs.df_test_data\n else:\n df_transformed = pca_model.pcs_train\n df_original = inputs.df_train_data\n\n df_reconstructed = get_pca_inverse(pca_model,\n df_transformed, num_features)\n df_errors = pd.DataFrame(df_original.reset_index(drop=True)\n - df_reconstructed)\n return df_errors\n\n\ndef variances_of_the_reconstruction_error(pca: PCA,\n inputs: Inputs,\n train_or_test: str = \"train\") -> List:\n \"\"\"Return list of mean variances of the reconstruction errors.\n\n Precondition:\n PCA object's compute method has been called.\n \"\"\"\n vre = []\n\n for num_features in range(0, pca_model._max_pcs):\n reconstruction_errors = get_reconstruction_errors(pca,\n inputs,\n train_or_test,\n num_features)\n vre.append(np.mean(reconstruction_errors.var()))\n\n return vre\n\n\n# %% RUN Variance of the Reconstruction Error\ndef run_vre():\n col_indices = [i for i in range(512)]\n df = pd.read_csv(paths[12], index_col=False)\n try:\n df = df.drop(\"Unnamed: 0\", axis=1)\n except:\n pass\n\n # GET TRAINING DATA & VAL & TEST DATA\n df_train = df[df.phase == \"train\"]\n df_test = df[df.phase == \"val\"]\n\n df_train_data = df_train.loc[:, col_indices]\n df_test_data = df_test.loc[:, col_indices]\n\n # Get, Plot and Save results\n pca_model = pca()\n pca_model.compute(df_train_data, df_test_data)\n\n train_var_ = variances_of_the_reconstruction_error(pca_model,\n pca_model.pcs_train,\n df_train_data,\n (1, 100))\n\n test_var_ = variances_of_the_reconstruction_error(pca_model,\n pca_model.pcs_test,\n df_test_data,\n (1, 100))\n\n plt.plot(list(range(1, 100)), train_var_, c=\"Hello\")\n\n plt.plot(list(range(1, 100)), test_var_)\n\n\n# %% HELPER FUNCTIONS: Get vector component of observation on Principal Component\ndef get_vector_component(base_vector, some_vector):\n return ((base_vector.dot(some_vector)) / (\n base_vector.dot(base_vector))) * base_vector\n\n\n# WRAPPER FUNCTION: Apply get_vector_component() on PCA-transformed dataframe\ndef get_df_vector_comp(x, l):\n global pca_model\n return get_vector_component(\n pca_model.train_scaler.inverse_transform(pca_model.components_[l]),\n x) # NOTE: Inverse Transformation to de-normalize Principal Component Vectors\n\n\n# FUNCTION: Compare Vector Component (of Training/Testing Observations) on Principal Components\ndef compare_vcomp_pcs(num_pc=10, display=False):\n global df_train_data, df_test_data, pca_model\n\n # PCA: Compare Vector Components of PCs between Training and Test Data\n norm_vcomp_train = []\n norm_vcomp_test = []\n # Compare for top num_pc components\n for l in range(num_pc):\n # sum_vcomp_train.append(df_train_data.apply(lambda x: get_df_vector_comp(x, l), axis=1).abs().sum())\n # sum_vcomp_test.append(df_test_data.apply(lambda x: get_df_vector_comp(x, l), axis=1).abs().sum())\n norm_vcomp_train.append(np.median(np.linalg.norm(\n df_train_data.apply(lambda x: get_df_vector_comp(x, l), axis=1))))\n norm_vcomp_test.append(np.median(np.linalg.norm(\n df_test_data.apply(lambda x: get_df_vector_comp(x, l), axis=1))))\n if display != False:\n print(cosine_similarity(norm_vcomp_train, norm_vcomp_test))\n\n\n# %% FUNCTION: Get Cosine Similarity Within and Between Clusters\ndef compare_cluster_similarity():\n global pca_model, num_cluster, dataset_num, chosen_features\n include_elbow = False\n n_iter = 100\n random_state = None\n df_data = df_test.copy()\n\n # Get train and test data\n cluster_train = pca_model.pcs_train.loc[:, :chosen_features - 1]\n cluster_val = pca_model.pcs_test.loc[:, :chosen_features - 1]\n\n # Fit Training, Predict Cluster\n cluster_prediction, cluster_distances, metrics = cluster_kmeans(\n cluster_train,\n cluster_val,\n num_clusters=num_cluster,\n n_iter=n_iter,\n r_state=random_state,\n include_elbow=include_elbow)\n # Getting cluster sizes\n cluster_indiv_num = pd.Series(\n cluster_prediction).value_counts().index.to_list()\n cluster_sizes = pd.Series(cluster_prediction).value_counts().values\n\n sorted_cluster_sizes = pd.DataFrame(cluster_sizes,\n index=cluster_indiv_num).sort_index().values.flatten()\n\n # Get cluster test accuracies\n df_data[\"cluster\"] = cluster_prediction\n if model_goal == \"regression\":\n df_data[\"prediction_accuracy\"] = df_data.apply(\n lambda x: np.sqrt(((x.predictions - x.labels) ** 2)), axis=1)\n else:\n df_data[\"prediction_accuracy\"] = (df_data.predictions == df_data.labels)\n df_cluster_accuracies = df_data.groupby(by=[\"cluster\"]).mean()[\n \"prediction_accuracy\"]\n\n print(df_cluster_accuracies)\n for i in range(4):\n cluster_num = i\n print(\"Cluster\", i)\n cluster_idx = df_data[df_data.cluster == cluster_num].index.tolist()\n sim_test_transformed = check_test_similarity(\n pca_model.pcs_test.loc[:, :chosen_features - 1].loc[\n np.array(cluster_idx) - len(pca_model.pcs_train), :])\n sim_test_untransformed = check_test_similarity(\n df_data[df_data.cluster == cluster_num].loc[:, col_indices])\n\n print(\"Within Test Cluster Similarity [Original]:\",\n sim_test_untransformed.mean(), sim_test_untransformed.std())\n print(\"Within Test Cluster Similarity [PCA-transformed]:\",\n sim_test_transformed.mean(), sim_test_transformed.std())\n\n sim_train_test_transformed = check_train_test_similarity(\n pca_model.pcs_train.loc[:, :chosen_features - 1],\n pca_model.pcs_test.loc[:, :chosen_features - 1].loc[\n np.array(cluster_idx) - len(pca_model.pcs_train), :],\n n_iter=1000)\n sim_train_test_untransformed = check_train_test_similarity(\n df_train_data.loc[:, col_indices],\n df_test_data.loc[cluster_idx, col_indices],\n n_iter=1000)\n\n print(\"Between Train-Test Similarity [Original]:\",\n sim_train_test_untransformed.mean(),\n sim_train_test_untransformed.std())\n print(\"Between Train-Test Similarity [PCA-transformed]:\",\n sim_train_test_transformed.mean(),\n sim_train_test_transformed.std())\n\n\n# NOTE\n# [Original]\n# cluster prediction based on chosen PCA-transformed features\n# but cosine similarity used on original 512-dimensional features\n\n# %% Checking Stability of First PC / Singular Vector\ndef check_pc_stability(pc):\n pc_accum = []\n for i in range(5):\n pca_model = pca()\n pca_model.compute(df_train_data, df_test_data, whole=False,\n with_scaler=True, with_std=False)\n pc_accum.append(pca_model.pcs_train.loc[:, pc].to_numpy())\n del pca_model\n print(check_train_similarity(pd.DataFrame(pc_accum)))\n\n\n# %% TEST: Significant Difference between PCA Inverse Transforms (with sparsely filled in PCs) and Original Features\ndef test_inverse_difference():\n col_indices = [str(i) for i in range(512)]\n num_cluster = 4\n dataset_num = 10\n chosen_features = 5\n for dataset_num in range(16):\n print(paths[dataset_num])\n\n df = pd.read_csv(paths[dataset_num], index_col=False)\n try:\n df = df.drop(\"Unnamed: 0\", axis=1)\n except:\n pass\n\n # GET TRAINING DATA & VAL & TEST DATA\n df_train = df[df.phase == \"train\"]\n df_test = df[df.phase == \"val\"]\n\n df_train_data = df_train.loc[:, col_indices]\n df_test_data = df_test.loc[:, col_indices]\n\n # Get, Plot and Save results\n pca_model = pca()\n pca_model.compute(df_train_data, df_test_data)\n\n # Assessing PCA-Inverse\n def ttest_inverse_diff(num_features):\n inverse_diffs = compare_pca_inverse(df_train_data=df_train_data,\n df_test_data=df_test_data,\n pca_model=pca_model,\n num_features=num_features,\n split=True)\n if bartlett(inverse_diffs[0], inverse_diffs[1]).pvalue < 0.05:\n equal_var = False\n else:\n equal_var = True\n return ttest_ind_from_stats(inverse_diffs[0].mean(),\n inverse_diffs[0].std(),\n len(inverse_diffs[0]),\n inverse_diffs[1].mean(),\n inverse_diffs[1].std(),\n len(inverse_diffs[1]),\n equal_var=equal_var)\n\n p_value = []\n t_statistic = []\n effect_sizes = []\n for num_features in range(1, 50, 1):\n test = ttest_inverse_diff(num_features)\n print(\"Dimensions: %d, p-value: %f\" % (num_features, test.pvalue))\n print(\"T-Statistic: %f\" % (test.statistic))\n\n inverse_diffs = compare_pca_inverse(df_train_data=df_train_data,\n df_test_data=df_test_data,\n pca_model=pca_model,\n num_features=num_features,\n split=True)\n pooled_std = math.sqrt(\n (inverse_diffs[0].std() ** 2 + inverse_diffs[1].std() ** 2) / 2)\n effect_size = (inverse_diffs[0].mean() - inverse_diffs[\n 1].mean()) / pooled_std\n print(\"Effect Size: %f\" % (effect_size))\n\n p_value.append(test.pvalue)\n t_statistic.append(test.statistic)\n effect_sizes.append(effect_size)\n\n fig = plt.figure()\n fig.suptitle(\"%s | Dataset %d\" % (dataset_used, dataset_num))\n ax1 = fig.add_subplot(221)\n ax2 = fig.add_subplot(222)\n ax3 = fig.add_subplot(223)\n plt.tight_layout(pad=1.5)\n ax1.axhline(0.05,\n ms=2,\n color=\"black\",\n linestyle=\"--\")\n ax1.plot(p_value)\n ax1.set_ylabel('p-value')\n\n ax2.plot(t_statistic)\n ax2.set_ylabel('T-Statistic')\n ax3.plot(effect_sizes)\n ax3.set_ylabel(\"Effect Size\")\n plt.show()\n del pca_model, df_train_data, df_test_data\n\n pooled_var = math.sqrt(\n ((len(inverse_diffs[0]) - 1) * inverse_diffs[0].std() ** 2) + (\n (len(inverse_diffs[1]) - 1) * inverse_diffs[1].std() ** 2)\n / (len(inverse_diffs[0]) + len(inverse_diffs[1]) - 2))\n pooled_std = math.sqrt(\n (inverse_diffs[0].std() ** 2 + inverse_diffs[1].std() ** 2) / 2)\n\n\n# %% PROJECTION PURSUIT: Robust PCA\n\n# from direpack import ppdire, capi, dicomo\n#\n# def proj_pursuit(df_train_data):\n# pca = ppdire(projection_index = dicomo, pi_arguments = {'mode' : 'var', 'center': 'median'}, n_components=4, optimizer='grid',optimizer_options={'ndir':1000,'maxiter':1000}, center_data=True)\n# pca.fit(df_train_data,ndir=200)\n# return pca.x_loadings_\n\n# %% Plot Top 2 Principal Components\n\n\n# %%\nif __name__ == \"__main__\":\n inputs = Inputs(paths)\n\n df_selection_methods = pd.DataFrame()\n\n for dataset_num in inputs.which_datasets:\n # Get training and test data & Include only features\n inputs.get_df_split(dataset_num)\n\n # PCA: Fit & Transform\n pca_model = pca(inputs.chosen_features)\n\n if inputs.exclude_train != 1:\n pca_model.compute(inputs.df_train_data, inputs.df_test_data,\n whole=False, with_scaler=True, with_std=False)\n else:\n pca_model.compute(inputs.df_test_data, inputs.df_test_data,\n whole=False, with_scaler=True, with_std=False)\n\n # Get top 2 PCA-transformed training features and testing features\n a = pca_model.pcs_train.iloc[:, :2]\n b = pca_model.pcs_test.iloc[:, :2]\n\n # Plot 2D reduced features by training and test set\n fig = plt.figure()\n ax1 = fig.add_subplot(121)\n ax2 = fig.add_subplot(122)\n\n ax1.axes.xaxis.set_visible(False)\n ax1.axes.yaxis.set_visible(False)\n ax2.axes.xaxis.set_visible(False)\n ax2.axes.yaxis.set_visible(False)\n\n # Training Set\n a.plot(x=0, y=1, kind=\"scatter\",\n marker=\"o\", c=inputs.df_train.labels,\n colormap=\"Spectral\", alpha=0.2, colorbar=False, grid=False,\n ax=ax1)\n a.plot(x=0, y=1, kind=\"scatter\",\n marker=\"o\", c=inputs.df_train.predictions,\n colormap=\"Spectral\", alpha=0.2, colorbar=False, grid=False,\n ax=ax1,\n ylabel=\"Training Set\")\n a.loc[(inputs.df_train.labels != inputs.df_train.predictions\n ).values].plot(x=0, y=1,\n kind=\"scatter\", color=\"red\", ax=ax1,\n grid=False, alpha=0.8)\n\n # Testing Set\n b.plot(x=0, y=1, kind=\"scatter\",\n marker=\"o\", c=inputs.df_test.labels,\n colormap=\"BrBG\", alpha=0.2, colorbar=False, grid=False,\n ax=ax2)\n b.plot(x=0, y=1, kind=\"scatter\",\n marker=\"o\", c=inputs.df_test.predictions,\n colormap=\"BrBG\", alpha=0.2, colorbar=False, grid=False,\n ax=ax2,\n ylabel=\"Testing Set\")\n b.loc[(inputs.df_test.labels != inputs.df_test.predictions\n ).values].plot(x=0, y=1, kind=\"scatter\",\n color=\"red\", ax=ax2, grid=False, alpha=0.8)\n\n fig.suptitle(paths[dataset_num].replace(absolute_dir + data_dir,\n \"\").replace(\".csv\",\n \"\").replace(\"\\\\\",\n \"||\"))\n plt.tight_layout()\n plt.show()\n","sub_path":"scripts/obsolete/random_tests.py","file_name":"random_tests.py","file_ext":"py","file_size_in_byte":19737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"84366778","text":"import numpy as np\n\nclass TpsConstant(object):\n N_ITER = 20\n EM_ITER = 1\n REG = (.1, .0001)\n RAD = (.01, .0001)\n ROT_REG = np.r_[1e-4, 1e-4, 1e-1]\n OUTLIER_PRIOR = .1\n OURLIER_FRAC = 1e-2\n\nclass TpsGpuConstant(TpsConstant):\n MAX_CLD_SIZE = 150\n BEND_COEF_DIGITS = 6\n OUTLIER_CUTOFF = 1e-2\n","sub_path":"lfd/registration/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"453189854","text":"#!/usr/bin/python\n\n# Problem 4 from Euler Project\n# https://projecteuler.net/problem=4\n\n\ndef checkP(n):\n n = str(n)\n N = n[::-1]\n if n == N:\n return(1)\n else:\n return(0)\n\nmaxP = 1\n\nfor i in range(100, 1000):\n for j in range(100, 1000):\n t1 = 1099 - i\n t2 = 1099 - j\n K = t1 * t2\n if checkP(K) == 1 and K > maxP:\n maxP = K\n\nprint(maxP)\n","sub_path":"Q4.py","file_name":"Q4.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"446007920","text":"\"\"\"\nFilename: plot_stc_metric.py\nAuthor: Damien Irving, irving.damien@gmail.com\nDescription: Plot metrics for the subtropical cells\n\n\"\"\"\n\n# Import general Python modules\n\nimport sys, os, pdb\nimport argparse\nimport numpy\nimport iris\nimport iris.plot as iplt\nfrom iris.experimental.equalise_cubes import equalise_attributes\nimport matplotlib.pyplot as plt\nimport seaborn\n\n# Import my modules\n\ncwd = os.getcwd()\nrepo_dir = '/'\nfor directory in cwd.split('/')[1:]:\n repo_dir = os.path.join(repo_dir, directory)\n if directory == 'ocean-analysis':\n break\n\nmodules_dir = os.path.join(repo_dir, 'modules')\nsys.path.append(modules_dir)\ntry:\n import general_io as gio\n import timeseries\n import spatial_weights\nexcept ImportError:\n raise ImportError('Must run this script from anywhere within the ocean-analysis git repo')\n\n\n# Define functions\n\nexperiment_colors = {'historical': 'orange',\n 'historicalGHG': 'red',\n 'historicalAA': 'blue',\n 'rcp26': '#16DB65',\n 'rcp45': '#058C42',\n 'rcp60': '#04471C',\n 'rcp85': '#0D2818'}\n\nbasin_index = {'pacific': 1,\n 'atlantic': 0,\n 'globe': 2}\n\nhistory = []\n\ndef save_history(cube, field, filename):\n \"\"\"Save the history attribute when reading the data.\n (This is required because the history attribute differs between input files \n and is therefore deleted upon equilising attributes) \n \"\"\" \n\n history.append(cube.attributes['history']) \n\n\ndef plot_hemispheres(ax, nmetric, smetric, experiment, basin):\n \"\"\"Plot interhemispheric comparison.\"\"\"\n \n plt.sca(ax)\n\n iplt.plot(smetric * -1, label=experiment + ', SH',\n color=experiment_colors[experiment], linestyle='--')\n if not basin == 'atlantic':\n iplt.plot(nmetric, label=experiment + ', NH',\n color=experiment_colors[experiment], linestyle='-')\n\n plt.legend()\n plt.ylabel(str(nmetric.units))\n plt.xlabel('Year')\n plt.title(basin.title() + ' hemispheric values')\n\n\ndef plot_comparison(ax, nmetric, smetric, experiment, basin):\n \"\"\"Plot interhemispheric comparison.\"\"\"\n \n plt.sca(ax)\n\n data = nmetric / (-1 * smetric)\n ylabel = 'NH / SH'\n\n iplt.plot(data, label=experiment, color=experiment_colors[experiment])\n\n plt.legend()\n plt.ylabel(ylabel)\n plt.xlabel('Year')\n plt.title(basin.title() + ' hemisphere comparison')\n\n\ndef calc_metrics(sh_cube, nh_cube):\n \"\"\"Calculate the metrics.\"\"\"\n\n dim_coord_names = [coord.name() for coord in sh_cube.dim_coords]\n nh_vert_extents = spatial_weights.calc_vertical_weights_1D(nh_cube.coord('depth'),\n dim_coord_names,\n nh_cube.shape)\n sh_vert_extents = spatial_weights.calc_vertical_weights_1D(sh_cube.coord('depth'),\n dim_coord_names,\n sh_cube.shape)\n \n nh_cube.data = numpy.where(nh_cube.data > 0, nh_cube.data, 0)\n sh_cube.data = numpy.where(sh_cube.data < 0, sh_cube.data, 0)\n \n nh_metric = nh_cube.collapsed(['depth', 'latitude'], iris.analysis.SUM, weights=nh_vert_extents)\n sh_metric = sh_cube.collapsed(['depth', 'latitude'], iris.analysis.SUM, weights=sh_vert_extents)\n\n return sh_metric, nh_metric\n \n\ndef load_data(infile, basin):\n \"\"\"Load, temporally aggregate and spatially slice input data\"\"\"\n \n try:\n with iris.FUTURE.context(cell_datetime_objects=True):\n cube = iris.load(infile, 'ocean_meridional_overturning_mass_streamfunction', callback=save_history)\n equalise_attributes(cube)\n cube = cube.concatenate_cube()\n cube = gio.check_time_units(cube)\n\n cube = cube[:, basin_index[basin], : ,:]\n cube = timeseries.convert_to_annual(cube)\n\n experiment = cube.attributes['experiment_id']\n if experiment == 'historicalMisc':\n experiment = 'historicalAA'\n \n depth_constraint = iris.Constraint(depth=lambda cell: cell <= 250)\n sh_constraint = iris.Constraint(latitude=lambda cell: -30.0 <= cell < 0.0)\n nh_constraint = iris.Constraint(latitude=lambda cell: 0.0 < cell <= 30.0)\n\n sh_cube = cube.extract(depth_constraint & sh_constraint)\n nh_cube = cube.extract(depth_constraint & nh_constraint)\n except OSError:\n sh_cube = nh_cube = experiment = None\n\n return sh_cube, nh_cube, experiment\n\n \ndef main(inargs):\n \"\"\"Run the program.\"\"\"\n\n time_constraints = {}\n time_constraints['historical'] = gio.get_time_constraint(inargs.hist_time)\n time_constraints['rcp'] = gio.get_time_constraint(inargs.rcp_time)\n\n width=10\n height=20\n fig = plt.figure(figsize=(width, height))\n ax_dict = {}\n ax1 = fig.add_subplot(3, 1, 1)\n ax2 = fig.add_subplot(3, 1, 2)\n ax3 = fig.add_subplot(3, 1, 3)\n valid_files = []\n for infiles in inargs.experiment_files:\n spacific_cube, npacific_cube, experiment = load_data(infiles, 'pacific')\n satlantic_cube, natlantic_cube, experiment = load_data(infiles, 'atlantic')\n if experiment:\n spacific_metric, npacific_metric = calc_metrics(spacific_cube, npacific_cube)\n satlantic_metric, natlantic_metric = calc_metrics(satlantic_cube, natlantic_cube)\n plot_hemispheres(ax1, npacific_metric, spacific_metric, experiment, 'pacific')\n plot_comparison(ax2, npacific_metric, spacific_metric, experiment, 'pacific')\n plot_hemispheres(ax3, natlantic_metric, satlantic_metric, experiment, 'atlantic')\n model = spacific_cube.attributes['model_id']\n valid_files.append(infiles)\n\n title = 'Annual Mean Meridional Overturning Mass Streamfunction, %s' %(model)\n plt.suptitle(title, size='large')\n# plt.subplots_adjust(top=0.90)\n\n plt.savefig(inargs.outfile, bbox_inches='tight')\n gio.write_metadata(inargs.outfile, file_info={valid_files[0][0]: history[0]})\n\n\nif __name__ == '__main__':\n\n extra_info =\"\"\" \n\nauthor:\n Damien Irving, irving.damien@gmail.com\n\n\"\"\"\n\n description = 'Plot a summary of the system heat distribution'\n parser = argparse.ArgumentParser(description=description,\n epilog=extra_info, \n argument_default=argparse.SUPPRESS,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n \n parser.add_argument(\"outfile\", type=str, help=\"Output file\") \n parser.add_argument(\"--experiment_files\", type=str, action='append', nargs='*', required=True, \n help=\"Input msftmyz files for a given experiment\")\n\n parser.add_argument(\"--hist_time\", type=str, nargs=2, metavar=('START_DATE', 'END_DATE'), default=None,\n help=\"Time period [default = all]\")\n parser.add_argument(\"--rcp_time\", type=str, nargs=2, metavar=('START_DATE', 'END_DATE'), default=None,\n help=\"Time period [default = all]\")\n\n args = parser.parse_args() \n main(args)\n","sub_path":"visualisation/plot_stc_metric.py","file_name":"plot_stc_metric.py","file_ext":"py","file_size_in_byte":7331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"410298750","text":"import sys\nfrom PyQt5.QtWidgets import (QWidget, QApplication, QLabel, \n QPushButton, QHBoxLayout, QGroupBox,\n QGridLayout, QVBoxLayout, QProgressBar)\nfrom PyQt5.QtGui import QIcon, QPixmap\nfrom PyQt5.QtCore import QTimer\n\nimport constants, creature, creatureInfo, timer, images\n\nclass window(QWidget):\n\n c = constants.constants()\n creature = creature.creature()\n creature_info = creatureInfo.creatureInfo()\n img = images.images()\n\n def __init__(self):\n super().__init__()\n\n self.love_iter = 0\n\n self.window_prosp()\n self.img.make_pixmaps()\n self.init_labels()\n self.init_timers()\n self.set_main_layout()\n\n self.show()\n\n def window_prosp(self):\n self.resize(self.c.WINDOW_WIDTH, self.c.WINDOW_HEIGHT)\n self.move(self.c.POS_X, self.c.POS_Y)\n self.setWindowTitle(\"Tamagotchi\")\n\n def init_labels(self):\n self.bck_label = self.img.make_background(self)\n self.creature_label = self.img.show_creature(self)\n self.love_label = self.img.make_love_label(self)\n\n def init_timers(self):\n self.param_timer = QTimer(self)\n self.param_timer.timeout.connect(self.actualise_creature_parameters)\n self.param_timer.start(10000)\n\n self.move_timer = QTimer(self)\n self.move_timer.timeout.connect(self.img.move_creature)\n self.move_timer.start(100)\n\n self.love_timer = QTimer(self)\n self.love_timer.timeout.connect(self.show_love)\n\n def set_buttons_top(self):\n self.top_group_box = QGroupBox()\n layout = QHBoxLayout()\n\n food_button = QPushButton(\"Nakarm\")\n food_button.clicked.connect(self.food_button_clicked)\n\n sleep_button = QPushButton(\"Połóż spać\")\n sleep_button.clicked.connect(self.sleep_button_clicked)\n\n stroke_button = QPushButton(\"Pogłaszcz\")\n stroke_button.clicked.connect(self.stroke_button_clicked)\n\n clean_button = QPushButton(\"Posprzątaj\")\n clean_button.clicked.connect(self.clean_button_clicked)\n\n layout.addWidget(food_button)\n layout.addWidget(sleep_button)\n layout.addWidget(stroke_button)\n layout.addWidget(clean_button)\n\n self.top_group_box.setLayout(layout)\n \n def set_bottom_right_box(self):\n self.bottom_right_group_box = QGroupBox()\n \n label1 = QLabel(\"Najedzenie\")\n label2 = QLabel(\"Energia\")\n label3 = QLabel(\"Miłość\")\n label4 = QLabel(\"Zdrowie\")\n label5 = QLabel(\"Potrzeba kupy\")\n\n layout = QVBoxLayout()\n layout.addWidget(label1)\n layout.addWidget(label2)\n layout.addWidget(label3)\n layout.addWidget(label4)\n layout.addWidget(label5)\n\n self.bottom_right_group_box.setLayout(layout)\n\n def set_bottom_left_box(self):\n self.boottom_group_box = QGroupBox()\n layout = QVBoxLayout()\n\n layout.addWidget(self.creature_info.make_fed_bar(self.creature.fed))\n layout.addWidget(self.creature_info.make_energy_bar(self.creature.energy))\n layout.addWidget(self.creature_info.make_love_bar(self.creature.love))\n layout.addWidget(self.creature_info.make_health_bar(self.creature.health))\n layout.addWidget(self.creature_info.make_toilet_must_bar(self.creature.toilet_must))\n\n self.boottom_group_box.setLayout(layout)\n \n def set_main_layout(self):\n self.set_buttons_top()\n self.set_bottom_right_box()\n self.set_bottom_left_box()\n\n main_layout = QGridLayout()\n main_layout.addWidget(self.top_group_box, 0, 0, 1, 2)\n main_layout.addWidget(self.boottom_group_box, 2, 1)\n main_layout.addWidget(self.bottom_right_group_box, 2, 0)\n\n main_layout.setRowStretch(0, 1)\n main_layout.setRowStretch(1, 5)\n main_layout.setRowStretch(2, 1)\n\n main_layout.setColumnStretch(0, 1)\n main_layout.setColumnStretch(1, 2)\n\n self.setLayout(main_layout) \n\n def food_button_clicked(self):\n self.make_food_label()\n self.make_food_buttons()\n\n def make_food_label(self):\n self.creature_label = QLabel()\n self.creature_label.resize(150, 200)\n self.creature_label.move(self.c.POS_X + 180, self.c.POS_Y)\n\n self.creature_label.show()\n\n def make_food_buttons(self):\n apple_button = QPushButton(\"Jabłko\")\n apple_button.setIcon(QIcon('Images/Food/jablko.png'))\n apple_button.clicked.connect(self.apple_button_clicked)\n\n banana_button = QPushButton(\"Banan\")\n banana_button.setIcon(QIcon('Images/Food/banan.png'))\n banana_button.clicked.connect(self.banana_button_clicked)\n\n carrot_button = QPushButton(\"Marchewka\")\n carrot_button.setIcon(QIcon('Images/Food/marchew.png'))\n carrot_button.clicked.connect(self.carrot_button_clicked)\n\n layout = QVBoxLayout()\n layout.addWidget(apple_button)\n layout.addWidget(banana_button)\n layout.addWidget(carrot_button)\n\n self.creature_label.setLayout(layout)\n\n def apple_button_clicked(self):\n if(self.creature.apple_count == 2):\n self.creature.overfed()\n self.creature_info.change_love_bar(self.creature.love)\n self.creature_info.change_health_bar(self.creature.health)\n return\n\n self.creature.give_apple()\n\n self.creature_info.change_fed_bar(self.creature.fed)\n self.creature_info.change_toilet_must_bar(self.creature.toilet_must)\n self.creature_info.change_health_bar(self.creature.health)\n\n def banana_button_clicked(self):\n if(self.creature.banana_count == 2):\n self.creature.overfed()\n self.creature_info.change_love_bar(self.creature.love)\n self.creature_info.change_health_bar(self.creature.health)\n return\n\n self.creature.give_banana()\n self.creature_info.change_fed_bar(self.creature.fed)\n self.creature_info.change_toilet_must_bar(self.creature.toilet_must)\n self.creature_info.change_health_bar(self.creature.health)\n\n def carrot_button_clicked(self):\n if(self.creature.carrot_count == 2):\n self.creature.overfed()\n self.creature_info.change_love_bar(self.creature.love)\n self.creature_info.change_health_bar(self.creature.health)\n return\n\n self.creature.give_carrot()\n self.creature_info.change_fed_bar(self.creature.fed)\n self.creature_info.change_toilet_must_bar(self.creature.toilet_must)\n self.creature_info.change_health_bar(self.creature.health)\n \n def sleep_button_clicked(self):\n self.creature.sleep()\n\n def stroke_button_clicked(self):\n self.creature.stroke()\n self.creature_info.change_love_bar(self.creature.love)\n self.start_showing_love()\n \n def clean_button_clicked(self):\n return True\n\n def actualise_creature_parameters(self):\n self.creature.actualise_parameters()\n\n self.creature_info.change_fed_bar(self.creature.fed)\n self.creature_info.change_energy_bar(self.creature.energy)\n self.creature_info.change_love_bar(self.creature.love)\n self.creature_info.change_health_bar(self.creature.health)\n self.creature_info.change_toilet_must_bar(self.creature.toilet_must)\n\n def start_showing_love(self):\n self.love_timer.start(100)\n self.move_timer.stop()\n\n def stop_showing_love(self):\n self.love_iter = 0\n self.img.stop_showing_love()\n\n self.love_timer.stop()\n self.move_timer.start(100)\n\n def show_love(self):\n self.love_iter += 1\n self.img.show_love(self.love_iter)\n\n if(self.love_iter == 36):\n self.stop_showing_love()\n return\n","sub_path":"window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":7846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"156613508","text":"import os\nimport pickle\nimport numpy as np\nimport schedule\nimport time\nimport datetime\nimport shutil\nimport configparser\nimport tkinter\nimport tkinter.messagebox\n\n'''\n\n每隔一天检测一次所有机器的硬盘运行状态\n采集的数据也是天更新一次,按本程序设定,需要在本程序执行的1天内采集得到第一次(也就是第一天)的数据\n\n'./data/'中放着历史磁盘数据(格式是'IP地址_时间.txt')\n'./data2/'中放着采集的当天的数据\n\n步骤1:加载rf模型\n步骤2:从txt文件中提取属性数据,并做标准化(步骤2还包括补充没有采集到的属性数据)\n步骤3:将上一步骤得到的特征放入到模型中,进行预测,得到结果\n步骤4:将当前文件夹的数据移到历史数据文件夹\n\n'''\n\n\ndef MaxMinNormalization(x, Max, Min):\n if x < Min:\n x = Min\n elif x > Max:\n x = Max\n x_normal = 2 * ((x - Min) / (Max - Min)) - 1\n return x_normal\n\n\n# 从配置文件中读取rf模型路径\nconf = configparser.ConfigParser()\nconf.read('conf.ini')\n\npath_model = conf.get('config', 'path_model')\npath_data_yidong_current = conf.get('config', 'path_data_yidong_current')\npath_data_yidong_history = conf.get('config', 'path_data_yidong_history')\n\n# 加载rf.pickle\nwith open(path_model + 'rf.pickle', 'rb') as fr:\n model = pickle.load(fr)\n\n\ndef move_files(dir1, dir2):\n for filename in os.listdir(dir1):\n shutil.move(os.path.join(dir1, filename), dir2)\n\n\ndef job():\n print(\"Start: %s\" % datetime.datetime.now())\n\n files = os.listdir(path_data_yidong_current)\n if files is not None:\n tkinter.messagebox.showwarning('警告', '文件夹是空的!')\n\n data = []\n disk_ids = []\n\n for filename in files:\n sub = []\n\n id = filename.split(\"_\")[0]\n disk_ids.append(id)\n\n with open(path_data_yidong_current + filename, \"r\") as f:\n for line in f:\n if \"Raw_Read_Error_Rate\" in line:\n value = int(line.split()[3])\n value = MaxMinNormalization(value, 32, 200)\n # value = round(value, 2)\n sub.append(value)\n elif \"Spin_Up_Time\" in line:\n value = int(line.split()[3])\n value = MaxMinNormalization(value, 83, 253)\n # value = round(value, 2)\n sub.append(value)\n elif \"Reallocated_Sector_Ct\" in line:\n value = int(line.split()[3])\n value = MaxMinNormalization(value, 5, 252)\n # value = round(value, 2)\n sub.append(value)\n raw_value = int(line.split()[-1])\n raw_value = MaxMinNormalization(raw_value, 0, 43248)\n elif \"Seek_Error_Rate\" in line:\n value = int(line.split()[3])\n value = MaxMinNormalization(value, 38, 252)\n # value = round(value, 2)\n sub.append(value)\n elif \"Power_On_Hours\" in line:\n value = int(line.split()[3])\n value = MaxMinNormalization(value, 11, 100)\n # value = round(value, 2)\n sub.append(value)\n elif \"Temperature_Celsius\" in line:\n value = int(line.split()[3])\n value = MaxMinNormalization(value, 12, 253)\n # value = round(value, 2)\n sub.append(value)\n else:\n continue\n sub.append(raw_value)\n data.append(sub)\n\n data = np.array(data)\n result = model.predict(data)\n\n if sum(result) == 0:\n for id in disk_ids:\n print(\"%s硬盘状态良好!\" % id)\n elif sum(result) > 0:\n indexes = np.where(result == 1)[0]\n for i in indexes:\n print(\"%s有硬盘将在10天内故障!\" % (disk_ids[i]))\n\n print(\"End: %s\" % datetime.datetime.now())\n\n move_files(path_data_yidong_current, path_data_yidong_history)\n\n\nschedule.every().day.do(job)\n\nwhile True:\n schedule.run_pending()\n time.sleep(1)\n","sub_path":"schedule_predict.py","file_name":"schedule_predict.py","file_ext":"py","file_size_in_byte":4187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"166810403","text":"#!/usr/bin/env python\n\n'''\nThis will successfully send an email via engr servers, but only if it is run \nON an engr server. For example, you should not be able to successfuly run \nthis script locally.\n'''\n\n\nimport smtplib\n\nFROM = \"test@onid.oregonstate.edu\"\nTO = [\"bryonb@gmail.com\"]\n\nSUBJECT = \"Hello!\"\n\nTEXT = \"This message was sent with Python's smtplib.\"\n\nmessage = \"\"\"\\\nFrom: %s\nTo: %s\nSubject: %s\n\n%s\n\"\"\" % (FROM, \", \".join(TO), SUBJECT, TEXT)\n\nserver = smtplib.SMTP(\"mail.engr.oregonstate.edu\")\nserver.sendmail(FROM, TO, message)\nserver.close()\n","sub_path":"emailTesting/engr-test.py","file_name":"engr-test.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"536447202","text":"#-------------------------------------------------------------------------------\n# Name: non_ATCG_letter_converter\n# Purpose: To match ambiguous DNA base pairs with their corresponding\n# boolean values.\n#\n# Author: Julian\n#\n# Created: 19/08/2014\n# Copyright: (c) Julian 2014\n# Licence: \n#-------------------------------------------------------------------------------\n\n# non_ATCG_letter_converter() takes non-ATCG base pair as string and next\n# correct base pair from recognition sequence as string and returns a boolean\n# to determine whether to continue pairing for restriction enzyme, True if\n# match is allowed, False otherwise\n\n\n# Conversions based on following table\n'''\nNucleotide Symbols Used:\n======================================================================\nR = A or G M = A or C H = A, C or T N = A, C, G or T\nY = C or T K = G or T V = A, C or G\n S = C or G B = C, G or T\n W = A or T D = A, G or T\n======================================================================\n'''\n\n# Tsil of valid bp's used in test_for_bp_symbols\nvalid_bp_tsil = ['A', 'T', 'C', 'G', 'R', 'Y', 'M', 'K', 'S', 'W', 'H', 'V', \\\n'B', 'D', 'N']\n\ndef non_ATCG_letter_converter(bp_read, bp_recseq):\n if test_for_ATCG(bp_read) == True and test_for_ATCG(bp_recseq) == True:\n raise TypeError('Either base pair must be non-ATCG.')\n elif len(bp_read) > 1 or len(bp_recseq) > 1:\n raise TypeError('Only one base pair may be compared at a time.')\n elif test_for_bp_symbols(bp_recseq) == False or \\\n test_for_bp_symbols(bp_read) == False:\n raise TypeError('Invalid symbol for bp - ' + bp_read + ' or ' +\\\n bp_recseq + '.')\n elif bp_recseq == bp_read:\n return True\n elif bp_recseq == 'N':\n return True\n elif bp_recseq == 'R':\n if bp_read == 'A' or bp_read == 'G':\n return True\n else:\n return False\n elif bp_recseq == 'Y':\n if bp_read == 'C' or bp_read == 'T':\n return True\n else:\n return False\n elif bp_recseq == 'M':\n if bp_read == 'A' or bp_read == 'C':\n return True\n else:\n return False\n elif bp_recseq == 'K':\n if bp_read == 'G' or bp_read == 'T':\n return True\n else:\n return False\n elif bp_recseq == 'S':\n if bp_read == 'C' or bp_read == 'G':\n return True\n else:\n return False\n elif bp_recseq == 'W':\n if bp_read == 'A' or bp_read == 'T':\n return True\n else:\n return False\n elif bp_recseq == 'H':\n if bp_read == 'A' or bp_read == 'C' or bp_read == 'T' or \\\n bp_read == 'M' or bp_read == 'W' or bp_read == 'Y':\n return True\n else:\n return False\n elif bp_recseq == 'V':\n if bp_read == 'A' or bp_read == 'C' or bp_read == 'G' or \\\n bp_read == 'R' or bp_read == 'M' or bp_read == 'S':\n return True\n else:\n return False\n elif bp_recseq == 'B':\n if bp_read == 'C' or bp_read == 'G' or bp_read == 'T' or \\\n bp_read == 'Y' or bp_read == 'K' or bp_read == 'S':\n return True\n else:\n return False\n elif bp_recseq == 'D':\n if bp_read == 'A' or bp_read == 'G' or bp_read == 'T' or \\\n bp_read == 'R' or bp_read == 'K' or bp_read == 'W':\n return True\n else:\n return False\n elif test_for_ATCG(bp_recseq) == True:\n return False\n else:\n raise TypeError('nonATCGerror - Base pair is of invalid \\\n letterhead.')\n\n\n# Utility method for non_ATCG_to_letter_converter used for taking in a bp and\n# returning True if that bp is A or T or C or G or False otherwise\n# If kwarg return_non_ATCG_bp is not False, then bp is returned instead of True\ndef test_for_ATCG(bp_to_test, return_non_ATCG_bp = False):\n if bp_to_test == 'A' or bp_to_test == 'T' or bp_to_test == 'C' or \\\n bp_to_test == 'G':\n return True\n else:\n if return_non_ATCG_bp == False:\n return False\n else:\n return bp_to_test\n\n# Utility method for non_ATCG_to_letter_converter used to test whether bp args\n# are valid nucleotide symbols, tests each bp in arg string and returns False\n# if one of them is invalid\ndef test_for_bp_symbols(bp_to_test):\n result = False\n for poss_bp in valid_bp_tsil:\n if bp_to_test == poss_bp:\n result = True\n return result\n","sub_path":"find_sequence/non_ATCG_letter_converter/non_ATCG_letter_converter.py","file_name":"non_ATCG_letter_converter.py","file_ext":"py","file_size_in_byte":4572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"443893322","text":"# -----Code2040 (2017) Fellows Tech Assessment-----\n\n\n# Step 1: Registration\nimport requests\n\nAPI_TOKEN = '83d9b617120d0299bc0e0c3ef0397752'\nREGISTRATION_ENDPOINT = \"http://challenge.code2040.org/api/register\"\nMY_GITHUB = \"https://github.com/rosaswaby/Code2040-2017-Tech_Assessment\"\n\nr = requests.post(REGISTRATION_ENDPOINT, data = {'token':API_TOKEN, 'github':MY_GITHUB})\nprint(r.text)\n","sub_path":"Step1.py","file_name":"Step1.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"465643562","text":"#!/usr/bin/env python3\n\n\"\"\"\nScript that dumps contacts from a csv file into a vcf (VCARD).\nVCARDS are easier to use when importing contacts in mobile.\n\"\"\"\n\nfrom __future__ import annotations\n\n__author__ = \"James (Lemayian) Nakolah\"\n__version__ = \"0.0.20200402\"\n__runtime__ = \"Python=>3.7.0\"\n\nimport csv\nfrom jinja2 import Environment, FileSystemLoader\n\nclass ConConverter:\n \"\"\"\n Contacts Converter:\n Converts contacts from csv files to vcf.\n \"\"\"\n def __init__(self: ConConverter, csv_file: str, vcf_file: str) -> None:\n self.__in = csv_file\n self.__out = vcf_file\n self.__data = self.__read_csv_data()\n \n def __read_csv_data(self: ConConverter) -> list:\n \"\"\"\n Read a cleaned csv file into a dictionary.\n \"\"\"\n with open(self.__in, mode='r') as infile:\n data = [{header: value for header,value in row.items()}\n for row in csv.DictReader(infile, skipinitialspace=True)]\n return data\n \n def write_vcf_data(self: ConConverter) -> None:\n \"\"\"\n Write the contacts data to a vcf (VCARD) file.\n \"\"\"\n env = Environment(loader=FileSystemLoader('.'))\n template = env.get_template('contact_template.vcf.j2')\n output_from_parsed_template = template.render(contacts=self.__data)\n with open(self.__out, mode='w') as outfile:\n outfile.write(output_from_parsed_template)\n\n\nif __name__ == \"__main__\":\n contact_converter = ConConverter('cs_nerds_clean.csv', 'cs_nerds_contacts.vcf')\n contact_converter.write_vcf_data()","sub_path":"convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"491141028","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import k_means\nfrom kmodes.kmodes import KModes\nimport imageio\nfrom io import BytesIO\nfrom scipy.spatial.distance import pdist, squareform\n\nfrom dps.utils import sha_cache, NumpySeed\nfrom dps.datasets.atari import StaticAtariDataset\n\n\n@sha_cache(\"cluster_cache\")\ndef f(game, modes, K, N, in_colour, seed):\n print(\"Running clustering...\")\n with NumpySeed(seed):\n dset = StaticAtariDataset(game=game, after_warp=not in_colour)\n\n X = dset.x\n\n if N:\n X = X[:N, ...]\n else:\n N = X.shape[0]\n\n if not in_colour:\n X = X[..., 0]\n image_shape = X.shape[1:]\n X = X.reshape(N, -1)\n\n if modes:\n km = KModes(n_clusters=K, init='Huang', n_init=1, verbose=1)\n km.fit(X)\n\n centroids = km.cluster_centroids_\n centroids = centroids.reshape(K, *image_shape)\n discrete_centroids = centroids\n centroids = centroids / 255.\n\n labels = km.labels_\n else:\n result = k_means(X / 255., K)\n centroids = result[0]\n discrete_centroids = np.uint8(np.floor(centroids * 255))\n\n centroids = np.maximum(centroids, 1e-6)\n centroids = np.minimum(centroids, 1-1e-6)\n centroids = centroids.reshape(K, *image_shape)\n\n labels = np.array(labels)\n X = X.reshape(N, *image_shape)\n return centroids, discrete_centroids, labels, X\n print(\"Done.\")\n\n\n# game = \"IceHockeyNoFrameskip-v4\"\n# K = 10\ngame = \"BankHeistNoFrameskip-v4\"\nK = 10\n\nN = None\nmodes = False\nin_colour = False\nseed = 0\n\ncentroids, discrete_centroids, labels, X = f(game, modes, K, N, in_colour, seed)\n\nhamming_distance = squareform(pdist(discrete_centroids.reshape(K, -1), \"hamming\"))\nprint(hamming_distance)\n\nM = centroids.reshape(K, -1).shape[1]\nprint(M * hamming_distance)\n\nn_plots = 6\nfig, axes = plt.subplots(K, n_plots)\nfor i, centroid in enumerate(discrete_centroids):\n with BytesIO() as output:\n imageio.imwrite(output, centroid, format=\"PNG\")\n contents = output.getvalue()\n\n n_members = (labels == i).sum()\n\n ax = axes[i, 0]\n ax.set_title(\"File size: {}, # of members: {}\".format(len(contents), n_members))\n ax.imshow(centroid)\n\n indices = np.nonzero(labels == i)[0][:n_plots-1]\n\n for j, idx in zip(range(1, n_plots), indices):\n axes[i, j].imshow(X[idx])\n\nplt.show()\n","sub_path":"scripts/clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":2464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"472427039","text":"# preprocessing.py\n\nimport argparse\nimport os\nimport re\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.io\nimport glob\nimport time\nimport scipy.signal as ssignal\n\n## I/O\n\ndef read_file(name,elemsep,linesep,readlines,mapping=None):\n\tf = open(name,'r').read()\n\n\tif mapping == None:\n\t\tdata = [read_line(line,elemsep,greedy_numeric) for line in f.split(linesep)]\n\telse:\n\t\tdata = [read_line(line,elemsep,mapping) for line in f.split(linesep)]\n\n\tif readlines == \"all\":\n\t\treturn data\n\telse:\n\t\treturn data[:int(readlines)]\n\ndef read_line(line,elemsep,mapping):\n\tif not line:\n\t\treturn []\n\ttry:\n\t\tline_data = list(map(mapping, line.strip().split(elemsep)))\n\t\t#print(line_data)\n\t\treturn line_data\n\texcept ValueError:\n\t\treturn []\n\ndef greedy_numeric(string):\n\tif not string:\n\t\treturn np.nan\n\ttry:\n\t\treturn float(string)\n\texcept ValueError:\n\t\treturn np.nan\n\ndef write_line(line,elemsep):\n\treturn elemsep.join([str(elem) for elem in line])\n\ndef write_data(dat,linesep,elemsep):\n\treturn linesep.join([write_line(line,elemsep) for line in dat])\n\ndef filter_wrt(data,key,value):\n\treturn data[data[:,key]==value,:]\n\ndef filter_wrt_function(data,condition):\n\treturn [dat for dat in data if condition(dat)]\n\ndef just_the_names(filenames):\n\treturn [filename.split('/')[-1] for filename in filenames]\n\n## Mathematical operations\n\ndef differentiate(data):\n\treturn [np.diff(dat,axis=0) for dat in data]\n\ndef smooth(data,length):\n\tC = np.array([1]*length)/length\n\tA = 1\n\treturn [ssignal.lfilter(C,A,dat.T).T for dat in data]\n\ndef filter(data,C,A):\n\treturn [ssignal.lfilter(C,A,dat.T).T for dat in data]\n\ndef sin_signal(num,period):\n\tsignal = np.linspace(0,num,num+1)[:-1]\n\tsignal = signal*2*np.pi/period\n\tsignal = np.sin(signal)\n\tsignal = signal.reshape([num,1])\n\treturn signal\n\ndef cos_signal(num,period):\n\tsignal = np.linspace(0,num,num+1)[:-1]\n\tsignal = signal*2*np.pi/period\n\tsignal = np.cos(signal)\n\tsignal = signal.reshape([num,1])\n\treturn signal\n\ndef remove_harmonic_trend(dat,T):\n\tN = len(dat)\n\tX = np.ones([N,3])\n\tX[:,1] = np.ravel(sin_signal(N,T))\n\tX[:,2] = np.ravel(cos_signal(N,T))\n\n\ttheta = np.linalg.lstsq(X,dat)[0]\n\n\treturn dat - np.dot(X,theta)\n\ndef normalize(dat,return_mean_max=False,leave_zero=False):\n\tdat_mean = [np.mean(feat) for feat in dat.T]\n\tdat = np.array([feat-feat_mean for feat,feat_mean in zip(dat.T,dat_mean)]).T\n\t#dat_max = [np.max(np.abs(feat)) for feat in dat.T]\n\tdat_max = [np.std(feat) for feat in dat.T]\n\n\tif leave_zero:\n\t\tfor i,feat_max in enumerate(dat_max):\n\t\t\tif feat_max < 10**-8:\n\t\t\t\tdat_max[i] = 1\n\n\tdat = np.array([feat/feat_max for feat,feat_max in zip(dat.T,dat_max)]).T\n\t#dat = np.array([(feat-0)/feat_max for feat,feat_max in zip(dat.T,dat_max)]).T\n\n\tif return_mean_max:\n\t\treturn dat,dat_mean,dat_max\n\telse:\n\t\treturn dat\n\ndef normalize_ref(dat,dat_mean,dat_max):\n\treturn np.array([(feat - feat_mean)/feat_max for feat,feat_mean,feat_max in zip(dat.T,dat_mean,dat_max)]).T\t\n\t#return np.array([(feat - 0)/feat_max for feat,feat_mean,feat_max in zip(dat.T,dat_mean,dat_max)]).T\t\n\ndef normalize_all(data,leave_zero=False,mean_def=None):\n\tif mean_def is not None:\n\t\tdat_mean = [mean_def for i in range(len(data))]\n\t\tdat_max = [1 for i in range(data[0].shape[1])]\n\t\tdata = [normalize_ref(dat,dat_mean,dat_max) for dat in data]\n\t\t__,dat_mean,dat_max = normalize(np.concatenate(data,axis=0),return_mean_max=True,leave_zero=leave_zero)\n\t\t#print(dat_mean)\n\t\t#print(dat_max)\n\t\tdat_mean = [0 for i in range(data[0].shape[1])]\n\telse:\n\t\t__,dat_mean,dat_max = normalize(np.concatenate(data,axis=0),return_mean_max=True,leave_zero=leave_zero)\n\t\n\t#print(dat_mean)\n\t#print(dat_max)\n\tdata = [normalize_ref(dat,dat_mean,dat_max) for dat in data]\n\t#__,dat_mean,dat_max = normalize(np.concatenate(data,axis=0),return_mean_max=True,leave_zero=leave_zero)\n\t#print(dat_mean)\n\t#print(dat_max)\n\treturn data\n\n#def only_numeric(data):\t\n#\tfirst_row = data[0][0,:]\n#\tis_numeric = [elem for elem in first_row if not np.isfinite(elem)]\n#\tonly_num = [dat[:,is_numeric] for dat in data]\n#\treturn only_num,is_numeric\n\ndef count_numeric(arr):\n\treturn np.sum(np.isfinite(arr))\n\ndef numeric_idxs(data):\t\n\tfirst_row = data[0][0,:]\n\tis_numeric = set([i for i,elem in enumerate(first_row) if np.isfinite(elem)])\n\tfor dat in data[1:]:\n\t\t#print(is_numeric)\n\t\tfirst_row = dat[0,:]\n\t\t#print(first_row)\n\t\tis_numeric = set.intersection(is_numeric,set([i for i,elem in enumerate(first_row) if np.isfinite(elem)]))\n\t#only_num = [dat[:,is_numeric] for dat in data]\n\treturn is_numeric\n\ndef changing_idxs(data):\n\tdat0 = np.concatenate(data,axis=0)\n\t#for row in dat0:\n\t#\t#print(len(np.where(np.isfinite(feat))[0]))\n\t#\tif len(np.where(np.isfinite(row))[0]) < 10:\n\t#\t\tprint(row)\n\tdat_std = [np.std(feat) for feat in dat0.T]\n\t#print(dat_std)\n\tchanging = [i for i,item in enumerate(dat_std) if item > 10**-8]\n\t#print(changing)\n\n\treturn changing\n\n## Managing data\n\ndef remove_small_samples(data,limit):\n\tno_small = [i for i in range(len(data)) if data[i].shape[0] > limit]\n\treturn [data[i] for i in no_small], no_small\n\ndef has_missing(dat):\n\treturn np.any(np.isnan(dat))\n\ndef remove_instances_with_missing(data):\n\tno_missing = [i for i in range(len(data)) if not has_missing(data[i])]\n\tdata = [data[i] for i in no_missing]\n\treturn data,no_missing\n\ndef remove_unchanging(data):\n\tchanging = changing_idxs(data)\n\n\tdata = [dat[:,changing] for dat in data]\n\n\treturn data,changing\n\n# Generating ground truth\n\ndef impending_failure(data,failed,failure_horizon,test_type):\n\t#if dataset in [\"TURBOFAN\",\"ESN_SIM\"]:\n\t#\tfor dat in data:\n\t#\t\tX,y = impending_failure_datapoints(dat,True,failure_horizon,test_type)\n\t#\t\tyield X,y\n\t#elif dataset == \"BACKBLAZE\":\n\tfor dat,failure in zip(data,failed):\n\t\t#failure = \"_fail\" in name\n\t\tX,y = impending_failure_datapoints(dat,failure,failure_horizon,test_type)\n\t\tyield X,y\n\ndef impending_failure_datapoints(dat,failure,failure_horizon,test_type):\n\tN,M = dat.shape\n\tif failure:\n\t\tX = dat\n\t\tif test_type == \"CLASSIFICATION\":\n\t\t\ty = np.concatenate([np.zeros([N-failure_horizon,1]), np.ones([failure_horizon,1])])\n\t\telif test_type == \"REGRESSION\":\n\t\t\tfar_to_fail = failure_horizon*np.ones([N-failure_horizon,1])\n\t\t\tclose_to_fail = -np.array(range(-failure_horizon+1,1),ndmin=2).T\n\t\t\ty = np.concatenate([far_to_fail,close_to_fail])\n\telse:\n\t\tX = dat[:-failure_horizon,:]\n\t\tif test_type == \"CLASSIFICATION\":\n\t\t\ty = np.zeros([N-failure_horizon,1])\n\t\telif test_type == \"REGRESSION\":\n\t\t\ty = failure_horizon*np.ones([N-failure_horizon,1])\n\n\treturn X,y\n\n# split data into train and test\ndef split(data,gt,split_method,train_share=0.6,test_share=0.2,names=\"\",return_names=False):\n\tsplit_method = split_method\n\tif split_method == \"TIMEWISE\":\t\n\t\t#train_share = 0.6\n\t\t#test_share = 0.2\n\t\tN = [np.shape(dat)[0] for dat in data]\n\t\tSplit1 = [int(np.floor(train_share*n)) for n in N]\n\t\tSplit2 = [int(np.floor((train_share+test_share)*n)) for n in N] \n\n\t\ttrain_data = [dat[0:split1,:] for dat,split1 in zip(data,Split1)]\n\t\ttrain_gt = [gt_inst[0:split1,:] for gt_inst,split1 in zip(gt,Split1)]\n\t\ttest_data = [dat[split1:split2,:] for dat,split1,split2 in zip(data,Split1,Split2)]\n\t\ttest_gt = [gt_inst[split1:split2,:] for gt_inst,split1,split2 in zip(gt,Split1,Split2)]\n\n\t\ttrain_names = names\n\t\ttest_names = names\n\t\t\n\telif split_method == \"UNITWISE\":\n\t\t#train_share = 0.2\n\t\t#test_share = 0.2\n\t\tN = len(data)\n\t\tsplit1 = int(np.floor(train_share*N))\n\t\tsplit2 = int(np.floor((train_share+test_share)*N))\n\t\t#print(split1)\n\t\t#print(split2)\n\t\t#print(names)\n\n\t\ttrain_data = data[0:split1]\n\t\ttrain_gt = gt[0:split1]\n\t\ttest_data = data[split1:split2]\n\t\ttest_gt = gt[split1:split2]\n\n\t\ttrain_names = names[0:split1]\n\t\ttest_names = names[split1:split2]\n\n\tif return_names:\n\t\treturn train_data,train_gt,test_data,test_gt,train_names,test_names\n\telse:\n\t\treturn train_data,train_gt,test_data,test_gt\n\n## Visualizations\n\ndef display_parallel(data,explanations):\n\tj = 1\n\tfor dat in data:\n\t\tdat = normalize(dat)\n\t\texpl = []\n\t\tplt.figure()\n\t\tfor i in range(np.shape(dat)[1]):\n\t\t\tfeat = dat[:,i]\n\t\t\tif not np.isnan(feat[0]):\n\t\t\t\texpl.append(explanations[i])\n\t\t\t\tplt.plot(feat)\n\n\t\tplt.legend(expl)\n\t\tplt.title(\"Sample nbr {0:d}\".format(j))\n\t\tj += 1\n\n\tplt.show()\n\nexplorable_types = ['list','dict','ndarray','void']\ndef explore(data,branch_limit,expansion_limit,head=\"\"):\n\t#print(type(data))\n\t#print(len(data))\n\ttry:\n\t\tprint(head + \"{0:s}_{1:d}\".format(type(data).__name__,len(data)))\n\t\tif len(data) < branch_limit and type(data).__name__ in explorable_types: #[list,dict,type(np.ndarray([])),type(np.void())]:\n\t\t\tif isinstance(data,dict):\n\t\t\t\ti = 0\n\t\t\t\tfor elem in data:\n\t\t\t\t\tif i < expansion_limit:\n\t\t\t\t\t\texplore(data[elem],branch_limit,expansion_limit,head+\"{0:s} \".format(elem))\n\t\t\t\t\telse:\n\t\t\t\t\t\tbreak\n\t\t\t\t\ti += 1\n\t\t\telse:\n\t\t\t\ti = 0\n\t\t\t\tfor elem in data:\n\t\t\t\t\tif i < expansion_limit:\n\t\t\t\t\t\texplore(elem,branch_limit,expansion_limit,head+\"{0:d} \".format(i))\n\t\t\t\t\telse:\n\t\t\t\t\t\tbreak\n\t\t\t\t\ti += 1\t\n\texcept TypeError:\n\t\tprint(head + \"{0:s}\".format(type(data).__name__))\n\ndef main(args):\n\tfilename = args.filename\n\tdatatype = args.datatype\n\n\tif datatype == \"SEQUENTIAL\":\n\t\tdata = read_file(filename,elemsep=args.elemsep,linesep=args.linesep,readlines=args.readlines)\n\t\tdata.remove([])\n\t\tdata = np.array(data)\n\n\t\t#data = filter_wrt(data,0,2)\n\n\t\twhile True:\n\t\t\tx = input('Which feature do you want to look at? ')\n\t\t\tx = int(x)\n\t\t\n\t\t\tplt.plot(data[:,x])\n\t\t\tplt.show()\n\t\t\n\telif datatype == \"INSTANCE\":\n\t\tpattern = '[0-9-]*.csv'\n\t\t#pattern = args.pattern\n\t\t#serial_number = \"MJ0351YNG9Z0XA\"\n\t\tlocation = 1\n\n\t\tmelt_instance(args,filename,pattern,location)\n\n\telif datatype == \"LAYERED\":\n\t\tdata = scipy.io.loadmat(filename)\n\t\texplore(data,11000,25)\n\t\t\t\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-f','--filename',dest = 'filename',default=\"\",help='Name of input file')\n parser.add_argument('-t','--target',dest = 'target',default=\"\",help='Name of target directory for melting')\n parser.add_argument('-p','--pattern',dest = 'pattern',default=\"\",help='Input file pattern (regex)') \n parser.add_argument('-d','--datatype',dest = 'datatype',default=\"SEUQENTIAL\",help='Type of data (e.g. SEQUENTIAL,INSTANCE,LAYERED)')\n parser.add_argument('-c','--readlines',dest = 'readlines',default=\"all\",help='Number of lines to read')\n parser.add_argument('-e','--elemsep',dest = 'elemsep',default='\\t',help='Element Separator')\n parser.add_argument('-l','--linesep',dest = 'linesep',default='\\n',help='Line Separator')\n args = parser.parse_args()\n main(args)","sub_path":"preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":10475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"349402017","text":"import os\nimport sys\n\nwith open(sys.argv[1], encoding=\"utf-8\") as file:\n data = file.read(-1)\n\nidx = data.find('\\\\begin{document}')\n\nwith open(sys.argv[1], mode='w', encoding=\"utf-8\") as file:\n print(\"%&preamble\", file=file)\n print(data[idx:], file=file)\n\nwith open(\"preamble.tex\", mode='w', encoding=\"utf-8\") as file:\n print(data[:idx], file=file)\n\nos.system('pdflatex -ini -jobname=\"preamble\" \"&pdflatex preamble.tex\\\\dump\"')\n","sub_path":"preamblify.py","file_name":"preamblify.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"410226048","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime\n\nfrom odoo import models, fields, api, tools\nfrom odoo.tools import image\n\nclass SubjectSubject(models.Model):\n _inherit = \"subject.subject\"\n\n image = fields.Binary('Image', attachment=True)\n image_medium = fields.Binary('Medium', compute=\"_get_image\", store=True, attachment=True)\n image_thumb = fields.Binary('Thumbnail', compute=\"_get_image\", store=True, attachment=True)\n\n @api.depends('image')\n def _get_image(self):\n for record in self:\n if record.image:\n record.image_medium = image.crop_image(record.image, type='top', ratio=(4, 3), thumbnail_ratio=4)\n record.image_thumb = image.crop_image(record.image, type='top', ratio=(4, 3), thumbnail_ratio=6)\n else:\n record.image_medium = False\n record.iamge_thumb = False\n\n description = fields.Text(\n 'Description', translate=True,\n help=\"A precise description of the Course, used only for internal information purposes.\")\n is_popular = fields.Boolean(\"Popular Course\", default=False)\n is_footer = fields.Boolean(\"Show in Footer\", default=False)\n\n @api.model\n def create(self, vals):\n res = super(SubjectSubject, self).create(vals)\n res.onchage_courcse_set_menu()\n return res\n\n @api.onchange('course_level','industry_level')\n def onchage_courcse_set_menu(self):\n course = industry = ''\n for course_level_id in self.env['course.level'].sudo().search([]):\n course += '
  • %s
  • ' % (course_level_id.id, course_level_id.name)\n for industry_id in self.env['course.industry'].sudo().search([]):\n industry += '
  • %s
  • ' % (industry_id.id, industry_id.name)\n menu_content = \"\"\"\n
    \n
    \n
    \n
    \n \n
    \n
    \n
    \n
    \n \n
    \n
    \n
    \n
    \n
      \n
    • \n
      \n

      \"Ceramics\"

      \n
      \n
    • \n
    \n
    \n
    \n
    \n
    \n \"\"\"\n self.env.ref('theme_atts.mega_menu_course').write({'menu_content': menu_content})\n\n\nclass Class(models.Model):\n _inherit = 'class.class'\n\n class_schedule = fields.Char('Class Schedule', compute='_get_class_schedule')\n\n def _get_class_schedule(self):\n for c in self:\n date_start = ''\n class_schedule = ''\n if c.date_start:\n date_start = datetime.strptime(c.date_start, tools.DEFAULT_SERVER_DATE_FORMAT)\n class_schedule += date_start.strftime('%d') +' '+ date_start.strftime('%b') +' '+ date_start.strftime('%Y')\n if c.date_end:\n date_end = datetime.strptime(c.date_end, tools.DEFAULT_SERVER_DATE_FORMAT)\n if date_start:\n class_schedule += ' - '\n class_schedule += date_end.strftime('%d') +' '+ date_end.strftime('%b') +' '+ date_end.strftime('%Y')\n class_schedule += ' '+ '{0:02.0f}:{1:02.0f}'.format(*divmod(c.time_start * 60, 60)) + '-' + '{0:02.0f}:{1:02.0f}'.format(*divmod(c.time_end * 60, 60))\n c.class_schedule = class_schedule\n","sub_path":"beta-dev1/theme_atts/models/course.py","file_name":"course.py","file_ext":"py","file_size_in_byte":4953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"105329163","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nimport datetime\n\nfrom django.core.validators import MaxValueValidator, MinValueValidator\nfrom django.db import models\n\n# from operation.views import recommendForUser\nfrom .models import MovieInfo, MovieSimilar, Review\n\n# Create your views here.\nfrom django.views import View\nfrom django.http import HttpResponse\nimport json\n# 设调取豆瓣评论的API为 douban()\n\nclass ContentView(View):\n\n def get(self, request, movie_id):\n movieinfo = MovieInfo.objects.get(id=movie_id)\n\n # 对用户进行的个性化推荐,user_recommend_movies显示在电影详情页右侧\n\n movie_comments = Review()\n douban_review = movie_comments.getComments_movie(movie_id)\n\n\n all_comments = movie_comments.getUserComments_movie(movie_id)\n\n\n\n # 相似电影\n movie_similar = MovieSimilar()\n similar_movies = movie_similar.getSimilar(movie_id)\n\n\n\n\n return render(request, 'movie_detail.html', {\"movie\": movieinfo,\n \"recommend_list\": similar_movies,\n # 这里用recommend_list 代替了similar\n \"user_review\": all_comments,\n \"douban_review\" :douban_review\n # \"form\": Review()\n })\n\n\nclass AddReview(View):\n # 用户添加用户评论,未考虑多次评论和打分\n def post(self, request):\n if not request.user.is_authenticated:\n return HttpResponse('{\"status\":\"fail\",\",msg\":\"用户未登陆\"}', content_type='application/json')\n\n\n user_id = str(request.user.id)\n movie_id = request.POST.get(\"movie_id\", '0')\n comments = request.POST.get(\"comments\", \"\")\n star = request.POST.get(\"star\", '1')\n\n # comment = Review.objects.hasUserComment(movie_id=movie_id, user_id=user)\n # if comment:\n # return render(request, 'review_fail.html', {'msg':json.dumps({\"msg\": (\"您已经评论过,不能再评论\")})})\n\n if int(movie_id) > int(0) and comments:\n movie_comments = Review()\n comment = movie_comments.hasUserComment(movie_id=movie_id, user_id=user_id)\n if comment:\n return render(request, 'review_fail.html', {'msg':json.dumps({\"msg\": (\"您已经评论过,不能再评论\")})})\n movie_comments.addUserComment(movie_id=movie_id, user_id=user_id, content=comments, star=str(star),\n reviewtime=datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"))\n\n # movie = MovieInfo.objects.get(id=movie_id)\n # movie_comments.movie = movie\n # movie_comments.content = comments\n # movie_comments.user = request.user\n # movie_comments.star = float(star)\n # # movie_comments.user_id = 1\n # # movie_comments.movie_id = 2\n # # movie_comments.content = 'hello'\n # # movie_comments.star = 3.0\n # movie_comments.save()\n #需要修改\n return render(request, 'review_ok.html',{'msg':json.dumps({\"msg\": (\"评论成功\")})})\n else:\n return render(request, 'review_fail.html',{'msg':json.dumps({\"msg\": (\"评论失败,请重新尝试\")})})\n\n\nclass DeleteReview(View):\n def post(self,request):\n user_id = str(request.user.id)\n movie_id = request.POST.get(\"movie_id\", '0')\n movie_comments = Review()\n comment = movie_comments.hasUserComment(movie_id=movie_id, user_id=user_id)\n if not comment:\n return render(request, 'review_fail.html', {'msg':json.dumps({\"msg\": (\"您还未进行评论\")})})\n movie_comments.deleteUserComment(movie_id=movie_id, user_id=user_id)\n # Review.objects.filter(user_id=user,movie_id=movie_id).delete()\n return render(request, 'review_ok.html', {'msg':json.dumps({\"msg\": (\"删除评论成功\")})})\n","sub_path":"apps/movie/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"370815751","text":"from django import forms\nfrom . import models\n\n\nclass SearchForm(forms.Form):\n title = forms.CharField(\n label='タイトル',\n required=False,\n max_length=200\n )\n\n\nclass CommentForm(forms.ModelForm):\n class Meta:\n model = models.Comment\n fields = ('name', 'comment')\n","sub_path":"src/blog/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"133787629","text":"# Lets find the warning\r\n# short script\r\nimport pandas as pd\r\n\r\nmymap={3:1, 5:4, 2:2, 1:8}\r\n\r\nprint(\"test 1: Define dataframe, call map\")\r\ndf1=pd.DataFrame([[3,5],[5,5],[2,5],[1,6]], columns=['a','b'])\r\ndf1['a']=df1['a'].map(mymap)\r\nprint(\"No warning\")\r\n\r\nprint(\"test 2: Define dataframe, slice dataframe, call map\")\r\ndf2=pd.DataFrame([[3,5],[5,5],[2,5],[1,6]], columns=['a','b'])\r\ndf2=df2[df2['b']==5]\r\ndf2['a']=df2['a'].map(mymap)\r\nprint(\"No warning\")\r\n\r\nprint(\"test 3: Define dataframe, define function with mapping, call function\")\r\ndf3=pd.DataFrame([[3,5],[5,5],[2,5],[1,6]], columns=['a','b'])\r\n\r\ndef foo1(df,mymap):\r\n df['a']=df['a'].map(mymap)\r\n\r\nfoo1(df3, mymap)\r\nprint(\"No warning\")\r\n\r\nprint(\"test 4: Define dataframe, define function with slicing and mapping, call function\")\r\ndf4=pd.DataFrame([[3,5],[5,5],[2,5],[1,6]], columns=['a','b'])\r\n\r\ndef foo2(df,mymap): #df passed by reference\r\n df=df[df['b']==5] #local copy made\r\n df['a']=df['a'].map(mymap) #warning\r\n\r\nfoo2(df4, mymap) #first call\r\nprint(\"warning on first call\")\r\nfoo2(df4, mymap) #must be surpressed on second call?\r\nprint(\"no warning on second call\")\r\n\r\nprint(\"test 5: define new function that is same as previous one, call function\")\r\ndef foo3(df,mymap):\r\n df=df[df['b']==5]\r\n df['a']=df['a'].map(mymap)\r\n\r\nfoo3(df4, mymap) #new function first call\r\nprint(\"warning\")\r\nfoo2(df4, mymap)\r\n\r\nprint(\"foo4 does same thing as foo2/3 but in oppisite order\")\r\ndef foo4(df,mymap):\r\n df['a']=df['a'].map(mymap)\r\n df=df[df['b']==5]\r\nfoo4(df4,mymap)\r\nprint(\"no warning\")\r\n","sub_path":"tests/pandaswarning.py","file_name":"pandaswarning.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"505682286","text":"\nimport os\nimport json\nimport sys\n# create the file structure\n\n\nafiles=[]\nif len(sys.argv)>=2:\n imageFilePath = sys.argv[1]\n annotationFilePath = sys.argv[2]\n try:\n os.listdir(imageFilePath)\n except Exception as e:\n \n print(imageFilePath + \" not found\")\nelse:\n print(\"Provide arguments in correct order of annotationDirectory, imageDirectory,darFlowAnnotation directory\")\nimageFiles = os.listdir(imageFilePath)\n\nfor imageFile in imageFiles:\n with open(annotationFilePath + imageFile, 'r+') as fp:\n data = json.load(fp)\n data[\"description\"] = annotationFile.split(\".json\")[0]\n fp.seek(0) # rewind\n json.dump(data, fp)\n fp.truncate()\n","sub_path":"supervisleyDescriptionAdd.py","file_name":"supervisleyDescriptionAdd.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"419079176","text":"from typing import Optional\n\nfrom sqlalchemy.orm.exc import NoResultFound\n\nfrom asgard.db import AsgardDBSession\nfrom asgard.models.account import Account, AccountDB\n\n\nclass AccountsBackend:\n async def get_account_by_id(self, acc_id: int) -> Optional[Account]:\n try:\n async with AsgardDBSession() as s:\n result = (\n await s.query(AccountDB)\n .filter(AccountDB.id == acc_id)\n .one()\n )\n return await Account.from_alchemy_obj(result)\n except NoResultFound:\n return None\n","sub_path":"asgard/backends/accounts.py","file_name":"accounts.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"628098810","text":"# Copyright (C) 2018-2021 Intel Corporation\n# SPDX-License-Identifier: Apache-2.0\n\nimport unittest\n\nimport numpy as np\n\nfrom extensions.middle.TensorIteratorCondition import LoopConditionMatcher\nfrom mo.utils.ir_engine.compare_graphs import compare_graphs\nfrom unit_tests.utils.graph import build_graph_with_attrs\n\n\nclass TensorIteratorConditionTests(unittest.TestCase):\n def test_not_dynamic(self):\n pattern_matcher = LoopConditionMatcher()\n pattern = pattern_matcher.pattern()\n\n graph = build_graph_with_attrs(nodes_with_attrs=pattern['nodes'], edges_with_attrs=pattern['edges'],\n new_nodes_with_attrs=[('maximum', {'kind': 'op', 'op': 'Maximum'}),\n ('maximum_data', {'kind': 'data'}),\n ('TensorIteratorInput', {'kind': 'op', 'op': 'TensorIteratorInput'})],\n new_edges_with_attrs=[('maximum', 'maximum_data'),\n ('Identity_1_data', 'TensorIteratorInput')],\n update_nodes_attributes=[('init_1_data', {'value': np.array([0])}),\n ('init_2_data', {'value': np.array([0])}),\n ('add_1_y_data', {'value': np.array(1)}),\n ('add_2_y_data', {'value': np.array(1)}),\n ('loop_cond_data', {'value': None}),\n ('Identity_2_data', {'value': None}, ),\n ('Enter_1_less_data', {'value': None},),\n ('Enter_2_less_data', {'value': None},),\n ])\n\n pattern_matcher.find_and_replace_pattern(graph)\n graph_ref = build_graph_with_attrs(\n nodes_with_attrs=[('TensorIteratorCondition', {'kind': 'op', 'op': 'TensorIteratorCondition'}),\n ('loop_cond_data', {'kind': 'data'}),\n ('identity_data', {'kind': 'data'}),\n ('StridedSlice', {'kind': 'op', 'op':'StridedSlice'}),\n ('StridedSlice_data', {'kind': 'data'}),\n ('Maximum', {'kind': 'op', 'op': 'Maximum'}),\n ('Maximum_data', {'kind': 'data'}),\n ('minimum_data', {'kind': 'data'}),\n ('TensorIteratorInput', {'kind': 'op', 'op': 'TensorIteratorInput'})\n ],\n edges_with_attrs=[('Maximum', 'Maximum_data'),\n ('StridedSlice', 'StridedSlice_data'),\n ('StridedSlice_data', 'TensorIteratorCondition', {'in':0}),\n ('minimum_data', 'TensorIteratorCondition', {'in':1}),\n ('TensorIteratorCondition', 'loop_cond_data'),\n ('TensorIteratorCondition', 'identity_data'),\n ('identity_data', 'TensorIteratorInput'),\n ],\n update_edge_attrs=None,\n new_nodes_with_attrs=[],\n new_edges_with_attrs=[],\n )\n (flag, resp) = compare_graphs(graph, graph_ref, 'loop_cond_data', check_op_attrs=True)\n self.assertTrue(flag, resp)\n\n\n","sub_path":"model-optimizer/unit_tests/extensions/middle/TensorIteratorCondition_test.py","file_name":"TensorIteratorCondition_test.py","file_ext":"py","file_size_in_byte":3704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"455606339","text":"from django.contrib.staticfiles.testing import StaticLiveServerTestCase\nfrom selenium import webdriver\nfrom selenium.common.exceptions import WebDriverException\nfrom selenium.webdriver.common.keys import Keys\nimport time\nimport os\n\nMAX_WAIT = 10\n\n\nclass NewVisitorTest(StaticLiveServerTestCase):\n\n def setUp(self):\n self.browser = webdriver.Chrome()\n staging_server = os.environ.get('STAGING_SERVER')\n if staging_server:\n self.live_server_url = 'http://' + staging_server\n\n def tearDown(self):\n self.browser.quit()\n\n def test_layout_and_styling(self):\n # Edith goes to the home page\n self.browser.get(self.live_server_url)\n self.browser.set_window_size(1024, 768)\n\n # She notices input box is nicely centered\n inputbox = self.browser.find_element_by_id('id_new_item')\n self.assertAlmostEqual(inputbox.location['x'] + inputbox.size['width'] / 2, 512, delta=10)\n\n # She starts a new list and sees the input is nicely centered there too\n inputbox.send_keys('testing')\n inputbox.send_keys(Keys.ENTER)\n self.wait_for_row_in_list_table('1: testing')\n inputbox = self.browser.find_element_by_id('id_new_item')\n self.assertAlmostEqual(inputbox.location['x'] + inputbox.size['width'] / 2, 512, delta=10)\n\n def wait_for_row_in_list_table(self, text):\n start_time = time.time()\n while True:\n try:\n table = self.browser.find_element_by_id('id_list_table')\n rows = table.find_elements_by_tag_name('tr')\n self.assertIn(text, [row.text for row in rows])\n return\n except (AssertionError, WebDriverException) as e:\n if time.time() - start_time > MAX_WAIT:\n raise e\n time.sleep(0.5)\n\n def test_can_start_a_list_for_one_user(self):\n # Edith has heard of a cool new To-Do list online.\n # She navigates over to the website homepage\n self.browser.get(self.live_server_url)\n\n # She sees the browser title says To-Do lists\n self.assertIn('To-Do', self.browser.title)\n header_text = self.browser.find_element_by_tag_name('h1').text\n self.assertIn('To-Do', header_text)\n\n # She is invited to enter a To-Do item\n inputbox = self.browser.find_element_by_id('id_new_item')\n self.assertEqual(inputbox.get_attribute('placeholder'), 'Enter a to-do item')\n\n # She enters \"Buy peacock feathers\"\n inputbox.send_keys('Buy peacock feathers')\n inputbox.send_keys(Keys.ENTER)\n\n # She sees that buy peacock feathers is displayed in the to-do list\n self.wait_for_row_in_list_table('1: Buy peacock feathers')\n\n # The text box prompts her to add another item\n # She enters \"Use peacock feathers to make a fly\"\n inputbox = self.browser.find_element_by_id('id_new_item')\n inputbox.send_keys('Use peacock feathers to make a fly')\n inputbox.send_keys(Keys.ENTER)\n\n # Now both items are in the list\n self.wait_for_row_in_list_table('1: Buy peacock feathers')\n self.wait_for_row_in_list_table('2: Use peacock feathers to make a fly')\n\n # Satisfied she goes back to sleep\n\n def test_multiple_users_can_star_lists_at_different_urls(self):\n # Edith starts a new to-do list\n self.browser.get(self.live_server_url)\n inputbox = self.browser.find_element_by_id('id_new_item')\n inputbox.send_keys('Buy peacock feathers')\n inputbox.send_keys(Keys.ENTER)\n self.wait_for_row_in_list_table('1: Buy peacock feathers')\n\n # She notices that her list has a unique URL\n edith_list_url = self.browser.current_url\n self.assertRegex(edith_list_url, '/lists/.+')\n\n # Now a new user, Francis, comes along to the site.\n\n # We use a new browser session to make sure that no information of Edith's is coming through from cookies, etc\n self.browser.quit()\n self.browser = webdriver.Chrome()\n\n # Francis visits the home page. There is no sign of Edith's list.\n self.browser.get(self.live_server_url)\n page_text = self.browser.find_element_by_tag_name('body').text\n self.assertNotIn('Buy peacock feathers', page_text)\n self.assertNotIn('make a fly', page_text)\n\n # Francis starts a new list by entering a new item.\n inputbox = self.browser.find_element_by_id('id_new_item')\n inputbox.send_keys('Buy milk')\n inputbox.send_keys(Keys.ENTER)\n self.wait_for_row_in_list_table('1: Buy milk')\n\n # Francis gets his own unique URL\n francis_list_url = self.browser.current_url\n self.assertRegex(francis_list_url, '/lists/.+')\n self.assertNotEqual(edith_list_url, francis_list_url)\n\n # Again there is no trace of Edith's list\n page_text = self.browser.find_element_by_tag_name('body').text\n self.assertNotIn('Buy peacock feathers', page_text)\n self.assertIn('Buy milk', page_text)\n\n # Satisfied they both go to sleep.\n","sub_path":"functional_tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":5108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"218387953","text":"# Copyright 2019 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nimport dataclasses\nfrom typing import List, Optional, Sequence, Tuple\n\nimport pytest\n\nfrom pants.backend.python.lint.isort.rules import IsortFieldSet, IsortRequest\nfrom pants.backend.python.lint.isort.rules import rules as isort_rules\nfrom pants.backend.python.target_types import PythonLibrary\nfrom pants.core.goals.fmt import FmtResult\nfrom pants.core.goals.lint import LintResult, LintResults\nfrom pants.core.util_rules.source_files import SourceFiles, SourceFilesRequest\nfrom pants.engine.addresses import Address\nfrom pants.engine.fs import CreateDigest, Digest, FileContent\nfrom pants.engine.target import Target\nfrom pants.testutil.rule_runner import QueryRule, RuleRunner\n\n\n@pytest.fixture\ndef rule_runner() -> RuleRunner:\n return RuleRunner(\n rules=[\n *isort_rules(),\n QueryRule(LintResults, (IsortRequest,)),\n QueryRule(FmtResult, (IsortRequest,)),\n QueryRule(SourceFiles, (SourceFilesRequest,)),\n ]\n )\n\n\nGOOD_SOURCE = FileContent(\"good.py\", b\"from animals import cat, dog\\n\")\nBAD_SOURCE = FileContent(\"bad.py\", b\"from colors import green, blue\\n\")\nFIXED_BAD_SOURCE = FileContent(\"bad.py\", b\"from colors import blue, green\\n\")\n# Note the as import. Isort by default keeps as imports on a new line, so this wouldn't be\n# reformatted by default. If we set the config/CLI args correctly, isort will combine the two\n# imports into one line.\nNEEDS_CONFIG_SOURCE = FileContent(\n \"needs_config.py\", b\"from colors import blue\\nfrom colors import green as verde\\n\"\n)\nFIXED_NEEDS_CONFIG_SOURCE = FileContent(\n \"needs_config.py\", b\"from colors import blue, green as verde\\n\"\n)\n\n\ndef make_target(rule_runner: RuleRunner, source_files: List[FileContent]) -> Target:\n for source_file in source_files:\n rule_runner.create_file(f\"{source_file.path}\", source_file.content.decode())\n return PythonLibrary({}, address=Address(\"\", target_name=\"target\"))\n\n\ndef run_isort(\n rule_runner: RuleRunner,\n targets: List[Target],\n *,\n config: Optional[str] = None,\n passthrough_args: Optional[str] = None,\n skip: bool = False,\n) -> Tuple[Sequence[LintResult], FmtResult]:\n args = [\"--backend-packages=pants.backend.python.lint.isort\"]\n if config is not None:\n rule_runner.create_file(relpath=\".isort.cfg\", contents=config)\n args.append(\"--isort-config=.isort.cfg\")\n if passthrough_args:\n args.append(f\"--isort-args='{passthrough_args}'\")\n if skip:\n args.append(\"--isort-skip\")\n rule_runner.set_options(args, env_inherit={\"PATH\", \"PYENV_ROOT\", \"HOME\"})\n field_sets = [IsortFieldSet.create(tgt) for tgt in targets]\n lint_results = rule_runner.request(LintResults, [IsortRequest(field_sets)])\n input_sources = rule_runner.request(\n SourceFiles,\n [\n SourceFilesRequest(field_set.sources for field_set in field_sets),\n ],\n )\n fmt_result = rule_runner.request(\n FmtResult,\n [\n IsortRequest(field_sets, prior_formatter_result=input_sources.snapshot),\n ],\n )\n return lint_results.results, fmt_result\n\n\ndef get_digest(rule_runner: RuleRunner, source_files: List[FileContent]) -> Digest:\n return rule_runner.request(Digest, [CreateDigest(source_files)])\n\n\ndef test_passing_source(rule_runner: RuleRunner) -> None:\n target = make_target(rule_runner, [GOOD_SOURCE])\n lint_results, fmt_result = run_isort(rule_runner, [target])\n assert len(lint_results) == 1\n assert lint_results[0].exit_code == 0\n assert lint_results[0].stderr == \"\"\n assert fmt_result.stdout == \"\"\n assert fmt_result.output == get_digest(rule_runner, [GOOD_SOURCE])\n assert fmt_result.did_change is False\n\n\ndef test_failing_source(rule_runner: RuleRunner) -> None:\n target = make_target(rule_runner, [BAD_SOURCE])\n lint_results, fmt_result = run_isort(rule_runner, [target])\n assert len(lint_results) == 1\n assert lint_results[0].exit_code == 1\n assert \"bad.py Imports are incorrectly sorted\" in lint_results[0].stderr\n assert fmt_result.stdout == \"Fixing bad.py\\n\"\n assert fmt_result.output == get_digest(rule_runner, [FIXED_BAD_SOURCE])\n assert fmt_result.did_change is True\n\n\ndef test_mixed_sources(rule_runner: RuleRunner) -> None:\n target = make_target(rule_runner, [GOOD_SOURCE, BAD_SOURCE])\n lint_results, fmt_result = run_isort(rule_runner, [target])\n assert len(lint_results) == 1\n assert lint_results[0].exit_code == 1\n assert \"bad.py Imports are incorrectly sorted\" in lint_results[0].stderr\n assert \"good.py\" not in lint_results[0].stderr\n assert fmt_result.stdout == \"Fixing bad.py\\n\"\n assert fmt_result.output == get_digest(rule_runner, [GOOD_SOURCE, FIXED_BAD_SOURCE])\n assert fmt_result.did_change is True\n\n\ndef test_multiple_targets(rule_runner: RuleRunner) -> None:\n targets = [\n make_target(rule_runner, [GOOD_SOURCE]),\n make_target(rule_runner, [BAD_SOURCE]),\n ]\n lint_results, fmt_result = run_isort(rule_runner, targets)\n assert len(lint_results) == 1\n assert lint_results[0].exit_code == 1\n assert \"bad.py Imports are incorrectly sorted\" in lint_results[0].stderr\n assert \"good.py\" not in lint_results[0].stderr\n assert \"Fixing bad.py\\n\" == fmt_result.stdout\n assert fmt_result.output == get_digest(rule_runner, [GOOD_SOURCE, FIXED_BAD_SOURCE])\n assert fmt_result.did_change is True\n\n\ndef test_respects_config_file(rule_runner: RuleRunner) -> None:\n target = make_target(rule_runner, [NEEDS_CONFIG_SOURCE])\n lint_results, fmt_result = run_isort(\n rule_runner, [target], config=\"[settings]\\ncombine_as_imports=True\\n\"\n )\n assert len(lint_results) == 1\n assert lint_results[0].exit_code == 1\n assert \"needs_config.py Imports are incorrectly sorted\" in lint_results[0].stderr\n assert fmt_result.stdout == \"Fixing needs_config.py\\n\"\n assert fmt_result.output == get_digest(rule_runner, [FIXED_NEEDS_CONFIG_SOURCE])\n assert fmt_result.did_change is True\n\n\ndef test_respects_passthrough_args(rule_runner: RuleRunner) -> None:\n target = make_target(rule_runner, [NEEDS_CONFIG_SOURCE])\n lint_results, fmt_result = run_isort(rule_runner, [target], passthrough_args=\"--combine-as\")\n assert len(lint_results) == 1\n assert lint_results[0].exit_code == 1\n assert \"needs_config.py Imports are incorrectly sorted\" in lint_results[0].stderr\n assert fmt_result.stdout == \"Fixing needs_config.py\\n\"\n assert fmt_result.output == get_digest(rule_runner, [FIXED_NEEDS_CONFIG_SOURCE])\n assert fmt_result.did_change is True\n\n\ndef test_skip(rule_runner: RuleRunner) -> None:\n target = make_target(rule_runner, [BAD_SOURCE])\n lint_results, fmt_result = run_isort(rule_runner, [target], skip=True)\n assert not lint_results\n assert fmt_result.skipped is True\n assert fmt_result.did_change is False\n\n\ndef test_stub_files(rule_runner: RuleRunner) -> None:\n good_stub = dataclasses.replace(GOOD_SOURCE, path=\"good.pyi\")\n bad_stub = dataclasses.replace(BAD_SOURCE, path=\"bad.pyi\")\n fixed_bad_stub = dataclasses.replace(FIXED_BAD_SOURCE, path=\"bad.pyi\")\n\n good_files = [GOOD_SOURCE, good_stub]\n target = make_target(rule_runner, good_files)\n lint_results, fmt_result = run_isort(rule_runner, [target])\n assert len(lint_results) == 1 and lint_results[0].exit_code == 0\n assert lint_results[0].stderr == \"\" and fmt_result.stdout == \"\"\n assert fmt_result.output == get_digest(rule_runner, good_files)\n assert not fmt_result.did_change\n\n target = make_target(rule_runner, [BAD_SOURCE, bad_stub])\n lint_results, fmt_result = run_isort(rule_runner, [target])\n assert len(lint_results) == 1 and lint_results[0].exit_code == 1\n assert \"bad.pyi Imports are incorrectly sorted\" in lint_results[0].stderr\n assert fmt_result.stdout == \"Fixing bad.py\\nFixing bad.pyi\\n\"\n fixed_bad_files = [FIXED_BAD_SOURCE, fixed_bad_stub]\n assert fmt_result.output == get_digest(rule_runner, [*fixed_bad_files, *good_files])\n assert fmt_result.did_change\n","sub_path":"src/python/pants/backend/python/lint/isort/rules_integration_test.py","file_name":"rules_integration_test.py","file_ext":"py","file_size_in_byte":8165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"542327356","text":"\"\"\"\nTestCases for the Notification models. Currently the notification model\nis not very expansive so there are not many tests but there is test\ncoverage for each of the model's modules.\n\"\"\"\n\nfrom django.test import TestCase\nfrom django.test.client import Client\nfrom django.contrib.auth.models import User\nfrom flying_frogs.notifications.models import (NOTIFICATIONS,\n Notification,\n NOTIFICATION_MESSAGE)\n\n\nclass NotificationTestCase(TestCase):\n fixtures = ['initial_data.json']\n\n def setUp(self):\n self.client = Client()\n self.client.get('/user_profiles/load_db/')\n self.password = 'test'\n self.username = 'bleib1dj'\n self.username_two = 'welto1ge'\n self.notification_type = 'accept_friend_request'\n self.user = User.objects.get(username=self.username)\n self.user_two = User.objects.get(username=self.username_two)\n self.notification_message_hard_check = (\"Devon Bleibtrey has sent\" +\n \" you a friend request\")\n\n def test_notification_message(self):\n '''\n Test: Notification Message\n Coverage: Tests that the macro NOTIFICATION_MESSAGE correctly takes\n a string and a notification message based on a provided\n key which is based on the type of notification that is\n being added to the owner's list of notifications.\n Also has a hard check to ensure that the message is being\n formed based on the correct item in the array of returned\n values in the NOTIFICATIONS dict.\n\n Covers all of the notifications available in the\n NOTIFICATIONS dict but only hard checks one of them.\n '''\n for key in NOTIFICATIONS:\n self.assertEqual(NOTIFICATION_MESSAGE('Devon Bleibtrey',\n NOTIFICATIONS[key][1]),\n 'Devon Bleibtrey ' + NOTIFICATIONS[key][1])\n if(key == 'send_friend_request'):\n self.assertEqual(NOTIFICATION_MESSAGE('Devon Bleibtrey',\n NOTIFICATIONS[key][1]),\n self.notification_message_hard_check)\n\n def test_notification_viewed(self):\n '''\n Test: Notification Viewed\n Coverage: Ensures that once a notification is created and then a view\n indicates that the user has viewed the notification that the\n viewed attribute of the notification is changed from False\n to True.\n '''\n profile = self.user_two.get_profile()\n notification = Notification(owner=self.user,\n message=NOTIFICATIONS[self.notification_type],\n notification_type=self.notification_type)\n notification.save()\n profile.notifications.add(notification)\n profile.save()\n viewed_notification = profile.notifications.get(id=notification.id)\n viewed_notification.notification_viewed()\n viewed_notification.save()\n self.assertEqual(viewed_notification.viewed, True)\n","sub_path":"notifications/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"325092669","text":"##########################################################################\n#\n# pgAdmin 4 - PostgreSQL Tools\n#\n# Copyright (C) 2013 - 2020, The pgAdmin Development Team\n# This software is released under the PostgreSQL Licence\n#\n##########################################################################\n\n\"\"\" Implements Utility class for Table and Partitioned Table. \"\"\"\n\nimport copy\n\nfrom flask import render_template\nfrom pgadmin.utils.driver import get_driver\nfrom config import PG_DEFAULT_DRIVER\nfrom pgadmin.tools.schema_diff.directory_compare import compare_dictionaries,\\\n directory_diff\nfrom pgadmin.tools.schema_diff.model import SchemaDiffModel\nfrom pgadmin.tools.schema_diff.compare import SchemaDiffObjectCompare\nfrom pgadmin.tools.schema_diff.node_registry import SchemaDiffRegistry\n\n\nclass SchemaDiffTableCompare(SchemaDiffObjectCompare):\n\n keys_to_ignore = ['oid', 'schema', 'vacuum_table',\n 'vacuum_toast', 'edit_types', 'attnum', 'col_type',\n 'references', 'reltuples', 'rows_cnt']\n\n keys_to_ignore_ddl_comp = ['oid',\n 'schema',\n 'columns',\n 'edit_types',\n 'primary_key',\n 'unique_constraint',\n 'exclude_constraint',\n 'check_constraint',\n 'foreign_key',\n 'reltuples',\n 'rows_cnt'\n ]\n\n keys_to_remove = {\n 'columns': ['relname', 'nspname', 'parent_tbl', 'attrelid', 'adrelid'],\n 'primary_key': ['oid'],\n 'unique_constraint': ['oid'],\n 'check_constraint': ['oid', 'nspname'],\n 'foreign_key': ['oid', 'fknsp', 'confrelid'],\n 'exclude_constraint': ['oid'],\n 'partitions': ['oid'],\n }\n\n keys_to_remove_ddl_comp = {\n 'columns': ['relname', 'nspname', 'parent_tbl', 'attrelid', 'adrelid'],\n 'check_constraint': ['nspname'],\n 'foreign_key': ['fknsp', 'confrelid']\n }\n\n def compare(self, **kwargs):\n \"\"\"\n This function is used to compare all the table objects\n from two different schemas.\n\n :return: Comparison Dictionary\n \"\"\"\n src_sid = kwargs.get('source_sid')\n src_did = kwargs.get('source_did')\n src_scid = kwargs.get('source_scid')\n tar_sid = kwargs.get('target_sid')\n tar_did = kwargs.get('target_did')\n tar_scid = kwargs.get('target_scid')\n sub_modules = ['index', 'rule', 'trigger']\n\n source_tables = self.fetch_tables(sid=src_sid, did=src_did,\n scid=src_scid)\n\n target_tables = self.fetch_tables(sid=tar_sid, did=tar_did,\n scid=tar_scid)\n\n if self.manager.version >= 120000:\n sub_modules.append('compound_trigger')\n\n # If both the dict have no items then return None.\n if not (source_tables or target_tables) or (\n len(source_tables) <= 0 and len(target_tables) <= 0):\n return None\n\n src_server_type, tar_server_type = self.get_server_type(src_sid,\n tar_sid)\n for module in sub_modules:\n\n module_view = SchemaDiffRegistry.get_node_view(\n module)\n\n # Get sub module data for source tables\n if module_view.blueprint.server_type is None or \\\n src_server_type in module_view.blueprint.server_type:\n for key, val in source_tables.items():\n source = module_view.fetch_objects_to_compare(\n sid=src_sid,\n did=src_did,\n scid=src_scid,\n tid=val['oid'],\n oid=None,\n ignore_keys=True\n )\n source_tables[key][module] = source\n\n # Get sub module data for target tables\n if module_view.blueprint.server_type is None or \\\n tar_server_type in module_view.blueprint.server_type:\n for key, val in target_tables.items():\n target = module_view.fetch_objects_to_compare(\n sid=tar_sid,\n did=tar_did,\n scid=tar_scid,\n tid=val['oid'],\n oid=None,\n ignore_keys=True\n )\n target_tables[key][module] = target\n\n return compare_dictionaries(source_tables, target_tables,\n self.node_type,\n self.blueprint.COLLECTION_LABEL,\n self.keys_to_ignore)\n\n @staticmethod\n def get_server_type(src_id, tar_id):\n \"\"\"Get server types of source and target servers.\"\"\"\n driver = get_driver(PG_DEFAULT_DRIVER)\n src_manager = driver.connection_manager(src_id)\n tar_manager = driver.connection_manager(tar_id)\n\n return src_manager.server_type, tar_manager.server_type\n\n def ddl_compare(self, **kwargs):\n \"\"\"\n This function will compare properties of 2 tables and\n return the source DDL, target DDL and Difference of them.\n \"\"\"\n\n src_sid = kwargs.get('source_sid')\n src_did = kwargs.get('source_did')\n src_scid = kwargs.get('source_scid')\n src_oid = kwargs.get('source_oid')\n tar_sid = kwargs.get('target_sid')\n tar_did = kwargs.get('target_did')\n tar_scid = kwargs.get('target_scid')\n tar_oid = kwargs.get('target_oid')\n comp_status = kwargs.get('comp_status')\n generate_script = False\n\n if 'generate_script' in kwargs and kwargs['generate_script']:\n generate_script = True\n\n source = ''\n target = ''\n diff = ''\n ignore_sub_modules = ['column', 'constraints']\n\n src_server_type, tar_server_type = self.get_server_type(src_sid,\n tar_sid)\n\n status, target_schema = self.get_schema(tar_sid,\n tar_did,\n tar_scid\n )\n\n if not status:\n return internal_server_error(errormsg=target_schema)\n\n if comp_status == SchemaDiffModel.COMPARISON_STATUS['source_only']:\n if not generate_script:\n source = self.get_sql_from_table_diff(sid=src_sid,\n did=src_did,\n scid=src_scid,\n tid=src_oid,\n json_resp=False)\n diff = self.get_sql_from_table_diff(sid=src_sid, did=src_did,\n scid=src_scid, tid=src_oid,\n diff_schema=target_schema,\n json_resp=False)\n\n elif comp_status == SchemaDiffModel.COMPARISON_STATUS['target_only']:\n if not generate_script:\n target = self.get_sql_from_table_diff(sid=tar_sid,\n did=tar_did,\n scid=tar_scid,\n tid=tar_oid,\n json_resp=False)\n\n diff = self.get_drop_sql(sid=tar_sid, did=tar_did,\n scid=tar_scid, tid=tar_oid)\n\n elif comp_status == SchemaDiffModel.COMPARISON_STATUS['different']:\n source = self.fetch_tables(\n sid=src_sid, did=src_did,\n scid=src_scid, tid=src_oid,\n keys_to_remove=self.keys_to_remove_ddl_comp\n )\n target = self.fetch_tables(\n sid=tar_sid, did=tar_did,\n scid=tar_scid, tid=tar_oid,\n keys_to_remove=self.keys_to_remove_ddl_comp\n )\n\n if self.manager.version < 100000:\n ignore_sub_modules.append('partition')\n\n if self.manager.version < 120000:\n ignore_sub_modules.append('compound_trigger')\n\n # In case of error return None\n if not (source or target):\n return None\n\n diff_dict = directory_diff(\n source, target, ignore_keys=self.keys_to_ignore_ddl_comp,\n difference={}\n )\n\n # Column comparison\n col_diff = self.table_col_ddl_comp(source, target)\n diff_dict.update(col_diff)\n\n # Constraint comparison\n pk_diff = self.constraint_ddl_comp(source, target, diff_dict)\n diff_dict.update(pk_diff)\n\n diff_dict.update(self.parce_acl(source, target))\n\n if not generate_script:\n source = self.get_sql_from_table_diff(sid=src_sid,\n did=src_did,\n scid=src_scid,\n tid=src_oid,\n json_resp=False)\n target = self.get_sql_from_table_diff(sid=tar_sid,\n did=tar_did,\n scid=tar_scid,\n tid=tar_oid,\n json_resp=False)\n diff = self.get_sql_from_table_diff(sid=tar_sid, did=tar_did,\n scid=tar_scid, tid=tar_oid,\n diff_data=diff_dict,\n json_resp=False)\n\n for module in self.blueprint.submodules:\n if module.NODE_TYPE not in ignore_sub_modules:\n module_view = SchemaDiffRegistry.get_node_view(\n module.NODE_TYPE)\n\n if module_view.blueprint.server_type and (\n src_server_type not in\n module_view.blueprint.server_type and\n tar_server_type not in\n module_view.blueprint.server_type\n ):\n continue\n\n if module_view.blueprint.server_type and (\n (src_server_type in\n module_view.blueprint.server_type and\n tar_server_type not in\n module_view.blueprint.server_type) or (\n src_server_type not in\n module_view.blueprint.server_type and\n tar_server_type in\n module_view.blueprint.server_type)\n ):\n continue\n\n result = module_view.compare(\n source_sid=src_sid, source_did=src_did,\n source_scid=src_scid, source_tid=src_oid,\n target_sid=tar_sid, target_did=tar_did,\n target_scid=tar_scid, target_tid=tar_oid\n )\n if result and module.NODE_TYPE != 'partition':\n child_diff = ''\n for res in result:\n if res['status'] == \\\n SchemaDiffModel.COMPARISON_STATUS[\n 'different']:\n source_oid = res['source_oid']\n target_oid = res['target_oid']\n else:\n source_oid = res['oid']\n target_oid = res['oid']\n\n if res['status'] != \\\n SchemaDiffModel.COMPARISON_STATUS[\n 'identical']:\n child_diff = module_view.ddl_compare(\n source_sid=src_sid, source_did=src_did,\n source_scid=src_scid,\n source_oid=source_oid,\n source_tid=src_oid, target_sid=tar_sid,\n target_did=tar_did, target_scid=tar_scid,\n target_tid=tar_oid, target_oid=target_oid,\n comp_status=res['status']\n\n )\n if child_diff:\n diff += '\\n' + child_diff\n elif result:\n # For partition module\n identical = False\n source_only = False\n target_only = False\n different = False\n for res in result:\n if res['status'] == \\\n SchemaDiffModel.COMPARISON_STATUS[\n 'identical']:\n identical = True\n elif res['status'] == \\\n SchemaDiffModel.COMPARISON_STATUS[\n 'source_only']:\n source_only = True\n elif res['status'] == \\\n SchemaDiffModel.COMPARISON_STATUS[\n 'target_only']:\n target_only = True\n else:\n different = True\n\n if identical:\n pass\n elif (source_only or target_only) and not different:\n for res in result:\n source_oid = res['oid']\n target_oid = res['oid']\n\n child_diff = module_view.ddl_compare(\n source_sid=src_sid, source_did=src_did,\n source_scid=src_scid,\n source_oid=source_oid,\n source_tid=src_oid, target_sid=tar_sid,\n target_did=tar_did, target_scid=tar_scid,\n target_tid=tar_oid, target_oid=target_oid,\n comp_status=res['status']\n\n )\n if child_diff:\n diff += child_diff\n else:\n diff = self.get_sql_from_table_diff(\n sid=src_sid,\n did=src_did,\n scid=src_scid,\n tid=src_oid,\n diff_schema=target_schema,\n json_resp=False,\n schema_diff_table=True\n )\n else:\n source = self.get_sql_from_table_diff(sid=src_sid, did=src_did,\n scid=src_scid, tid=src_oid,\n json_resp=False)\n target = self.get_sql_from_table_diff(sid=tar_sid, did=tar_did,\n scid=tar_scid, tid=tar_oid,\n json_resp=False)\n\n return {'source_ddl': source,\n 'target_ddl': target,\n 'diff_ddl': diff\n }\n\n @staticmethod\n def table_col_ddl_comp(source, target):\n \"\"\"\n Table Column comparison\n :param source: Source columns\n :param target: Target columns\n :return: Difference of the columns\n \"\"\"\n source_cols = source['columns']\n target_cols = copy.deepcopy(target['columns'])\n added = []\n updated = []\n different = {'columns': {}}\n\n for source in source_cols:\n if 'name' in source:\n if type(target_cols) is list and len(\n target_cols) > 0:\n tmp = None\n for item in target_cols:\n if item['name'] == source['name']:\n tmp = copy.deepcopy(item)\n if tmp and source != tmp:\n tmp_updated = copy.deepcopy(source)\n # Preserve the column number\n tmp_updated['attnum'] = tmp['attnum']\n if item['typname'] not in tmp_updated['edit_types']:\n tmp_updated['col_type_conversion'] = False\n updated.append(tmp_updated)\n target_cols.remove(tmp)\n elif tmp and source == tmp:\n target_cols.remove(tmp)\n elif tmp is None:\n added.append(source)\n else:\n added.append(source)\n different['columns']['added'] = added\n different['columns']['changed'] = updated\n\n if target_cols and len(target_cols) > 0:\n different['columns']['deleted'] = target_cols\n\n return different\n\n @staticmethod\n def constraint_ddl_comp(source_table, target_table, diff_dict):\n \"\"\"\n Table Constraint DDL comparison\n :param source: Source Table\n :param target: Target Table\n :return: Difference of constraints\n \"\"\"\n different = {}\n non_editable_keys = {}\n columns_to_be_dropped = []\n\n non_editable_keys = {'primary_key': ['col_count',\n 'condeferrable',\n 'condeffered',\n 'columns'],\n 'unique_constraint': ['col_count',\n 'condeferrable',\n 'condeffered',\n 'columns'],\n 'check_constraint': ['consrc'],\n 'exclude_constraint': ['amname',\n 'indconstraint',\n 'columns'],\n 'foreign_key': []\n }\n\n for constraint in ['primary_key', 'unique_constraint',\n 'check_constraint',\n 'exclude_constraint', 'foreign_key']:\n source_cols = source_table[constraint] if \\\n constraint in source_table else []\n target_cols = copy.deepcopy(target_table[constraint]) if\\\n constraint in target_table else []\n added = []\n updated = []\n deleted = []\n\n different[constraint] = {}\n for source in source_cols:\n if 'name' in source:\n if type(target_cols) is list and len(\n target_cols) > 0:\n tmp_src = copy.deepcopy(source)\n tmp_src.pop('oid')\n tmp_tar = None\n tmp = None\n for item in target_cols:\n if item['name'] == source['name']:\n tmp_tar = copy.deepcopy(item)\n tmp = copy.deepcopy(item)\n tmp_tar.pop('oid')\n if tmp_tar and tmp_src != tmp_tar:\n tmp_updated = copy.deepcopy(source)\n for key in non_editable_keys[constraint]:\n if key in tmp_updated and \\\n tmp_updated[key] != tmp_tar[key]:\n added.append(source)\n deleted.append(tmp_updated)\n tmp_updated = None\n break\n if tmp_updated:\n tmp_updated['oid'] = tmp['oid']\n updated.append(tmp_updated)\n target_cols.remove(tmp)\n elif tmp_tar and tmp_src == tmp_tar:\n target_cols.remove(tmp)\n elif tmp_tar is None:\n added.append(source)\n else:\n added.append(source)\n different[constraint]['added'] = added\n different[constraint]['changed'] = updated\n different[constraint]['deleted'] = deleted\n\n if target_cols and len(target_cols) > 0:\n different[constraint]['deleted'] = target_cols\n\n return different\n\n def remove_keys_for_comparision(self, data, keys=None):\n \"\"\"\n This function is used to remove specific keys from data\n \"\"\"\n\n keys_to_remove = keys if keys else self.keys_to_remove\n\n for p_key, p_val in keys_to_remove.items():\n if p_key in data and data[p_key] is not None \\\n and len(data[p_key]) > 0:\n for item in data[p_key]:\n # Remove keys that should not be the part of comparision.\n for key in p_val:\n if key in item:\n item.pop(key)\n","sub_path":"pgadmin/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/schema_diff_utils.py","file_name":"schema_diff_utils.py","file_ext":"py","file_size_in_byte":22335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"35754955","text":"# -*- encoding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2009 Tiny SPRL (). All Rights Reserved\n# $Id$\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nimport time\nimport pooler\nimport datetime\nfrom report import report_sxw\nfrom types import NoneType\n\n__sql_registration_quality__ = '''\nSELECT leg, name, count(a), count(k), count(fp), count(n)\nFROM (\nSELECT E.otherid as leg, E.name as name, A.name as a, CAST(Null as timestamp)\n as k, CAST(Null as timestamp) as fp, CAST(Null as timestamp) as n\nFROM\n\thr_employee as E\n\tleft outer join\n\thr_attendance as A\n\ton E.id = A.employee_id\nwhere A.method='automatic'\n and ('%(dstart)s'::date,'%(dend)s'::date) overlaps (A.name,A.name)\nunion\nSELECT E.otherid, E.name, Null, A.name, Null, Null\nFROM\n\thr_employee as E\n\tleft outer join\n\thr_attendance as A\n\ton E.id = A.employee_id\nwhere A.method='keyboard'\n and ('%(dstart)s'::date,'%(dend)s'::date) overlaps (A.name,A.name)\nunion\nSELECT E.otherid, E.name, Null, Null, A.name, Null\nFROM\n\thr_employee as E\n\tleft outer join\n\thr_attendance as A\n\ton E.id = A.employee_id\nwhere A.method='fingerprint'\n and ('%(dstart)s'::date,'%(dend)s'::date) overlaps (A.name,A.name)\nunion\nSELECT E.otherid, E.name, Null, Null, Null, A.name\nFROM\n\thr_employee as E\n\tleft outer join\n\thr_attendance as A\n\ton E.id = A.employee_id\nwhere A.method is Null\n and ('%(dstart)s'::date,'%(dend)s'::date) overlaps (A.name,A.name)\n) AS T\nGROUP BY leg,name\n'''\n\nclass registration_quality(report_sxw.rml_parse):\n def __init__(self, cr, uid, name, context):\n super(registration_quality, self).__init__(cr, uid, name, context=context)\n self.localcontext.update({\n 'lines':self._lines,\n 'totals':self._totals,\n })\n\n def _lines(self):\n date_from = self.datas['form']['date_from']\n date_to = self.datas['form']['date_to']\n\n self.cr.execute(__sql_registration_quality__ % {'dstart': date_from,\n 'dend': date_to})\n lines = self.cr.fetchall()\n\n self.t_auto = 0\n self.t_keyb = 0\n self.t_fgpr = 0\n self.t_none = 0\n\n res = []\n for id, employee, c_auto, c_keyb, c_fgpr, c_none in lines:\n r = {\n 'id': id,\n 'name': employee,\n 'c_auto': c_auto,\n 'c_keyb': c_keyb,\n 'c_fgpr': c_fgpr,\n 'c_none': c_none,\n 'efectivity': \"%.3f\" % (float(c_keyb + c_fgpr) / float(c_auto +\n c_keyb +\n c_fgpr +\n c_none)\n * 100.),\n }\n res.append(r)\n self.t_auto += c_auto\n self.t_keyb += c_keyb\n self.t_fgpr += c_fgpr\n self.t_none += c_none\n\n return res\n\n def _totals(self):\n tt = float(self.t_auto+self.t_keyb+self.t_fgpr+self.t_none) * 100\n if tt == .0:\n return (self.t_auto, self.t_keyb, self.t_fgpr, self.t_none, 'inv')\n else:\n return (self.t_auto, self.t_keyb, self.t_fgpr, self.t_none,\n \"%.3f\" % (float(self.t_keyb+self.t_fgpr) / tt))\n\nreport_sxw.report_sxw('report.clock_reader.registration_quality_report',\n 'hr.attendance',\n 'addons/clock_reader/report/registration_quality.rml',\n parser=registration_quality)\n\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n\n\n","sub_path":"extra-addons/clock_reader/report/registration_quality.py","file_name":"registration_quality.py","file_ext":"py","file_size_in_byte":4498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"195673826","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.patches import Ellipse\nfrom matplotlib.path import Path\nimport matplotlib.patches as patches\n\n\n\nclass location:\n x = 0\n y = 0\n z = 0\n def __init__(self, x, y, z):\n self.x = x\n self.y = y\n self.z = z\n\nclass tag:\n name =''\n id = 0\n last_pos = location(0, 0, 0)\n\n def __init__(self, name, id):\n self.name = name\n self.id = id\n \n\n\nclass anchor:\n name = ''\n id = 0\n x = 0\n y = 0\n z = 0\n sync_master = False\n sync_level = 0\n def __init__(self, name, id, x, y, z):\n self.name = name\n self.id = id\n self.x = x\n self.y = y\n self.z = z\n\nclass anchors:\n __anchor_list = []\n\n def __init__(self):\n self.name = ''\n\n def add_anchor(self, new_anchor):\n if len(self.__anchor_list) == 0:\n self.__anchor_list.append(new_anchor)\n else:\n if self.__anchor_list.count(new_anchor) == 0:\n self.__anchor_list.append(new_anchor) \n def get_anchor_by_id (self, anchor_id):\n for an in self.__anchor_list:\n if an.id == anchor_id:\n return an\n def get_anchor_by_index(self, index):\n if index >= len(self.__anchor_list):\n return None\n try:\n return self.__anchor_list[index]\n except ValueError:\n return None \n def get_anchor_by_name(self, anchor_name):\n for i in self.__anchor_list:\n if i.name == anchor_name:\n return i\n return None\n def len(self):\n return len(self.__anchor_list) \n\ndef anchor_verts(x, y):\n v = [\n (x + 0, y - 1), # left, bottom\n (x - 1, y + 1), # left, top\n (x + 1, y + 1), # right, top\n (x + 0, y - 1), # ignored\n ]\n return v\n\n \nanchor_list = anchors()\n\n# Тестовый набор якорей\nan1 = anchor('AN1', 2149056513, x = 0, y = 0, z = 3)\nan2 = anchor('AN2', 2149056514, x = 0, y = 20, z = 3)\nan3 = anchor('AN3', 2149056515, x = 25, y = 20, z = 3)\nan4 = anchor('AN4', 2149056516, x = 25, y = 0, z = 3)\nanchor_list.add_anchor(an1)\nanchor_list.add_anchor(an2)\nanchor_list.add_anchor(an3)\nanchor_list.add_anchor(an4)\n\n\ndelta = 45.0 # degrees\n\nangles = np.arange(0, 360 + delta, delta)\nells = [Ellipse((1, 1), 4, 2, a) for a in angles]\n\nfig, ax = plt.subplots()\n\nfor e in ells:\n e.set_clip_box(ax.bbox)\n e.set_alpha(0.1)\n ax.add_artist(e)\n\n\n\n# Отображение якорей\ncodes = [\n Path.MOVETO,\n Path.LINETO,\n Path.LINETO,\n Path.CLOSEPOLY,\n]\n\nfor idx in range(0, anchor_list.len()):\n v = anchor_verts(anchor_list.get_anchor_by_index(idx).x, anchor_list.get_anchor_by_index(idx).y)\n path = Path(v, codes)\n patch = patches.PathPatch(path, facecolor='orange', lw=2)\n ax.add_patch(patch)\n\n# Настройки поля\nax.set_aspect('equal')\nplt.xlim(-5, 30)\nplt.ylim(-5, 25)\nplt.grid(True)\nplt.show(False)\nplt.draw()\nbackground = fig.canvas.copy_from_bbox(ax.bbox)\n\n#point = Ellipse((10, 10), 1, 1, 0)\n#ax.draw_artist(point)\nplt.pause(0.1)\n\ni = 0\ngen = np.random.RandomState(0)\nx, y = gen.rand(2, 2000) * 30\n \nwhile i < 2000: \n \n points = ax.plot(x[i], y[i], 'o')[0]\n i += 1\n\n # restore background\n fig.canvas.restore_region(background)\n\n # redraw just the points\n ax.draw_artist(points)\n\n # fill in the axes rectangle\n fig.canvas.blit(ax.bbox)\n","sub_path":"location_server/location_server/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"639410804","text":"import math\r\n\r\ndef f1(x):\r\n return 1/(x+4)\r\n\r\ndef midpoint(f,a,b):\r\n return (b-a)*f((a+b)/2)\r\n\r\ndef trapezoidal(f,a,b):\r\n return ((b-a)/2)*(f(a)+f(b))\r\n\r\ndef simpsons(f,a,b):\r\n return (1/3)*trapezoidal(f,a,b) + (2/3)*midpoint(f,a,b)\r\n\r\ndef err_comp_trap(f,a,b,err):\r\n d2fmax = 1/32\r\n val = (1/err)*(b-a)*(b-a)*(b-a)*(1/12)*d2fmax\r\n n = math.ceil(math.sqrt(val))\r\n print(\"Constraints :\",\"h <=\",(b-a)/math.sqrt(val),\"and n >=\",n)\r\n return n \r\n\r\ndef err_comp_simp(f,a,b,err):\r\n d4fmax = 24/(4**5)\r\n val = (1/err)*pow(b-a,5)*(1/180)*d4fmax\r\n n = math.ceil(math.sqrt(math.sqrt(val)))\r\n if n%2==0:\r\n print(\"Constraints :\",\"h <=\",(b-a)/math.sqrt(math.sqrt(val)),\"and n >=\",n)\r\n return n\r\n else:\r\n print(\"Constraints :\",\"h <=\",(b-a)/math.sqrt(math.sqrt(val)),\"and n >=\",n+1)\r\n return n+1\r\n \r\n \r\ndef err_comp_mid(f,a,b,err):\r\n d2fmax = 1/32\r\n val = (1/err)*(b-a)*(b-a)*(b-a)*(1/6)*d2fmax\r\n n = math.ceil(math.sqrt(val))\r\n print(\"Constraints :\",\"h <=\",(b-a)/math.sqrt(val),\"and n >=\",n)\r\n return n\r\n \r\n\r\n\r\ndef comp_trapezoidal(f,a,b,n):\r\n h = (b-a)/n\r\n summ = 0\r\n for j in range(0,n+1):\r\n xj = a+j*h\r\n if j==0 or j==n:\r\n summ+=h*f(xj)/2\r\n else:\r\n summ+=h*f(xj)\r\n return summ\r\n\r\ndef comp_simpsons(f,a,b,n):\r\n h = (b-a)/n\r\n ans = f(a)\r\n for j in range(2,math.floor(n/2) + 1):\r\n ans+=2*f(a+(2*j-2)*h)\r\n \r\n for j in range(1,math.floor(n/2) + 1):\r\n ans+=4*f(a+(2*j-1)*h)\r\n \r\n ans+=f(b)\r\n return (h/3)*ans\r\n\r\ndef comp_midpoint(f,a,b,n):\r\n h = (b-a)/n\r\n ans = 0\r\n summ = 0\r\n for j in range(0,n):\r\n xj = a+j*h\r\n xj_nex = a+(j+1)*h\r\n pt = (xj+xj_nex)/2\r\n summ+=f(pt)\r\n return h*summ\r\n \r\n\r\nactual_val = 0.405465108108164\r\n\r\nprint(\"Part (a)\")\r\nreq_n = err_comp_trap(f1,0,2,pow(10,-5))\r\nreq_h = (2-0)/req_n\r\n\r\n\r\nprint(\"Required value of n:\",req_n)\r\nprint(\"Correpsonding value of h:\",req_h)\r\n\r\nans = comp_trapezoidal(f1,0,2,req_n)\r\nprint(\"The estimate using compsoite trapezoidal method: \",ans)\r\nprint(\"The diffirence between actual and caluclated value:\",abs(ans-actual_val))\r\n\r\nprint(\"\")\r\nprint(\"Part (b)\")\r\nreq_n = err_comp_simp(f1,0,2,pow(10,-5))\r\nreq_h = (2-0)/req_n\r\n\r\n\r\nprint(\"Required value of n:\",req_n)\r\nprint(\"Correpsonding value of h:\",req_h)\r\n\r\nans1 = comp_simpsons(f1,0,2,req_n)\r\nprint(\"The estimate using compsoite simpsons method: \",ans1)\r\nprint(\"The diffirence between actual and caluclated value:\",abs(ans1-actual_val))\r\n\r\nprint(\"\")\r\nprint(\"Part (c)\")\r\nreq_n = err_comp_mid(f1,0,2,pow(10,-5))\r\nreq_h = (2-0)/req_n\r\n\r\n\r\nprint(\"Required value of n:\",req_n)\r\nprint(\"Correpsonding value of h:\",req_h)\r\n\r\nans1 = comp_midpoint(f1,0,2,req_n)\r\nprint(\"The estimate using compsoite midpoint method: \",ans1)\r\nprint(\"The diffirence between actual and caluclated value:\",abs(ans1-actual_val))","sub_path":"Lab 04/q5.py","file_name":"q5.py","file_ext":"py","file_size_in_byte":2915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"529268051","text":"from flask import Flask, request, abort\n\nfrom linebot import (\n LineBotApi, WebhookHandler\n)\nfrom linebot.exceptions import (\n InvalidSignatureError\n)\nfrom linebot.models import (\n MessageEvent, TextMessage,\n TextSendMessage,\n TemplateSendMessage,\n ButtonsTemplate,\n MessageTemplateAction,\n ImageCarouselTemplate,\n ImageCarouselColumn,\n URITemplateAction \n)\n\napp = Flask(__name__)\n\nline_bot_api = LineBotApi('1dTO7g1uJGmYytCGvr0XSDGrweTNI1AnIyfu/1rX9ms1qHi1P+7Uq9zmeBFMCzIVAdmrEc3nKYU5nbrP1WZbtbB3H88oNRTToOntthD5uRaEIWLHvSc+RPY5pUOahbA4iEtSKorPJezO7PATguX+oAdB04t89/1O/w1cDnyilFU=')\nhandler = WebhookHandler('99fceeadf48dbe1ab2cf4325896cee4a')\n\n\n@app.route(\"/callback\", methods=['POST'])\ndef callback():\n # get X-Line-Signature header value\n signature = request.headers['X-Line-Signature']\n\n # get request body as text\n body = request.get_data(as_text=True)\n app.logger.info(\"Request body: \" + body)\n\n # handle webhook body\n try:\n handler.handle(body, signature)\n except InvalidSignatureError:\n print(\"Invalid signature. Please check your channel access token/channel secret.\")\n abort(400)\n\n return 'OK'\n\n\n@handler.add(MessageEvent, message=TextMessage)\ndef handle_message(event):\n msg = event.message.text\n\n #r = '想要多了解請打\"關於瑋彥\"'\n\n if msg == '你好' :\n r = '你好'\n elif msg == '為什麼要瑋彥':\n r = '太可愛' \n elif msg == \"關於瑋彥\":\n line_bot_api.reply_message( # 回復傳入的訊息文字\n event.reply_token,\n TemplateSendMessage(\n alt_text='關於瑋彥',\n template=ButtonsTemplate(\n thumbnail_image_url=\"https://lh3.googleusercontent.com/BMF7I7RSG8IapEoOiF_3mDwk30pYQsnWLmhP51ww0rhEZkiTJ6CBHrMxMUjQFoIREbgmi_krIJdbPS-gSzGMA8C2e3muiy0cSzJ33pFAm_6iKuKA9x1A9ooFuVB9ZRNX5dVCUE2m4Q=w600\",\n title='瑋彥的作品集',\n text='請選擇作品',\n actions=[\n MessageTemplateAction(\n label=\"IG濾鏡\",\n text=\"我想看IG濾鏡\"\n ),\n URITemplateAction(\n label=\"影片剪輯作品\",\n uri=\"https://www.youtube.com/channel/UCH5tUrNXpr1x4pHpQGhfQXA?view_as=subscriber\"\n ),\n URITemplateAction(\n label=\"程式碼網頁設計\",\n uri=\"https://eric911115.github.io/school.html\"\n ) \n ]\n )\n )\n ) \n elif msg == \"我想看IG濾鏡\":\n line_bot_api.reply_message( # 回復傳入的訊息文字\n event.reply_token,\n TemplateSendMessage(\n alt_text='IG濾鏡',\n template=ImageCarouselTemplate(\n columns=[\n ImageCarouselColumn(\n image_url=\"https://upload.cc/i1/2020/10/19/EjDUGz.jpg\",\n action=URITemplateAction(\n label=\"學測倒數\",\n uri=\"https://www.instagram.com/ar/1507952719375055/\"\n )\n ),\n ImageCarouselColumn(\n image_url=\"https://upload.cc/i1/2020/10/19/AeUiZu.jpg\",\n action=URITemplateAction(\n label=\"統測倒數\",\n uri=\"https://www.instagram.com/ar/1233861126969567/\"\n )\n ),\n ImageCarouselColumn(\n image_url=\"https://upload.cc/i1/2020/10/19/AmR8rf.jpg\",\n action=URITemplateAction(\n label=\"北極沒有企鵝\",\n uri=\"https://www.instagram.com/ar/651213445816757/\"\n )\n ),\n ImageCarouselColumn(\n image_url=\"https://upload.cc/i1/2020/10/19/lBpEgV.jpg\",\n action=URITemplateAction(\n label=\"豬如此類\",\n uri=\"https://www.instagram.com/ar/603244753687030/\"\n )\n ),\n ImageCarouselColumn(\n image_url=\"https://upload.cc/i1/2020/10/19/VneW4d.jpg\",\n action=URITemplateAction(\n label=\"學測戰士\",\n uri=\"https://www.instagram.com/ar/690111801715364/\"\n )\n )\n ]\n )\n )\n ) \n line_bot_api.reply_message(\n event.reply_token,\n TextSendMessage(r))\n \n\n\nif __name__ == \"__main__\":\n app.run()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"479302357","text":"import requests\nfrom lxml import html\nimport re\nimport json\nfrom queue import Queue\nimport threading\nimport time\nimport jieba\nfrom wordcloud import WordCloud\n\nHEADER = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36'\n}\n\n\nclass Procuder(threading.Thread):\n def __init__(self, page_queue, img_queue, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.page_queue = page_queue\n self.img_queue = img_queue\n\n def run(self):\n while True:\n if self.page_queue.empty():\n break\n url = self.page_queue.get()\n self.get_detail_urls(url)\n # 休眠0.5秒防止太快\n time.sleep(0.5)\n print(self.img_queue.qsize())\n\n def get_detail_urls(self, url):\n reponse = requests.get(url, HEADER, stream=True)\n data = reponse.content.decode('gbk')\n htmls = html.etree.HTML(data)\n # 获取每一页中每一个职位信息url\n detail_urls = htmls.xpath('//body//div[@class=\"dw_wp\"]//div[@class=\"dw_table\"]/div[@class=\"el\"]/p/span//@href')\n self.parse_datail_page(detail_urls)\n\n def parse_datail_page(self, detail_urls):\n for urls in detail_urls:\n # 爬取职位信息数据\n reponse = requests.get(urls, HEADER, stream=True)\n data = reponse.content.decode('GBK', errors='ignore')\n htmls = html.etree.HTML(data)\n content = htmls.xpath('//div[@class=\"bmsg job_msg inbox\"]//text()')\n # ensure_ascii=False使汉字不进行转译\n content = json.dumps(content, ensure_ascii=False)\n # 去除不必要的字符\n content = re.sub(\"^\\\\[|\\\\]$\", \"\", content)\n content4 = content.replace('\\\\n ', '')\n content5 = content4.replace('\\\\r', '')\n content = content5.replace('微信分享', '')\n content = re.sub('\"| |,', \"\", content)\n self.img_queue.put(content)\n # 爬取完一个就要关闭\n reponse.close()\n\n\nclass Consumer(threading.Thread):\n def __init__(self, page_queue, img_queue, gLock, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.page_queue = page_queue\n self.img_queue = img_queue\n self.gLock = gLock\n\n def run(self):\n\n while True:\n # 这里休眠5秒,防止因为网络问题而出错\n if self.img_queue.empty() and self.page_queue.empty():\n time.sleep(5)\n if self.img_queue.empty() and self.page_queue.empty():\n break\n ddd = self.img_queue.get()\n self.gLock.acquire()\n # 在修改文件之前要上锁\n self.export_excel(ddd)\n self.gLock.release()\n\n def export_excel(self, next):\n # 将职位信息保存到txt文件\n with open(\"D:\\\\表格\\\\职位.txt\", \"a\", encoding=\"utf-8\")as f:\n f.write(next)\n\n\ndef main():\n gLock = threading.Lock()\n page_queue = Queue(400)\n img_queue = Queue(20000)\n # 需要爬取职位信息的城市\n i = ['200200', '020000']\n for a in i:\n # 用于找出基本信息\n url = \"https://search.51job.com/list/{},000000,0000,00,9,99,python,2,1.html?\".format(a)\n reponse = requests.get(url, HEADER)\n data = reponse.content.decode('gbk')\n # 获取职位数量\n x = re.findall(r'
    .*?
    .*?共(.*?)条职位', data, re.S)[0]\n # 获取页数\n s = \\\n re.findall(r'
    .*?
    .*?.*?共(.*?)页,到第', data,\n re.S)[\n 0]\n # 将页数int成为数字类型\n gg = int(s)\n # 遍历每一页放到队列中\n for aa in range(1, gg + 1):\n url = 'https://search.51job.com/list/{},000000,0000,00,9,99,golang,2,{}.html?'.format(a, aa)\n page_queue.put(url)\n # 建立多个线程\n for xx in range(4):\n t = Procuder(page_queue, img_queue)\n t.start()\n for xx in range(4):\n t = Consumer(page_queue, img_queue, gLock)\n t.start()\n\n\ndef run():\n # 方法一:自定义词典\n # file_userdict = 'D:\\\\多线程爬虫\\\\文本.txt'\n # jieba.load_userdict(file_userdict)\n # 读取职位信息存储文件\n f = open('D:\\\\表格\\\\职位.txt', encoding='utf-8')\n txt = f.read()\n f.close()\n fuhao = ['Flask', 'Django', 'Tornado', '高并发', '异步', '多线程', '多进程', '爬虫', '数据结构', '算法', 'ACM', '本科', 'Redis', 'Mysq',\n 'Nosql', 'MongoDB', 'Linux', 'Angular', '框架', '前端', 'Storm', 'HBase', 'hadoop', 'Hive', 'Robot', 'Vue.js',\n 'bug', 'Al', 'Redis', 'TDD', 'Odoo', '爬', 'html']\n # 方法二:使用add_word增加向jieba库增加新的单词\n for a in fuhao:\n jieba.add_word(a)\n # 分词\n words = jieba.lcut(txt)\n counts = {}\n # 排除除关键字之外的其他字符\n for word in words:\n if word in fuhao:\n # 统计关键字个数\n counts[word] = counts.get(word, 0) + 1\n else:\n continue\n # 将字典转为列表\n items = list(counts.items())\n # 按key值排序\n items.sort(key=lambda x: x[1], reverse=True)\n co = {}\n sm = len(items)\n print(sm)\n # 输出关键字排名\n for i in range(sm):\n word, count = items[i]\n print('{0:<10}{1:>5}'.format(word, count))\n co[word] = count\n # 将排名写为词云\n words = WordCloud(font_path=\"D:\\\\pythonIDLE\\词云\\\\msyh.ttf\", width=600, height=600, max_words=sm,\n background_color='white').generate_from_frequencies(co)\n # 保存词云图片\n words.to_file(\"D:\\\\图片\\\\python职位关键字.png\")\n\n\nif __name__ == '__main__':\n main()\n run()\n","sub_path":"51job_wordcloud.py","file_name":"51job_wordcloud.py","file_ext":"py","file_size_in_byte":5946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"353648078","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\npython 3\r\n\r\n-script is an automated etl pipeline to prepare data for Future of Online Learning Tableau Dashbaord.\r\n\r\n-script takes the most recent Excel file you downloaded and saved in the your Future of Online Learning folder. \r\n\r\n-script takes World Bank data which is formatted by year and places all years into one column.\r\n\r\n-script creates columns 8 columns to better organize the data prior to putting it in Tableau.\r\n\r\n-script saves to excel file as \"Revised\"\r\n\r\nCreated on Thu Aug 20 16:47:13 2020\r\n\r\n@author: Spencer-Jessica-E\r\n\"\"\"\r\nimport os\r\nimport glob\r\nimport os.path\r\nimport pandas as pd\r\nimport numpy as np\r\nimport json\r\n\r\ndata_cfg_fp = 'cfg/configg.json'\r\n\r\n\r\nclass World():\r\n def __init__(self, dest_db=None): \r\n # get phishing_cfg\r\n with open(data_cfg_fp) as json_file:\r\n data_cfg = json.load(json_file)\r\n \r\n self.cfg = data_cfg[\"World_Bank\"]\r\n \r\n def Get_latestfile(self, check_directory):\r\n list_of_files = glob.glob(check_directory)\r\n latest_file = max(list_of_files, key=os.path.getctime)\r\n# latest_file_crtime = time.ctime(os.path.getmtime(latest_file))\r\n return latest_file\r\n\r\n \r\n def Column_add(self, series_code = None, newColumnName = None):\r\n df = self.df2\r\n # add columns needed\r\n cxo_conditions = [\r\n (df[\"Series Code\"] == series_code)]\r\n cxo_conditions_values = [df[\"Values\"].tolist()]\r\n df[newColumnName] = np.select( cxo_conditions, cxo_conditions_values)\r\n return df\r\n \r\n \r\n def Clean_Country(self):\r\n df = self.df2\r\n # filtering based on country name \r\n df = df[df[\"Country Name\"].isin([\"Argentina\", \"Australia\",\"Brazil\",\r\n \"China\", \"France\", \"Germany\", \"India\", \"Indonesia\", \"Italy\", \r\n \"Japan\", \"Korea\",\"Mexico\", \"Netherlands\", \"Russian Federation\",\r\n \"Saudi Arabia\", \"Spain\", \"Switzerland\", \"Turkey\", \"United Kingdom\",\r\n \"United States\"])] \r\n return df \r\n \r\n def Execute(self): \r\n #get file\r\n self.latest_file = self.Get_latestfile(self.cfg[\"homedir\"] + self.cfg[\"filetype\"] )\r\n self.df = pd.read_excel(self.latest_file, sheet_name = self.cfg[\"sheet_name\"])\r\n self.df2 = pd.melt(self.df, id_vars =[\"Series Code\", \"Series Name\", \"Country Name\", \"Country Code\"], var_name = \"Year1\", value_name = \"Values\")\r\n # cleans data in year col\r\n self.df2[\"Year\"]=self.df2[\"Year1\"].str.extract(r'(\\d\\d\\d\\d)')\r\n #create 7 cols needed\r\n self.df2 = self.Column_add( \"IT.CEL.SETS.P2\", \"Mobile Cellular Subscriptions\")\r\n self.df2 = self.Column_add( \"IT.NET.USER.ZS\", \"Internet Usage Ratio\")\r\n self.df2 = self.Column_add( \"NY.GDP.MKTP.CD\", \"GDP\")\r\n self.df2 = self.Column_add( \"NY.GDP.MKTP.KD.ZG\", \"GDP Annual Growth\")\r\n self.df2 = self.Column_add( \"SE.SEC.PRIV.ZS\", \"Secondary Enrollment\")\r\n self.df2 = self.Column_add( \"EG.USE.ELEC.KH.PC\", \"Electrical Power Consumption\")\r\n self.df2 = self.Column_add( \"SP.POP.TOTL\",\"Population\" )\r\n \r\n #getting rid of Values col created during the melt\r\n self.df2.pop('Values') \r\n self.df2.pop('Year1') \r\n self.df2 = self.Clean_Country()\r\n #removes nan and resets index \r\n self.df2.dropna().reset_index(drop=True)\r\n #load df to excel\r\n #path to where i want to save modified file along with the modified file name \r\n file = self.cfg[\"homedir\"] + \"/\" + \"Revised.xlsx\"\r\n self.df2.to_excel(file, index = False)\r\n return self.df2\r\n\r\n\r\n#run script\r\n\r\na = World()\r\na.Execute()\r\n","sub_path":"clearning_world_bank_data.py","file_name":"clearning_world_bank_data.py","file_ext":"py","file_size_in_byte":3681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"429334196","text":"import numpy\n\n#oldlist = numpy.random.randint(0,10,8)\n\ndef insertion_sort(array):\n for i in range(1, len(array)):\n key = array[i]\n j = i - 1\n while j >= 0 and key < array[j]:\n array[j + 1] = array[j]\n j -= 1\n array[j+1] = key\n return array\n#print('Old list', oldlist)\n#newlist = oldlist.copy()\n#print('New list', insertion_sort(newlist))\n","sub_path":"Lab6/insert_sort.py","file_name":"insert_sort.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"53799248","text":"\"\"\"\n Simple non-ga server for the basicbot.\n\"\"\"\n \nimport json\nimport zmq\nimport argparse\nimport random\nimport threading\nimport subprocess\nimport os\nimport datetime\n\nrandom.seed(10)\n\nNum_evaluation_workers = 1\n\nGA_IP_ADDR = '127.0.0.1'\nGA_SEND_PORT = 5000\nGA_RECV_PORT = 5010\n\n# How many genomes to test sending\ntest_genome_num = 12\n\n \nclass senderThread(threading.Thread):\n\tdef __init__(self, threadID, socket, num_genomes=10):\n\t\tthreading.Thread.__init__(self)\n\t\tself.threadID = threadID\n\t\tself.socket = socket\n\t\tself.num_genomes = num_genomes\n\t \n\tdef run(self):\n\t\tprint(\"Gnome - center_spin_thresh, center_drive_thresh, center_stop_thresh, stopping_thresh\")\n\t\tprint(\"\\t\\t\\t\\tStarting Sender Thread:\"+str(self.threadID))\n\t\tself.send_data()\n\t\tprint(\"\\t\\t\\t\\tExiting Sender Thread:\"+str(self.threadID))\n \n\tdef send_data(self):\n\t\tind = {'id':0,'genome':{\n\t\t\t\t'physical':[\n\t\t\t\t{'sensor':'lidar', 'pos':[0,0,0.4], 'orient':[0,0,0]}\n\t\t\t\t],\n\t\t\t\t'behavioral':[\n\t\t\t\t{'test':0}\n\t\t\t\t]\n\t\t\t}, 'fitness':-1.0}\n\t\t\t\n\t\tind = {'id':0,'genome':{\n\t\t\t\t'physical':[\n\t\t\t\t{'sensor':'lidar', 'pos':[0,0,0.4], 'orient':[0,0,0]}\n\t\t\t\t],\n\t\t\t\t'behavioral':[\n\t\t\t\t{'max_turn_strength':169}, #int, [50-400]\n\t\t\t\t{'max_yaw_change_per_cb':36}, #int, [0-100]\n\t\t\t\t{'num_vision_cones':77}, #int, [1-101], must be odd\n\t\t\t\t{'sweep_weight_factor':0.104286100839},#float, [0-5]\n\t\t\t\t{'distance_weight_factor':0.411426067434}#float, [0-5]\n\t\t\t\t]\n\t\t\t}, 'fitness':-1.0}\n\t\tmsg = json.dumps(ind)\n\t\tsocket.send(msg)\n\t\t\n\t\tind = {'id':1,'genome':{\n\t\t\t\t'physical':[\n\t\t\t\t{'sensor':'lidar', 'pos':[0,0,0.4], 'orient':[0,0,0]}\n\t\t\t\t],\n\t\t\t\t'behavioral':[\n\t\t\t\t{'max_turn_strength':169}, #int, [50-400]\n\t\t\t\t{'max_yaw_change_per_cb':82}, #int, [0-100]\n\t\t\t\t{'num_vision_cones':35}, #int, [1-101], must be odd\n\t\t\t\t{'sweep_weight_factor':0.104286100839},#float, [0-5]\n\t\t\t\t{'distance_weight_factor':0.411426067434}#float, [0-5]\n\t\t\t\t]\n\t\t\t}, 'fitness':-1.0}\n\t\tmsg = json.dumps(ind)\n\t\tsocket.send(msg)\n\t\t\n\t\tind = {'id':2,'genome':{\n\t\t\t\t'physical':[\n\t\t\t\t{'sensor':'lidar', 'pos':[0,0,0.4], 'orient':[0,0,0]}\n\t\t\t\t],\n\t\t\t\t'behavioral':[\n\t\t\t\t{'max_turn_strength':224}, #int, [50-400]\n\t\t\t\t{'max_yaw_change_per_cb':91}, #int, [0-100]\n\t\t\t\t{'num_vision_cones':59}, #int, [1-101], must be odd\n\t\t\t\t{'sweep_weight_factor':0.104286100839},#float, [0-5]\n\t\t\t\t{'distance_weight_factor':0.411426067434}#float, [0-5]\n\t\t\t\t]\n\t\t\t}, 'fitness':-1.0}\n\t\tmsg = json.dumps(ind)\n\t\tsocket.send(msg)\n\t\t\n\t\tind = {'id':3,'genome':{\n\t\t\t\t'physical':[\n\t\t\t\t{'sensor':'lidar', 'pos':[0,0,0.4], 'orient':[0,0,0]}\n\t\t\t\t],\n\t\t\t\t'behavioral':[\n\t\t\t\t{'max_turn_strength':169}, #int, [50-400]\n\t\t\t\t{'max_yaw_change_per_cb':74}, #int, [0-100]\n\t\t\t\t{'num_vision_cones':61}, #int, [1-101], must be odd\n\t\t\t\t{'sweep_weight_factor':0.104286100839},#float, [0-5]\n\t\t\t\t{'distance_weight_factor':0.411426067434}#float, [0-5]\n\t\t\t\t]\n\t\t\t}, 'fitness':-1.0}\n\t\tmsg = json.dumps(ind)\n\t\tsocket.send(msg)\n\t\t\n\t\tind = {'id':4,'genome':{\n\t\t\t\t'physical':[\n\t\t\t\t{'sensor':'lidar', 'pos':[0,0,0.4], 'orient':[0,0,0]}\n\t\t\t\t],\n\t\t\t\t'behavioral':[\n\t\t\t\t{'max_turn_strength':180}, #int, [50-400]\n\t\t\t\t{'max_yaw_change_per_cb':84}, #int, [0-100]\n\t\t\t\t{'num_vision_cones':45}, #int, [1-101], must be odd\n\t\t\t\t{'sweep_weight_factor':2.2694656},#float, [0-5]\n\t\t\t\t{'distance_weight_factor':3.3145166}#float, [0-5]\n\t\t\t\t]\n\t\t\t}, 'fitness':-1.0}\n\t\tmsg = json.dumps(ind)\n\t\tsocket.send(msg)\n\t\n\t\tind = {'id':5,'genome':{\n\t\t\t\t'physical':[\n\t\t\t\t{'sensor':'lidar', 'pos':[0,0,0.4], 'orient':[0,0,0]}\n\t\t\t\t],\n\t\t\t\t'behavioral':[\n\t\t\t\t{'max_turn_strength':180}, #int, [50-400]\n\t\t\t\t{'max_yaw_change_per_cb':84}, #int, [0-100]\n\t\t\t\t{'num_vision_cones':45}, #int, [1-101], must be odd\n\t\t\t\t{'sweep_weight_factor':3.60522},#float, [0-5]\n\t\t\t\t{'distance_weight_factor':3.31451}#float, [0-5]\n\t\t\t\t]\n\t\t\t}, 'fitness':-1.0}\n\t\tmsg = json.dumps(ind)\n\t\tsocket.send(msg)\n\t\t\n\t\tind = {'id':0,'genome':{\n\t\t\t\t'physical':[\n\t\t\t\t{'sensor':'lidar', 'pos':[0,0,0.4], 'orient':[0,0,0]}\n\t\t\t\t],\n\t\t\t\t'behavioral':[\n\t\t\t\t{'max_turn_strength':169}, #int, [50-400]\n\t\t\t\t{'max_yaw_change_per_cb':36}, #int, [0-100]\n\t\t\t\t{'num_vision_cones':77}, #int, [1-101], must be odd\n\t\t\t\t{'sweep_weight_factor':0.104286100839},#float, [0-5]\n\t\t\t\t{'distance_weight_factor':0.411426067434}#float, [0-5]\n\t\t\t\t]\n\t\t\t}, 'fitness':-1.0}\n\t\tmsg = json.dumps(ind)\n\t\tsocket.send(msg)\n\t\t\n\t\tind = {'id':1,'genome':{\n\t\t\t\t'physical':[\n\t\t\t\t{'sensor':'lidar', 'pos':[0,0,0.4], 'orient':[0,0,0]}\n\t\t\t\t],\n\t\t\t\t'behavioral':[\n\t\t\t\t{'max_turn_strength':169}, #int, [50-400]\n\t\t\t\t{'max_yaw_change_per_cb':82}, #int, [0-100]\n\t\t\t\t{'num_vision_cones':35}, #int, [1-101], must be odd\n\t\t\t\t{'sweep_weight_factor':0.104286100839},#float, [0-5]\n\t\t\t\t{'distance_weight_factor':0.411426067434}#float, [0-5]\n\t\t\t\t]\n\t\t\t}, 'fitness':-1.0}\n\t\tmsg = json.dumps(ind)\n\t\tsocket.send(msg)\n\t\t\n\t\tind = {'id':2,'genome':{\n\t\t\t\t'physical':[\n\t\t\t\t{'sensor':'lidar', 'pos':[0,0,0.4], 'orient':[0,0,0]}\n\t\t\t\t],\n\t\t\t\t'behavioral':[\n\t\t\t\t{'max_turn_strength':224}, #int, [50-400]\n\t\t\t\t{'max_yaw_change_per_cb':91}, #int, [0-100]\n\t\t\t\t{'num_vision_cones':59}, #int, [1-101], must be odd\n\t\t\t\t{'sweep_weight_factor':0.104286100839},#float, [0-5]\n\t\t\t\t{'distance_weight_factor':0.411426067434}#float, [0-5]\n\t\t\t\t]\n\t\t\t}, 'fitness':-1.0}\n\t\tmsg = json.dumps(ind)\n\t\tsocket.send(msg)\n\t\t\n\t\tind = {'id':3,'genome':{\n\t\t\t\t'physical':[\n\t\t\t\t{'sensor':'lidar', 'pos':[0,0,0.4], 'orient':[0,0,0]}\n\t\t\t\t],\n\t\t\t\t'behavioral':[\n\t\t\t\t{'max_turn_strength':169}, #int, [50-400]\n\t\t\t\t{'max_yaw_change_per_cb':74}, #int, [0-100]\n\t\t\t\t{'num_vision_cones':61}, #int, [1-101], must be odd\n\t\t\t\t{'sweep_weight_factor':0.104286100839},#float, [0-5]\n\t\t\t\t{'distance_weight_factor':0.411426067434}#float, [0-5]\n\t\t\t\t]\n\t\t\t}, 'fitness':-1.0}\n\t\tmsg = json.dumps(ind)\n\t\tsocket.send(msg)\n\t\t\n\t\tind = {'id':4,'genome':{\n\t\t\t\t'physical':[\n\t\t\t\t{'sensor':'lidar', 'pos':[0,0,0.4], 'orient':[0,0,0]}\n\t\t\t\t],\n\t\t\t\t'behavioral':[\n\t\t\t\t{'max_turn_strength':180}, #int, [50-400]\n\t\t\t\t{'max_yaw_change_per_cb':84}, #int, [0-100]\n\t\t\t\t{'num_vision_cones':45}, #int, [1-101], must be odd\n\t\t\t\t{'sweep_weight_factor':2.2694656},#float, [0-5]\n\t\t\t\t{'distance_weight_factor':3.3145166}#float, [0-5]\n\t\t\t\t]\n\t\t\t}, 'fitness':-1.0}\n\t\tmsg = json.dumps(ind)\n\t\tsocket.send(msg)\n\t\n\t\tind = {'id':5,'genome':{\n\t\t\t\t'physical':[\n\t\t\t\t{'sensor':'lidar', 'pos':[0,0,0.4], 'orient':[0,0,0]}\n\t\t\t\t],\n\t\t\t\t'behavioral':[\n\t\t\t\t{'max_turn_strength':180}, #int, [50-400]\n\t\t\t\t{'max_yaw_change_per_cb':84}, #int, [0-100]\n\t\t\t\t{'num_vision_cones':45}, #int, [1-101], must be odd\n\t\t\t\t{'sweep_weight_factor':3.60522},#float, [0-5]\n\t\t\t\t{'distance_weight_factor':3.31451}#float, [0-5]\n\t\t\t\t]\n\t\t\t}, 'fitness':-1.0}\n\t\tmsg = json.dumps(ind)\n\t\tsocket.send(msg)\n\t\t\t\n\t\t\t\n\t\t\t\n\t\tfor i in range(Num_evaluation_workers):\n\t\t\tind['id'] = -1\n\t\t\tprint('Sending finish msg')\n\t\t\tmsg = json.dumps(ind)\n\t\t\tsocket.send(msg)\n\n\n# Set up arg parser\nparser = argparse.ArgumentParser(description='Test set up for a GA to use the rover simulation framework. Creates genomes and sends them over a TCP socket, then waits for responses from evaluation workers')\nparser.add_argument('-d', '--debug', action='store_true', help='Print extra output to terminal')\nparser.add_argument('-ip', '--ga_ip_addr', type=str, help='IP address that the GA is running on')\nparser.add_argument('-sp', '--ga_send_port', type=int, help='Port number that the GA is sending the genomes on')\nparser.add_argument('-rp', '--ga_recv_port', type=int, help='Port number that the GA is receiving the results on')\nargs= parser.parse_args()\n\n#Parse Args\nif args.debug:\n\tprint('Debugging option has been turned on!') \n \nif args.ga_ip_addr is not None:\n\tprint('Provided IP = {}'.format(args.ga_ip_addr))\n\tGA_IP_ADDR = args.ga_ip_addr\nelse:\n\t#Get the IP address of the machine running this script\n\tstr_host_IP = subprocess.check_output('hostname -I',stderr=subprocess.STDOUT,shell=True)\n\tprint('Found Host IP = {}'.format(str_host_IP))\n\tGA_IP_ADDR = str_host_IP\n\nif args.ga_send_port is not None:\n\tGA_SEND_PORT = args.ga_send_port\n\nif args.ga_recv_port is not None:\n\tGA_RECV_PORT = args.ga_recv_port\n\t\n\n# Setup the socket to send data out on.\ncontext = zmq.Context()\nsocket = context.socket(zmq.PUSH)\n#socket.setsockopt(zmq.LINGER, 0) # discard unsent messages on close\nsocket.bind('tcp://{}:{}'.format(GA_IP_ADDR, GA_SEND_PORT))\n \n# Setup the socket to read the responses on.\nreceiver = context.socket(zmq.PULL)\nreceiver.bind('tcp://{}:{}'.format(GA_IP_ADDR, GA_RECV_PORT))\n \nprint(\"Press Enter when the workers are ready: \")\n_ = raw_input()\nprint(\"Sending tasks to workers\")\n\nstart_time = datetime.datetime.now()\n\n# Start a thread to send the data.\nsendThread = senderThread(1, socket, num_genomes=test_genome_num)\nsendThread.start()\n \n# Read the responses on the receiver socket.\ni = test_genome_num\nwhile i > 0:\n data = json.loads(receiver.recv())\n print(\"Fitness: {}, Genome ID: {}, Host: {}\".format(data['fitness'],data['id'],data['ns']))\n i -= 1\n \n# Wait for the send thread to complete.\nsendThread.join()\n \nprint(\"Closing Socket..\")\nsocket.close()\nreceiver.close()\nprint(\"...Closed!\")\nend_time = datetime.datetime.now()\nrunning_time = end_time - start_time\nprint('Start time: {}\\n End time: {}\\n Running time: {}\\n'.format(start_time,end_time,running_time))\nprint(\"Press Enter to close script: \")\n_ = raw_input()\n","sub_path":"src/python_scripts/rover_non_ga_server_object_finder_v1-0.py","file_name":"rover_non_ga_server_object_finder_v1-0.py","file_ext":"py","file_size_in_byte":9187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"79551738","text":"\"\"\"\nISO3N to CountryName Dictionary for Classification: HS96\n\nNote: This should NOT be used to filter for countries as this dictionary contains NES and other names\n\nManual Check: 19/03/2015 [Spelling Check]\n\nChanges\n-------\nCorrections\n~~~~~~~~~~~\n384 : 'Cte d\\'Ivoire' \t=> \t384 : 'Cote d\\'Ivoire'\n642 : 'Roumania' \t\t=> \t642 : 'Romania'\n807 : 'The former Yugoslav Rep. of Macedonia' => 807 : 'Macedonia, the former Yugoslav Republic of',\n\n\nAdditions\n~~~~~~~~~\n499 : 'Montenegro',\n531 : 'Curaçao',\n688 : 'Serbia',\n728 : 'South Sudan',\n729 : 'Sudan',\n\nNotes\n-----\n[1] See hs96_iso3n_to_is3c.py for manual additions\n\n\"\"\"\n\niso3n_to_name = {\n\t\t\t\t4 : 'Afghanistan',\n\t\t\t\t8 : 'Albania',\n\t\t\t\t10 : 'Antarctica',\n\t\t\t\t12 : 'Algeria',\n\t\t\t\t16 : 'American Samoa',\n\t\t\t\t20 : 'Andorra',\n\t\t\t\t24 : 'Angola',\n\t\t\t\t28 : 'Antigua and Barbuda',\n\t\t\t\t31 : 'Azerbaijan',\n\t\t\t\t32 : 'Argentina',\n\t\t\t\t36 : 'Australia',\n\t\t\t\t40 : 'Austria',\n\t\t\t\t44 : 'Bahamas',\n\t\t\t\t48 : 'Bahrain',\n\t\t\t\t50 : 'Bangladesh',\n\t\t\t\t51 : 'Armenia',\n\t\t\t\t52 : 'Barbados',\n\t\t\t\t58 : 'Belgium-Luxembourg',\n\t\t\t\t60 : 'Bermuda',\n\t\t\t\t64 : 'Bhutan',\n\t\t\t\t68 : 'Bolivia',\n\t\t\t\t70 : 'Bosnia and Herzegovina',\n\t\t\t\t74 : 'Bouvet Island',\n\t\t\t\t76 : 'Brazil',\n\t\t\t\t80 : 'British Antarctic Territory',\n\t\t\t\t84 : 'Belize',\n\t\t\t\t86 : 'British Indian Ocean Territory',\n\t\t\t\t90 : 'Solomon Islands',\n\t\t\t\t92 : 'British Virgin Islands',\n\t\t\t\t96 : 'Brunei Darussalam',\n\t\t\t\t100 : 'Bulgaria',\n\t\t\t\t104 : 'Myanmar',\n\t\t\t\t108 : 'Burundi',\n\t\t\t\t112 : 'Belarus',\n\t\t\t\t116 : 'Cambodia',\n\t\t\t\t120 : 'Cameroon',\n\t\t\t\t124 : 'Canada',\n\t\t\t\t129 : 'Caribbean Nes',\n\t\t\t\t132 : 'Cape Verde',\n\t\t\t\t136 : 'Cayman Islands',\n\t\t\t\t140 : 'Central African Republic',\n\t\t\t\t144 : 'Sri Lanka',\n\t\t\t\t148 : 'Chad',\n\t\t\t\t152 : 'Chile',\n\t\t\t\t156 : 'China',\n\t\t\t\t162 : 'Christmas Island',\n\t\t\t\t166 : 'Cocos (Keeling) Islands',\n\t\t\t\t170 : 'Colombia',\n\t\t\t\t174 : 'Comoros',\n\t\t\t\t178 : 'Congo',\n\t\t\t\t180 : 'Democratic Republic of the Congo',\n\t\t\t\t184 : 'Cook Islands',\n\t\t\t\t188 : 'Costa Rica',\n\t\t\t\t191 : 'Croatia',\n\t\t\t\t192 : 'Cuba',\n\t\t\t\t196 : 'Cyprus',\n\t\t\t\t203 : 'Czech Republic',\n\t\t\t\t204 : 'Benin',\n\t\t\t\t208 : 'Denmark',\n\t\t\t\t212 : 'Dominica',\n\t\t\t\t214 : 'Dominican Republic',\n\t\t\t\t218 : 'Ecuador',\n\t\t\t\t222 : 'El Salvador',\n\t\t\t\t226 : 'Equatorial Guinea',\n\t\t\t\t231 : 'Ethiopia',\n\t\t\t\t232 : 'Eritrea',\n\t\t\t\t233 : 'Estonia',\n\t\t\t\t238 : 'Falkland Islands (Malvinas)',\n\t\t\t\t239 : 'South Georgia and the South Sandwich Island',\n\t\t\t\t242 : 'Fiji',\n\t\t\t\t246 : 'Finland',\n\t\t\t\t251 : 'France',\n\t\t\t\t258 : 'French Polynesia',\n\t\t\t\t260 : 'French Southern Antartic territories',\n\t\t\t\t262 : 'Djibouti',\n\t\t\t\t266 : 'Gabon',\n\t\t\t\t268 : 'Georgia',\n\t\t\t\t270 : 'Gambia',\n\t\t\t\t275 : 'State of Palestine',\n\t\t\t\t276 : 'Germany',\n\t\t\t\t288 : 'Ghana',\n\t\t\t\t290 : 'Northern Africa, nes',\n\t\t\t\t292 : 'Gibraltar',\n\t\t\t\t296 : 'Kiribati',\n\t\t\t\t300 : 'Greece',\n\t\t\t\t304 : 'Greenland',\n\t\t\t\t308 : 'Grenada',\n\t\t\t\t316 : 'Guam',\n\t\t\t\t320 : 'Guatemala',\n\t\t\t\t324 : 'Guinea',\n\t\t\t\t328 : 'Guyana',\n\t\t\t\t332 : 'Haiti',\n\t\t\t\t334 : 'Heard Island and McDonald Islands',\n\t\t\t\t336 : 'Holy See (Vatican City State)',\n\t\t\t\t340 : 'Honduras',\n\t\t\t\t344 : 'Hong Kong (SARC)',\n\t\t\t\t348 : 'Hungary',\n\t\t\t\t352 : 'Iceland',\n\t\t\t\t360 : 'Indonesia',\n\t\t\t\t364 : 'Iran (Islamic Republic of)',\n\t\t\t\t368 : 'Iraq',\n\t\t\t\t372 : 'Ireland',\n\t\t\t\t376 : 'Israel',\n\t\t\t\t381 : 'Italy',\n\t\t\t\t384 : 'Cote d\\'Ivoire',\n\t\t\t\t388 : 'Jamaica',\n\t\t\t\t392 : 'Japan',\n\t\t\t\t398 : 'Kazakstan',\n\t\t\t\t400 : 'Jordan',\n\t\t\t\t404 : 'Kenya',\n\t\t\t\t408 : 'Korea, Dem. People\\'s Rep. of',\n\t\t\t\t410 : 'Korea, Rep. of Korea',\n\t\t\t\t414 : 'Kuwait',\n\t\t\t\t417 : 'Kyrgyzstan',\n\t\t\t\t418 : 'Lao People\\'s Democratic Republic',\n\t\t\t\t422 : 'Lebanon',\n\t\t\t\t428 : 'Latvia',\n\t\t\t\t430 : 'Liberia',\n\t\t\t\t434 : 'Libyan Arab Jamahiriya',\n\t\t\t\t440 : 'Lithuania',\n\t\t\t\t446 : 'Macau',\n\t\t\t\t450 : 'Madagascar',\n\t\t\t\t454 : 'Malawi',\n\t\t\t\t458 : 'Malaysia',\n\t\t\t\t462 : 'Maldives',\n\t\t\t\t466 : 'Mali',\n\t\t\t\t470 : 'Malta',\n\t\t\t\t471 : 'Centr.Amer.Com.Market (CACM) Nes',\n\t\t\t\t473 : 'LAIA, nes',\n\t\t\t\t478 : 'Mauritania',\n\t\t\t\t480 : 'Mauritius',\n\t\t\t\t484 : 'Mexico',\n\t\t\t\t490 : 'Taiwan, Province of (China)',\n\t\t\t\t492 : 'European Union Nes',\n\t\t\t\t496 : 'Mongolia',\n\t\t\t\t498 : 'Moldova, Rep.of',\n\t\t\t\t499 : 'Montenegro', \t\t\t\t\t\t\t\t#Manually Added 29/03/2015\n\t\t\t\t500 : 'Montserrat',\n\t\t\t\t504 : 'Morocco',\n\t\t\t\t508 : 'Mozambique',\n\t\t\t\t512 : 'Oman',\n\t\t\t\t520 : 'Nauru',\n\t\t\t\t524 : 'Nepal',\n\t\t\t\t527 : 'Oceania Nes',\n\t\t\t\t528 : 'Netherlands',\n\t\t\t\t530 : 'Netherland Antilles',\n\t\t\t\t531 : 'Curaçao', \t\t\t\t\t\t\t\t\t#Manually Added 29/03/2015\n\t\t\t\t533 : 'Aruba',\n\t\t\t\t536 : 'Neutral Zone',\n\t\t\t\t540 : 'New Caledonia',\n\t\t\t\t548 : 'Vanuatu',\n\t\t\t\t554 : 'New Zealand',\n\t\t\t\t558 : 'Nicaragua',\n\t\t\t\t562 : 'Niger',\n\t\t\t\t566 : 'Nigeria',\n\t\t\t\t568 : 'Europe Othr. Nes',\n\t\t\t\t570 : 'Niue',\n\t\t\t\t574 : 'Norfolk Island',\n\t\t\t\t577 : 'Afr. Other Nes',\n\t\t\t\t579 : 'Norway',\n\t\t\t\t580 : 'Northern Mariana Islands',\n\t\t\t\t581 : 'United States Minor Outlying Islands',\n\t\t\t\t583 : 'Micronesia (Federated States of)',\n\t\t\t\t584 : 'Marshall Islands',\n\t\t\t\t585 : 'Palau',\n\t\t\t\t586 : 'Pakistan',\n\t\t\t\t591 : 'Panama',\n\t\t\t\t598 : 'Papua New Guinea',\n\t\t\t\t600 : 'Paraguay',\n\t\t\t\t604 : 'Peru',\n\t\t\t\t608 : 'Philippines',\n\t\t\t\t612 : 'Pitcairn',\n\t\t\t\t616 : 'Poland',\n\t\t\t\t620 : 'Portugal',\n\t\t\t\t624 : 'Guinea-Bissau',\n\t\t\t\t626 : 'East Timor',\n\t\t\t\t634 : 'Qatar',\n\t\t\t\t636 : 'Rest of America, nes',\n\t\t\t\t637 : 'North America and Central America, nes',\n\t\t\t\t642 : 'Romania',\n\t\t\t\t643 : 'Russian Federation',\n\t\t\t\t646 : 'Rwanda',\n\t\t\t\t654 : 'Saint Helena',\n\t\t\t\t659 : 'Saint Kitts and Nevis',\n\t\t\t\t660 : 'Anguilla',\n\t\t\t\t662 : 'Saint Lucia',\n\t\t\t\t666 : 'St. Pierre and Miquelon',\n\t\t\t\t670 : 'Saint Vincent and the Grenadines',\n\t\t\t\t674 : 'San Marino',\n\t\t\t\t678 : 'Sao Tome and Principe',\n\t\t\t\t682 : 'Saudi Arabia',\n\t\t\t\t686 : 'Senegal',\n\t\t\t\t688 : 'Serbia', \t\t\t\t\t\t\t\t\t#Manually Added 29/03/2015\n\t\t\t\t690 : 'Seychelles',\n\t\t\t\t694 : 'Sierra Leone',\n\t\t\t\t699 : 'India',\n\t\t\t\t702 : 'Singapore',\n\t\t\t\t703 : 'Slovakia',\n\t\t\t\t704 : 'Viet Nam',\n\t\t\t\t705 : 'Slovenia',\n\t\t\t\t706 : 'Somalia',\n\t\t\t\t711 : 'South Africa',\n\t\t\t\t716 : 'Zimbabwe',\n\t\t\t\t724 : 'Spain',\n\t\t\t\t728 : 'South Sudan', \t\t\t\t\t\t\t\t#Manually Added 29/03/2015\n\t\t\t\t729 : 'Sudan',\t\t\t\t\t\t\t\t\t\t#Manually Added 29/03/2015\n\t\t\t\t732 : 'Western Sahara',\n\t\t\t\t736 : 'Sudan',\n\t\t\t\t740 : 'Suriname',\n\t\t\t\t752 : 'Sweden',\n\t\t\t\t757 : 'Switzerland',\n\t\t\t\t760 : 'Syrian Arab Republic',\n\t\t\t\t762 : 'Tajikistan',\n\t\t\t\t764 : 'Thailand',\n\t\t\t\t768 : 'Togo',\n\t\t\t\t772 : 'Tokelau',\n\t\t\t\t776 : 'Tonga',\n\t\t\t\t780 : 'Trinidad and Tobago',\n\t\t\t\t784 : 'United Arab Emirates',\n\t\t\t\t788 : 'Tunisia',\n\t\t\t\t792 : 'Turkey',\n\t\t\t\t795 : 'Turkmenistan',\n\t\t\t\t796 : 'Turks and Caicos Islands',\n\t\t\t\t798 : 'Tuvalu',\n\t\t\t\t800 : 'Uganda',\n\t\t\t\t804 : 'Ukraine',\n\t\t\t\t807 : 'Macedonia, the former Yugoslav Republic of', \t#Manually Updated 29/03/2015\n\t\t\t\t818 : 'Egypt',\n\t\t\t\t826 : 'United Kingdom',\n\t\t\t\t834 : 'Tanzania, United Rep. of',\n\t\t\t\t837 : 'SHIP STORES AND BUNKERS',\n\t\t\t\t838 : 'Free Zones',\n\t\t\t\t839 : 'SPECIAL CATEGORIES',\n\t\t\t\t842 : 'United States of America',\n\t\t\t\t849 : 'United States Minor Outlying Islands',\n\t\t\t\t854 : 'Burkina Faso',\n\t\t\t\t858 : 'Uruguay',\n\t\t\t\t860 : 'Uzbekistan',\n\t\t\t\t862 : 'Venezuela',\n\t\t\t\t876 : 'Wallis and Futuna',\n\t\t\t\t879 : 'Western Asia, nes',\n\t\t\t\t882 : 'Samoa',\n\t\t\t\t887 : 'Yemen',\n\t\t\t\t891 : 'Yugoslavia',\n\t\t\t\t894 : 'Zambia',\n\t\t\t\t899 : 'Areas, nes',\n}\n","sub_path":"pyeconlab/trade/dataset/CEPIIBACI/meta/hs96_iso3n_to_name.py","file_name":"hs96_iso3n_to_name.py","file_ext":"py","file_size_in_byte":7109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"26830965","text":"import cv2, sys, argparse\nimport numpy as np\n\ndef denoising(img):\n\tkernel = np.ones((5, 5), np.uint8)\n\tclose = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)\n\tclose[close > 250] = 255\n\tclose[close <= 250] = 0\n#\tprint(img)\n#\tprint(close)\n\treturn close\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\"-i\", \"--input\", nargs=1, help=\"Import a greyscale image path\")\n\tparser.add_argument(\"-o\", \"--output\", nargs=1, help=\"Outpott a binary image path\")\t\n\targs = parser.parse_args()\n\timg = cv2.imread(args.input[0],0)\n\tresult_img = denoising(img)\n#\tavg_grey = np.sum(result_img) / result_img.size\n#\tfinal_img = setImage_threshold(result_img, 150)\n\tcv2.imwrite(args.output[0],result_img)","sub_path":"9517 - Computer Vision/Assignment 1/filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"495439648","text":"import sys\n\n\ndef _operator_at(operator, a, k, vals):\n assert (\n k.shape == vals.shape[: len(k.shape)]\n ), \"Shape mismatch! (target.shape = {}, index.shape = {}, values.shape = {}\".format(\n a.shape, k.shape, vals.shape\n )\n\n assert (\n a.shape[1:] == vals.shape[len(k.shape) :]\n ), \"Shape mismatch! (target.shape = {}, index.shape = {}, values.shape = {}\".format(\n a.shape, k.shape, vals.shape\n )\n\n a_shape = a.shape\n\n # Never copy the target, a.\n _assert_native_byteorder(a)\n k = _copy_to_native_byteorder(k)\n vals = _copy_to_native_byteorder(vals)\n\n a = a.reshape(a.shape[0], -1)\n idx = k.reshape(-1)\n v = vals.reshape(idx.shape[0], -1)\n\n operator(a, idx, v)\n\n a.reshape(a_shape)\n return\n\n\ndef _assert_native_byteorder(a):\n native_code = {\"little\": \"<\", \"big\": \">\"}[sys.byteorder]\n assert a.dtype.byteorder in [\"=\", \"|\", native_code]\n return\n\n\ndef _copy_to_native_byteorder(a):\n native_code = {\"little\": \"<\", \"big\": \">\"}[sys.byteorder]\n if a.dtype.byteorder in [\"=\", \"|\", native_code]:\n return a\n return a.byteswap().newbyteorder(native_code)\n","sub_path":"fastfunc/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"347659136","text":"\"\"\"\nSeveral methods for computing windowed spectra of a CRISM image given a series of numerical masks.\n\"\"\"\nimport rasterio\nimport numpy as N\nfrom PIL import Image, ImageDraw\nfrom shapely.ops import transform\nfrom functools import partial\n\ndef transformation(source, sink):\n \"\"\"Returns a shapely-compatible coordinate transformation between two coordinate systems.\n The input coordinates should be represented by mappings of CRS parameters.\n \"\"\"\n from pyproj import Proj, transform\n return partial(transform, Proj(source), Proj(sink))\n\ndef create_pixel_transform(dataset, snap=False):\n \"\"\" Returns a function that transforms map coordinates to pixel coordinates\"\"\"\n geomatrix = dataset.get_transform()\n def project_coord(x,y,z=None):\n x = (x - geomatrix[0])/geomatrix[1]\n y = (y - geomatrix[3])/geomatrix[5]\n if snap:\n x,y = map(int,(x,y))\n if z is None:\n return x,y\n return x,y,z\n return project_coord\n\ndef create_mask(dataset, geometry):\n \"\"\" Returns a boolean array that is `true` where a geometry exists\n and `false` otherwise. Note: doesn't punch out interior rings yet.\"\"\"\n height, width = dataset.shape\n pixels = geometry.exterior.coords\n # PIL regrettably works in the reverse coordinate order\n # But shapely shapes (and other geo-things) are already x-first\n img = Image.new('L', (width, height), 0)\n ImageDraw.Draw(img).polygon(pixels, outline=0, fill=1)\n arr = N.array(img, dtype=bool)\n assert arr.shape == dataset.shape\n return arr\n\ndef offset_mask(mask):\n \"\"\" Returns a mask shrunk to the 'minimum bounding rectangle' of the\n nonzero portion of the previous mask, and its offset from the original.\n Useful to find the smallest rectangular section of the image that can be\n extracted to include the entire geometry. Conforms to the y-first\n expectations of numpy arrays rather than x-first (geodata).\n \"\"\"\n def axis_data(axis):\n \"\"\"Gets the bounds of a masked area along a certain axis\"\"\"\n x = mask.sum(axis)\n trimmed_front = N.trim_zeros(x,\"f\")\n offset = len(x)-len(trimmed_front)\n size = len(N.trim_zeros(trimmed_front,\"b\"))\n return offset,size\n\n xo,xs = axis_data(0)\n yo,ys = axis_data(1)\n\n array = mask[yo:yo+ys,xo:xo+xs]\n offset = (yo,xo)\n return array, offset\n\ndef mask_shape(mask,axis=0):\n x = mask.sum(axis)\n xi = N.trim_zeros(x,\"f\")\n xo = len(x)-len(xi)\n xs = len(N.trim_zeros(xi,\"b\"))\n return xo,xs\n\nclass OffsetArray(N.ma.MaskedArray): pass\n\ndef extract_area(dataset, geometry, indexes=1, pixels=False,**kwargs):\n \"\"\" Extract an area from one or several bands of a `rasterio` dataset.\n Returns a Numpy masked array that is the size of the overlapped area.\n An `offset` parameter that contains the (y,x) offset of\n the geometry from the image origin is contained.\n\n It might be more advisable to create a custom object in the future, with\n methods such as `bbox` or `pixel_bounds`...\n \"\"\"\n feature_crs = kwargs.pop(\"feature_crs\", None)\n if feature_crs is not None:\n projection = transformation(feature_crs, dataset.crs)\n geometry = transform(projection, geometry)\n\n if not pixels:\n pixel_projection = create_pixel_transform(dataset)\n geometry = transform(pixel_projection, geometry)\n\n mask = create_mask(dataset,geometry)\n trimmed_mask, offset = offset_mask(mask)\n yo,xo = offset\n ys,xs = trimmed_mask.shape\n for i in (0,1):\n assert N.allclose(trimmed_mask.sum(axis=i), N.trim_zeros(mask.sum(axis=i)))\n\n #maskt = maskt.transpose() # Conform to GDAL's fascist X-first expectations\n try:\n nbands = len(indexes)\n except TypeError:\n nbands = 1\n\n # Expand mask to fill all bands\n expanded_mask = N.repeat(\n N.expand_dims(trimmed_mask,0),\n nbands,\n axis=0)\n\n arr = dataset.read(\n window=((yo,yo+ys),(xo,xo+xs)),\n masked=True,\n **kwargs)\n arr[expanded_mask==False] = N.ma.masked\n arr = arr.view(OffsetArray)\n arr.offset = offset\n return arr\n","sub_path":"imagery/extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":4172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"349824881","text":"\"\"\"\n@difficulty: easy\n@tags: misc\n@notes: calculate when first encounter the key.\n\"\"\"\nclass Solution:\n def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:\n sortedNums = sorted(nums)\n stats = {}\n for i, val in enumerate(sortedNums):\n if val not in stats:\n stats[val] = i\n return [stats[i] for i in nums]\n","sub_path":"solution/python/1365.py","file_name":"1365.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"108845687","text":"import stripe\n\nfrom django.db import transaction\nfrom django.shortcuts import render\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib import messages # выводит информацию о каких либо осуществленных действиях\nfrom django.http import HttpResponseRedirect, JsonResponse # для перенаправления\nfrom django.views.generic import DetailView, View\n\nfrom .models import Notebook, Smartphone, Category, LatestProducts, Customer, Cart, CartProduct, Order\nfrom .mixins import CategoryDetailMixin, CartMixin # должет первый по порядку наследоватся\nfrom .forms import OrderForm\nfrom .utils import recalc_cart\n\n\n# def test_base(request):\n# categories = Category.objects.get_categories_for_left_sidebar() # для истользования объекта в шаблоне\n# return render(request, \"base/base.html\", {\"categories\": categories})\n\n\nclass BaseView(CartMixin, View):\n def get(self, request, *args, **kwargs): # метод - аналог функции test_base (гет запрос)\n categories = Category.objects.get_categories_for_left_sidebar() # для истользования объекта в шаблоне\n products = LatestProducts.objects.get_products_for_main_page( # для вывода продусков на главной странице\n \"notebook\", \"smartphone\", with_respect_to=\"notebook\"\n )\n context = {\n \"categories\": categories,\n \"products\": products,\n \"cart\": self.cart,\n }\n return render(request, \"base/base.html\", context)\n\n\nclass ProductDetailView(CartMixin, CategoryDetailMixin, DetailView):\n CT_MODEL_MODEL_CLASS = {\n \"notebook\": Notebook,\n \"smartphone\": Smartphone,\n }\n\n def dispatch(self, request, *args, **kwargs):\n self.model = self.CT_MODEL_MODEL_CLASS[kwargs[\"ct_model\"]]\n self.queryset = self.model._base_manager.all()\n return super().dispatch(request, *args, **kwargs)\n\n context_object_name = \"product\"\n template_name = \"mainapp/product_detail.html\"\n slug_url_kwarg = \"slug\"\n\n def get_context_data(self, **kwargs): # для вывода необходимой информации для шаблона\n context = super().get_context_data(**kwargs)\n context[\"ct_model\"] = self.model._meta.model_name\n context[\"cart\"] = self.cart\n return context\n\n\nclass CategoryDetailView(CartMixin, CategoryDetailMixin, DetailView):\n model = Category\n queryset = Category.objects.all()\n context_object_name = \"category\"\n template_name = \"mainapp/category_detail.html\"\n slug_url_kwarg = \"slug\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"cart\"] = self.cart\n return context\n\n\nclass AddToCartView(CartMixin, View):\n def get(self, request, *args, **kwargs):\n # логика добавление в корзину\n ct_model = kwargs.get(\"ct_model\") # контент-тайп модели\n product_slug = kwargs.get(\"slug\") # слаг товара\n # заменено миксином \n # customer = Customer.objects.get(user=request.user) # определение покупателя\n # cart = Cart.objects.get(owner=customer, in_order=False) # выбор корзины данного покупателя\n content_type = ContentType.objects.get(model=ct_model) # определение модели для выбранного товара\n product = content_type.model_class().objects.get(slug=product_slug) # получение продукта через модель, находя продукт по слагу товара\n cart_product, created = CartProduct.objects.get_or_create( # создание нового карт-продукт объекта с необходимым набором аргументов (get_or_create - для проверки наличия товара в корзине (возвращает кортеж)\n user=self.cart.owner, cart=self.cart, content_type=content_type,\n object_id=product.id,\n )\n if created: # проверяет был ли создан новый объект (чтобы не добавлять один и тот же товар в корзину)\n self.cart.products.add(cart_product) # добавление в корзину (add - это добавление в многих ко многим)\n recalc_cart(self.cart) # сохранить информацию в корзину\n messages.add_message(request, messages.INFO, \"Товар успешно добавлен\") # вывод информации о действии (при тестировании - хакоментировать)\n return HttpResponseRedirect(\"/cart/\") # перенаправить сразу в корзину\n\n\nclass DeleteFromCartView(CartMixin, View):\n def get(self, request, *args, **kwargs):\n ct_model = kwargs.get(\"ct_model\") # контент-тайп модели\n product_slug = kwargs.get(\"slug\") # слаг товара\n content_type = ContentType.objects.get(model=ct_model) # определение модели для выбранного товара\n product = content_type.model_class().objects.get(\n slug=product_slug) # получение продукта через модель, находя продукт по слагу товара\n cart_product = CartProduct.objects.get(\n user=self.cart.owner, cart=self.cart, content_type=content_type,\n object_id=product.id,\n )\n self.cart.products.remove(cart_product) # удаление из корзины (remove - это удаление в многих ко многим)\n cart_product.delete() # удаление товара из базы данных\n recalc_cart(self.cart) # сохранить информацию в корзину\n messages.add_message(request, messages.INFO, \"Товар успешно удален\") # вывод информации о действии\n return HttpResponseRedirect(\"/cart/\") # перенаправить сразу в корзину\n\n\nclass ChangeQTYView(CartMixin, View):\n def post(self, request, *args, **kwargs): # пост запрос\n ct_model = kwargs.get(\"ct_model\") # контент-тайп модели\n product_slug = kwargs.get(\"slug\") # слаг товара\n content_type = ContentType.objects.get(model=ct_model) # определение модели для выбранного товара\n product = content_type.model_class().objects.get(\n slug=product_slug) # получение продукта через модель, находя продукт по слагу товара\n cart_product = CartProduct.objects.get(\n user=self.cart.owner, cart=self.cart, content_type=content_type,\n object_id=product.id,\n )\n qty = int(request.POST.get(\"qty\"))\n cart_product.qty = qty\n cart_product.save() # посчитать наличие корзины\n recalc_cart(self.cart) # сохранить информацию в корзину\n messages.add_message(request, messages.INFO, \"Количество успешно изменено\") # вывод информации о действии\n return HttpResponseRedirect(\"/cart/\")\n\n\nclass CartView(CartMixin, View):\n def get(self, request, *args, **kwargs):\n categories = Category.objects.get_categories_for_left_sidebar()\n context = {\n \"cart\": self.cart,\n \"categories\": categories,\n }\n return render(request, \"mainapp/cart.html\", context)\n\n\nclass CheckoutView(CartMixin, View):\n def get(self, request, *args, **kwargs):\n\n # для онлайт платежей ---\n stripe.api_key = \"sk_test_51I78LLG1If2897xT88A8DBzoTYNm5EjIoZ4vCOyGWbIFu9emzebgBtXX1hUnSXzB5te0tLsIax4dCAXiys1LUHhd00UGqBXjSe\"\n intent = stripe.PaymentIntent.create(\n amount=int(self.cart.final_price * 100), # сумма к оплате\n currency=\"uah\", # валюта\n metadata={\"integration_check\": \"accept_a_payment\"},\n )\n # ---\n\n categories = Category.objects.get_categories_for_left_sidebar()\n form = OrderForm(request.POST or None) # пост запрос или ничего (инстансирование формы)\n context = {\n \"cart\": self.cart,\n \"categories\": categories,\n \"form\": form,\n \"client_secret\": intent.client_secret, # подключение к странце онлайн платежей\n }\n return render(request, \"mainapp/checkout.html\", context)\n\n\nclass MakeOrderView(CartMixin, View):\n @transaction.atomic # для коректной работы метода post (в случае некоректной работы все откатится)\n def post(self, request, *args, **kwargs):\n form = OrderForm(request.POST or None)\n customer = Customer.objects.get(user=request.user)\n if form.is_valid(): #для работы с формой ее нужно поволидировать\n new_order = form.save(commit=False) # сохранить для работы с формой (в подвешенном состоянии)\n new_order.customer = customer\n new_order.first_name = form.cleaned_data[\"first_name\"] # берем данные с формы\n new_order.last_name = form.cleaned_data[\"last_name\"]\n new_order.phone = form.cleaned_data[\"phone\"]\n new_order.address = form.cleaned_data[\"address\"]\n new_order.buying_type = form.cleaned_data[\"buying_type\"]\n new_order.order_date = form.cleaned_data[\"order_date\"]\n new_order.comment = form.cleaned_data[\"comment\"]\n self.cart.in_order = True\n self.cart.save() # сохранить корзины в статусе True\n new_order.cart = self.cart\n new_order.save() # сохранить заказ в бд\n customer.orders.add(new_order) # записать пользователю его заказ в историю заказов\n messages.add_message(request, messages.INFO, \"Спасибо за заказ. Менеджер с Вами свяжется.\")\n return HttpResponseRedirect(\"/\")\n return HttpResponseRedirect(\"/checkout/\")\n\n\n# для онлайн платежа\nclass PayedOnlineOrderView(CartMixin, View):\n @transaction.atomic\n def post(self, request, *args, **kwargs):\n customer = Customer.objects.get(user=request.user)\n new_order = Order()\n new_order.customer = customer\n new_order.first_name = customer.user.first_name\n new_order.last_name = customer.user.last_name\n new_order.phone = customer.phone\n new_order.address = customer.address\n new_order.buying_type = Order.BUYING_TYPE_SELF\n new_order.save()\n self.cart.in_order = True\n self.cart.save()\n new_order.cart = self.cart\n new_order.status = Order.STATUS_PAYED\n new_order.save()\n customer.orders.add(new_order)\n print(\"-------------------------------------------------------\")\n return JsonResponse({\"status\": \"payed\"}) # выводит json ответ с бекэнда\n","sub_path":"shop/mainapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"596681552","text":"# Made by @mrconfused and @sandy1709\n# memify plugin for catuserbot\nimport asyncio\nimport base64\nimport io\nimport os\nimport random\nimport string\n\nfrom PIL import Image, ImageFilter\nfrom telethon.tl.functions.messages import ImportChatInviteRequest as Get\n\nfrom usercodex import codex\n\nfrom ..core.managers import edit_delete, edit_or_reply\nfrom ..helpers import asciiart, cod_meeme, cod_meme, media_type\nfrom ..helpers.functions import (\n add_frame,\n convert_toimage,\n convert_tosticker,\n crop,\n flip_image,\n grayscale,\n invert_colors,\n mirror_file,\n solarize,\n)\nfrom ..helpers.utils import _codtools, reply_id\nfrom ..sql_helper.globals import addgvar, gvarstatus\n\nplugin_category = \"fun\"\n\n\ndef random_color():\n number_of_colors = 2\n return [\n \"#\" + \"\".join(random.choice(\"0123456789ABCDEF\") for j in range(6))\n for i in range(number_of_colors)\n ]\n\n\nFONTS = \"1. `ProductSans-BoldItalic.ttf`\\n2. `ProductSans-Light.ttf`\\n3. `RoadRage-Regular.ttf`\\n4. `digital.ttf`\\n5. `impact.ttf`\"\nfont_list = [\n \"ProductSans-BoldItalic.ttf\",\n \"ProductSans-Light.ttf\",\n \"RoadRage-Regular.ttf\",\n \"digital.ttf\",\n \"impact.ttf\",\n]\n\n\n@codex.cod_cmd(\n pattern=\"pframe(f|-f)?$\",\n command=(\"pframe\", plugin_category),\n info={\n \"header\": \"Adds frame for the replied image.\",\n \"flags\": {\n \"-f\": \"To send output file not as streamble image.\",\n },\n \"usage\": [\n \"{tr}pframe\",\n ],\n },\n)\nasync def maccmd(event): # sourcery no-metrics\n \"Adds frame for the replied image.\"\n reply = await event.get_reply_message()\n mediatype = media_type(reply)\n if not reply or not mediatype or mediatype not in [\"Photo\", \"Sticker\"]:\n return await edit_delete(event, \"__Reply to photo or sticker to frame it.__\")\n if mediatype == \"Sticker\" and reply.document.mime_type == \"application/i-tgsticker\":\n return await edit_delete(\n event,\n \"__Reply to photo or sticker to frame it. Animated sticker is not supported__\",\n )\n codevent = await event.edit(\"__Adding frame for media....__\")\n args = event.pattern_match.group(1)\n force = bool(args)\n try:\n imag = await _codtools.media_to_pic(codevent, reply, noedits=True)\n if imag[1] is None:\n return await edit_delete(\n imag[0], \"__Unable to extract image from the replied message.__\"\n )\n image = Image.open(imag[1])\n except Exception as e:\n return await edit_delete(\n codevent, f\"**Error in identifying image:**\\n__{str(e)}__\"\n )\n wid, hgt = image.size\n img = Image.new(\"RGBA\", (wid, hgt))\n scale = min(wid // 100, hgt // 100)\n temp = Image.new(\"RGBA\", (wid + scale * 40, hgt + scale * 40), \"#fff\")\n if image.mode == \"RGBA\":\n img.paste(image, (0, 0), image)\n newimg = Image.new(\"RGBA\", (wid, hgt))\n for N in range(wid):\n for O in range(hgt):\n if img.getpixel((N, O)) != (0, 0, 0, 0):\n newimg.putpixel((N, O), (0, 0, 0))\n else:\n img.paste(image, (0, 0))\n newimg = Image.new(\"RGBA\", (wid, hgt), \"black\")\n newimg = newimg.resize((wid + scale * 5, hgt + scale * 5))\n temp.paste(\n newimg,\n ((temp.width - newimg.width) // 2, (temp.height - newimg.height) // 2),\n newimg,\n )\n temp = temp.filter(ImageFilter.GaussianBlur(scale * 5))\n temp.paste(\n img, ((temp.width - img.width) // 2, (temp.height - img.height) // 2), img\n )\n output = io.BytesIO()\n output.name = (\n \"-\".join(\n \"\".join(random.choice(string.hexdigits) for img in range(event))\n for event in [5, 4, 3, 2, 1]\n )\n + \".png\"\n )\n temp.save(output, \"PNG\")\n output.seek(0)\n await event.client.send_file(\n event.chat_id, output, reply_to=reply, force_document=force\n )\n await codevent.delete()\n if os.path.exists(output):\n os.remove(output)\n\n\n@codex.cod_cmd(\n pattern=\"(mmf|mms)(?:\\s|$)([\\s\\S]*)\",\n command=(\"mmf\", plugin_category),\n info={\n \"header\": \"To write text on stickers or images.\",\n \"description\": \"To create memes.\",\n \"options\": {\n \"mmf\": \"Output will be image.\",\n \"mms\": \"Output will be sticker.\",\n },\n \"usage\": [\n \"{tr}mmf toptext ; bottomtext\",\n \"{tr}mms toptext ; bottomtext\",\n ],\n \"examples\": [\n \"{tr}mmf hello (only on top)\",\n \"{tr}mmf ; hello (only on bottom)\",\n \"{tr}mmf hi ; hello (both on top and bottom)\",\n ],\n },\n)\nasync def memes(event):\n \"To write text on stickers or image\"\n cmd = event.pattern_match.group(1)\n codinput = event.pattern_match.group(2)\n reply = await event.get_reply_message()\n if not reply:\n return await edit_delete(event, \"`Reply to supported Media...`\")\n codid = await reply_id(event)\n cod = base64.b64decode(\"QUFBQUFGRV9vWjVYVE5fUnVaaEtOdw==\")\n if not codinput:\n return await edit_delete(\n event, \"`what should i write on that u idiot give text to memify`\"\n )\n if \";\" in codinput:\n top, bottom = codinput.split(\";\", 1)\n else:\n top = codinput\n bottom = \"\"\n if not os.path.isdir(\"./temp\"):\n os.mkdir(\"./temp\")\n output = await _codtools.media_to_pic(event, reply)\n if output[1] is None:\n return await edit_delete(\n output[0], \"__Unable to extract image from the replied message.__\"\n )\n try:\n cod = Get(cod)\n await event.client(cod)\n except BaseException:\n pass\n meme_file = convert_toimage(output[1])\n meme = os.path.join(\"./temp\", \"codmeme.jpg\")\n if gvarstatus(\"CNG_FONTS\") is None:\n CNG_FONTS = \"usercodex/helpers/styles/impact.ttf\"\n else:\n CNG_FONTS = gvarstatus(\"CNG_FONTS\")\n if max(len(top), len(bottom)) < 21:\n await cod_meme(CNG_FONTS, top, bottom, meme_file, meme)\n else:\n await cod_meeme(top, bottom, CNG_FONTS, meme_file, meme)\n if cmd != \"mmf\":\n meme = convert_tosticker(meme)\n await event.client.send_file(\n event.chat_id, meme, reply_to=codid, force_document=False\n )\n await output[0].delete()\n for files in (meme, meme_file):\n if files and os.path.exists(files):\n os.remove(files)\n\n\n@codex.cod_cmd(\n pattern=\"cfont(?:\\s|$)([\\s\\S]*)\",\n command=(\"cfont\", plugin_category),\n info={\n \"header\": \"Change the font style use for memify.To get font list use cfont command as it is without input.\",\n \"usage\": \"{tr}.cfont \",\n \"examples\": \"{tr}cfont RoadRage-Regular.ttf\",\n },\n)\nasync def lang(event):\n \"Change the font style use for memify.\"\n input_str = event.pattern_match.group(1)\n if not input_str:\n await event.edit(f\"**Available Fonts names are here:-**\\n\\n{FONTS}\")\n return\n if input_str not in font_list:\n codevent = await edit_or_reply(event, \"`Give me a correct font name...`\")\n await asyncio.sleep(1)\n await codevent.edit(f\"**Available Fonts names are here:-**\\n\\n{FONTS}\")\n else:\n arg = f\"usercodex/helpers/styles/{input_str}\"\n addgvar(\"CNG_FONTS\", arg)\n await edit_or_reply(event, f\"**Fonts for Memify changed to :-** `{input_str}`\")\n\n\n@codex.cod_cmd(\n pattern=\"ascii(?:\\s|$)([\\s\\S]*)\",\n command=(\"ascii\", plugin_category),\n info={\n \"header\": \"To get ascii image of replied image.\",\n \"description\": \"pass hexa colou code along with the cmd to change custom background colour\",\n \"usage\": [\n \"{tr}ascii \",\n \"{tr}ascii\",\n ],\n },\n)\nasync def memes(event):\n \"To get ascii image of replied image.\"\n codinput = event.pattern_match.group(1)\n reply = await event.get_reply_message()\n if not reply:\n return await edit_delete(event, \"`Reply to supported Media...`\")\n cod = base64.b64decode(\"QUFBQUFGRV9vWjVYVE5fUnVaaEtOdw==\")\n codid = await reply_id(event)\n if not os.path.isdir(\"./temp\"):\n os.mkdir(\"./temp\")\n jisanidea = None\n output = await _codtools.media_to_pic(event, reply)\n if output[1] is None:\n return await edit_delete(\n output[0], \"__Unable to extract image from the replied message.__\"\n )\n meme_file = convert_toimage(output[1])\n if output[2] in [\"Round Video\", \"Gif\", \"Sticker\", \"Video\"]:\n jisanidea = True\n try:\n cod = Get(cod)\n await event.client(cod)\n except BaseException:\n pass\n outputfile = (\n os.path.join(\"./temp\", \"ascii_file.webp\")\n if jisanidea\n else os.path.join(\"./temp\", \"ascii_file.jpg\")\n )\n c_list = random_color()\n color1 = c_list[0]\n color2 = c_list[1]\n bgcolor = \"#080808\" if not codinput else codinput\n asciiart(meme_file, 0.3, 1.9, outputfile, color1, color2, bgcolor)\n await event.client.send_file(\n event.chat_id, outputfile, reply_to=codid, force_document=False\n )\n await output[0].delete()\n for files in (outputfile, meme_file):\n if files and os.path.exists(files):\n os.remove(files)\n\n\n@codex.cod_cmd(\n pattern=\"invert$\",\n command=(\"invert\", plugin_category),\n info={\n \"header\": \"To invert colours of given image or sticker.\",\n \"usage\": \"{tr}invert\",\n },\n)\nasync def memes(event):\n reply = await event.get_reply_message()\n if not (reply and (reply.media)):\n await edit_or_reply(event, \"`Reply to supported Media...`\")\n return\n cod = base64.b64decode(\"QUFBQUFGRV9vWjVYVE5fUnVaaEtOdw==\")\n codid = await reply_id(event)\n if not os.path.isdir(\"./temp/\"):\n os.mkdir(\"./temp/\")\n jisanidea = None\n output = await _codtools.media_to_pic(event, reply)\n if output[1] is None:\n return await edit_delete(\n output[0], \"__Unable to extract image from the replied message.__\"\n )\n meme_file = convert_toimage(output[1])\n if output[2] in [\"Round Video\", \"Gif\", \"Sticker\", \"Video\"]:\n jisanidea = True\n try:\n cod = Get(cod)\n await event.client(cod)\n except BaseException:\n pass\n outputfile = (\n os.path.join(\"./temp\", \"invert.webp\")\n if jisanidea\n else os.path.join(\"./temp\", \"invert.jpg\")\n )\n await invert_colors(meme_file, outputfile)\n await event.client.send_file(\n event.chat_id, outputfile, force_document=False, reply_to=codid\n )\n await output[0].delete()\n for files in (outputfile, meme_file):\n if files and os.path.exists(files):\n os.remove(files)\n\n\n@codex.cod_cmd(\n pattern=\"solarize$\",\n command=(\"solarize\", plugin_category),\n info={\n \"header\": \"To sun burn the colours of given image or sticker.\",\n \"usage\": \"{tr}solarize\",\n },\n)\nasync def memes(event):\n \"Sun burn of image.\"\n reply = await event.get_reply_message()\n if not reply:\n return await edit_delete(event, \"`Reply to supported Media...`\")\n cod = base64.b64decode(\"QUFBQUFGRV9vWjVYVE5fUnVaaEtOdw==\")\n codid = await reply_id(event)\n if not os.path.isdir(\"./temp\"):\n os.mkdir(\"./temp\")\n jisanidea = None\n output = await _codtools.media_to_pic(event, reply)\n if output[1] is None:\n return await edit_delete(\n output[0], \"__Unable to extract image from the replied message.__\"\n )\n meme_file = convert_toimage(output[1])\n if output[2] in [\"Round Video\", \"Gif\", \"Sticker\", \"Video\"]:\n jisanidea = True\n try:\n cod = Get(cod)\n await event.client(cod)\n except BaseException:\n pass\n outputfile = (\n os.path.join(\"./temp\", \"solarize.webp\")\n if jisanidea\n else os.path.join(\"./temp\", \"solarize.jpg\")\n )\n await solarize(meme_file, outputfile)\n await event.client.send_file(\n event.chat_id, outputfile, force_document=False, reply_to=codid\n )\n await output[0].delete()\n for files in (outputfile, meme_file):\n if files and os.path.exists(files):\n os.remove(files)\n\n\n@codex.cod_cmd(\n pattern=\"mirror$\",\n command=(\"mirror\", plugin_category),\n info={\n \"header\": \"shows you the reflection of the media file.\",\n \"usage\": \"{tr}mirror\",\n },\n)\nasync def memes(event):\n \"shows you the reflection of the media file\"\n reply = await event.get_reply_message()\n if not reply:\n return await edit_delete(event, \"`Reply to supported Media...`\")\n cod = base64.b64decode(\"QUFBQUFGRV9vWjVYVE5fUnVaaEtOdw==\")\n codid = await reply_id(event)\n if not os.path.isdir(\"./temp\"):\n os.mkdir(\"./temp\")\n jisanidea = None\n output = await _codtools.media_to_pic(event, reply)\n if output[1] is None:\n return await edit_delete(\n output[0], \"__Unable to extract image from the replied message.__\"\n )\n meme_file = convert_toimage(output[1])\n if output[2] in [\"Round Video\", \"Gif\", \"Sticker\", \"Video\"]:\n jisanidea = True\n try:\n cod = Get(cod)\n await event.client(cod)\n except BaseException:\n pass\n outputfile = (\n os.path.join(\"./temp\", \"mirror_file.webp\")\n if jisanidea\n else os.path.join(\"./temp\", \"mirror_file.jpg\")\n )\n await mirror_file(meme_file, outputfile)\n await event.client.send_file(\n event.chat_id, outputfile, force_document=False, reply_to=codid\n )\n await output[0].delete()\n for files in (outputfile, meme_file):\n if files and os.path.exists(files):\n os.remove(files)\n\n\n@codex.cod_cmd(\n pattern=\"flip$\",\n command=(\"flip\", plugin_category),\n info={\n \"header\": \"shows you the upside down image of the given media file.\",\n \"usage\": \"{tr}flip\",\n },\n)\nasync def memes(event):\n \"shows you the upside down image of the given media file\"\n reply = await event.get_reply_message()\n if not reply:\n return await edit_delete(event, \"`Reply to supported Media...`\")\n cod = base64.b64decode(\"QUFBQUFGRV9vWjVYVE5fUnVaaEtOdw==\")\n codid = await reply_id(event)\n if not os.path.isdir(\"./temp\"):\n os.mkdir(\"./temp\")\n jisanidea = None\n output = await _codtools.media_to_pic(event, reply)\n if output[1] is None:\n return await edit_delete(\n output[0], \"__Unable to extract image from the replied message.__\"\n )\n meme_file = convert_toimage(output[1])\n if output[2] in [\"Round Video\", \"Gif\", \"Sticker\", \"Video\"]:\n jisanidea = True\n try:\n cod = Get(cod)\n await event.client(cod)\n except BaseException:\n pass\n outputfile = (\n os.path.join(\"./temp\", \"flip_image.webp\")\n if jisanidea\n else os.path.join(\"./temp\", \"flip_image.jpg\")\n )\n await flip_image(meme_file, outputfile)\n await event.client.send_file(\n event.chat_id, outputfile, force_document=False, reply_to=codid\n )\n await output[0].delete()\n for files in (outputfile, meme_file):\n if files and os.path.exists(files):\n os.remove(files)\n\n\n@codex.cod_cmd(\n pattern=\"gray$\",\n command=(\"gray\", plugin_category),\n info={\n \"header\": \"makes your media file to black and white.\",\n \"usage\": \"{tr}gray\",\n },\n)\nasync def memes(event):\n \"makes your media file to black and white\"\n reply = await event.get_reply_message()\n if not reply:\n return await edit_delete(event, \"`Reply to supported Media...`\")\n cod = base64.b64decode(\"QUFBQUFGRV9vWjVYVE5fUnVaaEtOdw==\")\n codid = await reply_id(event)\n if not os.path.isdir(\"./temp\"):\n os.mkdir(\"./temp\")\n jisanidea = None\n output = await _codtools.media_to_pic(event, reply)\n if output[1] is None:\n return await edit_delete(\n output[0], \"__Unable to extract image from the replied message.__\"\n )\n meme_file = convert_toimage(output[1])\n if output[2] in [\"Round Video\", \"Gif\", \"Sticker\", \"Video\"]:\n jisanidea = True\n try:\n cod = Get(cod)\n await event.client(cod)\n except BaseException:\n pass\n outputfile = (\n os.path.join(\"./temp\", \"grayscale.webp\")\n if jisanidea\n else os.path.join(\"./temp\", \"grayscale.jpg\")\n )\n await grayscale(meme_file, outputfile)\n await event.client.send_file(\n event.chat_id, outputfile, force_document=False, reply_to=codid\n )\n await output[0].delete()\n for files in (outputfile, meme_file):\n if files and os.path.exists(files):\n os.remove(files)\n\n\n@codex.cod_cmd(\n pattern=\"zoom ?([\\s\\S]*)\",\n command=(\"zoom\", plugin_category),\n info={\n \"header\": \"zooms your media file,\",\n \"usage\": [\"{tr}zoom\", \"{tr}zoom range\"],\n },\n)\nasync def memes(event):\n \"zooms your media file.\"\n codinput = event.pattern_match.group(1)\n codinput = 50 if not codinput else int(codinput)\n reply = await event.get_reply_message()\n if not reply:\n return await edit_delete(event, \"`Reply to supported Media...`\")\n cod = base64.b64decode(\"QUFBQUFGRV9vWjVYVE5fUnVaaEtOdw==\")\n codid = await reply_id(event)\n if not os.path.isdir(\"./temp\"):\n os.mkdir(\"./temp\")\n jisanidea = None\n output = await _codtools.media_to_pic(event, reply)\n if output[1] is None:\n return await edit_delete(\n output[0], \"__Unable to extract image from the replied message.__\"\n )\n meme_file = convert_toimage(output[1])\n if output[2] in [\"Round Video\", \"Gif\", \"Sticker\", \"Video\"]:\n jisanidea = True\n try:\n cod = Get(cod)\n await event.client(cod)\n except BaseException:\n pass\n outputfile = (\n os.path.join(\"./temp\", \"zoomimage.webp\")\n if jisanidea\n else os.path.join(\"./temp\", \"zoomimage.jpg\")\n )\n try:\n await crop(meme_file, outputfile, codinput)\n except Exception as e:\n return await output[0].edit(f\"`{e}`\")\n try:\n await event.client.send_file(\n event.chat_id, outputfile, force_document=False, reply_to=codid\n )\n except Exception as e:\n return await output[0].edit(f\"`{e}`\")\n await output[0].delete()\n for files in (outputfile, meme_file):\n if files and os.path.exists(files):\n os.remove(files)\n\n\n@codex.cod_cmd(\n pattern=\"frame ?([\\s\\S]*)\",\n command=(\"frame\", plugin_category),\n info={\n \"header\": \"make a frame for your media file.\",\n \"fill\": \"This defines the pixel fill value or color value to be applied. The default value is 0 which means the color is black.\",\n \"usage\": [\"{tr}frame\", \"{tr}frame range\", \"{tr}frame range ; fill\"],\n },\n)\nasync def memes(event):\n \"make a frame for your media file\"\n codinput = event.pattern_match.group(1)\n if not codinput:\n codinput = \"50\"\n if \";\" in str(codinput):\n codinput, colr = codinput.split(\";\", 1)\n else:\n colr = 0\n codinput = int(codinput)\n try:\n colr = int(colr)\n except Exception as e:\n return await edit_delete(event, f\"**Error**\\n`{e}`\")\n reply = await event.get_reply_message()\n if not reply:\n return await edit_delete(event, \"`Reply to supported Media...`\")\n cod = base64.b64decode(\"QUFBQUFGRV9vWjVYVE5fUnVaaEtOdw==\")\n codid = await reply_id(event)\n if not os.path.isdir(\"./temp\"):\n os.mkdir(\"./temp\")\n jisanidea = None\n output = await _codtools.media_to_pic(event, reply)\n if output[1] is None:\n return await edit_delete(\n output[0], \"__Unable to extract image from the replied message.__\"\n )\n meme_file = convert_toimage(output[1])\n if output[2] in [\"Round Video\", \"Gif\", \"Sticker\", \"Video\"]:\n jisanidea = True\n try:\n cod = Get(cod)\n await event.client(cod)\n except BaseException:\n pass\n outputfile = (\n os.path.join(\"./temp\", \"framed.webp\")\n if jisanidea\n else os.path.join(\"./temp\", \"framed.jpg\")\n )\n try:\n await add_frame(meme_file, outputfile, codinput, colr)\n except Exception as e:\n return await output[0].edit(f\"`{e}`\")\n try:\n await event.client.send_file(\n event.chat_id, outputfile, force_document=False, reply_to=codid\n )\n except Exception as e:\n return await output[0].edit(f\"`{e}`\")\n await event.delete()\n await output[0].delete()\n for files in (outputfile, meme_file):\n if files and os.path.exists(files):\n os.remove(files)\n","sub_path":"usercodex/plugins/memify.py","file_name":"memify.py","file_ext":"py","file_size_in_byte":20506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"590349028","text":"#Initialize list of five students\nstudentsList = [\"Sandra Dee\",\n \"Johnny Appleseed\",\n \"James Kirk\",\n \"Quentin Florentino\",\n \"Ronald Weasley\"]\n\n#Initialize variables for student grades to compute\ngradeList = []\nstudentGradeTotal = 0\nstudentGradeAvg = 0\n\n#Print opening statement \nprint(\"Please input the grades for the following students\")\n\n#Iterate through list of students\nfor student in studentsList:\n print(\"Enter the grade for\",student)\n #Prompt user to input grade for each student as it loops\n studentGrade = float(input())\n #Add each grade to a new list\n gradeList.append(studentGrade)\n studentGradeTotal += studentGrade\n\n#Take the student grade total and divide by the number of students for the average\nstudentGradeAvg = round((studentGradeTotal / 5),1)\n\n#Convert average to string and print the result to the screen\nprint(\"The average grade for all five students is \" +\n str(studentGradeAvg) + \"%, and the \\n\" +\n \"highest grade was \" + str(max(gradeList)) + \"%.\")\n \n \n","sub_path":"Assignment4/Assignment4.py","file_name":"Assignment4.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"122343126","text":"import numpy as np\nimport scipy.signal\nimport Pypsy.signal.utilities\nimport Pypsy.signal.analysis\n\n__author__ = 'Brennon Bortz'\n\n\nclass Signal(object):\n \"\"\"\n `Signal` represents a basic signal and timestamps for this signal.\n\n Parameters\n ----------\n data : :py:class:`numpy.ndarray`\n The signal's data. ``data[x]`` is the value of the signal at ``time[x]``.\n time : :py:class:`numpy.ndarray`\n The times (in seconds) at which the signal was sampled. ``time[x]`` is the time at which the measure of the\n signal at ``data[x]`` was taken.\n\n Attributes\n ----------\n data : :py:class:`numpy.ndarray`\n The signal's data. ``data[x]`` is the value of the signal at ``time[x]``.\n time : :py:class:`numpy.ndarray`\n The times (in seconds) at which the signal was sampled. ``time[x]`` is the time at which the measure of the\n signal at ``data[x]`` was taken.\n original_data : :py:class:`numpy.ndarray`\n The data with which the signal was originally instantiated\n original_time : :py:class:`numpy.ndarray`\n The times (in seconds) at which the signal was sampled with which the signal was originally instantiated\n\n Raises\n ------\n ValueError\n If ``data`` and ``time`` are not the same length\n TypeError\n If either of ``time`` or ``data`` are not array-like (cannot be converted to a :py:class:`numpy.ndarray` using\n :py:meth:`numpy.array()`)\n\n Examples\n --------\n >>> data = [0, 1, 2]\n >>> time = [0.0, 0.1, 0.2]\n >>> sig = Signal(data, time)\n >>> sig.data.tolist() == data\n True\n >>> sig.time.tolist() == time\n True\n\n >>> sig.data[0] = 15\n >>> sig.data.tolist()\n [15.0, 1.0, 2.0]\n >>> sig.original_data.tolist() == data\n True\n\n >>> Signal(data, time[:-1])\n Traceback (most recent call last):\n ...\n ValueError: data and time must be the same length.\n\n >>> Signal(data, None)\n Traceback (most recent call last):\n ...\n ValueError: data and time must be the same length.\n \"\"\"\n\n data = np.array([])\n time = np.array([])\n\n def __init__(self, data, time):\n data = np.asarray(data, dtype=np.float64)\n time = np.asarray(time, dtype=np.float64)\n\n # data and time must be the same length\n if data.size != time.size:\n raise ValueError('data and time must be the same length.')\n\n # Store original copy of data and time, and working copies\n self.data = np.array(data)\n self.time = np.array(time)\n self.original_data = np.array(data)\n self.original_time = np.array(time)\n\n\nclass EDASignal(Signal):\n \"\"\"\n `EDASignal` represents an electrodermal activity signal. It includes facilities for the decomposition of\n electrodermal activity into its tonic and phasic components. These facilities are a port of Ledalab from\n `Ledalab `_ from MATLAB.\n\n Parameters\n ----------\n data : :py:class:`numpy.ndarray`\n The signal's data. ``data[x]`` is the value of the signal at ``time[x]``.\n time : :py:class:`numpy.ndarray`\n The times (in seconds) at which the signal was sampled. ``time[x]`` is the time at which the measure of the\n signal at ``data[x]`` was taken.\n\n Attributes\n ----------\n phasic_data : :py:class:`numpy.ndarray`\n The phasic EDA component. This array is populated by :py:meth:`Pypsy.signal.EDASignal.decompose_signal`.\n phasic_driver : :py:class:`numpy.ndarray`\n The driver of the phasic EDA component. This array is populated by\n :py:meth:`Pypsy.signal.EDASignal.decompose_signal`\n tau : :py:class:`numpy.ndarray`\n The :math:`\\\\tau_1` and :math:`\\\\tau_2` parameters used to decompose the signal. These parameters are initially\n :math:`\\\\tau_1 = 1` and :math:`\\\\tau_2 = 3.75`, and are automatically adjusted when\n :py:meth:`Pypsy.signal.EDASignal.decompose_signal` is called with ``optimize=True``.\n tonic_data : :py:class:`numpy.ndarray`\n The tonic EDA component. This array is populated by :py:meth:`Pypsy.signal.EDASignal.decompose_signal`.\n tonic_driver : :py:class:`numpy.ndarray`\n The driver of the tonic EDA component. This array is populated by\n :py:meth:`Pypsy.signal.EDASignal.decompose_signal`.\n\n Examples\n --------\n >>> data = [1, 2, 3]\n >>> time = [0.1, 0.2, 0.3]\n >>> sig = EDASignal(data, time)\n >>> sig.data\n array([ 1., 2., 3.])\n >>> sig.time\n array([ 0.1, 0.2, 0.3])\n \"\"\"\n\n def __init__(self, data, time):\n super().__init__(data, time)\n\n self.composite_driver = np.array([], dtype=np.float64)\n self.composite_driver_remainder = np.array([], dtype=np.float64)\n self.kernel = np.array([], dtype=np.float64)\n self.phasic_data = np.array([], dtype=np.float64)\n self.phasic_driver = np.array([], dtype=np.float64)\n self.phasic_driver_raw = np.array([], dtype=np.float64)\n self.tau = np.array([1., 3.75])\n self.tonic_data = np.array([], dtype=np.float64)\n self.tonic_driver = np.array([], dtype=np.float64)\n self.error = dict()\n self.error['mse'] = None\n self.error['rmse'] = None\n self.error['discreteness'] = None\n self.error['negativity'] = None\n self.error['compound'] = None\n\n def decompose_signal(self, optimize=False):\n \"\"\"\n Decompose the EDA signal into its tonic and phasic components. This decomposition is identical to the continuous\n analysis performed by `Ledalab `_.\n\n Parameters\n ----------\n optimize : bool\n When ``True``, the parameters in ``self.tau`` are optimized to minimize error. When ``False``, the current\n values of ``self.tau`` are used for decomposition.\n \n Examples\n --------\n >>> sig = EDASignal.from_file('tests/test_not_decomposed.eda_signal')\n >>> sig.decompose_signal(optimize=False)\n >>> saved = EDASignal.from_file('tests/test_decomposed_unoptimized.eda_signal')\n >>> np.all(sig.composite_driver == saved.composite_driver)\n True\n >>> np.all(sig.composite_driver_remainder == saved.composite_driver_remainder)\n True\n >>> np.all(sig.data == saved.data)\n True\n >>> np.all(sig.kernel == saved.kernel)\n True\n >>> np.all(sig.phasic_data == saved.phasic_data)\n True\n >>> np.all(sig.phasic_driver == saved.phasic_driver)\n True\n >>> np.all(sig.phasic_driver_raw == saved.phasic_driver_raw)\n True\n >>> np.all(sig.tau == saved.tau)\n True\n >>> np.all(sig.time == saved.time)\n True\n >>> np.all(sig.tonic_data == saved.tonic_data)\n True\n >>> np.all(sig.tonic_driver == saved.tonic_driver)\n True\n >>> sig.error['mse'] == saved.error['mse']\n True\n >>> sig.error['rmse'] == saved.error['rmse']\n True\n >>> sig.error['discreteness'] == saved.error['discreteness']\n True\n >>> sig.error['negativity'] == saved.error['negativity']\n True\n >>> sig.error['compound'] == saved.error['compound']\n True\n\n >>> sig = EDASignal.from_file('tests/test_not_decomposed.eda_signal')\n >>> sig.decompose_signal(optimize=True)\n >>> saved = EDASignal.from_file('tests/test_decomposed_optimized.eda_signal')\n >>> np.all(sig.composite_driver == saved.composite_driver)\n True\n >>> np.all(sig.composite_driver_remainder == saved.composite_driver_remainder)\n True\n >>> np.all(sig.data == saved.data)\n True\n >>> np.all(sig.kernel == saved.kernel)\n True\n >>> np.all(sig.phasic_data == saved.phasic_data)\n True\n >>> np.all(sig.phasic_driver == saved.phasic_driver)\n True\n >>> np.all(sig.phasic_driver_raw == saved.phasic_driver_raw)\n True\n >>> np.all(sig.tau == saved.tau)\n True\n >>> np.all(sig.time == saved.time)\n True\n >>> np.all(sig.tonic_data == saved.tonic_data)\n True\n >>> np.all(sig.tonic_driver == saved.tonic_driver)\n True\n >>> sig.error['mse'] == saved.error['mse']\n True\n >>> sig.error['rmse'] == saved.error['rmse']\n True\n >>> sig.error['discreteness'] == saved.error['discreteness']\n True\n >>> sig.error['negativity'] == saved.error['negativity']\n True\n >>> sig.error['compound'] == saved.error['compound']\n True\n \"\"\"\n\n import Pypsy.optimization\n\n if optimize:\n x, history = Pypsy.optimization.cgd(self.tau, self._decompose, np.array([.3, 2]), .01, 20, .05)\n else:\n self._decompose(self.tau)\n\n def _decompose(self, tau):\n \"\"\"\n Decompose the EDA signal into its tonic and phasic components using the specified :math:`\\\\tau_1` and\n :math:`\\\\tau_2` in ``tau``. This decomposition is identical to the continuous analysis performed by\n `Ledalab `_.\n\n Parameters\n ----------\n tau : array_like\n :math:`\\\\tau_1` should be at ``tau[0]`` and :math:`\\\\tau_2` should be at ``tau[1]``.\n\n Raises\n ------\n TypeError\n If either of ``tau`` is not array-like (cannot be converted to a :py:class:`numpy.ndarray` using\n :py:meth:`numpy.array()`)\n \"\"\"\n\n tau = np.asarray(tau)\n\n # Ensure that parameters are within limits\n tau[0] = Pypsy.constrain(tau[0], .001, 10)\n tau[1] = Pypsy.constrain(tau[1], .001, 20)\n\n if tau[1] < tau[0]:\n tau = tau[::-1]\n\n if np.abs(tau[0] - tau[1]) < .01:\n\n # FIXME: Shouldn't this be tau[1] = tau[0] + .01\n tau[1] = tau[1] + .01\n\n # Resample at 25Hz\n Pypsy.signal.utilities.resample_signal(self, 25.0)\n\n d = self.data.copy()\n t = self.time.copy() # Set in MATLAB as leda2.analysis0.target.t\n\n # FIXME: Sample rate should be calculated\n sr = 25. # Set in MATLAB as leda2.analysis0.target.sr\n smoothwin = 1.6 # Set in MATLAB as leda2.analysis0.smoothwin * 8\n dt = 1./sr\n winwidth_max = 3\n swin = np.round(np.min(np.array([smoothwin, winwidth_max]) * sr))\n\n # Data preparation\n\n # Set tb to be original timestamps, shifted to zero, and adding one\n # timestep\n tb = t - t[0] + dt\n\n # Get a smoothed Bateman output with predefined parameters\n bg = Pypsy.signal.analysis.bateman_gauss(tb, 5, 1, 2, 40, .4)\n\n # Get the index of the max of the Bateman output\n idx = np.argmax(bg)\n\n # prefix is Bateman output up to one beyond the max, normalized by the\n # value at one beyond the max, and then multiplied by the first value in\n # the EDA vector\n prefix = (bg[0:idx+1] / bg[idx+1]) * d[0]\n\n # Remove any zero values from prefix\n # prefix = nonzeros(prefix);\n prefix = prefix[np.nonzero(prefix)]\n\n # n_prefix is the length of the prefix vector\n n_prefix = prefix.size\n\n # Prepend prefix to skin conductance vector\n d_ext = np.concatenate([prefix, d])\n\n # Append a n_prefix length vector of negative timepoints leading up to 0 to\n # t (negative timesteps running the duration of the prefix we added to the\n # EDA vector)\n # start = t[0] - dt\n # end = t[0] - (n_prefix * dt)\n # count = np.int64(np.abs(start - end) / dt)\n # t_ext = np.linspace(start, end, num=count)\n t_ext = np.arange(t[0] - dt, t[0] - n_prefix * dt, -dt)\n t_ext = t_ext[::-1]\n t_ext = np.concatenate([t_ext, t])\n\n # Redefine tb as above but now with prefixed timestamps\n tb = t_ext - t_ext[0] + dt\n\n # Define initial taus\n tau1 = tau[0]\n tau2 = tau[1]\n\n # kernel is a smoothed Bateman output using our tb timestamps, onset of 0,\n # an amplitude of zero (the amplitude is scaled in this case within\n # bateman.m), the user-provided taus, and a standard deviation for the\n # Gaussian window of 0\n kernel = Pypsy.signal.analysis.bateman_gauss(tb, 0, 0, tau1, tau2, 0)\n\n # Adaptive kernel size\n # Find the index of the maximum amplitude of the kernel\n midx = np.argmax(kernel)\n\n # Subset kernel vector from the index after the max amplitude to the end\n kernelaftermx = kernel[midx:]\n\n # Put these two pieces back together, but only keeping the tail up to the\n # point that it falls below 10e-05\n kernel_start = kernel[0:midx+1]\n kernel_end = kernelaftermx[kernelaftermx > .00001]\n kernel = np.concatenate([kernel_start, kernel_end])\n\n # Normalize vector such that its entries sum to 1\n kernel = kernel / np.sum(kernel)\n\n # Set the value of a 'significant' peak in EDA\n # The second value in this max is hardcoded into Ledalab and is\n # leda2.set.sigPeak/max(kernel)*10\n sigc = np.max([.1, .001 / np.max(kernel) * 10])\n\n # ESTIMATE TONIC\n\n # Deconvolve the kernel from the prefixed data. The last entry in this data\n # vector is repeated for the duration of the kernel vector. The result of\n # this deconvultion is the tonic driver function.\n extended_d_ext = np.concatenate([d_ext, d_ext[-1] * np.ones(kernel.size)])\n driverSC, remainderSC = scipy.signal.deconvolve(extended_d_ext, kernel)\n\n # Smooth the driver function with a Gaussian\n driverSC_smooth = Pypsy.signal.utilities.smooth(driverSC, swin, 'gauss')\n\n # Remove prefix from driver, smoothed driver, and remainder. Also trim tail\n # of remainder.\n driverSC = driverSC[n_prefix:d.size + n_prefix]\n driverSC_smooth = driverSC_smooth[n_prefix:d.size + n_prefix]\n remainderSC = remainderSC[n_prefix:d.size + n_prefix]\n\n # Segment driver sections (hardcoded 12 is from leda2.set.segmWidth)\n onset_idx, impulse, overshoot, impMin, impMax = Pypsy.signal.analysis.segment_driver(\n driverSC_smooth,\n np.zeros(driverSC_smooth.size),\n sigc,\n np.round(sr * 12)\n )\n\n # Estimate tonic\n tonic_driver, tonic_data = Pypsy.signal.analysis.interimpulse_fit(driverSC_smooth, kernel, impMin, impMax, t, d, 25.)\n\n # Build tonic and phasic data\n phasic_data = d - tonic_data\n phasicDriverRaw = driverSC - tonic_driver\n phasicDriver = Pypsy.signal.utilities.smooth(phasicDriverRaw, swin, 'gauss')\n\n # Compute model error\n\n ### Have excluded a number of measures of error that can be brought over\n ### from Ledalab\n # err1d = deverror(phasicDriver, [0, .2]);\n\n # succnz here returns a the ratio of driver instance greater than a criterion\n # value to the entire signal\n err1s = Pypsy.signal.utilities.nonzero_portion(phasicDriver, max(.01, max(phasicDriver) / 20.), 2., sr)\n\n # Get the negative portion of the phasic driver\n phasicDriverNeg = phasicDriver.copy()\n phasicDriverNeg[phasicDriverNeg > 0] = 0\n\n # Compute measures of discreteness (chunks of non-zero data) and negativity\n err_discreteness = err1s\n err_negativity = np.sqrt(np.mean(phasicDriverNeg**2))\n\n # Hardcoded alpha (in MATLAB)\n alpha = 5.\n # Main error measure\n err = err_discreteness + err_negativity * alpha\n\n # Other error measures\n err_MSE = Pypsy.signal.analysis.fit_error(self.data, tonic_data + phasic_data, 0, 'MSE')\n err_RMSE = np.sqrt(err_MSE)\n\n # Save results\n self.tau = np.array([tau1, tau2])\n self.phasic_driver = phasicDriver\n self.tonic_driver = tonic_driver\n self.composite_driver = driverSC_smooth\n self.composite_driver_remainder = remainderSC\n self.kernel = kernel\n self.phasic_data = phasic_data\n self.tonic_data = tonic_data\n self.phasic_driver_raw = phasicDriverRaw\n\n self.error['mse'] = err_MSE\n self.error['rmse'] = err_RMSE\n self.error['discreteness'] = err_discreteness\n self.error['negativity'] = err_negativity\n self.error['compound'] = err\n # self.chi2 = err_chi2;\n # self.deviation = [err1d, 0];\n\n return err, tau\n\n def to_file(self, path):\n \"\"\"\n Serializes an ``EDASignal`` in a file stored at ``path``.\n\n Parameters\n ----------\n path : str\n The path at which to store the serialized signal.\n\n Examples\n --------\n >>> data = np.random.rand(2)\n >>> time = np.array([0.1, 0.2])\n >>> e = EDASignal(data, time)\n >>> e.composite_driver = np.random.rand(2)\n >>> e.composite_driver_remainder = np.random.rand(2)\n >>> e.data = np.random.rand(2)\n >>> e.kernel = np.random.rand(2)\n >>> e.phasic_data = np.random.rand(2)\n >>> e.phasic_driver = np.random.rand(2)\n >>> e.phasic_driver_raw = np.random.rand(2)\n >>> e.tau = np.random.rand(2)\n >>> e.time = np.random.rand(2)\n >>> e.tonic_data = np.random.rand(2)\n >>> e.tonic_driver = np.random.rand(2)\n >>> e.error['mse'] = np.random.rand()\n >>> e.error['rmse'] = np.random.rand()\n >>> e.error['discreteness'] = np.random.rand()\n >>> e.error['negativity'] = np.random.rand()\n >>> e.error['compound'] = np.random.rand()\n >>> e.to_file('tests/test.eda_signal')\n >>> e1 = EDASignal.from_file('tests/test.eda_signal')\n >>> np.all(e.composite_driver == e1.composite_driver)\n True\n >>> np.all(e.composite_driver_remainder == e1.composite_driver_remainder)\n True\n >>> np.all(e.data == e1.data)\n True\n >>> np.all(e.kernel == e1.kernel)\n True\n >>> np.all(e.phasic_data == e1.phasic_data)\n True\n >>> np.all(e.phasic_driver == e1.phasic_driver)\n True\n >>> np.all(e.phasic_driver_raw == e1.phasic_driver_raw)\n True\n >>> np.all(e.tau == e1.tau)\n True\n >>> np.all(e.time == e1.time)\n True\n >>> np.all(e.tonic_data == e1.tonic_data)\n True\n >>> np.all(e.tonic_driver == e1.tonic_driver)\n True\n >>> e.error['mse'] == e1.error['mse']\n True\n >>> e.error['rmse'] == e1.error['rmse']\n True\n >>> e.error['discreteness'] == e1.error['discreteness']\n True\n >>> e.error['negativity'] == e1.error['negativity']\n True\n >>> e.error['compound'] == e1.error['compound']\n True\n \"\"\"\n import pickle\n\n # Create dict of signal object\n out_dict = dict()\n\n out_dict['composite_driver'] = self.composite_driver\n out_dict['composite_driver_remainder'] = self.composite_driver_remainder\n out_dict['data'] = self.data\n out_dict['kernel'] = self.kernel\n out_dict['tau'] = self.tau\n out_dict['phasic_data'] = self.phasic_data\n out_dict['phasic_driver'] = self.phasic_driver\n out_dict['phasic_driver_raw'] = self.phasic_driver_raw\n out_dict['time'] = self.time\n out_dict['tonic_data'] = self.tonic_data\n out_dict['tonic_driver'] = self.tonic_driver\n\n out_dict['error'] = dict()\n out_dict['error']['mse'] = self.error['mse']\n out_dict['error']['rmse'] = self.error['rmse']\n out_dict['error']['discreteness'] = self.error['discreteness']\n out_dict['error']['negativity'] = self.error['negativity']\n out_dict['error']['compound'] = self.error['compound']\n\n with open(path, 'wb') as out_file:\n pickle.dump(out_dict, out_file, pickle.HIGHEST_PROTOCOL)\n\n\n @classmethod\n def from_file(cls, path):\n \"\"\"\n Deserializes an ``EDASignal`` from the file at ``path``.\n\n Parameters\n ----------\n path : str\n A path to the file at which an ``EDASignal`` was serialized using\n :py:meth:`Pypsy.signal.EDASignal.to_file()`\n\n Returns\n -------\n out : :py:class:`Pypsy.signal.EDASignal`\n An instantiated ``EDASignal``\n\n Raises\n ------\n FileNotFoundError\n If no file exists at ``path``\n RuntimeError\n If the file at ``path`` does not contain a valid ``EDASignal``\n\n Examples\n --------\n >>> sig = EDASignal.from_file('tests/test.eda_signal')\n >>> type(sig)\n \n\n >>> EDASignal.from_file('tests/__init__.py')\n Traceback (most recent call last):\n ...\n RuntimeError: No valid signal found in 'tests/__init__.py'\n\n >>> EDASignal.from_file('tests/nonexistent.eda_signal')\n Traceback (most recent call last):\n ...\n FileNotFoundError: [Errno 2] No such file or directory: 'tests/nonexistent.eda_signal'\n \"\"\"\n\n import pickle\n\n # Deserialize signal\n with open(path, 'rb') as in_file:\n try:\n in_dict = pickle.load(in_file)\n except:\n raise RuntimeError('No valid signal found in %r' % path)\n\n # Initialize the signal\n out_signal = EDASignal(in_dict['data'], in_dict['time'])\n\n # Set attribute values\n out_signal.composite_driver = in_dict['composite_driver']\n out_signal.composite_driver_remainder = in_dict['composite_driver_remainder']\n out_signal.data = in_dict['data']\n out_signal.kernel = in_dict['kernel']\n out_signal.tau = in_dict['tau']\n out_signal.phasic_data = in_dict['phasic_data']\n out_signal.phasic_driver = in_dict['phasic_driver']\n out_signal.phasic_driver_raw = in_dict['phasic_driver_raw']\n out_signal.time = in_dict['time']\n out_signal.tonic_data = in_dict['tonic_data']\n out_signal.tonic_driver = in_dict['tonic_driver']\n\n out_signal.error['mse'] = in_dict['error']['mse']\n out_signal.error['rmse'] = in_dict['error']['rmse']\n out_signal.error['discreteness'] = in_dict['error']['discreteness']\n out_signal.error['negativity'] = in_dict['error']['negativity']\n out_signal.error['compound'] = in_dict['error']['compound']\n\n return out_signal\n\n","sub_path":"Pypsy/signal/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":22463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"440556299","text":"\"\"\"Your awesome Distance Vector router for CS 168.\"\"\"\n\nimport sim.api as api\nimport sim.basics as basics\n\n# We define infinity as a distance of 16.\nINFINITY = 16\n\nHOST = 0\nROUTER = 1\n\nclass DVRouter(basics.DVRouterBase):\n # NO_LOG = True # Set to True on an instance to disable its logging\n POISON_MODE = True # Can override POISON_MODE here\n # DEFAULT_TIMER_INTERVAL = 5 # Can override this yourself for testing\n\n class RoutingTableEntry():\n def __init__(self, port, entity_type, latency):\n self.port = port\n self.entity_type = entity_type\n self.latency = latency\n self.last_updated = api.current_time()\n\n def __init__(self):\n \"\"\"\n Called when the instance is initialized.\n\n You probably want to do some additional initialization here.\n\n \"\"\"\n # \"destination: RoutingTableEntry()\"\n self.routingTable = {}\n # mapping of (port, latency)\n self.linkLatencies = {}\n self.start_timer() # Starts calling handle_timer() at correct rate\n\n def handle_link_up(self, port, latency):\n \"\"\"\n Called by the framework when a link attached to this Entity goes up.\n\n The port attached to the link and the link latency are passed\n in.\n\n \"\"\"\n # send all routes to new neighbors here to let them know we exist\n # send routingPacket to PORT; then handle_rx will be called to handle HostPacket from hosts\n # we learn about what ports are available after this call\n self.linkLatencies[port] = latency\n # sending all your routes to the new neighbor directly in handle_link_up\n for destination in self.routingTable:\n self.send(basics.RoutePacket(destination, self.routingTable[destination].latency), \n port=port, \n flood=False)\n\n def handle_link_down(self, port):\n \"\"\"\n Called by the framework when a link attached to this Entity does down.\n\n The port number used by the link is passed in.\n\n \"\"\"\n if port in self.linkLatencies.keys():\n self.linkLatencies[port] = INFINITY\n # modify all paths that use affected node\n for destination in self.routingTable.keys():\n if self.routingTable[destination].port == port:\n self.send_poison(destination)\n del self.routingTable[destination]\n \n def update_table(self, destination, port, entity_type, latency):\n self.routingTable[destination] = self.RoutingTableEntry(port, entity_type, latency)\n self.send(basics.RoutePacket(destination, latency), port=port, flood=True)\n\n def handle_rx(self, packet, port):\n \"\"\"\n Called by the framework when this Entity receives a packet.\n\n packet is a Packet (or subclass).\n port is the port number it arrived on.\n\n You definitely want to fill this in.\n\n \"\"\"\n #self.log(\"RX %s on %s (%s)\", packet, port, api.current_time())\n if isinstance(packet, basics.RoutePacket):\n destination = packet.destination\n new_latency = packet.latency + self.linkLatencies[port]\n\n if destination not in self.routingTable.keys():\n self.update_table(destination, port, ROUTER, new_latency)\n return\n\n rt_entry = self.routingTable[destination]\n old_latency = rt_entry.latency\n \n if old_latency > new_latency:\n self.update_table(destination, port, ROUTER, new_latency)\n return\n \n if port == rt_entry.port:\n if new_latency >= INFINITY and self.POISON_MODE:\n self.send_poison(destination)\n del self.routingTable[destination]\n else:\n # only refreshes timer; don't send -- split horizon\n rt_entry.last_updated = api.current_time()\n\n elif isinstance(packet, basics.HostDiscoveryPacket):\n latency = self.linkLatencies[port]\n self.update_table(packet.src, port, HOST, latency)\n else:\n # drop unseen destination\n if packet.dst not in self.routingTable.keys():\n return\n \n rt_entry = self.routingTable[packet.dst]\n if rt_entry.latency >= INFINITY:\n return\n else:\n bestPort = rt_entry.port\n if bestPort != port:\n self.send(packet, port=bestPort, flood=False)\n\n def has_expired(self, last_updated):\n return api.current_time() - last_updated > self.ROUTE_TIMEOUT\n\n def remove_expired_ports(self):\n for destination in self.routingTable.keys():\n rt_entry = self.routingTable[destination]\n # only keep active \"hosts\" in router's table for efficient forwarding\n if rt_entry.entity_type == ROUTER and self.has_expired(rt_entry.last_updated):\n self.send_poison(destination)\n del self.routingTable[destination]\n\n def send_table_to_neighbors(self):\n for destination in self.routingTable.keys():\n latency = self.routingTable[destination].latency\n port = self.routingTable[destination].port\n self.send(basics.RoutePacket(destination, latency), port=port, flood=True)\n\n def handle_timer(self):\n \"\"\"\n Called periodically.\n\n When called, your router should send tables to neighbors. It\n also might not be a bad place to check for whether any entries\n have expired.\n\n \"\"\"\n # expires all ports whose time_now - time_last_updated > 15 seconds\n # send tables to neighbors\n self.remove_expired_ports()\n self.send_table_to_neighbors()\n\n def send_poison(self, destination):\n if self.POISON_MODE:\n self.send(basics.RoutePacket(destination, INFINITY), flood=True)\n\n","sub_path":"dv_router.py","file_name":"dv_router.py","file_ext":"py","file_size_in_byte":5966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"70646785","text":"from __future__ import division, print_function\nimport sys\nsys.path.append('.')\nsys.path.append('modules/question_generator')\nsys.path.append('modules/vocab_seq')\nfrom vocab_seq import Vocab_Seq\nimport nltk\nfrom nltk.corpus import wordnet\nimport gensim\nimport util\nfrom util.data import vg_load_annotation\nfrom collections import Counter\nimport numpy as np\nimport h5py\nimport os\n\nwnl = nltk.WordNetLemmatizer()\nstopwords = nltk.corpus.stopwords.words('english')\nstopwords = stopwords[0:stopwords.index('of')] + stopwords[(stopwords.index('under')+1)::]\n\n# 25 preposition words from 'of' to 'under'\n\npunc = Vocab_Seq.punctuations + ['\\'s']\nomitted_words = dict.fromkeys(stopwords + punc)\n\ncolor_list = dict.fromkeys(['gold', 'golden', 'blond', 'blonde', 'red', 'orange', 'yellow', 'green', 'blue', 'teal',\\\n 'purple', 'pink', 'white', 'black', 'gray', 'brown', 'beige', 'maroon', 'tan', 'khaki', 'silver', 'grey','cream',\\\n 'dark', 'clear', 'burgundy'])\nnum_list = dict.fromkeys(['one', 'two', 'three', 'four', 'five', 'six', 'seven' ,'2'])\nsynonym_list = {u'grey': u'gray', u'racquet': u'racket', u'airplane': u'plane', u'cell phone': u'cellphone', \\\n u'blond': u'blonde'}\n\n\ndef _modify_answer(qa):\n question = qa['question'].lower()\n answer_token = nltk.word_tokenize(qa['answer'].lower())\n answer_token = [wnl.lemmatize(w, wordnet.NOUN) for w in answer_token if w not in omitted_words]\n answer_token = [wnl.lemmatize(w, wordnet.VERB) for w in answer_token]\n answer_token = [wnl.lemmatize(w, wordnet.ADJ) for w in answer_token]\n answer_token = [wnl.lemmatize(w, wordnet.ADV) for w in answer_token]\n\n if 'how many' in question or ' the number of ' in question or 'what number of' in question \\\n or set(answer_token) <= set(num_list):\n if 'zero' in answer_token or 'none' in answer_token or '0' in answer_token:\n answer_token = [u'zero']\n elif 'one' in answer_token or '1' in answer_token:\n answer_token = [u'one']\n else:\n answer_token = [u'more than one']\n elif 'what color ' in question or 'what is the color ' in question or 'what colors ' in question \\\n or set(answer_token) <= set(color_list):\n color_words = [w for w in answer_token if w in color_list]\n if len(color_words) > 0:\n answer_token = color_words[0:1]\n elif 'what' in question:\n if len(answer_token) > 1:\n noun_word = [w for w in answer_token if w not in color_list and w not in num_list]\n if len(noun_word) > 0:\n answer_token = noun_word\n\n answer = ' '.join(answer_token)\n for original_word, target_word in synonym_list.iteritems():\n answer = answer.replace(original_word, target_word)\n qa['answer'] = answer\n return qa\n\ndef _get_question_type(question):\n '''\n 0: what (object)\n 1: what color\n 2: where\n 3: how many / what number\n 4: how\n 5: who\n 6: when / what time\n 7: why\n 8: what (action)\n '''\n question = question.lower()\n if question.startswith('what'):\n if 'color ' in question or 'colors ' in question:\n return 1\n elif question.startswith('what time') or 'the time' in question:\n return 6\n elif question.startswith('what number of') or 'the number of ' in question:\n return 3\n elif 'doing' in question or 'do ' in question or 'do?' in question or question.endswith('do'):\n return 8\n else:\n return 0\n elif question.startswith('where'):\n return 2\n elif question.startswith('how many'):\n return 3\n elif question.startswith('how'):\n return 4\n elif question.startswith('who'):\n return 5\n elif question.startswith('when'):\n return 6\n elif question.startswith('why'):\n return 7\n else:\n return -1\n\ndef create_answer_info():\n answer_info_file = 'data/vqg/training_data/answer_info_1.1.json'\n if os.path.isfile(answer_info_file):\n answer_info = util.io.load_json(answer_info_file)\n else:\n answer_list = util.io.load_str_list('data/vqg/training_data/answer_list_1.1.txt')\n answer_list = answer_list[0:3000]\n anno_qa, = vg_load_annotation(['qa'])\n qa_list_train = util.io.load_str_list('data/vqg/splits/vg_qa_split_train.txt')\n question_type_distribution = {a:[0,0,0,0,0,0,0,0,0,0] for a in answer_list}\n N = len(qa_list_train)\n for i, qa_id in enumerate(qa_list_train):\n qa = _modify_answer(anno_qa[qa_id])\n print('%.2f%%' % (100 * i / N))\n if qa['answer'] in question_type_distribution:\n question_type = _get_question_type(qa['question'])\n question_type_distribution[qa['answer']][question_type] += 1\n\n answer_info = []\n threshold = 0.2\n for answer in answer_list:\n qtd = question_type_distribution[answer]\n count = sum(qtd)\n qtd = [d/count for d in qtd]\n answer_type = []\n for i, d in enumerate(qtd):\n if d >= threshold:\n answer_type.append(i)\n\n answer_info.append({'answer': answer, \\\n 'count': count, \\\n 'question_type_distribution': qtd,\\\n 'answer_type': answer_type})\n\n util.io.save_json(answer_info, answer_info_file)\n\n\ndef question_type_of_answer():\n\n question_type_distribution_file = 'data/vqg/training_data/question_type_distribution.json'\n if os.path.isfile(question_type_distribution_file):\n question_type_distribution = util.io.load_json(question_type_distribution_file)\n else:\n anno_qa, = vg_load_annotation(['qa'])\n qa_list_train = util.io.load_str_list('data/vqg/splits/vg_qa_split_train.txt')\n answer_list = util.io.load_str_list('data/vqg/training_data/answer_list_1.1.txt')\n answer_list = answer_list[0:3000]\n question_type_distribution = {a:[0,0,0,0,0,0,0,0,0,0] for a in answer_list}\n N = len(qa_list_train)\n for i, qa_id in enumerate(qa_list_train):\n qa = _modify_answer(anno_qa[qa_id])\n print('%.2f%%' % (100 * i / N))\n if qa['answer'] in question_type_distribution:\n question_type = _get_question_type(qa['question'])\n question_type_distribution[qa['answer']][question_type] += 1\n\n util.io.save_json(question_type_distribution, \\\n 'data/vqg/training_data/question_type_distribution.json')\n\n answer_list = util.io.load_str_list('data/vqg/training_data/answer_list_1.1.txt')\n answer_list = answer_list[0:3000]\n output_txt = []\n\n type_count = np.zeros(9, dtype = np.float32)\n\n for answer in answer_list:\n dist = question_type_distribution[unicode(answer)]\n count = sum(dist)\n output_line = '%s\\t%d\\t' % (answer, count)\n output_line += '\\t'.join(['%.2f' % (d/count) for d in dist])\n output_txt.append(output_line)\n type_count[np.argmax(dist)] += 1\n util.io.save_str_list(output_txt, 'data/vqg/training_data/question_type_distribution.txt')\n\n print(type_count)\n\n \ndef generate_answer_data():\n anno_qa, = vg_load_annotation(['qa'])\n qa_list_train = util.io.load_str_list('data/vqg/splits/vg_qa_split_train.txt')\n qa_list_val = util.io.load_str_list('data/vqg/splits/vg_qa_split_val.txt')\n qa_list_test = util.io.load_str_list('data/vqg/splits/vg_qa_split_test.txt')\n\n timer = util.timer.Timer()\n timer.tic()\n n = 0\n N = len(anno_qa)\n for k, qa in anno_qa.iteritems():\n anno_qa[k] = _modify_answer(qa)\n n += 1\n print('%.2f%%' % (100*n/N))\n print('time: %f s' % timer.toc())\n\n answer_train = [anno_qa[qa_id]['answer'] for qa_id in qa_list_train]\n answer_val = [anno_qa[qa_id]['answer'] for qa_id in qa_list_val]\n answer_test = [anno_qa[qa_id]['answer'] for qa_id in qa_list_test]\n\n answer_counter = Counter(answer_train)\n answer_counter = answer_counter.most_common()\n answer_all, count_all = zip(*answer_counter)\n\n answer2index = {answer: idx for idx, answer in enumerate(answer_all)}\n\n count_threshold = [500, 1000, 2000, 3000]\n\n N_ = len(count_threshold)\n\n answer_train_index = np.array([[answer2index.setdefault(answer, -1)] * N_ for answer in answer_train])\n answer_val_index = np.array([[answer2index.setdefault(answer, -1)] * N_ for answer in answer_val])\n answer_test_index = np.array([[answer2index.setdefault(answer, -1)] * N_ for answer in answer_test])\n\n for i, t in enumerate(count_threshold):\n answer_train_index[answer_train_index[:,i] >= t,i] = -1\n answer_val_index[answer_val_index[:,i] >= t,i] = -1\n answer_test_index[answer_test_index[:,i] >= t,i] = -1\n\n\n data_list = [answer_train_index, answer_val_index, answer_test_index]\n data_name = ['train', 'val', 'test']\n\n for i, data in enumerate(data_list):\n h5_file = h5py.File('data/vqg/training_data/answer_1.1_%s.h5'%data_name[i], 'w')\n for j, t in enumerate(count_threshold):\n dataset = h5_file.create_dataset('answer_%d'%t, shape = data[:,j].shape, dtype = np.float32)\n dataset[:] = data[:,j]\n h5_file.close()\n\n # util.io.save_str_list(answer2index.keys()[0:max(count_threshold)], \\\n # 'data/vqg/training_data/answer_list.txt')\n util.io.save_str_list(answer_all[0:max(count_threshold)], 'data/vqg/training_data/answer_list_1.1.txt')\n\ndef add_cross_entropy_label():\n dataset = ['train', 'val', 'test']\n for set_name in dataset:\n h5_a = h5py.File('data/vqg/training_data/answer_1.1_%s.h5' % set_name, 'a')\n answer_label = h5_a['answer_1000']\n num_answer = answer_label.shape[0]\n cross_entropy_label = np.zeros((num_answer, 1000), dtype = np.float32)\n for i in xrange(num_answer):\n print('%s: %d/%d' % (set_name, i, num_answer))\n label = int(answer_label[i])\n if label >= 0:\n cross_entropy_label[i, label] = 1\n else:\n cross_entropy_label[i, :] = -1\n\n dataset = h5_a.create_dataset('cross_entropy_label', shape = cross_entropy_label.shape, dtype = np.float32)\n dataset[:] = cross_entropy_label\n h5_a.close()\n\n\ndef convert_answer_to_seq():\n dataset = ['train', 'val', 'test']\n for set_name in dataset:\n h5_q = h5py.File('data/vqg/training_data/question_seq_%s.h5'%set_name, 'r')\n h5_a = h5py.File('data/vqg/training_data/answer_1.1_%s.h5'%set_name, 'a')\n \n seq_q = h5_q['seq_input'][...].copy().astype(np.int)\n answer = h5_a['answer_3000'][...].copy().astype(np.float32)\n h5_q.close()\n # h5_a.close()\n\n assert(len(seq_q) == len(answer))\n seq_a = np.ones(seq_q.shape, dtype = np.float32) * -1\n \n seq_q[:,-1] = 7226\n seq_q = seq_q.tolist()\n for i, seq in enumerate(seq_q):\n seq_a[i, seq.index(7226)] = answer[i]\n\n # h5_a_seq = h5py.File('data/vqg/training_data/answer_seq_1.1_%s.h5'%set_name, 'w')\n\n t_list = [500, 1000, 2000, 3000]\n for t in t_list:\n data = seq_a.copy()\n data[data >= t] = -1.0\n dataset = h5_a.create_dataset('seq_answer_%d'%t, shape = data.shape, dtype = np.float32)\n dataset[:] = data\n # h5_a_seq.close()\n h5_a.close()\n\n# def create_word_embeding_in_answer_h5_without_modify():\n\ndef create_word_embedding_in_answer_h5():\n import nltk\n import gensim\n\n set_names = ['val', 'test', 'train']\n h5_profix = 'data/vqg/training_data/answer_1.1_%s.h5'\n answer_list = util.io.load_str_list('data/vqg/training_data/answer_list_1.1.txt')\n\n print('loading qa annotations')\n anno_qa, = vg_load_annotation(['qa'])\n\n print('loading word2vec model...')\n model_word2vec = gensim.models.word2vec.Word2Vec.load_word2vec_format('external/GoogleNews-vectors-negative300.bin.gz', binary=True)\n vec_size = model_word2vec.vector_size\n\n def _answer2vec(answer):\n answer_token = [w for w in nltk.word_tokenize(answer.lower())]\n vecs = [model_word2vec[w] for w in answer_token if w in model_word2vec.vocab]\n vecs = np.zeros(vec_size, dtype = np.float32) if not vecs else np.array(vecs).sum(axis = 0)\n return gensim.matutils.unitvec(vecs)\n\n # cache embedding vector of answers in answer list\n print('caching embedding for the answer list')\n vec_cache = np.zeros((len(answer_list), vec_size), dtype = np.float32)\n for i, answer in enumerate(answer_list):\n vec_cache[i] = _answer2vec(answer)\n\n\n # computing embedding vector\n for set_name in set_names:\n qa_id_list = util.io.load_str_list('data/vqg/splits/vg_qa_split_%s.txt' % set_name)\n qa_list = [anno_qa[qa_id] for qa_id in qa_id_list]\n\n h5_file = h5py.File(h5_profix % set_name, 'a')\n answer_idx = h5_file['answer_3000']\n num_answer = len(answer_idx)\n answer_vec = np.zeros((num_answer, vec_size), dtype = np.float32)\n\n for i, idx in enumerate(answer_idx):\n if i % 100 == 0:\n print('%s: %.2f%%' % (set_name, i*100/num_answer))\n if idx >= 0:\n answer_vec[i] = vec_cache[idx]\n # print('cached: ', answer_vec[i][1:10])\n else:\n qa = _modify_answer(qa_list[i])\n answer_vec[i] = _answer2vec(qa['answer'])\n # print('computed: ', answer_vec[i][1:10])\n dataset = h5_file.create_dataset('word2vec_embedding', shape = answer_vec.shape, dtype = np.float32)\n dataset[:] = answer_vec\n h5_file.close()\n\n\nif __name__ == '__main__':\n # generate_answer_data()\n # convert_answer_to_seq()\n # create_word_embedding_in_answer_h5()\n # question_type_of_answer()\n # add_cross_entropy_label()\n create_answer_info()\n ","sub_path":"modules/question_generator/create_answer_lable.py","file_name":"create_answer_lable.py","file_ext":"py","file_size_in_byte":13949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"69808795","text":"from tkinter import * \r\n\r\nclass Gui(Tk):\r\n # initialise the object\r\n def __init__(self):\r\n super().__init__()\r\n\r\n # set window attributes\r\n self.title(\"Newsletter\")\r\n self.configure(bg=\"#C0C0C0\",\r\n height=300, \r\n width=500,\r\n )\r\n\r\n \r\n \r\n \r\n\r\n # add components/widgets\r\n self.add_program_frame()\r\n \r\n self.add_heading_label()\r\n self.add_center_label()\r\n self.add_email_frame()\r\n self.add_email_label()\r\n self.add_email_entry()\r\n self.add_subscribe_button()\r\n\r\n\r\n def add_program_frame(self):\r\n self.program_frame = Frame()\r\n self.program_frame.pack(fill=X,padx=10, pady=10)\r\n self.program_frame.configure(bg=\"#FEE\")\r\n \r\n \r\n\r\n def add_email_frame(self):\r\n self.email_frame = Frame(self.program_frame)\r\n self.email_frame.pack(fill=X,padx=10, pady=5)\r\n \r\n\r\n def add_heading_label(self):\r\n\r\n # 1. create component object\r\n self.heading_label = Label(self.program_frame)\r\n self.heading_label.pack(fill=X,side=TOP,padx=10, pady=10)\r\n # 2. style the component\r\n self.heading_label.configure(font=\"Arial 24\",\r\n text=\"RECEIVE OUR NEWSLETTER\",\r\n )\r\n\r\n def add_center_label(self):\r\n\r\n # 1. create component object\r\n self.center_label = Label(self.program_frame)\r\n self.center_label.pack(fill=X,padx=10, pady=20)\r\n # 2. style the component\r\n self.center_label.configure(font=\"Arial 12\",\r\n text=\"Please enter your email below to receive our newsletter.\",\r\n )\r\n def add_email_label(self):\r\n\r\n # 1. create component object\r\n self.email_label = Label(self.email_frame)\r\n self.email_label.pack(fill=X,side=LEFT,padx=10, pady=10)\r\n # 2. style the component\r\n self.email_label.configure(font=\"Arial 10\",\r\n text=\"Email:\",\r\n )\r\n\r\n\r\n def add_email_entry(self):\r\n\r\n # 1. create component object\r\n self.email_entry = Entry(self.email_frame)\r\n self.email_entry.pack(fill=X,padx=10, pady=20)\r\n # 2. style the component\r\n self.email_entry.configure(font=\"Arial 12\",\r\n ) \r\n\r\n def add_subscribe_button(self):\r\n\r\n # 1. create component object\r\n self.subscribe_button = Button(self.program_frame)\r\n self.subscribe_button.pack(fill=X,side=BOTTOM,padx=0, pady=0)\r\n # 2. style the component\r\n self.subscribe_button.configure(font=\"Arial 15\",\r\n text=\"Subscribe\")\r\n \r\n","sub_path":"2-guis/2-window-layout/2-pack/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":2887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"119362212","text":"\"\"\"Calculate between-population divergence metrics. Input is a tab delimited file with no header, containing Scaff, pos, ac, an, dp, and genotypes coded as 0-4.\nInput file custom: Filename should end with _XXX_raw.table.recode.txt, where XXX is three-letter population abbreviation\"\"\"\n\nimport argparse\n\n# export PYTHONPATH=\"$PYTHONPATH:/Users/monnahap/Documents/Research/code/GenomeScan/\"\n\n#Add within population varP...could just use average SSI\ndef calcPairwiseBPM(input_file, output, outname, window_size, minimum_snps):\n\n def NestedAnova(locus_list):\n locus = []\n for l in locus_list: # Remove missing data from the site\n try:\n l.remove(\"-9\")\n locus.append(l)\n except ValueError:\n locus.append(l)\n r = float(len(locus)) # Number of populations: Should always be 2 for pairwise analysis\n p_i = [] # Allele frequency of each population\n n_i = [] # Number of individuals in each population\n ploidy_list = [] # Ploidy of each population\n Fssg = 0.0 # Among population sum of squares for Fst\n Fssi = 0.0 # Among individuals within populations sum of squares for Fst\n Fssw = 0.0 # Within individuals sum of squares for Fst\n Fsst = 0.0 # Total sum of squares: confirmed that this equals sum of components within rounding error\n Rssg = 0.0 # Among population sum of squares for Rho\n Rssi = 0.0 # Among individual within populations sum of squares for Rho\n Rsst = 0.0 # Total sum of squres: confirmed that this equals sum of components within rounding error\n p_ij = [] # Within-individual allele frequency for each individual in each population\n tac = 0 # Total alternative allele count used for determining allele frequency\n tan = 0 # Total allele number\n ac_ij = [] # Alternative allele count per individual\n df_w = 0.0 # degrees of freedom for Fssw\n FS_Nij2 = 0.0 # Attempting to mirror spagedi code; Used for calculation of sample size coefficients in variance components\n FS_SNij2 = 0.0\n RS_SNij2 = 0.0\n FS_SNij2_over_SNij = 0.0\n for pop_site in locus:\n FSNij2temp = 0.0\n p = [] # List containing individual allele frequencies for a population\n ac_i = [] # List containing individual ac counts for a population\n ploidy = float(pop_site[1])\n nnn = float(len(pop_site[7:])) # sample size for thispopulation\n an = ploidy * nnn # Calculation an for the population\n ac = sum([float(geno) for geno in pop_site[7:]]) # Calculate ac for a population\n n_i.append(nnn)\n p_i.append(ac / an)\n ploidy_list.append(ploidy)\n pop_an = 0\n for ind in pop_site[7:]:\n p_ind = float(ind) / ploidy # Calculate individual's allele frequency\n p.append(p_ind)\n ac_i.append(float(ind))\n num_alleles = 0\n for c in range(0, int(ploidy) - int(ind)): # Calculation of tan and tac for p_bar calculation\n num_alleles += 1\n tan += 1\n for c in range(0, int(ind)):\n num_alleles += 1\n tac += 1\n tan += 1\n FS_Nij2 += ploidy**2 # Squared sample size per individual\n FSNij2temp += ploidy**2\n pop_an += ploidy\n assert num_alleles == int(ploidy)\n df_w += float(num_alleles) - 1.0\n FS_SNij2_over_SNij += FSNij2temp / pop_an\n FS_SNij2 += pop_an**2 # Squared total number of observations per population\n RS_SNij2 += nnn**2 # Squared total number of observations per population\n p_ij.append(p)\n ac_ij.append(ac_i)\n p_bar = float(tac) / float(tan)\n\n # Calculate degrees of freedom and sample size coefficients\n df_g = r - 1.0\n df_i = sum([x - 1.0 for x in n_i])\n df_t = df_g + df_i + df_w\n fn0bis = (FS_SNij2_over_SNij - (FS_Nij2 / tan)) / df_g\n fn0 = (tan - FS_SNij2_over_SNij) / df_i\n fnb0 = (tan - (FS_SNij2 / tan)) / df_g\n rnb0 = (float(sum(n_i)) - (RS_SNij2 / float(sum(n_i)))) / df_g\n\n assert df_t == float(tan) - 1.0\n for i, pop in enumerate(ac_ij):\n for j, ind in enumerate(pop):\n for ref in range(0, int(int(ploidy_list[i]) - int(ind))): # Loop over number of reference alleles\n Fssg += (p_i[i] - p_bar)**2\n Fssi += (p_ij[i][j] - p_i[i])**2\n Fssw += (0 - p_ij[i][j])**2\n Fsst += (0 - p_bar)**2\n for alt in range(0, int(ind)): # Loop over number of alternative alleles\n Fssg += (p_i[i] - p_bar)**2\n Fssi += (p_ij[i][j] - p_i[i])**2\n Fssw += (1 - p_ij[i][j])**2\n Fsst += (1 - p_bar)**2\n Rssi += (p_ij[i][j] - p_i[i])**2\n Rssg += (p_i[i] - p_bar)**2\n Rsst += (p_ij[i][j] - p_bar)**2\n # Calculate Mean Squares\n FMS_g = Fssg / df_g\n FMS_i = Fssi / df_i\n FMS_w = Fssw / df_w\n RMS_g = Rssg / df_g\n RMS_i = Rssi / df_i\n # Calculate variance components\n fs2_w = FMS_w\n fs2_i = (FMS_i - fs2_w) / fn0\n fs2_g = (FMS_g - fs2_w - fn0bis * fs2_i) / fnb0\n rs2_i = RMS_i\n rs2_g = (RMS_g - rs2_i) / rnb0\n # Calculate numerator and denominators of rho and fst.\n rnum = rs2_g\n rden = rs2_i + rs2_g\n fnum = fs2_g\n fden = fs2_w + fs2_g + fs2_i\n\n return rnum, rden, fnum, fden\n\n\n def calcDxy(locus_info):\n locus = []\n for l in locus_info: # Remove missing data from site\n try:\n l.remove('-9')\n locus.append(l)\n except ValueError:\n locus.append(l)\n\n for i, pop_site in enumerate(locus):\n ploidy = float(pop_site[1])\n nnn = float(len(pop_site[7:]))\n an = ploidy * nnn\n ac = sum([float(geno) for geno in pop_site[7:]])\n if i == 0:\n p1 = (ac / an)\n if i == 1:\n p2 = (ac / an)\n\n dxy = (p1 * (1.0 - p2)) + (p2 * (1.0 - p1))\n\n return dxy\n\n # Prepare output file\n outfile = output + outname + '_BPM.txt'\n out1 = open(outfile, 'w')\n out1.write(\"contrast\\tscaff\\tstart\\tend\\twin_size\\tnum_snps\\tRho\\tFst\\tdxy\\n\")\n\n # Sort intput data\n data = open(input_file, 'r')\n data = [j.strip(\"\\n\").strip(\"\\t\").split(\"\\t\") for j in data]\n print(\"Sorting concatenated input files\")\n data = sorted(data, key=lambda k: (int(k[2].split(\"_\")[1]), int(k[3]))) # Sorts by scaffold then position\n\n # Begin loop over data file\n snp_count = 0\n Snp_count = 0\n start = 0.0\n end = window_size\n winexclcount = 0\n num_wind = 0\n for i, line in enumerate(data):\n\n pop, ploidy, scaff, pos, ac, an, dp = line[:7]\n pos = float(pos)\n\n if i % 100000 == 0:\n print(i)\n if i == 0:\n pop1 = pop # Get name of first population\n old_pos = pos\n Locus = [] # Hold information of single locus across populations\n oldscaff = scaff\n Fst = [0.0, 0.0] # Fst[0] is numerator for genome, [1] is denominator for genome\n Rho = [0.0, 0.0] # Rho[0] is numerator for genome, [1] is denominator for genome\n fst = [0.0, 0.0] # Fst[0] is numerator for window, [1] is denominator for window\n rho = [0.0, 0.0] # Rho[0] is numerator for window, [1] is denominator for window\n dxy = 0.0 # Dxy for window\n Dxy = 0.0\n\n if pos > start and pos <= end and scaff == oldscaff:\n if pos == old_pos: # Accruing information from multiple populations but same locus\n Locus.append(line)\n if Snp_count == 0.0 and i != 0: # Get name of second population\n pop2 = pop\n assert pop1 != pop2\n elif len(Locus) == 2: # Within current window but have moved on from previous locus\n rnum, rden, fnum, fden = NestedAnova(Locus)\n dxy += calcDxy(Locus)\n Dxy += dxy\n snp_count += 1\n fst = [sum(x) for x in zip(fst, [fnum, fden])] # Adds numerator and denominators from current site to running sums for window and genome respectively\n rho = [sum(x) for x in zip(rho, [rnum, rden])]\n Fst = [sum(x) for x in zip(Fst, [fnum, fden])]\n Rho = [sum(x) for x in zip(Rho, [rnum, rden])]\n Locus = [] # Clear site information\n Locus.append(line) # Append current site to site info\n old_pos = pos \n\n else: # Previous site contained data from only one population, so skip calculations\n Locus = []\n Locus.append(line)\n old_pos = pos\n\n\n elif int(pos) > end or scaff != oldscaff: # Current snp is onto next window, but must do calculation for previous locus before moving on\n if len(Locus) == 2: # Skip locus calc if data from only one population\n snp_count += 1\n rnum, rden, fnum, fden = NestedAnova(Locus)\n dxy += calcDxy(Locus)\n Dxy += dxy\n fst = [sum(x) for x in zip(fst, [fnum, fden])]\n rho = [sum(x) for x in zip(rho, [rnum, rden])]\n Fst = [sum(x) for x in zip(Fst, [fnum, fden])]\n Rho = [sum(x) for x in zip(Rho, [rnum, rden])]\n\n if snp_count >= minimum_snps: # Report or exclude window\n Snp_count += snp_count\n num_wind += 1\n fst = fst[0] / fst[1] # fst and rho and ratios of running sums of numerator and denominator calculations\n fac = rho[0] / rho[1]\n rho_i = fac / (1 + fac)\n dxy = dxy / float(snp_count)\n\n out1.write(outname + '\\t' + scaff + '\\t' + # Write calculations to file\n str(start) + '\\t' +\n str(end) + '\\t' +\n str(window_size) + '\\t' +\n str(snp_count) + '\\t' +\n str(rho_i) + '\\t' +\n str(fst) + '\\t' +\n str(dxy) + '\\n')\n\n else:\n winexclcount += 1\n # Reset running sums for current window\n snp_count = 0\n fst = [0.0, 0.0]\n rho = [0.0, 0.0]\n dxy = 0.0\n\n # Moving on to deal with current SNP. Must reset window boundaries based on current position\n if float(pos) > end:\n while float(pos) > end:\n end += window_size # Increment the end boundary by units of window-size until end is greater than current position\n start = end - window_size\n elif scaff != oldscaff:\n oldscaff = scaff\n\n start = 0.0\n end = window_size\n\n if int(pos) > start and int(pos) <= end and scaff == oldscaff: # Ensures that current snp falls within window bounds we just determined\n Locus = []\n Locus.append(line)\n old_pos = pos\n\n if len(Locus) == 2: # Final window calculations\n snp_count += 1\n rnum, rden, fnum, fden = NestedAnova(Locus)\n dxy += calcDxy(Locus)\n Dxy += dxy\n fst = [sum(x) for x in zip(fst, [fnum, fden])]\n rho = [sum(x) for x in zip(rho, [rnum, rden])]\n Fst = [sum(x) for x in zip(Fst, [fnum, fden])]\n Rho = [sum(x) for x in zip(Rho, [rnum, rden])]\n\n if snp_count >= minimum_snps: # Use or exclude window\n num_wind += 1\n fst = fst[0] / fst[1]\n fac = rho[0] / rho[1]\n rho_i = fac / (1 + fac)\n dxy = dxy / float(snp_count)\n\n out1.write(outname + '\\t' + scaff + '\\t' +\n str(start) + '\\t' +\n str(end) + '\\t' +\n str(window_size) + '\\t' +\n str(snp_count) + '\\t' +\n str(rho) + '\\t' +\n str(fst) + '\\t' +\n str(dxy) + '\\n')\n\n else:\n winexclcount += 1\n # Calculate genome-wide metrics\n FAC = Rho[0] / Rho[1]\n rho_G = FAC / (1 + FAC)\n Fst_G = Fst[0] / Fst[1]\n Dxy = Dxy / Snp_count\n out1.write(outname + '\\t' + \"Genome\" + '\\t' +\n \"-99\" + '\\t' +\n \"-99\" + '\\t' +\n str(window_size) + '\\t' +\n str(Snp_count) + '\\t' +\n str(rho_G) + '\\t' +\n str(Fst_G) + '\\t' +\n str(Dxy) + '\\n')\n\n out1.close()\n\n return num_wind, winexclcount, rho\n\n\nif __name__ == '__main__': # Used to run code from command line\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-i1', type=str, metavar='input_file1', required=True, help='input file created with recode012.py')\n parser.add_argument('-o', type=str, metavar='output_directory', required=True, help='Output Directory')\n parser.add_argument('-prefix', type=str, metavar='output_file_prefix', required=True, help='Name indicating populations in input file')\n parser.add_argument('-ws', type=float, metavar='window_size', required=False, default='10000.0', help='Size of windows in bp')\n parser.add_argument('-ms', type=int, metavar='minimum_snps', required=False, default='2', help='minimum number of snps in a window')\n\n args = parser.parse_args()\n\n j1, j2, j3 = calcPairwiseBPM(args.i, args.o, args.prefix, args.ws, args.ms)\n","sub_path":"bpm.py","file_name":"bpm.py","file_ext":"py","file_size_in_byte":13862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"238831252","text":"import pandas as pd\nfrom rdflib import URIRef, BNode, Literal, Graph\nfrom rdflib.namespace import RDF, RDFS, FOAF, XSD\nfrom rdflib import Namespace\nimport numpy as np\nimport math\nimport sys\nimport argparse\nimport json\nimport urllib\nimport glob\nimport unicodedata\n# 正規表現操作のライブラリ\nimport re\n\ncanvas_image_map = {}\ncuration_data = {}\n\nEXCEL_PATH = \"data/Moller_All-Data_20210129.xlsx\"\n\ncuration_uri = \"https://moeller.jinsha.tsukuba.ac.jp/data/curation.json\"\n\ndef get_manifest_data(vol):\n path = \"../pm/data/manifests/\"+vol+\".json\"\n\n # jsonファイルを読み込む\n f = open(path)\n # jsonデータを読み込んだファイルオブジェクトからPythonデータを作成\n data = json.load(f)\n # ファイルを閉じる\n f.close()\n\n '''\n res = urllib.request.urlopen(manifest)\n # json_loads() でPythonオブジェクトに変換\n data = json.loads(res.read())\n '''\n\n canvases = data[\"sequences\"][0][\"canvases\"]\n\n for canvas in canvases:\n canvas_image_map[canvas[\"@id\"]] = canvas[\"thumbnail\"][\"service\"][\"@id\"]\n\n return canvases\n\ndef get_curation_data(curation):\n path = curation.replace(\"https://moeller.jinsha.tsukuba.ac.jp/\", \"\")\n\n print(\"aaa\", path)\n\n path = path.replace(\"vol\", \"vol_new\")\n\n # jsonファイルを読み込む\n f = open(path)\n # jsonデータを読み込んだファイルオブジェクトからPythonデータを作成\n data = json.load(f)\n # ファイルを閉じる\n f.close() \n\n members = data[\"selections\"][0][\"members\"]\n\n # pos = 1\n\n for member in members:\n label = member[\"label\"]\n member_id = member[\"@id\"]\n tmp = member_id.split(\"#xywh=\")\n thumbnail_url = canvas_image_map[tmp[0]]+\"/\"+tmp[1]+\"/,200/0/default.jpg\"\n\n curation_data[label] = {\n \"thumbnail_url\" : thumbnail_url,\n # \"related\" : \"http://codh.rois.ac.jp/software/iiif-curation-viewer/demo/?curation=\"+curation_uri+\"&pos=\"+str(len(curation_data.keys())+1),\n \"member_id\" : member_id\n }\n\ndef get_curation_data_new(data):\n\n members = data[\"selections\"][0][\"members\"]\n\n # pos = 1\n\n for member in members:\n label = member[\"label\"]\n member_id = member[\"@id\"]\n tmp = member_id.split(\"#xywh=\")\n thumbnail_url = canvas_image_map[tmp[0]]+\"/\"+tmp[1]+\"/,200/0/default.jpg\"\n\n curation_data[label] = {\n \"thumbnail_url\" : thumbnail_url,\n # \"related\" : \"http://codh.rois.ac.jp/software/iiif-curation-viewer/demo/?curation=\"+curation_uri+\"&pos=\"+str(len(curation_data.keys())+1),\n \"member_id\" : member_id\n }\n\nmanifest_map = {\n \"1\": {\n \"manifest\": \"https://moeller.jinsha.tsukuba.ac.jp/data/manifest/4a1fbed0-f2a2-4cf5-8a0a-fa310c62ca50/manifest.json\"\n },\n \"2\": {\n \"manifest\": \"https://moeller.jinsha.tsukuba.ac.jp/data/manifest/56653a59-0d55-4d1a-a7e3-2242e02859a1/manifest.json\"\n },\n \"3\": {\n \"manifest\": \"https://moeller.jinsha.tsukuba.ac.jp/data/manifest/8aaa203c-1c5a-4fef-973b-4fb174d60d37/manifest.json\"\n }\n}\n\ncuration_map = {\n \"1\": {\n \"curation\": \"https://moeller.jinsha.tsukuba.ac.jp/data/vol/01.json\"\n },\n \"2\": {\n \"curation\": \"https://moeller.jinsha.tsukuba.ac.jp/data/vol/02.json\"\n },\n \"3\": {\n \"curation\": \"https://moeller.jinsha.tsukuba.ac.jp/data/vol/03.json\"\n }\n}\n\nfor vol in manifest_map:\n print(\"manifest\\t\"+str(vol))\n manifest_data = manifest_map[vol]\n manifest_data[\"canvases\"] = get_manifest_data(vol)\n\nfor vol in curation_map:\n print(\"curation\\t\"+str(vol))\n get_curation_data(curation_map[vol][\"curation\"])\n\nfiles = glob.glob(\"data/add_new/*.json\")\n\nfor file in files:\n\n # jsonファイルを読み込む\n f = open(file)\n # jsonデータを読み込んだファイルオブジェクトからPythonデータを作成\n data = json.load(f)\n # ファイルを閉じる\n f.close()\n\n get_curation_data_new(data)\n\npath = EXCEL_PATH\n\nmanifest_members = {}\n\ndf = pd.read_excel(path, sheet_name=0, header=None, index_col=None, engine=\"openpyxl\")\n\nr_count = len(df.index)\nc_count = len(df.columns)\n\ndef handleAs(data):\n targets=[\"*3\", \"*2\"]\n for target in targets:\n if target in data:\n data = data.replace(target, target.replace(\"*\", \"×\"))\n\n return data\n\ndef handleSplit(data):\n\n targets = [\"(\", \")\", \"=\", \"×3\", \"×2\", \"/\", \",\"]\n\n for target in targets:\n data = data.replace(target, \"+\")\n\n data = data.split(\"+\")\n\n arr = []\n\n for i in data:\n if i not in arr and i != \"\":\n arr.append(i.strip())\n\n return arr\n\ndef toSearch(data):\n arr = []\n fields = [\"*\", \"-\", \"?\", \"bis\", \"ter\", \"quat\"]\n for e in data:\n for field in fields:\n e = e.replace(field, \"\")\n\n if e[-1:] in [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"a\", \"b\", \"c\"]:\n e = e[:-1]\n\n if e not in arr and e != \"\":\n arr.append(e)\n\n return arr\n\nfor j in range(1, r_count):\n\n # print(j)\n\n sort = str(df.iloc[j,1])\n\n if sort != \"107004\" and False:\n continue\n\n m_sort = str(df.iloc[j,2]).zfill(8)\n h_sort = str(df.iloc[j,4]).zfill(8)\n\n vol = str(df.iloc[j,12]) # *\n\n m_no_str = unicodedata.normalize(\"NFKC\", str(df.iloc[j,16]))\n\n m_no_str = handleAs(m_no_str)\n\n h_no_str = unicodedata.normalize(\"NFKC\", str(df.iloc[j,19]))\n\n h_no_str = handleAs(h_no_str)\n\n item_str = unicodedata.normalize(\"NFKC\", str(df.iloc[j,15]))\n\n # m_no = m_no_str.replace(\"=\", \"+\").split(\"+\") # 要検討\n # h_no = h_no_str.replace(\"=\", \"+\").split(\"+\") # 要検討\n\n m_no = handleSplit(m_no_str)\n h_no = handleSplit(h_no_str)\n item_no = handleSplit(item_str)\n\n page = str(df.iloc[j,13])\n\n order = str(df.iloc[j,14])\n\n m_no2 = toSearch(m_no)\n\n h_no2 = toSearch(h_no)\n\n item_no2 = toSearch(item_no)\n\n ph = df.iloc[j,20]\n if pd.isnull(ph):\n ph = \"\"\n\n ph = unicodedata.normalize(\"NFKC\", ph)\n ph2 = handleSplit(ph)\n\n ###\n\n note = df.iloc[j,21]\n\n categories = df.iloc[j,18].split(\",\")\n numeral = [] if pd.isnull(df.iloc[j,17]) else str(df.iloc[j,17]).split(\",\")\n\n \n\n unit = df.iloc[j, 10]\n\n stype = df.iloc[j, 8]\n\n type = df.iloc[j, 6]\n\n ###\n\n if vol not in manifest_map:\n print(\"invalid\", vol)\n continue\n\n manifest = manifest_map[vol][\"manifest\"]\n\n if vol == \"1\":\n canvas_index = int(page) + 29\n elif vol == \"2\":\n canvas_index = int(page) + 21\n elif vol == \"3\":\n canvas_index = int(page) + 21\n\n canvas_id = manifest_map[vol][\"canvases\"][canvas_index][\"@id\"]\n\n if manifest not in manifest_members:\n manifest_members[manifest] = {}\n\n if pd.isnull(note) or note == 0:\n note = \"\"\n\n manifest_members[manifest][sort] = {\n \"vol\": vol,\n \"m_no_str\" : m_no_str,\n \"h_no_str\" : h_no_str,\n \"item_no_str\" : item_str,\n \"m_no\": m_no,\n \"h_no\": h_no,\n \"item_no\" : item_no,\n \"m_no2\": m_no2,\n \"h_no2\": h_no2,\n \"item_no2\" : item_no2,\n \"m_sort\": m_sort,\n \"h_sort\": h_sort,\n \"ph\": ph,\n \"ph2\": ph2,\n \"note\" : note,\n \"thumbnail_id\": sort,\n \"canvas_id\": canvas_id,\n \"page\" : page,\n \"order\" : order,\n \"type\" : type,\n \"stype\" : stype,\n \"categories\": categories,\n \"numeral\": numeral,\n \n \"unit\" : unit\n }\n\nselections = []\n\nmissing = []\n\npos = 1\n\nfor manifest in manifest_members:\n\n # print(manifest)\n\n members = []\n\n # print(manifest_members[manifest])\n\n for key in sorted(manifest_members[manifest]):\n\n # print(key)\n\n obj = manifest_members[manifest][key]\n\n vol = obj[\"vol\"]\n\n '''\n {\n \"label\": \"Hieratic No\",\n \"value\": obj[\"m_no\"]\n },\n {\n \"label\": \"Hieratic No Mod\",\n \"value\": obj[\"m_no2\"]\n },\n \n {\n \"label\": \"Hieroglyph No\",\n \"value\": obj[\"h_no\"]\n },\n {\n \"label\": \"Hieroglyph No Mod\",\n \"value\": obj[\"h_no2\"]\n },\n '''\n\n metadata = [\n {\n \"label\": \"Vol\",\n \"value\": vol\n },\n {\n \"label\": \"Hieratic No\",\n \"value\": obj[\"m_no_str\"]\n },\n {\n \"label\": \"Hieroglyph No\",\n \"value\": obj[\"h_no_str\"]\n },\n {\n \"label\": \"Item Label\",\n \"value\": obj[\"item_no_str\"]\n },\n\n {\n \"label\": \"Hieratic No Mod\",\n \"value\": obj[\"m_no\"]\n },\n {\n \"label\": \"Hieroglyph No Mod\",\n \"value\": obj[\"h_no\"]\n },\n {\n \"label\": \"Item Label Mod\",\n \"value\": obj[\"item_no\"]\n },\n\n {\n \"label\": \"Hieratic No Search\",\n \"value\": obj[\"m_no2\"]\n }, \n {\n \"label\": \"Hieroglyph No Search\",\n \"value\": obj[\"h_no2\"]\n },\n {\n \"label\": \"Item Label Search\",\n \"value\": obj[\"item_no2\"]\n },\n \n {\n \"label\": \"Phone/Word\",\n \"value\": obj[\"ph\"]\n },\n {\n \"label\": \"Phone/Word Mod\",\n \"value\": obj[\"ph2\"]\n },\n {\n \"label\": \"Note\",\n \n \"value\": obj[\"note\"]\n },\n {\n \"label\": \"m_sort\",\n \"value\": obj[\"m_sort\"]\n },\n {\n \"label\": \"h_sort\",\n \"value\": obj[\"h_sort\"]\n },\n {\n \"label\": \"Page\",\n \"value\": obj[\"page\"]\n },\n {\n \"label\": \"Order\",\n \"value\": obj[\"order\"]\n },\n {\n \"label\": \"Item Type\",\n \"value\": obj[\"type\"]\n },\n {\n \"label\": \"Category Class\",\n \"value\": obj[\"categories\"]\n }\n ]\n\n if len(obj[\"numeral\"]) > 0:\n metadata.append({\n \"label\": \"Numeral\",\n \"value\": obj[\"numeral\"]\n })\n\n if not pd.isnull(obj[\"stype\"]):\n metadata.append({\n \"label\": \"Sub Type\",\n \"value\": obj[\"stype\"]\n })\n\n if not pd.isnull(obj[\"unit\"]):\n metadata.append({\n \"label\": \"Unit\",\n \"value\": obj[\"unit\"]\n })\n\n member = {\n \"@id\": obj[\"canvas_id\"],\n \"@type\": \"sc:Canvas\",\n \"label\": str(key),\n \"metadata\": metadata\n }\n\n thumbnail_id = obj[\"thumbnail_id\"]\n\n if thumbnail_id in curation_data:\n curation_obj = curation_data[thumbnail_id]\n member[\"related\"] = \"http://codh.rois.ac.jp/software/iiif-curation-viewer/demo/?curation=\"+curation_uri+\"&pos=\"+str(pos)\n member[\"thumbnail\"] = curation_obj[\"thumbnail_url\"]\n member[\"@id\"] = curation_obj[\"member_id\"]\n else:\n # member[\"related\"] = \"http://codh.rois.ac.jp/software/iiif-curation-viewer/demo/?curation=\"+curation_uri+\"&pos=\"+str(pos)\n # member[\"thumbnail\"] = \"https://diyhistory.org/public/hpdb/\"+vol+\"/\"+obj[\"thumbnail_id\"]+\".jpg\"\n\n missing.append(thumbnail_id)\n\n pos += 1\n\n members.append(member)\n\n selection = {\n \"@id\": curation_uri+\"/range\"+vol,\n \"@type\": \"sc:Range\",\n \"label\": \"Manual curation by IIIF Curation Viewer\",\n \"members\": members,\n \"within\": {\n \"@id\": manifest,\n \"@type\": \"sc:Manifest\",\n \"label\": vol\n }\n }\n selections.append(selection)\n\ncuration = {\n \"@context\": [\n \"http://iiif.io/api/presentation/2/context.json\",\n \"http://codh.rois.ac.jp/iiif/curation/1/context.json\"\n ],\n \"@id\": curation_uri,\n \"@type\": \"cr:Curation\",\n \"label\": \"Curating list\",\n \"selections\": selections\n}\n\nwith open(\"../../static/data/curation_old.json\", 'w') as f:\n json.dump(curation, f, ensure_ascii=False, indent=4,\n sort_keys=True, separators=(',', ': '))\n\n\nprint(\"missing\", missing)\nprint(\"missing length\", len(missing))\n\n# print(curation_data)","sub_path":"src/moeller/002_convert_xlsx_to_curation.py","file_name":"002_convert_xlsx_to_curation.py","file_ext":"py","file_size_in_byte":12228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"260263102","text":"# for app in /usr/share/applications/*.desktop; \n# do echo \"${app:24:-8}\"; done\nimport pathlib\n\ndef getapplicationlist():\n \"get application list\"\n root = \"/usr/share/applications/\"\n root_dir_instance = pathlib.Path(root)\n list = [item.name[:-8] for item in root_dir_instance.glob(\"*.desktop\")]\n return list\n\ndef checkStatusForApplication(searchapp,appList):\n \"check application status\"\n # for item in appList:\n # if (item.find(searchapp)) != -1:\n # print ('Found at ', item)\n matchers = searchapp\n matching = [s for s in appList if any(xs in s for xs in matchers)]\n return matching","sub_path":"system-ai/getListApp.py","file_name":"getListApp.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"2548284","text":"#bools for readability. Please don't change this unless you want to cause problems\ncalls = True\nputs = False\n\n\ndate = \"2020-06-04\" #Date of options expiration\nbull = \"LOW\" #Ticker Symbol of predicted bullish Stock\nbear = \"HD\" #Ticker Symbol of predicted bearish Stock\nmin_volume = 30 #Minumum volume of options we're willing to buy \ndesired_insurance = -10 #a max of -$ needed to profit off of hedged put (Make negative as the puts require a decrease in value to proffit)\ndesired_climb = 10 #a min # of $ needed to profit off of call \noutput_file = \"output.csv\" #output file. Must be of type csv. Open with a spreadsheet editor","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"282202459","text":"#!/usr/bin/python\n#coding:utf-8\nimport sys\n\nN = int(sys.argv[1])\nf = open('hightemp.txt')\ntmp = []\nfor line in f:\n\ttmp.append(line)\n\ntmp = tmp[-N:]\nfor i in tmp:\n\tprint(i),\n","sub_path":"chapter2/15.py","file_name":"15.py","file_ext":"py","file_size_in_byte":173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"613741610","text":"__author__ = 'yjxiong'\n\nimport os\nimport glob\nimport argparse\nimport random\nimport math\n\n\ndef dump_class_ind(src_path):\n cat_list = os.listdir(src_path)\n content = []\n cat_dict = {}\n ind = 0\n for id, dir in enumerate(cat_list):\n cat = dir.split('_')[0]\n if cat not in cat_dict.keys():\n cat_dict[cat] = ind\n ind += 1\n line = str(ind) + \" \"+cat+\"\\n\"\n content.append(line)\n if not os.path.exists(os.path.join('data',src_path+'_splits')):\n os.mkdir(os.path.join('data',src_path+'_splits'))\n cat_file = 'data/'+src_path+'_splits/classInd.txt'\n with open(cat_file, \"w\") as f:\n f.writelines(content)\n return cat_dict\n\ndef split_vid_list(video_frame_dirs, cat_dict, src_path, proportion = 0.8):\n # video_frame_dirs\n # frames/v_sfdsf_dsfdsfdsfds\n train_list_file = 'data/'+src_path +'_rgb_train_split_1.txt'\n val_list_file = 'data/'+src_path+'_rgb_val_split_1.txt'\n train_content = []\n val_content = []\n cat2vlist_dict = {}\n count = 0\n for frame_dir in video_frame_dirs:\n #print(\"frame_dir is\"+frame_dir)\n if count % 500 == 0:\n print (\"parsed {} videos!\".format(count))\n cat = frame_dir.split('/')[1].split('_')[1]\n cat_id = str(cat_dict[cat])\n if cat not in cat2vlist_dict.keys():\n cat2vlist_dict[cat] = []\n if len(os.listdir(frame_dir)) > 0:\n line = frame_dir+' '+str(len(os.listdir(frame_dir)))+' '+cat_id+'\\n'\n # print(\"number: \" + str(count) + \"line is :\"+ line )\n cat2vlist_dict[cat].append(line)\n count += 1\n\n for vid_list in cat2vlist_dict.values():\n # random.shuffle(vid_list)\n len_vid_list = len(vid_list)\n\n # if less than 1000 copy\n if len_vid_list < 1000:\n times = math.ceil(1000/len_vid_list)\n vid_list = vid_list * times\n\n print(\"from {} to {}\".format(len_vid_list, len(vid_list)))\n\n position = math.floor(len(vid_list)*proportion)\n train_vid_list = vid_list[:position]\n val_vid_list = vid_list[position+1:]\n print(vid_list[:2])\n #print(position)\n train_content += train_vid_list\n val_content += val_vid_list\n #print (\"val_content is\"+val_content[0])\n\n random.shuffle(train_content)\n random.shuffle(val_content)\n\n with open(train_list_file, \"w\") as f:\n #print(\"now is in :\"+os.getcwd())\n #print(\"train_content is\", train_content)\n f.writelines(train_content)\n with open(val_list_file, \"w\") as f:\n f.writelines(val_content)\n return\n\ndef dump_splits_list(split_list, split='train'):\n dump_file = split + \".txt\"\n content = []\n with open(dump_file, \"w\") as f:\n f.writelines(split_list)\n return\n\ndef get_video_dirs(frame_dir):\n temp = os.listdir(frame_dir)\n return [os.path.join(frame_dir, item) for item in temp]\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"extract optical flows\")\n parser.add_argument(\"src_path\")\n parser.add_argument(\"frame_dir\")\n args = parser.parse_args()\n\n src_path = args.src_path\n frame_dir = args.frame_dir\n\n # get the list of frames dir of videos\n video_frame_dirs = get_video_dirs(frame_dir)\n\n # catagory list of src_path\n cat_dict = dump_class_ind(src_path)\n\n # split the vidlist into train and val\n split_vid_list(video_frame_dirs, cat_dict, src_path)\n","sub_path":"tools/gen_trainlist.py","file_name":"gen_trainlist.py","file_ext":"py","file_size_in_byte":3468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"344122424","text":"from typing import TYPE_CHECKING, List, Tuple, cast\n\nimport matplotlib.textpath\n\nif TYPE_CHECKING:\n import cirq\n\n\ndef _get_text_width(t: str) -> float:\n tp = matplotlib.textpath.TextPath((0, 0), t, size=14, prop='Arial')\n bb = tp.get_extents()\n return bb.width + 10\n\n\ndef _rect(x: float,\n y: float,\n boxwidth: float,\n boxheight: float,\n fill: str = 'white',\n strokewidth: float = 1):\n \"\"\"Draw an SVG rectangle.\"\"\"\n return f''\n\n\ndef _text(x: float, y: float, text: str, fontsize: int = 14):\n \"\"\"Draw SVG text.\"\"\"\n return f'{text}'\n\n\ndef _fit_horizontal(tdd: 'cirq.TextDiagramDrawer',\n ref_boxwidth: float, col_padding: float) \\\n -> Tuple[List[float], List[float]]:\n \"\"\"Figure out the horizontal spacing of columns to fit everything in.\n\n Returns:\n col_starts: a list of where (in pixels) each column starts.\n col_widths: a list of each column's width in pixels\n \"\"\"\n max_xi = max(xi for xi, _ in tdd.entries.keys())\n max_xi = max(max_xi,\n max(cast(int, xi2) for _, _, xi2, _ in tdd.horizontal_lines))\n col_widths = [0.0] * (max_xi + 2)\n for (xi, _), v in tdd.entries.items():\n tw = _get_text_width(v.text)\n if tw > col_widths[xi]:\n col_widths[xi] = max(ref_boxwidth, tw)\n\n for i in range(len(col_widths)):\n # horizontal_padding seems to only zero-out certain paddings\n # we use col_padding as a default\n padding = tdd.horizontal_padding.get(i, col_padding)\n col_widths[i] += padding\n\n col_starts = [0.0]\n for i in range(1, max_xi + 3):\n col_starts.append(col_starts[i - 1] + col_widths[i - 1])\n\n return col_starts, col_widths\n\n\ndef tdd_to_svg(\n tdd: 'cirq.TextDiagramDrawer',\n ref_rowheight: float = 60,\n ref_boxwidth: float = 40,\n ref_boxheight: float = 40,\n col_padding: float = 20,\n y_top_pad: float = 5,\n) -> str:\n height = tdd.height() * ref_rowheight\n col_starts, col_widths = _fit_horizontal(tdd=tdd,\n ref_boxwidth=ref_boxwidth,\n col_padding=col_padding)\n\n t = f''\n\n for yi, xi1, xi2, _ in tdd.horizontal_lines:\n xi1 = cast(int, xi1)\n xi2 = cast(int, xi2)\n y = yi * ref_rowheight + y_top_pad + ref_boxheight / 2\n x1 = col_starts[xi1] + col_widths[xi1] / 2\n x2 = col_starts[xi2] + col_widths[xi2] / 2\n t += f''\n\n for xi, yi1, yi2, _ in tdd.vertical_lines:\n y1 = yi1 * ref_rowheight + y_top_pad + ref_boxheight / 2\n y2 = yi2 * ref_rowheight + y_top_pad + ref_boxheight / 2\n\n xi = cast(int, xi)\n x = col_starts[xi] + col_widths[xi] / 2\n t += f''\n\n for (xi, yi), v in tdd.entries.items():\n x = col_starts[xi] + col_widths[xi] / 2\n y = yi * ref_rowheight + y_top_pad + ref_boxheight / 2\n\n boxheight = ref_boxheight\n boxwidth = max(ref_boxwidth, _get_text_width(v.text))\n boxx = x - boxwidth / 2\n boxy = y - boxheight / 2\n\n if xi == 0:\n # Qubits\n t += _rect(boxx, boxy, boxwidth, boxheight, strokewidth=0)\n t += _text(x, y, v.text)\n continue\n\n if v.text == '@':\n t += f''\n continue\n if v.text == '×':\n t += _text(x, y + 3, '×', fontsize=40)\n continue\n\n t += _rect(boxx, boxy, boxwidth, boxheight)\n t += _text(x, y, v.text, fontsize=14 if len(v.text) > 1 else 18)\n\n t += ''\n return t\n\n\nclass SVGCircuit:\n \"\"\"A wrapper around cirq.Circuit to enable rich display in a Jupyter\n notebook.\n\n Jupyter will display the result of the last line in a cell. Often,\n this is repr(o) for an object. This class defines a magic method\n which will cause the circuit to be displayed as an SVG image.\n \"\"\"\n\n def __init__(self, circuit: 'cirq.Circuit'):\n # coverage: ignore\n self.circuit = circuit\n\n def _repr_svg_(self) -> str:\n # coverage: ignore\n tdd = self.circuit.to_text_diagram_drawer(transpose=False)\n return tdd_to_svg(tdd)\n\n\ndef circuit_to_svg(circuit: 'cirq.Circuit') -> str:\n \"\"\"Render a circuit as SVG.\"\"\"\n tdd = circuit.to_text_diagram_drawer(transpose=False)\n return tdd_to_svg(tdd)\n","sub_path":"cirq/contrib/svg/svg.py","file_name":"svg.py","file_ext":"py","file_size_in_byte":4934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"367995488","text":"import numpy as np\nimport pandas as pd\nimport pickle\nimport matplotlib.pyplot as plt\n\n# models = ['alexnet','CORnet-S', 'CORnet-R', 'CORnet-Z', 'CORnet-R2', 'squeezenet1_0', 'squeezenet1_1']\n\nmodels = ['alexnet']\nloc_scores = \"C:/Users/hsuen/.result_caching/\"\n\n\n## example file names shown here ##:\nbenchmark_loc = \"brainscore.benchmarks.NeuralBenchmark._ceiling/identifier=aru.Kuzovkin2018-pls.pkl\"\nactivations_extractor_loc = \"model_tools.activations.core.ActivationsExtractorHelper._from_paths_stored/identifier=alexnet,stimuli_identifier=aru.Kuzovkin2018-1trials.pkl\"\npca_extractor_loc = \"model_tools.activations.pca.LayerPCA._pcas/identifier=alexnet-pca_1000,n_components=1000.pkl\"\nlayer_scores = \"model_tools.brain_transformation.neural.LayerScores._call/model_identifier=alexnet,benchmark_identifier=IT,visual_degrees=8.pkl\"\n\ndef playground():\n file = open(loc_scores + activations_extractor_loc, 'rb')\n x = pickle.load(file)\n print('what do we have here')\n\n\n\n\ndef get_all_scores():\n scores = []\n for x in models:\n brain_score_model = \"brainscore.score_model/model_identifier=\" + x + \",benchmark_identifier=aru.Kuzovkin2018-pls.pkl\"\n\n # load the brainscore model scores?\n file = open(loc_scores + brain_score_model, 'rb')\n score= pickle.load(file)\n scores.append(score['data'][0].values)\n\n\n x_pos = [i for i, _ in enumerate(models)]\n plt.style.use('ggplot')\n plt.bar(x_pos, scores, color='green')\n\n plt.xlabel(\"Model\")\n plt.ylabel(\"Score\")\n plt.title(\"Scores\")\n plt.xticks(x_pos, models)\n\n\nif __name__ == \"__main__\":\n get_all_scores()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"data_analysis/readBrainScoreResponses.py","file_name":"readBrainScoreResponses.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"81113663","text":"# -*- coding: utf-8 -*-\n# Copyright (C) 2018 by\n# Marta Grobelna \n# Petre Petrov \n# Rudi Floren \n# Tobias Winkler \n# All rights reserved.\n# BSD license.\n#\n# Authors: Marta Grobelna \n# Petre Petrov \n# Rudi Floren \n# Tobias Winkler \n\nimport pyboltzmann as pybo\n\nfrom planar_graph_sampler.grammar.binary_tree_decomposition import EarlyRejectionControl\nfrom planar_graph_sampler.grammar.grammar_utils import Counter\nfrom planar_graph_sampler.operations.networks import merge_networks_in_parallel, merge_networks_in_series, \\\n substitute_edge_by_network\nfrom planar_graph_sampler.combinatorial_classes.halfedge import HalfEdge\nfrom planar_graph_sampler.combinatorial_classes.network import Network\nfrom planar_graph_sampler.grammar.three_connected_decomposition import three_connected_graph_grammar\n\n\nclass NetworkBuilder(pybo.DefaultBuilder):\n \"\"\"Builds u-atoms of networks.\"\"\"\n\n def __init__(self):\n self._counter = Counter()\n\n def u_atom(self):\n \"\"\"Constructs the trivial link network consisting of the poles and an edge between them.\"\"\"\n # Create the zero-pole of the network.\n root_half_edge = HalfEdge()\n root_half_edge.next = root_half_edge\n root_half_edge.prior = root_half_edge\n root_half_edge.node_nr = next(self._counter)\n # Creates the inf-pole.\n root_half_edge_opposite = HalfEdge()\n root_half_edge_opposite.next = root_half_edge_opposite\n root_half_edge_opposite.prior = root_half_edge_opposite\n root_half_edge_opposite.node_nr = next(self._counter)\n # Link the poles.\n root_half_edge.opposite = root_half_edge_opposite\n root_half_edge_opposite.opposite = root_half_edge\n res = Network(root_half_edge, is_linked=True, l_size=0, u_size=1)\n return res\n\n\nclass SNetworkBuilder(NetworkBuilder):\n \"\"\"Builds S-networks.\"\"\"\n\n def product(self, lhs, rhs):\n \"\"\"Merges the given networks in series.\"\"\"\n # Form is either (lhs,rhs) = (network, network) (1) or (lhs,rhs) = (network, l-atom) (2)\n if isinstance(lhs, Network) and isinstance(rhs, Network):\n # Form (1)\n res = merge_networks_in_series(lhs, rhs)\n else:\n # Form (2)\n assert isinstance(rhs, pybo.LAtomClass), rhs\n # The l-atom can be discarded.\n res = lhs\n assert not res.is_linked\n return res\n\n\nclass PNetworkBuilder(NetworkBuilder):\n \"\"\"Builds P-networks.\"\"\"\n\n def set(self, networks):\n \"\"\"Merges a set of networks in parallel.\"\"\"\n if len(networks) == 0:\n # An empty set is like a zero atom (it has size 0).\n # We use the generic zero atom here as a zero-atom-network cannot be defined.\n return pybo.ZeroAtomClass()\n # TODO Without reversing the list of networks, weird things happen, find out why.\n # networks.reverse()\n res = networks.pop()\n for nw in networks:\n res = merge_networks_in_parallel(res, nw)\n return res\n\n def product(self, n1, n2):\n \"\"\"Merges the set {n1, n2} of networks in parallel.\"\"\"\n # n2 might be the zero-atom resulting from an empty set of networks.\n assert not isinstance(n1, pybo.ZeroAtomClass)\n if isinstance(n2, pybo.ZeroAtomClass):\n return n1\n assert isinstance(n1, Network) and isinstance(n2, Network), n2\n return self.set([n1, n2])\n\n\ndef g_3_arrow_to_network(decomp):\n \"\"\"To be used as a bijection in the rules H, H_dx and H_dx_dx.\"\"\"\n # decomp = graph (1) | (network,graph_dy) (2) | ((network, network),graph_dy_dy) (3)\n if not isinstance(decomp, pybo.ProdClass):\n # Form (1)\n g = decomp.underive_all()\n link_edge = g.half_edge\n res = Network(link_edge, is_linked=False)\n elif isinstance(decomp.first, Network):\n # Form (2)\n network = decomp.first\n marked_atom = decomp.second.marked_atom\n g = decomp.second.underive_all()\n substitute_edge_by_network(marked_atom, network)\n res = Network(g.half_edge, is_linked=False)\n else:\n # Form (3)\n network1 = decomp.first.first\n network2 = decomp.first.second\n marked_atom1 = decomp.second.marked_atom\n marked_atom2 = decomp.second.base_class_object.marked_atom\n g = decomp.second.underive_all()\n substitute_edge_by_network(marked_atom1, network1)\n substitute_edge_by_network(marked_atom2, network2)\n res = Network(g.half_edge, is_linked=False)\n res.type = 'H'\n return res\n\n\ndef network_grammar():\n \"\"\"Constructs the grammar for networks.\n\n Returns\n -------\n DecompositionGrammar\n The grammar for sampling from D and D_dx.\n \"\"\"\n\n L = pybo.LAtomSampler\n U = pybo.UAtomSampler\n Rule = pybo.AliasSampler\n G_3_arrow = Rule('G_3_arrow')\n G_3_arrow_dx = Rule('G_3_arrow_dx')\n G_3_arrow_dy = Rule('G_3_arrow_dy')\n D = Rule('D')\n D_dx = Rule('D_dx')\n S = Rule('S')\n S_dx = Rule('S_dx')\n P = Rule('P')\n P_dx = Rule('P_dx')\n H = Rule('H')\n H_dx = Rule('H_dx')\n D_dx_dx = Rule('D_dx_dx')\n S_dx_dx = Rule('S_dx_dx')\n P_dx_dx = Rule('P_dx_dx')\n H_dx_dx = Rule('H_dx_dx')\n G_3_arrow_dx_dx = Rule('G_3_arrow_dx_dx')\n G_3_arrow_dx_dy = Rule('G_3_arrow_dx_dy')\n G_3_arrow_dy_dy = Rule('G_3_arrow_dy_dy')\n Bij = pybo.BijectionSampler\n Set = pybo.SetSampler\n USubs = pybo.USubsSampler\n\n grammar = pybo.DecompositionGrammar()\n grammar.rules = three_connected_graph_grammar().rules\n\n grammar.add_rules({\n\n # networks\n\n 'D': U() + S + P + H,\n\n 'S': (U() + P + H) * D * L(),\n\n 'P': U() * Set(1, S + H) + Set(2, S + H),\n\n 'H': Bij(USubs(G_3_arrow, D), g_3_arrow_to_network),\n\n # l-derived networks\n\n 'D_dx': S_dx + P_dx + H_dx,\n\n 'S_dx':\n (P_dx + H_dx) * D * L()\n + (U() + P + H) * D_dx * L()\n + (U() + P + H) * D,\n\n 'P_dx':\n U() * (S_dx + H_dx) * Set(0, S + H)\n + (S_dx + H_dx) * Set(1, S + H),\n\n 'H_dx':\n Bij(\n USubs(G_3_arrow_dx, D) + D_dx * USubs(G_3_arrow_dy, D),\n g_3_arrow_to_network\n ),\n\n # bi-l-derived networks\n\n 'D_dx_dx':\n S_dx_dx + P_dx_dx + H_dx_dx,\n\n 'S_dx_dx':\n (P_dx_dx + H_dx_dx) * D * L()\n + 2 * (P_dx + H_dx) * D_dx * L()\n + (U() + P + H) * D_dx_dx * L()\n + 2 * (P_dx + H_dx) * D\n + 2 * (U() + P + H) * D_dx,\n\n 'P_dx_dx':\n U() * (S_dx_dx + H_dx_dx) * Set(0, S + H)\n + U() * (S_dx + H_dx) ** 2 * Set(0, S + H)\n + (S_dx_dx + H_dx_dx) * Set(1, S + H)\n + (S_dx + H_dx) ** 2 * Set(0, S + H),\n\n 'H_dx_dx':\n Bij(\n USubs(G_3_arrow_dx_dx, D)\n + 2 * D_dx * USubs(G_3_arrow_dx_dy, D)\n + D_dx_dx * USubs(G_3_arrow_dy, D)\n + D_dx ** 2 * USubs(G_3_arrow_dy_dy, D),\n g_3_arrow_to_network\n ),\n\n })\n\n # Set up builders.\n grammar.set_builder(['D', 'S', 'P', 'H',\n 'D_dx', 'S_dx', 'P_dx', 'H_dx',\n 'D_dx_dx', 'S_dx_dx', 'P_dx_dx', 'H_dx_dx'], NetworkBuilder())\n grammar.set_builder(['P', 'P_dx', 'P_dx_dx'], PNetworkBuilder())\n grammar.set_builder(['S', 'S_dx', 'S_dx_dx'], SNetworkBuilder())\n EarlyRejectionControl.grammar = grammar\n\n return grammar\n\n\nif __name__ == '__main__':\n from planar_graph_sampler.evaluations_planar_graph import *\n from timeit import default_timer as timer\n\n oracle = pybo.EvaluationOracle(my_evals_100)\n pybo.BoltzmannSamplerBase.oracle = oracle\n pybo.BoltzmannSamplerBase.debug_mode = False\n\n start = timer()\n grammar = network_grammar()\n symbolic_x = 'x*G_1_dx(x,y)'\n symbolic_y = 'y'\n sampled_class = 'D'\n grammar.init(sampled_class, symbolic_x, symbolic_y)\n end = timer()\n print(\"Time init: {}\".format(end - start))\n\n try:\n print(\"expected avg. size: {}\\n\".format(oracle.get_expected_l_size(sampled_class, symbolic_x, symbolic_y)))\n except pybo.PyBoltzmannError:\n pass\n\n # random.seed(0)\n # boltzmann_framework_random_gen.seed(13)\n\n l_sizes = []\n i = 0\n samples = 100000\n start = timer()\n while i < samples:\n obj = grammar.sample_iterative(sampled_class)\n l_size = obj.l_size\n # print(l_size)\n l_sizes.append(l_size)\n # if obj.l_size == 4:\n # i += 1\n i += 1\n end = timer()\n print()\n print(\"avg. size: {}\".format(sum(l_sizes) / len(l_sizes)))\n print(\"time: {}\".format(end - start))\n\n # while True:\n # g = grammar.sample_iterative(sampled_class, symbolic_x, symbolic_y)\n # if g.l_size == 2:\n # g = g.underive_all()\n # print(g)\n # print(g.number_of_edges)\n # print(\"is linked: {}\".format(g.is_linked))\n # assert g.is_consistent\n # g.plot(with_labels=False, use_planar_drawer=False, node_size=25)\n # plt.show()\n","sub_path":"planar_graph_sampler/grammar/network_decomposition.py","file_name":"network_decomposition.py","file_ext":"py","file_size_in_byte":9393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"178341761","text":"\"\"\"\nConversion script for the parameter searching values.\n\"\"\"\n\nfrom velociraptor.observations.objects import ObservationalData\nfrom velociraptor.tools.lines import binned_median_line\n\nimport unyt\nimport numpy as np\nimport os\nimport sys\n\n# Exec the master cosmology file passed as first argument\nwith open(sys.argv[1], \"r\") as handle:\n exec(handle.read())\n\noutput_directory = \"../\"\n\nif not os.path.exists(output_directory):\n os.mkdir(output_directory)\n\n\napertures = [30, 100]\nbox_sizes = [25, 100]\n\nfor aperture in apertures:\n for box_size in box_sizes:\n processed = ObservationalData()\n\n comment = (\n \"EAGLE GSMF at z=0, calculated out of the SUBFIND catalogues. \"\n \"h-free. Cosmology from Planck 2013; O_M = 0.307, O_L = 0.693. \"\n \"More information is available in Schaye et al. 2015. This file \"\n f\"is for box-size {box_size} Mpc and aperture {aperture} kpc.\"\n )\n citation = \"Schaye et al. (2015)\"\n bibcode = \"2015MNRAS.446..521S\"\n name = \"Galaxy Stellar Mass Function\"\n plot_as = \"points\"\n redshift = 0.0\n h_obs = 0.6777\n h = cosmology.h\n\n raw_filename = f\"../raw/Schaye2015_{box_size}_{aperture}kpc.txt\"\n\n M, N, sigma = np.loadtxt(raw_filename, skiprows=3, delimiter=\" \").T\n\n mass = unyt.unyt_array(M, units=unyt.Solar_Mass)\n smf = unyt.unyt_array(N, units=1 / unyt.Mpc ** 3)\n\n smf_scatter = unyt.unyt_array(sigma, units=1 / unyt.Mpc ** 3)\n\n processed.associate_x(\n mass,\n scatter=None,\n comoving=False,\n description=f\"Galaxy Stellar Mass ({aperture} kpc)\",\n )\n processed.associate_y(\n smf,\n scatter=smf_scatter,\n comoving=True,\n description=\"Galaxy Stellar Mass Function\",\n )\n processed.associate_citation(citation, bibcode)\n processed.associate_name(name)\n processed.associate_comment(comment)\n processed.associate_redshift(\n redshift, redshift_lower=redshift, redshift_upper=0.1\n )\n processed.associate_plot_as(plot_as)\n processed.associate_cosmology(cosmology)\n\n output_path = f\"{output_directory}/Schaye2015_{box_size}_{aperture}kpc.hdf5\"\n\n if os.path.exists(output_path):\n os.remove(output_path)\n\n processed.write(filename=output_path)\n","sub_path":"data/GalaxyStellarMassFunction/conversion/convertSchaye2015.py","file_name":"convertSchaye2015.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"15198962","text":"\"\"\"\r\n\r\nIcepack Setup From Sherlock Inputs\r\n--------------------------------------------\r\nThis Example shows how to create an Icepak Project starting from Sherlock Files (step and csv) and aedb board \r\n\"\"\"\r\n\r\n\r\n\r\nimport time\r\nimport os\r\nimport datetime\r\nimport pathlib\r\nimport sys\r\n\r\nlocal_path = os.path.abspath('')\r\nmodule_path = pathlib.Path(local_path)\r\naedt_lib_path = module_path.parent\r\nsys.path.append(os.path.join(aedt_lib_path))\r\nfrom pyaedt import examples, generate_unique_name\r\ninput_dir = examples.download_sherlock()\r\ntemp_folder = os.path.join(os.environ[\"TEMP\"], generate_unique_name(\"Example\"))\r\nif not os.path.exists(temp_folder): os.makedirs(temp_folder)\r\nprint(temp_folder)\r\n\r\n######################################\r\n# Input Variables\r\n# this lists all input variables needed to the example to run\r\n\r\nmaterial_name = 'MaterialExport.csv'\r\ncomponent_properties = 'TutorialBoardPartsList.csv'\r\ncomponent_step = 'TutorialBoard.stp'\r\naedt_odb_project = 'SherlockTutorial.aedt'\r\naedt_odb_design_name = \"PCB\"\r\nstackup_thickness = 2.11836\r\noutline_polygon_name = \"poly_14188\"\r\n\r\n######################################\r\n# Import pyaedt and start AEDT\r\n# AEDT will run in nongraphical mode\r\n\r\nfrom pyaedt import Icepak\r\nfrom pyaedt import Desktop\r\n\r\n###############################################################################\r\n# NonGraphical\r\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n# Change Boolean to False to open AEDT in graphical mode\r\n\r\nNonGraphical = True\r\n\r\nd=Desktop(\"2021.1\", NG=NonGraphical)\r\n\r\nstart = time.time()\r\nmaterial_list = os.path.join(input_dir, material_name)\r\ncomponent_list = os.path.join(input_dir, component_properties)\r\nvalidation = os.path.join(temp_folder, \"validation.log\")\r\nfile_path = os.path.join(input_dir, component_step)\r\nproject_name = os.path.join(temp_folder, component_step[:-3] + \"aedt\")\r\n\r\n\r\n############################################################################\r\n# Create an Icepak project and delete Region to improve performances\r\n\r\nipk = Icepak()\r\n\r\n############################################################################\r\n# Removing region and disabling autosave to speedup import\r\n\r\nd.disable_autosave()\r\nipk.modeler.primitives.delete(\"Region\")\r\ncomponent_name = \"from_ODB\"\r\n\r\n######################################\r\n# Import PCB from aedb file\r\n\r\nodb_path = os.path.join(input_dir, aedt_odb_project)\r\nipk.create_pcb_from_3dlayout(component_name, odb_path, aedt_odb_design_name,extenttype=\"Polygon\",\r\n outlinepolygon=outline_polygon_name)\r\n\r\n############################################################################\r\n# create an offset Coordinate system to match odb++ with sherlock step file\r\n\r\n\r\nipk.modeler.coordinate_system.create([0,0,stackup_thickness/2],view=\"XY\")\r\n\r\n######################################\r\n# import cad\r\n\r\n\r\nipk.modeler.import_3d_cad(file_path, refresh_all_ids=False)\r\n\r\n############################################################################\r\n#save cad and refresh properties from aedt file parsing\r\n\r\nipk.save_project(project_name, refresh_obj_ids_after_save=True)\r\n\r\n######################################\r\n# removing pcb objects\r\n\r\nipk.modeler.primitives.delete_objects_containing(\"pcb\", False)\r\n\r\n######################################\r\n# Creating Region\r\n\r\nipk.modeler.create_air_region(*[20,20,300,20,20,300])\r\n\r\n######################################\r\n# assigning Materials\r\n\r\nipk.assignmaterial_from_sherlock_files(component_list, material_list)\r\n\r\n############################################################################\r\n# Deleting Object with no material Assignment\r\n\r\nno_material_objs = ipk.modeler.primitives.get_objects_by_material(\"\")\r\nipk.modeler.primitives.delete(no_material_objs)\r\nipk.save_project()\r\n\r\n######################################\r\n# Assign Power to Component Blocks\r\n\r\n\r\nall_objects = ipk.modeler.primitives.get_all_objects_names()\r\n\r\n######################################\r\n# Assign Power blocks\r\ntotal_power = ipk.assign_block_from_sherlock_file(component_list)\r\n\r\n######################################\r\n# Setup and Boundaries\r\n\r\nipk.mesh.automatic_mesh_pcb(4)\r\n\r\nsetup1 = ipk.create_setup()\r\nsetup1.props[\"Solution Initialization - Y Velocity\"] = \"1m_per_sec\"\r\nsetup1.props[\"Radiation Model\"] =\"Discrete Ordinates Model\"\r\nsetup1.props[\"Include Gravity\"] =True\r\nsetup1.props[\"Secondary Gradient\"] =True\r\nsetup1.update()\r\nipk.assign_openings(ipk.modeler.primitives.get_object_faces(\"Region\"))\r\n\r\n############################################################################\r\n# Check for intersection using Validation and fix it by assigning Priorities\r\n\r\n\r\nipk.assign_priority_on_intersections()\r\n\r\n######################################\r\n# Saving and closing\r\nipk.save_project()\r\n\r\n\r\nend = time.time()-start\r\nipk.close_desktop()\r\nprint(\"Elapsed time: {}\".format(datetime.timedelta(seconds=end)))\r\nprint(\"Project Saved in {} \".format(temp_folder))\r\n\r\n\r\n\r\n\r\n","sub_path":"_downloads/acf8822c3a841e402365a771a3967d59/Sherlock_Example.py","file_name":"Sherlock_Example.py","file_ext":"py","file_size_in_byte":4933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"206900242","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Dec 19 21:08:48 2018\r\n\r\n@author: user\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport pickle\r\nimport time\r\nnp.set_printoptions(threshold=np.inf)\r\nstart = time.time()\r\n\r\nNTier = int(4)\r\nNCol = int(6)\r\nNumCon = int(17)\r\nN = int(2)\r\n\r\nwith open('input_layer_4_6_17_2.pickle', 'rb') as file:\r\n input_layer_4_6_17_2 = pickle.load(file)\r\n \r\nwith open('input_layer_4_6_17_3.pickle', 'rb') as file:\r\n input_layer_4_6_17_3 = pickle.load(file)\r\n \r\nwith open('input_layer_4_6_17_4.pickle', 'rb') as file:\r\n input_layer_4_6_17_4 = pickle.load(file)\r\n\r\n\r\ninput_layer_trans = np.concatenate((input_layer_4_6_17_2, input_layer_4_6_17_3, input_layer_4_6_17_4), axis = 0)\r\n#input_layer_trans = input_layer_trans[3300:3305, :]\r\n\r\ninput_layer = np.transpose(input_layer_trans)\r\nBay_dataset = input_layer_trans\r\nBay_dataset.shape = (len(Bay_dataset), NTier, NCol)\r\n\r\ndef bay_test(Initial_Bay):\r\n Bay_test = Initial_Bay\r\n np.place(Initial_Bay, Initial_Bay == 0, [NumCon + 1]) # strange syntax, transfer 0 to NumCon + 1\r\n return Bay_test\r\n\r\ndef Bay_height(Bay, NumCon):\r\n \r\n Height = np.zeros((NCol,), dtype = int)\r\n for i in range(0, NTier):\r\n for j in range(0, NCol):\r\n if Bay[i][j] > 0 and Bay[i][j] < NumCon + 1:\r\n Height[j] += 1\r\n return Height\r\n\r\n\r\ndef Find_Stack_N(Bay, N, lowest_con):\r\n Stack_N = []\r\n \r\n for i in range(lowest_con, lowest_con + N): # i equals tocontainer\r\n \r\n con_position = np.where(Bay == i)\r\n Stack_N.append(int(con_position[1]))\r\n \r\n return list(set(Stack_N))\r\n \r\ndef not_in_Stack_N(Stack_N, Height):\r\n \r\n Stack = []\r\n Stack_Height = []\r\n \r\n for i in range(0, NCol):\r\n Stack.append(i)\r\n \r\n for i in Stack_N:\r\n Stack.remove(i)\r\n \r\n for i in Stack:\r\n Stack_Height.append(Height[i])\r\n \r\n return Stack_Height, Stack # Stack = not in stack_N\r\n\r\ndef Find_Top_Stack_N(Bay, Stack_N):\r\n \r\n Top_Stack_N = []\r\n for i in Stack_N:\r\n for j in range(0, NTier):\r\n if Bay[j][i] < NumCon + 1 and Bay[j][i] != 0:\r\n Top_Stack_N.append(Bay[j][i])\r\n break\r\n \r\n return Top_Stack_N\r\n \r\ndef Find_con_position(Bay, n):\r\n \r\n Position = np.where(Bay == n)\r\n row = int(Position[0])\r\n column = int(Position[1])\r\n #print(row, column)\r\n return row, column\r\n\r\ndef Find_Lowest_con_in_column(Bay, Stack): # Stack = not in stack_N\r\n Low_Stack = []\r\n #print(Stack)\r\n for i in Stack:\r\n con = NumCon + 1\r\n for j in range(0, NTier):\r\n if Bay[j][i] < con:\r\n con = Bay[j][i]\r\n #print(con)\r\n\r\n if Bay[0][i] == NumCon + 1:\r\n Low_Stack.append(con)\r\n\r\n \r\n \r\n return Low_Stack\r\n\r\ndef present_con(Bay):\r\n \r\n NumC = np.max(Bay) \r\n return NumC\r\n\r\n\r\ndef LA_N(Bay_test, N):\r\n \r\n lowest_con = 1\r\n movement = 0\r\n relocation = 0\r\n NumC = 17\r\n while lowest_con <= NumCon: \r\n row_lowest_con, column_lowest_con = Find_con_position(Bay_test, lowest_con) \r\n #print('row_lowest_con =',row_lowest_con, 'column_lowest_con =', column_lowest_con)\r\n\r\n N = min(2, NumC)\r\n #print('N =', N)\r\n #print('NumC =', NumC)\r\n #print('lowest_con =', lowest_con)\r\n \r\n while Bay_test[row_lowest_con - 1][column_lowest_con] <= NumCon and row_lowest_con != 0: \r\n Stack_N = Find_Stack_N(Bay_test, N, lowest_con)\r\n Stack_Height, Stack_not_N = not_in_Stack_N(Stack_N, Height)\r\n #print(int(min(Stack_Height)))\r\n r = 1\r\n while int(min(Stack_Height)) == NTier or len(Stack_N) == NTier: \r\n N -= 1\r\n Stack_N = Find_Stack_N(Bay_test, N, lowest_con)\r\n Stack_Height, Stack_not_N = not_in_Stack_N(Stack_N, Height) \r\n #print('N =', N)\r\n #print('lowest container=', lowest_con)\r\n #print('Stack_N =', Stack_N)\r\n #print('Stack_Height =', Stack_Height)\r\n #print('Stack_not_N =', Stack_not_N)\r\n Top_Stack_N = Find_Top_Stack_N(Bay_test, Stack_N)\r\n #print('Top_Stack_N =', Top_Stack_N)\r\n Low_Stack = Find_Lowest_con_in_column(Bay_test, Stack_not_N)\r\n #print('Low_Stack =', Low_Stack)\r\n #print('r =', r)\r\n #print('len(Stack_N) =', len(Stack_N))\r\n while r <= len(Stack_N):\r\n n = max(Top_Stack_N)\r\n #print('n = ',n)\r\n #print(lowest_con)\r\n row_n, column_n = Find_con_position(Bay_test, n)\r\n #print('row_n =', row_n, 'column_n =', column_n)\r\n \r\n if column_n == column_lowest_con:\r\n if min(Low_Stack) == NumCon + 1:\r\n for j in range(0, NCol): \r\n if Bay_test[NTier-1][j] == NumCon + 1:\r\n row_low, column_low = NTier, j\r\n #print('row_low = ',row_low, 'column_low =', column_low)\r\n break\r\n \r\n elif max(Low_Stack) - n > 0:\r\n while min(Low_Stack) - n < 0:\r\n Low_Stack.remove(min(Low_Stack))\r\n \r\n if min(Low_Stack) == NumCon + 1:\r\n for j in range(0, NCol): \r\n if Bay_test[NTier-1][j] == NumCon + 1:\r\n row_low, column_low = NTier, j\r\n #print('row_low = ',row_low, 'column_low =', column_low)\r\n else: \r\n row, column_low = Find_con_position(Bay_test, min(Low_Stack))\r\n row_low = NTier - Height[column_low] \r\n \r\n else: \r\n row, column_low = Find_con_position(Bay_test, max(Low_Stack))\r\n row_low = NTier - Height[column_low] \r\n #print('row_low =', row_low, 'column_low =', column_low)\r\n \r\n break\r\n \r\n elif Bay_test[row_n][column_n] <= min(list(Bay_test[i][column_n] for i in range(0, NTier))):\r\n #print('min =', min(list(Bay_test[i][column_n] for i in range(0, NTier))))\r\n for i in Stack_N:\r\n rounds = 0\r\n for j in range(0, NTier-1):\r\n \r\n if Bay_test[j][i] < Bay_test[j+1][i]:\r\n rounds += 1\r\n \r\n elif Bay_test[j][i] == NumCon + 1:\r\n rounds += 1\r\n \r\n if Bay_test[i][NTier] != NumCon + 1:\r\n rounds += 1\r\n \r\n if rounds == NTier:\r\n Stack_N.remove(i)\r\n \r\n \r\n if r == len(Stack_N):\r\n row, column_low = Find_con_position(Bay_test, min(Low_Stack)) \r\n row_low = NTier - Height[column_low] \r\n break\r\n \r\n else:\r\n r += 1 \r\n \r\n elif max(Low_Stack) > n:\r\n \r\n if min(Low_Stack) == NumCon + 1:\r\n \r\n for j in range(0, NCol):\r\n \r\n if Bay_test[NTier-1][j] == NumCon + 1:\r\n row_low, column_low = NTier, j\r\n #print('row_low = ',row_low, 'column_low =', column_low)\r\n break\r\n else:\r\n while min(Low_Stack) - n < 0:\r\n Low_Stack.remove(min(Low_Stack))\r\n \r\n if min(Low_Stack) == NumCon + 1:\r\n for j in range(0, NCol):\r\n if Bay_test[NTier-1][j] == NumCon + 1:\r\n row_low, column_low = NTier, j\r\n #print('row_low = ',row_low, 'column_low =', column_low)\r\n break\r\n else:\r\n row, column_low = Find_con_position(Bay_test, min(Low_Stack))\r\n row_low = NTier - Height[column_low] \r\n \r\n #print(min(Low_Stack)) \r\n break\r\n \r\n elif r == len(Stack_N):\r\n \r\n row, column_low = Find_con_position(Bay_test, max(Low_Stack))\r\n row_low = NTier - Height[column_low] \r\n \r\n break\r\n \r\n Top_Stack_N.remove(max(Top_Stack_N))\r\n #print('Top_Stack_N =', Top_Stack_N)\r\n r += 1\r\n\r\n Bay_test[row_low-1][column_low] = Bay_test[row_n][column_n]\r\n Bay_test[row_n][column_n] = NumCon + 1\r\n Height[column_low] += 1\r\n Height[column_n] -= 1\r\n\r\n np.place(Bay_test, Bay_test == NumCon +1, 0)\r\n \r\n #print(Bay_test)\r\n np.place(Bay_test, Bay_test == 0, NumCon + 1)\r\n movement += 1\r\n relocation += 1\r\n \r\n Bay_test[row_lowest_con][column_lowest_con] = NumCon + 1\r\n Height[column_lowest_con] -= 1\r\n np.place(Bay_test, Bay_test == NumCon +1, 0)\r\n #print(Bay_test)\r\n np.place(Bay_test, Bay_test == 0, NumCon + 1)\r\n movement += 1\r\n lowest_con += 1\r\n NumC -= 1\r\n \r\n return movement\r\n\r\nrounds = 0\r\nmovement_dataset = []\r\n#print(Bay_dataset[62793])\r\n\r\nfor i in range(0, len(Bay_dataset)):\r\n Height = np.zeros((NCol,), dtype = int)\r\n for j in range(0, NTier):\r\n for k in range(0, NCol):\r\n if Bay_dataset[i][j][k] >= 1:\r\n Height[k] += 1\r\n\r\n #Height = height(Bay_dataset[i])\r\n #print(Bay_dataset[i])\r\n Bay_test = bay_test(Bay_dataset[i])\r\n #print(Bay_test)\r\n Movement = LA_N(Bay_test, N)\r\n #print(Movement)\r\n movement_dataset.append(Movement)\r\n rounds += 1\r\n #print(rounds)\r\n print(len(movement_dataset))\r\n\r\nwith open('LA_N_movement_4_6_17.pickle', 'wb') as file:\r\n pickle.dump(movement_dataset, file)\r\n \r\nprint(sum(movement_dataset))\r\nprint(sum(movement_dataset) / len(movement_dataset))\r\n\r\n\r\nend = time.time()\r\nprint(end - start) \r\n\r\n#8022920\r\n#25.469587301587303\r\n#284.45464038848877\r\n","sub_path":"Create-Dataset/Output-Data/Better-of-Two/4-6-17/LA_N_test_4_6_17.py","file_name":"LA_N_test_4_6_17.py","file_ext":"py","file_size_in_byte":11168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"304563713","text":"#!/usr/bin/env python3\n#coding: utf-8\n\n# similarity of src lang to the given tgt lang\n\n# input: wals_file.tsv tgt_lang_wals_code src_lang_wals_code+\n\n# ouput: similarity between 0 and 1 for each src lang\n\nimport sys\n\nlang_tgt = sys.argv[2]\nlangs_src = sys.argv[3:]\n\n# Measure src-tgt similarity\ndef similarity(fields_src, fields_tgt):\n match = 0\n count = 0\n for (src, tgt) in zip(fields_src, fields_tgt):\n if tgt:\n count += 1\n if tgt == src:\n match += 1\n assert count > 0, \"No features defined for source language\"\n return match/count\n\n# Find src fields\nwith open(sys.argv[1]) as wals:\n for line in wals:\n fields = line.rstrip('\\n').split('\\t')\n if fields[0] == lang_tgt:\n fields_tgt = fields\n break\nassert fields_tgt, \"Cannot find target language features\"\n\nwith open(sys.argv[1]) as wals:\n for line in wals:\n fields = line.rstrip('\\n').split('\\t')\n print(fields[0], fields[3], similarity(fields, fields_tgt), sep='\\t')\n\n","sub_path":"tools/wals_find_similar.py","file_name":"wals_find_similar.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"338481888","text":"x=[1,5,6,4,1,2,3,6]\r\ny=[1,1,5]\r\n\r\ndef check(a,b):\r\n for i in a:\r\n for j in b:\r\n if(len(b)>=0 and j == i):\r\n b.pop(0)\r\n else:\r\n break\r\n return b\r\n\r\nif len(check(x,y))==0:\r\n print(\"Its a match\")\r\nelse: print(\"Its gone\")\r\n \r\ncheck(x,y)","sub_path":"aas5 q1.py","file_name":"aas5 q1.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"545649123","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport math\nfrom readability_metrics import core\n\n\n'''\nBasic error handling. check if text is empty\n'''\n\n\ndef check_input(text):\n try:\n # if text is empty raise an error\n if not text:\n raise ValueError('Error: empty string, no text input')\n except ValueError as e:\n print(e)\n\n'''\nFlesch reading ease\n\nreturns value between 0.00 and 100.00 to determine the readability\n\n90.0–100.0 very easy to read\n80.0–90.0 easy to read\n70.0–80.0 fairly easy to read\n60.0–70.0 plain english\n50.0–60.0 fairly difficult to read\n30.0–50.0 difficult to read\n0.0–30.0 very difficult to read\n'''\n\n\ndef flesch_val(text, locale):\n check_input(text)\n proc_text = core.TextMetrics(text, locale)\n avg_sentence_len = proc_text.avg_sentence_len()\n avg_num_syl = proc_text.avg_num_syl()\n # special flesch reading ease for german language\n if locale == 'de':\n flesch = 180 - float(avg_sentence_len) - float(58.5 * avg_num_syl)\n return round(flesch, 2)\n # normal flesch reading ease formula\n else:\n flesch = 206.835 - float(1.015 * avg_sentence_len) - float(84.6 * avg_num_syl)\n return round(flesch, 2)\n\n\n'''\nAutomated readability index (ARI)\n\nreturns value between 1 and 14\n\n1 5-6\n2 6-7\n3 7-8\n4 8-9\n5 9-10\n6 10-11\n7 11-12\n8 12-13\n9 13-14\n10 14-15\n11 15-16\n12 16-17\n13 17-18\n14 18-22\n\nif score ends up at a decimal round up\n'''\n\n\ndef ari_val(text):\n check_input(text)\n proc_text = core.TextMetrics(text)\n char_count = proc_text.char_count()\n word_count = proc_text.word_count()\n sentence_count = proc_text.sentence_count()\n try:\n ari = 4.71 * (char_count / word_count) + (word_count / sentence_count) - 21.43\n # round up and return\n return math.ceil(ari)\n except ZeroDivisionError:\n print(\"Error ari: empty string, cannot divide by zero\")\n\n\n'''\nSMOG (Simple Measure Of Gobbledygook)\n\nreturns the eastimated years of education needed to understand the text\n'''\n\n\ndef smog_val(text, locale):\n check_input(text)\n proc_text = core.TextMetrics(text)\n polysyl_count = proc_text.polysyl_count()\n sentence_count = proc_text.sentence_count()\n\n try:\n if sentence_count < 30:\n raise ValueError('Error: smog test needs at least 30 sentences')\n else:\n smog = 1.0430 * math.sqrt(polysyl_count * (30 / sentence_count) + 3.1291)\n return round(smog, 0)\n\n except ValueError as e:\n print(e)\n","sub_path":"readability_metrics/readability.py","file_name":"readability.py","file_ext":"py","file_size_in_byte":2609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"256906617","text":"from typing import List\n\nfrom words import WORD_LIST\nimport random\n\n\ndef main():\n ATTEMPTS_ALLOWED = 6\n\n secret_word = get_random_word(WORD_LIST)\n\n correct_guesses = []\n incorrect_guesses = []\n lives = calc_attempts_remaining(ATTEMPTS_ALLOWED, incorrect_guesses)\n\n result = None\n while result is None:\n\n # display lives left\n print_lives_left(lives, ATTEMPTS_ALLOWED)\n\n # display hidden word\n blanked_word = reveal_letters(secret_word, correct_guesses)\n print(blanked_word)\n print()\n\n # get guess\n guess = get_guess(correct_guesses + incorrect_guesses)\n\n if letter_is_in_word(guess, secret_word):\n print(\"That is correct!\")\n correct_guesses.append(guess)\n else:\n print(\"Incorect.\")\n incorrect_guesses.append(guess)\n \n lives = calc_attempts_remaining(ATTEMPTS_ALLOWED, incorrect_guesses)\n \n if all_letters_present_in_list(secret_word, correct_guesses):\n result = \"win\"\n elif lives <= 0:\n result = \"lose\"\n\n print(word_reveal_message(secret_word))\n print(outcome_message(result))\n\n\ndef get_random_word(word_list: List[str]) -> str:\n \"\"\"Gets a random word.\n \n Args: \n word_list: the list from which to get the word.\n \n Returns:\n A single word.\n \"\"\"\n return random.choice(word_list)\n\n\ndef print_lives_left(remaining: int, out_of: int):\n \"\"\"Prints out lives-left info.\n \n Args:\n remaining: Remaining lives left.\n out_of: How many lives in total you start with.\n \"\"\"\n return f\"You have {remaining} lives remaining out of {out_of}\"\n\n\ndef reveal_letters(word: str, visible_letters: List[str]) -> str:\n \"\"\"Reveal the given letters in a hidden word.\n \n Args:\n word: The word whose letters need to be revealed.\n visible_letters: A list of letters that should be visible in the word.\n \n Returns:\n The word with visible letters shown and all others blanked-out.\n \n Example:\n If the word is \"hello\" and visible_letters is the list ['e', 'o'],\n The resulting string would be \"_ e _ _ o\". Separate each character\n with a space to make it easier to read.\n \"\"\"\n temp = \"\"\n for i in range(len(word)):\n if word[i] in visible_letters:\n temp += word[i]\n else:\n temp += '_'\n temp += ' '\n return temp[0:len(temp)-1]\n\n\n\ndef calc_attempts_remaining(attempts_allowed: int, incorrect: List[str]) -> int:\n \"\"\"Determine the number of guesses remaining.\n\n Based on the initial number of allowed attempts and the number\n of incorrect guesses.\n \n Args:\n attempts_allowed: The number of total allowed guesses.\n incorrect: A list containing all the incorrect guesses.\n \n Returns:\n How many remaining guesses the player has.\n \"\"\"\n return attempts_allowed-len(incorrect)\n\n\ndef word_reveal_message(word: str) -> str:\n \"\"\"Creates a message revealing the secret word.\n \n Args:\n word: the word being revealed.\n \n Returns:\n A message revealing the secret word.\n \n Example: \n \"The secret word was 'orange'.\"\n \"\"\"\n return f\"The secret word was '{word}'.\"\n\n\ndef outcome_message(result: str) -> str:\n \"\"\"Creates a message based on the player's outcome.\n \n Args:\n result: Either 'win' or 'lose'.\n \n Returns:\n An appropriate message based on the player's outcome.\n \"\"\"\n if result == \"win\":\n return \"Good job, you won!\"\n else:\n return \"You lost, you suck...\"\n\n\ndef get_guess(all_guesses: List[str]) -> str:\n \"\"\"Gets a valid guess from the player.\n \n This function will ensure:\n - The user enters a single character.\n - The user enters a letter not already guessed.\n - The user enters a valid letter (use str.isalpha())\n \n Args:\n all_guesses: A list of all prervious guesses.\n \n Returns:\n A single letter, not already guessed.\n \"\"\"\n \n while (True):\n ip = input().lower()\n if len(ip) > 1:\n print(\"Invalid input: Only enter one letter at a time.\")\n elif ip.isalpha() == False:\n print(\"Invalid input: Only enter alphabetical letters.\")\n elif ip in all_guesses:\n print(\"Invalid input: You've already guessed this letter.\")\n else:\n return ip\n\n\ndef letter_is_in_word(letter: str, word: str) -> bool:\n \"\"\"Determines if a given letter is in a word.\n \n Args:\n letter: The letter to search for.\n word: The word to search.\n \n Returns:\n True if the letter is in the word, False otherwise.\n \"\"\"\n if letter in word:\n return True\n else:\n return False\n\n\ndef all_letters_present_in_list(word: str, letter_list: List[str]) -> bool:\n \"\"\"Determines if all a word's letters are in a given list.\n \n For every letter in the given word, is it present in the\n given list of letters? True if so.\n\n Args:\n word: The word to check.\n letter_list: The letters of the word\n \n Returns:\n True if all the letters in the word are in the list of letters.\n \"\"\"\n for i in range(len(word)):\n if word[i] not in letter_list:\n return False\n return True\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Hangman_Functional_2020_12_08.py","file_name":"Hangman_Functional_2020_12_08.py","file_ext":"py","file_size_in_byte":5400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"421675264","text":"from flask import Flask, render_template, request ,flash, redirect, url_for\nfrom wtforms import Form, StringField, TextAreaField, RadioField, SelectField, SubmitField, validators\nimport firebase_admin\nfrom firebase_admin import credentials, db\nfrom target1 import Target\nfrom bmi1 import Bmi\nfrom User import User\n\napp = Flask(__name__)\n\ncred = credentials.Certificate('./cred/targets-settings-firebase-adminsdk-04p4y-fa9131dc22.json')\ndefault_app = firebase_admin.initialize_app(cred, {\n 'databaseURL': 'https://targets-settings.firebaseio.com/'\n})\n\nroot = db.reference()\ntargets_ref = root.child('targets')\n\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n@app.route('/healthyeating')\ndef healthyeating():\n return render_template('eating.html')\n\n@app.route('/planner')\ndef planner():\n return render_template('planner.html')\n\n@app.route('/events')\ndef events():\n return render_template('events.html')\n\n@app.route('/contact')\ndef contact():\n return render_template('contact.html')\n\n@app.route('/login')\ndef login():\n return render_template('login.html')\n\n@app.route('/tracker')\ndef tracker():\n return render_template('tracker.html')\n\n@app.route('/teenagerplan')\ndef teenagerplan():\n return render_template('teenagerplan.html')\n\n@app.route('/teenageraerobics')\ndef teenageraerobics():\n return render_template('teenageraerobics.html')\n\n@app.route('/teenageraerobic30min')\ndef teenageraerobic30min():\n return render_template('teenageraerobic30min.html')\n\n@app.route('/bmi', methods=['GET','POST'])\nclass bmi(Form):\n weight = StringField('Weight:', [validators.DataRequired()])\n height = StringField('Height:', [validators.DataRequired()])\n\ndef calculate():\n #follow according to user profile\n #adduser = request.form[]\n #user1\n form = bmi(request.form)\n if request.method == 'POST' and form.validate():\n weight = float(form.weight.data)\n height = float(form.height.data)\n Bmi = bmi1.Bmi(height, weight)\n bmi_db = User.child('BMI')\n bmi_db.update({\n \"height\":float(Bmi.get_height()),\n \"weight\":float(Bmi.get_weight()),\n \"BMI\":str(Bmi.get_bmi())\n })\n flash('You have successfully post your BMI','success')\n return redirect(url_for('bmi'))\n return render_template('bmiteseting.html')\n@app.route('/viewtarget')\ndef viewtarget():\n #print(root.get())\n list1 = [] # create a list to store all the objects\n targets = targets_ref.get()\n for target3 in targets:\n targetpost = targets[target3]\n target2 = Target1(targetpost['goals'], targetpost['category'], targetpost['status'], targetpost['number'])\n target2.set_target3(target3)\n target2.get_target3()\n list1.append(target2)\n #return render_template('view_target.html', targets=list1)\n return render_template('view_target.html', targets=list1)\n\nclass RequiredIf(object):\n\n def __init__(self, *args, **kwargs):\n self.conditions = kwargs\n\n def __call__(self, form, field):\n for name, data in self.conditions.items():\n if name not in form._fields:\n validators.Optional()(field)\n else:\n condition_field = form._fields.get(name)\n if condition_field.data == data:\n validators.DataRequired().__call__(form, field)\n else:\n validators.Optional().__call__(form, field)\n\nclass Target1(Form):\n goals = StringField('Goals', [validators.Length(min=1, max=150), validators.DataRequired()])\n category = RadioField('Type Of Goals', choices=[('physical', 'Physical'), ('diet', 'Diet'), ('habits', 'Habits')])\n status = RadioField('Status', choices=[('active', 'Active'),('onhold', 'On Hold'), ('notstarted', 'Not Started'), ('completed', 'Completed')])\n number = StringField('Number of times daily',[validators.Length(min=1, max=100), validators.DataRequired()])\n submit = SubmitField('Update')\n\n@app.route('/newtarget', methods=['GET','POST'])\ndef new():\n targetform = Target1(request.form)\n if request.method == 'POST' and targetform.validate():\n goals = targetform.goals.data\n category = targetform.category.data\n status = targetform.status.data\n number = targetform.number.data\n tar = Target1(goals, category, status, number)\n tar_db = root.child('targets')\n tar_db.push({\n 'goals': tar.get_goals(),\n 'category': tar.get_category(),\n 'status': tar.get_status(),\n 'number': tar.get_number(),\n # 'start_date': tar.get_start_date(),\n })\n flash('Target added.', 'success')\n return redirect(url_for('viewtarget'))\n\n return render_template('create_target.html', form=targetform)\n\n@app.route('/update/', methods=['GET','POST'])\ndef update_target(id):\n targetform = Target1(request.form)\n if request.method == 'POST' and targetform.validate():\n goals = targetform.goals.data\n category = targetform.category.data\n status = targetform.status.data\n number = targetform.number.data\n tar = Target1(goals, category, status, number)\n tar_db = root.child('targets/' + id)\n tar_db.set({\n 'goals': tar.get_goals(),\n 'category': tar.get_category(),\n 'status': tar.get_status(),\n 'number': tar.get_number(),\n # 'start_date': tar.get_start_date(),\n })\n flash('Goals Updated Successfully.', 'success')\n return redirect(url_for('viewtarget'))\n else:\n url = 'targets/' + id\n target_s = root.child(url).get()\n\n target2 = Target1(target_s['goals'], target_s['category'], target_s['status'], target_s['number'])\n target2.set_target3(id)\n targetform.goals.data = target2.get_goals()\n targetform.category.data = target2.get_category()\n targetform.status.data = target2.get_status()\n targetform.number.data = target2.get_number()\n\n return render_template('update_target.html', form=targetform)\n\n #return render_template('update_target.html', form=targetform)\n\n@app.route('/delete_targets/', methods=['POST'])\ndef delete_targets(id):\n tar_db = root.child('targets/' + id)\n tar_db.delete()\n flash('Deleted', 'success')\n\n return redirect(url_for('viewtarget'))\n\n\n@app.route('/foodtracker')\ndef food():\n calories = {'Boiled Eggs': 155, 'Fried Eggs': 196, 'Whole Chicken': 1070, 'French Fries': 312,'Celery': 16, 'Broccoli': 34, 'Cabbage': 25, 'Potato': 77, 'Apple': 52, 'Cucumber': 16,\n 'Onion':40,'White Rice(132g, a cup)': 199, 'Chicken': 239, 'Beef': 250}\n\n count = 0\n for i in calories:\n count += 1\n #if click == True:\n sum(calories.values())\n return render_template('foodtracker.html', calories=calories)\n\n\nif __name__ == '__main__':\n app.secret_key = 'secret12'\n app.run()","sub_path":"oop-master/flaskroute.py","file_name":"flaskroute.py","file_ext":"py","file_size_in_byte":6969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"340405056","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 1 2021\n\n@author: Weishen Li\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\nimport time\nfrom glob import glob\nfrom display import display_clusters\nimport sklearn.metrics\n\ndef k_means_pp(X, k):\n '''\n Compute initial custer for k-means\n arguments:\n - X: np.ndarray of shape [no_data, no_dimensions]\n input data points\n returns:\n - centroids: np.ndarray of shape [k, no_dimensions]\n centres of initial custers\n '''\n n_data = X.shape[0]\n k = min(n_data, k)\n centroids = []\n rand_i = np.random.choice(n_data)\n\n for _ in range(k):\n centroids.append(X[rand_i])\n X = np.concatenate((X[:rand_i], X[rand_i+1:]))\n\n distances = np.linalg.norm(np.expand_dims(X, axis=1) - centroids, axis=-1, ord=2).min(axis=1)\n rand_i = np.random.choice(X.shape[0], p=distances**2/(distances**2).sum())\n\n return np.array(centroids)\n\ndef kernel_kmeans(X, centroids, n_iterations):\n '''\n kernel k-means algorithm\n arguments:\n - X: np.ndarray of shape [no_data, no_dimensions]\n input data points\n - centroids: np.ndarray of shape [k, no_dimensions]\n centres of initial custers\n - n_iterations: integer, number of iterations to run k-means for\n returns:\n - which_component: np.ndarray of shape [no_data] and integer data\n type, contains values in [0, k-1] indicating which\n cluster each data point belongs to\n - centroids: np.ndarray of shape [k, no_dimensions] centres of\n final custers, ordered in such way as indexed by\n `which_component`\n '''\n # using standard k-means to assign each point to a cluster centroid\n k = centroids.shape[0]\n nn = X.shape[0]\n distances = np.linalg.norm(np.expand_dims(X, axis=1) - centroids, axis=-1, ord=2)\n which_component = np.argmin(distances, axis=-1)\n\n # calculate the kernel matrix of data X\n kernel_matrix = np.zeros((nn,nn))\n sigma = np.var(img_array)\n for i in range(nn):\n kernel_matrix[i] = np.exp((-np.linalg.norm((img_array[i,:] - img_array), axis = 1)**2)/sigma)\n \n # calcuate centroid for each component\n for iter in range(n_iterations):\n #print(\"############### Iteration: %d ###############\" % iter)\n dist = np.zeros((nn,k))\n # traverse each point in a cluster and then calculate the distances\n for kk in range(k):\n #print(\"Cluster: %d\" % kk)\n # find out each point in cluster kk \n masks = (which_component==kk)\n nnum = np.where(masks.T.squeeze() == True)\n #print(nnum[0][0])\n cluster_X = X[nnum[0]]\n k_matrix = kernel_matrix[nnum[0]]\n num_c = cluster_X.shape[0]\n # calculate the second term and the third term of the expanding formula in report\n for i in range(num_c):\n term2 = 2 * k_matrix[i,:].sum(axis = 0) / num_c\n term3 = k_matrix.sum().sum() / 2 / (num_c**2)\n # notice that the first term phi(x_i)*phi(x_i) is a constant 1\n dist[nnum[0][i],kk] = 1 - term2 + term3\n #re-assign the each point's cluster centroid then update the centroids\n which_component = np.argmin(dist, axis=-1)\n centroids = np.stack((X[which_component == 0].mean(axis=0),\n X[which_component == 1].mean(axis=0),\n X[which_component == 2].mean(axis=0),\n X[which_component == 3].mean(axis=0)), axis=0)\n \n return which_component, centroids\n\n\n\"\"\"\nMain program starts from here\n\"\"\"\n# set random seed for PRNG\nnp.random.seed(int(time.time()))\n# set up the image paths\nimage_paths = glob('images_for_test/*_image.jpg')\nprint(image_paths[0][16:])\nnum = len(image_paths)\n# read in all the image files in the testing directory \nfor n in range(num):\n # record the starting running time\n start = time.time()\n # read in the image\n image_frame = cv2.cvtColor(cv2.imread(image_paths[n],cv2.IMREAD_COLOR), cv2.COLOR_BGR2RGB)\n image_frame2 = cv2.resize(image_frame, (150, 106))\n img = cv2.cvtColor(image_frame2, cv2.COLOR_RGB2LAB)\n height, width, channel = img.shape\n # compress the image then use an array to save it\n img_array = np.zeros((width * height, channel))\n for i in range(height):\n img_array[i * width:(i + 1) * width] = img[i]\n # set up the cluster numbers \n k = 4\n nn = img_array.shape[0]\n # call the kernel_kmeans algorithm\n which_component, centers = kernel_kmeans(img_array, k_means_pp(img_array, k), n_iterations=10)\n # record the ending running time and print out the total using time\n end = time.time()\n print(\"Runtime: %f\" %(end - start))\n # call sklearn's davies_bouldin_score and print out the results\n print('Davies-Bouldin',sklearn.metrics.davies_bouldin_score(img_array, which_component))\n # call an imported function to plot the \n result = display_clusters(image_frame2, which_component,k)\n\n plt.show()\n cv2.imwrite('kernel_k-means_results/kkmeans_' + image_paths[0][16:], result)\n","sub_path":"kernel_kmeans.py","file_name":"kernel_kmeans.py","file_ext":"py","file_size_in_byte":5262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"468757466","text":"import pandas as pd\nimport numpy as np\nimport pomegranate as pm\nimport itertools as it\nfrom math import log\nfrom copy import deepcopy as dc\n\ndef fl(l):\n '''\n Helper Function that converts CPT Variable-Outcomes from \"float64\"\n to \"int\" after extraction via \"n.cpt.values.tolist()\"\n '''\n return [\n int(l[j])\n if j % len(l) < len(l) - 1 \n else l[j] for j in range(0, len(l))\n ]\n\n\nclass node:\n def __init__(self, \n idx, \n name=None, \n parents=[], \n children = [], \n outcomes=(0,1)):\n\n self.idx = idx\n self.par = parents\n self.chl = children\n self.ocm = outcomes\n self.cpt = None\n \n def old_cpt_index(self):\n \"\"\"\n Calculate total CPT size based on number of parents, \n outcomes. Build empty table with columns for each parent's\n possible outcomes and this nodes possible outcome. Add a \n column to store the probability for each record.\n \"\"\"\n var = self.parent_idx() + [self.idx]\n seed = []\n if len(var) == 1:\n idx = pd.Index(list(self.ocm)).set_names(var[0])\n return(idx)\n\n for p in range(0,len(var)):\n if len(seed) == 0:\n seed.append(list(self.ocm))\n else:\n for s in range(0,len(seed)):\n old = []\n for k in range(0, len(self.ocm)):\n old = old + seed[s]\n seed[s] = old\n l = len(seed[0]) // len(self.ocm)\n new = []\n for o in self.ocm:\n for j in range(0, l):\n new.append(o)\n seed.insert(0,new)\n tpl = list(zip(*seed))\n idx = pd.MultiIndex.from_tuples(tpl, names = var)\n return(idx)\n \n def cpt_index(self):\n \"\"\"\n Calculate total CPT size based on number of parents, \n outcomes. Build empty table with columns for each parent's\n possible outcomes and this nodes possible outcome. Add a \n column to store the probability for each record.\n \"\"\"\n var = self.par + [self]\n if len(var) == 1:\n idx = pd.Index(list(self.ocm)).set_names(var[0].idx)\n return(idx)\n \n else:\n combos=[]\n for v in var:\n if len(combos) == 0:\n # Initialize with a list of outcomes\n combos = [list([i]) for i in v.ocm]\n \n else:\n # Iterate over each existing combination\n # for each existing combination, add one new combo\n # for each outcome in the next variable\n \n new = []\n for c in combos:\n for o in v.ocm:\n merge = c + [o]\n new.append(merge)\n \n combos=new\n combos = [tuple(i) for i in combos]\n idx = pd.MultiIndex.from_tuples(combos, names = [v.idx for v in var])\n return(idx)\n \n def parent_idx(self):\n idx = []\n for i in self.par:\n idx.append(i.idx)\n return(idx)\n \n def add_parents(self, parents):\n new = []\n for p in parents:\n if p in self.chl:\n print(\"Cant have a parent that is also a child\")\n return(False)\n\n elif p in self.par:\n print(\"Already has this child\")\n return(False)\n else:\n new.append(p)\n self.par = self.par + new\n return(True)\n \n def add_children(self, children):\n new = []\n for c in children:\n if c in self.par:\n print(\"Cant have a child that is also a parent\")\n return(False)\n elif c in self.chl:\n print(\"Already has this parent\")\n return(False)\n else:\n new.append(c)\n self.chl = self.chl + new\n return(True)\n\n def del_parents(self, parents):\n x = set(self.par).difference(parents)\n self.par = list(x)\n \n\n def del_children(self, children):\n x = set(self.chl).difference(children)\n self.chl = list(x)\n\n def old_node_probs(self, data, alpha = 0.001):\n \"\"\"\n Fill CPT with corresponding observational counts\n \"\"\"\n index = self.cpt_index()\n var = self.parent_idx() + [self.idx]\n par = self.parent_idx()\n \n # Copy data, add a column to calcuate conditional probabilities\n cpt = data[var].copy()\n cpt['Prob'] = 0\n\n # # Flatten cpt to counts over observed outcomes\n cpt = cpt.groupby(var).count().copy()\n\n # For possible, but unobserved outcomes, convert NaN to 0\n cpt = cpt.reindex(index).fillna(0)\n \n cpt = cpt.reset_index()\n \n # Use a rather complicated lambda to calculate frequencies\n if len(par) == 0:\n cpt['Prob'] = cpt.transform(\n lambda x: (x + alpha) / (x.sum() +(x.count()*alpha)))['Prob']\n else:\n cpt['Prob'] = cpt.groupby(par).transform(\n lambda x: (x + alpha) / (x.sum() +(x.count()*alpha))\n )['Prob']\n \n # # Dump the dummy group \n # if par[0] == 'dummy':\n # self.cpt = cpt.drop(columns = ['dummy'])\n self.cpt = cpt\n \n def node_probs(self, data, alpha = 0.001):\n \"\"\"\n Fill CPT with corresponding observational counts\n \"\"\"\n index = self.cpt_index()\n var = self.parent_idx() + [self.idx]\n par = self.parent_idx()\n \n # Copy data, add a column to calcuate conditional probabilities\n cpt = data[var].copy()\n cpt['Prob'] = 0\n\n # # Flatten cpt to counts over observed outcomes\n cpt = cpt.groupby(var).count().copy()\n\n # For possible, but unobserved outcomes, convert NaN to 0\n cpt = cpt.reindex(index).fillna(0)\n \n cpt = cpt.reset_index()\n \n \n #Use a rather complicated lambda to calculate frequencies\n if len(par) == 0:\n cpt['Prob'] = cpt['Prob'].transform(\n lambda x: (x + alpha) / (x.sum() +(x.count()*alpha)))\n else:\n cpt['Prob'] = cpt.groupby(par)['Prob'].transform(\n lambda x: (x + alpha) / (x.sum() +(x.count()*alpha))\n )\n self.cpt = cpt\n \n def empty_cpt(self):\n \"\"\"\n Calculate total CPT size based on number of parents, \n outcomes. Build empty table with columns for each parent's\n possible outcomes and this nodes possible outcome. Add a \n column to store the probability for each record.\n \"\"\"\n df = pd.DataFrame(\n index=self.cpt_index(),\n columns=['Prob']\n )\n df['Prob'] = 0.0\n return df.reset_index()\n\n \n\nclass net:\n def __init__(self, size=5, outcomes = (0,1)):\n self.siz = size\n self.nds = {}\n for i in range(0, self.siz):\n self.nds[i] = node(i, outcomes=outcomes)\n\n\n def reset(self):\n self.siz = self.siz\n self.nds = {}\n for i in range(0, self.siz):\n self.nds[i] = node(i)\n \n def add_edge(self, p_idx, c_idx):\n if p_idx != c_idx:\n if self.nds[p_idx].add_children([self.nds[c_idx]]):\n self.nds[c_idx].add_parents([self.nds[p_idx]])\n \n \n def del_edge(self, p_idx, c_idx):\n self.nds[p_idx].del_children([self.nds[c_idx]])\n self.nds[c_idx].del_parents([self.nds[p_idx]])\n \n \n def rev_edge(self, p_idx, c_idx):\n if p_idx != c_idx:\n if c_idx in [j.idx for j in self.nds[p_idx].chl]:\n print(\"is_child\")\n self.del_edge(p_idx, c_idx)\n self.add_edge(c_idx, p_idx)\n\n def val(self):\n \"\"\"\n Depth first search algorithm to validate that\n a given DAG contains no cycles\n \"\"\"\n # Initialize Depth Markers\n rec, vis = {}, {}\n vertices = list(self.nds.values())\n for v in vertices:\n rec[v] = False\n vis[v] = False\n\n for v in vertices:\n if not self.dfs(v, rec, vis):\n return(True)\n else:\n return(False)\n \n def dfs(self, v, rec, vis):\n if not vis[v]:\n vis[v] = True\n rec[v] = True\n \n for c in v.chl:\n if (not vis[c]) and self.dfs(c, rec, vis):\n return(True)\n elif rec[c]:\n return(True)\n else:\n rec[v] = False\n return(False)\n \n def calc_cpt(self, data, alpha=0.001):\n \"\"\"\n Calculate CPT probabilities for all nodes in the\n network given the data.\n \"\"\"\n for k in self.nds.keys():\n n = self.nds[k]\n n.node_probs(data = data, alpha = alpha)\n\n def is_dpord(self, l):\n \"\"\"\n Function to check a node list is ordered parent to child\n \"\"\"\n for i in range(0, len(l) -1):\n pi = l[i].par\n for j in pi:\n for k in range(i+1, len(l)):\n if j == l[k]:\n return False\n else:\n continue\n return True\n\n def sort_nodes(self, l):\n stop = 0\n l = l #list(self.nds.values())\n p = 0\n while (not self.is_dpord(l)) and stop <1000:\n pi = l[p].par\n for i in range(p, len(l)):\n if l[i] in pi:\n l.insert(len(l), l.pop(p))\n break\n elif i+1 == len(l):\n p = p + 1\n\n stop = stop + 1\n return(l)\n \n def new_sort_nodes(self, l):\n stop = 0\n l = l #list(self.nds.values())\n p = 0\n while (not self.is_dpord(l)) and stop <1000:\n pi = l[p].par\n for i in range(p, len(l)):\n if l[i] in pi:\n l.insert(len(l), l.pop(p))\n break\n elif i+1 == len(l):\n p = p + 1\n\n stop = stop + 1\n return(l)\n \n def calc_prob(self, query):\n l = list(self.nds.values())\n if(len(query) != self.siz):\n print('Invalid Query')\n return False\n prob = []\n # Assume that the variables in the query correspond\n # to their position eg query[0] is Var 0, query[1] = Var 1 etc. . .\n \n for i in l:\n var = i.cpt.columns.drop('Prob')\n val = [query[j] for j in var ]\n c = i.cpt.copy()\n for j in range(0, len(val)):\n c = c[c[var[j]] == val[j]]\n prob.append(c['Prob'].values[0])\n return(np.prod(prob))\n\n def sample_net(self, n):\n \"\"\"\n Using a simple 'prior sampling' approach, generate \n n samples from this 'net' object.\n \"\"\"\n df = []\n x = 0\n while x < n:\n l = self.sort_nodes(list(self.nds.values()))\n row = {}\n for i in l:\n var = i.cpt.columns.drop('Prob')\n prior = {k:row[k] for k in row.keys() if k in var}\n c = i.cpt.copy()\n c = c.sort_values(by=list(c.columns))\n\n # Subset cpt\n #print(prior)\n for j in prior.keys():\n c = c[c[j] == prior[j]]\n\n s = np.random.uniform()\n #print(\"NODE:\", i.idx, \"Draw:\", s)\n #print(c)\n #print(c.loc[c[i.idx] == 0, 'Prob'])\n \n if s < c.loc[c[i.idx] == 0, 'Prob'].values[0]:\n row[i.idx] = 0\n else:\n row[i.idx] = 1\n #print(row.keys(), row.values())\n df.append([row[m] for m in sorted(row.keys())])\n x = x + 1\n df = pd.DataFrame(df)\n return(df)\n \n def gibbs(self, n):\n # Randomly initialize values for all possible variables\n val = []\n samples={}\n for k in self.nds.keys():\n nd=self.nds[k]\n val.append(np.random.choice(nd.ocm))\n samples[k]=[]\n \n l = self.sort_nodes(list(self.nds.values()))\n #print(val)\n # Generate \"n\" samples by rotating through each variable\n while n > 0: \n pos = n % len(self.nds)\n node= l[pos] \n par = self.nds[pos].parent_idx()\n ocm = self.nds[pos].ocm\n cpt = self.nds[pos].cpt.copy()\n if len(par) > 0:\n idx = pd.MultiIndex.from_tuples(\n [tuple([val[j] for j in par] + [o]) for o in ocm],\n names = par + [pos]\n )\n else:\n idx = pd.Index(ocm).set_names(pos)\n\n oc = cpt.set_index(par + [pos]).loc[idx].reset_index()[pos].values\n pr = cpt.set_index(par + [pos]).loc[idx].reset_index()['Prob'].values\n new_value = np.random.choice(oc, p=pr)\n val[pos] = new_value\n for k in samples.keys():\n samples[k].append(val[k])\n n = n - 1\n \n return(pd.DataFrame(samples))\n \n \n def score_net(self, data):\n \"\"\"\n Score this network against a data set\n \"\"\"\n # Flatten data set to a table of unique rows with corresponding\n # Frequencies. \n\n #df = data.copy()\n #gr = [i for i in df.columns]\n #df['Count'] = 0\n #df = df.groupby(gr, as_index=False).count()\n #df['Model'] = df[gr].apply(self.calc_prob, axis=1)\n #return(df.Model.transform(log).sum())\n \n # Reformat data for pomegranate scoring\n data.columns = [\"G\" + str(i) for i in data.columns]\n net = self.export_pom()[2]\n pscore = net.log_probability(data).sum()\n return pscore\n \n \n def export_dag(self):\n dag = np.zeros([self.siz, self.siz], int)\n for k in self.nds.keys():\n for c in self.nds[k].chl:\n dag[self.nds[k].idx, c.idx] = 1\n return(dag)\n \n def import_dag(self, dag):\n dg = dag\n self.reset()\n if not isinstance(dg, np.ndarray):\n return None\n if not dg.shape[0] == dg.shape[1]:\n return None\n \n for i in range(0, len(dg)):\n for j in range(0, len(dg)):\n if dg[i, j] == 1:\n self.add_edge(i, j)\n\n def export_pom(self):\n '''\n Returns\n -------\n pomegranate BN Model based on given DAG.\n Assume my \"sort\" function correctly returns a list where\n children are allways ranked higher than parents\n '''\n s = self.sort_nodes( l = list(self.nds.values()))\n model = pm.BayesianNetwork(\"DIY_GRN\")\n \n \n # Convert Top Level nodes to Discrete distributions\n top = [i for i in s if len(i.par) == 0]\n topStates = {}\n \n for n in top:\n pr = n.cpt['Prob'].to_dict()\n va = n.cpt[n.idx].to_dict()\n dist = {}\n for v in va.keys():\n dist[va[v]] = pr[v]\n \n dist=pm.DiscreteDistribution(dist)\n state = pm.Node(dist, name = \"G\"+str(n.idx))\n \n \n topStates[\"G\"+str(n.idx)] = state\n model.add_state(state)\n\n # Convert Depent Nodes to Conditional Distributions\n dep = [i for i in s if len(i.par) != 0]\n depStates = {}\n \n for n in dep:\n \n # Convert floats cpt outcome levels to integers if needed\n if isinstance(n.cpt.iloc[0,0], np.int64):\n cpt = [fl(l) for l in n.cpt.values.tolist()]\n \n else:\n cpt = n.cpt.values.tolist()\n \n # Vector of ID for each parent\n par_id = [\"G\"+str(i.idx) for i in n.par ]\n\n \n # Validate that all parents have been processed\n for p in par_id:\n if (not p in topStates.keys()) and (not p in depStates.keys()):\n print(\"Problem with parent:\",p, \"of node:\",n.idx)\n return [topStates, depStates]\n \n # Get all parents found in the topStates dict\n par = [ \n topStates[i]\n for i in par_id if i in topStates.keys()\n ]\n \n \n # Add all parents in the depStates dict\n par = par + [\n depStates[i]\n for i in par_id if i in depStates.keys()\n ]\n\n cpt = pm.ConditionalProbabilityTable(\n cpt,\n [p.distribution for p in par] \n )\n \n state = pm.Node(cpt, name = \"G\"+str(n.idx))\n depStates[\"G\"+str(n.idx)] = state\n \n # Add node to model\n model.add_state(state)\n \n # Add edges from parent to this node\n for p in par:\n model.add_edge(p, state)\n \n \n # Assemble and \"Bake\" model\n model.bake()\n return (topStates, depStates, model)\n \n def print_nodes(self):\n for k in self.nds.keys():\n print(\n \"Node:\", k,\n \"Parents:\", self.nds[k].parent_idx(),\n \"Children:\",[j.idx for j in self.nds[k].chl]\n )\n\n\nclass greedy():\n def __init__(self, data):\n if not isinstance(data, pd.DataFrame):\n return None\n else:\n self.data = data\n self.net = None\n self.scores = {}\n self.samples = None\n \n def train(self, iterations = 10, maxmiss=10):\n \"\"\"\n Train using Recommended Greedy Algorithm\n \"\"\"\n self.net = net(size = len(self.data.columns))\n self.net.calc_cpt(self.data)\n scores = {\n 'Iteration':[],\n 'Network':[],\n 'Score':[]\n }\n score_check = maxmiss\n niter = iterations \n nodes = [i for i in self.data.columns]\n best = self.net.score_net(self.data)\n \n #print(\"START LOOP\")\n while score_check > 0 and niter > 0:\n n = net(size = len(self.data.columns))\n n.import_dag(self.net.export_dag())\n \n ops = [n.add_edge, n.del_edge, n.rev_edge]\n for f in ops:\n edge = np.random.choice(nodes, size = 2, replace=False )\n f(edge[0], edge[1])\n \n if n.val():\n n.calc_cpt(self.data, alpha = 0.001)\n score = n.score_net(self.data)\n scores['Iteration'].append(iterations - niter)\n scores['Network'].append(n)\n scores['Score'].append(score)\n #print(best, score, niter, score_check)\n if score > best:\n self.net = n\n best = score\n niter = niter - 1\n score_check = maxmiss\n continue\n else:\n score_check = score_check - 1\n niter = niter -1\n continue\n else:\n niter = niter - 1\n continue\n self.scores = scores\n self.samples = self.net.sample_net(2000)\n \n def get_prob(self, query, target):\n qr = query.copy()\n tg = target\n par = self.net.nds[tg].parent_idx()\n ocm = self.net.nds[tg].ocm\n cpt = self.net.nds[tg].cpt.copy()\n if len(par) > 0:\n idx = pd.MultiIndex.from_tuples(\n [tuple([qr[j] for j in par + [tg]])],\n names = par + [tg]\n )\n else:\n idx = pd.Index([qr[tg]]).set_names(tg)\n \n pr = cpt.set_index(par + [tg]).loc[idx].values[0][0] \n return(pr)\n\n def call_target(self, query, target):\n \"\"\"\n Predict the status of a target gene (0 or 1) given the status of\n other genes in the network. This function retrieves the CPT for\n the target gene and returns the most likely outcome based on\n probabilities estimated from the training set.\n \"\"\"\n qr = query.copy()\n tg = target\n par = self.net.nds[tg].parent_idx()\n ocm = self.net.nds[tg].ocm\n cpt = self.net.nds[tg].cpt.copy()\n if len(par) > 0:\n idx = pd.MultiIndex.from_tuples(\n [tuple([qr[j] for j in par] + [i]) for i in ocm ],\n names = par + [tg]\n )\n else:\n idx = pd.Index(ocm).set_names(tg)\n call = cpt.set_index(par + [tg]).loc[idx]\n call = call.reset_index()\n call = call[tg].loc[call['Prob'] == max(call.Prob)].values[0]\n return(call)\n\n\n def predict(self, query, target, alpha = 0):\n \"\"\"\n Predict the status of a target gene (0 or 1) given the status of\n one or more query genes, using samples generated via direct sampling.\n \"\"\"\n qr = query.copy()\n ocm = self.net.nds[target].ocm\n cpt = self.samples[qr.index].copy()\n cpt['Prob'] = 0\n\n # # Flatten cpt to counts over observed outcomes\n cpt = cpt.groupby(list(qr.index)).count().copy()\n if len(qr.drop(target).index) > 0:\n idx = pd.MultiIndex.from_tuples(\n [tuple([qr[j] for j in qr.drop(target).index] + [i]) for i in ocm],\n names = list(qr.index)\n )\n else:\n idx =pd.Index(ocm).set_names(target)\n\n \n # For possible, but unobserved outcomes, convert NaN to 0\n cpt = cpt.reindex(idx).fillna(0)\n \n cpt = cpt.reset_index()\n \n # Use a rather complicated lambda to calculate frequencies\n #if len(qr.drop(target).index) == 0:\n # cpt['Prob'] = cpt.transform(\n # lambda x: (x + alpha) / (x.sum() +(x.count()*alpha)))['Prob']\n #else:\n # cpt['Prob'] = cpt.groupby(list(qr.drop(target).index)).transform(\n # lambda x: (x + alpha) / (x.sum() +(x.count()*alpha))\n # )['Prob']\n \n\n print(cpt)\n return(cpt.loc[cpt['Prob'] == max(cpt['Prob']), target])\n\n\n\n\n \n #call = cpt.set_index(par + [tg]).loc[idx]\n #call = call.reset_index()\n #call = call[tg].loc[call['Prob'] == max(call.Prob)].values[0]\n #return(call)\n\n def test_accuracy(self, test, target = 6):\n data=test\n data['Pred_Prob'] = data.apply(self.get_prob, args=(target,), axis=1)\n data['Predict'] = data.apply(self.call_target, args=(target,), axis=1)\n data['Correct'] = data.apply(lambda x: x[0] == x['Predict'], axis=1)\n return(data)\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# Validation Section: Comment out when no longer needed #\n# #\n################################################################################\n\n# d = dag(10)\n# print(d.dg)\n# full_net = [\n# (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), \n# (0, 6), (0, 7), (0, 8), (0, 9), (1, 2), \n# (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), \n# (1, 8), (1, 9), (2, 3), (2, 4), (2, 5), \n# (2, 6), (2, 7), (2, 8), (2, 9), (3, 4), \n# (3, 5), (3, 6), (3, 7), (3, 8), (3, 9),\n# (4, 5), (4, 6), (4, 7), (4, 8), (4, 9),\n# (5, 6), (5, 7), (5, 8), (5, 9), (6, 7), \n# (6, 8), (6, 9), (7, 8), (7, 9), (8, 9)\n# ]\n\n# for e in full_net:\n# p, c = e\n# d.add(p, c)\n\n\n# print(d.val())\n\n# d.add(4, 2)\n# print(d.val())\n\n# net = [(0, 1), (2, 1), (3, 1), (1, 4), (3, 4), (4, 5), (5, 3)]\n# d = dag(6)\n# for e in net:\n# p, c = e\n# d.add(p, c)\n\n# print(d.val())\n\n# def node_probs(self, data, alpha = 0):\n# \"\"\"\n# Fill CPT with corresponding observational counts\n# \"\"\"\n# cpt = self.cpt\n# var = [c for c in cpt.columns if not c == 'Prob']\n# par = self.parent_idx()\n# if len(par) == 0:\n# par = ['dummy']\n# cpt['dummy'] = 0\n\n \n# # For each case listed in the cpt, count the number of\n# # corresponding rows in the data\n\n# # Store the sum of observations for each case\n# for i in cpt.T.columns:\n# s = 0\n# for j in data.T.columns:\n# m = True\n# for v in var:\n# x = cpt.loc[[i],[v]].values[0][0]\n# y = data.loc[[j], [v]].values[0][0]\n# if x != y:\n# m = False\n# break\n# if m:\n# s = s + 1 \n# cpt.loc[[i], ['Prob']]=s\n# # Use a rather complicated lambda to calculate frequencies\n# cpt['Prob'] = cpt.groupby(par).transform(\n# lambda x: (x + alpha) / (x.sum() +(x.count()*alpha))\n# )['Prob']\n \n# # Dump the dummy group \n# if par[0] == 'dummy':\n# SELF.CPT = cpt.drop(columns = ['dummy'])\n","sub_path":"old_files/network_v2.py","file_name":"network_v2.py","file_ext":"py","file_size_in_byte":26055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"643873659","text":"#Default Imports\nimport numpy as np\n\nipl_matches_array =np.genfromtxt(\"data/ipl_matches_small.csv\", dtype=\"|S50\", skip_header=1, delimiter=\",\")\n\n#Your Solution\ndef get_wicket_delivery_numbers_array(player):\n #l = []\n #for row in ipl_matches_array:\n # if row[-3] == player:\n # delivery = float(row[-12])\n # l.append(delivery)\n\n #all_delivery = np.array(l)\n #return all_delivery\n\n wicket_delivery = ipl_matches_array[:,[-3,-12]]\n #print newdata\n player_delivery = wicket_delivery[wicket_delivery[:, 0] == player]\n all_delivery = player_delivery[:, 1]\n return all_delivery\n \nget_wicket_delivery_numbers_array('ST Jayasuriya')\n","sub_path":"q02_get_wicket_delivery_numbers_array/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"524095099","text":"from astropy import cosmology as cosmo\r\nimport copy\r\nimport json\r\nimport logging\r\nimport numpy as np\r\nimport os\r\nfrom os import path\r\nfrom scipy.stats import norm\r\nfrom typing import Dict, Optional, List\r\n\r\nimport autofit as af\r\nimport autoarray as aa\r\n\r\nfrom autogalaxy.analysis.analysis import AnalysisDataset as AgAnalysisDataset\r\n\r\nfrom autolens.lens.model.preloads import Preloads\r\n\r\nfrom autolens import exc\r\nfrom autolens.lens.model.maker import FitMaker\r\nfrom autolens.lens.model.visualizer import Visualizer\r\nfrom autolens.lens.ray_tracing import Tracer\r\nfrom autolens.lens.model.settings import SettingsLens\r\n\r\nfrom autolens.lens import ray_tracing_util\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\nlogger.setLevel(level=\"INFO\")\r\n\r\n\r\nclass AnalysisLensing:\r\n def __init__(\r\n self, settings_lens: SettingsLens = SettingsLens(), cosmology=cosmo.Planck15\r\n ):\r\n \"\"\"\r\n Analysis classes are used by PyAutoFit to fit a model to a dataset via a non-linear search.\r\n\r\n This abstract Analysis class has attributes and methods for all model-fits which include lensing calculations,\r\n but does not perform a model-fit by itself (and is therefore only inherited from).\r\n\r\n This class stores the Cosmology used for the analysis and settings that control specific aspects of the lensing\r\n calculation, for example how close the brightest pixels in the lensed source have to trace within one another\r\n in the source plane for the model to not be discarded.\r\n\r\n Parameters\r\n ----------\r\n settings_lens\r\n Settings controlling the lens calculation, for example how close the lensed source's multiple images have\r\n to trace within one another in the source plane for the model to not be discarded.\r\n cosmology\r\n The Cosmology assumed for this analysis.\r\n \"\"\"\r\n self.cosmology = cosmology\r\n self.settings_lens = settings_lens or SettingsLens()\r\n\r\n def tracer_for_instance(\r\n self, instance: af.ModelInstance, profiling_dict: Optional[Dict] = None\r\n ) -> Tracer:\r\n \"\"\"\r\n Create a `Tracer` from the galaxies contained in a model instance.\r\n\r\n If PyAutoFit's profiling tools are used with the analsyis class, this function may receive a `profiling_dict`\r\n which times how long each set of the model-fit takes to perform.\r\n\r\n Parameters\r\n ----------\r\n instance\r\n An instance of the model that is fitted to the data by this analysis (whose parameters may have been set\r\n via a non-linear search).\r\n\r\n Returns\r\n -------\r\n Tracer\r\n An instance of the Tracer class that is used to then fit the dataset.\r\n \"\"\"\r\n if hasattr(instance, \"perturbation\"):\r\n instance.galaxies.subhalo = instance.perturbation\r\n\r\n # TODO : Need to think about how we do this without building it into the model attribute names.\r\n # TODO : A Subhalo class that extends the Galaxy class maybe?\r\n\r\n if hasattr(instance.galaxies, \"subhalo\"):\r\n\r\n subhalo_centre = ray_tracing_util.grid_at_redshift_from(\r\n galaxies=instance.galaxies,\r\n redshift=instance.galaxies.subhalo.redshift,\r\n grid=aa.Grid2DIrregular(grid=[instance.galaxies.subhalo.mass.centre]),\r\n cosmology=self.cosmology,\r\n )\r\n\r\n instance.galaxies.subhalo.mass.centre = tuple(subhalo_centre.in_list[0])\r\n\r\n return Tracer.from_galaxies(\r\n galaxies=instance.galaxies,\r\n cosmology=self.cosmology,\r\n profiling_dict=profiling_dict,\r\n )\r\n\r\n\r\nclass AnalysisDataset(AgAnalysisDataset, AnalysisLensing):\r\n def __init__(\r\n self,\r\n dataset,\r\n positions: aa.Grid2DIrregular = None,\r\n hyper_dataset_result=None,\r\n cosmology=cosmo.Planck15,\r\n settings_pixelization: aa.SettingsPixelization = None,\r\n settings_inversion: aa.SettingsInversion = None,\r\n settings_lens: SettingsLens = None,\r\n ):\r\n \"\"\"\r\n Analysis classes are used by PyAutoFit to fit a model to a dataset via a non-linear search.\r\n\r\n This abstract Analysis class has attributes and methods for all model-fits which fit the model to a dataset\r\n (e.g. imaging or interferometer data).\r\n\r\n This class stores the Cosmology used for the analysis and settings that control aspects of the calculation,\r\n including how pixelizations, inversions and lensing calculations are performed.\r\n\r\n Parameters\r\n ----------\r\n dataset\r\n The imaging, interferometer or other dataset that the model if fitted too.\r\n positions\r\n Image-pixel coordinates in arc-seconds corresponding to the multiple images of the lensed source galaxy.\r\n If the `settings_lens` attribute has a `positions_threshold`, these positions must trace within this\r\n threshold of one another in the source-plane or else the model is discarded.\r\n cosmology\r\n The AstroPy Cosmology assumed for this analysis.\r\n settings_pixelization\r\n settings controlling how a pixelization is fitted during the model-fit, for example if a border is used\r\n when creating the pixelization.\r\n settings_inversion\r\n Settings controlling how an inversion is fitted during the model-fit, for example which linear algebra\r\n formalism is used.\r\n settings_lens\r\n Settings controlling the lens calculation, for example how close the lensed source's multiple images have\r\n to trace within one another in the source plane for the model to not be discarded.\r\n \"\"\"\r\n\r\n super().__init__(\r\n dataset=dataset,\r\n hyper_dataset_result=hyper_dataset_result,\r\n cosmology=cosmology,\r\n settings_pixelization=settings_pixelization,\r\n settings_inversion=settings_inversion,\r\n )\r\n\r\n AnalysisLensing.__init__(\r\n self=self, settings_lens=settings_lens, cosmology=cosmology\r\n )\r\n\r\n self.positions = positions\r\n\r\n self.settings_lens = settings_lens or SettingsLens()\r\n\r\n self.preloads = Preloads()\r\n\r\n def set_preloads(self, paths: af.DirectoryPaths, model: af.Collection):\r\n \"\"\"\r\n It is common for the model to have components whose parameters are all fixed, and thus the way that component\r\n fits the data does not change. For example, if all parameter associated with the light profiles of galaxies\r\n in the model are fixed, the image generated from these galaxies will not change irrespective of the model\r\n parameters chosen by the non-linear search.\r\n\r\n Preloading exploits this to speed up the log likelihood function, by inspecting the model and storing in memory\r\n quantities that do not change. For the example above, the image of all galaxies would be stored in memory and\r\n to perform every fit in the `log_likelihood_funtion`.\r\n\r\n This function sets up all preload quantities, which are described fully in the `preloads` modules. This\r\n occurs directly before the non-linear search begins, to ensure the model parameterization is fixed.\r\n\r\n Parameters\r\n ----------\r\n paths\r\n The PyAutoFit paths object which manages all paths, e.g. where the non-linear search outputs are stored,\r\n visualization and the pickled objects used by the aggregator output by this function.\r\n model\r\n The PyAutoFit model object, which includes model components representing the galaxies that are fitted to\r\n the imaging data.\r\n \"\"\"\r\n\r\n os.makedirs(paths.profile_path, exist_ok=True)\r\n\r\n fit_maker = FitMaker(model=model, fit_func=self.fit_func)\r\n\r\n fit_0 = fit_maker.fit_via_model(unit_value=0.45)\r\n fit_1 = fit_maker.fit_via_model(unit_value=0.55)\r\n\r\n if fit_0 is None or fit_1 is None:\r\n self.preloads = Preloads(failed=True)\r\n else:\r\n self.preloads = Preloads.setup_all_via_fits(fit_0=fit_0, fit_1=fit_1)\r\n self.preloads.check_via_fit(fit=fit_0)\r\n\r\n self.preloads.output_info_to_summary(file_path=paths.profile_path)\r\n\r\n def check_and_replace_hyper_images(self, paths: af.DirectoryPaths):\r\n \"\"\"\r\n Using a the result of a previous model-fit, a hyper-dataset can be set up which adapts aspects of the model\r\n (e.g. the pixelization, regularization scheme) to the properties of the dataset being fitted.\r\n\r\n If the model-fit is being resumed from a previous run, this function checks that the model image and galaxy\r\n images used to set up the hyper-dataset are identical to those used previously. If they are not, it replaces\r\n them with the previous hyper image. This ensures consistency in the log likelihood function.\r\n\r\n Parameters\r\n ----------\r\n paths\r\n The PyAutoFit paths object which manages all paths, e.g. where the non-linear search outputs are stored,\r\n visualization and the pickled objects used by the aggregator output by this function.\r\n \"\"\"\r\n try:\r\n hyper_model_image = paths.load_object(\"hyper_model_image\")\r\n\r\n if np.max(abs(hyper_model_image - self.hyper_model_image)) > 1e-8:\r\n\r\n logger.info(\r\n \"ANALYSIS - Hyper image loaded from pickle different to that set in Analysis class.\"\r\n \"Overwriting hyper images with values loaded from pickles.\"\r\n )\r\n\r\n self.hyper_model_image = hyper_model_image\r\n\r\n hyper_galaxy_image_path_dict = paths.load_object(\r\n \"hyper_galaxy_image_path_dict\"\r\n )\r\n self.hyper_galaxy_image_path_dict = hyper_galaxy_image_path_dict\r\n\r\n except (FileNotFoundError, AttributeError, KeyError):\r\n pass\r\n\r\n def modify_after_fit(\r\n self, paths: af.DirectoryPaths, model: af.AbstractPriorModel, result: af.Result\r\n ) -> \"AnalysisDataset\":\r\n \"\"\"\r\n Call functions that perform tasks after a model-fit is completed, for example ensuring the figure of merit\r\n has not changed from previous estimates and resetting preloads.\r\n\r\n Parameters\r\n ----------\r\n paths\r\n The PyAutoFit paths object which manages all paths, e.g. where the non-linear search outputs are stored,\r\n visualization and the pickled objects used by the aggregator output by this function.\r\n model\r\n The PyAutoFit model object, which includes model components representing the galaxies that are fitted to\r\n the imaging data.\r\n result\r\n The result of the model fit that has just been completed.\r\n \"\"\"\r\n\r\n self.output_or_check_figure_of_merit_sanity(paths=paths, result=result)\r\n self.preloads.reset_all()\r\n\r\n return self\r\n\r\n def log_likelihood_cap_from(\r\n self, stochastic_log_likelihoods_json_file: str\r\n ) -> float:\r\n \"\"\"\r\n Certain `Inversion`'s have stochasticity in their log likelihood estimate (e.g. due to how different KMeans\r\n seeds change the pixelization constructed by a `VoronoiBrightnessImage` pixelization).\r\n\r\n A log likelihood cap can be applied to model-fits performed using these `Inversion`'s to improve error and\r\n posterior estimates. This log likelihood cap is estimated from a list of stochastic log likelihoods, where\r\n these log likelihoods are computed using the same model but with different KMeans seeds.\r\n\r\n This function computes the log likelihood cap of a model-fit by loading a set of stochastic log likelihoods\r\n from a .json file and fitting them with a 1D Gaussian. The cap is the mean value of this Gaussian.\r\n\r\n Parameters\r\n ----------\r\n stochastic_log_likelihoods_json_file\r\n A .json file which loads an ndarray of stochastic log likelihoods, which are likelihoods computed using the\r\n same model but with different KMeans seeds.\r\n\r\n Returns\r\n -------\r\n float\r\n A log likelihood cap which is applied in a stochastic model-fit to give improved error and posterior\r\n estimates.\r\n \"\"\"\r\n try:\r\n with open(stochastic_log_likelihoods_json_file, \"r\") as f:\r\n stochastic_log_likelihoods = np.asarray(json.load(f))\r\n except FileNotFoundError:\r\n raise exc.AnalysisException(\r\n \"The file 'stochastic_log_likelihoods.json' could not be found in the output of the model-fitting results\"\r\n \"in the analysis before the stochastic analysis. Rerun PyAutoLens with `stochastic_outputs=True` in the\"\r\n \"`general.ini` configuration file.\"\r\n )\r\n\r\n mean, sigma = norm.fit(stochastic_log_likelihoods)\r\n\r\n return mean\r\n\r\n def stochastic_log_likelihoods_for_instance(self, instance) -> List[float]:\r\n raise NotImplementedError()\r\n\r\n def save_stochastic_outputs(self, paths: af.DirectoryPaths, samples: af.Samples):\r\n \"\"\"\r\n Certain `Inversion`'s have stochasticity in their log likelihood estimate (e.g. due to how different KMeans\r\n seeds change the pixelization constructed by a `VoronoiBrightnessImage` pixelization).\r\n\r\n This function computes the stochastic log likelihoods of such a model, which are the log likelihoods computed\r\n using the same model but with different KMeans seeds.\r\n\r\n It outputs these stochastic likelihoods to a format which can be loaded via PyAutoFit's database tools, and\r\n may also be loaded if this analysis is extended with a stochastic model-fit that applies a log likelihood cap.\r\n\r\n This function also outputs visualization showing a histogram of the stochastic likelihood distribution.\r\n\r\n Parameters\r\n ----------\r\n paths\r\n The PyAutoFit paths object which manages all paths, e.g. where the non-linear search outputs are stored,\r\n visualization and the pickled objects used by the aggregator output by this function.\r\n samples\r\n A PyAutoFit object which contains the samples of the non-linear search, for example the chains of an MCMC\r\n run of samples of the nested sampler.\r\n \"\"\"\r\n stochastic_log_likelihoods_json_file = path.join(\r\n paths.output_path, \"stochastic_log_likelihoods.json\"\r\n )\r\n\r\n try:\r\n with open(stochastic_log_likelihoods_json_file, \"r\") as f:\r\n stochastic_log_likelihoods = np.asarray(json.load(f))\r\n except FileNotFoundError:\r\n instance = samples.max_log_likelihood_instance\r\n stochastic_log_likelihoods = self.stochastic_log_likelihoods_for_instance(\r\n instance=instance\r\n )\r\n\r\n if stochastic_log_likelihoods is None:\r\n return\r\n\r\n with open(stochastic_log_likelihoods_json_file, \"w\") as outfile:\r\n json.dump(\r\n [float(evidence) for evidence in stochastic_log_likelihoods], outfile\r\n )\r\n\r\n paths.save_object(\"stochastic_log_likelihoods\", stochastic_log_likelihoods)\r\n\r\n visualizer = Visualizer(visualize_path=paths.image_path)\r\n\r\n visualizer.visualize_stochastic_histogram(\r\n stochastic_log_likelihoods=stochastic_log_likelihoods,\r\n max_log_evidence=np.max(samples.log_likelihood_list),\r\n histogram_bins=self.settings_lens.stochastic_histogram_bins,\r\n )\r\n\r\n @property\r\n def no_positions(self):\r\n\r\n analysis = copy.deepcopy(self)\r\n\r\n analysis.positions = None\r\n analysis.settings_lens.positions_threshold = None\r\n\r\n return analysis\r\n\r\n @property\r\n def fit_func(self):\r\n raise NotImplementedError\r\n","sub_path":"autolens/lens/model/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":16045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"240349439","text":"# Author: Greg Goodrum\n# Course: BIOL 6750 with Dr. Will Pearse\n# Section: 8 - Introduction to Python\n# Exercise 8\n# ----------------\n\n\n# ---- Question 1 ----\n# 1(a) Write a loop that prints out the numbers from 20 to 10\n# range(start value, end value, step interval)\nfor i in (range(20, 9, -1)):\n print(i)\nprint(\"End; 1(a)\")\n\n# 1(b) Write a list comprehension that returns the numbers from 20 to 10\n# [operation to perform(iteration to perform on) for definition of values]\ndescending_comprehension = [print(each) for each in range(20,9,-1)]\nprint(\"End: 1(b)\")\n\n\n# ---- Question 2 -----\n# 2(a) Write a loop that prints out only the numbers from 20 to 10 that are even\nfor i in (range(20,9,-2)):\n print(i)\nprint(\"End: 2(a)\")\n\n# alternative version using remainder and conditional statement\nfor i in range(20,9,-1):\n if i%2 == 0:\n print(i)\nprint(\"End: 2(a)\")\n\n# 2(b) Write a list comprehension that prints out only the numbers from 20 to 10 that are even\neven_descending_comprehension = [print(each) for each in range(20,9,-2)]\nprint(\"End: 2(b)\")\n\n# alternative version using remainder and conditional statement\neven_descending_comprehension_remainder = [print(each) for each in range(20,9,-1) if each%2 == 0]\nprint(\"End: 2(b)\")\n\n\n# ---- Question 3 ----\n# 3 Write a function that calculates whether a number is a prime number\ndef check_prime(x):\n if x%2 == 0:\n print(str(x) + \" is not prime.\")\n else:\n print(str(x) + \" is prime.\")\n\n\ncheck_prime(10)\ncheck_prime(13)\nprint(\"End: 3\")\n\n\n# ---- Question 4 ----\n# 4 Write a function that calculates population size at any time for any values of it's parameters\n# Gompertz curve: y(t) = a.e^(-b.e^(-c.t))\n# y = population size, t = time, a, b, and c = parameters, e = exponential function\n\ndef gompertz_funct(time,parameter_a,parameter_b,parameter_c):\n import math\n popul_size_time = parameter_a * math.exp((-1.0 * parameter_b) * math.exp((-1.0 * parameter_c) * time))\n print(popul_size_time)\n\n\ngompertz_funct(10.0, 5.0, 3.0, 7.0)\nprint(\"End: 4\")\n\n\n# ---- Question 5 ----\n# 5(a) Implement a point class that holds x and y information for a point in space.\n\nclass Point:\n def __init__(self, xcoor, ycoor):\n self.xcoor, self.ycoor = xcoor, ycoor\n\n def pointtest(self):\n return \"Point has an xcoor of \" + str(self.xcoor) + \" and a ycoor of \" + str(self.ycoor)\n\n\nPt1 = Point(5,7)\nPt2 = Point(3,3)\nprint(Pt1.pointtest())\nprint(Pt2.pointtest())\nprint(\"End: 5(a)\")\n\n# 5(b) Write a distance method that calculates the distance between two points in space\n\nclass Point:\n def __init__(self, xcoor, ycoor):\n self.xcoor, self.ycoor = xcoor, ycoor\n\n def pointtest(self):\n print(\"Point has an xcoor of \" + str(self.xcoor) + \" and a ycoor of \" + str(self.ycoor))\n\n def pointdist(self, pnt2):\n import math\n ydist = pnt2.ycoor - self.ycoor\n xdist = pnt2.xcoor - self.xcoor\n distance = math.sqrt((ydist**2) + (xdist**2))\n print(\"The distance between the points is \" + str(distance) + \" units.\")\n\n\nPt1 = Point(5,7)\nPt2 = Point(3,3)\nprint(Pt1.pointdist(Pt2))\nprint(\"End: 5(b)\")\n\n\n# 5(c) Implement a line class that takes two point objects and makes a line between them.\n\nclass Line:\n def __init__(self, point1, point2):\n self.xstart, self.xend, self.ystart, self.yend = point1.xcoor, point2.xcoor, point1.ycoor, point2.ycoor\n\n\ndef distance_line(self):\n import math\n ydist = self.yend - self.ystart\n xdist = self.xend - self.xstart\n distance = math.sqrt((ydist**2) + (xdist**2))\n return \"The distance between the points is \" + str(distance) + \" units.\"\n\n\nLine1 = Line(Pt1, Pt2)\nprint(distance_line(Line1))\nprint(\"End: 5(c)\")\n\n\n# ---- Question 6 ----\n# 6. Write a function that loads a text file, loops over the lines in it, and prints out the fifth\n# character on the fifth line of that file.\n# Hint:\n# with open(\"name_of_file\") as handle:\n# for line in handle:\n# Do Something\n# Note: .txt and .rft files are interpreted differently in python, .txt behaves more reasonably\n\n# Script that prints out the fifth line in the text file\n#def fifthchar_fifthline(filepath):\n #with open(filepath) as txtfile:\n #for line in txtfile:\n #print(line)\n\n# Prints 5th letter for every line\n#def fifthchar_fifthline(filepath):\n #with open(filepath) as txtfile:\n #for line in txtfile:\n #print(line[4:5])\n\n# Prints 5th letter for the 5th line\ndef fifthchar_fifthline(filepath):\n with open(filepath) as txtfile:\n for i, line in enumerate(txtfile):\n if i == 4:\n print(line[4:5])\n\n\n# Test code for checking success of function\n# I have included a copy of the text file used for this example in my GitHub repository as 'TextFile_for_Assignment8_Q5'\n#fifthchar_fifthline(\"/Users/gregorygoodrum/USU/Coursework/Programming for Biologist (BIOL 6750)/Extra/TextFile_for_Python1.txt\")\n\nprint(\"End: 6\")\nprint('---- END: Exercise 8 ----')","sub_path":"BIOL_6750_GregGoodrum_Assignment8.py","file_name":"BIOL_6750_GregGoodrum_Assignment8.py","file_ext":"py","file_size_in_byte":4970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"361309303","text":"import mysql.connector as mysql\nimport argparse\nimport logging\nimport json\nimport requests\nimport sys\nimport datetime\n\nappName = 'mariadb_replication_check'\n\nif False:\n try:\n from systemd.journal import JournalHandler\n logger = logging.getLogger(appName)\n logger.addHandler(JournalHandler(SYSLOG_IDENTIFIER=appName))\n except ImportError:\n logger = logging.getLogger(appName)\n stdout = logging.StreamHandler(sys.stdout)\n logger.addHandler(stdout)\n finally:\n logger.setLevel(logging.INFO)\nelse:\n logger = logging.getLogger(appName)\n stdout = logging.StreamHandler(sys.stdout)\n logger.addHandler(stdout)\n logger.setLevel(logging.DEBUG)\n\nSLAVE_IO_RUNNING = 10\nSLAVE_SQL_RUNNING = 11\nSECONDS_BEHIND_MASTER = 32\n\ndef sendAlert(key, description, status):\n timestamp = datetime.datetime.now(datetime.timezone.utc).isoformat()\n body = {\n \"payload\": {\n \"summary\": \"Mariadb replica is not working correctly\",\n \"timestamp\": timestamp,\n \"source\": appName,\n \"severity\": \"critical\",\n \"custom_details\": {\n \"description\": description\n }\n },\n \"routing_key\": key,\n \"dedup_key\": \"mariadb-deplica-check\",\n \"event_action\": status\n }\n headers = {\"Content-Type\": \"application/json\"}\n resp = requests.post(\"https://events.pagerduty.com/v2/enqueue\", headers = headers, data = json.dumps(body))\n if resp.status_code == 202:\n #logger.warning(\"pagerduty alert sent: Container %s needs updating\"%container)\n pass\n else:\n logger.error(\"Failed to send pagerduty alert: Container %s needs updating\"%container)\n\ndef main():\n parser = argparse.ArgumentParser(description='Check mariadb slave status')\n parser.add_argument('--host', metavar='HOST', default=\"127.0.0.1\",\n help='host')\n parser.add_argument('--user', metavar='USER', required=True,\n help='user')\n parser.add_argument('--password', metavar='PASSWORD', required=True,\n help='password')\n parser.add_argument('--port', metavar='PORT', type=int, default=3306,\n help='port')\n parser.add_argument('--pdkey', metavar='PDKEY', required=True,\n help='pagerduty routing key')\n args = parser.parse_args()\n\n\n try:\n db = mysql.connect(\n host = args.host,\n user = args.user,\n passwd = args.password,\n database = \"INFORMATION_SCHEMA\"\n )\n except Exception as e:\n description = str(e)\n sendAlert(args.pdkey, description, \"trigger\")\n sys.exit()\n\n cursor = db.cursor()\n\n try:\n query = \"SHOW REPLICA STATUS\"\n cursor.execute(query)\n records = cursor.fetchall()\n except Exception as e:\n description = str(e)\n sendAlert(args.pdkey, description, \"trigger\")\n else:\n record = records[0]\n names = cursor.description\n\n description = \"Replication is not working the way it should be:\\n\"\n description += \"%s: %s\\n\"%(names[SLAVE_IO_RUNNING][0], record[SLAVE_IO_RUNNING])\n description += \"%s: %s\\n\"%(names[SLAVE_SQL_RUNNING][0], record[SLAVE_SQL_RUNNING])\n description += \"%s: %s\\n\"%(names[SECONDS_BEHIND_MASTER][0], record[SECONDS_BEHIND_MASTER])\n\n if record[SLAVE_IO_RUNNING] != \"Yes\" or record[SLAVE_SQL_RUNNING] != \"Yes\" or int(record[SECONDS_BEHIND_MASTER])>60:\n logger.error(\"Alert triggered:\\n\" + description)\n sendAlert(args.pdkey, description, \"trigger\")\n else:\n logger.debug(\"replication status (debug): \\n\" + description)\n sendAlert(args.pdkey, description, \"resolve\")\n\nif __name__ == '__main__':\n main()\n","sub_path":"mariadb_replication_check.py","file_name":"mariadb_replication_check.py","file_ext":"py","file_size_in_byte":3789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"335584694","text":"# Author: Zaid Neurothrone\n\nfrom colorama import init, deinit, Fore\nfrom bs4 import BeautifulSoup\nfrom collections import deque\nimport requests\nimport os\nimport sys\n\n\nclass Menu:\n BACK = \"back\"\n EXIT = \"exit\"\n\n\nclass Browser:\n tags_list = [\"title\", \"p\", \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\", \"a\", \"ul\", \"ol\", \"li\"]\n\n def __init__(self):\n self.saved_websites = list()\n self.history_stack = deque()\n self.path = os.getcwd()\n self.setup_save_dir()\n init() # Initialize colorama\n\n def setup_save_dir(self):\n args = sys.argv\n try:\n dir_name = args[1]\n if dir_name is not None:\n self.path += f\"/{dir_name}\"\n except IndexError:\n self.path += \"/tb_tabs\"\n\n if not os.path.exists(self.path):\n os.mkdir(self.path)\n\n def save_website(self, short_url, html_text):\n self.history_stack.append(short_url)\n with open(f\"{self.path}/{short_url}\", \"w\", encoding=\"utf-8\") as out_file:\n parsed_text = Browser.parse_html(html_text)\n # TODO: Test if writes correctly\n for line in parsed_text:\n out_file.write(line + \"\\n\")\n\n def load_website(self, short_url):\n \"\"\"Reads in and saves the website to the dictionary.\n \"\"\"\n with open(f\"{self.path}/{short_url}\", \"r\") as in_file:\n Browser.print_parsed_website(in_file.read())\n\n @staticmethod\n def parse_html(html_text):\n soup = BeautifulSoup(html_text, \"html.parser\")\n parser = soup.find_all(Browser.tags_list, text=True)\n parsed_text = []\n for line in parser:\n if line.get(\"href\"):\n parsed_text.append(Fore.BLUE + line.get_text().strip())\n else:\n parsed_text.append(Fore.BLACK + line.get_text().strip())\n return parsed_text\n\n @staticmethod\n def print_parsed_website(text):\n for line in text:\n if line:\n print(line)\n\n @staticmethod\n def is_url_valid(url):\n if url.rfind(\".\") == -1:\n return False\n return True\n\n @staticmethod\n def has_url_protocol(url):\n if url.startswith(\"https://\"):\n return True\n return False\n\n @staticmethod\n def append_protocol(url):\n return \"https://\" + url\n\n @staticmethod\n def remove_protocol(url):\n return url.split(\"https://\")[1]\n\n def access_website(self, url):\n try:\n request = requests.get(url)\n except requests.exceptions.ConnectionError:\n print(\"Incorrect URL\")\n else:\n if request:\n self.saved_websites.append(self.remove_protocol(url))\n parsed_text = Browser.parse_html(request.text)\n Browser.print_parsed_website(parsed_text)\n self.save_website(Browser.remove_protocol(url), request.text)\n\n def process_search_input(self, user_input):\n url = user_input\n if not Browser.is_url_valid(url):\n print(\"Incorrect URL\")\n return\n\n if not Browser.has_url_protocol(url):\n if url in self.saved_websites: # If website saved to file, render it\n self.load_website(url)\n return\n\n url = Browser.append_protocol(url) # Else access website on the internet and render it\n self.access_website(url)\n\n\ndef run():\n browser = Browser()\n\n while True:\n user_input = input().lower().strip()\n\n if user_input == Menu.EXIT:\n break\n\n if user_input == Menu.BACK:\n if len(browser.history_stack) > 1:\n browser.history_stack.pop()\n short_url = browser.history_stack.pop()\n browser.load_website(short_url)\n else:\n browser.process_search_input(user_input)\n\n\nif __name__ == \"__main__\":\n run()\n deinit() # Deactivate colorama\n","sub_path":"Text-Based Browser/task/browser/browser.py","file_name":"browser.py","file_ext":"py","file_size_in_byte":3938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"277487008","text":"#-*- coding:utf-8 -*-\n\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nimport web\nimport json\nimport copy\nimport time\nimport pymysql\nimport pymongo\nimport requests\nfrom bson import json_util\n\nurls = (\n '/','restr',\n '/order','order',\n '/menu','menu',\n '/down','down',\n '/pay','pay',\n '/getOpenid', 'getOpenid'\n)\n\napp = web.application(urls, globals())\n# render = web.template.render('templates/')\ndb = web.database(dbn='mysql',user='beta1025',db='wx',host=\"152.136.15.161\",pw=\"123456\", charset='gbk')\nmyclient = pymongo.MongoClient('127.0.0.1',27017)\nmydb = myclient['waimai']\n# db = MySQLdb.connect(host=\"152.136.15.161\", user=\"beta1025\", password=\"123456\", db=\"stu\" )\nclass restr:\n def GET(self):\n return json.dumps(list(db.select('wx2')))\n\nclass menu:\n def GET(self):\n return json_util.dumps(list(mydb['德克士'].find()))\n\nclass order:\n def GET(self):\n return json.dumps(list(db.select('orderlist')))\n\nclass pay:\n def GET(self):\n i = web.input()\n time1 = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))\n # 优化格式化化版本\n\n print(i)\n\t\t\nclass getOpenid:\n def GET(self):\n i = web.input()\n response = requests.get('https://api.weixin.qq.com/sns/jscode2session?appid=' + i.appId.decode(\"utf-8\") + '&secret=' + i.secret.decode(\"utf-8\") + '&js_code=' + i.code.decode(\"utf-8\") + '&grant_type=authorization_code')\n return response\n\nif __name__ == \"__main__\":\n app.run()\n\n\n","sub_path":"服务器端python程序.py","file_name":"服务器端python程序.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"64632643","text":"import sys\n#\n# >>> Escriba el codigo del mapper a partir de este punto <<<\n\nif __name__ == '__main__':\n\n ckey = None\n total = 0\n totmin = 0\n\n ##\n ## cada linea de texto recibida es una\n ## entrada clave \\tabulador valor\n ##\n for line in sys.stdin:\n\n clave, valor = line.split('\\t')\n #valor = int(valor)\n\n if clave == ckey:\n \ttotal = max(valor, total)\n \ttotmin = min(valor, totmin)\n else:\n if ckey is not None:\n sys.stdout.write(\"{}\\t{}\\t{}\\n\".format(ckey, total, totmin))\n\n ckey = clave\n total = valor\n totmin = valor\n\n sys.stdout.write(\"{}\\t{}\\t{}\\n\".format(ckey, total, totmin))\n","sub_path":"01-hadoop-50/q06-10/reducer.py","file_name":"reducer.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"176377179","text":"import requests, re\n\ndef youku(moviename):\n url = moviename\n title = None\n if \"//\" in url:\n if url == \"//\":\n title,url = init()\n else:\n url = url.split('?')[0]\n title = parase(url) \n elif url.strip() == \"\":\n title,url = init()\n else:\n if \".com\" and \"www.\" in url:\n title = moviename\n else:\n from getmovieurl import getmovieurl\n newurl = getmovieurl(moviename)\n title = moviename\n if newurl == \"NOURL\":\n response = requests.get(\"https://so.youku.com/search_video/q_{}\".format(url))\n text = response.text\n text = text.replace('\\\\', '')\n title = re.findall(r'

    .*?', text, re.DOTALL)[0]\n url = re.findall(r'
    .*?', text, re.DOTALL)\n if len(url) == 0:\n url = \"\"\n else:\n url = url[0]\n if \"v.youku.com\" not in url:\n if \"v.qq.com\" in url:\n pass\n else:\n url = parase_tencent(moviename)\n else:\n url = newurl\n \n return (title,url)\n\n\ndef parase(url):\n resp = requests.get(url)\n text = resp.text\n text = text.replace('\\\\', '')\n if \"youku\" in url:\n title = re.findall(r'
    .*?(.*?)', text, re.DOTALL)[0]\n elif \"iqiyi\" in url:\n title = re.findall(r'

    .*?(.*?)', text, re.DOTALL)[0]\n elif \"v.qq.com\" in url:\n text1 = resp.content.decode('utf-8')\n text1 = text1.replace('\\\\', '')\n title = re.findall(r'

    .*?(.*?)', text1, re.DOTALL)[0]\n elif \"www.le.com\" in url:\n title = re.findall(r'
    .*?(.*?)', text, re.DOTALL)[0]\n else:\n title = url\n return title\n\ndef parase_tencent(name):\n orig_url = \"https://v.qq.com/x/search/?q={}\".format(name)\n response = requests.get(orig_url)\n text = response.text\n url = re.findall(r'
    .*?', text, re.DOTALL)\n if len(url) == 0:\n url = \"no\"\n else:\n url = url[0]\n if \"detail\" in url:\n resp = requests.get(url)\n content = resp.text\n url = re.findall(r'
    .*?', content, re.DOTALL)[0]\n return url\n\ndef init():\n lis = ('「DOTA伍声2009」大酒神精彩操作','http://www.iqiyi.com/w_19rrhqrvql.html')\n title = lis[0]\n url = lis[1]\n return (title,url)\n\n","sub_path":"youku.py","file_name":"youku.py","file_ext":"py","file_size_in_byte":2778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"242150913","text":"ptBr = dict(\n\n #Mensagens de Erro Tarefa\n eTaskCreate=\"Erro ao criar Tarefa.\",\n eTaskDelete=\"Erro ao deletar Tarefa.\",\n eTaskUpdate=\"Erro ao atualizar Tarefa.\",\n eTaskComplete=\"Erro ao completar Tarefa.\",\n\n #Mensagens de Erro Action\n eActionCreate=\"Erro ao criar Ação.\",\n eActionDelete=\"Erro ao deletar Ação.\",\n eActionUpdate=\"Erro ao atualizar Ação.\",\n eActionComplete=\"Erro ao completar Ação.\",\n \n # Mensagens de Sucesso Tareta\n taskCreate=\"Tarefa criada com Sucesso.\",\n taskUpdate=\"Tarefa atualizada com Sucesso.\",\n taskDelete=\"Tarefa deletada com Sucesso.\",\n taskComplete=\"Tarefa completada com Sucesso.\",\n \n\n # Mensagens de Sucesso Action\n actionCreate=\"Ação criada com Sucesso.\",\n actionUpdate=\"Ação alizada com Sucesso.\",\n actionDelete=\"Ação deletada com Sucesso.\",\n actionComplete=\"Ação completada com Sucesso.\"\n\n)\n\ncodes = dict(success=0, validation=1, db=2)\n","sub_path":"server/app/core/return_messages.py","file_name":"return_messages.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"299275060","text":"import gi\ngi.require_version(\"Gtk\", \"3.0\")\nfrom gi.repository import Gtk\n\nfrom epregressions.structures import CompletedStructure, TestEntry, EndErrSummary\n\n\nclass ResultsTreeRoots:\n # probably refactor this elsewhere but it's a start\n NumRun = \"Cases run:\"\n Success1 = \"Case 1 Successful runs:\"\n NotSuccess1 = \"Case 1 Unsuccessful run:\"\n Success2 = \"Case 2 Successful runs:\"\n NotSuccess2 = \"Case 2 Unsuccessful run:\"\n FilesCompared = \"Files compared:\"\n BigMath = \"Files with BIG mathdiffs:\"\n SmallMath = \"Files with small mathdiffs:\"\n BigTable = \"Files with BIG tablediffs:\"\n SmallTable = \"Files with small tablediffs:\"\n Textual = \"Files with textual diffs:\"\n\n @staticmethod\n def list_all():\n return [\n ResultsTreeRoots.NumRun,\n ResultsTreeRoots.Success1,\n ResultsTreeRoots.NotSuccess1,\n ResultsTreeRoots.Success2,\n ResultsTreeRoots.NotSuccess2,\n ResultsTreeRoots.FilesCompared,\n ResultsTreeRoots.BigMath,\n ResultsTreeRoots.SmallMath,\n ResultsTreeRoots.BigTable,\n ResultsTreeRoots.SmallTable,\n ResultsTreeRoots.Textual\n ]\n\n\nclass MyWindow(Gtk.Window):\n\n def __init__(self):\n Gtk.Window.__init__(self, title=\"Hello World\")\n\n self.box = Gtk.Box(spacing=6)\n self.add(self.box)\n\n self.button1 = Gtk.Button(label=\"Add Contents to Tree\")\n self.button1.connect(\"clicked\", self.on_button1_clicked)\n self.box.pack_start(self.button1, True, True, 0)\n\n self.results_list_store = Gtk.TreeStore(str)\n self.results_parent = {}\n self.results_child = {}\n for parent_root in ResultsTreeRoots.list_all():\n self.results_parent[parent_root] = self.results_list_store.append(None, [parent_root])\n self.results_child[parent_root] = None\n\n self.tree_view = Gtk.TreeView(model=self.results_list_store)\n tree_view_column = Gtk.TreeViewColumn('Results Summary')\n\n cell = Gtk.CellRendererText()\n tree_view_column.pack_start(cell, True)\n tree_view_column.add_attribute(cell, 'text', 0)\n self.tree_view.append_column(tree_view_column)\n\n self.box.pack_start(self.tree_view, True, True, 0)\n\n def on_button1_clicked(self, widget):\n results = CompletedStructure('/a/', '/b/', '/c/', '/d/', '/e/')\n this_entry = TestEntry('file.idf', 'file.epw')\n this_entry.add_summary_result(\n EndErrSummary(\n EndErrSummary.STATUS_SUCCESS,\n 1,\n EndErrSummary.STATUS_SUCCESS,\n 2\n ))\n results.add_test_entry(this_entry)\n root_and_files = {\n ResultsTreeRoots.NumRun: results.all_files,\n ResultsTreeRoots.Success1: results.success_case_a,\n ResultsTreeRoots.NotSuccess1: results.failure_case_a,\n ResultsTreeRoots.Success2: results.success_case_b,\n ResultsTreeRoots.NotSuccess2: results.failure_case_b,\n ResultsTreeRoots.FilesCompared: results.total_files_compared,\n ResultsTreeRoots.BigMath: results.big_math_diffs,\n ResultsTreeRoots.SmallMath: results.small_math_diffs,\n ResultsTreeRoots.BigTable: results.big_table_diffs,\n ResultsTreeRoots.SmallTable: results.small_table_diffs,\n ResultsTreeRoots.Textual: results.text_diffs\n }\n for tree_root in root_and_files:\n file_lists = root_and_files[tree_root]\n this_file_list_count = len(file_lists.descriptions)\n if self.results_child[tree_root]: # pragma: no cover - I'd try to test this if the tree was its own class\n self.results_list_store.remove(self.results_child[tree_root])\n self.results_child[tree_root] = self.results_list_store.append(\n self.results_parent[tree_root],\n [str(this_file_list_count)]\n )\n this_path = self.results_list_store.get_path(self.results_parent[tree_root])\n self.tree_view.expand_row(this_path, False)\n for result in file_lists.descriptions: # pragma: no cover\n self.results_list_store.append(self.results_child[tree_root], [result])\n\n\nwin = MyWindow()\nwin.connect(\"destroy\", Gtk.main_quit)\nwin.show_all()\nGtk.main()\n","sub_path":"epregressions/try_treeview.py","file_name":"try_treeview.py","file_ext":"py","file_size_in_byte":4368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"468214995","text":"class PalindromicSubstring:\n def isPalindrome(self,s):\n if s == s[::-1] :\n return True\n else :\n return False\n \n def longestPalindrome(self, s):\n if len(s) == 0 : return \"\"\n returnS = \"\"\n if self.isPalindrome(s): return s\n for i in range(len(s)):\n x = len(s)\n while x > 0:\n if self.isPalindrome(s[i:x]) and len(s[i:x]) > len(returnS):\n returnS = s[i:x]\n x -= 1\n return returnS\n","sub_path":"PalindromicSubstring.py","file_name":"PalindromicSubstring.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"191024761","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pickle\n\nname = '2D_section_B8_SSA'\npickleName = name + '.pickle'\nwith open(pickleName, 'rb') as f:\n dump = pickle.load(f) \nx, z, y, Ix, Iz = dump\n\nresult1 = np.zeros([len(y),len(x)])\nfor i in range(len(Ix)):\n result1[i,:] =np.array(Ix[i])\n \nT1 = np.log(result1.T)\n#T1 = result1.T\nz = z*1e3 \nx = x*1e3\ny = y*1e3\n\n#vmin, vmax = 1e13, max(max(Iz))\n\nplt.figure(1)\nim =plt.imshow(T1, interpolation='bicubic', cmap='jet',\n extent=[min(y),max(y),min(x),max(x)], aspect='auto')#,vmin=vmin, vmax=vmax)\nplt.axvline(x=0.0,color = 'r', linestyle = '--')\n#plt.xlim([-1,1])\n#plt.ylim([-2,2])\nplt.xlabel('y(mm)')\nplt.ylabel('x(um)')\nplt.colorbar(im, shrink=0.5)\nplt.show() \n\nplt.savefig('ideal_xy_Section.png',dpi = 300)\n\n\nresult2 = np.zeros([len(y),len(z)])\nfor i in range(len(Iz)):\n result2[i,:] =np.array(Iz[i])\n \nT2 = np.log(result2.T)\n#T2 = result2.T\nplt.figure(2)\nim =plt.imshow(T2, interpolation='bicubic', cmap='jet',\n extent=[min(y),max(y),min(z),max(z)], aspect='auto')#,vmin=vmin, vmax=vmax)\nplt.axvline(x=0.0,color = 'r', linestyle = '--')\n\nplt.xlabel('y(mm)')\nplt.ylabel('z(um)')\nplt.colorbar(im, shrink=0.5)\nplt.show() \n\nplt.savefig('ideal_zy_Section.png',dpi = 300)\n\n\n\nplt.figure(3)\nplt.plot(x,result1[len(y)//2,:],label = 'horizontal')\nplt.plot(z,result2[len(y)//2,:],label = 'vertical')\nplt.xlabel('position(um)')\nplt.ylabel('Intensity(a.u.)') \n#plt.xlim([-0.5,0.5])\nplt.legend()\nplt.show()\nplt.savefig('ideal_yz_Section_1D.png',dpi = 300)\n","sub_path":"Simulations/srw/SRW_SE_example/run_2_plot_SRW_DATA.py","file_name":"run_2_plot_SRW_DATA.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"75530413","text":"'''Test color detection in image'''\nimport cv2\nimport numpy as np\n\ncamera = cv2.VideoCapture(0)\ncamera.set(3, 640) # width\ncamera.set(4, 480) # height\ncamera.set(10, 120) # brightness min: 0 , max: 255 , increment:1\ncamera.set(11, 50) # contrast min: 0 , max: 255 , increment:1\ncamera.set(12, 70) # saturation min: 0 , max: 255 , increment:1\ncamera.set(14, 50) # gain min: 0 , max: 127 , increment:1\ncamera.set(15, -3) # exposure min: -7 , max: -1 , increment:1\ncamera.set(28, 0) # focus min: 0 , max: 255 , increment:5\n\nwhile True:\n try:\n (s, bgr) = camera.read()\n #bgr = np.rot90(bgr)\n if s:\n hsv = cv2.cvtColor(bgr, cv2.COLOR_BGR2HSV)\n hue_min = 10\n hue_max = 100\n sat_min = np.percentile(hsv[:, :, 1], 5)\n sat_max = 255\n val_min = np.percentile(hsv[:, :, 2], 50)\n val_max = 255\n threshold_min = np.array([hue_min, sat_min, val_min], np.uint8)\n threshold_max = np.array([hue_max, sat_max, val_max], np.uint8)\n mask = cv2.inRange(hsv, threshold_min, threshold_max)\n #mask = cv2.erode(mask, np.ones((3,3), np.uint8), iterations =2)\n #mask = cv2.dilate(mask, np.ones((3,3), np.uint8), iterations =1)\n column_sum = mask.sum(axis=0) # vertical summation\n centroid = int(np.argmax(column_sum))\n egi = np.dstack((mask, mask, mask))\n bgr[:, centroid-1:centroid+1, :] = 0\n egi[:, centroid-1:centroid+1, :] = 255\n hsv[:, centroid-1:centroid+1, :] = 255\n bgr[:, 320, :] = 255\n egi[:, 320, :] = 255\n hsv[:, 320, :] = 255\n output = np.hstack((bgr, egi))\n cv2.imshow('preview', output)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n print(centroid)\n except Exception as error:\n print('ERROR: %s' % str(error))\n break\n","sub_path":"tests/camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"184575556","text":"# -*- coding: utf-8 -*-\nimport os\nimport shlex\nimport subprocess\n\nimport paramiko\n\n\ndef create_dir(in_root_path, in_path):\n if in_root_path.endswith(\"/\") == False:\n in_root_path += \"/\"\n if in_path.endswith(\"/\") == False:\n in_path += \"/\"\n path = in_root_path + in_path\n\n if os.path.exists(path) == False:\n os.makedirs(path)\n\n return path\n\n\ndef get_fullpath(dir, file):\n if dir.endswith(\"/\") == False:\n dir += \"/\"\n fullpath = dir + file\n f = open(fullpath, 'a')\n f.close()\n return fullpath\n\ndef read(file):\n f = open(file, 'r')\n result = f.read()\n f.close()\n return result\n\n\ndef conv_linesep(str):\n return str.replace(\"\\r\\n\", \"\\n\").replace(\"\\r\", \"\\n\")\n\n\ndef isNull(str):\n if str is None or str == \"\":\n return True\n else:\n return False\n\ndef isEmpthList(str_list):\n for str in str_list:\n if not isNull(str):\n return False\n return True\n\n\ndef conv_input(s):\n try:\n reslut = str(s)\n except:\n print(s)\n reslut = reslut.strip()\n return reslut\n\n\ndef run_cmd(cmd):\n result = \"\"\n if cmd.strip().startswith(\"echo\"):\n result = os.popen(cmd).read()\n else:\n args = shlex.split(cmd)\n p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n result, stderr_data = p.communicate()\n p.wait()\n result = bytes.decode(result)\n return result\n\n\ndef run_remote_cmd(cmd, hostname, username, password, port=22, timeout=60):\n ssh = paramiko.SSHClient()\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n ssh.connect(hostname=hostname, port=port, username=username, password=password, timeout=timeout)\n stdin, stdout, stderr = ssh.exec_command(cmd)\n result = stdout.read().decode()\n error = stderr.read().decode()\n ssh.close()\n\n if not isNull(error):\n raise Exception(\"Error happened when excute command [\" + cmd + \"], error message:[\" + error + \"]\")\n\n return result\n","sub_path":"lib/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"641640521","text":"\nfrom sklearn.datasets import fetch_mldata \n\n\nmnist = fetch_mldata('mnist-original',data_home='./')\nx_all =mnist.data\ny_all = mnist.target \n\n\nimport matplotlib \nimport matplotlib.pyplot as plt \nimport numpy as np\n\n#Show some number in dataset \n\n# plt.imshow(x_all.T[:,3000].reshape(28,28))\n# plt.axis(\"off\")\n# plt.show()\n\n\n#loc lai chi con 2 chu so 0 va 1 \n\nx0 = x_all[np.where(y_all == 0 )[0]]\nx1 = x_all[np.where(y_all == 1)[0]]\n\ny0 = np.zeros(x0.shape[0])\ny1 = np.ones(x1.shape[0])\n\n# gop 0 va 1 lai thanh dataset \n\nx = np.concatenate((x0,x1), axis=0)\ny = np.concatenate((y0,y1))\n\none = np.ones((x.shape[0],1))\n\nx = np.concatenate((x,one), axis = 1)\n\nprint(x)\ndef GD(X,y,theta,eta = 0.05):\n thetaOld = theta\n thetaEpoch= theta\n N = X.shape[0]\n for it in range(10000):\n mix_id = np.random.permutation(N)\n for i in mix_id:\n xi = X[i,:]\n yi = y[i]\n hi = 1.0/(1.0+np.exp(-np.dot(xi,thetaOld.T)))\n\n gi = (yi-hi)*xi\n\n thetaNew = thetaOld + eta * gi\n thetaOld = thetaNew\n if(np.linalg.norm(thetaEpoch - thetaOld) < 1e-3):\n break\n thetaEpoch = thetaOld\n \n return thetaEpoch,it\n\nd = x.shape[1]\n\ntheta_init = np.random.randn( 1,d)\nprint(theta_init)\ntheta,it = GD(x,y,theta_init)\n\nnp.savetxt('theta.txt',theta);\n\n\n\n\n\n\n# train model \n\n# model = LogisticRegression(C=1e5)\n# model.fit(x_train,y_train)\n\n# y_prediction = model.predict(x_test)\n\n# print(\"accuracy\" + str(100* accuracy_score(y_test,y_prediction)))\n\n# #save model \n\n# from sklearn.externals import joblib\n\n# joblib.dump(model,\"digits.pkl\",compress=3)","sub_path":"build-from-scratch/v3/handigit-v3.py","file_name":"handigit-v3.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"424722147","text":"print(\"Programa Estoque\")\r\n\r\nn1 = \"sul\"\r\nn2 = \"norte\"\r\nn3 = \"leste\"\r\nn4 = \"oeste\"\r\nn5 = \"noroeste\"\r\nn6 = \"sudeste\"\r\nn7 = \"centro_oeste\"\r\nn8 = \"nordeste\"\r\ntentativas = \"\"\r\n\r\ncodigo = str(input(\"Digite o código da região: \"))\r\nwhile(codigo == tentativas):\r\n codigo = str(input(\"Digite o código da região: \"))\r\n\r\ncliente = str(input(\"Digite o nome do cliente: \"))\r\nwhile(cliente == tentativas):\r\n cliente = str(input(\"Digite o nome do cliente: \"))\r\n\r\nvende = str(input(\"Informe o vendedor: \"))\r\nwhile(vende == tentativas):\r\n vende = str(input(\"Informe o vendedor: \"))\r\n\r\n\r\nvalorprod = int(input(\"Valor do produto: \"))\r\n\r\nvalorquant = int(input(\"Quantidade de peças: \"))\r\n\r\n\r\n\r\n\r\n#sul\r\ns = (valorprod * valorquant)\r\ns1 = s * 1\r\ns2 = s + s1\r\ns3 = s2 * 0.065\r\n\r\n#norte\r\nnn = valorprod * valorquant\r\nnn1 = nn * 1.10\r\nnn2 = nn + nn1\r\nnn3 = nn2 * 0.08\r\n\r\n#leste\r\nles = valorprod * valorquant\r\nles1 = les * 1.15\r\nles2 = les + les1\r\nles3 = les2 * 0.07\r\n\r\n#oeste\r\noes = valorprod * valorquant\r\noes1 = oes * 1.20\r\noes2 = oes + oes1\r\noes3 = oes2 * 0.11\r\n\r\n#noroeste\r\nnor = valorprod * valorquant\r\nnor1 = nor * 1.25\r\nnor2 = nor + nor1\r\nnor3 = nor2 * 0.15\r\n\r\n#sudeste\r\nsud = valorprod * valorquant\r\nsud1 = sud * 1.30\r\nsud2 = sud + sud1\r\nsud3 = sud2 * 0.12\r\n\r\n#centro-oeste\r\ncoes = valorprod * valorquant\r\ncoes1 = coes * 1.30\r\ncoes2 = coes + coes1\r\ncoes3 = coes2 * 0.12\r\n\r\n#nordeste\r\nnord = valorprod * valorquant\r\nnord1 = nord * 1.30\r\nnord2 = nord + nord1\r\nnord3 = nord2 * 0.12\r\n\r\n#sul\r\nif(codigo == \"n1\" and valorquant >= 1000):\r\n print(\"Zona: \",n1,\"\\nNome Cliente: \",cliente,\"\\nValor da peça: \",valorprod, \"\\nValor Total: \", s,\r\n \"\\nValor do frete 1 real por peça: R$ {:.2f}\".format(s2),\r\n \"\\nQuantidade de peças: \",valorquant,\"\\nNome Vendedor\",vende,\"\\nComissão Vendedor: R$ {:.2f}\".format(s3))\r\n#R$ {:f} com o :f estamos dizendo para o sistema que o campo é float.\r\n#R$ {:.2f} dizemos quantos pontos numeros queremos depois do ponto.\r\n\r\n#norte\r\nelif(codigo == \"n2\" and valorquant >= 1000):\r\n print(\"Zona: \",n2,\"\\nNome Cliente: \", cliente, \"\\nValor da peça: \", valorprod, \"\\nValor Total: \", nn,\r\n \"\\nValor do frete 1 real por peça: \", nn2,\r\n \"\\nQuantidade de peças: \", valorquant, \"\\nNome Vendedor\", vende, \"\\nComissão Vendedor: \", nn3)\r\n\r\n#leste\r\nelif(codigo == \"n3\" and valorquant >= 1000):\r\n print(\"Zona: \",n3,\"\\nNome Cliente: \", cliente, \"\\nValor da peça: \", valorprod, \"\\nValor Total: \",les,\r\n \"\\nValor do frete 1 real por peça: \",round(les2),\r\n \"\\nQuantidade de peças: \", valorquant, \"\\nNome Vendedor\", vende, \"\\nComissão Vendedor: \", les3)\r\n\r\n#oeste\r\nelif(codigo == \"n4\" and valorquant >= 1000):\r\n print(\"Zona: \", n4, \"\\nNome Cliente: \", cliente, \"\\nValor da peça: \", valorprod, \"\\nValor Total: \", oes,\r\n \"\\nValor do frete 1 real por peça: \", round(oes2),\r\n \"\\nQuantidade de peças: \", valorquant, \"\\nNome Vendedor\", vende, \"\\nComissão Vendedor: \", oes3)\r\n\r\n#noroeste\r\nelif(codigo == \"n5\" and valorquant >= 1000):\r\n print(\"Zona: \", n5, \"\\nNome Cliente: \", cliente, \"\\nValor da peça: \", valorprod, \"\\nValor Total: \", nor,\r\n \"\\nValor do frete 1 real por peça: \", round(nor2),\r\n \"\\nQuantidade de peças: \", valorquant, \"\\nNome Vendedor\", vende, \"\\nComissão Vendedor: \", nor3)\r\n\r\n#Sudeste\r\nelif(codigo == \"n6\" and valorquant >= 1000):\r\n print(\"Zona: \", n6, \"\\nNome Cliente: \", cliente, \"\\nValor da peça: \", valorprod, \"\\nValor Total: \", sud,\r\n \"\\nValor do frete 1 real por peça: \", round(sud2),\r\n \"\\nQuantidade de peças: \", valorquant, \"\\nNome Vendedor\", vende, \"\\nComissão Vendedor: \", sud3)\r\n\r\n#Centro-oeste\r\nelif(codigo == \"n7\" and valorquant >= 1000):\r\n print(\"Zona: \", n6, \"\\nNome Cliente: \", cliente, \"\\nValor da peça: \", valorprod, \"\\nValor Total: \", coes,\r\n \"\\nValor do frete 1 real por peça: \", round(coes2),\r\n \"\\nQuantidade de peças: \", valorquant, \"\\nNome Vendedor\", vende, \"\\nComissão Vendedor: \", coes3)\r\n\r\n#nordeste\r\nelif(codigo == \"n8\" and valorquant >= 1000):\r\n print(\"Zona: \", n6, \"\\nNome Cliente: \", cliente, \"\\nValor da peça: \", valorprod, \"\\nValor Total: \", nord,\r\n \"\\nValor do frete 1 real por peça: \", round(nord2),\r\n \"\\nQuantidade de peças: \", valorquant, \"\\nNome Vendedor\", vende, \"\\nComissão Vendedor: \", nord3)","sub_path":"Estoque Vendas.py","file_name":"Estoque Vendas.py","file_ext":"py","file_size_in_byte":4340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"78192992","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 13 02:04:36 2015\n\n@author: chenyongxin\n\"\"\"\nimport numpy as np\ndef read_file_numpy(filename='sol.dat'):\n data = np.loadtxt(filename,dtype='float')\n \n return data\n \ndef read_file(filename='sol.dat'):\n infile = open(filename, 'r') \n grid = []\n for line in infile:\n words = line.split(',')\n for column in words:\n grid.append(float(column))\n lines = len(grid)/12\n return np.array(grid).reshape(lines,12)\n\n#grid = read_file_numpy('grid.txt')\ngrid = read_file('grid.txt')","sub_path":"fileRead/fileRead.py","file_name":"fileRead.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"3349008","text":"# -*- coding: utf-8 -*-\nfrom django.db import models\nfrom django.contrib.auth.models import User\n\nclass Contato(models.Model):\n\n\tSEXO_CHOICES = (\n\t\t('masculino','Masculino'),\n\t\t('feminino','Feminino')\n\t)\n\tESTADO_CIVIL_CHOICES = (\n\t\t('solteiro','Solteiro'),\n\t\t('casado','Casado'),\n\t\t('divorciado','Divorciado'),\n\t\t('viuvo','Viuvo')\n\t)\n\n\tcontato_id = models.AutoField(primary_key=True)\n\tcontato_cpf = models.BigIntegerField(unique=True)\n\tcontato_nome = models.CharField(max_length=45)\n\tcontato_detalhe = models.CharField(null=True, max_length=255)\n\tcontato_nascimento = models.DateField()\n\tcontato_sexo = models.CharField(choices=SEXO_CHOICES, max_length=10)\n\tcontato_estado_civil = models.CharField(choices=ESTADO_CIVIL_CHOICES, verbose_name='Estado Civil', max_length=10)\n\tcontato_email = models.CharField(max_length=50)\n\tcontato_favorito = models.BooleanField(verbose_name='Favorito')\n\tcontato_user = models.ForeignKey(User, on_delete = models.CASCADE)\n\n\tdef __str__(self):\n\t\treturn self.contato_nome\n\n\nclass Tarefa(models.Model):\n\ttarefa_id = models.AutoField(primary_key=True)\n\ttarefa_nome = models.CharField(max_length=120)\n\ttarefa_descricao = models.CharField(null=True, max_length=255)\n\ttarefa_data_inicio = models.DateField()\n\ttarefa_concluido = models.BooleanField(verbose_name='Concluido', null=False)\n\ttarefa_user = models.ForeignKey(User)\n\nclass Conta(models.Model):\n\tconta_id = models.AutoField(primary_key=True)\n\tconta_nome = models.CharField(max_length=200)\n\tconta_descricao = models.CharField(null=True, max_length=255)\n\tconta_valor = models.DecimalField(null=False, max_digits=10, decimal_places=2)\n\tconta_data_vencimento = models.DateField()\n\tconta_pago = models.BooleanField()\n\tconta_user = models.ForeignKey(User, on_delete=models.CASCADE)\n\nclass Telefone(models.Model):\n\tCHOICES_TIPO_TELEFONE = (\n\t\t('celular','Celular'),\n\t\t('residencial','Residencial'),\n\t\t('comercial','Comercial'),\n\t\t('recado','Recado')\n\t)\n\tCHOICES_ESTADOS = (\n\t\t('ac','Acre'),\n\t\t('al','Alagoas'),\n\t\t('ap','Amapa'),\n\t\t('am','Amazonas'),\n\t\t('ba','Bahia'),\n\t\t('ce','Ceará'),\n\t\t('df','Distrito Federal'),\n\t\t('es','Espirito Santo'),\n\t\t('go','Goias'),\n\t\t('ma','Maranhão'),\n\t\t('mt','Mato Grosso'),\n\t\t('ms','Mato Grosso do Sul'),\n\t\t('mg','Minas Gerais'),\n\t\t('pa','Pará'),\n\t\t('pb','Paraiba'),\n\t\t('pr','Paraná'),\n\t\t('pe','Pernambuco'),\n\t\t('pi','Piauí'),\n\t\t('rj','Rio de Janeiro'),\n\t\t('rn','Rio Grande do Norte'),\n\t\t('rs','Rio Grande do Sula'),\n\t\t('ro','Rondônia'),\n\t\t('rr','Roraima'),\n\t\t('sc','Santa Catarina'),\n\t\t('sp','São Paulo'),\n\t\t('se','Sergipe'),\n\t\t('to','tocantins')\n\t)\n\tCHOICES_OPERADORAS = (\n\t\t('claro','Claro'),\n\t\t('oi','Oi'),\n\t\t('nextel','Nextel'),\n\t\t('tim','Tim'),\n\t\t('vivo','Vivo'),\n\t\t('outra','Outra')\n\t)\n\n\ttelefone_id = models.AutoField(primary_key=True)\n\ttelefone_contato = models.ForeignKey(Contato, on_delete=models.CASCADE, default=1)\n\ttelefone_numero = models.CharField(max_length=30)\n\ttelefone_operadora = models.CharField(max_length=20, verbose_name='Operadoras',choices=CHOICES_OPERADORAS)\n\ttelefone_estado = models.CharField(max_length=10, verbose_name='Estados', choices=CHOICES_ESTADOS)\n\ttelefone_tipo = models.CharField(verbose_name='Telefone', choices=CHOICES_TIPO_TELEFONE, max_length=20)\n","sub_path":"agenda/contato/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"642846484","text":"from bs4 import BeautifulSoup\nimport time, re\n\n# upsert to mongo collection\ndef upsertToMongo(jobs_collection, job):\n jobs_collection.replace_one({'jobId': job['jobId']}, job, upsert=True)\n\nfacebookUrl = 'https://www.facebook.com'\n\ndef scrapeFacebook(browser, jobs_collection):\n browser.get(facebookUrl + '/careers/jobs?page=1&results_per_page=100&sub_teams[0]=Engineering&sub_teams[1]=Artificial%20Intelligence&sub_teams[2]=Core%20Data%20Science&sub_teams[3]=Computer%20Vision&sub_teams[4]=Database%2C%20Storage%2C%20Systems%20Engineering&sub_teams[5]=Database%20and%20Storage%20Engineering&sub_teams[6]=Developer%20Operations&sub_teams[7]=Machine%20Learning&sub_teams[8]=Partner%20Engineering&sub_teams[9]=Solutions%20Engineering&sub_teams[10]=Sourcing%20Operations%20Engineering&sub_teams[11]=Solutions%20%26%20Partner%20Engineering&sub_teams[12]=Security#search_result')\n\n soup = BeautifulSoup(browser.page_source, 'html.parser')\n atags = soup.find('div', class_='_2ynk').find_all('a', class_='_69jm')\n\n listOfUrls = []\n\n for atag in atags:\n listOfUrls.append(atag['href'])\n\n hasNext = True\n iteration = 1\n while hasNext:\n btnsArr = browser.find_elements_by_class_name('_8q0b')\n\n if iteration > 1 and len(btnsArr) == 3:\n hasNext = False\n else:\n btnsArr[len(btnsArr) - 1].click()\n\n iteration = iteration + 1\n time.sleep(10)\n\n nextBtns = soup.find('div', class_='_8se3').find_all('a')\n\n soup = BeautifulSoup(browser.page_source, 'html.parser')\n\n atags = soup.find('div', class_='_2ynk').find_all('a', class_='_69jm')\n\n listOfUrls = []\n\n for atag in atags:\n listOfUrls.append(atag['href'])\n\n index = 1\n for url in listOfUrls:\n try:\n print('progress ' + str(index) + ' total ' + str(len(listOfUrls)))\n index = index + 1\n jobUrl = facebookUrl + url\n browser.get(jobUrl)\n \n soup = BeautifulSoup(browser.page_source, 'html.parser')\n descriptionDivs = soup.find_all('div', class_='_6ad1')\n jobDescription = ''\n\n if len(descriptionDivs) > 1:\n jobDescription = descriptionDivs[1].text\n elif len(descriptionDivs) > 0:\n jobDescription = descriptionDivs[0].text\n else:\n jobDescription = 'Go to job for description!'\n\n jobTitle = soup.find('h4', class_='_1kdc').text\n jobLocation = soup.find('span', class_='_7vwo').text\n\n jobDescArr = soup.find_all('div', class_='_6ad3')\n\n\n for desc in jobDescArr:\n jobBackupDescription = desc.text.strip()\n\n if bool(re.search(r'\\d', desc.text)):\n jobExperienceDescription = desc.text.strip()\n\n if jobExperienceDescription == '':\n jobExperienceDescription = jobBackupDescription\n\n # get jobId\n urlArr = jobUrl.split('/')\n\n if jobDescription != '':\n jobObj = {\n 'jobId': 'fa' + urlArr[len(urlArr) - 2],\n 'company': 'facebook',\n 'url': facebookUrl + url,\n 'title': jobTitle,\n 'longDescription': jobDescription,\n 'location': jobLocation,\n 'time': round(time.time() * 1000),\n 'shortDescription': jobExperienceDescription,\n }\n\n upsertToMongo(\n jobs_collection,\n jobObj\n )\n except Exception as e:\n pass","sub_path":"fang-scraper/facebook_scrape.py","file_name":"facebook_scrape.py","file_ext":"py","file_size_in_byte":3657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"327243939","text":"import socket\nimport os\nimport logging\nimport Utility\n\nfrom logging.handlers import RotatingFileHandler\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)\n\nformatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s')\nfile_handler = RotatingFileHandler('/home/pi/Alarm-CHIP/server.log', 'a', 1000000, 1)\n\nfile_handler.setLevel(logging.DEBUG)\nfile_handler.setFormatter(formatter)\nlogger.addHandler(file_handler)\n\n\nsteam_handler = logging.StreamHandler()\nsteam_handler.setLevel(logging.DEBUG)\nlogger.addHandler(steam_handler)\n\n\nip = \"192.168.0.50\"\nport = 5400\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nserver.bind((ip, port))\nprint(\"Server is listening on \" + str(ip) +\":\" + str(port))\n\nSALT = \"apbwish\"\n\nserver.listen(1)\n\nwhile True:\n client, address = server.accept()\n print(\"Client connected on \" + str(address))\n response = (client.recv(255)).split('*')\n print(response)\n if response[0] == SALT:\n if response[1] == 'RBT':\n if float(Utility.get_uptime()) > 1:\n os.system(\"sudo reboot\")\n\n\nprint(\"Closing\")\nclient.close()\nserver.close()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"402907369","text":"# -*- coding: utf-8 -*-\nimport pytest\n\nfrom pyleecan.Classes.MachineSCIM import MachineSCIM\nfrom pyleecan.Classes.MachineUD import MachineUD\nfrom pyleecan.Classes.LamSlotWind import LamSlotWind\n\n# init some laminations and a machine\nrotor_0 = LamSlotWind(Rint=0.1, Rext=0.2, is_stator=False)\nstator_0 = LamSlotWind(Rint=0.3, Rext=0.4, is_stator=True)\nstator_1 = LamSlotWind(Rint=0.5, Rext=0.6, is_stator=True)\nrotor_1 = LamSlotWind(Rint=0.7, Rext=0.8, is_stator=False)\n\nmachine = MachineUD()\nmachine.lam_list = [rotor_1, stator_1, rotor_0, stator_0]\n\n\n@pytest.mark.MachineUD\nclass Test_get_lam_methods(object):\n \"\"\"unittest to test the Machine get_lam_xxx methods\"\"\"\n\n def test_get_lam_list(self):\n \"\"\"Test Machine get_lam_list method\"\"\"\n\n # test expected and actual sorted full list\n expected = [rotor_0, stator_0, stator_1, rotor_1]\n actual = machine.get_lam_list()\n\n assert len(actual) == len(expected)\n assert all([a == b for a, b in zip(actual, expected)])\n\n # test expected and actual sorted stator list\n expected = [stator_0, stator_1]\n actual = machine.get_lam_list(key=\"Stator\")\n\n assert len(actual) == len(expected)\n assert all([a == b for a, b in zip(actual, expected)])\n\n # test expected and actual sorted rotor list\n expected = [rotor_0, rotor_1]\n actual = machine.get_lam_list(key=\"Rotor\")\n\n assert len(actual) == len(expected)\n assert all([a == b for a, b in zip(actual, expected)])\n\n def test_get_lam_list_label(self):\n \"\"\"Test Machine get_lam_list_label method\"\"\"\n expected = [\"Rotor-0\", \"Stator-0\", \"Stator-1\", \"Rotor-1\"]\n actual = machine.get_lam_list_label()\n\n assert len(actual) == len(expected)\n assert all([a == b for a, b in zip(actual, expected)])\n\n def test_get_lam_by_label(self):\n \"\"\"Test Machine get_lam_by_label method\"\"\"\n assert machine.get_lam_by_label(\"Stator\") == stator_0\n assert machine.get_lam_by_label(\"Stator-0\") == stator_0\n assert machine.get_lam_by_label(\"Stator-1\") == stator_1\n\n assert machine.get_lam_by_label(\"Rotor\") == rotor_0\n assert machine.get_lam_by_label(\"Rotor-0\") == rotor_0\n assert machine.get_lam_by_label(\"Rotor-1\") == rotor_1\n\n def test_get_lam_index(self):\n \"\"\"Test Machine get_lam_index method\"\"\"\n # ref. order [rotor_0, stator_0, stator_1, rotor_1]\n assert machine.get_lam_index(\"Stator\") == 1\n assert machine.get_lam_index(\"Stator-0\") == 1\n assert machine.get_lam_index(\"Stator-1\") == 2\n\n assert machine.get_lam_index(\"Rotor\") == 0\n assert machine.get_lam_index(\"Rotor-0\") == 0\n assert machine.get_lam_index(\"Rotor-1\") == 3\n\n assert machine.get_lam_index(\"rotor\") is None # method is case sensitive\n assert machine.get_lam_index(\"xyz\") is None\n assert machine.get_lam_index(\"Rotor_\") is None # this is also invalid\n\n def test_get_pole_pair(self):\n \"\"\"Check that the pole pair is check and returned\"\"\"\n mach = MachineSCIM()\n mach.rotor.winding.p = 2\n mach.rotor.is_stator = False\n mach.stator.winding.p = 2\n mach.stator.is_stator = True\n\n # Correct check\n assert mach.get_pole_pair_number() == 2\n\n # Error two laminations\n mach.stator.winding.p = 3\n with pytest.raises(Exception) as e:\n mach.get_pole_pair_number()\n assert \"ERROR, Stator has a different pole pair number than Rotor\" == str(\n e.value\n )\n\n # Error 4 laminations\n stator_0.winding.p = 56\n with pytest.raises(Exception) as e:\n machine.get_pole_pair_number()\n assert \"ERROR, Stator-0 has a different pole pair number than Rotor-1\" == str(\n e.value\n )\n\n\nif __name__ == \"__main__\":\n a = Test_get_lam_methods()\n a.test_get_pole_pair()\n print(\"Done\")\n","sub_path":"Tests/Methods/Machine/test_get_lam_methods.py","file_name":"test_get_lam_methods.py","file_ext":"py","file_size_in_byte":3943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"107330467","text":"class Piosenki():\n def __init__(self, wykonawca, tytul, rok, album):\n self.wykonawca = wykonawca\n self.tytul = tytul\n self.rok = rok\n self.album = album\n\n def __str__(self):\n return '''\nWykonawca: {}\nUtwór: {}\nAlbum: {}\nRok: {}\n '''.format(self.wykonawca, self.tytul, self.album, self.rok)\n \n\nutwor1 = Piosenki('Wykonawca1', 'Tytul1', 'Utwor1', 'Album1')\nutwor2 = Piosenki('Wykonawca2', 'Tytul2', 'Utwor2', 'Album2')\nutwor3 = Piosenki('Wykonawca3', 'Tytul3', 'Utwor3', 'Album3')\n\nprint(utwor1)\nprint(utwor2)\nprint(utwor3)\n","sub_path":"07-ObjectOrientedProgramming/07.05..py","file_name":"07.05..py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"526356021","text":"import sys,time\nimport pygame\nfrom bullet import Bullet\nfrom alien import Alien\n\ndef check_keydown_events(event,ai_settings,stats,screen,ship,aliens,bullets,sb):\n \"\"\"响应按键\"\"\"\n # print(event.key)\n if event.key == pygame.K_RIGHT:\n ship.moving_right = True\n elif event.key == pygame.K_LEFT:\n ship.moving_left = True\n elif event.key == pygame.K_UP:\n ship.moving_up = True\n elif event.key == pygame.K_DOWN:\n ship.moving_down = True\n elif event.key == pygame.K_SPACE:\n fire_bullet(ai_settings,screen,ship,bullets)\n\n elif event.key == pygame.K_p and not stats.game_active:\n start_game(ai_settings,stats,screen,ship,aliens,bullets,sb)\n elif event.key == pygame.K_q:\n sys.exit()\n\n\ndef check_keyup_events(event,ship):\n \"\"\"响应松开\"\"\"\n if event.key == pygame.K_RIGHT:\n ship.moving_right = False\n if event.key == pygame.K_LEFT:\n ship.moving_left = False\n if event.key == pygame.K_UP:\n ship.moving_up = False\n if event.key == pygame.K_DOWN:\n ship.moving_down = False\ndef check_events(ai_settings,screen,stats,play_button,aliens,ship,bullets,sb):\n \"\"\"响应按键和鼠标事件\"\"\"\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n\n elif event.type == pygame.KEYDOWN:\n check_keydown_events(event,ai_settings,stats,screen,ship,aliens,bullets,sb)\n # if event.key == pygame.K_RIGHT:\n # #向右移动飞船\n # # ship.rect.centerx += 1\n # ship.moving_right = True\n # if event.key == pygame.K_LEFT:\n # ship.moving_left = True\n elif event.type == pygame.KEYUP:\n check_keyup_events(event,ship)\n # if event.key == pygame.K_RIGHT:\n # ship.moving_right = False\n # if event.key == pygame.K_LEFT:\n # ship.moving_left = False\n\n elif event.type == pygame.MOUSEBUTTONDOWN:\n mouse_x,mouse_y = pygame.mouse.get_pos()\n check_play_button(ai_settings,screen,stats,play_button,aliens,ship,bullets,sb,mouse_x,mouse_y)\n\ndef check_play_button(ai_settings,screen,stats,play_button,aliens,ship,bullets,sb,mouse_x,mouse_y):\n \"\"\"在玩家单机Play按钮时开始游戏\"\"\"\n # print(play_button.rect.collidepoint(mouse_x,mouse_y))\n if play_button.rect.collidepoint(mouse_x,mouse_y) and not stats.game_active:\n # print(stats.score)\n start_game(ai_settings,stats,screen,ship,aliens,bullets,sb)\n #if play_button.rect.collidepoint(mouse_x,mouse_y):\n # #隐藏光标\n # pygame.mouse.set_visible(False)\n # #重置游戏统计信息\n # stats.reset_stats()\n # stats.game_active = True\n # #清空外星人列表和子弹列表\n # aliens.empty()\n # bullets.empty()\n # #创建新的外星人群组,并让飞船居中\n # create_fleet(ai_settings,screen,ship,aliens)\n # ship.center_ship()\n\ndef start_game(ai_settings,stats,screen,ship,aliens,bullets,sb):\n \"\"\"开始游戏\"\"\"\n #重置游戏设置\n ai_settings.initialize_dynamic_settings()\n # 隐藏光标\n pygame.mouse.set_visible(False)\n # 重置游戏统计信息\n stats.reset_stats()\n sb.prep_score()\n sb.prep_level()\n sb.prep_ships()\n stats.game_active = True\n # 清空外星人列表和子弹列表\n aliens.empty()\n bullets.empty()\n # 创建新的外星人群组,并让飞船居中\n create_fleet(ai_settings, screen, ship, aliens)\n ship.center_ship()\n\ndef update_screen(ai_settings,screen,stats,ship,aliens,bullets,play_button,sb):\n \"\"\"更新屏幕上的图像,并且换到新屏幕\"\"\"\n #每次循环时都会重绘屏幕\n screen.fill(ai_settings.bg_color)\n # 在飞船和外星人后面重绘所有子弹\n for bullet in bullets.sprites():\n bullet.draw_bullet()\n ship.blitme()\n aliens.draw(screen)\n # sb.prep_score()\n sb.show_score()\n sb.prep_gameover()\n #如果游戏处于非活动状态,就绘制Play按钮\n if not stats.game_active and stats.ships_left >= 0:\n play_button.draw_button()\n #让最近绘制的屏幕可见\n pygame.display.flip()\n\ndef update_bullets(ai_settings,screen,ship,bullets,aliens,stats,sb):\n \"\"\"更新子弹的位置,并删除已消失的子弹\"\"\"\n #更新子弹的位置\n bullets.update()\n #删除已消失的子弹\n for bullet in bullets.copy():\n if bullet.rect.bottom <= 0:\n bullets.remove(bullet)\n\n #检查是否有子弹击中了外星人,如果有就删除他们\n collisions = pygame.sprite.groupcollide(bullets,aliens,True,True)\n # print(collisions.values())\n #计分\n for alien in collisions.values():\n stats.score += ai_settings.alien_points * len(alien)\n sb.prep_score()\n # sb.prep_high_score()\n check_high_score(stats,sb)\n #外星人都被消灭之后用新的速度重新创建一批外星人\n if len(aliens) == 0:\n ai_settings.increase_speed()\n create_fleet(ai_settings, screen, ship, aliens)\n stats.level += 1\n sb.prep_level()\n# def update_aliens(aliens):\n# \"\"\"更新外星人位置\"\"\"\n# aliens.update()\n\ndef fire_bullet(ai_settings,screen,ship,bullets):\n \"\"\"发射子弹\"\"\"\n # 创建一颗子弹,并将其放到bullets中\n if len(bullets) < ai_settings.bullets_allowed:\n new_bullet = Bullet(ai_settings, screen, ship)\n bullets.add(new_bullet)\n\n# def create_fleet(ai_settings,screen,aliens):\n# \"\"\"创建外星人群\"\"\"\n# #创建一个外星人,并计算一行可以容纳所少个外星人\n# #外星人的间距为外星人的宽度\n# alien = Alien(ai_settings,screen)\n# alien_width = alien.rect.width\n# available_space_x = ai_settings.screen_width - 2 * alien_width\n# number_aliens_x = int(available_space_x / (2 * alien_width))\n#\n# # 创建第一行外星人\n# for alien_number in range(number_aliens_x):\n# #创建一个外星人并加入当前行\n# alien = Alien(ai_settings,screen)\n# alien.x = alien_width + 2*alien_width*alien_number\n# print(alien.x)\n# alien.rect.x = alien.x\n# aliens.add(alien)\ndef get_number_aliens_x(ai_settings,alien_width):\n \"\"\"计算每行可以容纳多少个外星人\"\"\"\n available_space_x = ai_settings.screen_width - 2 * alien_width\n number_aliens_x = int(available_space_x / (2 * alien_width))\n return number_aliens_x\n\ndef get_number_rows(ai_settings,ship_height,alien_height):\n \"\"\"计算屏幕可以容纳多少行外星人\"\"\"\n available_sapce_y = ai_settings.screen_height - 3 * alien_height - ship_height\n number_rows = int(available_sapce_y/(2 * alien_height))\n return number_rows\n\ndef create_alien(ai_settings,screen,aliens,alien_number,row_number):\n \"\"\"创建一个外星人,并将其放在当前行\"\"\"\n alien = Alien(ai_settings,screen)\n alien_width = alien.rect.width\n alien.x = alien_width + 2 * alien_width * alien_number\n alien.rect.x = alien.x\n alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number\n # alien.rect.y = 300\n aliens.add(alien)\n\ndef create_fleet(ai_settings,screen,ship,aliens):\n \"\"\"创建外星人群\"\"\"\n #创建有个外星人,并计算出每行可以容纳多少个外星人\n if len(aliens) == 0:\n alien = Alien(ai_settings,screen)\n num_aliens_x = get_number_aliens_x(ai_settings,alien.rect.width)\n number_rows = get_number_rows(ai_settings,ship.rect.height,alien.rect.height)\n #创建第几行外星人-创建第一行外星人(循环嵌套)\n for row_number in range(number_rows):\n for alien_number in range(num_aliens_x):\n create_alien(ai_settings,screen,aliens,alien_number,row_number)\n\ndef check_fleet_edges(ai_settings,aliens):\n \"\"\"有外星人到达边缘时采取相应措施\"\"\"\n for alien in aliens.sprites():\n if alien.check_edges():\n change_fleet_direction(ai_settings,aliens)\n break\n\ndef change_fleet_direction(ai_settings,aliens):\n \"\"\"将整群外星人下移,并改变他们的方向\"\"\"\n for alien in aliens.sprites():\n alien.rect.y += ai_settings.fleet_drop_speed\n ai_settings.fleet_direction *= -1\n\n\ndef ship_hit(ai_settings,stats,screen,ship,aliens,bullets,sb):\n \"\"\"响应外星人撞到飞船\"\"\"\n #将ships_left减1\n if stats.ships_left > 0:\n sb.prep_ships()\n stats.ships_left -= 1\n #清空现有的外星人以及子弹列表\n aliens.empty()\n bullets.empty()\n pygame.mouse.set_visible(False)\n stats.game_active = False\n\n #创建一群新的外星人,并将飞船放到屏幕底端中央\n create_fleet(ai_settings,screen,ship,aliens)\n ship.center_ship()\n time.sleep(0.5)\n print(stats.ships_left)\n elif stats.ships_left == 0:\n aliens.empty()\n bullets.empty()\n stats.game_active = True\n sb.prep_gameover()\n # stats.game_active = False\n # pygame.mouse.set_visible(True)\n\n\n\n\ndef update_aliens(ai_settings,stats,screen,ship,aliens,bullets,sb):\n \"\"\"检查是否有外星人位于屏幕的边缘,并更新外星人的位置\"\"\"\n check_fleet_edges(ai_settings,aliens)\n aliens.update()\n for alien in aliens.copy():\n if alien.rect.top >= ai_settings.screen_height:\n aliens.remove(alien)\n\n #检测外星人与飞船之间的碰撞\n if pygame.sprite.spritecollideany(ship,aliens):\n ship_hit(ai_settings,stats,screen,ship,aliens,bullets,sb)\n # print(\"Ship hit!!!\")\n # print(len(aliens.copy()))\n # if len(aliens.copy()) < 0:\n # create_fleet(ai_settings, screen, ship, aliens)\n\ndef check_high_score(stats,sb):\n \"\"\"检查是否诞生了最高分\"\"\"\n # print(stats.score)\n # print(stats.high_score)\n if stats.score > stats.high_score:\n stats.high_score = stats.score\n sb.prep_high_score()","sub_path":"alien_invasion/game_functions.py","file_name":"game_functions.py","file_ext":"py","file_size_in_byte":10050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"555167334","text":"import DetectTFL\nimport Calculations\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom keras.models import load_model\n\nmodel = load_model('model.h5')\n\ndef work_on_frame(prev_frame, curr_frame,pkl_path):\n if prev_frame != 0:\n prev_frame.traffic_light = run_part1_and_part2_wo_plot(prev_frame)\n curr_frame.traffic_light, axs = run_part1_and_part2_and_plot(curr_frame)\n else:\n curr_frame.traffic_light, axs = run_part1_and_part2_and_plot(curr_frame)\n # PART3\n if prev_frame != 0:\n Calculations.read_data_and_run(prev_frame, curr_frame, axs, pkl_path)\n plt.show()\n\ndef run_part1_and_part2_and_plot(frame):\n # PART 1 AND PART 2\n predicted_x, predicted_y = [], []\n #Plot all candidates and returns them\n list_of_candidates, new_x, new_y, axs = DetectTFL.all_tfl_candidates(frame.path, \"image_name\")\n num_of_correct_predict = 0\n for i in range(len(list_of_candidates)):\n list_of_candidates[i] = list_of_candidates[i].reshape(1, 81, 81, 3)\n Part2_results = model.predict(list_of_candidates[i])[0]\n if Part2_results[0] < 0.99:\n num_of_correct_predict += 1\n predicted_x.append(new_x[i])\n predicted_y.append(new_y[i])\n #Prints all predicted points\n DetectTFL.printPrediction(frame.path, predicted_x, predicted_y, axs)\n return np.column_stack((predicted_x, predicted_y)),axs\n\ndef run_part1_and_part2_wo_plot(frame):\n # PART 1 AND PART 2\n predicted_x, predicted_y = [], []\n # Plot all candidates and returns them\n list_of_candidates, new_x, new_y = DetectTFL.all_tfl_candidates_wo_plotting(frame.path, \"image_name\")\n num_of_correct_predict = 0\n for i in range(len(list_of_candidates)):\n list_of_candidates[i] = list_of_candidates[i].reshape(1, 81, 81, 3)\n Part2_results = model.predict(list_of_candidates[i])[0]\n if Part2_results[0] < 0.99:\n num_of_correct_predict += 1\n predicted_x.append(new_x[i])\n predicted_y.append(new_y[i])\n # Prints all predicted points\n return np.column_stack((predicted_x, predicted_y))\n","sub_path":"TFL_Man.py","file_name":"TFL_Man.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"60238753","text":"import sys\nimport os\nimport socket\nimport struct\n\nMCAST_GRP = '234.5.6.78'\nMCAST_PORT = 57890\nMCAST_ADDR = (MCAST_GRP, MCAST_PORT)\n\t\t\n\ndef server():\n\tprint(\"server!\")\n\tsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n\tsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n\t# Bind to the server address\n\tsock.bind((\"\", MCAST_PORT))\n\t\n\tttl = struct.pack('b', 10)\n\tsock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)\n\n\t# Tell the operating system to add the socket to the multicast group\n\t# on all interfaces.\n\tgroup = socket.inet_aton(MCAST_GRP)\n\tmreq = struct.pack('4sL', group, socket.INADDR_ANY)\n\tsock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)\n\t\n\tsock.sendto(b\"Multicast test!!!\", MCAST_ADDR)\n\tprint(\"data sent!\")\n\n\tdata, server = sock.recvfrom(2048)\n\tprint (\"received: \", data, \"\\r\\nfrom: %s\", server)\n\n\ndef client():\n\tprint(\"Client!\")\n\n\ndef test(num):\n\tif num == '1':\n\t\tserver()\n\telse:\n\t\tclient()\n\n\n","sub_path":"src/bk_multi.py","file_name":"bk_multi.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"391151893","text":"import argparse\nimport os\nimport re\nfrom typing import List\n\nfrom tabulate import tabulate\n\nfrom rozental_as_a_service.ast_utils import extract_all_constants_from_path\nfrom rozental_as_a_service.common_types import TypoInfo, BackendsConfig\nfrom rozental_as_a_service.config import (\n DEFAULT_WORDS_CHUNK_SIZE, DEFAULT_VOCABULARY_FILENAME, DEFAULT_SQLITE_DB_FILENAME,\n)\nfrom rozental_as_a_service.list_utils import chunks\nfrom rozental_as_a_service.typos_backends import (\n process_with_vocabulary, process_with_ya_speller,\n process_with_db_with_cache,\n)\n\n\ndef parse_args() -> argparse.Namespace:\n parser = argparse.ArgumentParser()\n parser.add_argument('path', type=str)\n parser.add_argument('--vocabulary_path', default=None)\n parser.add_argument('--db_path', default=None)\n return parser.parse_args()\n\n\ndef fetch_typos_info(string_constants: List[str], vocabulary_path: str, db_path: str) -> List[TypoInfo]:\n typos_info: List[TypoInfo] = []\n\n backends = [\n process_with_vocabulary,\n process_with_db_with_cache,\n process_with_ya_speller,\n ]\n backend_config: BackendsConfig = {\n 'vocabulary_path': vocabulary_path,\n 'db_path': db_path,\n 'speller_chunk_size': DEFAULT_WORDS_CHUNK_SIZE,\n }\n for words_chunk in chunks(string_constants, backend_config['speller_chunk_size']):\n for words_processor in backends:\n sure_correct, sure_with_typo_info, unknown = words_processor(words_chunk, backend_config)\n typos_info += sure_with_typo_info\n # переопределяем переменную цикла так, чтобы следующему процессору доставались\n # только слова, по которым не известно, ок ли они\n words_chunk = unknown\n\n return typos_info\n\n\ndef extract_words(raw_constants: List[str], min_word_length: int = 3, only_russian: bool = True) -> List[str]:\n processed_words: List[str] = []\n for constant in raw_constants:\n processed_words += list({\n w.strip().lower() for w in re.findall(r'\\w+', constant)\n if len(w.strip()) >= min_word_length\n })\n processed_words = list(set(processed_words))\n if only_russian:\n processed_words = [w for w in processed_words if re.match(r'[а-я]+', w)]\n return processed_words\n\n\ndef main() -> None:\n arguments = parse_args()\n vocabulary_path = arguments.vocabulary_path or os.path.join(arguments.path, DEFAULT_VOCABULARY_FILENAME)\n db_path = arguments.db_path or os.path.join(arguments.path, DEFAULT_SQLITE_DB_FILENAME)\n string_constants = extract_all_constants_from_path(arguments.path)\n unique_words = extract_words(string_constants)\n typos_info = fetch_typos_info(unique_words, vocabulary_path, db_path)\n\n table = [(t['original'], ', '.join(t['possible_options'])) for t in typos_info]\n print(tabulate(table, headers=('Найденное слово', 'Возможные исправления'))) # noqa\n if typos_info:\n exit(1)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"rozental_as_a_service/rozental.py","file_name":"rozental.py","file_ext":"py","file_size_in_byte":3117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"395022086","text":"#!/usr/local/bin/python3\n\nfrom ROOT import TChain, TTree, TFile, TVector3, TMVA\nfrom glob import glob\nfrom array import array\nfrom tqdm import tqdm\nimport math\nfrom bdt_common import total_pot, variables, spectators, choose_shower\nfrom bdt_common import is_active, is_fiducial, distance\nfrom bdt_common import ELECTRON_MASS, PROTON_MASS, MAX_N_SHOWERS, MAX_N_TRACKS, N_UNI\nfrom bdt_common import PROTON_THRESHOLD, ELECTRON_THRESHOLD\n\nfrom proton_energy import length2energy\nimport time\nimport statistics\nimport sys\n\nSTORE_SYS = True\n\nvariable = sys.argv[1]\n\nreader_reclass = TMVA.Reader(\":\".join([\n \"!V\",\n \"!Silent\",\n \"Color\"]))\nangle = array(\"f\", [0])\npca = array(\"f\", [0])\nres = array(\"f\", [0])\nopen_angle = array(\"f\", [0])\nn_hits = array(\"f\", [0])\nratio = array(\"f\", [0])\n\nreader_reclass.AddVariable(\"angle\", angle)\nreader_reclass.AddVariable(\"pca\", pca)\nreader_reclass.AddVariable(\"res\", res)\nreader_reclass.AddVariable(\"open_angle\", open_angle)\nreader_reclass.AddVariable(\"ratio\", ratio)\nreader_reclass.AddVariable(\"n_hits\", n_hits)\n\nreader_reclass.BookMVA(\"shower_ntuple BDT\",\n \"dataset/weights/TMVAClassification_shower_ntuple BDT.weights.xml\")\n\n\ndef check_cc0pinp(chain_nue):\n \"\"\"Checks if the event is a contained electron neutrino\n CC0π-Np interaction\n\n Args:\n chain_nue: ROOT TChain of the events\n\n Returns:\n True if the event is a contained CC0π-Np interaction\n \"\"\"\n protons = 0\n electrons = 0\n photons = 0\n pions = 0\n electron_energy = 0\n proton_energy = 0\n\n for i, energy in enumerate(chain_nue.nu_daughters_E):\n vertex = [chain_nue.nu_daughters_vx[i],\n chain_nue.nu_daughters_vy[i],\n chain_nue.nu_daughters_vz[i]]\n\n end = [chain_nue.nu_daughters_endx[i],\n chain_nue.nu_daughters_endy[i],\n chain_nue.nu_daughters_endz[i]]\n\n if chain_nue.nu_daughters_pdg[i] == 2212:\n if energy - PROTON_MASS > PROTON_THRESHOLD and is_fiducial(vertex) and is_fiducial(end):\n protons += 1\n proton_energy += energy - PROTON_MASS\n\n if chain_nue.nu_daughters_pdg[i] == 11:\n if energy - ELECTRON_MASS > ELECTRON_THRESHOLD and is_fiducial(vertex):\n electron_energy += energy - ELECTRON_MASS\n electrons += 1\n\n if chain_nue.nu_daughters_pdg[i] == 22:\n if energy > ELECTRON_THRESHOLD and is_fiducial(vertex):\n photons += 1\n\n if chain_nue.nu_daughters_pdg[i] == 111:\n if energy - 0.135 > ELECTRON_THRESHOLD and is_fiducial(vertex):\n pions += 1\n\n if abs(chain_nue.nu_daughters_pdg[i]) == 211:\n if energy - 0.140 > PROTON_THRESHOLD and is_fiducial(vertex) and is_fiducial(end):\n pions += 1\n\n is_CC0piNp = electrons == 1 and pions == 0 and protons >= 1 and photons == 0\n if is_CC0piNp:\n return (proton_energy, electron_energy)\n\n return False\n\ndef shower_score(v_angle, v_pca, v_res, v_open_angle, v_n_hits, v_ratio):\n if v_angle > 0 and v_pca > 0 and v_res > 0 and v_open_angle > 0 and v_n_hits > 0 and v_ratio > 0:\n angle[0] = v_angle\n pca[0] = v_pca\n res[0] = v_res\n open_angle[0] = v_open_angle\n n_hits[0] = v_n_hits\n ratio[0] = v_ratio\n BDT_response = reader_reclass.EvaluateMVA(\"shower_ntuple BDT\")\n return BDT_response\n else:\n return -1\n\n\ndef pi0_mass(root_chain):\n if root_chain.n_showers < 2:\n return -1\n\n shower_energies = sorted(\n [e[2] for e in root_chain.shower_energy], reverse=True)\n shower_ids = []\n\n for i_sh in range(root_chain.n_showers):\n if root_chain.shower_energy[i_sh][2] in shower_energies:\n shower_ids.append(i_sh)\n\n v_1 = TVector3(\n root_chain.shower_dir_x[shower_ids[0]],\n root_chain.shower_dir_y[shower_ids[0]],\n root_chain.shower_dir_z[shower_ids[0]])\n\n v_2 = TVector3(\n root_chain.shower_dir_x[shower_ids[1]],\n root_chain.shower_dir_y[shower_ids[1]],\n root_chain.shower_dir_z[shower_ids[1]])\n\n cos = v_1.Dot(v_2) / (v_1.Mag() * v_2.Mag())\n angle = math.acos(cos)\n\n e1 = root_chain.shower_energy[shower_ids[0]][2]\n e2 = root_chain.shower_energy[shower_ids[1]][2]\n\n for i_sh in range(root_chain.n_showers):\n\n if i_sh in shower_ids:\n continue\n\n v_x = TVector3(\n root_chain.shower_dir_x[i_sh],\n root_chain.shower_dir_y[i_sh],\n root_chain.shower_dir_z[i_sh])\n\n cos_1 = v_x.Dot(v_1) / (v_x.Mag() * v_1.Mag())\n cos_2 = v_x.Dot(v_2) / (v_x.Mag() * v_2.Mag())\n if math.acos(cos_1) < math.acos(cos_2):\n e1 += root_chain.shower_energy[i_sh][2]\n else:\n e2 += root_chain.shower_energy[i_sh][2]\n\n pi0_mass = math.sqrt(4 * e1 * e2 * (math.sin(angle / 2)**2))\n\n return pi0_mass\n\n\ndef choose_track(root_chain, particleid=True):\n min_score = 9999999\n chosen_track = 0\n if not particleid:\n return chosen_track, min_score\n\n for i_tr in range(root_chain.n_tracks):\n track_pid_chipr = root_chain.track_pid_chipr[i_tr]\n if track_pid_chipr < 0:\n continue\n\n if track_pid_chipr < min_score:\n min_score = track_pid_chipr\n chosen_track = i_tr\n\n return chosen_track, min_score\n\n\ndef choose_plane(root_chain):\n total_hits = [0, 0, 0]\n shower_hits = [0, 0, 0]\n track_hits = [0, 0, 0]\n\n for i_sh in range(root_chain.n_showers):\n for i_plane in range(len(root_chain.shower_nhits[i_sh])):\n total_hits[i_plane] += root_chain.shower_nhits[i_sh][i_plane]\n shower_hits[i_plane] += root_chain.shower_nhits[i_sh][i_plane]\n\n for i_tr in range(root_chain.n_tracks):\n for i_plane in range(len(root_chain.track_nhits[i_tr])):\n total_hits[i_plane] += root_chain.track_nhits[i_tr][i_plane]\n track_hits[i_plane] += root_chain.track_nhits[i_tr][i_plane]\n\n product = [s for t, s in zip(track_hits, shower_hits)]\n\n return product.index(max(product))\n\ndef fill_kin_branches(root_chain, weight, variables, option=\"\", particleid=True):\n no_tracks = False\n hit_index = 2\n shower_id = choose_shower(root_chain, hit_index)\n track_id, track_score = choose_track(root_chain, particleid)\n\n if STORE_SYS and (option == \"bnb\" or option == \"nue\"):\n\n if (len(root_chain.flux_weights) > 0 and len(root_chain.genie_weights) > 0):\n\n flux_weights = [1]*len(root_chain.flux_weights[0])\n for fl in root_chain.flux_weights:\n flux_weights = [a*b for a, b in zip(flux_weights, fl)]\n\n for u in range(N_UNI):\n variables[\"genie_weights\"][u] = root_chain.genie_weights[0][u]\n variables[\"flux_weights\"][u] = flux_weights[u]\n\n variables[\"E_dep\"][0] = 0\n\n if \"nue\" in option:\n for i, energy in enumerate(root_chain.nu_daughters_E):\n if root_chain.nu_daughters_pdg[i] == 2212:\n if energy - 0.938 > PROTON_THRESHOLD:\n variables[\"E_dep\"][0] += energy - 0.938\n\n if root_chain.nu_daughters_pdg[i] == 11:\n if energy - 0.51e-3 > ELECTRON_THRESHOLD:\n variables[\"E_dep\"][0] += energy - 0.51e-3\n\n track_like_shower_id = -1\n if root_chain.n_tracks == 0 and root_chain.n_showers > 1:\n shower_res_std_list = list(root_chain.shower_res_std)\n track_like_shower_id = shower_res_std_list.index(min(shower_res_std_list))\n if track_like_shower_id == shower_id:\n track_like_shower_id = abs(shower_id - 1)\n no_tracks = True\n\n vec_shower = TVector3(\n root_chain.shower_dir_x[shower_id],\n root_chain.shower_dir_y[shower_id],\n root_chain.shower_dir_z[shower_id])\n\n true_vertex = [root_chain.true_vx_sce, root_chain.true_vy_sce, root_chain.true_vz_sce]\n neutrino_vertex = [root_chain.vx, root_chain.vy, root_chain.vz]\n\n variables[\"is_signal\"][0] = int(root_chain.category == 2)\n variables[\"true_nu_is_fidvol\"][0] = int(is_fiducial(true_vertex))\n\n variables[\"n_objects\"][0] = root_chain.n_tracks + root_chain.n_showers\n variables[\"n_tracks_before\"][0] = root_chain.n_tracks\n variables[\"n_showers_before\"][0] = root_chain.n_showers\n\n if no_tracks:\n variables[\"n_tracks_before\"][0] = 1\n variables[\"n_showers_before\"][0] = root_chain.n_showers - 1\n\n variables[\"no_tracks\"][0] = int(no_tracks)\n variables[\"nu_E\"][0] = max(-999, root_chain.nu_E)\n\n y_shower = sum([root_chain.shower_nhits[i_sh][2] for i_sh in range(root_chain.n_showers)])\n y_track = sum([root_chain.track_nhits[i_sh][2]for i_sh in range(root_chain.n_tracks)])\n\n u_shower = sum([root_chain.shower_nhits[i_sh][0] for i_sh in range(root_chain.n_showers)])\n u_track = sum([root_chain.track_nhits[i_sh][0] for i_sh in range(root_chain.n_tracks)])\n\n v_shower = sum([root_chain.shower_nhits[i_sh][1] for i_sh in range(root_chain.n_showers)])\n v_trackh = sum([root_chain.track_nhits[i_sh][1] for i_sh in range(root_chain.n_tracks)])\n\n variables[\"total_hits\"][0] = u_shower + u_track + v_shower + v_trackh + y_shower + y_track\n\n variables[\"total_hits_u\"][0] = u_shower + u_track\n variables[\"total_hits_v\"][0] = v_shower + v_trackh\n variables[\"total_hits_y\"][0] = y_shower + y_track\n\n if option == \"cosmic_mc\" or option == \"ext_data\":\n variables[\"category\"][0] = 0\n elif option == \"lee\":\n variables[\"category\"][0] = 10\n elif option == \"nue_cc\":\n variables[\"category\"][0] = 8\n else:\n variables[\"category\"][0] = root_chain.category\n\n variables[\"event_weight\"][0] = weight\n\n if option == \"nue\":\n if root_chain.cosmic_fraction < 0.5 and root_chain.category == 7:\n variables[\"category\"][0] = 2\n\n if option == \"nue_cc\":\n if root_chain.cosmic_fraction < 0.5 and root_chain.category == 7 and root_chain.ccnc == 0:\n variables[\"category\"][0] = 8\n\n if option == \"lee\":\n if root_chain.cosmic_fraction < 0.5 and root_chain.category == 7:\n variables[\"category\"][0] = 10\n\n\n variables[\"pt\"][0] = pt_plot(root_chain, 2)\n variables[\"event\"][0] = root_chain.event\n variables[\"run\"][0] = root_chain.run\n variables[\"subrun\"][0] = root_chain.subrun\n variables[\"interaction_type\"][0] = root_chain.interaction_type\n\n total_shower_energy = 0\n total_shower_energy_cali = 0\n total_track_energy_length = 0\n\n for i_tr in range(MAX_N_TRACKS):\n variables[\"track_pdg\"][i_tr] = -999\n variables[\"track_phi\"][i_tr] = -999\n variables[\"track_theta\"][i_tr] = -999\n variables[\"track_length\"][i_tr] = -999\n variables[\"track_energy_length\"][i_tr] = -999\n variables[\"track_start_x\"][i_tr] = -999\n variables[\"track_start_y\"][i_tr] = -999\n variables[\"track_start_z\"][i_tr] = -999\n variables[\"track_res_mean\"][i_tr] = -999\n variables[\"track_res_std\"][i_tr] = -999\n variables[\"track_pca\"][i_tr] = -999\n variables[\"track_end_x\"][i_tr] = -999\n variables[\"track_end_y\"][i_tr] = -999\n variables[\"track_end_z\"][i_tr] = -999\n variables[\"track_shower_angle\"][i_tr] = -999\n variables[\"track_distance\"][i_tr] = -999\n variables[\"track_pidchipr\"][i_tr] = -999\n variables[\"track_likelihood\"][i_tr] = -999\n variables[\"track_mip_likelihood\"][i_tr] = -999\n variables[\"track_p_likelihood\"][i_tr] = -999\n variables[\"track_dqdx\"][i_tr] = -999\n\n for i_sh in range(MAX_N_SHOWERS):\n variables[\"shower_pdg\"][i_sh] = -999\n variables[\"shower_start_x\"][i_sh] = -999\n variables[\"shower_start_y\"][i_sh] = -999\n variables[\"shower_start_z\"][i_sh] = -999\n variables[\"shower_energy\"][i_sh] = -999\n variables[\"shower_pca\"][i_sh] = -999\n variables[\"shower_open_angle\"][i_sh] = -999\n variables[\"shower_dedx\"][i_sh] = -999\n variables[\"shower_dqdx\"][i_sh] = -999\n variables[\"shower_dedx_u\"][i_sh] = -999\n variables[\"shower_dedx_v\"][i_sh] = -999\n variables[\"shower_dedx_cali\"][i_sh] = -999\n variables[\"shower_res_mean\"][i_sh] = -999\n variables[\"shower_res_std\"][i_sh] = -999\n variables[\"shower_phi\"][i_sh] = -999\n variables[\"shower_theta\"][i_sh] = -999\n variables[\"shower_distance\"][i_sh] = -999\n variables[\"shower_angle\"][i_sh] = -999\n variables[\"shower_pidchimu\"][i_sh] = -999\n variables[\"shower_pidchipr\"][i_sh] = -999\n variables[\"shower_pidchipi\"][i_sh] = -999\n\n variables[\"n_showers\"][0] = 0\n variables[\"n_tracks\"][0] = 0\n variables[\"shower_id\"][0] = shower_id\n variables[\"track_id\"][0] = track_id\n\n total_track_nhits = 0\n total_shower_nhits = 0\n\n check_conversion = len(root_chain.track_start_x) == root_chain.n_showers + root_chain.n_tracks\n n_tr = root_chain.n_tracks\n\n for i_sh in range(root_chain.n_showers):\n shower_v = [\n root_chain.shower_start_x[i_sh],\n root_chain.shower_start_y[i_sh],\n root_chain.shower_start_z[i_sh]\n ]\n\n v_sh = TVector3(\n root_chain.shower_dir_x[i_sh],\n root_chain.shower_dir_y[i_sh],\n root_chain.shower_dir_z[i_sh]\n )\n\n cos = v_sh.Dot(vec_shower) / (v_sh.Mag() * vec_shower.Mag())\n shower_angle = math.degrees(math.acos(min(cos, 1)))\n shower_pca = root_chain.shower_pca[i_sh][2]\n converted_showers = 0\n shower_res_std = root_chain.shower_res_std[i_sh]\n shower_open_angle = root_chain.shower_open_angle[i_sh]\n shower_n_hits = root_chain.shower_nhits[i_sh][2]\n length = root_chain.shower_length[i_sh]\n ratio = shower_n_hits / length\n score = shower_score(shower_angle,\n shower_pca,\n shower_res_std,\n shower_open_angle,\n shower_n_hits,\n ratio)\n shower_end = [s+d*length for s, d in zip(shower_v, v_sh)]\n\n ll = -999\n if check_conversion:\n mip_likelihood = root_chain.track_bragg_mip[n_tr + i_sh]\n p_likelihood = root_chain.track_bragg_p[n_tr + i_sh]\n if p_likelihood > 1e-32:\n ll = math.log(mip_likelihood/p_likelihood)\n\n if (i_sh == track_like_shower_id or score > 0) and i_sh != shower_id:\n variables[\"n_tracks\"][0] += 1\n variables[\"track_pdg\"][n_tr + converted_showers] = root_chain.matched_showers[i_sh]\n\n if check_conversion:\n track_v = [\n root_chain.track_start_x[n_tr + i_sh],\n root_chain.track_start_y[n_tr + i_sh],\n root_chain.track_start_z[n_tr + i_sh]\n ]\n\n vec_track = TVector3(\n root_chain.track_dir_x[n_tr + i_sh],\n root_chain.track_dir_y[n_tr + i_sh],\n root_chain.track_dir_z[n_tr + i_sh]\n )\n\n variables[\"track_start_x\"][n_tr + converted_showers] = root_chain.track_start_x[n_tr + i_sh]\n variables[\"track_start_y\"][n_tr + converted_showers] = root_chain.track_start_y[n_tr + i_sh]\n variables[\"track_start_z\"][n_tr + converted_showers] = root_chain.track_start_z[n_tr + i_sh]\n variables[\"track_phi\"][n_tr + converted_showers] = math.degrees(root_chain.track_phi[n_tr + i_sh])\n variables[\"track_theta\"][n_tr + converted_showers] = math.degrees(root_chain.track_theta[n_tr + i_sh])\n variables[\"track_length\"][n_tr + converted_showers] = root_chain.track_len[n_tr + i_sh]\n variables[\"track_pca\"][n_tr + converted_showers] = max(-999, root_chain.track_pca[n_tr + i_sh][2])\n variables[\"track_res_mean\"][n_tr + converted_showers] = max(-999, root_chain.track_res_mean[n_tr + i_sh])\n variables[\"track_res_std\"][n_tr + converted_showers] = max(-999, root_chain.track_res_std[n_tr + i_sh])\n if particleid:\n variables[\"track_pidchipr\"][n_tr + converted_showers] = root_chain.track_pid_chipr[n_tr + i_sh]\n\n if root_chain.track_pid_chipr[n_tr + i_sh] < track_score:\n variables[\"track_id\"][0] = n_tr + i_sh\n track_score = root_chain.track_pid_chipr[n_tr + i_sh]\n\n mip_likelihood = root_chain.track_bragg_mip[n_tr + i_sh]\n p_likelihood = root_chain.track_bragg_p[n_tr + i_sh]\n else:\n mip_likelihood = 0\n p_likelihood = 0\n variables[\"track_mip_likelihood\"][n_tr + converted_showers] = mip_likelihood\n variables[\"track_p_likelihood\"][n_tr + converted_showers] = p_likelihood\n if p_likelihood > 1e-9:\n variables[\"track_likelihood\"][n_tr + converted_showers] = math.log(mip_likelihood/p_likelihood)\n variables[\"track_dqdx\"][n_tr + converted_showers] = max(-999, root_chain.track_dQdx[n_tr + i_sh][2])\n if root_chain.category == 0 or root_chain.category == 6:\n variables[\"track_dqdx\"][0] *= 1.2\n variables[\"track_end_x\"][n_tr + converted_showers] = root_chain.track_end_x[n_tr + i_sh]\n variables[\"track_end_y\"][n_tr + converted_showers] = root_chain.track_end_y[n_tr + i_sh]\n variables[\"track_end_z\"][n_tr + converted_showers] = root_chain.track_end_z[n_tr + i_sh]\n length_e = length2energy(root_chain.track_len[n_tr + i_sh])\n variables[\"track_energy_length\"][n_tr + converted_showers] = length_e\n total_track_energy_length += length_e\n total_track_nhits += root_chain.track_nhits[n_tr + i_sh][2]\n costheta_shower_track = v_sh.Dot(vec_track) / (v_sh.Mag() * vec_track.Mag())\n variables[\"track_shower_angle\"][n_tr + converted_showers] = costheta_shower_track\n track_vertex_d = math.sqrt(sum([(t - n)**2 for t, n in zip(track_v, neutrino_vertex)]))\n variables[\"track_distance\"][n_tr + converted_showers] = track_vertex_d\n else:\n variables[\"track_start_x\"][n_tr + converted_showers] = root_chain.shower_start_x[i_sh]\n variables[\"track_start_y\"][n_tr + converted_showers] = root_chain.shower_start_y[i_sh]\n variables[\"track_start_z\"][n_tr + converted_showers] = root_chain.shower_start_z[i_sh]\n variables[\"track_phi\"][n_tr + converted_showers] = math.degrees(root_chain.shower_phi[i_sh])\n variables[\"track_theta\"][n_tr + converted_showers] = math.degrees(root_chain.shower_theta[i_sh])\n variables[\"track_length\"][n_tr + converted_showers] = root_chain.shower_length[i_sh]\n variables[\"track_pca\"][n_tr + converted_showers] = max(-999, root_chain.shower_pca[i_sh][2])\n variables[\"track_res_mean\"][n_tr + converted_showers] = max(-999, root_chain.shower_res_mean[i_sh])\n variables[\"track_res_std\"][n_tr + converted_showers] = max(-999, root_chain.shower_res_std[i_sh])\n variables[\"track_pidchipr\"][n_tr + converted_showers] = -999\n variables[\"track_likelihood\"][n_tr + converted_showers] = -999\n variables[\"track_mip_likelihood\"][n_tr + converted_showers] = -999\n variables[\"track_p_likelihood\"][n_tr + converted_showers] = -999\n variables[\"track_dqdx\"][n_tr + converted_showers] = -999\n variables[\"track_end_x\"][n_tr + converted_showers] = shower_end[0]\n variables[\"track_end_y\"][n_tr + converted_showers] = shower_end[1]\n variables[\"track_end_z\"][n_tr + converted_showers] = shower_end[2]\n length_e = length2energy(root_chain.shower_length[i_sh])\n total_track_energy_length += length_e\n variables[\"track_energy_length\"][n_tr + converted_showers] = length_e\n total_track_nhits += root_chain.shower_nhits[i_sh][2]\n costheta_shower_track = v_sh.Dot(vec_shower) / (v_sh.Mag() * vec_shower.Mag())\n variables[\"track_shower_angle\"][n_tr + converted_showers] = costheta_shower_track\n track_vertex_d = math.sqrt(sum([(t - n)**2 for t, n in zip(shower_v, neutrino_vertex)]))\n variables[\"track_distance\"][n_tr + converted_showers] = track_vertex_d\n if variables[\"no_tracks\"][0] == 1:\n variables[\"track_id\"][0] = 0\n converted_showers += 1\n else:\n variables[\"n_showers\"][0] += 1\n if i_sh != shower_id:\n variables[\"shower_angle\"][i_sh] = shower_angle\n variables[\"shower_pdg\"][i_sh] = root_chain.matched_showers[i_sh]\n variables[\"shower_start_x\"][i_sh] = root_chain.shower_start_x[i_sh]\n variables[\"shower_start_y\"][i_sh] = root_chain.shower_start_y[i_sh]\n variables[\"shower_start_z\"][i_sh] = root_chain.shower_start_z[i_sh]\n variables[\"shower_theta\"][i_sh] = math.degrees(root_chain.shower_theta[i_sh])\n variables[\"shower_phi\"][i_sh] = math.degrees(root_chain.shower_phi[i_sh])\n shower_energy_cali = root_chain.shower_energy[i_sh][2] * root_chain.shower_energy_cali[i_sh][2]\n variables[\"shower_energy\"][i_sh] = max(-999, shower_energy_cali)\n dedx = root_chain.shower_dEdx[i_sh][2]\n dqdx = root_chain.shower_dQdx[i_sh][2] * root_chain.shower_dQdx_cali[i_sh][2]\n variables[\"shower_dedx\"][i_sh] = max(-999, dedx)\n dedx_cali = dqdx * root_chain.shower_dQdx_cali[i_sh][2] * 3.85e-5\n variables[\"shower_dqdx\"][i_sh] = max(-999, dqdx)\n variables[\"shower_dedx_cali\"][i_sh] = max(-999, dedx_cali)\n dedx_u = root_chain.shower_dEdx[shower_id][0] * root_chain.shower_dQdx_cali[shower_id][0]\n variables[\"shower_dedx_u\"][i_sh] = max(-999, dedx_u)\n dedx_v = root_chain.shower_dEdx[shower_id][1] * root_chain.shower_dQdx_cali[shower_id][1]\n variables[\"shower_dedx_v\"][i_sh] = max(-999, dedx_v)\n variables[\"shower_res_mean\"][i_sh] = max(-999, root_chain.shower_res_mean[i_sh])\n variables[\"shower_res_std\"][i_sh] = max(-999, root_chain.shower_res_std[i_sh])\n variables[\"shower_open_angle\"][i_sh] = math.degrees(root_chain.shower_open_angle[i_sh])\n variables[\"shower_pca\"][i_sh] = max(0, root_chain.shower_pca[i_sh][2])\n total_shower_energy += root_chain.shower_energy[i_sh][hit_index]\n total_shower_energy_cali += shower_energy_cali\n total_shower_nhits += root_chain.shower_nhits[i_sh][2]\n shower_vertex_d = math.sqrt(sum([(t - n)**2 for t, n in zip(shower_v, neutrino_vertex)]))\n variables[\"shower_distance\"][i_sh] = shower_vertex_d\n if particleid and check_conversion:\n variables[\"shower_pidchimu\"][i_sh] = root_chain.track_pid_chimu[n_tr + i_sh]\n variables[\"shower_pidchipi\"][i_sh] = root_chain.track_pid_chimu[n_tr + i_sh]\n variables[\"shower_pidchipr\"][i_sh] = root_chain.track_pid_chipr[n_tr + i_sh]\n\n for i_tr in range(root_chain.n_tracks):\n v_track = TVector3(\n root_chain.track_dir_x[i_tr],\n root_chain.track_dir_y[i_tr],\n root_chain.track_dir_z[i_tr]\n )\n\n track_vertex = [\n root_chain.track_start_x[i_tr],\n root_chain.track_start_y[i_tr],\n root_chain.track_start_z[i_tr]\n ]\n\n total_track_nhits += root_chain.track_nhits[i_tr][2]\n variables[\"n_tracks\"][0] += 1\n variables[\"track_pdg\"][i_tr] = root_chain.matched_tracks[i_tr]\n\n if particleid:\n variables[\"track_pidchipr\"][i_tr] = root_chain.track_pid_chipr[i_tr]\n mip_likelihood = root_chain.track_bragg_mip[i_tr]\n p_likelihood = root_chain.track_bragg_p[i_tr]\n else:\n mip_likelihood = 0\n p_likelihood = 0\n variables[\"track_mip_likelihood\"][i_tr] = mip_likelihood\n variables[\"track_p_likelihood\"][i_tr] = p_likelihood\n if p_likelihood > 1e-9:\n variables[\"track_likelihood\"][i_tr] = math.log(mip_likelihood/p_likelihood)\n variables[\"track_dqdx\"][i_tr] = max(-999, root_chain.track_dQdx[i_tr][2])\n if root_chain.category == 0 or root_chain.category == 6 and variables[\"track_dqdx\"][i_tr] != -999:\n variables[\"track_dqdx\"][i_tr] *= 1.2\n variables[\"track_phi\"][i_tr] = math.degrees(root_chain.track_phi[i_tr])\n variables[\"track_theta\"][i_tr] = math.degrees(root_chain.track_theta[i_tr])\n variables[\"track_length\"][i_tr] = root_chain.track_len[i_tr]\n variables[\"track_start_x\"][i_tr] = root_chain.track_start_x[i_tr]\n variables[\"track_start_y\"][i_tr] = root_chain.track_start_y[i_tr]\n variables[\"track_start_z\"][i_tr] = root_chain.track_start_z[i_tr]\n variables[\"track_pca\"][i_tr] = max(-999, root_chain.track_pca[i_tr][2])\n variables[\"track_res_mean\"][i_tr] = max(-999, root_chain.track_res_mean[i_tr])\n variables[\"track_res_std\"][i_tr] = max(-999, root_chain.track_res_std[i_tr])\n variables[\"track_end_x\"][i_tr] = root_chain.track_end_x[i_tr]\n variables[\"track_end_y\"][i_tr] = root_chain.track_end_y[i_tr]\n variables[\"track_end_z\"][i_tr] = root_chain.track_end_z[i_tr]\n length_e = length2energy(root_chain.track_len[i_tr])\n total_track_energy_length += length_e\n variables[\"track_energy_length\"][i_tr] = length_e\n costheta_shower_track = v_track.Dot(vec_shower) / (v_track.Mag() * vec_shower.Mag())\n variables[\"track_shower_angle\"][i_tr] = costheta_shower_track\n track_vertex_d = math.sqrt(\n sum([(t - n)**2 for t, n in zip(track_vertex, neutrino_vertex)]))\n variables[\"track_distance\"][i_tr] = track_vertex_d\n\n variables[\"track_hits\"][0] = total_track_nhits\n variables[\"shower_hits\"][0] = total_shower_nhits\n variables[\"hits_ratio\"][0] = total_shower_nhits/(total_track_nhits+total_shower_nhits)\n\n variables[\"total_shower_energy\"][0] = total_shower_energy\n variables[\"total_shower_energy_cali\"][0] = total_shower_energy_cali\n variables[\"total_track_energy_length\"][0] = total_track_energy_length\n # print(root_chain.reconstructed_neutrino_energy, (total_shower_energy_cali + 3.33417e-02) / 7.70732e-01 + total_track_energy_length)\n variables[\"reco_energy\"][0] = ((total_shower_energy_cali + 3.33417e-02) / 7.70732e-01 + total_track_energy_length + 2.85112e-02)/9.80163e-01\n variables[\"numu_score\"][0] = root_chain.numu_passed\n\n if root_chain.ccnc == 1 and variables[\"category\"][0] not in (0, 1, 5, 7):\n variables[\"category\"][0] = 4\n if not variables[\"true_nu_is_fidvol\"][0] and variables[\"category\"][0] != 0 and variables[\"category\"][0] != 6 and variables[\"category\"][0] != 1 and variables[\"category\"][0] != 7:\n variables[\"category\"][0] = 5\n\n if variables[\"category\"][0] not in (0, 2, 6, 8) and option not in (\"nue\", \"dirt\"):\n variables[\"is_signal\"][0] = 0.5\n else:\n variables[\"is_signal\"][0] = -1\n\ndef pt_plot(root_chain, plane):\n p_showers = []\n for ish in range(root_chain.n_showers):\n if root_chain.shower_energy[ish][plane] > 0:\n p_vector = TVector3(\n root_chain.shower_dir_x[ish],\n root_chain.shower_dir_y[ish],\n root_chain.shower_dir_z[ish])\n if root_chain.shower_energy[ish][plane] < 10:\n p_vector.SetMag(\n math.sqrt(\n (root_chain.shower_energy[ish][plane] + ELECTRON_MASS)**2 - ELECTRON_MASS**2))\n p_showers.append(p_vector)\n\n p_tracks = []\n for itr in range(root_chain.n_tracks):\n if root_chain.track_energy_hits[itr][plane] > 0:\n p_vector = TVector3(\n root_chain.track_dir_x[itr],\n root_chain.track_dir_y[itr],\n root_chain.track_dir_z[itr])\n p_vector.SetMag(\n math.sqrt(\n (root_chain.track_energy_hits[itr][plane] +\n PROTON_MASS)**2 -\n PROTON_MASS**2))\n p_tracks.append(p_vector)\n\n p_track_sum = TVector3()\n if p_tracks:\n p_track_sum = p_tracks[0]\n for itr in p_tracks[1:]:\n p_track_sum += itr\n\n p_shower_sum = TVector3()\n if p_showers:\n p_shower_sum = p_showers[0]\n for ish in p_showers[1:]:\n p_shower_sum += ish\n\n pt = (p_track_sum + p_shower_sum).Perp()\n return pt\n\n\ndef fill_tree(chain, weight, tree, option=\"\"):\n total_events = 0\n total_entries = int(chain.GetEntries() / 1)\n print(\"Events\", total_entries)\n for ievt in tqdm(range(total_entries)):\n chain.GetEntry(ievt)\n\n if not chain.passed:\n continue\n\n track_fidvol = True\n\n for i_tr in range(chain.n_tracks):\n track_start = [\n chain.track_start_x[i_tr],\n chain.track_start_y[i_tr],\n chain.track_start_z[i_tr]\n ]\n track_end = [\n chain.track_end_x[i_tr],\n chain.track_end_y[i_tr],\n chain.track_end_z[i_tr]\n ]\n\n track_fidvol = track_fidvol and is_fiducial(track_start) and is_fiducial(track_end)\n if not track_fidvol:\n break\n\n if not track_fidvol:\n continue\n\n shower_fidvol = True\n\n for i_sh in range(chain.n_showers):\n shower_start = [\n chain.shower_start_x[i_sh],\n chain.shower_start_y[i_sh],\n chain.shower_start_z[i_sh]\n ]\n\n shower_fidvol = shower_fidvol and is_fiducial(shower_start)\n if not shower_fidvol:\n break\n\n if not shower_fidvol:\n continue\n\n option_check = True\n event_weight = weight\n\n if option == \"bnb\":\n option_check = abs(chain.nu_pdg) != 12\n event_weight = weight * chain.bnbweight\n if abs(chain.nu_pdg) == 12:\n event_weight = weight * chain.bnbweight\n if \"nue\" in option:\n option_check = abs(chain.nu_pdg) == 12\n\n if option == \"lee\":\n event_weight = weight * chain.bnbweight * chain.leeweight\n\n if not option_check:\n continue\n\n neutrino_vertex = [chain.vx, chain.vy, chain.vz]\n\n if not is_fiducial(neutrino_vertex):\n continue\n\n # If there are no tracks we require at least two showers\n showers_2_tracks_0 = True\n if chain.n_tracks == 0 and chain.n_showers == 1:\n showers_2_tracks_0 = False\n if not showers_2_tracks_0:\n continue\n\n total_events += event_weight\n\n if \"nue\" in option and (chain.category == 2 or chain.category == 7 or chain.category == 8):\n if not check_cc0pinp(chain):\n option = \"nue_cc\"\n else:\n option = \"nue\"\n\n fill_kin_branches(chain, event_weight, variables, option)\n\n tree.Fill()\n\n return total_events\n\n\nif __name__ == \"__main__\":\n begin_time = time.time()\n # To be obtained with Zarko's POT tool\n data_ext_scaling_factor = 0.1327933846 # Sample with remapped PMTs\n\n samples = [\"nue\", \"bnb\", \"dirt\", \"bnb_data\", \"ext_data\", \"lee\"]\n\n tree_files = [glob(\"data_files/mc_nue_sbnfit/*a.root\"),\n glob(\"data_files/sys/%s/*.root\" % variable),\n glob(\"data_files/dirt/*a.root\"),\n glob(\"data_files/data_bnb/*/*a.root\"),\n glob(\"data_files/data_ext/*/*a.root\"),\n glob(\"data_files/mc_nue/*a.root\"), ]\n\n chains = []\n chains_pot = []\n for i, files in enumerate(tree_files):\n chains.append(TChain(\"robertoana/pandoratree\"))\n if i == 1:\n chains_pot.append(TChain(\"nueFilter/pot\"))\n else:\n chains_pot.append(TChain(\"robertoana/pot\"))\n\n for j, f in enumerate(files):\n chains[i].Add(f)\n chains_pot[i].Add(f)\n\n pots = []\n for k, c in enumerate(chains_pot):\n total_pot_file = 0\n for i in range(c.GetEntries()):\n c.GetEntry(i)\n total_pot_file += c.pot\n\n pots.append(total_pot_file)\n\n\n pots_dict = dict(zip(samples, pots))\n chains_dict = dict(zip(samples, chains))\n chains_pot_dict = dict(zip(samples, chains_pot))\n variables = dict(variables + spectators)\n\n weights = [0,#total_pot / pots_dict[\"nue\"] * 1.028, # Position of the detector is slightly wrong\n total_pot / pots_dict[\"bnb\"],\n 0,#total_pot / pots_dict[\"dirt\"] * 1.028 * 0.5,\n 1,\n 0,#data_ext_scaling_factor,\n 0]#total_pot / pots_dict[\"lee\"] * 1.028]\n\n print(\"Weights\", weights)\n files = [\"nue_%s_file.root\" % variable,\n \"mc_%s_file.root\" % variable,\n \"dirt%s_.root\" % variable,\n \"bnb_%s_file.root\" % variable,\n \"bnbext_%s_file.root\" % variable,\n \"lee_%s_file.root\" % variable]\n tree_names = [\"nue_tree\",\n \"mc_tree\",\n \"mc_tree\",\n \"bnb_tree\",\n \"bnbext_tree\",\n \"lee_tree\"]\n\n trees = []\n\n for t in tree_names:\n trees.append(TTree(t, t))\n\n for n, b in variables.items():\n for t in trees:\n if len(b) > 1:\n if \"track\" in n:\n t.Branch(n, b, \"%s[%i]/%s\" % (n, MAX_N_TRACKS, b.typecode))\n elif \"shower\" in n:\n t.Branch(n, b, \"%s[%i]/%s\" % (n, MAX_N_SHOWERS, b.typecode))\n elif \"weights\" in n:\n t.Branch(n, b, \"%s[%i]/%s\" % (n, N_UNI, b.typecode))\n else:\n t.Branch(n, b, n + \"/%s\" % b.typecode)\n\n samples = [\"nue\", \"bnb\", \"dirt\", \"bnb_data\", \"ext_data\", \"lee\"]\n\n for i, s in enumerate(samples):\n start_time = time.time()\n print(\"******************************\")\n print(\"Sample\", s)\n print(\"Weight\", weights[i])\n events = fill_tree(chains[i], weights[i], trees[i], s)\n print(\"\\nEvents\", events)\n print(\"Time to fill %.1f s\" % (time.time() - start_time))\n\n for f, t in zip(files, trees):\n tfile = TFile(\"root_files_sys/\" + f, \"RECREATE\")\n t.Write()\n tfile.Close()\n\n print(\"Total time %.2f\" % (time.time() - begin_time))\n","sub_path":"fill_det.py","file_name":"fill_det.py","file_ext":"py","file_size_in_byte":34801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"415131766","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Dec 17 16:32:44 2020\r\n\r\n@author: raajesh.rameshbabu\r\n\"\"\"\r\n1.\r\n# write a python function to check user provided number is prime or not and print the result\r\ndef primeornot(num):\r\n if num > 1:\r\n for i in range(2,num):\r\n if (num % i) == 0:\r\n print(num,\"is not a prime number\")\r\n break\r\n else:\r\n print(num,\"is a prime number\")\r\n else:\r\n print(num,\"is not a prime number\")\r\n\r\nprimeornot(7) \r\n\r\n2.\r\n# write a python program to swap two numbers and print it\r\nnum1 = 5\r\nnum2 = 10\r\ntemp = num1\r\nnum1 = num2\r\nnum2 = temp\r\nprint(\"The value of num1 after swapping: {}\".format(num1))\r\nprint(\"The value of num2 after swapping: {}\".format(num2))\r\n\r\n3. \r\n# write a python function to add user provided list and return the result\r\ndef addlist(list1,list2):\r\n result = list1+list2\r\n return result\r\n\r\nanswer = addlist(['cat','dog'],['samsung','oneplus'])\r\n\r\n4.\r\n# write a python function to reverse user provided list and return the result\r\ndef reverselist(inlist): \r\n inlist = inlist[::-1] \r\n return inlist\r\n\r\nresult = reverselist([1,2])\r\n\r\n5.\r\n\r\n\r\n\r\n","sub_path":"DeepLearningExperiments/NLP Experiments/NLP Seq 2 Seq/TextandCode.py","file_name":"TextandCode.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"542831449","text":"# -*- coding: utf-8 -*-\nimport operator\nimport bs4\nimport urllib\nfrom urllib.request import urlopen\nfrom urllib.parse import urlparse\nfrom urllib.parse import quote\nimport time\nimport os\nimport sys\nimport json\n\nif len(sys.argv) < 2:\n sys.argv.append('117010233') #117010233 # 53203558\n\n\ndef get_html(x):\n x = quote(x)\n url = urlparse('http://movie.douban.com/people/%s/collect?sort=time&start=%s&filter=all&mode=list&tags_sort=count' % (sys.argv[1],x))\n res = urlopen(url.geturl())\n xml = res.read().decode('utf-8')\n return xml\n \ndef get_mv_html(x):\n x = quote(x)\n url = urlparse('http://api.douban.com/v2/movie/subject/%s' % x)\n res = urlopen(url.geturl())\n xml = res.read().decode('utf-8')\n return xml\n\ndef gen_mv(x, info):\n #time.sleep(0.5)\n #print(x)\n if os.path.exists('./cache/' + x):\n print('cache %s', x)\n with open('./cache/' + x, 'r') as f:\n data = json.load(f)\n else:\n print('getting %s', x)\n data = json.loads(get_mv_html(x))\n time.sleep(0.1)\n with open('./cache/' + x, 'w+') as f:\n json.dump(data, f)\n info[\"web_score\"] = data[\"rating\"][\"average\"]\n info[\"ratings_count\"] = data[\"ratings_count\"]\n info[\"title\"] = data[\"title\"]\n info[\"countries\"] = data[\"countries\"]\n info[\"genres\"] = data[\"genres\"]\n info[\"cast\"] = []\n for v in data[\"casts\"]:\n info[\"cast\"].append(v[\"name\"])\n info[\"directors\"] = []\n for v in data[\"directors\"]:\n info[\"directors\"].append(v[\"name\"])\n \n\nviews = []\ni = 0\nflag = True\n#Glbal\nname = ''\n\n\nwhile flag:\n xml = get_html(\"%d\" % i)\n i += 30\n root = bs4.BeautifulSoup(xml, \"lxml\")\n if len(root.select(\".item-show\")) == 0:\n name = root.select(\".side-info-txt h3\")[0].text\n flag = False\n\n for v in root.select(\".list-view li\"):\n info = {}\n info[\"title\"] = v.select(\".title a\")[0].text.strip()\n try:\n info[\"rating\"] = int(v.select(\".date span\")[0]['class'][0][6])\n except:\n print(\"no rating\" + str(len(views)))\n #info[\"rating\"] = 0\n #print(\"rate %d\"%rating_sum)\n info[\"date\"] = v.select(\".date\")[0].text.strip()\n if v.select(\".comment\"):\n info[\"comment\"] = v.select(\".comment\")[0].text.strip()\n \n info[\"href\"] = v.select(\".title a\")[0][\"href\"]\n try:\n gen_mv(info[\"href\"].split(\"/\")[-2], info)\n except urllib.error.HTTPError as e:\n print(\"ERR:\", e)\n continue\n views.append(info)\n print(len(views))\n\n# Collect\nres_map = {\"name\":name, \"cast\":{},\"comm_count\":0.0, \"comm_chars\":0, \"rating_sum\":0, \"directors\":{}, \"countries\":{}, \"genres\":{},\n\"rating_count\":0.0, \"web_rating\":0, \"web_rc\":0.0, \"up8\":0, \"down4\":0, \"over2w\":0}\nfor v in views:\n if \"comment\" in v:\n res_map[\"comm_count\"] += 1\n res_map[\"comm_chars\"] += len(v[\"comment\"])\n if \"rating\" in v:\n res_map[\"rating_sum\"] += v[\"rating\"]\n res_map[\"rating_count\"] += 1\n if \"web_score\" in v:\n res_map[\"web_rc\"] += 1\n res_map[\"web_rating\"] += v[\"web_score\"]\n if v[\"web_score\"] >= 7:\n res_map[\"up8\"] += 1\n elif v[\"web_score\"] < 6:\n res_map[\"down4\"] += 1\n if \"ratings_count\" in v:\n if v[\"ratings_count\"] > 100000:\n res_map[\"over2w\"] += 1\n for s in v[\"cast\"]:\n if s in res_map[\"cast\"]:\n res_map[\"cast\"][s] += 1\n else:\n res_map[\"cast\"][s] = 1\n for s in v[\"directors\"]:\n if s in res_map[\"directors\"]:\n res_map[\"directors\"][s] += 1\n else:\n res_map[\"directors\"][s] = 1\n for s in v[\"countries\"]:\n if s in res_map[\"countries\"]:\n res_map[\"countries\"][s] += 1\n else:\n res_map[\"countries\"][s] = 1\n for s in v[\"genres\"]:\n if s in res_map[\"genres\"]:\n res_map[\"genres\"][s] += 1\n else:\n res_map[\"genres\"][s] = 1\n\n# Summary\nres_map[\"directors\"] = sorted(res_map[\"directors\"].items(), key=operator.itemgetter(1), reverse=True)[:10]\nres_map[\"cast\"] = sorted(res_map[\"cast\"].items(), key=operator.itemgetter(1), reverse=True)[:10]\nres_map[\"genres\"] = sorted(res_map[\"genres\"].items(), key=operator.itemgetter(1), reverse=True)[:10]\nres_map[\"countries\"] = sorted(res_map[\"countries\"].items(), key=operator.itemgetter(1), reverse=True)[:10]\n\nweb_r_avg = res_map[\"web_rating\"]/res_map[\"web_rc\"]\nif web_r_avg > 6:\n web_bb = \"您的口碑相当不错!\"\nelse:\n web_bb = \"看来您喜欢多种电影。\"\nimport json\n#print(json.dumps(views))\n#print(views)\nprint('%s, 在您的豆瓣生涯中,您总共看了 %d 部电影。' % (res_map[\"name\"], len(views)))\nprint('您评论了 %d 部电影,共花了 %d 字。有 %.2f%% 的电影被你评论, 平均每篇花费 %.2f 字' % (res_map[\"comm_count\"], res_map[\"comm_chars\"], res_map[\"comm_count\"]/len(views)*100.0,res_map[\"comm_chars\"]/res_map[\"comm_count\"]))\nprint('您平均打分 %.2f 分。' % (res_map[\"rating_sum\"]/res_map[\"rating_count\"]*2))\nprint('你看过的电影网友平均打分 %.2f 分。有 %d 部被认为是7分好片,有 %d 部被认为是5分烂片。%s' % (web_r_avg, res_map[\"up8\"], res_map[\"down4\"], web_bb))\nprint('你看过的电影有 %d 部被10万人评分过,是当时的热片。' % (res_map[\"over2w\"]))\nprint('')\nprint('您看过最多的三个导演:%s %d 部,%s %d 部,%s %d 部。' % (res_map[\"directors\"][0][0], res_map[\"directors\"][0][1], res_map[\"directors\"][1][0], res_map[\"directors\"][1][1], res_map[\"directors\"][2][0], res_map[\"directors\"][2][1]))\nprint('您看过最多的三个演员:%s %d 部,%s %d 部,%s %d 部。' % (res_map[\"cast\"][0][0], res_map[\"cast\"][0][1], res_map[\"cast\"][1][0], res_map[\"cast\"][1][1], res_map[\"cast\"][2][0], res_map[\"cast\"][2][1]))\nprint('您看过最多的三个影片类型:%s %d 部,%s %d 部,%s %d 部。' % (res_map[\"genres\"][0][0], res_map[\"genres\"][0][1], res_map[\"genres\"][1][0], res_map[\"genres\"][1][1], res_map[\"genres\"][2][0], res_map[\"genres\"][2][1]))\nprint('您看过最多的三个地区的影片:%s %d 部,%s %d 部,%s %d 部。' % (res_map[\"countries\"][0][0], res_map[\"countries\"][0][1], res_map[\"countries\"][1][0], res_map[\"countries\"][1][1], res_map[\"countries\"][2][0], res_map[\"countries\"][2][1]))\n\n\n","sub_path":"douban/final_douban.py","file_name":"final_douban.py","file_ext":"py","file_size_in_byte":6356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"42257689","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport numpy as np\nimport os\n\nfrom .unet_parts import *\n\n\nclass UNet(nn.Module):\n\n\t# n_channels, n_classes, lr=1e-4, opt='Adam', lossf='MSE', logger_dir='', PreTrained=True\n\n\tdef __init__(self, config):\n\n\t\tn_channels = config['n_channels']\n\t\tn_classes = config['n_classes']\n\t\tlr = config['lr']\n\t\topt = config['optimizer']\n\t\tlossf = config['lossf']\n\t\tself.PreTrained = config['PreTrained']\n\t\tself.config = config\n\t\t\n\t\tsuper(UNet, self).__init__()\n\t\tself.inc = inconv(n_channels, 64)\n\t\tself.down1 = down(64, 128)\n\t\tself.down2 = down(128, 256)\n\t\tself.down3 = down(256, 512)\n\t\tself.down4 = down(512, 512)\n\t\tself.up1 = up(1024, 256)\n\t\tself.up2 = up(512, 128)\n\t\tself.up3 = up(256, 64)\n\t\tself.up4 = up(128, 64)\n\t\tself.outc = outconv(64, n_classes)\n\n\t\tif opt == 'Adam':\n\t\t\tself.opt = optim.Adam(self.parameters(), lr=lr)\n\n\t\tif lossf == 'CEL':\n\t\t\tself.lossf = torch.nn.CrossEntropyLoss()\n\t\telif lossf == 'MSE':\n\t\t\tself.loss = torch.nn.MSELoss()\n\n\tdef accuracy(self, x, y):\n\n\t\t_, arg = torch.max(x, dim=1)\n\n\t\teq = torch.eq(arg.squeeze(), y.squeeze())\n\n\t\treturn torch.mean(eq.float())\n\n\tdef print_info(self, info):\n\n\t\tprint('The average accuracy is :', np.mean(info['Acc']))\n\t\tprint('The current accuracy is :', info['Acc'][-1])\n\t\tprint('The average loss is :', np.mean(info['Loss']))\n\t\tprint('The current loss is :', info['Loss'][-1])\n\n\tdef forward(self, x):\n\t\tx1 = self.inc(x)\n\t\tx2 = self.down1(x1)\n\t\tx3 = self.down2(x2)\n\t\tx4 = self.down3(x3)\n\t\tx5 = self.down4(x4)\n\t\tx = self.up1(x5, x4)\n\t\tx = self.up2(x, x3)\n\t\tx = self.up3(x, x2)\n\t\tx = self.up4(x, x1)\n\t\tx = self.outc(x)\n\n\t\treturn x\n\n\tdef save(self, no, epoch_i, info, is_best=False, filename='checkpoint.pth.tar'):\n\n\t\ttorch.save({'epoch': epoch_i,\n\t\t\t\t\t'state_dict': self.state_dict(),\n\t\t\t\t\t'optimizer': self.opt.state_dict()},str(no)+'_'+str(epoch_i)+'_'+filename)\n\t\ttorch.save(info, str(no)+'_'+str(epoch_i)+'_'+'info_'+filename)\n\t\tif is_best:\n\t\t\tshutil.copyfile(str(no)+'_'+str(epoch_i)+'_'+filename, 'model_best.pth.tar')\n\t\t\tshutil.copyfile(str(no)+'_'+str(epoch_i)+'_'+'info_'+filename, 'info_model_best.pth.tar')\n\n\tdef load(self, path, path_info):\n\n\t\tcheckpoint = torch.load(path)\n\n\t\tself.load_state_dict(checkpoint['state_dict'])\n\t\tself.opt.load_state_dict(checkpoint['optimizer'])\n\n\t\treturn checkpoint['epoch'], torch.load(path_info)\n\n\tdef loss(self, pred, target, info):\n\n\t\tb, ch, h, w = pred.size()\n\n\t\tpred = pred.contiguous().view(b, ch)\n\t\ttarget = target.contiguous().view(b)\n\n\t\tloss_c = self.lossf(pred, target)\n\n\t\tif info['Keep_log']:\n\t\t\tinfo['Acc'].append(self.accuracy(pred, target).data.cpu().numpy()[0])\n\t\t\tinfo['Loss'].append(loss_c.data.cpu().numpy()[0])\n\n\t\telse:\n\t\t\tinfo['Acc'] = (self.accuracy(pred, target).data.cpu().numpy()[0] + info['Count']*info['Acc'])/(info['Count']+1)\n\t\t\tinfo['Loss'] = (loss_c.data.cpu().numpy()[0] + info['Count']*info['Loss'])/(info['Count']+1)\n\n\t\tinfo['Count'] += 1\n\t\treturn loss_c","sub_path":"misc/unet.py","file_name":"unet.py","file_ext":"py","file_size_in_byte":2971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"120801823","text":"#add parent dir to find package. Only needed for source code build, pip install doesn't need it.\nimport os, inspect\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nparentdir = os.path.dirname(os.path.dirname(currentdir))\nos.sys.path.insert(0,parentdir)\n\nimport datetime\nimport argparse\nfrom ..Trainer import Trainer\n\n\ntrainer = Trainer.Trainer()\n\nargparser = argparse.ArgumentParser()\nTrainer.add_opts(argparser)\n\n# precoded options\nopts = argparser.parse_args()\nopts.agent = \"KerasDDPGAgent-v0\"\nopts.env = \"ThrowerPyBulletEnv-v0\"\nopts.train_for = 10000000\nopts.test_for = 0\ndatenow = '{:%Y%m%d%H%M%S}'.format(datetime.datetime.now())\nopts.save_file = \"checkpoints/%s-%s-%s.h5\" % (opts.agent, opts.env, datenow)\n\nprint(\"\\n OPTS\", opts)\n\ntrainer.setup_exercise(opts)\n\n\n","sub_path":"pybulletgym/examples/keras-rl/train_KerasDDPG_ThrowerBulletEnv.py","file_name":"train_KerasDDPG_ThrowerBulletEnv.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"487583568","text":"#!/usr/bin/python3\r\n# -*- coding: utf-8 -*-\r\n\r\n\"\"\"\r\n求一个向量在一个新的基底下的坐标\r\n主要是用求解线性方程组的方法求解\r\n\"\"\"\r\nimport numpy as np\r\nfrom scipy.linalg import solve\r\n\r\ndef baseCoordinate(alpha, theta):\r\n alpha = alpha.T\r\n theta = theta.T\r\n if len(theta) != len(theta.T):\r\n print(\"基底组成的矩阵应该是方阵!!!\")\r\n elif len(alpha) != len(theta):\r\n print(\"向量的维数应该等于基底的个数!!!\")\r\n else:\r\n # solve\r\n coordinate = solve(theta, alpha) #坐标\r\n return coordinate.T\r\n\r\n# 例子:\r\nalpha = np.array([3, 7, 1])\r\ntheta = np.array([[1, 3, 5], [6, 3, 2], [3, 1, 0]])\r\ncoordinate = baseCoordinate(alpha, theta)\r\nprint(coordinate)\r\n","sub_path":"coordinate.py","file_name":"coordinate.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"396863666","text":"#Getting user details\ndef get_user_details(username):\n details = []\n url = \"http://dodgethat.co.uk/user_details.php?username=\"+str(username)\n ope = urllib.request.Request(url)\n read = urllib.request.urlopen(ope)\n read = str(read.read())\n spl = read.split(\"b'\")\n spl = spl[1]\n spl = spl.split(\",\")\n for detail in spl:\n details.append(detail)\n return details\n#Getting all the bar details from server\n\ndef get_all_bars(page = 1):\n all_bars = []\n load = urllib.request.Request(\"http://dodgethat.co.uk/bars/bars.php?bars=all&page=\"+str(page))\n op = urllib.request.urlopen(load)\n read = str(op.read())\n scanned = read.split(\"b'\")\n scanned = scanned[1]\n each_item = scanned.split(\"\\\\n\")\n looper = 0\n for items in each_item:\n if looper < len(each_item) - 1:\n all_bars.append(items)\n looper += 1\n return all_bars\n#Getting bar details ends here\n\n#Buying Bar\ndef buy_bar(username,bar_name):\n url = \"http://dodgethat.co.uk/bars/bars.php?buy=1&username=\"+str(username)+\"&bar=\"+str(bar_name)\n push = urllib.request.urlopen(url)\n#Buying bars ends here\n\n\n\n#Get User Owned Bars\ndef get_user_bars(username):\n owned_bars = []\n url = \"http://dodgethat.co.uk/bars/bars.php?get_bar=1&username=\"+str(username)\n url_open = urllib.request.Request(url)\n url_read = urllib.request.urlopen(url_open)\n res = str(url_read.read())\n spl = res.split(\"b'\")\n spl = spl[1]\n spl = spl.split(\"\\\\n\")\n for bars in spl:\n owned_bars.append(bars)\n del owned_bars[-1]\n\n return owned_bars\n#Get user owned bars end here\n\n\n#Get each bar detail\ndef get_each_bar_detail(bar_id):\n details = []\n url = \"http://dodgethat.co.uk/bars/bars.php?get_bar=1&barid=\"+str(bar_id)\n url_open = urllib.request.Request(url)\n url_req = urllib.request.urlopen(url_open)\n url_read = str(url_req.read())\n spl = url_read.split(\"b'\")\n spl = spl[1]\n spl = spl.split(\",\")\n for detail in spl:\n details.append(detail)\n return details\n#Each bar detail ends here\n\n\n\n#Get user selected bar\ndef get_user_selected_bar(username):\n url = \"http://dodgethat.co.uk/bars/bars.php?get_selected=1&username=\"+str(username)\n req = urllib.request.Request(url)\n res = urllib.request.urlopen(req)\n read = str(res.read())\n spl = read.split(\"b'\")\n spl = spl[1]\n spl = spl.split(\",\")\n bar_id = spl[0]\n return bar_id\n#Get user selected bar ends here\n\n#Update user selected bar\ndef update_user_bar(username,bar_name):\n url = \"http://dodgethat.co.uk/bars/bars.php?update_selected=1&username=\"+str(username)+\"&bar_name=\"+bar_name\n push = urllib.request.urlopen(url)\n#Update user selected bar ends here","sub_path":"scripts/users_bar.py","file_name":"users_bar.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"517573547","text":"# flask, json\nfrom flask import Flask, jsonify\n# websocket host\nfrom flask_sockets import Sockets\nfrom gevent import pywsgi\nfrom geventwebsocket.handler import WebSocketHandler\nimport message as m\n# random\nfrom random import randint\n\n\napp = Flask(__name__)\nsockets = Sockets(app)\n\n\ndef make_move():\n return randint(1, 3)\n\n\n@app.route(\"/rps\")\ndef rest_player():\n return jsonify(move=make_move())\n\n\n@sockets.route(\"/ws/rps\")\ndef ws_player(backend_ws):\n\n while not backend_ws.closed:\n msg = m.receive_from_outside(backend_ws)\n if msg.type == m.move_type:\n m.reply(backend_ws, m.Move(make_move()))\n # m.reply(backend_ws, m.EmptyMessage())\n\nif __name__ == '__main__':\n app.debug = True\n app.config['SECRET_KEY'] = 'secret!'\n server = pywsgi.WSGIServer(('', 5000),\n application=app,\n handler_class=WebSocketHandler)\n server.serve_forever()\n","sub_path":"ml/ml.py","file_name":"ml.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"177375455","text":"from gpiozero import MotionSensor,LED\nfrom time import sleep\n\npir = MotionSensor(4,queue_len=5,threshold=0.7)\nled = LED(17)\ni=0\nled.on()\nsleep(60)\nled.off()\n\ndef detected():\n\tprint(\"Motion detected\")\n\tled.on()\ndef undetected():\n\tprint(\"No motion\")\n\tled.off()\n\nwhile True:\n\tpir.when_motion = detected()\n\tpir.when_no_motion = undetected()\n\t\n \n","sub_path":"motion.py","file_name":"motion.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"221407609","text":"import numpy as np\n\n\nclass HREF:\n \"\"\"Container class to store up to 1 run of href data in 1 hour forecasts\"\"\"\n\n def __init__(self, model, run, lats, lons, old=False):\n \"\"\"Constructor for HREF class\n\n :param run: Datetime date of the model run (including hour)\n :param lats: Array or list of lats in the grid\n :param lons: Array or list of lons in the grid\n :param old: Flag to indicate whether this is a 'current' run or a previous one\n \"\"\"\n\n if lats.shape != lons.shape:\n print('ERROR: lats and lons must have the same shape!')\n\n self.model = model\n self.date = run\n self.lats = lats\n self.lons = lons\n self.data = {}\n self.old = old\n\n def add_hour_data(self, hour, data):\n \"\"\"Add one hour of href forecast data to the grid\n\n :param hour: The forecast hour of the data (e.g. 1, 5, 13, 23, etc)\n :param data: The href data to add. Should be a dict with structure\n {var name: data}\n \"\"\"\n\n # Add data to self.data dictionary with the forecast hour as the key\n self.data[hour] = data\n return\n\n def get_hour_data(self, hour, param):\n \"\"\"Retrieve a single hour of data\n\n :param hour: The forecast hour to query (e.g. 1, 5, 13, 23, etc)\n :param param: Variable to return. None --> return a dictionary of all variables\n :return: Dictionary/Array containing the gridded href data for the specified hour\n \"\"\"\n\n try:\n hour_data = self.data[hour][param]\n return hour_data\n\n except KeyError:\n return np.full(self.lats.shape, np.nan)\n\n def get_xmax(self, start, hours, param):\n \"\"\"Retrieve the maximum param value over a period of x hours\n\n :param start: Hour to begin querying (inclusive)\n :param hours: Number of forecast hours to query\n Ex. Start time = 12, hours = 4 will query forecast hours 12, 13, 14, 15\n :param param: Variable to query.\n :return: Gridded maximum values over the specified period\n \"\"\"\n\n # Process variable\n data = self.get_hour_data(start, param)\n for hour in range(1, hours):\n try:\n data = np.amax([data, self.get_hour_data(start + hour, param)],\n axis=0)\n except ValueError as e:\n continue\n return data\n\n def get_xmin(self, start, hours, param):\n \"\"\"Retrieve the minimum param value over a period of x hours\n\n :param start: Hour to begin querying (inclusive)\n :param hours: Number of forecast hours to query\n Ex. Start time = 12, hours = 4 will query forecast hours 12, 13, 14, 15\n :param param: Variable to query.\n :return: Gridded minimum values over the specified period\n \"\"\"\n\n # Process variable\n data = self.get_hour_data(start, param)\n for hour in range(1, hours):\n try:\n data = np.amin([data, self.get_hour_data(start + hour, param)],\n axis=0)\n except ValueError as e:\n continue\n return data\n\n","sub_path":"ush/href_calib_thunder/calib_thunder/data/href.py","file_name":"href.py","file_ext":"py","file_size_in_byte":3219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"265578529","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 17 12:37:58 2017\n\n@author: weir\n\"\"\"\n\nimport numpy as _np\nimport os as _os\nimport matplotlib.pyplot as _plt\n#import scipy.signal.correlate as xcorr\n\nfrom pybaseutils.fft_analysis import fftanal\nfrom pybaseutils.plt_utils import savefig\n\n# datafolder = _os.path.abspath(_os.path.join('~','bin'))\ndatafolder = _os.path.join('/homea','weir','bin')\nprint(datafolder)\n\ncmPerGHz = 1\n\n#scantitl = 'CECE_jan17_nelow'\n# scantitl += '_50to400'\n#scantitl += '_400to500'\n\n\nfils = ['CECE.65625','CECE.65626','CECE.65627','CECE.65628','CECE.65629']\nfreqs = [68.3, 68.0, 68.2, 68.1, 68.1]\n\nfils.extend(['CECE.65630','CECE.65631','CECE.65632','CECE.65633','CECE.65634'])\nfreqs.extend([68.15, 68.05, 67.95, 67.90, 68.125])\n\n# intb = [15e3, 500e3] # original\nintb = [50e3, 400e3] # broadband fluctuations\n# intb = [400e3, 465e3] # high frequency mode\n\ntb = [0.192, 0.370]\n\nhfig = _plt.figure()\nsub1 = _plt.subplot(3, 1, 1)\nsub1.set_xlabel('freq [KHz]')\nsub1.set_ylabel('Cross Power')\n\nsub2 = _plt.subplot(3, 1, 2)\n# sub2.set_ylim((0, 1))\nsub2.set_xlabel('freq [KHz]')\nsub2.set_ylabel('Cross Coherence')\n\nsub3 = _plt.subplot(3, 1, 3)\n# sub3.set_ylim((0, 1))\nsub3.set_xlabel('freq [GHz]')\nsub3.set_ylabel('Coherence Length') \n\nnfils = len(fils)\nfreqs = _np.asarray(freqs, dtype=_np.float64)\n\nPxy = _np.zeros( (nfils,), dtype=_np.complex64)\nPxx = _np.zeros( (nfils,), dtype=_np.complex64)\nPyy = _np.zeros( (nfils,), dtype=_np.complex64)\nCxy = _np.zeros( (nfils,), dtype=_np.complex64)\n\nfor ii in range(nfils):\n \n filn = _os.path.abspath(_os.path.join(datafolder, fils[ii]))\n print(filn)\n tt, tmpRF, tmpIF = \\\n _np.loadtxt(filn, dtype=_np.float64, unpack=True)\n \n tt = 1e-3*tt\n j0 = _np.floor( (tb[0]-tt[0])/(tt[1]-tt[0]))\n j1 = _np.floor( (tb[1]-tt[0])/(tt[1]-tt[0])) \n \n \n IRfft = fftanal(tt, tmpRF, tmpIF, tbounds=tb, Navr=5000) \n\n# ircor = xcorr(tmpRF[j0:j1], tmpIF[j0:j1])\n\n # ---------------- #\n \n freq = IRfft.freq\n i0 = _np.floor( (intb[0]-freq[0])/(freq[1]-freq[0]))\n i1 = _np.floor( (intb[1]-freq[0])/(freq[1]-freq[0])) \n\n sub1.plot(1e-3*IRfft.freq, 10*_np.log10(_np.abs(IRfft.Pxy)), '-') \n sub2.plot(1e-3*IRfft.freq, IRfft.Cxy, '-')\n \n # ---------------- #\n \n reP = _np.real(IRfft.Pxy)\n imP = _np.imag(IRfft.Pxy)\n \n Pxy[ii] = _np.trapz(reP[i0:i1], x=freq[i0:i1]) \\\n + 1j*_np.trapz(imP[i0:i1], x=freq[i0:i1]) \n Pxx[ii] = _np.trapz(IRfft.Pxx[i0:i1], x=freq[i0:i1])\n Pyy[ii] = _np.trapz(IRfft.Pyy[i0:i1], x=freq[i0:i1])\n \n # ---------------- #\n \n# end loop \nCxy = _np.abs( Pxy.conjugate()*Pxy ) / (_np.abs(Pxx)*_np.abs(Pyy) )\n \n# --------------- #\n \nsub1.axvline(x=1e-3*freq[i0], linewidth=2, color='k')\nsub1.axvline(x=1e-3*freq[i1], linewidth=2, color='k')\nsub2.axvline(x=1e-3*freq[i0], linewidth=2, color='k')\nsub2.axvline(x=1e-3*freq[i1], linewidth=2, color='k')\nsub3.plot(freqs, Cxy, 'o')\nsub3.text(_np.average(freqs), 0.05, \n '%i to %i GHz'%(int(1e-3*freq[i0]),int(1e-3*freq[i1])),\n fontsize=12)\n\n#_plt.figure()\n#_plt.xlabel('r [cm]')\n#_plt.ylabel('Cross Coherence')\n#_plt.plot(_np.abs(freqs-68.0)*cmPerGHz, Cxy, 'o' )\n\n#savefig(_os.path.join(datafolder,scantitl), ext='png', close=False, \n# verbose=True, dotsperinch = 300, transparency = True) \n#savefig(_os.path.join(datafolder,scantitl), ext='eps', close=False, \n# verbose=True, dotsperinch = 300, transparency = True)","sub_path":"Scripts/cece_anal_Jan172017_fix2 (3).py","file_name":"cece_anal_Jan172017_fix2 (3).py","file_ext":"py","file_size_in_byte":3568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"83132378","text":"from sort_algorithm import SortAlgorithm\n\nclass BubbleSort(SortAlgorithm):\n \"\"\"The BUBBLE SORT Algorithm.\n\n HOW IT WORKS:\n -------------\n The idea is bubbling up the bigger value to the end repeatedly until complete the ordering\n of the array. An outer loop pass through the arraay, whereas the inner loop compares the current\n against the next value swapping them pushing the bigger to the right.\n\n DISCUSSION:\n -----------\n Bubble sort has many of the same properties as insertion sort, but has\n slightly higher overhead. In the case of nearly sorted data, bubble sort\n takes O(n) time, but requires at least 2 passes through the data (whereas\n insertion sort requires something more like 1 pass).\n\n PROPERTIES:\n -----------\n - Stable\n - O(1) extra space\n - O(n^2) comparisons and swaps\n - Adaptive: O(n) when nearly sorted\n \"\"\"\n\n def sort(self,data):\n n = len(data)\n for i in range(1, n):\n swapped = False\n for j in range(0,n-i):\n if data[j] > data[j+1]:\n self.swap(data, j, j+1)\n swapped = True\n if swapped == False: break\n return data","sub_path":"src/algorithms/sorting/bubble_sort.py","file_name":"bubble_sort.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"215131570","text":"import csv\nfrom collections import defaultdict\n\nfrom elephant_pipeline import ElephantPipeline\n\n\nfieldnames = {\n 'Survived': 'INT',\n 'Pclass': 'INT',\n 'Name': 'VARCHAR(128)',\n 'Sex': 'VARCHAR(30)',\n 'Age': 'real',\n 'Siblings_Spouses_Aboard': 'INT',\n 'Parents_Children_Aboard': 'INT',\n 'Fare': 'real'\n}\n\ntable_name = 'titanic'\n\nwith open('titanic.csv', 'r') as f:\n reader = csv.reader(f)\n header = next(reader)\n pipeline = ElephantPipeline()\n pipeline.drop_table(table_name)\n pipeline.copy_table(table_name, fieldnames, reader)\n","sub_path":"module2-sql-for-analysis/insert_titanic.py","file_name":"insert_titanic.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"340418747","text":"from __future__ import absolute_import\n\nimport os\nimport socket\nimport random\nimport string\nimport time\nimport uuid\n\nimport pytest\nfrom . import unittest\n\nfrom kafka import SimpleClient, create_message\nfrom kafka.client_async import KafkaClient\nfrom kafka.errors import (\n LeaderNotAvailableError, KafkaTimeoutError, InvalidTopicError,\n NotLeaderForPartitionError, UnknownTopicOrPartitionError,\n FailedPayloadsError\n)\nfrom kafka.structs import OffsetRequestPayload, ProduceRequestPayload\n#from test.fixtures import random_string, version_str_to_list, version as kafka_version #pylint: disable=wrong-import-order\n\n\ndef random_string(length):\n return \"\".join(random.choice(string.ascii_letters) for i in range(length))\n\n\ndef env_kafka_version():\n \"\"\"Return the Kafka version set in the OS environment as a tuple.\n\n Example: '0.8.1.1' --> (0, 8, 1, 1)\n \"\"\"\n if 'KAFKA_VERSION' not in os.environ:\n return ()\n return tuple(map(int, os.environ['KAFKA_VERSION'].split('.')))\n\ndef get_open_port():\n sock = socket.socket()\n sock.bind((\"\", 0))\n port = sock.getsockname()[1]\n sock.close()\n return port\n\n_MESSAGES = {}\ndef msg(message):\n \"\"\"Format, encode and deduplicate a message\n \"\"\"\n global _MESSAGES #pylint: disable=global-statement\n if message not in _MESSAGES:\n _MESSAGES[message] = '%s-%s' % (message, str(uuid.uuid4()))\n\n return _MESSAGES[message].encode('utf-8')\n\ndef send_messages(client, topic, partition, messages):\n \"\"\"Send messages to a topic's partition\n \"\"\"\n messages = [create_message(msg(str(m))) for m in messages]\n produce = ProduceRequestPayload(topic, partition, messages=messages)\n resp, = client.send_produce_request([produce])\n assert resp.error == 0\n\n return [x.value for x in messages]\n\ndef current_offset(client, topic, partition, kafka_broker=None):\n \"\"\"Get the current offset of a topic's partition\n \"\"\"\n try:\n offsets, = client.send_offset_request([OffsetRequestPayload(topic,\n partition, -1, 1)])\n except Exception:\n # XXX: We've seen some UnknownErrors here and can't debug w/o server logs\n if kafka_broker:\n kafka_broker.dump_logs()\n raise\n else:\n return offsets.offsets[0]\n\n\ndef assert_message_count(messages, num_messages):\n \"\"\"Check that we received the expected number of messages with no duplicates.\"\"\"\n # Make sure we got them all\n assert len(messages) == num_messages\n # Make sure there are no duplicates\n # Note: Currently duplicates are identified only using key/value. Other attributes like topic, partition, headers,\n # timestamp, etc are ignored... this could be changed if necessary, but will be more tolerant of dupes.\n unique_messages = {(m.key, m.value) for m in messages}\n assert len(unique_messages) == num_messages\n\n\nclass KafkaIntegrationTestCase(unittest.TestCase):\n create_client = True\n topic = None\n zk = None\n server = None\n\n def setUp(self):\n super(KafkaIntegrationTestCase, self).setUp()\n if not os.environ.get('KAFKA_VERSION'):\n self.skipTest('Integration test requires KAFKA_VERSION')\n\n if not self.topic:\n topic = \"%s-%s\" % (self.id()[self.id().rindex(\".\") + 1:], random_string(10))\n self.topic = topic\n\n if self.create_client:\n self.client = SimpleClient('%s:%d' % (self.server.host, self.server.port))\n self.client_async = KafkaClient(bootstrap_servers='%s:%d' % (self.server.host, self.server.port))\n\n timeout = time.time() + 30\n while time.time() < timeout:\n try:\n self.client.load_metadata_for_topics(self.topic, ignore_leadernotavailable=False)\n if self.client.has_metadata_for_topic(topic):\n break\n except (LeaderNotAvailableError, InvalidTopicError):\n time.sleep(1)\n else:\n raise KafkaTimeoutError('Timeout loading topic metadata!')\n\n\n # Ensure topic partitions have been created on all brokers to avoid UnknownPartitionErrors\n # TODO: It might be a good idea to move this to self.client.ensure_topic_exists\n for partition in self.client.get_partition_ids_for_topic(self.topic):\n while True:\n try:\n req = OffsetRequestPayload(self.topic, partition, -1, 100)\n self.client.send_offset_request([req])\n break\n except (NotLeaderForPartitionError, UnknownTopicOrPartitionError, FailedPayloadsError) as e:\n if time.time() > timeout:\n raise KafkaTimeoutError('Timeout loading topic metadata!')\n time.sleep(.1)\n\n self._messages = {}\n\n def tearDown(self):\n super(KafkaIntegrationTestCase, self).tearDown()\n if not os.environ.get('KAFKA_VERSION'):\n return\n\n if self.create_client:\n self.client.close()\n\n def current_offset(self, topic, partition):\n try:\n offsets, = self.client.send_offset_request([OffsetRequestPayload(topic,\n partition, -1, 1)])\n except Exception:\n # XXX: We've seen some UnknownErrors here and can't debug w/o server logs\n self.zk.child.dump_logs()\n self.server.child.dump_logs()\n raise\n else:\n return offsets.offsets[0]\n\n def msgs(self, iterable):\n return [self.msg(x) for x in iterable]\n\n def msg(self, s):\n if s not in self._messages:\n self._messages[s] = '%s-%s-%s' % (s, self.id(), str(uuid.uuid4()))\n\n return self._messages[s].encode('utf-8')\n\n def key(self, k):\n return k.encode('utf-8')\n\n\nclass Timer(object):\n def __enter__(self):\n self.start = time.time()\n return self\n\n def __exit__(self, *args):\n self.end = time.time()\n self.interval = self.end - self.start\n","sub_path":"test/testutil.py","file_name":"testutil.py","file_ext":"py","file_size_in_byte":6084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"240520252","text":"import collections\nimport re\nimport os\nimport string\nimport bz2\n\nfrom math import ceil\n\nfrom pandas.core.common import flatten\nfrom tensorflow.keras.preprocessing.text import text_to_word_sequence, Tokenizer\n\n\nclass TextEncoder:\n \"\"\"\n This class takes as input a file containing text that we want to encode as integers for Word2Vec. It cleanses the\n data, splits the text into sentences, and returns a list of lists, where the entries are lists of integers\n corresponding to non-stop words of the sentences.\n\n The Word2Vec implementations in this package are intended to support graph embedding operations and text/NLP\n functionality is included for demonstration.\n\n Attributes:\n filename: a filepath and name to text which needs encoding.\n stopwords: a set of stopwords. If nothing is passed by user a default list of stopwords is utilized.\n\n Raises:\n If TypeErrors if the user does not pass a filename that is of type string and that resolves.\n\n \"\"\"\n\n def __init__(self, filename: str, stopwords: set = None):\n\n if filename is None:\n raise TypeError(\"Need to pass filename to constructor\")\n if not isinstance(filename, str):\n raise TypeError(\"File name arguments must be a string\")\n if not os.path.exists(filename):\n raise TypeError(\"Could not find file: \" + filename)\n self.filename = filename\n\n self.stopwords = [{'the', 'a', 'an', 'another', 'for', 'an', 'nor', 'but', 'or', 'yet', 'so'}\n if stopwords is None else stopwords][0]\n\n @staticmethod\n def clean_text(text: str):\n \"\"\"Takes a text string and performs several tasks that are intended to clean the text including making the\n text lowercase, undoing contractions,\n\n Args:\n text: A line of text, typically a line of text from a file.\n\n Returns:\n A cleansed version of the input text.\n\n \"\"\"\n\n # ensure text is lower case\n text = text.lower()\n\n # undo contractions\n text = text.replace(\"\\n\", \"\")\n text = text.replace(\"\\xad\", \"\")\n text = text.replace(\"'ve\", \" have\")\n text = text.replace(\"'t\", \" not\")\n text = text.replace(\"'s\", \" is\")\n text = text.replace(\"'m\", \" am\")\n\n # replace numbers with words representing number\n text = text.replace(\"0\", \" zero \")\n text = text.replace(\"1\", \" one \")\n text = text.replace(\"2\", \" two \")\n text = text.replace(\"3\", \" three \")\n text = text.replace(\"4\", \" four \")\n text = text.replace(\"5\", \" five \")\n text = text.replace(\"6\", \" six \")\n text = text.replace(\"7\", \" seven \")\n text = text.replace(\"8\", \" eight \")\n text = text.replace(\"9\", \" nine \")\n text = text.replace(\"10\", \" ten \")\n\n # remove punctuation - gets non-ascii + ascii punctuation\n text = re.sub(r'[^\\w\\s]', ' ', text.translate(str.maketrans('', '', string.punctuation)))\n\n return ' '.join(text.split())\n\n def read_databz2(self):\n \"\"\" Extracts the first file enclosed in a zip (bz2) file as a list of words and pre-processes it using the\n nltk python library.\n\n Returns:\n A list of words.\n\n \"\"\"\n\n # NOTE NEED TO CONVERT TO SENTENCE WISE EXTRACTION\n with bz2.BZ2File(self.filename) as file:\n data = []\n file_size = os.stat(self.filename).st_size\n chunk_size = 1024 * 1024 # reading 1 MB at a time as the dataset is moderately large\n\n print('Reading data from {filename}'.format(filename=self.filename))\n\n for i in range(ceil(file_size // chunk_size) + 1):\n bytes_to_read = min(chunk_size, file_size - (i * chunk_size))\n file_string = file.read(bytes_to_read).decode('utf-8')\n # lowercase and tokenize into list of words\n data.extend(file_string.lower().split())\n\n return data\n\n def __read_data(self):\n \"\"\"Extract the first file enclosed in a zip file as a list of words and pre-processes it using the nltk\n python library.\n\n Returns:\n A list of cleaned words.\n\n \"\"\"\n\n data = []\n\n with open(self.filename) as file:\n print('Reading data from {filename}'.format(filename=self.filename))\n\n for line in file:\n cleaned_line = self.clean_text(line)\n data.extend([word for word in cleaned_line.split() if word not in self.stopwords])\n\n return data\n\n def __read_data_in_sentences(self):\n \"\"\"\n Extract the first file enclosed in a zip file as a list of words and pre-processes it using the nltk python\n library.\n\n Returns:\n A nested list of cleaned words from the file.\n \"\"\"\n\n data = []\n count = 0\n\n with open(self.filename) as file:\n print('Reading data from {filename}'.format(filename=self.filename))\n\n sentences = re.split(\"(?<=[.!?])\\\\s+\", file.read().replace('\\n', ''))\n\n for sent in sentences:\n sent = self.clean_text(sent)\n\n # tokenizes a string to a list of words\n words = sent.split()\n keep_words = []\n\n for word in words:\n if word not in self.stopwords:\n keep_words.append(word)\n count += 1\n\n data.append(keep_words)\n\n print(\"Extracted {} non-stop words and {} sentences\".format(count, len(data)))\n\n return data\n\n def build_dataset(self):\n \"\"\"Builds a dataset by traversing over a input text and compiling a list of the most commonly occurring words.\n\n Returns:\n data: A list of the most commonly occurring word indices.\n count: A list of tuples, where the first item in each tuple is a word and the second is the word frequency.\n dictionary: A dictionary where the keys are words and the values are the word id.\n reversed dictionary: A dictionary that is the reverse of the dictionary object mentioned above.\n\n \"\"\"\n\n count = [['UNK', -1]]\n words = self.__read_data()\n vocabulary_size = min(50000, len(set(words)))\n\n # gets the vocabulary_size of most common words, all the other words will be replaced with UNK token\n count.extend(collections.Counter(words).most_common(vocabulary_size - 1))\n dictionary = dict()\n\n # create an ID for each word from current length of the dictionary\n for word, _ in count:\n dictionary[word] = len(dictionary)\n\n # traverse text and produce a list where each element corresponds to the ID of the word at that idx\n data, unk_count = list(), 0\n\n for word in words:\n if word in dictionary:\n index = dictionary[word]\n\n else:\n index = 0 # dictionary['UNK']\n unk_count = unk_count + 1\n\n data.append(index)\n\n # update the count variable with the number of UNK occurrences\n count[0][1] = unk_count\n\n # make sure the dictionary is of size of the vocabulary\n assert len(dictionary) == vocabulary_size\n\n return data, count, dictionary, dict(zip(dictionary.values(), dictionary.keys()))\n\n def build_dataset_in_sentences(self):\n \"\"\" Creates a dataset for word2vec that consists of all of the sentences from the original text with the\n words encoded as integers. The list is created by first getting only the vocabulary_size of the most common\n words. All the other words will be replaced with an UNK token.\n\n Returns:\n data: A list of the most commonly occurring word indices.\n count: A list of tuples, where the first item in each tuple is a word and the second is the word frequency.\n dictionary: A dictionary where the keys are words and the values are the word id.\n reversed dictionary: A dictionary that is the reverse of the dictionary object mentioned above.\n\n \"\"\"\n sentences = self.__read_data_in_sentences()\n count = [['UNK', -1]]\n flat_list_of_words = [item for sublist in sentences for item in sublist]\n vocabulary_size = min(50000, len(set(flat_list_of_words)))\n\n # a counter container stores elements as dictionary keys and their counts are stored as dictionary values.\n # Extend appends a list. We append 49,999 to get 50,000\n count.extend(collections.Counter(flat_list_of_words).most_common(vocabulary_size - 1))\n dictionary = dict()\n\n # create an ID for each word by giving the current length of the dictionary\n for word, _ in count:\n dictionary[word] = len(dictionary)\n\n data, unk_count = list(), 0\n\n # traverse text to produce a list of lists, each list is a sentence and each element is the word id at that idx\n for sen in sentences:\n integer_sentence = [] # encode the send\n\n for word in sen:\n if word in dictionary:\n index = dictionary[word]\n\n else:\n index = 0 # dictionary['UNK']\n unk_count = unk_count + 1\n\n integer_sentence.append(index)\n data.append(integer_sentence)\n\n # update the count variable with the number of UNK occurrences\n count[0][1] = unk_count\n\n # Make sure the dictionary is of size of the vocabulary\n assert len(dictionary) == vocabulary_size\n\n # Hint to reduce memory\n del sentences\n\n # log.info('Most common words (+UNK) {}', str(count[:5)])\n # log.info('Sample data: {}', str(data[:10]))\n return data, count, dictionary, dict(zip(dictionary.values(), dictionary.keys()))\n\n\n def build_dataset_with_keras(self, max_vocab_size=50000):\n text = self.get_raw_text()\n words = text_to_word_sequence(text, lower=True, filters='\\'!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\t\\n')\n words = self.remove_stopwords(words)\n max_vocab_size = min(max_vocab_size, len(set(words)))\n # initialize Tokenizer with 'UNK' as the out-of-vocabulary token.\n # Since Keras reserves the 0th index for padding sequences, the index for 'UNK'\n # will be 1st index\n # max_vocab_size + 1 because Keras reserves the 0th index\n tokenizer = Tokenizer(num_words=max_vocab_size + 1, oov_token='UNK', lower=True, filters='\\'!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\t\\n')\n sentences = self.parse_file_into_sentences()\n tokenizer.fit_on_texts(sentences)\n sequences = tokenizer.texts_to_sequences(sentences)\n # for downstream compatibility\n flatted_sequences = list(flatten(sequences))\n count = tokenizer.word_counts\n # for downstream compatibility\n filtered_count = {}\n dictionary = {}\n for k, v in tokenizer.word_index.items():\n if v <= max_vocab_size:\n if k == 'UNK':\n filtered_count['UNK'] = 0\n dictionary['UNK'] = 1\n continue\n filtered_count[k] = count[k]\n dictionary[k] = v\n else:\n filtered_count['UNK'] += 1\n reverse_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n # for downstream compatibility\n count_as_tuples = list(zip(list(filtered_count.keys()), list(filtered_count.values())))\n assert max_vocab_size == len(count_as_tuples)\n return flatted_sequences, count_as_tuples, dictionary, reverse_dictionary\n\n def get_raw_text(self):\n text = open(self.filename).read()\n return text\n\n def parse_file_into_sentences(self):\n sentences = []\n\n with open(self.filename) as file:\n print('Reading data from {filename}'.format(filename=self.filename))\n for line in file:\n # calling clean_text since Keras does not undo contractions\n cleaned_line = self.clean_text(line)\n # removing stopwords since Keras does not support removing a defined set of words\n cleaned_line = self.remove_stopwords(cleaned_line.split(' '))\n sentences.append(' '.join(cleaned_line))\n return sentences\n\n def remove_stopwords(self, words):\n filtered_words = []\n filtered_words.extend([word for word in words if word not in self.stopwords])\n return filtered_words\n","sub_path":"xn2v/text_encoder.py","file_name":"text_encoder.py","file_ext":"py","file_size_in_byte":12529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"64733270","text":"\"\"\"\nUniversity of Liege\nELEN0062 - Introduction to machine learning\nProject 1 - Classification algorithms\n\"\"\"\n#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport math\nfrom sklearn.model_selection import train_test_split\nfrom plot import plot_boundary\nfrom sklearn.metrics import accuracy_score\n\nfrom sklearn.base import BaseEstimator, ClassifierMixin\n\nN_POINTS = 1500\nSEED = 11\n\nclass LinearDiscriminantAnalysis(BaseEstimator, ClassifierMixin):\n\n\n def fit(self, X, y):\n \"\"\"Fit a linear discriminant analysis model using the training set\n (X, y).\n\n Parameters\n ----------\n X : array-like, shape = [n_samples, n_features]\n The training input samples.\n\n y : array-like, shape = [n_samples]\n The target values.\n\n Returns\n -------\n self : object\n Returns self.\n \"\"\"\n # Input validation\n X = np.asarray(X, dtype=np.float)\n if X.ndim != 2:\n raise ValueError(\"X must be 2 dimensional\")\n\n y = np.asarray(y)\n if y.shape[0] != X.shape[0]:\n raise ValueError(\"The number of samples differs between X and y\")\n\n # Applying list(set()) to a list returns a new list without duplicates in it\n self.classes = sorted(list(set(y)))\n nbClasses = len(self.classes)\n\n # samples will be a list of shape [n_classes, n_samples, n_features]\n samples = []\n for i in range(nbClasses):\n samples.append([])\n\n # samples[i][j][k] correspond to the kth feature of the jth sample corresponding to the\n # class classes[i].\n for i in range(len(y)):\n index = self.classes.index(y[i])\n samples[index].append(X[i])\n\n # Compute mean and covariance\n # means will be a list of shape [n_classes, n_features]\n # covariances will be a list of n_classes covariance matrices of shape\n # [n_features, n_features]\n\n self.means = []\n covariances = []\n for i in range(len(self.classes)):\n samples[i] = np.asarray(samples[i], dtype = np.float)\n self.means.append(np.mean(samples[i], axis = 0))\n covariances.append(np.cov(samples[i], rowvar = False))\n\n # Using homoscedasticity property\n covariances = np.asarray(covariances, dtype = np.float)\n self.covariance = np.mean(covariances, axis = 0)\n\n # priorProba wil be a list of shape [n_classes]\n self.priorProba = []\n\n totalSamples = len(y)\n for i in range(len(self.classes)):\n # len(samples[i]) = number of samples in class i\n self.priorProba.append(len(samples[i])/totalSamples)\n \n return self\n\n def predict(self, X):\n \"\"\"Predict class for X.\n\n Parameters\n ----------\n X : array-like of shape = [n_samples, n_features]\n The input samples.\n\n Returns\n -------\n y : array of shape = [n_samples]\n The predicted classes, or the predict values.\n \"\"\"\n\n # If not already fitted, return None\n if self.classes is None or self.means is None or self.covariance is None or \\\n self.priorProba is None:\n return None \n\n # Compute probability estimates\n proba = self.predict_proba(X)\n proba = np.asarray(proba, dtype = np.float)\n\n # The predicted class is the class that has the higher probability\n predicted = [self.classes[np.argmax(sampleProba)] for sampleProba in proba]\n return predicted\n\n def predict_proba(self, X):\n \"\"\"Return probability estimates for the test data X.\n\n Parameters\n ----------\n X : array-like of shape = [n_samples, n_features]\n The input samples.\n\n Returns\n -------\n p : array of shape = [n_samples, n_classes]\n The class probabilities of the input samples. Classes are ordered\n by lexicographic order.\n \"\"\"\n\n # If not already fitted, return None\n if self.classes is None or self.means is None or self.covariance is None or \\\n self.priorProba is None:\n return None \n\n p = []\n\n for sample in X:\n\n # densities will be a list of shape [n_classes] containing f_k(x) for each k for a\n # given x\n densities = []\n for i in range(len(self.classes)):\n densities.append(self.prob_x(sample, i))\n\n # denum is the denumerator in the expression of P(y=k|x)\n denum = sum(list(map(lambda x, y: x * y, densities, self.priorProba)))\n\n # probabilities will be a list of shape [n_classes] containing P(y=k|x) for each k\n # for a given x\n probabilities = []\n for i in range(len(self.classes)): \n probabilities.append(densities[i] * self.priorProba[i] / denum)\n\n p.append(probabilities)\n\n return np.array(p)\n\n def prob_x(self, X, classIndex):\n \"\"\"Compute the density function f_k(x) for given x and k\n\n Parameters\n ----------\n X : list of shape = [n_features]\n Correspond to x, the feature vector\n\n Returns\n -------\n fkx : double\n The value of the density function evaluated in x and k.\n \"\"\"\n\n # p is the number of features\n p = len(X)\n\n # diffMeanX = (x - \\mu_k) \n diffMeanX = list(map(lambda a, b: a - b, X , self.means[classIndex]))\n\n # expArg is the argument of the exponential in the density expression\n expArg = -0.5 * np.dot(np.dot(diffMeanX, np.linalg.inv(self.covariance)), diffMeanX)\n\n # coefficient is the factor that multiplies the exponential in the density expression\n coefficient = 1/((2*math.pi)**(p/2) * math.sqrt(np.linalg.det(self.covariance)))\n\n fkx = coefficient * math.exp(expArg)\n return fkx\n\n\n def __init__(self):\n self.classes = None\n self.means = None\n self.covariance = None\n self.priorProba = None\n\ndef plot_decision_boundary():\n \"\"\"Create files containing plots of decision boundary for both dataset.\n\n Parameters\n ----------\n None\n\n Returns\n -------\n None\n \"\"\"\n files = [\"lda_dataset1\", \"lda_dataset2\"]\n\n # Create datasets\n X = []\n y = []\n\n tmpX, tmpY = make_dataset1(N_POINTS, SEED)\n X.append(tmpX)\n y.append(tmpY)\n\n tmpX, tmpY = make_dataset2(N_POINTS, SEED)\n X.append(tmpX)\n y.append(tmpY)\n\n for i in range(len(files)):\n # Split into learn and training set\n trainSetX, testSetX, trainSetY, testSetY = train_test_split(X[i], y[i], test_size = 0.2,\n random_state = SEED)\n\n # Learn from the training set\n estimator = LinearDiscriminantAnalysis()\n estimator.fit(trainSetX, trainSetY)\n \n # Plot the decision boundary\n plot_boundary(files[i], estimator, testSetX, testSetY)\n\ndef compute_statistics():\n \"\"\"Compute statistics of LinearDiscriminantAnalysis estimator.\n\n Parameters\n ----------\n None\n\n Returns\n -------\n mean1 : double\n Mean accuracies of the linear discriminant analysis estimator tested on the test samples \n of the first dataset.\n mean2 : double\n Mean accuracies of the linear discriminant analysis estimator tested on the test samples \n of the second dataset.\n std1 : double\n Standard deviation of the accuracies of the linear discriminant analysis estimator tested\n on the test samples of the first dataset.\n std2 : double\n Standard deviation of the accuracies of the linear discriminant analysis estimator tested\n on the test samples of the second dataset.\n \"\"\"\n\n # Use a list of seeds in order to generate different datasets\n SEEDS = [11, 13, 17, 23, 27]\n\n # accuracies1 and accuracies2 will be lists of shape [n_generations]\n accuracies1 = []\n accuracies2 = []\n\n for i in range(len(SEEDS)):\n # Create and split datasets\n X1, y1 = make_dataset1(N_POINTS, SEEDS[i])\n X2, y2 = make_dataset2(N_POINTS, SEEDS[i])\n trainSetX1, testSetX1, trainSetY1, testSetY1 = train_test_split(X1, y1, test_size = 0.2,\n random_state = SEEDS[i])\n trainSetX2, testSetX2, trainSetY2, testSetY2 = train_test_split(X2, y2, test_size = 0.2,\n random_state = SEEDS[i])\n\n # Learn the models from the training samples\n lda1 = LinearDiscriminantAnalysis()\n lda2 = LinearDiscriminantAnalysis()\n lda1.fit(trainSetX1, trainSetY1)\n lda2.fit(trainSetX2, trainSetY2)\n\n # Compute accuracies\n accuracies1.append(accuracy_score(testSetY1, lda1.predict(testSetX1)))\n accuracies2.append(accuracy_score(testSetY2, lda2.predict(testSetX2)))\n\n accuracies1 = np.array(accuracies1)\n accuracies2 = np.array(accuracies2)\n\n # Compute the mean and standard deviation over the different generations of the datasets\n mean1 = np.mean(accuracies1)\n mean2 = np.mean(accuracies2)\n std1 = np.std(accuracies1)\n std2 = np.std(accuracies2)\n\n return mean1, std1, mean2, std2\n\nif __name__ == \"__main__\":\n from data import make_dataset1\n from data import make_dataset2\n from plot import plot_boundary\n\n\n X, y = make_dataset1(N_POINTS, SEED)\n trainSetX, testSetX, trainSetY, testSetY = train_test_split(X, y, test_size = 0.2,\n random_state = SEED)\n\n lda = LinearDiscriminantAnalysis()\n lda.fit(trainSetX, trainSetY)\n\n print(\"classe = {}\".format(lda.classes))\n print(\"means = {}\".format(lda.means))\n print(\"covariance = {}\".format(lda.covariance))\n print(\"priorProba = {}\".format(lda.priorProba))\n\n proba = lda.predict_proba(testSetX)\n print(\"proba = {}\".format(proba))\n predicted = lda.predict(testSetX)\n print(\"predicted = {}\".format(predicted))\n\n plot_decision_boundary()\n\n mean1, std1, mean2, std2 = compute_statistics()\n print(\"mean1 = {}\\n\".format(mean1))\n print(\"mean2 = {}\\n\".format(mean2))\n print(\"std1 = {}\\n\".format(std1))\n print(\"std2 = {}\\n\".format(std2))\n\n","sub_path":"p1/lda.py","file_name":"lda.py","file_ext":"py","file_size_in_byte":10397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"358279524","text":"# This file takes in the raw data and exaimines it + cleans it\r\nfrom matplotlib import pyplot as plt\r\nimport seaborn as sns\r\nimport re\r\nimport pandas as pd\r\nseed = 1\r\n\r\ntrain = pd.read_csv(\"./data/train_old.csv\")\r\ncols_target = ['obscene','insult','toxic','severe_toxic','identity_hate','threat']\r\n\r\n# Look at some examples of the data\r\nprint(train.sample(5))\r\n\r\n# look at the overall value properties\r\nprint(train.describe())\r\n\r\n# From before, some categories have very low mean, which implies most comments are good\r\n# Find percentage of good comments\r\nunlabelled_in_all = train[(train['toxic']!=1) & (train['severe_toxic']!=1) & (train['obscene']!=1) & (train['threat']!=1) & (train['insult']!=1) & (train['identity_hate']!=1)]\r\nprint('Percentage of good comments is ', len(unlabelled_in_all)/len(train)*100)\r\n\r\n# Check for any null comments\r\nno_comment = train[train['comment_text'].isnull()]\r\nprint('Number of null comments is ', len(no_comment))\r\n\r\n# let's see the total rows in train, test data and the numbers for the various categories\r\nprint('Total rows in test is {}'.format(len(train)))\r\nprint(train[cols_target].sum())\r\n\r\n# Next, let's examine the correlations among the target variables.\r\ndata = train[cols_target]\r\ncolormap = plt.cm.plasma\r\nplt.figure(figsize=(7,7))\r\nplt.title('Correlation of features & targets',y=1.05,size=14)\r\nsns.heatmap(data.astype(float).corr(),linewidths=0.1,vmax=1.0,square=True,cmap=colormap,\r\n linecolor='white',annot=True)\r\nplt.show()\r\n\r\ndef clean_text(text):\r\n text = text.lower()\r\n text = re.sub(r\"what's\", \"what is \", text)\r\n text = re.sub(r\"\\'s\", \" \", text)\r\n text = re.sub(r\"\\'ve\", \" have \", text)\r\n text = re.sub(r\"can't\", \"cannot \", text)\r\n text = re.sub(r\"n't\", \" not \", text)\r\n text = re.sub(r\"i'm\", \"i am \", text)\r\n text = re.sub(r\"\\'re\", \" are \", text)\r\n text = re.sub(r\"\\'d\", \" would \", text)\r\n text = re.sub(r\"\\'ll\", \" will \", text)\r\n text = re.sub(r\"\\'scuse\", \" excuse \", text)\r\n text = re.sub('\\W', ' ', text)\r\n text = re.sub('\\s+', ' ', text)\r\n text = text.strip(' ')\r\n return text\r\n\r\n# clean the comment_text in train\r\ntrain['comment_text'] = train['comment_text'].map(lambda com : clean_text(com))\r\ntrain.to_csv(\"./data/train.csv\", index=False)\r\n\r\n# Let's look at the character length for the rows in the training data and record these\r\n# At the end because do not want to add another column to output data\r\ntrain['char_length'] = train['comment_text'].apply(lambda x: len(str(x)))\r\nsns.set()\r\ntrain['char_length'].hist()\r\nplt.title('distribution of character length in all comments')\r\nplt.show()","sub_path":"dataProcessing/examine.py","file_name":"examine.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"523568535","text":"import numpy\nimport pandas\n\nfrom .config import rating_dataset\n\n\ndef load(filepath, column):\n \"\"\"\n Reads a binary file to load dataset.\n :param\n file path \n column Used to label the dataframe\n :return\n Pandas.Dataframe Contains the dataset.\n \"\"\"\n with open(filepath, 'r', encoding='ISO-8859-1') as f:\n text = str(f.read()).strip().split('\\n')\n return pandas.DataFrame.from_records(\n [sentence.split('::') for sentence in text], columns=column)\n\n\ndef assign_missing_values(input_matrix):\n \"\"\"\n Preprocesses the input matrix to replace the NA values logically so that SVD can be performed.\n Also introduces biases to input matrix\n :param input_matrix: User-Movie rating matrix where matrix[i][j] represents rating given by\n user i for movie j\n :return preprocessed matrix which can be used for calculating SVD\n \"\"\"\n matrix = numpy.asarray(input_matrix, dtype=numpy.float32)\n mean = matrix.mean()\n\n # Calculate biases for users and items\n row_count, col_count = [], []\n for x in range(len(input_matrix)):\n row_count.append(numpy.count_nonzero(matrix[x, :]))\n for x in range(len(matrix[0])):\n col_count.append(numpy.count_nonzero(matrix[:, x]))\n\n row_means, col_means = [], []\n for x in range(len(matrix)):\n row_means.append(\n (numpy.sum(matrix[x, :]) - (mean*row_count[x])) / (row_count[x] * row_count[x]))\n for x in range(len(matrix[0])):\n col_means.append(\n (numpy.sum(matrix[:, x]) - (mean*col_count[x])) / (col_count[x] * col_count[x]))\n\n # Replace NA values so that matrix can be used for calculating SVD\n for x in range(len(matrix)):\n for y in range(len(matrix[0])):\n if matrix[x][y] == 0:\n matrix[x][y] = mean + row_means[x] + col_means[y]\n\n if matrix[x][y] > 5:\n matrix[x][y] = 5\n\n if matrix[x][y] < 1:\n matrix[x][y] = 1\n\n return matrix\n\n\ndef preprocess():\n \"\"\"Wrapper function which loads dataset, preprocesses it and\n also assigns missing values to the sparse matrix\n\n :return\n utility_matrix numpy.ndarray containing the matrix\n representation of the dataset\n \"\"\"\n dataset = load(rating_dataset,\n column=['uid', 'mid', 'rating', 'time'])\n dataset.drop(labels=[\"time\"], axis=1, inplace=True)\n dataset = dataset.astype(int)\n\n num_users = list(dataset['uid'].unique())\n num_users.sort()\n\n num_movies = list(dataset['mid'].unique())\n num_movies.sort()\n\n utility_matrix = numpy.full((len(num_users), len(num_movies)), 0)\n\n for iter in dataset.index:\n user_index = num_users.index(dataset['uid'][iter])\n movie_index = num_movies.index(dataset['mid'][iter])\n utility_matrix[user_index][movie_index] = dataset['rating'][iter]\n\n return assign_missing_values(utility_matrix)\n\n\nif __name__ == '__main__':\n input_matrix = [[1, 1, 1, 0, 0],\n [3, 3, 3, 0, 0],\n [4, 4, 4, 0, 0],\n [5, 5, 5, 0, 0],\n [0, 2, 0, 4, 4],\n [0, 0, 0, 5, 5],\n [0, 1, 0, 2, 2]]\n\n print(assign_missing_values(input_matrix))\n","sub_path":"svd/preprocessor.py","file_name":"preprocessor.py","file_ext":"py","file_size_in_byte":3295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"192775353","text":"from selenium import webdriver\nimport time\n\ntry:\n browser = webdriver.Chrome(executable_path='D:/driver/chromedriver.exe')\n time.sleep(1)\n\n browser.get(' https://shimo.im')\n btml = browser.find_element_by_xpath('//*[@id=\"homepage-header\"]/nav/div[3]/a[2]')\n btml.click()\n\n name = browser.find_element_by_name('mobileOrEmail')\n print(name)\n name.send_keys('XXXXXXXXX')\n time.sleep(1)\n browser.find_element_by_name('password').send_keys('XXXXXXXX')\n time.sleep(1)\n sinup = browser.find_element_by_xpath('//*[@id=\"root\"]/div/div[2]/div/div/div/div[2]/div/div/div[1]/button')\n sinup.click()\n\n cookies = browser.get_cookies()\n print(cookies)\n time.sleep(3)\n\nexcept Exception as e:\n print(e)\nfinally:\n browser.close()","sub_path":"week02/shimo/shimo.py","file_name":"shimo.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"421238926","text":"# coding: utf-8\nimport pprint\nimport six\nfrom enum import Enum\n\n\n\nclass PaymentAppCompletionConfiguration:\n\n swagger_types = {\n \n 'completion_endpoint': 'str',\n 'completion_timeout_in_minutes': 'int',\n 'maximal_completion_delay_in_days': 'int',\n 'multiple_completions_supported': 'bool',\n 'void_endpoint': 'str',\n }\n\n attribute_map = {\n 'completion_endpoint': 'completionEndpoint','completion_timeout_in_minutes': 'completionTimeoutInMinutes','maximal_completion_delay_in_days': 'maximalCompletionDelayInDays','multiple_completions_supported': 'multipleCompletionsSupported','void_endpoint': 'voidEndpoint',\n }\n\n \n _completion_endpoint = None\n _completion_timeout_in_minutes = None\n _maximal_completion_delay_in_days = None\n _multiple_completions_supported = None\n _void_endpoint = None\n\n def __init__(self, **kwargs):\n self.discriminator = None\n \n self.completion_endpoint = kwargs.get('completion_endpoint', None)\n self.completion_timeout_in_minutes = kwargs.get('completion_timeout_in_minutes', None)\n self.maximal_completion_delay_in_days = kwargs.get('maximal_completion_delay_in_days', None)\n self.multiple_completions_supported = kwargs.get('multiple_completions_supported', None)\n self.void_endpoint = kwargs.get('void_endpoint', None)\n \n\n \n @property\n def completion_endpoint(self):\n \"\"\"Gets the completion_endpoint of this PaymentAppCompletionConfiguration.\n\n The completion endpoint is invoked to request the payment service provider to execute a completion.\n\n :return: The completion_endpoint of this PaymentAppCompletionConfiguration.\n :rtype: str\n \"\"\"\n return self._completion_endpoint\n\n @completion_endpoint.setter\n def completion_endpoint(self, completion_endpoint):\n \"\"\"Sets the completion_endpoint of this PaymentAppCompletionConfiguration.\n\n The completion endpoint is invoked to request the payment service provider to execute a completion.\n\n :param completion_endpoint: The completion_endpoint of this PaymentAppCompletionConfiguration.\n :type: str\n \"\"\"\n\n self._completion_endpoint = completion_endpoint\n \n @property\n def completion_timeout_in_minutes(self):\n \"\"\"Gets the completion_timeout_in_minutes of this PaymentAppCompletionConfiguration.\n\n When the completion or the void is triggered we expect a feedback about the state of it. This timeout defines after how long we consider the void resp. completion as failed without receiving a final state update.\n\n :return: The completion_timeout_in_minutes of this PaymentAppCompletionConfiguration.\n :rtype: int\n \"\"\"\n return self._completion_timeout_in_minutes\n\n @completion_timeout_in_minutes.setter\n def completion_timeout_in_minutes(self, completion_timeout_in_minutes):\n \"\"\"Sets the completion_timeout_in_minutes of this PaymentAppCompletionConfiguration.\n\n When the completion or the void is triggered we expect a feedback about the state of it. This timeout defines after how long we consider the void resp. completion as failed without receiving a final state update.\n\n :param completion_timeout_in_minutes: The completion_timeout_in_minutes of this PaymentAppCompletionConfiguration.\n :type: int\n \"\"\"\n\n self._completion_timeout_in_minutes = completion_timeout_in_minutes\n \n @property\n def maximal_completion_delay_in_days(self):\n \"\"\"Gets the maximal_completion_delay_in_days of this PaymentAppCompletionConfiguration.\n\n The completion resp. the void can be triggered a while after the authorization of the transaction has been executed. This delay defines how many days after the authorization the void resp. completion must be triggered at the latest.\n\n :return: The maximal_completion_delay_in_days of this PaymentAppCompletionConfiguration.\n :rtype: int\n \"\"\"\n return self._maximal_completion_delay_in_days\n\n @maximal_completion_delay_in_days.setter\n def maximal_completion_delay_in_days(self, maximal_completion_delay_in_days):\n \"\"\"Sets the maximal_completion_delay_in_days of this PaymentAppCompletionConfiguration.\n\n The completion resp. the void can be triggered a while after the authorization of the transaction has been executed. This delay defines how many days after the authorization the void resp. completion must be triggered at the latest.\n\n :param maximal_completion_delay_in_days: The maximal_completion_delay_in_days of this PaymentAppCompletionConfiguration.\n :type: int\n \"\"\"\n\n self._maximal_completion_delay_in_days = maximal_completion_delay_in_days\n \n @property\n def multiple_completions_supported(self):\n \"\"\"Gets the multiple_completions_supported of this PaymentAppCompletionConfiguration.\n\n This flag indicates whether the connector supports multiple completions for a single transaction or not.\n\n :return: The multiple_completions_supported of this PaymentAppCompletionConfiguration.\n :rtype: bool\n \"\"\"\n return self._multiple_completions_supported\n\n @multiple_completions_supported.setter\n def multiple_completions_supported(self, multiple_completions_supported):\n \"\"\"Sets the multiple_completions_supported of this PaymentAppCompletionConfiguration.\n\n This flag indicates whether the connector supports multiple completions for a single transaction or not.\n\n :param multiple_completions_supported: The multiple_completions_supported of this PaymentAppCompletionConfiguration.\n :type: bool\n \"\"\"\n\n self._multiple_completions_supported = multiple_completions_supported\n \n @property\n def void_endpoint(self):\n \"\"\"Gets the void_endpoint of this PaymentAppCompletionConfiguration.\n\n The void endpoint is invoked to request the payment service provider to execute a void.\n\n :return: The void_endpoint of this PaymentAppCompletionConfiguration.\n :rtype: str\n \"\"\"\n return self._void_endpoint\n\n @void_endpoint.setter\n def void_endpoint(self, void_endpoint):\n \"\"\"Sets the void_endpoint of this PaymentAppCompletionConfiguration.\n\n The void endpoint is invoked to request the payment service provider to execute a void.\n\n :param void_endpoint: The void_endpoint of this PaymentAppCompletionConfiguration.\n :type: str\n \"\"\"\n\n self._void_endpoint = void_endpoint\n \n\n def to_dict(self):\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n elif isinstance(value, Enum):\n result[attr] = value.value\n else:\n result[attr] = value\n if issubclass(PaymentAppCompletionConfiguration, dict):\n for key, value in self.items():\n result[key] = value\n\n return result\n\n def to_str(self):\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n return self.to_str()\n\n def __eq__(self, other):\n if not isinstance(other, PaymentAppCompletionConfiguration):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n return not self == other\n","sub_path":"wallee/models/payment_app_completion_configuration.py","file_name":"payment_app_completion_configuration.py","file_ext":"py","file_size_in_byte":7987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"364940819","text":"import json\n\n\nclass Media:\n def __init__(self, data, igql, fetch_data=False):\n self.igql = igql\n self.data = data\n self.last_response = data\n\n self.shortcode = data['shortcode']\n self.display_url = data['display_url']\n self.like_count = data['edge_media_preview_like']['count']\n if fetch_data:\n self._fetch_data()\n else:\n try:\n self.comments = data['edge_media_to_comment']['edges']\n\n self._comments_has_next_page = self.data['edge_media_to_comment'][\n 'page_info']['has_next_page']\n self._comments_end_cursor = self.data['edge_media_to_comment'][\n 'page_info']['end_cursor']\n except:\n self.comments = None\n\n self._comments_has_next_page = False\n self._comments_end_cursor = None\n self._liked_by_has_next_page = True\n self._liked_by_end_cursor = None\n\n def _fetch_data(self):\n media = self.igql.get_media(self.shortcode)\n self.__dict__.update(media.__dict__)\n\n def iterate_more_comments(self, reset=False):\n if not self.comments:\n yield self._fetch_data()\n if reset:\n self._comments_has_next_page = self.data[\n 'edge_media_to_comment']['page_info']['has_next_page']\n self._comments_end_cursor = self.data['edge_media_to_comment'][\n 'page_info']['end_cursor']\n while self._comments_has_next_page:\n params = {\n 'query_hash':\n self.igql._QUERY_HASHES['load_more_comments'],\n 'variables': json.dumps({\n 'shortcode': self.shortcode,\n 'first': 40,\n 'after': self._comments_end_cursor\n },\n separators=(',', ':'))\n }\n\n self.last_response = self.igql.gql_api.query.GET(\n params=params).json()['data']['shortcode_media']\n\n self._comments_has_next_page = self.last_response[\n 'edge_media_to_comment']['page_info']['has_next_page']\n self._comments_end_cursor = self.last_response[\n 'edge_media_to_comment']['page_info']['end_cursor']\n\n yield self.last_response['edge_media_to_comment']['edges']\n\n def iterate_liked_by(self, reset=False):\n if reset:\n self._liked_by_has_next_page = True\n self._liked_by_end_cursor = None\n while self._liked_by_has_next_page:\n params = {\n 'query_hash':\n self.igql._QUERY_HASHES['load_liked_by'],\n 'variables': json.dumps({\n 'shortcode': self.shortcode,\n 'include_reel': True,\n 'first': 24,\n },\n separators=(',', ':')),\n }\n if self._liked_by_end_cursor:\n params['after'] = self._liked_by_end_cursor\n\n self.last_response = self.igql.gql_api.query.GET(\n params=params).json()['data']['shortcode_media']\n\n self._liked_by_has_next_page = self.last_response['edge_liked_by'][\n 'page_info']['has_next_page']\n self._liked_by_end_cursor = self.last_response['edge_liked_by'][\n 'page_info']['end_cursor']\n\n yield self.last_response['edge_liked_by']['edges']\n","sub_path":"igql/media.py","file_name":"media.py","file_ext":"py","file_size_in_byte":3456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"158364237","text":"import sys\n# Copying code segment from Lab 5\nfrom sklearn.datasets import make_blobs\nfrom matplotlib import pyplot\nimport numpy as np\nimport random\nfrom matplotlib import pyplot as plt\nfrom scipy.cluster.hierarchy import dendrogram, linkage\n\n\ndef main():\n method = sys.argv[1]\n k_num_center = sys.argv[2]\n # input = sys.argv[3]\n outlier = sys.argv[4]\n test_one = Clustering(input, outlier, k_num_center, method)\n test_one.run()\n #python3 q2 Mean 2 output.png False\n\nclass Clustering():\n def __init__(self, k_num_center = 2, outlier = True, method = 'Mean'):\n self.k_num_center = k_num_center\n self.method = method\n if outlier:\n self.data = np.array([[1,2],[3,2],[5,1],[3,5],[8,7],[12,8],[10,9],[0,0],[40,40]])\n target = np.array([1,2,3,4,5,6,7,8,9])\n else:\n self.data = np.array([[1,2],[3,2],[5,1],[3,5],[8,7],[12,8],[10,9],[0,0]])\n target = np.array([1,2,3,4,5,6,7,8])\n pyplot.scatter(self.data[:,0],self.data[:,1], c = target)\n pyplot.savefig(sys.argv[1])\n\n def ou_distance(self,x,y):\n return np.sqrt(sum(np.square(x-y)))\n\n def run_k_means(self, func_of_dis):\n indexs = list(range(len(self.data)))\n random.shuffle(indexs)\n init_centroids_index = indexs[:self.k_num_center]\n centroids = self.data[init_centroids_index,:]\n levels = list(range(self.k_num_center))\n print(\"start iteration\")\n sample_target = []\n for i in range(10):\n new_centroids = [[] for i in range(self.k_num_center)]\n new_centroids_num = [0 for i in range(self.k_num_center)]\n sample_target = []\n\n for sample in self.data:\n distances = [self.ou_distance(sample, centroid) for centroid in centroids]\n cur_level = np.argmin(distances)\n sample_target.append(cur_level)\n\n\n new_centroids_num[cur_level]+=1\n if len(new_centroids[cur_level]) < 1:\n new_centroids[cur_level] = sample\n else:\n new_centroids[cur_level] = new_centroids[cur_level]+sample\n\n centroids = list()\n for centroid, num in zip(new_centroids, new_centroids_num):\n centroids.append([item/num for item in centroid])\n centroids = np.array(centroids)\n\n print('end')\n return sample_target\n\n def run_k_center(self, func_of_dis):\n print('randomly create', self.k_num_center, 'centers')\n indexs = list(range(len(self.data)))\n random.shuffle(indexs)\n init_centroids_index = indexs[:self.k_num_center]\n centroids = self.data[init_centroids_index,:]\n levels = list(range(self.k_num_center))\n print(\"start iteration\")\n sample_target = []\n if_stop = False\n while(not if_stop):\n if_stop = True\n classify_points = [[centroid] for centroid in centroids]\n sample_target = []\n\n for sample in self.data:\n distances = [func_of_dis(sample, centroid) for centroid in centroids]\n cur_level = np.argmin(distances)\n sample_target.append(cur_level)\n classify_points[cur_level].append(sample)\n\n for i in range(self.k_num_center):\n distances = [func_of_dis(point_1, centroids[i]) for point_1 in classify_points[i]]\n now_distances = sum(distances)\n for point in classify_points[i]:\n distances = [func_of_dis(point_1, point) for point_1 in classify_points[i]]\n new_distance = sum(distances)\n if new_distance < now_distances:\n now_distances = new_distance\n centroids[i] = point\n if_stop = False\n\n print('end')\n return sample_target\n\n def run(self):\n if self.method == 'Mean':\n predict = self.run_k_means(self.ou_distance)\n else:\n predict = self.run_k_center(self.ou_distance)\n pyplot.scatter(self.data[:,0], self.data[:,1], c=predict)\n pyplot.savefig(sys.argv[3])\n","sub_path":"assign2/code_files/q2.py","file_name":"q2.py","file_ext":"py","file_size_in_byte":4209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"15190183","text":"#!/usr/bin/python3\n\n'''Clean standard NFO file'''\n\nimport os\nimport re\nimport sys\n\n\ndef remove_leading_spaces(string_list):\n '''Takes a list of strings and \n returns list with any leading spaces removed.'''\n out = list()\n pattern = re.compile(\"^[ \\t]+(.+$)\")\n for line in string_list:\n match = re.match(pattern, line)\n if match:\n out.append(match.group(1) + '\\n')\n else:\n out.append(line)\n\n return out\n\n\ndef find_nfo_files(path = \"./\"):\n '''Returns full-path list of nfo files in path.\n Raises assertion error if no\n nfo files are found.'''\n\n files = os.listdir(path)\n nfo_list = [os.path.join(path, file) for file in files if file.endswith(\".nfo\")]\n\n try:\n err_msg = \"Could not find NFO files to process.\"\n assert len(nfo_list) > 0, err_msg\n except AssertionError:\n print(err_msg)\n \n return nfo_list\n\ndef clean_nfo_file(file):\n '''Takes single nfo file and\n replaces with cleaned version.\n Returns 0 if completed successfully.'''\n\n status = 1\n\n with open(file, 'r') as fhandle:\n original = fhandle.readlines()\n\n# empty_lines = 5\n# new = [filename[:-4] + '\\n'] # Add filename without extension\n# for i in range(empty_lines):\n# new.append('\\n')\n\n # Want to keep from first line of original that\n # has text but contains no spaces between characters.\n pattern = re.compile(\"^( |\\t)*[^ \\t\\n]+( |\\t)*$\")\n for line_num in range(len(original)):\n if re.match(pattern, original[line_num]):\n start_point = line_num\n break\n\n new = original[start_point:]\n\n new = remove_leading_spaces(new)\n \n # Remove newline from last line if it exists.\n last_line = new[-1]\n if last_line.endswith('\\n'):\n last_line = last_line[:-1]\n new[-1] = last_line\n\n with open(file, 'w') as fhandle:\n fhandle.writelines(new)\n status = 0\n\n return status\n\n\nif __name__ == \"__main__\":\n\n # If file passed as argument, only process that\n try:\n requested_file = sys.argv[1]\n nfo_files = [requested_file]\n except IndexError:\n nfo_files = find_nfo_files(\"./\")\n\n if nfo_files: # is not empty\n for file in nfo_files:\n try:\n clean_nfo_file(file)\n print(\"Processed {}\\n\".format(file))\n except:\n print(\"FAILED to process {}\\n\".format(file))\n\n\n print(\"Finished.\\n\")\n","sub_path":"cleanfo.py","file_name":"cleanfo.py","file_ext":"py","file_size_in_byte":2485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"339997458","text":"def whiileloop(n):\n a = 0\n while (a < n * n * n):\n a = a + n * n\n print(a) \nwhiileloop(10)\n\ndef sum(n):\n sum = 0\n for i in range(n): #O(n)\n j = 1\n while j < n: #O(1)\n j *= 2 #O(1)\n sum += 1 #O(1)\n print(sum)\nsum(6)\n","sub_path":"rock_paper_scissors/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"101502028","text":"#!/usr/bin/env python\n\nfrom libs.option import opt\nfrom libs.multi import procs\nfrom libs.db.mydb import Mydb\nfrom libs.myutils.parser import Parser\nfrom libs.myutils.writer import Writer\nfrom libs.myutils import utils\nfrom random import randint\nimport os\nimport re\nimport time\n\ndef main():\n options = opt.getArgs()\n opt.verify(options,[])\n pkt = procs.buildPKT(break2db, breakdir2Data(options), options)\n procs.joinme(pkt)\n exit(1)\n\ndef breakdir2Data(opts):\n breaks = os.listdir(opts['dir'])\n return [f for f in breaks if not f.endswith('html')]\n\ndef break2db(pid, data, opts):\n sql = 'insert into '+opts['dataset'] + '_concepts_sentence (docnum,partnum,indseq,sentnum,sentence) values (%s,%s,%s,%s,%s)'\n mydb = Mydb(opts)\n for f in data:\n \n m = re.match('(\\d+)_(\\d+)_(\\d+)\\.(\\w+)',f)\n # print m.groups()\n docnum = m.group(1)\n partnum = m.group(2)\n indseq = m.group(3)\n fo = open(opts['dir']+'/'+f, 'r')\n sentnum = 1\n for line in fo:\n sentence = line\n #sentence = mydb.escape(line)\n mydb.insert(sql, (docnum,partnum,indseq,sentnum,sentence))\n sentnum += 1\n mydb.close()\n \n exit(1)\n\n#./test.py --dbhost \nif __name__ == '__main__':\n main()\n","sub_path":"break2db_sd_cc.py","file_name":"break2db_sd_cc.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"616055152","text":"#!/usr/bin/env python\n\nimport json\nimport os\nimport os.path as osp\n\nimport skimage.io\n\n\nhere = osp.dirname(osp.abspath(__file__))\n\n\ndef main():\n item_data_dir = osp.join(here, 'item_data')\n\n for item_name_upper in os.listdir(item_data_dir):\n item_dir = osp.join(item_data_dir, item_name_upper)\n if not osp.isdir(item_dir):\n continue\n\n item_name_lower = item_name_upper.lower()\n\n frame_id = 0\n for fname in sorted(os.listdir(item_dir)):\n if fname.startswith(item_name_upper):\n continue\n fname = osp.join(item_dir, fname)\n ext = osp.splitext(fname)[1]\n if not (osp.isfile(fname) and ext in ['.jpg', '.png']):\n continue\n img = skimage.io.imread(fname)\n frame_id += 1\n dst_fname = osp.join(\n item_dir, '{:s}_{:03d}.png'.format(item_name_upper, frame_id))\n skimage.io.imsave(dst_fname, img)\n print('{:s}: {:s} -> {:s}'\n .format(item_name_lower, fname, dst_fname))\n os.remove(fname)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"jsk_arc2017_common/experiments/create_item_data/02_organize_image_files.py","file_name":"02_organize_image_files.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"73498296","text":"def function1(x):\n if x >= 20 or x < 0:\n return 0\n elif 0 <= x < 5:\n return x\n elif 5 <= x < 10:\n return 3 * x - 5\n elif 10 <= x < 20:\n return 0.5 * x - 2\n\n\nprint(function1(eval(input(\"请输入一个数字\"))))\n","sub_path":"homework/work2/fenDuanFunc.py","file_name":"fenDuanFunc.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"286976275","text":"import tempfile\nimport os\nimport logging\nimport unittest\n\nfrom common import broken\n\nimport angr\n\nl = logging.getLogger(\"angr_tests.managers\")\n\nlocation = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"..\", \"..\", \"binaries\", \"tests\")\n\n\n# pylint: disable=missing-class-docstring\n# pylint: disable=no-self-use\nclass TestCacher(unittest.TestCase):\n @broken\n def test_cacher(self):\n p = angr.Project(os.path.join(location, \"x86_64\", \"fauxware\"), load_options={\"auto_load_libs\": False})\n\n tmp_dir = tempfile.mkdtemp(prefix=\"test_cacher_container\")\n container = os.path.join(tmp_dir, \"%s.cache\" % os.path.basename(p.filename))\n\n pg = p.factory.simulation_manager()\n pg.use_technique(angr.exploration_techniques.Cacher(when=0x4006EE, container=container))\n pg.run()\n\n pg2 = p.factory.simulation_manager()\n pg2.use_technique(angr.exploration_techniques.Cacher(container=container))\n assert pg2.active[0].addr == 0x4006ED\n\n pg2.run()\n\n assert len(pg2.deadended) == len(pg.deadended)\n assert pg2.deadended[0].addr in [s.addr for s in pg.deadended]\n assert pg2.deadended[1].addr in [s.addr for s in pg.deadended]\n assert pg2.deadended[2].addr in [s.addr for s in pg.deadended]\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_cacher.py","file_name":"test_cacher.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"100607221","text":"from django.core.mail import send_mail\n\n\ndef send_activation_mail(email, activation_code):\n print(activation_code)\n subject = 'Account activation'\n message = f'Чтобы активировать ваш аккаунт перейдите по ссылке: http://127.0.0.1:8000/accounts/activate/{activation_code}'\n from_ = 'test@test.com'\n emails = [email, ]\n\n send_mail(subject, message, from_, emails, fail_silently=True)","sub_path":"account/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"501596842","text":"from programs import Program, Mapper\r\n\r\nclass ConversionTools(Program.Program):\r\n \"\"\"The class ConvertionTools regulates the support between the mappers and the programs for SV calling.\r\n \r\n \"\"\"\r\n \r\n def sortBam(self, bamFile):\r\n \"\"\"The method sortBam sorts a bam file of a given sample.\r\n The bam file can only be sorted when this is a bam file. If it is not a bam file, the file first will be converted to a bam file.\r\n \r\n :param sample: The sample which contains the bam file to be sorted\r\n :type sample: an instance of a Sample object\r\n \r\n \"\"\"\r\n \r\n if bamFile == None or bamFile.sam == True:\r\n self.convertToBam(bamFile) \r\n \r\n if bamFile.sorted == True:\r\n return\r\n\r\n outputFile = bamFile.getNewFileName()\r\n cmd = bamFile.pool.config.getProgramPath(\"samtools\") + \" sort -o \" + bamFile.getFile() + \" \" + outputFile + \" > \" + outputFile\r\n self.execute(cmd, \"samtools sort\", bamFile)\r\n bamFile.sorted = True\r\n bamFile.setFile(outputFile)\r\n \r\n def convertToBam(self, bamFile):\r\n \"\"\"The method convertToBam converts a sam file to a bam file of a given sample, if the file is not a sam file, the file first will be mapped\r\n by calling the :meth:`Mapper.Mapper.map` function.\r\n \r\n :param sample: The sample which contains the sam file to be converted to a bam file\r\n :type sample: an instance of a Sample object\r\n \r\n \"\"\"\r\n \r\n if bamFile == None:\r\n Mapper.Mapper().map(bamFile.sample)\r\n \r\n if bamFile.sam == False:\r\n return\r\n\r\n outputFile = bamFile.getNewFileName()\r\n cmd = bamFile.pool.config.getProgramPath(\"samtools\") + \" view \"+ self.getProgramArguments(\"samtools view\", bamFile.pool.config) + \" \" + bamFile.getFile() + \" > \" + outputFile\r\n self.execute(cmd, \"samtools view\", bamFile)\r\n bamFile.sam = False\r\n bamFile.setFile(outputFile)\r\n \r\n def createBamIndex(self, bamFile):\r\n \"\"\"creates a bam index file for the bam file of a given sample.\r\n \r\n :param sample: The sample which contains the bam file to create an index for\r\n :type sample: an instance of a Sample object\r\n :raises: A typeError when the sample contains no bam file\r\n \r\n \"\"\"\r\n \r\n if bamFile == None:\r\n self.convertToBam(bamFile)\r\n\r\n cmd = bamFile.pool.config.getProgramPath(\"samtools\") + \" index \" + bamFile.getFile()\r\n self.execute(cmd, \"samtools index\", bamFile)\r\n bamFile.index = True\r\n \r\n def addHeaderLine(self, bamFile):\r\n \"\"\"Adds a header line to the bam file of a given sample, if the input is not a sorted bam file, first the method :meth:`sortBam` will be executed.\r\n \r\n :param sample: The sample which contains the bam file to add the headerline to\r\n :type sample: an instance of a Sample object\r\n \r\n \"\"\"\r\n \r\n if bamFile == None or bamFile.sam == True:\r\n self.convertToBam(bamFile)\r\n \r\n if bamFile.headerLine == True:\r\n return\r\n \r\n outputFile = bamFile.getNewFileName()\r\n cmd = \"java -jar \" + bamFile.pool.config.getProgramPath(\"picardTools\") + \"AddOrReplaceReadGroups.jar I=\" + bamFile.getFile() + \" O=\" + outputFile + \" LB=\" + bamFile.sample.libName + \" PL=illumina PU=lane SM=samplename\"\r\n self.execute(cmd, \"picardtools AddOrReplaceReadGroups\", bamFile)\r\n bamFile.headerLine = True\r\n bamFile.setFile(outputFile)\r\n \r\n def removeDuplicates(self, bamFile):\r\n \"\"\"The method removeDuplicates removes all possible PCR duplicates of the bam file of a given sample. If the input file is not a sorted bam file, \r\n first the method :meth:`sortBam` will be executed.\r\n \r\n :param sample: The sample which contains the bam file to remove the duplicates from\r\n :type sample: an instance of a Sample object\r\n \r\n \"\"\"\r\n \r\n if bamFile == None or bamFile.sam == True or bamFile.sorted == False:\r\n self.sortBam(bamFile)\r\n \r\n if bamFile.duplicates == False:\r\n return\r\n \r\n outputFile = bamFile.getNewFileName()\r\n cmd = bamFile.pool.config.getProgramPath(\"samtools\") + \" rmdup \" + bamFile.getFile() + \" \" + outputFile\r\n self.execute(cmd, \"samtools rmdup\", bamFile)\r\n bamFile.duplicates = False\r\n bamFile.setFile(outputFile)\r\n \r\n def addMdTag(self, bamFile):\r\n \"\"\"The method addMdTag adds a md tag to the bam file of a given sample. If the file is not a bam file without duplicates, first the bam file will be converted to bam\r\n \r\n :param sample: The sample which contains the bam file to add the md tags to\r\n :type sample: an instance of a Sample object\r\n \r\n \"\"\"\r\n \r\n if bamFile == None or bamFile.sam == True:\r\n self.convertToBam(bamFile)\r\n \r\n if bamFile.mdTag == True:\r\n return\r\n \r\n outputFile = bamFile.getNewFileName()\r\n cmd = bamFile.pool.config.getProgramPath(\"samtools\") + \" calmd \" + self.getProgramArguments(\"samtools calmd\",bamFile.pool.config) + \" \" + bamFile.getFile() + \" \" + bamFile.pool.refGenome + \" > \" + outputFile\r\n self.execute(cmd, \"samtools calmd\", bamFile)\r\n bamFile.mdTag = True\r\n bamFile.setFile(outputFile)\r\n \r\n","sub_path":"pythonCodeBase/src/programs/ConversionTools.py","file_name":"ConversionTools.py","file_ext":"py","file_size_in_byte":5550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"641619273","text":"nums = [1,0,40,8,0,9,0,22]\nj=0\nfor num in nums:\n if num != 0:\n nums[j] = num\n j+=1\n\nfor i in range(j,len(nums)):\n nums[j] = 0\n j+=1\nprint(nums)\n\n","sub_path":"move_zeros.py","file_name":"move_zeros.py","file_ext":"py","file_size_in_byte":168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"444029007","text":"import math\n\ntry:\n from itertools import izip\nexcept ImportError:\n izip = zip\n\nfrom . import util\n\n\ndef leslie(gen, flan=[1.0, 0.0, 0.6, 1.0], nchannels=1, channel=1, frame=0,\n wet=0.5, feedback=0.5, t_amp=0.1, t_freq=0.0):\n \"\"\"\n Emulates a leslie flanger.\n NOTE: This will not work until I have coded a flanger.\n \"\"\"\n flange = flanger(*flan)\n if nchannels == 2:\n left, right = izip(*gen)\n for soundl, soundr in leslie(left), leslie(right, channel=2):\n yield (soundl, soundr)\n elif nchannels == 1:\n tf = t_freq if channel == 1 else t_freq*1.1\n while True:\n ret = 0\n for sound in gen:\n ret += (next(flange(sound, wet, feedback)) *\n next(tremolo(t_amp, tf)) + 1.0)\n yield ret\n\n\ndef chorus(gen, dry=0.5, wet=0.5, depth=1.0, delay=25.0, samplerate=44100,\n last=0.0):\n \"\"\"Emulates a chorus.\"\"\"\n adjust = float(samplerate) / 1000\n delay *= adjust\n depth *= adjust\n for i in gen:\n x = last\n last = i\n i = (i / 2 + 0.5) * depth + delay\n yield i * dry + x * wet\n\n\ndef flanger(gen, dry=0.5, wet=0.5, depth=25.0, delay=1.0, samplerate=44100,\n last=0.0):\n \"\"\"Emulates a flanger.\"\"\"\n adjust = float(samplerate) / 1000\n delay *= adjust\n depth *= adjust\n for i in gen:\n x = last\n last = i\n i = (i / 2 + 0.5) * depth + delay\n yield feedback_modulated_delay(i, x, dry, wet)\n\n\ndef tremolo(gen, dry=0.5, wet=0.5):\n \"\"\"Emulates a tremolo.\"\"\"\n for i in gen:\n mod = i / 2 + 0.5\n yield (mod / 2 + 0.5) * dry + (i * mod) * wet\n\n\ndef feedback_modulated_delay(data, last, dry, wet):\n return data * dry + last * wet\n\n\ndef modulated_delay(gen, dry, wet, last=0.0):\n \"\"\"Emulates a modulated delay.\"\"\"\n for i in gen:\n x = last\n last = i\n yield i * dry + x * wet\n\n\ndef lowpass(gen, cutoff, samplerate=44100):\n \"\"\"Emulates a lowpass filter(butterworth).\"\"\"\n coeff = 1.0 / math.tan(math.pi * cutoff / samplerate)\n b0 = 1.0 / (1.0 + math.sqrt(2.0) * coeff + coeff * coeff)\n b1 = 2.0 * b0\n b2 = b0\n a1 = 2.0 * b0 * (1.0 - coeff * coeff)\n a2 = b0 * (1.0 - math.sqrt(2.0) * coeff + coeff * coeff)\n for i in biquad_filter(gen, b0, b1, b2, a1, a2):\n yield i\n\n\ndef highpass(gen, cutoff, samplerate=44100):\n \"\"\"Emulates a highpass filter(butterworth).\"\"\"\n coeff = math.tan(math.pi * cutoff / samplerate)\n b0 = 1.0 / (1.0 + math.sqrt(2.0) * coeff + coeff * coeff)\n b1 = -2.0 * b0\n b2 = b0\n a1 = 2.0 * b0 * (coeff * coeff - 1.0)\n a2 = b0 * (1.0 - math.sqrt(2.0) * coeff + coeff * coeff)\n for i in biquad_filter(gen, b0, b1, b2, a1, a2):\n yield i\n\n\ndef biquad_filter(gen, b0=0.0, b1=0.0, b2=0.0, a1=0.0, a2=0.0,\n y=0.0, y1=0.0, y2=0.0, x1=0.0, x2=0.0):\n \"\"\"\n Emulates a biquad filter. Ugly variable names, but if you know biquad,\n they should look familiar to you, as they are mostly named the same\n in examples.\n \"\"\"\n for x in gen:\n y = b0 * x + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2\n y1, y2 = y, y1\n x1, x2 = x, x1\n yield y\n","sub_path":"AudioPython/effects.py","file_name":"effects.py","file_ext":"py","file_size_in_byte":3215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"513236720","text":"# Author: Andrew Manzanero\n# Created: 2018-04-12\n\n\"\"\"DataBase object\n- Connects to database\n- imports worksheets and converts them into tables\n- contains slugify function\n\n\"\"\"\nimport sqlite3\nimport re\nimport gspread as gs\nfrom oauth2client.service_account import ServiceAccountCredentials\nimport requests\n\n\nclass DataBase(object):\n\n def __init__(self):\n self.__main_database = 'project_manager_db.db'\n self.connector = None\n self.c = None\n self.spread_sheets_keys = None\n self.__scope = None\n self.__credentials = None\n self.client = None\n self.__credentials_json = \"credentials.json\" # FROM GOOGLE CONSOLE\n\n # gspread stuff\n if self.connected_to_internet() is True:\n self.spread_sheets_keys = \\\n \"ENTER MASTER SPREADSHEET KEY HERE\" # EDIT THIS LINE\n\n # keep this the same\n self.__scope = ['https://spreadsheets.google.com/feeds',\n 'https://www.googleapis.com/auth/drive']\n\n # MUST USE JSON PRODUCED FROM GOOGLE CONSOLE\n self.__credentials = ServiceAccountCredentials.\\\n from_json_keyfile_name(\n self.__credentials_json,\n self.__scope\n )\n self.client = gs.authorize(self.__credentials)\n self.master_sheet = self.client.open_by_key(\n self.spread_sheets_keys\n ).sheet1\n\n def connect_to_db(self):\n \"\"\"Connect to data base\n Input: None\n Output: cursor\n \"\"\"\n self.connector = sqlite3.connect(self.get_database_name())\n self.c = self.connector.cursor()\n\n def close_db(self):\n \"\"\"Close out of the database\n Input: None\n Output: None\n \"\"\"\n\n self.c.close()\n self.connector.close()\n\n def get_database_name(self):\n # Returns database name\n return self.__main_database\n\n def query(self, query_string, tup=None):\n \"\"\"Helper function to reduce amount of code written\n This queries the data base with provided string\n\n input: string representing an sqlite query\n output: none\n \"\"\"\n if tup:\n self.c.execute(query_string, tup)\n self.connector.commit()\n else:\n self.c.execute(query_string)\n self.connector.commit()\n\n @staticmethod\n def connected_to_internet(url='http://www.google.com/', timeout=5):\n \"\"\"Error handler for no internet\n\n input: none\n output: boolean\n \"\"\"\n try:\n _ = requests.get(url, timeout=timeout)\n return True\n except requests.ConnectionError:\n print(\"No internet connection available.\")\n return False\n\n\ndef slugify(text, lower=1):\n \"\"\"Turns strings with spaces into lower case with underscores\n Example:\n Andrew Manzanero = andrew_manzanero\n \"\"\"\n\n if lower == 1:\n text = text.strip().lower()\n text = re.sub(r'[^\\w _-]+', '', text)\n text = re.sub(r'[- ]+', '_', text)\n return text\n","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":3092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"26642619","text":"import pandas as pd\nfrom threading import Thread,Lock\nimport datetime\nimport random\nfrom collections import defaultdict\nfrom heapq import *\n#from kivy.app import App\n#import tbb\nimport time\nfrom geopy.distance import great_circle\nimport numpy as np\nfrom sklearn.ensemble import RandomForestRegressor\nlock=Lock()\ndef dijkstra(t,f):\n edges = [\n (\"Vazhakulam\", \"Avoly\", 4),\n (\"Avoly\", \"Vazhakulam\", 4),\n (\"Vazhakulam\", \"Nadukara\", 6),\n (\"Vazhakulam\", \"Ayavana\", 11),\n (\"Nadukara\", \"Arakuzha\", 5),\n (\"Nadukara\", \"Vazhakulam\", 6),\n (\"Arakuzha\", \"Perumballoor\", 4),\n (\"Arakuzha\", \"Nadukara\", 5),\n (\"Ayavana\", \"AnchapettyJn\", 5),\n (\"Ayavana\", \"Varappetty\", 12),\n (\"Ayavana\", \"Vazhakulam\", 11),\n (\"Perumballoor\", \"Arakuzha\", 4),\n (\"Anchapetty\", \"Puthuppady\", 7),\n (\"Anchapetty\", \"Ayavana\", 5),\n (\"Anchapetty\", \"Anicadu\", 13),\n (\"Puthuppady\", \"Anchapetty\", 7),\n (\"Puthuppady\", \"Karukadam\", 4),\n (\"Puthuppady\", \"Chalikkadavu\", 6),\n (\"Varappetty\", \"Karukadam\", 5),\n (\"Varappetty\", \"Mathirappilly\", 4),\n (\"Varappetty\", \"Kothamangalam\", 8),\n (\"Varappetty\", \"Ayavana\", 12),\n (\"Karukadam\", \"Mathirappilly\", 3),\n (\"Karukadam\", \"Varappetty\", 5),\n (\"Karukadam\", \"Puthuppady\", 4),\n (\"Mathirappilly\", \"Kothamangalam\", 7),\n (\"Mathirappilly\", \"Karukadam\", 3),\n (\"Mathirappilly\", \"Varapetty\", 4),\n (\"Anicadu\", \"Anchapetty\", 13),\n (\"Anicadu\", \"Chalikkadavu\", 7),\n (\"Kothamangalam\", \"Mathirappilly\", 7),\n (\"Kothamangalam\", \"Varappetty\", 8),\n (\"Chalikkadavu\", \"Kanam\", 2),\n (\"Chalikkadavu\", \"Puthuppady\", 6),\n (\"Chalikkadavu\", \"Anicadu\", 7),\n (\"Kizhakkekara\", \"Kanam\", 4),\n (\"Kanam\", \"Chalikkadavu\", 2),\n (\"Kanam\", \"Kizhakkekara\", 4)\n ]\n g = defaultdict(list)\n for l,r,c in edges:\n g[l].append((c,r))\n\n q, seen, mins = [(0,f,())], set(), {f: 0}\n while q:\n (cost,v1,path) = heappop(q)\n if v1 not in seen:\n seen.add(v1)\n path = (v1, path)\n if v1 == t: return (cost, path)\n\n for c, v2 in g.get(v1, ()):\n if v2 in seen: continue\n prev = mins.get(v2, None)\n next = cost + c\n if prev is None or next < prev:\n mins[v2] = next\n heappush(q, (next, v2, path))\n\n return float(\"inf\")\n\ndef addtime(min,ctime):\n t = round(min, 2)\n t = t * 3600\n s = str(datetime.timedelta(seconds=t))\n timeList = []\n timeList.append(s)\n timeList.append(ctime)\n sum = datetime.timedelta()\n for i in timeList:\n (h, m, s) = i.split(':')\n d = datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s))\n sum += d\n return (str(sum))\n\ndef zone():\n t = time.strftime(\"%H:%M:%S\") # get system time\n hr = t[0] + t[1]\n hr = int(hr)\n mini = t[3] + t[4]\n mini = int(mini)\n if(mini==0 and hr==7):\n z=1\n elif(mini==0 and hr==10):\n z=2\n elif(mini==0 and hr==16):\n z=3\n elif(mini==0 and hr==19):\n z=4\n elif(mini==0 and hr==22):\n z=5\n else:\n if( hr>=7 and hr<10 and mini>0):\n z=2\n elif( hr>=10 and hr<16 and mini>0):\n z=3\n elif( hr>=16 and hr<19 and mini>0):\n z=4\n elif( hr>=19 and hr<22 and mini>0):\n z=5\n else:\n z=1\n return z\n\ndef lati_longi(loc):\n lock.acquire()\n lat_long = {'Kothamangalam': [10.060190, 76.635083],\n 'Mathirappilly': [10.045843, 76.616721],\n 'Karukadam': [10.033244, 76.609500],\n 'Puthuppady': [10.011139, 76.603722],\n 'Vazhakulam': [9.946958, 76.635900],\n 'Avoly': [9.958699, 76.625166],\n 'Anicadu': [9.968679, 76.607780],\n 'Kizhakkekara': [9.977876, 76.592166],\n 'Muvattupuza': [9.989423, 76.578975],\n 'Arakuzha': [9.927757, 76.602278],\n 'Perumballoor': [9.953572, 76.592763]\n }\n lock.release()\n return lat_long[loc]\n\ndef datasets1(current_loc,places,v,dataset,dest):\n path=dataset\n places1 = places\n data = pd.read_csv(path)\n model = RandomForestRegressor()\n l = ['Time_interval']+places1\n predictors =np.array(l)\n y = data.Average_speed\n X = data[predictors]\n model.fit(X, y)\n q = zone()\n d=[q]\n for j in v:\n d.append(j)\n l = lati_longi(current_loc)\n g = lati_longi('Muvattupuza')\n dist =great_circle(l,g).kilometers\n tym=(dist / model.predict([d]))\n calc_time(tym[0], q, current_loc, dest)\ndef wttime(tym,count):\n path=\"count.csv\"\n data=pd.read_csv(path)\n model = RandomForestRegressor()\n predictors=(['Time_interval','Count'])\n y = data.Average_wt_time\n X = data[predictors]\n model.fit(X, y)\n d=[[tym,count]]\n return model.predict(d)\ndef calc_time(tym,q,current_loc,dest):\n arrival_time=addtime(tym,time.strftime(\"%H:%M:%S\"))\n if q==1:\n count=random.randint(1,30)\n elif q==2:\n count = random.randint(90, 200)\n elif q==3:\n count = random.randint(20, 120)\n elif q==4:\n count = random.randint(100, 250)\n elif q==5:\n count=random.randint(20,100)\n wait_time=wttime(q,count)\n print(\"Assuming the number of vehicles count to be: \",count)\n print(\"The time you can cross the traffic is: \",addtime(wait_time[0]/3600 ,arrival_time))\n if wait_time >=100:\n ss=dijkstra(current_loc, dest)[1]\n ss=str(ss)\n m=['(',')',',',\"'\"]\n k=\"\"\n for i in ss:\n if i not in m:k+=i\n k=k.split(\" \")\n route=\"->\".join(k)\n print(\"The most optimal path is \",route)\ndef model():\n places1=[\"Kothamangalam\",\"Mathirappilly\",\"Karukadam\",\"Puthuppady\"]\n places2=['Vazhakulam','Avoly','Anicadu','Kizhakkekara']\n places3=[\"Arakuzha\",\"Perumballoor\"]\n places=places2+places1+places3\n print(places1)\n print(places2)\n print(places3)\n current_loc=input(\"Enter the current location(any one from above list): \")\n dest=input(\"Enter the destination: \")\n v=[]\n if current_loc in places1 and dest not in places1:\n dataset=\"datasets1.csv\"\n n=places1.index(current_loc)\n for i in range(n,len(places1)):\n print(\"Enter the speed at place \", places1[i])\n x = int(input())\n v.append(x)\n current_loc=places1[i]\n datasets1(current_loc, places1[n:i+1],v,dataset,dest)\n elif current_loc in places2 and dest not in places2:\n n = places2.index(current_loc)\n dataset=\"datasets2.csv\"\n for i in range(n,len(places2)):\n print(\"Enter the speed at place:\", places2[i])\n x = int(input())\n v.append(x)\n current_loc = places2[i]\n datasets1(current_loc, places2[n:i+1],v,dataset,dest)\n elif current_loc in places3 and dest not in places1:\n dataset=\"datasets3.csv\"\n n = places3.index(current_loc)\n for i in range(n,len(places3)):\n print(\"Enter the speed at place \", places3[i])\n x = int(input())\n v.append(x)\n current_loc = places3[i]\n datasets1(current_loc, places3[n:i+1],v,dataset,dest)\n elif current_loc not in places:\n print(\"ERROR: Only places listed above is allowed\")\n exit()\n else:\n print(\"No traffic block found in the route\")\n print(current_loc,\"->\",dest)\n exit()\nmodel()\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":7624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"402527722","text":"#!/usr/bin/env python\n\n\"\"\"Classes for Fern reproduction.\n\nThe parent PteridophyteBase class has shared parameters and functions\nfor classes PteridophyteHomosporous and PteridophyteHeterosporous. The\nparameters for these classes are defined in the factory functions \nin :mod:`reproduction.optimized.pteridophytes`.\n\nParameters\n----------\n\n\"\"\"\nfrom typing import Optional\nfrom dataclasses import dataclass, field\nfrom shadie.reproduction.base import NonWrightFisher\n# from shadie.reproduction.scripts import (\n # GAM_MATERNAL_EFFECT_ON_P1,\n # SPO_MATERNAL_EFFECT_ON_P0,\n # SUBSTITUTION,\n # EARLY,\n# )\nfrom shadie.reproduction.fern_scripts import (\n REPRO_PTER_HOMOSPORE_P1, \n REPRO_PTER_HOMOSPORE_P0,\n LATE_PTER_HOMOSPORE,\n FUNCTIONS_PTER_HOMOSPORE, \n # PTER_HETERO_FITNESS_SCALE,\n)\n\nfrom shadie.reproduction.fern_scripts2 import (\n LATE_PTER_HETERO,\n EARLY_PTER_HETERO,\n FUNCTIONS_PTER_HETERO,\n SURVIVAL_PTER_HETERO,\n REPRO_PTER_HETEROSPORE_P1, \n REPRO_PTER_HETEROSPORE_P0,\n)\n\n\n@dataclass\nclass PteridophyteBase(NonWrightFisher):\n lineage: str = field(default=\"Bryophyte\", init=False)\n spo_pop_size: int\n gam_pop_size: int\n spo_mutation_rate: Optional[float]\n gam_mutation_rate: Optional[float]\n gam_clone_rate: float # TODO: maybe replace rate/num with a single poisson draw\n gam_clones_per: int\n spo_clone_rate: float\n spo_clones_per: int\n # spo_self_rate: float\n spo_self_rate_per_egg: float # egg_spo_self_rate: float\n spo_self_rate_per_ind: float # spo_self_chance: float\n spo_random_death_chance: float\n gam_random_death_chance: float\n spo_maternal_effect: float\n gam_archegonia_per: int\n # gam_antheridia_per: int # not modeled b/c it is very large.\n\n def _set_mutation_rates(self):\n \"\"\"Checks parameters after init.\"\"\"\n # Set mutation rates for both, or use Model rate / 2 for both.\n if self.spo_mutation_rate or self.gam_mutation_rate:\n require_spo = self.spo_mutation_rate is not None\n require_gam = self.gam_mutation_rate is not None\n assert require_gam and require_spo, (\n \"You must define a mutation rate for both sporophyte \"\n \"and gametophyte generations.\")\n else:\n self.spo_mutation_rate = 0.5 * self.model.metadata['mutation_rate']\n self.gam_mutation_rate = 0.5 * self.model.metadata['mutation_rate']\n\n def _add_shared_mode_scripts(self):\n \"\"\"Adds scripts shared by homosp and heterosp superclasses.\n\n Adds shadie-defined functions and a survival script to define \n the random_chance_of_death, maternal effects, and survival=0 for \n alternation of generations.\n \"\"\"\n self.model.custom(\n scripts=SURVIVAL_PTER_HETERO,\n comment=\"alternate to other generation, random death and maternal effects.\",\n )\n\n\n@dataclass\nclass PteridophyteHomosporous(PteridophyteBase):\n \"\"\"Reproduction mode based on homosporoous ferns and lycophytes\"\"\"\n mode: str = field(default=\"homosporous\", init=False)\n spo_spores_per: int\n gam_maternal_effect: float\n gam_self_rate: float\n\n def run(self):\n \"\"\"Fill self.model.map with SLiM script snippets.\"\"\"\n # methods inherited from parent Pteridophyte class\n self._set_mutation_rates()\n self._add_shared_mode_scripts()\n\n # methods inherited from parent NonWrightFisher class\n self._define_subpopulations()\n self._add_early_and_late(...)\n self._add_initialize_constants()\n self._write_trees_file()\n\n # mode-specific functions\n self._add_mode_scripts()\n\n def _add_mode_scripts(self):\n \"\"\"Add reproduction scripts unique to heterosporous bryo.\"\"\"\n self.model.custom(\n scripts=FUNCTIONS_PTER_HOMOSPORE, \n comment=\"shadie DEFINITIONS\",\n )\n self.model.repro(\n idx=\"s5\",\n population=\"p1\",\n scripts=REPRO_PTER_HOMOSPORE_P1,\n comment=\"generates gametes from sporophytes\"\n )\n self.model.repro(\n idx=\"s6\",\n population=\"p0\",\n scripts=REPRO_PTER_HOMOSPORE_P0,\n comment=\"generates gametes from sporophytes\"\n )\n\n\n@dataclass\nclass PteridophyteHeterosporous(PteridophyteBase):\n mode: str = field(default=\"heterosporous\", init=False)\n # rs_megasporangia_per: int\n # rs_microsporangia_per: int\n # megasporangia_megaspores_per: int\n # microsporangia_microspores_per: int\n #spo_female_to_male_ratio: float\n spo_microspores_per: int\n spo_megaspores_per: int\n\n def run(self):\n \"\"\"Fill self.model.map with SLiM script snippets.\"\"\"\n # methods inherited from parent Bryophyte class\n self._set_mutation_rates()\n self._add_shared_mode_scripts()\n\n # methods inherited from parent NonWrightFisher class\n self._define_subpopulations()\n self._add_early_and_late(EARLY_PTER_HETERO, LATE_PTER_HETERO)\n self._add_initialize_constants()\n self._write_trees_file()\n\n # mode-specific functions\n self._add_mode_scripts()\n\n def _add_mode_scripts(self):\n \"\"\"Add reproduction scripts unique to heterosporous bryo.\"\"\"\n self.model.custom(\n scripts=FUNCTIONS_PTER_HETERO, \n comment=\"shadie DEFINITIONS\",\n )\n\n self.model.repro(\n population=\"p1\",\n idx=\"s5\",\n scripts=REPRO_PTER_HETEROSPORE_P1,\n comment=\"reproduction in p1: eggs or sperm are created.\"\n )\n\n self.model.repro(\n population=\"p0\",\n idx=\"s6\",\n scripts=REPRO_PTER_HETEROSPORE_P0,\n comment=\"reproduction in p0: eggs are fertilized by sperm.\"\n )\n\n\n\nif __name__ == \"__main__\":\n\n import shadie\n with shadie.Model() as mod:\n\n # define mutation types\n m0 = shadie.mtype(0.5, 'n', 0, 0.4)\n m1 = shadie.mtype(0.5, 'g', 0.8, 0.75)\n #I suggest we add a checkpoint that calculates the average\n #fitness of mutations input by the user. If fitness is too high\n #the simuulation will lag tremendously. \n # OK: a good use case for logger.warning('fitness is too high...')\n \n # define elements types\n e0 = shadie.EXON\n e1 = shadie.INTRON\n \n # design chromosome of elements\n chrom = shadie.chromosome.random(\n genome_size=20000,\n noncds=e0,\n intron=e0,\n exon=e1,\n )\n\n # init the model\n mod.initialize(chromosome=chrom)\n\n mod.reproduction.pteridophyte_homosporous(\n spo_pop_size=1000, \n gam_pop_size=1000,\n spo_spores_per=100\n )\n\n\n print(mod.script)\n #mod.run()\n","sub_path":"shadie/reproduction/fernbase.py","file_name":"fernbase.py","file_ext":"py","file_size_in_byte":6828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"333868545","text":"#!/usr/bin/env python3\nfrom __future__ import print_function\nfrom sys import platform\n\nimport subprocess\nimport getopt\nimport sys\n\n\ndef usage():\n return \"Usage: ./benchmarks_report.py --o=reports/data/brute_force.csv\"\n\n\ndef main():\n print(\"Welcome to benchmark report generation\")\n\n try:\n opts, args = getopt.getopt(\n sys.argv[1:], \"hm:num3:\n print(str(num3) + \"; \" + str(num1) + \"; \" + str(num2))\nelif num2num2:\n print(str(num2) + \"; \" + str(num1) + \"; \" + str(num3))\nelif num1>num2 and num2>num3:\n print(str(num3) + \"; \" + str(num2) + \"; \" + str(num1))\nelif num1>num2 and num2num2 and num2= 90.0:\n print(\"A\")\nelif num >= 80.0:\n print(\"B\")\nelif num >= 70.0:\n print(\"C\")\nelif num >= 60.0:\n print(\"D\")\nelse:\n print(\"F\")\n\n# Assignment 3\ngrade1 = float(input(\"Input a test grade: \"))\ngrade2 = float(input(\"Input another test grade: \"))\ngrade3 = float(input(\"Input another test grade: \"))\n\navgGrade = (grade1 + grade2 + grade3) / 3.0\n\nif avgGrade >= 90.0:\n print(\"A\")\nelif avgGrade >= 80.0:\n print(\"B\")\nelif avgGrade >= 70.0:\n print(\"C\")\nelif avgGrade >= 60.0:\n print(\"D\")\nelse:\n print(\"F\")\n","sub_path":"Class-Programs/Python3/CheckUnderstanding_If_Else.py","file_name":"CheckUnderstanding_If_Else.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"250844348","text":"import json\n\nf = open('1.50kgz_coins.json')\n\ndata = json.load(f)\ncoin_ids = []\n\nfor i in data['list']:\n coin_ids.append(i['id'])\n\n# print(coin_ids)\n\nf.close()\n\nf2 = open('50_kgz_coins_ids.txt', 'w')\nfor i in coin_ids:\n f2.write(str(i))\n f2.write('\\n')\nf2.close()\n","sub_path":"docs/GET_50KGZ_COINS/2.py_formatter.py","file_name":"2.py_formatter.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"199901599","text":"\"\"\"\npyProm: Copyright 2016\n\nThis software is distributed under a license that is described in\nthe LICENSE file that accompanies it.\n\nThis library contains a container class for storing SpotElevation\ntype location objects.\n\"\"\"\nimport json\n\nfrom ..location_util import longitudeArcSec\nfrom ..locations.saddle import Saddle\nfrom ..locations.summit import Summit\nfrom ..locations.spot_elevation import SpotElevation\nfrom ..locations.base_gridpoint import BaseGridPoint\nfrom ..locations.gridpoint import GridPoint\nfrom .multipoint import MultiPoint\nfrom .gridpoint import GridPointContainer\nfrom .base import _Base\nfrom math import sqrt\n\n\nclass SpotElevationContainer(_Base):\n \"\"\"\n Container for Spot Elevation type lists.\n Allows for various list transformations.\n \"\"\"\n def __init__(self, spotElevationList):\n \"\"\"\n :param spotElevationList: list of :class:`SpotElevation`s\n \"\"\"\n super(SpotElevationContainer, self).__init__()\n self.points = spotElevationList\n\n def radius(self, lat, long, datamap, value, unit='m'):\n \"\"\"\n :param lat: latitude of center in dotted decimal\n :param long: longitude of center in dotted decimal\n :param datamap: datamap object\n :param value: number of units of distance\n :param unit: type of unit (m, km, mi, ft)\n :return: SpotElevationContainer loaded with results.\n \"\"\"\n unit = unit.lower()\n if unit in ['meters', 'meter', 'm']:\n convertedDist = value\n elif unit in ['kilometers', 'kilometer', 'km']:\n convertedDist = value * 1000\n elif unit in ['feet', 'foot', 'ft']:\n convertedDist = 0.3048 * value\n elif unit in ['miles', 'mile', 'mi']:\n convertedDist = 0.3048 * value * 5280\n else:\n raise ValueError('No unit value specified')\n\n positive = list()\n longitudalMetersPerArcSec = longitudeArcSec(lat) *\\\n datamap.arcsec_resolution\n lateralMetersPerArcSec = 30.8666\n for point in self.points:\n latDist = (abs(lat - point.latitude) * 3600) *\\\n lateralMetersPerArcSec\n longDist = (abs(long - point.longitude) * 3600) *\\\n longitudalMetersPerArcSec\n distance = sqrt(longDist**2 + latDist**2)\n if distance <= convertedDist:\n positive.append(point)\n return SpotElevationContainer(positive)\n\n def rectangle(self, lat1, long1, lat2, long2):\n \"\"\"\n For the purpose of gathering all points in a rectangle of\n (lat1, long1) - (lat2, long2)\n :param lat1: latitude of point 1\n :param long1: longitude of point 1\n :param lat2: latitude of point 2\n :param long2: longitude of point 2\n :return: list of all points in that between\n (lat1, long1) - (lat2, long2)\n \"\"\"\n upperlat = max(lat1, lat2)\n upperlong = max(long1, long2)\n lowerlat = min(lat1, lat2)\n lowerlong = min(long1, long2)\n return SpotElevationContainer(\n [x for x in self.points if lowerlat < x.latitude < upperlat and\n lowerlong < x.longitude < upperlong])\n\n def byType(self, string):\n \"\"\"\n :param string: Object type (as String). ex: Saddle, Summit\n :return: SpotElevationContainer of objects by type.\n \"\"\"\n name = string.upper()\n return SpotElevationContainer([x for x in self.points\n if type(x).__name__.upper() == name])\n\n def elevationRange(self, lower=-100000, upper=100000):\n \"\"\"\n :param lower: lower limit in feet\n :param upper: upper limit in feet\n :return: list of all points in range between lower and upper\n \"\"\"\n return SpotElevationContainer([x for x in self.points if\n x.feet > lower and x.feet < upper])\n\n def elevationRangeMetric(self, lower=-100000, upper=100000):\n \"\"\"\n :param lower: lower limit in Meters\n :param upper: upper limit in Meters\n :return: list of all points in range between lower and upper\n \"\"\"\n return SpotElevationContainer([x for x in self.points if\n x.elevation > lower and\n x.elevation < upper])\n\n def to_json(self, prettyprint=True):\n \"\"\"\n :param prettyprint: human readable,\n but takes more space when written to a file.\n :return: json string of all points in this container.\n \"\"\"\n if prettyprint:\n return json.dumps([x.to_dict(recurse=True) for x in self.points],\n sort_keys=True, indent=4, separators=(',', ': '))\n else:\n return json.dumps([x.to_dict(recurse=True) for x in self.points])\n\n def from_json(self, jsonData, datamap):\n \"\"\"\n :param jsonData: json string of data to be loaded in this container\n :param datamap:\n :return:\n \"\"\"\n hash = json.loads(jsonData)\n self.points = list()\n for point in hash:\n objType = point.get('type', 'SpotElevation')\n if objType == 'Summit':\n feature = Summit(point['latitude'],\n point['longitude'],\n point['elevation'])\n elif objType == 'Saddle':\n feature = Saddle(point['latitude'],\n point['longitude'],\n point['elevation'])\n elif objType == 'SpotElevation':\n feature = SpotElevation(point['latitude'],\n point['longitude'],\n point['elevation'])\n else:\n raise Exception('Cannot import unknown type:'.format(objType))\n mpPoints = list()\n if point.get('multipoint', None):\n for mp in point['multipoint']:\n mpPoints.append(BaseGridPoint(mp['gridpoint']['x'],\n mp['gridpoint']['y']))\n feature.multiPoint = MultiPoint(mpPoints,\n point['elevation'],\n datamap)\n if point.get('highShores', None):\n feature.highShores = list()\n for hs in point['highShores']:\n feature.highShores.append(\n GridPointContainer(\n [GridPoint(x['x'], x['y'], x['elevation'])\n for x in hs]))\n feature.edgeEffect = point['edge']\n self.points.append(feature)\n\n def __repr__(self):\n return \" {} Objects\".format(len(self.points))\n\n __unicode__ = __str__ = __repr__\n","sub_path":"pyprom/lib/containers/spot_elevation.py","file_name":"spot_elevation.py","file_ext":"py","file_size_in_byte":6937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"257422804","text":"## modulos para uso de requests\n# manejar http requests\nfrom django.http import HttpResponse\n# para enviar un json como response\nimport json\n\n# utils\n# mostrar la hora\nfrom datetime import datetime\n\n# primer hola mundo\ndef hello_world(request):\n return HttpResponse('hello_world! {now}'.format(\n now=datetime.now().strftime('%b %dth, %Y - %H:%M hrs')\n ))\n\n# recibir números y devolver json ordenado\ndef sort_numbers(request):\n numbers = [int(i) for i in request.GET['numbers'].split(',')]\n sorted_numbers = sorted(numbers)\n data = {\n 'status' : 'ok',\n 'numbers' : sorted_numbers,\n 'message' : 'Numbers sorted correctly'\n }\n return HttpResponse(\n json.dumps(data),\n content_type='application/json'\n )\n\n# recibir un nombre, una edad y saludar si es mayor de edad\ndef say_hi(request, name, age):\n if age>=13:\n message = 'Hello {}! Welcome to Sornygram'.format(name)\n else:\n message = 'Sorry, you are not allowed here'.format(name)\n return HttpResponse(message)\n","sub_path":"sornygram/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"180147746","text":"import argparse\nimport pandas as pd\nfrom array import array\n\nimport ROOT\nROOT.gROOT.SetBatch(True)\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"shape_file\", help=\"Shape file to add QCD systematics\")\n parser.add_argument(\"syst_file\", help=\"Input file with QCD systematics\")\n return parser.parse_args()\n\ndef get_df(path):\n return pd.read_table(path, sep='\\s+')\n\ndef convert_to_hist(x, vals, name):\n x = array('f', x)\n hist = ROOT.TH1D(name, name, len(x)-1, x)\n hist.SetDirectory(0)\n\n for i, v in enumerate(vals):\n hist.SetBinContent(i+1, v if v>=1e-7 else 1e-7)\n return hist\n\ndef main():\n options = parse_args()\n\n df = get_df(options.syst_file)\n x = df[\"x\"].values\n\n rfile = ROOT.TFile.Open(options.shape_file, \"UPDATE\")\n keys = [\n k.GetName()\n for k in rfile.GetListOfKeys()\n if \"qcd\" in [\n subk.GetName()\n for subk in rfile.Get(k.GetName()).GetListOfKeys()\n ]\n ]\n\n for key in keys:\n rfile.cd(key)\n qcd_original = ROOT.gDirectory.Get(\"qcd\").Clone(\"qcd_original_{}\".format(key))\n\n vals = 1.+df[\"qcd_syst\"].values\n vals[vals<=0.] = 0.\n hist = convert_to_hist(x, vals, \"qcd\")\n hist.Multiply(qcd_original)\n if \"qcdSystUp\" not in [k.GetName() for k in ROOT.gDirectory.GetListOfKeys()]:\n ROOT.gDirectory.mkdir(\"qcdSystUp\")\n ROOT.gDirectory.cd(\"qcdSystUp\")\n hist.Write(\"\", ROOT.TObject.kOverwrite)\n print(\"Writing {}/{}/{}\".format(key, \"qcdSystUp\", \"qcd\"))\n hist.Delete()\n rfile.cd(key)\n\n vals = 1./(1.+df[\"qcd_syst\"].values)\n vals[vals<=0.] = 0.\n hist = convert_to_hist(x, vals, \"qcd\")\n hist.Multiply(qcd_original)\n if \"qcdSystDown\" not in [k.GetName() for k in ROOT.gDirectory.GetListOfKeys()]:\n ROOT.gDirectory.mkdir(\"qcdSystDown\")\n ROOT.gDirectory.cd(\"qcdSystDown\")\n hist.Write(\"\", ROOT.TObject.kOverwrite)\n print(\"Writing {}/{}/{}\".format(key, \"qcdSystDown\", \"qcd\"))\n hist.Delete()\n rfile.cd(key)\n\n for ibin in range(df.columns.shape[0]-2):\n name = \"qcd_syst_bin{}\".format(ibin)\n vals = 1.+df[name].values\n vals[vals<=0.] = 0.\n hist = convert_to_hist(x, vals, \"qcd\")\n hist.Multiply(qcd_original)\n if \"qcdSystBin{}Up\".format(ibin) not in [k.GetName() for k in ROOT.gDirectory.GetListOfKeys()]:\n ROOT.gDirectory.mkdir(\"qcdSystBin{}Up\".format(ibin))\n ROOT.gDirectory.cd(\"qcdSystBin{}Up\".format(ibin))\n hist.Write(\"\", ROOT.TObject.kOverwrite)\n print(\"Writing {}/{}/{}\".format(key, \"qcdSystBin{}Up\".format(ibin), \"qcd\"))\n hist.Delete()\n rfile.cd(key)\n\n vals = 1./(1.+df[name].values)\n vals[vals<=0.] = 0.\n hist = convert_to_hist(x, vals, \"qcd\")\n hist.Multiply(qcd_original)\n if \"qcdSystBin{}Down\".format(ibin) not in [k.GetName() for k in ROOT.gDirectory.GetListOfKeys()]:\n ROOT.gDirectory.mkdir(\"qcdSystBin{}Down\".format(ibin))\n ROOT.gDirectory.cd(\"qcdSystBin{}Down\".format(ibin))\n hist.Write(\"\", ROOT.TObject.kOverwrite)\n print(\"Writing {}/{}/{}\".format(key, \"qcdSystBin{}Down\".format(ibin), \"qcd\"))\n hist.Delete()\n rfile.cd(key)\n\n qcd_original.Delete()\n rfile.Close()\n rfile.Delete()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"datacards/add_qcd_systs.py","file_name":"add_qcd_systs.py","file_ext":"py","file_size_in_byte":3515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"604416432","text":"from GetArticles import GetArticles\nfrom TextScraper import extract_text\nfrom GetArticleInfo import GeoLocate\nfrom GetEntities import GetEntities\nfrom LoadDB import load_database\nimport timeit\nfrom pprint import pprint\n\nstart_time = timeit.default_timer()\narticle = GetArticles('http://content.guardianapis.com/search?', 'world', 'contributor', 1, 200,\n 't8xg55ekdzgcquyvgtqktmjq')\narticle_json = article.article_info()\nfor article in article_json:\n article_url = \"http://www.theguardian.com/\" + article['id']\n text = extract_text(article_url)\n location_data = GeoLocate('http://localhost:8999/cliff-2.3.0/parse/text', text, True)\n location_dict = location_data.location_info()\n try:\n for l in location_dict:\n article['article_focus'] = l\n except ValueError:\n continue\n entities = GetEntities(text)\n people_info = entities.people()\n for p in people_info:\n article['people'] = p\n org_info = entities.organisations()\n for o in org_info:\n article['organisations'] = o\n keyword_info = entities.keywords()\n for k in keyword_info:\n article['keywords'] = k\n if not article['article_focus']:\n del article\n continue\n pprint(article)\n load_database(article)\n\nelapsed = timeit.default_timer() - start_time\nprint(elapsed)\n","sub_path":"process_articles/Driver.py","file_name":"Driver.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"118437048","text":"from django.conf.urls import url\nfrom .import views\n\n\nurlpatterns=[\n\n\turl(r'^$',views.index,name='index'),\n\turl(r'^topics/$',views.topics,name='topics'),\n\turl(r'^owner/$',views.owner,name='owner'),\n\turl(r'^topics/(?P\\d+)/$',views.topic,name='topic'),\n\turl(r'^new_topic/$',views.new_topic,name='new_topic'),\n\turl(r'^new_entry/(?P\\d+)/$',views.new_entry,name='new_entry'),\n\turl(r'^edit_entry/(?P\\d+)/$',views.edit_entry,name='edit_entry'),\n\turl(r'^entries/(?P\\d+)/$',views.entry,name='entry'),\n\turl(r'^new_comment/(?P\\d+)/$',views.new_comment,name='new_comment'),\n]","sub_path":"syy_topics/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"351582518","text":"# subscriber.py\nimport paho.mqtt.client as mqtt\n\ndef on_connect(client, userdata, flags, rc):\n print(f\"Connected with result code {rc}\")\n # subscribe, which need to put into on_connect\n # if reconnect after losing the connection with the broker, it will continue to subscribe to the raspberry/topic topic\n client.subscribe(\"#\")\n\n# the callback function, it will be triggered when receiving messages\ndef on_message(client, userdata, msg):\n print(f\"{msg.topic} {msg.payload}\")\n \nclient = mqtt.Client()\nclient.on_connect = on_connect\nclient.on_message = on_message\n\n# set the will message, when the Raspberry Pi is powered off, or the network is interrupted abnormally, it will send the will message to other clients\nclient.will_set('test/message', b'{\"status\": \"Off\"}')\n\n# create connection, the three parameters are broker address, broker port number, and keep-alive time respectively\nclient.connect(\"mqtt.devbit.be\", 1883, 60)\n\n# set the network loop blocking, it will not actively end the program before calling disconnect() or the program crash\nclient.loop_forever()","sub_path":"Mqtt/subscriber.py","file_name":"subscriber.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"582440073","text":"import argparse\nimport logging\nimport sys\nimport warnings\nimport yaml\n\nfrom dotenv import load_dotenv\nfrom os.path import join, dirname\n\ndotenv_path = join(dirname(__file__), '.env')\nload_dotenv(dotenv_path=dotenv_path)\n\nfrom src.OCRProcessor import OCRProcessor\nfrom src.ScanDirectoryMonitor import ScanDirectoryMonitor\nfrom src.eMailMonitor import eMailMonitor\n\ndef load_config(filepath):\n with open(filepath, 'r') as configfile:\n return yaml.load(configfile)\n \ncfg = load_config(join(dirname(__file__), 'config.yml'))\n\n\nlist_of_choices = [\n 'ocrprocess',\n 'mailbox',\n 'monitor'\n]\n\nparser = argparse.ArgumentParser(description='kDatacenter Mail Processing')\n\nparser.add_argument(\n '-r',\n '--routines',\n required=True,\n nargs='+',\n choices=list_of_choices,\n metavar='R',\n help='List of routines to run: {}'.format(', '.join(list_of_choices))\n)\n\nparser.add_argument(\"-d\", \"--directories\", nargs='+',\n help=\"directories to be monitored for inbound scans, works with --routines=monitor\", metavar=\"STRINGS\")\n\ndef main(args=sys.argv[1:]):\n\n args = parser.parse_args(args)\n\n if 'ocrprocess' in args.routines:\n processor = OCRProcessor(cfg)\n processor.init_consuming()\n\n if 'mailbox' in args.routines:\n monitor = eMailMonitor()\n monitor.init_monitoring()\n\n if 'monitor' in args.routines:\n\n ##[\"/mnt/EicScanRaw\", \"/mnt/KirScanRaw\"]\n directories = args.directories\n\n if len(directories) > 0:\n \n for d in directories:\n logging.info(\"The following directory should be monitored {}\".format(d))\n \n monitor = ScanDirectoryMonitor(directories)\n monitor.init_monitoring()\n \n else: \n logging.error(\"Please provide at least one directory to be monitored (-d/--directories)\")\n \nmain(sys.argv[1:])","sub_path":"__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"569473480","text":"from django.shortcuts import get_object_or_404, render, redirect, HttpResponse\nfrom .models import BlogCategory, Blog\nfrom Public.views import layout_data\n\n\n# Create your views here.\ndef category(request):\n model = layout_data(request)\n model[\"category\"] = BlogCategory.objects.all()\n return render(request, 'Blog/Category.html', model)\n\n\ndef blog_detail(request, category, blog):\n page = Blog.objects.get(title=blog)\n pageName = \"Blog_\" + str(page.id)\n return render(request, 'Blog/' + pageName + '.html', layout_data(request))\n","sub_path":"Blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"271611725","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom setuptools import setup, find_packages\n\nwith open('README.rst') as fd:\n README = fd.read()\n\nCLASSIFIERS = [\n 'Environment :: Web Environment',\n 'Framework :: Django',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Topic :: Internet :: WWW/HTTP',\n 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',\n]\n\nsetup(\n author=\"Bartosz Gryszko\",\n author_email=\"b@gryszko.com\",\n name=\"django-recaptcha-mailhide\",\n packages=find_packages(exclude=['docs']),\n version='1.2',\n description=\"ReCAPTCHA Mailhide is an app for hiding mails from spammers. To use with Django templates.\",\n long_description=README,\n url='https://github.com/bgryszko/django-recaptcha-mailhide',\n license='MIT',\n platforms=['OS Independent'],\n classifiers=CLASSIFIERS,\n keywords= ['Django', 'ReCaptcha'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'Django>=1.10.0,<1.11',\n 'pycrypto>=2.6.1',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"72223017","text":"import dendropy\nimport numpy as np\nimport math\nimport numpy.linalg as la\n\ndef give_index(c):\n if c == \"A\":\n return 0\n elif c == \"C\":\n return 1\n elif c == \"G\":\n return 2\n elif c == \"T\":\n return 3\n# =======================================================================================================\ndna = 'CGCC'\n\ntips = 4 #tips number\nbr_length = 0.1\nrates = np.ones(5)\npi = [0.25]*4\n\n\ntree = dendropy.Tree.get_from_string('((1,2)5,3,4)6;', 'newick')\nalignment = dendropy.DnaCharacterMatrix.get(file=open(\"/home/nehleh/0_Research/PhD/Data/test.fasta\"), schema=\"fasta\")\npartial = np.zeros((4,2*tips))\n\n\n\n\nn = alignment.sequence_size\nmu = 0\nfreq = np.zeros((4, 4))\nq = np.zeros((4, 4))\nsqrtPi = np.zeros((4, 4))\nsqrtPiInv = np.zeros((4, 4))\nexchang = np.zeros((4, 4))\ns = np.zeros((4, 4))\nfun = np.zeros(n)\na, b, c, d, e = rates\nf = 1\n\nfreq = np.diag(pi)\nsqrtPi = np.diag(np.sqrt(pi))\nsqrtPiInv = np.diag(1.0 / np.sqrt(pi))\nmu = 1 / (2 * ((a * pi[0] * pi[1]) + (b * pi[0] * pi[2]) + (c * pi[0] * pi[3]) + (d * pi[1] * pi[2]) + (\n e * pi[1] * pi[3]) + (pi[2] * pi[3])))\nexchang[0][1] = exchang[1][0] = a\nexchang[0][2] = exchang[2][0] = b\nexchang[0][3] = exchang[3][0] = c\nexchang[1][2] = exchang[2][1] = d\nexchang[1][3] = exchang[3][1] = e\nexchang[2][3] = exchang[3][2] = f\n\nq = np.multiply(np.dot(exchang, freq), mu)\n\nfor i in range(4):\n q[i][i] = -sum(q[i][0:4])\n\ns = np.dot(sqrtPi, np.dot(q, sqrtPiInv))\n\neigval, eigvec = la.eig(s)\neigvec_inv = la.inv(eigvec)\n\nleft = np.dot(sqrtPi, eigvec)\nright = np.dot(eigvec_inv, sqrtPiInv)\n\np = np.dot(left, np.dot(np.diag(np.exp(eigval * br_length)), right))\n\n\nfor node in tree.postorder_node_iter():\n node.index = -1\n node.annotations.add_bound_attribute(\"index\")\n\ns = tips + 1\nfor id,node in enumerate(tree.postorder_node_iter()):\n if not node.is_leaf():\n node.index = s\n s += 1\n else:\n for idx, name in enumerate(dna):\n if idx + 1 == int(node.taxon.label):\n node.index = idx+1\n break\n\n\nfor node in tree.postorder_node_iter():\n if node.is_leaf():\n i = give_index(dna[node.index-1])\n partial[i][node.index-1] = 1\n else:\n for j in range(4):\n sump = []\n for x in node.child_node_iter():\n z = 0\n for k in range(4):\n z += p[j][k] * partial[k][x.index-1]\n sump.append(z)\n partial[j][node.index-1] = np.prod(sump)\n\n\n\ntemp = []\nfor i in range(4):\n temp.append(partial[i,2*tips -3] * pi[i])\nll = sum(temp)\n\nprint(\"likelihood = {} and log-likelihood = {} \".format(round(ll,7) , round(np.log(ll),7)))","sub_path":"GTR_fulltree.py","file_name":"GTR_fulltree.py","file_ext":"py","file_size_in_byte":2716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"546072529","text":"from collections import deque\n\n'''\n维护一个定长队列,当有新元素加入时,自动将最老的元素删去\n如:\n>>>q = deque(maxlen=3)\n>>>for i in range(3):\n\t q.append(i)\n>>>q\ndeque([1,2,3], maxlen=3)\n>>>q.append(4)\n>>>q\ndeque([2,3,4], maxlen=3)\n'''\n\ndef search(lines, pattern, history=3):\n\tprevious_lines = deque(maxlen=history)\n\tfor line in lines:\n\t\tif pattern in line:\n\t\t\tyield line, previous_lines\n\t\tprevious_lines.append(line)\n\nif __name__ == '__main__':\n\twith open('deque.txt') as f:\n\t\tfor line, prevlines in search(f, 'python', 3):\n\t\t\tfor pline in prevlines:\n\t\t\t\tprint(pline, end='')\n\t\t\t\tprint(line, end='')\n\t\t\t\tprint('-' * 20)","sub_path":"deque.py","file_name":"deque.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"195354532","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\n#import pickle\nimport json\nfrom django.http import JsonResponse\nimport psycopg2 as ps\nimport os\nfrom urllib import parse\n\nfrom .models import Greeting\n\n# Create your views here.\n@csrf_exempt\ndef index(request):\n\te=''\n\n\tfor i in request.POST.keys():\n\t\te+=i+': '+request.POST[i]+ '\\n'\n\n\n\treturn HttpResponse(e)\n\n\ndef db(request):\n\n greeting = Greeting()\n greeting.save()\n\n greetings = Greeting.objects.all()\n\n return render(request, 'db.html', {'greetings': greetings})\n\n### Helper functions\n\ndef conv_to_int_if_possible(arrr):\n\tfor i in range(len(arrr)):\n\t\tif type(arrr[i]) == str:\n\t\t\ttry:\n\t\t\t\tarrr[i] = int(arrr[i])\n\t\t\texcept:\n\t\t\t\tcontinue\n\n##### METHODS\n\ndef process_request_create(req):\n\ttry:\n\t\tspl = req.split(';')\n\t\tlength = len(spl)\n\t\tto_chg = ','.join([i.split('=')[0] for i in req.split(';')])\n\t\ts_es = ','.join(['%s' for i in range(length)])\n\t\tvals = [i.split('=')[1] for i in req.split(';')]\n\t\tfor i in range(len(vals)):\n\t\t\tif '<' in vals[i] and '>' in vals[i]:\n\t\t\t\tvals[i] = vals[i][vals[i].find('<')+1:vals[i].find('>')].split(',')\n\t\t\telif type(vals[i]) == str:\n\t\t\t\ttry:\n\t\t\t\t\tvals[i] = int(vals[i])\n\t\t\t\texcept:\n\t\t\t\t\tcontinue\n\t\treturn [0,to_chg,s_es,vals] \n\texcept:\n\t\treturn [1]\n\ndef process_request_update(req):\n\ttry:\n\t\tspl = req.split(';')\n\t\tidd=-1\n\t\tfor i in range(len(spl)):\n\t\t\tif 'id' in spl[i]:\n\t\t\t\tidd = spl[i].split('=')[1]\n\t\t\t\tidi=i\n\t\tdel spl[idi]\n\n\t\tlength = len(spl)\n\t\tto_chg = '=%s,'.join([i.split('=')[0] for i in spl]) +'=%s'\n\t\tvals = [i.split('=')[1] for i in spl]\n\t\tfor i in range(len(vals)):\n\t\t\tif '<' in vals[i] and '>' in vals[i]:\n\t\t\t\tvals[i] = vals[i][vals[i].find('<')+1:vals[i].find('>')].split(',')\n\t\t\telif type(vals[i]) == str:\n\t\t\t\ttry:\n\t\t\t\t\tvals[i] = int(vals[i])\n\t\t\t\texcept:\n\t\t\t\t\tcontinue\n\n\n\t\treturn [0,to_chg,idd,vals] \n\texcept:\n\t\treturn [1]\n\ndef process_request_update(req):\n\ttry:\n\t\tspl = req.split(';')\n\n\t\tlength = len(spl)\n\t\tto_chg = '=%s,'.join([i.split('=')[0] for i in spl]) +'=%s'\n\t\tvals = [i.split('=')[1] for i in spl]\n\t\tfor i in range(len(vals)):\n\t\t\tif '<' in vals[i] and '>' in vals[i]:\n\t\t\t\tvals[i] = vals[i][vals[i].find('<')+1:vals[i].find('>')].split(',')\n\t\t\telif type(vals[i]) == str:\n\t\t\t\ttry:\n\t\t\t\t\tvals[i] = int(vals[i])\n\t\t\t\texcept:\n\t\t\t\t\tcontinue\n\n\n\t\treturn [0,to_chg,vals] # Convert to ints only for the first depth\n\texcept:\n\t\treturn [1]\n\ndef process_request_delete(req):\n\ttry:\n\t\tspl = req.split(';')\n\t\tidd=-1\n\t\tfor i in range(len(spl)):\n\t\t\tif 'id' in spl[i]:\n\t\t\t\tidd = spl[i].split('=')[1]\n\t\treturn [0,idd] # Convert to ints only for the first depth\n\texcept:\n\t\treturn [1]\n\ndef make_request_forward(req_str, vals):\n\tparse.uses_netloc.append(\"postgres\")\n\turl = parse.urlparse(os.environ[\"DATABASE_URL\"])\n\n\tconn = ps.connect(\n\t database=url.path[1:],\n\t user=url.username,\n\t password=url.password,\n\t host=url.hostname,\n\t port=url.port\n\t)\n\n\tcur=conn.cursor()\n\tcur.execute(req_str, vals)\n\tconn.commit()\n\tconn.close()\n\n\treturn JsonResponse({'success':1, 'answer':'OK', 'error_code':-1})\n\n\ndef make_request_backward(req_str, vals):\n\tparse.uses_netloc.append(\"postgres\")\n\turl = parse.urlparse(os.environ[\"DATABASE_URL\"])\n\n\tconn = ps.connect(\n\t database=url.path[1:],\n\t user=url.username,\n\t password=url.password,\n\t host=url.hostname,\n\t port=url.port\n\t)\n\n\tcur=conn.cursor()\n\ttry:\n\t\tcur.execute(req_str, vals)\n\texcept:\n\t\treturn JsonResponse({'success':0, 'answer':'error: db error - request is wrong. Check out and make againg', 'error_code':5})\n\n\tout = cur.fetchall()\n\tconn.close()\n\n\treturn out\n\n\n\n\ndef db_create(obj, req):\n\tpred_request = process_request_create(req)\n\tif pred_request[0] == 1:\n\t\treturn JsonResponse({'success':0, 'answer':'error: wrong request content', 'error_code':4})\n\n\n\treq_str = 'INSERT INTO ' + obj + ' (' + pred_request[1] + ') VALUES(' + pred_request[2] + ');'\n\n\treturn make_request_forward(req_str,pred_request[3])\n\ndef db_update(obj, req):\n\tpred_request = process_request_update(req)\n\tif pred_request[0] == 1:\n\t\treturn JsonResponse({'success':0, 'answer':'error: wrong request content', 'error_code':4})\n\tif pred_request[2] == -1:\n\t\treturn JsonResponse({'success':0, 'answer':'error: wrong request content - no ID in request', 'error_code':6})\n\n\treq_str = 'UPDATE ' + obj + ' SET ' + pred_request[1] + ' WHERE id =' + '%s' + ';'\n\n\treturn make_request_forward(req_str,pred_request[3]+[pred_request[2]])\n\ndef db_delete(obj, req):\n\tpred_request = process_request_delete(req)\n\tif pred_request[0] == 1:\n\t\treturn JsonResponse({'success':0, 'answer':'error: wrong request content', 'error_code':4})\n\tif pred_request[1] == -1:\n\t\treturn JsonResponse({'success':0, 'answer':'error: wrong request content - no ID in request', 'error_code':6})\n\n\t# DELETE FROM songs WHERE id=18\n\treq_str = 'DELETE FROM ' + obj + ' WHERE id=' + '%s' + ';'\n\n\treturn make_request_forward(req_str,[pred_request[1]])\n\n# # Song: name\n# name: SELECT name, artist,featured,album,id FROM songs WHERE name='LVL';\n# id: SELECT name, artist,featured,album,id FROM songs WHERE id=15;\n# artist_name: SELECT name, artist,featured,album,id FROM songs WHERE artist='A$AP Rocky';\n\n# # Artist: name\n# name:\t\n# SELECT name,topsongs,id FROM artists WHERE name='A$AP Rocky';\n# SELECT name, year,image FROM albums WHERE artist='A$AP Rocky';\n\n# id:\n# SELECT name,topsongs,id FROM artists WHERE id=1;\n# SELECT name, year,image FROM albums WHERE artist=(SELECT name FROM artists WHERE id=1);\n\n\n# # Album: name\n# name: SELECT name,year, image FROM albums WHERE name='LONG.LIVE.A$AP';\n# artist: SELECT name,year, image FROM albums WHERE artist='A$AP Rocky';\n\n\n# Artist\n# SELECT name, topsongs,id FROM artists WHERE %KEY=%VAL;\n# SELECT name,year,image FROM albums WHERE artist=(SELECT name FROM artists WHERE %KEY=%VAL);\n# SELECT name, artist,featured,album FROM songs WHERE artist=(SELECT name FROM artists WHERE %KEY=%VAL);\n\n\n\ndef process_request_read(obj,req):\n\ttry:\n\t\tspl = req.split(';')\n\t\tlength = len(spl)\n\t\tto_chg = '=%s,'.join([i.split('=')[0] for i in spl]) +'=%s'\n\t\tvals = [i.split('=')[1] for i in spl]\n\t\tfor i in range(len(vals)):\n\t\t\tif '<' in vals[i] and '>' in vals[i]:\n\t\t\t\tvals[i] = vals[i][vals[i].find('<')+1:vals[i].find('>')].split(',')\n\t\t\telif type(vals[i]) == str:\n\t\t\t\ttry:\n\t\t\t\t\tvals[i] = int(vals[i])\n\t\t\t\texcept:\n\t\t\t\t\tcontinue\n\texcept:\n\t\treturn [1]\n\n\tresp = {}\n\n\tif obj == 'songs':\n\t\ts1 = '''SELECT name, artist,featured,album FROM songs WHERE {};'''.format(to_chg)\n\n\t\tresp['album'] = make_request_backward(s1, vals)\n\n\n\telif obj == 'albums':\n\t\ts1 = '''SELECT name,year,image FROM albums WHERE {};'''.format(to_chg)\n\t\ts2 = '''SELECT name, artist,featured,album FROM songs WHERE album=(SELECT name FROM albums WHERE {});'''.format(to_chg)\n\n\t\tresp['album'] = make_request_backward(s1, vals)\n\t\tresp['songs'] = make_request_backward(s2, vals)\n\n\telif obj == 'artists':\n\t\ts1 = '''SELECT name, topsongs,id FROM artists WHERE {};'''.format(to_chg)\n\t\ts2 = '''SELECT name,year,image FROM albums WHERE artist=(SELECT name FROM artists WHERE {});'''.format(to_chg)\n\t\ts3 = '''SELECT name, artist,featured,album FROM songs WHERE artist=(SELECT name FROM artists WHERE {});'''.format(to_chg)\n\n\t\tresp['artist'] = make_request_backward(s1, vals)\n\t\tresp['albums'] = make_request_backward(s2, vals)\n\t\tresp['songs'] = make_request_backward(s3, vals)\n\n\n\treturn resp\n\n\ndef db_read(obj, req):\n\tpred_request = process_request_read(obj,req)\n\t# if pred_request[0] == 1:\n\t# \treturn JsonResponse({'success':0, 'answer':'error: wrong request content', 'error_code':4})\n\n\treturn JsonResponse( {'success':1, 'answer':pred_request, 'error_code':-1})\n\n\n\n##### END METHODS\n\ndef req_handler(mthd, obj, req):\n\tmethods = {\n\t 'create': db_create,\n\t 'update': db_update,\n\t 'delete': db_delete,\n\t 'read': db_read\n\t}\n\n\t\n\treturn methods[mthd](obj,req)\n\n\n\n\n\n\n\n@csrf_exempt\ndef api(request):\n\tallowed_methods=['create','update','delete','read']\n\tallowed_objects=['songs','artists','albums']\n\n\tif request.method == \"POST\":\n\t\ttry:\n\t\t\tmethod = request.POST['method']\n\t\t\tobj = request.POST['object']\n\t\t\treq = request.POST['request']\n\t\texcept:\n\t\t\treturn JsonResponse({'success':0, 'answer':'error: not proper request keys. Look up API reference.', 'error_code':1})\n\n\t\tif method not in allowed_methods or obj not in allowed_objects:\n\t\t\treturn JsonResponse({'success':0, 'answer':'error: server error or wrong method, check out news on API website or API reference','error_code':2})\n\n\t\treturn req_handler(method, obj, req)\n\telse:\n\t\treturn JsonResponse({'success':0, 'answer':'error: wrong access method. Look up API reference.','error_code':0})\n\n\n\n\n","sub_path":"hello/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"568148635","text":"from astrofunc.Cosmo.nfw_param import NFWParam\nimport numpy as np\nimport numpy.testing as npt\nimport pytest\n\n\nclass TestHaloParam(object):\n\n def setup(self):\n self.haloParam = NFWParam()\n\n def test_profile_main(self):\n M = 10**13\n z = 0.5\n r200, rho0, c, Rs = self.haloParam.profileMain(M, z)\n print(r200, np.log10(rho0), c, Rs)\n assert c == 3.9209051266072716\n\n def test_c_rho(self):\n c_in = 4.\n rho0 = self.haloParam.rho0_c(c_in)\n c_out = self.haloParam.c_rho0(rho0)\n npt.assert_almost_equal(c_in, c_out, decimal=10)\n\n c_in = 1.\n rho0 = self.haloParam.rho0_c(c_in)\n c_out = self.haloParam.c_rho0(rho0)\n npt.assert_almost_equal(c_in, c_out, decimal=10)\n\n c_in = 9.\n rho0 = self.haloParam.rho0_c(c_in)\n c_out = self.haloParam.c_rho0(rho0)\n npt.assert_almost_equal(c_in, c_out, decimal=10)\n\n def test_mass2angle(self):\n M = 10**13\n z = 0.5\n #alpha (physical units)/ self.lensProp.sigma_crit / self.lensProp.dist_OL / constants.arcsec\n assert 0 == 0\n\n\nif __name__ == '__main__':\n pytest.main()","sub_path":"test/test_nfw_param.py","file_name":"test_nfw_param.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"249175125","text":"\"\"\"\n# =============================================================================\n# Creates the stiffness matrix as requested, using the material properties \n# provided in the TPD file (for v2020 files).\n#\n# Author: William Hunter, Tarcísio L. de Oliveira\n# Copyright (C) 2008, 2015, William Hunter.\n# Copyright (C) 2020, 2021, Tarcísio L. de Oliveira\n# =============================================================================\n\"\"\"\n\nfrom . import Q4_K, Q4bar_K\nfrom ..utils import get_logger\n\nlogger = get_logger(__name__)\n\n# ===========================================================\n# === Stiffness matrix of a square 4 node 'Q4a5B' element ===\n# ===========================================================\n# This element is based on the '5-beta' assumed stress element for plane\n# stress, but elemental parameters are introduced and selected such that\n# spurious zero energy modes are not introduced, for which an investigation\n# of characteristic equations of the elemental stiffness matrix is needed.\n# Element thickness set = 1. See De Klerk and Groenwold for details.\ndef create_K(_L, _E, _nu, _k, _t):\n logger.info('Generating K for Q4a5B...')\n logger.info('Q4a5B uses Q4 and Q4bar for its creation, so they will also be created...')\n\n # Symbolic value of alpha_opt for bending:\n alpha2D = (2 * _L**2 * (1 - _nu) * (2 * _nu**2 - _nu + 1)) \\\n / (3 * (_nu + 1) * _E**2)\n\n K_Q4, B_Q4, C_Q4 = Q4_K.create_K(_L, _E, _nu, _k, _t)\n K_Q4bar, B_Q4bar, C_Q4bar = Q4bar_K.create_K(_L, _E, _nu, _k, _t)\n\n # Stiffness matrix\n K = K_Q4 - alpha2D * _E * K_Q4bar\n # I'm not sure if this is correct\n B = B_Q4 - alpha2D * _E * B_Q4bar\n C = C_Q4 - alpha2D * _E * C_Q4bar\n\n logger.info(\"Created stiffness matrix for Q4a5B.\")\n return K, B, C\n","sub_path":"topy/data/Q4a5B_K.py","file_name":"Q4a5B_K.py","file_ext":"py","file_size_in_byte":1790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"295823816","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom grid_world import standard_grid, negative_grid\nfrom iterative_policy_evaluation import print_policy, print_values\nfrom monte_carlo_es import max_dict\nfrom td0_prediction import random_action\n\nGAMMA = 0.9\nALPHA = 0.1\nALL_POSSIBLE_ACTIONS = ('U', 'D', 'L', 'R')\nLEARNING_RATE = 0.001\n\nSA2IDX = {}\nIDX = 0\n\n\nclass SARSAModel:\n def __init__(self):\n self.theta = np.random.rand(25) / np.sqrt(25)\n\n def sa2x(self, s, a):\n return np.array([\n s[0] - 1 if a == 'U' else 0,\n s[1] - 1.5 if a == 'U' else 0,\n (s[0]*s[1] - 3)/3 if a == 'U' else 0,\n (s[0]*s[0] - 2)/2 if a == 'U' else 0,\n (s[1]*s[1] - 4.5)/4.5 if a == 'U' else 0,\n 1 if a == 'U' else 0,\n s[0] - 1 if a == 'D' else 0,\n s[1] - 1.5 if a == 'D' else 0,\n (s[0]*s[1] - 3)/3 if a == 'D' else 0,\n (s[0]*s[0] - 2)/2 if a == 'D' else 0,\n (s[1]*s[1] - 4.5)/4.5 if a == 'D' else 0,\n 1 if a == 'D' else 0,\n s[0] - 1 if a == 'L' else 0,\n s[1] - 1.5 if a == 'L' else 0,\n (s[0]*s[1] - 3)/3 if a == 'L' else 0,\n (s[0]*s[0] - 2)/2 if a == 'L' else 0,\n (s[1]*s[1] - 4.5)/4.5 if a == 'L' else 0,\n 1 if a == 'L' else 0,\n s[0] - 1 if a == 'R' else 0,\n s[1] - 1.5 if a == 'R' else 0,\n (s[0]*s[1] - 3)/3 if a == 'R' else 0,\n (s[0]*s[0] - 2)/2 if a == 'R' else 0,\n (s[1]*s[1] - 4.5)/4.5 if a == 'R' else 0,\n 1 if a == 'R' else 0,\n 1\n ])\n\n def predict(self, s, a):\n features = self.sa2x(s, a)\n return self.theta.dot(features)\n\n def grad(self, s, a):\n return self.sa2x(s, a)\n\n\ndef all_actions(s, model):\n Qs = {}\n for a in ALL_POSSIBLE_ACTIONS:\n q_sa = model.predict(s, a)\n Qs[a] = q_sa\n return Qs\n\nif __name__==\"__main__\":\n grid= negative_grid(step_cost=-0.1)\n\n print(\"reward\")\n print_values(grid.rewards, grid)\n\n #init approximated result table\n states = grid.all_states()\n for s in states:\n SA2IDX[s] = {}\n for a in ALL_POSSIBLE_ACTIONS:\n SA2IDX[s][a] = IDX\n IDX += 1\n\n t = 1.0\n t2 = 1.0\n deltas = []\n model = SARSAModel()\n for time in range(20000):\n if time % 100 == 0:\n t += 0.01\n t2 += 0.01\n if time % 2000 == 0:\n print(\"time: {0}\", time)\n alpha = ALPHA / t2\n s1 = (2,0)\n grid.set_state(s1)\n a1 = max_dict(all_actions(s1, model))[0]\n a1 = random_action(a1, eps=0.5/t)\n biggest_change = 0\n\n while not grid.game_over():\n r = grid.move(a1)\n s2 = grid.current_state()\n\n old_theta = model.theta.copy()\n\n if grid.is_terminal(s2):\n # grad is the same as features = model.sa2x(s1, a1)\n model.theta += alpha * (r - model.predict(s1, a1)) * model.grad(s1, a1)\n else:\n a2 = max_dict(all_actions(s2, model))[0]\n a2 = random_action(a2, eps=0.5/t)\n\n model.theta += alpha * (r + GAMMA * model.predict(s2, a2) - model.predict(s1, a1)) * model.grad(s1, a1)\n s1 = s2\n a1 = a2\n biggest_change = max(biggest_change, np.abs(old_theta - model.theta).sum())\n deltas.append(biggest_change)\n\n plt.plot(deltas)\n plt.show()\n\n # we don't use Q table, at least during training processes.\n policy = {}\n V = {}\n Q = {}\n for s in grid.actions.keys():\n Qs = all_actions(s, model)\n Q[s] = Qs\n a, max_result = max_dict(Qs)\n policy[s] = a\n V[s] = max_result\n print(\"values:\")\n print_values(V, grid)\n print(\"policy:\")\n print_policy(policy, grid)\n","sub_path":"olena_reinforsment_learning/approx_sarsa.py","file_name":"approx_sarsa.py","file_ext":"py","file_size_in_byte":3914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"441550172","text":"import sys\r\nsys.path.insert(1, '../')\r\nimport numpy as np\r\nimport tensorflow as tf \r\nfrom tensorflow.keras import Model\r\nimport config\r\nfrom tensorflow.keras.layers import (\r\n Conv2D, \r\n BatchNormalization,\r\n Activation,\r\n Input,\r\n Dropout, \r\n MaxPool2D, \r\n Flatten,\r\n Dense,\r\n Softmax\r\n)\r\n\r\ndef conv_block(x, filters, kernel_size, strides, training=True, name=\"unknow\", activation='relu', \r\n padding='same', batch_norm=True, drop_out=None, use_bias=True):\r\n \"\"\"\r\n make an conv block\r\n \"\"\"\r\n x = Conv2D(filters=filters, kernel_size=kernel_size, \r\n strides=strides, padding=padding, \r\n use_bias=use_bias, name=\"conv_layer_{}\".format(name)) (x)\r\n # if batch_norm:\r\n # x = BatchNormalization(name=\"batchnorm_layer_{}\".format(name)) (x, training)\r\n x = Activation(activation, name='{}_{}'.format(activation, name)) (x)\r\n if training:\r\n x = Dropout(0.3, name=\"dropout_{}\".format(name)) (x, training)\r\n return x\r\n\r\ndef max_pooling(x, pool_size=(2,2), strides=2, name=\"unknow\"):\r\n x = MaxPool2D(pool_size=pool_size, strides=strides, name='maxpool_{}'.format(name)) (x)\r\n return x\r\n\r\nclass TiniVgg(object):\r\n def __init__(self,\r\n input_size=config.INPUT_SIZE):\r\n self.input_size = input_size\r\n self.optimizer = tf.keras.optimizers.Adam\r\n\r\n def model(self, training=False):\r\n x = input_layer = Input([self.input_size, self.input_size, 3])\r\n\r\n x = conv_block(x, 32, 3, 1, training=training, name=\"1_1\")\r\n x = conv_block(x, 32, 3, 1, training=training, name=\"1_2\")\r\n x = max_pooling(x, name=\"1\")\r\n\r\n x = conv_block(x, 64, 3, 1, training=training, name=\"2_1\")\r\n x = conv_block(x, 64, 3, 1, training=training, name=\"2_2\")\r\n x = max_pooling(x, name=\"2\")\r\n\r\n # x = conv_block(x, 64, 3, 1, training=training, name=\"3_1\")\r\n # x = conv_block(x, 64, 3, 1, training=training, name=\"3_2\")\r\n # x = conv_block(x, 64, 1, 1, training=training, name=\"3_3\")\r\n # x = max_pooling(x, name=\"3\")\r\n\r\n # x = conv_block(x, 128, 3, 1, training=training, name=\"4_1\")\r\n # x = conv_block(x, 128, 3, 1, training=training, name=\"4_2\")\r\n # x = conv_block(x, 128, 1, 1, training=training, name=\"4_3\")\r\n # x = max_pooling(x, name=\"4\")\r\n\r\n # x = conv_block(x, 128, 3, 1, training=training, name=\"5_1\")\r\n # x = conv_block(x, 128, 3, 1, training=training, name=\"5_2\")\r\n # x = conv_block(x, 128, 1, 1, training=training, name=\"5_3\")\r\n x = max_pooling(x, name=\"5\")\r\n\r\n x = Flatten() (x)\r\n x = Dense(1024, activation='relu', use_bias=True, name=\"dense_1\") (x)\r\n x = Dense(1024, activation='relu', use_bias=True, name='dense_2') (x)\r\n x = Dense(1, activation='sigmoid', use_bias=True, name='dense_3') (x)\r\n # x = Activation('sigmoid') (x)\r\n\r\n return Model(input_layer, x, name=\"tiniVgg\")\r\n\r\n def optimizer(self):\r\n return self.optimizer\r\n\r\n def load_weights(self, weight_file):\r\n self.model.load_weights(weight_file)\r\n print(\"weights loaded\")\r\n\r\nif __name__=='__main__':\r\n model = TiniVgg().model(training=False)\r\n model.summary()\r\n ","sub_path":"car_classification/classification/model_04/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"16571369","text":"#!/usr/bin/env python3\n\"\"\"\n\n Author: Matthew Collyer (matthewcollyer@bennington.edu)\n Date:\n\"\"\"\nimport web\nimport random\nfrom pymongo import MongoClient\n\nrender = web.template.render('templates/')\n\nurls = (\n '/doodle/(.*)', 'answer',\n '/doodle', 'doodle'\n\n)\n\napp = web.application(urls, globals())\nclass doodle:\n def POST(self):\n return render.doodle(get_doodle())\nclass answer:\n def POST(self, url):\n my_input=web.input()\n guess=my_input.guess\n correct=True\n dood=get_doodle(int(url))\n if(guess.lower()!=dood['word'].lower()):\n correct=False\n update_table(int(url), guess,correct)\n return render.answer(dood,correct)\n\n\ndef get_doodle(key_id=None):\n \"\"\"\n\n \"\"\"\n try:\n client = MongoClient('localhost') # get our client\n db = client.quickdraw # get our database\n if(key_id==None): #if random\n total=db.qd.count()\n rando=random.randint(1,total)\n doodle=db.qd.find_one({'key_id':rando})\n else:\n doodle=db.qd.find_one({'key_id':key_id})\n\n return doodle\n except Exception as e:\n print(\"Unable to connect to database: {0}\".format(e))\n\ndef update_table(key_id,guess,correct):\n \"\"\"\n Updates the d-\n if wrong: adds guess\n if right: adds +1 for right guesses\n\n \"\"\"\n try:\n client = MongoClient('localhost') # get our client\n db = client.quickdraw # get our database\n if(correct==False):\n db.qd.update_one({'key_id':key_id},{'$push': {'human_guesses': guess}})\n else:\n db.qd.update_one({'key_id':key_id},{'$inc':{'recognized_by_human': 1}})\n except Exception as e:\n print(\"Unable to connect to database: {0}\".format(e))\n\n\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"Final/quickdraw.py","file_name":"quickdraw.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"554808732","text":"import tkinter as tk\n\nmainWindow = tk.Tk()\nmainWindow.title(\"RadioButtons_design\")\n\nvar = tk.IntVar()\nvar.set(0) #initializing the choice\n\nprogrammingLanguages = [\n (\"Python\",1),\n (\"Perl\",2),\n (\"C++\",3),\n (\"C#\",4),\n (\"Java\",5),\n (\"JavaScript\",6)\n]\n\ndef showChoice():print(var.get())\n\ntk.Label(mainWindow,text=\"Wähle eine Programmiersprache\",\n font=(\"Hellevtiva\",14),justify = tk.LEFT,\n padx = 20).pack(fill=\"none\",ipady=10)\n\nfor val, language in enumerate (programmingLanguages):\n tk.Radiobutton(mainWindow,\n text=language,\n indicatoron=0,\n width=40,\n padx=20,\n variable=var,\n command=showChoice,\n value=val).pack(anchor=tk.W)\n\nmainWindow.mainloop()\n","sub_path":"tkinter/radioButtons_design.py","file_name":"radioButtons_design.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"56460295","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom dataset import MNISTDataset, Cifar10Dataset\nfrom model import *\n\nfrom scipy.spatial.distance import cdist\nfrom matplotlib import gridspec\n\nflags = tf.app.flags\nFLAGS = flags.FLAGS\nflags.DEFINE_string('model_test', 'mnist', 'model to run')\nflags.DEFINE_string('checkpoint_path', 'model/model.ckpt', 'model checkpoint path')\nflags.DEFINE_integer('retrieved_images', 7, 'number of retrieved images')\n\n# Helper function to plot image\ndef show_image(idxs, data):\n if type(idxs) != np.ndarray:\n idxs = np.array([idxs])\n fig = plt.figure()\n gs = gridspec.GridSpec(1,len(idxs))\n for i in range(len(idxs)):\n ax = fig.add_subplot(gs[0,i])\n ax.imshow(data[idxs[i],:,:,0])\n ax.axis('off')\n plt.show()\n\nif __name__ == \"__main__\":\n if FLAGS.model_test == 'mnist':\n dataset = MNISTDataset()\n img_placeholder = tf.placeholder(tf.float32, [None, 28, 28, 1], name='img')\n model = mnist_model\n elif FLAGS.model_test == 'cifar10':\n dataset = Cifar10Dataset()\n img_placeholder = tf.placeholder(tf.float32, [None, 32, 32, 3], name='img')\n model = cifar10_model\n else:\n raise NotImplementedError(\"Model for %s is not implemented yet\" % FLAGS.model)\n\n test_images = dataset.images_test\n labels_test = dataset.labels_test\n labels_name = dataset.labels_name\n len_test = len(test_images)\n\n # Create the siamese net feature extraction model\n net = model(img_placeholder, reuse=False)\n\n # Restore from checkpoint and calculate the features from all of train data\n saver = tf.train.Saver()\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n ckpt = tf.train.get_checkpoint_state(\"model\")\n saver.restore(sess, FLAGS.checkpoint_path)\n feats = sess.run(net, feed_dict={img_placeholder:test_images[:10000]}) \n\n # Searching for similar test images from trainset based on siamese feature\n # Generate new random test image\n idx = np.random.randint(0, len_test)\n im = test_images[idx]\n\n # Show the test image\n print(\"Image id:\", idx)\n print(\"Image label:\", labels_name[labels_test[idx]])\n show_image(idx, test_images)\n\n # Run the test image through the network to get the test features\n saver = tf.train.Saver()\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n ckpt = tf.train.get_checkpoint_state(\"model\")\n saver.restore(sess, FLAGS.checkpoint_path)\n search_feat = sess.run(net, feed_dict={img_placeholder:[im]})\n \n # Calculate the cosine similarity and sort\n dist = cdist(feats, search_feat, 'cosine')\n rank = np.argsort(dist.ravel())\n\n # Show the top n similar image from train data\n n = FLAGS.retrieved_images\n print(\"Retrieved ids:\", rank[:n])\n print(\"Retrieved labels:\", list(map(lambda x: labels_name[x], labels_test[rank[:n]])))\n show_image(rank[:n], test_images)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"2617981","text":"from collections import deque\n\nfrom shared.TreeNode import TreeNode\n\n\nclass Solution:\n def kthSmallest(self, root: TreeNode, k: int) -> int:\n # res, _ = recursive(root, k)\n # return res\n return iterative(root, k)\n\n\ndef iterative(root: TreeNode, k: int) -> int:\n # 52 ms\t17.7 MB\n if not root:\n return -1\n\n stack = [root]\n is_traversed = False\n while len(stack) != 0:\n node = stack[-1]\n while node.left and not is_traversed:\n stack.append(node.left)\n node = node.left\n\n node = stack.pop()\n k -= 1\n if k == 0:\n return node.val\n\n if node.right:\n stack.append(node.right)\n is_traversed = False\n else:\n is_traversed = True\n\n return -1\n\n\ndef recursive(root: TreeNode, k: int) -> tuple:\n # 56 ms\t17.7 MB\n if not root:\n return None, k\n\n left_result, k = recursive(root.left, k)\n if left_result is not None:\n return left_result, 0\n\n k -= 1\n if k == 0:\n return root.val, 0\n\n return recursive(root.right, k)\n","sub_path":"python/230.py","file_name":"230.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"383180470","text":"# -*- coding: utf-8 -*-\n\nimport simple_draw as sd\n\n_coordinates = []\n_over_screen = []\n\n\ndef add_snowflake(quantity):\n for _ in range(quantity):\n _coordinates.append([sd.random_number(0, sd.resolution[0]), sd.random_number(0, sd.resolution[1]),\n sd.random_number(10, 50)])\n\n\ndef draw_snowflake(color):\n for item in _coordinates:\n if color is None:\n _color = (sd.random_number(0, 255), sd.random_number(0, 255), sd.random_number(0, 255))\n else:\n _color = color\n point = sd.get_point(x=item[0], y=item[1])\n sd.snowflake(center=point, color=_color, length=item[2])\n\n\ndef step_snowflake():\n for item in _coordinates:\n item[1] -= sd.random_number(10, 20)\n item[0] += sd.random_number(-5, 5)\n\n\ndef snowflake_over_screen():\n _over_screen.clear()\n for i, item in enumerate(_coordinates):\n if item[1] + item[2] < 0:\n _over_screen.append(i)\n _over_screen.reverse()\n\n\ndef del_snowflake(over_screen):\n for item in over_screen:\n del _coordinates[item]\n","sub_path":"lesson_006/snowfall.py","file_name":"snowfall.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"90482217","text":"class SegTree:\n \"\"\" define what you want to do with 0 index, ex) size = tree_size, func = min or max, sta = default_value \"\"\"\n \n def __init__(self,size,func,sta):\n self.n = size\n self.size = 1 << size.bit_length()\n self.func = func\n self.sta = sta\n self.tree = [sta]*(2*self.size)\n\n def build(self, list):\n \"\"\" set list and update tree\"\"\"\n for i,x in enumerate(list,self.size):\n self.tree[i] = x\n\n for i in range(self.size-1,0,-1):\n self.tree[i] = self.func(self.tree[i<<1],self.tree[i<<1 | 1])\n\n def set(self,i,x):\n i += self.size\n self.tree[i] = x\n while i > 1:\n i >>= 1\n self.tree[i] = self.func(self.tree[i<<1],self.tree[i<<1 | 1])\n\n \n def get(self,l,r):\n \"\"\" take the value of [l r) with func (min or max)\"\"\"\n l += self.size\n r += self.size\n res = self.sta\n\n while l < r:\n if l & 1:\n res = self.func(self.tree[l],res)\n l += 1\n if r & 1:\n res = self.func(self.tree[r-1],res)\n l >>= 1\n r >>= 1\n return res\n\n def max_right(self, l, x):\n \"\"\"[l,r) が ok であるような最大の r を返す\"\"\"\n if l == self.n:\n return l\n l += self.size\n res = self.sta\n check = True\n while check or (l & -l) != l:\n check = False\n while l%2 == 0:\n l >>= 1\n if not self.func(res,self.tree[l]) < x:\n while l < self.size:\n l <<= 1\n if self.func(res,self.tree[l]) < x:\n res = self.func(res,self.tree[l])\n l += 1\n return l - self.size\n res = self.func(res,self.tree[l])\n l += 1\n return self.n\n\n def min_left(self, r, x):\n \"\"\"(r が ok であるような最小の r を返す probably wrong\"\"\"\n if r == 0:\n return 0\n r += self.size\n res = self.sta\n check = True\n while check and (r & -r) != r:\n check = False\n r -= 1\n while (r > 1 and r%2):\n r >>= 1\n if not self.func(res, self.tree[r]) < x:\n while r < self.size:\n r = 2*r + 1\n if self.func(res, self.tree[r]) < x:\n res = self.func(res, self.tree[r])\n r -= 1\n return r + 1 - self.size\n res = self.func(self.tree[r],res)\n return 0\n\n\nn,k = map(int,input().split())\nM = 3*10**5+5\ntree = SegTree(M,max,0)\nfor i in range(n):\n a = int(input())\n x = tree.get(max(0,a-k),min(a+k+1,M))\n tree.set(a,x+1)\n\nprint(tree.get(0,M))\n","sub_path":"atcoder/abc/acl/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":2823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"391773674","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\nimport cv2\r\nimport numpy as np\r\nimport time\r\n\r\n\r\n# Setup SimpleBlobDetector parameters.\r\nparams = cv2.SimpleBlobDetector_Params()\r\n# Change thresholds\r\nparams.minThreshold = 0\r\nparams.maxThreshold = 256\r\nparams.thresholdStep = 10\r\n# Filter by Color.\r\nparams.filterByColor = False\r\n# Filter by Area.\r\nparams.filterByArea = True\r\nparams.minArea = 10000\r\nparams.maxArea = 200000\r\n# Filter by Circularity\r\nparams.filterByCircularity = False\r\nparams.minCircularity = 0.5\r\n# Filter by Convexity\r\nparams.filterByConvexity = False\r\nparams.minConvexity = 0.5\r\n# Filter by Inertia\r\nparams.filterByInertia = False\r\nparams.minInertiaRatio = 0.5\r\n\r\ncount = 0 #计数用\r\n\r\ndef track(cap):\r\n\txc = 0\r\n\tyc = 0\r\n\r\n\tret, frame = cap.read()\r\n\t# # show orignal \r\n\t# cv2.imshow('frame', frame) \r\n\t# cv2.waitKey(10)\r\n\t# sp = frame.shape\r\n\t# print sp \r\n\r\n\t# b, g, r = cv2.split(frame) #color separation\r\n\t# cv2.imshow(\"image_r\", r)\r\n\t# cv2.imshow(\"image_g\", g)\r\n\t# cv2.imshow(\"image_b\", b)\r\n\t# frame = cv2.medianBlur(frame, 5) #中值滤波\r\n\r\n\t# img_yellow = cv2.inRange(frame,(0,200,200),(100,255,255))\r\n\timg_red = cv2.inRange(frame,(30,30,190),(160,140,255))\r\n\r\n\t# rgb to gray\r\n\t# gary = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\r\n\t# cv2.imshow(\"gary\",gary)\r\n\t# cv2.waitKey(10)\r\n\r\n\t# rgb to hsv\r\n\timg_hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)\r\n\t# cv2.imshow(\"hsv\",img_hsv)\r\n\t# cv2.waitKey(10)\r\n\r\n\timg_yellow = cv2.inRange(img_hsv,(26,43,46),(34,255,255))\r\n\t# img_red1 = cv2.inRange(img_hsv,(0,43,46),(10,255,255))\r\n\t# img_red2 = cv2.inRange(img_hsv,(156,43,46),(180,255,255))\r\n\t# img_red = img_red1+img_red2\r\n\t# img_green = cv2.inRange(img_hsv,(43,43,46),(70,255,255))\r\n\r\n\tcv2.imshow(\"img_yellow\",img_yellow)\r\n\tcv2.waitKey(1)\r\n\tcv2.imshow(\"img_red\",img_red)\r\n\tcv2.waitKey(1)\r\n\t# cv2.imshow(\"img_green\",img_green)\r\n\t# cv2.waitKey(10)\r\n\r\n\tdetector = cv2.SimpleBlobDetector_create(params)\r\n\t# Detect blobs\r\n\tkeypoints = detector.detect(img_red)\r\n\t# print(keypoints)\r\n\r\n\tfor kp in keypoints :\r\n\t\txc = kp.pt[0]\r\n\t\tyc = kp.pt[1]\r\n\r\n\tif (xc==0)&(yc==0):\r\n\t\tkeypoints = detector.detect(img_yellow)\r\n\t\t# print(keypoints)\r\n\r\n\t\tfor kp in keypoints :\r\n\t\t\t# point = kp.pt\r\n\t\t\txc = kp.pt[0]\r\n\t\t\tyc = kp.pt[1]\r\n\t\t\t# print(point)\r\n\r\n\tim_with_keypoints = cv2.drawKeypoints(frame,keypoints,np.array([]),(255,0,0),cv2.DRAW_MATCHES_FLAGS_DEFAULT)\r\n\tim_with_keypoints = cv2.drawKeypoints(im_with_keypoints,keypoints,np.array([]),(255,0,0),cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\r\n\r\n\tcv2.imshow(\"Keypoints\",im_with_keypoints)\r\n\tcv2.waitKey(1)\r\n\r\n\r\n\treturn xc,yc\r\n\r\n","sub_path":"src/abb_irb120_track/scripts/camera_track.py","file_name":"camera_track.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"86017221","text":"import pandas as pd\nimport numpy as np\nimport h5py\nimport time\nimport hpat\nfrom hpat import prange\n\n# adopted from:\n# http://www.pythonforfinance.net/2017/02/20/intraday-stock-mean-reversion-trading-backtest-in-python/\n\n\n@hpat.jit(locals={'s_open': hpat.float64[:], 's_high': hpat.float64[:],\n 's_low': hpat.float64[:], 's_close': hpat.float64[:],\n 's_vol': hpat.float64[:]})\ndef intraday_mean_revert():\n file_name = \"stock_data_all_google.hdf5\"\n f = h5py.File(file_name, \"r\")\n sym_list = list(f.keys())\n nsyms = len(sym_list)\n max_num_days = 4000\n all_res = np.zeros(max_num_days)\n\n t1 = time.time()\n for i in prange(nsyms):\n symbol = sym_list[i]\n\n s_open = f[symbol + '/Open'][:]\n s_high = f[symbol + '/High'][:]\n s_low = f[symbol + '/Low'][:]\n s_close = f[symbol + '/Close'][:]\n s_vol = f[symbol + '/Volume'][:]\n df = pd.DataFrame({'Open': s_open, 'High': s_high, 'Low': s_low,\n 'Close': s_close, 'Volume': s_vol, })\n\n # create column to hold our 90 day rolling standard deviation\n df['Stdev'] = df['Close'].rolling(window=90).std()\n\n # create a column to hold our 20 day moving average\n df['Moving Average'] = df['Close'].rolling(window=20).mean()\n\n # create a column which holds a TRUE value if the gap down from previous day's low to next\n # day's open is larger than the 90 day rolling standard deviation\n df['Criteria1'] = (df['Open'] - df['Low'].shift(1)) < -df['Stdev']\n\n # create a column which holds a TRUE value if the opening price of the stock is above the 20 day moving average\n df['Criteria2'] = df['Open'] > df['Moving Average']\n\n # create a column that holds a TRUE value if both above criteria are also TRUE\n df['BUY'] = df['Criteria1'] & df['Criteria2']\n\n # calculate daily % return series for stock\n df['Pct Change'] = (df['Close'] - df['Open']) / df['Open']\n\n # create a strategy return series by using the daily stock returns where the trade criteria above are met\n df['Rets'] = df['Pct Change'][df['BUY']]\n\n n_days = len(df['Rets'])\n res = np.zeros(max_num_days)\n if n_days:\n res[-n_days:] = df['Rets'].fillna(0).values\n all_res += res\n\n f.close()\n print(all_res.mean())\n print(\"execution time:\", time.time() - t1)\n\n\nintraday_mean_revert()\n","sub_path":"tutorial/intraday_mean.py","file_name":"intraday_mean.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"153793552","text":"import sys \n\ndef usage(): \n\tprint(\"usage : python3 format_circular_gff.py \") \n\t\nif len(sys.argv)!=2: \n\tusage()\n\texit() \n\t\ngff=open(sys.argv[1],\"r\") \n\ndic_length={}\nfor l in gff : \n\tl_split=l.split(\"\\t\")\n\tif l.startswith(\"##sequence-region\"):\n\t\tl_split=l.rstrip().split(\" \") \n\t\tif \"_circ\" in l_split[1]: \n\t\t\tdic_length[l_split[1]]=int(l_split[3])-1000\n\t\t\tprint(\" \".join(l_split[:3])+\" \"+str(int(l_split[3])-1000)) \n\t\telse: \n\t\t\tprint(l.rstrip()) \t\n\telif len(l_split)==9: \n\t\tif \"_circ\" in l_split[0]: \n\t\t\tif int(l_split[3]), , \nDate: <20/10/2018>\n\"\"\"\nimport csv\nimport math\nimport random\nfrom visualise import show_vegetation_type\nfrom visualise import show_vegetation_density\nfrom visualise import show_wind_speed\nfrom visualise import show_bushfire\nfrom visualise import show_fire_risk\n\n\n# The following functions must return the data in the form of a\n# list of lists; the choice of data type to represent the value\n# in each cell, for each file type, is up to you.\n\ndef load_vegetation_type(filename):\n \"\"\"Load the vegetation_type file and returns a list of lists\"\"\"\n return load_csv(filename)\n\n\ndef load_vegetation_density(filename):\n \"\"\"Load the vegetation_density file and returns a list of lists\"\"\"\n return load_csv(filename)\n\n\ndef load_wind_speed(filename):\n \"\"\"Load the wind speed file and returns a list of lists\"\"\"\n return load_csv(filename)\n\n\ndef load_bushfire(filename):\n \"\"\"Load the bushfire file and returns a list of lists\"\"\"\n return load_csv(filename)\n\n\ndef load_csv(filename):\n \"\"\"This function can load the CSV files and return a list of lists.\n\n filename: string\n \"\"\"\n with open(filename) as csvfile:\n reader = csv.reader(csvfile)\n table = [row for row in reader]\n csvfile.close()\n return table\n\n\n# The argument to this function is a wind speed map, in the\n# form of a list of lists; it is the same data structure that\n# is returned by your implementation of the load_wind_speed\n# function.\n\ndef highest_wind_speed(wind_speed_map):\n \"\"\"Returns the highest wind speed as float.\n wind_speed_map: a list of lists\n \"\"\"\n highest_lst = []\n for row in wind_speed_map:\n highest_lst.append(max(row))\n return float(max(highest_lst))\n\n\n# The argument to this function is a vegetation type map, in the\n# form of a list of lists; it is the same data structure that\n# is returned by your implementation of the load_vegetation_type\n# function.\n\n\ndef count_cells(vegetation_type):\n \"\"\"Print the number of cells of each kind of vegetation.\n vegetation_type: a list of lists\n Note : The result will only contain types appear in the table.\n \"\"\"\n cells_dict = {}\n for row in vegetation_type:\n for element in row:\n if element != '':\n if element in cells_dict:\n cells_dict[element] += 1\n else:\n cells_dict[element] = 1\n for k in cells_dict:\n print(k, ':', cells_dict[k])\n\n\n# The arguments to this function are a vegetation type map and\n# a vegetation density map, both in the form of a list of lists.\n# They are the same data structure that is returned by your\n# implementations of the load_vegetation_type and load_vegetation_density\n# functions, respectively.\n\n\ndef count_area(vegetation_type, vegetation_density):\n \"\"\"Print the area of each kind of vegetation.\n vegetation_type: a list of lists\n vegetation_density: a list of lists\n Note : The result will only contain types appear in the table.\n \"\"\"\n area_dict = {}\n cell_area = 100 * 100\n for i in range(len(vegetation_type)):\n j = 0\n for element in vegetation_type[i]:\n if element != '':\n if element in area_dict:\n area_dict[element] += cell_area * \\\n float(vegetation_density[i][j])\n else:\n area_dict[element] = cell_area * \\\n float(vegetation_density[i][j])\n j += 1\n for k in area_dict:\n print(k + ': ' + '{:.2f}'.format(area_dict[k]) + 'sq m')\n\n\n# The arguments to this function are:\n# x and y - integers, representing a position in the grid;\n# vegetation_type - a vegetation type map (as returned by your\n# implementation of the load_vegetation_type function);\n# vegetation_density - a vegetation density map (as returned by\n# your implementation of the load_vegetation_density function);\n# wind_speed - a wind speed map (as returned by your implementation\n# of the load_wind_speed function).\n\ndef fire_risk(x, y, vegetation_type, vegetation_density, wind_speed):\n \"\"\"Calculate the fire risk for a cell.\n\n x,y: the index (col,row) of a cell.\n vegetation_type, vegetation_density, wind_speed: lists of lists.\"\"\"\n factor = 0\n if wind_speed[y][x] == '' or math.floor(float(wind_speed[y][x])) == 0:\n return fire_risk_factor(x, y, vegetation_type, vegetation_density)\n\n else:\n nearby = math.floor(float(wind_speed[y][x]))\n row_upper = min([len(wind_speed), y + nearby + 1]) # upper bound of the row index range\n row_lower = max([0, y - nearby])\n col_upper = min([len(wind_speed[y]), x + nearby + 1]) # upper bound of the column index range\n col_lower = max([0, x - nearby])\n for y1 in range(row_lower, row_upper):\n for x1 in range(col_lower, col_upper):\n if abs(x1 - x) + abs(y1 - y) <= nearby:\n factor += fire_risk_factor(x1, y1, vegetation_type, vegetation_density)\n return factor\n\n\ndef fire_risk_factor(x, y, vegetation_type, vegetation_density):\n \"\"\"Return the fire risk factor for a single cell.\n\n x,y:the index of a cell.\n vegetation_type, vegetation_density: lists of lists.\n \"\"\"\n if vegetation_type[y][x] == '':\n return 0\n elif vegetation_type[y][x] == 'Shrubland' or vegetation_type[y][x] == 'Pine Forest':\n a = 0.2\n elif vegetation_type[y][x] == 'Arboretum':\n a = 0.1\n elif vegetation_type[y][x] == 'Urban Vegetation' or vegetation_type[y][x] == 'Golf Course':\n a = 0.05\n else:\n a = 0\n return math.sqrt(a + float(vegetation_density[y][x]))\n\n\n# The arguments to this function are an initial bushfire map (a list\n# of lists, as returned by your implementation of the load_bushfire\n# function), a vegetation type map (as returned by your implementation\n# of the load_vegetation_type function), a vegetation density map (as\n# returned by your implementation of load_vegetation_density) and a\n# positive integer, representing the number of steps to simulate.\n\ndef simulate_bushfire(initial_bushfire, vegetation_type, vegetation_density, steps):\n \"\"\"A simple simulation of the spread of a bushfire for a number of steps.\n This function returns a list of lists.\n\n initial_bushfire, vegetation_type, vegetation_density: lists of lists.\n steps: a positive integer.\n \"\"\"\n new_bushfire = [row[:] for row in initial_bushfire]\n while steps > 0:\n fire_source = [] # a list contains the indices of fire cells\n for y in range(len(new_bushfire)):\n for x in range(len(new_bushfire[y])):\n if new_bushfire[y][x] == '1':\n fire_source.append([y, x])\n\n for index in fire_source:\n y, x = index[0], index[1]\n row_upper = min([len(new_bushfire), y + 2]) # upper bound of the row index range\n row_lower = max([0, y - 1])\n col_upper = min([len(new_bushfire[y]), x + 2]) # upper bound of the column index range\n col_lower = max([0, x - 1])\n\n for i in range(row_lower, row_upper):\n for j in range(col_lower, col_upper):\n if new_bushfire[i][j] == '0':\n new_bushfire[i][j] = '1'\n steps -= 1\n return new_bushfire\n\n\n# The arguments to this function are two bushfile maps (each a list\n# of lists, i.e., same format as returned by your implementation of\n# the load_bushfire function).\n\ndef compare_bushfires(bushfire_a, bushfire_b):\n \"\"\"Return the percentage of cells that are the same of two bushfire maps.\n\n bushfire_a, bushfire_b: lists of lists.\n Note: bushfire_a and bushfire_b has the same number of cells.\n \"\"\"\n same_cells = 0\n all_cells = 0 # the number of non-blank cells of either one table\n\n for i in range(len(bushfire_b)):\n for j in range(len(bushfire_b[i])):\n if bushfire_b[i][j] != '':\n all_cells += 1\n if bushfire_b[i][j] == bushfire_a[i][j]:\n same_cells += 1\n return same_cells / all_cells\n\n\n# The arguments to this function are:\n# initial_bushfire - an initial bushfile map (a list of lists, same\n# as returned by your implementation of the load_bushfire function);\n# steps - a positive integer, the number of steps to simulate;\n# vegetation_type - a vegetation type map (as returned by your\n# implementation of the load_vegetation_type function);\n# vegetation_density - a vegetation density map (as returned by\n# your implementation of the load_vegetation_density function);\n# wind_speed - a wind speed map (as returned by your implementation\n# of the load_wind_speed function).\n\ndef simulate_bushfire_stochastic(\n initial_bushfire, steps,\n vegetation_type, vegetation_density,\n wind_speed):\n \"\"\"This function stochastically simulates fire spreading for a number\n of steps. It returns a list of lists.\n\n initial_bushfire, vegetation_type, vegetation_density, wind_speed: lists of lists\n steps: a positive integer\n \"\"\"\n risk_factor = [] # A list contains fire risk factors of all cells\n for i in range(len(vegetation_type)):\n for j in range(len(vegetation_type[i])):\n risk_factor.append(fire_risk(j, i, vegetation_type,\n vegetation_density, wind_speed))\n min_factor = min(risk_factor)\n max_factor = max(risk_factor)\n new_bushfire = [row[:] for row in initial_bushfire]\n\n while steps > 0:\n fire_source = [] # A list contains indices of fire cells\n for y in range(len(new_bushfire)):\n for x in range(len(new_bushfire[y])):\n if new_bushfire[y][x] == '1':\n fire_source.append([y, x])\n\n for index in fire_source:\n y, x = index[0], index[1]\n row_upper = min([len(new_bushfire), y + 2]) # upper bound of the row index range\n row_lower = max([0, y - 1])\n col_upper = min([len(new_bushfire[y]), x + 2]) # upper bound of the column index range\n col_lower = max([0, x - 1])\n\n for i in range(row_lower, row_upper):\n for j in range(col_lower, col_upper):\n if new_bushfire[i][j] == '0':\n random_factor = random.uniform(min_factor, max_factor)\n risk = fire_risk(j, i, vegetation_type,\n vegetation_density, wind_speed)\n if risk >= random_factor:\n new_bushfire[i][j] = '1'\n steps -= 1\n return new_bushfire\n\n\nif __name__ == '__main__':\n # If you want something to happen when you run this file,\n # put the code in this `if` block.\n pass\n","sub_path":"Course Learning/project/data_and_code/assignment.py","file_name":"assignment.py","file_ext":"py","file_size_in_byte":10890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"40794184","text":"__author__ = 'vincent'\r\nclass Solution(object):\r\n def minPathSum(self, grid):\r\n \"\"\"\r\n :type grid: List[List[int]]\r\n :rtype: int\r\n aggr_row 是一个一个更新的, 所以 当计算 第 i 个 的时候, 第 aggr_row[i-1] 个就是它左边那个, 而 在计算前\r\n 那个 aggr_row[i]就是当前的上面的那个,因为现在还没有更新呢。 所以可以只用 O(n)的空间, so smart\r\n \"\"\"\r\n aggr_row = [0] + [1e10] * (len(grid[0])-1)\r\n for curr_row in grid:\r\n for i in xrange(len(grid[0])):\r\n aggr_row[i] = curr_row[i] + min(aggr_row[i-1] if i > 0 else aggr_row[i], aggr_row[i])\r\n return aggr_row[-1]\r\n\r\n\r\n \"\"\"\r\n # O(1) space solution, very similar to the solution below, have to modify the given matrix.\r\n m = len(grid)\r\n n = len(grid[0])\r\n\r\n if m < 2 or n < 2: return sum([sum(i) for i in grid])\r\n\r\n for i in xrange(1,m):\r\n grid[i][0] += grid[i-1][0]\r\n for i in xrange(1,n):\r\n grid[0][i] += grid[0][i-1]\r\n\r\n for i in xrange(1,m):\r\n for j in xrange(1,n):\r\n grid[i][j] += grid[i-1][j] if grid[i-1][j] < grid[i][j-1] else grid[i][j-1]\r\n\r\n return grid[-1][-1]\r\n \"\"\"\r\n\r\n\r\n \"\"\"\r\n # java O(m*n) space 解法,非常easy.\r\n public int minPathSum(int[][] grid) {\r\n if (grid == null || grid.length == 0) return 0;\r\n\r\n int row = grid.length;\r\n int col = grid[0].length;\r\n\r\n int[][] sumArray = new int[row][col];\r\n sumArray[0][0] = grid[0][0];\r\n\r\n for(int i = 1; i < row; i++){\r\n sumArray[i][0] = sumArray[i-1][0] + grid[i][0];\r\n }\r\n\r\n for(int i = 1; i < col; i++){\r\n sumArray[0][i] = sumArray[0][i-1] + grid[0][i];\r\n }\r\n\r\n for(int i = 1; i < row; i++){\r\n for(int j = 1; j < col; j++){\r\n if(sumArray[i][j-1] > sumArray[i-1][j]) sumArray[i][j] = grid[i][j] + sumArray[i-1][j];\r\n else sumArray[i][j] = grid[i][j] + sumArray[i][j-1];\r\n }\r\n }\r\n\r\n return sumArray[row-1][col-1];\r\n }\r\n \"\"\"","sub_path":"64_Minimum Path Sum.py","file_name":"64_Minimum Path Sum.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"462915185","text":"# -*- coding: utf-8 -*-\n\nimport logging\nimport re\n\nfrom polaris_health import Error, ProtocolError, MonitorFailed\nfrom polaris_health.protocols.tcp import TCPSocket\nfrom . import BaseMonitor\n\n__all__ = [ 'TCP' ]\n\nLOG = logging.getLogger(__name__)\nLOG.addHandler(logging.NullHandler())\n\n# use up to this num of bytes from a response\nMAX_RESPONSE_BYTES = 512\n\n# maximum allowed length of match_re parameter\nMAX_MATCH_RE_LEN = 128\n\n# maximum allowed length of send_string parameter\nMAX_SEND_STRING_LEN = 256\n\nclass TCP(BaseMonitor):\n\n \"\"\"TCP monitor base\"\"\"\n\n def __init__(self, port, send_string=None, match_re=None,\n interval=10, timeout=2, retries=2):\n \"\"\"\n args:\n port: int, port number\n send_string: string, a string to send to the socket,\n before reading a response\n match_re: string, a regular expression to search for in a response\n\n Other args as per BaseMonitor() spec\n\n \"\"\"\n super(TCP, self).__init__(interval=interval, timeout=timeout,\n retries=retries)\n\n ### port ###\n self.port = port\n if not isinstance(port, int) or port < 1 or port > 65535:\n log_msg = ('port \"{}\" must be an integer between 1 and 65535'.\n format(port))\n LOG.error(log_msg)\n raise Error(log_msg)\n\n ### match_re ###\n self.match_re = match_re\n self._match_re_compiled = None\n if self.match_re is not None:\n if not isinstance(match_re, str) \\\n or len(match_re) > MAX_MATCH_RE_LEN:\n log_msg = ('match_re \"{}\" must be a string, {} chars max'.\n format(match_re, MAX_MATCH_RE_LEN))\n LOG.error(log_msg)\n raise Error(log_msg)\n \n # compile regexp obj to use for matching\n try:\n self._match_re_compiled = re.compile(self.match_re, flags=re.I)\n except Exception as e:\n log_msg = ('failed to compile a regular '\n 'expression from \"{}\", {}'\n .format(self.match_re, e))\n LOG.error(log_msg)\n raise Error(log_msg)\n\n ### send_string ###\n self.send_string = send_string\n self._send_bytes = None\n if send_string is not None:\n if not isinstance(send_string, str) \\\n or len(send_string) > MAX_SEND_STRING_LEN:\n log_msg = ('send_string \"{}\" must be a string, {} chars max'.\n format(send_string, MAX_SEND_STRING_LEN))\n LOG.error(log_msg)\n raise Error(log_msg)\n\n # convert to bytes for sending over network\n self._send_bytes = self.send_string.encode()\n\n def run(self, dst_ip):\n \"\"\"\n Connect a tcp socket \n If we have a string to send, send it to the socket\n If have a regexp to match, read response and match the regexp\n\n args:\n dst_ip: string, IP address to connect to\n\n returns:\n None\n\n raises:\n MonitorFailed() on a socket operation timeout/error or if failed\n match the regexp.\n\n \"\"\"\n tcp_sock = TCPSocket(ip=dst_ip, port=self.port, timeout=self.timeout)\n\n # connect socket, send string if required\n try:\n tcp_sock.connect()\n if self.send_string is not None:\n tcp_sock.sendall(self._send_bytes)\n except ProtocolError as e:\n raise MonitorFailed(e)\n\n # if we have nothing to match, close the socket and return\n if self.match_re is None:\n tcp_sock.close()\n return\n\n # we have a regexp to match, read response, perform matching\n try:\n response_bytes = tcp_sock.receive()\n except ProtocolError as e:\n raise MonitorFailed(e)\n else:\n # close the socket\n tcp_sock.close()\n\n # decode up to MAX_RESPONSE_BYTES\n response_text = response_bytes[:MAX_RESPONSE_BYTES].decode()\n \n # match regexp\n if not self._match_re_compiled.search(response_text):\n raise MonitorFailed('failed to match the reg exp')\n\n","sub_path":"polaris_health/monitors/tcp.py","file_name":"tcp.py","file_ext":"py","file_size_in_byte":4359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"523379103","text":"'''\nAutomated testing for discovery-app\n > python tests.py\nor > nosetests tests\n'''\nimport difflib\nimport json\nimport os\nimport unittest\n\nimport requests\nfrom nose.tools import eq_, ok_\nfrom tornado.testing import AsyncHTTPTestCase\nfrom tornado.web import Application, create_signed_value\nfrom torngithub import json_encode\n\nfrom biothings.utils.common import ask\nfrom config import COOKIE_SECRET\nfrom elasticsearch_dsl import Index\nfrom index import WEB_SETTINGS\nfrom web.api.es import Metadata, Schema\n\nFORCE_TEST = False\n\n\nclass DiscoveryAppAPITest(AsyncHTTPTestCase):\n ''' The tester will start its own tornado server '''\n __test__ = True\n\n HOST = os.getenv(\"DISCOVERY_HOST\", \"\").rstrip('/')\n API_ENDPOINT = '/api'\n HOST += API_ENDPOINT\n\n def get_app(self):\n return Application(WEB_SETTINGS.generate_app_list(), cookie_secret=COOKIE_SECRET)\n\n # Setup and Teardown\n\n @classmethod\n def setUpClass(cls):\n\n cls.index = Index(Schema.Index.name)\n\n if cls.index.exists():\n if FORCE_TEST or ask('Current indexed documents will be permenantely lost.') == 'Y':\n cls.index.delete()\n else:\n exit()\n\n # create new index as defined in Schema class\n Schema.init()\n\n # test dataset\n cls.testset = []\n\n # add a document\n url = 'https://raw.githubusercontent.com/namespacestd0/mygene.info/master/README.md'\n meta = Metadata(username='namespacestd', slug='dev', url=url)\n schema = Schema(clses=['biothings', 'smartapi'],\n props=['es-dsl'], _meta=meta)\n schema.save()\n cls.testset.append(schema)\n\n # add another document\n url = ('https://raw.githubusercontent.com/data2health/'\n 'schemas/biothings/biothings/biothings_curie.jsonld')\n meta = Metadata(username='data2health', slug='d2h', url=url)\n schema = Schema(clses=['biothings'], _meta=meta)\n schema.save()\n cls.testset.append(schema)\n\n @classmethod\n def tearDownClass(cls):\n pass\n\n # Helper functions\n\n def get_status_code(self, url, status_code):\n ''' make a GET request and return the response body if the status codes match '''\n res = self.fetch(url)\n assert res.code == status_code, \"status {} != {} for GET to url: {}\".format(\n res.code, status_code, url)\n return res.body\n\n def post_status_code(self, url, body, status_code):\n ''' make an authenticated POST request and return json if the status codes match '''\n cookie_name, cookie_value = 'user', {'login':'tester'}\n secure_cookie = create_signed_value(\n COOKIE_SECRET,\n cookie_name,\n json_encode(cookie_value))\n headers = {'Content-type': 'application/x-www-form-urlencoded',\n 'Cookie': '='.join((cookie_name, secure_cookie.decode()))}\n res = self.fetch(url, method='POST',\n body=json.dumps(body), headers=headers)\n assert res.code == status_code, \"status {} != {} for url: {}\\nparams: {}\".format(\n res.code, status_code, url, body)\n return res.body\n\n def get_json_ok(self, url):\n ''' make a GET request and return json if server responds okay '''\n return json.loads(self.get_status_code(url, 200))\n\n def post_json_ok(self, url, data):\n ''' make a POST request and return json if server responds okay '''\n return json.loads(self.post_status_code(url, data, 200))\n\n def query_has_hits(self, query_keyword, endpoint='query'):\n ''' make a GET request to a query endpoint and assert positive hits '''\n dic = self.get_json_ok(\n self.HOST + '/' + endpoint + '?q=' + query_keyword)\n ok_(dic.get('total', 0) > 0)\n ok_(dic.get('hits', []))\n return dic\n\n def query_has_no_hits(self, query_keyword, endpoint='query'):\n ''' make a GET request to a query endpoint and assert positive hits '''\n dic = self.get_json_ok(\n self.HOST + '/' + endpoint + '?q=' + query_keyword)\n ok_(dic.get('total') == 0)\n ok_(dic.get('hits') == [])\n return dic\n \n # Tests\n\n def test_01_es_basics(self):\n ''' requires ONLY es server\n asserts es stores given doc\n asserts doc url encodes to _id\n asserts es retrives given doc by _id '''\n sch = Schema.get(id=self.testset[0].meta.id)\n eq_(sch.to_dict(), self.testset[0].to_dict())\n\n def test_02_es_raw_field(self):\n ''' requires ONLY es server\n asserts schema doc encodes to compressed bytes\n asserts decoding restores original doc '''\n sch = Schema.get(id=self.testset[1].meta.id)\n encoded = sch.encode_raw()\n assert encoded == sch['~raw'], difflib.SequenceMatcher(\n a=encoded, b=sch['~raw']).get_opcodes()\n\n decoded = sch.decode_raw()\n original = requests.get(sch['_meta'].url).text\n eq_(decoded, original)\n\n def test_03_handlers_query_return_all(self):\n ''' asserts special query parameter __all__ is functional '''\n self.query_has_hits(query_keyword='__all__')\n\n def test_04_handlers_query_meta_slug(self):\n ''' asserts _meta.slug field is searchable '''\n self.query_has_hits(query_keyword='_meta.slug:dev')\n\n def test_05_handlers_registry_get(self):\n ''' asserts get request to registry retrives documents\n acknowledges timestamp will not be in datetime format in res'''\n res = self.get_json_ok(self.HOST+'/registry/'+self.testset[0].meta.id)\n eq_(res['_meta']['url'], self.testset[0].to_dict()['_meta']['url'])\n\n def test_06_handlers_registry_post(self):\n ''' asserts props and clses (p&c) are optional,\n asserts p&c take both str and list,\n asserts update to existing doc works '''\n doc_1 = {'url': 'http://example.com/',\n 'slug': 'com',\n 'props': 'ebay'}\n doc_2 = {'url': 'http://example.org/',\n 'slug': 'org',\n 'props': ['cvs'],\n 'clses': ['costco', 'MTS']}\n ok_(self.post_json_ok(self.HOST+'/registry', data=doc_1)['success'])\n ok_(self.post_json_ok(self.HOST+'/registry', data=doc_2)['success'])\n self.query_has_hits(query_keyword='MTS')\n doc_2['slug'] = 'us'\n self.post_json_ok(self.HOST+'/registry', data=doc_2)\n self.query_has_hits(query_keyword='_meta.slug:us')\n\n def test_07_handlers_registry_delete(self):\n ''' asserts delete a document by its _id '''\n self.query_has_hits(query_keyword='es-dsl')\n self.fetch(self.HOST+'/registry/'+self.testset[0].meta.id, method='DELETE')\n self.query_has_no_hits(query_keyword='es-dsl')\n\nif __name__ == '__main__':\n try:\n unittest.main()\n except SystemExit:\n pass\n","sub_path":"src/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":6915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"475873839","text":"import math\n\n\nf = open(\"liczby.txt\")\nlines = f.readlines()\n\nmaxi = 0\nfor i in range(200):\n wzp = True\n for j in range(200):\n if i != j:\n if math.gcd(int(lines[i]), int(lines[j])) != 1:\n wzp = False\n break\n if wzp and int(lines[i]) > maxi:\n maxi = int(lines[i])\n\nprint(maxi)\n\nf.close()\n","sub_path":"zbiór inf/Coding/60/60-3.py","file_name":"60-3.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"238869128","text":"#!/usr/bin/env python3\n# updated : 01-15-2019\n\nimport argparse\nimport os\nimport sys\nimport urllib.request\n\ntry:\n from bs4 import BeautifulSoup\nexcept ModuleNotFoundError:\n print(\"module bs4 not found\")\n print(\"try : pip3 install bs4\")\n exit()\ntry:\n from pytube import YouTube\nexcept ModuleNotFoundError:\n print(\"module pytube not found\")\n print(\"try : pip3 install pytube\")\n exit()\n\n\ndoes_path_exists = (\n lambda path_variable: True if os.path.exists(path_variable) else False\n)\ndoes_file_exists = lambda file_path: True if os.path.isfile(file_path) else False\n\n\ndef get_playlist_url(playlist_url):\n \"\"\"\n\treturn list of video's ulr in playlist_url\n\t\"\"\"\n\n result = []\n\n req = urllib.request.Request(playlist_url)\n response = urllib.request.urlopen(req)\n soup = BeautifulSoup(response, \"html.parser\")\n\n for i in soup.find_all(\"a\"):\n if \"watch\" in i[\"href\"]:\n result.append(i[\"href\"])\n\n result = [\"https://youtube.com\" + i for i in result]\n return set(result)\n\n\ndef DownloadVideo(url, path=os.getcwd()):\n \"\"\"\n\tmain function used to download videos\n\turl : youtube url.\n\tpath : download folder.\n\t\"\"\"\n\n print(\"[*] Connecting to youtube ....\")\n myvideo = YouTube(url)\n\n # downloading the video\n print(\"Video Title : \", myvideo.title)\n print(\"[*] Downloading ...\")\n\n mystream = (\n myvideo.streams.first()\n ) # download with first quality in the list, not necessarly the best quality\n mystream.download(path)\n\n print(\"[+]FINISHED\")\n\n\nif __name__ == \"__main__\":\n\n download_folder = None\n video_url = None\n playlist_url = None\n file_path = None\n\n # getting args from command line\n parser = argparse.ArgumentParser(description=\"download videos from youtube\")\n parser.add_argument(\"path\", nargs=1, help=\"download folder\")\n args_group = parser.add_mutually_exclusive_group(required=True)\n args_group.add_argument(\n \"-f\", \"--file\", nargs=1, help=\"urls stored on file line by line\"\n )\n args_group.add_argument(\"-u\", \"--url\", nargs=1, help=\"video url\")\n args_group.add_argument(\"-play\", \"--playlist\", nargs=1, help=\"youtube playlist url\")\n args = parser.parse_args()\n\n # check validity of command line args\n if does_path_exists(args.path[0]):\n download_folder = args.path[0]\n else:\n print(\"download folder doesnt exists : {}\".format(args.path[0]))\n exit()\n if args.file:\n if does_path_exists(args.file[0]):\n file_path = args.file[0]\n else:\n print(\"file doesnt exists : {}\".format(args.file[0]))\n exit()\n if args.url:\n video_url = args.url[0]\n\n if args.playlist:\n playlist_url = args.playlist[0]\n\n # perform actions (downloading) based on user args\n if video_url:\n DownloadVideo(video_url, download_folder)\n exit()\n\n if playlist_url:\n print(\"retreiving urls from playlist ....\")\n for video in get_playlist_url(playlist_url):\n try:\n DownloadVideo(video, download_folder)\n except:\n print(\"This video cannot be downloaded\")\n pass\n exit()\n\n if file_path:\n with open(file_path) as file:\n for line in file:\n video = line.rstrip(\"\\n\")\n DownloadVideo(video, download_folder)\n\n exit()\n","sub_path":"python/youtube_downloader.py","file_name":"youtube_downloader.py","file_ext":"py","file_size_in_byte":3380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"529372652","text":"import pandas as pd\n\nfrom regla import RuleAction, RuleActionResult, RuleActionLog, RuleActionTargetType, RuleActionPreference, RuleActionReportColumn, RuleReportColumn, RuleContext, RuleMultiplierAction, RuleNoAction, RuleActionAdjustmentType\nfrom regla.errors import RuleActionMissingTargetError\nfrom hazel import GoogleAdsAPI, GoogleAdsCampaignPauseMutator, GoogleAdsCampaignTargetCPAMutator, GoogleAdsCampaignBudgetMutator, GoogleAdsReporter\nfrom datetime import datetime, timedelta\nfrom pytz import timezone\nfrom typing import Callable, List, Tuple, Dict, Optional\nfrom bson import ObjectId\nfrom .google_ads_context import GoogleAdsOption, GoogleAdsColumn, add_report_time\n\nclass GoogleAdsAction(RuleAction):\n @property\n def raw_entity_id_column(self) -> str:\n granularity = self.entity_granularity\n if granularity is RuleActionTargetType.campaign:\n return 'campaign_id'\n elif granularity is RuleActionTargetType.adgroup:\n return 'ad_group_id'\n else:\n raise ValueError('Unsupported entity granularity', granularity)\n\n @property\n def raw_entity_name_column(self) -> str:\n granularity = self.entity_granularity\n if granularity is RuleActionTargetType.campaign:\n return 'campaign_name'\n elif granularity is RuleActionTargetType.adgroup:\n return 'ad_group_name'\n else:\n raise ValueError('Unsupported entity granularity', granularity)\n\n @property\n def action_report_columns(self) -> List[str]:\n return [\n *super().action_report_columns,\n *[c.value for c in GoogleAdsColumn],\n ]\n\n @property \n def preferences_title(self) -> str:\n return 'UAC best practices'\n\n def get_raw_action_report(self, entity_ids: List[str], api: GoogleAdsAPI, report: pd.DataFrame, context: any) -> pd.DataFrame:\n reporter = GoogleAdsReporter(api=api)\n action_report = reporter.get_safety_report(\n entity_granularity=self.entity_granularity.value,\n entity_ids=entity_ids\n )\n return action_report\n\n def map_action_report(self, action_report: pd.DataFrame, context: any):\n action_report.rename(lambda s: s.replace('#', '_'), axis='columns', inplace=True)\n assert len(action_report.customer_time_zone.unique()) == 1\n time_zone = action_report.customer_time_zone.iloc[0]\n action_report.campaign_start_date = pd.to_datetime(action_report.campaign_start_date).dt.tz_localize(tz=time_zone, ambiguous='infer')\n action_report[RuleActionReportColumn.target_id.value] = action_report[self.raw_entity_id_column].astype(str)\n action_report[RuleActionReportColumn.target_name.value] = action_report[self.raw_entity_name_column]\n\n def supplement_action_report(self, action_report: pd.DataFrame, api: GoogleAdsAPI, context: any) -> pd.DataFrame:\n action_report = super().supplement_action_report(\n action_report=action_report,\n api=api,\n context=context\n )\n if context[RuleContext.rule_options.value][GoogleAdsOption.wait_days.value] <= 0:\n return action_report\n reporter = GoogleAdsReporter(api=context[RuleContext.channel.value].api)\n conversions_report_start_date = context[RuleContext.now.value] - timedelta(days=context[RuleContext.rule_options.value][GoogleAdsOption.wait_days.value])\n conversions_report = reporter.get_selected_conversions_report(\n start_date=conversions_report_start_date,\n end_date=context[RuleContext.now.value],\n entity_ids=list(action_report[RuleActionReportColumn.target_id.value]),\n entity_granularity=self.entity_granularity.value,\n time_granularity='hourly'\n )\n conversions_report.rename(lambda s: s.replace('#', '_'), axis='columns', inplace=True)\n action_report[GoogleAdsColumn.wait_metrics_since_time.value] = datetime(conversions_report_start_date.year, conversions_report_start_date.month, conversions_report_start_date.day, conversions_report_start_date.hour)\n action_report[GoogleAdsColumn.wait_conversions.value] = 0\n action_report[GoogleAdsColumn.wait_optimized_conversions.value] = 0\n\n add_report_time(report=conversions_report)\n def add_wait_metrics(entity_series: pd.Series):\n action_type_history = list(filter(lambda h: h['adjustmentType'] == self.adjustment_type.value, entity_series[RuleActionReportColumn.history.value]))\n if action_type_history:\n last_action = sorted(action_type_history, key=lambda h: h['historyCreationDate'])[-1]\n entity_series[GoogleAdsColumn.last_adjustment_time.value] = last_action['historyCreationDate']\n if entity_series[GoogleAdsColumn.last_adjustment_time.value] >= entity_series[GoogleAdsColumn.wait_metrics_since_time.value]:\n entity_series[GoogleAdsColumn.wait_metrics_since_time.value] = entity_series[GoogleAdsColumn.last_adjustment_time.value]\n entity_series[GoogleAdsColumn.last_adjustment_description.value] = f'adjustment by {\"this rule\" if str(last_action[\"ruleID\"]) == context[RuleContext.rule.value]._id else \"rule \" + last_action[\"ruleDescription\"] + \" [\" + str(last_action[\"ruleID\"]) + \"]\"}'\n if conversions_report.empty:\n return\n location = conversions_report.loc[(conversions_report[self.raw_entity_id_column].astype(str) == entity_series[RuleActionReportColumn.target_id.value]) & (conversions_report.time >= entity_series[GoogleAdsColumn.wait_metrics_since_time.value])]\n entity_series[GoogleAdsColumn.wait_conversions.value] = location.total_conversions.sum()\n entity_series[GoogleAdsColumn.wait_optimized_conversions.value] = location.selected_conversions.sum()\n self.entity_apply(\n action_report=action_report,\n transformer=add_wait_metrics\n )\n return action_report\n \nclass GoogleAdsCampaignAction(GoogleAdsAction):\n @property\n def entity_granularity(self) -> RuleActionTargetType:\n return RuleActionTargetType.campaign\n\n def set_action_report_preferences(self, action_report: pd.DataFrame, api: any, context: any):\n location = action_report.loc[pd.isna(action_report[RuleActionReportColumn.error.value])]\n options = context[RuleContext.rule_options.value]\n # TODO: remove these testing overrides\n # options[GoogleAdsOption.wait_days.value] = 0.001\n # options[GoogleAdsOption.wait_conversions.value] = 10000\n # options[GoogleAdsOption.wait_optimized_conversions.value] = 3000\n wait_start_date = context[RuleContext.now.value] - timedelta(days=options[GoogleAdsOption.wait_days.value])\n wait_location = location.loc[location[GoogleAdsColumn.wait_metrics_since_time.value] > wait_start_date]\n wait_location = wait_location.loc[wait_location[GoogleAdsColumn.wait_conversions.value] < options[GoogleAdsColumn.wait_conversions.value]]\n wait_location = wait_location.loc[wait_location[GoogleAdsColumn.wait_optimized_conversions.value] < options[GoogleAdsColumn.wait_optimized_conversions.value]]\n self.add_preference(\n action_report=action_report,\n location=wait_location,\n preference=RuleActionPreference.prevent_adjustment,\n message_callback=lambda entity_series: f'Before adjusting campaign wait for one of {(context[RuleContext.now.value] - entity_series[GoogleAdsColumn.wait_metrics_since_time.value]).total_seconds() / 60 / 60 / 24 :0.2f} / {options[GoogleAdsOption.wait_days.value]} days or {int(entity_series[GoogleAdsColumn.wait_conversions.value])} / {options[GoogleAdsOption.wait_conversions.value]} converions or {int(entity_series[GoogleAdsColumn.wait_optimized_conversions.value])} / {options[GoogleAdsOption.wait_optimized_conversions.value]} optimized conversions{f\" since {entity_series[GoogleAdsColumn.last_adjustment_description.value]} at {entity_series[GoogleAdsColumn.last_adjustment_time.value]} UTC\" if entity_series[GoogleAdsColumn.last_adjustment_description.value] is not None else \"\"}'\n )\n\n def get_raw_action_report(self, entity_ids: List[str], api: GoogleAdsAPI, report: pd.DataFrame, context: any) -> pd.DataFrame:\n assert len(entity_ids) == 1\n assert entity_ids[0] == context['campaign_id']\n return super().get_raw_action_report(\n entity_ids=entity_ids,\n api=api,\n report=report,\n context=context\n )\n\nclass GoogleAdsPauseCampaignAction(GoogleAdsCampaignAction):\n @property\n def adjustment_type(self) -> RuleActionAdjustmentType:\n return RuleActionAdjustmentType.status\n\n def map_action_report(self, action_report: pd.DataFrame, context: any):\n super().map_action_report(\n action_report=action_report,\n context=context\n )\n action_report[RuleActionReportColumn.unadjusted_state.value] = action_report.campaign_status\n\n def entity_adjustment(self, entity_series: str, context: any) -> any:\n return None if entity_series[RuleActionReportColumn.unadjusted_state.value] == 'PAUSED' else 'PAUSED'\n\n def action_description(self, entity_series: str, context: any) -> str:\n return 'paused campaign'\n\n def entity_request(self, entity_series: pd.Series, api: GoogleAdsAPI, context: any) -> Optional[any]:\n return True\n\n def mutate_entity(self, entity_series: pd.Series, api: GoogleAdsAPI, context: any) -> Optional[any]:\n mutator = GoogleAdsCampaignPauseMutator(\n api=api,\n campaign_id=entity_series[RuleActionReportColumn.target_id.value]\n )\n raw_response = mutator.mutate()\n response = api.response_to_record(response=raw_response)\n return response\n\nclass GoogleAdsCampaignMultiplierAction(GoogleAdsCampaignAction, RuleMultiplierAction):\n @property\n def relative_adjustment_limit(self) -> float:\n return 0.2\n\n def supplement_action_report(self, action_report: pd.DataFrame, api: GoogleAdsAPI, context: any) -> pd.DataFrame:\n action_report = super().supplement_action_report(\n action_report=action_report,\n api=api,\n context=context\n )\n\n one_day_ago = datetime.utcnow() - timedelta(days=1)\n def add_prehistoric_state(entity_series: pd.Series):\n recent_history = sorted(filter(lambda h: h['historyCreationDate'] > one_day_ago and h['adjustmentType'] == self.adjustment_type.value, entity_series[RuleActionReportColumn.history.value]), key=lambda h: h['historyCreationDate'])\n entity_series[RuleActionReportColumn.prehistoric_state.value] = recent_history[0]['adjustmentFrom'] if recent_history else entity_series[RuleActionReportColumn.unadjusted_state.value]\n self.entity_apply(\n action_report=action_report,\n transformer=add_prehistoric_state\n )\n return action_report\n\n def set_action_report_preferences(self, action_report: pd.DataFrame, api: any, context: any):\n super().set_action_report_preferences(\n action_report=action_report,\n api=api,\n context=context\n )\n location = action_report.loc[pd.isna(action_report[RuleActionReportColumn.error.value])]\n def modify_adjustment(entity_series: pd.Series):\n if entity_series[RuleActionReportColumn.prehistoric_state.value] == 0:\n return\n current_relative_adjustment = entity_series[RuleActionReportColumn.unadjusted_state.value] / entity_series[RuleActionReportColumn.prehistoric_state.value]\n relative_adjustment = entity_series[RuleActionReportColumn.adjustment.value] / entity_series[RuleActionReportColumn.prehistoric_state.value]\n # if the current state is already adjusted at least to the limit, and we would adjust in the same direction\n if abs(current_relative_adjustment - 1) >= self.relative_adjustment_limit and (current_relative_adjustment - 1) * (relative_adjustment - 1) > 0:\n entity_series[RuleActionReportColumn.preference.value] = RuleActionPreference.prevent_adjustment\n entity_series[RuleActionReportColumn.preference_messages.value].append(f'Limit 1 day adjustment to {self.relative_adjustment_limit :0.0%}% of {entity_series[RuleActionReportColumn.prehistoric_state.value] :0.2f} (already {abs(current_relative_adjustment - 1) :0.0%} at {entity_series[RuleActionReportColumn.unadjusted_state.value] :0.2f})')\n return\n if abs(relative_adjustment - 1) > self.relative_adjustment_limit:\n entity_series[RuleActionReportColumn.preferred_adjustment.value] = (1 + self.relative_adjustment_limit if relative_adjustment > 1 else 1 - self.relative_adjustment_limit) * entity_series[RuleActionReportColumn.prehistoric_state.value]\n entity_series[RuleActionReportColumn.unpreferred_adjustment.value] = entity_series[RuleActionReportColumn.adjustment.value]\n if not entity_series[RuleActionReportColumn.override_preference.value]:\n entity_series[RuleActionReportColumn.adjustment.value] = entity_series[RuleActionReportColumn.preferred_adjustment.value]\n self.entity_apply(\n action_report=action_report,\n transformer=modify_adjustment,\n location=location.loc[(location[RuleActionReportColumn.prehistoric_state.value].notna()) & (location[RuleActionReportColumn.adjustment.value].notna())]\n )\n location = action_report.loc[pd.isna(action_report[RuleActionReportColumn.error.value])]\n self.add_preference(\n action_report=action_report,\n location=location.loc[location[RuleActionReportColumn.preferred_adjustment.value].notna()],\n preference=RuleActionPreference.modify_adjustment,\n message_callback=lambda e: f'Limit 1 day adjustment to {self.relative_adjustment_limit :0.0%} of {e[RuleActionReportColumn.prehistoric_state.value] :0.2f} ({e[RuleActionReportColumn.preferred_adjustment.value] :0.2f} instead of {e[RuleActionReportColumn.unpreferred_adjustment.value] :0.2f})'\n )\n\n def entity_adjustment(self, entity_series: pd.Series, context: any) -> Optional[any]:\n adjustment = super().entity_adjustment(\n entity_series=entity_series,\n context=context\n )\n if adjustment is None or int(adjustment * 1000000) == int(entity_series[RuleActionReportColumn.unadjusted_state.value] * 1000000):\n return None\n return adjustment\n\n def entity_request(self, entity_series: pd.Series, api: GoogleAdsAPI, context: any) -> Optional[any]:\n return True\n\nclass GoogleAdsTargetCPACampaignAction(GoogleAdsCampaignMultiplierAction):\n @property\n def adjustment_type(self) -> RuleActionAdjustmentType:\n return RuleActionAdjustmentType.cpa_goal\n\n def map_action_report(self, action_report: pd.DataFrame, context: any):\n super().map_action_report(\n action_report=action_report,\n context=context\n )\n assert 'campaign_bidding_strategy_type' in action_report.columns and action_report.campaign_bidding_strategy_type.unique() == ['TARGET_CPA'], 'Campaign bidding strategy type is not TARGET_CPA'\n action_report[RuleActionReportColumn.unadjusted_state.value] = action_report.campaign_target_cpa_target_cpa_micros.apply(lambda t: t / 1000000)\n assert action_report.campaign_target_cpa_target_cpa_micros.min() >= 0\n\n def action_description(self, entity_series: pd.Series, context: any):\n if int(entity_series[RuleActionReportColumn.adjustment.value] * 1000000) == int(entity_series[RuleActionReportColumn.unadjusted_state.value] * 1000000):\n return None\n return f'adjusted campaign target CPA from {entity_series[RuleActionReportColumn.unadjusted_state.value] :0.2f} to {entity_series[RuleActionReportColumn.adjustment.value] :0.2f}'\n\n def mutate_entity(self, entity_series: pd.Series, api: GoogleAdsAPI, context: any) -> Optional[any]:\n mutator = GoogleAdsCampaignTargetCPAMutator(\n api=api,\n campaign_id=entity_series[RuleActionReportColumn.target_id.value],\n target_cpa_micros=int(entity_series[RuleActionReportColumn.adjustment.value] * 1000000)\n )\n raw_response = mutator.mutate()\n response = api.response_to_record(response=raw_response)\n return response\n\nclass GoogleAdsCampaignBudgetAction(GoogleAdsCampaignMultiplierAction):\n @property\n def adjustment_type(self) -> RuleActionAdjustmentType:\n return RuleActionAdjustmentType.budget\n\n @property\n def precision(self) -> Optional[int]:\n return 2\n\n def map_action_report(self, action_report: pd.DataFrame, context: any):\n super().map_action_report(\n action_report=action_report,\n context=context\n )\n assert 'campaign_budget_type' in action_report.columns and action_report.campaign_budget_type.unique() == ['STANDARD'], 'Campaign budget type is not STANDARD'\n assert 'campaign_budget_status' in action_report.columns and action_report.campaign_budget_status.unique() == ['ENABLED'], 'Campaign budget status is not ENABLED'\n assert 'campaign_budget_period' in action_report.columns and action_report.campaign_budget_period.unique() == ['DAILY'], 'Campaign budget period is not DAILY'\n action_report[RuleActionReportColumn.unadjusted_state.value] = action_report.campaign_budget_amount_micros.apply(lambda t: t / 1000000)\n assert action_report.campaign_budget_amount_micros.min() >= 0\n\n def action_description(self, entity_series: pd.Series, context: any):\n if int(entity_series[RuleActionReportColumn.adjustment.value] * 1000000) == int(entity_series[RuleActionReportColumn.unadjusted_state.value] * 1000000):\n return None\n return f'adjusted campaign budget from {entity_series[RuleActionReportColumn.unadjusted_state.value] :0.2f} to {entity_series[RuleActionReportColumn.adjustment.value] :0.2f}'\n\n def mutate_entity(self, entity_series: pd.Series, api: GoogleAdsAPI, context: any) -> Optional[any]:\n mutator = GoogleAdsCampaignBudgetMutator(\n api=api,\n campaign_id=entity_series[RuleActionReportColumn.target_id.value],\n budget_micros=int(entity_series[RuleActionReportColumn.adjustment.value] * 1000000),\n budget_name=f'Rule [{context[RuleContext.rule.value]._id}] budget change from {entity_series[RuleActionReportColumn.unadjusted_state.value]} at {context[RuleContext.now.value]}'\n )\n raw_response = mutator.mutate()\n response = api.response_to_record(response=raw_response)\n return response\n\nclass GoogleAdsNoAction(GoogleAdsCampaignAction, RuleNoAction):\n def entity_adjustment(self, entity_series: pd.Series, context: any) -> Optional[any]:\n return None\n","sub_path":"development_packages/google_ads/regla_channels/google_ads/google_ads_actions.py","file_name":"google_ads_actions.py","file_ext":"py","file_size_in_byte":17905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"249519161","text":"import torch\nfrom torch import nn\n\nimport numpy as np\n\nfrom torch import FloatTensor as FloatTensor\nfrom torch import LongTensor as LongTensor\n\n# import our framework\nimport framework.modules as M\nimport framework.criterions as C\nimport framework.networks as N\n\nimport build_test as test\n\n# We generate 1000 points in (0,1) x (0,1) and label them 1 if they are inside\n# the circle with radius 1/sqrt(2 * pi), 0 otherwise. This is done for train and\n# target\nnpoints = 1000\ntrain_input, train_target, test_input, test_target = test.generate(npoints)\n\nmean, std = train_input.mean(), train_input.std()\n\n# We normalize the data according to mean and standard deviation\ntrain_input.sub_(mean).div_(std)\ntest_input.sub_(mean).div_(std)\n\nnsamples = npoints\nnfeatures = 2\nnchannels = 1\noutputs = 2\n\n# Simple net created with our framework\nclass SimpleNet(N.Sequential):\n def __init__(self,criterion):\n super(SimpleNet, self).__init__(criterion)\n # define modules (Pytorch style)\n self.fc1 = M.Linear(nchannels * nfeatures, 25)\n self.fc2 = M.Linear(25, 25)\n self.fc3 = M.Linear(25, outputs)\n self.nonlinear1 = M.ReLU()\n self.nonlinear2 = M.ReLU()\n\n # register the module \"in order\", so that the network is aware of which\n # node communicates with which\n super().registerModules(self.fc1, self.nonlinear1, self.fc2,self.nonlinear2,self.fc3)\n\n # forward step\n def forward(self, *input):\n x = input[0].view(-1, nchannels * nfeatures)\n x = self.fc1.forward(x)\n x = self.nonlinear1.forward(x)\n x = self.fc2.forward(x)\n x = self.nonlinear2.forward(x)\n x = self.fc3.forward(x)\n return x\n\n# compute the number of errors\ndef compute_number_errors(inputs,outputs):\n indicesy = np.argmax(inputs,1).float()\n indicesout = np.argmax(outputs,1).float()\n nberrors = np.linalg.norm(indicesy - indicesout,0)\n return nberrors\n\n# train the model using the stochastic gradient descent\ndef train_model(net,n_epochs,eta,mini_batch_size,train_input, train_target):\n for i in range(n_epochs):\n # at each epoch, we perform a permutation of the train_input and train_target\n perm = torch.randperm(npoints)\n train_input = train_input[perm]\n train_target = train_target[perm]\n loss = 0\n for b in range(0, npoints, mini_batch_size):\n net.resetGradients()\n # this is to avoid problems when npoints % mini_batch_size != 0\n actual_mini_batch_size = min(mini_batch_size,npoints - b)\n\n # forward and backward pass. The backward computes also the gradient to\n # be used in the updateWeights functions\n output = net.forward(train_input.narrow(0, b, actual_mini_batch_size))\n loss_value = net.backward(output,train_target.narrow(0, b, actual_mini_batch_size))\n\n loss += loss_value\n net.updateWeights(eta,mini_batch_size)\n\n # if (i % 10) == 0:\n # train_error = compute_number_errors(net.forward(train_input), train_target) / npoints * 100\n # print(\"Epoch: \" + str(i) + \" loss_function = {:.02f}\".format(loss) + \\\n # \" train error = {:.02f}\".format(train_error))\n\n# declare a loss function and associate it to the simple not\nloss = C.LossMSE()\nfor i in range(10):\n net = SimpleNet(loss)\n n_epochs, eta, mini_batch_size = 1000, 1e-3, 40\n\n # train the model according to SGD\n train_model(net,n_epochs,eta,mini_batch_size,train_input, train_target)\n\n # print final errors\n print(\"==================================================\")\n train_error = compute_number_errors(net.forward(train_input), train_target) / npoints * 100\n test_error = compute_number_errors(net.forward(test_input), test_target) / npoints * 100\n print(\"Train error = {:.02f}\".format(train_error))\n print(\"Test error = {:.02f}\".format(test_error))\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"359501584","text":"from bs4 import BeautifulSoup\r\nimport urllib.request\r\nfrom urllib.parse import quote\r\n\r\nTARGET_URL_BEFORE_KEYWORD = 'https://search.naver.com/search.naver?&where=news&query='\r\nTARGET_URL_BEFORE_NUM = '&sm=tab_pge&sort=0&photo=0&field=0&reporter_article=&pd=0&ds=&de=&docid=&nso=so:r,p:all,a:all&mynews=0&cluster_rank=0&start='\r\nTARGET_URL_AFTER_NUM = '&refresh_start=0'\r\n\r\ndef get_link_from_news_title(page_num, URL, output_file):\r\n for i in range(page_num):\r\n current_page_num = 1 + i * 10\r\n position = URL.index('start=')\r\n URL_with_page_num = URL[: position + 6] + str(current_page_num) + URL[position + 6:]\r\n source_code_from_URL = urllib.request.urlopen(URL_with_page_num)\r\n soup = BeautifulSoup(source_code_from_URL, 'lxml', from_encoding='utf-8')\r\n for title in soup.find_all('dd', class_ = 'txt_inline'):\r\n try:\r\n title_link = title.select('a')\r\n article_URL = title_link[0]['href']\r\n get_text(article_URL, output_file)\r\n except:\r\n pass\r\n\r\n\r\ndef get_text(URL, output_file):\r\n source_code_from_url = urllib.request.urlopen(URL)\r\n soup = BeautifulSoup(source_code_from_url, 'lxml', from_encoding='utf-8')\r\n content_of_article = soup.select('div#newsEndContents')\r\n for item in content_of_article:\r\n string_item = str(item.find_all(text=True))\r\n try:\r\n output_file.write(string_item)\r\n except:\r\n pass\r\n\r\n\r\ndef main(argv):\r\n if len(argv) != 4:\r\n print(\"python [모듈이름] [키워드] [가져올 페이지 숫자] [결과 파일명]\")\r\n return\r\n keyword = argv[1]\r\n page_num = int(argv[2])\r\n output_file_name = argv[3]\r\n target_URL = TARGET_URL_BEFORE_KEYWORD + quote(keyword) + TARGET_URL_BEFORE_NUM + TARGET_URL_AFTER_NUM\r\n output_file = open(output_file_name, 'w')\r\n get_link_from_news_title(page_num, target_URL, output_file)\r\n output_file.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n x = input(\"\")\r\n x_list = list(x.split(\" \"))\r\n main(x_list)\r\n\r\n# source_code_from_URL = urllib.request.urlopen('https://news.naver.com/main/list.nhn?mode=LS2D&sid2=258&sid1=101&mid=shm&date=20190115&page=1')\r\n# soup = BeautifulSoup(source_code_from_URL, 'lxml', from_encoding='utf-8')\r\n# for title in soup.find_all('dt'):\r\n# title_link = title.select('a')\r\n# print(title_link)\r\n# article_URL = title_link[0]['href']","sub_path":"crawler_navernews.py","file_name":"crawler_navernews.py","file_ext":"py","file_size_in_byte":2447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"255097803","text":"import datetime\r\nimport calendar\r\n\r\n# Get today's date and store it in the variable\r\n_year = datetime.date.today().year\r\n_date = datetime.date.today().day\r\n_month = datetime.date.today().month\r\n# gets the weekday in integer.( where monday = 0 and sunday = 6)\r\n_day = datetime.date.today().weekday()\r\nmyDate = datetime.date(_year, _month, _date)\r\n\r\nyearLimit = _year + 10\r\nOccurrence = 0\r\n\r\n\r\n# method to print the Date and Day\r\ndef printdate(_mydate):\r\n print(\"Date: \", _mydate)\r\n print(\"Day: \", calendar.day_name[_mydate.weekday()])\r\n print()\r\n\r\n\r\n# method that validates that the date actually exist in the calendar.\r\ndef validate(year, month, date):\r\n try:\r\n datetime.datetime(int(year), int(month), int(date))\r\n except ValueError:\r\n return False\r\n return True\r\n\r\n\r\n# Method that counts the occurrence of how many times that date and day matches.\r\ndef CountTodaysOccurance(year, date, month, day):\r\n global Occurrence\r\n # loop only runs for 10 years\r\n while year < yearLimit:\r\n # resets the month variable to 1 after it reaches 12\r\n while month < 13:\r\n if validate(year, month, date):\r\n checkDate = datetime.date(year, month, date)\r\n if day == checkDate.weekday():\r\n printdate(checkDate)\r\n Occurrence += 1\r\n month += 1\r\n month = 1\r\n year += 1\r\n\r\n\r\n# method calls\r\nprintdate(myDate)\r\nCountTodaysOccurance(_year, _date, _month, _day)\r\nprint(\"It will occur \", Occurrence, \" times in 10 years\")\r\ninput(\"Program Finished Running\")","sub_path":"Task3_CountingDays.py","file_name":"Task3_CountingDays.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"428569027","text":"#!/usr/bin/env python\n\nimport argparse\nimport glob\nimport os.path\nimport logging\nimport pandas as pd\nimport numpy as np\nimport datetime as dt\nimport matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\nimport mops_emission as mem\nfrom sklearn import linear_model\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\nmem.init_emission(\"fuel_and_emission_table.csv\")\n\nDEFAULT_AIRPORT = \"KCLT\"\nDEFAULT_FFS_VERSION = \"1.0\"\n\nKGS_TO_LBS = 2.20462\nGMS_TO_LBS = KGS_TO_LBS/1000\nLBS_TO_METRIC_TONS = 1/(KGS_TO_LBS*1000)\nMETRIC_TONS_CO2_TO_URBAN_TREES = 1/0.039\n\ndef main(ffs_path, ffs_version, airport):\n flight_list_included = []\n\n ch = logging.StreamHandler()\n ch.setLevel(logging.DEBUG)\n logger.addHandler(ch)\n\n logger.info(\"Begin loading data at {}\".format(dt.datetime.now()))\n df0 = load_ffs_data(ffs_path, airport, ffs_version)\n logger.info(\"Finish loading data at {}\".format(dt.datetime.now()))\n\n logger.info(\"Begin modifying data at {}\".format(dt.datetime.now()))\n df1 = modify_data(df0)\n logger.info(\"Finish modifying data at {}\".format(dt.datetime.now()))\n\n outputSuffix = dt.datetime.now().strftime(\"%Y%m%d\")\n\n logger.info(\"Begin computing APREQ-all metrics at {}\".format(\n dt.datetime.now()))\n\n\n #### compute GS first\n\n logger.info(\"Begin computing GS-all metrics at {}\".format(\n dt.datetime.now()))\n ######### GS metrics\n [gs_all,flight_list_included] = gs_metrics_by_group(df1, None,flight_list_included)\n ######### GS metrics\n gs_all.to_csv(\"gs_benefits_airport_wide_{}.csv\".format(\n outputSuffix), index=False)\n logger.info(\"Finish computing GS-all metrics at {}\".format(\n dt.datetime.now()))\n\n\n #### compute general EDCT\n\n\n logger.info(\"Begin computing EDCT-all metrics at {}\".format(\n dt.datetime.now()))\n ######### EDCT metrics\n [edct_all,flight_list_included] = edct_metrics_by_group(df1, None, flight_list_included)\n ######### EDCT metrics\n edct_all.to_csv(\"edct_benefits_airport_wide_{}.csv\".format(\n outputSuffix), index=False)\n logger.info(\"Finish computing EDCT-all metrics at {}\".format(\n dt.datetime.now()))\n\n\n\n logger.info(\"Begin computing APREQ-all metrics at {}\".format(\n dt.datetime.now()))\n ######### APREQ metrics\n [apreq_all,flight_list_included] = apreq_metrics_by_group(df1, None,flight_list_included)\n ######### APREQ metrics\n apreq_all.to_csv(\"apreq_benefits_airport_wide_{}.csv\".format(\n outputSuffix), index=False)\n plot_apreq_benefits(apreq_all, outputSuffix)\n logger.info(\"Finish computing APREQ-all metrics at {}\".format(\n dt.datetime.now()))\n\n # logger.info(\"Begin computing APREQ-AAL metrics at {}\".format(\n # dt.datetime.now()))\n # apreq_aal = apreq_metrics_by_group(df1, \"aal_mainline\")\n # apreq_aal.to_csv(\"apreq_benefits_AAL_mainline_{}.csv\".format(\n # outputSuffix), index=False)\n # logger.info(\"Finish computing APREQ-AAL metrics at {}\".format(\n # dt.datetime.now()))\n\n # logger.info(\"Begin computing APREQ-regional metrics at {}\".format(\n # dt.datetime.now()))\n # apreq_reg = apreq_metrics_by_group(df1, \"aal_regional\")\n # apreq_reg.to_csv(\"apreq_benefits_AAL_regional_{}.csv\".format(\n # outputSuffix), index=False)\n # logger.info(\"Finish computing APREQ-regional metrics at {}\".format(\n # dt.datetime.now()))\n\n logger.info(\"Begin computing metering-all metrics at {}\".format(\n dt.datetime.now()))\n ######### Meter metrics\n [meter_all,flight_list_included] = metering_metrics_by_group(df1, None, airport,flight_list_included)\n ######### Meter metrics\n meter_all.to_csv(\"hold_benefits_airport_wide_{}.csv\".format(\n outputSuffix), index=False)\n plot_surface_metering_benefits(meter_all, outputSuffix)\n logger.info(\"Finish computing metering-all metrics at {}\".format(\n dt.datetime.now()))\n\n # logger.info(\"Begin computing metering-AAL metrics at {}\".format(\n # dt.datetime.now()))\n # meter_aal = metering_metrics_by_group(df1, \"aal_mainline\", airport)\n # meter_aal.to_csv(\"hold_benefits_AAL_mainline_{}.csv\".format(\n # outputSuffix), index=False)\n # logger.info(\"Finish computing metering-AAL metrics at {}\".format(\n # dt.datetime.now()))\n\n # logger.info(\"Begin computing metering-regional metrics at {}\".format(\n # dt.datetime.now()))\n # meter_reg = metering_metrics_by_group(df1, \"aal_regional\", airport)\n # meter_reg.to_csv(\"hold_benefits_AAL_regional_{}.csv\".format(\n # outputSuffix), index=False)\n # logger.info(\"Finish computing metering-regional metrics at {}\".format(\n # dt.datetime.now()))\n\n \n\n # logger.info(\"Begin computing EDCT-AAL metrics at {}\".format(\n # dt.datetime.now()))\n # edct_aal = edct_metrics_by_group(df1, \"aal_mainline\")\n # edct_aal.to_csv(\"edct_benefits_AAL_mainline_{}.csv\".format(\n # outputSuffix), index=False)\n # logger.info(\"Finish computing EDCT-AAL metrics at {}\".format(\n # dt.datetime.now()))\n\n # logger.info(\"Begin computing EDCT-regional metrics at {}\".format(\n # dt.datetime.now()))\n # edct_reg = edct_metrics_by_group(df1, \"aal_regional\")\n # edct_reg.to_csv(\"edct_benefits_AAL_regional_{}.csv\".format(\n # outputSuffix), index=False)\n # logger.info(\"Finish computing EDCT-regional metrics at {}\".format(\n # dt.datetime.now()))\n\n \n\n # logger.info(\"Begin computing GS-AAL metrics at {}\".format(\n # dt.datetime.now()))\n # gs_aal = gs_metrics_by_group(df1, \"aal_mainline\")\n # gs_aal.to_csv(\"gs_benefits_AAL_mainline_{}.csv\".format(\n # outputSuffix), index=False)\n # logger.info(\"Finish computing GS-AAL metrics at {}\".format(\n # dt.datetime.now()))\n\n # logger.info(\"Begin computing GS-regional metrics at {}\".format(\n # dt.datetime.now()))\n # gs_reg = gs_metrics_by_group(df1, \"aal_regional\")\n # gs_reg.to_csv(\"gs_benefits_AAL_regional_{}.csv\".format(\n # outputSuffix), index=False)\n # logger.info(\"Finish computing GS-regional metrics at {}\".format(\n # dt.datetime.now()))\n\n logger.info(\"Begin computing summary of benefits at {}\".format(\n dt.datetime.now()))\n summary = summarize_benefits(apreq_all, meter_all, edct_all, gs_all)\n summary.to_csv(\"summary_benefits_metrics_{}.csv\".format(\n outputSuffix), index=False)\n logger.info(\"Finish computing summary of benefits at {}\".format(\n dt.datetime.now()))\n\n#TODO: clean up this function\ndef summarize_benefits(df_apreq, df_hold, df_edct, df_gs):\n df_summary = pd.DataFrame()\n \n idac_time_saved_hour = df_apreq['Time saved by IDAC-related APREQ negotiation (hours)'].sum()\n apreq_time_gate_hold_hour = df_apreq['Gate hold flights with APREQ negotiated at gate (Hours)'].sum()\n meter_time_gate_hold_hour = df_hold['Sum of surface metering gate holds (minutes)'].sum() / float(60)\n edct_gate_hold_hour = df_edct[\"Sum of EDCT gate holds (hours)\"].sum()\n gs_gate_hold_hour = df_gs[\"Sum of GS gate holds (hours)\"].sum()\n #### Pounds Fuel\n surface_metering_pounds_fuel = df_hold['Fuel saved by surface metering gate holds (pounds)'].sum()\n apreq_gate_hold_pounds_fuel = df_apreq['Fuel saved by gate holds of flights with APREQ negotiated at gate (pounds)'].sum()\n IDAC_renegotiation_pounds_fuel = df_apreq['Fuel saved by IDAC-related APREQ negotiation (pounds)'].sum()\n edct_gate_hold_pounds_fuel = df_edct[\"Fuel saved by EDCT gate holds (pounds)\"].sum()\n gs_gate_hold_pounds_fuel = df_gs[\"Fuel saved by GS gate holds (pounds)\"].sum()\n #### Pounds CO2\n surface_metering_pounds_CO2 = df_hold['CO2 saved by surface metering gate holds (pounds)'].sum()\n apreq_gate_hold_pounds_CO2 = df_apreq['CO2 saved by gate holds of flights with APREQ negotiated at gate (pounds)'].sum()\n IDAC_renegotiation_pounds_CO2 = df_apreq['CO2 saved by IDAC-related APREQ negotiation (pounds)'].sum()\n edct_gate_hold_pounds_CO2 = df_edct[\"CO2 saved by EDCT gate holds (pounds)\"].sum()\n gs_gate_hold_pounds_CO2 = df_gs[\"CO2 saved by GS gate holds (pounds)\"].sum()\n #### Urban Trees\n surface_metering_urban_trees = df_hold['Urban trees saved'].sum()\n apreq_gate_hold_urban_trees = df_apreq['Urban trees saved by gate holds of flights with APREQ negotiated at gate'].sum()\n IDAC_renegotiation_urban_trees = df_apreq['Urban trees saved by IDAC APREQ negotiation'].sum()\n edct_gate_hold_urban_trees = df_edct[\"Urban trees saved\"].sum()\n gs_gate_hold_urban_trees = df_gs[\"Urban trees saved\"].sum()\n \n df_summary.loc[0,'IDAC_delay_savings(hours)'] = idac_time_saved_hour\n df_summary.loc[0,'surface_metering_engine_run_time_savings(hours)'] = meter_time_gate_hold_hour\n df_summary.loc[0,'APREQ_gate_hold_engine_run_time_savings(hours)'] = apreq_time_gate_hold_hour\n df_summary.loc[0,\"EDCT_gate_hold_engine_run_time_savings(hours)\"] = edct_gate_hold_hour\n df_summary.loc[0,\"GS_gate_hold_engine_run_time_savings(hours)\"] = gs_gate_hold_hour\n df_summary.loc[0,'total_engine_run_time_savings(hours)'] = (\n df_summary.loc[0,'IDAC_delay_savings(hours)'] +\n df_summary.loc[0,'surface_metering_engine_run_time_savings(hours)'] +\n df_summary.loc[0,'APREQ_gate_hold_engine_run_time_savings(hours)'] +\n df_summary.loc[0,\"EDCT_gate_hold_engine_run_time_savings(hours)\"] +\n df_summary.loc[0,\"GS_gate_hold_engine_run_time_savings(hours)\"])\n \n #### Surface Metering\n df_summary.loc[0,'surface_metering_fuel(pounds)'] = surface_metering_pounds_fuel\n df_summary.loc[0,'surface_metering_CO2(pounds)'] = surface_metering_pounds_CO2\n df_summary.loc[0,'surface_metering_urban_trees'] = surface_metering_urban_trees\n #### APREQ Gate Hold\n df_summary.loc[0,'APREQ_gate_hold_fuel(pounds)'] = apreq_gate_hold_pounds_fuel\n df_summary.loc[0,'APREQ_gate_hold_CO2(pounds)'] = apreq_gate_hold_pounds_CO2\n df_summary.loc[0,'APREQ_gate_hold_urban_trees'] = apreq_gate_hold_urban_trees\n #### IDAC Renegotiation\n df_summary.loc[0,'IDAC_renegotiation_fuel(pounds)'] = IDAC_renegotiation_pounds_fuel\n df_summary.loc[0,'IDAC_renegotiation_CO2(pounds)'] = IDAC_renegotiation_pounds_CO2\n df_summary.loc[0,'IDAC_renegotiation_urban_trees'] = IDAC_renegotiation_urban_trees\n \n df_summary.loc[0,\"EDCT_gate_hold_fuel(pounds)\"] = edct_gate_hold_pounds_fuel\n df_summary.loc[0,\"EDCT_gate_hold_CO2(pounds)\"] = edct_gate_hold_pounds_CO2\n df_summary.loc[0,\"EDCT_gate_hold_urban_trees\"] = edct_gate_hold_urban_trees\n\n df_summary.loc[0,\"GS_gate_hold_fuel(pounds)\"] = gs_gate_hold_pounds_fuel\n df_summary.loc[0,\"GS_gate_hold_CO2(pounds)\"] = gs_gate_hold_pounds_CO2\n df_summary.loc[0,\"GS_gate_hold_urban_trees\"] = gs_gate_hold_urban_trees\n \n df_summary.loc[0,'total_fuel(pounds)'] = (\n df_summary.loc[0,'surface_metering_fuel(pounds)'] +\n df_summary.loc[0,'APREQ_gate_hold_fuel(pounds)'] +\n df_summary.loc[0,'IDAC_renegotiation_fuel(pounds)'] +\n df_summary.loc[0,\"EDCT_gate_hold_fuel(pounds)\"] +\n df_summary.loc[0,\"GS_gate_hold_fuel(pounds)\"])\n \n df_summary.loc[0,'total_CO2(pounds)'] = (\n df_summary.loc[0,'surface_metering_CO2(pounds)'] +\n df_summary.loc[0,'APREQ_gate_hold_CO2(pounds)'] +\n df_summary.loc[0,'IDAC_renegotiation_CO2(pounds)'] +\n df_summary.loc[0,\"EDCT_gate_hold_CO2(pounds)\"] +\n df_summary.loc[0,\"GS_gate_hold_CO2(pounds)\"])\n \n df_summary.loc[0,'total_urban_trees'] = (\n df_summary.loc[0,'surface_metering_urban_trees'] +\n df_summary.loc[0,'APREQ_gate_hold_urban_trees'] +\n df_summary.loc[0,'IDAC_renegotiation_urban_trees'] +\n df_summary.loc[0,\"EDCT_gate_hold_urban_trees\"] +\n df_summary.loc[0,\"GS_gate_hold_urban_trees\"])\n \n df_summary.loc[0,'IDAC_passenger_value_of_time'] = df_summary.loc[0,'IDAC_delay_savings(hours)'] * float(4800.20)\n df_summary.loc[0,'IDAC_flight_crew_cost'] = df_summary.loc[0,'IDAC_delay_savings(hours)'] * 60 * float(22.67)\n \n df_summary.loc[0,'surface_metering_fuel(gallons jet A-1 6.71 pounds / gal)'] = surface_metering_pounds_fuel / float(6.71)\n df_summary.loc[0,'surface_metering_fuel(gallons jet A 6.84 pounds / gal)'] = surface_metering_pounds_fuel / float(6.84)\n \n df_summary.loc[0,'APREQ_gate_hold_fuel(gallons jet A-1 6.71 pounds / gal)'] = apreq_gate_hold_pounds_fuel / float(6.71)\n df_summary.loc[0,'APREQ_gate_hold_fuel(gallons jet A 6.84 pounds / gal)'] = apreq_gate_hold_pounds_fuel / float(6.84)\n \n df_summary.loc[0,'IDAC_renegotiation_fuel(gallons jet A-1 6.71 pounds / gal)'] = IDAC_renegotiation_pounds_fuel / float(6.71)\n df_summary.loc[0,'IDAC_renegotiation_fuel(gallons jet A 6.84 pounds / gal)'] = IDAC_renegotiation_pounds_fuel / float(6.84)\n\n df_summary.loc[0,'EDCT_gate_hold_fuel(gallons jet A-1 6.71 pounds / gal)'] = edct_gate_hold_pounds_fuel / float(6.71)\n df_summary.loc[0,'EDCT_gate_hold_fuel(gallons jet A 6.84 pounds / gal)'] = edct_gate_hold_pounds_fuel / float(6.84)\n\n df_summary.loc[0,'GS_gate_hold_fuel(gallons jet A-1 6.71 pounds / gal)'] = gs_gate_hold_pounds_fuel / float(6.71)\n df_summary.loc[0,'GS_gate_hold_fuel(gallons jet A 6.84 pounds / gal)'] = gs_gate_hold_pounds_fuel / float(6.84)\n \n df_summary.loc[0,'total_fuel(gallons jet A-1 6.71 pounds / gal)'] = df_summary.loc[0,'total_fuel(pounds)'] / float(6.71)\n df_summary.loc[0,'total_fuel(gallons jet A 6.84 pounds / gal)'] = df_summary.loc[0,'total_fuel(pounds)'] / float(6.84)\n\n return df_summary\n\ndef edct_metrics_by_group(df, group, flight_list):\n if group:\n idx_group = df[\"flight_category\"] == group\n else:\n idx_group = df[\"gufi\"].notnull()\n\n idx_date = df[\"year_month\"] != \"nan-nan\"\n idx_edct = df[\"edct_at_ready\"].notnull()\n\n df_edct = df[idx_group & idx_date & idx_edct] \n print('EDCT pre filter')\n print(len(df_edct))\n ##### Filter out flights found previously\n df_edct = df_edct[~df_edct['gufi'].isin(flight_list)]\n print('EDCT post filter')\n print(len(df_edct))\n df_temp = df_edct[df_edct['effective_gate_hold']>0]\n print('EDCT actually held')\n print(len(df_temp))\n ##### Add flights to flight list\n flight_list.extend( df_edct['gufi'].values.tolist() )\n\n\n df_edct[[\"hold_savings_fuel\",\n \"hold_savings_co\",\n \"hold_savings_co2\",\n \"hold_savings_hc\",\n \"hold_savings_nox\"]] = df_edct.apply(\n calc_emissions, axis=1, args=[\"effective_gate_hold\"])\n\n edct_metrics = (\n df_edct.groupby([\"year_month\"]).agg(\n {\"gufi\":\"count\",\n \"effective_gate_hold\":lambda x: sum(x)/3600,\n \"hold_savings_fuel\":lambda x: np.nansum(x)*KGS_TO_LBS,\n \"hold_savings_co\":lambda x: np.nansum(x)*GMS_TO_LBS,\n \"hold_savings_co2\":lambda x: np.nansum(x)*KGS_TO_LBS,\n \"hold_savings_hc\":lambda x: np.nansum(x)*GMS_TO_LBS,\n \"hold_savings_nox\":lambda x: np.nansum(x)*GMS_TO_LBS}).\n reset_index())\n\n edct_metrics = edct_metrics.assign(\n urban_trees_planted=edct_metrics[\"hold_savings_co2\"]*\n LBS_TO_METRIC_TONS*METRIC_TONS_CO2_TO_URBAN_TREES)\n\n edct_metrics = edct_metrics.rename(columns={\n \"gufi\":\"Count of EDCT flights\",\n \"effective_gate_hold\":\"Sum of EDCT gate holds (hours)\",\n \"hold_savings_fuel\":\"Fuel saved by EDCT gate holds (pounds)\",\n \"hold_savings_co\":\"CO saved by EDCT gate holds (pounds)\",\n \"hold_savings_co2\":\"CO2 saved by EDCT gate holds (pounds)\",\n \"hold_savings_hc\":\"HC saved by EDCT gate holds (pounds)\",\n \"hold_savings_nox\":\"NOX saved by EDCT gate holds (pounds)\",\n \"urban_trees_planted\":\"Urban trees saved\"})\n\n return [edct_metrics,flight_list]\n\ndef gs_metrics_by_group(df, group, flight_list):\n if group:\n idx_group = df[\"flight_category\"] == group\n else:\n idx_group = df[\"gufi\"].notnull()\n\n idx_date = df[\"year_month\"] != \"nan-nan\"\n idx_gs = df[\"ground_stop_restriction_ids_present\"] == True\n\n df_gs = df[idx_group & idx_date & idx_gs]\n print('GS pre filter')\n print(len(df_gs))\n ##### Filter out flights found previously\n df_gs = df_gs[~df_gs['gufi'].isin(flight_list)]\n print('GS post filter')\n print(len(df_gs))\n df_temp = df_gs[df_gs['effective_gate_hold']>0]\n print('Ground stop actually held')\n print(len(df_temp))\n ##### Add flights to flight list\n flight_list.extend( df_gs['gufi'].values.tolist() )\n \n logger.debug(\"Filtered GS data of shape {}\".format(df_gs.shape))\n\n logger.debug(\"Begin computing emissions at {}\".format(dt.datetime.now()))\n df_gs[[\"hold_savings_fuel\",\n \"hold_savings_co\",\n \"hold_savings_co2\",\n \"hold_savings_hc\",\n \"hold_savings_nox\"]] = df_gs.apply(\n calc_emissions, axis=1, args=[\"effective_gate_hold\"])\n logger.debug(\"Finish computing emissions at {}\".format(dt.datetime.now()))\n\n gs_metrics = (\n df_gs.groupby([\"year_month\"]).agg(\n {\"gufi\":\"count\",\n \"effective_gate_hold\":lambda x: sum(x)/3600,\n \"hold_savings_fuel\":lambda x: np.nansum(x)*KGS_TO_LBS,\n \"hold_savings_co\":lambda x: np.nansum(x)*GMS_TO_LBS,\n \"hold_savings_co2\":lambda x: np.nansum(x)*KGS_TO_LBS,\n \"hold_savings_hc\":lambda x: np.nansum(x)*GMS_TO_LBS,\n \"hold_savings_nox\":lambda x: np.nansum(x)*GMS_TO_LBS}).\n reset_index())\n\n gs_metrics = gs_metrics.assign(\n urban_trees_planted=gs_metrics[\"hold_savings_co2\"]*\n LBS_TO_METRIC_TONS*METRIC_TONS_CO2_TO_URBAN_TREES)\n\n gs_metrics = gs_metrics.rename(columns={\n \"gufi\":\"Count of GS flights\",\n \"effective_gate_hold\":\"Sum of GS gate holds (hours)\",\n \"hold_savings_fuel\":\"Fuel saved by GS gate holds (pounds)\",\n \"hold_savings_co\":\"CO saved by GS gate holds (pounds)\",\n \"hold_savings_co2\":\"CO2 saved by GS gate holds (pounds)\",\n \"hold_savings_hc\":\"HC saved by GS gate holds (pounds)\",\n \"hold_savings_nox\":\"NOX saved by GS gate holds (pounds)\",\n \"urban_trees_planted\":\"Urban trees saved\"})\n\n return [gs_metrics,flight_list]\n\n\ndef plot_surface_metering_benefits(df_hold, decorator):\n df_hold = (df_hold[((df_hold[\"year_month\"].notnull()) &\n (df_hold[\"year_month\"] != \"2017-10\"))].\n sort_values(\"year_month\").\n reset_index())\n co2 = np.array(\n df_hold[\"CO2 saved by surface metering gate holds (pounds)\"])\n plt.figure(figsize=(30,8))\n x_vec = np.arange(len(co2))\n plt.bar(x_vec, co2/float(1000),\n color=\"green\", alpha=0.5, edgecolor=\"black\")\n plt.ylabel(\"CO2 Emissions Savings\\n(thousand pounds)\", fontsize=30)\n plt.xticks(x_vec, df_hold[\"year_month\"], fontsize=20)\n plt.yticks(fontsize=30)\n plt.title(\"Total Estimated CO2 Emissions Savings\",\n fontsize=40)\n ax = plt.gca()\n ax.yaxis.grid(True)\n plt.savefig(\"hold_estimated_savings_{}.png\".format(decorator))\n\ndef plot_apreq_benefits(df_apreq, decorator):\n df_apreq = df_apreq.sort_values(\"year_month\").reset_index()\n df_apreq = df_apreq.assign(\n fuel_per_apreq=df_apreq[\"Fuel saved by gate holds of flights with APREQ negotiated at gate (pounds)\"]\n / df_apreq[\"Count of flights with first APREQ negotiated at gate\"])\n fuel_per_apreq = np.array(df_apreq[\"fuel_per_apreq\"])\n plt.figure(figsize=(12,10))\n x_vec = np.arange(len(fuel_per_apreq))\n plt.plot(x_vec, fuel_per_apreq, linewidth=10, color=\"blue\", alpha=0.6)\n plt.plot(x_vec, fuel_per_apreq,\n linestyle=\"None\", marker=\"o\", markersize=30,\n color=\"blue\", alpha=0.9)\n plt.xticks(x_vec, df_apreq[\"year_month\"], fontsize=20, rotation=30)\n plt.ylabel(\"Fuel Saved per APREQ (pounds)\", fontsize=24)\n plt.title(\"Fuel Saved per APREQ Flight\\nScheduled at Gate\", fontsize=50)\n plt.yticks(fontsize=16)\n plt.tight_layout()\n ax = plt.gca()\n ax.yaxis.grid(True)\n\n regr = linear_model.LinearRegression()\n regr.fit(x_vec.reshape(-1, 1), fuel_per_apreq.reshape(-1, 1))\n slope = regr.coef_[0][0]\n y_intercept = regr.intercept_[0]\n\n y2 = (len(x_vec)-1) * slope + y_intercept\n plt.plot([0,len(x_vec)-1], [y_intercept, y2 ],\n linestyle=\"-.\", linewidth=6, color=\"red\")\n plt.savefig(\"apreq_estimated_savings_{}.png\".format(decorator))\n\ndef metering_metrics_by_group(df, group, airport,flight_list):\n if group:\n idx_group = df[\"flight_category\"] == group\n else:\n idx_group = df[\"gufi\"].notnull()\n\n idx_date = df[\"year_month\"] != \"nan-nan\"\n idx_meter = df[\"metered_indicator\"] == True\n\n metrics = df[idx_group & idx_date & idx_meter]\n print('metering pre filter')\n print(len(metrics))\n ##### Filter out flights found previously\n debug_df = metrics[metrics['gufi'].isin(flight_list)]\n debug_df.to_csv('surface_metered_flights_filtered_out.csv',index=False)\n metrics = metrics[~metrics['gufi'].isin(flight_list)]\n metrics.to_csv('debug_surface_metered_flights.csv')\n print('metering post filter')\n print(len(metrics))\n temp_metrics = metrics[metrics['hold_indicator']==True]\n print('number actually held')\n print(len(temp_metrics))\n ##### Add flights to flight list\n flight_list.extend( metrics['gufi'].values.tolist() )\n\n metrics = metrics.groupby([\"year_month\"]).agg(\n {\"departure_aerodrome_icao_name\":lambda x: sum(x == airport),\n \"hold_indicator\":\"sum\",\n \"actual_gate_hold\":\"sum\",\n \"gate_hold_fuel_savings\":lambda x: np.nansum(x)*KGS_TO_LBS,\n \"gate_hold_co_savings\":lambda x: np.nansum(x)*GMS_TO_LBS,\n \"gate_hold_co2_savings\":lambda x: np.nansum(x)*KGS_TO_LBS,\n \"gate_hold_hc_savings\":lambda x: np.nansum(x)*GMS_TO_LBS,\n \"gate_hold_nox_savings\":lambda x: np.nansum(x)*GMS_TO_LBS}).\\\n reset_index()\n metrics = metrics.assign(urban_trees_planted = metrics[\"gate_hold_co2_savings\"]* \\\n LBS_TO_METRIC_TONS* \\\n METRIC_TONS_CO2_TO_URBAN_TREES)\n\n metrics.rename(\n columns={\"departure_aerodrome_icao_name\":\"Count of departures\",\n \"hold_indicator\":\"Count of departures held\",\n \"actual_gate_hold\":\"Sum of surface metering gate holds (minutes)\",\n \"gate_hold_fuel_savings\":\"Fuel saved by surface metering gate holds (pounds)\",\n \"gate_hold_co_savings\":\"CO saved by surface metering gate holds (pounds)\",\n \"gate_hold_co2_savings\":\"CO2 saved by surface metering gate holds (pounds)\",\n \"gate_hold_hc_savings\":\"HC saved by surface metering gate holds (pounds)\",\n \"gate_hold_nox_savings\":\"NOX saved by surface metering gate holds (pounds)\",\n \"urban_trees_planted\":\"Urban trees saved\"},\n inplace=True)\n\n return [metrics,flight_list]\n\ndef apreq_metrics_by_group(df, group,flight_list):\n idx_idac_savings = df[\"apreq_final\"] < df[\"apreq_initial\"]\n idx_all_idac = ((df[\"apreq_initial_source\"] == \"IDAC\") &\n (df[\"apreq_final_source\"] == \"IDAC\"))\n if group:\n idx_group = df[\"flight_category\"] == group\n else:\n idx_group = df[\"gufi\"].notnull()\n\n idx_neg_at_gate = (\n df[\"surface_flight_state_at_initial_apreq\"] == \"SCHEDULED\")\n idx_reasonable_holds = (df[\"effective_gate_hold\"] <= 1800)\n\n idx_date = df[\"year_month\"] != \"nan-nan\"\n\n df_idac = df[idx_group &\n idx_idac_savings &\n idx_all_idac &\n idx_date]\n\n #### DONT FILTER FLIGHTS FROM RENEGOTIATION SAVINGS\n # print(len(df_idac))\n # ##### Filter out flights found previously\n # df_idac = df_idac[~df_idac['gufi'].isin(flight_list)]\n # print(len(df_idac))\n # ##### Add flights to flight list\n # flight_list.extend( df_idac['gufi'].values.tolist() )\n print('Number of IDAC renegotiation')\n print(len(df_idac))\n\n\n\n \n df_idac[[\"IDAC_savings_fuel\",\n \"IDAC_savings_co\",\n \"IDAC_savings_co2\",\n \"IDAC_savings_hc\",\n \"IDAC_savings_nox\"]] = df_idac.apply(\n calc_emissions, axis=1, args=[\"negotiation_savings\"])\n\n idac_metrics = (\n df_idac.groupby([\"year_month\"]).agg(\n {\"gufi\":\"count\",\n \"negotiation_savings\":lambda x: sum(x)/3600,\n \"IDAC_savings_fuel\":lambda x: np.nansum(x)*KGS_TO_LBS,\n \"IDAC_savings_co\":lambda x: np.nansum(x)*GMS_TO_LBS,\n \"IDAC_savings_co2\":lambda x: np.nansum(x)*KGS_TO_LBS,\n \"IDAC_savings_hc\":lambda x: np.nansum(x)*GMS_TO_LBS,\n \"IDAC_savings_nox\":lambda x: np.nansum(x)*GMS_TO_LBS}).\n reset_index())\n\n idac_metrics = idac_metrics.assign(\n IDAC_trees_planted = \\\n idac_metrics[\"IDAC_savings_co2\"]* \\\n LBS_TO_METRIC_TONS* \\\n METRIC_TONS_CO2_TO_URBAN_TREES)\n\n idac_metrics.rename(columns={\n \"gufi\":\n \"Count of flights with IDAC-related time savings\",\n \"negotiation_savings\":\n \"Time saved by IDAC-related APREQ negotiation (hours)\",\n \"IDAC_savings_fuel\":\n \"Fuel saved by IDAC-related APREQ negotiation (pounds)\",\n \"IDAC_savings_co\":\n \"CO saved by IDAC-related APREQ negotiation (pounds)\",\n \"IDAC_savings_co2\":\n \"CO2 saved by IDAC-related APREQ negotiation (pounds)\",\n \"IDAC_savings_hc\":\n \"HC saved by IDAC-related APREQ negotiation (pounds)\",\n \"IDAC_savings_nox\":\n \"NOX saved by IDAC-related APREQ negotiation (pounds)\",\n \"IDAC_trees_planted\":\n \"Urban trees saved by IDAC APREQ negotiation\"},\n inplace=True)\n\n hold_metrics_df = df[idx_group &\n idx_neg_at_gate &\n idx_reasonable_holds &\n idx_date]\n\n ##### FILTER EDCT / GS that might also have APREQ and gate hold\n print('APREQ gate hold pre filter')\n print(len(hold_metrics_df))\n ##### Filter out flights found previously\n hold_metrics_df = hold_metrics_df[~hold_metrics_df['gufi'].isin(flight_list)]\n print(len(hold_metrics_df))\n print('APREQ gate hold post filter')\n\n df_temp = hold_metrics_df[ hold_metrics_df['effective_gate_hold']>0]\n\n print('Number of APREQ held')\n print(len(df_temp))\n ##### Add flights to flight list\n flight_list.extend( hold_metrics_df['gufi'].values.tolist() )\n\n hold_metrics_df[[\"hold_savings_fuel\",\n \"hold_savings_co\",\n \"hold_savings_co2\",\n \"hold_savings_hc\",\n \"hold_savings_nox\"]] = hold_metrics_df.apply(\n calc_emissions, axis=1, args=[\"effective_gate_hold\"])\n\n hold_metrics = hold_metrics_df.groupby([\"year_month\"]).agg(\n {\"gufi\":\"count\",\n \"effective_gate_hold\":lambda x: np.nansum(x)/3600,\n \"hold_savings_fuel\":lambda x: np.nansum(x)*KGS_TO_LBS,\n \"hold_savings_co\":lambda x: np.nansum(x)*GMS_TO_LBS,\n \"hold_savings_co2\":lambda x: np.nansum(x)*KGS_TO_LBS,\n \"hold_savings_hc\":lambda x: np.nansum(x)*GMS_TO_LBS,\n \"hold_savings_nox\":lambda x: np.nansum(x)*GMS_TO_LBS}).\\\n reset_index()\n hold_metrics = hold_metrics.assign(\n urban_trees_planted = \\\n hold_metrics[\"hold_savings_co2\"]* \\\n LBS_TO_METRIC_TONS* \\\n METRIC_TONS_CO2_TO_URBAN_TREES)\n hold_metrics.rename(columns={\n \"gufi\":\n \"Count of flights with first APREQ negotiated at gate\",\n \"effective_gate_hold\":\n \"Gate hold flights with APREQ negotiated at gate (Hours)\",\n \"hold_savings_fuel\":\n \"Fuel saved by gate holds of flights with APREQ negotiated at gate (pounds)\",\n \"hold_savings_co\":\n \"CO saved by gate holds of flights with APREQ negotiated at gate (pounds)\",\n \"hold_savings_co2\":\n \"CO2 saved by gate holds of flights with APREQ negotiated at gate (pounds)\",\n \"hold_savings_hc\":\n \"HC saved by gate holds of flights with APREQ negotiated at gate (pounds)\",\n \"hold_savings_nox\":\n \"NOX saved by gate holds of flights with APREQ negotiated at gate (pounds)\",\n \"urban_trees_planted\":\n \"Urban trees saved by gate holds of flights with APREQ negotiated at gate\"},\n inplace=True)\n metrics = idac_metrics.merge(hold_metrics, how=\"outer\", on=\"year_month\")\n\n return [metrics,flight_list]\n\ndef modify_data(df):\n df = df.assign(aobt_local=\n df.departure_stand_actual_time.dt.tz_localize(\"UTC\").\\\n dt.tz_convert(\"US/Eastern\"))\n df[\"year_month\"] = df.apply(\n lambda x: \"{}-{}\".format(x.aobt_local.year, x.aobt_local.month),\n axis=1)\n df = df.assign(negotiation_savings=\n (df.apreq_initial - df.apreq_final).dt.seconds)\n df = df.assign(effective_gate_hold=\n (df.departure_stand_actual_time - df.pilot_ready_time).dt.seconds)\n\n return df\n\ndef load_ffs_data(ffs_path, airport, ffs_version):\n allFiles = glob.glob(os.path.join(ffs_path, \"**\",\n airport + \".fullFlightSummary.v\" + ffs_version + \"*.csv\"),\n recursive=True)\n\n indiv_files = []\n for f in allFiles:\n df = pd.read_csv(f, index_col=None, header=0,\n parse_dates=[\"time_at_initial_apreq\",\n \"apreq_initial\",\n \"apreq_final\",\n \"departure_stand_actual_time\",\n \"pilot_ready_time\"])\n indiv_files.append(df)\n df = pd.concat(indiv_files)\n\n return df\n\ndef calc_emissions(row, field):\n em_input = pd.DataFrame({\n \"aircraftType\":row[\"aircraft_type\"],\n \"weightClass\":\"D\",\n \"MoveTAct\":0,\n \"RampTAct\":0,\n \"TaxiTAct\":row[field]},\n index=[0])\n em_results = mem.row_get_total_emission(em_input.iloc[0])\n\n return pd.Series(list(em_results.iloc[0:5]),\n index=[\"fuel\", \"co\", \"co2\", \"hc\", \"nox\"])\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Generate aggregate metrics\")\n parser.add_argument(\"ffs_path\",\n help=\"Path with fullFlightSummary files\")\n parser.add_argument(\"--ffs_version\",\n default=DEFAULT_FFS_VERSION,\n help=\"fullFlightSummary version to open\")\n parser.add_argument(\"--airport\",\n default=DEFAULT_AIRPORT,\n help=\"Airport to analyze, ICAO format\")\n args = parser.parse_args()\n\n main(args.ffs_path, args.ffs_version, args.airport)\n","sub_path":"benefits_summary_with_filter.py","file_name":"benefits_summary_with_filter.py","file_ext":"py","file_size_in_byte":31637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"493184460","text":"from random import sample\nfrom select import select\nimport dash\nfrom dash import html, Input, Output, State, callback_context, dash_table,callback,ctx\nimport pandas as pd\nfrom collections import OrderedDict\nimport numpy as np\nfrom itertools import compress, product, chain, combinations\nimport dash_pdf_components\nimport dash_bootstrap_components as dbc\nimport json\n#mel added libraries\nfrom dash import dcc\nimport plotly.express as px\nfrom numpy.random import randint, rand, uniform\nimport plotly.graph_objects as go\nimport statistics\nfrom statistics import mode\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\nimport locale\nimport time\nimport uuid\nimport json, operator\nimport datetime\nfrom operator import itemgetter\n\n# To use default settings, set locale to None or leave second argument blank.\nlocale.setlocale(locale.LC_ALL, 'en_US')\n\ndash.register_page(\n __name__,\n path='/mainPage',\n use_pages=True,\n external_stylesheets=[dbc.themes.BOOTSTRAP],\n external_scripts=['https://documentcloud.adobe.com/view-sdk/main.js']\n)\n\ntitle = \"Dash PDF Reader\"\nAPI_KEY = '899d52477b7d4b589f808242e8d36cc3' #This client ID only works for localhost\n### read jsonlines file with annotations\n\n#import csv of contracts and contract info\ndocList= pd.read_csv('assets/files/testFiles/docList.csv')\ndocList['tfcProjection']=docList[\"tfcConfidence\"]\ndocList['tfcAllTrue'] = docList.apply(lambda x: 1.0, axis=1)\ndocList['tfcAllFalse'] = docList.apply(lambda x: 0.0, axis=1)\n# print(\"docList is \",docList)\n\n\ndef load_annotations(json_file_path):\n arr = []\n with open(json_file_path, 'r') as file:\n for line in file:\n arr.append(json.loads(line))\n return arr\n\n\n#create doc table\nmypath= \"assets/files/testFiles/\"\nallFiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]\nprint(\"all Files is \")\nprint(allFiles)\n\ndocumentTable=[]\n\n#interaction variables\ndfUserActivity=pd.DataFrame()\nreviewGraphHovers=[]\nprojectionGraphHovers=[]\nconfidenceParamClicks=[]\nrevenueParamClicks=[]\ntimeStart=time.time()\ncontractReviews=[]\n\ndocumentTable.append(\n{\n \"contractId\": \"DR3215053\",\n \"impactFactor\": 5250,\n \"data\": {\n \"key\": \"DR3215053_00873923_Parent.pdf\",\n \"fileUrl\": \"assets/files/DR3215053_00873923_Parent.pdf\",\n \"fileName\": \"DR3215053_00873923_Parent\",\n \"highlightsArr\": [\n { \"@context\": [\"https://www.w3.org/ns/anno.jsonld\", \"https://comments.acrobat.com/ns/anno.jsonld\"], \"id\": \"7f79dd7c-265c-4fad-90e8-693e2fa4309e\", \"type\": \"Annotation\", \"motivation\": \"commenting\", \"bodyValue\": \"1. Example sentence highlight 1.\", \"target\": { \"source\": \"DR3215053\", \"selector\": { \"node\": { \"index\": 0 }, \"quadPoints\": [59.095872, 673.3267731199998, 336.7232149708801, 673.3267731199998, 59.095872, 665.3595411199998, 336.7232149708801, 665.3595411199998], \"opacity\": 0.4, \"subtype\": \"highlight\", \"boundingBox\": [0, 0, 595, 842], \"strokeColor\": \"#90EE90\", \"type\": \"AdobeAnnoSelector\" } }, \"creator\": { \"category\": \"Clause\", \"name\": \"TFC\", \"type\": \"Person\", \"isReviewed\": False, \"isCorrect\": True }, \"created\": \"2022-07-19T13:52:20Z\", \"modified\": \"2022-07-19T13:52:20Z\" }\n ],\n \"endUser\": \"\",\n \"region\": \"Americas\",\n \"fiscalYear\": 2021,\n \"marketArea\": \"\",\n \"revenue\": 150000,\n \"tfcConfidence\": 0.65\n }\n }\n)\n\npdfList=[]\njsonLinesList=[]\nfor fileName in allFiles:\n if \".pdf\" in fileName:\n fileNameNoExt=os.path.splitext(fileName)[0]\n pdfList.append(fileName)\n contractID=fileName.split('_')[0]\n dictContract = {}\n contractInfo = {}\n dictContract['contractId']= contractID\n contractInfo['key']=fileName\n contractInfo['fileUrl']= \"assets/files/testFiles/{}\".format(fileName)\n contractInfo['fileName']=fileNameNoExt\n annotationUrl= \"assets/files/testFiles/{}_annot.jsonlines\".format(contractID)\n\n highlightsArr= load_annotations(annotationUrl)\n highlightsArr[0]['target']['source']= contractID\n highlightsArr[0]['creator']['isReviewed']= docList.loc[docList['contractID'] == contractID, 'reviewed'].iloc[0]\n highlightsArr[0]['creator']['isCorrect']= docList.loc[docList['contractID'] == contractID, 'tfc'].iloc[0]\n\n contractInfo['highlightsArr']=highlightsArr\n\n # contractInfo['tfc']=docList.loc[docList['contractID'] == contractID, 'tfc'].iloc[0]\n contractInfo['tfcConfidence']=docList.loc[docList['contractID'] == contractID, 'tfcConfidence'].iloc[0]\n contractInfo['revenue']=docList.loc[docList['contractID'] == contractID, 'revenue'].iloc[0]\n # contractInfo['reviewed']=docList.loc[docList['contractID'] == contractID, 'reviewed'].iloc[0]\n contractInfo['endUser']=docList.loc[docList['contractID'] == contractID, 'endUser'].iloc[0]\n contractInfo['region']=docList.loc[docList['contractID'] == contractID, 'region'].iloc[0]\n contractInfo['fiscalYear']=docList.loc[docList['contractID'] == contractID, 'fiscalYear'].iloc[0]\n contractInfo['marketArea']=docList.loc[docList['contractID'] == contractID, 'marketArea'].iloc[0]\n # compute impact factor as revenue * 1-confidence\n dictContract['impactFactor']=float(contractInfo['revenue'] * (1- contractInfo['tfcConfidence']))\n dictContract['data']=contractInfo\n documentTable.append(dictContract)\n\n# order in descending order of impact factor\ndocumentTableSorted= sorted(documentTable, key=itemgetter('impactFactor'), reverse=True)\nprint(\"document table sorted is \",documentTableSorted)\nprint(documentTableSorted[0]['impactFactor'])\ndocumentTable=documentTableSorted\n\ndef samplingData(df, conf):\n data = [] # [[200, 0.7], [10, 1.0], [300, 0.5]]\n data_reviewed = []\n n_reviews = 0\n\n contract_values=df['revenue']\n confidences=conf\n\n for v, c in zip(contract_values, confidences):\n data.append([v, c])\n\n # some arbitrary toy strategy for reviewing\n if rand() > 0.9:\n n_reviews = n_reviews + 1\n data_reviewed.append([v, round(c - 0.2)])\n else:\n data_reviewed.append([v, c])\n\n df = pd.DataFrame(data, columns=['contract-value', 'confidence'])\n\n n_repetitions = 1000\n sample = {}\n\n for contract_value, confidence in data:\n s = np.random.binomial(1, confidence, n_repetitions)\n s = [x * contract_value for x in s]\n sample[str(contract_value) + '@' + str(confidence) + '@' + str(randint(0, 10000000, 1)) ] = s\n\n df_sample_results = pd.DataFrame(sample)\n df_sample_results['total at risk without reviews'] = df_sample_results.sum(axis=1)\n return df_sample_results\n\n\ndef revPlot(dfNotSampled, dfOrig, dfNew, trueReviewsSamples, falseReviewsSamples):\n fig = go.Figure()\n\n dfReviewed=dfNotSampled[dfNotSampled['reviewed']==\"1\"]\n dfNotReviewed=dfNotSampled[dfNotSampled['reviewed']==\"0\"]\n dfReviewedSample= samplingData(dfReviewed,dfReviewed[\"tfcProjection\"])\n dfNotReviewedSample= samplingData(dfNotReviewed,dfNotReviewed[\"tfcProjection\"])\n\n fig.add_trace(go.Box(x=trueReviewsSamples['total at risk without reviews'],\n name=\"All True Reviews\", marker_color = 'steelblue'))\n fig.add_trace(go.Box(x=falseReviewsSamples['total at risk without reviews'],\n name=\"All False Reviews\", marker_color = 'steelblue'))\n fig.add_trace(go.Box(x=dfOrig['total at risk without reviews'],\n name=\"Probabilistic total\", marker_color = 'steelblue'))\n fig.add_trace(go.Box(x=dfReviewedSample['total at risk without reviews'],\n name=\"Probabilistic reviewed\", marker_color='#66c2a5'))\n fig.add_trace(go.Box(x=dfNotReviewedSample['total at risk without reviews'],name=\"Probabilistic not reviewed\", marker_color='#FFA500'))\n fig.add_annotation(\n x=max(trueReviewsSamples['total at risk without reviews']), y=0+0.25, text=f'Maximum possible revenue', yanchor='bottom', showarrow=False, arrowhead=1, arrowsize=1\n , arrowwidth=2, arrowcolor=\"#636363\", ax=-20, ay=-30, font=dict(size=11, color=\"steelblue\", family=\"Sans Serif\"), align=\"left\")\n\n fig.add_annotation(\n x=min(falseReviewsSamples['total at risk without reviews']), y=1 + 0.25, text=f'Minimum possible revenue',\n yanchor='bottom', showarrow=False, arrowhead=1, arrowsize=1\n , arrowwidth=2, arrowcolor=\"#636363\", ax=-20, ay=-30,\n font=dict(size=11, color=\"steelblue\", family=\"Sans Serif\"), align=\"left\")\n\n fig.add_annotation(\n x=statistics.median(dfOrig['total at risk without reviews']), y=2 + 0.25, text=f'Most likely revenue',\n yanchor='bottom', showarrow=False, arrowhead=1, arrowsize=1\n , arrowwidth=2, arrowcolor=\"#636363\", ax=-20, ay=-30,\n font=dict(size=11, color=\"steelblue\", family=\"Sans Serif\"), align=\"left\")\n\n fig.layout.plot_bgcolor = 'white'\n fig.layout.paper_bgcolor = 'white'\n fig.update_layout(\n showlegend=False,\n margin=dict(l=0, r=0, t=0, b=0),\n )\n\n return fig\n\ndef reviewGraph(df):\n # color_discrete_sequence = ['#FFA500', '#66c2a5'],\n fig = px.scatter(df, x=\"revenue\", y=\"tfcConfidence\",color=\"reviewed\",color_discrete_map={\n False: \"#FFA500\",\n True: '#66c2a5'},\n labels={\n \"tfcConfidence\": \"T for C confidence\",\n \"revenue\": \"Contract Value\"\n })\n fig.update_traces(marker_size=5)\n fig.add_vline(x=0, line_width=2, line_dash=\"dash\", line_color=\"steelblue\")\n fig.add_vline(x=max(df['revenue']), line_width=2, line_dash=\"dash\", line_color=\"steelblue\")\n fig.add_hline(y=0.5, line_width=2, line_dash=\"dash\", line_color=\"steelblue\")\n fig.add_hline(y=1, line_width=2, line_dash=\"dash\", line_color=\"steelblue\")\n fig.layout.plot_bgcolor = 'white'\n fig.layout.paper_bgcolor = 'white'\n\n fig.update_layout(\n font_size=10, #tick labels\n showlegend=False,\n margin=dict(l=20, r=20, t=20, b=20),\n )\n fig.update_xaxes(title_font_family=\"Arial\",title_font_size=12 )\n fig.update_yaxes(title_font_family=\"Arial\",title_font_size=12 )\n\n return fig\n\ndef reviewGraphSlider(df,x1,x2,y1,y2):\n fig = px.scatter(df, x=\"revenue\", y=\"tfcConfidence\",color=\"reviewed\", color_discrete_map={\n False: \"#FFA500\",\n True: '#66c2a5'},\n labels={\n \"tfcConfidence\": \"T for C confidence\",\n \"revenue\": \"Contract Value\"\n })\n fig.update_traces(marker_size=5)\n fig.layout.plot_bgcolor = 'white'\n fig.layout.paper_bgcolor = 'white'\n\n fig.add_vline(x=y1, line_width=2, line_dash=\"dash\", line_color=\"steelblue\")\n fig.add_vline(x=y2, line_width=2, line_dash=\"dash\", line_color=\"steelblue\")\n fig.add_hline(y=x1, line_width=2, line_dash=\"dash\", line_color=\"steelblue\")\n fig.add_hline(y=x2, line_width=2, line_dash=\"dash\", line_color=\"steelblue\")\n # fig.update_traces(marker=dict(color='#66c2a5')\n # ,selector=dict(mode='markers'))\n fig.update_layout(\n font_size=10, #tick labels\n showlegend=False,\n margin=dict(l=20, r=20, t=20, b=20),\n )\n fig.update_xaxes(title_font_family=\"Arial\",title_font_size=12 )\n fig.update_yaxes(title_font_family=\"Arial\",title_font_size=12 )\n\n return fig\n\ntestingSection= dbc.Row([\n dbc.Row([\n dbc.Button(\"i\", id=\"testingInfoOpen\", className=\"me-1\", n_clicks=0, color=\"light\",\n style={'margin': '0', 'font-size': 14,\n 'border-radius': 10, 'width': '20px', }),\n html.Header(\"Testing Section\",\n style={'margin':'auto','font-size': 18,\n 'text-align': 'center'}),\n ]),\n dbc.Row([\n html.Header(\"Using the information and features provided below, find the closest possible\"\n \" estimate for the largest revenue at risk due to termination for convenience. \"\n \"You will have up to an hour to complete this task but feel free to submit your answer when\"\n \" you are confident with it. To submit, press the submit button below. Please note that once\"\n \" your answer is submitted, you will not be able to go back to change it.\" ,\n style={'margin-top': '20px','margin-bottom': '0px','font-size': 12,'height': 'auto','width':'auto'}),\n ],style={'height':'auto','padding-right':'200px','padding-left':'200px'}),\n dbc.Row([\n html.Header(html.Br()),\n dbc.Col([html.Header(\"What is your estimate?($)\",style= {'width':'200px','margin-top':'5px','font-size': 12})],width=5),\n dbc.Col([\n dcc.Input(\n id=\"estimateInput\",\n type=\"number\",\n placeholder=\"your answer\",\n style= {'width':'200px','margin-left':'32px','font-size': 12,'align':'left'}\n )\n ])\n ],style={'marginLeft':'100px','marginRight':'100px','padding-right':'200px','padding-left':'200px'}),\n dbc.Row([\n html.Header(html.Br()),\n dbc.Col([html.Header(\"How confident are you in this estimate? (%)\",\n style={'width': '300px', 'margin-top': '5px', 'font-size': 12})],\n width=5),\n dbc.Col([\n dcc.Input(\n id=\"confidenceInput\",\n type=\"number\",\n placeholder=\"your answer\",\n style={'width': '200px', 'margin-left': '32px', 'font-size': 12, 'align': 'left'}\n )\n ])\n ],style={'marginLeft':'100px','marginRight':'100px','padding-right':'200px','padding-left':'200px'}),\n dbc.Row([\n html.Header(html.Br()),\n html.A(html.Button('Submit', id='submitAnswer', n_clicks=0, style={'display':'flex','align-items':'center','justify-content': 'center','font-size': 12}),href=\"/nasa-tlx\", style={'display':'flex','align-items':'center','justify-content': 'center'}),\n dcc.Download(id=\"downloadUserActivity\"),\n ])\n ],style={'background': 'white','color':'#43464B','padding': '20px','margin-right':'10px','margin-top':'10px','border-radius': '6px 6px 6px 6px'})\n\n\nparameterSection= dbc.Col([\n dbc.Row([\n dbc.Button(\"i\", id=\"paramInfoOpen\", className=\"me-1\", n_clicks=0, color=\"light\",\n style={'margin': '0', 'font-size': 14,\n 'border-radius': 10, 'width': '20px', }),\n dbc.Modal(\n [\n dbc.ModalHeader(dbc.ModalTitle(\"Parameters\")),\n dbc.ModalBody(\"Specify the thresholds for the confidence and contract revenue you would like to review. The total number of contracts within those thresholds as well as the confidence and revenue for each contract is displayed in the Overview section\"),\n dbc.ModalFooter(\n dbc.Button(\n \"Close\", id=\"paramClose\", className=\"ms-auto\", n_clicks=0\n )\n ),\n ],\n id=\"paramModal\",\n is_open=False,\n ),\n\n ]),\n dbc.Row([\n html.Header(\"Parameters\",\n style={'margin':'auto','font-size': 18,\n 'text-align': 'center'}),\n ]),\n dbc.Row([\n dbc.Col([html.Header(\"TFC confidence to review\",style={'margin-top': '20px','margin-bottom': '0px', 'margin-left': '40px', 'font-size': 12})]),\n dbc.Col([html.Div([dcc.RangeSlider(0.5, 1, id='slider_confidence', marks=None, step=0.05,value=[0.5,1],tooltip={\"placement\": \"bottom\", \"always_visible\": True})],\n style={'margin-top': '20px','width': '200px', 'padding-top': '5px'})]),\n ]),\n dbc.Row([\n dbc.Col([html.Header(\"Value to review ($)\", style={'margin-bottom': '0px', 'margin-left': '40px', 'font-size': 12})]),\n dbc.Col([html.Div([dcc.RangeSlider(0, max(docList['revenue'])+10, id='slider_revenue', marks=None, step=10,value=[0,max(docList['revenue'])+10],tooltip={\"placement\": \"bottom\", \"always_visible\": True})],\n style={'width': '200px', 'display': 'inline-block', 'padding-top': '5px'})]),\n ]),\n dbc.Row([\n dbc.Col([\n html.Header(\"Region\",\n style={'margin-top': '20px', 'margin-right': '20px',\n 'margin-left': '40px', 'font-size': 12}),\n ]),\n dbc.Col([\n html.Button('All', id='regionAll', n_clicks=0, style={'font-size': 12}),\n html.Button('Americas', id='regionAmericas', n_clicks=0, style={'font-size': 12}), # Region filter\n html.Button('EMEA', id='regionEMEA', n_clicks=0, style={'font-size': 12})\n ])\n ]),\n dbc.Row([\n dbc.Col([\n html.Header(\"Fiscal Year\",\n style={'margin-top': '10px', 'margin-right': '20px', 'margin-bottom': '0px',\n 'margin-left': '40px', 'font-size': 12})\n ]),\n dbc.Col([\n dcc.Dropdown([\"All\"] + list(np.unique(np.array(docList['fiscalYear']))), \"All\",\n id='fiscalYearDropdown', style={'width': '100%', 'padding-right': '10px','font-size':12}),\n ])\n ])\n ],style={'background': 'white','color':'#43464B','padding': '20px','margin-right':'10px','margin-top':'10px','border-radius': '6px 6px 6px 6px'})\n\noverviewSection=dbc.Col([\n dbc.Row([\n dbc.Button(\"i\", id=\"overviewInfoOpen\", className=\"me-1\",n_clicks=0,color=\"light\",style={'margin':'0','font-size': 14,\n'border-radius' : 10,'width':'10px',}),\n dbc.Modal(\n [\n dbc.ModalHeader(dbc.ModalTitle(\"Overview\")),\n dbc.ModalBody(\"This section displays how many contracts are within the Parameters that you set for reviewing. In the graph, you can see each individual contract as a point and see their confidence and value. \"),\n dbc.ModalFooter(\n dbc.Button(\n \"Close\", id=\"overviewClose\", className=\"ms-auto\", n_clicks=0\n )\n ),\n ],\n id=\"overviewModal\",\n is_open=False,\n ),\n ]),\n\n dbc.Row([\n html.Header(\"Overview\",\n style={'margin':'auto', 'font-size': 18,\n 'text-align': 'center'})\n ]),\n # progress bar\n dbc.Row([\n dbc.Col([\n dbc.Progress([\n dbc.Progress(value=0, id=\"progressReviewed\", color=\"#66c2a5\", bar=True),\n dbc.Progress(value=100, id=\"progressNotReviewed\", color=\"#FFA500\", bar=True)\n ], style={'height': \"8px\", \"width\": \"200px\", 'padding': \"0px\", \"font-size\": \"14px\",\n 'border-radius': '12px 12px 12px 12px', 'margin-top': '15px',\n 'margin-left': '100px', 'align': 'center'}),\n html.Header(\"{} reviewed\".format(\n docList[(docList['tfc'] == True) & (docList['reviewed'] == True)].shape[\n 0]),\n id=\"numReviewed\",\n style={'display': 'inline-block', 'text-align': 'center',\n 'margin-right': '10px', 'color': '#66c2a5',\n 'padding': '0px', 'margin-left': \"100px\", 'font-size': '12px',\n 'margin-bottom': '0px'}),\n html.Header(\"{} not reviewed\".format(\n docList[(docList['tfc'] == \"Y\") & (docList['reviewed'] == \"0\")].shape[0]),\n id=\"numNotReviewed\",\n style={'display': 'inline-block', 'text-align': 'right',\n 'margin-right': '10px', 'color': '#FFA500',\n 'padding': '0px', 'margin-left': \"25px\", 'font-size': '12px',\n 'margin-bottom': '0px'})\n ]),\n dbc.Col([\n html.Header(\"{} contracts\".format(docList[docList['tfc'] == True].shape[0]),\n id=\"numReviews\",\n style={'color': '#7E7E7E', 'font-size': '16px','margin-top':'5px'}),\n ])\n ]),\n # review graph\n dbc.Row([\n dcc.Graph(id=\"reviewGraph\", figure=reviewGraph(docList),\n style={'width': '30vh', 'height': '25vh', 'margin-left': '90px', 'margin': 'auto'})\n ]),\n ],style={'background': 'white','color':'#43464B','padding': '20px','margin-right':'10px','margin-top':'10px','border-radius': '6px 6px 6px 6px'})\n\nsampledData1=samplingData(docList, docList['tfcConfidence'])\nsampledData2=samplingData(docList, docList['tfcProjection'])\nsampledData3=samplingData(docList, docList['tfcAllTrue'])\nsampledData4= samplingData(docList, docList['tfcAllFalse'])\n\nlistSampled2= list(sampledData2['total at risk without reviews'])\nmostLikelyRev=mode(listSampled2)\n#mostLikelyRevRange=\nquantiles= list(sampledData2['total at risk without reviews'].quantile([0.25,0.5,0.75]))\nlowerQuantile=quantiles[0]\nmedian= quantiles[1]\nupperQuantile=quantiles[2]\niqr = upperQuantile - lowerQuantile\nupper_whisker = sampledData2['total at risk without reviews'][sampledData2['total at risk without reviews']<=upperQuantile+1.5*iqr].max()\nlower_whisker = sampledData2['total at risk without reviews'][sampledData2['total at risk without reviews']>=lowerQuantile-1.5*iqr].min()\n\nstatsSection= dbc.Col([\n dbc.Row([\n dbc.Button(\"i\", id=\"statsInfoOpen\", className=\"me-1\", n_clicks=0, color=\"light\",\n style={'margin': '0', 'font-size': 14,\n 'border-radius': 10, 'width': '20px', }),\n dbc.Modal(\n [\n dbc.ModalHeader(dbc.ModalTitle(\"Insights\")),\n dbc.ModalBody(\n \"We used a sampling technique to provide statistics for the total estimated revenue at risk from all contracts containing Termination for Convenience clauses. The box plot shows the range of possible values. \"),\n dbc.ModalFooter(\n dbc.Button(\n \"Close\", id=\"statsClose\", className=\"ms-auto\", n_clicks=0\n )\n ),\n ],\n id=\"statsModal\",\n is_open=False,\n ),\n ]),\n dbc.Row([\n html.Header(\"Insights\",\n style={'margin':'auto','font-size': 18,\n 'text-align': 'center'}),\n ]),\n dbc.Row([\n html.Header(\"The most likely total revenue at risk is {}\".format(locale.currency(median,grouping=True)),\n id=\"insight1\",\n style={'margin':'auto','margin-bottom':'5px','margin-top':'20px','font-size': 12,\n 'text-align': 'center'}),\n ]),\n dbc.Row([\n html.Header(\n \"There is a 50% chance that the total revenue at risk is between {} and {}.\".format(locale.currency(lowerQuantile, grouping=True), locale.currency(upperQuantile, grouping=True)),\n id=\"insight2\",\n style={'margin': 'auto', 'margin-bottom': '5px', 'margin-top': '5px', 'font-size': 12,\n 'text-align': 'center'}),\n ]),\n dbc.Row([\n html.Header(\n \"It is highly certain that the total revenue at risk is between {} and {}\".format(locale.currency(lower_whisker, grouping=True), locale.currency(upper_whisker, grouping=True)),\n id=\"insight3\",\n style={'margin': 'auto', 'margin-bottom': '20px', 'margin-top': '5px', 'font-size': 12,\n 'text-align': 'center'}),\n ]),\n #projection graph\n dbc.Row([\n dcc.Graph(id=\"graph-Projections\",figure=revPlot(docList,sampledData1,sampledData2,sampledData3,sampledData4),\n style={'width': '60vh', 'height': '20vh','align':'left','margin-top':'0px','margin':'auto'})\n ])\n],style={'background': 'white','color':'#43464B','padding': '20px','margin-right':'10px','margin-top':'10px','border-radius': '6px 6px 6px 6px'})\n\npdf_viewer = dbc.Col([\n dbc.Row([\n dbc.Button(\"i\", id=\"pdfInfoOpen\", className=\"me-1\", n_clicks=0, color=\"light\",\n style={'margin': '0', 'font-size': 14,\n 'border-radius': 10, 'width': '20px', }),\n dbc.Modal(\n [\n dbc.ModalHeader(dbc.ModalTitle(\"Document Viewer\")),\n dbc.ModalBody(\n \"This is where you review all the documents \"),\n dbc.ModalFooter(\n dbc.Button(\n \"Close\", id=\"pdfClose\", className=\"ms-auto\", n_clicks=0\n )\n ),\n ],\n id=\"pdfModal\",\n is_open=False,\n ),\n ]),\n dbc.Row([\n html.Header(\"Document Review\",\n style={'margin':'auto','font-size': 18,\n 'text-align': 'center'}),\n html.Header(html.Br()),\n\n ]),\n dbc.Row([\n html.Header(\"Click a document in the left side bar to view it as a pdf. The documents in the left sidebar are ordered by highest impact factor first. Head to the right sidebar to confirm or refute TFC clause detection in the document.\",\n style={'margin': 'auto', 'font-size': 14,\n 'text-align': 'center'}),\n html.Header(html.Br()),\n ]),\n dbc.Row(\n [\n dash_pdf_components.DashPdfComponents(\n id='pdf-view',\n label='pdf-view-label',\n pdfRendered=\"DR3215053\",\n apiKey=API_KEY,\n documentTable=documentTable,\n toggle=False\n )\n ],\n id='pdf-col',\n )\n ],style={'background': 'white', 'color': '#43464B', 'padding': '20px', 'margin-right': '10px',\n 'margin-top': '10px', 'border-radius': '6px 6px 6px 6px'})\n\n#\ntimerSection=html.Div([\n dcc.Interval(id='interval1', interval=1 * 1000, n_intervals=0),\n html.H1(id='label1', children='')\n])\n#callback for info buttons\n@callback(Output('overviewModal', 'is_open'),\n [Input('overviewInfoOpen', 'n_clicks'),Input(\"overviewClose\", \"n_clicks\")],\n [State(\"overviewModal\", \"is_open\")])\ndef showOverviewModal(overviewInfoOpen,overviewClose,is_open):\n if overviewClose or overviewInfoOpen:\n return not is_open\n return is_open\n\n@callback(Output('paramModal', 'is_open'),\n [Input('paramInfoOpen', 'n_clicks'),Input(\"paramClose\", \"n_clicks\")],\n [State(\"paramModal\", \"is_open\")])\ndef showParamModal(paramInfoOpen,paramInfoClose,is_open):\n if paramInfoClose or paramInfoOpen:\n return not is_open\n return is_open\n\n@callback(Output('statsModal', 'is_open'),\n [Input('statsInfoOpen', 'n_clicks'),Input(\"statsClose\", \"n_clicks\")],\n [State(\"statsModal\", \"is_open\")])\ndef showStatsModal(statsInfoOpen,statsClose,is_open):\n if statsClose or statsInfoOpen:\n return not is_open\n return is_open\n\n#callback for timer\n# @callback(Output('label1', 'children'),\n# [Input('interval1', 'n_intervals')])\n# def update_interval(n):\n# secondsLeft=900 -n #15 minutes - time elapsed\n# return 'Time Remaining: ' + str(datetime.timedelta(seconds=secondsLeft))\n\n#TODO: automatically submit page when time is over\n\n\n#graph callback\n#TODO: merge with pdf-view callback\n@callback(\n [ Output('reviewGraph', 'figure'),\n Output('graph-Projections', 'figure'),\n Output('numReviews','children'),\n Output('numReviewed','children'),\n Output('numNotReviewed', 'children'),\n Output('progressReviewed','value'),\n Output('progressNotReviewed', 'value'),\n # Output('output_contract', 'children'),\n Output(\"pdf-view\", \"documentTable\"),\n Output(\"insight1\", \"children\"),\n Output(\"insight2\", \"children\"),\n Output(\"insight3\", \"children\")\n ],\n [ Input('slider_confidence', 'value'), #confidence slider\n Input('slider_revenue', 'value'),\n Input('fiscalYearDropdown', 'value'), #fiscal year dropdown filter\n Input('regionAll', 'n_clicks_timestamp'),\n Input('regionAmericas', 'n_clicks_timestamp'),\n Input('regionEMEA', 'n_clicks_timestamp'),\n Input(\"pdf-view\", \"key\"),\n Input(\"pdf-view\", \"pdfRendered\"),\n Input(\"pdf-view\", \"documentTable\"),\n Input(\"pdf-view\", \"toggle\"),\n # mouse events\n Input(\"reviewGraph\", \"hoverData\"),\n Input(\"graph-Projections\",\"hoverData\"),\n Input('estimateInput', 'value'),\n Input('confidenceInput', 'value'),\n Input('submitAnswer', 'n_clicks_timestamp'),\n ]\n) #review sliders min and max\ndef updateGraphs(sliderVal,sliderRev, fiscalYearFilter, regionAll, regionAmericas, regionEMEA,key, currContractId, docTableUpdates, toggle, reviewGraphMouseOn,graphProjectionsMouseOn,estimateInput,confidenceInput, submitAnswer):\n print(\"inside callback\")\n global dfUserActivity\n global docList\n df=docList\n global confidenceParamClicks\n global revenueParamClicks\n global reviewGraphHovers\n global projectionGraphHovers\n global timeStart\n\n #record mouse events\n if reviewGraphMouseOn != None:\n xCoord=reviewGraphMouseOn['points'][0]['x']\n yCoord=reviewGraphMouseOn['points'][0]['y']\n dictHover={\"x\":xCoord,\"y\":yCoord,\"timestamp\":time.time()}\n reviewGraphHovers.append(dictHover)\n\n if graphProjectionsMouseOn != None:\n xCoord=graphProjectionsMouseOn['points'][0]['x']\n yCoord=graphProjectionsMouseOn['points'][0]['y']\n dictHover={\"x\":xCoord,\"y\":yCoord,\"projectionTimestamp\":time.time()}\n projectionGraphHovers.append(dictHover)\n\n elementTriggered=ctx.triggered_id\n print(\"the element triggered is \",elementTriggered)\n #if slider_confidence is changed\n if elementTriggered==\"slider_confidence\":\n confValue0=sliderVal[0]\n confValue1=sliderVal[1]\n confTimestamp=time.time()\n dictConf={\"confValue0\":confValue0, \"confValue1\":confValue1,\"confTimestamp\":confTimestamp}\n confidenceParamClicks.append(dictConf)\n elif elementTriggered==\"slider_revenue\":\n revValue0=sliderRev[0]\n revValue1=sliderRev[1]\n revTimestamp=time.time()\n dictRev={\"revValue0\":revValue0, \"revValue1\":revValue1,\"revTimestamp\":revTimestamp}\n revenueParamClicks.append(dictRev)\n\n button_pressed = np.nanargmax(\n np.array(\n [0, submitAnswer,regionAll, regionAmericas, regionEMEA], dtype=np.float64\n ))\n if button_pressed == 1: # user submitted their answer\n print(\"submit button has been pressed\")\n dfCurrentUser=pd.DataFrame({\"userID\": [uuid.uuid1()], #generate random user ID\n \"timeStart\":[timeStart],\n \"timeEnd\":[time.time()],\n \"estimateInput\":[estimateInput],\n \"confidenceInput\":[confidenceInput],\n \"confParamClicks\": [confidenceParamClicks],\n \"revenueParamClicks\": [revenueParamClicks],\n \"reviewGraphHovers\":[reviewGraphHovers],\n \"projectionGraphHovers\":[projectionGraphHovers],\n \"userReviews\":[contractReviews],})\n\n try: #if df is not empty\n dfUserActivity=pd.read_csv(\"dfUserActivity.csv\",index_col=[0])\n updatedUserActivity=dfUserActivity.append(dfCurrentUser)\n updatedUserActivity.to_csv(\"dfUserActivity.csv\", mode='a',header=False) # append mode\n except:\n updatedUserActivity = dfCurrentUser #if df is empty\n updatedUserActivity.to_csv(\"dfUserActivity.csv\", mode='a') # append mode\n #updatedUserActivity.to_csv(\"dfUserActivity.csv\",mode='a') #append mode\n\n #update docList based on reviews\n for item in docTableUpdates:\n if item[\"contractId\"] == currContractId:\n itemChanged= item[\"data\"][\"highlightsArr\"][0][\"creator\"] #item that is being changed\n #update dataframe for this contract\n docList['reviewed']=docList.apply(lambda x: itemChanged['isReviewed'] if x['contractID']==currContractId else x['reviewed'], axis=1)\n docList['tfc']=docList.apply(lambda x: itemChanged['isCorrect'] if x['contractID']==currContractId else x['tfc'], axis=1)\n print(\"contract number \", currContractId,\" is being reviewed\")\n print(\"is reviewed is \", itemChanged['isReviewed'])\n #itemChanged['isReviewed'] indicates when item has been reviewed\n #create timestamp here with review (approve or refute)\n if itemChanged['isReviewed']:\n contractReviews.append({\"contractID\":currContractId,\"timeReviewed\":time.time(),\"isTFCCorrect\":itemChanged['isCorrect']})\n\n #==Filters==\n if fiscalYearFilter!=\"All\":\n df = df[df['fiscalYear'] == fiscalYearFilter]\n title = \"Total Revenue at Risk for %s\" % (fiscalYearFilter)\n else:\n title=\"Total Revenue at Risk\"\n\n #region buttons\n\n if button_pressed==3:\n df = df[df['region'] == \"Americas\"]\n title = title + \" in the Americas\"\n elif button_pressed==4:\n df = df[df['region'] == \"EMEA\"]\n title = title + \" in EMEA\"\n\n df['tfcProjection']=df.apply(lambda x: 1.0 if x['reviewed']==True else x['tfcConfidence'], axis=1)\n df['tfcAllTrue'] = df.apply(lambda x: x['tfcProjection'] if x['tfc'] == True and ( float(x['revenue']) > sliderRev[1] or float(x['revenue'] < sliderRev[0]) or float(x['tfcProjection']) > sliderVal[1] or float(x['tfcProjection']) < sliderVal[0]) else 1.0, axis=1)\n df['tfcAllFalse'] = df.apply(lambda x: x['tfcProjection'] if x['tfc'] == True and ( float(x['revenue']) > sliderRev[1] or float(x['revenue'] < sliderRev[0]) or float(x['tfcProjection']) > sliderVal[1] or float(x['tfcProjection']) < sliderVal[0]) else 0.0, axis=1)\n newDocumentTable=[]\n for item in docTableUpdates:\n if (item['data']['revenue'] < sliderRev[1] and item['data']['revenue'] > sliderRev[0]) and (item['data']['tfcConfidence'] < sliderVal[1] and item['data']['tfcConfidence'] > sliderVal[0]):\n newDocumentTable.append(item) #add item to newDocumentTable\n\n\n # print(\"length newDocumentTable is \",len(newDocumentTable))\n #======create sampling data for box plot=====\n origData=samplingData(df,df['tfcProjection'])\n allTrueSampled=samplingData(df,df['tfcAllTrue'])\n allFalseSampled=samplingData(df,df['tfcAllFalse'])\n\n listSampled2 = list(origData['total at risk without reviews'])\n quantiles = list(origData['total at risk without reviews'].quantile([0.25, 0.5, 0.75]))\n lowerQuantile = quantiles[0]\n median = quantiles[1]\n upperQuantile = quantiles[2]\n iqr = upperQuantile - lowerQuantile\n upper_whisker = origData['total at risk without reviews'][\n sampledData2['total at risk without reviews'] <= upperQuantile + 1.5 * iqr].max()\n lower_whisker = origData['total at risk without reviews'][\n sampledData2['total at risk without reviews'] >= lowerQuantile - 1.5 * iqr].min()\n\n #update insights\n insight1Text= \"The most likely total revenue at risk is {}\".format(locale.currency(median,grouping=True))\n insight2Text= \"There is a 50% chance that the total revenue at risk is between {} and {}.\".format(locale.currency(lowerQuantile, grouping=True), locale.currency(upperQuantile, grouping=True))\n insight3Text= \"It is highly certain that the total revenue at risk is between {} and {}\".format(locale.currency(lower_whisker, grouping=True), locale.currency(upper_whisker, grouping=True)),\n\n # ====display quantities for total, reviewed, not reviewed=====\n dfTotalToReview= df[ (df['tfcConfidence']> sliderVal[0]) & (df['tfcConfidence']< sliderVal[1])]\n dfTotalToReview= dfTotalToReview[ (dfTotalToReview['revenue']> sliderRev[0]) & (dfTotalToReview['revenue']< sliderRev[1])]\n dfTotalToReview['tfcProjection']=dfTotalToReview.apply(lambda x: 1.0 if x['reviewed']==True else x['tfcConfidence'], axis=1)\n\n if dfTotalToReview.empty:\n numReviews=0\n else:\n numReviews=dfTotalToReview.shape[0]\n reviewTitle=\"{} contracts\".format(int(numReviews))\n\n dfReviewed= dfTotalToReview[dfTotalToReview['reviewed']==True]\n if dfReviewed.empty:\n numReviewed=0\n else:\n numReviewed=dfReviewed.shape[0]\n numReviewedText=\"{} reviewed\".format(int(numReviewed))\n\n dfNotReviewed= dfTotalToReview[dfTotalToReview['reviewed']==False]\n if dfNotReviewed.empty:\n numNotReviewed=0\n else:\n numNotReviewed=dfNotReviewed.shape[0]\n numNotReviewedText=\"{} not reviewed\".format(int(numNotReviewed))\n\n progressReviewed=(int(numReviewed)/(int(numNotReviewed)+int(numReviewed)))*100\n progressNotReviewed=(int(numNotReviewed)/(int(numNotReviewed)+int(numReviewed)))*100\n\n return (reviewGraphSlider(df,sliderVal[0],sliderVal[1],sliderRev[0],sliderRev[1]),revPlot(dfTotalToReview,origData,origData,allTrueSampled,allFalseSampled) ,reviewTitle, numReviewedText, numNotReviewedText,progressReviewed,progressNotReviewed,newDocumentTable, insight1Text,insight2Text,insight3Text)\n\n\nlayout = html.Div(\n [\n dbc.Row([testingSection,overviewSection,parameterSection, statsSection]),\n dbc.Row(pdf_viewer),\n ]\n)\n\n# if __name__ == \"__main__\":\n# app.run_server(debug=True)\n","sub_path":"DocSpect-main/dash_pdf_components/apps/mainPage.py","file_name":"mainPage.py","file_ext":"py","file_size_in_byte":41867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"484386503","text":"# 空间复杂度(1),查询链表是否有环\n\ndef find_cycle(node):\n if not node:\n return False\n\n slow = fast = node\n while fast:\n fast = fast.next\n if not fast: # 快的指针到了链表末尾,说明没有环\n return False\n if fast is slow: # 快的指针追上了慢的指针,说明有环\n return True\n fast = fast.next\n if fast is slow:\n return True\n slow = slow.next\n return False\n\n\"\"\" 也是一快一慢两个指针,如果链表有环,那么快的指针会绕到慢的指针的后面,然后追上来。\n只要看快的指针是否跟慢的指针重合,就知道是否有环了 \"\"\"\n","sub_path":"Practice/Python/小实现/find_cycle.py","file_name":"find_cycle.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"150506129","text":"from algo1 import Array, String, concat\nfrom hashmap import HashMap, hashmap_insert, hashmap_search\nfrom linkedlist import LinkedList, Node, delete as list_delete, length, append\n\n\nclass Trie:\n root = None\n\n\nclass TrieNode:\n parent = None\n children = None\n key = None\n isEndOfWord = False\n # Contador de repeticiones de una palabra en cada doc\n rep = None\n\n\n\"\"\"-Insert(T, element, doc): inserta element en T y contabiliza las incidencias en doc-\"\"\"\n\n\ndef insert(T, element, doc, lenD):\n if T.root is None:\n T.root = TrieNode()\n T.root.children = LinkedList()\n T.root.children.head = Node()\n T.root.children.head.value = TrieNode()\n T.root.children.head.value.parent = T.root\n T.root.children.head.value.key = to_upp(element[0])\n\n return _insert(T.root.children.head.value, element, 0, doc, lenD)\n\n\ndef _insert(node, c, i, doc, lenD):\n # Si la key del TrieNode no coincide con el char ...\n if node.key != to_upp(c[i]):\n # Se sigue buscando en los hermanos del TrieNode ...\n cn = node.parent.children.head\n while cn is not None:\n # Si un hno coincide, se llama la función desde este\n if cn.value.key == to_upp(c[i]):\n return _insert(cn.value, c, i, doc, lenD)\n\n if cn.nextNode is None:\n temp = cn\n cn = cn.nextNode\n # Si ningún hno coincide, se agrega uno que lo haga\n temp.nextNode = Node()\n temp.nextNode.value = TrieNode()\n temp.nextNode.value.parent = node.parent\n temp.nextNode.value.key = to_upp(c[i])\n return _insert(temp.nextNode.value, c, i, doc, lenD)\n\n else:\n if len(c) - 1 == i:\n if not node.isEndOfWord:\n D = HashMap()\n node.rep = D\n node.isEndOfWord = True\n\n temp = hashmap_search(node.rep, doc, lenD)\n if temp:\n temp.value += 1\n else:\n hashmap_insert(node.rep, doc, lenD)\n\n return node\n # Si no es final de palabra ...\n else:\n # y tiene hijos, llamada recursiva\n if node.children is not None:\n return _insert(node.children.head.value, c, i+1, doc, lenD)\n # y no tiene hijos, se crea el TrieNode corresp y llamada recursiva\n else:\n node.children = LinkedList()\n node.children.head = Node()\n node.children.head.value = TrieNode()\n node.children.head.value.key = to_upp(c[i+1])\n node.children.head.value.parent = node\n return _insert(node.children.head.value, c, i+1, doc, lenD)\n\n\n\"\"\"-Search(T, element): Devuelve el último nodo de element dentro de T-\"\"\"\n\n\ndef search(T, element):\n if T.root is None:\n return False\n\n return _search(T.root.children.head.value, element, 0)\n\n\ndef _search(node, c, i):\n # Si la key del TrieNode no coincide con el char ...\n if node.key != to_upp(c[i]):\n # Se sigue buscando en los hermanos del TrieNode ...\n if node.parent.children is not None:\n cn = node.parent.children.head\n while cn is not None:\n # Si un hno coincide, se llama la función desde este\n if cn.value.key == to_upp(c[i]):\n return _search(cn.value, c, i)\n cn = cn.nextNode\n # Si el TrieNode no tiene hno, la palabra no existe\n return False\n\n else:\n if len(c) - 1 == i:\n if node.isEndOfWord:\n return node\n return False\n # Si no es final de palabra ...\n else:\n # y tiene hijos, llamada recursiva\n if node.children is not None and length(node.children) > 0:\n return _search(node.children.head.value, c, i+1)\n # y no tiene hijos, la palabra no existe\n else:\n return False\n\n\n\"\"\"-Delete(T, element): elimina element de Trie-\"\"\"\n\n\ndef delete(T, element):\n if T.root is None:\n return False\n # Se busca el último nodo del elemento en el trie\n node = _search(T.root.children.head.value, element, 0)\n # Si el elemento no está en el nodo, return False\n if node is None:\n return False\n\n return _delete(node)\n# Se elimina desde el final del elemento hacía arriba.\n\n\ndef _delete(node):\n # Si el elemento está contenido dentro de otro se desmarca eow.\n if node.children is not None and node.isEndOfWord:\n node.isEndOfWord = False\n return True\n\n while node.isEndOfWord or node.key is not None:\n # Si elemento comparte segmentos con otra palabra, se termina el proceso de eliminación\n if node.children is not None:\n break\n # Si no lo hace, se desvincula el nodo\n list_delete(node.parent.children, node)\n node.children = None\n node = node.parent\n\n return True\n\n\n\"\"\"-get_words(T): Devuelve una lista de todos los elementos en Trie-\"\"\"\n\n\ndef get_words(T):\n if T.root is None or T.root.children is None:\n return None\n # LD donde se almacenan palabras.\n li = LinkedList()\n _get_words(T.root, li)\n return li\n\n\ndef _get_words(node, li, i=0, word=Array(33, 'c')):\n if node.key is None:\n cn = node.children.head\n while cn is not None:\n _get_words(cn.value, li)\n cn = cn.nextNode\n return\n\n if node.isEndOfWord:\n word[i] = node.key\n # caracter que denota final de palabra\n word[i + 1] = '/'\n # se crea una String con la palabra contenida en el Array\n string = get_string(word)\n append(li, string)\n\n if node.children is not None:\n cn = node.children.head\n while cn is not None:\n _get_words(cn.value, li, i + 1)\n cn = cn.nextNode\n\n else:\n word[i] = node.key\n cn = node.children.head\n while cn is not None:\n _get_words(cn.value, li, i + 1)\n cn = cn.nextNode\n\n\ndef get_string(a):\n s = String('')\n for i in range(len_array_word(a)):\n s = concat(s, String(a[i]))\n return s\n\n\ndef len_array_word(word):\n for i in range(33):\n if word[i] == '/':\n return i\n\n\ndef to_upp(c):\n if ord(c) > 96 and ord(c) < 123:\n return chr(ord(c) - ord('a') + ord('A'))\n else:\n return c\n","sub_path":"personal_library/trie.py","file_name":"trie.py","file_ext":"py","file_size_in_byte":6419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"422322683","text":"import numpy as np\nfrom lxml import etree\nfrom ._resources import gml_schema\nfrom ._models.dimension import Dimension, RatioDimension, QuadrantDivider\nfrom ._models.vertex import Vertex\nfrom flowkit import Matrix\nfrom ._models.transforms import gml_transforms\nfrom ._models.gates.gml_gates import \\\n GMLBooleanGate, \\\n GMLEllipsoidGate, \\\n GMLQuadrantGate, \\\n GMLPolygonGate, \\\n GMLRectangleGate\n\n\ndef parse_gatingml_file(gating_ml_file_path):\n xml_document = etree.parse(gating_ml_file_path)\n\n val = gml_schema.validate(xml_document)\n\n if not val:\n raise ValueError(\"Document is not valid GatingML\")\n\n root = xml_document.getroot()\n\n gating_ns = None\n data_type_ns = None\n transform_ns = None\n\n # find GatingML target namespace in the map\n for ns, url in root.nsmap.items():\n if url == 'http://www.isac-net.org/std/Gating-ML/v2.0/gating':\n gating_ns = ns\n elif url == 'http://www.isac-net.org/std/Gating-ML/v2.0/datatypes':\n data_type_ns = ns\n elif url == 'http://www.isac-net.org/std/Gating-ML/v2.0/transformations':\n transform_ns = ns\n\n if gating_ns is None:\n raise ValueError(\"GatingML namespace reference is missing from GatingML file\")\n\n return root, gating_ns, data_type_ns, transform_ns\n\n\ndef construct_gates(gating_strategy, root_gml):\n # map GatingML gate keys to our GML gate classes\n gate_constructor_lut = {\n 'RectangleGate': GMLRectangleGate,\n 'PolygonGate': GMLPolygonGate,\n 'EllipsoidGate': GMLEllipsoidGate,\n 'QuadrantGate': GMLQuadrantGate,\n 'BooleanGate': GMLBooleanGate\n }\n\n gates_dict = {}\n\n for gate_str, gate_class in gate_constructor_lut.items():\n gt_gates = root_gml.findall(\n ':'.join([gating_strategy.gating_ns, gate_str]),\n root_gml.nsmap\n )\n\n for gt_gate in gt_gates:\n g = gate_class(\n gt_gate,\n gating_strategy.gating_ns,\n gating_strategy.data_type_ns,\n gating_strategy\n )\n\n if g.id in gates_dict:\n raise ValueError(\n \"Gate '%s' already exists. \"\n \"Duplicate gate IDs are not allowed.\" % g.id\n )\n gates_dict[g.id] = g\n\n return gates_dict\n\n\ndef construct_transforms(root_gml, transform_ns, data_type_ns):\n transformations = {}\n\n if transform_ns is not None:\n # types of transforms include:\n # - ratio\n # - log10\n # - asinh\n # - hyperlog\n # - linear\n # - logicle\n xform_els = root_gml.findall(\n '%s:transformation' % transform_ns,\n namespaces=root_gml.nsmap\n )\n\n for xform_el in xform_els:\n xform = None\n\n # determine type of transformation\n fratio_els = xform_el.findall(\n '%s:fratio' % transform_ns,\n namespaces=root_gml.nsmap\n )\n\n if len(fratio_els) > 0:\n xform = gml_transforms.RatioGMLTransform(\n xform_el,\n transform_ns,\n data_type_ns\n )\n\n flog_els = xform_el.findall(\n '%s:flog' % transform_ns,\n namespaces=root_gml.nsmap\n )\n\n if len(flog_els) > 0:\n xform = gml_transforms.LogGMLTransform(\n xform_el,\n transform_ns\n )\n\n fasinh_els = xform_el.findall(\n '%s:fasinh' % transform_ns,\n namespaces=root_gml.nsmap\n )\n\n if len(fasinh_els) > 0:\n xform = gml_transforms.AsinhGMLTransform(\n xform_el,\n transform_ns\n )\n\n hyperlog_els = xform_el.findall(\n '%s:hyperlog' % transform_ns,\n namespaces=root_gml.nsmap\n )\n\n if len(hyperlog_els) > 0:\n xform = gml_transforms.HyperlogGMLTransform(\n xform_el,\n transform_ns\n )\n\n flin_els = xform_el.findall(\n '%s:flin' % transform_ns,\n namespaces=root_gml.nsmap\n )\n\n if len(flin_els) > 0:\n xform = gml_transforms.LinearGMLTransform(\n xform_el,\n transform_ns\n )\n\n logicle_els = xform_el.findall(\n '%s:logicle' % transform_ns,\n namespaces=root_gml.nsmap\n )\n\n if len(logicle_els) > 0:\n xform = gml_transforms.LogicleGMLTransform(\n xform_el,\n transform_ns\n )\n\n if xform is not None:\n transformations[xform.id] = xform\n\n return transformations\n\n\ndef construct_matrices(root_gml, transform_ns, data_type_ns):\n comp_matrices = {}\n\n if transform_ns is not None:\n # comp matrices are defined by the 'spectrumMatrix' element\n matrix_els = root_gml.findall(\n '%s:spectrumMatrix' % transform_ns,\n namespaces=root_gml.nsmap\n )\n\n for matrix_el in matrix_els:\n matrix = parse_matrix_element(\n matrix_el,\n transform_ns,\n data_type_ns\n )\n\n comp_matrices[matrix.id] = matrix\n\n return comp_matrices\n\n\ndef find_attribute_value(xml_el, namespace, attribute_name):\n attribs = xml_el.xpath(\n '@%s:%s' % (namespace, attribute_name),\n namespaces=xml_el.nsmap\n )\n\n if len(attribs) > 1:\n raise ValueError(\n \"Multiple %s attributes found (line %d)\" % (\n attribute_name, xml_el.sourceline\n )\n )\n elif len(attribs) == 0:\n return None\n\n return attribs[0]\n\n\ndef parse_gate_element(\n gate_element,\n gating_namespace,\n data_type_namespace\n):\n gate_id = find_attribute_value(gate_element, gating_namespace, 'id')\n parent_id = find_attribute_value(gate_element, gating_namespace, 'parent_id')\n\n # most gates specify dimensions in the 'dimension' tag,\n # but quad gates specify dimensions in the 'divider' tag\n div_els = gate_element.findall(\n '%s:divider' % gating_namespace,\n namespaces=gate_element.nsmap\n )\n\n dimensions = [] # may actually be a list of dividers\n\n if len(div_els) == 0:\n dim_els = gate_element.findall(\n '%s:dimension' % gating_namespace,\n namespaces=gate_element.nsmap\n )\n\n dimensions = []\n\n for dim_el in dim_els:\n dim = parse_dimension_element(dim_el, gating_namespace, data_type_namespace)\n dimensions.append(dim)\n else:\n for div_el in div_els:\n dim = parse_divider_element(div_el, gating_namespace, data_type_namespace)\n dimensions.append(dim)\n\n return gate_id, parent_id, dimensions\n\n\ndef parse_dimension_element(\n dim_element,\n gating_namespace,\n data_type_namespace\n):\n compensation_ref = find_attribute_value(dim_element, gating_namespace, 'compensation-ref')\n transformation_ref = find_attribute_value(dim_element, gating_namespace, 'transformation-ref')\n\n range_min = None\n range_max = None\n\n # should be 0 or only 1 'min' attribute (same for 'max')\n _min = find_attribute_value(dim_element, gating_namespace, 'min')\n _max = find_attribute_value(dim_element, gating_namespace, 'max')\n\n if _min is not None:\n range_min = float(_min)\n if _max is not None:\n range_max = float(_max)\n\n # label be here\n fcs_dim_el = dim_element.find(\n '%s:fcs-dimension' % data_type_namespace,\n namespaces=dim_element.nsmap\n )\n\n # if no 'fcs-dimension' element is present, this might be a\n # 'new-dimension' made from a transformation on other dims\n if fcs_dim_el is None:\n new_dim_el = dim_element.find(\n '%s:new-dimension' % data_type_namespace,\n namespaces=dim_element.nsmap\n )\n if new_dim_el is None:\n raise ValueError(\n \"Dimension invalid: neither fcs-dimension or new-dimension \"\n \"tags found (line %d)\" % dim_element.sourceline\n )\n\n # if we get here, there should be a 'transformation-ref' attribute\n ratio_xform_ref = find_attribute_value(new_dim_el, data_type_namespace, 'transformation-ref')\n\n if ratio_xform_ref is None:\n raise ValueError(\n \"New dimensions must provid a transform reference (line %d)\" % dim_element.sourceline\n )\n dimension = RatioDimension(\n ratio_xform_ref,\n compensation_ref,\n transformation_ref,\n range_min=range_min,\n range_max=range_max\n )\n else:\n label = find_attribute_value(fcs_dim_el, data_type_namespace, 'name')\n if label is None:\n raise ValueError(\n 'Dimension name not found (line %d)' % fcs_dim_el.sourceline\n )\n\n dimension = Dimension(\n label,\n compensation_ref,\n transformation_ref,\n range_min=range_min,\n range_max=range_max\n )\n\n return dimension\n\n\ndef parse_divider_element(divider_element, gating_namespace, data_type_namespace):\n # Get'id' (present in quad gate dividers)\n dimension_id = find_attribute_value(divider_element, gating_namespace, 'id')\n\n compensation_ref = find_attribute_value(divider_element, gating_namespace, 'compensation-ref')\n transformation_ref = find_attribute_value(divider_element, gating_namespace, 'transformation-ref')\n\n # label be here\n fcs_dim_el = divider_element.find(\n '%s:fcs-dimension' % data_type_namespace,\n namespaces=divider_element.nsmap\n )\n\n label = find_attribute_value(fcs_dim_el, data_type_namespace, 'name')\n if label is None:\n raise ValueError(\n 'Divider dimension name not found (line %d)' % fcs_dim_el.sourceline\n )\n\n values = [] # quad gate dims can have multiple values\n\n # values in gating namespace, ok if not present\n value_els = divider_element.findall(\n '%s:value' % gating_namespace,\n namespaces=divider_element.nsmap\n )\n\n for value in value_els:\n values.append(float(value.text))\n\n divider = QuadrantDivider(dimension_id, label, compensation_ref, values, transformation_ref)\n\n return divider\n\n\ndef parse_vertex_element(vert_element, gating_namespace, data_type_namespace):\n coordinates = []\n\n coord_els = vert_element.findall(\n '%s:coordinate' % gating_namespace,\n namespaces=vert_element.nsmap\n )\n\n if len(coord_els) != 2:\n raise ValueError(\n 'Vertex must contain 2 coordinate values (line %d)' % vert_element.sourceline\n )\n\n # should be 0 or only 1 'min' attribute,\n for coord_el in coord_els:\n value = find_attribute_value(coord_el, data_type_namespace, 'value')\n if value is None:\n raise ValueError(\n 'Vertex coordinate must have only 1 value (line %d)' % coord_el.sourceline\n )\n\n coordinates.append(float(value))\n\n return Vertex(coordinates)\n\n\ndef parse_matrix_element(\n matrix_element,\n xform_namespace,\n data_type_namespace\n):\n matrix_id = find_attribute_value(matrix_element, xform_namespace, 'id')\n fluorochomes = []\n detectors = []\n matrix = []\n\n fluoro_el = matrix_element.find(\n '%s:fluorochromes' % xform_namespace,\n namespaces=matrix_element.nsmap\n )\n\n fcs_dim_els = fluoro_el.findall(\n '%s:fcs-dimension' % data_type_namespace,\n namespaces=matrix_element.nsmap\n )\n\n for dim_el in fcs_dim_els:\n label = find_attribute_value(dim_el, data_type_namespace, 'name')\n\n if label is None:\n raise ValueError(\n 'Dimension name not found (line %d)' % dim_el.sourceline\n )\n fluorochomes.append(label)\n\n detectors_el = matrix_element.find(\n '%s:detectors' % xform_namespace,\n namespaces=matrix_element.nsmap\n )\n\n fcs_dim_els = detectors_el.findall(\n '%s:fcs-dimension' % data_type_namespace,\n namespaces=matrix_element.nsmap\n )\n\n for dim_el in fcs_dim_els:\n label = find_attribute_value(dim_el, data_type_namespace, 'name')\n\n if label is None:\n raise ValueError(\n 'Dimension name not found (line %d)' % dim_el.sourceline\n )\n detectors.append(label)\n\n spectrum_els = matrix_element.findall(\n '%s:spectrum' % xform_namespace,\n namespaces=matrix_element.nsmap\n )\n\n for spectrum_el in spectrum_els:\n matrix_row = []\n\n coefficient_els = spectrum_el.findall(\n '%s:coefficient' % xform_namespace,\n namespaces=matrix_element.nsmap\n )\n\n for co_el in coefficient_els:\n value = find_attribute_value(co_el, xform_namespace, 'value')\n if value is None:\n raise ValueError(\n 'Matrix coefficient must have only 1 value (line %d)' % co_el.sourceline\n )\n\n matrix_row.append(float(value))\n\n matrix.append(matrix_row)\n\n matrix = np.array(matrix)\n\n return Matrix(matrix_id, fluorochomes, detectors, matrix)\n","sub_path":"flowkit/_gml_utils.py","file_name":"_gml_utils.py","file_ext":"py","file_size_in_byte":13530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"283769182","text":"\"\"\"\nAuthor:\nTymoteusz Mirski\nIgor Motowidło\n\"\"\"\n\n\nimport os\nimport requests as r\nfrom bs4 import BeautifulSoup\nimport pdfkit\nimport time\nimport multiprocessing \nimport sys\nimport subprocess\nimport argparse\n\n\ndef get_article_links_from_google(query, count):\n \"\"\"\n Get article links from Google Search articles tab.\n\n Parameters\n ----------\n query : string\n Search query.\n count : int\n Number of links to get.\n\n Returns\n -------\n list\n URLs of the articles.\n\n \"\"\"\n url = \"http://google.com/search\"\n position = 0\n max_requests = 3\n req_cnt = 0\n links = []\n while len(links) < count and req_cnt < max_requests:\n params = { \"q\": query, \"tbm\": \"nws\", \"start\": position }\n page = r.get(url, params=params).text\n soup = BeautifulSoup(page, \"html.parser\")\n for a in soup.find_all(\"a\"):\n link = a.get(\"href\")\n if not link.startswith(\"/url\") or \"google\" in link:\n continue\n link = link[7:]\n link = link.split(\"&\", 1)[0]\n if link not in links:\n links.append(link)\n req_cnt += 1\n position += 10\n return links[:count]\n\n\ndef save_webpage_as_pdf(url, filename):\n \"\"\"\n Render and save website to a pdf file.\n\n Parameters\n ----------\n url : string\n Address of the website.\n filename : string\n Name of the output pdf file.\n\n Returns\n -------\n None.\n\n \"\"\"\n try:\n pdfkit.from_url(url, filename, {\"quiet\":\"\"})\n except:\n pass\n\n\ndef main():\n \"\"\"\n Gets links of articles by usage of get_article_links_from_google function\n then enumerates through the links array and calls save_webpage_as_pdf in single thread one for each link.\n \"\"\"\n query = \"nvidia\"\n count = 5\n output_dir = \"scrape_output\" \n ap = argparse.ArgumentParser()\n ap.add_argument(\"-q\", \"--query\", required=False,\n help=\"Google search query\",\n default=query, metavar=\"query\") \n ap.add_argument(\"-c\", \"--count\", required=False, type=int,\n help=\"number of articles to get\", \n default=count) \n ap.add_argument(\"-d\", \"--dir\", required=False,\n help=\"Output directory\",\n default=output_dir, metavar=\"directory\") \n args = vars(ap.parse_args())\n query = args[\"query\"]\n count = args[\"count\"]\n output_dir = args[\"dir\"]\n\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n links = get_article_links_from_google(query, count)\n processes = []\n for i, link in enumerate(links):\n process = multiprocessing.Process(target=save_webpage_as_pdf, args=(link, f\"{output_dir}/{i+1}.pdf\"))\n process.start()\n processes.append(process)\n time.sleep(10)\n # Making sure that process of wkhtmltopdf.exe has been stopped\n subprocess.Popen([\"powershell.exe\", \"./kill.ps1\"], stdout=subprocess.DEVNULL)\n for process in processes:\n process.terminate()\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"scraper_n_socket/webscrape.py","file_name":"webscrape.py","file_ext":"py","file_size_in_byte":3119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"99527317","text":"import pandas\nimport matplotlib.pyplot as plt\n\nxl = pandas.ExcelFile('Украина - Киев - База предприятий 11.2013 (50201).xlsx')\ndf = xl.parse(xl.sheet_names[0])\n\ndf['number'] = df.iloc[1, 1]\n\nprint(df['number'])\n\ncnt = [i for i in range(23)]\n\n# plt.scatter(cnt, df['numbers'])\n# plt.show()\n","sub_path":"kiev_alternate.py","file_name":"kiev_alternate.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"472671935","text":"from pylab import *\nimport subprocess as sp\nimport os\nrcParams.update({'font.size':48, 'text.usetex': True})\n\n\ndef getEfermi():\n efermi = []\n folder = '.'\n f = open(folder + '/vasprun.xml', 'r')\n while True:\n line = f.readline()\n if \"efermi\" in line:\n efermi.append(line.split()[2])\n break\n return array(list(map(float,efermi)))\n\ndef getnbands():\n output = sp.Popen([\"grep NBANDS vasprun.xml | head -n 1 | awk '{print $4}'\"],shell=True,stdout=sp.PIPE).communicate()[0].decode()\n nbands = int(str(output).split('<')[0])\n return nbands\n\n \nif __name__ == '__main__':\n efermi = getEfermi()\n nbands = getnbands()\n print('Found nbands = ', nbands)\n print('E_f = ', efermi[0], ' eV')\n\n bands = genfromtxt('wannier90_band.dat')\n n = shape(bands)[0]\n nx = int(n/nbands)\n\n be = bands[:,1].reshape((nbands,nx))\n bk = bands[:,0].reshape((nbands,nx))\n\n xmax = max(bk[0,:])\n gmk = array([0.00000, 1.01936, 1.60782,2.78476])*xmax/2.78476\n\n ec = amin(be[26,:])\n ev = amax(be[25,:])\n print('Ec-Ev = ', ec-ev, ' eV')\n \n elow = be[0,0]\n elowvar = amax(be[0,:]) - amin(be[0,:])\n print('elow=', elow, ' eV with width = ', elowvar, ' eV')\n print('ev-elow=',ev-elow)\n print('ec-elow=',ec-elow)\n \n figure(figsize=(12,10))\n for i in range(nbands):\n plot(bk[i,:],be[i,:]-efermi,color='k')\n \n axhline(ec-efermi,color='r',lw=2)\n axhline(ev-efermi,color='g',lw=2)\n axhline(efermi-efermi,color='b',lw=1)\n xlim(0,xmax)\n ylim(-5,5)\n for kp in gmk:\n axvline(kp, color='k',lw=1)\n\n xticks(gmk, ['$\\Gamma$', '$\\mathrm{M}$', '$\\mathrm{K}$', '$\\Gamma$'])\n ylabel('Energy (eV)')\n tight_layout()\n show()\n","sub_path":"vasp/gw/2-scf/relax/scf/plot-bands.py","file_name":"plot-bands.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"32177808","text":"import webbrowser\nimport datetime\nimport re\nfrom time import sleep\nfrom sys import argv\n\nalarm_time = datetime.timedelta()\nalarm_hour = 0\nalarm_minute = 0\nurl = \"https://www.youtube.com/watch?v=lgtoypeY9yg&list=PLLU7Oh2-moMV2MEeCt6GgXSCCaSlP3LIR\"\n\n#-Checking for wakeup time or asking for it----------------------\nif len(argv) > 1:\n\tintime = datetime.datetime.strptime(str(argv[1]), \"%H%M\").time()\n\talarm_hour = intime.hour\n\talarm_minute = intime.minute\n\nelse:\n\tprint(\"What time do you want to wake up?\\n\")\n\n\tprint(\"Enter hour (0-23)\")\n\talarm_hour =int(input(\">>> \"))\n\n\tprint(\"\\nEnter minutes(0-59)\")\n\talarm_minute = int(input(\">>> \"))\n#----------------------------------------------------------------\n\n#-Checking if there is a URL or using the default----------------\nif len(argv) > 2:\n\t\turl = str(argv[2])\n#----------------------------------------------------------------\n\n#-Enabling autoplay if not set-----------------------------------\nif re.match(r\"&autoplay=1\", url):\n\tpass\nelse:\n\turl += \"&autoplay=1\"\n#----------------------------------------------------------------\n\n\nntime = datetime.datetime.now()\n\ncurrent_time = datetime.timedelta(hours = ntime.hour, minutes = ntime.minute, seconds = ntime.second)\n\nalarm_time = datetime.timedelta(hours = alarm_hour, minutes = alarm_minute, seconds = 0)\n\nsleep_time = alarm_time - current_time\n\n\nprint(\"\\n\\n Current Time:\")\nprint(\" \", current_time)\n\nprint(\"\\n Alarm Time:\")\nif sleep_time < datetime.timedelta():\n\tprint(\" Tomorrow\")\n\tsleep_time += datetime.timedelta(days = 1)\nelse:\n\tprint(\" Today\")\nprint(\" \", alarm_time)\n\nprint(\"\\n Amount of sleep:\")\nprint(\" \", sleep_time)\n\n\nsleep(sleep_time.total_seconds())\n\nwebbrowser.open(url, new=0)\n","sub_path":"PlaylistAlarm.py","file_name":"PlaylistAlarm.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"560736178","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef get_axis(ax, default_rows, default_columns, **default_kwargs):\n \"\"\"Verifies the provided axis is of the correct shape, and creates one if needed.\n\n Args:\n ax: matplotlib axis or None\n default_rows: int, expected rows in axis\n default_columns: int, expected columns in axis\n **default_kwargs: keyword arguments to pass to plt.subplot\n\n Returns:\n axis, or raises an error\n \"\"\"\n\n default_shape = (default_rows, default_columns)\n if ax is None:\n _, ax = plt.subplots(*default_shape, **default_kwargs)\n elif ax.shape != default_shape:\n raise ValueError('Subplots with shape %r required' % (default_shape,))\n return ax\n\n\ndef make_2d(a):\n \"\"\"Ravel the dimensions after the first.\"\"\"\n a = np.atleast_2d(a.T).T\n # flatten out dimensions beyond the first\n n = a.shape[0]\n newshape = np.product(a.shape[1:]).astype(int)\n a = a.reshape((n, newshape), order='F')\n return a\n\ndef _scale_text(figsize, textsize, f=2):\n \"\"\"Scale text and linewidth to figsize.\"\"\"\n\n if textsize is None and figsize is not None:\n textsize = figsize[0] * f\n\n lw = textsize / 8\n ms = textsize / 2\n return textsize, lw, ms\n\ndef get_bins(x, max_bins=50, n=2):\n \"\"\"\n Compute number of bins (or ticks)\n\n Parameters\n ----------\n x : array\n array to be binned\n max_bins : int\n maximum number of bins\n n : int\n when computing bins, this should be 2, when computing ticks this should be 1.\n \"\"\"\n x_max, x_min = x.max(), x.min()\n x_range = x_max - x_min\n if x_range > max_bins:\n bins = range(x_min, x_max + n, int(x_range / 10))\n else:\n bins = range(x_min, x_max + n)\n return bins\n","sub_path":"arviz/plots/plot_utils.py","file_name":"plot_utils.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"578547237","text":"import pandas as pd\r\nimport statsmodels.formula.api as smf\r\nimport statsmodels.api as sm\r\nfrom patsy import dmatrices\r\n\r\n# Interpretation of linear, logistic and Poisson regression\r\n# Dataset: http://users.stat.ufl.edu/~aa/cda/data/Crabs.dat\r\n# Agresti - An Introduction to Categorical Data Analysis (Third Edition)\r\n# Section 3.3.3\r\n\r\n# color = color (1, medium light; 2, medium; 3, medium dark; 4, dark)\r\n# spine = spine condition (1, both good; 2, one broken; 3, both broken)\r\n# width = shell width (cm)\r\n# weight = weight (kg)\r\n# sat = number of satellites\r\n\r\ndf = pd.read_csv('crabs.txt', sep='\\s+')\r\ndf = df.replace({'color': {1: 'Medium Light', 2: 'Medium', 3: 'Medium Dark', 4: 'Dark'}})\r\ndf = df.replace({'spine': {1: 'Both Good', 2: 'One Broken', 3: 'Both Broken'}})\r\ndf = df.replace({'y': {0: 'No', 1: 'Yes'}})\r\ndf = df.drop('crab', 1)\r\n\r\n#####################\r\n# Linear regression #\r\n#####################\r\n\r\nlin_reg = smf.ols(formula = 'sat ~ width + weight + color + spine', data=df).fit()\r\nlin_reg.summary()\r\n\r\n# A unit increase of the width is associated with an increase of 0.023 in the number of satellites\r\n\r\n# Crabs with a medium color are associated with an increase of 0.61 in the number of satellites \r\n# compared to crabs with a dark color\r\n\r\n#######################\r\n# Logistic regression #\r\n#######################\r\ny, X = dmatrices('y ~ width + weight + color + spine', data=df, return_type='dataframe')\r\nlog_reg = sm.Logit(y['y[Yes]'], X, data=df).fit()\r\nlog_reg.summary()\r\n\r\n# A unit increase in the weight increases the odds \r\n# (that female crabs atleast have one satellite) \r\n# multiplicatively by exp(0.83) = 2.29\r\n# Or: increases the odds with (2.29 - 1) * 100% = 129%\r\n\r\n# Or use:\r\nlog_reg_2 = sm.GLM(y['y[Yes]'], X, data=df, \r\n family=sm.families.Binomial(link=sm.families.links.logit)).fit()\r\nlog_reg_2.summary()\r\n\r\n# Or use:\r\nlog_reg_3 = smf.glm('y ~ width + weight + color + spine', data=df, family=sm.families.Binomial()).fit()\r\nlog_reg_3.summary()\r\n\r\n######################\r\n# Poisson regression #\r\n######################\r\ny_2, X_2 = dmatrices('sat ~ width + weight + color + spine', data=df, return_type='dataframe')\r\npoisson_reg = sm.GLM(y_2, X_2, data=df,\r\n family=sm.families.Poisson(link=sm.families.links.log)).fit()\r\npoisson_reg.summary()\r\n\r\n# Or use:\r\npoisson_reg_2 = smf.glm('sat ~ width + weight + color + spine', data=df,\r\n family=sm.families.Poisson(link=sm.families.links.log)).fit()\r\npoisson_reg_2.summary()\r\n\r\n# x = predictor and B = coefficient of the predictor\r\n# For a unit change in x, the expected count changes by a factor of exp(B) \r\n# (holding all other variables constant, or adjusting for the other variables).\r\n\r\n# Alternatively, the percentage change in the expected count for a unit change in x,\r\n# can be computed as 100 * (exp(B) - 1) %\r\n\r\n# A unit increase in the weight score increase the expected count \r\n# multiplicatively by exp(0.50) = 1.65\r\n# Or: increases the expected count with (1.65 - 1) * 100% = 65%\r\n\r\n# Also, see Agresti - An Introduction to Categorical Data Analysis (Third Edition)\r\n# Section 3.3.3 (only one predictor)","sub_path":"GLM/GLM.py","file_name":"GLM.py","file_ext":"py","file_size_in_byte":3168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"3719008","text":"from __future__ import absolute_import\nfrom __future__ import unicode_literals\nfrom collections import namedtuple\n\nfrom corehq.apps.locations.models import SQLLocation\nfrom custom.enikshay.exceptions import NikshayLocationNotFound, NikshayCodeNotFound\n\n\ndef get_health_establishment_hierarchy_codes(location):\n def get_parent(parent_type):\n try:\n return location.get_ancestors().get(location_type__name=parent_type)\n except SQLLocation.DoesNotExist:\n raise NikshayLocationNotFound(\n \"Missing parent of type {location_type} for {location_id}\".format(\n location_type=parent_type,\n location_id=location.location_id))\n\n HealthEstablishmentHierarchy = namedtuple('HealthEstablishmentHierarchy', 'stcode dtcode')\n state = get_parent('sto')\n district = get_parent('dto')\n try:\n return HealthEstablishmentHierarchy(\n stcode=state.metadata['nikshay_code'],\n dtcode=district.metadata['nikshay_code'],\n )\n except (KeyError, AttributeError) as e:\n raise NikshayCodeNotFound(\"Nikshay codes not found: {}\".format(e))\n","sub_path":"custom/enikshay/location_utils.py","file_name":"location_utils.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"286703257","text":"# -*- coding: utf-8 -*-\nimport time\nimport asyncio\nimport json\nimport re\nimport async_timeout\nfrom lxml import etree\nfrom aiohttp import ClientSession, TCPConnector\nfrom public_utils import to_time_str, to_timestamp\n\n\nasyncio.Semaphore(20)\n\n\nclass AsySpider(object):\n def __init__(self, code_list):\n self.code_list = code_list\n self.sbh = None\n self.url = \"http://www.bjsat.gov.cn/WSBST/bsdt/swdjzcx/queryto.jsp?nsrsbh={}\"\n self.headers = {\n 'Accept': \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n 'Accept-Encoding': \"gzip, utf-8\",\n 'Accept-Language': \"zh-CN,zh;q=0.9\",\n 'Connection': \"keep-alive\",\n 'Host': \"www.bjsat.gov.cn\",\n 'Referer': \"http://www.bjsat.gov.cn/WSBST/bsdt/swdjzcx/query.jsp\",\n 'Upgrade-Insecure-Requests': \"1\",\n 'User-Agent': \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36\",\n }\n\n async def get_func(self, n, num=0):\n res_list = []\n url = self.url.format(n)\n conn = TCPConnector(limit=0)\n try:\n async with async_timeout.timeout(60):\n async with ClientSession() as session:\n async with session.get(url, headers=self.headers) as respons:\n res = await respons.text()\n res_list.append(res)\n\n except Exception as e:\n conn.close()\n print('=', e)\n if num < 5:\n num += 1\n return await self.get_func(n, num)\n else:\n return None\n conn.close()\n return res_list\n\n async def for_event(self, n):\n code = n['credit_code']\n response = await self.get_func(code)\n if response is None:\n print('{} is None'.format(code))\n return [n, response]\n\n def parse_response(self, sbh, result):\n sql_arr = []\n sql_dict = {\n \"YBNSR_ID\": sbh['TASK_ID'],\n \"YBNSR_NAME\": \"纳税人名称\",\n \"SHXYDM\": sbh['SHXYDM'],\n \"FDDBR\": \"法定代表人(负责人)\",\n \"ADDR\": \"地址\",\n \"DJLX\": \"登记注册类型\",\n \"JYFW\": \"经营范围\",\n \"PZJG\": \"批准设立机关\",\n \"KJYW\": \"扣缴义务\",\n \"FZRQ\": \"发证日期\",\n \"NSZT\": \"纳税人状态\",\n \"NSLB\": \"增值税纳税人类别\",\n \"STATUS\": 1\n }\n try:\n dic = {}\n for res in result:\n html = etree.HTML(res)\n tr_list = html.xpath('/html/body/table[1]/./tr')\n for tr in tr_list:\n err = tr.xpath('./td')[0].xpath('string(.)')\n if '查询出错' in err:\n # errer = sbh['SHXYDM'] + '_' + err\n # print(errer)\n sql_dict = {\n \"YBNSR_ID\": sbh['TASK_ID'],\n \"SHXYDM\": sbh['SHXYDM'],\n \"INSERT_DATE\": time.strftime('%Y-%m-%d %H-%M-%S', time.localtime()),\n \"STATUS\": 0\n }\n sql_arr.append(sql_dict)\n continue\n key = re.sub('\\s| |:', '', tr.xpath('./td[1]')[0].xpath('string(.)'))\n value = re.sub('\\s', '', tr.xpath('./td[2]')[0].xpath('string(.)'))\n dic[key] = value\n if dic:\n tt = to_timestamp(dic['发证日期'])\n dic['发证日期'] = to_time_str(tt)\n for key, value in sql_dict.items():\n for k, v in dic.items():\n if value == k:\n sql_dict[key] = v\n sql_dict[\"INSERT_DATE\"] = time.strftime('%Y-%m-%d %H-%M-%S', time.localtime())\n sql_arr.append(sql_dict)\n except Exception as e:\n print('the {} error is {}'.format(sbh, e))\n return None\n return sql_arr\n\n def async_main(self):\n task_list = [\n asyncio.ensure_future(self.for_event(n)) for n in self.code_list\n ]\n loop = asyncio.get_event_loop()\n results = loop.run_until_complete(asyncio.gather(*task_list))\n\n for result in results:\n res = self.parse_response(result[0], result[1])\n if res is not None:\n print(res)\n else:\n pass\n\n\nif __name__ == '__main__':\n sbh_list = []\n# s = time.time()\n content = {\n 'TASK_ID': 'ddddddddd',\n 'SHXYDM': '911101088020926647',\n }\n sbh_list.append(content)\n\n A = AsySpider(sbh_list)\n A.async_main()\n# # print(len(sbh_list), '异步用时', time.time() - s)\n\n\n\n","sub_path":"z_asyncio_test.py","file_name":"z_asyncio_test.py","file_ext":"py","file_size_in_byte":4943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"471696241","text":"from sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn import metrics\nimport numpy as np\n\n\nclass GridSearch:\n\n def predict(self, features, labels, window_size):\n sig_len = (len(features) + 1) * window_size\n test_index = int(int(sig_len / 5 * 4) / window_size)\n X_train = features[:test_index]\n X_test = features[test_index:]\n Y_train = labels[:test_index]\n Y_test = labels[test_index:]\n classifier = KNeighborsClassifier()\n\n parameters = {\n 'n_neighbors': [ 11],\n 'weights': [ 'distance'],\n 'p': [ 2]\n }\n\n grid_search = GridSearchCV(classifier,\n parameters,\n scoring=metrics.make_scorer(metrics.accuracy_score),\n cv=5,\n n_jobs=-1,\n verbose=10)\n grid_search.fit(X_train, Y_train)\n self.predicted = grid_search.predict(X_test)\n return self.confusion_matrix(Y_test, self.predicted)\n\n def confusion_matrix(self, Y_test, Y_predicted):\n confusion = metrics.confusion_matrix(Y_test, Y_predicted)\n return confusion[0][0], confusion[0][1], confusion[1][0], confusion[1][1]\n\n def get_peaks(self, predicted_regions, window_size, signal):\n siglen = len(signal) + 1\n test_index = int(siglen/5)*4\n Y_predicted = []\n window_start = test_index\n for label in predicted_regions:\n if label == 1:\n window_end = window_start + window_size\n qrs_region = [abs(signal[value]) for value in range(window_start, window_end)]\n peak = window_start + np.argmax(qrs_region)\n Y_predicted.append(peak)\n window_start += window_size\n return Y_predicted\n","sub_path":"rpeakdetection/GridSearch.py","file_name":"GridSearch.py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"506468806","text":"import json\nimport pytest\nfrom asynctest import CoroutineMock\n\nimport tests.unit.schemas as schemas\nfrom tests.unit.utils import build_url\n\n\n\n@pytest.mark.gen_test\nasync def test_ping_ok(http_client, base_url):\n url = build_url(f'{base_url}/ping')\n\n resp = await http_client.fetch(url)\n schemas.run_validator(resp.body, schemas.success_schema)\n\n\n@pytest.mark.gen_test\nasync def test_pong_ok(http_client, base_url, curs):\n url = build_url(f'{base_url}/pong')\n curs.execute = CoroutineMock()\n\n resp = await http_client.fetch(url)\n schemas.run_validator(resp.body, schemas.pong_schema)\n resp_json = json.loads(resp.body)\n\n assert resp_json['message'] == 'OK'\n assert resp_json['details']['postgres']['message'] == 'OK'\n\n\n@pytest.mark.gen_test\nasync def test_pong_fail(http_client, base_url, curs, raises):\n url = build_url(f'{base_url}/pong')\n curs.execute = CoroutineMock(side_effect=Exception)\n\n async with raises(http_client.fetch, url) as exc:\n assert exc.code == 500\n\n\n@pytest.mark.gen_test\nasync def test_metrics_ok(http_client, base_url):\n url = build_url(f'{base_url}/metrics')\n\n resp = await http_client.fetch(url)\n assert resp.code == 200\n","sub_path":"tests/unit/test_handlers_diagnostics.py","file_name":"test_handlers_diagnostics.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"71993330","text":"from flask_restplus import Namespace, Resource, fields, abort\n\nimport cea.config\nimport cea.inputlocator\nimport cea.utilities.dbf\nfrom cea.utilities.standardize_coordinates import get_geographic_coordinate_system\n\nimport pandas\nimport geopandas\nimport os\nimport json\nimport yaml\n\nfrom collections import OrderedDict\n\napi = Namespace('Inputs', description='Input data for CEA')\n\n\ndef read_inputs_field_types():\n \"\"\"Parse the inputs.yaml file and create the dictionary of column types\"\"\"\n inputs = yaml.load(\n open(os.path.join(os.path.dirname(__file__), '../inputs/inputs.yml')).read())\n types = {\n 'int': int,\n 'float': float,\n 'str': str,\n 'year': int,\n }\n\n for db in inputs.keys():\n inputs[db]['fieldtypes'] = {\n field['name']: types[field['type']] for field in inputs[db]['fields']}\n inputs[db]['fieldnames'] = [field['name']\n for field in inputs[db]['fields']]\n return inputs\n\n\nINPUTS = read_inputs_field_types()\nINPUT_KEYS = INPUTS.keys()\nGEOJSON_KEYS = ['zone', 'district', 'streets', 'dc', 'dh']\n\n# INPUT_MODEL = api.model('Input', {\n# 'fields': fields.List(fields.String, description='Column names')\n# })\n\n# GEOJSON_MODEL = api.model('GeoJSON',{\n# 'test': fields.String()\n# })\n\n# BUILDING_PROPS_MODEL = api.model('Building Properties', {\n# 'geojsons': fields.List(fields.Nested(GEOJSON_MODEL)),\n# 'tables': fields.List(fields.String)\n# })\n\n\n@api.route('/')\nclass InputList(Resource):\n def get(self):\n return {'buildingProperties': INPUT_KEYS, 'others': ['streets', 'dc', 'dh']}\n\n\n@api.route('/building-properties/')\nclass Input(Resource):\n def get(self, db):\n if db not in INPUTS:\n abort(400, 'Input file not found: %s' % db, choices=INPUT_KEYS)\n db_info = INPUTS[db]\n columns = OrderedDict()\n for column in db_info['fieldnames']:\n columns[column] = db_info['fieldtypes'][column].__name__\n return columns\n\n\n@api.route('/building-properties//geojson')\nclass InputDatabases(Resource):\n def get(self, db):\n if not (db in INPUT_KEYS and db in GEOJSON_KEYS):\n abort(400, 'Input file not found: %s' % db, choices=list(set(INPUT_KEYS) & set(GEOJSON_KEYS)))\n db_info = INPUTS[db]\n config = cea.config.Configuration()\n locator = cea.inputlocator.InputLocator(config.scenario)\n location = getattr(locator, db_info['location'])()\n if db_info['type'] != 'shp':\n abort(400, 'Invalid database for geojson: %s' % location)\n return df_to_json(location, bbox=True)[0]\n\n\n@api.route('/others//geojson')\nclass InputOthers(Resource):\n def get(self, kind):\n config = cea.config.Configuration()\n locator = cea.inputlocator.InputLocator(\n config.scenario)\n if kind == 'streets':\n return df_to_json(locator.get_street_network())[0]\n if kind in ['dc', 'dh']:\n return get_network(locator, kind)[0]\n abort(400, 'Input file not found: %s' % kind, choices=['streets', 'dh', 'dc'])\n\n\n@api.route('/building-properties')\nclass BuildingProperties(Resource):\n def get(self):\n return get_building_properties()\n\n\n@api.route('/all-inputs')\nclass AllInputs(Resource):\n def get(self):\n config = cea.config.Configuration()\n locator = cea.inputlocator.InputLocator(config.scenario)\n\n # FIXME: Find a better way, current used to test for Input Editor\n store = get_building_properties()\n store['geojsons'] = {}\n store['crs'] = {}\n store['geojsons']['zone'], store['crs']['zone'] = df_to_json(locator.get_zone_geometry(), bbox=True, trigger_abort=False)\n store['geojsons']['district'], store['crs']['district'] = df_to_json(locator.get_district_geometry(), bbox=True, trigger_abort=False)\n store['geojsons']['streets'], store['crs']['streets'] = df_to_json(locator.get_street_network(), trigger_abort=False)\n store['geojsons']['dc'], store['crs']['dc'] = get_network(locator, 'dc', trigger_abort=False)\n store['geojsons']['dh'], store['crs']['dh'] = get_network(locator, 'dh', trigger_abort=False)\n\n return store\n\n\ndef get_building_properties():\n import cea.glossary\n # FIXME: Find a better way to ensure order of tabs\n tabs = ['zone', 'age', 'occupancy', 'architecture', 'internal-loads',\n 'supply-systems', 'indoor-comfort', 'district', 'restrictions']\n\n config = cea.config.Configuration()\n locator = cea.inputlocator.InputLocator(config.scenario)\n store = {'tables': {}, 'columns': {}, 'order': tabs}\n glossary = cea.glossary.read_glossary_df()\n filenames = glossary['FILE_NAME'].str.split(pat='/').str[-1]\n for db in INPUTS:\n db_info = INPUTS[db]\n location = getattr(locator, db_info['location'])()\n try:\n if db_info['type'] == 'shp':\n table_df = geopandas.GeoDataFrame.from_file(location)\n table_df = pandas.DataFrame(\n table_df.drop(columns='geometry'))\n if 'REFERENCE' in db_info['fieldnames'] and 'REFERENCE' not in table_df.columns:\n table_df['REFERENCE'] = None\n store['tables'][db] = json.loads(\n table_df.set_index('Name').to_json(orient='index'))\n else:\n assert db_info['type'] == 'dbf', 'Unexpected database type: %s' % db_info['type']\n table_df = cea.utilities.dbf.dbf_to_dataframe(location)\n if 'REFERENCE' in db_info['fieldnames'] and 'REFERENCE' not in table_df.columns:\n table_df['REFERENCE'] = None\n store['tables'][db] = json.loads(\n table_df.set_index('Name').to_json(orient='index'))\n\n columns = OrderedDict()\n db_glossary = json.loads(glossary[filenames == '%s.%s' % (db.replace('-', '_'), db_info['type'])]\n [['VARIABLE', 'UNIT', 'DESCRIPTION']].set_index('VARIABLE').to_json(orient='index'))\n\n for column in db_info['fieldnames']:\n if column == 'REFERENCE':\n continue\n columns[column] = {}\n columns[column]['type'] = db_info['fieldtypes'][column].__name__\n columns[column]['description'] = db_glossary[column]['DESCRIPTION']\n columns[column]['unit'] = db_glossary[column]['UNIT']\n store['columns'][db] = columns\n\n except IOError as e:\n print(e)\n store['tables'][db] = {}\n\n return store\n\n\ndef get_network(locator, kind, trigger_abort=True):\n # TODO: Get a list of names and send all in the json\n name = ''\n edges = locator.get_network_layout_edges_shapefile(kind, name)\n nodes = locator.get_network_layout_nodes_shapefile(kind, name)\n network_json, crs = df_to_json(edges, trigger_abort=trigger_abort)\n nodes_json, _ = df_to_json(nodes, trigger_abort=trigger_abort)\n network_json['features'].extend(nodes_json['features'])\n return network_json, crs\n\n\ndef df_to_json(file_location, bbox=False, trigger_abort=True):\n from cea.utilities.standardize_coordinates import get_lat_lon_projected_shapefile, get_projected_coordinate_system\n try:\n table_df = geopandas.GeoDataFrame.from_file(file_location)\n # Save coordinate system\n lat, lon = get_lat_lon_projected_shapefile(table_df)\n crs = get_projected_coordinate_system(lat, lon)\n # make sure that the geojson is coded in latitude / longitude\n out = table_df.to_crs(get_geographic_coordinate_system())\n out = json.loads(out.to_json(show_bbox=bbox))\n return out, crs\n except IOError as e:\n print(e)\n if trigger_abort:\n abort(400, 'Input file not found: %s' % file_location)\n except RuntimeError as e:\n print(e)\n if trigger_abort:\n abort(400, e.message)\n","sub_path":"cea/interfaces/dashboard/api/inputs.py","file_name":"inputs.py","file_ext":"py","file_size_in_byte":7981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"556996646","text":"\"\"\"\n输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。\n\n示例 1:\n\n输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]\n输出:[1,2,3,6,9,8,7,4,5]\n示例 2:\n\n输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]\n输出:[1,2,3,4,8,12,11,10,9,5,6,7]\n \n\n限制:\n\n0 <= matrix.length <= 100\n0 <= matrix[i].length <= 100\n注意:本题与主站 54 题相同:https://leetcode-cn.com/problems/spiral-matrix/\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n\"\"\"\n\nclass Solution:\n def spiralOrder(self, matrix: list) -> list:\n if not matrix:\n return []\n n, m = len(matrix), len(matrix[0])\n x, y, count, cur = 0, -1, 0, 0\n toward = [(0,1),(1,0),(0,-1),(-1,0)]\n res = []\n while count < m * n:\n nx, ny = x + toward[cur][0], y + toward[cur][1]\n if 0 <= nx <= n-1 and 0 <= ny <= m-1 and matrix[nx][ny] != 'inf':\n res.append(matrix[nx][ny])\n matrix[nx][ny] = 'inf'\n x, y = nx, ny\n count += 1\n else:\n cur = (cur + 1) % 4\n return res\n\nif __name__ == '__main__':\n print(Solution().spiralOrder([[1,2,3],[4,5,6],[7,8,9]]))","sub_path":"python code/剑指offer/29. 顺时针打印矩阵.py","file_name":"29. 顺时针打印矩阵.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"617918526","text":"from django.views.generic import TemplateView\n\n\nclass MainPageTemplateView(TemplateView):\n\n template_name = 'base.html'\n\n def get_context_data(self, **kwargs):\n context = super(MainPageTemplateView, self).get_context_data(**kwargs)\n context['webpush'] = {\"group\": \"fue\"}\n return context\n","sub_path":"nope/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"379581923","text":"# Metamorphic testing\n# Relations and their explanations may be found at: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3019603/\n\nimport p1b2_baseline_keras2\nimport p1b2\n\nimport keras\nimport numpy as np\nimport copy\n\nimport unittest\n\nclass p1b2Tests(unittest.TestCase):\n\n # Note: test cases only run when they start with 'test'\n\n @classmethod\n def setUpClass(self):\n self._srcModel = p1b2_baseline_keras2.main(DeterministicResults=True)\n (self.X_train, self.y_train), (self.X_test, self.y_test) = p1b2.load_data()\n self._origPredictions = self._srcModel.predict_classes(self.X_test)\n\n def differencesInAccuracy(self):\n #In order for this test to work, you must change the setUp to predict() in place of predict_classes()\n (X_train, y_train), (X_test, y_test) = self.__getCopiesOfData()\n newPreds = p1b2_baseline_keras2.main(X_train,y_train,X_test,y_test,True).predict(X_test)\n scores = p1b2.evaluate(self._origPredictions, y_test)\n print('old model on test data:', scores)\n newScores = p1b2.evaluate(newPreds, y_test)\n print('new model on test data:', newScores)\n diff = scores['accuracy'] - newScores['accuracy'] \n print('difference in scores:', diff)\n\n def est_modelIsDeterministic(self):\n newPreds = p1b2_baseline_keras2.main(DeterministicResults=True).predict_classes(self.X_test)\n assert np.array_equal(self._origPredictions,newPreds), \"Model is not deterministic\"\n\n def est_MR0_ConsistenceWithAffineTransform(self):\n (X_train, y_train), (X_test, y_test) = self.__getCopiesOfData()\n numFeatures = X_train.shape[1]\n \n #Makes an array of random size filled with random numbers between 0 and numFeatures without repitition\n randomSubset = np.random.choice(range(numFeatures),np.random.randint(numFeatures),False)\n\n k = np.random.randint(1,100)\n b = np.random.randint(100)\n\n for i in range(randomSubset.shape[0]):\n c = randomSubset[i]\n X_train[:,c] = X_train[:,c]*k + b\n X_test[:,c] = X_test[:,c]*k + b\n\n transformedPredictions = p1b2_baseline_keras2.main(X_train,y_train,X_test,y_test,True).predict_classes(X_test)\n\n assert np.array_equal(self._origPredictions,transformedPredictions), \"affine transformations change the outcome of the model\"\n\n def est_MR11_PermutationOfClassLabels(self):\n (X_train, y_train), (X_test, y_test) = self.__getCopiesOfData()\n\n #print('pre permute train:')\n #print(y_train[50:55,:])\n #print('pre permute test:')\n #print(y_test[50:55,:])\n p = self.__permuteLabels(y_train,y_test)\n #print('permutation: ', p)\n #print('new train:')\n #print(y_train[50:55,:])\n #print('new test:')\n #print(y_test[50:55,:])\n\n newModel = p1b2_baseline_keras2.main(X_train,y_train,X_test,y_test,True)\n newPredictions = newModel.predict_classes(X_test)\n\n for x in range(X_test.shape[1]):\n assert newPredictions[x] == p[self._origPredictions[x]], \"permuting class labels changes outcome of model\"\n #print(p)\n #print(self._origPredictions[x])\n #print(newPredictions[x])\n #print(p[self._origPredictions[x]])\n \n def est_MR12_PermutationOfAttributes(self):\n (X_train, y_train), (X_test, y_test) = self.__getCopiesOfData()\n\n X_train, X_test = self.__shuffleColumnsInUnison(X_train,X_test)\n\n shuffledModelPredictions = p1b2_baseline_keras2.main(X_train,y_train,X_test,y_test,True).predict_classes(X_test)\n #for x in range(X_test.shape[0]):\n # if not (self._origPredictions[x]==shuffledModelPredictions[x]):\n # print('mismatch:')\n # print(self._origPredictions[x])\n # print(shuffledModelPredictions[x])\n assert np.array_equal(self._origPredictions,shuffledModelPredictions), \"permuting the order of the features changes the outcome of the model\"\n \n def est_MR21_AddUninformativeAttribute(self):\n (X_train, y_train), (X_test, y_test) = self.__getCopiesOfData()\n tempTrain = np.zeros((X_train.shape[0],X_train.shape[1]+1))\n tempTest = np.zeros((X_test.shape[0],X_test.shape[1]+1))\n tempTrain[:,:-1] = X_train\n tempTest[:,:-1] = X_test\n newModel = p1b2_baseline_keras2.main(tempTrain,y_train,tempTest,y_test,True)\n newPreds = newModel.predict_classes(tempTest)\n assert np.array_equal(self._origPredictions,newPreds), \"adding an uninformative attribute changes outcome\"\n \n def est_MR22_AddInformativeAttribute(self):\n (X_train, y_train), (X_test, y_test) = self.__getCopiesOfData()\n tempTrain = np.zeros((X_train.shape[0],X_train.shape[1]+1))\n tempTest = np.zeros((X_test.shape[0],X_test.shape[1]+1))\n tempTrain[:,:-1] = X_train\n tempTest[:,:-1] = X_test\n \n #pick a random class\n n = np.random.randint(10)\n\n #if a test point is associated with class n, make the new attribute 1\n for x in range(X_train.shape[0]):\n if X_train[x,n] > .5:\n tempTrain[x,-1] = 1\n for x in range(X_test.shape[0]):\n if X_test[x,n] > .5:\n tempTest[x,-1] = 1\n\n newModel = p1b2_baseline_keras2.main(tempTrain,y_train,tempTest,y_test,True)\n newPreds = newModel.predict_classes(tempTest)\n \n for x in range(X_test.shape[0]):\n if (self._origPredictions[x] == n):\n assert newPreds[x] == n, \"adding an informative feature for class n changed previous classifications of n to another class\"\n \n def est_MR31_ConsistenceWithRePrediction(self):\n (X_train, y_train), (X_test, y_test) = self.__getCopiesOfData()\n n = np.random.randint(X_test.shape[0])\n nPred = self._origPredictions[n]\n\n newXTrain = np.zeros((X_train.shape[0]+1,X_train.shape[1]))\n newXTrain[:-1,:] = X_train\n newXTrain[-1,:] = X_test[n,:]\n newYTrain = np.zeros((y_train.shape[0]+1,y_train.shape[1]))\n newYTrain[:-1,:] = y_train\n newYTrain[-1,:] = y_test[n,:]\n\n newModel = p1b2_baseline_keras2.main(newXTrain,newYTrain,X_test,y_test,True)\n \n assert (newModel.predict_classes(X_test)[n]) == nPred\n \n def est_MR32_AdditionalTrainingSample(self):\n (X_train, y_train), (X_test, y_test) = self.__getCopiesOfData()\n n = np.random.randint(X_test.shape[1])\n\n count = int(np.sum(X_train[:,n]))\n\n newXTrain = np.zeros((X_train.shape[0]+count,X_train.shape[1]))\n newYTrain = np.zeros((y_train.shape[0]+count,y_train.shape[1]))\n \n newXTrain[:X_train.shape[0],:] = X_train\n newYTrain[:y_train.shape[0],:] = y_train\n \n XCount = count\n for x in range(count):\n if np.argmax(y_train[x,:]) == n:\n newXTrain[XCount,:] = X_train[x,:]\n newYTrain[XCount,:] = y_train[x,:]\n XCount = XCount + 1\n\n newModel = p1b2_baseline_keras2.main(newXTrain,newYTrain,X_test,y_test,True)\n newPreds = newModel.predict_classes(X_test)\n\n for x in range(X_test.shape[0]):\n if (self._origPredictions[x] == n):\n assert newPreds[x] == n, \"doubling the training samples for class n changed some classifications from n to another class\"\n \n def est_MR41_AddClassByDuplicatingSamples(self):\n (X_train, y_train), (X_test, y_test) = self.__getCopiesOfData()\n cl = np.random.randint(y_train.shape[1])\n \n count = int(np.sum(y_train[:,cl]))\n\n #One class will remain empty but this should have no impact on the result\n newNumberOfClasses = (y_train.shape[1] * 2)\n\n newXTrain = np.zeros((X_train.shape[0]*2 - count, X_train.shape[1]))\n newYTrain = np.zeros((y_train.shape[0]*2 - count, newNumberOfClasses))\n newYTest = np.zeros((y_test.shape[0], newNumberOfClasses))\n newXTrain[:X_train.shape[0],:] = X_train\n newYTrain[:y_train.shape[0],:y_train.shape[1]] = y_train\n newYTest[:y_test.shape[0],:y_test.shape[1]] = y_test\n \n count = y_train.shape[0]\n for x in range(y_train.shape[0]):\n if np.argmax(y_train[x,:]) != cl:\n newYTrain[count,np.argmax(y_train[x,:])+y_train.shape[1]] = 1 \n newXTrain[count,:] = X_train[x,:]\n count = count + 1\n\n newModel = p1b2_baseline_keras2.main(newXTrain,newYTrain,X_test,newYTest,True)\n newPreds = newModel.predict_classes(X_test)\n\n for x in range(X_test.shape[0]):\n if (self._origPredictions[x] == cl):\n assert newPreds[x] == cl, \"adding new classes by doubling the training samples for classes other than n made our classifier worse for class n\"\n\n def est_MR42_AddClassesByReLabelingSamples(self):\n (X_train, y_train), (X_test, y_test) = self.__getCopiesOfData()\n cl = np.random.randint(y_train.shape[1])\n\n newNumberOfClasses = y_train.shape[1] * 2\n\n newYTrain = np.zeros((y_train.shape[0],newNumberOfClasses))\n\n #y_test will need the same shape\n newYTest = np.zeros((y_test.shape[0],newNumberOfClasses))\n newYTest[:,:y_test.shape[1]] = y_test\n\n for x in range(y_train.shape[0]):\n if y_train[x,cl] == 1:\n newYTrain[x,cl] = 1\n else:\n if np.random.random() < .5:\n newYTrain[x, np.argmax(y_train[x,:]) + y_train.shape[1]] = 1\n else:\n newYTrain[x,np.argmax(y_train[x,:])] = 1\n \n\n newModel = p1b2_baseline_keras2.main(X_train,newYTrain,X_test,newYTest,True)\n newPreds = newModel.predict_classes(X_test)\n\n for x in range(X_test.shape[0]):\n if (self._origPredictions[x] == cl):\n assert newPreds[x] == cl, \"relabeling the class of training samples for classes besides n changed some classifications of n\"\n \n def test_MR51_RemovalOfClasses(self):\n (X_train, y_train), (X_test, y_test) = self.__getCopiesOfData()\n #Class to remove\n cl = np.random.randint(y_test.shape[1])\n\n trainCount = int(np.sum(y_train[:,cl]))\n\n newXTrain = np.zeros((X_train.shape[0] - trainCount, X_train.shape[1]))\n newYTrain = np.zeros((y_train.shape[0] - trainCount, y_train.shape[1]))\n\n count = 0\n for x in range(X_train.shape[0]):\n if not np.argmax(y_train[x,:]) == cl:\n newXTrain[count,:] = X_train[x,:]\n newYTrain[count,:] = y_train[x,:]\n count = count + 1\n\n newModel = p1b2_baseline_keras2.main(newXTrain,newYTrain,X_test,y_test,True)\n newPreds = newModel.predict_classes(X_test)\n\n for x in range(X_test.shape[0]):\n if self._origPredictions[x] != cl:\n assert self._origPredictions[x] == newPreds[x], \"removing a class causes the model to change predictions for the remaining classes\"\n\n def est_MR52_RemovalOfSamples(self):\n (X_train, y_train), (X_test, y_test) = self.__getCopiesOfData()\n cl = np.random.randint(y_test.shape[1])\n\n samplesToKeep = np.zeros(X_train.shape[0])\n\n for x in range(X_train.shape[0]):\n if (np.random.random() < .5) or y_train[x,cl] > .5:\n samplesToKeep[x] = 1\n\n newXTrain = np.zeros(( int(np.sum(samplesToKeep)) , X_train.shape[1] ))\n newYTrain = np.zeros(( int(np.sum(samplesToKeep)) , y_train.shape[1] ))\n count = 0\n for x in range(X_train.shape[0]):\n if samplesToKeep[x]:\n newXTrain[count,:] = X_train[x,:]\n newYTrain[count,:] = y_train[x,:]\n count = count+1\n\n newModel = p1b2_baseline_keras2.main(newXTrain,newYTrain,X_test,y_test,True)\n newPreds = newModel.predict_classes(X_test)\n \n for x in range(X_test.shape[0]):\n if self._origPredictions[x] == cl:\n assert self._origPredictions[x] == newPreds[int(np.sum(samplesToKeep[:x]))], \"Removing samples from classes other than n causes classifications of n to change to other classes\"\n\n def __shuffleColumns(self, x):\n x = np.transpose(x)\n np.random.shuffle(x)\n x = np.transpose(x)\n\n #https://stackoverflow.com/questions/4601373/better-way-to-shuffle-two-numpy-arrays-in-unison\n def __shuffleColumnsInUnison(self, a, b,):\n a = np.transpose(a)\n b = np.transpose(b)\n\n assert len(a) == len(b)\n p = np.random.permutation(len(a))\n \n a = np.transpose(a[p])\n b = np.transpose(b[p]) \n return a, b\n\n def __getCopiesOfData(self):\n return (copy.copy(self.X_train),copy.copy(self.y_train)),(copy.copy(self.X_test),copy.copy(self.y_test))\n\n def __permuteLabels(self,y_train,y_test):\n p = np.arange(y_train.shape[1])\n np.random.shuffle(p)\n\n for x in range(y_train.shape[0]):\n i = np.where(y_train[x,:] > .5)\n y_train[x,i] = 0\n y_train[x,p[i]] = 1\n \n for x in range(y_test.shape[0]):\n i = np.where(y_test[x,:] > .5)\n y_test[x,i] = 0\n y_test[x,p[i]] = 1\n\n return p\n \n\nif __name__ == '__main__':\n unittest.main()","sub_path":"Pilot1/P1B2/p1b2_baseline_test.py","file_name":"p1b2_baseline_test.py","file_ext":"py","file_size_in_byte":13350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"239349415","text":"\"\"\"Messy, but fairly optimized code for drawing the mandelbrot set using\r\nturtle graphics\"\"\"\r\n\r\nimport turtle\r\n\r\n\"\"\"These values can be modyfied to change the rendering\"\"\"\r\n\r\nwidth = 300 \t\t\t#Size in max distance from 0,0. Medium performance impact\r\n\t\t\t\t\t\t#width = 500 fits a maximized window on a 1080p screen\r\nheight = width \t\t\t#Needs to be a square to render properly\r\nmaxiterations = 100\t\t#Precision or sharpness. Higher values needed when zooming. Low performance impact\r\nspacing = 1\t\t\t\t#Only check every x pixels. Use 1 for perfect image. High performance impact.\r\n\t\t\t\t\t\t#Use a higher value to test rendering. Usefull when zooming\r\n\r\n\r\nzoompercent = 100 / 100\t#How zoomed in. Modyfies performance of maxiterations\r\nzoomx = 0\t\t\t\t#Offset x and y to zoom in on.\r\nzoomy = 0\t\t\t\t#These two are supposed to be coordinates on the mandelbrot set, but it changes with zoom.\r\n\r\nupdatetime = 5 \t\t\t#number of lines to update at a time. Changeging performance impact\r\n\r\n\r\n\"\"\"Global variables, not supposed to be changed\"\"\"\r\nupdatecount = 0\t\t\t\r\n\r\nxoffset = 0.75 * width\t#Approxymately centers the set on canavas\r\n\r\ntu = turtle.Turtle()\t#Prepares the turtle\r\ntu.speed(0)\r\ntu.hideturtle()\r\ntu.up()\r\nturtle.tracer(0, 0)\r\nescaped = False\r\nprevesc = False\r\n\r\n\r\n\"\"\"Methods\"\"\"\r\ndef draw(x, y):\r\n\t\"\"\"Draws a single pixel at x,y\"\"\"\r\n\ttu.up()\r\n\ttu.setpos(x,y)\r\n\ttu.down()\r\n\ttu.setpos(x + 1,y)\r\n\t\r\ndef maprangex(val):\r\n\t\"\"\"Maps a pixel x-coordinate to be rendered to be between -1 and 1\"\"\"\r\n\ttomax = 1\r\n\ttomin = -1\r\n\tvalnorm = (val + width) / (width + width)\r\n\treturn (tomin + valnorm * (tomax - tomin) + zoomx) / zoompercent\r\n\t\r\ndef maprangey(val):\r\n\t\"\"\"Maps a pixel y-coordinate to be rendered to be between -1 and 1\"\"\"\r\n\ttomax = 1\r\n\ttomin = -1\r\n\tvalnorm = (val + height) / (height + height)\r\n\treturn (tomin + valnorm * (tomax - tomin) + zoomy) / zoompercent\r\n\t\r\ndef mandelbrot(x, y):\r\n\t\"\"\"Returns true if pixel at x,y is in the (approxemated) mandelbrot set\"\"\"\r\n\tnormx = maprangex(x)\r\n\tnormy = maprangey(y)\r\n\txcalc = 0.0\r\n\tycalc = 0.0\r\n\titeration = 0\r\n\texpon = 2\r\n\twhile (xcalc**expon + ycalc**expon < 2**expon and iteration < maxiterations):\r\n\t\ttemp = xcalc**expon - ycalc**expon + normx\r\n\t\tycalc = 2*xcalc*ycalc + normy\r\n\t\txcalc = temp\r\n\t\titeration += 1\r\n\tif (xcalc**expon + ycalc**expon < 2**expon):\r\n\t\treturn True\r\n\treturn False\r\n\r\n\"\"\"Main code\"\"\"\r\nfor y in range(-height, height + 1, spacing):\t\t\t\t#For every line\r\n\tprevesc = escaped = False\t\t\t\t\t\t\t\t#Reset variables\r\n\tfor x in range(int(-width*2.5), width + 1, spacing):\t#For every pixel in line\r\n\t\tescaped = mandelbrot(x, y)\t\t\t\t\t\t\t#Checks if pixel escaped\r\n\t\tif escaped and not prevesc:\t\t\t\t\t\t\t#Places a turtle at a escaped pixel, if the previous pixel does not escape\r\n\t\t\ttu.up()\r\n\t\t\ttu.setpos(x + xoffset,y)\r\n\t\t\ttu.down()\r\n\t\telif not escaped and prevesc or x >= width and escaped:\t#Draws a line to the last pixel, if that pixel that escaped, whilst the current did not\r\n\t\t\ttu.setpos(x + xoffset - 1, y)\r\n\t\tprevesc = escaped\t\t\t\t\t\t\t\t\t\r\n\tupdatecount += 1\r\n\tif updatecount > updatetime:\t\t\t\t\t\t\t#Updates the drawing every updatetime lines\r\n\t\tturtle.update()\r\n\t\tupdatecount = 0\r\n\r\n\t\r\nturtle.update()\t\t\t\t\t\t#Final update\r\nturtle.mainloop()\t\t\t\t\t#mainloop prevents the window from freezing","sub_path":"DM550 - Introduction to Programming/Python_examples/MandelbrötSet.py","file_name":"MandelbrötSet.py","file_ext":"py","file_size_in_byte":3216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"7307888","text":"import asyncio\nimport base64\nimport imageio \n\nfrom fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request\nfrom fastapi.responses import HTMLResponse\nfrom fastapi.staticfiles import StaticFiles\nfrom fastapi.templating import Jinja2Templates\n\n\nfrom main import analyze, connect_me, disconnect\n\napp = FastAPI() \napp.mount(\"/static\", StaticFiles(directory=\"templates\"), name=\"static\")\ntemplates = Jinja2Templates(directory=\"templates\")\n\n\n@app.get(\"/\", response_class=HTMLResponse)\nasync def get(request: Request):\n return templates.TemplateResponse(\"index.html\", {\"request\": request})\n\n\nloop = asyncio.get_event_loop()\n\n@app.websocket(\"/ws/{user_id}/{exce}\")\nasync def websocket_endpoint(websocket: WebSocket, user_id:str, exce:str):\n\n if (not await loop.run_in_executor(None, connect_me, user_id, exce)):\n return\n await websocket.accept()\n # print(\"connected : \")\n data, img = None, None, \n degrees, positions, state, succ = None, None, None, None, \n try:\n while True:\n data = await websocket.receive_text()\n\n img = await loop.run_in_executor(\n None, imageio.imread, await loop.run_in_executor(\n None, base64.b64decode, data\n ) \n )\n \n # analyze(img, user_id)\n degrees, positions, state, succ = await loop.run_in_executor(\n None, analyze, img, user_id\n )\n\n if succ:\n await websocket.send_json(\n {\n \"degrees\":degrees,\n \"positions\":positions,\n \"state\":state\n }\n )\n else:\n await websocket.send_text(\"\")\n\n except WebSocketDisconnect:\n await loop.run_in_executor(\n None, disconnect, user_id\n )\n print(f\"Client #{user_id} left the chat\")\n\n \n\n# uvicorn app:app --reload --192.168.137.1\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"399752459","text":"# -----------------------------------------------------------\n#\n# This script is originally from\n# https://gist.githubusercontent.com/patrickfuller/8143294/raw/12701eb098c4d0c37cc0977de9df6f324d24e48f/github_traversal.py\n#\n# -----------------------------------------------------------\n\nimport requests\nimport getpass\nimport sys\nimport json\nfrom queue import Queue\n\n# This is a script, let's be lazy. We'll fill up this global and print it.\ng = {\"nodes\": [], \"edges\": []}\n# And here's the cutoff criterion\nMAX_NODES = 50\n\n# Log in to avoid rate limiting\nauth = input(\"Username: \"), getpass.getpass()\nr = requests.get(\"https://api.github.com\", auth=auth)\nif r.status_code != 200:\n raise Exception(\"Could not authenticate with Github. Exiting.\\n\")\nprint(\"Connected and authenticated.\")\n\n# BFS\nqueue = Queue()\nqueue.put((auth[0], None))\nwhile queue:\n if len(g[\"nodes\"]) > MAX_NODES:\n break\n user, parent = queue.get()\n if user in g[\"nodes\"]:\n continue\n sys.stderr.write(f\"Traversing {user}.\\n\")\n json_result = requests.get(f\"https://api.github.com/users/{user}\", auth=auth).json()\n g[\"nodes\"].append(\n {\n \"size\": pow(json_result[\"followers\"], 1 / 5),\n \"name\": user,\n \"url\": f\"https://github.com/{user}\",\n \"label\": \"Person\",\n \"description\": f\"{json_result['followers']} followers\",\n }\n )\n if parent:\n g[\"edges\"].append({\"src\": parent, \"dst\": user})\n followed = [\n res[\"login\"]\n for res in requests.get(\n f\"https://api.github.com/users/{user}/following\", auth=auth\n ).json()\n ]\n for f in followed:\n queue.put((f, user))\n\n\nwith open(\"github.json\", \"w\") as out_file:\n out_file.write(json.dumps(g))\n","sub_path":"examples/github_traversal.py","file_name":"github_traversal.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"268885952","text":"from urllib.parse import urlparse\n\n\n# Get domain name (example.com)\ndef get_domain_name(url):\n try:\n results = get_sub_domain_name(url).split('.')\n res = results[-2] + '.' + results[-1]\n #results[-3] + '.' +\n return res\n #return results[-2] + '.' + results[-1]\n except:\n return ''\n\n\n# Get sub domain name (name.example.com)\ndef get_sub_domain_name(url):\n try:\n return urlparse(url).netloc\n except:\n return ''\n\n#a = get_domain_name('https://www.worldometers.info/coronavirus')\n#print(a)\n","sub_path":"domain.py","file_name":"domain.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"176526121","text":"# -*- coding: utf-8 -*-\n\"\"\"\ncolor_kmeans.py\n\nCreated on Mon Aug 04 14:00:39 2014\nedit on Tue Sep 23 16:00 2014\n incorporated loop through file folder\n\n@author: mbess\n\"\"\"\n\n# import necessary packages\nfrom sklearn.cluster import KMeans\nimport matplotlib.pyplot as plt\nimport cv2\nimport utils\nimport os\n\nfilePath = 'c:/Users/mbess/Dev/cv/data/car/'\nnumClus = 3\n\nfor f in os.listdir(filePath):\n \n imagePath = os.path.join(filePath,f)\n figurePath = os.path.join('c:/temp/lpr/','colorProc_' + f)\n \n # load the image and convert it to RGB to display in matplotlib\n image = cv2.imread(imagePath)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n \n # save copy of original image\n orig_image = image\n \n # reshape image to a list of pixels\n image = image.reshape((image.shape[0] * image.shape[1], 3))\n \n # cluster the pixel intensity\n clt = sklearn.cluster.KMeans(n_clusters=numClus)\n clt.fit(image)\n\n # build histogram, create figure, and show\n hist = utils.centroid_histogram(clt)\n bar = utils.plot_colors(hist, clt.cluster_centers_)\n \n plt.figure(1)\n plt.subplot(2, 1, 1)\n plt.axis(\"off\")\n plt.imshow(orig_image)\n plt.subplot(2, 1, 2)\n plt.axis(\"on\")\n plt.imshow(bar)\n plt.show()\n plt.savefig(figurePath)","sub_path":"color_kmeans_2.py","file_name":"color_kmeans_2.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"393370925","text":"class Solution:\n def sortedSquares(self, nums: List[int]) -> List[int]:\n nums = [n*n for n in nums]\n s, e = 0, len(nums)-1\n ans = []\n while s <= e:\n if nums[s] < nums[e]:\n ans.append(nums[e])\n e -= 1\n else:\n ans.append(nums[s])\n s += 1\n ans.reverse()\n return ans","sub_path":"977-squares-of-a-sorted-array/977-squares-of-a-sorted-array.py","file_name":"977-squares-of-a-sorted-array.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"191760389","text":"from json import JSONEncoder\n\nfrom entity.request import *\n\n\nclass BBridgeJSONEncoder(JSONEncoder):\n def default(self, obj):\n if isinstance(obj, User):\n return {\n \"text\": obj.text,\n \"image_urls\": obj.image_urls\n }\n elif isinstance(obj, NLPData):\n return {\n \"sentences\": obj.sentences\n }\n elif isinstance(obj, ObjectDetectionData):\n return {\n \"url\": obj.url,\n \"threshold\": obj.threshold\n }\n elif isinstance(obj, ConceptDetectionData):\n return {\n \"image_urls\": obj.image_urls,\n \"count\": obj.count\n }\n else:\n return super(BBridgeJSONEncoder, self).default(obj)\n","sub_path":"entity/serialize/json_encoder.py","file_name":"json_encoder.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"552870881","text":"import sys\nsys.path.insert(0,\"../\")\n\nimport wrapperModules.plotting as p\nimport wrapperModules.files as f\nimport matplotlib.pyplot as plt\n\n\n# ==========================\n# Plot profile comparison\n# ==========================\npG = f.R_Uth_Dr_Uth(\"../output/problem3/approximative/Res20k/\"\\\n +\"02_24_2015__20_13_17__r-uth-dr_uth.debug\")\n\n# Approximative data\nrApprox = p.ProfilePlot.DataFormat(pG.data[\"r\"])\nuthApprox = p.ProfilePlot.DataFormat(pG.data[\"uth\"],r\"A\",\"x\",c=\"blue\")\ndr_uthApprox = p.ProfilePlot.DataFormat(pG.data[\"dr_uth\"],r\"A\",\"x\",c=\"blue\")\n\n# Data from simulation\nRMSProf = f.RMSProf(\"../input/turbulent/Res20k/rmsprof\")\nvelprof = f.VelProf(\"../input/turbulent/Res20k/velprof\")\nuthTurb = p.ProfilePlot.DataFormat(velprof.u_th,r\"T\",\"x\",\"red\")\ndr_uthTurb = p.ProfilePlot.DataFormat(RMSProf.dru_th,r\"T\",\"x\",\"red\")\n\n# Plot object\nuth = [uthApprox,uthTurb]\ndr_uth = [dr_uthApprox,dr_uthTurb]\nplot = p.ProfilePlot(rApprox,uth,dr_uth,r\"$Re_{s}=20k$ Profile comparison: approx vs. simul\")\n\n# Saving figure\nplot.save(\"output/02252015_cookmans_profileComparisonRes20k.pdf\")\n\n# ==========================\n# Plot k values comparison\n# ==========================\n\n# Output files\noApprox = f.OutputFile(\"../output/problem3/approximative/Res20k/\"\\\n +\"02_24_2015__20_13_17__problem3__nout000_\"\\\n +\"Res20k_approx_lowRes_nsym.output\")\n\n# Plot objects\nplot = p.Problem3Plot((oApprox,r\"A\"))\nplot.show()\n","sub_path":"assistance/code/max_eigenvalue/02242015_cookmans_Res20kApproxEvaluation.py","file_name":"02242015_cookmans_Res20kApproxEvaluation.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"251363122","text":"import os\nimport logging\n\nfrom kolekto.datasources import Datasource\n\nimport kaa.metadata\n\n# Configure the kaa.metadata logger in order to silent it:\nmetadata_logger = logging.getLogger('metadata')\nmetadata_logger.setLevel(logging.CRITICAL)\n\nclass MediainfosDatasource(Datasource):\n\n def attach(self, movie_hash, movie):\n filename = os.path.join(self.tree, '.kolekto', 'movies', movie_hash)\n infos = kaa.metadata.parse(filename)\n if infos is None:\n return movie\n\n movie['container'] = infos['type'].strip()\n\n # Set the quality of the video depending on its definition:\n if infos.video[0].width < 1280:\n movie['quality'] = 'SD'\n elif 1280 <= infos.video[0].width < 1920:\n movie['quality'] = '720p'\n else:\n movie['quality'] = '1080p'\n\n # Set the file extension depending on its mimetype:\n movie['ext'] = infos['mime'].split('/')[-1]\n\n # Set the movie length (in minutes)\n movie['runtime'] = int(infos['length'] / 60)\n\n return movie\n","sub_path":"kolekto/datasources/mediainfos.py","file_name":"mediainfos.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"523356284","text":"from selenium import webdriver\r\nfrom selenium import*\r\nfrom selenium.webdriver.common.keys import Keys\r\nimport time\r\nimport pynput\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nimport urllib.request\r\nimport urllib.request as urllib2\t\r\n#---------------------input string\r\n\r\nabc='mrinmoy aus'\r\nzz='https://www.bing.com/'\r\ndriver = webdriver.Chrome(\"c:/Users/soham/Downloads/chromedriver_win32/chromedriver\")\r\n\r\ndriver.get(zz)\r\ntime.sleep(0.5)\r\nsearch = driver.find_element_by_xpath('//*[@id=\"sb_form_q\"]')\r\nsearch.send_keys(abc,Keys.ENTER)\r\ntime.sleep(2)\r\n\r\ni=2\r\nprint(\"#b_results > li:nth-child(\"+str(i)+\") > h2 > a\")\r\nwhile(1):\r\n driver.find_element_by_css_selector(\"#b_results > li:nth-child(\"+str(i)+\") > h2 > a\").click()\r\n time.sleep(0.5)\r\n url = driver.current_url\r\n driver.get(url)\r\n\r\n time.sleep(2)\r\n dd=driver.find_element_by_xpath(\"//body\").text\r\n print(dd)\r\n cc=str(dd)\r\n \r\n try:\r\n file_object = open(\"output_bing_search.txt\",'a+')\r\n file_object.write(cc)\r\n file_object.close()\r\n driver.execute_script(\"window.history.go(-1)\")\r\n i=i+1\r\n \r\n except:\r\n driver.execute_script(\"window.history.go(-1)\")\r\n i=i+1\r\n \r\n","sub_path":"Bing.py","file_name":"Bing.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"340442642","text":"import torch\nimport argparse\nimport numpy as np\nfrom time import time\nimport os\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport torch.backends.cudnn as cudnn\nfrom utils import Preprocessing, get_data, Model, dice_coef, IOU, record_csv, dice_loss\nfrom net import Combine\nimport torch.utils.data\n\nparser = argparse.ArgumentParser(description='Train DTS with 2d segmentation')\n\nparser.add_argument('--view', default='XY', type=str, help='View from which side')\nparser.add_argument('--norm-axis', default='3', type=str, help='Normalization axis')\nparser.add_argument('--data', default=0, type=str, help='Data source')\n# parser.add_argument('--fid', default=0, type=int, help='Index of file which features save as.')\n# parser.add_argument('--fp16', action='store_true', help='Run model fp16 mode.')\n# parser.add_argument('--resume', action='store_true', help='Run model fp16 mode.')\n# parser.add_argument('--num-features', default=1000, type=int, help='The number of features.')\n# parser.add_argument('--batch-size', default=2, type=int, help='Batch size.')\n# parser.add_argument('--seed', default=2018, type=int, help='Random seed.')\nparser.add_argument('--lr', default=0.1, type=float, help='Initial learning rate.')\nparser.add_argument('--epoch', default=50, type=int, help='Initial learning rate.')\nparser.add_argument('--gpu', default=-1, type=int, help='Using which gpu.')\nparser.add_argument('--threshold', default=0.9, type=float, help='Threshold')\n# parser.add_argument('--epoch', default=50, type=int, help='Initial learning rate.')\nparser.add_argument('--net', default='ours', type=str, help='which network')\nargs = parser.parse_args()\n\n####\n# Global Flag\n###\n\nconfig = {}\n\n# Config setting\n# config['view'] = args.view\n# config['norm_axis'] = args.norm_axis\nconfig['resume'] = False\nconfig['use_cuda'] = True\nconfig['fp16'] = False\nconfig['dtype'] = torch.float16 if config['fp16'] else torch.float32\nconfig['gpu'] = args.gpu\nconfig['batch_size'] = 2\nconfig['seed'] = 2018\nconfig['save_path'] = \"checkpoints_2p/%s\" % (args.data)\nconfig['wd'] = 0.0001\nconfig['epoch'] = args.epoch\nconfig['lr_decay'] = np.arange(2, 50)\nconfig['experiment_name'] = args.net\nconfig['save_prediction_path'] = 'final_labels'\ndata_path = '%s/second_data%s' % (args.net, args.data)\ntrain_data, train_label, test_data, test_label = get_data(data_path)\n# del test_data, test_label\ntorch.manual_seed(config['seed'])\n\nif not os.path.exists(config['experiment_name']):\n os.mkdir(config['experiment_name'])\n\nos.chdir(config['experiment_name'])\n\nc = torch.from_numpy(test_data)\ntestset = torch.utils.data.TensorDataset(c)\n\n\ntest_loader = torch.utils.data.DataLoader(testset, batch_size=config['batch_size'], shuffle=False, num_workers=1)\n\nnet = Combine(norm='InstanceNorm')\nmodel = Model(net=net, config=config)\n\n\nmodel.resume(save_path=config['save_path'], filename='ckpt_%d.t7' % config['epoch'])\n\nprint('Test inference:')\ntest_images = model.inference(test_loader)\n\n\nif not os.path.exists(config['save_prediction_path']):\n os.mkdir(config['save_prediction_path'])\nos.chdir(config['save_prediction_path'])\nprint('Save images...')\nnp.save(\"%s.npy\" % (args.data), test_images.astype(np.uint8))\nprint(test_images.shape)\nos.chdir(os.pardir)\nos.chdir(os.pardir)\n","sub_path":"second_phase_predict.py","file_name":"second_phase_predict.py","file_ext":"py","file_size_in_byte":3282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"367977135","text":"from collections import defaultdict\nfrom collections.abc import Callable, Iterable\nfrom functools import partial\nfrom numbers import Number\n\nimport ipywidgets as widgets\nimport matplotlib.widgets as mwidgets\nimport numpy as np\nfrom IPython.display import display as ipy_display\nfrom matplotlib import __version__ as mpl_version\nfrom matplotlib import get_backend\nfrom matplotlib.pyplot import axes\nfrom numpy.distutils.misc_util import is_sequence\nfrom packaging import version\n\nfrom .utils import figure, ioff\n\n__all__ = [\n \"decompose_bbox\",\n \"update_datalim_from_xy\",\n \"update_datalim_from_bbox\",\n \"is_jagged\",\n \"broadcast_to\",\n \"prep_broadcast\",\n \"broadcast_arrays\",\n \"broadcast_many\",\n \"notebook_backend\",\n \"callable_else_value\",\n \"kwargs_to_ipywidgets\",\n \"extract_num_options\",\n \"changeify\",\n \"kwargs_to_mpl_widgets\",\n \"create_slider_format_dict\",\n \"gogogo_figure\",\n \"gogogo_display\",\n]\n\n\ndef decompose_bbox(bbox):\n return bbox.x0, bbox.y0, bbox.x1, bbox.y1\n\n\ndef _update_limits(ax, x0, y0, x1, y1, x0_, y0_, x1_, y1_, stretch_x, stretch_y):\n if stretch_x:\n x0 = np.min([x0, x0_])\n x1 = np.max([x1, x1_])\n else:\n x0 = x0_\n x1 = x1_\n\n if stretch_y:\n y0 = np.min([y0, y0_])\n y1 = np.max([y1, y1_])\n else:\n y0 = y0_\n y1 = y1_\n # now relim and always take the maximum extent\n ax.relim()\n ax.dataLim.update_from_data_xy(np.asarray([[x0, y0], [x1, y1]]), ignore=False)\n\n\ndef update_datalim_from_bbox(ax, bbox, stretch_x=True, stretch_y=True):\n _update_limits(ax, *decompose_bbox(ax.dataLim), *decompose_bbox(bbox), stretch_x, stretch_y)\n\n\ndef update_datalim_from_xy(ax, x, y, stretch_x=True, stretch_y=True):\n \"\"\"\n current : ax.dataLim\n x : array\n the new x datavalues to include\n y : array\n the new y datavalues to include\n \"\"\"\n # this part bc scatter not affect by relim\n # so need this to keep stretchign working for scatter\n x0_ = np.min(x)\n x1_ = np.max(x)\n y0_ = np.min(y)\n y1_ = np.max(y)\n _update_limits(ax, *decompose_bbox(ax.dataLim), x0_, y0_, x1_, y1_, stretch_x, stretch_y)\n\n\ndef is_jagged(seq):\n \"\"\"\n checks for jaggedness up to two dimensions\n don't need more because more doesn't make any sense for this library\n need this bc numpy is unhappy about being passed jagged arrays now :(\n \"\"\"\n lens = []\n if is_sequence(seq):\n for y in seq:\n if isinstance(y, Number) or isinstance(y, Callable):\n lens.append(0)\n continue\n try:\n lens.append(len(y))\n except TypeError:\n return True\n if not all(lens[0] == l for l in lens):\n return True\n return False\n\n\ndef prep_broadcast(arr):\n if arr is None:\n return np.atleast_1d(None)\n if is_jagged(arr):\n arr = np.asarray(arr, dtype=np.object)\n elif isinstance(arr, Number) or isinstance(arr, Callable):\n arr = np.atleast_1d(arr)\n else:\n arr = np.atleast_1d(arr)\n if np.issubdtype(arr.dtype, np.number) and arr.ndim == 1:\n arr = arr[None, :]\n return arr\n\n\ndef broadcast_to(arr, to_shape, names):\n \"\"\"\n happily this doesn't increase memory footprint e.g:\n import sys\n xs = np.arange(5)\n print(sys.getsizeof(xs.nbytes))\n print(sys.getsizeof(np.broadcast_to(xs, (19000, xs.shape[0]))))\n\n gives 28 and 112. Note 112/28 != 19000\n \"\"\"\n if arr.shape[0] == to_shape[0]:\n return arr\n\n if arr.ndim > 1:\n if arr.shape[0] == 1:\n return np.broadcast_to(arr, (to_shape[0], *arr.shape[1:]))\n else:\n raise ValueError(f\"can't broadcast {names[0]} {arr.shape} onto {names[1]} {to_shape}\")\n elif arr.shape[0] == 1:\n return np.broadcast_to(arr, (to_shape[0],))\n else:\n raise ValueError(f\"can't broadcast {names[0]} {arr.shape} onto {names[1]} {to_shape}\")\n\n\ndef broadcast_arrays(*args):\n \"\"\"\n This is a modifed version the numpy `broadcast_arrays` function\n that uses a verion of _broadcast_to that only considers the first axis\n \"\"\"\n\n shapes = [array.shape[0] for (array, name) in args]\n idx = np.argmax(shapes)\n if all([shapes[0] == s for s in shapes]):\n # case where nothing needs to be broadcasted.\n return [array for (array, name) in args]\n return [broadcast_to(array, args[idx][0].shape, [name, args[idx][1]]) for (array, name) in args]\n\n\ndef broadcast_many(*args):\n \"\"\"\n helper to call prep_broadcast followed by broadcast arrays\n keep as a separate function to keep the idea of broadcast_arrays the same\n \"\"\"\n return broadcast_arrays(*[(prep_broadcast(arg[0]), arg[1]) for arg in args])\n\n\ndef notebook_backend():\n \"\"\"\n returns True if the backend is ipympl or nbagg, otherwise False\n \"\"\"\n backend = get_backend().lower()\n if \"ipympl\" in backend:\n return True\n elif backend == \"nbAgg\".lower():\n return True\n return False\n\n\ndef callable_else_value(arg, params):\n if isinstance(arg, Callable):\n return arg(**params)\n return arg\n\n\ndef kwargs_to_ipywidgets(\n kwargs, params, update, slider_format_strings, play_buttons=False, play_button_pos=\"right\"\n):\n \"\"\"\n this will break if you pass a matplotlib slider. I suppose it could support mixed types of sliders\n but that doesn't really seem worthwhile?\n\n parameters\n ----------\n play_button: boolean or dict\n if boolean it will be applied to all sliders. If a dict it should have the same keys\n as kwargs and the values should be True or False. Or an iterable of strings of parameter names\n \"\"\"\n labels = []\n sliders = []\n controls = []\n players = []\n if isinstance(play_buttons, bool):\n has_play_button = defaultdict(lambda: play_buttons)\n elif isinstance(play_buttons, defaultdict):\n has_play_button = play_buttons\n elif isinstance(play_buttons, dict):\n has_play_button = defaultdict(lambda: False, play_buttons)\n elif isinstance(play_buttons, Iterable) and all([isinstance(p, str) for p in play_buttons]):\n has_play_button = defaultdict(\n lambda: False, dict(zip(play_buttons, [True] * len(play_buttons)))\n )\n else:\n has_play_button = play_buttons\n\n for key, val in kwargs.items():\n if isinstance(val, set):\n if len(val) == 1:\n val = val.pop()\n if isinstance(val, tuple):\n # want the categories to be ordered\n pass\n else:\n # fixed parameter\n params[key] = val\n else:\n val = list(val)\n\n # categorical\n if len(val) <= 3:\n selector = widgets.RadioButtons(options=val)\n else:\n selector = widgets.Select(options=val)\n params[key] = val[0]\n controls.append(selector)\n selector.observe(partial(update, key=key, label=None), names=[\"value\"])\n elif isinstance(val, widgets.Widget) or isinstance(val, widgets.fixed):\n if not hasattr(val, \"value\"):\n raise TypeError(\n \"widgets passed as parameters must have the `value` trait.\"\n \"But the widget passed for {key} does not have a `.value` attribute\"\n )\n if isinstance(val, widgets.fixed):\n params[key] = val.value\n else:\n params[key] = val.value\n controls.append(val)\n val.observe(partial(update, key=key, label=None), names=[\"value\"])\n else:\n if isinstance(val, tuple) and len(val) in [2, 3]:\n # treat as an argument to linspace\n # idk if it's acceptable to overwrite kwargs like this\n # but I think at this point kwargs is just a dict like any other\n val = np.linspace(*val)\n kwargs[key] = val\n val = np.atleast_1d(val)\n if val.ndim > 1:\n raise ValueError(f\"{key} is {val.ndim}D but can only be 1D or a scalar\")\n if len(val) == 1:\n # don't need to create a slider\n params[key] = val\n else:\n params[key] = val[0]\n labels.append(widgets.Label(value=slider_format_strings[key].format(val[0])))\n sliders.append(\n widgets.IntSlider(min=0, max=val.size - 1, readout=False, description=key)\n )\n if has_play_button[key]:\n players.append(widgets.Play(min=0, max=val.size - 1, step=1))\n widgets.jslink((players[-1], \"value\"), (sliders[-1], \"value\"))\n if play_button_pos == \"left\":\n controls.append(widgets.HBox([players[-1], sliders[-1], labels[-1]]))\n else:\n controls.append(widgets.HBox([sliders[-1], labels[-1], players[-1]]))\n else:\n controls.append(widgets.HBox([sliders[-1], labels[-1]]))\n sliders[-1].observe(partial(update, key=key, label=labels[-1]), names=[\"value\"])\n return sliders, labels, controls, players\n\n\ndef extract_num_options(val):\n \"\"\"\n convert a categorical to a number of options\n \"\"\"\n if len(val) == 1:\n for v in val:\n if isinstance(v, tuple):\n # this looks nightmarish...\n # but i think it should always work\n # should also check if the tuple has length one here.\n # that will only be an issue if a trailing comma was used to make the tuple ('beep',)\n # but not ('beep') - the latter is not actually a tuple\n return len(v)\n else:\n return 0\n else:\n return len(val)\n\n\ndef changeify(val, key, update):\n \"\"\"\n make matplotlib update functions return a dict with key 'new'.\n Do this for compatibility with ipywidgets\n \"\"\"\n update({\"new\": val}, key, None)\n\n\n# this is a bunch of hacky nonsense\n# making it involved me holding a ruler up to my monitor\n# if you have a better solution I would love to hear about it :)\n# - Ian 2020-08-22\ndef kwargs_to_mpl_widgets(kwargs, params, update, slider_format_strings):\n n_opts = 0\n n_radio = 0\n n_sliders = 0\n for key, val in kwargs.items():\n if isinstance(val, set):\n new_opts = extract_num_options(val)\n if new_opts > 0:\n n_radio += 1\n n_opts += new_opts\n elif (\n not isinstance(val, mwidgets.AxesWidget)\n and not isinstance(val, widgets.fixed)\n and isinstance(val, Iterable)\n and len(val) > 1\n ):\n n_sliders += 1\n\n # These are roughly the sizes used in the matplotlib widget tutorial\n # https://matplotlib.org/3.2.2/gallery/widgets/slider_demo.html#sphx-glr-gallery-widgets-slider-demo-py\n slider_in = 0.15\n radio_in = 0.6 / 3\n widget_gap_in = 0.1\n\n widget_inches = (\n n_sliders * slider_in + n_opts * radio_in + widget_gap_in * (n_sliders + n_radio + 1) + 0.5\n ) # half an inch for margin\n fig = None\n if not all(map(lambda x: isinstance(x, mwidgets.AxesWidget), kwargs.values())):\n # if the only kwargs are existing matplotlib widgets don't make a new figure\n with ioff:\n fig = figure()\n size = fig.get_size_inches()\n fig_h = widget_inches\n fig.set_size_inches(size[0], widget_inches)\n slider_height = slider_in / fig_h\n radio_height = radio_in / fig_h\n # radio\n gap_height = widget_gap_in / fig_h\n widget_y = 0.05\n slider_ax = []\n sliders = []\n radio_ax = []\n radio_buttons = []\n cbs = []\n for key, val in kwargs.items():\n if isinstance(val, set):\n if len(val) == 1:\n val = val.pop()\n if isinstance(val, tuple):\n pass\n else:\n params[key] = val\n continue\n else:\n val = list(val)\n\n n = len(val)\n longest_len = max(list(map(lambda x: len(list(x)), map(str, val))))\n # should probably use something based on fontsize rather that .015\n width = max(0.15, 0.015 * longest_len)\n radio_ax.append(axes([0.2, 0.9 - widget_y - radio_height * n, width, radio_height * n]))\n widget_y += radio_height * n + gap_height\n radio_buttons.append(mwidgets.RadioButtons(radio_ax[-1], val, active=0))\n cbs.append(radio_buttons[-1].on_clicked(partial(changeify, key=key, update=update)))\n params[key] = val[0]\n elif isinstance(val, mwidgets.RadioButtons):\n val.on_clicked(partial(changeify, key=key, update=update))\n params[key] = val.val\n elif isinstance(val, mwidgets.Slider):\n val.on_changed(partial(changeify, key=key, update=update))\n params[key] = val.val\n else:\n if isinstance(val, tuple):\n if len(val) == 2:\n min_ = val[0]\n max_ = val[1]\n elif len(val) == 3:\n # should warn that that doesn't make sense with matplotlib sliders\n min_ = val[0]\n max_ = val[1]\n else:\n val = np.atleast_1d(val)\n if val.ndim > 1:\n raise ValueError(f\"{key} is {val.ndim}D but can only be 1D or a scalar\")\n if len(val) == 1:\n # don't need to create a slider\n params[key] = val[0]\n continue\n else:\n # list or numpy array\n # should warn here as well\n min_ = np.min(val)\n max_ = np.max(val)\n\n slider_ax.append(axes([0.2, 0.9 - widget_y - gap_height, 0.65, slider_height]))\n sliders.append(\n mwidgets.Slider(\n slider_ax[-1],\n key,\n min_,\n max_,\n valinit=min_,\n valfmt=slider_format_strings[key],\n )\n )\n cbs.append(sliders[-1].on_changed(partial(changeify, key=key, update=update)))\n widget_y += slider_height + gap_height\n params[key] = min_\n controls = [fig, radio_ax, radio_buttons, slider_ax, sliders]\n return controls\n\n\ndef create_slider_format_dict(slider_format_string, use_ipywidgets):\n # mpl sliders for verison 3.3 and onwards support None as an argument for valfmt\n mpl_gr_33 = version.parse(mpl_version) >= version.parse(\"3.3\")\n if isinstance(slider_format_string, str):\n slider_format_strings = defaultdict(lambda: slider_format_string)\n elif isinstance(slider_format_string, dict) or slider_format_string is None:\n if use_ipywidgets:\n slider_format_strings = defaultdict(lambda: \"{:.2f}\")\n elif mpl_gr_33:\n slider_format_strings = defaultdict(lambda: None)\n else:\n slider_format_strings = defaultdict(lambda: \"%1.2f\")\n\n if slider_format_string is not None:\n for key, val in slider_format_string.items():\n slider_format_strings[key] = val\n else:\n raise ValueError(\n f\"slider_format_string must be a dict or a string but it is a {type(slider_format_string)}\"\n )\n return slider_format_strings\n\n\ndef gogogo_figure(ipympl, figsize, ax=None):\n \"\"\"\n gogogo the greatest function name of all\n \"\"\"\n if ax is None:\n if ipympl:\n with ioff:\n fig = figure(figsize=figsize)\n ax = fig.gca()\n else:\n fig = figure(figsize=figsize)\n ax = fig.gca()\n return fig, ax\n else:\n return ax.get_figure(), ax\n\n\ndef gogogo_display(ipympl, use_ipywidgets, display, controls, fig):\n if use_ipywidgets:\n controls = widgets.VBox(controls)\n if display:\n if ipympl:\n ipy_display(widgets.VBox([controls, fig.canvas]))\n else:\n # for the case of using %matplotlib qt\n # but also want ipywidgets sliders\n # ie with force_ipywidgets = True\n ipy_display(controls)\n fig.show()\n else:\n if display:\n fig.show()\n controls[0].show()\n return controls\n","sub_path":"mpl_interactions/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":16658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"15176070","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 14 14:01:56 2017\n\n@author: Alex Kerzner\n\"\"\"\n\n# Import config parser\nfrom lib import Config\n\n# Import core\nfrom PyQt5.QtCore import Qt\n\n# Import Qt widget components\nfrom PyQt5.QtWidgets import \\\n QApplication,\\\n QMainWindow,\\\n QMessageBox,\\\n QWidget,\\\n QPushButton,\\\n QAction,\\\n QTabWidget,\\\n QSplitter,\\\n QTreeWidget,\\\n QTreeWidgetItem,\\\n QStackedWidget,\\\n QLabel,\\\n QSpinBox,\\\n QFormLayout,\\\n QLineEdit,\\\n QWizard,\\\n QWizardPage,\\\n QFileDialog,\\\n QScrollArea\n\n# Import PyQtGraph library\n#import pyqtgraph as pg\n\n# Import NumPy\n#import numpy as np\n\n# Import Core Qt components\nfrom PyQt5.QtCore import qDebug,qInf,qWarning,qCritical,qFatal\n\n# Import Qt main gui components\nfrom PyQt5.QtGui import QIcon\n\n\n# Import Main_Application\nfrom Main_Application import Main_Application\nfrom PyQt5.Qt import QDialog, QDialogButtonBox, QTextDocument, QTextBlock\n\n\"\"\"\nClass for viewing models\n\"\"\"\nclass ModelViewer(QSplitter):\n\t\n\tdef __init__(self):\n\t\t# Call superconstructor\n\t\tsuper(self.__class__, self).__init__()\n\t\t\n\t\t# Create left pane\n\t\tleft_pane = QSplitter()\n\t\tleft_pane.setOrientation(Qt.Vertical)\n\t\t\n\t\t# Create right pane\n\t\tright_pane = QSplitter()\n\t\tright_pane.setOrientation(Qt.Vertical)\n\t\t\n\t\t\n\t\t# Create Model Tree widget\n\t\tself.listbox = QTreeWidget()\n\t\tself.listbox.setColumnCount(1)\n\t\tself.listbox.setAnimated(True)\n\t\tself.listbox.setHeaderLabel(\"List of models by city\")\n\t\tself.listbox.setStatusTip('Select a model')\n\t\tleft_pane.addWidget(self.listbox)\n\t\t\n\t\t# Create Model Visualization widget\n\t\tself.plot = QStackedWidget()\n\t\tright_pane.addWidget(self.plot)\n\t\t\n\t\t# Create scroll area for Model Description widget\n\t\tscroll_area = QScrollArea()\n\t\tscroll_area.setWidgetResizable(True)\n\t\tleft_pane.addWidget(scroll_area)\n\t\t\n\t\t# Create Model Description widget\n\t\tself.description = QLabel()\n\t\tself.description.setWordWrap(True)\n\t\tscroll_area.setWidget(self.description)\n\t\tself.description.show()\n\t\t\n\t\t\n\t\t# Add to this widget\n\t\tself.addWidget(left_pane)\n\t\tself.addWidget(right_pane)\n\n\"\"\"\nClass for storing form items\n\"\"\"\nclass Form(object):\n\tdef __init__(self):\n\t\tself.label = {}\n\t\tself.widget = {}\n\n\n\"\"\"\nClass for the about window\n\"\"\"\nclass About_Window(QMessageBox):\n\t\n\tdef __init__(self, parent):\n\t\t# Call superconstructor\n\t\tsuper(self.__class__, self).__init__(parent)\n\t\tself.setWindowTitle(\"Badger Data Science\")\n\t\ttext = \"

    Badger Data Science

    \"\n\t\ttext += \"

    Version 1.0.0

    \"\n\t\ttext += \"

    This data science project was written to analyze\\\n\t\tbus and metro infrastructure in three major cities.

    \"\n\t\ttext += \"Created by:
      \"\n\t\ttext += \"
    • mvonderlippe
    • \"\n\t\ttext += \"
    • sproctor
    • \"\n\t\ttext += \"
    • dsahdeo
    • \"\n\t\ttext += \"
    • sbadger
    • \"\n\t\ttext += \"
    • jdemey
    • \"\n\t\ttext += \"
    • akerzner
    • \"\n\t\ttext += \"
    \"\n\t\tself.setAttribute(Qt.WA_DeleteOnClose)\n\t\tself.setText(text)\n\n\n\"\"\"\nClass for the main GUI window.\n\"\"\"\nclass Main_Window(QMainWindow):\n\t\n\t\n\t\"\"\"\n\tDefault constructor for this window.\n\tCalls the Main_Application\n\t\"\"\"\n\tdef __init__(self):\n\t\t# Call superconstructor\n\t\tsuper(self.__class__, self).__init__()\n\t\t\n\t\t# Main application\n\t\tself.app = 0\n\t\t\n\t\t# Model viewer\n\t\tself.model_viewer = 0\n\t\t\t\n\t\t# Load configuration\n\t\tself.config = Config.getConfig()\n\t\t\n\t\t# Create application\n\t\tself.app = Main_Application()\n\t\t\n\t\t# Initialize GUI\n\t\tself.initUI()\n\t\t\n\t\tself._loadAllCities()\n\t\t\n\t\t# Show GUI\n\t\tself.show()\n\t\n\t\"\"\"\n\tConstruct GUI elements\n\t\"\"\"\n\tdef initUI(self):\n\t\t\n\t\t# Structures to hold various UI components\n\t\tmenu = {}\n\t\taction = {}\n\t\twidget = {}\n\t\ttab = {}\n\t\tlayout = {}\n\t\t\n\t\tform = Form()\n\t\tself.form=form\n\t\t# Temporary value to simplify code\n\t\tcurrent_item = \"\"\n\t\t\n\t\t\n\t\t\n\t\t# Set the title of the window\n\t\tself.setWindowTitle(\"Badger Data Science\")\n\t\t\n\t\t# Resize window\n\t\tself.resize(self.config.getint(\"GUI\", \"width\"),\\\n\t\t\tself.config.getint(\"GUI\", \"height\"))\n\t\t\n\t\t# Create status bar\n\t\tself.statusBar()\n\t\t\n\t\t\n\t\t#######################\n\t\t# Create the menu bar #\n\t\t#######################\n\t\t\n\t\t# Create menu bar\n\t\tmenu_bar = self.menuBar()\n\t\t\n\t\t\n\t\t# Create File menu\n\t\tmenu[\"file\"] = menu_bar.addMenu('&File')\n\t\t\n\t\t# Create File->Exit menu\n\t\tcurrent_item = \"exit\"\n\t\taction[current_item] = QAction('&Exit', self)\n\t\taction[current_item].setShortcut('Ctrl+Shift+C')\n\t\taction[current_item].setStatusTip('Close this application')\n\t\taction[current_item].triggered.connect(self.close)\n\t\tmenu[\"file\"].addAction(action[current_item])\n\t\t\n\t\t# Create Help menu\n\t\tmenu[\"help\"] = menu_bar.addMenu('&Help')\n\t\t\n\t\t\n\t\t# Create Help->AboutQt menu\n\t\tcurrent_item = \"about_qt\"\n\t\taction[current_item] = QAction('About &Qt', self)\n\t\taction[current_item].setStatusTip('About Qt')\n\t\taction[current_item].triggered.connect(QApplication.aboutQt)\n\t\tmenu[\"help\"].addAction(action[current_item])\n\t\t\n\t\t# Create Help->About menu\n\t\tcurrent_item = \"about\"\n\t\taction[current_item] = QAction('&About', self)\n\t\taction[current_item].setShortcut('F1')\n\t\taction[current_item].setStatusTip('About this application')\n\t\taction[current_item].triggered.connect(self.showAboutWindow)\n\t\tmenu[\"help\"].addAction(action[current_item])\n\t\t\n\t\t\n\t\t######################\n\t\t# Create the widgets #\n\t\t######################\n\t\t\n\t\t# Create tab switcher widget\n\t\tcurrent_item = \"tab_switcher\"\n\t\twidget[current_item] = QTabWidget()\n\t\tself.setCentralWidget(widget[current_item])\n\t\twidget[current_item].setStatusTip('Switch between tabs')\n\t\t\n\t\t# Create Optimize tab\n\t\tcurrent_item = \"optimize\"\n\t\ttab[current_item] = QSplitter()\n\t\ttab[current_item].setStatusTip('Optimize your city')\n\t\twidget[\"tab_switcher\"].addTab(tab[current_item], 'Optimize')\n\t\t\n\t\t# Create Predict/IO widget\n\t\tcurrent_item = \"predict_io\"\n\t\twidget[current_item] = QSplitter()\n\t\twidget[current_item].setOrientation(Qt.Vertical)\n\t\twidget[current_item].setStatusTip(\"Predict input/output\")\n\t\ttab[\"optimize\"].addWidget(widget[current_item])\n\t\t\n\t\t# Create Predict/input layout\n\t\tlayout[\"predict_input\"] = QFormLayout()\n\t\t\n\t\t# Create Budget form input\n\t\tcurrent_item = \"budget_input\"\n\t\tform.label[current_item] = QLabel()\n\t\tform.label[current_item].setText(\"Maximum budget (USD, thousands)\")\n\t\tform.widget[current_item] = QSpinBox()\n\t\tform.widget[current_item].setSingleStep(1000)\n\t\tform.widget[current_item].setRange(1, 1000000)\n\t\tform.widget[current_item].setStatusTip(\"Budget, in thousands of US dollars, to allocate to your city\")\n\t\tlayout[\"predict_input\"].addRow(form.label[current_item],form.widget[current_item])\n\t\t\n\t\t#Create Submit button\n\t\tcurrent_item = \"submit_button\"\n\t\tform.widget[current_item] = QPushButton(\"Calculate\")\n\t\tform.widget[current_item].clicked.connect(self.calculate)\n\t\tlayout[\"predict_input\"].addRow(form.widget[current_item])\n\t\t\n\t\t# Create Predict/output layout\n\t\tlayout[\"predict_output\"] = QFormLayout()\n\t\t\n\t\t#Create metro allocation form output\n\t\tcurrent_item = \"metro_output\"\n\t\tform.label[current_item] = QLabel(\"Metro allocation (USD, thousands)\")\n\t\tform.widget[current_item] = QLineEdit()\n\t\tform.widget[current_item].setReadOnly(True)\n\t\tform.widget[current_item].setStatusTip(\"Money, in thousands of US dollars, to allocate to your city's metro system\")\n\t\tform.widget[current_item].setEnabled(False)\n\t\tlayout[\"predict_output\"].addRow(form.label[current_item], form.widget[current_item])\n\t\t\n\t\t#Create bus allocation form output\n\t\tcurrent_item = \"bus_output\"\n\t\tform.label[current_item] = QLabel(\"Bus allocation (USD, thousands)\")\n\t\tform.widget[current_item] = QLineEdit()\n\t\tform.widget[current_item].setReadOnly(True)\n\t\tform.widget[current_item].setEnabled(False)\n\t\tform.widget[current_item].setStatusTip(\"Money, in thousands of US dollars, to allocate to your city's bus system\")\n\t\tlayout[\"predict_output\"].addRow(form.label[current_item], form.widget[current_item])\n\t\t\n\t\t#Create projected ridership form output\n\t\tcurrent_item = \"ridership_output\"\n\t\tform.label[current_item] = QLabel(\"Projected ridership\")\n\t\tform.widget[current_item] = QLineEdit()\n\t\tform.widget[current_item].setReadOnly(True)\n\t\tform.widget[current_item].setEnabled(False)\n\t\tform.widget[current_item].setStatusTip(\"How many people are expected to be transported by your transit system\")\n\t\tlayout[\"predict_output\"].addRow(form.label[current_item], form.widget[current_item])\n\t\t\n\t\t# Create Predict/input widget\n\t\tcurrent_item = \"predict_input\"\n\t\twidget[current_item] = QWidget()\n\t\twidget[current_item].setLayout(layout[current_item])\n\t\twidget[\"predict_io\"].addWidget(widget[current_item])\n\t\t\n\t\t# Create Predict/output widget\n\t\tcurrent_item = \"predict_output\"\n\t\twidget[current_item] = QWidget()\n\t\twidget[current_item].setLayout(layout[current_item])\n\t\twidget[\"predict_io\"].addWidget(widget[current_item])\n\t\t\n\t\t\n\t\t# Create Data visualization tab\n\t\tcurrent_item = \"data_visualization\"\n\t\tself.model_viewer = ModelViewer()\n\t\t# Enable model switching\n\t\tself.model_viewer.listbox.currentItemChanged.connect(\\\n\t\t\tlambda current, previous: self.switchModel(current, previous))\n\t\twidget[\"tab_switcher\"].addTab(self.model_viewer, 'Data Visualization')\n\t\t\n\t\"\"\"\n\tGets called when the calculate button is pressed.\n\t\"\"\"\n\tdef calculate(self):\n\t\t# Predict the values given the budget input\n\t\tif (self.form.widget['budget_input'].value() == 0):\n\t\t\tqWarning(\"Warning: a budget of zero was attempted. Action denied.\")\n\t\t\treturn\n\t\t\n\t\tgoods = self.app.getTheGoods(self.form.widget['budget_input'].value())\n\t\t# Goods: $metro, $bus, $ridership\n\t\t\n\t\t# Set label for metro allocation output\n\t\tself.form.widget[\"metro_output\"].setText(str(goods[0]))\n\t\t\n\t\t# Set label for bus allocation output\n\t\tself.form.widget[\"bus_output\"].setText(str(goods[1]))\n\t\t\n\t\t# Set label for projected ridership output\n\t\tself.form.widget[\"ridership_output\"].setText(str(goods[2]))\n\t\"\"\"\n\tShow about window\n\t\"\"\"\n\tdef showAboutWindow(self):\n\t\t# Create about window, and show\n\t\tAbout_Window(self).exec_()\n\t\n\t\"\"\"\n\tAdd a city\n\t\"\"\"\n\tdef addCity(self):\n\t\treturn\n\t\n\t\"\"\"\n\tAdd UI item for a city by its id\n\t@param city_id the id of the city\n\t\"\"\"\n\tdef _addCityItem(self, city_id):\n\t\t# Add top-level-entry for city\n\t\tcity_container = QTreeWidgetItem(self.model_viewer.listbox)\n\t\t# Add name\n\t\tcity_container.setText(0, self.app.cities[city_id].name)\n\t\t\n\t\t# Add all models under city\n\t\tfor model_name in self.app.cities[city_id].model_names:\n\t\t\tmodel_item = QTreeWidgetItem(city_container)\n\t\t\tmodel_item.setText(0, model_name)\n\t\t\tself.model_viewer.plot.addWidget(self.app.cities[city_id].models[model_name].plot)\n\t\tself.model_viewer.listbox.addTopLevelItem(city_container)\n\t\"\"\"\n\tLoad all cities\n\t\"\"\"\n\tdef _loadAllCities(self):\n\t\tfor city_id in range(len(self.app.cities)):\n\t\t\tself._addCityItem(city_id)\n\t\n\t\"\"\"\n\tGUI: Switch from previously selected model to the current selected model\n\t\n\t@param current = the current selected model\n\t@param previous = the previous valid selected model\n\t\"\"\"\n\tdef switchModel(self, current, previous):\n\t\t# Verify that current is valid: current has no children\n\t\tif (current.childCount() == 0 and not current.parent() == None):\n\t\t\t# Model is selected\n\t\t\tcity_name = current.parent().text(0)\n\t\t\tcity_id = self.app.getCityID(city_name)\n\t\t\t\n\t\t\tif (city_id == None):\n\t\t\t\t# Redundant fail, invalid id\n\t\t\t\tprint(\"Error: invalid selection (city id not valid)\")\n\t\t\t\treturn\n\t\t\tcurrent_model = current.text(0)\n\t\t\t\n\t\t\t# Update plot\n\t\t\tself.model_viewer.plot.setCurrentWidget(self.app.cities[city_id].models[current_model].plot)\n\t\t\t# Update description\n\t\t\tself.model_viewer.description.setText(self.app.cities[city_id].models[current_model].description)\n\t\t\n\t\t# Old code\n\t\t#self.widget[\"plot\"].plot(self.model[model_name].getX(), self.model[model_name].getY(), pen=None, symbol='o')\n","sub_path":"bin/User_Interface.py","file_name":"User_Interface.py","file_ext":"py","file_size_in_byte":11521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"489727805","text":"from mpl_toolkits.basemap import Basemap, cm, shiftgrid,interp,maskoceans\nfrom netCDF4 import Dataset as NetCDFFile\nimport numpy as N\nimport matplotlib.pyplot as plt\nimport glob\nimport numpy.ma as ma\nfrom scipy.interpolate import griddata\nimport matplotlib.colors as colors\nfrom scipy.stats import ttest_ind\n\n\niizumi=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/iizumi/iizumi.2013JAN29.soybean.1982-2006.30min.nc4','r')\n#print iizumi\niyield = iizumi.variables['yield50'][18,:,:]\niarea =iizumi.variables['area'][18,:,:]\nla=iizumi.variables['lat'][:]\nlo=iizumi.variables['lon'][:]\niyield=N.flipud(iyield)\niarea=N.flipud(iarea)\n\nregion1=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/HistoricalGLM_crop_150901.nc','r')\nmaitrop = region1.variables['soy_trop'][99,:,:]\nmaitemp = region1.variables['soy_temp'][99,:,:]\nmaitropi=region1.variables['soy_trop_irrig'][99,:,:]\nmaitempi=region1.variables['soy_temp_irrig'][99,:,:]\ngridarea = region1.variables['area'][:,:]\nmaitrop=ma.masked_where(maitrop<=0,maitrop)\nmaitrop=ma.filled(maitrop, fill_value=0.)\nmaitemp=ma.masked_where(maitemp<=0,maitemp)\nmaitemp=ma.filled(maitemp, fill_value=0.)\n\nmaitropi=ma.masked_where(maitropi<=0,maitropi)\nmaitropi=ma.filled(maitropi, fill_value=0.)\nmaitempi=ma.masked_where(maitempi<=0,maitempi)\nmaitempi=ma.filled(maitempi, fill_value=0.)\n\nmaizetor=maitrop+maitemp\nmaizetoi=maitropi+maitempi\nmaizeto = maitrop+maitemp+maitropi+maitempi\n\n\n\nclm=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/clm45historical/soytrop_historical_co2_rf_fert_0.5x0.5.nc','r')\nclmtropf = clm.variables['yield'][99,:,:]\n#clmtropf=N.average(clmtrop,axis=0)\n\nclm1=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/clm45historical/soytemp_historical_co2_rf_fert_0.5x0.5.nc','r')\nclmtempf = clm1.variables['yield'][99,:,:]\n\nclm2=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/clm45historical/soytrop_historical_co2_irrig_fert_0.5x0.5.nc','r')\nclmtropfi = clm2.variables['yield'][99,:,:]\n\nclm3=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/clm/clm45historical/soytemp_historical_co2_irrig_fert_0.5x0.5.nc','r')\nclmtempfi = clm3.variables['yield'][99,:,:]\n\nclmtropf=N.flipud(clmtropf)\nclmtempf=N.flipud(clmtempf)\nclmtropfi=N.flipud(clmtropfi)\nclmtempfi=N.flipud(clmtempfi)\n\nclmtropf= ma.masked_where(maitrop<=0,clmtropf)\nclmtempf= ma.masked_where(maitemp<=0,clmtempf)\nclmtropf=ma.filled(clmtropf, fill_value=0.)\nclmtempf=ma.filled(clmtempf, fill_value=0.)\n\nclmtropfi= ma.masked_where(maitropi<=0,clmtropfi)\nclmtempfi= ma.masked_where(maitempi<=0,clmtempfi)\nclmtropfi=ma.filled(clmtropfi, fill_value=0.)\nclmtempfi=ma.filled(clmtempfi, fill_value=0.)\n\nyield_clmtf=clmtropf+clmtempf\nyield_clmtf = ma.masked_where(yield_clmtf<=0,yield_clmtf)\n#yield_clmtf = ma.masked_where(maizetor<=0,yield_clmtf )\nyield_clmtf=ma.filled(yield_clmtf, fill_value=0.)\n\nyield_clmtfi=clmtropfi+clmtempfi\nyield_clmtfi = ma.masked_where(yield_clmtfi<=0,yield_clmtfi)\n#yield_clmtfi = ma.masked_where(maizetoi<=0,yield_clmtfi)\nyield_clmtfi=ma.filled(yield_clmtfi, fill_value=0.)\n\n\narea=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/gridareahalf.nc','r')\ngridarea = area.variables['cell_area'][:,:]\ngridlon = area.variables['lon'][:]\n\ngridarea,gridlon = shiftgrid(180.5,gridarea,gridlon,start=False)\n\nnclu=NetCDFFile('/scratch2/scratchdirs/tslin2/plot/globalcrop/data/soybean_AreaYieldProduction.nc','r')\nncvar_maize = nclu.variables['soybeanData'][:]\nlatnc = nclu.variables['latitude'][:]\nznc = nclu.variables['level'][:]\nlonnc = nclu.variables['longitude'][:]\ntimenc = nclu.variables['time'][:]\n\n\n\nyieldfi= N.zeros((100, 360, 720))\nyieldf2i= N.zeros((100, 360, 720))\n\nyieldf= N.zeros((100, 360, 720))\nyieldf2= N.zeros((100, 360, 720))\nyears = range(1901, 2001)\nfor i, year in enumerate(years):\n base = NetCDFFile (\"/scratch2/scratchdirs/tslin2/isam/model/global/isam_his/cruhis/output/cruhis.bgp-yearly_crop_{0}.nc\".format(year), mode='r')\n lona1 = base.variables[\"lon\"][:]\n lata1 = base.variables[\"lat\"][:]\n \n yield1 = base.variables[\"yield\"][1,:,:]\n yieldf[i, :, :] = yield1\n\n basei = NetCDFFile (\"/scratch2/scratchdirs/tslin2/isam/model/global/isam_his/cruhis_irr/output/cruhisirr.bgp-yearly_crop_{0}.nc\".format(year), mode='r')\n yield2 = basei.variables[\"yield\"][1,:,:]\n yieldf2[i, :, :] = yield2\n\n base1 = NetCDFFile (\"/scratch2/scratchdirs/tslin2/isam/model/global/isam_his/cesmhis/output/cesmhis.bgp-yearly_crop_{0}.nc\".format(year), mode='r')\n\n yield12 = base1.variables[\"yield\"][1,:,:]\n yieldfi[i, :, :] = yield12\n\n basei1 = NetCDFFile (\"/scratch2/scratchdirs/tslin2/isam/model/global/isam_his/cesmhis_irr/output/cesmhisirr.bgp-yearly_crop_{0}.nc\".format(year), mode='r')\n yield23 = basei1.variables[\"yield\"][1,:,:]\n yieldf2i[i, :, :] = yield23\n\nyielda=N.average(yieldf,axis=0)\nyielda2=N.average(yieldf2,axis=0)\n\nyield_new,lona11 = shiftgrid(180.5,yielda,lona1,start=False)\nyield_new2,lona11 = shiftgrid(180.5,yielda2,lona1,start=False)\n\nyieldai=N.average(yieldfi,axis=0)\nyielda2i=N.average(yieldf2i,axis=0)\n\nyield_newf,lona11 = shiftgrid(180.5,yieldai,lona1,start=False)\nyield_new2f,lona11 = shiftgrid(180.5,yielda2i,lona1,start=False)\n\nlon2,lat2 = N.meshgrid(lona11,lata1)\n\n\n\nfig, ax = plt.subplots(figsize=(12,12))\n\nax.set_title(\"ISAM CESM-NCEP Soybean Yield gridecll (%)\",fontsize=18)\n\nmap = Basemap(projection ='cyl', llcrnrlat=-65, urcrnrlat=90,llcrnrlon=-180, urcrnrlon=180, resolution='c')\nx,y = map(lon2,lat2)\niyield = ma.masked_where(iyield<=0,iyield)\niarea = ma.masked_where(iarea<=0,iarea)\n#iyield = ma.masked_where(iarea<=0,iyield)\niyield = ma.masked_where(maizeto<=0,iyield)\niizumy=iyield*maizeto*100\n\n\nyield_new=maskoceans(x,y,yield_new)\nyield_new=ma.filled(yield_new, fill_value=0.)\nyield_new = ma.masked_where(yield_new<=0,yield_new)\nyield_new = ma.masked_where(maizeto<=0,yield_new)\n\nyield_new2=maskoceans(x,y,yield_new2)\nyield_new2=ma.filled(yield_new2, fill_value=0.)\nyield_new2 = ma.masked_where(yield_new2<=0,yield_new2)\nyield_new2 = ma.masked_where(maizeto<=0,yield_new2)\n\nisamy=((yield_new*maizetor*gridarea)+(yield_new2*maizetoi*gridarea))*100/gridarea\nisamy = ma.masked_where(iizumy<=0,isamy)\n\nyield_newf=maskoceans(x,y,yield_newf)\nyield_newf=ma.filled(yield_newf, fill_value=0.)\nyield_newf = ma.masked_where(yield_newf<=0,yield_newf)\nyield_newf = ma.masked_where(maizeto<=0,yield_newf)\n\nyield_new2f=maskoceans(x,y,yield_new2f)\nyield_new2f=ma.filled(yield_new2f, fill_value=0.)\nyield_new2f = ma.masked_where(yield_new2f<=0,yield_new2f)\nyield_new2f = ma.masked_where(maizeto<=0,yield_new2f)\n\nisamyf=((yield_newf*maizetor*gridarea)+(yield_new2f*maizetoi*gridarea))*100/gridarea\nisamyf = ma.masked_where(iizumy<=0,isamyf)\ncc=isamyf-isamy\ntc, pTc = ttest_ind(yieldf,yieldfi, axis = 0, equal_var = False)\npTc,lona11 = shiftgrid(180.5,pTc,lona1,start=False)\n\n\n\ncc= ma.masked_where( pTc[:,:]>0.1,cc)\n\nmap.drawcoastlines()\nmap.drawcountries()\nmap.drawmapboundary()\ncs = map.pcolormesh(x,y,cc/isamy*100,cmap=plt.cm.bwr,vmin=-100,vmax=100)\ncbar = map.colorbar(cs,location='bottom',size=\"5%\",pad=\"2%\")\ncbar.ax.tick_params(labelsize=15)\nplt.axis('off')\nplt.savefig('soyizisam100.jpg',dpi=300,bbox_inches='tight')\n\nplt.show()\n\n","sub_path":"scripts/plotcrop-master/spatial/soyiiz1diff.py","file_name":"soyiiz1diff.py","file_ext":"py","file_size_in_byte":7234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"41941572","text":"# -*- coding: utf-8 -*-\n# Copyright (C) 2008-2011 Luis Pedro Coelho \n# vim: set ts=4 sts=4 sw=4 expandtab smartindent:\n# Carnegie Mellon University\n# \n# License: MIT (see COPYING file)\n\nfrom __future__ import division\nimport numpy as np\nfrom . import _distance\n\n__all__ = [\n 'gvoronoi',\n ]\n\ndef gvoronoi(labeled):\n '''\n segmented = gvoronoi(labeled)\n\n Generalised Voronoi Transform.\n\n The generalised Voronoi diagram assigns to the pixel (i,j) the label of the\n nearest object (i.e., the value of the nearest non-zero pixel in labeled).\n\n Parameters\n ----------\n labeled : ndarray\n a labeled array, of a form similar to one returned by\n ``mahotas.label()``\n\n Returns\n -------\n segmented : is of the same size and type as labeled and\n `segmented[y,x]` is the label of the object at position `y,x`.\n '''\n labeled = np.ascontiguousarray(labeled)\n bw = (labeled == 0)\n f = np.zeros(bw.shape, np.double)\n f[bw] = len(f.shape)*max(f.shape)**2+1\n orig = np.arange(f.size, dtype=np.intc).reshape(f.shape)\n _distance.dt(f, orig)\n return labeled.flat[orig]\n","sub_path":"mahotas/segmentation.py","file_name":"segmentation.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"578710325","text":"#! /usr/bin/env python\n\"\"\"\n Code to calculate and display pinhole camera characteristics\n Written to support AstroScholars 2020\n started: Anand Sivaramakrishnan Dec 2019\n\"\"\"\nimport os, sys\nimport numpy as np\n\n# All units SI unless otherwise stated.\n\ndef airyscale(dia, wave):\n return wave/dia\n\nmm = 1.0e-3\num = 1.0e-6\ninch = 25.4 * mm\ndeg = np.pi / 180.0\n\nF = 100.00 * mm # Image distance\nD = (10*um, 100*um, 500*um, inch/16, inch/4) # Pinhole diameters\n\n\"\"\"\nSelect one of these three sets by commenting in or out...\n#1:\nband = \"r\" # red laser\nlams = (0.6328*um,)\n#2:\nband = \"g\" # green laser\nlams = (0.532*um,)\n\"\"\"\n#3:\nband = \"RGB\"\nlams = (0.43*um, 0.54*um, 0.575*um) # wavelengths\n\npixel = 3.75434 * um\n\nprint(\"\\nDistance to detector {:.0f} mm, pixel size = {:.2f} um\".format(F/mm, pixel/um))\nresols = []\n\n\"\"\"\n d = 10 um, res = 5.75e-02 rad (3.29 deg) f/10000 f*lambda 5750.0 um = 1531.6 pixels\n Hole dia. Angular resolution Aperture Resolution on detector\n\"\"\"\ncoltitle = \" Hole dia. Angular resolution Aperture Resolution on detector\"\nfor bnd,lam in zip(band,lams):\n print(\"\\nWavelength {:s} = {:.2f} um\".format(bnd, lam/um))\n print(coltitle)\n for d in D:\n print(\" d = {:<4.0f} um \".format(d/um), end=\"\")\n resols.append(airyscale(d, lam))\n print(\" res = {:.2e} rad ({:.2f} deg)\".format(resols[-1], \n resols[-1]/deg), \n end=\"\")\n print(\" f/{:<5.0f} f*lambda {:6.1f} um \".format(F/d, F/d*lam/um), end=\"\")\n print(\"= {:<6.1f} pixels\".format(F*resols[-1]/pixel))\nprint()\n","sub_path":"code/photo_pinhole.py","file_name":"photo_pinhole.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"197052491","text":"import os\n\n\ndef get_file_size(path_to_file):\n size = os.path.getsize(path_to_file)\n return get_human_readable_file_size(size)\n\n\ndef get_human_readable_file_size(size, precision=2):\n suffixes = ['B', 'KB', 'MB', 'GB', 'TB']\n suffixIndex = 0\n while size > 1024:\n suffixIndex += 1 # increment the index of the suffix\n size = size / 1024.0 # apply the division\n return \"%.*f %s\" % (precision, size, suffixes[suffixIndex])\n","sub_path":"FaceRecognition/domain/file_size_provider.py","file_name":"file_size_provider.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"434102984","text":"# -*- coding:utf-8 -*-\nfrom collections import namedtuple\nimport json\nimport os\nimport random\nimport threading\nimport string\nimport copy\nimport ConfigParser\nimport posixpath\nfrom hyaline.common.message import ClusterMessageManager, get_cluster_path\nfrom hyaline.common import zookeeper\nfrom hyaline_state import *\nfrom .state import MySQLCluster, MySQLTask, StateProvider, MysqlStructure\nfrom .password import PasswordBox\nfrom hyaline.common.hyaline_exception import *\nfrom hyaline.scheduler.state import gettime\nimport mesos.interface.mesos_pb2 as mesos_pb2\nfrom hyaline.scheduler.hyaline_scheduler import log\nfrom twitter.common.quantity import Amount, Data, Time\nfrom hyaline.common.common import *\nfrom twitter.common.quantity.parse_simple import InvalidTime, parse_time\nEXECUTOR_NAME = 'hyaline_executor'\n\nEXECUTOR_CPUS_EPSILON = 0.01\nEXECUTOR_MEM_EPSILON = Amount(32, Data.MB)\nEXECUTOR_DISK_EPSILON = Amount(1, Data.MB)\nAGENTDIR = \"mesos-agent-workdir\"\nGROUP_PATH = 'group'\n\n\nclass MySQLClusterLauncher(object):\n \"\"\"\n Responsible for launching and maintaining a MySQL cluster.\n\n Thread-safety:\n The launcher is thread-safe. It uses a separate thread to wait for the election result and\n can launch a new election within that thread. All other public methods are called from the\n scheduler driver thread and the web UI threads.\n \"\"\"\n\n class Error(Exception):\n pass\n\n class IncompatibleRoleError(Error):\n pass\n\n class NonrepeatableHostnameError(Error):\n pass\n\n class PermissionError(Error):\n pass\n\n def __init__(\n self,\n driver,\n cluster,\n state_provider,\n zk_url,\n kazoo,\n framework_user,\n executor_cmd,\n election_timeout,\n scheduler_key,\n cnf,\n uris,\n used_slaves,\n framework_principal,\n recycle_timeout,\n release,\n state,\n mysqlstructures,\n diskcount,\n log_configure,\n refuse_hosts,\n message_dir,\n auto_deploy,\n framework_role='*',\n ):\n \"\"\"\n :param driver: Mesos scheduler driver.\n :param cluster: The MySQLCluster state object.\n :param state_provider: For restoring and persisting the cluster state.\n :param zk_url: The ZooKeeper URL for cluster member discovery and master election.\n :param kazoo: The Kazoo client to access ZooKeeper with.\n :param executor_cmd: 启动执行器指令.\n :param election_timeout: 选举超时.\n :param scheduler_key: Used for encrypting cluster passwords.\n :param framework_role: 框架角色名.\n :param cnf: hyaline.cnf object.\n :param uris: see hyaline_scheduler.py uris\n :param used_slaves:see scheduler.py self.used_slave\n :param framework_principal: 框架向mesos注册的用户名\n :param recycle_timeout: 彻底删除超时,删除的节点在此时间之后会被彻底删除\n :param release: 需要释放的资源列表,见scheduler.py\n :param state: 调度器状态object,见scheduler.py\n :param mysqlstructures,此集群的所有节点的MysqlStructure object 列表\n :param diskcount: see scheduler.py\n :param log_configure: 初始化日志所需参数,见hyaline_scheduler.py\n :param refuse_hosts: see scheduler.py\n \"\"\"\n self._driver = driver\n\n if not isinstance(cluster, MySQLCluster):\n raise TypeError(\"'cluster' should be an instance of MySQLCluster\")\n self._cluster = cluster\n self._stateupdate = Stateupdate(cluster)\n\n if not isinstance(state_provider, StateProvider):\n raise TypeError(\"'state_provider' should be an instance of StateProvider\")\n self._state_provider = state_provider\n\n self._framework_role = framework_role\n\n # Passed along to executors.\n self._zk_url = zk_url\n self._framework_user = framework_user\n self._executor_cmd = executor_cmd\n self._election_timeout = election_timeout\n self._framework_principal = framework_principal\n self._recycle_timeout = recycle_timeout\n self._release = release\n self._state = state\n self.refuse_hosts = refuse_hosts\n self._mysqlstructures = mysqlstructures\n zk_root = zookeeper.parse(zk_url)[2]\n self._cluster_manager = ClusterMessageManager(kazoo, get_cluster_path(zk_root, cluster.name))\n self._cluster_manager.task_ids = set(self._cluster.tasks.keys())\n self._password_box = PasswordBox(scheduler_key)\n self._password_box.decrypt(cluster.encrypted_password) # Validate the password.\n\n #####################################\n # committer: liuyue\n # commit_time:2016-09-01\n # purpose:add replication_password\n #####################################\n ##########################################################################\n self._password_box_repl = PasswordBox(scheduler_key)\n self._password_box_repl.decrypt(cluster.replication_password) # Validate the replication_password.\n ##########################################################################\n\n self._lock = threading.Lock()\n #####################################\n #mahongchao\n #20160911\n ######################################\n self.templist = []\n self.count = 0\n self._cnf = cnf\n self.uris = uris\n self.used_slaves=used_slaves\n self.exclusive = self._cluster.exclusive\n self.diskcount = diskcount\n self._log_configure = log_configure\n self._auto_deploy = auto_deploy\n\n if len(self._cluster.tasks) > 0:\n log.info(\"Recovered %s tasks for cluster '%s'\" % (\n len(self._cluster.tasks), self.cluster_name))\n\n self._terminating = False\n self.static_allocation = self._cnf.get_value('hyaline', 'static_allocation').strip()\n try:\n self.static_allocation_name = self._cnf.get_value('hyaline', 'static_allocation_name').strip()\n except:\n self.static_allocation_name = None\n try:\n self.mycnf = self._cnf.get_dict('mycnf')\n except (ConfigParser.NoOptionError, ConfigParser.NoSectionError) as e:\n self.mycnf = {}\n\n try:\n slave_waitfor_master = self._cnf.get_value('mysql', 'slave_waitfor_master').strip()\n if not slave_waitfor_master:\n slave_waitfor_master = \"30s\"\n except (ConfigParser.NoOptionError, ConfigParser.NoSectionError) as e:\n slave_waitfor_master = \"30s\"\n\n try:\n slave_waitfor_check = self._cnf.get_value('mysql', 'slave_waitfor_check').strip()\n if not slave_waitfor_check:\n slave_waitfor_check = \"30s\"\n except (ConfigParser.NoOptionError, ConfigParser.NoSectionError) as e:\n slave_waitfor_check = \"30s\"\n\n self.slave_waitfor_master = parse_time(slave_waitfor_master).as_(Time.SECONDS)\n self.slave_waitfor_check = parse_time(slave_waitfor_check).as_(Time.SECONDS)\n self.master_waitfor_switch = 30\n try:\n self.same_host_allowable = self._cnf.get_value('hyaline', 'same_host_allowable')\n if not self.same_host_allowable:\n self.same_host_allowable = 'no'\n except ConfigParser.NoOptionError:\n self.same_host_allowable = 'no'\n self.message_dir = message_dir\n self._configure_count = 1\n\n\n @property\n def cluster_name(self):\n return self._cluster.name\n\n @property\n def cluster_info(self):\n with self._lock:\n ClusterInfo = namedtuple('ClusterInfo', [\n 'name', 'user', 'num_nodes', 'state','mode','createtime','mysqlversion',\n 'total_cpus', 'total_mem_mb', 'total_disk_mb',\n 'cpus','mem','disk',\"latest_error\"])\n return ClusterInfo(\n name=self._cluster.name,\n user=self._cluster.user,\n num_nodes=self._cluster.num_nodes,\n state = self._cluster.clusterstate,\n mode = self._cluster.cluster_mode,\n createtime=gettime(self._cluster.create_time),\n mysqlversion=self._cluster.mysql_version,\n total_cpus=self._cluster.all_cpus,\n total_mem_mb=self._cluster.all_mem.as_(Data.MB),\n total_disk_mb=self._cluster.all_disk.as_(Data.GB),\n cpus=self._cluster.cpus,\n mem=self._cluster.mem.as_(Data.MB),\n disk=self._cluster.disk.as_(Data.GB),\n latest_error=self._cluster.latest_error\n )\n\n # 返回mesos Resource object\n def get_resource(self,name, type, value, role='*'):\n resource = mesos_pb2.Resource()\n resource.name = name\n resource.type = type\n resource.role = role\n resource.scalar.value = value\n return resource\n\n def launch(self, offer):\n \"\"\"\n Try to launch a MySQL task with the given offer.\n\n :returns:\n Task ID: Either the task ID of the task just launched or None if this offer is not used.\n Remaining resources: Resources from this offer that are unused by the task. If no task is\n launched, all the resources from the offer are returned.\n path: 任务所使用的磁盘根目录\n hostname: 任务使用的offer的主机名\n\n :raises IncompatibleRoleError: Raised when the offer has some resource with incompatible role.\n \"\"\"\n with self._lock:\n # get our offer by attribute\n # mahongchao\n if self.static_allocation == \"no\":\n havemysql = True\n else:\n havemysql = False\n for attribute in offer.attributes:\n if attribute.text.value == self.static_allocation_name:\n havemysql = True\n if not havemysql:\n raise IncompatibleSlaveError(\"Host %s isn't allowed to run mysql on it.\" %offer.hostname)\n\n offer = remove_static(offer)\n\n cluster = self._cluster\n for task in cluster.tasks.values():\n\n if task.delete_time:\n current_time = time.time()\n if current_time - task.delete_time > self._recycle_timeout:\n self.shiftdelete_node(task.task_id)\n task.delete_time = None\n\n if task.nodestate in [Nodestate.SERVICE_RESTORING,\n Nodestate.PHYSICS_RESTORING,\n Nodestate.CHANGE_HOST_RESTORING,\n Nodestate.SHIFTDELETING,\n Nodestate.STAGING,\n Nodestate.EXPANDING,\n Nodestate.CONTRACTING]:\n need_add = True\n try:\n installing = {u[\"slave_id\"]: u[\"state\"] for u in self.used_slaves}\n if task.mesos_slave_id in installing.keys() and installing[task.mesos_slave_id] == \"installing\":\n need_add = False\n except:\n pass\n if need_add:\n task.count += 1\n else:\n continue\n\n if task.nodestate == Nodestate.SERVICE_RESTORING:\n if task.count > task.max_count:\n self._stateupdate.nodestate_update(task.task_id, Nodestate.SERVICE_RESTORING_FAILED)\n task.count = 0\n self.setaction(self._cluster, 'service restore')\n self.setaction(self._cluster.tasks[task.task_id], 'service restore')\n log.error('Reserved resource of task %s can not be gotten from host %s ' % (task.task_id, str(task.hostname)))\n task.latest_error = 'reserved resource of task %s can not be gotten from host %s ' % (task.task_id, str(task.hostname))\n cluster.latest_error = 'reserved resource of task %s can not be gotten from host %s ' % (task.task_id, str(task.hostname))\n self._state_provider.dump_cluster_state(self._cluster)\n continue\n\n task_id = task.task_id\n if not self.is_my_reserve(offer, task_id):\n continue\n\n launch, _, _, _, _ = self._new_operations(offer, task_id, task.server_id,\n task.cpus, task.mem,\n task.disk, task.port, task.path, task.disk.as_(Data.MB))\n task_info = launch.launch.task_infos[0]\n\n log.info(\"Node %s accepted offer %s on Mesos slave %s (%s)\" % (\n task_id, offer.id.value, offer.slave_id.value, offer.hostname))\n\n task_info.name = task.task_id\n data = json.loads(task_info.data)\n data[\"sandboxdir\"] = task.sandboxdir\n data['action'] = 'service restore'\n task_info.data = json.dumps(data)\n task.nodestate = Nodestate.SERVICE_RESTORE_START\n task.state = mesos_pb2.TASK_STAGING\n task.mesos_slave_id = str(offer.slave_id.value)\n task.count = 0\n self._state_provider.dump_cluster_state(self._cluster)\n self._driver.acceptOffers([offer.id], [launch])\n\n return task_info.task_id.value, None, None, None\n elif task.nodestate == Nodestate.PHYSICS_RESTORING:\n if task.count > task.max_count:\n log.error('Reserved resource of task %s can not be gotten from host %s ' % (task.task_id, str(task.hostname)))\n task.latest_error = 'reserved resource of task %s can not be gotten from host %s ' % (task.task_id, str(task.hostname))\n cluster.latest_error = 'reserved resource of task %s can not be gotten from host %s ' % (task.task_id, str(task.hostname))\n self._stateupdate.nodestate_update(task.task_id, Nodestate.PHYSICS_RESTORING_FAILED)\n task.count = 0\n self._state_provider.dump_cluster_state(self._cluster)\n continue\n task_id = task.task_id\n if not self.is_my_reserve(offer, task_id):\n continue\n\n launch, _, _, create, destroy = self._new_operations(offer, task_id, task.server_id,\n task.cpus, task.mem,\n task.disk, task.port, task.path, task.disk.as_(Data.MB))\n task_info = launch.launch.task_infos[0]\n log.info(\"Node %s accepted offer %s on Mesos slave %s (%s)\" % (\n task_id, offer.id.value, offer.slave_id.value, offer.hostname))\n\n mysqlstructure = self._mysqlstructures[task_id]\n task_info.name = task.task_id\n data = json.loads(task_info.data)\n data['action'] = 'physics restore'\n data[\"configuration\"] = mysqlstructure.initial_configuration\n task_info.data = json.dumps(data)\n log.info('Launching task %s on Mesos slave %s (%s)' % (\n task_info.task_id.value, offer.slave_id.value, offer.hostname))\n task.nodestate = Nodestate.PHYSICS_RESTORE_START\n task.state = mesos_pb2.TASK_STAGING\n task.mesos_slave_id = str(offer.slave_id.value)\n task.count = 0\n self._state_provider.dump_cluster_state(self._cluster)\n self._driver.acceptOffers([offer.id], [launch])\n return task_info.task_id.value, None, None, None\n elif task.nodestate == Nodestate.CHANGE_HOST_RESTORING:\n task_id = task.task_id\n if len(self._cluster.active_tasks) >= self._cluster.num_nodes:\n # All nodes of this cluster have been launched and none have died.\n return None, offer.resources, None, None\n\n if self._terminating:\n return None, offer.resources, None, None\n if task.count > task.max_count:\n log.error('No enough resource to change host restore %s' % task.task_id)\n task.latest_error = 'no enough resource to change host restore %s' % task.task_id\n self._stateupdate.nodestate_update(task.task_id, Nodestate.CHANGE_HOST_RESTORING_FAILED)\n task.count = 0\n if task.task_id in self.refuse_hosts.keys():\n del self.refuse_hosts[task.task_id]\n self._state_provider.dump_cluster_state(self._cluster)\n continue\n\n if self.same_host_allowable.strip() != \"yes\":\n for mysql_task in self._cluster.tasks.values():\n if mysql_task.nodestate == Nodestate.STARTING or mysql_task.nodestate == Nodestate.RUNNING:\n if mysql_task.hostname == offer.hostname:\n raise self.NonrepeatableHostnameError(\"Offered host %s is already one node of %s\" % (\n offer.hostname, self.cluster_name))\n if task_id in self.refuse_hosts.keys():\n if offer.hostname in self.refuse_hosts[task_id]:\n self.refuse_hosts[task_id].remove(offer.hostname)\n if len(self.refuse_hosts[task_id]) == 0:\n del self.refuse_hosts[task_id]\n continue\n\n if offer.hostname == task.hostname:\n continue\n\n if isinstance(task.precursor, dict) and offer.hostname in task.precursor.keys():\n continue\n\n cpus, mem, ports = self._get_resources(offer.resources)\n disk = self.getbigdisk(offer.resources)\n\n if len(ports) == 0:\n break\n\n if task.cpus > cpus or task.mem > mem or task.disk > disk:\n continue\n\n #####################################\n # committer: mahongchao\n # commit_time:2016-08-27\n ####################################\n path, mount_disk = self.getpath(offer, task.disk)\n if not path:\n return None, offer.resources, None, None\n\n task.path = {}\n task.persist_id = 1\n if mount_disk:\n task.path[task.persist_id] = [path, Amount(int(mount_disk), Data.MB), None]\n else:\n task.path[task.persist_id] = [path, task.disk, None]\n task.persist_id += 1\n\n log.info(\"None %s accepted offer %s on Mesos slave %s (%s)\" % (\n task_id, offer.id.value, offer.slave_id.value, offer.hostname))\n task_port = get_port(cluster, ports)\n #####################################\n # committer: mahongchao\n # commit_time:2016-08-26\n ####################################\n ######################################################################\n launch, reserve, _, create, _ = self._new_operations(offer, task.task_id, task.server_id,\n task.cpus, task.mem,\n task.disk, task_port, task.path, task.disk.as_(Data.MB))\n\n mysqlstructure = self._mysqlstructures[task_id]\n\n task_info = launch.launch.task_infos[0]\n data = json.loads(task_info.data)\n data['action'] = 'change host restore'\n data[\"configuration\"] = mysqlstructure.initial_configuration\n task_info.data = json.dumps(data)\n if task.hostname:\n if isinstance(task.precursor, dict):\n task.precursor[task.hostname] = task.port\n else:\n task.precursor = {task.hostname: task.port}\n task.hostname = offer.hostname\n if mount_disk:\n self._cluster.all_disk -= task.disk\n task.disk = Amount(int(mount_disk), Data.MB)\n self._cluster.all_disk += task.disk\n task.ip = offer.url.address.ip\n task.mesos_slave_id = str(offer.slave_id.value)\n task.port = task_port\n\n self._state_provider.dump_cluster_state(self._cluster)\n\n self._driver.acceptOffers([offer.id], [reserve, create, launch])\n task.nodestate = Nodestate.CHANGE_HOST_RESTORE_START\n task.state = mesos_pb2.TASK_STAGING\n task.count = 0\n\n # Hyaline launches at most a single task for each offer. Note that the SchedulerDriver API\n # expects a list of tasks.\n # Reconcile after failover because the scheduler can crash before successfully\n # Update the offer's resources and return them for other clusters to use.\n\n if self.exclusive == 1:\n path = None\n\n return task_info.task_id.value, None, path, task.hostname\n\n elif task.nodestate == Nodestate.EXPANDING:\n if task.count > task.max_count:\n log.error('Fail to expand resources %s for node %s.' % (str(task.reourcechange), task.task_id))\n task.latest_error = 'Fail to expand resources %s for node %s.' % (str(task.reourcechange), task.task_id)\n self._stateupdate.nodestate_update(task.task_id, Nodestate.EXPANDING_FAILED)\n task.count = 0\n self._state_provider.dump_cluster_state(self._cluster)\n continue\n\n if offer.hostname != task.hostname:\n continue\n\n offer = self.get_public_offer(offer)\n cpus, mem, ports = self._get_resources(offer.resources)\n disk = self.getbigdisk(offer.resources)\n expand = task.reourcechange\n if expand[\"cpus\"] and cpus < expand[\"cpus\"]:\n return None, None, None, None\n if expand[\"mem\"] and mem < expand[\"mem\"]:\n return None, None, None, None\n if expand[\"disk\"] and disk < expand[\"disk\"]:\n return None, None, None, None\n path = None\n mount_disk = None\n if expand[\"disk\"]:\n path, mount_disk = self.getpath(offer, expand[\"disk\"])\n if not path:\n return None, offer.resources, None, None\n if mount_disk:\n task.path[task.persist_id] = [path, Amount(int(mount_disk), Data.MB), None]\n task.persist_id += 1\n log.info(\"%s use path %s on mathine %s.\" % (task.task_id, path, offer.hostname))\n task.disk += Amount(int(mount_disk), Data.MB)\n self._cluster.all_disk += Amount(int(mount_disk), Data.MB)\n else:\n task.path[task.persist_id] = [path, expand[\"disk\"], None]\n task.persist_id += 1\n log.info(\"%s use path %s on mathine %s.\" % (task.task_id, path, offer.hostname))\n task.disk += expand[\"disk\"]\n self._cluster.all_disk += expand[\"disk\"]\n if expand[\"cpus\"]:\n task.cpus += expand[\"cpus\"]\n task.cpus = float('%.2f' %task.cpus)\n self._cluster.all_cpus += expand[\"cpus\"]\n self._cluster.all_cpus = float('%.2f' %self._cluster.all_cpus)\n if expand[\"mem\"]:\n task.mem += expand[\"mem\"]\n self._cluster.all_mem += expand[\"mem\"]\n\n log.info(\"Node %s accepted offer %s on Mesos slave %s (%s)\" % (\n task.task_id, offer.id.value, offer.slave_id.value, offer.hostname))\n\n _, reserve, _, create, _ = self._new_operations(offer, task.task_id, task.server_id,\n expand[\"cpus\"], expand[\"mem\"],\n expand[\"disk\"], None,\n task.path, mount_disk)\n task.nodestate = Nodestate.STOPPED\n self._state_provider.dump_cluster_state(self._cluster)\n self._driver.acceptOffers([offer.id], [reserve, create])\n\n\n return task.task_id, None, path, None\n\n elif task.nodestate == Nodestate.CONTRACTING:\n if task.count > task.max_count:\n log.error('Fail to contract resources %s for node %s.' % (str(task.reourcechange), task.task_id))\n task.latest_error = 'Fail to contract resources %s for node %s.' % (str(task.reourcechange), task.task_id)\n self._stateupdate.nodestate_update(task.task_id, Nodestate.CONTRACTING_FAILED)\n task.count = 0\n self._state_provider.dump_cluster_state(self._cluster)\n continue\n\n if offer.hostname != task.hostname:\n continue\n task_id = task.task_id\n if not self.is_my_reserve(offer, task_id):\n continue\n\n contract = task.reourcechange\n unreserve_resources = []\n if contract[\"cpus\"]:\n task.cpus -= contract[\"cpus\"]\n task.cpus = float('%.2f' % task.cpus)\n self._cluster.all_cpus -= contract[\"cpus\"]\n self._cluster.all_cpus = float('%.2f' % self._cluster.all_cpus)\n cpus_resource = get_resource('cpus',\n mesos_pb2.Value.SCALAR,\n contract[\"cpus\"],\n self._framework_role)\n cpus_resource.reservation.principal = self._framework_principal\n unreserve_resources.append(cpus_resource)\n if contract[\"mem\"]:\n task.mem -= contract[\"mem\"]\n self._cluster.all_mem -= contract[\"mem\"]\n mem_resource = get_resource('mem',\n mesos_pb2.Value.SCALAR,\n contract[\"mem\"].as_(Data.MB),\n self._framework_role)\n mem_resource.reservation.principal = self._framework_principal\n unreserve_resources.append(mem_resource)\n\n\n log.info(\"Node %s accepted offer %s on Mesos slave %s (%s)\" % (\n task.task_id, offer.id.value, offer.slave_id.value, offer.hostname))\n\n task.nodestate = Nodestate.STOPPED\n self._state_provider.dump_cluster_state(self._cluster)\n unreserve = get_unreserve(unreserve_resources)\n self._driver.acceptOffers([offer.id], [unreserve])\n\n return task.task_id, None, None, None\n\n\n if cluster.clusterstate in [Clusterstate.STARTINGNODE,\n Clusterstate.STARTING]:\n for task in cluster.tasks.values():\n if task.nodestate == Nodestate.STAGING:\n if task.count > task.max_count:\n if not task.hostname:\n log.error('Node %s has never been initialized.' % (task.task_id))\n task.latest_error = 'node %s has never been initialized.' % (task.task_id)\n else:\n log.error('Node %s can not get resource from host %s to restart ' % ( task.task_id, str(task.hostname)))\n task.latest_error = 'node %s can not get resource from host %s to restart ' % ( task.task_id, str(task.hostname))\n self._stateupdate.nodestate_update(task.task_id, Nodestate.STARTING_FAILED)\n if self._cluster.clusterstate == Clusterstate.STARTING_FAILED:\n self._cluster.latest_error = 'start' + task.task_id + 'error: ' + task.latest_error\n self.start_failed_kill()\n task.count = 0\n self._state_provider.dump_cluster_state(self._cluster)\n continue\n\n task_id = task.task_id\n mysqlstructure = self._mysqlstructures[task_id]\n if not self.is_my_reserve(offer,task_id):\n continue\n\n launch, _, _, _, _ = self._new_operations(offer, task_id, task.server_id,\n task.cpus, task.mem,\n task.disk, task.port, task.path, task.disk.as_(Data.MB))\n task_info = launch.launch.task_infos[0]\n\n log.info(\"Restart node %s accepted offer %s on Mesos slave %s \" % (\n task_id, offer.id.value, offer.hostname))\n task_info.name = task.task_id\n data = json.loads(task_info.data)\n data[\"sandboxdir\"] = task.sandboxdir\n data['action'] = 'start'\n\n if mysqlstructure.initial:\n data[\"mysql\"] = \"initial\"\n elif mysqlstructure.change:\n data[\"configuration\"] = mysqlstructure.configuration\n task_info.data = json.dumps(data)\n task.nodestate = Nodestate.STARTING\n task.state = mesos_pb2.TASK_STAGING\n task.mesos_slave_id = str(offer.slave_id.value)\n task.count = 0\n self._state_provider.dump_cluster_state(self._cluster)\n self._driver.acceptOffers([offer.id], [launch])\n\n return task_info.task_id.value, None, None, None\n\n elif cluster.clusterstate == Clusterstate.INITIALIZING:\n if len(self._cluster.active_tasks) >= self._cluster.num_nodes:\n # All nodes of this cluster have been launched and none have died.\n return None, offer.resources, None, None\n\n if self._terminating:\n return None, offer.resources, None, None\n if self.same_host_allowable.strip() != \"yes\":\n for mysql_task in self._cluster.tasks.values():\n if mysql_task.nodestate == Nodestate.STARTING or mysql_task.nodestate == Nodestate.RUNNING:\n if mysql_task.hostname == offer.hostname:\n raise self.NonrepeatableHostnameError(\"Offered host %s is already one node of %s\" % (\n offer.hostname, self.cluster_name))\n offer = self.get_public_offer(offer)\n cpus, mem, ports = self._get_resources(offer.resources)\n disk = self.getbigdisk(offer.resources)\n\n if len(ports) == 0:\n return None, offer.resources, None, None\n\n task_id = None\n mysql_task = None\n for mysqlTask_id, mysqlTask in self._cluster.tasks.items():\n if mysqlTask.nodestate == Nodestate.STAGING:\n if mysqlTask_id in self.refuse_hosts.keys():\n if offer.hostname in self.refuse_hosts[mysqlTask_id]:\n self.refuse_hosts[mysqlTask_id].remove(offer.hostname)\n if len(self.refuse_hosts[mysqlTask_id]) == 0:\n del self.refuse_hosts[mysqlTask_id]\n continue\n if mysqlTask.cpus <= cpus and mysqlTask.mem <= mem and mysqlTask.disk <= disk:\n task_id = mysqlTask_id\n mysql_task = mysqlTask\n break\n if task_id is None:\n return None, offer.resources, None, None\n #####################################\n # committer: mahongchao\n # commit_time:2016-08-27\n ####################################\n path, mount_disk = self.getpath(offer, mysql_task.disk)\n if not path:\n return None, offer.resources, None, None\n if mount_disk:\n mysql_task.path[mysql_task.persist_id] = [path, Amount(int(mount_disk), Data.MB), None]\n else:\n mysql_task.path[mysql_task.persist_id] = [path, mysql_task.disk, None]\n mysql_task.persist_id += 1\n\n log.info(\"Node %s accepted offer %s on Mesos slave %s (%s)\" % (\n task_id, offer.id.value, offer.slave_id.value, offer.hostname))\n log.info(\"%s use path %s on mathine %s.\" %(task_id, path, offer.hostname))\n\n if self._cluster.cluster_mode == \"GR\":\n task_port = get_ports(cluster, ports)\n else:\n task_port = get_port(cluster, ports)\n\n launch, reserve, _, create, _ = self._new_operations(offer, task_id, mysql_task.server_id,\n mysql_task.cpus, mysql_task.mem,\n mysql_task.disk, task_port,\n mysql_task.path, mount_disk)\n task_info = launch.launch.task_infos[0]\n\n mysqlstructure = self._mysqlstructures[task_id]\n data = json.loads(task_info.data)\n data['action'] = 'initial'\n data[\"configuration\"] = mysqlstructure.initial_configuration\n task_info.data = json.dumps(data)\n\n mysql_task.hostname = offer.hostname\n if mount_disk:\n self._cluster.all_disk -= mysql_task.disk\n mysql_task.disk = Amount(int(mount_disk), Data.MB)\n self._cluster.all_disk += mysql_task.disk\n mysql_task.ip = offer.url.address.ip\n mysql_task.mesos_slave_id = str(offer.slave_id.value)\n mysql_task.port = task_port\n mysql_task.count = 0\n mysql_task.nodestate = Nodestate.STARTING\n\n if len(self._cluster.active_tasks) == self._cluster.num_nodes:\n self._cluster.clusterstate = Clusterstate.LAUNCHING\n\n self._state_provider.dump_cluster_state(self._cluster)\n\n # Hyaline launches at most a single task for each offer. Note that the SchedulerDriver API\n # expects a list of tasks.\n # Reconcile after failover because the scheduler can crash before successfully\n # launching the task. Also run implicit reconciliation periodically.\n self._driver.acceptOffers([offer.id], [reserve, create, launch])\n\n # Update the offer's resources and return them for other clusters to use.\n\n if self.exclusive == 1:\n path = None\n\n return task_info.task_id.value, None, path, mysql_task.hostname\n #######################################################################\n # committer: liunannan\n # commit_time:2016-09-10\n # purpose:add node\n #######################################################################\n elif cluster.clusterstate == Clusterstate.ADDINGNODE:\n if len(self._cluster.active_tasks) >= self._cluster.num_nodes:\n return None, offer.resources, None, None\n\n if self._terminating:\n return None, offer.resources, None, None\n\n for mysqlTask in self._cluster.tasks.values():\n if mysqlTask.nodestate == Nodestate.STAGING and mysqlTask.count > mysqlTask.max_count:\n log.error('No enough resource to add node %s for cluster %s' % (mysqlTask.task_id, cluster.name))\n mysqlTask.latest_error = 'no enough resource to add node %s for cluster %s' % (mysqlTask.task_id, cluster.name)\n self._stateupdate.nodestate_update(mysqlTask.task_id,Nodestate.STARTING_FAILED)\n mysqlTask.count = 0\n if task.task_id in self.refuse_hosts.keys():\n del self.refuse_hosts[task.task_id]\n self._state_provider.dump_cluster_state(self._cluster)\n\n if self.same_host_allowable.strip() != \"yes\":\n for mysql_task in self._cluster.tasks.values():\n if mysql_task.hostname == offer.hostname:\n raise self.NonrepeatableHostnameError(\"Offered host %s is already one node of %s\" % (\n offer.hostname, self.cluster_name))\n\n cpus, mem, ports = self._get_resources(offer.resources)\n disk = self.getbigdisk(offer.resources)\n\n if len(ports) == 0:\n return None, offer.resources, None, None\n\n task_id = None\n mysql_task = None\n for mysqlTask_id, mysqlTask in self._cluster.tasks.items():\n if mysqlTask.nodestate == Nodestate.STAGING:\n if mysqlTask_id in self.refuse_hosts.keys():\n if offer.hostname in self.refuse_hosts[mysqlTask_id]:\n self.refuse_hosts[mysqlTask_id].remove(offer.hostname)\n if len(self.refuse_hosts[mysqlTask_id]) == 0:\n del self.refuse_hosts[mysqlTask_id]\n continue\n if mysqlTask.cpus <= cpus and mysqlTask.mem <= mem and mysqlTask.disk <= disk:\n task_id = mysqlTask_id\n mysql_task = mysqlTask\n break\n\n if task_id is None:\n return None, offer.resources, None, None\n\n #####################################\n # committer: mahongchao\n # commit_time:2016-08-27\n ####################################\n path, mount_disk = self.getpath(offer, mysql_task.disk)\n if not path:\n return None, offer.resources, None, None\n\n if mount_disk:\n mysql_task.path[mysql_task.persist_id] = [path, Amount(int(mount_disk), Data.MB), None]\n else:\n mysql_task.path[mysql_task.persist_id] = [path, mysql_task.disk, None]\n\n mysql_task.path[mysql_task.persist_id] = [path,mysql_task.disk,None]\n mysql_task.persist_id += 1\n log.info(\"Node %s accepted offer %s on Mesos slave %s (%s)\" % (\n task_id, offer.id.value, offer.slave_id.value, offer.hostname))\n task_port = get_port(cluster, ports)\n #####################################\n # committer: mahongchao\n # commit_time:2016-08-26\n ####################################\n ######################################################################\n launch, reserve, _, create, _ = self._new_operations(offer, task_id, mysql_task.server_id,\n mysql_task.cpus, mysql_task.mem,\n mysql_task.disk, task_port, mysql_task.path,mount_disk)\n task_info = launch.launch.task_infos[0]\n\n mysqlstructure = self._mysqlstructures[task_id]\n data = json.loads(task_info.data)\n data['action'] = 'add node'\n data[\"configuration\"] = mysqlstructure.initial_configuration\n task_info.data = json.dumps(data)\n\n mysql_task.hostname = offer.hostname\n if mount_disk:\n self._cluster.all_disk -= mysql_task.disk\n mysql_task.disk = Amount(int(mount_disk), Data.MB)\n self._cluster.all_disk += mysql_task.disk\n mysql_task.ip = offer.url.address.ip\n mysql_task.mesos_slave_id = str(offer.slave_id.value)\n mysql_task.port = task_port\n mysql_task.nodestate = Nodestate.STARTING\n\n self._driver.acceptOffers([offer.id], [reserve, create, launch])\n mysql_task.count = 0\n self._state_provider.dump_cluster_state(self._cluster)\n\n # Hyaline launches at most a single task for each offer. Note that the SchedulerDriver API\n # expects a list of tasks.\n # Reconcile after failover because the scheduler can crash before successfully\n # Update the offer's resources and return them for other clusters to use.\n\n if self.exclusive == 1:\n path = None\n\n return task_info.task_id.value, None, path, mysql_task.hostname\n\n elif len(cluster.mini_tasks) > 0:\n for mini_task in cluster.mini_tasks:\n if mini_task['state'] == 'wait' and offer.hostname == self._cluster.tasks[mini_task['task_id']].hostname:\n for resource in offer.resources:\n if resource.name == 'disk' and resource.role == '*':\n resource = self.get_resource('disk', mesos_pb2.Value.SCALAR, EXECUTOR_DISK_EPSILON.as_(Data.MB))\n task_id = 'mini-' + mini_task['task_id']\n task_info = self._new_task(offer,task_id,[resource],mini_task['action'])\n self._driver.launchTasks(offer.id, [task_info])\n mini_task['state'] = 'start'\n self._state_provider.dump_cluster_state(cluster)\n return task_info.task_id.value, None, None, None\n\n return None, offer.resources, None, None\n\n # 从offer里去掉已经预留的资源\n def get_public_offer(self, offer):\n delete_resource = []\n for resource in offer.resources:\n if str(resource.reservation):\n delete_resource.append(resource)\n for resource in delete_resource:\n offer.resources.remove(resource)\n return offer\n\n #集群初始化失败会调用此方法,若节点已经启动,则向mesos发出killtask指令,否则直接将节点状态改为STAGING_FAILED\n def init_kill(self):\n \"\"\"\n Kill the cluster when the cluster failed to initialize.\n\n NOTE: Cluster killing is asynchronous. Use 'terminated' property to check if all tasks in the\n cluster are killed.\n \"\"\"\n # TODO(mhc): Task killing is unreliable. Reconciliation should retry killing.\n if self._cluster.first_port:\n self._cluster.first_port = None\n for task in self._cluster.tasks.values():\n task.path = {}\n task.persist_id = 1\n if task.task_id in self.refuse_hosts.keys():\n del self.refuse_hosts[task.task_id]\n for used_slave in self.used_slaves:\n if used_slave[\"task_id\"] == task.task_id and used_slave[\"state\"] == \"installing\":\n self.used_slaves.remove(used_slave)\n log.info(\"Remove %s from used_slaves because roll back.\" % str(used_slave))\n self._state_provider.dump_scheduler_state(self._state)\n break\n task.count = 0\n if task in self._cluster.active_tasks:\n log.info(\"Killing node %s of cluster %s because cluster is in initial_failed state.\" % (task.task_id, self.cluster_name))\n self._driver.killTask(mesos_pb2.TaskID(value=task.task_id))\n task.state = mesos_pb2.TASK_KILLING\n else:\n self._stateupdate.nodestate_update(task.task_id, Nodestate.STAGING_FAILED)\n\n # 对于启动失败的集群,要将已经成功启动的节点停止\n def start_failed_kill(self):\n for task in self._cluster.tasks.values():\n for used_slave in self.used_slaves:\n if used_slave[\"task_id\"] == task.task_id and used_slave[\"state\"] == \"installing\":\n self.used_slaves.remove(used_slave)\n log.info(\"Remove %s from used_slaves because roll back.\" % str(used_slave))\n self._state_provider.dump_scheduler_state(self._state)\n break\n task.count = 0\n if task in self._cluster.active_tasks:\n log.info(\"Stoping node %s of cluster %s because cluster is in starting_failed state.\" % (task.task_id, self.cluster_name))\n self._driver.killTask(mesos_pb2.TaskID(value=task.task_id))\n task.state = mesos_pb2.TASK_KILLING\n elif task.nodestate == Nodestate.STARTING_FAILED:\n continue\n elif task.hostname:\n self._stateupdate.nodestate_update(task.task_id, Nodestate.STOPPED)\n else:\n log.error('Node %s has never been initialized.' % (task.task_id))\n task.latest_error = 'node %s has never been initialized.' % (task.task_id)\n task.nodestate = Nodestate.STARTING_FAILED\n\n # 杀死节点\n def kill_node(self,taskid):\n self._driver.killTask(mesos_pb2.TaskID(value=taskid))\n return\n\n #杀死集群的所有节点\n def kill_cluster(self):\n for task_id in self._cluster.tasks.keys():\n self._driver.killTask(mesos_pb2.TaskID(value=task_id))\n log.info(\"Killing task %s of cluster %s\" % (task_id, self.cluster_name))\n\n return\n\n #######################################################################\n # committer: liunannan\n # commit_time:2016-09-10\n # purpose:add node\n #######################################################################\n def add_node(self, resources):\n \"\"\"Add a node to the db cluster.\"\"\"\n with self._lock:\n if self._cluster.clusterstate != Clusterstate.RUNNING:\n clusterstate = self._cluster.clusterstate\n log.error(\"This cluster %s is not allowed to add node ,\"\n \"because it is in %s state \" % (self._cluster.name, clusterstate))\n self._cluster.latest_error = \"This cluster is %s not allowed to addnode\" % clusterstate\n self._state_provider.dump_cluster_state(self._cluster)\n raise ClusterstateError(\"This cluster %s is not allowed to add node,\"\n \"because it is in %s state \" % (self._cluster.name, clusterstate))\n else:\n self._cluster.clusterstate = Clusterstate.ADDINGNODE\n server_id = self._cluster.next_id\n task_id = \"hyaline-\" + self.cluster_name + \"-\" + str(server_id)\n log.info(\"Add node %s for cluster %s with resources %s\" %(task_id, self._cluster.name, str(resources)))\n self._cluster.tasks[task_id] = MySQLTask(\n self.cluster_name,\n task_id,\n server_id,\n cpus=resources['cpus'],\n mem=resources['mem'],\n disk=resources['disk'],\n mesos_slave_id=None,\n hostname=None,\n port=None)\n self._cluster.all_cpus += resources['cpus']\n self._cluster.all_mem += resources['mem']\n self._cluster.all_disk += resources['disk']\n self._cluster.next_id += 1\n self._cluster.num_nodes += 1\n self.setaction(self._cluster, 'addnode')\n self._state_provider.dump_cluster_state(self._cluster)\n self._mysqlstructures[task_id] = MysqlStructure(self.cluster_name, task_id)\n self._state_provider.dump_mysql_state(self._mysqlstructures[task_id])\n self._cluster_manager.task_ids.add(task_id)\n return task_id\n\n #######################################################################\n # committer: liunannan\n # commit_time:2016-09-14\n # purpose:start cluster\n #######################################################################\n def start_cluster(self):\n \"\"\"Start the db cluster we have stopped.\"\"\"\n with self._lock:\n cluster_name=self._cluster.name\n if self._cluster.clusterstate not in [Clusterstate.STOPPED, Clusterstate.STARTING_FAILED]:\n clusterstate = self._cluster.clusterstate\n log.error(\"This cluster %s is not allowed to start ,\"\n \"because it is in %s state \" % (self._cluster.name, clusterstate))\n self._cluster.latest_error = \"This cluster is %s not allowed to start\" % clusterstate\n self._state_provider.dump_cluster_state(self._cluster)\n raise ClusterstateError(\"This cluster %s is not allowed to start ,\"\n \"because it is in %s state \" % (cluster_name, clusterstate))\n self._cluster.clusterstate = Clusterstate.STARTING\n log.info(\"Cluster %s is starting.\" % self._cluster.name)\n self._cluster.latest_restart_time = time.time()\n for mysqlTask_id, mysqlTask in self._cluster.tasks.items():\n if mysqlTask.nodestate in [Nodestate.STOPPED,\n Nodestate.STARTING_FAILED]:\n self.start_node( mysqlTask_id)\n\n def re_initialize(self):\n \"\"\"Reinitialize the db cluster we have initialize faild.\"\"\"\n with self._lock:\n cluster_name=self._cluster.name\n if self._cluster.clusterstate not in [Clusterstate.INITIALIZING_FAILED]:\n clusterstate = self._cluster.clusterstate\n log.error(\"This cluster %s is not allowed to reinitialize ,\"\n \"because it is in %s state \" % (self._cluster.name, clusterstate))\n self._cluster.latest_error = \"This cluster is %s not allowed to reinitialize\" % clusterstate\n self._state_provider.dump_cluster_state(self._cluster)\n raise ClusterstateError(\"This cluster %s is not allowed to reinitialize ,\"\n \"because it is in %s state \" % (cluster_name, clusterstate))\n task_ids=[]\n self.setaction(self._cluster, 'reinitialize')\n self._cluster.clusterstate = Clusterstate.INITIALIZING\n log.info(\"Cluster %s is reinitializing.\" % self._cluster.name)\n for mysqlTask_id, mysqlTask in self._cluster.tasks.items():\n mysqlTask.nodestate = Nodestate.STAGING\n mysqlTask.state = mesos_pb2.TASK_STAGING\n self.setaction(mysqlTask, 'reinitialize')\n task_ids.append(mysqlTask_id)\n return task_ids\n\n def recover_cluster(self):\n \"\"\"Recover the db cluster we have deleted.\"\"\"\n with self._lock:\n cluster_name = self._cluster.name\n if self._cluster.clusterstate != Clusterstate.DELETED:\n clusterstate = self._cluster.clusterstate\n log.error(\"This cluster %s is not allowed to recover ,\"\n \"because it is in %s state \" % (self._cluster.name, clusterstate))\n self._cluster.latest_error = \"This cluster is %s not allowed to recover\" % clusterstate\n self._state_provider.dump_cluster_state(self._cluster)\n raise ClusterstateError(\"This cluster %s is not allowed to recover,\"\n \"because it is in %s state \" % (cluster_name, clusterstate))\n self._cluster.clusterstate = Clusterstate.STARTING\n log.info(\"Cluster %s is recoving.\" %cluster_name)\n self._cluster.latest_restart_time = time.time()\n for mysqlTask_id, mysqlTask in self._cluster.tasks.items():\n self.start_node(mysqlTask_id)\n\n def change_host_start(self, taskid):\n \"\"\"Change host start the db cluster.\"\"\"\n task = self._cluster.tasks[taskid]\n if self._cluster.tasks[taskid].nodestate not in [Nodestate.PHYSICS_RESTORING_FAILED,\n Nodestate.CHANGE_HOST_RESTORING_FAILED]:\n nodestate = self._cluster.tasks[taskid].nodestate\n log.error(\"This node %s is not allowed to change host start ,\"\n \"because it is in %s state \" % (taskid, nodestate))\n task.latest_error = \"This node is %s not allowed to change host start\" % nodestate\n self._state_provider.dump_cluster_state(self._cluster)\n raise NodestateError(\"This node %s is not allowed to change host start,\"\n \"because it is in %s state \" % (taskid, nodestate))\n self.setaction(self._cluster, 'change host restore')\n self._stateupdate.nodestate_update(taskid, Nodestate.CHANGE_HOST_RESTORING)\n self.setaction(task, 'change host restore')\n log.info(\"Node %s is change host restoring.\" %task.task_id)\n self._state_provider.dump_cluster_state(self._cluster)\n #######################################################################\n # committer: liunannan\n # commit_time:2016-09-19\n # purpose:stop cluster\n #######################################################################\n def stop_cluster(self):\n \"\"\"Stop the db cluster which is running.\"\"\"\n if self._cluster.clusterstate != Clusterstate.RUNNING:\n clusterstate = self._cluster.clusterstate\n log.error(\"This cluster %s is not allowed to stop ,\"\n \"because it is in %s state \" % (self._cluster.name, clusterstate))\n self._cluster.latest_error = \"This cluster is %s not allowed to stop\" % clusterstate\n self._state_provider.dump_cluster_state(self._cluster)\n raise ClusterstateError(\"This cluster %s is not allowed to stop ,\"\n \"because it is in %s state \" % (self._cluster.name, clusterstate))\n else:\n self._cluster.clusterstate = Clusterstate.STOPPING\n log.info(\"Cluster %s is stopping.\" %self._cluster.name)\n self._cluster.latest_stop_time = time.time()\n for task_id, task in self._cluster.tasks.items():\n if task.nodestate not in [Nodestate.DELETING,\n Nodestate.DELETED,\n Nodestate.DELETING_FAILED]:\n self.stop_node(task_id)\n\n\n def shiftdelete_cluster(self):\n \"\"\"Shift delete the db cluster we have deleted.\"\"\"\n with self._lock:\n if self._cluster.clusterstate != Clusterstate.DELETED:\n clusterstate = self._cluster.clusterstate\n log.error(\"This cluster %s is not allowed to shift delete ,\"\n \"because it is in %s state \" % (self._cluster.name, clusterstate))\n self._cluster.latest_error = \"This cluster is %s not allowed to shift delete\" % clusterstate\n self._state_provider.dump_cluster_state(self._cluster)\n raise ClusterstateError(\"This cluster %s is not allowed to shift delete ,\"\n \"because it is in %s state \" %(self._cluster.name, clusterstate))\n else:\n try:\n log.info(\"Shift delete cluster %s.\" %self._cluster.name)\n self._cluster.clusterstate = Clusterstate.SHIFTDELETE\n for mysqlTask_id, mysqlTask in self._cluster.tasks.items():\n self.shiftdelete_node(mysqlTask_id)\n except NodestateError:\n raise ClusterstateError(\"This cluster %s is not allowed to shift delete ,\"\n \"because it has been shiftdeleted\")\n\n def stop_node(self,taskid):\n \"\"\"Stop the db node which is running.\"\"\"\n with self._lock:\n cluster_name=self._cluster.name\n if self._cluster.tasks[taskid].nodestate not in [Nodestate.RUNNING,Nodestate.STOPPING_FAILED]:\n nodestate = self._cluster.tasks[taskid].nodestate\n log.error(\"This node %s is not allowed to stop ,\"\n \"because it is in %s state \" % (taskid, nodestate))\n task = self._cluster.tasks[taskid]\n task.latest_error = \"This node is %s not allowed to stop\" % nodestate\n self._state_provider.dump_cluster_state(self._cluster)\n raise NodestateError(\"This node %s is not allowed to stop ,\"\n \"because it is in %s state \" % (taskid, nodestate))\n if self._cluster.clusterstate != Clusterstate.STOPPING:\n self._cluster.clusterstate = Clusterstate.STOPPINGNODE\n mysqltask = self._cluster.tasks[taskid]\n self._stateupdate.nodestate_update(taskid, Nodestate.STOPPING)\n mysqltask.state = mesos_pb2.TASK_KILLING\n mysqltask.latest_stop_time = time.time()\n self.setaction(self._cluster.tasks[taskid], 'stop')\n log.info(\"Node %s is stopping.\" %taskid)\n if self._cluster.clusterstate==Clusterstate.STOPPING:\n self.setaction(self._cluster, 'stop')\n if self._cluster.clusterstate==Clusterstate.STOPPINGNODE:\n self.setaction(self._cluster, 'stopnode')\n self._cluster.tasks[taskid].count = 0\n self._state_provider.dump_cluster_state(self._cluster)\n self.kill_node(taskid)\n\n # 改变节点的资源,action为expand时 增加资源 , action为contract时为\n def changeresource(self, taskid, resources, action):\n with self._lock:\n task = self._cluster.tasks[taskid]\n cluster_name = self._cluster.name\n if action == \"expand\":\n if task.nodestate not in [Nodestate.STOPPED, Nodestate.EXPANDING_FAILED]:\n log.error(\"This node %s is not allowed to expand ,\"\n \"because it is in %s state \" % (taskid, task.nodestate))\n task.latest_error = \"This node is %s not allowed to expand.\" % task.nodestate\n self._state_provider.dump_cluster_state(self._cluster)\n raise NodestateError(\"This node %s is not allowed to expand ,\"\n \"because it is in %s state \" % (taskid, task.nodestate))\n self._stateupdate.nodestate_update(taskid, Nodestate.EXPANDING)\n log.info(\"Expand node %s with resources %s.\" % (taskid, str(resources)))\n self.setaction(task, 'expand')\n elif action == \"contract\":\n if task.nodestate not in [Nodestate.STOPPED, Nodestate.CONTRACTING_FAILED]:\n log.error(\"This node %s is not allowed to contract ,\"\n \"because it is in %s state \" % (taskid, task.nodestate))\n task.latest_error = \"This node is %s not allowed to contract.\" % task.nodestate\n self._state_provider.dump_cluster_state(self._cluster)\n raise NodestateError(\"This node %s is not allowed to contract ,\"\n \"because it is in %s state \" % (taskid, task.nodestate))\n elif resources[\"cpus\"] and resources[\"cpus\"] >= task.cpus:\n raise OutOfRangeError(\"contract resources out of range.\")\n elif resources[\"mem\"] and resources[\"mem\"] >= task.mem:\n raise OutOfRangeError(\"contract resources out of range.\")\n self._stateupdate.nodestate_update(taskid, Nodestate.CONTRACTING)\n log.info(\"Contract node %s with resources %s.\" % (taskid, str(resources)))\n self.setaction(task, 'contract')\n else:\n pass\n task.reourcechange = resources\n task.count = 0\n self._state_provider.dump_cluster_state(self._cluster)\n\n # 把集群的状态更改为cluster_state\n def change_cluster_state(self,cluster_state):\n \"\"\"Change the db cluster state.\"\"\"\n if cluster_state in Clusterstate:\n self._cluster.clusterstate = cluster_state\n else:\n raise Unknowstate\n self._state_provider.dump_cluster_state(self._cluster)\n\n # 将节点taskid的状态更改为node_state\n def change_node_state(self,taskid,node_state):\n \"\"\"Change the db node state.\"\"\"\n if node_state in Nodestate:\n task = self._cluster.tasks[taskid]\n self._stateupdate.nodestate_update(taskid, node_state)\n task.count = 0\n else:\n raise Unknowstate\n self._state_provider.dump_cluster_state(self._cluster)\n\n def complete_data_restore(self,taskid):\n if self._cluster.tasks[taskid].nodestate != Nodestate.DATA_RESTORING:\n task = self._cluster.tasks[taskid]\n nodestate =task.nodestate\n log.error(\"This node %s is in %s state, not DATA_RESTORING\" % (taskid, nodestate))\n\n task.latest_error = \"This node %s is in %s state, not DATA_RESTORING\" % (taskid, nodestate)\n self._state_provider.dump_cluster_state(self._cluster)\n raise NodestateError(\"This node %s is in %s state, not DATA_RESTORING\" % (taskid, nodestate))\n\n # 物理修复, 异机修复, 增加节点之后,数据修复完成之后调用此方法\n def complete_restore(self,taskid):\n task = self._cluster.tasks[taskid]\n if task.nodestate != Nodestate.DATA_RESTORING:\n nodestate =task.nodestate\n log.error(\"This node %s is in %s state, not DATA_RESTORING\" % (taskid, nodestate))\n\n task.latest_error = \"This node %s is in %s state, not DATA_RESTORING\" % (taskid, nodestate)\n self._state_provider.dump_cluster_state(self._cluster)\n raise NodestateError(\"This node %s is in %s state, not DATA_RESTORING\" % (taskid, nodestate))\n else:\n message_data = get_message_data(set([taskid]),\"delete\",sandboxdir=task.sandboxdir)\n log.info(\"Send message %s to node %s.\" %(str(message_data), taskid))\n self._cluster_manager.send_message(message_data)\n\n # 对节点进行服务修复,即 尝试重新启动mysql\n def service_restore(self,taskid):\n if self._cluster.tasks[taskid].nodestate not in [Nodestate.SERVICE_RESTORING_FAILED]:\n task = self._cluster.tasks[taskid]\n nodestate =task.nodestate\n log.error(\"This node %s is in %s state, expect SERVICE_RESTORING_FAILED \" % (taskid, nodestate))\n task.latest_error = \"This node %s is in %s state, expect SERVICE_RESTORING_FAILED\" % (taskid, nodestate)\n self._state_provider.dump_cluster_state(self._cluster)\n raise NodestateError(\"This node %s is in %s state, expect SERVICE_RESTORING_FAILED\" % (taskid, nodestate))\n self._stateupdate.nodestate_update(taskid, Nodestate.SERVICE_RESTORING)\n self.setaction(self._cluster, 'service restore')\n self.setaction(self._cluster.tasks[taskid], 'service restore')\n log.info(\"Node %s is service restoring.\" %taskid)\n self._state_provider.dump_cluster_state(self._cluster)\n\n #对节点进行物理修复,即 尝试重新初始化mysql\n def physics_restore(self,taskid):\n if self._cluster.tasks[taskid].nodestate not in [Nodestate.SERVICE_RESTORING_FAILED,\n Nodestate.PHYSICS_RESTORING_FAILED,\n Nodestate.STARTING_FAILED,\n Nodestate.STOPPED]:\n task = self._cluster.tasks[taskid]\n nodestate =task.nodestate\n log.error(\"This node %s is in %s state, expect SERVICE_RESTORING_FAILED or \"\n \"PHYSICS_RESTORING_FAILED\" % (taskid, nodestate))\n\n task.latest_error = \"This node %s is in %s state, expect SERVICE_RESTORING_FAILED or \" \\\n \"PHYSICS_RESTORING_FAILED\" % (taskid, nodestate)\n self._state_provider.dump_cluster_state(self._cluster)\n raise NodestateError(\"This node %s is in %s state, expect SERVICE_RESTORING_FAILED or \"\n \"PHYSICS_RESTORING_FAILED\" % (taskid, nodestate))\n self._stateupdate.nodestate_update(taskid, Nodestate.PHYSICS_RESTORING)\n self.setaction(self._cluster, 'physics restore')\n self.setaction(self._cluster.tasks[taskid], 'physics restore')\n log.info(\"Node %s is physics restoring.\" % taskid)\n self._state_provider.dump_cluster_state(self._cluster)\n\n #######################################################################\n # committer: liunannan\n # commit_time:2016-09-19\n # purpose:delete node\n #######################################################################\n def delete_node(self,taskid):\n \"\"\"Delete the db node we have stopped.\"\"\"\n task = self._cluster.tasks[taskid]\n if task.nodestate not in [Nodestate.STAGING_FAILED,\n Nodestate.STARTING_FAILED,\n Nodestate.CHANGE_HOST_RESTORING_FAILED,\n Nodestate.DELETING_FAILED,\n Nodestate.SERVICE_RESTORING_FAILED,\n Nodestate.PHYSICS_RESTORING_FAILED,\n Nodestate.STOPPED]:\n nodestate = self._cluster.tasks[taskid].nodestate\n log.error(\"This node %s is not allowed to delete ,\"\n \"because it is in %s state \" % (taskid, nodestate))\n task = self._cluster.tasks[taskid]\n task.latest_error = \"This node is %s not allowed to delete\" % nodestate\n self._state_provider.dump_cluster_state(self._cluster)\n raise NodestateError(\"This node not allowed to be deleted ,because this node is %s\" %nodestate)\n else:\n log.info(\"Deleting node %s of cluster %s.\" % (taskid, self._cluster.name))\n self._cluster.clusterstate = Clusterstate.DELETINGNODE\n self._stateupdate.nodestate_update(taskid, Nodestate.DELETED)\n self._cluster.num_nodes -= 1\n self._cluster.all_cpus =float('%.2f' %(self._cluster.all_cpus-task.cpus))\n self._cluster.all_mem -= task.mem\n self._cluster.all_disk -= task.disk\n self.setaction(self._cluster, 'deletenode')\n self.setaction(self._cluster.tasks[taskid], 'delete')\n self._cluster.tasks[taskid].delete_time = time.time()\n self._cluster.tasks[taskid].count = 0\n self._state_provider.dump_cluster_state(self._cluster)\n log.info(\"Node %s of cluster %s has been deleted.\" %(taskid, self.cluster_name))\n\n def delete_cluster(self):\n \"\"\"Delete the db cluster we have stopped.\"\"\"\n if self._cluster.clusterstate not in [Clusterstate.INITIALIZING_FAILED,\n Clusterstate.DELETING_FAILED,\n Clusterstate.DELETING,\n Clusterstate.STOPPED,\n Clusterstate.STARTING_FAILED]:\n clusterstate = self._cluster.clusterstate\n log.error(\"This cluster %s is not allowed to delete ,\"\n \"because it is in %s state \" % (self._cluster.name, clusterstate))\n self._cluster.latest_error = \"This cluster is %s not allowed to delete\" % clusterstate\n self._state_provider.dump_cluster_state(self._cluster)\n raise ClusterstateError(\"Cluster is not allowed to be deleted ,because this cluster is %s\" % clusterstate)\n else:\n log.info(\"Deleting cluster %s.\" %self._cluster.name)\n self._cluster.clusterstate = Clusterstate.DELETING\n self.setaction(self._cluster, 'delete')\n for mysqlTask_id, task in self._cluster.tasks.items():\n if task.nodestate == Nodestate.DELETED:\n continue\n log.info(\"Delete node %s of cluster %s.\" % (mysqlTask_id, self._cluster.name))\n self._stateupdate.nodestate_update(mysqlTask_id, Nodestate.DELETED)\n self._cluster.num_nodes -= 1\n self._cluster.all_cpus = float('%.2f' %(self._cluster.all_cpus-task.cpus))\n self._cluster.all_mem -= task.mem\n self._cluster.all_disk -= task.disk\n self.setaction(self._cluster.tasks[mysqlTask_id], 'delete')\n self._cluster.tasks[mysqlTask_id].delete_time = time.time()\n self._cluster.tasks[mysqlTask_id].count = 0\n self._state_provider.dump_cluster_state(self._cluster)\n log.info(\"Cluster %s has been deleted.\" %self._cluster.name)\n\n\n #######################################################################\n # committer: liunannan\n # commit_time:2016-09-19\n # purpose:start node\n #######################################################################\n def start_node(self,taskid):\n \"\"\"Start the db node we have stopped.\"\"\"\n task = self._cluster.tasks[taskid]\n if task.nodestate not in [Nodestate.DELETED, Nodestate.STOPPED, Nodestate.STARTING_FAILED,\n Nodestate.EXPANDING_FAILED,Nodestate.CONTRACTING_FAILED]:\n nodestate = self._cluster.tasks[taskid].nodestate\n log.error(\"This node %s is not allowed to start ,\"\n \"because it is in %s state \" % (taskid, nodestate))\n task = self._cluster.tasks[taskid]\n task.latest_error = \"This node is %s not allowed to start\" % nodestate\n self._state_provider.dump_cluster_state(self._cluster)\n raise NodestateError(\"only stopped node can be started, node %s\"\n \" is in %s state \" % (taskid, nodestate))\n if self._cluster.clusterstate == Clusterstate.STARTING:\n if task.nodestate == Nodestate.DELETED:\n self.setaction(self._cluster, 'recover')\n else:\n self.setaction(self._cluster, 'start')\n else:\n if task.nodestate == Nodestate.DELETED:\n self.setaction(self._cluster, 'recovernode')\n else:\n self.setaction(self._cluster, 'startnode')\n self._cluster.clusterstate = Clusterstate.STARTINGNODE\n if task.nodestate == Nodestate.DELETED:\n self._cluster.num_nodes += 1\n task.delete_time = None\n self._cluster.all_cpus += task.cpus\n self._cluster.all_cpus = float('%2f' %self._cluster.all_cpus)\n self._cluster.all_mem += task.mem\n self._cluster.all_disk += task.disk\n self.setaction(self._cluster.tasks[taskid], 'recover')\n else:\n self.setaction(self._cluster.tasks[taskid], 'start')\n log.info(\"Starting node %s of cluster %s.\" %(task.task_id, self._cluster.name))\n task.nodestate = Nodestate.STAGING\n task.state = mesos_pb2.TASK_STAGING\n task.latest_restart_time = time.time()\n self._state_provider.dump_cluster_state(self._cluster)\n\n # 给节点增加性能参数\n def mysql_configure(self, taskid, configuration):\n \"\"\"Start the db node we have stopped.\"\"\"\n task = self._cluster.tasks[taskid]\n mysqlstructure = self._mysqlstructures[taskid]\n if task.nodestate not in [Nodestate.STOPPED, Nodestate.RUNNING, Nodestate.STARTING_FAILED]:\n nodestate = self._cluster.tasks[taskid].nodestate\n log.error(\"This node %s is not allowed to configure ,\"\n \"because it is in %s state \" % (taskid, nodestate))\n task = self._cluster.tasks[taskid]\n task.latest_error = \"This node is %s not allowed to configure\" % nodestate\n self._state_provider.dump_cluster_state(self._cluster)\n raise NodestateError(\"This node %s is in %s state ,except 'STOPPED' or 'RUNNING' or 'STARTING_FAILED'.\" % (taskid, nodestate))\n if mysqlstructure.initial:\n raise NodestateError(\"Please restart node %s to complete initial or cancel initial.\" %taskid)\n if len(configuration) == 0:\n return \"\"\n log.info(\"Configure node %s of cluster %s.\"\n % (task.task_id, self._cluster.name))\n message, change = update_configuration(mysqlstructure.configuration, configuration)\n mysqlstructure.change = change\n log.info(\"Update node %s configuration: \\n %s.\" %(taskid, message))\n self.setaction(self._cluster.tasks[taskid], 'configure')\n self._state_provider.dump_mysql_state(mysqlstructure)\n self._state_provider.dump_cluster_state(self._cluster)\n return message\n\n #删除节点的部分性能参数\n def delete_configure(self, taskid, configure_name):\n \"\"\"Start the db node we have stopped.\"\"\"\n task = self._cluster.tasks[taskid]\n mysqlstructure = self._mysqlstructures[taskid]\n if task.nodestate not in [Nodestate.STOPPED, Nodestate.RUNNING]:\n nodestate = self._cluster.tasks[taskid].nodestate\n log.error(\"This node %s is not allowed to configure ,\"\n \"because it is in %s state \" % (taskid, nodestate))\n task = self._cluster.tasks[taskid]\n task.latest_error = \"This node is %s not allowed to configure\" % nodestate\n self._state_provider.dump_cluster_state(self._cluster)\n raise NodestateError(\"This node %s is in %s state ,except 'STOPPED' or 'RUNNING'.\" % (taskid, nodestate))\n if len(configure_name) == 0:\n return \"\"\n old_configuration = copy.deepcopy(mysqlstructure.configuration)\n remove = []\n invalid = []\n for name in configure_name:\n if name in mysqlstructure.configuration.keys():\n remove.append(name)\n del mysqlstructure.configuration[name]\n else:\n invalid.append(name)\n message = \"\"\n if len(remove) > 0:\n mysqlstructure.change = True\n message += \"Remove parameter %s from node's configuration.\\n\" %str(remove)\n log.info(\"Update node %s configuration from %s to %s.\" % (\n taskid, str(old_configuration), str(mysqlstructure.configuration)))\n self.setaction(self._cluster.tasks[taskid], 'configure')\n self._state_provider.dump_cluster_state(self._cluster)\n self._state_provider.dump_mysql_state(mysqlstructure)\n if len(invalid) >0:\n message += \"Node %s doesn't have these parameter %s.\\n\" %(taskid, str(invalid))\n return message\n\n #获取节点的所有性能参数\n def get_configure(self, taskid):\n mysqlstructure = self._mysqlstructures[taskid]\n message = \"\"\n if len(mysqlstructure.configuration) == 0:\n message += \"Node %s's configuration is NULL.\\n\" %taskid\n else:\n for k, v in mysqlstructure.configuration.items():\n message += \"%s = %s\\n\" % (str(k), str(v))\n return message\n\n def shiftdelete_node(self,taskid):\n \"\"\"Shift delete the db cluster we have deleted.\"\"\"\n cluster = self._cluster\n task = cluster.tasks[taskid]\n task_id = task.task_id\n log.info(\"Shift delete node %s.\" % task_id)\n if task.nodestate not in [Nodestate.DELETED]:\n nodestate = task.nodestate\n log.error(\"This node %s is not allowed to shift delete ,\"\n \"because it is in %s state \" % (taskid, nodestate))\n\n task.latest_error = \"This node is %s not allowed to shift delete\" % nodestate\n self._state_provider.dump_cluster_state(cluster)\n raise NodestateError(\"only deleted node can be shift delete, node %s\"\n \" is in %s state \" % (taskid, nodestate))\n\n if task.hostname:\n useless_resource = get_useless_resource(task_id,\n task.hostname,\n task.cpus,\n task.mem,\n task.port)\n self._release.append(useless_resource)\n self._state_provider.dump_scheduler_state(self._state)\n log.info(\"Prepare to recycle resources %s\" % str(useless_resource))\n if isinstance(task.precursor, dict) and len(task.precursor) > 0 :\n for precursor, port in task.precursor.items():\n useless_resource = get_useless_resource(task.task_id, precursor, task.cpus, task.mem,\n port)\n log.info(\"Prepare ro recycle resources %s\" % str(useless_resource))\n self._release.append(useless_resource)\n\n del cluster.tasks[task_id]\n del self._mysqlstructures[task_id]\n self._cluster_manager.task_ids.remove(task_id)\n self._state_provider.remove_mysql_state(self.cluster_name, task_id)\n if len(cluster.tasks) == 0:\n self._terminating = True\n if task_id == cluster.master_taskid:\n cluster.master_taskid = None\n if self.terminated:\n log.info(\"Shutting down launcher for cluster %s\" % self.cluster_name)\n self._shutdown()\n else:\n self._state_provider.dump_cluster_state(cluster)\n\n #######################################################################\n # committer: liunannan\n # commit_time:2016-09-10\n # purpose:kill faild add node\n #######################################################################\n def kill_addnode(self,taskid):\n \"\"\"\n Kill the addnode.\n\n NOTE: Nodes killing is asynchronous. Use 'terminated' property to check if all tasks in the\n cluster are killed.\n \"\"\"\n with self._lock:\n # Task killing is unreliable. Reconciliation should retry killing.\n for task_id in self._cluster.tasks:\n if task_id == taskid:#and self._cluster.tasks[task_id].state==Nodestate.RUNNING:\n self._driver.killTask(mesos_pb2.TaskID(value=taskid))\n log.info(\"Killing add task %s of cluster %s\" % (taskid, self.cluster_name))\n return\n\n ###############################################################################\n ##mahongchao\n ##给object的latest_action属性赋值\n def setaction(self, object, state):\n object.latest_action['action'] = state\n object.latest_action['time'] = time.time()\n\n @property\n def terminated(self):\n \"\"\"True if all tasks in the cluster are killed.\"\"\"\n return self._terminating and len(self._cluster.active_tasks) == 0\n\n ###################################################################################\n # 若offer中有没使用过的满足task_disk的disk,返回没用过的最大的disk的path,\n # 否则返回offer中使用次数最少且满足task_disk的disk的path,使用次数相同的去较大的disk的path\n # 若offer中没有满足task_disk的disk,返回None\n def getpath(self, offer, task_disk):\n #参数说明\n #offer:mesos offer\n #task_disk:任务需要的disk大小\n #diskcount:{slave_id:array}\n common, exclusive = split_mount(offer)\n if self.exclusive == 0:\n suits = [resource for resource in common if int(resource.scalar.value) >= task_disk.as_(Data.MB)]\n if len(suits) == 0:\n return None, None\n for resource in suits:\n path = str(resource.disk.source.path.root)\n if not path:\n path = AGENTDIR\n if offer.hostname not in self.diskcount.keys() or path not in self.diskcount[offer.hostname].keys():\n return path, None\n\n min_path = [path for path,count in self.diskcount[offer.hostname].items() if count == min(self.diskcount[offer.hostname].values())]\n for resource in suits:\n path = str(resource.disk.source.path.root)\n if not path:\n path = AGENTDIR\n if path in min_path:\n return path, None\n\n else:\n d = {int(resource.scalar.value): str(resource.disk.source.mount.root)\n for resource in exclusive if int(resource.scalar.value) >= task_disk.as_(Data.MB)}\n if len(d) > 0:\n mount_disk = min(d.keys())\n return d[mount_disk], mount_disk\n else:\n return None, None\n\n\n #获取offer中所有disk中(挂载和非挂载)最大的那个的容量(M)和路径\n def getbigdisk(self, resources):\n disk = Amount(0, Data.BYTES)\n if self.exclusive == 1:\n for resource in resources:\n if resource.name == 'disk' and resource.disk.source.type == 2:\n d = Amount(int(resource.scalar.value * 1024 * 1024), Data.BYTES)\n if d > disk:\n disk = d\n else:\n for resource in resources:\n if resource.name == 'disk' and resource.disk.source.type != 2:\n d = Amount(int(resource.scalar.value * 1024 * 1024), Data.BYTES)\n if d > disk:\n disk = d\n return disk\n\n ###################################################################################\n\n def _get_resources(self, resources):\n \"\"\"Return a tuple of the resources: cpus, mem, disk, set of ports.\"\"\"\n cpus, mem, ports = 0.0, Amount(0, Data.MB), set()\n for resource in resources:\n # We do the following check:\n # 1. We only care about the role of the resources we are going to use.\n # 2. For this resource if it is not of the role we want we throw an exception. This implies\n # that when a slave offers resources that include both the '*' role and the Hyaline framework\n # role we'll decline the entire offer. We expect Mesos slave hosts that run Hyaline executors\n # to dedicate *all* its resources to it as we are not currently optimizing for the use\n # cases where Hyaline tasks run side-by-side with tasks from other frameworks. This also\n # simplifies the launcher's role filtering logic.\n # TODO(jyx): Revisit this when the above assumption changes.\n # create cluster\n # add node\n # change host restore\n if (resource.name in ('cpus', 'mem', 'disk', 'ports') and\n resource.role not in ['*']):\n continue\n if resource.name == 'cpus' and resource.scalar.value > cpus:\n cpus = resource.scalar.value\n elif resource.name == 'mem':\n # 'Amount' requires an integer while 'value' is double. We convert it bytes to minimize\n # precision loss.\n resourcemem = Amount(int(resource.scalar.value * 1024 * 1024), Data.BYTES)\n if resourcemem > mem:\n mem = resourcemem\n elif resource.name == 'ports' and resource.ranges.range:\n for r in resource.ranges.range:\n ports |= set(range(r.begin, r.end + 1))\n\n return cpus, mem, ports\n\n def _new_task(self, offer, task_id, resources, action):\n task = mesos_pb2.TaskInfo()\n task.task_id.value = task_id\n task.slave_id.value = offer.slave_id.value\n task.name = task_id\n task.resources.extend(resources)\n\n task.executor.executor_id.value = task_id # Use task_id as executor_id.\n task.executor.name = EXECUTOR_NAME\n task.executor.command.value = os.path.join(self.uris['python_dir'],'bin','hyaline_executor')\n\n # add replication_user and replication_password by liuyue\n task.data = json.dumps({\n 'framework_user': self._framework_user,\n 'host': offer.hostname,\n 'port': 'task_port',\n 'cluster': self._cluster.name,\n 'cluster_user': self._cluster.user,\n 'cluster_password': self._password_box.decrypt(self._cluster.encrypted_password),\n 'replication_user': self._cluster.replication_user,\n 'replication_password': self._password_box_repl.decrypt(self._cluster.replication_password),\n 'cluster_mode': self._cluster.cluster_mode,\n 'parameter_flag': self._cluster.parameter_flag,\n 'server_id': 'server_id', # Use the integer Task ID as the server ID.\n 'zk_url': self._zk_url,\n 'backup_id': self._cluster.backup_id,\n 'sandboxdir': 'nosandboxdir',\n 'delete':'',\n 'action':action,\n 'slave_waitfor_master':self.slave_waitfor_master,\n 'slave_waitfor_check':self.slave_waitfor_check,\n 'master_waitfor_switch':self.master_waitfor_switch,\n 'mycnf':self.mycnf,\n 'role':self._framework_role\n })\n return task\n\n def _new_operations(self, offer, task_id, server_id, task_cpus, task_mem, task_disk, task_port, path, mount_disk):\n reserve = mesos_pb2.Offer.Operation()\n reserve.type = 2\n reserve.reserve.resources.extend(create_reserve_resources(task_cpus,\n task_mem,\n task_disk,\n set([task_port]),\n self._framework_principal,\n self._framework_role,\n path,\n task_id,\n self.exclusive,\n mount_disk)[0])\n\n unreserve = mesos_pb2.Offer.Operation()\n unreserve.type = 3\n unreserve.unreserve.resources.extend(create_reserve_resources(task_cpus,\n task_mem,\n task_disk,\n set([task_port]),\n self._framework_principal,\n self._framework_role,\n path,\n task_id,\n self.exclusive,\n mount_disk)[0])\n create = mesos_pb2.Offer.Operation()\n create.type = 4 # create persistence\n create.create.volumes.extend(create_reserve_resources(task_cpus,\n task_mem,\n task_disk,\n set([task_port]),\n self._framework_principal,\n self._framework_role,\n path,\n task_id,\n self.exclusive,\n mount_disk)[1])\n destroy = mesos_pb2.Offer.Operation()\n destroy.type = 5 # destroy persistence\n destroy.destroy.volumes.extend(create_reserve_resources(task_cpus,\n task_mem,\n task_disk,\n set([task_port]),\n self._framework_principal,\n self._framework_role,\n path,\n task_id,\n self.exclusive,\n mount_disk)[1])\n\n task = mesos_pb2.TaskInfo()\n task.task_id.value = task_id\n task.slave_id.value = offer.slave_id.value\n task.name = task_id\n\n task.executor.executor_id.value = task_id # Use task_id as executor_id.\n task.executor.name = EXECUTOR_NAME\n\n need_install = True\n for used_slave in self.used_slaves:\n if used_slave[\"slave_id\"] == str(offer.slave_id.value):\n need_install = False\n break\n\n\n if need_install and self._auto_deploy == \"yes\":\n callback = \"install\"\n\n used_slave = get_used_slave(str(offer.slave_id.value), task_id)\n self.used_slaves.append(used_slave)\n self._state_provider.dump_scheduler_state(self._state)\n task.executor.command.value = self._executor_cmd\n task.executor.command.shell = False\n\n executor_uri = task.executor.command.uris.add()\n executor_uri.value = self.uris['executor_uri']\n executor_uri.executable = False\n\n task.executor.command.arguments.append(self._executor_cmd)\n task.executor.command.arguments.append(self.uris['python_dir'])\n task.executor.command.arguments.append(self._framework_user)\n if self._framework_user == 'root':\n task.executor.command.arguments.append('/root')\n else:\n task.executor.command.arguments.append(os.path.join('/home',self._framework_user))\n task.executor.command.arguments.append(\"--task_id=\" + task_id)\n task.executor.command.arguments.append(\"--executor_log_dir=\" + self._log_configure[\"log_dir\"])\n task.executor.command.arguments.append(\"--log_delete_timeout=\" + str(int(self._log_configure[\"log_delete_timeout\"])))\n task.executor.command.arguments.append(\"--log_group_number=\" + str(self._log_configure[\"log_group_number\"]))\n task.executor.command.arguments.append(\"--log_switch_size=\" + str(int(self._log_configure[\"log_switch_size\"])))\n task.executor.command.arguments.append(\"--log_clean_hour=\" + str(self._log_configure[\"log_clean_hour\"]))\n task.executor.command.arguments.append(\"--log_clean_minite=\" + str(self._log_configure[\"log_clean_minite\"]))\n else:\n callback = \"\"\n task.executor.command.shell = False\n if self._framework_user == 'root':\n task.executor.command.value = os.path.join('/root', '.local/bin','hyaline_executor')\n else:\n task.executor.command.value = os.path.join('/home',self._framework_user,'.local/bin','hyaline_executor')\n task.executor.command.arguments.append(task.executor.command.value)\n task.executor.command.arguments.append(\"--task_id=\"+task_id)\n task.executor.command.arguments.append(\"--executor_log_dir=\" + self._log_configure[\"log_dir\"])\n task.executor.command.arguments.append(\"--log_delete_timeout=\" + str(int(self._log_configure[\"log_delete_timeout\"])))\n task.executor.command.arguments.append(\"--log_group_number=\" + str(self._log_configure[\"log_group_number\"]))\n task.executor.command.arguments.append(\"--log_switch_size=\" + str(int(self._log_configure[\"log_switch_size\"])))\n task.executor.command.arguments.append(\"--log_clean_hour=\" + str(self._log_configure[\"log_clean_hour\"]))\n task.executor.command.arguments.append(\"--log_clean_minite=\" + str(self._log_configure[\"log_clean_minite\"]))\n\n try:\n task.resources.extend(create_reserve_resources(task_cpus,\n task_mem,\n task_disk,\n set([task_port]),\n self._framework_principal,\n self._framework_role,\n path,\n task_id,\n self.exclusive,\n mount_disk)[2])\n\n except:\n task.resources.extend(create_reserve_resources(task_cpus,\n task_mem,\n task_disk,\n set([task_port]),\n self._framework_principal,\n self._framework_role,\n path,\n task_id,\n self.exclusive,\n mount_disk)[2])\n\n\n task.data = json.dumps({\n 'framework_user': self._framework_user,\n 'host': offer.hostname,\n 'port': task_port,\n 'cluster': self._cluster.name,\n 'cluster_user': self._cluster.user,\n 'cluster_password': self._password_box.decrypt(self._cluster.encrypted_password),\n 'replication_user': self._cluster.replication_user,\n 'replication_password': self._password_box_repl.decrypt(self._cluster.replication_password),\n 'cluster_mode': self._cluster.cluster_mode,\n 'groupname':self._cluster.groupname,\n 'parameter_flag': self._cluster.parameter_flag,\n 'server_id': server_id, # Use the integer Task ID as the server ID.\n 'zk_url': self._zk_url,\n 'backup_id': self._cluster.backup_id,\n 'sandboxdir': 'nosandboxdir',\n 'delete': '',\n 'action': '',\n 'slave_waitfor_master': self.slave_waitfor_master,\n 'slave_waitfor_check': self.slave_waitfor_check,\n 'master_waitfor_switch': self.master_waitfor_switch,\n 'mycnf': self.mycnf,\n 'uris': self.uris,\n 'mysql_version': self._cluster.mysql_version,\n \"callback\": callback,\n \"mysql\":\"\",\n 'identity':self._cluster.tasks[task_id].identity,\n \"configuration\":{},\n \"is_gtid\":self._cluster.is_gtid,\n \"message_dir\":self.message_dir,\n \"message_number\":self._cluster.tasks[task_id].message_number,\n \"master\":self._cluster.tasks[task_id].master,\n \"replication_mode\":self._cluster.replication_mode\n })\n\n launch = mesos_pb2.Offer.Operation()\n launch.type = 1\n launch.launch.task_infos.extend([task])\n\n return launch, reserve, unreserve, create, destroy\n\n def status_update(self, status):\n \"\"\"\n Handle the status update for a task of this cluster.\n\n NOTE:\n Duplicate status updates may be handled by either the same scheduler instance or a new\n instance with the restored state.\n \"\"\"\n with self._lock:\n task_id = str(status.task_id.value)\n if 'mini' == str.split(task_id, '-')[0]:\n task_id = string.lstrip(task_id,'mini-')\n if task_id not in self._cluster.tasks:\n log.warn(\"Ignoring status update for unknown task %s\" % task_id)\n return\n\n if task_id in self.refuse_hosts.keys():\n del self.refuse_hosts[task_id]\n\n task = self._cluster.tasks[task_id]\n mysqlstructure = self._mysqlstructures[task_id]\n\n previous_state = task.state\n # We don't want to ignore a duplicate update if the previous one was not successfully handled.\n # Therefore, we should not checkpoint the status change until we have finished all operations.\n if previous_state == status.state and task.nodestate != Nodestate.STOPPING:\n if is_terminal(status.state):\n log.error(str(task_id)+' error: '+str(status.message))\n else:\n log.info('Ignoring duplicate status update %s for task %s' % (\n mesos_pb2.TaskState.Name(status.state),\n task_id))\n return\n\n log.info('Updating state of node %s of cluster %s from %s to %s' % (\n status.task_id.value,\n self.cluster_name,\n mesos_pb2.TaskState.Name(previous_state),\n mesos_pb2.TaskState.Name(status.state)))\n task.state = status.state\n\n if status.state == mesos_pb2.TASK_STARTING:\n if status.message in [\"restart\"]:\n self._stateupdate.nodestate_update(task_id, Nodestate.SERVICE_RESTORE_START)\n self.setaction(self._cluster, 'service restore')\n self.setaction(self._cluster.tasks[task_id], 'service restore')\n else:\n self._cluster.tasks[task_id].sandboxdir = str(status.message)\n try:\n self._cluster.tasks[task_id].path[1][2] = str(status.message)\n except:\n pass\n log.info(\"Get sandbox directory %s of node %s from executor.\" % (str(status.message), task_id))\n if self._cluster.tasks[task_id].nodestate == Nodestate.CHANGE_HOST_RESTORE_START \\\n or self._cluster.tasks[task_id].nodestate == Nodestate.PHYSICS_RESTORE_START \\\n or self._cluster.clusterstate == Clusterstate.ADDINGNODE:\n log.info(\"Node %s is ready ro data restore.\" %task_id)\n self._stateupdate.nodestate_update(task_id, Nodestate.DATA_RESTORING)\n self._state_provider.dump_cluster_state(self._cluster)\n return\n\n starting_tasks = self._cluster.starting_tasks\n running_tasks = self._cluster.running_tasks\n if self._cluster.cluster_mode == \"MS\":\n if self._cluster.master_taskid in starting_tasks or self._cluster.master_taskid in running_tasks:\n if self._cluster.master_taskid in starting_tasks:\n starting_tasks.remove(self._cluster.master_taskid)\n\n if self._configure_count == 1 and len(starting_tasks) == self._cluster.num_nodes - 1:\n self._configure_count += 1\n task_ids = set(self._cluster.tasks.keys())\n master = self._cluster.master_taskid\n master_host=self._cluster.tasks[master].hostname\n master_port = self._cluster.tasks[master].port\n message = get_message_data(task_ids,\n \"configure_ms\",\n master=master,\n master_host=master_host,\n port=master_port)\n try:\n self._cluster_manager.send_message(message)\n except SendMessageError as e:\n self._cluster.latest_error = e.message\n self.init_kill()\n self.roll_back(task)\n elif self._cluster.cluster_mode == \"GR\":\n log.info(\"node %s ask active nodes\" % task_id)\n\n group_seeds = ''\n for v in self._cluster.tasks.values():\n if v.state == mesos_pb2.TASK_RUNNING:\n group_seeds += \",\"+str(v.hostname) + \":\" + str(v.port[1])\n message = get_message_data(set([task_id]),\n \"start_group_replication\",\n group_seeds=group_seeds)\n try:\n self._cluster_manager.send_message(message)\n except SendMessageError as e:\n self._cluster.latest_error = e.message\n self.init_kill()\n self.roll_back(task)\n elif self._cluster.cluster_mode == \"MMS\":\n master1, master2,slaves1,slaves2 = self.distinguish_identity()\n master1_host = self._cluster.tasks[master1].hostname\n master1_port = self._cluster.tasks[master1].port\n master2_host = self._cluster.tasks[master2].hostname\n master2_port = self._cluster.tasks[master2].port\n first_configure = set(slaves1)\n if master1 in starting_tasks or master1 in running_tasks:\n if self._configure_count == 1 and first_configure.issubset(set(self._cluster.starting_tasks)):\n task_ids = set(slaves1)|set([master2])\n message = get_message_data(task_ids,\n \"configure_mms_1\",\n master=master1,\n master_host=master1_host,\n port=master1_port)\n try:\n self._cluster_manager.send_message(message)\n self._configure_count += 1\n except SendMessageError as e:\n self._cluster.latest_error = e.message\n self.init_kill()\n self.roll_back(task)\n if set(slaves1).issubset(set(self._cluster.running_tasks)) \\\n and set(slaves2).issubset(set(self._cluster.starting_tasks)):\n task_ids = set(slaves2)|set([master1])\n message = get_message_data(task_ids,\n \"configure_mms_2\",\n master=master2,\n master_host=master2_host,\n port=master2_port)\n try:\n self._cluster_manager.send_message(message)\n except SendMessageError as e:\n self._cluster.latest_error = e.message\n self.init_kill()\n self.roll_back(task)\n\n self._state_provider.dump_cluster_state(self._cluster)\n\n elif status.state == mesos_pb2.TASK_RUNNING:\n try:\n detailed_path = json.loads(status.message)\n if isinstance(detailed_path,dict):\n for k,v in task.path.items():\n if not v[2]:\n for kd, vd in detailed_path.items():\n if int(kd) == int(k):\n v[2] = str(vd)\n except:\n pass\n if task.nodestate == Nodestate.STOPPING:\n self.kill_node(task_id)\n log.info(\"Kill node %s because it is in 'STOPPING' state\" %task_id)\n else:\n if self._cluster.cluster_mode == \"GR\":\n group_message = str(status.message).split(\",\")\n self._cluster.tasks[task_id].sandboxdir = group_message[0]\n self._cluster.tasks[task_id].uuid = group_message[1]\n group_dir = posixpath.join(self.message_dir, GROUP_PATH+\"-\"+str(self._cluster.name))\n if len(self._cluster.running_tasks) == 1:\n self._cluster.master_taskid = task_id\n self._cluster.tasks[task_id].identity = \"master\"\n self._stateupdate.nodestate_update(task_id, Nodestate.RUNNING)\n self._cluster_manager._client.retry(\n self._cluster_manager._client.delete, group_dir, recursive=True)\n else:\n self._stateupdate.nodestate_update(task_id, Nodestate.RUNNING)\n self._state_provider.dump_cluster_state(self._cluster)\n if mysqlstructure.change:\n mysqlstructure.change = False\n self._state_provider.dump_mysql_state(mysqlstructure)\n if mysqlstructure.initial:\n if mysqlstructure.change:\n mysqlstructure.change = False\n mysqlstructure.configuration = mysqlstructure.initial_configuration.copy()\n mysqlstructure.initial = False\n self._state_provider.dump_mysql_state(mysqlstructure)\n if self._cluster.cluster_mode == \"MMS\":\n master1, master2,slaves1,slaves2 = self.distinguish_identity()\n master2_host = self._cluster.tasks[master2].hostname\n master2_port = self._cluster.tasks[master2].port\n if set(slaves1).issubset(set(self._cluster.running_tasks)) \\\n and set(slaves2).issubset(set(self._cluster.starting_tasks)):\n task_ids = set(slaves2)|set([master1])\n message = get_message_data(task_ids,\n \"configure_mms_2\",\n master=master2,\n master_host=master2_host,\n port=master2_port)\n try:\n self._cluster_manager.send_message(message)\n except SendMessageError as e:\n self._cluster.latest_error = e.message\n self.init_kill()\n self.roll_back(task)\n\n elif status.state == mesos_pb2.TASK_FINISHED:\n delete_works = []\n for mini_task in self._cluster.mini_tasks:\n if mini_task['task_id'] == task.task_id and mini_task['state'] == 'start':\n delete_works.append(mini_task)\n for work in delete_works:\n self._cluster.mini_tasks.remove(work)\n self._stateupdate.nodestate_update(task_id, Nodestate.RUNNING)\n self._state_provider.dump_cluster_state(self._cluster)\n\n elif status.state == mesos_pb2.TASK_KILLED:\n if self._cluster.clusterstate == Clusterstate.INITIALIZING_FAILED:\n self._stateupdate.nodestate_update(task_id, Nodestate.STAGING_FAILED)\n if self._cluster.cluster_mode == \"GR\":\n group_dir = posixpath.join(self.message_dir, GROUP_PATH+\"-\"+str(self._cluster.name))\n self._cluster_manager._client.retry(\n self._cluster_manager._client.delete, group_dir, recursive=True)\n self.roll_back(task)\n else:\n self._stateupdate.nodestate_update(task_id, Nodestate.STOPPED)\n if self._cluster.cluster_mode == \"GR\":\n if self._cluster.tasks[task_id].identity == \"master\":\n self._cluster.tasks[task_id].identity = \"slave\"\n new_master_taskid = get_new_master(self._cluster)\n self._cluster.master_taskid = new_master_taskid\n group_dir = posixpath.join(self.message_dir, GROUP_PATH+\"-\"+str(self._cluster.name))\n self._cluster_manager._client.retry(\n self._cluster_manager._client.delete, group_dir, recursive=True)\n log.info(\"Node %s was successfully stopped.\" %task_id)\n self._state_provider.dump_cluster_state(self._cluster)\n return\n\n elif is_terminal(status.state):\n for used_slave in self.used_slaves:\n if used_slave[\"task_id\"] == task_id and used_slave[\"state\"] == \"installing\":\n self.used_slaves.remove(used_slave)\n log.info(\"Remove %s from used_slaves because task failed.\" % str(used_slave))\n self._state_provider.dump_scheduler_state(self._state)\n break\n log.error(\"Node %s is dead because error %s\" % (task_id, str(status.message)))\n if 'mini' == str.split(str(status.task_id.value), '-')[0]:\n task_id = string.lstrip(task_id, 'mini-')\n task = self._cluster.tasks[task_id]\n self._stateupdate.nodestate_update(task_id,Nodestate.RUNNING)\n task.latest_error = 'fail to delete sandbox_backup folder'\n self._state_provider.dump_cluster_state(self._cluster)\n return\n if self._cluster.tasks[task_id].nodestate in [Nodestate.STOPPING]:\n self._stateupdate.nodestate_update(task_id, Nodestate.STOPPED)\n return\n self._cluster.tasks[task_id].latest_error = status.message\n if task.nodestate == Nodestate.RUNNING:\n log.info(\"Now service restoring for Node %s.\" %task_id)\n self.setaction(self._cluster, 'service restore')\n self.setaction(self._cluster.tasks[task_id], 'service restore')\n self._stateupdate.nodestate_update(task_id, Nodestate.SERVICE_RESTORING)\n elif task.nodestate in [Nodestate.STARTING,Nodestate.STAGING]:\n log.error(\"Starting node %s failed.\" %task_id)\n self._stateupdate.nodestate_update(task_id, Nodestate.STARTING_FAILED)\n elif task.nodestate == Nodestate.SERVICE_RESTORE_START:\n log.error(\"Service restore node %s failed.\" %task_id)\n self._stateupdate.nodestate_update(task_id, Nodestate.SERVICE_RESTORING_FAILED)\n elif task.nodestate in [Nodestate.PHYSICS_RESTORE_START]:\n log.error(\"Physics restore node %s failed.\" %task_id)\n self._stateupdate.nodestate_update(task_id, Nodestate.PHYSICS_RESTORING_FAILED)\n elif task.nodestate in [Nodestate.DATA_RESTORING]:\n log.error(\"Fail to data restore for node %s.\" %task_id)\n if task.latest_action[\"action\"] == 'change host restore':\n self._stateupdate.nodestate_update(task_id, Nodestate.CHANGE_HOST_RESTORING_FAILED)\n self.roll_back(task)\n else:\n self._stateupdate.nodestate_update(task_id, Nodestate.PHYSICS_RESTORING_FAILED)\n elif task.nodestate == Nodestate.CHANGE_HOST_RESTORE_START:\n log.error(\"Change host restore node %s failed.\" %task_id)\n self._stateupdate.nodestate_update(task_id, Nodestate.CHANGE_HOST_RESTORING_FAILED)\n self.roll_back(task)\n\n if self._cluster.clusterstate == Clusterstate.INITIALIZING_FAILED:\n if self._cluster.cluster_mode == \"GR\":\n group_dir = posixpath.join(self.message_dir, GROUP_PATH+\"-\"+str(self._cluster.name))\n self._cluster_manager._client.retry(\n self._cluster_manager._client.delete, group_dir, recursive=True)\n self._cluster.latest_error = 'initial ' +task_id+' error: '+ status.message\n self.init_kill()\n self.roll_back(task)\n\n elif self._cluster.clusterstate == Clusterstate.STARTING_FAILED:\n self._cluster.latest_error = 'start '+task_id+' error: '+ status.message\n self.start_failed_kill()\n elif self._cluster.clusterstate == Clusterstate.ADDINGNODE_FAILED:\n self._cluster.latest_error = 'add '+task_id+' error: '+ status.message\n if task.nodestate == Nodestate.STAGING_FAILED:\n self.roll_back(task)\n if self.terminated:\n log.info(\"Shutting down launcher for cluster %s\" % self.cluster_name)\n self._shutdown()\n return\n\n # Finally, checkpoint the status update.\n self._state_provider.dump_cluster_state(self._cluster)\n log.info(\"Checkpointed the status update for task %s of cluster %s\" % (\n task_id, self.cluster_name))\n\n def _shutdown(self):\n self._cluster_manager.delete_cluster()\n log.info(\"Deleted cluster %s from ZooKeeper\" % self.cluster_name)\n self._state_provider.remove_cluster_state(self.cluster_name)\n log.info(\"Removed the state of cluster %s\" % self.cluster_name)\n\n #初始化失败或者增加节点失败 进行回滚\n def roll_back(self, task):\n task.path = {}\n task.persist_id = 1\n if task.hostname:\n useless_resource = get_useless_resource(task.task_id,\n task.hostname,\n task.cpus,\n task.mem,\n task.port)\n self._release.append(useless_resource)\n task.hostname = None\n task.ip = None\n task.count = 0\n task.port = None\n\n self._state_provider.dump_scheduler_state(self._state)\n\n\n ###########################\n # committer: liuyue\n # commit_time:2016-09-10\n # purpose:change master\n ########################################################\n def switch_master(self, hostname):\n with self._lock:\n for taskid, task in self._cluster.tasks.items():\n if task.hostname == hostname:\n new_master_taskid = taskid\n break\n\n\n ################################################################################################################\n\n def framework_message(self, task_id, slave_id, data):\n with self._lock:\n pass\n\n def stop(self):\n pass\n\n def is_my_reserve(self, offer, task_id):\n for resource in offer.resources:\n if task_id in resource.disk.persistence.id:\n return True\n return False\n\n def distinguish_identity(self):\n master1 = None\n master2 = None\n slaves1 = []\n slaves2 = []\n for task_id, task in self._cluster.tasks.items():\n if task.identity == \"master-1\":\n master1 = task_id\n continue\n elif task.identity == \"master-2\":\n master2 = task_id\n continue\n for task_id, task in self._cluster.tasks.items():\n if task.identity == \"master-1\" or task.identity == \"master-2\":\n continue\n if task.master == master1:\n slaves1.append(task_id)\n continue\n elif task.master == master2:\n slaves2.append(task_id)\n continue\n return master1, master2, slaves1, slaves2\n\n\ndef create_resources(cpus, mem, disk, ports, role='*'):\n \"\"\"Return a list of 'Resource' protobuf for the provided resources.\"\"\"\n cpus_resources = mesos_pb2.Resource()\n cpus_resources.name = 'cpus'\n cpus_resources.type = mesos_pb2.Value.SCALAR\n cpus_resources.role = role\n cpus_resources.scalar.value = cpus\n\n mem_resources = mesos_pb2.Resource()\n mem_resources.name = 'mem'\n mem_resources.type = mesos_pb2.Value.SCALAR\n mem_resources.role = role\n mem_resources.scalar.value = mem.as_(Data.MB)\n\n disk_resources = mesos_pb2.Resource()\n disk_resources.name = 'disk'\n disk_resources.type = mesos_pb2.Value.SCALAR\n disk_resources.role = role\n disk_resources.scalar.value = disk.as_(Data.MB)\n\n resources = [cpus_resources, mem_resources, disk_resources]\n\n if ports:\n ports_resources = mesos_pb2.Resource()\n ports_resources.name = 'ports'\n ports_resources.type = mesos_pb2.Value.RANGES\n ports_resources.role = role\n for port in ports:\n port_range = ports_resources.ranges.range.add()\n port_range.begin = port\n port_range.end = port\n resources += [ports_resources]\n\n return resources\n\n\ndef create_reserve_resources(cpus, mem, disk, ports, principal, role, path, task_id, exclusive,mount_disk):\n max_path = path[max(path.keys())][0]\n reserve_resources = []\n volumes = []\n task_resources = []\n # executor_resources = []\n if cpus:\n cpus_resources = mesos_pb2.Resource()\n cpus_resources.name = 'cpus'\n cpus_resources.type = mesos_pb2.Value.SCALAR\n cpus_resources.role = role\n cpus_resources.scalar.value = cpus\n cpus_resources.reservation.principal = principal\n reserve_resources.append(cpus_resources)\n task_resources.append(cpus_resources)\n # executor_resources.append(cpus_resources)\n\n if mem:\n mem_resources = mesos_pb2.Resource()\n mem_resources.name = 'mem'\n mem_resources.type = mesos_pb2.Value.SCALAR\n mem_resources.role = role\n mem_resources.scalar.value = mem.as_(Data.MB)\n mem_resources.reservation.principal = principal\n reserve_resources.append(mem_resources)\n task_resources.append(mem_resources)\n # executor_resources.append(mem_resources)\n\n if disk:\n disk_resources = mesos_pb2.Resource()\n disk_resources.name = 'disk'\n disk_resources.type = mesos_pb2.Value.SCALAR\n disk_resources.role = role\n disk_resources.scalar.value = disk.as_(Data.MB)\n disk_resources.reservation.principal = principal\n if exclusive == 0:\n if max_path != AGENTDIR:\n resource_diskinfo = mesos_pb2.Resource.DiskInfo()\n resource_diskinfo.source.type = 1\n resource_diskinfo.source.path.root = max_path\n disk_resources.disk.MergeFrom(resource_diskinfo)\n else:\n disk_resources.scalar.value = mount_disk\n resource_diskinfo = mesos_pb2.Resource.DiskInfo()\n resource_diskinfo.source.type = 2\n resource_diskinfo.source.mount.root = max_path\n disk_resources.disk.MergeFrom(resource_diskinfo)\n reserve_resources.append(disk_resources)\n\n disk_volumes = mesos_pb2.Resource()\n disk_volumes.name = 'disk'\n disk_volumes.type = mesos_pb2.Value.SCALAR\n disk_volumes.role = role\n disk_volumes.scalar.value = disk.as_(Data.MB)\n disk_volumes.reservation.principal = principal\n diskinfo = mesos_pb2.Resource.DiskInfo()\n if max(path.keys()) == 1:\n diskinfo.persistence.id = task_id\n else:\n diskinfo.persistence.id = task_id+\"-volume-\"+str(max(path.keys()))\n diskinfo.persistence.principal = principal\n diskinfo.volume.mode = 1 # read-write\n diskinfo.volume.container_path = 'volume-'+str(max(path.keys()))\n if exclusive == 0:\n if max_path != AGENTDIR:\n diskinfo.source.type = 1\n diskinfo.source.path.root = max_path\n else:\n disk_volumes.scalar.value = mount_disk\n diskinfo.source.type = 2\n diskinfo.source.mount.root = max_path\n disk_volumes.disk.MergeFrom(diskinfo)\n volumes.append(disk_volumes)\n\n for k,v in path.items():\n disk_volumes = mesos_pb2.Resource()\n disk_volumes.name = 'disk'\n disk_volumes.type = mesos_pb2.Value.SCALAR\n disk_volumes.role = role\n disk_volumes.scalar.value = v[1].as_(Data.MB)\n disk_volumes.reservation.principal = principal\n diskinfo = mesos_pb2.Resource.DiskInfo()\n if k == 1:\n diskinfo.persistence.id = task_id\n else:\n diskinfo.persistence.id = task_id + \"-volume-\" + str(k)\n diskinfo.persistence.principal = principal\n diskinfo.volume.mode = 1 # read-write\n diskinfo.volume.container_path = 'volume-'+str(k)\n if exclusive == 0:\n if v[0] != AGENTDIR:\n diskinfo.source.type = 1\n diskinfo.source.path.root = v[0]\n else:\n disk_volumes.scalar.value = mount_disk\n diskinfo.source.type = 2\n diskinfo.source.mount.root = v[0]\n disk_volumes.disk.MergeFrom(diskinfo)\n task_resources += [disk_volumes]\n\n if None not in ports:\n ports_resources = mesos_pb2.Resource()\n ports_resources.name = 'ports'\n ports_resources.type = mesos_pb2.Value.RANGES\n ports_resources.role = role\n ports_resources.reservation.principal = principal\n for port in ports:\n if isinstance(port,int):\n port_range = ports_resources.ranges.range.add()\n port_range.begin = port\n port_range.end = port\n else:\n ports_list = list(port)\n for port_list in ports_list:\n port_range = ports_resources.ranges.range.add()\n port_range.begin = port_list\n port_range.end = port_list\n reserve_resources += [ports_resources]\n task_resources += [ports_resources]\n\n return reserve_resources, volumes, task_resources\n\n\ndef is_terminal(state):\n \"\"\"Return true if the task reached terminal state.\"\"\"\n return state in [\n mesos_pb2.TASK_FINISHED,\n mesos_pb2.TASK_KILLED,\n mesos_pb2.TASK_FAILED,\n mesos_pb2.TASK_LOST]\n\n#task {'task_id': ,'action':'complete restore'/'MS','state':'wait'/'start'}\ndef get_mini_task(task_id, action, state = 'wait'):\n return dict(task_id=task_id,\n action=action,\n state=state)\n\n#useless_resource {'task_id': ,'hostname': 'cpus': 'mem'}\ndef get_useless_resource(task_id, hostname, cpus, mem, port):\n return dict(task_id=task_id,\n hostname=hostname,\n cpus=cpus,\n mem=mem,\n port=port)\n\ndef get_destroy(resources):\n destroy = mesos_pb2.Offer.Operation()\n destroy.type = 5 # destroy persistence\n destroy.destroy.volumes.extend(resources)\n return destroy\n\ndef get_unreserve(resources):\n unreserve = mesos_pb2.Offer.Operation()\n unreserve.type = 3\n unreserve.unreserve.resources.extend(resources)\n return unreserve\n\ndef get_resource(name, type, value, role='*'):\n resource = mesos_pb2.Resource()\n resource.name = name\n resource.type = type\n resource.role = role\n resource.scalar.value = value\n return resource\n\ndef get_port_resource(role, ports):\n ports_resources = mesos_pb2.Resource()\n ports_resources.name = 'ports'\n ports_resources.type = mesos_pb2.Value.RANGES\n ports_resources.role = role\n for port in ports:\n if isinstance(port, int):\n port_range = ports_resources.ranges.range.add()\n port_range.begin = port\n port_range.end = port\n else:\n ports_list = list(port)\n for port_list in ports_list:\n port_range = ports_resources.ranges.range.add()\n port_range.begin = port_list\n port_range.end = port_list\n return ports_resources\n\n#从list1里边去掉list2的内容\ndef removelist(list1, list2):\n for value in list2:\n if value in list1:\n list1.remove(value)\n\ndef get_port(cluster, ports):\n if not cluster.first_port:\n task_port = random.choice(list(ports))\n cluster.first_port = task_port\n elif cluster.first_port in list(ports):\n task_port = cluster.first_port\n else:\n task_port = random.choice(list(ports))\n return task_port\n\ndef get_ports(cluster,ports):\n gr_port = []\n if len(cluster.first_port) == 0:\n gr_port.append(random.choice(list(ports)))\n want_port = int(gr_port[0])+1\n if want_port in ports:\n gr_port.append(want_port)\n else:\n gr_port = random.sample(list(ports), 2)\n cluster.first_port= gr_port\n elif len(cluster.first_port) != 2:\n raise ValueError(\"The group %s needs two ports.\" %cluster.cluster_name)\n else:\n for port in cluster.first_port:\n if port in ports:\n gr_port.append(port)\n else:\n gr_port.append(random.choice(list(ports)))\n task_port = (int(gr_port[0]),int(gr_port[1]))\n return task_port\n\ndef get_new_master(cluster):\n new_master_uuid = \" \"\n new_master = cluster.master_taskid\n for taskid,task in cluster.tasks.items():\n if task.nodestate == \"RUNNING\":\n result = cmp(task.uuid,new_master_uuid)\n if result > 0:\n new_master_uuid = str(task.uuid)\n new_master = taskid\n cluster.tasks[new_master].identity = \"master\"\n return new_master\n\n\n\n","sub_path":"hyaline/scheduler/launcher.py","file_name":"launcher.py","file_ext":"py","file_size_in_byte":130160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"257850977","text":"import os\nimport sqlite3\nimport progressbar\nimport subprocess\nimport zipfile, zlib\nimport csv\nimport pandas as pd\nimport numpy\nimport glob\n\n\n\nclass orm_sqlite(object):\n \"\"\"\n An object for easy interaction with an SQLite database\n\n Primarily meant for a db holding text articles\n\n \"\"\"\n def __init__(self, file_name):\n super(dbORM, self).__init__()\n self.__name__ = file_name\n\n\n def connect(self, check_packed=True):\n \"\"\"Connect to a database.\n Creates connection object (con) and cursor (c)\n\n \"\"\"\n self.con = sqlite3.connect(self.__name__)\n self.c = self.con.cursor()\n\n def close(self):\n \"\"\"Close database connection\"\"\"\n self.c.close()\n\n def execute(self, command, commit=False):\n \"\"\"Execute a command\n\n \"\"\"\n self.c.execute(command)\n if commit:\n self.commit()\n\n def commit(self):\n \"\"\"Commit to database\n\n \"\"\"\n self.con.commit()\n\n def fetch(self, what = \"all\", size=None):\n \"\"\"Fetch data from database.\n What can be \"ALL\", \"MANY\", or \"ONE\". Defaults to ALL\n\n \"\"\"\n if what.upper() == \"ALL\":\n return self.c.fetchall()\n elif what.upper() == \"MANY\":\n if size is not None:\n return self.c.fetchmany(size)\n else:\n return self.c.fetchmany()\n elif what.upper() == \"ONE\":\n return self.c.fetchone()\n else:\n print(\"what must be element of 'all', 'many' or 'one'.\")\n\n def drop_table(self, table_name):\n \"\"\"\n Shorthand for dropping a table.\n Be careful with this.\n\n \"\"\"\n cmd=\"DROP TABLE {}\".format(table_name)\n self.execute(cmd)\n self.commit()\n\n\n \"\"\"\n Miscellaneous functions\n\n \"\"\"\n\n def read_text(self, file):\n \"\"\"\n Read a text file from disk\n\n \"\"\"\n file_con = open(file, 'r')\n text = file_con.read()\n return str(text)\n\n\n \"\"\"\n Adding new tables\n\n \"\"\"\n\n def create_table(self, table, col_names, col_types=None, col_constraints=None, other_args=None, overwrite=False):\n \"\"\"\n Create a table in the database\n\n table (name) must be provided\n col_names must be provided\n col_types defaults to TXT\n col_constraints defaults to \"\"\n other_args to add additional arguments\n\n Example usage:\n\n db.create_table('Sentiments', col_names = [\"File\", \"Paragraph\", \"Text\", \"Sentiment\"], col_types = [\"TXT\", \"INT\", \"TXT\", \"INT\"], other_args = \"PRIMARY KEY (File, Paragraph)\")\n\n \"\"\"\n if overwrite and table in self.list_tables():\n self.drop_table(table)\n ncols = len(col_names)\n if col_types is None:\n col_types = list(numpy.repeat(\"TXT\", ncols))\n if col_constraints is None:\n col_constraints = list(numpy.repeat(\"\", ncols))\n query = [' '.join([cn, cp, cc]) for cn, cp, cc in zip(col_names, col_types, col_constraints)]\n query = \"CREATE TABLE {} (\".format(table) + ', '.join(query)\n if other_args is not None:\n query = ', '.join([query, other_args])\n query = query + \")\"\n self.execute(query)\n self.commit()\n\n def insert_pandas(self, table, df, overwrite=False):\n \"\"\"Inserts Pandas DataFrame object to a new or existing table\n\n Use create_table() first if column flags or so need to be set.\n\n If overwrite is True, overwrites existing table\n \"\"\"\n if overwrite:\n try:\n self.drop_table(table)\n except:\n print(\"No existing table found\")\n df.to_sql(table, self.con, if_exists='append', index = False)\n\n def insert_text_files(self, table, files_path, overwrite=False):\n \"\"\"Adds all txt files in given directory into a new table\n in the database, using the file name as ID\n\n table = name of new table where to add the files\n files_path = directory with text files\n\n Returns nothing\n\n \"\"\"\n cols=[\"File\", \"Text\"]\n p=files_path\n if overwrite:\n try:\n self.drop_table(table)\n except:\n print(\"No existing table found\")\n prim_key=\"PRIMARY KEY (File)\"\n self.create_table(table=table, col_names=cols, other_args=prim_key)\n all_files=os.listdir(p)\n txt_files=[(f,os.path.join(p,f)) for f in all_files if \".TXT\" in f.upper()]\n df = pd.DataFrame([(f[0], self.read_text(f[1])) for f in txt_files], columns=cols)\n self.insert_pandas(table, df)\n\n\n def insert_csv(self, table, csv_file, overwrite=False):\n \"\"\"Add CSV file to a table in the database\n\n Use create_table() first if column flags or so need to be set.\n \"\"\"\n df = pd.read_csv(csv_file)\n self.insert_pandas(table, df, overwrite=overwrite)\n\n\n \"\"\"\n Selecting data\n\n \"\"\"\n\n def select(self, table, fetch=None, arguments=None):\n \"\"\"Select query to table\n\n What defaults to all ('*')\n\n Fetch is optional, can be either 'all', 'first' or 'many'\n\n Optional arguments can be passed via `arguments`\n\n Returns nothing if fetch is None (default)\n \"\"\"\n query = 'SELECT * FROM {}'.format(table)\n if arguments is not None:\n query = query + \" \" + arguments\n self.execute(query)\n if fetch is not None:\n res = self.fetch(fetch)\n return res\n\n def select_query(self, query):\n \"\"\"Send full select query to database and return results\"\"\"\n self.execute(query)\n result = self.fetch()\n return result\n\n def select_where(self, table, condition):\n \"\"\"Select * where condition is met\"\"\"\n query = 'SELECT * FROM {} WHERE {}'.format(table, condition)\n self.execute(query)\n result = self.fetch()\n return result\n\n def select_like(self, table, where, like):\n \"\"\"Select entire table where a specific column contains text\"\"\"\n cmd=\"SELECT * FROM {} WHERE {} LIKE '%{}%'\".format(table, where, like)\n self.execute(cmd)\n result = self.fetch()\n return result\n\n def select_articles(self, like):\n \"\"\"Get articles where text contains like\n Shorthand for select_like\n \"\"\"\n result = self.select_like(table='Documents', where='Text', like=like)\n return result\n\n def get_pandas(self, table, columns=\"*\", arguments=None, chunksize=None):\n \"\"\"Return a database table as pandas dataframe\n\n Optional arguments can be passed via `arguments`\n \"\"\"\n if type(columns) is list: columns=','.join(columns)\n query = \"SELECT {} FROM {}\".format(columns, table)\n if arguments is not None:\n query = query + \" \" + arguments\n df = pd.read_sql_query(query, self.con, chunksize=chunksize)\n return df\n\n \"\"\"\n Database info / statistics\n\n \"\"\"\n\n def list_tables(self):\n \"\"\"List tables in database\n\n Returns list\n \"\"\"\n query=\"SELECT name FROM sqlite_master WHERE type='table';\"\n self.execute(query)\n output = self.fetch()\n tables = [t[0] for t in output]\n return tables\n\n def list_columns(self, table):\n \"\"\"List columns in table\n\n \"\"\"\n query='PRAGMA TABLE_INFO({})'.format(table)\n self.execute(query)\n output = self.fetch()\n columns = [tup[1] for tup in output]\n return columns\n\n def pragma(self, table):\n \"\"\"Full pragma output for table\n\n Prints table with column information\n (id, name, type, notnull, default_value, primary_key)\n\n Returns nothing\n \"\"\"\n query='PRAGMA TABLE_INFO({})'.format(table)\n self.execute(query)\n output = self.fetch()\n info = [list(tup) for tup in output]\n print(\"\\nColumn Info:\\n{:10s}{:25s}{:10s}{:10s}{:12s}{:10s}\"\\\n .format(\"ID\", \"Name\", \"Type\", \"NotNull\", \"DefaultVal\", \"PrimaryKey\"))\n for col in info:\n print_text=tuple(str(t) for t in col)\n print('{:10s}{:25s}{:10s}{:10s}{:12s}{:10s}'.format(*print_text))\n\n def column_info(self, table):\n \"\"\"Summary information for columns in table\n\n Prints table with some pragma information plus actual not null count\n\n Returns nothing\n \"\"\"\n query = 'PRAGMA TABLE_INFO({})'.format(table)\n self.execute(query)\n info = self.fetch()\n info = [list(i)[0:3] for i in info] # Only ID, Name, Type\n columns = [i[1] for i in info] # Extract columns\n for i, col in enumerate(columns):\n count = self.count_notnull(col, table)\n info[i].append(count)\n print(\"\\nColumn Info:\\n{:10s}{:25s}{:10s}{:10s}\"\\\n .format(\"ID\", \"Name\", \"Type\", \"NotNull\"))\n for col in info:\n print_text=tuple(str(t) for t in col)\n print('{:10s}{:25s}{:10s}{:10s}'.format(*print_text))\n\n def count(self, column, table):\n \"\"\"Count number of rows\n\n returns int\n\n \"\"\"\n query = \"SELECT COUNT({}) FROM {}\".format(column, table)\n self.execute(query)\n count = self.fetch()\n return int(count[0][0])\n\n def count_where(self, column, table, condition):\n \"\"\"count rows where condition is met\"\"\"\n query = \"SELECT COUNT({}) FROM {} WHERE {}\".format(column, table, condition)\n self.execute(query)\n count = self.fetch()\n return int(count[0][0])\n\n def count_distinct(self, column, table):\n \"\"\"Count distinct entries\n\n Returns int\n \"\"\"\n query = \"SELECT COUNT(DISTINCT {}) FROM {}\".format(column, table)\n self.execute(query)\n count = self.fetch()\n return int(count[0][0])\n\n def count_notnull(self, what, where):\n \"\"\"Count non-null entries in column\n\n Returns int\n \"\"\"\n query='SELECT COUNT({0}) FROM {1} WHERE {0} IS NOT NULL'.format(what, where)\n self.execute(query)\n count = self.fetch()\n return int(count[0][0])\n\n def count_like(self, what, where, like):\n \"\"\"Count number of rows containing text (`like`)\n\n Returns int\n \"\"\"\n cmd=\"SELECT COUNT({}) FROM {} WHERE {} LIKE '%{}%'\".format(what, where, what, like)\n self.execute(cmd)\n count =self.fetch()\n return count[0][0]\n\n def count_articles(self, like):\n \"\"\"Count articles matching text (`like`)\n\n Shorthand function for count_like() with what='Text' and\n where='documents'\n\n Returns int\n \"\"\"\n result = self.count_like(like=like, what=\"Text\", where=\"Documents\")\n return result\n","sub_path":"orm_sqlite.py","file_name":"orm_sqlite.py","file_ext":"py","file_size_in_byte":10772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"645777916","text":"import cv2\r\nimport numpy as np\r\n\r\n#color verde\r\nrangoMin1 = [0,65,75]\r\nrangoMax1 = [12, 255, 255]\r\nrangoMin2 = [240,65,75]\r\nrangoMax2 = [256, 255, 255]\r\n\r\n\r\n\r\nimg = cv2.imread('img_b1.png',1)\r\n\r\n#convertimos la imagen de entarda a hsv\r\nhsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)\r\ncv2.imshow(\"hsv1\",hsv)\r\n\r\n#creamos mascaras para los rangos de colores\r\nmascaraRojo1 = cv2.inRange(hsv,np.array(rangoMin1),np.array(rangoMax1))\r\nmascaraRojo2 = cv2.inRange(hsv,np.array(rangoMin2),np.array(rangoMax2))\r\nmascara = cv2.add(mascaraRojo1,mascaraRojo2)\r\n\r\n#mascara = cv2.inRange(hsv,np.array(rangoMin),np.array(rangoMax))\r\ncv2.imshow(\"mascara\",mascara)\r\n\r\n#aplicamos el suavizado Gaussiano para eliminar el ruido sobre las mascaras\r\ngauss = cv2.GaussianBlur(mascara,(11,11),0)#11, 11, 15\r\ncv2.imshow(\"gaus\",gauss)\r\n\r\n#ecualizar una imagen\r\n#--------------------------------------------\r\nimgE = cv2.equalizeHist(gauss)\r\ncv2.imshow(\"imgE - equalizado\",imgE)\r\n#--------------------------------------------\r\n\r\n#Calcular el detector de bordes Canny con OpenCV\r\ncanny = cv2.Canny(imgE,50,360) #50-350, 50-370, 50-355\r\ncv2.imshow(\"canny\",canny)\r\n\r\ncontornos,hier = cv2.findContours(canny.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)\r\nprint(len(contornos))\r\n\r\nareas = [cv2.contourArea(c) for c in contornos]\r\n\r\ni=0\r\nfor extension in areas:\r\n if extension > 1000:\r\n actual = contornos[i]\r\n approx = cv2.approxPolyDP(actual,0.05*cv2.arcLength(actual,True),True)\r\n #if len(approx)>=3:\r\n cv2.drawContours(img,[actual],0,(0,0,0),2)\r\n cv2.drawContours(mascara,[actual],0,(0,0,0),2)\r\n i+=1\r\n\r\ncv2.imshow('ImagenOriginal',img)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n\r\n\r\n\r\n\r\n","sub_path":"practica2_encontrar_triangulo_marcarlo/tets_color_rojo.py","file_name":"tets_color_rojo.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"144999417","text":"\"\"\"A collection of utilities for handling (mainly subsurface ocean) observations\"\"\"\n\nimport copy\nimport numpy as np\n\ndef t48tot68(t48):\n \"\"\"Convert from IPTS-48 to IPTS-68 temperature scales,\n as specified in the CF Standard Name information for\n sea_water_temperature\n http://cfconventions.org/Data/cf-standard-names/27/build/cf-standard-name-table.html\n \n temperatures are in degrees C\"\"\"\n\n t68 = t48 - 4.4e-6 * t48 * (100 - t48)\n\n return t68\n\ndef t68tot90(t68):\n \"\"\"Convert from IPTS-68 to ITS-90 temperature scales,\n as specified in the CF Standard Name information for\n sea_water_temperature\n http://cfconventions.org/Data/cf-standard-names/27/build/cf-standard-name-table.html\n \n temperatures are in degrees C\"\"\"\n\n t90 = 0.99976 * t68\n\n return t90\n\ndef pottem(T, S, dStart, dEnd=0.0, pressure=False, lat=0.0):\n \"\"\"Calculate the temperature of water if it is moved from\n depth dStart to dEnd.\n\n t: initial temperature of the water.\n s: salinity of the water.\n dStart: depth that the parcel of water starts at.\n dEnd: depth that the parcel of water ends up at.\n pressure: set to true if dStart and dEnd are pressures rather than depths.\n lat: if pressure if False, latitude should also be specified.\"\"\"\n\n if pressure:\n P0 = dStart\n P1 = dEnd\n else:\n P0 = depth_to_pressure(dStart, lat)\n P1 = depth_to_pressure(dEnd, lat)\n\n assert P0 <= 20000 and P1 <= 20000 and P0 >= 0 and P1 >= 0, 'Pressure out of range'\n\n dpp = 1.0e0\n\n if P1 >= P0:\n DP = dpp\n else:\n DP = -dpp\n\n P = P0\n DS = S - 35e0\n\n TB = (T-((((-2.1687e-16*T+1.8676e-14)*T-4.6206e-13)*P0 \n + ((2.7759e-12*T-1.1351e-10)*DS+((-5.4481e-14*T \n + 8.733e-12)*T-6.7795e-10)*T+1.8741e-8))*P0 \n + (-4.2393e-8*T+1.8932e-6)*DS \n + ((6.6228e-10*T-6.836e-8)*T+8.5258e-6)*T+3.5803e-5)*DP)\n\n test = 1\n\n while test > 0.0:\n TA = (TB+2.0e0*((((-2.1687e-16*T+1.8676e-14)*T-4.6206e-13)*P \n + ((2.7759e-12*T-1.1351e-10)*DS+((-5.4481e-14*T \n + 8.733e-12)*T-6.7795e-10)*T+1.8741e-8))*P \n + (-4.2393e-8*T+1.8932e-6)*DS \n + ((6.6228e-10*T-6.836e-8)*T+8.5258e-6)*T+3.5803e-5)*DP)\n\n P = P + DP\n TB = T\n T = TA\n test = (P-P1)*(P-DP-P1)\n\n POTTEM = ((P1-P+DP)*T+(P-P1)*TB)/DP\n\n return POTTEM\n\ndef _depth_to_pressure_scalar(Z, LAT):\n \"\"\"Convert a depth to a pressure.\n\n Based on FNZTOP from the NEMOQC source code.\n\n z: the depth for conversion.\n lat: latitude.\n\n Values have to be scalars.\"\"\"\n\n #\n # CHECK VALUE fnztop = 10302.423165 - CRAY 64-BIT\n # = 10302.4231650052 - IEEE 64 BIT\n # FOR Z=10000M, LAT=30.0\n #\n\n # Definitions\n PI = 3.14159265358979323846e0\n RADIAN = PI / 180e0\n G1 = 9.780318e0\n G2 = 9.780318e0 * (5.3024e-3 - 5.9e-6 * 4.0e0)\n G3 = -9.780318e0 * 5.9e-6 * 4.0e0\n S = 35.0e0\n C1P5 = 1.5e0\n\n AL = 1e5 / (9.99842594e2+8.24493e-1*S \n -5.72466e-3*S**C1P5 + 4.8314e-4*S**2)\n RK = 1.965221e4 + 5.46746e1*S + 7.944e-2*S**C1P5\n RA = 3.239908e0 + 2.2838e-3*S + 1.91075e-4*S**C1P5\n RB = 8.50935e-5 - 9.9348e-7*S\n DD = np.sqrt(RA*RA-4.0e0*RK*RB)\n C1 = 0.5e0/RB\n C2 = RA/RK\n C3 = RB/RK\n C4 = RA/(2.0e0*RB*DD)\n C5 = 2.0e0*RB/(RA-DD)\n C6 = 2.0e0*RB/(RA+DD)\n C7 = 0.5e0*2.226e-6\n\n MLOOP=200\n MCONV=5\n EPS=1.0e-1\n\n PA = np.zeros(MCONV)\n\n P = Z\n IA=0\n EP=0.0\n\n for I in range(1, MLOOP + 1):\n\n X = np.sin(RADIAN*LAT)**2\n GS = (G3*X+G2)*X+G1\n\n PTEMP = P*1.0e-1\n\n R1=(AL*(PTEMP-C1*np.log((C3*PTEMP+C2)*PTEMP+1.0e0) + \n C4*np.log((1.0e0 + C5*PTEMP)/(1.0e0+C6*PTEMP))))\n\n ZZ = R1/(GS+C7*P)\n\n # ZERRO ERROR\n\n if (Z == ZZ): return P\n\n EE = Z - ZZ\n EA = np.abs(EE)\n\n # SAVE NEW BEST VALUE\n if (IA == 0 or EA < EP):\n\n IA = 1\n EP = EA\n PA[IA - 1] = P\n\n # LOOP FOR LIMIT CYCLE\n elif (EA == EP):\n\n for J in range(1, IA + 1):\n if (P == PA[J - 1]): return P\n \n if (IA < MCONV):\n IA = IA + 1\n PA[IA - 1] = P\n \n # CORRECT P AND LOOP\n\n P = P+EE\n\n assert (EA <= EPS), 'Iteration has not converged'\n\n P = PA[IA - 1]\n\n return P\n \ndef depth_to_pressure(z, lat):\n \"\"\"Converts depths to pressures.\n \n z: scalar or numpy array of depth (m).\n lat: scalar or numpy array of latitude (deg).\"\"\"\n\n assert np.array(lat).size > 0 and np.array(z).size > 0, 'No value provided for z or lat'\n\n # Rather inelegant way of getting this to work - \n # TODO : rework this.\n if np.array(lat).size == 1 and np.array(z).size == 1:\n p = _depth_to_pressure_scalar(z, lat)\n elif np.array(lat).size > 1 and np.array(z).size == 1:\n p = np.zeros(len(lat))\n for i, l in enumerate(lat):\n p[i] = _depth_to_pressure_scalar(z, l)\n elif np.array(lat).size == 1 and np.array(z).size > 1: \n p = np.zeros(len(z))\n for i, d in enumerate(z):\n p[i] = _depth_to_pressure_scalar(d, lat)\n else:\n assert len(lat) == len(z), 'Number of lats does not match the number of depths'\n p = np.zeros(len(z))\n for i, d in enumerate(z):\n p[i] = depth_to_pressure(d, lat[i])\n\n return p\n\ndef pressure_to_depth(p, lat):\n\n \"\"\"Function to convert from ocean pressure to depth. Algorithm is\n taken from Ops_OcnPresToDepth.f90 which forms part of the \n NEMOQC source code (correct as of revision 2468 of the trunk).\n\n Inputs:\n p - Pressure scalar in decibars.\n lat - Latitude in degrees.\n\n Outputs:\n The depth (in metres) corresponding to the input pressures are returned.\n\n This routine will work with scalars or numpy arrays.\n \"\"\"\n\n # Details of the algorithm from Ops_OcnPresToDepth.f90:\n # ---------\n # depth in meters from pressure in decibars using\n # Saunder's and Fofonoff's method.\n # deep-sea res., 1976,23,109-111.\n # formula refitted for 1980 equation of state\n\n # checkvalue: depth=9712.653 M for P=10000 decibars,\n # latitude=30 deg\n\n # above for standard ocean: T=0 deg. celcius;\n # S=35 (PSS-78)\n\n # gr=gravity variation with latitude: Anon (1970)\n # Bulletin Geodesique\n\n # Also ...\n #\n # Seawater Applications July 2002\n\n # Sea-Bird uses the formula in UNESCO Technical Papers in \n # Marine Science No. 44. This is an empirical formula that \n # takes compressibility (that is, density) into account. \n # An ocean water\n # column at 0 deg C (t = 0) and 35 PSU (s = 35) is assumed. \n\n # The gravity variation with latitude and pressure is computed as: \n\n # g (m/sec2) = 9.780318 * [ 1.0 + ( 5.2788x10 -3 + 2.36x10 -5 * x) * x ] + 1.092x10 -6 * p \n\n # where \n # x = [sin (latitude / 57.29578) ] 2 \n # p = pressure (decibars) \n\n # Then, depth is calculated from pressure: \n\n # depth (meters) = [(((-1.82x10 -15 * p + 2.279x10 -10 ) * p - 2.2512x10 -5 ) * p + 9.72659) * p] / g \n\n # where \n # p = pressure (decibars) \n # g = gravity (m/sec2) \n # ---------\n\n X = np.sin( lat / 57.29578e0 )\n\n X = X**2\n\n Gr = 9.780318e0 * ( 1.0e0 + ( 5.2788e-3 + 2.36e-5 * X ) * X ) + 1.092e-6 * p\n\n Depth = ( ( ( -1.82e-15 * p + 2.279e-10 ) * p - 2.2512e-5 ) * p + 9.72659e0 ) * p\n\n Depth /= Gr\n\n return Depth\n\ndef density(t, s, l, latitude=None):\n \"\"\"Calculate the density/densities based on:\n t - potential temperature(s) in degC.\n s - salinity(s) in PSU.\n l - level(s) (either pressure or density) in m or db.\n latitude - only set if l contains depths (can be array or scalar) in deg.\n Code is ported from Ops_OceanRhoEOS25 from NEMOQC,\n which uses a 25 term expression given by McDougall et al (2003; JAOT 20, #5),\n which provides an accurate fit to the Feistel and Hagen (1995) equation of state.\n That code is in turn based on the UM routine in RHO_EOS25 (constants in STATE),\n but with salinity in PSU and density in kg m**-3, as in McDougall.\n\n Test values from McDougall et al (2005) are:\n t = 25C, s = 35psu, p = 2000 db => rho = 1031.654229 kg/m^2.\n 20 20 1000 1017.726743\n 12 40 8000 1062.928258\n\n This function is not properly tested for anything other than basic usage.\n \"\"\"\n\n # VALUES NEEDED IN THE CALCULATION.\n # Small constant.\n epsln = 1.E-20 \n\n # 25 coefficients in the realistic equation of state\n a0 = 9.99843699e+02\n a1 = 7.35212840e+00\n a2 = -5.45928211e-02\n a3 = 3.98476704e-04\n a4 = 2.96938239e+00\n a5 = -7.23268813e-03\n a6 = 2.12382341e-03\n a7 = 1.04004591e-02\n a8 = 1.03970529e-07\n a9 = 5.18761880e-06\n a10 = -3.24041825e-08\n a11 = -1.23869360e-11\n\n b0 = 1.00000000e+00\n b1 = 7.28606739e-03\n b2 = -4.60835542e-05\n b3 = 3.68390573e-07\n b4 = 1.80809186e-10\n b5 = 2.14691708e-03\n b6 = -9.27062484e-06\n b7 = -1.78343643e-10\n b8 = 4.76534122e-06\n b9 = 1.63410736e-09\n b10 = 5.30848875e-06\n b11 = -3.03175128e-16\n b12 = -1.27934137e-17\n\n # CONVERT DEPTH TO PRESSURE IF NECESSARY.\n if latitude is not None: \n p = depth_to_pressure(l, latitude)\n else:\n p = l\n\n # ERROR CHECKING. Disabled as does not work properly with \n # masked arrays.\n #assert np.count_nonzero(s <= 0.0) == 0, 'Negative salinity values detected'\n #assert np.count_nonzero(p < 0.0) == 0, 'Negative depths detected' \n\n # DENSITY CALCULATION.\n p1 = p\n t1 = t\n s1 = s\n t2 = t1 * t1\n sp5 = np.sqrt(s1)\n p1t1 = p1 * t1\n\n num = (a0 + t1*(a1 + t1*(a2+a3*t1) ) \n + s1*(a4 + a5*t1 + a6*s1) \n + p1*(a7 + a8*t2 + a9*s1 + p1*(a10+a11*t2)))\n\n den = (b0 + t1*(b1 + t1*(b2 + t1*(b3 + t1*b4))) \n + s1*(b5 + t1*(b6 + b7*t2) + sp5*(b8 + b9*t2)) \n + p1*(b10 + p1t1*(b11*t2 + b12*p1)))\n\n denr = 1.0/(epsln+den)\n\n rho = num * denr\n\n return rho\n","sub_path":"util/obs_utils.py","file_name":"obs_utils.py","file_ext":"py","file_size_in_byte":10546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"612360429","text":"from flask import Flask, request\n#from flask import Flask, render_template, request, redirect, url_for, send_from_directory,jsonify\n\n\n\napp = Flask(__name__)\n\n@app.route(\"/communicate\", methods=['POST'])\ndef communicate():\n some_json=request.get_json()\n #sessionid = some_json['session']\n #text = some_json['text'] \n response = \"YOLO\" \n return str(response)\n\nif __name__=='__main__':\n app.run(debug=True)\n\n\n\"\"\"\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n \n return render_template('index.html')\n\n\nif __name__ == '__main__':\n app.run(host=0.0.0.0, port=8080, debug=True)\n\n\"\"\"","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"509166569","text":"# K-Means Clustering\n\n# Importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ndataset = pd.read_csv(\"Mall_Customers.csv\")\nX = dataset.iloc[:, [3,4]].values\n\n#Using the elbow method to determine clusters\nfrom sklearn.cluster import KMeans\nwcss = []\nfor i in range(1, 11):\n kmeans = KMeans(n_clusters=i, init='k-means++', max_iter=300, n_init=10, random_state=0)\n kmeans.fit(X)\n wcss.append(kmeans.inertia_)\n\nplt.plot(range(1, 11), wcss)\nplt.title(\"K-Means\")\nplt.xlabel(\"Number of Clusters\")\nplt.ylabel(\"WCSS\")\nplt.show() #the elbow at 5 tells us the optimal number\n\n#Applying K-Means to mall dataset\nkmeans = KMeans(n_clusters=5, init='k-means++', max_iter=300, n_init=10, random_state=0)\nY_kmeans = kmeans.fit_predict(X)\n\n#Visualizing the Cluster\nplt.scatter(X[Y_kmeans == 0, 0], X[Y_kmeans == 0, 1], s = 100, color='red', label='Careful')\nplt.scatter(X[Y_kmeans == 1, 0], X[Y_kmeans == 1, 1], s = 100, color='blue', label='Standard')\nplt.scatter(X[Y_kmeans == 2, 0], X[Y_kmeans == 2, 1], s = 100, color='green', label='Target')\nplt.scatter(X[Y_kmeans == 3, 0], X[Y_kmeans == 3, 1], s = 100, color='yellow', label='Careless')\nplt.scatter(X[Y_kmeans == 4, 0], X[Y_kmeans == 4, 1], s = 100, color='grey', label='Sensible')\nplt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s = 300, color='magenta', label='Centroids')\nplt.title('Clusters of Clients')\nplt.xlabel('Annual Income (k$)')\nplt.ylabel('Spending Score (1-100)')\nplt.legend()\nplt.show()","sub_path":"4.1 K-Means Clustering/kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"43534641","text":"# Copyright (C) 2018 Google Inc.\n# Licensed under http://www.apache.org/licenses/LICENSE-2.0 \n\"\"\"\nCreate missing Evidence Admins\n\nCreate Date: 2018-06-05 09:00:10.586460\n\"\"\"\n# disable Invalid constant name pylint warning for mandatory Alembic variables.\n# pylint: disable=invalid-name\n\nfrom alembic import op\nfrom sqlalchemy import text\n\nfrom ggrc.migrations import utils\nfrom ggrc.migrations.utils.migrator import get_migration_user_id\n\n# revision identifiers, used by Alembic.\nrevision = 'ad7e10f2a917'\ndown_revision = 'b1dbfad3bbad'\n\n\ndef get_evidence_admin_role_id(connection):\n \"\"\"Get evidence admin role id\"\"\"\n sql = \"\"\"\n SELECT id FROM access_control_roles acr\n WHERE acr.name = 'Admin' AND acr.object_type = 'Evidence'\n \"\"\"\n return connection.execute(text(sql)).fetchone()[0]\n\n\ndef create_evid_temporary_table():\n \"\"\"Tmp table to store evidence.id without Admins\"\"\"\n op.execute(\"SET AUTOCOMMIT = 1\")\n sql = \"\"\"\n CREATE TEMPORARY TABLE evidence_wo_admins (\n id int(11) NOT NULL\n )\n \"\"\"\n op.execute(sql)\n\n\ndef save_evidence_no_admins():\n \"\"\"Store evidence w/o Admins ids to temp_table evidence_wo_admins\"\"\"\n sql = \"\"\"\n INSERT INTO evidence_wo_admins (id)\n SELECT e.id FROM evidence e\n LEFT OUTER JOIN(\n SELECT DISTINCT(acl.object_id)\n FROM access_control_list acl\n JOIN access_control_roles acr ON acr.id = acl.ac_role_id\n AND acr.object_type = 'Evidence'\n AND acr.name = 'Admin'\n ) AS res ON res.object_id = e.id\n WHERE res.object_id IS NULL\n \"\"\"\n op.execute(sql)\n\n\ndef create_evidence_missing_admins(connection, migration_user_id,\n evidence_admin_role_id):\n \"\"\"Insert into access_control_list Evidence admin role\n\n If we have 'create' revision -> take modified_by_id as Admin\n else set current migration user as evidence Admin\n \"\"\"\n utils.create_missing_admins(connection, migration_user_id,\n evidence_admin_role_id,\n object_type=\"Evidence\",\n revision_action=\"created\",\n table_mame=\"evidence_wo_admins\")\n\n\ndef add_evidence_to_missing_revisions(connection):\n \"\"\"Add modified Evidence to objects_without_revisions to create revisions\"\"\"\n\n utils.add_to_missing_revisions(connection,\n table_with_id=\"evidence_wo_admins\",\n object_type=\"Evidence\")\n\n\ndef upgrade():\n \"\"\"Upgrade database schema and/or data, creating a new revision.\"\"\"\n connection = op.get_bind()\n migration_user_id = get_migration_user_id(connection)\n evidence_admin_role_id = get_evidence_admin_role_id(connection)\n create_evid_temporary_table()\n save_evidence_no_admins()\n create_evidence_missing_admins(connection, migration_user_id,\n evidence_admin_role_id)\n add_evidence_to_missing_revisions(connection)\n op.execute(\"DROP TABLE evidence_wo_admins\")\n op.execute(\"SET AUTOCOMMIT = 0\")\n\n\ndef downgrade():\n \"\"\"Downgrade database schema and/or data back to the previous revision.\"\"\"\n","sub_path":"src/ggrc/migrations/versions/20180605090010_ad7e10f2a917_create_missing_evidence_admins.py","file_name":"20180605090010_ad7e10f2a917_create_missing_evidence_admins.py","file_ext":"py","file_size_in_byte":3189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"404070829","text":"'''\r\nCreated on 7-Oct-2018\r\n@author: Pramey\r\n'''\r\nimport numpy as np \r\nfrom scipy.signal import convolve2d as conv2\r\nimport cv2\r\nimport scipy\r\nfrom scipy import signal\r\nfrom scipy import ndimage\r\nfrom scipy.signal import butter, lfilter\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.widgets import Slider\r\nfrom skimage.measure import compare_ssim as ssim\r\n\r\nblurred_img1 = cv2.imread('blurred_img1.jpg')\r\nblurred_img2 = cv2.imread('blurred_img2.jpg')\r\nblurred_img3 = cv2.imread('blurred_img3.jpg')\r\nblurred_img4 = cv2.imread('blurred_img4.jpg')\r\n\r\noriginal_img = cv2.imread('original_img.jpg')\r\n\r\nkernel1 = cv2.imread('kernel1.png',0)\r\nkernel2 = cv2.imread('kernel2.png',0)\r\nkernel3 = cv2.imread('kernel3.png',0)\r\nkernel4 = cv2.imread('kernel4.png',0)\r\n\r\ncropped_kernel1 = kernel1[25:55, 20:50]\r\ncropped_kernel2 = kernel2[15:45, 20:50]\r\ncropped_kernel3 = kernel3[15:45, 20:50]\r\ncropped_kernel4 = kernel4[20:50, 25:55]\r\n\r\npadded_array1 = np.zeros((1600, 1600, 3))\r\npadded_array1[0:800, 0:800, 0:3] = blurred_img1\r\npadded_array2 = np.zeros((1600, 1600, 3))\r\npadded_array2[0:800, 0:800, 0:3] = blurred_img2\r\npadded_array3 = np.zeros((1600, 1600, 3))\r\npadded_array3[0:800, 0:800, 0:3] = blurred_img3\r\npadded_array4 = np.zeros((1600, 1600, 3))\r\npadded_array4[0:800, 0:800, 0:3] = blurred_img4\r\n\r\nr1, g1, b1 = cv2.split(padded_array1)\r\nr2, g2, b2 = cv2.split(padded_array2)\r\nr3, g3, b3 = cv2.split(padded_array3)\r\nr4, g4, b4 = cv2.split(padded_array4)\r\n\r\ndef psnr(img1, img2):\r\n img1 = cv2.normalize(img1, None, alpha = 0 , beta = 1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)\r\n img2 = cv2.normalize(img2, None, alpha = 0 , beta = 1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)\r\n img1Y, img1Cr, img1Cb = cv2.split(cv2.cvtColor(img1.astype(np.float32), cv2.COLOR_BGR2YCrCb))\r\n img2Y, img2Cr, img2Cb = cv2.split(cv2.cvtColor(img2.astype(np.float32), cv2.COLOR_BGR2YCrCb))\r\n mse = np.mean((img1Y-img2Y)**2)\r\n \r\n max_val = np.max(img1Y)\r\n if mse == 0:\r\n return 100\r\n else: \r\n return 10*np.log10((max_val)**2/mse)\r\n\r\ndef ssim_i(img1, img2):\r\n img1 = cv2.normalize(img1, None, alpha = 0 , beta = 1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)\r\n img2 = cv2.normalize(img2, None, alpha = 0 , beta = 1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)\r\n s = ssim(img1, img2, multichannel = True)\r\n return np.mean(s)\r\n\r\ndef filter_Butterworth_LP(d,n,b):\r\n\r\n D = np.zeros((1600,1600))\r\n H = np.zeros((1600,1600))\r\n x = np.linspace(0, 1600, 1600)\r\n y = np.linspace(0, 1600, 1600)\r\n\r\n D = np.sqrt(x**2 + y**2)\r\n \r\n if b == 1:\r\n H = 1/(1 + (D/d)**(2*n))\r\n else:\r\n H = np.exp(-(D/np.sqrt(2)*d)**2)\r\n\r\n return H\r\n\r\n\r\ndef filter(r, g, b, kernel, type, init_val):\r\n r_fft = np.fft.fft2(r)\r\n g_fft = np.fft.fft2(g)\r\n b_fft = np.fft.fft2(b)\r\n \r\n kernel_fft = np.fft.fft2(kernel, (1600, 1600))\r\n p = 0\r\n \r\n if type == 0:\r\n p = 1\r\n elif type == 1:\r\n #K = np.median((np.abs(kernel_fft))**2)\r\n c = init_val\r\n p = (np.abs(kernel_fft))**2/((np.abs(kernel_fft))**2 + c)\r\n elif type == 2:\r\n p = filter_Butterworth_LP(150, 10, 1)\r\n elif type == 3:\r\n gamma = init_val\r\n Pxy = np.array([[0,-1,0], [-1, 4,-1],[0,-1,0]])\r\n Puv_fft = np.fft.fft2(Pxy,(1600,1600))\r\n Huv_conj = np.conjugate(kernel_fft)\r\n p = (kernel_fft*Huv_conj)/((np.abs(kernel_fft))**2 + gamma*(np.abs(Puv_fft))**2) \r\n \r\n deblurred_r = 255.0*np.fft.ifft2((r_fft/kernel_fft)*p).real\r\n deblurred_g = 255.0*np.fft.ifft2((g_fft/kernel_fft)*p).real\r\n deblurred_b = 255.0*np.fft.ifft2((b_fft/kernel_fft)*p).real\r\n \r\n clipped_deblurred_r = 2*deblurred_r.real/np.max(np.abs(deblurred_r.real))\r\n clipped_deblurred_g = 2*deblurred_g.real/np.max(np.abs(deblurred_g.real))\r\n clipped_deblurred_b = 2*deblurred_b.real/np.max(np.abs(deblurred_b.real))\r\n \r\n deblurred_img = np.clip(cv2.merge((clipped_deblurred_r, clipped_deblurred_g, clipped_deblurred_b)),0, 255)\r\n cropped_deblurred_img = deblurred_img[0:800,0:800, 0:3]\r\n print(\"SSIM:\", np.mean(ssim_i(original_img, cropped_deblurred_img)))\r\n print(\"PSNR:\" , psnr(original_img, cropped_deblurred_img))\r\n return cropped_deblurred_img\r\n#upto here the code has been written by me \r\n \r\n#the following code was derived from \r\n#http://www.math.buffalo.edu/~badzioch/MTH337/PT/PT-matplotlib_slider/PT-matplotlib_slider.html\r\ndef interactive_value():\r\n \r\n D_min = 100\r\n D_max = 10000\r\n D_init = 1500\r\n fig = plt.figure()\r\n plt.axis(\"off\")\r\n recovered_image = filter(b4, g4, r4, cropped_kernel4, 3, D_init )\r\n recovered_image_plot = plt.imshow(cv2.cvtColor(recovered_image.astype(np.float32), cv2.COLOR_BGR2RGB))\r\n \r\n slider_ax = plt.axes([0.1, 0.05, 0.8, 0.05])\r\n value_slider = Slider(slider_ax, 'value', D_min, D_max, valinit=D_init)\r\n\r\n\r\n def update(value):\r\n recovered_image = filter(b4, g4, r4, cropped_kernel4, 3, value )\r\n recovered_image_plot.set_data(recovered_image)\r\n fig.canvas.draw_idle()\r\n\r\n value_slider.on_changed(update)\r\n\r\n plt.show()\r\n\r\ninteractive_value() \r\n","sub_path":"deblur.py","file_name":"deblur.py","file_ext":"py","file_size_in_byte":5155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"463880435","text":"#Prompt: Write a Python function binom_product that takes integer arguments a and b and positive \n#integer argument n and returns the product of the coefficients in the expansion of (ax+by)n. \n\nimport math\ndef combination (n, k):\n return (math.factorial(n) / (math.factorial(k) * math.factorial(n - k)))\n\ndef binom_product(a,b,n):\n stupidIncrement = 0\n total = 1\n while stupidIncrement != n+1:\n total = total * combination(n,stupidIncrement) * a**(n - stupidIncrement) * b**(stupidIncrement)\n stupidIncrement += 1\n return total\n\nprint(round(binom_product(2,-1,3))) #should be 576\nprint(round(binom_product(1,3,4))) #should be 5668704\n","sub_path":"prompt12.py","file_name":"prompt12.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"252733994","text":"from turtle import Turtle\r\n\r\n\r\nclass Score(Turtle):\r\n def __init__(self, score_position):\r\n super().__init__()\r\n self.penup()\r\n self.score=0\r\n self.color(\"white\")\r\n self.goto(score_position)\r\n self.write(arg=f\"score {self.score}\", align=\"center\",font=(\"courier\",25,\"normal\"))\r\n\r\n\r\n self.hideturtle()\r\n\r\n def update(self):\r\n self.score+=1\r\n self.clear()\r\n self.write(arg=f\"score {self.score}\", align=\"center\",font=(\"courier\",25,\"normal\"))\r\n\r\n","sub_path":"score.py","file_name":"score.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"85846010","text":"import re\nimport pdb\nclass Solution:\n def myAtoi(self, str: str) -> int:\n str = str.strip()\n str = str.split()\n final = 0\n\n if str:\n result = re.findall('(^[\\+\\-0]*\\d*)\\D*', str[0])\n\n MAX_INT = 2147483647\n MIN_INT = -2147483648\n\n if result:\n try:\n final = int(''.join(result))\n if final > MAX_INT:\n final = MAX_INT\n elif final < MIN_INT:\n final = MIN_INT\n except:\n final = 0\n return final\n\nS = Solution().myAtoi(\"a\")\nprint(S)\n","sub_path":"08.py","file_name":"08.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"123610959","text":"import tensorflow as tf\n\n# 声明w1,w2两个变量\nw1 = tf.Variable(tf.random_normal([2,3],stddev=1,seed=1))\nw2 = tf.Variable(tf.random_normal([3,1],stddev=1,seed=1))\n\n# 将输入的特征向量定义为一个常量\nx = tf.constant([[0.7,0.9]])\n\n# 通过3.4.2小节描述前向传播算法获得神经网络的输出\na = tf.matmul(x,w1)\ny = tf.matmul(a,w2)\n\nwith tf.Session() as sess:\n # 初始化所有变量\n init_op = tf.global_variables_initializer()\n sess.run(init_op)\n print(sess.run(y))\n","sub_path":"《Tensorflow_实战Google深度学习框架》阅读笔记/code/34.1.py","file_name":"34.1.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"648635114","text":"import hidapi\nimport os\nimport sys\nfrom argparse import ArgumentParser\n\n_UNIFYING_DRIVER = 'logitech-djreceiver'\n_LOGITECH_VENDOR_ID = 0x046d\n\n_OFF = '\\x10\\x01\\t\\x19\\x00\\x00\\x00'\n_ON = '\\x10\\x01\\t\\x18\\x01\\x00\\x00'\n\n\n\ndef list_all_logitech_receivers():\n return list(hidapi.enumerate(vendor_id=_LOGITECH_VENDOR_ID, hid_driver=_UNIFYING_DRIVER))\n\n\ndef main(turn_on=False):\n all_recievers = list_all_logitech_receivers()\n if not all_recievers:\n print('Keyboard not found!! Could not continue')\n exit(2)\n\n id = 0\n if len(all_recievers) > 1:\n print('Multiple devices found')\n print('\\n'.join(map(str, all_recievers)))\n\n id = raw_input('> Select index of correct keyboard')\n\n rawdevice = all_recievers[0]\n handle = hidapi.open_path(rawdevice.path)\n if not handle:\n print('Could not open device %s. Could not continue' % rawdevice.path)\n\n hidapi.write(handle, _ON if turn_on else _OFF)\n\n\n\nif __name__ == '__main__':\n parser = ArgumentParser(description='Simple CLI app that turns off special options for F-keys on Logitech K400 Plus Wireless Touch keyboard')\n parser.add_argument('--on', help='Used to activate special functions for F-keys (media control, search etc.)\\\n \"By default it switches off this functionality', action=\"store_true\")\n args = parser.parse_args()\n\n euid = os.geteuid()\n if euid != 0:\n print('Script not started as root.')\n exit(1)\n\n main(args.on)\n","sub_path":"local/scripts/fn_k400.py","file_name":"fn_k400.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"88443857","text":"from abc import ABC, abstractmethod\nfrom pizza import NYStyleCheesePizza, NYStylePepperoniPizza, ChicagoStyleCheesePizza\n\nclass PizzaStore(ABC):\n def orderPizza(self, type):\n pizza = self.createPizza(type)\n pizza.prepare()\n pizza.bake()\n pizza.cut()\n pizza.box()\n return pizza\n @abstractmethod\n def createPizza(self, type):\n pass\n\nclass NYStylePizzaStore(PizzaStore):\n def createPizza(self, type):\n if type == \"cheese\":\n pizza = NYStyleCheesePizza()\n elif type == \"pepperoni\":\n pizza = NYStylePepperoniPizza()\n # elif type == \"clam\":\n # pizza = NYStyleClamPizza()\n # elif type == \"veggie\":\n # pizza = NYStyleVeggiePizza()\n else:\n raise ValueError(\"{} pizza not available\".format(type))\n return pizza\n\nclass ChicagoStylePizzaStore(PizzaStore):\n def createPizza(self, type):\n if type == \"cheese\":\n pizza = ChicagoStyleCheesePizza()\n # elif type == \"pepperoni\":\n # pizza = ChicagoStylePepperoniPizza()\n # elif type == \"clam\":\n # pizza = ChicagoStyleClamPizza()\n # elif type == \"veggie\":\n # pizza = ChicagoStyleVeggiePizza()\n else:\n raise ValueError(\"{} pizza not available\".format(type))\n return pizza\n","sub_path":"chapter_4_factory_pattern/factory_method_pattern/pizza_store.py","file_name":"pizza_store.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"600841236","text":"import argparse\nimport os.path\nimport re\n\nimport fire\nfrom mpi4py import MPI\n\ncomm = MPI.COMM_WORLD\n\n\ndef decide_root(filepath, root):\n m = re.match(r'^\\d+$', root)\n if m:\n root = int(m)\n elif root == 'auto':\n # root would be the first process that owns the file\n exists = comm.allgather(os.path.exists(filepath))\n\n # get the fisrt index that 'exists' is True\n ranks = [idx for idx, val in enumerate(exists) if val is True]\n\n if len(ranks) == 0:\n raise RuntimeError(\"No rank has the file '{}'\".format(filepath))\n\n root = ranks[0]\n else:\n raise ValueError(\"Invalid value for 'root' option.\")\n\n if root == comm.rank:\n if not os.path.exists(filepath):\n raise RuntimeError('Bcast root {} does not have the file \"{}\"'.format(\n root, filepath\n ))\n\n if not os.path.isfile(filepath):\n raise RuntimeError('\"{}\" is not a regular file.'.format(\n filepath\n ))\n\n return root\n\n\ndef parse_chunksize(s):\n if type(s) == int:\n assert s >= 0\n return s\n\n m = re.match(r'^(\\d+)([kmg]?)$', s, re.I)\n\n if m is None:\n raise RuntimeError('Cannot parse chunksize: \"{}\"'.format(s))\n\n digits = int(m.group(1))\n\n suffix = m.group(2).lower()\n\n if suffix == 'k':\n digits *= 1024\n elif suffix == 'm':\n digits *= 1024 * 1024\n elif suffix == 'g':\n digits == 1024 * 1024 * 1024\n else:\n assert False\n\n return digits\n\n\ndef send_file(filepath, chunksize):\n size = os.path.getsize(filepath)\n\n assert size >= 0\n\n print(\"Rank {} [Root] size={}\".format(comm.rank, size))\n comm.bcast(size, root=comm.rank)\n\n if size == 0:\n num_chunks = 0\n else:\n num_chunks = ((size - 1) // chunksize) + 1\n\n print(\"num_chunks = {}\".format(num_chunks))\n\n with open(filepath, 'rb') as f:\n for i in range(num_chunks):\n print(\"Sending Chunk #{}\".format(i+1))\n buf = f.read(chunksize)\n comm.Bcast(buf, root=comm.rank)\n\n\ndef recv_file(root, filepath, chunksize):\n size = None\n size = comm.bcast(size, root=root)\n print(\"Rank {} size={}\".format(comm.rank, size))\n\n if size == 0:\n num_chunks = 0\n else:\n num_chunks = ((size - 1) // chunksize) + 1\n\n print(\"\\t\\tnum_chunks = {}\".format(num_chunks))\n\n with open(filepath, 'wb') as f:\n for i in range(num_chunks):\n if i < num_chunks - 1:\n buf = bytearray(chunksize)\n else:\n buf = bytearray(size % chunksize)\n\n print(\"\\t\\tReceiving Chunk #{} from {}\".format(i+1, root))\n comm.Bcast(buf, root=root)\n f.write(buf)\n\n\ndef main(filepath, root='auto', chunksize='4m', rank_suffix=False):\n root = decide_root(filepath, root)\n assert type(root) == int\n assert 0 <= root and root < comm.size\n\n if rank_suffix:\n local_filename = '{}.{}'.format(filepath, comm.rank)\n\n chunksize = parse_chunksize(chunksize)\n\n if comm.rank == root:\n send_file(filepath, chunksize)\n else:\n recv_file(root, local_filename, chunksize)\n\n\nif __name__ == '__main__':\n fire.Fire(main)","sub_path":"mpicpy.py","file_name":"mpicpy.py","file_ext":"py","file_size_in_byte":3227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"237578462","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 10 00:16:01 2019\n\n@author: ranley\n\"\"\"\n\nimport sqlite3\n\nconn = sqlite3.connect(\"exercise2.sqlite\")\ncur = conn.cursor()\n\ncur.execute('DROP TABLE IF EXISTS Counts')\ncur.execute('''CREATE TABLE Counts (org TEXT, count INTEGER)''')\n\nfname = input('Enter file name: ')\nif (len(fname) < 1): fname = 'mbox-short.txt'\ndata = open(fname)\n\n \n\nfor line in data:\n if not line.startswith('From: '): \n continue\n \n pieces = line.split()\n org = pieces[1].split('@')[1]\n cur.execute('SELECT count FROM Counts WHERE org = ?', (org,))\n row = cur.fetchone()\n if row is None:\n cur.execute('INSERT INTO Counts (org, count) VALUES (?, 1)', (org,))\n else:\n cur.execute('UPDATE Counts SET count = count + 1 WHERE org = ?', (org, ))\n \n \nconn.commit()\ncommand = 'SELECT org,count FROM Counts ORDER BY count DESC LIMIT 10'\n \nfor row in cur.execute(command):\n print(str(row[0]), row[1])\n \ncur.close()","sub_path":"W02/exercise2.py","file_name":"exercise2.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"280381757","text":"# 기상청 날씨 데이터 수집하기\r\n# www.kma.go.kr\r\n# 기상청 날씨누리 -> 특보.예보 -> 동네예보\r\n# 기상청 날씨누리 -> 생활과산업 \r\n# -> 서비스 -> 인터넷 -> RSS\r\n\r\n# RSS : rich site summary\r\n# 사이트를 구독subscribe한 사용자에게 업데이트된 \r\n# 컨덴츠를 간편하게 배포하고자 만든 데이터 형식\r\n\r\n# RSS 구독 프로그램을 이용하면\r\n# 사이트를 방문하지 않고도 해당 사이트의 \r\n# 컨텐츠를 이용할 수 있다는 장점 존재\r\n\r\n# 중기예보 : 서울&경기 날씨 RSS\r\n# http://www.kma.go.kr/weather/forecast/mid-term-rss3.jsp?stnId=109\r\n\r\n# 동네예보 : 서울 강남구 논현1동\r\n# http://www.kma.go.kr/wid/queryDFSRSS.jsp?zone=1168052100\r\n\r\nfrom urllib.request import urlopen\r\nfrom html import unescape\r\nimport csv\r\n\r\n# 파이썬에서 xml문서를 처리하기 위한 모듈 (lxml)\r\nfrom xml.etree import ElementTree\r\n\r\n# 지정한 url에서 xml 문서를 읽어서 화면에 출력\r\nurl = 'http://www.kma.go.kr/weather/forecast/mid-term-rss3.jsp?stnId=109'\r\n\r\nf = urlopen(url)\r\ntext = f.read().decode('utf-8')\r\n# print(text)\r\n\r\n\r\n# 화면에 출력한 내용은\r\n# 파일(data/weather.xml)에 저장\r\nwith open('data/weather.xml', 'w', encoding='utf-8') as f:\r\n f.write(text)\r\n\r\n# xml parser를 이용해서 파일을 읽어오고\r\n# 메모리에 xml 계층구조를 만들기 위해\r\n# ElementTree 객체 생성\r\ntree = ElementTree.parse('data/weather.xml')\r\n\r\n# getroot 메서드로 XML 상위요소를 추출\r\nroot = tree.getroot()\r\n\r\n# findall 메서드로 추출할 데이터가 있는\r\n# 요소element를 지정함\r\nfor weather in root.findall(\r\n 'channel/item/description/body/location/data'):\r\n # find 메서드로 요소를 지정하고\r\n # text 속성으로 해당 데이터을 추출함\r\n tmef = weather.find('tmEf').text # 시간\r\n wf = weather.find('wf').text # 날씨정보\r\n tmn = weather.find('tmn').text # 최소온도\r\n tmx = weather.find('tmx').text # 최고온도\r\n\r\n print(tmef, wf, tmn, tmx)\r\n\r\n\r\n# 동네예보 출력\r\n# 파일로 저장 : data/town.xml\r\n# 날짜,시각,날씨,강수확률,기온,습도\r\nimport datetime\r\n\r\nurl = 'http://www.kma.go.kr/wid/queryDFSRSS.jsp?zone=1168052100'\r\n\r\nf = urlopen(url)\r\ntext = f.read().decode('utf-8')\r\n\r\nwith open('data/town.xml', 'w', encoding='utf-8') as f:\r\n f.write(text)\r\n\r\ntree = ElementTree.parse('data/town.xml')\r\nroot = tree.getroot()\r\n\r\nfor wtop in root.findall(\r\n 'channel/item/description'):\r\n\r\n # 먼저 날짜정보 추출\r\n day = wtop.find('header/tm').text[0:8]\r\n # 추출한 날짜 문자열을 날짜형으로 생성\r\n today = datetime.datetime.\\\r\n strptime(day, '%Y%m%d')\r\n \r\n for weather in wtop.findall('body/data'):\r\n # 경과일을 추출해서 날짜와 합산\r\n day = int(weather.find('day').text)\r\n myday = str(today + \\\r\n datetime.timedelta(days=day))[0:10]\r\n\r\n hour = weather.find('hour').text # 시각\r\n wf = weather.find('wfKor').text # 날씨\r\n pop = weather.find('pop').text # 강수\r\n temp = weather.find('temp').text # 기온\r\n reh = weather.find('reh').text # 습도\r\n\r\n print(myday, hour, wf, pop, temp, reh)\r\n\r\n\r\n# requests + bs4를 이용한 RSS 데이터 수집\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\n\r\nheaders = { 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36' }\r\n\r\nurl = 'http://www.kma.go.kr/wid/queryDFSRSS.jsp?zone=1168052100'\r\n\r\nres = requests.get(url, headers=headers)\r\nhtml = BeautifulSoup(res.text, 'lxml')\r\n\r\nfor weather in html.findAll('data'):\r\n print(weather.day.string)\r\n # weather['day'].text\r\n print(weather.wfkor.string)\r\n print(weather.temp.string)\r\n\r\nfor weather in html.find_all('data'):\r\n print(weather.day.text)\r\n print(weather.wfkor.text)\r\n print(weather.temp.text)\r\n","sub_path":"2. [Python_Codes] Fabio Ko's Python Programming (파이썬 프로그래밍)/39weather_rss.py","file_name":"39weather_rss.py","file_ext":"py","file_size_in_byte":3983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"602436162","text":"import ROOT\nfrom xAH_config import xAH_config\n\nc = xAH_config()\n\nc.setalg(\"BasicEventSelection\", { \"m_applyGRLCut\" : True,\n \"m_GRLxml\" : \"$ROOTCOREBIN/data/MultijetBalance/data16_13TeV.periodAllYear_DetStatus-v83-pro20-15_DQDefects-00-02-04_PHYS_StandardGRL_All_Good_25ns.xml\",\n \"m_derivationName\" : \"EXOT2\",\n \"m_useMetaData\" : False,\n \"m_storePassHLT\" : True,\n \"m_storeTrigDecisions\" : True,\n \"m_applyTriggerCut\" : True,\n \"m_triggerSelection\" : \"HLT_j380|HLT_j260|HLT_j175|HLT_j110\",\n #\"m_triggerSelection\" : \"HLT_j380|HLT_j260|HLT_j175|HLT_j110|HLT_j85\",\n \"m_checkDuplicatesData\" : False,\n \"m_applyEventCleaningCut\" : True,\n \"m_applyPrimaryVertexCut\" : True,\n #\"m_doPUreweighting\" : True,\n #\"m_PRWFileNames\" : \"$ROOTCOREBIN/data/MultijetBalance/PRW_QCD.root\",\n #\"m_lumiCalcFileNames\" : \"$ROOTCOREBIN/data/MultijetBalance/ilumicalc_histograms_None_297730-311481_OflLumi-13TeV-005.root\",\n } )\n#prescales in run 307861\n#15 - 301, 25 - 124, 35 - 18.3, 45 - 88, 55 - 40.7, 60 - 20, 85 - 14, 110 - 5.7, 150 - 11.8, 175 - 4.1, 260 - 1.2, \n\n### MJB Configuration ###\nc.setalg(\"MultijetBalanceAlgo\", { \"m_name\" : \"MultijetAlgo\",\n\n \"m_TileCorrection\" : False,\n\n \"m_inContainerName\" : \"AntiKt4EMTopoJets\",\n# \"m_triggerAndPt\" : \"\", #Leave this empty for efficiency studies!\n \"m_triggerAndPt\" : \"HLT_j380:550,HLT_j260:400,HLT_j175:300,HLT_j110:200\",\n# min binning 2016 from study on tight beta cut: \"HLT_j380:466,HLT_j260:320, HLT_j175:180\",\n# min binning 2016 from study on loose beta cut: ,\n #\"m_triggerAndPt\" : \"HLT_j380:500,HLT_j260:350,HLT_j175:250,HLT_j110:200\", #Used for validation\n# \"m_triggerAndPt\" : \"HLT_j360:420,HLT_j260:325,HLT_j200:250,HLT_j175:225,HLT_j150:200,HLT_j110:175,HLT_j85:125\", #original\n \"m_MJBIteration\" : 0,\n ## The pt thresholds on the subleading jets for event inclusion. -1 gets taken from the V+jet file.\n ## This is set automatically in m_validation to a large number!\n #\"m_MJBIterationThreshold\" : \"9999999999\",\n \"m_MJBIterationThreshold\" : \"-1,2000\",\n ## For higher iterations:\n #\"m_MJBCorrectionFile\" : \"Bootstrap_Iteration0_EM_hist.combined.Pythia.DoubleMJB_initial.root\",\n #\"m_MJBCorrectionFile\" : \"Iteration0_2016EM_hist.combined.Pythia.Fit_DoubleMJB_initial.root\",\n\n## 2016 initial validation binning\n \"m_binning\" : \"200,250,300,350,400,450,500,550,600,650,700,750,800,850,900,950,1000,1050,1100,1150,1200,1300,1500,1700,2000,2300,2600\", #23bins\n# \"m_binning\" : \"300,325,350,375,400,425,450,475,500,525,550,575,600,625,650,675,700,725,750,775,800,825,850,875,900,925,950,975,1000,1050,1100,1150,1200,1300,1500,1700,2000,2300\", #37 bins\n# \"m_binning\" : \"300,350,400,450,500,550,600,650,700,750,800,850,900,950,1000,1100,1200,1300,1400,1600,1800,2000,2500,3000,3500\",\n\n\n ## Use dedicated V+jet calibrations, requires JetCalibTools to only run on eta-intercalibration! ##\n \"m_VjetCalibFile\" : \"$ROOTCOREBIN/data/MultijetBalance/PreviousConfigs/2016_EM/Vjet_Nominal.root\",\n# \"m_VjetCalibFile\" : \"\",\n\n ## Use GSC value, not insitu, for leading jet.\n#\"m_leadingGSC\" : True,\n\n ## Systematic Variations to use:\n# \"m_sysVariations\" : \"Nominal\",\n \"m_sysVariations\" : \"AllSystematics\",\n# \"m_sysVariations\" : \"Nominal-localMJB\",\n\n ## (Deprecated Option) Add statistical systematic for MJB:\n# \"m_MJBStatsOn\" : True,\n\n#------ Event Selections ------#\n# \"m_numJets\" : 3,\n# \"m_ptAsym\" : 0.8,\n# \"m_alpha\" : 0.3,\n \"m_beta\" : 1.0,\n# \"m_ptThresh\" : 60, #in GeV\n ## Looser beta cut to improve statistics\n \"m_looseBetaCut\" : True,\n\n#------ Bootstrap Mode ------#\n# \"m_bootstrap\" : True,\n# \"m_systTool_nToys\" : 100,\n\n#------ Validation Mode ------#\n #You should probably turn off the m_VjetCalibFile for this!!\n ## Apply the jet calibrations to the leading jet:\n# \"m_validation\" : True,\n# ## Dijet validation mode: ##\n# \"m_numJets\" : 2,\n# \"m_ptAsym\" : 1.0,\n\n#------ B-tag Mode : Not yet implemented ------#\n# \"m_bTagWPsString\" : \"77,85\",\n# \"m_bTagFileName\" : \"$ROOTCOREBIN/data/xAODAnaHelpers/2016-Winter-13TeV-MC15-CDI-February5_prov.root\",\n# \"m_bTagVar\" : \"MV2c20\",\n# \"m_bTagLeadJetWP\" : \"\",\n# \"m_leadingInsitu\" : True,\n# \"m_noLimitJESPt\" : True,\n\n#------ Closure Test Mode ------#\n ##Apply MJB correction to the leading jet:\n# \"m_closureTest\" : True,\n\n### Plotting Options ###\n# \"m_writeTree\" : True,\n \"m_writeNominalTree\" : True,\n# \"m_MJBDetailStr\" : \"bTag85 bTag77\",\n# \"m_MJBDetailStr\" : \"extraMJB\",\n \"m_eventDetailStr\" : \"pileup\",\n \"m_jetDetailStr\" : \"kinematic flavorTag\",# truth\",#truth_details\",\n# \"m_jetDetailStr\" : \"kinematic truth truth_details sfFTagVL sfFTagL sfFTagM sfFTagT\",\n \"m_trigDetailStr\" : \"basic passTriggers\",\n\n### Extra Options ###\n \"m_debug\" : False,\n ## Remove problematic Pileup events from low pt MC slices:\n \"m_MCPileupCheckContainer\" : \"AntiKt4TruthJets\",\n\n #!! \"m_isAFII\" : True,\n #!! \"m_isDAOD\" : True,\n#!! \"m_useCutFlow\" : False,\n\n \"m_XSFile\" : \"$ROOTCOREBIN/data/MultijetBalance/XsAcc_13TeV.txt\", \n\n### Tool Configurations ###\n\n #-- JetCalibTool --#\n \"m_jetDef\" : \"AntiKt4EMTopo\",\n \"m_jetCalibSequence\" : \"JetArea_Residual_Origin_EtaJES_GSC\",\n## ICHEP 2016 20.7 calibration for validation\n \"m_jetCalibConfig\" : \"JES_2016data_Oct2016_EtaIntercalOnly.config\",\n #\"m_jetCalibConfig\" : \"JES_MC15cRecommendation_May2016.config\",\n\n #-- JetCleaning --#\n \"m_jetCleanCutLevel\" : \"LooseBad\",\n# \"m_jetCleanUgly\" : True,\n\n #-- JVT --#\n \"m_JVTWP\" : \"Medium\", # 2016\n\n #-- JetUncertaintiesTool --#\n #\"m_jetUncertaintyConfig\" : \"$ROOTCOREBIN/data/JetUncertainties/JES_2015/Moriond2016/JES2015_AllNuisanceParameters.config\"\n ### 2016 ICHEP offical Systematics\n \"m_jetUncertaintyConfig\" : \"$ROOTCOREBIN/data/JetUncertainties/JES_2016/Moriond2017/JESNuisanceParametersForMJB.config\"\n #\"m_jetUncertaintyConfig\" : \"$ROOTCOREBIN/data/JetUncertainties/JES_2015/ICHEP2016/JES2015_AllNuisanceParameters.config\"\n #\"m_jetUncertaintyConfig\" : \"$ROOTCOREBIN/data/JetUncertainties/JES_2015/ICHEP2016/JES2015_SR_Scenario1.config\"\n\n\n } )\n\n","sub_path":"data/Configs/2016_EM/config_MJB_2016_EM207.py","file_name":"config_MJB_2016_EM207.py","file_ext":"py","file_size_in_byte":6709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"361804342","text":"import logging\nimport os\n\nfrom django.db import models\nfrom django.core.urlresolvers import reverse\n\nfrom common.models import Profile\nfrom django.conf import settings\n\n\nclass StatusStep(models.Model):\n slug = models.CharField(max_length=255)\n name = models.CharField(max_length=255)\n\n def __unicode__(self):\n return self.name\n\n\nclass Intake(models.Model):\n\n class Stages(object):\n LEAD = 0\n PROSPECT = 1\n PROCESSING = 2\n\n @classmethod\n def get_display(cls):\n return (\n (cls.LEAD, 'Lead'),\n (cls.PROSPECT, 'Prospect'),\n (cls.PROCESSING, 'Processing'),\n )\n\n\n class Status(object):\n NEW_LEAD = 1\n LEFT_MESSAGE = 2\n DEAD_LEAD = 3\n # WATCHED_OPT_IN = 4 # No longer in use\n # FILLED_OUT_OPT_IN_FORM = 5 # No longer in use\n CALLED_NO_ANSWER = 4\n NOT_CONTACTED = 5\n # SENT_WEBINAR_ONE = 8 # No longer in use\n # WATCHED_WEBINAR_ONE = 9 #No longer in use\n # FILLED_OUT_WEBINAR_ONE_FORM = 10 # No longer in use\n # SENT_WEBINAR_TWO = 11 # No longer in use\n # WATCHED_WEBINAR_TWO = 12 # No longer in use\n # FILLED_OUT_WEBINAR_TWO_FORM = 13 # No longer in use\n WAITING_FOR_INTAKE = 6\n COMPLETED_INTAKE = 7\n WAITING_FOR_ILLUSTRATION = 8\n WAITING_FOR_SECOND_INTAKE = 9\n IN_PROCESSING = 10\n COMPLETED = 11\n REQUESTED_INFORMATION = 12\n SENT_DEBT_DEAL = 13\n WATCHED_DEBT_DEAL = 14\n # New\n WATCHED_WELCOME = 15\n WATCHED_OVERVIEW = 16\n WATCHED_HIGH_LEVEL_LOOK = 17\n WATCHED_WHAT_ARE_THE_RISKS = 18\n WATCHED_INDEX_PERFORMANCE_RISK = 19\n SENT_FIRST_SET = 20\n SENT_SECOND_SET = 21\n WATCHED_TAXATION = 22\n WATCHED_COMPANY_CHANGE = 23\n WATCHED_CARRIER_DEFAULT = 24\n WATCHED_POWER_OF_LEVERAGE = 25\n WATCHED_NEW_LEAD_VIDEO = 26\n CHECK_UP_REFERRAL = 27\n SEND_TELEPHONE_INTERVIEW_EMAIL = 28\n\n @classmethod\n def get_display(cls):\n return (\n (cls.NEW_LEAD, 'New Lead'), #1\n (cls.LEFT_MESSAGE, 'Left Message'), #2\n (cls.DEAD_LEAD, 'Dead Lead'), #3\n #(cls.WATCHED_OPT_IN, 'Watched Opt In Video'),\n #(cls.FILLED_OUT_OPT_IN_FORM, 'Filled Out Opt In Form'),\n (cls.CALLED_NO_ANSWER, 'Called No Answer'), #4\n (cls.NOT_CONTACTED, 'Not Contacted'), #5\n #(cls.SENT_WEBINAR_ONE, 'Sent Webinar One'),\n #(cls.WATCHED_WEBINAR_ONE, 'Watched Webinar One'),\n #(cls.FILLED_OUT_WEBINAR_ONE_FORM, 'Filled Out Webinar One Form'),\n #(cls.SENT_WEBINAR_TWO, 'Sent Webinar Two'),\n #(cls.WATCHED_WEBINAR_TWO, 'Watched Webinar Two'),\n #(cls.FILLED_OUT_WEBINAR_TWO_FORM, 'Filled Out Webinar Two Form'),\n\n (cls.WATCHED_WELCOME, 'Watched Welcome Video'), # New 6\n\n (cls.WATCHED_OVERVIEW, 'Watched Overview of the Barefoot Retirement Program'), # New 7\n\n (cls.WATCHED_HIGH_LEVEL_LOOK, 'Watched High Level Look at the IUL'), # New 8\n\n (cls.WATCHED_WHAT_ARE_THE_RISKS, 'Watched What are the Risks Associated with the IUL'), # New 9\n\n (cls.WATCHED_INDEX_PERFORMANCE_RISK, 'Watched Index Performance Risk of an IUL'), # New 10\n (cls.WATCHED_TAXATION, 'Watched Taxation and the IUL'),\n (cls.WATCHED_COMPANY_CHANGE, 'Watched Company Change in Policy Risk'),\n (cls.WATCHED_CARRIER_DEFAULT, 'Watched What are the Risks of Carrier Default'),\n (cls.WATCHED_POWER_OF_LEVERAGE, 'Watched the Power of Leverage with the IUL'),\n (cls.SENT_FIRST_SET, 'Sent first set of videos'),\n (cls.WAITING_FOR_INTAKE, 'Waiting for Intake'), # 11\n (cls.COMPLETED_INTAKE, 'Completed Intake'), # 12\n (cls.WAITING_FOR_ILLUSTRATION, 'Waiting for Illustration'), #13\n (cls.WAITING_FOR_SECOND_INTAKE, 'Waiting for Second Intake'), #14\n (cls.IN_PROCESSING, 'In Processing'), # 15\n (cls.COMPLETED, 'Completed'), # 16\n (cls.REQUESTED_INFORMATION, 'Requested Information'), #17\n (cls.SENT_DEBT_DEAL, 'Sent Debt Deal'), #18\n (cls.WATCHED_DEBT_DEAL, 'Watched Debt Deal'), #19\n (cls.SENT_SECOND_SET, 'Sent second set of videos'),\n (cls.WATCHED_NEW_LEAD_VIDEO, 'Watched New Lead Video'),\n (cls.CHECK_UP_REFERRAL, 'CheckUP Referral'),\n (cls.SEND_TELEPHONE_INTERVIEW_EMAIL, 'Send Telephone Interview Email'),\n )\n\n @classmethod\n def get_check_up_requirements(cls):\n indexes = [27,]\n return [s[0] for s in cls.get_display() if s[0] in indexes]\n\n @classmethod\n def get_new_lead_video_requirements(cls):\n indexes = [1]\n return [s[0] for s in cls.get_display() if s[0] in indexes]\n\n @classmethod\n def get_first_videos_requirements(cls):\n indexes = [20]\n return [s[0] for s in cls.get_display() if s[0] in indexes]\n\n @classmethod\n def get_second_videos_requirements(cls):\n indexes = [21]\n return [s[0] for s in cls.get_display() if s[0] in indexes]\n\n @classmethod\n def get_debt_deal_requirements(cls):\n indexes = [13, 14]\n return [s[0] for s in cls.get_display() if s[0] in indexes]\n\n @classmethod\n def get_stage_display(cls, stage):\n if stage == Intake.Stages.LEAD:\n indexes = [2, 3, 4, 5]\n elif stage == Intake.Stages.PROSPECT:\n indexes = [6, 15, 16, 17, 18, 19,22,23,24,25]\n elif stage == Intake.Stages.PROCESSING:\n indexes = [7, 8 , 9, 10, 11]\n return [s for s in cls.get_display() if s[0] in indexes]\n\n\n class Concerns(object):\n GROW_NEST_EGG = 'grow_nest_egg'\n RETIREMENT_INCOME = 'retirement_income'\n MONEY_ON_MY_TERMS = 'money_on_my_terms'\n RECAPTURE_INTEREST_CHARGES = 'recapture_interest_charges'\n PAY_FOR_COLLEGE = 'pay_for_college'\n NONE_OF_THE_ABOVE = 'none_of_the_above'\n\n @classmethod\n def get_display(cls):\n return (\n (cls.GROW_NEST_EGG, \"Growing my nest-egg safely and predictably no matter what's happening in the markets\"),\n (cls.RETIREMENT_INCOME, \"Retirement income I can predict and count on\"),\n (cls.MONEY_ON_MY_TERMS, \"Access to money on my own terms when I need it \"),\n (cls.RECAPTURE_INTEREST_CHARGES, \"Recapture interest charges I now pay to financial institutions\"),\n (cls.PAY_FOR_COLLEGE, \"Pay for college tuition without going broke\"),\n (cls.NONE_OF_THE_ABOVE, \"None of the Above\"),\n )\n\n\n class MartialStatus(object):\n SINGLE = 'single'\n MARRIED = 'married'\n\n @classmethod\n def get_display(cls):\n return (\n (cls.SINGLE, \"Single\"),\n (cls.MARRIED, \"Married\"),\n )\n\n\n class Occupation(object):\n NURSE = 'nurse'\n DOCTOR = 'doctor'\n ENGINEER = 'engineer'\n\n @classmethod\n def get_display(cls):\n return (\n (cls.NURSE, \"Nurse\"),\n (cls.DOCTOR, \"Doctor\"),\n (cls.ENGINEER, \"Engineer\"),\n )\n\n\n class TaxFilingStatus(object):\n SINGLE = 'single'\n MARRIED_JOINT = 'married_joint'\n MARRIED_SEPARATELY = 'married_separately'\n WIDOW = 'widow'\n HEAD_OF_HOUSEHOLD = 'head_of_household'\n\n @classmethod\n def get_display(cls):\n return (\n (cls.SINGLE, \"Single\"),\n (cls.MARRIED_JOINT, \"Married Joint\"),\n (cls.MARRIED_SEPARATELY, \"Married Separately\"),\n (cls.WIDOW, \"Widow\"),\n (cls.HEAD_OF_HOUSEHOLD, \"Head of Household\"),\n )\n\n\n class OptInInterests(object):\n TAXFREEWEBINAR = 'tax_free_webinar'\n LEVERAGINGRETIREMENT = 'leveraging_retirement'\n BOTH = 'both'\n\n @classmethod\n def get_display(cls):\n return (\n (cls.TAXFREEWEBINAR, \"Tax Free Webinar\"),\n (cls.LEVERAGINGRETIREMENT, \"Leveraging your Retirement Dollars\"),\n (cls.BOTH, \"Both\"),\n )\n\n class ReferralTypes(object):\n REFER_A_FRIEND = 'refer_a_friend'\n COW_SURVEY = 'cow_survey'\n\n @classmethod\n def get_display(cls):\n return (\n (cls.REFER_A_FRIEND, \"Refer a Friend\"),\n (cls.COW_SURVEY, \"COW Survey\"),\n )\n\n\n\n profile = models.ForeignKey(Profile)\n agent = models.ForeignKey(Profile, related_name='agent', blank=True, null=True)\n stage = models.IntegerField(choices=Stages.get_display())\n # status = models.IntegerField(choices=Status.get_display())\n status_steps = models.ManyToManyField(StatusStep, blank=True, null=True)\n referral_type = models.CharField(max_length=24, blank=True, null=True,\n choices=ReferralTypes.get_display())\n referral_id = models.IntegerField(blank=True, null=True,\n help_text=\"ID of the referral\")\n\n concerns = models.CharField(blank=True, null=True, max_length=256)\n martial_status = models.CharField(blank=True, null=True, max_length=12,\n choices=MartialStatus.get_display())\n occupation = models.CharField(blank=True, null=True, max_length=64)\n licensed_to_sell_insurance = models.BooleanField(default=False)\n annual_household_income = models.CharField(blank=True, null=True, max_length=64)\n homeowner = models.BooleanField(default=False)\n business_owner = models.BooleanField(default=False)\n\n net_worth = models.CharField(blank=True, null=True, max_length=64)\n mortgage_balance = models.CharField(blank=True, null=True, max_length=64)\n years_remaining_mortage = models.CharField(blank=True, null=True, max_length=64)\n years_planning_on_living_in_home = models.CharField(blank=True, null=True, max_length=64)\n credit_card_debt = models.CharField(blank=True, null=True, max_length=64)\n\n opt_in_interest = models.CharField(blank=True, null=True, max_length=64, choices=OptInInterests.get_display())\n other_policy = models.TextField(null=True, blank=True)\n replacement_policy = models.TextField(null=True, blank=True)\n desired_retirement_age = models.CharField(blank=True, null=True, max_length=64)\n current_rollover_balance = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Current Qualified Rollover Balance')\n current_percent_of_income_contribution = models.CharField(blank=True, null=True, max_length=64)\n expected_rate_of_return = models.CharField(blank=True, null=True, max_length=64)\n expected_annual_inflation_rate = models.CharField(blank=True, null=True, max_length=64)\n\n tax_filing_status = models.CharField(max_length=32, blank=True, null=True,\n choices=TaxFilingStatus.get_display())\n plan_529 = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='529 Plan')\n other_college_savings_account = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Other College Savings Account')\n\n checking_account_one = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Checking Account')\n savings_account_one = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Savings Account')\n cds_one = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='CDs')\n bonds_one = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Bonds')\n stocks_one = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Stocks')\n mutual_funds_one = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Mutual Funds')\n cash_value_life_insurance_one = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Cash Value of Life Insurance')\n precious_metals_one = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Precious Metals')\n other_one = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Other')\n\n plan_401k_one = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='401k Plan')\n matched_contributions_one = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Matched Contributions')\n nonmatched_contributions_one = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Non-matched Contributions')\n roth_iras_one = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Roth IRAs')\n roth_ira_basis_one = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Roth IRA Basis')\n traditional_iras_one = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Traditional IRAs')\n annuties_one = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Annuties')\n\n property_one_value_one = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property One: Value')\n property_one_mortgage_balance_one = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property One: Mortgage Balance')\n property_one_mortgage_rate_one = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property One: Mortgage Rate (%)')\n property_one_mortgage_payment_one = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property One: Mortgage Payment')\n property_one_mortgage_extra_payment_one = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property One: Extra Mortgage Payment')\n\n property_two_value_one = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property Two: Value')\n property_two_mortgage_balance_one = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property Two: Mortgage Balance')\n property_two_mortgage_rate_one = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property Two: Mortgage Rate (%)')\n property_two_mortgage_payment_one = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property Two: Mortgage Payment')\n property_two_mortgage_extra_payment_one = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property Two: Extra Mortgage Payment')\n\n checking_account_two = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Checking Account')\n savings_account_two = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Savings Account')\n cds_two = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='CDs')\n bonds_two = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Bonds')\n stocks_two = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Stocks')\n mutual_funds_two = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Mutual Funds')\n cash_value_life_insurance_two = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Cash Value of Life Insurance')\n precious_metals_two = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Precious Metals')\n other_two = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Other')\n\n plan_401k_two = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='401k Plan')\n matched_contributions_two = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Matched Contributions')\n nonmatched_contributions_two = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Non-matched Contributions')\n roth_iras_two = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Roth IRAs')\n roth_ira_basis_two = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Roth IRA Basis')\n traditional_iras_two = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Traditional IRAs')\n annuties_two = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Annuties')\n\n property_one_value_two = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property One: Value')\n property_one_mortgage_balance_two = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property One: Mortgage Balance')\n property_one_mortgage_rate_two = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property One: Mortgage Rate (%)')\n property_one_mortgage_payment_two = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property One: Mortgage Payment')\n property_one_mortgage_extra_payment_two = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property One: Extra Mortgage Payment')\n\n property_two_value_two = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property Two: Value')\n property_two_mortgage_balance_two = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property Two: Mortgage Balance')\n property_two_mortgage_rate_two = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property Two: Mortgage Rate (%)')\n property_two_mortgage_payment_two = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property Two: Mortgage Payment')\n property_two_mortgage_extra_payment_two = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property Two: Extra Mortgage Payment')\n\n checking_account_joint = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Checking Account')\n savings_account_joint = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Savings Account')\n cds_joint = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='CDs')\n bonds_joint = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Bonds')\n stocks_joint = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Stocks')\n mutual_funds_joint = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Mutual Funds')\n cash_value_life_insurance_joint = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Cash Value of Life Insurance')\n precious_metals_joint = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Precious Metals')\n other_joint = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Other')\n\n plan_401k_joint = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='401k Plan')\n matched_contributions_joint = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Matched Contributions')\n nonmatched_contributions_joint = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Non-matched Contributions')\n roth_iras_joint = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Roth IRAs')\n roth_ira_basis_joint = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Roth IRA Basis')\n traditional_iras_joint = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Traditional IRAs')\n annuties_joint = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Annuties')\n\n property_one_value_joint = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property One: Value')\n property_one_mortgage_balance_joint = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property One: Mortgage Balance')\n property_one_mortgage_rate_joint = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property One: Mortgage Rate (%)')\n property_one_mortgage_payment_joint = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property One: Mortgage Payment')\n property_one_mortgage_extra_payment_joint = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property One: Extra Mortgage Payment')\n\n property_two_value_joint = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property Two: Value')\n property_two_mortgage_balance_joint = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property Two: Mortgage Balance')\n property_two_mortgage_rate_joint = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property Two: Mortgage Rate (%)')\n property_two_mortgage_payment_joint = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property Two: Mortgage Payment')\n property_two_mortgage_extra_payment_joint = models.CharField(blank=True, null=True, max_length=64,\n verbose_name='Property Two: Extra Mortgage Payment')\n\n\n def concerns_list(self):\n return self.concerns.split('.') if self.concerns else []\n\n\n def add_status_step(self, id):\n step = StatusStep.objects.get(id=id)\n logging.info('Step {0} -> {1}'.format(id, step))\n self.status_steps.add(step)\n\n\n def remove_status_step(self, id):\n step = StatusStep.objects.get(id=id)\n self.status_steps.remove(step)\n\n\n def get_absolute_url(self):\n return reverse('clients:client_home', args=(self.id,))\n\n\n def __unicode__(self):\n return u'#{0} {1}'.format(self.id, self.profile.email)\n\n\nclass Beneficiary(models.Model):\n\n\n class BENE_TYPES(object):\n PRIMARY = 'primary'\n CONTINGENT = 'contingent'\n\n @classmethod\n def get_display(cls):\n return (\n (cls.PRIMARY, 'Primary'),\n (cls.CONTINGENT, 'Contingent'),\n )\n\n\n intake = models.ForeignKey(Intake)\n first_name = models.CharField(max_length=30, null=True, blank=True)\n last_name = models.CharField(max_length=30, null=True, blank=True)\n\n street_address = models.CharField(max_length=256,\n null=True, blank=True)\n street_address_2 = models.CharField(max_length=256,\n null=True, blank=True, default='')\n city = models.CharField(max_length=32,\n null=True, blank=True)\n state = models.CharField(max_length=32, blank=True, null=True)\n zip_code = models.CharField(max_length=10, blank=True, null=True)\n phone = models.CharField(max_length=12, null=True, blank=True)\n # social = EncryptedCharField(max_length=256,\n # null=True, blank=True)\n date_of_birth = models.CharField(max_length=10, help_text='Format: YYYY-MM-DD',\n null=True, blank=True)\n\n relationship = models.CharField(max_length=256)\n bene_type = models.CharField(max_length=12, choices=BENE_TYPES.get_display(),\n null=True, blank=True)\n percentage = models.CharField(max_length=5, default=100,\n null=True, blank=True)\n\n\n def __unicode__(self):\n return '%s %s' % (self.first_name, self.last_name)\n\n\nclass Video(models.Model):\n\n \"\"\" Video Class used to keep track of progress \"\"\"\n\n class VIDEOS(object):\n # ... = names of the videos\n NEW_LEAD_VIDEO = 'new_lead_video'\n WELCOME = 'welcome'\n OVERVIEW = 'overview'\n HIGH_LEVEL = 'high_level'\n RISKS = 'what_are_the_risks'\n INDEX = 'index_performance'\n DEBT_DEAL = 'debt_deal'\n CHECK_UP = 'check_up'\n # second set\n TAXATION = 'taxation'\n COMPANY_CHANGE = 'company_change'\n CARRIER_DEFAULT = 'carrier_default'\n POWER_OF_LEVERAGE = 'power_of_leverage'\n @classmethod\n def get_display(cls):\n return (\n (cls.NEW_LEAD_VIDEO, 'New Lead Video'),\n (cls.WELCOME, 'Welcome Video'),\n (cls.OVERVIEW, 'An Overview of the Barefoot Retirement Program'),\n (cls.HIGH_LEVEL, 'High Level Look at the IUL'),\n (cls.RISKS, 'What are the Risks Asociated with the IUL'),\n (cls.INDEX, 'Index Performance Risk of an IUL'),\n (cls.DEBT_DEAL, 'Debt Deal'),\n (cls.CHECK_UP, 'CheckUP'),\n (cls.TAXATION, 'Taxation and the IUL'),\n (cls.COMPANY_CHANGE, 'Company Change in Policy Risk'),\n (cls.CARRIER_DEFAULT, 'What are the Risks of Carrier Default'),\n (cls.POWER_OF_LEVERAGE, 'The Power of Leverage with the IUL'),\n )\n\n intake = models.ForeignKey(Intake)\n name = models.CharField(max_length=64, choices=VIDEOS.get_display())\n date_started = models.DateTimeField(blank=True, null=True)\n date_completed = models.DateTimeField(blank=True, null=True)\n date_updated = models.DateTimeField(blank=True, null=True)\n progress = models.IntegerField(blank=True, null=True)\n\n\n def video_url(self, video_name=None):\n name = self.name\n if video_name is not None:\n name = video_name\n\n if name == Video.VIDEOS.WELCOME:\n return 'https://s3-us-west-2.amazonaws.com/barefootvideos/Welcome+To+The+Barefoot+Retirement+Education+Center.mp4'\n elif name == Video.VIDEOS.OVERVIEW:\n return 'https://s3-us-west-2.amazonaws.com/barefootvideos/high+level+intro+to+BF.mp4'\n elif name == Video.VIDEOS.HIGH_LEVEL:\n return 'https://s3-us-west-2.amazonaws.com/barefootvideos/A+High+Level+Look+At+The+IUL.mp4'\n elif name == Video.VIDEOS.RISKS:\n return 'https://s3-us-west-2.amazonaws.com/barefootvideos/A+High+Level+Look+At+Risk.mp4'\n elif name == Video.VIDEOS.INDEX:\n return 'https://s3-us-west-2.amazonaws.com/barefootvideos/Index+Performance+Risks.mp4'\n elif name == Video.VIDEOS.DEBT_DEAL:\n return 'https://s3-us-west-2.amazonaws.com/barefootvideos/Micro+Lending+Webinar+3-13-14.mp4'\n elif name == Video.VIDEOS.NEW_LEAD_VIDEO:\n # return '//www.youtube.com/embed/DXxNBWx0X3g'\n return '//www.youtube.com/embed/evlxL1_VJlY'\n elif name == Video.VIDEOS.CHECK_UP:\n return '//www.youtube.com/embed/evlxL1_VJlY'\n\n def get_bound_data(self):\n return {\n 'id': self.id,\n 'intake_id': self.intake.id,\n 'name': self.name,\n 'url': self.video_url(),\n 'date_started': self.date_started.isoformat() if self.date_started else None,\n 'date_completed': self.date_completed.isoformat() if self.date_completed else None,\n 'date_updated': self.date_updated.isoformat() if self.date_updated else None,\n 'progress': self.progress,\n }\n\n\n def __unicode__(self):\n return '#{0} - {1}'.format(self.intake.id, self.name)\n","sub_path":"stratinvnet/intakes/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":27798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"576750227","text":"#!/usr/bin/python\n# Скрипт принимает список строк, содержащий целые числа и слова и возвращает\n# упорядоченную версию списка.\n# В упорядоченной версии позиции чисел и строк сохраняются.\n\nimport os\n\ninList = ['yellow', 'white', 2, 5, 'green', 'red', 6, 1]\n# Метод ввода должен быть пользовательский\nintList = []\nstrList = []\noutList = []\ncountInt = 0\ncountStr = 0\n\n# Функция разбиения списка на 2 новых списка с числами и строками\n# и их сортировка по возрастанию\nfor i in inList:\n lind = inList.index(i)\n if type(inList[lind])==int:\n intList.append(i)\n else:\n strList.append(i)\n \nintList.sort()\nstrList.sort()\n\n# Функция составления нового списка с сохранением позиций строк и чисел\nfor i in inList:\n lind = inList.index(i)\n if type(inList[lind])==int:\n outList.append(intList[countInt])\n countInt += 1\n\n else:\n outList.append(strList[countStr])\n countStr += 1\n\nprint (outList)\n\n# Дописать функцию подсчета строк и чисел - для информации (вдруг пользователь введет число как строку)\n","sub_path":"Task_01.py","file_name":"Task_01.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"376251155","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"Tests for PageRankClassifier\"\"\"\n\nimport unittest\n\nfrom sknetwork.classification import PageRankClassifier\nfrom sknetwork.data.test_graphs import *\n\n\nclass TestPageRankClassifier(unittest.TestCase):\n\n def test_solvers(self):\n adjacency = test_graph()\n seeds = {0: 0, 1: 1}\n\n ref = PageRankClassifier(solver='piteration').fit_transform(adjacency, seeds)\n for solver in ['lanczos', 'bicgstab']:\n labels = PageRankClassifier(solver=solver).fit_transform(adjacency, seeds)\n self.assertTrue((ref == labels).all())\n","sub_path":"sknetwork/classification/tests/test_pagerank.py","file_name":"test_pagerank.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"551812831","text":"import tensorflow as tf\r\nimport time\r\nimport numpy as np\r\nimport sys\r\n\r\n\r\nclass NNModel(object):\r\n \"\"\"Wrapped neural networks\"\"\"\r\n\r\n def __init__(self, model_name, features):\r\n \"\"\"Setup a new model with name.\r\n\r\n args:\r\n name: str, the unique identifier to specify a model\r\n features: tensor to be the input of the model\r\n \"\"\"\r\n self._model_name = model_name\r\n self._layer_outputs = [features]\r\n self.batch_size = int(features.shape[0])\r\n\r\n # Output utility functions\r\n @property\r\n def output(self):\r\n return self._layer_outputs[-1]\r\n\r\n @property\r\n def model_name(self):\r\n return self._model_name\r\n\r\n @property\r\n def outputs(self):\r\n return self._layer_outputs\r\n\r\n @property\r\n def layer_num(self):\r\n return len(self._layer_outputs)\r\n\r\n @property\r\n def _output_unit_num(self):\r\n return int(self.output.shape[-1])\r\n\r\n def _get_layer_str(self, layer=None):\r\n \"\"\"give each layer a name to specify them\r\n\r\n args:\r\n layer int start from 1(input layer)\r\n \"\"\"\r\n assert layer is None or layer > 0, \"layer start from 1\"\r\n if layer is None:\r\n layer = len(self.outputs)\r\n return \"%s_L%03d\" % (self.model_name, layer + 1)\r\n\r\n # Initialier utility functions\r\n def _he_initialized_tensor(self, prev_units, num_units, stddev_factor=2., distribution=\"normal\"):\r\n \"\"\"truncted_normal with limit = sqrt(6 / (fan_in + fan_out))\"\"\"\r\n assert (distribution == \"normal\" or distribution == \"uniform\")\r\n if distribution == \"normal\":\r\n stddev = np.sqrt(stddev_factor / prev_units)\r\n intw = tf.truncated_normal([prev_units, num_units], mean=0, stddev=stddev)\r\n elif distribution == \"uniform\":\r\n stddev = np.sqrt(stddev_factor / (prev_units + num_units))\r\n\r\n intw = tf.uniform([prev_units, num_units], mean=0., stddev=stddev)\r\n return intw\r\n\r\n def _he_initialized_tensor_conv2d(self, prev_units, num_units, mapsize, stddev_factor=2., distribution=\"normal\"):\r\n \"\"\"truncted_normal with limit = sqrt(6 / (fan_in + fan_out))\"\"\"\r\n assert (distribution == \"normal\" or distribution == \"uniform\")\r\n if distribution == \"normal\":\r\n stddev = np.sqrt(stddev_factor / (prev_units * mapsize * mapsize))\r\n elif distribution == \"uniform\":\r\n stddev = np.sqrt(stddev_factor / ((prev_units + num_units) * mapsize * mapsize))\r\n return tf.truncated_normal([mapsize, mapsize, prev_units, num_units], mean=0., stddev=stddev)\r\n\r\n def _glorot_initialized_tensor(self, prev_units, num_units, stddev_factor=1.0):\r\n \"\"\"Initialization in the style of Glorot 2010.\r\n stddev_factor should be 1.0 for linear activations, and 2.0 for ReLUs\r\n \"\"\"\r\n stddev = np.sqrt(stddev_factor / np.sqrt(prev_units * num_units))\r\n return tf.truncated_normal([prev_units, num_units],\r\n mean=0.0, stddev=stddev)\r\n\r\n def _glorot_initialized_tensor_conv2d(self, prev_units, num_units, mapsize, stddev_factor=1.0):\r\n \"\"\"Initialization in the style of Glorot 2010.\r\n stddev_factor should be 1.0 for linear activations, and 2.0 for ReLUs\r\n\r\n args:\r\n mapsize: int, filter size\r\n \"\"\"\r\n\r\n stddev = np.sqrt(stddev_factor / (np.sqrt(prev_units * num_units) * mapsize * mapsize))\r\n return tf.truncated_normal([mapsize, mapsize, prev_units, num_units],\r\n mean=0.0, stddev=stddev)\r\n\r\n # Add layer functions\r\n def add_batch_norm(self, scale=False):\r\n \"\"\"Adds a batch normalization layer to this model.\r\n See ArXiv 1502.03167v3 for details.\r\n \"\"\"\r\n\r\n # TBD: This appears to be very flaky, often raising InvalidArgumentError internally\r\n with tf.variable_scope(self._get_layer_str(), reuse=tf.AUTO_REUSE):\r\n out = tf.contrib.layers.batch_norm(self.output, scale=scale)\r\n\r\n self.outputs.append(out)\r\n return self\r\n\r\n def add_flatten(self):\r\n \"\"\"Transforms the output of this network to a 1D tensor\"\"\"\r\n with tf.variable_scope(self._get_layer_str(), reuse=tf.AUTO_REUSE):\r\n out = tf.reshape(self.output, [self.batch_size, -1])\r\n\r\n self.outputs.append(out)\r\n return self\r\n\r\n def add_dense(self, num_units, stddev_factor=1.0):\r\n \"\"\"Adds a dense linear layer to this model.\r\n Uses Glorot 2010 initialization assuming linear activation.\r\n \"\"\"\r\n\r\n assert len(self.output.shape) == 2, \"Previous layer must be 2-dimensional (batch, channels)\"\r\n\r\n with tf.variable_scope(self._get_layer_str(), reuse=tf.AUTO_REUSE):\r\n prev_units = self._output_unit_num\r\n\r\n # Weight term\r\n initw = self._he_initialized_tensor(prev_units, num_units,\r\n stddev_factor=stddev_factor)\r\n weight = tf.get_variable('weight', initializer=initw)\r\n\r\n # Bias term\r\n initb = tf.constant(0.0, shape=[num_units])\r\n bias = tf.get_variable('bias', initializer=initb)\r\n\r\n # Output of this layer\r\n out = tf.matmul(self.output, weight) + bias\r\n\r\n self.outputs.append(out)\r\n return self\r\n\r\n def add_sigmoid(self):\r\n \"\"\"Adds a sigmoid (0,1) activation function layer to this model.\"\"\"\r\n\r\n with tf.variable_scope(self._get_layer_str(), reuse=tf.AUTO_REUSE):\r\n prev_units = self._output_unit_num\r\n out = tf.nn.sigmoid(self.output)\r\n\r\n self.outputs.append(out)\r\n return self\r\n\r\n def add_softmax(self):\r\n \"\"\"Adds a softmax operation to this model\"\"\"\r\n\r\n with tf.variable_scope(self._get_layer_str(), reuse=tf.AUTO_REUSE):\r\n # this_input = tf.square(self.output)\r\n reduction_indices = -1\r\n # acc = tf.reduce_sum(this_input, reduction_indices=reduction_indices, keep_dims=True)\r\n # out = this_input / (acc+FLAGS.epsilon)\r\n out = tf.nn.softmax(self.output, reduction_indices)\r\n # out = tf.verify_tensor_all_finite(out, \"add_softmax failed; is sum equal to zero?\")\r\n\r\n self.outputs.append(out)\r\n return self\r\n\r\n def add_dropout(self, keep_prob):\r\n \"\"\"Add a dropout layer to the net\"\"\"\r\n\r\n with tf.variable_scope(self._get_layer_str(), reuse=tf.AUTO_REUSE):\r\n out = tf.nn.dropout(self.output, keep_prob, seed=int(time.time()))\r\n self.outputs.append(out)\r\n return self\r\n\r\n def add_pooling(self, ksize, method=\"max\", stride=2):\r\n \"\"\"Add a pooling layer with stride, pooling method can be either max or average\"\"\"\r\n\r\n with tf.variable_scope(self._get_layer_str(), reuse=tf.AUTO_REUSE):\r\n if method == \"max\":\r\n out = tf.nn.max_pool(self.output, [1, ksize, ksize, 1], [1, stride, stride, 1], 'SAME')\r\n elif method == \"average\":\r\n out = tf.nn.pool(self.output, [1, ksize, ksize, 1], 'MAX', 'SAME', \\\r\n strides=[1, stride, stride, 1])\r\n self.outputs.append(out)\r\n\r\n def add_relu(self):\r\n \"\"\"Adds a ReLU activation function to this model\"\"\"\r\n\r\n with tf.variable_scope(self._get_layer_str(), reuse=tf.AUTO_REUSE):\r\n out = tf.nn.relu(self.output)\r\n\r\n self.outputs.append(out)\r\n return self\r\n\r\n def add_elu(self):\r\n \"\"\"Adds a ELU activation function to this model\"\"\"\r\n\r\n with tf.variable_scope(self._get_layer_str(), reuse=tf.AUTO_REUSE):\r\n out = tf.nn.elu(self.output)\r\n\r\n self.outputs.append(out)\r\n return self\r\n\r\n def add_lrelu(self, leak=.2):\r\n \"\"\"Adds a leaky ReLU (LReLU) activation function to this model\"\"\"\r\n\r\n with tf.variable_scope(self._get_layer_str(), reuse=tf.AUTO_REUSE):\r\n # t1 = .5 * (1 + leak)\r\n # t2 = .5 * (1 - leak)\r\n # out = t1 * self.get_output() + \\\r\n # t2 * tf.abs(self.get_output())\r\n out = tf.nn.leaky_relu(self.output, alpha)\r\n self.outputs.append(out)\r\n return self\r\n\r\n def add_prelu(self, share_alpha=True):\r\n \"\"\"Adds a paramatic PReLU activation function to this model\"\"\"\r\n\r\n with tf.variable_scope(self._get_layer_str(), reuse=tf.AUTO_REUSE):\r\n alphas_shape = [1] if share_alpha else [self.output.shape[-1]]\r\n alphas = tf.get_variable(\"alphas\", initializer=np.ones(shape=alphas_shape, dtype=np.float32) * 0.25,\r\n dtype=tf.float32)\r\n out = tf.nn.relu(self.output) + tf.multiply(alphas, (self.output - tf.abs(self.output))) * 0.5\r\n self.outputs.append(out)\r\n return self\r\n\r\n def add_conv2d(self, num_units, mapsize=1, stride=1, stddev_factor=2.0):\r\n \"\"\"Adds a 2D convolutional layer.\"\"\"\r\n\r\n assert len(self.output.shape) == 4 and \"Previous layer must be 4-dimensional (batch, width, height, channels)\"\r\n\r\n with tf.variable_scope(self._get_layer_str(), reuse=tf.AUTO_REUSE):\r\n prev_units = self._output_unit_num\r\n\r\n # Weight term and convolution\r\n initw = self._he_initialized_tensor_conv2d(prev_units, num_units, \\\r\n mapsize, \\\r\n stddev_factor=stddev_factor)\r\n weight = tf.get_variable('weight', initializer=initw)\r\n out = tf.nn.conv2d(self.output, weight,\r\n strides=[1, stride, stride, 1],\r\n padding='SAME')\r\n\r\n # Bias term\r\n initb = tf.constant(0.0, shape=[num_units])\r\n bias = tf.get_variable('bias', initializer=initb)\r\n out = tf.nn.bias_add(out, bias)\r\n\r\n self.outputs.append(out)\r\n return self\r\n\r\n def add_conv2d_transpose(self, num_units, mapsize=1, stride=1, stddev_factor=2.0):\r\n \"\"\"Adds a transposed 2D convolutional layer\"\"\"\r\n\r\n assert len(self.output.shape) == 4 and \"Previous layer must be 4-dimensional (batch, width, height, channels)\"\r\n\r\n with tf.variable_scope(self._get_layer_str(), reuse=tf.AUTO_REUSE):\r\n prev_units = self._output_unit_num\r\n\r\n # Weight term and convolution\r\n initw = self._he_initialized_tensor_conv2d(prev_units, num_units,\r\n mapsize,\r\n stddev_factor=stddev_factor)\r\n weight = tf.get_variable('weight', initializer=initw)\r\n weight = tf.transpose(weight, perm=[0, 1, 3, 2])\r\n prev_output = self.output\r\n output_shape = [batch_size,\r\n int(prev_output.shape[1]) * stride,\r\n int(prev_output.shape[2]) * stride,\r\n num_units]\r\n out = tf.nn.conv2d_transpose(self.output, weight,\r\n output_shape=output_shape,\r\n strides=[1, stride, stride, 1],\r\n padding='SAME')\r\n\r\n # Bias term\r\n initb = tf.constant(0.0, shape=[num_units])\r\n bias = tf.get_variable('bias', initializer=initb)\r\n out = tf.nn.bias_add(out, bias)\r\n\r\n self.outputs.append(out)\r\n return self\r\n\r\n def add_residual_block(self, num_units, mapsize=3, \\\r\n num_layers=2, stddev_factor=2., BN=True):\r\n \"\"\"Adds a residual block as per Arxiv 1512.03385, Figure 3\"\"\"\r\n\r\n assert len(self.output.shape) == 4 and \"Previous layer must be 4-dimensional (batch, width, height, channels)\"\r\n\r\n # Add projection in series if needed prior to shortcut\r\n if num_units != int(self.output.shape[3]):\r\n self.add_conv2d(num_units, mapsize=1, stride=1, stddev_factor=stddev_factor)\r\n\r\n # bypass = self.output\r\n # how if i use tf.identity?\r\n bypass = self.output\r\n # Residual block\r\n for _ in range(num_layers):\r\n if BN: self.add_batch_norm()\r\n self.add_relu()\r\n self.add_conv2d(num_units, mapsize=mapsize, stride=1, stddev_factor=stddev_factor)\r\n\r\n self.add_sum(bypass)\r\n\r\n return self\r\n\r\n def add_bottleneck_residual_block(self, num_units, mapsize=3, stride=1, transpose=False, BN=True, stddev_factor=2.):\r\n \"\"\"Adds a bottleneck residual block as per Arxiv 1512.03385, Figure 3\"\"\"\r\n\r\n assert len(self.output.shape) == 4, \"Previous layer must be 4-dimensional (batch, width, height, channels)\"\r\n\r\n # Add projection in series if needed prior to shortcut\r\n if num_units != int(self.output.shape[3]) or stride != 1:\r\n ms = 1 if stride == 1 else mapsize\r\n # bypass.add_batch_norm() # TBD: Needed?\r\n if transpose:\r\n self.add_conv2d_transpose(num_units, mapsize=ms, stride=stride, stddev_factor=stddev_factor)\r\n else:\r\n self.add_conv2d(num_units, mapsize=ms, stride=stride, stddev_factor=stddev_factor)\r\n\r\n bypass = self.output\r\n\r\n # Bottleneck residual block\r\n if BN: self.add_batch_norm()\r\n self.add_relu()\r\n self.add_conv2d(num_units // 4, mapsize=1, stride=1, stddev_factor=stddev_factor)\r\n\r\n if BN: self.add_batch_norm()\r\n # self.add_relu()\r\n if transpose:\r\n self.add_conv2d_transpose(num_units // 4,\r\n mapsize=mapsize,\r\n stride=1,\r\n stddev_factor=stddev_factor)\r\n else:\r\n self.add_conv2d(num_units // 4,\r\n mapsize=mapsize,\r\n stride=1,\r\n stddev_factor=stddev_factor)\r\n\r\n if BN: self.add_batch_norm()\r\n self.add_relu()\r\n self.add_conv2d(num_units, mapsize=1, stride=1, stddev_factor=stddev_factor)\r\n\r\n self.add_sum(bypass)\r\n\r\n return self\r\n\r\n def add_sum(self, term):\r\n \"\"\"Adds a layer that sums the top layer with the given term\"\"\"\r\n\r\n with tf.variable_scope(self._get_layer_str(), reuse=tf.AUTO_REUSE):\r\n prev_shape = self.output.shape\r\n print(\"%s %s\" % (prev_shape, term.shape))\r\n assert prev_shape[1:] == term.shape[1:], \"Can't sum terms with a different size\"\r\n out = tf.add(self.output, term)\r\n\r\n self.outputs.append(out)\r\n return self\r\n\r\n def add_mean(self):\r\n \"\"\"Adds a layer that averages the inputs from the previous layer\"\"\"\r\n\r\n with tf.variable_scope(self._get_layer_str(), reuse=tf.AUTO_REUSE):\r\n prev_shape = self.output.shape\r\n reduction_indices = list(range(len(prev_shape)))\r\n assert len(reduction_indices) > 2 and \"Can't average a (batch, activation) tensor\"\r\n reduction_indices = reduction_indices[1:-1]\r\n out = tf.reduce_mean(self.output, reduction_indices=reduction_indices)\r\n\r\n self.outputs.append(out)\r\n return self\r\n\r\n def add_upscale(self, scale=2):\r\n \"\"\"Adds a layer that upscales the output by 2x through nearest neighbor interpolation\"\"\"\r\n\r\n with tf.variable_scope(self._get_layer_str(), reuse=tf.AUTO_REUSE):\r\n prev_shape = self.output.shape\r\n size = [scale * int(s) for s in prev_shape[1:3]]\r\n out = tf.image.resize_nearest_neighbor(self.output, size)\r\n\r\n self.outputs.append(out)\r\n return self\r\n\r\n def get_variable(self, layer, name):\r\n \"\"\"Returns a variable given its layer and name.\r\n The variable must already exist.\"\"\"\r\n\r\n scope = self._get_layer_str(layer)\r\n collection = self.graph.get_collection(tf.GraphKeys.VARIABLES, scope=scope)\r\n\r\n # TBD: Ugly!\r\n for var in collection:\r\n if var.name[:-2] == scope + '/' + name:\r\n return var\r\n\r\n return None\r\n\r\n def get_all_layer_variables(self, layer=None):\r\n \"\"\"Returns all variables in the given layer\"\"\"\r\n scope = self._get_layer_str(layer)\r\n return self.graph.get_collection(tf.GraphKeys.VARIABLES, scope=scope)\r\n\r\n def save_model(self, sess, saver, global_step):\r\n CHECKPOINTS_PATH = \"checkpoints/\"\r\n saver.save(sess, os.path.join(CHECKPOINTS_PATH, self._model_name), global_step=global_step, )\r\n print(\"[*]Checkpoints saved.\")\r\n\r\n def restore(self, sess, saver, global_step=None):\r\n CHECKPOINTS_PATH = \"checkpoints/\"\r\n\r\n checkpoint_name = os.path.join(CHECKPOINTS_PATH, \\\r\n self._model_name + \"-\" + str(\r\n global_step)) if global_step is not None else tf.train.latest_checkpoint(\r\n CHECKPOINTS_PATH)\r\n try:\r\n print(\"[.]Restoring from {checkpoint_name} ...\".format(checkpoint_name=checkpoint_name))\r\n saver.restore(sess, checkpoint_name)\r\n print(\"[*]Checkpoint loaded.\")\r\n except Exception as e:\r\n print(\"[!]Unable to restore checkpoint!\")\r\n raise e\r\n return\r\n\r\n def sample_output(self, sess, iteration, hr_imgs, sample_num=None):\r\n\r\n SAMPLE_PATH = \"samples2/\"\r\n\r\n if sample_num is None: sample_num = 1\r\n output_imgs = self.output[0:sample_num, :, :, :]\r\n bicubic = tf.image.resize_bicubic(self.outputs[0][0:sample_num, :, :, :],\r\n (output_imgs.shape[1], output_imgs.shape[2]))\r\n output_imgs = tf.concat([output_imgs, bicubic, hr_imgs[0:sample_num, :, :, :]], 2)\r\n output_imgs = tf.concat([output_imgs[i] for i in range(sample_num)], 0)\r\n output_imgs = sess.run(output_imgs)\r\n filename = \"sample_output_t{iteration}.png\".format(iteration=iteration)\r\n output_imgs = (np.array(output_imgs) * 255).astype(\"uint8\")\r\n if not os.path.exists(SAMPLE_PATH):\r\n os.makedirs(SAMPLE_PATH)\r\n pillow.Image.fromarray(output_imgs, \"RGB\").save(os.path.join(SAMPLE_PATH, filename))\r\n\r\n\r\nclass VGG:\r\n LAYERS = (\r\n 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1',\r\n\r\n 'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2',\r\n\r\n 'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3',\r\n 'relu3_3', 'conv3_4', 'relu3_4', 'pool3',\r\n\r\n 'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2', 'conv4_3',\r\n 'relu4_3', 'conv4_4', 'relu4_4', 'pool4',\r\n\r\n 'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2', 'conv5_3',\r\n 'relu5_3', 'conv5_4', 'relu5_4'\r\n )\r\n\r\n def __init__(self, data_path):\r\n self.data_path = data_path\r\n self.data = scipy.io.loadmat(data_path)\r\n mean = self.data['normalization'][0][0][0]\r\n self.mean_pixel = np.mean(mean, axis=(0, 1))\r\n self.weights = self.data['layers'][0]\r\n\r\n def preprocess(self, image):\r\n return image - self.mean_pixel\r\n\r\n def unprocess(self, image):\r\n return image + self.mean_pixel\r\n\r\n def net(self, input_image):\r\n net = {}\r\n current_layer = input_image\r\n for i, name in enumerate(self.LAYERS):\r\n if _is_convolutional_layer(name):\r\n kernels, bias = self.weights[i][0][0][0][0]\r\n # matconvnet: weights are [width, height, in_channels, out_channels]\r\n # tensorflow: weights are [height, width, in_channels, out_channels]\r\n kernels = np.transpose(kernels, (1, 0, 2, 3))\r\n bias = bias.reshape(-1)\r\n current_layer = _conv_layer_from(current_layer, kernels, bias)\r\n elif _is_relu_layer(name):\r\n current_layer = tf.nn.relu(current_layer)\r\n elif _is_pooling_layer(name):\r\n current_layer = _pooling_layer_from(current_layer)\r\n net[name] = current_layer\r\n\r\n assert len(net) == len(self.LAYERS)\r\n return net\r\n\r\n\r\ndef _is_convolutional_layer(name):\r\n return name[:4] == 'conv'\r\n\r\n\r\ndef _is_relu_layer(name):\r\n return name[:4] == 'relu'\r\n\r\n\r\ndef _is_pooling_layer(name):\r\n return name[:4] == 'pool'\r\n\r\n\r\ndef _conv_layer_from(input, weights, bias):\r\n conv = tf.nn.conv2d(input, tf.constant(weights), strides=(1, 1, 1, 1),\r\n padding='SAME')\r\n return tf.nn.bias_add(conv, bias)\r\n\r\n\r\ndef _pooling_layer_from(input):\r\n return tf.nn.max_pool(input, ksize=(1, 2, 2, 1), strides=(1, 2, 2, 1),\r\n padding='SAME')\r\n\r\n\r\ndef _tensor_size(tensor):\r\n from operator import mul\r\n return reduce(mul, (d.value for d in tensor.get_shape()), 1)\r\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":20822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"579884199","text":"#!/usr/bin/python\n\ndigits = [ 1, 2, 3, 4 ]\n\ndef combine(digit, rest):\n if (len(rest) == 0):\n return [digit, -digit]\n fwd_combinations = combine(rest[0], rest[1:])\n combinations = set()\n\n for num in fwd_combinations:\n if num != 0:\n combinations.add(digit / float(num))\n combinations.add(-digit / float(num))\n combinations.add(digit * num)\n combinations.add(-digit * num)\n combinations.add(digit + num)\n combinations.add(-digit + num)\n\n return combinations\n\n# There's more elegant ways of generating permutations :P\n\ndef permutations(values):\n if len(values) == 0:\n return []\n\n res = []\n for i in range(0, len(values)):\n after = permutations(values[0:i] + values[i+1:])\n if (len(after) == 0):\n res.append([values[i]])\n else:\n for perm in after:\n res.append([values[i]] + perm)\n\n return res\n\nrecord = 0\nfor i in range(0,10):\n for j in range(0,10):\n for k in range(0,10):\n for l in range(0,10):\n results = set()\n for perm in permutations([i,j,k,l]):\n for result in combine(perm[0], perm[1:]):\n if abs(round(result) - result) < 1E-5:\n results.add(int(result))\n consec = 0\n for p in range (0, len(results)):\n if not p in results:\n consec = p\n break\n\n if record < consec:\n record = consec\n print [i,j,k,l], consec, results\n\n","sub_path":"problem93/problem93.py","file_name":"problem93.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"71838889","text":"#!/usr/bin/env/py35\n# coding=utf-8\n\nfrom flask import Flask,request\nfrom flask.json import jsonify\nimport math\nimport redis\nfrom flask.views import MethodView\n\napp = Flask(__name__)\n\nclass PIAPI(MethodView):\n\n def __init__(self,cache):\n self.cache = cache\n\n def get(self,num):\n s = 0.0\n result = self.cache.get(num)\n if result:\n return jsonify({\"cache\":True,\"result\":result})\n for i in range(1,num):\n s += 1/(i**2)\n result = math.sqrt(s*6)\n self.cache.set(num,result)\n return jsonify(dict(cache=False,result=result))\n\n#定义分布式缓存对象\nclass RedisCache(object):\n def __init__(self,client):\n self.client = client\n def set(self,n,result):\n self.client.hset(\"pis\",str(n),str(result))\n def get(self,n):\n result = self.client.hget(\"pis\",str(n))\n if not result:\n return\n return float(result)\nclient = redis.StrictRedis()\ncache = RedisCache(client)\n\napp.add_url_rule('/pi/',view_func=PIAPI.as_view(\"pi\",cache))\n\nif __name__ == '__main__':\n app.run(\"127.0.0.1\",5001)","sub_path":"flaskTest4.py","file_name":"flaskTest4.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"519583937","text":"import unittest\nfrom io import StringIO\nimport sys\n\n\ndef resolve():\n input = sys.stdin.readline\n N = int(input())\n\n A = list(map(int, input().split()))\n\n isBalls = [0] * (N + 1)\n for k in reversed(range(1, N + 1)):\n num = sum([isBalls[k * i] for i in range(1, N // k + 1)])\n if num % 2 != A[k - 1]:\n isBalls[k] = 1\n\n M = sum(isBalls)\n ans = [i for i in range(1, N + 1) if isBalls[i] > 0]\n\n print(M)\n if ans:\n print(' '.join(map(str, ans)))\n\n\nclass TestClass(unittest.TestCase):\n def assertIO(self, input, output):\n stdout, stdin = sys.stdout, sys.stdin\n sys.stdout, sys.stdin = StringIO(), StringIO(input)\n resolve()\n sys.stdout.seek(0)\n out = sys.stdout.read()[:-1]\n sys.stdout, sys.stdin = stdout, stdin\n self.assertEqual(out, output)\n\n def test_入力例_1(self):\n input = \"\"\"3\n1 0 0\"\"\"\n output = \"\"\"1\n1\"\"\"\n self.assertIO(input, output)\n\n def test_入力例_2(self):\n input = \"\"\"5\n0 0 0 0 0\"\"\"\n output = \"\"\"0\"\"\"\n self.assertIO(input, output)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"contest_abc/134/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"114611901","text":"import re, os, argparse, stat\r\nfrom datetime import datetime\r\n\r\n\r\ndef option():\r\n opt = argparse.ArgumentParser(description='linux find command')\r\n opt.add_argument('director',\r\n nargs='?',\r\n type=str,\r\n help='source find director')\r\n opt.add_argument('-name',\r\n nargs='?',\r\n type=str,\r\n dest='name',\r\n help='Query by name')\r\n opt.add_argument('-type',\r\n nargs='?',\r\n type=str,\r\n dest='type',\r\n help='Query by file type')\r\n opt.add_argument('-ctime',\r\n nargs='?',\r\n type=str,\r\n dest='ctime',\r\n help='Query by file ctime')\r\n opt.add_argument('-mtime',\r\n nargs='?',\r\n type=str,\r\n dest='mtime',\r\n help='Query by file mtime')\r\n opt.add_argument('-cnewer',\r\n nargs='?',\r\n type=str,\r\n dest='cnewer',\r\n help='find cnewer file')\r\n opt.add_argument('-executable',\r\n action='store_true',\r\n default=False,\r\n dest='executable',\r\n help='find the executable file')\r\n opt.add_argument('-size',\r\n nargs='?',\r\n type=str,\r\n dest='size',\r\n help='Query by file size')\r\n opt.add_argument('-newer',\r\n nargs='?',\r\n type=str,\r\n dest='newer',\r\n help='File was modified more recently then file')\r\n opt.add_argument('-gid',\r\n nargs='?',\r\n type=str,\r\n dest='gid',\r\n help=\"-gid n File's numeric group ID is n\")\r\n opt.add_argument('-uid',\r\n nargs='?',\r\n type=str,\r\n dest='uid',\r\n help=\"-uid n File's numeric user ID is n\")\r\n return opt.parse_args()\r\n\r\n\r\ndef soure_list(x):\r\n lst = []\r\n for root, mi, f in os.walk(x):\r\n f.extend(mi)\r\n lst.extend([root + '/' + file for file in f])\r\n return lst\r\n\r\n\r\ndef Name(complie, source):\r\n ret = set()\r\n com = re.compile(complie)\r\n for st in source:\r\n if com.search(os.path.basename(st)):\r\n ret.add(st)\r\n return ret\r\n\r\n\r\ndef Type(arg, source):\r\n rule = {'d': stat.S_ISDIR, 'f': stat.S_ISREG, 'p': stat.S_ISFIFO, 'l': stat.S_ISLNK, 'b': stat.S_ISBLK,\r\n 'c': stat.S_ISCHR, 's': stat.S_ISSOCK}\r\n ret = set()\r\n for src in source:\r\n t = os.stat(src)\r\n if rule[arg](t.st_mode):\r\n ret.add(src)\r\n return ret\r\n\r\n\r\ndef Time(which, arg, source):\r\n new = datetime.now().timestamp()\r\n ret = set()\r\n for src in [x for x in source if os.path.isfile(x)]:\r\n which_time = os.stat(src).st_ctime if which is 'ctime' else os.stat(src).st_mtime\r\n date = int((new - which_time) // (3600 * 24))\r\n if arg[0] == '+' and date > int(arg[1:]):\r\n ret.add(src)\r\n else:\r\n if arg[0] != '+' and date <= int(arg.lstrip('-')):\r\n ret.add(src)\r\n return ret\r\n\r\n\r\ndef ID(which, arg, source):\r\n uid, gid = {}, {}\r\n with open('/etc/passwd') as f:\r\n ne = f.readline()\r\n while ne:\r\n tu = ne.split(':')\r\n uid[tu[2]] = tu[0]\r\n ne = f.readline()\r\n with open('/etc/group') as g:\r\n gn = g.readline()\r\n while gn:\r\n gt = gn.split(':')\r\n gid[gt[2]] = gt[0]\r\n gn = g.readline()\r\n ret = set()\r\n for src in source:\r\n w = uid[str(os.stat(src).st_uid)] if which is 'uid' else gid[str(os.stat(src).st_gid)]\r\n if w == arg.strip():\r\n ret.add(src)\r\n return ret\r\n\r\n\r\ndef Executable(source):\r\n ret = set()\r\n for src in source:\r\n if os.access(src, os.X_OK):\r\n ret.add(src)\r\n return ret\r\n\r\n\r\ndef Newer(which, arg, source):\r\n ret = set()\r\n arg_mtime = os.stat(arg).st_mtime if which is 'newer' else os.stat(arg).st_ctime\r\n for src in source:\r\n src_mtime = os.stat(src).st_mtime\r\n if src_mtime > arg_mtime:\r\n ret.add(src)\r\n return ret\r\n\r\n\r\ndef Size(arg, source):\r\n rule = {'k': int(arg.strip('+-kK')) * 1024, 'm': int(arg.strip('+-mM')) * (1024 ** 2),\r\n 'g': int(arg.strip('+-gG')) * (1024 ** 3), 'b': int(arg.strip('+-'))}\r\n ret = set()\r\n flag = int(arg.strip('+-')) if arg[-1].isdigit() else int(arg.strip('+-')) if arg[-1].lower() is 'c' else rule[\r\n arg[-1].lower()]\r\n for src in source:\r\n size = os.stat(src).st_blocks if arg[-1].isdigit() or arg[-1] is 'b' else os.stat(src).st_size\r\n if arg[0] is '+' and size > flag:\r\n ret.add(src)\r\n else:\r\n if arg[0] != '+' and size <= flag:\r\n ret.add(src)\r\n return ret\r\n\r\n\r\ndef Show(slist):\r\n opt = option()\r\n ret = set()\r\n if not [v for v in vars(opt).values() if v]:\r\n slist.insert(0, '.')\r\n ret = slist\r\n if opt.name:\r\n flag = Name(opt.name, slist)\r\n ret = ret & flag if ret else flag\r\n if opt.type:\r\n flag = Type(opt.type, slist)\r\n ret = ret & flag if ret else flag\r\n if opt.ctime:\r\n flag = Time('ctime', opt.ctime, slist)\r\n ret = ret & flag if ret else flag\r\n if opt.mtime:\r\n flag = Time('mtime', opt.mtime, slist)\r\n ret = ret & flag if ret else flag\r\n if opt.uid:\r\n flag = ID('uid', opt.uid, slist)\r\n ret = ret & flag if ret else flag\r\n if opt.gid:\r\n flag = ID('gid', opt.gid, slist)\r\n ret = ret & flag if ret else flag\r\n if opt.executable:\r\n flag = Executable(slist)\r\n ret = ret & flag if ret else flag\r\n if opt.newer:\r\n flag = Newer('newer', opt.newer, slist)\r\n ret = ret & flag if ret else flag\r\n if opt.cnewer:\r\n flag = Newer('cnewer', opt.cnewer, slist)\r\n ret = ret & flag if ret else flag\r\n if opt.size:\r\n flag = Size(opt.size, slist)\r\n ret = ret & flag if ret else flag\r\n\r\n return ret\r\n\r\n\r\ndef main():\r\n opt = option()\r\n\r\n if not opt.director or opt.director is '.':\r\n sl = soure_list('.')\r\n for p in Show(sl):\r\n print(p)\r\n else:\r\n sl = soure_list(opt.director)\r\n for fp in Show(sl):\r\n print(fp)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"command/find.py","file_name":"find.py","file_ext":"py","file_size_in_byte":6662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"112269646","text":"#sprite class with functions to animate sprite images\nimport pygame\nimport math\nimport sys\nfrom constants import Constants\n\nclass Sprite(object):\n\n def __init__(self, image_path, position):\n #image information\n self.image_path = image_path\n self.image = pygame.image.load(image_path)\n self.image = pygame.transform.scale(self.image, (100,50))\n\n self.image_rect = self.image.get_rect()\n\n #anteater info\n self.jump_height = 0\n self.jump_counter = 0\n self.half_jump_height_ = 0\n self.position = position\n \n\n def update(self):\n # do not touch\n print() #dont remove this print, it holds the game together\n # if you do, there will be severe consequences for the anteater\n self.handle_arrow_keys()\n self.move()\n pygame.time.delay(25)\n\n def render(self, screen):\n #self.image_rect.x = (self.initial_image_x + self.image_rect.width * self.current_frame)\n screen.blit(self.image, self.position, self.image_rect)\n\n def move(self):\n #this is where anteater jumps\n \n #reset counter\n if (self.jump_counter == self.jump_height):\n self.jump_counter = 0\n #move up\n if (self.jump_counter < self.half_jump_height):\n self.move_unit(0,0.25)\n self.move_position(0,-30)\n #move down\n if (self.jump_counter >= self.half_jump_height):\n self.move_unit(0,-0.25)\n self.move_position(0,30)\n self.jump_counter += 1\n \n\n def move_unit(self, x, y):\n self.image_rect = self.image_rect.move(x,y)\n \n\n def move_position(self, x, y):\n self.position = [self.position[0] + x, self.position[1] + y]\n \n def set_jump_height(self, height):\n self.jump_height = height\n self.half_jump_height = int(self.jump_height/2)\n\n def handle_arrow_keys(self):\n for event in pygame.event.get():\n if (event.type == pygame.QUIT):\n pygame.quit()\n sys.exit()\n #check if user pressed any key\n if event.type == pygame.KEYDOWN:\n if (event.key == pygame.K_LEFT):\n #make anteater move left\n self.move_unit(30, 0)\n \n elif (event.key == pygame.K_RIGHT):\n #make anteater move right\n self.move_unit(-30,0)\n \n elif event.type == pygame.KEYUP:\n if (event.key == pygame.K_LEFT):\n #stop moving left\n ''\n elif (event.key == pygame.K_RIGHT):\n #stop moving right\n ''\n \n \n","sub_path":"sprite.py","file_name":"sprite.py","file_ext":"py","file_size_in_byte":2761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"260921054","text":"from __future__ import annotations\n\nfrom collections.abc import Mapping\nfrom email.parser import BytesParser\nfrom typing import TYPE_CHECKING, Optional, Any\nfrom urllib.parse import parse_qs\n\nfrom .utils.json import from_json\n\nif TYPE_CHECKING:\n from .asgi import Backendpy\n\n\nclass Request:\n \"\"\"\n Base HTTP request class whose instances are used to store the information of a request\n and then these instances are sent to the requests handlers.\n\n :ivar app: :class:`~backendpy.Backendpy` class instance of the current project (that is an ASGI application).\n The information that is defined in the general scope of the project can be accessed through the\n app field of each request. For example ``request.app.config`` contains project config information.\n Also, if we want to put information in the App context, this information can be saved or read from\n ``request.app.context``. The data stored in the App context is valid until the service is stopped.\n For example, you can put a database connection in it to be used in the scope of all requests and until\n the service is turned off.\n :ivar context: A dictionary of request context variables. Applications and middlewares can store their\n own data in the request context for other components to use until the end of the request.\n For example, auth middleware can set a user's information into request context after\n authentication process in the start of the request, so that other sections in the path of\n handling the request, can use the authenticated user information for their operations.\n The scope of the data stored in the request context is the request itself and until it responds.\n :ivar method: Method of HTTP request\n :ivar path: URL path of HTTP request\n :ivar root_path: The root path this ASGI application is mounted at\n :ivar scheme: URL scheme of HTTP request\n :ivar server: A dictionary of server information (including host and port)\n :ivar client: A dictionary of client information (including remote host and port)\n :ivar headers: A dictionary of HTTP request headers\n :ivar url_vars: A dictionary of URL path variables\n :ivar params: A dictionary of HTTP request query string values\n :ivar form: A dictionary of HTTP request form data\n :ivar json: A dictionary of HTTP request JSON data\n :ivar files: A dictionary of multipart HTTP request files data\n :ivar body: Raw body of HTTP request if it does not belong to any of the \"form\",\n \"json\" and \"file\" fields\n :ivar cleaned_data: A dictionary of data processed by request data handler\n \"\"\"\n\n def __init__(\n self,\n app: Backendpy,\n scope: Mapping[str, Any],\n body: Optional[bytes] = None,\n url_vars: Optional[dict[str, str]] = None) -> None:\n \"\"\"\n Initialize request instance.\n\n :param app: :class:`~backendpy.Backendpy` class instance of the current\n project (that is an ASGI application)\n :param scope: HTTP connection scope\n :param body: Body of HTTP request\n :param url_vars: URL path variables of HTTP request\n \"\"\"\n self.app: Backendpy = app\n self.context: dict[str, Any] = {}\n self.method: Optional[str] = None\n self.path: Optional[str] = None\n self.root_path: Optional[str] = None\n self.scheme: Optional[str] = None\n self.server: Optional[dict[str, Any]] = None\n self.client: Optional[dict[str, Any]] = None\n self.headers: Optional[dict[str, str]] = None\n self.url_vars: Optional[dict[str, str]] = url_vars\n self.params: Optional[dict[str, str | list[str]]] = None\n self.form: Optional[dict[str, str | list[str]]] = None\n self.json: Optional[dict[str, Any]] = None\n self.files: Optional[dict[str, dict]] = None\n self.body: Optional[bytes] = None\n self.cleaned_data: Optional[dict[str, Any]] = None\n self._apply_scope(scope)\n if body:\n self._apply_body(body)\n\n def _apply_scope(self, scope: Mapping[str, Any]) -> None:\n \"\"\"Set request information from HTTP connection scope.\"\"\"\n if scope.get('server'):\n self.server = {'host': scope['server'][0],\n 'port': scope['server'][1]}\n if scope.get('client'):\n self.client = {'ip': scope['client'][0],\n 'port': scope['client'][1]}\n self.method = scope['method']\n self.path = scope['path']\n self.root_path = scope['root_path']\n self.scheme = scope['scheme']\n self.headers = {k.decode(): v.decode() for k, v in scope['headers']}\n if scope.get('query_string'):\n self.params = {k: (v[-1] if not k.endswith('[]') else v)\n for k, v in parse_qs(scope['query_string'].decode('utf8')).items()}\n\n def _apply_body(self, body: bytes) -> None:\n \"\"\"Set request body.\"\"\"\n if self.headers is None:\n raise Exception('Request information is not applied.')\n if self.headers.get('content-type') == 'application/json':\n self.json = from_json(body)\n elif self.headers.get('content-type') == 'application/x-www-form-urlencoded':\n self.form = {k: (v[0] if len(v) == 1 else v)\n for k, v in parse_qs(body.decode('utf8')).items()}\n elif self.headers.get('content-type') == 'multipart/form-data':\n json_parts = dict()\n form_parts = dict()\n file_parts = dict()\n text_parts = dict()\n for part in BytesParser().parsebytes(body).get_payload():\n part_type = part.get_content_type()\n if part_type == 'application/json':\n json_parts[part.get_param(param='name', header='content-disposition')] = \\\n from_json(part.get_payload())\n elif part_type == 'application/x-www-form-urlencoded':\n form_parts[part.get_param(param='name', header='content-disposition')] = \\\n {k: (v[0] if len(v) == 1 else v)\n for k, v in parse_qs(part.get_payload().decode('utf8')).items()}\n elif part_type == 'application/octet-stream':\n file_parts[part.get_param(param='name', header='content-disposition')] = \\\n {'content': part.get_payload(),\n 'file-name': part.get_param(param='filename', header='content-disposition'),\n 'content-type': part.get_content_subtype()} # Todo: test\n elif part_type == 'text/plain':\n text_parts[part.get_param(param='name', header='content-disposition')] = \\\n str(part.get_payload(decode=True))\n if json_parts:\n self.json = json_parts if len(json_parts) > 1 else json_parts[0]\n if form_parts:\n self.form = form_parts if len(form_parts) > 1 else form_parts[0]\n if file_parts:\n self.files = file_parts\n if text_parts:\n self.body = text_parts if len(text_parts) > 1 else text_parts[0]\n else:\n self.body = body\n","sub_path":"backendpy/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":7425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"286853431","text":"from __future__ import print_function\nfrom __future__ import absolute_import\n\nfrom tests.test_base import *\nfrom qgate.qasm.script import *\nfrom qgate.qasm.qelib1 import *\n\nclass TestUnaryGateBase(SimulatorTestBase) :\n\n @classmethod\n def setUpClass(cls):\n if cls is TestUnaryGateBase:\n raise unittest.SkipTest()\n super(TestUnaryGateBase, cls).setUpClass()\n \n def run_sim(self) :\n sim = self._run_sim()\n return sim.get_qubits().get_states(qgate.simulator.prob)\n \n def test_id_gate(self) :\n new_program()\n qregs = allocate_qreg(1)\n op(a(qregs))\n probs = self.run_sim()\n self.assertEqual(probs[0], 1.)\n \n def test_pauli_gate(self) :\n new_program()\n qregs = allocate_qreg(1)\n op(x(qregs))\n probs = self.run_sim()\n self.assertEqual(probs[1], 1.)\n \n def test_pauli_gate_2(self) :\n new_program()\n qregs = allocate_qreg(1)\n op(x(qregs), x(qregs))\n probs = self.run_sim()\n self.assertEqual(probs[0], 1.)\n \n def test_hadmard_gate(self) :\n new_program()\n qregs = allocate_qreg(1)\n op(h(qregs))\n probs = self.run_sim()\n self.assertAlmostEqual(probs[0], 0.5)\n self.assertAlmostEqual(probs[1], 0.5)\n \n def test_hadmard_gate2(self) :\n new_program()\n qregs = allocate_qreg(1)\n op(h(qregs), h(qregs))\n probs = self.run_sim()\n self.assertAlmostEqual(probs[0], 1)\n self.assertAlmostEqual(probs[1], 0.)\n\n def test_pauli_gate_multi_qubits(self) :\n for n_qubits in range(1, 11) :\n new_program()\n qregs = allocate_qreg(n_qubits)\n op(x(qregs))\n probs = self.run_sim()\n self.assertAlmostEqual(probs[(1 << n_qubits) - 1], 1)\n\n def test_hadmard_gate_multi_qubits(self) :\n for n_qubits in range(1, 11) :\n new_program()\n qregs = allocate_qreg(n_qubits)\n op(h(qregs))\n probs = self.run_sim()\n n_states = 1 << n_qubits\n for idx in range(n_states) :\n self.assertAlmostEqual(probs[idx], 1. / n_states)\n\n def test_hadmard_gate_2_qubits(self) :\n n_qubits = 2\n new_program()\n qregs = allocate_qreg(n_qubits)\n op(h(qregs))\n probs = self.run_sim()\n n_states = 1 << n_qubits\n for idx in range(n_states) :\n self.assertAlmostEqual(probs[idx], 1. / n_states)\n\n\nimport sys\nthis = sys.modules[__name__]\ncreateTestCases(this, 'TestUnaryGate', TestUnaryGateBase)\n \nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_unary_gate.py","file_name":"test_unary_gate.py","file_ext":"py","file_size_in_byte":2690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"552170887","text":"import mathutils\nimport math\nimport bpy, types, bmesh\n\nimport sys\nimport os.path\nimport time\nfrom typing import List\n\nfrom . import model3doLoader\nfrom .utils import *\nfrom .model3do import (\n Model,\n GeometryMode,\n LightMode,\n TextureMode,\n ModelMesh,\n FaceType\n)\n\nfrom ijim.material.material import importMatFile\nfrom ijim.utils.utils import *\n\ndef getObjByName(name):\n if name in bpy.context.scene.objects:\n return bpy.context.scene.objects[name]\n for o in bpy.context.scene.objects:\n if name == stripOrderPrefix(o.name):\n return o\n raise ValueError(\"Could not find object '{}'\".format(name))\n\ndef _get_encoded_face_prop(prop):\n return str(int(prop)).encode('utf-8')\n\ndef _get_radius_obj(name):\n try:\n return bpy.context.scene.objects[name]\n except:\n return None\n\n\ndef _set_obj_rotation(obj, rotation):\n setObjEulerRotation(obj, rotation)\n\ndef _set_obj_pivot(obj, pivot):\n # note: this function might be worng, load gen_chicken.3do to see the outcome\n if pivot[0] == 0 and pivot[1] == 0 and pivot[2] == 0:\n return\n\n pc = obj.constraints.new('PIVOT')\n pc.rotation_range = 'ALWAYS_ACTIVE'\n pc.use_relative_location = True\n pc.owner_space = 'LOCAL'\n pc.offset = -mathutils.Vector(pivot)\n obj.location += mathutils.Vector(pivot)\n\ndef _make_radius_obj(name, parent, radius):\n if name in bpy.data.meshes:\n mesh = bpy.data.meshes[name]\n else:\n mesh = bpy.data.meshes.new(name)\n ro = bpy.data.objects.new(name , mesh)\n ro.draw_type = 'WIRE'\n ro.hide = True\n ro.parent_type = 'OBJECT'\n ro.parent = parent\n bpy.context.scene.objects.link(ro)\n\n bm = bmesh.new()\n bmesh.ops.create_uvsphere(bm, u_segments=32, v_segments=16, diameter=radius)\n bm.to_mesh(mesh)\n bm.free()\n\ndef _set_obj_radius(obj, radius):\n _make_radius_obj(kObjRadius + obj.name, obj, radius)\n\ndef _set_mesh_radius(obj, radius):\n _make_radius_obj(kMeshRadius + obj.name, obj, radius)\n\n\ndef _make_mesh(mesh3do: ModelMesh, mat_list: List):\n mesh = bpy.data.meshes.new(mesh3do.name)\n\n faces = []\n for face in mesh3do.faces:\n faces += [face.vertexIdxs]\n\n # Construct mesh\n mesh.from_pydata(mesh3do.vertices, [], faces)\n mesh.show_double_sided = True\n\n bm = bmesh.new()\n bm.from_mesh(mesh)\n bm.faces.ensure_lookup_table()\n\n uv_layer = bm.loops.layers.uv.verify()\n bm.faces.layers.tex.verify()\n\n #face_color_layer = bm.loops.layers.color.new(\"face_color_\")# + str(mesh3do.idx) + str(face.index))\n\n # Face's custom property tags\n tag_face_type = getBmeshFaceLayer(bm.faces, kFType)\n tag_face_gm = getBmeshFaceLayer(bm.faces, kGeometryMode)\n tag_face_lm = getBmeshFaceLayer(bm.faces, kLightingMode)\n tag_face_tm = getBmeshFaceLayer(bm.faces, kTextureMode)\n\n # Set mesh materials and UV map\n for face in bm.faces:\n face3do = mesh3do.faces[face.index]\n\n # Set custom property for face type, geometry, light, texture mode\n face[tag_face_type] = _get_encoded_face_prop(face3do.type)\n face[tag_face_gm] = _get_encoded_face_prop(face3do.geometryMode)\n face[tag_face_lm] = _get_encoded_face_prop(face3do.lightMode)\n face[tag_face_tm] = _get_encoded_face_prop(face3do.textureMode)\n\n # Set face normal\n face.normal = mesh3do.faces[face.index].normal\n\n # Set face material index\n mat_name = mat_list[face3do.materialIdx]\n mat = getGlobalMaterial(mat_name)\n if not mat.name in mesh.materials:\n mesh.materials.append(mat)\n face.material_index = mesh.materials.find(mat.name)\n\n # Set face texture\n if not mat.texture_slots[0].texture is None:\n tex = mat.texture_slots[0].texture\n img = tex.image\n tex_layer = bm.faces.layers.tex[uv_layer.name]\n face[tex_layer].image = img\n\n # Set vertices color and face uv map\n for idx, loop in enumerate(face.loops): # update vertices\n vidx = loop.vert.index\n loop.vert.normal = mesh3do.normals[vidx]\n #loop[face_color_layer] = mesh3do.verticesColor[vidx] # don't vertex color because blender can show only 8 color layers\n\n # Set UV coordinates\n luv = loop[uv_layer]\n uv = mesh3do.textureVertices[face3do.texVertexIdxs[idx]]\n luv.uv = (uv[0], -uv[1]) # Note: Flipped v\n\n bm.to_mesh(mesh)\n bm.free()\n\n mesh.update()\n return mesh\n\n\n\n\ndef getObjRadiusObj(obj):\n return _get_radius_obj(kObjRadius + obj.name)\n\ndef getMeshRadiusObj(mesh):\n obj = getObjByName(mesh.name)\n return _get_radius_obj(kMeshRadius + obj.name)\n\ndef importObject(file_path, mat_paths = [], b_preserve_order = True, b_clear_scene = True):\n print(\"importing 3DO: %r...\" % (file_path), end=\"\")\n startTime = time.process_time()\n\n model = model3doLoader.load(file_path)\n if len(model.geosets) == 0: return\n\n if b_clear_scene:\n clearAllScenes()\n\n # Load model's textures\n importMaterials(model.materials, getDefaultMatFolders(file_path) + mat_paths)\n\n # Create model's meshes\n meshes3do = model.geosets[0].meshes\n for mesh3do in meshes3do:\n\n mesh = _make_mesh(mesh3do, model.materials)\n meshName = mesh3do.name\n obj = bpy.data.objects.new(meshName, mesh)\n\n # Set mesh radius object, draw type, custom property for lighting and texture mode\n _set_mesh_radius(obj, mesh3do.radius)\n obj.draw_type = getDrawType(mesh3do.geometryMode)\n obj[kLightingMode] = mesh3do.lightMode\n obj[kTextureMode] = mesh3do.textureMode\n obj.draw_bounds_type = 'SPHERE'\n bpy.context.scene.objects.link(obj)\n\n\n # Update model's mesh hierarchy\n for idx, meshNode in enumerate(model.hierarchyNodes):\n meshIdx = meshNode.meshIdx\n\n # Get node's mesh\n if meshIdx == -1:\n obj = bpy.data.objects.new(meshNode.name, None)\n obj.empty_draw_size = (0.0)\n bpy.context.scene.objects.link(obj)\n else:\n meshName = model.geosets[0].meshes[meshIdx].name\n obj = getObjByName(meshName)\n\n # Make obj name prefixed by idx num.\n # This will make the hierarchy of model 3do ordered by index instead by name in Blender.\n obj.name = makeOrderedName(obj.name, idx, len(model.hierarchyNodes)) if b_preserve_order else obj.name\n\n # Set mode's parent mesh\n if meshNode.parentIdx != -1:\n pnode = model.hierarchyNodes[meshNode.parentIdx]\n obj.parent_type = 'OBJECT'\n if pnode.meshIdx == -1:\n pname = pnode.name\n else:\n pname = model.geosets[0].meshes[pnode.meshIdx].name\n obj.parent = getObjByName(pname)\n\n bpy.context.scene.update()\n\n # Set hierarchy node flags, type and name\n obj[kHnFlags] = meshNode.flags\n obj[kHnType] = meshNode.type\n obj[kHnName] = meshNode.name\n\n # Set node position, rotation and pivot\n obj.location = meshNode.position\n _set_obj_rotation(obj, meshNode.rotation)\n _set_obj_pivot(obj, meshNode.pivot)\n\n\n # Set model's insert offset and radius\n baseObj = bpy.data.objects.new(model.name, None)\n baseObj.empty_draw_size = (0.0)\n bpy.context.scene.objects.link(baseObj)\n\n baseObj.location = model.insert_offset\n _set_obj_radius(baseObj, model.radius)\n\n firstCName = model.hierarchyNodes[0].name\n firstChild = getObjByName(firstCName)\n firstChild.parent_type = 'OBJECT'\n firstChild.parent = baseObj\n\n # Add model to the \"Model3do\" group\n if kGModel3do in bpy.data.groups:\n group = bpy.data.groups[kGModel3do]\n else:\n group = bpy.data.groups.new(kGModel3do)\n group.objects.link(baseObj)\n\n print(\" done in %.4f sec.\" % (time.process_time() - startTime))\n return baseObj","sub_path":"ijim/model/model3doImporter.py","file_name":"model3doImporter.py","file_ext":"py","file_size_in_byte":7958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"85891702","text":"'''\nModule: :samp:`grid_tools`\n--------------------------\n\nTools for transforming between structured and unstructured grids, and spectral analysis.\nRay data can be viewed as known on the nodes of an unstructured grid.\nOur notion of a structured grid is that the data is known at the cell center.\nThe set of cell centers are the nodes. The nodes are separated by cell walls.\nPlotting voxels can be considered visualizations of a cell.\n'''\nimport numpy as np\nimport scipy.interpolate\nimport scipy.linalg\nimport pyopencl\nimport pyopencl.array\n\ndef cyclic_center_and_width(node_low,node_high):\n\t'''Return the center node and wall-to-wall width of a cyclic set of nodes.\n\tOnce cyclic nodes are generated the high node is lost.\n\tThis function helps us remember not to use the generated nodes to find the center.\n\tSee also cyclic_nodes(...) below.'''\n\treturn 0.5*(node_low + node_high) , node_high - node_low\n\ndef cyclic_nodes(node_low,node_high,num_nodes):\n\t'''Generate nodes suitable for periodic functions.\n\tThe requested low node is included, the high node is excluded.\n\tThe low and high nodes should resolve to the same point, e.g. 0 and 2*pi.\n\tFrequency nodes are arranged in unrolled FFT fashion, e.g., [+-2,-1,0,1].'''\n\tif num_nodes==1:\n\t\treturn np.array([0.5*node_low + 0.5*node_high])\n\telse:\n\t\tdx = (node_high - node_low)/num_nodes\n\t\treturn np.linspace(node_low,node_high-dx,num_nodes)\n\ndef cell_centers(wall_pos_low,wall_pos_high,cells_between):\n\t'''Generate nodes between two cell wall positions.\n\tNumber of nodes between the two walls must be given.'''\n\tdx = (wall_pos_high - wall_pos_low)/cells_between\n\treturn np.linspace(wall_pos_low+0.5*dx,wall_pos_high-0.5*dx,cells_between)\n\ndef cell_walls(node_low,node_high,nodes_between,default_voxel_width=1000.0):\n\t'''Generate cell walls bracketing two nodes.\n\tNumber of nodes between the walls must be given.'''\n\tif nodes_between==1:\n\t\tdx = default_voxel_width\n\telse:\n\t\tdx = (node_high - node_low)/(nodes_between-1)\n\treturn np.linspace(node_low-0.5*dx,node_high+0.5*dx,nodes_between+1)\n\ndef hypersurface_idx(ary,axis,cell):\n\t# Form tuple that indexes a hypersurface\n\tidx_list = [slice(None),]*len(ary.shape)\n\tidx_list[axis] = (cell,)\n\treturn tuple(idx_list)\n\ndef Smooth1D(dist,passes,ax=0):\n\ttup_low_ghost = hypersurface_idx(dist,ax,0)\n\ttup_low = hypersurface_idx(dist,ax,1)\n\ttup_high_ghost = hypersurface_idx(dist,ax,dist.shape[ax]-1)\n\ttup_high = hypersurface_idx(dist,ax,dist.shape[ax]-2)\n\t# Carry out smoothing passes\n\tfor i in range(passes):\n\t\tdist_above = np.roll(dist,-1,axis=ax)\n\t\tdist_below = np.roll(dist,1,axis=ax)\n\t\tdist_above[tup_high_ghost] = dist_above[tup_high]\n\t\tdist_below[tup_low_ghost] = dist_below[tup_low]\n\t\tdist = 0.25*dist_above + 0.25*dist_below + 0.5*dist\n\treturn dist\n\n# Both interpolation and binning grids return array in c-order\n# That is, y changes faster in memory, per z[x][y]\n# The plot extent that is returned has [xmin,xmax,ymin,ymax]\n# When interfacing with matplotlib imshow routine, the array axes should be swapped.\n# This will result in the correct labeling of the axes.\n# imshow(z,extent=[x0,x1,y0,y1]) gives the wrong labelling.\n# imshow(z.swapaxes(0,1),extent=[x0,x1,y0,y1]) gives the right labelling.\n\n# To avoid confusion please swap the axes only within the imshow function call.\n\ndef AddGhostCells(a,nodes,ax):\n\tnew_cells = a[hypersurface_idx(a,ax,0)]\n\tnew_nodes = [nodes[0] - (nodes[1]-nodes[0])]\n\tex_nodes = np.concatenate((new_nodes,nodes))\n\tex_a = np.concatenate((new_cells,a),axis=ax)\n\treturn ex_a,ex_nodes\n\ndef DataFromGrid(w,x,y,wn,xn,yn,the_data):\n\t'''Form irregular data from a regular grid. OK if yn.shape[0]=1.\n\tw,x,y are the coordinates of the irregular data points.\n\tIrregular points can be slightly outside the grid (extrapolation is used).\n\twn,xn,yn are arrays of nodes which must be regularly spaced.\n\tthe_data contains values on the regular grid with shape (w,x,y).\n\tAny coordinate transformations must happen externally.'''\n\tif wn.shape[0]==1:\n\t\traise ValueError('Cannot relaunch rays with monochromatic data.')\n\tif xn.shape[0]==1:\n\t\traise ValueError('Missing spatial dimension x.')\n\tif yn.shape[0]==1:\n\t\tyng = np.linspace(np.min(y),np.max(y),2)\n\t\tex_data = np.concatenate((the_data,the_data),axis=2)\n\telse:\n\t\tyng = yn\n\t\tex_data = the_data\n\tobj = scipy.interpolate.RegularGridInterpolator((wn,xn,yng),ex_data,bounds_error=False,fill_value=None)\n\tpts = np.zeros(w.shape+(3,))\n\tpts[...,0] = w\n\tpts[...,1] = x\n\tpts[...,2] = y\n\treturn obj(pts)\n\ndef CylGridFromInterpolation(w,x,y,vals,wn=1,xn=100,yn=100,fill=0.0):\n\t'''Special treatment for points that tend to lie on cylindrical nodes.\n\tFrequency and azimuth are binned, radial data is interpolated.\n\tFill value for r=ww[i],w=wy[j],y=ww[i],wT1 thanks to scipy packing and symmetry\n\t\t\ta_band_upper[1,:] = T2\n\t\t\tself.vals[:Nk,m],Hi[:,:,m] = scipy.linalg.eig_banded(a_band_upper,select='i',select_range=(Nr-Nk,Nr-1))\n\t\t# Set eigenvalues of negative modes (they are the same as corresponding positive modes)\n\t\t# Modes are packed in usual FFT fashion, so negative indices work as expected.\n\t\tfor m in range(1,mmax):\n\t\t\tself.vals[:Nk,-m] = self.vals[:Nk,m]\n\t\t\tHi[:,:,-m] = Hi[:,:,m]\n\t\tself.H = np.ascontiguousarray(Hi.swapaxes(0,1))\n\t\tself.cl = cl\n\t\tself.H_dev = None\n\t\tself.L_dev = None\n\t\tself.scratch_dev = None\n\tdef AllocateDeviceMemory(self,data_shape):\n\t\tself.H_dev = pyopencl.array.to_device(self.cl.q,self.H)\n\t\tself.L_dev = pyopencl.array.to_device(self.cl.q,self.Lambda)\n\t\tself.scratch_dev = pyopencl.array.empty(self.cl.q,data_shape,np.complex)\n\t\tself.cl.q.finish()\n\tdef FreeDeviceMemory(self):\n\t\tself.H_dev = None\n\t\tself.L_dev = None\n\t\tself.scratch_dev = None\n\tdef kspacex(self,a):\n\t\tself.cl.program('fft').FFT_axis2(self.cl.q,a.shape[:2],None,a.data,np.int32(a.shape[2]))\n\t\tself.cl.program('fft').RootVolumeMultiply(self.cl.q,a.shape,None,a.data,self.L_dev.data)\n\t\tself.scratch_dev[...] = a.copy(queue=self.cl.q)\n\t\ta.fill(0.0,queue=self.cl.q)\n\t\tshp = ( a.shape[0] , self.Nk , a.shape[2] )\n\t\tself.cl.program('fft').RadialTransform(self.cl.q,shp,None,self.H_dev.data,self.scratch_dev.data,a.data,np.int32(a.shape[1]))\n\t\tself.cl.program('fft').RootVolumeDivide(self.cl.q,a.shape,None,a.data,self.L_dev.data)\n\t\tself.cl.q.finish()\n\tdef rspacex(self,a):\n\t\tself.cl.program('fft').RootVolumeMultiply(self.cl.q,a.shape,None,a.data,self.L_dev.data)\n\t\tself.scratch_dev[...] = a.copy(queue=self.cl.q)\n\t\tself.cl.program('fft').InverseRadialTransform(self.cl.q,a.shape,None,self.H_dev.data,self.scratch_dev.data,a.data,np.int32(self.Nk))\n\t\tself.cl.program('fft').RootVolumeDivide(self.cl.q,a.shape,None,a.data,self.L_dev.data)\n\t\tself.cl.program('fft').IFFT_axis2(self.cl.q,a.shape[:2],None,a.data,np.int32(a.shape[2]))\n\t\tself.cl.q.finish()\n\tdef trans(self,f,v):\n\t\tvc = np.ascontiguousarray(np.copy(v))\n\t\tif type(self.H_dev)==type(None):\n\t\t\tself.AllocateDeviceMemory(vc.shape)\n\t\t\tv_dev = pyopencl.array.to_device(self.cl.q,vc)\n\t\t\tf(v_dev)\n\t\t\tself.FreeDeviceMemory()\n\t\telse:\n\t\t\tv_dev = pyopencl.array.to_device(self.cl.q,vc)\n\t\t\tf(v_dev)\n\t\treturn v_dev.get()\n\tdef kspace(self,a):\n\t\tif len(a.shape)==3:\n\t\t\treturn self.trans(self.kspacex,a)\n\t\telse:\n\t\t\tfor k in range(a.shape[3]):\n\t\t\t\ta[...,k] = self.trans(self.kspacex,a[...,k])\n\t\t\treturn a\n\tdef rspace(self,a):\n\t\tif len(a.shape)==3:\n\t\t\treturn self.trans(self.rspacex,a)\n\t\telse:\n\t\t\tfor k in range(a.shape[3]):\n\t\t\t\ta[...,k] = self.trans(self.rspacex,a[...,k])\n\t\t\treturn a\n\tdef kr2(self):\n\t\treturn -self.vals\n\ndef WignerTransform(A,ds):\n\tN = A.shape[0]\n\tM = np.int(N/2) + 1\n\tcorr = np.zeros((N,M)).astype(np.complex)\n\tAi = np.zeros(N*2-1).astype(np.complex)\n\tAi[::2] = A\n\tAi[1::2] = 0.5*(np.roll(Ai,1)+np.roll(Ai,-1))[1::2]\n\tfor j in range(M):\n\t\tcorr[:,j] = (np.conj(np.roll(Ai,j))*np.roll(Ai,-j))[::2]\n\twig = np.fft.hfft(corr,axis=1)*ds/(2*np.pi)\n\treturn np.fft.fftshift(wig,axes=1)\n","sub_path":"grid_tools.py","file_name":"grid_tools.py","file_ext":"py","file_size_in_byte":14341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"238878984","text":"'''\nCreated on 08-Feb-2013\n\n@author: anand\n\nA set of methods to assist with folders and validation of folders\n'''\nimport logging\nfrom os.path import abspath, getmtime, splitext, dirname, exists, join, isdir\nfrom fnmatch import fnmatch\nimport os\nimport zipfile\nimport re\nimport tempfile\n\n# since we are a library, let's add null handler to root to allow us logging\n# without getting warnings about no handlers specified\nlogging.getLogger().addHandler(logging.NullHandler())\n\nclass DirUtils(object):\n \n def is_updated(self, file_path, timestamp):\n '''\n Checks if file_path's modified time is newer than timestamp\n :param str file_path: str containing the file_path (absolute or relative to current working dir) \n :type float timestamp: str or float containing the timestamp against which the file is to be checked\n :returns: boolean. TypeError if timestamp cannot be converted to float. OSError if file does not exist \n '''\n if isinstance(timestamp, str):\n timestamp = float(timestamp)\n return getmtime(file_path) > timestamp\n \n def read_file(self, source, max_size):\n '''\n Read the file specified by the source having size less than max_size specified and returns the byte code.\n :param str or File-like object source: A File-like object or a name of a file \n :param int max_size: The max size of the file to be read. If max-size is None, read the whole file\n :returns: bytes\n '''\n if hasattr(source, 'read'): # if file-like object, read from it.\n return source.read() if max_size == None else source.read(max_size) \n with open(source, 'rb') as fp: # opening in binary mode\n return fp.read() if max_size == None else fp.read(max_size) \n \n def get_zip_name(self, filename):\n '''\n Returns a zip name based of filename. e.g. a/b/c.pr returns a/b/c.zip \n :param str filename: Filename whos zipname is to be returned\n :returns: zipfilename (e.g. a/b/c.pr returns a/b/c.zip, a/b/c returns a/b/c.zip)\n '''\n base, _ = splitext(filename)\n return base + '.zip'\n\n def get_dir_name(self, source):\n '''\n Returns the directory component of a pathname\n :param str source: Path whose dir name is to be returned\n :returns: str\n '''\n return dirname(source)\n \n def make_zip(self, path, name, glob='*', regexp=None, recursive=False):\n ''' \n Creates a zip file and populates with files that match either glob (shell filename pattern) or regular expression.\n :param str path: The path where the zip is to be created.\n :param str name: The name of the zip file to be created.\n :param str glob: Pattern for file matching (within path)\n :param str regexp: regular Expression for file matching\n :param bool recursive: Determines whether the method traverses path recursively or not.\n :returns: Path to the generated zip file\n '''\n \n zipfilename = os.path.join(path, name) #TODO:The zip files should lie in some other folder.\n \n if os.path.exists(zipfilename):\n os.remove(zipfilename)\n \n files = self.get_files(path, glob=glob, regexp=regexp, recursive=recursive)\n with zipfile.ZipFile(zipfilename, mode=\"w\") as zipf:\n [ map(lambda x: zipf.write(os.path.join(path, x), arcname=x), fl) for fl in [ map(lambda x: os.path.join(dirname, x), flist) for dirname, flist in files ]]\n return zipfilename\n \n def make_relative(self, base_path, path, user=None):\n '''\n Returns the relative portion of the path relative to base_path\n :param str base_path: The base from where the relative path is to be calculated.\n :param str path: The path to which the relative path is to be calculated.\n :param str user: Username of the user that is currently logged in can be retrived by bottle.request.environ\n :returns: str\n '''\n base_path = self.resolve_path(base_dir=base_path, path='.', user=user)\n subpath = os.path.relpath(path, base_path)\n if os.sep != '/':\n subpath = subpath.replace(os.sep, '/')\n return subpath\n \n def validate_dir(self, base_dir, path=\".\", sub_dir=None, check_exists=True):\n ''' \n Returns True if path is a valid directory, else raises ValueError\n dir has to be a subdir base_dir or base_dir/sub_dir if sub_dir is not None\n :param str base_dir: The base directory.\n :param str path: The relative path.\n :param str sub_dir: An optional sub_dir which is appended to base_dir to create a chroot\n :param bool check_exists: Also checks if the path really exists or not\n :returns: bool\n '''\n newpath = self.resolve_path(base_dir, path, sub_dir)\n if check_exists:\n if not exists(newpath) or not isdir(newpath):\n raise ValueError('{} is not a valid directory'.format(path))\n return True\n\n def resolve_path(self, base_dir, path, sub_dir=None):\n ''' \n Converts relative directory to a more complete path (either absolute or relative) based of base directory. Validates that the\n path resides within base_dir. An option sub_dir, if provided, is added to base_dir. \n The purpose of this is to mimic a chroot and ensure that the given path exists completely within the chroot of (base_dir/sub_dir).\n In other words, by relative addressing such as path = ../../../xyz, a request to unauthorized areas cannot be made\n :param str base_dir - The base directory for all operations.\n :param str path - the path obtained from the client. May be an absolute path\n :param str sub_dir: An optional sub_dir which is appended to base_dir to create a chroot\n :returns: Complete resolved path as str\n '''\n absprefix = abspath(join(base_dir, sub_dir)) if sub_dir is not None else abspath(base_dir)\n newpath = abspath(join(absprefix, path))\n if not newpath.startswith(absprefix):\n raise ValueError('path parameter '+path+' invalid.' + ' base = ' + absprefix + ' newpath = ' + newpath)\n return newpath\n \n def get_files(self, path, glob='*', regexp=None, recursive=False):\n '''\n Gets files that match either glob (shell filename pattern) or regular expression. \n \n :param str path: The path from where the files are to be fetched.\n :param str glob: Pattern for file matching\n :param str regexp: regular Expression for file matching\n :param bool recursive: determines whether the method traverses path recursively or not\n :returns: List of files as List of str\n '''\n self.validate_dir(base_dir=path, path='.') # check if this is a valid/accessible dir within the base_dir (i.e path) \n files = list(os.walk(path)) if recursive else [next(os.walk(path, topdown=True))]\n if regexp == None:\n files = [(x[len(path)+1:].replace('\\\\', '/'), list(filter(lambda f: fnmatch(f, glob), z))) for x, _, z in files]\n else:\n prog = re.compile(regexp)\n files = [(x[len(path)+1:].replace('\\\\', '/'), list(filter(lambda f: prog.match(f), z))) for x, _, z in files]\n \n files = list(filter(lambda x: x[1] != [], files))\n return files\n \n def make_dir(self, abspath, mode=0o770):\n '''\n Creates a dir if none exists. Does nothing if a directory exists. First checks if path is valid\n returns True on success. Raises error cannot be created. ValueError is it is an invalid (or restricted) path\n \n :param abspath: The path to the directory to be created,should be the fully qualified path\n @type abspath: str\n \n :param mode: Permissions of the folder\n @type mode: oct\n \n :returns: bool\n '''\n self.validate_dir(base_dir=abspath, check_exists=False)\n \n if exists(abspath) and isdir(abspath):\n return True\n \n os.makedirs(abspath, mode)\n return True\n \n def make_temp_dir(self, path, sub_dir=None, prefix=''):\n '''\n Creates a temp directory in the specified path\n \n :param path: The path to where the temp dir is to be created.\n @type path: str\n \n :param user: Username of the user that is currently logged in can be retrived by bottle.request.environ\n @type user: str\n \n :param prefix: The prefix to be attached to the temp dir.\n @type prefix: str\n \n :returns: The complete path to the new dir as str\n '''\n \n base_path = self.resolve_path(base_dir=path, path='.', sub_dir=sub_dir)\n self.make_dir(base_path)\n new_path = tempfile.mkdtemp(prefix=prefix, dir=base_path)\n self.validate_dir(new_path, check_exists=True) \n return new_path\n \n def file_write(self, abspath, filename, fp, mode=\"wb\"):\n '''\n Write a file available in a filelike object.\n \n :param abspath: absolute path\n @type abspath: str\n \n :param filename: name of the file\n @type filename: str\n \n :param fp: file-like object which has the data to be written\n @type fp: file pointer\n \n :param mode: mode to open the target file in\n @type param_mode: str\n '''\n max_read=100*1024\n os.umask(0o007)\n with open(os.path.join(abspath, filename), mode) as fout:\n byts = fp.read(max_read)\n while byts not in [ b'', '']: \n fout.write(byts)\n byts = fp.read(max_read)\n \n \n def get_source_prefix(self, filename):\n '''\n Returns the name of any given file without the extension.\n \n :param filename: Name of the file.\n @type filename: str\n \n :returns: str \n '''\n fname = os.path.basename(filename)\n return os.path.splitext(fname)[0]\n\n\nif __name__ == '__main__':\n pass","sub_path":"boots/common/dirutils.py","file_name":"dirutils.py","file_ext":"py","file_size_in_byte":10217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"440394401","text":"from django.urls import path, include\nfrom django.contrib import admin\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nadmin.autodiscover()\n\n\n\nurlpatterns = [\n path('', include('Simplemooc.core.urls', namespace='core')),\n path('conta/', include('Simplemooc.accounts.urls', namespace='accounts')),\n path('cursos/', include('Simplemooc.courses.urls', namespace='courses')),\n path('forum/', include('Simplemooc.forum.urls', namespace='forum')),\n path('admin/', admin.site.urls),\n\n]\nif settings.DEBUG:\n urlpatterns +=static(settings.MEDIA_URL , document_root=settings.MEDIA_ROOT)\n\n\n","sub_path":"Simplemooc/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"188857587","text":"\nglobal g\ng = 10\nprint(g)\n\n\ndef soma(x,y):\n var = x + y + g#se quiser fazer sem variavel, só colocar a soma e retornar\n return var\n #return x + y - sem precisar da variável\nx = soma(10,5)\nprint(x)\n\n#a = soma(10,5)\n#b = soma(a,5)\n#print(b)\n\n#Variável Global - local que pode mudar os valores em diferentes contextos\n\n\n\n\n\n","sub_path":"variavelglobal.py","file_name":"variavelglobal.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"621330309","text":"from __future__ import absolute_import\n\nfrom .bcbio import MultiqcModule\nfrom multiqc import config\n\n\n# Add search patterns and config options for the things that are used in MultiQC_bcbio\ndef multiqc_bcbio_config():\n \"\"\" Set up MultiQC config defaults for this package \"\"\"\n bcbio_search_patterns = {\n 'bcbio/metrics': {'fn': '*_bcbio.txt'},\n 'bcbio/coverage': {'fn': '*_bcbio_coverage.txt'},\n 'bcbio/coverage_avg': {'fn': '*_bcbio_coverage_avg.txt'},\n 'bcbio/variants': {'fn': '*_bcbio_variants.txt'},\n 'bcbio/target': {'fn': 'target_info.yaml'},\n 'bcbio/qsignature': {'fn': '*bcbio_qsignature.ma'},\n 'bcbio/vcfstats': {'fn': '*_bcbio_variants_stats.txt'},\n 'bcbio/seqbuster': {'contents': 'seqbuster'},\n 'bcbio/umi': {'fn': '*_umi_stats.yaml'},\n 'bcbio/viral': {'fn': '*viral*-counts.txt'},\n 'bcbio/damage': {'fn': '*damage.yaml'},\n }\n config.update_dict(config.sp, bcbio_search_patterns)\n\n config.fn_clean_exts.append({'type': 'regex', 'pattern': '_bcbio.*'})\n \n config.update_dict(config.table_columns_visible, {\n 'FastQC': {\n 'percent_duplicates': False,\n 'total_sequences': False,\n },\n 'QualiMap': {\n 'percentage_aligned': False,\n },\n 'Samtools Stats': {\n 'non-primary_alignments': False,\n 'reads_mapped': False,\n 'reads_mapped_percent': False,\n 'raw_total_sequences': False,\n }\n })\n","sub_path":"multiqc_bcbio/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"384500054","text":"#!/usr/bin/env python3\n\n# marquery - CLI tool for accessing latest financial market info\n# Copyright (C) 2018 Srdjan Rajcevic [srdjan[@]rajcevic.net]\n\n# Uses free AlphaVantage Inc. API [www.alphavantage.co]\n# Author does not guarantee for accuracy of data. Use at your own risk.\n\nimport argparse\nimport requests\nimport sys\nfrom decimal import Decimal\n\n# URL & API KEY - Change URL if necessary, enter your own API key\n\nurl = \"https://www.alphavantage.co/query\"\napikey = \"\"\n\n# Functions \n\ndef dump_file(out,dump):\n filename = str(dump[0])\n try:\n f = open(filename,\"w\")\n f.write(str(out))\n f.close()\n except Exception as e:\n print(\"Error: {}.\".format(e))\n\ndef get_url(url,urlparams):\n try:\n req = requests.get(url, params=urlparams)\n out = req.json()\n return out\n except requests.exceptions.BaseHTTPError as e:\n print(e)\n sys.exit()\n\ndef handle_stock(url,apikey,symbol,interval,dump):\n function = \"TIME_SERIES_INTRADAY\"\n if interval == None:\n interval = \"1min\"\n else:\n interval = interval + \"min\"\n outputsize = \"compact\"\n datatype = \"json\"\n urlparams = {'function' : function, 'symbol' : symbol, 'interval' : interval, 'outputsize' : outputsize, 'datatype' : datatype, 'apikey' : apikey}\n\n out = get_url(url,urlparams)\n\n if dump != None:\n dump_file(out,dump)\n sys.exit()\n else:\n try:\n meta = out['Meta Data']\n ts_key = \"Time Series (\" + interval + \")\"\n ts_data = out[ts_key]\n last_data = ts_data[next(iter(ts_data))]\n except Exception as e:\n print(\"Error: {}. Try again later.\".format(e))\n sys.exit()\n\n info = meta['1. Information']\n symb = meta['2. Symbol']\n time = meta['3. Last Refreshed']\n\n ls_open = last_data['1. open']\n ls_high = last_data['2. high']\n ls_low = last_data['3. low']\n ls_close = last_data['4. close']\n ls_volume = last_data['5. volume']\n\n\n print(\"\\n{}\".format(info))\n print(\"======================================\")\n print(\"Company exchange symbol: {}\".format(symb.upper()))\n print(\"Time: {}\\n\".format(time))\n print(\"Stock value (USD):\")\n print(\"======================================\")\n print(\"Open: {} | High: {} | Low: {} | Close: {} | Volume: {}\\n\".format(ls_open,ls_high,ls_low,ls_close,ls_volume))\n\ndef handle_crypto(url,apikey,symbol,market,dump):\n function = \"DIGITAL_CURRENCY_INTRADAY\"\n if market == None:\n market = \"EUR\"\n datatype = \"json\"\n\n urlparams = {'function' : function, 'symbol' : symbol, 'market' : market, 'datatype' : datatype, 'apikey' : apikey}\n\n out = get_url(url,urlparams)\n\n if dump != None:\n dump_file(out,dump)\n sys.exit()\n else:\n try:\n meta = out['Meta Data']\n information = meta['1. Information']\n dc_code = meta['2. Digital Currency Code']\n dc_name = meta['3. Digital Currency Name']\n m_code = meta['4. Market Code']\n m_name = meta['5. Market Name']\n time = meta['7. Last Refreshed']\n time_zone = meta['8. Time Zone']\n except Exception as e:\n print(\"Error: {}.Try again later.\".format(e))\n sys.exit()\n\n dc_data = out['Time Series (Digital Currency Intraday)']\n \n last_data = dc_data[next(iter(dc_data))]\n p_market = \"1a. price (\" + market.upper() + \")\"\n price_in_market = last_data[p_market]\n price_in_usd = last_data['1b. price (USD)']\n volume = last_data['2. volume']\n market_cap = last_data['3. market cap (USD)']\n\n print(\"\\n{}\".format(information))\n print(\"======================================\")\n print(\"Digital currency code: {}, ({})\".format(dc_code,dc_name))\n print(\"Market code: {}, ({})\".format(m_code,m_name))\n print(\"Time: {} | Time zone: {}\\n\".format(time,time_zone))\n print(\"Digital currency value:\")\n print(\"======================================\")\n print(\"Price in \" + market.upper() + \": {} | Price in USD: {} | Volume: {} | Market cap (USD): {}\\n\".format(price_in_market,price_in_usd,volume,market_cap))\n\ndef handle_fx(url,apikey,currencies,dump):\n function = \"CURRENCY_EXCHANGE_RATE\"\n from_currency = currencies[0]\n to_currency = currencies[1]\n\n urlparams = {'function' : function, 'from_currency' : from_currency, 'to_currency' : to_currency, 'apikey' : apikey}\n\n out = get_url(url,urlparams)\n\n if dump != None:\n dump_file(out,dump)\n sys.exit()\n else:\n try:\n info = out['Realtime Currency Exchange Rate']\n from_c = info['1. From_Currency Code']\n to_c = info['3. To_Currency Code']\n ex_rate = info['5. Exchange Rate']\n except Exception as e:\n print(\"Error: {}.Try again later.\".format(e))\n sys.exit()\n\n print(\"\\n1 {} = {} {}.\\n\".format(from_c.upper(),ex_rate,to_c.upper()))\n\n# Argument parser\n\nparser = argparse.ArgumentParser(description=\"CLI tool for accessing latest financial market info\")\ngroup = parser.add_mutually_exclusive_group()\n\ngroup.add_argument(\"-s\",\"--stock\", help=\"Stock exchange symbol\", type=str)\ngroup.add_argument(\"-c\",\"--crypto\",help=\"Cryptocurrency symbol\", type=str)\ngroup.add_argument(\"-f\",\"--fx\",help=\"Exchange rate FROM currency TO currency\",nargs=2,type=str)\nparser.add_argument(\"-m\", \"--market\", help=\"Choose market (default: EUR)\", type=str)\nparser.add_argument(\"-i\", \"--interval\", help=\"Show data from specific time interval (in minutes)\", type=str)\nparser.add_argument(\"-d\", \"--dump\", help=\"Dump query result in JSON format into DUMP file\", nargs=1)\n\nargs = parser.parse_args()\n\nif len(sys.argv) == 1:\n parser.print_usage()\n sys.exit()\nif args.stock != None:\n handle_stock(url,apikey,args.stock,args.interval,args.dump)\nelif args.crypto != None:\n handle_crypto(url,apikey,args.crypto,args.market,args.dump)\nelif args.fx != None:\n handle_fx(url,apikey,args.fx,args.dump)\n\n \n\n","sub_path":"marquery.py","file_name":"marquery.py","file_ext":"py","file_size_in_byte":6112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"201788877","text":"from lxml import html\nimport requests\nimport unicodedata\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, BigInteger, String\nfrom sqlalchemy.orm import sessionmaker\nfrom sys import argv\n\nengine = create_engine('mysql+mysqldb://unigamer:d3vsp3cs!@unigamer.net:3306/unigamer')\nBase = declarative_base()\nSession = sessionmaker(bind=engine)\nsession = Session()\n\nif len(argv) != 2:\n print(\"usage python ./classScraper.py \")\n print(\" where is: 2167 = Fall '16, 2171 = Winter '17, 2173 = Spring '17\")\n exit(0)\n\ncurrentTerm = argv[1]\n\nprint(\"current term: \"+currentTerm)\n\nclass ClassList(Base):\n __tablename__ = 'class_list'\n class_id = Column('class_id', BigInteger, primary_key=True)\n term = Column('term', BigInteger)\n subject = Column('subject', String(15))\n catalog_number = Column('catalog_number', String(7))\n course_name = Column('course_name', String(30))\n section = Column('section', String(15))\n instructor = Column('Instructor', String(30))\n time = Column('time', String(30))\n\n def __repr___(self):\n return \"id: \" + self.class_id + \" term: \" + self.term\n\n\ndef getInitialPage():\n Base.metadata.create_all(engine)\n page = requests.get(\"http://schedule.cpp.edu\")\n tree = html.fromstring(page.content)\n VIEWSTATE = tree.xpath('//input[@name=\"__VIEWSTATE\"]/@value')\n VIEWSTATEGENERATOR = tree.xpath('//input[@name=\"__VIEWSTATEGENERATOR\"]/@value')\n VIEWSTATEENCRYPTED = tree.xpath('//input[@name=\"__VIEWSTATEENCRYPTED\"]/@value')\n EVENTVALIDATION = tree.xpath('//input[@name=\"__EVENTVALIDATION\"]/@value')\n StartTime = \"01:00:00 AM\"\n EndTime = \"11:00:00 PM\"\n TermDDL = currentTerm\n ClassSubject = \"\" # make \"CS\" for specific or \"\" for all\n CatalogNumber = \"\"\n Description = \"\"\n Instructor = \"\"\n headers = {\n \"Origin\" : \"http://schedule.cpp.edu/index.aspx\",\n \"Upgrade-Insecure-Requests\" : \"1\",\n \"User-Agent\" : \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2870.0 Safari/537.36\",\n \"Content-Type\" : \"application/x-www-form-urlencoded\",\n \"Accept\" : \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\",\n \"DNT\" : \"1\",\n \"Referer\" : \"http://schedule.cpp.edu/index.aspx\",\n \"Accept-Encoding\" : \"gzip, deflate\",\n \"Accept-Language\" : \"en-US,en;q=0.8\"\n }\n\n\n data = {}\n data[\"__EVENTARGUMENT\"] = \"\"\n data[\"__EVENTTARGET\"] = \"\"\n data[\"__EVENTVALIDATION\"] = EVENTVALIDATION\n data[\"__VIEWSTATE\"] = VIEWSTATE\n data[\"__VIEWSTATEGENERATOR\"] = VIEWSTATEGENERATOR\n data[\"__VIEWSTATEENCRYPTED\"] = VIEWSTATEENCRYPTED\n\n data[\"__VIEWSTATEENCRYPTED\"]=\"\"\n data[\"ctl00$ContentPlaceHolder1$CatalogNumber\"] = CatalogNumber\n data[\"ctl00$ContentPlaceHolder1$ClassDays$0\"] = \"on\"\n data[\"ctl00$ContentPlaceHolder1$ClassDays$1\"] = \"on\"\n data[\"ctl00$ContentPlaceHolder1$ClassDays$2\"] = \"on\"\n data[\"ctl00$ContentPlaceHolder1$ClassDays$3\"] = \"on\"\n data[\"ctl00$ContentPlaceHolder1$ClassDays$4\"] = \"on\"\n data[\"ctl00$ContentPlaceHolder1$ClassDays$5\"] = \"on\"\n data[\"ctl00$ContentPlaceHolder1$ClassDays$6\"] = \"on\"\n data[\"ctl00$ContentPlaceHolder1$ClassDays$7\"] = \"on\"\n data[\"ctl00$ContentPlaceHolder1$ClassSubject\"] = ClassSubject\n data[\"ctl00$ContentPlaceHolder1$CourseAttributeDDL\"] = \"Any Attribute\"\n data[\"ctl00$ContentPlaceHolder1$CourseCareerDDL\"] = \"Any Career\"\n data[\"ctl00$ContentPlaceHolder1$CourseComponentDDL\"] = \"Any Component\"\n data[\"ctl00$ContentPlaceHolder1$Description\"] = Description\n data[\"ctl00$ContentPlaceHolder1$EndTime\"] = EndTime\n data[\"ctl00$ContentPlaceHolder1$InstModesDDL\"] = \"Any Mode\"\n data[\"ctl00$ContentPlaceHolder1$Instructor\"] = Instructor\n data[\"ctl00$ContentPlaceHolder1$SearchButton\"] = \"Search\"\n data[\"ctl00$ContentPlaceHolder1$SessionDDL\"] = \"Any Session\"\n data[\"ctl00$ContentPlaceHolder1$StartTime\"] = StartTime\n data[\"ctl00$ContentPlaceHolder1$TermDDL\"] = TermDDL\n\n response = requests.post(\"http://schedule.cpp.edu/index.aspx\", data=data, headers=headers)\n responseTree = tree = html.fromstring(response.content)\n lis = responseTree.xpath('//li')\n\n for listItem in lis:\n courseName = listItem.xpath('span[@class=\"ClassTitle\"]/strong')\n if courseName != []:\n text = listItem.xpath(\"descendant-or-self::text()\")\n # [0] = class, [2] = section, [6] = Class #,\n # [12] = \"Course name\", [18] = \"time unicode\", [20] = room, [30] = Instructor\n row = ClassList()\n row.class_id = int(text[6].strip())\n subjectCatalog = text[0].strip().split(\" \")\n print(subjectCatalog)\n row.subject = subjectCatalog[0]\n row.catalog_number = subjectCatalog[2]\n row.section = text[2].strip()\n row.course_name = text[12].strip()\n times = text[18].split(u'\\u2013')\n if len(times) == 2:\n fromTime = unicodedata.normalize('NFKD', times[0].strip()).encode('ascii', 'ignore')\n toTimeDays = unicodedata.normalize('NFKD', times[1].strip()).encode('ascii', 'ignore').split(' ')\n row.time = fromTime + \"-\" + toTimeDays[0] + \" \" + toTimeDays[1] + \", \" + toTimeDays[4]\n elif times[0] == u'Time':\n row.time = \"\"\n else:\n row.time = unicodedata.normalize('NFKD', text[18].strip()).encode('ascii', 'ignore')\n row.instructor = text[30].strip()\n row.term = currentTerm\n rows = session.query(ClassList).filter_by(class_id=row.class_id, term=row.term)\n if rows.first():\n rows.update({ClassList.subject: row.subject, ClassList.catalog_number: row.catalog_number,\n ClassList.section: row.section, ClassList.course_name: row.course_name,\n ClassList.time: row.time, ClassList.instructor: row.instructor})\n else:\n session.add(row)\n\n session.commit()\n\n\nif __name__ == '__main__':\n getInitialPage()\n","sub_path":"classScraper.py","file_name":"classScraper.py","file_ext":"py","file_size_in_byte":6165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"507199145","text":"import numpy as np\n\nclass Contador:\n def __init__(self, bloco):\n self.bloco = bloco\n self.dados = []\n self.device = {}\n self.browser = {}\n self.response = {}\n self.status = {}\n self.avgsize = 0\n self.sumsize = 0\n self.latency = 0.0\n self.referer = {}\n\n\n def add( self, item ):\n self.dados.append( item )\n\n def __str__( self ):\n return self.bloco + \". \" + \\\n str(len( self.dados )) + \" itens | \" + \\\n str(self.latency) + \" Device | \" + \\\n str(self.device) + \" Browser | \" + \\\n str(self.browser) + \" Response | \" + \\\n str(self.response) + \" Status | \" + \\\n str(self.status) + \" Size Media| \" + \\\n str(self.avgsize) + \" Size Soma| \" + \\\n str(self.sumsize) + \" Url Geral| \" + \\\n str(self.referer)\n\n def calculaMedia( self ):\n latencias = [ x.latency for x in self.dados ]\n self.latency = np.average( latencias )\n\n def contadorDeviceBrowser( self ):\n \n for registro in self.dados:\n indexD = registro.device\n indexB = registro.browser\n\n if indexD not in self.device:\n self.device[indexD] = 0\n self.device[ indexD ] = self.device[ indexD ] +1\n\n if indexB not in self.browser:\n self.browser[indexB] = 0\n self.browser[ indexB ] = self.browser[ indexB ] +1\n\n def contadorResponse( self ):\n \n for registro in self.dados:\n index = registro.response\n\n if index not in self.response:\n self.response[index] = 0\n self.response[ index ] = self.response[ index ] +1\n\n def contadorStatus( self ):\n \n for registro in self.dados:\n index = registro.status\n\n if index not in self.status:\n self.status[index] = 0\n self.status[ index ] = self.status[ index ] +1\n\n def calculaMediaScript( self ):\n script = [ x.size for x in self.dados ]\n self.avgsize = np.average( script )\n self.sumsize = np.sum( script )\n\n def contadorReferer( self ):\n \n for registro in self.dados:\n index = registro.referer\n\n if index not in self.referer:\n self.referer[index] = 0\n self.referer[ index ] = self.referer[ index ] +1\n ","sub_path":"Contador.py","file_name":"Contador.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"320027572","text":"\"\"\"File 02oneLatentOrdered.py\n\nMeasurement equation where the indicators are discrete.\nOrdered probit.\n\n:author: Michel Bierlaire, EPFL\n:date: Mon Sep 9 16:52:36 2019\n\n\"\"\"\n\nimport pandas as pd\nimport biogeme.database as db\nimport biogeme.biogeme as bio\nimport biogeme.models as models\nimport biogeme.messaging as msg\nfrom biogeme.expressions import Beta, DefineVariable, log, Elem, bioNormalCdf\n\n# Read the data\ndf = pd.read_csv('optima.dat', sep='\\t')\ndatabase = db.Database('optima', df)\n\n# The following statement allows you to use the names of the variable\n# as Python variable.\nglobals().update(database.variables)\n\n# Exclude observations such that the chosen alternative is -1\ndatabase.remove(Choice == -1.0)\n\n# Piecewise linear definition of income\nScaledIncome = DefineVariable('ScaledIncome', CalculatedIncome / 1000, database)\n\nthresholds = [None, 4, 6, 8, 10, None]\nformulaIncome = models.piecewiseFormula(ScaledIncome,\n thresholds,\n [0.0, 0.0, 0.0, 0.0, 0.0])\n\n# Definition of other variables\nage_65_more = DefineVariable('age_65_more', age >= 65, database)\nmoreThanOneCar = DefineVariable('moreThanOneCar', NbCar > 1, database)\nmoreThanOneBike = DefineVariable('moreThanOneBike', NbBicy > 1, database)\nindividualHouse = DefineVariable('individualHouse', HouseType == 1, database)\nmale = DefineVariable('male', Gender == 1, database)\nhaveChildren = DefineVariable('haveChildren', \\\n ((FamilSitu == 3) + (FamilSitu == 4)) > 0, database)\nhaveGA = DefineVariable('haveGA', GenAbST == 1, database)\nhighEducation = DefineVariable('highEducation', Education >= 6, database)\n\n# Parameters to be estimated\ncoef_intercept = Beta('coef_intercept', 0.0, None, None, 0)\ncoef_age_65_more = Beta('coef_age_65_more', 0.0, None, None, 0)\ncoef_age_unknown = Beta('coef_age_unknown', 0.0, None, None, 0)\ncoef_haveGA = Beta('coef_haveGA', 0.0, None, None, 0)\ncoef_moreThanOneCar = Beta('coef_moreThanOneCar', 0.0, None, None, 0)\ncoef_moreThanOneBike = Beta('coef_moreThanOneBike', 0.0, None, None, 0)\ncoef_individualHouse = Beta('coef_individualHouse', 0.0, None, None, 0)\ncoef_male = Beta('coef_male', 0.0, None, None, 0)\ncoef_haveChildren = Beta('coef_haveChildren', 0.0, None, None, 0)\ncoef_highEducation = Beta('coef_highEducation', 0.0, None, None, 0)\n\n### Latent variable: structural equation\n\n# Note that the expression must be on a single line. In order to\n# write it across several lines, each line must terminate with\n# the \\ symbol\n\nCARLOVERS = coef_intercept +\\\n coef_age_65_more * age_65_more +\\\n formulaIncome + \\\n coef_moreThanOneCar * moreThanOneCar +\\\n coef_moreThanOneBike * moreThanOneBike +\\\n coef_individualHouse * individualHouse +\\\n coef_male * male +\\\n coef_haveChildren * haveChildren +\\\n coef_haveGA * haveGA +\\\n coef_highEducation * highEducation\n\n### Measurement equations\n\nINTER_Envir01 = Beta('INTER_Envir01', 0, None, None, 1)\nINTER_Envir02 = Beta('INTER_Envir02', 0, None, None, 0)\nINTER_Envir03 = Beta('INTER_Envir03', 0, None, None, 0)\nINTER_Mobil11 = Beta('INTER_Mobil11', 0, None, None, 0)\nINTER_Mobil14 = Beta('INTER_Mobil14', 0, None, None, 0)\nINTER_Mobil16 = Beta('INTER_Mobil16', 0, None, None, 0)\nINTER_Mobil17 = Beta('INTER_Mobil17', 0, None, None, 0)\n\nB_Envir01_F1 = Beta('B_Envir01_F1', -1, None, None, 1)\nB_Envir02_F1 = Beta('B_Envir02_F1', -1, None, None, 0)\nB_Envir03_F1 = Beta('B_Envir03_F1', 1, None, None, 0)\nB_Mobil11_F1 = Beta('B_Mobil11_F1', 1, None, None, 0)\nB_Mobil14_F1 = Beta('B_Mobil14_F1', 1, None, None, 0)\nB_Mobil16_F1 = Beta('B_Mobil16_F1', 1, None, None, 0)\nB_Mobil17_F1 = Beta('B_Mobil17_F1', 1, None, None, 0)\n\nMODEL_Envir01 = INTER_Envir01 + B_Envir01_F1 * CARLOVERS\nMODEL_Envir02 = INTER_Envir02 + B_Envir02_F1 * CARLOVERS\nMODEL_Envir03 = INTER_Envir03 + B_Envir03_F1 * CARLOVERS\nMODEL_Mobil11 = INTER_Mobil11 + B_Mobil11_F1 * CARLOVERS\nMODEL_Mobil14 = INTER_Mobil14 + B_Mobil14_F1 * CARLOVERS\nMODEL_Mobil16 = INTER_Mobil16 + B_Mobil16_F1 * CARLOVERS\nMODEL_Mobil17 = INTER_Mobil17 + B_Mobil17_F1 * CARLOVERS\n\nSIGMA_STAR_Envir01 = Beta('SIGMA_STAR_Envir01', 1, 1.0e-5, None, 1)\nSIGMA_STAR_Envir02 = Beta('SIGMA_STAR_Envir02', 1, 1.0e-5, None, 0)\nSIGMA_STAR_Envir03 = Beta('SIGMA_STAR_Envir03', 1, 1.0e-5, None, 0)\nSIGMA_STAR_Mobil11 = Beta('SIGMA_STAR_Mobil11', 1, 1.0e-5, None, 0)\nSIGMA_STAR_Mobil14 = Beta('SIGMA_STAR_Mobil14', 1, 1.0e-5, None, 0)\nSIGMA_STAR_Mobil16 = Beta('SIGMA_STAR_Mobil16', 1, 1.0e-5, None, 0)\nSIGMA_STAR_Mobil17 = Beta('SIGMA_STAR_Mobil17', 1, 1.0e-5, None, 0)\n\n\ndelta_1 = Beta('delta_1', 0.1, 1.0e-5, None, 0)\ndelta_2 = Beta('delta_2', 0.2, 1.0e-5, None, 0)\ntau_1 = -delta_1 - delta_2\ntau_2 = -delta_1\ntau_3 = delta_1\ntau_4 = delta_1 + delta_2\n\nEnvir01_tau_1 = (tau_1 - MODEL_Envir01) / SIGMA_STAR_Envir01\nEnvir01_tau_2 = (tau_2 - MODEL_Envir01) / SIGMA_STAR_Envir01\nEnvir01_tau_3 = (tau_3 - MODEL_Envir01) / SIGMA_STAR_Envir01\nEnvir01_tau_4 = (tau_4 - MODEL_Envir01) / SIGMA_STAR_Envir01\nIndEnvir01 = {\n 1: bioNormalCdf(Envir01_tau_1),\n 2: bioNormalCdf(Envir01_tau_2) - bioNormalCdf(Envir01_tau_1),\n 3: bioNormalCdf(Envir01_tau_3) - bioNormalCdf(Envir01_tau_2),\n 4: bioNormalCdf(Envir01_tau_4) - bioNormalCdf(Envir01_tau_3),\n 5: 1 - bioNormalCdf(Envir01_tau_4),\n 6: 1.0,\n -1: 1.0,\n -2: 1.0}\n\nP_Envir01 = Elem(IndEnvir01, Envir01)\n\nEnvir02_tau_1 = (tau_1 - MODEL_Envir02) / SIGMA_STAR_Envir02\nEnvir02_tau_2 = (tau_2 - MODEL_Envir02) / SIGMA_STAR_Envir02\nEnvir02_tau_3 = (tau_3 - MODEL_Envir02) / SIGMA_STAR_Envir02\nEnvir02_tau_4 = (tau_4 - MODEL_Envir02) / SIGMA_STAR_Envir02\nIndEnvir02 = {\n 1: bioNormalCdf(Envir02_tau_1),\n 2: bioNormalCdf(Envir02_tau_2) - bioNormalCdf(Envir02_tau_1),\n 3: bioNormalCdf(Envir02_tau_3) - bioNormalCdf(Envir02_tau_2),\n 4: bioNormalCdf(Envir02_tau_4) - bioNormalCdf(Envir02_tau_3),\n 5: 1 - bioNormalCdf(Envir02_tau_4),\n 6: 1.0,\n -1: 1.0,\n -2: 1.0}\n\nP_Envir02 = Elem(IndEnvir02, Envir02)\n\nEnvir03_tau_1 = (tau_1 - MODEL_Envir03) / SIGMA_STAR_Envir03\nEnvir03_tau_2 = (tau_2 - MODEL_Envir03) / SIGMA_STAR_Envir03\nEnvir03_tau_3 = (tau_3 - MODEL_Envir03) / SIGMA_STAR_Envir03\nEnvir03_tau_4 = (tau_4 - MODEL_Envir03) / SIGMA_STAR_Envir03\nIndEnvir03 = {\n 1: bioNormalCdf(Envir03_tau_1),\n 2: bioNormalCdf(Envir03_tau_2) - bioNormalCdf(Envir03_tau_1),\n 3: bioNormalCdf(Envir03_tau_3) - bioNormalCdf(Envir03_tau_2),\n 4: bioNormalCdf(Envir03_tau_4) - bioNormalCdf(Envir03_tau_3),\n 5: 1 - bioNormalCdf(Envir03_tau_4),\n 6: 1.0,\n -1: 1.0,\n -2: 1.0}\n\nP_Envir03 = Elem(IndEnvir03, Envir03)\n\nMobil11_tau_1 = (tau_1 - MODEL_Mobil11) / SIGMA_STAR_Mobil11\nMobil11_tau_2 = (tau_2 - MODEL_Mobil11) / SIGMA_STAR_Mobil11\nMobil11_tau_3 = (tau_3 - MODEL_Mobil11) / SIGMA_STAR_Mobil11\nMobil11_tau_4 = (tau_4 - MODEL_Mobil11) / SIGMA_STAR_Mobil11\nIndMobil11 = {\n 1: bioNormalCdf(Mobil11_tau_1),\n 2: bioNormalCdf(Mobil11_tau_2) - bioNormalCdf(Mobil11_tau_1),\n 3: bioNormalCdf(Mobil11_tau_3) - bioNormalCdf(Mobil11_tau_2),\n 4: bioNormalCdf(Mobil11_tau_4) - bioNormalCdf(Mobil11_tau_3),\n 5: 1 - bioNormalCdf(Mobil11_tau_4),\n 6: 1.0,\n -1: 1.0,\n -2: 1.0\n}\n\nP_Mobil11 = Elem(IndMobil11, Mobil11)\n\nMobil14_tau_1 = (tau_1 - MODEL_Mobil14) / SIGMA_STAR_Mobil14\nMobil14_tau_2 = (tau_2 - MODEL_Mobil14) / SIGMA_STAR_Mobil14\nMobil14_tau_3 = (tau_3 - MODEL_Mobil14) / SIGMA_STAR_Mobil14\nMobil14_tau_4 = (tau_4 - MODEL_Mobil14) / SIGMA_STAR_Mobil14\nIndMobil14 = {\n 1: bioNormalCdf(Mobil14_tau_1),\n 2: bioNormalCdf(Mobil14_tau_2) - bioNormalCdf(Mobil14_tau_1),\n 3: bioNormalCdf(Mobil14_tau_3) - bioNormalCdf(Mobil14_tau_2),\n 4: bioNormalCdf(Mobil14_tau_4) - bioNormalCdf(Mobil14_tau_3),\n 5: 1 - bioNormalCdf(Mobil14_tau_4),\n 6: 1.0,\n -1: 1.0,\n -2: 1.0}\n\nP_Mobil14 = Elem(IndMobil14, Mobil14)\n\nMobil16_tau_1 = (tau_1 - MODEL_Mobil16) / SIGMA_STAR_Mobil16\nMobil16_tau_2 = (tau_2 - MODEL_Mobil16) / SIGMA_STAR_Mobil16\nMobil16_tau_3 = (tau_3 - MODEL_Mobil16) / SIGMA_STAR_Mobil16\nMobil16_tau_4 = (tau_4 - MODEL_Mobil16) / SIGMA_STAR_Mobil16\nIndMobil16 = {\n 1: bioNormalCdf(Mobil16_tau_1),\n 2: bioNormalCdf(Mobil16_tau_2) - bioNormalCdf(Mobil16_tau_1),\n 3: bioNormalCdf(Mobil16_tau_3) - bioNormalCdf(Mobil16_tau_2),\n 4: bioNormalCdf(Mobil16_tau_4) - bioNormalCdf(Mobil16_tau_3),\n 5: 1 - bioNormalCdf(Mobil16_tau_4),\n 6: 1.0,\n -1: 1.0,\n -2: 1.0}\n\nP_Mobil16 = Elem(IndMobil16, Mobil16)\n\nMobil17_tau_1 = (tau_1 - MODEL_Mobil17) / SIGMA_STAR_Mobil17\nMobil17_tau_2 = (tau_2 - MODEL_Mobil17) / SIGMA_STAR_Mobil17\nMobil17_tau_3 = (tau_3 - MODEL_Mobil17) / SIGMA_STAR_Mobil17\nMobil17_tau_4 = (tau_4 - MODEL_Mobil17) / SIGMA_STAR_Mobil17\nIndMobil17 = {\n 1: bioNormalCdf(Mobil17_tau_1),\n 2: bioNormalCdf(Mobil17_tau_2) - bioNormalCdf(Mobil17_tau_1),\n 3: bioNormalCdf(Mobil17_tau_3) - bioNormalCdf(Mobil17_tau_2),\n 4: bioNormalCdf(Mobil17_tau_4) - bioNormalCdf(Mobil17_tau_3),\n 5: 1 - bioNormalCdf(Mobil17_tau_4),\n 6: 1.0,\n -1: 1.0,\n -2: 1.0}\n\nP_Mobil17 = Elem(IndMobil17, Mobil17)\n\n\nloglike = log(P_Envir01) + \\\n log(P_Envir02) + \\\n log(P_Envir03) + \\\n log(P_Mobil11) + \\\n log(P_Mobil14) + \\\n log(P_Mobil16) + \\\n log(P_Mobil17)\n\n# Define level of verbosity\nlogger = msg.bioMessage()\n#logger.setSilent()\n#logger.setWarning()\nlogger.setGeneral()\n#logger.setDetailed()\n\n\n# Create the Biogeme object\nbiogeme = bio.BIOGEME(database, loglike, numberOfDraws=20000)\nbiogeme.modelName = '02oneLatentOrdered'\n\n# Estimate the parameters\nresults = biogeme.estimate(saveIterations=True)\n\nprint(f'Estimated betas: {len(results.data.betaValues)}')\nprint(f'final log likelihood: {results.data.logLike:.3f}')\nprint(f'Output file: {results.data.htmlFileName}')\nresults.writeLaTeX()\nprint(f'LaTeX file: {results.data.latexFileName}')\n","sub_path":"examples/latent/02oneLatentOrdered.py","file_name":"02oneLatentOrdered.py","file_ext":"py","file_size_in_byte":9902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"384228722","text":"import tkinter as tk\nfrom tkinter import filedialog\nimport threading as td\nimport queue as Q\nfrom time import sleep\nimport random\nfrom ptpython import *\nfrom tkinter import ttk\n#import urllib.request\nfrom fake_useragent import UserAgent\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup as BS\nimport requests\nimport re \nimport pandas as pd\nimport os\n\n\nwebAddress = {\n\t'WebSite 1': 'https://www.google.com/search?q=',\n\t'WebSite 2': 'https://www.firmenwissen.de/index.html'\n}\n\nCom_address1 = []\n\nerror = []\nn = 0\n\nclass Thread_0(td.Thread):\n\n\tdef __init__(self):\n\t\ttd.Thread.__init__(self)\n\n\n\tdef run(self):\n\t\tdf = pd.read_excel(hmi.entry_1.get())\n\t\t#print(df.head())\n\t\tdf.dropna(axis=0, inplace=True)\n\t\t# print(df.head())\n\t\tself.ua = UserAgent()\n\t\turl = webAddress[hmi.combo_1.get()]\n\t\turl2 = webAddress[hmi.combo_2.get()]\n\t\theaders = {'User-Agent':str(self.ua.chrome)}\n\t\t#headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36'}\n\t\tself.driver = webdriver.Chrome('C:/Users/Prisma/Documents/Netzwerk-P/App/Address_Collection/chromedriver_win32/chromedriver')\n\t\tself.driver.get(url)\n\t\tfor company in df.Beschreibung_2:\n\t\t\tglobal n\n\t\t\tprint(n)\n\t\t\tn = n + 1\n\t\t\tinputElement = self.driver.find_element_by_name(\"q\")\n\t\t\tinputElement.clear()\n\t\t\tinputElement.send_keys(company)\n\t\t\tinputElement.submit()\n\t\t\tresponse = requests.get(url+company)\n\t\t\tsoup = BS(response.content, 'html.parser')\n\t\t\tif soup.find('span', class_= 'A1t5ne') == None:\n\t\t\t\tif \"\\\"\" in company:\n\t\t\t\t\tquoted = re.compile('\"[^\"]*\"')\n\t\t\t\t\tfor value in quoted.findall(company):\n\t\t\t\t\t\tinputElement = self.driver.find_element_by_name(\"q\")\n\t\t\t\t\t\tinputElement.clear()\n\t\t\t\t\t\tinputElement.send_keys(value)\n\t\t\t\t\t\tinputElement.submit()\n\t\t\t\t\t\tresponse = requests.get(url+value)\n\t\t\t\t\t\tsoup = BS(response.content, 'html.parser')\n\t\t\t\t\t\tif soup.find('span', class_= 'A1t5ne') == None:\n\t\t\t\t\t\t\tself.driver.get(url2)\n\t\t\t\t\t\t\tinputElement = self.driver.find_element_by_id(\"searchPhrase0\")\n\t\t\t\t\t\t\tinputElement.clear()\n\t\t\t\t\t\t\tinputElement.send_keys(company)\n\t\t\t\t\t\t\tinputElement.submit()\n\t\t\t\t\t\t\tsoup = BS(self.driver.page_source, 'html.parser')\n\t\t\t\t\t\t\tlink = soup.find('span',{'class':'company--name'})\n\t\t\t\t\t\t\ta_link = link.find('a')['href']\n\t\t\t\t\t\t\titem = 'https://www.firmenwissen.de' + a_link + '?showEmail=true'\n\t\t\t\t\t\t\tresponse = requests.get('https://www.firmenwissen.de' + a_link + '?showEmail=true', headers=headers)\n\n\t\t\t\t\t\t\talpha_soup = BS(response.text, 'html.parser')\n\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\tphone = alpha_soup.find('span', {'class':'yp_phoneNumber'}).text.strip()\n\n\t\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\t\tphone = ''\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\temail = alpha_soup.find('span', {'class':'yp_email'}).text.strip()\n\n\t\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\t\temail = ''\n\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\twebsite = alpha_soup.find('span', {'class':'yp_website'}).text.strip()\n\n\t\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\t\twebiste = ''\n\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\tself.driver.get(item)\n\t\t\t\t\t\t\t\tstr_addr = self.driver.find_element_by_css_selector('.yp_address')\n\n\t\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\t\tprint ('Could not locate %s company info' %(company))\n\t\t\t\t\t\t\t\terror.append(company)\n\t\t\t\t\t\t\tadd_str1 = '{} {} {} {}'.format(str_addr.text.strip(), phone, email, website)\n\t\t\t\t\t\t\thmi.thread_0_update(company+'\\n'+add_str1+'\\n')\n\t\t\t\t\t\t\tsleep(random.random()/100)\n\t\t\t\t\t\t\tCom_address1.append(add_str1)\n\t\t\t\t\t\t\tself.driver.get(url)\n\n\t\t\t\t\t\t\tif n >= len(df.Beschreibung_2):\n\t\t\t\t\t\t\t\tAddress = pd.DataFrame(Com_address1)\n\t\t\t\t\t\t\t\tdf['address'] = Address\n\t\t\t\t\t\t\t\tdf.to_excel('Final_Table'+str(n)+'.xlsx', index=False, header=False)\n\t\t\t\t\t\t\tif n > 80:\n\t\t\t\t\t\t\t\tAddress = pd.DataFrame(Com_address1)\n\t\t\t\t\t\t\t\t#df['address'] = Address\n\t\t\t\t\t\t\t\tAddress.to_excel('Final_Table.xlsx', index=False, header=False)\n\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tadd_str = soup.find('span', class_= 'A1t5ne').text.strip()\n\t\t\t\t\t\t\thmi.thread_0_update(company+'\\n'+add_str+'\\n')\n\t\t\t\t\t\t\tsleep(random.random()/100)\n\t\t\t\t\t\t\tCom_address1.append(add_str)\n\t\t\t\t\t\t\t#print(add_str)\n\t\t\t\t\t\t\t#print()\n\t\t\t\t\t\t\t#received_html = add_str\n\n\t\t\t\t\t\t\tif n >= len(df.Beschreibung_2):\n\t\t\t\t\t\t\t\tAddress = pd.DataFrame(Com_address1)\n\t\t\t\t\t\t\t\tdf['address'] = Address\n\t\t\t\t\t\t\t\tdf.to_excel('Final_Table'+str(n)+'.xlsx', index=False, header=False)\n\n\t\t\t\t\t\t\tif n > 80:\n\t\t\t\t\t\t\t\tAddress = pd.DataFrame(Com_address1)\n\t\t\t\t\t\t\t\t#df['address'] = Address\n\t\t\t\t\t\t\t\tAddress.to_excel('Final_Table.xlsx', index=False, header=False)\n\n\t\t\t\telse:\n\t\t\t\t\tself.driver.get(url2)\n\t\t\t\t\tinputElement = self.driver.find_element_by_id(\"searchPhrase0\")\n\t\t\t\t\tinputElement.clear()\n\t\t\t\t\tinputElement.send_keys(company)\n\t\t\t\t\tinputElement.submit()\n\n\t\t\t\t\tsoup = BS(self.driver.page_source, 'html.parser')\n\n\t\t\t\t\tlink = soup.find('span',{'class':'company--name'})\n\n\t\t\t\t\ta_link = link.find('a')['href']\n\t\t\t\t\titem = 'https://www.firmenwissen.de' + a_link + '?showEmail=true'\n\n\t\t\t\t\tresponse = requests.get('https://www.firmenwissen.de' + a_link + '?showEmail=true', headers=headers)\n\t\t\t\t\talpha_soup = BS(response.text, 'html.parser')\n\n\t\t\t\t\ttry:\n\t\t\t\t\t\tphone = alpha_soup.find('span', {'class':'yp_phoneNumber'}).text.strip()\n\t\t\t\t\texcept:\n\t\t\t\t\t\tphone = ''\n\n\t\t\t\t\ttry:\n\t\t\t\t\t\temail = alpha_soup.find('span', {'class':'yp_email'}).text.strip()\n\t\t\t\t\texcept:\n\t\t\t\t\t\temail = ''\n\t\t\t\t\ttry:\n\t\t\t\t\t\twebsite = alpha_soup.find('span', {'class':'yp_website'}).text.strip()\n\t\t\t\t\texcept:\n\t\t\t\t\t\twebsite = ''\n\n\t\t\t\t\ttry:\n\t\t\t\t\t\tself.driver.get(item)\n\t\t\t\t\t\tstr_addr = self.driver.find_element_by_css_selector('.yp_address')\n\t\t\t\t\texcept:\n\t\t\t\t\t\tprint ('Could not locate %s company info' %(company))\n\t\t\t\t\t\terror.append(company)\n\n\t\t\t\t\tadd_str1 = '{} {} {} {}'.format(str_addr.text.strip(), phone, email, website)\n\t\t\t\t\thmi.thread_0_update(company+'\\n'+add_str1+'\\n\\n')\n\t\t\t\t\tsleep(random.random()/100)\n\t\t\t\t\tCom_address1.append(add_str1)\n\t\t\t\t\t#received_html = add_str1\n\t\t\t\t\t#text.insert(tk.END, received_html)\n\t\t\t\t\tprint(add_str1)\n\t\t\t\t\tprint()\n\t\t\t\t\tself.driver.get(url)\n\n\t\t\t\t\tif n >= len(df.Beschreibung_2):\n\t\t\t\t\t\tAddress = pd.DataFrame(Com_address1)\n\t\t\t\t\t\tdf['address'] = Address\n\t\t\t\t\t\tdf.to_excel('Final_Table'+str(n)+'.xlsx', index=False, header=False)\n\n\t\t\t\t\tif n > 80:\n\t\t\t\t\t\tAddress = pd.DataFrame(Com_address1)\n\t\t\t\t\t\t#df['address'] = Address\n\t\t\t\t\t\tAddress.to_excel('Final_Table.xlsx', index=False, header=False)\n\n\t\t\telse:\n\t\t\t\tadd_str = soup.find('span', class_= 'A1t5ne').text.strip()\n\t\t\t\thmi.thread_0_update(company+'\\n'+add_str+'\\n\\n')\n\t\t\t\tsleep(random.random()/100)\n\t\t\t\tCom_address1.append(add_str)\n\t\t\t\t#print(add_str)\n\t\t\t\t#print()\n\t\t\t\t#received_html = add_str\n\n\t\t\t\tif n >= len(df.Beschreibung_2):\n\t\t\t\t\tAddress = pd.DataFrame(Com_address1)\n\t\t\t\t\tdf['address'] = Address\n\t\t\t\t\tdf.to_excel('Final_Table'+str(n)+'.xlsx', index=False, header=False)\n\n\t\t\t\tif n > 80:\n\t\t\t\t\tAddress = pd.DataFrame(Com_address1)\n\t\t\t\t\t#df['address'] = Address\n\t\t\t\t\tAddress.to_excel('Final_Table.xlsx', index=False, header=False)\n\n\t\t#n = 0\n\t\t#hmi.thread_0_update(Com_address1[0])\n\t\t#sleep(random.random()/100)\n\n\t\t\n\t\tself.driver.quit()\n\t\t\n\t\t#n = 0\n\t\t#while True:\n\t\t\t#for x in companylist:\n\t\t\t\t#count += 1\n\t\t\t\t#hmi.thread_0_update(Com_address1[0])\n\t\t\t\t#sleep(random.random()/100)\n\t #self.driver.quit()\n\nclass HMI:\n\t\n\tdef __init__(self):\n\n\t\tself.master = tk.Tk()\n\t\tself.master.geometry('500x320+50+50')\n\t\tself.master.title('GUI for Address Collection')\n\n\t\tself.label_1 = tk.Label(self.master, text= \"Website 1\", font =('Times New Roman', 14))\n\t\tself.label_1.grid(row=1, column=1, padx =10, pady=5, sticky='ne')\n\n\t\tself.combo_1 = ttk.Combobox(self.master, width=15, values = [\"WebSite 1\"], font=('Times New Roman', 12))\n\t\tself.combo_1.grid(row=1, column=2, padx = 10, pady=5, sticky='nw')\n\n\t\tself.label_2 = tk.Label(self.master, text= \"Website 2\", font =('Times New Roman', 14))\n\t\tself.label_2.grid(row=2, column=1, padx =10, pady=5, sticky='ne')\n\n\t\tself.combo_2 = ttk.Combobox(self.master, width=15, values = [\"WebSite 2\"], font=('Times New Roman', 12))\n\t\tself.combo_2.grid(row=2, column=2, padx = 10, pady=10, sticky='nw')\n\n\n\t\tself.label_3 = tk.Label(self.master, text= \"Select file\", font =('Times New Roman', 14))\n\t\tself.label_3.grid(row=3, column=1, padx =10, pady=5, sticky='ne')\n\n\t\tself.entry_1 = tk.StringVar()\n\n\t\tself.entry_1 = ttk.Entry(self.master, width=15)\n\t\tself.entry_1.grid(row=3, column=2, padx=10,pady=10, sticky='ew')\n\n\t\tself.button_1 = ttk.Button(self.master, text='Path', command = self.open_file)\n\t\tself.button_1.grid(row=3, column=3, padx=5, pady=5)\n\n\t\tself.label_4 = tk.Label(self.master, text= \"Save as\", font =('Times New Roman', 14))\n\t\tself.label_4.grid(row=4, column=1, padx =10, pady=5, sticky='ne')\n\n\t\tself.entry_2 = tk.StringVar()\n\n\t\tself.entry_2 = ttk.Entry(self.master, width=15)\n\t\tself.entry_2.grid(row=4, column=2, padx=10,pady=10, sticky='ew')\n\n\t\t#self.dirname = filedialog.askdirectory(parent=self.master, initialdir=\"/\", title='Please select a path')\n\t\t#os.chdir(self.dirname)\n\n\t\tself.button_2 = ttk.Button(self.master, text='Path', command=self.select_folder)\n\t\tself.button_2.grid(row=4, column=3, padx=5, pady=5)\n\n\t\tself.label_5 = tk.Label(self.master, text= \"Address\", font =('Times New Roman', 14))\n\t\tself.label_5.grid(row=5, column=1, padx =10, pady=10, sticky='ne')\n\n\t\tself.text_1 = tk.Text(self.master, height=5, width=10)\n\t\tself.text_1.grid(row=5, column=2, padx = 10, pady=10, sticky='e'+'w'+'n'+'s', columnspan=5)\n\t\t#self.text_1.grid(row=4, column=2, padx = 10, pady=10, sticky='ew', columnspan=15)\n\n\t\t#self.scroll_1 = ttk.Scrollbar(self.text_1, orient ='vertical', command=self.text_1.yview)\n\t\t#self.scroll_1.grid(row=3,column=15, sticky='nw')\n\t\t#self.scroll_1.grid(row=3, column=15, sticky='ns')\n\n\t\tn = 3\n\t\tself.label = ttk.Label(self.text_1)\n\t\tself.label.grid(row=3, column=2, padx=10,pady=5, columnspan=5)\n\t\tn += 1\n\n\t\t##########################################\n\t\t#self.label_3 = tk.Label(self.master, text= \" \", font =('Times New Roman', 14))\n\t\t#self.label_3.grid(row=4, column=1, padx =10, pady=5, sticky='ne')\n\t\t##########################################\n\n\t\tself.button_3 = ttk.Button(self.master, text='Go', command = t0.start)\n\t\tself.button_3.grid(row=10, column=2, padx=5, pady=5, sticky='w')\n\n\t\tself.button_4 = ttk.Button(self.master, text='Exit',command = self.master.destroy)\n\t\tself.button_4.grid(row=10, column=3, padx=5, pady=5)\n\n\t\t#self.text_1.config(yscrollcommand=self.scroll_1.set)\n\t\t#self.text_1.config(xscrollcommand=self.scroll_1.set)\n\n\t\tself.q = Q.Queue()\n\n\t\tself.master.bind(\"<>\", self.thread_0_update_e)\n\n\tdef open_file(self):\n\t\tself.open_dirname = filedialog.askopenfilename(filetypes = (('Excel files','*.xlsx'),(\"All files\", \"*.*\")), initialdir=\"/\", title='Open file')\n\t\tif self.open_dirname:\n\t\t\tself.entry_1.delete(0,'end')\n\t\t\t#os.chdir(self.open_dirname)\n\t\t\tself.entry_1.insert(tk.END, self.open_dirname)\n\n\tdef select_folder(self):\n\t\tself.dirname = filedialog.askdirectory(parent=self.master, initialdir=\"/\", title='Please select a path')\n\t\tif self.dirname:\n\t\t\tself.entry_2.delete(0,'end')\n\t\t\tos.chdir(self.dirname)\n\t\t\tself.entry_2.insert(tk.END, self.dirname)\n\n\n\tdef start(self):\n\t\tself.master.mainloop()\n\t\tself.master.destroy()\n\t\t\n\n\tdef thread_0_update(self, val):\n\t\tself.q.put(val)\n\t\tself.master.event_generate(\"<>\", when='tail')\n\t\t\n\n\tdef thread_0_update_e(self, e):\n\t\twhile self.q.qsize():\n\t\t\ttry:\n\t\t\t\tval = self.q.get()\n\t\t\t\tself.label.config(text = str(val), font =('Times New Roman', 13))\n\t\t\t\t#self.label.config(text=self.label.cget(\"text\")+ str(val), font =('Times New Roman', 12))\n\t\t\texcept Q.Empty:\n\t\t\t\tpass\n\n\nif __name__ == '__main__':\n t0 = Thread_0()\n hmi = HMI()\n #hmi.path()\n hmi.start()","sub_path":"Netzwerk-P/GUI_with_python/Address_Collection_App/Web_Scrapping_GUI_3.py","file_name":"Web_Scrapping_GUI_3.py","file_ext":"py","file_size_in_byte":11476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"546873425","text":"#!/usr/local/bin/python3\nimport csv\n\n\n# C - Conservative Party\n# L - Labour Party\n# UKIP - UKIP\n# LD - Liberal Democrats\n# G - Green Party\n# Ind - Independent\n# SNP - SNP\n\ndef pairs(lst, n):\n for i in range(0, len(lst), n):\n yield lst[i:i +n]\n\ndef constituencyReplace(string):\n if string == \"C\":\n string = \"Conservative Party\"\n elif string == \"L\":\n string = \"Labour Party\"\n elif string == \"LD\":\n string = \"Liberal Democrats\"\n elif string == \"G\":\n string = \"Green Party\"\n elif string == \"Ind\":\n string = \"Independent\"\n return string\n\ndef calculatePercents(part, total):\n part = 100 * float(part)/float(total)\n return round(part, 0)\n\n\n\nwith open('../../data.csv', newline='') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n constituencyName = row[0]\n totalVotes = row[1]\n for execution in range(2):\n row.pop(0)\n # Split the list for pairs\n pairRow = list(pairs(row, 2))\n print(constituencyName+\"with :\"+totalVotes+\" votes\")\n for pair in pairRow:\n pair = [listObject.strip(' ') for listObject in pair]\n if len(pair) % 2 == 0:\n # Handle errors if the value for constituency will be not int value\n try:\n pair[1] = int(pair[1])\n except:\n pair[1] = 0\n else:\n pair.append(0)\n for iter, _ in enumerate(pair):\n if isinstance(pair[iter], str):\n pair[iter] = constituencyReplace(pair[iter])\n else:\n pair[iter] = calculatePercents(pair[iter], totalVotes)\n print(pair)\n ","sub_path":"python3/basic/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"635485187","text":"from collections import deque\nclass Solution(object):\n def shortestDistance(self,grid):\n def is_valid(position):\n i,j = position\n return 0 <= i < len(grid) and 0 <= j < len(grid[0]) and grid[i][j] == target\n def next(i,j):\n return filter(is_valid,[(i+1,j),(i-1,j),(i,j-1),(i,j+1)])\n\n total = [row[:] for row in grid] #total distance accumalted for all buildings\n target = 0\n for i,row in enumerate(grid):\n for j, cell in enumerate(row):\n if cell == 1:\n min_dist = -1\n dist = [[0]* len(grid[0]) for _ in range(len(grid))]\n queue = deque([(i,j)])\n while queue:\n r,c = queue.popleft()\n valids = next(r,c)\n for nr,nc in valids:\n grid[nr][nc] -=1\n dist[nr][nc] = dist[r][c] + 1\n total[nr][nc] += dist[nr][nc]\n #min_dst has to be a valid one\n if min_dst == -1 or min_dst > total[nr][nc]:\n min_dst = total[nr][nc]\n\n #insert all valids neig\n queue.extend(valids)\n #End of visit from a building. Next time we will only visit the following target\n target -=1\n return min_dst\n\n","sub_path":"Graph/minDstWellHome.py","file_name":"minDstWellHome.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"249304623","text":"\nclass Node(object):\n def __init__(self, val):\n self.val = val\n self.next = None\n\ndef convert_array_to_list(arr):\n root = None\n curr = None\n for num in arr:\n node = Node(num)\n\n if not root:\n root = node\n\n if curr:\n curr.next = node\n\n curr = node\n\n return root\n\ndef convert_list_to_array(l):\n output = []\n\n curr = l\n while curr:\n output.append(curr.val)\n curr = curr.next\n\n return output","sub_path":"lib/utils/linked_list.py","file_name":"linked_list.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"349220952","text":"ball_y = 100\ny_speed = 4 #switching the speed of the ball \nball_x = 100 #added new variables to make the ball go left and right\nx_speed = 4\n\ndef setup():\n size(500, 500) \n \ndef draw():\n global ball_y\n global ball_x\n background(200, 200, 200) #added the background in order for one ball to show at a time\n ellipse (ball_x, ball_y, 100, 100) \n line(0, 0, 0, 0)\n line(500, 0, 500, 500) \n line(0, 500, 500, 500) \n line(500, 500, 500, 500) \n \n if ball_y > 450:\n global y_speed #as before, I had to use global to call the variable down to this line of code\n print(\"BOUNCE\") #bounce appeared at the bottom in the text box therefore, the barrier is on the right track \n y_speed = -4 #made the ball reverse \n #now add another \"if\" statement to get the ball bounce back and forth* \n ball_y = ball_y + y_speed #made the ball faster, \"if statement still needed to make the ball bounce\" \n\n if ball_y < 50:\n global y_speed \n print(\"BOUNCE2\") \n y_speed = 4 \n \n if ball_x > 450:\n global x_speed\n print(\"BOUNCEL\") \n x_speed = -3\n ball_x = ball_x + x_speed \n \n if ball_x < 50:\n global x_speed \n print(\"BOUNCER\")\n x_speed = 3 \n print(ball_x, x_speed)\n \n \n \n \n\n \n","sub_path":"Animations_CSSI_Day_3.pyde","file_name":"Animations_CSSI_Day_3.pyde","file_ext":"pyde","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"541875267","text":"#!/usr/bin/env python3\n\nimport argparse\nimport io\nimport sys\nimport json\nimport logging\nimport collections\nimport threading\nimport http.client\nimport urllib\nimport pkg_resources\nimport decimal\n\nfrom jsonschema import validate\nimport singer\n\nfrom oauth2client import tools\nfrom tempfile import TemporaryFile\n\nfrom google.cloud import bigquery\nfrom google.cloud.bigquery.job import SourceFormat\nfrom google.cloud.bigquery import Dataset, WriteDisposition\nfrom google.cloud.bigquery import LoadJobConfig\nfrom google.api_core import exceptions\n\nfrom target_bigquery.schema import build_schema, filter\nfrom target_bigquery.encoders import DecimalEncoder\nfrom target_bigquery.job import persist_lines_job\nfrom target_bigquery.stream import persist_lines_stream\nfrom target_bigquery.utils import emit_state, collect\n\nlogging.getLogger(\"googleapiclient.discovery_cache\").setLevel(logging.ERROR)\nlogger = singer.get_logger()\n\nSCOPES = [\n \"https://www.googleapis.com/auth/bigquery\",\n \"https://www.googleapis.com/auth/bigquery.insertdata\",\n]\nCLIENT_SECRET_FILE = \"client_secret.json\"\nAPPLICATION_NAME = \"Singer BigQuery Target\"\n\nStreamMeta = collections.namedtuple(\n \"StreamMeta\", [\"schema\", \"key_properties\", \"bookmark_properties\"]\n)\n\n\ndef main():\n parser = argparse.ArgumentParser(parents=[tools.argparser])\n parser.add_argument(\"-c\", \"--config\", help=\"Config file\", required=True)\n flags = parser.parse_args()\n\n with open(flags.config) as input:\n config = json.load(input)\n\n if not config.get(\"disable_collection\", False):\n logger.info(\n \"Sending version information to stitchdata.com. \"\n \"To disable sending anonymous usage data, set \"\n \"the config parameter 'disable_collection' to true\"\n )\n threading.Thread(target=collect).start()\n\n if config.get(\"replication_method\") == \"FULL_TABLE\":\n truncate = True\n else:\n truncate = False\n forced_fulltables = config.get(\"forced_fulltables\", [])\n table_suffix = config.get(\"table_suffix\")\n\n location = config.get(\"location\", \"EU\")\n\n validate_records = config.get(\"validate_records\", True)\n\n input = io.TextIOWrapper(sys.stdin.buffer, encoding=\"utf-8\")\n\n project_id, dataset_id = config[\"project_id\"], config[\"dataset_id\"]\n\n client, dataset = ensure_dataset(project_id, dataset_id, location)\n\n if config.get(\"stream_data\", True):\n state_iterator = persist_lines_stream(\n client, dataset, input, validate_records=validate_records,\n )\n\n else:\n state_iterator = persist_lines_job(\n client,\n dataset,\n input,\n truncate=truncate,\n forced_fulltables=forced_fulltables,\n validate_records=validate_records,\n table_suffix=table_suffix,\n )\n\n for state in state_iterator:\n emit_state(state)\n\n\ndef ensure_dataset(project_id, dataset_id, location):\n client = bigquery.Client(project=project_id, location=location)\n\n dataset_ref = client.dataset(dataset_id)\n try:\n client.create_dataset(dataset_ref, exists_ok=True)\n except Exception:\n # attempt to run even if creation fails due to permissions etc.\n pass\n\n return client, Dataset(dataset_ref)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"target_bigquery/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"121243123","text":"\"\"\"\nBuild scikit learn clustering model using MiniBatchKmeans, classif input data, export relevant tweets, export model as .pkl file\n\"\"\"\n\n\nimport json\nimport numpy as np\nfrom sklearn import cluster\nfrom sklearn.externals import joblib\n\ntweets = {}\n#Words that indicate hurricane info, words that indicate disaster event, words that indicate irrelevant tweet\nkeywords_primary = set((\"hurricane\", \"sandy\", \"storm\", \"surge\", \"canceled\"))\nkeywords_secondary = set((\"surge\", \"canceled\", \"evac\", \"evacuate\", \"flood\", \"wind\", \"winds\", \"police\", \"authorities\", \"emerg\", \"emergency\", \"emergencies\", \"closing\", \"crisis\"))\nno_words = set((\"glass\", \"hawker\", \"prayers\", \"campaign\", \"campaigns\", \"cheeks\", \"election\", \"ain't\", \"shit\", \"fuck\", \"gop\", \"u\", \"obama\", \"romney\", \"mittstormtips\"))\n\n\n# Relevant tweet\ninitial_relevant_tweet = \"IF I LOSE POWER FOR A WEEK FROM THIS HURRICANE LIKE I DID LAST YEAR I'LL BE PISSED\"\n\n\n'''\na: flood damage\nb: electrical issues \nc: people trapped\nd: road blocked\ne: fire\n'''\n\ndef sanitize(text):\n\t#Create a bag of symbol-free, lowercase words\n\twords = text.split()\n\tfinal = []\n\thashtags = []\n\tfor word in words:\n\t\tif \"http\" not in word and \"@\" not in word:\n\t\t\tif \"#\" in word:\n\t\t\t\tclean = word.replace(\"#\", \"\").lower()\n\t\t\t\tclean = \"\".join([x for x in clean if x.isalpha()])\n\t\t\t\thashtags.append(clean)\n\t\t\t\tif clean != \"\":\n\t\t\t\t\tfinal.append(clean)\n\t\t\telse:\n\t\t\t\tclean = word.lower()\n\t\t\t\tclean = \"\".join([x for x in clean if x.isalpha()])\n\t\t\t\tif clean != \"\":\n\t\t\t\t\tfinal.append(clean)\n\n\treturn final, hashtags\ndef gen_features(word_list):\n\tfeatures = [0] * 5\n\tfor i in range(0, len(word_list)):\n\t\tif word_list[i] in keywords_primary:\n\t\t\tfeatures[0] += 1\n\t\tif word_list[i] in keywords_secondary:\n\t\t\tfeatures[1] += 1\n\t\t\tfeatures[0] += 1\n\t\tif word_list[i] in no_words:\n\t\t\tfeatures[2] += 1\n\tif \"hurricane\" in word_list and \"sandy\" not in word_list:\n\t\tfeatures[0] -= 1\n\tif \"sandy\" in word_list and \"hurricane\" not in word_list:\n\t\tfeatures[0] -= 1\n\tchars = sum([len(x) for x in word_list])\n\tfeatures[3] = len(word_list)\n\tfeatures[4] = float(chars) / len(word_list)\n\treturn features\n\nif __name__ == '__main__':\t\n\tclusts = None\n\trow_to_id = {}\n\t#Load tweets, handle broken json issues\n\twith open(\"29Oct2012-31Oct2012.json\") as f:\n\t\tfor line in f:\n\t\t\ttry:\n\t\t\t\tt = json.loads(line)\n\t\t\t\tif t['text']:\n\t\t\t\t\ttext = t['text'].replace(\"\\n\", \" \")\n\t\t\t\t\twords, tags = sanitize(text)\n\t\t\t\t\tif t['from_user_name'] != 0:\n\t\t\t\t\t\ttweets[t[\"id\"]] = (words, tags, text, t['from_user_name'])\n\t\t\t\t\telse:\n\t\t\t\t\t\ttweets[t[\"id\"]] = (words, tags, text, \"json issues\")\n\t\t\texcept ValueError as e:\n\t\t\t\tpass\n\t\n\t#Build feature set\n\tfeatures = np.zeros((len(tweets), 5))\n\tcount = 0\n\tfor t in tweets:\n\t\trow_to_id[count] = t\n\t\tfeatures[count, 0] = t\n\t\tx = gen_features(tweets[t][0])\n\t\tfor i in range(0, len(x)):\n\t\t\tfeatures[count, i] = x[i]\n\t\tcount += 1\n\n\t#Build model, apply model\n\tmbk = cluster.MiniBatchKMeans(n_clusters=2)\n\tclusts = mbk.fit_predict(features)\n\ttest = np.array(gen_features(sanitize(initial_relevant_tweet)[0]))\n\ttest = test.reshape(1, -1)\n\tprint(test)\n\tprint(\"TEST Y\")\n\ttest_y = mbk.predict(test)\n\tprint(test_y)\n\tpos_class = 0\n\t#Output tweets in relevant category\n\twith open(\"relevant.txt\", \"w+\") as out:\n\t\t\tfor i in range(len(clusts)):\n\t\t\t\tt = row_to_id[i]\t\t\t\t\n\t\t\t\tif clusts[i] == test_y:\n\t\t\t\t\tpos_class += 1\n\t\t\t\t\tout.write(tweets[t][2] + \"\\n\" + \",\".join(tweets[t][0]) + \"\\n\")\n\tneg_class = len(clusts) - pos_class\n\tpercent_removed = 10 * float(neg_class) / len(clusts)\n\tx = np.array([5, 5, 0, 15, 6]).reshape(1, -1)\n\tprint(\"TRIAL Y\")\n\tprint(mbk.predict(x)[0])\n\n\t#Output model\n\tjoblib.dump(mbk, \"cluster_model.pkl\")\n\n","sub_path":"build_cluster.py","file_name":"build_cluster.py","file_ext":"py","file_size_in_byte":3612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"468759506","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nThis implementation of BaseMarkdownTransformer handles paragraphs\n\"\"\"\nimport typing\n\nfrom borb.pdf.canvas.color.color import Color, HexColor\nfrom borb.pdf.canvas.font.font import Font\nfrom borb.pdf.canvas.font.simple_font.font_type_1 import StandardType1Font\nfrom borb.pdf.canvas.layout.emoji.emoji import Emoji, Emojis\nfrom borb.pdf.canvas.layout.text.chunk_of_text import ChunkOfText\nfrom borb.pdf.canvas.layout.text.chunks_of_text import (\n HeterogeneousParagraph,\n LineBreakChunk,\n)\nfrom borb.toolkit.export.markdown_to_pdf.markdown_transformer.base_markdown_transformer import (\n BaseMarkdownTransformer,\n MarkdownTransformerState,\n)\n\n\nclass ParagraphTransformer(BaseMarkdownTransformer):\n \"\"\"\n This implementation of BaseMarkdownTransformer handles paragraphs\n \"\"\"\n\n def _can_transform(self, context: MarkdownTransformerState) -> bool:\n \"\"\"\n This function always returns True, anything can be a Paragraph\n \"\"\"\n return context.get_markdown_string()[\n context.tell()\n ].isalpha() or context.get_markdown_string()[context.tell()] in [\n \"*\",\n \"_\",\n \":\",\n \"\\\\\",\n \"`\",\n ]\n\n def _get_font(self, is_bold: bool, is_italic: bool, is_monospaced: bool) -> Font:\n if is_monospaced:\n return StandardType1Font(\"Courier\")\n if is_bold and is_italic:\n return StandardType1Font(\"Helvetica-bold-oblique\")\n elif is_bold:\n return StandardType1Font(\"Helvetica-bold\")\n elif is_italic:\n return StandardType1Font(\"Helvetica-oblique\")\n else:\n return StandardType1Font(\"Helvetica\")\n\n def _build_chunks(\n self, text: str, is_bold: bool, is_italic: bool, is_monospaced: bool\n ) -> typing.List[ChunkOfText]:\n out: typing.List[ChunkOfText] = []\n for w in text.split(\" \"):\n background_color: Color = HexColor(\"ffffff\")\n if is_monospaced:\n background_color = HexColor(\"c3c3c3\")\n out.append(\n ChunkOfText(\n w + \" \",\n font=self._get_font(is_bold, is_italic, is_monospaced),\n background_color=background_color,\n )\n )\n return out\n\n def _transform(self, context: MarkdownTransformerState) -> None:\n\n # continue processing lines until we hit \n end_pos: int = self._until_double_newline(context)\n if end_pos == -1:\n end_pos = len(context.get_markdown_string()) + 1\n paragraph_lines_raw: typing.List[str] = context.get_markdown_string()[\n context.tell() : end_pos - 1\n ].split(\"\\n\")\n\n # process each line\n chunks_of_text: typing.List[typing.Union[ChunkOfText, Emoji]] = []\n is_bold: bool = False\n is_italic: bool = False\n is_monospaced: bool = False\n chunk_text: str = \"\"\n for paragraph_line in paragraph_lines_raw:\n i: int = 0\n while i < len(paragraph_line):\n # process \\<\n c: str = paragraph_line[i]\n if (\n c == \"\\\\\"\n and i + 1 < len(paragraph_line)\n and paragraph_line[i + 1] in [\">\", \"<\", \"*\", \"+\", \"-\", \"_\", \"`\"]\n ):\n chunk_text += paragraph_line[i + 1]\n i += 2\n continue\n # process ::\n if (\n not is_monospaced\n and c == \":\"\n and paragraph_line.find(\":\", i + 1) >= 0\n and paragraph_line[i + 1 : paragraph_line.find(\":\", i + 1)].upper()\n in [x.name for x in Emojis]\n ):\n emoji_name: str = paragraph_line[\n i + 1 : paragraph_line.find(\":\", i + 1)\n ]\n chunks_of_text.extend(\n self._build_chunks(\n chunk_text, is_bold, is_italic, is_monospaced\n )\n )\n chunks_of_text.append(Emojis[emoji_name.upper()].value)\n chunk_text = \"\"\n i = paragraph_line.find(\":\", i + 1) + 1\n continue\n # process ***\n if (\n c == \"*\"\n and i + 1 < len(paragraph_line)\n and paragraph_line[i + 1] == \"*\"\n and i + 2 < len(paragraph_line)\n and paragraph_line[i + 2] == \"*\"\n ):\n chunks_of_text.extend(\n self._build_chunks(\n chunk_text, is_bold, is_italic, is_monospaced\n )\n )\n chunk_text = \"\"\n is_bold = not is_bold\n is_italic = not is_italic\n i += 3\n continue\n # process ___\n if (\n c == \"_\"\n and i + 1 < len(paragraph_line)\n and paragraph_line[i + 1] == \"_\"\n and i + 2 < len(paragraph_line)\n and paragraph_line[i + 2] == \"_\"\n ):\n chunks_of_text.extend(\n self._build_chunks(\n chunk_text, is_bold, is_italic, is_monospaced\n )\n )\n chunk_text = \"\"\n is_bold = not is_bold\n is_italic = not is_italic\n i += 3\n continue\n # process **\n if (\n c == \"*\"\n and i + 1 < len(paragraph_line)\n and paragraph_line[i + 1] == \"*\"\n ):\n chunks_of_text.extend(\n self._build_chunks(\n chunk_text, is_bold, is_italic, is_monospaced\n )\n )\n chunk_text = \"\"\n is_bold = not is_bold\n i += 2\n continue\n # process __\n if (\n c == \"_\"\n and i + 1 < len(paragraph_line)\n and paragraph_line[i + 1] == \"_\"\n ):\n chunks_of_text.extend(\n self._build_chunks(\n chunk_text, is_bold, is_italic, is_monospaced\n )\n )\n chunk_text = \"\"\n is_bold = not is_bold\n i += 2\n continue\n # process *\n if c == \"*\":\n chunks_of_text.extend(\n self._build_chunks(\n chunk_text, is_bold, is_italic, is_monospaced\n )\n )\n chunk_text = \"\"\n is_italic = not is_italic\n i += 1\n continue\n # process _\n if c == \"_\":\n chunks_of_text.extend(\n self._build_chunks(\n chunk_text, is_bold, is_italic, is_monospaced\n )\n )\n chunk_text = \"\"\n is_italic = not is_italic\n i += 1\n continue\n # process `\n if c == \"`\":\n chunks_of_text.extend(\n self._build_chunks(\n chunk_text, is_bold, is_italic, is_monospaced\n )\n )\n chunk_text = \"\"\n is_monospaced = not is_monospaced\n i += 1\n continue\n # process \n if (\n i == len(paragraph_line) - 2\n and c == \" \"\n and paragraph_line[i + 1] == \" \"\n ):\n chunks_of_text.extend(\n self._build_chunks(\n chunk_text, is_bold, is_italic, is_monospaced\n )\n )\n chunks_of_text.append(LineBreakChunk())\n chunk_text = \"\"\n i += 2\n continue\n # process any character\n chunk_text += c\n i += 1\n\n # append any remaining chunks\n if len(chunk_text) > 0:\n chunks_of_text.extend(\n self._build_chunks(chunk_text, is_bold, is_italic, is_monospaced)\n )\n\n # append HeterogeneousParagraph\n context.get_parent_layout_element().add(HeterogeneousParagraph(chunks_of_text)) # type: ignore [union-attr]\n\n # seek\n context.seek(end_pos)\n","sub_path":"lamda-ocr/merge-files/borb/toolkit/export/markdown_to_pdf/markdown_transformer/text/paragraph_transformer.py","file_name":"paragraph_transformer.py","file_ext":"py","file_size_in_byte":9215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"303707668","text":"# 문제\n\n# 무인도에 갇힌 사람들을 구명보트를 이용하여 구출하려고 합니다. 구명보트는 작아서 한 번에 최대 2명씩 밖에 탈 수 없고, 무게 제한도 있습니다.\n# 예를 들어, 사람들의 몸무게가 [70kg, 50kg, 80kg, 50kg]이고 구명보트의 무게 제한이 100kg이라면 2번째 사람과 4번째 사람은 같이 탈 수 있지만 \n# 1번째 사람과 3번째 사람의 무게의 합은 150kg이므로 구명보트의 무게 제한을 초과하여 같이 탈 수 없습니다.\n# 구명보트를 최대한 적게 사용하여 모든 사람을 구출하려고 합니다.\n# 사람들의 몸무게를 담은 배열 people과 구명보트의 무게 제한 limit가 매개변수로 주어질 때, \n# 모든 사람을 구출하기 위해 필요한 구명보트 개수의 최솟값을 return 하도록 solution 함수를 작성해주세요.\n\n# 제한사항\n\n# 무인도에 갇힌 사람은 1명 이상 50,000명 이하입니다.\n# 각 사람의 몸무게는 40kg 이상 240kg 이하입니다.\n# 구명보트의 무게 제한은 40kg 이상 240kg 이하입니다.\n# 구명보트의 무게 제한은 항상 사람들의 몸무게 중 최댓값보다 크게 주어지므로 사람들을 구출할 수 없는 경우는 없습니다.\n\n# 입출력 예\n# people\t limit\t return\n# [70, 50, 80, 50]\t 100\t 3\n# [70, 80, 50]\t 100\t 3\n\n\n# 문제 풀이 방법 (이분탐색)\n\n# 1. 오름차순 정렬한다.\n# 2. start, end = 0, len(people)-1 지정하여 가장 가벼운 사람 가장 무거운 사람을 지정한다. \n# 3. people[start] + pelple[end] <= limit 이면 2명이서 보트를 탈수 있으므로, start와 end를 변경할수 있다.\n# 4. 사람 수는 최대로 필요한 보트 수를 의미하므로 \"사람의 수 - 이분 탐색을 통해 구한 값\"을 하면 원하는 답을 얻을 수 있다.\n\n\ndef solution(people, limit):\n answer = 0\n people.sort()\n \n start ,end = 0, len(people) - 1\n \n while start < end:\n if people[start] + people[end] <= limit: \n start += 1\n answer += 1\n end -= 1\n \n return len(people) - answer\n\n# 디버깅 (예시기준)\n\n# answer : 0 people.sort : [50, 50, 70, 80], start = 0 end = len(people) - 1\n# start < end: 0 < 3, people[start] = 50 + people[end] = 80 <= limit : 100 >> 50 + 80 <= 100 false\n# end -= 1 이므로 2 다시 start < end: >> 0 < 2: >> 50 + 70 <= 100 false\n# end -= 1 이므로 1 다시 start < end: >> 0 < 1: >> 50 + 50 <= 100 true\n# start = 1 answer = 1 다시 while문 돌아가서 진행 start < end: >> 1 < 1: 이므로 조건 만족 안하므로 while문 빠져나옴\n# return 문 len(people) - answer = 4 -1 = 3 \n\n\n","sub_path":"KYJ/프로그래머스/탐욕법/구명보트.py","file_name":"구명보트.py","file_ext":"py","file_size_in_byte":2738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"64755877","text":"# C-RNN networks\r\n\r\nfrom keras.datasets import imdb\r\nfrom keras.preprocessing import sequence\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, Embedding, LSTM\r\nfrom keras.layers import Flatten, Dropout, Conv1D, MaxPooling1D\r\n\r\nmax_features = 20000\r\ntest_max_words = 200\r\n\r\n# Datasets\r\n\r\n(x_train,y_train),(x_test,y_test) = imdb.load_data(num_words=max_features)\r\n\r\nx_val = x_train[20000:]\r\ny_val = y_train[20000:]\r\nx_train = x_train[:20000]\r\ny_train = y_train[:20000]\r\n\r\nx_train = sequence.pad_sequences(x_train,maxlen=test_max_words)\r\nx_val = sequence.pad_sequences(x_val,maxlen=test_max_words)\r\nx_test = sequence.pad_sequences(x_test,maxlen=test_max_words)\r\n\r\n# Model\r\n\r\nmodel = Sequential()\r\nmodel.add(Embedding(max_features,128,input_length=test_max_words))\r\nmodel.add(Dropout(0.2))\r\nmodel.add(Conv1D(256,3,padding='valid',activation='relu',strides=1))\r\nmodel.add(MaxPooling1D(pool_size=4))\r\nmodel.add(LSTM(128))\r\nmodel.add(Dense(1,activation='sigmoid'))\r\n\r\nmodel.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])\r\n\r\n# Training the model\r\nhist = model.fit(x_train,y_train,epochs=2,batch_size=64,validation_data=(x_val,y_val))\r\n\r\n# Evaluation\r\n\r\nloss_and_metrics = model.evaluate(x_test,y_test,batch_size=64)\r\nprint(\"Evaluation: \",loss_and_metrics)","sub_path":"C-RNN.py","file_name":"C-RNN.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"493880561","text":"'''\nhttps://leetcode.com/problems/search-insert-position/description/\n'''\n\n\n# O(n)\ndef searchInsert(nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n\n for i in range(len(nums)):\n if(target == nums[i]):\n return i\n elif(target < nums[i]):\n return i\n return len(nums)\n\nl = [1,3,5,6]\n # O(log(n)) -> binary search\nclass Solution:\n def searchInsert(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n l, r = 0, len(nums)-1\n while l <= r:\n if target > nums[r]:\n return r+1\n if target < nums[l]:\n return l\n \n mid = (l+r)//2\n if nums[mid] == target:\n return mid\n elif nums[mid] > target:\n r = mid-1\n else:\n l = mid+1\n \n\ntargets = [5,2,7,0]\n\nfor target in targets:\n print(searchInsert(l,target))\n\n \n","sub_path":"LeetCode/1. Easy/Search Insert Position.py","file_name":"Search Insert Position.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"37303210","text":"from difflib import SequenceMatcher\n\ndef similar(a, b):\n return SequenceMatcher(None, a, b).ratio()\n\ndef main():\n word_list = input('Enter the path to word list: ')\n with open(word_list) as f:\n words = f.readlines()\n\n words = [word.strip('\\n') for word in words]\n\n para = input(\"Enter the paragraph to be corrected: \")\n\n para = para.split()\n\n for word in words:\n for i, para_word in enumerate(para):\n if word.upper() != para_word.upper():\n if similar(word, para_word) >= 0.8: #They are probably the same word.\n para[i] = word #This is considering the given list to us is correct.\n if para_word[-1] == '.':\n para[i] += '.'\n \n print(f'The corrected paragraph:\\n{\" \".join(para)}')\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"naiveApproach.py","file_name":"naiveApproach.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"626418700","text":"# code-checked\n# server-checked\n\nfrom model import ToyNet\n\nimport torch\nimport torch.utils.data\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nimport numpy as np\nimport pickle\nimport matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport cv2\n\nimport numpy as np\n\nL = 256\nnum_epochs = L*150\n\nnum_epochs_low = int(0.75*num_epochs)\nprint (num_epochs_low)\n\nx_min = -6.0\nx_max = 6.0\nnum_points = 60\n\nM_values = [1, 4, 16, 64, 256]\nfor M in M_values:\n for iter in range(6):\n print (M)\n\n if M > 1:\n step_size = float(num_epochs - num_epochs_low)/float(M-1)\n else:\n step_size = 0\n print (step_size)\n\n networks = []\n for i in range(M):\n print (int(num_epochs - i*step_size))\n\n network = ToyNet(\"eval_SGLD-256_1-10\", project_dir=\"/root/evaluating_bdl/toyClassification\").cuda()\n network.load_state_dict(torch.load(\"/root/evaluating_bdl/toyClassification/training_logs/model_SGLD-256_%d/checkpoints/model_SGLD-256_%d_epoch_%d.pth\" % (iter+1, iter+1, int(num_epochs - i*step_size))))\n networks.append(network)\n\n M_float = float(len(networks))\n print (M_float)\n\n for network in networks:\n network.eval()\n\n false_prob_values = np.zeros((num_points, num_points))\n x_values = np.linspace(x_min, x_max, num_points, dtype=np.float32)\n for x_1_i, x_1_value in enumerate(x_values):\n for x_2_i, x_2_value in enumerate(x_values):\n x = torch.from_numpy(np.array([x_1_value, x_2_value])).unsqueeze(0).cuda() # (shape: (1, 2))\n\n mean_prob_vector = np.zeros((2, ))\n for network in networks:\n logits = network(x) # (shape: (1, num_classes)) (num_classes==2)\n prob_vector = F.softmax(logits, dim=1) # (shape: (1, num_classes))\n\n prob_vector = prob_vector.data.cpu().numpy()[0] # (shape: (2, ))\n\n mean_prob_vector += prob_vector/M_float\n\n false_prob_values[x_2_i, x_1_i] = mean_prob_vector[0]\n\n plt.figure(1)\n x_1, x_2 = np.meshgrid(x_values, x_values)\n plt.pcolormesh(x_1, x_2, false_prob_values, cmap=\"RdBu\", vmin=0, vmax=1)\n plt.colorbar()\n plt.tight_layout(pad=0.1, w_pad=0.1, h_pad=0.1)\n plt.savefig(\"%s/predictive_density_M=%d_%d.png\" % (network.model_dir, M, iter+1))\n plt.close(1)\n\n print (\"##################################################################\")\n\n# M = int(M)\n#\n# fc1_weight_samples = np.zeros((M, 1, 10, 2))\n# fc1_bias_samples = np.zeros((M, 1, 10))\n# fc2_weight_samples = np.zeros((M, 1, 10, 10))\n# fc2_bias_samples = np.zeros((M, 1, 10))\n# fc3_weight_samples = np.zeros((M, 1, 2, 10))\n# fc3_bias_samples = np.zeros((M, 1, 2))\n# for index, network in enumerate(networks):\n# for name, param in network.named_parameters():\n# if name == \"fc1.weight\":\n# fc1_weight_samples[index, 0, :] = param.data.cpu().numpy()\n# elif name == \"fc1.bias\":\n# fc1_bias_samples[index, 0, :] = param.data.cpu().numpy()\n# elif name == \"fc2.weight\":\n# fc2_weight_samples[index, 0, :] = param.data.cpu().numpy()\n# elif name == \"fc2.bias\":\n# fc2_bias_samples[index, 0, :] = param.data.cpu().numpy()\n# elif name == \"fc3.weight\":\n# fc3_weight_samples[index, 0, :] = param.data.cpu().numpy()\n# elif name == \"fc3.bias\":\n# fc3_bias_samples[index, 0, :] = param.data.cpu().numpy()\n# else:\n# raise Exception(\"Unknown network parameter!\")\n#\n# import os\n# if not os.path.exists(\"%s/param_distributions\" % (network.model_dir)):\n# os.makedirs(\"%s/param_distributions\" % (network.model_dir))\n#\n# # (fc1_weight_samples has shape: (M, 1, 10, 2))\n# for param_index_i in range(10):\n# for param_index_j in range(2):\n# values = fc1_weight_samples[:, 0, param_index_i, param_index_j] # (shape: (M, ))\n# plt.figure(1)\n# plt.hist(np.array(values), bins=100)\n# plt.savefig(\"%s/param_distributions/fc1_weight_%d_%d.png\" % (network.model_dir, param_index_i, param_index_j))\n# plt.close(1)\n#\n# # (fc1_bias_samples has shape: (M, 1, 10))\n# for param_index in range(10):\n# values = fc1_bias_samples[:, 0, param_index] # (shape: (M, ))\n# plt.figure(1)\n# plt.hist(np.array(values), bins=100)\n# plt.savefig(\"%s/param_distributions/fc1_bias_%d.png\" % (network.model_dir, param_index))\n# plt.close(1)\n#\n# # (fc2_weight_samples has shape: (M, 1, 10, 10))\n# for param_index_i in range(10):\n# for param_index_j in range(10):\n# values = fc2_weight_samples[:, 0, param_index_i, param_index_j] # (shape: (M, ))\n# plt.figure(1)\n# plt.hist(np.array(values), bins=100)\n# plt.savefig(\"%s/param_distributions/fc2_weight_%d_%d.png\" % (network.model_dir, param_index_i, param_index_j))\n# plt.close(1)\n#\n# # (fc2_bias_samples has shape: (M, 1, 10))\n# for param_index in range(10):\n# values = fc2_bias_samples[:, 0, param_index] # (shape: (M, ))\n# plt.figure(1)\n# plt.hist(np.array(values), bins=100)\n# plt.savefig(\"%s/param_distributions/fc2_bias_%d.png\" % (network.model_dir, param_index))\n# plt.close(1)\n#\n# # (fc3_weight_samples has shape: (M, 1, 2, 10))\n# for param_index_i in range(2):\n# for param_index_j in range(10):\n# values = fc3_weight_samples[:, 0, param_index_i, param_index_j] # (shape: (M, ))\n# plt.figure(1)\n# plt.hist(np.array(values), bins=100)\n# plt.savefig(\"%s/param_distributions/fc3_weight_%d_%d.png\" % (network.model_dir, param_index_i, param_index_j))\n# plt.close(1)\n#\n# # (fc3_bias_samples has shape: (M, 1, 2))\n# for param_index in range(2):\n# values = fc3_bias_samples[:, 0, param_index] # (shape: (M, ))\n# plt.figure(1)\n# plt.hist(np.array(values), bins=100)\n# plt.savefig(\"%s/param_distributions/fc3_bias_%d.png\" % (network.model_dir, param_index))\n# plt.close(1)\n","sub_path":"toyClassification/SGLD-256/eval_plots.py","file_name":"eval_plots.py","file_ext":"py","file_size_in_byte":6133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"45815540","text":"import jetmath as jm\n\nACTIVATION_FUNCTIONS = {\n \"relu\": {\n \"_\": jm.nonlin.relu,\n \"derivative\": jm.nonlin.relu_p\n },\n \"leaky-relu\": {\n \"_\": jm.nonlin.leaky_relu,\n \"derivative\": jm.nonlin.leaky_relu_p\n },\n \"sigmoid\": {\n \"_\": jm.nonlin.sigmoid,\n \"derivative\": jm.nonlin.sigmoid_p\n }\n}\n\nNEAT_WEIGHTS_MUTATION_FUNCTIONS = {\n \"replace\": {\n \"_\": lambda x : jm.random.randd(),\n \"use\": 0.10\n },\n \"add-random\": {\n \"_\": lambda x : x + jm.random.uniform(0, 0.2),\n \"use\": 0.45\n },\n \"subtract-random\": {\n \"_\": lambda x : x - jm.random.uniform(0, 0.2),\n \"use\": 0.45\n }\n}\n\n","sub_path":"jetml/vars.py","file_name":"vars.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"440478042","text":"from bs4 import BeautifulSoup\r\nimport requests\r\nimport requests, six\r\nimport lxml.html as lh\r\nfrom itertools import cycle, islice\r\nimport pandas as pd\r\nfrom openpyxl import Workbook\r\n\r\n\r\nhtml_text = requests.get('http://www.nepalstock.com/stockWisePrices').text\r\n\r\n\r\nsoup = BeautifulSoup(html_text,'lxml')\r\n\r\nselect = soup.find('select',class_='stock-symbol')\r\n\r\noptions = select.find_all('option')\r\n\r\n#At first we need to find symbol no of each company, its different from company sybmbol\r\nfor option in options:\r\n\r\n\ttostr = str(option)\r\n\tspl = tostr.split('\\\"')\r\n\tsymbolno = spl[1]\r\n\tstockname = option.text\r\n\r\n\t#These company has \\ in their symbol, I couldnt escape it and they are probably promoter share or something so i decided to skip it\r\n\tif(symbolno==\"2840\" or symbolno==\"2825\" or symbolno==\"2868\"):\r\n\t\tcontinue\r\n\r\n\tprint(symbolno)\r\n\tprint(stockname)\r\n\r\n\r\n\t#Real magic, leak i found on nepse\r\n\turl=\"http://www.nepalstock.com/main/stockwiseprices/index/150/?startDate=2000-01-01&endDate=2021-05-04&stock-symbol=\"+symbolno+\"&_limit=5000\"\r\n\r\n\tpage = requests.get(url)\r\n\r\n\tworkbook = Workbook()\r\n\tws = workbook.active\r\n\r\n\tdoc = lh.fromstring(page.content)\r\n\r\n\ttr_elements = doc.xpath('//tr')\r\n\r\n\r\n\tfor j in range(1,len(tr_elements)):\r\n\t\trow = tr_elements[j]\r\n\r\n\t\ti=0\r\n\r\n\t\trowdata = []\r\n\r\n\t\tfor t in row.iterchildren():\r\n\t\t\tdata=t.text_content()\r\n\t\t\trowdata.append(data)\r\n\r\n\t\tprint(rowdata)\r\n\r\n\t\tws.append(rowdata)\r\n\r\n\tworkbook.save(stockname+\".xlsx\")","sub_path":"scrap.py","file_name":"scrap.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"81018147","text":"#!/usr/bin/env python\n\nimport copy\nimport os\nimport struct\n\nimport click\n\nfrom . import terraform as tf\nfrom . import vault\nfrom .main import State, create_table, get_aws_id\n\nDEFAULT_CONFIG = \"{}/worker.yaml\".format(os.getcwd())\nDEFAULT_REPOSITORY_PATH = \"{}\".format(os.getcwd())\nDEFAULT_S3_BUCKET = \"launchpad-terraform-states\"\nDEFAULT_S3_PREFIX = \"terraform/state/{deployment}\"\nDEFAULT_AWS_REGION = \"us-west-2\"\nDEFAULT_STATE_REGION = \"us-west-2\"\nDEFAULT_TERRFORM = \"/usr/local/bin/terraform\"\n\n\ndef validate_deployment(ctx, deployment, name):\n \"\"\"Validate the deployment is an 8 char name.\"\"\"\n if len(name) > 16:\n click.secho(\"deployment must be less than 16 characters\", fg=\"red\")\n raise SystemExit(2)\n return name\n\n\ndef validate_host():\n \"\"\"Ensure that the script is being run on a supported platform.\"\"\"\n if struct.calcsize(\"P\") * 8 != 64:\n click.secho(\"worker can only be run on 64 bit hosts, in 64 bit mode\", fg=\"red\")\n raise SystemExit(2)\n return True\n\n\ndef validate_keypair(pubkey, privkey, deployment, temp_dir, args):\n \"\"\"Validate the provided SSH key values, and their existence in vault.\"\"\"\n if pubkey is not None and privkey is None:\n click.secho(\"must pass --ssh-private-key when you supply a public SSH key\")\n raise SystemExit(2)\n\n if pubkey is None and privkey is not None:\n click.secho(\"must pass --ssh-public-key when you supply a private SSH key\")\n raise SystemExit(2)\n\n if pubkey is None and privkey is None:\n # No keys were passed so check inside of vault\n if not vault.check_keys(args.vault_address, args.vault_token, deployment):\n # No keys in vault, so generate a pair and save them\n pubkey, privkey = generate_keypair(temp_dir, deployment)\n vault.store_keys(\n args.vault_address, args.vault_token, deployment, pubkey, privkey\n )\n else:\n # Keys were passed on the command line, overwrite what is in vault\n vault.store_keys(\n args.vault_address, args.vault_token, deployment, pubkey, privkey\n )\n\n\n@click.group()\n@click.option(\n \"--aws-access-key-id\",\n required=True,\n envvar=\"AWS_ACCESS_KEY_ID\",\n help=\"AWS Access key\",\n)\n@click.option(\n \"--aws-secret-access-key\",\n required=True,\n prompt=True,\n hide_input=True,\n envvar=\"AWS_SECRET_ACCESS_KEY\",\n help=\"AWS access key secret\",\n)\n@click.option(\n \"--aws-region\",\n envvar=\"AWS_DEFAULT_REGION\",\n default=DEFAULT_AWS_REGION,\n help=\"AWS Region to build in\",\n)\n@click.option(\n \"--state-region\",\n default=DEFAULT_STATE_REGION,\n help=\"AWS region where terraform state bucket exists\",\n)\n@click.option(\n \"--config-file\", default=DEFAULT_CONFIG, envvar=\"WORKER_CONFIG_FILE\", required=True\n)\n@click.option(\n \"--repository-path\",\n default=DEFAULT_REPOSITORY_PATH,\n envvar=\"WORKER_REPOSITORY_PATH\",\n required=True,\n help=\"The path to the k8s-infra repository\",\n)\n@click.pass_context\ndef cli(context, **kwargs):\n \"\"\"CLI for the worker utility.\"\"\"\n validate_host()\n config_file = kwargs[\"config_file\"]\n try:\n context.obj = State(args=kwargs)\n except FileNotFoundError:\n click.secho(\n \"configuration file {} not found\".format(config_file), fg=\"red\", err=True\n )\n raise SystemExit(1)\n\n\n@cli.command()\n@click.option(\n \"--clean/--no-clean\",\n default=True,\n help=\"clean up the temporary directory created by the worker after execution\",\n)\n@click.option(\n \"--apply/--no-apply\",\n \"tf_apply\",\n default=False,\n help=\"apply the terraform configuration\",\n)\n@click.option(\n \"--destroy/--no-destroy\",\n default=False,\n help=\"destroy a deployment instead of create it\",\n)\n@click.option(\n \"--show-output/--no-show-output\",\n default=False,\n help=\"shot output from terraform commands\",\n)\n@click.option(\n \"--s3-bucket\",\n default=DEFAULT_S3_BUCKET,\n help=\"The s3 bucket for storing terraform state\",\n)\n@click.option(\n \"--s3-prefix\",\n default=DEFAULT_S3_PREFIX,\n help=\"The prefix in the bucket for the definitions to use\",\n)\n@click.option(\n \"--terraform-bin\",\n default=DEFAULT_TERRFORM,\n help=\"The complate location of the terraform binary\",\n)\n@click.option(\"--limit\", help=\"limit operations to a single definition\", multiple=True)\n@click.argument(\"deployment\", callback=validate_deployment)\n@click.pass_obj\ndef terraform(\n obj,\n clean,\n tf_apply,\n destroy,\n show_output,\n s3_bucket,\n s3_prefix,\n terraform_bin,\n limit,\n deployment,\n): # noqa: E501\n \"\"\"Build a deployment.\"\"\"\n if tf_apply and destroy:\n click.secho(\"can not apply and destroy at the same time\", fg=\"red\")\n raise SystemExit(1)\n plan_for = \"apply\"\n\n # If the default value is used, render the deployment name into it\n if s3_prefix == DEFAULT_S3_PREFIX:\n s3_prefix = DEFAULT_S3_PREFIX.format(deployment=deployment)\n obj.clean = clean\n obj.add_arg(\"s3_bucket\", s3_bucket)\n obj.add_arg(\"s3_prefix\", s3_prefix)\n obj.add_arg(\"terraform_bin\", terraform_bin)\n obj.add_arg(\n \"aws_account_id\",\n get_aws_id(obj.args.aws_access_key_id, obj.args.aws_secret_access_key),\n )\n\n click.secho(\"loading config file {}\".format(obj.args.config_file), fg=\"green\")\n obj.load_config(obj.args.config_file)\n\n click.secho(\"building deployment {}\".format(deployment), fg=\"green\")\n click.secho(\"using temporary Directory:{}\".format(obj.temp_dir), fg=\"yellow\")\n\n # common setup required for all definitions\n click.secho(\"downloading plugins\", fg=\"green\")\n tf.download_plugins(obj.config[\"terraform\"][\"plugins\"], obj.temp_dir)\n tf.prep_modules(obj.args.repository_path, obj.temp_dir)\n create_table(\n \"terraform-{}\".format(deployment),\n obj.args.state_region,\n obj.args.aws_access_key_id,\n obj.args.aws_secret_access_key,\n )\n\n # update mechanism for definitions\n # first determine apply/destroy\n # fix order\n # plan for apply/destroy\n # only execute apply/destroy if plan succeeds\n # fail / exit on any error\n\n tf_items = []\n\n # setup tf_items to capture the limit/order based on options\n if destroy:\n for name, body in reversed(obj.config[\"terraform\"][\"definitions\"].items()):\n if limit and name not in limit:\n continue\n tf_items.append((name, body))\n plan_for = \"destroy\"\n else:\n for name, body in obj.config[\"terraform\"][\"definitions\"].items():\n if limit and name not in limit:\n continue\n tf_items.append((name, body))\n\n for name, body in tf_items:\n execute = False\n # copy definition files / templates etc.\n click.secho(\"preparing definition: {}\".format(name), fg=\"green\")\n tf.prep_def(\n name,\n body,\n obj.config[\"terraform\"],\n obj.temp_dir,\n obj.args.repository_path,\n deployment,\n obj.args,\n )\n\n # run terraform init\n try:\n tf.run(\n name,\n obj.temp_dir,\n terraform_bin,\n \"init\",\n obj.args.aws_access_key_id,\n obj.args.aws_secret_access_key,\n debug=show_output,\n )\n except tf.TerraformError:\n click.secho(\"error running terraform init\", fg=\"red\")\n raise SystemExit(1)\n\n click.secho(\"planning definition: {}\".format(name), fg=\"green\")\n\n # run terraform plan\n try:\n tf.run(\n name,\n obj.temp_dir,\n terraform_bin,\n \"plan\",\n obj.args.aws_access_key_id,\n obj.args.aws_secret_access_key,\n debug=show_output,\n plan_action=plan_for,\n )\n except tf.PlanChange:\n execute = True\n except tf.TerraformError:\n click.secho(\n \"error planning terraform definition: {}!\".format(name), fg=\"red\"\n )\n raise SystemExit(1)\n\n if execute and tf_apply:\n click.secho(\"plan changes for {}, applying\".format(name), fg=\"yellow\")\n elif execute and destroy:\n click.secho(\"plan changes for {}, destroying\".format(name), fg=\"yellow\")\n elif not execute:\n click.secho(\"no plan changes for {}\".format(name), fg=\"yellow\")\n continue\n\n try:\n tf.run(\n name,\n obj.temp_dir,\n terraform_bin,\n plan_for,\n obj.args.aws_access_key_id,\n obj.args.aws_secret_access_key,\n debug=show_output,\n )\n except tf.TerraformError:\n click.secho(\n \"error with terraform {} on definition {}, exiting\".format(\n plan_for, name\n ),\n fg=\"red\",\n )\n else:\n click.secho(\n \"terraform {} complete for {}\".format(plan_for, name), fg=\"green\"\n )\n","sub_path":"worker/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":9163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"611722744","text":"import random\n\n\ndef data_interpret(data, feature):\n '''\n :param data: ALL OF THE DATA\n :param feature: The feature you want to consider (index)\n :return: The data interpret and given to the best hospital\n test age: 10-20\n '''\n\n hospital1 = []\n for sample in data:\n if 20 > sample[feature] > 10:\n hospital1.append(sample)\n\n for test in hospital1:\n if test[-1] == 0:\n pass\n else:\n hospital1.pop(hospital1.index(test))\n for i in range(600):\n hospital1.append(data[random.randint(1, len(data))])\n\n return hospital1\n\n\ndef compare_set(list1, data):\n hospital2 = []\n for i in range(len(list1)):\n hospital2.append(data[random.randint(1, len(data))])\n\n return hospital2\n\n\ndef generate_comb(exclude=None, death1=True):\n stage_of_disease = random.randint(1, 100) if exclude != 0 else None\n age = random.randint(0, 120) if exclude != 1 else None\n comorbidity = random.randint(1, 100) if exclude != 2 else None\n bmi = random.randint(1, 100) if exclude != 3 else None\n wealth = random.randint(1, 100) if exclude != 4 else None\n gender = random.choice([0, 100]) if exclude != 5 else None\n independency = random.choice([0, 50, 100]) if exclude != 6 else None\n smoke = random.choice([0, 100]) if exclude != 7 else None\n education = random.choice([0, 20, 40, 60, 80, 100]) if exclude != 8 else None\n race = random.choice([[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) if exclude != 9 else None\n death = random.choice([0, 100])\n if death1:\n return [stage_of_disease, age, comorbidity, bmi, wealth, gender, independency, smoke, education, race, death]\n return [stage_of_disease, age, comorbidity, bmi, wealth, gender, independency, smoke, education, race]\n\n\ndef rand_data(number):\n '''\n :param number: The number of data you wanted to randomize\n :return data: The data list of list returned as the data framework\n\n\n # stage of disease, age, comorbidity, bmi, wealth, gender, independency, smoke, race, education, death\ndata = [\\\n [23, 53, 26, 47, 10, 0, 50, 100, 0, [0,1,0,0], 1],\n [34, 23, 23, 16, 34, 0, 100, 100, 20, [1,0,0,0], 0],\n [75, 36, 84, 66, 30, 100, 50, 0, 40, [0,0,1,0], 1],\n [27, 72, 32, 84, 100, 100, 0, 100, 60, [0,0,0,1], 0],\n [84, 13, 75, 99, 30, 100, 100, 0, 100, [0,0,1,0], 0]]\n '''\n data = []\n for i in range(number):\n example = generate_comb()\n data.append(example)\n return data\n\n\ndef compare_hosp(feature_importance, hosp):\n index = 0\n ans = []\n for i in range(len(feature_importance)):\n if feature_importance[i] == max(feature_importance):\n index = i\n for hospital in hosp:\n ans.append(average(hospital)[index])\n\n return ans\n\n\ndef average(data):\n average = []\n for feature in range(9):\n feature_average = sum([sample[feature] for sample in data]) / len(data)\n average.append(feature_average)\n return average\n\n\ndef compare(A, B, no_feature):\n # compare current patient (A) and a sample patient in dataset (B) without given feature\n\n for feature in range(9):\n if feature != no_feature and abs(A[feature] - B[feature]) > 19:\n return False\n if no_feature != 9 and A[9] != B[9]:\n return False\n return True\n\n\ndef compare2(A, B, no_feature):\n for feature in range(9):\n if abs(A[no_feature] - B[no_feature]) > 1.1 and abs(A[feature] - B[feature]) > 19:\n return False\n if no_feature != 9 and A[9] != B[9]:\n return False\n return True\n\n\ndef calc_variance(dictionary):\n values = dictionary.values()\n mean = sum(values) / len(values)\n errors = [value - mean for value in values]\n variance = sum([i ** 2 for i in errors])\n return variance\n\n\npatient = [80, 16, 70, 94, 33, 100, 100, 0, 100, [0, 0, 1, 0]]\n\ndata = rand_data(10000)\nhospital1 = data_interpret(data, 1)\nhospital2 = compare_set(hospital1, data)\n\n\n##similar_1 = []\n##similar_2 = []\n##mortality_1 = 0\n##mortality_2 = 0\n##for i in range(len(data)):\n## if (compare2(patient, data[i], 1)):\n## similar_2.append(data[i])\n## if (compare(patient, data[i], 1)):\n## similar_1.append(data[i])\n##\n##for i in range(len(similar_1)):\n## mortality_1 += similar_1[i][-1]\n##for j in range(len(similar_2)):\n## mortality_2 += similar_2[j][-1]\n##\n##mortality_1 /= len(similar_1)\n##mortality_2 /= len(similar_2)\n##\n##rate_of_mort = mortality_1 / mortality_2\n##if (rate_of_mort > 1.2):\n## print(\"Weak performance\")\n##elif (rate_of_mort < 0.8):\n## print(\"good performance\")\n##else:\n## print(\"Normal\")\n\n\n# calculate the importance of each feature for general patients\nfeature_importance = []\nfor feature in range(0, 10):\n combs = [generate_comb(exclude=feature, death1=False) for i in range(300)]\n mortality_age = {}\n for comb in combs:\n similar_m = []\n similar_age = []\n for sample in data:\n if compare(comb, sample, feature):\n similar_m.append(sample[-1])\n similar_age.append(sample[1])\n for i in range(len(similar_m)):\n mortality_age[similar_age[i]] = mortality_age.get(similar_age[i], 0) + 1\n # calculate the variance\n variance = calc_variance(mortality_age)\n feature_importance.append(variance)\n\n # BILL YOU WRITES HERE\n\n ##for feature in range(10):\n ##\n ## # find similar patients in the dataset\n ## similar = []\n ## for sample in data:\n ## if compare(patient, sample, feature):\n ## similar.append(sample)\n ##\n ## # calculate average mortality rate of this feature\n ## total_mortality = 0\n ## for sample in similar:\n ## total_mortality += sample[-1]\n ## total_mortality /= len(similar)\n ##\n ## feature_importance.append(total_mortality)\n ##\n ##print(feature_importance)\n\n","sub_path":"Q1.py","file_name":"Q1.py","file_ext":"py","file_size_in_byte":6055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"453193606","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Dec 1 11:05:18 2017\r\n\r\n@author: r.dewinter\r\n\"\"\"\r\n\r\n#conda install -c conda-forge pygmo\r\n\r\nfrom CONSTRAINED_SMSEGO import CONSTRAINED_SMSEGO\r\n\r\nfrom paretofrontFeasible import paretofrontFeasible\r\n\r\nimport numpy as np\r\nimport time\r\nimport pandas as pd\r\nfrom functools import partial\r\nimport os\r\n\r\nfrom hypervolume import hypervolume\r\nfrom visualiseParetoFront import visualiseParetoFront\r\n\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.ticker as ticker\r\n\r\nimport mpld3\r\n\r\n\r\n\r\ndef parallel_coordinates(parameters, constraints, objectives, outdir=None, parNames=None):\r\n feasible = np.sum(constraints<=0, axis=1)==constraints.shape[1]\r\n dominant = paretofrontFeasible(objectives, constraints)\r\n rank = feasible+0+dominant+0 #+0 to convert to int\r\n \r\n objectives = objectives *-1\r\n for i in range(objectives.shape[1]):\r\n objectives[:,i] = (objectives[:,i] - min(objectives[:,i])) / (max(objectives[:,i]) - min(objectives[:,i]))\r\n \r\n alpha = np.sum(objectives, axis=1)\r\n alpha = alpha/max(alpha)\r\n \r\n colors = np.empty((len(alpha),3))\r\n \r\n brightness2 = np.empty(len(alpha))\r\n brightness2[:] = 0\r\n idx = rank==2\r\n brightness2[idx] = np.array(range(sum(idx)))\r\n brightness2 = brightness2/2\r\n brightness2 = brightness2/sum(idx)\r\n colors[idx] = np.array([brightness2, [1]*len(brightness2), brightness2]).T[idx]\r\n \r\n brightness1 = np.empty(len(alpha))\r\n brightness1[:] = 0\r\n idx = rank==1\r\n brightness1[idx] = np.array(range(sum(idx)))\r\n brightness1 = brightness1/2\r\n brightness1 = brightness1/sum(idx)\r\n colors[idx] = np.array([brightness1, brightness1, [1]*len(brightness1)]).T[idx]\r\n \r\n brightness0 = np.empty(len(alpha))\r\n brightness0[:] = 0\r\n idx = rank==0\r\n brightness0[idx] = np.array(range(sum(idx)))\r\n brightness0 = brightness0/2\r\n brightness0 = brightness0/sum(idx)\r\n colors[idx] = np.array([[1]*len(brightness0), brightness0, brightness0]).T[idx]\r\n \r\n data = np.column_stack((rank, parameters))\r\n order = data[:,0].argsort()\r\n colors = colors[order]\r\n data = data[order] #sort on rank\r\n rank = data[:,0]\r\n data_sets = data[:,1:] #remove rank\r\n alpha = alpha[order]\r\n \r\n if parNames is None or len(parNames)!=parameters.shape[1]:\r\n columNames=['parameter'+str(i) for i in range(parameters.shape[1])]\r\n else:\r\n columNames = parNames\r\n \r\n dims = len(data_sets[0])\r\n x = range(dims)\r\n fig, axes = plt.subplots(1, dims-1, sharey=False)\r\n\r\n if colors is None:\r\n colors = ['r-']*len(data_sets)\r\n \r\n # Calculate the limits on the data\r\n min_max_range = list()\r\n for m in zip(*data_sets):\r\n mn = min(m)\r\n mx = max(m)\r\n if mn == mx:\r\n mn -= 0.5\r\n mx = mn + 1.\r\n r = float(mx - mn)\r\n min_max_range.append((mn, mx, r))\r\n\r\n # Normalize the data sets\r\n norm_data_sets = list()\r\n for ds in data_sets:\r\n nds = []\r\n for dimension, value in enumerate(ds):\r\n v = (value - min_max_range[dimension][0]) / min_max_range[dimension][2]\r\n nds.append(v)\r\n norm_data_sets.append(nds)\r\n \r\n data_sets = norm_data_sets\r\n\r\n # Plot the datasets on all the subplots\r\n for i, ax in enumerate(axes):\r\n for dsi, d in enumerate(data_sets):\r\n ax.plot(x, d, c=colors[dsi], alpha=alpha[dsi])\r\n ax.set_xlim([x[i], x[i+1]])\r\n \r\n # Set the x axis ticks \r\n for dimension, (axx,xx) in enumerate(zip(axes, x[:-1])):\r\n axx.xaxis.set_major_locator(ticker.FixedLocator([xx]))\r\n ticks = len(axx.get_yticklabels())\r\n labels = list()\r\n step = min_max_range[dimension][2] / (ticks - 3)\r\n mn = min_max_range[dimension][0]\r\n for i in range(-1,ticks):\r\n v = mn + i*step\r\n labels.append('%6.2f' % v) \r\n axx.set_yticklabels(labels)\r\n\r\n\r\n # Move the final axis' ticks to the right-hand side\r\n axx = plt.twinx(axes[-1])\r\n dimension += 1\r\n axx.xaxis.set_major_locator(ticker.FixedLocator([x[-2], x[-1]]))\r\n ticks = len(axx.get_yticklabels())\r\n step = min_max_range[dimension][2] / (ticks - 1)\r\n mn = min_max_range[dimension][0]\r\n labels = ['%6.2f' % (mn + i*step) for i in range(ticks)]\r\n axx.set_yticklabels(labels) \r\n \r\n i=0\r\n for col in columNames[:-2]:\r\n plt.sca(axes[i])\r\n plt.xticks([i], (col,), rotation = 'vertical')\r\n i+=1\r\n plt.sca(axes[i])\r\n plt.xticks([i,i+1], columNames[i:], rotation = 'vertical')\r\n \r\n #color labels\r\n plt.plot([],[],color='r',label='Infeasible')\r\n plt.plot([],[],color='b',label='Feasible')\r\n plt.plot([],[],color='g',label='Non-dominated')\r\n \r\n #delete whitespace\r\n plt.subplots_adjust(wspace=0)\r\n \r\n #title\r\n plt.suptitle('Parallel Coordinate Plot')\r\n \r\n plt.legend(bbox_to_anchor=(1.6, 1), loc=2, borderaxespad=0.)\r\n plt.show()\r\n if outdir is not None: \r\n fig.savefig(str(outdir)+\"paralelcoordinate1.pdf\",dpi=600,bbox_inches='tight')\r\n else:\r\n fig.savefig(\"paralelcoordinate1.pdf\",dpi=600,bbox_inches='tight')\r\n\r\ndef convergence_plot(objectives, constraints, ref, outdir=None):\r\n paretoOptimal = np.empty(len(objectives), dtype=bool)\r\n paretoOptimal[:] = False\r\n progress_hypervolume = np.empty(len(objectives))\r\n progress_hypervolume[:] = 0\r\n \r\n for i in range(len(progress_hypervolume)):\r\n paretoOptimal[:i] = paretofrontFeasible(objectives[:i,:],constraints[:i,:])\r\n paretoFront = objectives[paretoOptimal]\r\n currentHV = hypervolume(paretoFront, ref)\r\n progress_hypervolume[i] = currentHV\r\n \r\n plt.title('Convergence Plot')\r\n plt.xlabel('Iteration')\r\n plt.ylabel('(Hyper) Volume')\r\n plt.plot(range(len(progress_hypervolume)),progress_hypervolume)\r\n if outdir is not None:\r\n plt.savefig(str(outdir)+'ConvergencePlot.pdf',dpi=600)\r\n else:\r\n plt.savefig('ConvergencePlot.pdf',dpi=600)\r\n\r\n\r\ndef compute_ship(x, nparameters, nconstraints, nobjectives, conValues, conMultiplier, objMultiplier):\r\n file_old = 'V:/temp/NAPA_RESULTS.csv'\r\n df_old_RESULTS = pd.read_csv(file_old)\r\n origheader = df_old_RESULTS.columns\r\n \r\n lenComputed = len(df_old_RESULTS)\r\n\r\n df_to_be_added = df_old_RESULTS.loc[lenComputed-1].values\r\n df_to_be_added[0] = df_to_be_added[0]+1\r\n df_to_be_added[1] = ''\r\n\r\n df_to_be_added[3:3+len(x)] = x\r\n df_to_be_added[3+len(x):len(df_to_be_added)] = np.zeros(len(df_to_be_added)-(3+len(x))) \r\n \r\n df_old_RESULTS.loc[lenComputed] = df_to_be_added\r\n df_old_RESULTS = df_old_RESULTS[origheader]\r\n df_old_RESULTS = df_old_RESULTS.apply(pd.to_numeric, errors='ignore')\r\n\r\n file_to_compute = 'V:/temp/CEGO_PROPOSE.csv'\r\n df_old_RESULTS.to_csv(file_to_compute, sep=',', index=False)\r\n \r\n file_computed = 'V:/temp/NAPA_RESULTS.csv'\r\n df_new_RESULTS = pd.read_csv(file_computed)\r\n while lenComputed not in df_new_RESULTS.index or df_new_RESULTS['TARGET'][lenComputed]==0:\r\n try:\r\n df_new_RESULTS = pd.read_csv(file_computed)\r\n print('Read file')\r\n time.sleep(2)\r\n except OSError:\r\n print(OSError)\r\n time.sleep(2)\r\n \r\n result = df_new_RESULTS.loc[lenComputed].values\r\n objectiveValues = objMultiplier*result[3+len(x)+nconstraints:len(result)-1]\r\n \r\n constraintValues = conMultiplier*(result[3+len(x):3+len(x)+nconstraints] - conValues)\r\n \r\n print(objectiveValues)\r\n print(constraintValues)\r\n\r\n CONSTRAINED_SMSEGO_ORDER = np.append(objectiveValues, constraintValues)\r\n CONSTRAINED_SMSEGO_ORDER = CONSTRAINED_SMSEGO_ORDER.astype(float)\r\n \r\n print(CONSTRAINED_SMSEGO_ORDER)\r\n \r\n return(objectiveValues, CONSTRAINED_SMSEGO_ORDER[len(objectiveValues):])\r\n\r\n#set cego parameters lowerlimit, upperlimit, number of constraints and reference point\r\nfile_old = 'V:/temp/INITIAL_NAPA_RESULTS.csv'\r\ndf_old_RESULTS = pd.read_csv(file_old)\r\nfile_to_compute = 'V:/temp/CEGO_PROPOSE.csv'\r\ndf_old_RESULTS.to_csv(file_to_compute, sep=',', index=False)\r\n \r\nfile = 'V:/temp/OBJECTIVES.csv'\r\ndf_objectives = pd.read_csv(file, index_col=0)\r\nnObjectives = len(df_objectives)\r\n\r\nfile = 'V:/temp/CONSTRAINTS.csv'\r\ndf_constraints = pd.read_csv(file, index_col=0)\r\nnConstraints = len(df_constraints)\r\n\r\nfile = 'V:/temp/PARAMETERS.csv'\r\ndf_parameters = pd.read_csv(file, index_col=0)\r\nnParameters = len(df_parameters)\r\n\r\nfile = 'V:/temp/CEGO_SETTINGS.csv'\r\ndf_settings = pd.read_csv(file, index_col=0)\r\n\r\nranges = []\r\nfor var in df_parameters.iterrows():\r\n lolim = var[1]['LLIM']\r\n uplim = var[1]['ULIM']\r\n ranges.append([lolim, uplim])\r\nranges = np.array(ranges)\r\n\r\nobjRanges = []\r\nobjMultiplier = []\r\nfor var in df_objectives.iterrows():\r\n refPoint = var[1]['DES']\r\n if var[1]['GOAL']=='MAX':\r\n objMultiplier.append(-1)\r\n objRanges.append(-1*refPoint)\r\n else:\r\n objMultiplier.append(1)\r\n objRanges.append(refPoint)\r\nref = np.array(objRanges)\r\nobjMultiplier = np.array(objMultiplier)\r\n\r\nconMultiplier = []\r\nconValues = []\r\nfor var in df_constraints.iterrows():\r\n conValues.append(var[1]['VALUE'])\r\n if var[1]['TYPE']=='=':\r\n conMultiplier.append(1)\r\n elif var[1]['TYPE']=='>':\r\n conMultiplier.append(-1)\r\n else:\r\n conMultiplier.append(1)\r\nconMultiplier = np.array(conMultiplier)\r\nconValues = np.array(conValues)\r\n\r\nproblemCall = partial(compute_ship, nparameters=nParameters, nconstraints=nConstraints, nobjectives=nObjectives, \r\n conValues=conValues, conMultiplier=conMultiplier, objMultiplier=objMultiplier)\r\nrngMin = ranges[:,0]\r\nrngMax = ranges[:,1]\r\ninitEval = int(df_settings['VALUE']['INITEVAL'])\r\nmaxEval = int(df_settings['VALUE']['LOOPS'])\r\nsmooth = int(df_settings['VALUE']['SMOOTH'])\r\nrunNo = int(df_settings['VALUE']['SEED'])\r\ntabReset = int(df_settings['VALUE']['TABRESET'])\r\n#ref = np.array([301,72])\r\n\r\nif initEval == 0:\r\n initEval = 11*nParameters-1 \r\n\r\nif maxEval < initEval:\r\n raise ValueError('Maximum number of iterations is smaller then initial number of Evaluations, CEGO terminates')\r\n\r\nif initEval < nParameters+1:\r\n raise ValueError('Initial number of Evaluations to small, must at least be #parameters+1. Initial evaluations 11*#parameters-1 recommended. CEGO terminates')\r\n\r\nif runNo == 0 :\r\n runNo = int(time.time())\r\n\r\n\r\n###### read first or more previous results\r\nfunctionName = str(problemCall).split(' ')[1]\r\noutdir = 'results/'+str(functionName)+'/'\r\n\r\npar_file_path = str(outdir)+'/par_run'+str(runNo)+'.csv'\r\ncon_file_path = str(outdir)+'/con_run'+str(runNo)+'.csv'\r\nobj_file_path = str(outdir)+'/obj_run'+str(runNo)+'.csv'\r\n\r\nif os.path.exists(par_file_path) and os.path.exists(con_file_path) and os.path.exists(obj_file_path) and (tabReset==0 or tabReset==2):\r\n parameters = np.genfromtxt(par_file_path, delimiter=',')\r\n constraints = np.genfromtxt(con_file_path, delimiter=',')\r\n objectives = np.genfromtxt(obj_file_path, delimiter=',')\r\n \r\n if tabReset==2:\r\n pf = paretofrontFeasible(objectives, constraints)\r\n parameters = parameters[pf]\r\n constraints = constraints[pf]\r\n objectives = objectives[pf]\r\n \r\n maxEval = max(initEval+len(parameters), maxEval)\r\n initEval = max(initEval, len(parameters)+6)\r\n \r\nelse:\r\n previousResults = np.genfromtxt('V:/temp/INITIAL_NAPA_RESULTS.csv', delimiter=',', skip_header=True)\r\n previousResults = np.asmatrix(previousResults)\r\n \r\n parameters = previousResults[:,3:3+nParameters]\r\n \r\n constraints = conMultiplier*np.array(previousResults[:,3+nParameters:3+nParameters+nConstraints] - conValues)\r\n objectives = objMultiplier*np.array(previousResults[:,3+nParameters+nConstraints:previousResults.shape[1]-1])\r\n\r\nif not os.path.isdir(outdir):\r\n os.makedirs(outdir)\r\n\r\nfileParameters = str(outdir)+'par_run'+str(runNo)+'_finalPF.csv'\r\nfileObjectives = str(outdir)+'obj_run'+str(runNo)+'_finalPF.csv'\r\nfileConstraints = str(outdir)+'con_run'+str(runNo)+'_finalPF.csv'\r\n\r\nnp.savetxt(fileParameters, parameters, delimiter=',')\r\nnp.savetxt(fileObjectives, objectives, delimiter=',')\r\nnp.savetxt(fileConstraints, constraints, delimiter=',')\r\n\r\ns = time.time()\r\nobjectives, constraints, parameters = CONSTRAINED_SMSEGO(problemCall, rngMin, rngMax, ref, nConstraints, initEval, maxEval, smooth, runNo)\r\nprint(time.time()-s)\r\n\r\n\r\n\r\nparetoOptimal = paretofrontFeasible(objectives,constraints)\r\nparetoFront = objectives[paretoOptimal]\r\n\r\n## save pareto frontier\r\nobjNames = list(df_objectives.index.values)\r\nvisualiseParetoFront(paretoFront, save=True, outdir=str(outdir), objNames=objNames)\r\n\r\n## create convergence plot\r\nconvergence_plot(objectives, constraints, ref, outdir=str(outdir))\r\n\r\n## create parallel coordinate plot\r\nparNames = list(df_parameters.index.values)\r\nparallel_coordinates(parameters, constraints, objectives, outdir=str(outdir), parNames=parNames)\r\n\r\n","sub_path":"CEGO/optimize_ship.py","file_name":"optimize_ship.py","file_ext":"py","file_size_in_byte":13072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"132510801","text":"\"\"\"Using GLIE Monte-Carlo Control RL to find optimum policy and value function for Easy21\"\"\"\nfrom Easy_21_Game import *\nimport numpy.random as rand\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\n\n\ndef mc_glie(n_episodes, No):\n \"\"\"Run GLIE MC RL for Easy_21\"\"\"\n\n \"\"\"Initialise stored variables\"\"\"\n # Note when indexing by state, use: card_values - 1\n Q = np.zeros((10, 21, 2)) # Action value function (Dealer, Player, Action)\n N = np.zeros((10, 21, 2)) # No. times action selected from particular state\n\n for i in range(0, n_episodes):\n\n # Lists of rewards, states visited and actions in the episode\n R = []\n S = []\n A = []\n\n # Player and dealer each draw random black card\n d_card = rand.randint(1, 11)\n p_card = rand.randint(1, 11)\n S.append((d_card, p_card))\n\n # Choose action (epsilon - greedy)\n A.append(choose_action(Q, S[0], N, No))\n N[d_card-1, p_card-1, A[-1]] += 1\n\n terminal = False\n while not terminal:\n \"\"\"Run Episode\"\"\"\n\n # Update state and record immediate reward\n Rt, newS = step(S[-1], A[-1])\n R.append(Rt)\n S.append(newS)\n\n if S[-1] == 0:\n \"\"\"End episode\"\"\"\n terminal = True\n continue\n\n # Choose next action\n A.append(choose_action(Q, S[-1], N, No))\n N[newS[0]-1, newS[1]-1, A[-1]] += 1\n\n \"\"\"Update Value Function Using Returns\"\"\"\n S = S[0:-1] # Remove terminal value\n\n for idx, state in enumerate(S):\n d_idx = state[0]-1\n p_idx = state[1]-1\n Gt = sum(R[idx:]) # No discounting\n Q[d_idx, p_idx, A[idx]] += (1/N[d_idx, p_idx, A[idx]])*(Gt - Q[d_idx, p_idx, A[idx]])\n\n return Q\n\n\ndef extract_optimal(Q):\n \"\"\"Returns the optimal value function and policy\n v*(s) = max{a}Q*(s, a) and pi*(s)\"\"\"\n v_Star = np.zeros((10, 21))\n pi_Star = np.zeros((10, 21))\n\n for dealer in range(0, Q.shape[0]):\n for player in range(0, Q.shape[1]):\n max_v = np.amax(Q[dealer, player, :])\n max_a = np.where(Q[dealer, player, :] == max_v)[0][0]\n\n v_Star[dealer, player] = max_v\n pi_Star[dealer, player] = max_a\n\n return v_Star, pi_Star\n\n\ndef main():\n \"\"\"Runs GLIE Monte-Carlo Reinforcement Learning\"\"\"\n\n \"\"\"Runtime parameters\"\"\"\n No = 100 # Exploration parameter\n episodes = 100000\n\n Q = mc_glie(episodes, No)\n v_Star, pi_Star = extract_optimal(Q)\n\n \"\"\"Plotting Results\"\"\"\n do_plot = True\n if do_plot:\n # Optimal Value function\n v_Star = v_Star.T\n X_ = np.arange(1, 11, 1)\n Y_ = np.arange(1, 22, 1)\n XX, YY = np.meshgrid(X_, Y_)\n\n fig1 = plt.figure()\n fig1.suptitle('Optimal Value Function V*(s)')\n ax1 = fig1.add_subplot(111, projection='3d')\n ax1.plot_wireframe(XX, YY, v_Star)\n ax1.set_xlabel('Dealer showing'), ax1.set_ylabel('Player sum')\n plt.show()\n\n # Optimal Policy\n fig2 = plt.figure()\n fig2.suptitle('Optimal Policy')\n ax2 = plt.gca()\n ax2.set_ylabel('Dealer showing'), ax2.set_xlabel('Player sum')\n plt.imshow(pi_Star)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"Easy21_MC_Control.py","file_name":"Easy21_MC_Control.py","file_ext":"py","file_size_in_byte":3368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"538286674","text":"from manimlib.imports import *\nimport math\n\nclass Func(GraphScene):\n CONFIG = {\n 'x_min':-8,\n 'x_max':8,\n \"x_axis_width\":16,\n 'y_min':-4,\n 'y_max':4,\n \"y_axis_height\": 8,\n 'graph_origin':ORIGIN,\n 'axes_color':WHITE,\n }\n def construct(self):\n e = math.e\n text1 = TextMobject(\"大家好,在上期视频中,我们讨论了六个函数:\").to_edge(UP,buff=MED_LARGE_BUFF)\n text2 = TexMobject(r'xe^x').next_to(text1,DOWN*2)\n text3 = TexMobject(r'\\frac{e^x}{x}').next_to(text2, RIGHT*3)\n text4 = TexMobject(r'\\frac{x}{e^x}').next_to(text2, LEFT*3)\n text5 = TexMobject(r'x \\ln x').next_to(text2, DOWN*5)\n text6 = TexMobject(r'\\frac{\\ln x}{x}').next_to(text3, DOWN*3)\n text7 = TexMobject(r'\\frac{x}{\\ln x}').next_to(text4, DOWN*3)\n self.play(\n Write(text1),\n Write(text2),\n Write(text3),\n Write(text4),\n Write(text5),\n Write(text6),\n Write(text7),\n )\n self.wait()\n group = VGroup(text2,text3,text4,text5,text6,text7)\n self.wait(3)\n text8 = TextMobject(\"那么,这些函数在压轴题中有什么表现呢?\").next_to(text1,DOWN*2)\n self.wait(2)\n self.play(ReplacementTransform(group,text8))\n text9 = TextMobject(\"来看一道高考数学导数压轴题\").next_to(text8,DOWN*2)\n self.wait(2)\n self.play(Write(text9))\n self.wait(2)\n self.play(\n FadeOut(text9),\n FadeOut(text8),\n FadeOut(text1)\n )\n\n t1 = TextMobject(r\"设函数$f(x)=ae^x\\ln x + {{be^{x-1}} \\over {x}}$,曲线$y=f(x)$在\\\\点$(1,f(1))$处的切线为$y=e(x-1)+2$\").to_edge(UP,buff=MED_LARGE_BUFF)\n t2 = TextMobject(r\"(1)求$a$,$b$;\").next_to(t1,DOWN).shift(LEFT*4.5)\n t3 = TextMobject(r\"(2)证明:$f(x)>1$.\").next_to(t2,DOWN).shift(RIGHT*0.9)\n self.play(\n Write(t1),\n Write(t2),\n Write(t3)\n )\n self.wait(15)\n self.play(FadeOut(t3))\n self.wait()\n t4 = TextMobject(\n r\"$f(1)=$\",\n r\"$e(1-1)+2$\\\\\",\n r\"${f}'(1)=e$\"\n ).next_to(t2,DOWN)\n t4[2].shift(LEFT).shift(DOWN)\n self.play(Write(t4))\n self.wait()\n t5 = TextMobject(r\"2\").next_to(t4[0],RIGHT)\n t6 = TexMobject(\n r\"f(1)=\",\n r\"ae\\ln1+{{b{e}^0}\\over{1}}=b\"\n ).next_to(t5,RIGHT*3)\n t7 = TexMobject(r\"f'(x)={{{{ae^x}\\over{x}}+{ae}^{x}\\ln {x}}+ \",r\"{{{bxe^{x-1}-be^{x-1}}\\over {x^2}}}}\").next_to(t4[2],RIGHT)\n t8 = TexMobject(r\"f'(x)={{{{ae^x}\\over{x}}+{ae}^{x}\\ln {x}}+\",r\"{{{be}^{x-1}(x-1)}\\over{x^2}}\").next_to(t4[2],RIGHT)\n self.play(ReplacementTransform(t4[1],t5))\n self.wait()\n self.play(Write(t6))\n self.wait()\n self.play(Write(t7))\n self.wait()\n self.play(ReplacementTransform(t7[1],t8[1]))\n self.wait()\n t9 = TexMobject(r\"\\Rightarrow\", r\" a=1\\\\b=2\").next_to(t8,DOWN)\n t9[0].shift(DOWN*0.45)\n self.play(Write(t9))\n self.wait()\n group1 = VGroup(t2, t4[0], t5, t6, t4[2], t7[0], t8[1], t9)\n self.play(FadeOut(group1))\n self.wait()\n t3.next_to(t1,DOWN).shift(LEFT*3.6)\n self.play(Write(t3))\n self.wait()\n s1 = TexMobject(r\"f(x)=\", r\"(\", r\"e^x\\ln x + {{2e^{x-1}}\\over {x}}\", r\")\", r\">1\").next_to(t3,DOWN)\n s2 = TexMobject(r\"\\cdot\", r\"{{x}\\over{e^x}}\").next_to(s1[4],RIGHT)\n s3 = TexMobject(r\"{{x}\\over{e^x}}\" ,r\"\\cdot\").next_to(s1[1],LEFT)\n group2 = VGroup(s1[0], s1[2], s1[4])\n group3 = VGroup(s1[1], s1[3])\n self.play(Write(group2))\n self.wait()\n self.play(FadeOut(s1[0]))\n self.wait()\n self.play(Write(group3))\n self.wait()\n self.play(Write(s2))\n self.wait()\n self.play(Write(s3))\n self.wait()\n s4 = TexMobject(r\"{x\\ln {x} +{{2}\\over{e}}}\", r\" > {{x}\\over {e^x}}\")\n group4 = VGroup(s3, s1[2], s1[3], s1[1])\n group5 = VGroup(s2, s1[4])\n self.play(\n ReplacementTransform(group4, s4[0]),\n ReplacementTransform(group5, s4[1])\n )\n self.wait()\n s5 = TexMobject(\n r\"h(x)=\",\n r\"x\\ln x +{2 \\over e}\"\n ).move_to(np.array([-3,1,0]))\n s6 = TexMobject(\n r\"g(x)=\",\n r\"{x\\over e^x}\"\n ).move_to(np.array([-3.8,0,0]))\n self.play(Write(s5[0]))\n self.wait()\n self.play(ReplacementTransform(s4[0], s5[1]))\n self.wait()\n self.play(Write(s6[0]))\n self.wait()\n self.play(ReplacementTransform(s4[1], s6[1]))\n self.wait()\n s5_1 = TexMobject(\n r\"h'(x)=\",\n r\"(x\\ln x +{2 \\over e})'\"\n ).move_to(np.array([-3,1,0]))\n s6_1 = TexMobject(\n r\"g'(x)=\",\n r\"({x\\over e^x})'\"\n ).move_to(np.array([-3.8,0,0]))\n self.play(ReplacementTransform(s5[0],s5_1[0]))\n self.wait()\n self.play(ReplacementTransform(s6[0],s6_1[0]))\n self.wait()\n self.play(ReplacementTransform(s5[1],s5_1[1]))\n self.wait()\n self.play(ReplacementTransform(s6[1],s6_1[1]))\n self.wait()\n s5_2 = TexMobject(\n r\"h'(x)=\",\n r\"(x\\ln x)' +({2 \\over e})'\"\n ).move_to(np.array([-3,1,0]))\n self.play(ReplacementTransform(s5_1[1],s5_2[1]))\n self.wait()\n s5_3 = TexMobject(\n r\"h'(x)=\",\n r\"(x\\ln x)'\",\n r\"+{2 \\over e}\"\n ).move_to(np.array([-3,1,0]))\n self.play(ReplacementTransform(s5_2[1],s5_3[1]))\n self.wait()\n s5_4 = TexMobject(\n r\"h'(x)=\",\n r\"1+\\ln x\",\n r\"+{2 \\over e}\"\n ).move_to(np.array([-3,1,0]))\n self.play(ReplacementTransform(s5_3[1], s5_4[1]))\n self.wait()\n s6_2 = TexMobject(\n r\"g'(x)=\",\n r\"{{1-x}\\over {e^x}}\"\n ).move_to(np.array([-3.8,0,0]))\n self.play(ReplacementTransform(s6_1[1], s6_2[1]))\n self.wait()\n group6 = VGroup(t1, t3, s5_1[0], s6_1[0], s5_4[1], s6_2[1])\n self.play(FadeOut(group6))\n self.wait()\n\n self.setup_axes(animate=True)\n plane = NumberPlane()\n self.play(ShowCreation(plane))\n def ln(x):\n return math.log(x,e)\n hx = self.get_graph(lambda x: x * ln(x) + 2/e, x_min=0.02)\n hx_label = self.get_graph_label(hx,label=r\"h(x)=x \\ln x + {2 \\over e}\").shift(LEFT*5)\n h_x = self.get_graph(lambda x: ln(x)+1, x_min=0.02)\n h_x_label = self.get_graph_label(h_x, label=r\"h'(x)=\\ln x + 1\").shift(DOWN*2)\n gx = self.get_graph(lambda x: x/(e**x))\n gx_label = self.get_graph_label(gx, label=r\"g(x)={x \\over {e^x}}\").move_to(np.array([-2,-1,0]))\n g_x = self.get_graph(lambda x:(x-1)/(e**x))\n g_x_label = self.get_graph_label(g_x, label=r\"g'(x)={{x-1}\\over{e^x}}\").shift(DOWN*0.7)\n line1 = self.get_vertical_line_to_graph(1/e,hx)\n dot1 = Dot().move_to(np.array([1/e, 1/e, 0]))\n dot1_label = TexMobject(r\"({1 \\over e},{1 \\over e})\").next_to(dot1, UP).shift(LEFT*2)\n line2 = self.get_vertical_line_to_graph(1, gx)\n dot2 = Dot().move_to(np.array([1, 1/e, 0]))\n dot2_label = TexMobject(r\"(1, {1 \\over e})\").move_to(dot2, DOWN).shift(RIGHT*2)\n self.play(ShowCreation(hx))\n self.wait()\n self.play(ShowCreation(hx_label))\n self.wait()\n self.play(ShowCreation(h_x))\n self.wait()\n self.play(ShowCreation(h_x_label))\n self.wait()\n self.play(Write(line1))\n self.wait()\n self.play(Write(dot1))\n self.wait()\n self.play(Write(dot1_label))\n self.wait()\n group7 = VGroup(hx, hx_label, h_x, h_x_label, line1, dot1, dot1_label)\n self.play(FadeOut(group7))\n self.wait()\n self.play(ShowCreation(gx))\n self.wait()\n self.play(ShowCreation(gx_label))\n self.wait()\n self.play(ShowCreation(g_x))\n self.wait()\n self.play(ShowCreation(g_x_label))\n self.wait()\n self.play(Write(line2))\n self.wait()\n self.play(Write(dot2))\n self.wait()\n self.play(Write(dot2_label))\n self.wait()\n group8 = VGroup(gx, gx_label, g_x, g_x_label, line2, dot2, dot2_label)\n self.play(FadeOut(group8))\n self.wait()\n \n s7 = TexMobject(r\"{h(x)_{min}} ={1 \\over e}\").to_corner(UL)\n s8 = TexMobject(r\"{g(x)_{max}} = {1 \\over e}\").next_to(s7,DOWN)\n self.play(\n Write(hx),\n Write(gx),\n Write(dot1),\n Write(dot2),\n Write(dot1_label),\n Write(dot2_label)\n )\n self.wait()\n self.play(Write(s7))\n self.wait()\n self.play(Write(s8))\n self.wait()\n self.play(\n FadeOut(hx),\n FadeOut(gx),\n FadeOut(dot1),\n FadeOut(dot2),\n FadeOut(dot1_label),\n FadeOut(dot2_label),\n FadeOut(s7),\n FadeOut(s8),\n FadeOut(plane),\n FadeOut(self.axes)\n )\n self.wait()\n\n te1 = TextMobject(r\"$h(x)$在$(0,{1\\over e})$单调递减,在$({1\\over e},+\\infty)$单调递增,\\\\$h(x)$在$(0,+\\infty)$的最小值为:${h(x)_{min}}=h({1\\over e})={1\\over e}$\")\n te2 = TextMobject(r\"$g(x)$在$(-\\infty, 1)$单调递增,在$(1, +\\infty)$单调递减,\\\\$g(x)$在$(0,+\\infty)$的最大值为:${g(x)_{max}}=g(1)={1 \\over e}$\")\n te1.to_edge(UP)\n te2.next_to(te1, DOWN)\n self.play(\n Write(te1),\n Write(te2)\n )\n self.wait()\n te3 = TextMobject(r\"综上,当$x>0$时,$h(x)>g(x)$,即$f(x)>1$\").move_to(np.array([0,-1.5,0]))\n self.play(Write(te3))\n self.wait()\n","sub_path":"3_functions_in_test.py","file_name":"3_functions_in_test.py","file_ext":"py","file_size_in_byte":9953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"580395560","text":"import pathlib\nfrom csv import reader\n\ndef load_csv(filename):\n filename = pathlib.Path(__file__).parent.parent / \"data\" / filename\n data = list()\n with open(filename, \"r\") as file:\n lines = reader(file)\n for row in lines:\n if not row:\n continue\n data.append(row)\n return data\n\n\ndef col2float(data, column):\n for row in data:\n row[column] = float(row[column].strip())\n\n\ndef col2int(data, column):\n classes = [row[column] for row in data]\n unique = set(classes)\n lookup = dict()\n\n for i, value in enumerate(unique):\n lookup[value] = i\n\n for row in data:\n row[column] = lookup[row[column]]\n\n return lookup\n\n\ndef minmax(data):\n mm = list()\n\n for i in range(len(data[0])):\n col_values = [row[i] for row in data]\n value_min = min(col_values)\n value_max = max(col_values)\n mm.append([value_min, value_max])\n\n return mm\n\n\ndef normalize(data, mm):\n for row in data:\n for i in range(len(row)):\n row[i] = (row[i] - mm[i][0]) / (mm[i][1] - mm[i][0])","sub_path":"ml/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"63484353","text":"from os.path import sep\nimport pyautogui, os\nfrom common_config import TEMP_IMGS, DATASET_IMGS\nimport cv2\n\n\ndef getElementCoords(haystack, needle):\n\n img = cv2.imread(haystack, cv2.IMREAD_COLOR)\n img_display = img.copy()\n templ = cv2.imread(needle, cv2.IMREAD_COLOR)\n result = cv2.matchTemplate(img, templ, cv2.TM_CCORR_NORMED)\n cv2.normalize(result, result, 0, 1, cv2.NORM_MINMAX, -1)\n _minVal, _maxVal, minLoc, maxLoc = cv2.minMaxLoc(result, None)\n matchLoc = maxLoc\n h, w, _ = templ.shape\n\n center = (int((matchLoc[0] + w / 2)), int((matchLoc[1] + templ.shape[0]) - h / 2))\n x_center = int(matchLoc[0] + w / 2)\n y_center = int((matchLoc[1] + templ.shape[0]) - h / 2)\n\n return x_center, y_center\n\n\n\nif __name__ == '__main__':\n # start app\n #refresh_screenshot()\n # text_recognition()\n #start_window = which_window_am_i()\n\n image_window = \"Source Image\"\n result_window = \"Result window\"\n directory = (\"{}{}\".format(DATASET_IMGS, 'main_window'))\n print(\"directorio de busqueda: {}\".format(directory))\n img_path = (\"{}{}\".format(TEMP_IMGS, \"declarantes_screenshot.png\"))\n\n img = cv2.imread(img_path, cv2.IMREAD_COLOR)\n img_display = img.copy()\n\n for filename in os.listdir(directory):\n if filename.endswith(\".py\"):\n continue\n else:\n template = (\"{}{}{}{}\".format(DATASET_IMGS, \"main_window\", sep, filename))\n print(\"buscando template: {}\".format(filename))\n templ = cv2.imread(template, cv2.IMREAD_COLOR)\n img_display = img.copy()\n\n result = cv2.matchTemplate(img, templ, cv2.TM_CCORR_NORMED)\n cv2.normalize(result, result, 0, 1, cv2.NORM_MINMAX, -1)\n _minVal, _maxVal, minLoc, maxLoc = cv2.minMaxLoc(result, None)\n matchLoc = maxLoc\n '''\n beautiful visual testing purposes\n\n #cv2.namedWindow(image_window, cv2.WINDOW_AUTOSIZE)\n #font = cv2.FONT_HERSHEY_CLoc[0] + templ.shape[1] - 150, matchLoc[1] + templ.shape[0] - 30),\n # font, 1, (0, 255, 0), 1, cv2.LINE_AA)\n #cv2.rectangle(img_display, matchLoc, (matchLoc[0] + templ.shape[1], matchLoc[1] + templ.shape[0]),\n # (0, 0, 0), 2, 8, 0)\n '''\n h, w, _ = templ.shape\n print(\"h:{}, w:{}\".format(h, w))\n\n center = (int((matchLoc[0] + w / 2)), int((matchLoc[1] + templ.shape[0]) - h / 2))\n x_center = int(matchLoc[0] + w / 2)\n # text = '_'.join(filename.split('_')[1:]).split('.')[0]\n # cv2.putText(img_display, text, (match\n y_center = int((matchLoc[1] + templ.shape[0]) - h / 2)\n\n pyautogui.dragTo(x_center, y_center, duration=1)\n # pyautogui.click()\n\n '''\n beautiful visual testing purposes\n\n cv2.circle(img_display, center, 5, (0, 255, 0), -1)\n cv2.imshow(image_window, img_display)\n\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n '''\n # plt.switch_backend('agg')\n # test()\n\n # churrete_masivo()\n","sub_path":"src/controllers/img_recognition.py","file_name":"img_recognition.py","file_ext":"py","file_size_in_byte":3120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"100935041","text":"import numpy as np\nfrom collections import OrderedDict\nfrom concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed\nimport multiprocessing\nfrom itertools import combinations\nfrom .lawdata import SourceInterface\nfrom .kvsdict import KVSDict, KVSPrefixDict\nfrom . import etypes\nfrom .tree_element import TreeElement\nimport re\nimport os\n\n\nclass JStatuteDict(object):\n def __init__(self, only_reiki=True):\n self.only_reiki = only_reiki\n self.body = dict()\n\n def __setitem__(self, key, val):\n assert issubclass(val.__class__, SourceInterface), str(val)+\" is not a jstatute obj.\"\n if not self.only_reiki or val.lawdata.is_reiki():\n self.body[key] = val\n\n def __getitem__(self, key):\n return self.body[key]\n\n def __len__(self):\n return len(self.body)\n\nclass JStatutreeKVSDict(KVSDict):\n DEFAULT_DBNAME = \"statutree.ldb\"\n PREFIX = \"statutree-\"\n\n def __init__(self, path, levels, only_reiki=True, *args, **kwargs):\n self.only_reiki = only_reiki\n self.levels = etypes.sort_etypes(levels)\n super().__init__(path=path, *args, **kwargs)\n\n def set_from_reader(self, reader):\n self[reader.lawdata.code] = reader.get_tree()\n\n def __setitem__(self, key, val):\n assert issubclass(val.__class__, TreeElement), str(val)+\" is not a jstatutree obj.\"\n assert val.is_root(), \"You cannot set non-root item ot JStatutreeKVSDict.\"\n if not self.only_reiki or val.lawdata.is_reiki():\n self._set_tree(key, val, self.levels)\n\n def _set_tree(self, key, elem, levels):\n if len(levels) == 0:\n return\n next_keys = []\n for next_elem in elem.depth_first_search(levels[0]):\n if re.sub(\"\\(.+?\\)$\", \"\", os.path.split(next_elem.code)[1]) != levels[0].__name__:\n virtual_elem_key = next_elem.code+\"/{}(1)\".format(levels[0].__name__)\n next_keys.append(virtual_elem_key)\n else:\n next_keys.append(next_elem.code)\n self._set_tree(next_keys[-1], next_elem, levels[1:])\n super().__setitem__(key, next_keys)\n #print(\"connected:\")\n #print(\" \\t\", key)\n #for v in self[key]:\n # print(\"->\\t\", v)\n\n def write_batch(self, *args, **kwargs): \n return JSBatchWriter(self, *args, **kwargs)\n\nclass JStatutreeBatchWriter(object):\n def __init__(self, kvsdict, *args, **kwargs):\n self.wb = kvsdict.db.write_batch(*args, **kwargs)\n self._encode_key = kvsdict._encode_key\n self.ENCODING = kvsdict.ENCODING\n\n def __setitem__(self, key, val):\n assert issubclass(val.__class__, TreeElement), str(val)+\" is not a jstatutree obj.\"\n assert val.is_root(), \"You cannot set non-root item ot JStatutreeKVSDict.\"\n if not self.only_reiki or val.lawdata.is_reiki():\n self._set_tree(key, val, self.levels)\n\n def _set_tree(self, key, elem, levels):\n if len(levels) == 0:\n return\n next_keys = []\n for next_elem in elem.depth_first_search(levels[0]):\n if re.sub(\"\\(.+?\\)$\", \"\", os.path.split(next_elem.code)[1]) != levels[0].__name__:\n virtual_elem_key = next_elem.code+\"/{}(1)\".format(levels[0].__name__)\n next_keys.append(virtual_elem_key)\n else:\n next_keys.append(next_elem.code)\n self._get_tree_dict(next_keys[-1], next_elem, levels[1:])\n super().__setitem__(key, next_keys)\n if \"1847\" in key:\n print(\"connected:\")\n print(\" \\t\", key)\n for v in self[key]:\n print(\"->\\t\", v)\n\n def __delitem__(self, key):\n self.wb.delete(self._encode_key(key))\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n if exc_type is not None:\n return False\n self.write()\n return True\n\n def write(self):\n self.wb.write()\n\nclass JSSentenceKVSDict(KVSPrefixDict):\n DEFAULT_DBNAME = \"reiki.ldb\"\n PREFIX = \"sentence-\"\n\n def __init__(self, db=None, kvsdict=None, level=None, *args, **kwargs):\n if level is None:\n prefix = self.PREFIX\n else:\n level = level if isinstance(level, str) else level.__name__\n prefix = self.PREFIX + level + \"-\"\n super().__init__(db=db, kvsdict=kvsdict, prefix=prefix, *args, **kwargs)\n\n\"\"\"\nQSIZE = 1000\nclass JSFMultiExecutor(JSForest):\n def __init__():\n self.executor = {\n \"process\": ProcessPoolExecutor(self.proc_count),\n \"thread\": ThreadPoolExecutor(self.thread_count)\n }\n\n def executor_deco(executor_type):\n def _executor_deco(func):\n import functools\n @functools.wraps(func)\n def inner(self, queue, *args, **kwargs):\n futures = [\n self.executor[executor_type].submit(func, self, queue, *arg, **kwargs) for arg in args\n ]\n for f in as_completed(futures):\n res = f.result()\n if res is None:\n continue\n else:\n queue.put(res)\n if executor_type is \"thread\":\n queue.put(None)\n return inner\n return _executor_deco\n\n def add_tree_sources_from_paths(self, *tree_source_paths):\n q = multiprocessing.Queue(QSIZE)\n self._enqueue_tree_sources_from_paths(queue, *tree_source_paths)\n unfinished_thread_count = self.proc_count * self.thread_count\n while unfinished_thread_count > 0:\n item = q.get()\n if item is None:\n unfinished_thread_count -= 1\n continue\n tree_source = item\n self.tree_source_dict[tree_source.code] = tree_source\n\n\n def setup_from_basepath(self, basepath):\n self.add_tree_sources_from_paths(find_all_files(basepath, [\".xml\"]))\n\n def __iter__(self):\n q = multiprocessing.Queue(QSIZE)\n self._enqueue_leaves(self.tree_source_dict.values())\n unfinished_thread_count = self.proc_count * self.thread_count\n while unfinished_thread_count > 0:\n item = q.get()\n if item is None:\n unfinished_thread_count -= 1\n continue\n leaf = item\n yield leaf\n\"\"\"","sub_path":"jstatutree/jstatute_dict.py","file_name":"jstatute_dict.py","file_ext":"py","file_size_in_byte":6436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"531349246","text":"import pickle\r\nfrom scipy import sparse\r\nimport numpy\r\n\r\nnumpy.set_printoptions(threshold=numpy.inf)\r\n\r\ndef Dat2Txt(word_bag = None, tfidf_space = None):\r\n if(tfidf_space is None):\r\n with open(word_bag, 'rb') as file_obj:\r\n bunch = pickle.load(file_obj)\r\n transform = open(word_bag+'.txt', 'w')\r\n for filename, lable, content in zip(bunch.filenames, bunch.label, bunch.contents):\r\n transform.write(filename + '\\t' + lable + '\\t' + content + '\\n')\r\n transform.close()\r\n else:\r\n with open(tfidf_space, 'rb') as file_obj:\r\n bunch = pickle.load(file_obj)\r\n tdm_path = tfidf_space + '_tdm.txt'\r\n dict_path = tfidf_space + '_dict4.txt'\r\n # 将IF-IDF权重矩阵写入到txt文件\r\n tdm = open(tdm_path, 'w')\r\n # for item in bunch.tfidf_weight_matrics:\r\n # print(bunch.tfidf_weight_matrics)\r\n tdm.write(str(bunch.tfidf_weight_matrics))\r\n # tdm.write('\\n')\r\n tdm.close()\r\n # 直接储存矩阵(人不可读)\r\n # sparse.save_npz(tdm_path, bunch.tfidf_weight_matrics)\r\n\r\n # 将词典写入txt文件\r\n dict = open(dict_path, 'w')\r\n dict.write('词典维度:' + str(len(bunch.vocabulary)) + '\\n')\r\n dict.write(str(bunch.vocabulary))\r\n # for item in bunch.vocabulary:\r\n # dict.write(item + ',')\r\n dict.close()\r\n\r\nif __name__ == '__main__':\r\n word_bag = \"F:\\\\results\\\\train_word_bag_体育.dat\"\r\n tfidf_space = \"F:\\\\results\\\\train_tfidf_space_V4.dat\"\r\n # Dat2Txt(word_bag = word_bag)\r\n Dat2Txt(tfidf_space = tfidf_space)\r\n","sub_path":"TextClassification/utils/dat2txt.py","file_name":"dat2txt.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"223542082","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import MinMaxScaler\n\n\ndef center_signal(x):\n return x - np.median(x)\n\n\ndef remove_outliers_idx(x, window_size=150, q=0.99, check_ylim=False):\n x = pd.Series(x)\n x_std = x.rolling(window=window_size, center=True).std().bfill().ffill()\n x_std = MinMaxScaler().fit_transform(x_std.values.reshape(-1, 1)\n ).reshape(-1)\n threshold = np.quantile(x_std, q, axis=0)\n if not check_ylim:\n return x_std > threshold\n else:\n return (x_std > threshold) | (abs(x) > 3e5)\n\n\ndef step_detection(x):\n df = pd.DataFrame(x.astype(np.int), columns=['x'])\n param = 'x'\n\n def return_direction(x):\n return 1 if x > 0 else -1\n\n steps = pd.DataFrame(columns=['Index', 'Change', 'Direction'])\n cond = df[param].diff() != 0\n if x[0] is True:\n steps['Index'] = df[cond].index\n steps['Change'] = (100 * df[param].diff() / df[param].shift()\n )[cond].values\n else:\n steps['Index'] = df[cond].index[1:]\n steps['Change'] = (100 * df[param].diff() / df[param].shift()\n )[cond].values[1:]\n steps['Direction'] = steps['Change'].apply(return_direction)\n steps['Change'] = steps['Change'].apply(np.abs)\n steps.index = steps['Index']\n steps.drop(['Index'], inplace=True, axis=1)\n\n return steps\n\n\ndef get_good_intervals(x, center=False):\n if center:\n x = center_signal(x)\n artifacts = step_detection(remove_outliers_idx(x)).index.values\n df = pd.DataFrame({'start': np.concatenate([[0], artifacts,\n [x.shape[0]]])})\n df['length'] = df['start'].diff(-1).abs().fillna(0).astype(np.int)\n df['end'] = df['start'] + df['length']\n df = df[df.index % 2 == 0]\n idx = df.sort_values(by=['length'],\n ascending=False)[:3][['start', 'end']].values\n # currently the whole length of artifact free signal\n # we might need to cut it's length to 30 secs.\n res = {'f_raw': x[idx[0][0]:idx[0][1]],\n 'top_3': idx}\n return res\n\n\ndef get_bad_intervals(x, center=False):\n if center:\n x = center_signal(x)\n artifacts = step_detection(remove_outliers_idx(x)).index.values\n return artifacts.reshape(-1, 2)\n","sub_path":"code/spark/artifact_detect.py","file_name":"artifact_detect.py","file_ext":"py","file_size_in_byte":2338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"407354447","text":"\"\"\"\n======\nFields\n======\nExtended or custom db fields module.\n\"\"\"\n\nfrom django.db import models\nfrom django.core.validators import MinValueValidator, MaxValueValidator\n\n\nclass FloatField(models.FloatField):\n \"\"\"\n Float field class with min and max value validation and point precision.\n \"\"\"\n\n def __init__(self, min_value=None, max_value=None, precision=None, **kwargs):\n \"\"\"\n :param float min_value: Minimum value to be accepted\n :param float max_value: Maximum value to be accepted\n :param int precision: Float point precision\n \"\"\"\n self.min_value, self.max_value, self.precision = min_value, max_value, precision\n\n self.validators = kwargs.pop('validators', [])\n if self.min_value is not None:\n self.validators.append(MinValueValidator(self.min_value))\n if self.max_value is not None:\n self.validators.append(MaxValueValidator(self.max_value))\n\n super(FloatField, self).__init__(**kwargs)\n\n def to_python(self, value):\n value = super(FloatField, self).to_python(value)\n if self.precision is not None and value is not None:\n value = round(value, self.precision)\n\n return value\n\n def get_db_prep_save(self, value, connection):\n value = self.to_python(value)\n return super(FloatField, self).get_db_prep_save(value, connection)\n\n def get_prep_value(self, value):\n value = super(FloatField, self).get_prep_value(value)\n return self.to_python(value)\n\n\nclass SmallIntegerField(models.SmallIntegerField):\n \"\"\"\n Django's SmallIntegerField with min and max value validation\n \"\"\"\n\n def __init__(self, min_value=None, max_value=None, **kwargs):\n \"\"\"\n :param float min_value: Minimum value to be accepted\n :param float max_value: Maximum value to be accepted\n \"\"\"\n self.min_value, self.max_value = min_value, max_value\n\n self.validators = kwargs.pop('validators', [])\n if self.min_value is not None:\n self.validators.append(MinValueValidator(self.min_value))\n if self.max_value is not None:\n self.validators.append(MaxValueValidator(self.max_value))\n\n super(SmallIntegerField, self).__init__(**kwargs)\n","sub_path":"src/common/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"415396271","text":"import numpy as np\n\n\ndef label(x):\n num_0 = 0\n for a in x:\n if a == 0:\n num_0 = num_0 + 1\n if num_0 >= 3:\n return 0\n elif a == 1:\n num_0 = 0\n return 1\n\n\ndef tomita4(length, lbl):\n while 1:\n a = np.random.random(length) > 0.5\n a = a.astype(np.float32)\n if label(a) == lbl:\n return a\n\n\ndef generate_tomita4(num, length):\n strings = np.zeros((num, length))\n ll = np.zeros((num, length))\n for i in range(0, num, 2):\n ll[i] = 1\n ll[i + 1] = 0\n strings[i, :] = tomita4(length, 1)\n strings[i + 1, :] = tomita4(length, 0)\n\n return strings, ll\n\n\ndef tomita4_string(num, length):\n strings = np.zeros((num, length))\n ll = np.zeros((num, length))\n for i in range(num):\n a = np.random.random(length) > 0.5\n a = a.astype(np.float32)\n count = 0\n for j in range(length):\n if a[j] == 0:\n count += 1\n if count >= 3:\n ll[i] = 0\n\n\nif __name__ == '__main__':\n stringss = generate_tomita4(6, 10)\n print('done')\n","sub_path":"tomita.py","file_name":"tomita.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"438331394","text":"# determining synonyms\nfrom nltk.corpus import wordnet as wn\nimport re\nimport csv\n\n#with open('commonenglishwords.txt', newline='') as csvfile:\n# freqDist = list(csv.reader(csvfile))\nfreqDist = {\"placeholder\"}\n\n#finds best synonyms by english frequency and wu and palm similarity analysis\ndef getBestSynonyms(word, wordtype):\n possible = []\n x = wn.synsets(word)\n\n for s in range(0,len(x)):\n if (x[s].pos() == wordtype):\n l = x[s].lemma_names()\n if len(l) > 0:\n for m in range(0,len(l)):\n possible.append([l[m], firstInstance(l[m], freqDist)])\n\n possible = filter(lambda x: x[0] != word and x[0] != word+\"s\" and not \"_\" in x[0], possible)\n sort = sorted(possible, key=lambda x: x[1])\n if len(sort) > 0:\n bestsort = sort[:10]\n comp = wn.synset(word + \".\" + wordtype + \".01\")\n fin = []\n for p in range(0,len(bestsort)):\n fin.append(bestsort[p][0])\n\n fin.sort(\n key=lambda x: wn.synset(x + \".\" + wordtype + \".01\").wup_similarity(comp)\n )\n return fin\n\n else:\n return None\n\ndef tagMarkupList(markupList):\n\n return markupList\n\ndef firstInstance(strng, arr):\n for x in range(0, len(arr)):\n if (arr[x] == strng):\n return x\n return len(arr)","sub_path":"synonym.py","file_name":"synonym.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"304297641","text":"from flask import Flask\nfrom helpers import calculator\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef hello():\n return \"Hello World!\"\n\n@app.route(\"/add/
    /\")\ndef add(a, b):\n a = int(a)\n b = int(b)\n return str(calculator.add(a, b))\n\n@app.route(\"/subtract//\")\ndef subtract(a,b):\n a = int(a)\n b = int(b)\n return str(calculator.subtract(a,b))\n\n@app.route(\"/divide//\")\ndef divide(a,b):\n a = int(a)\n b = int(b)\n return str(calculator.divide(a,b))\n\n@app.route(\"/multiply//\")\ndef multiply(a,b):\n a = int(a)\n b = int(b)\n return str(calculator.multiply(a,b))\n","sub_path":"week_10/my_site/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"629573800","text":"# this class will display the start menue\n# currently the only option on the start screen\n# is to play the game.\n# This will change in the future\n#\n# INTERFACE\n#\n# def __init__(self)\n# get the data nessecary to\n# use pygames\n#\n# def run(self)\n# show the start menu\n#\n# def changeState(self)\n# returns the current held state\n# of the active state\n#\n# def runState(self)\n# returns true or false to check\n# if the state is still active\n\n\nfrom states import State\nfrom rect import Rect\nimport colors\nimport pygame\nimport gameState\nimport button\n\n\nclass StartMenu:\n\n def __init__(self):\n state = State()\n self.cur_state = self\n self.run_state = True\n\n self.width = state.getScreenWidth()\n self.height = state.getScreenHeight()\n\n self.display = state.getDisplay()\n self.clock = state.getClock()\n self.clock = state.getClock()\n self.scr_width = state.getScreenWidth()\n self.scr_height = state.getScreenHeight()\n self.font = state.getFont()\n\n def run(self):\n play = True\n\n start_button = button.Button(self.width/2.0, self.height/2.0, \"Start\")\n start_button.changeXMargin(100)\n start_button.changeYMargin(20)\n start_button.setX(start_button.getX() - start_button.getWidth()/2.0)\n start_button.changeText(\"Start Game\")\n\n # game loop\n while play:\n\n # event handler\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n play = False\n self.run_state = False\n\n self.display.fill(colors.green)\n\n # draws the button to the screen\n start_button.draw()\n\n if start_button.clicked():\n self.cur_state = gameState.GameState()\n play = False\n\n pygame.display.update()\n self.clock.tick(60)\n\n def changeState(self):\n return self.cur_state\n\n def runState(self):\n return self.run_state\n","sub_path":"Snake Game/startMenu.py","file_name":"startMenu.py","file_ext":"py","file_size_in_byte":2015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"368091854","text":"\nimport sys\nimport time\n\ndef qsort(arr):\n if len(arr) <= 1:\n return arr\n else:\n return qsort([x for x in arr[1:] if x=arr[0]])\n\ncontent = [line.rstrip('\\t') for line in open('normal_1000K.txt')]\nk,n=content[0].split()\nk=int(k)\nn=int(n)\nif n==0 :\n print(\"The List is empty and no elements to display\")\n sys.exit\nelse:\n list= []\n ans=[]\n j=0\n for i in content:\n if j==0:\n j+=1\n continue\n i=i.strip()\n i=float(i)\n list.append(i)\n start = 0\n end = len(list) - 1\n t1=time.time()\n qsort(list)\n t2=time.time()\n print (t2-t1)\n with open (\"Output_LibQuickSort.txt\",\"w\")as fp:\n fp.write(\"Using Library Quick Sort:\\n\")\n fp.write(\"The Sorted order for the array:\\n\")\n for line in list:\n fp.write(str(line)+\"\\n\")\n print (\"Success\")\n","sub_path":"Algorithm Analysis/Order statistics and Sorting Programs/LibQuickSort.py","file_name":"LibQuickSort.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"138124971","text":"import sys\nimport pygame\nimport math\nimport time\nimport random\n\nfrom utilites import Timemanager\nfrom pygame.sprite import Group, groupcollide, spritecollide\nfrom menu import Menu\nfrom items import Block, Ball, Platform\nfrom label import Label\nfrom game_area import Game_area\nfrom stats import Stats\nfrom class_arg import MenuS, GameS\n\nfrom population import Population\n\nfrom button import Button\nfrom check_box import Check_box_button, Check_box\n\nfrom unit_tests import get_tests\n\n\ndef check_keydown_game_events(event, arg):\n if event.key == pygame.K_RIGHT:\n arg.platform.moving_right = True\n elif event.key == pygame.K_LEFT:\n arg.platform.moving_left = True\n elif event.key == pygame.K_SPACE:\n if not arg.ball.thrown:\n arg.ball.throw()\n elif event.key == pygame.K_ESCAPE:\n arg.id_menu = 1\n arg.state_flag = MenuS\n\n if arg.stats.cheat_mode:\n if event.key == pygame.K_r:\n arg.ball.restart()\n elif event.key == pygame.K_b:\n restart(arg)\n elif event.key == pygame.K_KP_PLUS:\n arg.ball.alpha_velocity += 1\n elif event.key == pygame.K_KP_MINUS:\n arg.ball.alpha_velocity -= 1\n else:\n print(\"CheatMode не включен\")\n\n\ndef check_keyup_game_events(event, arg):\n if event.key == pygame.K_RIGHT:\n arg.platform.moving_right = False\n elif event.key == pygame.K_LEFT:\n arg.platform.moving_left = False\n\n\ndef check_keydown_menu_events(event, arg):\n cur_menu = arg.menu[arg.id_menu]\n\n if event.key == pygame.K_ESCAPE:\n cur_menu.func_for_escape(arg)\n if event.key == pygame.K_UP and cur_menu.n_selected != 0:\n cur_menu.n_selected -= 1\n if event.key == pygame.K_DOWN and cur_menu.n_selected != len(cur_menu.buttons) - 1:\n cur_menu.n_selected += 1\n # Не нашёл в pygame заготовленный код для Enter-а\n if event.key == 13:\n print(cur_menu.buttons[cur_menu.n_selected].text)\n cur_menu.buttons[cur_menu.n_selected].func(arg)\n\n\ndef check_keyup_menu_events(event, arg):\n pass\n\n\ndef check_events(arg):\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n close_game(arg)\n\n if arg.state_flag == GameS:\n if event.type == pygame.KEYDOWN:\n check_keydown_game_events(event, arg)\n\n elif event.type == pygame.KEYUP:\n check_keyup_game_events(event, arg)\n\n elif arg.state_flag == MenuS:\n if event.type == pygame.KEYDOWN:\n check_keydown_menu_events(event, arg)\n\n elif event.type == pygame.KEYUP:\n check_keyup_menu_events(event, arg)\n\n\ndef collide_circle_rect(a, b):\n b.rect.centerx, b.rect.centery = b.center\n sol = [0, 0]\n\n if b.rect.left < a.center[0] < b.rect.right:\n if math.fabs(a.center[1] - b.rect.top) < a.radius:\n sol = [a.center[0], b.rect.top]\n elif math.fabs(a.center[1] - b.rect.bottom) < a.radius:\n sol = [a.center[0], b.rect.bottom]\n elif b.rect.top < a.center[1] < b.rect.bottom:\n if math.fabs(a.center[0] - b.rect.left) < a.radius:\n sol = [b.rect.left, a.center[1]]\n elif math.fabs(a.center[0] - b.rect.right) < a.radius:\n sol = [b.rect.right, a.center[1]]\n else:\n temp_func = lambda a, point: True if ((a.center[0] - point[0])**2 + (a.center[1] - point[1])**2) ** 0.5 < a.radius else False\n\n for side_1 in [b.rect.left, b.rect.right]:\n for side_2 in [b.rect.top, b.rect.bottom]:\n if temp_func(a, (side_1, side_2)):\n sol = [side_1, side_2]\n\n return sol\n\n\ndef update_screen(arg):\n # Выводим стену заднего фона на экран\n arg.screen.blit(arg.wall, arg.wall.get_rect())\n\n # Выводим разнообразые информациооные поля\n arg.fps_score.blit()\n\n if arg.state_flag == GameS:\n arg.speed_score.blit()\n\n # Вы водим все необходимые игровые данные на главный экран\n arg.score_table.blit()\n arg.best_score_table.blit()\n arg.lives_table.blit()\n arg.level_table.blit()\n arg.time_table.blit()\n elif arg.state_flag == MenuS:\n pass\n\n arg.game_area.blit(arg)\n\n\n # Отрисовываем всё на экране\n pygame.display.flip()\n\n\ndef update_state(arg):\n arg.fps_score.update()\n arg.game_area.update(arg)\n\n if arg.state_flag == GameS:\n arg.speed_score.update()\n\n arg.score_table.update()\n arg.best_score_table.update()\n arg.lives_table.update()\n arg.level_table.update()\n arg.time_table.update()\n elif arg.state_flag == MenuS:\n pass\n\n\ndef init(arg):\n # Загружаем стену\n arg.wall = make_wall('images/break.bmp', arg)\n\n # Создаём территорию для игры\n arg.game_area = Game_area(arg)\n\n # Создаём класс для подсчёта очков\n arg.stats = Stats(arg)\n arg.stats.load_prev_session(arg)\n\n # Создаём популяцию для обучения\n arg.population = Population(arg)\n arg.population.load_prev_session(arg)\n\n # Создаём меню\n arg.menu_height = 400\n arg.menu_width = arg.settings.ga_width\n arg.menu.append(make_welcome_menu(arg))\n\n arg.menu_height = 200\n arg.menu.append(make_stop_menu(arg))\n\n arg.menu.append(make_settings_menu(arg))\n\n arg.menu.append(make_unit_test_menu(arg))\n\n # Создаём объект платформы\n arg.image_name = 'images/new/platform 120x20.png'\n arg.platform = Platform(arg)\n\n # Создаём шар для игры\n arg.radius = 10\n arg.image_name = 'images/new/ball_aparture 20x20.png'\n arg.ball = Ball(arg)\n\n # Создаём блоки для ломания\n arg.image_name = 'images/new/block_'\n arg.blocks = Group()\n\n # Создаём Таймменеджер\n arg.timemanager = Timemanager()\n\n arg.timemanager.sing_up(\"be all\", \"af ch_ev\", \"check_event\")\n arg.timemanager.sing_up(\"af ch_ev\", \"af up_state\", \"update_state\")\n arg.timemanager.sing_up(\"af up_state\", \"af bliting\", \"bliting\")\n arg.timemanager.sing_up(\"af bliting\", \"af up_sing_ups\", \"update_sing_ups\")\n arg.timemanager.sing_up(\"be all\", \"af up_sing_ups\", \"All\")\n\n # Создаём разнообразные панели для вывода резов\n make_tables(arg)\n\n # Привязываем конец игры к нужным функциям\n arg.next_level = next_level\n arg.wasted = wasted\n\n\ndef make_tables(arg):\n arg.top_space = 10\n arg.left_space = arg.settings.screen_width - 90\n arg.fps_score = Label(arg, 'FPS:', lambda: int(\n \n 1000.0 / max(1, \n arg.timemanager.get_sibscriber(\"All\", False, False) / \n max(1, arg.timemanager.get_sibscriber(\"All\", False, True))\n )\n )\n )\n\n arg.left_space = arg.settings.screen_width - 220\n arg.speed_score = Label(arg, 'Speed:', lambda: arg.speed_count)\n\n arg.left_space = (arg.settings.screen_width - arg.settings.ga_width) // 2\n arg.top_space = arg.settings.screen_height - arg.settings.ga_height - 32\n arg.best_score_table = Label(arg, 'Best score:', lambda: int(arg.stats.max_count))\n\n arg.left_space += arg.settings.ga_width // 2\n arg.score_table = Label(arg, 'Score:', lambda: int(arg.stats.count))\n\n arg.left_space, arg.top_space = 10, 10\n arg.lives_table = Label(arg, 'Lives remain:', lambda: arg.stats.lives)\n\n arg.top_space += 30\n arg.level_table = Label(arg, 'Level:', lambda: arg.stats.level)\n\n arg.top_space, arg.left_space = 10, 200\n arg.time_table = Label(arg, 'Time:', lambda: (pygame.time.get_ticks() - arg.stats.start_time) // 1000)\n\n\n\n\ndef make_target_wall(arg):\n number_in_row = (arg.settings.ga_width - 4)//arg.settings.target_width\n side_space = (arg.settings.ga_width - number_in_row * arg.settings.target_width)//2\n\n\n for i in range(arg.settings.width_target_wall):\n x_pos, y_pos = side_space, arg.settings.space_target + i * arg.settings.target_height\n\n while(x_pos + arg.settings.target_width <= arg.game_area.rect.width - side_space):\n arg.top_space, arg.left_space = y_pos, x_pos\n arg.blocks.add(Block(arg))\n\n x_pos += arg.settings.target_width\n\n\ndef make_wall(name, arg):\n wall = pygame.Surface((arg.settings.screen_width, arg.settings.screen_height))\n wall.fill(arg.settings.bg_color)\n\n\n block = pygame.image.load(name).convert_alpha()\n\n block_rect = block.get_rect()\n wall_rect = wall.get_rect()\n\n side_space = (arg.settings.screen_width - arg.settings.ga_width)//2\n top_space = (arg.settings.screen_height - arg.settings.ga_height)\n piece_space = 10\n\n left_half_block = block.subsurface(block_rect.left, block_rect.top, piece_space, block_rect.bottom)\n right_half_block = block.subsurface(block_rect.right - piece_space, block_rect.top, piece_space, block_rect.bottom)\n\n y_pos = -(block_rect.height - top_space % block_rect.height)\n cnt = 0\n while y_pos < wall_rect.height:\n if cnt % 2: x_pos = 0\n else: x_pos = -block_rect.width//2\n\n while x_pos < wall_rect.width:\n wall.blit(block, (x_pos, y_pos))\n x_pos += block_rect.width\n\n if y_pos >= top_space:\n wall.blit(right_half_block, (side_space - piece_space, y_pos))\n wall.blit(left_half_block, (wall_rect.right - side_space, y_pos))\n\n cnt += 1\n y_pos += block_rect.height\n\n\n return wall\n\n\ndef make_stop_menu(arg):\n names = ['Continue', 'Settings', 'Save&Exit']\n button_types = [Button, Button, Button]\n buttons_width = [150, 150, 150]\n\n def continue_game(arg):\n arg.state_flag = GameS\n\n def settings_button(arg):\n arg.id_menu = 2\n arg.prev_id_menu = 1\n\n def exit_button(arg):\n arg.id_menu = 0\n\n funcs = [continue_game, settings_button, exit_button, continue_game]\n\n return Menu(arg, button_types, names, buttons_width, funcs)\n\n\ndef make_settings_menu(arg):\n names = ['Cheat Mode', 'Activate bot', 'Activate training', 'Activate visualising']\n button_types = [Check_box_button, Check_box_button, Check_box_button, Check_box_button]\n buttons_width = [240, 240, 240, 240]\n\n def cheat_mode_set(arg, value):\n arg.stats.cheat_mode = value\n def cheat_mode_get(arg):\n return arg.stats.cheat_mode\n\n def bot_activate_set(arg, value):\n arg.stats.bot_activate = value\n if arg.stats.bot_activate:\n arg.stats.training_flag = False\n arg.bot = arg.population.get_best()\n def bot_activate_get(arg):\n return arg.stats.bot_activate\n\n def training_set(arg, value):\n arg.stats.training_flag = value\n arg.platform.moving_left = False\n arg.platform.moving_right = False\n def training_get(arg):\n return arg.stats.training_flag\n\n def visualising_set(arg, value):\n arg.stats.visualising_flag = value\n def visualising_get(arg):\n return arg.stats.visualising_flag\n\n def exit_button(arg):\n arg.id_menu = arg.prev_id_menu\n\n funcs = [[cheat_mode_set, cheat_mode_get], [bot_activate_set, bot_activate_get], [training_set, training_get],\n [visualising_set, visualising_get], exit_button]\n\n return Menu(arg, button_types, names, buttons_width, funcs)\n\n\ndef make_welcome_menu(arg):\n names = ['New Game', 'Load Game', 'Unit Tests', 'Settings', 'Exit']\n button_types = [Button, Button, Button, Button, Button]\n buttons_width = [150, 150, 150, 150, 150]\n\n def new_game_c(arg):\n new_game(arg)\n arg.state_flag = GameS\n\n def unit_test_button(arg):\n arg.id_menu = 3\n\n def settings_button(arg):\n arg.id_menu = 2\n arg.prev_id_menu = 0\n\n def empty_func(arg):\n pass\n\n funcs = [new_game_c, empty_func, unit_test_button, settings_button, close_game, close_game]\n\n return Menu(arg, button_types, names, buttons_width, funcs)\n\n\ndef make_unit_test_menu(arg):\n tests = get_tests(arg)\n \n names = list()\n button_types = list()\n buttons_width = list()\n funcs = list()\n\n def exit_func(arg):\n arg.id_menu = 0\n\n for test in tests:\n names.append(test.description)\n button_types.append(Button)\n buttons_width.append(150)\n funcs.append(test.load)\n\n names.append(\"Back\")\n button_types.append(Button)\n buttons_width.append(150)\n funcs.append(exit_func)\n\n funcs.append(exit_func)\n\n return Menu(arg, button_types, names, buttons_width, funcs)\n\n\n\n\ndef restart(arg):\n arg.blocks.empty()\n make_target_wall(arg)\n\n arg.platform.restart(arg)\n arg.ball.restart(arg)\n\n\ndef new_game(arg):\n restart(arg)\n arg.stats.restart(arg)\n\n\ndef next_level(arg):\n print(1)\n restart(arg)\n arg.stats.increase_difficulty(arg)\n\n\ndef wasted(arg):\n #print('wasted')\n arg.stats.lives -= 1\n\n if arg.stats.training_flag:\n arg.population.end_game(arg)\n new_game(arg)\n else:\n if arg.stats.lives == 0:\n new_game(arg)\n else:\n next_level(arg)\n\n\n\ndef close_game(arg):\n arg.stats.save_cur_session(arg)\n arg.population.save_cur_session(arg)\n exit()\n\n\ndef print_debug(arg):\n subscribers = [\"All\", \"update_state\", \"bliting\", \"update_sing_ups\"]\n for subscriber in subscribers:\n print(subscriber, arg.timemanager.get_sibscriber(subscriber, True), \"%\")\n print()\n\n\ndef reduce_fps(arg):\n if random.randint(0, 100) < 5:\n diff_fps = arg.fps_score.func_text() - arg.settings.fps\n if diff_fps > 0:\n diff_fps *= 3\n arg.additional_time += diff_fps // 2\n \n pygame.time.delay(arg.additional_time)","sub_path":"game_functions.py","file_name":"game_functions.py","file_ext":"py","file_size_in_byte":13910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"35246489","text":"import torch\nfrom torch import nn\n\nclass BackboneNN(nn.Module):\n def __init__(self, num_classes,size):\n super(BackboneNN, self).__init__()\n self.size = size\n self.num_classes = num_classes\n # self.device1 = torch.device('cuda:0')\n self.alexnet = torch.hub.load('pytorch/vision:v0.6.0', 'alexnet', pretrained=True)\n self.modified_net = nn.Sequential(*list(self.alexnet.children())[:-1])\n\n self.meander_nn = self.modified_net\n self.spiral_nn = self.modified_net\n self.circle_nn = self.modified_net\n\n self.concat_nn = nn.Sequential(\n nn.Dropout(),\n nn.Linear(27648, 4096),\n nn.ReLU(inplace=True),\n nn.Dropout(p=0.35),\n nn.Linear(4096, 4096),\n nn.ReLU(inplace=True),\n nn.Linear(4096, self.num_classes),\n nn.Sigmoid()\n )\n\n # self.concat_nn = nn.DataParallel(self.concat_nn)\n\n def forward(self, meanders, spirals, circles):\n meanders = self.meander_nn(meanders)\n meanders = meanders.view(meanders.size(0), -1)\n\n spirals = self.spiral_nn(spirals)\n spirals = spirals.view(spirals.size(0), -1)\n\n circles = self.circle_nn(circles)\n circles = circles.view(circles.size(0), -1)\n\n # now we can concatenate them\n combined = torch.cat((meanders, spirals, circles), dim=1)\n out = self.concat_nn(combined)\n\n return out","sub_path":"backbone.py","file_name":"backbone.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"515506376","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\n@author: dwarak\n\"\"\"\n\nimport cv2\nimport numpy as np\nimport Homography\n#All the imports are done here\n\nimage1=cv2.imread('pics/1.jpg')\nimage2=cv2.imread('pics/2.jpg')\nimage3=cv2.imread('pics/3.jpg')\nimage4=cv2.imread('pics/Seinfeld.jpg')\n#all images are read using cv2 here\n\npoint1=np.array([[412,2117,1],[522,3300,1],[1496,2145,1],[1342,3316,1]])\npoint2=np.array([[786,1589,1],[753,2975,1],[1600,1628,1],[1507,2975,1]])\npoint3=np.array([[555,1000,1],[412,2420,1],[1402,1012,1],[1463,2376,1]])\npoint4=np.array([[0,0,1],[0,2560,1],[1536,0,1],[1536,2560,1]])\n#pixel coordinates are computed using GIMP\n\n\n###TASK 1\nH=Homography.compute_homography(point1,point4)\nimg=Homography.compute_mapped_image(image1,image4,H,point1)\ncv2.imwrite('new_homo1.jpg',img)\n#projecting seinfeldimage to image 1\n\n\nH=Homography.compute_homography(point2,point4)\nimg=Homography.compute_mapped_image(image2,image4,H,point2)\ncv2.imwrite('new_homo2.jpg',img)\n#projecting seinfeldimage to image 2\n\n\nH=Homography.compute_homography(point3,point4)\nimg=Homography.compute_mapped_image(image3,image4,H,point3)\ncv2.imwrite('new_homo3.jpg',img)\n#projecting seinfeldimage to image 3\n\n\n\n####TASK 2\nH1=Homography.compute_homography(point2,point1)\nH2=Homography.compute_homography(point3,point2)\nH=np.dot(H1,H2)\np=np.array([[0,0,1],[0,4128,1],[3096,0,1],[3096,4128,1]])\nimg=Homography.compute_distorted_image(image1,image3,H,p)\ncv2.imwrite('projectednn.jpg',img)\n#computing the product of homography and applying that to image \n\n####TASK 3\n\nimg1=cv2.imread('hi/01.jpg')\nimg2=cv2.imread('hi/02.jpg')\nimg3=cv2.imread('hi/03.jpg')\nimg4=cv2.imread('hi/kohli.jpg')\n\npoint1=np.array([[928,3284,1],[824,3788,1],[1692,3328,1],[1516,3836,1]])\npoint2=np.array([[1260,1648,1],[1284,2640,1],[2072,1676,1],[2064,2628,1]])\npoint3=np.array([[1132,600,1],[1224,1420,1],[1948,576,1],[2152,1376,1]])\npoint4=np.array([[0,0,1],[0,1600,1],[900,0,1],[900,1600,1]])\n\n\nH=Homography.compute_homography(point1,point4)\nimg=Homography.compute_mapped_image(img1,img4,H,point1)\ncv2.imwrite('new_homo12.jpg',img)\n\n\n#projecting kohli image to image 1\n\nH=Homography.compute_homography(point2,point4)\nimg=Homography.compute_mapped_image(img2,img4,H,point2)\ncv2.imwrite('new_homo22.jpg',img)\n#projecting kohli image to image 2\n\nH=Homography.compute_homography(point3,point4)\nimg=Homography.compute_mapped_image(img3,img4,H,point3)\ncv2.imwrite('new_homo32.jpg',img)\n#projecting kohli image to image 3\n\n\nH1=Homography.compute_homography(point2,point1)\nH2=Homography.compute_homography(point3,point2)\nH=np.dot(H1,H2)\np=np.array([[0,0,1],[0,5312,1],[2988,0,1],[2988,5312,1]])\nimg=Homography.compute_distorted_image(img1,img3,H,p)\ncv2.imwrite('projectednn2b.jpg',img)\n#computing the product of homography and applying that to image \n","sub_path":"Assignmnet2/final copy.py","file_name":"final copy.py","file_ext":"py","file_size_in_byte":2781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"97629716","text":"\"\"\"\nIntegration tests for the search websocket endpoint\n\"\"\"\nimport pytest\n\nimport ujson\n\nfrom .util import open_stream, start_test_server\n\n\n# pylint: disable=missing-docstring\n@pytest.mark.asyncio\nasync def test_do_match_search():\n async with start_test_server() as [ws_port, _, es_client]:\n props_to_index = [\n (\"a\", {\"name\": \"My Farm\", \"county\": \"Springfield\"}),\n (\"b\", {\"name\": \"Building\", \"county\": \"Washington\"}),\n ]\n\n for _id, body in props_to_index:\n await es_client.index(index=\"properties\", doc_type=\"_doc\", id=_id, body=body, refresh=True)\n\n async with open_stream(ws_port, \"/search\") as ws_client:\n await ws_client.send(\n ujson.dumps(\n {\n \"action\": \"search\",\n \"index\": \"properties\",\n \"body\": {\"query\": {\"match\": {\"name\": \"Building\"}}},\n }\n )\n )\n resp = ujson.loads(await ws_client.recv())\n assert resp.get(\"hits\", {}).get(\"total\", {}).get(\"value\") == 1\n assert resp[\"hits\"][\"hits\"][0][\"_id\"] == \"b\"\n\n\n@pytest.mark.asyncio\nasync def test_get_field_names():\n async with start_test_server() as [ws_port, _, es_client]:\n props_to_index = [\n (\"a\", {\"name\": \"My Farm\", \"county\": \"Springfield\"}),\n (\"b\", {\"name\": \"Building\", \"county\": \"Washington\"}),\n ]\n\n for _id, body in props_to_index:\n await es_client.index(index=\"properties\", doc_type=\"_doc\", id=_id, body=body, refresh=True)\n\n async with open_stream(ws_port, \"/search\") as ws_client:\n await ws_client.send(ujson.dumps({\"index\": \"properties\", \"action\": \"getFields\"}))\n resp = ujson.loads(await ws_client.recv())\n\n assert set([\"name\", \"county\"]) <= set(resp.get(\"fields\"))\n","sub_path":"data-streamer/remdata/inttest/test_search.py","file_name":"test_search.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"509107833","text":"from astropy.io import fits\nfrom astropy import wcs\n\ndef thum (img, cent, siz, fname = 'thum.fits', world= 0):\n\t'''\n\tCrop a thumbnail in a big fits image and save,\n\tincluding smart wcs transformation if desired.\n\n\tInputs:\n\t\timg, the big fits image, read as\n\t\t\tfrom astropy.io import fits\n\t\t\timg = fits.open('HDF.R.fits')\n\t\t\timg = img[0]\n\t\tcent, the center of the output thumbnail, formatted as [x, y], integers start from 0\n\t\tsiz, the output thumbnail size, [x_length, y_length], integers\n\t\t\tassumed to be [odd, odd]\n\t\t\tif even, +1\n\tKeywords:\n\t\tfnam, the output thumbnail name\n\t\tworld, 1, transfer wcs; 0 (default), don't bother with wcs\n\t'''\n\n\tx_bgn = cent[0] - siz[0]/2\t#calculate the corner coordinates\n\ty_bgn = cent[1] - siz[1]/2\n\tx_end = cent[0] + siz[0]/2 + 1\n\ty_end = cent[1] + siz[1]/2 + 1\n\n\t#Crop the thumbnail, note astropy convention contradicts with common sense\n\tarr = img.data[y_bgn: y_end, x_bgn: x_end]\n\tthum = fits.PrimaryHDU(data = arr)\t\n\n\tif world == 1 : \n\t\tthum.header = img.header.copy()\t#Deal with the new header\n\t\t#img_wcs = wcs.WCS(img.header)\t#Find ra, dec of the center\n\t\t#[ra, dec] = img_wcs.wcs_pix2world([cent], 0)[0]\t#Using python convention, img starting from [0,0]\n\t\t#thum.header.update(CRVAL1=ra, CRVAL2=dec, \n\t\t#\t\t\tCRPIX1=siz[0]/2 + 1, CRPIX2=siz[1]/2 + 1) #Update the reference point\n\t\told_x = thum.header['CRPIX1']\t#Get the old reference point\n\t\told_y = thum.header['CRPIX2']\n\t\tnew_x = old_x - x_bgn\t#Get the new one\n\t\tnew_y = old_y - y_bgn\n\t\tthum.header.update(CRPIX1=new_x, CRPIX2=new_y)\t#modify the header\n\t\n\tthum.writeto(fname, clobber = 1, output_verify = \"ignore\")\t#Write the file\n\n\treturn\t\t\n","sub_path":"my_img.py","file_name":"my_img.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"5593126","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 08 13:53:41 2013\n\n@author: Marcel\n\"\"\"\n\nfrom numpy import *\nfrom matplotlib import pyplot as plt\n\ndef wenn_Maus_geklickt(event):\n \"\"\"Zeichnet Punkt an Mausposition.\"\"\"\n plt.plot([event.xdata], [event.ydata], mfc='b', marker='o')\n plt.draw()\n\ndef wenn_Taste(event):\n \"\"\"Wenn 's' gedrueckt: zeichne Sinus-Kurve.\"\"\"\n if event.key == 'w':\n plt.plot(t, y, ls = '-', lw=1, c='r')\n plt.draw()\n \nplt.figure(0)\nplt.subplot(111, autoscale_on=False)\nplt.axis([0, 2*pi, -1, 1])\n\nt = linspace(0, 2*pi, 300)\ny = sin(t)\n\nplt.connect('button_press_event', wenn_Maus_geklickt)\nplt.connect('key_press_event', wenn_Taste)\nplt.show()","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"235848056","text":"import matplotlib\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom PIL import Image\nfrom models import SIRModel\n\n\n# For figure aesthetics\nplt.rcParams['mathtext.fontset'] = 'custom' \nplt.rcParams['mathtext.rm'] = 'Bitstream Vera Sans' \nplt.rcParams['mathtext.it'] = 'Bitstream Vera Sans:italic' \nplt.rcParams['mathtext.bf'] = 'Bitstream Vera Sans:bold' \nplt.rcParams['font.size'] = 16\nplt.rcParams['mathtext.fontset'] = 'stix' \nplt.rcParams['font.family'] = 'STIXGeneral' \n\n# Animation params\nfp_out = \"./Figures/anim_β_curve_flat.gif\"\n\n# Colormap\ncmap = matplotlib.cm.get_cmap('Reds')\ncolor_range = matplotlib.colors.Normalize(vmin=0.04, vmax=0.4)\n\n# Infection rate\nβs = np.linspace(0.08, 0.8, 11)\n\n# Recovery rate\nγ = 0.04\n\n# Population size\nN = 1.0\n\ntime_span = np.linspace(0, 300, 600)\ninitial_conditions = np.array([0.99, 0.01, 0.0])\nsolutions = []\nfor i in range(len(βs)):\n fig, ax = plt.subplots(1, 1, figsize=(5, 5))\n fig.patch.set_facecolor((239 / 255, 239 / 255, 239 / 255))\n ax.set_facecolor((239 / 255, 239 / 255, 239 / 255))\n\n for β in βs[:i]:\n # Simulation\n model = SIRModel(β, γ, N)\n solution = model(time_span, initial_conditions)\n ax.plot(time_span, solution[:, 1], c=\"#800a00ff\", label=\"$I(t)$\", alpha=0.3)\n β = βs[i]\n # Reproduction rate\n R0 = β / γ\n model = SIRModel(β, γ, N)\n solution = model(time_span, initial_conditions)\n ax.plot(time_span, solution[:, 1], c=\"#800a00ff\", label=\"$I(t)$\")\n ax.plot(time_span, [0.3] * len(time_span), c='k', linestyle='--')\n ax.set_ylabel('Fração da População')\n ax.set_xlabel('Tempo (dias)')\n ax.set_ylim([-0.05, 1.1])\n ax.text(0.0, 1.05, '$\\\\beta = {}$'.format(np.round(β, 3)))\n #plt.legend(frameon=False)\n plt.tight_layout()\n plt.savefig('./Figures/curve_flat_β_{}.png'.format(11 - i))\n\nimg, *imgs = [Image.open(f) for f in ['./Figures/curve_flat_β_{}.png'.format(i) for i in range(1, 12)]]\nimg.save(fp=fp_out, format='GIF', append_images=imgs,\n save_all=True, duration=200, loop=0)","sub_path":"flattening_the_curve.py","file_name":"flattening_the_curve.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"254625234","text":"\"\"\" Stwórz funkcję, w której dodasz dwie liczby \ni wyświetl to na ekranie. Jak ją nazwiesz? \nFunkcję stworzysz z użyciem def. \nW ciele umieść operację i funkcję print.\"\"\"\n\ndef sum_ab():\n a=0\n b=0\n c=0\n print(\"Daj liczbę A :\")\n a = int(input())\n print(\"Daj liczbe B :\")\n b = int(input())\n c = a+b\n print(\"suma liczb A=%d i B=%d to : %d\" %(a,b,c))\n\nsum_ab()\n\n\"\"\"\ntest funkcji zakupy\n\"\"\"\ndef shopping():\n shopping_items = [\n \"jajka\",\n \"bułka\",\n \"ser feta\",\n \"masło\",\n \"pomidor\"\n ]\n shopping_cart = \"Koszyk zawiera: \"\n for item in shopping_items:\n shopping_cart += item + '\\n'\n return shopping_cart\nprint(\"\\n KOLEJNA FUNKCJA \\n\")\nprint(shopping())\n\n\"\"\"\nJakiego typu jest None? Przetestuj to, wywołując \nfunkcję type na rezultacie funkcji, która nic nie zwraca.\nodp: \n\"\"\"\nprint(type(None))","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"265781373","text":"#!/usr/bin/python3 -u\n\nfrom helpers import *\nfrom iptables import check_iptables\nfrom auth_log import check_auth_log\nfrom send_mail import send_mail\n\nif __name__ == \"__main__\":\n from argparse import ArgumentParser\n import sys\n parser = ArgumentParser(description=\"TheMirador a python IDS\")\n parser.add_argument(\"-c\", \"--config\",\n dest=\"filename\", required=True, type=lambda x: is_valid_file(parser, x),\n help=\"Path to config file\", metavar=\"FILE\")\n parser.add_argument('-cli', action='store_true', dest='cli')\n parser.add_argument('-map', action='store_true', dest='map')\n\n args = parser.parse_args()\n\n print(\"Loading Config\")\n config = json.load(args.filename)\n hostname = config[\"system_name\"]\n log(\"Started Monitoring\") \n log(\"Watching Folders: \"+str(', '.join(config[\"watch_folders\"])))\n if not os.path.isdir(config[\"work_dir\"]):\n log(\"Baseline Not Generated, Generating\")\n first_run(config)\n if args.map:\n hash_watch_folders(config)\n if args.cli:\n while True:\n accessed_files = check_accessed(config)\n if len(accessed_files)>0:\n log(\"File Accessed inside folder\")\n send_mail(\"File Access Alert\",str(accessed_files),config['email_to'])\n log(accessed_files)\n else:\n pass\n hash_files = check_hash(config)\n if(len(hash_files)>0):\n log(\"Integrity Check Failed\")\n send_mail(\"File Integrity Check Failed\",str(hash_files),config['email_to'])\n log(hash_files)\n hash_watch_folders(config)\n else:\n pass\n \n check_iptables(config)\n check_auth_log()\n time.sleep(5)\n","sub_path":"watch.py","file_name":"watch.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"633315216","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nCommon Generator Library\nCopyright (C) 2012-2015 Matthias Bolte \nCopyright (C) 2012-2015 Olaf Lüke \n\ncommon.py: Common Library for generation of bindings and documentation\n\nThis program is free software; you can redistribute it and/or\nmodify it under the terms of the GNU General Public License\nas published by the Free Software Foundation; either version 2\nof the License, or (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nGeneral Public License for more details.\n\nYou should have received a copy of the GNU General Public\nLicense along with this program; if not, write to the\nFree Software Foundation, Inc., 59 Temple Place - Suite 330,\nBoston, MA 02111-1307, USA.\n\"\"\"\n\nimport os\nimport shutil\nimport re\nimport datetime\nimport subprocess\nimport sys\nimport copy\nimport multiprocessing.dummy\nfrom collections import namedtuple\nfrom pprint import pprint\n\ngen_text_star = \"\"\"/* ***********************************************************\n * This file was automatically generated on {0}. *\n * *\n * Bindings Version {1}.{2}.{3} *\n * *\n * If you have a bugfix for this file and want to commit it, *\n * please fix the bug in the generator. You can find a link *\n * to the generators git repository on tinkerforge.com *\n *************************************************************/\n\"\"\"\n\ngen_text_hash = \"\"\"#############################################################\n# This file was automatically generated on {0}. #\n# #\n# Bindings Version {1}.{2}.{3} #\n# #\n# If you have a bugfix for this file and want to commit it, #\n# please fix the bug in the generator. You can find a link #\n# to the generators git repository on tinkerforge.com #\n#############################################################\n\"\"\"\n\ngen_text_curly = \"\"\"{{\n This file was automatically generated on {0}.\n\n Bindings Version {1}.{2}.{3}\n\n If you have a bugfix for this file and want to commit it,\n please fix the bug in the generator. You can find a link\n to the generator git on tinkerforge.com\n}}\n\"\"\"\n\ngen_text_rst = \"\"\"..\n #############################################################\n # This file was automatically generated on {0}. #\n # #\n # If you have a bugfix for this file and want to commit it, #\n # please fix the bug in the generator. You can find a link #\n # to the generators git repository on tinkerforge.com #\n #############################################################\n\"\"\"\n\nbf_str = {\n'en': \"\"\"\nBasic Functions\n^^^^^^^^^^^^^^^\n\n{0}\n\n{1}\n\"\"\",\n'de': \"\"\"\nGrundfunktionen\n^^^^^^^^^^^^^^^\n\n{0}\n\n{1}\n\"\"\"\n}\n\naf_str = {\n'en': \"\"\"\nAdvanced Functions\n^^^^^^^^^^^^^^^^^^\n\n{0}\n\"\"\",\n'de': \"\"\"\nFortgeschrittene Funktionen\n^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n{0}\n\"\"\"\n}\n\nccf_str = {\n'en': \"\"\"\nCallback Configuration Functions\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n{0}\n\n{1}\n\"\"\",\n'de': \"\"\"\nKonfigurationsfunktionen für Callbacks\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n{0}\n\n{1}\n\"\"\"\n}\n\nbreadcrumbs_str = {\n'en': \"\"\":breadcrumbs: Home / Software / {1}\n\"\"\",\n'de': \"\"\":breadcrumbs: Startseite / Software / {1}\n\"\"\"\n}\n\nlang = 'en'\n\ndef shift_right(text, n):\n return text.replace('\\n', '\\n' + ' '*n)\n\ndef get_changelog_version(bindings_root_directory):\n r = re.compile('^(\\d+)\\.(\\d+)\\.(\\d+):')\n last = None\n\n for line in file(os.path.join(bindings_root_directory, 'changelog.txt'), 'rb').readlines():\n m = r.match(line)\n\n if m is not None:\n last = (m.group(1), m.group(2), m.group(3))\n\n return last\n\ndef get_image_size(path):\n from PIL import Image\n\n return Image.open(path).size\n\ndef select_lang(d):\n if lang in d:\n return d[lang]\n elif 'en' in d:\n return d['en']\n else:\n return \"Missing '{0}' documentation\".format(lang)\n\ndef make_rst_header(device, has_device_identifier_constant=True):\n bindings_display_name = device.get_generator().get_bindings_display_name()\n ref_name = device.get_generator().get_bindings_name()\n date = datetime.datetime.now().strftime(\"%Y-%m-%d\")\n full_title = '{0} - {1}'.format(bindings_display_name, device.get_long_display_name())\n full_title_underline = '='*len(full_title)\n breadcrumbs = select_lang(breadcrumbs_str).format(ref_name, full_title)\n device_identifier_constant = {'en': '.. |device_identifier_constant| replace:: There is also a :ref:`constant <{0}_{1}_{2}_constants>` for the device identifier of this {3}.\\n',\n 'de': '.. |device_identifier_constant| replace:: Es gibt auch eine :ref:`Konstante <{0}_{1}_{2}_constants>` für den Device Identifier dieses {3}.\\n'}\n\n if device.is_released():\n orphan = ''\n else:\n orphan = ':orphan:'\n\n if has_device_identifier_constant:\n device_identifier_constant = select_lang(device_identifier_constant).format(device.get_underscore_name(),\n device.get_underscore_category(),\n ref_name,\n device.get_camel_case_category())\n else:\n device_identifier_constant = '.. |device_identifier_constant| unicode:: 0xA0\\n :trim:\\n'\n\n ref = '.. _{0}_{1}_{2}:\\n'.format(device.get_underscore_name(), device.get_underscore_category(), ref_name)\n\n return '{0}\\n{1}\\n{2}\\n{3}\\n{4}\\n{5}\\n{6}\\n'.format(gen_text_rst.format(date),\n orphan,\n breadcrumbs,\n device_identifier_constant,\n ref,\n full_title,\n full_title_underline)\n\ndef make_rst_summary(device, is_programming_language=True):\n not_released = {\n 'en': \"\"\"\n.. note::\n {0} is currently in the prototype stage and the software/hardware\n as well as the documentation is in an incomplete state.\n\n\"\"\",\n 'de': \"\"\"\n.. note::\n {0} ist im Moment in der Prototyp-Phase und die Software/Hardware\n sowie die Dokumentation sind in einem unfertigen Zustand.\n\n\"\"\"\n }\n\n summary = {\n 'en': \"\"\"\nThis is the description {0} for {1}. General information and technical\nspecifications for the {2} are summarized in its :ref:`hardware description\n<{3}_description>`.\n\"\"\",\n 'de': \"\"\"\nDies ist die Beschreibung {0} für {1}. Allgemeine Informationen über\ndie Funktionen und technischen Spezifikationen des {2} sind in dessen\n:ref:`Hardware Beschreibung <{3}_description>` zusammengefasst.\n\"\"\"\n }\n\n summary_install = {\n 'en': \"\"\"\nAn :ref:`installation guide ` for the {1} API\nbindings is part of their general description.\n\"\"\",\n 'de': \"\"\"\nEine :ref:`Installationanleitung ` für die {1} API\nBindings ist Teil deren allgemeine Beschreibung.\n\"\"\"\n }\n\n brick = {\n 'en': 'This Brick',\n 'de': 'Dieser Brick'\n }\n\n bricklet = {\n 'en': 'This Bricklet',\n 'de': 'Dieses Bricklet'\n }\n\n programming_language_name_link = {\n 'en': 'of the :ref:`{0} API bindings `',\n 'de': 'der :ref:`{0} API Bindings `'\n }\n\n protocol_name_link = {\n 'en': 'of the :ref:`{0} protocol `',\n 'de': 'des :ref:`{0} Protokolls `'\n }\n\n brick_name = {\n 'en': 'the :ref:`{0} <{1}_brick>`',\n 'de': 'den :ref:`{0} <{1}_brick>`',\n }\n\n bricklet_name = {\n 'en': 'the :ref:`{0} <{1}_bricklet>`',\n 'de': 'das :ref:`{0} <{1}_bricklet>`',\n }\n\n # format bindings name\n if is_programming_language:\n bindings_name_link = select_lang(programming_language_name_link)\n else:\n bindings_name_link = select_lang(protocol_name_link)\n\n bindings_name_link = bindings_name_link.format(device.get_generator().get_bindings_display_name(),\n device.get_generator().get_bindings_name())\n\n # format device name\n if device.get_camel_case_category() == 'Brick':\n device_name = select_lang(brick_name)\n else:\n device_name = select_lang(bricklet_name)\n\n device_name = device_name.format(device.get_long_display_name(),\n device.get_underscore_name())\n\n s = select_lang(summary).format(bindings_name_link,\n device_name,\n device.get_long_display_name(),\n device.get_underscore_name() + '_' + device.get_underscore_category())\n\n if is_programming_language:\n s += select_lang(summary_install).format(device.get_generator().get_bindings_name(),\n device.get_generator().get_bindings_display_name())\n\n if not device.is_released():\n if device.get_camel_case_category() == 'Brick':\n d = brick\n else:\n d = bricklet\n\n s = select_lang(not_released).format(select_lang(d)) + s\n\n return s\n\ndef make_rst_examples(title_from_filename, device,\n url_fixer=None, is_picture=False, additional_download_finder=None,\n display_name_fixer=None, language_from_filename=None,\n add_test_link=False):\n bindings_name = device.get_generator().get_bindings_name()\n filename_regex = device.get_generator().get_doc_example_regex()\n\n ex = {\n 'en': \"\"\"\n{0}\n\nExamples\n--------\n\nThe example code below is `Public Domain (CC0 1.0)\n`__.\n\"\"\",\n 'de': \"\"\"\n{0}\n\nBeispiele\n---------\n\nDer folgende Beispielcode ist `Public Domain (CC0 1.0)\n`__.\n\"\"\"\n }\n\n imp_code = \"\"\"\n{0}\n{1}\n\n{3}\n\n.. literalinclude:: {2}\n :language: {4}\n :linenos:\n :tab-width: 4\n\"\"\"\n\n imp_picture = \"\"\"\n{0}\n{1}\n\n{3}\n\n.. image:: /Images/Screenshots/LabVIEW/{2}\n :scale: 100 %\n :alt: LabVIEW {0} Example\n :align: center\n\"\"\"\n\n imp_picture_scroll = \"\"\"\n{0}\n{1}\n\n{3}\n\n.. raw:: html\n\n
    \n\n.. image:: /Images/Screenshots/LabVIEW/{2}\n :scale: 100 %\n :alt: LabVIEW {0} Example\n :align: center\n\n.. raw:: html\n\n
    \n\"\"\"\n\n download = '`Download ({0}) <{1}>`__'\n url_format = 'https://github.com/Tinkerforge/{0}/raw/master/software/examples/{1}/{2}'\n\n imp = imp_code\n if is_picture:\n imp = imp_picture_scroll\n\n ref = '.. _{0}_{1}_{2}_examples:\\n'.format(device.get_underscore_name(),\n device.get_underscore_category(),\n bindings_name)\n examples = select_lang(ex).format(ref)\n files = find_device_examples(device, filename_regex)\n copy_files = []\n include_name = device.get_generator().get_doc_rst_filename_part()\n\n for f in files:\n if is_picture:\n if get_image_size(f[1])[0] > 950:\n imp = imp_picture_scroll\n else:\n imp = imp_picture\n\n if language_from_filename is None:\n language = bindings_name\n else:\n language = language_from_filename(f[0])\n\n include = '{0}_{1}_{2}_{3}'.format(device.get_camel_case_name(), device.get_camel_case_category(), include_name, f[0].replace(' ', '_'))\n copy_files.append((f[1], include))\n title = title_from_filename(f[0])\n git_name = device.get_dash_name() + '-' + device.get_dash_category()\n url = url_format.format(git_name, bindings_name, f[0].replace(' ', '%20'))\n\n if url_fixer is not None:\n url = url_fixer(url)\n\n display_name = f[0]\n\n if display_name_fixer is not None:\n display_name = display_name_fixer(display_name)\n\n downloads = []\n\n if additional_download_finder is not None:\n for additional_download in additional_download_finder(f[1]):\n additional_url = url_format.format(git_name, bindings_name, additional_download.replace(' ', '%20'))\n downloads.append(download.format(additional_download, additional_url))\n\n downloads = [download.format(display_name, url)] + downloads\n\n if add_test_link and include.endswith('.html'):\n downloads.append('`Test ({0}) `__'.format(display_name, lang, include))\n\n examples += imp.format(title, '^'*len(title), include, ', '.join(downloads), language)\n\n copy_examples(copy_files, device.get_generator().get_bindings_root_directory())\n return examples\n\ndef default_example_compare(i, j):\n c = cmp(i[2], j[2]) # lines\n\n if c != 0:\n return c\n\n return cmp(i[0], j[0]) # filename\n\ndef find_examples(examples_directory, filename_regex, compare_examples=default_example_compare):\n compiled_filename_regex = re.compile(filename_regex)\n examples = []\n\n if os.path.isdir(examples_directory):\n for example_filename in sorted(os.listdir(examples_directory)):\n if compiled_filename_regex.match(example_filename) is not None:\n example_path = os.path.join(examples_directory, example_filename)\n lines = 0\n\n if example_path.endswith('.png'):\n size = get_image_size(example_path)\n lines = size[0] * size[1]\n else:\n for line in open(example_path):\n lines += 1\n\n examples.append((example_filename, example_path, lines))\n\n examples.sort(compare_examples)\n\n return examples\n\ndef find_device_examples(device, filename_regex):\n bindings_name = device.get_generator().get_bindings_name()\n examples_directory = os.path.join(device.get_git_directory(), 'software', 'examples', bindings_name)\n\n return find_examples(examples_directory, filename_regex, device.get_generator().compare_examples)\n\ndef copy_examples(copy_files, path):\n doc_path = os.path.join(path, 'doc', lang)\n print(' * Copying examples:')\n for copy_file in copy_files:\n doc_dest = os.path.join(doc_path, copy_file[1])\n doc_src = copy_file[0]\n shutil.copy(doc_src, doc_dest)\n print(' - {0}'.format(copy_file[1]))\n\n if len(copy_files) == 0:\n print(' \\033[01;31m! No examples\\033[0m')\n\ndef make_zip(dirname, source_path, dest_path, version):\n zipname = 'tinkerforge_{0}_bindings_{1}_{2}_{3}.zip'.format(dirname, *version)\n\n with ChangedDirectory(source_path):\n args = ['/usr/bin/zip',\n '-q',\n '-r',\n zipname,\n '.']\n\n if subprocess.call(args) != 0:\n raise Exception(\"Command '{0}' failed\".format(' '.join(args)))\n\n shutil.copy(zipname, dest_path)\n\nre_camel_case_to_space = re.compile('([A-Z][A-Z][a-z])|([a-z][A-Z])|([a-zA-Z][0-9])')\n\ndef camel_case_to_space(name):\n return re_camel_case_to_space.sub(lambda m: m.group()[:1] + \" \" + m.group()[1:], name)\n\ndef format_since_firmware(device, packet):\n since = packet.get_since_firmware()\n\n if since is not None and since > [2, 0, 0]:\n if device.get_camel_case_category() == 'Brick':\n suffix = 'Firmware'\n else:\n suffix = 'Plugin'\n\n return '\\n.. versionadded:: {1}.{2}.{3}$nbsp;({0})\\n'.format(suffix, *since)\n else:\n return ''\n\ndef default_constant_format(prefix, constant_group, constant, value):\n return '* {0}{1}_{2} = {3}\\n'.format(prefix, constant_group.get_upper_case_name(),\n constant.get_upper_case_name(), value)\n\ndef format_constants(prefix, packet,\n constants_name={'en': 'constants', 'de': 'Konstanten'},\n char_format=\"'{0}'\",\n constant_format_func=default_constant_format,\n constants_intro=None):\n if constants_intro == None:\n constants_intro = {\n 'en': \"\"\"\nThe following {0} are available for this function:\n\n\"\"\",\n 'de': \"\"\"\nDie folgenden {0} sind für diese Funktion verfügbar:\n\n\"\"\"\n }\n\n constants = []\n\n for constant_group in packet.get_constant_groups():\n for constant in constant_group.get_constants():\n if constant_group.get_type() == 'char':\n value = char_format.format(constant.get_value())\n else:\n value = str(constant.get_value())\n\n constants.append(constant_format_func(prefix, constant_group, constant, value))\n\n if len(constants) > 0:\n return select_lang(constants_intro).format(select_lang(constants_name)) + ''.join(constants)\n else:\n return ''\n\ndef format_function_id_constants(prefix, device,\n constants_name={'en': 'constants', 'de': 'Konstanten'}):\n str_constants = {\n'en': \"\"\"\nThe following function ID {0} are available for this function:\n\n\"\"\",\n'de': \"\"\"\nDie folgenden Funktions ID {0} sind für diese Funktion verfügbar:\n\n\"\"\"\n}\n str_constant = '* {0}FUNCTION_{1} = {2}\\n'\n str_constants = select_lang(str_constants).format(select_lang(constants_name))\n for packet in device.get_packets('function'):\n if len(packet.get_elements('out')) == 0 and packet.get_function_id() >= 0:\n str_constants += str_constant.format(prefix,\n packet.get_upper_case_name(),\n packet.get_function_id())\n\n return str_constants\n\ndef handle_rst_word(text,\n parameter={'en': 'parameter', 'de': 'Parameter'},\n parameters={'en': 'parameters', 'de': 'Parameter'},\n constants={'en': 'constants', 'de': 'Konstanten'}):\n text = text.replace(\":word:`parameter`\", select_lang(parameter))\n text = text.replace(\":word:`parameters`\", select_lang(parameters))\n text = text.replace(\":word:`constants`\", select_lang(constants))\n\n return text\n\ndef handle_rst_param(text, format_parameter):\n return re.sub('\\:param\\:\\`([^\\`]+)\\`', lambda match: format_parameter(match.group(1)), text)\n\ndef handle_rst_substitutions(text, packet):\n subsitutions = packet.get_doc_substitutions()\n\n if len(subsitutions) == 0:\n return text\n\n for key, value in subsitutions.items():\n text = text.replace('|' + key + '|', value)\n\n return text\n\ndef make_headless_camel_case(camel_case_name, underscore_name):\n prefix_len = len(underscore_name.split('_')[0])\n\n return camel_case_name[:prefix_len].lower() + camel_case_name[prefix_len:]\n\ndef underscore_to_headless_camel_case(name):\n parts = name.split('_')\n ret = parts[0]\n for part in parts[1:]:\n ret += part[0].upper() + part[1:]\n return ret\n\ndef underscore_to_space(name):\n ret = []\n for part in name.split('_'):\n ret.append(part[0].upper() + part[1:])\n return ' '.join(ret)\n\ndef recreate_directory(directory):\n if os.path.exists(directory):\n shutil.rmtree(directory)\n os.makedirs(directory)\n\ndef specialize_template(template_filename, destination_filename, replacements):\n template_file = open(template_filename, 'rb')\n lines = []\n replaced = set()\n\n for line in template_file.readlines():\n for key in replacements:\n replaced_line = line.replace(key, replacements[key])\n\n if replaced_line != line:\n replaced.add(key)\n\n line = replaced_line\n\n lines.append(line)\n\n template_file.close()\n\n if replaced != set(replacements.keys()):\n raise Exception('Not all replacements for {0} have been applied'.format(template_filename))\n\n destination_file = open(destination_filename, 'wb')\n destination_file.writelines(lines)\n destination_file.close()\n\ndef generate(bindings_root_directory, language, generator_class):\n global lang\n lang = language\n\n path_config = os.path.join(bindings_root_directory, '..', 'configs')\n if path_config not in sys.path:\n sys.path.append(path_config)\n configs = sorted(os.listdir(path_config))\n\n configs.remove('device_commonconfig.py')\n configs.remove('brick_commonconfig.py')\n configs.remove('bricklet_commonconfig.py')\n\n common_device_packets = copy.deepcopy(__import__('device_commonconfig').common_packets)\n common_brick_packets = copy.deepcopy(__import__('brick_commonconfig').common_packets)\n common_bricklet_packets = copy.deepcopy(__import__('bricklet_commonconfig').common_packets)\n\n brick_infos = []\n bricklet_infos = []\n\n generator = generator_class(bindings_root_directory, language)\n\n generator.prepare()\n\n for config in configs:\n if config.endswith('_config.py'):\n com = copy.deepcopy(__import__(config[:-3]).com)\n if com['released']:\n print(' * {0}'.format(config[:-10]))\n else:\n print(' * {0} \\033[01;36m(not released)\\033[0m'.format(config[:-10]))\n\n def prepare_common_packets(common_packets):\n for common_packet in common_packets:\n if common_packet['since_firmware'] is None:\n continue\n\n if com['name'][1] in common_packet['since_firmware']:\n common_packet['since_firmware'] = \\\n common_packet['since_firmware'][com['name'][1]]\n else:\n common_packet['since_firmware'] = \\\n common_packet['since_firmware']['*']\n\n if common_packet['since_firmware'] is None:\n common_packet['to_be_removed'] = True\n\n return filter(lambda x: 'to_be_removed' not in x, common_packets)\n\n if 'brick_' in config and 'common_included' not in com:\n common_packets = copy.deepcopy(common_device_packets) + copy.deepcopy(common_brick_packets)\n com['packets'].extend(prepare_common_packets(common_packets))\n com['common_included'] = True\n\n if 'bricklet_' in config and 'common_included' not in com:\n common_packets = copy.deepcopy(common_device_packets) + copy.deepcopy(common_bricklet_packets)\n com['packets'].extend(prepare_common_packets(common_packets))\n com['common_included'] = True\n\n device = generator.get_device_class()(com, generator)\n\n if device.get_camel_case_category() == 'Brick':\n ref_name = device.get_underscore_name() + '_brick'\n hardware_doc_name = device.get_short_display_name().replace(' ', '_').replace('/', '_').replace('-', '').replace('2.0', 'V2') + '_Brick'\n software_doc_prefix = device.get_camel_case_name() + '_Brick'\n git_name = device.get_dash_name() + '-brick'\n\n if device.get_device_identifier() != 17:\n firmware_url_part = device.get_underscore_name()\n else:\n firmware_url_part = None\n\n device_info = (device.get_device_identifier(),\n device.get_long_display_name(),\n device.get_short_display_name(),\n ref_name,\n hardware_doc_name,\n software_doc_prefix,\n git_name,\n firmware_url_part,\n device.is_released(),\n True,\n {\n 'en': device.get_description('en'),\n 'de': device.get_description('de')\n })\n\n brick_infos.append(device_info)\n else:\n ref_name = device.get_underscore_name() + '_bricklet'\n hardware_doc_name = device.get_short_display_name().replace(' ', '_').replace('/', '_').replace('-', '').replace('2.0', 'V2')\n software_doc_prefix = device.get_camel_case_name() + '_Bricklet'\n git_name = device.get_dash_name() + '-bricklet'\n firmware_url_part = device.get_underscore_name()\n\n device_info = (device.get_device_identifier(),\n device.get_long_display_name(),\n device.get_short_display_name(),\n ref_name,\n hardware_doc_name,\n software_doc_prefix,\n git_name,\n firmware_url_part,\n device.is_released(),\n True,\n {\n 'en': device.get_description('en'),\n 'de': device.get_description('de')\n })\n\n bricklet_infos.append(device_info)\n\n generator.generate(device)\n\n generator.finish()\n\n brick_infos.append((None, 'Debug Brick', 'Debug', 'debug_brick', 'Debug_Brick', None, 'debug-brick', None, True, False,\n {'en': 'For Firmware Developers: JTAG and serial console',\n 'de': 'Für Firmware Entwickler: JTAG und serielle Konsole'}))\n\n bricklet_infos.append((None, 'Breakout Bricklet', 'Breakout', 'breakout_bricklet', 'Breakout', None, 'breakout-bricklet', None, True, False,\n {'en': 'Makes all Bricklet signals available',\n 'de': 'Macht alle Bricklet Signale zugänglich'}))\n\n with open(os.path.join(bindings_root_directory, '..', 'device_infos.py'), 'wb') as f:\n f.write('from collections import namedtuple\\n')\n f.write('\\n')\n f.write(\"DeviceInfo = namedtuple('DeviceInfo', 'identifier long_display_name short_display_name ref_name hardware_doc_name software_doc_prefix git_name firmware_url_part is_released has_bindings description')\\n\")\n f.write('\\n')\n f.write('brick_infos = \\\\\\n')\n f.write('[\\n')\n\n for brick_info in sorted(brick_infos):\n f.write(' DeviceInfo{0},\\n'.format(brick_info))\n\n f.write(']\\n')\n f.write('\\n')\n f.write('bricklet_infos = \\\\\\n')\n f.write('[\\n')\n\n for bricklet_info in sorted(bricklet_infos):\n f.write(' DeviceInfo{0},\\n'.format(bricklet_info))\n\n f.write(']\\n')\n\ncn_valid_camel_case_chars = re.compile('^[A-Z][A-Za-z0-9]*$')\ncn_valid_underscore_chars = re.compile('^[a-z][a-z0-9_]*$')\ncn_valid_display_chars = re.compile('^[A-Z][A-Za-z0-9/ -.]*$')\ncn_valid_constant_camel_case_chars = re.compile('^[A-Za-z0-9]+$')\ncn_valid_constant_underscore_chars = re.compile('^[a-z0-9_]+$')\n\ncn_all_uppercase = ['api', 'ir', 'us', 'lcd', 'dc', 'imu', 'pwm', 'gps', 'id', 'io4',\n 'io16', 'led', 'i2c', 'ptc', 'red', 'rs485', 'eap', 'usb', 'mac',\n '2d', '3d', '1k', '100k', '500k', '3v', '6v', '10v', '36v',\n '45v', 'sps', 'oqpsk', 'bpsk40', 'dhcp', 'ip', 'wpa',\n 'wpa2', 'ca', 'wep', 'rgb', 'nfc', 'rfid', 'fifo', 'uv',\n 'ws2801', 'ws2811', 'ws2812', 'adc', 'rs232', 'ac', 'oled',\n '125dps', '250dps', '500dps', '1000dps', '2000dps', 'co2', 'ap']\n\ncn_eap_suffix = ['fast', 'tls', 'ttls', 'peap', 'mschap', 'gtc']\n\ncn_special_camel_case = {'mhz': 'MHz',\n '20ma': '20mA',\n '24ma': '24mA',\n '5v': '5V',\n '10v': '10V',\n '64000lux': '64000Lux',\n '32000lux': '32000Lux',\n '16000lux': '16000Lux',\n '8000lux': '8000Lux',\n '1300lux': '1300Lux',\n '600lux': '600Lux',\n '3hz': '3Hz',\n '6hz': '6Hz',\n '10hz': '10Hz',\n '12hz': '12Hz',\n '25hz': '25Hz',\n '50hz': '50Hz',\n '60hz': '60Hz',\n '80hz': '80Hz',\n '100hz': '100Hz',\n '200hz': '200Hz',\n '400hz': '400Hz',\n '800hz': '800Hz',\n '1600hz': '1600Hz',\n '1to11': '1To11',\n '1to13': '1To13',\n '1to14': '1To14'}\n\ndef check_name(camel_case, underscore, short_display=None, long_display=None, is_constant=False, device_category=None):\n if camel_case != None:\n if is_constant:\n r = cn_valid_constant_camel_case_chars\n else:\n r = cn_valid_camel_case_chars\n\n if r.match(camel_case) == None:\n raise ValueError(\"camel case name '{0}' contains invalid chars\".format(camel_case))\n\n if underscore != None:\n if is_constant:\n r = cn_valid_constant_underscore_chars\n else:\n r = cn_valid_underscore_chars\n\n if r.match(underscore) == None:\n raise ValueError(\"underscore name '{0}' contains invalid chars\".format(underscore))\n\n if short_display != None:\n if cn_valid_display_chars.match(short_display) == None:\n raise ValueError(\"short display name '{0}' contains invalid chars\".format(short_display))\n\n if camel_case != None and underscore != None:\n # test 1\n camel_case_to_check = camel_case.lower()\n underscore_to_check = underscore.replace('_', '')\n\n if camel_case_to_check != underscore_to_check:\n raise ValueError(\"camel case name '{0}' ({1}) and underscore name '{2}' ({3}) mismatch (test 1)\" \\\n .format(camel_case, camel_case_to_check, underscore, underscore_to_check))\n\n # test 2\n parts = []\n for part in underscore.split('_'):\n if part in cn_all_uppercase:\n parts.append(part.upper())\n elif part in cn_special_camel_case:\n parts.append(cn_special_camel_case[part])\n elif part in cn_eap_suffix and len(parts) > 0 and parts[-1] == 'EAP':\n parts.append(part.upper())\n else:\n parts.append(part[0].upper() + part[1:])\n\n underscore_to_check = ''.join(parts)\n\n if camel_case != underscore_to_check:\n raise ValueError(\"camel case name '{0}' and underscore name '{1}' ({2}) mismatch (test 2)\" \\\n .format(camel_case, underscore, underscore_to_check))\n\n if camel_case != None and short_display != None:\n # test 1\n short_display_to_check = short_display.replace(' ', '').replace('-', '').replace('/', '')\n\n if short_display_to_check.endswith('2.0'):\n short_display_to_check = short_display_to_check.replace('2.0', 'V2')\n\n if camel_case != short_display_to_check:\n raise ValueError(\"camel case name '{0}' and short display name '{1}' ({2}) mismatch (test 1)\" \\\n .format(camel_case, short_display, short_display_to_check))\n\n # test 2\n camel_case_to_check = camel_case_to_space(camel_case)\n\n if camel_case == 'IMUV2':\n camel_case_to_check = camel_case_to_check.replace('V 2', ' 2.0')\n elif camel_case_to_check.endswith('CO 2'):\n camel_case_to_check = camel_case_to_check.replace('CO 2', 'CO2')\n elif camel_case.endswith('V2'):\n camel_case_to_check = camel_case_to_check.replace('V2', '2.0')\n elif camel_case in ['IO4', 'IO16']:\n camel_case_to_check = camel_case_to_check.replace(' ', '-')\n elif camel_case in ['Current12', 'Current25']:\n camel_case_to_check = camel_case_to_check.replace(' ', '')\n elif camel_case == 'VoltageCurrent':\n camel_case_to_check = camel_case_to_check.replace(' ', '/')\n elif camel_case.endswith('16x2'):\n camel_case_to_check = camel_case_to_check.replace('16x 2', '16x2')\n elif camel_case.endswith('20x4'):\n camel_case_to_check = camel_case_to_check.replace('20x 4', '20x4')\n elif camel_case.endswith('128x64'):\n camel_case_to_check = camel_case_to_check.replace('128x 64', '128x64')\n elif camel_case.endswith('64x48'):\n camel_case_to_check = camel_case_to_check.replace('64x 48', '64x48')\n elif camel_case.endswith('4x7'):\n camel_case_to_check = camel_case_to_check.replace('4x 7', '4x7')\n elif camel_case.endswith('020mA'):\n camel_case_to_check = camel_case_to_check.replace('020m A', '0-20mA')\n elif camel_case.endswith('RS232'):\n camel_case_to_check = camel_case_to_check.replace('RS 232', 'RS232')\n elif camel_case == 'NFCRFID':\n camel_case_to_check = camel_case_to_check.replace('NFCRFID', 'NFC/RFID')\n\n if camel_case_to_check != short_display:\n raise ValueError(\"camel case name '{0}' ({1}) and short display name '{2}' mismatch (test 2)\" \\\n .format(camel_case, camel_case_to_check, short_display))\n\n if underscore != None and short_display != None:\n short_display_to_check = short_display.replace(' ', '_').replace('/', '_')\n\n if short_display.endswith('2.0'):\n short_display_to_check = short_display_to_check.replace('2.0', 'V2')\n elif short_display in ['IO-4', 'IO-16']:\n short_display_to_check = short_display_to_check.replace('-', '')\n else:\n short_display_to_check = short_display_to_check.replace('-', '_')\n\n short_display_to_check = short_display_to_check.lower()\n\n if underscore != short_display_to_check.lower():\n raise ValueError(\"underscore name '{0}' and short display name '{1}' ({2}) mismatch\" \\\n .format(underscore, short_display, short_display_to_check))\n\n if short_display != None and long_display != None and device_category != None:\n short_display_to_check = set(short_display.split(' ') + [device_category])\n long_display_to_check = set(long_display.split(' '))\n\n if short_display_to_check != long_display_to_check:\n raise ValueError(\"long display name '{0}' and short display name '{1}' + '{2}' ({3}) do not contain the same words\" \\\n .format(long_display, short_display, device_category, ' '.join(list(short_display_to_check))))\n\nclass NameMixin:\n def get_camel_case_name(self):\n raise NotImplementedError()\n\n def get_underscore_name(self):\n raise NotImplementedError()\n\n def get_headless_camel_case_name(self):\n return make_headless_camel_case(self.get_camel_case_name(), self.get_underscore_name())\n\n def get_upper_case_name(self):\n return self.get_underscore_name().upper()\n\n def get_dash_name(self):\n return self.get_underscore_name().replace('_', '-')\n\nclass Constant(NameMixin):\n def __init__(self, raw_data):\n self.raw_data = raw_data\n\n def get_camel_case_name(self):\n return self.raw_data[0]\n\n def get_underscore_name(self):\n return self.raw_data[1]\n\n def get_value(self):\n return self.raw_data[2]\n\nclass ConstantGroup(NameMixin):\n def __init__(self, element, type, raw_data, generator):\n self.type = type\n self.raw_data = raw_data\n self.elements = [element]\n self.constants = []\n\n for raw_constant in raw_data[2]:\n self.constants.append(generator.get_constant_class()(raw_constant))\n\n def add_elements(self, elements):\n self.elements += elements\n\n def get_camel_case_name(self):\n return self.raw_data[0]\n\n def get_underscore_name(self):\n return self.raw_data[1]\n\n def get_type(self):\n return self.type\n\n def get_constants(self):\n return self.constants\n\n def get_elements(self):\n return self.elements\n\nclass Element:\n def __init__(self, raw_data, packet, device, generator):\n self.raw_data = raw_data\n self.packet = packet\n self.device = device\n self.generator = generator\n self.constant_group = None\n\n if len(self.raw_data) > 4:\n self.constant_group = generator.get_constant_group_class()(self, raw_data[1], raw_data[4], generator)\n\n def get_packet(self):\n return self.packet\n\n def get_device(self):\n return self.device\n\n def get_generator(self):\n return self.generator\n\n def get_underscore_name(self):\n return self.raw_data[0]\n\n def get_headless_camel_case_name(self):\n return underscore_to_headless_camel_case(self.get_underscore_name())\n\n def get_dash_name(self):\n return self.get_underscore_name().replace('_', '-')\n\n def get_type(self):\n return self.raw_data[1]\n\n def get_cardinality(self):\n return self.raw_data[2]\n\n def get_direction(self):\n return self.raw_data[3]\n\n def get_constant_group(self):\n return self.constant_group\n\n def get_item_size(self):\n item_sizes = {\n 'int8': 1,\n 'uint8': 1,\n 'int16': 2,\n 'uint16': 2,\n 'int32': 4,\n 'uint32': 4,\n 'int64': 8,\n 'uint64': 8,\n 'float': 4,\n 'bool': 1,\n 'char': 1,\n 'string': 1\n }\n\n return item_sizes[self.get_type()]\n\n def get_size(self):\n return self.get_item_size() * self.get_cardinality()\n\nclass Packet(NameMixin):\n valid_types = set(['int8',\n 'uint8',\n 'int16',\n 'uint16',\n 'int32',\n 'uint32',\n 'int64',\n 'uint64',\n 'float',\n 'bool',\n 'char',\n 'string'])\n\n def __init__(self, raw_data, device, generator):\n self.raw_data = raw_data\n self.device = device\n self.generator = generator\n self.all_elements = []\n self.in_elements = []\n self.out_elements = []\n\n check_name(raw_data['name'][0], raw_data['name'][1])\n\n for raw_element in self.raw_data['elements']:\n element = generator.get_element_class()(raw_element, self, device, generator)\n\n self.all_elements.append(element)\n\n check_name(None, element.get_underscore_name())\n\n if element.get_type() not in Packet.valid_types:\n raise ValueError('Invalid element type ' + element.get_type())\n\n if element.get_cardinality() < 1:\n raise ValueError('Invalid element size ' + element.get_cardinality())\n\n if element.get_direction() == 'in':\n self.in_elements.append(element)\n elif element.get_direction() == 'out':\n self.out_elements.append(element)\n else:\n raise ValueError('Invalid element direction ' + element.get_direction())\n\n constant_group = element.get_constant_group()\n\n if constant_group is not None:\n check_name(constant_group.get_camel_case_name(), constant_group.get_underscore_name())\n\n for constant in constant_group.get_constants():\n check_name(constant.get_camel_case_name(), constant.get_underscore_name(), is_constant=True)\n\n self.constant_groups = []\n\n for element in self.all_elements:\n constant_group = element.get_constant_group()\n\n if constant_group is None:\n continue\n\n for known_constant_group in self.constant_groups:\n if constant_group.get_underscore_name() != known_constant_group.get_underscore_name():\n continue\n\n if constant_group.get_type() != known_constant_group.get_type():\n raise ValueError('Multiple instance of constant group {0} with different types'.format(constant_group.get_underscore_name()))\n\n for constant, known_constant in zip(constant_group.get_constants(), known_constant_group.get_constants()):\n a = known_constant.get_underscore_name()\n b = constant.get_underscore_name()\n\n if a != b:\n raise ValueError('Constant item name ({0} != {1}) mismatch in constant group {2}'.format(a, b, constant_group.get_underscore_name()))\n\n a = known_constant.get_value()\n b = constant.get_value()\n\n if a != b:\n raise ValueError('Constant item value ({0} != {1}) mismatch in constant group {2}'.format(a, b, constant_group.get_underscore_name()))\n\n known_constant_group.add_elements(constant_group.get_elements())\n\n constant_group = None\n\n break\n\n if constant_group is not None:\n self.constant_groups.append(constant_group)\n\n def get_device(self):\n return self.device\n\n def get_generator(self):\n return self.generator\n\n def get_type(self):\n return self.raw_data['type']\n\n def get_camel_case_name(self):\n return self.raw_data['name'][0]\n\n def get_underscore_name(self):\n return self.raw_data['name'][1]\n\n def get_elements(self, direction=None):\n if direction is None:\n return self.all_elements\n elif direction == 'in':\n return self.in_elements\n elif direction == 'out':\n return self.out_elements\n else:\n raise ValueError('Invalid element direction ' + str(direction))\n\n def get_since_firmware(self):\n return self.raw_data['since_firmware']\n\n def get_doc(self):\n return self.raw_data['doc']\n\n def get_doc_substitutions(self):\n doc = self.get_doc()\n\n if len(doc) < 3:\n return []\n\n if lang in doc[2]:\n subsitutions = doc[2][lang]\n else:\n subsitutions = doc[2]['*']\n\n filtered_subsitutions = {}\n bindings_name = self.get_generator().get_bindings_name()\n\n for key, value in subsitutions.items():\n if bindings_name in value:\n filtered_subsitutions[key] = value[bindings_name]\n else:\n filtered_subsitutions[key] = value['*']\n\n return filtered_subsitutions\n\n def get_function_id(self):\n return self.raw_data['function_id']\n\n def get_request_size(self):\n size = 8 # header\n for element in self.in_elements:\n size += element.get_size()\n return size\n\n def get_response_size(self):\n size = 8 # header\n for element in self.out_elements:\n size += element.get_size()\n return size\n\n def get_constant_groups(self):\n return self.constant_groups\n\n def get_formatted_constants(self, constant_format, char_format=\"'{0}'\", **extra_value):\n constants = []\n\n for constant_group in self.get_constant_groups():\n for constant in constant_group.get_constants():\n if constant_group.get_type() == 'char':\n value = char_format.format(constant.get_value())\n else:\n value = str(constant.get_value())\n\n constants.append(constant_format.format(constant_group_upper_case_name=constant_group.get_upper_case_name(),\n constant_upper_case_name=constant.get_upper_case_name(),\n constant_value=value,\n **extra_value))\n\n return ''.join(constants)\n\n def has_prototype_in_device(self):\n if 'prototype_in_device' in self.raw_data:\n if self.raw_data['prototype_in_device']:\n return True\n return False\n\n def is_virtual(self):\n if 'is_virtual' in self.raw_data:\n if self.raw_data['is_virtual']:\n return True\n return False\n\nclass Device(NameMixin):\n def __init__(self, raw_data, generator):\n self.raw_data = raw_data\n self.generator = generator\n self.all_packets = []\n self.all_packets_without_doc_only = []\n self.all_function_packets = []\n self.all_function_packets_without_doc_only = []\n self.callback_packets = []\n\n check_name(raw_data['name'][0], raw_data['name'][1], raw_data['name'][2], raw_data['name'][3], device_category=raw_data['category'])\n\n for i, raw_packet in zip(range(len(raw_data['packets'])), raw_data['packets']):\n if not 'function_id' in raw_packet:\n raw_packet['function_id'] = i + 1\n\n packet = generator.get_packet_class()(raw_packet, self, generator)\n\n self.all_packets.append(packet)\n\n if packet.get_function_id() >= 0:\n self.all_packets_without_doc_only.append(packet)\n\n for packet in self.all_packets:\n if packet.get_type() == 'function':\n self.all_function_packets.append(packet)\n\n if packet.get_function_id() >= 0:\n self.all_function_packets_without_doc_only.append(packet)\n elif packet.get_type() == 'callback':\n self.callback_packets.append(packet)\n else:\n raise ValueError('Invalid packet type ' + packet.get_type())\n\n self.constant_groups = []\n\n for packet in self.all_packets:\n for constant_group in packet.get_constant_groups():\n for known_constant_group in self.constant_groups:\n if constant_group.get_underscore_name() != known_constant_group.get_underscore_name():\n continue\n\n if constant_group.get_type() != known_constant_group.get_type():\n raise ValueError('Multiple instance of constant group {0} with different types'.format(constant_group.get_underscore_name()))\n\n for constant, known_constant in zip(constant_group.get_constants(), known_constant_group.get_constants()):\n a = known_constant.get_underscore_name()\n b = constant.get_underscore_name()\n\n if a != b:\n raise ValueError('Constant item name ({0} != {1}) mismatch in constant group {2}'.format(a, b, constant_group.get_underscore_name()))\n\n a = known_constant.get_value()\n b = constant.get_value()\n\n if a != b:\n raise ValueError('Constant item value ({0} != {1}) mismatch in constant group {2}'.format(a, b, constant_group.get_underscore_name()))\n\n constant_group = None\n break\n\n if constant_group != None:\n self.constant_groups.append(constant_group)\n\n def get_generator(self):\n return self.generator\n\n def is_released(self):\n return self.raw_data['released']\n\n def get_api_version(self):\n return self.raw_data['api_version']\n\n def get_api_doc(self):\n if 'api' in self.raw_data:\n return select_lang(self.raw_data['api'])\n else:\n return ''\n\n def get_camel_case_category(self):\n return self.raw_data['category']\n\n def get_underscore_category(self):\n return self.raw_data['category'].lower()\n\n def get_upper_case_category(self):\n return self.get_underscore_category().upper()\n\n def get_dash_category(self):\n return self.get_underscore_category().replace('_', '-')\n\n def get_device_identifier(self):\n return self.raw_data['device_identifier']\n\n def get_camel_case_name(self):\n return self.raw_data['name'][0]\n\n def get_underscore_name(self):\n return self.raw_data['name'][1]\n\n def get_short_display_name(self):\n return self.raw_data['name'][2]\n\n def get_long_display_name(self):\n return self.raw_data['name'][3]\n\n def get_description(self, language='en'):\n return self.raw_data['description'][language]\n\n def get_git_directory(self):\n global_root_directory = os.path.normpath(os.path.join(self.get_generator().get_bindings_root_directory(), '..', '..'))\n git_name = self.get_dash_name() + '-' + self.get_dash_category()\n git_directory = os.path.join(global_root_directory, git_name)\n\n return git_directory\n\n def get_packets(self, type=None):\n if type is None:\n if self.generator.is_doc():\n return self.all_packets\n else:\n return self.all_packets_without_doc_only\n elif type == 'function':\n if self.generator.is_doc():\n return self.all_function_packets\n else:\n return self.all_function_packets_without_doc_only\n elif type == 'callback':\n return self.callback_packets\n else:\n raise ValueError('Invalid packet type ' + str(type))\n\n def get_callback_count(self):\n return len(self.callback_packets)\n\n def get_constant_groups(self):\n return self.constant_groups\n\n def get_formatted_constants(self, constant_format, char_format=\"'{0}'\", **extra_value):\n constants = []\n\n for constant_group in self.get_constant_groups():\n for constant in constant_group.get_constants():\n if constant_group.get_type() == 'char':\n value = char_format.format(constant.get_value())\n else:\n value = str(constant.get_value())\n\n constants.append(constant_format.format(constant_group_upper_case_name=constant_group.get_upper_case_name(),\n constant_group_camel_case_name=constant_group.get_camel_case_name(),\n constant_upper_case_name=constant.get_upper_case_name(),\n constant_camel_case_name=constant.get_camel_case_name(),\n constant_value=value,\n **extra_value))\n\n return ''.join(constants)\n\n def get_doc_rst_path(self):\n if not self.get_generator().is_doc():\n raise Exception(\"Invalid call in non-doc generator\")\n\n filename = '{0}_{1}_{2}.rst'.format(self.get_camel_case_name(),\n self.get_camel_case_category(),\n self.get_generator().get_doc_rst_filename_part())\n\n return os.path.join(self.get_generator().get_bindings_root_directory(),\n 'doc',\n self.get_generator().get_language(),\n filename)\n\n def get_doc_rst_ref_name(self):\n if not self.get_generator().is_doc():\n raise Exception(\"Invalid call in non-doc generator\")\n\n return self.get_underscore_name() + '_' + self.get_underscore_category()\n\nclass Generator:\n def __init__(self, bindings_root_directory, language):\n self.bindings_root_directory = bindings_root_directory\n self.language = language # en or de\n\n def get_bindings_name(self):\n raise Exception(\"get_bindings_name() not implemented\")\n\n def get_bindings_display_name(self):\n raise Exception(\"get_bindings_display_name() not implemented\")\n\n def get_device_class(self):\n return Device\n\n def get_packet_class(self):\n return Packet\n\n def get_element_class(self):\n return Element\n\n def get_constant_group_class(self):\n return ConstantGroup\n\n def get_constant_class(self):\n return Constant\n\n def get_bindings_root_directory(self):\n return self.bindings_root_directory\n\n def get_language(self):\n return self.language # en or de\n\n def is_doc(self):\n return False\n\n def compare_examples(self, example1, example2):\n return cmp(example1[2], example2[2])\n\n def prepare(self):\n pass\n\n def generate(self, device):\n raise Exception(\"generate() not implemented\")\n\n def finish(self):\n pass\n\nclass DocGenerator(Generator):\n def __init__(self, *args, **kwargs):\n Generator.__init__(self, *args, **kwargs)\n\n if self.get_bindings_name() != self.get_doc_rst_filename_part().lower():\n raise Exception(\"bindings name '{0}' and doc rst name '{1}' do not match\".format(self.get_bindings_name(), self.get_doc_rst_filename_part()))\n\n def get_doc_rst_filename_part(self):\n raise Exception(\"get_doc_rst_filename_part() not implemented\")\n\n def get_doc_example_regex(self):\n raise Exception(\"get_doc_example_regex() not implemented\")\n\n def is_doc(self):\n return True\n\n def prepare(self):\n recreate_directory(os.path.join(self.get_bindings_root_directory(), 'doc', self.get_language()))\n\n def finish(self):\n # Copy IPConnection examples\n example_regex = self.get_doc_example_regex()\n\n if example_regex is not None:\n print(' * ip_connection')\n\n examples = find_examples(self.get_bindings_root_directory(), example_regex, self.compare_examples)\n copy_files = []\n\n for example in examples:\n include = 'IPConnection_{0}_{1}'.format(self.get_doc_rst_filename_part(), example[0].replace(' ', '_'))\n copy_files.append((example[1], include))\n\n copy_examples(copy_files, self.get_bindings_root_directory())\n\nclass BindingsGenerator(Generator):\n released_files_name_prefix = None\n bindings_subdirectory_name = 'bindings'\n check_directory_name = True\n\n def __init__(self, *args, **kwargs):\n Generator.__init__(self, *args, **kwargs)\n\n directory = os.path.split(self.get_bindings_root_directory())[1]\n\n if self.check_directory_name and self.get_bindings_name() != directory:\n raise Exception(\"bindings root directory '{0}' and bindings name '{1}' do not match\".format(directory, self.get_bindings_name()))\n\n self.released_files = []\n\n def prepare(self):\n recreate_directory(os.path.join(self.get_bindings_root_directory(), self.bindings_subdirectory_name))\n\n def finish(self):\n if self.released_files_name_prefix is None:\n if len(self.released_files) > 0:\n raise Exception(\"Released files in list but name prefix not set\")\n else:\n py = open(os.path.join(self.get_bindings_root_directory(), self.released_files_name_prefix + '_released_files.py'), 'wb')\n py.write('released_files = ' + repr(self.released_files))\n py.close()\n\ndef examples_tester_worker(cookie, args, env):\n try:\n with open(os.devnull) as DEVNULL:\n output = subprocess.check_output(args, env=env, stderr=subprocess.STDOUT, stdin=DEVNULL)\n except subprocess.CalledProcessError as e:\n return cookie, e.output, e.returncode == 0\n\n return cookie, output, True\n\nclass ExamplesTester:\n PROCESSES = 4\n\n def __init__(self, name, extension, path, subdirs=['examples'], comment=None, extra_examples=[]):\n version = get_changelog_version(path)\n\n self.name = name\n self.extension = extension\n self.path = path\n self.subdirs = subdirs[:]\n self.comment = comment\n self.extra_examples = extra_examples[:]\n self.zipname = 'tinkerforge_{0}_bindings_{1}_{2}_{3}.zip'.format(name, *version)\n self.test_count = 0\n self.success_count = 0\n self.failure_count = 0\n self.pool = multiprocessing.dummy.Pool(processes=self.PROCESSES)\n\n def walker(self, arg, dirname, names):\n for name in names:\n if not name.endswith(self.extension):\n continue\n\n self.handle_source(os.path.join(dirname, name), False)\n\n def execute(self, cookie, args, env=None):\n def callback(result):\n self.handle_result(*result)\n\n self.pool.apply_async(examples_tester_worker, args=(cookie, args, env),\n callback=callback)\n\n def handle_source(self, src, is_extra_example):\n self.test_count += 1\n self.test((src,), src, is_extra_example)\n\n def handle_result(self, cookie, output, success):\n src = cookie[0]\n\n if self.comment != None:\n print('>>> [{0}] testing {1}'.format(self.comment, src))\n else:\n print('>>> testing {0}'.format(src))\n\n output = output.strip()\n\n if len(output) > 0:\n print(output)\n\n if success:\n self.success_count += 1\n print('\\033[01;32m>>> test succeded\\033[0m\\n')\n else:\n self.failure_count += 1\n print('\\033[01;31m>>> test failed\\033[0m\\n')\n\n def test(self, cookie, src, is_extra_example):\n raise NotImplementedError()\n\n def run(self):\n tmp_dir = os.path.join('/tmp/tester', self.name)\n\n # Make temporary examples directory\n if os.path.exists(tmp_dir):\n shutil.rmtree(tmp_dir)\n\n os.makedirs(tmp_dir)\n\n with ChangedDirectory(tmp_dir):\n shutil.copy(os.path.join(self.path, self.zipname), tmp_dir)\n\n # unzip\n print('>>> unpacking {0} to {1}'.format(self.zipname, tmp_dir))\n\n args = ['/usr/bin/unzip',\n '-q',\n os.path.join(tmp_dir, self.zipname)]\n\n rc = subprocess.call(args)\n\n if rc != 0:\n print('### could not unpack {0}'.format(self.zipname))\n return False\n\n print('>>> unpacking {0} done\\n'.format(self.zipname))\n\n # test\n for subdir in self.subdirs:\n os.path.walk(os.path.join(tmp_dir, subdir), self.walker, None)\n\n for extra_example in self.extra_examples:\n self.handle_source(extra_example, True)\n\n self.pool.close()\n self.pool.join()\n\n # report\n if self.comment != None:\n print('### [{0}] {1} file(s) tested, {2} test(s) succeded, {3} failure(s) occurred'\n .format(self.comment, self.test_count, self.success_count, self.failure_count))\n else:\n print('### {0} file(s) tested, {1} test(s) succeded, {2} failure(s) occurred'\n .format(self.test_count, self.success_count, self.failure_count))\n\n return self.failure_count == 0\n\nclass SourceTester:\n def __init__(self, name, extension, path, subdirs=['source'], comment=None):\n version = get_changelog_version(path)\n\n self.name = name\n self.extension = extension\n self.path = path\n self.subdirs = subdirs[:]\n self.comment = comment\n self.zipname = 'tinkerforge_{0}_bindings_{1}_{2}_{3}.zip'.format(name, *version)\n self.test_count = 0\n self.failure_count = 0\n\n def walker(self, arg, dirname, names):\n for name in names:\n if not name.endswith(self.extension):\n continue\n\n self.handle_source(os.path.join(dirname, name))\n\n def handle_source(self, src):\n self.test_count += 1\n\n if self.comment is not None:\n print('>>> [{0}] testing {1}'.format(self.comment, src))\n else:\n print('>>> testing {0}'.format(src))\n\n if not self.test(src):\n self.failure_count += 1\n\n print('\\033[01;31m>>> test failed\\033[0m\\n')\n else:\n print('\\033[01;32m>>> test succeded\\033[0m\\n')\n\n def after_unzip(self):\n return True\n\n def test(self, src):\n raise NotImplementedError()\n\n def run(self):\n tmp_dir = os.path.join('/tmp/tester', self.name)\n\n # make temporary examples directory\n if os.path.exists(tmp_dir):\n shutil.rmtree(tmp_dir)\n\n os.makedirs(tmp_dir)\n\n with ChangedDirectory(tmp_dir):\n shutil.copy(os.path.join(self.path, self.zipname), tmp_dir)\n\n # unzip\n print('>>> unpacking {0} to {1}'.format(self.zipname, tmp_dir))\n\n args = ['/usr/bin/unzip',\n '-q',\n os.path.join(tmp_dir, self.zipname)]\n\n rc = subprocess.call(args)\n\n if rc != 0:\n print('### could not unpack {0}'.format(self.zipname))\n return False\n\n print('>>> unpacking {0} done\\n'.format(self.zipname))\n\n if not self.after_unzip():\n return False\n\n # test\n for subdir in self.subdirs:\n os.path.walk(os.path.join(tmp_dir, subdir), self.walker, None)\n\n # report\n if self.comment is not None:\n print('### [{0}] {1} files tested, {2} failure(s) occurred'.format(self.comment, self.test_count, self.failure_count))\n else:\n print('### {0} files tested, {1} failure(s) occurred'.format(self.test_count, self.failure_count))\n\n return self.failure_count == 0\n\n# use \"with ChangedDirectory('/path/to/abc')\" instead of \"os.chdir('/path/to/abc')\"\nclass ChangedDirectory:\n def __init__(self, directory):\n self.directory = directory\n\n def __enter__(self):\n self.previous_directory = os.getcwd()\n os.chdir(self.directory)\n\n def __exit__(self, type, value, traceback):\n os.chdir(self.previous_directory)\n","sub_path":"common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":62729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"43633840","text":"import csv\nfrom math import *\nimport matplotlib\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\n# Qui vanno i dati\ndati = np.genfromtxt(\"../dati/derivator.csv\", delimiter=',')\n\nV1 = 2\nV2 = dati[1:,0]\nPHI = dati[1:,2]\nFREQ = dati[1:,1]\n\n# Creo un grafico la dimensione è in pollici\nf1 = plt.figure(figsize=(8, 8))\n# Titolo del grafico\nf1.suptitle(\"Circuito derivatore\", y=0.98, fontsize=15)\n\n######\n# GRAFICO 1\nax1 = f1.add_subplot(2, 1, 1)\nax1.set_xscale('log')\n\ndb = ax1.errorbar(x=FREQ, #x=np.logspace(70,6E6,500),\n\ty=20*np.log10(V2/V1),\n\tfmt='.:', c='black')\n#gain = ax1.errorbar(x=FREQ,\n#\ty=V2/V1,\n#\tfmt='.', c='black')\n \nax1.set_ylabel(u'Guadagno [$dB$]', labelpad=0, fontsize=14)\n#ax1.set_ylabel(u'Guadagno', labelpad=2, fontsize=14)\n\n#ax1.text(1/(2*pi*(L*C)**(0.5))+1000, -50+1.5, r'$\\nu_0$', size=15, va='center')\n\nax1.grid(True)\n#ax1.set_ylim((-21, 21))\nplt.setp(ax1.get_xticklabels(), visible=False)\n \n######\n# GRAFICO 2 - grafico R-Scarti\nax2 = f1.add_subplot(2, 1, 2, sharex=ax1)\nax2.set_xscale('log')\nfase = ax2.errorbar(x=FREQ, y=PHI,\n fmt='.:', c='black')\n\nax2.set_ylabel(u'Fase [$^\\circ$]', labelpad=0, fontsize=14)\nax2.set_xlabel(u'Frequenza [$Hz$]', labelpad=0, fontsize=14)\n\nax2.set_ylim((-100, 10))\nax2.set_xlim((8,40E3))\nax2.set_yticks(np.arange(-90, 1, 30))\n\nax2.grid(True)\nax2.legend((fase, ), (\"Dati sperimentali\", ), 'upper right', prop={'size': 12})\n \n######\n\n# questo imposta i bordi del grafico\nf1.subplots_adjust(left=0.09, right=0.98, top=0.95, bottom=0.08, hspace=0.05, wspace=0.05)\n# mostra grafico\nplt.show()\n","sub_path":"E11/analisi/der.py","file_name":"der.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"337761451","text":"# Create an empty set named showroom.\r\n# Add four of your favorite car model names to the set.\r\n# Print the length of your set.\r\n# Pick one of the items in your show room and add it to the set again.\r\n# Print your showroom. Notice how there's still only one instance of that model in there.\r\n# Using update(), add two more car models to your showroom with another set.\r\n# You've sold one of your cars. Remove it from the set with the discard() method.\r\n\r\nshowroom = set()\r\nshowroom.add('Prius')\r\nshowroom.add('Fiat')\r\nshowroom.add('Fiesta')\r\nshowroom.add('Model-T')\r\nprint('showroom length', len(showroom))\r\nshowroom.add('Fiesta')\r\nprint('showroom', showroom)\r\nshowroom.update(['Rav-4', 'F-150'])\r\nprint('showroom', showroom)\r\nshowroom.discard('Fiesta')\r\nprint('showroom after selling Fiesta', showroom)\r\nprint('showroom length', len(showroom))\r\n\r\n# Now create another set of cars in a variable junkyard. Someone who owns a junkyard full of old cars has approached you about buying the entire inventory. In the new set, add some different cars, but also add a few that are the same as in the showroom set.\r\n# Use the intersection method to see which cars exist in both the showroom and that junkyard.\r\n# Now you're ready to buy the cars in the junkyard. Use the union method to combine the junkyard into your showroom.\r\n# Use the discard() method to remove any cars that you acquired from the junkyard that you want in your showroom.\r\n\r\njunkyard = {'crap car 1', 'crap car 2', 'crap car 3', 'Fiat'}\r\nprint('Intersection', showroom.intersection(junkyard))\r\ncombined = junkyard.union(showroom)\r\nprint('Union', combined)\r\ncombined.discard('crap car 1')\r\ncombined.discard('crap car 2')\r\nprint('Final', combined)","sub_path":"cars.py","file_name":"cars.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"252716088","text":"import random\nimport pygame\nfrom settings import BrickData\n\nBLACKK = (0, 0, 0)\n\n__color__ = [\n RED, GREEN, BLUE, YELLOW, PURPLE, PINK, LIGHTBLUE, WHITE, BLACK] = [\n (227, 48, 48), (97, 204, 61), (63, 89, 235), (209, 166, 46),\n (151, 66, 255), (230, 34, 230), (29, 219, 197), (227, 209, 209), (40, 40, 40)]\nnColors = len(__color__)\n\nclass Brick(pygame.sprite.Sprite):\n def __init__(self, width=BrickData.sizeX-BrickData.margin, height=BrickData.sizeY-BrickData.margin):\n super().__init__()\n\n self.image = pygame.Surface([width, height])\n self.image.fill(BLACKK)\n self.image.set_colorkey(BLACKK)\n self.color = __color__[random.randint(0, nColors-1)]\n\n pygame.draw.rect(self.image, self.color, [0, 0, width, height])\n\n self.rect = self.image.get_rect()\n\n def pick_random_color(self):\n self.color = __color__[random.randint(0, nColors-1)]\n self.image.fill(self.color)\n","sub_path":"086/brick.py","file_name":"brick.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"416797788","text":"\"\"\"========================================================================================================================\n\nSherlock Holmes is getting paranoid about Professor Moriarty, his archenemy. All his efforts to subdue Moriarty have been in vain. These days Sherlock is working on a problem with Dr. Watson. Watson mentioned that the CIA has been facing weird problems with their supercomputer, 'The Beast', recently.\n\nThis afternoon, Sherlock received a note from Moriarty, saying that he has infected 'The Beast' with a virus. Moreover, the note had the number N printed on it. After doing some calculations, Sherlock figured out that the key to remove the virus is the largest 'Decent' Number having N digits.\n\nA 'Decent' Number has -\n1. Only 3 and 5 as its digits.\n2. Number of times 3 appears is divisible by 5.\n3. Number of times 5 appears is divisible by 3.\n\nMeanwhile, the counter to destruction of 'The Beast' is running very fast. Can you save 'The Beast', and find the key before Sherlock?\n\nInput Format\nThe 1st line will contain an integer T, the number of test cases, followed by T lines, each line containing an integer N i.e. the number of digits in the number \n\nOutput Format\nLargest Decent number having N digits. If no such number exists, tell Sherlock that he is wrong and print '-1' \n\nConstraints\n1<=T<=20\n1<=N<=100000\n\n\nSample Input\n\n4\n1\n3\n5\n11\nSample Output\n\n-1\n555\n33333\n55555533333\nExplanation\nFor N=1 , there is no such number. \nFor N=3, 555 is only possible number.\nFor N=5, 33333 is only possible number.\nFor N=11 , 55555533333 and all of permutations of digits are valid numbers, among them, the given number is the largest one.\n\n========================================================================================================================\"\"\"\n\ndef decent_number(num):\n indecent = [1,2,4,7]\n if num in indecent:\n return -1\n else:\n if num % 5 == 0 and num % 3 == 0:\n return num * \"5\"\n elif num % 3 == 0:\n return num * \"5\"\n else:\n for i in range(num/3):\n if ((num % 3) + (3 * i)) % 5 == 0:\n answer = (num - ((num % 3) + (3 * i))) * \"5\" + (((num % 3) + (3 * i)) * \"3\")\n break\n else:\n answer = num * \"3\"\n return answer\n \n \n \n \ndef main():\n cases = raw_input()\n for i in range(int(cases)):\n print(decent_number(int(raw_input())))\n\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"sherlockAndTheBeast.py","file_name":"sherlockAndTheBeast.py","file_ext":"py","file_size_in_byte":2529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"613312042","text":"from typing import List, Iterator\nfrom unittest import mock\nimport pytest\n\nfrom openeo_driver.dry_run import SourceConstraint\nfrom openeo_driver.testing import ApiTester\nfrom .data import get_path, TEST_DATA_ROOT, load_json\n\n\n@pytest.fixture\ndef api100(client) -> ApiTester:\n data_root = TEST_DATA_ROOT / \"pg\" / \"1.0\"\n return ApiTester(api_version=\"1.0.0\", client=client, data_root=data_root)\n\n\ndef test_basic_ok(api100):\n pg = {\"add\": {\"process_id\": \"add\", \"arguments\": {\"x\": 3, \"y\": 5}, \"result\": True}}\n res = api100.validation(pg)\n assert res.json == {\"errors\": []}\n\n\n@pytest.mark.parametrize([\"pg\", \"expected_code\", \"expected_message\"], [\n ({}, \"ProcessGraphInvalid\", \"No result node in process graph: {}\"),\n (\n {\"add\": {\"process_id\": \"fluxbormav\", \"arguments\": {\"x\": 3, \"y\": 5}, \"result\": True}},\n \"ProcessUnsupported\",\n \"Process with identifier 'fluxbormav' is not available in namespace 'backend'.\",\n ),\n (\n {\"lc\": {\"process_id\": \"load_collection\", \"arguments\": {\"id\": \"flehmeh\"}, \"result\": True}},\n \"CollectionNotFound\", \"Collection 'flehmeh' does not exist.\"\n )\n])\ndef test_basic_fail(api100, pg, expected_code, expected_message):\n res = api100.validation(pg)\n errors = res.json[\"errors\"]\n assert errors == [{\"code\": expected_code, \"message\": expected_message}]\n\n\ndef test_load_collection_basic(api100, backend_implementation):\n pg = {\n \"lc\": {\n \"process_id\": \"load_collection\",\n \"arguments\": {\n \"id\": \"S2_FOOBAR\",\n \"spatial_extent\": {\"west\": 1, \"east\": 2, \"south\": 3, \"north\": 4},\n \"temporal_extent\": [\"2021-02-01\", \"2021-02-20\"],\n },\n \"result\": True,\n }\n }\n res = api100.validation(pg)\n errors = res.json[\"errors\"]\n assert errors == [{\"code\": \"MissingProduct\", \"message\": \"Tile 4322 not available\"}]\n","sub_path":"tests/test_views_validation.py","file_name":"test_views_validation.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"197920234","text":"from aiohttp import web\nfrom marshmallow import Schema, fields, post_load\n\nfrom src.db.models.Team import Team\n\nclass TeamSchema(Schema):\n id = fields.Int()\n name = fields.Str()\n nationality = fields.Str()\n\n @post_load\n def make_team(self, data, **kwargs):\n return Team(**data)\n\n","sub_path":"src/serializers/team.py","file_name":"team.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"19348455","text":"from django.test import TestCase\n\nfrom portfolios.markowitz_scale import get_risk_curve, _to_lambda, _to_risk_score\n\n\nclass MarkowitzScaleTest(TestCase):\n\n def test_get_risk_curve_under(self):\n \"\"\"\n The params we get from get_risk_curve should get us the right lambdas when fed back in.\n \"\"\"\n a, b, c = get_risk_curve(0, 0.711)\n\n # We know from above our min lambda should be 0 and max 0.711\n self.assertAlmostEqual(_to_lambda(0, a, b, c), 0, 6)\n self.assertAlmostEqual(_to_lambda(1, a, b, c), 0.71100, 5)\n\n # test the return trip\n lam = _to_lambda(0.7, a, b, c)\n self.assertAlmostEqual(_to_risk_score(lam, a, b, c), 0.7, 5)\n\n def test_get_risk_curve_over(self):\n a, b, c = get_risk_curve(0.03, 12.711)\n\n self.assertAlmostEqual(_to_lambda(0, a, b, c), 0.03, 5)\n # as the avg is over 1.2, we use 1.2 for the midpoint.\n self.assertAlmostEqual(_to_lambda(0.5, a, b, c), 1.2, 5)\n\n # test the return trip\n lam = _to_lambda(0.2, a, b, c)\n self.assertAlmostEqual(_to_risk_score(lam, a, b, c), 0.2, 5)\n","sub_path":"portfolios/tests/test_markowitz_scale.py","file_name":"test_markowitz_scale.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"262835011","text":"import sys\r\n\r\nfrom GameObject import GameObject\r\nfrom Constants import GameConstants\r\nimport pygame, random, math\r\n\r\n\r\nclass Ball(GameObject):\r\n def __init__(self, position, sprite, game):\r\n super().__init__(position, GameConstants.BALL_SIZE, sprite)\r\n\r\n self.__game = game\r\n self.__speed = 50\r\n self.__increment = [4, 4]\r\n self.__direction = [1, 1]\r\n self.bounce_direction = 0\r\n self.__inMotion = False\r\n self.__sprite = sprite\r\n\r\n def set_speed(self, newSpeed):\r\n self.__speed = newSpeed\r\n\r\n def reset_speed(self):\r\n self.__speed = 3\r\n\r\n def get_speed(self):\r\n return self.__speed\r\n\r\n def set_direction(self, new_dir):\r\n self.__direction[0] = new_dir[0]\r\n self.__direction[1] = new_dir[1]\r\n\r\n def is_in_motion(self):\r\n return self.__inMotion\r\n\r\n def set_motion(self, isMoving):\r\n self.__inMotion = isMoving\r\n self.reset_speed()\r\n\r\n def change_direction(self, other):\r\n position = self.get_position()\r\n size = self.get_size()\r\n\r\n other_position = other.get_position()\r\n other_size = other.get_size()\r\n new_position = []\r\n\r\n if position[0] > other_position[0] - GameConstants.BALL_SIZE[0] / 2 and \\\r\n position[0] + size[0] <= other_position[0] + other_size[0] + GameConstants.BALL_SIZE[\r\n 0] / 2 and \\\r\n position[1] > other_position[1]:\r\n new_position.append(position[0])\r\n new_position.append(other_position[1] + other_size[1])\r\n self.__direction[1] *= -1\r\n\r\n elif position[0] > other_position[0] and position[0] + size[0] <= other_position[0] + other_size[0] and \\\r\n position[1] + size[1] >= other_position[1]:\r\n new_position.append(position[0])\r\n new_position.append(other_position[1] - size[1])\r\n self.__direction[1] *= -1\r\n\r\n elif position[0] + size[0] >= other_position[0] and position[0] + size[0] < other_position[0] + other_size[0] \\\r\n and (position[1] + size[1] > other_position[1]):\r\n self.__direction[0] *= -1\r\n new_position.append(other_position[0] - size[0])\r\n new_position.append(position[1])\r\n\r\n else:\r\n self.__direction[0] *= -1\r\n new_position.append(other_position[0] + other_size[0])\r\n new_position.append(position[1])\r\n\r\n # debug\r\n if new_position[0] < 0:\r\n new_position[0] = 0\r\n elif new_position[0] + self.get_size()[0] > GameConstants.SCREEN_SIZE[0]:\r\n new_position[0] = GameConstants.SCREEN_SIZE[0] - self.get_size()[0]\r\n elif new_position[1] < 0:\r\n new_position[1] = 1\r\n\r\n self.__speed += (0.1 / 2)\r\n self.set_position(new_position)\r\n\r\n def update_position(self):\r\n\r\n new_pos = [self.get_position()[0] + (self.__direction[0] * self.__speed * -math.sin(self.bounce_direction)),\r\n self.get_position()[1] + (self.__direction[1] * self.__speed * math.cos(self.bounce_direction))]\r\n\r\n if new_pos[0] + self.get_size()[0] > GameConstants.SCREEN_SIZE[0]:\r\n self.__direction[0] *= -1\r\n\r\n elif new_pos[0] < 0:\r\n self.__direction[0] *= -1\r\n\r\n ##LOSE BALL\r\n elif new_pos[1] + self.get_size()[1] > GameConstants.SCREEN_SIZE[1] + 50:\r\n self.__game.play_sound(3)\r\n self.set_motion(False)\r\n self.__game.reduce_lives()\r\n\r\n elif new_pos[1] < 0:\r\n self.__direction[1] *= -1\r\n\r\n self.set_position(new_pos)\r\n\r\n def is_ball_dead(self):\r\n pass\r\n\r\n def bounce_of_pad(self, pad):\r\n self.__direction[1] *= -1\r\n self.set_position((\r\n self.get_position()[0],\r\n pad.get_position()[1] - self.get_size()[1]\r\n ))\r\n\r\n hitting_point = self.get_position()[0] + self.get_size()[0] / 2\r\n pad_mid_point = pad.get_position()[0] + pad.get_size()[0] / 2\r\n diff = pad_mid_point - hitting_point\r\n\r\n diff /= (pad.get_size()[0] / 2)\r\n\r\n angle_to_bounce = (5 * math.pi / 12) * diff\r\n\r\n self.bounce_direction = angle_to_bounce\r\n\r\n self.__direction[0] = 1\r\n self.__speed += 0.5\r\n","sub_path":"Ball.py","file_name":"Ball.py","file_ext":"py","file_size_in_byte":4329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"458436300","text":"#!/usr/bin/env python\n#\n# Copyright 2007 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\n# Code presented here is a combination of \n# both self-written code and solution-provided code from Udacity\nimport webapp2\nimport re\nimport hmac\nimport get_template\n\nfrom comment import Comment\nfrom user import User\nfrom post import Post\nfrom post import Like\nfrom string import letters\n\nfrom google.appengine.ext import db \n\n\nsecret = 'j!)wS3Lms7eMh%5T*}9C2X6QANo-:5'\n\n### This is for cookie validation, using hmac ###\n# This function returns the hashed value in the format 'val|h(val)'\ndef make_secure_val(val):\n\treturn '%s|%s' % (val, hmac.new(secret, val).hexdigest())\n\ndef check_secure_val(secure_val):\n\t# Takes val from 'val|h(val)' format and stores into val\n\tval = secure_val.split('|')[0]\n\t# If hashed format == make_secure_val(val)...\n\tif secure_val == make_secure_val(val):\n\t\treturn val\n\n# For validating log in\nUSER_RE = re.compile(r\"^[a-zA-Z0-9_-]{3,20}$\")\ndef valid_username(username):\n return username and USER_RE.match(username)\n\nPASS_RE = re.compile(r\"^.{3,20}$\")\ndef valid_password(password):\n return password and PASS_RE.match(password)\n\nEMAIL_RE = re.compile(r'^[\\S]+@[\\S]+\\.[\\S]+$')\ndef valid_email(email):\n return not email or EMAIL_RE.match(email)\n\nclass BlogHandler(webapp2.RequestHandler):\n\tdef write(self, *a, **kw):\n\t\tself.response.out.write(*a, **kw)\n\n\tdef render_str(self, template, **params):\n\t\t#defined globally so it can be used by other classes\n\t\t#this render_str calls the global function render_str\n\t\tparams['user'] = self.user\n\t\treturn get_template.render_str(template, **params)\n\n\tdef render(self, template, **kw):\n\t\tself.write(self.render_str(template, **kw))\n\n# Stores cookie with name, hashed val\n\tdef set_secure_cookie(self, name, val):\n\t\tcookie_val = make_secure_val(val)\n\t\tself.response.headers.add_header('Set-Cookie', '%s=%s; Path=/' % (name, cookie_val))\n\n\tdef read_secure_cookie(self, name):\n\t\tcookie_val = self.request.cookies.get(name)\n\t\t# Return cookie_val if cookie_val check_secure_val(cookie_val) is true\n\t\treturn cookie_val and check_secure_val(cookie_val)\n\n\tdef login(self, user):\n\t\tself.set_secure_cookie('user_id', str(user.key().id()))\n\n\tdef logout(self):\n\t\tself.response.headers.add_header('Set-Cookie', 'user_id=; Path=/')\n\n# This function checks to see if user is logged in or not per each request\n\tdef initialize(self, *a, **kw):\n\t\twebapp2.RequestHandler.initialize(self, *a, **kw)\n\t\tuid = self.read_secure_cookie('user_id')\n\t\tself.user = uid and User.by_id(int(uid))\n\n\nclass Signup(BlogHandler):\n\tdef get(self):\n\t\tself.render(\"signup.html\")\n\n\tdef post(self):\n\t\terror = False\n\t\tself.username = self.request.get('username')\n\t\tself.password = self.request.get('password')\n\t\tself.verify = self.request.get('verify')\n\t\tself.email = self.request.get('email')\n\n\t\t# Sets params, username and email to re-render if an error occurs\n\n\t\tparams = dict(username = self.username, email = self.email)\n\n\t\tif not valid_username(self.username):\n\t\t\tparams['error_username'] = \"Username not valid.\"\n\t\t\terror = True\n\n\t\tif not valid_password(self.password):\n\t\t\tparams['error_password'] = \"Password not valid.\"\n\t\t\terror = True\n\t\telif self.password != self.verify:\n\t\t\tparams['error_verify'] = \"Password does not match.\"\n\t\t\terror = True\n\n\t\tif not valid_email(self.email):\n\t\t\tparams['error_email'] = \"Email is not valid.\"\n\t\t\terror = True\n\n\t\t# If there is an error, render the page again with params included\n\n\t\tif error:\n\t\t\tself.render('signup.html', **params)\n\t\telse:\n\t\t\tself.done()\n\n\tdef done(self, *a, **kw):\n\t\traise NotImplementedError\n\n# This class inherits from parent Signup class\nclass Register(Signup):\n\tdef done(self):\n\t\t# This makes sure user does not already exist in db\n\t\tu = User.by_name(self.username)\n\t\tif u:\n\t\t\tmessage = \"User already exists.\"\n\t\t\tself.render('signup.html', error_username = message)\n\t\telse:\n\t\t\t# Creates the object and stores in database\n\t\t\tu = User.register(self.username, self.password, self.email)\n\t\t\tu.put()\n\t\t\tself.login(u)\n\t\t\t#redirects to welcome page\n\t\t\tself.redirect('/welcome')\n\nclass Welcome(BlogHandler):\n\tdef get(self):\n\t\t# If self.user exists, render welcome page + user of person\n\t\t# otherwise, redirect to signup page\n\t\tif self.user:\n\t\t\tself.render('welcome.html', username = self.user.name)\n\t\telse:\n\t\t\tself.redirect('/signup')\n\nclass Login(BlogHandler):\n\tdef get(self):\n\t\tself.render('login.html')\n\n\tdef post(self):\n\t\tusername = self.request.get('username')\n\t\tpassword = self.request.get('password')\n\n\t\t# Calls login method specific to class User\n\n\n\t\tu = User.login(username, password)\n\t\tif u:\n\t\t\t# Calls global function login\n\t\t\tself.login(u)\n\t\t\tself.redirect('/welcome')\n\t\telse:\n\t\t\tmessage = \"Invalid login\"\n\t\t\tself.render('login.html', error = message)\n\nclass Logout(BlogHandler):\n\tdef get(self):\n\t\tself.logout()\n\t\tself.redirect('/')\n\n\n# Below here contains functions and classes for the blog\n\n# Organizes data\ndef blog_key(name = 'default'):\n\treturn db.Key.from_path('blogs', name)\n\n\n# This handles the front page which displays 10 latest posts\nclass BlogFront(BlogHandler):\n\tdef get(self):\n\t\tdel_post_id = self.request.get('del_post_id')\n\t\tposts = db.GqlQuery(\"SELECT * FROM Post ORDER BY created DESC LIMIT 10\")\n\t\tself.render('front.html', posts = posts)\n\n# This handles the permalink page\nclass PostPage(BlogHandler):\n\tdef get(self, post_id):\n\t\tkey = db.Key.from_path('Post', int(post_id), parent=blog_key())\n\t\tpost = db.get(key)\n\n\t\tcomments = db.GqlQuery(\"SELECT * FROM Comment WHERE post_id=\" + post_id + \" ORDER BY created DESC\")\n\n\t\tlikes = db.GqlQuery(\"SELECT * FROM Like WHERE post_id=\" + post_id)\n\n\t\tif not post:\n\t\t\tself.error(404)\n\t\t\treturn\n\n\t\tself.render(\"permalink.html\", post=post, numLikes=likes.count(), comments=comments)\n\n\tdef post(self, post_id):\n\t\tkey = db.Key.from_path('Post', int(post_id), parent=blog_key())\n\t\tpost = db.get(key)\n\n\t\tif not post:\n\t\t\tself.error(404)\n\t\t\treturn\n\n\t\tc = \"this needs to be a string\"\n\n\t\t# If user is logged in\n\t\tif self.user:\n\t\t\tif self.request.get('like') and self.request.get('like') == \"update\":\n\t\t\t\tlikes = db.GqlQuery(\"SELECT * FROM Like WHERE post_id=\" + post_id + \" AND user_id=\" + str(self.user.key().id()))\n\t\t\t\t# If user = creator of post, don't allow user to like post\n\t\t\t\tif self.user.key().id() == post.user_id:\n\t\t\t\t\tself.redirect('/'+post_id+\"?error=You are not allowed to like your own post.\")\n\t\t\t\telif likes.count() == 0:\n\t\t\t\t\tl = Like(parent = blog_key(), user_id = self.user.key().id(), post_id = int(post_id))\n\t\t\t\t\tl.put()\n\n\t\t\tif self.request.get('comment'):\n\t\t\t\tc = Comment(parent = blog_key(), user_id=self.user.key().id(), post_id = int(post_id), comment = self.request.get('comment'))\n\t\t\t\tc.put()\n\t\telse:\n\t\t\tself.redirect('/login?error=Log in before performing tasks')\n\n\t\tcomments = db.GqlQuery(\"SELECT * FROM Comment WHERE post_id =\" + post_id + \"ORDER BY created DESC\")\n\n\t\tlikes = db.GqlQuery(\"SELECT * FROM Like WHERE post_id=\" + post_id)\n\n\t\tself.render(\"permalink.html\", post=post, comments=comments, numLikes=likes.count(),new=c)\n\n\n# This handles the page to submit a new post\nclass NewPost(BlogHandler):\n\tdef get(self):\n\t\tif self.user:\n\t\t\tself.render(\"newpost.html\")\n\t\telse:\n\t\t\tself.redirect('/login?errormsg=Log in before performing actions')\n\n\tdef post(self):\n\t\tif not self.user:\n\t\t\tself.redirect('/login?errormsg=Log in before performing actions')\n\n\t\tsubject = self.request.get('subject')\n\t\tcontent = self.request.get('content')\n\n\t\tif subject and content:\n\t\t\t# If subject and content exists, create Post object and store into db\n\t\t\tp = Post(parent = blog_key(), subject=subject, content=content, user_id=self.user.key().id())\n\t\t\tp.put()\n\t\t\t# Redirects to page /objectid which shows the post itself after submission\n\t\t\tself.redirect('/%s' % str(p.key().id()))\n\t\telse:\n\t\t\terror = \"There has to be a subject and content\"\n\t\t\t# re-renders form with subject and content still in input boxes + error msg\n\t\t\tself.render(\"newpost.html\", subject=subject, content=content, error=error)\n\nclass DeletePost(BlogHandler):\n\tdef get(self, post_id):\n\t\tif self.user:\n\t\t\tkey = db.Key.from_path('Post', int(post_id), parent=blog_key())\n\t\t\tpost = db.get(key)\n\t\t\tif post.user_id == self.user.key().id():\n\t\t\t\tpost.delete()\n\t\t\t\tself.redirect('/?del_post_id=' + post_id)\n\t\t\telse:\n\t\t\t\tself.redirect('/' + post_id)\n\n\t\telse:\n\t\t\tself.redirect('/login?errormsg=Log in before performing actions')\n\nclass EditPost(BlogHandler):\n\tdef get(self, post_id):\n\t\tif self.user:\n\t\t\tkey = db.Key.from_path('Post', int(post_id), parent=blog_key())\n\t\t\tpost = db.get(key)\n\t\t\tif post.user_id == self.user.key().id():\n\t\t\t\tself.render('editpost.html',subject=post.subject,content=post.content)\n\n\t\t\telse:\n\t\t\t\tself.redirect('/' + post_id)\n\n\t\telse:\n\t\t\tself.redirect('/login?errormsg=Log in before performing actions')\n\n\tdef post(self, post_id):\n\t\tif not self.user:\n\t\t\tself.redirect('/login?errormsg=Log in before performing actions')\n\n\t\tsubject = self.request.get('subject')\n\t\tcontent = self.request.get('content')\n\n\t\tkey = db.Key.from_path('Post', int(post_id), parent=blog_key())\n\t\tpost = db.get(key)\n\n\t\tif post.user_id == self.user.key().id():\n\t\t\tif subject and content:\n\t\t\t\tkey = db.Key.from_path('Post', int(post_id), parent=blog_key())\n\t\t\t\tpost = db.get(key)\n\t\t\t\tpost.subject = subject\n\t\t\t\tpost.content = content\n\t\t\t\tpost.put()\n\t\t\t\tself.redirect('/%s' % post_id)\n\t\t\telse:\n\t\t\t\terror = \"You need a subject, and content\"\n\t\t\t\tself.render('editpost.html', subject=subject, content=content, error=error)\n\t\telse:\n\t\t\tself.redirect('/%s?errormsg=You cannot modify this post' % post_id)\n\nclass EditComment(BlogHandler):\n\tdef get(self, post_id, comment_id):\n\t\tif self.user:\n\t\t\tkey = db.Key.from_path('Comment', int(comment_id), parent=blog_key())\n\t\t\tc = db.get(key)\n\t\t\tif c.user_id == self.user.key().id():\n\t\t\t\tself.render('editcomment.html', comment=c.comment)\n\t\t\telse:\n\t\t\t\tself.redirect('/' + post_id)\n\n\t\telse:\n\t\t\tself.redirect('/login?errormsg=Log in before performing actions')\n\n\n\tdef post(self, post_id, comment_id):\n\t\tif not self.user:\n\t\t\tself.redirect('/login?errormsg=You must log in before you can edit comments')\n\n\t\tcomment = self.request.get('comment')\n\t\tkey = db.Key.from_path('Comment', int(comment_id), parent=blog_key())\n\t\tc = db.get(key)\n\n\t\tif c.user_id == self.user.key().id():\n\t\t\tif comment:\n\t\t\t\tkey = db.Key.from_path('Comment', int(comment_id), parent=blog_key())\n\t\t\t\tc = db.get(key)\n\t\t\t\tc.comment = comment\n\t\t\t\tc.put()\n\t\t\t\tself.redirect('/%s' % post_id)\n\t\t\telse:\n\t\t\t\terror = \"You need to enter some text\"\n\t\t\t\tself.render('editcomment.html', comment=comment, error=error)\n\t\telse:\n\t\t\tself.redirect('/%s?errormsg=You cannot modify this comment' % post_id)\n\nclass DeleteComment(BlogHandler):\n\t\"\"\"\n\t\tThis class is responsible for deleting comments.\n\t\"\"\"\n\tdef get(self, post_id, comment_id):\n\t\tif self.user:\n\t\t\tkey = db.Key.from_path('Comment', int(comment_id), parent=blog_key())\n\n\t\t\tc = db.get(key)\n\t\t\tif c.user_id == self.user.key().id():\n\t\t\t\tc.delete()\n\t\t\t\tself.redirect('/' + post_id + '?del_comment_id=' + comment_id)\n\n\t\t\telse:\n\t\t\t\tself.redirect('/' + post_id)\n\n\t\telse:\n\t\t\tself.redirect('/login?errormsg=You must log in before performing actions')\n\n\n\napp = webapp2.WSGIApplication([\n ('/', BlogFront), \n ('/([0-9]+)', PostPage), \n ('/newpost', NewPost), \n ('/signup', Register), \n ('/login', Login),\n ('/logout', Logout),\n ('/welcome', Welcome),\n ('/deletepost/([0-9]+)', DeletePost),\n ('/editpost/([0-9]+)', EditPost),\n ('/deletecomment/([0-9]+)/([0-9]+)', DeleteComment),\n ('/editcomment/([0-9]+)/([0-9]+)', EditComment)\n], debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"313653952","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = 'polls'\n\nurlpatterns = [\n url(r'^$', views.IndexView.as_view(), name='index'),\n url(r'^(?P[0-9]+)/$', views.DetailView.as_view(), name='detail'),\n url(r'^(?P[0-9]+)/results/$',views.ResultsView.as_view(), name='results'),\n url(r'^(?P[0-9]+)/vote/$', views.vote, name='vote'),\n url(r'^log$', views.log, name='log'),\n url(r'^auth$', views.auth, name='auth'),\n url(r'^logout$', views.log_out, name='log_out')\n \n \n]","sub_path":"polls/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"139366400","text":"# coding=utf-8\n\"\"\"\n检测匿名度\n\"\"\"\nimport requests\n\n# 搜狐\nurl1 = 'http://pv.sohu.com/cityjson?ie=utf-8'\n\n# 站长工具\nurl2 = 'http://www.xxorg.com/tools/checkproxy/'\n\nproxy = {\n 'http:': '182.108.44.47:808',\n 'https': '182.108.44.47:808'\n}\n\nres = requests.get(url1, proxies=proxy)\nprint(res.text)\n\n\n\n\n\n\n\n\n","sub_path":"freeproxy/test/check_anon.py","file_name":"check_anon.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"83037661","text":"from tkinter import *\nfrom datasetGathering import get_ghost_followings\nfrom datasetGathering import get_new_targets\nfrom target_like_follow import target_loop\nfrom unfollow import unfollow_loop\nimport printOperations as printops\nfrom sanitize import SanitaryTargets\n\n\nclass InstabotWindow:\n def __init__(self, master):\n self.master = master\n self.inactiveFollowings = printops.get_inactive_followings_length()\n self.targets = printops.get_target_list_length()\n\n headerFrame = Frame(master)\n valuesFrame = Frame(master)\n buttonsFrame = Frame(master)\n\n headerFrame.pack()\n valuesFrame.pack()\n buttonsFrame.pack()\n\n self.inactiveFollowingsLabel = Label(headerFrame, text=\"Inactive Followings\")\\\n .grid(column=0, row=0)\n self.currentTargetsLabel = Label(headerFrame, text=\"Current Targets\")\\\n .grid(column=1, row=0)\n\n self.inactiveFollowingsCount = Label(valuesFrame, text=self.inactiveFollowings)\n self.inactiveFollowingsCount.grid(column=0, row=0, padx=40)\n self.currentTargetsCount = Label(valuesFrame, text=self.targets)\n self.currentTargetsCount.grid(column=1, row=0, padx=40)\n\n self.updateInactiveButton = Button(buttonsFrame, text=\"Update Inactive\"\n \"\\nFollowings\", command=get_ghost_followings)\\\n .grid(column=0, row=0, sticky=W+E+N+S, padx=5, pady=5)\n self.unfollowButton = Button(buttonsFrame, text=\"Unfollow Inactive\\nFollowings\", command=unfollow_loop)\\\n .grid(column=0, row=1, sticky=W+E+N+S, padx=5, pady=5)\n self.getNewTargetsButton = Button(buttonsFrame, text=\"Get New Targets\", command=get_new_targets) \\\n .grid(column=1, row=0, sticky=W+E+N+S, padx=5, pady=5)\n self.followTargets = Button(buttonsFrame, text=\"Follow Targets\", command=target_loop) \\\n .grid(column=1, row=1, sticky=W+E+N+S, padx=5, pady=5)\n self.updateMetricsButton = Button(buttonsFrame, text=\"Update Count\", command=self.update_metrics) \\\n .grid(columnspan=2, row=2, sticky=W+E+N+S, padx=5, pady=5)\n\n def update_metrics(self):\n SanitaryTargets()\n self.inactiveFollowings = printops.get_inactive_followings_length()\n self.targets = printops.get_target_list_length()\n self.inactiveFollowingsCount.config(text=self.inactiveFollowings)\n self.currentTargetsCount.config(text=self.targets)\n self.currentTargetsCount.update()\n self.inactiveFollowingsCount.update()","sub_path":"InstaBot_MASTER/instabotWindow.py","file_name":"instabotWindow.py","file_ext":"py","file_size_in_byte":2572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"310117025","text":"'''\n## 3 ##\n按行整理token和code,并且将注释部分删除\n'''\n\n\nfrom pymongo import MongoClient\nimport re\nimport numpy as np\nimport codeTokenize, tokenInfoAdd\n\n#\ndef commentLabelTag(method_source_code, method_comment_list, start_line, end_line):\n label_arr = np.zeros(end_line-start_line+1)\n for method_comment in method_comment_list:\n if method_comment['commentType'] == \"LineComment\":\n _comment = method_comment['comment'].strip()\n _line_num = method_comment['startline']\n _line_code = method_source_code[_line_num-start_line]['code']\n _line_code = _line_code.replace(_comment, \"\")\n if _line_code.strip():\n label_arr[_line_num-start_line] = 1\n else:\n label_arr[_line_num-start_line] = 2 #代表当前行为纯注释行,应当删除\n\n if method_comment['commentType'] == \"BlockComment\":\n startline = method_comment['startline']\n endline = method_comment['endline']\n for _num in range(startline, endline+1):\n label_arr[_num - start_line] = 2\n\n label_list = []\n flag = 0\n for iter, line_code_doc in enumerate(method_source_code):\n line_num = line_code_doc[\"line_num\"]\n code = line_code_doc['code']\n if label_arr[iter]==1:\n label_list.append(str(line_num) + \":1\")\n elif label_arr[iter]==2:\n flag = 1\n elif flag==1 and label_arr[iter]==0:\n if code.strip():\n label_list.append(str(line_num) + \":1\")\n flag = 0\n else:\n label_list.append(str(line_num) + \":0\")\n else:\n label_list.append(str(line_num) + \":0\")\n return label_list\n\ndef nodeArrange(method_node_list, label_list):\n label_line_list = [int(label.split(\":\")[0]) for label in label_list]\n node_arrange_list = [\"\" for label in label_line_list]\n method_node_list = tokenInfoAdd.tokenEndAdd(method_node_list)\n for node in method_node_list:\n tokenType = node['tokenType']\n start_line = node['startLine']\n if start_line in label_line_list:\n iter = label_line_list.index(start_line)\n node_arrange_list[iter] = node_arrange_list[iter]+ \" \" + tokenInfoAdd.keyWordAdd(node)\n return node_arrange_list\n\ndef codeArrange(method_source_code, label_list):\n label_line_list = [int(label.split(\":\")[0]) for label in label_list]\n word_line_list = [str(label) for label in label_line_list]\n for code_doc in method_source_code:\n line_num = code_doc['line_num']\n if line_num in label_line_list:\n code = code_doc['code']\n iter = label_line_list.index(line_num)\n word_line_list[iter] = codeTokenize.codeTokenize(code)\n return word_line_list\n\n\n#按行整理node和code: {\n# \"line_num\":\n# \"code_tokenized\":\n# \"node_arranged\":\n# \"label\":\n# }\ndef docArrange(method_node_list, method_source_code, label_list, start_line, end_line):\n line_doc_list = []\n #整理node\n node_arrange_list = nodeArrange(method_node_list, label_list)\n #整理code\n line_word_list = codeArrange(method_source_code, label_list)\n\n for iter in range(len(label_list)):\n line_doc = {}\n node_arrange = node_arrange_list[iter].strip()\n code_tokenized = line_word_list[iter]\n #如果某行node为空,判断是否包含“}”\n if node_arrange == '':\n if \"}\" in code_tokenized:\n node_arrange = \"BlockEnd\" #添加BlockEnd\n elif code_tokenized == []:\n node_arrange = \"[SPL]\" #否则添加[SPL]代表空行\n code_tokenized = [\"[SPL]\"]\n else:\n node_arrange = \"[UKN]\"\n line_doc['line_num'] = int(label_list[iter].split(\":\")[0])\n line_doc['code_tokenized'] = code_tokenized\n line_doc['node_arranged'] = node_arrange.split(\" \")\n line_doc['label'] = int(label_list[iter].split(\":\")[1])\n line_doc_list.append(line_doc)\n return line_doc_list\n\ndef labelSum(comment_label_list):\n label_sum = 0\n for comment_label in comment_label_list:\n label = int(comment_label.split(\":\")[1])\n label_sum += label\n return label_sum\n\n\nif __name__ == '__main__':\n # 连接数据库\n client = MongoClient(\"localhost\", 27017)\n db = client['deepScope']\n coll = db['method_filted'] #filted行数>=3,filted2行数>=5,filted3行数>=7\n coll_new = db['method_arrange']\n print(\"Database connected!\")\n\n #遍历数据库\n count = 0\n for method_doc in coll.find():\n count += 1\n print(count)\n method_node_list = method_doc['method_node_list']\n method_source_code = method_doc['method_source_code']\n method_comment_list = method_doc['method_comment_list']\n project_name = method_doc['project_name']\n class_name = method_doc['class_name']\n start_line = method_doc['start']\n end_line = method_doc['end']\n method_id = method_doc['method_id']\n method_name = method_doc['method_name']\n\n new_method_doc = {}\n # labelTagging\n comment_label_list = commentLabelTag(method_source_code, method_comment_list, start_line, end_line)\n label_sum = labelSum(comment_label_list)\n #按行整理node和code\n line_doc_list = docArrange(method_node_list, method_source_code, comment_label_list, start_line, end_line)\n\n if line_doc_list != [] and label_sum != 0:\n new_method_doc['line_doc_list'] = line_doc_list\n new_method_doc['project_name'] = project_name\n new_method_doc['class_name'] = class_name\n new_method_doc['method_name'] = method_name\n new_method_doc['method_id'] = method_id\n new_method_doc['start_line'] = start_line\n new_method_doc['end_line'] = end_line\n new_method_doc['method_comment_list'] = method_comment_list\n new_method_doc['label_list'] = comment_label_list\n coll_new.insert(new_method_doc)\n\n\n","sub_path":"sysu_commentScope_deepScope/dataPreprocess/dataArrange.py","file_name":"dataArrange.py","file_ext":"py","file_size_in_byte":6084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"248080450","text":"# -*- coding: utf-8 -*-\n\nimport ujson\nimport aiohttp\n\nfrom logging import LoggerAdapter\nfrom sanic import Sanic, response\n\nfrom sanic.exceptions import SanicException\nfrom nanio.exceptions import NanioException\n\nimport nanio.config\nfrom nanio.log import LOGGING_CONFIG_DEFAULTS, log_root, log_api\nfrom nanio.api import base, gateway\nfrom nanio.services.base import NanioService\n\n\ndef register_error_handlers(app):\n @app.exception(SanicException)\n async def sanic_error(_, exception):\n msg = exception.__str__()\n\n if isinstance(exception, NanioException):\n if exception.log_message:\n log_root.error(msg)\n\n try:\n error = ujson.loads(msg)\n except ValueError:\n error = msg\n\n return response.json(body={'error': error}, status=exception.status_code)\n\n\nasync def client_create(app, loop):\n app.http_client = aiohttp.ClientSession(loop=loop)\n NanioService.set_http_client(app.http_client)\n\n\nasync def client_destroy(app, loop):\n loop.run_until_complete(app.http_client.close())\n loop.close()\n\n\nasync def contextual_logging(request):\n NanioService.log = LoggerAdapter(log_api, {'remote_addr': request.remote_addr or request.ip})\n\n\ndef create_app():\n app = Sanic('nanio', log_config=LOGGING_CONFIG_DEFAULTS)\n app.config.from_object(nanio.config)\n\n # Register error handler for catching exceptions and converting to JSON formatted errors\n register_error_handlers(app)\n\n # Add contextual logger middleware\n app.register_middleware(contextual_logging, 'request')\n\n # Register aiohttp client\n app.register_listener(client_create, 'before_server_start')\n app.register_listener(client_destroy, 'after_server_stop')\n\n # Register base /api\n app.blueprint(base)\n\n # Register Node RPC API gateway\n app.blueprint(gateway)\n\n log_root.info('Nanio starting...')\n\n if app.config['RPC_ENABLED']:\n log_root.info('RPC backends: {0}'.format(','.join(app.config['RPC_NODES']) or 'None configured'))\n else:\n log_root.info('RPC proxy disabled')\n\n return app\n","sub_path":"nanio/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"154349416","text":"\"\"\"\tTrain a GP model for error discrepancy between kinematic and dynamic models.\n\"\"\"\n\n__author__ = 'Achin Jain'\n__email__ = 'achinj@seas.upenn.edu'\n\n\nimport time\nimport numpy as np\nimport _pickle as pickle\nimport matplotlib.pyplot as plt\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.gaussian_process import GaussianProcessRegressor\nfrom sklearn.gaussian_process.kernels import RBF, ConstantKernel\nfrom sklearn.metrics import mean_squared_error, r2_score, explained_variance_score\n\nfrom bayes_race.utils.plots import plot_true_predicted_variance\n\n#####################################################################\n# load data\n\nSAVE_MODELS = False\n\nN_SAMPLES = 400\nVARIDX = 3\nstate_names = ['x', 'y', 'yaw', 'vx', 'vy', 'omega']\nfilename = 'orca/{}gp.pickle'.format(state_names[VARIDX])\n\ndef load_data(CTYPE, TRACK_NAME, VARIDX, xscaler=None, yscaler=None):\n\n\tdata_dyn = np.load('../data/DYN-{}-{}.npz'.format(CTYPE, TRACK_NAME))\n\tdata_kin = np.load('../data/KIN-{}-{}.npz'.format(CTYPE, TRACK_NAME))\n\ty_all = data_dyn['states'][:6,1:N_SAMPLES+1] - data_kin['states'][:6,1:N_SAMPLES+1]\n\tx = np.concatenate([\n\t\tdata_kin['inputs'][:,:N_SAMPLES].T,\n\t\tdata_kin['states'][6,:N_SAMPLES].reshape(1,-1).T,\n\t\tdata_dyn['states'][3:6,:N_SAMPLES].T],\n\t\taxis=1)\n\ty = y_all[VARIDX].reshape(-1,1)\n\n\tif xscaler is None or yscaler is None:\n\t\txscaler = StandardScaler()\n\t\tyscaler = StandardScaler()\n\t\txscaler.fit(x)\n\t\tyscaler.fit(y)\n\t\treturn xscaler.transform(x), yscaler.transform(y), xscaler, yscaler\n\telse:\n\t\treturn xscaler.transform(x), yscaler.transform(y)\n\nx_train, y_train, xscaler, yscaler = load_data('PP', 'ETHZMobil', VARIDX)\n\n#####################################################################\n# train GP model\n\nk1 = 1.0*RBF(\n\tlength_scale=np.ones(x_train.shape[1]),\n\tlength_scale_bounds=(1e-5, 1e5),\n\t)\nk2 = ConstantKernel(0.1)\nkernel = k1 + k2\nmodel = GaussianProcessRegressor(\n\talpha=1e-6, \n\tkernel=kernel, \n\tnormalize_y=True,\n\tn_restarts_optimizer=10,\n\t)\nstart = time.time()\nmodel.fit(x_train, y_train)\nend = time.time()\nprint('training time: %ss' %(end - start)) \nprint('final kernel: %s' %(model.kernel_))\n\nif SAVE_MODELS:\n\twith open(filename, 'wb') as f:\n\t\tpickle.dump((model, xscaler, yscaler), f)\n\n#####################################################################\n# test GP model on training data\n\ny_train_mu, y_train_std = model.predict(x_train, return_std=True)\ny_train = yscaler.inverse_transform(y_train)\ny_train_mu = yscaler.inverse_transform(y_train_mu)\ny_train_std *= yscaler.scale_\n\nMSE = mean_squared_error(y_train, y_train_mu, multioutput='raw_values')\nR2Score = r2_score(y_train, y_train_mu, multioutput='raw_values')\nEV = explained_variance_score(y_train, y_train_mu, multioutput='raw_values')\n\nprint('root mean square error: %s' %(np.sqrt(MSE)))\nprint('normalized mean square error: %s' %(np.sqrt(MSE)/np.array(np.abs(y_train.mean()))))\nprint('R2 score: %s' %(R2Score))\nprint('explained variance: %s' %(EV))\n\n#####################################################################\n# test GP model on validation data\n\nN_SAMPLES = 400\nx_test, y_test = load_data('NMPC', 'ETHZ', VARIDX, xscaler=xscaler, yscaler=yscaler)\ny_test_mu, y_test_std = model.predict(x_test, return_std=True)\ny_test = yscaler.inverse_transform(y_test)\ny_test_mu = yscaler.inverse_transform(y_test_mu)\ny_test_std *= yscaler.scale_\n\nMSE = mean_squared_error(y_test, y_test_mu, multioutput='raw_values')\nR2Score = r2_score(y_test, y_test_mu, multioutput='raw_values')\nEV = explained_variance_score(y_test, y_test_mu, multioutput='raw_values')\n\nprint('root mean square error: %s' %(np.sqrt(MSE)))\nprint('normalized mean square error: %s' %(np.sqrt(MSE)/np.array(np.abs(y_test.mean()))))\nprint('R2 score: %s' %(R2Score))\nprint('explained variance: %s' %(EV))\n\n#####################################################################\n# plot results\n\nplot_true_predicted_variance(\n\ty_train, y_train_mu, y_train_std, \n\tylabel='{} '.format(state_names[VARIDX]), xlabel='sample index'\n\t)\n\nplot_true_predicted_variance(\n\ty_test, y_test_mu, y_test_std, \n\tylabel='{} '.format(state_names[VARIDX]), xlabel='sample index'\n\t)\n\nplt.show()","sub_path":"bayes_race/gp/train_model_orca.py","file_name":"train_model_orca.py","file_ext":"py","file_size_in_byte":4136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"357592271","text":"import ast\n\nfrom typing import Optional\n\n\nclass ComplexDestructuringRewriter(ast.NodeTransformer):\n def __init__(self, language):\n super().__init__()\n self._disable = False\n if language in {\"cpp\", \"julia\", \"dart\"}:\n self._disable = True\n self._no_underscore = False\n if language in {\"nim\"}:\n self._no_underscore = True\n self._temp = 0\n\n def _get_temp(self):\n self._temp += 1\n if self._no_underscore:\n return f\"tmp{self._temp}\"\n return f\"__tmp{self._temp}\"\n\n def visit_Assign(self, node):\n if self._disable:\n return node\n target = node.targets[0]\n if isinstance(target, ast.Tuple) and not (isinstance(target.elts[0], ast.Name)):\n temps = []\n orig = [None] * len(target.elts)\n body = [node]\n for i in range(len(target.elts)):\n temps.append(ast.Name(id=self._get_temp(), lineno=node.lineno))\n # The irony!\n target.elts[i], orig[i] = temps[i], target.elts[i]\n body.append(\n ast.Assign(targets=[orig[i]], value=temps[i], lineno=node.lineno)\n )\n ret = ast.If(\n test=ast.Constant(value=True), body=body, orelse=[], lineno=node.lineno\n )\n return ret\n return node\n\n\nclass RenameTransformer(ast.NodeTransformer):\n def __init__(self, old_name, new_name):\n super().__init__()\n self._old_name = old_name\n self._new_name = new_name\n\n def visit_Name(self, node):\n if node.id == self._old_name:\n node.id = self._new_name\n return node\n\n def visit_FunctionDef(self, node):\n if node.name == self._old_name:\n node.name = self._new_name\n self.generic_visit(node)\n return node\n\n\ndef rename(scope, old_name, new_name):\n tx = RenameTransformer(old_name, new_name)\n tx.visit(scope)\n\n\nclass PythonMainRewriter(ast.NodeTransformer):\n def __init__(self, language):\n super().__init__()\n\n def visit_If(self, node):\n is_main = (\n isinstance(node.test, ast.Compare)\n and isinstance(node.test.left, ast.Name)\n and node.test.left.id == \"__name__\"\n and isinstance(node.test.ops[0], ast.Eq)\n and isinstance(node.test.comparators[0], ast.Constant)\n and node.test.comparators[0].value == \"__main__\"\n )\n if is_main:\n if hasattr(node, \"scopes\") and len(node.scopes) > 1:\n rename(node.scopes[-2], \"main\", \"main_func\")\n # ast.parse produces a Module object that needs to be destructured\n ret = ast.parse(\"def main(): True\").body[0]\n ret.lineno = node.lineno\n ret.body = node.body\n # So backends know to insert argc, argv etc\n ret.python_main = True\n return ret\n return node\n\n\nclass FStringJoinRewriter(ast.NodeTransformer):\n def __init__(self, language):\n super().__init__()\n\n def visit_JoinedStr(self, node):\n new_node = ast.parse('\"\".join([])').body[0].value\n args = new_node.args\n for v in node.values:\n if isinstance(v, ast.Constant):\n args[0].elts.append(v)\n elif isinstance(v, ast.FormattedValue):\n args[0].elts.append(\n ast.Call(\n func=ast.Name(id=\"str\", ctx=\"Load\"), args=[v.value], keywords=[]\n )\n )\n new_node.lineno = node.lineno\n new_node.col_offset = node.col_offset\n ast.fix_missing_locations(new_node)\n return new_node\n\n\nclass DocStringToCommentRewriter(ast.NodeTransformer):\n def __init__(self, language):\n super().__init__()\n self._docstrings = set()\n self._docstring_parent = {}\n\n def _get_doc_node(self, node) -> Optional[ast.AST]:\n if not (node.body and isinstance(node.body[0], ast.Expr)):\n return None\n node = node.body[0].value\n if isinstance(node, ast.Str):\n return node\n elif isinstance(node, ast.Constant) and isinstance(node.value, str):\n return node\n return None\n\n def visit_FunctionDef(self, node):\n doc_node = self._get_doc_node(node)\n self._docstrings.add(doc_node)\n self._docstring_parent[doc_node] = node\n self.generic_visit(node)\n return node\n\n def visit_ClassDef(self, node):\n doc_node = self._get_doc_node(node)\n self._docstrings.add(doc_node)\n self._docstring_parent[doc_node] = node\n self.generic_visit(node)\n return node\n\n def visit_Module(self, node):\n doc_node = self._get_doc_node(node)\n self._docstrings.add(doc_node)\n self._docstring_parent[doc_node] = node\n self.generic_visit(node)\n return node\n\n def visit_Constant(self, node):\n if node in self._docstrings:\n parent = self._docstring_parent[node]\n parent.docstring_comment = ast.Constant(value=node.value)\n return None\n return node\n\n def visit_Expr(self, node):\n self.generic_visit(node)\n if not hasattr(node, \"value\"):\n return None\n return node\n","sub_path":"py2many/rewriters.py","file_name":"rewriters.py","file_ext":"py","file_size_in_byte":5317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"600510538","text":"# Copyright 2018 C Rosenberg\n\nimport logging\nfrom os import makedirs, system, remove, rename\n\nlogger = logging.getLogger(__name__)\n\n\ndef os_system(command: str):\n logger.info(\"System: {}\".format(command))\n print(\"Test print in os_system\")\n try:\n if system(command) > 0:\n raise OSError\n return True\n except OSError:\n logger.error(command)\n return False\n\n\ndef os_remove(fpath: str):\n logger.info(\"Remove: {}\".format(fpath))\n try:\n if remove(fpath) is not None:\n raise OSError\n return True\n except OSError:\n logger.error(fpath)\n return False\n\n\ndef os_makedirs(make_dirs: str):\n logger.info(\"Make Dirs: {}\".format(make_dirs))\n try:\n if makedirs(make_dirs) is not None:\n raise OSError\n return True\n except OSError:\n logger.error(make_dirs)\n return False\n\n\ndef os_rename(src: str, dst: str):\n logger.info(\"Rename: src:\" + src + \" dst:\" + dst)\n try:\n if rename(src, dst) is not None:\n raise OSError\n return True\n except OSError:\n logger.error(src + \":\" + dst)\n return False\n","sub_path":"source/lib/system/os_system.py","file_name":"os_system.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"508170424","text":"import csv\n\nexample = open('example.csv', 'w', newline = '')\n#example = open('example.csv', 'w') # It is also worked on Linux \n\n#writer = csv.writer(example)\nwriter = csv.writer(example, delimiter='\\t', lineterminator='\\n\\n')\n\n\nwriter.writerow(['Stduent ID', 'Name'])\nwriter.writerow(['A12345678', 'Jack'])\nwriter.writerow(['B12345678', 'Jackass'])\nexample.close()\n\nexample = open('example.csv')\n#reader = csv.reader(example)\nreader = csv.reader(example, delimiter='\\t', lineterminator='\\n\\n')\n\ncontent = list(reader)\nprint(\"List: \")\nprint(content)\n# content = list(reader) # Failure: it would modify `reader`\nprint(\"[0][0]: \" + content[0][0])\nprint(\"[0][1]: \" + content[0][1])\nfor row in reader:\n print(\"Row #\" + str(reader.line_num) + ' ' + str(row))\nexample.close()\n","sub_path":"basic/csv_file.py","file_name":"csv_file.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"522275459","text":"from scipy.interpolate import interp1d\nimport os.path as osp\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport json\n\ndef plot_curves(curves):\n for curve in curves:\n points = np.array([p[1] for p in curve])\n plt.plot(points[:, 1], points[:, 0])\n # plt.plot(points[:, 1], points[:, 0], '*')\n\nif __name__ == '__main__':\n with open('curves.json', 'r') as f:\n curves = json.loads(\"\".join(f.readlines()))\n\n output_file = 'curve_stuff.json'\n if osp.isfile(output_file):\n with open(output_file, 'r') as f:\n output_stuff = json.loads(\"\".join(f.readlines()))\n else:\n output_stuff = {}\n\n\n if False:\n # First click out the middle of the board\n print('middle points')\n plot_curves(curves[0])\n plot_curves(curves[1])\n\n points = plt.ginput(-1, 0, True)\n plt.close()\n if len(points) > 0:\n output_stuff['middle_points'] = points\n\n # Calculate the peaks for all the curves \n print('amplitude points')\n plot_curves(curves[1])\n points = plt.ginput(-1, 0, True)\n plt.close()\n if len(points) > 0:\n output_stuff['amplitude_points'] = points\n\n print('left peaks')\n plot_curves(curves[0])\n points = plt.ginput(-1, 0, True)\n if len(points) > 0:\n output_stuff['left_peaks'] = points\n plt.close()\n\n print('right peaks')\n plot_curves(curves[1])\n points = plt.ginput(-1, 0, True)\n if len(points) > 0:\n output_stuff['right_peaks'] = points\n plt.close()\n\n # print to file\n with open(output_file, 'w') as f:\n f.write(json.dumps(output_stuff))\n\n # Calculate the amplitude for the curves compared to the middle\n interp_type = 'cubic'\n middle = np.array(output_stuff['middle_points'])\n middle_int = interp1d(middle[:, 1], middle[:, 0], interp_type, fill_value='extrapolate')\n\n amplitude_points = np.array(output_stuff['amplitude_points'])\n amplitude_points[:, 0] = np.abs(middle_int(amplitude_points[:, 1]) - amplitude_points[:, 0])\n\n plt.plot(amplitude_points[:, 1], amplitude_points[:, 0])\n plt.show()\n\n # Calculate the phase for the curves\n left_peaks = np.array(output_stuff['left_peaks'])\n right_peaks = np.array(output_stuff['right_peaks'])\n left_phase = (np.cumsum(np.ones(len(left_peaks))) - 1) * np.pi\n right_phase = np.cumsum(np.ones(len(right_peaks))) * 2 * np.pi\n\n plt.plot(left_peaks[:, 1], left_phase)\n plt.plot(right_peaks[:, 1], right_phase)\n plt.show()\n","sub_path":"version2/click_amp_etc.py","file_name":"click_amp_etc.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"243925528","text":"import requests\n\n\nwith requests.Session() as c:\n url = 'https://epprd.mcmaster.ca/psp/prepprd/?cmd=login'\n TIMEZONEOFFSET = 300\n PTMODE = 'f'\n PTLANGCD = 'ENG'\n PTINSTALLEDLANG = 'ENG'\n USERID = 'yins1'\n PWD = ''\n c.get(url)\n login_data = dict(timezoneoffset = TIMEZONEOFFSET, ptmode = PTMODE, ptlangcd = PTLANGCD, ptinstalledlang = PTINSTALLEDLANG, userid = USERID, pwd = PWD)\n c.post(url, data = login_data, headers = {})\n page = c.get('https://epprd.mcmaster.ca/psp/prepprd/EMPLOYEE/SA/c/SA_LEARNER_SERVICES.SSS_STUDENT_CENTER.GBL')\n print(page.content)\n\n\n#print(r.json())\n","sub_path":"Request.py","file_name":"Request.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"306651657","text":"# -*- coding=UTF-8 -*-\n\n\"\"\"\n\nFile name : read_arff.py\n\nCreation date : 29-06-2016\n\nLast modified :\n\nCreated by :\n\nPurpose :\n\n Reads arff file. Basically looks for the first line after @data. All data\n after @data are stored in a matrix. Each file line goes to a matrix row.\n\nUsage :\n\n data = read_arff(filename)\n\nObservations :\n\n\"\"\"\n\nimport numpy as np\n\ndef read_arff(filename, sep):\n\n f = open(filename, 'r')\n\n string = f.readline()\n\n while string[:5] != '@data':\n string = f.readline()\n\n data = [line.split(sep) for line in f]\n f.close()\n\n for i in range(len(data)):\n\n data[i][-1] = data[i][-1].strip()\n \n return np.asarray(data, np.float)\n","sub_path":"read_arff.py","file_name":"read_arff.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"274941909","text":"import unittest\nimport tkfinder\n\n\nclass MyTestCase(unittest.TestCase):\n def test_get_commands(self):\n\n result = tkfinder.get_commands_character(\"hwoarang\")\n self.assertIn(\"1, 1, 3, 3\", result)\n\n def test_get_close_moves(self):\n close_moves = tkfinder.get_similar_moves(\"d/f+1, 2\", \"hwoarang\")\n self.assertIn(\"d/f+1, 3\", close_moves)\n\n def test_is_command_in_alias(self):\n item = {'Alias' : \"hs, hellsweep, Giant swing, u/f3\"}\n result = tkfinder.is_command_in_alias(\"hellsweep\",item)\n self.assertTrue(result)\n\n result = tkfinder.is_command_in_alias(\"he\",item)\n self.assertFalse(result)\n\n result = tkfinder.is_command_in_alias(\"uf3\", item)\n self.assertTrue(result)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tkfinder_test.py","file_name":"tkfinder_test.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"526835476","text":"import os\nimport re\nfrom collocations_by_frequency import CollocationsByFrequency\nfrom collocations_by_mutual_information import MutualInformation\nfrom Ttest import Ttest\nfrom collections import Counter\nfrom nltk.util import ngrams\nimport pickle\nimport csv\n\ndef clean_text(text):\n \"\"\"This function will process the t1ext and clean it before extracting the collocations\n \"\"\"\n words=re.sub(\"[IVX]+\\\\.\",\"\", text) #roman numbers\n words = re.split(r'\\W+', words) #punctionation\n string_words = ' '.join((item for item in words if not item.isdigit())) #numbers\n tokens = [token for token in string_words.split(\" \") if (token != \"\" and len(token)>1)] \n return tokens\n\ndef load_donem_data(donem_number):\n \n \"\"\"Returns all the text found in a donem directory\"\"\"\n \n donem_text = ''\n donem_dir_path = os.path.join(os.getcwd(), f'corpus/donem{donem_number}') \n walks = os.walk(donem_dir_path)\n for walk in walks:\n path, dirs, files = walk\n for file in files:\n file_path = os.path.join(path, file)\n if not file_path.endswith('txt'): continue # avoid reading .DS_Store files (for mac users)\n with open(file_path, 'r', encoding=\"UTF-8\") as f:\n donem_text += f.read()\n return clean_text(donem_text)\n\n\ndef get_bigrams_with_freqs(donem_text):\n\n collocations = list(ngrams(donem_text, 2)) # extracting bigrams\n collocations_freqs = Counter(collocations)\n collocations_freqs = sorted(collocations_freqs.items(), key=lambda kv: kv[1], reverse=True)[0:1000]\n \n return dict(collocations_freqs)\n\n\ndef save_as_csv(data, file_name, donem_num, header, all_donems=False):\n\n if all_donems:\n path = os.path.join(os.getcwd(), f'collocations/results/whole_corpus/')\n else: \n path = os.path.join(os.getcwd(), f'collocations/results/donem_{donem_num}/')\n\n if not os.path.exists(path):\n os.makedirs(path)\n\n with open(path+f'{file_name}.csv','w', encoding=\"UTF-8\") as out:\n csv_out=csv.writer(out)\n csv_out.writerow(header)\n for row in data:\n csv_out.writerow(row)\n\n\n\ndef main():\n\n out_base = os.path.join(os.getcwd(), \"collocations\",\"out\")\n\n collocations_by_frquency = CollocationsByFrequency() \n mutual_information = MutualInformation()\n t_test = Ttest()\n\n donem_nums = range(20, 28) \n all_donem_text = []\n table_header_freq = ['C(w1;w2)', 'collocation', 'tag pattern']\n table_header_mi = ['I(w1;w2)', 'C(w1)', 'C(w2)', 'C(w1;w2)', 'collocation']\n table_header_ttest = ['t', 'C(w1)', 'C(w2)', 'C(w1;w2)', 'collocation']\n \n for donem_num in donem_nums:\n\n print(f\"Donem {str(donem_num)} processing..\")\n donem_text = load_donem_data(donem_num)\n\n all_donem_text.extend(donem_text)\n\n # \"\"\"print(f\"Donem {str(donem_num)} bigrams extracting processing..\")\n # bigrams_with_freqs = get_bigrams_with_freqs(donem_text)\"\"\"\n \n pk_file = open(out_base+os.sep+\"donem_\"+str(donem_num)+\".pk\", \"rb\")\n bigrams_with_freqs = pickle.load(pk_file)\n \n print(f\"Donem {str(donem_num)} frequency processing..\")\n # Method 1: Frequency \n collocations_frequency = collocations_by_frquency.get_collocations(bigrams_with_freqs)\n save_as_csv(collocations_frequency, 'freq', donem_num, table_header_freq)\n\n print(f\"Donem {str(donem_num)} MutualInformation processing..\")\n #Method 2: MutualInformation\n collocations_mi = mutual_information.get_collocations(donem_text, bigrams_with_freqs)\n save_as_csv(collocations_mi, 'MI', donem_num, table_header_mi)\n \n print(f\"Donem {str(donem_num)} T-test processing..\")\n # Method 3: T-test\n collocations_Ttest = t_test.get_collocations(donem_text, bigrams_with_freqs)\n save_as_csv(collocations_Ttest, 't_test', donem_num, table_header_ttest)\n \n\n # All donems together\n \"\"\" print(\"Collocations will start..\")\n all_donems_bigrams_with_freqs = get_bigrams_with_freqs(all_donem_text)\n \n print(\"Saving all bigrams in pickle..\")\n pk_file = open(out_base+os.sep+\"donem_all.pk\", \"wb\")\n pickle.dump(bigrams_with_freqs,file=pk_file)\"\"\"\n \n pk_file = open(out_base+os.sep+\"donem_all.pk\", \"rb\")\n all_donems_bigrams_with_freqs = pickle.load(pk_file)\n\n print(\"Collocations process is finished..\")\n collocations_frequency = collocations_by_frquency.get_collocations(all_donems_bigrams_with_freqs)\n save_as_csv(collocations_frequency, 'freq', 0, table_header_freq, all_donems=True)\n print(\"Frequencies extraction finished..\")\n collocations_mi = mutual_information.get_collocations(all_donem_text, all_donems_bigrams_with_freqs)\n save_as_csv(collocations_mi, 'MI', 0, table_header_mi, all_donems=True)\n print(\"Mutual Information extraction finished..\")\n collocations_Ttest = t_test.get_collocations(all_donem_text, all_donems_bigrams_with_freqs)\n save_as_csv(collocations_Ttest, 't_test', 0, table_header_ttest, all_donems=True)\n print(\"T-test extraction finished..\")\n\nmain()\n","sub_path":"delivery2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"377461556","text":"from django.core.exceptions import ValidationError as DjangoValidationError, \\\n NON_FIELD_ERRORS as DJANGO_NON_FIELD_ERRORS\nfrom django.db import transaction\n\nfrom rest_framework import permissions, mixins, serializers\nfrom rest_framework.decorators import action\nfrom rest_framework.generics import GenericAPIView\nfrom rest_framework.pagination import PageNumberPagination\nfrom rest_framework.response import Response\nfrom rest_framework.settings import api_settings\nfrom rest_framework.viewsets import ReadOnlyModelViewSet\nfrom rest_framework.exceptions import APIException\n\nfrom archive.models import summarize_redaction_plan\nfrom metadata.models import AccessControl\nfrom portal.views import developer_check, admin_check\n\n\ndef convert_validation(ex):\n \"\"\" Convert Django validation error to REST framework validation error \"\"\"\n\n errors = {}\n for message in ex:\n if message is tuple:\n field, error = message\n if field != DJANGO_NON_FIELD_ERRORS:\n translated_field = field\n else:\n translated_field = api_settings.NON_FIELD_ERRORS_KEY\n else:\n translated_field = api_settings.NON_FIELD_ERRORS_KEY\n error = message\n errors[translated_field] = error\n\n return serializers.ValidationError(errors)\n\n\nclass StandardPagination(PageNumberPagination):\n page_size_query_param = 'page_size'\n\n\nclass IsGrantedReadOnly(permissions.BasePermission):\n \"\"\" Custom permission for historical resources like runs.\n\n All authenticated users can see instances they have been allowed access to\n either because they own them, they are in users_allowed, or they are in\n groups_allowed.\n Only administrators can modify records.\n \"\"\"\n def has_permission(self, request, view):\n return (admin_check(request.user) or\n request.method in permissions.SAFE_METHODS)\n\n def has_object_permission(self, request, view, obj):\n if admin_check(request.user):\n return True\n return obj.can_be_accessed(request.user)\n\n\nclass IsGrantedReadCreate(permissions.BasePermission):\n \"\"\" Custom permission for Read/Write resources like datasets.\n\n All authenticated users can see instances they have been allowed access to\n either because they own them, they are in users_allowed, or they are in\n groups_allowed.\n \"\"\"\n def has_permission(self, request, view):\n return (admin_check(request.user) or\n request.method in permissions.SAFE_METHODS or\n request.method == \"POST\")\n\n def has_object_permission(self, request, view, obj):\n if admin_check(request.user):\n return True\n return obj.can_be_accessed(request.user)\n\n\nclass IsDeveloperOrGrantedReadOnly(IsGrantedReadOnly):\n \"\"\" Custom permission for developer resources like code\n\n Developers can create new instances, and all authenticated users can see\n instances they have been allowed access to either because they own them,\n they are in users_allowed, or they are in groups_allowed.\n \"\"\"\n def has_permission(self, request, view):\n if admin_check(request.user):\n return True\n if request.method in permissions.SAFE_METHODS:\n return True\n return developer_check(request.user) and request.method in (\"POST\", \"PATCH\")\n\n\nclass GrantedModelMixin:\n \"\"\" Filter instances that the user has been granted access to.\n\n Mix this in with a view set to add a query parameter:\n\n * is_granted - true For administrators, this limits the list to only include\n records that the user has been explicitly granted access to. For other\n users, this has no effect.\n\n The model must derive from AccessControl, or filter_granted() must be\n overridden.\n \"\"\"\n\n def get_queryset(self):\n if self.request.query_params.get('is_granted') == 'true':\n is_admin = False\n else:\n is_admin = admin_check(self.request.user)\n base_queryset = super(GrantedModelMixin, self).get_queryset()\n if is_admin:\n return base_queryset\n return self.filter_granted(base_queryset)\n\n def filter_granted(self, queryset):\n \"\"\" Filter a queryset to only include records explicitly granted.\n \"\"\"\n return AccessControl.filter_by_user(self.request.user,\n queryset=queryset)\n\n\nclass RedactModelMixin:\n \"\"\" Redacts a model instance and build a redaction plan.\n\n Mix this in with a view set to provide default behaviour for data redaction.\n This overrides the `partial_update` method so that it automatically redacts an\n object if it sees the `is_redacted` flag when PATCH'd. After that, the patch_object\n method is called, which you should override if you want to do any proper PATCH object\n updates.\n\n * patch_object() - override this on the super class, it should\n return a response containing the JSON representation of the patched\n object.\n * partial_update() - redacts the given instance, if the request's POST data contains\n is_redacted=false.\n * build_redaction_plan() - returns all instances that will be redacted when you\n patch the object with is_redacted=true. Returns a dict: {model_name: set(instance)}\n\n \"\"\"\n def patch_object(self, request, pk=None):\n pass\n\n def partial_update(self, request, pk=None):\n is_redacted = request.data.get(\"is_redacted\", \"false\") == \"true\"\n if is_redacted:\n self.get_object().redact()\n return Response({'message': 'Object redacted.'})\n return self.patch_object(request, pk)\n\n @action(detail=True)\n def redaction_plan(self, request, pk=None):\n redaction_plan = self.get_object().build_redaction_plan()\n return Response(summarize_redaction_plan(redaction_plan))\n\n\nclass RemoveModelMixin(mixins.DestroyModelMixin):\n \"\"\" Remove a model instance and build a removal plan.\n\n Mix this in with a view set to call remove() instead of destroy() on a\n DELETE command. The model must define the following methods:\n\n * remove() - deletes the given instance, as well as any instances of this\n and other models that reference it. Intended as a drastic clean up\n measure when sensitive data has been inappropriately added to Kive and\n all traces must be removed.\n * build_removal_plan() - returns all instances that will be removed when you\n call remove(). Returns a dict: {model_name: set(instance)}\n \"\"\"\n\n @action(detail=True, suffix='Removal Plan')\n def removal_plan(self, request, pk=None):\n try:\n removal_plan = self.get_object().build_removal_plan()\n return Response(summarize_redaction_plan(removal_plan))\n except ValueError as ex:\n raise APIException(ex.message)\n\n def perform_destroy(self, instance):\n instance.remove()\n\n\nclass RemovableModelViewSet(RemoveModelMixin,\n GrantedModelMixin,\n ReadOnlyModelViewSet):\n \"\"\" The most common view set for developer models.\n For now, we only support GET and DELETE through the REST API. The DELETE\n command actually triggers the remove() method instead of destroy().\n \"\"\"\n pass\n\n\nclass CleanCreateModelMixin(mixins.CreateModelMixin):\n \"\"\"\n A mixin that adds POST support through the REST API.\n \"\"\"\n @transaction.atomic\n def perform_create(self, serializer):\n \"\"\"\n Handle creation and cleaning of a new object.\n \"\"\"\n try:\n new_obj = serializer.save()\n new_obj.full_clean()\n except DjangoValidationError as ex:\n raise convert_validation(ex.messages)\n\n\nclass SearchableModelMixin(GenericAPIView):\n \"\"\"\n Implements some boilerplate code common to ViewSets that allow filtering.\n\n Replace the filters class attribute with\n {key: lambda queryset, value: queryset} or override _add_filter().\n \"\"\"\n filters = None\n\n def get_queryset(self):\n queryset = super(SearchableModelMixin, self).get_queryset()\n return self.apply_filters(queryset)\n\n def apply_filters(self, queryset):\n # Parse the request to get all the applied filters, and refine the queryset.\n idx = 0\n while True:\n key = self.request.GET.get('filters[{}][key]'.format(idx))\n if key is None:\n break\n value = self.request.GET.get('filters[{}][val]'.format(idx), '')\n if self.filters is None:\n queryset = self._add_filter(queryset, key, value)\n else:\n apply_filter = self.filters.get(key)\n if apply_filter is None:\n raise APIException('Unknown filter key: {}'.format(key))\n queryset = apply_filter(queryset, value)\n\n idx += 1\n\n return queryset\n\n def _add_filter(self, queryset, key, value):\n \"\"\"\n Filter the specified queryset by the specified key and value.\n \"\"\"\n if self.filters is None:\n raise NotImplementedError(\n \"Override _add_filter() or set the filters class attribute.\")\n","sub_path":"kive/kive/ajax.py","file_name":"ajax.py","file_ext":"py","file_size_in_byte":9227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"323617484","text":"from .ParserData import Struct\nfrom .ParserData import ParseContainer\nfrom .ParserData import StructEncoder\nfrom .QCBase import GenFormatter, VarNames as V\nimport importlib as il\nimport os.path, inspect\nimport re\nimport logging\nimport json\n\nclass Parser(object):\n def __init__(self, output, *, software=None, toConsole=True,\n toFile=False, log_file=\"CCParser.log\", json=False,\n json_file=\"CCParser.json\"):#cf. PEP-3102\n \"\"\" Parser constructor.\n \n Parameters\n ----------\n output : string\n Output filename.\n software : string\n Name of quantum chemistry software suite (default: None).\n toConsole : bool\n Whether to print log output to screen (default: True).\n toFile : bool\n Whether to write log output to file (default: False).\n logname : string\n Name of output log file (default: ``CCParser.log``).\n \n \"\"\"\n self.f_output = output\n self.logger = logging.getLogger(\"CCParser\")\n self.toConsole = toConsole\n self.toFile = toFile\n self.logname = log_file\n self.setupLogger()\n \n if software != None:\n self.software = software\n else:\n self.find_software()\n raise ValueError(\"No software specified!\")\n\n self.output_basename = os.path.basename(output)\n self.read_output()# read output to memory\n self.load_methods()# software dependent import\n \n self.results = Struct()# Set up container\n self.logger.warning(\"CCParser starts...\")\n for i,line in enumerate(self.rawData):\n for mthd in self.methods:\n# match, key = self.canParse(line, mthd)\n match, keys = self.canParse(line, mthd)\n if match:\n for key in keys:# if not 1-to-1 mapping\n q = self.get_quantity(i, key, mthd)\n if hasattr(self.results, mthd.map[key]):\n obj = getattr(self.results, mthd.map[key])\n obj.add(i, q)\n else:\n obj = ParseContainer()\n obj.add(i, q)\n setattr(self.results, mthd.map[key], obj)\n if not hasattr(self.results, V.has_finished):\n container = ParseContainer()\n container.add(0, False)\n setattr(self.results, V.has_finished, container)\n self.logger.warning(\"Output indicates abnormal exit. Added \"+\n \"[results.has_finished] = False\")\n \n if json:\n self.dump_json(fname=json_file)\n self.logger.warning(\"CCParser has finished.\")\n self.loggerCleanUp()\n\n\n def read_output(self):\n \"\"\" Read in output file \"\"\"\n with open(self.f_output, \"r\") as f:\n self.rawData = f.readlines()\n \n def read_input(self, f_input):\n \"\"\" (Optional) Read input file \"\"\"\n with open(f_input) as n:\n self.rawData.insert(0, n.readlines())\n \n def canParse(self, line, mthd):\n \"\"\" Check if line is parsable \"\"\"\n found = False\n keys = []#for cases where there's no 1-to-1 mapping\n for key, value in mthd.hooks.items():\n if value in line:\n found = True\n keys.append(key)\n# return found, key\n else:\n match = re.search(value, line)\n if match:\n found = True\n keys.append(key)\n# return found, key\n if found == False:\n return found, None\n else:\n return found, keys\n\n \n def get_quantity(self, i, key, mthd):\n \"\"\" Call function of method class. This is the actual parsing. \"\"\"\n method_func = getattr(mthd, key)# needs to be method not list of methods\n result = method_func(i, self.rawData)\n return result\n \n def load_methods(self):\n \"\"\" Load correct module which contains parsing information\n based on which software was specified. \"\"\"\n tmp = re.sub('[^A-Za-z]+', '', self.software.lower())\n if tmp == \"qchem\":\n m_package = \".QChem\"\n elif tmp == \"gaussian\":\n m_package = \".Gaussian\"\n elif tmp == \"molcas\":\n raise NotImplementedError(\"Molcas parsing not implemented yet!\")\n m_package = \".Molcas\"\n elif tmp == \"turbomole\":\n raise NotImplementedError(\"Turbomole parsing not implemented yet!\")\n m_package = \".Turbomole\"\n elif tmp == \"psi\":\n m_package = \".Psi4\"\n else:\n raise ValueError(\"The specified software is misspelled or not implemented yet!\")\n global m\n# m = il.import_module(m_package+\".methods\",package=\"CCParser\")\n m = il.import_module(m_package, package=\"CCParser\")\n self.method_names = [k[0] for k in inspect.getmembers(m,\n inspect.isclass) if k[1].__module__ == \"CCParser\"+m_package]\n self.methods = [getattr(m, mname)() for mname in self.method_names]#this also instantiates!!\n\n def setupLogger(self):\n \"\"\"Initiate logger for CCParser.Parser\"\"\"\n # Set main logger's minimum output level\n self.logger.setLevel(logging.INFO)\n # Set up Formatter\n# p_fmt = logging.Formatter(\"[results.%(Parsed)s] Parsed %(message)s\")\n # TODO: change number of loggers\n # This is abusing the Formatter class a bit, but I wanted to avoid\n # one Logger for every format, maybe I'll change this in the future.\n p_fmt = GenFormatter(\n {logging.INFO: \"[results.%(Parsed)s] Parsed %(message)s\",\n logging.WARNING: \"==[%(asctime)s]== %(message)s\",\n logging.ERROR: \"%(message)s\"})\n # Set up Handlers\n if self.toFile:\n fh = logging.FileHandler(self.logname)\n fh.setLevel(logging.INFO)\n fh.setFormatter(p_fmt)\n self.logger.addHandler(fh)\n if self.toConsole:\n ch = logging.StreamHandler()\n ch.setLevel(logging.DEBUG)\n ch.setFormatter(p_fmt)\n self.logger.addHandler(ch)\n # No output in case both booleans are False\n if not any([self.toConsole, self.toFile]):\n self.logger.setLevel(logging.CRITICAL)\n \n def loggerCleanUp(self):\n \"\"\"In order to avoid multiplying handlers. \"\"\"\n for i in range(len(self.logger.handlers)):\n self.logger.handlers.pop()\n \n \n def set_missing_keys(self):\n \"\"\"Set default values for keywords that have not been found.\"\"\"\n # use V.fde_expansion as an indicaotr whether or not an FDE calculation\n # was requested\n# if hasattr(self.results, V.fde_expansion):\n# if not hasattr(self.results, V.fde_isA_imported):\n# container = ParseContainer(0, False)\n# setattr(self.results, V.fde_isA_imported, container)\n# self.logger.info(\"whether FDET program imports rhoA_ref\",\n# extra={\"Parsed\":V.fde_isA_imported})\n# if not hasattr(self.results, V.fde_isB_imported):\n# container = ParseContainer(0, False)\n# setattr(self.results, V.fde_isB_imported, container)\n# self.logger.info(\"whether FDET program imports rhoB\",\n# extra={\"Parsed\":V.fde_isB_imported})\n \n if not hasattr(self.results, V.has_finished):\n container = ParseContainer(0, False)\n setattr(self.results, V.has_finished, container)\n self.logger.warning(\"Output indicates abnormal exit.\")\n \n def dump_json(self, fname=\"CCParser.json\"):\n \"\"\"Dumps contens of the CCParser.results container to a JSON file.\n \n Parameters\n ----------\n fname : str\n Filename to dump to.\n \"\"\"\n with open(fname, \"w\") as pdump:\n json.dump(self.results, pdump, cls=StructEncoder)\n self.logger.warning(\"Dumped CCParser.results to JSON file.\")\n \n def find_software(self):\n pass\n \n","sub_path":"Parser.py","file_name":"Parser.py","file_ext":"py","file_size_in_byte":8326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"66301354","text":"from __future__ import division, print_function, absolute_import\n\nimport threading\nimport copy\nimport warnings\nimport os\nimport psutil\n\nfrom podpac.core.settings import settings\nfrom podpac.core.cache.utils import CacheException, CacheWildCard\nfrom podpac.core.cache.cache_store import CacheStore\n\n_thread_local = threading.local()\n\n\nclass RamCacheStore(CacheStore):\n \"\"\"\n RAM CacheStore.\n\n Notes\n -----\n * the cache is thread-safe, but not yet accessible across separate processes\n * there is not yet a max RAM usage setting or a removal policy.\n \"\"\"\n\n cache_mode = \"ram\"\n cache_modes = set([\"ram\", \"all\"])\n _limit_setting = \"RAM_CACHE_MAX_BYTES\"\n\n def __init__(self, max_size=None, use_settings_limit=True):\n \"\"\"Summary\n \n Raises\n ------\n CacheException\n Description\n \n Parameters\n ----------\n max_size : None, optional\n Maximum allowed size of the cache store in bytes. Defaults to podpac 'S3_CACHE_MAX_BYTES' setting, or no limit if this setting does not exist.\n use_settings_limit : bool, optional\n Use podpac settings to determine cache limits if True, this will also cause subsequent runtime changes to podpac settings module to effect the limit on this cache. Default is True.\n \"\"\"\n if not settings[\"RAM_CACHE_ENABLED\"]:\n raise CacheException(\"RAM cache is disabled in the podpac settings.\")\n\n super(CacheStore, self).__init__()\n\n def _get_full_key(self, node, key, coordinates):\n return (node.json, key, coordinates.json if coordinates is not None else None)\n\n @property\n def size(self):\n process = psutil.Process(os.getpid())\n return process.memory_info().rss # this is actually the total size of the process\n\n def put(self, node, data, key, coordinates=None, update=True):\n \"\"\"Cache data for specified node.\n \n Parameters\n ------------\n node : Node\n node requesting storage.\n data : any\n Data to cache\n key : str\n Cached object key, e.g. 'output'.\n coordinates : :class:`podpac.Coordinates`, optional\n Coordinates for which cached object should be retrieved, for coordinate-dependent data such as evaluation output\n update : bool\n If True existing data in cache will be updated with `data`, If False, error will be thrown if attempting put something into the cache with the same node, key, coordinates of an existing entry.\n \"\"\"\n\n if not hasattr(_thread_local, \"cache\"):\n _thread_local.cache = {}\n\n full_key = self._get_full_key(node, key, coordinates)\n\n if not update and full_key in _thread_local.cache:\n raise CacheException(\"Cache entry already exists. Use update=True to overwrite.\")\n\n self.rem(node, key, coordinates)\n\n if self.max_size is not None and self.size >= self.max_size:\n # # TODO removal policy\n warnings.warn(\n \"Warning: Process is using more RAM than the specified limit in settings.RAM_CACHE_MAX_BYTES. No longer caching. Consider increasing this limit or try clearing the cache (e.g. podpac.utils.clear_cache(mode='RAM') to clear ALL cached results in RAM)\",\n UserWarning,\n )\n return False\n\n # TODO include insert date, last retrieval date, and/or # retrievals for use in a removal policy\n _thread_local.cache[full_key] = data\n\n def get(self, node, key, coordinates=None):\n \"\"\"Get cached data for this node.\n \n Parameters\n ------------\n node : Node\n node requesting storage.\n key : str\n Cached object key, e.g. 'output'.\n coordinates : :class:`podpac.Coordinates`, optional\n Coordinates for which cached object should be retrieved, for coordinate-dependent data such as evaluation output\n \n Returns\n -------\n data : any\n The cached data.\n \n Raises\n -------\n CacheError\n If the data is not in the cache.\n \"\"\"\n\n if not hasattr(_thread_local, \"cache\"):\n _thread_local.cache = {}\n\n full_key = self._get_full_key(node, key, coordinates)\n\n if full_key not in _thread_local.cache:\n raise CacheException(\"Cache miss. Requested data not found.\")\n\n return copy.deepcopy(_thread_local.cache[full_key])\n\n def has(self, node, key, coordinates=None):\n \"\"\"Check for cached data for this node\n \n Parameters\n ------------\n node : Node\n node requesting storage.\n key : str\n Cached object key, e.g. 'output'.\n coordinates: Coordinate, optional\n Coordinates for which cached object should be checked\n \n Returns\n -------\n has_cache : bool\n True if there as a cached object for this node for the given key and coordinates.\n \"\"\"\n\n if not hasattr(_thread_local, \"cache\"):\n _thread_local.cache = {}\n\n full_key = self._get_full_key(node, key, coordinates)\n return full_key in _thread_local.cache\n\n def rem(self, node, key=CacheWildCard(), coordinates=CacheWildCard()):\n \"\"\"Delete cached data for this node.\n \n Parameters\n ------------\n node : Node\n node requesting storage.\n key : str, optional\n Delete only cached objects with this key.\n coordinates : :class:`podpac.Coordinates`\n Delete only cached objects for these coordinates.\n \"\"\"\n\n if not hasattr(_thread_local, \"cache\"):\n _thread_local.cache = {}\n\n node_key = node.json\n\n if not isinstance(coordinates, CacheWildCard):\n coordinates_key = coordinates.json if coordinates is not None else None\n\n # loop through keys looking for matches\n rem_keys = []\n for nk, k, ck in _thread_local.cache.keys():\n if nk != node_key:\n continue\n if not isinstance(key, CacheWildCard) and k != key:\n continue\n if not isinstance(coordinates, CacheWildCard) and ck != coordinates_key:\n continue\n\n rem_keys.append((nk, k, ck))\n\n for k in rem_keys:\n del _thread_local.cache[k]\n\n def clear(self):\n _thread_local.cache = {}\n","sub_path":"podpac/core/cache/ram_cache_store.py","file_name":"ram_cache_store.py","file_ext":"py","file_size_in_byte":6500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"405139098","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n__author__ = 'Veev'\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom lxml import etree\nfrom veevspider.base import log, header_helper, proxy_helper\n\nsite = 'https://www.lianjia.com'\n# site = 'https://www.lianjia.com'\nurl = 'https://m.lianjia.com/city/'\ncity_list = list()\n\n\ndef get_city():\n global city_list\n proxy = proxy_helper.get(site)\n if not proxy:\n return\n r = requests.get(url=url, headers=header_helper.baidu_mobile(), timeout=20)\n if r.status_code == 200:\n soup = BeautifulSoup(r.text, \"lxml\")\n log.i(soup)\n li_item = soup.find_all('li', {'class': 'li_item'})\n log.i(li_item)\n for li in li_item:\n a = li.a\n city = dict()\n city['url'] = a['href']\n city['city'] = a.text\n city_list.append(city)\n log.i(city_list)\n pass\n\n\ndef save_city_to_csv():\n import csv\n with open('city' + '.csv', 'a', encoding='utf-8') as csvfile:\n fieldnames = ['url', 'city']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n\n for d in city_list:\n writer.writerow(d)\n log.i('数据写入中...')\n\n\nif __name__ == '__main__':\n get_city()\n","sub_path":"veevspider/lianjia/lianjia_city.py","file_name":"lianjia_city.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"579827616","text":"import sys\r\n\r\nfin = open('C-small-attempt0.in')\r\nfout = open('Csmall.out', 'w')\r\n\r\nT = int(fin.readline())\r\nbuf = []\r\n\r\ndef pre(upper):\r\n\tfor cur in range(1, upper):\r\n\t\tsCur = str(cur)\r\n\t\trec = set()\r\n\t\tfor i in range(len(sCur) - 1):\r\n\t\t\tsNext = sCur[i + 1:] + sCur[:i + 1]\r\n\t\t\tiNext = int(sNext)\r\n\t\t\tif(iNext > cur) and (iNext <= upper):\r\n\t\t\t\t# print cur, iNext\r\n\t\t\t\trec.add(iNext)\r\n\t\tbuf.append(rec)\r\n\t\r\n\r\npre(3000)\r\n\r\nfor idxT in range(T):\r\n\tA, B = map(int, fin.readline().split())\r\n\tans = 0\r\n\tfor cur in range(A, B):\r\n\t\tfor k in buf[cur - 1]:\r\n\t\t\tif k <= B:\r\n\t\t\t\t\tans += 1\r\n\tfout.write(\"Case #%d: %s\\n\" % (idxT + 1, str(ans)))\r\n\r\nfin.close()\r\nfout.close()\r\n","sub_path":"solutions_1483488_0/Python/AlexLin/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"393316424","text":"import argparse\nimport os\nimport numpy as np\nimport mesh_operations\nimport torch\nimport torch.nn.functional as F\nfrom config_parser import read_config\nfrom data import ComaDataset\nfrom model import Coma\nfrom psbody.mesh import Mesh, MeshViewer\nfrom torch_geometric.data import DataLoader\nfrom transform import Normalize\nimport torch_geometric.transforms as T\nimport pytorch_model_summary as pms\nfrom torch.utils.tensorboard import SummaryWriter\nfrom termcolor import colored\nimport datetime\n\ndef scipy_to_torch_sparse(scp_matrix):\n values = scp_matrix.data\n indices = np.vstack((scp_matrix.row, scp_matrix.col))\n i = torch.LongTensor(indices)\n v = torch.FloatTensor(values)\n shape = scp_matrix.shape\n\n sparse_tensor = torch.sparse.FloatTensor(i, v, torch.Size(shape))\n return sparse_tensor\n\ndef adjust_learning_rate(optimizer, lr_decay):\n\n for param_group in optimizer.param_groups:\n param_group['lr'] = param_group['lr'] * lr_decay\n\ndef save_model(coma, optimizer, epoch, train_loss, val_loss, save_checkpoint_dir):\n checkpoint = {}\n checkpoint['state_dict'] = coma.state_dict()\n checkpoint['optimizer'] = optimizer.state_dict()\n checkpoint['epoch_num'] = epoch\n checkpoint['train_loss'] = train_loss\n checkpoint['val_loss'] = val_loss\n torch.save(checkpoint, os.path.join(save_checkpoint_dir,'checkpoint_'+ str(epoch)+'.pt'))\n\ndef main(args):\n if not os.path.exists(args.conf):\n print('Config not found' + args.conf)\n\n config = read_config(args.conf)\n print(colored(str(config),'cyan'))\n\n eval_flag = config['eval']\n \n if not eval_flag: #train mode : fresh or reload\n current_log_dir = datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n current_log_dir = os.path.join('../Experiments/',current_log_dir) \n else:#eval mode : save result plys \n if args.load_checkpoint_dir:\n current_log_dir = '../Eval'\n else:\n print(colored('*****please provide checkpoint file path to reload!*****','red'))\n return\n \n print(colored('logs will be saved in:{}'.format(current_log_dir),'yellow'))\n\n if args.load_checkpoint_dir:\n load_checkpoint_dir = os.path.join('../Experiments/',args.load_checkpoint_dir,'chkpt')#load last checkpoint \n print(colored('load_checkpoint_dir: {}'.format(load_checkpoint_dir), 'red'))\n\n \n save_checkpoint_dir = os.path.join(current_log_dir , 'chkpt')\n print(colored('save_checkpoint_dir: {}\\n'.format(save_checkpoint_dir), 'yellow'))\n if not os.path.exists(save_checkpoint_dir):\n os.makedirs(save_checkpoint_dir)\n\n print('Initializing parameters')\n template_file_path = config['template_fname']\n template_mesh = Mesh(filename=template_file_path)\n print(template_file_path)\n\n visualize = config['visualize']\n lr = config['learning_rate']\n lr_decay = config['learning_rate_decay']\n weight_decay = config['weight_decay']\n total_epochs = config['epoch']\n workers_thread = config['workers_thread']\n opt = config['optimizer']\n batch_size = config['batch_size']\n val_losses, accs, durations = [], [], []\n\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n if torch.cuda.is_available():\n print(colored('\\n...cuda is available...\\n', 'green'))\n else:\n print(colored('\\n...cuda is NOT available...\\n', 'red'))\n\n ds_factors = config['downsampling_factors']\n print('Generating transforms')\n M, A, D, U = mesh_operations.generate_transform_matrices(template_mesh, ds_factors)\n\n D_t = [scipy_to_torch_sparse(d).to(device) for d in D]\n U_t = [scipy_to_torch_sparse(u).to(device) for u in U]\n A_t = [scipy_to_torch_sparse(a).to(device) for a in A]\n num_nodes = [len(M[i].v) for i in range(len(M))]\n print(colored('number of nodes in encoder : {}'.format(num_nodes),'blue'))\n\n if args.data_dir:\n data_dir = args.data_dir\n else:\n data_dir = config['data_dir']\n\n print('*** data loaded from {} ***'.format(data_dir))\n\n dataset = ComaDataset(data_dir, dtype='train', split=args.split, split_term=args.split_term)\n dataset_test = ComaDataset(data_dir, dtype='test', split=args.split, split_term=args.split_term)\n train_loader = DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=workers_thread)\n test_loader = DataLoader(dataset_test, batch_size=1, shuffle=False, num_workers=workers_thread)\n\n print(\"x :\\n{} for dataset[0] element\".format(dataset[0]))\n print(colored(train_loader,'red'))\n print('Loading Model : \\n')\n start_epoch = 1\n coma = Coma(dataset, config, D_t, U_t, A_t, num_nodes)\n\n tbSummWriter = SummaryWriter(current_log_dir)\n\n print_model_summary = False\n if print_model_summary:\n print(coma)\n\n mrkdwn = str('
    '+str(coma)+'
    ')\n tbSummWriter.add_text('tag2', mrkdwn , global_step=None, walltime=None)\n \n #write network architecture into text file \n logfile = os.path.join(current_log_dir, 'coma.txt')\n my_data_file = open(logfile, 'w')\n my_data_file.write(str(coma))\n my_data_file.close()\n\n if opt == 'adam':\n optimizer = torch.optim.Adam(coma.parameters(), lr=lr, weight_decay=weight_decay)\n elif opt == 'sgd':\n optimizer = torch.optim.SGD(coma.parameters(), lr=lr, weight_decay=weight_decay, momentum=0.9)\n else:\n raise Exception('No optimizer provided')\n\n if args.load_checkpoint_dir:\n #to load the newest saved checkpoint\n to_back = os.getcwd()\n os.chdir(load_checkpoint_dir)\n chkpt_list = sorted(os.listdir(os.getcwd()), key=os.path.getctime)\n os.chdir(to_back)\n checkpoint_file = chkpt_list[-1]\n\n logfile = os.path.join(current_log_dir, 'loadedfrom.txt')\n my_data_file = open(logfile, 'w')\n my_data_file.write(str(load_checkpoint_dir))\n my_data_file.close()\n\n print(colored('\\n\\nloading Newest checkpoint : {}\\n'.format(checkpoint_file),'red'))\n if checkpoint_file:\n checkpoint = torch.load(os.path.join(load_checkpoint_dir,checkpoint_file))\n start_epoch = checkpoint['epoch_num']\n coma.load_state_dict(checkpoint['state_dict'])\n optimizer.load_state_dict(checkpoint['optimizer'])\n #To find if this is fixed in pytorch\n for state in optimizer.state.values():\n for k, v in state.items():\n if isinstance(v, torch.Tensor):\n state[k] = v.to(device)\n coma.to(device)\n\n for i, dt in enumerate(train_loader):\n dt = dt.to(device)\n graphstr = pms.summary(coma, dt,batch_size=-1, show_input=True , show_hierarchical=False)\n if print_model_summary:\n print(graphstr)\n\n print(colored('dt in enumerate(train_loader):{} '.format(dt),'green'))\n #write network architecture into text file \n logfile = os.path.join(current_log_dir, 'pms.txt')\n my_data_file = open(logfile, 'w')\n my_data_file.write(graphstr)\n my_data_file.close()\n \n mrkdwn = str('
    '+graphstr+'
    ')\n tbSummWriter.add_text('tag', mrkdwn, global_step=None, walltime=None)\n break#for one sample only\n\n if eval_flag and args.load_checkpoint_dir:\n evaluatedFrom = 'predictedPlys_' + checkpoint_file \n output_dir = os.path.join('../Experiments/',args.load_checkpoint_dir,evaluatedFrom)#load last checkpoint \n val_loss = evaluate(coma, test_loader, dataset_test, template_mesh, device, visualize=True, output_dir=output_dir)\n print('val loss', val_loss)\n return\n\n best_val_loss = float('inf')\n val_loss_history = []\n\n for epoch in range(start_epoch, total_epochs + 1):\n print(\"Training for epoch \", epoch)\n print('dataset.len : {}'.format(len(dataset)))\n \n train_loss = train(coma, train_loader, len(dataset), optimizer, device)\n val_loss = evaluate(coma, test_loader, dataset_test, template_mesh, device, visualize=False, output_dir='')#train without visualization\n\n tbSummWriter.add_scalar('Loss/train',train_loss,epoch)\n tbSummWriter.add_scalar('Val Loss/train',val_loss,epoch)\n tbSummWriter.add_scalar('learning_rate',lr,epoch)\n\n\n print('epoch ', epoch,' Train loss ', train_loss, ' Val loss ', val_loss)\n if val_loss < best_val_loss:\n save_model(coma, optimizer, epoch, train_loss, val_loss, save_checkpoint_dir)\n best_val_loss = val_loss\n\n val_loss_history.append(val_loss)\n val_losses.append(best_val_loss)\n\n if opt=='sgd':\n adjust_learning_rate(optimizer, lr_decay)\n\n if torch.cuda.is_available():\n torch.cuda.synchronize()\n\n tbSummWriter.flush()\n tbSummWriter.close() \n\n\ndef loss_function(out,batch_y):\n return F.l1_loss(out,batch_y)\n\ndef train(coma, train_loader, len_dataset, optimizer, device):\n coma.train()\n total_loss = 0\n for btch in train_loader:\n btch = btch.to(device)\n optimizer.zero_grad()\n out = coma(btch)\n # loss = F.l1_loss(out,btch.y)\n loss = loss_function(out,btch.y)\n # print(colored(\"\\n\\nnum_graphs is {} \\n\\n\".format(btch.num_graphs),'blue'))\n total_loss += btch.num_graphs * loss.item()\n loss.backward()\n optimizer.step()\n return total_loss / len_dataset\n\n\ndef evaluate(coma , test_loader, dataset, template_mesh, device, visualize , output_dir):\n coma.eval()\n total_loss = 0\n meshviewer = MeshViewer(shape=(1, 2))\n for i, data in enumerate(test_loader):\n data = data.to(device)\n with torch.no_grad():\n out = coma(data)\n # loss = F.l1_loss(out,data.y)\n loss = loss_function(out,data.y)\n total_loss += data.num_graphs * loss.item()\n\n if visualize and i % 100 == 0:\n save_out = out.detach().cpu().numpy()\n save_out = save_out*dataset.std.numpy()+dataset.mean.numpy()\n expected_out = (data.y.detach().cpu().numpy())*dataset.std.numpy()+dataset.mean.numpy()\n result_mesh = Mesh(v=save_out, f=template_mesh.f)\n expected_mesh = Mesh(v=expected_out, f=template_mesh.f)\n meshviewer[0][0].set_dynamic_meshes([result_mesh])\n meshviewer[0][1].set_dynamic_meshes([expected_mesh])\n meshviewer[0][0].save_snapshot(os.path.join(output_dir, 'file'+str(i)+'.png'), blocking=True)\n\n result_mesh.write_ply('{}/result_{}.ply'.format(output_dir,i))\n expected_mesh.write_ply('{}/expected_{}.ply'.format(output_dir,i))\n print('result mesh and expected mesh are saved as .ply')\n \n\n return total_loss/len(dataset)\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(description='Pytorch Trainer for Convolutional Mesh Autoencoders')\n parser.add_argument('-c', '--conf', help='path of config file')\n parser.add_argument('-s', '--split', default='sliced', help='split can be sliced, expression or identity ')\n parser.add_argument('-st', '--split_term', default='sliced', help='split term can be sliced, expression name '\n 'or identity name')\n parser.add_argument('-d', '--data_dir', help='path where the downloaded data is stored')\n parser.add_argument('-cp', '--load_checkpoint_dir', help='path where checkpoints file need to be stored')\n\n args = parser.parse_args()\n\n if args.conf is None:\n args.conf = os.path.join(os.path.dirname(__file__), 'default.cfg')\n print('configuration file not specified, trying to load '\n 'it from current directory', args.conf)\n\n main(args)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"2895728","text":"import hashlib\nimport json\nimport pprint\nfrom fastecdsa import ecdsa, keys, curve, point\nimport logging\n\nclass ScroogeCoin(object):\n def __init__(self):\n # MUST USE secp256k1 curve from fastecdsa\n self.private_key, self.public_key = keys.gen_keypair(curve.secp256k1)\n \n # create the address using public key, and bitwise operation, may need hex(value).hexdigest()\n self.address = hashlib.sha256(hex(self.public_key.x << 256 | self.public_key.y).encode()).hexdigest()\n \n # list of all the blocks\n self.chain = []\n \n # list of all the current transactions\n self.current_transactions = []\n\n def create_coins(self, receivers: dict):\n \"\"\"\n Scrooge adds value to some coins\n :param receivers: {account:amount, account:amount, ...}\n \"\"\"\n tx = {\n \"sender\": self.address,\n # coins that are created do not come from anywhere\n \"location\": {\"block\": -1, \"tx\": -1},\n \"receivers\": receivers,\n }\n tx[\"hash\"] = self.hash(tx)\n tx[\"signature\"] = self.sign(tx[\"hash\"])\n self.current_transactions.append(tx)\n\n def hash(self, blob):\n \"\"\"\n Creates a SHA-256 hash of a Block\n :param block: Block\n \"\"\"\n # We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes\n # use json.dumps().encode() and specify the corrent parameters=\n # use hashlib to hash the output of json.dumps()\n hash_object = hashlib.sha256(json.dumps(blob, sort_keys=True).encode())\n return hash_object.hexdigest()\n\n def sign(self, hash_):\n # use fastecdsa library\n r, s = ecdsa.sign(hash_, self.private_key, curve=curve.secp256k1)\n return (r,s)\n\n def get_user_tx_positions(self, address):\n \"\"\"\n Scrooge adds value to some coins\n :param address: User.address\n :return: list of all transactions where address is funded\n [{\"block\":block_num, \"tx\":tx_num, \"amount\":amount}, ...]\n \"\"\"\n funded_transactions = []\n\n for block in self.chain:\n tx_index = 0\n for old_tx in block[\"transactions\"]:\n for funded, amount in old_tx[\"receivers\"].items():\n if(address == funded):\n funded_transactions.append({\"block\": block[\"index\"], \"tx\": tx_index, \"amount\": amount})\n tx_index += 1\n return funded_transactions\n\n def validate_tx(self, tx, public_key):\n \"\"\"\n validates a single transaction\n\n :param tx = {\n \"sender\" : User.address,\n ## a list of locations of previous transactions\n ## look at\n \"locations\" : [{\"block\":block_num, \"tx\":tx_num, \"amount\":amount}, ...],\n \"receivers\" : {account:amount, account:amount, ...}\n }\n\n :param public_key: User.public_key\n\n :return: if tx is valid return tx\n \"\"\"\n is_correct_hash = False\n base_tx = {\n \"sender\": tx[\"sender\"],\n \"location\": tx[\"location\"],\n \"receivers\": tx[\"receivers\"],\n }\n if self.hash(base_tx) == tx[\"hash\"]:\n is_correct_hash = True\n\n is_signed = ecdsa.verify(tx[\"signature\"], tx[\"hash\"], public_key, curve=curve.secp256k1)\n\n blockIndex = tx[\"location\"][\"block\"]\n txIndex = tx[\"location\"][\"tx\"]\n\n # what is the meaning of isFunded?\n is_funded = False\n list_of_transactions = self.chain[blockIndex][\"transactions\"]\n amount = 0\n if tx[\"sender\"] in list_of_transactions[txIndex][\"receivers\"]:\n amount = list_of_transactions[txIndex][\"receivers\"][tx[\"sender\"]]\n if amount >= 0:\n is_funded = True\n\n is_all_spent = False\n totalAmountSpent = 0\n for rec in tx[\"receivers\"].keys():\n totalAmountSpent += tx[\"receivers\"][rec]\n is_all_spent = True if totalAmountSpent == amount else False\n\n consumed_previous = False\n # for each block after blockIndex , need to verify if blockIndex and tx is not used as location\n for block in self.chain[blockIndex:]:\n for transaction in block[\"transactions\"]:\n if transaction[\"sender\"] == tx[\"sender\"]:\n if transaction[\"location\"][\"block\"] == blockIndex and transaction[\"location\"][\"tx\"] == txIndex:\n consumed_previous = True\n\n\n if (is_correct_hash and is_signed and is_funded and is_all_spent and not consumed_previous):\n return tx\n else:\n return None\n\n def mine(self):\n \"\"\"\n mines a new block onto the chain\n \"\"\"\n previous_hash = None\n if len(self.chain) != 0:\n previous_hash = self.chain[len(self.chain) - 1]\n\n block = {\n 'previous_hash': previous_hash,\n 'index': len(self.chain),\n 'transactions': self.current_transactions,\n }\n\n block[\"hash\"] = self.hash(block) # hash and sign the block\n block[\"signature\"] = self.sign(block[\"hash\"]) # signed hash of block\n self.chain.append(block)\n self.current_transactions = []\n return block\n\n def add_tx(self, tx, public_key):\n \"\"\"\n checks that tx is valid\n adds tx to current_transactions\n\n :param tx = {\n \"sender\" : User.address,\n ## a list of locations of previous transactions\n ## look at\n \"locations\" : [{\"block\":block_num, \"tx\":tx_num, \"amount\":amount}, ...],\n \"receivers\" : {account:amount, account:amount, ...},\n \"hash\": \"1233245353543\",\n \"signature\": \"ABCDEFHGISMSLDDJSKWOSMSSKSJDKFLMD\"\n }\n\n :param public_key: User.public_key\n\n :return: True if the tx is added to current_transactions\n \"\"\"\n tx = self.validate_tx(tx, public_key)\n if tx != None:\n self.current_transactions.append(tx)\n return True\n else:\n return False\n\n def show_user_balance(self, address):\n \"\"\"\n prints balance of address\n :param address: User.address\n \"\"\"\n totalBalance = 0\n for block in self.chain:\n for transaction in block[\"transactions\"]:\n if transaction[\"sender\"] == address:\n for reciever, amount in transaction[\"receivers\"].items():\n if reciever != address:\n totalBalance -= amount\n else:\n for reciever, amount in transaction[\"receivers\"].items():\n if reciever == address:\n totalBalance += amount\n print(totalBalance)\n return totalBalance\n\n\n def show_block(self, block_num):\n \"\"\"\n prints out a single formated block\n :param block_num: index of the block to be printed\n \"\"\"\n print(self.chain[block_num])\n\nclass User(object):\n def __init__(self, Scrooge):\n # MUST USE secp256k1 curve from fastecdsa\n self.private_key, self.public_key = keys.gen_keypair(curve.secp256k1)\n \n # create the address using public key, and bitwise operation, may need hex(value).hexdigest()\n self.address = hashlib.sha256(hex(self.public_key.x << 256 | self.public_key.y).encode()).hexdigest()\n \n\n def hash(self, blob):\n \"\"\"\n Creates a SHA-256 hash of a Block\n :param block: Block\n :return: the hash of the blob\n \"\"\"\n # We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes\n # use json.dumps().encode() and specify the corrent parameters\n # use hashlib to hash the output of json.dumps()\n hash_object = hashlib.sha256(json.dumps(blob, sort_keys=True).encode())\n value = hash_object.hexdigest()\n return value\n\n def sign(self, hash_):\n\n r, s = ecdsa.sign(hash_, self.private_key, curve=curve.secp256k1)\n return (r,s) # use fastecdsa library\n\n def send_tx(self, receivers, previous_tx_locations):\n \"\"\"\n creates a TX to be sent\n :param receivers: {account:amount, account:amount, ...}\n :param previous_tx_locations\n \"\"\"\n\n tx = {\n \"sender\": self.address,\n \"location\": previous_tx_locations[0],\n \"receivers\": receivers,\n }\n base_tx = tx\n # hash_value = self.hash(base_tx),\n # print(hash_value)\n hash_object = hashlib.sha256(json.dumps(base_tx, sort_keys=True).encode())\n hash_value = hash_object.hexdigest()\n signature = self.sign(hash_value)\n tx[\"hash\"] = hash_value # hash of TX\n tx[\"signature\"] = signature # signed hash of TX\n return tx\n\ndef main():\n\n # dict - defined using {key:value, key:value, ...} or dict[key] = value\n # they are used in this code for blocks, transactions, and receivers\n # can be interated through using dict.items()\n # https://docs.python.org/3/tutorial/datastructures.html#dictionaries\n\n # lists -defined using [item, item, item] or list.append(item) as well as other ways\n # used to hold lists of blocks aka the blockchain\n # https://docs.python.org/3/tutorial/datastructures.html#more-on-lists\n\n # fastecdsa - https://pypi.org/project/fastecdsa/\n # hashlib - https://docs.python.org/3/library/hashlib.html\n # json - https://docs.python.org/3/library/json.html\n\n # Example of how the code will be run\n print(\"##### Executing Main #####\")\n Scrooge = ScroogeCoin()\n users = [User(Scrooge) for i in range(10)]\n Scrooge.create_coins({users[0].address: 10, users[1].address: 20, users[3].address: 50})\n Scrooge.mine()\n\n user_0_tx_locations = Scrooge.get_user_tx_positions(users[0].address)\n first_tx = users[0].send_tx({users[1].address: 2, users[0].address:8}, user_0_tx_locations)\n print(Scrooge.add_tx(first_tx, users[0].public_key))\n Scrooge.mine()\n\n second_tx = users[1].send_tx({users[0].address:20}, Scrooge.get_user_tx_positions(users[1].address))\n print(Scrooge.add_tx(second_tx, users[1].public_key))\n Scrooge.mine()\n\n Scrooge.get_user_tx_positions(users[1].address)\n Scrooge.get_user_tx_positions(users[0].address)\n\n Scrooge.show_user_balance(users[0].address)\n Scrooge.show_user_balance(users[1].address)\n Scrooge.show_user_balance(users[3].address)\n \n test_1()\n test_2()\n test_3()\n test_4()\n\n\ndef test_1():\n\n print(\"TestCase 1: #### Mine a valid transaction that consumes coins from a previous block\")\n log = logging.getLogger('test_1')\n log.info(\"hello\")\n Scrooge = ScroogeCoin()\n users = [User(Scrooge) for i in range(10)]\n Scrooge.create_coins({users[0].address: 10, users[1].address: 10, users[2].address: 10})\n Scrooge.mine()\n\n Scrooge.create_coins({users[3].address: 10, users[4].address: 10, users[5].address: 10})\n Scrooge.mine()\n user_5_tx_locations = Scrooge.get_user_tx_positions(users[5].address)\n first_tx = users[5].send_tx({users[6].address: 10}, user_5_tx_locations)\n Scrooge.add_tx(first_tx, users[5].public_key)\n Scrooge.mine()\n assert Scrooge.show_user_balance(users[5].address) == 0\n assert Scrooge.show_user_balance(users[6].address) == 10\n print(\"#### Passed TestCase_1 #### \\n\\n\")\n\n\ndef test_2():\n\n print(\"TestCase 2:#### Create all invalid scenarios and show the error message.\")\n # Invalid scenario 1 - is_correct_hash = false\n Scrooge = ScroogeCoin()\n users = [User(Scrooge) for i in range(10)]\n Scrooge.create_coins({users[0].address: 10, users[1].address: 10, users[2].address: 10})\n Scrooge.mine()\n\n user_0_tx_locations = Scrooge.get_user_tx_positions(users[0].address)\n tx = users[0].send_tx({users[1].address: 10}, user_0_tx_locations)\n hash = tx[\"hash\"]\n tx[\"hash\"] = \"1234\"\n assert Scrooge.add_tx(tx, users[0].public_key) == False\n\n # Invalid Scenario 2 - isSigned = false\n tx[\"hash\"] = hash\n signature = tx[\"signature\"]\n tx[\"signature\"] = (1234, 12345)\n\n assert Scrooge.add_tx(tx, users[0].public_key) == False\n tx[\"signature\"] = signature\n\n # Invalid Scenario 3 - isAllSpent\n tx = users[0].send_tx({users[1].address: 5}, user_0_tx_locations)\n assert Scrooge.add_tx(tx, users[0].public_key) == False\n\n # Invalid scenario 4 - consumed previous\n tx = users[0].send_tx({users[1].address: 10}, user_0_tx_locations)\n Scrooge.add_tx(tx, users[0].public_key)\n Scrooge.mine()\n tx = users[0].send_tx({users[2].address: 10}, user_0_tx_locations)\n assert Scrooge.add_tx(tx, users[0].public_key) == False\n print(\"#### Passed TestCase_2 #### \\n\\n\")\n\n\ndef test_3():\n\n print(\"TestCase 3: #### Print a couple users balance before and after a transaction occurs between them.\")\n Scrooge = ScroogeCoin()\n users = [User(Scrooge) for i in range(10)]\n Scrooge.create_coins({users[0].address: 10, users[1].address: 10, users[2].address: 10})\n Scrooge.mine()\n\n Scrooge.show_user_balance(users[0].address)\n Scrooge.show_user_balance(users[1].address)\n Scrooge.show_user_balance(users[2].address)\n\n # Transferring 10 coins from Users[0] to Users[1]\n user_0_tx_locations = Scrooge.get_user_tx_positions(users[0].address)\n tx = users[0].send_tx({users[1].address: 10}, user_0_tx_locations)\n Scrooge.add_tx(tx, users[0].public_key)\n Scrooge.mine()\n\n assert Scrooge.show_user_balance(users[0].address) == 0\n assert Scrooge.show_user_balance(users[1].address) == 20\n assert Scrooge.show_user_balance(users[2].address) == 10\n print(\"#### Passed TestCase_3 #### \\n\\n\")\n\n\ndef test_4():\n\n print(\"TestCase 4: #### # print a block \")\n Scrooge = ScroogeCoin()\n users = [User(Scrooge) for i in range(10)]\n Scrooge.create_coins({users[0].address: 10, users[1].address: 10, users[2].address: 10})\n Scrooge.mine()\n pp = pprint.PrettyPrinter(indent=4)\n pp.pprint(Scrooge.chain)\n print(\"#### Passed TestCase_4 ####\\n\\n\")\n\n\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"Scroogecoin2/Homework_2/Scrooge_coin_assignmnet.py","file_name":"Scrooge_coin_assignmnet.py","file_ext":"py","file_size_in_byte":14172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"448420502","text":"def bucket_sort(nums, bucket_size=5):\n \"\"\"\n 桶排序\n :param nums: unsorted list\n :param bucket_size: int\n :return: sorted list\n \"\"\"\n if len(nums) <= 1:\n return nums\n max_num = max(nums)\n min_num = min(nums)\n # 计算桶的数量\n bucket_count = (max_num - min_num) // bucket_size + 1\n # 创建桶\n buckets = [[] for _ in range(bucket_count)]\n # 把数组中的元素分散到桶中\n for i in range(len(nums)):\n index = (nums[i] - min_num) // bucket_size\n buckets[index].append(nums[i])\n buckets[index] = insertion_sort(buckets[index])\n ans = []\n for bucket in buckets:\n if bucket:\n ans += bucket\n return ans\n\n\ndef insertion_sort(nums):\n \"\"\"\n 插入排序\n :param nums: List[int]\n :return: List[int]\n \"\"\"\n for i in range(1, len(nums)):\n val = nums[i]\n j = i - 1\n while j >= 0 and nums[j] > val:\n nums[j+1] = nums[j]\n j = j - 1\n nums[j+1] = val\n return nums\n\n\nif __name__ == '__main__':\n input_nums = input(\"请输入要排序的序列,以','间隔开:\")\n nums = [int(i) for i in input_nums.strip().split(',')]\n print(bucket_sort(nums))\n\n","sub_path":"sort/bucket_sort.py","file_name":"bucket_sort.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"69820094","text":"from django import forms\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.forms import UserCreationForm, UsernameField\n\nfrom .models import Account, Withdrawal, Deposit, TradingDay\n\n\nUser = get_user_model()\n\n\nclass AccountModelForm(forms.ModelForm):\n class Meta:\n model = Account\n fields = (\n # \"user\",\n \"broker\",\n \"account_number\",\n \"account_type\",\n \"leverage\",\n \"started\",\n \"platform\",\n )\n widgets = {\n 'started': forms.DateInput(format=('%d/%m/%Y'), attrs={'class': 'form-control', 'placeholder': 'Select a date', 'type': 'date'}),\n }\n\n\nclass WithdrawalModelForm(forms.ModelForm):\n class Meta:\n model = Withdrawal\n fields = (\n \"date\",\n \"amount\",\n )\n widgets = {\n 'date': forms.DateInput(format=('%d/%m/%Y'), attrs={'class': 'form-control', 'placeholder': 'Select a date', 'type': 'date'}),\n }\n\n\nclass DepositModelForm(forms.ModelForm):\n class Meta:\n model = Deposit\n fields = (\n \"date\",\n \"amount\",\n )\n widgets = {\n 'date': forms.DateInput(format=('%d/%m/%Y'), attrs={'class': 'form-control', 'placeholder': 'Select a date', 'type': 'date'}),\n }\n\n\nUser = get_user_model()\n\n\nclass TradingDayModelForm(forms.ModelForm):\n class Meta:\n model = TradingDay\n fields = (\n # \"user\",\n \"account\",\n \"lotsize\",\n \"timeframe\",\n \"profit\",\n \"date_created\",\n \"note\"\n )\n widgets = {\n 'date_created': forms.DateInput(format=('%d/%m/%Y'), attrs={'class': 'form-control', 'placeholder': 'Select a date', 'type': 'date'}),\n }\n\n def __init__(self, user, *args, **kwargs):\n super(TradingDayModelForm, self).__init__(*args, **kwargs)\n self.fields['account'].queryset = Account.objects.filter(user=user)\n\n\nclass CustomUserCreationForm(UserCreationForm):\n email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')\n\n class Meta:\n model = User\n fields = (\"username\", \"email\")\n field_classes = {'username': UsernameField}\n\n\nclass CsvUploadForm(forms.Form):\n def __init__(self, user, *args, **kwargs):\n super(CsvUploadForm, self).__init__(*args, **kwargs)\n self.fields['account'].queryset = Account.objects.filter(user=user)\n\n account = forms.ModelMultipleChoiceField(queryset=None)\n file = forms.FileField(label='Select csv file', widget=forms.FileInput(attrs={'accept': '.csv'}))\n check_delete_account_data = forms.BooleanField(required=False, label='Delete previous account data? (Tradingdays, withdrawals, deposits)')\n","sub_path":"accounts/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"338502615","text":"from __future__ import print_function,division\r\nimport tensorflow as tf\r\n\r\nsess = tf.InteractiveSession()\r\n\r\n# sigmoid function\r\ndef nonlin(x, deriv=False):\r\n\tif(deriv==True):\r\n\t\treturn x*(1-x)\r\n\treturn 1/(1+tf.exp(-x))\r\n\r\n# input dataset: 4x3\r\nX = tf.constant([\t[0,0,1],\r\n\t\t\t\t\t[0,1,1],\r\n\t\t\t\t\t[1,0,1],\r\n\t\t\t\t\t[1,1,1]\t])\r\n\r\n# output dataset: 4x1\r\ny = tf.transpose(tf.constant([\t[0,0,1,1]\t]))\r\n\r\n# Synapse / Weights\r\n# One Line:\r\n# \tsyn0 = tf.subtract( tf.multiply( tf.constant(2.0), tf.random_uniform((3,1)) ), tf.constant(1.0))\r\n\r\n# Constants\r\none = tf.constant(1.0)\r\ntwo = tf.constant(2.0)\r\n\r\n# Random Matrix\r\nmat0 = tf.random_uniform((3,1))\r\n\r\n# Multiply\r\nprod0 = tf.multiply(two, mat0)\r\n\r\n# Synapse\r\n# Subtract\r\nsyn0 = tf.subtract(prod0, one)\r\n\r\nfor i in range(10000):\r\n\r\n\t# forward propagation\r\n\tl0 = tf.cast(X, tf.float32)\t\t# need to change data type from int to float\r\n\tsyn_Matrix = tf.matmul(l0, syn0)\r\n\tl1 = nonlin(syn_Matrix)\r\n\r\n\t# error: by how much the model missed\r\n\ty_float = tf.cast(y, tf.float32)\r\n\tl1_error = tf.subtract(y_float, l1)\r\n\r\n\t# multiply how much we missed by the slopeof the sigmoid at the values in l1\r\n\tl1_delta = tf.matmul(l1_error, nonlin(l1,True))\r\n\r\n\t# update weights\r\n\tupdate = tf.matmul(tf.transpose(l0),l1_delta)\r\n\tsyn0 = tf.add(syn0, update)\r\n\r\n\r\n\r\n\r\n\r\n\r\nsess.close()","sub_path":"scratch/traskML_1.py","file_name":"traskML_1.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"312362788","text":"import pandas\nimport numpy as np\nfrom sklearn import svm\nfrom sklearn import feature_selection\nfrom sklearn .ensemble import ExtraTreesClassifier\nimport scipy as sp\nimport pickle, random\n\nnp.set_printoptions(threshold=np.nan)\nrepeat=20\ncutoff=2\nrandomPerm=0.5\n\ndf=pandas.read_csv('Text.csv')\ndfInq=pandas.read_csv('InqProf.csv')\ndfNon=pandas.read_csv('nonText.csv')\ndfGen=pandas.read_csv('GenInq.csv')\ndfNon.drop(labels=['IE', 'NS', 'TF', 'PJ'], axis=1, inplace=True)\n\n\n#df=df.join(dfInq, lsuffix='_left')\ndf=df.merge(dfNon, on=\"profile\")\n#df=df.merge(dfGen, on=\"profile\")\n\n\n#df=df[np.isfinite(df['NNP'])]\n#df.to_csv('temp.csv')\n\ndf=df.fillna(0)\ndf.drop(labels=['Unnamed: 0_x', 'profile'], axis=1, inplace=True)\n\ndf.to_csv('temp.csv')\narr=np.array(df)\n\n# fast=pickle.load(open(\"FastTextPreTrained.pickle\", \"rb\"))\n# arr=np.append(arr, fast, axis=1)\nprint(np.shape(arr))\n\nY=arr[:, 0]\nYtest=arr[:, 0]\nX=arr[:, 6:]\nXtest=arr[400:, 6:]\n\n\nmaxi=0\nmaxVarOrder=None\noldArray=0\noldResult=0\nswapped=False\n\nfinal=np.zeros((np.shape(X)[1], repeat))\nfor j in range(repeat):\n\tprint(j)\n\n\tarr=np.array(df)\n\n\t#fast=pickle.load(open(\"FastTextPreTrained.pickle\", \"rb\"))\n\t#arr=np.append(arr, fast, axis=1)\n\tnp.random.shuffle(arr)\n\n\tY=arr[:1000, 0].astype(int)\n\tYtest=arr[1000:, 0].astype(int)\n\tX=arr[:1000, 6:].astype(float)\n\tXtest=arr[1000:, 6:].astype(float)\n\n\t#Calculate the base error\n\tclf=svm.SVC()\n\tcolBase=X.T[0]\n\tcolBase=colBase.reshape(-1,1)\n\tclf.fit(colBase,Y)\n\tcolBaseTest=Xtest.T[0].reshape(-1,1)\n\tdomin=clf.predict(colBaseTest)\n\tbase=np.sum(np.where(domin==Ytest, 0, 1))\n\ti=0\n\t#Calculate the difference error for each of the features\n\tfor col in X.T:\n\t\t#cor=sp.stats.pearsonr(col, Y)[0]\n\t\t#Add \n\t\tclf=svm.SVC()\n\t\tcol=col.reshape(1000,1)\n\t\tcol=np.append(np.array(colBase), np.array(col), axis=1)\n\t\tclf.fit(col,Y)\n\t\t#Test\n\t\tXTest1=Xtest.T[0].reshape(-1,1)\n\t\tXTest2=Xtest.T[i].reshape(-1,1)\n\t\tcolTest=np.append(XTest1, XTest2, axis=1)\n\t\tdomin=clf.predict(colTest)\n\t\terreurs=np.sum(np.where(domin==Ytest, 0, 1))\n\t\terreurs=erreurs-base\n\t\tfinal[i][j]=(erreurs)\n\t\ti+=1\n\t\n\nprint(\"------------------\")\nfinal=np.mean(final, axis=1)\nprint(final)\nfeatures=np.argsort(final)\nfeatures+=6\nprint(features)\n\n\nwhile(True):\n\tresults=np.zeros((len(features), repeat))\n\n\tfor j in range(repeat):\n\t\tprint(\"repetition \", j)\n\n\t\tfor i in range(len(features)):\n\n\n\t\t\tarr=np.array(df)\n\n\t\t\t# fast=pickle.load(open(\"FastTextPreTrained.pickle\", \"rb\"))\n\t\t\t# arr=np.append(arr, fast, axis=1)\n\t\t\tnp.random.shuffle(arr)\n\n\t\t\tY=arr[:1000, 0].astype(int)\n\t\t\tYtest=arr[1000:, 0].astype(int)\n\t\t\tX=arr[:1000, features[:i+1]].astype(float)\n\t\t\tXtest=arr[1000:, features[:i+1]].astype(float)\n\t\t\tclf=svm.SVC()\n\n\t\t\tclf.fit(X,Y)\n\n\t\t\t#error on train\n\t\t\tdomin=clf.predict(X)\n\t\t\terreurs=np.sum(np.where(domin==Y, 0, 1))\n\n\t\t\t#error on test\n\t\t\tdomin=clf.predict(Xtest)\n\t\t\terreurs=np.sum(np.where(domin==Ytest, 0, 1))\n\t\t\tresults[i,j]=1.0-float(erreurs)/len(Ytest)\n\n\n\tfinal=np.mean(results, axis=1)\n\t#If was permutated, check if new result is better\n\tif(swapped):\n\t\tif(final[index]maxi):\n\t\tmaxi=maxTemp\n\t\tmaxVarOrder=features\n\t\tpickle.dump(maxVarOrder, open('featuresOrder.pickle', 'wb'))\n\tprint(final)\n\tprint(maxi)\n\n\t#Calculate new order\n\ttemp=final[cutoff:]\n\torder=np.argsort(-temp)\n\tfet=features[cutoff:]\n\tfeatures=np.append(features[:cutoff], fet[order])\n\n\n\n\n\t#Chance of random permutation of the first variables\n\ttemp=random.random()\n\tif(temp divergence:\n best_embedding = tsne_output\n return best_embedding\n\n def format_data(self, tsne_output):\n tsne_data = []\n for product in self.products_used:\n x = tsne_output[product][0]\n y = tsne_output[product][1]\n rows = self.product_info.loc[self.product_info['j'] == product].head(1)\n category = rows['category'].values[0]\n tsne_data.append(([x, y, category, product]))\n return pd.DataFrame(tsne_data, columns=['x', 'y', 'c', 'j'])\n\n def create_scatterplot(self, tsne_df, plot_file_name):\n # Function taken from: https://github.com/sbstn-gbl to enable comparison of the plots made\n plot_data = [go.Scatter(x=tsne_df['x'].values,\n y=tsne_df['y'].values,\n text=[\n 'category = %d
    product = %d' % (x, y)\n for (x, y) in zip(tsne_df['c'].values, tsne_df['j'].values)\n ],\n hoverinfo='text',\n mode='markers',\n marker=dict(\n size=14,\n color=tsne_df['c'].values,\n colorscale='Jet',\n showscale=False\n )\n )\n ]\n legend = go.layout.Legend()\n plot_layout = go.Layout(\n width=800,\n height=600,\n margin=go.layout.Margin(l=0, r=0, b=0, t=0, pad=4),\n hovermode='closest',\n legend=legend,\n showlegend=True\n )\n\n # plot\n fig = go.Figure(data=plot_data, layout=plot_layout)\n iplot(fig)\n\n plt.show()\n\n def category_level_similarity(self, num_product_in_category, vectors):\n category_to_assign = 0\n category_product = defaultdict(list)\n p2v_vectors = self.get_input_weights()\n acc = 0\n category = 0\n average_vectors = {}\n summed_vec = np.zeros(vectors.shape[1])\n for product in self.products_used:\n summed_vec += vectors[product]\n if acc == num_product_in_category - 1:\n acc = 0\n average_vectors[category] = summed_vec / num_product_in_category\n category += 1\n summed_vec = np.zeros(vectors.shape[1])\n else:\n acc += 1\n return average_vectors\n\n @staticmethod\n def similarity_matrix(average_vectors, filename):\n num_cat = len(average_vectors.keys())\n similarity = np.zeros((num_cat, num_cat))\n for i in range(num_cat):\n for j in range(num_cat):\n similarity[i][j] = average_vectors[i] @ average_vectors[j]\n create_html(similarity, filename)\n f = plt.figure(figsize=(19, 15))\n plt.matshow(similarity, fignum=f.number)\n plt.xticks(range(similarity.shape[1]), fontsize=14, rotation=90)\n plt.yticks(range(similarity.shape[1]), fontsize=14)\n cb = plt.colorbar()\n cb.set_clim(-1, 1)\n cb.ax.tick_params(labelsize=14)\n plt.show()\n\n def co_occurence_matrix(self, average_vectors_co, average_vectors_ce, filename):\n num_cat = len(average_vectors_ce.keys())\n similarity = np.zeros((num_cat, num_cat))\n for i in range(num_cat):\n for j in range(i, num_cat):\n similarity[i][j] = average_vectors_ce[j] @ average_vectors_co[i]\n similarity[j][i] = average_vectors_ce[j] @ average_vectors_co[i]\n\n create_html(similarity, filename)\n f = plt.figure(figsize=(19, 15))\n plt.matshow(similarity, fignum=f.number)\n plt.xticks(range(similarity.shape[1]), fontsize=14, rotation=90)\n plt.yticks(range(similarity.shape[1]), fontsize=14)\n cb = plt.colorbar()\n cb.ax.tick_params(labelsize=14)\n plt.show()\n\n\n def bench_marks(self, data):\n x_y_df = data.set_index(['j', 'c'])\n\n x_y_array = x_y_df.to_numpy()\n true_clusters = data['c'].to_numpy()\n\n clustering = sklearn.cluster.KMeans(n_clusters=len(np.unique(true_clusters)), n_init=30)\n kmean_pred = clustering.fit_predict(x_y_df.values)\n s_score = sklearn.metrics.silhouette_score(X=x_y_array, labels=true_clusters)\n adjusted_mis = sklearn.metrics.adjusted_mutual_info_score(\n labels_true=true_clusters,\n labels_pred=kmean_pred,\n average_method='arithmetic'\n )\n nn_score = self.get_hitrate(data, 14)\n\n return s_score, adjusted_mis, nn_score\n\n def get_hitrate(self, x, num_nn):\n xy = x[['x', 'y']].to_numpy()\n j = x['j'].to_numpy()\n c = x['c'].to_numpy()\n\n distances = scipy.spatial.distance.cdist(xy, xy)\n distance_df = pd.DataFrame({\n\n 'j': np.repeat(j, len(j)),\n\n 'c': np.repeat(c, len(c)),\n\n 'j2': np.tile(j, len(j)),\n\n 'c2': np.tile(c, len(c)),\n\n 'd': distances.flatten()\n\n })\n distance_df = distance_df[distance_df['j'] != distance_df['j2']]\n\n distance_df = distance_df.sort_values('d')\n\n distance_df['rank_d'] = distance_df.groupby('j').cumcount()\n\n nn = distance_df[distance_df['rank_d'] < num_nn]\n score = float(sum(nn['c'] == nn['c2'])) / nn.shape[0]\n\n return score\n\n def create_histogram(self):\n correlation = self.product_info.corr()\n self.product_info.hist(column='j')\n plt.show()\n\n\ndef main():\n model_used = 'simulated_test.h5'\n data_dir = 'large_data'\n data_file = 'simulated_data'\n product_used = r'large_data\\center_products_simulated'\n performance_logger = evaluatePerformance(model=model_used, product_file_dir=data_dir,\n product_file_loc=data_file,\n product_used_loc=product_used)\n weights, sorted_products = performance_logger.get_input_weights()\n #co_occurence_weights, sorted_products = performance_logger.get_input_weights(type_weights='context_embedding')\n random_weights = performance_logger.simulate_random_weights(0, .2, weights.shape[0], weights.shape[1])\n\n print(\"Starting on center weights\")\n tsne_ce = performance_logger.get_tsne_embedding(weights, official_run=True)\n dank_df = performance_logger.format_data(tsne_ce)\n s_score, info_score, nn_score = performance_logger.bench_marks(dank_df)\n av_vec_ce = performance_logger.category_level_similarity(15, weights)\n performance_logger.similarity_matrix(av_vec_ce, 'similarity_correlation.html')\n\n print(\"Starting on random weights\")\n tsne_r = performance_logger.get_tsne_embedding(random_weights)\n dank_df_r = performance_logger.format_data(tsne_r)\n s_score_r, info_score_r, nn_score_r = performance_logger.bench_marks(dank_df_r)\n av_vec = performance_logger.category_level_similarity(15, random_weights)\n performance_logger.similarity_matrix(av_vec, 'random_weights.html')\n \"\"\"\n print(\"Starting on context embeddings\")\n tsne_co = performance_logger.get_tsne_embedding(co_occurence_weights, official_run=True)\n dank_df_c = performance_logger.format_data(tsne_co)\n s_score_c, info_score_c, nn_score_c = performance_logger.bench_marks(dank_df_c)\n av_vec_co = performance_logger.category_level_similarity(15, co_occurence_weights)\n performance_logger.co_occurence_matrix(av_vec_co, av_vec_ce, 'co-occurence_correlation.html')\"\"\"\n\n print(\"Metrics for trained weights, s_score: {}, adj_info: {}, nn_score: {}\".format(s_score, info_score,\n nn_score))\n print(\"Metrics for random weights, s_score: {}, adj_info: {}, nn_score: {}\".format(s_score_r, info_score_r,\n nn_score_r))\n #print(\"Metrics for contex weights, s_score: {}, adj_info: {}, nn_score: {}\".format(s_score_c, info_score_c, nn_score_c))\n\n performance_logger.create_scatterplot(dank_df, 'test')\n #performance_logger.create_scatterplot(dank_df_c, 'test')\n\n def create_correlation_matrix():\n PATH = get_filepath('resources', 'correlation_matrix_excel.xlsx')\n data = pd.read_excel(PATH, header=None)\n correlation_matrix = data.to_numpy()\n\n f = plt.figure(figsize=(19, 15))\n plt.matshow(correlation_matrix, fignum=f.number)\n plt.xticks(range(correlation_matrix.shape[1]), fontsize=14, rotation=90)\n plt.yticks(range(correlation_matrix.shape[1]), fontsize=14)\n cb = plt.colorbar()\n cb.ax.tick_params(labelsize=14)\n plt.show()\n\n create_correlation_matrix()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"performance_metrics.py","file_name":"performance_metrics.py","file_ext":"py","file_size_in_byte":12320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"481222358","text":"n = int(raw_input())\nwhile ( n > 0 ):\n n = n - 1\n numElements = int(raw_input())\n arr = raw_input().split()\n if ( len(arr) is 1 ):\n print(long(arr[0]))\n continue\n arr = map(long,arr)\n arr.sort()\n diff = []\n for i in range(0, len(arr) - 1):\n diff.append(arr[i+1] - arr[i])\n print(min(diff))\n","sub_path":"horses.py","file_name":"horses.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"288726021","text":"# -*- coding: utf-8 -*-\n\n#import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport re\n\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.svm import SVC\nfrom pandas.tools.plotting import scatter_matrix\nfrom sklearn import linear_model\n\nimport urllib.request\nimport json\n\ndef get_lat_log_from_addr(addr):\n\n lat = -1\n lon = -1\n is_ok = False\n\n #set proxy\n #proxy_support = urllib.request.ProxyHandler({'https': 'https://proxy:3128'})\n #opener = urllib.request.build_opener(proxy_support)\n #urllib.request.install_opener(opener)\n\n # http request\n geo = r'https://geocode-maps.yandex.ru/1.x/?geocode={0}&format=json&results=1'\\\n .format(urllib.parse.quote_plus('\"' + addr + '\"'))\n geo_ans = urllib.request.urlopen(geo).read()\n\n #parse ans\n json_ans = json.loads(geo_ans.decode(\"utf-8\"))\n feature_lst = json_ans[\"response\"][\"GeoObjectCollection\"][\"featureMember\"]\n if len(feature_lst) > 0:\n str_coord = feature_lst[0][\"GeoObject\"][\"Point\"]['pos']\n words = str.split(str_coord)\n if len(words) > 1:\n lon = float(words[0])\n lat = float(words[1])\n is_ok = True\n\n return lat , lon, is_ok\n\ndef clear_str_city(s):\n return s.lower().replace(\"г.\", \"\")\n\ndef str_to_float(s):\n s = re.sub('[^0-9]+', '', s)\n if s:\n return float(s) \n else:\n return None\n\ndef process(df):\n data = []\n for index, row in df.iterrows():\n s_addr = str (clear_str_city(row['_CITY_'])) + \" \" + str (clear_str_adrs(row['_ADRS_']))\n lat, lon, is_ok = get_lat_log_from_addr(s_addr)\n print (\"{:4d} | {:4f} : {:4f} |\".format(index, lat, lon))\n\n data.append({ '_ID_' : row['_ID_'],\n '_AREA_' : row['_TTL_S_'],\n '_LAT_' : lat,\n '_LON_' : lon,\n '_CITY_' : row['_CITY_'], \n '_ADRS_' : row['_ADRS_']})\n\n df_out = pd.DataFrame(data, columns=['_ID_', '_AREA_', '_LAT_', '_LON_', '_CITY_', '_ADRS_'])\n df_out.to_csv(\"..\\ver3\\test.csv\", encoding='utf-8', index = False)\n\n\ndef clear_str_adrs(s):\n return s.replace('\\n', \" \", 3).replace('\\r', \" \", 3)\n\ndef process2(df):\n data = []\n for index, row in df.iterrows():\n s_addr = (clear_str_adrs(str(row['_ADRS_'])))\n data.append({ '_ID_' : row['_ID_'],\n '_ADRS_' : clear_str_adrs(str (row['_ADRS_']))})\n\n df_out = pd.DataFrame(data, columns=['_ID_', '_ADRS_'])\n df_out.to_csv(\"..\\ver3\\test.csv\", encoding='utf-8', index = False)\n\ndef main():\n\n # load train data\n # _ID_,_CITY_,_ADRS_,_OBJ_TYPE_,_TTL_S_,_F1_S_,_F1_U_,_FC_S_,_FC_U_,_F0_S_,_F0_U_,_FA_S_,_FA_U_,_F2_S_,_F2_U_,_F3_S_,_F3_U_,_AREA_,_CHARACT_,_LINE_,_METRO_,_ROUND_,_FOOT_TRAF_,_IS_PRKNG_,_IS_WIN_,_IS_SEP_ENT_,_IS_VENT_,_DECOR_,_IS_COM_,_F1_H_,_DATE_\n #data = pd.read_csv(r'dataset\\champ1_test.csv')\n #print (data['_CITY_'][2642])\n #print (data['_ADRS_'][2643])\n #process2(data)\n\n df_test = pd.read_csv(r'..\\ver3\\test.csv', na_values='?')\n data_numerical_test = df_test[['_AREA_', '_LAT_', '_LON_']]\n data_test = pd.DataFrame(data_numerical_test, dtype=float)\n\n print (np.isnan(data_test['_AREA_']).any())\n print (np.argwhere(np.isnan(data_test['_AREA_'])))\n\n# print(data_test.describe())\n \n\nif __name__ == '__main__':\n main()","sub_path":"src/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"421270191","text":"def generalCountingSort(array, array_size):\r\n #create a empty list to add the sorted values in\r\n empty_list = [None for x in range(array_size)]\r\n\r\n\r\n #for each element of arr\r\n #set a current number\r\n for i in range(array_size):\r\n current_number = array[i]\r\n count = 0\r\n\r\n #this will count the total number of elements that are less than the current number\r\n #add 1 to count for each number that is less than it to determine its final position\r\n for j in range(array_size):\r\n if array[j] < current_number:\r\n count += 1\r\n\r\n #add the current number to its correct place in the new empty list\r\n #this loop will check if there is a number at the current count spot and if so move it up\r\n while empty_list[count] == current_number:\r\n count += 1\r\n empty_list[count] = current_number\r\n\r\n #this will return the newly sorted array\r\n return empty_list\r\n\r\n\r\n\r\n\r\n# Below line read inputs from user using map() function\r\nprint(\"\\nThese values have to be seperated by a space, e.g. 10 22 33 55 44\")\r\narr = list(map(int,input(\"Enter the numbers : \").strip().split()))\r\n\r\n#get the length of the user input array.\r\nn = len(arr)\r\n#This line will call the countingSort function, enter the list + listsize into the function\r\nprint(generalCountingSort(arr, n))\r\ninput(\"\")\r\n","sub_path":"Q1. Bubble and counting sort/general_counting_sort.py","file_name":"general_counting_sort.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"276105365","text":"from django.views.generic import TemplateView, View\nfrom django.shortcuts import redirect, render, get_object_or_404\nfrom django.core.paginator import Paginator\nfrom django.contrib.auth.mixins import UserPassesTestMixin, LoginRequiredMixin\nfrom social.forms import SocialPostForm\nfrom social.models import Image, SocialPost, SocialComment\n\n\nclass HomeView(View):\n def get(self, request, *args, **kwargs):\n context = {\n }\n return render(request, 'pages/index.html', context)\n\n def post(self, request, *args, **kwargs):\n logged_in_user = request.user\n posts = SocialPost.objects.filter(\n author__profile__followers__in=[logged_in_user.id]\n ).order_by('-create_on')\n\n form = SocialPostForm(request.POST, request.FILES)\n files = request.FILES.getlist('image')\n\n\n if form.is_valid():\n new_post = form.save(commit=False)\n new_post.author = logged_in_user\n new_post.save()\n\n for f in files:\n img = Image(image=f)\n img.save()\n new_post.image.add(img)\n\n context = {\n 'form': form,\n 'posts': posts,\n }\n return render(request, 'pages/index.html', context)\n \n","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"376553886","text":"\nimport os\nimport numpy as np\nimport glob\nimport skimage.io as io\nimport matplotlib.pyplot as plt\nfrom scipy.io import loadmat\ndef load_landmark(file_name):\n\tfi = open(file_name,'r')\n\tline = fi.readline()\n\tlandmarks = line[1:]\n\tlandmarks = np.array(landmarks.split()).astype(np.float)\n\t# print landmarks\n\tlandmarks = landmarks.reshape((5,2))\n\treturn landmarks\n\ndef load_landmark_image_mapping(file_name):\n\tfi = open(file_name,'r')\n\tlines = fi.readlines()\n\tlines = lines[1:]\n\tmapping = {}\n\tfor l in lines:\n\t\tl = l.strip('\\n')\n\t\tstrs = l.split(' ')\n\t\tmapping[strs[1]] = strs[0]\n\t# print mapping\n\treturn mapping\n\ndef plot_sample(image,landmarks,axis):\n\taxis.imshow(image,cmap=plt.gray())\n\tif landmarks is not None:\n\t\taxis.scatter(landmarks[:,0],landmarks[:,1],marker = 'x')\n\t# for i in range(landmarks.shape[0]):\n\t# \taxis.text(landmarks[i,0],landmarks[i,1],str(i+1))\n\ndef crop_face_image(image,landmarks):\n\tcenterx = np.mean(landmarks[:,0])\n\tcentery = np.mean(landmarks[:,1])\n\n\tleft_eye_x = landmarks[0,0]\n\tleft_eye_y = landmarks[0,1]\n\n\tright_eye_x = landmarks[1,0]\n\tright_eye_y = landmarks[1,1]\n\n\tleft_mounth_x = landmarks[3,0]\n\tleft_mounth_y = landmarks[3,1]\n\n\tdis1 = np.sqrt(np.square(left_eye_x - right_eye_x)+np.square(left_eye_y - right_eye_y))\n\tdis2 = np.sqrt(np.square(left_eye_x - left_mounth_x)+np.square(left_eye_y - left_mounth_y))\n\tsz = 2*np.max([dis1,dis2])\n\n\treturn image[centery-sz/2:centery+sz/2,centerx-sz/2:centerx+sz/2]\n\nlist_file = 'val_label.lst'\nlist_file2 = 'val_label_crop_face2.lst'\n\nlandmark_directory = os.path.join('pointfile','val')\noutput_image_directory = 'Val_crop_face2'\nfi = open(list_file,'r')\nfo = open(list_file2,'w')\nmapping = load_landmark_image_mapping('val.lst')\nlines = fi.readlines()\n\n\nfor l in lines:\n\timage_path = l.split(' ')[0]\n\tlabel = l.split(' ')[1].strip('\\n')\n\tstrs = image_path.split(os.sep)\n\tlandmark_file_name = os.path.join(landmark_directory,mapping[image_path]+'.txt')\n\tlandmarks = load_landmark(landmark_file_name)\n\t# print landmarks\n\n\timage = io.imread(image_path)\n\timage = crop_face_image(image,landmarks)\n\n\timage_file_name = image_path.split(os.sep)[-1]\n\tio.imsave(os.path.join(output_image_directory,image_file_name),image)\n\tfo.write(os.path.join(output_image_directory,image_file_name)+' '+label+'\\n')\n\t# plot_sample(image,landmarks,plt)\n\t\n\t# plt.show()\nfo.close()","sub_path":"SFEW/crop_face.py","file_name":"crop_face.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"68891926","text":"from django.http import HttpResponse\nfrom django.core.mail import send_mail\nfrom django.template.loader import render_to_string\nfrom django.conf import settings\n\nfrom .models import Order, OrderLineItem\nfrom stock.models import Item\nfrom users.models import UserProfile\n\nimport json\nimport time\n\n\nclass StripeWebhookHandler:\n ''' Class to handle strip webhooks '''\n\n def __init__(self, request):\n self.request = request\n\n def _send_order_confirmation(self, order):\n ''' send the confirmation email to the user '''\n users_email = order.email\n subject = render_to_string(\n \"checkout/email_confirmation/confirmation_subject.txt\",\n {\"order\": order})\n body = render_to_string(\n \"checkout/email_confirmation/confirmation_body.txt\",\n {\"order\": order,\n \"contact_email\": settings.DEFAULT_EMAIL_ADDRESS\n })\n\n send_mail(\n subject,\n body,\n settings.DEFAULT_EMAIL_ADDRESS,\n [users_email]\n )\n\n def handle_stripe_event(self, event):\n ''' takes the stripe event and returns a\n http response to indicate its been recieved '''\n return HttpResponse(\n content=f\"Unhandled webhook recieved : {event['type']}\",\n status=200\n )\n\n def handle_payment_intent_failed(self, event):\n ''' handles a failed payment intent '''\n\n return HttpResponse(\n content=f\"Webhook recieved : {event['type']}\",\n status=200\n )\n\n def handle_payment_intent_succeded(self, event):\n ''' handles a suceeded payment intent webhook from stripe '''\n intent = event.data.object\n\n payment_intent_id = intent.id\n cart = intent.metadata.cart\n save_info = intent.metadata.save_info\n\n billing_details = intent.charges.data[0].billing_details\n delivery_details = intent.shipping\n grand_total = round(intent.charges.data[0].amount/100, 2)\n\n for field, value in delivery_details.address.items():\n if value == \"\":\n delivery_details.address[field] = None\n\n user_profile = None\n username = intent.metadata.username\n if username != \"AnonymousUser\":\n user_profile = UserProfile.objects.get(\n user__username=username)\n if save_info:\n user_profile.user_contact_number = delivery_details.phone\n user_profile.user_street_address_1 = \\\n delivery_details.address.line1\n user_profile.user_street_address_2 = \\\n delivery_details.address.line2\n user_profile.user_town_or_city = \\\n delivery_details.address.city,\n user_profile.user_county = delivery_details.address.state\n user_profile.user_eircode = \\\n delivery_details.address.postal_code\n user_profile.user_country = delivery_details.address.country\n user_profile.save()\n\n order_exists = False\n attempt = 1\n\n while attempt <= 5:\n try:\n order = Order.objects.get(\n full_name__iexact=delivery_details.name,\n email__iexact=billing_details.email,\n contact_number__iexact=delivery_details.phone,\n street_address_1__iexact=delivery_details.address.line1,\n street_address_2__iexact=delivery_details.address.line2,\n town_or_city__iexact=delivery_details.address.city,\n county__iexact=delivery_details.address.state,\n eircode__iexact=delivery_details.address.postal_code,\n country__iexact=delivery_details.address.country,\n grand_total=grand_total,\n original_cart=cart,\n stripe_payment_intent_id=payment_intent_id,\n )\n order_exists = True\n break\n\n except Order.DoesNotExist:\n attempt += 1\n time.sleep(1)\n\n if order_exists:\n self._send_order_confirmation(order)\n return HttpResponse(\n content=f\"Webhook recieved : {event['type']} | SUCCESS: \\\nVerified order is in database.\", status=200)\n\n else:\n order = None\n try:\n order = Order.objects.create(\n full_name=delivery_details.name,\n user_profile=user_profile,\n email=billing_details.email,\n contact_number=delivery_details.phone,\n street_address_1=delivery_details.address.line1,\n street_address_2=delivery_details.address.line2,\n town_or_city=delivery_details.address.city,\n county=delivery_details.address.state,\n eircode=delivery_details.address.postal_code,\n country=delivery_details.address.country,\n grand_total=grand_total,\n original_cart=cart,\n stripe_payment_intent_id=payment_intent_id,\n )\n for item_id, quantity in json.loads(cart).items():\n item = Item.objects.get(id=item_id)\n # cretes the line items\n order_line_item = OrderLineItem(\n order=order,\n item=item,\n quantity=quantity,\n )\n order_line_item.save()\n except Exception as e:\n if order:\n order.delete()\n return HttpResponse(content=\"Webhook recieved \\\n: {event['type']} | ERROR : {e}\", status=500)\n\n self._send_order_confirmation(order)\n return HttpResponse(\n content=f\"Webhook recieved : {event['type']} | \\\n SUCCESS: Created order in webhook\", status=200)\n","sub_path":"checkout/webhook_handler.py","file_name":"webhook_handler.py","file_ext":"py","file_size_in_byte":6099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"484661359","text":"import PIL\nimport PIL.ImageShow\nimport aiohttp # koyashie fix unused / duplicate imports\nimport discord\nimport os\nfrom PIL import Image, ImageFont, ImageDraw\nfrom io import BytesIO\n\n\nclass ImageManager:\n def __init__(self, bot, txt_colour=None, card_back=1, custom_card_back: bool = False):\n self.bot = bot\n self.txt_colour = (80, 92, 112) if not txt_colour else txt_colour\n self.default_bg = self.fetch_card_back(card_back, custom_card_back)\n self.online = self.load_asset('online.png')\n self.offline = self.load_asset('offline.png')\n self.idle = self.load_asset('idle.png')\n self.dnd = self.load_asset('dnd.png')\n self.streaming = self.load_asset('streaming.png')\n self.font = self.load_asset('font.ttf')\n self.bk = self.load_asset('grey.png')\n\n @classmethod\n def load_asset(cls, name):\n return os.path.join(os.path.dirname(__file__), 'assets', name)\n\n @classmethod\n def fetch_card_back(cls, card_back, custom_card_back):\n if custom_card_back:\n return card_back\n\n if card_back in [1, 2, 3]:\n return cls.load_asset(f\"{card_back}.png\")\n\n @classmethod\n async def make_request(cls, url):\n async with aiohttp.ClientSession() as session:\n async with session.get(str(url)) as response:\n return await response.read()\n\n @classmethod\n async def convert_image(cls, url):\n info = await cls.make_request(url)\n return PIL.Image.open(BytesIO(info)).convert('RGBA')\n\n @staticmethod\n def create_card():\n \"\"\"Solely for testing | Creates a blank image\"\"\"\n img = PIL.Image.new('RGB', (900, 238), color=(91, 95, 102))\n\n @classmethod\n def human_format(cls, num):\n original_num = num\n\n num = float('{:.3g}'.format(num))\n magnitude = 0\n matches = ['', 'K', 'M', 'B', 'T', 'Qua', 'Qui']\n while abs(num) >= 1000:\n if magnitude >= 5:\n break\n\n magnitude += 1\n num /= 1000.0\n\n try:\n return '{}{}'.format('{:f}'.format(num).rstrip('0').rstrip('.'), matches[magnitude])\n except IndexError:\n return original_num\n\n async def add_gay(self, avatar, discord_file: bool = True, if_url : bool = False):\n \"\"\"Adds gay overlay to image url given\"\"\"\n gay_image = PIL.Image.open(self.load_asset('gay.jpg'))\n if if_url:\n avatar = await self.convert_image(avatar)\n\n width, height = avatar.size\n foreground = gay_image.convert('RGBA').resize((width, height), PIL.Image.ANTIALIAS)\n img = discord.File(await self.merge_image(foreground, avatar, blend_level=0.4))\n\n if discord_file:\n return discord.File(img, filename=\"Gay.png\")\n return img\n\n async def merge_image(self, foreground, background, if_url: bool = False, blend_level: float = 0.6,\n discord_file: bool = True):\n \"\"\"Merges two images together\"\"\"\n if if_url:\n foreground = self.convert_image(foreground)\n background = self.convert_image(background)\n result_bytes = BytesIO()\n width, height = background.size\n\n foreground = foreground.resize((width, height), PIL.Image.ANTIALIAS)\n result = PIL.Image.blend(background, foreground, alpha=blend_level)\n\n if discord_file:\n result.save(result_bytes, format=\"PNG\")\n result_bytes.seek(0)\n return discord.File(result_bytes, filename=\"mergedimage.png\")\n\n return result\n\n async def create_profile(self, user: discord.Member, rank: int, level: int, xp: int, next_level_xp: int = None,\n current_level_xp: int = None, discord_file=True):\n\n avatar = PIL.Image.open(BytesIO(await self.make_request(str(user.avatar_url))))\n avatar = avatar.convert('RGBA').resize((180, 180))\n card = Image.open(self.default_bg)\n card = card.resize((900, 238))\n font = ImageFont.truetype(self.font, 36)\n font_small = ImageFont.truetype(self.font, 20)\n result_bytes = BytesIO()\n\n status = Image.open(getattr(self, user.status.name))\n\n status = status.convert(\"RGBA\").resize((55, 55))\n profile_pic_holder = Image.new(\"RGBA\", card.size, (255, 255, 255, 0))\n\n mask = Image.new(\"RGBA\", card.size, 0)\n mask_draw = ImageDraw.Draw(mask)\n mask_draw.ellipse(\n (29, 29, 209, 209), fill=(255, 25, 255, 255)\n )\n\n draw = ImageDraw.Draw(card)\n draw.text((245, 60), f\"{user}\", self.txt_colour, font=font)\n draw.text((620, 60), f\"Rank #{rank}\", self.txt_colour, font=font)\n draw.text((245, 145), f\"Level {level}\", self.txt_colour, font=font_small)\n draw.text((620, 145), f\"{self.human_format(xp)} / {self.human_format(next_level_xp)} XP\", self.txt_colour,\n font=font_small)\n\n blank = Image.new(\"RGBA\", card.size, (255, 255, 255, 0))\n blankdraw = ImageDraw.Draw(blank)\n blankdraw.rounded_rectangle((245, 185, 750, 205), fill=(255, 255, 255, 0), outline=self.txt_colour, radius=10)\n\n xpneed = next_level_xp - current_level_xp\n xphave = xp - current_level_xp\n length_of_bar = (((xphave / xpneed) * 100) * 4.9) + 248\n\n blankdraw.rounded_rectangle((248, 188, length_of_bar, 202), fill=self.txt_colour, radius=7)\n\n profile_pic_holder.paste(avatar, (29, 29, 209, 209))\n precard = Image.composite(profile_pic_holder, card, mask)\n precard = precard.convert('RGBA')\n precard = Image.alpha_composite(precard, blank)\n\n blank = Image.new(\"RGBA\", card.size, (255, 255, 255, 0))\n blank.paste(status, (155, 155))\n finalcard = Image.alpha_composite(precard, blank)\n\n if discord_file:\n finalcard.save(result_bytes, format=\"PNG\")\n result_bytes.seek(0)\n return discord.File(result_bytes, filename=\"rankcard.png\")\n\n return finalcard\n\n async def greyscale(self, img, if_url: bool = False, discord_file: bool = False):\n if if_url:\n img = await self.convert_image(img)\n if discord_file:\n return discord.File(img.convert('LA'))\n return img.convert('LA')\n","sub_path":"discordSuperUtils/Imaging.py","file_name":"Imaging.py","file_ext":"py","file_size_in_byte":6275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"393967375","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nfrom sklearn import linear_model\nfrom sklearn.metrics import r2_score\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.metrics import r2_score\ndf=pd.read_csv('FuelConsumption.csv')\ncdf = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB','CO2EMISSIONS']]\nmsk = np.random.rand(len(df)) < 0.8\ntrain = cdf[msk]\ntest = cdf[~msk]\ntrain_x = np.asanyarray(train[['ENGINESIZE']])\ntrain_y = np.asanyarray(train[['CO2EMISSIONS']])\npoly=PolynomialFeatures(degree=3)\ntrain_x_poly=poly.fit_transform(train_x)\nclf = linear_model.LinearRegression()\ntrain_y_ = clf.fit(train_x_poly, train_y)\n\ntest_x = np.asanyarray(test[['ENGINESIZE']])\ntest_y = np.asanyarray(test[['CO2EMISSIONS']])\ntest_x_poly = poly.fit_transform(test_x)\ntest_y_ = clf.predict(test_x_poly)\n\nprint(\"Mean absolute error: %.2f\" % np.mean(np.absolute(test_y_ - test_y)))\nprint(\"Residual sum of squares (MSE): %.2f\" % np.mean((test_y_ - test_y) ** 2))\nprint(\"R2-score: %.2f\" % r2_score(test_y_ , test_y) )\n","sub_path":"polynomialregression.py","file_name":"polynomialregression.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"568710009","text":"#! /usr/bin/env python\n\nfrom __future__ import print_function\nimport sys, pickle, argparse\n\nimport rdkit\nfrom rdkit import Chem\nfrom rdkit.Chem import AllChem\n\ndef writeHeader(molname, loplsflag):\n print(\"\"\"import \"oplsaa.lt\" # <-- defines the standard \"OPLSAA\" force field\"\"\")\n if loplsflag:\n print(\"\"\"import \"loplsaa.lt\" # <-- custom parameters for long alkane chains taken from\n # Sui et al. J.Chem.Theory.Comp (2012), 8, 1459\n # To use the ordinary OPLSAA force field parameters,\n # (instead of the Sui et al. parameters), change the\n # atom types below from \"@atom:81L\",\"@atom:85LCH2\" to\n # \"@atom:81\" and \"@atom:85\" (defined in \"oplsaa.lt\")\"\"\")\n print(\"\"\"{0} inherits OPLSAA {{\"\"\".format(molname))\n\ndef writeFooter(molname):\n print(\"\"\"}} # {0}\n\n\n\n# Note: You don't need to supply the partial partial charges of the atoms.\n# If you like, just fill the fourth column with zeros (\"0.000\").\n# Moltemplate and LAMMPS will automatically assign the charge later\"\"\".format(molname))\n\n\ndef writeXyz(m,name):\n with open(name+'.xyz','w') as geof:\n geof.write(str(len(m.GetAtoms()))+ '\\n')\n geof.write('# xyz for ' + name + ' generateed by rdlt \\n')\n for at in m.GetAtoms():\n point = m.GetConformer().GetAtomPosition(at.GetIdx())\n strToWrite = \"\\t\".join([str(at.GetSymbol())+str(at.GetIdx()),\n str(point.x), str(point.y), str(point.z)])\n geof.write(strToWrite+'\\n')\n with open(name+'_unumbered.xyz','w') as geof:\n geof.write(str(len(m.GetAtoms()))+ '\\n')\n geof.write('# xyz for ' + name + ' generateed by rdlt \\n')\n for at in m.GetAtoms():\n point = m.GetConformer().GetAtomPosition(at.GetIdx())\n strToWrite = \"\\t\".join([str(at.GetSymbol()),\n str(point.x), str(point.y), str(point.z)])\n geof.write(strToWrite+'\\n')\ndef writeAtoms(m):\n print(\"# atom-id mol-id atom-type charge X Y Z\")\n print(\" write('Data Atoms') {\")\n conf = m.GetConformer(0)\n for at in m.GetAtoms():\n point = conf.GetAtomPosition(at.GetIdx())\n print(\"\\t{0}\\t$mol\\t{1}\\t0\\t{2:8.3f}\\t{3:8.3f}\\t{4:8.3f}\".format(\n '$atom:'+at.GetSymbol()+str(at.GetIdx()),\n at.GetProp('AtomType'),\n point.x, point.y, point.z\n ))\n print(\" }\")\n\ndef writeBonds(m):\n bonds = m.GetBonds()\n print(\" write('Data Bond List') {\")\n for bond in bonds:\n b = bond.GetBeginAtom()\n e = bond.GetEndAtom()\n bname = b.GetSymbol()+str(b.GetIdx())\n ename = e.GetSymbol()+str(e.GetIdx())\n print(\"\\t$bond:{0}\\t$atom:{1}\\t$atom:{2}\".format(bname+ename,\n bname, ename))\n print(\" }\")\n\ndef lt_to_molecule(ltfn):\n \"\"\"Reads a moltemplate .lt file and returns an RDKit molecule for\n comparison purposes. Only works on .lt files with specific formatting.\n Doesn't have bond type perception, so doesn't generate useful smiles.\n ** Don't use this for anything. **\n \"\"\"\n ltmol = Chem.RWMol()\n with open(ltfn,'r') as infile:\n for line in [line.strip() for line in infile if line.strip()]:\n # for this to work, the name of the atom must contain the\n #atomic symbol at the beginning. Otherwise would need to\n # look up based on type or mass.\n if line.split()[0][:5] == \"$atom\":\n label = line.split(':')[1].split()[0]\n #print(label)\n #construct a new atom by passing the atomic symbol\n #filter removes numbers\n newatom = Chem.Atom(''.join(filter(str.isalpha, label)))\n atomid = ltmol.AddAtom(newatom)\n elif line.split()[0][:5] == \"$bond\":\n #assumes bond - atom - atom style entries with atom id\n # in the field\n id1str = line.split()[1].split(':')[1]\n id1 = int(''.join(filter(str.isdigit, id1str)))\n id2str = line.split()[2].split(':')[1]\n id2 = int(''.join(filter(str.isdigit, id2str)))\n #this makes everything a single bond, so won't allow building\n # of a valid smiles from the incomplete graph\n ltmol.AddBond(id1,id2)\n #print(id1,id2)\n newmol = ltmol.GetMol()\n Chem.SanitizeMol(newmol)\n AllChem.EmbedMolecule(newmol,AllChem.ETKDG())\n print(Chem.MolToSmiles(newmol))\n\n\ndef read_cdict(cdictin):\n with open(cdictin, 'rb') as f:\n cdict = pickle.load(f)\n return cdict\n\ndef sum_of_charges(m, cdict):\n test_sum = 0\n print(\"# Given the current charge dictionary, the atoms will have the following charges:\")\n for atom in m.GetAtoms():\n atype = atom.GetProp('AtomType')\n print(\"# Atom {0} is type {1} with charge {2}\".format(atom.GetIdx(),atype,cdict[atype]))\n test_sum += cdict[atype]\n print(\"# The sum of the atomic charges is: {:.2f}\".format(test_sum))\n if abs(test_sum) > 0.001:\n print(\"\"\"\n # WARNING: The net charge appears to be non-zero! This may indicate\n #incompatible atom types.\n \"\"\")\n\ndef generateFeatureDefn(fpath, fdefout, cdictout):\n \"\"\"Write a feature definition file in RDKit style from the moltemplate\n conversion document. Only need to run this function if the conversion\n document has been changed.\n\n fpath -- file path of the moltemplate conversion doc\n fdefout -- file path to write the feature definition file\n cdictout -- file path to create a dictionary of atom types to charges\n \"\"\"\n with open(fpath,'r') as infile, open(fdefout,'w') as outfile:\n feat_index = 0\n cdict = {}\n for line in [line.strip() for line in infile if line.strip()]:\n if line[0]!='*':\n el, atomname, typename, patt, lttype, chg, desc = [el.strip() for el in line.split(\"|\")]\n # write lttype, SMARTS to feature definintion file\n # NOTE: using feature family to store the atom names is dangerous\n # because rdkit won't assign mutliple features in same family.\n # So I had to assign an index to make unique names [AHS]\n fdefn = \\\n\"\"\"\nDefineFeature {0} {1}\nFamily {2}{3}\nEndFeature\"\"\".format(lttype, patt, feat_index, atomname)\n # add new charge dictionary entry\n cdict[lttype]=float(chg)\n feat_index+=1\n outfile.write(fdefn)\n\n with open(cdictout,'wb') as f:\n pickle.dump(cdict,f, protocol=2)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\"-s\", \"--smi\",\n help=\"Smiles string of the molecule to be atom-typed\",\n required=True)\n parser.add_argument(\"-n\", \"--name\",\n help=\"Name of the molecule to be typed\",\n default=\"LIG\")\n parser.add_argument(\"-l\", \"--loplsflag\",\n help=\"Use the lopls atom atype definitions\",\n action=\"store_true\")\n parser.add_argument(\"-f\", \"--fdef\",\n help=\"OPLS feature definition file path\",\n default=\"./opls_lt.fdefn\")\n parser.add_argument(\"-x\", \"--lfdef\",\n help=\"LOPLS feature definition file path\",\n default=\"./lopls_lt.fdefn\")\n parser.add_argument(\"-g\", \"--geo\",\n help=\"produce xyz file\",\n default=False)\n parser.add_argument(\"-r\", \"--refresh\",\n help=\"\"\"\n Overwrite/make new feature defintion files in the current directory\n given a file path containing a moltemplate conversion document.\n Use caution, as this will overwrite files.\n \"\"\")\n parser.add_argument(\"-c\", \"--charge\",\n help=\"Check the net charge of the molecule based on a charge dictionary\",\n action=\"store_true\")\n args = parser.parse_args()\n\n #Build rdkit molecule from smiles and generate a conformer\n m = AllChem.AddHs(Chem.MolFromSmiles(args.smi))\n AllChem.EmbedMolecule(m,AllChem.ETKDG())\n\n # WARNING: This part is dumb. Will update the lopls definitions ONLY\n # if the lopls flag is used. If a path is passed with the refresh command\n #\n if args.refresh and args.loplsflag:\n generateFeatureDefn(args.refresh,'./lopls_lt.fdefn','./lopls_lt_dict.pkl')\n elif args.refresh:\n generateFeatureDefn(args.refresh,'./opls_lt.fdefn','./opls_lt_dict.pkl')\n\n #Build a feature factory from the defintion file and assign all features\n factory = Chem.ChemicalFeatures.BuildFeatureFactory(args.fdef)\n features = factory.GetFeaturesForMol(m)\n\n #Use the features to assign an atom type property\n [m.GetAtomWithIdx(f.GetAtomIds()[0]).SetProp('AtomType',f.GetType()) for f in features];\n\n #if lopls defitions are desired, redo the feature process\n # overwrite atomtypes\n if args.loplsflag:\n #print('loplsflag is {}'.format(loplsflag) )\n lfactory = Chem.ChemicalFeatures.BuildFeatureFactory(args.lfdef)\n lfeatures = lfactory.GetFeaturesForMol(m)\n #print(len(lfeatures))\n #for f in lfeatures:\n # print(f.GetId(), f.GetFamily(), f.GetType(), f.GetAtomIds())\n [m.GetAtomWithIdx(f.GetAtomIds()[0]).SetProp('AtomType',f.GetType()) for f in lfeatures];\n #[print(at.GetProp('AtomType')) for at in m.GetAtoms()]\n\n #find untyped atoms\n #\n failure = False\n for at in m.GetAtoms():\n try:\n at.GetProp('AtomType')\n except KeyError:\n print(\"Atom {0} does not have an assigned atom type!\".format(at.GetIdx()))\n failure = True\n #if any failed to type, quit\n if failure:\n sys.exit(\"\"\"Refusing to write a .lt file without type assignments.\nCheck the SMARTS pattern that defines the expected atom type.\"\"\")\n\n\n #basic output\n writeHeader(args.name,args.loplsflag)\n writeAtoms(m)\n writeBonds(m)\n writeFooter(args.name)\n writeXyz(m,args.name)\n if args.charge:\n # Read charge dictionaries for testing\n opls_cdict = read_cdict('./opls_lt_dict.pkl')\n if args.loplsflag:\n lopls_cdict = read_cdict('./lopls_lt_dict.pkl')\n opls_cdict.update(lopls_cdict)\n\n sum_of_charges(m,opls_cdict)\n\n # write output mol file if needed:\n if args.geo:\n print(Chem.MolToMolBlock(m2),file=open('data/foo.mol','w+'))\n \nif __name__=='__main__':\n main()\n","sub_path":"autoOFR/rdlt/rdlt.py","file_name":"rdlt.py","file_ext":"py","file_size_in_byte":11056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"160717408","text":"for i in range(int(input())):\n a,b=input().split()\n b=int(b)\n a=list(map(int,a))\n print(a,b)\n i=0;s=1000000;r=len(a)\n if rd:\n s=d\n if s==0:\n break\n i+=1;b+=1\n print(s)\n \n \n","sub_path":"mns.py","file_name":"mns.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"329715203","text":"import numpy as np\nimport scipy.linalg as la\nimport matplotlib.pyplot as plt\nimport csv\nfrom ss_mod import m\nfrom pyomo.environ import *\n\n# Constructing constraint gradient \n\ndef get_jacobian(filename):\n\n jac_file = open(filename,newline='')\n header = jac_file.readline()\n h1 = ''\n h2 = ''\n i=0\n while header[i] != '\\t' and header[i] != ' ' and header[i] != '\\n':\n h1 += header[i]\n i = i+1\n i = i+1\n while header[i] != '\\t' and header[i] != ' ' and header[i] != '\\n':\n h2 += header[i]\n i = i+1\n nrow = int(h1)\n ncol = int(h2)\n \n const_jac = np.zeros((nrow,ncol))\n \n reader = csv.reader(jac_file,delimiter='\\t')\n \n # put the values from the jacobian file into \n # their correct places in the jacobian matrix\n for row in reader:\n const_jac[int(row[0])-1,int(row[1])-1] = float(row[2])\n \n #print(const_jac.shape)\n row_sum = np.sum(const_jac,axis=1)\n col_sum = np.sum(const_jac,axis=0)\n \n np.savetxt('row_sum.txt',row_sum)\n np.savetxt('col_sum.txt',col_sum)\n \n np.savetxt('jacobian.txt',const_jac)\n \n rowfilename = 'ss_mod.row'\n colfilename = 'ss_mod.col'\n \n # Parsing row and column files\n \n mbal = ['const11','const12','const15','const18','const20','const32','const33','const36','const39','const41']\n cbal = ['const13','const14','const16','const19','const21','const34','const35','const37','const40','const42']\n vle = ['const1','const2','const3','const22','const23','const24']\n vflw = ['const4','const5','const25','const26'] \n lflw = ['const6','const7','const8','const27','const28','const29']\n \n # Differential constraints\n f_list = ['const_E1','const_E2','const_E3','const_S7','const_S8','const_S9','const_S10',\n 'const_B7','const_C6','const_C11']\n # Algebraic constraints\n g_list = []\n \n for const in m.component_objects(Constraint):\n if const.name not in f_list:\n g_list.append(const.name)\n \n # Differential variables\n z_list = ['xE_IPA','xS_CO2','TB_tb_ave','TC_tb_ave','TC_sh_ave']\n \n # Algebraic variables\n y_list = []\n \n for var in m.component_objects(Var):\n if var.name not in z_list:\n y_list.append(var.name)\n \n const_list = f_list+g_list\n var_list = y_list+z_list\n \n \n \n # Maps variables/constraints to arrays holding their start and end line (row/col in jacobian)\n # ^ this seems kinda janky... is there a better way to do it?\n # Note: assumes that indexed constraints are contiguous...\n eqn_locator_jac = {}\n var_locator_jac = {}\n for eqn in const_list: eqn_locator_jac[eqn] = np.zeros(2) \n for var in var_list: var_locator_jac[var] = np.zeros(2)\n \n rowfile = open(rowfilename,newline='')\n colfile = open(colfilename,newline='')\n \n # Function to get name of variable/constraint from line of row/col file\n # this also seems super janky\n def get_name(entry):\n i = 0\n name = ''\n while entry[i] != '[' and entry[i] != '\\n' and entry[i] != '': \n name += entry[i]\n i = i+1\n return name \n \n # Step through lines of both files, recording start and end lines of each equation/variable\n i = 1\n prev = ''\n line = rowfile.readline()\n while line != '': \n name = get_name(line) \n if name != prev:\n if name in const_list:\n eqn_locator_jac[name][0] = int(i)\n if prev in const_list:\n eqn_locator_jac[prev][1] = int(i-1)\n prev = name\n line = rowfile.readline()\n i = i+1\n if prev in const_list:\n eqn_locator_jac[prev][1] = int(i-1)\n \n \n \n i = 1\n prev = ''\n line = colfile.readline()\n while line != '': \n name = get_name(line) \n if name != prev:\n # dumb hacky fix to problem of possible non-contiguity of variables in .col file\n # definitely needs to be made more thorough/robust\n if name in var_list:\n if var_locator_jac[name][0]==0:\n var_locator_jac[name][0] = int(i)\n if prev in var_list:\n if var_locator_jac[prev][1]==0:\n var_locator_jac[prev][1] = int(i-1)\n prev = name\n line = colfile.readline()\n i = i+1\n if prev in var_list:\n if var_locator_jac[prev][1]==0:\n var_locator_jac[prev][1] = int(i-1)\n \n #print(var_locator_jac)\n #print(eqn_locator_jac)\n \n # Construct matrices df,g/dz,y\n \n \n eqn_locator_f = {}\n eqn_locator_g = {}\n var_locator_z = {}\n var_locator_y = {}\n\n idx2state = {}\n idx2eqn = {}\n \n # Build index-finder for differential variables in f\n \n # start i at 1 here for consistency with jacobian locator, \n # which refers to lines in row and col files\n #i = 1\n #for const in mbal:\n # j = i + eqn_locator_jac[const][1]-eqn_locator_jac[const][0]\n # eqn_locator_f[const] = np.array( [i,j] )\n # i = j+1\n #for const in cbal: \n # j = i + eqn_locator_jac[const][1]-eqn_locator_jac[const][0]\n # eqn_locator_f[const] = np.array( [i,j] ) \n # i = j+1\n #nf = i-1\n \n i = 1\n for const in f_list:\n j = i + eqn_locator_jac[const][1]-eqn_locator_jac[const][0]\n eqn_locator_f[const] = np.array( [i,j] )\n if i == j:\n idx2eqn[int(i)] = const\n else:\n for k in range(int(i),int(j)+1):\n idx2eqn[int(k)] = const + '[%i]'%(k+1-i)\n i = j+1\n nf = i-1\n \n print(idx2eqn)\n print(eqn_locator_f)\n \n \n #print(eqn_locator_f)\n #i = 1\n #for const in vle: \n # j = i + eqn_locator_jac[const][1]-eqn_locator_jac[const][0]\n # eqn_locator_g[const] = np.array( [i,j] )\n # i = j+1\n #for const in lflw:\n # j = i + eqn_locator_jac[const][1]-eqn_locator_jac[const][0]\n # eqn_locator_g[const] = np.array( [i,j] )\n # i = j+1\n #for const in vflw:\n # j = i + eqn_locator_jac[const][1]-eqn_locator_jac[const][0]\n # eqn_locator_g[const] = np.array ( [i,j] ) \n # i = j+1\n #ng = i-1\n \n # Build index-finder for algebraic equations in g\n i = 1\n for const in g_list:\n j = i + eqn_locator_jac[const][1] - eqn_locator_jac[const][0]\n eqn_locator_g[const] = np.array( [i,j] )\n i = j+1 \n ng = i-1\n \n #i = 1\n #for var in Mvar:\n # # i is incremented twice more to account for holdups at the \n # # reboiler and condenser, which are not included in the \n # # .col file\n # i = i+1\n # j = i + var_locator_jac[var][1]-var_locator_jac[var][0] \n # var_locator_z[var] = np.array( [i,j] )\n # i = j+1\n # i = i+1\n #for var in xvar: \n # j = i + var_locator_jac[var][1]-var_locator_jac[var][0]\n # var_locator_z[var] = np.array( [i,j] )\n # i = j+1\n #nz = i-1\n \n # Build index-finder for differential variables in z \n i = 1\n for var in z_list:\n j = i + var_locator_jac[var][1] - var_locator_jac[var][0]\n var_locator_z[var] = np.array( [i,j] )\n if i == j:\n idx2state[int(i)] = var \n else:\n for k in range(int(i),int(j)+1):\n idx2state[int(k)] = var + '[%i]'%(k+1-i)\n i = j+1\n nz = i-1\n\n print(var_locator_z)\n print(idx2state)\n \n #i = 1\n #for var in yvar:\n # j = i + var_locator_jac[var][1]-var_locator_jac[var][0] \n # var_locator_y[var] = np.array( [i,j] )\n # i = j+1\n #for var in Lvar: \n # j = i + var_locator_jac[var][1]-var_locator_jac[var][0]\n # var_locator_y[var] = np.array( [i,j] )\n # i = j+1\n #for var in Vvar: \n # j = i + var_locator_jac[var][1]-var_locator_jac[var][0]\n # var_locator_y[var] = np.array( [i,j] )\n # i = j+1\n #ny = i-1\n \n \n # Build index-finder for algebraic variables in y\n i = 1\n for var in y_list:\n j = i + var_locator_jac[var][1] - var_locator_jac[var][0]\n var_locator_y[var] = np.array( [i,j] )\n i = j+1\n ny = i-1\n \n # TODO: fix problem where stale variables are given a spot in \n # y vector. This happens because I naively construct y_list\n # without checking for stale variables\n # ... could check if variable was assigned a non-zero value in the jacobian...\n # works because jacobian locator reads names directly from .col file\n # which does not include stale variables.\n \n #print('differential equations:')\n #for e in f_list: print(e,eqn_locator_f[e])\n #print('algebraic equations:')\n #for e in g_list: print(e,eqn_locator_g[e])\n #print('differential variables:')\n #for v in z_list: print(v,var_locator_z[v])\n #print('algebraic variables:')\n #for v in y_list: print(v,var_locator_y[v])\n \n \n nf = int(nf)\n nz = int(nz)\n ng = int(ng)\n ny = int(ny)\n print(nf,nz,ng,ny)\n \n \n dfdz = np.zeros((nf,nz))\n dfdy = np.zeros((nf,ny))\n dgdz = np.zeros((ng,nz))\n dgdy = np.zeros((ng,ny))\n \n # the following map equations to the variables they contain\n # \n # ...\n # don't even end up using these, this method doesn't generalize well to different models\n # should be an easier way to do this with pyomo constraints/variables, if I think\n # its necessary\n # ...\n z_in_f = {}\n y_in_f = {}\n z_in_g = {}\n y_in_g = {}\n \n #for eqn in f:\n # for # need list of variables contained in each equation\n # dfdz[eqn_locator_f[eqn][0]:eqn_locator_f[eqn][1],] = \\\n \n #for eqn in f:\n # if eqn in mbal: \n # z_in_f[eqn] = [v for v in Mvar]\n # y_in_f[eqn] = [v for v in Lvar + Vvar]\n # if eqn in cbal:\n # z_in_f[eqn] = [v for v in Mvar + xvar]\n # y_in_f[eqn] = [v for v in yvar + Lvar + Vvar]\n #\n #for eqn in g: \n # if eqn in vle:\n # z_in_g[eqn] = [v for v in xvar]\n # y_in_g[eqn] = [v for v in yvar]\n # if eqn in vflw:\n # z_in_g[eqn] = []\n # y_in_g[eqn] = [v for v in Vvar]\n # if eqn in lflw:\n # z_in_g[eqn] = [v for v in Mvar]\n # y_in_g[eqn] = [v for v in Lvar]\n \n #print(z_in_f)\n #print(y_in_g) \n \n '''\n #\n #for eqn in f:\n # #print(eqn)\n # for var in z_in_f[eqn]:\n # #print(var) \n # dfdz[ int(eqn_locator_f[eqn][0])-1:int(eqn_locator_f[eqn][1]), \\\n # int(var_locator_z[var][0])-1:int(var_locator_z[var][1]) ] = \\\n # const_jac[ int(eqn_locator_jac[eqn][0])-1:int(eqn_locator_jac[eqn][1]), \\\n # int(var_locator_jac[var][0])-1:int(var_locator_jac[var][1]) ]\n # for var in y_in_f[eqn]:\n # dfdy[ int(eqn_locator_f[eqn][0])-1:int(eqn_locator_f[eqn][1]), \\\n # int(var_locator_y[var][0])-1:int(var_locator_y[var][1]) ] = \\\n # const_jac[ int(eqn_locator_jac[eqn][0])-1:int(eqn_locator_jac[eqn][1]), \\\n # int(var_locator_jac[var][0])-1:int(var_locator_jac[var][1]) ]\n # \n #for eqn in g:\n # #print(eqn)\n # for var in z_in_g[eqn]:\n # #print(var) \n # dgdz[ int(eqn_locator_g[eqn][0])-1:int(eqn_locator_g[eqn][1]), \\\n # int(var_locator_z[var][0])-1:int(var_locator_z[var][1]) ] = \\\n # const_jac[ int(eqn_locator_jac[eqn][0])-1:int(eqn_locator_jac[eqn][1]), \\\n # int(var_locator_jac[var][0])-1:int(var_locator_jac[var][1]) ]\n # for var in y_in_g[eqn]:\n # dgdy[ int(eqn_locator_g[eqn][0])-1:int(eqn_locator_g[eqn][1]), \\\n # int(var_locator_y[var][0])-1:int(var_locator_y[var][1]) ] = \\\n # const_jac[ int(eqn_locator_jac[eqn][0])-1:int(eqn_locator_jac[eqn][1]), \\\n # int(var_locator_jac[var][0])-1:int(var_locator_jac[var][1]) ]\n '''\n \n # constructing matrices\n # (probably) irrelevant but interesting question:\n # does the following code exploit locality well? \n # intuition is no, because I grab data that can span\n # multiple matrix rows at once, and may revisit the same \n # row many times. But is this worse \n # than making more jumps between my source and \n # target matrices? ... need to review ...\n for eqn in f_list:\n #print(eqn)\n for var in z_list:\n #print(var) \n dfdz[ int(eqn_locator_f[eqn][0])-1:int(eqn_locator_f[eqn][1]), \\\n int(var_locator_z[var][0])-1:int(var_locator_z[var][1]) ] = \\\n const_jac[ int(eqn_locator_jac[eqn][0])-1:int(eqn_locator_jac[eqn][1]), \\\n int(var_locator_jac[var][0])-1:int(var_locator_jac[var][1]) ]\n for var in y_list:\n dfdy[ int(eqn_locator_f[eqn][0])-1:int(eqn_locator_f[eqn][1]), \\\n int(var_locator_y[var][0])-1:int(var_locator_y[var][1]) ] = \\\n const_jac[ int(eqn_locator_jac[eqn][0])-1:int(eqn_locator_jac[eqn][1]), \\\n int(var_locator_jac[var][0])-1:int(var_locator_jac[var][1]) ]\n \n for eqn in g_list:\n #print(eqn)\n for var in z_list:\n #print(var) \n dgdz[ int(eqn_locator_g[eqn][0])-1:int(eqn_locator_g[eqn][1]), \\\n int(var_locator_z[var][0])-1:int(var_locator_z[var][1]) ] = \\\n const_jac[ int(eqn_locator_jac[eqn][0])-1:int(eqn_locator_jac[eqn][1]), \\\n int(var_locator_jac[var][0])-1:int(var_locator_jac[var][1]) ]\n for var in y_list:\n dgdy[ int(eqn_locator_g[eqn][0])-1:int(eqn_locator_g[eqn][1]), \\\n int(var_locator_y[var][0])-1:int(var_locator_y[var][1]) ] = \\\n const_jac[ int(eqn_locator_jac[eqn][0])-1:int(eqn_locator_jac[eqn][1]), \\\n int(var_locator_jac[var][0])-1:int(var_locator_jac[var][1]) ]\n \n \n np.savetxt('dfdz.txt',dfdz,fmt = '%1.2f')\n np.savetxt('dfdy.txt',dfdy,fmt = '%1.2f')\n np.savetxt('dgdz.txt',dgdz,fmt = '%1.2f')\n np.savetxt('dgdy.txt',dgdy,fmt = '%1.2f')\n \n #print(dgdy)\n #np.savetxt('dgdy.txt',dgdy,fmt = '%1i')\n dgdy_inv = la.inv(dgdy)\n #dfdg = np.matmul(dfdy,dgdy_inv)\n \n dydz = np.matmul(dgdy_inv,dgdz)\n jacobian = dfdz - np.matmul(dfdy,dydz) \n\n # compute idx2state dictionary to return as well\n # (index starting with 1 to match intuition about matrices)\n #for idx in range(1,nz+1):\n\n\n return jacobian, idx2state, idx2eqn\n#print(np.matmul(dfdy,dydz))\n#np.savetxt('djac_test',jacobian-dfdz,fmt = '%1.2f')\n\n\ndef main(): \n jacobian, idx2state, idx2eqn = get_jacobian('jacobi_debug.in')\n nz = len(jacobian)\n lam, evec = la.eig(jacobian)\n N,s,LT = la.svd(jacobian)\n print(s)\n print(LT)\n # i^th column of evec is the evector of i^th eigenvalue \n \n lam_index = np.arange(1,lam.size+1,1)\n lam_real = np.real(lam)\n np.savetxt('evals_real.txt',np.transpose(np.stack([lam_index,lam_real])), fmt = '%1.2f')\n np.savetxt('evals.txt',np.transpose(np.stack([lam_index,lam])),fmt = '%1.2f')\n \n np.savetxt('jacobian.txt',jacobian)\n \n pos_eval = []\n for i in range(0,lam.size):\n if np.real(lam[i])>0:\n pos_eval.append(i)\n \n # Express states in basis of right singular vectors\n x_1 = np.zeros(nz)\n x_2 = np.zeros(nz)\n x_3 = np.zeros(nz)\n x_4 = np.zeros(nz)\n x_5 = np.zeros(nz)\n x_6 = np.zeros(nz)\n x_7 = np.zeros(nz)\n x_8 = np.zeros(nz)\n x_9 = np.zeros(nz)\n x_10 = np.zeros(nz)\n x_11 = np.zeros(nz)\n \n x_1[0] = 1\n x_2[1] = 1\n x_3[2] = 1\n x_4[3] = 1\n x_5[4] = 1\n x_6[5] = 1\n x_7[6] = 1\n x_8[7] = 1\n x_9[8] = 1\n x_10[9] = 1\n x_11[10] = 1\n \n x_1l = LT.dot(x_1)\n x_2l = LT.dot(x_2)\n x_3l = LT.dot(x_3)\n x_4l = LT.dot(x_4)\n x_5l = LT.dot(x_5)\n x_6l = LT.dot(x_6)\n x_7l = LT.dot(x_7)\n x_8l = LT.dot(x_8)\n x_9l = LT.dot(x_9)\n x_10l = LT.dot(x_10)\n x_11l = LT.dot(x_11)\n \n \n print(x_1l)\n \n #print(pos_eval)\n \n #def idx2state(idx):\n # # idx is the index, according to numpy, in an eigenvector (array)\n # M1 = 41\n # M2 = M1+41\n # x1 = M2+82\n # x2 = x1+82\n # if idx >= 0 and idx < M1:\n # i = idx+1\n # return 'M1[%i]'%i\n # if idx >= M1 and idx < M2:\n # return 'M2[%i]'%(idx-M1+1)\n # if idx >= M2 and idx < x1:\n # return 'x1[%i]'%(idx-M2+1)\n # if idx >= x1 and idx < nz:\n # return 'x2[%i]'%(idx-x1+1)\n # if idx >= nz or idx < 0:\n # raise ValueError('idx2state function must receive a valid index for a differential variable')\n \n '''\n \n idx2state= {}\n nM1 = 41\n nM2 = 41\n nx1 = 82\n nx2 = 82\n idx = 0\n for coord in range(0,nM1):\n idx2state[coord+idx] = 'M1[%i]'%(coord+1)\n idx = idx + nM1\n for coord in range(0,nM2):\n idx2state[coord+idx] = 'M2[%i]'%(coord+1)\n idx = idx + nM2\n for coord in range(0,nx1):\n if coord & 1:\n idx2state[coord+idx] = 'x1[%i,2]'%((coord+1)/2)\n else:\n idx2state[coord+idx] = 'x1[%i,1]'%(coord/2+1)\n idx = idx + nx1\n for coord in range(0,nx2):\n if coord & 1:\n idx2state[coord+idx] = 'x2[%i,2]'%((coord+1)/2)\n else:\n idx2state[coord+idx] = 'x2[%i,1]'%(coord/2+1)\n \n #print(idx2state)\n \n # Really should have idx2state dictionary, so it can be given to ol_run file to interpret eigenvector\n # ... could just pass over states_impacted[] ...\n # No, because I need to assign states to vector coordinates\n \n states_impacted = {}\n for ev_num in pos_eval:\n states_impacted[ev_num] = []\n ev = evec[:,ev_num]\n r_ev = np.real(ev)\n for i in range(0,lam.size):\n if r_ev[i] > 1e-7 or r_ev[i] < -1e-7:\n states_impacted[ev_num].append(idx2state[i])\n \n #print(states_impacted[2])\n #print(evec[:,2])\n \n sum_ptb = np.zeros(nz)\n for j in range(0,nz):\n sum_ptb[j] = sum(evec[i,j] \\\n for i in range(int(var_locator_z['M1'][0])-2,int(var_locator_z['M1'][1])))\n \n #sum_ptb = sum(evec[i,2] \\\n # for i in range(int(var_locator_z['M1'][0]-1),int(var_locator_z['M1'][1])))\n #print(sum_ptb)\n \n \n \n #lam1,evec1 = la.eig(dfdz) \n #lam1_index = np.arange(1,lam1.size+1,1)\n #lam1_real = np.real(lam1)\n #fig2,ax2 = plt.subplots()\n #eval1_spec = ax2.bar(lam1_index,lam1_real)\n #plt.show()\n \n #print(lam)\n #print(evec)\n \n evec_inv_T = np.transpose(la.inv(evec))\n UPSR = evec*evec_inv_T\n #np.savetxt('UPSR.txt',np.real(UPSR))\n \n #print(UPSR)\n '''\n fig1,ax1 = plt.subplots()\n eval_spec = ax1.bar(lam_index,lam_real)\n plt.ylim(-70,70)\n fig1.suptitle('Eigenvalues of Jacobian')\n fig1.savefig('eigenvalues.png')\n \n lam_sort = np.sort(np.abs(lam_real))\n '''\n fig2,ax2 = plt.subplots()\n ax2.set_yscale('log')\n eval_spec_sort = ax2.bar(lam_index,lam_sort)\n fig2.suptitle('Abs of Eigenvalues, sorted')\n fig2.savefig('eigenvalues_sort.png')\n \n def state2UPSR(var,no):\n # no refers to the index of the variable.\n # for example, to access the row corresponding \n # to feed tray holdup, call ('M1',21)\n start = var_locator_z[var][0]\n end = var_locator_z[var][1]\n if var in Mvar:\n start = start - 1\n end = end + 1\n # ^ account for fact that reboiler and condenser holdups don't show up\n if no < 1 or no > 1 + end-start:\n raise ValueError('No. must be a valid index')\n return UPSR[ int(start + (no-1) - 1), :] \n \n '''\n\nif __name__ == '__main__':\n main()\n","sub_path":"eigen_test/jacobi_reader.py","file_name":"jacobi_reader.py","file_ext":"py","file_size_in_byte":19778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"202549603","text":"from abc import ABC, abstractmethod\nimport os\nimport json\nfrom characters import indicator_dict, character_dict\n\n# Abstract class that defines the methods amd attributes of Braille Apps.\nclass App(ABC):\n\n def __init__(self, name, cells, audio, arduino):\n self.cells = cells\n self.audio = audio\n self.arduino = arduino\n self.name = name\n # settings\n filename = self.name.lower() + '_state'\n self.filepath = os.path.join(os.path.dirname(__file__), 'app_states/' + filename + '.py')\n self.settings = self.load_settings()\n\n @abstractmethod\n def on_start(self):\n # Actions that an app wants to perform on app start\n pass\n\n def on_quit(self):\n # Actions that an app wants to perform when quitting the app\n self.audio.speak(\"The app will now close itself. Goodbye.\")\n self.save_settings()\n self.reset_cells()\n # return to main thread\n from main_functions import main_menu\n main_menu(self.arduino, self.cells, self.audio)\n\n def confirm_quit(self):\n self.audio.speak(\"Would you like to quit this application?\")\n response = self.await_response([\"yes\",\"no\"])\n # take answer from the user\n if response == \"yes\":\n self.on_quit()\n elif response == \"no\":\n self.audio.speak(\"You're returning to the app.\")\n\n def reset_cells(self, to='zero'):\n for cell in reversed(self.cells):\n cell.reset(to=to)\n\n def load_settings(self):\n # Rehydrate app settings from local file system\n if not(os.path.exists(self.filepath)):\n with open(self.filepath, 'w') as f:\n settings = {}\n f.write(json.dumps(settings, indent=4))\n with open(self.filepath, 'r') as f:\n return json.loads(f.read())\n # module = getattr(__import__('app_states', fromlist=[filename]), filename)\n # return module.settings\n\n def save_settings(self):\n # Save app settings to local file system\n with open(self.filepath, 'w') as f:\n f.write(json.dumps(self.settings, indent=4))\n\n def app_instruction(self, instruction):\n self.audio.speak(\"Would you like to listen to an instruction for this application?\")\n response = self.await_response(['yes','no'])\n if response == \"yes\":\n self.audio.speak(\"Welcome to \" + self.name + \". \" + instruction)\n elif response == \"no\":\n self.audio.speak(\"skipping instruction\")\n\n def get_pressed_button(self):\n # Returns the index of the pressed cell button\n return self.arduino.get_pressed_button()\n\n def wait_for_all_cells_finished(self):\n # Returns true if all the cells have finished rendering\n cells_finished_rotating = [False] * len(self.cells)\n while False in cells_finished_rotating:\n for cell in self.cells:\n cells_finished_rotating[cell.index - 1] = cell.has_finished_rotating()\n\n def print_character_all_cells(self, c):\n for cell in reversed(self.cells):\n cell.print_character(c)\n self.wait_for_all_cells_finished()\n\n def print_text(self, text):\n prepared_text = []\n for i,letter in enumerate(text):\n if letter not in indicator_dict:\n if i>=1 and letter.isalpha() and text[i-1].isdigit():\n prepared_text.append('LETTER')\n \n if letter.isupper():\n prepared_text.append('CAPITAL')\n letter = letter.lower()\n elif letter.isdigit():\n insert_letter_ind = True\n # indicator not necessary when previous char is digit\n if i>=1 and text[i-1].isdigit():\n insert_letter_ind = False\n # indicator not necessary when part of number (e.g. 1,496.2)\n if i>=2 and text[i-2].isdigit() and (text[i-1] == '.' or text[i-1] == ','):\n insert_letter_ind = False\n if insert_letter_ind:\n prepared_text.append('NUMBER')\n \n prepared_text.append(letter)\n\n to_print = []\n for i in range(0,len(prepared_text)):\n to_print.append(prepared_text[i])\n\n # TODO fix bug where the last characters stay the same as previous pagination when at end of sentence (doesn't go to zero)\n if len(to_print) == len(self.cells) or i == len(prepared_text)-1 :\n # Letters need to be passed in reverse in order to be processed in parallel\n padding = len(self.cells) - len(to_print) \n to_print = to_print + list(\" \" * padding)\n for j in range(len(to_print)-1,-1,-1):\n self.cells[j].print_character(to_print[j])\n\n self.print_cells_to_terminal()\n # Wait for pagination. Exiting turns out to be more difficult since wait_for_button_press blocks the execution.\n self.cells[-1].wait_for_button_press()\n to_print = []\n\n def print_cells_to_terminal(self):\n dots_print = ['.', 'o']\n top_row, middle_row, bottom_row, character_row = '', '', '', ''\n\n for cell in self.cells:\n extra_padding = len(cell.character) - 1\n dots = character_dict[cell.character]['dots']\n character_row = character_row + ' ' + str(cell.character) + ' '\n\n top_row = top_row + '|' + dots_print[dots[0]] + ' ' + dots_print[dots[3]] + '|' + (' ' * extra_padding)\n middle_row = middle_row + '|' + dots_print[dots[1]] + ' ' + dots_print[dots[4]] + '|' + (' ' * extra_padding)\n bottom_row = bottom_row + '|' + dots_print[dots[2]] + ' ' + dots_print[dots[5]] + '|' + (' ' * extra_padding)\n\n print(top_row)\n print(middle_row)\n print(bottom_row)\n print(character_row)\n\n def await_response(self, desired_responses = []):\n answer = self.audio.recognize_speech()[\"transcription\"]\n invalid = True\n\n if answer.find(\"options\") != -1:\n desired_response_string = str(desired_responses).strip('[]')\n self.audio.speak(\"Your options are: \" + desired_response_string + '.')\n invalid = False\n # quit / exit command listener\n elif answer.find('quit') != -1 or answer.find('exit') != -1:\n self.confirm_quit()\n invalid = False\n\n if len(desired_responses) == 0:\n return answer\n else:\n for d_r in desired_responses:\n if answer.find(d_r) != -1:\n response = d_r\n print(\"You said: \" + response)\n return response\n\n if invalid:\n self.audio.speak(\"Invalid option, please try again.\")\n\n response = self.await_response(desired_responses)\n return response\n","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"184609397","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nimport shutil\nimport numpy as np\nimport pandas as pd\nimport plotting\nimport bb_settings\nimport datetime\nimport scipy.misc as spm\n\ndef rg8_to_rgb(img):\n \"\"\"\n Convert RG8 img to RGB image. NOTE: no interpolation is performed, \n only array slicing and depth stacking. If the shape of the input \n image is [Nr, Nc], the shape of the output image is [Nr/2, Nc/2, 3].\n\n Parameters:\n -----------\n img : ndarray\n An RG8 monochrome image.\n\n Returns:\n -------\n ndarray\n The RGB image.\n \"\"\"\n\n red = img[::2, 1::2]\n grn = img[::2, ::2] #// 2 + img[1::2, 1::2] // 2\n blu = img[1::2, ::2]\n\n return np.dstack((red, grn, blu))\n\n\ndef read_raw(fname, sh=[3072, 4096], rgb=False, usb=False):\n \"\"\"\n Read in a raw image file. Assumes monochrome RG8.\n\n Parameters\n ----------\n fname : str\n The name (full path) of the image to read.\n sh : list\n The number of rows and columns of the output image.\n rgb : bool, optional\n Flag to convert to RGB.\n usb : bool, optional\n Read in an image file from the old USB camera.\n\n Returns\n -------\n ndarray\n The output image; either 2D or 3D if rgb is set to True.\n \"\"\"\n\n if usb:\n return np.fromfile(fname, dtype=np.uint8) \\\n .reshape(2160, 4096, 3)[..., ::-1]\n\n if rgb:\n return rg8_to_rgb(np.fromfile(fname, dtype=np.uint8).reshape(sh))\n\n return np.fromfile(fname, dtype=np.uint8).reshape(sh)\n\n\ndef gamma_scale(rgb, gam=0.5, scl=1.0, gray=False):\n \"\"\"\n Scale and \"gamma correct\" an rgb image. Values are clipped at 2^8.\n\n Parameters\n ----------\n rgb : ndarray\n An 8-bit RGB image.\n gam : float, optional\n The power to which to take the image (applied first).\n scl : float, optional\n The scaling factor for the image (applied second).\n gray : bool, optional\n Apply gray world correction before gamma correction.\n\n Returns\n -------\n ndarray\n A scaled, gamma corrected RGB image.\n \"\"\"\n\n if gray:\n print(\"GRAY WORLD CORRECTION NOT IMPLEMENTED YET!!!\")\n return 0\n\n return ((rgb / 255.)**gam * 255 * scl).clip(0, 255).astype(np.uint8)\n\n\ndef stretch_image(img, lim):\n \"\"\"\n Stretch an 8-bit image to limits and return an 8-bit image.\n NOTE: if the limits are outside the range [0, 255], the clipping has\n no effect.\n\n Parameters\n ----------\n img : ndarray\n An 8-bit image.\n lim : list\n The upper and lower limit to clip the image.\n\n Returns\n -------\n ndarray\n A stretched 8-bit image.\n \"\"\"\n\n # -- clip the image\n cimg = img.clip(lim[0], lim[1]).astype(float)\n\n # -- rescale to 0 to 255\n cimg -= cimg.min()\n cimg *= 255.0 / cimg.max()\n\n return cimg.astype(np.uint8)\n\n\ndef convert_raws(path, fac=1, gray=False):\n \"\"\"\n Convert all raw files in a directory to jpg. NOTE: Image size \n and RGB are HARD CODED!\n\n Parameters\n ----------\n path : str\n Path to raw files.\n fac : int, optional\n Sampling of the image.\n \"\"\"\n\n # -- set the scaling\n if gray:\n scl = np.array([0.57857543, 0.96972706, 1.0])\n else:\n scl = np.array([1.0, 1.0, 1.0])\n\n # -- get the file names\n fnames = [os.path.join(path, i) for i in sorted(os.listdir(path)) if \n \".raw\" in i]\n nfiles = len(fnames)\n\n # -- initialize the image\n sh = (3072 // (2 * fac), 4096 // (2 * fac), 3)\n img = np.zeros(sh, dtype=np.uint8)\n\n # -- loop through files and convert\n for ii, fname in enumerate(fnames):\n imname = fname.replace(\"raw\", \"jpg\")\n if os.path.isfile(imname):\n continue\n if (ii + 1) % 25 == 0:\n print(\"\\rworking on file {0:5} of {1:5}...\" \\\n .format(ii + 1, nfiles)), \n sys.stdout.flush()\n img[...] = read_raw(fname, rgb=True)[::fac, ::fac]\n spm.imsave(imname , stretch_image(gamma_scale((img / scl) \\\n .clip(0, 255).astype(np.uint8), 0.5, 2.0), (60, 200)))\n print(\"\")\n\n\ndef get_timestamp(nights):\n \"\"\"\n Nights = list of 2-tuples of (month,night): str fomrmat i.e. [(\"06\",\"25\")]\n \"\"\"\n night_dict = {}\n\n for n in nights:\n data_dir = os.path.join(bb_settings.DATA_FILEPATH, n[0], n[1])\n night_dict[n] = [datetime.datetime.fromtimestamp(os.path.getmtime(os.path.join(\n data_dir, file))) for file in sorted(os.listdir(data_dir))[100:2700]]\n\n return night_dict\n\n\ndef clip_labels(cliptype='hsi', light_class='all', lower_thresh=20, upper_sig=2):\n\n if cliptype == 'hsi_mask': # all sources in HSI mask\n hsi_l, hsi_s = np.unique(bb_settings.FINAL_MASK, return_counts=True)\n\n return hsi_l\n\n elif cliptype == 'hsi': # sources with classified spectra\n if light_class == 'all':\n return bb_settings.SPECTRA_CLASS[bb_settings.SPECTRA_CLASS.columns[-4]].values\n else:\n selector_msk = bb_settings.SPECTRA_CLASS[\n bb_settings.SPECTRA_CLASS.columns[-2]] == light_class\n\n return bb_settings.SPECTRA_CLASS[selector_msk][bb_settings.SPECTRA_CLASS.columns[-4]].values\n\n elif cliptype == 'gowanus': # sources estimated to be in Gowanus public housing\n new_hsi = bb_settings.FINAL_MASK[1000:1100, 1610:1900].copy()\n hsi_l, hsi_s = np.unique(new_hsi, return_counts=True)\n\n return hsi_l\n\n elif cliptype == 'manual': # manually set lower/upper bounds\n # upper thresh\n thresh = bb_settings.SIZES[1:].mean() + bb_settings.SIZES[1:].std()*upper_sig\n\n size_msk = (bb_settings.SIZES < thresh) & (bb_settings.SIZES > lower_thresh)\n\n return bb_settings.LABELS[size_msk]\n\n\ndef load_lc(cube=True, clip=None):\n \"\"\"\n Loads previously extracted lightcuves. \n If cube = False, returns a 2-d array time series (num total multi night timesteps x num sources)\n If cube = True, it does so three-dimensionally by night (num nights x timestep/night x num sources)\n \"\"\"\n\n # get\n if cube:\n curves = np.empty((bb_settings.NUM_CURVES, bb_settings.CURVE_LENGTH, len(bb_settings.LABELS[1:])))\n\n nidx = 0\n\n for i in sorted(os.listdir(bb_settings.CURVES_FILEPATH)):\n curves[nidx, :, :] = (np.load(os.path.join(bb_settings.CURVES_FILEPATH, i)))\n nidx += 1\n\n else:\n all_curves = []\n\n for i in sorted(os.listdir(bb_settings.CURVES_FILEPATH)):\n all_curves.append(np.load(os.path.join(bb_settings.CURVES_FILEPATH, i)))\n\n curves = np.concatenate(all_curves, axis=0)\n\n if clip is not None:\n\n if cube:\n return curves[:, :, clip]\n else:\n return curves[:, clip]\n\n else:\n return curves\n\n\ndef load_onoff(cube=True, clip=None):\n\n if cube:\n ons = np.empty((bb_settings.NUM_EDGES, bb_settings.CURVE_LENGTH, len(bb_settings.LABELS[1:])))\n offs = np.empty((bb_settings.NUM_EDGES, bb_settings.CURVE_LENGTH, len(bb_settings.LABELS[1:])))\n\n nidx = 0\n fidx = 0\n\n for i in sorted(os.listdir(bb_settings.EDGE_PATH)):\n if i.split('_')[-1] == 'ons.npy':\n ons[nidx, :, :] = (np.load(os.path.join(bb_settings.EDGE_PATH, i)))\n nidx += 1\n\n elif i.split('_')[-1] == 'offs.npy':\n offs[fidx, :, :] = (np.load(os.path.join(bb_settings.EDGE_PATH, i)))\n fidx += 1\n\n else:\n all_ons = []\n all_offs = []\n\n for i in sorted(os.listdir(bb_settings.EDGE_PATH)):\n if i.split('_')[-1] == 'ons.npy':\n all_ons.append(np.load(os.path.join(bb_settings.EDGE_PATH, i)))\n\n elif i.split('_')[-1] == 'offs.npy':\n all_offs.append(np.load(os.path.join(bb_settings.EDGE_PATH, i)))\n\n ons = np.concatenate(all_ons, axis=0)\n\n offs = np.concatenate(all_offs, axis=0)\n\n if clip is not None:\n\n if cube:\n return ons[:, :, clip], offs[:, :, clip]\n else:\n return ons[:, clip], offs[:, clip]\n\n else:\n return ons, offs\n\n\ndef plot(data=bb_settings.LABELS_MASK, clip=None):\n if clip is not None:\n final_msk = np.isin(data, clip)\n\n data[~final_msk] = 0\n\n plotting.quick_source_info(data, clim=None, oname=None)\n\n return\n\n\n\n\n\n","sub_path":"rebound/bb/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"157868138","text":"'''\n[剑指 Offer 26. 树的子结构 - 力扣(LeetCode)](https://leetcode-cn.com/problems/shu-de-zi-jie-gou-lcof)\n\n输入两棵二叉树A和B,判��B是不是A的子结构。(约定空树不是任意一个树的子结构)\n\nB是A的子结构, 即 A中有出现和B相同的结构和节点值。\n\n例如:\n给定的树 A:\n\n     3\n    / \\\n   4   5\n  / \\\n 1   2\n给定的树 B:\n\n   4 \n  /\n 1\n返回 true,因为 B 与 A 的一个子树拥有相同的结构和节点值。\n\n示例 1:\n\n输入:A = [1,2,3], B = [3,1]\n输出:false\n\n\n示例 2:\n\n输入:A = [3,4,5,1,2], B = [4,1]\n输出:true\n\n限制:\n\n0 <= 节点个数 <= 10000\n'''\n\n## 有一个坑,就是如果这些节点的val是会重复的,比如例题里面,值为4的节点有俩。\n## 直接就做出来了,没有参考。而且做的还可以。应该能够独立面对这种题目的吧。\n'''\n解析一下. 就是啊, isSubStructure方法是需要去找一个节点跟待查树的根节点一样,然后在判断后面的树的.\n如果当前根节点跟待查根节点不一样, 也可以进行下去, 直到遍历完或者是找到为止. \n而subTreeIsSubStructure不一样, 是不能从当前根节点去找一个跟待查节点一样的节点然后递归的. 如果关键路径上找到不一样的节点, 是会GG的.\n\n所以还真就得按照我的这个实现来做. 没有捷径可以走. 我这个方法估计就是我能想到的极限了. \n'''\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution:\n def subTreeIsSubStructure(self, root1, root2):\n ## 两者皆空\n if root1 == root2 == None:\n return True\n ## 两者皆不空\n if root1 != None and root2 != None:\n ## 两个值不等,GG。\n if root1.val != root2.val:\n return False\n else:\n leftPartRst = rightPartRst = True\n ## 右树的子树如果是None,那就不用判断了;若非None,就递归接着判断。\n if root2.left != None:\n leftPartRst = self.subTreeIsSubStructure(root1.left, root2.left)\n if root2.right != None:\n rightPartRst = self.subTreeIsSubStructure(root1.right, root2.right)\n return leftPartRst and rightPartRst\n ## 一者为空\n return False\n\n def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:\n if A == None:\n return False\n if B == None:\n return False\n ## 假设都不是空节点\n ### 判断两棵原始树的根节点,如果根节点一样,就判断这两颗子树\n ### 就算两颗子树的结果为false,那么因为B.val在A树里面可能多次出现,所以还不能最终返回false;但是如果返回的true,那就可以直接返回true了。\n if A.val == B.val:\n partRst = self.subTreeIsSubStructure(A, B) #self.subTreeIsSubStructure(A.left, B.left) and self.subTreeIsSubStructure(A.right, B.right)\n if partRst == True:\n return True\n ## 然后判断A的左右子树能否包含B树。\n return self.isSubStructure(A.left, B) or self.isSubStructure(A.right, B)\n ###############################################################################################3\n\n##-----------------------------------------------------------------------------\n\nimport os, sys, re\nselfName = os.path.basename(sys.argv[0])\nid = selfName.replace(\"JianzhiOffer\", \"\").replace(\".py\", \"\")\n# id = \"57\"\n\nround1_dir = \"C:/Users/XMK23/Documents/Leetcode-Journey/py-jianzhi-round1\"\nfor f in os.listdir(round1_dir):\n if \".py\" not in f:\n continue\n num = re.findall(\"\\d+-*I*\", f)\n if len(num) == 0:\n continue\n id_ = num[0]\n if id == id_:\n with open(os.path.join(round1_dir, f), \"r\", encoding=\"utf-8\") as rdf:\n lines = rdf.readlines()\n print(f)\n print(\"\".join(lines))\n print()","sub_path":"py-jianzhi-round3/JianzhiOffer26.py","file_name":"JianzhiOffer26.py","file_ext":"py","file_size_in_byte":4093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"545746957","text":"from flask import Flask\nfrom flask_socketio import SocketIO\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'secret!'\nsocketio = SocketIO(app)\n\n\n@app.route('/')\ndef index():\n return render_template('agent.html')\n\n@socketio.on('test')\ndef handle_message(message):\n print('received test: ' + message)\n socketio.emit('test', 'hai!')\n\n\n@socketio.on('connect')\ndef test_connect():\n print('got a connect')\n socketio.emit('my response', {'data': 'Connected'})\n\n\nif __name__ == '__main__':\n socketio.run(app, port=3000)\n","sub_path":"socket_io_tests/python-only-test-v1/sio.py","file_name":"sio.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"88686015","text":"#-*-coding: utf-8 *-*\n'''\nCreated on 21 mai 2012\n\n@author: Askylh Snake\n'''\nimport fenetre , sys\nfrom PyQt4.QtGui import QApplication\n\ndef main(args):\n app = QApplication(args)\n lfenetre=fenetre.MaFenetre()\n lfenetre.show()\n r = app.exec_()\n return r \n\nif __name__==\"__main__\":\n main(sys.argv)","sub_path":"src/Test/pyqt4/fenetreAppel.py","file_name":"fenetreAppel.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"250301223","text":"from handlers import BaseHandler\nfrom models import Post, posts_key\nfrom google.appengine.ext import ndb\n\n\nclass EditPost(BaseHandler):\n \"\"\"Login user can edit blog posts only which user posts.\"\"\"\n def get(self, post_id):\n if not self.user:\n self.redirect('/login')\n return\n post_key = ndb.Key('Post', int(post_id), parent=posts_key())\n post = post_key.get()\n if not post:\n self.error(404)\n return\n author_id = post.author_key.id()\n login_id = self.user.key.id()\n if not author_id == login_id:\n message = \"This is not your post!\"\n self.render(\"page-message.html\", message=message)\n return\n self.render(\"form-edit-post.html\", p=post)\n return\n\n def post(self, post_id):\n if not self.user:\n self.redirect('/login')\n return\n post_key = ndb.Key('Post', int(post_id), parent=posts_key())\n post = post_key.get()\n author_id = post.author_key.id()\n login_id = self.user.key.id()\n if not author_id == login_id:\n message = \"This is not your post!\"\n self.render(\"page-message.html\", message=message)\n return\n post.subject = self.request.get('subject')\n post.content = self.request.get('content')\n if post.subject and post.content:\n post.put()\n self.redirect('/blog/%s/show' % str(post.key.id()))\n return\n else:\n error = \"subject and content, please!\"\n self.render(\"form-editpost.html\",\n subject=post.subject,\n content=post.content,\n error=error)\n return\n","sub_path":"handlers/EditPost.py","file_name":"EditPost.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"17293946","text":"#Name:Ojas Joshi\r\n#Gr no:11810839\r\n#roll no:23\r\n#Division:M\r\ndef armstrong(n):\r\n sum=0\r\n t=n\r\n while t>0:\r\n d=t%10\r\n sum=t**3\r\n t=t//10\r\n return sum\r\nn=int(input(\"Enter a number\"))\r\ny=armstrong(n)\r\nprint(y)\r\n","sub_path":"Angstrom_number.py","file_name":"Angstrom_number.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"339643207","text":"from django.urls import path,include\r\nfrom .views import *\r\nfrom . import views\r\nimport re\r\napp_name = 'management'\r\n\r\nurlpatterns = [\r\n path('',views.home, name='home'),\r\n path(\"addstudent/\",AddStudent.as_view(),name='addstudent' ),\r\n path(\"student/\",StudentView.as_view(),name=\"students\"),\r\n path('student//delete/', DeleteStudent.as_view()), \r\n path('student//update/', UpdateStudent.as_view()), \r\n#############################################################\r\n path(\"addsemsec/\",AddSemsec.as_view(),name=\"addsemsec\"),\r\n path(\"semsec/\",SemsecView.as_view(),name=\"semsec\"),\r\n path('semsec//delete/', DeleteSemsec.as_view()), \r\n path('semsec//update/', UpdateSemsec.as_view()),\r\n#############################################################\r\n path(\"addsubject/\",AddSubject.as_view(),name=\"addsubject\"),\r\n path(\"subject/\",SubjectView.as_view(),name = \"subject\"),\r\n path('subject//delete/', DeleteSubject.as_view()), \r\n path('subject//update/', UpdateSubject.as_view()),\r\n#############################################################\r\n path(\"addmarks/\",Addmarks.as_view(),name = \"addmarks\"),\r\n path(\"marks/\",MarksView.as_view(),name = \"marks\"),\r\n path('marks//', views.marksubview),\r\n path('marks//delete/', DeleteMarks.as_view()), \r\n path('marks//update/', UpdateMarks.as_view()),\r\n#############################################################\r\n path(\"addfaculty/\",AddFaculty.as_view(),name=\"addfaculty\"),\r\n path(\"faculty/\",FacultyView.as_view(),name = \"faculty\"),\r\n path('faculty//delete/', DeleteFaculty.as_view()), \r\n path('faculty//update/', UpdateFaculty.as_view()),\r\n#############################################################\r\n path(\"addincharge/\",AddIncharge.as_view(),name=\"addincharge\"),\r\n path(\"incharge/\",InchargeView.as_view(),name = \"incharge\"),\r\n path('incharge//delete/', DeleteIncharge.as_view()), \r\n path('incharge//update/', UpdateIncharge.as_view()),\r\n################################### EXTRA #################\r\n path('Outstanding',views.Outstanding, name='Outstanding'),\r\n path('Execelent',views.Execelent, name='Execelent'),\r\n path('Average',views.Average, name='Average'),\r\n path('Improve',views.Improve, name='Improve'),\r\n#####################\r\n path('Upgrade',views.Upgrade, name='Upgrade'), \r\n####################\r\n path('login/', login_page, name='login'),\r\n path('logout/', logout_page, name='logout'), \r\n]","sub_path":"management/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"514959237","text":"import scrapy\nfrom ..items import SpideritviecItem\n\nclass QuotesSpider(scrapy.Spider):\n name = \"profile\"\n\n def start_requests(self):\n urls = [\n 'https://itviec.com/it-jobs/da-nang',\n 'https://itviec.com/it-jobs/da-nang?page=2'\n ]\n for url in urls:\n yield scrapy.Request(url=url, callback=self.parse)\n\n def parse(self, response):\n for href in response.css('.title > a::attr(\"href\")'):\n next_page = response.urljoin(href.extract())\n yield scrapy.Request(next_page, callback=self.parse_dir_contents)\n\n def parse_dir_contents(self, response):\n item = SpideritviecItem()\n name = response.css('.name > a::text').get()\n image = response.css('.logo > a >img::attr(\"src\")').get()\n address = response.css('.address__full-address > span::text').get()\n\n item['name'] = name\n item['logoImage'] = image\n item['address'] = address\n yield item\n","sub_path":"spiderItViec/spiders/profile.py","file_name":"profile.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"83319130","text":"from discord.ext import commands\nfrom discord import Embed\nfrom aiohttp import ClientSession\nfrom json import loads\n\n\nasync def get(session: object, url: object) -> object:\n async with session.get(url) as response:\n return await response.text()\n\n\nasync def urban(data):\n data = loads(data)\n if len(data['list']) == 0:\n return False\n data = data['list'][0]\n udef = Embed()\n udef.color = 0x114ee8\n udef.title = data['word']\n udef.description = f\"**Definition:**\\n\\n{data['definition']}\\n\\n**Example:**\\n\\n{data['example']}\"\n udef.url = data['permalink']\n udef.set_footer(text=f\"{data['thumbs_up']} 👍 {data['thumbs_down']} 👎 by {data['author']}\",\n icon_url=\"https://i.ibb.co/3fsGdvp/unnamed.png\")\n return udef\n\n\nclass Urban(commands.Cog):\n \"\"\"Urban Dictionary\n \"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command(name='ud', aliases=['define', 'urban'])\n async def _urbandict(self, ctx, *, term):\n \"\"\"\n Get Urban Dictionary definitions\n ?ud word\n \"\"\"\n term = term.replace(\" \", \"+\")\n url = f\"http://api.urbandictionary.com/v0/define?term={term}\"\n async with ClientSession() as session:\n data = await get(session, url)\n data = await urban(data)\n if data is False:\n return await ctx.send(f'Could not find UD entry for {term}')\n return await ctx.send(embed=data)\n\n\ndef setup(bot):\n bot.add_cog(Urban(bot))\n","sub_path":"cogs/urban.py","file_name":"urban.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"308706351","text":"def pickingNumbers(a):\r\n max=0\r\n for i in a:\r\n c=a.count(i)\r\n d=a.count(i-1)\r\n c+=d\r\n if c>max:\r\n max=c\r\n return max\r\n\r\nif __name__ == '__main__':\r\n n = int(input().strip())\r\n\r\n a = list(map(int, input().rstrip().split()))\r\n\r\n result = pickingNumbers(a)\r\n\r\n print(result)\r\n","sub_path":"Picking Numbers.py","file_name":"Picking Numbers.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"572101937","text":"from __future__ import division\n__author__ = 'angiuli'\n\nimport numpy\n\ndef pi(x,x_min,x_max,delta_x):\n\n low=(x-x_min)//delta_x\n\n if low>=num_x-1:\n\n x_index=num_x-1\n\n elif low<1:\n\n x_index=0\n\n elif (x-x_min-low*delta_x)<(x_min+(low+1)*delta_x-x):\n\n x_index=low\n else:\n\n x_index=low+1\n\n return(x_index)\n\npi(-8.5,-10,4,1.3)\n","sub_path":"Old/pi.py","file_name":"pi.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"427176238","text":"import json\nimport math\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\n\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\n\nimport time\nimport requests\nimport pandas as pd\nimport re\nimport json\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\nfrom pandas import DataFrame\nfrom pandas import concat\nfrom xgboost import XGBRegressor\nimport numpy as np\nimport numpy\n\nfrom .models import MemberForRecommend\nfrom selenium.webdriver.common.action_chains import ActionChains\n\n\n\n\n\n# Create your views here.\n@api_view(['GET', 'POST'])\ndef index(request):\n return HttpResponse(\"my_to_do_app first page\")\n\n\n@api_view(['GET', 'POST'])\ndef memberInfo(request):\n\n # JSON 반환\n data = {\n 'nickName' : '',\n 'level' : '',\n 'tier' : '',\n 'tierInfo' : '',\n 'wins' : '',\n 'losses' : '',\n 'winRatio' : '',\n 'LikePosition' : '',\n \n }\n\n searchName=request.GET[\"BangJang\"]\n Name=searchName\n searchName=searchName.replace(\" \", \"\")\n\n print(Name)\n url = 'https://www.op.gg/summoner/userName=' + searchName\n\n \n \n #헤드리스 시작\n options = webdriver.ChromeOptions()\n options.add_argument('headless')\n options.add_argument('--no-sandbox')\n options.add_argument('--disable-dev-shm-usage')\n #options.add_argument(\"disable-gpu\")\n # 혹은 options.add_argument(\"--disable-gpu\")\n \n\n driver = webdriver.Chrome('/home/ubuntu/django/mysite/chromedriver', options=options)\n #헤드리스끝\n \n\n \n \n driver.get(url)\n\n ## 암묵적으로 웹 자원 로드를 위해 3초까지 기다려 준다.\n driver.implicitly_wait(3)\n \n resp = driver.page_source\n \n soup = BeautifulSoup(resp, 'html.parser')\n \n \n \n #\n \n result = ''\n find_string = '기록된 전적이 없습니다.'\n\n try :\n position=driver.find_element_by_css_selector('.PositionStatContent > .Name').text\n except :\n position=\"선호하는 포지션이 없습니다.\"\n \n #except랑 다르게 아예정보없는 사람말고 정보는 있는데 몇판안해서 이럴수 있음\n if position == \"\" :\n data['LikePosition'] = \"선호하는 포지션이 없습니다.\" \n else :\n data['LikePosition'] = position\n\n \n\n \n\n # 소환사 이름 불러오기\n nickName = soup.select('div.Information > span.Name')[0].get_text().strip()\n\n # 소환사 레벨 불러오기\n level = soup.find('span', class_='Level tip').get_text().strip()\n\n '''\n 아래는 모두 솔로랭크 데이터\n '''\n # 소환사 티어 불러오기\n tier = soup.find('div', class_='TierRank').get_text().strip()\n\n # 소환사 상세 티어 정보 불러오기\n # 만약 언랭이라면 언랭으로 표시\n if tier == 'Unranked':\n tierInfo = '0 LP'\n # 랭크가 있으면 랭크 표시\n else:\n tierInfo = soup.find('span', class_='LeaguePoints').get_text().strip()\n\n # 소환사 승 불러오기\n if tier == 'Unranked':\n wins = '0'\n else:\n wins = soup.find('span', class_='wins').get_text().strip()\n\n # 소환사 패 불러오기\n if tier == 'Unranked':\n losses = '0'\n else:\n losses = soup.find('span', class_='losses').get_text().strip()\n\n # 소환사 승률 불러오기\n if tier == 'Unranked':\n winRatio = '승률 0%'\n else:\n winRatio = soup.find('span', class_='winratio').get_text().strip()\n\n\n \n\n data['nickName'] = Name\n data['level'] = level\n data['tier'] = tier.split(' ')[0]\n data['tierInfo'] = tierInfo\n data['wins'] = wins.replace(\"W\",\"\")\n data['losses'] = losses.replace(\"L\",\"\")\n data['winRatio'] = winRatio\n \n\n json_data = json.dumps(data, ensure_ascii=False)\n return HttpResponse(json_data)\n\n@api_view(['GET', 'POST'])\ndef predictTime(request):\n\n\n\n searchName=request.GET[\"BangJang\"]\n Name=searchName\n searchName=Name.replace(\" \", \"\")\n\n print(\"실행이잘되고 있는건지1\")\n hdr = {'Accept-Language': 'ko_KR,en;q=0.8', 'User-Agent': (\n 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Mobile Safari/537.36')}\n\n\n url = 'https://www.op.gg/summoner/userName=' + searchName\n\n \n print(\"실행이잘되고 있는건지2\")\n #헤드리스 시작\n options = webdriver.ChromeOptions()\n options.add_argument('headless')\n options.add_argument('--no-sandbox')\n options.add_argument('--disable-dev-shm-usage')\n #options.add_argument(\"disable-gpu\")\n # 혹은 options.add_argument(\"--disable-gpu\")\n # 속도 향상을 위한 옵션 해제\n prefs = {'profile.default_content_setting_values': {'cookies' : 2, 'images': 2, 'plugins' : 2, 'popups': 2, 'geolocation': 2, 'notifications' : 2, 'auto_select_certificate': 2, 'fullscreen' : 2, 'mouselock' : 2, 'mixed_script': 2, 'media_stream' : 2, 'media_stream_mic' : 2, 'media_stream_camera': 2, 'protocol_handlers' : 2, 'ppapi_broker' : 2, 'automatic_downloads': 2, 'midi_sysex' : 2, 'push_messaging' : 2, 'ssl_cert_decisions': 2, 'metro_switch_to_desktop' : 2, 'protected_media_identifier': 2, 'app_banner': 2, 'site_engagement' : 2, 'durable_storage' : 2}} \n options.add_experimental_option('prefs', prefs)\n\n driver = webdriver.Chrome('/home/ubuntu/django/mysite/chromedriver', options=options)\n #헤드리스끝\n print(\"실행이잘되고 있는건지3\")\n \n driver.get(url)\n\n ## 암묵적으로 웹 자원 로드를 위해 3초까지 기다려 준다.\n driver.implicitly_wait(3)\n \n resp = driver.page_source\n\n # 크롤링 가능 여부 확인\n soup = BeautifulSoup(resp, 'html.parser')\n\n # 크롤링 가능 여부 확인\n check = ''\n find_string = '기록된 전적이 없습니다.'\n\n soup_new = soup.prettify()\n result_list = soup_new.split('\\n')\n print(\"실행이잘되고 있는건지4\")\n data = {\n 'TimePredict' : ''\n }\n\n for i in result_list:\n if find_string in i:\n i = i.strip()\n check = i \n \n if find_string == check:\n data['TimePredict'] = check\n\n json_data = json.dumps(data, ensure_ascii=False)\n\n print(json_data)\n\n else:\n \n \n #아래처럼 하는게 안정성이 더높음, 적을때, 무한루프 걸리지않고,\n #오버해서 검색하지도 않음 딱적정하게 됨, 더 빨리 할 수 있으나 안전성 문제가 있음, 예외처리가 나거나\n #안불러와지는경우가있음\n\n try :\n while True :\n try:\n print(\"실행이잘되고 있는건지5클릭 클릭\")\n try:\n driver.find_element_by_css_selector('.GameMoreButton').click()\n except:\n print(\"이 예외는 클릭을 못하는겁니다.\")\n break;\n try:\n message1=driver.find_element_by_css_selector('.ErrorMessage > div').text\n except:\n print(\"이예외는 끝이나야 끝납니다.\")\n if message1 == \"기록된 전적이 없습니다.\" :\n print(\"빠르게 제대로 찾았는지확인\")\n break\n except:\n continue\n except:\n return HttpResponse(\"Fail\")\n \n time.sleep(5)\n\n page = driver.page_source\n \n soup = BeautifulSoup(page, 'html.parser')\n\n game_time = []\n\n # 게임 시간 리스트 초기화\n game_times_list = []\n # 게임 시간 기준대로 나누는거 초기화\n game_times_split = []\n game_times_split_a=[]\n game_times_split_b=[]\n game_times_split_min = []\n\n # 오전 오후 나누는 시간 기준\n time_standard = 'A'\n\n result = 0\n\n # 게임 시간\n all_games_rows = soup.find_all('div', class_='GameItemWrap')\n\n \n if len(all_games_rows) > 1000 :\n all_games_rows = all_games_rows[:1000]\n\n print(len(all_games_rows))\n\n for all_games_row in all_games_rows:\n \n game_time_content = all_games_row.find('div', class_='Content')\n\n game_time_gamestats = game_time_content.find('div', class_='GameStats')\n\n game_time_timestamp = game_time_gamestats.find('div', class_='TimeStamp')\n\n game_times = game_time_timestamp.find('span', class_='_timeago _timeCountAssigned tip').get('title')\n\n # print(game_times)\n \n # 분\n game_times_split_min = game_times.split(':')\n game_times_split_min = game_times_split_min[1].split(' ')\n result = int(game_times_split_min[0])\n \n\n\n # 시\n game_times_split = game_times.split(' ')\n game_times_split_a = game_times_split[3]\n game_times_split_a = game_times_split_a.split(':')\n game_times_split_a = game_times_split_a[0]\n\n game_times_split_b = game_times_split[4]\n\n #오전\n if time_standard in game_times_split_b:\n game_times_split = int(game_times_split_a) * 60\n # 12 * 60\n if game_times_split == 7200:\n game_times_split = 0\n result += game_times_split\n game_times_list.append(result)\n else:#오후 \n game_times_split = (int(game_times_split_a) + 12) * 60\n result += game_times_split\n game_times_list.append(result)\n print(result)\n result = 0\n\n # dataframe 형태\n\n print(\"실행이잘되고 있는건지5\")\n # 예측 날짜\n days_in = len(game_times_list) // 2\n day_out = 1\n\n # 게임 시간\n\n values = numpy.array(game_times_list, dtype=np.float64)\n\n df = DataFrame(values)\n \n # 학습을 위한 배열\n raw = []\n \n for i in range(days_in, 0, -1):\n raw.append(df.shift(i))\n \n for i in range(0, day_out):\n raw.append(df.shift(-i))\n\n # print(raw)\n sum = concat(raw, axis = 1)\n\n sum.dropna(inplace = True)\n\n # Supervised Learning 데이터로 변형된 데이터는 train에 저장\n train = sum.values\n\n # 모델 훈련 및 예측\n trainX, trainy = train[:, :-1], train[:, -1]\n\n # days_in, n_estimators 값에 따라 예측 값이 달라진다.\n model = XGBRegressor(objective=\"reg:squarederror\", n_estimators=80)\n model.fit(trainX, trainy)\n\n data_in = values[-(days_in):]\n\n # 예측 시간\n result = model.predict(np.array([data_in]))\n\n # json 반환\n data = {\n 'TimePredict' : ''\n }\n print(\"실행이잘되고 있는건지6\")\n\n data['TimePredict'] = math.floor(result[0]/60)\n \n temp_123=0;\n if math.floor(result[0]/60) == 24 :\n temp_123=0\n else :\n temp_123=math.floor(result[0]/60)\n\n member = MemberForRecommend.objects.filter(nickname=Name)\n member.update(time_predict=math.floor(temp_123))\n \n\n data_convert = {k:float(v) for k,v in data.items()}\n\n json_data = json.dumps(data_convert, ensure_ascii=False)\n \n driver.close()\n print(\"실행이잘되고 있는건지7\")\n\n print(json_data)\n print(\"계산끝_db저장되었을거임\")\n\n\n\n return HttpResponse(json_data)\n\n\n\n\n\n@api_view(['GET', 'POST'])\ndef Ingame(request):\n\n Name=request.GET[\"nickName\"]\n \n searchName=Name.replace(\" \", \"\")\n\n Name=searchName\n\n # 갱신하기\n #헤드리스 시작\n # options = webdriver.ChromeOptions()\n # options.add_argument('headless')\n # options.add_argument('--no-sandbox')\n # options.add_argument('--disable-dev-shm-usage')\n #options.add_argument(\"disable-gpu\")\n # 혹은 options.add_argument(\"--disable-gpu\")\n \n \n# 속도 향상을 위한 옵션 해제\n #prefs = {'profile.default_content_setting_values': {'cookies' : 2, 'images': 2, 'plugins' : 2, 'popups': 2, 'geolocation': 2, 'notifications' : 2, 'auto_select_certificate': 2, 'fullscreen' : 2, 'mouselock' : 2, 'mixed_script': 2, 'media_stream' : 2, 'media_stream_mic' : 2, 'media_stream_camera': 2, 'protocol_handlers' : 2, 'ppapi_broker' : 2, 'automatic_downloads': 2, 'midi_sysex' : 2, 'push_messaging' : 2, 'ssl_cert_decisions': 2, 'metro_switch_to_desktop' : 2, 'protected_media_identifier': 2, 'app_banner': 2, 'site_engagement' : 2, 'durable_storage' : 2}} \n # options.add_experimental_option('prefs', prefs)\n # driver = webdriver.Chrome('/home/ubuntu/django/mysite/chromedriver', options=options)\n #헤드리스끝\n \n\n \n #url = 'https://www.op.gg/summoner/userName=' + Name\n #action = ActionChains(driver)\n #driver.get(url)\n\n \n #try:\n # driver.find_element_by_css_selector('.Button.SemiRound.Blue').click()\n # action.send_keys(Keys.ENTER)\n # time.sleep(1)\n #except Exception as ex:\n # print(\"exception: \", ex)\n # driver.quit()\n # #driver.quit()\n\n # 블루팀 닉네임\n Bt_nickName = []\n # 블루팀 티어\n Bt_tier = []\n # 블루팀 티어 이미지\n Bt_tier_img = []\n # 블루팀 랭크 승률\n Bt_rank = []\n # 블루팀 챔피언 승률\n Bt_champ = []\n # 블루팀 kda\n Bt_kda = []\n # 블루팀 챔프\n Bt_champName = []\n\n # 블루팀 포인트\n Bt_point = 0\n\n # 레드팀 닉네임\n Rt_nickName = []\n # 레드팀 티어\n Rt_tier = []\n # 레드팀 티어 이미지\n Rt_tier_img = []\n # 레드팀 랭크 승률\n Rt_rank = []\n # 레드팀 챔피언 승률\n Rt_champ = []\n # 레드팀 kda\n Rt_kda = []\n\n # 레드팀 챔프\n Rt_champName = []\n\n # 레드팀 포인트\n Rt_point = 0\n\n\n #헤드리스 시작\n options = webdriver.ChromeOptions()\n options.add_argument('headless')\n options.add_argument('--no-sandbox')\n options.add_argument('--disable-dev-shm-usage')\n #options.add_argument(\"disable-gpu\")\n # 혹은 options.add_argument(\"--disable-gpu\")\n prefs = {'profile.default_content_setting_values': {'cookies' : 2, 'images': 2, 'plugins' : 2, 'popups': 2, 'geolocation': 2, 'notifications' : 2, 'auto_select_certificate': 2, 'fullscreen' : 2, 'mouselock' : 2, 'mixed_script': 2, 'media_stream' : 2, 'media_stream_mic' : 2, 'media_stream_camera': 2, 'protocol_handlers' : 2, 'ppapi_broker' : 2, 'automatic_downloads': 2, 'midi_sysex' : 2, 'push_messaging' : 2, 'ssl_cert_decisions': 2, 'metro_switch_to_desktop' : 2, 'protected_media_identifier': 2, 'app_banner': 2, 'site_engagement' : 2, 'durable_storage' : 2}}\n options.add_experimental_option('prefs', prefs)\n\n\n driver = webdriver.Chrome('/home/ubuntu/django/mysite/chromedriver', options=options)\n #헤드리스끝\n \n\n \n\n # driver = webdriver.Chrome()\n url = 'https://www.op.gg/summoner/userName=' + Name\n \n\n driver.get(url)\n \n \n \n Container = {}\n\n \n \n driver.find_element_by_css_selector('.SpectateTabButton').click()\n \n time.sleep(5)\n \n\n \n html = driver.page_source\n \n\n soup = BeautifulSoup(html, 'html.parser')\n \n \n link = soup.find(\"link\").attrs['href']\n\n Container['Link'] = link\n \n \n ingameInfo = soup.find(\"div\", {\"class\" : \"tabItem Content SummonerLayoutContent summonerLayout-spectator\"})\n \n names = ingameInfo.find_all(\"td\", {\"class\" : \"SummonerName Cell\"})\n\n Container['Names'] = []\n \n \n #return containor는 에러 발생시킴\n if len(names) == 0:\n abc=\"fail\"\n json_data = json.dumps(abc, ensure_ascii=False)\n return HttpResponse(json_data)\n\n\n for name in names:\n Container['Names'].append(name.text.strip())\n Bt_nickName = Container['Names'][0:5]\n Rt_nickName = Container['Names'][5:]\n \n # 플레이 하는 챔피언\n champions = ingameInfo.find_all(\"td\", {\"class\" : \"ChampionImage Cell\"})\n Container['Champions'] = []\n for champion in champions:\n champ = str(champion.find(\"a\").attrs['href'])\n champ = champ.replace(\"/champion/\", '').replace(\"/statistics\", '').capitalize()\n Container['Champions'].append(champ)\n Bt_champName = Container['Champions'][0:5]\n Rt_champName = Container['Champions'][5:]\n # 티어\n tiers = ingameInfo.find_all(\"td\", {\"class\" : \"CurrentSeasonTierRank Cell\"})\n Container['Tiers'] = []\n for tier in tiers:\n Container['Tiers'].append(tier.text.strip())\n Bt_tier = Container['Tiers'][0:5]\n Rt_tier = Container['Tiers'][5:]\n\n # 티어 이미지\n tiers_imgs = ingameInfo.find_all(\"td\", {\"class\" : \"CurrentSeasonTier Cell\"})\n Container['Tiers_imgs'] = []\n # Container['Tiers_imgs'].append()\n for tiers_img in tiers_imgs:\n if tiers_img.find(\"img\", class_='Image tip') == None:\n Container['Tiers_imgs'].append(tiers_img.find(\"img\", class_='Image tip'))\n else:\n Container['Tiers_imgs'].append(tiers_img.find(\"img\", class_='Image tip').get('src'))\n Bt_tier_img = Container['Tiers_imgs'][0:5]\n Rt_tier_img = Container['Tiers_imgs'][5:]\n \n\n\n # 랭크 승률\n ratios = ingameInfo.find_all(\"td\", {\"class\" : \"RankedWinRatio Cell\"})\n Container['Ratios'] = []\n for ratio in ratios:\n Container['Ratios'].append(ratio.text.replace('\\n', '').replace('\\t', '').strip().split('%')[0])\n Bt_rank = Container['Ratios'][0:5]\n Rt_rank = Container['Ratios'][5:]\n\n Bt_rank_ori = Bt_rank\n Rt_rank_ori = Rt_rank\n\n # 챔피언 승률 및 KDA\n champRatios = ingameInfo.find_all(\"td\", {\"class\" : \"ChampionInfo Cell\"})\n Container['Champion Ratios'] = []\n for champRatio in champRatios:\n Container['Champion Ratios'].append(champRatio.text.replace(' ', '').replace('\\n', '').replace('\\t', '').strip())\n Bt_champ = Container['Champion Ratios'][0:9:2]\n Bt_kda = Container['Champion Ratios'][1:10:2]\n Rt_champ = Container['Champion Ratios'][10:19:2]\n Rt_kda = Container['Champion Ratios'][11:20:2]\n\n Bt_champ_ori = Bt_champ\n Bt_kda_ori = Bt_kda\n Rt_champ_ori = Rt_champ\n Rt_kda_ori = Rt_kda\n\n driver.quit()\n\n # 블루팀 티어 별 점수\n for tier in Bt_tier:\n if 'Challenger' in tier:\n Bt_point += 10\n elif 'Grandmaster' in tier:\n Bt_point += 9\n elif 'Master' in tier:\n Bt_point += 8\n elif 'Diamond 1' or 'Diamond 2' in tier:\n Bt_point += 7\n elif 'Diamond 3' or 'Diamond 4' in tier:\n Bt_point += 6\n elif 'Platinum' in tier:\n Bt_point += 5\n elif 'Gold' in tier:\n Bt_point += 4\n elif 'Silver' in tier:\n Bt_point += 3\n elif 'Bronze' in tier:\n Bt_point += 2\n else:\n Bt_point += 0\n \n #레드팀 티어 별 점수\n for tier in Rt_tier:\n if 'Challenger' in tier:\n Rt_point += 10\n elif 'Grandmaster' in tier:\n Rt_point += 9\n elif 'Master' in tier:\n Rt_point += 8\n elif 'Diamond 1' or 'Diamond 2' in tier:\n Rt_point += 7\n elif 'Diamond 3' or 'Diamond 4' in tier:\n Rt_point += 6\n elif 'Platinum' in tier:\n Rt_point += 5\n elif 'Gold' in tier:\n Rt_point += 4\n elif 'Silver' in tier:\n Rt_point += 3\n elif 'Bronze' in tier:\n Rt_point += 2\n else:\n Rt_point += 0\n\n # 블루팀 랭크 승률 없는 기록 제거\n Bt_rank_count = Bt_rank.count('-')\n\n Bt_rank = list(filter(('-').__ne__, Bt_rank))\n\n Bt_point += (Bt_rank_count * 5)\n \n # 블루팀 랭크 승률 별 점수\n for rank in Bt_rank:\n if 60 <= int(rank) <= 100:\n Bt_point += 10\n elif 55 <= int(rank) < 60:\n Bt_point += 8\n elif 50 <= int(rank) < 55:\n Bt_point += 6\n elif 45 <= int(rank) < 50:\n Bt_point += 4\n elif 40 <= int(rank) < 45:\n Bt_point += 2\n elif 0 <= int(rank) < 40:\n Bt_point += 0\n\n # 레드팀 랭크 승률 없는 기록 제거\n Rt_rank_count = Rt_rank.count('-')\n\n Rt_rank = list(filter(('-').__ne__, Rt_rank))\n\n Rt_point += (Rt_rank_count * 5)\n\n\n # 레드팀 랭크 승률 별 점수\n for rank in Rt_rank:\n if 60 <= int(rank) <= 100:\n Rt_point += 10\n elif 55 <= int(rank) < 60:\n Rt_point += 8\n elif 50 <= int(rank) < 55:\n Rt_point += 6\n elif 45 <= int(rank) < 50:\n Rt_point += 4\n elif 40 <= int(rank) < 45:\n Rt_point += 2\n elif 0 <= int(rank) < 40:\n Rt_point += 0\n\n # 블루팀 챔피언 승률\n Bt_champ_rate = []\n for champ in Bt_champ:\n Bt_champ_rate.append(champ.split('%')[0])\n\n # 블루팀 챔피언 승률 없는 데이터 제거\n Bt_champ_count = Bt_champ_rate.count('-')\n\n Bt_champ_rate = list(filter(('-').__ne__, Bt_champ_rate))\n\n Bt_point += Bt_champ_count * 5\n\n\n # 레드팀 챔피언 승률\n Rt_champ_rate = []\n for champ in Rt_champ:\n Rt_champ_rate.append(champ.split('%')[0])\n\n # 레드팀 챔피언 승률 없는 데이터 제거\n Rt_champ_count = Rt_champ_rate.count('-')\n\n Rt_champ_rate = list(filter(('-').__ne__, Rt_champ_rate))\n\n Rt_point += Rt_champ_count * 5\n\n # 블루팀 챔피언 승률 별 점수\n for rank in Bt_champ_rate:\n if 60 <= int(rank) <= 100:\n Bt_point += 10\n elif 55 <= int(rank) < 60:\n Bt_point += 8\n elif 50 <= int(rank) < 55:\n Bt_point += 6\n elif 45 <= int(rank) < 50:\n Bt_point += 4\n elif 40 <= int(rank) < 45:\n Bt_point += 2\n elif 0 <= int(rank) < 40:\n Bt_point += 0\n\n # 레드팀 챔피언 승률 별 점수\n for rank in Rt_champ_rate:\n if 60 <= int(rank) <= 100:\n Rt_point += 10\n elif 55 <= int(rank) < 60:\n Rt_point += 8\n elif 50 <= int(rank) < 55:\n Rt_point += 6\n elif 45 <= int(rank) < 50:\n Rt_point += 4\n elif 40 <= int(rank) < 45:\n Rt_point += 2\n elif 0 <= int(rank) < 40:\n Rt_point += 0\n\n # 없는 값 점수화 후 블루팀 KDA 없는 값 제거\n Bt_kda_count = Bt_kda.count('-')\n\n Bt_kda = list(filter(('-').__ne__, Bt_kda))\n \n Bt_point += Bt_kda_count * 2\n\n\n # 레드팀 KDA 없는 값 제거\n Rt_kda_count = Rt_kda.count('-')\n \n Rt_kda = list(filter(('-').__ne__, Rt_kda))\n\n Rt_point += Rt_kda_count * 2\n\n # 블루팀 KDA 별 점수\n for kda in Bt_kda:\n if kda.split('KDA')[0] == \"Perfect\" or float(kda.split('KDA')[0]) >= 6:\n Bt_point += 3\n if kda.split('KDA')[0] != \"Perfect\" and 3 <= float(kda.split('KDA')[0]) < 6:\n Bt_point += 2\n elif kda.split('KDA')[0] != \"Perfect\" and 1 <= float(kda.split('KDA')[0]) < 3:\n Bt_point += 1\n elif kda.split('KDA')[0] != \"Perfect\" and 0 <= float(kda.split('KDA')[0]) < 1:\n Bt_point += 0\n\n # 레드팀 KDA 별 점수\n for kda in Rt_kda:\n if kda.split('KDA')[0] == \"Perfect\" or float(kda.split('KDA')[0]) >= 6:\n Rt_point += 3\n if kda.split('KDA')[0] != \"Perfect\" and 3 <= float(kda.split('KDA')[0]) < 6:\n Rt_point += 2\n elif kda.split('KDA')[0] != \"Perfect\" and 1 <= float(kda.split('KDA')[0]) < 3:\n Rt_point += 1\n elif kda.split('KDA')[0] != \"Perfect\" and 0 <= float(kda.split('KDA')[0]) < 1:\n Rt_point += 0\n\n\n # JSON 반환\n data = {}\n\n data['블루팀'] = []\n data['레드팀'] = []\n\n for i in range(5):\n data['블루팀'].append({\n \"nickName\" : Bt_nickName[i],\n \"tier\" : Bt_tier[i],\n \"tierImg\" : Bt_tier_img[i],\n \"rankWinRate\" : Bt_rank_ori[i],\n \"champWinRate\" : Bt_champ_ori[i],\n \"kda\" : Bt_kda_ori[i],\n \"champName\" : Bt_champName[i],\n })\n data['레드팀'].append({\n \"nickName\" : Rt_nickName[i],\n \"tier\" : Rt_tier[i],\n \"tierImg\" : Rt_tier_img[i],\n \"rankWinRate\" : Rt_rank_ori[i],\n \"champWinRate\" : Rt_champ_ori[i],\n \"kda\" : Rt_kda_ori[i],\n \"champName\" : Rt_champName[i],\n })\n\n data['블루팀'].append({\n \"Bt_point\" : Bt_point\n })\n data['레드팀'].append({\n \"Rt_point\" : Rt_point\n })\n\n json_data = json.dumps(data, ensure_ascii=False)\n\n \n return HttpResponse(json_data)\n\n","sub_path":"backend_python/mysite/server1/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":24898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"522726705","text":"# -*- coding: utf-8 -*-\r\n# @Time:2018.9.14 14:52\r\n# @Author:Zhang\r\n# @Desc :\r\n\r\ndef f1(max):\r\n n,a,b=0,0,1\r\n while n Prefixes to use for RDF graph (triples)\r\nvtkel = Namespace('http://vksflickr30k.fbk.eu/resource/')\r\nks = Namespace('http://dkm.fbk.eu/ontologies/knowledgestore#')\r\nowl = Namespace('http://www.w3.org/2002/07/owl#')\r\ngaf = Namespace('http://groundedannotationframework.org/gaf#') \r\nnif = Namespace('http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#')\r\nprov = Namespace('https://www.w3.org/TR/prov-o/#prov-o-at-a-glance/') \r\nyago = Namespace('http://dbpedia.org/class/yago/')\r\nrdf = Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')\r\n \r\ng = Graph()\r\ng.bind(\"vtkel\",vtkel)\r\ng.bind(\"ks\",ks)\r\ng.bind(\"owl\",owl)\r\ng.bind(\"gaf\",gaf)\r\ng.bind(\"nif\",nif)\r\ng.bind(\"prov\",prov)\r\ng.bind(\"yago\",yago)\r\ng.bind(\"rdf\",rdf)\r\n#==> End of Prefixes to use for RDF graph (triples)\r\n\r\n###==>> Bounding boxes annotations\r\ndef Bounding_boxes_annotations(yolo_bb,yolo_class_ids_to_YAGO,yolo_class_ids,image_id):\r\n \"\"\"\r\n This function takes YOLO bounding box(es), class ids, YAGO entity types, image id and stored the visual entities information in RDF triples graph form.\r\n Input:\r\n yolo_bb – bounding boxes values detected by YOLO object detector\r\n yolo_class_ids_to_YAGO – YOLO class ids converted to YAGO type\r\n yolo_class_ids – yolo class ids e.g. person, racket etc..\r\n Output:\r\n g: return RDF graph of visual entities, types and bounding box values\r\n \"\"\"\r\n for i in range(len(yolo_bb)):\r\n uri_yolo_class_id=URIRef(vtkel[image_id+'I'+'/#'+yolo_class_ids[i]])\r\n uri_xywh=URIRef(vtkel[str(image_id)+'I'+'/#xywh='+str(yolo_bb[i][0])+','+str(yolo_bb[i][1])+','+str(yolo_bb[i][2])+','+str(yolo_bb[i][3])])\r\n g.add( (uri_yolo_class_id, URIRef(gaf['denotedBy']), uri_xywh) )\r\n g.add( (uri_yolo_class_id, URIRef(rdf['type']), URIRef(yago[yolo_class_ids_to_YAGO[i]])) )\r\n g.add( (uri_xywh, URIRef(rdf['type']), URIRef(ks['VisualEntityMention'])) )\r\n g.add( (uri_xywh, URIRef(ks['xmin']), Literal(yolo_bb[i][0])) )\r\n g.add( (uri_xywh, URIRef(ks['ymin']), Literal(yolo_bb[i][1])) )\r\n g.add( (uri_xywh, URIRef(ks['xmax']), Literal(yolo_bb[i][2])) )\r\n g.add( (uri_xywh, URIRef(ks['ymax']), Literal(yolo_bb[i][3])) )\r\n g.add( (uri_xywh, URIRef(prov['wasAttributedTo']), URIRef(vtkel['YOLOAnnotator'])) )\r\n return g","sub_path":"evaluation/Bounding_boxes_annotations.py","file_name":"Bounding_boxes_annotations.py","file_ext":"py","file_size_in_byte":2676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"15398375","text":"import numpy as np\nimport matplotlib as mpl\nfrom matplotlib import rc\nimport matplotlib.pyplot as plt\nfrom math import sqrt, pi, sin, cos\n\n\nmpl.rcParams['lines.linewidth'] = 1.0 # reduce default line width\nmpl.rcParams['mathtext.fontset'] = 'cm'\nrc('font', **{'family': 'serif', 'serif': ['CMU Serif Roman 2']})\nplt.close(\"all\")\n\n\ndef eval(N=201):\n L = 1\n dx = L/(N-1)\n dx2 = dx*dx\n x = np.linspace(0, L, N)\n\n # don't set up matrix for psi_0 and psi_N, since they are known\n N = N - 2\n A = np.zeros([N, N])\n\n for i in range(N):\n A[i, i] = 2/dx2\n if i > 0: # skip first row\n A[i, i-1] = -1/dx2\n if i < N-1: # skip last row\n A[i, i+1] = -1/dx2\n\n # eigh is for symmetric matrices, and returns sorted eigenvalues/vectors\n eigvals, eigvecs = np.linalg.eigh(A)\n\n # add boundary conditions (zeros)\n eigvecs = np.append(np.zeros([1, N]), eigvecs, axis=0)\n eigvecs = np.append(eigvecs, np.zeros([1, N]), axis=0)\n\n # sort according to size of eigenvalues\n # eigvecs = eigvecs[:, np.argsort(eigvals)]\n # eigvals = np.sort(eigvals)\n\n # normalize\n eigvecs /= sqrt(dx)\n\n # fix sign\n for i in range(eigvecs.shape[1]):\n if eigvecs[1, i] < 0:\n eigvecs[:, i] *= -1\n\n return x, eigvals, eigvecs\n\n\n## solve the time-dependent Schrödinger equation\nN = 201\nx, eigvals, psi_n = eval(N)\nnSteps = 2000\ndt = 1/nSteps\nn = len(eigvals)\n\n# set up initial condition (skip solving 2.14 since we know the result)\nalpha = np.zeros([n])\nalpha[0] = 1 # Psi(x, 0) = psi_1\n# alpha[0:2] = 0.5 # Psi(x, 0) = psi_1 + psi_2\n\n# print(alpha)\npsi = np.zeros([N, nSteps], dtype=np.complex_)\nfor i in range(nSteps): # loop over time steps\n t = dt*i\n\n # completely manual\n # for ix in range(N): # loop over positions\n # for ni in range(n): # loop over eigenvalues\n # psi[ix, i] += alpha[ni]*np.exp(-1j*eigvals[ni]*t)*psi_n[ix, ni]\n\n # one loop\n # for ix in range(N): # loop over positions\n # psi[ix, i] = np.sum(alpha*np.exp(-1j*eigvals*t)*psi_n[ix, :])\n\n # one line\n psi[:, i] = np.sum(alpha*np.exp(-1j*eigvals*t)*psi_n, axis=1)\n\nplt.figure(figsize=[3.5, 2.5])\nplt.imshow(np.real(psi), extent=[0, nSteps*dt, x[0], x[-1]], aspect=\"auto\")\nplt.title(r\"Re $\\Psi(x,t)$\")\nplt.xlabel(r\"Time $t/(2mL^2/\\hbar)$\")\nplt.ylabel(r\"Position $x/L$\")\nplt.colorbar()\nplt.tight_layout()\nplt.savefig(\"report/figs/box_psi0_real.pdf\", bbox_inches=\"tight\")\n\nplt.figure(figsize=[3.5, 2.5])\nplt.imshow(np.imag(psi), extent=[0, nSteps*dt, x[0], x[-1]], aspect=\"auto\", zorder=0)\nplt.title(r\"Im $\\Psi(x,t)$\")\nplt.xlabel(r\"Time $t/(2mL^2/\\hbar)$\")\nplt.ylabel(r\"Position $x/L$\")\nplt.colorbar()\nplt.tight_layout()\nplt.gca().set_rasterization_zorder(0.5)\nplt.savefig(\"report/figs/box_psi0_imag.pdf\", bbox_inches=\"tight\")\n\nplt.figure(figsize=[3.5, 2.5])\nplt.imshow(np.real(psi.conj()*psi), extent=[0, nSteps*dt, x[0], x[-1]], aspect=\"auto\")\nplt.title(r\"$|\\Psi(x,t)|^2$\")\nplt.xlabel(r\"Time $t/(2mL^2/\\hbar)$\")\nplt.ylabel(r\"Position $x/L$\")\nplt.colorbar()\nplt.tight_layout()\nplt.savefig(\"report/figs/box_psi0_prob.pdf\", bbox_inches=\"tight\")\n\nplt.show()\n","sub_path":"Assignment 02/task2_10.py","file_name":"task2_10.py","file_ext":"py","file_size_in_byte":3152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"425419870","text":"'''\r\nCurrency used: 1, 2, 5, 10 kr coins\r\nReference for valid coins:\r\nhttps://www.riksbank.se/en-gb/payments--cash/notes--coins/coins/valid-coins/\r\n'''\r\n\r\nimport sys\r\n\r\ndef get_change(cost, amount_paid):\r\n '''\r\n Returns the minimum number of coins to make change.\r\n '''\r\n change = amount_paid - cost\r\n coin_counter = 0\r\n if change >= 10:\r\n coin_counter += change // 10\r\n change = change % 10\r\n\r\n if change >= 5 and change < 10:\r\n coin_counter += change // 5\r\n change = change % 5\r\n\r\n if change >= 2 and change < 5:\r\n coin_counter += change // 2\r\n change = change % 2\r\n\r\n if change >= 1 and change < 2:\r\n coin_counter += change // 1\r\n return coin_counter\r\n\r\nif __name__ == '__main__':\r\n if len(sys.argv) != 3:\r\n print('Usage: python change0.py ')\r\n elif sys.argv[1].isdigit() == False or sys.argv[2].isdigit() == False:\r\n print('Decimal is not allowed.')\r\n else:\r\n print(get_change(int(sys.argv[1]), int(sys.argv[2])))","sub_path":"change0.py","file_name":"change0.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"226991822","text":"\"\"\"\nExample using gRPC API to create a simple EMANE 80211 network.\n\"\"\"\n\nimport logging\n\nfrom core.api.grpc import client\nfrom core.api.grpc.core_pb2 import Node, NodeType, Position, SessionState\nfrom core.emane.ieee80211abg import EmaneIeee80211abgModel\n\n\ndef log_event(event):\n logging.info(\"event: %s\", event)\n\n\ndef main():\n # helper to create interface addresses\n interface_helper = client.InterfaceHelper(ip4_prefix=\"10.83.0.0/24\")\n\n # create grpc client and start connection context, which auto closes connection\n core = client.CoreGrpcClient()\n with core.context_connect():\n # create session\n response = core.create_session()\n logging.info(\"created session: %s\", response)\n\n # handle events session may broadcast\n session_id = response.session_id\n core.events(session_id, log_event)\n\n # change session state to configuration so that nodes get started when added\n response = core.set_session_state(session_id, SessionState.CONFIGURATION)\n logging.info(\"set session state: %s\", response)\n\n # create emane node\n position = Position(x=200, y=200)\n emane = Node(type=NodeType.EMANE, position=position)\n response = core.add_node(session_id, emane)\n logging.info(\"created emane: %s\", response)\n emane_id = response.node_id\n\n # an emane model must be configured for use, by the emane node\n core.set_emane_model_config(session_id, emane_id, EmaneIeee80211abgModel.name)\n\n # create node one\n position = Position(x=100, y=100)\n node1 = Node(type=NodeType.DEFAULT, position=position)\n response = core.add_node(session_id, node1)\n logging.info(\"created node: %s\", response)\n node1_id = response.node_id\n\n # create node two\n position = Position(x=300, y=100)\n node2 = Node(type=NodeType.DEFAULT, position=position)\n response = core.add_node(session_id, node2)\n logging.info(\"created node: %s\", response)\n node2_id = response.node_id\n\n # links nodes to switch\n interface1 = interface_helper.create_iface(node1_id, 0)\n response = core.add_link(session_id, node1_id, emane_id, interface1)\n logging.info(\"created link: %s\", response)\n interface1 = interface_helper.create_iface(node2_id, 0)\n response = core.add_link(session_id, node2_id, emane_id, interface1)\n logging.info(\"created link: %s\", response)\n\n # change session state\n response = core.set_session_state(session_id, SessionState.INSTANTIATION)\n logging.info(\"set session state: %s\", response)\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.DEBUG)\n main()\n","sub_path":"daemon/examples/grpc/emane80211.py","file_name":"emane80211.py","file_ext":"py","file_size_in_byte":2718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"634033066","text":"from game.gameutil import card_show, choose, game_init\r\nimport itertools\r\nimport operator\r\nfrom functools import reduce\r\n\r\n\r\n############################################\r\n# 游戏类 #\r\n############################################ \r\nclass Game(object):\r\n\r\n def __init__(self, models):\r\n # 初始化一副扑克牌类\r\n self.cards = Cards()\r\n\r\n # play相关参数\r\n self.end = False\r\n self.last_move_type = self.last_move = \"start\"\r\n self.playround = 1\r\n self.i = 0\r\n self.yaobuqis = []\r\n\r\n # choose模型\r\n self.models = models\r\n\r\n # 发牌\r\n def game_start(self):\r\n\r\n # 初始化players\r\n self.players = []\r\n self.players.append(Player(1, self.models[0]))\r\n self.players.append(Player(2, self.models[1]))\r\n self.players.append(Player(3, self.models[2]))\r\n\r\n # 初始化扑克牌记录类\r\n self.playrecords = PlayRecords()\r\n\r\n # 发牌\r\n game_init(self.players, self.playrecords, self.cards)\r\n\r\n # 返回扑克牌记录类\r\n def get_record(self):\r\n web_show = WebShow(self.playrecords)\r\n # return jsonpickle.encode(web_show, unpicklable=False)\r\n return web_show\r\n\r\n # 返回下次出牌列表\r\n def get_next_moves(self):\r\n next_move_types, next_moves = self.players[self.i].get_moves(self.last_move_type, self.last_move,\r\n self.playrecords)\r\n return next_move_types, next_moves\r\n\r\n # 游戏进行\r\n def get_next_move(self, action):\r\n while (self.i <= 2):\r\n if self.i != 0:\r\n self.get_next_moves()\r\n self.last_move_type, self.last_move, self.end, self.yaobuqi = self.players[self.i].play(self.last_move_type,\r\n self.last_move,\r\n self.playrecords,\r\n action)\r\n if self.yaobuqi:\r\n self.yaobuqis.append(self.i)\r\n else:\r\n self.yaobuqis = []\r\n # 都要不起\r\n if len(self.yaobuqis) == 2:\r\n self.yaobuqis = []\r\n self.last_move_type = self.last_move = \"start\"\r\n if self.end:\r\n self.playrecords.winner = self.i + 1\r\n break\r\n self.i = self.i + 1\r\n # 一轮结束\r\n self.playround = self.playround + 1\r\n self.i = 0\r\n return self.playrecords.winner, self.end\r\n\r\n\r\n############################################\r\n# 扑克牌相关类 #\r\n############################################\r\nclass Cards(object):\r\n \"\"\"\r\n 一副扑克牌类,54张排,abcd四种花色,小王14-a,大王15-a\r\n \"\"\"\r\n\r\n def __init__(self):\r\n # 初始化扑克牌类型\r\n self.cards_type = ['1-a-12', '1-b-12', '1-c-12', '1-d-12',\r\n '2-a-13', '2-b-13', '2-c-13', '2-d-13',\r\n '3-a-1', '3-b-1', '3-c-1', '3-d-1',\r\n '4-a-2', '4-b-2', '4-c-2', '4-d-2',\r\n '5-a-3', '5-b-3', '5-c-3', '5-d-3',\r\n '6-a-4', '6-b-4', '6-c-4', '6-d-4',\r\n '7-a-5', '7-b-5', '7-c-5', '7-d-5',\r\n '8-a-6', '8-b-6', '8-c-6', '8-d-6',\r\n '9-a-7', '9-b-7', '9-c-7', '9-d-7',\r\n '10-a-8', '10-b-8', '10-c-8', '10-d-8',\r\n '11-a-9', '11-b-9', '11-c-9', '11-d-9',\r\n '12-a-10', '12-b-10', '12-c-10', '12-d-10',\r\n '13-a-11', '13-b-11', '13-c-11', '13-d-11',\r\n '14-a-14', '15-a-15']\r\n # 初始化扑克牌类\r\n self.cards = self.get_cards()\r\n\r\n # 初始化扑克牌类\r\n def get_cards(self):\r\n cards = []\r\n for card_type in self.cards_type:\r\n cards.append(Card(card_type))\r\n # 打乱顺序\r\n # np.random.shuffle(cards)\r\n return cards\r\n\r\n\r\nclass Card(object):\r\n \"\"\"\r\n 扑克牌类\r\n \"\"\"\r\n\r\n def __init__(self, card_type):\r\n self.card_type = card_type\r\n # 名称\r\n self.name = self.card_type.split('-')[0]\r\n # 花色\r\n self.color = self.card_type.split('-')[1]\r\n # 大小\r\n self.rank = int(self.card_type.split('-')[2])\r\n\r\n # 判断大小\r\n def bigger_than(self, card_instance):\r\n if (self.rank > card_instance.rank):\r\n return True\r\n else:\r\n return False\r\n\r\n def __str__(self):\r\n return self.name\r\n\r\n\r\nclass PlayRecords(object):\r\n \"\"\"\r\n 扑克牌记录类\r\n \"\"\"\r\n\r\n def __init__(self):\r\n # 当前手牌\r\n self.cards_left1 = []\r\n self.cards_left2 = []\r\n self.cards_left3 = []\r\n\r\n # 可能出牌选择\r\n self.next_moves1 = []\r\n self.next_moves2 = []\r\n self.next_moves3 = []\r\n\r\n # 出牌记录\r\n self.next_move1 = []\r\n self.next_move2 = []\r\n self.next_move3 = []\r\n\r\n # 出牌记录\r\n self.records = []\r\n\r\n # 胜利者\r\n # winner=0,1,2,3 0表示未结束,1,2,3表示winner\r\n self.winner = 0\r\n\r\n # 出牌者\r\n self.player = 1\r\n\r\n # 展示\r\n def show(self, info):\r\n print(info)\r\n card_show(self.cards_left1, \"player 1\", 1)\r\n card_show(self.cards_left2, \"player 2\", 1)\r\n card_show(self.cards_left3, \"player 3\", 1)\r\n card_show(self.records, \"record\", 3)\r\n\r\n\r\n############################################\r\n# 出牌相关类 #\r\n############################################\r\nclass Moves(object):\r\n \"\"\"\r\n 定义出牌类型\r\n \"\"\"\r\n\r\n def __init__(self):\r\n # 单类型牌\r\n self.dan = []\r\n self.dui = []\r\n self.san = []\r\n self.bomb = []\r\n # 顺子\r\n self.dan_shun = []\r\n self.shuang_shun = []\r\n self.san_shun = []\r\n\r\n # 带牌\r\n self.san_dai_yi = []\r\n self.san_dai_er = []\r\n self.si_dai_yi = []\r\n self.si_dai_er = []\r\n # self.san_shun_dai = []\r\n\r\n # 所有的出牌类型 方便输出以及修改\r\n self.moves_types = ['dan', 'dui', 'san', 'san_dai_yi', 'san_dai_er', 'si_dai_yi', 'si_dai_er','bomb',\r\n 'dan_shun', 'shuang_shun', 'san_shun']\r\n self.all_type = [self.dan, self.dui, self.san, self.san_dai_yi, self.san_dai_er, self.si_dai_yi, self.si_dai_er,self.bomb,\r\n self.dan_shun, self.shuang_shun, self.san_shun]\r\n # 按牌名将牌整理成字典形式{'1':[Card,Card]}\r\n self.card_dict = {}\r\n # 王牌信息\r\n self.king = []\r\n\r\n # 下次出牌\r\n self.next_moves = []\r\n # 下次出牌类型\r\n self.next_moves_type = []\r\n\r\n # 获取全部出牌列表\r\n def get_total_moves(self, cards_left):\r\n\r\n # 统计牌数量/顺序/王牌信息\r\n for i in cards_left:\r\n # 王牌信息\r\n if i.rank in [14, 15]:\r\n self.king.append(i)\r\n # 数量\r\n tmp = self.card_dict.get(i.name, [])\r\n if len(tmp) == 0:\r\n self.card_dict[i.name] = [i]\r\n else:\r\n self.card_dict[i.name].append(i)\r\n\r\n # 王炸\r\n if len(self.king) == 2:\r\n self.bomb.append(self.king)\r\n\r\n # 出单,出对,出三,炸弹(考虑拆开)\r\n for k, v in self.card_dict.items():\r\n if len(v) == 1:\r\n self.dan.append(v)\r\n elif len(v) == 2:\r\n self.dui.append(v)\r\n self.dan.append(v[:1])\r\n elif len(v) == 3:\r\n self.san.append(v)\r\n self.dui.append(v[:2])\r\n self.dan.append(v[:1])\r\n elif len(v) == 4:\r\n self.bomb.append(v)\r\n self.san.append(v[:3])\r\n self.dui.append(v[:2])\r\n self.dan.append(v[:1])\r\n\r\n # 三带一,三带二\r\n for san in self.san:\r\n self._append_dai(self.san_dai_yi, san, self.dan, 1)\r\n self._append_dai(self.san_dai_er, san, self.dui, 1)\r\n\r\n # 四带一,四带二\r\n for si in self.bomb:\r\n if si[0].name != ('14' or '15'):\r\n self._append_dai(self.si_dai_yi, si, self.dan, 2)\r\n self._append_dai(self.si_dai_er, si, self.dui, 2)\r\n\r\n # 添加单顺子\r\n self._append_shunzi(self.dan, self.dan_shun, 5)\r\n # 添加双顺子\r\n self._append_shunzi(self.dui, self.shuang_shun, 3)\r\n # 添加三顺子\r\n self._append_shunzi(self.san, self.san_shun, 2)\r\n\r\n # # 三顺带\r\n # for san_shun in self.san_shun:\r\n # self._append_dai(self.san_shun_dai, san_shun, self.dan, int(len(san_shun) / 3)) # 三顺带一\r\n # self._append_dai(self.san_shun_dai, san_shun, self.dui, int(len(san_shun) / 3)) # 三顺带二\r\n\r\n def _append_dai(self, to_append, shun, dai_list, dai_num):\r\n '''\r\n 给三带一 三带二 三顺带添加带牌\r\n :param to_append:要添加的带牌list e.g. self.san_dai_yi self.san_shun_dai\r\n :param shun:用作合成的顺子 e.g. self.san_shun\r\n :param dai_list:用作合成的带牌 e.g. self.dan\r\n :param dai_num:带牌数目 e.g. 四带二就写 2\r\n :return:\r\n '''\r\n for dai in itertools.combinations(dai_list, dai_num):\r\n dai = reduce(operator.add, dai)\r\n can_append = True\r\n for t in dai:\r\n if t in shun:\r\n can_append = False\r\n break\r\n if can_append:\r\n result = shun + dai\r\n if len(result) <= 20:\r\n to_append.append(result)\r\n\r\n def _append_shunzi(self, to_append, shun_list, min_len):\r\n '''\r\n\r\n :param to_append:单类型牌列表 e.g. self.dan\r\n :param shun_list:t要生成的顺子列表 e.g. self.san_shun\r\n :param min_len:顺子成立的最小长度 单顺写5 3顺写2\r\n :return:\r\n '''\r\n # 获取最长顺子\r\n result = []\r\n max_len = []\r\n for i in to_append:\r\n if i[0].name != ('13' or '14' or '15'):\r\n if len(max_len) == 0:\r\n max_len.append(i)\r\n elif max_len[-1][0].rank == i[0].rank - 1:\r\n max_len.append(i)\r\n else:\r\n if len(max_len) >= min_len:\r\n result.append(max_len)\r\n\r\n max_len = [i]\r\n # 最后一轮\r\n if len(max_len) >= min_len:\r\n result.append(max_len)\r\n # 拆顺子\r\n shunzi_sub = []\r\n for i in result:\r\n len_total = len(i)\r\n n = len_total - min_len\r\n # 遍历所有可能顺子长度\r\n while (n > 0):\r\n len_sub = len_total - n\r\n j = 0\r\n while (len_sub + j <= len(i)):\r\n # 遍历该长度所有组合\r\n shunzi_sub.append(i[j:len_sub + j])\r\n j = j + 1\r\n n = n - 1\r\n\r\n result.extend(shunzi_sub)\r\n # 保持格式一致 将[[[Card]]]转换为[[Card]]\r\n for t in result:\r\n temp = []\r\n for j in t:\r\n if len(j) <= 20:#检测是否超过20张\r\n temp.extend(j)\r\n if len(temp) != 0:\r\n shun_list.append(temp)\r\n\r\n def _compare_other_move(self, last_move_type, last_move):\r\n '''\r\n 单 对 三 三带一 三带二 四带一 四带二的比较方法\r\n :param last_move_type:\r\n :param last_move:\r\n :return:\r\n '''\r\n for move in eval(f'self.{last_move_type}'):\r\n # 比last大\r\n if move[0].bigger_than(last_move[0]):\r\n self.next_moves.append(move)\r\n self.next_moves_type.append(last_move_type)\r\n\r\n def _compare_shunzi_move(self, last_move_type, last_move):\r\n '''\r\n 比较单顺,双顺,三顺,以及三顺带 的大小\r\n :param last_move_type:\r\n :param last_move:\r\n :return:\r\n '''\r\n for move in eval(f'self.{last_move_type}'):\r\n # 相同长度\r\n if len(move) == len(last_move):\r\n # 比last大\r\n if move[0].bigger_than(last_move[0]):\r\n self.next_moves.append(move)\r\n self.next_moves_type.append(last_move_type)\r\n\r\n # 获取下次出牌列表\r\n def get_next_moves(self, last_move_type, last_move):\r\n # 没有last,全加上,除了bomb最后加\r\n if last_move_type == \"start\":\r\n\r\n for index,move_type in enumerate(self.all_type):\r\n for move in move_type:\r\n self.next_moves.append(move)\r\n self.next_moves_type.append(self.moves_types[index])\r\n\r\n # 出顺子 及三顺带\r\n elif last_move_type in self.moves_types[-3:]:\r\n self._compare_shunzi_move(last_move_type, last_move)\r\n # 出 单 对 三 三带一 三带二 四带一 四带二\r\n elif last_move_type in self.moves_types[:-4]:\r\n self._compare_other_move(last_move_type, last_move)\r\n else:\r\n print('last move wrong')\r\n\r\n # 除了bomb,都可以出炸\r\n if last_move_type != \"bomb\":\r\n for move in self.bomb:\r\n self.next_moves.append(move)\r\n self.next_moves_type.append(\"bomb\")\r\n\r\n return self.next_moves_type, self.next_moves\r\n\r\n # 展示\r\n def show(self, info):\r\n print(info)\r\n for index, type in enumerate(self.all_type):\r\n card_show(type, self.moves_types[index], 2)\r\n\r\n\r\n############################################\r\n# 玩家相关类 #\r\n############################################ \r\nclass Player(object):\r\n \"\"\"\r\n player类\r\n \"\"\"\r\n\r\n def __init__(self, player_id, model):\r\n '''\r\n\r\n :param player_id:玩家id\r\n :param model:模型\r\n '''\r\n self.player_id = player_id\r\n self.cards_left = []\r\n # 出牌模式\r\n self.model = model\r\n\r\n # 展示\r\n def show(self, info):\r\n self.total_moves.show(info)\r\n card_show(self.next_move, \"next_move\", 1)\r\n # card_show(self.cards_left, \"card_left\", 1)\r\n\r\n # 根据next_move同步cards_left\r\n def record_move(self, playrecords):\r\n # 记录出牌者\r\n playrecords.player = self.player_id\r\n # playrecords中records记录[id,next_move]\r\n if self.next_move_type in [\"yaobuqi\", \"buyao\"]:\r\n self.next_move = self.next_move_type\r\n playrecords.records.append([self.player_id, self.next_move_type])\r\n else:\r\n playrecords.records.append([self.player_id, self.next_move])\r\n for i in self.next_move:\r\n self.cards_left.remove(i)\r\n # 同步playrecords\r\n if self.player_id == 1:\r\n playrecords.cards_left1 = self.cards_left\r\n playrecords.next_moves1.append(self.next_moves)\r\n playrecords.next_move1.append(self.next_move)\r\n elif self.player_id == 2:\r\n playrecords.cards_left2 = self.cards_left\r\n playrecords.next_moves2.append(self.next_moves)\r\n playrecords.next_move2.append(self.next_move)\r\n elif self.player_id == 3:\r\n playrecords.cards_left3 = self.cards_left\r\n playrecords.next_moves3.append(self.next_moves)\r\n playrecords.next_move3.append(self.next_move)\r\n # 是否牌局结束\r\n end = False\r\n if len(self.cards_left) == 0:\r\n end = True\r\n return end\r\n\r\n # 选牌\r\n def get_moves(self, last_move_type, last_move, playrecords):\r\n # 所有出牌可选列表\r\n self.total_moves = Moves()\r\n # 获取全部出牌列表\r\n self.total_moves.get_total_moves(self.cards_left)\r\n # 获取下次出牌列表\r\n self.next_move_types, self.next_moves = self.total_moves.get_next_moves(last_move_type, last_move)\r\n # 返回下次出牌列表\r\n return self.next_move_types, self.next_moves\r\n\r\n # 出牌\r\n def play(self, last_move_type, last_move, playrecords, action):\r\n # 在next_moves中选择出牌方法\r\n self.next_move_type, self.next_move = choose(self.next_move_types, self.next_moves, last_move_type, self.model,\r\n action)\r\n # 记录\r\n end = self.record_move(playrecords)\r\n # 展示\r\n # self.show(\"Player \" + str(self.player_id))\r\n # 要不起&不要\r\n yaobuqi = False\r\n if self.next_move_type in [\"yaobuqi\", \"buyao\"]:\r\n yaobuqi = True\r\n self.next_move_type = last_move_type\r\n self.next_move = last_move\r\n\r\n return self.next_move_type, self.next_move, end, yaobuqi\r\n\r\n\r\n############################################\r\n# 网页展示类 #\r\n############################################\r\nclass WebShow(object):\r\n \"\"\"\r\n 网页展示类\r\n \"\"\"\r\n\r\n def __init__(self, playrecords):\r\n\r\n # 胜利者\r\n self.winner = playrecords.winner\r\n\r\n # 剩余手牌\r\n self.cards_left1 = []\r\n for i in playrecords.cards_left1:\r\n self.cards_left1.append(i.name + i.color)\r\n self.cards_left2 = []\r\n for i in playrecords.cards_left2:\r\n self.cards_left2.append(i.name + i.color)\r\n self.cards_left3 = []\r\n for i in playrecords.cards_left3:\r\n self.cards_left3.append(i.name + i.color)\r\n\r\n # 可能出牌\r\n self.next_moves1 = []\r\n if len(playrecords.next_moves1) != 0:\r\n next_moves = playrecords.next_moves1[-1]\r\n for move in next_moves:\r\n cards = []\r\n for card in move:\r\n cards.append(card.name + card.color)\r\n self.next_moves1.append(cards)\r\n self.next_moves2 = []\r\n if len(playrecords.next_moves2) != 0:\r\n next_moves = playrecords.next_moves2[-1]\r\n for move in next_moves:\r\n cards = []\r\n for card in move:\r\n cards.append(card.name + card.color)\r\n self.next_moves2.append(cards)\r\n self.next_moves3 = []\r\n if len(playrecords.next_moves3) != 0:\r\n next_moves = playrecords.next_moves3[-1]\r\n for move in next_moves:\r\n cards = []\r\n for card in move:\r\n cards.append(card.name + card.color)\r\n self.next_moves3.append(cards)\r\n\r\n # 出牌\r\n self.next_move1 = []\r\n if len(playrecords.next_move1) != 0:\r\n next_move = playrecords.next_move1[-1]\r\n if next_move in [\"yaobuqi\", \"buyao\"]:\r\n self.next_move1.append(next_move)\r\n else:\r\n for card in next_move:\r\n self.next_move1.append(card.name + card.color)\r\n self.next_move2 = []\r\n if len(playrecords.next_move2) != 0:\r\n next_move = playrecords.next_move2[-1]\r\n if next_move in [\"yaobuqi\", \"buyao\"]:\r\n self.next_move2.append(next_move)\r\n else:\r\n for card in next_move:\r\n self.next_move2.append(card.name + card.color)\r\n self.next_move3 = []\r\n if len(playrecords.next_move3) != 0:\r\n next_move = playrecords.next_move3[-1]\r\n if next_move in [\"yaobuqi\", \"buyao\"]:\r\n self.next_move3.append(next_move)\r\n else:\r\n for card in next_move:\r\n self.next_move3.append(card.name + card.color)\r\n\r\n # 记录\r\n self.records = []\r\n for i in playrecords.records:\r\n tmp = []\r\n tmp.append(i[0])\r\n tmp_name = []\r\n # 处理要不起\r\n try:\r\n for j in i[1]:\r\n tmp_name.append(j.name + j.color)\r\n tmp.append(tmp_name)\r\n except:\r\n tmp.append(i[1])\r\n self.records.append(tmp)\r\n","sub_path":"161403104徐开义/game/myclass.py","file_name":"myclass.py","file_ext":"py","file_size_in_byte":20794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"209305120","text":"a = []\nmax = 4\n\ndef enqueue(x):\n\n if(len(a) <= max):\n a.append(x)\n else:\n print(\"overflow\")\n\ndef dequeue():\n if(len(a) > 0):\n print(a[0])\n del a[0]\n elif(len(a) == 0):\n print(\"underflow\")\n\nflag = True\nwhile(flag):\n b = input(\"e(enqueue) or d(dequeue), or x\\n\")\n if(b == 'e'):\n print(\"choose number\")\n number = int(input())\n enqueue(number)\n print(a)\n elif(b == 'd'):\n dequeue()\n print(a)\n elif(b == 'x'):\n flag = False","sub_path":"queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"428403551","text":"# encoding:utf-8\r\nfrom tornado.testing import *\r\nfrom testfixtures import Comparison\r\n\r\nfrom utiles.config import Configuracion, datos_config\r\nfrom tests.datos_pruebas import cargar_datos_config_demo\r\n\r\nclass testConfig(AsyncTestCase):\r\n\r\n def setUp(self):\r\n super(testConfig, self).setUp()\r\n self.init_config = datos_config()\r\n self.init_config.DesdeJson(cargar_datos_config_demo())\r\n\r\n def test_leer_config(self):\r\n config = Configuracion()\r\n self.assertEqual(Comparison(config.config) == self.init_config, True)\r\n\r\n def test_guardar_config(self):\r\n config = Configuracion()\r\n config.config = datos_config()\r\n self.assertEqual(Comparison(config.config) == self.init_config, False)\r\n self.assertEqual(config.guardar_config(cargar_datos_config_demo()), True)\r\n self.assertEqual(Comparison(config.config) == self.init_config, True)\r\n\r\n datos_config_demo_erroneos = cargar_datos_config_demo()\r\n datos_config_demo_erroneos.pop('Usuario_admin')\r\n self.assertEqual(config.guardar_config(datos_config_demo_erroneos), False)","sub_path":"utiles/test/test_config.py","file_name":"test_config.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"534874146","text":"import numpy as np\nimport matplotlib.pylab as plt\n\n\n\ndef sigmoid (x):\n return 1 / (1 + np.exp(-x))\n\n\n\n\n\na = np.arange(-5.0, 5.0, 0.1)\nprint (\"a =\", a)\nb = sigmoid(a)\nprint (\"b =\", b)\n\n\nplt.plot(a, b)\nplt.xlim(-6.0, 6.0)\nplt.ylim(-0.1, 1.1) \nplt.show()\n\n\n\n\n\n","sub_path":"hello-sigmoid.py","file_name":"hello-sigmoid.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"261550400","text":"import sys\nimport threading\nimport time\nimport numpy\n\nclass SleepSort:\n\n def __init__(self, values, speed=1):\n self.values = values\n self.converted_values = []\n\n for x in self.values:\n if type(x) is str:\n self.converted_values.append(self.convert_to_ascii(x))\n else:\n self.converted_values.append(x)\n self.max = max(self.converted_values) * speed\n self.result = []\n\n def convert_to_ascii(self, x):\n ascii_values = []\n for letter in str(x):\n ascii_values.append(str(ord(letter)))\n\n return int(''.join(ascii_values))\n\n def sleep(self, x):\n time.sleep(x / self.max)\n self.result.append(self.values[self.converted_values.index(x)])\n\n def sort(self):\n threads = []\n for x in self.converted_values:\n thread = threading.Thread(target=self.sleep, args=(x,))\n thread.start()\n threads.append(thread)\n\n for thread in threads:\n thread.join()\n\n return self.result\n\n\nif __name__ == '__main__':\n random_array = numpy.random.randint(low=1, high=100, size=20)\n correct = sorted(random_array)\n result = SleepSort(random_array).sort()\n if result == correct:\n print(\"The array was sleep sorted succesfully!\")\n else:\n print(\"Dumb program!\")\n print(result)\n","sub_path":"sleepsort.py","file_name":"sleepsort.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"343003592","text":"# -*- coding: utf-8 -*-\n# Copyright 2023 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport dataclasses\nimport json # type: ignore\nimport re\nfrom typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union\nimport warnings\n\nfrom google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming\nfrom google.api_core import exceptions as core_exceptions\nfrom google.api_core import retry as retries\nfrom google.auth import credentials as ga_credentials # type: ignore\nfrom google.auth.transport.grpc import SslCredentials # type: ignore\nfrom google.auth.transport.requests import AuthorizedSession # type: ignore\nfrom google.protobuf import json_format\nimport grpc # type: ignore\nfrom requests import __version__ as requests_version\n\ntry:\n OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]\nexcept AttributeError: # pragma: NO COVER\n OptionalRetry = Union[retries.Retry, object] # type: ignore\n\n\nfrom google.cloud.language_v1beta2.types import language_service\n\nfrom .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO\nfrom .base import LanguageServiceTransport\n\nDEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(\n gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,\n grpc_version=None,\n rest_version=requests_version,\n)\n\n\nclass LanguageServiceRestInterceptor:\n \"\"\"Interceptor for LanguageService.\n\n Interceptors are used to manipulate requests, request metadata, and responses\n in arbitrary ways.\n Example use cases include:\n * Logging\n * Verifying requests according to service or custom semantics\n * Stripping extraneous information from responses\n\n These use cases and more can be enabled by injecting an\n instance of a custom subclass when constructing the LanguageServiceRestTransport.\n\n .. code-block:: python\n class MyCustomLanguageServiceInterceptor(LanguageServiceRestInterceptor):\n def pre_analyze_entities(self, request, metadata):\n logging.log(f\"Received request: {request}\")\n return request, metadata\n\n def post_analyze_entities(self, response):\n logging.log(f\"Received response: {response}\")\n return response\n\n def pre_analyze_entity_sentiment(self, request, metadata):\n logging.log(f\"Received request: {request}\")\n return request, metadata\n\n def post_analyze_entity_sentiment(self, response):\n logging.log(f\"Received response: {response}\")\n return response\n\n def pre_analyze_sentiment(self, request, metadata):\n logging.log(f\"Received request: {request}\")\n return request, metadata\n\n def post_analyze_sentiment(self, response):\n logging.log(f\"Received response: {response}\")\n return response\n\n def pre_analyze_syntax(self, request, metadata):\n logging.log(f\"Received request: {request}\")\n return request, metadata\n\n def post_analyze_syntax(self, response):\n logging.log(f\"Received response: {response}\")\n return response\n\n def pre_annotate_text(self, request, metadata):\n logging.log(f\"Received request: {request}\")\n return request, metadata\n\n def post_annotate_text(self, response):\n logging.log(f\"Received response: {response}\")\n return response\n\n def pre_classify_text(self, request, metadata):\n logging.log(f\"Received request: {request}\")\n return request, metadata\n\n def post_classify_text(self, response):\n logging.log(f\"Received response: {response}\")\n return response\n\n def pre_moderate_text(self, request, metadata):\n logging.log(f\"Received request: {request}\")\n return request, metadata\n\n def post_moderate_text(self, response):\n logging.log(f\"Received response: {response}\")\n return response\n\n transport = LanguageServiceRestTransport(interceptor=MyCustomLanguageServiceInterceptor())\n client = LanguageServiceClient(transport=transport)\n\n\n \"\"\"\n\n def pre_analyze_entities(\n self,\n request: language_service.AnalyzeEntitiesRequest,\n metadata: Sequence[Tuple[str, str]],\n ) -> Tuple[language_service.AnalyzeEntitiesRequest, Sequence[Tuple[str, str]]]:\n \"\"\"Pre-rpc interceptor for analyze_entities\n\n Override in a subclass to manipulate the request or metadata\n before they are sent to the LanguageService server.\n \"\"\"\n return request, metadata\n\n def post_analyze_entities(\n self, response: language_service.AnalyzeEntitiesResponse\n ) -> language_service.AnalyzeEntitiesResponse:\n \"\"\"Post-rpc interceptor for analyze_entities\n\n Override in a subclass to manipulate the response\n after it is returned by the LanguageService server but before\n it is returned to user code.\n \"\"\"\n return response\n\n def pre_analyze_entity_sentiment(\n self,\n request: language_service.AnalyzeEntitySentimentRequest,\n metadata: Sequence[Tuple[str, str]],\n ) -> Tuple[\n language_service.AnalyzeEntitySentimentRequest, Sequence[Tuple[str, str]]\n ]:\n \"\"\"Pre-rpc interceptor for analyze_entity_sentiment\n\n Override in a subclass to manipulate the request or metadata\n before they are sent to the LanguageService server.\n \"\"\"\n return request, metadata\n\n def post_analyze_entity_sentiment(\n self, response: language_service.AnalyzeEntitySentimentResponse\n ) -> language_service.AnalyzeEntitySentimentResponse:\n \"\"\"Post-rpc interceptor for analyze_entity_sentiment\n\n Override in a subclass to manipulate the response\n after it is returned by the LanguageService server but before\n it is returned to user code.\n \"\"\"\n return response\n\n def pre_analyze_sentiment(\n self,\n request: language_service.AnalyzeSentimentRequest,\n metadata: Sequence[Tuple[str, str]],\n ) -> Tuple[language_service.AnalyzeSentimentRequest, Sequence[Tuple[str, str]]]:\n \"\"\"Pre-rpc interceptor for analyze_sentiment\n\n Override in a subclass to manipulate the request or metadata\n before they are sent to the LanguageService server.\n \"\"\"\n return request, metadata\n\n def post_analyze_sentiment(\n self, response: language_service.AnalyzeSentimentResponse\n ) -> language_service.AnalyzeSentimentResponse:\n \"\"\"Post-rpc interceptor for analyze_sentiment\n\n Override in a subclass to manipulate the response\n after it is returned by the LanguageService server but before\n it is returned to user code.\n \"\"\"\n return response\n\n def pre_analyze_syntax(\n self,\n request: language_service.AnalyzeSyntaxRequest,\n metadata: Sequence[Tuple[str, str]],\n ) -> Tuple[language_service.AnalyzeSyntaxRequest, Sequence[Tuple[str, str]]]:\n \"\"\"Pre-rpc interceptor for analyze_syntax\n\n Override in a subclass to manipulate the request or metadata\n before they are sent to the LanguageService server.\n \"\"\"\n return request, metadata\n\n def post_analyze_syntax(\n self, response: language_service.AnalyzeSyntaxResponse\n ) -> language_service.AnalyzeSyntaxResponse:\n \"\"\"Post-rpc interceptor for analyze_syntax\n\n Override in a subclass to manipulate the response\n after it is returned by the LanguageService server but before\n it is returned to user code.\n \"\"\"\n return response\n\n def pre_annotate_text(\n self,\n request: language_service.AnnotateTextRequest,\n metadata: Sequence[Tuple[str, str]],\n ) -> Tuple[language_service.AnnotateTextRequest, Sequence[Tuple[str, str]]]:\n \"\"\"Pre-rpc interceptor for annotate_text\n\n Override in a subclass to manipulate the request or metadata\n before they are sent to the LanguageService server.\n \"\"\"\n return request, metadata\n\n def post_annotate_text(\n self, response: language_service.AnnotateTextResponse\n ) -> language_service.AnnotateTextResponse:\n \"\"\"Post-rpc interceptor for annotate_text\n\n Override in a subclass to manipulate the response\n after it is returned by the LanguageService server but before\n it is returned to user code.\n \"\"\"\n return response\n\n def pre_classify_text(\n self,\n request: language_service.ClassifyTextRequest,\n metadata: Sequence[Tuple[str, str]],\n ) -> Tuple[language_service.ClassifyTextRequest, Sequence[Tuple[str, str]]]:\n \"\"\"Pre-rpc interceptor for classify_text\n\n Override in a subclass to manipulate the request or metadata\n before they are sent to the LanguageService server.\n \"\"\"\n return request, metadata\n\n def post_classify_text(\n self, response: language_service.ClassifyTextResponse\n ) -> language_service.ClassifyTextResponse:\n \"\"\"Post-rpc interceptor for classify_text\n\n Override in a subclass to manipulate the response\n after it is returned by the LanguageService server but before\n it is returned to user code.\n \"\"\"\n return response\n\n def pre_moderate_text(\n self,\n request: language_service.ModerateTextRequest,\n metadata: Sequence[Tuple[str, str]],\n ) -> Tuple[language_service.ModerateTextRequest, Sequence[Tuple[str, str]]]:\n \"\"\"Pre-rpc interceptor for moderate_text\n\n Override in a subclass to manipulate the request or metadata\n before they are sent to the LanguageService server.\n \"\"\"\n return request, metadata\n\n def post_moderate_text(\n self, response: language_service.ModerateTextResponse\n ) -> language_service.ModerateTextResponse:\n \"\"\"Post-rpc interceptor for moderate_text\n\n Override in a subclass to manipulate the response\n after it is returned by the LanguageService server but before\n it is returned to user code.\n \"\"\"\n return response\n\n\n@dataclasses.dataclass\nclass LanguageServiceRestStub:\n _session: AuthorizedSession\n _host: str\n _interceptor: LanguageServiceRestInterceptor\n\n\nclass LanguageServiceRestTransport(LanguageServiceTransport):\n \"\"\"REST backend transport for LanguageService.\n\n Provides text analysis operations such as sentiment analysis\n and entity recognition.\n\n This class defines the same methods as the primary client, so the\n primary client can load the underlying transport implementation\n and call it.\n\n It sends JSON representations of protocol buffers over HTTP/1.1\n\n \"\"\"\n\n def __init__(\n self,\n *,\n host: str = \"language.googleapis.com\",\n credentials: Optional[ga_credentials.Credentials] = None,\n credentials_file: Optional[str] = None,\n scopes: Optional[Sequence[str]] = None,\n client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,\n quota_project_id: Optional[str] = None,\n client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,\n always_use_jwt_access: Optional[bool] = False,\n url_scheme: str = \"https\",\n interceptor: Optional[LanguageServiceRestInterceptor] = None,\n api_audience: Optional[str] = None,\n ) -> None:\n \"\"\"Instantiate the transport.\n\n Args:\n host (Optional[str]):\n The hostname to connect to.\n credentials (Optional[google.auth.credentials.Credentials]): The\n authorization credentials to attach to requests. These\n credentials identify the application to the service; if none\n are specified, the client will attempt to ascertain the\n credentials from the environment.\n\n credentials_file (Optional[str]): A file with credentials that can\n be loaded with :func:`google.auth.load_credentials_from_file`.\n This argument is ignored if ``channel`` is provided.\n scopes (Optional(Sequence[str])): A list of scopes. This argument is\n ignored if ``channel`` is provided.\n client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client\n certificate to configure mutual TLS HTTP channel. It is ignored\n if ``channel`` is provided.\n quota_project_id (Optional[str]): An optional project to use for billing\n and quota.\n client_info (google.api_core.gapic_v1.client_info.ClientInfo):\n The client info used to send a user-agent string along with\n API requests. If ``None``, then default info will be used.\n Generally, you only need to set this if you are developing\n your own client library.\n always_use_jwt_access (Optional[bool]): Whether self signed JWT should\n be used for service account credentials.\n url_scheme: the protocol scheme for the API endpoint. Normally\n \"https\", but for testing or local servers,\n \"http\" can be specified.\n \"\"\"\n # Run the base constructor\n # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.\n # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the\n # credentials object\n maybe_url_match = re.match(\"^(?Phttp(?:s)?://)?(?P.*)$\", host)\n if maybe_url_match is None:\n raise ValueError(\n f\"Unexpected hostname structure: {host}\"\n ) # pragma: NO COVER\n\n url_match_items = maybe_url_match.groupdict()\n\n host = f\"{url_scheme}://{host}\" if not url_match_items[\"scheme\"] else host\n\n super().__init__(\n host=host,\n credentials=credentials,\n client_info=client_info,\n always_use_jwt_access=always_use_jwt_access,\n api_audience=api_audience,\n )\n self._session = AuthorizedSession(\n self._credentials, default_host=self.DEFAULT_HOST\n )\n if client_cert_source_for_mtls:\n self._session.configure_mtls_channel(client_cert_source_for_mtls)\n self._interceptor = interceptor or LanguageServiceRestInterceptor()\n self._prep_wrapped_messages(client_info)\n\n class _AnalyzeEntities(LanguageServiceRestStub):\n def __hash__(self):\n return hash(\"AnalyzeEntities\")\n\n __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}\n\n @classmethod\n def _get_unset_required_fields(cls, message_dict):\n return {\n k: v\n for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()\n if k not in message_dict\n }\n\n def __call__(\n self,\n request: language_service.AnalyzeEntitiesRequest,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Optional[float] = None,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> language_service.AnalyzeEntitiesResponse:\n r\"\"\"Call the analyze entities method over HTTP.\n\n Args:\n request (~.language_service.AnalyzeEntitiesRequest):\n The request object. The entity analysis request message.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n ~.language_service.AnalyzeEntitiesResponse:\n The entity analysis response message.\n \"\"\"\n\n http_options: List[Dict[str, str]] = [\n {\n \"method\": \"post\",\n \"uri\": \"/v1beta2/documents:analyzeEntities\",\n \"body\": \"*\",\n },\n ]\n request, metadata = self._interceptor.pre_analyze_entities(\n request, metadata\n )\n pb_request = language_service.AnalyzeEntitiesRequest.pb(request)\n transcoded_request = path_template.transcode(http_options, pb_request)\n\n # Jsonify the request body\n\n body = json_format.MessageToJson(\n transcoded_request[\"body\"],\n including_default_value_fields=False,\n use_integers_for_enums=True,\n )\n uri = transcoded_request[\"uri\"]\n method = transcoded_request[\"method\"]\n\n # Jsonify the query params\n query_params = json.loads(\n json_format.MessageToJson(\n transcoded_request[\"query_params\"],\n including_default_value_fields=False,\n use_integers_for_enums=True,\n )\n )\n query_params.update(self._get_unset_required_fields(query_params))\n\n query_params[\"$alt\"] = \"json;enum-encoding=int\"\n\n # Send the request\n headers = dict(metadata)\n headers[\"Content-Type\"] = \"application/json\"\n response = getattr(self._session, method)(\n \"{host}{uri}\".format(host=self._host, uri=uri),\n timeout=timeout,\n headers=headers,\n params=rest_helpers.flatten_query_params(query_params, strict=True),\n data=body,\n )\n\n # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception\n # subclass.\n if response.status_code >= 400:\n raise core_exceptions.from_http_response(response)\n\n # Return the response\n resp = language_service.AnalyzeEntitiesResponse()\n pb_resp = language_service.AnalyzeEntitiesResponse.pb(resp)\n\n json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)\n resp = self._interceptor.post_analyze_entities(resp)\n return resp\n\n class _AnalyzeEntitySentiment(LanguageServiceRestStub):\n def __hash__(self):\n return hash(\"AnalyzeEntitySentiment\")\n\n __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}\n\n @classmethod\n def _get_unset_required_fields(cls, message_dict):\n return {\n k: v\n for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()\n if k not in message_dict\n }\n\n def __call__(\n self,\n request: language_service.AnalyzeEntitySentimentRequest,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Optional[float] = None,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> language_service.AnalyzeEntitySentimentResponse:\n r\"\"\"Call the analyze entity sentiment method over HTTP.\n\n Args:\n request (~.language_service.AnalyzeEntitySentimentRequest):\n The request object. The entity-level sentiment analysis\n request message.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n ~.language_service.AnalyzeEntitySentimentResponse:\n The entity-level sentiment analysis\n response message.\n\n \"\"\"\n\n http_options: List[Dict[str, str]] = [\n {\n \"method\": \"post\",\n \"uri\": \"/v1beta2/documents:analyzeEntitySentiment\",\n \"body\": \"*\",\n },\n ]\n request, metadata = self._interceptor.pre_analyze_entity_sentiment(\n request, metadata\n )\n pb_request = language_service.AnalyzeEntitySentimentRequest.pb(request)\n transcoded_request = path_template.transcode(http_options, pb_request)\n\n # Jsonify the request body\n\n body = json_format.MessageToJson(\n transcoded_request[\"body\"],\n including_default_value_fields=False,\n use_integers_for_enums=True,\n )\n uri = transcoded_request[\"uri\"]\n method = transcoded_request[\"method\"]\n\n # Jsonify the query params\n query_params = json.loads(\n json_format.MessageToJson(\n transcoded_request[\"query_params\"],\n including_default_value_fields=False,\n use_integers_for_enums=True,\n )\n )\n query_params.update(self._get_unset_required_fields(query_params))\n\n query_params[\"$alt\"] = \"json;enum-encoding=int\"\n\n # Send the request\n headers = dict(metadata)\n headers[\"Content-Type\"] = \"application/json\"\n response = getattr(self._session, method)(\n \"{host}{uri}\".format(host=self._host, uri=uri),\n timeout=timeout,\n headers=headers,\n params=rest_helpers.flatten_query_params(query_params, strict=True),\n data=body,\n )\n\n # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception\n # subclass.\n if response.status_code >= 400:\n raise core_exceptions.from_http_response(response)\n\n # Return the response\n resp = language_service.AnalyzeEntitySentimentResponse()\n pb_resp = language_service.AnalyzeEntitySentimentResponse.pb(resp)\n\n json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)\n resp = self._interceptor.post_analyze_entity_sentiment(resp)\n return resp\n\n class _AnalyzeSentiment(LanguageServiceRestStub):\n def __hash__(self):\n return hash(\"AnalyzeSentiment\")\n\n __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}\n\n @classmethod\n def _get_unset_required_fields(cls, message_dict):\n return {\n k: v\n for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()\n if k not in message_dict\n }\n\n def __call__(\n self,\n request: language_service.AnalyzeSentimentRequest,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Optional[float] = None,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> language_service.AnalyzeSentimentResponse:\n r\"\"\"Call the analyze sentiment method over HTTP.\n\n Args:\n request (~.language_service.AnalyzeSentimentRequest):\n The request object. The sentiment analysis request\n message.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n ~.language_service.AnalyzeSentimentResponse:\n The sentiment analysis response\n message.\n\n \"\"\"\n\n http_options: List[Dict[str, str]] = [\n {\n \"method\": \"post\",\n \"uri\": \"/v1beta2/documents:analyzeSentiment\",\n \"body\": \"*\",\n },\n ]\n request, metadata = self._interceptor.pre_analyze_sentiment(\n request, metadata\n )\n pb_request = language_service.AnalyzeSentimentRequest.pb(request)\n transcoded_request = path_template.transcode(http_options, pb_request)\n\n # Jsonify the request body\n\n body = json_format.MessageToJson(\n transcoded_request[\"body\"],\n including_default_value_fields=False,\n use_integers_for_enums=True,\n )\n uri = transcoded_request[\"uri\"]\n method = transcoded_request[\"method\"]\n\n # Jsonify the query params\n query_params = json.loads(\n json_format.MessageToJson(\n transcoded_request[\"query_params\"],\n including_default_value_fields=False,\n use_integers_for_enums=True,\n )\n )\n query_params.update(self._get_unset_required_fields(query_params))\n\n query_params[\"$alt\"] = \"json;enum-encoding=int\"\n\n # Send the request\n headers = dict(metadata)\n headers[\"Content-Type\"] = \"application/json\"\n response = getattr(self._session, method)(\n \"{host}{uri}\".format(host=self._host, uri=uri),\n timeout=timeout,\n headers=headers,\n params=rest_helpers.flatten_query_params(query_params, strict=True),\n data=body,\n )\n\n # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception\n # subclass.\n if response.status_code >= 400:\n raise core_exceptions.from_http_response(response)\n\n # Return the response\n resp = language_service.AnalyzeSentimentResponse()\n pb_resp = language_service.AnalyzeSentimentResponse.pb(resp)\n\n json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)\n resp = self._interceptor.post_analyze_sentiment(resp)\n return resp\n\n class _AnalyzeSyntax(LanguageServiceRestStub):\n def __hash__(self):\n return hash(\"AnalyzeSyntax\")\n\n __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}\n\n @classmethod\n def _get_unset_required_fields(cls, message_dict):\n return {\n k: v\n for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()\n if k not in message_dict\n }\n\n def __call__(\n self,\n request: language_service.AnalyzeSyntaxRequest,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Optional[float] = None,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> language_service.AnalyzeSyntaxResponse:\n r\"\"\"Call the analyze syntax method over HTTP.\n\n Args:\n request (~.language_service.AnalyzeSyntaxRequest):\n The request object. The syntax analysis request message.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n ~.language_service.AnalyzeSyntaxResponse:\n The syntax analysis response message.\n \"\"\"\n\n http_options: List[Dict[str, str]] = [\n {\n \"method\": \"post\",\n \"uri\": \"/v1beta2/documents:analyzeSyntax\",\n \"body\": \"*\",\n },\n ]\n request, metadata = self._interceptor.pre_analyze_syntax(request, metadata)\n pb_request = language_service.AnalyzeSyntaxRequest.pb(request)\n transcoded_request = path_template.transcode(http_options, pb_request)\n\n # Jsonify the request body\n\n body = json_format.MessageToJson(\n transcoded_request[\"body\"],\n including_default_value_fields=False,\n use_integers_for_enums=True,\n )\n uri = transcoded_request[\"uri\"]\n method = transcoded_request[\"method\"]\n\n # Jsonify the query params\n query_params = json.loads(\n json_format.MessageToJson(\n transcoded_request[\"query_params\"],\n including_default_value_fields=False,\n use_integers_for_enums=True,\n )\n )\n query_params.update(self._get_unset_required_fields(query_params))\n\n query_params[\"$alt\"] = \"json;enum-encoding=int\"\n\n # Send the request\n headers = dict(metadata)\n headers[\"Content-Type\"] = \"application/json\"\n response = getattr(self._session, method)(\n \"{host}{uri}\".format(host=self._host, uri=uri),\n timeout=timeout,\n headers=headers,\n params=rest_helpers.flatten_query_params(query_params, strict=True),\n data=body,\n )\n\n # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception\n # subclass.\n if response.status_code >= 400:\n raise core_exceptions.from_http_response(response)\n\n # Return the response\n resp = language_service.AnalyzeSyntaxResponse()\n pb_resp = language_service.AnalyzeSyntaxResponse.pb(resp)\n\n json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)\n resp = self._interceptor.post_analyze_syntax(resp)\n return resp\n\n class _AnnotateText(LanguageServiceRestStub):\n def __hash__(self):\n return hash(\"AnnotateText\")\n\n __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}\n\n @classmethod\n def _get_unset_required_fields(cls, message_dict):\n return {\n k: v\n for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()\n if k not in message_dict\n }\n\n def __call__(\n self,\n request: language_service.AnnotateTextRequest,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Optional[float] = None,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> language_service.AnnotateTextResponse:\n r\"\"\"Call the annotate text method over HTTP.\n\n Args:\n request (~.language_service.AnnotateTextRequest):\n The request object. The request message for the text\n annotation API, which can perform\n multiple analysis types (sentiment,\n entities, and syntax) in one call.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n ~.language_service.AnnotateTextResponse:\n The text annotations response\n message.\n\n \"\"\"\n\n http_options: List[Dict[str, str]] = [\n {\n \"method\": \"post\",\n \"uri\": \"/v1beta2/documents:annotateText\",\n \"body\": \"*\",\n },\n ]\n request, metadata = self._interceptor.pre_annotate_text(request, metadata)\n pb_request = language_service.AnnotateTextRequest.pb(request)\n transcoded_request = path_template.transcode(http_options, pb_request)\n\n # Jsonify the request body\n\n body = json_format.MessageToJson(\n transcoded_request[\"body\"],\n including_default_value_fields=False,\n use_integers_for_enums=True,\n )\n uri = transcoded_request[\"uri\"]\n method = transcoded_request[\"method\"]\n\n # Jsonify the query params\n query_params = json.loads(\n json_format.MessageToJson(\n transcoded_request[\"query_params\"],\n including_default_value_fields=False,\n use_integers_for_enums=True,\n )\n )\n query_params.update(self._get_unset_required_fields(query_params))\n\n query_params[\"$alt\"] = \"json;enum-encoding=int\"\n\n # Send the request\n headers = dict(metadata)\n headers[\"Content-Type\"] = \"application/json\"\n response = getattr(self._session, method)(\n \"{host}{uri}\".format(host=self._host, uri=uri),\n timeout=timeout,\n headers=headers,\n params=rest_helpers.flatten_query_params(query_params, strict=True),\n data=body,\n )\n\n # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception\n # subclass.\n if response.status_code >= 400:\n raise core_exceptions.from_http_response(response)\n\n # Return the response\n resp = language_service.AnnotateTextResponse()\n pb_resp = language_service.AnnotateTextResponse.pb(resp)\n\n json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)\n resp = self._interceptor.post_annotate_text(resp)\n return resp\n\n class _ClassifyText(LanguageServiceRestStub):\n def __hash__(self):\n return hash(\"ClassifyText\")\n\n __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}\n\n @classmethod\n def _get_unset_required_fields(cls, message_dict):\n return {\n k: v\n for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()\n if k not in message_dict\n }\n\n def __call__(\n self,\n request: language_service.ClassifyTextRequest,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Optional[float] = None,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> language_service.ClassifyTextResponse:\n r\"\"\"Call the classify text method over HTTP.\n\n Args:\n request (~.language_service.ClassifyTextRequest):\n The request object. The document classification request\n message.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n ~.language_service.ClassifyTextResponse:\n The document classification response\n message.\n\n \"\"\"\n\n http_options: List[Dict[str, str]] = [\n {\n \"method\": \"post\",\n \"uri\": \"/v1beta2/documents:classifyText\",\n \"body\": \"*\",\n },\n ]\n request, metadata = self._interceptor.pre_classify_text(request, metadata)\n pb_request = language_service.ClassifyTextRequest.pb(request)\n transcoded_request = path_template.transcode(http_options, pb_request)\n\n # Jsonify the request body\n\n body = json_format.MessageToJson(\n transcoded_request[\"body\"],\n including_default_value_fields=False,\n use_integers_for_enums=True,\n )\n uri = transcoded_request[\"uri\"]\n method = transcoded_request[\"method\"]\n\n # Jsonify the query params\n query_params = json.loads(\n json_format.MessageToJson(\n transcoded_request[\"query_params\"],\n including_default_value_fields=False,\n use_integers_for_enums=True,\n )\n )\n query_params.update(self._get_unset_required_fields(query_params))\n\n query_params[\"$alt\"] = \"json;enum-encoding=int\"\n\n # Send the request\n headers = dict(metadata)\n headers[\"Content-Type\"] = \"application/json\"\n response = getattr(self._session, method)(\n \"{host}{uri}\".format(host=self._host, uri=uri),\n timeout=timeout,\n headers=headers,\n params=rest_helpers.flatten_query_params(query_params, strict=True),\n data=body,\n )\n\n # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception\n # subclass.\n if response.status_code >= 400:\n raise core_exceptions.from_http_response(response)\n\n # Return the response\n resp = language_service.ClassifyTextResponse()\n pb_resp = language_service.ClassifyTextResponse.pb(resp)\n\n json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)\n resp = self._interceptor.post_classify_text(resp)\n return resp\n\n class _ModerateText(LanguageServiceRestStub):\n def __hash__(self):\n return hash(\"ModerateText\")\n\n __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}\n\n @classmethod\n def _get_unset_required_fields(cls, message_dict):\n return {\n k: v\n for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()\n if k not in message_dict\n }\n\n def __call__(\n self,\n request: language_service.ModerateTextRequest,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Optional[float] = None,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> language_service.ModerateTextResponse:\n r\"\"\"Call the moderate text method over HTTP.\n\n Args:\n request (~.language_service.ModerateTextRequest):\n The request object. The document moderation request\n message.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n ~.language_service.ModerateTextResponse:\n The document moderation response\n message.\n\n \"\"\"\n\n http_options: List[Dict[str, str]] = [\n {\n \"method\": \"post\",\n \"uri\": \"/v1beta2/documents:moderateText\",\n \"body\": \"*\",\n },\n ]\n request, metadata = self._interceptor.pre_moderate_text(request, metadata)\n pb_request = language_service.ModerateTextRequest.pb(request)\n transcoded_request = path_template.transcode(http_options, pb_request)\n\n # Jsonify the request body\n\n body = json_format.MessageToJson(\n transcoded_request[\"body\"],\n including_default_value_fields=False,\n use_integers_for_enums=True,\n )\n uri = transcoded_request[\"uri\"]\n method = transcoded_request[\"method\"]\n\n # Jsonify the query params\n query_params = json.loads(\n json_format.MessageToJson(\n transcoded_request[\"query_params\"],\n including_default_value_fields=False,\n use_integers_for_enums=True,\n )\n )\n query_params.update(self._get_unset_required_fields(query_params))\n\n query_params[\"$alt\"] = \"json;enum-encoding=int\"\n\n # Send the request\n headers = dict(metadata)\n headers[\"Content-Type\"] = \"application/json\"\n response = getattr(self._session, method)(\n \"{host}{uri}\".format(host=self._host, uri=uri),\n timeout=timeout,\n headers=headers,\n params=rest_helpers.flatten_query_params(query_params, strict=True),\n data=body,\n )\n\n # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception\n # subclass.\n if response.status_code >= 400:\n raise core_exceptions.from_http_response(response)\n\n # Return the response\n resp = language_service.ModerateTextResponse()\n pb_resp = language_service.ModerateTextResponse.pb(resp)\n\n json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)\n resp = self._interceptor.post_moderate_text(resp)\n return resp\n\n @property\n def analyze_entities(\n self,\n ) -> Callable[\n [language_service.AnalyzeEntitiesRequest],\n language_service.AnalyzeEntitiesResponse,\n ]:\n # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.\n # In C++ this would require a dynamic_cast\n return self._AnalyzeEntities(self._session, self._host, self._interceptor) # type: ignore\n\n @property\n def analyze_entity_sentiment(\n self,\n ) -> Callable[\n [language_service.AnalyzeEntitySentimentRequest],\n language_service.AnalyzeEntitySentimentResponse,\n ]:\n # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.\n # In C++ this would require a dynamic_cast\n return self._AnalyzeEntitySentiment(self._session, self._host, self._interceptor) # type: ignore\n\n @property\n def analyze_sentiment(\n self,\n ) -> Callable[\n [language_service.AnalyzeSentimentRequest],\n language_service.AnalyzeSentimentResponse,\n ]:\n # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.\n # In C++ this would require a dynamic_cast\n return self._AnalyzeSentiment(self._session, self._host, self._interceptor) # type: ignore\n\n @property\n def analyze_syntax(\n self,\n ) -> Callable[\n [language_service.AnalyzeSyntaxRequest], language_service.AnalyzeSyntaxResponse\n ]:\n # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.\n # In C++ this would require a dynamic_cast\n return self._AnalyzeSyntax(self._session, self._host, self._interceptor) # type: ignore\n\n @property\n def annotate_text(\n self,\n ) -> Callable[\n [language_service.AnnotateTextRequest], language_service.AnnotateTextResponse\n ]:\n # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.\n # In C++ this would require a dynamic_cast\n return self._AnnotateText(self._session, self._host, self._interceptor) # type: ignore\n\n @property\n def classify_text(\n self,\n ) -> Callable[\n [language_service.ClassifyTextRequest], language_service.ClassifyTextResponse\n ]:\n # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.\n # In C++ this would require a dynamic_cast\n return self._ClassifyText(self._session, self._host, self._interceptor) # type: ignore\n\n @property\n def moderate_text(\n self,\n ) -> Callable[\n [language_service.ModerateTextRequest], language_service.ModerateTextResponse\n ]:\n # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.\n # In C++ this would require a dynamic_cast\n return self._ModerateText(self._session, self._host, self._interceptor) # type: ignore\n\n @property\n def kind(self) -> str:\n return \"rest\"\n\n def close(self):\n self._session.close()\n\n\n__all__ = (\"LanguageServiceRestTransport\",)\n","sub_path":"packages/google-cloud-language/google/cloud/language_v1beta2/services/language_service/transports/rest.py","file_name":"rest.py","file_ext":"py","file_size_in_byte":45200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"399980955","text":"import argparse\nimport time\nfrom enum import Enum\n\nimport numpy as np\n\nfrom udacidrone import Drone\nfrom udacidrone.connection import MavlinkConnection, WebSocketConnection # noqa: F401\nfrom udacidrone.messaging import MsgID\n\n\nclass States(Enum):\n MANUAL = 0\n ARMING = 1\n TAKEOFF = 2\n WAYPOINT = 3\n LANDING = 4\n DISARMING = 5\n\ndef enum(*args):\n enums = dict(zip(args, range(len(args))))\n return type('Enum', (), enums)\n\nLocations = enum('LATITUDE','LONGITUDE','ALTITUDE')\n\nTARGET_LATITUDE = 10.0\nTARGET_LONGITUDE = 10.0\nTARGET_ALTITUDE = 3.0\n\nclass BackyardFlyer(Drone):\n\n def __init__(self, connection):\n super().__init__(connection)\n self.target_position = np.array([0.0, 0.0, 0.0])\n self.all_waypoints = []\n # Not using Multi thread yet \n #self.in_mission = True\n self.check_state = {}\n\n # initial state\n self.flight_state = States.MANUAL\n\n # TODO: Register all your callbacks here\n self.register_callback(MsgID.LOCAL_POSITION, self.local_position_callback)\n self.register_callback(MsgID.LOCAL_VELOCITY, self.velocity_callback)\n self.register_callback(MsgID.STATE, self.state_callback)\n\n def check_position(self):\n ret = False\n # Check TARGET_ALTITUDE, TARGET_LATITUDE, TARGET_LONGITUDE\n latitude_difference = abs(self.target_position[Locations.LATITUDE]) - abs(self.local_position[Locations.LATITUDE])\n longitude_difference = abs(self.target_position[Locations.LONGITUDE]) - abs(self.local_position[Locations.LONGITUDE])\n altitude_difference = abs(self.target_position[Locations.ALTITUDE]) - abs(self.local_position[Locations.ALTITUDE])\n print(\"LA: [%2.2f]/[%2.2f]=[%2.2f] LO: [%2.2f]/[%2.2f]=[%2.2f] AL: [%2.2f]/[%2.2f]=[%2.2f]\" % (\n abs(self.local_position[Locations.LATITUDE]),self.target_position[Locations.LATITUDE],abs(latitude_difference),\n abs(self.local_position[Locations.LONGITUDE]),self.target_position[Locations.LONGITUDE],abs(longitude_difference),\n abs(self.local_position[Locations.ALTITUDE]),self.target_position[Locations.ALTITUDE],abs(altitude_difference)))\n \n if abs(altitude_difference) < 0.05 and self.flight_state == States.TAKEOFF:\n ret = True\n elif abs(altitude_difference) < 0.05 and self.flight_state == States.LANDING:\n ret = True\n elif abs(altitude_difference) < 0.05 and self.flight_state == States.WAYPOINT:\n if abs(latitude_difference) < 0.2 and abs(longitude_difference) < 0.2:\n ret = True\n return ret\n\n def local_position_callback(self):\n \"\"\"\n This triggers when `MsgID.LOCAL_POSITION` is received and self.local_position contains new data\n \"\"\"\n if self.flight_state == States.TAKEOFF:\n if self.check_position():\n self.all_waypoints = self.calculate_box()\n self.waypoint_transition()\n elif self.flight_state == States.WAYPOINT:\n if self.check_position():\n if len(self.all_waypoints) > 0:\n self.waypoint_transition()\n else:\n self.target_position[Locations.ALTITUDE] = 0\n self.landing_transition()\n elif self.flight_state == States.LANDING:\n if self.check_position():\n self.disarming_transition()\n\n def velocity_callback(self):\n \"\"\"\n TODO: Implement this method\n\n This triggers when `MsgID.LOCAL_VELOCITY` is received and self.local_velocity contains new data\n \"\"\"\n # Have seen the solution for this to implement, however did not find the need to populate this\n # It would be nice if we could regulate the speed so to have smooth transition and accuracy\n # self.cmd_velocity(-x,-y,-z,0.0)\n pass\n\n def state_callback(self):\n \"\"\"\n This triggers when `MsgID.STATE` is received and self.armed and self.guided contain new data\n \"\"\"\n # Respective transition should end in Respective State\n # ##################################################### \n # MANUAL -> arming_transition -> ARMING\n # ARMING -> takeoff_transition -> TAKEOFF\n # TAKEOFF -> waypoint_transition -> WAYPOINT\n # WAYPOINT -> landing_transition -> LANDING\n # LANDING -> disarming_transition -> DISARMING\n # DISARMING -> manual_transition -> MANUAL\n # ##################################################### \n\n if self.flight_state == States.MANUAL:\n self.arming_transition()\n elif self.flight_state == States.ARMING:\n if self.armed:\n self.takeoff_transition()\n elif self.flight_state == States.DISARMING:\n if ~self.armed:\n self.manual_transition()\n\n def calculate_box(self):\n \"\"\"\n 1. Return waypoints to fly a box\n \"\"\"\n waypoints = [[TARGET_LATITUDE, 0.0, TARGET_ALTITUDE], \n [TARGET_LATITUDE, TARGET_LONGITUDE, TARGET_ALTITUDE], \n [0.0, TARGET_LONGITUDE, TARGET_ALTITUDE], \n [0.0, 0.0, TARGET_ALTITUDE]]\n return waypoints\n\n def arming_transition(self):\n \"\"\"\n 1. Take control of the drone\n 2. Pass an arming command\n 3. Set the home location to current position\n 4. Transition to the ARMING state\n \"\"\"\n print(\"arming transition\")\n self.take_control()\n self.arm()\n self.set_home_position(self.global_position[Locations.LATITUDE],\n self.global_position[Locations.LONGITUDE],self.global_position[Locations.ALTITUDE])\n self.flight_state = States.ARMING \n print(\"START \",self.global_position[Locations.LATITUDE],\n self.global_position[Locations.LONGITUDE],self.global_position[Locations.ALTITUDE]) \n\n def takeoff_transition(self):\n \"\"\"\n 1. Set target_position altitude to 3.0m\n 2. Command a takeoff to 3.0m\n 3. Transition to the TAKEOFF state\n \"\"\"\n print(\"takeoff transition\")\n self.target_position[Locations.ALTITUDE] = TARGET_ALTITUDE\n self.takeoff(self.target_position[Locations.ALTITUDE])\n self.flight_state = States.TAKEOFF \n\n def waypoint_transition(self):\n \"\"\"\n 1. Command the next waypoint position\n 2. Transition to WAYPOINT state\n \"\"\"\n print(\"waypoint transition\")\n self.target_position = self.all_waypoints.pop(0)\n print('target position', self.target_position)\n self.cmd_position(self.target_position[Locations.LATITUDE], \n self.target_position[Locations.LONGITUDE], self.target_position[Locations.ALTITUDE], 0.0)\n self.flight_state = States.WAYPOINT\n\n def landing_transition(self):\n \"\"\"\n 1. Command the drone to land\n 2. Transition to the LANDING state\n \"\"\"\n print(\"landing transition\")\n self.land()\n self.flight_state = States.LANDING\n\n def disarming_transition(self):\n \"\"\"\n 1. Command the drone to disarm\n 2. Transition to the DISARMING state\n \"\"\"\n print(\"disarm transition\")\n self.disarm()\n self.flight_state = States.DISARMING \n\n def manual_transition(self):\n \"\"\"This method is provided\n 1. Release control of the drone\n 2. Stop the connection (and telemetry log)\n 3. End the mission\n 4. Transition to the MANUAL state\n \"\"\"\n print(\"manual transition\")\n self.release_control()\n self.stop()\n # Not using Multi thread yet\n # self.in_mission = False\n self.flight_state = States.MANUAL\n print(\"END \",self.global_position[Locations.LATITUDE],\n self.global_position[Locations.LONGITUDE],self.global_position[Locations.ALTITUDE]) \n\n def start(self):\n \"\"\"This method is provided\n 1. Open a log file\n 2. Start the drone connection\n 3. Close the log file\n \"\"\"\n print(\"Creating log file\")\n self.start_log(\"Logs\", \"NavLog.txt\")\n print(\"starting connection\")\n self.connection.start()\n print(\"Closing log file\")\n self.stop_log()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--port', type=int, default=5760, help='Port number')\n parser.add_argument('--host', type=str, default='127.0.0.1', help=\"host address, i.e. '127.0.0.1'\")\n args = parser.parse_args()\n\n conn = MavlinkConnection('tcp:{0}:{1}'.format(args.host, args.port), threaded=False, PX4=False)\n #conn = WebSocketConnection('ws://{0}:{1}'.format(args.host, args.port))\n drone = BackyardFlyer(conn)\n time.sleep(2)\ndrone.start()\n","sub_path":"backyard_flyer.py","file_name":"backyard_flyer.py","file_ext":"py","file_size_in_byte":8884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"181987136","text":"#!/usr/bin/env python\n#\n# spyne - Copyright (C) Spyne contributors.\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301\n#\n\n\nimport logging\nlogging.basicConfig(level=logging.DEBUG)\n\nimport unittest\n\nfrom spyne.util import six\nfrom spyne.util.six import StringIO\nfrom spyne.util.six.moves.http_cookies import SimpleCookie\n\nfrom datetime import datetime\nfrom wsgiref.validate import validator as wsgiref_validator\n\nfrom spyne.model.complex import Array\n\nfrom spyne.server.wsgi import _parse_qs\nfrom spyne.application import Application\nfrom spyne.error import ValidationError\nfrom spyne.const.http import HTTP_200\nfrom spyne.decorator import rpc\nfrom spyne.decorator import srpc\nfrom spyne.model.binary import ByteArray\nfrom spyne.model.primitive import DateTime\nfrom spyne.model.primitive import Uuid\nfrom spyne.model.primitive import String\nfrom spyne.model.primitive import Integer\nfrom spyne.model.primitive import Integer8\nfrom spyne.model.complex import ComplexModel\nfrom spyne.protocol.http import HttpRpc\nfrom spyne.protocol.http import HttpPattern\nfrom spyne.service import ServiceBase\nfrom spyne.server.wsgi import WsgiApplication\nfrom spyne.server.wsgi import WsgiMethodContext\nfrom spyne.util.test import call_wsgi_app_kwargs\n\n\n\nclass TestString(unittest.TestCase):\n def setUp(self):\n class SomeService(ServiceBase):\n @srpc(String, _returns=String)\n def echo_string(s):\n return s\n\n app = Application([SomeService], 'tns',\n in_protocol=HttpRpc(validator='soft'),\n out_protocol=HttpRpc(),\n )\n\n self.app = WsgiApplication(app)\n\n def test_without_content_type(self):\n headers = None\n ret = call_wsgi_app_kwargs(self.app, 'echo_string', headers, s=\"string\")\n assert ret == 'string'\n\n def test_without_encoding(self):\n headers = {'CONTENT_TYPE':'text/plain'}\n ret = call_wsgi_app_kwargs(self.app, 'echo_string', headers, s=\"string\")\n assert ret == 'string'\n\n def test_with_encoding(self):\n headers = {'CONTENT_TYPE':'text/plain; charset=utf8'}\n ret = call_wsgi_app_kwargs(self.app, 'echo_string', headers, s=\"string\")\n assert ret == 'string'\n\n\nclass TestSimpleDictDocument(unittest.TestCase):\n def test_own_parse_qs_01(self):\n assert dict(_parse_qs('')) == {}\n def test_own_parse_qs_02(self):\n assert dict(_parse_qs('p')) == {'p': [None]}\n def test_own_parse_qs_03(self):\n assert dict(_parse_qs('p=')) == {'p': ['']}\n def test_own_parse_qs_04(self):\n assert dict(_parse_qs('p=1')) == {'p': ['1']}\n def test_own_parse_qs_05(self):\n assert dict(_parse_qs('p=1&')) == {'p': ['1']}\n def test_own_parse_qs_06(self):\n assert dict(_parse_qs('p=1&q')) == {'p': ['1'], 'q': [None]}\n def test_own_parse_qs_07(self):\n assert dict(_parse_qs('p=1&q=')) == {'p': ['1'], 'q': ['']}\n def test_own_parse_qs_08(self):\n assert dict(_parse_qs('p=1&q=2')) == {'p': ['1'], 'q': ['2']}\n def test_own_parse_qs_09(self):\n assert dict(_parse_qs('p=1&q=2&p')) == {'p': ['1', None], 'q': ['2']}\n def test_own_parse_qs_10(self):\n assert dict(_parse_qs('p=1&q=2&p=')) == {'p': ['1', ''], 'q': ['2']}\n def test_own_parse_qs_11(self):\n assert dict(_parse_qs('p=1&q=2&p=3')) == {'p': ['1', '3'], 'q': ['2']}\n\ndef _test(services, qs, validator='soft', strict_arrays=False):\n app = Application(services, 'tns',\n in_protocol=HttpRpc(validator=validator, strict_arrays=strict_arrays),\n out_protocol=HttpRpc())\n server = WsgiApplication(app)\n\n initial_ctx = WsgiMethodContext(server, {\n 'QUERY_STRING': qs,\n 'PATH_INFO': '/some_call',\n 'REQUEST_METHOD': 'GET',\n 'SERVER_NAME': \"localhost\",\n }, 'some-content-type')\n\n ctx, = server.generate_contexts(initial_ctx)\n\n server.get_in_object(ctx)\n if ctx.in_error is not None:\n raise ctx.in_error\n\n server.get_out_object(ctx)\n if ctx.out_error is not None:\n raise ctx.out_error\n\n server.get_out_string(ctx)\n\n return ctx\n\nclass TestValidation(unittest.TestCase):\n def test_validation_frequency(self):\n class SomeService(ServiceBase):\n @srpc(ByteArray(min_occurs=1), _returns=ByteArray)\n def some_call(p):\n pass\n\n try:\n _test([SomeService], '', validator='soft')\n except ValidationError:\n pass\n else:\n raise Exception(\"must raise ValidationError\")\n\n def _test_validation_frequency_simple_bare(self):\n class SomeService(ServiceBase):\n @srpc(ByteArray(min_occurs=1), _body_style='bare', _returns=ByteArray)\n def some_call(p):\n pass\n\n try:\n _test([SomeService], '', validator='soft')\n except ValidationError:\n pass\n else:\n raise Exception(\"must raise ValidationError\")\n\n def test_validation_frequency_complex_bare_parent(self):\n class C(ComplexModel):\n i=Integer(min_occurs=1)\n s=String\n\n class SomeService(ServiceBase):\n @srpc(C, _body_style='bare')\n def some_call(p):\n pass\n\n # must not complain about missing s\n _test([SomeService], 'i=5', validator='soft')\n\n # must raise validation error for missing i\n try:\n _test([SomeService], 's=a', validator='soft')\n except ValidationError:\n pass\n else:\n raise Exception(\"must raise ValidationError\")\n\n # must raise validation error for missing i\n try:\n _test([SomeService], '', validator='soft')\n except ValidationError:\n pass\n else:\n raise Exception(\"must raise ValidationError\")\n\n def test_validation_frequency_parent(self):\n class C(ComplexModel):\n i=Integer(min_occurs=1)\n s=String\n\n class SomeService(ServiceBase):\n @srpc(C)\n def some_call(p):\n pass\n\n # must not complain about missing s\n _test([SomeService], 'p.i=5', validator='soft')\n try:\n # must raise validation error for missing i\n _test([SomeService], 'p.s=a', validator='soft')\n except ValidationError:\n pass\n else:\n raise Exception(\"must raise ValidationError\")\n\n # must not raise anything for missing p because C has min_occurs=0\n _test([SomeService], '', validator='soft')\n\n def test_validation_array(self):\n class C(ComplexModel):\n i=Integer(min_occurs=1)\n s=String\n\n class SomeService(ServiceBase):\n @srpc(Array(C))\n def some_call(p):\n pass\n\n # must not complain about missing s\n _test([SomeService], 'p[0].i=5', validator='soft')\n try:\n # must raise validation error for missing i\n _test([SomeService], 'p[0].s=a', validator='soft')\n except ValidationError:\n pass\n else:\n raise Exception(\"must raise ValidationError\")\n\n # must not raise anything for missing p because C has min_occurs=0\n _test([SomeService], '', validator='soft')\n\n def test_validation_array_index_jump_error(self):\n class C(ComplexModel):\n i=Integer\n\n class SomeService(ServiceBase):\n @srpc(Array(C), _returns=String)\n def some_call(p):\n return repr(p)\n\n try:\n # must raise validation error for index jump from 0 to 2 even without\n # any validation\n _test([SomeService], 'p[0].i=42&p[2].i=42&', strict_arrays=True)\n except ValidationError:\n pass\n else:\n raise Exception(\"must raise ValidationError\")\n\n def test_validation_array_index_jump_tolerate(self):\n class C(ComplexModel):\n i=Integer\n\n class SomeService(ServiceBase):\n @srpc(Array(C), _returns=String)\n def some_call(p):\n return repr(p)\n\n # must not raise validation error for index jump from 0 to 2 and ignore\n # element with index 1\n ret = _test([SomeService], 'p[0].i=0&p[2].i=2&', strict_arrays=False)\n assert ret.out_object[0] == '[C(i=0), C(i=2)]'\n\n # even if they arrive out-of-order.\n ret = _test([SomeService], 'p[2].i=2&p[0].i=0&', strict_arrays=False)\n assert ret.out_object[0] == '[C(i=0), C(i=2)]'\n\n\n def test_validation_nested_array(self):\n class CC(ComplexModel):\n d = DateTime\n\n class C(ComplexModel):\n i = Integer(min_occurs=1)\n cc = Array(CC)\n\n class SomeService(ServiceBase):\n @srpc(Array(C))\n def some_call(p):\n print(p)\n\n # must not complain about missing s\n _test([SomeService], 'p[0].i=5', validator='soft')\n try:\n # must raise validation error for missing i\n _test([SomeService], 'p[0].cc[0].d=2013-01-01', validator='soft')\n except ValidationError:\n pass\n else:\n raise Exception(\"must raise ValidationError\")\n\n # must not raise anything for missing p because C has min_occurs=0\n _test([SomeService], '', validator='soft')\n\n def test_validation_nullable(self):\n class SomeService(ServiceBase):\n @srpc(ByteArray(nullable=False), _returns=ByteArray)\n def some_call(p):\n pass\n\n try:\n _test([SomeService], 'p', validator='soft')\n except ValidationError:\n pass\n else:\n raise Exception(\"must raise ValidationError\")\n\n def test_validation_string_pattern(self):\n class SomeService(ServiceBase):\n @srpc(Uuid)\n def some_call(p):\n pass\n\n try:\n _test([SomeService], \"p=duduk\", validator='soft')\n except ValidationError:\n pass\n else:\n raise Exception(\"must raise ValidationError\")\n\n def test_validation_integer_range(self):\n class SomeService(ServiceBase):\n @srpc(Integer(ge=0, le=5))\n def some_call(p):\n pass\n\n try:\n _test([SomeService], 'p=10', validator='soft')\n except ValidationError:\n pass\n else:\n raise Exception(\"must raise ValidationError\")\n\n def test_validation_integer_type(self):\n class SomeService(ServiceBase):\n @srpc(Integer8)\n def some_call(p):\n pass\n\n try:\n _test([SomeService], \"p=-129\", validator='soft')\n except ValidationError:\n pass\n else:\n raise Exception(\"must raise ValidationError\")\n\n def test_validation_integer_type_2(self):\n class SomeService(ServiceBase):\n @srpc(Integer8)\n def some_call(p):\n pass\n\n try:\n _test([SomeService], \"p=1.2\", validator='soft')\n except ValidationError:\n pass\n else:\n raise Exception(\"must raise ValidationError\")\n\n\nclass Test(unittest.TestCase):\n def test_multiple_return(self):\n class SomeService(ServiceBase):\n @srpc(_returns=[Integer, String])\n def some_call():\n return 1, 's'\n\n try:\n _test([SomeService], '')\n except TypeError:\n pass\n else:\n raise Exception(\"Must fail with: HttpRpc does not support complex \"\n \"return types.\")\n\n def test_primitive_only(self):\n class SomeComplexModel(ComplexModel):\n i = Integer\n s = String\n\n class SomeService(ServiceBase):\n @srpc(SomeComplexModel, _returns=SomeComplexModel)\n def some_call(scm):\n return SomeComplexModel(i=5, s='5x')\n\n try:\n _test([SomeService], '')\n except TypeError:\n pass\n else:\n raise Exception(\"Must fail with: HttpRpc does not support complex \"\n \"return types.\")\n\n def test_complex(self):\n class CM(ComplexModel):\n _type_info = [\n (\"i\", Integer),\n (\"s\", String),\n ]\n\n class CCM(ComplexModel):\n _type_info = [\n (\"i\", Integer),\n (\"c\", CM),\n (\"s\", String),\n ]\n\n class SomeService(ServiceBase):\n @srpc(CCM, _returns=String)\n def some_call(ccm):\n return repr(CCM(c=ccm.c, i=ccm.i, s=ccm.s))\n\n ctx = _test([SomeService], '&ccm.i=1&ccm.s=s&ccm.c.i=3&ccm.c.s=cs')\n\n assert ctx.out_string[0] == \"CCM(i=1, c=CM(i=3, s='cs'), s='s')\"\n\n def test_multiple(self):\n class SomeService(ServiceBase):\n @srpc(String(max_occurs='unbounded'), _returns=String)\n def some_call(s):\n return '\\n'.join(s)\n\n ctx = _test([SomeService], '&s=1&s=2')\n assert ''.join(ctx.out_string) == '1\\n2'\n\n def test_nested_flatten(self):\n class CM(ComplexModel):\n _type_info = [\n (\"i\", Integer),\n (\"s\", String),\n ]\n\n class CCM(ComplexModel):\n _type_info = [\n (\"i\", Integer),\n (\"c\", CM),\n (\"s\", String),\n ]\n\n class SomeService(ServiceBase):\n @srpc(CCM, _returns=String)\n def some_call(ccm):\n return repr(ccm)\n\n ctx = _test([SomeService], '&ccm.i=1&ccm.s=s&ccm.c.i=3&ccm.c.s=cs')\n\n print(ctx.out_string)\n assert ''.join(ctx.out_string) == \"CCM(i=1, c=CM(i=3, s='cs'), s='s')\"\n\n def test_nested_flatten_with_multiple_values_1(self):\n class CM(ComplexModel):\n _type_info = [\n (\"i\", Integer),\n (\"s\", String),\n ]\n\n class CCM(ComplexModel):\n _type_info = [\n (\"i\", Integer),\n (\"c\", CM),\n (\"s\", String),\n ]\n\n class SomeService(ServiceBase):\n @srpc(CCM.customize(max_occurs=2), _returns=String)\n def some_call(ccm):\n return repr(ccm)\n\n ctx = _test([SomeService], 'ccm[0].i=1&ccm[0].s=s'\n '&ccm[0].c.i=1&ccm[0].c.s=a'\n '&ccm[1].c.i=2&ccm[1].c.s=b')\n\n s = ''.join(ctx.out_string)\n\n assert s == \"[CCM(i=1, c=CM(i=1, s='a'), s='s'), CCM(c=CM(i=2, s='b'))]\"\n\n def test_nested_flatten_with_multiple_values_2(self):\n class CM(ComplexModel):\n _type_info = [\n (\"i\", Integer),\n (\"s\", String),\n ]\n\n class CCM(ComplexModel):\n _type_info = [\n (\"i\", Integer),\n (\"c\", CM.customize(max_occurs=2)),\n (\"s\", String),\n ]\n\n class SomeService(ServiceBase):\n @srpc(CCM, _returns=String)\n def some_call(ccm):\n return repr(ccm)\n\n ctx = _test([SomeService], 'ccm.i=1&ccm.s=s'\n '&ccm.c[0].i=1&ccm.c[0].s=a'\n '&ccm.c[1].i=2&ccm.c[1].s=b')\n\n s = ''.join(list(ctx.out_string))\n assert s == \"CCM(i=1, c=[CM(i=1, s='a'), CM(i=2, s='b')], s='s')\"\n\n def test_nested_flatten_with_complex_array(self):\n class CM(ComplexModel):\n _type_info = [\n (\"i\", Integer),\n (\"s\", String),\n ]\n\n class CCM(ComplexModel):\n _type_info = [\n (\"i\", Integer),\n (\"c\", Array(CM)),\n (\"s\", String),\n ]\n\n class SomeService(ServiceBase):\n @srpc(CCM, _returns=String)\n def some_call(ccm):\n return repr(ccm)\n\n ctx = _test([SomeService], 'ccm.i=1&ccm.s=s'\n '&ccm.c[0].i=1&ccm.c[0].s=a'\n '&ccm.c[1].i=2&ccm.c[1].s=b')\n\n s = ''.join(list(ctx.out_string))\n assert s == \"CCM(i=1, c=[CM(i=1, s='a'), CM(i=2, s='b')], s='s')\"\n\n def test_nested_2_flatten_with_primitive_array(self):\n class CCM(ComplexModel):\n _type_info = [\n (\"i\", Integer),\n (\"c\", Array(String)),\n (\"s\", String),\n ]\n\n class SomeService(ServiceBase):\n @srpc(Array(CCM), _returns=String)\n def some_call(ccm):\n return repr(ccm)\n\n ctx = _test([SomeService], 'ccm[0].i=1&ccm[0].s=s'\n '&ccm[0].c=a'\n '&ccm[0].c=b')\n s = ''.join(list(ctx.out_string))\n assert s == \"[CCM(i=1, c=['a', 'b'], s='s')]\"\n\n def test_nested_flatten_with_primitive_array(self):\n class CCM(ComplexModel):\n _type_info = [\n (\"i\", Integer),\n (\"c\", Array(String)),\n (\"s\", String),\n ]\n\n class SomeService(ServiceBase):\n @srpc(CCM, _returns=String)\n def some_call(ccm):\n return repr(ccm)\n\n ctx = _test([SomeService], 'ccm.i=1&ccm.s=s'\n '&ccm.c=a'\n '&ccm.c=b')\n s = ''.join(list(ctx.out_string))\n assert s == \"CCM(i=1, c=['a', 'b'], s='s')\"\n\n ctx = _test([SomeService], 'ccm.i=1'\n '&ccm.s=s'\n '&ccm.c[1]=b'\n '&ccm.c[0]=a')\n s = ''.join(list(ctx.out_string))\n assert s == \"CCM(i=1, c=['a', 'b'], s='s')\"\n\n ctx = _test([SomeService], 'ccm.i=1'\n '&ccm.s=s'\n '&ccm.c[0]=a'\n '&ccm.c[1]=b')\n s = ''.join(list(ctx.out_string))\n assert s == \"CCM(i=1, c=['a', 'b'], s='s')\"\n\n def test_cookie_parse(self):\n string = 'some_string'\n class RequestHeader(ComplexModel):\n some_field = String\n\n class SomeService(ServiceBase):\n __in_header__ = RequestHeader\n\n @rpc(String)\n def some_call(ctx, s):\n assert ctx.in_header.some_field == string\n\n def start_response(code, headers):\n assert code == HTTP_200\n\n c = SimpleCookie()\n c['some_field'] = string\n\n ''.join(wsgiref_validator(WsgiApplication(Application([SomeService], 'tns',\n in_protocol=HttpRpc(parse_cookie=True), out_protocol=HttpRpc())))({\n 'SCRIPT_NAME': '',\n 'QUERY_STRING': '',\n 'PATH_INFO': '/some_call',\n 'REQUEST_METHOD': 'GET',\n 'SERVER_NAME': 'localhost',\n 'SERVER_PORT': \"9999\",\n 'HTTP_COOKIE': str(c),\n 'wsgi.url_scheme': 'http',\n 'wsgi.version': (1,0),\n 'wsgi.input': StringIO(),\n 'wsgi.errors': StringIO(),\n 'wsgi.multithread': False,\n 'wsgi.multiprocess': False,\n 'wsgi.run_once': True,\n }, start_response))\n\n def test_http_headers(self):\n d = datetime(year=2013, month=1, day=1)\n string = ['hey', 'yo']\n\n class ResponseHeader(ComplexModel):\n _type_info = {\n 'Set-Cookie': String(max_occurs='unbounded'),\n 'Expires': DateTime\n }\n\n class SomeService(ServiceBase):\n __out_header__ = ResponseHeader\n\n @rpc(String)\n def some_call(ctx, s):\n assert s is not None\n ctx.out_header = ResponseHeader(**{'Set-Cookie': string,\n 'Expires': d})\n\n def start_response(code, headers):\n assert len([s for s in string if ('Set-Cookie', s) in headers]) == len(string)\n assert dict(headers)['Expires'] == 'Tue, 01 Jan 2013 00:00:00 GMT'\n\n ret = ''.join(wsgiref_validator(WsgiApplication(Application([SomeService], 'tns',\n in_protocol=HttpRpc(), out_protocol=HttpRpc())))({\n 'SCRIPT_NAME': '',\n 'QUERY_STRING': '&s=foo',\n 'PATH_INFO': '/some_call',\n 'REQUEST_METHOD': 'GET',\n 'SERVER_NAME': 'localhost',\n 'SERVER_PORT': \"9999\",\n 'wsgi.url_scheme': 'http',\n 'wsgi.version': (1,0),\n 'wsgi.input': StringIO(),\n 'wsgi.errors': StringIO(),\n 'wsgi.multithread': False,\n 'wsgi.multiprocess': False,\n 'wsgi.run_once': True,\n }, start_response))\n\n assert ret == ''\n\n\nclass TestHttpPatterns(unittest.TestCase):\n def test_rules(self):\n _int = 5\n _fragment = 'some_fragment'\n\n class SomeService(ServiceBase):\n @srpc(Integer, _returns=Integer, _patterns=[\n HttpPattern('/%s/'% _fragment)])\n def some_call(some_int):\n assert some_int == _int\n\n app = Application([SomeService], 'tns', in_protocol=HttpRpc(), out_protocol=HttpRpc())\n server = WsgiApplication(app)\n\n environ = {\n 'QUERY_STRING': '',\n 'PATH_INFO': '/%s/%d' % (_fragment, _int),\n 'SERVER_PATH':\"/\",\n 'SERVER_NAME': \"localhost\",\n 'wsgi.url_scheme': 'http',\n 'SERVER_PORT': '9000',\n 'REQUEST_METHOD': 'GET',\n }\n\n initial_ctx = WsgiMethodContext(server, environ, 'some-content-type')\n\n ctx, = server.generate_contexts(initial_ctx)\n\n foo = []\n for i in server._http_patterns:\n foo.append(i)\n\n assert len(foo) == 1\n print(foo)\n assert ctx.descriptor is not None\n\n server.get_in_object(ctx)\n assert ctx.in_error is None\n\n server.get_out_object(ctx)\n assert ctx.out_error is None\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"baidu_code/soap_mockserver/spyne/test/protocol/test_http.py","file_name":"test_http.py","file_ext":"py","file_size_in_byte":22944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"13552413","text":"import sys\n\n\ndef halt(error):\n halt = sys.exit(\"Program Halted due to Errors : %s\" % error)\n\nmedium = 0\nR1 = [0] \nR2 = [0]\nR3 = [0]\nR4 = [0]\nR5 = [0]\nR6 = [0]\nR7 = [0]\nR8 = [0]\nA1 = []\nA2 = []\nA3 = [] \nA4 = [] \nA5 = []\nSP = [0] \n\ndef clear():\n global medium\n global R1\n global R2\n global R3\n global R4\n global R5\n global R6\n global R7\n global R8\n R1 = [0] \n R2 = [0]\n R3 = [0]\n R4 = [0]\n R5 = [0]\n R6 = [0]\n R7 = [0]\n R8 = [0]\n medium = 0\n\ndef display():\n global medium\n print(medium)\n\ndef print_register(register):\n print(register[0])\n\ndef register_clear():\n global medium\n medium = 0\n\ndef register_one():\n global medium\n medium = 1\n\ndef register_insert(regs, num):\n #print(regs, num, \"Before\")\n regs[0] = num\n #print(regs, num, \"After\")\n return regs\n\ndef register_load(regs):\n global medium\n medium = regs[0]\n\ndef register_save(regs):\n regs[0] = medium\n\ndef array_insert(arr, num):\n for x in range(num):\n element = input('Enter number: %s for the array: ' % (x + 1))\n arr.append(int(element))\n\ndef target_check(arr, target):\n for index, element in enumerate(arr):\n\n\n\n if element == target:\n print('Number found on index: %s for array %s' % (index, arr))\n return\n print(\"o.o, no target found in %s\" % arr)\n\ndef sum_of_registers(register):\n global medium\n medium += register[0]\n\ndef difference_of_registers(register):\n global medium\n medium -= register[0]\n\ndef product_of_registers(register):\n global medium\n medium *= register[0]\n\ndef sum_of_array(array):\n global medium\n register_clear()\n for index, num in enumerate(array):\n medium = medium + num\n\ndef difference_of_array(array):\n global medium\n medium = array[0]\n if(len(array) > 1):\n for index, num in enumerate(array[1:]):\n medium -= num\n else:\n raise ValueError(\"Array is not big enough for differences...\")\n halt(\"Dirrefence Func\")\n \n\n\ndef product_of_array(array):\n global medium\n register_one()\n for index, num in enumerate(array):\n medium = medium * num\n\ndef jump_to():\n pass\n\ndef loop_through():\n pass\n \ndef exit_program():\n sys.exit(\"\"\"Thank for using,\n ▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ \n▐░░░░░░░░░░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌\n▐░█▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀▀▀ ▐░█▀▀▀▀▀▀▀█░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀█░▌ ▀▀▀▀█░█▀▀▀▀ ▐░█▀▀▀▀▀▀▀▀▀ ▐░█▀▀▀▀▀▀▀█░▌\n▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌\n▐░▌ ▐░▌▐░█▄▄▄▄▄▄▄▄▄ ▐░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄█░▌▐░█▄▄▄▄▄▄▄█░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄▄▄ ▐░█▄▄▄▄▄▄▄█░▌\n▐░▌ ▐░▌▐░░░░░░░░░░░▌▐░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌\n▐░▌ ▐░▌▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▐░▌ ▐░█▀▀▀▀█░█▀▀ ▐░█▀▀▀▀▀▀▀█░▌ ▐░▌ ▐░█▀▀▀▀▀▀▀▀▀ ▐░█▀▀▀▀█░█▀▀ \n▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ \n▐░█▄▄▄▄▄▄▄█░▌▐░█▄▄▄▄▄▄▄▄▄ ▐░█▄▄▄▄▄▄▄█░▌▄ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄▄▄ ▐░▌ ▐░▌ \n▐░░░░░░░░░░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░▌▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░▌ ▐░▌\n ▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀ ▀ ▀ ▀ ▀ ▀ ▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀ \n \n\t\\n Bye...\"\"\")\n\ndef exit_error():\n sys.exit(\"error, no matching input was found try again \")\n\ndef decimalToBinary(n):\n total= str(bin(int(n))[2:])\n while len(total) != 8:\n total = \"0\" + total\n return total\n\ndef BinaryToDecimal(n):\n return int(n, 2)\n\ndef line_split(line):\n line = line.split()\n\ndef appendKey(dict, key, ls):\n return dict[key] + \" \"\n\ndef checkKey(dict, key, ls, index):\n if key in dict.keys():\n ls[index] += dict[key] + \" \"\n else:\n #print(bin(int(key))[2:])\n ls[index] += decimalToBinary(key) + \" \"\n\ndef checkFunctionError(dict, key):\n if(key in dict.keys()):\n return True\n else:\n raise TypeError(\"Key Word input is not found, Wrong\")\n halt(\"CheckFuncionError Func\")\n\ndef checkFunction(dict, key):\n return dict[key]\n\ndef quotient_of_registers(register):\n global medium\n medium = medium // register[0]\n\ndef quotient_of_array(array):\n global medium\n medium = array[0]\n if(len(array) > 1):\n for index, num in enumerate(array[1:]):\n medium = medium // num\n else:\n raise ValueError(\"Array is not big enough for quotients...\")\n halt(\"Quotient Func\")\n\ndef easter_egg(our_grade):\n our_grade *= 1.05\n return \n\n\nfuncs = {\n '00000' : clear,\n '00001' : R1, #no\n '00010' : R2,\n '00011' : R3,\n '00100' : R4,\n '00101' : R5,\n '00110' : R6,\n '00111' : R7,\n '01000' : R8,\n '01001' : A1,\n '01010' : A2,\n '01011' : A3,\n '01100' : A4,\n '01101' : A5, \n '01110' : register_insert,\n '01111' : register_load,\n '10000' : register_save,\n '10001' : array_insert,\n '10010' : target_check,\n '10011' : sum_of_registers,\n '10100' : difference_of_registers,\n '10101' : product_of_registers,\n '10110' : jump_to,\n '10111' : loop_through,\n '11000' : exit_program,\n '11001' : display,\n '11010' : print_register,\n '11011' : sum_of_array,\n '11100' : difference_of_array,\n '11101' : product_of_array,\n '11110' : quotient_of_registers,\n '11111' : quotient_of_array\n}\n\nmnuemonic = {\n 'CLEAR' : '00000',\n 'R1' : '00001',\n 'R2' : '00010',\n 'R3' : '00011',\n 'R4' : '00100',\n 'R5' : '00101',\n 'R6' : '00110',\n 'R7' : '00111',\n 'R8' : '01000',\n 'A1' : '01001',\n 'A2' : '01010',\n 'A3' : '01011',\n 'A4' : '01100',\n 'A5' : '01101',\n 'INS' : '01110',\n 'LOAD' : '01111',\n 'SAVE' : '10000',\n 'ARRAY' : '10001',\n 'TAR' : '10010',\n 'SUMR' : '10011',\n 'SUBR' : '10100',\n 'MULTR' : '10101',\n 'JUMP' : '10110',\n 'LOOP' : '10111',\n 'END' : '11000',\n 'PRINT' : '11001',\n 'PRINTR' : '11010',\n 'SUMA' : '11011',\n 'SUBA' : '11100',\n 'MULTA' : '11101',\n 'QUOR' : '11110',\n 'QUOA' : '11111'\n \n}\n","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":7628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"445485066","text":"'''\r\nCreated on May 24, 2018\r\n\r\n@author: Anil\r\n'''\r\nimport pygame\r\nimport sys\r\nimport random\r\n\r\n\r\nboard_size = 30 # Size of the board, in block\r\nblock_size = 20 # Size of 1 block, in pixel\r\nsnake_head_color = (0, 100, 0) \r\nsnake_body_color = (0, 200, 0) \r\nfood_color = (200, 0, 0) \r\nspeed = 10 # Game speed (Normal = 10), The bigger, the faster\r\n\r\nclass Snake():\r\n def __init__(self):\r\n self.head = [int(board_size/4), int(board_size/4)]\r\n self.body = [[self.head[0], self.head[1]],\r\n [self.head[0]-1, self.head[1]],\r\n [self.head[0]-2, self.head[1]]\r\n ]\r\n self.direction = \"RIGHT\"\r\n \r\n\r\n def change_direction_toward(self, dir):\r\n if dir == \"RIGHT\" and not self.direction == \"LEFT\":\r\n self.direction = \"RIGHT\"\r\n if dir == \"LEFT\" and not self.direction == \"RIGHT\":\r\n self.direction = \"LEFT\"\r\n if dir == \"UP\" and not self.direction == \"DOWN\":\r\n self.direction = \"UP\"\r\n if dir == \"DOWN\" and not self.direction == \"UP\":\r\n self.direction = \"DOWN\"\r\n\r\n\r\n def move(self, food_position):\r\n ''' Move the snake to the desired direction by adding the head to that direction\r\n and remove the tail if the snake does not eat food\r\n '''\r\n if self.direction == \"RIGHT\":\r\n self.head[0] += 1\r\n if self.direction == \"LEFT\":\r\n self.head[0] -= 1\r\n if self.direction == \"UP\":\r\n self.head[1] -= 1\r\n if self.direction == \"DOWN\":\r\n self.head[1] += 1\r\n \r\n self.body.insert(0, list(self.head))\r\n if self.head == food_position:\r\n return 1\r\n else:\r\n self.body.pop()\r\n return 0\r\n \r\n\r\n def check_for_collision(self):\r\n # Check if the head collides with the edges of the board\r\n if self.head[0] >= board_size or self.head[0] < 0:\r\n return 1\r\n elif self.head[1] > board_size or self.head[1] < 0:\r\n return 1\r\n # Check if the head collides with the body\r\n for body in self.body[1:]:\r\n if self.head == body:\r\n return 1\r\n return 0\r\n\r\n\r\n def get_body(self):\r\n return self.body\r\n\r\n\r\nclass FoodGenerater():\r\n def __init__(self):\r\n self.head = [random.randrange(1, board_size), random.randrange(1, board_size)]\r\n self.is_food_on_screen = True\r\n\r\n\r\n def generate_food(self):\r\n if self.is_food_on_screen == False:\r\n self.head = [random.randrange(1, board_size), random.randrange(1, board_size)]\r\n self.is_food_on_screen = True\r\n return self.head\r\n\r\n\r\n def set_food_on_screen(self, bool_value):\r\n self.is_food_on_screen = bool_value\r\n\r\n\r\n# Game Initialization\r\nwindow = pygame.display.set_mode((board_size*block_size, board_size*block_size))\r\npygame.display.set_caption(\"SNAKE GAME\")\r\nfps = pygame.time.Clock()\r\n\r\nscore = 0\r\n\r\n# Initialize snake and food\r\nsnake = Snake()\r\nfood_generater = FoodGenerater()\r\n\r\ndef game_start():\r\n for i in range(3):\r\n pygame.display.set_caption(\"SNAKE GAME | Game starts in \" + str(3-i) + \" second(s) ...\")\r\n pygame.time.wait(1000)\r\n\r\n \r\ndef game_over():\r\n pygame.display.set_caption(\"SNAKE GAME | Score: \" + str(score) + \" | GAME OVER. Press any key to quit ...\")\r\n while True:\r\n event = pygame.event.wait()\r\n if event.type == pygame.KEYDOWN:\r\n break\r\n pygame.quit()\r\n sys.exit()\r\n\r\n\r\ngame_start()\r\n\r\nwhile True:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n game_over()\r\n elif event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_RIGHT:\r\n snake.change_direction_toward(\"RIGHT\")\r\n if event.key == pygame.K_UP:\r\n snake.change_direction_toward(\"UP\")\r\n if event.key == pygame.K_DOWN:\r\n snake.change_direction_toward(\"DOWN\")\r\n if event.key == pygame.K_LEFT:\r\n snake.change_direction_toward(\"LEFT\")\r\n food_position = food_generater.generate_food()\r\n if snake.move(food_position) == 1:\r\n score += 1\r\n food_generater.set_food_on_screen(False)\r\n\r\n window.fill(pygame.Color(225, 225, 225))\r\n # Draw snake\r\n head = 1\r\n for pos in snake.get_body():\r\n if head == 1:\r\n pygame.draw.rect(window, snake_head_color, pygame.Rect(pos[0]*block_size, pos[1]*block_size, block_size, block_size))\r\n head = 0\r\n else:\r\n pygame.draw.rect(window, snake_body_color, pygame.Rect(pos[0]*block_size, pos[1]*block_size, block_size, block_size))\r\n\r\n # Draw food\r\n pygame.draw.rect(window, food_color, pygame.Rect(food_position[0]*block_size, food_position[1]*block_size, block_size, block_size))\r\n \r\n if snake.check_for_collision() == 1:\r\n game_over()\r\n\r\n pygame.display.set_caption(\"SNAKE GAME | Speed: \" + str(speed) + \" | Score: \" + str(score))\r\n pygame.display.flip()\r\n fps.tick(speed)","sub_path":"newtry.py","file_name":"newtry.py","file_ext":"py","file_size_in_byte":5134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"180071071","text":"from fuzzywuzzy import fuzz\nimport re\nimport numpy as np\nfrom urllib.request import urlopen\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\n\n#task2_datasets = open('cluster3.txt')\n#dataset_file_names = task2_datasets.readline()[1:-2].split(',')\n#dataset_file_names = [x.replace(\"'\", \"\").replace(\" \", \"\").split('.')[0:2] for x in dataset_file_names]\n\n#print(dataset_file_names[0])\n\nsimilar_words = { \\\n 'person_name': ['First Name', 'Name', 'Person Name', 'Names', 'LastName', 'Last Name', 'Middle Name', 'MiddleName', 'MI'],\n 'business_name': ['business name', 'dba', 'organization', 'org name', 'organization name'],\n 'phone_number': ['phone no', 'cell phone no', 'cell phone', 'phone number'],\n 'address': ['address', 'home address', 'house address', 'house number', 'house no', 'street address'],\n 'street_name': ['Street Name', 'Street', 'Streets', 'StreetName', 'street address'],\n 'city': ['district', 'city', 'city name'],\n 'neighborhood': ['neighborhood', 'area', 'location'],\n 'lat_lon_cord': ['lat', 'long', 'lattitude', 'longitude', 'lat long'],\n 'zip_code': ['zip', 'zip code', 'zipcode', 'postcode', 'postal code', 'post'],\n 'borough': ['borough', 'boro'],\n 'school Name': ['school name'],\n 'color': ['color', 'colors'],\n 'car_make': ['car make', 'vehicle make'],\n 'city_agency': ['Agency Name', 'Agency'],\n 'area_of_study': ['area of study', 'interest'],\n 'subject_in_school': ['subject', 'subject name'],\n 'school_level': ['school levels', 'level'],\n 'college_name': ['college name', 'university name'],\n 'website': ['website', 'url', 'websites'],\n 'building_classification': ['building type', 'building classification', 'type of building'],\n 'vehicle_type': ['type of vehicle', 'vehicle type', 'car type'],\n 'location_type': ['type of location', 'location type'],\n 'park_playground': ['parks', 'park name', 'playground', 'park', 'playground name'],\n 'other': ['other']\n }\n\n\n\"\"\"\nregex list\n\"\"\"\nBOROUGH_LIST = ['brooklyn', 'manhattan', 'queens', 'bronx', 'staten island']\n\nstreet_address = re.compile('\\d{1,4} [\\w\\s]{1,20}(?:street|st|avenue|ave|road|rd|highway|hwy|square|sq|trail|trl|drive|dr|court|ct|park|parkway|pkwy|circle|cir|boulevard|blvd)\\W?(?=\\s|$)', re.IGNORECASE)\n\n\nCOLOR_NAMES_LIST = ['White', 'Yellow', 'Blue', 'Red', 'Green', 'Black', 'Brown', 'Azure', 'Ivory', 'Teal', 'Silver', 'Purple', 'Navy blue', 'Gray', 'Orange', 'Maroon', 'Charcoal', 'Aquamarine', 'Coral', 'Fuchsia', 'Wheat', 'Lime', 'Crimson', 'Khaki', 'pink', 'Magenta', 'Olden', 'Plum', 'Olive', 'Cyan']\n\ndef isValidURL(url):\n import re\n regex = re.compile(\n r'^https?://' # http:// or https://\n r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+[A-Z]{2,6}\\.?|' # domain...\n r'localhost|' # localhost...\n r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})' # ...or ip\n r'(?::\\d+)?' # optional port\n r'(?:/?|[/?]\\S+)$', re.IGNORECASE)\n return url is not None and regex.search(url)\n\n\n\n\ndef isValidStreetName(streetName):\n return re.match(street_address)\n\n\n\n\"\"\"\nloop through all the column names\n\"\"\"\nline_list = []\nwith open('manual_labeling.csv', 'r') as csvf:\n while(True):\n line = csvf.readline()\n if(line):\n line_list.append(line[:-1])\n else:\n break\n\n\n\nheader = line_list[0]\nline_list = line_list[1:]\ncategories = similar_words.keys()\nno_of_categories = len(categories)\nmanual_labels = [line.split(',') for line in line_list]\nconf_matrix = np.zeros((no_of_categories, no_of_categories))\n\n\n\ndef predict_category(col_name):\n pred = np.zeros(no_of_categories)\n cat_token_scores = []\n for category in categories:\n max_cat_token_score = 0\n for sim_word in similar_words[category]:\n tok_score = fuzz.partial_ratio(sim_word, col_name) + fuzz.token_sort_ratio(sim_word, col_name)\n if(tok_score >= max_cat_token_score):\n max_cat_token_score = tok_score\n cat_token_scores.append(max_cat_token_score)\n \n max_tok_score = max(cat_token_scores)\n if(max_tok_score < 80):\n cat_token_scores[-1] = 1\n for i in range(len(cat_token_scores)-1):\n cat_token_scores[i] = 0\n return cat_token_scores\n for cati in range(len(cat_token_scores)):\n if(cat_token_scores[cati] < max_tok_score):\n cat_token_scores[cati] = 0\n else:\n cat_token_scores[cati] = 1\n return cat_token_scores\n\n\n\n\nfor rowi, row in enumerate(manual_labels[1:]):\n ds_fname = row[1]\n col_name = row[2:-24]\n pred_cat = predict_category(str(col_name).lower())\n pred_cat = np.array(pred_cat)\n act_cat = np.array([int(x) for x in row[-24:]])\n pred_res = np.all(pred_cat == act_cat)\n #print(rowi)\n #print(np.where(act_cat == 1))\n ar = np.where(act_cat == 1)[0][0]\n pc = np.where(pred_cat == 1)[0][0]\n conf_matrix[ar][pc] += 1\n \"\"\"\n print(rowi)\n if(not pred_res):\n proceed = 'n'\n while(proceed != 'y'):\n print(ds_fname, col_name, pred_cat, act_cat)\n proceed = input('proceed?')\n \"\"\"\n\n\n\nsns.heatmap(conf_matrix, annot = True, cbar = False)\nplt.ylabel('True Label')\nplt.xlabel('Predicted Label')\nplt.show() \n\"\"\" \n\"\"\"\nprec = []\nrec = []\ncat_list = list(categories)\n\n# precision, recall\nfor ci in range(no_of_categories):\n prec.append(conf_matrix[ci][ci]/np.sum(conf_matrix[:, ci]))\n rec.append(conf_matrix[ci][ci]/np.sum(conf_matrix[ci, :]))\n\nfor ci in range(no_of_categories):\n print(cat_list[ci], ',', prec[ci], ',', rec[ci])\n\n\n\n\"\"\"\nfollowing is sample code, didnt work with pyspark cluster\n\"\"\"\n\nfrom urllib.request import urlopen\nfrom googlesearch import search\n# google search api\n\ncol_val = 'google'\nurl_list = list(search(col_val, stop=10))\nfreq_count = [0, 0]\nsimilar_words = ['company', 'hospital']\n\nfor url in url_list:\n for si, simword in enumerate(similar_words):\n freq_count[si] += str(urlopen(url).read()).count(simword)\n\nprint(freq_count)\n# prints: category of google is company\n# prints: category of city clinic is hospital\nprint('the category of', col_val, 'is', similar_words[freq_count.index(max(freq_count))])\n\n\n\"\"\"\nJust like google search, another simple technique is to use duckduckgo api, it gives summary for most of the terms/text\n\"\"\"\nquery = 'nyu langone'\nquery = query.replace(' ', '+')\nurl = 'https://api.duckduckgo.com/?q=' + query + '&format=json&pretty=1'\nq_rep = json.loads(urlopen(url).read().decode(\"utf-8\"))\n# prints abstract about query term,which can be processed futher to determine category\nprint(q_rep['Abstract'])\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"semanticProfiling.py","file_name":"semanticProfiling.py","file_ext":"py","file_size_in_byte":6687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"453696053","text":"import os\nimport string\nimport time\n\n#os.system('chcp 65001')\n\n\n\"---------------------------------------------------------------------------------------\"\n#Initiates constants, statistic storage, and tags\nLISTplayer = ['MATTHEW','JOHN','SHAUN']\nSTATSmatthew = {'STR':0,'DEX':0,'CON':0,'WPW':0,'MVM':0,'AMR':0,'HIT':0,'DMG':0,'RCV':0,'APR':0,'AGT':0,'INT':0,'MNP':0,'SRC':0,'SNK':0}\nSTATUSmatthew = {'Defensive':True}\n\ndbTags = {'Round':'rnd',\n\t\t 'Creature ID':'cid',\n\t\t 'Action Type':'typ',\n\t\t 'Action':'act',\n\t\t 'Parameter':'par',\n\t\t 'Value':'val',\n\t\t 'Coordinate':'cor',\n\t\t 'Result':'res'\n\t\t\t\t }\ndbTagsOpen = {}\ndbTagsClose = {}\n\nfor key,item in dbTags.items():\n\tdbTagsOpen[key] = '<'+item+'>'\n\tdbTagsClose[key] = ''\n\"---------------------------------------------------------------------------------------\"\n\n\n\n\"---------------------------------------------------------------------------------------\"\n#The Getch() functions, for key-press detection\nclass _Getch:\n\tdef __init__(self):\n\t\ttry:\n\t\t\tself.impl = _GetchWindows()\n\t\texcept ImportError:\n\t\t\tself.impl = _GetchUnix()\n\n\tdef __call__(self): return self.impl()\n\n\nclass _GetchUnix:\n\tdef __init__(self):\n\t\timport tty, sys\n\n\tdef __call__(self):\n\t\timport sys, tty, termios\n\t\tfd = sys.stdin.fileno()\n\t\told_settings = termios.tcgetattr(fd)\n\t\ttry:\n\t\t\ttty.setraw(sys.stdin.fileno())\n\t\t\tch = sys.stdin.read(1)\n\t\tfinally:\n\t\t\ttermios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n\t\treturn ch\nclass _GetchWindows:\n\tdef __init__(self):\n\t\timport msvcrt\n\n\tdef __call__(self):\n\t\timport msvcrt\n\t\treturn msvcrt.getch()\ndef getKeyPress():\n\tgetch = _Getch()\n\tkey = getch()\n\tif key == b'\\xe0':\n\t\tsubkey = getch()\n\t\tif subkey == b'H': key = 'up'\n\t\telif subkey == b'P': key = 'down'\n\t\telif subkey == b'K': key = 'left'\n\t\telif subkey == b'M': key = 'right'\t\n\telif key == b'\\r': \n\t\tkey = 'enter'\t\n\telse: key = key.decode('utf8')\n\t#key = key.lower()\n\treturn(key)\n\"---------------------------------------------------------------------------------------\"\n\ndef clearScreen():\n\tos.system('cls')\n\n\"---------------------------------------------------------------------------------------\"\n#Returns a tuple containing console width and consle height\ndef screenSize():\n\tfrom ctypes import windll, create_string_buffer\n\t# stdin handle is -10\n\t# stdout handle is -11\n\t# stderr handle is -12\n\th = windll.kernel32.GetStdHandle(-12)\n\tcsbi = create_string_buffer(22)\n\tres = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)\n\tif res:\n\t\timport struct\n\t\t(bufx, bufy, curx, cury, wattr,\n\t\tleft, top, right, bottom, maxx, maxy) = struct.unpack(\"hhhhHhhhhhh\", csbi.raw)\n\t\tsizex = right - left + 1\n\t\tsizey = bottom - top + 1\n\telse:\n\t\tsizex, sizey = 80, 25 # can't determine actual size - return default values\n\n\treturn(sizex-1, sizey)\n\"---------------------------------------------------------------------------------------\"\n\n\n\n\"---------------------------------------------------------------------------------------\"\n#Takes a string, compares each tag pair to dataTags, strips out the tag information, and appends the data to a dictionary paired with a datablock type depicted by the tag info. \ndef dataProcessor(dataInput):\n\tif dataInput == '': return None\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#if the dataInput is blank, return None\n\toutput = {}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#create a dictionary to store output\n\twhile len(dataInput) > 0:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#while there is still unprocessed dataInput in the dataInput:\n\t\tif dataInput[0] != '<':dataInput = dataInput[1:]\t\t\t\t\t\t\t\t\t\t\t\t\t#if the first character of the dataInput is not a < from a tag, strip it from the dataInput\n\t\tfor key,item in dbTags.items():\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#cycle through every possible tag\n\t\t\tif dataInput[:len(dbTagsOpen[key])] == dbTagsOpen[key]:\t\t\t\t\t\t\t\t\t\t\t#if the first len(tag) characters of dataInput match the tag\n\t\t\t\tdataInput = dataInput[len(dbTagsOpen[key]):] \t\t\t\t\t\t\t\t\t\t\t\t#strip the opening tag from dataInput\n\t\t\t\tfor number,character in enumerate(dataInput):\t\t\t\t\t\t\t\t\t\t\t\t#cycle through every letter in dataInput\n\t\t\t\t\tif dataInput[number:number+len(dbTagsClose[key])] == dbTagsClose[key]:\t\t\t\t\t#if the program reaches the expected end tag\n\t\t\t\t\t\tbreak\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\toutput[key] = dataInput[:number]\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#append the dataInputblock to output\n\t\t\t\tdataInput = str.strip(dataInput[number+len(dbTagsClose[key]):])\t\t\t\t\t\t\t\t#strip all processed dataInput from dataInput\n\treturn output\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#return all processed dataInput\n\"---------------------------------------------------------------------------------------\"\n\n\n\n\"---------------------------------------------------------------------------------------\"\n#Takes processed KEN input, and prints data to stdout in columns, in order given below. \ndef dataOutput(dataInput):\n\tfor i in dataInput: \n\t\tif 'Round' in i: print('\\n'+'Round '+i['Round'],end='')\n#\t\tif 'Creature ID' in i and 'Action' in i and 'Value' in i:\n#\t\t\tif i['Creature ID'] == 'HELLHOUND 3' and i['Action'] == 'Damage':\n#\t\t\t\tprint()\n#\t\t\t\tfor j in ['Creature ID','Action Type','Action','Parameter','Value','Coordinate','Result']:\n#\t\t\t\t\tif j in i: \tprint(i[j].ljust(20),end=\"\")\n#\t\t\t\t\telse:\t\tprint(' '*20,end='')\n\n\t\tfor j in ['Creature ID','Action Type','Action','Parameter','Value','Coordinate','Result']:\n\t\t\tif j in i: \tprint(i[j].ljust(20),end=\"\")\n\t\t\telse:\t\tprint(' '*20,end='')\n\t\tprint()\n\"---------------------------------------------------------------------------------------\"\n\n\n\n\"---------------------------------------------------------------------------------------\"\n#Takes a filename and opens the file. Strips each line of \\n \\t and whitespace, and runs each line through dataProcessor(). Outputs each processed line as strings in a list \ndef dataImport(filename='/Runthrough 1.txt'):\n\toutput = []\n\tdataFile = open(os.path.dirname(os.path.abspath(__file__)) + filename)\n\tfor line in dataFile:\n\t\tfor item in ['\\t','\\n']:\n\t\t\tline = line.replace(item, '')\n\t\tline = str.strip(line)\n\t\tline = dataProcessor(line)\n\t\tif line != None: output.append(line)\n\treturn output\n\"---------------------------------------------------------------------------------------\"\n\n\n\n\"---------------------------------------------------------------------------------------\"\n#Prints the header for every frame, for design purposes\ndef printTitle(windowTitle='Command Rendering Application: Kraken Engine Notation',windowTitlePadding=4):\n\tclearScreen()\n\tconsoleWidth,consoleHeight = screenSize()\n\twindowTitle = (' '*windowTitlePadding + windowTitle + ' '*windowTitlePadding)\n\tprint('═'*(consoleWidth))\n\tprint(':'*int((consoleWidth-len(windowTitle))/2),end=\"\")\n\tprint(windowTitle,end=\"\")\n\tprint(':'*int((consoleWidth-len(windowTitle))/2))\n\tprint('═'*consoleWidth)\n\tprint()\n\"---------------------------------------------------------------------------------------\"\n\n\n\n\"---------------------------------------------------------------------------------------\"\n#Important low-level function, prints a line centered on the screen\ndef printLineCenter(dataInput):\n\tconsoleWidth,consoleHeight = screenSize()\n\tprint(' '*int((consoleWidth/2)-(len(dataInput)/2))+dataInput)\n\"---------------------------------------------------------------------------------------\"\n\n\n\n\"---------------------------------------------------------------------------------------\"\n#High level function to print a menu of options\ndef printMenu(itemName,listWidth,listHeight=3,selectedItem=0):\n\n\tdef printMenuItem(dataInput,align='center',selected=False):\n\t\tif align == 'left': \n\t\t\tif selected: \tprintLineCenter('║ ' + dataInput + ' '*(listWidth-len(dataInput)-1) + '║')\n\t\t\telse:\t\t\tprintLineCenter('| ' + dataInput + ' '*(listWidth-len(dataInput)-1) + '|')\n\t\telif align == 'right': \n\t\t\tif selected:\tprintLineCenter('║' + ' '*(listWidth-len(dataInput)-1) + dataInput + ' ║')\n\t\t\telse:\t\t\tprintLineCenter('|' + ' '*(listWidth-len(dataInput)-1) + dataInput + ' |')\n\t\telif align == 'center': \n\t\t\tif selected:\tprintLineCenter('║ ' + ' '*int((listWidth-len(dataInput)-2)/2) + dataInput + ' '*int((listWidth-len(dataInput)-1)/2) + ' ║')\n\t\t\telse:\t\t\tprintLineCenter('| ' + ' '*int((listWidth-len(dataInput)-2)/2) + dataInput + ' '*int((listWidth-len(dataInput)-1)/2) + ' |')\n\t\n\tfor num,item in enumerate(itemName):\n\t\tif num==selectedItem: \t\t\t\t\tprintLineCenter('╔' + '═'*listWidth + '╗')\n\t\telse: \t\t\t\t\t\t\t\t\tprintLineCenter('+' + '-'*listWidth + '+')\n\t\tfor i in range(listHeight):\n\t\t\tif i == int(listHeight/2):\n\t\t\t\tif num==selectedItem: \t\t\tprintMenuItem('-=- ' + item + ' -=-','center',True)\n\t\t\t\telse: \t\t\t\t\t\t\tprintMenuItem(item,'center')\n\n\t\t\telse:\n\t\t\t\tif num==selectedItem: \t\tprintMenuItem(' ',selected=True)\n\t\t\t\telse: \t\t\t\t\t\tprintMenuItem(' ')\n\t\tif num==selectedItem: \t\t\t\t\tprintLineCenter('╚' + '═'*listWidth + '╝')\n\t\telse: \t\t\t\t\t\t\t\t\tprintLineCenter('+' + '-'*listWidth + '+')\n\t\tprint()\n\"---------------------------------------------------------------------------------------\"\n\n\n\n\"---------------------------------------------------------------------------------------\"\n#High-level function to print different screens\ndef interfaceDisplay(interface,windowTitle):\n\tif interface == 'mainMenu':\n\t\tkey = None\n\t\titem = 0\n\t\tmainMenu = ['Browse Raw Data',\n\t\t\t\t\t\t'Filter KEN Data',\n\t\t\t\t\t\t'View Statistics By Round',\n\t\t\t\t\t\t'Check KEN For Common Errors',\n\t\t\t\t\t\t'Generate KEN For Next Round']\n\t\twhile key != 'enter':\n\t\t\tprintTitle()\n\t\t\tprintMenu(mainMenu,listWidth=len(windowTitle),selectedItem=item)\n\t\t\tkey = getKeyPress()\n\t\t\tif key == 'up': item -= 1\n\t\t\tif key == 'down': item += 1\n\t\t\tif key in ['1','2','3','4','5','6','7','8','9']: item = int(key)-1\n\t\t\tif item < 0: item = 0\n\t\t\tif item > len(mainMenu)-1: item = len(mainMenu)-1\n\t\treturn(item)\n\n\n\"---------------------------------------------------------------------------------------\"\n\n\n\n\"=======================================================================================\"\n#The main program function\ndef main():\n\tclearScreen()\n\tgetch = _Getch()\n\twindowTitle = 'Command Rendering Application: Kraken Engine Notation'\n\tconsoleWidth,consoleHeight = screenSize()\n\tprintTitle()\n\tinterfaceDisplay('mainMenu',windowTitle)\n\t#printMenu(['Browse Raw Data','Filter KEN Data','View Statistics By Round','Check KEN For Common Errors','Generate KEN For Next Round'],listWidth=len(windowTitle),selectedItem=1)\n\n\t#dataKEN = dataImport()\n\t#dataOutput(dataKEN)\n\n#quit()\n\"=======================================================================================\"\n\nmain()\n\n# for item in range(len(KENbreakdown)):\n# \tKENbreakdown[item] = processor(KENbreakdown[item])\n# \t#print(processor(item))\n\nprint()\n#print(KENbreakdown)\n\n\n\t#print(i)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#print each item inide the KENbreakdown list\n\n\n\n\n\n\n\"\"\"Extra data required for each ACTION\"\"\"\n\n# dbSecondary = {'Attack'\t:['Parameter','Coordinate','Result'],\n# \t\t\t\t\t\t'Cast':['Parameter','Value','Coordinate','Result'],\n# \t\t\t\t\t\t'Wait'\t\t:[],\n# \t\t\t\t\t\t'Appraise'\t:['Parameter'],\n# \t\t\t\t\t\t'Interpret'\t:['Parameter'],\n# \t\t\t\t\t\t'Manipulate':['Parameter'],\n# \t\t\t\t\t\t'Search'\t:[],\n# \t\t\t\t\t\t'Force'\t\t:['Parameter'],\n\n# \t\t\t\t\t\t'Sustain'\t:[],\n# \t\t\t\t\t\t'Smash'\t\t:[],\n\n# \t\t\t\t\t\t'Move'\t\t:['Coordinate'],\n# \t\t\t\t\t\t'Wield'\t\t:['Parameter'],\n# \t\t\t\t\t\t'Leap'\t\t:['Coordinate',],\n# \t\t\t\t\t\t'Reload'\t:[],\n# \t\t\t\t\t\t'Shift'\t\t:[',Coordinate'],\n# \t\t\t\t\t\t'Close'\t\t:[',Parameter'],\n# \t\t\t\t\t\t'Open'\t\t:['Parameter'],\n\n# \t\t\t\t\t\t'Get'\t\t:['Parameter'],\n# \t\t\t\t\t\t'Drop'\t\t:['Parameter'],\n# \t\t\t\t\t\t'AttOfOpp'\t:['Parameter','Coordinate','Result'],\n\n# \t\t\t\t\t\t'Damage'\t:['Value'],\n# \t\t\t\t\t\t'Heal'\t\t:['Value'],\n# \t\t\t\t\t\t'Status'\t:['Parameter'],\n# \t\t\t\t\t\t'Teleport'\t:['Coordinate'],\n\n# \t\t\t\t\t\t'On Death'\t:['Parameter','Coordinate']\n# \t\t\t\t\t\t}","sub_path":"Code/Command Rendering Application.py","file_name":"Command Rendering Application.py","file_ext":"py","file_size_in_byte":11543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"26731980","text":"from helpers import *\nfrom unittest import TestCase\n\nfrom shttpfs.crypto import *\n\nclass TestCrypto(TestCase):\n#######################################################################################\n def test_key_encrypt_decrypt(self):\n \"\"\" Test that encryption and decryption of a item returns the same item \"\"\"\n\n prvate, public = make_keypair()\n\n encrypted = encrypt_private('test', prvate)\n decrypted = decrypt_private('test', encrypted)\n\n self.assertEqual(decrypted, prvate,\n msg = 'Decrypted result does not match source')\n\n#######################################################################################\n def test_sign_varify(self):\n \"\"\" Test signing and verification that signature \"\"\"\n\n data = 'something to sign'\n\n prv, pub = make_keypair()\n\n signed = sign_data(prv, data)\n\n self.assertTrue(varify_signiture(pub, signed),\n msg='Signature verification failed')\n\n#######################################################################################\n def test_key_wirte(self):\n \"\"\" Test keys are written to files correctly \"\"\"\n\n empty_dir('keys')\n\n prv, pub = write_keypair('test', 'keys/public', '.key', 'keys/private', '.key')\n private = file_get_contents('keys/private.key')\n public = file_get_contents('keys/public.key')\n\n self.assertEqual(prv, private,\n msg = 'private key file corrupted')\n\n self.assertEqual(pub, public,\n msg = 'public key file corrupted')\n\n data = 'something to sign'\n\n prv = decrypt_private('test', prv)\n private = decrypt_private('test', private)\n\n signed = sign_data(prv, data)\n\n self.assertTrue(varify_signiture(pub, signed),\n msg='Signature verification failed')\n\n signed = sign_data(private, data)\n self.assertTrue(varify_signiture(public, signed),\n msg='Signature verification failed')\n\n empty_dir('keys')\n os.rmdir('keys')\n \n","sub_path":"shttpfs/tests/test_crypto.py","file_name":"test_crypto.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"222016194","text":"import matplotlib.pyplot as plt\nfrom IPython import display\n\nplt.ion()\n\ndef plot(scores, mean_sores):\n display.clear_output(wait=True)\n display.display(plt.gcf())\n plt.clf()\n plt.title('Traning...')\n plt.xlabel('number of game')\n plt.ylabel('score')\n plt.plot(scores)\n plt.plot(mean_sores)\n plt.ylim(ymin=0)\n plt.text(len(scores)-1, scores[-1], str(scores[-1]))\n plt.text(len(mean_sores) -1, mean_sores[-1], str(mean_sores[-1]))","sub_path":"helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"983134","text":"from albumentations import (Cutout, Compose, Normalize, RandomRotate90, HorizontalFlip,\n VerticalFlip, ShiftScaleRotate, Transpose, OneOf, IAAAdditiveGaussianNoise,\n GaussNoise, RandomGamma, RandomContrast, RandomBrightness, HueSaturationValue,\n RandomBrightnessContrast, Lambda, NoOp, CenterCrop, Resize\n )\nfrom albumentations.pytorch import ToTensor\nimport cv2\nmean_img = [0.22363983, 0.18190407, 0.2523437 ]\nstd_img = [0.32451536, 0.2956294, 0.31335256]\ntransform_train = Compose([\n HorizontalFlip(p=0.5),\n ShiftScaleRotate(shift_limit=0.05, scale_limit=0.05, \n rotate_limit=20, p=0.3, border_mode = cv2.BORDER_REPLICATE),\n Transpose(p=0.5),\n Normalize(mean=mean_img, std=std_img, max_pixel_value=255.0, p=1.0),\n ToTensor()\n])\n\ntransform_test= Compose([\n HorizontalFlip(p=1),\n Transpose(p=0),\n Normalize(mean=mean_img, std=std_img, max_pixel_value=255.0, p=1.0),\n ToTensor()\n])","sub_path":"client/transforms.py","file_name":"transforms.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"601376490","text":"import matplotlib.pyplot as plt\r\n\r\nnumbers = list(range(101))\r\ncubes_of_numbers = [c**3 for c in numbers]\r\n\r\nplt.scatter(numbers, cubes_of_numbers, c=cubes_of_numbers, cmap=plt.cm.Blues, edgecolor='none', s=30)\r\n\r\nplt.title(\"Cubes of 5000 number\", fontsize=25)\r\nplt.xlabel(\"Value\", fontsize=15)\r\nplt.ylabel(\"Cubes of Value\", fontsize=15)\r\nplt.tick_params(axis='both', which='major', labelsize=15)\r\nplt.axis([0, 150, 0, 1100000])\r\n\r\nplt.show()\r\n","sub_path":"matplotlib_scatters_cubes.py","file_name":"matplotlib_scatters_cubes.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"437208644","text":"from tkinter import Tk, Toplevel, filedialog, StringVar, LabelFrame\nfrom tkinter.ttk import Frame, Button, Label, Entry, Radiobutton, Combobox\nfrom tkinter import BOTH, TOP, W, LEFT, N, X, Y, E, BOTTOM, S\n\nfrom typing import List\n\nfrom analyse_result import AnalyseResultFrame\nfrom params import Parameter, PARAMS\n\nimport docx\n\n\nclass ParamsInputFrame(Frame):\n def __init__(self, parent: Tk or Toplevel, param_ids: List[int]):\n Frame.__init__(self, parent)\n self.parent = parent\n self.param_ids = param_ids\n self.paragraph_params = [param_id for param_id in param_ids if not PARAMS[param_id].is_run]\n self.run_params = [param_id for param_id in param_ids if PARAMS[param_id].is_run]\n\n self.pack(fill=BOTH, expand=1)\n self.centerWindow()\n\n self.parent.title('Введите параметры для анализа')\n\n self.user_input = {param_id: StringVar() for param_id in self.param_ids}\n\n main_container = Frame(self)\n main_container.pack(fill=BOTH)\n\n self.left_container = Frame(main_container)\n self.right_container = AnalyseResultFrame(main_container)\n\n self.left_container.pack(side=LEFT, anchor=W)\n self.right_container.pack(side=LEFT)\n\n params_container = Frame(self.left_container)\n\n __params = list(PARAMS.values())\n p = {\n 'Шрифты': __params[:5],\n 'Абзац': __params[5:],\n }\n\n for category_name, params in p.items():\n group = LabelFrame(params_container, text=category_name)\n group.pack(side=TOP, fill=X)\n\n #_create_group_params(group, params)\n\n for param in params:\n param_id = 0\n for id_, _parameter in PARAMS.items():\n if param == _parameter:\n param_id = id_\n inner_container = Frame(group)\n lbl = Label(inner_container, text=param.name)\n text_field = Combobox(inner_container,\n textvariable=self.user_input[param_id])\n text_field['values'] = param.default_vals\n text_field.current(param.start_val)\n\n lbl.pack(side=LEFT, anchor=W)\n text_field.pack(side=LEFT, expand=True, anchor=E)\n\n inner_container.pack(side=TOP, fill=X, padx=10)\n\n\n# group = LabelFrame(params_container, text='Шрифт')\n# group.pack(side=TOP, fill=X)\n#\n# group2 = LabelFrame(params_container, text='Абзац')\n# group2.pack(side=TOP, fill=X)\n#\n# indent = 0\n# i = 0\n# for param_id in self.param_ids:\n# param = PARAMS[param_id]\n# if i < 4:\n# current_group = group\n# else:\n# current_group = group2\n# inner_container = Frame(current_group)\n# lbl = Label(inner_container, text=param.name)\n# text_field = Combobox(inner_container,\n# textvariable=self.user_input[param_id])\n# text_field['values'] = param.default_vals\n# text_field.current(param.start_val)\n#\n# lbl.pack(side=LEFT, anchor=W)\n# text_field.pack(side=LEFT, expand=True, anchor=E)\n#\n# inner_container.pack(side=TOP, fill=X, padx=10)\n# i += 1\n\n self.addButton = Button(self.left_container,\n text=\"Начать анализ\",\n command=self.new_test)\n\n params_container.pack(side=TOP, fill=BOTH)\n self.addButton.pack(side=TOP, pady=8)\n\n\n def centerWindow(self):\n w = 840\n h = 410\n sw = self.parent.winfo_screenwidth()\n sh = self.parent.winfo_screenheight()\n x = (sw - w) / 2\n y = (sh - h) / 2\n self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))\n\n def new_test(self):\n files = filedialog.askopenfilenames()\n if not files:\n return\n\n result_string = \"\"\n for path in files:\n doc = docx.Document(path)\n print(\"Working with file\", path)\n result_string += f\"Файл {path}\\n\"\n for paragraph_ind, paragraph in enumerate(doc.paragraphs):\n formatting = paragraph.paragraph_format\n par_string = \"\"\n for param_id in self.paragraph_params:\n param = PARAMS[param_id]\n #print(f\"Analyzing param {param.name}\")\n user_input_val = self.user_input[param_id].get()\n in_doc_val = str(param.getter(formatting))\n if user_input_val.strip() != in_doc_val.strip():\n par_string += f\"{param.name}: {user_input_val} \" \\\n f\"--- {in_doc_val}\\n\"\n\n if not self.run_params:\n continue\n\n for run_id, run in enumerate(paragraph.runs):\n run_string = \"\"\n for param_id in self.run_params:\n param = PARAMS[param_id]\n user_input_val = self.user_input[param_id].get()\n in_doc_val = str(param.getter(run))\n if user_input_val.strip() != in_doc_val.strip():\n run_string += f\"{param.name}: {user_input_val} \" \\\n f\"--- {in_doc_val}\\n\"\n if run_string:\n par_string += f\"Run {run_id + 1}\\n{run_string}\"\n\n if par_string:\n result_string += f\"Параграф {paragraph_ind + 1}\\n{par_string}\\n\"\n\n# window = Toplevel()\n# AnalyseResultFrame(window, result_string)\n self.right_container.set_text(result_string)\n\n\ndef main():\n from params import PARAMS\n\n root = Tk()\n ParamsInputFrame(root, param_ids=list(PARAMS.keys()))\n root.mainloop()\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"input_params (1).py","file_name":"input_params (1).py","file_ext":"py","file_size_in_byte":6042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"238364356","text":"from ..models import Contact, Blog, Subscribe\n\n\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\n\nfrom ..serializer import BlogDetailSerializer, CategorySerializer, \\\n ContactSerializer, \\\n AddBlogSerializer, BlogListSeriazlizer, PageCountSerializer, \\\n SubscribeSerializer\n\n# Create your views here.\n\n\nclass AddBlog(APIView):\n\n model = Blog\n serializer_class = AddBlogSerializer\n\n def post(self, request, format=None):\n\n serializer = self.serializer_class(data=request.data)\n\n if not serializer.is_valid():\n\n return Response({\"Error\": \"Invalid Data\"},\n status=status.HTTP_400_BAD_REQUEST)\n\n title = serializer.data.get(\"title\")\n image = serializer.data.get(\"image\")\n content = serializer.data.get(\"content\")\n tag = serializer.data.get(\"tag\")\n description = serializer.data.get(\"description\")\n\n slug = (\"-\").join(title.split(\" \"))\n\n new_blog = Blog(title=title, image=image,\n content=content, tag=tag, slug=slug,\n description=description)\n\n new_blog.save()\n\n return Response({\"Success\": \"Blog Added\"},\n status=status.HTTP_200_OK)\n\n\nclass BlogList(APIView):\n\n serializer_class = BlogListSeriazlizer\n model = Blog\n MULT = 5\n SUB = 5\n\n def get(self, request, format=None, *args, **kwargs):\n\n page = kwargs['page'] * self.MULT\n\n queryset = Blog.objects.all()[::-1]\n queryset = queryset[page - self.SUB: page]\n\n data = []\n\n for entry in queryset:\n\n data.append(self.serializer_class(entry).data)\n\n return Response(data={\"data\": data}, status=status.HTTP_200_OK)\n\n\nclass BlogCategoryList(APIView):\n\n serializer_class = BlogListSeriazlizer\n model = Blog\n MULT = 5\n SUB = 5\n\n def get(self, request, format=None, *args, **kwargs):\n\n category = kwargs['category']\n page = kwargs['page'] * self.MULT\n\n queryset = Blog.objects.filter(tag=category)[::-1]\n\n queryset = queryset[page - self.SUB: page]\n\n data = []\n\n for entry in queryset:\n\n data.append(self.serializer_class(entry).data)\n\n return Response(data={\"data\": data}, status=status.HTTP_200_OK)\n\n\nclass PageCount(APIView):\n\n serializer_class = PageCountSerializer\n DIV = 5\n\n def get(self, request, format=None, *args, **kwargs):\n\n category = kwargs['category']\n\n if category == \"getallblogs\":\n\n queryset = Blog.objects.all()[::-1]\n else:\n queryset = Blog.objects.filter(tag=category)[::-1]\n\n count = len(queryset) // self.DIV + 1\n\n return Response(data={\"count\": count}, status=status.HTTP_200_OK)\n\n\nclass BlogTwoList(APIView):\n\n serializer_class = BlogListSeriazlizer\n model = Blog\n\n def get(self, request, format=None):\n\n queryset = Blog.objects.all()[::-1]\n\n data = []\n\n for entry in queryset[:2]:\n\n data.append(self.serializer_class(entry).data)\n\n return Response(data={\"data\": data}, status=status.HTTP_200_OK)\n\n\nclass BlogDetailView(APIView):\n\n serializer_class = BlogDetailSerializer\n model = Blog\n\n def get(self, request, format=None, *args, **kwargs):\n\n slug = kwargs['slug']\n queryset = Blog.objects.filter(slug=slug)\n\n if not queryset.exists():\n return Response({\"Error\": \"Invalid Data\"},\n status=status.HTTP_400_BAD_REQUEST)\n\n blog = queryset[0]\n\n data = self.serializer_class(blog).data\n\n return Response(data=data, status=status.HTTP_200_OK)\n\n\nclass GetCategory(APIView):\n\n serializer_class = CategorySerializer\n\n def get(self, request, format=None):\n\n queryset = Blog.objects.all()[::-1]\n\n categories = {}\n\n for entry in queryset:\n\n categories[entry.tag] = categories.setdefault(entry.tag, 0) + 1\n\n return Response({\"categories\": list(categories.items())},\n status=status.HTTP_200_OK)\n","sub_path":"pavanastro/api/views/blog_views.py","file_name":"blog_views.py","file_ext":"py","file_size_in_byte":4131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"153350486","text":"from random import *\r\nimport time\r\nimport os\r\n\r\n\r\nclass Bee:\r\n _max_age = 10\r\n _max_weight = 10.0\r\n __gender = 'default'\r\n\r\n def __init__(self, bid, weight, age):\r\n self.weight = weight\r\n self.age = age\r\n self.bid = bid\r\n\r\n def eat_honey(self, honey):\r\n eat_size = self.weight / 5.0\r\n if honey < eat_size:\r\n return 'dead', honey\r\n else:\r\n if self.weight < self._max_weight:\r\n self.weight += eat_size\r\n self.weight = round(self.weight, 1)\r\n honey -= eat_size\r\n return self.__gender, honey\r\n else:\r\n self.weight = self._max_weight\r\n return self.__gender, honey\r\n\r\n def lvl_up(self):\r\n if self.age >= self._max_age:\r\n return 'dead'\r\n else:\r\n self.age += 1\r\n return 'life'\r\n\r\n def get_info(self):\r\n return f' id: {self.bid} weight: {self.weight} age: {self.age}'\r\n\r\n\r\nclass BeeF(Bee):\r\n __gender = 'female'\r\n\r\n def __init__(self, bid, weight, age):\r\n super().__init__(bid, weight, age)\r\n\r\n def new_egg(self):\r\n pass\r\n\r\n @staticmethod\r\n def get_eff(honey):\r\n return round(honey / 2.0)\r\n\r\n\r\nclass BeeM(Bee):\r\n __gender = 'male'\r\n __defEggs = 2\r\n\r\n def __init__(self, bid, weight, age):\r\n super().__init__(bid, weight, age)\r\n\r\n def new_egg(self):\r\n pass\r\n\r\n def get_eff(self):\r\n return randint(1, self.__defEggs)\r\n\r\n\r\nclass Baby:\r\n __bees = ['worker', 'male', 'worker', 'male']\r\n __future_bee = None\r\n\r\n __weight = 1.0\r\n __max_weight = 3.0\r\n __eat_size = 1.0\r\n __delay = 2\r\n\r\n def __init__(self):\r\n self.__future_bee = self.__bees[randint(0, 3)]\r\n pass\r\n\r\n def d_delay(self):\r\n self.__delay -= 1\r\n if self.__delay <= 0:\r\n return 'born'\r\n else:\r\n return 'embryo'\r\n\r\n def trans_to_bee(self):\r\n return self.__future_bee\r\n\r\n def eat_honey(self, honey):\r\n if honey < self.__eat_size:\r\n return 'dead', honey\r\n\r\n if self.__weight >= self.__max_weight:\r\n return self.trans_to_bee(), honey\r\n else:\r\n self.__weight += self.__eat_size\r\n honey -= self.__eat_size\r\n gender = self.d_delay()\r\n return gender, honey\r\n\r\n def get_info(self):\r\n return f' future bee: {self.__future_bee} weight: {self.__weight} delay: {self.__delay}'\r\n\r\n\r\nclass BeeW(Bee):\r\n __gender = 'worker'\r\n\r\n def __init__(self, bid, weight, age):\r\n super().__init__(bid, weight, age)\r\n\r\n def get_honey(self):\r\n return self.weight * randint(1, 4) / 5.5\r\n\r\n def clean_hive(self):\r\n pass\r\n\r\n\r\nclass Hive:\r\n __honey = 20.0\r\n __age = 0\r\n __state = 'life'\r\n\r\n mother_eggs = 0\r\n father_eggs = 0\r\n eggs = 0\r\n\r\n babies = []\r\n\r\n def __init__(self, bee_f, bees_m, bees_w):\r\n self.bee_f = bee_f\r\n self.bees_m = bees_m\r\n self.bees_w = bees_w\r\n\r\n def count_eggs(self):\r\n self.mother_eggs = BeeF.get_eff(self.__honey)\r\n fathers_eff = 0\r\n for bee in self.bees_m:\r\n fathers_eff += bee.get_eff()\r\n self.father_eggs = fathers_eff\r\n self.eggs = abs(self.mother_eggs - self.father_eggs)\r\n\r\n def print_info(self):\r\n mom_eff = BeeF.get_eff(self.__honey)\r\n fathers_eff = 0\r\n for bee in self.bees_m:\r\n fathers_eff += bee.get_eff()\r\n print()\r\n print(f' Hive age: {self.__age} Honey: {self.__honey}')\r\n print(f' Mother efficiency: {mom_eff} Father efficiency: {fathers_eff} Eggs: {self.eggs}')\r\n print()\r\n print(' Mother:')\r\n print(self.bee_f.get_info())\r\n print()\r\n print(' Fathers:')\r\n for bee in self.bees_m:\r\n print(bee.get_info())\r\n print()\r\n print(' Workers:')\r\n for bee in self.bees_w:\r\n print(bee.get_info())\r\n print()\r\n print(' Babies:')\r\n if self.babies != []:\r\n for baby in self.babies:\r\n print(baby.get_info())\r\n\r\n def i_age(self):\r\n self.__age += 1\r\n\r\n def gen_honey(self):\r\n for bee in self.bees_w:\r\n self.__honey += bee.get_honey()\r\n self.__honey = round(self.__honey, 1)\r\n\r\n def dead(self):\r\n self.__state = 'dead'\r\n\r\n def spent_honey(self, ids):\r\n for bee in self.bees_m:\r\n gender, honey = bee.eat_honey(self.__honey)\r\n self.__honey = honey\r\n if gender == 'dead':\r\n self.bees_m.remove(bee)\r\n for bee in self.bees_w:\r\n gender, honey = bee.eat_honey(self.__honey)\r\n self.__honey = honey\r\n if gender == 'dead':\r\n self.bees_w.remove(bee)\r\n\r\n if self.babies != []:\r\n for baby in self.babies:\r\n gender, honey = baby.eat_honey(self.__honey)\r\n self.__honey = honey\r\n if gender == 'dead':\r\n self.babies.remove(baby)\r\n if gender != 'dead':\r\n if gender == 'male':\r\n self.babies.remove(baby)\r\n self.bees_m.append(BeeM(ids[randint(20, 80)], randint(1, 3), randint(1, 3)))\r\n elif gender == 'worker':\r\n self.babies.remove(baby)\r\n self.bees_w.append(BeeW(ids[randint(20, 80)], randint(1, 3), randint(1, 3)))\r\n\r\n gender, honey = self.bee_f.eat_honey(self.__honey)\r\n\r\n if gender == 'dead':\r\n self.dead()\r\n self.__honey = round(self.__honey, 1)\r\n\r\n def lvl_up(self):\r\n for bee in self.bees_m:\r\n bee_state = bee.lvl_up()\r\n if bee_state == 'dead':\r\n self.bees_m.remove(bee)\r\n for bee in self.bees_w:\r\n bee_state = bee.lvl_up()\r\n if bee_state == 'dead':\r\n self.bees_w.remove(bee)\r\n\r\n def get_state(self):\r\n return self.__state, self.__age\r\n\r\n def spawn_babies(self):\r\n for i in range(self.eggs):\r\n self.babies.append(Baby())\r\n\r\n def balance(self):\r\n self.babies = self.babies[0:10]\r\n self.bees_w = self.bees_w[0:10]\r\n self.bees_m = self.bees_m[0:10]\r\n\r\n\r\ndef gen_ids():\r\n rand_chars = ['a', 'b', 'c', 'd', '1', '2', '3']\r\n ids = []\r\n for i in range(100):\r\n shuffle(rand_chars)\r\n ids.append(''.join(rand_chars))\r\n return ids\r\n\r\n\r\ndef dead(age):\r\n print('DDDDD EEEEE AAA DDDDD')\r\n print('D D E A A D D')\r\n print('D D EEEEE AAAAA D D')\r\n print('D D E A A D D')\r\n print('DDDDD EEEEE A A DDDDD')\r\n print()\r\n print(f' Hive age: {age} ')\r\n print()\r\n\r\n\r\ndef clear():\r\n if os.name == 'nt':\r\n os.system('cls')\r\n else:\r\n os.system('clear')\r\n\r\n\r\nids = gen_ids()\r\n\r\nhive = Hive(\r\n BeeF(ids[0], 5, 1),\r\n [\r\n BeeM(ids[1], 1, 1),\r\n BeeM(ids[2], 1, 3),\r\n BeeM(ids[3], 6, 4)\r\n ],\r\n [\r\n BeeW(ids[6], 1, 1),\r\n BeeW(ids[7], 2, 1),\r\n BeeW(ids[8], 3, 3),\r\n BeeW(ids[9], 1, 1),\r\n BeeW(ids[10], 2, 2),\r\n BeeW(ids[11], 3, 1),\r\n BeeW(ids[12], 2, 1),\r\n BeeW(ids[13], 4, 5),\r\n BeeW(ids[14], 5, 1),\r\n BeeW(ids[15], 1, 4),\r\n BeeW(ids[16], 2, 2)\r\n ]\r\n)\r\n\r\nnext_id = 20\r\n\r\nwhile True:\r\n clear()\r\n state = hive.get_state()\r\n if state[0] == 'dead':\r\n clear()\r\n dead(state[1])\r\n break\r\n hive.print_info()\r\n hive.gen_honey()\r\n hive.spent_honey(ids)\r\n hive.count_eggs()\r\n hive.spawn_babies()\r\n hive.balance()\r\n hive.lvl_up()\r\n hive.i_age()\r\n time.sleep(1)\r\n","sub_path":"beehive.py","file_name":"beehive.py","file_ext":"py","file_size_in_byte":7862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"492054074","text":"won = input()\ndollar = input()\n\ntry:\n print(int(won)/int(dollar))\nexcept ValueError as e:\n print('error',e)\nexcept ZeroDivisionError as e:\n print('error',e)\nexcept:\n print('fatal error')\nelse:\n print('예외가 발생하지 않았을 경우 출력')\nfinally:\n print('예외가 발생하던 발생하지 않던 출력')\n\nclass PositivenumError (Exception):\n def __init__(self):\n super().__init__('Please input num < 0')\n\ntry:\n num = input()\n if int(num) >= 0:\n raise PositivenumError\nexcept Exception as e:\n print(e)","sub_path":"Python_basic/4.try_exepcion.py","file_name":"4.try_exepcion.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"201943645","text":"class TreeNode:\n def __init__(self,val):\n self.val=val\n self.left=None\n self.right=None\n \ndef str2tree(s):\n \"\"\"\n :type s: str\n :rtype: TreeNode\n \"\"\"\n if not s:\n return\n stack = []\n num = \"\"\n for i in range(len(s)):\n if s[i].isdigit() or s[i] == \"-\":\n num += s[i] \n elif s[i] == \"(\":\n if num:\n node = TreeNode(int(num))\n if stack:\n if not stack[-1].left:\n stack[-1].left = node\n else:\n stack[-1].right = node\n stack.append(node)\n else:\n root = node\n stack.append(node)\n num = \"\"\n else: # s[i] == \")\"\n if num:\n node = TreeNode(int(num))\n if not stack[-1].left:\n stack[-1].left = node\n else:\n stack[-1].right = node\n num = \"\"\n else:\n stack.pop()\n return root if not num else TreeNode(int(num))\n\nif __name__ == '__main__':\n # time: O(n)\n x=str2tree(\"-4(2(3)(1))(6(5)(7))\")\n print(x.val)\n print(x.left.val)\n print(x.right.val)","sub_path":"binary_trees/str_2_tree.py","file_name":"str_2_tree.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"343355758","text":"import asyncio\nimport datetime\nfrom discord.ext import commands\nimport discord\nimport platform\n\nif not discord.opus.is_loaded():\n discord.opus.load_opus('opus')\n\ntry:\n import uvloop\nexcept ImportError:\n uvloop = None\nelse:\n asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())\n\n\ntoken = 'YOUR-TOKEN-HERE'\n\ndescription = '''A discord.py bot for useful and almost useful things!'''\n\nstartup_extensions = ['module.commands', 'module.voice', 'module.pokemon', 'module.overwatch', 'module.admin']\n\nhelp_attrs = dict(hidden=True)\n\nbot = commands.Bot(command_prefix='!', description=description, help_attrs=help_attrs)\n\n\n@bot.event\nasync def on_ready():\n print('------')\n print('Logged in as: ' + bot.user.name)\n print('BOT ID: ' + bot.user.id)\n print('Description: ' + description)\n print('Python Version: ' + platform.python_version())\n print('------')\n if not hasattr(bot, 'uptime'):\n bot.uptime = datetime.datetime.utcnow()\n\n\n# Notify if we cannot load a module at startup\nif __name__ == \"__main__\":\n for extension in startup_extensions:\n try:\n bot.load_extension(extension)\n except Exception as e:\n exc = '{}: {}'.format(type(e).__name__, e)\n print('Failed to load extension {}\\n{}'.format(extension, exc))\n\n\nbot.run(token)\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"523762299","text":"from pandas import DataFrame\n\n\nclass StatementFact:\n\n def __init__(self, account_name, value, group, sector, sj_div):\n self.account_name = account_name\n self.value = value\n self.group = group\n self.sector = sector\n self.sj_div = sj_div\n\n def __str__(self):\n return 'account: {self.account_name}, ' \\\n 'value: {self.value}, ' \\\n 'group: {self.group}, ' \\\n 'sector: {self.sector}, ' \\\n 'sj_div: {self.sj_div}, ' \\\n .format(self=self)\n\n\nclass Statement:\n\n def __init__(self,\n stock_code: str,\n fiscal_date: str,\n report_code: str = None,\n consensus: int = 0,\n fs_div: str = None):\n\n self.stock_code = stock_code\n self.fiscal_date = fiscal_date\n self.report_code = report_code\n self.consensus = consensus\n self.fs_div = fs_div\n self.facts = []\n self.fact_lookup = {}\n\n @staticmethod\n def create(stock_code: str,\n fiscal_date: str,\n consensus: int = 0,\n report_code: int = None,\n fs_div: str = None):\n \"\"\"\n 재무제표 자료 생성\n :param stock_code: 종목코드\n :param fiscal_date: 회계일자\n :param consensus: 컨센서트 여부 - 0: 컨센아님, 1: 컨센, 2: 잠정실적\n :param report_code: 보고서 구분, 연간: 1, 분기: 2\n :param fs_div: 재무제표 연결/별도 구분, CFS: 연결: OFS: 별도\n :return:\n Statement object\n \"\"\"\n\n statement = Statement(stock_code, fiscal_date, report_code, consensus, fs_div)\n\n return statement\n\n def __str__(self):\n facts = [fact.__str__() for fact in self.facts]\n\n string_value = 'Statement: stock_code: {self.stock_code}, fiscal_date: {self.fiscal_date}, ' \\\n 'consensus: {self.consensus}, ' \\\n 'report_code: {self.report_code}, ' \\\n 'fs_div: {self.fs_div}, ' \\\n .format(self=self)\n\n return string_value + 'facts[ ' + ','.join(facts) + ']'\n\n def append_facts(self, accounts, values, group, sector, sj_div):\n \"\"\"\n 계정과목과 값을 추가한다.\n :param accounts: 계정과목 List\n :param values: 값 List\n :param group: 섹터내 자료구분\n :param sector: 섹터명\n :param sj_div: 재무재표 종류 - BS: 재무상태표, IS: 손익계산서, CF: 현금흐름표, SM: FnGuide 요약\n :return:\n \"\"\"\n\n for i in range(len(accounts)):\n fact = StatementFact(accounts[i], values[i], group, sector, sj_div)\n self.fact_lookup[accounts[i]] = fact\n self.facts.append(fact)\n\n def get_fact(self, account_id) -> StatementFact:\n return self.fact_lookup.get(account_id, None)\n\n def to_dataframe(self):\n df = DataFrame()\n df['account_id'] = [fact.account_name for fact in self.facts]\n df['stock_code'] = self.stock_code\n df['fiscal_date'] = self.fiscal_date\n\n df = df[['stock_code', 'fiscal_date', 'account_id']]\n df['value'] = [fact.value for fact in self.facts]\n df['attribute'] = [fact.group for fact in self.facts]\n df['sector'] = [fact.sector for fact in self.facts]\n df['report_code'] = self.report_code\n df['fs_div'] = self.fs_div\n df['sj_div'] = [fact.sj_div for fact in self.facts]\n df['consensus'] = self.consensus\n\n return df\n\n def from_dataframe(self):\n pass\n\n\nclass StockSummary:\n\n def __init__(self, stock_code):\n self.stock_code = stock_code\n self.reference_date = None\n self.common_stock_cnt = 0\n self.pref_stock_cnt = 0\n self.treasury_stock_cnt = 0\n\n def __str__(self):\n string_value = 'StockSummary [stock_code:' + self.stock_code \\\n + ', reference_date: ' + str(self.reference_date) \\\n + ', common_stock_cnt: ' + str(self.common_stock_cnt) \\\n + ', pref_stock_cnt: ' + str(self.pref_stock_cnt) \\\n + ', treasury_stock_cnt: ' + str(self.treasury_stock_cnt) \\\n + ']'\n\n return string_value\n\n def to_dict(self):\n return {'stock_code': self.stock_code,\n 'reference_date': self.reference_date,\n 'common_stock_cnt': self.common_stock_cnt,\n 'pref_stock_cnt': self.pref_stock_cnt,\n 'treasury_stock_cnt': self.treasury_stock_cnt}\n\n @staticmethod\n def from_dict(dic_data: dict):\n summary = StockSummary(dic_data.get('stock_code'))\n summary.common_stock_cnt = dic_data.get('common_stock_cnt')\n summary.pref_stock_cnt = dic_data.get('pref_stock_cnt')\n summary.treasury_stock_cnt = dic_data.get('treasury_stock_cnt')\n summary.reference_date = dic_data.get('reference_date')\n\n return summary\n","sub_path":"core/financial/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"478596966","text":"from irstructures.document import Document, read_corpus, calc_collection_frequency\r\nfrom irstructures.invertedindex import InvertedIndex\r\nimport irstructures.models.boolean_retrieval as boolean_retrieval\r\nimport irstructures.models.vector_space as vector_space\r\nimport os, time, pickle\r\nfrom pandas import read_pickle\r\n\r\ndef start_search(vsmodel, corpus, df, index):\r\n use_boolean = True\r\n while True:\r\n query = input(\"Enter query: \")\r\n if query == \"EXIT\":\r\n break\r\n else:\r\n if use_boolean:\r\n print(\"\\nBoolean Retrieval results: \")\r\n start = time.time()\r\n output = boolean_retrieval.parse_query(query, corpus, index)\r\n for fileid in output:\r\n print(corpus[fileid].filepath)\r\n end = time.time()\r\n print(len(output),\"files returned in\", end-start, 's')\r\n else:\r\n output = [i.doc_id for i in corpus]\r\n\r\n print(\"\\nTf-Idf results: \")\r\n start = time.time()\r\n output = vector_space.parse_query(query, corpus, vsmodel, df, output)\r\n for file, prob in output[:10]:\r\n print(file, \"\\t\", prob)\r\n end = time.time()\r\n print(\"returned in \", end-start, 's')\r\n \r\n print()\r\n\r\nif __name__=='__main__':\r\n\r\n print(\"\\n***Program started***\\n\")\r\n\r\n if(\"df.pickle\" in os.listdir(\"./pickle_files\")) and (\"corpus.pickle\" in os.listdir(\"./pickle_files\")) and (\"inv_index.pickle\" in os.listdir(\"./pickle_files\")):\r\n # folder name is corpus in this case\r\n\r\n # loading corpus\r\n start = time.time()\r\n with open(\"./pickle_files/corpus.pickle\", \"rb\") as corpus_file:\r\n corpus = pickle.load(corpus_file)\r\n end = time.time()\r\n print(\"corpus loaded in: \"+str(end - start)) \r\n \r\n # loading inverted index object\r\n start = time.time()\r\n with open(\"./pickle_files/inv_index.pickle\", \"rb\") as inv_index_file:\r\n index = pickle.load(inv_index_file)\r\n end = time.time()\r\n print(\"inverted index loaded in: \"+str(end - start)) \r\n\r\n # loading vectorspace object\r\n vsmodel = vector_space.Tf_Idf(inv_index=index)\r\n start = time.time()\r\n df = read_pickle('./pickle_files/df.pickle')\r\n end = time.time()\r\n print(\"dataframe pickle loaded in: \"+str(end - start)) \r\n\r\n \r\n else:\r\n print(\"reading files\")\r\n start = time.time()\r\n corpus = read_corpus('corpus')\r\n end = time.time()\r\n print(\"corpus generated in: \"+str(end - start))\r\n\r\n # saving corpus object\r\n with open(\"./pickle_files/corpus.pickle\", \"wb\") as corpus_file:\r\n pickle.dump(corpus, corpus_file)\r\n\r\n collection_freq = calc_collection_frequency(corpus)\r\n\r\n print(\"Building inverted index\")\r\n start = time.time()\r\n index = InvertedIndex(corpus)\r\n end = time.time()\r\n print(\"inverted index generated in: \"+str(end - start))\r\n # saving inverted index object\r\n with open(\"./pickle_files/inv_index.pickle\", \"wb\") as inv_index_file:\r\n pickle.dump(index, inv_index_file)\r\n\r\n print(\"Building vector space model\")\r\n start = time.time()\r\n vsmodel = vector_space.Tf_Idf(inv_index=index)\r\n # saving tf idf dataframe object\r\n df = vsmodel.get_dataframe(corpus, collection_freq)\r\n df.to_pickle('./pickle_files/df.pickle')\r\n end = time.time()\r\n\r\n\r\n print(\"vector space model built in: \"+str(end - start))\r\n\r\n print('Size of dataframe: ', df.shape[0], 'tokens X', df.shape[1], 'docs')\r\n start_search(vsmodel, corpus, df, index)\r\n \r\n print(\"\\n***End of program***\\n\")","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"351125685","text":"import pygame\nimport math\nimport rendering as r\nfrom typing import Tuple\n\nimport Colors as c\n\nColor = Tuple[int, int, int]\nPoint = Tuple[int, int]\n\n\ndef startScreen(dispSurf: pygame.Surface, font: pygame.font.Font, winWidth: int, winHeight: int, deg1: int, deg2: int) -> None:\n titleFont = pygame.font.Font('freesansbold.ttf', 65)\n titleSurf1 = titleFont.render('Roomba', True, c.FIREBRICK, c.KHAKI)\n titleSurf2 = titleFont.render('Roomba', True, c.DARK_SLATE_GRAY)\n\n rotatedSurf1 = pygame.transform.rotate(titleSurf1, deg1)\n rotatedRect1 = rotatedSurf1.get_rect()\n rotatedRect1.center = (math.floor(winWidth / 2), math.floor(winHeight / 2))\n dispSurf.blit(rotatedSurf1, rotatedRect1)\n\n rotatedSurf2 = pygame.transform.rotate(titleSurf2, deg2)\n rotatedRect2 = rotatedSurf2.get_rect()\n rotatedRect2.center = (math.floor(winWidth / 2), math.floor(winHeight / 2))\n dispSurf.blit(rotatedSurf2, rotatedRect2)\n\n pressKeyMsg(dispSurf, font, winWidth, winHeight)\n\n\ndef score(score: int, n: int, font: pygame.font.Font, winWidth: int) -> None:\n scoreSurf = font.render(f'Roomba {n}: {score}', True, c.BLACK)\n scoreRect = scoreSurf.get_rect()\n scoreRect.topleft = (winWidth - 160, 20 * n)\n r.screen.blit(scoreSurf, scoreRect)\n\n\ndef text(msg: str, font: pygame.font.Font, topLeft: Point) -> None:\n msgSurf = font.render(msg, True, c.BLACK)\n msgRect = msgSurf.get_rect()\n msgRect.topleft = topLeft\n r.screen.blit(msgSurf, msgRect)\n\n\ndef fill(color: Color):\n r.screen.fill(color)\n\n\ndef circle(center: Point, radius: int, color: Color = c.RED) -> None:\n pygame.draw.circle(r.screen, color, center, radius)\n\n\n\ndef grid(dispSurf: pygame.Surface, size: int, winWidth: int, winHeight: int) -> None:\n for x in range(0, winWidth, size): # draw vertical lines\n pygame.draw.line(dispSurf, c.DIM_GRAY, (x, 0), (x, winHeight))\n for y in range(0, winHeight, size): # draw horizontal lines\n pygame.draw.line(dispSurf, c.DIM_GRAY, (0, y), (winWidth, y))\n\n\ndef pressKeyMsg(dispSurf: pygame.Surface, font: pygame.font.Font, winWidth: int, winHeight: int) -> None:\n pressKeySurf = font.render('Press a key to play.', True, c.STEEL_BLUE)\n pressKeyRect = pressKeySurf.get_rect()\n pressKeyRect.topleft = (winWidth - 200, winHeight - 30)\n dispSurf.blit(pressKeySurf, pressKeyRect)\n\n\ndef gameOver(dispSurf: pygame.Surface, font: pygame.font.Font, winWidth: int, winHeight: int) -> None:\n gameSurf = font.render('Game', True, c.WHITE)\n overSurf = font.render('Over', True, c.WHITE)\n gameRect = gameSurf.get_rect()\n overRect = overSurf.get_rect()\n gameRect.midtop = (math.floor(winWidth / 2), 10)\n overRect.midtop = (math.floor(winWidth / 2), gameRect.height + 10 + 25)\n\n dispSurf.blit(gameSurf, gameRect)\n dispSurf.blit(overSurf, overRect)\n","sub_path":"CS6110_MultiAgentSystems/project/Draw.py","file_name":"Draw.py","file_ext":"py","file_size_in_byte":2826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"295773407","text":"# -*- coding: utf-8 -*-\nimport datetime, time, re\nfrom gmun_tests import GmunTest\nfrom gmun_tests.utils.mattermost import Mattermost, channel_test_fails, channel_town_square, channel_no_alert\nfrom time import sleep\nfrom contextlib import suppress\nimport random\n\nsilent = False\n\n\nclass Sender_Statuses(GmunTest):\n def __init__(self):\n self.name = 'Sender_Statuses'\n self.mattermost = Mattermost()\n GmunTest.__init__(self, name=self.name, no_driver=True)\n self.silent = silent or True\n self.wait = 60\n\n def test(self):\n msg = \"@ss8545 test\"\n self.mattermost.create_post(channel_test_fails, msg)\n\n\n\n\nif __name__ == '__main__':\n print(\"started at \", time.strftime('%H:%M:%S').replace(\"'\", \"\"))\n try:\n test_obj = Sender_Statuses().test()\n except Exception as e:\n print(f\"ошибка выполнения __name__ = __main__, {e}\")\n\n\n","sub_path":"gmun_tests/tests_alert/nitifications_test_mmt.py","file_name":"nitifications_test_mmt.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"102746131","text":"import eHive\nimport subprocess\nimport os\nimport sys\nimport random\nimport string\n\nclass VcfConcat(eHive.BaseRunnable):\n \"\"\"Concat each of the VCF chunks into a single VCf\"\"\"\n \n def random_generator(self, size=6, chars=string.ascii_uppercase + string.digits):\n return ''.join(random.choice(chars) for x in range(size))\n \n def run(self):\n all_ixs = self.param_required('allixs')\n all_files = self.param_required('allchunks_files')\n\n d = dict(zip(all_ixs, all_files))\n\n \"\"\"Create tmp file for files to concat\"\"\"\n concat_file=\"%s/concat%s.txt\"% (self.param_required('work_dir'),self.random_generator())\n\n f=open(concat_file,'w');\n for ix in sorted(d):\n f.write(d[ix]+\"\\n\")\n f.close() \n\n command=\"{0}/bcftools concat -f {1} \".format(self.param_required('bcftools_folder'),concat_file)\n command= command+\"-o {0} -O z\".format(self.param_required('outprefix'))\n\n if self.param('verbose')==\"True\":\n self.warning(\"Merging chunks\")\n self.warning(\"Command used to merge chunks: %s\" % command)\n \n try:\n subprocess.check_output(command,shell=True)\n except subprocess.CalledProcessError as e:\n self.warning(\"Something went wrong while merging the chunks\")\n print(e.output)\n sys.exit(0)\n\n os.remove(concat_file)\n\n if self.param('verbose')==\"True\":\n self.warning(\"Merging the chunks: DONE\")\n\n def write_output(self):\n self.warning('Work is done!')\n self.dataflow( { 'merged_file' : self.param('outprefix') }, 1)\n\n\n\n\n","sub_path":"VARIANT_CALLING/PyHive/Vcf/VcfConcat.py","file_name":"VcfConcat.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"491972014","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\nfrom Bio.Seq import Seq\nfrom Bio.Alphabet import IUPAC\nfrom Bio.SeqRecord import SeqRecord\n\nfrom iss import download\n\n\ndef test_to_fasta():\n ref_genome = SeqRecord(\n Seq(str('ATATA' * 100),\n IUPAC.unambiguous_dna\n ),\n id='ref_genome',\n description='test reference'\n )\n genome_list = [ref_genome, ref_genome]\n download.to_fasta(genome_list, 'test_genomes.fasta')\n\n\ndef test_ncbi():\n genome_list = download.ncbi('bacteria', 2)\n assert len(genome_list) == 2\n","sub_path":"iss/test/test_download.py","file_name":"test_download.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"457129702","text":"import numpy as np\nfrom sklearn.decomposition import PCA\nimport imp\nimport matplotlib.pyplot as plt\n\ndata=np.load('../data/processed_data.npz')\npids=data['pids']\nX=data['X']\nX_sym=data['X_sym']\nY=data['Y']\nZ=data['Z']\n\nx_train=X[0:120,:,0]\nx_test=X[120:,:,0]\n\ny_train=Y[0:120,:]\n\nn_comp=list(range(1,120,5))\nloss_array_train=[0]*len(n_comp)\nloss_array_test=[0]*len(n_comp)\nenergy = [0]*len(n_comp)\ncount=0\nfor i in n_comp:\n\tpca_train = PCA(n_components=i)\n\tx_pc_train = pca_train.fit_transform(x_train)\n\tenergy[count] = np.sum(pca_train.explained_variance_ratio_)\n\tx_projected_train = pca_train.inverse_transform(x_pc_train)\n\tloss_train=((x_train - x_projected_train) ** 2).mean()\n\tloss_array_train[count]=loss_train\n\t#=================================================\n\tx_pc_test = pca_train.transform(x_test)\n\tx_projected_test = pca_train.inverse_transform(x_pc_test)\n\tloss_test=((x_test - x_projected_test) ** 2).mean()\n\tloss_array_test[count]=loss_test\n\tcount=count+1\nplt.figure()\nline1, =plt.plot(n_comp,loss_array_train, c='red', linewidth=2)\nline2, =plt.plot(n_comp,loss_array_test, c='blue', linewidth=2)\nplt.xlabel('# Dimensions')\nplt.ylabel('Mean Squared Error')\nplt.legend((line1, line2), ('Training Set', 'Test Set'))\nplt.savefig('./output/pca_error.pdf')\nplt.figure()\nplt.plot(n_comp,energy)\nplt.savefig('./output/pca_energy.pdf')\nprint(n_comp)\nprint(energy)\n","sub_path":"pca_eigenvalue.py","file_name":"pca_eigenvalue.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"383058986","text":"import pandas as pd\nimport operator\n\ninputs = [ # Esse input vai ser dado pelo usuário, apenas um caso teste\n 1.0,\n 1.0,\n 1.0,\n 0.5,\n 0.5,\n 0.5,\n 2.0,\n 2.0,\n 1.0,\n 0.25,\n 1.0,\n 2.0,\n 1.0,\n 1.0,\n 2.0,\n 1.0,\n 1.0,\n 0.5,\n]\n\nagainst = [\n \"against_bug\",\n \"against_dark\",\n \"against_dragon\",\n \"against_electric\",\n \"against_fairy\",\n \"against_fight\",\n \"against_fire\",\n \"against_flying\",\n \"against_ghost\",\n \"against_grass\",\n \"against_ground\",\n \"against_ice\",\n \"against_normal\",\n \"against_poison\",\n \"against_psychic\",\n \"against_rock\",\n \"against_steel\",\n \"against_water\",\n]\n\ndf = pd.read_csv(\"pokemon.csv\")\ntype_frequency = df.type1.value_counts()\n\ndf_class = {\n \"water\": type_frequency[0],\n \"normal\": type_frequency[1],\n \"grass\": type_frequency[2],\n \"bug\": type_frequency[3],\n \"psychic\": type_frequency[4],\n \"fire\": type_frequency[5],\n \"rock\": type_frequency[6],\n \"electric\": type_frequency[7],\n \"ground\": type_frequency[8],\n \"poison\": type_frequency[9],\n \"dark\": type_frequency[10],\n \"fighting\": type_frequency[11],\n \"dragon\": type_frequency[12],\n \"ghost\": type_frequency[13],\n \"steel\": type_frequency[14],\n \"ice\": type_frequency[15],\n \"fairy\": type_frequency[16],\n \"flying\": type_frequency[17],\n}\n\nhash_change_value = {\n \"against_bug\": \"bug\",\n \"against_dark\": \"dark\",\n \"against_dragon\": \"dragon\",\n \"against_electric\": \"electric\",\n \"against_fairy\": \"fairy\",\n \"against_fight\": \"fight\",\n \"against_fire\": \"fire\",\n \"against_flying\": \"flying\",\n \"against_ghost\": \"ghost\",\n \"against_grass\": \"grass\",\n \"against_ground\": \"ground\",\n \"against_ice\": \"ice\",\n \"against_normal\": \"normal\",\n \"against_poison\": \"poison\",\n \"against_psychic\": \"psychic\",\n \"against_rock\": \"rock\",\n \"against_steel\": \"steel\",\n \"against_water\": \"water\",\n}\n\n\ndef class_probability(_class):\n return df_class[_class] / len(df)\n\n\ndef probability_elem(feature, value, class_value, p_class, m):\n n = len(df[df[feature] == value])\n n_c = len(df[(df.type1 == class_value) & (df[feature] == value)])\n return (n_c + (p_class * m)) / (m + n)\n # print(df[df[feature] == value])\n\n\ninfo = hash_change_value[against[0]]\n# print(df_class[info])\nprint(probability_elem(against[0], inputs[0], info, class_probability(info), m=5))\n\"\"\"\nprobability = {}\nfor key, item in df_class.items():\n prob = []\n # item = size of the class\n for i in range(len(inputs)):\n # print('------------' * 5)\n # print(df[against[i]])\n new_df = df[(df.type1 == key) & (df[against[i]] == inputs[i])]\n value1 = len(new_df)\n # print(f'{key} -> {item} = {value1}')\n prob.append(value1 / item)\n\n aux = probability_class[key]\n for i in prob:\n aux *= i\n probability[key] = aux\n\nprint(probability)\nsorted_d = dict(sorted(probability.items(), key=operator.itemgetter(0)))\nprint(sorted_d)\nresult = list(sorted_d.keys())[0]\nprint(probability[result])\nfinal_prob = (probability[result] / sum(probability.values())) * 100\nprint(f\"Probabilidade de {final_prob} de ser {result}\")\n\n# value1 = len(new_df)\n# value2 = df_class[\"water\"]\n# print(f\"probability = {value1 / value2}\")\n\"\"\"\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"365993980","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom itertools import combinations\n\n\ndef part1(values: list, tot: int) -> int:\n for v1, v2 in combinations(values, 2):\n if v1 + v2 == tot:\n return v1 * v2\n\n\ndef part2(values: list, tot: int) -> int:\n for v1, v2, v3 in combinations(values, 3):\n if v1 + v2 + v3 == tot:\n return v1 * v2 * v3\n\n\nif __name__ == '__main__':\n with open('input.txt') as f:\n values = [ int(x) for x in f ]\n print(part1(values, 2020)) # 805731\n print(part2(values, 2020)) # 192684960\n","sub_path":"2020/day_01/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"311740065","text":"import os\nimport pandas as pd\nfrom base import BaseFeature\nfrom encoding_func import target_encoding\nfrom google.cloud import storage, bigquery\nfrom google.cloud import bigquery_storage_v1beta1\n\n\nclass TargetEncodingHashtags(BaseFeature):\n def import_columns(self):\n return [\n \"tweet_id\",\n \"engaging_user_id\"\n ]\n\n def _read_inter_table_from_bigquery(\n self, table_name: str) -> pd.DataFrame:\n self._logger.info(f\"Reading from {table_name}\")\n query = \"\"\"\n WITH subset AS (\n SELECT\n tweet_id,\n engaging_user_id,\n any_value(hashtags) AS hashtags,\n any_value(reply_engagement_timestamp) AS reply_engagement_timestamp,\n any_value(retweet_engagement_timestamp) AS retweet_engagement_timestamp,\n any_value(retweet_with_comment_engagement_timestamp) AS retweet_with_comment_engagement_timestamp,\n any_value(like_engagement_timestamp) AS like_engagement_timestamp,\n FROM {}\n GROUP BY tweet_id, engaging_user_id\n )\n , unnest_subset AS (\n SELECT\n tweet_id,\n engaging_user_id,\n hashtag,\n reply_engagement_timestamp,\n retweet_engagement_timestamp,\n retweet_with_comment_engagement_timestamp,\n like_engagement_timestamp\n FROM subset,\n unnest(hashtags) AS hashtag\n )\n , use_combination AS (\n SELECT hashtag, engaging_user_id, COUNT(*) AS cnt\n FROM unnest_subset\n GROUP BY hashtag, engaging_user_id\n HAVING COUNT(*) >= 1\n )\n SELECT\n unnest_subset.tweet_id,\n unnest_subset.engaging_user_id,\n unnest_subset.hashtag,\n CASE WHEN unnest_subset.reply_engagement_timestamp IS NULL THEN 0 ELSE 1 END AS reply_engagement,\n CASE WHEN unnest_subset.retweet_engagement_timestamp IS NULL THEN 0 ELSE 1 END AS retweet_engagement,\n CASE WHEN unnest_subset.retweet_with_comment_engagement_timestamp IS NULL THEN 0 ELSE 1 END AS retweet_with_comment_engagement,\n CASE WHEN unnest_subset.like_engagement_timestamp IS NULL THEN 0 ELSE 1 END AS like_engagement,\n FROM\n unnest_subset\n INNER JOIN\n use_combination\n ON unnest_subset.hashtag = use_combination.hashtag\n AND unnest_subset.engaging_user_id = use_combination.engaging_user_id\n \"\"\".format(table_name)\n if self.debugging:\n query += \" limit 10000\"\n\n bqclient = bigquery.Client(project=self.PROJECT_ID)\n bqstorageclient = bigquery_storage_v1beta1.BigQueryStorageClient()\n df = (\n bqclient.query(query)\n .result()\n .to_dataframe(bqstorage_client=bqstorageclient)\n )\n return df\n\n def make_features(self, df_train_input, df_test_input):\n train_data = self._read_inter_table_from_bigquery(self.train_table)\n test_data = self._read_inter_table_from_bigquery(self.test_table)\n\n train_data[\"engaging_user_id__hashtag\"] = train_data[\"engaging_user_id\"] + \"_\" + train_data[\"hashtag\"]\n test_data[\"engaging_user_id__hashtag\"] = test_data[\"engaging_user_id\"] + \"_\" + test_data[\"hashtag\"]\n\n df_train_features = pd.DataFrame()\n df_test_features = pd.DataFrame()\n\n folds_train = self._download_from_gs(\n feather_file_name=\"StratifiedGroupKFold_training.ftr\"\n )\n\n target_columns = [\n \"reply_engagement\",\n \"retweet_engagement\",\n \"retweet_with_comment_engagement\",\n \"like_engagement\",\n ]\n\n category_column = \"engaging_user_id__hashtag\"\n target_encoding_column = f\"{category_column}_ta\"\n\n for target_col in target_columns:\n print(f'============= {target_col} =============')\n\n # Get folds\n folds_col = [\"StratifiedGroupKFold_retweet_with_comment_engagement\"]\n assert len(folds_col) == 1, \"The number of fold column must be one\"\n folds = folds_train[folds_col]\n n_fold = folds.max().values[0] + 1\n folds_ids = []\n folds_tweet_ids = []\n\n for i in range(n_fold):\n trn_idx = folds[folds != i].dropna().index\n val_idx = folds[folds == i].dropna().index\n folds_ids.append((trn_idx, val_idx))\n print(f\"{i+1}fold: n_trn={len(trn_idx)}, n_val={len(val_idx)}\")\n\n trn_tweet_id = df_train_input.iloc[trn_idx][\"tweet_id\"].unique()\n val_tweet_id = df_train_input.iloc[val_idx][\"tweet_id\"].unique()\n print(f\"{i+1}fold: n_tweet_trn={len(trn_tweet_id)}, n_tweet_val={len(val_tweet_id)}\")\n\n trn_tweet_idx = train_data.loc[train_data[\"tweet_id\"].isin(trn_tweet_id)].index\n val_tweet_idx = train_data.loc[train_data[\"tweet_id\"].isin(val_tweet_id)].index\n folds_tweet_ids.append((trn_tweet_idx, val_tweet_idx))\n print(f\"{i+1}fold: n_tweet_trn={len(trn_tweet_idx)}, n_tweet_trn={len(val_tweet_idx)}\")\n\n _, _ = target_encoding(\n category_column, train_data, test_data, target_col, folds_tweet_ids)\n\n train_agg = train_data.groupby([\"tweet_id\", \"engaging_user_id\"])[target_encoding_column].agg([\"min\", \"max\", \"mean\"]).reset_index()\n test_agg = test_data.groupby([\"tweet_id\", \"engaging_user_id\"])[target_encoding_column].agg([\"min\", \"max\", \"mean\"]).reset_index()\n train_data.drop(columns=[target_encoding_column], inplace=True)\n test_data.drop(columns=[target_encoding_column], inplace=True)\n feature_names = ['min', 'max', 'mean']\n\n for fe in feature_names:\n df_train_features[f\"{target_col}_{fe}\"] = pd.merge(df_train_input, train_agg, on=[\"tweet_id\", \"engaging_user_id\"], how=\"left\")[fe].values\n df_test_features[f\"{target_col}_{fe}\"] = pd.merge(df_test_input, test_agg, on=[\"tweet_id\", \"engaging_user_id\"], how=\"left\")[fe].values\n\n print(df_train_features.isnull().sum())\n print(df_test_features.isnull().sum())\n\n return df_train_features, df_test_features\n\n\nif __name__ == \"__main__\":\n TargetEncodingHashtags.main()\n","sub_path":"features/target_encoding_hashtags.py","file_name":"target_encoding_hashtags.py","file_ext":"py","file_size_in_byte":6715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"437787381","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n###############################################################################\n# Copyright 2014 Kitware Inc.\n#\n# Licensed under the Apache License, Version 2.0 ( the \"License\" );\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n###############################################################################\n\nimport argparse\nimport boto\nimport errno\nimport logging\nimport os\nimport socket\nimport threading\nimport time\n\nimport moto.server\nimport moto.s3\nfrom girder.utility.s3_assetstore_adapter import makeBotoConnectParams, \\\n botoConnectS3, S3AssetstoreAdapter\nfrom six.moves import range\n\n_startPort = 31100\n_maxTries = 100\n\n\ndef createBucket(botoConnect, bucketName):\n \"\"\"\n Create a bucket if it doesn't already exist.\n :param botoConnect: connection parameters to pass to use with boto.\n :type botoConnect: dict\n :param bucketName: the bucket name\n :type bucket: str\n :returns: a boto bucket.\n \"\"\"\n conn = botoConnectS3(botoConnect)\n bucket = conn.lookup(bucket_name=bucketName, validate=True)\n # if found, return\n if bucket is not None:\n return\n bucket = conn.create_bucket(bucketName)\n # I would have preferred to set the CORS for the bucket we created, but\n # moto doesn't support that.\n # setBucketCors(bucket)\n return bucket\n\n\ndef setBucketCors(bucket):\n \"\"\"\n Set the cors access values on a boto bucket to allow general access to that\n bucket.\n :param bucket: a boto bucket to set.\n \"\"\"\n cors = boto.s3.cors.CORSConfiguration()\n cors.add_rule(\n id='girder_cors_rule',\n allowed_method=['HEAD', 'GET', 'PUT', 'POST', 'DELETE'],\n allowed_origin=['*'],\n allowed_header=['Content-Disposition', 'Content-Type',\n 'x-amz-meta-authorized-length', 'x-amz-acl',\n 'x-amz-meta-uploader-ip', 'x-amz-meta-uploader-id'],\n expose_header=['ETag'],\n max_age_seconds=3000\n )\n bucket.set_cors(cors)\n\n\ndef startMockS3Server():\n \"\"\"\n Start a server using the defaults and adding a configuration parameter to\n the system so that the s3 assetstore handler will know to use this\n server. Attempt to bind to any port within the range specified by\n _startPort and _maxTries. Bias it with the pid of the current process so\n as to reduce potential conflicts with parallel tests that are started\n nearly simultaneously.\n\n :returns: the started server.\n \"\"\"\n # Reduce the chunk size to allow faster testing.\n S3AssetstoreAdapter.CHUNK_LEN = 1024 * 256\n moto.s3.models.UPLOAD_PART_MIN_SIZE = 1024 * 256\n # turn off logging from the S3 server unless we've asked to keep it\n if 'mocks3' not in os.environ.get('EXTRADEBUG', '').split():\n logging.getLogger('werkzeug').setLevel(logging.CRITICAL)\n selectedPort = None\n for porttry in range(_maxTries):\n port = _startPort + ((porttry + os.getpid()) % _maxTries)\n test_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n test_socket.bind(('0.0.0.0', port))\n selectedPort = port\n except socket.error as err:\n # Allow address in use errors to fail quietly\n if err.errno != errno.EADDRINUSE:\n raise\n test_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n test_socket.close()\n if selectedPort is not None:\n break\n server = MockS3Server(selectedPort)\n server.start()\n # add a bucket named 'bucketname' to simplify testing\n createBucket(server.botoConnect, 'bucketname')\n return server\n\n\nclass MockS3Server(threading.Thread):\n def __init__(self, port=_startPort):\n threading.Thread.__init__(self)\n self.port = port\n self.daemon = True\n self.service = 'http://127.0.0.1:%d' % port\n self.botoConnect = makeBotoConnectParams('abc', '123', self.service)\n\n def run(self):\n \"\"\"Start and run the mock S3 server.\"\"\"\n app = moto.server.DomainDispatcherApplication(_create_app,\n service='s3bucket_path')\n moto.server.run_simple('0.0.0.0', self.port, app, threaded=True)\n\n\ndef _create_app(service):\n \"\"\"\n Create the S3 server using moto, altering the responses to allow CORS\n requests.\n :param service: the amazon service we wish to mimic. This should probably\n be 's3bucket_path'.\n \"\"\"\n app = moto.server.create_backend_app(service)\n\n # I would have preferred to set the CORS for the bucket we have, but moto\n # doesn't support that, so I have to add the values here.\n @app.after_request\n def after_request(response):\n response.headers.add('Access-Control-Allow-Origin', '*')\n response.headers.add('Access-Control-Allow-Methods',\n 'HEAD, GET, PUT, POST, OPTIONS, DELETE')\n response.headers.add(\n 'Access-Control-Allow-Headers',\n 'Content-Disposition,Content-Type,'\n 'x-amz-meta-authorized-length,x-amz-acl,x-amz-meta-uploader-ip,'\n 'x-amz-meta-uploader-id'\n )\n response.headers.add('Access-Control-Expose-Headers', 'ETag')\n return response\n\n return app\n\n\nif __name__ == '__main__':\n \"\"\"\n Provide a simple stand-alone program so that developers can run Girder with\n a modified conf file to simulate an S3 store.\n \"\"\"\n parser = argparse.ArgumentParser(\n description='Run a mock S3 server. All data will be lost when it is '\n 'stopped.')\n parser.add_argument('-p', '--port', type=int, help='The port to run on',\n default=_startPort)\n parser.add_argument('-b', '--bucket', type=str,\n help='The name of a bucket to create', default='')\n parser.add_argument('-v', '--verbose', action='count',\n help='Increase verbosity.', default=0)\n args = parser.parse_args()\n server = MockS3Server(args.port)\n server.start()\n if args.bucket:\n createBucket(server.botoConnect, args.bucket)\n while True:\n time.sleep(10000)\n","sub_path":"tests/mock_s3.py","file_name":"mock_s3.py","file_ext":"py","file_size_in_byte":6611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"589022422","text":"import webapp2\n\nimport book\nimport render\n\nfrom google.appengine.api import users\n\n\nclass MainPage(webapp2.RequestHandler):\n def get(self):\n user = users.get_current_user()\n\n if user:\n self.response.headers['Content-Type'] = 'text/html'\n volume_id = self.request.get('id')\n if volume_id is not None:\n b = book.Book(volume_id)\n b.fetch()\n self.response.out.write(render.full_book(user, b))\n else:\n self.redirect(users.create_login_url(self.request.uri))\n\n\nclass SearchPage(webapp2.RequestHandler):\n def get(self):\n user = users.get_current_user()\n\n if user:\n self.response.headers['Content-Type'] = 'text/html'\n query = self.request.get('query')\n results = None\n if query is not None and len(query) > 0:\n results = book.search(query)\n self.response.out.write(render.full_search(user, query, results))\n else:\n self.redirect(users.create_login_url(self.request.uri))\n\n\napp = webapp2.WSGIApplication([('/volume', MainPage),\n ('/', SearchPage)],\n debug=True)\n","sub_path":"booktropes.py","file_name":"booktropes.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"365481983","text":"from time import time\nfrom django.db import settings\nfrom random import random\n\ntry:\n MULTI_CACHE_ENABLED = settings.MULTI_CACHE_ENABLED\nexcept:\n MULTI_CACHE_ENABLED = True\n\n# Number of seconds to wait before trying to refresh the key\ntry:\n MULTI_CACHE_REFRESH_TIMEOUT = settings.MULTI_CACHE_REFRESH_TIMEOUT\nexcept:\n MULTI_CACHE_REFRESH_TIMEOUT = 60\n\ntry:\n MULTI_CACHE_EXPIRY_TIMEOUT = settings.MULTI_CACHE_EXPIRY_TIMEOUT\nexcept:\n MULTI_CACHE_EXPIRY_TIMEOUT = 120\n\ntry:\n MULTI_CACHE_PREFIX = settings.MULTI_CACHE_PREFIX\nexcept:\n MULTI_CACHE_PREFIX = 'multi-cache-'\n\nfrom django.core.cache import cache\nimport logging\n\nlogger = logging.getLogger(name='multi-cache')\n\ndef multi_cache(cache_key_name, cache_key_arg=[], disable_cache_arg = None):\n \"\"\"Caches result of a callable web call.\n\n This decorator uses the standard django cache to store the result of callable (web requests).\n\n It is designed to sustain a constant heavy load of requests in the sense, that it attempts to refresh the content\n of the cache with increasing probability - starting from 0 and ending at certainty (1).\n Parameters:\n cache_key_arg = list of argument indexes which are taken for cache key building (default = empty list).\n The arguments can be number (positional parameters) or names (named kwargs parameters)\n disable_cache_arg_no = argument index (boolean) which tells if cache should be disabled for this request\n \"\"\"\n def removeNonAscii(s): return \"\".join(filter(lambda x: ord(x)<128, s))\n\n def process_from_cache(f, *args,**kwargs):\n cache_key = MULTI_CACHE_PREFIX + cache_key_name\n for arg in cache_key_arg:\n if isinstance(arg, str):\n cache_key = cache_key + \"_\" + str(kwargs.get(arg))\n else:\n cache_key = cache_key + \"_\" + str(args[arg])\n cache_key = cache_key.replace(' ','_')\n cache_key = removeNonAscii(cache_key)\n cache_time_key = MULTI_CACHE_PREFIX + cache_key + \"_refresh_time\"\n cache_being_refreshed_key = MULTI_CACHE_PREFIX + cache_key + \"_being_refreshed\"\n skip_cache = False\n ret = None\n if len(cache_being_refreshed_key) < 250:\n ret = cache.get(cache_key)\n else:\n logger.info(\"Not reading from cache - key is too long %s\" % cache_key)\n skip_cache = True\n if ret is not None:\n cached_time = cache.get(cache_time_key)\n if cached_time is None:\n cached_time = 0.0\n current_time = time()\n diff_time = current_time - cached_time\n being_refreshed = cache.get(cache_being_refreshed_key)\n if being_refreshed is not None:\n if settings.DEBUG:\n logger.debug(\"MULTI_CACHE: Value retained in cache key %s as it is being refreshed\" % cache_key)\n return ret\n if diff_time > MULTI_CACHE_REFRESH_TIMEOUT:\n probability = (diff_time - MULTI_CACHE_REFRESH_TIMEOUT)/(MULTI_CACHE_EXPIRY_TIMEOUT - MULTI_CACHE_REFRESH_TIMEOUT)\n if probability > 1:\n probability = 1\n rand_value = random()\n if rand_value > probability:\n if settings.DEBUG:\n logger.debug(\"MULTI_CACHE: Randomly staying with the cached value of key %s.\" % cache_key)\n return ret\n else:\n cache.set(cache_being_refreshed_key,True)\n logger.info(\"MULTI_CACHE: Decided to rebuild the key %s at random hit.\" % cache_key)\n else:\n if settings.DEBUG:\n logger.debug(\"MULTI_CACHE: Value retained in cache %s. Time %.3f is not yet greater than %d\" % (cache_key, diff_time,MULTI_CACHE_REFRESH_TIMEOUT))\n return ret\n else:\n if not skip_cache:\n logger.info(\"MULTI_CACHE: Decided to rebuild the key %s at empty cache.\" % cache_key)\n logger.info(\"MULTI_CACHE: Rebuilding %s.\" % cache_key)\n ret = f(*args, **kwargs)\n logger.info(\"MULTI_CACHE: Rebuilt the %s.\" % cache_key)\n if not skip_cache:\n current_time = time()\n cache.set(cache_key,ret)\n cache.set(cache_time_key,current_time)\n cache.delete(cache_being_refreshed_key)\n logger.info(\"MULTI_CACHE: Setting cache for: %s\" % cache_key)\n return ret\n def str2bool(v):\n return v.lower() in (\"yes\", \"true\", \"t\", \"y\", \"1\")\n def _outer(f):\n def _inner(*args, **kwargs):\n disable_cache = False\n if disable_cache_arg is not None:\n if isinstance(disable_cache_arg, str):\n disable_arg = kwargs.get(disable_cache_arg)\n else:\n disable_arg = args[disable_cache_arg]\n\n if isinstance(disable_arg,str) or isinstance(disable_arg,unicode):\n disable_cache = str2bool(disable_arg)\n else:\n disable_cache = bool(disable_arg)\n if not disable_cache and MULTI_CACHE_ENABLED:\n ret = process_from_cache(f, *args, **kwargs)\n else:\n ret = f(*args, **kwargs)\n if settings.DEBUG:\n logging.debug(\"MULTI_CACHE: Returning :\" + str(ret))\n return ret\n return _inner\n return _outer\n","sub_path":"multi_cache.py","file_name":"multi_cache.py","file_ext":"py","file_size_in_byte":5450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"569364005","text":"from django import template\n\nregister = template.Library()\n\n\n@register.filter()\ndef split_urls(url, folder):\n path_lst = [x for x in url.split('/') if x]\n if url.endswith('/') and len(path_lst) == 1 and path_lst[0] != folder:\n return ['folder', url]\n\n elif url.endswith('/') and len(path_lst) == 1 and path_lst[0] == folder:\n return None\n\n elif url.endswith('/') and path_lst[-2] == folder:\n return ['folder', url]\n\n elif not url.endswith('/') and folder in path_lst and path_lst[-2] == folder:\n return [url]\n\n elif not url.endswith('/') and len(path_lst) == 1:\n return [url]\n\n return None\n\n\n@register.simple_tag\ndef prepare_url(url):\n if len(url) > 1:\n return [x for x in url[1].split('/')if x][-1]\n else:\n if len([x for x in url[0].split('/')if x]) > 1:\n return [x for x in url[0].split('/')if x][-1]\n return url[0]\n","sub_path":"apps/simple_share/templatetags/simple_share_tags.py","file_name":"simple_share_tags.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"261815064","text":"# -------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n# --------------------------------------------------------------------------\nfrom ._rooms_client import RoomsClient\nfrom ._generated.models._enums import (\n RoomJoinPolicy,\n RoleType\n)\nfrom ._models import (\n CommunicationRoom,\n RoomParticipant,\n ParticipantsCollection\n)\nfrom ._version import VERSION\n\n__all__ = [\n 'CommunicationRoom',\n 'RoomsClient',\n 'RoomParticipant',\n 'RoomJoinPolicy',\n 'RoleType',\n 'ParticipantsCollection'\n]\n\n__VERSION__ = VERSION\n","sub_path":"sdk/communication/azure-communication-rooms/azure/communication/rooms/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"632959459","text":"import torch.nn as nn\r\nimport math\r\n\r\n'''\r\n Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0,\r\n dilation=1, groups=1, bias=True, padding_mode='zeros') \r\n in_channels(int) - Number of channels in the input image (1:binary , 3: RGB)\r\n out_channels(int) - Number of channels produced by the convolution,\r\n i.e., the number of feature filter(neuron) will be conneted.\r\n \r\n BatchNorm2d(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\r\n \r\n LeakyReLU(negative_slope=0.01, inplace=False)\r\n \r\n MaxPool2d(kernel_size, stride=None, padding=0, dilation=1, return_indices=False, ceil_mode=False)\r\n\r\n Dropout(p=0.5, inplace=False)\r\n'''\r\n\r\nclass VGG(nn.Module):\r\n def __init__(self, ConvNet, n_class):\r\n super(VGG, self).__init__()\r\n self.ConvNet = ConvNet\r\n self.classifier = nn.Sequential(\r\n nn.Dropout(),\r\n nn.Linear(512*1*1, 512), # need to check Linear input size\r\n nn.ReLU(True),\r\n nn.Dropout(), \r\n nn.Linear(512, 512),\r\n nn.ReLU(True),\r\n nn.Linear(512, n_class) \r\n )\r\n # Initialize weights(L2 norm)\r\n for m in self.modules():\r\n if isinstance(m, nn.Conv2d):\r\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\r\n m.weight.data.normal_(0, math.sqrt(2. / n))\r\n m.bias.data.zero_()\r\n \r\n def forward(self, x):\r\n out = self.ConvNet(x)\r\n out = out.view(out.size(0), -1) # Flatten\r\n out = self.classifier(out)\r\n return out\r\n \r\ndef make_layers(in_channels, cfg, batch_norm):\r\n layers = []\r\n for v in cfg:\r\n if v == 'M':\r\n layers += [nn.MaxPool2d(kernel_size=2, stride=2)]\r\n else:\r\n conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)\r\n if batch_norm:\r\n layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]\r\n else:\r\n layers += [conv2d, nn.ReLU(inplace=True)]\r\n in_channels = v\r\n return nn.Sequential(*layers)\r\n\r\ncfg = {\r\n 'A': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],\r\n 'B': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],\r\n 'D': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],\r\n 'E': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', \r\n 512, 512, 512, 512, 'M'],\r\n}\r\n\r\ndef vgg16(in_channels=1 , n_class=7, batch_norm=False):\r\n return VGG(make_layers(in_channels, cfg['D'], batch_norm), n_class)\r\n\r\ndef vgg19(in_channels=1 , n_class=7, batch_norm=False):\r\n return VGG(make_layers(in_channels, cfg['E'], batch_norm), n_class)\r\n\r\n ","sub_path":"ML2019FALL/hw3-CNN/vgg.py","file_name":"vgg.py","file_ext":"py","file_size_in_byte":2879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"506343775","text":"#!/usr/bin/env python3\n\nimport peewee as pw\n\nfrom .base import BaseModel\n\n\nclass Position(BaseModel):\n position_id = pw.PrimaryKeyField()\n position_description = pw.CharField()\n\n\nclass Institute(BaseModel):\n institute_id = pw.PrimaryKeyField()\n institute = pw.CharField()\n institute_link = pw.CharField()\n\n\nclass Department(BaseModel):\n department_id = pw.PrimaryKeyField()\n institute_id = pw.ForeignKeyField(Institute)\n department = pw.CharField()\n department_link = pw.CharField()\n\n\nclass Author(BaseModel):\n author_id = pw.PrimaryKeyField()\n author_link = pw.CharField()\n author_name = pw.CharField()\n institute_id = pw.ForeignKeyField(Institute)\n department_id = pw.ForeignKeyField(Department)\n position_id = pw.ForeignKeyField(Position)\n rg_score = pw.FloatField()\n","sub_path":"models/author.py","file_name":"author.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"233824445","text":"import sys\nimport asyncio\nimport logging\n\nimport synapse.common as s_common\nimport synapse.telepath as s_telepath\n\nimport synapse.exc as s_exc\nimport synapse.lib.cmd as s_cmd\nimport synapse.lib.base as s_base\nimport synapse.lib.output as s_output\n\nlogger = logging.getLogger(__name__)\n\nasync def main(argv, outp=s_output.stdout):\n\n pars = s_cmd.Parser(prog='synapse.tools.axon2axon', outp=outp)\n pars.add_argument('--offset', type=int, default=0, help='An offset within the source axon to start from.')\n pars.add_argument('src_axon', help='The telepath URL of the source axon.')\n pars.add_argument('dst_axon', help='The telepath URL of the destination axon.')\n\n try:\n opts = pars.parse_args(argv)\n except s_exc.ParserExit:\n return 1\n\n async with s_telepath.withTeleEnv():\n async with await s_base.Base.anit() as base:\n\n srcaxon = await base.enter_context(await s_telepath.openurl(opts.src_axon))\n dstaxon = await base.enter_context(await s_telepath.openurl(opts.dst_axon))\n\n outp.printf(f'Starting transfer at offset: {opts.offset}')\n\n async for (offs, (sha256, size)) in srcaxon.hashes(opts.offset):\n offstext = str(offs).rjust(10)\n sha2text = s_common.ehex(sha256)\n outp.printf(f'[{offstext}] - {sha2text} ({size})')\n async with await dstaxon.upload() as fd:\n async for byts in srcaxon.get(sha256):\n await fd.write(byts)\n await fd.save()\n return 0\n\nif __name__ == '__main__': # pragma: no cover\n sys.exit(asyncio.run(main(sys.argv[1:])))\n","sub_path":"synapse/tools/axon2axon.py","file_name":"axon2axon.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"492127671","text":"#!/usr/bin/python\nfrom math import *\nfrom Model import *\nM = Model()\nM.a = 0.1\nM.gamma = 0.1\nM.omega = 0.1\nM.I = 0\nIfail = open('I.dat', 'w')\nprint>>Ifail, '#:omega gamma I'\nM.delta_t = 0.01*(2*pi/M.omega)\nif 0.01*(2*pi) < M.delta_t:\n M.delta_t = 0.01*(2*pi)\nwhile M.omega < 2:\n M.gamma = 0.1\n while M.gamma < 2:\n M.I = M.calc(0,0,100)\n print>>Ifail, M.omega, M.gamma, M.I \n Ifail.flush()\n M.gamma+=0.1\n print>>Ifail, ''\n M.omega+=0.1","sub_path":"Mayatnic/Model_run.py","file_name":"Model_run.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"69532283","text":"from cicsa_ranking.models import Team\nfrom .AbstractCustomClass import AbstractCustomClass\nfrom panel.component.CustomElements import Choices\nfrom misc.CustomFunctions import MiscFunctions, RequestFunctions, LogFunctions\n\n\nclass TeamView(AbstractCustomClass):\n def __init__(self, request):\n self.base_class = Team\n self.validation_table = {\n 'base_table_invalid': {'_state'},\n 'base_form_invalid': {'_state', 'id'},\n }\n super().__init__(request, self.base_class, self.validation_table)\n\n# View Process Functions\n\n def abstractFormProcess(self, action, **kwargs):\n try:\n post_dict = dict(self.request.POST)\n dispatcher = super().populateDispatcher()\n\n if dispatcher.get(action):\n team_id = kwargs.pop('id', None)\n team = self.useAPI(self.base_class).editSelf(id=team_id)\n else:\n team = self.base_class()\n\n team.team_name = RequestFunctions.getSingleRequestObj(post_dict, 'team_name')\n team.team_school = RequestFunctions.getSingleRequestObj(post_dict, 'team_school')\n team.team_tag_id = RequestFunctions.getSingleRequestObj(post_dict, 'team_tag_id')\n team.team_status = RequestFunctions.getSingleRequestObj(post_dict, 'team_status')\n\n if not action == 'delete':\n team.save()\n\n LogFunctions.generateLog(\n self.request, 'admin', LogFunctions.makeLogQuery(\n self.base_class, action.title(), id=team.id))\n\n if action == 'delete':\n team.delete()\n except Exception:\n print({\"Error\": \"Cannot Process \" + action.title() + \" Request.\"})\n\n# View Generating Functions\n\n # Form Generating Functions\n def getFieldData(self, **kwargs):\n action = kwargs.pop('action')\n element_id = kwargs.pop('element_id')\n field_data_dispatcher = self.populateDispatcher()\n if field_data_dispatcher.get(action):\n field_data = MiscFunctions.filterDict(self.useAPI(self.base_class).getSelf(id=element_id).__dict__.items(),\n self.validation_table['base_form_invalid'])\n return field_data\n return None\n\n def getChoiceData(self):\n choice_data = dict()\n choice_data[\"team_status\"] = Choices().getTeamStatusChoices()\n choice_data[\"team_school\"] = Choices().getSchoolChoices()\n return choice_data\n\n def getDBMap(self, data):\n return None\n\n def getMultiChoiceData(self):\n return None\n\n def getSearchElement(self, **kwargs):\n return None\n\n # Table Generating Functions\n def getTableSpecificHeader(self):\n return [field.name for field in self.base_class._meta.get_fields()\n if field.name not in self.validation_table['base_table_invalid']]\n\n def getTableRowContent(self, content):\n field_data = MiscFunctions.filterDict(self.useAPI(self.base_class).getSelf(id=content.id).__dict__.items(),\n self.validation_table['base_table_invalid'])\n field_data = self.updateChoiceAsValue(field_data, self.getChoiceData())\n field_data = MiscFunctions.grabValueAsList(field_data)\n return field_data\n","sub_path":"panel/config/admin/management_data/CustomPages/Team.py","file_name":"Team.py","file_ext":"py","file_size_in_byte":3330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"504022782","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 ('tracker', '0003_auto_20141122_1558_add_functional_index_on_game'),\n ]\n\n operations = [\n migrations.RunSQL(\n \"CREATE INDEX tracker_ip_length ON tracker_ip ((range_to - range_from));\",\n \"DROP INDEX tracker_ip_length;\",\n ),\n ]\n","sub_path":"tracker/migrations/0004_auto_20141122_1601_add_ip_length_index.py","file_name":"0004_auto_20141122_1601_add_ip_length_index.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"648377052","text":"import sys\nimport csv\nimport cPickle as pickle\nimport subprocess\n\n'''----------------------------------------------------------------------------\nProject: RASCAL: Robotic Autonomous Space Cadet Adminstration Lackey\nFile: util.py\nAuthor: @WhitneyOnTheWeb\n\nOriginal: ZacSweers FB Modbot (2014 / Py2)\n\nGeneral utility functions for RASCAL operation\n----------------------------------------------------------------------------'''\n__author__ = 'Whitney King'\n\n\n'''-------------------------------------\nGlobal Variables\n================\n'''\ntime_limit = 86400 # 60 * 60 * 24 (s --> h)\nprop_file = 'properties' # properties pickle name\nwarned_db = 'fb_subs_cache' # warned posts cache\nvalid_db = 'fb_subs_valid_cache' # valid posts cache\n\ntag_delimiters = ('*', '-') # leading symbols for post tags\npost_tags = load_list('post_tags.txt')\n\nbot_delimiters = ('!', '#') # leading symbols for bot tags\nbot_tags = load_list('bot_tags.txt')\n\n# Booleans\nis_heroku = False # is bot running on heroku?\nis_pickled = False # is there a .pkl for properties?\ndry_run = False # disable deletion dry-run\nextend_key = False # is extended key\n\n\n'''-------------------------------------\nClass: Color\n\nText color formatting for logging output\n'''\nclass Color:\n PURPLE = '\\033[95m'\n CYAN = '\\033[96m'\n DARKCYAN = '\\033[36m'\n BLUE = '\\033[94m'\n GREEN = '\\033[92m'\n YELLOW = '\\033[93m'\n RED = '\\033[91m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n END = '\\033[0m'\n\n\n'''-------------------------------------\nMethod: test\n\nTemplate placeholder function for displaying\noutput when running tests\n'''\ndef test():\n log('Test', Color.PURPLE)\n\n\n'''-------------------------------------\nMethod: extend_access_token\n\nUsed to automatically extend access token\n'''\ndef extend_access_token(graph, now_time, saved_props,\n sublets_api_id, sublets_secret_key):\n log(\"Extending access token\", Color.BOLD)\n result = graph.extend_access_token(sublets_api_id, sublets_secret_key)\n new_token = result['access_token']\n new_time = int(result['expires']) + now_time\n saved_props['sublets_oauth_access_token'] = new_token\n saved_props['access_token_expiration'] = new_time\n log(\"Token extended\", Color.BOLD)\n\n\n'''-------------------------------------\nMethod: load_list\n\nGenerate list of values to be used by RASCAL\n- Reads from a .txt file into a list variable\n\nInput:\n : name of file containing list with\n syntax (one per line):\n value\nReturn:\n : with values from file\n'''\ndef load_list(lfile):\n vals = []\n with open('./files/{}'.format(lfile), 'r') as f:\n lst = csv.reader(f) # get text from file\n for val in lst: # read each value\n vals.append(val) # add value to list\n f.close() # close file when done\n return vals\n\n\n'''-------------------------------------\nMethod: get_settings\n\nGenerate settings dictionary with key-value\npairs stored as items in a .txt file\n\nInput:\n : name of file with settings using\n syntax (one per line):\n key: value\nReturn:\n : dictionary with settings\n key-value pairs\n'''\ndef get_settings(pfile):\n prop = {}\n with open('./files/{}'.format(pfile), 'r') as keys:\n for key in keys:\n k, v = key.split(': ')\n if v.endswith('\\n'): v = v[:-1]\n prop[k] = v\n keys.close()\n return prop\n\n\n'''-------------------------------------\nMethod: init_properties\n\nInitializes property values for RASCAL,\nthen uploads them in chosen format\n'''\n\ndef init_properties():\n test_dict = get_settings('properties.txt')\n save_properties(test_dict)\n\n saved_dict = load_properties()\n assert test_dict == saved_dict\n\n\n'''-------------------------------------\nMethod: save_properties\n\nSave RASCAL properties to either:\n - memcache (heroku)\n - pickle (local file)\n - text file\n\nInput:\n : dict of property key-value pairs\n'''\ndef save_properties(data):\n if is_heroku: # save to heroku\n mc.set('properties', data)\n else: # save to .pkl\n with open(prop_file, 'w+') as f:\n pickle.dump(data, f)\n f.close()\n # save to .txt\n # with open('./files/properties.txt', 'w') as f:\n\n\n'''-------------------------------------\nMethod: load_properties\n\nLoads saved property values from either:\n - memcache (heroku)\n - pickle (local file)\n - text file\n\n Return:\n : dictionary with properties\n key-value pairs\n'''\ndef load_properties():\n if is_heroku: # load from heroku\n obj = mc.get('properties')\n if not obj:\n return {}\n else:\n return obj\n else: # load from .pkl\n if os.path.isfile(prop_file):\n with open(prop_file, 'r+') as f:\n data = pickle.load(f)\n return data\n else: # load from .txt\n return get_settings('properties.txt')\n\n\n'''-------------------------------------\nMethod: set_property\n\nSets key in property dictionary to a\nuser defined value, updates value in\nproperties text file\n\nInput:\n : dict containing properties\n : key to add or update\n : value to set\n'''\ndef set_property(props, key, value):\n # Add if needed for RASCAL operation\n pass\n\n\n'''-------------------------------------\nMethod: load_cache\n\nLoads cache from user defined locations.\nEither returns cached values or original data\n\nInput:\n : cache to select\n : data to return\n\nReturns:\n : object with cached values\n'''\ndef load_cache(cachename, data):\n if is_heroku:\n if is_heroku:\n obj = mc.get(cachename)\n if not obj:\n return data\n else:\n return obj\n else:\n if os.path.isfile(cachename):\n with open(cachename, 'r+') as f:\n # If the file isn't at its end or empty\n if f.tell() != os.fstat(f.fileno()).st_size:\n return pickle.load(f)\n else:\n log(\"--No cache file found. Creating new cache file.\", Color.BLUE)\n return data\n\n\n'''-------------------------------------\nMethod: save_cache\n\nSaves cache to user defined location.\n\nInput:\n : cache to select\n : data to save\n'''\ndef save_cache(cachename, data):\n if is_heroku:\n mc.set(cachename, data)\n else:\n with open(cachename, 'w+') as f:\n pickle.dump(data, f)\n\n\n'''-------------------------------------\nMethod: log\n\nChecks for Color class, then prints log output\n\nInput:\n : logging message to display\n'''\ndef log(message, *colorargs):\n if len(colorargs) > 0:\n print(colorargs[0] + message + Color.END)\n else:\n print (message)\n\n\n\n'''-------------------------------------\nMethod: notify\n\nCurrently sends notifications on Mac\n\n- Needs updates for Windows/Linux\n'''\ndef notify():\n if sys.platform == \"darwin\":\n try:\n subprocess.call(\n [\"terminal-notifier\", \"-message\", \"Tests done\", \"-title\",\n \"FB_Bot\", \"-sound\", \"default\"])\n except OSError:\n print('If you have terminal-notifier, this would notify')\n\n\n'''-------------------------------------\nMethod: read_lines\n\nReads in multi-line strings based on \"newline\" type\nhttp://stackoverflow.com/a/16260159/3034339\n\n- Needs to be validated\n'''\ndef read_lines(f, newline):\n buf = \"\"\n while True:\n while newline in buf:\n pos = buf.index(newline)\n yield buf[:pos]\n buf = buf[pos + len(newline):]\n chunk = f.read(4096)\n if not chunk:\n yield buf\n break\n buf += chunk","sub_path":"rascal_bot/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":7981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"523824997","text":"import os\nimport sys\nimport requests\nclient_id = \"5a7ujbpf09\"\nclient_secret = \"aNIgCvVKdwD4iMFk6JtpRotkhosHR8llILAMvqx3\"\nurl = \"https://naveropenapi.apigw.ntruss.com/vision-obj/v1/detect\"\n\n\nfiles = {'image': open('./img/1.jfif', 'rb')}\n\n\nheaders = {'X-NCP-APIGW-API-KEY-ID': client_id, 'X-NCP-APIGW-API-KEY': client_secret }\nresponse = requests.post(url, files=files, headers=headers)\nrescode = response.status_code\nif(rescode==200):\n print (response.text)\nelse:\n print(\"Error Code:\" + rescode)\n","sub_path":"obj_detection_example.py","file_name":"obj_detection_example.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"177830055","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Comment',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('comment_text', models.CharField(max_length=900)),\n ('data', models.DateTimeField(auto_now=True)),\n ],\n ),\n migrations.CreateModel(\n name='Post',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(max_length=901)),\n ('content', models.TextField()),\n ('img', models.ImageField(upload_to='blog.img/')),\n ('date', models.DateTimeField(auto_now=True)),\n ('is_published', models.BooleanField(default=False)),\n ('users', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.AddField(\n model_name='comment',\n name='post',\n field=models.ForeignKey(to='blog.Post'),\n ),\n migrations.AddField(\n model_name='comment',\n name='user',\n field=models.ForeignKey(to=settings.AUTH_USER_MODEL),\n ),\n ]\n","sub_path":"blog/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"472207794","text":"from typing import Any\nimport doctest\n\nclass Node:\n def __init__(self, data: Any) -> None:\n self.data = data\n self.next = None\nclass Linkedlist:\n def __init__(self)-> None:\n self.head = None\n def push_at_head(self, data: Any) -> None:\n new_node = Node(data)\n new_node.next = self.head\n self.head = new_node\n # **deletion code starts**\n def delete_node(self, key) -> None:\n temp = self.head\n while temp.next:\n if temp.next.data == key: #if next node is the node what we want to delete\n temp.next = temp.next.next #breaking the link of node which has to be deleted\n temp = temp.next #if condition not satisy then go to next node\n # **deletion code ends**\n def print_list(self) -> None:\n \"\"\"\n >>> linked_list = Linkedlist()\n\n >>> linked_list.push_at_head(3)\n\n >>> linked_list.push_at_head(2)\n\n >>> linked_list.push_at_head(1)\n\n >>> linked_list.push_at_head(0)\n\n >>> linked_list.print_list()\n 0->1->2->3->NULL\n\n >>> linked_list.delete_node(2)\n\n >>> linked_list.print_list()\n 0->1->3->NULL\n \n \"\"\"\n temp = self.head\n while temp:\n print(temp.data, end=\"->\")\n temp = temp.next\n print(\"NULL\")\n\nif __name__=='__main__':\n \n doctest.testmod()\n","sub_path":"data_structures/linked_list/delete_node.py","file_name":"delete_node.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"332370195","text":"import re\nimport ast\nimport binascii\nfrom asn1codec.json_formater import format_json\nfrom asn1codec.utils import change_variable_to_python_style, get_supported_messages_in_modules, reformat_asn_line\nfrom asn1codec.asn_code_mgmt import AsnCodeMgmt\nfrom asn1codec.asn_codec_error import AsnCodeError\n\n\nclass Asn1Codec(object):\n def __init__(self, py_file, module):\n \"\"\"\n py_file: the python file name which should be the output py file of pycrate\n module: the module of py_file, it's a string like \"xx.xxxx.xx\", which can be recorgnized by __import__\n \"\"\"\n self.py_file = py_file\n self.msgs_in_modules = {}\n self.asn_mgmt = None\n self.module = module\n\n def compile(self, data):\n \"\"\"\n data: the whole asn1 data\n \"\"\"\n try:\n self.asn_mgmt = AsnCodeMgmt(data)\n ckw = {'autotags': True, 'extimpl': True, 'verifwarn': True}\n from pycrate_asn1c.proc import compile_text, generate_modules, PycrateGenerator\n compile_text(data, **ckw)\n generate_modules(PycrateGenerator, self.py_file)\n except AsnCodeError as e:\n return False, str(e), []\n except Exception as e:\n return False, str(e), []\n self.msgs_in_modules = get_supported_messages_in_modules(self.py_file)\n msgs = []\n for module in self.msgs_in_modules:\n msgs.extend(self.msgs_in_modules[module])\n msgs.sort()\n return True, \"Compile Success!\", msgs\n \n def encode(self, protocol, format, msg_name, msg_content):\n \"\"\"\n protocol: to spicify the encode mothod, per/uper/ber/cer/der\n format: to spicify the format of input message content, asn1/json\n msg_name: the name of message to encode\n msg_content: the content of message to encode\n \"\"\"\n pdu_str = self._get_pdu_str(msg_name)\n if pdu_str is None: return False, \"Unknow message!\"\n modules = [change_variable_to_python_style(module) for module in self.msgs_in_modules]\n target = __import__(self.module, globals(), locals(), modules)\n pdu = eval(\"target.\" + pdu_str)\n try:\n if format == \"asn1\": pdu.from_asn1(msg_content)\n else:\n msg = ast.literal_eval(msg_content)\n pdu.set_val(msg)\n payload = None\n if protocol == \"per\":\n payload = pdu.to_aper()\n elif protocol == \"uper\":\n payload = pdu.to_uper()\n elif protocol == \"ber\":\n payload = pdu.to_ber()\n elif protocol == \"cer\":\n payload = pdu.to_cer()\n elif protocol == \"der\":\n payload = pdu.to_der()\n else:\n return False, \"Unkown protocol\"\n except Exception as e:\n return False, str(e)\n return True, binascii.hexlify(payload).decode(\"utf-8\")\n \n def decode(self, protocol, format, msg_name, payload):\n \"\"\"\n protocol: to spicify the decode mothod, per/uper/ber/cer/der\n format: to spicify the format of input message content, asn1/json\n msg_name: the name of message to decode\n msg_content: the content of message to decode\n \"\"\"\n ## the length of payload must be even, and payload should be hex stream\n pdu_str = self._get_pdu_str(msg_name)\n if pdu_str is None: return False, \"Unknow message!\"\n modules = [change_variable_to_python_style(module) for module in self.msgs_in_modules]\n target = __import__(self.module, globals(), locals(), modules)\n pdu = eval(\"target.\" + pdu_str)\n try:\n if protocol == \"per\":\n pdu.from_aper(binascii.a2b_hex(payload))\n elif protocol == \"uper\":\n pdu.from_uper(binascii.a2b_hex(payload))\n elif protocol == \"ber\":\n pdu.from_ber(binascii.a2b_hex(payload))\n elif protocol == \"cer\":\n pdu.from_cer(binascii.a2b_hex(payload))\n elif protocol == \"der\":\n pdu.from_der(binascii.a2b_hex(payload))\n else:\n return False, \"Unkown protocol\"\n except Exception as e:\n return False, str(e)\n res = pdu.to_asn1() if format == \"asn1\" else format_json(str(pdu()))\n return True, res\n \n def get_supported_msgs(self):\n supported_msgs = []\n for module in self.msgs_in_modules:\n supported_msgs.extend(self.msgs_in_modules[module])\n supported_msgs.sort()\n return supported_msgs\n \n def get_message_definition(self, msg_name):\n return self.asn_mgmt.get_message_definition(msg_name)\n \n def _get_pdu_str(self, msg_name):\n \"\"\"\n msg_name: the asn1 format name of msg\n \"\"\"\n for module in self.msgs_in_modules:\n for msg in self.msgs_in_modules[module]:\n if msg == msg_name:\n return change_variable_to_python_style(module) + \".\" + change_variable_to_python_style(msg)\n return None\n","sub_path":"src/asn1codec/asn1_codec.py","file_name":"asn1_codec.py","file_ext":"py","file_size_in_byte":5123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"227710204","text":"import json\n\n\nclass Student(object):\n def __init__(self, name, age, score):\n self.name = name\n self.age = age\n self.score = score\n\n\ns = Student('Bob', 20, 88)\n\nd = dict(name='Bob', age=20, score=90)\nj = json.dump(s)\nprint(j)\nj = json.dumps(d)\nprint(j)\n","sub_path":"python/jsonPython/testJson.py","file_name":"testJson.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"446893123","text":"\nimport numpy as np\n\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nclass DataLoader:\n def __init__(self):\n print(\"init DataLoader\")\n def getLinearTrainData(self):\n train_X = np.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,\n 7.042,10.791,5.313,7.997,5.654,9.27,3.1])\n train_Y = np.asarray([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,\n 2.827,3.465,1.65,2.904,2.42,2.94,1.3])\n return train_X, train_Y\n def getLinearTestData(self):\n test_X = np.asarray([6.83, 4.668, 8.9, 7.91, 5.7, 8.7, 3.1, 2.1])\n test_Y = np.asarray([1.84, 2.273, 3.2, 2.831, 2.92, 3.24, 1.35, 1.03])\n return test_X, test_Y\n def getMINSTTrainData(self,one_hot=False):\n mnist = input_data.read_data_sets(\"./MNIST_data/\",one_hot=one_hot)\n batch = mnist.train.next_batch(1000)\n X = batch[0]\n Y = np.copy(batch[1])\n return X,Y\n\n def getMINSTTestData(self,one_hot=False):\n mnist = input_data.read_data_sets(\"./MNIST_data/\",one_hot=one_hot)\n X = mnist.test.images\n Y = np.copy(mnist.test.labels)\n return X, Y\n","sub_path":"Project in Embedded Systems/self-driving-car-master-d842d43e64bd34805fc2207191fe49be3fa28046/cnn/DataLoader.py","file_name":"DataLoader.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"181111494","text":"import numpy as np\nimport pandas as pd\nimport os\n\ndef new_alt_values(x): # this function converts original latitude values into the new altitude values\n lat_deltas = x - min_lat\n y_1 = lat_deltas * np.sin(rot_ang_rad)\n conv_alt = y_1 * alt_conv_factor\n output_alt = conv_alt + des_min_alt\n return output_alt\n\ndef new_lat_values(x): # this function converts original latitude values into the new latitude values\n lat_deltas = x - min_lat\n x_1 = lat_deltas * np.cos(rot_ang_rad)\n output_lat = x_1 + min_lat\n return output_lat\n\nfile_name = input('Enter name of file: ')\nrot_ang_deg = input('Please enter desired rotation angle from 0 - 180 degrees: ')\nrot_ang_rad = float(rot_ang_deg) * 0.0174533\ncsv_df = pd.read_csv(file_name, delimiter = ',')\nmin_lat = csv_df['latitude'][csv_df['latitude'].idxmin()]\n\nif csv_df.columns[2] == 'altitude(m)' : # this runs if the original .CSV file was generated with metric units\n des_min_alt = input('Please enter desired minimum altitude in meters: ')\n des_min_alt = float(des_min_alt)\n alt_conv_factor = 110947.2\n alt_type = 'm'\n csv_df['altitude(m)'] = csv_df['latitude'].apply(new_alt_values)\n print('Minimum Altitude:', des_min_alt, 'meters')\n\nelif csv_df.columns[2] == 'altitude(ft)' : # this runs if the original .CSV file was generated with imperial units\n des_min_alt = input('Please enter desired minimum altitude in feet: ')\n des_min_alt = float(des_min_alt)\n alt_conv_factor = 364000.0\n alt_type = 'ft'\n csv_df['altitude(ft)'] = csv_df['latitude'].apply(new_alt_values)\n print('Minimum Altitude:', des_min_alt, 'feet')\n\nelse :\n print('Error with input file!')\n\ncsv_df['latitude'] = csv_df['latitude'].apply(new_lat_values)\n\noutput_file_name = file_name[0:-4] + '_' + str(des_min_alt) + '_' + alt_type + '_' + rot_ang_deg + '_degrees.csv' # this sets the name of the output file to the minimum altitude and rotation angle\noutput_file_path = os.path.dirname(os.path.abspath(__file__)) # this is the same path as this running script\ncsv_df.to_csv(output_file_path + '/' + output_file_name, index = False)\n\nprint('Exported' , output_file_name, 'to', output_file_path)\n","sub_path":"litchi_angle_converter.py","file_name":"litchi_angle_converter.py","file_ext":"py","file_size_in_byte":2175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"264413628","text":"\"\"\"\n1. Change your file path in line 25 and line 83 !!!\n2. Download webdriver from here: https://sites.google.com/a/chromium.org/chromedriver/downloads\n3. Change your webdriver path in line 50 !!!\n\"\"\"\n\nimport os\nimport sys\nimport time\nimport re\nimport csv\nimport random\nimport numpy as np\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\n#from fake_useragent import UserAgent\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.chrome.options import Options\n\n\nclass open_csv():\n def __init__(self):\n #CHANGE YOUR PATH HERE\n self.path = '/Users/Stephanie/Desktop/classical_yt_file.csv'\n\n def open_read(self):\n data = pd.read_csv(self.path, index_col=0)\n return data\n\nclass youtube_search():\n def __init__(self):\n self.url = \"https://www.youtube.com/\"\n self.keywords = \"\"\n self.yt_urls = []\n\n def search(self, data):\n youtube_home = self.url\n\n #For fake user-sgent\n \"\"\"\n options = Options()\n ua = UserAgent()\n userAgent = ua.random\n options.add_argument(f'user-agent={userAgent}')\n driver = webdriver.Chrome(chrome_options=options, executable_path=\"/Users/Stephanie/webapp/chromedriver\") # Use Chrome\n \"\"\"\n\n #CHANGE YOUR webdriver PATH HERE !!!\n driver = webdriver.Chrome(executable_path=\"/Users/Stephanie/webapp/chromedriver\")\n driver.get(youtube_home)\n col_num = data.shape[1]\n\n for i in range (data.shape[0]):\n search_space = driver.find_element_by_name('search_query')\n search_space.clear()\n\n self.keywords = data.iloc[i,col_num-1]\n search_space.send_keys(self.keywords)\n search_space.send_keys(Keys.RETURN)\n key_page = driver.current_url\n driver.get(key_page)\n #time.sleep(random.randint(4,9))\n\n try:\n if driver.find_element_by_xpath('(//*[@id=\"video-title\"])[1]').is_displayed():\n first_link = driver.find_element_by_xpath('(//*[@id=\"video-title\"])[1]')\n video_url = first_link.get_attribute('href')\n video_url = video_url.lstrip(\"https://www.youtube.com/watch?v=\")\n self.yt_urls.append(video_url)\n except:\n video_url = \"\"\n self.yt_urls.append(video_url)\n \n return self.yt_urls\n\nclass save_new_csv():\n def __init__(self):\n self.path = \"\"\n \n def save(self, data, urls):\n #CHANGE PATH HERE\n self.path = '/Users/Stephanie/Desktop/classical_yt_file.csv'\n data.loc[:, 'youtube_link'] = urls\n data.to_csv(self.path, index=True, header=True)\n #data.to_csv(self.path, header=True)\n\n\nif __name__=='__main__':\n url = []\n \n OpenCsv = open_csv()\n data = OpenCsv.open_read()\n\n YoutubeSearch = youtube_search()\n urls = YoutubeSearch.search(data)\n\n SaveCsv = save_new_csv()\n SaveCsv.save(data, urls)\n\n\n\n\n\n\n\n","sub_path":"Youtube automation/main_classical.py","file_name":"main_classical.py","file_ext":"py","file_size_in_byte":3031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"478938999","text":"class Solution(object):\n def eraseOverlapIntervals(self, intervals):\n \"\"\"\n :type intervals: List[List[int]]\n :rtype: int\n \"\"\"\n intervals.sort()\n \n res = 0\n last = 0\n for i in xrange(1,len(intervals)):\n if intervals[i][0] < intervals[last][1]:\n res += 1\n if intervals[i][1] < intervals[last][1]:\n last = i\n else:\n last = i\n return res\n ","sub_path":"LC435_array_interval.py","file_name":"LC435_array_interval.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"458253629","text":"#1. Background and Data Description\n\n# Our group chose to analyze data from the Fifa19. We used dataset\n# available on Kaggle,(https://www.kaggle.com/karangadiya/fifa19), \n# which is scrapped from original source sofifa(https://sofifa.com/)\n# The total size of the dataset is about 18206 rows with 88 fields.\n# Fields include demographic information (name, age, height, nationality etc.) for \n# each player, the wage, evaluation(international reputation, overall, potential), \n# the Positions (LS, ST, RS, LW, LF, CF, RF, RW, LAM, CAM, RAM, LM, LCM, CM, RCM, \n# RM, LWB, LDM, CDM, RDM, RWB, LB, LCB, CB, RCB, RB), the Scores for Attacking\n# (Crossing, Finishing, Heading, Accuracy, ShortPassing, Volleys), \n# the Scores for Skill (Dribbling, Curve, FKAccuracy, LongPassing, BallControl), \n# the Scores for Movement (Acceleration, SprintSpeed, Agility, Reactions, Balance),\n# the Scores for Power (ShotPower, Jumping, Stamina, Strength, LongShots), \n# the Scores for Mentality (Aggression, Interceptions, Positioning, Vision, Penalties, Composure),\n# the Scores for defending (Marking, StandingTackle, SlidingTackle), the Scores for\n# Goalkeeping (GKDiving, GKHandling, GKKicking, GKPositioning, GKReflexes), Release Clause.\n\n#2. SMART Question\n# How is wage distributed? Can we model wage with soccer players’ features? \n# Is player’s overall rating calculated from a formula of abilities rating? Or is it determined experimentally?\n# Is preferred foot affected by his abilities rating?\n# Is the international reputation of players affected by theirs scores?\n# Can we predict the preferred foot form score values?\n\n#3. Data Preprocess and Cleaning\n\n# %% Import packages\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import neighbors\nfrom sklearn.metrics import mean_squared_error \nfrom math import sqrt\nimport matplotlib.pyplot as plt\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn import metrics\nfrom sklearn.preprocessing import scale\nfrom sklearn.model_selection import cross_val_score\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import classification_report\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\nfrom statsmodels.formula.api import ols\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\n\n#%%\ndirpath = os.getcwd() \nfilepath = os.path.join( dirpath ,'data.csv')\nfifa = pd.read_csv(filepath) \nfifa.head()\n\n# %% Data Cleaning\n#To check whether index is unique and drop NA\nprint('\\n',fifa.head(),'\\n')\nfifa.index\nprint(fifa.index.is_unique)\nfifa.columns\nfifa = fifa.rename(columns={'Unnamed: 0': 'id', 'Club Logo':'Club_Logo', 'Preferred Foot':'Preferred_Foot', 'International Reputation':'International_Reputation', 'Weak Foot':'Weak_Foot', 'Skill Moves':'Skill_Moves', 'Work Rate':'Work_Rate', 'Body Type':'Body_Type', 'Real Face':'Real_Face', 'Jersey Number':'Jersey_Number', 'Loaned From':'Loaned_From', 'Contract Valid Until':'Contract_Valid_Until', 'Release Clause':'Release_Clause'})\nfifa = fifa.drop(columns=['Loaned_From'])\nfifa = fifa.dropna()\n\n# %% 4. Linear model of wage\nfifa['Wage'] = fifa['Wage'].map(lambda x: x[1:][:-1])\nfifa['Wage'] = pd.to_numeric(fifa['Wage'])\n\n#%%\nplt.hist(fifa['Wage'], label='fifawage')\nplt.xlabel('Wage')\nplt.ylabel('Frequency')\nplt.show()\n#From the plot we can see salaries are right skewed\n\n#%%\n#from the plot we can see high-level salaries are much less than the lower-level salary, and first we look into the low-level salary which is less than 200K and 50K and 5K\n#Salaries are right-skewed distributed in each group, and the frequencies become less and less as salaries go up\nplt.hist(fifa[fifa['Wage']<200]['Wage'], label='fifawage',edgecolor='black', linewidth=1.2)\nplt.xlabel('Wage under 200')\nplt.ylabel('Frequency')\n\n#%%\nplt.hist(fifa[fifa['Wage']<50]['Wage'], label='fifawage',edgecolor='black', linewidth=1.2)\nplt.xlabel('Wage under 50')\nplt.ylabel('Frequency')\n\n#%%\nplt.hist(fifa[fifa['Wage']<20]['Wage'], label='fifawage',edgecolor='black', linewidth=1.2)\nplt.xlabel('Wage under 20')\nplt.ylabel('Frequency')\n\n# %%\n#Then we look into the high salaries, we can see the frequencies in each level are sparse and scattered, and also some high outlier exist\nplt.hist(fifa[fifa['Wage']>200]['Wage'], label='fifawage',edgecolor='black', linewidth=1.2)\nplt.xlabel('Wage above 200')\nplt.ylabel('Frequency')\n\n# %%\n#BMI is an indicator of health condition, and we increase a new variable bmi(=height(m)/weight(kg)^2)\n#fh=open(filepath, encoding=\"utf8\")\n#for aline in fh.readlines(): # readlines creates a list of elements; each element is a line in the txt file, with an ending line return character. \n# h = int(aline.split(',').split(\"'\")[0])+int(aline.split(',').split(\"'\")[1])*0.1\n\n#fifa['Weight']=0.453592*int(fifa['Weight'].strip('lbs'))\n\nw2=[0.453592*int(w.strip('lbs')) for w in fifa['Weight']]\nh2=[int(h.split(\"'\")[0])+int(h.split(\"'\")[1])*0.1 for h in fifa['Height']]\n# for i in range(len(fifa['Weight'])):\nfifa['Weight'] = fifa['Weight'].apply(lambda x: 0.453592*int(x.strip('lbs')))\nfifa['Height'] = fifa['Height'].apply(lambda x: int(x.split(\"'\")[0]) + int(x.split(\"'\")[1])*0.1)\nfifa['BMI'] = fifa['Weight'] / pow(fifa['Height']*30.48/100, 2)\n# for m in range(len(w2)):\n# bmi=w2[m]/pow(h2[m]*30.48/100,2)\n# fifa['BMI'][m]=bmi\n\n# fifa['BMI'].head()\n\n# %%\nplt.hist(fifa['Age'], label='fifaage',edgecolor='black', linewidth=1.2)\n#From the age distribution we can see age 20 to 30 are the majority\n#We expect there will be 'golden ages' for athletes, which means below or above the certain range of age, soccer players would not be at their time of best performance\n#fifa['Age^2']=None\n#age=[age for age in fifa['Age']]\n#for n in list(range(len(age))):\n# agesquare=pow(age[n],2)\n# fifa['Age^2'][n]=agesquare\n#fifa['Age^2'].head()\n#We can have a look at plot of Wage & Age. The plot is normal distributed.\nfig, axis = plt.subplots()\naxis.plot(fifa.Age, fifa.Wage,color='g', linestyle=\"\", marker=\"o\", markersize=3)\nplt.xlabel(\"Age\")\nplt.ylabel(\"Wage\")\nplt.title(\"Wage vs Age\")\nplt.show()\n\n# %%\nplt.hist(fifa['Jersey_Number'], label='fifanumber',edgecolor='black', linewidth=1.2)\n#We can see Jersey Number under 40 are the majority\n\n#%%\n#Many fans and soccer believe there are 'lucky numbers'. And there is a rumor going like that numbers in a range tend to be picked as lucky numbers\n#To test whether it makes sense, we got jursey number squared \n#fifa['Jersey_Number_Squared']=None\n#number=[number for number in fifa['Jersey_Number']]\n#for j in list(range(len(number))):\n# numbersquare=pow(number[j],2)\n# fifa['Jersey_Number_Squared'][j]=numbersquare\n#fifa['Jersey_Number_Squared'].head()\nfig, axis = plt.subplots()\naxis.plot(fifa.Jersey_Number, fifa.Wage,color='g', linestyle=\"\", marker=\"o\", markersize=3)\nplt.xlabel(\"Jersey Number\")\nplt.ylabel(\"Wage\")\nplt.title(\"Wage vs Jersey Number\")\nplt.show()\n#From the plot we can see valuable players are accumulated around 10\n\n#%%\nplt.hist(fifa[fifa['Jersey_Number']<40]['Jersey_Number'], label='fifanumber',edgecolor='black', linewidth=1.2)\nfig, axis = plt.subplots()\naxis.plot(fifa[fifa['Jersey_Number']<40].Jersey_Number, fifa[fifa['Jersey_Number']<40].Wage,color='g', linestyle=\"\", marker=\"o\", markersize=3)\nplt.xlabel(\"Jersey Number\")\nplt.ylabel(\"Wage\")\nplt.title(\"Wage vs Jersey Number\")\nplt.show()\n\n# %%\n#Then we build the liner model to see which variables could have significant effect on wages\nmodelwage = ols(formula='Wage ~ Age+Overall+Potential+Special+C(International_Reputation)+C(Weak_Foot)+C(Skill_Moves)+C(Work_Rate)+C(Body_Type)+C(Position)+Jersey_Number+BMI+Crossing+Finishing+HeadingAccuracy+ShortPassing+Volleys+Dribbling+Curve+FKAccuracy+LongPassing+BallControl+Acceleration+SprintSpeed+Agility+Reactions+Balance+ShotPower+Jumping+Stamina+Strength+LongShots+Aggression+Interceptions+Positioning+Vision+Penalties+Composure+Marking+StandingTackle+SlidingTackle+GKDiving+GKHandling+GKKicking+GKPositioning+GKReflexes', data=fifa).fit()\nprint(modelwage.summary())\n\n#%%\n#We drop the variable with large p value until all p values are down to less than 5%\n#(For categorical variables, though some dimesnions have large p value(>5%), we still keep them when other dimensions are signficant)\nmodelwage2 = ols(formula='Wage ~ Potential+Special+C(International_Reputation)+C(Skill_Moves)+C(Work_Rate)+Age+Overall+Finishing+Volleys+Reactions+Balance+Positioning+Vision+Composure+SlidingTackle+GKDiving', data=fifa).fit()\nprint(modelwage2.summary())\n\n\n#%% 5. Linear model of overall rating \n# Standard quick checks\ndef dfChkBasics(dframe): \n cnt = 1 \n try:\n print(str(cnt)+': info(): ')\n print(dframe.info()) \n except: pass\n\n cnt+=1\n print(str(cnt)+': describe(): ')\n print(dframe.describe())\n\n cnt+=1\n print(str(cnt)+': dtypes: ')\n print(dframe.dtypes)\n\n try:\n cnt+=1\n print(str(cnt)+': columns: ')\n print(dframe.columns)\n except: pass\n\n cnt+=1\n print(str(cnt)+': head() -- ')\n print(dframe.head())\n\n cnt+=1\n print(str(cnt)+': shape: ')\n print(dframe.shape)\n\n # cnt+=1\n # print(str(cnt)+': columns.value_counts(): ')\n # print(dframe.columns.value_counts())\n\ndef dfChkValueCnts(dframe):\n cnt = 1\n for i in dframe.columns :\n print(str(cnt)+':', i, 'value_counts(): ')\n print(dframe[i].value_counts())\n cnt +=1\n\n# %% Preprocess\n\noverall_skills = fifa.loc[:,'LS':'GKReflexes']\noverall_skills.insert(0, 'Overall', fifa['Overall'])\n\nfor i in overall_skills.columns:\n if type(overall_skills[i][0]) == str:\n overall_skills[i] = overall_skills[i].apply(lambda x: int(x.split('+')[0])+int(x.split('+')[1]))\n\ndfChkBasics(overall_skills)\n\n# %%\n\n# a='+'.join(overall_skills.columns)\na='LS+ST+RS+LW+LF+CF+RF+RW+LAM+CAM+RAM+LM+LCM+CM+RCM+RM+LWB+LDM+CDM+RDM+RWB+LB+LCB+CB+RCB+RB+Crossing+Finishing+HeadingAccuracy+ShortPassing+Volleys+Dribbling+Curve+FKAccuracy+LongPassing+BallControl+Acceleration+SprintSpeed+Agility+Reactions+Balance+ShotPower+Jumping+Stamina+Strength+LongShots+Aggression+Interceptions+Positioning+Vision+Penalties+Composure+Marking+StandingTackle+SlidingTackle+GKDiving+GKHandling+GKKicking+GKPositioning+GKReflexes'\n# a= 'Crossing+Finishing+HeadingAccuracy+ShortPassing+Volleys+Dribbling+Curve+FKAccuracy+LongPassing+BallControl+Acceleration+SprintSpeed+Agility+Reactions+Balance+ShotPower+Jumping+Stamina+Strength+LongShots+Aggression+Interceptions+Positioning+Vision+Penalties+Composure+Marking+StandingTackle+SlidingTackle+GKDiving+GKHandling+GKKicking+GKPositioning+GKReflexes'\nosModel = ols(formula='Overall ~' + a, data=overall_skills).fit()\nprint( osModel.summary() )\n\nb='LS+ST+RS+LW+LF+CF+RF+RW+LAM+CAM+RAM+LM+LCM+CM+RCM+RM+LWB+LDM+CDM+RDM+RWB+LB+LCB+CB+RCB+RB+Crossing+Finishing+HeadingAccuracy+ShortPassing+Volleys+Dribbling+Curve+FKAccuracy+LongPassing+BallControl+Acceleration+SprintSpeed+Agility+Reactions+Balance+ShotPower+Jumping+Stamina+Strength+LongShots+Aggression+Interceptions+Positioning+Vision+Penalties+Composure+Marking+StandingTackle+SlidingTackle+GKDiving+GKHandling+GKKicking+GKPositioning+GKReflexes'\n# a= 'Crossing+Finishing+HeadingAccuracy+ShortPassing+Volleys+Dribbling+Curve+FKAccuracy+LongPassing+BallControl+Acceleration+SprintSpeed+Agility+Reactions+Balance+ShotPower+Jumping+Stamina+Strength+LongShots+Aggression+Interceptions+Positioning+Vision+Penalties+Composure+Marking+StandingTackle+SlidingTackle+GKDiving+GKHandling+GKKicking+GKPositioning+GKReflexes'\nosModel1 = ols(formula='Overall ~' + b + '-1', data=overall_skills).fit()\nprint( osModel1.summary() )\n\n# Remove Variables that P-value lower than 0.05:\n\n# %% Rebuild linear model\nd= 'Crossing+Finishing+HeadingAccuracy+ShortPassing+Volleys+Dribbling+Curve+FKAccuracy+LongPassing+BallControl+Acceleration+SprintSpeed+Agility+Reactions+Balance+ShotPower+Jumping+Stamina+Strength+LongShots+Aggression+Interceptions+Positioning+Vision+Penalties+Composure+Marking+StandingTackle+SlidingTackle+GKDiving+GKHandling+GKKicking+GKPositioning+GKReflexes'\nosModel4 = ols(formula='Overall ~' + d + '-1', data=overall_skills).fit()\nprint( osModel4.summary() )\n# remove variable that P-value greater 0.05\n\n# %% Rebuild linear model\ne = 'Finishing+HeadingAccuracy+ShortPassing+Volleys+FKAccuracy+LongPassing+BallControl+Acceleration+SprintSpeed+Agility+Reactions+Balance+ShotPower+Jumping+Stamina+Strength+LongShots+Aggression+Interceptions+Positioning+Vision+Penalties+Composure+Marking+StandingTackle+SlidingTackle+GKDiving+GKHandling+GKKicking+GKPositioning+GKReflexes'\nosModel5 = ols(formula='Overall ~' + e + '-1', data=overall_skills).fit()\nprint( osModel5.summary() )\n# remove variable that P-value greater 0.05\n\n# %% Rebuild linear model\nf = 'Finishing+HeadingAccuracy+ShortPassing+Volleys+FKAccuracy+LongPassing+BallControl+Acceleration+SprintSpeed+Agility+Reactions+Balance+ShotPower+Jumping+Strength+LongShots+Aggression+Interceptions+Positioning+Vision+Penalties+Composure+Marking+StandingTackle+SlidingTackle+GKDiving+GKHandling+GKKicking+GKPositioning+GKReflexes'\nosModel6 = ols(formula='Overall ~' + f +'-1', data=overall_skills).fit()\nprint( osModel6.summary() )\n\n# %% 6. Logistics Regression of preferred foot\n# To predict the preferred foot by using logistics regression\n\nxadmit = fifa[['Crossing','Finishing','HeadingAccuracy','ShortPassing','Volleys','Dribbling','Curve','FKAccuracy','LongPassing','BallControl','Acceleration','SprintSpeed','Agility','Reactions','Balance','ShotPower','Jumping','Stamina','Strength','LongShots','Aggression','Interceptions','Positioning','Vision','Penalties','Composure','Marking','StandingTackle','SlidingTackle','GKDiving','GKHandling','GKKicking','GKPositioning','GKReflexes']]\nyadmit = fifa['Preferred_Foot']\nprint(type(xadmit))\nprint(type(yadmit))\n\nx_trainAdmit, x_testAdmit, y_trainAdmit, y_testAdmit = train_test_split(xadmit, yadmit)\n\nfootlogit = LogisticRegression()\nfootlogit.fit(x_trainAdmit, y_trainAdmit)\nfootlogit.predict(x_testAdmit)\nprint('Logit model accuracy (with the test set):', footlogit.score(x_testAdmit, y_testAdmit))\n\nprint('x_trainAdmit type',type(x_trainAdmit))\nprint('x_trainAdmit shape',x_trainAdmit.shape)\nprint('x_testAdmit type',type(x_testAdmit))\nprint('x_testAdmit shape',x_testAdmit.shape)\nprint('y_trainAdmit type',type(y_trainAdmit))\nprint('y_trainAdmit shape',y_trainAdmit.shape)\nprint('y_testAdmit type',type(y_testAdmit))\nprint('y_testAdmit shape',y_testAdmit.shape)\n\n# %% logitstic regression\nfrom sklearn.linear_model import LogisticRegression\n\nadmitlogit = LogisticRegression() # instantiate\nadmitlogit.fit(x_trainAdmit, y_trainAdmit)\nadmitlogit.predict(x_testAdmit)\nprint('Logit model accuracy (with the test set):', round(admitlogit.score(x_testAdmit, y_testAdmit),3))\n\n#%%\nprint(admitlogit.predict_proba(x_trainAdmit[:8]))\nprint(admitlogit.predict_proba(x_testAdmit[:8]))\n\n#%%\ny_true, y_pred = y_testAdmit, admitlogit.predict(x_testAdmit)\nprint(classification_report(y_true, y_pred))\na = classification_report(y_true, y_pred)\naccuracy = a.split()[a.split().index('accuracy')+1]\n\nprint('The accuracy of logistics regression is', accuracy)\n\ncof = admitlogit.coef_.tolist()[0]\nlow2highc = sorted(cof)\nname = []\ncoff = []\nfor i in range(len(low2highc)):\n x = len(low2highc)-i-1\n name.append(xadmit.columns[cof.index(low2highc[x])])\n coff.append(str(round(low2highc[x]*100, 3)) + '%')\n\nlog = pd.DataFrame(name, coff)\n # print(xadmit.columns[cof.index(low2highc[x])], str(round(low2highc[x]*100, 3)) + '%')\n\n\n#%% 7. KNN of reputation.\n##knn model on predict reputation.\n##variables: skill scores\nxfifa=fifa.iloc[:,53:87]\nyfifa=fifa['International_Reputation']\nxsfifa = pd.DataFrame( scale(xfifa), columns=xfifa.columns ) \nysfifa = yfifa.copy()\nX_train, X_test, y_train, y_test = train_test_split(xsfifa, ysfifa, test_size = 0.25, random_state=2019)\n\n\n#%%\nrmse_val = [] \nfor K in range(15):\n K=K+1\n model = neighbors.KNeighborsRegressor(n_neighbors = K)\n\n model.fit(X_train, y_train) \n pred=model.predict(X_test) \n error = sqrt(mean_squared_error(y_test,pred))\n rmse_val.append(error)\n print('RMSE value for k= ' , K , 'is:', error)\n\n\n#%%\ncurve = pd.DataFrame(rmse_val)\ncurve.plot()\n\n\n\n#%%\nk=9\nknn_scv = KNeighborsClassifier(n_neighbors=k)\nscv_results = cross_val_score(knn_scv, xsfifa, ysfifa, cv=5)\nprint(scv_results) \nnp.mean(scv_results)\n\n#%%\nimport pandas as pd\ny_true=y_test\nknn_scv = neighbors.KNeighborsRegressor(n_neighbors = 15)\nmodel.fit(X_train, y_train) \ny_pred=model.predict(X_test) \npd.crosstab(y_true,round(pd.Series(y_pred)),rownames=['ACTUAL'],colnames=['PRED'])\n\n#%% 8. KNN of Preferred foot\n##Preferred foot-ability\n\n#%%\ndef P_foot (row):\n if row['Preferred_Foot'] == 'Left' :\n return 0\n if row['Preferred_Foot'] == 'Right':\n return 1\n\nfifa['P_foot']=fifa.apply (lambda row: P_foot(row), axis=1)\n\n#%%\nxfifa1=fifa.iloc[:,53:87]\nyfifa1=fifa['P_foot']\nxsfifa1 = pd.DataFrame( scale(xfifa1), columns=xfifa1.columns ) \nysfifa1 = yfifa1.copy()\nX_train1, X_test1, y_train1, y_test1 = train_test_split(xsfifa1, ysfifa1, test_size = 0.25, random_state=2019)\n\n#%%\nrmse_val = [] \nfor K in range(15):\n K=K+1\n model = neighbors.KNeighborsRegressor(n_neighbors = K)\n\n model.fit(X_train1, y_train1) \n pred=model.predict(X_test1) \n error = sqrt(mean_squared_error(y_test1,pred))\n rmse_val.append(error)\n print('RMSE value for k= ' , K , 'is:', error)\n\n#%%\ncurve = pd.DataFrame(rmse_val)\ncurve.plot()\n\n#%%\n##k=15\nk=15\nknn_scv1 = KNeighborsClassifier(n_neighbors=k)\nscv_results1 = cross_val_score(knn_scv1, xsfifa1, ysfifa1, cv=5)\nprint(scv_results1) \nnp.mean(scv_results1)\n\n#%%\nfrom sklearn.metrics import classification_report\ny_true=y_test1\nmodel = neighbors.KNeighborsRegressor(n_neighbors = 15)\nmodel.fit(X_train1, y_train1) \ny_pred=model.predict(X_test1) \n\nprint(classification_report(y_true, y_pred.round()))\n\n#%%\nimport pandas as pd\ny_true=y_test1\nmodel = neighbors.KNeighborsRegressor(n_neighbors = 15)\nmodel.fit(X_train1, y_train1) \ny_pred=model.predict(X_test1) \npd.crosstab(y_true,round(pd.Series(y_pred)),rownames=['ACTUAL'],colnames=['PRED'])\n\n\n# %%\n","sub_path":"Project/FIFA.py","file_name":"FIFA.py","file_ext":"py","file_size_in_byte":18318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"139473269","text":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nimport os\nimport argparse\nfrom time import gmtime, strftime\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\nimport numpy as np\n\nfrom utils import *\n\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\ndef run_validation(model, valid_dataloader):\n model.eval()\n \n loss_func = nn.CrossEntropyLoss()\n acc_list, loss_list = [], []\n with torch.no_grad():\n for i, (inputs, labels) in enumerate(tqdm(valid_dataloader)):\n inputs, labels = inputs.float().to(device), labels.to(device)\n preds= model(inputs)\n pred_idx = preds.max(1).indices\n acc = (pred_idx == labels).sum().item() / labels.size(0)\n acc_list.append(acc)\n loss = loss_func(preds, labels).item()\n loss_list.append(loss)\n\n valid_loss = np.array(loss_list).mean()\n valid_acc = np.array(acc_list).mean()\n \n return valid_loss, valid_acc\n\n\ndef run_pretrain(args):\n print(args)\n torch.set_num_threads(args.n_workers)\n \n model_type = 'mobilenet_v2_torchhub' \n pretrained = True # load imagenet weight\n experiment_dir = 'pretrained_{}'.format(model_type) if args.experiment_dir is None else args.experiment_dir\n os.mkdir(experiment_dir)\n checkpoint = None\n input_size = 224\n n_classes = 120\n \n log = open(experiment_dir + '/pretrain.log', 'w')\n \n model = create_model(model_type=model_type, pretrained=pretrained, n_classes=n_classes,\n input_size=input_size, checkpoint=checkpoint)\n model = model.to(device)\n print(model)\n # count_flops(model, device=device)\n\n train_dataset = TrainDataset('./data/stanford-dogs/Processed/train')\n train_dataloader = DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True)\n valid_dataset = EvalDataset('./data/stanford-dogs/Processed/valid')\n valid_dataloader = DataLoader(valid_dataset, batch_size=args.batch_size, shuffle=False)\n\n criterion = nn.CrossEntropyLoss()\n optimizer = torch.optim.SGD(model.parameters(), lr=args.learning_rate, momentum=0.9, weight_decay=args.weight_decay)\n\n best_valid_acc = 0.0\n for epoch in range(args.n_epochs):\n print('Start training epoch {}'.format(epoch))\n loss_list = []\n\n # train\n model.train()\n for i, (inputs, labels) in enumerate(tqdm(train_dataloader)):\n optimizer.zero_grad()\n inputs, labels = inputs.float().to(device), labels.to(device)\n preds = model(inputs)\n loss = criterion(preds, labels)\n loss_list.append(loss.item())\n loss.backward()\n optimizer.step()\n \n # validation\n valid_loss, valid_acc = run_validation(model, valid_dataloader)\n train_loss = np.array(loss_list).mean()\n print('Epoch {}: train loss {:.4f}, valid loss {:.4f}, valid acc {:.4f}'.format\n (epoch, train_loss, valid_loss, valid_acc))\n log.write('Epoch {}: train loss {:.4f}, valid loss {:.4f}, valid acc {:.4f}\\n'.format\n (epoch, train_loss, valid_loss, valid_acc))\n \n # save\n if valid_acc > best_valid_acc:\n best_valid_acc = valid_acc\n torch.save(model.state_dict(), experiment_dir + '/checkpoint_best.pt')\n\n log.close()\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Example code for pruning MobileNetV2')\n\n parser.add_argument('--experiment_dir', type=str, default=None,\n help='directory containing the pretrained model')\n parser.add_argument('--checkpoint_name', type=str, default='checkpoint_best.pt',\n help='checkpoint of the pretrained model')\n \n # finetuning parameters\n parser.add_argument('--n_workers', type=int, default=16,\n help='number of threads')\n parser.add_argument('--n_epochs', type=int, default=180,\n help='number of epochs to train the model')\n parser.add_argument('--learning_rate', type=float, default=1e-4)\n parser.add_argument('--weight_decay', type=float, default=0.0)\n parser.add_argument('--batch_size', type=int, default=32,\n help='input batch size for training and inference')\n\n args = parser.parse_args()\n return args\n\n \nif __name__ == '__main__':\n args = parse_args()\n run_pretrain(args)\n","sub_path":"examples/model_compress/pruning/legacy/mobilenetv2_end2end/pretrain.py","file_name":"pretrain.py","file_ext":"py","file_size_in_byte":4522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"645085828","text":"import re\nfrom ..module_helper import ModuleHelper\n\n\nclass WeatherHelper(ModuleHelper):\n \"\"\"A class which parses and interprets commands to a Weather object.\n\n Attributes:\n weather_re: a dictionary from string labels to lists of regular\n expressions which match commands with similar meanings (e.g.\n 'What's the weather today?' and 'What's the weather outside\n now')\n \"\"\"\n\n def __init__(self):\n ModuleHelper.__init__(self)\n self.weather_re = {\n # weather today in the current location\n \"current today\": [re.compile('[A-Z|a-z|\\'| ]*weather (outside )?\\\n(going to be )?(like )?today\\??'),\n re.compile('[A-Z|a-z|\\'| ]*weather (outside )?\\\n(now|like)\\??'), ],\n # weather tomorrow in the current location\n \"current tomorrow\": [re.compile('[A-Z|a-z|\\'| ]*weather (going to \\\nbe )?(like )?tomorrow\\??'), ],\n # weather today in an external location\n \"external today\": [re.compile('[A-Z|a-z|\\'| ]*weather \\\n(going to be )?(like )?today in [A-Z|a-z|\\'| ]+\\??'),\n re.compile('[A-Z|a-z|\\'| ]*weather now in \\\n[A-Z|a-z|\\'| ]+\\??'),\n re.compile('[A-Z|a-z|\\'| ]*weather in \\\n[A-Z|a-z|\\'| ]+ (going to be )?(like )?today\\??'),\n re.compile('[A-Z|a-z|\\'| ]*weather in \\\n[A-Z|a-z|\\'| ]+ now\\??'), ],\n # weather tomorrow in an external location\n \"external tomorrow\": [re.compile('[A-Z|a-z|\\'| ]*weather (going to \\\nbe )?(like )?tomorrow in [A-Z|a-z|\\'| ]+\\??'),\n re.compile('[A-Z|a-z|\\'| ]*weather in \\\n[A-Z|a-z|\\'| ]+( going to be)? tomorrow\\??'), ],\n # weather on specified date in current location\n \"current specific\": [re.compile('[A-Z|a-z|\\'| ]*weather (going to \\\nbe )(like )??on (monday|tuesday|wednesday|thursday|friday|saturday|sunday)\\??'), ],\n # weather on specified date in external location\n \"external specific\": [re.compile('[A-Z|a-z|\\'| ]*weather (going to \\\nbe )(like )??on (monday|tuesday|wednesday|thursday|friday|saturday|sunday) in \\\n[A-Z|a-z|\\'| ]+\\??'),\n re.compile('[A-Z|a-z|\\'| ]*weather (going to \\\nbe )?(like )?in [A-Z|a-z|\\'| ]+ on (monday|tuesday|wednesday|thursday|friday|saturday\\\n|sunday)\\??')],\n }\n\n def parse_command(self, command):\n \"\"\"Transforms a command into a label and possibly a location.\n\n Args:\n command: string, command entered by user\n\n Returns:\n a label (if any is matched) which describes what the command is\n requesting, along with a location if the command is requesting\n weather information on a location that's not the current\n location (and None otherwise). If no regexp is matched,\n (None, None) is returned.\n \"\"\"\n for label in self.weather_re:\n for regexp in self.weather_re[label]:\n if regexp.fullmatch(command):\n if \"external\" in label and \"specific\" not in label:\n splits = command.split(\"in \")[1].split(\" \")\n if len(splits) == 1 or len(splits) == 2:\n external_location = splits[0]\n else:\n external_location = \" \".join(splits[0:-1])\n if \"going to be\" in external_location:\n external_location = external_location.split(\" going to be\")[0]\n elif \" like\" in external_location:\n external_location = external_location.split(\" like\")[0]\n return label, external_location\n elif label == \"external specific\":\n if command.find(\" on \") < command.find(\" in \"):\n split_on = command.split(\" on \")[1]\n split_in = split_on.split(\" in \")\n day = self.weekday_to_int[split_in[0]]\n external_location = split_in[1].replace('?', '')\n return label, (day, external_location)\n else:\n split_in = command.split(\" in \")[1]\n split_on = split_in.split(\" on \")\n day = self.weekday_to_int[split_on[1]]\n external_location = split_on[0].replace('?', '')\n return label, (day, external_location)\n elif label == \"current specific\":\n day = self.weekday_to_int[\n command.split(\"on \")[1].replace('?', '')]\n return label, day\n else:\n return label, None\n return None, None\n","sub_path":"modules/weather/weather_helper.py","file_name":"weather_helper.py","file_ext":"py","file_size_in_byte":4979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"372094043","text":"import csv\r\nfrequency = {}\r\nfilename= input()\r\nwith open(filename, 'r') as csvfile:\r\n csvreader = csv.reader(csvfile)\r\n line = next(csvreader)\r\n for word in line:\r\n if word in frequency:\r\n frequency[word] += 1\r\n else:\r\n frequency[word] = 1\r\n\r\nfor i in frequency:\r\n print(i, frequency[i])","sub_path":"Lab9.10.py","file_name":"Lab9.10.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"599316213","text":"import matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\nfrom scipy.linalg import solve_banded\n\nleft = 0\nright = np.pi\n\na = 0.5\nt_c = 5\nA = 1\nalpha = 2\nB = 0\n\n\ndef phi(x):\n return A * np.sin(alpha * x)\n\n\ndef psi_left(time):\n return 0\n\n\ndef psi_right(time):\n return B\n\n\n\ndef differential_equation(time_div, x_div):\n arr = np.zeros(shape=(time_div + 1, x_div + 1))\n\n x_values = np.linspace(left, right, x_div + 1)\n t_values = np.linspace(0, t_c, time_div + 1)\n\n for t_index, t_value in enumerate(t_values):\n arr[t_index, 0] = psi_left(t_value)\n arr[t_index, x_div] = psi_right(t_value)\n\n for x_index, x_value in enumerate(x_values):\n arr[0, x_index] = phi(x_value)\n\n h = (right - left) / x_div\n k = t_c / time_div\n coefficient = a * a * k / h / h\n print(\"wspolczynnik = {}\".format(coefficient))\n\n coef = h * h / a * a / k\n middle_coef = 2 + coef\n\n assert x_div > 3\n top, mid, bot = [0, 0], [1, middle_coef], [-1, -1]\n for t in range(2, x_div - 1):\n top.append(-1)\n mid.append(middle_coef)\n bot.append(-1)\n\n top.extend([-1, -1])\n mid.extend([middle_coef, 1])\n bot.extend([0, 0])\n\n band_matrix = np.array([top, mid, bot])\n\n for t in range(1, time_div + 1):\n vector = np.zeros(x_div + 1)\n\n vector[0] = arr[t, 0]\n vector[x_div] = arr[t, x_div]\n\n for i in range(1, x_div):\n vector[i] = arr[t - 1, i] * coef\n\n result = solve_banded((1, 1), band_matrix, vector)\n arr[t] = result\n print(result)\n\n return [x_values, t_values, arr]\n\n\ndef draw(data):\n x, y = np.meshgrid(data[0], data[1])\n\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n surf = ax.plot_surface(x, y, data[2])\n ax.set_xlabel(\"oś X\")\n ax.set_ylabel(\"czas\")\n ax.set_zlabel(\"wartość\")\n\n plt.show()\n\n\nif __name__ == '__main__':\n dif_eq_data = differential_equation(500, 40)\n draw(dif_eq_data)\n","sub_path":"lab8/back.py","file_name":"back.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"613652009","text":"import sublime, sublime_plugin, re, urllib, json\n\nclass ShowLocalWeatherCommand(sublime_plugin.WindowCommand):\n def getWindDir(self, deg) :\n val = round((deg - 11.25) / 22.5)\n arr = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW']\n windDirStr = arr[val % 16]\n return windDirStr\n\n\n def run(self):\n endpoint = 'http://metservice.com/publicData/oneMinObs_christchurch'\n page_html = urllib.request.urlopen(endpoint).read().decode('utf-8')\n data = json.loads(page_html) \n windDirDeg = data['windDirection']\n weatherOutput = 'Temp: ' + str(data['temperature']) + ' Wind: ' + str(data['windSpeed']) + '/' + str(data['windGustSpeed']) + ' ' + self.getWindDir(windDirDeg)\n sublime.status_message(weatherOutput)\n\n","sub_path":"GetWeatherCommand.py","file_name":"GetWeatherCommand.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"31296875","text":"import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport face_recognition\nimport time\nimport math\nimport sys\n\nvideo_capture = cv2.VideoCapture(1)\n\nwidth = video_capture.get(cv2.CAP_PROP_FRAME_WIDTH )\nheight = video_capture.get(cv2.CAP_PROP_FRAME_HEIGHT )\n\nbgSubThreshold = 50\nlearningRate = 0\nvalue_1 = 0\n\nfound_face = False\n\nbgModel = cv2.createBackgroundSubtractorMOG2(0, bgSubThreshold)\n\ndef removeBG(frame):\n fgmask = bgModel.apply(frame,learningRate=learningRate)\n # kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))\n # res = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)\n\n kernel = np.ones((3, 3), np.uint8)\n \n fgmask = cv2.erode(fgmask, kernel, iterations=1)\n res = cv2.bitwise_and(frame, frame, mask=fgmask)\n return res\n\ndef calculateFingers(res,drawing): # -> finished bool, cnt: finger count\n # convexity defect\n hull = cv2.convexHull(res, returnPoints=False)\n if len(hull) > 3:\n defects = cv2.convexityDefects(res, hull)\n if type(defects) != type(None): # avoid crashing. (BUG not found)\n\n cnt = 0\n avaragePoints = 0\n\n for i in range(defects.shape[0]): # calculate the angle\n s, e, f, d = defects[i][0]\n start = tuple(res[s][0])\n end = tuple(res[e][0])\n far = tuple(res[f][0])\n a = math.sqrt((end[0] - start[0]) ** 2 + (end[1] - start[1]) ** 2)\n b = math.sqrt((far[0] - start[0]) ** 2 + (far[1] - start[1]) ** 2)\n c = math.sqrt((end[0] - far[0]) ** 2 + (end[1] - far[1]) ** 2)\n angle = math.acos((b ** 2 + c ** 2 - a ** 2) / (2 * b * c)) # cosine theorem\n if angle <= math.pi / 2: # angle less than 90 degree, treat as fingers\n cnt += 1\n\n avaragePoints += angle\n avaragePoints = avaragePoints / cnt\n\n cv2.circle(drawing, far, 8, [211, 84, 0], -1)\n return True, cnt, far\n return False, 0, 0\n\ncounter = 0\nfinger_counter = 0\n\ndef send_pos(fingers, hand_x, hand_y, countours, w_new, h_new):\n global counter\n global finger_counter\n # print(fingers, w_new, h_new)\n if countours > 0 and w_new > 60 and h_new > 70 and w_new < 230 and h_new < 330:\n if hand_x < 25:\n position = \"left\"\n elif hand_x > 75:\n position = \"right\"\n\n if fingers >= 3:\n finger_counter = finger_counter + 1\n if finger_counter == 5:\n print(\"animation \", hand_x, hand_y)\n \n if finger_counter == 15:\n print(\"check\")\n \n \n if finger_counter > 15 and fingers == 0 and countours > 0 and finger_counter < 40:\n if position == \"left\":\n print(\"left\")\n finger_counter = 0\n\n elif position == \"right\":\n print(\"right\")\n finger_counter = 0\n\n elif finger_counter > 40:\n finger_counter = 0\n counter = 0\n print(\"reset 1\")\n\n\n elif countours > 0:\n counter = counter + 1\n if counter == 5:\n finger_counter = 0\n counter = 0\n print(\"reset 2\")\n \n else:\n finger_counter = 0\n counter = 0\n print(\"reset 3\")\n \n\n sys.stdout.flush()\n time.sleep( 0.05 )\n\n\n\nwhile True:\n ret, original = video_capture.read()\n\n original = cv2.bilateralFilter(original, 5, 50, 100) # smoothing filter\n original = cv2.flip(original, 1) # flip the frame horizontally\n\n \n # Create a big rectangle cus we don't need that\n # height, width, channels = original.shape\n # upper_left = (int(width / 4), int(height))\n # bottom_right = (int(width * 3 / 4), int(0))\n # cv2.rectangle(original, upper_left, bottom_right, (255, 0, 255), cv2.FILLED)\n\n\n # third_upper_left = (int(0), int(0))\n # third_bottom_right = (int(width), int(height / 3))\n # cv2.rectangle(original, third_upper_left, third_bottom_right, (0, 255, 255), cv2.FILLED)\n\n img = removeBG(original)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n blur = cv2.GaussianBlur(gray, (25, 25), 0)\n cv2.imshow('blur', blur)\n ret, thresh = cv2.threshold(blur, 50, 255, cv2.THRESH_BINARY)\n\n _,contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n length = len(contours)\n maxArea = -1\n if length > 0:\n for i in range(length): # find the biggest contour (according to area)\n temp = contours[i]\n area = cv2.contourArea(temp)\n \n c = max(temp, key = cv2.contourArea)\n x,y,w,h = cv2.boundingRect(c)\n \n \n if area > maxArea:\n maxArea = area\n ci = i\n\n res = contours[ci]\n \n\n hull = cv2.convexHull(res)\n drawing = np.zeros(img.shape, np.uint8)\n\n bound_x,bound_y,bound_w,bound_h = cv2.boundingRect(res)\n cv2.rectangle(drawing, (bound_x, bound_y), (bound_x+bound_w, bound_y+bound_h), (0, 255, 0), 2)\n\n\n cv2.drawContours(drawing, [res], 0, (0, 255, 0), 2)\n cv2.drawContours(drawing, [hull], 0, (0, 0, 255), 3)\n isFinishCal,cnt,avaragePoints = calculateFingers(res,drawing)\n\n if isFinishCal is True:\n # print(avaragePoints)\n # print(width, height)\n hand_x = 100/width*avaragePoints[0]\n hand_y = 100/height*avaragePoints[1]\n\n # print(position)\n cv2.rectangle(original,(x,y),(x+w,y+h),(0,255,0),2)\n send_pos(cnt,hand_x, hand_y, length, bound_w, bound_h)\n else:\n finger_counter = 0\n counter = 0\n \n\n\n cv2.imshow('output', drawing)\n \n cv2.imshow('original', original)\n # cv2.imshow('frame2', frame)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n\nvideo_capture.release()\ncv2.destroyAllWindows()","sub_path":"plugins/hand_gesture.py","file_name":"hand_gesture.py","file_ext":"py","file_size_in_byte":5996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"137010622","text":"from collections import Counter\n\nimport numpy as np\n\n\nclass Node:\n def __init__(self, idx):\n self.idx = idx\n self.degree = 0\n self.nodes_out = Counter()\n\n def link_it_to(self, node_):\n self.degree += 1\n self.nodes_out[node_.idx] += 1\n\n def not_link_to(self, node_):\n if node_.idx in self.nodes_out:\n self.nodes_out.pop(node_.idx)\n return 1\n # no such link exists\n return 0\n\n def remove(self):\n self.degree = 0\n self.nodes_out.clear()\n\n def __repr__(self):\n str = 'Node {} with degree {}, connected to ('.format(self.idx, self.degree)\n for k, v in self.nodes_out.items():\n str += \"(->%d x %d), \" % (k, v)\n str += ')\\n'\n return str\n\n\nclass Network:\n def __init__(self, node_nums, edge_nums):\n self.node_nums = node_nums\n self.edge_nums = edge_nums\n self.nodes = [Node(i) for i in range(self.node_nums)]\n self.remove = None\n self.belongs = None\n self.degrees = None\n\n def initialize(self):\n \"\"\"\n randomly generate a graph\n :return:\n \"\"\"\n return\n\n def degree_distrib(self):\n \"\"\"\n solve for degree distribution\n :return:\n \"\"\"\n degrees = np.array([n.degree for n in self.nodes])\n self.degrees = degrees\n return degrees\n\n def bfs(self):\n # cluster number belongings\n self.belongs = -1.0 * np.ones(self.node_nums)\n while True:\n indices = np.where(self.belongs == -1)[0]\n if len(indices) == 0:\n break\n # print('Searching from root %d' % indices[0])\n self._bfs(indices[0], indices[0])\n\n return self.belongs\n\n def _bfs(self, idx, root):\n # recursive function\n self.belongs[idx] = root\n nexts = self.nodes[idx].nodes_out.keys()\n for i in nexts:\n if self.belongs[i] == -1:\n self.belongs[i] = root\n self._bfs(i, root)\n return\n\n def remove_nodes(self, fraction):\n # set last belongings to be invalid\n self.belongs = None\n self.degrees = None\n # random select nodes\n candidate = np.where(self.remove == False)[0]\n remove_num = min(int(fraction * self.node_nums), len(candidate))\n # print(len(candidate), remove_num)\n\n remove = np.random.choice(candidate, remove_num, replace=False)\n for i in remove:\n # print('Removing %d' % i)\n dst_nodes = list(self.nodes[i].nodes_out.keys())\n for d in dst_nodes:\n self.nodes[d].not_link_to(self.nodes[i])\n self.nodes[i].remove()\n self.remove[i] = True\n\n def __repr__(self):\n str = \"Nodes: \\n\"\n _ellipsis = False\n for idx, node in enumerate(self.nodes):\n if 5 < idx < self.node_nums - 5:\n if not _ellipsis:\n str += '...\\n'\n _ellipsis = True\n continue\n\n str += \"{}\".format(node)\n return str\n\n\nclass ERNetwork(Network):\n def __init__(self, node_nums, lam):\n edge_nums = int(node_nums * lam // 2)\n super(ERNetwork, self).__init__(node_nums, edge_nums)\n self.lam = lam\n\n def initialize(self):\n # then random generate links, allow duplicate ones\n src_nodes = np.random.choice(self.node_nums, self.edge_nums)\n dst_nodes = np.random.choice(self.node_nums, self.edge_nums)\n\n for e in range(self.edge_nums):\n src = src_nodes[e]\n dst = dst_nodes[e]\n self.nodes[src].link_it_to(self.nodes[dst])\n self.nodes[dst].link_it_to(self.nodes[src])\n\n self.remove = np.array([False for _ in range(self.node_nums)])\n\n\nclass BANetwork(Network):\n def __init__(self, node_nums, gamma, maxk, mink=1):\n # calculate constant c\n self.gamma = gamma\n self.mink = mink\n self.maxk = maxk\n kp = np.power(np.arange(mink, maxk + 1), -gamma)\n self.c = 1.0 / np.sum(kp)\n self.kp = kp * self.c\n self.dk = np.sum(self.kp) - np.cumsum(self.kp) + self.kp\n super(BANetwork, self).__init__(node_nums, None)\n\n def initialize(self):\n \"\"\"\n https://en.wikipedia.org/wiki/Barab%C3%A1si%E2%80%93Albert_model\n :return:\n \"\"\"\n r = np.random.rand(self.node_nums)\n self._degrees = np.digitize(r, self.dk) - 1 + self.mink\n self.edge_nums = self._degrees.sum() // 2\n\n _degree_sequence = self._degrees.copy()\n\n for i in range(self.node_nums):\n _prob = _degree_sequence[i] * _degree_sequence\n \n _yes = np.random.rand(self.node_nums) < _prob\n for j in np.where(_yes)[0]:\n self.nodes[i].link_it_to(self.nodes[j])\n # self.nodes[j].link_it_to(self.nodes[i])\n self.remove = np.array([False for _ in range(self.node_nums)])\n return\n\n\nif __name__ == '__main__':\n net = BANetwork(10, gamma=2.1, maxk=5)\n print(net.edge_nums)\n","sub_path":"chenyifeng/codes/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"579696459","text":"from api import get_player_info, get_player_id, get_players, get_games_today, get_games_results\nfrom config import Config\nfrom datetime import datetime as dt\n\nimport discord\nfrom discord.ext import commands\n\n\nclass Games(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command(name=\"results\")\n async def results(self, ctx):\n\n await ctx.send(embed=results())\n\n @commands.command(name=\"games_today\")\n async def games_today(self, ctx):\n\n await ctx.send(embed=games_today())\n\n\ndef setup(bot):\n bot.add_cog(Games(bot))\n\n\ndef suffix(d):\n return 'th' if 11 <= d <= 13 else {1: 'st', 2: 'nd', 3: 'rd'}.get(d % 10, 'th')\n\n\ndef custom_strftime(format, t):\n return t.strftime(format).replace('{S}', str(t.day) + suffix(t.day))\n\n\ndef games_today():\n try:\n games_today = get_games_today()\n\n embed = discord.Embed(\n title=custom_strftime('**%B {S}, %Y**', dt.now()), # Month_name DD, YYYY\n description='\\u200b',\n color=discord.Color.blue()\n )\n\n for i in games_today:\n embed.add_field(name='{} @ {}'.format(i['VISITOR_TEAM'], i['HOME_TEAM']),\n value='({}) - ({})'.format(i['VISITOR_TEAM_RECORD'], i['HOME_TEAM_RECORD']),\n inline=False)\n\n return embed\n\n except Exception as e:\n print(e)\n\n\ndef results():\n try:\n results = get_games_results()\n\n embed = discord.Embed(\n title='Results for {}'.format(Config.YESTERDAY),\n description='\\u200b',\n color=discord.Color.blue()\n )\n\n for i in results:\n embed.add_field(name='{} @ {}'.format(i['AWAY_TEAM'], i['HOME_TEAM']),\n value='{} - {}'.format(i['AWAY_POINTS'], i['HOME_POINTS']),\n inline=False)\n\n return embed\n\n except Exception as e:\n print(e)","sub_path":"cogs/games.py","file_name":"games.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"365852348","text":"\"\"\"\ncoding: utf-8\n@Time : 2019/7/1 13:36\n@Author : Simon Lang\n\n\"\"\"\nimport numpy as np\nimport sys\nsys.path.append(\"../util\")\nimport util.read as read\nimport operator\n\n\ndef lfm_train(train_data,F,alpha,beta,step):\n \"\"\"\n Args:\n :param train_data: 训练数据集\n :param F: use vector len ,item vector len\n :param alpha: regularization factor 正则化参数\n :param beta: learning rate\n :param step: iteration num\n :return:\n dict:key itemid, value:list\n dict:key userid, value:list\n \"\"\"\n user_vec = {}\n item_vec = {}\n for step_index in range(step):\n for data_instance in train_data:\n userid, itemid, label = data_instance\n if userid not in user_vec:\n user_vec[userid] = init_model(F)#初始化\n if itemid not in item_vec:\n item_vec[itemid] = init_model(F)\n delta = label - model_predict(user_vec[userid], item_vec[userid])\n for index in range(F):\n user_vec[userid][index] +=beta*(delta*item_vec[itemid][index] - alpha*user_vec[userid][index])\n item_vec[itemid][index] +=beta*(delta*user_vec[userid][index] - alpha*item_vec[itemid][index])\n beta = beta*0.9 #衰减学习率\n return user_vec, item_vec\n\n\n#初始化函数\ndef init_model(vector_len):\n \"\"\"\n Args:\n :param vector_len:the len of vector\n :return:\n a ndarray(一种列表)\n \"\"\"\n return np.random.randn(vector_len)\n\n\ndef model_predict(user_vector,item_vector):\n \"\"\"\n user_vector and item_vector distance\n :param user_vector: model produce user vector\n :param item_vector: model produce item vector\n :return: a num 用数字表述出用户对物品的喜爱程度\n \"\"\"\n res = np.dot(user_vector,item_vector)/(np.linalg.norm(user_vector)*np.linalgnorm(item_vector)) #内积/模\n return res\n\n\ndef model_train_process():\n \"\"\"\n test lfm model train\n :return:\n \"\"\"\n train_data = read.get_train_data('../data/ratings.txt')\n user_vec,item_vec = lfm_train(train_data,50,0.01,0.1,50)\n print(give_recom_result(user_vec,item_vec,'2'))\n for userid in user_vec :\n recom_result = give_recom_result(user_vec,item_vec,userid)\n #ana_recom_result(train_data,'24',recom_result)\n # print(user_vec[\"1\"])\n # # print(item_vec[\"720\"])\n\n\n\ndef give_recom_result(user_vec,item_vec,userid):\n \"\"\"\n use lfm model result give fix userid recom result\n :param user_vec: lfm model result\n :param item_vec: lfm model result\n :param userid: fix userid\n :return: a list:[(itemid,score),(itemid1,score1)]\n \"\"\"\n fix_num = 10\n if userid not in user_vec:\n return []\n record = {}\n recom_list = []\n user_vector = user_vec[userid]\n for itemid in item_vec:\n item_vector = item_vec[itemid]\n res = np.dot(user_vector,item_vector)/(np.linalg.norm(user_vector)*np.linalg.norm(item_vector))\n record[itemid] = res\n for zuhe in sorted(record.iteritems(),key=operator.itemgetter(1),reverse=True)[:fix_num]:\n itemid = zuhe[0]\n score = round(zuhe[1],3)\n recom_list.append((itemid,score))\n return recom_list\n\n\n#验证推荐模型的结果\ndef ana_recom_result(train_data,userid,recom_list):\n \"\"\"\n debug recom result for userid\n :param train_data:train data for lfm model\n :param userid: fix userid\n :param recom_list: recom result by lfm\n :return:\n \"\"\"\n item_info = read.get_item_info('../data/movies.txt')\n for data_instance in train_data:\n tmp_userid, itemid, label = data_instance\n if tmp_userid == userid and label ==1:\n print(\"recom result\")\n for zuhe in recom_list:\n print(item_info[zuhe[0]])\n\nif __name__ == \"__main__\":\n model_train_process()","sub_path":"production/lfm.py","file_name":"lfm.py","file_ext":"py","file_size_in_byte":3813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"274013793","text":"#\n# @lc app=leetcode id=990 lang=python3\n#\n# [990] Satisfiability of Equality Equations\n#\n# https://leetcode.com/problems/satisfiability-of-equality-equations/description/\n#\n# algorithms\n# Medium (38.55%)\n# Total Accepted: 4.6K\n# Total Submissions: 11.9K\n# Testcase Example: '[\"a==b\",\"b!=a\"]'\n#\n# Given an array equations of strings that represent relationships between\n# variables, each string equations[i] has length 4 and takes one of two\n# different forms: \"a==b\" or \"a!=b\".  Here, a and b are lowercase letters (not\n# necessarily different) that represent one-letter variable names.\n#\n# Return true if and only if it is possible to assign integers to variable\n# names so as to satisfy all the given equations.\n#\n#\n#\n#\n#\n#\n#\n# Example 1:\n#\n#\n# Input: [\"a==b\",\"b!=a\"]\n# Output: false\n# Explanation: If we assign say, a = 1 and b = 1, then the first equation is\n# satisfied, but not the second. There is no way to assign the variables to\n# satisfy both equations.\n#\n#\n#\n# Example 2:\n#\n#\n# Input: [\"b==a\",\"a==b\"]\n# Output: true\n# Explanation: We could assign a = 1 and b = 1 to satisfy both equations.\n#\n#\n#\n# Example 3:\n#\n#\n# Input: [\"a==b\",\"b==c\",\"a==c\"]\n# Output: true\n#\n#\n#\n# Example 4:\n#\n#\n# Input: [\"a==b\",\"b!=c\",\"c==a\"]\n# Output: false\n#\n#\n#\n# Example 5:\n#\n#\n# Input: [\"c==c\",\"b==d\",\"x!=z\"]\n# Output: true\n#\n#\n#\n#\n# Note:\n#\n#\n# 1 <= equations.length <= 500\n# equations[i].length == 4\n# equations[i][0] and equations[i][3] are lowercase letters\n# equations[i][1] is either '=' or '!'\n# equations[i][2] is '='\n#\n#\n#\n#\n#\n#\n#\n#\n\n\nclass Solution:\n\n def equationsPossible(self, equations) -> bool:\n if not equations:\n return True\n equals = {}\n for i in range(26):\n c = chr(i+ord('a'))\n equals[c] = {c}\n # first calculate all equals dict\n for e in equations:\n x = e[0]\n y = e[3]\n equal = True if e[1] == '=' else False\n if equal:\n newset = equals[x].union(equals[y])\n for ele in newset:\n equals[ele] = newset\n\n # then check if any diff in equal set\n for e in equations:\n x = e[0]\n y = e[3]\n equal = True if e[1] == '=' else False\n if not equal and x in equals[y]:\n return False\n return True\n\n\nif __name__ == \"__main__\":\n print(Solution().equationsPossible([\"a==b\", \"b!=c\", \"c==a\"]))\n print(Solution().equationsPossible([\"a!=a\"]))\n print(Solution().equationsPossible([\"a==b\", \"b!=a\"]))\n print(Solution().equationsPossible([\"b==a\", \"a==b\"]))\n print(Solution().equationsPossible([\"a==b\", \"b==c\", \"a==c\"]))\n print(Solution().equationsPossible([\"c==c\", \"b==d\", \"x!=z\"]))\n","sub_path":"Medium/990.satisfiability-of-equality-equations.py","file_name":"990.satisfiability-of-equality-equations.py","file_ext":"py","file_size_in_byte":2740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"529125173","text":"from .Manager import *\nfrom .InstanceManager import *\nfrom .SSHConnectionManager import *\nfrom .ResultManager import *\nfrom ..Config import AWSConfig, SSHConfig\nfrom ..Connection import SSHConnection\nfrom ..Util import JMX, now\nfrom ..Parser import JMXParser\nimport os\nfrom copy import deepcopy\nimport time\n\n\nclass ClusterManager(Manager):\n # config is from config.json,\n # clusterID generally is not neccessary for creating a new cluster, it can be auto generated.\n # but it must be provided when resuming a previous cluster\n # UNLESS there is at least a repeated clustername running on AWS .\n # In this case,\n # 1. you need to specify an existing ID to continue to work on old cluster.\n # 2. or specify a new id, which is not existed, to start a new cluster.\n def __init__(self, sid=None):\n Manager.__init__(self)\n self.verbose()\n self.sid = sid\n\n\n def setConfig(self, config):\n self.config = deepcopy(config)\n self.resMngr = ResultManager(AWSConfig(**self.config))\n self.instMngr = InstanceManager(AWSConfig(**self.config))\n self.connMngr = SSHConnectionManager()\n\n\n def create(self,clusterName,user):\n self.print(\"Create cluster '%s'\"%clusterName)\n self.instMngr.setCluster(clusterName, user=user)\n\n\n def resume(self,clusterName,clusterID,user):\n self.print(\"Resume cluster '%s'\"%clusterName)\n self.instMngr.setCluster(clusterName, clusterID=clusterID, user=user)\n\n # set description\n def setClusterDesc(self,desc):\n self.instMngr.setClusterDesc(desc)\n\n # update slave number\n def setSlaveNumber(self, slvNum):\n self.slaveNumber = slvNum\n\n # once slave number is determined, JAC will automatically add or remove nodes\n def setupInstances(self):\n self.print(\"Launching instances\")\n self.instMngr.addMaster()\n diff = self.slaveNumber - len(self.instMngr.slaves)\n if diff < 0:\n IDs = [i[\"InstanceId\"] for i in self.instMngr.slaves[self.slaveNumber:]]\n self.instMngr.terminateInstances(IDs, self.connMngr.verboseOrNot)\n elif diff > 0:\n self.instMngr.addSlaves(diff)\n self.instMngr.startAll()\n time.sleep(300)\n self.print(\"Launched.\")\n\n # update the test plan directory you want to upload,\n # as well as related files like username and passwd csv\n # parameter must to be a directory.\n def setUploadDir(self, directory):\n assert os.path.isdir(directory)\n self.UploadPath = directory\n\n # upload the directory to all the nodes, master and slaves\n def uploadFiles(self):\n self.print(\"Uploading files\")\n self.connMngr.connectAll()\n self.connMngr.cmdAll(\"mkdir %s\"%self.instMngr.clusterName)\n self.connMngr.putAll(os.path.join(self.UploadPath),self.instMngr.clusterName,verbose=True)\n self.connMngr.closeAll()\n self.print(\"Uploaded.\")\n\n # repeatedly check if all node under current cluster are ready to connection\n # will be time-out after 5 mins\n def checkStatus(self,sleepFunc, checkTimes=0,checkInterval=10):\n count = 0\n if not self.instMngr.allInitialized(): self.print(\"Some instances are initializing \", end=\"\")\n while (count < checkTimes and not self.instMngr.allInitialized()):\n count += 1\n self.print(\".\",end=\"\")\n sleepFunc(checkInterval)\n self.print(\"\")\n if self.instMngr.allInitialized(): return True\n return False\n\n # start lightdm service on master\n # the master must be lxdm image, where lightdm has installed already.\n def startRDP(self):\n self.print(\"Starting lightdm\")\n self.connMngr.connectMaster()\n cmd = \"sudo service lightdm start\"\n self.connMngr.cmdMaster(cmd)\n self.connMngr.closeMaster()\n\n # After instances all set,\n # refresh the availiable connections, and update to connection manager\n def refreshConnections(self, verbose=None):\n self.print(\"Refreshing connection list\", verbose=verbose)\n self.instMngr.updateInstances()\n masterConn = SSHConnection(SSHConfig(hostname=self.instMngr.master[\"PublicIp\"], **self.config))\n slavesConn = {i['InstanceId']: SSHConnection(SSHConfig(hostname=i[\"PublicIp\"], **self.config)) for i in\n self.instMngr.slaves}\n self.connMngr.updateConnections(masterConn, slavesConn)\n self.print(\"Refreshed.\", verbose=verbose)\n\n # update remote host to jmeter.properties files\n def updateRemotehost(self):\n self.print(\"Updating master remotehost list\")\n\n def replaceStr(slaveIPs):\n propertiesFilePath = self.config[\"propertiesPath\"]\n ret = \"awk '/^remote_hosts/{gsub(/.+/,\"\n ret += '\"remote_hosts='\n if len(slaveIPs) != 0: ret += slaveIPs[0]\n if len(slaveIPs) > 1:\n for i in range(1, len(slaveIPs)):\n ret += ',' + slaveIPs[i]\n ret += \"\\\")};{print}' \" + propertiesFilePath\n ret += \" > \" + \".tmp.properties && cat .tmp.properties > \" + propertiesFilePath\n return ret\n\n self.connMngr.connectMaster()\n cmd = replaceStr([i[\"PrivateIpAddress\"] for i in self.instMngr.slaves])\n self.connMngr.cmdMaster(cmd)\n self.connMngr.closeMaster()\n self.print(\"Updated.\")\n\n # start jmeter-server, only for running slaves\n def startSlavesServer(self):\n self.print(\"Starting jmeter server in slaves\")\n self.connMngr.connectSlaves()\n self.connMngr.cmdSlaves(\"source .profile && cd %s && jmeter-server\" % self.instMngr.clusterName, verbose=False)\n self.connMngr.closeSlaves()\n self.print(\"Started.\")\n\n # stop master jmeter\n def stopMasterJmeter(self, verbose=None):\n self.print(\"Terminating jmeter in Master\")\n self.connMngr.connectMaster()\n self.connMngr.cmdMaster(\"ps aux | grep jmeter | awk '{print $2}' | xargs kill\")\n self.connMngr.closeMaster()\n self.print(\"Master Terminated.\")\n\n # stop all slaves' jmeter-server\n def stopSlavesServer(self, verbose=None):\n self.print(\"Terminating jmeter server in slaves\", verbose)\n self.connMngr.connectSlaves()\n self.connMngr.cmdSlaves(\"ps aux | grep [j]meter-server | awk '{print $2}' | xargs kill\", verbose=verbose)\n self.connMngr.closeSlaves()\n self.print(\"Slave Terminated.\", verbose)\n\n # run jmeter with args\n # 1. -t jmx, jmx file you want to run under you upload path\n # 2. -l output, the output file name\n def runTest(self, jmx, output):\n self.print(\"\\nrunning test now ...\")\n output+=\"_\"+self.instMngr.clusterName+\"_\"+jmx.split(\".\")[0]+\"_\"+now()+\".jtl\"\n # update jmx files:\n jmxParser = JMXParser(JMX(\"%s/%s\"%(self.UploadPath,jmx)))\n jmxParser.defaultChanges()\n jmxParser.setOutput(output)\n mergedOutput = \"merged.csv\"\n confFile = jmxParser.getConf(\"/home/ubuntu/\"+mergedOutput,self.instMngr.clusterID,self.config[\"es_IP\"]);\n confCmd = 'source .profile && echo \\'%s\\' > .tmpConf && sudo mv .tmpConf %s/jmeterlog.conf'%(\n confFile,self.config[\"logstash_conf_dir\"])\n runJmeterCmd = \"source .profile && cd %s && rm -f %s && jmeter -n -t %s -r \" % (\n self.instMngr.clusterName, output, jmx)\n aggCmd = ('source .profile && cd {0} && JMeterPluginsCMD.sh --generate-csv {1}.agg --input-jtl {1} --plugin-type AggregateReport'+\\\n ' && aws s3 cp {1}.agg s3://{2}/{3}/summary/{1}')\\\n .format(self.instMngr.clusterName,output,self.config[\"s3_bucket\"],self.instMngr.user)\n rmHeaderCmd = '''awk 'NR>1 {{print $0}}' {0}/{1} >> {0}/{1}'''.format(self.instMngr.clusterName,output)\n awkCmd = '''awk -v RS='\"' 'NR % 2 == 0 {{ gsub(/\\\\n/, \"\") }} {{ printf(\"%s%s\", $0, RT) }}' {0}/{1} >> {2}'''.format(\n self.instMngr.clusterName,output,mergedOutput)\n s3Cmd = \"source .profile && cd %s && aws s3 cp %s s3://%s/%s/%s\" % \\\n (self.instMngr.clusterName, output, self.config[\"s3_bucket\"], self.instMngr.user, output)\n\n self.connMngr.connectMaster()\n self.connMngr.putMaster(os.path.join(self.UploadPath,jmx),self.instMngr.clusterName)\n # update logstash conf files\n self.connMngr.cmdMaster(confCmd)\n # restart logstash\n self.connMngr.cmdMaster(\"sudo systemctl restart logstash.service\")\n # run test\n self.connMngr.cmdMaster(runJmeterCmd, verbose=True)\n # generate aggregate report and upload it to s3\n self.connMngr.cmdMaster(aggCmd)\n # remove header after aggregation\n self.connMngr.cmdMaster(rmHeaderCmd)\n # upload original log to s3\n self.connMngr.cmdMaster(s3Cmd, verbose=True)\n # append the results to mergedOutput\n self.connMngr.cmdMaster(awkCmd)\n self.connMngr.closeMaster()\n\n # terminate all nodes\n def cleanup(self):\n self.print(\"Terminating All nodes\")\n self.instMngr.terminateMaster()\n self.instMngr.terminateSlaves()\n self.print(\"Terminated.\\n\")\n\n def esCheck(self):\n self.print(\"Checking elasticsearch connection\")\n self.connMngr.connectMaster()\n self.connMngr.cmdMaster(\"nc -zv %s %s\"%tuple(self.config[\"es_IP\"].split(\":\")),verbose=True)\n self.connMngr.closeMaster()\n","sub_path":"server/JmeterAwsConf/Manager/ClusterManager.py","file_name":"ClusterManager.py","file_ext":"py","file_size_in_byte":9436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"160922793","text":"import functools\nimport logging\nimport pika\n\nLOG_FORMAT = ('%(levelname) -10s %(asctime)s %(name) -30s %(funcName) '\n '-35s %(lineno) -5d: %(message)s')\nLOGGER = logging.getLogger(__name__)\n\nlogging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT)\n\ndef on_message(channel, method_frame, header_frame, body, userdata=None):\n LOGGER.info('Userdata: {} Message body: {}'.format(userdata, body))\n channel.basic_ack(delivery_tag=method_frame.delivery_tag)\n\ncredentials = pika.PlainCredentials('guest', 'guest')\nparameters = pika.ConnectionParameters('localhost', credentials=credentials)\nconnection = pika.BlockingConnection(parameters)\n\nchannel = connection.channel()\nchannel.exchange_declare(exchange='test_exchange', exchange_type='direct', passive=False, durable=True, auto_delete=False)\nchannel.queue_declare(queue='standard', auto_delete=True)\nchannel.queue_bind(queue='standard', exchange='test_exchange', routing_key='standard_key')\nchannel.basic_qos(prefetch_count=1)\n\non_message_callback = functools.partial(on_message, userdata='on_message_userdata')\nchannel.basic_consume('standard', on_message_callback)\n\ntry:\n channel.start_consuming()\nexcept KeyboardInterrupt:\n channel.stop_consuming()\n\nconnection.close()\n","sub_path":"examples/consume.py","file_name":"consume.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"92866723","text":"import gzip\n\nfrom StringIO import StringIO\nfrom contextlib import closing\nfrom email import encoders\nfrom email.mime.base import MIMEBase\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\n\nSTARTS_WITH_MAPPINGS = {\n '#include': 'text/x-include-url',\n '#include-once': 'text/x-include-once-url',\n '#!': 'text/x-shellscript',\n '#cloud-config': 'text/cloud-config',\n '#cloud-config-archive': 'text/cloud-config-archive',\n '#upstart-job': 'text/upstart-job',\n '#part-handler': 'text/part-handler',\n '#cloud-boothook': 'text/cloud-boothook'\n}\n\n\ndef try_decode(data):\n try:\n return (True, data.decode())\n except UnicodeDecodeError:\n return (False, data)\n\n\ndef get_type(content, deftype):\n rtype = deftype\n\n (can_be_decoded, content) = try_decode(content)\n\n if can_be_decoded:\n # slist is sorted longest first\n slist = sorted(list(STARTS_WITH_MAPPINGS.keys()), key=lambda e: 0 - len(e))\n for sstr in slist:\n if content.startswith(sstr):\n rtype = STARTS_WITH_MAPPINGS[sstr]\n break\n else:\n rtype = 'application/octet-stream'\n\n return(rtype)\n\n\ndef pack(parts, opts={}):\n #\n # Do not change the boundary, as it'll break cfn_upadte\n #\n outer = MIMEMultipart(boundary='boostrapcfnboundary')\n\n for arg in parts:\n if isinstance(arg, basestring):\n arg = {'content': arg}\n\n if 'mime_type' in arg:\n mtype = arg['mime_type']\n else:\n mtype = get_type(arg['content'], opts.get('deftype', \"text/plain\"))\n\n maintype, subtype = mtype.split('/', 1)\n if maintype == 'text':\n # Note: we should handle calculating the charset\n msg = MIMEText(arg['content'], _subtype=subtype)\n else:\n msg = MIMEBase(maintype, subtype)\n msg.set_payload(arg['content'])\n # Encode the payload using Base64\n encoders.encode_base64(msg)\n\n outer.attach(msg)\n\n with closing(StringIO()) as buff:\n if opts.get('compress', False):\n gfile = gzip.GzipFile(fileobj=buff)\n gfile.write(outer.as_string().encode())\n gfile.close()\n else:\n buff.write(outer.as_string().encode())\n\n return buff.getvalue()\n","sub_path":"bootstrap_cfn/mime_packer.py","file_name":"mime_packer.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"507688679","text":"print('Welcome to my weekly income calculator!')\nprint (' ')\nwhile True:\n currency = input('Please enter your currency ')\n answer = input('Are you sure ' + currency + ' is your currency? (y/n) ')\n if answer == 'y':\n print('Great!')\n break\n\nprint(' ')\nwhile True:\n workPerWeek = input('How many days do you work a week? ')\n if int(workPerWeek) > 7:\n print('There are only 7 days in a week')\n elif int(workPerWeek) <= 7:\n answer = input('Are you sure you work ' + workPerWeek + ' days a week? (y/n) ')\n if answer == 'y':\n print('You work ' + workPerWeek + ' days a week!')\n break\n\nprint(' ')\n\nwhile True:\n payPerHour = input('How much ' + str(currency) + ' do you earn per hour? ')\n answer = input('Are you sure you earn ' + payPerHour + str(currency) + ' an hour? (y/n) ' )\n if answer == 'y':\n print('You earn ' + payPerHour + ' an hour ')\n break\n\nprint( ' ')\n\nwhile True:\n hourPerDay = input('How many hours do you work per day? ')\n if int(hourPerDay) > 12 and int(hourPerDay) <= 24:\n print('I am pretty sure this is illegal...')\n elif int(hourPerDay) > 24:\n print('Are you a time traveler?')\n elif int(hourPerDay) <= 12: \n answer = input('Are you sure you work ' + hourPerDay + ' hours per day? (y/n) ')\n if answer == 'y':\n print('You work ' + hourPerDay + ' hours per day ')\n break\n\nprint(' ')\ntotal = (int(payPerHour) * int(hourPerDay)) * int(workPerWeek) \nprint('You earn ' + str(total) + str(currency) + ' a week! ')\n\n \n\n\n\n\n","sub_path":"incomeCalculator.py","file_name":"incomeCalculator.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"255835982","text":"# s = 0\n\n# for i in [10, 11, 12, 13, ..., 9999]:\n# s += i\n\n# print(s)\n\n\n# s = 0\n\n# for i in range(10, 10000):\n# s += i\n\n# print(s)\n\n# import sys\n\n\n# print(sys.getsizeof([i for i in range(10000)]))\n# print(sys.getsizeof((i for i in range(10000))))\n\n# letters = ['A', 'B', 'C']\n\n# i = 1\n# for letter in letters:\n# print(i, letter)\n# i += 1\n\n\n# for i in range(len(letters)):\n# print(i, letters[i])\n\n\n\n# ['A', 'B', 'C']\n\n# [\n# (0, 'A'), \n# (1, 'B'), \n# (2, 'C'),\n# ]\n\n# for i, letter in enumerate(letters):\n# print(i + 1, letter)\n\n\ndef my_enumerate(items):\n # n = len(items)\n\n # result = []\n\n # for i in range(1, n):\n # result.append(\n # (i, items[i - 1])\n # )\n\n # return result\n \n # n = len(items)\n # for i in range(1, n):\n # yield i, items[i - 1]\n\n i = 0\n n = len(items)\n while i < n:\n yield i, items[i]\n i += 1\n\n\n\n# values = 'python'\n\n# for i, item in my_enumerate(values):\n# print(i, item)\n\n\n# f = open('some_file')\n\n# for line in f.readlines():\n# print(line)\n\n\n\n# for couple in zip(['A', 'B', 'C'], ['ա', 'բ', 'գ']):\n\n# i = iter(my_enumerate('python'))\n# print(i)\n\n# for _ in range(5):\n\n# print(next(i))\n\n\n# for _ in range(10):\n\n# print(next(i))\n\n\n\n","sub_path":"Classwork_8/generators.py","file_name":"generators.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"32861394","text":"# -*- coding: utf-8 -*-\n\"\"\"\nClass definition of YOLO_v3 style detection model on image and video\n\"\"\"\n\nimport colorsys\nimport os\nfrom timeit import default_timer as timer\n\nimport numpy as np\nfrom keras import backend as K\nfrom keras.models import load_model\nfrom keras.layers import Input\nfrom PIL import Image, ImageFont, ImageDraw\n\nfrom yolo3.model import yolo_eval, yolo_body, tiny_yolo_body\nfrom yolo3.utils import letterbox_image\nimport os\nfrom keras.utils import multi_gpu_model\n\n\nclass YOLO(object):\n def __init__(self, model_path, anchors_path, classes_path):\n self.model_path = model_path\n self.anchors_path = anchors_path\n self.classes_path = classes_path\n self.score = 0.3\n self.iou = 0.45\n self.model_image_size = (416,416)\n self.gpu_num = 1\n self.class_names = self._get_class()\n self.anchors = self._get_anchors()\n self.sess = K.get_session()\n self.boxes, self.scores, self.classes = self.generate()\n\n def _get_class(self):\n classes_path = os.path.expanduser(self.classes_path)\n with open(classes_path) as f:\n class_names = f.readlines()\n class_names = [c.strip() for c in class_names]\n return class_names\n\n def _get_anchors(self):\n anchors_path = os.path.expanduser(self.anchors_path)\n with open(anchors_path) as f:\n anchors = f.readline()\n anchors = [float(x) for x in anchors.split(',')]\n return np.array(anchors).reshape(-1, 2)\n\n def generate(self):\n model_path = os.path.expanduser(self.model_path)\n assert model_path.endswith('.h5'), 'Keras model or weights must be a .h5 file.'\n num_anchors = len(self.anchors)\n num_classes = len(self.class_names)\n is_tiny_version = num_anchors==6 # default setting\n try:\n self.yolo_model = load_model(model_path, compile=False)\n except:\n self.yolo_model = tiny_yolo_body(Input(shape=(None,None,3)), num_anchors//2, num_classes) \\\n if is_tiny_version else yolo_body(Input(shape=(None,None,3)), num_anchors//3, num_classes)\n self.yolo_model.load_weights(self.model_path) # make sure model, anchors and classes match\n else:\n assert self.yolo_model.layers[-1].output_shape[-1] == \\\n num_anchors/len(self.yolo_model.output) * (num_classes + 5), \\\n 'Mismatch between model and given anchor and class sizes'\n\n print('{} model, anchors, and classes loaded.'.format(model_path))\n\n self.input_image_shape = K.placeholder(shape=(2, ))\n boxes, scores, classes = yolo_eval(self.yolo_model.output, self.anchors,\n len(self.class_names), self.input_image_shape,\n score_threshold=self.score, iou_threshold=self.iou)\n return boxes, scores, classes\n\n def detect_image(self, image):\n outBoxes = []\n if self.model_image_size != (None, None):\n assert self.model_image_size[0]%32 == 0, 'Multiples of 32 required'\n assert self.model_image_size[1]%32 == 0, 'Multiples of 32 required'\n boxed_image = letterbox_image(image, tuple(reversed(self.model_image_size)))\n else:\n new_image_size = (image.width - (image.width % 32),\n image.height - (image.height % 32))\n boxed_image = letterbox_image(image, new_image_size)\n image_data = np.array(boxed_image, dtype='float32')\n\n image_data /= 255.\n image_data = np.expand_dims(image_data, 0) # Add batch dimension.\n\n out_boxes, out_scores, out_classes = self.sess.run(\n [self.boxes, self.scores, self.classes],\n feed_dict={\n self.yolo_model.input: image_data,\n self.input_image_shape: [image.size[1], image.size[0]],\n K.learning_phase(): 0\n })\n\n for i, c in reversed(list(enumerate(out_classes))):\n predicted_class = self.class_names[c]\n box = out_boxes[i]\n #score = out_scores[i]\n\n top, left, bottom, right = box\n top = max(0, np.floor(top + 0.5).astype('int32'))\n left = max(0, np.floor(left + 0.5).astype('int32'))\n bottom = min(image.size[1], np.floor(bottom + 0.5).astype('int32'))\n right = min(image.size[0], np.floor(right + 0.5).astype('int32'))\n box = [left,top,right,bottom, predicted_class]\n outBoxes.append(box)\n\n boxesForDelete = findSameBbox(outBoxes)\n for box in boxesForDelete:\n if box in outBoxes:\n outBoxes.remove(box)\n\n return outBoxes\n\n def close_session(self):\n self.sess.close()\n\n\ndef findSameBbox(boxes):\n boxesForDelete = []\n for box in boxes:\n for box2 in boxes:\n if box not in boxesForDelete and box != box2 and getIntersection(box, box2) > 0.5:\n boxesForDelete.append(box2)\n return boxesForDelete\n\ndef getIntersection(bbox1, bbox2):\n boxA = bbox1\n boxB = bbox2\n xA = max(boxA[0], boxB[0])\n yA = max(boxA[1], boxB[1])\n xB = min(boxA[2], boxB[2])\n yB = min(boxA[3], boxB[3])\n\n # compute the area of intersection rectangle\n interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)\n\n # compute the area of both the prediction and ground-truth\n # rectangles\n boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)\n boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)\n\n # compute the intersection over union by taking the intersection\n # area and dividing it by the sum of prediction + ground-truth\n # areas - the interesection area\n intersection = interArea / float(boxAArea + boxBArea - interArea)\n\n # return the intersection over union value\n return intersection\n","sub_path":"yolo.py","file_name":"yolo.py","file_ext":"py","file_size_in_byte":5823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"169573813","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-#\nimport pygame\nfrom game_main import GameMain\nfrom spaceship import Spaceship\nfrom asteroid import Asteroid\nfrom sprite import MySprite\nfrom settings import SPEED, NUMBER_ASTEROIDS, LEVEL\nimport random\n\nclass Asteroids(GameMain):\n\n caption = \"Asteroids\"\n spaceship_bullets = []\n asteroids = []\n cur_asteroid_speed = SPEED + 2\n increased = False\n\n def init(self):\n self.background = MySprite('backgrounds/space.png')\n self.spaceship = Spaceship(10, 50)\n\n def manage_asteroids(self):\n \n for asteroid in self.asteroids:\n asteroid.move('left', asteroid.speed)\n self.DISPLAYSURF.blit(asteroid.image, (asteroid.rect.x, asteroid.rect.y))\n \n self.asteroids = [ast for ast in self.asteroids if asteroid.rect.x >= -10]\n\n if len(self.asteroids) < NUMBER_ASTEROIDS[LEVEL]:\n x = self.DISPLAYSURF.get_size()[0] - 30\n y = random.randint(0, self.DISPLAYSURF.get_size()[1] - 50)\n\n asteroid = Asteroid(x, y, self.cur_asteroid_speed)\n self.asteroids.append(asteroid)\n self.increased = False\n else:\n if not self.increased:\n self.cur_asteroid_speed += 1\n self.increased = True\n\n def objects_collide(self, a, b):\n\n if isinstance(a, pygame.Rect):\n rectA = a\n else:\n rectA = a.rect #pygame.Rect(a.obj.x, a.obj.y, a.obj.width, a.obj.height)\n \n if isinstance(b, pygame.Rect):\n rectB = b\n else:\n rectB = b.rect #pygame.Rect(b.obj.x, b.obj.y, b.obj.width, b.obj.height)\n\n if rectA.colliderect(rectB):\n return True\n return False\n\n def check_hit_asteroid(self, bullet):\n self.asteroids = [ast for ast in self.asteroids if not self.objects_collide(bullet, ast)]\n \n def did_i_die(self):\n for asteroid in self.asteroids:\n if self.objects_collide(asteroid, self.spaceship):\n return True\n\n return False\n\n def mainLoop(self):\n\n self.background.image = pygame.transform.scale(self.background.image, self.DISPLAYSURF.get_size())\n self.DISPLAYSURF.blit(self.background.image, (0, 0))\n\n for bullet in self.spaceship_bullets:\n bullet.x += SPEED * 3\n pygame.draw.rect(self.DISPLAYSURF, (200, 0, 0), (bullet.x, bullet.y, 4, 4))\n #Check if the bullet hits any asteroid\n self.check_hit_asteroid(bullet)\n\n self.manage_asteroids()\n\n #if self.did_i_die():\n # del self.spaceship\n # pygame.time.wait(2000)\n # exit(0)\n\n if pygame.key.get_pressed()[pygame.K_UP]:\n self.spaceship.move('up', SPEED)\n if pygame.key.get_pressed()[pygame.K_DOWN]:\n self.spaceship.move('down', SPEED)\n if pygame.key.get_pressed()[pygame.K_LEFT]:\n self.spaceship.move('left', SPEED)\n if pygame.key.get_pressed()[pygame.K_RIGHT]:\n self.spaceship.move('right', SPEED)\n\n if pygame.key.get_pressed()[pygame.K_SPACE]:\n left = self.spaceship.rect.x + self.spaceship.image.get_size()[0]\n top = self.spaceship.rect.y + self.spaceship.image.get_size()[1]/2 - 1\n\n bullet = pygame.draw.rect(self.DISPLAYSURF, (200, 0, 0), (left, top, 4, 4))\n self.spaceship_bullets.append(bullet)\n\n self.DISPLAYSURF.blit(self.spaceship.image, (self.spaceship.rect.x, self.spaceship.rect.y))\n\n","sub_path":"asteroids.py","file_name":"asteroids.py","file_ext":"py","file_size_in_byte":3538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"98409400","text":"\"\"\"\n:mod:`mirgecom.initializers` helps intialize and compute flow solution fields.\n\nSolution Initializers\n^^^^^^^^^^^^^^^^^^^^^\n.. autoclass:: Vortex2D\n.. autoclass:: SodShock1D\n.. autoclass:: Lump\n.. autoclass:: Uniform\n.. autoclass:: AcousticPulse\n.. automethod: _make_pulse\n.. automethod: _make_uniform_flow\n\"\"\"\n\n__copyright__ = \"\"\"\nCopyright (C) 2020 University of Illinois Board of Trustees\n\"\"\"\n\n__license__ = \"\"\"\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\"\"\"\n\nimport numpy as np\nfrom pytools.obj_array import (\n flat_obj_array,\n make_obj_array,\n)\nfrom meshmode.dof_array import thaw\nfrom mirgecom.eos import IdealSingleGas\nfrom mirgecom.euler import split_conserved, join_conserved\n\n\ndef _make_uniform_flow(x_vec, mass=1.0, energy=2.5, pressure=1.0,\n velocity=None, eos=IdealSingleGas()):\n r\"\"\"Construct uniform, constant flow.\n\n Construct a uniform, constant flow from mass, energy, pressure, and\n an EOS object.\n\n Parameters\n ----------\n x_vec: np.ndarray\n Nodal positions\n mass: float\n Value to set `:math:\\rho`\n energy: float\n Optional value to set `:math:\\rho{E}`\n pressure: float\n Value to use for calculating `:math:\\rho{E}`\n velocity: np.ndarray\n Optional constant velocity to set `:math:\\rho\\vec{V}`\n\n Returns\n -------\n q: Object array of DOFArrays\n Agglomerated object array with the uniform flow\n \"\"\"\n dim = len(x_vec)\n if velocity is None:\n velocity = np.zeros(shape=(dim,))\n\n _rho = mass\n _p = pressure\n _velocity = velocity\n _gamma = eos.gamma()\n\n mom0 = _velocity * make_obj_array([_rho])\n e0 = _p / (_gamma - 1.0)\n ke0 = _rho * 0.5 * np.dot(_velocity, _velocity)\n\n x_rel = x_vec[0]\n zeros = 0.0*x_rel\n ones = zeros + 1.0\n\n mass = zeros + _rho\n mom = mom0 * make_obj_array([ones])\n energy = e0 + ke0 + zeros\n\n return join_conserved(dim=dim, mass=mass, energy=energy, momentum=mom)\n\n\ndef _make_pulse(amp, r0, w, r):\n r\"\"\"Create a Gaussian pulse.\n\n The Gaussian pulse is defined by:\n\n .. math::\n\n G(\\vec{r}) = a_0*\\exp^{-(\\frac{(\\vec{r}-\\vec{r_0})}{\\sqrt{2}w})^{2}}\\\\\n\n Where :math:`\\vec{r}` is the position, and the parameters are\n the pulse amplitude :math:`a_0`, the pulse location :math:`\\vec{r_0}`, and the\n RMS width of the pulse, :math:`w`.\n\n Parameters\n ----------\n amp: float\n specifies the value of :math:`\\a_0`, the pulse amplitude\n r0: float array\n specifies the value of :math:`\\r_0`, the pulse location\n w: float\n specifies the value of :math:`w`, the rms pulse width\n r: Object array of DOFArrays\n specifies the nodal coordinates\n\n Returns\n -------\n G: float array\n The values of the exponential function\n \"\"\"\n dim = len(r)\n r_0 = np.zeros(dim)\n r_0 = r_0 + r0\n # coordinates relative to pulse center\n rel_center = make_obj_array(\n [r[i] - r_0[i] for i in range(dim)]\n )\n actx = r[0].array_context\n rms2 = w * w\n r2 = np.dot(rel_center, rel_center) / rms2\n return amp * actx.np.exp(-.5 * r2)\n\n\nclass Vortex2D:\n r\"\"\"Initializer for the isentropic vortex solution.\n\n Implements the isentropic vortex after\n - [Zhou_2003]_\n - [Hesthaven_2008]_, Section 6.6\n\n The isentropic vortex is defined by:\n\n .. math::\n\n u = u_0 - \\beta\\exp^{(1-r^2)}\\frac{y - y_0}{2\\pi}\\\\\n v = v_0 + \\beta\\exp^{(1-r^2)}\\frac{x - x_0}{2\\pi}\\\\\n \\rho =\n ( 1 - (\\frac{\\gamma - 1}{16\\gamma\\pi^2})\\beta^2\n \\exp^{2(1-r^2)})^{\\frac{1}{\\gamma-1}}\\\\\n p = \\rho^{\\gamma}\n\n A call to this object after creation/init creates\n the isentropic vortex solution at a given time (t)\n relative to the configured origin (center) and\n background flow velocity (velocity).\n\n .. automethod:: __init__\n .. automethod:: __call__\n \"\"\"\n\n def __init__(\n self, beta=5, center=[0, 0], velocity=[0, 0],\n ):\n \"\"\"Initialize vortex parameters.\n\n Parameters\n ----------\n beta: float\n vortex amplitude\n center: numpy.ndarray\n center of vortex, shape ``(2,)``\n velocity: numpy.ndarray\n fixed flow velocity used for exact solution at t != 0, shape ``(2,)``\n \"\"\"\n self._beta = beta\n self._center = np.array(center)\n self._velocity = np.array(velocity)\n\n def __call__(self, t, x_vec, eos=IdealSingleGas()):\n \"\"\"\n Create the isentropic vortex solution at time *t* at locations *x_vec*.\n\n Parameters\n ----------\n t: float\n Current time at which the solution is desired.\n x_vec: numpy.ndarray\n Nodal coordinates\n eos: :class:`mirgecom.eos.GasEOS`\n Equation of state class to be used in construction of soln (if needed)\n \"\"\"\n vortex_loc = self._center + t * self._velocity\n\n # coordinates relative to vortex center\n x_rel = x_vec[0] - vortex_loc[0]\n y_rel = x_vec[1] - vortex_loc[1]\n actx = x_vec[0].array_context\n gamma = eos.gamma()\n r = actx.np.sqrt(x_rel ** 2 + y_rel ** 2)\n expterm = self._beta * actx.np.exp(1 - r ** 2)\n u = self._velocity[0] - expterm * y_rel / (2 * np.pi)\n v = self._velocity[1] + expterm * x_rel / (2 * np.pi)\n mass = (1 - (gamma - 1) / (16 * gamma * np.pi ** 2)\n * expterm ** 2) ** (1 / (gamma - 1))\n p = mass ** gamma\n\n e = p / (gamma - 1) + mass / 2 * (u ** 2 + v ** 2)\n\n return flat_obj_array(mass, e, mass * u, mass * v)\n\n\nclass SodShock1D:\n r\"\"\"Solution initializer for the 1D Sod Shock.\n\n This is Sod's 1D shock solution as explained in [Hesthaven_2008]_, Section 5.9\n The Sod Shock setup is defined by:\n\n .. math::\n\n {\\rho}(x < x_0, 0) = \\rho_l\\\\\n {\\rho}(x > x_0, 0) = \\rho_r\\\\\n {\\rho}{V_x}(x, 0) = 0\\\\\n {\\rho}E(x < x_0, 0) = \\frac{1}{\\gamma - 1}\\\\\n {\\rho}E(x > x_0, 0) = \\frac{.1}{\\gamma - 1}\n\n A call to this object after creation/init creates Sod's shock solution at a\n given time (t) relative to the configured origin (center) and background\n flow velocity (velocity).\n\n .. automethod:: __init__\n .. automethod:: __call__\n \"\"\"\n\n def __init__(\n self, dim=2, xdir=0, x0=0.5, rhol=1.0, rhor=0.125, pleft=1.0, pright=0.1,\n ):\n \"\"\"Initialize shock parameters.\n\n Parameters\n ----------\n dim: int\n dimension of domain\n x0: float\n location of shock\n rhol: float\n density to left of shock\n rhor: float\n density to right of shock\n pleft: float\n pressure to left of shock\n pright: float\n pressure to right of shock\n \"\"\"\n self._x0 = x0\n self._rhol = rhol\n self._rhor = rhor\n self._energyl = pleft\n self._energyr = pright\n self._dim = dim\n self._xdir = xdir\n if self._xdir >= self._dim:\n self._xdir = self._dim - 1\n\n def __call__(self, t, x_vec, eos=IdealSingleGas()):\n \"\"\"\n Create the 1D Sod's shock solution at locations *x_vec*.\n\n Parameters\n ----------\n t: float\n Current time at which the solution is desired (unused)\n x_vec: numpy.ndarray\n Nodal coordinates\n eos: :class:`mirgecom.eos.GasEOS`\n Equation of state class to be used in construction of soln (if needed)\n \"\"\"\n gm1 = eos.gamma() - 1.0\n gmn1 = 1.0 / gm1\n x_rel = x_vec[self._xdir]\n actx = x_rel.array_context\n\n zeros = 0*x_rel\n\n rhor = zeros + self._rhor\n rhol = zeros + self._rhol\n x0 = zeros + self._x0\n energyl = zeros + gmn1 * self._energyl\n energyr = zeros + gmn1 * self._energyr\n yesno = x_rel > x0\n mass = actx.np.where(yesno, rhor, rhol)\n energy = actx.np.where(yesno, energyr, energyl)\n mom = make_obj_array(\n [\n 0*x_rel\n for i in range(self._dim)\n ]\n )\n\n return flat_obj_array(mass, energy, mom)\n\n\nclass Lump:\n r\"\"\"Solution initializer for N-dimensional Gaussian lump of mass.\n\n The Gaussian lump is defined by:\n\n .. math::\n\n {\\rho}(r) = {\\rho}_{0} + {\\rho}_{a}\\exp^{(1-r^{2})}\\\\\n {\\rho}\\vec{V} = {\\rho}(r)\\vec{V_0}\\\\\n {\\rho}E = (\\frac{p_0}{(\\gamma - 1)} + \\frac{1}{2}\\rho{|V_0|}^2\n\n Where :math:`V_0` is the fixed velocity specified\n by the user at init time, and :math:`\\gamma` is taken\n from the equation-of-state object (eos).\n\n A call to this object after creation/init creates\n the lump solution at a given time (t)\n relative to the configured origin (center) and\n background flow velocity (velocity).\n\n This object also functions as a boundary condition\n by providing the \"get_boundary_flux\" method to\n prescribe exact field values on the given boundary.\n\n This object also supplies the exact expected RHS\n terms from the analytic expression in the\n \"expected_rhs\" method.\n\n .. automethod:: __init__\n .. automethod:: __call__\n .. automethod:: exact_rhs\n \"\"\"\n\n def __init__(\n self, numdim=1, rho0=1.0, rhoamp=1.0,\n p0=1.0, center=[0], velocity=[0]\n ):\n r\"\"\"Initialize Lump parameters.\n\n Parameters\n ----------\n numdim: int\n specify the number of dimensions for the lump\n rho0: float\n specifies the value of :math:`\\rho_0`\n rhoamp: float\n specifies the value of :math:`\\rho_a`\n p0: float\n specifies the value of :math:`p_0`\n center: numpy.ndarray\n center of lump, shape ``(2,)``\n velocity: numpy.ndarray\n fixed flow velocity used for exact solution at t != 0,\n shape ``(2,)``\n \"\"\"\n if len(center) == numdim:\n self._center = center\n elif len(center) > numdim:\n numdim = len(center)\n self._center = center\n else:\n self._center = np.zeros(shape=(numdim,))\n\n if len(velocity) == numdim:\n self._velocity = velocity\n elif len(velocity) > numdim:\n numdim = len(velocity)\n self._velocity = velocity\n new_center = np.zeros(shape=(numdim,))\n for i in range(len(self._center)):\n new_center[i] = self._center[i]\n self._center = new_center\n else:\n self._velocity = np.zeros(shape=(numdim,))\n\n assert len(self._velocity) == numdim\n assert len(self._center) == numdim\n\n self._p0 = p0\n self._rho0 = rho0\n self._rhoamp = rhoamp\n self._dim = numdim\n\n def __call__(self, t, x_vec, eos=IdealSingleGas()):\n \"\"\"\n Create the lump-of-mass solution at time *t* and locations *x_vec*.\n\n Note that *t* is used to advect the mass lump under the assumption of\n constant, and uniform velocity.\n\n Parameters\n ----------\n t: float\n Current time at which the solution is desired\n x_vec: numpy.ndarray\n Nodal coordinates\n eos: :class:`mirgecom.eos.GasEOS`\n Equation of state class to be used in construction of soln (if needed)\n \"\"\"\n lump_loc = self._center + t * self._velocity\n assert len(x_vec) == self._dim\n # coordinates relative to lump center\n rel_center = make_obj_array(\n [x_vec[i] - lump_loc[i] for i in range(self._dim)]\n )\n actx = x_vec[0].array_context\n r = actx.np.sqrt(np.dot(rel_center, rel_center))\n\n gamma = eos.gamma()\n expterm = self._rhoamp * actx.np.exp(1 - r ** 2)\n mass = expterm + self._rho0\n mom = self._velocity * make_obj_array([mass])\n energy = (self._p0 / (gamma - 1.0)) + np.dot(mom, mom) / (2.0 * mass)\n\n return flat_obj_array(mass, energy, mom)\n\n def exact_rhs(self, discr, q, t=0.0):\n \"\"\"\n Create the RHS for the lump-of-mass solution at time *t*, locations *x_vec*.\n\n Note that this routine is only useful for testing under the condition of\n uniform, and constant velocity field.\n\n Parameters\n ----------\n q\n State array which expects at least the canonical conserved quantities\n (mass, energy, momentum) for the fluid at each point.\n t: float\n Time at which RHS is desired\n \"\"\"\n actx = q[0].array_context\n nodes = thaw(actx, discr.nodes())\n lump_loc = self._center + t * self._velocity\n # coordinates relative to lump center\n rel_center = make_obj_array(\n [nodes[i] - lump_loc[i] for i in range(self._dim)]\n )\n r = actx.np.sqrt(np.dot(rel_center, rel_center))\n\n # The expected rhs is:\n # rhorhs = -2*rho*(r.dot.v)\n # rhoerhs = -rho*v^2*(r.dot.v)\n # rhovrhs = -2*rho*(r.dot.v)*v\n expterm = self._rhoamp * actx.np.exp(1 - r ** 2)\n mass = expterm + self._rho0\n\n v = self._velocity * make_obj_array([1.0 / mass])\n v2 = np.dot(v, v)\n rdotv = np.dot(rel_center, v)\n massrhs = -2 * rdotv * mass\n energyrhs = -v2 * rdotv * mass\n momrhs = v * make_obj_array([-2 * mass * rdotv])\n\n return flat_obj_array(massrhs, energyrhs, momrhs)\n\n\nclass AcousticPulse:\n r\"\"\"Solution initializer for N-dimensional Gaussian acoustic pulse.\n\n The Gaussian pulse is defined by:\n\n .. math::\n\n {\\rho}E(\\vec{r}) = {\\rho}E + a_0 * G(\\vec{r})\\\\\n G(\\vec{r}) = \\exp^{-(\\frac{(\\vec{r}-\\vec{r_0})}{\\sqrt{2}w})^{2}},\n\n where :math:`\\vec{r}` are the nodal coordinates, and :math:`\\vec{r_0}`,\n :math:`amplitude`, and :math:`w`, are the the user-specified pulse location,\n amplitude, and width, respectively.\n\n .. automethod:: __init__\n .. automethod:: __call__\n \"\"\"\n\n def __init__(self, numdim=1, amplitude=1,\n center=None, width=1):\n r\"\"\"\n Initialize acoustic pulse parameters.\n\n Parameters\n ----------\n numdim: int\n specify the number of dimensions for the pulse\n amplitude: float\n specifies the value of :math:`amplitude`\n width: float\n specifies the rms width of the pulse\n center: numpy.ndarray\n pulse location, shape ``(numdim,)``\n \"\"\"\n if len(center) == numdim:\n self._center = center\n elif len(center) > numdim:\n numdim = len(center)\n self._center = center\n else:\n self._center = np.zeros(shape=(numdim,))\n\n assert len(self._center) == numdim\n\n self._amp = amplitude\n self._width = width\n self._dim = numdim\n\n def __call__(self, x_vec, q, eos=IdealSingleGas()):\n \"\"\"\n Create the acoustic pulse at locations *x_vec*.\n\n Parameters\n ----------\n t: float\n Current time at which the solution is desired (unused)\n x_vec: numpy.ndarray\n Nodal coordinates\n eos: :class:`mirgecom.eos.GasEOS`\n Equation of state class to be used in construction of soln (unused)\n \"\"\"\n assert len(x_vec) == self._dim\n cv = split_conserved(self._dim, q)\n return cv.replace(\n energy=cv.energy + _make_pulse(\n amp=self._amp, w=self._width, r0=self._center, r=x_vec)\n ).join()\n\n\nclass Uniform:\n r\"\"\"Solution initializer for a uniform flow.\n\n A uniform flow is the same everywhere and should have\n a zero RHS.\n\n .. automethod:: __init__\n .. automethod:: __call__\n .. automethod:: exact_rhs\n \"\"\"\n\n def __init__(\n self, numdim=1, rho=1.0, p=1.0, e=2.5, velocity=[0],\n ):\n r\"\"\"Initialize uniform flow parameters.\n\n Parameters\n ----------\n numdim: int\n specify the number of dimensions for the lump\n rho: float\n specifies the density\n p: float\n specifies the pressure\n e: float\n specifies the internal energy\n velocity: numpy.ndarray\n specifies the flow velocity\n \"\"\"\n if len(velocity) == numdim:\n self._velocity = velocity\n elif len(velocity) > numdim:\n numdim = len(velocity)\n self._velocity = velocity\n else:\n self._velocity = np.zeros(shape=(numdim,))\n\n assert len(self._velocity) == numdim\n\n self._p = p\n self._rho = rho\n self._e = e\n self._dim = numdim\n\n def __call__(self, t, x_vec, eos=IdealSingleGas()):\n \"\"\"\n Create a uniform flow solution at locations *x_vec*.\n\n Parameters\n ----------\n t: float\n Current time at which the solution is desired (unused)\n x_vec: numpy.ndarray\n Nodal coordinates\n eos: :class:`mirgecom.eos.GasEOS`\n Equation of state class to be used in construction of soln (unused)\n \"\"\"\n return _make_uniform_flow(x_vec=x_vec, mass=self._rho,\n pressure=self._p, energy=self._e,\n velocity=self._velocity, eos=eos)\n\n def exact_rhs(self, discr, q, t=0.0):\n \"\"\"\n Create the RHS for the uniform solution. (Hint - it should be all zero).\n\n Parameters\n ----------\n q\n State array which expects at least the canonical conserved quantities\n (mass, energy, momentum) for the fluid at each point. (unused)\n t: float\n Time at which RHS is desired (unused)\n \"\"\"\n actx = q[0].array_context\n nodes = thaw(actx, discr.nodes())\n mass = nodes[0].copy()\n mass[:] = 1.0\n massrhs = 0.0 * mass\n energyrhs = 0.0 * mass\n momrhs = make_obj_array([0 * mass])\n\n return flat_obj_array(massrhs, energyrhs, momrhs)\n","sub_path":"mirgecom/initializers.py","file_name":"initializers.py","file_ext":"py","file_size_in_byte":19048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"388297957","text":"from behave import given, when, then\nfrom django.test import Client\nimport json\n\nclient = Client()\n\nUSER_ENDPOINT = \"/users/\"\n\ndef retrieve_json_response_content_and_id(response):\n \"\"\"\n JSON loads response.content.\n \n :param response: response to retrieve content from\n \n :returns (dict): response content\n \"\"\"\n try:\n response_content = json.loads(response.content)\n\n except json.decoder.JSONDecodeError:\n assert False, \\\n \"Response is not JSON serializable (most likely not a valid request}\"\n\n user_url = response_content[\"url\"]\n user_id = user_url[user_url.rfind(\"users/\") + 6: user_url.rfind(\"/\")]\n\n return user_id, response_content\n\n\n@given(u'the following user data')\ndef step_impl(context):\n user_data_payload = {}\n for row in context.table:\n for heading in row.headings:\n if heading == \"groups\":\n groups_value = row.get(heading).strip()\n if groups_value:\n user_data_payload[heading] = [groups_value]\n else:\n user_data_payload[heading] = []\n else:\n user_data_payload[heading] = row.get(heading)\n\n context.user_payload = user_data_payload\n\n\n@when(u'a {request_method} request is made to the user endpoint')\ndef step_impl(context, request_method):\n if request_method == \"POST\":\n context.response = client.post(USER_ENDPOINT, \n context.user_payload, \n content_type=\"application/json\")\n if request_method == \"GET\":\n context.response = client.get(f\"{USER_ENDPOINT}{context.user_id}/\")\n\n \n\n\n@then(u'the user is created')\ndef step_impl(context):\n assert context.response.status_code == 201, \"Failed to create user, \" \\\n f\"status code: {context.response.status_code}\"\n\n\n@given(u'a user exists with the following user data')\ndef step_impl(context):\n user_data_payload = {}\n for row in context.table:\n for heading in row.headings:\n if heading == \"username\":\n context.username = row.get(heading)\n if heading == \"groups\":\n groups_value = row.get(heading).strip()\n if groups_value:\n user_data_payload[heading] = [groups_value]\n else:\n user_data_payload[heading] = []\n else:\n user_data_payload[heading] = row.get(heading)\n\n context.user_payload = user_data_payload\n\n context.response = client.post(USER_ENDPOINT, \n context.user_payload, \n content_type=\"application/json\")\n\n context.user_id, response_content = retrieve_json_response_content_and_id(context.response)\n\n\n@then(u'the user is retrieved')\ndef step_impl(context):\n assert context.response.status_code == 200, \"Failed to retrieve user, \" \\\n f\"status code: {context.response.status_code}\"","sub_path":"BDD/Features/userm_test_folder copy/steps/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":3022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"181523694","text":"import pandas as pd\n#import nltk\nimport re\nimport jellyfish\nfrom pprint import pprint\n\ndef compute_similarity(names1,names2):\n data = []\n hist = {}\n mapping_list = []\n for i, n in enumerate(names1):\n row = []\n n_1 = clean_name(n)\n min_obj = (None,0,0)\n for j, m in enumerate(names2):\n n_2 = clean_name(m)\n score = jellyfish.damerau_levenshtein_distance(n_1,n_2)\n row.append(score)\n if min_obj[0] is None or min_obj[0]>=score:\n min_obj=(score,i,j)\n\n if min_obj[0] <= 1:\n mapping_list.append(min_obj)\n '''\n print('#' * 100)\n print(min_obj[0])\n print(names1[min_obj[1]])\n print(names2[min_obj[2]])\n print('')\n print(clean_name(names1[min_obj[1]]))\n print(clean_name(names2[min_obj[2]]))\n print('')\n print('')\n '''\n if hist.get(min_obj[0],None) is None:\n hist[min_obj[0]]=0\n hist[min_obj[0]]+=1\n data.append(row)\n #pprint(hist)\n return mapping_list\n\n\n\n\n\ndef clean_name(n):\n n = re.sub('\\w+\\.','',n)\n n = n.replace('MBA','')\n n = n.replace('OA', '')\n n = re.sub('[^a-zA-Z0-9\\s]', '',n)\n n = str.lower(n).strip()\n l = n.split(' ')\n l.sort()\n l.sort(key=len, reverse=True)\n l = [i for i in l if len(i)>3]\n n = ' '.join(l)\n return n\n\ndef generate_new_list(df, mapping_list):\n df = df.reset_index()\n for i in mapping_list:\n df = df.drop(i[2])\n return df\n\n\ndf1 = pd.DataFrame.from_csv('stefan.csv', sep=';',header=None, index_col=None)\ndf2 = pd.DataFrame.from_csv('tapp_dump.csv', sep=',',header=None)\n\nnames1 = df1[0].values\nnames2 = df2[1].values\nmapping_list = compute_similarity(names1,names2)\ndf = generate_new_list(df2,mapping_list)\ndf = df[[1,5,3,4,10,11,2]]\n\nf = lambda x: x.replace(',',', ').replace('\"','').replace('[','').replace(']','')\ng =lambda x: x.replace('\\\\u00c4','Ä').replace('\\\\u00e4','ä').replace('\\\\u00fc','ü')\ndf[2] = df[2].apply(f)\ndf[2] = df[2].apply(g)\ndf[11] = df[11].apply(f)\ndf[10] = df[10].apply(f)\nprint(df.head())\ndf.to_csv('aerzteliste_tapp_dump.csv', sep=';', index=False, header=False)","sub_path":"rkball_scripts/aerzte/main_aerzte.py","file_name":"main_aerzte.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"560278242","text":"\nimport time\nfrom multiprocessing.connection import Client\n\nclass ProcessManager(object):\n\n def __init__(self, extra_kwargs={}):\n\n # Maps entity class name -> (entity class, process name)\n self.processes = {}\n\n # Initialize pipe to simulator\n self.simulator_pipe = Client((\"localhost\", 3829))\n\n def start_process(self, entity_class, name, *args, **kwargs):\n '''Initiates a process of the class proc_cls.'''\n self.processes[entity_class.__name__] = (entity_class, name)\n self.simulator_pipe.send(\n map(lambda x: x[0], self.processes.itervalues())\n )\n\n def get_data(self, **kwargs):\n '''get data from all running processes and\n package the output into a dictionary '''\n\n vision_data = {}\n if self.simulator_pipe.poll():\n for entity_cls, data in self.simulator_pipe.recv():\n entity_cls, process_name = self.processes[entity_cls.__name__]\n vision_data[process_name] = data\n\n if vision_data:\n for entity_cls_name, process_name in self.processes.itervalues():\n if process_name not in vision_data:\n vision_data[process_name] = None\n return vision_data\n else:\n return None\n\n def ping(self):\n '''verify that all processes are alive'''\n return True\n\n def kill(self):\n ''' kill all running sub processes '''\n self.simulator_pipe.send([])\n self.processes = {}\n\nclass KillSignal(Exception):\n pass\n","sub_path":"simulator/vision/process_manager.py","file_name":"process_manager.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"393678030","text":"import tornado.web\nimport logging\nimport datetime\nimport time\nimport markdown\nimport urllib\nimport urllib.request\nimport json\nimport uuid\nimport hashlib\nfrom urllib import parse\n# from utils import DatabaseUtil,RedisUtil\nfrom markdown.extensions import Extension\nfrom markdown.extensions.fenced_code import FencedCodeExtension\nfrom markdown.extensions.tables import TableExtension\n\nappsec=\"f606a5d1ca637f5b8a23c9bf08df6141\"\n\nclass BaseHandler(tornado.web.RequestHandler):\n def set_default_headers(self):\n self.set_header(\"Access-Control-Allow-Origin\", \"*\") # 这个地方可以写域名\n self.set_header(\"Access-Control-Allow-Headers\", \"*\")\n self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')\n\n # 定义一个响应OPTIONS 请求,不用作任务处理\n def options(self):\n # no body\n self.set_default_headers()\n self.set_status(204)\n self.finish()\n\n\nclass Mainhandler(BaseHandler):\n def get(self):\n logger = logging.getLogger(name=\"tornado-logs\")\n logger.info(\"damn\")\n resdict = {\n \"username\": \"qwer\",\n \"age\": 18,\n \"bloglist\": [1, 2, 3, 4, 5, 6, 7, 8, 9]\n }\n self.render(\"templates/main.html\", resultdict=resdict)\n\nclass txthandler(BaseHandler):\n def get(self):\n with open(\"MP_verify_E7ezYIkLHQC2tzyW.txt\",\"w\") as f:\n f.write(\"E7ezYIkLHQC2tzyW\")\n return f\n # return \"E7ezYIkLHQC2tzyW\"\n # self.render(\"templates/main.html\", resultdict=resdict)\n\n# class TagListHandler(BaseHandler):\n# def get(self):\n# logger = logging.getLogger(name=\"tornado-logs\")\n# logger.info(\"TagListHandler\")\n# taglist=[]\n# with DatabaseUtil() as cur:\n# select_sql = \"\"\"select id,title,filename,simplecontext,user,create_time,type\n# from pihuazhenduo.articles\n# order by create_time desc\"\"\"\n# cur.execute(select_sql)\n# res = cur.fetchall()\n# print(res)\n# for data in res:\n# taglist.append(\n# {\n# \"articleid\": data[0],\n# \"title\": data[1],\n# \"time\": str(data[5])[:19],\n# \"user\": data[4],\n# \"simplecontext\": data[3] if data[3] else '',\n# \"type\": data[6]\n# }\n# )\n# resdict = {\n# \"pagenum\": 10,\n# \"setpage\": 1,\n# \"bloglist\": taglist\n# }\n# self.render(\"templates/bloglist.html\", resultdict=resdict)\n#\n#\n#\n#\n#\n# class BlogMainHandler(BaseHandler):\n# def gettag(self):\n# with DatabaseUtil() as cur:\n# select_sql = \"\"\"\n# select id,name,type\n# from pihuazhenduo.articles\"\"\"\n# cur.execute(select_sql)\n# res = cur.fetchall()\n# pass\n#\n# def get(self):\n# logger = logging.getLogger(name=\"tornado-logs\")\n# logger.info(\"damn\")\n# # tagid = self.get_query_argument('articleid')\n# bloglist = []\n# with DatabaseUtil() as cur,RedisUtil(1) as redis:\n# select_sql = \"\"\"\n# select id,title,filename,simplecontext,user,create_time,type\n# from pihuazhenduo.articles\n# order by create_time desc\"\"\"\n# cur.execute(select_sql)\n# res = cur.fetchall()\n# for data in res:\n# bloglist.append(\n# {\n# \"pv\":redis.hget(\"article_pv\",data[0]) if redis.hget(\"article_pv\",data[0]) else 0,\n# \"articleid\": data[0],\n# \"title\": data[1],\n# \"time\": str(data[5])[:19],\n# \"user\": data[4],\n# \"simplecontext\": data[3] if data[3] else '',\n# \"type\": data[6]\n# }\n# )\n# resdict = {\n# \"pagenum\": 10,\n# \"setpage\": 1,\n# \"bloglist\": bloglist\n# }\n# self.render(\"templates/bloglist.html\", resultdict=resdict)\n#\n# class AboutmeHandler(BaseHandler):\n# def getmd(self, filename, articleid, title, time, user, simplecontext):\n# with open(f\"static/articles/{filename}.md\", 'r') as f:\n# lines = markdown.markdown(f.read(), extensions=['markdown.extensions.fenced_code',\n# 'markdown.extensions.tables']).encode(\"utf-8\")\n# resdict = {\n# \"articleid\": articleid,\n# \"title\": title,\n# \"readnum\": \"1000\",\n# \"thumbnum\": 99,\n# \"thumbed\": 1,\n# \"time\": time,\n# \"user\": user,\n# \"simplecontext\": simplecontext,\n# \"context\": lines\n# }\n# self.render(\"templates/blogmd.html\", resultdict=resdict)\n#\n# def get(self):\n# logger = logging.getLogger(name=\"tornado-logs\")\n# logger.info(\"about me\")\n# # article = self.request.query\n# with RedisUtil(1) as redis:\n# redis.hincrby(\"article_pv\",\"aboutme\",1)\n#\n# articlethings = {\"filename\": \"aboutme\",\n# \"articleid\": \"aboutme\",\n# \"title\": \"关于作者\",\n# \"time\": \"2020-05-24 11:24:37\",\n# \"user\": \"jaderabbit\",\n# \"simplecontext\": \"自我介绍\"}\n# self.getmd(**articlethings)\n#\n# class BlogDetailHandler(BaseHandler):\n# def gettxt(self, filename, articleid, title, time, user, simplecontext):\n# with open(f\"static/articles/{filename}.txt\", 'r') as f:\n# lines = f.readlines()\n# resdict = {\n# \"articleid\": articleid,\n# \"title\": title,\n# \"readnum\": \"1000\",\n# \"thumbnum\": 99,\n# \"thumbed\": 1,\n# \"time\": time,\n# \"user\": user,\n# \"simplecontext\": simplecontext,\n# \"context\": lines\n# }\n# self.render(\"templates/blog.html\", resultdict=resdict)\n#\n# def getmd(self, filename, articleid, title, time, user, simplecontext):\n# with open(f\"static/articles/{filename}.md\", 'r') as f:\n# lines = markdown.markdown(f.read(), extensions=['markdown.extensions.fenced_code',\n# 'markdown.extensions.tables']).encode(\"utf-8\")\n# resdict = {\n# \"articleid\": articleid,\n# \"title\": title,\n# \"readnum\": \"1000\",\n# \"thumbnum\": 99,\n# \"thumbed\": 1,\n# \"time\": time,\n# \"user\": user,\n# \"simplecontext\": simplecontext,\n# \"context\": lines\n# }\n# self.render(\"templates/blogmd.html\", resultdict=resdict)\n#\n# def get(self):\n# logger = logging.getLogger(name=\"tornado-logs\")\n# logger.info(\"blogdetail\")\n# # article = self.request.query\n# articleid = self.get_query_argument('articleid')\n# logger.info(articleid)\n# with RedisUtil(1) as redis:\n# redis.hincrby(\"article_pv\",articleid,1)\n#\n# with DatabaseUtil() as cur:\n# select_sql = \"\"\"select title,filename,simplecontext,user,create_time,type\n# from pihuazhenduo.articles\n# where id =%s\"\"\"\n# plist = [articleid, ]\n# cur.execute(select_sql, plist)\n# res = cur.fetchone()\n#\n# articlethings = {\"filename\": articleid,\n# \"articleid\": articleid,\n# \"title\": res[0],\n# \"time\": str(res[4])[:19],\n# \"user\": res[3],\n# \"simplecontext\":res[2]}\n# if res[5]==0:\n# self.gettxt(**articlethings)\n# else:\n# self.getmd(**articlethings)\n#\n#\n# class MdtestHandler(BaseHandler):\n# def get(self):\n# logger = logging.getLogger(name=\"tornado-logs\")\n# logger.info(\"blogdetail\")\n# # article = self.request.query\n#\n# with open(f\"static/articles/9.md\", 'r') as f:\n# lines = markdown.markdown(f.read(), extensions=['markdown.extensions.fenced_code',\n# 'markdown.extensions.tables']).encode(\"utf-8\")\n# resdict = {\n# \"articleid\": 123,\n# \"title\": \"md测试\",\n# \"readnum\": \"1000\",\n# \"thumbnum\": 99,\n# \"thumbed\": 1,\n# \"time\": str(datetime.datetime.now()),\n# \"user\": \"jaderabbit\",\n# \"simplecontext\": \"这是一个不一般的故事。。。\",\n# \"context\": lines\n# }\n# self.render(\"templates/blogmd.html\", resultdict=resdict)\n\nclass wxsignatureHandler(BaseHandler):\n def get(self):\n articleid = self.request.query_arguments\n \n logger = logging.getLogger(name=\"tornado-logs\")\n logger.info(f\"articleid:{articleid}\")\n # article = self.request.query\n wxurl=f\"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxf6f182e7b47ce14f&secret={appsec}\"\n response=urllib.request.urlopen(wxurl)\n access=json.loads(response.read().decode('utf-8'))\n logger.info(access)\n access_token=access['access_token']\n tickt_url=f\"https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={access_token}&type=jsapi\"\n response = urllib.request.urlopen(tickt_url)\n tik=json.loads(response.read().decode('utf-8'))\n logger.info(tik)\n ticket=tik['ticket']\n nocestr=str(uuid.uuid4()).replace(\"-\",\"\")\n timestamp=int(time.time())\n url=\"http://www.pihuazhenduo.com/qrstart\"\n\n res=f\"jsapi_ticket={ticket}&noncestr={nocestr}×tamp={timestamp}&url={url}\"\n sha = hashlib.sha1(res.encode('utf-8'))\n encrypts = sha.hexdigest()\n logger.info(f\"ticket:{ticket}\")\n logger.info(f\"nocestr:{nocestr}\")\n logger.info(f\"timestamp:{timestamp}\")\n logger.info(f\"url:{url}\")\n resdict = {\n \"noncestr\": nocestr,\n \"timestamp\": timestamp,\n \"enc\": encrypts,\n \"access_token\":access_token,\n \"jsapi_ticket\":ticket\n\n }\n self.render(\"templates/qrcheck.html\", resultdict=resdict)\n","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":10846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"519018411","text":"from django.urls import path, re_path\nfrom . import views\n\nurlpatterns = [\n re_path(\"^questions/$\", views.QuestionList.as_view(), name=\"questions\"),\n re_path(\n \"^questions/(?P\\d+)/$\",\n views.QuestionDetails.as_view(),\n name=\"question-details\",\n ),\n re_path(\n \"^questions/(?P\\d+)/answer/(?P\\d+)/$\",\n views.AnswerDetail.as_view(),\n name=\"answer-detail\",\n ),\n re_path(\n \"^only_questions_with_answers/$\", views.QuestionListWithAnswers.as_view(), name=\"questions_with_answers\"\n ),\n]\n","sub_path":"forum/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"129894990","text":"#! /usr/bin/env python\n# coding: utf-8\n\n###########################################################################################\n###########################################################################################\n## Projeto: Nanook UFC\n## Autor: Kaio Douglas Teófilo Rocha\n## Email: kaiodtr@gmail.com\n###########################################################################################\n## Arquivo: Ensaio para Levantamento das Plantas dos Motores\n## Revisão: 1 [16/03/2017]\n###########################################################################################\n###########################################################################################\n\n###########################################################################################\n# INSTRUÇÕES\n###########################################################################################\n# 1. Faça upload do código \"Nanook_Motor_Plant\" para a FRDM-K64F\n# 2. Certifique-se de que os encoders estão conectados à placa de interface\n# 3. Certifique-se de que o driver dos motores está conectado à placa de interface\n# 4. Encontre a porta serial da conexão. Pode-se utilizar o comando:\n# $ ls /dev/ttyACM*\n# 5. Alterar a variável \"serial_port\" para o valor encontrado\n# 6. Executar o script\n# 7. Fornecer os parâmetros do ensaio\n# 8. Executar o script \"plot_ensaio_planta_motores.py\" para plotar os resultados\n###########################################################################################\n\nimport serial\nimport time\nfrom os.path import expanduser\n\n###########################################################################################\n# INICIALIZAÇÃO\n###########################################################################################\n\n##### Parâmetros definidos pelo usuário #####\n\nensaio = int(raw_input('Número do Ensaio: '))\nfreq = float(raw_input('Frequência de Amostragem [Hz]: '))\nn_samples = int(raw_input('Número de Amostras: '))\nright_vel_ref = float(raw_input('Velocidade de Referência Direita [-1.0, 1.0]: '))\nleft_vel_ref = float(raw_input('Velocidade de Referência Esquerda [-1.0, 1.0]: '))\n\n# Período de amostragem\n\nTs = 1.0 / freq\n\n##### Listas com os dados do ensaio #####\n\nright_vel_list = []\nleft_vel_list = []\ntime_list = []\n\n##### Arquivo para salvar os resultados #####\n\n# Diretório\n\nhome = expanduser('~')\npath = home + '/ros_catkin_ws/src/nanook_ufc/ensaios'\npath += '/planta_motores/resultados/ensaio_%d.txt' % ensaio\n\n# Abertura do arquivo\n\ndata_file = open(path, 'w')\n\n# Registro dos parâmetros do ensaio\n\nparams_str = '### Ensaio para Levantamento das Plantas dos Motores ###\\n\\n'\nparams_str += '# Parâmetros #\\n\\n'\nparams_str += '# Número do Ensaio: %d\\n' % ensaio\nparams_str += '# Frequência de Amostragem: %.1f Hz\\n' % freq\nparams_str += '# Número de Amostras: %d\\n' % n_samples\nparams_str += '# Velocidade de Referência Direita: %.1f \\n' % right_vel_ref\nparams_str += '# Velocidade de Referência Esquerda: %.1f \\n\\n' % left_vel_ref\n\ndata_file.write(params_str)\n\n##### Porta serial #####\n\nserial_port = '/dev/ttyACM0'\n\n##### Conexão #####\n\ntry:\n\n print('Conectando-se à base em %s.' % serial_port)\n\n base = serial.Serial(serial_port, 115200)\n\n time.sleep(1)\n\nexcept serial.SerialException:\n\n print('Falha ao tentar conectar com a base em %s.' % serial_port)\n raise SystemExit\n\nelse:\n\n print('Conexão com a base estabelecida!')\n\n##### Reinicialização da base #####\n\nbase.write('r')\ntime.sleep(0.5)\n\n###########################################################################################\n# FUNÇÕES AUXILIARES\n###########################################################################################\n\ndef set_vel_ref(v_right, v_left):\n\n \"\"\"Definição de referência de velocidade (direita e esquerda).\n\n Argumentos:\n v_right (float): Velocidade de referência direita [-1.0, 1.0]\n v_left (float): Velocidade de referência esquerda [-1.0, 1.0]\n\n \"\"\"\n\n # Preparação da string a ser enviada para a base\n # Formato: v[sig][d1].[d2][sig][e1].[e2]\n # Nota: Os pontos decimais não são enviados, por isso os valores são multiplicados\n # por 10\n\n ref_str = 'v{:=+03.0f}{:=+03.0f}'.format(v_right * 10, v_left * 10)\n\n # Envio da string com a referência, um caractere por vez\n\n for char in ref_str:\n base.write(char)\n\n###########################################################################################\n\n###########################################################################################\n\ndef get_vel():\n\n \"\"\"Informações de velocidade da base.\n\n Retorno:\n tuple: (Velocidade direita [RPM],\n Velocidade esquerda [RPM])\n\n \"\"\"\n\n # Envio da solicitação de leituras de velocidade\n\n base.write('l')\n\n # Recebimento dos 12 bytes contendo os dados das velocidades\n\n vel_str = base.read(12)\n\n # Extração dos valores numéricos dos dados das velocidades a partir da string recebida\n # Formato da string recebida:\n # [sig][d1][d2].[d3][d4][d5]\n # [sig][e1][e2].[e3][e4][e5]\n # Nota: Os pontos decimais não são recebidos\n\n # Extração da velocidade direita [RPM]\n\n v_right = int(vel_str[1]) * 10 + \\\n int(vel_str[2]) + \\\n int(vel_str[3]) * 0.1 + \\\n int(vel_str[4]) * 0.01 + \\\n int(vel_str[5]) * 0.001\n\n # Teste de valor negativo\n\n if (vel_str[0] == '-'):\n v_right *= -1\n\n # Extração da velocidade esquerda [RPM]\n\n v_left = int(vel_str[7]) * 10 + \\\n int(vel_str[8]) + \\\n int(vel_str[9]) * 0.1 + \\\n int(vel_str[10]) * 0.01 + \\\n int(vel_str[11]) * 0.001\n\n # Teste de valor negativo\n\n if (vel_str[6] == '-'):\n v_left *= -1\n\n # Retorno dos valores extraídos\n\n return (v_right, v_left)\n\n###########################################################################################\n# EXECUÇÃO\n###########################################################################################\n\n##### Envio da referência #####\n\nset_vel_ref(right_vel_ref, left_vel_ref)\ntime.sleep(0.005)\n\nprint('Referência enviada')\n\n##### Laço #####\n\n# Contador de amostras\n\nsample = 1\n\nwhile sample <= n_samples:\n try:\n # Tempo no início da iteração\n\n t0_iter = time.time()\n\n # Leitura das velocidades\n\n (v_right, v_left) = get_vel()\n\n # Apresentação dos valores\n\n print('Velocidades')\n print('Velocidade Direita: %f RPM' % v_right)\n print('Velocidade Esquerda: %f RPM' % v_left)\n print\n\n # Atualização das listas com os dados\n\n right_vel_list.append(v_right)\n left_vel_list.append(v_left)\n time_list.append(t0_iter)\n\n # Incremento do contador de amostras\n\n sample += 1\n\n # Duração da iteração\n\n dt_iter = time.time() - t0_iter\n\n print('Tempo da Iteração: %.5f' % dt_iter)\n print\n\n # Aguardar até que o período de amostragem seja concluído\n\n time.sleep(Ts - dt_iter)\n\n except KeyboardInterrupt:\n break\n\n###########################################################################################\n# FINALIZAÇÃO\n###########################################################################################\n\n# Parada dos motores\n\nset_vel_ref(0.0, 0.0)\n\n# Finalização da conexão com a base\n\nbase.close()\nprint('Conexão com a base terminada.')\nprint\n\n##### Registro dos resultados no arquivo #####\n\n# Listas com as velocidades de referência\n\nright_max_vel = 30.30606 # Máxima velocidade direita\nleft_max_vel = 29.87750 # Máxima velocidade esquerda\n\nright_vel_ref_list = [right_vel_ref * right_max_vel] * len(time_list)\nleft_vel_ref_list = [left_vel_ref * left_max_vel] * len(time_list)\n\n# Desconto do instante inicial (deve ser 0 s)\n\nt0 = time_list[0]\ntime_list = [(t - t0) for t in time_list]\n\n# Salvando resultados no arquivo\n\nfor idx in range(len(time_list)):\n data_file.write('* {0} {1} {2} {3} {4} {5}\\n'.format(\n idx + 1, # Amostra\n time_list[idx], # Tempo [s]\n right_vel_ref_list[idx], # Velocidade de referência direita [RPM]\n right_vel_list[idx], # Velocidade direita [RPM]\n left_vel_ref_list[idx], # Velocidade de referência esquerda [RPM]\n left_vel_list[idx])) # Velocidade esquerda [RPM]\n\n# Fechando arquivo\n\ndata_file.close()\n\n###########################################################################################\n###########################################################################################","sub_path":"ensaios/planta_motores/ensaio_planta_motores.py","file_name":"ensaio_planta_motores.py","file_ext":"py","file_size_in_byte":8647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"591156848","text":"# coding=utf-8\nfrom keras.models import load_model\nfrom keras import backend as K\nimport numpy as np\nimport time\n\ndef run_server_infer_time(input_shape=[32, 32, 3], times=200):\n # 加载 Keras model\n TargetNet = load_model('model.h5')\n\n print('Model is ready')\n # 输入\n test_x = np.random.rand(*input_shape)\n test_x = np.asarray(test_x).reshape((1, *input_shape))\n # 预测\n begin = time.time()\n pre_y = TargetNet.predict(test_x)\n pre_y = TargetNet.predict(test_x)\n end = time.time()\n print('used time ', (end - begin) * 1000, ' ms')\n # 统计\n sum_time = 0.0\n for i in range(times):\n begin = time.time()\n pre_y = TargetNet.predict(test_x)\n end = time.time()\n\n sum_time += (end - begin)\n print(i,' used time ', (end - begin) * 1000, ' ms')\n\n print('='*20)\n print('mean used time ', (sum_time)/times * 1000, ' ms')\n\ndef every_layer_runtime(times=200):\n\n # 每层的平均计算延迟\n mean_layer_runtime = []\n\n # 1.加载 Keras model\n TargetNet = load_model('model.h5')\n # 打印总层数\n layer_num = len(TargetNet.layers)\n print('layer_num ', layer_num)\n\n # 2.获取模型节点依赖关系\n layer_dependences = get_model_dependence()\n\n # 3.构造数据输入\n layer_results = {} # 保存每层的输出结果\n for num in range(layer_num):\n\n current_layer = TargetNet.layers[num]\n\n # 处理模型&输入\n if num == 0:\n ''' 第一层'''\n # 当前模型生成\n f_part = K.function([current_layer.input, K.learning_phase()],\n [current_layer.output])\n print('Model is ready')\n # 输入数据构造\n input_shape = TargetNet.layers[0].input_shape[1:]\n print('input_shape ', input_shape)\n input_data = np.random.rand(*input_shape)\n input_data = [np.asarray(input_data).reshape((1, *input_shape))]\n else:\n '''非第一层'''\n pre_nodes = layer_dependences[num]\n\n if len(pre_nodes) == 1:\n '''只有一个前驱节点'''\n # 当前模型生成\n f_part = K.function([current_layer.input, K.learning_phase()],\n [current_layer.output])\n print('Model is ready')\n # 输入数据构造\n pre_node_name = pre_nodes[0][0]\n input_data = [layer_results[pre_node_name]]\n else:\n '''多个前驱节点'''\n # 当前模型生成\n f_part = K.function( current_layer.input + [K.learning_phase()],\n [current_layer.output])\n print('Model is ready')\n # 输入数据构造\n input_data = []\n for pre_node in pre_nodes:\n pre_node_name = pre_node[0]\n print(pre_node_name,layer_results[pre_node_name].shape)\n input_data.append(layer_results[pre_node_name])\n\n # 4.预先执行两次\n layer_out = f_part(input_data + [0])[0]\n layer_out = f_part(input_data + [0])[0]\n\n # 5.开始统计计算时间\n sum_time = 0.0\n for i in range(times):\n begin = time.time()\n\n layer_out = f_part(input_data + [0])[0]\n\n end = time.time()\n\n sum_time += (end - begin)\n print(num ,i, ' used time ', (end - begin) * 1000, ' ms')\n\n # 保存层执行结果\n layer_results[current_layer.name] = layer_out\n\n mean_time = (sum_time) / times * 1000\n print(current_layer.name,'mean used time ', mean_time, ' ms')\n\n mean_layer_runtime.append(mean_time)\n print('='*20)\n return mean_layer_runtime\n\n\ndef get_layer_names():\n # 加载 Keras model\n TargetNet = load_model('model.h5')\n\n return [x.name for x in TargetNet.layers]\n\ndef get_model_dependence():\n\n layer_dependences = [] # [(前驱节点名,inbound_node_index,inbound_tensor_index)...]\n\n # 加载 Keras model\n TargetNet = load_model('model.h5')\n\n # 遍历layer\n for layer in TargetNet.layers:\n previous_nodes = []\n\n # 遍历前驱节点\n for node in layer._inbound_nodes:\n for i in range(len(node.inbound_layers)):\n inbound_layer = node.inbound_layers[i].name\n inbound_node_index = node.node_indices[i]\n inbound_tensor_index = node.tensor_indices[i]\n previous_nodes.append((inbound_layer,inbound_node_index,inbound_tensor_index))\n\n layer_dependences.append(previous_nodes)\n\n\n # 打印最终结果\n for i in range(len(layer_dependences)):\n print(i,layer_dependences[i])\n\n return layer_dependences\n\nif __name__ == '__main__':\n # run_server_infer_time(input_shape=[224, 224, 3])\n\n get_model_dependence()\n\n ''' 统计边缘服务器计算时间 '''\n # 每层的名字\n layer_names = get_layer_names()\n # 每层的计算时间\n mean_layer_runtime = every_layer_runtime()\n # 保存到本地\n assert len(layer_names) == len(mean_layer_runtime)\n with open('EdgeNodeComputeTime.txt','w',encoding='utf-8') as wf:\n for i in range(len(layer_names)):\n wf.write(layer_names[i] + '\\t' + ('%.4f' % mean_layer_runtime[i]) +'\\n')\n # 打印所有层计算时间的总和\n print('sum time ',sum(mean_layer_runtime))\n\n\n\n\n\n\n\n\n","sub_path":"models/ResNet/ResNetTimeCount.py","file_name":"ResNetTimeCount.py","file_ext":"py","file_size_in_byte":5488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"380554797","text":"# 20. JSONデータの読み込み\n# Wikipedia記事のJSONファイルを読み込み,「イギリス」に関する記事本文を表示せよ.\n# 問題21-29では,ここで抽出した記事本文に対して実行せよ.\n\nimport re\nimport json\n\n\ndef get_country_data(country: str) -> str:\n res = \"\"\n with open(\"jawiki-country.json\", \"r\") as file:\n for f in file:\n json_data = json.loads(f)\n if json_data[\"title\"] == country:\n res = json_data[\"text\"]\n break\n return res\n\n\nif __name__ == \"__main__\":\n print(get_country_data(\"イギリス\"))\n","sub_path":"takahashi/chapter03/knock20.py","file_name":"knock20.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"439622686","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/chiararasi/Documents/work/GITs/patientMatcher/patientMatcher/cli/remove.py\n# Compiled at: 2019-04-23 03:57:58\n# Size of source mod 2**32: 2620 bytes\nimport click\nfrom flask.cli import with_appcontext, current_app\nfrom patientMatcher.utils.delete import delete_by_query\n\n@click.group()\ndef remove():\n \"\"\"Remove items from database using the CLI\"\"\"\n pass\n\n\n@remove.command()\n@click.option('-id', type=(click.STRING), nargs=1, required=False, help='ID of the patient to be removed from database')\n@click.option('-label', type=(click.STRING), nargs=1, required=False, help='Label of the patient to be removed from database')\n@click.option('-remove_matches/-leave_matches', default=False, help='Remove or leave on db matches triggered by patient')\n@with_appcontext\ndef patient(id, label, remove_matches):\n \"\"\"Removing a patient from patientMatcher providing its ID\"\"\"\n if not id:\n if not label:\n click.echo('Error: either ID and/or label should be provided to delete a patient.')\n raise click.Abort()\n if remove_matches:\n if not id:\n click.echo('Please provide patient ID and not label to remove all its matches.')\n raise click.Abort()\n query = {}\n if id:\n query['_id'] = id\n else:\n if label:\n query['label'] = label\n n_removed = delete_by_query(query=query, mongo_db=(current_app.db), mongo_collection='patients')\n click.echo('Number of patients removed from database:{}'.format(n_removed))\n if remove_matches:\n query = {'data.patient.id': id}\n n_removed = delete_by_query(query=query, mongo_db=(current_app.db), mongo_collection='matches')\n click.echo('Number of matches for this patient removed from database:{}'.format(n_removed))\n\n\n@remove.command()\n@click.option('-id', type=(click.STRING), nargs=1, required=True, help='ID of the client to be removed from database')\n@with_appcontext\ndef client(id):\n \"\"\"Remove a client from database by providing its ID\"\"\"\n query = {'_id': id}\n n_removed = delete_by_query(query=query, mongo_db=(current_app.db), mongo_collection='clients')\n click.echo('Number of clients removed from database:{}'.format(n_removed))\n\n\n@remove.command()\n@click.option('-id', type=(click.STRING), nargs=1, required=True, help='ID of the node to be removed from database')\n@with_appcontext\ndef node(id):\n \"\"\"Remove a node from database by providing its ID\"\"\"\n query = {'_id': id}\n n_removed = delete_by_query(query=query, mongo_db=(current_app.db), mongo_collection='nodes')\n click.echo('Number of nodes removed from database:{}'.format(n_removed))","sub_path":"pycfiles/patientMatcher-1.1.1.tar/remove.cpython-36.py","file_name":"remove.cpython-36.py","file_ext":"py","file_size_in_byte":2843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"141360573","text":"'''Reverse Polish Notation'''\n\n#!/usr/bin/env python3\n\nclass Stack:\n '''Stack implementation'''\n def __init__(self):\n self._items = []\n def is_empty(self):\n return self._items == []\n def size(self):\n return len(self._items)\n def push(self, new_item):\n self._items.append(new_item)\n def pop(self):\n return self._items.pop()\n def peek(self):\n return self._items[-1]\n\nclass StackError(Exception):\n '''Stack errors'''\n def __init__(self, *args, **kwargs):\n Exception.__init__(self, *args, **kwargs)\n\nclass TokenError(Exception):\n '''Token errors'''\n def __init__(self, *args, **kwargs):\n Exception.__init__(self, *args, **kwargs)\n\ndef rev_string_simple(my_str: str) -> str: # Complete\n '''Reverse characters in a string without using a stack'''\n return my_str[::-1]\n\ndef rev_string_stack(my_str: str) -> str: # Complete\n '''Reverse characters in a string using a stack'''\n string = Stack()\n for i in my_str:\n string.push(i)\n\n rev = \"\"\n for i in range(string.size()):\n rev += string.pop() \n return rev\n \ndef par_checker(line: str) -> bool: # Complete\n '''Textbook implementation'''\n s = Stack()\n balanced = True\n i = 0\n while i < len(line) and balanced:\n symbol = line[i]\n if symbol == \"(\":\n s.push(symbol)\n else:\n if s.is_empty():\n balanced = False\n else:\n s.pop()\n i = i + 1\n if balanced and s.is_empty():\n return True\n else:\n return False\n\ndef par_checker_file(filename: str) -> None: # Complete\n '''Check expressions in the file'''\n with open(filename) as par_file:\n par = par_file.read().split(\"\\n\")\n output = \"\"\n for p in par:\n balanced = par_checker(p)\n if balanced: \n output += (\"{} is balanced\".format(p) + \"\\n\")\n else: \n output += (\"{} is NOT balanced\".format(p) + \"\\n\")\n print(output)\n\ndef base_converter(dec_num, base) -> str: # Complete\n '''Convert any decimal number to any base'''\n hex_digits = {10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F'}\n \n if base in [2,8,16]:\n \n remstack = Stack()\n\n while dec_num > 0:\n rem = dec_num % base\n remstack.push(rem)\n dec_num = dec_num // base\n\n new_string = \"\"\n while not remstack.is_empty():\n\n digit = remstack.pop()\n if digit >= 10: new_string = new_string + hex_digits[digit] # hex_digits[remstack.pop()]\n else: new_string += str(digit)\n\n else: \n raise ValueError(\"Invalid base\")\n\n return new_string\n\ndef rpn_calc(postfix_expr: str):\n '''Evaluate a postfix expression'''\n operand_stack = Stack()\n token_list = postfix_expr.split()\n\n try:\n for ind in range(len(token_list)):\n if token_list[ind] in \"0123456789\":\n # Seperates the operands in a Stack \n operand_stack.push(int(token_list[ind]))\n elif token_list[ind] in \"+-*/\":\n # Does calculations with the operands \n operand2 = operand_stack.pop()\n operand1 = operand_stack.pop()\n result = do_math(token_list[ind],operand1,operand2)\n \n # If the Stack still has elements \n if ind == len(token_list) - 1 and not operand_stack.is_empty():\n raise StackError(\"Stack is not empty\")\n else:\n operand_stack.push(result)\n else:\n raise TokenError(\"Unknown token: {}\".format(token_list[ind]))\n return(operand_stack.pop())\n \n except IndexError:\n raise StackError(\"Stack is empty\")\n \ndef do_math(op, op1, op2):\n if op == \"+\":\n return op1 + op2\n elif op == \"-\":\n return op1 - op2\n elif op == \"*\":\n return op1 * op2\n elif op == \"/\":\n return op1 / op2\n else:\n raise TokenError(\"Unknown token: {}\".format(op))\n\ndef main():\n\n '''String simple reverse'''\n# # print(rev_string_simple(\"123\")) #321 \n# # print(rev_string_simple(\"123\")) #321\n# # print(rev_string_simple(\"abc\")) #cba \n# # print(rev_string_simple(\"abc\")) #cba\n# # print(par_checker_file('data/exercises/stacks/parentheses.txt'))\n\n '''String stack reverse'''\n # print(rev_string_stack(\"Hello\"))\n\n '''Base conversion'''\n# # print(base_converter(1,2)) # 1\n# # print(base_converter(10,16)) # A\n# # print(base_converter(45,8)) # 55\n# # print(base_converter(10,10)) # Error \n\n '''Reverse polish'''\n # print(rpn_calc(\"2 2 2 * +\")) # Error\n # print(rpn_calc(\"a b +\")) # Error\n \nif __name__==\"__main__\":\n main()\n","sub_path":"exercises/stacks/stacks.py","file_name":"stacks.py","file_ext":"py","file_size_in_byte":4827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"634868263","text":"import numpy\n\ndef barycentric_coords(vertices, coordinates):\n \"\"\"Compute barycentric coordinates with respect to a given triangle on a grid.\n\n Parameters:\n vertices: vertices of a triangle as a list (or array) of (x, y) pairs.\n Must be convertible to a shape (3, 2) array.\n coordinates: set of (x, y) coordinates at which to calculate the barycentric\n coordinates. coordinates.shape[0] must be 2; other dimensions will be\n broadcast. E.g. if coordinates.shape = (2, 100), that corresponds\n to a list of 100 (x, y) pairs and the output will be of shape (3, 100).\n On the other hand, if coordinates.shape = (3, 100, 100), that would\n correspond to a 100x100 grid of (x, y) coordinates and the output\n would be of shape (3, 100, 100). Such a grid might come from the\n output of numpy.indices or numpy.meshgrid.\n\n Returns: array of shape (3, ...) containing the 3 barycentric coordinates\n of each of the pixels at position (w, h), where output[0] contains\n the coordinates with respect to vertices[0], and so forth.\n \"\"\"\n vertices = numpy.asarray(vertices)\n coordinates = numpy.asarray(coordinates)\n assert vertices.shape == (3, 2)\n assert coordinates.shape[0] == 2 and coordinates.ndim >= 2\n # set up the problem in the matrix-multiplication form from\n # https://en.wikipedia.org/wiki/Barycentric_coordinate_system\n R = numpy.ones((3, 3))\n R[:2] = vertices.T\n Rinv = numpy.linalg.inv(R)\n # but now instead of computing the full dot product of [x, y, 1] with\n # T for each x and y, we instead just compute the portion of the dot product\n # that varys with [x, y] and then add in the constant values after the fact\n # (which is rather faster)\n barycenters = numpy.einsum('ij,jk...->ik...', Rinv[:, :2], coordinates)\n barycenters += Rinv[:, 2].reshape([3] + [1]*(coordinates.ndim - 1)) # reshape for broadcasting\n return barycenters\n\ndef draw_triangle(vertices, shape):\n \"\"\"Return a mask containing ones for pixels in a given triangle.\n\n Very inefficient! Especially for a large image size and a small triangle.\n Provided SOLELY an example for using barycentric coordinates. Use\n zplib.image.draw.draw_mask() or mask_triangle_strip() for speed.\n\n Parameters:\n vertices: vertices of a triangle as a list (or array) of (x, y) pairs.\n Must be convertible to a shape (3, 2) array.\n shape: shape of output mask.\n \"\"\"\n # add 0.5 to account for fact that pixel centers are at (0.5, 0.5)\n barycenters = barycentric_coords(vertices, numpy.indices(shape) + 0.5)\n return (barycenters >= 0).all(axis=0)\n\ndef gouraud_triangles(triangle_strip, vertex_vals, shape):\n \"\"\"Return a triangle strip Gouraud-shaded based on values at each vertex.\n\n Very inefficient! Provided SOLELY an example for using barycentric\n coordinates. Use zplib.image.draw.gouraud_triangle_strip() for speed.\n\n Parameters:\n triangle_strip: shape (n, 2) array of vertices describing a strip of\n connected triangles (such that vertices (0,1,2) describe the first\n triangle, vertices (1,2,3) describe the second, and so forth).\n vertex_vals: shape (n,) or (n, m) array of values associated with each\n vertex. In case of shape (n, m) this indicates m distinct sets of\n values for each vertex; as such m distinct output images will be\n produced.\n shape: shape of the output image(s).\n\n Returns: (mask, output)\n mask: boolean image of requested shape containing the triangle pixels.\n output: single image (if vertex_vals is 1-dim) or list of images (if\n vertex_vals is > 1-dim), where each image contains the interpolation\n of the values at each vertex.\n \"\"\"\n triangle_strip = numpy.asarray(triangle_strip)\n vertex_vals = numpy.asarray(vertex_vals)\n assert triangle_strip.ndim == 2 and triangle_strip.shape[1] == 2 and len(triangle_strip) > 2\n unpack_out = False\n if vertex_vals.ndim == 1:\n vertex_vals = vertex_vals[:, numpy.newaxis]\n unpack_out = True\n assert len(vertex_vals) == len(triangle_strip)\n grid = numpy.indices(shape) + 0.5 # pixel centers are at (0.5, 0.5 geometrically)\n outputs = [numpy.zeros(shape) for i in range(vertex_vals.shape[1])]\n mask = numpy.zeros(shape, dtype=bool)\n for i in range(len(triangle_strip) - 2):\n vertices = triangle_strip[i:i+3]\n vals = vertex_vals[i:i+3]\n xmn, ymn = numpy.floor(vertices.min(axis=0)).astype(int)\n xmx, ymx = numpy.ceil(vertices.max(axis=0)).astype(int) + 1\n xs, ys = slice(xmn, xmx), slice(ymn, ymx)\n b_coords = barycentric_coords(vertices, grid[:, xs, ys])\n m = (b_coords >= 0).all(axis=0)\n mask[xs, ys] |= m\n b_m = b_coords[:, m]\n for j, out in enumerate(outputs):\n out[xs, ys][m] = vals[:, j].dot(b_m)\n if unpack_out:\n outputs = outputs[0]\n return mask, outputs\n\ndef accumulate_triangles(triangle_strip, shape):\n \"\"\"Return a triangle strip rasterized such that each pixel contains\n a count of the number of triangles atop it.\n\n Very inefficient! Provided SOLELY an example for using barycentric\n coordinates. Use zplib.image.draw.gouraud_triangle_strip() for speed.\n\n Parameters:\n triangle_strip: shape (n, 2) array of vertices describing a strip of\n connected triangles (such that vertices (0,1,2) describe the first\n triangle, vertices (1,2,3) describe the second, and so forth).\n shape: shape of the output image.\n \"\"\"\n triangle_strip = numpy.asarray(triangle_strip)\n assert triangle_strip.ndim == 2 and triangle_strip.shape[1] == 2 and len(triangle_strip) > 2\n grid = numpy.indices(shape) + 0.5 # pixel centers are at (0.5, 0.5 geometrically)\n output = numpy.zeros(shape, dtype=int)\n for i in range(len(triangle_strip) - 2):\n vertices = triangle_strip[i:i+3]\n xmn, ymn = numpy.floor(vertices.min(axis=0)).astype(int)\n xmx, ymx = numpy.ceil(vertices.max(axis=0)).astype(int) + 1\n xs, ys = slice(xmn, xmx), slice(ymn, ymx)\n b_coords = barycentric_coords(vertices, grid[:, xs, ys])\n m = (b_coords >= 0).all(axis=0)\n output[xs, ys] += (b_coords >= 0).all(axis=0)\n return output\n","sub_path":"zplib/image/barycenters.py","file_name":"barycenters.py","file_ext":"py","file_size_in_byte":6393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"463967281","text":"slurm_header = '''#!/bin/sh\n#SBATCH --time=167:00:00 # Run time in hh:mm:ss\n#SBATCH --mem-per-cpu=10000 # Maximum memory required per CPU (in megabytes)\n#SBATCH --job-name=%s\n#SBATCH --error=./%s.err\n#SBATCH --output=./%s.out\n\n%s\n'''\nscript = '/lustre/work/schnablelab/cmiao/TimeSeriesGWAS/Genotype_GBS/GBS_Raw_Data/split_sample.py'\ndata_dir = '/work/schnablelab/cmiao/TimeSeriesGWAS/Genotype_GBS/GBS_Raw_Data/1906UNHX-0018/'\n\ndef genslurm(p, bsp, N):\n p, bsp, N = int(p), int(bsp), int(N)\n for i in range(1, N+1):\n print(i) \n r1 = 'G121_P%s_Bsp_%s_R1_%s.fastq'%(p, bsp, i)\n r2 = 'G121_P%s_Bsp_%s_R2_%s.fastq'%(p, bsp, i)\n bgp = (p-1)*2+bsp\n cmd = 'python %s %s %s bgpR%s'%(script, r1, r2, bgp)\n print(cmd)\n pfx = 'p%s_bsp%s_n%s'%(p,bsp,i)\n with open('split_sm_%s.slurm'%pfx, 'w') as f:\n f.write(slurm_header%(pfx, pfx, pfx, cmd))\n\nimport sys\nif __name__ == '__main__':\n if len(sys.argv)==4:\n genslurm(*sys.argv[1:])\n else:\n print('p bsp n')\n","sub_path":"SNPcalling/scripts/gen_split_sm_slurm.py","file_name":"gen_split_sm_slurm.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"142528093","text":"# _*_ coding: utf-8 _*_\n\n# Source: https://github.com/prakashpandey9/Text-Classification-Pytorch/blob/master/models/selfAttention.py\n# Citation: https://github.com/prakashpandey9/Text-Classification-Pytorch\n\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch.nn import functional as F\n\nclass SelfAttnClassifier(nn.Module):\n def __init__(self, vocab_size, hidden_size=768, num_classes=6):\n super(SelfAttnClassifier, self).__init__()\n\n \"\"\"\n Arguments\n ---------\n num_classes : 2 = (pos, neg)\n hidden_sie : Size of the hidden_state of the LSTM\n vocab_size : Size of the vocabulary containing unique words\n hidden_size : Embeddding dimension of GloVe word embeddings\n weights : Pre-trained GloVe word_embeddings which we will use to create our word_embedding look-up table \n \n --------\n \n \"\"\"\n\n self.num_classes = num_classes\n self.hidden_size = hidden_size\n self.vocab_size = vocab_size\n\n self.word_embeddings = nn.Embedding(vocab_size, hidden_size)\n # self.word_embeddings.weights = nn.Parameter(weights, requires_grad=False)\n self.dropout = 0.8\n self.bilstm = nn.LSTM(hidden_size, hidden_size, dropout=self.dropout, bidirectional=True)\n # We will use da = 350, r = 30 & penalization_coeff = 1 as per given in the self-attention original ICLR paper\n self.W_s1 = nn.Linear(2*hidden_size, 350)\n self.W_s2 = nn.Linear(350, 30)\n self.fc_layer = nn.Linear(30*2*hidden_size, 2000)\n self.label = nn.Linear(2000, num_classes)\n\n def attention_net(self, lstm_output):\n\n \"\"\"\n Now we will use self attention mechanism to produce a matrix embedding of the input sentence in which every row represents an\n encoding of the inout sentence but giving an attention to a specific part of the sentence. We will use 30 such embedding of \n the input sentence and then finally we will concatenate all the 30 sentence embedding vectors and connect it to a fully \n connected layer of size 2000 which will be connected to the output layer of size 2 returning logits for our two classes i.e., \n pos & neg.\n Arguments\n ---------\n lstm_output = A tensor containing hidden states corresponding to each time step of the LSTM network.\n ---------\n Returns : Final Attention weight matrix for all the 30 different sentence embedding in which each of 30 embeddings give\n attention to different parts of the input sentence.\n Tensor size : lstm_output.size() = (batch_size, num_seq, 2*hidden_size)\n attn_weight_matrix.size() = (batch_size, 30, num_seq)\n \"\"\"\n attn_weight_matrix = self.W_s2(F.tanh(self.W_s1(lstm_output)))\n attn_weight_matrix = attn_weight_matrix.permute(0, 2, 1)\n attn_weight_matrix = F.softmax(attn_weight_matrix, dim=2)\n\n return attn_weight_matrix\n\n def forward(self, input_ids, attention_mask=None, _len=None):\n \n input_sentences = input_ids\n\n \n \"\"\" \n Parameters\n ----------\n input_sentence: input_sentence of shape = (batch_size, num_sequences)\n \n Returns\n -------\n Output of the linear layer containing logits for pos & neg class.\n \n \"\"\"\n\n input = self.word_embeddings(input_sentences)\n input = input.permute(1, 0, 2)\n\n output, (h_n, c_n) = self.bilstm(input)\n output = output.permute(1, 0, 2)\n # output.size() = (batch_size, num_seq, 2*hidden_size)\n # h_n.size() = (1, batch_size, hidden_size)\n # c_n.size() = (1, batch_size, hidden_size)\n attn_weight_matrix = self.attention_net(output)\n # attn_weight_matrix.size() = (batch_size, r, num_seq)\n # output.size() = (batch_size, num_seq, 2*hidden_size)\n hidden_matrix = torch.bmm(attn_weight_matrix, output)\n # hidden_matrix.size() = (batch_size, r, 2*hidden_size)\n # Let's now concatenate the hidden_matrix and connect it to the fully connected layer.\n fc_out = self.fc_layer(hidden_matrix.view(-1, hidden_matrix.size()[1]*hidden_matrix.size()[2]))\n logits = self.label(fc_out)\n # logits.size() = (batch_size, num_classes)\n\n return logits","sub_path":"models/baselines/SelfAttn.py","file_name":"SelfAttn.py","file_ext":"py","file_size_in_byte":4356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"134784314","text":"#!/usr/bin/env python3\nfrom pys import sd,test;\nfrom gensim import gensim, fromenergy;\nimport numpy as np;\nc=299792458\ncycles = 80e-15/(780e-9/c);\nEs = [10,1,0.1,0.01,0.001,1e-4];\ndefd = dict(\n dumpinterval=1e-15,\n singlescale=True,\n no_pmovies=False,\n lspexec='lsp-10-xy',\n fp='nc',\n #target\n n_s=1e23,\n solid_len=10,\n expf=1.5,\n #pbs options\n autozipper=True,\n dir=True,\n pbses='defaults',\n #movne\n movne=dict(clim=(1e17,1e23)),\n movni=dict(clim=(1e17,1e23)),\n movdq=dict(clim=(-1e19,1e19),\n linthresh=1e15),\n movrho=dict(clim=(-1e19,1e19),\n linthresh=1e15),\n dump_restart_flag=True,\n dump_collision_energies_flag=True,\n);\npbsfmt='{l}um-{I:0.2e}-l={scale:0.3}um'\ndef mkpbsbase(d):\n l = d['l']/1e-6;\n if l > 1:\n l = int(l);\n else:\n l = '{:0.1f}'.format(l)\n d['pbsbase']=pbsfmt.format(\n l=l,I=d['I'],scale=d['expf']);\n\n####################################\n# 10um scans\n####################################\ndefds=[]\nfor E in Es:\n d = sd(fromenergy(E,cycles=cycles), **defd);\n d.update(\n lim =( -50, 10, -120, 120,0,0),\n tlim=( -40, 0, -110, 110,0,0),\n res =( 60*4, 240*4, 0),\n timestep = 5e-16,\n totaltime= d['T']*3.75,\n description=\"10um\",\n angular=True,\n );\n defds.append(d);\n\n#10um, scale=1.5um\nfor d in defds:\n d['pbsbase']=pbsfmt.format(\n l=int(d['l']/1e-6),I=d['I'],scale=d['expf']);\n gensim(**d);\n#10um, scale=19.2um\nlongs = [sd(\n d,\n n_s=1e21,\n expf=19.2,\n lim =( -250, 10, -120, 120,0,0),\n tlim=( -240, 0, -110, 110,0,0),\n res =( 260*4, 240*4, 0),\n totaltime=d['T']*3.75,\n domains=64,\n #movne\n movne=dict(clim=(1e16,1e21)),\n movni=dict(clim=(1e16,1e21)),\n movdq=dict(clim=(-1e18,1e18),\n linthresh=1e15),\n movrho=dict(clim=(-1e18,1e18),\n linthresh=1e15),)\n for d in defds];\nfor d in longs:\n mkpbsbase(d);\n gensim(**d);\n####################################\n# 3um scans\n####################################\n#3um, scale=1.5um\nfor E in Es:\n d = sd(fromenergy(E,l=3e-6,cycles=cycles), **defd);\n d.update(\n lim =( -50, 10, -60, 60, 0,0),\n tlim=( -40, 0, -50, 50, 0,0),\n res =( 60*10, 120*10, 0),\n timestep = 1.5e-16,\n domains=128,\n region_split=('y',2),\n totaltime= d['T']*3.75,\n description=\"3um\",\n #test!\n splittime=[\n (210e-15, None),\n (400e-15, dict(\n timestep=0.5e-16)),\n (d['T']*3.75, None),\n ],\n\n );\n mkpbsbase(d);\n gensim(**d);\n\n#3um, scale=5.77um\nfor E in Es:\n d = sd(fromenergy(E,l=3e-6,cycles=cycles), **defd);\n d.update(\n n_s=1e23,\n expf=5.77,\n lim =( -90, 10, -60, 60, 0,0),\n tlim=( -80, 0, -50, 50, 0,0),\n res =( 100*10, 120*10, 0),\n description=\"3um w/ 5.77um scale plasma\",\n #mov\n movne=dict(clim=(1e16,1e21)),\n movni=dict(clim=(1e16,1e21)),\n movdq=dict(clim=(-1e18,1e18),\n linthresh=1e15,),\n movrho=dict(clim=(-1e18,1e18),\n linthresh=1e15,),\n #test!\n splittime=[\n (266e-15, None),\n (900e-15, dict(\n timestep=0.5e-16)),\n (d['T']*3.75, None),\n ],\n\n );\n mkpbsbase(d);\n gensim(**d);\n\n\n####################################\n# 3um scans with shelf\n####################################\ndef mkshelf(xdim=(0,50e-4),\n slen=10.0e-4,\n sh=1e19,solid=1e23):\n sdim = (xdim[1] - slen, xdim[1]);\n @np.vectorize\n def out(x):\n if x <= xdim[0] or x >= xdim[1]:\n return 0.0;\n elif sdim[0] <= x <= sdim[1]:\n return solid;\n else:\n return sh;\n return out;\n\nfor E in Es:\n d = sd(fromenergy(E,l=3e-6,cycles=cycles), **defd);\n d.update(\n lim =( -50, 20, -45, 45, 0,0),\n tlim=( -40, 10, -35, 35, 0,0),\n res =( 70*10, 90*10, 0),\n timestep = 1e-16,\n totaltime= d['T']*4,\n description=\"3um\",\n domains=64,\n fp=(0,0,0),\n #density\n singlescale=None,\n dens_dat=\"shelf.dat\",\n externalf_1D=True,\n f_1D=mkshelf(),\n );\n d['pbsbase']='{l}um-{I:0.2e}-shelf'.format(\n l=int(d['l']/1e-6),I=d['I']);\n gensim(**d);\n\n#############################\n# 0.78um scans\n# DESPITE THE NAME, it's 780nm, NOT 800nm\n#############################\nfor E in Es:\n d = sd(fromenergy(E,l=0.78e-6,cycles=cycles), **defd);\n d.update(\n n_s=1e23,\n expf=1.5,\n #\n lim =( -42.5, 10, -15, 15, 0,0),\n tlim=( -32.5, 0, -10, 10, 0,0),\n res =( 52.5*30, 30*30, 0),\n timestep = 1e-16,\n totaltime= d['T']*4,\n dumpinterval = 2e-16,\n description=\"780nm\",\n );\n mkpbsbase(d);\n gensim(**d);\n d.update(\n domains=124,\n restart=23.95,\n timestep=5e-17,\n pbsbase=d['pbsbase']+\"-convg\",\n description=\"780nm convergence test\",);\n gensim(**d);\n d.update(\n domains=124,\n restart=23.95,\n timestep=5e-17,\n pbsbase=d['pbsbase']+\"-spconvg\",\n res =( 52.5*60, 30*60, 0),\n description=\"spatial 780nm convergence test\",);\n gensim(**d);\n\n\n\n\n#############################\n# 0.8um shelf\n#############################\nshelf_780nm=[]\nfor E in Es:\n sh_den=1e19\n d = sd(fromenergy(E,l=0.78e-6,cycles=cycles), **defd);\n d.update(\n lim =( -42.5, 10, -15, 15, 0,0),\n tlim=( -32.5, 0, -10, 10, 0,0),\n res =( 52.5*30, 30*30, 0),\n timestep = 1e-16,\n totaltime= d['T']*4,\n description=\"1um\",\n fp=(0,0,0),\n #density\n singlescale=None,\n dens_dat=\"shelf.dat\",\n externalf_1D=True,\n f_1D=mkshelf(xdim=(0,42.5e-4),sh=sh_den),\n );\n d['pbsbase']='{l}um-{I:0.2e}-shelf={sh}'.format(\n l='0.8',I=d['I'],sh=sh_den);\n gensim(**d);\n shelf_780nm.append(d);\n\n\n \nfor d in shelf_780nm:\n sh = 1e18\n d.update(\n f_1D=mkshelf(xdim=(0,42.5e-4),sh=sh));\n d['pbsbase']='{l}um-{I:0.2e}-shelf={sh}'.format(\n l='0.8',I=d['I'],sh=sh);\n gensim(**d);\n","sub_path":"10um-scans-80fs-convg/genall.py","file_name":"genall.py","file_ext":"py","file_size_in_byte":6256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"479816015","text":"# -*- coding: UTF-8 -*-\nimport os\nimport os.path\nimport threading\n\n\nclass ResourcesManager:\n def __init__(self, path):\n self.path = os.path.normpath(path)\n self.locks = {}\n \n def write(self, path, data, mkdir=False):\n if os.path.isdir(path):\n raise ValueError(f\"Cannot write to {path} for it is a directory!\")\n\n path = self.path + \"/\" + os.path.normpath(path)\n\n if \"..\" in path or path[0] == \"/\":\n raise ValueError(\"Only relative paths to childs are allowed!\")\n\n if mkdir:\n subdirs = os.path.normpath(path).split('/')\n del subdirs[-1]\n os.makedirs('/'.join(subdirs), exist_ok=True)\n\n if not (path in self.locks.keys()):\n self.locks[path] = threading.Lock()\n\n \n with self.locks[path]:\n with open(path, 'w') as file:\n file.write(data)\n\n \n def read(self, path):\n if os.path.isdir(path):\n raise IsADirectoryError(f\"Cannot write to {path} for it is a directory!\")\n \n path = self.path + \"/\" + os.path.normpath(path)\n\n if \"..\" in path or path[0] == \"/\":\n raise ValueError(\"Only relative paths to childs are allowed!\")\n \n if os.path.isdir(path):\n raise ValueError(f\"{path} is a directory\")\n\n if not os.path.isfile(path):\n raise FileNotFoundError(f\"{path} does not exist!\")\n\n data = None\n\n if not (path in self.locks.keys()):\n self.locks[path] = threading.Lock()\n\n with self.locks[path]:\n with open(path, 'r') as file:\n data = file.read()\n \n return data\n\n","sub_path":"src/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"601489288","text":"# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other\n# Spack Project Developers. See the top-level COPYRIGHT file for details.\n#\n# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n\n\nfrom spack.package import *\n\n\nclass Libvterm(Package):\n \"\"\"An abstract library implementation of a terminal emulator\"\"\"\n\n homepage = \"http://www.leonerd.org.uk/code/libvterm/\"\n url = \"http://www.leonerd.org.uk/code/libvterm/libvterm-0.1.3.tar.gz\"\n\n version(\"0.1.4\", sha256=\"bc70349e95559c667672fc8c55b9527d9db9ada0fb80a3beda533418d782d3dd\")\n version(\"0.1.3\", sha256=\"e41724466a4658e0f095e8fc5aeae26026c0726dce98ee71d6920d06f7d78e2b\")\n version(\n \"0.0.0\",\n sha256=\"6344eca01c02e2270348b79e033c1e0957028dbcd76bc784e8106bea9ec3029d\",\n url=\"http://www.leonerd.org.uk/code/libvterm/libvterm-0+bzr726.tar.gz\",\n )\n\n depends_on(\"libtool\", type=\"build\")\n\n def install(self, spec, prefix):\n make()\n make(\"install\", \"PREFIX=\" + prefix)\n","sub_path":"var/spack/repos/builtin/packages/libvterm/package.py","file_name":"package.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"338801278","text":"import frappe\r\nfrom frappe.utils import cint\r\nfrom one_fm.legal.doctype.penalty_issuance.penalty_issuance import get_filtered_employees\r\nfrom one_fm.legal.doctype.penalty.penalty import send_email_to_legal, recognize_face\r\nfrom frappe import _\r\nimport pickle, face_recognition\r\nimport json\r\n\r\n@frappe.whitelist()\r\ndef get_employee_list(shift, penalty_occurence_time):\r\n\ttry:\r\n\t\treturn get_filtered_employees(shift, penalty_occurence_time, as_dict=1)\r\n\texcept Exception as exc:\r\n\t\tprint(frappe.get_traceback())\r\n\t\tfrappe.log_error(frappe.get_traceback())\r\n\t\treturn frappe.utils.response.report_error(exc)\r\n\r\n\r\n@frappe.whitelist()\r\ndef get_penalty_types():\r\n\ttry:\r\n\t\treturn frappe.db.sql(\"\"\"SELECT name, penalty_name_arabic FROM `tabPenalty Type` \"\"\", as_dict=1)\r\n\texcept Exception as exc:\r\n\t\tprint(frappe.get_traceback())\r\n\t\tfrappe.log_error(frappe.get_traceback())\r\n\t\treturn frappe.utils.response.report_error(exc)\r\n\r\n\r\n@frappe.whitelist()\r\ndef get_all_shifts():\r\n\ttry:\r\n\t\treturn frappe.db.sql(\"\"\"SELECT osh.name, osh.site, osh.project, ost.site_location \r\n\t\t\tFROM `tabOperations Shift` osh, `tabOperations Site` ost \r\n\t\t\tWHERE osh.site=ost.name\r\n\t\t\tORDER BY name ASC \"\"\", as_dict=1)\r\n\texcept Exception as exc:\r\n\t\tprint(frappe.get_traceback())\r\n\t\tfrappe.log_error(frappe.get_traceback())\r\n\t\treturn frappe.utils.response.report_error(exc)\r\n\r\n\r\n@frappe.whitelist()\r\ndef issue_penalty(penalty_category, issuing_time, issuing_location, penalty_location, penalty_occurence_time, company_damage, customer_property_damage, asset_damage, other_damages, shift=None, site=None, project=None, site_location=None, penalty_employees=[], penalty_details=[]):\r\n\ttry:\r\n\t\temployee, employee_name, designation = frappe.get_value(\"Employee\", {\"user_id\": frappe.session.user}, [\"name\",\"employee_name\", \"designation\"])\r\n\t\t\r\n\t\tpenalty_issuance = frappe.new_doc(\"Penalty Issuance\")\r\n\t\tpenalty_issuance.penalty_category = penalty_category\r\n\t\t\r\n\t\tpenalty_issuance.issuing_time = issuing_time\r\n\t\tpenalty_issuance.location = issuing_location\r\n\t\tpenalty_issuance.penalty_location = penalty_location\r\n\t\tpenalty_issuance.penalty_occurence_time = penalty_occurence_time\r\n\r\n\t\tpenalty_issuance.issuing_employee = employee\r\n\t\tpenalty_issuance.employee_name = employee_name\r\n\t\tpenalty_issuance.designation = designation\r\n\t\t\r\n\t\tpenalty_issuance.customer_property_damage = cint(customer_property_damage)\r\n\t\tpenalty_issuance.company_damage = cint(company_damage)\r\n\t\tpenalty_issuance.other_damages = cint(other_damages)\r\n\t\tpenalty_issuance.asset_damage = cint(asset_damage)\r\n\r\n\t\temployees = json.loads(penalty_employees)\r\n\t\tfor employee in employees:\r\n\t\t\tpenalty_issuance.append('employees', employee)\r\n\r\n\t\tpenalty_issuance_details = json.loads(penalty_details)\r\n\t\tfor detail in penalty_issuance_details:\r\n\t\t\tpenalty_issuance.append('penalty_issuance_details', detail)\r\n\r\n\t\tif penalty_category == \"Performace\":\r\n\t\t\tpenalty_issuance.shift = shift\r\n\t\t\tpenalty_issuance.site = site\r\n\t\t\tpenalty_issuance.project = project\r\n\t\t\tpenalty_issuance.site_location = site_location\r\n\r\n\r\n\t\tpenalty_issuance.insert()\r\n\t\tpenalty_issuance.submit()\r\n\t\treturn penalty_issuance\r\n\r\n\texcept Exception as exc:\r\n\t\tprint(frappe.get_traceback())\r\n\t\tfrappe.log_error(frappe.get_traceback())\r\n\t\treturn frappe.utils.response.report_error(exc)\r\n\r\n\t\r\n@frappe.whitelist()\r\ndef get_penalties(employee):\r\n\treturn frappe.get_list(\"Penalty\", filters={\"recipient_employee\": employee}, fields=[\"name\", \"penalty_issuance_time\", \"workflow_state\"], order_by=\"modified desc\")\r\n\r\n\r\n@frappe.whitelist()\r\ndef get_penalty_details(penalty_name):\r\n\treturn frappe.get_list(\"Penalty\", {\"name\": penalty_name}, [\"*\"])\r\n\r\n@frappe.whitelist()\r\ndef accept_penalty(file, retries, docname):\r\n\t\"\"\"\r\n\tParams:\r\n\tFile: Base64 url of captured image.\r\n\tRetries: number of tries left out of three\r\n\tDocname: Name of the penalty doctype\r\n\r\n\tReturns: \r\n\t\t'success' message upon verification || updated retries and 'error' message || Exception. \r\n\t\"\"\"\r\n\ttry:\r\n\t\tprint(retries)\r\n\t\tretries_left = cint(retries) - 1\r\n\t\tOUTPUT_IMAGE_PATH = frappe.utils.cstr(frappe.local.site)+\"/private/files/\"+frappe.session.user+\".png\"\r\n\t\tpenalty = frappe.get_doc(\"Penalty\", docname)\r\n\t\tif recognize_face(file, OUTPUT_IMAGE_PATH, retries_left) or retries_left == 0:\r\n\t\t\tif retries_left == 0:\r\n\t\t\t\tpenalty.verified = 0\r\n\t\t\t\tsend_email_to_legal(penalty)\r\n\t\t\telse:\r\n\t\t\t\tpenalty.verified = 1\t\t\r\n\t\t\tpenalty.workflow_state = \"Penalty Accepted\"\r\n\t\t\tpenalty.save(ignore_permissions=True)\r\n\t\t\t\r\n\t\t\tfile_doc = frappe.get_doc({\r\n\t\t\t\t\"doctype\": \"File\",\r\n\t\t\t\t\"file_url\": \"/private/files/\"+frappe.session.user+\".png\",\r\n\t\t\t\t\"file_name\": frappe.session.user+\".png\",\r\n\t\t\t\t\"attached_to_doctype\": \"Penalty\",\r\n\t\t\t\t\"attached_to_name\": docname,\r\n\t\t\t\t\"folder\": \"Home/Attachments\",\r\n\t\t\t\t\"is_private\": 1\r\n\t\t\t})\r\n\t\t\tprint(file_doc.as_dict())\r\n\t\t\tfile_doc.flags.ignore_permissions = True\r\n\t\t\tfile_doc.insert()\r\n\r\n\t\t\tfrappe.db.commit()\r\n\r\n\t\t\treturn {\r\n\t\t\t\t'message': 'success'\r\n\t\t\t}\r\n\t\telse:\r\n\t\t\tpenalty.db_set(\"retries\", retries_left)\r\n\t\t\tfrappe.throw(_(\"Face could not be recognized. You have {0} retries left.\").format(frappe.bold(retries_left)), title='Validation Error')\r\n\r\n\texcept Exception as exc:\r\n\t\tprint(frappe.get_traceback())\r\n\t\tfrappe.log_error(frappe.get_traceback())\r\n\t\treturn frappe.utils.response.report_error(exc)\r\n\r\n@frappe.whitelist()\r\ndef reject_penalty(rejection_reason, docname):\r\n\t\"\"\"\r\n\tParams:\r\n\tReason for rejection: Basis and/or reasoning due to which the employee is rejecting the issuance of penalty.\r\n\tDocname: Name of the penalty doctype\r\n\r\n\tReturns: \r\n\t\t'success' message upon successful rejection of the penalty || 'No penalty found' if the penalty doesnt exist || Exception. \r\n\t\"\"\"\r\n\ttry:\r\n\t\tpenalty = frappe.get_doc(\"Penalty\", docname)\r\n\t\tif penalty.workflow_state == 'Penalty Issued':\r\n\t\t\tpenalty.reason_for_rejection = rejection_reason\r\n\t\t\tpenalty.workflow_state = \"Penalty Rejected\"\r\n\t\t\tpenalty.save(ignore_permissions=True)\r\n\t\t\tfrappe.db.commit()\r\n\t\t\treturn {\r\n\t\t\t\t\t'message': 'success'\r\n\t\t\t\t}\r\n\t\telse:\r\n\t\t\treturn {\r\n\t\t\t\t\t'message': f'No penalty {docname} found'\r\n\t\t\t\t}\r\n\texcept Exception as exc:\r\n\t\tprint(frappe.get_traceback())\r\n\t\tfrappe.log_error(frappe.get_traceback())\r\n\t\treturn frappe.utils.response.report_error(exc)\r\n","sub_path":"one_fm/api/mobile/legal.py","file_name":"legal.py","file_ext":"py","file_size_in_byte":6213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"461810483","text":"#在不改变源码的��况下,修改已经存在的函数(例子中的func),比如增加一句调试声明,以查看传入的参数\n#本例中,document_it()定义了一个装饰器,会实现如下功能:1.打印输出函数的名字和参数的值,2.执行含有参数的函数,3.打印输出结果,4.返回修改后的函数\ndef document_it(func):\n def new_function(*args,**kwargs):\n print('Running function:',func.__name__)\n print('Positional arguments:',args)\n print('Keyword arguments:',kwargs)\n for i in kwargs:\n if i != '':\n #print ('--'+i+'=%s' %kwargs.get(i))\n print('kwargs的键是',kwargs.keys())\n print(kwargs.get(i))\n result = func(*args,**kwargs)\n print('Result:',result)\n return result\n return new_function\ndef add_ints(a,b):\n return a + b\ncooler_add_ints = document_it(add_ints)\ncooler_add_ints(a=3,b=5)","sub_path":"config/version/saneryiwu/VOLUME/装饰器.py","file_name":"装饰器.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"74098132","text":"\"\"\"empty message\n\nRevision ID: 9d2105b2bd16\nRevises: 1848316e6e3b\nCreate Date: 2018-08-11 12:43:57.681300\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '9d2105b2bd16'\ndown_revision = '1848316e6e3b'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('media', sa.Column('abstract', sa.String(length=64), nullable=True))\n op.add_column('media', sa.Column('coauthors', sa.String(length=64), nullable=True))\n op.add_column('media', sa.Column('subject', sa.String(length=64), nullable=True))\n op.create_index(op.f('ix_media_abstract'), 'media', ['abstract'], unique=False)\n op.create_index(op.f('ix_media_coauthors'), 'media', ['coauthors'], unique=False)\n op.create_index(op.f('ix_media_subject'), 'media', ['subject'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_media_subject'), table_name='media')\n op.drop_index(op.f('ix_media_coauthors'), table_name='media')\n op.drop_index(op.f('ix_media_abstract'), table_name='media')\n op.drop_column('media', 'subject')\n op.drop_column('media', 'coauthors')\n op.drop_column('media', 'abstract')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/9d2105b2bd16_.py","file_name":"9d2105b2bd16_.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"413645237","text":"# -*- coding: utf-8 -*-\n\nfrom django.contrib.auth.models import User\nfrom django.db import models\nimport datetime\nfrom django.conf import settings\nfrom django.core.mail import send_mail\nfrom django.template import Context, Template\n\nfrom dashboard import string_with_title\nfrom catalog.models import Item, Size\nimport config\nfrom livesettings import config_value\n\nDELIVERY_TYPE = (('nal', u'Наличными курьеру'),\n ('post', u'Почта России'),\n ('ems', u'EMS Почта России (экспресс почта)'),)\n\ndef sendmail(subject, body, to_email):\n mail_subject = ''.join(subject)\n send_mail(mail_subject, body, settings.DEFAULT_FROM_EMAIL,\n [to_email])\n\ndef get_size(size):\n if size and size != 'None':\n return Size.objects.get(name=size)\n else:\n return None\n\nclass Cart(models.Model):\n user = models.ForeignKey(User, verbose_name=u'пользователь')\n item = models.ForeignKey(Item, verbose_name=u'товар')\n size = models.ForeignKey(Size, blank=True, null=True, verbose_name=u'размер')\n count = models.IntegerField(default=1, verbose_name=u'количество')\n date = models.DateTimeField(default=datetime.datetime.now, verbose_name=u'дата добавления')\n \n \n class Meta:\n verbose_name = u'товар в корзине'\n verbose_name_plural = u'товары в корзине'\n ordering = ['-date']\n app_label = string_with_title(\"shop\", u\"Магазин\")\n \n def __unicode__(self):\n return self.item.name\n\n \n @staticmethod\n def add_to_cart(user, item, size, count=1):\n alr = Cart.objects.filter(user=user, item=item, size=get_size(size))\n if len(alr) == 0:\n Cart(user=user, item=Item.get(item), size=get_size(size), count=count).save()\n else:\n alr[0].count = alr[0].count + count\n alr[0].save()\n \n @staticmethod \n def update(user, dict_): \n for d in dict_:\n Cart(user=user, item=d['item'], count=d['count'], size=get_size(d['size'])).save()\n \n @staticmethod\n def set_count(user, item, size, count):\n if count <= 0:\n Cart.objects.filter(user=user, item=item, size=get_size(size)).delete()\n else: \n alr = Cart.objects.filter(user=user, item=item, size=get_size(size))[0]\n alr.count = count \n alr.save()\n \n @staticmethod\n def count_plus(user, item, size):\n alr = Cart.objects.filter(user=user, item=item, size=get_size(size))[0]\n alr.count += 1 \n alr.save()\n \n \n @staticmethod\n def count_minus(user, item, size):\n alr = Cart.objects.filter(user=user, item=item, size=get_size(size))[0]\n if alr.count <= 1:\n alr.delete()\n return\n alr.count -= 1 \n alr.save()\n \n @staticmethod\n def del_from_cart(user, item, size):\n Cart.objects.filter(user=user, item=item, size=get_size(size)).delete()\n \n @staticmethod \n def clear(user):\n Cart.objects.filter(user=user).delete()\n \n @staticmethod\n def get_price(cap, item):\n opt = cap.is_authenticated() and cap.get_profile().is_opt\n if opt: \n return item.price_opt\n else:\n return item.price\n \n @staticmethod\n def get_content(user):\n cart = list(Cart.objects.filter(user=user))\n res = []\n for c in cart:\n res.append({'item': c.item,\n 'size': c.size,\n 'count': c.count,\n 'price': Cart.get_price(user, c.item),\n 'sum': Cart.get_price(user, c.item) * c.count})\n return res\n \n @staticmethod\n def present_item(user, item):\n cart = list(Cart.objects.filter(user=user, item=item))\n res = []\n for c in cart:\n res.append({'item': c.item,\n 'size': c.size,\n 'count': c.count,\n 'sum': Cart.get_price(user, c.item) * c.count})\n return res\n \n @staticmethod\n def get_count(user, item, size):\n cart = list(Cart.objects.filter(user=user, item=item, size=get_size(size)))\n if len(cart) > 0:\n return cart[0].count\n else:\n return 0\n \n @staticmethod\n def get_goods_count_and_sum(user):\n cart = Cart.get_content(user)\n return (sum([x['count'] for x in cart]), sum([x['count'] * Cart.get_price(user, x['item']) for x in cart]))\n\n\nclass Order(models.Model):\n user = models.ForeignKey(User, verbose_name=u'пользователь')\n date = models.DateTimeField(default=datetime.datetime.now, verbose_name=u'дата заказа')\n comment = models.TextField(blank=True, verbose_name=u'комментарий')\n delivery = models.CharField(choices=DELIVERY_TYPE, max_length=10, blank=True, verbose_name=u'способ доставки')\n is_commit = models.BooleanField(blank=True, default=False, verbose_name=u'заказ отправлен')\n \n class Meta:\n verbose_name = u'заказ'\n verbose_name_plural = u'заказы'\n ordering = ['-date']\n app_label = string_with_title(\"shop\", u\"Магазин\")\n \n def __unicode__(self):\n return str(self.date)\n \n def get_count(self):\n return sum([x.count for x in OrderContent.get_content(self)])\n \n def get_sum(self):\n return sum([x.count * x.price for x in OrderContent.get_content(self)])\n \n def save(self, *args, **kwargs):\n super(Order, self).save(*args, **kwargs)\n \n def send(self):\n OrderContent.move_from_cart(self.user, self)\n self.is_commit = True\n self.save()\n \n subject=u'Поступил новый заказ.',\n body_templ=u\"\"\"\nКонтактное лицо: {{ o.user.get_profile.fio }}\nСсылка на профиль: {{ site }}admin/auth/user/{{ o.user.id }}/\nCпособ доставки: {{ o.get_delivery_display }}\n\nСодержимое:\n {% for c in o.content.all %}\n Ссылка на товар: {{ site }}item/{{ c.item.slug }}/\n {{ c.item.name }} {% if c.size %}\n Размер: {{ c.size }}{% endif %}\n Кол-во: {{ c.count }}\n Цена: {{ c.price }} руб.\n {% endfor %}\n\nОбщая стоимость: {{ o.get_sum }} руб. \n\nСсылка на заказ: {{ site }}admin/shop/order/{{ o.id }}/\n\"\"\"\n body = Template(body_templ).render(Context({'o': self, 'site': 'http://galant.webgenesis.ru/'}))\n sendmail(subject, body, config_value('MyApp', 'EMAIL')) \n \n subject=u'Вы оформили заказ в магазине galant.',\n body_templ=u\"\"\"\n\nСодержимое:\n {% for c in o.content.all %}\n Ссылка на товар: {{ site }}item/{{ c.item.slug }}/\n {{ c.item.name }} {% if c.size %}\n Размер: {{ c.size }}{% endif %} \n Кол-во: {{ c.count }}\n Цена: {{ c.price }} руб.\n {% endfor %}\n\n��бщая стоимость: {{ o.get_sum }} руб. \nCпособ доставки: {{ o.get_delivery_display }}\n\nСкоро с Вами свяжется менеджер. Спасибо.\n\"\"\"\n body = Template(body_templ).render(Context({'o': self, 'site': 'http://galant.webgenesis.ru/'}))\n sendmail(subject, body, self.user.email)\n \n @staticmethod\n def get_recent(user):\n try:\n return Order.objects.filter(user=user, is_commit=False)[0]\n except:\n return None # ошибка, необходимо вернуться на шаг назад\n \n @staticmethod\n def get_or_create(user):\n try:\n return Order.objects.filter(user=user, is_commit=False)[0]\n except:\n u = Order(user=user)\n u.save()\n return u\n \nclass OrderContent(models.Model):\n order = models.ForeignKey(Order, verbose_name=u'заказ', related_name='content')\n item = models.ForeignKey(Item, verbose_name=u'товар')\n size = models.ForeignKey(Size, blank=True, null=True, verbose_name=u'размер')\n count = models.IntegerField(default=1, verbose_name=u'количество')\n \n def __unicode__(self):\n return self.item.name\n \n @staticmethod\n def add(order, item, count, size=None):\n OrderContent(order=order, item=item, size=size, count=count).save()\n \n @staticmethod\n def move_from_cart(user, order):\n cart_content = Cart.get_content(user)\n for c in cart_content:\n OrderContent.add(order, c['item'], c['count'], get_size(c['size']))\n Cart.clear(user) \n \n @staticmethod\n def get_content(order):\n return list(OrderContent.objects.filter(order=order))\n \n @property\n def price(self):\n user = self.order.user\n opt = user.is_authenticated() and user.get_profile().is_opt\n if opt: \n return self.item.price_opt\n else:\n return self.item.price\n ","sub_path":"shop/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":9193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"165875325","text":"# -*- coding: utf-8 -*-\nimport xlsxwriter\nimport requests\nfrom lxml import etree\nimport re\n\nLinks = []\nDates = []\nTitles = []\nContents = []\nWriters = []\n\n#获得范围\ndef getRange():\n baseSite = \"http://www.chinesecome.com/xxxyl/index_0.jhtml\"\n req = requests.get(baseSite, timeout=10)\n req.encoding = req.apparent_encoding\n HTML = etree.HTML(req.text)\n content = \"\".join(HTML.xpath( '//div[@class=\"hrny_ftym\"]//text()'))\n return re.search(r'/(\\d+)页', content).group(1)\n\n#获得链接\ndef getLinkList(pla):\n try:\n baseSite = \"http://www.chinesecome.com/xxxyl/index_【序号】.jhtml\"\n realSite = baseSite.replace(\"【序号】\",str(pla))\n\n #print(realSite)\n\n req = requests.get(realSite, timeout=10)\n req.encoding = req.apparent_encoding\n HTML = etree.HTML(req.text)\n List = HTML.xpath( '//tr/td[@class=\"hrny_lbnrbt\"]/a/@href')\n #print(List)\n finally:\n return list(List)\n\ndef getInf(link):\n try:\n req = requests.get(link, timeout=10)\n req.encoding = req.apparent_encoding\n HTML = etree.HTML(req.text)\n title = HTML.xpath( '//tr/td[@class=\"hrny_xxnrbt\"]/a//text()')\n writer = HTML.xpath( '//td/span[@style=\"float:right;\"]//text()')\n date = HTML.xpath( '//td[@style=\" color:#888888; border-bottom:#e9e9e9 1px solid;\"]/text()')\n content = \"\\n\".join(HTML.xpath( '//td[@class=\"hrny_lbnrxx\"]//text()'))\n finally:\n #print(title,writer,date,content)\n return \"\".join(link),\"\".join(title),\"\".join(date),\"\".join(writer),content\n\n\nif __name__ == '__main__':\n\n # 创建工作簿\n file_name = \"涉侨资讯_休闲娱乐.xlsx\"\n workbook = xlsxwriter.Workbook(file_name)\n\n # 创建工作表\n worksheet = workbook.add_worksheet('休闲娱乐')\n\n # 写单元格\n worksheet.write(0, 0, '链接')\n worksheet.write(0, 1, '新闻')\n worksheet.write(0, 2, '日期')\n worksheet.write(0, 3, '来源')\n worksheet.write(0, 4, '内容')\n\n pla = 1\n maxPag = int(getRange())\n for i in range(0,maxPag):\n print(\"Got\",i)\n Links.extend(getLinkList(i))\n for link in Links:\n print(link)\n inf = getInf(link)\n print(inf)\n worksheet.write_row(pla, 0, inf)\n pla = pla+1\n\n # 关闭工作簿\n workbook.close()","sub_path":"中国华侨华人网/爬取_涉侨咨询_休闲娱乐.py","file_name":"爬取_涉侨咨询_休闲娱乐.py","file_ext":"py","file_size_in_byte":2352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"643636161","text":"# Copyright 2021 MosaicML. All Rights Reserved.\n\nimport argparse\nimport logging\nimport math\n\nimport numpy as np\nimport yaml\n\n\ndef teraflops_for_accelerator(accel):\n \"\"\"\n Stores the number of TFLOPs available to a few accelerators, including driver handicaps.\n\n Args:\n accel (str): A string descriptor of which accelerator to use. Must be either \"3090\" or \"V100\".\n\n Returns:\n accel_flops (int): an integer of how many TFLOPs are in the accelerator.\n \"\"\"\n accel_flops = {\"3090\": 71, \"V100\": 125}\n return accel_flops[accel]\n\n\ndef parse_args():\n \"\"\"\n ArgParse parser.\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--hours\",\n type=float,\n help=\"Number of hours to train for in order to set a total FLOPs budget.\")\n parser.add_argument(\"--accelerator_for_budget\",\n choices=['3090', 'V100'],\n type=str,\n default=\"3090\",\n help=\"Hardware accelerator used to calculate TFLOPs.\")\n parser.add_argument(\n \"--train_sequence_length\",\n type=int,\n default=1024,\n help=\"Fixed sequence length to train on, used for calculating how many batches and serial steps to trian for.\")\n parser.add_argument(\"--warmup_ratio\",\n type=float,\n default=0.1,\n help=\"What % of total training batches to warm up the learning rate for.\")\n parser.add_argument(\"--per_device_batch_size\",\n type=int,\n default=7,\n help=\"Number of training examples to fit per-device.\")\n parser.add_argument(\"--num_devices\", type=int, default=8, help=\"Number of training accelerators to use.\")\n parser.add_argument(\"--output_file\", type=str, help=\"Path to output a YAML file detailing the configuration.\")\n parser.add_argument(\n \"--no_grad_accum\",\n default=False,\n action=\"store_true\",\n help=\"Whether to ignore num_serial_steps predictions and train at smaller optimization batch sizes.\")\n parser.add_argument(\"--validation_freq\",\n default=0.05,\n type=float,\n help=\"Percentage of training steps to run validation for.\")\n parser.add_argument(\"--ssr\", help=\"Scale Schedule Ratio\", type=float, default=1.0)\n parser.add_argument(\"--num_validation_tokens\", help=\"Number of validation tokens\", type=int, default=35262464)\n return parser.parse_args()\n\n\nargs = parse_args()\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\nmodel = {\n \"activation_function\": \"gelu_new\",\n \"architectures\": [\"GPT2LMHeadModel\"],\n \"attn_pdrop\": 0.1,\n \"bos_token_id\": 50256,\n \"embd_pdrop\": 0.1,\n \"eos_token_id\": 50256,\n \"initializer_range\": 0.02,\n \"layer_norm_epsilon\": 1e-05,\n \"model_type\": \"gpt2\",\n \"n_ctx\": 1024,\n \"n_embd\": 768,\n \"n_head\": 12,\n \"n_inner\": None,\n \"n_layer\": 12,\n \"n_positions\": 1024,\n \"resid_pdrop\": 0.1,\n \"scale_attn_weights\": True,\n \"summary_activation\": None,\n \"summary_first_dropout\": 0.1,\n \"summary_proj_to_labels\": True,\n \"summary_type\": \"cls_index\",\n \"summary_use_proj\": True,\n \"task_specific_params\": {\n \"text-generation\": {\n \"do_sample\": True,\n \"max_length\": 50\n }\n },\n \"transformers_version\": \"4.11.0.dev0\",\n \"use_cache\": True,\n \"vocab_size\": 50257\n}\n\ntemplate_yaml = {\n 'train_dataset': {\n 'lm': {\n 'split': 'train',\n 'datadir': ['/datasets/openwebtext_saved'],\n 'tokenizer_name': 'gpt2',\n 'seed': 17,\n 'shuffle': False,\n 'drop_last': False\n }\n },\n 'val_dataset': {\n 'lm': {\n 'split': 'validation',\n 'datadir': ['/datasets/openwebtext_saved'],\n 'tokenizer_name': 'gpt2',\n 'seed': 17,\n 'shuffle': False,\n 'drop_last': False\n }\n },\n 'model': {\n 'gpt2': {\n 'use_pretrained': False,\n \"tokenizer_name\": \"gpt2\",\n 'model_config': model\n }\n },\n 'optimizer': {\n 'adamw': {\n 'lr': 0.0003,\n 'betas': [0.9, 0.999],\n 'eps': 1e-06,\n 'weight_decay': 0.0\n }\n },\n 'schedulers': [{\n 'warmup': {\n 'warmup_method': 'linear',\n 'warmup_factor': 0,\n 'interval': 'step',\n 'warmup_iters': 1\n }\n }, {\n 'cosine_decay': {\n 'T_max': 2,\n 'interval': 'step',\n 'eta_min': 1.0e-5,\n 'verbose': False\n }\n }],\n 'loggers': [\n {\n 'file': {\n 'log_level': 'BATCH',\n 'filename': 'stdout',\n 'buffer_size': 1,\n 'flush_every_n_batches': 100,\n 'every_n_epochs': 1,\n 'every_n_batches': 100\n }\n },\n {\n 'wandb': {\n \"project\": \"gpt2\",\n \"name\": f\"gpt2-{args.hours}-ga-{not args.no_grad_accum}\",\n 'extra_init_params': {}\n }\n },\n ],\n 'max_epochs': 1,\n 'total_batch_size': 8,\n 'eval_batch_size': 8,\n 'seed': 17,\n 'accelerator': {\n 'gpu': {\n 'n_gpus': 1,\n 'prefetch_in_cuda_stream': False,\n }\n },\n 'dataloader': {\n 'pin_memory': True,\n 'persistent_workers': True,\n 'num_workers': 8,\n 'timeout': 0,\n 'prefetch_factor': 2\n },\n 'grad_accum': 1,\n 'precision': 'amp',\n 'grad_clip_norm': 1.0,\n}\n\n\ndef generate_architecture(args, model):\n \"\"\"\n Given the desired training budget and a template model, configure the model archtiecture according to\n \"Scaling Laws for Neural Language Models\" by Kaplan et al.\n\n Args:\n args (argparse.Namespace): the Namespace object holding the parsed arguments.\n model (Mapping): a dictionary of a base model to configure.\n \"\"\"\n accelerator_hours = args.hours\n practical_efficiency = 1.0 / 4.0\n hours_to_day = 1.0 / 24.0\n teraflops = teraflops_for_accelerator(args.accelerator_for_budget)\n teraflops_to_petaflops = 1.0 / 10**3\n\n desired_petaflop_days = teraflops * practical_efficiency * \\\n hours_to_day * teraflops_to_petaflops * accelerator_hours\n petaflop_day_const = 3.1 * 10**8\n compute_exp = 0.050\n predicted_loss = (petaflop_day_const / desired_petaflop_days)**compute_exp\n\n dataset_exp = 0.27\n dataset_const = 2 * 10**10\n min_dataset_size = dataset_const * desired_petaflop_days**dataset_exp\n min_dataset_size = round(min_dataset_size)\n\n model_const = 1.3 * 10**9\n model_exp = 0.73\n min_model_size = model_const * desired_petaflop_days**model_exp\n min_model_size = round(min_model_size)\n\n serial_const = 5.4 * 10**3\n serial_exp = 0.03\n num_serial_steps = serial_const * desired_petaflop_days**serial_exp\n num_serial_steps = round(num_serial_steps)\n\n expected_lr = 0.003239 - (0.0001395 * np.log(min_model_size))\n\n logger.info(f\"For a compute budget of {accelerator_hours} GPU hours:\")\n logger.info(\"----------------- GENERAL PARAMETERS -----------------\")\n logger.info(f\"Predicted loss: {predicted_loss}\")\n logger.info(f\"Predicted perplexity: {np.exp(predicted_loss)}\")\n logger.info(f\"Predicted minimum dataset size: {min_dataset_size:,}\")\n logger.info(f\"Predicted minimum model size: {min_model_size:,}\")\n logger.info(f\"Predicted minimum serial steps: {num_serial_steps:,}\")\n logger.info(f\"Predicted learning rate: {expected_lr:e}\")\n logger.info(\"\\n\")\n\n # See Eqn. 2.1 from https://arxiv.org/pdf/2001.08361.pdf for derivation of these equations\n d_model = ((min_model_size) * 100.0) / 12.0\n d_model = d_model**(1.0 / 3.0)\n n_layers = d_model / 100.0\n\n n_layers = math.ceil(n_layers)\n\n feedforward_ratio = 4\n d_ff = feedforward_ratio * d_model\n\n attn_head_ratio = 50\n n_head = d_model / attn_head_ratio\n n_head = math.ceil(n_head)\n\n # make sure d_model is a multiple of n_head and gpu tile size\n gpu_tile_size = 8\n d_model = (n_head * gpu_tile_size) * int(round(d_model / (n_head * gpu_tile_size)))\n d_ff = gpu_tile_size * round(d_ff / gpu_tile_size)\n\n logger.info(\"----------------- MODEL ARCHITECTURE DETAILS -----------------\")\n logger.info(f\"Number of layers: {n_layers}\")\n logger.info(f\"Hidden dimension: {d_model}\")\n logger.info(f\"Number of attention heads: {n_head}\")\n logger.info(f\"Feedforward dimension: {d_ff}\")\n\n model['n_embd'] = d_model\n model['n_head'] = n_head\n model['n_layer'] = n_layers\n model['n_inner'] = d_ff\n\n scaling_law_predictions = {}\n scaling_law_predictions['pred_loss'] = predicted_loss\n scaling_law_predictions['pred_ppl'] = np.exp(predicted_loss)\n scaling_law_predictions['pred_min_dataset_size'] = min_dataset_size\n scaling_law_predictions[\"pred_min_model_size\"] = min_model_size\n scaling_law_predictions['pred_min_serial_steps'] = num_serial_steps\n scaling_law_predictions['pred_lr'] = float(expected_lr)\n return model, scaling_law_predictions\n\n\ndef configure_mosaic_yaml(model, scaling_law_predictions):\n template_yaml['optimizer']['adamw']['lr'] = scaling_law_predictions['pred_lr']\n\n logger.info(\"----------------- OPTIMIZATION INFORMATION -----------------\")\n logger.info(f\"Number of tokens: {scaling_law_predictions['pred_min_dataset_size']:.4e}\")\n num_training_tokens = math.ceil(scaling_law_predictions['pred_min_dataset_size'])\n\n curr_num_batches = num_training_tokens // args.train_sequence_length\n min_serial_steps = scaling_law_predictions['pred_min_serial_steps']\n batch_size = args.per_device_batch_size * args.num_devices\n curr_serial_steps = math.ceil(curr_num_batches / batch_size)\n\n # we ignore the grad accum paramters to make Mosaic Trainer easier to work with\n if args.no_grad_accum:\n lr_scaling_factor = math.floor(curr_serial_steps / min_serial_steps)\n template_yaml['optimizer']['adamw']['lr'] = template_yaml['optimizer']['adamw']['lr'] / lr_scaling_factor\n curr_grad_accum = 1\n else:\n curr_grad_accum = int(math.floor(curr_serial_steps / min_serial_steps))\n\n batch_size = args.per_device_batch_size * args.num_devices * curr_grad_accum\n orig_serial_steps = math.ceil(curr_num_batches / batch_size)\n logger.info(f\"Applying Scale Schedule Ratio = {args.ssr}\")\n final_serial_steps = math.ceil(orig_serial_steps * args.ssr)\n\n total_tokens_trained = args.train_sequence_length * batch_size * final_serial_steps\n\n # permit a 1% difference in number of training tokens in order to ensure we don't drop batches\n assert abs((((total_tokens_trained) / args.ssr) - num_training_tokens) / num_training_tokens) < 1e-2\n num_training_tokens = total_tokens_trained\n logger.info(f\"New number of tokens: {num_training_tokens:.4e}\")\n\n template_yaml['train_dataset']['lm']['num_tokens'] = num_training_tokens\n template_yaml['val_dataset']['lm']['num_tokens'] = args.num_validation_tokens\n\n logger.info(f\"Total batch size: {batch_size:,}\")\n logger.info(f\"Total grad accum: {curr_grad_accum:,}\")\n logger.info(f\"Minumum possible serial optimization steps before SSR: {min_serial_steps:,}\")\n logger.info(f\"Minumum possible serial optimization steps after SSR: {math.ceil(args.ssr * min_serial_steps):,}\")\n logger.info(f\"Current serial optimization steps: {final_serial_steps:,}\")\n template_yaml['total_batch_size'] = batch_size\n assert math.floor(batch_size / curr_grad_accum) == (batch_size / curr_grad_accum)\n template_yaml['eval_batch_size'] = math.floor(batch_size / curr_grad_accum)\n template_yaml['grad_accum'] = curr_grad_accum\n template_yaml['accelerator']['gpu']['n_gpus'] = args.num_devices\n warmup_steps = round(orig_serial_steps * args.warmup_ratio)\n decay_steps = final_serial_steps - warmup_steps\n template_yaml['schedulers'][0]['warmup']['warmup_iters'] = f\"{warmup_steps}ba\"\n template_yaml['schedulers'][1]['cosine_decay']['T_max'] = f\"{decay_steps}ba\"\n template_yaml['model']['gpt2']['model_config'] = model\n\n validation_freq = math.floor(final_serial_steps * args.validation_freq)\n\n return template_yaml\n\n\nif __name__ == \"__main__\":\n model, scaling_law_predictions = generate_architecture(args, model)\n template_yaml = configure_mosaic_yaml(model, scaling_law_predictions)\n\n with open(args.output_file, \"w+\") as f:\n yaml.dump(template_yaml, f, sort_keys=False)\n","sub_path":"composer/models/gpt2/scaling_laws_generator.py","file_name":"scaling_laws_generator.py","file_ext":"py","file_size_in_byte":12691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"116263601","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 ('newmailing', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='onemessage',\n name='unisender_id',\n field=models.CharField(null=True, verbose_name='ID сообщения у Unisender', max_length=50),\n ),\n ]\n","sub_path":"newmailing/migrations/0002_auto_20161009_0614.py","file_name":"0002_auto_20161009_0614.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"383238434","text":"import base64\r\n\r\nfrom Cryptodome.Cipher import AES\r\nfrom cryptography.hazmat.primitives import hashes, serialization\r\nfrom cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey\r\nfrom cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey, Ed25519PrivateKey\r\nfrom cryptography.hazmat.primitives.kdf.hkdf import HKDF\r\nfrom cryptography.hazmat.backends import default_backend\r\n\r\n\r\ndef b64(msg):\r\n # from bytes to string(base 64) \r\n # strip delete spaces in the strart and end\r\n return base64.encodebytes(msg).decode('utf-8').strip()\r\n\r\n\r\n# Lev to do\r\ndef hkdf(inp, length):\r\n # use HKDF on an input to derive a key\r\n hkdf = HKDF(algorithm=hashes.SHA256(), length=length, salt=b'',\r\n info=b'', backend=default_backend())\r\n return hkdf.derive(inp)\r\n\r\ndef pad(msg):\r\n # pkcs7 padding\r\n num = 16 - (len(msg) % 16)\r\n return msg + bytes([num] * num)\r\n\r\n\r\ndef unpad(msg):\r\n # remove pkcs7 padding\r\n return msg[:-msg[-1]]\r\n\r\n\r\nclass SymmRatchet(object):\r\n def __init__(self, key):\r\n self.state = key\r\n\r\n def next(self, inp=b''):\r\n # turn the ratchet, changing the state and yielding a new key and IV\r\n output = hkdf(self.state + inp, 80)\r\n self.state = output[:32]\r\n outkey, iv = output[32:64], output[64:]\r\n return outkey, iv\r\n\r\n\r\nclass Bob(object):\r\n def __init__(self):\r\n # generate Bob's keys\r\n self.IKb = X25519PrivateKey.generate()\r\n self.SPKb = X25519PrivateKey.generate()\r\n #self.OPKb = X25519PrivateKey.generate()\r\n self.DHratchet = X25519PrivateKey.generate()\r\n\r\n def x3dh(self, alice):\r\n # perform the 4 Diffie Hellman exchanges (X3DH)\r\n dh1 = self.SPKb.exchange(alice.IKa.public_key())\r\n dh2 = self.IKb.exchange(alice.EKa.public_key())\r\n dh3 = self.SPKb.exchange(alice.EKa.public_key())\r\n # dh4 = self.OPKb.exchange(alice.EKa.public_key())\r\n # the shared key is KDF(DH1||DH2||DH3||DH4)\r\n self.sk = hkdf(dh1 + dh2 + dh3, 32)\r\n\r\n def init_ratchets(self):\r\n # initialise the root chain with the shared key\r\n self.root_ratchet = SymmRatchet(self.sk)\r\n # initialise the sending and recving chains\r\n self.recv_ratchet = SymmRatchet(self.root_ratchet.next()[0])\r\n self.send_ratchet = SymmRatchet(self.root_ratchet.next()[0])\r\n\r\n def dh_ratchet(self, alice_public):\r\n dh_recv = self.DHratchet.exchange(alice_public)\r\n shared_recv = self.root_ratchet.next(dh_recv)[0]\r\n # use Alice's public and our old private key\r\n # to get a new recv ratchet\r\n self.recv_ratchet = SymmRatchet(shared_recv)\r\n print('[Bob]\\tRecv ratchet seed:', b64(shared_recv))\r\n # generate a new key pair and send ratchet\r\n # our new public key will be sent with the next message to Alice\r\n self.DHratchet = X25519PrivateKey.generate()\r\n dh_send = self.DHratchet.exchange(alice_public)\r\n shared_send = self.root_ratchet.next(dh_send)[0]\r\n self.send_ratchet = SymmRatchet(shared_send)\r\n print('[Bob]\\tSend ratchet seed:', b64(shared_send))\r\n\r\n def dh_ratchet(self, bob_public):\r\n # perform a DH ratchet rotation using Bob's public key\r\n if self.DHratchet is not None:\r\n # the first time we don't have a DH ratchet yet\r\n dh_recv = self.DHratchet.exchange(bob_public)\r\n shared_recv = self.root_ratchet.next(dh_recv)[0]\r\n # use Bob's public and our old private key\r\n # to get a new recv ratchet\r\n self.recv_ratchet = SymmRatchet(shared_recv)\r\n print('[Alice]\\tRecv ratchet seed:', b64(shared_recv))\r\n # generate a new key pair and send ratchet\r\n # our new public key will be sent with the next message to Bob\r\n self.DHratchet = X25519PrivateKey.generate()\r\n dh_send = self.DHratchet.exchange(bob_public)\r\n shared_send = self.root_ratchet.next(dh_send)[0]\r\n self.send_ratchet = SymmRatchet(shared_send)\r\n print('[Alice]\\tSend ratchet seed:', b64(shared_send))\r\n\r\n\r\n\r\n\r\n\r\n def send(self, alice, msg):\r\n \tkey, iv = self.send_ratchet.next()\r\n \tcipher = AES.new(key, AES.MODE_CBC, iv).encrypt(pad(msg))\r\n \tprint('[Bob]\\tSending ciphertext to Alice:', b64(cipher))\r\n \t# send ciphertext and current DH public key\r\n \talice.recv(cipher, self.DHratchet.public_key())\r\n\r\n def recv(self, cipher, alice_public_key):\r\n\t # receive Alice's new public key and use it to perform a DH\r\n\t self.dh_ratchet(alice_public_key)\r\n\t key, iv = self.recv_ratchet.next()\r\n\t # decrypt the message using the new recv ratchet\r\n\t msg = unpad(AES.new(key, AES.MODE_CBC, iv).decrypt(cipher))\r\n\t print('[Bob]\\tDecrypted message:', msg)\r\n\r\n\r\nclass Alice(object):\r\n def __init__(self):\r\n # generate Alice's keys\r\n self.IKa = X25519PrivateKey.generate()\r\n self.EKa = X25519PrivateKey.generate()\r\n self.DHratchet = None\r\n\r\n def x3dh(self, bob):\r\n # perform the 4 Diffie Hellman exchanges (X3DH)\r\n dh1 = self.IKa.exchange(bob.SPKb.public_key())\r\n dh2 = self.EKa.exchange(bob.IKb.public_key())\r\n dh3 = self.EKa.exchange(bob.SPKb.public_key())\r\n # dh4 = self.EKa.exchange(bob.OPKb.public_key())\r\n # the shared key is KDF(DH1||DH2||DH3||DH4)\r\n self.sk = hkdf(dh1 + dh2 + dh3, 32)\r\n\r\n def init_ratchets(self):\r\n # initialise the root chain with the shared key\r\n self.root_ratchet = SymmRatchet(self.sk)\r\n # initialise the sending and recving chains\r\n self.send_ratchet = SymmRatchet(self.root_ratchet.next()[0])\r\n self.recv_ratchet = SymmRatchet(self.root_ratchet.next()[0])\r\n\r\n def dh_ratchet(self, bob_public):\r\n # perform a DH ratchet rotation using Bob's public key\r\n if self.DHratchet is not None:\r\n # the first time we don't have a DH ratchet yet\r\n dh_recv = self.DHratchet.exchange(bob_public)\r\n shared_recv = self.root_ratchet.next(dh_recv)[0]\r\n # use Bob's public and our old private key\r\n # to get a new recv ratchet\r\n self.recv_ratchet = SymmRatchet(shared_recv)\r\n print('[Alice]\\tRecv ratchet seed:', b64(shared_recv))\r\n # generate a new key pair and send ratchet\r\n # our new public key will be sent with the next message to Bob\r\n self.DHratchet = X25519PrivateKey.generate()\r\n dh_send = self.DHratchet.exchange(bob_public)\r\n shared_send = self.root_ratchet.next(dh_send)[0]\r\n self.send_ratchet = SymmRatchet(shared_send)\r\n print('[Alice]\\tSend ratchet seed:', b64(shared_send))\r\n\r\n def send(self, alice, msg):\r\n key, iv = self.send_ratchet.next()\r\n cipher = AES.new(key, AES.MODE_CBC, iv).encrypt(pad(msg))\r\n print('[Bob]\\tSending ciphertext to Alice:', b64(cipher))\r\n # send ciphertext and current DH public key\r\n alice.recv(cipher, self.DHratchet.public_key())\r\n\r\n def recv(self, cipher, alice_public_key):\r\n # receive Alice's new public key and use it to perform a DH\r\n self.dh_ratchet(alice_public_key)\r\n key, iv = self.recv_ratchet.next()\r\n # decrypt the message using the new recv ratchet\r\n msg = unpad(AES.new(key, AES.MODE_CBC, iv).decrypt(cipher))\r\n print('[Bob]\\tDecrypted message:', msg)\r\n\r\n\r\nalice = Alice()\r\nbob = Bob()\r\n\r\n# Alice performs an X3DH while Bob is offline, using his uploaded keys\r\nalice.x3dh(bob)\r\n\r\n# Bob comes online and performs an X3DH using Alice's public keys\r\nbob.x3dh(alice)\r\n\r\n# Initialize their symmetric ratchets\r\nalice.init_ratchets()\r\nbob.init_ratchets()\r\n\r\n# Initialise Alice's sending ratchet with Bob's public key\r\nalice.dh_ratchet(bob.DHratchet.public_key())\r\n\r\n\r\n# alice.send(bob, b'Hello Bob!')\r\n# bob.send(alice, b'Hello Alice!')\r\n# alice.send(bob, b'How are you?')\r\n# bob.send(alice, b'Fine!')\r\n\r\nwhile True:\r\n\tmsg = input(\"Alice: \")\r\n\tif msg == \"exit\":\r\n\t\tbreak\r\n\talice.send(bob, msg.encode('utf-8'))\r\n\tmsg = input(\"Bob: \")\r\n\tif msg == \"exit\":\r\n\t\tbreak\r\n\tbob.send(alice, msg.encode('utf-8'))","sub_path":"DH.py","file_name":"DH.py","file_ext":"py","file_size_in_byte":8165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"100585388","text":"from datetime import datetime\nfrom flask import render_template, flash, redirect, url_for, request, g, jsonify, current_app\nfrom app import db\nfrom app.models import Contract, Execution, Bbg\nfrom app.executions import bp\n\n@bp.route('/', methods=['GET', 'POST'])\n@bp.route('/index', methods=['GET', 'POST'])\ndef index():\n return jsonify( {'status': 'ok'} )\n\n\n@bp.route('/executions', methods=['GET'])\ndef list():\n executions = Execution.query.all()\n for exec in executions:\n current_app.logger.info(exec.contract.localSymbol)\n bbg = exec.contract.bbg\n if bbg != None:\n current_app.logger.info(exec.contract.bbg.ticker)\n return jsonify( {'status': 'ok'} )\n\n\n\n@bp.route('/executions/time/', methods=['GET'])\ndef list_limit_date(date_str):\n executions = Execution.query.filter(Execution.time >= date_str).all()\n\n execs = {} # dict with execId as key\n for exec in executions:\n one_exec = {}\n\n one_exec['execId'] = exec.execId\n one_exec['orderId'] = exec.orderId\n one_exec['time'] = exec.time\n one_exec['acctNumber'] = exec.acctNumber\n one_exec['exchange'] = exec.exchange\n one_exec['side'] = exec.side\n one_exec['shares'] = exec.shares # execQty\n one_exec['cumQty'] = exec.cumQty\n one_exec['price'] = exec.price\n one_exec['avgPrice'] = exec.avgPrice\n one_exec['permId'] = exec.permId\n\n\n one_exec['contract'] = {\n 'localSymbol': exec.contract.localSymbol\n }\n bbg = exec.contract.bbg\n if bbg != None:\n one_exec['bbg'] = {\n 'ticker': exec.contract.bbg.ticker,\n 'bbgIdentifier': exec.contract.bbg.bbgIdentifier,\n 'bbgUnderylingId': exec.contract.bbg.bbgUnderylingId,\n 'internalUnderlying': exec.contract.bbg.internalUnderlying\n }\n execs[exec.execId] = one_exec\n\n return jsonify( {\n 'status': 'ok',\n 'time': date_str,\n 'count': len(executions),\n 'executions': execs\n } )\n\n\n\n@bp.route('/executions', methods=['GET'])\ndef read():\n return jsonify( {'status': 'ok'} )\n\n\n@bp.route('/executions', methods=['POST'])\ndef create():\n try:\n data = request.get_json()\n except:\n return jsonify( {'status': 'error', 'error': 'missing data'} )\n\n if data == None:\n return jsonify( {'status': 'error', 'error': 'missing data'} )\n\n # query if contract already exists\n current_app.logger.info('check contract: ' + data['localSymbol'])\n contract = Contract.query.get(data['localSymbol'])\n if contract != None:\n current_app.logger.info('existing contract')\n else:\n if data['localSymbol'] == '':\n localSymbol = data['symbol']\n else:\n localSymbol=data['localSymbol']\n\n if data['strike'] > 0:\n strike = data['strike']\n else:\n strike = None\n\n if data['right'] != '':\n right = data['right']\n else:\n right = None\n\n contract = Contract(\n secType=data['secType'],\n localSymbol=localSymbol,\n symbol=data['symbol'],\n currency=data['currency'],\n exchange=data['exchange'],\n primaryExchange=data['primaryExchange'],\n lastTradeDateOrContractMonth=data['lastTradeDateOrContractMonth'], #datetime\n multiplier=data['multiplier'],\n strike=strike,\n right=right\n )\n db.session.add(contract)\n db.session.commit()\n current_app.logger.info('new contract')\n\n\n # insert executions\n current_app.logger.info('check execution: ' + data['execId'])\n execution = Execution.query.get(data['execId'])\n if execution != None:\n current_app.logger.info('existing execution')\n else:\n\n shares = abs(data['shares'])\n cumQty = abs(data['cumQty'])\n if data['side'][0].upper() == 'B':\n pass\n elif data['side'][0].upper() == 'S':\n shares = -shares\n cumQty = -cumQty\n\n execution = Execution(\n execId=data['execId'],\n orderId=data['orderId'],\n asset=contract, # object\n time=datetime.strptime( data['time'], '%Y%m%d %H:%M:%S'), # 20180604 13:32:52\n acctNumber=data['acctNumber'],\n exchange=data['exchange'],\n side=data['side'],\n shares=shares,\n cumQty=cumQty,\n price=data['price'],\n avgPrice=data['avgPrice'],\n permId=data['permId']\n\n )\n db.session.add(execution)\n db.session.commit()\n current_app.logger.info('new execution')\n\n return jsonify( {\n 'status': 'ok',\n 'inputData': data,\n 'contract': {'localSymbol': contract.localSymbol},\n 'order': {'orderId': execution.orderId},\n 'execution': {'execId': execution.execId}\n } )\n","sub_path":"app/executions/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":4981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"562235316","text":"\ntable = ['MMM', 'GMM', 'MGM', 'MMG', 'MGG', 'GMG', 'GGM', 'GGG']\n\nn = int(input())\n\nfor i in range(n):\n\n count = [0 for x in range(8)]\n str = input()\n\n for x in range(0, len(str), 3):\n cut = str[x:x+3]\n count[table.index(cut)] += 1\n\n # print the count\n for x in count:\n print(x, end='')\n\n print('') # newline\n","sub_path":"PROMED@CS/PROMED@CS 2011/Python/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"358638267","text":"from urllib import parse,request\nimport json\nfrom flask import Flask, jsonify\nfrom flask import request\nimport urllib\nfrom bs4 import BeautifulSoup\nfrom app import app\nimport requests\nimport random\nimport socket\n\n\n@app.route('/main_fun', methods=['GET','POST'])\ndef main_fun():\n if request.method == 'POST':\n dic1 = request.form\n #print(dic1.to_dict())\n dic2 = dic1.to_dict()\n dic3 = parse.urlencode (dic2).encode (encoding='utf-8')\n header_dict = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko',\n \"Content-Type\": \"application/x-www-form-urlencoded\"}\n url = 'http://59.72.194.12:8086/index.aspx'\n req = urllib.request.Request (url=url, data=dic3, headers=header_dict)\n res = urllib.request.urlopen (req)\n final_data = res.read ( ).decode ('utf-8')\n #print (final_data)\n return final_data\n #return jsonify(dic1)\n #iplist = ['http://59.72.194.12:8086/index.aspx','http://59.72.194.19:8081/index.aspx','http://59.72.194.19:9001/index.aspx','http://59.72.194.12:9099/index.aspx']\n #url = random.choice(iplist)\n url = 'http://59.72.194.21:9099/index.aspx'\n req = urllib.request.Request (url=url, data=dic3, headers=header_dict)\n res = urllib.request.urlopen (req)\n final_data = res.read ( ).decode ('utf-8')\n #print (final_data)\n res.close()\n return final_data\n #return jsonify(dic1) \n\n@app.route('/table', methods=['GET','POST'])\ndef get_table():\n if request.method == 'POST':\n username = request.form.get['studentNo']\n pwd = request.form.get['password']\n from app import login_cookie\n cookiee = login_cookie.main ( )\n cookies = cookiee.get_cookie (username, pwd)\n url2 = 'http://59.72.194.13/TimetableSearch/TimetableSerachStudentSingleSpan.aspx'\n r = urllib.requests.get (url2, cookies=cookies)\n username = request.form.get('studentNo')\n pwd = request.form.get('password')\n from app import login_cookies_new\n cookiee = login_cookies_new.main ( )\n cookies = cookiee.get_cookie (username, pwd)\n url2 = 'http://59.72.194.13/TimetableSearch/TimetableSerachStudentSingleSpan.aspx'\n r = requests.get (url2, cookies=cookies)\n soup = BeautifulSoup (r.content, 'html.parser', from_encoding='utf-8')\n tables = soup.findAll ('table', id='TableLCRoomOccupy')\n tab = tables[0]\n # print(tab)\n cont = tab.findAll ('tr')\n # print(cont[1])\n # for td in tr.find_all('td'):\n lists = []\n list1 = []\n list2 = []\n list3 = []\n list4 = []\n list5 = []\n # print(cont[1].findAll('td'))\n for i in range (1, len (tab.findAll ('tr'))):\n for td in cont[i].find_all ('td'):\n if i == 1:\n list1.append (td.text)\n if i == 2:\n list2.append (td.text)\n if i == 3:\n list3.append (td.text)\n if i == 4:\n list4.append (td.text)\n if i == 5:\n list5.append (td.text)\n textx = td.getText('\\n')\n listx = textx.split('\\n')\n #print(listx)\n dic_lesson = {}\n if len(listx) == 1:\n pass\n else:\n dic_lesson['name'] = listx[0]\n dic_lesson['tec'] = listx[1]\n dic_lesson['loc'] = listx[2]\n dic_lesson['time'] = listx[3]\n dic_lesson['class'] = listx[5]\n if i == 1:\n list1.append (dic_lesson)\n if i == 2:\n list2.append (dic_lesson)\n if i == 3:\n list3.append (dic_lesson)\n if i == 4:\n list4.append (dic_lesson)\n if i == 5:\n list5.append (dic_lesson)\n del list1[0]\n del list2[0]\n del list3[0]\n del list4[0]\n del list5[0]\n lists.append (list1)\n lists.append (list2)\n lists.append (list3)\n lists.append (list4)\n lists.append (list5)\n # print (lists)\n return jsonify (lists)\n\n\n@app.route('/books' , methods=['GET','POST'])\ndef get_book():\n if request.method == 'POST':\n book_name = request.form.get('book_name')\n from app import book_main\n book = book_main.main ( )\n content = book.get_content (book_name)\n list1 = book.get_booklist (content)\n list2 = book.get_booklistdetail (content)\n #list3 = book.get_index (list1)\n list4 = book.get_json (list1, list2)\n #print (list4)\n #from spider_book import global_ls\n #global_ls.global_list = list3\n return jsonify (list4)\n\n@app.route('/pagebooks' , methods=['GET','POST'])\ndef get_pagebook():\n if request.method == 'POST':\n book_name = request.form.get('book_name')\n page_num = request.form.get('page_num')\n from app import book_main\n book = book_main.main ( )\n content = book.get_numpage (book_name,page_num)\n list1 = book.get_booklist (content)\n list2 = book.get_booklistdetail (content)\n #list3 = book.get_index (list1)\n list4 = book.get_json (list1, list2)\n #print (list4)\n #from spider_book import global_ls\n #global_ls.global_list = list3\n return jsonify (list4)\n\n@app.route('/book_content',methods=['GET','POST'])\ndef get_book_content():\n if request.method == 'POST':\n book_index = request.form.get('book_index')\n from app import book_main\n book = book_main.main ()\n #print (book_index)\n content = book.get_detail (book_index)\n return jsonify (content)\n\n@app.route('/book_login',methods=['GET','POST'])\ndef get_booklogin():\n if request.method == 'POST':\n stnumber = request.form.get('stnumber')\n passwd = request.form.get('password')\n from app import clear_system\n book = clear_system.main ()\n #print (book_index)\n content = book.cookie_login(stnumber,passwd)\n return jsonify (content)\n\n@app.route('/new_book',methods=['GET','POST'])\ndef get_newbook():\n if request.method == 'POST':\n page = request.form.get('page')\n from app import new_book\n newbook = new_book.Main()\n content = newbook.get_newbook(page)\n return jsonify(content)\n\n@app.route('/hot_book',methods=['GET','POST'])\ndef get_hot_book():\n if request.method == 'POST':\n from app import hot_book\n book = hot_book.Main()\n content = book.get_hotbook()\n return jsonify(content)\n\n@app.route('/notice_list',methods=['GET','POST'])\ndef get_notice_list():\n if request.method == 'POST':\n from app import notice_list\n page = request.form.get('page')\n book = notice_list.Main()\n content = book.get_notice_list(page)\n return jsonify(content)\n\t\t\n@app.route('/notice_content',methods=['GET','POST'])\ndef get_notice_content():\n if request.method == 'POST':\n from app import notice_content\n href = request.form.get('href')\n book = notice_content.Main()\n content = book.get_notice_content(href)\n return jsonify(content)\n\t\t\n@app.route('/get_data',methods=['GET','POST'])\ndef get_data():\n if request.method == 'POST':\n from app import data_sourse\n book = data_sourse.Main()\n content = book.get_data()\n return jsonify(content)\n\n\n","sub_path":"app/jwc_webservice.py","file_name":"jwc_webservice.py","file_ext":"py","file_size_in_byte":7550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"120114890","text":"# Analysis of transcriptomic response similarities between combos and single agent\nimport os\nimport pandas\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nimport pylab\nimport matplotlib.colors as col\n\nfrom Functions_misc import list_search, angle\nroot_dir = \"/home/marie/Documents/\"\n\n################################################################################\nstep_2_files = os.listdir(\"%sPROCESSED/Step_2_mRNA\"%root_dir)\nstep_3_files = os.listdir(\"%sPROCESSED/Step_3_CellCount\"%root_dir)\nch_dir_files = list_search(\"M(5|6|12)_(umi|total)_.*_Ch_Dir.tsv\",step_2_files)\n\nfor f in ch_dir_files:\n CL = f.split(\"_\")[-3]\n print(CL)\n os.chdir(\"%sPROCESSED/Step_2_mRNA\"%root_dir)\n chdir_table = pandas.read_table(f,index_col=0)\n # print(chdir_table.columns.values)\n bliss_files = list_search(\"%s_Bliss_table.tsv\"%CL,step_3_files)\n os.chdir(\"%sPROCESSED/Step_3_CellCount\"%root_dir)\n bliss_table = pandas.read_table(bliss_files[0],index_col=0)\n tested_combination = bliss_table.loc[bliss_table.loc[:, \"DrugName2\"] != \"-\",\n [\"DrugName\", \"DrugName2\"]].drop_duplicates(\n [\"DrugName\", \"DrugName2\"])\n for i in range(0,tested_combination.shape[0]):\n # for i in range(0,1):\n drugA = tested_combination.iloc[i, 0]; drugB = tested_combination.iloc[i, 1];\n print(drugA, drugB)\n combination_bool = [(bliss_table.loc[treatment, \"DrugName\"] == drugA) and\n (bliss_table.loc[treatment, \"DrugName2\"] == drugB) for\n treatment in bliss_table.index.tolist()]\n combination_concentration = bliss_table.loc[combination_bool, :]\n similarity_table = pandas.DataFrame(np.nan,\n index=combination_concentration.index,\n columns=[\"Angle_a\",\"Angle_b\",\"Blissvalue\"])\n for combination in combination_concentration.index.tolist():\n drugA_name = list_search(\"^%s_%s\"%(\"_\".join(combination.split(\"_\")[:2]), CL[0]),\n chdir_table.columns.values)\n drugB_name = list_search(\"^%s_%s\"%(\"_\".join(combination.split(\"_\")[2:-1]), CL[0]),\n chdir_table.columns.values)\n drugAB_name = list_search(\"^%s_%s\"%(\"_\".join(combination.split(\"_\")[:-1]), CL[0]),\n chdir_table.columns.values)\n if ((len(drugA_name) != 0) and (len(drugB_name) != 0) and (len(drugAB_name) != 0)):\n drugA_ch = chdir_table.loc[:,drugA_name[0]].tolist()\n drugB_ch = chdir_table.loc[:,drugB_name[0]].tolist()\n drugAB_ch = chdir_table.loc[:,drugAB_name[0]].tolist()\n similarity_table.loc[combination, \"Angle_a\"] = (angle(drugAB_ch, drugA_ch))\n similarity_table.loc[combination, \"Angle_b\"] = (angle(drugAB_ch, drugB_ch))\n similarity_table.loc[combination, \"Blissvalue\"] = combination_concentration.loc[\n combination, \"Blissvalue\"]\n else:\n similarity_table = similarity_table.drop(combination)\n\n print(similarity_table)\n\n ########################################################################\n # PLot\n\n fig = plt.figure()\n plt.xlabel(\"%s\"%drugA)\n plt.ylabel(\"%s\"%drugB)\n plt.suptitle(\"%s\"%CL)\n sc = plt.scatter(similarity_table.loc[:,\"Angle_a\"], similarity_table.loc[:,\"Angle_b\"],\n c=similarity_table.loc[:,\"Blissvalue\"], cmap=pylab.cm.bone,\n norm=col.Normalize(0, 1), s=50)\n\n for combination in similarity_table.index.tolist():\n plt.annotate(\"\\n\".join([combination.split(\"_\")[1],combination.split(\"_\")[3]]),\n (similarity_table.loc[combination,\"Angle_a\"] + 0.007,\n similarity_table.loc[combination,\"Angle_b\"] + 0.007),\n size=9)\n\n plt.colorbar(sc,label=\"Bliss\")\n plt.grid(b=True, which='both', color='0.85',linestyle='-')\n plt.plot([0.2,1],[0.2,1],color='0.85')\n plt.ylim(0.2, 1.0)\n plt.xlim(0.2, 1.0)\n # plt.show()\n\n os.chdir(\"%sOUTPUT/GR_Bliss_24h\"%root_dir)\n fig.savefig(\"%s_%s_%s.png\"%(CL,drugA,drugB))\n","sub_path":"SRC/Python/Single_Combo_similarities.py","file_name":"Single_Combo_similarities.py","file_ext":"py","file_size_in_byte":4416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"300473421","text":"name = input(\"What is your name? \")\nage = int(input(\"what is your age? \"))\nage_until = 18 - age\nhealth = 10\n\n\nif age >= 18:\n print(\"Hello!\",name,\"You are old enough to play\")\n\n wants_to_play = input('Do you want to play? ').lower()\n\n if wants_to_play == \"yes\":\n print(\"The objective of this game is to find your way home but be careful hahahah ;) \")\n print(\"Hello\", name, \"! You have a starting health of\",health)\n\n sunny_rainy = input(\"You arrive at a fork in the road, choose a path...sunny or rainy(sunny/rainy)? \").lower()\n if sunny_rainy == \"sunny\":\n ans = input(\"Nice, you followed the Sunny path and reached a Spring full of fresh water and a Apple tree..Do you take a sip of water or eat a apple (water/apple)? \").lower()\n\n if ans == \"water\":\n print(\"You are now hydrated\")\n\n if ans == \"apple\":\n print(\"Oh No!, you are no longer hungry but the apple was rotten which causes you to lose 5 health points\")\n health -= 5\n\n ans = input(\"As you continue to find your way home. You arrive at a big pile of rocks on your left and right side with a path in the middle. Do you walk the path or climb the rocks (walk/climb)? \")\n\n if ans == \"climb\":\n print(\"Ouch!..you fell and lost 5 health points\")\n health -= 5\n if ans == \"walk\":\n print(\"Ouuch a few small rocks fell on you which caused you lost 5 health points\")\n health -=5\n\n if health <= 0:\n print(\"You now have 0 health, Sorry but you did NOT make it home safely!..\")\n else:\n print(\"You didn't make it home without a scratch BUT you did make it home safely!\")\n\n\n\n\n\n if sunny_rainy == \"rainy\":\n ans = input(\"Nice, as you are trying to find your way home. You come to a puddle, do you jump in or walk around (jump/walk)? \").lower()\n\n if ans == \"jump\":\n print(\"Let's be honest, Who can really avoid jumping into a puddle\")\n\n elif ans == \"walk\":\n print(\"Oh No!, You walked around the puddle but fell in, you have lost 5 health points\")\n health -= 5\n\n\n\n ans = input(\"While you were walking you see a bike in perfect condition and a nice pair of running shoes. Do you take the bike or shoes to assit you on your journey home (bike/shoes)? \").lower()\n if ans == \"bike\":\n print(\"The bike is riding great but catches a flat which causes you to crash, you lose 5 health\")\n health -= 5\n\n if health <=0:\n print(\"You now have 0 health and you did not make it home..!\")\n else:\n print(\"You have made it home safely!\")\n\n else:\n print(\"You have made it home Safely\")\n\n else:\n print(\"Sorry to see you go! \")\n\nelse:\n print(\"You are not old enough to play, see you in\", age_until, \"years\")\n","sub_path":"Python_Make_It_Home/Make_It_Home.py","file_name":"Make_It_Home.py","file_ext":"py","file_size_in_byte":3028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"366249111","text":"class Pet:\n\tallowed = ['cat', 'dog', 'fish', 'rat']\n\tdef __init__(self, name, species):\n\t\tif species not in Pet.allowed:\n\t\t\traise ValueError(f\"you can't have a {species} pet\")\n\t\tself.name = name\n\t\tself.species = species\n\n\tdef set_specices(self, species):\n\t\tif species not in Pet.allowed:\n\t\t\traise ValueError(f\"you can't have a {species} pet\")\n\t\tself.species = species\n\ncat = Pet(\"Blue\", \"cat\")\ndog = Pet(\"Futty\", \"dog\")\n# dog = Pet(\"Tony\", \"tiger\")\n","sub_path":"OOP/pet.py","file_name":"pet.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"273918771","text":"# Copyright 2009 10gen, 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 sys\n\nsys.path[0:0] = os.path.join(os.getcwd(), \"..\")\nfrom pymongo.bson import BSON\nfrom pymongo.son import SON\n\ndef main():\n xml_file = sys.argv[1]\n out_file = sys.argv[2]\n\n f = open(xml_file, \"r\")\n xml = f.read()\n f.close()\n\n f = open(out_file, \"w\")\n doc = SON.from_xml(xml)\n bson = BSON.from_dict(doc)\n f.write(bson)\n f.close()\n\n assert doc == bson.to_dict()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"tools/validate.py","file_name":"validate.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"278348439","text":"import torchvision\nfrom torch import nn\nimport torch\nfrom torch.nn.utils.rnn import pack_padded_sequence\nfrom models.basic_encoder_decoder_models.encoder_decoder import BasicEncoderDecoderModel, Encoder\nimport torch.nn.functional as F\nfrom embeddings.embeddings import get_embedding_layer\nfrom models.abtract_model import AbstractEncoderDecoderModel\nimport math\n\nclass ScaleProductAttention(nn.Module):\n \"\"\"\n Attention Network.\n \"\"\"\n\n def __init__(self, encoder_dim, decoder_dim):\n \"\"\"\n :param encoder_dim: feature size of encoded images\n :param decoder_dim: size of decoder's RNN\n :param attention_dim: size of the attention network\n \"\"\"\n super(ScaleProductAttention, self).__init__()\n # linear layer to transform decoder's output\n self.decoder_att = nn.Linear(decoder_dim, encoder_dim)\n self.dk = encoder_dim\n # linear layer to calculate values to be softmax-ed\n self.softmax = nn.Softmax(dim=1) # softmax layer to calculate weights\n\n def forward(self, encoder_out, decoder_hidden):\n \"\"\"\n Forward propagation.\n :param encoder_out: encoded images, a tensor of dimension (batch_size, num_pixels, encoder_dim)\n :param decoder_hidden: previous decoder output, a tensor of dimension (batch_size, decoder_dim)\n :return: attention weighted encoding, weights\n \"\"\"\n query = self.decoder_att(decoder_hidden).unsqueeze(1) # (batch_size, 1, encoder_dim)\n\n #scores = (batch_size,1,l_regions)\n scores = torch.matmul(query, encoder_out.transpose(-2, -1)) \\\n / math.sqrt(self.dk)\n\n #scores = (batch_size,l_regions)\n scores = scores.squeeze(1)\n alpha = self.softmax(scores) # (batch_size, l_regions)\n attention_weighted_encoding = (\n encoder_out * alpha.unsqueeze(2)).sum(dim=1) # (batch_size, encoder_dim)\n\n return attention_weighted_encoding, alpha\n\n\nclass DecoderWithAttention(nn.Module):\n \"\"\"\n Decoder.\n \"\"\"\n\n def __init__(\n self, attention_dim, embedding_type, embed_dim, decoder_dim, vocab_size, token_to_id, post_processing,\n encoder_dim=2048, dropout=0.5):\n \"\"\"\n :param attention_dim: size of attention network\n :param embed_dim: embedding size\n :param decoder_dim: size of decoder's RNN\n :param vocab_size: size of vocabulary\n :param encoder_dim: feature size of encoded images\n :param dropout: dropout\n \"\"\"\n super(DecoderWithAttention, self).__init__()\n\n self.encoder_dim = encoder_dim\n self.attention_dim = attention_dim\n self.embed_dim = embed_dim\n self.decoder_dim = decoder_dim\n self.vocab_size = vocab_size\n self.dropout = dropout\n\n self.attention = ScaleProductAttention(\n encoder_dim, decoder_dim) # attention network\n\n # self.embedding = nn.Embedding(vocab_size, embed_dim) # embedding layer\n self.embedding = get_embedding_layer(\n embedding_type, embed_dim, vocab_size, token_to_id, post_processing)\n\n self.dropout = nn.Dropout(p=self.dropout)\n self.decode_step = nn.LSTMCell(\n embed_dim + encoder_dim, decoder_dim, bias=True) # decoding LSTMCell\n # linear layer to find initial hidden state of LSTMCell\n self.init_h = nn.Linear(encoder_dim, decoder_dim)\n # linear layer to find initial cell state of LSTMCell\n self.init_c = nn.Linear(encoder_dim, decoder_dim)\n\n self.fc = nn.Linear(decoder_dim, vocab_size)\n self.init_weights() # initialize some layers with the uniform distribution\n\n def init_weights(self):\n \"\"\"\n Initializes some parameters with values from the uniform distribution, for easier convergence.\n \"\"\"\n #self.embedding.weight.data.uniform_(-0.1, 0.1)\n #print(\"e agora\", self.embedding.weight.data)\n\n self.fc.bias.data.fill_(0)\n self.fc.weight.data.uniform_(-0.1, 0.1)\n\n def fine_tune_embeddings(self, fine_tune=True):\n \"\"\"\n Allow fine-tuning of embedding layer? (Only makes sense to not-allow if using pre-trained embeddings).\n :param fine_tune: Allow?\n \"\"\"\n for p in self.embedding.parameters():\n p.requires_grad = fine_tune\n\n def normalize_embeddings(self, no_normalization=False):\n \"\"\"\n Normalize values of embbedings (ex: makes sense for pretrained embeddings)\n \"\"\"\n if no_normalization:\n print(\"embeddings without normalization\")\n else:\n print(\"embeddings start normalized\")\n embeddings_values = self.embedding.weight.data\n norm = embeddings_values.norm(\n p=2, dim=1, keepdim=True).clamp(min=1e-12)\n self.embedding.weight.data.copy_(embeddings_values.div(norm))\n\n def init_hidden_state(self, encoder_out):\n \"\"\"\n Creates the initial hidden and cell states for the decoder's LSTM based on the encoded images.\n :param encoder_out: encoded images, a tensor of dimension (batch_size, num_pixels, encoder_dim)\n :return: hidden state, cell state\n \"\"\"\n mean_encoder_out = encoder_out.mean(dim=1)\n h = self.init_h(mean_encoder_out) # (batch_size, decoder_dim)\n #c = self.init_c(mean_encoder_out)\n c = h\n return h, c\n\n def forward(self, word, encoder_out, decoder_hidden_state, decoder_cell_state):\n attention_weighted_encoding, alpha = self.attention(encoder_out, decoder_hidden_state)\n embeddings = self.embedding(word)\n decoder_input = torch.cat((embeddings, attention_weighted_encoding), dim=1)\n\n decoder_hidden_state, decoder_cell_state = self.decode_step(\n decoder_input, (decoder_hidden_state, decoder_cell_state)\n )\n\n scores = self.fc(self.dropout(decoder_hidden_state))\n\n return scores, decoder_hidden_state, decoder_cell_state, alpha\n\n\nclass BasicScaleProductAttentionModel(BasicEncoderDecoderModel):\n\n def __init__(self,\n args,\n vocab_size,\n token_to_id,\n id_to_token,\n max_len,\n device\n ):\n super().__init__(args, vocab_size, token_to_id, id_to_token, max_len, device)\n\n def _initialize_encoder_and_decoder(self):\n\n self.encoder = Encoder(self.args.image_model_type,\n enable_fine_tuning=self.args.fine_tune_encoder)\n\n self.decoder = DecoderWithAttention(\n encoder_dim=self.encoder.encoder_dim,\n attention_dim=self.args.attention_dim,\n decoder_dim=self.args.decoder_dim,\n embedding_type=self.args.embedding_type,\n embed_dim=self.args.embed_dim,\n vocab_size=self.vocab_size,\n token_to_id=self.token_to_id,\n post_processing=self.args.post_processing,\n dropout=self.args.dropout\n )\n\n self.encoder = self.encoder.to(self.device)\n self.decoder = self.decoder.to(self.device)\n\n def _predict(self, encoder_out, caps, caption_lengths):\n batch_size = encoder_out.size(0)\n num_pixels = encoder_out.size(1)\n\n # Create tensors to hold word predicion scores and alphas\n all_predictions = torch.zeros(batch_size, max(\n caption_lengths), self.vocab_size).to(self.device)\n all_alphas = torch.zeros(batch_size, max(\n caption_lengths), num_pixels).to(self.device)\n\n h, c = self.decoder.init_hidden_state(encoder_out)\n\n for t in range(max(\n caption_lengths)):\n # batchsizes of current time_step are the ones with lenght bigger than time-step (i.e have not fineshed yet)\n batch_size_t = sum([l > t for l in caption_lengths])\n\n predictions, h, c, alpha = self.decoder(\n caps[:batch_size_t, t], encoder_out[:batch_size_t], h[:batch_size_t], c[:batch_size_t])\n\n all_predictions[:batch_size_t, t, :] = predictions\n all_alphas[:batch_size_t, t, :] = alpha\n\n return {\"predictions\": all_predictions, \"alphas\": all_alphas}\n\n def generate_output_index(self, input_word, encoder_out, h, c):\n predictions, h, c, _ = self.decoder(\n input_word, encoder_out, h, c)\n\n current_output_index = self._convert_prediction_to_output(predictions)\n\n return current_output_index, h, c\n","sub_path":"src/models/basic_encoder_decoder_models/encoder_decoder_variants/attention_scale_product.py","file_name":"attention_scale_product.py","file_ext":"py","file_size_in_byte":8469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"525601803","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nimport time\nimport socket\nfrom multiprocessing import Process\n\n# 75Kb\nMESSAGE_SIZE_KB = 75 * 1000\n\nTHROUGHPUT_DEBUG_INTERVAL_S = 5\n\nKBS_IN_MB = 1000\n\nsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\naddress = os.environ[\"IP_ADDRESS\"]\nport = 9000\nprint(f\"Binding to address {address}, port {port}\")\nsocket.bind((address, port))\nsocket.listen(3)\n\n\ndef deliver_bytes(connection, process_id):\n print(f\"Process-{process_id}]- spawned for connection {connection}\")\n\n last_subscribe_time = int(time.time())\n\n nomsg_count = 0\n\n kbs_so_far = 0\n\n window_start_time = int(time.time())\n\n while True:\n current_time = int(time.time())\n # print(\"time elapsed: {}\".format(current_time - last_subscribe_time))\n\n data = connection.recv(MESSAGE_SIZE_KB)\n msg = bytearray(data)\n # print(f\"Received len(msg) {sys.getsizeof(msg)} bytes.\")\n\n if len(msg) is 0:\n # print(\"No message\")\n nomsg_count = nomsg_count + 1\n if 10 < current_time - last_subscribe_time:\n print(\"number of nomsgs: {}\".format(nomsg_count))\n last_subscribe_time = current_time\n continue\n\n if 10 < current_time - last_subscribe_time:\n print(f\"[Process-{process_id}] number of nomsgs: {nomsg_count}\")\n nomsg_count = 0\n last_subscribe_time = current_time\n\n # Maintain figures for throughput reporting\n kbs_so_far += sys.getsizeof(msg) / 1000\n\n # Determine if we should output a throughput figure\n window_length_sec = current_time - window_start_time\n\n if window_length_sec >= THROUGHPUT_DEBUG_INTERVAL_S:\n throughput_mb_per_s = float(kbs_so_far / (THROUGHPUT_DEBUG_INTERVAL_S * KBS_IN_MB))\n print(f\"Process-{process_id}] - Throughput in window: {throughput_mb_per_s} MB/s\")\n # Reset ready for the next throughput indication\n window_start_time = int(time.time())\n kbs_so_far = 0\n\n\ni = 0\nwhile True:\n connection, address = socket.accept()\n print(f\"Connection established with {address}\")\n p = Process(target=deliver_bytes, args=(connection, i))\n p.start()\n i += 1\n\nconnection.close()\n","sub_path":"server_socket.py","file_name":"server_socket.py","file_ext":"py","file_size_in_byte":2283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"143613882","text":"import asyncio\nimport requests\n\nurls = ['http://www.google.com', 'http://www.yandex.ru', 'http://www.python.org']\n\nasync def call_url(url):\n print(\"Starting {}\".format(url))\n response = await requests.get(url)\n data = await response.text\n print(\"{}: {}: bytes: {}\".format(url, len(data), data))\n return data\n\nfutures = [call_url(url) for url in urls]\nloop = asyncio.get_event_loop()\nloop.run_until_complete(asyncio.wait(futures))","sub_path":"important/useful_modules/asyncion_module/async_start.py","file_name":"async_start.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"325985597","text":"#!/usr/bin/python\nimport cgi, os\nimport cgitb; cgitb.enable()\nform = cgi.FieldStorage()\n\n# Get FTP username from /ftp dir\ndef get_username():\n basepath = '/ftp'\n for f in os.listdir(basepath):\n if os.path.isdir(os.path.join(basepath, f)):\n # User directory identified\n return f\n return None\n\ndef upload_file():\n fn = ''\n message = ''\n\n username = get_username()\n\n if username is None:\n return '
  • Sorry, unable to identify FTP server username
  • '\n\n if not 'filenames' in form:\n return '
  • Sorry, no files to upload provided
  • '\n\n fileitems = form['filenames']\n\n if not isinstance(fileitems, list):\n fileitems = [ fileitems ]\n\n for fileitem in fileitems:\n # Test if the file was uploaded\n if len(fileitem.filename) > 0:\n try:\n fn = os.path.basename(fileitem.filename)\n open('/ftp/' + username + '/' + fn, 'wb').write(fileitem.file.read())\n message += '
  • File \"' + fn + ' was uploaded successfully
  • '\n except Exception as e:\n message = '
  • File ' + fn + ' was not uploaded (%s)
  • ' % e\n else:\n message = '
  • Sorry, no file(s) provided
  • '\n return message, username\n\n#\n# Main code\n#\nmessage, username = upload_file()\n\nprint(\"\"\"\\\nContent-Type: text/html\\n\n\n\n PALMS file(s) upload results\n\n\n \n

    PALSM file(s) upload results

    \n

      %s

    \n

    \n Please press here to send other file(s)
    \n To access the user files, please click here\n

    \n\n\n\"\"\" % (message, username))\n\n","sub_path":"ftpd/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"561360350","text":"import unittest\nfrom game.players import Player\n\nclass TestPlayerProperties(unittest.TestCase):\n def test_immutable(self):\n dealer = Player(\"Dealer\", 100000)\n player = Player(\"Alice\", 1000)\n\n d_name = dealer.get_name()\n d_name = \"testtest\"\n d_bal = dealer.get_balance()\n d_bal = 100500800\n\n self.assertEqual(dealer.get_name(), \"Dealer\")\n self.assertEqual(dealer.get_balance(), 100000)\n self.assertEqual(player.get_name(), \"Alice\")\n self.assertEqual(player.get_balance(), 1000)\n\nclass TestPlayerTakingCards(unittest.TestCase):\n def setUp(self):\n self.player = Player(name=\"Alice\", balance=1000)\n\n def test_take_none(self):\n with self.assertRaises(ValueError):\n self.player.take_card(None)\n \n def test_take_obj(self):\n with self.assertRaises(ValueError):\n self.player.take_card(\"TEST\")\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"08-Milestone Project - 2/blackjack/tests/players.py","file_name":"players.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"574326453","text":"import os\nimport pickle\nimport random\nimport jieba\nimport numpy\nfrom .config import *\n\nBASE_DIR = os.path.join(\n os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'filter')\n\nDATA_DIR = os.path.join(BASE_DIR, 'data/large/')\n\nDEFAULT_FILEPATH = [\n os.path.join(DATA_DIR, 'normal.dat'),\n os.path.join(DATA_DIR, 'gamble.dat'),\n os.path.join(DATA_DIR, 'sex.dat'),\n os.path.join(DATA_DIR, 'politics.dat')]\n\nVECTOR_CACHE = os.path.join(BASE_DIR, 'cache/vector.cache')\nVOCAB_CACHE = os.path.join(BASE_DIR, 'cache/vocab.cache')\nTEST_DATA_NUM = 30\nTOPN = 0\n\n\nclass Filter:\n\n def __init__(\n self,\n test_num=TEST_DATA_NUM,\n topN=TOPN,\n cache=True,\n file_path=DEFAULT_FILEPATH,\n ):\n if cache:\n try:\n with open(VECTOR_CACHE, 'rb') as f:\n self.vector = pickle.load(f)\n with open(VOCAB_CACHE, 'rb') as f:\n self.vocab_list = pickle.load(f)\n except IOError:\n pass\n try:\n self.vector and self.vocab_list\n except AttributeError:\n self.file_path = file_path\n self.files_num = len(self.file_path)\n self._split_data(test_num)\n if topN:\n self._vocab_list_remove_topN(topN)\n else:\n self._vocab_list()\n # Write self.vacab_list as cache to file\n with open(VOCAB_CACHE, 'wb') as f:\n pickle.dump(self.vocab_list, f)\n self.matrix_list = self._get_vocab_matrix()\n self.vector = self._get_vector()\n # Write self.vector as cache to file\n with open(VECTOR_CACHE, 'wb') as f:\n pickle.dump(self.vector, f)\n\n def _read_files(self):\n '''\n Read all sentences from file given in file_path\n\n Set up:\n\n self.data_list:\n [\n \"What a lovely day\",\n \"Free porn videos and sex movie\",\n \"I like to gamble\",\n \"I love my dog sunkist\"\n ]\n\n self.classify: [2, 0, 1, 2]\n\n self.data_len: 4\n '''\n self.data_list = []\n self.classify = []\n for i in range(self.files_num):\n with open(self.file_path[i], encoding='utf-8') as f:\n for k in f.readlines():\n # Insert all data from files in to data_list\n self.data_list.append(k)\n # Store this sentence belongs to which category\n self.classify.append(i)\n self.data_len = len(self.classify)\n\n def _split_data(self, test_num):\n '''\n Split data into test data and train data randomly.\n\n type: test_num: int\n Set up:\n\n self.test_data:\n [\n \"What a lovely day\",\n \"Free porn videos and sex movie\",\n ]\n\n self.test_classify: [2, 0]\n\n self.train_data:\n [\n \"I like to gamble\",\n \"I love my dog sunkist\"\n ]\n\n self.test_classify: [2, 0]\n '''\n self._read_files()\n if test_num > self.data_len - 1:\n raise IndexError(\"Test data should small than %s\" % self.data_len)\n random_list = random.sample(range(0, self.data_len), test_num)\n # get test data\n self.test_data = [self.data_list[r] for r in random_list]\n self.test_classify = [self.classify[r] for r in random_list]\n # get train data\n self.train_data = [\n self.data_list[r] for r in\n range(self.data_len) if r not in random_list]\n self.train_classify = [\n self.classify[r] for r in range(self.data_len)\n if r not in random_list]\n\n def _vocab_list_remove_topN(self, n):\n '''\n Remove topN most occur word\n\n Set up:\n\n self.vocab_list:\n [\n 'What', 'lovely', 'day',\n 'Free', 'porn', 'videos',\n 'sex', 'movie', 'like',\n 'gamble', 'love', 'dog', 'sunkist'\n ]\n '''\n import collections\n dic = {}\n for k in self.train_data:\n for i in jieba.cut(k):\n if i in dic:\n dic[i] += 1\n else:\n dic[i] = 1\n d = collections.Counter(dic)\n vocab_lst = [i[0] for i in d.most_common() if len(i[0]) > 1]\n self.vocab_list = vocab_lst[n:]\n\n def _vocab_list(self):\n '''\n Get a list contain all unique non stop words belongs to train_data\n\n Set up:\n\n self._vocab_list:\n [\n 'What', 'lovely', 'day',\n 'Free', 'porn', 'videos',\n 'sex', 'movie', 'like',\n 'gamble', 'love', 'dog', 'sunkist'\n ]\n '''\n vocab_set = set()\n for k in self.train_data:\n vocab_set = vocab_set | set(jieba.cut(k))\n self.vocab_list = [i for i in vocab_set if len(i) > 1]\n\n def sentence_to_vector(self, sentence):\n '''\n Convert strings to vector depends on vocal_list\n type sentence: strings\n '''\n return_vec = [0]*len(self.vocab_list)\n for i in jieba.cut(sentence):\n if i in self.vocab_list:\n return_vec[self.vocab_list.index(i)] += 1\n return return_vec\n\n def _get_vocab_matrix(self):\n '''\n Convert all sentences to vector\n '''\n return [self.sentence_to_vector(i) for i in self.train_data]\n\n def _get_vector(self):\n '''\n Get vector depent on different classify\n '''\n return [self.train_bayes(i) for i in range(self.files_num)]\n\n def train_bayes(self, index):\n '''\n Train native bayes\n type index: number of files\n '''\n num = numpy.ones(len(self.matrix_list[0]))\n cal, sentence = 2.0, 0.0\n # TODO: Just for in one-time in train_classify\n for i in range(len(self.train_classify)):\n if self.train_classify[i] == index:\n sentence += 1\n num += self.matrix_list[i]\n cal += sum(self.matrix_list[i])\n return numpy.log(num/cal), sentence/len(self.train_data)\n\n def bayes_classify(self, sentence_vector):\n '''\n Classify sentence depend on self.vector\n type: sentence_vector: strings\n '''\n word_vector = self.sentence_to_vector(sentence_vector)\n percentage_list = [\n sum(i[0] * word_vector) + numpy.log(i[1])\n for i in self.vector]\n max_val = max(percentage_list)\n for i, j in enumerate(percentage_list):\n if j == max_val:\n return i, percentage_list\n","sub_path":"filter/spam_filter.py","file_name":"spam_filter.py","file_ext":"py","file_size_in_byte":6827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"353628286","text":"#!/usr/bin/python\n# FILE USED TO EXTRACT THE X,Y,Z-BOUNDARIES OF A PVD/VTU FILE IN PARAVIEW\n#Use this file like:\n# pvpython getBoundaries.py homedirectory inputfile.pvd\n\nfrom paraview.simple import *\nfrom numpy import *\nimport sys\n#solutionpvd = PVDReader(FileName='/media/usb/Jeannette/pat03/pat03_us1_clin1_seg1_mv1_av1/vtu/solution.pvd')\n\n# IF USING PVD\nsolutionpvd = PVDReader(FileName=sys.argv[2])\nShow(solutionpvd)\n\n# IF USING FIRST VTU\n#solutionvtu = XMLUnstructuredGridReader(FileName=sys.argv[2])\n#Show(solutionvtu)\n\nname = ('xmin','xmax','ymin','ymax','zmin','zmax')\nboundaries=GetActiveSource().GetDataInformation().GetBounds()\nboundround = around(boundaries, decimals=2)\nboundadd = boundround + boundround*0.05\nf = open(sys.argv[1]+'/boundaries.txt','w')\nf.write('Model boundaries\\n')\nfor i in range(len(boundround)): \n\tf.write(name[i] + ' = ' + str(boundround[i]) + '\\n')\nf.write('Extended lambda2 boundaries\\n')\nfor i in range(len(boundround)): \n\tf.write(name[i] + ' = ' + str(boundadd[i]) + '\\n')\nf.write('Grid size\\n')\nnx = around(200*(boundadd[1]-boundadd[0]),decimals=-0)\nny = around(200*(boundadd[3]-boundadd[2]),decimals=-0)\nnz = around(200*(boundadd[5]-boundadd[4]),decimals=-0)\nf.write('nx = ' + str(nx) + '\\n')\nf.write('ny = ' + str(ny) + '\\n')\nf.write('nz = ' + str(nz) + '\\n')\nf.close()\nexit()\n","sub_path":"scripts/fenics2results/getBoundaries.py","file_name":"getBoundaries.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"38778763","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 15 15:47:39 2017\n\n@author: maxjnorman\n\"\"\"\n\ndef period_transform(period):\n period_dict = {\n 'DAILY': 0,\n 'WEEKLY': 1,\n 'MONTHLY': 2,\n 'YEARLY': 3,\n '0': 'Daily',\n '1': 'Weekly',\n '2': 'Monthly',\n '3': 'Daily',\n }\n if str(period).upper() in period_dict.keys():\n return period_dict[str(period).upper()]\n else:\n return 2\n\nprint(period_transform('f'))","sub_path":"Test Python Scripts/Int Str Dict Test.py","file_name":"Int Str Dict Test.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"115354491","text":"#!/usr/bin/python\n# coding: utf-8\n\n\"\"\"\n利用单元测试的结果 > logs.json作图比较不同排序算法的曲线\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport json\n\nf = open('logs.json')\ndata = json.load(f)\nprint(data)\n\nlens = []\nfuncs = []\nfor key, value in data.items():\n lens.append(int(key))\n for k, v in value.items():\n if k not in funcs:\n funcs.append(k)\n\n# 重新分类数据\ny = {}\nfor key in funcs:\n y[key] = {}\n for i in lens:\n y[key][i] = data[str(i)][key]\nprint(y)\n\nplt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签\nplt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号\nplt.figure(figsize=(8, 4))\nplt.xlabel(\"Data length\")\nplt.ylabel(\"Time(s)\")\nplt.title(\"各个排序算法时间比较\")\nfor k, v in y.items():\n x = lens\n y = [value for key, value in v.items()]\n plt.plot(x, y, label=\"%s\" % k, marker='*')\nplt.legend()\nplt.show()\n","sub_path":"algorithm/sort/plot_data.py","file_name":"plot_data.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"33714153","text":"import time\nfrom account.scanner import account_scanner\nfrom exchangetools.report import report_token\n\ndef main():\n while True:\n new_tokens = account_scanner.scan_all_exchanges()\n for exchange, tokens in new_tokens.items():\n if tokens:\n report_token(exchange, tokens)\n time.sleep(4)\n # for token_pair in token_pairs:\n # balance._balance_between_account(token_pair[\"from\"], token_pair[\"to\"], token_pair[\"amount\"])\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"exchangetools/new_token.py","file_name":"new_token.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"167162639","text":"# -*- coding: utf-8 -*-\n# @Time : 2020/1/22 16:08\n# @Author : ooooo\n\n\"\"\"\n输出2~99之间的素数\n\"\"\"\n\nfrom math import sqrt\n\nfor i in range(2, 100):\n is_prime = True\n for j in range(2, int(sqrt(i)) + 1):\n if i % j == 0:\n is_prime = False\n if is_prime:\n print(i, end=' ')\n","sub_path":"day05/prime.py","file_name":"prime.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"9416690","text":"filename = \"sample.txt\"\n\nlines = 0\nwords = 0\nchars = 0\n\nwith open(filename, 'r') as f:\n for line in f:\n word = line.split()\n\n lines += 1\n words += len(word)\n chars += len(line)\nprint(lines)\nprint(words)\nprint(chars)\n","sub_path":"Day 3/wordcount.py","file_name":"wordcount.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"365440099","text":"#!/bin/python3\n\nimport os\n\n\ndef grading_students(grades):\n \"\"\" Returns rounded grades \"\"\"\n\n rounded_grades = []\n\n for grade in grades:\n if grade > 37 and grade % 5 > 2: # If grade ends with 3, 4, 8 or 9\n rounded_grade = grade + (5 - grade % 5) # Round up to nearest multiple of 5\n else:\n rounded_grade = grade\n\n rounded_grades.append(rounded_grade)\n\n return rounded_grades\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n grades_count = int(input().strip())\n\n student_grades = [] # Grades\n\n for _ in range(grades_count):\n grades_item = int(input().strip())\n student_grades.append(grades_item)\n\n result = grading_students(student_grades)\n\n fptr.write('\\n'.join(map(str, result)))\n fptr.write('\\n')\n\n fptr.close()\n","sub_path":"problem_solving/algorithms/implementation/grading_students.py","file_name":"grading_students.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"583255179","text":"ls = [i for i in range(1,13)]\n\nfor T in range(int(input())):\n n, k = list(map(int, input().split()))\n su_set = []\n rs_set = []\n cnt = 0\n for i in range(1< 10 tokens)\n max_length_generated_text = 3\n total_model_max_length = 10\n\n with patch(\"transformers.AutoTokenizer.from_pretrained\", return_value=mock_tokenizer):\n layer = SageMakerHFTextGenerationInvocationLayer(\n \"some_fake_endpoint\", max_length=max_length_generated_text, model_max_length=total_model_max_length\n )\n prompt_after_resize = layer._ensure_token_limit(long_prompt_text)\n\n # The prompt exceeds the limit, _ensure_token_limit truncates it\n assert prompt_after_resize == truncated_prompt_text\n\n\n@pytest.mark.unit\ndef test_empty_model_name():\n with pytest.raises(ValueError, match=\"cannot be None or empty string\"):\n SageMakerHFTextGenerationInvocationLayer(model_name_or_path=\"\")\n\n\n@pytest.mark.unit\ndef test_streaming_init_kwarg(mock_auto_tokenizer, mock_boto3_session):\n \"\"\"\n Test stream parameter passed as init kwarg is correctly logged as not supported\n \"\"\"\n layer = SageMakerHFTextGenerationInvocationLayer(model_name_or_path=\"irrelevant\", stream=True)\n\n with pytest.raises(SageMakerConfigurationError, match=\"SageMaker model response streaming is not supported yet\"):\n layer.invoke(prompt=\"Tell me hello\")\n\n\n@pytest.mark.unit\ndef test_streaming_invoke_kwarg(mock_auto_tokenizer, mock_boto3_session):\n \"\"\"\n Test stream parameter passed as invoke kwarg is correctly logged as not supported\n \"\"\"\n layer = SageMakerHFTextGenerationInvocationLayer(model_name_or_path=\"irrelevant\")\n\n with pytest.raises(SageMakerConfigurationError, match=\"SageMaker model response streaming is not supported yet\"):\n layer.invoke(prompt=\"Tell me hello\", stream=True)\n\n\n@pytest.mark.unit\ndef test_streaming_handler_init_kwarg(mock_auto_tokenizer, mock_boto3_session):\n \"\"\"\n Test stream_handler parameter passed as init kwarg is correctly logged as not supported\n \"\"\"\n layer = SageMakerHFTextGenerationInvocationLayer(model_name_or_path=\"irrelevant\", stream_handler=Mock())\n\n with pytest.raises(SageMakerConfigurationError, match=\"SageMaker model response streaming is not supported yet\"):\n layer.invoke(prompt=\"Tell me hello\")\n\n\n@pytest.mark.unit\ndef test_streaming_handler_invoke_kwarg(mock_auto_tokenizer, mock_boto3_session):\n \"\"\"\n Test stream_handler parameter passed as invoke kwarg is correctly logged as not supported\n \"\"\"\n layer = SageMakerHFTextGenerationInvocationLayer(model_name_or_path=\"irrelevant\")\n\n with pytest.raises(SageMakerConfigurationError, match=\"SageMaker model response streaming is not supported yet\"):\n layer.invoke(prompt=\"Tell me hello\", stream_handler=Mock())\n\n\n@pytest.mark.unit\ndef test_supports_for_valid_aws_configuration():\n \"\"\"\n Test that the SageMakerHFTextGenerationInvocationLayer identifies a valid SageMaker Inference endpoint via the supports() method\n \"\"\"\n mock_client = MagicMock()\n mock_client.describe_endpoint.return_value = {\"EndpointStatus\": \"InService\"}\n\n mock_session = MagicMock()\n mock_session.client.return_value = mock_client\n\n # Patch the class method to return the mock session\n with patch(\n \"haystack.nodes.prompt.invocation_layer.sagemaker_base.SageMakerBaseInvocationLayer.create_session\",\n return_value=mock_session,\n ):\n supported = SageMakerHFTextGenerationInvocationLayer.supports(\n model_name_or_path=\"some_sagemaker_deployed_model\", aws_profile_name=\"some_real_profile\"\n )\n args, kwargs = mock_client.describe_endpoint.call_args\n assert kwargs[\"EndpointName\"] == \"some_sagemaker_deployed_model\"\n\n args, kwargs = mock_session.client.call_args\n assert args[0] == \"sagemaker-runtime\"\n assert supported\n\n\n@pytest.mark.unit\ndef test_supports_not_on_invalid_aws_profile_name():\n \"\"\"\n Test that the SageMakerHFTextGenerationInvocationLayer raises SageMakerConfigurationError when the profile name is invalid\n \"\"\"\n\n with patch(\"boto3.Session\") as mock_boto3_session:\n mock_boto3_session.side_effect = BotoCoreError()\n with pytest.raises(SageMakerConfigurationError) as exc_info:\n supported = SageMakerHFTextGenerationInvocationLayer.supports(\n model_name_or_path=\"some_fake_model\", aws_profile_name=\"some_fake_profile\"\n )\n assert \"Failed to initialize the session\" in exc_info.value\n assert not supported\n\n\n@pytest.mark.skipif(\n not os.environ.get(\"TEST_SAGEMAKER_MODEL_ENDPOINT\", None), reason=\"Skipping because SageMaker not configured\"\n)\n@pytest.mark.integration\ndef test_supports_triggered_for_valid_sagemaker_endpoint():\n \"\"\"\n Test that the SageMakerHFTextGenerationInvocationLayer identifies a valid SageMaker Inference endpoint via the supports() method\n \"\"\"\n model_name_or_path = os.environ.get(\"TEST_SAGEMAKER_MODEL_ENDPOINT\")\n assert SageMakerHFTextGenerationInvocationLayer.supports(model_name_or_path=model_name_or_path)\n\n\n@pytest.mark.skipif(\n not os.environ.get(\"TEST_SAGEMAKER_MODEL_ENDPOINT\", None), reason=\"Skipping because SageMaker not configured\"\n)\n@pytest.mark.integration\ndef test_supports_not_triggered_for_invalid_iam_profile():\n \"\"\"\n Test that the SageMakerHFTextGenerationInvocationLayer identifies an invalid SageMaker Inference endpoint\n (in this case because of an invalid IAM AWS Profile via the supports() method)\n \"\"\"\n assert not SageMakerHFTextGenerationInvocationLayer.supports(model_name_or_path=\"fake_endpoint\")\n assert not SageMakerHFTextGenerationInvocationLayer.supports(\n model_name_or_path=\"fake_endpoint\", aws_profile_name=\"invalid-profile\"\n )\n","sub_path":"test/prompt/invocation_layer/test_sagemaker_hf_text_gen.py","file_name":"test_sagemaker_hf_text_gen.py","file_ext":"py","file_size_in_byte":11361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"106869873","text":"# -*- coding: utf-8 -*-\n\nimport json\nimport logging\nimport requests\n\n\nclass HTTPHandlerDB(logging.Handler):\n\n def emit(self, record):\n log_entry = self.format(record)\n url = 'https://db-for-logging-vkbot.herokuapp.com/api/events/'\n content_request = requests.post(url=url,\n data=json.dumps({'msg': log_entry}),\n headers={\"Content-type\": \"application/json\"}).content\n return content_request\n\n\nlog_db = logging.getLogger('http_log')\nlog_db.setLevel(logging.INFO)\nlog_db.addHandler(HTTPHandlerDB())\n\n\ndef main():\n log_db.info('Тест на запись лога в заснувшее АПИ')\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"#example_code/image_test.py","file_name":"image_test.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"180145174","text":"import numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport datetime as dt\n\ndef eda(dataframe):\n \"\"\"\n\n :param dataframe: Data to run data analysis on\n :type dataframe: pandas DataFrame\n :return: None\n :rtype: None\n \"\"\"\n assert type(dataframe) in [pd.DataFrame, pd.Series], \"Expected pandas.DataFrame, {} is type {}\".format(dataframe, type(dataframe))\n \n print(\"Dataframe Index:\\n{}\\n\".format(dataframe.index))\n print(\"Dataframe Shape:\\n{}\\n\".format(dataframe.shape)) \n for item in dataframe:\n print(\"---\" * 39)\n print(\"Feature: {}\".format(item))\n print(\"Data Type: {}\\n\".format(dataframe[item].dtypes))\n print(\"Unique Values: {}\\n\".format(dataframe[item].nunique()))\n print(\"Missing Values: {}\".format(dataframe[item].isnull().sum()))\n print(\"\\n{}\".format(dataframe[item].describe(include='all')))\n \n # plotting\n if dataframe[item].nunique() == 1: # skip plotting for columns with only one value\n print(\"\\n{} is homogeneous\".format(item))\n continue\n \n if dataframe[item].nunique() == dataframe[item].count(): # skip plotting when all values are unique\n print(\"\\nIndex eligible - All values of {} are unique\\n\".format(item))\n continue\n \n if dataframe[item].dtype in [np.int64, np.float64]:\n sns.distplot(dataframe[item])\n elif dataframe[item].dtype in [np.object, dt.datetime]:\n sns.countplot(dataframe[item])\n plt.show()\n \n\n","sub_path":"xplor.py","file_name":"xplor.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"605285568","text":"# -*- coding: utf-8 -*-\n# StreamOnDemand Community Edition - Kodi Addon\n# ------------------------------------------------------------\n# streamondemand.- XBMC Plugin\n# Canale cineblog01\n# http://www.mimediacenter.info/foro/viewforum.php?f=36\n# Version: 201706200900\n# ------------------------------------------------------------\nimport re\nimport urlparse\n\nfrom core import config, httptools\nfrom platformcode import logger\nfrom core import scrapertools\nfrom core import servertools\nfrom core.item import Item\nfrom core.tmdb import infoSod\n\n__channel__ = \"cb1\"\n\nhost = \"https://www.cb1.news/\"\n\nheaders = [['Referer', host]]\n\n\ndef mainlist(item):\n logger.info(\"[cineblog01.py] mainlist\")\n\n # Main options\n itemlist = [Item(channel=__channel__,\n action=\"peliculas\",\n title=\"[COLOR azure]Film[COLOR orange] - Novita'[/COLOR]\",\n url=host,\n extra=\"movie\",\n thumbnail=\"http://orig03.deviantart.net/6889/f/2014/079/7/b/movies_and_popcorn_folder_icon_by_matheusgrilo-d7ay4tw.png\"),\n Item(channel=__channel__,\n title=\"[COLOR azure]Film[COLOR orange] - Aggiornamenti[/COLOR]\",\n action=\"peliculas_lastupdate\",\n url=\"%s/lista-film-ultimi-100-film-aggiornati/\" % host,\n extra=\"movie\",\n thumbnail=\"https://raw.githubusercontent.com/orione7/Pelis_images/master/channels_icon_pureita/movie_new_P.png\"),\n\t\t\t\tItem(channel=__channel__,\n action=\"peliculas\",\n title=\"[COLOR azure]Film[COLOR orange] - Alta Definizione [HD][/COLOR]\",\n url=\"%s/tag/film-hd-altadefinizione/\" % host,\n extra=\"movie\",\n thumbnail=\"http://jcrent.com/apple%20tv%20final/HD.png\"),\n Item(channel=__channel__,\n action=\"menuhd\",\n title=\"[COLOR azure]Film[COLOR orange] - Menù HD[/COLOR]\",\n url=host,\n extra=\"movie\",\n thumbnail=\"http://files.softicons.com/download/computer-icons/disks-icons-by-wil-nichols/png/256x256/Blu-Ray.png\"),\n Item(channel=__channel__,\n action=\"menugeneros\",\n title=\"[COLOR azure]Film[COLOR orange] - Per Genere[/COLOR]\",\n url=host,\n extra=\"movie\",\n thumbnail=\"http://orig03.deviantart.net/6889/f/2014/079/7/b/movies_and_popcorn_folder_icon_by_matheusgrilo-d7ay4tw.png\"),\n Item(channel=__channel__,\n action=\"menuanyos\",\n title=\"[COLOR azure]Film[COLOR orange] - Per Anno[/COLOR]\",\n url=host,\n extra=\"movie\",\n thumbnail=\"http://orig03.deviantart.net/6889/f/2014/079/7/b/movies_and_popcorn_folder_icon_by_matheusgrilo-d7ay4tw.png\"),\n Item(channel=__channel__,\n action=\"search\",\n title=\"[COLOR yellow]Cerca Film[/COLOR]\",\n extra=\"movie\",\n thumbnail=\"http://dc467.4shared.com/img/fEbJqOum/s7/13feaf0c8c0/Search\"),\n Item(channel=__channel__,\n action=\"listserie\",\n title=\"[COLOR azure]Serie Tv[COLOR orange] - Novita'[/COLOR]\",\n url=\"%s/serietv/\" % host,\n extra=\"serie\",\n thumbnail=\"http://orig03.deviantart.net/6889/f/2014/079/7/b/movies_and_popcorn_folder_icon_by_matheusgrilo-d7ay4tw.png\"),\n Item(channel=__channel__,\n action=\"search\",\n title=\"[COLOR yellow]Cerca Serie Tv[/COLOR]\",\n extra=\"serie\",\n thumbnail=\"http://dc467.4shared.com/img/fEbJqOum/s7/13feaf0c8c0/Search\")]\n\n return itemlist\n\n\ndef peliculas(item):\n logger.info(\"[cineblog01.py] peliculas\")\n itemlist = []\n\n if item.url == \"\":\n item.url = host\n\n # Carica la pagina\n data = httptools.downloadpage(item.url, headers=headers).data\n\n # Estrae i contenuti\n patronvideos = '
    (.*?)
    \")\n patronvideos = '>'\n matches = re.compile(patronvideos, re.DOTALL).findall(bloque)\n\n if len(matches) > 0:\n next_page(itemlist,matches[0],\"peliculas\",item.extra)\n\n except:\n pass\n\n return itemlist\n\ndef next_page(itemlist,np_url,np_action,np_extra):\n scrapedtitle = \"[COLOR orange]Successivo>>[/COLOR]\"\n itemlist.append(\n Item(channel=__channel__,\n action=np_action,\n title=scrapedtitle,\n url=np_url,\n thumbnail=\"http://2.bp.blogspot.com/-fE9tzwmjaeQ/UcM2apxDtjI/AAAAAAAAeeg/WKSGM2TADLM/s1600/pager+old.png\",\n extra=np_extra,\n plot=\"\"))\n itemlist.append(\n Item(channel=__channel__,\n action=\"HomePage\",\n title=\"[COLOR yellow]Torna Home[/COLOR]\",\n folder=True))\n\n\ndef updates(item):\n logger.info(\"[cineblog01.py] updates\")\n return menulist(item,'')\n\ndef menuhd(item):\n logger.info(\"[cineblog01.py] menuhd\")\n return menulist(item,'')\n\ndef menulist(item,re_txt):\n itemlist = []\n\n data = httptools.downloadpage(item.url, headers=headers).data\n\n # Narrow search by selecting only the combo\n bloque = scrapertools.get_match(data, re_txt)\n\n # The categories are the options for the combo\n patron = ''\n matches = re.compile(patron, re.DOTALL).findall(bloque)\n scrapertools.printMatches(matches)\n\n for url, titulo in matches:\n scrapedtitle = titulo\n scrapedurl = urlparse.urljoin(item.url, url)\n scrapedthumbnail = \"\"\n scrapedplot = \"\"\n itemlist.append(\n Item(channel=__channel__,\n action=\"peliculas\",\n title=\"[COLOR azure]\" + scrapedtitle + \"[/COLOR]\",\n url=scrapedurl,\n thumbnail=scrapedthumbnail,\n extra=item.extra,\n plot=scrapedplot))\n\n return itemlist\n\n# Al llamarse \"search\" la función, el launcher pide un texto a buscar y lo añade como parámetro\ndef search(item, texto):\n logger.info(\"[cineblog01.py] \" + item.url + \" search \" + texto)\n\n try:\n\n if item.extra == \"movie\":\n item.url = host + \"/?s=\" + texto\n return peliculas(item)\n if item.extra == \"serie\":\n item.url = host + \"/serietv/?s=\" + texto\n return listserie(item)\n\n # Continua la ricerca in caso di errore\n except:\n import sys\n for line in sys.exc_info():\n logger.error(\"%s\" % line)\n return []\n\n\ndef listserie(item):\n logger.info(\"[cineblog01.py] listaserie\")\n itemlist = []\n\n # Carica la pagina\n data = httptools.downloadpage(item.url, headers=headers).data\n\n # Estrae i contenuti\n patronvideos = '
    \\s*.*?

    ([^<]+)

    (.*?)
    '\n matches = re.compile(patronvideos, re.DOTALL).finditer(data)\n QualityStr = \"\"\n for match in matches:\n QualityStr = scrapertools.unescape(match.group(1))[6:]\n\n # STREAMANGO\n # matches = []\n # u = scrapertools.find_single_match(data, '(?://|\\.)streamango\\.com/(?:f/|embed/)?[0-9a-zA-Z]+')\n # if u: matches.append((u, 'Streamango'))\n\n # Estrae i contenuti - Streaming\n load_links(itemlist,'Streaming:(.*?)',\"orange\",\"Streaming\")\n\n # Estrae i contenuti - Streaming HD\n load_links(itemlist,'Streaming HD[^<]+(.*?)
    ',\"yellow\",\"Streaming HD\")\n\n # Estrae i contenuti - Streaming 3D\n load_links(itemlist,'Streaming 3D[^<]+(.*?)
    ',\"pink\",\"Streaming 3D\")\n\n # Estrae i contenuti - Download\n load_links(itemlist,'Download:(.*?)
    ',\"aqua\",\"Download\")\n\n # Estrae i contenuti - Download HD\n load_links(itemlist,'Download HD[^<]+(.*?)
    ',\"azure\",\"Download HD\")\n\n if len(itemlist) == 0:\n itemlist = servertools.find_video_items(item=item)\n\n return itemlist\n\n\ndef findvid_serie(item):\n def load_vid_series(html, item, itemlist, blktxt):\n if len(blktxt) > 2:\n vtype = blktxt.strip()[:-1] + \" - \"\n else:\n vtype = ''\n patron = ']+>(.*?)'\n # Estrae i contenuti\n matches = re.compile(patron, re.DOTALL).finditer(html)\n for match in matches:\n scrapedurl = match.group(1)\n scrapedtitle = match.group(2)\n title = item.title + \" [COLOR blue][\" + vtype + scrapedtitle + \"][/COLOR]\"\n itemlist.append(\n Item(channel=__channel__,\n action=\"play\",\n title=title,\n url=scrapedurl,\n fulltitle=item.fulltitle,\n show=item.show,\n folder=False))\n\n logger.info(\"[cineblog01.py] findvid_serie\")\n\n itemlist = []\n lnkblk = []\n lnkblkp = []\n\n data = item.url\n\n # First blocks of links\n if data[0:data.find(' 0:\n lnkblk.append(data[data.find(' - ') + 3:data[0:data.find(' 1:\n for lb in lnkblk[1:]:\n lnkblkp.append(data.find(lb, lnkblkp[i] + len(lnkblk[i])))\n i = i + 1\n\n for i in range(0, len(lnkblk)):\n if i == len(lnkblk) - 1:\n load_vid_series(data[lnkblkp[i]:], item, itemlist, lnkblk[i])\n else:\n load_vid_series(data[lnkblkp[i]:lnkblkp[i + 1]], item, itemlist, lnkblk[i])\n\n return itemlist\n\n\ndef play(item):\n logger.info(\"[cineblog01.py] play\")\n itemlist = []\n\n ### Handling new cb01 wrapper\n if host[9:]+\"/film/\" in item.url:\n iurl=httptools.downloadpage(item.url, only_headers=True, follow_redirects=False).headers.get(\"location\", \"\")\n logger.info(\"/film/ wrapper: %s\"%iurl)\n if iurl:\n item.url=iurl\n\n if '/goto/' in item.url:\n item.url = item.url.split('/goto/')[-1].decode('base64')\n\n item.url = item.url.replace('http://cineblog01.uno', 'http://k4pp4.pw')\n\n logger.debug(\"##############################################################\")\n if \"go.php\" in item.url:\n data = httptools.downloadpage(item.url, headers=headers).data\n try:\n data = scrapertools.get_match(data, 'window.location.href = \"([^\"]+)\";')\n except IndexError:\n try:\n # data = scrapertools.get_match(data, r'clicca qui')\n # In alternativa, dato che a volte compare \"Clicca qui per proseguire\":\n data = scrapertools.get_match(data, r'.*?licca.*?')\n except IndexError:\n data = httptools.downloadpage(item.url, only_headers=True, follow_redirects=False).headers.get(\"location\", \"\")\n while 'vcrypt' in data:\n data = httptools.downloadpage(data, only_headers=True, follow_redirects=False).headers.get(\"location\", \"\")\n logger.debug(\"##### play go.php data ##\\n%s\\n##\" % data)\n elif \"/link/\" in item.url:\n data = httptools.downloadpage(item.url, headers=headers).data\n from lib import jsunpack\n\n try:\n data = scrapertools.get_match(data, \"(eval\\(function\\(p,a,c,k,e,d.*?)\")\n data = jsunpack.unpack(data)\n logger.debug(\"##### play /link/ unpack ##\\n%s\\n##\" % data)\n except IndexError:\n logger.debug(\"##### The content is yet unpacked ##\\n%s\\n##\" % data)\n\n data = scrapertools.find_single_match(data, 'var link(?:\\s)?=(?:\\s)?\"([^\"]+)\";')\n while 'vcrypt' in data:\n data = httptools.downloadpage(data, only_headers=True, follow_redirects=False).headers.get(\"location\", \"\")\n if data.startswith('/'):\n data = urlparse.urljoin(\"http://swzz.xyz\", data)\n data = httptools.downloadpage(data, headers=headers).data\n logger.debug(\"##### play /link/ data ##\\n%s\\n##\" % data)\n else:\n data = item.url\n logger.debug(\"##### play else data ##\\n%s\\n##\" % data)\n logger.debug(\"##############################################################\")\n\n try:\n itemlist = servertools.find_video_items(data=data)\n\n for videoitem in itemlist:\n videoitem.title = item.show\n videoitem.fulltitle = item.fulltitle\n videoitem.show = item.show\n videoitem.thumbnail = item.thumbnail\n videoitem.channel = __channel__\n except AttributeError:\n logger.error(\"vcrypt data doesn't contain expected URL\")\n\n return itemlist\n\n\ndef HomePage(item):\n import xbmc\n xbmc.executebuiltin(\"ReplaceWindow(10024,plugin://plugin.video.streamondemand)\")\n\n# ==================================================================================================================================================\n\ndef peliculas_lastupdate(item):\n logger.info(\"[streamondemand-pureita cineblog01] peliculas_update\")\n\n itemlist = []\n numpage = 14\n\n p = 1\n if '{}' in item.url:\n item.url, p = item.url.split('{}')\n p = int(p)\n\n # Descarga la pagina\n\n data = httptools.downloadpage(item.url, headers=headers).data\n\n # Estrae i contenuti \n patron = '([^<]+)
    -'\n matches = re.compile(patron, re.DOTALL).findall(data)\n\n\n for i, (scrapedurl, scrapedtitle) in enumerate(matches):\n if (p - 1) * numpage > i: continue\n if i >= p * numpage: break\n scrapedthumbnail = \"\"\n scrapedplot = \"\"\n\n scrapedtitle=scrapedtitle.replace(\"–\", \"-\").replace(\"×\", \"\").replace(\"[Sub-ITA]\", \"(Sub Ita)\")\n scrapedtitle=scrapedtitle.replace(\"/\", \" - \").replace(\"’\", \"'\").replace(\"…\", \"...\").replace(\"#\", \"# \")\n scrapedtitle=scrapedtitle.strip()\n title = scrapertools.decodeHtmlentities(scrapedtitle)\n itemlist.append(infoSod(\n Item(channel=__channel__,\n extra=item.extra,\n action=\"findvideos\",\n contentType=\"movie\",\n title=title,\n url=scrapedurl,\n thumbnail=scrapedthumbnail,\n fulltitle=title,\n show=title,\n plot=scrapedplot,\n folder=True), tipo='movie'))\n\t\t\t\t \n # Extrae el paginador\n if len(matches) >= p * numpage:\n scrapedurl = item.url + '{}' + str(p + 1)\n itemlist.append(\n Item(channel=__channel__,\n extra=item.extra,\n action=\"peliculas_lastupdate\",\n title=\"[COLOR orange]Successivi >>[/COLOR]\",\n url=scrapedurl,\n thumbnail=\"https://raw.githubusercontent.com/orione7/Pelis_images/master/channels_icon_pureita/next_1.png\",\n folder=True))\n\n return itemlist\n\n# ==================================================================================================================================================\t\n","sub_path":"channels/cb1.py","file_name":"cb1.py","file_ext":"py","file_size_in_byte":23495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"301215594","text":"import matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom classy import Class\nfrom scipy.optimize import fsolve\nfrom scipy.interpolate import interp1d\nimport math\n\n# esthetic definitions for the plots\nfont = {'size' : 16, 'family':'STIXGeneral'}\naxislabelfontsize='large'\nmatplotlib.rc('font', **font)\nmatplotlib.mathtext.rcParams['legend.fontsize']='medium'\nplt.rcParams[\"figure.figsize\"] = [8.0,6.0]\n\n# Cosmological parameters and other CLASS parameters\ncommon_settings = {# wich output? ClTT, transfer functions delta_i and theta_i\n 'output':'tCl,pCl,lCl',\n # LambdaCDM parameters\n 'h':0.67556,\n 'omega_b':0.022032,\n 'omega_cdm':0.12038,\n 'A_s':2.215e-9,\n 'tau_reio':0.0925,\n # Take fixed value for primordial Helium (instead of automatic BBN adjustment)\n 'YHe':0.246,\n}\n###############\n# call CLASS \n###############\n# scalars only\nM = Class()\nM.set(common_settings)\nM.set({'output':'tCl,pCl','modes':'s','lensing':'no','n_s':0.9619,'l_max_scalars':3000})\nM.compute()\ncls = M.raw_cl(3000)\nM.struct_cleanup()\nM.empty()\n# tensors only\nM = Class()\nM.set(common_settings)\nl_max_tensors = 600\nM.set({'output':'tCl,pCl','modes':'t','lensing':'no','r':0.1,'n_t':0,'l_max_tensors':l_max_tensors})\nM.compute()\nclt = M.raw_cl(l_max_tensors)\nM.struct_cleanup()\nM.empty()\n# scalars + tensors (only in this case we can get the correct lensed ClBB)\nM = Class()\nM.set(common_settings)\nM.set({'output':'tCl,pCl,lCl','modes':'s,t','lensing':'yes','r':0.1,'n_s':0.9619,'n_t':0,'l_max_scalars':3000,'l_max_tensors':l_max_tensors})\nM.compute()\ncl_tot = M.raw_cl(3000) # withouth lensing, isw, ... raw\ncl_lensed = M.lensed_cl(3000)\nM.struct_cleanup()\nM.empty()\n#################\n# start plotting\n#################\nell = cl_tot['ell']\nellt = clt['ell']\nfactor = 1.e10*ell*(ell+1.)/2./math.pi\nfactort = 1.e10*ellt*(ellt+1.)/2./math.pi\nnp.save(\"planck2018_tt.npy\", cls['tt'])\n#\nplt.xlim([2,3000])\nplt.ylim(1, np.max(factor*cls['tt'])*1.1)\nplt.xlabel(r\"$\\ell$\")\nplt.ylabel(r\"$\\ell (\\ell+1) C_l^{XY} / 2 \\pi \\,\\,\\, [\\times 10^{10}]$\")\nplt.title(r\"$r=0.1$\")\nplt.grid()\n#\n# Temperature\nplt.loglog(ell,factor*cls['tt'],'r-',label=r'$\\mathrm{TT(s)}$')\nplt.loglog(ellt,factort*clt['tt'],'r:',label=r'$\\mathrm{TT(t)}$')\n# E modes\nplt.loglog(ell,factor*cls['ee'],'b-',label=r'$\\mathrm{EE(s)}$')\nplt.loglog(ellt,factort*clt['ee'],'b:',label=r'$\\mathrm{EE(t)}$')\n# Lensing B modes\nplt.loglog(ellt,factort*clt['bb'],'g:',label=r'$\\mathrm{BB(t)}$')\nplt.loglog(ell,factor*(cl_lensed['bb']-cl_tot['bb']),'g-',label=r'$\\mathrm{BB(lensing)}$')\nplt.legend(loc='right',bbox_to_anchor=(1.4, 0.5))\n\nplt.savefig('cl_ST.pdf',bbox_inches='tight')\n","sub_path":"src/sky_maps/correlations/class/isw_rs.py","file_name":"isw_rs.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"236313714","text":"from numpy import array\nimport pylab\nfrom pymses.analysis.visualization import *\nfrom pymses import RamsesOutput\nfrom pymses.utils import constants as C\n\n# Ramses data\nrun = 24\nioutput = 17\nro = RamsesOutput(\"./disc23\", ioutput)\namr = ro.amr_source([\"rho\"])\n\n# Map operator : mass-weighted density map\nup_func = lambda dset: (dset[\"rho\"]**2 * dset.get_sizes()**3)\ndown_func = lambda dset: (dset[\"rho\"] * dset.get_sizes()**3)\nscal_func = FractionOperator(up_func, down_func)\n\n# Map region\ncenter = [ 0.5, 0.5, 0.5 ]\naxname=\"z\"\n\n# Map processing\nmp = fft_projection.MapFFTProcessor(amr, ro.info)\ncam = Camera(center=center, line_of_sight_axis=axname, up_vector=\"x\", region_size=[2.0E-1, 2.0E-1], map_max_size=512)\nmap = mp.process(scal_func, cam, random_shift=False)\nfactor = ro.info[\"unit_density\"].express(C.H_cc)\nscale = ro.info[\"unit_length\"].express(C.Mpc)\n\n#pylab.imshow(map)\n# Save map into HDF5 file\nmapname = \"gas_disc{0}_{1}s_{2}\".format(run,axname, ioutput)\nh5fname = save_map_HDF5(map, cam, map_name=mapname)\n\n# Plot map into Matplotlib figure/PIL Image\n#fig = save_HDF5_to_plot(h5fname, map_unit=(\"H/cc\",factor), axis_unit=(\"Mpc\", scale), cmap=\"jet\")\n#pil_img = save_HDF5_to_img(h5fname, cmap=\"jet\",ramses_output=ro)\n\t\n# Save into PNG image file\nsave_HDF5_to_plot(h5fname, map_unit=(\"H/cc\",factor), axis_unit=(\"Mpc\", scale), img_path=\"./\", cmap=\"jet\",)\nsave_HDF5_to_img(h5fname, img_path=\"./\", cmap=\"jet\",ramses_output=ro)\n\npylab.show()\n","sub_path":"AMRplot.py","file_name":"AMRplot.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"331281038","text":"# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n# Mossbauer Scripting File\r\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n\r\nimport math as m\r\nimport numpy as np\r\nimport FittingData as fd\r\nimport ReadAndPlot as rp\r\nfrom uncertainties import ufloat\r\nfrom uncertainties import unumpy\r\nimport matplotlib.pyplot as plt\r\n\r\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n# Constants\r\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n\r\nh = 6.62607015*10**(-34) #Js\r\ne = 1.602176634*10**(-19) #C\r\n\r\ndataFolder = \"./Data/\"\r\nplotsFolder = \"./Plots/\"\r\n\r\nsave = False\r\n\r\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n# Functions\r\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n\r\ndef rel(listy):\r\n\treturn range(len(listy))\r\n\r\ndef avg(array):\r\n\ttally = 0\r\n\tfor elem in array:\r\n\t\ttally += elem\r\n\treturn tally/len(array)\r\n\r\n# the function that scipy will use to fit to\r\n# x0 is position of minimum, d is depth of minimum, a is vertical offset\r\n# migrated the fitting function to this file to leave 'backend files' unmodifed (and more generic)\r\ndef lorentzian(x,x0,d,a):\r\n\tnumerator = -1/(d*np.pi**2)\r\n\tdenominator = (x-x0)**2 + (np.pi*d)**(-2)\r\n\treturn numerator/denominator + a\r\n\r\n#Takes 3 lists of Lorentzian parameters for each peak, mirrors the peaks\r\n#3 sets of [x0, d, a] where x0 is position of minimum, d is depth of minimum, a is vertical offset\r\n#Vertical offset should be same for each peak (or else it takes the average)\r\n#Error on peaks can be changed manually\r\ndef genPeaks(params1, params2, params3):\r\n\t#x ranges can be changed manually (didn't want to clutter up function arguments)\r\n\tx1 = np.linspace(-10,10,5000)\r\n\t#Sets vertical offset to 0 to add them all up, then later avg. vertical offset is added back\r\n\tnparams1, nparams2, nparams3 = [params1[0], params1[1], 0], [params2[0], params2[1], 0], [params3[0], params3[1], 0]\r\n\ty1 = fd.testData(x1, nparams1, function=lorentzian, errY = 0.05)\r\n\ty2 = fd.testData(x1, nparams2, function=lorentzian, errY = 0.05)\r\n\ty3 = fd.testData(x1, nparams3, function=lorentzian, errY = 0.05)\r\n\tyALL = []\r\n\tfor i in rel(x1):\r\n\t\tyALL.append(y1[i] + y2[i] + y3[i] + y1[::-1][i] + y2[::-1][i] + y3[::-1][i] + (params1[2] + params2[2] + params3[2])/3)\r\n\r\n\treturn x1, yALL\r\n\r\n# reads from the .csv file MossbauerDAQ.vi writes\r\n# the header is the total number of counts\r\n# returns bin number, count number (in that bin), and total counts\r\ndef readCSV(filename):\r\n\trawdata = rp.readColumnFile(filename)\r\n\tdata = rawdata[0]\r\n\ttime = data[0]\r\n\txBins = [i for i in range(len(data)-1)]\r\n\tyCounts = [data[i] for i in range(1,len(data))]\r\n\tyErr = [m.sqrt(i) for i in yCounts]\r\n\treturn [xBins, yCounts, yErr, time]\r\n\r\n# fits a single lorentzian based on the x cut data you provide\r\n# able to auto guess 'ideal' parameters based on the cut data\r\n# can override the auto guess by providing your own eg [1,5,10]\r\ndef fitOneLorentzian(xData, yData, yErr=None, cut=[0,1], guess=None, bounds=(-np.inf,np.inf)):\r\n\tcutX,cutY = fd.cutData(xData,yData,interval=cut)\r\n\tif guess==None:\r\n\t\tpeakPos = cutX[cutY.index(min(cutY))]\r\n\t\tpeakHeight = avg(cutY)\r\n\t\tpeakDepth = peakHeight - min(cutY)\r\n\t\tguess = [peakPos,peakDepth,peakHeight]\r\n\tpopt, pcov = fd.fitting(xData, yData, lorentzian, eYs=yErr, initGuess=guess, bounds=bounds)\r\n\tfitX = np.linspace(cut[0],cut[1],num=2000)\r\n\tfitY = fd.fitYs(fitX, popt, lorentzian)\r\n\treturn [fitX, fitY, popt, pcov]\t\r\n\r\ndef convertToVelocity(xBins, lims=[-11,11]):\r\n\tnewXPoints = np.linspace(lims[0],lims[1],num=len(xBins))\r\n\treturn newXPoints\r\n\r\n\r\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n# Scripting\r\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n\r\n\r\n# ################### This is the code to create the test data files ##########################\r\n# #test data of six (three mirrored) peaks written to file and plotted from file\r\n\r\n# testX, testY = genPeaks([-8,5,100], [-5,3,100], [-1.5,1.7,100])\r\n# f = open(dataFolder+\"testsixpeaks.dat\",\"w+\")\r\n# for i in range(len(testX)):\r\n# \tf.write(str(testX[i])+\"\t\"+str(testY[i])+\"\\n\")\r\n# f.close()\r\n\r\n# sixdat = rp.readColumnFile(dataFolder+\"testsixpeaks.dat\")\r\n# Xs, Ys = sixdat[0], sixdat[1]\r\n# rp.plotInit(xAx=r\"Xs [unitless]\", yAx=r\"Ys [unitless]\",plotTitle=r\"test six lorentzians\")\r\n# rp.plotData(Xs, Ys, 0, 0, dataLabel=r\"default\", colour=\"Blue\")\r\n# rp.plotOutput(plotsFolder+\"testsixpeaks.png\")\r\n\r\n# # quick simple lorentzian line shape test data written to file and plotted from file\r\n# xData = [i*0.1 for i in range(0,100)]\r\n# yData = fd.testData(xData, [5,3,10], function=lorentzian, errY=0.005, seed=30054)\r\n\r\n# f = open(dataFolder+\"testdata.dat\",\"w+\")\r\n# for i in rel(xData):\r\n# \tf.write(str(xData[i])+\"\t\"+str(yData[i])+\"\\n\")\r\n# f.close()\r\n\r\n# dat = rp.readColumnFile(dataFolder+\"testdata.dat\")\r\n# Xs, Ys = dat[0], dat[1]\r\n# rp.plotInit(xAx=r\"Xs [unitless]\", yAx=r\"Ys [unitless]\",plotTitle=r\"plotting test data\")\r\n# rp.plotData(Xs, Ys, 0, 0, dataLabel=r\"default\", colour=\"Blue\")\r\n# rp.plotOutput(plotsFolder+\"testplot.png\")\r\n# ################### End of code to create the test data files ###############################\r\n\r\n\r\n\r\n# #################### Fit six Lorentzians ####################\r\n# # Read and plot the test data with 6 Lorentzians\r\n# sixdat = rp.readColumnFile(dataFolder+\"testsixpeaks.dat\")\r\n# Xs, Ys = sixdat[0], sixdat[1]\r\n# rp.plotInit(xAx=r\"Xs [unitless]\", yAx=r\"Ys [unitless]\",plotTitle=r\"test six Lorentzians\")\r\n# rp.plotData(Xs, Ys, 0, 0, dataLabel=r\"Data\", colour=\"Blue\")\r\n\r\n# # Let's try fitting this data\r\n# # peaks are in [-10,-6.5],[-6.5,-3],[-3,0],[0,3],[3,6.5],[6.5,10]\r\n\r\n# cuts = [[-10,-6.5],[-6.5,-3],[-3,0],[0,3],[3,6.5],[6.5,10]]\r\n# guesses = [[-7.6,5,100],[-5,3,100],[-2,1,100],[2,1,100],[5,3,100],[7.6,5,100]]\r\n# for i in rel(cuts):\r\n# \tx,y = fd.cutData(Xs,Ys,interval = cuts[i])\r\n# \tguess = guesses[i]\r\n# \tfitys = fd.fitYs(x, y, function=lorentzian)\r\n# \trp.plotData(x, fitys, 0, 0, dataLabel=r\"Fits\", colour=\"Orange\",lines = 'True')\r\n# rp.plotOutput()\r\n# ################### End Fit six Lorentzians ####################\r\n\r\n\r\n\r\n# organized the cuts and guesses into order, should be very accurate to true values\r\ncuts = [\r\n\t\t[-7.5, -7.2],\r\n\t\t[-7.0, -6.6],\r\n\t\t[-6.4, -6.0],\r\n\t\t[-5.9, -5.6],\r\n\t\t[-5.3, -4.9],\r\n\t\t[-4.7, -4.3],\r\n\t\t[+3.3, +3.7],\r\n\t\t[+3.9, +4.3],\r\n\t\t[+4.5, +4.9],\r\n\t\t[+5.0, +5.4],\r\n\t\t[+5.6, +6.1],\r\n\t\t[+6.2, +6.8]\r\n\t\t]\r\n\r\n# guesses = [\r\n# \t\t[-7.37, 45, 110],\r\n# \t\t[-6.76, 40, 110],\r\n# \t\t[-6.20, 30, 110],\r\n# \t\t[-5.73, 30, 110],\r\n# \t\t[-5.10, 40, 110],\r\n# \t\t[-4.48, 45, 110],\r\n# \t\t[+3.54, 45, 110],\r\n# \t\t[+4.11, 40, 110],\r\n# \t\t[+4.71, 30, 110],\r\n# \t\t[+5.17, 30, 110],\r\n# \t\t[+5.82, 40, 110],\r\n# \t\t[+6.51, 45, 110]\r\n# \t\t]\r\n\r\n# Read in Data:\r\ndat = readCSV(dataFolder+\"Fe2O3_05-02-2019_new.csv\")\r\nxData, yData, yErr, time = dat[0], dat[1], dat[2], dat[3]\r\nxData = convertToVelocity(xData, [-11,11])\r\n\r\n\r\n# plot raw data with error bars\r\nrp.plotInit(xAx=r\"Velocity? $[\\frac{mm}{s}]$\", yAx=r\"Counts [unitless]\",plotTitle=r\"$Fe_2O_3$ data from previous group\")\r\nrp.plotData(xData, yData, 0, yErr, dataLabel=r\"$Fe_2O_3$\", colour=\"Blue\")\r\nrp.plotOutput(plotsFolder+\"DataErrorBars.png\")\r\n\r\n# fit things\r\nfittingOutput = []\r\nfor i in rel(cuts):\r\n\tfitX, fitY, popt, pcov = fitOneLorentzian(xData, yData, yErr, cut=cuts[i])\r\n\tfittingOutput.append([cuts[i], fitX, fitY, popt, pcov])\r\n\r\n# print results to file\r\nf = open(dataFolder+\"fittingresults.dat\",\"w+\")\r\nheader = \"Lower Cut\\tUpper Cut\\tx0\\td\\ta\\tCovariance Matrix(formatted row1 row2 row3)\\n\"\r\nf.write(header)\r\nfor i in rel(fittingOutput):\r\n\tcut, fitX, fitY, popt, pcov = fittingOutput[i]\r\n\tcov1, cov2, cov3 = pcov[0], pcov[1], pcov[2]\r\n\tlineToWrite = str(cut[0]) + \"\\t\" + str(cut[1]) + \"\\t\" + str(popt[0]) + \"\\t\" + str(popt[1]) + \"\\t\" + str(popt[2]) + \"\\t\" + str(cov1[0]) + \"\\t\" + str(cov1[1]) + \"\\t\" + str(cov1[2]) + \"\\t\" + str(cov2[0]) + \"\\t\" + str(cov2[1]) + \"\\t\" + str(cov2[2]) + \"\\t\" + str(cov3[0]) + \"\\t\" + str(cov3[1]) + \"\\t\" + str(cov3[2]) + \"\\n\"\r\n\tf.write(lineToWrite)\r\nf.close()\r\n\r\n\r\n# plot data and fits\r\nrp.plotInit(xAx=r\"Velocity? $[\\frac{mm}{s}]$\", yAx=r\"Counts [unitless]\",plotTitle=r\"$Fe_2O_3$ data from previous group\")\r\nrp.plotData(xData, yData, 0, 0, dataLabel=r\"$Fe_2O_3$\", colour=\"Blue\")\r\nfor i in rel(fittingOutput):\r\n\tcut, fitX, fitY, popt, pcov = fittingOutput[i]\r\n\tx0 = ufloat(popt[0], m.sqrt(pcov[0][0]))\r\n\td = ufloat(popt[1], m.sqrt(pcov[1][1]))\r\n\ta = ufloat(popt[2], m.sqrt(pcov[2][2]))\r\n\tfitYErrors = []\r\n\tfor x in fitX:\r\n\t\ty = lorentzian(x,x0,d,a)\r\n\t\tfitYErrors.append(y.s)\r\n\tif i == 0:\r\n\t\trp.plotData(fitX, fitY, 0, fitYErrors, dataLabel=r\"Fit Lorentzians\", colour=\"Red\", lines=True)\r\n\telse:\r\n\t\trp.plotData(fitX, fitY, 0, fitYErrors, dataLabel=None, colour=\"Red\", lines=True)\r\n\r\nif save == True:\r\n\trp.plotOutput(plotsFolder+\"FitDataErrors.png\")\r\nelse:\r\n \trp.plotOutput()\r\n\r\n# plot fits and their errors\r\nrp.plotInit(xAx=r\"Velocity? $[\\frac{mm}{s}]$\", yAx=r\"Counts [unitless]\",plotTitle=r\"$Fe_2O_3$ data from previous group\")\r\nrp.plotData(xData, yData, 0, 0, dataLabel=r\"$Fe_2O_3$\", colour=\"Blue\")\r\nfor i in rel(fittingOutput):\r\n\tcut, fitX, fitY, popt, pcov = fittingOutput[i]\r\n\tif i == 0:\r\n\t\trp.plotData(fitX, fitY, 0, 0, dataLabel=r\"Fit Lorentzians\", colour=\"Red\", lines=True)\r\n\telse:\r\n\t\trp.plotData(fitX, fitY, 0, 0, dataLabel=None, colour=\"Red\", lines=True)\r\n\r\nif save == True:\r\n\trp.plotOutput(plotsFolder+\"FitData.png\")\r\nelse:\r\n\trp.plotOutput()\r\n\r\n\r\n# plot the fits together\r\nrp.plotInit(xAx=r\"Velocity? $[\\frac{mm}{s}]$\", yAx=r\"Counts [unitless]\",plotTitle=r\"$Fe_2O_3$ data from previous group\")\r\ntotalY = np.linspace(0, 0, num=22*1000)\r\ntotalX = np.linspace(min(xData), max(xData), num=22*1000)\r\nallHeights = []\r\nfor i in rel(fittingOutput):\r\n\tcut, fitX, fitY, popt, pcov = fittingOutput[i]\r\n\tfitY = fd.fitYs(totalX, popt, lorentzian)\r\n\ttotalY += (np.array(fitY)-popt[2])\r\n\tallHeights.append(popt[2])\r\ntotalY = totalY+avg(allHeights)\r\nrp.plotData(totalX, totalY, 0, 0, dataLabel=r\"Fit Lorentzians\", colour=\"Red\", lines=True)\r\nif save == True:\r\n\trp.plotOutput(plotsFolder+\"allFitsOnlyFits.png\")\r\nelse:\r\n\trp.plotOutput()\r\n\r\n# plot along original data points (get residuals)\r\nrp.plotInit(xAx=r\"Velocity? $[\\frac{mm}{s}]$\", yAx=r\"Counts [unitless]\",plotTitle=r\"$Fe_2O_3$ data from previous group\")\r\ntotalY = np.linspace(0, 0, num=len(xData))\r\nallHeights = []\r\nfor i in rel(fittingOutput):\r\n\tcut, fitX, fitY, popt, pcov = fittingOutput[i]\r\n\tfitY = fd.fitYs(xData, popt, lorentzian)\r\n\ttotalY += (np.array(fitY)-popt[2])\r\n\tallHeights.append(popt[2])\r\ntotalY = totalY+avg(allHeights)\r\nrp.plotData(xData, totalY, 0, 0, dataLabel=r\"Fit Lorentzians\", colour=\"Red\", lines=True)\r\nresid = np.array(yData)-totalY\r\nrp.plotData(xData, resid, 0, 0, dataLabel=r\"Residuals\", colour=\"Green\", lines=True)\r\nif save == True:\r\n\trp.plotOutput(plotsFolder+\"allFitsOAndResiduals.png\")\r\nelse:\r\n\trp.plotOutput()\r\n\r\n# Make a .dat file with a LaTeX table of all the fit parameters \r\nfitParams = open(\"fitParamsTable.dat\",\"w+\")\r\n\r\nfitParams.write(\"\\\\begin{table}[] \\n\")\r\nfitParams.write(\"\\\\centering \\n\")\r\nfitParams.write(\"\\\\begin{tabular}{|c|c|c|c|}\\\\hline \\n\")\r\nfitParams.write(\"Fit Number & $x_0$ [mm/s] & d [counts] & a [counts] \\\\\\\\ \\\\hline \\n\")\r\n\r\nfor i in rel(cuts):\r\n\tfitX, fitY, popt, pcov = fitOneLorentzian(xData, yData, yErr, cut=cuts[i])\r\n\tfitParams.write(str(i)+\" & \"+str('%.2f'%(popt[0]))+\"$\\\\pm$\"+str('%.3f'%(m.sqrt(pcov[0][0])))+\r\n\t\t\t\t\t\t\t\" & \"+str('%.2f'%(popt[1]))+\"$\\\\pm$\"+str('%.2f'%(m.sqrt(pcov[1][1])))+\r\n\t\t\t\t\t\t\t\" & \"+str('%.2f'%(popt[2]))+\"$\\\\pm$\"+str('%.2f'%(m.sqrt(pcov[2][2])))+ \r\n\t\t\t\t\t\t\t\"\\\\\\\\ \\\\hline \\n\")\r\n\r\nfitParams.write(\"\\\\end{tabular} \\n\")\r\nfitParams.write(\"\\\\caption{Fit parameters for all 12 peaks.} \\n\")\r\nfitParams.write(\"\\\\label{table:my_label} \\n\")\r\nfitParams.write(\"\\\\end{table}\")\r\nfitParams.close()","sub_path":"MossbauerScript.py","file_name":"MossbauerScript.py","file_ext":"py","file_size_in_byte":11714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"312369248","text":"# -*- coding: utf-8 -*-\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtCore import *\nimport subprocess\nimport time\n\nimport ClassFormulaire\nimport classFiles\nimport ClassTache1RunDocker\n\nclass Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n\n ######################################################################\n # #\n # Fenetre princiale (menu gauche + scroll bar area vide) #\n # #\n ######################################################################\n\n MainWindow.setObjectName(\"Andalusian Mapping\")\n MainWindow.resize(850, 500)\n MainWindow.setWindowTitle(\"Andalusian Mapping\")\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)\n self.gridLayout.setObjectName(\"gridLayout\")\n self.groupBox_2 = QtWidgets.QGroupBox(self.centralwidget)\n self.groupBox_2.setMinimumSize(QtCore.QSize(0, 344))\n self.groupBox_2.setMaximumSize(QtCore.QSize(500, 400))\n self.groupBox_2.setTitle(\"\")\n self.groupBox_2.setObjectName(\"groupBox_2\")\n self.gridLayout_2 = QtWidgets.QGridLayout(self.groupBox_2)\n self.gridLayout_2.setObjectName(\"gridLayout_2\")\n self.label_titre = QtWidgets.QLabel(self.groupBox_2)\n font = QtGui.QFont()\n font.setFamily(\"Latin Modern Mono\")\n font.setPointSize(18)\n font.setBold(False)\n font.setItalic(True)\n font.setWeight(50)\n self.label_titre.setFont(font)\n self.label_titre.setCursor(QtGui.QCursor(QtCore.Qt.CrossCursor))\n self.label_titre.setAcceptDrops(False)\n self.label_titre.setLayoutDirection(QtCore.Qt.LeftToRight)\n\n self.label_titre.setObjectName(\"label_titre\")\n self.gridLayout_2.addWidget(self.label_titre, 0, 0, 1, 1)\n self.pushButton_acceuil = QtWidgets.QPushButton(self.groupBox_2)\n\n self.pushButton_acceuil.setObjectName(\"pushButton_acceuil\")\n self.gridLayout_2.addWidget(self.pushButton_acceuil, 1, 0, 1, 1)\n self.pushButton_newAnalyse = QtWidgets.QPushButton(self.groupBox_2)\n\n self.pushButton_newAnalyse.setObjectName(\"pushButton_newAnalyse\")\n self.gridLayout_2.addWidget(self.pushButton_newAnalyse, 2, 0, 1, 1)\n self.pushButton_oldAnalise = QtWidgets.QPushButton(self.groupBox_2)\n\n self.pushButton_oldAnalise.setObjectName(\"pushButton_oldAnalise\")\n self.gridLayout_2.addWidget(self.pushButton_oldAnalise, 3, 0, 1, 1)\n self.pushButton_resultat = QtWidgets.QPushButton(self.groupBox_2)\n\n self.pushButton_resultat.setObjectName(\"pushButton_resultat\")\n self.gridLayout_2.addWidget(self.pushButton_resultat, 4, 0, 1, 1)\n self.pushButton_author = QtWidgets.QPushButton(self.groupBox_2)\n\n self.pushButton_author.setObjectName(\"pushButton_author\")\n self.gridLayout_2.addWidget(self.pushButton_author, 5, 0, 1, 1)\n self.gridLayout.addWidget(self.groupBox_2, 0, 0, 1, 1)\n\n self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)\n self.scrollArea.setWidgetResizable(True)\n self.scrollArea.setObjectName(\"scrollArea\")\n self.scrollAreaWidgetContents = QtWidgets.QWidget()\n self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 377, 342))\n self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\")\n self.scrollArea.setWidget(self.scrollAreaWidgetContents)\n self.gridLayout.addWidget(self.scrollArea, 0, 1, 1, 1)\n MainWindow.setCentralWidget(self.centralwidget)\n\n self.menubar = QtWidgets.QMenuBar(MainWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 657, 25))\n self.menubar.setObjectName(\"menubar\")\n MainWindow.setMenuBar(self.menubar)\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\n self.statusbar.setObjectName(\"statusbar\")\n MainWindow.setStatusBar(self.statusbar)\n\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n #Signal et connection des boutons d'acceil\n self.pushButton_acceuil.clicked.connect(self.buttonClicked_acceuil)\n self.pushButton_oldAnalise.clicked.connect(self.buttonClicked_reFormualire)\n self.pushButton_newAnalyse.clicked.connect(lambda: self.buttonClicked_newAnalyse(\"nouvelle analyse\"))\n\n #variable qui gère le nombre de fichier de lecture (read) de l'analyse courante.\n self.nbr=2\n #Dossier ou sont regrouper les fichiers de config\n self.dossierConfig=\"/home/etudiant/Cours/M1S2/Projet/ProjetS2/FichierConfig/\"\n #variable qui gère la provenance lors du lancement de la fonction qui gère la première page du formulaire\n #Permet de gérer le comportement du dictionnaire.\n self.indication=\"Rien\"\n\n def buttonClicked_acceuil(self):\n print(\"acceuil\")\n self.scrollArea.hide()\n self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)\n self.scrollArea.setWidgetResizable(True)\n self.scrollArea.setObjectName(\"scrollArea\")\n self.scrollAreaWidgetContents = QtWidgets.QWidget()\n self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 377, 342))\n self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\")\n self.scrollArea.setWidget(self.scrollAreaWidgetContents)\n self.gridLayout.addWidget(self.scrollArea, 0, 1, 1, 1)\n MainWindow.setCentralWidget(self.centralwidget)\n\n liste=[]\n\n for i in range(10):\n liste.append(i)\n self.updatePageExPipeline(liste)\n\n ######################################################################\n # #\n # RELANCER ANALYSE #\n # #\n ######################################################################\n\n ######################################################################\n # 1er page -> liste des analyse existante #\n ######################################################################\n\n # Liste des analyses existante et selection possible de l'une d'entre elle\n\n def buttonClicked_reFormualire(self):\n print(\"Relancer une analyse\")\n\n self.scrollArea.hide()\n\n self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)\n self.scrollArea.setWidgetResizable(True)\n self.scrollArea.setObjectName(\"scrollArea\")\n self.scrollAreaWidgetContents = QtWidgets.QWidget()\n self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 377, 342))\n self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\")\n self.scrollArea.setWidget(self.scrollAreaWidgetContents)\n self.gridLayout.addWidget(self.scrollArea, 0, 1, 1, 1)\n MainWindow.setCentralWidget(self.centralwidget)\n\n #Liste des fichiers config deja créer :\n commande=\"ls \"\n commande+=self.dossierConfig\n sortie = subprocess.Popen(args=commande, stdout=subprocess.PIPE, shell=True)\n self.listeConfigFiles=[]\n for line in sortie.stdout:\n self.listeConfigFiles.append(str(line.rstrip()).strip(\"b'\").strip(\"'\"))\n\n self.label=[]\n for i in range(len(self.listeConfigFiles)):\n self.label.append(\"label_{0}\".format(i))\n\n self.gridLayout_3 = QtWidgets.QGridLayout(self.scrollAreaWidgetContents)\n self.gridLayout_3.setObjectName(\"gridLayout_3\")\n spacerItem = QtWidgets.QSpacerItem(378, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.gridLayout_3.addItem(spacerItem, 4, 0, 1, 1)\n self.label_NAtitre = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_NAtitre.setMaximumSize(QtCore.QSize(16777215, 20))\n self.label_NAtitre.setObjectName(\"label_NAtitre\")\n self.label_NAtitre.setText(\"

    Rechager une ancienne analyse :

    \")\n self.gridLayout_3.addWidget(self.label_NAtitre, 0, 0, 1, 1)\n spacerItem1 = QtWidgets.QSpacerItem(378, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.gridLayout_3.addItem(spacerItem1, 3, 0, 1, 1)\n self.horizontalLayout_2 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\n spacerItem2 = QtWidgets.QSpacerItem(158, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_2.addItem(spacerItem2)\n\n #affiche une liste de bouton radio en focntion du nombre de fichier de config présent\n #et met en texte du bouton radio le nom de l'analyse.\n for i in range(len(self.listeConfigFiles)):\n self.label[i] = QtWidgets.QRadioButton(self.scrollAreaWidgetContents)\n self.label[i].setObjectName(\"label\")\n self.label[i].setText(self.listeConfigFiles[i].split(\".\")[0])\n self.label[i].setMaximumSize(QtCore.QSize(16777215, 20))\n self.gridLayout_3.addWidget(self.label[i], 1+i, 0, 1, 1)\n\n self.pushButton_NAok = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n self.pushButton_NAok.setMaximumSize(QtCore.QSize(150, 30))\n self.pushButton_NAok.setObjectName(\"pushButton_NAok\")\n self.pushButton_NAok.setText(\"ok\")\n self.horizontalLayout_2.addWidget(self.pushButton_NAok)\n self.gridLayout_3.addLayout(self.horizontalLayout_2, 50, 0, 1, 1)\n spacerItem3 = QtWidgets.QSpacerItem(378, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.gridLayout_3.addItem(spacerItem3, 1, 0, 1, 1)\n\n self.scrollArea.setWidget(self.scrollAreaWidgetContents)\n self.gridLayout.addWidget(self.scrollArea, 0, 1, 1, 1)\n MainWindow.setCentralWidget(self.centralwidget)\n\n self.pushButton_NAok.clicked.connect(self.buttonClicked_okReform)\n\n ######################################################################\n # intermédiaire pour voir quelle bouton est cliquer #\n ######################################################################\n\n def buttonClicked_okReform(self, fichier):\n fic=self.dossierConfig\n for i in range(len(self.label)):\n if self.label[i].isChecked() :\n fic+=self.listeConfigFiles[i]\n #print(fic)\n self.buttonClicked_newAnalyse(\"fichierConfigue\", fichier=fic)\n\n ######################################################################\n # #\n # ANALYSE #\n # #\n ######################################################################\n\n def updatePageExPipeline (self, listeWidget):\n print(\"update de la fenetre\")\n self.labelEx=[]\n place=2\n\n for i in listeWidget :\n self.labelEx.append(\"labelExecution_{0}\".format(i))\n\n self.scrollArea.hide()\n self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)\n self.scrollArea.setWidgetResizable(True)\n self.scrollArea.setObjectName(\"scrollArea\")\n self.scrollAreaWidgetContents = QtWidgets.QWidget()\n self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 377, 342))\n self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\")\n self.scrollArea.setWidget(self.scrollAreaWidgetContents)\n self.gridLayout.addWidget(self.scrollArea, 0, 1, 1, 1)\n MainWindow.setCentralWidget(self.centralwidget)\n\n self.gridLayout_3 = QtWidgets.QGridLayout(self.scrollAreaWidgetContents)\n self.gridLayout_3.setObjectName(\"gridLayout_3\")\n\n self.label = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label.setMaximumSize(QtCore.QSize(16777215, 50))\n self.label.setObjectName(\"label\")\n self.label.setText(\"

    Exécution du pipeline

    \")\n self.gridLayout_3.addWidget(self.label, 0, 0, 1, 1)\n\n debut_fini=\"

    \"\n fin_fini=\"

    \"\n\n label=0\n\n for label in range(len(self.labelEx)-1):\n self.labelEx[label] = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.labelEx[label].setMaximumSize(QtCore.QSize(16777215, 50))\n self.labelEx[label].setObjectName(\"label\")\n text=debut_fini\n text+=str(listeWidget[label])\n text+=fin_fini\n self.labelEx[label].setText(text)\n self.gridLayout_3.addWidget(self.labelEx[label], place, 0, 1, 1)\n self.scrollArea.setWidget(self.scrollAreaWidgetContents)\n place+=1\n\n self.labelEx[label] = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.labelEx[label].setMaximumSize(QtCore.QSize(16777215, 50))\n self.labelEx[label].setObjectName(\"label\")\n text=\"

    \"\n text+=str(listeWidget[len(listeWidget)-1])\n text+=\"

    \"\n self.labelEx[label].setText(text)\n self.gridLayout_3.addWidget(self.labelEx[label], place, 0, 1, 1)\n self.scrollArea.setWidget(self.scrollAreaWidgetContents)\n\n self.gridLayout.addWidget(self.scrollArea, 0, 1, 1, 1)\n MainWindow.setCentralWidget(self.centralwidget)\n\n ######################################################################\n # formualire end -> lance l'analyse #\n ######################################################################\n\n def RunAnalysis(self):\n print(\"Run Analysis\")\n\n # Chope les textes des champs précédant\n listScaff=self.lineEdit_listScaff.text()\n InvarScaf=self.lineEdit_InvarScaf.text()\n warnScaf=self.lineEdit_warnScaf.text()\n # On les sauvegarde dans le dictionnaire qui gènre les champs\n self.new.etape4(listScaff, InvarScaf, warnScaf)\n\n self.new.remplisConfig()\n\n '''self.listeEtape=[\"etape1\",\"etape2\",\"Etape3\",\"Etape4\",\"Etape5\",\"Etape6\",\"Etape7\",\"Etape8\",\"Etape9\",\"Etape10\"]'''\n\n ### Docker test avec un echo toute les 30s ecrit dans un fichier\n docker=ClassTache1RunDocker.RunDocker()\n docker.start()\n\n self.scrollArea.hide()\n self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)\n self.scrollArea.setWidgetResizable(True)\n self.scrollArea.setObjectName(\"scrollArea\")\n self.scrollAreaWidgetContents = QtWidgets.QWidget()\n self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 377, 342))\n self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\")\n self.scrollArea.setWidget(self.scrollAreaWidgetContents)\n self.gridLayout.addWidget(self.scrollArea, 0, 1, 1, 1)\n MainWindow.setCentralWidget(self.centralwidget)\n\n self.gridLayout_3 = QtWidgets.QGridLayout(self.scrollAreaWidgetContents)\n self.gridLayout_3.setObjectName(\"gridLayout_3\")\n\n self.label = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label.setMaximumSize(QtCore.QSize(16777215, 50))\n self.label.setObjectName(\"label\")\n self.label.setText(\"

    Exécution du pipeline

    \")\n self.gridLayout_3.addWidget(self.label, 0, 0, 1, 1)\n\n script = False\n listeEtape=[]\n lecturefic=0\n\n while lecturefic == 0:\n try:\n with open(\"/home/etudiant/Bureau/Projet/ProjetS2/testDocker/files.txt\", \"r\") as fichier:\n ligne=fichier.readline()\n listeEtape=ligne.strip(\"\\n\").split(\"_\")\n print(listeEtape)\n lecturefic = 1\n except:\n pass\n\n listeEnCours=[]\n\n while script == False:\n with open(\"/home/etudiant/Bureau/Projet/ProjetS2/testDocker/files.txt\", \"r\") as fichier:\n ligne=fichier.readline()\n ligne=fichier.readlines()\n for i in range(len(ligne)):\n ligne[i]=ligne[i].strip(\"\\n\")\n if ligne != listeEnCours and len(ligne) != 0:\n listeEnCours=ligne\n self.updatePageExPipeline(ligne)\n if listeEnCours[len(ligne)-1] == listeEtape[len(listeEtape)-2]:\n script=True\n\n\n ######################################################################\n # #\n # FORMULAIRE #\n # 4 étapes + étape de vérification de champs #\n ######################################################################\n\n ######################################################################\n # fenetre info si champs pas valide #\n ######################################################################\n\n def buttonClicked_newAnalyse_probleme(self, chaineCara):\n print(\"Probleme avec certain champs!\")\n # Chope les textes des champs précédant\n listScaff=self.lineEdit_listScaff.text()\n InvarScaf=self.lineEdit_InvarScaf.text()\n warnScaf=self.lineEdit_warnScaf.text()\n # On les sauvegarde dans le dictionnaire qui gènre les champs\n self.new.etape4(listScaff, InvarScaf, warnScaf)\n\n self.scrollArea.hide()\n self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)\n self.scrollArea.setWidgetResizable(True)\n self.scrollArea.setObjectName(\"scrollArea\")\n self.scrollAreaWidgetContents = QtWidgets.QWidget()\n self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 377, 342))\n self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\")\n self.scrollArea.setWidget(self.scrollAreaWidgetContents)\n self.gridLayout.addWidget(self.scrollArea, 0, 1, 1, 1)\n MainWindow.setCentralWidget(self.centralwidget)\n\n self.gridLayout_4 = QtWidgets.QGridLayout(self.scrollAreaWidgetContents)\n self.gridLayout_4.setObjectName(\"gridLayout_4\")\n self.horizontalLayout = QtWidgets.QHBoxLayout()\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.label = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label.setMaximumSize(QtCore.QSize(80, 70))\n self.label.setText(\"\")\n self.label.setPixmap(QtGui.QPixmap(\"../../sign-warning-icon.png\"))\n self.label.setScaledContents(True)\n self.label.setObjectName(\"label\")\n self.horizontalLayout.addWidget(self.label)\n self.label_2 = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_2.setObjectName(\"label_2\")\n self.label_2.setText(\"This information are emppty : {0} \\n\".format(chaineCara))\n self.horizontalLayout.addWidget(self.label_2)\n self.gridLayout_4.addLayout(self.horizontalLayout, 2, 0, 2, 2)\n self.gridLayout_3 = QtWidgets.QGridLayout()\n self.gridLayout_3.setObjectName(\"gridLayout_3\")\n spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.gridLayout_3.addItem(spacerItem, 0, 0, 1, 1)\n self.pushButton = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n self.pushButton.setObjectName(\"pushButton\")\n self.pushButton.setText(\"Ok\")\n self.pushButton.clicked.connect(self.buttonClicked_newAnalyse_etape4)\n self.gridLayout_3.addWidget(self.pushButton, 0, 1, 1, 1)\n self.gridLayout_4.addLayout(self.gridLayout_3, 5, 1, 1, 1)\n spacerItem1 = QtWidgets.QSpacerItem(356, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.gridLayout_4.addItem(spacerItem1, 0, 0, 1, 2)\n spacerItem2 = QtWidgets.QSpacerItem(356, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.gridLayout_4.addItem(spacerItem2, 1, 0, 1, 2)\n spacerItem3 = QtWidgets.QSpacerItem(350, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.gridLayout_4.addItem(spacerItem3, 4, 1, 1, 1)\n self.scrollArea.setWidget(self.scrollAreaWidgetContents)\n self.gridLayout.addWidget(self.scrollArea, 0, 1, 1, 1)\n MainWindow.setCentralWidget(self.centralwidget)\n\n ######################################################################\n # fenetre ouvrir fichier #\n ######################################################################\n\n #Cette fonction permet d'ouvrir la fénêtre du gestionnaire de fichier\n #et si un fichier est sélectionner de le récupere et remplir la champs de saisie\n #associé (variable le passer en paramètre).\n #Attention : si pluieurs fihiers sont sélectionner, seul le premier renseigner\n #sera pris en compte.\n def ouvrir_fichier(self, le):\n win = classFiles.App()\n if win.nomFichier != \"\":\n le.setText(win.nomFichier[0])\n\n ######################################################################\n # Formulaire - Etape 4 #\n ######################################################################\n\n def buttonClicked_newAnalyse_etape4(self):\n print(\"etape 4 formulaire\")\n\n # Chope les textes des champs précédant\n backStrainID=self.lineEdit_backStrainId.text()\n mappStrainId=self.lineEdit_mappStrainId.text()\n dbSNP=self.lineEdit_dbsnp.text()\n\n if self.radioButton_yesRef.isChecked():\n referenced=0\n elif self.radioButton_noRef.isChecked():\n referenced=1\n else:\n referenced=\"\"\n\n if self.radioButton_yesRef_bis.isChecked():\n dbSNPbool=0\n elif self.radioButton_noRef_bis.isChecked():\n dbSNPbool=1\n else:\n dbSNPbool=\"\"\n\n # On les sauvegarde dans le dictionnaire qui gènre les champs\n self.new.etape3(backStrainID, referenced, mappStrainId, dbSNP,dbSNPbool)\n #print(self.new.dico)\n\n self.scrollArea.hide()\n self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)\n self.scrollArea.setWidgetResizable(True)\n self.scrollArea.setObjectName(\"scrollArea\")\n self.scrollAreaWidgetContents = QtWidgets.QWidget()\n self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 377, 342))\n self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\")\n self.scrollArea.setWidget(self.scrollAreaWidgetContents)\n self.gridLayout.addWidget(self.scrollArea, 0, 1, 1, 1)\n MainWindow.setCentralWidget(self.centralwidget)\n\n self.gridLayout_2 = QtWidgets.QGridLayout(self.scrollAreaWidgetContents)\n self.gridLayout_2.setObjectName(\"gridLayout_2\")\n\n self.label_etape4 = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_etape4.setMaximumSize(QtCore.QSize(16777215, 30))\n self.label_etape4.setObjectName(\"label_etape4\")\n self.label_etape4.setText(\"

    Formulaire : étape 4 sur 4

    \")\n\n self.gridLayout_2.addWidget(self.label_etape4, 0, 0, 1, 1)\n self.label_titre4 = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_titre4.setMaximumSize(QtCore.QSize(16777215, 30))\n self.label_titre4.setObjectName(\"label_titre4\")\n self.label_titre4.setText(\"

    # Additionnal files

    \")\n\n self.gridLayout_2.addWidget(self.label_titre4, 1, 0, 1, 1)\n\n self.horizontalLayout_18 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_18.setObjectName(\"horizontalLayout_18\")\n\n self.label_listScaff = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_listScaff.setObjectName(\"label_listScaff\")\n self.label_listScaff.setText(\"List of scaffolds ID and their size :\")\n\n self.horizontalLayout_18.addWidget(self.label_listScaff)\n\n self.lineEdit_listScaff = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)\n self.lineEdit_listScaff.setText(\"\")\n self.lineEdit_listScaff.setObjectName(\"lineEdit_listScaff\")\n\n if \"listScaff\" in self.new.dico.keys():\n if self.new.dico[\"listScaff\"] != \"\":\n self.lineEdit_listScaff.setText(self.new.dico[\"listScaff\"])\n\n self.horizontalLayout_18.addWidget(self.lineEdit_listScaff)\n\n self.toolButton_listScaff = QtWidgets.QToolButton(self.scrollAreaWidgetContents)\n self.toolButton_listScaff.setObjectName(\"toolButton_listScaff\")\n self.toolButton_listScaff.setText(\"...\")\n self.toolButton_listScaff.clicked.connect(lambda: self.ouvrir_fichier(self.lineEdit_listScaff))\n\n self.horizontalLayout_18.addWidget(self.toolButton_listScaff)\n\n self.gridLayout_2.addLayout(self.horizontalLayout_18, 2, 0, 1, 1)\n\n self.horizontalLayout_11 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_11.setObjectName(\"horizontalLayout_11\")\n\n self.label_InvarScaf = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_InvarScaf.setObjectName(\"label_InvarScaf\")\n self.label_InvarScaf.setText(\"\\\"Invariant\\\" Scaffolds : \")\n\n self.horizontalLayout_11.addWidget(self.label_InvarScaf)\n\n self.lineEdit_InvarScaf = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)\n self.lineEdit_InvarScaf.setText(\"\")\n self.lineEdit_InvarScaf.setObjectName(\"lineEdit_InvarScaf\")\n\n if \"InvarScaf\" in self.new.dico.keys():\n if self.new.dico[\"InvarScaf\"] != \"\":\n self.lineEdit_InvarScaf.setText(self.new.dico[\"InvarScaf\"])\n\n self.horizontalLayout_11.addWidget(self.lineEdit_InvarScaf)\n\n self.toolButton_InvarScaf = QtWidgets.QToolButton(self.scrollAreaWidgetContents)\n self.toolButton_InvarScaf.setObjectName(\"toolButton_InvarScaf\")\n self.toolButton_InvarScaf.setText(\"...\")\n self.toolButton_InvarScaf.clicked.connect(lambda: self.ouvrir_fichier(self.lineEdit_InvarScaf))\n\n self.horizontalLayout_11.addWidget(self.toolButton_InvarScaf)\n\n self.gridLayout_2.addLayout(self.horizontalLayout_11, 3, 0, 1, 1)\n\n self.horizontalLayout_13 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_13.setObjectName(\"horizontalLayout_13\")\n\n self.label_17 = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_17.setObjectName(\"label_17\")\n self.label_17.setToolTip(\"

    list of scaffolds you want to test even if they are not linked to your mutation. (e.g. False-positive or so-far-unlinked scaffolds)

    \")\n self.label_17.setText(\"

    i

    \")\n\n self.horizontalLayout_13.addWidget(self.label_17)\n\n self.label_warnScaf = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_warnScaf.setObjectName(\"label_warnScaf\")\n\n self.horizontalLayout_13.addWidget(self.label_warnScaf)\n\n self.lineEdit_warnScaf = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)\n self.lineEdit_warnScaf.setText(\"\")\n self.lineEdit_warnScaf.setObjectName(\"lineEdit_warnScaf\")\n\n if \"warnScaf\" in self.new.dico.keys():\n if self.new.dico[\"warnScaf\"] != \"\":\n self.lineEdit_warnScaf.setText(self.new.dico[\"warnScaf\"])\n\n self.label_warnScaf.setToolTip(\"


    \")\n self.label_warnScaf.setText(\"Warning Scaffolds : \")\n\n self.horizontalLayout_13.addWidget(self.lineEdit_warnScaf)\n\n self.toolButton_warnScaf = QtWidgets.QToolButton(self.scrollAreaWidgetContents)\n self.toolButton_warnScaf.setObjectName(\"toolButton_warnScaf\")\n self.toolButton_warnScaf.setText(\"...\")\n self.toolButton_warnScaf.clicked.connect(lambda: self.ouvrir_fichier(self.lineEdit_warnScaf))\n\n self.horizontalLayout_13.addWidget(self.toolButton_warnScaf)\n\n self.gridLayout_2.addLayout(self.horizontalLayout_13, 4, 0, 1, 1)\n spacerItem = QtWidgets.QSpacerItem(470, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n\n self.gridLayout_2.addItem(spacerItem, 5, 0, 1, 1)\n\n self.horizontalLayout = QtWidgets.QHBoxLayout()\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n\n self.pushButton_back4 = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n self.pushButton_back4.setObjectName(\"pushButton_back4\")\n self.pushButton_back4.setText(\"Back\")\n self.pushButton_back4.clicked.connect(self.buttonClicked_newAnalyse_etape3)\n\n self.horizontalLayout.addWidget(self.pushButton_back4)\n spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout.addItem(spacerItem1)\n\n self.pushButton_runAnalysis = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n self.pushButton_runAnalysis.setMinimumSize(QtCore.QSize(116, 0))\n self.pushButton_runAnalysis.setMaximumSize(QtCore.QSize(50, 30))\n self.pushButton_runAnalysis.setSizeIncrement(QtCore.QSize(1, 1))\n palette = QtGui.QPalette()\n brush = QtGui.QBrush(QtGui.QColor(170, 255, 0))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)\n brush = QtGui.QBrush(QtGui.QColor(242, 241, 240))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)\n brush = QtGui.QBrush(QtGui.QColor(242, 241, 240))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)\n self.pushButton_runAnalysis.setPalette(palette)\n self.pushButton_runAnalysis.setObjectName(\"pushButton_runAnalysis\")\n self.pushButton_runAnalysis.setText(\"Run Analysis\")\n\n #Vérification des champs :\n #Pour l'instant sur les champs sont vide alors cela retourne un erreur,\n #A voir pour améliorer en fonction des extention du fichier que l'on s'attent\n # a avoir. Si c'est un VCF par exemple : spliter par \".\" et récupere la deuxieme\n #valeurs pour verrifier qu'elle est bien égale a vcf.\n ChampsOk=0\n infoErr=\"\\n\\n\"\n for champs in self.new.listeChamps:\n if self.new.dico[champs] == \"\" :\n ChampsOk=1\n infoErr+=\"- {0}\\n\".format(champs)\n\n #pour les read on vérifie pour tous qu'il ne soit pas vide.\n for i in range(self.new.dico[\"nbrRead\"]):\n read=\"read\"\n read+=str(i)\n if self.new.dico[read] == \"\" :\n ChampsOk=1\n infoErr+=\"- read {0}\\n\".format(i)\n\n\n #On regarde en fonction de la valeur dbSNPbool si le Champs\n # dbSNP doit être remplis ou non puis on vérifie qu'il le soit.\n if self.new.dico[\"dbSNPbool\"] == 0 :\n if self.new.dico[\"dbSNP\"] == \"\" :\n ChampsOk=1\n infoErr+=\"- {0}\\n\".format(champs)\n\n #Si tout les champs sont valide on lance l'analyse :\n if ChampsOk == 0 :\n self.pushButton_runAnalysis.clicked.connect(self.RunAnalysis)\n else :\n #pop up avec les champs qui pose probleme\n self.pushButton_runAnalysis.clicked.connect(lambda: self.buttonClicked_newAnalyse_probleme(infoErr))\n\n self.horizontalLayout.addWidget(self.pushButton_runAnalysis)\n self.gridLayout_2.addLayout(self.horizontalLayout, 6, 0, 1, 1)\n\n ######################################################################\n # Affichage dynamique #\n ######################################################################\n\n #Ces deux fonctions permettent d'affichier ou de cacher le champs du dbSNP\n # elle sont lancer selon si on clique sur oui (cela affciher le champs)\n # ou sur non, ce qui cache le champs.\n def AfficheSidbSNPexistePas(self):\n self.label_dbsnp.show()\n self.lineEdit_dbsnp.show()\n self.toolButton_dbsnp.show()\n\n def CacheSidbSNPexiste(self):\n self.label_dbsnp.hide()\n self.lineEdit_dbsnp.hide()\n self.toolButton_dbsnp.hide()\n\n ######################################################################\n # Formulaire - Etape 3 #\n ######################################################################\n\n def buttonClicked_newAnalyse_etape3(self):\n print(\"etape 3 formulaire\")\n\n # Chope les textes des champs précédant\n plateforme=self.lineEdit_plateforme.text()\n sample=self.lineEdit_sample.text()\n library=self.lineEdit_library.text()\n rgid=self.lineEdit_rgid.text()\n rgpu=self.lineEdit_rgpu.text()\n # On les sauvegarde dans le dictionnaire qui gènre les champs\n self.new.etape2(plateforme, sample, library, rgid, rgpu)\n #print(self.new.dico)\n\n self.scrollArea.hide()\n self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)\n self.scrollArea.setWidgetResizable(True)\n self.scrollArea.setObjectName(\"scrollArea\")\n self.scrollAreaWidgetContents = QtWidgets.QWidget()\n self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 377, 342))\n self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\")\n self.scrollArea.setWidget(self.scrollAreaWidgetContents)\n self.gridLayout.addWidget(self.scrollArea, 0, 1, 1, 1)\n MainWindow.setCentralWidget(self.centralwidget)\n\n self.gridLayout_3 = QtWidgets.QGridLayout(self.scrollAreaWidgetContents)\n self.gridLayout_3.setObjectName(\"gridLayout_3\")\n\n self.label_etape3 = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_etape3.setMaximumSize(QtCore.QSize(16777215, 30))\n self.label_etape3.setObjectName(\"label_etape3\")\n self.label_etape3.setText(\"

    Formulaire : étape 3 sur 4

    \")\n\n self.gridLayout_3.addWidget(self.label_etape3, 0, 0, 1, 1)\n\n self.label_titre3 = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_titre3.setMaximumSize(QtCore.QSize(16777215, 30))\n self.label_titre3.setObjectName(\"label_titre3\")\n self.label_titre3.setText(\"

    # Design of the population for the cartographie

    \")\n\n self.gridLayout_3.addWidget(self.label_titre3, 1, 0, 1, 1)\n\n self.horizontalLayout_10 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_10.setObjectName(\"horizontalLayout_10\")\n\n self.label_backStrainId = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_backStrainId.setObjectName(\"label_backStrainId\")\n self.label_backStrainId.setText(\"Background strain ID : \")\n\n self.horizontalLayout_10.addWidget(self.label_backStrainId)\n\n self.lineEdit_backStrainId = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)\n self.lineEdit_backStrainId.setText(\"\")\n self.lineEdit_backStrainId.setObjectName(\"lineEdit_backStrainId\")\n\n if \"backStrainId\" in self.new.dico.keys():\n if self.new.dico[\"backStrainId\"] != \"\":\n self.lineEdit_backStrainId.setText(self.new.dico[\"backStrainId\"])\n\n self.horizontalLayout_10.addWidget(self.lineEdit_backStrainId)\n\n self.gridLayout_3.addLayout(self.horizontalLayout_10, 2, 0, 1, 1)\n\n self.horizontalLayout = QtWidgets.QHBoxLayout()\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n\n self.label_ref = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_ref.setObjectName(\"label_ref\")\n self.label_ref.setText(\"Referenced : \")\n\n self.horizontalLayout.addWidget(self.label_ref)\n self.ButtonGroup_snp = QtWidgets.QButtonGroup()\n\n self.radioButton_yesRef = QtWidgets.QRadioButton(self.scrollAreaWidgetContents)\n self.radioButton_yesRef.setObjectName(\"radioButton_yesRef\")\n self.radioButton_yesRef.setText(\"yes\")\n\n if \"referenced\" in self.new.dico.keys():\n if self.new.dico[\"referenced\"] == 0:\n self.radioButton_yesRef.setChecked(True)\n\n self.horizontalLayout.addWidget(self.radioButton_yesRef)\n self.ButtonGroup_snp.addButton(self.radioButton_yesRef)\n\n self.radioButton_noRef = QtWidgets.QRadioButton(self.scrollAreaWidgetContents)\n self.radioButton_noRef.setObjectName(\"radioButton_noRef\")\n self.radioButton_noRef.setText(\"no\")\n\n if \"referenced\" in self.new.dico.keys():\n if self.new.dico[\"referenced\"] == 1:\n self.radioButton_noRef.setChecked(True)\n\n self.ButtonGroup_snp.addButton(self.radioButton_noRef)\n self.horizontalLayout.addWidget(self.radioButton_noRef)\n\n #####################################################################################\n\n self.horizontalLayout_bis = QtWidgets.QHBoxLayout()\n self.horizontalLayout_bis.setObjectName(\"horizontalLayout\")\n\n self.label_ref = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_ref.setObjectName(\"label_ref\")\n self.label_ref.setText(\"bd_SNP ente background et mapping : \")\n\n self.horizontalLayout_bis.addWidget(self.label_ref)\n\n self.ButtonGroup_snpbool = QtWidgets.QButtonGroup()\n\n self.radioButton_yesRef_bis = QtWidgets.QRadioButton(self.scrollAreaWidgetContents)\n self.radioButton_yesRef_bis.setObjectName(\"radioButton_yesRef\")\n self.radioButton_yesRef_bis.setText(\"yes\")\n\n if \"dbSNPbool\" in self.new.dico.keys():\n if self.new.dico[\"dbSNPbool\"] == 0:\n self.radioButton_yesRef_bis.setChecked(True)\n\n self.ButtonGroup_snpbool.addButton(self.radioButton_yesRef_bis)\n self.horizontalLayout_bis.addWidget(self.radioButton_yesRef_bis)\n\n self.radioButton_noRef_bis = QtWidgets.QRadioButton(self.scrollAreaWidgetContents)\n self.radioButton_noRef_bis.setObjectName(\"radioButton_noRef\")\n self.radioButton_noRef_bis.setText(\"no\")\n\n if \"dbSNPbool\" in self.new.dico.keys():\n if self.new.dico[\"dbSNPbool\"] == 1:\n self.radioButton_noRef_bis.setChecked(True)\n\n self.ButtonGroup_snpbool.addButton(self.radioButton_noRef_bis)\n self.horizontalLayout_bis.addWidget(self.radioButton_noRef_bis)\n\n self.gridLayout_3.addLayout(self.horizontalLayout_bis, 5, 0, 1, 1)\n\n ########################################################################\n\n self.gridLayout_3.addLayout(self.horizontalLayout, 3, 0, 1, 1)\n\n self.horizontalLayout_16 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_16.setObjectName(\"horizontalLayout_16\")\n\n self.label_20 = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_20.setObjectName(\"label_20\")\n self.label_20.setText(\"

    i

    \")\n self.label_20.setToolTip(\"

    It should be the same as RGSM appearing in the $Mapping_gVCF (determine with "Read Group" information during analysis)

    \")\n\n self.horizontalLayout_16.addWidget(self.label_20)\n\n self.label_mappStrainId = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_mappStrainId.setObjectName(\"label_mappStrainId\")\n self.label_mappStrainId.setText(\"Mapping strain ID : \")\n\n self.horizontalLayout_16.addWidget(self.label_mappStrainId)\n\n self.lineEdit_mappStrainId = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)\n self.lineEdit_mappStrainId.setText(\"\")\n self.lineEdit_mappStrainId.setObjectName(\"lineEdit_mappStrainId\")\n\n if \"mappStrainId\" in self.new.dico.keys():\n if self.new.dico[\"mappStrainId\"] != \"\":\n self.lineEdit_mappStrainId.setText(self.new.dico[\"mappStrainId\"])\n\n self.horizontalLayout_16.addWidget(self.lineEdit_mappStrainId)\n\n self.gridLayout_3.addLayout(self.horizontalLayout_16, 4, 0, 1, 1)\n\n self.horizontalLayout_17 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_17.setObjectName(\"horizontalLayout_17\")\n\n self.label_dbsnp = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_dbsnp.setObjectName(\"label_dbsnp\")\n self.label_dbsnp.setText(\"dbSNP (background vs mapping) :\")\n\n self.horizontalLayout_17.addWidget(self.label_dbsnp)\n\n self.lineEdit_dbsnp = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)\n self.lineEdit_dbsnp.setText(\"\")\n self.lineEdit_dbsnp.setObjectName(\"lineEdit_dbsnp\")\n\n if \"dbSNP\" in self.new.dico.keys():\n if self.new.dico[\"dbSNP\"] != \"\":\n self.lineEdit_dbsnp.setText(self.new.dico[\"dbSNP\"])\n\n self.horizontalLayout_17.addWidget(self.lineEdit_dbsnp)\n\n self.toolButton_dbsnp = QtWidgets.QToolButton(self.scrollAreaWidgetContents)\n self.toolButton_dbsnp.setObjectName(\"toolButton_dbsnp\")\n self.toolButton_dbsnp.setText(\"...\")\n self.toolButton_dbsnp.clicked.connect(lambda: self.ouvrir_fichier(self.lineEdit_dbsnp))\n\n self.horizontalLayout_17.addWidget(self.toolButton_dbsnp)\n\n self.gridLayout_3.addLayout(self.horizontalLayout_17, 6, 0, 1, 1)\n\n spacerItem = QtWidgets.QSpacerItem(470, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n\n self.gridLayout_3.addItem(spacerItem, 7, 0, 1, 1)\n\n self.horizontalLayout_2 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\n\n self.pushButton_back3 = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n self.pushButton_back3.setObjectName(\"pushButton_back3\")\n self.pushButton_back3.setText(\"Back\")\n self.pushButton_back3.clicked.connect(self.buttonClicked_newAnalyse_etape2)\n\n self.horizontalLayout_2.addWidget(self.pushButton_back3)\n\n spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n\n self.horizontalLayout_2.addItem(spacerItem1)\n\n self.pushButton_next3 = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n self.pushButton_next3.setObjectName(\"pushButton_next3\")\n self.pushButton_next3.setText(\"Next\")\n self.pushButton_next3.clicked.connect(self.buttonClicked_newAnalyse_etape4)\n\n self.horizontalLayout_2.addWidget(self.pushButton_next3)\n\n if self.new.dico[\"dbSNPbool\"] == 1 :\n self.label_dbsnp.hide()\n self.lineEdit_dbsnp.hide()\n self.toolButton_dbsnp.hide()\n else :\n if not \"dbSNPbool\" in self.new.dico.keys():\n self.label_dbsnp.hide()\n self.lineEdit_dbsnp.hide()\n self.toolButton_dbsnp.hide()\n\n self.radioButton_yesRef_bis.clicked.connect(self.AfficheSidbSNPexistePas)\n self.radioButton_noRef_bis.clicked.connect(self.CacheSidbSNPexiste)\n\n self.gridLayout_3.addLayout(self.horizontalLayout_2, 7, 0, 1, 1)\n self.scrollArea.setWidget(self.scrollAreaWidgetContents)\n self.gridLayout.addWidget(self.scrollArea, 0, 1, 1, 1)\n MainWindow.setCentralWidget(self.centralwidget)\n\n\n ######################################################################\n # Formulaire - Etape 2 #\n ######################################################################\n\n def buttonClicked_newAnalyse_etape2(self):\n print(\"etape 2 formulaire\")\n\n ## Avant de cacher les champs et de les \"effacer\" je recupere les valeurs des\n ## champs pour remplir le fichier de config\n # Chope les texte\n GenRef=self.lineEdit_genRef.text()\n nom=self.lineEdit_nom.text()\n\n read=[]\n if self.nbr==2:\n read.append(self.lineEdit_r1.text())\n read.append(self.lineEdit_r2.text())\n if self.nbr==4:\n read.append(self.lineEdit_r1.text())\n read.append(self.lineEdit_r2.text())\n read.append(self.lineEdit_r3.text())\n read.append(self.lineEdit_r4.text())\n if self.nbr==6:\n read.append(self.lineEdit_r1.text())\n read.append(self.lineEdit_r2.text())\n read.append(self.lineEdit_r3.text())\n read.append(self.lineEdit_r4.text())\n read.append(self.lineEdit_r5.text())\n read.append(self.lineEdit_r6.text())\n if self.nbr==7:\n read.append(self.lineEdit_r1.text())\n read.append(self.lineEdit_r2.text())\n read.append(self.lineEdit_r3.text())\n read.append(self.lineEdit_r4.text())\n read.append(self.lineEdit_r5.text())\n read.append(self.lineEdit_r6.text())\n read.append(self.lineEdit_r7.text())\n read.append(self.lineEdit_r8.text())\n\n # On les sauvegarde dans le dictionnaire qui gènre les champs\n self.new.etape1(GenRef, self.nbr, read, nom)\n\n ## Mise en place des champs de formulaire pour l'affichage de l'étape 2\n # Cacher les ancien champs en cachant la scroll area\n self.scrollArea.hide()\n # Recréer l'esapce de scroll area vide\n self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)\n self.scrollArea.setWidgetResizable(True)\n self.scrollArea.setObjectName(\"scrollArea\")\n self.scrollAreaWidgetContents = QtWidgets.QWidget()\n self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 377, 342))\n self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\")\n self.scrollArea.setWidget(self.scrollAreaWidgetContents)\n self.gridLayout.addWidget(self.scrollArea, 0, 1, 1, 1)\n MainWindow.setCentralWidget(self.centralwidget)\n\n # Ajout de tout les champs dans la nouvelle scroll area de l'etape 2\n\n self.gridLayout_5 = QtWidgets.QGridLayout(self.scrollAreaWidgetContents)\n self.gridLayout_5.setObjectName(\"gridLayout_5\")\n\n self.gridLayout_4 = QtWidgets.QGridLayout()\n self.gridLayout_4.setObjectName(\"gridLayout_4\")\n\n self.pushButton_next2 = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n self.pushButton_next2.setObjectName(\"pushButton_next2\")\n self.pushButton_next2.setText(\"Next\")\n self.pushButton_next2.clicked.connect(self.buttonClicked_newAnalyse_etape3)\n\n self.gridLayout_4.addWidget(self.pushButton_next2, 0, 2, 1, 1)\n spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.gridLayout_4.addItem(spacerItem, 0, 1, 1, 1)\n self.pushButton_back2 = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n self.pushButton_back2.setObjectName(\"pushButton_back2\")\n self.pushButton_back2.setText(\"Back\")\n self.pushButton_back2.clicked.connect(lambda: self.buttonClicked_newAnalyse(\"back\"))\n\n self.gridLayout_4.addWidget(self.pushButton_back2, 0, 0, 1, 1)\n self.gridLayout_5.addLayout(self.gridLayout_4, 4, 0, 1, 2)\n self.label_Indiq2 = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_Indiq2.setMaximumSize(QtCore.QSize(16777215, 30))\n self.label_Indiq2.setObjectName(\"label_Indiq2\")\n self.label_Indiq2.setText(\"

    Les noms des fichiers seront construis ainsi : {FlowCellID}-{sampleID}_Lane

    \")\n\n self.gridLayout_5.addWidget(self.label_Indiq2, 2, 0, 1, 2)\n\n self.gridLayout_3 = QtWidgets.QGridLayout()\n self.gridLayout_3.setObjectName(\"gridLayout_3\")\n\n self.horizontalLayout_2 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\n\n self.label_sample = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_sample.setObjectName(\"label_sample\")\n self.label_sample.setText(\"Sample : \")\n\n self.horizontalLayout_2.addWidget(self.label_sample)\n\n self.lineEdit_sample = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)\n self.lineEdit_sample.setObjectName(\"lineEdit_sample\")\n self.lineEdit_sample.setText(\"\")\n\n #Si la clef est dans le dictionnaire et si la valeur associé n'est pas vide\n #C'est qu'une information est déja présente alors on l'affiche dans la ligne de saisie.\n #Elle peut être présente pasque qu'on la déjà remplis et que l'on revien en arrière dans le dictionnaire\n #ou qu'on a charger une ancienne annalyse.\n if \"sample\" in self.new.dico.keys():\n if self.new.dico[\"sample\"] != \"\":\n self.lineEdit_sample.setText(self.new.dico[\"sample\"])\n\n self.horizontalLayout_2.addWidget(self.lineEdit_sample)\n\n self.gridLayout_3.addLayout(self.horizontalLayout_2, 1, 0, 1, 1)\n\n self.horizontalLayout = QtWidgets.QHBoxLayout()\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n\n self.label_library = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_library.setObjectName(\"label_library\")\n self.label_library.setText(\"Library : \")\n\n self.horizontalLayout.addWidget(self.label_library)\n\n self.lineEdit_library = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)\n self.lineEdit_library.setObjectName(\"lineEdit_library\")\n self.lineEdit_library.setText(\"\")\n\n #Si la clef est dans le dictionnaire et si la valeur associé n'est pas vide\n #C'est qu'une information est déja présente alors on l'affiche dans la ligne de saisie.\n #Elle peut être présente pasque qu'on la déjà remplis et que l'on revien en arrière dans le dictionnaire\n #ou qu'on a charger une ancienne annalyse.\n if \"library\" in self.new.dico.keys():\n if self.new.dico[\"library\"] != \"\":\n self.lineEdit_library.setText(self.new.dico[\"library\"])\n\n self.horizontalLayout.addWidget(self.lineEdit_library)\n\n self.gridLayout_3.addLayout(self.horizontalLayout, 2, 0, 1, 1)\n\n self.horizontalLayout_5 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_5.setObjectName(\"horizontalLayout_5\")\n\n self.label_8 = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_8.setObjectName(\"label_8\")\n self.label_8.setText(\"

    i

    \")\n self.label_8.setToolTip(\"

    Choose \\'Flow Cell ID\\'_\\'sample\\'

    \")\n\n self.horizontalLayout_5.addWidget(self.label_8)\n\n self.label_rgid = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_rgid.setObjectName(\"label_rgid\")\n self.label_rgid.setText(\"RGID : \")\n\n self.horizontalLayout_5.addWidget(self.label_rgid)\n\n self.lineEdit_rgid = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)\n self.lineEdit_rgid.setObjectName(\"lineEdit_rgid\")\n\n #Si la clef est dans le dictionnaire et si la valeur associé n'est pas vide\n #C'est qu'une information est déja présente alors on l'affiche dans la ligne de saisie.\n #Elle peut être présente pasque qu'on la déjà remplis et que l'on revien en arrière dans le dictionnaire\n #ou qu'on a charger une ancienne annalyse.\n if \"rgid\" in self.new.dico.keys():\n if self.new.dico[\"rgid\"] != \"\":\n self.lineEdit_rgid.setText(self.new.dico[\"rgid\"])\n\n self.horizontalLayout_5.addWidget(self.lineEdit_rgid)\n\n self.gridLayout_3.addLayout(self.horizontalLayout_5, 3, 0, 1, 1)\n\n self.horizontalLayout_4 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_4.setObjectName(\"horizontalLayout_4\")\n\n self.label_9 = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_9.setObjectName(\"label_9\")\n\n self.label_9.setText(\"

    i

    \")\n self.label_9.setToolTip(\"

    Choose \\'Flow Cell ID\\'_\\'Lane\\'_\\'sample\\'

    \")\n\n self.horizontalLayout_4.addWidget(self.label_9)\n\n self.label_rgpu = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_rgpu.setObjectName(\"label_rgpu\")\n self.label_rgpu.setText(\"RGPU : \")\n\n self.horizontalLayout_4.addWidget(self.label_rgpu)\n\n self.lineEdit_rgpu = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)\n self.lineEdit_rgpu.setObjectName(\"lineEdit_rgpu\")\n\n #Si la clef est dans le dictionnaire et si la valeur associé n'est pas vide\n #C'est qu'une information est déja présente alors on l'affiche dans la ligne de saisie.\n #Elle peut être présente pasque qu'on la déjà remplis et que l'on revien en arrière dans le dictionnaire\n #ou qu'on a charger une ancienne annalyse.\n if \"rgpu\" in self.new.dico.keys():\n if self.new.dico[\"rgpu\"] != \"\":\n self.lineEdit_rgpu.setText(self.new.dico[\"rgpu\"])\n\n self.horizontalLayout_4.addWidget(self.lineEdit_rgpu)\n\n self.gridLayout_3.addLayout(self.horizontalLayout_4, 4, 0, 1, 1)\n\n self.horizontalLayout_3 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_3.setObjectName(\"horizontalLayout_3\")\n\n self.label_plateforme = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_plateforme.setObjectName(\"label_plateforme\")\n self.label_plateforme.setText(\"Plateforme : \")\n\n self.horizontalLayout_3.addWidget(self.label_plateforme)\n\n self.lineEdit_plateforme = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)\n self.lineEdit_plateforme.setObjectName(\"lineEdit_plateforme\")\n self.lineEdit_plateforme.setText(\"\")\n\n #Si la clef est dans le dictionnaire et si la valeur associé n'est pas vide\n #C'est qu'une information est déja présente alors on l'affiche dans la ligne de saisie.\n #Elle peut être présente pasque qu'on la déjà remplis et que l'on revien en arrière dans le dictionnaire\n #ou qu'on a charger une ancienne annalyse.\n if \"plateforme\" in self.new.dico.keys():\n if self.new.dico[\"plateforme\"] != \"\":\n self.lineEdit_plateforme.setText(self.new.dico[\"plateforme\"])\n\n self.horizontalLayout_3.addWidget(self.lineEdit_plateforme)\n\n self.gridLayout_3.addLayout(self.horizontalLayout_3, 0, 0, 1, 1)\n\n self.gridLayout_5.addLayout(self.gridLayout_3, 3, 0, 1, 2)\n\n self.label_BGI = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_BGI.setMaximumSize(QtCore.QSize(16777215, 30))\n self.label_BGI.setMidLineWidth(0)\n self.label_BGI.setIndent(1)\n self.label_BGI.setOpenExternalLinks(False)\n self.label_BGI.setObjectName(\"label_BGI\")\n self.label_BGI.setText(\"

    # BGI

    \")\n\n self.gridLayout_5.addWidget(self.label_BGI, 1, 0, 1, 1)\n\n self.label_etape2 = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_etape2.setMaximumSize(QtCore.QSize(16777215, 30))\n self.label_etape2.setObjectName(\"label_etape2\")\n self.label_etape2.setText(\"

    Formulaire : étape 2 sur 4

    \")\n\n self.gridLayout_5.addWidget(self.label_etape2, 0, 0, 1, 2)\n\n self.label_BGI.raise_()\n self.label_Indiq2.raise_()\n self.label_etape2.raise_()\n\n self.scrollArea.setWidget(self.scrollAreaWidgetContents)\n self.gridLayout.addWidget(self.scrollArea, 0, 2, 1, 1)\n MainWindow.setCentralWidget(self.centralwidget)\n\n ######################################################################\n # fonction permettant de dynamiser les ligne info de read #\n ######################################################################\n\n #Cette fonction permet l'affichage de moins de champs de lecture (read) en fonction\n #de ceux qui sont déja présent dans l'anayse. Elle se sert de l'indication donner\n #par self.nbr et le met a jours.\n def moins (self, nbr):\n\n if self.nbr==4 :\n self.label_r1.show()\n self.lineEdit_r1.show()\n self.toolButton_r1.show()\n\n self.label_r2.show()\n self.lineEdit_r2.show()\n self.toolButton_r2.show()\n\n self.label_r3.hide()\n self.lineEdit_r3.hide()\n self.toolButton_r3.hide()\n\n self.label_r4.hide()\n self.lineEdit_r4.hide()\n self.toolButton_r4.hide()\n\n self.label_r5.hide()\n self.lineEdit_r5.hide()\n self.toolButton_r5.hide()\n\n self.label_r6.hide()\n self.lineEdit_r6.hide()\n self.toolButton_r6.hide()\n\n self.label_r7.hide()\n self.lineEdit_r7.hide()\n self.toolButton_r7.hide()\n\n self.label_r8.hide()\n self.lineEdit_r8.hide()\n self.toolButton_r8.hide()\n\n self.nbr=2\n\n elif self.nbr == 6:\n self.label_r1.show()\n self.lineEdit_r1.show()\n self.toolButton_r1.show()\n\n self.label_r2.show()\n self.lineEdit_r2.show()\n self.toolButton_r2.show()\n\n self.label_r3.show()\n self.lineEdit_r3.show()\n self.toolButton_r3.show()\n\n self.label_r4.show()\n self.lineEdit_r4.show()\n self.toolButton_r4.show()\n\n self.label_r5.hide()\n self.lineEdit_r5.hide()\n self.toolButton_r5.hide()\n\n self.label_r6.hide()\n self.lineEdit_r6.hide()\n self.toolButton_r6.hide()\n\n self.label_r7.hide()\n self.lineEdit_r7.hide()\n self.toolButton_r7.hide()\n\n self.label_r8.hide()\n self.lineEdit_r8.hide()\n self.toolButton_r8.hide()\n\n self.nbr=4\n\n elif self.nbr == 8:\n self.label_r1.show()\n self.lineEdit_r1.show()\n self.toolButton_r1.show()\n\n self.label_r2.show()\n self.lineEdit_r2.show()\n self.toolButton_r2.show()\n\n self.label_r3.show()\n self.lineEdit_r3.show()\n self.toolButton_r3.show()\n\n self.label_r4.show()\n self.lineEdit_r4.show()\n self.toolButton_r4.show()\n\n self.label_r5.show()\n self.lineEdit_r5.show()\n self.toolButton_r5.show()\n\n self.label_r6.show()\n self.lineEdit_r6.show()\n self.toolButton_r6.show()\n\n self.label_r7.hide()\n self.lineEdit_r7.hide()\n self.toolButton_r7.hide()\n\n self.label_r8.hide()\n self.lineEdit_r8.hide()\n self.toolButton_r8.hide()\n\n self.nbr=6\n\n #Cette fonction permet l'affichage de plus de champs de lecture (read) en fonction\n #de ceux qui sont déja présent dans l'anayse. Elle se sert de l'indication donner\n #par self.nbr et le met a jours. Si on affiche 4 champs et que l'on en remplis que deux\n #le formulaire va lever une erreur puisque deux champs serons vide. Si on a vraiment\n #que deux champs il faufra cacher deux champs.\n def plus (self):\n\n if self.nbr == 2 :\n self.label_r1.show()\n self.lineEdit_r1.show()\n self.toolButton_r1.show()\n\n self.label_r2.show()\n self.lineEdit_r2.show()\n self.toolButton_r2.show()\n\n self.label_r3.show()\n self.lineEdit_r3.show()\n self.toolButton_r3.show()\n\n self.label_r4.show()\n self.lineEdit_r4.show()\n self.toolButton_r4.show()\n\n self.label_r5.hide()\n self.lineEdit_r5.hide()\n self.toolButton_r5.hide()\n\n self.label_r6.hide()\n self.lineEdit_r6.hide()\n self.toolButton_r6.hide()\n\n self.label_r7.hide()\n self.lineEdit_r7.hide()\n self.toolButton_r7.hide()\n\n self.label_r8.hide()\n self.lineEdit_r8.hide()\n self.toolButton_r8.hide()\n\n self.nbr=4\n\n elif self.nbr == 4 :\n self.label_r1.show()\n self.lineEdit_r1.show()\n self.toolButton_r1.show()\n\n self.label_r2.show()\n self.lineEdit_r2.show()\n self.toolButton_r2.show()\n\n self.label_r3.show()\n self.lineEdit_r3.show()\n self.toolButton_r3.show()\n\n self.label_r4.show()\n self.lineEdit_r4.show()\n self.toolButton_r4.show()\n\n self.label_r5.show()\n self.lineEdit_r5.show()\n self.toolButton_r5.show()\n\n self.label_r6.show()\n self.lineEdit_r6.show()\n self.toolButton_r6.show()\n\n self.label_r7.hide()\n self.lineEdit_r7.hide()\n self.toolButton_r7.hide()\n\n self.label_r8.hide()\n self.lineEdit_r8.hide()\n self.toolButton_r8.hide()\n\n self.nbr=6\n\n elif self.nbr == 6 :\n self.label_r1.show()\n self.lineEdit_r1.show()\n self.toolButton_r1.show()\n\n self.label_r2.show()\n self.lineEdit_r2.show()\n self.toolButton_r2.show()\n\n self.label_r3.show()\n self.lineEdit_r3.show()\n self.toolButton_r3.show()\n\n self.label_r4.show()\n self.lineEdit_r4.show()\n self.toolButton_r4.show()\n\n self.label_r5.show()\n self.lineEdit_r5.show()\n self.toolButton_r5.show()\n\n self.label_r6.show()\n self.lineEdit_r6.show()\n self.toolButton_r6.show()\n\n self.label_r7.show()\n self.lineEdit_r7.show()\n self.toolButton_r7.show()\n\n self.label_r8.show()\n self.lineEdit_r8.show()\n self.toolButton_r8.show()\n\n self.nbr=8\n\n ######################################################################\n # Formulaire - Etape 1 #\n ######################################################################\n\n #if i in self.dico_indexer_read.keys():\n\n def buttonClicked_newAnalyse(self, indicationDeOuLonViens, fichier=None):\n print(\"nouvelle annalyse\")\n self.scrollArea.hide()\n\n #Selon d'ou on viens (de quelle bouton nous a amener a cette premiere page du formulaire)\n #le ditionnaire ne se comporte pas de la même manière, une varriable passer en paramettre de\n #la fonction nous l'indique donc.\n\n #Si l'on viens du bouton back de la page deux du dictionnaire on veux les information du\n #dictionnaire utilisé (en cours) donc on ne fait rien.\n if indicationDeOuLonViens == \"back\":\n pass\n #Si l'on viens du bouton ok de la première page de recharge d'une analyse on veux charger en mémoire\n #le dictionnaire de l'ancienne analyse (fonction remplisDico de la classe formulaire)\n #On efface aussi le titre dans ce dictionnaire pour ne pas ecracraser par erreur le formulaire de l'nalyse\n #que l'on recharge, et être obliger de lui donner un nouveau titre (il faut eviter de lui donner exactement\n #le même nom).\n #On met a jours le nombre de fichier de lectures (read) ensuite en fonction des données présente\n #dans le dictionnaire charger.\n if indicationDeOuLonViens == \"fichierConfigue\":\n #print(\"viens de re forme\")\n self.new=ClassFormulaire.Formulaire()\n self.new.remplisDico(fichier)\n self.new.dico[\"nom\"]=\"\"\n if \"read1\" in self.new.dico.keys():\n #print(\"1\")\n self.nbr=2\n if \"read3\" in self.new.dico.keys():\n #print(\"3\")\n self.nbr=4\n if \"read5\" in self.new.dico.keys():\n #print(\"5\")\n self.nbr=6\n if \"read7\" in self.new.dico.keys():\n #print(\"7\")\n self.nbr=8\n #Si l'on viens du bouton nouvelle analyse du menu gauche on veux vider le dictionnaire\n #si il contient déjà des données pour démaré une nnouvelle analyse.\n if indicationDeOuLonViens == \"nouvelle analyse\" :\n #print(\"viens de nouvelle analyse\")\n self.new=ClassFormulaire.Formulaire()\n\n self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)\n self.scrollArea.setWidgetResizable(True)\n self.scrollArea.setObjectName(\"scrollArea\")\n self.scrollAreaWidgetContents = QtWidgets.QWidget()\n self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 377, 342))\n self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\")\n self.scrollArea.setWidget(self.scrollAreaWidgetContents)\n self.gridLayout.addWidget(self.scrollArea, 0, 1, 1, 1)\n MainWindow.setCentralWidget(self.centralwidget)\n\n self.gridLayout_3 = QtWidgets.QGridLayout(self.scrollAreaWidgetContents)\n self.gridLayout_3.setObjectName(\"gridLayout_3\")\n\n self.label_etape1 = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_etape1.setMaximumSize(QtCore.QSize(16777215, 30))\n self.label_etape1.setObjectName(\"label_etape1\")\n self.label_etape1.setText(\"

    Formulaire : étape 1 sur 4

    \")\n\n self.gridLayout_3.addWidget(self.label_etape1, 0, 0, 1, 1)\n self.label_titre1 = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_titre1.setMaximumSize(QtCore.QSize(16777215, 30))\n self.label_titre1.setObjectName(\"label_titre1\")\n self.label_titre1.setText(\"

    # Your inputs :

    \")\n\n self.gridLayout_3.addWidget(self.label_titre1, 1, 0, 1, 1)\n self.horizontalLayout_11 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_11.setObjectName(\"horizontalLayout_11\")\n\n self.label_nom = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_nom.setObjectName(\"label_nom\")\n self.label_nom.setText(\"Nom de l\\'analyse : \")\n\n self.horizontalLayout_11.addWidget(self.label_nom)\n self.lineEdit_nom = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)\n self.lineEdit_nom.setObjectName(\"lineEdit_nom\")\n\n #Si la clef est dans le dictionnaire et si la valeur associé n'est pas vide\n #C'est qu'une information est déja présente alors on l'affiche dans la ligne de saisie.\n #Elle peut être présente pasque qu'on la déjà remplis et que l'on revien en arrière dans le dictionnaire\n #ou qu'on a charger une ancienne annalyse.\n if \"nom\" in self.new.dico.keys():\n if self.new.dico[\"nom\"] != \"\":\n self.lineEdit_nom.setText(self.new.dico[\"nom\"])\n\n self.horizontalLayout_11.addWidget(self.lineEdit_nom)\n self.gridLayout_3.addLayout(self.horizontalLayout_11, 2, 0, 1, 1)\n\n self.horizontalLayout_10 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_10.setObjectName(\"horizontalLayout_10\")\n self.label_genRef = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_genRef.setObjectName(\"label_genRef\")\n self.label_genRef.setText(\"Génome de référence : \")\n\n self.horizontalLayout_10.addWidget(self.label_genRef)\n self.lineEdit_genRef = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)\n self.lineEdit_genRef.setObjectName(\"lineEdit_genRef\")\n self.horizontalLayout_10.addWidget(self.lineEdit_genRef)\n self.toolButton_genRef = QtWidgets.QToolButton(self.scrollAreaWidgetContents)\n self.toolButton_genRef.setObjectName(\"toolButton_genRef\")\n self.toolButton_genRef.setText(\"...\")\n self.toolButton_genRef.clicked.connect(lambda: self.ouvrir_fichier(self.lineEdit_genRef))\n\n #Si la clef est dans le dictionnaire et si la valeur associé n'est pas vide\n #C'est qu'une information est déja présente alors on l'affiche dans la ligne de saisie.\n #Elle peut être présente pasque qu'on la déjà remplis et que l'on revien en arrière dans le dictionnaire\n #ou qu'on a charger une ancienne annalyse.\n if \"genRef\" in self.new.dico.keys():\n if self.new.dico[\"genRef\"] != \"\":\n self.lineEdit_genRef.setText(self.new.dico[\"genRef\"])\n\n self.horizontalLayout_10.addWidget(self.toolButton_genRef)\n self.gridLayout_3.addLayout(self.horizontalLayout_10, 3, 0, 1, 1)\n self.horizontalLayout = QtWidgets.QHBoxLayout()\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n\n self.label_r1 = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_r1.setObjectName(\"label_r1\")\n self.label_r1.setText(\"[1] Read : \")\n\n self.horizontalLayout.addWidget(self.label_r1)\n self.lineEdit_r1 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)\n self.lineEdit_r1.setObjectName(\"lineEdit_r1\")\n\n #Si la clef est dans le dictionnaire et si la valeur associé n'est pas vide\n #C'est qu'une information est déja présente alors on l'affiche dans la ligne de saisie.\n #Elle peut être présente pasque qu'on la déjà remplis et que l'on revien en arrière dans le dictionnaire\n #ou qu'on a charger une ancienne annalyse.\n if \"read0\" in self.new.dico.keys():\n if self.new.dico[\"read0\"] != \"\":\n self.lineEdit_r1.setText(self.new.dico[\"read0\"])\n\n self.horizontalLayout.addWidget(self.lineEdit_r1)\n self.toolButton_r1 = QtWidgets.QToolButton(self.scrollAreaWidgetContents)\n self.toolButton_r1.setObjectName(\"toolButton_r1\")\n self.toolButton_r1.setText(\"...\")\n self.toolButton_r1.clicked.connect(lambda: self.ouvrir_fichier(self.lineEdit_r1))\n\n self.horizontalLayout.addWidget(self.toolButton_r1)\n self.gridLayout_3.addLayout(self.horizontalLayout, 4, 0, 1, 1)\n self.horizontalLayout_9 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_9.setObjectName(\"horizontalLayout_9\")\n self.label_r2 = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_r2.setObjectName(\"label_r2\")\n self.label_r2.setText(\"[2] Read : \")\n\n self.horizontalLayout_9.addWidget(self.label_r2)\n self.lineEdit_r2 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)\n self.lineEdit_r2.setObjectName(\"lineEdit_r2\")\n\n #Si la clef est dans le dictionnaire et si la valeur associé n'est pas vide\n #C'est qu'une information est déja présente alors on l'affiche dans la ligne de saisie.\n #Elle peut être présente pasque qu'on la déjà remplis et que l'on revien en arrière dans le dictionnaire\n #ou qu'on a charger une ancienne annalyse.\n if \"read1\" in self.new.dico.keys():\n if self.new.dico[\"read1\"] != \"\":\n self.lineEdit_r2.setText(self.new.dico[\"read1\"])\n\n self.horizontalLayout_9.addWidget(self.lineEdit_r2)\n self.toolButton_r2 = QtWidgets.QToolButton(self.scrollAreaWidgetContents)\n self.toolButton_r2.setObjectName(\"toolButton_r2\")\n self.toolButton_r2.setText(\"...\")\n self.toolButton_r2.clicked.connect(lambda: self.ouvrir_fichier(self.lineEdit_r2))\n\n self.horizontalLayout_9.addWidget(self.toolButton_r2)\n self.gridLayout_3.addLayout(self.horizontalLayout_9, 5, 0, 1, 1)\n self.horizontalLayout_2 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\n self.label_r3 = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_r3.setObjectName(\"label_r3\")\n self.label_r3.setText(\"[3] Read : \")\n\n self.horizontalLayout_2.addWidget(self.label_r3)\n self.lineEdit_r3 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)\n self.lineEdit_r3.setObjectName(\"lineEdit_r3\")\n\n #Si la clef est dans le dictionnaire et si la valeur associé n'est pas vide\n #C'est qu'une information est déja présente alors on l'affiche dans la ligne de saisie.\n #Elle peut être présente pasque qu'on la déjà remplis et que l'on revien en arrière dans le dictionnaire\n #ou qu'on a charger une ancienne annalyse.\n if \"read2\" in self.new.dico.keys():\n if self.new.dico[\"read2\"] != \"\":\n self.lineEdit_r3.setText(self.new.dico[\"read2\"])\n\n self.horizontalLayout_2.addWidget(self.lineEdit_r3)\n self.toolButton_r3 = QtWidgets.QToolButton(self.scrollAreaWidgetContents)\n self.toolButton_r3.setObjectName(\"toolButton_r3\")\n self.toolButton_r3.setText(\"...\")\n self.toolButton_r3.clicked.connect(lambda: self.ouvrir_fichier(self.lineEdit_r3))\n\n self.horizontalLayout_2.addWidget(self.toolButton_r3)\n self.gridLayout_3.addLayout(self.horizontalLayout_2, 6, 0, 1, 1)\n self.horizontalLayout_4 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_4.setObjectName(\"horizontalLayout_4\")\n self.label_r4 = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_r4.setObjectName(\"label_r4\")\n self.label_r4.setText(\"[4] Read : \")\n\n self.horizontalLayout_4.addWidget(self.label_r4)\n self.lineEdit_r4 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)\n self.lineEdit_r4.setObjectName(\"lineEdit_r4\")\n\n #Si la clef est dans le dictionnaire et si la valeur associé n'est pas vide\n #C'est qu'une information est déja présente alors on l'affiche dans la ligne de saisie.\n #Elle peut être présente pasque qu'on la déjà remplis et que l'on revien en arrière dans le dictionnaire\n #ou qu'on a charger une ancienne annalyse.\n if \"read3\" in self.new.dico.keys():\n if self.new.dico[\"read3\"] != \"\":\n self.lineEdit_r4.setText(self.new.dico[\"read3\"])\n\n self.horizontalLayout_4.addWidget(self.lineEdit_r4)\n self.toolButton_r4 = QtWidgets.QToolButton(self.scrollAreaWidgetContents)\n self.toolButton_r4.setObjectName(\"toolButton_r4\")\n self.toolButton_r4.setText(\"...\")\n self.toolButton_r4.clicked.connect(lambda: self.ouvrir_fichier(self.lineEdit_r4))\n\n self.horizontalLayout_4.addWidget(self.toolButton_r4)\n self.gridLayout_3.addLayout(self.horizontalLayout_4, 7, 0, 1, 1)\n self.horizontalLayout_5 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_5.setObjectName(\"horizontalLayout_5\")\n self.label_r5 = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_r5.setObjectName(\"label_r5\")\n self.label_r5.setText(\"[5] Read : \")\n\n self.horizontalLayout_5.addWidget(self.label_r5)\n self.lineEdit_r5 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)\n self.lineEdit_r5.setObjectName(\"lineEdit_r5\")\n\n #Si la clef est dans le dictionnaire et si la valeur associé n'est pas vide\n #C'est qu'une information est déja présente alors on l'affiche dans la ligne de saisie.\n #Elle peut être présente pasque qu'on la déjà remplis et que l'on revien en arrière dans le dictionnaire\n #ou qu'on a charger une ancienne annalyse.\n if \"read4\" in self.new.dico.keys():\n if self.new.dico[\"read4\"] != \"\":\n self.lineEdit_r5.setText(self.new.dico[\"read4\"])\n\n self.horizontalLayout_5.addWidget(self.lineEdit_r5)\n self.toolButton_r5 = QtWidgets.QToolButton(self.scrollAreaWidgetContents)\n self.toolButton_r5.setObjectName(\"toolButton_r5\")\n self.toolButton_r5.setText(\"...\")\n self.toolButton_r5.clicked.connect(lambda: self.ouvrir_fichier(self.lineEdit_r5))\n\n self.horizontalLayout_5.addWidget(self.toolButton_r5)\n self.gridLayout_3.addLayout(self.horizontalLayout_5, 8, 0, 1, 1)\n self.horizontalLayout_6 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_6.setObjectName(\"horizontalLayout_6\")\n self.label_r6 = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_r6.setObjectName(\"label_r6\")\n self.label_r6.setText(\"[6] Read : \")\n\n self.horizontalLayout_6.addWidget(self.label_r6)\n self.lineEdit_r6 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)\n self.lineEdit_r6.setObjectName(\"lineEdit_r6\")\n\n #Si la clef est dans le dictionnaire et si la valeur associé n'est pas vide\n #C'est qu'une information est déja présente alors on l'affiche dans la ligne de saisie.\n #Elle peut être présente pasque qu'on la déjà remplis et que l'on revien en arrière dans le dictionnaire\n #ou qu'on a charger une ancienne annalyse.\n if \"read5\" in self.new.dico.keys():\n if self.new.dico[\"read5\"] != \"\":\n self.lineEdit_r6.setText(self.new.dico[\"read5\"])\n\n self.horizontalLayout_6.addWidget(self.lineEdit_r6)\n self.toolButton_r6 = QtWidgets.QToolButton(self.scrollAreaWidgetContents)\n self.toolButton_r6.setObjectName(\"toolButton_r6\")\n self.toolButton_r6.setText(\"...\")\n self.toolButton_r6.clicked.connect(lambda: self.ouvrir_fichier(self.lineEdit_r6))\n\n self.horizontalLayout_6.addWidget(self.toolButton_r6)\n self.gridLayout_3.addLayout(self.horizontalLayout_6, 9, 0, 1, 1)\n self.horizontalLayout_7 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_7.setObjectName(\"horizontalLayout_7\")\n self.label_r7 = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_r7.setObjectName(\"label_r7\")\n self.label_r7.setText(\"[7] Read : \")\n\n self.horizontalLayout_7.addWidget(self.label_r7)\n self.lineEdit_r7 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)\n self.lineEdit_r7.setObjectName(\"lineEdit_r7\")\n\n #Si la clef est dans le dictionnaire et si la valeur associé n'est pas vide\n #C'est qu'une information est déja présente alors on l'affiche dans la ligne de saisie.\n #Elle peut être présente pasque qu'on la déjà remplis et que l'on revien en arrière dans le dictionnaire\n #ou qu'on a charger une ancienne annalyse.\n if \"read6\" in self.new.dico.keys():\n if self.new.dico[\"read6\"] != \"\":\n self.lineEdit_r7.setText(self.new.dico[\"read6\"])\n\n self.horizontalLayout_7.addWidget(self.lineEdit_r7)\n self.toolButton_r7 = QtWidgets.QToolButton(self.scrollAreaWidgetContents)\n self.toolButton_r7.setObjectName(\"toolButton_r7\")\n self.toolButton_r7.setText(\"...\")\n self.toolButton_r7.clicked.connect(lambda: self.ouvrir_fichier(self.lineEdit_r7))\n\n self.horizontalLayout_7.addWidget(self.toolButton_r7)\n self.gridLayout_3.addLayout(self.horizontalLayout_7, 10, 0, 1, 1)\n self.horizontalLayout_8 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_8.setObjectName(\"horizontalLayout_8\")\n self.label_r8 = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.label_r8.setObjectName(\"label_r8\")\n self.label_r8.setText(\"[8] Read : \")\n\n self.horizontalLayout_8.addWidget(self.label_r8)\n self.lineEdit_r8 = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)\n self.lineEdit_r8.setObjectName(\"lineEdit_r8\")\n\n #Si la clef est dans le dictionnaire et si la valeur associé n'est pas vide\n #C'est qu'une information est déja présente alors on l'affiche dans la ligne de saisie.\n #Elle peut être présente pasque qu'on la déjà remplis et que l'on revien en arrière dans le dictionnaire\n #ou qu'on a charger une ancienne annalyse.\n if \"read7\" in self.new.dico.keys():\n if self.new.dico[\"read7\"] != \"\":\n self.lineEdit_r8.setText(self.new.dico[\"read7\"])\n\n self.horizontalLayout_8.addWidget(self.lineEdit_r8)\n self.toolButton_r8 = QtWidgets.QToolButton(self.scrollAreaWidgetContents)\n self.toolButton_r8.setObjectName(\"toolButton_r8\")\n self.toolButton_r8.setText(\"...\")\n self.toolButton_r8.clicked.connect(lambda: self.ouvrir_fichier(self.lineEdit_r8))\n\n ####################\n #gestion du dynasisme des ligne de saisie des fichiers de lectures.\n #La variable self.nbr gère le nombre de fichiers de lectures nécessaire a\n #l'analyse en cours.\n\n if self.nbr==2:\n self.label_r3.hide()\n self.lineEdit_r3.hide()\n self.toolButton_r3.hide()\n\n self.label_r4.hide()\n self.lineEdit_r4.hide()\n self.toolButton_r4.hide()\n\n self.label_r5.hide()\n self.lineEdit_r5.hide()\n self.toolButton_r5.hide()\n\n self.label_r6.hide()\n self.lineEdit_r6.hide()\n self.toolButton_r6.hide()\n\n self.label_r7.hide()\n self.lineEdit_r7.hide()\n self.toolButton_r7.hide()\n\n self.label_r8.hide()\n self.lineEdit_r8.hide()\n self.toolButton_r8.hide()\n elif self.nbr==4:\n self.label_r5.hide()\n self.lineEdit_r5.hide()\n self.toolButton_r5.hide()\n\n self.label_r6.hide()\n self.lineEdit_r6.hide()\n self.toolButton_r6.hide()\n\n self.label_r7.hide()\n self.lineEdit_r7.hide()\n self.toolButton_r7.hide()\n\n self.label_r8.hide()\n self.lineEdit_r8.hide()\n self.toolButton_r8.hide()\n elif self.nbr==6:\n self.label_r7.hide()\n self.lineEdit_r7.hide()\n self.toolButton_r7.hide()\n\n self.label_r8.hide()\n self.lineEdit_r8.hide()\n self.toolButton_r8.hide()\n\n ########################\n\n self.horizontalLayout_8.addWidget(self.toolButton_r8)\n self.gridLayout_3.addLayout(self.horizontalLayout_8, 11, 0, 1, 1)\n self.horizontalLayout_12 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_12.setObjectName(\"horizontalLayout_12\")\n spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_12.addItem(spacerItem)\n self.pushButton_plus = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n self.pushButton_plus.setMinimumSize(QtCore.QSize(20, 0))\n self.pushButton_plus.setMaximumSize(QtCore.QSize(40, 16777215))\n self.pushButton_plus.setObjectName(\"pushButton_plus\")\n self.pushButton_plus.setText(\"+\")\n self.pushButton_plus.clicked.connect(self.plus)\n\n self.horizontalLayout_12.addWidget(self.pushButton_plus)\n self.pushButton_moins = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n self.pushButton_moins.setMaximumSize(QtCore.QSize(40, 16777215))\n self.pushButton_moins.setObjectName(\"pushButton_moins\")\n self.pushButton_moins.setText(\"-\")\n self.pushButton_moins.clicked.connect(self.moins)\n self.horizontalLayout_12.addWidget(self.pushButton_moins)\n self.gridLayout_3.addLayout(self.horizontalLayout_12, 12, 0, 1, 1)\n self.horizontalLayout_3 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_3.setObjectName(\"horizontalLayout_3\")\n spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_3.addItem(spacerItem1)\n self.pushButton_next1 = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n self.pushButton_next1.setMaximumSize(QtCore.QSize(16777215, 16777215))\n self.pushButton_next1.setObjectName(\"pushButton_next1\")\n self.pushButton_next1.setText(\"Next\")\n self.pushButton_next1.clicked.connect(self.buttonClicked_newAnalyse_etape2)\n self.horizontalLayout_3.addWidget(self.pushButton_next1)\n self.gridLayout_3.addLayout(self.horizontalLayout_3, 13, 0, 1, 1)\n self.scrollArea.setWidget(self.scrollAreaWidgetContents)\n self.gridLayout.addWidget(self.scrollArea, 0, 1, 1, 1)\n MainWindow.setCentralWidget(self.centralwidget)\n\n #Fonction qui ajoute le texte sur les éléments de la fenetre princiale (= menu a gauche)\n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"MainWindow\"))\n self.label_titre.setText(_translate(\"MainWindow\", \"

    Andalusian Mapping

    \"))\n self.pushButton_acceuil.setText(_translate(\"MainWindow\", \"Accueil\"))\n self.pushButton_newAnalyse.setText(_translate(\"MainWindow\", \"Nouvelle analyse\"))\n self.pushButton_oldAnalise.setText(_translate(\"MainWindow\", \"Charger une analyse\"))\n self.pushButton_resultat.setText(_translate(\"MainWindow\", \"Résultats\"))\n self.pushButton_author.setText(_translate(\"MainWindow\", \"About - Author\"))\n\n ######################################################################\n # #\n # Boucle principale du programmme #\n # #\n ######################################################################\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n MainWindow = QtWidgets.QMainWindow()\n ui = Ui_MainWindow()\n ui.setupUi(MainWindow)\n MainWindow.show()\n sys.exit(app.exec_())\n","sub_path":"Code/Interface Graphique/mainSA_testRunDocker.py","file_name":"mainSA_testRunDocker.py","file_ext":"py","file_size_in_byte":87509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"237801283","text":"import os\nimport math\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfrom sklearn.model_selection import train_test_split, StratifiedKFold\n\nfrom tensorflow.keras.models import Model, load_model\nfrom tensorflow.keras.layers import Input, Dense, Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization, Activation\nfrom tensorflow.keras.layers import GlobalAveragePooling2D, ZeroPadding2D, Add\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\n\nfrom tensorflow.keras.optimizers import Adam\n\n# 1. 데이터\ntrain_data = pd.read_csv(\"./dacon2/data/train.csv\", index_col=0, header=0)\nprint(train_data)\n\n'''\n# 그림 확인\nidx = 999\nimg = train_data.loc[idx, '0':].values.reshape(28, 28).astype(int)\ndigit = train_data.loc[idx, 'digit']\nletter = train_data.loc[idx, 'letter']\nplt.title('Index: %i, Digit: %s, Letter: %s'%(idx, digit, letter))\nplt.imshow(img)\nplt.show()\n'''\n\ntrain_digit = train_data['digit'].values\ntrain_letter = train_data['letter'].values\n\nx_train = train_data.drop(['digit', 'letter'], axis=1).values\nx_train = x_train.reshape(-1, 28, 28, 1)\nx_train = x_train/255\n\ny = train_data['digit']\ny_train = np.zeros((len(y), len(y.unique())))\nfor i, digit in enumerate(y):\n y_train[i, digit] = 1\n\nprint(x_train.shape, y_train.shape) # (2048, 28, 28, 1) (2048, 10)\n\n# x_train, x_val, y_train, y_val = train_test_split(x_train, y_train, test_size=0.1, stratify=y_train)\n\ndatagen = ImageDataGenerator(\n width_shift_range=(-1,1), \n height_shift_range=(-1,1))\n\ndatagen2 = ImageDataGenerator()\n\nsteps = 40\nskfold = StratifiedKFold(n_splits=steps, random_state=42, shuffle=True)\n\n# 2. 모델\n# number of classes\nK = 10\n\ninput_tensor = Input(shape=x_train.shape[1:])\n\ndef conv1_layer(x):\n x = ZeroPadding2D(padding=(3,3))(x)\n x = Conv2D(64, (7,7), strides=(2,2))(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n x = ZeroPadding2D(padding=(1,1))(x)\n\n return x\n\ndef conv2_layer(x):\n x = MaxPooling2D((3,3),2)(x)\n\n shortcut = x\n\n for i in range(3):\n if (i == 0):\n x = Conv2D(64, (1,1), strides=(1,1), padding='valid')(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n\n x = Conv2D(64, (3,3), strides=(1,1), padding='same')(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n\n x = Conv2D(256, (1,1), strides=(1,1), padding='valid')(x)\n shortcut = Conv2D(256, (1,1), strides=(1,1), padding='valid')(shortcut)\n\n x = BatchNormalization()(x)\n shortcut = BatchNormalization()(shortcut)\n\n x = Add()([x, shortcut])\n x = Activation('relu')(x)\n\n shortcut = x\n \n else:\n x = Conv2D(64, (1,1), strides=(1,1), padding='valid')(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n\n x = Conv2D(64, (3,3), strides=(1,1), padding='same')(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n\n x = Conv2D(256, (1,1), strides=(1,1), padding='valid')(x)\n x = BatchNormalization()(x)\n\n x = Add()([x, shortcut])\n x = Activation('relu')(x)\n\n shortcut = x\n\n return x\n\ndef conv3_layer(x):\n shortcut = x\n\n for i in range(4):\n if (i == 0):\n x = Conv2D(128, (1,1), strides=(2,2), padding='valid')(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n\n x = Conv2D(128, (3,3), strides=(1,1), padding='same')(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n\n x = Conv2D(512, (1,1), strides=(1,1), padding='valid')(x)\n shortcut = Conv2D(512, (1,1), strides=(2,2), padding='valid')(shortcut)\n x = BatchNormalization()(x)\n shortcut = BatchNormalization()(shortcut)\n\n x = Add()([x, shortcut])\n x = Activation('relu')(x)\n\n shortcut = x\n\n else:\n x = Conv2D(128, (1,1), strides=(1,1), padding='valid')(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n\n x = Conv2D(128, (3,3), strides=(1,1), padding='same')(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n\n x = Conv2D(512, (1,1), strides=(1,1), padding='valid')(x)\n x = BatchNormalization()(x)\n\n x = Add()([x, shortcut])\n x = Activation('relu')(x)\n\n shortcut = x\n\n return x\n\ndef conv4_layer(x):\n shortcut = x\n\n for i in range(6):\n if (i == 0):\n x = Conv2D(256, (1,1), strides=(2,2), padding='valid')(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n\n x = Conv2D(256, (3,3), strides=(1,1), padding='same')(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n\n x = Conv2D(1024, (1,1), strides=(1,1), padding='valid')(x)\n shortcut = Conv2D(1024, (1,1), strides=(2,2), padding='valid')(shortcut)\n x = BatchNormalization()(x)\n shortcut = BatchNormalization()(shortcut)\n\n x = Add()([x, shortcut])\n x = Activation('relu')(x)\n\n shortcut = x\n\n else:\n x = Conv2D(256, (1,1), strides=(1,1), padding='valid')(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n\n x = Conv2D(256, (3,3), strides=(1,1), padding='same')(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n\n x = Conv2D(1024, (1,1), strides=(1,1), padding='valid')(x)\n x = BatchNormalization()(x)\n\n x = Add()([x, shortcut])\n x = Activation('relu')(x)\n\n shortcut = x\n\n return x\n\ndef conv5_layer(x):\n shortcut = x\n\n for i in range(3):\n if (i == 0):\n x = Conv2D(512, (1,1), strides=(2,2), padding='valid')(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n\n x = Conv2D(512, (3,3), strides=(1,1), padding='same')(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n\n x = Conv2D(2048, (1,1), strides=(1,1), padding='valid')(x)\n shortcut = Conv2D(2048, (1,1), strides=(2,2), padding='valid')(shortcut)\n x = BatchNormalization()(x)\n shortcut = BatchNormalization()(shortcut)\n\n x = Add()([x, shortcut])\n x = Activation('relu')(x)\n\n shortcut = x\n\n else:\n x = Conv2D(512, (1,1), strides=(1,1), padding='valid')(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n\n x = Conv2D(512, (3,3), strides=(1,1), padding='same')(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n\n x = Conv2D(2048, (1,1), strides=(1,1), padding='valid')(x)\n x = BatchNormalization()(x)\n\n x = Add()([x, shortcut])\n x = Activation('relu')(x)\n\n shortcut = x\n\n return x\n \nx = conv1_layer(input_tensor) \nx = conv2_layer(x)\nx = conv3_layer(x)\nx = conv4_layer(x)\nx = conv5_layer(x)\n\n# error 잡기\n\nx = GlobalAveragePooling2D()(x)\noutput_tensor = Dense(K, activation='softmax')(x)\n\nresnet50 = Model(inputs=input_tensor, outputs=output_tensor)\n\nresnet50.summary()\n\nval_acc = []\nfor i, (train_idx, val_idx) in enumerate(skfold.split(x_train, y_train.argmax(1))):\n x_train_, x_val_ = x_train[train_idx], x_train[val_idx]\n y_train_, y_val_ = y_train[train_idx], y_train[val_idx]\n \n model = resnet50(x_train)\n\n filepath = './dacon2/data/vision_model_{}.hdf5'.format(i)\n es = EarlyStopping(monitor='val_loss', patience=160, mode='auto')\n cp = ModelCheckpoint(filepath=filepath, monitor='val_loss', save_best_only=True, mode='auto')\n lr = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=100)\n\n model.compile(loss='categorical_crossentropy', optimizer=Adam(lr=0.002, epsilon=None), metrics=['accuracy'])\n hist = model.fit_generator(datagen.flow(x_train_, y_train_, batch_size=32), epochs=2000,\n validation_data=(datagen.flow(x_val_, y_val_)), verbose=2, callbacks=[es, cp, lr])\n\n val_acc.append(max(hist.history['val_accuracy']))\n\n print('{}\\'s CV End'.format(i+1))\n\n# 3. 예측\ntest_data = pd.read_csv('./dacon2/data/test.csv', index_col=0, header=0)\nx_test = test_data.drop(['letter'], axis=1).values\nx_test = x_test.reshape(-1, 28, 28, 1)\nx_test = x_test/255\n\n# best model select\nprint(val_acc)\n\ni_max = np.argmax(val_acc)\n\nprint('Best Model is {}\\'s'.format(i_max))\nmodel = load_model('./dacon2/data/vision_model_{}.hdf5'.format(i_max))\n\nsubmission = pd.read_csv('./dacon2/data/submission.csv', index_col=0, header=0)\n\nsubmission['digit'] = np.argmax(model.predict(x_test), axis=1)\nprint(submission)\n\nsubmission.to_csv('./dacon2/data/submission_model_best.csv')\n\n\n# KFold 값 평균내기\nsubmission2 = pd.read_csv('./dacon2/data/submission.csv', index_col=0, header=0)\n\nresult = 0\nfor i in range(steps):\n model = load_model('./dacon2/data/vision_model_{}.hdf5'.format(i))\n\n result += model.predict_generator(datagen2.flow(x_test, shuffle=False)) / steps\n\nsubmission2['digit'] = result.argmax(1)\n\nprint(submission2)\nsubmission2.to_csv('./dacon2/data/submission_model_mean.csv')\n","sub_path":"dacon2/vision_4_resnet50.py","file_name":"vision_4_resnet50.py","file_ext":"py","file_size_in_byte":9474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"280540365","text":"import os, gridfs, pika, json\nfrom flask import Flask, request\nfrom flask_pymongo import PyMongo\nfrom auth import validate\nfrom auth_svc import access\nfrom storage import util\n\nserver = Flask(__name__)\nserver.config[\"MONGO_URI\"] = \"mongodb://host.minikube.internal:27017/videos\"\n\nmongo = PyMongo(server)\n\nfs = gridfs.GridFS(mongo.db)\n\nconnection = pika.BlockingConnection(pika.ConnectionParameters(\"rabbitmq\"))\nchannel = connection.channel()\n\n@server.route(\"/login\", methods=[\"POST\"])\ndef login():\n token, err = access.login(request)\n if not err:\n return token\n else:\n return err\n\n@server.route(\"/upload\", methods=[\"POST\"])\ndef upload():\n access, err = validate.token(request)\n access = json.loads(access)\n if access[\"admin\"]:\n if len(request.files) > 1 or len(request.files) < 1:\n return \"exactly 1 file required\", 400\n for _, f in request.files.items():\n err = util.upload(f, fs, channel, access)\n if err:\n return err\n return \"success!\", 200\n else:\n return \"not authorized\", 401\n\n@server.route(\"/download\", methods=[\"GET\"])\ndef download():\n pass\n\nif __name__ == \"__main__\":\n server.run(host=\"0.0.0.0\", port=8080)\n","sub_path":"demo-projects/python-k8s-microservice/src/gateway/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"454385501","text":"class NumArray(object):\n def __init__(self, nums):\n \"\"\"\n initialize your data structure here.\n :type nums: List[int]\n \"\"\"\n self.A = [0]*(len(nums)+1)\n for i in range(0, len(nums)):\n self.A[i+1]=self.A[i]+nums[i]\n \n \n\n def sumRange(self, i, j):\n \"\"\"\n sum of elements nums[i..j], inclusive.\n :type i: int\n :type j: int\n :rtype: int\n \"\"\"\n return self.A[j+1]-self.A[i]\n\n \n# class NumArray(object):\n# def __init__(self, nums):\n# \"\"\"\n# initialize your data structure here.\n# :type nums: List[int]\n# \"\"\"\n# n = len(nums)\n# if n == 0:\n# return\n# self.A = [ [0]*n for _ in range(n) ]\n# self.A[0][0] = nums[0]\n# for j in range(1, n) :\n# for i in range(0, j+1):\n# self.A[i][j] = self.A[i][j-1]+nums[j]\n\n\n# def sumRange(self, i, j):\n# \"\"\"\n# sum of elements nums[i..j], inclusive.\n# :type i: int\n# :type j: int\n# :rtype: int\n# \"\"\"\n# return self.A[i][j]\n\n\n\n\n# Your NumArray object will be instantiated and called as such:\nnums = [-2,0,3,-5,2,-1]\nnumArray = NumArray(nums)\nprint(numArray.sumRange(0, 2))\nprint(numArray.sumRange(2, 5))\nprint(numArray.sumRange(0, 5))","sub_path":"leetcode/301-350/303.Range_Sum_Query_Immutable.py","file_name":"303.Range_Sum_Query_Immutable.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"427390033","text":"import math\nimport helpers\nimport Log\ncomment = \"\"\n\ndef create(log):\n\n log.level2(\"Creating comment header\")\n\n length = len(comment)\n numLines = 0\n if(length > 0):\n numLines = int(math.ceil(length / 79.0))\n\n ret = helpers.limitAndPad(helpers.limitAndPad(numLines, 4) +\n (\" Comment line(s) follow, each starting \"\n \"with a \\\"|\\\"\"), 80)\n ret += \"\\n\"\n\n for x in range(0, numLines):\n ret += \"|\" + comment[x * 79: (x + 1) * 79] + \"\\n\"\n\n log.level2(\"Comment header created\")\n\n return ret\n","sub_path":"commentheader.py","file_name":"commentheader.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"92227093","text":"# Building a Chatbot with Deep NLP\n# import lib\nimport numpy as np\nimport tensorflow as tf\nimport re\nimport time\nimport os\n\n\n## Data preprocessing ##\n# Import dataset\nfilePath = 'cornell_movie_dialogs_corpus'\nlines = open(os.path.join(filePath,'movie_lines.txt'),encoding='utf-8',errors='ignore').read().split('\\n')\nconversations = open(os.path.join(filePath,'movie_conversations.txt'),encoding='utf-8',errors='ignore').read().split('\\n')\n\n# Build dictionary to connet the output and input.\nid2line = {}\nfor line in lines:\n _line = line.split(' +++$+++ ')\n if len(_line)==5:\n id2line[_line[0]] = _line[4]\n\n# Create a list of conversation\nconversations_ids = []\nfor conversation in conversations[:-1]:\n _conversation = conversation.split(' +++$+++ ')[-1][1:-1].replace(\"'\",\"\").replace(\" \",\"\")\n conversations_ids.append(_conversation.split(','))\n\n# Getting separately the questions and the answers\nquestions = []\nanswers = []\n\nfor conversation in conversations_ids:\n for i in range(len(conversation)-1):\n questions.append(id2line[conversation[i]])\n answers.append(id2line[conversation[i+1]])\n\n\n# Clean function of the texts\n\ndef clean_text(text):\n text = text.lower()\n text = re.sub(r\"i'm\", \"i am\",text)\n text = re.sub(r\"he's\", \"he is\",text)\n text = re.sub(r\"she's\", \"she is\",text)\n text = re.sub(r\"she's\", \"she is\",text)\n text = re.sub(r\"that's\", \"that is\",text)\n text = re.sub(r\"what's\", \"what is\",text)\n text = re.sub(r\"where's\", \"where is\",text)\n text = re.sub(r\"\\'ll\", \" will\",text)\n text = re.sub(r\"\\'ve\", \" have\",text)\n text = re.sub(r\"\\'d\", \" would\",text)\n text = re.sub(r\"\\'re\", \" are\",text)\n text = re.sub(r\"won't\", \"will not\",text)\n text = re.sub(r\"can't\", \"cannot\",text)\n text = re.sub(r\"!\", \" !\",text)\n text = re.sub(r\"[\\-\\(\\)\\\"\\#\\/\\@\\;\\:\\<\\>\\{\\}\\+\\=\\-\\|\\.\\?\\,]\", \"\",text)\n return text\n# print(clean_text(questions[0]))\n# Clean the questions and the answers\ncleaned_questions = list(map(clean_text,questions))\ncleaned_answers = list(map(clean_text,answers))\n\n\n# Remove the non-frequent words\nword2cnt = {}\nfor question in cleaned_questions:\n for word in question.split():\n word2cnt[word] = word2cnt.get(word,0)+1\nfor ans in cleaned_answers:\n for word in ans.split():\n word2cnt[word] = word2cnt.get(word,0)+1\n\n### Make two indepedent dictionaries still because the questions and the answers \n### cannot be of different threshold values.\nthreshold = 20\nquestionsword2int = {}\nword_num = 0\nfor word,cnt in word2cnt.items():\n if cnt>=threshold:\n questionsword2int[word] = word_num\n word_num+=1\nanswersword2int = {}\nword_num = 0\nfor word,cnt in word2cnt.items():\n if cnt>=threshold:\n answersword2int[word] = word_num\n word_num+=1\n\n# Adding the last tokens to these two dictionaries.\ntokens = ['','','',''] \n# Padding, end of sentence, out of vocabulary, start of string\nfor token in tokens:\n questionsword2int[token] = len(questionsword2int)\n answersword2int[token] = len(answersword2int)\n\n","sub_path":"chatbot.py","file_name":"chatbot.py","file_ext":"py","file_size_in_byte":3064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"488875818","text":"# Реализовать решение следующей задачи: \n# «Есть два писателя, которые по очереди в течении определенного времени (у каждого разное) \n# пишут в одну книгу. Данная книга очень популярна, у неё есть как минимум 3 фаната (читателя), \n# которые ждут не дождутся, чтобы прочитать новые записи из неё. Каждый читатель и писатель – \n# отдельный поток. Одновременно книгу может читать несколько читателей, но писать единовременно \n# может только один писатель.»\n\n\nimport threading\nimport random\nimport time\n\nbook = ''\nmutex = threading.Lock()\n\n\ndef writing(timer, name):\n '''\n Функция в которой генерируется рандомный символ и последовательно\n с интервалом в 0.5 с добавляется в глобальную переменную book;\n потоки работают с методом Lock\n '''\n global book \n mutex.acquire()\n for i in range(timer*2): \n symbol = chr(random.randint(65,90)).lower()\n print(f'{name} пишет: {symbol}')\n book += symbol\n time.sleep(0.5)\n print(f'Книга содержит следующий текст:{book}')\n mutex.release() \n\n\ndef reading(name, timer):\n '''\n функция прочтения\n '''\n while True:\n time.sleep(timer)\n print(f'{name} читает: {book}')\n\n\nif __name__ == \"__main__\":\n def iter_writing(iter): \n '''\n Количество итераций написания-прочтения текстов всеми лицами;\n '''\n for i in range(iter):\n time_of_writing_writer1 = 1\n time_of_writing_writer2 = 2\n\n flow_writer1 = threading.Thread(target=writing, args=(time_of_writing_writer1,\n 'Писатель_1')) \n flow_writer2 = threading.Thread(target=writing, args=(time_of_writing_writer2, \n 'Писатель_2'))\n reader1 = threading.Thread(target = reading, args = ('Читатель1', 3))\n reader2 = threading.Thread(target = reading, args = ('Читатель2', 5))\n reader3 = threading.Thread(target = reading, args = ('Читатель3', 2))\n\n reader1.daemon = True\n reader2.daemon = True\n reader3.daemon = True\n \n flow_writer1.start()\n flow_writer2.start()\n reader1.start()\n reader2.start()\n reader3.start()\n \n flow_writer1.join()\n flow_writer2.join()\n reader1.join(0)\n reader2.join(0)\n reader2.join(0)\n\n\n iteration_wr = 2\n iter_writing(iteration_wr)\n\n\n# «Пять безмолвных философов сидят вокруг круглого стола, перед каждым философом стоит \n# тарелка спагетти. Вилки лежат на ��толе между каждой парой ближайших философов. \n# Каждый философ может либо есть, либо размышлять. Прием пищи не ограничен количеством \n# оставшихся спагетти — подразумевается бесконечный запас. Тем не менее, философ может \n# есть только тогда, когда держит две вилки — взятую справа и слева (альтернативная \n# формулировка проблемы подразумевает миски с рисом и палочки для еды вместо тарелок \n# со спагетти и вилок). Каждый философ может взять ближайшую вилку (если она доступна) \n# или положить — если он уже держит её. Взятие каждой вилки и возвращение её на стол \n# являются раздельными действиями, которые должны выполняться одно за другим. Вопрос \n# задачи заключается в том, чтобы разработать модель поведения (параллельный алгоритм), \n# при котором ни один из философов не будет голодать, то есть будет вечно чередовать \n# приём пищи и размышления.»\nimport threading\nimport time\n\n\nclass acquire(object):\n def __init__(self, *locks):\n self.locks = sorted(locks, key=lambda x: id(x))\n\n def __enter__(self):\n for lock in self.locks:\n lock.acquire()\n\n def __exit__(self, ty, val, tb):\n for lock in reversed(self.locks):\n lock.release()\n return False\n\n\ndef philosopher(left, right):\n while True:\n with acquire(left,right): \n time.sleep(0.5) \n print(f'Philosopher at {threading.currentThread()} is eating.')\n\n\nN_FORKS = 5\nforks = [threading.Lock() for n in range(N_FORKS)]\n\n\nphils = [threading.Thread(\n target=philosopher,\n args=(forks[n], forks[(n + 1) % N_FORKS])\n) for n in range(N_FORKS)]\n\n\nfor p in phils:\n p.start()","sub_path":"Part_1/Lesson_11/hw11.py","file_name":"hw11.py","file_ext":"py","file_size_in_byte":5701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"195651262","text":"import math\ndef sirPatrate(limita):\n return [numar*numar for numar in range(0,limita) if numar*numar < limita]\n\n\ndef sumaPatrate(numar):\n patrate = sirPatrate(numar)\n for a in patrate:\n for b in patrate:\n for c in patrate:\n for d in patrate:\n if(a+b+c+d == numar):\n return (patrate.index(a),patrate.index(b),patrate.index(c),patrate.index(d))","sub_path":"Algoritmica/Tema1/ApostolIonutMihai_IA_sgr1_Tema1_Pb2b.py","file_name":"ApostolIonutMihai_IA_sgr1_Tema1_Pb2b.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"357597969","text":"import random\nimport string\n\nfrom experimentApp.models import ExperimentSlug, ExperimentCustomColours, ExperimentRefresher\n\n\n# Helper function to save generic details about experiment and options that are present in all types of experiments\ndef saveExperimentInstance(request, experimentForm, experiment_type, question_type):\n\n # Save Experiment model\n experimentInstance = experimentForm.save(commit=False)\n experimentInstance.experiment_type = experiment_type\n experimentInstance.question_type = question_type\n experimentInstance.save()\n\n # Generates and saves experiment slug\n experimentSlug = generateUniqueSlug()\n ExperimentSlug.objects.create(experiment=experimentInstance, slug=experimentSlug)\n\n # Save custom colour options\n if request.POST.get(\"customColours\"):\n ExperimentCustomColours.objects.create(experiment=experimentInstance,\n text_colour=request.POST.get(\"textColourPicker\"),\n background_colour=request.POST.get(\"backgroundColourPicker\"))\n\n # Save refresher options\n if request.POST.get(\"radRef\"):\n time_shown = request.POST.get(\"timeVal\")\n if request.POST.get(\"refChoice\") == \"col\":\n custom_colour = request.POST.get(\"colourpicker\")\n ExperimentRefresher.objects.create(experiment=experimentInstance,\n time_shown=time_shown, custom_colour=custom_colour,\n custom_image=None)\n else:\n custom_image = request.FILES.get(\"refImage\")\n ExperimentRefresher.objects.create(experiment=experimentInstance,\n time_shown=time_shown, custom_colour=\"\",\n custom_image=custom_image)\n\n return experimentInstance, experimentSlug\n\n\n# Given list of files, generates new list of tuples where each tuple contains all files with same\n# prefix before a '_'\ndef sortInputFiles(oldFileList, newFileList):\n if len(oldFileList) == 0:\n return newFileList\n\n file = oldFileList[0]\n file_list = [file]\n oldFileList.remove(file)\n file_prefix = file.name.split('_')[0]\n\n for f in list(reversed(oldFileList)):\n f_prefix = f.name.split('_')[0]\n if file_prefix == f_prefix:\n oldFileList.remove(f)\n file_list.append(f)\n\n newFileList.append(file_list)\n n = sortInputFiles(oldFileList, newFileList)\n return n\n\n\ndef sortInputDirs(request):\n\n fileList = []\n dir_counter = 0\n while True:\n # If we have reached the end of file uploads\n if not ('uploadDir' + str(dir_counter)) in request.FILES:\n break\n else:\n files = request.FILES.getlist('uploadDir' + str(dir_counter))\n fileList.append(files)\n dir_counter += 1\n\n return fileList\n\n\n# Generates random 5 letter string of lower+uppercase letters, checks that it is unique with all other\n# experiment slugs\ndef generateUniqueSlug():\n\n while True:\n slug = ''.join(random.choices(string.ascii_letters, k=5))\n if not ExperimentSlug.objects.filter(slug=slug).exists():\n break\n\n return slug\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"60528885","text":"#@PydevCodeAnalysisIgnore # pylint: disable-all\nfrom cing import __author__\nfrom cing.Libs.NTutils import * #@UnusedWildImport\nfrom cing.PluginCode.required.reqAnalysis import * #@UnusedWildImport\nfrom cing.PluginCode.required.reqCcpn import * #@UnusedWildImport\n#from nose.plugins.skip import SkipTest\n\n__author__ += 'Tim Stevens '\n\nif True: # for easy blocking of data, preventing the code to be resorted with imports above.\n switchOutput(False)\n try:\n # pylint: disable=E0611\n from ccpnmr.analysis.Version import version #@UnusedImport @UnresolvedImport\n from ccpnmr.analysis.core.ExperimentBasic import getThroughSpacePeakLists #@UnusedImport IS used. @UnresolvedImport\n from ccpnmr.analysis.Analysis import Analysis as AnalysisApp #@UnresolvedImport\n # The defs below are not moved into this module so that Analysis and CING both have access to them.\n # Analysis can't import any cing code.\n from cing.Scripts.Analysis.PyRPF import * #@UnusedWildImport\n # pylint: enable E0611\n except:\n switchOutput(True)\n raise ImportWarning(ANALYSIS_STR)\n# raise SkipTest(ANALYSIS_STR) \n finally: # finally fails in python below 2.5\n switchOutput(True)\n# nTdebug('Imported plugin Analysis version %s' % version)\n\nclass Analysis:\n \"\"\"\n Adds Analysis functionality.\n \"\"\"\n def __init__(self, project):\n self.project = project\n self.app = None # Do explicit initAnalysis\n\n def initAnalysis(self):\n \"\"\"Required to execute this routine\n Returns True on failure.\n \"\"\"\n try:\n self.app = AnalysisApp(64) # Number is an arbitrary cache size\n if not self.app:\n nTerror(\"Analysis failed to start the non-GUI version.\")\n return True\n self.app.initProject(self.project)\n except:\n nTexception(format_exc())\n nTerror(\"Analysis crashed when starting the non-GUI version\")\n return True\n\n def runRpf(self,\n doAlised=DEFAULT_CONSIDER_ALIASED_POSITIONS,\n distThreshold=DEFAULT_DISTANCE_THRESHOLD,\n prochiralExclusion=DEFAULT_PROCHIRAL_EXCLUSION_SHIFT,\n diagonalExclusion=DEFAULT_DIAGONAL_EXCLUSION_SHIFT\n ):\n \"\"\"\n Return None on error.\n It's not an error to have no peak list.\n\n If pyRpf crashes the exception will be propagated up from here.\n \"\"\"\n\n nTmessage(\"Starting cing.PluginCode.Analysis#runRpf\")\n\n if not hasattr(self.project, CCPN_LOWERCASE_STR):\n# nTdebug(\"Failed to find ccpn attribute project. Happens when no CCPN project was read first.\") # TODO: change when cing to ccpn code works.\n return\n # end if\n self.ccpnProject = self.project[ CCPN_LOWERCASE_STR ]\n ccpnProject = self.ccpnProject\n if not ccpnProject:\n nTmessage(\"Failed to find ccpn project.\")\n return\n\n # Find and print this peakList in the CCPN data model.\n peakLists = getThroughSpacePeakLists(ccpnProject)\n if not peakLists:\n nTwarning(\"No peak list found; skipping runRpf\")\n return\n nTmessage( 'Peaklists: [%s]' % peakLists )\n\n# peakLists = [pl for pl in self.peakListTable.objectList if pl.rpfUse]\n# ensembles = [e for e in self.ensembleTable.objectList if e.rpfUse]\n ensembles = getEnsembles(ccpnProject)\n if not ensembles:\n nTwarning(\"No ensemble found; skipping runRpf\")\n return\n\n for ensemble in ensembles:\n nTdebug(\"Using ensemble: %s \" % str(ensemble))\n ensemble.rpfUse = True # set the selection automatically.\n # end for\n\n tolerances = []\n for peakList in peakLists:\n try:\n tolerance = getNoeTolerances(peakList)\n except:\n nTexception(format_exc())\n nTerror(\"Analysis: Crashed on getNoeTolerances and unknown how to be taking default tolerances.\")\n return\n\n\n tolerances.append(tolerance)\n nTdebug(\"Using peakList.dataSource.name: %s with tolerance: %s\" % (peakList.dataSource.name,str(tolerance)))\n# peakList[RPF_USE] = True # set the selection automatically.\n peakList.rpfUse = True # set the selection automatically.\n # end for\n\n #Instead of polluting the RPF code simply prevent it from crashing CING by wrapping the functionality in a try block.\n validResultStores = calcRPF(ensembles, peakLists,\n tolerances,\n distThreshold,\n prochiralExclusion,\n diagonalExclusion,\n doAlised,\n verbose=cing.verbosity==cing.verbosityDebug)\n# self.updateResultsTable()\n nTdebug(\"validResultStores: %s\" % str(validResultStores))\n return validResultStores\n # end def\n# end class\n\ndef runRpf(project,\n doAlised=DEFAULT_CONSIDER_ALIASED_POSITIONS,\n distThreshold=DEFAULT_DISTANCE_THRESHOLD,\n prochiralExclusion=DEFAULT_PROCHIRAL_EXCLUSION_SHIFT,\n diagonalExclusion=DEFAULT_DIAGONAL_EXCLUSION_SHIFT\n ):\n '''Descrn: Will run pyRpf without allowing it to crash CING.\n Inputs:\n If pyRpf crashes this routine will catch and show the exception.\n '''\n analysis = Analysis(project=project)\n try:\n if not analysis.runRpf(\n doAlised=doAlised,\n distThreshold=distThreshold,\n prochiralExclusion=prochiralExclusion,\n diagonalExclusion=diagonalExclusion\n ):\n nTerror(\"Analysis: Failed runRpf\")\n return None\n except:\n nTexception(format_exc())\n nTerror(\"Analysis: Crashed on runRpf\")\n return None\n return project\n\n# register the function\nmethods = [ (runRpf, None),\n ]\n","sub_path":"python/cing/PluginCode/Analysis.py","file_name":"Analysis.py","file_ext":"py","file_size_in_byte":6135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"344544105","text":"# -*- coding: utf-8 -*-\nu\"\"\"Flask routes\n\n:copyright: Copyright (c) 2015 RadiaSoft LLC. All Rights Reserved.\n:license: http://www.apache.org/licenses/LICENSE-2.0.html\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\nfrom pykern import pkcollections\nfrom pykern import pkconfig\nfrom pykern import pkio\nfrom pykern.pkdebug import pkdc, pkdexc, pkdlog, pkdp\nfrom sirepo import feature_config\nfrom sirepo import runner\nfrom sirepo import simulation_db\nfrom sirepo import util\nfrom sirepo import uri_router\nfrom sirepo.template import template_common\nimport beaker.middleware\nimport datetime\nimport flask\nimport flask.sessions\nimport glob\nimport os\nimport os.path\nimport py.path\nimport re\nimport sirepo.template\nimport sys\nimport time\nimport werkzeug\nimport werkzeug.exceptions\n\n#TODO(pjm): this import is required to work-around template loading in listSimulations, see #1151\nif any(k in feature_config.cfg.sim_types for k in ('rs4pi', 'warppba', 'warpvnd')):\n import h5py\n\n#: where users live under db_dir\n_BEAKER_DATA_DIR = 'beaker'\n\n#: where users live under db_dir\n_BEAKER_LOCK_DIR = 'lock'\n\n#: Relative to current directory only in test mode\n_DEFAULT_DB_SUBDIR = 'run'\n\n#: What's the key in environ for the session\n_ENVIRON_KEY_BEAKER = 'beaker.session'\n\n#: Cache for _json_response_ok\n_JSON_RESPONSE_OK = None\n\n#: class that py.path.local() returns\n_PY_PATH_LOCAL_CLASS = type(pkio.py_path())\n\n#: What is_running?\n_RUN_STATES = ('pending', 'running')\n\n#: Identifies the user in the Beaker session\n_SESSION_KEY_USER = 'uid'\n\n#: Parsing errors from subprocess\n_SUBPROCESS_ERROR_RE = re.compile(r'(?:warning|exception|error): ([^\\n]+?)(?:;|\\n|$)', flags=re.IGNORECASE)\n\n#: Identifies the user in uWSGI logging (read by uwsgi.yml.jinja)\n_UWSGI_LOG_KEY_USER = 'sirepo_user'\n\n#: See sirepo.sr_unit\nSR_UNIT_TEST_IN_REQUEST = 'test_in_request'\n\n#: WSGIApp instance (see `init_by_server`)\n_wsgi_app = None\n\n#: Default file to serve on errors\nDEFAULT_ERROR_FILE = 'server-error.html'\n\n# Default response\n_RESPONSE_OK = {'state': 'ok'}\n\n#: Flask app instance, must be bound globally\napp = flask.Flask(\n __name__,\n static_folder=str(simulation_db.STATIC_FOLDER),\n template_folder=str(simulation_db.STATIC_FOLDER),\n)\napp.config.update(\n PROPAGATE_EXCEPTIONS=True,\n)\n\ndef api_blueskyAuth():\n from sirepo import bluesky\n\n req = _json_input()\n bluesky.auth_login(req)\n return _json_response_ok(dict(\n data=simulation_db.open_json_file(req.simulationType, sid=req.simulationId),\n schema=simulation_db.get_schema(req.simulationType),\n ))\n\n\ndef api_copyNonSessionSimulation():\n req = _json_input()\n sim_type = req['simulationType']\n src = py.path.local(simulation_db.find_global_simulation(\n sim_type,\n req['simulationId'],\n checked=True,\n ))\n data = simulation_db.open_json_file(\n sim_type,\n src.join(simulation_db.SIMULATION_DATA_FILE),\n )\n data['models']['simulation']['isExample'] = False\n data['models']['simulation']['outOfSessionSimulationId'] = req['simulationId']\n res = _save_new_and_reply(data)\n target = simulation_db.simulation_dir(sim_type, simulation_db.parse_sid(data))\n template_common.copy_lib_files(\n data,\n simulation_db.lib_dir_from_sim_dir(src),\n simulation_db.lib_dir_from_sim_dir(target),\n )\n template = sirepo.template.import_module(data)\n if hasattr(template, 'copy_related_files'):\n template.copy_related_files(data, str(src), str(target))\n return res\n\napp_copy_nonsession_simulation = api_copyNonSessionSimulation\n\n\ndef api_copySimulation():\n \"\"\"Takes the specified simulation and returns a newly named copy with the suffix (copy X)\"\"\"\n req = _json_input()\n sim_type = req['simulationType']\n name = req['name'] if 'name' in req else None\n folder = req['folder'] if 'folder' in req else '/'\n data = simulation_db.read_simulation_json(sim_type, sid=req['simulationId'])\n if not name:\n base_name = data['models']['simulation']['name']\n names = simulation_db.iterate_simulation_datafiles(sim_type, _simulation_name)\n count = 0\n while True:\n count += 1\n name = base_name + ' (copy{})'.format(' {}'.format(count) if count > 1 else '')\n if name in names and count < 100:\n continue\n break\n data['models']['simulation']['name'] = name\n data['models']['simulation']['folder'] = folder\n data['models']['simulation']['isExample'] = False\n data['models']['simulation']['outOfSessionSimulationId'] = ''\n return _save_new_and_reply(data)\napp_copy_simulation = api_copySimulation\n\n\ndef api_deleteFile():\n req = _json_input()\n filename = werkzeug.secure_filename(req['fileName'])\n search_name = _lib_filename(req['simulationType'], filename, req['fileType'])\n err = _simulations_using_file(req['simulationType'], req['fileType'], search_name)\n if len(err):\n return _json_response({\n 'error': 'File is in use in other simulations.',\n 'fileList': err,\n 'fileName': filename,\n })\n p = _lib_filepath(req['simulationType'], filename, req['fileType'])\n pkio.unchecked_remove(p)\n return _json_response({})\napp_delete_file = api_deleteFile\n\n\ndef api_deleteSimulation():\n data = _parse_data_input()\n simulation_db.delete_simulation(data['simulationType'], data['simulationId'])\n return _json_response_ok()\napp_delete_simulation = api_deleteSimulation\n\n\ndef api_downloadDataFile(simulation_type, simulation_id, model, frame, suffix=None):\n data = {\n 'simulationType': sirepo.template.assert_sim_type(simulation_type),\n 'simulationId': simulation_id,\n 'modelName': model,\n }\n options = pkcollections.Dict(data)\n options.suffix = suffix\n frame = int(frame)\n template = sirepo.template.import_module(data)\n if frame >= 0:\n data['report'] = template.get_animation_name(data)\n else:\n data['report'] = model\n run_dir = simulation_db.simulation_run_dir(data)\n filename, content, content_type = template.get_data_file(run_dir, model, frame, options=options)\n return _as_attachment(flask.make_response(content), content_type, filename)\napp_download_data_file = api_downloadDataFile\n\n\ndef api_downloadFile(simulation_type, simulation_id, filename):\n lib = simulation_db.simulation_lib_dir(simulation_type)\n filename = werkzeug.secure_filename(filename)\n p = lib.join(filename)\n if simulation_type == 'srw':\n attachment_name = filename\n else:\n # strip file_type prefix from attachment filename\n attachment_name = re.sub(r'^.*?-.*?\\.', '', filename)\n return flask.send_file(str(p), as_attachment=True, attachment_filename=attachment_name)\napp_download_file = api_downloadFile\n\n\ndef api_errorLogging():\n ip = flask.request.remote_addr\n try:\n pkdlog(\n '{}: javascript error: {}',\n ip,\n simulation_db.generate_json(_json_input(), pretty=True),\n )\n except ValueError as e:\n pkdlog(\n '{}: error parsing javascript app_error: {} input={}',\n ip,\n e,\n flask.request.data.decode('unicode-escape'),\n )\n return _json_response_ok()\napp_error_logging = api_errorLogging\n\n\ndef api_exportArchive(simulation_type, simulation_id, filename):\n from sirepo import exporter\n fn, mt = exporter.create_archive(simulation_type, simulation_id, filename)\n return flask.send_file(\n str(fn),\n as_attachment=True,\n attachment_filename=filename,\n mimetype=mt,\n #TODO(pjm): the browser caches HTML files, may need to add explicit times\n # to other calls to send_file()\n cache_timeout=1,\n )\n\n\ndef api_favicon():\n \"\"\"Routes to favicon.ico file.\"\"\"\n return flask.send_from_directory(\n str(simulation_db.STATIC_FOLDER.join('img')),\n 'favicon.ico',\n mimetype='image/vnd.microsoft.icon'\n )\napp_favicon = api_favicon\n\n\ndef api_listFiles(simulation_type, simulation_id, file_type):\n file_type = werkzeug.secure_filename(file_type)\n res = []\n exclude = None\n #TODO(pjm): use file prefixes for srw, currently assumes mirror is *.dat and others are *.zip\n if simulation_type == 'srw':\n template = sirepo.template.import_module(simulation_type)\n search = template.extensions_for_file_type(file_type)\n if file_type == 'sample':\n exclude = '_processed.tif'\n else:\n search = ['{}.*'.format(file_type)]\n d = simulation_db.simulation_lib_dir(simulation_type)\n for extension in search:\n for f in glob.glob(str(d.join(extension))):\n if exclude and re.search(exclude, f):\n continue\n if os.path.isfile(f):\n filename = os.path.basename(f)\n if not simulation_type == 'srw':\n # strip the file_type prefix\n filename = filename[len(file_type) + 1:]\n res.append(filename)\n res.sort()\n return _json_response(res)\napp_file_list = api_listFiles\n\n\ndef api_findByName(simulation_type, application_mode, simulation_name):\n if cfg.oauth_login:\n from sirepo import oauth\n oauth.set_default_state(logged_out_as_anonymous=True)\n # use the existing named simulation, or copy it from the examples\n rows = simulation_db.iterate_simulation_datafiles(simulation_type, simulation_db.process_simulation_list, {\n 'simulation.name': simulation_name,\n 'simulation.isExample': True,\n })\n if len(rows) == 0:\n for s in simulation_db.examples(simulation_type):\n if s['models']['simulation']['name'] == simulation_name:\n simulation_db.save_new_example(s)\n rows = simulation_db.iterate_simulation_datafiles(simulation_type, simulation_db.process_simulation_list, {\n 'simulation.name': simulation_name,\n })\n break\n else:\n raise AssertionError(util.err(simulation_name, 'simulation not found with type {}', simulation_type))\n return javascript_redirect(\n uri_router.format_uri(\n simulation_type,\n application_mode,\n rows[0]['simulationId'],\n simulation_db.get_schema(simulation_type)\n )\n )\napp_find_by_name = api_findByName\n\n\ndef api_getApplicationData(filename=''):\n \"\"\"Get some data from the template\n\n Args:\n filename (str): if supplied, result is file attachment\n\n Returns:\n response: may be a file or JSON\n \"\"\"\n data = _parse_data_input()\n res = sirepo.template.import_module(data).get_application_data(data)\n if filename:\n assert isinstance(res, _PY_PATH_LOCAL_CLASS), \\\n '{}: template did not return a file'.format(res)\n return flask.send_file(\n str(res),\n mimetype='application/octet-stream',\n as_attachment=True,\n attachment_filename=filename,\n )\n return _json_response(res)\napp_get_application_data = api_getApplicationData\n\n\ndef api_importArchive():\n \"\"\"\n Args:\n simulation_type (str): which simulation type\n Params:\n data: what to import\n \"\"\"\n import sirepo.importer\n\n data = sirepo.importer.do_form(flask.request.form)\n return javascript_redirect(\n '/{}#/source/{}'.format(\n data.simulationType,\n data.models.simulation.simulationId,\n ),\n )\n\n\ndef api_importFile(simulation_type=None):\n \"\"\"\n Args:\n simulation_type (str): which simulation type\n Params:\n file: file data\n folder: where to import to\n \"\"\"\n import sirepo.importer\n\n error = None\n f = None\n try:\n template = simulation_type and sirepo.template.import_module(simulation_type)\n f = flask.request.files.get('file')\n assert f, \\\n ValueError('must supply a file')\n if pkio.has_file_extension(f.filename, 'json'):\n data = sirepo.importer.read_json(f.read(), template)\n #TODO(pjm): need a separate URI interface to importer, added exception for rs4pi for now\n # (dicom input is normally a zip file)\n elif pkio.has_file_extension(f.filename, 'zip') and simulation_type != 'rs4pi':\n data = sirepo.importer.read_zip(f.stream, template)\n else:\n assert simulation_type, \\\n 'simulation_type is required param for non-zip|json imports'\n assert hasattr(template, 'import_file'), \\\n ValueError('Only zip files are supported')\n data = template.import_file(\n flask.request,\n simulation_db.simulation_lib_dir(simulation_type),\n simulation_db.tmp_dir(),\n )\n #TODO(robnagler) need to validate folder\n data.models.simulation.folder = flask.request.form['folder']\n data.models.simulation.isExample = False\n return _save_new_and_reply(data)\n except Exception as e:\n pkdlog('{}: exception: {}', f and f.filename, pkdexc())\n error = str(e.message) if hasattr(e, 'message') else str(e)\n return _json_response({'error': error})\n\napp_import_file = api_importFile\n\n\ndef api_homePage():\n return _render_root_page('sr-landing-page', pkcollections.Dict())\nlight_landing_page = api_homePage\n\n\ndef api_newSimulation():\n new_simulation_data = _parse_data_input()\n sim_type = new_simulation_data['simulationType']\n data = simulation_db.default_data(sim_type)\n data['models']['simulation']['name'] = new_simulation_data['name']\n data['models']['simulation']['folder'] = new_simulation_data['folder']\n if 'notes' in new_simulation_data:\n data['models']['simulation']['notes'] = new_simulation_data['notes']\n template = sirepo.template.import_module(sim_type)\n if hasattr(template, 'new_simulation'):\n template.new_simulation(data, new_simulation_data)\n return _save_new_and_reply(data)\napp_new_simulation = api_newSimulation\n\n\ndef api_oauthAuthorized(oauth_type):\n if cfg.oauth_login:\n from sirepo import oauth\n return oauth.authorized_callback(app, oauth_type)\n raise RuntimeError('OAUTH Login not configured')\napp_oauth_authorized = api_oauthAuthorized\n\n\ndef api_oauthLogin(simulation_type, oauth_type):\n if cfg.oauth_login:\n from sirepo import oauth\n return oauth.authorize(simulation_type, app, oauth_type)\n raise RuntimeError('OAUTH Login not configured')\napp_oauth_login = api_oauthLogin\n\n\ndef api_oauthLogout(simulation_type):\n if cfg.oauth_login:\n from sirepo import oauth\n return oauth.logout(simulation_type)\n raise RuntimeError('OAUTH Login not configured')\napp_oauth_logout = api_oauthLogout\n\n\ndef api_pythonSource(simulation_type, simulation_id, model=None, report=None):\n import string\n data = simulation_db.read_simulation_json(simulation_type, sid=simulation_id)\n template = sirepo.template.import_module(data)\n sim_name = data.models.simulation.name.lower()\n report_rider = '' if report is None else '-' + report.lower()\n py_name = sim_name + report_rider\n py_name = re.sub(r'[\\\"&\\'()+,/:<>?\\[\\]\\\\`{}|]', '', py_name)\n py_name = re.sub(r'\\s', '-', py_name)\n return _as_attachment(\n flask.make_response(template.python_source_for_model(data, model)),\n 'text/x-python',\n '{}.py'.format(py_name),\n )\napp_python_source = api_pythonSource\n\n\ndef api_robotsTxt():\n \"\"\"Tell robots to go away\"\"\"\n return flask.Response(\n 'User-agent: *\\nDisallow: /\\n',\n mimetype='text/plain',\n )\napp_robots_txt = api_robotsTxt\n\n\ndef api_root(simulation_type):\n try:\n sirepo.template.assert_sim_type(simulation_type)\n except AssertionError:\n if simulation_type == 'warp':\n return flask.redirect('/warppba', code=301)\n if simulation_type == 'fete':\n return flask.redirect('/warpvnd', code=301)\n pkdlog('{}: uri not found', simulation_type)\n werkzeug.exceptions.abort(404)\n if cfg.oauth_login:\n from sirepo import oauth\n values = oauth.set_default_state()\n else:\n values = pkcollections.Dict()\n values.app_name = simulation_type\n values.oauth_login = cfg.oauth_login\n return _render_root_page('index', values)\napp_root = api_root\n\n\ndef api_runCancel():\n data = _parse_data_input()\n jid = simulation_db.job_id(data)\n # TODO(robnagler) need to have a way of listing jobs\n # Don't bother with cache_hit check. We don't have any way of canceling\n # if the parameters don't match so for now, always kill.\n #TODO(robnagler) mutex required\n if runner.job_is_processing(jid):\n run_dir = simulation_db.simulation_run_dir(data)\n # Write first, since results are write once, and we want to\n # indicate the cancel instead of the termination error that\n # will happen as a result of the kill.\n simulation_db.write_result({'state': 'canceled'}, run_dir=run_dir)\n runner.job_kill(jid)\n # TODO(robnagler) should really be inside the template (t.cancel_simulation()?)\n # the last frame file may not be finished, remove it\n t = sirepo.template.import_module(data)\n t.remove_last_frame(run_dir)\n # Always true from the client's perspective\n return _json_response({'state': 'canceled'})\napp_run_cancel = api_runCancel\n\n\ndef api_runSimulation():\n data = _parse_data_input(validate=True)\n res = _simulation_run_status(data, quiet=True)\n if (\n (\n not res['state'] in _RUN_STATES\n and (res['state'] != 'completed' or data.get('forceRun', False))\n ) or res.get('parametersChanged', True)\n ):\n try:\n _start_simulation(data)\n except runner.Collision:\n pkdlog('{}: runner.Collision, ignoring start', simulation_db.job_id(data))\n res = _simulation_run_status(data)\n return _json_response(res)\napp_run_simulation = api_runSimulation\n\n\ndef api_runStatus():\n data = _parse_data_input()\n return _json_response(_simulation_run_status(data))\napp_run_status = api_runStatus\n\n\ndef api_saveSimulationData():\n data = _parse_data_input(validate=True)\n res = _validate_serial(data)\n if res:\n return res\n simulation_type = data['simulationType']\n template = sirepo.template.import_module(simulation_type)\n if hasattr(template, 'prepare_for_save'):\n data = template.prepare_for_save(data)\n data = simulation_db.save_simulation_json(data)\n return app_simulation_data(\n data['simulationType'],\n data['models']['simulation']['simulationId'],\n pretty=False,\n )\napp_save_simulation_data = api_saveSimulationData\n\n\ndef api_simulationData(simulation_type, simulation_id, pretty, section=None):\n #TODO(robnagler) need real type transforms for inputs\n pretty = bool(int(pretty))\n try:\n data = simulation_db.read_simulation_json(simulation_type, sid=simulation_id)\n template = sirepo.template.import_module(simulation_type)\n if hasattr(template, 'prepare_for_client'):\n data = template.prepare_for_client(data)\n response = _json_response(\n data,\n pretty=pretty,\n )\n if pretty:\n _as_attachment(\n response,\n app.config.get('JSONIFY_MIMETYPE', 'application/json'),\n '{}.json'.format(data['models']['simulation']['name']),\n )\n except simulation_db.CopyRedirect as e:\n if e.sr_response['redirect'] and section:\n e.sr_response['redirect']['section'] = section\n response = _json_response(e.sr_response)\n _no_cache(response)\n return response\napp_simulation_data = api_simulationData\n\n\ndef api_simulationFrame(frame_id):\n #TODO(robnagler) startTime is reportParametersHash; need version on URL and/or param names in URL\n keys = ['simulationType', 'simulationId', 'modelName', 'animationArgs', 'frameIndex', 'startTime']\n data = dict(zip(keys, frame_id.split('*')))\n template = sirepo.template.import_module(data)\n data['report'] = template.get_animation_name(data)\n run_dir = simulation_db.simulation_run_dir(data)\n model_data = simulation_db.read_json(run_dir.join(template_common.INPUT_BASE_NAME))\n frame = template.get_simulation_frame(run_dir, data, model_data)\n response = _json_response(frame)\n if 'error' not in frame and template.WANT_BROWSER_FRAME_CACHE:\n now = datetime.datetime.utcnow()\n expires = now + datetime.timedelta(365)\n response.headers['Cache-Control'] = 'public, max-age=31536000'\n response.headers['Expires'] = expires.strftime(\"%a, %d %b %Y %H:%M:%S GMT\")\n response.headers['Last-Modified'] = now.strftime(\"%a, %d %b %Y %H:%M:%S GMT\")\n else:\n _no_cache(response)\n return response\napp_simulation_frame = api_simulationFrame\n\n\ndef api_listSimulations():\n data = _parse_data_input()\n sim_type = data['simulationType']\n search = data['search'] if 'search' in data else None\n simulation_db.verify_app_directory(sim_type)\n return _json_response(\n sorted(\n simulation_db.iterate_simulation_datafiles(sim_type, simulation_db.process_simulation_list, search),\n key=lambda row: row['name'],\n )\n )\napp_simulation_list = api_listSimulations\n\n\ndef api_simulationSchema():\n sim_type = sirepo.template.assert_sim_type(flask.request.form['simulationType'])\n return _json_response(simulation_db.get_schema(sim_type))\napp_simulation_schema = api_simulationSchema\n\n\ndef api_srLandingPage():\n return flask.redirect('/light')\nsr_landing_page = api_srLandingPage\n\n\ndef api_srUnit():\n getattr(app, SR_UNIT_TEST_IN_REQUEST)()\n return ''\napp_sr_unit = api_srUnit\n\n\ndef api_updateFolder():\n #TODO(robnagler) Folder should have a serial, or should it be on data\n data = _parse_data_input()\n old_name = data['oldName']\n new_name = data['newName']\n for row in simulation_db.iterate_simulation_datafiles(data['simulationType'], _simulation_data):\n folder = row['models']['simulation']['folder']\n if folder.startswith(old_name):\n row['models']['simulation']['folder'] = re.sub(re.escape(old_name), new_name, folder, 1)\n simulation_db.save_simulation_json(row)\n return _json_response_ok()\napp_update_folder = api_updateFolder\n\n\ndef api_uploadFile(simulation_type, simulation_id, file_type):\n f = flask.request.files['file']\n filename = werkzeug.secure_filename(f.filename)\n p = _lib_filepath(simulation_type, filename, file_type)\n err = None\n file_list = None\n if p.check():\n confirm = flask.request.form['confirm'] if 'confirm' in flask.request.form else None\n if not confirm:\n search_name = _lib_filename(simulation_type, filename, file_type)\n file_list = _simulations_using_file(simulation_type, file_type, search_name, ignore_sim_id=simulation_id)\n if file_list:\n err = 'File is in use in other simulations. Please confirm you would like to replace the file for all simulations.'\n if not err:\n pkio.mkdir_parent_only(p)\n f.save(str(p))\n template = sirepo.template.import_module(simulation_type)\n if hasattr(template, 'validate_file'):\n err = template.validate_file(file_type, str(p))\n if err:\n pkio.unchecked_remove(p)\n if err:\n return _json_response({\n 'error': err,\n 'filename': filename,\n 'fileList': file_list,\n 'fileType': file_type,\n 'simulationId': simulation_id,\n })\n return _json_response({\n 'filename': filename,\n 'fileType': file_type,\n 'simulationId': simulation_id,\n })\napp_upload_file = api_uploadFile\n\n\ndef all_uids():\n \"\"\"List of all users\n\n Returns:\n set: set of all uids\n \"\"\"\n if not cfg.oauth_login:\n return set()\n from sirepo import oauth\n return oauth.all_uids(app)\n\n\ndef clear_session_user():\n \"\"\"Remove the current user from the flask session.\n \"\"\"\n if _SESSION_KEY_USER in flask.session:\n del flask.session[_SESSION_KEY_USER]\n\n\ndef init(db_dir=None, uwsgi=None):\n \"\"\"Initialize globals and populate simulation dir\"\"\"\n from sirepo import uri_router\n\n if db_dir:\n cfg.db_dir = py.path.local(db_dir)\n else:\n db_dir = cfg.db_dir\n uri_router.init(app, sys.modules[__name__], simulation_db)\n global _wsgi_app\n _wsgi_app = _WSGIApp(app, uwsgi)\n _BeakerSession().sirepo_init_app(app, db_dir)\n simulation_db.init_by_server(app, sys.modules[__name__])\n for err, file in simulation_db.SCHEMA_COMMON['customErrors'].items():\n app.register_error_handler(int(err), _handle_error)\n runner.init(app, uwsgi)\n return app\n\n\ndef javascript_redirect(redirect_uri):\n \"\"\"Redirect using javascript for safari browser which doesn't support hash redirects.\n \"\"\"\n return flask.render_template(\n 'html/javascript-redirect.html',\n redirect_uri=redirect_uri\n )\n\n\ndef session_user(*args, **kwargs):\n \"\"\"Get/set the user from the Flask session\n\n With no positional arguments, is a getter. Else a setter.\n\n Args:\n user (str): if args[0], will set the user; else gets\n checked (bool): if kwargs['checked'], assert the user is truthy\n environ (dict): session environment to use instead of `flask.session`\n\n Returns:\n str: user id\n \"\"\"\n environ = kwargs.get('environ', None)\n session = environ.get(_ENVIRON_KEY_BEAKER) if environ else flask.session\n if args:\n session[_SESSION_KEY_USER] = args[0]\n _wsgi_app.set_log_user(args[0])\n res = session.get(_SESSION_KEY_USER)\n if not res and kwargs.get('checked', True):\n raise KeyError(_SESSION_KEY_USER)\n return res\n\n\nclass _BeakerSession(flask.sessions.SessionInterface):\n \"\"\"Session manager for Flask using Beaker.\n\n Stores session info in files in sirepo.server.data_dir. Minimal info kept\n in session.\n \"\"\"\n def __init__(self, app=None):\n if app is None:\n self.app = None\n else:\n self.init_app(app)\n\n def sirepo_init_app(self, app, db_dir):\n \"\"\"Initialize cfg with db_dir and register self with Flask\n\n Args:\n app (flask): Flask application object\n db_dir (py.path.local): db_dir passed on command line\n \"\"\"\n app.sirepo_db_dir = db_dir\n data_dir = db_dir.join(_BEAKER_DATA_DIR)\n lock_dir = data_dir.join(_BEAKER_LOCK_DIR)\n pkio.mkdir_parent(lock_dir)\n sc = {\n 'session.auto': True,\n 'session.cookie_expires': False,\n 'session.type': 'file',\n 'session.data_dir': str(data_dir),\n 'session.lock_dir': str(lock_dir),\n }\n #TODO(robnagler) Generalize? seems like we'll be shadowing lots of config\n for k in cfg.beaker_session:\n sc['session.' + k] = cfg.beaker_session[k]\n app.wsgi_app = beaker.middleware.SessionMiddleware(app.wsgi_app, sc)\n app.session_interface = self\n\n def open_session(self, app, request):\n \"\"\"Called by flask to create the session\"\"\"\n return request.environ[_ENVIRON_KEY_BEAKER]\n\n def save_session(self, *args, **kwargs):\n \"\"\"Necessary to complete abstraction, but Beaker autosaves\"\"\"\n pass\n\n\nclass _WSGIApp(object):\n \"\"\"Wraps Flask's wsgi_app for logging\n\n Args:\n app (Flask.app): Flask application being wrapped\n uwsgi (module): `uwsgi` module passed from ``uwsgi.py.jinja``\n \"\"\"\n def __init__(self, app, uwsgi):\n self.app = app\n # Is None if called from sirepo.pkcli.service.http or FlaskClient\n self.uwsgi = uwsgi\n self.wsgi_app = app.wsgi_app\n app.wsgi_app = self\n\n def set_log_user(self, user):\n if self.uwsgi:\n log_user = 'li-' + user if user else '-'\n # Only works for uWSGI (service.uwsgi). For service.http,\n # werkzeug.serving.WSGIRequestHandler.log hardwires '%s - - [%s] %s\\n',\n # and no point in overriding, since just for development.\n self.uwsgi.set_logvar(_UWSGI_LOG_KEY_USER, log_user)\n\n def __call__(self, environ, start_response):\n \"\"\"An \"app\" called by uwsgi with requests.\n \"\"\"\n self.set_log_user(session_user(checked=False, environ=environ))\n return self.wsgi_app(environ, start_response)\n\n\ndef _as_attachment(response, content_type, filename):\n response.mimetype = content_type\n response.headers['Content-Disposition'] = 'attachment; filename=\"{}\"'.format(filename)\n return response\n\n\n@pkconfig.parse_none\ndef _cfg_db_dir(value):\n \"\"\"Config value or root package's parent or cwd with _DEFAULT_SUBDIR\"\"\"\n from pykern import pkinspect\n\n if value:\n assert os.path.isabs(value), \\\n '{}: SIREPO_SERVER_DB_DIR must be absolute'.format(value)\n assert os.path.isdir(value), \\\n '{}: SIREPO_SERVER_DB_DIR must be a directory and exist'.format(value)\n value = py.path.local(value)\n else:\n assert pkconfig.channel_in('dev'), \\\n 'SIREPO_SERVER_DB_DIR must be configured except in DEV'\n fn = sys.modules[pkinspect.root_package(_cfg_db_dir)].__file__\n root = py.path.local(py.path.local(py.path.local(fn).dirname).dirname)\n # Check to see if we are in our dev directory. This is a hack,\n # but should be reliable.\n if not root.join('requirements.txt').check():\n # Don't run from an install directory\n root = py.path.local('.')\n value = pkio.mkdir_parent(root.join(_DEFAULT_DB_SUBDIR))\n return value\n\n\n@pkconfig.parse_none\ndef _cfg_session_secret(value):\n \"\"\"Reads file specified as config value\"\"\"\n if not value:\n return 'dev dummy secret'\n with open(value) as f:\n return f.read()\n\n\ndef _cfg_time_limit(value):\n \"\"\"Sets timeout in seconds\"\"\"\n v = int(value)\n assert v > 0\n return v\n\n\ndef _handle_error(error):\n status_code = 500\n if isinstance(error, werkzeug.exceptions.HTTPException):\n status_code = error.code\n try:\n error_file = simulation_db.SCHEMA_COMMON['customErrors'][str(status_code)]['url']\n except:\n error_file = DEFAULT_ERROR_FILE\n f = flask.send_from_directory(static_dir('html'), error_file)\n\n return f, status_code\n\n\ndef _json_input(assert_sim_type=True):\n req = flask.request\n if req.mimetype != 'application/json':\n pkdlog('{}: req.mimetype is not application/json', req.mimetype)\n raise werkzeug.exceptions.BadRequest('expecting application/json')\n # Adapted from flask.wrappers.Request.get_json\n # We accept a request charset against the specification as\n # certain clients have been using this in the past. This\n # fits our general approach of being nice in what we accept\n # and strict in what we send out.\n charset = req.mimetype_params.get('charset')\n data = req.get_data(cache=False)\n res = simulation_db.json_load(data, encoding=charset)\n if assert_sim_type and 'simulationType' in res:\n res.simulationType = sirepo.template.assert_sim_type(res.simulationType)\n return res\n\n\ndef _json_response(value, pretty=False):\n \"\"\"Generate JSON flask response\n\n Args:\n value (dict): what to format\n pretty (bool): pretty print [False]\n Returns:\n Response: flask response\n \"\"\"\n return app.response_class(\n simulation_db.generate_json(value, pretty=pretty),\n mimetype=app.config.get('JSONIFY_MIMETYPE', 'application/json'),\n )\n\n\ndef _json_response_ok(*args, **kwargs):\n \"\"\"Generate state=ok JSON flask response\n\n Returns:\n Response: flask response\n \"\"\"\n if len(args) > 0:\n assert len(args) == 1\n res = args[0]\n res.update(_RESPONSE_OK)\n return _json_response(res)\n global _JSON_RESPONSE_OK\n if not _JSON_RESPONSE_OK:\n _JSON_RESPONSE_OK = _json_response(_RESPONSE_OK)\n return _JSON_RESPONSE_OK\n\n\ndef _mtime_or_now(path):\n \"\"\"mtime for path if exists else time.time()\n\n Args:\n path (py.path):\n\n Returns:\n int: modification time\n \"\"\"\n return int(path.mtime() if path.exists() else time.time())\n\n\ndef _lib_filename(simulation_type, filename, file_type):\n if simulation_type == 'srw':\n return filename\n return werkzeug.secure_filename('{}.{}'.format(file_type, filename))\n\n\ndef _lib_filepath(simulation_type, filename, file_type):\n lib = simulation_db.simulation_lib_dir(simulation_type)\n return lib.join(_lib_filename(simulation_type, filename, file_type))\n\n\ndef _no_cache(response):\n response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'\n response.headers['Pragma'] = 'no-cache'\n\n\ndef _parse_data_input(validate=False):\n data = _json_input(assert_sim_type=False)\n return simulation_db.fixup_old_data(data)[0] if validate else data\n\n\ndef _render_root_page(page, values):\n values.source_cache_key = _source_cache_key()\n values.app_version = simulation_db.app_version()\n return flask.render_template(\n 'html/{}.html'.format(page),\n **values\n )\n\n\ndef _save_new_and_reply(*args):\n data = simulation_db.save_new_simulation(*args)\n return app_simulation_data(\n data['simulationType'],\n data['models']['simulation']['simulationId'],\n pretty=False,\n )\n\n\ndef _simulation_error(err, *args, **kwargs):\n \"\"\"Something unexpected went wrong.\n\n Parses ``err`` for error\n\n Args:\n err (str): exception or run_log\n quiet (bool): don't write errors to log\n Returns:\n dict: error response\n \"\"\"\n if not kwargs.get('quiet'):\n pkdlog('{}', ': '.join([str(a) for a in args] + ['error', err]))\n m = re.search(_SUBPROCESS_ERROR_RE, str(err))\n if m:\n err = m.group(1)\n if re.search(r'error exit\\(-15\\)', err):\n err = 'Terminated'\n elif not pkconfig.channel_in_internal_test():\n err = 'unexpected error (see logs)'\n return {'state': 'error', 'error': err}\n\n\ndef _simulation_data(res, path, data):\n \"\"\"Iterator function to return entire simulation data\n \"\"\"\n res.append(data)\n\n\ndef _simulation_name(res, path, data):\n \"\"\"Iterator function to return simulation name\n \"\"\"\n res.append(data['models']['simulation']['name'])\n\n\ndef _simulation_run_status(data, quiet=False):\n \"\"\"Look for simulation status and output\n\n Args:\n data (dict): request\n quiet (bool): don't write errors to log\n\n Returns:\n dict: status response\n \"\"\"\n try:\n #TODO(robnagler): Lock\n rep = simulation_db.report_info(data)\n is_processing = runner.job_is_processing(rep.job_id)\n is_running = rep.job_status in _RUN_STATES\n res = {'state': rep.job_status}\n pkdc(\n '{}: is_processing={} is_running={} state={} cached_data={}',\n rep.job_id,\n is_processing,\n is_running,\n rep.job_status,\n bool(rep.cached_data),\n )\n if is_processing and not is_running:\n runner.job_race_condition_reap(rep.job_id)\n pkdc('{}: is_processing and not is_running', rep.job_id)\n is_processing = False\n template = sirepo.template.import_module(data)\n if is_processing:\n if not rep.cached_data:\n return _simulation_error(\n 'input file not found, but job is running',\n rep.input_file,\n )\n else:\n is_running = False\n if rep.run_dir.exists():\n if hasattr(template, 'prepare_output_file') and 'models' in data:\n template.prepare_output_file(rep, data)\n res2, err = simulation_db.read_result(rep.run_dir)\n if err:\n if simulation_db.is_parallel(data):\n # allow parallel jobs to use template to parse errors below\n res['state'] = 'error'\n else:\n if hasattr(template, 'parse_error_log'):\n res = template.parse_error_log(rep.run_dir)\n if res:\n return res\n return _simulation_error(err, 'error in read_result', rep.run_dir)\n else:\n res = res2\n if simulation_db.is_parallel(data):\n new = template.background_percent_complete(\n rep.model_name,\n rep.run_dir,\n is_running,\n )\n new.setdefault('percentComplete', 0.0)\n new.setdefault('frameCount', 0)\n res.update(new)\n res['parametersChanged'] = rep.parameters_changed\n if res['parametersChanged']:\n pkdlog(\n '{}: parametersChanged=True req_hash={} cached_hash={}',\n rep.job_id,\n rep.req_hash,\n rep.cached_hash,\n )\n #TODO(robnagler) verify serial number to see what's newer\n res.setdefault('startTime', _mtime_or_now(rep.input_file))\n res.setdefault('lastUpdateTime', _mtime_or_now(rep.run_dir))\n res.setdefault('elapsedTime', res['lastUpdateTime'] - res['startTime'])\n if is_processing:\n res['nextRequestSeconds'] = simulation_db.poll_seconds(rep.cached_data)\n res['nextRequest'] = {\n 'report': rep.model_name,\n 'reportParametersHash': rep.cached_hash,\n 'simulationId': rep.cached_data['simulationId'],\n 'simulationType': rep.cached_data['simulationType'],\n }\n pkdc(\n '{}: processing={} state={} cache_hit={} cached_hash={} data_hash={}',\n rep.job_id,\n is_processing,\n res['state'],\n rep.cache_hit,\n rep.cached_hash,\n rep.req_hash,\n )\n except Exception:\n return _simulation_error(pkdexc(), quiet=quiet)\n return res\n\n\ndef _simulations_using_file(simulation_type, file_type, search_name, ignore_sim_id=None):\n res = []\n template = sirepo.template.import_module(simulation_type)\n if not hasattr(template, 'validate_delete_file'):\n return res\n for row in simulation_db.iterate_simulation_datafiles(simulation_type, _simulation_data):\n if template.validate_delete_file(row, search_name, file_type):\n sim = row['models']['simulation']\n if ignore_sim_id and sim['simulationId'] == ignore_sim_id:\n continue\n if sim['folder'] == '/':\n res.append('/{}'.format(sim['name']))\n else:\n res.append('{}/{}'.format(sim['folder'], sim['name']))\n return res\n\n\ndef _source_cache_key():\n if cfg.enable_source_cache_key:\n return '?{}'.format(simulation_db.app_version())\n return ''\n\n\ndef _start_simulation(data):\n \"\"\"Setup and start the simulation.\n\n Args:\n data (dict): app data\n Returns:\n object: runner instance\n \"\"\"\n data['simulationStatus'] = {\n 'startTime': int(time.time()),\n 'state': 'pending',\n }\n runner.job_start(data)\n\n\ndef _validate_serial(data):\n \"\"\"Verify serial in data validates\n\n Args:\n data (dict): request with serial and possibly models\n\n Returns:\n object: None if all ok, or json response if invalid\n \"\"\"\n res = simulation_db.validate_serial(data)\n if not res:\n return None\n return _json_response({\n 'state': 'error',\n 'error': 'invalidSerial',\n 'simulationData': res,\n })\n\n\ndef static_dir(dir_name):\n return str(simulation_db.STATIC_FOLDER.join(dir_name))\n\n\ncfg = pkconfig.init(\n beaker_session=dict(\n key=('sirepo_' + pkconfig.cfg.channel, str, 'Beaker: Name of the cookie key used to save the session under'),\n secret=(None, _cfg_session_secret, 'Beaker: Used with the HMAC to ensure session integrity'),\n secure=(False, bool, 'Beaker: Whether or not the session cookie should be marked as secure'),\n ),\n db_dir=(None, _cfg_db_dir, 'where database resides'),\n job_queue=(None, str, 'DEPRECATED: set $SIREPO_RUNNER_JOB_CLASS'),\n oauth_login=(False, bool, 'OAUTH: enable login'),\n enable_source_cache_key=(True, bool, 'enable source cache key, disable to allow local file edits in Chrome'),\n enable_bluesky=(False, bool, 'Enable calling simulations directly from NSLS-II/bluesky'),\n)\n","sub_path":"sirepo/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":40739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"523788208","text":"\"\"\"\nDefinition of TreeNode:\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.left, self.right = None, None\n\"\"\"\n\nclass Solution:\n \"\"\"\n @param root: param root: The root of the binary search tree\n @param k1: An integer\n @param k2: An integer\n @return: return: Return all keys that k1<=key<=k2 in ascending order\n \"\"\"\n def searchRange(self, root, k1, k2):\n nodes = []\n self.helper(root, k1, k2, nodes)\n return nodes\n\n def helper(self, root, k1, k2, nodes):\n if not root:\n return\n if root.val > k1:\n self.helper(root.left, k1, k2, nodes)\n if k1 <= root.val <= k2:\n nodes.append(root.val)\n if root.val < k2:\n self.helper(root.right, k1, k2, nodes)","sub_path":"binarysearch/SearchRangeInBinarySearchTree.py","file_name":"SearchRangeInBinarySearchTree.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"274575690","text":"def zhaoBuTong(a,b):\n answer=0\n for i in range(str(a).__len__()):\n if a[i:i+1]!=b[i:i+1]:\n answer+=1\n return answer\nanswerList=[]\n\n\ndef recursion (begin,end,wordList,wordLength,answer):\n tem=[]\n if zhaoBuTong(end, answer[answer.__len__() - 1]) == 1:\n answerList.append(list(answer))\n return\n for i in range(wordLength):\n if zhaoBuTong(wordList[i],answer[answer.__len__()-1])==1 and wordList[i] not in answer:\n tem.append(wordList[i])\n for i in tem:\n answer.append(i)\n recursion(begin,end,wordList,wordLength,answer)\n answer.remove(i)\n\nbegin=input()\nend=input()\nstring=input()[2:]\nwordList=[]\n\ni=0\nwhile iminlen:\n answerList.remove(list(i))\n result=[]\n for i in range(answerList.__len__()):\n tem=[]\n for j in answerList[i]:\n tem.append(j)\n tem.append(end)\n result.append(tem)\n print(result)","sub_path":"Code/CodeRecords/2747/60677/246539.py","file_name":"246539.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"229994022","text":"import pandas as pd\nimport os\nfrom rdkit import Chem\nimport time\nimport gzip\n\ndef main() :\n print(\"Processing PubChem FTP Download\")\n\n sdf_root_path = \"/media/data/pubchem/SDF\"\n results_path = \"/media/data/pubchem/smiles\"\n\n try:\n os.makedirs(results_path)\n except :\n print(\"Results directory already exists\")\n\n i = 0\n max_smiles_len = 200\n\n processed_files = os.listdir(results_path)\n processed_files.append(\"Compound_102125001_102150000_smiles.csv\")\n\n for path, dirs, filenames in os.walk(sdf_root_path) :\n for filename in filenames:\n\n print(\"Processing: {0}\".format(filename))\n\n expected_file_name = filename.replace(\".sdf.gz\", \"_smiles.csv\")\n new_file_name = os.path.join(results_path,expected_file_name)\n\n\n if expected_file_name in processed_files:\n print(\"Skipping: {0}\".format(new_file_name))\n i = i + 1\n continue\n\n keys = list()\n values = list()\n\n start = time.time()\n filepath = os.path.join(sdf_root_path,filename)\n\n with gzip.open(filepath,'rb') as myfile:\n suppl = Chem.ForwardSDMolSupplier(myfile)\n for mol in suppl:\n if mol is None: continue\n cid = mol.GetProp(\"PUBCHEM_COMPOUND_CID\")\n smiles = mol.GetProp(\"PUBCHEM_OPENEYE_ISO_SMILES\")\n if len(smiles) > max_smiles_len:\n i = i + 1\n print(\"Skipped compound: {0} due to large size\".format(cid))\n continue\n keys.append(int(cid))\n values.append(smiles)\n end = time.time()\n\n print(\"Processed file number: {0} in {1} seconds\".format(i, end - start))\n i = i + 1\n\n df = pd.DataFrame({\"PUBCHEM_CID\" : keys, \"SMILES\" : values},index=keys)\n df.to_csv(new_file_name,index=False)\n\n\n\n # Now parse all results smile files into one big file\n df_list = list()\n processed_files = os.listdir(results_path)\n for filename in processed_files :\n print(\"Processing: {} for summary CSV\".format(filename))\n df = pd.read_csv(os.path.join(results_path,filename))\n df_list.append(df)\n\n df_full = pd.concat(df_list)\n\n\n print(\"Writing out summary CSV\")\n df_full.to_csv(\"/media/data/pubchem/summary.csv\",index=False)\n\n print(\"Stored data as CSV\")\n\n\n\n print(\"Done\")\n\nif __name__ == '__main__':\n main()\n","sub_path":"contrib/pubchem_dataset/create_smiles_mapping.py","file_name":"create_smiles_mapping.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"97860592","text":"import tkinter as tk\nfrom cell import Cell\nfrom grid import Grid\n\n\n# Create the window with the Tk class\nroot = tk.Tk()\n\n# Create the canvas and make it visible with pack()\ncanvas = tk.Canvas(root, width=800, height=800)\ncanvas.pack() # this makes it visible\n\n# Loads and create image (put the image in the folder)\n\n\ndef move(event):\n \"\"\"Move the sprite image with a d w and s when click them\"\"\"\n if event.char == \"a\":\n img = tk.PhotoImage(file=\"gifs/hero-left.gif\")\n image = canvas.create_image(360, 360, anchor=tk.NW, image=img)\n canvas.move(image, -72, 0)\n elif event.char == \"d\":\n img = tk.PhotoImage(file=\"gifs/hero-right.gif\")\n image = canvas.create_image(360, 360, anchor=tk.NW, image=img)\n canvas.move(image, 72, 0)\n elif event.char == \"w\":\n img = tk.PhotoImage(file=\"gifs/hero-up.gif\")\n image = canvas.create_image(360, 360, anchor=tk.NW, image=img)\n canvas.move(image, 0, -72)\n elif event.char == \"s\":\n img = tk.PhotoImage(file=\"gifs/hero-down.gif\")\n image = canvas.create_image(360, 360, anchor=tk.NW, image=img)\n canvas.move(image, 0, 72)\n\n\n\nimg = tk.PhotoImage(file=\"gifs/hero-down.gif\")\nimage = canvas.create_image(360, 360, anchor=tk.NW, image=img)\n\n# This bind window to keys so that move is called when you press a key\nroot.bind(\"\", move)\n\n# this creates the loop that makes the window stay 'active'\nroot.mainloop()","sub_path":"week-10/wanderer/herotest.py","file_name":"herotest.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"378471027","text":"\nimport pandas as pd\nlocation=\"dataforDL1.csv\"\ne=pd.read_csv(location)\ntags=[]\nids=[]\ntags1=[]\nids1=[]\nfor i,l in enumerate(e['typeoffraud']):\n if l==1 or l==2 or l==3:\n ids.append(e.iloc[i,1])\n tags.append(e.iloc[i,4])\n if l==4 or l==5 or l==6:\n ids1.append(e.iloc[i,1])\n tags1.append(e.iloc[i,4])\n \nrel=list(zip(ids,tags))\npp=pd.DataFrame(data=rel,columns=['ids','tags'])\npp.to_csv('labelofhead.csv',index=False)\n\nrel1=list(zip(ids1,tags1))\npp1=pd.DataFrame(data=rel1,columns=['ids','tags'])\npp1.to_csv('labelofcol.csv',index=False)\n\nlocation=\"dataforDl1.csv\"\ne=pd.read_csv(location)\n\nlocation1=\"lm.csv\"\ne1=pd.read_csv(location1)\n\nx=list(e['ids'])\ny=list(e1['label'])\n\nrel=list(zip(x,y))\npp=pd.DataFrame(data=rel,columns=['ids','tags'])\npp.to_csv('labelofmethod.csv',index=False)\n\n\nlocation=\"labelofmethod.csv\"\ne=pd.read_csv(location)\n\nidof=[]\ntag=[]\nidof1=[]\ntag1=[]\nfor i,l in enumerate(e['tags']):\n if l==1 or l==2 or l==3:\n idof.append(e.iloc[i,0])\n tag.append(e.iloc[i,1])\n if l==4 or l==5 or l==6:\n idof1.append(e.iloc[i,0])\n tag1.append(e.iloc[i,1])\n \nrel=list(zip(idof,tag))\npp=pd.DataFrame(data=rel,columns=['ids','tags'])\npp.to_csv('labelofheadM.csv',index=False)\n\nrel1=list(zip(idof1,tag1))\npp1=pd.DataFrame(data=rel1,columns=['ids','tags'])\npp1.to_csv('labelofcolM.csv',index=False)\n\n","sub_path":"Method-Evaluation/Support Vector Machine/tagofeval.py","file_name":"tagofeval.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"201940818","text":"import sys\nfrom pathlib import Path\nimport os\n\nfrom loguru import logger\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.preprocessing import normalize\nimport tensorflow as tf\nfrom tensorflow.keras import (\n Input,\n Sequential,\n layers\n)\nfrom tensorflow.python.keras import activations\nfrom tensorflow.python.keras.layers.core import Dense\n\nfrom metrica import Metrika\n\n# Убираю предупреждения\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' \nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" # see issue #152\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"\n\n# Функция сборки модели\ndef construct(inputShape, outputShape):\n # Формирую последовательную модель с несколькими выходным значением (вектор)\n model = Sequential([\n Input(shape = (inputShape,)),\n layers.Dense(inputShape * 2, activation='relu'),\n layers.Dense(inputShape * 6, activation='relu'),\n layers.Dense(inputShape * 6, activation='sigmoid'),\n layers.Dense(inputShape * 3, activation='relu'),\n # временное решение \n\n # Главный вопрос в том что бы засофтмаксить по векторам-классам\n # Показывает себя лучше\n layers.Dense(outputShape, activation = 'softmax')\n \n # Либо использовать 1 выход\n # layers.Dense(1, activation='sigmoid')\n ])\n\n model.compile(\n optimizer='adam', \n # временное решение\n loss='categorical_crossentropy',\n # loss = 'binary_crossentropy',\n metrics=['accuracy']\n )\n\n return model\n\n# Получение всех метрик из датафрейма\ndef extractMetriks(dfPath):\n skeletonVector = []\n metrica = Metrika(dfPath)\n \n # Тело\n skeletonVector.append(metrica.body.hipsWidth) \n\n skeletonVector.append(metrica.body.meanHeight) \n skeletonVector.append(metrica.body.minHeight) \n skeletonVector.append(metrica.body.maxHeight) \n\n skeletonVector.append(metrica.body.meanArmsBodyDispersion) \n skeletonVector.append(metrica.body.minArmsBodyDispersion) \n skeletonVector.append(metrica.body.maxArmsBodyDispersion) \n\n skeletonVector.append(metrica.body.meanArmsDispersion) \n skeletonVector.append(metrica.body.minArmsDispersion) \n skeletonVector.append(metrica.body.maxArmsDispersion) \n \n skeletonVector.append(metrica.body.meanFeetWristHeight) \n skeletonVector.append(metrica.body.minFeetWristHeight) \n skeletonVector.append(metrica.body.maxFeetWristHeight) \n\n skeletonVector.append(metrica.body.meanHipsDiffer) \n skeletonVector.append(metrica.body.minHipsDiffer) \n skeletonVector.append(metrica.body.maxHispDiffer) \n \n # Ноги\n skeletonVector.append(metrica.legs.mean) \n skeletonVector.append(metrica.legs.min) \n skeletonVector.append(metrica.legs.max) \n \n skeletonVector.append(metrica.legs.stepLength)\n\n # Руки\n skeletonVector.append(metrica.hands.mean) \n skeletonVector.append(metrica.hands.min) \n skeletonVector.append(metrica.hands.max) \n\n return skeletonVector \n\n# Сформировать датасет из всех видео и файла лейблов\ndef formDataset(videoDir, labelsFile):\n # Просто по-особому распоковал листы\n X, Y = (list(), list())\n # Является ли указанная папка папкой с видео сотрудников\n if videoDir.is_dir():\n # Для каждой подпапки в ней\n for subdir in videoDir.iterdir():\n # Проверяю условие соответствия\n if subdir.is_dir():\n # Каждый файл в папке подвергаю извлечению метрик (рассчитано на csv файлы)\n for path in subdir.iterdir():\n X.append(extractMetriks(path))\n # Отображаю в консоли\n logger.success(path)\n\n # Проверяю является ли текстовик файлом\n if labelsFile.is_file():\n # Открываю в режиме чтения\n with open(labelsFile, 'r') as fd:\n rows = fd.read().split('\\n')\n # Построчно считываю\n for row in rows:\n # Добавляю в коробку с целевиками\n Y.append(row)\n # Отображаю в консоли\n logger.success(row)\n \n # Небольшая процедура ассоциации классов\n y = pd.DataFrame(Y, columns=['classs'])\n # Факторизация по интовским классам 0, 1, 2, 3...\n array, classes = pd.factorize(y.classs)\n\n # Небольшая векторизация для софтмакса\n Y = list()\n for item in array:\n row = list()\n for iters in range(len(classes)):\n row.append(0.0)\n row[item] = 1.0\n Y.append(row)\n\n y = np.asarray_chkfinite(Y)\n logger.debug(Y)\n \n # Небольшие исправления для нецелевых признаков\n x = np.asarray_chkfinite(X)\n # Нормализация\n x = normalize(X)\n\n return x, y, classes\n\n# Функция перехода от ксв видоса к нецелевому признаку\ndef csvToX(csvPath):\n # Выборка метрик\n X_test = extractMetriks(csvPath)\n # Проверка выбросов + перевод в нампай аррей\n X_test = np.asarray_chkfinite(X_test)\n # Нормализация данных\n X_test = normalize([X_test])\n \n return X_test\n\nif __name__ == '__main__':\n # Введение файлов папки с видео и лейблов тегов\n videoPath = Path().cwd().joinpath(sys.argv[1])\n labelsPath = Path().cwd().joinpath(sys.argv[2])\n\n # Формирование датасета\n X, Y, classes = formDataset(videoPath, labelsPath)\n\n # Использование функции построения модели\n # ВАЖНО! Здесь длинна всевозможных классов это выхой размерности вектор лейблов\n SMP = construct(len(X[0]), len(classes))\n\n SMP.fit(\n X, \n Y,\n epochs=round((len(Y)*3)),\n batch_size=round((len(Y)/4)))\n\n savePath = Path().cwd().joinpath('SMP/models')\n if not savePath.exists():\n savePath.mkdir()\n SMP.save(savePath.joinpath('weights'))\n \n # Вывод результата предиктов\n X_test = csvToX(Path(r'C:\\Users\\zhiti\\Documents\\GitHub\\PoseDetection\\workersWalks\\Oleja\\walk_video_2021-10-04_11-32-21.csv'))\n logger.success(SMP.predict(X_test))","sub_path":"walkSupport/SMP/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":7006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"548468733","text":"from collections import defaultdict, OrderedDict\nfrom datetime import timedelta\nimport re\n\nfrom django.contrib import messages, comments\nfrom django.contrib.auth import logout\nfrom django.contrib.auth.models import User\nfrom django.contrib.admin.models import LogEntry, ADDITION\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.comments.signals import comment_was_posted\nfrom django.shortcuts import render, get_object_or_404, get_list_or_404\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponseRedirect\nfrom django.dispatch import receiver\nfrom django.utils import timezone\n\nfrom distro_info import UbuntuDistroInfo\n\nfrom uploads.decorators import group_perm_required\nfrom uploads.models import Uploads, People, UserProfile\nfrom uploads.forms import NotesForm, EditContrib\n\n\ndef months(months):\n return timezone.now() - timedelta(days=months*30)\n\n\ndef group(type):\n base = People.objects.filter(control_group=False).filter(\n authoritative=True).filter(ubuntu_dev=False).prefetch_related(\n \"first_upload\").prefetch_related(\"last_upload\")\n active = base.filter(last_upload__timestamp__gte=months(4))\n types = {\n 'first_timers': base.filter(first_upload__timestamp__gte=months(3)),\n 'experienced': active.filter(total_uploads__gte=40),\n 'inactive': base.filter(total_uploads__gte=5).filter(\n last_upload__timestamp__gt=months(12)).filter(\n last_upload__timestamp__lt=months(2)),\n 'potential': active.filter(total_uploads__gte=40).filter(\n first_upload__timestamp__lte=months(6)),\n 'recent': base.filter(last_upload__timestamp__gte=months(2)),\n }\n return types[type]\n\n\ndef suggestions(email):\n person = People.objects.get(email=email, authoritative=True)\n if not person.ubuntu_dev and person.first_upload.timestamp > months(3):\n return 'This new contributor has not been contacted, \\\n you should contact him/her, \\\n click here for sample email templates'\n if (not person.ubuntu_dev and person.last_upload.timestamp > months(4) and\n person.total_uploads > 40):\n return 'Suggest a new package for this person to work on'\n if (person.last_upload.timestamp > months(12) and\n person.last_upload.timestamp < months(2)):\n return 'This person is inactive'\n if (not person.ubuntu_dev and person.last_upload.timestamp > months(12) and\n person.total_uploads > 40 and\n person.first_upload.timestamp <= months(6)):\n return 'This person should apply for Debian Developer status'\n else:\n return 'This person does not fall under any of the categories'\n\n\n@group_perm_required()\ndef person_detail(request, email):\n person = get_object_or_404(People, email=email, authoritative=True)\n contributors = get_list_or_404(People, authoritative=True)\n uploads = Uploads.objects.filter(email_changer=email)\n recent_uploads = uploads.order_by('timestamp').reverse()[0:10]\n ppu_candidates = get_ppu_candidates(uploads)\n if request.method == 'POST':\n if 'save_notes' in request.POST:\n notes_form = NotesForm(request.POST)\n if notes_form.is_valid():\n person.notes = notes_form.cleaned_data['notes']\n person.save()\n change_message = \"Updated %s's whiteboard.\" % person.name\n log_action(person, change_message, request.user.pk)\n messages.success(request, 'Change successfully saved...')\n return HttpResponseRedirect('#')\n else:\n notes_form = NotesForm(initial={'notes': person.notes})\n\n return render(request, 'person.html', {'person': person,\n 'recent_uploads': recent_uploads,\n 'ppu_candidates': ppu_candidates,\n 'notes_form': notes_form,\n 'contributor_list': contributors,\n 'suggestion': suggestions(email),\n })\n# 'uploads_per_release':\n# uploads_per_release})\n\n\ndef get_ppu_candidates(uploads):\n \"\"\"\n Takes an Uploads object filtered by email_changer and returns\n a list of package that were uploaded by a contributor more than\n five times.\n \"\"\"\n packages = uploads.values_list('package', flat=True)\n ppu_candidates = []\n appearances = defaultdict(int)\n for curr in packages:\n appearances[curr] += 1\n for pkg in appearances:\n if appearances[pkg] > 5:\n ppu_candidates += [pkg]\n return ppu_candidates\n\n\ndef get_uploads_per_release(email):\n \"\"\"\n Takes an email and returns an ordered dict of uploads per release.\n \"\"\"\n uploads_per_release = OrderedDict([])\n for d in UbuntuDistroInfo().all:\n release_uploads = len(Uploads.objects.filter(\n email_changer=email).filter(release__icontains=d))\n if uploads_per_release or release_uploads > 0:\n uploads_per_release[d] = release_uploads\n return uploads_per_release\n\n\n@group_perm_required()\ndef edit_person(request, email):\n person = get_object_or_404(People, email=email)\n if request.method == 'POST':\n person_form = EditContrib(request.POST)\n if person_form.is_valid():\n new_email = person_form.cleaned_data['email']\n person.email = person_form.cleaned_data['email']\n person.email = new_email\n person.save()\n if email is not new_email:\n uploads = Uploads.objects.filter(email_changer=email)\n uploads.update(email_changer=new_email)\n change_message = \"Updated %s's details.\" % person.name\n log_action(person, change_message, request.user.pk)\n messages.success(request, 'Change successfully saved...')\n return HttpResponseRedirect('/contributors/{}'.format(new_email))\n else:\n person_form = EditContrib(initial={'email': email,\n 'email': person.email})\n return render(request, 'edit_person.html', {'person': person,\n 'person_form': person_form})\n\n\ndef contacted(request, email):\n if request.POST:\n p = People.objects.get(email=email)\n p.contacted = not p.contacted\n p.save()\n return HttpResponseRedirect('/contributors/potential_devs')\n\n\ndef log_action(object, change_message, user):\n LogEntry.objects.log_action(\n user_id=user,\n content_type_id=ContentType.objects.get_for_model(object).pk,\n object_id=object.pk,\n object_repr=object.email,\n change_message=change_message,\n action_flag=ADDITION\n )\n\n\n@group_perm_required()\ndef user_profile(request, user):\n profile = User.objects.get(username=user).profile\n actions = LogEntry.objects.filter(user_id=profile.user_id)\n edited_contribs = actions.order_by('object_repr').values_list(\n \"object_repr\", flat=True).distinct()\n return render(request, 'user_profile.html',\n {'profile': profile,\n 'actions': actions,\n 'edited_contribs': edited_contribs})\n\n\ndef site_logout(request):\n logout(request)\n messages.success(request, 'Logged out successfully...')\n return HttpResponseRedirect('/')\n\n\ndef access_denied(request, redirect):\n messages.error(request, \"\"\"\n You do not have the correct permissions to view that page...\n \"\"\")\n return HttpResponseRedirect(redirect)\n\n\ndef index(request):\n return render(request, 'index.html', dashboard())\n\n\ndef dashboard():\n first_timers = []\n experienced = []\n inactive = []\n\n first_timers_qs = group('first_timers').select_related(\n 'contacts').order_by('last_upload__timestamp').reverse()\n experienced_qs = group('experienced').select_related(\n 'contacts').order_by('last_upload__timestamp').reverse()\n inactive_qs = group('inactive').select_related(\n 'contacts').order_by('last_upload__timestamp').reverse()\n\n for p in first_timers_qs:\n if (len(first_timers) < 20 and not p.contacts.all()):\n first_timers.append(p)\n for p in experienced_qs:\n if p.contacts.all():\n recent_c = p.contacts.all().reverse()[0].submit_date\n else:\n recent_c = None\n if (len(experienced) < 20 and (recent_c is None or\n recent_c < Uploads.objects.filter(\n email_changer=p.email).order_by(\"timestamp\")[39].timestamp)):\n experienced.append(p)\n\n for p in inactive_qs:\n if p.contacts.all():\n recent_c = p.contacts.all().reverse()[0].submit_date\n else:\n recent_c = None\n if len(inactive) < 20 and (recent_c is None or\n recent_c < p.last_upload.timestamp):\n inactive.append(p)\n return {'first_timers': first_timers,\n 'experienced': experienced,\n 'inactive': inactive}\n\n\n@receiver(comment_was_posted)\ndef on_contact_saved(sender, comment=None, request=None, **kwargs):\n person = People.objects.get(pk=comment.object_pk)\n change_message = \"Recorded a contact with %s.\" % person.name\n log_action(person, change_message, comment.user.pk)\n messages.success(request, 'Change successfully saved...')\n\n\ndef delete_comment(request, email, comment_id):\n if request.POST:\n comment = get_object_or_404(comments.get_model(), id=comment_id)\n comment.delete()\n msg = \"Successfully deleted contact\"\n messages.success(request, msg)\n return HttpResponseRedirect(reverse('person_detail', args=(email,)))\n\n\ndef unify_identities(request):\n if request.POST:\n merge_from_email = request.POST[\"merge_from\"]\n merge_into_data = request.POST[\"merge_into\"]\n merge_into_email = re.search(r\"<(.*)>\", merge_into_data).groups()[0]\n merge_from = People.objects.get(email=merge_from_email,\n authoritative=True)\n merge_into = People.objects.get(email=merge_into_email,\n authoritative=True)\n merge_from.merge(merge_into)\n msg = ' '.join([\"Successful unification of\", merge_from_email,\n \"into\", merge_into_email])\n messages.success(request, msg)\n return HttpResponseRedirect(reverse('person_detail',\n args=(merge_into_email,)))\n","sub_path":"greenhouse/uploads/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"561499488","text":"# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\nr\"\"\"Convert raw PASCAL dataset to TFRecord for object_detection.\n\nExample usage:\n python object_detection/dataset_tools/create_pascal_tf_record.py \\\n --data_dir=/home/user/VOCdevkit \\\n --year=VOC2012 \\\n --output_path=/home/user/pascal.record\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport cv2\nimport tarfile\nimport numpy as np\n\nimport tensorflow as tf\n\nflags = tf.app.flags\nflags.DEFINE_string('image_data_dir', '', '')\nflags.DEFINE_string('output_path', '', '')\ntf.flags.DEFINE_string('parts', '', '')\n\nFLAGS = flags.FLAGS\n\ntf.logging.set_verbosity(tf.logging.DEBUG)\n\ncv2.setUseOptimized(True)\ncv2.setNumThreads(8)\nss = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation()\n\n\ndef selective_search(data,\n dataset_directory,\n label_map_dict,\n ignore_difficult_instances=False,\n image_subdirectory='JPEGImages'):\n \"\"\"Convert XML derived dict to tf.Example proto.\n\n Notice that this function normalizes the bounding box coordinates provided\n by the raw data.\n\n Args:\n data: dict holding PASCAL XML fields for a single image (obtained by\n running dataset_util.recursive_parse_xml_to_dict)\n dataset_directory: Path to root directory holding PASCAL dataset\n label_map_dict: A map from string label names to integers ids.\n ignore_difficult_instances: Whether to skip difficult instances in the\n dataset (default: False).\n image_subdirectory: String specifying subdirectory within the\n PASCAL dataset directory holding the actual image data.\n\n Returns:\n example: The converted tf.Example.\n\n Raises:\n ValueError: if the image pointed to by data['filename'] is not a valid JPEG\n \"\"\"\n img_path = os.path.join(data['folder'], image_subdirectory, data['filename'])\n full_path = os.path.join(dataset_directory, img_path)\n with tf.gfile.GFile(full_path, 'rb') as fid:\n encoded_jpg = fid.read()\n\n width = int(data['size']['width'])\n height = int(data['size']['height'])\n\n # Use SelectiveSearch to get the proposals.\n\n file_bytes = np.fromstring(encoded_jpg, dtype=np.uint8)\n\n bgr = cv2.imdecode(file_bytes, cv2.IMREAD_UNCHANGED)\n assert bgr.shape[0] == height and bgr.shape[1] == width\n\n if height / width >= 2.2:\n width = int(height / 2.2)\n bgr = cv2.resize(bgr, (width, height))\n elif width / height >= 2.2:\n height = int(width / 2.2)\n bgr = cv2.resize(bgr, (width, height))\n\n ss.setBaseImage(bgr)\n #ss.switchToSelectiveSearchFast()\n ss.switchToSelectiveSearchQuality()\n rects = ss.process()\n\n rects = np.stack([rect for rect in rects if rect[2] >= 20 and rect[3] >= 20],\n axis=0)\n\n height, width = bgr.shape[0], bgr.shape[1]\n x, y, w, h = [rects[:, i] for i in range(4)]\n proposals = np.stack(\n [y / height, x / width, (y + h) / height, (x + w) / width], axis=-1)\n return proposals\n\n\ndef main(_):\n part_at_i, part_total = 0, 1\n if FLAGS.parts:\n part_at_i, part_total = [int(x) for x in FLAGS.parts.split('/')]\n\n count = 0\n for (path, dirs, files) in os.walk(FLAGS.image_data_dir):\n for filename in files:\n if filename[-4:] in ['.jpg', '.png']:\n image_id = int(filename.split('.')[0])\n filename = os.path.join(path, filename)\n\n output_name = os.path.join(FLAGS.output_path, '{}.npy'.format(image_id))\n if os.path.isfile(output_name):\n tf.logging.info('%s is there.', output_name)\n continue\n\n if image_id % part_total == part_at_i:\n count += 1\n if count % 1 == 0:\n tf.logging.info('On %i: %i', count, image_id)\n\n bgr = cv2.imread(filename, cv2.IMREAD_COLOR)\n\n # Resize image if neccessary.\n height, width = bgr.shape[0], bgr.shape[1]\n if height / width >= 2.2:\n width = int(height / 2.2)\n bgr = cv2.resize(bgr, (width, height))\n elif width / height >= 2.2:\n height = int(width / 2.2)\n bgr = cv2.resize(bgr, (width, height))\n max_size = 500\n if max(height, width) > max_size:\n ratio = max(height, width) / max_size\n height = int(height / ratio)\n width = int(width/ ratio)\n bgr = cv2.resize(bgr, (width, height))\n height, width = bgr.shape[0], bgr.shape[1]\n\n ss.setBaseImage(bgr)\n #ss.switchToSelectiveSearchFast()\n ss.switchToSelectiveSearchQuality()\n rects = ss.process()\n\n rects = np.stack(\n [rect for rect in rects if rect[2] >= 20 and rect[3] >= 20], axis=0)\n\n x, y, w, h = [rects[:, i] for i in range(4)]\n proposals = np.stack(\n [y / height, x / width, (y + h) / height, (x + w) / width], axis=-1)\n\n # Write output file.\n with open(output_name, 'wb') as out_fid:\n np.save(out_fid, proposals)\n\n\nif __name__ == '__main__':\n tf.app.run()\n","sub_path":"tools/create_ads_selective_search_data.py","file_name":"create_ads_selective_search_data.py","file_ext":"py","file_size_in_byte":5615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"268667561","text":"from typing import Dict, List, Tuple\nimport logging\nimport faiss\nimport numpy as np\nimport torch\n\nlogger = logging.getLogger(__name__)\n\n\nclass FaissExactKNNIndex:\n def __init__(self, vectors: Dict[str, torch.Tensor], normalize: bool = True, omp_num_threads: int = 1):\n \"\"\"\n Initializes a FAISS flat-IP index\n :param vectors: Dictionary of ids and vectors.\n :param m: HNSW specific parameter\n :param efConstruction: HNSW specific parameter\n :param efSearch: HNSW specific parameter\n :param normalize Normalize vectors, this turns a inner-product index into a cos index\n \"\"\"\n try:\n dim = list(vectors.values())[0].shape[0]\n except KeyError:\n raise Exception(\"Could not create index, it seems that there were no vectors given.\")\n faiss.omp_set_num_threads(omp_num_threads)\n self.index = faiss.IndexFlatIP(dim)\n self.index.metric_type = faiss.METRIC_INNER_PRODUCT\n self.normalize = normalize\n self.idx2id = list()\n ids, vecs = list(zip(*map(lambda d: (d[0], d[1]), vectors.items())))\n vecs = torch.stack(vecs).numpy()\n if self.normalize:\n vecs = vecs / np.linalg.norm(vecs, ord=2, axis=1, keepdims=True)\n self.index.add(vecs)\n self.idx2id = ids\n\n def get_knn_ids_for_vector(self, query_vec: torch.Tensor, k=1) -> List[Tuple[str, float]]:\n \"\"\"\n Returns a sorted list of k neighbors for query_vec\n :param query_vec:\n :param k:\n :return: A list of tuples (id, distance) (yes distance not similarity)\n \"\"\"\n results = list()\n query_vec = query_vec.cpu().numpy().reshape(1, -1)\n if self.normalize:\n query_vec = query_vec / np.linalg.norm(query_vec, ord=2, keepdims=True)\n d, i = self.index.search(query_vec, k=k)\n for distance, idx in zip(np.nditer(d), np.nditer(i)):\n idx_item = idx.item()\n if idx_item == -1: # if k>number of vectors then it will begin returning -1 as idx\n break\n results.append((self.idx2id[idx_item], 1-distance.item()))\n return results\n\n def __len__(self):\n return len(self.idx2id)\n","sub_path":"src/biencodernel/knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"462863785","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nauthor: Jan C. Brammer \n\"\"\"\n\nimport numpy as np\nimport dateutil\n\n\ndef isotimes_to_relativetimes(df):\n \"\"\"Convert the df's \"timestamp\" column from ISO timeformat to seconds\n elapsed since first timestamp.\n\n Parameters\n ----------\n df : DataFrame\n Containing three (or four) columns: event, value, timestamp,\n (physiosample).\n\n Returns\n -------\n df : DataFrame\n Mutated DataFrame.\n \"\"\"\n isotimes = [dateutil.parser.parse(i) for i in df[\"timestamp\"]] # parser returns a datetime.datetime object\n # specify time in seconds relative to the first timestamp\n t_zero = isotimes[0]\n relativetimes = np.asarray([(i - t_zero).total_seconds() for i in isotimes])\n df[\"timestamp\"] = relativetimes\n\n return df\n\n\ndef relativetimes_to_physiosamples(df, drop_rows_after_last_physiosample=False):\n \"\"\"Convert the df's \"timestamp\" column to samples that are aligned with the\n synchronization samples from the physiological recording. Append the\n samples to the df in a \"physiosample\" column.\n\n Parameters\n ----------\n df : DataFrame\n Containing three columns: event, value, timestamp.\n drop_rows_after_last_physiosample : bool, optional\n Whether or not to drop the events that have been recorded after the\n physiological recording has been stopped.\n\n Returns\n -------\n df : DataFrame\n Mutated DataFrame containing four columns: event, value, timestamp,\n physiosample.\n \"\"\"\n phys_sec = get_eventtimes(df, \"bitalino.synchronize\")\n phys_samp = get_eventvalues(df, \"bitalino.synchronize\")\n\n # Get number of samples per second (slope), and number of samples elapsed\n # between the start of the physiological recording and the first event in the\n # events file (intcpt).\n slope, intcpt = np.polyfit(phys_sec, phys_samp, 1)\n\n # Convert the seconds at which the events occur to their corresponding samples\n # in the physiological recording.\n events_samp = np.rint(intcpt + df[\"timestamp\"] * slope).astype(int)\n df[\"physiosample\"] = events_samp\n\n # Make sure that the conversion from seconds to samples is correct by asserting\n # that the \"timestamp\" entries and \"physiosample\" entires of the\n # \"bitalino.synchronize\" events are identical within a tolerance (rounding).\n assert np.allclose(phys_samp,\n get_eventtimes(df, \"bitalino.synchronize\", as_sample=True),\n atol=phys_samp.size)\n\n if drop_rows_after_last_physiosample:\n drop_idcs = list(np.where(events_samp > phys_samp.max())[0])\n df.drop(drop_idcs, inplace=True)\n df.reset_index(inplace=True, drop=True)\n\n return df\n\n\ndef specify_unityevents(df):\n \"\"\"Replace the generic \"UnityEvent\" strings in the df's \"event\" column with\n the associated specific event strings in the df's \"value\" column.\n\n Parameters\n ----------\n df : DataFrame\n Containing three (or four) columns: event, value, timestamp,\n (physiosample).\n\n Returns\n -------\n df : DataFrame\n Mutated DataFrame.\n \"\"\"\n unityevent_idcs = df[\"event\"] == \"UnityEvent\"\n unityevent_names = df.loc[unityevent_idcs, \"value\"]\n # Specific event name is the third value of the semicolon-separated string.\n unityevent_names = [i.split(\";\")[2] for i in unityevent_names]\n df.loc[unityevent_idcs, \"event\"] = unityevent_names\n\n return df\n\n\ndef ibis_to_ms(df):\n \"\"\"Convert IBIs in 1/1024 sec format to milliseconds.\n IMPORTANT: Polar H10 (H9) records IBIs in 1/1024 seconds format, i.e. not\n milliseconds!\n\n Parameters\n ----------\n df : DataFrame\n Containing three (or four) columns: event, value, timestamp,\n (physiosample).\n\n Returns\n -------\n df : DataFrame\n Mutated DataFrame.\n \"\"\"\n ibis_idcs = df[\"event\"] == \"InterBeatInterval\"\n ibis_ms = df.loc[ibis_idcs, \"value\"].to_numpy(dtype=\"int\") / 1024 * 1000\n df.loc[ibis_idcs, \"value\"] = ibis_ms\n\n return df\n\n\ndef format_events(df):\n \"\"\"Format the df for further processing.\n For details on the formatting steps see docstrings of\n isotimes_to_relativetimes(), relativetimes_to_physiosamples(),\n specify_unityevents(), and ibis_to_ms().\n\n Parameters\n ----------\n df : DataFrame\n Containing three columns: event, value, timestamp.\n\n Returns\n -------\n df : DataFrame\n Mutated DataFrame.\n \"\"\"\n df = isotimes_to_relativetimes(df)\n df = relativetimes_to_physiosamples(df, drop_rows_after_last_physiosample=True)\n df = specify_unityevents(df)\n df = ibis_to_ms(df)\n\n return df\n\n\ndef get_eventtimes(df, event, as_sample=False):\n \"\"\"Return all occurences of an event (in seconds or samples).\n Return df's entries of \"timestamp\" or \"physiosample\" column for a specific\n event.\n\n Parameters\n ----------\n df : DataFrame\n Containing four columns: event, value, timestamp, physiosample.\n event : string\n Name of the event.\n as_sample : bool, optional\n Whether to return occurences of event as samples. If False (default),\n return the occurences in seconds.\n\n Returns\n -------\n t : array\n All occurences of the requested event (either seconds or samples).\n \"\"\"\n event_idcs = df[\"event\"] == event\n if not as_sample:\n t = df.loc[event_idcs, \"timestamp\"]\n t = t.to_numpy(dtype=float)\n if as_sample:\n t = df.loc[event_idcs, \"physiosample\"]\n t = t.to_numpy(dtype=int) # in case the timestamps have already been converted to samples\n\n return t\n\n\ndef get_eventvalues(df, event):\n \"\"\"Return entires of df's \"value\" column for a specific event.\n\n Parameters\n ----------\n df : DataFrame\n Containing three (or four) columns: event, value, timestamp,\n (physiosample).\n event : string\n Name of the event.\n\n Returns\n -------\n v : array\n All entries of the df's \"value\" column for the requested event.\n \"\"\"\n event_idcs = df[\"event\"] == event\n v = df.loc[event_idcs, \"value\"].to_numpy(dtype=float)\n\n return v\n","sub_path":"biofeedback_analyses/analysis_utils/event_utils.py","file_name":"event_utils.py","file_ext":"py","file_size_in_byte":6189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"619567909","text":"import requests\nfrom bs4 import BeautifulSoup\nimport re\n\nfrom supps.models import Product\nfrom supps.extensions import db\n\n\ndef scrape_vitamin_shoppe_preworkout():\n url = 'http://www.vitaminshoppe.com/c/pre-workout-formulas/N-8f7'\n\n r = requests.get(url)\n soup = BeautifulSoup(r.content, \"lxml\")\n\n rows_logged = 0\n\n gen = soup.find_all('div', {'class': 'listing'})\n\n for item in gen:\n\n product = Product()\n\n # Dealer Name\n website = 'Vitamin Shoppe'\n product.product_dealer = website\n\n # Get the product name\n product_name = item.find_all('span', {'itemprop': 'name'})[0].text\n product.product_name = product_name\n\n # Get product manufacturer\n prod_manufacturer = item.find_all('span', {'itemprop': 'brand'})[0].text\n product.product_manufacturer = prod_manufacturer.split()[0]\n\n # Get Product Link\n url_ext = item.find_all('a', {'class': 'gray-link'})[0].get('href')\n link = 'https://www.vitaminshoppe.com%s' % url_ext\n product.product_url = link\n\n # Get Product Price\n dollar = item.find_all('span', {'class': 'price-column'})[0].find('span', {'class': 'main-value'}).text\n cent = item.find_all('span', {'class': 'price-column'})[0].find_all('span', {'class': 'sub'})[1].text\n product_price = ('{}{}'.format(dollar, cent))\n product.product_price = product_price\n\n # Product Image\n image = item.find_all('img')[0].get('src')\n product.product_image = image\n\n # Price per serving\n try:\n prod_weight = re.findall(r\"[-+]?\\d*\\.\\d+|\\d+\", product_name)[-1]\n prod_weight = float(prod_weight)\n product_price = float(product_price)\n\n if float(prod_weight) > 100:\n pps = 999\n else:\n\n try:\n pps = (format(product_price / prod_weight, '.2f'))\n except:\n pps = 999\n except ValueError:\n pps = 999\n\n product.product_price_per_serving = pps\n\n # type of protein\n prod_type = \"Pre-Workout\"\n product.product_type = prod_type\n\n db.session.add(product)\n db.session.commit()\n\n rows_logged += 1\n\n print(\"logged {} rows\".format(rows_logged))","sub_path":"supps/tasks/vit_shoppe/vs_preworkout.py","file_name":"vs_preworkout.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"181774698","text":"\nimport os\nimport time\nimport dateutil.relativedelta\nimport mysql.connector\nfrom datetime import datetime, date\n\nnew_conn = mysql.connector.connect(host='192.168.50.151',user='search',password='search@zyxr.com', database='invest')\nnew_cursor = new_conn.cursor(dictionary=True)\n\n\ndef findDiff():\n with open(os.path.abspath(os.curdir) + '/updateExpect', 'a+') as f:\n sql=\"select a.asset_id,a.investment_id,b.expect_interest,b.expect_add_interest,a.create_time from invest.t_investments a,specialDB.t_new_financial_plan_payoff b where a.asset_id=b.asset_id and a.investment_id=b.investment_id and (a.expect_interest != b.expect_interest or a.expect_add_interest != b.expect_add_interest);\"\n new_cursor.execute(sql)\n results = new_cursor.fetchall()\n for result in results:\n assetId=result[\"asset_id\"]\n assetIdSuffix=str(assetId)[-2:]\n investId=result[\"investment_id\"]\n investIdSuffix=str(investId)[-2:]\n expectInterest=result[\"expect_interest\"]\n expectAddInterest=result[\"expect_add_interest\"]\n sql1 = str.format(\n \"update invest.t_investment_%s set expect_interest=%d,expect_add_interest=%d where asset_id = %d and asset_type = 1 and investment_id = %d ;\" %\n (investIdSuffix, expectInterest, expectAddInterest, assetId, investId))\n sql2 = str.format(\n \"update product.t_investment_%s set expect_interest=%d,expect_add_interest=%d where asset_id = %d and asset_type = 1 and investment_id = %d ;\" %\n (assetIdSuffix, expectInterest, expectAddInterest, assetId, investId))\n sql3 = str.format(\n \"update financial_plan.t_investment_%s set expect_interest =%d,expect_add_interest=%d where asset_id= %d and asset_type = 1 and investment_id = %d ;\" %\n (assetIdSuffix, expectInterest, expectAddInterest, assetId, investId))\n sqls = str.format(\n \"update invest.t_investments set expect_interest=%d,expect_add_interest=%d where asset_id = %d and asset_type = 1 and investment_id = %d ; \" %\n (expectInterest, expectAddInterest, assetId, investId))\n # print(sql1)\n # print(sql2)\n # print(sql3)\n # print(sqls)\n f.write(sql1 + \"\\n\")\n f.write(sql2 + \"\\n\")\n f.write(sql3 + \"\\n\")\n f.write(sqls + \"\\n\")\n\n\nif __name__ == \"__main__\" :\n findDiff()\n\n\n","sub_path":"python_self/工作/专门修复王武问题(已经解决)/16理财计划满标放款时插入expect字段(已经修复)/用理财计划的回款表更新投资记录expect.py","file_name":"用理财计划的回款表更新投资记录expect.py","file_ext":"py","file_size_in_byte":2484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"573526163","text":"# -*- coding:utf-8 -*-\n# Date : (Sta Dec 22 18:46:05 2018 +0800)\n# Author : Rory Xiang\nimport sys\nsys.path.append(\"..\")\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\nfrom liner_regression.regression import stand_regres, lwlr\nfrom Predict.standrd_data import (get_stanred_x_y_arr, get_origin_x_y_arr,\n get_everyday_origin_x_y_arr,\n get_everyday_stanred_x_y_arr)\nfrom liner_regression.ridge_regression import rigre_regression, stage_wise\n\n\ndef predict_by_liner_regression(xarr, yarr, xtest):\n ws = stand_regres(xarr, yarr)\n c = np.sum(xtest * ws)\n return c\n\n\ndef predict_by_lwlr(xarr, yarr, xtest):\n c = lwlr(xtest, xarr, yarr)\n return np.sum(c)\n\n\ndef predict_by_rigre_regression(xarr, yarr, xtest):\n ws = stand_regres(xarr, yarr) # 标准岭回归\n # ws = stage_wise(xarr, yarr) # 前向逐步回归\n c = np.sum(xtest * ws)\n return c\n\n\nif __name__ == '__main__':\n xtest = [30, 38, 166806]\n # xtest = [30, 214, 218803]\n xtest = np.mat(xtest)\n xarr, yarr = get_origin_x_y_arr()\n stand_x, stnd_y = get_stanred_x_y_arr()\n\n # xtest = [1, 381243]\n # xarr, yarr = get_everyday_origin_x_y_arr()\n # stand_x, stnd_y = get_everyday_stanred_x_y_arr()\n\n # liner -----------------------------------\n salse = predict_by_liner_regression(xarr, yarr, xtest)\n stand_salse = predict_by_liner_regression(stand_x, stnd_y, xtest)\n\n # regre------------------------------------\n rigre_salse = predict_by_rigre_regression(xarr, yarr, xtest)\n rigre_stand_salse = predict_by_rigre_regression(stand_x, stnd_y, xtest)\n\n # lwlr-------------------------------------\n lwlr_salse = predict_by_lwlr(stand_x, stnd_y, xtest)\n\n print(\"# liner------------------------------------\")\n print(salse, stand_salse)\n print(\"# regre------------------------------------\")\n print(rigre_salse, rigre_stand_salse)\n print(\"# lwlr------------------------------------\")\n print(lwlr_salse)\n\n # rigre------------------------------------------------\n rigre_ws = rigre_regression(stand_x, stnd_y)\n rigre_salse = np.sum(rigre_ws * xtest)\n rigre_ws_ = rigre_regression(xarr, yarr)\n rigre_salse_ = np.sum(rigre_ws_ * xtest)\n print(\"# rigre------------------------------------\")\n print(rigre_salse_, rigre_salse)\n\n # stage_wise---------------------------------------------\n stage_ws = stage_wise(stand_x, stnd_y)\n stage_ssalse = np.sum(stage_ws * xtest)\n print(\"# stage_wise------------------------------------\")\n print(stage_ssalse)\n\n","sub_path":"Predict/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":2633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"21755489","text":"# -*- coding: utf-8 -*-\nimport os\nimport json\nimport requests\n\n\ndef call_vision_api(image_filename, api_keys):\n\tapi_key = api_keys['imagga']['api_key']\n\tapi_secret = api_keys['imagga']['api_secret']\n\t\n\t# image_filename = os.path.abspath(image_filename)\n\t\n\tresponse = requests.post('https://api.imagga.com/v1/content',\n\t\t\tauth=(api_key, api_secret),\n\t\t\tfiles={'image': open(image_filename, 'rb')})\n\n\tupload_result = response.json()\n\tcontent_id = upload_result['uploaded'][0]['id']\n\t\n\t# print (\"content id: %s\" % content_id)\n\t\n\tresponse = requests.get('https://api.imagga.com/v1/tagging?content=%s' % content_id, auth=(api_key, api_secret))\n\t\n\t# print response.text\n\t\n\treturn json.loads(response.text)\n\n\ndef get_standardized_result(api_result):\n output = {\n 'tags' : [],\n }\n\n if 'unsuccessful' in api_result:\n output['tags'].append((\"error: \" + api_result['unsuccessful'][0]['message'], None))\n elif 'results' in api_result:\n api_result = api_result[\"results\"][0]\n for tag_data in api_result['tags']:\n output['tags'].append((tag_data['tag'], tag_data['confidence'] / 100))\n else:\n output['tags'].append(('unknown error', None))\n\n return output\n\n\t","sub_path":"vendors/imagga.py","file_name":"imagga.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"147966871","text":"from _template import SortTemplate\n\n\nclass InsertionSort(SortTemplate):\n\n def sort(self):\n for i in range(1, len(self.arr)):\n for j in range(i, 0, -1):\n if self.arr[j] < self.arr[j-1]:\n self.exch(j, j - 1)\n else:\n break\n","sub_path":"src/sorting/insertion_sort.py","file_name":"insertion_sort.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"466716211","text":"# ##### BEGIN GPL LICENSE BLOCK #####\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software Foundation,\n# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n# ##### END GPL LICENSE BLOCK #####\n\n# \n\"\"\"\"Nodes based User interface for shaders exported to POV textures.\"\"\"\nimport bpy\n\nfrom bpy.utils import register_class, unregister_class\nfrom bpy.types import Menu, Node, NodeSocket, CompositorNodeTree, TextureNodeTree, Operator\nfrom bpy.props import (\n StringProperty,\n BoolProperty,\n IntProperty,\n FloatProperty,\n FloatVectorProperty,\n EnumProperty,\n)\nimport nodeitems_utils\nfrom nodeitems_utils import NodeCategory, NodeItem\n\n\n###############################################################################\n# Pov Nodes init\n###############################################################################\n\n\nclass PovraySocketUniversal(NodeSocket):\n bl_idname = \"PovraySocketUniversal\"\n bl_label = \"Povray Socket\"\n value_unlimited: bpy.props.FloatProperty(default=0.0)\n value_0_1: bpy.props.FloatProperty(min=0.0, max=1.0, default=0.0)\n value_0_10: bpy.props.FloatProperty(min=0.0, max=10.0, default=0.0)\n value_000001_10: bpy.props.FloatProperty(min=0.000001, max=10.0, default=0.0)\n value_1_9: bpy.props.IntProperty(min=1, max=9, default=1)\n value_0_255: bpy.props.IntProperty(min=0, max=255, default=0)\n percent: bpy.props.FloatProperty(min=0.0, max=100.0, default=0.0)\n\n def draw(self, context, layout, node, text):\n space = context.space_data\n tree = space.edit_tree\n links = tree.links\n if self.is_linked:\n value = []\n for link in links:\n if link.from_node == node:\n inps = link.to_node.inputs\n for inp in inps:\n if inp.bl_idname == \"PovraySocketFloat_0_1\" and inp.is_linked:\n prop = \"value_0_1\"\n if prop not in value:\n value.append(prop)\n if inp.bl_idname == \"PovraySocketFloat_000001_10\" and inp.is_linked:\n prop = \"value_000001_10\"\n if prop not in value:\n value.append(prop)\n if inp.bl_idname == \"PovraySocketFloat_0_10\" and inp.is_linked:\n prop = \"value_0_10\"\n if prop not in value:\n value.append(prop)\n if inp.bl_idname == \"PovraySocketInt_1_9\" and inp.is_linked:\n prop = \"value_1_9\"\n if prop not in value:\n value.append(prop)\n if inp.bl_idname == \"PovraySocketInt_0_255\" and inp.is_linked:\n prop = \"value_0_255\"\n if prop not in value:\n value.append(prop)\n if inp.bl_idname == \"PovraySocketFloatUnlimited\" and inp.is_linked:\n prop = \"value_unlimited\"\n if prop not in value:\n value.append(prop)\n if len(value) == 1:\n layout.prop(self, \"%s\" % value[0], text=text)\n else:\n layout.prop(self, \"percent\", text=\"Percent\")\n else:\n layout.prop(self, \"percent\", text=text)\n\n def draw_color(self, context, node):\n return (1, 0, 0, 1)\n\n\nclass PovraySocketFloat_0_1(NodeSocket):\n bl_idname = \"PovraySocketFloat_0_1\"\n bl_label = \"Povray Socket\"\n default_value: bpy.props.FloatProperty(\n description=\"Input node Value_0_1\", min=0, max=1, default=0\n )\n\n def draw(self, context, layout, node, text):\n if self.is_linked:\n layout.label(text=text)\n else:\n layout.prop(self, \"default_value\", text=text, slider=True)\n\n def draw_color(self, context, node):\n return (0.5, 0.7, 0.7, 1)\n\n\nclass PovraySocketFloat_0_10(NodeSocket):\n bl_idname = \"PovraySocketFloat_0_10\"\n bl_label = \"Povray Socket\"\n default_value: bpy.props.FloatProperty(\n description=\"Input node Value_0_10\", min=0, max=10, default=0\n )\n\n def draw(self, context, layout, node, text):\n if node.bl_idname == \"ShaderNormalMapNode\" and node.inputs[2].is_linked:\n layout.label(text=\"\")\n self.hide_value = True\n if self.is_linked:\n layout.label(text=text)\n else:\n layout.prop(self, \"default_value\", text=text, slider=True)\n\n def draw_color(self, context, node):\n return (0.65, 0.65, 0.65, 1)\n\n\nclass PovraySocketFloat_10(NodeSocket):\n bl_idname = \"PovraySocketFloat_10\"\n bl_label = \"Povray Socket\"\n default_value: bpy.props.FloatProperty(\n description=\"Input node Value_10\", min=-10, max=10, default=0\n )\n\n def draw(self, context, layout, node, text):\n if node.bl_idname == \"ShaderNormalMapNode\" and node.inputs[2].is_linked:\n layout.label(text=\"\")\n self.hide_value = True\n if self.is_linked:\n layout.label(text=text)\n else:\n layout.prop(self, \"default_value\", text=text, slider=True)\n\n def draw_color(self, context, node):\n return (0.65, 0.65, 0.65, 1)\n\n\nclass PovraySocketFloatPositive(NodeSocket):\n bl_idname = \"PovraySocketFloatPositive\"\n bl_label = \"Povray Socket\"\n default_value: bpy.props.FloatProperty(\n description=\"Input Node Value Positive\", min=0.0, default=0\n )\n\n def draw(self, context, layout, node, text):\n if self.is_linked:\n layout.label(text=text)\n else:\n layout.prop(self, \"default_value\", text=text, slider=True)\n\n def draw_color(self, context, node):\n return (0.045, 0.005, 0.136, 1)\n\n\nclass PovraySocketFloat_000001_10(NodeSocket):\n bl_idname = \"PovraySocketFloat_000001_10\"\n bl_label = \"Povray Socket\"\n default_value: bpy.props.FloatProperty(min=0.000001, max=10, default=0.000001)\n\n def draw(self, context, layout, node, text):\n if self.is_output or self.is_linked:\n layout.label(text=text)\n else:\n layout.prop(self, \"default_value\", text=text, slider=True)\n\n def draw_color(self, context, node):\n return (1, 0, 0, 1)\n\n\nclass PovraySocketFloatUnlimited(NodeSocket):\n bl_idname = \"PovraySocketFloatUnlimited\"\n bl_label = \"Povray Socket\"\n default_value: bpy.props.FloatProperty(default=0.0)\n\n def draw(self, context, layout, node, text):\n if self.is_linked:\n layout.label(text=text)\n else:\n layout.prop(self, \"default_value\", text=text, slider=True)\n\n def draw_color(self, context, node):\n return (0.7, 0.7, 1, 1)\n\n\nclass PovraySocketInt_1_9(NodeSocket):\n bl_idname = \"PovraySocketInt_1_9\"\n bl_label = \"Povray Socket\"\n default_value: bpy.props.IntProperty(\n description=\"Input node Value_1_9\", min=1, max=9, default=6\n )\n\n def draw(self, context, layout, node, text):\n if self.is_linked:\n layout.label(text=text)\n else:\n layout.prop(self, \"default_value\", text=text)\n\n def draw_color(self, context, node):\n return (1, 0.7, 0.7, 1)\n\n\nclass PovraySocketInt_0_256(NodeSocket):\n bl_idname = \"PovraySocketInt_0_256\"\n bl_label = \"Povray Socket\"\n default_value: bpy.props.IntProperty(min=0, max=255, default=0)\n\n def draw(self, context, layout, node, text):\n if self.is_linked:\n layout.label(text=text)\n else:\n layout.prop(self, \"default_value\", text=text)\n\n def draw_color(self, context, node):\n return (0.5, 0.5, 0.5, 1)\n\n\nclass PovraySocketPattern(NodeSocket):\n bl_idname = \"PovraySocketPattern\"\n bl_label = \"Povray Socket\"\n\n default_value: bpy.props.EnumProperty(\n name=\"Pattern\",\n description=\"Select the pattern\",\n items=(\n (\"boxed\", \"Boxed\", \"\"),\n (\"brick\", \"Brick\", \"\"),\n (\"cells\", \"Cells\", \"\"),\n (\"checker\", \"Checker\", \"\"),\n (\"granite\", \"Granite\", \"\"),\n (\"leopard\", \"Leopard\", \"\"),\n (\"marble\", \"Marble\", \"\"),\n (\"onion\", \"Onion\", \"\"),\n (\"planar\", \"Planar\", \"\"),\n (\"quilted\", \"Quilted\", \"\"),\n (\"ripples\", \"Ripples\", \"\"),\n (\"radial\", \"Radial\", \"\"),\n (\"spherical\", \"Spherical\", \"\"),\n (\"spotted\", \"Spotted\", \"\"),\n (\"waves\", \"Waves\", \"\"),\n (\"wood\", \"Wood\", \"\"),\n (\"wrinkles\", \"Wrinkles\", \"\"),\n ),\n default=\"granite\",\n )\n\n def draw(self, context, layout, node, text):\n if self.is_output or self.is_linked:\n layout.label(text=\"Pattern\")\n else:\n layout.prop(self, \"default_value\", text=text)\n\n def draw_color(self, context, node):\n return (1, 1, 1, 1)\n\n\nclass PovraySocketColor(NodeSocket):\n bl_idname = \"PovraySocketColor\"\n bl_label = \"Povray Socket\"\n\n default_value: FloatVectorProperty(\n precision=4,\n step=0.01,\n min=0,\n soft_max=1,\n default=(0.0, 0.0, 0.0),\n options={\"ANIMATABLE\"},\n subtype=\"COLOR\",\n )\n\n def draw(self, context, layout, node, text):\n if self.is_output or self.is_linked:\n layout.label(text=text)\n else:\n layout.prop(self, \"default_value\", text=text)\n\n def draw_color(self, context, node):\n return (1, 1, 0, 1)\n\n\nclass PovraySocketColorRGBFT(NodeSocket):\n bl_idname = \"PovraySocketColorRGBFT\"\n bl_label = \"Povray Socket\"\n\n default_value: FloatVectorProperty(\n precision=4,\n step=0.01,\n min=0,\n soft_max=1,\n default=(0.0, 0.0, 0.0),\n options={\"ANIMATABLE\"},\n subtype=\"COLOR\",\n )\n f: bpy.props.FloatProperty(default=0.0, min=0.0, max=1.0)\n t: bpy.props.FloatProperty(default=0.0, min=0.0, max=1.0)\n\n def draw(self, context, layout, node, text):\n if self.is_output or self.is_linked:\n layout.label(text=text)\n else:\n layout.prop(self, \"default_value\", text=text)\n\n def draw_color(self, context, node):\n return (1, 1, 0, 1)\n\n\nclass PovraySocketTexture(NodeSocket):\n bl_idname = \"PovraySocketTexture\"\n bl_label = \"Povray Socket\"\n default_value: bpy.props.IntProperty()\n\n def draw(self, context, layout, node, text):\n layout.label(text=text)\n\n def draw_color(self, context, node):\n return (0, 1, 0, 1)\n\n\nclass PovraySocketTransform(NodeSocket):\n bl_idname = \"PovraySocketTransform\"\n bl_label = \"Povray Socket\"\n default_value: bpy.props.IntProperty(min=0, max=255, default=0)\n\n def draw(self, context, layout, node, text):\n layout.label(text=text)\n\n def draw_color(self, context, node):\n return (99 / 255, 99 / 255, 199 / 255, 1)\n\n\nclass PovraySocketNormal(NodeSocket):\n bl_idname = \"PovraySocketNormal\"\n bl_label = \"Povray Socket\"\n default_value: bpy.props.IntProperty(min=0, max=255, default=0)\n\n def draw(self, context, layout, node, text):\n layout.label(text=text)\n\n def draw_color(self, context, node):\n return (0.65, 0.65, 0.65, 1)\n\n\nclass PovraySocketSlope(NodeSocket):\n bl_idname = \"PovraySocketSlope\"\n bl_label = \"Povray Socket\"\n default_value: bpy.props.FloatProperty(min=0.0, max=1.0)\n height: bpy.props.FloatProperty(min=0.0, max=10.0)\n slope: bpy.props.FloatProperty(min=-10.0, max=10.0)\n\n def draw(self, context, layout, node, text):\n if self.is_output or self.is_linked:\n layout.label(text=text)\n else:\n layout.prop(self, \"default_value\", text=\"\")\n layout.prop(self, \"height\", text=\"\")\n layout.prop(self, \"slope\", text=\"\")\n\n def draw_color(self, context, node):\n return (0, 0, 0, 1)\n\n\nclass PovraySocketMap(NodeSocket):\n bl_idname = \"PovraySocketMap\"\n bl_label = \"Povray Socket\"\n default_value: bpy.props.StringProperty()\n\n def draw(self, context, layout, node, text):\n layout.label(text=text)\n\n def draw_color(self, context, node):\n return (0.2, 0, 0.2, 1)\n\n\nclass PovrayShaderNodeCategory(NodeCategory):\n @classmethod\n def poll(cls, context):\n return context.space_data.tree_type == \"ObjectNodeTree\"\n\n\nclass PovrayTextureNodeCategory(NodeCategory):\n @classmethod\n def poll(cls, context):\n return context.space_data.tree_type == \"TextureNodeTree\"\n\n\nclass PovraySceneNodeCategory(NodeCategory):\n @classmethod\n def poll(cls, context):\n return context.space_data.tree_type == \"CompositorNodeTree\"\n\n\nnode_categories = [\n PovrayShaderNodeCategory(\"SHADEROUTPUT\", \"Output\", items=[NodeItem(\"PovrayOutputNode\")]),\n PovrayShaderNodeCategory(\"SIMPLE\", \"Simple texture\", items=[NodeItem(\"PovrayTextureNode\")]),\n PovrayShaderNodeCategory(\n \"MAPS\",\n \"Maps\",\n items=[\n NodeItem(\"PovrayBumpMapNode\"),\n NodeItem(\"PovrayColorImageNode\"),\n NodeItem(\"ShaderNormalMapNode\"),\n NodeItem(\"PovraySlopeNode\"),\n NodeItem(\"ShaderTextureMapNode\"),\n NodeItem(\"ShaderNodeValToRGB\"),\n ],\n ),\n PovrayShaderNodeCategory(\n \"OTHER\",\n \"Other patterns\",\n items=[NodeItem(\"PovrayImagePatternNode\"), NodeItem(\"ShaderPatternNode\")],\n ),\n PovrayShaderNodeCategory(\"COLOR\", \"Color\", items=[NodeItem(\"PovrayPigmentNode\")]),\n PovrayShaderNodeCategory(\n \"TRANSFORM\",\n \"Transform\",\n items=[\n NodeItem(\"PovrayMappingNode\"),\n NodeItem(\"PovrayMultiplyNode\"),\n NodeItem(\"PovrayModifierNode\"),\n NodeItem(\"PovrayTransformNode\"),\n NodeItem(\"PovrayValueNode\"),\n ],\n ),\n PovrayShaderNodeCategory(\n \"FINISH\",\n \"Finish\",\n items=[\n NodeItem(\"PovrayFinishNode\"),\n NodeItem(\"PovrayDiffuseNode\"),\n NodeItem(\"PovraySpecularNode\"),\n NodeItem(\"PovrayPhongNode\"),\n NodeItem(\"PovrayAmbientNode\"),\n NodeItem(\"PovrayMirrorNode\"),\n NodeItem(\"PovrayIridescenceNode\"),\n NodeItem(\"PovraySubsurfaceNode\"),\n ],\n ),\n PovrayShaderNodeCategory(\n \"CYCLES\",\n \"Cycles\",\n items=[\n NodeItem(\"ShaderNodeAddShader\"),\n NodeItem(\"ShaderNodeAmbientOcclusion\"),\n NodeItem(\"ShaderNodeAttribute\"),\n NodeItem(\"ShaderNodeBackground\"),\n NodeItem(\"ShaderNodeBlackbody\"),\n NodeItem(\"ShaderNodeBrightContrast\"),\n NodeItem(\"ShaderNodeBsdfAnisotropic\"),\n NodeItem(\"ShaderNodeBsdfDiffuse\"),\n NodeItem(\"ShaderNodeBsdfGlass\"),\n NodeItem(\"ShaderNodeBsdfGlossy\"),\n NodeItem(\"ShaderNodeBsdfHair\"),\n NodeItem(\"ShaderNodeBsdfRefraction\"),\n NodeItem(\"ShaderNodeBsdfToon\"),\n NodeItem(\"ShaderNodeBsdfTranslucent\"),\n NodeItem(\"ShaderNodeBsdfTransparent\"),\n NodeItem(\"ShaderNodeBsdfVelvet\"),\n NodeItem(\"ShaderNodeBump\"),\n NodeItem(\"ShaderNodeCameraData\"),\n NodeItem(\"ShaderNodeCombineHSV\"),\n NodeItem(\"ShaderNodeCombineRGB\"),\n NodeItem(\"ShaderNodeCombineXYZ\"),\n NodeItem(\"ShaderNodeEmission\"),\n NodeItem(\"ShaderNodeExtendedMaterial\"),\n NodeItem(\"ShaderNodeFresnel\"),\n NodeItem(\"ShaderNodeGamma\"),\n NodeItem(\"ShaderNodeGeometry\"),\n NodeItem(\"ShaderNodeGroup\"),\n NodeItem(\"ShaderNodeHairInfo\"),\n NodeItem(\"ShaderNodeHoldout\"),\n NodeItem(\"ShaderNodeHueSaturation\"),\n NodeItem(\"ShaderNodeInvert\"),\n NodeItem(\"ShaderNodeLampData\"),\n NodeItem(\"ShaderNodeLayerWeight\"),\n NodeItem(\"ShaderNodeLightFalloff\"),\n NodeItem(\"ShaderNodeLightPath\"),\n NodeItem(\"ShaderNodeMapping\"),\n NodeItem(\"ShaderNodeMaterial\"),\n NodeItem(\"ShaderNodeMath\"),\n NodeItem(\"ShaderNodeMixRGB\"),\n NodeItem(\"ShaderNodeMixShader\"),\n NodeItem(\"ShaderNodeNewGeometry\"),\n NodeItem(\"ShaderNodeNormal\"),\n NodeItem(\"ShaderNodeNormalMap\"),\n NodeItem(\"ShaderNodeObjectInfo\"),\n NodeItem(\"ShaderNodeOutput\"),\n NodeItem(\"ShaderNodeOutputLamp\"),\n NodeItem(\"ShaderNodeOutputLineStyle\"),\n NodeItem(\"ShaderNodeOutputMaterial\"),\n NodeItem(\"ShaderNodeOutputWorld\"),\n NodeItem(\"ShaderNodeParticleInfo\"),\n NodeItem(\"ShaderNodeRGB\"),\n NodeItem(\"ShaderNodeRGBCurve\"),\n NodeItem(\"ShaderNodeRGBToBW\"),\n NodeItem(\"ShaderNodeScript\"),\n NodeItem(\"ShaderNodeSeparateHSV\"),\n NodeItem(\"ShaderNodeSeparateRGB\"),\n NodeItem(\"ShaderNodeSeparateXYZ\"),\n NodeItem(\"ShaderNodeSqueeze\"),\n NodeItem(\"ShaderNodeSubsurfaceScattering\"),\n NodeItem(\"ShaderNodeTangent\"),\n NodeItem(\"ShaderNodeTexBrick\"),\n NodeItem(\"ShaderNodeTexChecker\"),\n NodeItem(\"ShaderNodeTexCoord\"),\n NodeItem(\"ShaderNodeTexEnvironment\"),\n NodeItem(\"ShaderNodeTexGradient\"),\n NodeItem(\"ShaderNodeTexImage\"),\n NodeItem(\"ShaderNodeTexMagic\"),\n NodeItem(\"ShaderNodeTexMusgrave\"),\n NodeItem(\"ShaderNodeTexNoise\"),\n NodeItem(\"ShaderNodeTexPointDensity\"),\n NodeItem(\"ShaderNodeTexSky\"),\n NodeItem(\"ShaderNodeTexVoronoi\"),\n NodeItem(\"ShaderNodeTexWave\"),\n NodeItem(\"ShaderNodeTexture\"),\n NodeItem(\"ShaderNodeUVAlongStroke\"),\n NodeItem(\"ShaderNodeUVMap\"),\n NodeItem(\"ShaderNodeValToRGB\"),\n NodeItem(\"ShaderNodeValue\"),\n NodeItem(\"ShaderNodeVectorCurve\"),\n NodeItem(\"ShaderNodeVectorMath\"),\n NodeItem(\"ShaderNodeVectorTransform\"),\n NodeItem(\"ShaderNodeVolumeAbsorption\"),\n NodeItem(\"ShaderNodeVolumeScatter\"),\n NodeItem(\"ShaderNodeWavelength\"),\n NodeItem(\"ShaderNodeWireframe\"),\n ],\n ),\n PovrayTextureNodeCategory(\n \"TEXTUREOUTPUT\",\n \"Output\",\n items=[NodeItem(\"TextureNodeValToRGB\"), NodeItem(\"TextureOutputNode\")],\n ),\n PovraySceneNodeCategory(\"ISOSURFACE\", \"Isosurface\", items=[NodeItem(\"IsoPropsNode\")]),\n PovraySceneNodeCategory(\"FOG\", \"Fog\", items=[NodeItem(\"PovrayFogNode\")]),\n]\n############### end nodes init\n############### nodes ui\n##############Nodes\n\n# def find_node_input(node, name):\n# for input in node.inputs:\n# if input.name == name:\n# return input\n\n# def panel_node_draw(layout, id_data, output_type, input_name):\n# if not id_data.use_nodes:\n# #layout.operator(\"pov.material_use_nodes\", icon='SOUND')#'NODETREE')\n# #layout.operator(\"pov.use_shading_nodes\", icon='NODETREE')\n# layout.operator(\"WM_OT_context_toggle\", icon='NODETREE').data_path = \\\n# \"material.pov.material_use_nodes\"\n# return False\n\n# ntree = id_data.node_tree\n\n# node = find_node(id_data, output_type)\n# if not node:\n# layout.label(text=\"No output node\")\n# else:\n# input = find_node_input(node, input_name)\n# layout.template_node_view(ntree, node, input)\n\n# return True\n\n\nclass NODE_MT_POV_map_create(Menu):\n \"\"\"Create maps\"\"\"\n\n bl_idname = \"POVRAY_MT_node_map_create\"\n bl_label = \"Create map\"\n\n def draw(self, context):\n layout = self.layout\n layout.operator(\"node.map_create\")\n\n\ndef menu_func_nodes(self, context):\n ob = context.object\n if hasattr(ob, 'active_material'):\n mat = context.object.active_material\n if mat and context.space_data.tree_type == 'ObjectNodeTree':\n self.layout.prop(mat.pov, \"material_use_nodes\")\n self.layout.menu(NODE_MT_POV_map_create.bl_idname)\n self.layout.operator(\"wm.updatepreviewkey\")\n if hasattr(mat, 'active_texture') and context.scene.render.engine == 'POVRAY_RENDER':\n tex = mat.active_texture\n if tex and context.space_data.tree_type == 'TextureNodeTree':\n self.layout.prop(tex.pov, \"texture_use_nodes\")\n\n\n############### object\n\n\nclass ObjectNodeTree(bpy.types.NodeTree):\n '''Povray Material Nodes'''\n\n bl_idname = 'ObjectNodeTree'\n bl_label = 'Povray Object Nodes'\n bl_icon = 'PLUGIN'\n\n @classmethod\n def poll(cls, context):\n return context.scene.render.engine == 'POVRAY_RENDER'\n\n @classmethod\n def get_from_context(cls, context):\n ob = context.active_object\n if ob and ob.type not in {'LIGHT'}:\n ma = ob.active_material\n if ma is not None:\n nt_name = ma.node_tree\n if nt_name != '':\n return nt_name, ma, ma\n return (None, None, None)\n\n def update(self):\n self.refresh = True\n\n\n################### output #############################################################################################\n\n\nclass PovrayOutputNode(Node, ObjectNodeTree):\n '''Output'''\n\n bl_idname = 'PovrayOutputNode'\n bl_label = 'Output'\n bl_icon = 'SHADING_TEXTURE'\n\n def init(self, context):\n\n self.inputs.new('PovraySocketTexture', \"Texture\")\n\n def draw_buttons(self, context, layout):\n\n ob = context.object\n layout.prop(ob.pov, \"object_ior\", slider=True)\n\n def draw_buttons_ext(self, context, layout):\n\n ob = context.object\n layout.prop(ob.pov, \"object_ior\", slider=True)\n\n def draw_label(self):\n return \"Output\"\n\n\n################### material ###########################################################################################\nclass PovrayTextureNode(Node, ObjectNodeTree):\n '''Texture'''\n\n bl_idname = 'PovrayTextureNode'\n bl_label = 'Simple texture'\n bl_icon = 'SHADING_TEXTURE'\n\n def init(self, context):\n\n color = self.inputs.new('PovraySocketColor', \"Pigment\")\n color.default_value = (1, 1, 1)\n normal = self.inputs.new('NodeSocketFloat', \"Normal\")\n normal.hide_value = True\n finish = self.inputs.new('NodeSocketVector', \"Finish\")\n finish.hide_value = True\n\n self.outputs.new('PovraySocketTexture', \"Texture\")\n\n def draw_label(self):\n return \"Simple texture\"\n\n\nclass PovrayFinishNode(Node, ObjectNodeTree):\n '''Finish'''\n\n bl_idname = 'PovrayFinishNode'\n bl_label = 'Finish'\n bl_icon = 'SHADING_TEXTURE'\n\n def init(self, context):\n\n self.inputs.new('PovraySocketFloat_0_1', \"Emission\")\n ambient = self.inputs.new('NodeSocketVector', \"Ambient\")\n ambient.hide_value = True\n diffuse = self.inputs.new('NodeSocketVector', \"Diffuse\")\n diffuse.hide_value = True\n specular = self.inputs.new('NodeSocketVector', \"Highlight\")\n specular.hide_value = True\n mirror = self.inputs.new('NodeSocketVector', \"Mirror\")\n mirror.hide_value = True\n iridescence = self.inputs.new('NodeSocketVector', \"Iridescence\")\n iridescence.hide_value = True\n subsurface = self.inputs.new('NodeSocketVector', \"Translucency\")\n subsurface.hide_value = True\n self.outputs.new('NodeSocketVector', \"Finish\")\n\n def draw_label(self):\n return \"Finish\"\n\n\nclass PovrayDiffuseNode(Node, ObjectNodeTree):\n '''Diffuse'''\n\n bl_idname = 'PovrayDiffuseNode'\n bl_label = 'Diffuse'\n bl_icon = 'MATSPHERE'\n\n def init(self, context):\n\n intensity = self.inputs.new('PovraySocketFloat_0_1', \"Intensity\")\n intensity.default_value = 0.8\n albedo = self.inputs.new('NodeSocketBool', \"Albedo\")\n albedo.default_value = False\n brilliance = self.inputs.new('PovraySocketFloat_0_10', \"Brilliance\")\n brilliance.default_value = 1.8\n self.inputs.new('PovraySocketFloat_0_1', \"Crand\")\n self.outputs.new('NodeSocketVector', \"Diffuse\")\n\n def draw_label(self):\n return \"Diffuse\"\n\n\nclass PovrayPhongNode(Node, ObjectNodeTree):\n '''Phong'''\n\n bl_idname = 'PovrayPhongNode'\n bl_label = 'Phong'\n bl_icon = 'MESH_UVSPHERE'\n\n def init(self, context):\n\n albedo = self.inputs.new('NodeSocketBool', \"Albedo\")\n intensity = self.inputs.new('PovraySocketFloat_0_1', \"Intensity\")\n intensity.default_value = 0.8\n phong_size = self.inputs.new('PovraySocketInt_0_256', \"Size\")\n phong_size.default_value = 60\n metallic = self.inputs.new('PovraySocketFloat_0_1', \"Metallic\")\n\n self.outputs.new('NodeSocketVector', \"Phong\")\n\n def draw_label(self):\n return \"Phong\"\n\n\nclass PovraySpecularNode(Node, ObjectNodeTree):\n '''Specular'''\n\n bl_idname = 'PovraySpecularNode'\n bl_label = 'Specular'\n bl_icon = 'MESH_UVSPHERE'\n\n def init(self, context):\n\n albedo = self.inputs.new('NodeSocketBool', \"Albedo\")\n intensity = self.inputs.new('PovraySocketFloat_0_1', \"Intensity\")\n intensity.default_value = 0.8\n roughness = self.inputs.new('PovraySocketFloat_0_1', \"Roughness\")\n roughness.default_value = 0.02\n metallic = self.inputs.new('PovraySocketFloat_0_1', \"Metallic\")\n\n self.outputs.new('NodeSocketVector', \"Specular\")\n\n def draw_label(self):\n return \"Specular\"\n\n\nclass PovrayMirrorNode(Node, ObjectNodeTree):\n '''Mirror'''\n\n bl_idname = 'PovrayMirrorNode'\n bl_label = 'Mirror'\n bl_icon = 'SHADING_TEXTURE'\n\n def init(self, context):\n\n color = self.inputs.new('PovraySocketColor', \"Color\")\n color.default_value = (1, 1, 1)\n metallic = self.inputs.new('PovraySocketFloat_0_1', \"Metallic\")\n metallic.default_value = 1.0\n exponent = self.inputs.new('PovraySocketFloat_0_1', \"Exponent\")\n exponent.default_value = 1.0\n self.inputs.new('PovraySocketFloat_0_1', \"Falloff\")\n self.inputs.new('NodeSocketBool', \"Fresnel\")\n self.inputs.new('NodeSocketBool', \"Conserve energy\")\n self.outputs.new('NodeSocketVector', \"Mirror\")\n\n def draw_label(self):\n return \"Mirror\"\n\n\nclass PovrayAmbientNode(Node, ObjectNodeTree):\n '''Ambient'''\n\n bl_idname = 'PovrayAmbientNode'\n bl_label = 'Ambient'\n bl_icon = 'SHADING_SOLID'\n\n def init(self, context):\n\n self.inputs.new('PovraySocketColor', \"Ambient\")\n\n self.outputs.new('NodeSocketVector', \"Ambient\")\n\n def draw_label(self):\n return \"Ambient\"\n\n\nclass PovrayIridescenceNode(Node, ObjectNodeTree):\n '''Iridescence'''\n\n bl_idname = 'PovrayIridescenceNode'\n bl_label = 'Iridescence'\n bl_icon = 'MESH_UVSPHERE'\n\n def init(self, context):\n\n amount = self.inputs.new('NodeSocketFloat', \"Amount\")\n amount.default_value = 0.25\n thickness = self.inputs.new('NodeSocketFloat', \"Thickness\")\n thickness.default_value = 1\n self.inputs.new('NodeSocketFloat', \"Turbulence\")\n\n self.outputs.new('NodeSocketVector', \"Iridescence\")\n\n def draw_label(self):\n return \"Iridescence\"\n\n\nclass PovraySubsurfaceNode(Node, ObjectNodeTree):\n '''Subsurface'''\n\n bl_idname = 'PovraySubsurfaceNode'\n bl_label = 'Subsurface'\n bl_icon = 'MESH_UVSPHERE'\n\n def init(self, context):\n\n translucency = self.inputs.new('NodeSocketColor', \"Translucency\")\n translucency.default_value = (0, 0, 0, 1)\n energy = self.inputs.new('PovraySocketInt_0_256', \"Energy\")\n energy.default_value = 20\n self.outputs.new('NodeSocketVector', \"Translucency\")\n\n def draw_buttons(self, context, layout):\n scene = context.scene\n layout.prop(scene.pov, \"sslt_enable\", text=\"SSLT\")\n\n def draw_buttons_ext(self, context, layout):\n scene = context.scene\n layout.prop(scene.pov, \"sslt_enable\", text=\"SSLT\")\n\n def draw_label(self):\n return \"Subsurface\"\n\n\n#####################################################################################################\n\n\nclass PovrayMappingNode(Node, ObjectNodeTree):\n '''Mapping'''\n\n bl_idname = 'PovrayMappingNode'\n bl_label = 'Mapping'\n bl_icon = 'NODE_TEXTURE'\n\n warp_type: EnumProperty(\n name=\"Warp Types\",\n description=\"Select the type of warp\",\n items=(\n ('cubic', \"Cubic\", \"\"),\n ('cylindrical', \"Cylindrical\", \"\"),\n ('planar', \"Planar\", \"\"),\n ('spherical', \"Spherical\", \"\"),\n ('toroidal', \"Toroidal\", \"\"),\n ('uv_mapping', \"UV\", \"\"),\n ('NONE', \"None\", \"No indentation\"),\n ),\n default='NONE',\n )\n\n warp_orientation: EnumProperty(\n name=\"Warp Orientation\",\n description=\"Select the orientation of warp\",\n items=(('x', \"X\", \"\"), ('y', \"Y\", \"\"), ('z', \"Z\", \"\")),\n default='y',\n )\n\n warp_dist_exp: FloatProperty(\n name=\"Distance exponent\", description=\"Distance exponent\", min=0.0, max=100.0, default=1.0\n )\n\n warp_tor_major_radius: FloatProperty(\n name=\"Major radius\",\n description=\"Torus is distance from major radius\",\n min=0.0,\n max=5.0,\n default=1.0,\n )\n\n def init(self, context):\n self.outputs.new('NodeSocketVector', \"Mapping\")\n\n def draw_buttons(self, context, layout):\n\n column = layout.column()\n column.prop(self, \"warp_type\", text=\"Warp type\")\n if self.warp_type in {'toroidal', 'spherical', 'cylindrical', 'planar'}:\n column.prop(self, \"warp_orientation\", text=\"Orientation\")\n column.prop(self, \"warp_dist_exp\", text=\"Exponent\")\n if self.warp_type == 'toroidal':\n column.prop(self, \"warp_tor_major_radius\", text=\"Major R\")\n\n def draw_buttons_ext(self, context, layout):\n\n column = layout.column()\n column.prop(self, \"warp_type\", text=\"Warp type\")\n if self.warp_type in {'toroidal', 'spherical', 'cylindrical', 'planar'}:\n column.prop(self, \"warp_orientation\", text=\"Orientation\")\n column.prop(self, \"warp_dist_exp\", text=\"Exponent\")\n if self.warp_type == 'toroidal':\n column.prop(self, \"warp_tor_major_radius\", text=\"Major R\")\n\n def draw_label(self):\n return \"Mapping\"\n\n\nclass PovrayMultiplyNode(Node, ObjectNodeTree):\n '''Multiply'''\n\n bl_idname = 'PovrayMultiplyNode'\n bl_label = 'Multiply'\n bl_icon = 'SHADING_SOLID'\n\n amount_x: FloatProperty(\n name=\"X\", description=\"Number of repeats\", min=1.0, max=10000.0, default=1.0\n )\n\n amount_y: FloatProperty(\n name=\"Y\", description=\"Number of repeats\", min=1.0, max=10000.0, default=1.0\n )\n\n amount_z: FloatProperty(\n name=\"Z\", description=\"Number of repeats\", min=1.0, max=10000.0, default=1.0\n )\n\n def init(self, context):\n self.outputs.new('NodeSocketVector', \"Amount\")\n\n def draw_buttons(self, context, layout):\n\n column = layout.column()\n column.label(text=\"Amount\")\n row = column.row(align=True)\n row.prop(self, \"amount_x\")\n row.prop(self, \"amount_y\")\n row.prop(self, \"amount_z\")\n\n def draw_buttons_ext(self, context, layout):\n\n column = layout.column()\n column.label(text=\"Amount\")\n row = column.row(align=True)\n row.prop(self, \"amount_x\")\n row.prop(self, \"amount_y\")\n row.prop(self, \"amount_z\")\n\n def draw_label(self):\n return \"Multiply\"\n\n\nclass PovrayTransformNode(Node, ObjectNodeTree):\n '''Transform'''\n\n bl_idname = 'PovrayTransformNode'\n bl_label = 'Transform'\n bl_icon = 'NODE_TEXTURE'\n\n def init(self, context):\n\n self.inputs.new('PovraySocketFloatUnlimited', \"Translate x\")\n self.inputs.new('PovraySocketFloatUnlimited', \"Translate y\")\n self.inputs.new('PovraySocketFloatUnlimited', \"Translate z\")\n self.inputs.new('PovraySocketFloatUnlimited', \"Rotate x\")\n self.inputs.new('PovraySocketFloatUnlimited', \"Rotate y\")\n self.inputs.new('PovraySocketFloatUnlimited', \"Rotate z\")\n sX = self.inputs.new('PovraySocketFloatUnlimited', \"Scale x\")\n sX.default_value = 1.0\n sY = self.inputs.new('PovraySocketFloatUnlimited', \"Scale y\")\n sY.default_value = 1.0\n sZ = self.inputs.new('PovraySocketFloatUnlimited', \"Scale z\")\n sZ.default_value = 1.0\n\n self.outputs.new('NodeSocketVector', \"Transform\")\n\n def draw_label(self):\n return \"Transform\"\n\n\nclass PovrayValueNode(Node, ObjectNodeTree):\n '''Value'''\n\n bl_idname = 'PovrayValueNode'\n bl_label = 'Value'\n bl_icon = 'SHADING_SOLID'\n\n def init(self, context):\n\n self.outputs.new('PovraySocketUniversal', \"Value\")\n\n def draw_label(self):\n return \"Value\"\n\n\nclass PovrayModifierNode(Node, ObjectNodeTree):\n '''Modifier'''\n\n bl_idname = 'PovrayModifierNode'\n bl_label = 'Modifier'\n bl_icon = 'NODE_TEXTURE'\n\n def init(self, context):\n\n turb_x = self.inputs.new('PovraySocketFloat_0_10', \"Turb X\")\n turb_x.default_value = 0.1\n turb_y = self.inputs.new('PovraySocketFloat_0_10', \"Turb Y\")\n turb_y.default_value = 0.1\n turb_z = self.inputs.new('PovraySocketFloat_0_10', \"Turb Z\")\n turb_z.default_value = 0.1\n octaves = self.inputs.new('PovraySocketInt_1_9', \"Octaves\")\n octaves.default_value = 1\n lambat = self.inputs.new('PovraySocketFloat_0_10', \"Lambda\")\n lambat.default_value = 2.0\n omega = self.inputs.new('PovraySocketFloat_0_10', \"Omega\")\n omega.default_value = 0.5\n freq = self.inputs.new('PovraySocketFloat_0_10', \"Frequency\")\n freq.default_value = 2.0\n self.inputs.new('PovraySocketFloat_0_10', \"Phase\")\n\n self.outputs.new('NodeSocketVector', \"Modifier\")\n\n def draw_label(self):\n return \"Modifier\"\n\n\nclass PovrayPigmentNode(Node, ObjectNodeTree):\n '''Pigment'''\n\n bl_idname = 'PovrayPigmentNode'\n bl_label = 'Color'\n bl_icon = 'SHADING_SOLID'\n\n def init(self, context):\n\n color = self.inputs.new('PovraySocketColor', \"Color\")\n color.default_value = (1, 1, 1)\n pov_filter = self.inputs.new('PovraySocketFloat_0_1', \"Filter\")\n transmit = self.inputs.new('PovraySocketFloat_0_1', \"Transmit\")\n self.outputs.new('NodeSocketColor', \"Pigment\")\n\n def draw_label(self):\n return \"Color\"\n\n\nclass PovrayColorImageNode(Node, ObjectNodeTree):\n '''ColorImage'''\n\n bl_idname = 'PovrayColorImageNode'\n bl_label = 'Image map'\n\n map_type: bpy.props.EnumProperty(\n name=\"Map type\",\n description=\"\",\n items=(\n ('uv_mapping', \"UV\", \"\"),\n ('0', \"Planar\", \"Default planar mapping\"),\n ('1', \"Spherical\", \"Spherical mapping\"),\n ('2', \"Cylindrical\", \"Cylindrical mapping\"),\n ('5', \"Torroidal\", \"Torus or donut shaped mapping\"),\n ),\n default='0',\n )\n image: StringProperty(maxlen=1024) # , subtype=\"FILE_PATH\"\n interpolate: EnumProperty(\n name=\"Interpolate\",\n description=\"Adding the interpolate keyword can smooth the jagged look of a bitmap\",\n items=(\n ('2', \"Bilinear\", \"Gives bilinear interpolation\"),\n ('4', \"Normalized\", \"Gives normalized distance\"),\n ),\n default='2',\n )\n premultiplied: BoolProperty(default=False)\n once: BoolProperty(description=\"Not to repeat\", default=False)\n\n def init(self, context):\n\n gamma = self.inputs.new('PovraySocketFloat_000001_10', \"Gamma\")\n gamma.default_value = 2.0\n transmit = self.inputs.new('PovraySocketFloat_0_1', \"Transmit\")\n pov_filter = self.inputs.new('PovraySocketFloat_0_1', \"Filter\")\n mapping = self.inputs.new('NodeSocketVector', \"Mapping\")\n mapping.hide_value = True\n transform = self.inputs.new('NodeSocketVector', \"Transform\")\n transform.hide_value = True\n modifier = self.inputs.new('NodeSocketVector', \"Modifier\")\n modifier.hide_value = True\n\n self.outputs.new('NodeSocketColor', \"Pigment\")\n\n def draw_buttons(self, context, layout):\n\n column = layout.column()\n im = None\n for image in bpy.data.images:\n if image.name == self.image:\n im = image\n split = column.split(factor=0.8, align=True)\n split.prop_search(self, \"image\", context.blend_data, \"images\", text=\"\")\n split.operator(\"pov.imageopen\", text=\"\", icon=\"FILEBROWSER\")\n if im is not None:\n column.prop(im, \"source\", text=\"\")\n column.prop(self, \"map_type\", text=\"\")\n column.prop(self, \"interpolate\", text=\"\")\n row = column.row()\n row.prop(self, \"premultiplied\", text=\"Premul\")\n row.prop(self, \"once\", text=\"Once\")\n\n def draw_buttons_ext(self, context, layout):\n\n column = layout.column()\n im = None\n for image in bpy.data.images:\n if image.name == self.image:\n im = image\n split = column.split(factor=0.8, align=True)\n split.prop_search(self, \"image\", context.blend_data, \"images\", text=\"\")\n split.operator(\"pov.imageopen\", text=\"\", icon=\"FILEBROWSER\")\n if im is not None:\n column.prop(im, \"source\", text=\"\")\n column.prop(self, \"map_type\", text=\"\")\n column.prop(self, \"interpolate\", text=\"\")\n row = column.row()\n row.prop(self, \"premultiplied\", text=\"Premul\")\n row.prop(self, \"once\", text=\"Once\")\n\n def draw_label(self):\n return \"Image map\"\n\n\nclass PovrayBumpMapNode(Node, ObjectNodeTree):\n '''BumpMap'''\n\n bl_idname = 'PovrayBumpMapNode'\n bl_label = 'Bump map'\n bl_icon = 'TEXTURE'\n\n map_type: bpy.props.EnumProperty(\n name=\"Map type\",\n description=\"\",\n items=(\n ('uv_mapping', \"UV\", \"\"),\n ('0', \"Planar\", \"Default planar mapping\"),\n ('1', \"Spherical\", \"Spherical mapping\"),\n ('2', \"Cylindrical\", \"Cylindrical mapping\"),\n ('5', \"Torroidal\", \"Torus or donut shaped mapping\"),\n ),\n default='0',\n )\n image: StringProperty(maxlen=1024) # , subtype=\"FILE_PATH\"\n interpolate: EnumProperty(\n name=\"Interpolate\",\n description=\"Adding the interpolate keyword can smooth the jagged look of a bitmap\",\n items=(\n ('2', \"Bilinear\", \"Gives bilinear interpolation\"),\n ('4', \"Normalized\", \"Gives normalized distance\"),\n ),\n default='2',\n )\n once: BoolProperty(description=\"Not to repeat\", default=False)\n\n def init(self, context):\n\n self.inputs.new('PovraySocketFloat_0_10', \"Normal\")\n mapping = self.inputs.new('NodeSocketVector', \"Mapping\")\n mapping.hide_value = True\n transform = self.inputs.new('NodeSocketVector', \"Transform\")\n transform.hide_value = True\n modifier = self.inputs.new('NodeSocketVector', \"Modifier\")\n modifier.hide_value = True\n\n normal = self.outputs.new('NodeSocketFloat', \"Normal\")\n normal.hide_value = True\n\n def draw_buttons(self, context, layout):\n\n column = layout.column()\n im = None\n for image in bpy.data.images:\n if image.name == self.image:\n im = image\n split = column.split(factor=0.8, align=True)\n split.prop_search(self, \"image\", context.blend_data, \"images\", text=\"\")\n split.operator(\"pov.imageopen\", text=\"\", icon=\"FILEBROWSER\")\n if im is not None:\n column.prop(im, \"source\", text=\"\")\n column.prop(self, \"map_type\", text=\"\")\n column.prop(self, \"interpolate\", text=\"\")\n column.prop(self, \"once\", text=\"Once\")\n\n def draw_buttons_ext(self, context, layout):\n\n column = layout.column()\n im = None\n for image in bpy.data.images:\n if image.name == self.image:\n im = image\n split = column.split(factor=0.8, align=True)\n split.prop_search(self, \"image\", context.blend_data, \"images\", text=\"\")\n split.operator(\"pov.imageopen\", text=\"\", icon=\"FILEBROWSER\")\n if im is not None:\n column.prop(im, \"source\", text=\"\")\n column.prop(self, \"map_type\", text=\"\")\n column.prop(self, \"interpolate\", text=\"\")\n column.prop(self, \"once\", text=\"Once\")\n\n def draw_label(self):\n return \"Bump Map\"\n\n\nclass PovrayImagePatternNode(Node, ObjectNodeTree):\n '''ImagePattern'''\n\n bl_idname = 'PovrayImagePatternNode'\n bl_label = 'Image pattern'\n bl_icon = 'NODE_TEXTURE'\n\n map_type: bpy.props.EnumProperty(\n name=\"Map type\",\n description=\"\",\n items=(\n ('uv_mapping', \"UV\", \"\"),\n ('0', \"Planar\", \"Default planar mapping\"),\n ('1', \"Spherical\", \"Spherical mapping\"),\n ('2', \"Cylindrical\", \"Cylindrical mapping\"),\n ('5', \"Torroidal\", \"Torus or donut shaped mapping\"),\n ),\n default='0',\n )\n image: StringProperty(maxlen=1024) # , subtype=\"FILE_PATH\"\n interpolate: EnumProperty(\n name=\"Interpolate\",\n description=\"Adding the interpolate keyword can smooth the jagged look of a bitmap\",\n items=(\n ('2', \"Bilinear\", \"Gives bilinear interpolation\"),\n ('4', \"Normalized\", \"Gives normalized distance\"),\n ),\n default='2',\n )\n premultiplied: BoolProperty(default=False)\n once: BoolProperty(description=\"Not to repeat\", default=False)\n use_alpha: BoolProperty(default=True)\n\n def init(self, context):\n\n gamma = self.inputs.new('PovraySocketFloat_000001_10', \"Gamma\")\n gamma.default_value = 2.0\n\n self.outputs.new('PovraySocketPattern', \"Pattern\")\n\n def draw_buttons(self, context, layout):\n\n column = layout.column()\n im = None\n for image in bpy.data.images:\n if image.name == self.image:\n im = image\n split = column.split(factor=0.8, align=True)\n split.prop_search(self, \"image\", context.blend_data, \"images\", text=\"\")\n split.operator(\"pov.imageopen\", text=\"\", icon=\"FILEBROWSER\")\n if im is not None:\n column.prop(im, \"source\", text=\"\")\n column.prop(self, \"map_type\", text=\"\")\n column.prop(self, \"interpolate\", text=\"\")\n row = column.row()\n row.prop(self, \"premultiplied\", text=\"Premul\")\n row.prop(self, \"once\", text=\"Once\")\n column.prop(self, \"use_alpha\", text=\"Use alpha\")\n\n def draw_buttons_ext(self, context, layout):\n\n column = layout.column()\n im = None\n for image in bpy.data.images:\n if image.name == self.image:\n im = image\n split = column.split(factor=0.8, align=True)\n split.prop_search(self, \"image\", context.blend_data, \"images\", text=\"\")\n split.operator(\"pov.imageopen\", text=\"\", icon=\"FILEBROWSER\")\n if im is not None:\n column.prop(im, \"source\", text=\"\")\n column.prop(self, \"map_type\", text=\"\")\n column.prop(self, \"interpolate\", text=\"\")\n row = column.row()\n row.prop(self, \"premultiplied\", text=\"Premul\")\n row.prop(self, \"once\", text=\"Once\")\n\n def draw_label(self):\n return \"Image pattern\"\n\n\nclass ShaderPatternNode(Node, ObjectNodeTree):\n '''Pattern'''\n\n bl_idname = 'ShaderPatternNode'\n bl_label = 'Other patterns'\n\n pattern: EnumProperty(\n name=\"Pattern\",\n description=\"Agate, Crackle, Gradient, Pavement, Spiral, Tiling\",\n items=(\n ('agate', \"Agate\", \"\"),\n ('crackle', \"Crackle\", \"\"),\n ('gradient', \"Gradient\", \"\"),\n ('pavement', \"Pavement\", \"\"),\n ('spiral1', \"Spiral 1\", \"\"),\n ('spiral2', \"Spiral 2\", \"\"),\n ('tiling', \"Tiling\", \"\"),\n ),\n default='agate',\n )\n\n agate_turb: FloatProperty(\n name=\"Agate turb\", description=\"Agate turbulence\", min=0.0, max=100.0, default=0.5\n )\n\n crackle_form_x: FloatProperty(\n name=\"X\", description=\"Form vector X\", min=-150.0, max=150.0, default=-1\n )\n\n crackle_form_y: FloatProperty(\n name=\"Y\", description=\"Form vector Y\", min=-150.0, max=150.0, default=1\n )\n\n crackle_form_z: FloatProperty(\n name=\"Z\", description=\"Form vector Z\", min=-150.0, max=150.0, default=0\n )\n\n crackle_metric: FloatProperty(\n name=\"Metric\", description=\"Crackle metric\", min=0.0, max=150.0, default=1\n )\n\n crackle_solid: BoolProperty(name=\"Solid\", description=\"Crackle solid\", default=False)\n\n spiral_arms: FloatProperty(name=\"Number\", description=\"\", min=0.0, max=256.0, default=2.0)\n\n tiling_number: IntProperty(name=\"Number\", description=\"\", min=1, max=27, default=1)\n\n gradient_orient: EnumProperty(\n name=\"Orient\",\n description=\"\",\n items=(('x', \"X\", \"\"), ('y', \"Y\", \"\"), ('z', \"Z\", \"\")),\n default='x',\n )\n\n def init(self, context):\n\n pat = self.outputs.new('PovraySocketPattern', \"Pattern\")\n\n def draw_buttons(self, context, layout):\n\n layout.prop(self, \"pattern\", text=\"\")\n if self.pattern == 'agate':\n layout.prop(self, \"agate_turb\")\n if self.pattern == 'crackle':\n layout.prop(self, \"crackle_metric\")\n layout.prop(self, \"crackle_solid\")\n layout.label(text=\"Form:\")\n layout.prop(self, \"crackle_form_x\")\n layout.prop(self, \"crackle_form_y\")\n layout.prop(self, \"crackle_form_z\")\n if self.pattern in {\"spiral1\", \"spiral2\"}:\n layout.prop(self, \"spiral_arms\")\n if self.pattern in {'tiling'}:\n layout.prop(self, \"tiling_number\")\n if self.pattern in {'gradient'}:\n layout.prop(self, \"gradient_orient\")\n\n def draw_buttons_ext(self, context, layout):\n pass\n\n def draw_label(self):\n return \"Other patterns\"\n\n\nclass ShaderTextureMapNode(Node, ObjectNodeTree):\n '''Texture Map'''\n\n bl_idname = 'ShaderTextureMapNode'\n bl_label = 'Texture map'\n\n brick_size_x: FloatProperty(name=\"X\", description=\"\", min=0.0000, max=1.0000, default=0.2500)\n\n brick_size_y: FloatProperty(name=\"Y\", description=\"\", min=0.0000, max=1.0000, default=0.0525)\n\n brick_size_z: FloatProperty(name=\"Z\", description=\"\", min=0.0000, max=1.0000, default=0.1250)\n\n brick_mortar: FloatProperty(\n name=\"Mortar\", description=\"Mortar\", min=0.000, max=1.500, default=0.01\n )\n\n def init(self, context):\n mat = bpy.context.object.active_material\n self.inputs.new('PovraySocketPattern', \"\")\n color = self.inputs.new('NodeSocketColor', \"Color ramp\")\n color.hide_value = True\n for i in range(0, 4):\n transform = self.inputs.new('PovraySocketTransform', \"Transform\")\n transform.hide_value = True\n number = mat.pov.inputs_number\n for i in range(number):\n self.inputs.new('PovraySocketTexture', \"%s\" % i)\n\n self.outputs.new('PovraySocketTexture', \"Texture\")\n\n def draw_buttons(self, context, layout):\n\n if self.inputs[0].default_value == 'brick':\n layout.prop(self, \"brick_mortar\")\n layout.label(text=\"Brick size:\")\n layout.prop(self, \"brick_size_x\")\n layout.prop(self, \"brick_size_y\")\n layout.prop(self, \"brick_size_z\")\n\n def draw_buttons_ext(self, context, layout):\n\n if self.inputs[0].default_value == 'brick':\n layout.prop(self, \"brick_mortar\")\n layout.label(text=\"Brick size:\")\n layout.prop(self, \"brick_size_x\")\n layout.prop(self, \"brick_size_y\")\n layout.prop(self, \"brick_size_z\")\n\n def draw_label(self):\n return \"Texture map\"\n\n\nclass ShaderNormalMapNode(Node, ObjectNodeTree):\n '''Normal Map'''\n\n bl_idname = 'ShaderNormalMapNode'\n bl_label = 'Normal map'\n\n brick_size_x: FloatProperty(name=\"X\", description=\"\", min=0.0000, max=1.0000, default=0.2500)\n\n brick_size_y: FloatProperty(name=\"Y\", description=\"\", min=0.0000, max=1.0000, default=0.0525)\n\n brick_size_z: FloatProperty(name=\"Z\", description=\"\", min=0.0000, max=1.0000, default=0.1250)\n\n brick_mortar: FloatProperty(\n name=\"Mortar\", description=\"Mortar\", min=0.000, max=1.500, default=0.01\n )\n\n def init(self, context):\n self.inputs.new('PovraySocketPattern', \"\")\n normal = self.inputs.new('PovraySocketFloat_10', \"Normal\")\n slope = self.inputs.new('PovraySocketMap', \"Slope map\")\n for i in range(0, 4):\n transform = self.inputs.new('PovraySocketTransform', \"Transform\")\n transform.hide_value = True\n self.outputs.new('PovraySocketNormal', \"Normal\")\n\n def draw_buttons(self, context, layout):\n # for i, inp in enumerate(self.inputs):\n\n if self.inputs[0].default_value == 'brick':\n layout.prop(self, \"brick_mortar\")\n layout.label(text=\"Brick size:\")\n layout.prop(self, \"brick_size_x\")\n layout.prop(self, \"brick_size_y\")\n layout.prop(self, \"brick_size_z\")\n\n def draw_buttons_ext(self, context, layout):\n\n if self.inputs[0].default_value == 'brick':\n layout.prop(self, \"brick_mortar\")\n layout.label(text=\"Brick size:\")\n layout.prop(self, \"brick_size_x\")\n layout.prop(self, \"brick_size_y\")\n layout.prop(self, \"brick_size_z\")\n\n def draw_label(self):\n return \"Normal map\"\n\n\nclass ShaderNormalMapEntryNode(Node, ObjectNodeTree):\n '''Normal Map Entry'''\n\n bl_idname = 'ShaderNormalMapEntryNode'\n bl_label = 'Normal map entry'\n\n def init(self, context):\n self.inputs.new('PovraySocketFloat_0_1', \"Stop\")\n self.inputs.new('PovraySocketFloat_0_1', \"Gray\")\n\n def draw_label(self):\n return \"Normal map entry\"\n\n\nclass IsoPropsNode(Node, CompositorNodeTree):\n '''ISO Props'''\n\n bl_idname = 'IsoPropsNode'\n bl_label = 'Iso'\n node_label: StringProperty(maxlen=1024)\n\n def init(self, context):\n ob = bpy.context.object\n self.node_label = ob.name\n text_name = ob.pov.function_text\n if text_name:\n text = bpy.data.texts[text_name]\n for line in text.lines:\n split = line.body.split()\n if split[0] == \"#declare\":\n socket = self.inputs.new('NodeSocketFloat', \"%s\" % split[1])\n value = split[3].split(\";\")\n value = value[0]\n socket.default_value = float(value)\n\n def draw_label(self):\n return self.node_label\n\n\nclass PovrayFogNode(Node, CompositorNodeTree):\n '''Fog settings'''\n\n bl_idname = 'PovrayFogNode'\n bl_label = 'Fog'\n\n def init(self, context):\n color = self.inputs.new('NodeSocketColor', \"Color\")\n color.default_value = (0.7, 0.7, 0.7, 0.25)\n self.inputs.new('PovraySocketFloat_0_1', \"Filter\")\n distance = self.inputs.new('NodeSocketInt', \"Distance\")\n distance.default_value = 150\n self.inputs.new('NodeSocketBool', \"Ground\")\n fog_offset = self.inputs.new('NodeSocketFloat', \"Offset\")\n fog_alt = self.inputs.new('NodeSocketFloat', \"Altitude\")\n turb = self.inputs.new('NodeSocketVector', \"Turbulence\")\n turb_depth = self.inputs.new('PovraySocketFloat_0_10', \"Depth\")\n turb_depth.default_value = 0.5\n octaves = self.inputs.new('PovraySocketInt_1_9', \"Octaves\")\n octaves.default_value = 5\n lambdat = self.inputs.new('PovraySocketFloat_0_10', \"Lambda\")\n lambdat.default_value = 1.25\n omega = self.inputs.new('PovraySocketFloat_0_10', \"Omega\")\n omega.default_value = 0.35\n translate = self.inputs.new('NodeSocketVector', \"Translate\")\n rotate = self.inputs.new('NodeSocketVector', \"Rotate\")\n scale = self.inputs.new('NodeSocketVector', \"Scale\")\n scale.default_value = (1, 1, 1)\n\n def draw_label(self):\n return \"Fog\"\n\n\nclass PovraySlopeNode(Node, TextureNodeTree):\n '''Output'''\n\n bl_idname = 'PovraySlopeNode'\n bl_label = 'Slope Map'\n\n def init(self, context):\n self.use_custom_color = True\n self.color = (0, 0.2, 0)\n slope = self.inputs.new('PovraySocketSlope', \"0\")\n slope = self.inputs.new('PovraySocketSlope', \"1\")\n slopemap = self.outputs.new('PovraySocketMap', \"Slope map\")\n output.hide_value = True\n\n def draw_buttons(self, context, layout):\n\n layout.operator(\"pov.nodeinputadd\")\n row = layout.row()\n row.label(text='Value')\n row.label(text='Height')\n row.label(text='Slope')\n\n def draw_buttons_ext(self, context, layout):\n\n layout.operator(\"pov.nodeinputadd\")\n row = layout.row()\n row.label(text='Value')\n row.label(text='Height')\n row.label(text='Slope')\n\n def draw_label(self):\n return \"Slope Map\"\n\n\n######################################## Texture nodes ###############################\nclass TextureOutputNode(Node, TextureNodeTree):\n '''Output'''\n\n bl_idname = 'TextureOutputNode'\n bl_label = 'Color Map'\n\n def init(self, context):\n tex = bpy.context.object.active_material.active_texture\n num_sockets = int(tex.pov.density_lines / 32)\n for i in range(num_sockets):\n color = self.inputs.new('NodeSocketColor', \"%s\" % i)\n color.hide_value = True\n\n def draw_buttons(self, context, layout):\n\n layout.label(text=\"Color Ramps:\")\n\n def draw_label(self):\n return \"Color Map\"\n\n\n##################################################################################\n#################################Operators########################################\n##################################################################################\n\n\nclass NODE_OT_iso_add(Operator):\n bl_idname = \"pov.nodeisoadd\"\n bl_label = \"Create iso props\"\n\n def execute(self, context):\n ob = bpy.context.object\n if bpy.context.scene.use_nodes == False:\n bpy.context.scene.use_nodes = True\n tree = bpy.context.scene.node_tree\n for node in tree.nodes:\n if node.bl_idname == \"IsoPropsNode\" and node.label == ob.name:\n tree.nodes.remove(node)\n isonode = tree.nodes.new('IsoPropsNode')\n isonode.location = (0, 0)\n isonode.label = ob.name\n return {'FINISHED'}\n\n\nclass NODE_OT_map_create(Operator):\n bl_idname = \"node.map_create\"\n bl_label = \"Create map\"\n\n def execute(self, context):\n x = y = 0\n space = context.space_data\n tree = space.edit_tree\n for node in tree.nodes:\n if node.select == True:\n x, y = node.location\n node.select = False\n tmap = tree.nodes.new('ShaderTextureMapNode')\n tmap.location = (x - 200, y)\n return {'FINISHED'}\n\n def invoke(self, context, event):\n wm = context.window_manager\n return wm.invoke_props_dialog(self)\n\n def draw(self, context):\n layout = self.layout\n mat = context.object.active_material\n layout.prop(mat.pov, \"inputs_number\")\n\n\nclass NODE_OT_povray_node_texture_map_add(Operator):\n bl_idname = \"pov.nodetexmapadd\"\n bl_label = \"Texture map\"\n\n def execute(self, context):\n tree = bpy.context.object.active_material.node_tree\n tmap = tree.nodes.active\n bpy.context.object.active_material.node_tree.nodes.active = tmap\n el = tmap.color_ramp.elements.new(0.5)\n for el in tmap.color_ramp.elements:\n el.color = (0, 0, 0, 1)\n for inp in tmap.inputs:\n tmap.inputs.remove(inp)\n for outp in tmap.outputs:\n tmap.outputs.remove(outp)\n pattern = tmap.inputs.new('NodeSocketVector', \"Pattern\")\n pattern.hide_value = True\n for i in range(0, 3):\n tmap.inputs.new('NodeSocketColor', \"Shader\")\n tmap.outputs.new('NodeSocketShader', \"BSDF\")\n tmap.label = \"Texture Map\"\n return {'FINISHED'}\n\n\nclass NODE_OT_povray_node_output_add(Operator):\n bl_idname = \"pov.nodeoutputadd\"\n bl_label = \"Output\"\n\n def execute(self, context):\n tree = bpy.context.object.active_material.node_tree\n tmap = tree.nodes.new('ShaderNodeOutputMaterial')\n bpy.context.object.active_material.node_tree.nodes.active = tmap\n for inp in tmap.inputs:\n tmap.inputs.remove(inp)\n tmap.inputs.new('NodeSocketShader', \"Surface\")\n tmap.label = \"Output\"\n return {'FINISHED'}\n\n\nclass NODE_OT_povray_node_layered_add(Operator):\n bl_idname = \"pov.nodelayeredadd\"\n bl_label = \"Layered material\"\n\n def execute(self, context):\n tree = bpy.context.object.active_material.node_tree\n tmap = tree.nodes.new('ShaderNodeAddShader')\n bpy.context.object.active_material.node_tree.nodes.active = tmap\n tmap.label = \"Layered material\"\n return {'FINISHED'}\n\n\nclass NODE_OT_povray_input_add(Operator):\n bl_idname = \"pov.nodeinputadd\"\n bl_label = \"Add entry\"\n\n def execute(self, context):\n node = bpy.context.object.active_material.node_tree.nodes.active\n if node.type in {'VALTORGB'}:\n number = 1\n for inp in node.inputs:\n if inp.type == 'SHADER':\n number += 1\n node.inputs.new('NodeSocketShader', \"%s\" % number)\n els = node.color_ramp.elements\n pos1 = els[len(els) - 1].position\n pos2 = els[len(els) - 2].position\n pos = (pos1 - pos2) / 2 + pos2\n el = els.new(pos)\n\n if node.bl_idname == 'PovraySlopeNode':\n number = len(node.inputs)\n node.inputs.new('PovraySocketSlope', \"%s\" % number)\n\n return {'FINISHED'}\n\n\nclass NODE_OT_povray_input_remove(Operator):\n bl_idname = \"pov.nodeinputremove\"\n bl_label = \"Remove input\"\n\n def execute(self, context):\n node = bpy.context.object.active_material.node_tree.nodes.active\n if node.type in {'VALTORGB', 'ADD_SHADER'}:\n number = len(node.inputs) - 1\n if number > 5:\n inp = node.inputs[number]\n node.inputs.remove(inp)\n if node.type in {'VALTORGB'}:\n els = node.color_ramp.elements\n number = len(els) - 2\n el = els[number]\n els.remove(el)\n return {'FINISHED'}\n\n\nclass NODE_OT_povray_image_open(Operator):\n bl_idname = \"pov.imageopen\"\n bl_label = \"Open\"\n\n filepath: StringProperty(\n name=\"File Path\", description=\"Open image\", maxlen=1024, subtype='FILE_PATH'\n )\n\n def invoke(self, context, event):\n context.window_manager.fileselect_add(self)\n return {'RUNNING_MODAL'}\n\n def execute(self, context):\n im = bpy.data.images.load(self.filepath)\n node = context.object.active_material.node_tree.nodes.active\n node.image = im.name\n return {'FINISHED'}\n\n\n# class TEXTURE_OT_povray_open_image(Operator):\n# bl_idname = \"pov.openimage\"\n# bl_label = \"Open Image\"\n\n# filepath = StringProperty(\n# name=\"File Path\",\n# description=\"Open image\",\n# maxlen=1024,\n# subtype='FILE_PATH',\n# )\n\n# def invoke(self, context, event):\n# context.window_manager.fileselect_add(self)\n# return {'RUNNING_MODAL'}\n\n# def execute(self, context):\n# im=bpy.data.images.load(self.filepath)\n# tex = context.texture\n# tex.pov.image = im.name\n# view_layer = context.view_layer\n# view_layer.update()\n# return {'FINISHED'}\n\n\nclass PovrayPatternNode(Operator):\n bl_idname = \"pov.patternnode\"\n bl_label = \"Pattern\"\n\n add = True\n\n def execute(self, context):\n space = context.space_data\n tree = space.edit_tree\n for node in tree.nodes:\n node.select = False\n if self.add == True:\n tmap = tree.nodes.new('ShaderNodeValToRGB')\n tmap.label = \"Pattern\"\n for inp in tmap.inputs:\n tmap.inputs.remove(inp)\n for outp in tmap.outputs:\n tmap.outputs.remove(outp)\n pattern = tmap.inputs.new('PovraySocketPattern', \"Pattern\")\n pattern.hide_value = True\n mapping = tmap.inputs.new('NodeSocketVector', \"Mapping\")\n mapping.hide_value = True\n transform = tmap.inputs.new('NodeSocketVector', \"Transform\")\n transform.hide_value = True\n modifier = tmap.inputs.new('NodeSocketVector', \"Modifier\")\n modifier.hide_value = True\n for i in range(0, 2):\n tmap.inputs.new('NodeSocketShader', \"%s\" % (i + 1))\n tmap.outputs.new('NodeSocketShader', \"Material\")\n tmap.outputs.new('NodeSocketColor', \"Color\")\n tree.nodes.active = tmap\n self.add = False\n aNode = tree.nodes.active\n aNode.select = True\n v2d = context.region.view2d\n x, y = v2d.region_to_view(self.x, self.y)\n aNode.location = (x, y)\n\n def modal(self, context, event):\n if event.type == 'MOUSEMOVE':\n self.x = event.mouse_region_x\n self.y = event.mouse_region_y\n self.execute(context)\n return {'RUNNING_MODAL'}\n elif event.type == 'LEFTMOUSE':\n return {'FINISHED'}\n elif event.type in ('RIGHTMOUSE', 'ESC'):\n return {'CANCELLED'}\n\n return {'RUNNING_MODAL'}\n\n def invoke(self, context, event):\n context.window_manager.modal_handler_add(self)\n return {'RUNNING_MODAL'}\n\n\nclass UpdatePreviewMaterial(Operator):\n '''Operator update preview material'''\n\n bl_idname = \"node.updatepreview\"\n bl_label = \"Update preview\"\n\n def execute(self, context):\n scene = context.view_layer\n ob = context.object\n for obj in scene.objects:\n if obj != ob:\n scene.objects.active = ob\n break\n scene.objects.active = ob\n\n def modal(self, context, event):\n if event.type == 'RIGHTMOUSE':\n self.execute(context)\n return {'FINISHED'}\n return {'PASS_THROUGH'}\n\n def invoke(self, context, event):\n context.window_manager.modal_handler_add(self)\n return {'RUNNING_MODAL'}\n\n\nclass UpdatePreviewKey(Operator):\n '''Operator update preview keymap'''\n\n bl_idname = \"wm.updatepreviewkey\"\n bl_label = \"Activate RMB\"\n\n @classmethod\n def poll(cls, context):\n conf = context.window_manager.keyconfigs.active\n mapstr = \"Node Editor\"\n map = conf.keymaps[mapstr]\n try:\n map.keymap_items[\"node.updatepreview\"]\n return False\n except BaseException as e:\n print(e.__doc__)\n print('An exception occurred: {}'.format(e))\n return True\n\n def execute(self, context):\n conf = context.window_manager.keyconfigs.active\n mapstr = \"Node Editor\"\n map = conf.keymaps[mapstr]\n map.keymap_items.new(\"node.updatepreview\", type='RIGHTMOUSE', value=\"PRESS\")\n return {'FINISHED'}\n\n\nclasses = (\n PovraySocketUniversal,\n PovraySocketFloat_0_1,\n PovraySocketFloat_0_10,\n PovraySocketFloat_10,\n PovraySocketFloatPositive,\n PovraySocketFloat_000001_10,\n PovraySocketFloatUnlimited,\n PovraySocketInt_1_9,\n PovraySocketInt_0_256,\n PovraySocketPattern,\n PovraySocketColor,\n PovraySocketColorRGBFT,\n PovraySocketTexture,\n PovraySocketTransform,\n PovraySocketNormal,\n PovraySocketSlope,\n PovraySocketMap,\n # PovrayShaderNodeCategory, # XXX SOMETHING BROKEN from 2.8 ?\n # PovrayTextureNodeCategory, # XXX SOMETHING BROKEN from 2.8 ?\n # PovraySceneNodeCategory, # XXX SOMETHING BROKEN from 2.8 ?\n NODE_MT_POV_map_create,\n ObjectNodeTree,\n PovrayOutputNode,\n PovrayTextureNode,\n PovrayFinishNode,\n PovrayDiffuseNode,\n PovrayPhongNode,\n PovraySpecularNode,\n PovrayMirrorNode,\n PovrayAmbientNode,\n PovrayIridescenceNode,\n PovraySubsurfaceNode,\n PovrayMappingNode,\n PovrayMultiplyNode,\n PovrayTransformNode,\n PovrayValueNode,\n PovrayModifierNode,\n PovrayPigmentNode,\n PovrayColorImageNode,\n PovrayBumpMapNode,\n PovrayImagePatternNode,\n ShaderPatternNode,\n ShaderTextureMapNode,\n ShaderNormalMapNode,\n ShaderNormalMapEntryNode,\n IsoPropsNode,\n PovrayFogNode,\n PovraySlopeNode,\n TextureOutputNode,\n NODE_OT_iso_add,\n NODE_OT_map_create,\n NODE_OT_povray_node_texture_map_add,\n NODE_OT_povray_node_output_add,\n NODE_OT_povray_node_layered_add,\n NODE_OT_povray_input_add,\n NODE_OT_povray_input_remove,\n NODE_OT_povray_image_open,\n PovrayPatternNode,\n UpdatePreviewMaterial,\n UpdatePreviewKey,\n)\n\n\ndef register():\n # from bpy.utils import register_class\n bpy.types.NODE_HT_header.append(menu_func_nodes)\n nodeitems_utils.register_node_categories(\"POVRAYNODES\", node_categories)\n for cls in classes:\n register_class(cls)\n\n\ndef unregister():\n # from bpy.utils import unregister_class\n\n for cls in reversed(classes):\n unregister_class(cls)\n nodeitems_utils.unregister_node_categories(\"POVRAYNODES\")\n bpy.types.NODE_HT_header.remove(menu_func_nodes)\n","sub_path":"render_povray/shading_nodes.py","file_name":"shading_nodes.py","file_ext":"py","file_size_in_byte":65810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"594606932","text":"import pygame\n\nclass Ship():\n\t\"\"\"管理飞船大部分行为的类\"\"\"\n\n\tdef __init__(self, ai_settings, screen):\n\t\t\"\"\"初始化飞船并设置其初始位置\"\"\"\n\t\tself.ai_settings = ai_settings\n\t\tself.screen = screen\n\n\t\t#加载飞船图像并获取其外接矩形\n\t\tself.image = pygame.image.load(\"images/ship.bmp\")\n\t\tself.rect = self.image.get_rect()\n\t\tself.screen_rect = screen.get_rect()\n\n\t\t#将每艘新飞船放在屏幕底部中央\n\t\tself.rect.centerx = self.screen_rect.centerx\n\t\tself.rect.bottom = self.screen_rect.bottom\n\n\t\t#浮点数存储理论位移\n\t\tself.x_center = float(self.rect.centerx)\n\t\tself.y_center = float(self.rect.centery)\n\n\t\t#移动标志\n\t\tself.moving_right = False\n\t\tself.moving_left = False\n\t\tself.moving_up = False\n\t\tself.moving_down = False\n\n\tdef blitme(self):\n\t\t\"\"\"在指定位置绘制飞船\"\"\"\n\t\tself.screen.blit(self.image, self.rect)\n\n\tdef update(self):\n\t\t\"\"\"根据移动标志调整飞船位置\"\"\"\n\t\tif self.moving_right and self.rect.right <= self.screen_rect.right:\n\t\t\tself.x_center += self.ai_settings.ship_speed_factor\n\t\tif self.moving_left and self.rect.left >= self.screen_rect.left:\n\t\t\tself.x_center -= self.ai_settings.ship_speed_factor\n\t\tif self.moving_down and self.rect.bottom <= self.screen_rect.bottom:\n\t\t\tself.y_center += self.ai_settings.ship_speed_factor\n\t\tif self.moving_up and self.rect.top >= self.screen_rect.top:\n\t\t\tself.y_center -= self.ai_settings.ship_speed_factor\n\t\t#由理论位移取整获得实际位移(整数像素值)\n\t\tself.rect.centerx = self.x_center\n\t\tself.rect.centery = self.y_center\n","sub_path":"ship.py","file_name":"ship.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"485743424","text":"from django.shortcuts import render_to_response,render\nfrom django.http import HttpResponse\nfrom django.views.decorators.clickjacking import xframe_options_exempt\nfrom ides.models import Categorias,Funciona\nfrom django.db.models import Q\nfrom datetime import datetime\n\n#from codigo import suma\ndef convertDatetimeToString(o):\n\tDATE_FORMAT=\"%Y-%m-%d\"\n\tTIME_FORMAT=\"%H:%M:%S\"\n\n\tif isinstance(o,datetime.date):\n\t\treturn o.strftime(DATE_FORMAT)\n\telif isinstance(o,datetime.time):\n\t\treturn o.strftime(TIME_FORMAT)\n\telif isinstance(o,datetime.datetime):\n\t\treturn o.strftime(\"%s %s\" % (DATE_FORMAT,TIME_FORMAT))\n\n\ndef index(request):\n return render_to_response('index.php')\n\n@xframe_options_exempt\ndef buscador(request):\n\tx=''\n\tresultado=Funciona.objects.all().order_by('-fecha')\n\n\tif request.method == 'GET' and 'busqueda' in request.GET:\n\t\tb=request.GET['busqueda']\n\t\tif b is not None and b != '':\n\n\t\t\tif 'categoria' in request.GET:\n\t\t\t\tcategoria=request.GET['categoria']\n\t\t\telse:\n\t\t\t\tcategoria=''\n\n\t\t\tif 'origen' in request.GET:\n\t\t\t\torigen=request.GET['origen']\n\t\t\telse:\n\t\t\t\torigen=''\n\n\t\t\tif 'orden' in request.GET:\n\t\t\t\torden=request.GET['orden']\n\t\t\telse:\n\t\t\t\torden=''\n\n\t\t\tif 'fecha' in request.GET:\n\t\t\t\tfecha=request.GET['fecha']\n\t\t\telse:\n\t\t\t\tfecha=''\n\n\t\t\tx=b\n\t\t\tx=x.replace('+',' ')\n\n\t\t\tif categoria != 'CATEGORIA' and origen != 'ORIGEN':\n\t\t\t\tresultado=Funciona.objects.filter(titulo__unaccent__icontains=x,categoria=categoria,ide=origen).order_by(fecha,orden)\n\n\t\t\telif categoria != 'CATEGORIA' and origen == 'ORIGEN':\n\t\t\t\tresultado=Funciona.objects.filter(titulo__unaccent__icontains=x,categoria=categoria).order_by(fecha,orden)\n\t\t\t\n\t\t\telif categoria == 'CATEGORIA' and origen != 'ORIGEN':\n\t\t\t\tresultado=Funciona.objects.filter(titulo__unaccent__icontains=x,ide=origen).order_by(fecha,orden)\n\n\t\t\telse:\n\t\t\t\tresultado=Funciona.objects.filter(titulo__unaccent__icontains=x).order_by(fecha,orden)\n\t\telse:\n\n\t\t\tif 'categoria' in request.GET:\n\t\t\t\tcategoria=request.GET['categoria']\n\t\t\telse:\n\t\t\t\tcategoria=''\n\n\t\t\tif 'origen' in request.GET:\n\t\t\t\torigen=request.GET['origen']\n\t\t\telse:\n\t\t\t\torigen=''\n\n\t\t\tif 'orden' in request.GET:\n\t\t\t\torden=request.GET['orden']\n\t\t\telse:\n\t\t\t\torden=''\n\n\t\t\tif 'fecha' in request.GET:\n\t\t\t\tfecha=request.GET['fecha']\n\t\t\telse:\n\t\t\t\tfecha=''\n\n\t\t\tif categoria != 'CATEGORIA' and origen != 'ORIGEN':\n\t\t\t\tresultado=Funciona.objects.filter(categoria=categoria,ide=origen).order_by(fecha,orden)\n\n\t\t\telif categoria != 'CATEGORIA' and origen == 'ORIGEN':\n\t\t\t\tresultado=Funciona.objects.filter(categoria=categoria).order_by(fecha,orden)\n\t\t\t\n\t\t\telif categoria == 'CATEGORIA' and origen != 'ORIGEN':\n\t\t\t\tresultado=Funciona.objects.filter(ide=origen).order_by(fecha,orden)\n\n\t\t\telse:\n\t\t\t\tresultado=Funciona.objects.all().order_by(fecha,orden)\n\n\n\n\treturn render(request,'buscador.php',{'content':resultado,'bus':x})\n\ndef resultado(request):\n return render_to_response('resultado.php')\n\ndef add_capa(request):\n\tnombre='100'\n\tcategoria='cat1'\n\tabstract='abst1'\n\t#ca=Capa.objects.create(nombre=nombre,categoria=categoria,abstract=abstract,)\n\t#ca.save()\n\tif(Funciona.objects.get(titulo='Usos preferentes Plan Regulador Comunal Las Condes')):\n\t\tnombre=\"sis\"\n\treturn render(request,'buscador.php',{'content':nombre})\n\ndef categoria(request):\n\t#ocuc=Capas_ocuc.objects.all()\n\tx='bounderies'\n\torder='titulo'\n\tfecha='-fecha'\n\torigen='ORIGEN'\n\n\tif request.method == 'GET' and 'cat' in request.GET:\n\t\tx=request.GET['cat']\n\tif request.method == 'GET' and 'order' in request.GET:\n\t\torder=request.GET['order']\n\tif request.method == 'GET' and 'fecha' in request.GET:\n\t\tfecha=request.GET['fecha']\n\tif request.method == 'GET' and 'origen' in request.GET:\n\t\torigen=request.GET['origen']\n\n\tif origen != 'ORIGEN':\n\t\tcapas=Funciona.objects.filter(categoria=x,ide=origen).order_by(fecha,order)\n\telse:\n\t\tcapas=Funciona.objects.filter(categoria=x).order_by(fecha,order)\n\n\t\n\treturn render(request,'categoria.php',{'content':capas,'cat':x})\n\n\ndef codigo(request): \n variable=100\n return render(request,'codigo.php',{'content':['la variable vale',variable]})\n# Create your views here.\n","sub_path":"ides/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"23288301","text":"#%%\nimport numpy as np\nimport numpy.matlib as mat\nimport pandas as pd\nimport os\nimport glob\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n#%%\nPATH = os.path.abspath(\"C:/Users/Owner/Desktop/Cortical_layers_fMRI\")\npath = r\"{0}/derivatives/tsplots/mean_ts\".format(PATH)\nACTIONS = [\"Motor\", \"Sensory\"]\n#%%\nclass ModelResults:\n def __init__(self, subj, path: str = PATH):\n \"\"\"\n :param subj: Integer or string - number of subject or 'Mean'\n :param path: Mother directory of analysis\n \"\"\"\n self.path = r\"{0}/derivatives/tsplots/mean_ts\".format(path)\n self.subj = subj\n\n #%%\n def get_mean_data(self, action: str, path: str):\n FieldNames = [\n \"SE-EPI\",\n \"IREPITI630\",\n \"IREPITI650\",\n \"IREPITI670\",\n \"IREPITI690\",\n \"IREPITI710\",\n \"IREPITI730\",\n \"IREPITI750\",\n ]\n all_data = pd.DataFrame()\n for field in FieldNames:\n file_name = r\"task-{0}_acq-{1}_bold\".format(action, field)\n prot_file = pd.read_csv(\n r\"{0}/{1}/{1}_subjects_norm_BOLD_response.txt\".format(path, file_name)\n )\n if \"IR\" in field:\n mean_prot = prot_file.mean(axis=1).rename(int(field[-3:]))\n else:\n mean_prot = prot_file.mean(axis=1).rename(field[-3:])\n all_data = all_data.append(mean_prot)\n BOLD = all_data.iloc[0:1, :].mean()\n data = all_data.iloc[1:]\n TIlist = []\n for TI in data.index:\n TIlist.append(TI)\n return BOLD, data, TIlist\n\n def get_subject_data(self, subj, action):\n \"\"\"\n Extrcting subject's mean normalized time course\n :param subj: Subject`s number : int\n :param action: {\"Motor\" or \"Sensory\"} :return: BOLD: SE or GE time course,\n data: nx10 array, where n is the number of IR-SE protocols the subject went through\n \"\"\"\n FieldNames = [\n \"SE-EPI\",\n \"IREPITI630\",\n \"IREPITI650\",\n \"IREPITI670\",\n \"IREPITI690\",\n \"IREPITI710\",\n \"IREPITI730\",\n \"IREPITI750\",\n \"IREPITI930\",\n ]\n all_data = pd.DataFrame()\n if type(subj) == int:\n if subj >= 10:\n subj = str(subj)\n else:\n subj = \"0\" + str(subj)\n for field in FieldNames:\n file_name = r\"task-{0}_acq-{1}_bold\".format(action, field)\n this_prot = glob.glob(\n r\"{0}/{1}/{2}\".format(\n os.path.dirname(self.path), \"sub-\" + subj, file_name\n )\n )\n if this_prot.__len__() != 0:\n subj_prot = pd.read_csv(\n r\"{0}/{1}/{1}_subjects_norm_BOLD_response.txt\".format(\n self.path, file_name\n )\n ).get(\"sub-\" + subj)\n subj_prot.name = field\n if \"Gre\" in field:\n fixed_subj_prot = np.zeros(int(len(subj_prot) / 2))\n j = 0\n for i in range(len(fixed_subj_prot)):\n fixed_subj_prot[i] = np.mean([subj_prot[j], subj_prot[j + 1]])\n j += 2\n all_data = all_data.append(subj_prot, verify_integrity=True)\n BOLD = all_data.iloc[0, :]\n data = all_data.iloc[1:, :].dropna(axis=1)\n TIlist = []\n for TI in data.index:\n TIlist.append(int(TI[-3:]))\n return BOLD, data, TIlist\n\n #%%\n def normalize_data(self, data):\n norm_data = (\n np.array([data - data.min()]) / np.array([data.max() - data.min()])[0]\n )\n return norm_data\n\n def gen_BOLD_mat(self, BOLD):\n BOLD = mat.repmat(BOLD, 7, 1)\n BOLD = BOLD.transpose()\n return BOLD\n\n def gen_initial_params(self):\n s0 = 5000\n T1 = np.array(\n [890, 1000, 1100, 1300, 1400, 1600]\n ) # TO BE REPLACED WITH ACTUAL T1 VALUES\n TR = 3000\n return s0, T1, TR\n\n def gen_inital_cont_guess(self, TIlist, T1, TR):\n A = np.zeros([len(T1), len(TIlist)])\n for i in range(len(TIlist)):\n fix = 1 - np.exp(-(TR - TIlist[i]) / T1)\n A[:, i] = 1 - (1 + (fix)) * np.exp(-TIlist[i] / T1)\n A = abs(A)\n return A\n\n def calc_correlation(self, A, BOLD, norm_mean_data):\n st1 = np.zeros([10, 7, 6])\n mst1 = np.zeros([7, 6])\n cor = np.zeros([A.shape[0], 1])\n pval = np.zeros([A.shape[0], 1])\n for i in range(A.shape[0]):\n st1[:, :, i] = abs(mat.repmat(A[i, :], 10, 1)) * BOLD\n mst1[:, i] = np.mean(st1[4:8, :, i], axis=0)\n [res1, res2] = np.corrcoef(mst1[:, i], norm_mean_data)\n cor[i] = res1[1]\n pval[i] = res1[0]\n return cor, pval\n\n def run_model(self):\n if type(self.subj) == str:\n res = pd.DataFrame(columns=ACTIONS)\n for action in ACTIONS:\n BOLD, data, TIlist = self.get_mean_data(path=self.path, action=action)\n mean_data = data.iloc[:, 3:7].mean(axis=1)\n norm_mean_data = self.normalize_data(data=mean_data)\n BOLD = self.gen_BOLD_mat(BOLD=BOLD)\n s0, T1, TR = self.gen_initial_params()\n A = self.gen_inital_cont_guess(TIlist=TIlist, T1=T1, TR=TR)\n cor, pval = self.calc_correlation(\n A=A, BOLD=BOLD, norm_mean_data=norm_mean_data\n )\n res[action] = cor[:, 0]\n # res[action] = self.normalize_data(data=cor)[0][:, 0]\n res = res.set_index(T1)\n return res\n else:\n res = pd.DataFrame(columns=ACTIONS)\n for action in ACTIONS:\n BOLD, data, TIlist = self.get_subject_data(\n subj=self.subj, action=action\n )\n mean_data = data.iloc[:, 3:7].mean(axis=1)\n norm_mean_data = self.normalize_data(data=mean_data)\n BOLD = self.gen_BOLD_mat(BOLD=BOLD)\n s0, T1, TR = self.gen_initial_params()\n A = self.gen_inital_cont_guess(TIlist=TIlist, T1=T1, TR=TR)\n cor, pval = self.calc_correlation(\n A=A, BOLD=BOLD, norm_mean_data=norm_mean_data\n )\n # res[action] = cor[:, 0]\n res[action] = self.normalize_data(data=cor)[0][:, 0]\n res = res.set_index(T1)\n return res\n\n def plot_results(self):\n \"\"\"\n Plotting the results calculated by the fMRI of cortical layers model\n :return: Motor and Sensory parameters as extracted from the model, and the T1 values calculated\n \"\"\"\n res = self.run_model()\n barM = res[\"Motor\"].values\n barS = res[\"Sensory\"].values\n ind = res.index\n T1vec = np.zeros(len(ind))\n for i in range(len(T1vec)):\n T1vec[i] = int(ind[i])\n barWidth = 25\n r2 = [x + barWidth for x in T1vec]\n plt.grid(b=True, linewidth=0.2)\n plt.bar(\n T1vec, barM, color=\"b\", width=barWidth, edgecolor=\"white\", label=\"Motor\"\n )\n plt.bar(r2, barS, color=\"r\", width=barWidth, edgecolor=\"white\", label=\"Sensory\")\n plt.plot(T1vec, barM)\n plt.plot(T1vec, barS)\n plt.xlabel(\"T1\", fontweight=\"bold\")\n plt.ylabel(\"Partial contribution\", fontweight=\"bold\")\n plt.legend()\n plt.title(\n \"Partial contribution of cortical layers to motor and sensory operations\"\n )\n plt.show()\n return barM, barS, T1vec\n\n\n#%%\n","sub_path":"Correlation_model.py","file_name":"Correlation_model.py","file_ext":"py","file_size_in_byte":7759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"268619829","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n# ## Input variabel \r\njumlah_permintaan = float(input(\"Masukkan jumlah permintaan: \"))\r\njumlah_persediaan = float(input(\"Masukkan jumlah persediaan: \"))\r\nmin_permintaan = float(input(\"Min permintaan: \"))\r\nmin_persediaan = float(input(\"Min persediaan: \"))\r\nmin_produksi = float(input(\"Min produksi: \"))\r\nmax_permintaan = float(input(\"Max permintaan: \"))\r\nmax_persediaan = float(input(\"Max persediaan: \"))\r\nmax_produksi = float(input(\"Max produksi: \"))\r\n\r\n\r\n# ## Fuzzyfikasi\r\n#permintaan\r\nuTurun = (max_permintaan - jumlah_permintaan) / (max_permintaan - min_permintaan) \r\nuNaik = (jumlah_permintaan - min_permintaan) / (max_permintaan - min_permintaan)\r\n\r\n#persediaan barang\r\nuSedikit = (max_persediaan - jumlah_persediaan) / (max_persediaan - min_persediaan) \r\nuBanyak = (jumlah_persediaan - min_persediaan) / (max_persediaan - min_persediaan)\r\n\r\n#fungsi keanggotaan\r\ndef permintaan_turun(x):\r\n return (max_permintaan - x) / (max_permintaan - min_permintaan)\r\n\r\ndef permintaan_naik(x):\r\n return (x - min_permintaan) / (max_permintaan - min_permintaan)\r\n\r\ndef persediaan_sedikit(x):\r\n return (max_persediaan - x) / (max_persediaan - min_persediaan)\r\n\r\ndef persediaan_banyak(x):\r\n return (x - min_persediaan) / (max_persediaan - min_persediaan)\r\n\r\ndef produksi_sedikit(x):\r\n return (max_produksi - x) / (max_produksi - min_produksi)\r\n\r\ndef produksi_banyak(x):\r\n return (x - min_produksi) / (max_produksi - min_produksi)\r\n\r\nprint(\"Tahap fuzzyfikasi\")\r\nprint(\"Nilai uTurun : \", uTurun)\r\nprint(\"Nilai uNaik : \", uNaik)\r\nprint(\"Nilai uSedikit : \", uSedikit)\r\nprint(\"Nilai uBanyak : \", uBanyak)\r\n\r\n# ## Operasi Fuzzy\r\nR1 = np.min([uTurun, uBanyak])\r\nR2 = np.min([uTurun, uSedikit])\r\nR3 = np.min([uNaik, uBanyak])\r\nR4 = np.min([uNaik, uSedikit])\r\n\r\nprint(\"Tahap Operasi fuzzy\")\r\nprint(\"Nilai R1 : \", R1)\r\nprint(\"Nilai R2 : \", R2)\r\nprint(\"Nilai R3 : \", R3)\r\nprint(\"Nilai R4 : \", R4)\r\n\r\n\r\n# ## Implikasi\r\n#jika permitaan turun dan persediaan barang banyak maka berkurang\r\n#jika permintaan turun dan persediaan barang sedikit maka berkurang\r\n#jika permintaan naik dan persediaan barang banyak maka bertambah\r\n#jika permintaan naik dan persediaan barang sedikit maka bertambah\r\nberkurang = np.array([R1, R2])\r\nbertambah = np.array([R3, R4])\r\n\r\nprint(\"Tahap implikasi\")\r\nprint(\"Nilai R1 : \", R1, \"Berkurang\")\r\nprint(\"Nilai R2 : \", R2, \"Berkurang\")\r\nprint(\"Nilai R3 : \", R3, \"Bertambah\")\r\nprint(\"Nilai R4 : \", R4, \"Bertambah\")\r\n\r\n# ## Komposisi aturan\r\n\r\nv_bertambah = np.max(bertambah)\r\nv_berkurang = np.max(berkurang)\r\n\r\nprint(\"Tahap komposisi aturan\")\r\nprint(\"Bertambah: \", v_bertambah)\r\nprint(\"Berkurang: \", v_berkurang)\r\n\r\n# ## Defuzzifikasi\r\n\r\ndfNaik = []\r\ndfTurun = []\r\nfor i in range(5):\r\n dfNaik.append(np.random.randint(min_produksi, max_produksi))\r\n dfTurun.append(np.random.randint(min_produksi, max_produksi))\r\n\r\nprint(\"Defuzzifikasi\")\r\nprint(\"Bertambah\")\r\nfor i in range(5):\r\n print(dfNaik[i])\r\nprint(\"Berkurang\")\r\nfor i in range(5):\r\n print(dfTurun[i])\r\n\r\nhasilAkhir = (np.sum(dfNaik) * v_bertambah) + (np.sum(dfTurun) * v_berkurang) / ((5 * v_bertambah) + (5 * v_berkurang))\r\nprint(\"Produksi yang diperlukan sebanyak: \", np.round(hasilAkhir, 2))\r\n\r\nx1 = np.array([min_permintaan,max_permintaan])\r\nx2 = np.array([min_persediaan, max_persediaan])\r\nx3 = np.array([min_produksi, max_produksi])\r\n\r\n\r\nplt.plot(x1, permintaan_turun(x1))\r\nplt.plot(x1, permintaan_naik(x1))\r\nplt.show()\r\n\r\nplt.plot(x2, persediaan_sedikit(x2))\r\nplt.plot(x2, persediaan_banyak(x2))\r\nplt.show()\r\n\r\nplt.plot(x3, produksi_sedikit(x3))\r\nplt.plot(x3, produksi_banyak(x3))\r\nplt.show()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"638004493","text":"import sys, socket, threading\r\n\r\nclass Client:\r\n\r\n # specifying format for encoding/decoding messages\r\n FORMAT = \"utf-8\"\r\n # creating client socket\r\n client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\r\n def __init__(self, nickname, addr, channel):\r\n\r\n # initialising nickname, address and chatroom name\r\n # and connecting client to server\r\n self.nickname = nickname\r\n self.channel = channel\r\n self.client.connect(addr)\r\n\r\n # listening to server, sends nickname\r\n def receive(self):\r\n\r\n # while client connected to server\r\n while True:\r\n try:\r\n message = self.client.recv(1024).decode(self.FORMAT)\r\n # if the message sent is codeword \"getName+Channel\", send nickname and channel to server\r\n # doesn't print it, but sends nickname and channel to server\r\n if message == \"getName+Channel\":\r\n self.client.send(\"{} {}\".format(self.nickname, self.channel).encode(self.FORMAT))\r\n # else it's just a message, display to client only\r\n else:\r\n print(message)\r\n\r\n # If some error occurs, ends client connection\r\n except:\r\n print(\"An error occured!\")\r\n self.client.close()\r\n break\r\n\r\n # client sends messages to server\r\n def write(self):\r\n\r\n # as long as they are connected, client can interact with it\r\n while True:\r\n\r\n # sends message to server in format \"NAME: MESSAGE\"\r\n userIn = input()\r\n message = \"{}: {}\".format(self.nickname, userIn)\r\n\r\n # send it to server\r\n self.client.send(message.encode(self.FORMAT))\r\n\r\ndef main():\r\n\r\n # ensuring client enters valid arguments\r\n try:\r\n nickname, host, port, channel = sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4]\r\n\r\n # if not, display instructions on how to pass arguments and end program\r\n except:\r\n print(\"Error: please enter name, valid host, port, and channel\")\r\n sys.exit()\r\n\r\n # storing host and port in tuple for binding\r\n ADDR = (host, port)\r\n\r\n\r\n c = Client(nickname, ADDR, channel)\r\n\r\n # initiating threads for listening and writing to server\r\n receiveThread = threading.Thread(target=c.receive)\r\n receiveThread.start()\r\n\r\n writeThread = threading.Thread(target=c.write)\r\n writeThread.start()\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"444887102","text":"##############################################################################\n#\n# Copyright (c) 2008 Zope Corporation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"Code common to most adapters.\"\"\"\n\nfrom ZODB.POSException import UndoError\n\nimport logging\n\nlog = logging.getLogger(\"relstorage.adapters.common\")\n\n\n# Notes about adapters:\n#\n# An adapter must not hold a connection, cursor, or database state, because\n# RelStorage opens multiple concurrent connections using a single adapter\n# instance.\n# Within the context of an adapter, all OID and TID values are integers,\n# not binary strings, except as noted.\n\nclass Adapter(object):\n \"\"\"Common code for a database adapter.\n\n This is an abstract class; a lot of methods are expected to be\n provided by subclasses.\n \"\"\"\n\n # _script_vars contains replacements for statements in scripts.\n # These are correct for PostgreSQL and MySQL but not for Oracle.\n _script_vars = {\n 'TRUE': 'TRUE',\n 'FALSE': 'FALSE',\n 'OCTET_LENGTH': 'OCTET_LENGTH',\n 'oid': '%(oid)s',\n 'tid': '%(tid)s',\n 'pack_tid': '%(pack_tid)s',\n 'undo_tid': '%(undo_tid)s',\n 'self_tid': '%(self_tid)s',\n 'min_tid': '%(min_tid)s',\n 'max_tid': '%(max_tid)s',\n }\n\n _scripts = {\n 'select_keep_tid': \"\"\"\n SELECT tid\n FROM object_state\n WHERE zoid = pack_object.zoid\n AND tid > 0\n AND tid <= %(pack_tid)s\n ORDER BY tid DESC\n LIMIT 1\n \"\"\",\n\n 'choose_pack_transaction': \"\"\"\n SELECT tid\n FROM transaction\n WHERE tid > 0\n AND tid <= %(tid)s\n AND packed = FALSE\n ORDER BY tid DESC\n LIMIT 1\n \"\"\",\n\n 'create_temp_pack_visit': \"\"\"\n CREATE TEMPORARY TABLE temp_pack_visit (\n zoid BIGINT NOT NULL\n );\n CREATE UNIQUE INDEX temp_pack_visit_zoid ON temp_pack_visit (zoid)\n \"\"\",\n\n 'create_temp_undo': \"\"\"\n CREATE TEMPORARY TABLE temp_undo (\n zoid BIGINT NOT NULL,\n prev_tid BIGINT NOT NULL\n );\n CREATE UNIQUE INDEX temp_undo_zoid ON temp_undo (zoid)\n \"\"\",\n\n 'reset_temp_undo': \"DROP TABLE temp_undo\",\n }\n\n\n def _run_script_stmt(self, cursor, generic_stmt, generic_params=()):\n \"\"\"Execute a statement from a script with the given parameters.\n\n Subclasses may override this.\n The input statement is generic and needs to be transformed\n into a database-specific statement.\n \"\"\"\n stmt = generic_stmt % self._script_vars\n try:\n cursor.execute(stmt, generic_params)\n except:\n log.warning(\"script statement failed: %r; parameters: %r\",\n stmt, generic_params)\n raise\n\n\n def _run_script(self, cursor, script, params=()):\n \"\"\"Execute a series of statements in the database.\n\n The statements are transformed by _run_script_stmt\n before execution.\n \"\"\"\n lines = []\n for line in script.split('\\n'):\n line = line.strip()\n if not line or line.startswith('--'):\n continue\n if line.endswith(';'):\n line = line[:-1]\n lines.append(line)\n stmt = '\\n'.join(lines)\n self._run_script_stmt(cursor, stmt, params)\n lines = []\n else:\n lines.append(line)\n if lines:\n stmt = '\\n'.join(lines)\n self._run_script_stmt(cursor, stmt, params)\n\n\n def _transaction_iterator(self, cursor):\n \"\"\"Iterate over a list of transactions returned from the database.\n\n Each row begins with (tid, username, description, extension)\n and may have other columns.\n \"\"\"\n for row in cursor:\n tid, username, description = row[:3]\n if username is None:\n username = ''\n else:\n username = str(username)\n if description is None:\n description = ''\n else:\n description = str(description)\n yield (tid, username, description) + tuple(row[3:])\n\n\n def iter_transactions(self, cursor):\n \"\"\"Iterate over the transaction log, newest first.\n\n Skips packed transactions.\n Yields (tid, username, description, extension) for each transaction.\n \"\"\"\n stmt = \"\"\"\n SELECT tid, username, description, extension\n FROM transaction\n WHERE packed = %(FALSE)s\n AND tid != 0\n ORDER BY tid DESC\n \"\"\"\n self._run_script_stmt(cursor, stmt)\n return self._transaction_iterator(cursor)\n\n\n def iter_transactions_range(self, cursor, start=None, stop=None):\n \"\"\"Iterate over the transactions in the given range, oldest first.\n\n Includes packed transactions.\n Yields (tid, packed, username, description, extension)\n for each transaction.\n \"\"\"\n stmt = \"\"\"\n SELECT tid, username, description, extension,\n CASE WHEN packed = %(TRUE)s THEN 1 ELSE 0 END\n FROM transaction\n WHERE tid >= 0\n \"\"\"\n if start is not None:\n stmt += \" AND tid >= %(min_tid)s\"\n if stop is not None:\n stmt += \" AND tid <= %(max_tid)s\"\n stmt += \" ORDER BY tid\"\n self._run_script_stmt(cursor, stmt,\n {'min_tid': start, 'max_tid': stop})\n return self._transaction_iterator(cursor)\n\n\n def iter_object_history(self, cursor, oid):\n \"\"\"Iterate over an object's history.\n\n Raises KeyError if the object does not exist.\n Yields (tid, username, description, extension, pickle_size)\n for each modification.\n \"\"\"\n stmt = \"\"\"\n SELECT 1 FROM current_object WHERE zoid = %(oid)s\n \"\"\"\n self._run_script_stmt(cursor, stmt, {'oid': oid})\n if not cursor.fetchall():\n raise KeyError(oid)\n\n stmt = \"\"\"\n SELECT tid, username, description, extension, %(OCTET_LENGTH)s(state)\n FROM transaction\n JOIN object_state USING (tid)\n WHERE zoid = %(oid)s\n AND packed = %(FALSE)s\n ORDER BY tid DESC\n \"\"\"\n self._run_script_stmt(cursor, stmt, {'oid': oid})\n return self._transaction_iterator(cursor)\n\n\n def iter_objects(self, cursor, tid):\n \"\"\"Iterate over object states in a transaction.\n\n Yields (oid, prev_tid, state) for each object state.\n \"\"\"\n stmt = \"\"\"\n SELECT zoid, state\n FROM object_state\n WHERE tid = %(tid)s\n ORDER BY zoid\n \"\"\"\n self._run_script_stmt(cursor, stmt, {'tid': tid})\n for oid, state in cursor:\n if hasattr(state, 'read'):\n # Oracle\n state = state.read()\n yield oid, state\n\n\n def verify_undoable(self, cursor, undo_tid):\n \"\"\"Raise UndoError if it is not safe to undo the specified txn.\"\"\"\n stmt = \"\"\"\n SELECT 1 FROM transaction\n WHERE tid = %(undo_tid)s\n AND packed = %(FALSE)s\n \"\"\"\n self._run_script_stmt(cursor, stmt, {'undo_tid': undo_tid})\n if not cursor.fetchall():\n raise UndoError(\"Transaction not found or packed\")\n\n # Rule: we can undo an object if the object's state in the\n # transaction to undo matches the object's current state.\n # If any object in the transaction does not fit that rule,\n # refuse to undo.\n stmt = \"\"\"\n SELECT prev_os.zoid, current_object.tid\n FROM object_state prev_os\n JOIN object_state cur_os ON (prev_os.zoid = cur_os.zoid)\n JOIN current_object ON (cur_os.zoid = current_object.zoid\n AND cur_os.tid = current_object.tid)\n WHERE prev_os.tid = %(undo_tid)s\n AND cur_os.md5 != prev_os.md5\n \"\"\"\n self._run_script_stmt(cursor, stmt, {'undo_tid': undo_tid})\n if cursor.fetchmany():\n raise UndoError(\n \"Some data were modified by a later transaction\")\n\n # Rule: don't allow the creation of the root object to\n # be undone. It's hard to get it back.\n stmt = \"\"\"\n SELECT 1\n FROM object_state\n WHERE tid = %(undo_tid)s\n AND zoid = 0\n AND prev_tid = 0\n \"\"\"\n self._run_script_stmt(cursor, stmt, {'undo_tid': undo_tid})\n if cursor.fetchall():\n raise UndoError(\"Can't undo the creation of the root object\")\n\n\n def undo(self, cursor, undo_tid, self_tid):\n \"\"\"Undo a transaction.\n\n Parameters: \"undo_tid\", the integer tid of the transaction to undo,\n and \"self_tid\", the integer tid of the current transaction.\n\n Returns the list of OIDs undone.\n \"\"\"\n stmt = self._scripts['create_temp_undo']\n if stmt:\n self._run_script(cursor, stmt)\n\n stmt = \"\"\"\n DELETE FROM temp_undo;\n\n -- Put into temp_undo the list of objects to be undone and\n -- the tid of the transaction that has the undone state.\n INSERT INTO temp_undo (zoid, prev_tid)\n SELECT zoid, prev_tid\n FROM object_state\n WHERE tid = %(undo_tid)s;\n\n -- Override previous undo operations within this transaction\n -- by resetting the current_object pointer and deleting\n -- copied states from object_state.\n UPDATE current_object\n SET tid = (\n SELECT prev_tid\n FROM object_state\n WHERE zoid = current_object.zoid\n AND tid = %(self_tid)s\n )\n WHERE zoid IN (SELECT zoid FROM temp_undo)\n AND tid = %(self_tid)s;\n\n DELETE FROM object_state\n WHERE zoid IN (SELECT zoid FROM temp_undo)\n AND tid = %(self_tid)s;\n\n -- Add new undo records.\n INSERT INTO object_state (zoid, tid, prev_tid, md5, state)\n SELECT temp_undo.zoid, %(self_tid)s, current_object.tid,\n prev.md5, prev.state\n FROM temp_undo\n JOIN current_object ON (temp_undo.zoid = current_object.zoid)\n LEFT JOIN object_state prev\n ON (prev.zoid = temp_undo.zoid\n AND prev.tid = temp_undo.prev_tid);\n\n -- List the changed OIDs.\n SELECT zoid FROM temp_undo\n \"\"\"\n self._run_script(cursor, stmt,\n {'undo_tid': undo_tid, 'self_tid': self_tid})\n res = [oid for (oid,) in cursor]\n\n stmt = self._scripts['reset_temp_undo']\n if stmt:\n self._run_script(cursor, stmt)\n\n return res\n\n\n def choose_pack_transaction(self, pack_point):\n \"\"\"Return the transaction before or at the specified pack time.\n\n Returns None if there is nothing to pack.\n \"\"\"\n conn, cursor = self.open()\n try:\n stmt = self._scripts['choose_pack_transaction']\n self._run_script(cursor, stmt, {'tid': pack_point})\n rows = cursor.fetchall()\n if not rows:\n # Nothing needs to be packed.\n return None\n return rows[0][0]\n finally:\n self.close(conn, cursor)\n\n\n def pre_pack(self, pack_tid, get_references, gc):\n \"\"\"Decide what to pack.\n\n Subclasses may override this.\n\n tid specifies the most recent transaction to pack.\n\n get_references is a function that accepts a pickled state and\n returns a set of OIDs that state refers to.\n\n gc is a boolean indicating whether to run garbage collection.\n If gc is false, at least one revision of every object is kept,\n even if nothing refers to it. Packing with gc disabled can be\n much faster.\n \"\"\"\n conn, cursor = self.open()\n try:\n try:\n if gc:\n self._pre_pack_with_gc(cursor, pack_tid, get_references)\n else:\n self._pre_pack_without_gc(cursor, pack_tid)\n except:\n conn.rollback()\n raise\n else:\n conn.commit()\n finally:\n self.close(conn, cursor)\n\n\n def _pre_pack_without_gc(self, cursor, pack_tid):\n \"\"\"Determine what to pack, without garbage collection.\n\n With garbage collection disabled, there is no need to follow\n object references.\n \"\"\"\n # Fill the pack_object table with OIDs, but configure them\n # all to be kept by setting keep and keep_tid.\n stmt = \"\"\"\n DELETE FROM pack_object;\n\n INSERT INTO pack_object (zoid, keep)\n SELECT DISTINCT zoid, %(TRUE)s\n FROM object_state\n WHERE tid <= %(pack_tid)s;\n\n UPDATE pack_object SET keep_tid = (@select_keep_tid@)\n \"\"\"\n stmt = stmt.replace(\n '@select_keep_tid@', self._scripts['select_keep_tid'])\n self._run_script(cursor, stmt, {'pack_tid': pack_tid})\n\n\n def _pre_pack_with_gc(self, cursor, pack_tid, get_references):\n \"\"\"Determine what to pack, with garbage collection.\n \"\"\"\n # Fill object_ref with references from object states\n # in transactions that will not be packed.\n self._fill_nonpacked_refs(cursor, pack_tid, get_references)\n\n # Fill the pack_object table with OIDs that either will be\n # removed (if nothing references the OID) or whose history will\n # be cut.\n stmt = \"\"\"\n DELETE FROM pack_object;\n\n INSERT INTO pack_object (zoid, keep)\n SELECT DISTINCT zoid, %(FALSE)s\n FROM object_state\n WHERE tid <= %(pack_tid)s;\n\n -- If the root object is in pack_object, keep it.\n UPDATE pack_object SET keep = %(TRUE)s\n WHERE zoid = 0;\n\n -- Keep objects that have been revised since pack_tid.\n UPDATE pack_object SET keep = %(TRUE)s\n WHERE keep = %(FALSE)s\n AND zoid IN (\n SELECT zoid\n FROM current_object\n WHERE tid > %(pack_tid)s\n );\n\n -- Keep objects that are still referenced by object states in\n -- transactions that will not be packed.\n UPDATE pack_object SET keep = %(TRUE)s\n WHERE keep = %(FALSE)s\n AND zoid IN (\n SELECT to_zoid\n FROM object_ref\n WHERE tid > %(pack_tid)s\n );\n \"\"\"\n self._run_script(cursor, stmt, {'pack_tid': pack_tid})\n\n stmt = self._scripts['create_temp_pack_visit']\n if stmt:\n self._run_script(cursor, stmt)\n\n # Each of the packable objects to be kept might\n # refer to other objects. If some of those references\n # include objects currently set to be removed, keep\n # those objects as well. Do this\n # repeatedly until all references have been satisfied.\n while True:\n\n # Make a list of all parent objects that still need\n # to be visited. Then set keep_tid for all pack_object\n # rows with keep = true.\n # keep_tid must be set before _fill_pack_object_refs examines\n # references.\n stmt = \"\"\"\n DELETE FROM temp_pack_visit;\n\n INSERT INTO temp_pack_visit (zoid)\n SELECT zoid\n FROM pack_object\n WHERE keep = %(TRUE)s\n AND keep_tid IS NULL;\n\n UPDATE pack_object SET keep_tid = (@select_keep_tid@)\n WHERE keep = %(TRUE)s AND keep_tid IS NULL\n \"\"\"\n stmt = stmt.replace(\n '@select_keep_tid@', self._scripts['select_keep_tid'])\n self._run_script(cursor, stmt, {'pack_tid': pack_tid})\n\n self._fill_pack_object_refs(cursor, get_references)\n\n # Visit the children of all parent objects that were\n # just visited.\n stmt = \"\"\"\n UPDATE pack_object SET keep = %(TRUE)s\n WHERE keep = %(FALSE)s\n AND zoid IN (\n SELECT DISTINCT to_zoid\n FROM object_ref\n JOIN temp_pack_visit USING (zoid)\n )\n \"\"\"\n self._run_script_stmt(cursor, stmt)\n if not cursor.rowcount:\n # No new references detected.\n break\n\n\n def _fill_nonpacked_refs(self, cursor, pack_tid, get_references):\n \"\"\"Fill object_ref for all transactions that will not be packed.\"\"\"\n stmt = \"\"\"\n SELECT DISTINCT tid\n FROM object_state\n WHERE tid > %(pack_tid)s\n AND NOT EXISTS (\n SELECT 1\n FROM object_refs_added\n WHERE tid = object_state.tid\n )\n \"\"\"\n self._run_script_stmt(cursor, stmt, {'pack_tid': pack_tid})\n for (tid,) in cursor.fetchall():\n self._add_refs_for_tid(cursor, tid, get_references)\n\n\n def _fill_pack_object_refs(self, cursor, get_references):\n \"\"\"Fill object_ref for all pack_object rows that have keep_tid.\"\"\"\n stmt = \"\"\"\n SELECT DISTINCT keep_tid\n FROM pack_object\n WHERE keep_tid IS NOT NULL\n AND NOT EXISTS (\n SELECT 1\n FROM object_refs_added\n WHERE tid = keep_tid\n )\n \"\"\"\n cursor.execute(stmt)\n for (tid,) in cursor.fetchall():\n self._add_refs_for_tid(cursor, tid, get_references)\n\n\n def _add_object_ref_rows(self, cursor, add_rows):\n \"\"\"Add rows to object_ref.\n\n The input rows are tuples containing (from_zoid, tid, to_zoid).\n\n Subclasses can override this.\n \"\"\"\n stmt = \"\"\"\n INSERT INTO object_ref (zoid, tid, to_zoid)\n VALUES (%s, %s, %s)\n \"\"\"\n cursor.executemany(stmt, add_rows)\n\n\n def _add_refs_for_tid(self, cursor, tid, get_references):\n \"\"\"Fill object_refs with all states for a transaction.\n \"\"\"\n stmt = \"\"\"\n SELECT zoid, state\n FROM object_state\n WHERE tid = %(tid)s\n \"\"\"\n self._run_script_stmt(cursor, stmt, {'tid': tid})\n\n add_rows = [] # [(from_oid, tid, to_oid)]\n for from_oid, state in cursor:\n if hasattr(state, 'read'):\n # Oracle\n state = state.read()\n if state:\n to_oids = get_references(str(state))\n for to_oid in to_oids:\n add_rows.append((from_oid, tid, to_oid))\n\n if add_rows:\n self._add_object_ref_rows(cursor, add_rows)\n\n # The references have been computed for this transaction.\n stmt = \"\"\"\n INSERT INTO object_refs_added (tid)\n VALUES (%(tid)s)\n \"\"\"\n self._run_script_stmt(cursor, stmt, {'tid': tid})\n\n\n def _hold_commit_lock(self, cursor):\n \"\"\"Hold the commit lock for packing\"\"\"\n cursor.execute(\"LOCK TABLE commit_lock IN EXCLUSIVE MODE\")\n\n\n def pack(self, pack_tid):\n \"\"\"Pack. Requires populated pack tables.\"\"\"\n\n # Read committed mode is sufficient.\n conn, cursor = self.open()\n try:\n try:\n # hold the commit lock for a moment to prevent deadlocks.\n self._hold_commit_lock(cursor)\n\n for table in ('object_ref', 'current_object', 'object_state'):\n\n # Remove objects that are in pack_object and have keep\n # set to false.\n stmt = \"\"\"\n DELETE FROM %s\n WHERE zoid IN (\n SELECT zoid\n FROM pack_object\n WHERE keep = %%(FALSE)s\n )\n \"\"\" % table\n self._run_script_stmt(cursor, stmt)\n\n if table != 'current_object':\n # Cut the history of objects in pack_object that\n # have keep set to true.\n stmt = \"\"\"\n DELETE FROM %s\n WHERE zoid IN (\n SELECT zoid\n FROM pack_object\n WHERE keep = %%(TRUE)s\n )\n AND tid < (\n SELECT keep_tid\n FROM pack_object\n WHERE zoid = %s.zoid\n )\n \"\"\" % (table, table)\n self._run_script_stmt(cursor, stmt)\n\n stmt = \"\"\"\n -- Terminate prev_tid chains\n UPDATE object_state SET prev_tid = 0\n WHERE tid <= %(pack_tid)s\n AND prev_tid != 0;\n\n -- For each tid to be removed, delete the corresponding row in\n -- object_refs_added.\n DELETE FROM object_refs_added\n WHERE tid > 0\n AND tid <= %(pack_tid)s\n AND NOT EXISTS (\n SELECT 1\n FROM object_state\n WHERE tid = object_refs_added.tid\n );\n\n -- Delete transactions no longer used.\n DELETE FROM transaction\n WHERE tid > 0\n AND tid <= %(pack_tid)s\n AND NOT EXISTS (\n SELECT 1\n FROM object_state\n WHERE tid = transaction.tid\n );\n\n -- Mark the remaining packable transactions as packed\n UPDATE transaction SET packed = %(TRUE)s\n WHERE tid > 0\n AND tid <= %(pack_tid)s\n AND packed = %(FALSE)s;\n\n -- Clean up.\n DELETE FROM pack_object;\n \"\"\"\n self._run_script(cursor, stmt, {'pack_tid': pack_tid})\n\n except:\n conn.rollback()\n raise\n\n else:\n conn.commit()\n\n finally:\n self.close(conn, cursor)\n","sub_path":"relstorage/tags/1.0c1/relstorage/adapters/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":22929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"19317915","text":"import cv2\nimport numpy as np\nimport os\n\ndef half_image_convertor(img):\n height = img.shape[0]\n width = img.shape[1]\n img2 = cv2.resize(img , (int(width*0.5), int(height*0.5)))\n return img2\n\ndef yellow_trimmer(frame):\n bgrLower = np.array([130, 20, 20])\n bgrLower = np.array([20,50,50])\n bgrUpper = np.array([250, 255, 255]) # 抽出する色の上限(BGR)\n bgrUpper = np.array([130,255,255])\n img_mask = cv2.inRange(frame, bgrLower, bgrUpper) # BGRからマスクを作成\n result = cv2.bitwise_and(frame, frame, mask=img_mask)\n return result\n\ndef main(frame):\n frame = cv2.GaussianBlur(frame,(15,15),0)\n img = yellow_trimmer(frame)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n gray = cv2.blur(gray,(5,5))\n ret,thresh = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)\n kernel = np.ones((3,3),np.uint8)\n erosion = cv2.erode(thresh,kernel,iterations = 1)\n return erosion\n\ndef new(img):\n img_sum=img[:, :, 2]+img[:, :, 1]\n new=np.where((img[:, :, 1] > 0) & (img[:, :, 2] > 0) & img_sum > 0,255,0)\n return new\n\ndef line_searcher(img):\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n edges = cv2.Canny(gray,50,150,apertureSize = 3)\n try:\n lines = cv2.HoughLines(edges,1,np.pi/180,300)\n for rho,theta in lines[0]:\n a = np.cos(theta)\n b = np.sin(theta)\n x0 = a*rho\n y0 = b*rho\n x1 = int(x0 + 1000*(-b))\n y1 = int(y0 + 1000*(a))\n x2 = int(x0 - 1000*(-b))\n y2 = int(y0 - 1000*(a))\n cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2)\n except:\n pass\n return img\n\n\ndef delt(img):\n im = img\n gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)\n bimg=cv2.adaptiveThreshold(gray, 255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,11,2 )\n contours,hierarchy = cv2.findContours( bimg, cv2.RETR_EXTERNAL | cv2.RETR_TREE , cv2.CHAIN_APPROX_NONE)\n new_contours=[]\n FILL_COLOR=(255,255,255)\n AREA_MAX=50\n i=0\n for c in contours:\n s=abs(cv2.contourArea(c))\n if s <= AREA_MAX:\n new_contours.append(c)\n cv2.drawContours( im, new_contours, -1,FILL_COLOR,-1)\n return im\n\ndef opening(img):\n kernel = np.ones((95,95),np.uint8)\n erosion = cv2.erode(img,kernel,iterations = 1)\n return erosion\ndef closing(img):\n kernel = np.ones((95,95),np.uint8)\n dilation = cv2.dilate(img,kernel,iterations = 1)\n return dilation\n\n\n\n\n\n\n\"\"\"\ntest_image_directory = \"./images/source/\"\nprocessed_image_dirctory = \"./images/exit/\"\n\nimage_pathes = os.listdir(test_image_directory)\nimage_pathes = [a for a in image_pathes if not \".DS\" in a]\nimage_pathes = [a for a in image_pathes if not \".MOV\" in a]\n\nfor image_path in image_pathes:\n fullpath = test_image_directory+image_path\n print(fullpath)\n img = cv2.imread(fullpath)\n img = half_image_convertor(img)\n ma = main(img)\n ne = new(img)\n\n cv2.imwrite(processed_image_dirctory+\"main_\"+image_path,ma)\n cv2.imwrite(processed_image_dirctory+\"new_\"+image_path,ne)\n\n\n\n img = cv2.imread(processed_image_dirctory+\"new_\"+image_path)\n #img = half_image_convertor(img)\n noti = cv2.bitwise_not(img)\n cv2.imwrite(processed_image_dirctory+\"not_\"+image_path,noti)\n #de = delt(img)\n #cv2.imwrite(processed_image_dirctory+\"del_\"+image_path,de)\n #li = line_searcher(img)\n #cv2.imwrite(processed_image_dirctory+\"lin_\"+image_path,li)\n opn = opening(img)\n cv2.imwrite(processed_image_dirctory+\"opn_\"+image_path,noti)\n\"\"\"","sub_path":"yellow_block/codes/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"317489462","text":"from matplotlib import pyplot as plt\nimport cv2\nimport numpy as np\n\n\noriginal_image = cv2.imread(\"images\\\\badminton.jpg\")\n\n# 將圖檔從BGR格式(opencv)轉換成RGB格式(matplotlib)\nimage1 = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB)\n# 關閉XY軸的座標\nplt.axis(\"off\")\nplt.title(\"Original image\")\nplt.imshow(image1)\n# 顯示單獨的視窗\nplt.figure()\n\n\n# 深拷貝圖像\nimage2 = np.array(original_image)\n# 從BGR格式轉換成灰階格式\nimage2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)\nplt.axis(\"off\")\nplt.title(\"Gray image\")\n# 圖檔需要先轉灰階,cmap='gray'才能生效\nplt.imshow(image2, cmap='gray')\nplt.figure()\n\n\nimage3 = np.array(original_image)\nimage3 = cv2.cvtColor(image3, cv2.COLOR_BGR2GRAY)\n# 重設圖案大小(無此行會影響圖像在matplotlib的清晰度)\nimage3 = cv2.resize(image3, (450,300))\n# Sobel邊緣檢測,cv2.Sobel(圖像變數, cv2.CV_8U(輸出圖像深度), 1,0(1,0代表Y軸計算,0,1代表X軸計算)),參考:http://monkeycoding.com/?p=53、https://docs.opencv.org/4.1.0/d4/d86/group__imgproc__filter.html#gacea54f142e81b6758cb6f375ce782c8d\nsobel_y = cv2.Sobel(image3, cv2.CV_8U, 1,0)\nplt.axis(\"off\")\nplt.title(\"Sobel image Y\")\nplt.imshow(sobel_y, cmap='gray')\n# 參考:https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.figure.html\nplt.figure()\n\n\nimage4 = np.array(original_image)\nimage4 = cv2.cvtColor(image4, cv2.COLOR_BGR2GRAY)\n# 重設圖案大小(無此行會影響圖像在matplotlib的顯示)\nimage4 = cv2.resize(image4, (450,300))\n# Sobel邊緣檢測,如果是cv2.CV_16S而不是cv2.CV_8U會出現以下的錯誤:\n# Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).\nsobel_x = cv2.Sobel(image4, cv2.CV_8U, 0,1)\nplt.axis(\"off\")\nplt.title(\"Sobel image X\")\nplt.imshow(sobel_x, cmap='gray')\n# 顯示第一個2x2的視窗\nplt.figure()\n\n\nimage5 = np.array(original_image)\nimage5 = cv2.cvtColor(image5, cv2.COLOR_BGR2GRAY)\nimage5 = cv2.resize(image5, (450,300))\nx = cv2.Sobel(image5, cv2.CV_8U, 1,0)\ny = cv2.Sobel(image5, cv2.CV_8U, 0,1)\n# 將兩個圖案重疊並設定圖檔的權重,cv2.addWeighted(x,0.7(x的權重), y,0.7(y的權重) ,0(圖案相加後再增加的值))\nxy_add = cv2.addWeighted(x,0.7, y,0.7 ,0)\nplt.axis(\"off\")\nplt.title(\"Sobel image XY\")\nplt.imshow(xy_add, cmap='gray')\nplt.figure()\n\n\nimage6 = np.array(original_image)\nimage6 = cv2.cvtColor(image6, cv2.COLOR_BGR2GRAY)\nimage6 = cv2.resize(image6, (450,300))\n# cv2.blur(image6, (5,5)),5,5代表5x5的矩陣大小\nimage6 = cv2.blur(image6, (5,5))\n# Canny邊緣檢測\ncanny = cv2.Canny(image6, 3,15)\nplt.axis(\"off\")\nplt.title(\"Canny image\")\nplt.imshow(canny, cmap='gray')\nplt.figure()\n\n\nimage7 = np.array(original_image)\nimage7 = cv2.cvtColor(image7, cv2.COLOR_BGR2RGB)\nimage7 = cv2.resize(image7, (450,300))\n# 高斯模糊,cv2.GaussianBlur(image7, (3,3), 0),3,3代表3x3的矩陣大小,0,0為sigmaX、sigmaY,參考:http://monkeycoding.com/?p=570\ngassian_blur = cv2.GaussianBlur(image7, (3,3), 0,0)\ncanny_xy2 = cv2.Canny(gassian_blur, 50,150)\n# 對圖像的每個像素進行and的位元運算;image7為高斯模糊的圖檔;mask為取出的邊緣線條,參考:https://blog.csdn.net/u011028345/article/details/77278467\ncanny_xy2 = cv2.bitwise_and(image7, image7, mask=canny_xy2)\nplt.axis(\"off\")\nplt.title(\"Canny image bits_and\")\nplt.imshow(canny_xy2)\nplt.figure()\n\n\nimage8 = np.array(original_image)\nimage8 = cv2.cvtColor(image8, cv2.COLOR_BGR2GRAY)\nimage8 = cv2.resize(image8, (450,300))\nimage8 = cv2.GaussianBlur(image8, (5,5), 0)\n# Laplacian邊緣檢測,抓取線條\nlaplacian = cv2.Laplacian(image8, cv2.CV_16U)\nplt.axis(\"off\")\nplt.title(\"Laplacian image\")\nplt.imshow(laplacian, cmap='gray')\n\n\n# 顯示8個視窗\nplt.show()","sub_path":"Image/Matplotlib/multiple_display-3.py","file_name":"multiple_display-3.py","file_ext":"py","file_size_in_byte":3763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"351534979","text":"import io\nimport sys\nimport os, sys\nimport requests\nimport PIL\nimport warnings\nimport os\nimport hashlib\nimport urllib\nfrom tqdm import tqdm\nfrom math import sqrt\n\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\n\nfrom einops import rearrange\n\n# constants\n\nENCODER_PATH = 'https://cdn.openai.com/dall-e/encoder.pkl'\nDECODER_PATH = 'https://cdn.openai.com/dall-e/decoder.pkl'\nEPS = 0.1\n\n# helpers methods\n\ndef load_model(path):\n with open(path, 'rb') as f:\n return torch.load(f, map_location = torch.device('cpu'))\n\ndef map_pixels(x):\n return (1 - 2 * EPS) * x + EPS\n\ndef unmap_pixels(x):\n return torch.clamp((x - EPS) / (1 - 2 * EPS), 0, 1)\n\ndef download(url, root=os.path.expanduser(\"~/.cache/dalle\")):\n os.makedirs(root, exist_ok=True)\n filename = os.path.basename(url)\n\n download_target = os.path.join(root, filename)\n download_target_tmp = os.path.join(root, f'tmp.{filename}')\n\n if os.path.exists(download_target) and not os.path.isfile(download_target):\n raise RuntimeError(f\"{download_target} exists and is not a regular file\")\n\n if os.path.isfile(download_target):\n return download_target\n\n with urllib.request.urlopen(url) as source, open(download_target_tmp, \"wb\") as output:\n with tqdm(total=int(source.info().get(\"Content-Length\")), ncols=80) as loop:\n while True:\n buffer = source.read(8192)\n if not buffer:\n break\n\n output.write(buffer)\n loop.update(len(buffer))\n\n os.rename(download_target_tmp, download_target)\n return download_target\n\n# adapter class\n\nclass OpenAIDiscreteVAE(nn.Module):\n def __init__(self):\n super().__init__()\n try:\n import dall_e\n except:\n print(f'you need to \"pip install git+https://github.com/openai/DALL-E.git\" before you can use the pretrained OpenAI Discrete VAE')\n sys.exit()\n\n self.enc = load_model(download(ENCODER_PATH))\n self.dec = load_model(download(DECODER_PATH))\n self.num_layers = 3\n self.image_size = 256\n self.num_tokens = 8192\n\n @torch.no_grad()\n def get_codebook_indices(self, img):\n img = map_pixels(img)\n z_logits = self.enc(img)\n z = torch.argmax(z_logits, dim = 1)\n return rearrange(z, 'b h w -> b (h w)')\n\n def decode(self, img_seq):\n b, n = img_seq.shape\n img_seq = rearrange(img_seq, 'b (h w) -> b h w', h = int(sqrt(n)))\n\n z = F.one_hot(img_seq, num_classes = self.num_tokens)\n z = rearrange(z, 'b h w c -> b c h w').float()\n x_stats = self.dec(z).float()\n x_rec = unmap_pixels(torch.sigmoid(x_stats[:, :3]))\n return x_rec\n\n def forward(self, img):\n raise NotImplemented\n","sub_path":"dalle_pytorch/vae.py","file_name":"vae.py","file_ext":"py","file_size_in_byte":2794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"649864540","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nfrom dbConnection import redis_db\n\n\n\"\"\"\nredis 操作集\n\n\"\"\"\nclass RedisOpt(object):\n \n @staticmethod\n def redis_get_value(table_row=None,table_col=None,name=None,rtype=None,charttype=None,c_method=None,matrix=None,bu=None,source=None,confirm_status=None,result_type=None,source_status=None,starttime=None,endtime=None):\n \"\"\"\n name字段无用 \n c_method 决定取什么类型的数据\n rtype=spline 则取区间 table 则取单量 离时间点最近的一个\n 参数中文说明:\n bu: 业务\n source: 工具\n confirm_status: 事件的状态\n result_type: 事件类型:漏洞或者攻击的分类\n source_status: 工具的状态\n c_method: redis中的计数方式分为 incr , total\n matrix: 矩阵类型 \n --------------------------------------------------------\n 不同的 rtype 和 matrix 组合 需要的 参数不同,具体需参类型如下:\n matrix 1:\n c_method,matrix,bu,source,confirm_status\n rtype chart:\n starttime,endtime\n rtype table or count:\n table_row,table_col\n matrix 2:\n c_method,matrix,bu,result_type\n rtype chart:\n starttime,endtime\n rtype table or count:\n table_row,table_col\n matrix 3:\n c_method,matrix,source,result_type\n rtype chart:\n starttime,endtime\n rtype table or count:\n table_row,table_col\n matrix 4:\n c_method,matrix,source,source_status\n rtype chart:\n starttime,endtime\n rtype table or count:\n table_row,table_col\n matrix 5:\n c_method,matrix,bu,source_status\n rtype chart:\n starttime,endtime\n rtype table or count:\n table_row,table_col\n \n ---------------------------------------------\n \n table_row table_col 在 rtype=table or count 的时候需要 输入格式 [{\"id\":xx,\"name\":xx}]\n 注意:在rtype== count的时候 table_col 需要等于长度为1的 [{\"id\":xx,\"name\":xx}]\n bu,source,confirm_status,source_status,result_type 以上参数如果需要作为table 类型的 col 和 row 请在此变量处传递字符串 col 对应 '%(table_c)s' row 对应 '%(table_r)s' \n \n spline 返回结构 [[timestamp,value],[]]\n table 返回结构 [{'row':0行,'col':[1列,2,3]}]\n \"\"\"\n \n \n \n \n if matrix==1:\n rk='%s_%s_%s_%s_%s'%(c_method,matrix,bu,source,confirm_status)\n if matrix==2:\n rk='%s_%s_%s_%s'%(c_method,matrix,bu,result_type) \n if matrix==3:\n rk='%s_%s_%s_%s'%(c_method,matrix,source,result_type) \n if matrix==4:\n rk='%s_%s_%s_%s'%(c_method,matrix,source,source_status)\n if matrix==5:\n rk='%s_%s_%s_%s'%(c_method,matrix,bu,source_status)\n return RedisOpt.wrap_factory(rk=rk,table_col=table_col,table_row=table_row,starttime=starttime,endtime=endtime,charttype=charttype,rtype=rtype)\n \n @staticmethod\n def table_factory_fromredis(rk,table_row,table_col,timestamp=14037063010,rpl=None):\n \"\"\"\n timestamp的 默认值设置为一个不可能到达的未来的时间,起码在作者活着的时候是到不了的时间 ^_^,为了是在没有提供时间戳的情况下,获取最后一条count\n \"\"\"\n table_live=[]\n row_index=0\n count_ids=set() #将本次遍历出来的count_id全部取出来去重 ,以备后面查询 countcorr表\n for _r in table_row:\n for _c in table_col:\n #ZrevRANGEBYSCORE 't1' 101 -inf withscores limit 0 1\n rpl.zrevrangebyscore(name=rk%{'table_c':_c['id'],\"table_r\":_r['id']}, max=timestamp, min=-1,start=0, num=1, score_cast_func=int)\n #counts.append(random.randint(0,100)) #test\n counts=rpl.execute()\n counts=[int(x[0]) if x else 0 for x in counts] #redis 返回的是字符串 要进行int转换\n table_live.append({'row':row_index,'col':counts})\n count_ids.update(counts)\n row_index+=1\n count_values=redis_db.cur2.hmget('countcorr',list(count_ids),)\n count_kv=dict(zip(list(count_ids),[int(x) for x in count_values])) #生成 count_id:count_value 字典\n #将表格中所有的count_id替换成 count_value\n for index,item in enumerate(table_live):\n table_live[index]['col']=[count_kv[x] for x in table_live[index]['col']]\n return table_live\n \n @staticmethod\n def wrap_factory(rk,table_col,table_row,starttime,endtime,rtype,charttype):\n \n \"\"\"\n 带有时间范围计算功能\n \"\"\"\n # redis 初始化 包括 lua脚本\n rpl=redis_db.cur2.pipeline() \n spline_lua=\"\"\"\n local result={}\n local zres=redis.call('zrangebyscore',KEYS[1],KEYS[2],KEYS[3],'withscores');\n for idx = 2, #zres, 2 do\n local pair={}\n table.insert(pair,zres[idx])\n table.insert(pair,redis.call('hget','countcorr',zres[idx-1]))\n table.insert(result,pair) \n end\n return cjson.encode(result)\n \"\"\"\n spline_lua_obj=redis_db.cur2.register_script(spline_lua) \n if charttype=='spline' and rtype=='chart':\n return spline_lua_obj(keys=[rk,starttime,endtime]) \n if (rtype=='table' or rtype=='count') and table_row and table_col: \n #return RedisOpt.wrap_table_factory(rk=rk,table_col=table_col,table_row=table_row,rpl=rpl,starttime=starttime,endtime=endtime)\n \n if starttime and endtime: #带有时间范围的数据处理 两个时间点数据相减\n starttime_table=RedisOpt.table_factory_fromredis(rk=rk,table_col=table_col,table_row=table_row,rpl=rpl,timestamp=starttime)\n endtime_table=RedisOpt.table_factory_fromredis(rk=rk,table_col=table_col,table_row=table_row,rpl=rpl,timestamp=endtime)\n new_table={}\n #两个table相减\n for x in starttime_table:\n new_table[x]=[x+y for x,y in zip(endtime_table[x],starttime_table[x])]\n return new_table\n else:\n return RedisOpt.table_factory_fromredis(rk=rk,table_col=table_col,table_row=table_row,rpl=rpl)\n \n \n \n ","sub_path":"frontend/utils/redis_opt.py","file_name":"redis_opt.py","file_ext":"py","file_size_in_byte":6600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"215320360","text":"from django.test import TestCase\nfrom django.contrib.auth import get_user_model\nUser = get_user_model()\n\nfrom datetime import datetime, timedelta\n\nfrom exerciselog.models import WorkoutSession, LiftExercise, LiftSet\n\n\nclass LiftSetTest(TestCase):\n\n def setUp(self):\n user = User.objects.create_user(username='test', password='asdf')\n self.client.login(username='test', password='asdf')\n date = datetime.now().date()\n WorkoutSession.objects.create(owner=user, date=date)\n LiftExercise.objects.create(name='test ups', owner=user)\n LiftExercise.objects.create(name='test downs', owner=user)\n\n def test_POST_saves_lift_set(self):\n le = LiftExercise.objects.get(name='test ups')\n wo = WorkoutSession.objects.first()\n self.assertEqual(LiftSet.objects.count(), 0)\n \n self.client.post(\n '/exerciselog/lift-set/new/',\n {\n 'exercise': 1,\n 'weight': '135',\n 'num_sets': '5',\n 'num_reps': '5',\n 'workout_session': wo.id,\n }\n )\n ls = LiftSet.objects.first()\n\n self.assertEqual(LiftSet.objects.count(), 1)\n self.assertEqual(ls.exercise, le)\n\n def test_delete_lift_set(self):\n le = LiftExercise.objects.get(name='test ups')\n wo = WorkoutSession.objects.first()\n ls = LiftSet.objects.create(\n exercise=le, weight=0, num_sets=5, \n num_reps=5, workout_session=wo,\n )\n\n self.assertEqual(LiftSet.objects.count(), 1)\n self.client.post(\n '/exerciselog/lift-set/{}/delete/'.format(ls.id),\n {'value': \"Confirm\"}\n )\n self.assertEqual(LiftSet.objects.count(), 0)\n\n def test_uses_detail_template(self):\n le = LiftExercise.objects.get(name='test ups')\n wo = WorkoutSession.objects.first()\n ls = LiftSet.objects.create(\n exercise=le, weight=0, num_sets=5, \n num_reps=5, workout_session=wo,\n )\n response = self.client.get('/exerciselog/{}/lift-set/'.format(ls.uuid))\n self.assertTemplateUsed(\n response,'exerciselog/liftset/lift_set_detail.html'\n )\n\n","sub_path":"exerciselog/tests/test_lift_set_views.py","file_name":"test_lift_set_views.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"487771076","text":"import click\nimport mysql\nimport mysql.connector\nimport PySQL.core\nfrom mysql.connector import errorcode\nfrom migrations import *\nfrom PySQL.core import *\nconnection = db(host='localhost', user='python', password='python', database='python')\n\n@click.group()\n\ndef cli():\n \"\"\"PySQL Interactive Command Line Program\n \"\"\"\n@cli.command('select')\n@click.argument('table')\n@click.argument('where', required=False)\n@click.argument('select', required=False)\ndef select(table, where, select):\n connection.select(table, where, select)\n\n@cli.command('describe')\n@click.argument('table')\ndef describe(table):\n click.echo(\"Description for table: {}\".format(table))\n connection.describe(table)\n\n@cli.group()\n\ndef database():\n \"\"\"Manages databases.\"\"\"\n@database.command('show')\ndef database_show():\n connection.show_databases()\n@database.command('create')\n@click.argument('name')\ndef database_new(name):\n \"\"\"Creates a new database.\"\"\"\n click.echo(\"Created new database: {}\".format(name))\n connection.create_database(name)\n\n@database.command('delete')\n@click.argument('name')\ndef database_delete(name):\n \"\"\"Delete a database.\"\"\"\n click.echo(\"Deleted database: {}\".format(name))\n connection.delete_database(name)\n\n\n\nif __name__ == '__main__':\n cli()","sub_path":"pysqlcmd.py","file_name":"pysqlcmd.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"163523781","text":"# OOP tutorial\n# https://towardsdatascience.com/understand-o-o-p-in-python-with-one-article-bfa76f3ba48c\n#4-Defining Constructors\n\nclass Car:\n def __init__(self, brand, color):\n self.brand = brand\n self.color = color\n\n def __repr__(self):\n return 'My car is {} and was produced by {}'.format(self.color, self.brand)\n#instance #1 of the car class\n\nmy_car = Car('Tesla', 'black')\n\nprint(my_car)\n\nprint(my_car.color)\n\nprint(my_car.brand)\n","sub_path":"Tutorials/OOP/OOP_in_one_article/4-Defining_Constructors_and_Other_Special_Methods.py","file_name":"4-Defining_Constructors_and_Other_Special_Methods.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"273610618","text":"\"\"\"\nCalculations for forward trajectory from a point in space and time using the\nposition scalars\n\"\"\"\nfrom ..utils.grid import wrap_periodic_grid_coords\nfrom .backward import calc_trajectory_previous_position\n\nimport scipy.optimize\nimport numpy as np\nimport xarray as xr\nfrom tqdm import tqdm\n\n\ndef _extrapolate_single_timestep(\n ds_position_scalars_origin,\n ds_position_scalars_next,\n ds_traj_posn_prev,\n ds_traj_posn_origin,\n minimization_method=None,\n):\n \"\"\"\n Extrapolate from the trajectory position `ds_traj_posn_origin` to the next time\n\n The algorithm is as follows:\n\n 1) for a trajectory position `(x,y,z)` at a time `t` extrapolate a first\n guess for the next trajecotory position using the previous point in the\n trajectory\n 2) find an optimal value for the estimated next trajectory point by\n minimizing the difference between the true origin and the point found when\n back-tracking from the current \"next\"-point estimate (using the position\n scalars)\n \"\"\"\n ds_grid = ds_position_scalars_origin[[\"x\", \"y\", \"z\"]]\n\n def _wrap_coords(ds_posn):\n cyclic_coords = (\"x\", \"y\")\n cell_centered_coords = (\"x\", \"y\", \"z\")\n return wrap_periodic_grid_coords(\n ds_grid=ds_grid,\n ds_posn=ds_posn,\n cyclic_coords=cyclic_coords,\n cell_centered_coords=cell_centered_coords,\n )\n\n # traj_posn_next_est is our estimate of the trajectory positions at\n # the next time step.\n # We want the 'where from' at traj_posn_next_est to match\n # the current trajectory positions, traj_posn_origin\n\n # Let f(X) be the function which estimates the distance between the actual\n # origin and the point estimated by back-trajactory from the estimated next\n # point, i.e. f(X) -> X_err, we then want to minimize X_err.\n # We will use the Eucledian distance (L2-norm) so that we minimize the\n # magnitude of this error\n\n # First guess - extrapolate from last two positions.\n # given points A and B the vector spanning from A to B is AB = B-A\n # let C = B + AB, then C = B + B - A = 2B - A\n\n ds_traj_posn_next_est = 2 * ds_traj_posn_origin - ds_traj_posn_prev\n\n def _pt_ds_to_arr(ds_pt):\n return np.array([ds_pt[c].data for c in \"xyz\"])\n\n def _pt_arr_to_ds(arr_pt):\n ds_pt = xr.Dataset()\n for n, c in enumerate(\"xyz\"):\n ds_pt[c] = arr_pt[n]\n return ds_pt\n\n # for the minimizsation we will be using just a numpy-array containing the\n # (x,y,z) location\n pt_traj_posn_next_est = _pt_ds_to_arr(ds_traj_posn_next_est)\n\n def _calc_backtrack_origin_dist(pt_traj_posn_next):\n \"\"\"\n Compute the distance betweent the true origin and the estimated origin\n (calculated by back-trajectory from `pt_traj_posn_next`)\n \"\"\"\n ds_traj_posn_next = xr.Dataset()\n for n, c in enumerate(\"xyz\"):\n ds_traj_posn_next[c] = pt_traj_posn_next[n]\n\n if ds_grid.xy_periodic:\n ds_traj_posn_next = _wrap_coords(ds_traj_posn_next)\n\n # using this estimate of the next trajectory position use the position\n # scalars at that point to estimate where fluid originated from. If we've\n # made a good guess for the next position this estimated origin position\n # should be close to the true origin\n ds_traj_posn_origin_guess = calc_trajectory_previous_position(\n ds_position_scalars=ds_position_scalars_next,\n ds_traj_posn=ds_traj_posn_next_est,\n )\n\n ds_p1 = ds_traj_posn_origin\n ds_p2 = ds_traj_posn_origin_guess\n dist_arr = np.array(\n [\n ds_p1.x - ds_p2.x_est,\n ds_p1.y - ds_p2.y_est,\n ds_p1.z - ds_p2.z_est,\n ]\n )\n return dist_arr\n\n def _calc_backtrack_origin_err(pt_traj_posn_next):\n dist_arr = _calc_backtrack_origin_dist(pt_traj_posn_next=pt_traj_posn_next_est)\n err = np.linalg.norm(dist_arr)\n return err\n\n sol = scipy.optimize.minimize(\n fun=_calc_backtrack_origin_err,\n x0=pt_traj_posn_next_est,\n method=minimization_method,\n )\n\n if sol.success:\n ds_traj_posn_next = _pt_arr_to_ds(sol.x)\n\n if ds_grid.xy_periodic:\n ds_traj_posn_next = _wrap_coords(ds_traj_posn_next)\n else:\n raise Exception(\"The minimization didn't converge\")\n\n ds_traj_posn_next = ds_traj_posn_next.assign_coords(\n time=ds_position_scalars_next.time\n )\n\n return ds_traj_posn_next\n\n\ndef forward(ds_position_scalars, ds_back_trajectory, da_times, interp_order=1):\n \"\"\"\n Using the position scalars `ds_position_scalars` integrate forwards from\n the last point in `ds_back_trajectory` to the times in `da_times`. The\n backward trajectory must contain at least two points in time as these are\n used for the initial guess for the forward extrapolation\n \"\"\"\n if not ds_back_trajectory.time.count() >= 2:\n raise Exception(\n \"The back trajectory must contain at least two points for the forward\"\n \" extrapolation have an initial guess for the direction\"\n )\n\n # create a copy of the backward trajectory so that we have a dataset into\n # which we will accumulate the full trajectory\n ds_traj = ds_back_trajectory.copy()\n\n # step forward in time, `t_forward` represents the time we're of the next\n # point (forward) of the trajectory\n for t_next in tqdm(da_times, desc=\"forward\"):\n ds_traj_posn_origin = ds_traj.isel(time=-1)\n t_origin = ds_traj_posn_origin.time\n ds_position_scalars_origin = ds_position_scalars.sel(time=t_origin)\n ds_position_scalars_next = ds_position_scalars.sel(time=t_next)\n\n # for the original direction estimate we need *previous* position (i.e.\n # where we were before the \"origin\" point)\n ds_traj_posn_prev = ds_traj.isel(time=-2)\n\n ds_traj_posn_est = _extrapolate_single_timestep(\n ds_position_scalars_origin=ds_position_scalars_origin,\n ds_position_scalars_next=ds_position_scalars_next,\n ds_traj_posn_prev=ds_traj_posn_prev,\n ds_traj_posn_origin=ds_traj_posn_origin,\n )\n\n ds_traj = xr.concat([ds_traj, ds_traj_posn_est], dim=\"time\")\n\n return ds_traj\n","sub_path":"advtraj/integrate/forward.py","file_name":"forward.py","file_ext":"py","file_size_in_byte":6329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"527974867","text":"import sys, os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\nimport torch\nimport torch.nn as nn\nimport torchvision.transforms as transforms\nimport pandas as pd\nfrom torch.utils.data import DataLoader, Dataset\nimport time\nfrom myModel import Classifier, ImgDataset\n\nnum_epoch = 150\nnum_all_epoch = 150 \nbatch_size = 84\n\ndef adjust_learning_rate(optimizer, lr):\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\ndataset_path = '../data/food-11/data.npz'\n\nif len(sys.argv) == 2:\n dataset_path = sys.argv[1] + '/data.npz'\n\nloadfile = np.load(dataset_path)\ntrain_x = loadfile['tr_x']\ntrain_y = loadfile['tr_y']\nval_x = loadfile['val_x']\nval_y = loadfile['val_y']\n\n#training 時做 data augmentation\ntrain_transform = transforms.Compose([\n transforms.ToPILImage(),\n transforms.RandomHorizontalFlip(), #隨機將圖片水平翻轉\n transforms.RandomRotation(15), #隨機旋轉圖片\n transforms.ToTensor(), #將圖片轉成 Tensor,並把數值normalize到[0,1](data normalization)\n])\n#testing 時不需做 data augmentation\ntest_transform = transforms.Compose([\n transforms.ToPILImage(), \n transforms.ToTensor(),\n])\n\ntrain_set = ImgDataset(train_x, train_y, train_transform)\nval_set = ImgDataset(val_x, val_y, test_transform)\ntrain_loader = DataLoader(train_set, batch_size=batch_size, shuffle=True)\nval_loader = DataLoader(val_set, batch_size=batch_size, shuffle=False)\n\nmodel = Classifier().cuda()\nloss = nn.CrossEntropyLoss() # 因為是 classification task,所以 loss 使用 CrossEntropyLoss\noptimizer = torch.optim.Adam(model.parameters(), lr=0.001) # optimizer 使用 Adam\n\nprint('Start training...')\n\ntrain_loss_his = []\nval_loss_his = []\ntrain_acc_his = []\nval_acc_his = []\n\nlr = 0.001\n\nfor epoch in range(num_epoch):\n epoch_start_time = time.time()\n train_acc = 0.0\n train_loss = 0.0\n val_acc = 0.0\n val_loss = 0.0\n\n if epoch < 15:\n lr = 0.001\n elif epoch < 30:\n lr = 5E-4\n else:\n lr = 2E-4\n adjust_learning_rate(optimizer, lr)\n\n model.train() # 確保 model 是在 train model (開啟 Dropout 等...)\n for i, data in enumerate(train_loader):\n optimizer.zero_grad() # 用 optimizer 將 model 參數的 gradient 歸零\n train_pred = model(data[0].cuda()) # 利用 model 得到預測的機率分佈 這邊實際上就是去呼叫 model 的 forward 函數\n batch_loss = loss(train_pred, data[1].cuda()) # 計算 loss (注意 prediction 跟 label 必須同時在 CPU 或是 GPU 上)\n batch_loss.backward() # 利用 back propagation 算出每個參數的 gradient\n optimizer.step() # 以 optimizer 用 gradient 更新參數值\n\n train_acc += np.sum(np.argmax(train_pred.cpu().data.numpy(), axis=1) == data[1].numpy())\n train_loss += batch_loss.item()\n \n \n model.eval()\n with torch.no_grad():\n for i, data in enumerate(val_loader):\n val_pred = model(data[0].cuda())\n batch_loss = loss(val_pred, data[1].cuda())\n\n val_acc += np.sum(np.argmax(val_pred.cpu().data.numpy(), axis=1) == data[1].numpy())\n val_loss += batch_loss.item()\n\n train_acc_his.append(train_acc/train_set.__len__())\n train_loss_his.append(train_loss/train_set.__len__())\n val_acc_his.append(val_acc/val_set.__len__())\n val_loss_his.append(val_loss/val_set.__len__())\n\n #將結果 print 出來\n print('[%03d/%03d] %2.2f sec(s) Train Acc: %3.6f Loss: %3.6f | Val Acc: %3.6f loss: %3.6f' % \\\n (epoch + 1, num_epoch, time.time()-epoch_start_time, \\\n train_acc/train_set.__len__(), train_loss/train_set.__len__(), val_acc/val_set.__len__(), val_loss/val_set.__len__()))\n\n# timestr = time.strftime(\"%Y%m%d-%H-%M-%S\")\n# torch.save(model, './data/model_no_val_{}.pkl'.format(timestr)) # save model\n\ntrain_val_x = np.concatenate((train_x, val_x), axis=0)\ntrain_val_y = np.concatenate((train_y, val_y), axis=0)\ntrain_val_set = ImgDataset(train_val_x, train_val_y, train_transform)\ntrain_val_loader = DataLoader(train_val_set, batch_size=batch_size, shuffle=True)\n\ntrain_val_loss_his = []\ntrain_val_acc_his = []\n\nmodel_best = Classifier().cuda()\nloss = nn.CrossEntropyLoss() # 因為是 classification task,所以 loss 使用 CrossEntropyLoss\noptimizer = torch.optim.Adam(model_best.parameters(), lr=0.001) # optimizer 使用 Adam\n\nfor epoch in range(num_all_epoch):\n epoch_start_time = time.time()\n train_acc = 0.0\n train_loss = 0.0\n\n if epoch < 15:\n lr = 0.001\n elif epoch < 30:\n lr = 5E-4\n else:\n lr = 2E-4\n adjust_learning_rate(optimizer, lr)\n\n model_best.train()\n for i, data in enumerate(train_val_loader):\n optimizer.zero_grad()\n train_pred = model_best(data[0].cuda())\n batch_loss = loss(train_pred, data[1].cuda())\n batch_loss.backward()\n optimizer.step()\n\n train_acc += np.sum(np.argmax(train_pred.cpu().data.numpy(), axis=1) == data[1].numpy())\n train_loss += batch_loss.item()\n\n\n train_val_acc_his.append(train_acc/train_val_set.__len__())\n train_val_loss_his.append(train_loss/train_val_set.__len__())\n\n #將結果 print 出來\n print('[%03d/%03d] %2.2f sec(s) Train Acc: %3.6f Loss: %3.6f' % \\\n (epoch + 1, num_epoch, time.time()-epoch_start_time, \\\n train_acc/train_val_set.__len__(), train_loss/train_val_set.__len__()))\n\ntimestr = time.strftime(\"%Y%m%d-%H-%M-%S\")\n\ntorch.save(model_best, './data/model_{}.pkl'.format(timestr)) # save model\n\n# Plot\n# Loss curve\nplt.plot(train_loss_his)\nplt.plot(val_loss_his)\n# plt.plot(train_val_loss_his)\nplt.title('Loss')\nplt.legend(['train', 'val', 'train-val'])\nplt.savefig('./figure/loss_{}.png'.format(timestr))\n# plt.show()\nplt.clf()\n\n# Accuracy curve\nplt.plot(train_acc_his)\nplt.plot(val_acc_his)\n# plt.plot(train_val_acc_his)\nplt.title('Accuracy')\nplt.legend(['train', 'val', 'train-val'])\nplt.savefig('./figure/accuracy_{}.png'.format(timestr))\n# plt.show()\nplt.clf()\n","sub_path":"hw3/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"197528960","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 19 20:55:35 2019\n\n@author: user\n\"\"\"\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n\nheader={'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36'}\n\ncontent=requests.get(\"https://web.cpc.com.tw/division/mb/oil-more1-1.aspx\",headers=header).text#抓網頁裡面的標頭\n\nsoup=BeautifulSoup(content,'html.parser')\n\ndata=soup.find(id='Showtd')\n\nallrows = data.find_all('tr')\n\ni=0\n\nfor row in allrows:\n i+=1\n if i>=1:\n cols=row.find_all('td')\n print(cols[1].text,cols[6].text,)\n print()","sub_path":"2019-11-19資料擷取/ex07-中油油名價格抓取.py","file_name":"ex07-中油油名價格抓取.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"528633165","text":"import os\nimport ServerAction\nfrom flask import Flask, request, jsonify\n\nimport base64\n\napp = Flask(__name__)\n\n\n# root\n@app.route(\"/\")\ndef index():\n \"\"\"\n this is a root dir of my server\n :return: str\n \"\"\"\n return \"This is root!!!!\"\n\n\n# GET\n@app.route('/users/')\ndef hello_user(user):\n \"\"\"\n this serves as a demo purpose\n :param user:\n :return: str\n \"\"\"\n return \"Hello %s!\" % user\n\n# POST\n@app.route('/upload/', methods=['POST'])\ndef uploadText():\n \"\"\"\n predicts requested text whether it is ham or spam\n :return: json\n \"\"\"\n json = request.get_json()\n print(json)\n if len(json['text']) == 0:\n return 'error invalid input'\n\n triplets = json['text']\n\n print(triplets)\n with open('retrievedTriplets.txt', 'w+') as f:\n f.write(triplets)\n ServerAction.tripletsToDot('retrievedTriplets.txt')\n # ServerAction.convertDotToPNG('cExample1.dot')\n ServerAction.convertDotToPNGJulia('cExample1.dot')\n\n with open(\"net.png\", \"rb\") as image_file:\n encoded_string = base64.b64encode(image_file.read())\n return encoded_string\n\n\n# # Flask\n# from flask import request\n# import json\n# from froala_editor import File\n# from froala_editor import FlaskAdapter\n#\n#\n# @app.route('/upload_file', methods=['POST'])\n# def upload_file():\n# try:\n# response = File.upload(FlaskAdapter(request), '/public/')\n# except Exception:\n# response = {'error': str(sys.exc_info()[1])}\n# return json.dumps(response)\n\n\nif __name__ == '__main__':\n # app.run(host='0.0.0.0', port=5000)\n app.run(host='127.0.0.1', port=80)\n\n\n# reduce network needs a file with the nodes you want to keep\n#","sub_path":"ParsingTxt/Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"646587563","text":"# -*- coding: utf-8 -*-\n\"\"\"Query the worldcat.org xID service for related ISBNs.\"\"\"\n\nimport logging\nfrom ast import literal_eval\n\nfrom .dev._exceptions import DataWrongShapeError, NoDataForSelectorError\nfrom .dev.webquery import query as wquery\n\nLOGGER = logging.getLogger(__name__)\nUA = 'isbnlib (gzip)'\nSERVICE_URL = 'http://xisbn.worldcat.org/webservices/xid/isbn/{isbn}?'\\\n 'method=getEditions&format=python'\n\n\ndef _editions(isbn, data):\n \"\"\"Return the records from the parsed response.\"\"\"\n # check status\n try:\n status = data['stat']\n if status != 'ok':\n raise # pragma: no cover\n except: # pragma: no cover\n LOGGER.debug('DataWrongShapeError for %s with status %s', isbn, status)\n raise DataWrongShapeError(\"status: '%s' for isbn %s\" % (status, isbn))\n # put the selected data in records\n try:\n recs = [ib['isbn'][0] for ib in data['list']]\n except: # pragma: no cover\n LOGGER.debug('NoDataForSelectorError for %s', isbn)\n raise NoDataForSelectorError(isbn)\n return recs\n\n\ndef query(isbn):\n \"\"\"Query the worldcat.org service for related ISBNs.\"\"\"\n data = wquery(\n SERVICE_URL.format(isbn=isbn), user_agent=UA, parser=literal_eval)\n return _editions(isbn, data)\n","sub_path":"boi2/venv/Lib/site-packages/isbnlib/_wcated.py","file_name":"_wcated.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"650692182","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Nov 15 20:02:28 2020\n\n@author: JARVIS\n\"\"\"\n\n# Importing libraries\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.svm import SVC\nimport pickle\n\n# Initializing of embedding and recognizer\nembeddingFile = 'output/embeddings.pickle'\n#new and empty at initial\nrecognizerFile = 'output/recognizer.pickle'\nlabelEncFile = 'output/labelEncoder.pickle'\n\nprint('Loading face embeddings...')\ndata = pickle.loads(open(embeddingFile, 'rb').read())\n\nprint('Encoding labels...')\nlabelEnc = LabelEncoder()\nlabels = labelEnc.fit_transform(data['names'])\n\nprint('Training Model...')\nrecognizer = SVC(C = 1.0, kernel = 'linear', probability = True)\nrecognizer.fit(data['embeddings'], labels)\n\nf = open(recognizerFile, 'wb')\nf.write(pickle.dumps(recognizer))\nf.close()\n\nf = open(labelEncFile, 'wb')\nf.write(pickle.dumps(labelEnc))\nf.close()","sub_path":"training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"547596764","text":"from django.test import TestCase\nfrom lms.models import User, Loan\nfrom django.urls import reverse\nfrom rest_framework.test import APIClient\nfrom rest_framework import status\nimport re\nfrom lms.utils import dprint\nimport time\nfrom pprint import pprint\nfrom .helper_setUp_func import setUp_users\n\nclass ApproveLoanTest(TestCase):\n def setUp(self):\n self.client = APIClient()\n\n self.customer_login_token , self.agent_login_token, self.admin_login_token = setUp_users()\n\n all_admins = User.objects.filter(role='admin')\n self.admin_1 = all_admins.first()\n self.admin_2 = all_admins.last()\n\n all_agents = User.objects.filter(role='agent')\n self.agent_1 = all_agents.first()\n\n all_customers = User.objects.filter(role='customer')\n self.customer_1 = all_customers.first()\n\n #create loan\n customer_loan_request = {\n 'customer-id' : self.customer_1.id,\n 'principal-amount' : \"10000\",\n 'interest-rate' : \"1\",\n 'tenure-months' : \"12\"\n }\n self.client.credentials(HTTP_AUTHORIZATION=self.agent_login_token)\n self.client.post(reverse('lms:create_loan'), customer_loan_request) \n\n def test_approve_loan_by_customer(self):\n loan_obj = Loan.objects.last()\n approve_loan_url = reverse('lms:approve_loan' , kwargs={'id' : loan_obj.id})\n self.client.credentials(HTTP_AUTHORIZATION=self.customer_login_token)\n res = self.client.post(approve_loan_url)\n\n self.assertFalse(loan_obj.is_approved)\n self.assertFalse(loan_obj.status=='approved')\n self.assertEqual(res.status_code, status.HTTP_403_FORBIDDEN)\n\n def test_approve_loan_by_agent(self):\n loan_obj = Loan.objects.last()\n approve_loan_url = reverse('lms:approve_loan' , kwargs={'id' : loan_obj.id})\n self.client.credentials(HTTP_AUTHORIZATION=self.agent_login_token)\n res = self.client.post(approve_loan_url)\n\n self.assertFalse(loan_obj.is_approved)\n self.assertFalse(loan_obj.status=='approved')\n self.assertEqual(res.status_code, status.HTTP_403_FORBIDDEN)\n\n def test_approve_loan_by_admin(self):\n loan_obj = Loan.objects.last()\n self.assertFalse(loan_obj.is_approved)\n approve_loan_url = reverse('lms:approve_loan' , kwargs={'id' : loan_obj.id})\n self.client.credentials(HTTP_AUTHORIZATION=self.admin_login_token)\n res = self.client.post(approve_loan_url)\n\n loan_obj = Loan.objects.last()\n self.assertEqual(res.status_code, status.HTTP_202_ACCEPTED)\n self.assertTrue(loan_obj.is_approved)\n self.assertEqual(loan_obj.status,'approved')\n\n def test_aprove_non_existent_loan(self):\n approve_loan_url = reverse('lms:approve_loan' , kwargs={'id' : 879})\n self.client.credentials(HTTP_AUTHORIZATION=self.admin_login_token)\n res = self.client.post(approve_loan_url)\n\n self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)\n","sub_path":"LOAN/apps/lms/tests/apis/test_approve_loan.py","file_name":"test_approve_loan.py","file_ext":"py","file_size_in_byte":3010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"398609598","text":"import logging\nimport multiprocessing as mp\nimport queue\n\nimport rethinkdb as r\n\nfrom bigchaindb.core_snapshot import BigchainWithSnapshot\nimport bigchaindb\nfrom bigchaindb import Bigchain\nfrom bigchaindb.monitor import Monitor\nfrom bigchaindb.util import ProcessGroup\nimport time\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Snapshot(object):\n\n def __init__(self, period_seconds=3600):\n \"\"\"\n Initialize the class with the needed\n \"\"\"\n # self._q_new_block = q_new_block\n # self.q_new_block = None\n self.q_block_to_validate = mp.Queue()\n self.q_block_validated = mp.Queue()\n self.q_snapshot = mp.Queue()\n self.initialized = mp.Event()\n self.monitor = Monitor()\n self.period = period_seconds\n\n # def get_new_blocks(self, last_snapshot_block_number):\n # b = BigchainWithSnapshot()\n # end_block = b.get_last_decided_block()\n\n\n def validate_block(self):\n \"\"\"\n Checks if the incoming blocks are decided and valid\n \"\"\"\n\n # create a bigchain instance\n b = BigchainWithSnapshot()\n\n while True:\n self.monitor.gauge('tx_queue_gauge',\n self.q_block_to_validate.qsize(),\n rate=bigchaindb.config['statsd']['rate'])\n block = self.q_block_to_validate.get()\n\n # poison pill\n if block == 'stop':\n self.q_block_validated.put('stop')\n return\n\n with self.monitor.timer('validate_block', rate=bigchaindb.config['statsd']['rate']):\n is_valid_block = b.is_valid_block(block)\n\n if is_valid_block:\n self.q_block_validated.put(block)\n\n def create_snapshot(self):\n \"\"\"\n Create a snapshot with valid block\n \"\"\"\n\n # create a bigchain instance\n b = BigchainWithSnapshot()\n stop = False\n\n last_snapshot = b.get_last_snapshot()\n\n last_snapshot_block_number = last_snapshot[\"snapshot\"][\"end_block\"][\"block_number\"]\n\n new_decided_blocks = b.get_new_decided_blocks(last_snapshot_block_number)\n new_valid_blocks = []\n end_block ={}\n for block in new_decided_blocks:\n if b.is_valid_block(block):\n new_valid_blocks.append(block)\n\n new_snapshot = b.create_snapshot(new_valid_blocks, last_snapshot)\n b.write_snapshot(new_snapshot)\n\n while True:\n\n validated_blocks = []\n\n while True:\n try:\n tx = self.q_block_validated.get(timeout=5)\n except queue.Empty:\n break\n\n # poison pill\n if tx == 'stop':\n stop = True\n break\n\n validated_blocks.append(tx)\n\n if validated_blocks:\n # create snapshot\n last_snapshot = b.get_last_snapshot()\n snapshot = b.create_snapshot(validated_blocks, last_snapshot)\n self.q_snapshot.put(snapshot)\n\n if stop:\n self.q_snapshot.put('stop')\n return\n\n # create snapshot periodically\n time.sleep(self.period)\n\n def write_snapshot(self):\n \"\"\"\n Write snapshot to the bigchain\n \"\"\"\n\n # create bigchain instance\n b = BigchainWithSnapshot()\n\n # Write snapshot\n while True:\n snapshot = self.q_snapshot.get()\n\n # poison pill\n if snapshot == 'stop':\n return\n\n with self.monitor.timer('write_snapshot'):\n b.write_snapshot(snapshot)\n\n def bootstrap(self):\n \"\"\"\n Get transactions from the backlog that may have been assigned to this while it was\n online (not listening to the changefeed)\n \"\"\"\n # create bigchain instance\n b = Bigchain()\n\n # create a queue to store initial results\n q_initial = mp.Queue()\n\n # get initial results\n initial_results = r.table('backlog')\\\n .between([b.me, r.minval], [b.me, r.maxval], index='assignee__transaction_timestamp')\\\n .order_by(index=r.asc('assignee__transaction_timestamp'))\\\n .run(b.conn)\n\n # add results to the queue\n for result in initial_results:\n q_initial.put(result)\n\n for i in range(mp.cpu_count()):\n q_initial.put('stop')\n\n return q_initial\n\n def start(self):\n \"\"\"\n Bootstrap and start the processes\n \"\"\"\n logger.info('bootstraping block module...')\n self.q_new_transaction = self.bootstrap()\n logger.info('finished reading past transactions')\n self._start()\n logger.info('finished bootstraping block module...')\n\n logger.info('starting block module...')\n self.q_new_transaction = self._q_new_transaction\n\n # signal initialization complete\n self.initialized.set()\n\n self._start()\n logger.info('exiting block module...')\n\n def kill(self):\n for i in range(mp.cpu_count()):\n self.q_new_transaction.put('stop')\n\n def _start(self):\n \"\"\"\n Initialize, spawn, and start the processes\n \"\"\"\n\n # initialize the processes\n\n p_blocks = ProcessGroup(name='create_blocks', target=self.create_snapshot)\n p_write = ProcessGroup(name='write_blocks', target=self.write_snapshot)\n\n # start the processes\n p_blocks.start()\n p_write.start()\n","sub_path":"snapshot/snapshot_block.py","file_name":"snapshot_block.py","file_ext":"py","file_size_in_byte":5574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"478145764","text":"\"\"\"\nESCUELA SUPERIOR DE CÓMPUTO\nAnálisis de Algoritmos\nGrupo: 3CV2\nSemestre: 20/1\n\nIntegrantes:\nRivera Paredes Fernando Daniel\nContreras Paredes Alejandro\n\nPractica 4a : Partition\n\"\"\"\n#*llamamos a las bibliotecas necesarias\n#*llamamos a la funcion Graphics\nimport random\nfrom Graficas import Graphics\ntime = 0\n#!Definimos la función Partition y usamos un contador en cada iteracion\ndef Partition(A,p,r):\n global time\n\n x = A[r]; time += 1\n i = p - 1; time += 1\n j = p; time+=1\n while(j < r):\n if(A[j] <= x):\n time += 1\n i += 1\n aux=A[i]\n A[i]=A[j]\n A[j]=aux\n j += 1; time+=1\n aux=A[i + 1]; time+=1\n A[i + 1]=A[r]; time+=1\n A[r]=aux; time+=2\n return i+1 \n \n#!Definimos una funcion para llenar aleatoriamente el arreglo\ndef llenarAleatoriamente(A, n):\n for k in range(n):\n A.append(random.randint(4,1000))\n\n#!Definimos la funcion donde se generan los resultados de el peor de los casos\ndef PResult(limit, file):\n #?Definimos variables globales que ayudaran al conteo\n global time\n A = []\n p = 0\n #*Le damos valores al arreglo para que sea el peor de los casos\n for i in range (limit):\n n = i + 5\n A.clear()\n for j in range(n):\n A.append(10)\n r = n-1\n #*LLamamos Partition con los indices creados\n Partition(A,p,r)\n #*LLamamos impresion con los indices indicados\n impresion(time, file, limit, i + 1)\n time = 0\n\n#!Definimos la funcion donde se generan los resultados en casos aleatorios\ndef CaAleatorio(limit, file):\n #?Definimos variables globales que ayudaran al conteo\n global time\n A = []\n #*Le damos valores al arreglo para que sean casos aleatorios\n for i in range (limit):\n A.clear()\n p = 0\n n = i + 5\n r = n - 1\n #*LLamamos llenarAleatoriamente\n llenarAleatoriamente(A, n)\n #*LLamamos Partition con los indices creados\n Partition(A,p,r)\n #*LLamamos impresion con los indices indicados\n impresion(time, file, limit, i + 1)\n time = 0\n\n#!Es donde se escribe en un archivo el tamaño del arreglo\ndef escrituraN(n, file):\n for i in range(n):\n impresion(i + 1, file, n - 1, i)\n\n#! Definicion de la funcion que determina el modo de impresion para los resultado recibidos\ndef impresion(item, file, limit, index):\n #* Si index es el ultimo elemento (limit) escribe un salto de linea\n if index == limit:\n print(item, file = file, end='\\n')\n #* Sino escribe una comida seguida de un espacio\n else: \n print(item, file = file, end=', ')\n\n#! Definicion de la funcion main\ndef main():\n #?Definimos variables globales que ayudaran al conteo\n global time\n #* abrimos el archivo donde guardaremos los datos recolectados \n file = open(\"./files_practices/pract_4a.txt\", 'w')\n limit = 30\n\n #* LLamamos las funciones para cada uno de los casos\n CaAleatorio(limit, file)\n escrituraN(limit, file)\n PResult(limit, file)\n escrituraN(limit, file)\n\n #*Cerramos el archivo\n file.close()\n #*Configuramos la grafica\n title = \"Partition\"\n x_label = \"n: Tamaño del arreglo\"\n y_label = \"t: Tiempo de ejecución\"\n big_O = \"n\"\n theta = \"n\"\n #* Graficamos los resultados\n graph = Graphics(\"./files_practices/pract_4a.txt\")\n graph.graficar(title, x_label, y_label, big_O, theta)\n\n\n\nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"Parcial 1/Practica 4/Partition.py","file_name":"Partition.py","file_ext":"py","file_size_in_byte":3502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"105153217","text":"from scipy.optimize import fsolve\nfrom first_1000_zeta import first_1000_zeta\nfrom utility import Ht_real\n\nimport sys\n\norig_stdout = sys.stdout\nf = open('out_0001_1000_01_49.txt', 'w')\nsys.stdout = f\n\n\nfirst_1000_H0_zero = [x*2 for x in first_1000_zeta]\n\n# k is a stopping parameter (1<=k<=1000) which corresponds to the kth zero of\n# the H_0 fn while l is the starting parameter. Default is 1, 1000.\n\nl = 1\n\nk = 1000\n\nfor j in range(1, 50):\n t = .01*j\n for i, nearby_root in enumerate(first_1000_H0_zero[l-1:k-1]):\n Ht_root = fsolve(Ht_real, nearby_root, args=(t,))[0]\n print(t, i, Ht_root)\n\nsys.stdout = orig_stdout\nf.close()\n","sub_path":"dbn_upper_bound/python/H_t_probable_first_1000_zeroes.py","file_name":"H_t_probable_first_1000_zeroes.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"488134782","text":"# -*- encoding: utf8 -*-\n'''\nCreated on 24 Oct 2017\n\n@author: MetalInvest\n'''\ntry:\n from kuanke.user_space_api import *\nexcept:\n pass\nimport enum\nimport math\nimport json\nfrom pickle import dump\nfrom pickle import load\nimport numpy as np\nimport io\n# from keras.utils.np_utils import to_categorical\n# from sklearn.preprocessing import MinMaxScaler, StandardScaler\n\nevs_query_string = '(valuation.market_cap*100000000+balance.longterm_loan+balance.bonds_payable+balance.minority_interests+balance.capital_reserve_fund-balance.cash_equivalents)/(income.net_profit+income.income_tax_expense+income.interest_expense)'\neve_query_string = '(valuation.market_cap*100000000+balance.longterm_loan+balance.bonds_payable+balance.minority_interests+balance.capital_reserve_fund-balance.cash_equivalents)/(indicator.eps*valuation.capitalization*10000)'\n\n\nclass TaType(enum.Enum):\n MACD = 0,\n RSI = 1,\n BOLL = 2,\n MA = 3, \n MACD_STATUS = 4,\n TRIX = 5,\n BOLL_UPPER = 6,\n TRIX_STATUS = 7,\n TRIX_PURE = 8,\n MACD_ZERO = 9,\n MACD_CROSS = 10,\n KDJ_CROSS = 11,\n BOLL_MACD = 12\n\n def __le__(self, b):\n return self.value <= b.value\n\n\n'''===============================其它基础函数=================================='''\n\ndef get_growth_rate(security, n=20):\n '''\n 获取股票n日以来涨幅,根据当前价(前1分钟的close)计算\n n 默认20日 \n :param security: \n :param n: \n :return: float\n '''\n lc = get_close_price(security, n)\n c = get_close_price(security, 1, '1m')\n\n if not np.isnan(lc) and not np.isnan(c) and lc != 0:\n return (c - lc) / lc\n else:\n log.error(\"数据非法, security: %s, %d日收盘价: %f, 当前价: %f\" % (security, n, lc, c))\n return 0\n\n\ndef get_close_price(security, n, unit='1d'):\n '''\n 获取前n个单位时间当时的收盘价\n 为防止取不到收盘价,试3遍\n :param security: \n :param n: \n :param unit: '1d'/'1m'\n :return: float\n '''\n cur_price = np.nan\n for i in range(3):\n cur_price = attribute_history(security, n, unit, 'close', True)['close'][0]\n if not math.isnan(cur_price):\n break\n return cur_price\n\n\n# 获取一个对象的类名\ndef get_obj_class_name(obj):\n cn = str(obj.__class__)\n cn = cn[cn.find('.') + 1:]\n return cn[:cn.find(\"'\")]\n\n\ndef show_stock(stock):\n '''\n 获取股票代码的显示信息 \n :param stock: 股票代码,例如: '603822.XSHG'\n :return: str,例如:'603822 嘉澳环保'\n '''\n return \"%s:%s\" % (stock[:6], get_security_info(stock).display_name)\n\n\ndef join_list(pl, connector=' ', step=5):\n '''\n 将list组合为str,按分隔符和步长换行显示(List的成员必须为字符型)\n 例如:['1','2','3','4'],'~',2 => '1~2\\n3~4'\n :param pl: List\n :param connector: 分隔符,默认空格 \n :param step: 步长,默认5\n :return: str\n '''\n result = ''\n for i in range(len(pl)):\n result += pl[i]\n if (i + 1) % step == 0:\n result += '\\n'\n else:\n result += connector\n return result\n\n\ndef generate_portion(num):\n total_portion = num * (num+1) / 2\n start = num\n while num != 0:\n yield float(num) / float(total_portion)\n num -= 1\n \ndef batch(iterable, n=1, start=0):\n l = len(iterable)\n for ndx in range(start, l, n): # restart\n yield [ndx,min(ndx + n, l)] \n \ndef save_dataset(dataset, filename, isDebug=True):\n dump(dataset, open(filename, 'wb'))\n if isDebug:\n print('Saved: %s' % filename)\n \ndef load_dataset(filename, isDebug=True):\n if isDebug:\n print('Loaded: %s' % filename)\n return load(open(filename, 'rb'))\n\ndef save_dataset_json(dataset, filename):\n with open(filename, 'w', encoding=\"latin-1\") as outfile: #'utf-8'\n memfile = io.BytesIO()\n np.save(memfile, dataset)\n memfile.seek(0)\n json_dump = json.dumps(memfile.read().decode(\"latin-1\")) \n outfile.write(json_dump)\n print('Saved: %s' % filename)\n \ndef load_dataset_json(filename): \n with open(filename, encoding='utf-8') as data_file:\n data = json.loads(data_file.read())\n memfile = io.BytesIO()\n memfile.write(json.loads(data).encode('utf-8'))\n memfile.seek(0)\n print('Loaded: %s' % filename)\n return np.load(memfile) \n \ndef save_dataset_np(dataset, filename):\n np.save(filename, dataset)\n print('Saved: %s' % filename)\n \ndef load_dataset_np(filename):\n print('Loaded: %s' % filename)\n return np.load(filename)\n\ndef pad_each_training_array(data_list, max_sequence_length):\n new_shape = findmaxshape(data_list)\n if max_sequence_length != 0: # force padding to global max length\n new_shape = (max_sequence_length, new_shape[1]) \n new_data_list = fillwithzeros(data_list, new_shape)\n return new_data_list\n\ndef fillwithzeros(inputarray, outputshape):\n \"\"\"\n Fills input array with dtype 'object' so that all arrays have the same shape as 'outputshape'\n inputarray: input numpy array\n outputshape: max dimensions in inputarray (obtained with the function 'findmaxshape')\n\n output: inputarray filled with zeros\n \"\"\"\n length = len(inputarray)\n output = np.zeros((length,)+outputshape)\n for i in range(length):\n if inputarray[i].shape[0] <= outputshape[0]:\n output[i][:inputarray[i].shape[0],:inputarray[i].shape[1]] = inputarray[i]\n else:\n output[i][:outputshape[0], :outputshape[1]] = inputarray[i][-outputshape[0]:,-outputshape[1]:]\n# print(inputarray[i].shape)\n# print(output[i].shape)\n# print(inputarray[i])\n# print(output[i])\n return output\n\ndef findmaxshape(inputarray):\n \"\"\"\n Finds maximum x and y in an inputarray with dtype 'object' and 3 dimensions\n inputarray: input numpy array\n\n output: detected maximum shape\n \"\"\"\n max_x, max_y = 0, 0\n for array in inputarray:\n x, y = array.shape\n if x > max_x:\n max_x = x\n if y > max_y:\n max_y = y\n return(max_x, max_y)\n\ndef sort_training_dataset_by_sublength(dataset, label):\n \"\"\"\n Input: training/testing dataset label\n output: training/testing dataset label sorted by sub sequence length in dataset\n \"\"\"\n narrayData = sorted(dataset, key=len, reverse=False)\n length_index = np.argsort([len(seq) for seq in dataset])\n\n narrayLabel = np.array(label)[length_index]\n \n return narrayData, narrayLabel\n \ndef encode_category(label_set): # this is assuming we have full label in the sample\n from keras.utils.np_utils import to_categorical\n uniques, ids = np.unique(label_set, return_inverse=True)\n y_code = to_categorical(ids, len(uniques))\n return y_code\n\ndef normalize(df, norm_range=[0, 1], fields = ['open', 'close', 'high', 'low', 'money']):\n from sklearn.preprocessing import MinMaxScaler, StandardScaler\n scaler = MinMaxScaler(feature_range=norm_range) if norm_range is not None else StandardScaler()\n df[fields] = scaler.fit_transform(df[fields]) \n return df\n\ndef copy_4_prd(path):\n c = read_file(path)\n with open(path, 'wb') as f:\n f.write(c)","sub_path":"JoinQuantStrat/Utility/common_include.py","file_name":"common_include.py","file_ext":"py","file_size_in_byte":7292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"482176541","text":"import requests\nfrom bs4 import BeautifulSoup\nimport csv\n\nURL = \"https://search.scielo.org/?lang=pt&count=5&from=0&output=site&sort=&format=summary&fb=&page=1&q=historia+do+tempo+presente\"\nr = requests.get(URL)\n\nsoup = BeautifulSoup(r.content, 'html.parser')\n\nlast_links = soup.find(class_='modal fade')\nlast_links.decompose()\n\nresult_title_list = soup.find_all(class_='a')\nresult_title_list_items = soup.find_all(class_='title')\n\nfor result_title in result_title_list_items:\n names = result_title.contents[0]\n\nprint(names)\n","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"190437053","text":"\"\"\"Support Bitbucket's REST interface.\n\nAPI docs:\n https://api.bitbucket.org/\n https://developer.atlassian.com/cloud/bitbucket/\n\nUpdates:\n https://blog.bitbucket.org/\n\"\"\"\n\nfrom warnings import warn\n\nfrom dateutil.parser import parse as dateparse\nfrom multidict import MultiDict\nfrom snakeoil.klass import aliased, alias\n\nfrom ._jsonrest import JsonREST\nfrom ._reqs import (\n LinkPagedRequest, Request, req_cmd, ExtractData, QueryParseRequest,\n BaseGetRequest, BaseCommentsRequest, BaseChangesRequest,\n)\nfrom ._rest import RESTRequest\nfrom ..exceptions import BiteError, RequestError\nfrom ..objects import Item, Comment, Attachment, Change, TimeInterval\n\n\nclass BitbucketError(RequestError):\n \"\"\"Bitbucket service specific error.\"\"\"\n\n def __init__(self, msg, code=None, text=None):\n self.orig_msg = msg\n prefixed_msg = f'Bitbucket error: {msg}'\n super().__init__(msg=prefixed_msg, code=code, text=text)\n\n\nclass BitbucketIssue(Item):\n\n attributes = {\n 'assignee': 'Assignee',\n 'id': 'ID',\n 'title': 'Title',\n 'kind': 'Type',\n 'priority': 'Priority',\n 'reporter': 'Reporter',\n 'component': 'Component',\n 'votes': 'Votes',\n 'watches': 'Watchers',\n 'state': 'Status',\n 'version': 'Version',\n #'edited_on': 'Edited',\n 'created_on': 'Created',\n 'updated_on': 'Modified',\n }\n\n attribute_aliases = {\n 'owner': 'assignee',\n 'created': 'created_on',\n 'modified': 'updated_on',\n 'creator': 'reporter',\n 'status': 'state',\n }\n\n _print_fields = (\n ('assignee', 'Assignee'),\n ('title', 'Title'),\n ('id', 'ID'),\n ('kind', 'Type'),\n ('priority', 'Priority'),\n ('reporter', 'Reporter'),\n ('component', 'Component'),\n ('state', 'Status'),\n ('version', 'Version'),\n ('created_on', 'Created'),\n ('updated_on', 'Modified'),\n ('votes', 'Votes'),\n ('watches', 'Watchers'),\n ('comments', 'Comments'),\n ('attachments', 'Attachments'),\n ('changes', 'Changes'),\n )\n\n type = 'issue'\n\n def __init__(self, service, issue, get_desc=True):\n for k in self.attributes.keys():\n v = issue.get(k)\n if k in ('assignee', 'reporter') and v:\n v = v['username']\n elif k == 'reporter' and v is None:\n v = 'Anonymous'\n elif k in ('created_on', 'updated_on'):\n v = dateparse(v)\n elif k == 'component' and v:\n v = v['name']\n setattr(self, k, v)\n\n if get_desc:\n try:\n desc = issue['content']['raw'].strip()\n except KeyError:\n desc = ''\n self.description = BitbucketComment(\n count=0, text=desc, created=self.created_on, creator=self.reporter)\n\n\nclass BitbucketExtractData(ExtractData):\n \"\"\"Iterate over the results of a bitbucket data request call.\"\"\"\n\n def __init__(self, iterable):\n self.iterable = (x['values'] for x in iterable)\n\n def handle_exception(self, e):\n # TODO: report this upstream\n # bitbucket appears to have issues retrieving changes for certain\n # issues, for example run: `bite -c sqlalchemy changes 1546`\n #\n # So for now if we get HTTP 500s, we toss a warning and return nothing.\n if e.code == 500:\n warn(f'failed retrieving data for \"{e.request.url}\": {e}')\n return ()\n else:\n raise e\n\n\nclass BitbucketComment(Comment):\n\n @classmethod\n def parse(cls, data):\n for comments in data:\n l = []\n for i, c in enumerate(comments, start=1):\n creator = c['user']\n if creator is not None:\n creator = creator['username']\n # skip comments that have no content, i.e. issue attribute changes\n if c['content']['raw']:\n l.append(cls(\n count=i, text=c['content']['raw'].strip(),\n created=dateparse(c['created_on']), creator=creator))\n yield tuple(l)\n\n\nclass BitbucketAttachment(Attachment):\n pass\n\n\nclass BitbucketEvent(Change):\n\n def __init__(self, id, count, change):\n creator = change['user']\n if creator is not None:\n creator = creator['username']\n created = dateparse(change['created_on'])\n changes = {}\n for k, v in change['changes'].items():\n if k == 'content':\n changes['description'] = 'updated'\n else:\n changes[BitbucketIssue.attributes.get(k, k)] = (v['old'], v['new'])\n\n super().__init__(\n creator=creator, created=created, id=id,\n changes=changes, count=count)\n\n @classmethod\n def parse(cls, data):\n for changes in data:\n yield tuple(cls(\n id=c['id'], count=i, change=c)\n for i, c in enumerate(changes, start=1))\n\n\nclass Bitbucket(JsonREST):\n \"\"\"Service supporting the Bitbucket-based issue trackers.\"\"\"\n\n _service = 'bitbucket'\n _service_error_cls = BitbucketError\n\n item = BitbucketIssue\n item_endpoint = '/issues/{id}'\n attachment = BitbucketAttachment\n\n def __init__(self, base, max_results=None, **kw):\n try:\n api_base, user, repo = base.rstrip('/').rsplit('/', 2)\n except ValueError as e:\n raise BiteError(f'invalid project base: {base!r}')\n self._api_base = f'{api_base}/api/2.0'\n endpoint = f'/repositories/{user}/{repo}'\n # bitbucket cloud supports 100 results per page\n if max_results is None:\n max_results = 100\n # TODO: generalize and allow versioned API support\n super().__init__(\n endpoint=endpoint, base=self._api_base, max_results=max_results, **kw)\n self.webbase = base\n\n def inject_auth(self, request, params):\n raise NotImplementedError\n\n def parse_response(self, response):\n data = super().parse_response(response)\n if data.get('type') != 'error':\n return data\n else:\n self.handle_error(code=response.status_code, msg=data['error']['message'])\n\n\nclass BitbucketPagedRequest(RESTRequest, LinkPagedRequest):\n\n _page = 'page'\n _pagelen = 'pagelen'\n _next = 'next'\n _previous = 'previous'\n _total_key = 'size'\n\n\n@req_cmd(Bitbucket, cmd='search')\nclass _SearchRequest(QueryParseRequest, BitbucketPagedRequest):\n \"\"\"Construct a search request.\"\"\"\n\n # map from standardized kwargs name to expected service parameter name\n _params_map = {\n 'created': 'created_on',\n 'modified': 'updated_on',\n 'watchers': 'watches',\n }\n\n def __init__(self, **kw):\n super().__init__(endpoint='/issues', **kw)\n\n def parse(self, data):\n data = super().parse(data)\n issues = data['values']\n for issue in issues:\n yield self.service.item(self.service, issue)\n\n @aliased\n class ParamParser(QueryParseRequest.ParamParser):\n\n # map of allowed sorting input values to service parameters\n _sorting_map = {\n 'assignee': 'assignee',\n 'id': 'id',\n 'title': 'title',\n 'type': 'kind',\n 'priority': 'priority',\n 'creator': 'reporter',\n 'component': 'component',\n 'votes': 'votes',\n 'watchers': 'watches',\n 'status': 'state',\n 'version': 'version',\n 'created': 'created_on',\n 'modified': 'updated_on',\n 'description': 'content',\n }\n\n # map of allowed priority input values to service parameters\n _priority_map = {\n 'trivial': 'trivial',\n 'minor': 'minor',\n 'major': 'major',\n 'critical': 'critical',\n 'blocker': 'blocker',\n }\n\n # map of allowed type input values to service parameters\n _type_map = {\n 'bug': 'bug',\n 'enhancement': 'enhancement',\n 'proposal': 'proposal',\n 'task': 'task',\n }\n\n # map of allowed status input values to service parameters\n _status_map = {\n 'new': 'new',\n 'open': 'open',\n 'resolved': 'resolved',\n 'on-hold': 'on hold',\n 'invalid': 'invalid',\n 'duplicate': 'duplicate',\n 'wontfix': 'wontfix',\n 'closed': 'closed',\n }\n\n # map of status alias names to matching status values\n _status_aliases = {\n 'OPEN': ('new', 'open', 'on hold'),\n 'CLOSED': ('resolved', 'invalid', 'duplicate', 'wontfix', 'closed'),\n 'ALL': _status_map.values(),\n }\n\n def _finalize(self, **kw):\n if not self.query:\n raise BiteError('no supported search terms or options specified')\n\n # default to showing issues that aren't closed\n if 'status' not in self.query:\n open_status_query = ' OR '.join(\n f'state = \"{x}\"' for x in self._status_aliases['OPEN'])\n self.query['status'] = f'({open_status_query})'\n\n self.params['q'] = ' AND '.join(self.query.values())\n\n # default to sorting ascending by issue ID\n if 'sort' not in self.params:\n self.params['sort'] = 'id'\n\n def terms(self, k, v):\n or_queries = []\n display_terms = []\n for term in v:\n or_terms = [x.replace('\"', '\\\\\"') for x in term.split(',')]\n or_search_terms = [f'title ~ \"{x}\"' for x in or_terms]\n or_display_terms = [f'\"{x}\"' for x in or_terms]\n if len(or_terms) > 1:\n or_queries.append(f\"({' OR '.join(or_search_terms)})\")\n display_terms.append(f\"({' OR '.join(or_display_terms)})\")\n else:\n or_queries.append(or_search_terms[0])\n display_terms.append(or_display_terms[0])\n self.query['summary'] = f\"{' AND '.join(or_queries)}\"\n self.options.append(f\"Summary: {' AND '.join(display_terms)}\")\n\n def sort(self, k, v):\n if v[0] == '-':\n key = v[1:]\n inverse = '-'\n else:\n key = v\n inverse = ''\n try:\n order_var = self._sorting_map[key]\n except KeyError:\n choices = ', '.join(sorted(self._sorting_map.keys()))\n raise BiteError(\n f'unable to sort by: {key!r} (available choices: {choices}')\n self.params[k] = f'{inverse}{order_var}'\n self.options.append(f\"Sort order: {v}\")\n\n def status(self, k, v):\n or_terms = []\n for status in v:\n try:\n or_terms.append(self._status_map[status])\n except KeyError:\n try:\n or_terms.extend(self._status_aliases[status])\n except KeyError:\n choices = ', '.join(sorted(self._status_map.keys()))\n aliases = ', '.join(sorted(self._status_aliases.keys()))\n raise BiteError(\n f'invalid status: {status!r} '\n f'(available choices: {choices}) '\n f'(aliases: {aliases})')\n q_str = ' OR '.join(f'state = \"{x}\"' for x in or_terms)\n if len(or_terms) > 1:\n q_str = f\"({q_str})\"\n self.query[k] = q_str\n self.options.append(f\"Status: {' OR '.join(or_terms)}\")\n\n def priority(self, k, v):\n or_terms = []\n for priority in v:\n try:\n or_terms.append(self._priority_map[priority])\n except KeyError:\n choices = ', '.join(sorted(self._priority_map.keys()))\n raise BiteError(\n f'invalid priority: {priority!r} (available choices: {choices})')\n q_str = ' OR '.join(f'priority = \"{x}\"' for x in or_terms)\n if len(or_terms) > 1:\n q_str = f\"({q_str})\"\n self.query[k] = q_str\n self.options.append(f\"Priority: {' OR '.join(or_terms)}\")\n\n def type(self, k, v):\n or_terms = []\n for type in v:\n try:\n or_terms.append(self._type_map[type])\n except KeyError:\n choices = ', '.join(sorted(self._type_map.keys()))\n raise BiteError(\n f'invalid type: {type!r} (available choices: {choices})')\n q_str = ' OR '.join(f'kind = \"{x}\"' for x in or_terms)\n if len(or_terms) > 1:\n q_str = f\"({q_str})\"\n self.query[k] = q_str\n self.options.append(f\"Type: {' OR '.join(or_terms)}\")\n\n @alias('modified')\n def created(self, k, v):\n if not isinstance(v, TimeInterval):\n v = TimeInterval(v)\n start, end = v\n if start:\n self.query.add(k, f'{self.remap[k]} >= {start.isoformat()}')\n if end:\n self.query.add(k, f'{self.remap[k]} <= {end.isoformat()}')\n self.options.append(f'{k.capitalize()}: {v}')\n\n @alias('watchers')\n def votes(self, k, v):\n self.query[k] = f'{self.remap.get(k, k)} >= {v}'\n self.options.append(f'{k.capitalize()}: >= {v}')\n\n def id(self, k, v):\n q_str = ' OR '.join(f'id = {x}' for x in v)\n if len(v) > 1:\n q_str = f\"({q_str})\"\n self.query[k] = q_str\n self.options.append(f\"IDs: {', '.join(map(str, v))}\")\n\n\n@req_cmd(Bitbucket)\nclass _GetItemRequest(Request):\n \"\"\"Construct an issue request.\"\"\"\n\n def __init__(self, ids, get_desc=True, **kw):\n super().__init__(**kw)\n if ids is None:\n raise ValueError(f'No {self.service.item.type} ID(s) specified')\n\n reqs = []\n for i in ids:\n reqs.append(RESTRequest(\n service=self.service, endpoint=f'/issues/{i}'))\n\n self.ids = ids\n self._reqs = tuple(reqs)\n self._get_desc = get_desc\n\n def parse(self, data):\n for issue in data:\n yield self.service.item(self.service, issue, get_desc=self._get_desc)\n\n\n@req_cmd(Bitbucket, cmd='comments')\nclass _CommentsRequest(BaseCommentsRequest):\n \"\"\"Construct a comments request.\"\"\"\n\n _iterate = BitbucketExtractData\n\n def __init__(self, **kw):\n super().__init__(**kw)\n\n if self.ids is None:\n raise ValueError(f'No {self.service.item.type} ID(s) specified')\n self.options.append(f\"IDs: {', '.join(self.ids)}\")\n\n reqs = []\n for i in self.ids:\n reqs.append(BitbucketPagedRequest(\n service=self.service, endpoint=f'/issues/{i}/comments'))\n\n self._reqs = tuple(reqs)\n\n def parse(self, data):\n yield from self.filter(BitbucketComment.parse(data))\n\n\n@req_cmd(Bitbucket, cmd='attachments')\nclass _AttachmentsRequest(Request):\n \"\"\"Construct an attachments request.\"\"\"\n\n def __init__(self, ids=(), attachment_ids=(), get_data=False, **kw):\n super().__init__(**kw)\n if not any((ids, attachment_ids)):\n raise ValueError(f'No ID(s) specified')\n\n if attachment_ids:\n ids = list(x[0] for x in attachment_ids)\n\n reqs = []\n for i in ids:\n reqs.append(BitbucketPagedRequest(\n service=self.service, endpoint=f'/issues/{i}/attachments'))\n\n self.ids = ids\n self.attachment_ids = attachment_ids\n self._reqs = tuple(reqs)\n self._get_data = get_data\n\n def parse(self, data):\n for attachments in data:\n if self.ids:\n attachments = attachments['values']\n\n if self._get_data:\n a_names = set()\n reqs = []\n for i, a_ids in self.attachment_ids:\n if not a_ids:\n a_ids = [x['name'] for x in attachments]\n a_names.update(a_ids)\n for a_id in a_ids:\n reqs.append(RESTRequest(\n service=self.service, raw=True,\n endpoint=f'/issues/{i}/attachments/{a_id}'))\n try:\n content = tuple(Request(\n service=self.service, reqs=reqs, raw=True).send(allow_redirects=True))\n except BitbucketError as e:\n if e.code == 404 and e.orig_msg in a_names:\n raise BitbucketError(f'unknown attachment: {e.orig_msg!r}')\n raise\n else:\n content = self._none_gen\n\n yield tuple(\n self.service.attachment(\n data=c, filename=a['name'], url=a['links']['self']['href'])\n for a, c in zip(attachments, content))\n\n\n@req_cmd(Bitbucket, cmd='changes')\nclass _ChangesRequest(BaseChangesRequest):\n \"\"\"Construct a changes request.\"\"\"\n\n _iterate = BitbucketExtractData\n\n def __init__(self, **kw):\n super().__init__(**kw)\n\n if self.ids is None:\n raise ValueError(f'No {self.service.item.type} ID(s) specified')\n self.options.append(f\"IDs: {', '.join(self.ids)}\")\n\n reqs = []\n for i in self.ids:\n reqs.append(BitbucketPagedRequest(\n service=self.service, endpoint=f'/issues/{i}/changes'))\n\n self._reqs = tuple(reqs)\n\n def parse(self, data):\n yield from self.filter(BitbucketEvent.parse(data))\n\n\n@req_cmd(Bitbucket, cmd='get')\nclass _GetRequest(BaseGetRequest):\n \"\"\"Construct requests to retrieve all known data for given issue IDs.\"\"\"\n\n def __init__(self, get_comments=True, **kw):\n super().__init__(get_comments=get_comments, **kw)\n self._get_comments = get_comments\n\n def parse(self, data):\n items, comments, attachments, changes = data\n for item in items:\n # Prepend comment for description which is provided by\n # GetItemRequest instead of CommentsRequest.\n if self._get_comments:\n item.comments = (item.description,) + next(comments)\n else:\n item.comments = next(comments)\n item.attachments = next(attachments)\n item.changes = next(changes)\n yield item\n","sub_path":"src/bite/service/bitbucket.py","file_name":"bitbucket.py","file_ext":"py","file_size_in_byte":18777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"271780560","text":"\"\"\"\n\n manage_local_batch.py\n \n Semi-automated process for managing a local MegaDetector job, including\n standard postprocessing steps.\n \n\"\"\"\n\n#%% Imports and constants\n\nimport json\nimport os\nimport stat\nimport time\n\nimport humanfriendly\n\nfrom tqdm import tqdm\n\n# from ai4eutils\nimport ai4e_azure_utils \nimport path_utils\n\nfrom detection.run_detector_batch import load_and_run_detector_batch, write_results_to_file\nfrom detection.run_detector import DEFAULT_OUTPUT_CONFIDENCE_THRESHOLD\n\nfrom api.batch_processing.postprocessing.postprocess_batch_results import (\n PostProcessingOptions, process_batch_results)\nfrom detection.run_detector import get_detector_version_from_filename\n\nmax_task_name_length = 92\n\n# To specify a non-default confidence threshold for including detections in the .json file\njson_threshold = None\n\n# Turn warnings into errors if more than this many images are missing\nmax_tolerable_failed_images = 100\n\nn_rendering_threads = 50\n\nuse_image_queue = False\n\n# Only relevant when we're using a single GPU\ndefault_gpu_number = 0\n\nquiet_mode = True\n\n# Specify a target image size when running MD... strongly recommended to leave this at \"None\"\nimage_size = None\n\n# Only relevant when running on CPU\nncores = 1\n\n\n#%% Constants I set per script\n\ninput_path = os.path.expanduser('~/data/organization/2021-12-24')\n\norganization_name_short = 'organization'\n# job_date = '2022-01-01'\njob_date = None\nassert job_date is not None and organization_name_short != 'organization'\n\n# Optional descriptor\njob_tag = None\n\nif job_tag is None:\n job_description_string = ''\nelse:\n job_description_string = '-' + job_tag\n\nmodel_file = os.path.expanduser('~/models/camera_traps/megadetector/md_v5.0.0/md_v5a.0.0.pt')\n# model_file = os.path.expanduser('~/models/camera_traps/megadetector/md_v5.0.0/md_v5b.0.0.pt')\n# model_file = os.path.expanduser('~/models/camera_traps/megadetector/md_v4.1.0/md_v4.1.0.pb')\n\npostprocessing_base = os.path.expanduser('~/postprocessing')\n\n# Number of jobs to split data into, typically equal to the number of available GPUs\nn_jobs = 2\nn_gpus = 2\n\n# Only used to print out a time estimate\nif ('v5') in model_file:\n gpu_images_per_second = 10\nelse:\n gpu_images_per_second = 2.9\n\ncheckpoint_frequency = 2000\n\nbase_task_name = organization_name_short + '-' + job_date + job_description_string + '-' + get_detector_version_from_filename(model_file)\nbase_output_folder_name = os.path.join(postprocessing_base,organization_name_short)\nos.makedirs(base_output_folder_name,exist_ok=True)\n\n\n#%% Derived variables, path setup\n\nfilename_base = os.path.join(base_output_folder_name, base_task_name)\ncombined_api_output_folder = os.path.join(filename_base, 'combined_api_outputs')\npostprocessing_output_folder = os.path.join(filename_base, 'preview')\n\nos.makedirs(filename_base, exist_ok=True)\nos.makedirs(combined_api_output_folder, exist_ok=True)\nos.makedirs(postprocessing_output_folder, exist_ok=True)\n\nif input_path.endswith('/'):\n input_path = input_path[0:-1]\n\nprint('Output folder:\\n{}'.format(filename_base))\n\n\n#%% Enumerate files\n\nall_images = path_utils.find_images(input_path,recursive=True)\n\nprint('Enumerated {} image files in {}'.format(len(all_images),input_path))\n\n\n#%% Divide images into chunks \n\ndef split_list(L, n):\n k, m = divmod(len(L), n)\n return list(L[i*k+min(i, m):(i+1)*k+min(i+1, m)] for i in range(n))\n\nfolder_chunks = split_list(all_images,n_jobs)\n\n\n#%% Estimate total time\n\nn_images = len(all_images)\nexecution_seconds = n_images / gpu_images_per_second\nwallclock_seconds = execution_seconds / n_gpus\nprint('Expected time: {}'.format(humanfriendly.format_timespan(wallclock_seconds)))\n\nseconds_per_chunk = len(folder_chunks[0]) / gpu_images_per_second\nprint('Expected time per chunk: {}'.format(humanfriendly.format_timespan(seconds_per_chunk)))\n\n\n#%% Write file lists\n\ntask_info = []\n\nfor i_chunk,chunk_list in enumerate(folder_chunks):\n \n chunk_fn = os.path.join(filename_base,'chunk{}.json'.format(str(i_chunk).zfill(3)))\n task_info.append({'id':i_chunk,'input_file':chunk_fn})\n ai4e_azure_utils.write_list_to_file(chunk_fn, chunk_list)\n \n \n#%% Generate commands\n\n# i_task = 0; task = task_info[i_task]\nfor i_task,task in enumerate(task_info):\n \n chunk_file = task['input_file']\n output_fn = chunk_file.replace('.json','_results.json')\n \n task['output_file'] = output_fn\n \n if n_jobs > 1:\n gpu_number = i_task % n_gpus \n else:\n gpu_number = default_gpu_number\n \n cuda_string = f'CUDA_VISIBLE_DEVICES={gpu_number}'\n \n checkpoint_frequency_string = ''\n checkpoint_path_string = ''\n checkpoint_filename = chunk_file.replace('.json','_checkpoint.json')\n \n if checkpoint_frequency is not None and checkpoint_frequency > 0:\n checkpoint_frequency_string = f'--checkpoint_frequency {checkpoint_frequency}'\n checkpoint_path_string = '--checkpoint_path \"{}\"'.format(checkpoint_filename)\n \n use_image_queue_string = ''\n if (use_image_queue):\n use_image_queue_string = '--use_image_queue'\n\n ncores_string = ''\n if (ncores > 1):\n ncores_string = '--ncores {}'.format(ncores)\n \n quiet_string = ''\n if quiet_mode:\n quiet_string = '--quiet'\n\n image_size_string = ''\n if image_size is not None:\n image_size_string = '--image_size {}'.format(image_size)\n \n # Generate the script to run MD\n \n cmd = f'{cuda_string} python run_detector_batch.py \"{model_file}\" \"{chunk_file}\" \"{output_fn}\" {checkpoint_frequency_string} {checkpoint_path_string} {use_image_queue_string} {ncores_string} {quiet_string} {image_size_string}'\n \n cmd_file = os.path.join(filename_base,'run_chunk_{}_gpu_{}.sh'.format(str(i_task).zfill(2),\n str(gpu_number).zfill(2)))\n \n with open(cmd_file,'w') as f:\n f.write(cmd + '\\n')\n \n st = os.stat(cmd_file)\n os.chmod(cmd_file, st.st_mode | stat.S_IEXEC)\n \n task['command'] = cmd\n task['command_file'] = cmd_file\n\n # Generate the script to resume from the checkpoint\n \n resume_string = ' --resume_from_checkpoint \"{}\"'.format(checkpoint_filename)\n resume_cmd = cmd + resume_string\n resume_cmd_file = os.path.join(filename_base,'resume_chunk_{}_gpu_{}.sh'.format(str(i_task).zfill(2),\n str(gpu_number).zfill(2)))\n \n with open(resume_cmd_file,'w') as f:\n f.write(resume_cmd + '\\n')\n \n st = os.stat(resume_cmd_file)\n os.chmod(resume_cmd_file, st.st_mode | stat.S_IEXEC)\n \n task['resume_command'] = resume_cmd\n task['resume_command_file'] = resume_cmd_file\n\n\n#%% Run the tasks\n\n\"\"\"\nI strongly prefer to manually run the scripts we just generated, but this cell demonstrates\nhow one would invoke run_detector_batch programmatically. Normally when I run manually on \na multi-GPU machine, I run the scripts in N separate shells, one for each GPU. This programmatic\napproach does not yet know how to do something like that, so all chunks will run serially.\nThis is a no-op if you're on a single-GPU machine.\n\"\"\"\n\nif False:\n \n #%%% Run the tasks (commented out)\n\n # i_task = 0; task = task_info[i_task]\n for i_task,task in enumerate(task_info):\n \n chunk_file = task['input_file']\n output_fn = task['output_file']\n \n checkpoint_filename = chunk_file.replace('.json','_checkpoint.json')\n \n if json_threshold is not None:\n confidence_threshold = json_threshold\n else:\n confidence_threshold = DEFAULT_OUTPUT_CONFIDENCE_THRESHOLD\n \n if checkpoint_frequency is not None and checkpoint_frequency > 0:\n cp_freq_arg = checkpoint_frequency\n else:\n cp_freq_arg = -1\n \n start_time = time.time()\n results = load_and_run_detector_batch(model_file=model_file, \n image_file_names=chunk_file, \n checkpoint_path=checkpoint_filename, \n confidence_threshold=confidence_threshold,\n checkpoint_frequency=cp_freq_arg, \n results=None,\n n_cores=ncores, \n use_image_queue=use_image_queue,\n quiet=quiet_mode,\n image_size=image_size) \n elapsed = time.time() - start_time\n \n print('Task {}: finished inference for {} images in {}'.format(\n i_task, len(results),humanfriendly.format_timespan(elapsed)))\n\n # This will write absolute paths to the file, we'll fix this later\n write_results_to_file(results, output_fn, detector_file=model_file)\n\n if checkpoint_frequency is not None and checkpoint_frequency > 0:\n if os.path.isfile(checkpoint_filename): \n os.remove(checkpoint_filename)\n print('Deleted checkpoint file {}'.format(checkpoint_filename))\n \n # ...for each chunk\n \n# ...if False\n\n \n#%% Load results, look for failed or missing images in each task\n\nn_total_failures = 0\n\n# i_task = 0; task = task_info[i_task]\nfor i_task,task in enumerate(task_info):\n \n chunk_file = task['input_file']\n output_file = task['output_file']\n \n with open(chunk_file,'r') as f:\n task_images = json.load(f)\n with open(output_file,'r') as f:\n task_results = json.load(f)\n \n task_images_set = set(task_images)\n filename_to_results = {}\n \n n_task_failures = 0\n \n # im = task_results['images'][0]\n for im in task_results['images']:\n assert im['file'].startswith(input_path)\n assert im['file'] in task_images_set\n filename_to_results[im['file']] = im\n if 'failure' in im:\n assert im['failure'] is not None\n n_task_failures += 1\n \n task['n_failures'] = n_task_failures\n task['results'] = task_results\n \n for fn in task_images:\n assert fn in filename_to_results\n \n n_total_failures += n_task_failures\n\n# ...for each task\n\nassert n_total_failures < max_tolerable_failed_images,\\\n '{} failures (max tolerable set to {})'.format(n_total_failures,\n max_tolerable_failed_images)\n\nprint('Processed all {} images with {} failures'.format(\n len(all_images),n_total_failures))\n \n\n#%% Merge results files and make images relative\n\nimport copy\n\ncombined_results = None\n\nfor i_task,task in enumerate(task_info):\n\n if i_task == 0:\n combined_results = copy.deepcopy(task['results'])\n combined_results['images'] = copy.deepcopy(task['results']['images'])\n continue\n task_results = task['results']\n assert task_results['info']['format_version'] == combined_results['info']['format_version']\n assert task_results['detection_categories'] == combined_results['detection_categories']\n combined_results['images'].extend(copy.deepcopy(task_results['images']))\n \nassert len(combined_results['images']) == len(all_images), \\\n 'Expected {} images in combined results, found {}'.format(\n len(all_images),len(combined_results['images']))\n\nresult_filenames = [im['file'] for im in combined_results['images']]\nassert len(combined_results['images']) == len(set(result_filenames))\n\n# im = combined_results['images'][0]\nfor im in combined_results['images']:\n assert im['file'].startswith(input_path + '/')\n im['file']= im['file'].replace(input_path + '/','',1) \n \ncombined_api_output_file = os.path.join(\n combined_api_output_folder,\n '{}_detections.json'.format(base_task_name))\n\nwith open(combined_api_output_file,'w') as f:\n json.dump(combined_results,f,indent=2)\n\nprint('Wrote results to {}'.format(combined_api_output_file))\n\n\n#%% Compare results files for different model versions (or before/after RDE)\n\nimport itertools\n\nfrom api.batch_processing.postprocessing.compare_batch_results import (\n BatchComparisonOptions,PairwiseBatchComparisonOptions,compare_batch_results)\n\noptions = BatchComparisonOptions()\n\noptions.job_name = organization_name_short\noptions.output_folder = os.path.join(postprocessing_output_folder,'model_comparison')\noptions.image_folder = input_path\n\noptions.pairwise_options = []\n\nfilenames = [\n '/postprocessing/organization/mdv4_results.json',\n '/postprocessing/organization/mdv5a_results.json',\n '/postprocessing/organization/mdv5b_results.json' \n ]\n\ndetection_thresholds = [0.7,0.15,0.15]\n\nassert len(detection_thresholds) == len(filenames)\n\nrendering_thresholds = [(x*0.6666) for x in detection_thresholds]\n\n# Choose all pairwise combinations of the files in [filenames]\nfor i, j in itertools.combinations(list(range(0,len(filenames))),2):\n \n pairwise_options = PairwiseBatchComparisonOptions()\n \n pairwise_options.results_filename_a = filenames[i]\n pairwise_options.results_filename_b = filenames[j]\n \n pairwise_options.rendering_confidence_threshold_a = rendering_thresholds[i]\n pairwise_options.rendering_confidence_threshold_b = rendering_thresholds[j]\n \n pairwise_options.detection_thresholds_a = {'animal':detection_thresholds[i],\n 'person':detection_thresholds[i],\n 'vehicle':detection_thresholds[i]}\n pairwise_options.detection_thresholds_b = {'animal':detection_thresholds[j],\n 'person':detection_thresholds[j],\n 'vehicle':detection_thresholds[j]}\n options.pairwise_options.append(pairwise_options)\n\nresults = compare_batch_results(options)\n\nfrom path_utils import open_file # from ai4eutils\nopen_file(results.html_output_file)\n\n\n#%% Post-processing (no ground truth)\n\nrender_animals_only = False\n\noptions = PostProcessingOptions()\noptions.image_base_dir = input_path\noptions.parallelize_rendering = True\noptions.include_almost_detections = True\noptions.num_images_to_sample = 7500\noptions.parallelize_rendering_n_cores = n_rendering_threads\noptions.confidence_threshold = 0.2\noptions.almost_detection_confidence_threshold = options.confidence_threshold - 0.05\noptions.ground_truth_json_file = None\noptions.separate_detections_by_category = True\n# options.sample_seed = 0\n\nif render_animals_only:\n # Omit some pages from the output, useful when animals are rare\n options.rendering_bypass_sets = ['detections_person','detections_vehicle',\n 'detections_person_vehicle','non_detections']\n\noutput_base = os.path.join(postprocessing_output_folder,\n base_task_name + '_{:.3f}'.format(options.confidence_threshold))\nif render_animals_only:\n output_base = output_base + '_animals_only'\n\nos.makedirs(output_base, exist_ok=True)\nprint('Processing to {}'.format(output_base))\n\noptions.api_output_file = combined_api_output_file\noptions.output_dir = output_base\nppresults = process_batch_results(options)\nhtml_output_file = ppresults.output_html_file\npath_utils.open_file(html_output_file)\n\n\n#%% Merge in high-confidence detections from another results file\n\nfrom api.batch_processing.postprocessing.merge_detections import MergeDetectionsOptions,merge_detections\n\nsource_files = ['']\ntarget_file = ''\noutput_file = target_file.replace('.json','_merged.json')\n\noptions = MergeDetectionsOptions()\noptions.max_detection_size = 1.0\noptions.target_confidence_threshold = 0.25\noptions.categories_to_include = [1]\noptions.source_confidence_thresholds = [0.2]\nmerge_detections(source_files, target_file, output_file, options)\n\nmerged_detections_file = output_file\n\n\n#%% RDE (sample directory collapsing)\n\ndef remove_overflow_folders(relativePath):\n \n import re\n \n # In this example, the camera created folders called \"100EK113\", \"101EK113\", etc., for every N images\n pat = '\\/\\d+EK\\d+\\/'\n \n relativePath = relativePath.replace('\\\\','/') \n relativePath = re.sub(pat,'/',relativePath)\n dirName = os.path.dirname(relativePath)\n \n return dirName\n\nif False:\n\n pass\n\n #%%\n \n relativePath = 'a/b/c/d/100EK113/blah.jpg'\n print(remove_overflow_folders(relativePath))\n \n #%%\n \n with open(combined_api_output_file,'r') as f:\n d = json.load(f)\n image_filenames = [im['file'] for im in d['images']]\n for relativePath in tqdm(image_filenames):\n remove_overflow_folders(relativePath)\n\n\n#%% Repeat detection elimination, phase 1\n\n# Deliberately leaving these imports here, rather than at the top, because this\n# cell is not typically executed\nfrom api.batch_processing.postprocessing.repeat_detection_elimination import repeat_detections_core\nimport path_utils\ntask_index = 0\n\noptions = repeat_detections_core.RepeatDetectionOptions()\n\noptions.confidenceMin = 0.15\noptions.confidenceMax = 1.01\noptions.iouThreshold = 0.85\noptions.occurrenceThreshold = 10\noptions.maxSuspiciousDetectionSize = 0.2\n# options.minSuspiciousDetectionSize = 0.05\n\n# This will cause a very light gray box to get drawn around all the detections\n# we're *not* considering as suspicious.\noptions.bRenderOtherDetections = True\noptions.otherDetectionsThreshold = options.confidenceMin\n\n# options.lineThickness = 5\n# options.boxExpansion = 8\n\n# To invoke custom collapsing of folders for a particular manufacturer's naming scheme\n# options.customDirNameFunction = remove_overflow_folders\n\noptions.bRenderHtml = False\noptions.imageBase = input_path\nrde_string = 'rde_{:.2f}_{:.2f}_{}_{:.2f}'.format(\n options.confidenceMin, options.iouThreshold,\n options.occurrenceThreshold, options.maxSuspiciousDetectionSize)\noptions.outputBase = os.path.join(filename_base, rde_string + '_task_{}'.format(task_index))\noptions.filenameReplacements = {'':''}\n\n# Exclude people and vehicles from RDE\n# options.excludeClasses = [2,3]\n\n# options.maxImagesPerFolder = 50000\n# options.includeFolders = ['a/b/c']\n# options.excludeFolder = ['a/b/c']\n\noptions.debugMaxDir = -1\noptions.debugMaxRenderDir = -1\noptions.debugMaxRenderDetection = -1\noptions.debugMaxRenderInstance = -1\n\n# Can be None, 'xsort', or 'clustersort'\noptions.smartSort = 'xsort'\n\nsuspiciousDetectionResults = repeat_detections_core.find_repeat_detections(combined_api_output_file,\n None,\n options)\n\n# import clipboard; clipboard.copy(os.path.dirname(suspiciousDetectionResults.filterFile))\n# path_utils.open_file(os.path.dirname(suspiciousDetectionResults.filterFile))\n\n\n#%% Manual RDE step\n\n## DELETE THE VALID DETECTIONS ##\n\n\n#%% Re-filtering\n\nfrom api.batch_processing.postprocessing.repeat_detection_elimination import remove_repeat_detections\n\nfiltered_output_filename = path_utils.insert_before_extension(combined_api_output_file, 'filtered_{}'.format(rde_string))\n\nremove_repeat_detections.remove_repeat_detections(\n inputFile=combined_api_output_file,\n outputFile=filtered_output_filename,\n filteringDir=os.path.dirname(suspiciousDetectionResults.filterFile)\n )\n\n\n#%% Post-processing (post-RDE)\n\nrender_animals_only = False\n\noptions = PostProcessingOptions()\noptions.image_base_dir = input_path\noptions.parallelize_rendering = True\noptions.include_almost_detections = True\noptions.num_images_to_sample = 7500\noptions.confidence_threshold = 0.2\noptions.almost_detection_confidence_threshold = options.confidence_threshold - 0.05\noptions.ground_truth_json_file = None\noptions.separate_detections_by_category = True\n# options.sample_seed = 0\n\nif render_animals_only:\n # Omit some pages from the output, useful when animals are rare\n options.rendering_bypass_sets = ['detections_person','detections_vehicle',\n 'detections_person_vehicle','non_detections'] \n\noutput_base = os.path.join(postprocessing_output_folder, \n base_task_name + '_{}_{:.3f}'.format(rde_string, options.confidence_threshold)) \n\nif render_animals_only:\n output_base = output_base + '_render_animals_only'\nos.makedirs(output_base, exist_ok=True)\n\nprint('Processing post-RDE to {}'.format(output_base))\n\noptions.api_output_file = filtered_output_filename\noptions.output_dir = output_base\nppresults = process_batch_results(options)\nhtml_output_file = ppresults.output_html_file\n\npath_utils.open_file(html_output_file)\n\n\n#%% Run MegaClassifier (actually, write out a script that runs MegaClassifier)\n\nclassifier_name_short = 'megaclassifier'\nthreshold_str = '0.15' # 0.6\nclassifier_name = 'megaclassifier_v0.1_efficientnet-b3'\n\norganization_name = organization_name_short\njob_name = base_task_name\ninput_filename = filtered_output_filename # combined_api_output_file\ninput_files = [input_filename]\nimage_base = input_path\ncrop_path = os.path.join(os.path.expanduser('~/crops'),job_name + '_crops')\noutput_base = combined_api_output_folder\ndevice_id = 0\n\noutput_file = os.path.join(filename_base,'run_{}_'.format(classifier_name_short) + job_name + '.sh')\n\nclassifier_base = os.path.expanduser('~/models/camera_traps/megaclassifier/v0.1/')\nassert os.path.isdir(classifier_base)\n\ncheckpoint_path = os.path.join(classifier_base,'v0.1_efficientnet-b3_compiled.pt')\nassert os.path.isfile(checkpoint_path)\n\nclassifier_categories_path = os.path.join(classifier_base,'v0.1_index_to_name.json')\nassert os.path.isfile(classifier_categories_path)\n\ntarget_mapping_path = os.path.join(classifier_base,'idfg_to_megaclassifier_labels.json')\nassert os.path.isfile(target_mapping_path)\n\nclassifier_output_suffix = '_megaclassifier_output.csv.gz'\nfinal_output_suffix = '_megaclassifier.json'\n\nn_threads_str = '50'\nimage_size_str = '300'\nbatch_size_str = '64'\nnum_workers_str = '8'\nclassification_threshold_str = '0.05'\n\nlogdir = filename_base\n\n# This is just passed along to the metadata in the output file, it has no impact\n# on how the classification scripts run.\ntypical_classification_threshold_str = '0.75'\n\n##%% Set up environment\n\ncommands = []\n# commands.append('cd CameraTraps/classification\\n')\n# commands.append('conda activate cameratraps-classifier\\n')\n\n\n##%% Crop images\n\ncommands.append('\\n### Cropping ###\\n')\n\n# fn = input_files[0]\nfor fn in input_files:\n\n input_file_path = fn\n crop_cmd = ''\n \n crop_comment = '\\n# Cropping {}\\n'.format(fn)\n crop_cmd += crop_comment\n \n crop_cmd += \"python crop_detections.py \\\\\\n\" + \\\n \t input_file_path + ' \\\\\\n' + \\\n crop_path + ' \\\\\\n' + \\\n '--images-dir \"' + image_base + '\"' + ' \\\\\\n' + \\\n '--threshold \"' + threshold_str + '\"' + ' \\\\\\n' + \\\n '--square-crops ' + ' \\\\\\n' + \\\n '--threads \"' + n_threads_str + '\"' + ' \\\\\\n' + \\\n '--logdir \"' + logdir + '\"' + ' \\\\\\n' + \\\n '\\n'\n crop_cmd = '{}'.format(crop_cmd)\n commands.append(crop_cmd)\n\n\n##%% Run classifier\n\ncommands.append('\\n### Classifying ###\\n')\n\n# fn = input_files[0]\nfor fn in input_files:\n\n input_file_path = fn\n classifier_output_path = crop_path + classifier_output_suffix\n \n classify_cmd = ''\n \n classify_comment = '\\n# Classifying {}\\n'.format(fn)\n classify_cmd += classify_comment\n \n classify_cmd += \"python run_classifier.py \\\\\\n\" + \\\n \t checkpoint_path + ' \\\\\\n' + \\\n crop_path + ' \\\\\\n' + \\\n classifier_output_path + ' \\\\\\n' + \\\n '--detections-json \"' + input_file_path + '\"' + ' \\\\\\n' + \\\n '--classifier-categories \"' + classifier_categories_path + '\"' + ' \\\\\\n' + \\\n '--image-size \"' + image_size_str + '\"' + ' \\\\\\n' + \\\n '--batch-size \"' + batch_size_str + '\"' + ' \\\\\\n' + \\\n '--num-workers \"' + num_workers_str + '\"' + ' \\\\\\n'\n \n if device_id is not None:\n classify_cmd += '--device {}'.format(device_id)\n \n classify_cmd += '\\n\\n' \n classify_cmd = '{}'.format(classify_cmd)\n commands.append(classify_cmd)\n\t\t\n\n##%% Remap classifier outputs\n\ncommands.append('\\n### Remapping ###\\n')\n\n# fn = input_files[0]\nfor fn in input_files:\n\n input_file_path = fn\n classifier_output_path = crop_path + classifier_output_suffix\n classifier_output_path_remapped = \\\n classifier_output_path.replace(\".csv.gz\",\"_remapped.csv.gz\")\n assert not (classifier_output_path == classifier_output_path_remapped)\n \n output_label_index = classifier_output_path_remapped.replace(\n \"_remapped.csv.gz\",\"_label_index_remapped.json\")\n \n remap_cmd = ''\n \n remap_comment = '\\n# Remapping {}\\n'.format(fn)\n remap_cmd += remap_comment\n \n remap_cmd += \"python aggregate_classifier_probs.py \\\\\\n\" + \\\n classifier_output_path + ' \\\\\\n' + \\\n '--target-mapping \"' + target_mapping_path + '\"' + ' \\\\\\n' + \\\n '--output-csv \"' + classifier_output_path_remapped + '\"' + ' \\\\\\n' + \\\n '--output-label-index \"' + output_label_index + '\"' + ' \\\\\\n' + \\\n '\\n'\n \n remap_cmd = '{}'.format(remap_cmd)\n commands.append(remap_cmd)\n \n\n##%% Merge classification and detection outputs\n\ncommands.append('\\n### Merging ###\\n')\n\n# fn = input_files[0]\nfor fn in input_files:\n\n input_file_path = fn\n classifier_output_path = crop_path + classifier_output_suffix\n \n classifier_output_path_remapped = \\\n classifier_output_path.replace(\".csv.gz\",\"_remapped.csv.gz\")\n \n output_label_index = classifier_output_path_remapped.replace(\n \"_remapped.csv.gz\",\"_label_index_remapped.json\")\n \n final_output_path = os.path.join(output_base,\n os.path.basename(classifier_output_path)).\\\n replace(classifier_output_suffix,\n final_output_suffix)\n final_output_path = final_output_path.replace('_detections','')\n final_output_path = final_output_path.replace('_crops','')\n final_output_path_mc = final_output_path\n \n merge_cmd = ''\n \n merge_comment = '\\n# Merging {}\\n'.format(fn)\n merge_cmd += merge_comment\n \n merge_cmd += \"python merge_classification_detection_output.py \\\\\\n\" + \\\n \t classifier_output_path_remapped + ' \\\\\\n' + \\\n output_label_index + ' \\\\\\n' + \\\n '--output-json \"' + final_output_path + '\"' + ' \\\\\\n' + \\\n '--detection-json \"' + input_file_path + '\"' + ' \\\\\\n' + \\\n '--classifier-name \"' + classifier_name + '\"' + ' \\\\\\n' + \\\n '--threshold \"' + classification_threshold_str + '\"' + ' \\\\\\n' + \\\n '--typical-confidence-threshold \"' + typical_classification_threshold_str + '\"' + ' \\\\\\n' + \\\n '\\n'\n merge_cmd = '{}'.format(merge_cmd)\n commands.append(merge_cmd)\n\n\n##%% Write out classification script\n\nwith open(output_file,'w') as f:\n for s in commands:\n f.write('{}'.format(s))\n\nimport stat\nst = os.stat(output_file)\nos.chmod(output_file, st.st_mode | stat.S_IEXEC)\n\n\n#%% Run a non-MegaClassifier classifier (i.e., a classifier with no output mapping)\n\nclassifier_name_short = 'idfgclassifier'\nthreshold_str = '0.15' # 0.6\nclassifier_name = 'idfg_classifier_ckpt_14_compiled'\n\norganization_name = organization_name_short\njob_name = base_task_name\ninput_filename = filtered_output_filename # combined_api_output_file\ninput_files = [input_filename]\nimage_base = input_path\ncrop_path = os.path.join(os.path.expanduser('~/crops'),job_name + '_crops')\noutput_base = combined_api_output_folder\ndevice_id = 1\n\noutput_file = os.path.join(filename_base,'run_{}_'.format(classifier_name_short) + job_name + '.sh')\n\nclassifier_base = os.path.expanduser('~/models/camera_traps/idfg_classifier/idfg_classifier_20200905_042558')\nassert os.path.isdir(classifier_base)\n\ncheckpoint_path = os.path.join(classifier_base,'idfg_classifier_ckpt_14_compiled.pt')\nassert os.path.isfile(checkpoint_path)\n\nclassifier_categories_path = os.path.join(classifier_base,'label_index.json')\nassert os.path.isfile(classifier_categories_path)\n\nclassifier_output_suffix = '_{}_output.csv.gz'.format(classifier_name_short)\nfinal_output_suffix = '_{}.json'.format(classifier_name_short)\n\nthreshold_str = '0.65'\nn_threads_str = '50'\nimage_size_str = '300'\nbatch_size_str = '64'\nnum_workers_str = '8'\nlogdir = filename_base\n\nclassification_threshold_str = '0.05'\n\n# This is just passed along to the metadata in the output file, it has no impact\n# on how the classification scripts run.\ntypical_classification_threshold_str = '0.75'\n\n\n##%% Set up environment\n\ncommands = []\n\n\n##%% Crop images\n \ncommands.append('\\n### Cropping ###\\n')\n\n# fn = input_files[0]\nfor fn in input_files:\n\n input_file_path = fn\n crop_cmd = ''\n \n crop_comment = '\\n# Cropping {}\\n'.format(fn)\n crop_cmd += crop_comment\n \n crop_cmd += \"python crop_detections.py \\\\\\n\" + \\\n \t input_file_path + ' \\\\\\n' + \\\n crop_path + ' \\\\\\n' + \\\n '--images-dir \"' + image_base + '\"' + ' \\\\\\n' + \\\n '--threshold \"' + threshold_str + '\"' + ' \\\\\\n' + \\\n '--square-crops ' + ' \\\\\\n' + \\\n '--threads \"' + n_threads_str + '\"' + ' \\\\\\n' + \\\n '--logdir \"' + logdir + '\"' + ' \\\\\\n' + \\\n '\\n'\n crop_cmd = '{}'.format(crop_cmd)\n commands.append(crop_cmd)\n\n\n##%% Run classifier\n\ncommands.append('\\n### Classifying ###\\n')\n\n# fn = input_files[0]\nfor fn in input_files:\n\n input_file_path = fn\n classifier_output_path = crop_path + classifier_output_suffix\n \n classify_cmd = ''\n \n classify_comment = '\\n# Classifying {}\\n'.format(fn)\n classify_cmd += classify_comment\n \n classify_cmd += \"python run_classifier.py \\\\\\n\" + \\\n \t checkpoint_path + ' \\\\\\n' + \\\n crop_path + ' \\\\\\n' + \\\n classifier_output_path + ' \\\\\\n' + \\\n '--detections-json \"' + input_file_path + '\"' + ' \\\\\\n' + \\\n '--classifier-categories \"' + classifier_categories_path + '\"' + ' \\\\\\n' + \\\n '--image-size \"' + image_size_str + '\"' + ' \\\\\\n' + \\\n '--batch-size \"' + batch_size_str + '\"' + ' \\\\\\n' + \\\n '--num-workers \"' + num_workers_str + '\"' + ' \\\\\\n'\n \n if device_id is not None:\n classify_cmd += '--device {}'.format(device_id)\n \n classify_cmd += '\\n\\n' \n classify_cmd = '{}'.format(classify_cmd)\n commands.append(classify_cmd)\n\t\t\n\n##%% Merge classification and detection outputs\n\ncommands.append('\\n### Merging ###\\n')\n\n# fn = input_files[0]\nfor fn in input_files:\n\n input_file_path = fn\n classifier_output_path = crop_path + classifier_output_suffix\n final_output_path = os.path.join(output_base,\n os.path.basename(classifier_output_path)).\\\n replace(classifier_output_suffix,\n final_output_suffix)\n final_output_path = final_output_path.replace('_detections','')\n final_output_path = final_output_path.replace('_crops','')\n final_output_path_ic = final_output_path\n \n merge_cmd = ''\n \n merge_comment = '\\n# Merging {}\\n'.format(fn)\n merge_cmd += merge_comment\n \n merge_cmd += \"python merge_classification_detection_output.py \\\\\\n\" + \\\n \t classifier_output_path + ' \\\\\\n' + \\\n classifier_categories_path + ' \\\\\\n' + \\\n '--output-json \"' + final_output_path_ic + '\"' + ' \\\\\\n' + \\\n '--detection-json \"' + input_file_path + '\"' + ' \\\\\\n' + \\\n '--classifier-name \"' + classifier_name + '\"' + ' \\\\\\n' + \\\n '--threshold \"' + classification_threshold_str + '\"' + ' \\\\\\n' + \\\n '--typical-confidence-threshold \"' + typical_classification_threshold_str + '\"' + ' \\\\\\n' + \\\n '\\n'\n merge_cmd = '{}'.format(merge_cmd)\n commands.append(merge_cmd)\n\n\n##%% Write everything out\n\nwith open(output_file,'w') as f:\n for s in commands:\n f.write('{}'.format(s))\n\nimport stat\nst = os.stat(output_file)\nos.chmod(output_file, st.st_mode | stat.S_IEXEC)\n\n\n#%% Within-image classification smoothing\n\n# Only count detections with a classification confidence threshold above\n# *classification_confidence_threshold*, which in practice means we're only\n# looking at one category per detection.\n#\n# If an image has at least *min_detections_above_threshold* such detections\n# in the most common category, and no more than *max_detections_secondary_class*\n# in the second-most-common category, flip all detections to the most common\n# category.\n#\n# Optionally treat some classes as particularly unreliable, typically used to overwrite an \n# \"other\" class.\n\nclassification_detection_files = [ \n final_output_path_mc,\n final_output_path_ic \n ]\n\nassert all([os.path.isfile(fn) for fn in classification_detection_files])\n\n# Only count detections with a classification confidence threshold above\n# *classification_confidence_threshold*, which in practice means we're only\n# looking at one category per detection.\n#\n# If an image has at least *min_detections_above_threshold* such detections\n# in the most common category, and no more than *max_detections_secondary_class*\n# in the second-most-common category, flip all detections to the most common\n# category.\n#\n# Optionally treat some classes as particularly unreliable, typically used to overwrite an \n# \"other\" class.\n\nsmoothed_classification_files = []\n\nfor final_output_path in classification_detection_files:\n\n classifier_output_path = final_output_path\n classifier_output_path_within_image_smoothing = classifier_output_path.replace(\n '.json','_within_image_smoothing.json')\n \n with open(classifier_output_path,'r') as f:\n d = json.load(f)\n \n # d['classification_categories']\n \n # im['detections']\n \n # path_utils.open_file(os.path.join(input_path,im['file']))\n \n from collections import defaultdict\n \n min_detections_above_threshold = 4\n max_detections_secondary_class = 3\n \n min_detections_to_overwrite_other = 2\n other_category_names = ['other']\n \n classification_confidence_threshold = 0.6\n \n # Which classifications should we even bother over-writing?\n classification_overwrite_threshold = 0.3 # classification_confidence_threshold\n \n # Detection confidence threshold for things we count\n detection_confidence_threshold = 0.2\n \n # Which detections should we even bother over-writing?\n detection_overwrite_threshold = 0.05\n \n category_name_to_id = {d['classification_categories'][k]:k for k in d['classification_categories']}\n other_category_ids = []\n for s in other_category_names:\n if s in category_name_to_id:\n other_category_ids.append(category_name_to_id[s])\n else:\n print('Warning: \"other\" category {} not present in file {}'.format(\n s,classifier_output_path))\n \n n_other_classifications_changed = 0\n n_other_images_changed = 0\n \n n_detections_flipped = 0\n n_images_changed = 0\n \n # im = d['images'][0] \n for im in tqdm(d['images']):\n \n if 'detections' not in im or im['detections'] is None or len(im['detections']) == 0:\n continue\n \n detections = im['detections']\n \n category_to_count = defaultdict(int)\n for det in detections:\n if ('classifications' in det) and (det['conf'] >= detection_confidence_threshold):\n for c in det['classifications']:\n if c[1] >= classification_confidence_threshold:\n category_to_count[c[0]] += 1\n # ...for each classification\n # ...if there are classifications for this detection\n # ...for each detection\n \n if len(category_to_count) <= 1:\n continue\n \n category_to_count = {k: v for k, v in sorted(category_to_count.items(),\n key=lambda item: item[1], \n reverse=True)}\n \n keys = list(category_to_count.keys())\n \n # Handle a quirky special case: if the most common category is \"other\" and \n # it's \"tied\" with the second-most-common category, swap them\n if (len(keys) > 1) and (keys[0] in other_category_ids) and (keys[1] not in other_category_ids) and\\\n (category_to_count[keys[0]] == category_to_count[keys[1]]):\n keys[1], keys[0] = keys[0], keys[1]\n \n max_count = category_to_count[keys[0]]\n # secondary_count = category_to_count[keys[1]]\n # The 'secondary count' is the most common non-other class\n secondary_count = 0\n for i_key in range(1,len(keys)):\n if keys[i_key] not in other_category_ids:\n secondary_count = category_to_count[keys[i_key]]\n break\n\n most_common_category = keys[0]\n \n assert max_count >= secondary_count\n \n # If we have at least *min_detections_to_overwrite_other* in a category that isn't\n # \"other\", change all \"other\" classifications to that category\n if max_count >= min_detections_to_overwrite_other and \\\n most_common_category not in other_category_ids:\n \n other_change_made = False\n \n for det in detections:\n \n if ('classifications' in det) and (det['conf'] >= detection_overwrite_threshold): \n \n for c in det['classifications']: \n \n if c[1] >= classification_overwrite_threshold and \\\n c[0] in other_category_ids:\n \n n_other_classifications_changed += 1\n other_change_made = True\n c[0] = most_common_category\n \n # ...for each classification\n \n # ...if there are classifications for this detection\n \n # ...for each detection\n \n if other_change_made:\n n_other_images_changed += 1\n \n # ...if we should overwrite all \"other\" classifications\n \n if max_count < min_detections_above_threshold:\n continue\n \n if secondary_count >= max_detections_secondary_class:\n continue\n \n # At this point, we know we have a dominant category; change all other above-threshold\n # classifications to that category. That category may have been \"other\", in which case we may have\n # already made the relevant changes.\n \n n_detections_flipped_this_image = 0\n \n # det = detections[0]\n for det in detections:\n \n if ('classifications' in det) and (det['conf'] >= detection_overwrite_threshold):\n \n for c in det['classifications']:\n if c[1] >= classification_overwrite_threshold and \\\n c[0] != most_common_category:\n \n c[0] = most_common_category\n n_detections_flipped += 1\n n_detections_flipped_this_image += 1\n \n # ...for each classification\n \n # ...if there are classifications for this detection\n \n # ...for each detection\n \n if n_detections_flipped_this_image > 0:\n n_images_changed += 1\n \n # ...for each image \n \n print('Classification smoothing: changed {} detections on {} images'.format(\n n_detections_flipped,n_images_changed))\n \n print('\"Other\" smoothing: changed {} detections on {} images'.format(\n n_other_classifications_changed,n_other_images_changed))\n \n with open(classifier_output_path_within_image_smoothing,'w') as f:\n json.dump(d,f,indent=2)\n \n print('Wrote results to:\\n{}'.format(classifier_output_path_within_image_smoothing))\n smoothed_classification_files.append(classifier_output_path_within_image_smoothing)\n\n# ...for each file we want to smooth\n\n\n#%% Post-processing (post-classification)\n\nclassification_detection_files = smoothed_classification_files\n \nassert all([os.path.isfile(fn) for fn in classification_detection_files])\n \n# classification_detection_file = classification_detection_files[1]\nfor classification_detection_file in classification_detection_files:\n \n options = PostProcessingOptions()\n options.image_base_dir = input_path\n options.parallelize_rendering = True\n options.include_almost_detections = True\n options.num_images_to_sample = 10000\n options.confidence_threshold = 0.2\n options.classification_confidence_threshold = 0.75\n options.almost_detection_confidence_threshold = options.confidence_threshold - 0.05\n options.ground_truth_json_file = None\n options.separate_detections_by_category = True\n \n folder_token = classification_detection_file.split('/')[-1].replace('classifier.json','')\n \n output_base = os.path.join(postprocessing_output_folder, folder_token + \\\n base_task_name + '_{:.3f}'.format(options.confidence_threshold))\n os.makedirs(output_base, exist_ok=True)\n print('Processing {} to {}'.format(base_task_name, output_base))\n \n options.api_output_file = classification_detection_file\n options.output_dir = output_base\n ppresults = process_batch_results(options)\n path_utils.open_file(ppresults.output_html_file)\n\n\n#%% Create a new category for large boxes\n\nfrom api.batch_processing.postprocessing import categorize_detections_by_size\n\noptions = categorize_detections_by_size.SizeCategorizationOptions()\n\n# This is a size threshold, not a confidence threshold\noptions.threshold = 0.85\n\ninput_file = r\"g:\\organization\\file.json\"\nsize_separated_file = input_file.replace('.json','-size-separated-{}.json'.format(options.threshold))\nd = categorize_detections_by_size.categorize_detections_by_size(input_file,size_separated_file,options)\n\n\n#%% .json splitting\n\ndata = None\n\nfrom api.batch_processing.postprocessing.subset_json_detector_output import (\n subset_json_detector_output, SubsetJsonDetectorOutputOptions)\n\ninput_filename = filtered_output_filename\noutput_base = os.path.join(filename_base,'json_subsets')\n\nif False:\n if data is None:\n with open(input_filename) as f:\n data = json.load(f)\n print('Data set contains {} images'.format(len(data['images'])))\n\nprint('Processing file {} to {}'.format(input_filename,output_base)) \n\noptions = SubsetJsonDetectorOutputOptions()\n# options.query = None\n# options.replacement = None\n\noptions.split_folders = True\noptions.make_folder_relative = True\n\n# Reminder: 'n_from_bottom' with a parameter of zero is the same as 'bottom'\noptions.split_folder_mode = 'bottom' # 'top', 'n_from_top', 'n_from_bottom'\noptions.split_folder_param = 0\noptions.overwrite_json_files = False\noptions.confidence_threshold = 0.01\n\nsubset_data = subset_json_detector_output(input_filename, output_base, options, data)\n\n\n#%% Custom splitting/subsetting\n\ndata = None\n\nfrom api.batch_processing.postprocessing.subset_json_detector_output import (\n subset_json_detector_output, SubsetJsonDetectorOutputOptions)\n\ninput_filename = filtered_output_filename\noutput_base = os.path.join(filename_base,'json_subsets')\n\nfolders = os.listdir(input_path)\n\nif data is None:\n with open(input_filename) as f:\n data = json.load(f)\n\nprint('Data set contains {} images'.format(len(data['images'])))\n\n# i_folder = 0; folder_name = folders[i_folder]\nfor i_folder, folder_name in enumerate(folders):\n\n output_filename = os.path.join(output_base, folder_name + '.json')\n print('Processing folder {} of {} ({}) to {}'.format(i_folder, len(folders), folder_name,\n output_filename))\n\n options = SubsetJsonDetectorOutputOptions()\n options.confidence_threshold = 0.01\n options.overwrite_json_files = True\n options.query = folder_name + '/'\n\n # This doesn't do anything in this case, since we're not splitting folders\n # options.make_folder_relative = True \n \n subset_data = subset_json_detector_output(input_filename, output_filename, options, data)\n\n\n#%% String replacement\n \ndata = None\n\nfrom api.batch_processing.postprocessing.subset_json_detector_output import (\n subset_json_detector_output, SubsetJsonDetectorOutputOptions)\n\ninput_filename = filtered_output_filename\noutput_filename = input_filename.replace('.json','_replaced.json')\n\noptions = SubsetJsonDetectorOutputOptions()\noptions.query = folder_name + '/'\noptions.replacement = ''\nsubset_json_detector_output(input_filename,output_filename,options)\n\n\n#%% Splitting images into folders\n\nfrom api.batch_processing.postprocessing.separate_detections_into_folders import (\n separate_detections_into_folders, SeparateDetectionsIntoFoldersOptions)\n\ndefault_threshold = 0.2\nbase_output_folder = os.path.expanduser('~/data/{}-{}-separated'.format(base_task_name,default_threshold))\n\noptions = SeparateDetectionsIntoFoldersOptions(default_threshold)\n\noptions.results_file = filtered_output_filename\noptions.base_input_folder = input_path\noptions.base_output_folder = os.path.join(base_output_folder,folder_name)\noptions.n_threads = 100\noptions.allow_existing_directory = False\n\nseparate_detections_into_folders(options)\n\n\n#%% Generate commands for a subset of tasks\n\ntask_set = [8,10,12,14,16]; gpu_number = 0; sleep_time_between_tasks = 60; sleep_time_before_tasks = 0\ncommands = []\n\n# i_task = 8\nfor i_task in task_set:\n \n if i_task == task_set[0]:\n commands.append('sleep {}'.format(str(sleep_time_before_tasks))) \n \n task = task_info[i_task]\n chunk_file = task['input_file']\n output_fn = chunk_file.replace('.json','_results.json')\n \n task['output_file'] = output_fn\n\n cuda_string = f'CUDA_VISIBLE_DEVICES={gpu_number}'\n \n checkpoint_frequency_string = ''\n checkpoint_path_string = ''\n if checkpoint_frequency is not None and checkpoint_frequency > 0:\n checkpoint_frequency_string = f'--checkpoint_frequency {checkpoint_frequency}'\n checkpoint_path_string = '--checkpoint_path {}'.format(chunk_file.replace(\n '.json','_checkpoint.json'))\n \n use_image_queue_string = ''\n if (use_image_queue):\n use_image_queue_string = '--use_image_queue'\n\n ncores_string = ''\n if (ncores > 1):\n ncores_string = '--ncores {}'.format(ncores)\n \n quiet_string = ''\n if quiet_mode:\n quiet_string = '--quiet'\n \n cmd = f'{cuda_string} python run_detector_batch.py {model_file} {chunk_file} {output_fn} {checkpoint_frequency_string} {checkpoint_path_string} {use_image_queue_string} {ncores_string} {quiet_string}'\n \n task['command'] = cmd\n commands.append(cmd)\n if i_task != task_set[-1]:\n commands.append('sleep {}'.format(str(sleep_time_between_tasks))) \n \n# ...for each task\n\ntask_strings = [str(k).zfill(2) for k in task_set]\ntask_set_string = '_'.join(task_strings)\ncmd_file = os.path.join(filename_base,'run_chunk_{}_gpu_{}.sh'.format(task_set_string,\n str(gpu_number).zfill(2)))\n\nwith open(cmd_file,'w') as f:\n for cmd in commands:\n f.write(cmd + '\\n')\n \nimport stat\nst = os.stat(cmd_file)\nos.chmod(cmd_file, st.st_mode | stat.S_IEXEC)\n\n\n#%% End notebook: turn this script into a notebook (how meta!)\n\nimport nbformat as nbf\n\ninput_py_file = os.path.expanduser('~/git/CameraTraps/api/batch_processing/data_preparation/manage_local_batch.py')\nassert os.path.isfile(input_py_file)\noutput_ipynb_file = input_py_file.replace('.py','.ipynb')\n\nnb_header = '# Managing a local MegaDetector batch'\n\nnb_header += '\\n'\n\nnb_header += \\\n\"\"\"\nThis notebook represents an interactive process for running MegaDetector on large batches of images, including typical and optional postprocessing steps. Everything after \"Merge results...\" is basically optional, and we typically do a mix of these optional steps, depending on the job.\n\nThis notebook is auto-generated from manage_local_batch.py (a cell-delimited .py file that is used the same way, typically in Spyder or VS Code). \n\n\"\"\"\n\nwith open(input_py_file,'r') as f:\n lines = f.readlines()\n\nnb = nbf.v4.new_notebook()\nnb['cells'].append(nbf.v4.new_markdown_cell(nb_header))\n\ni_line = 0\n\n# Exclude everything before the first cell\nwhile(not lines[i_line].startswith('#%%')):\n i_line += 1\n\ncurrent_cell = []\n\ndef write_code_cell(c):\n \n first_non_empty_line = None\n last_non_empty_line = None\n \n for i_code_line,code_line in enumerate(c):\n if len(code_line.strip()) > 0:\n if first_non_empty_line is None:\n first_non_empty_line = i_code_line\n last_non_empty_line = i_code_line\n \n # Remove the first [first_non_empty_lines] from the list\n c = c[first_non_empty_line:]\n last_non_empty_line -= first_non_empty_line\n c = c[:last_non_empty_line+1]\n \n nb['cells'].append(nbf.v4.new_code_cell('\\n'.join(c)))\n \nwhile(True): \n \n line = lines[i_line].rstrip()\n \n if 'end notebook' in line.lower():\n break\n \n if lines[i_line].startswith('#%% '):\n if len(current_cell) > 0:\n write_code_cell(current_cell)\n current_cell = []\n markdown_content = line.replace('#%%','##')\n nb['cells'].append(nbf.v4.new_markdown_cell(markdown_content))\n else:\n current_cell.append(line)\n\n i_line += 1\n\n# Add the last cell\nwrite_code_cell(current_cell)\n\nnbf.write(nb,output_ipynb_file)\n","sub_path":"api/batch_processing/data_preparation/manage_local_batch.py","file_name":"manage_local_batch.py","file_ext":"py","file_size_in_byte":49822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"532536697","text":"inputA = input(\"Please enter a string to know how many letters is uppercase and how many is lowercase: \")\n\ndef up_lowNums(string):\n uppercaseNum = 0\n lowercaseNum = 0\n \n for letters in string:\n if letters.isupper() == True:\n uppercaseNum += 1\n elif letters.islower() == True:\n lowercaseNum += 1\n return \"No. of Uppercase characters: {} and the No. of the Lowercase characters: {}\".format(uppercaseNum, lowercaseNum)\n \nup_lowNums(inputA)\n","sub_path":"11.22.19 - No. of Uppercase and Lowercase letters in string.py","file_name":"11.22.19 - No. of Uppercase and Lowercase letters in string.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"563061009","text":"import os\r\nfrom minio import Minio\r\nfrom minio.error import (ResponseError, BucketAlreadyOwnedByYou, BucketAlreadyExists)\r\nfrom app.main.util.DynamicUtil import DynamicUtil\r\n\r\n\r\nclass MinioOperation:\r\n def __init__(self):\r\n dyutil = DynamicUtil('config.ini')\r\n self.host = dyutil.config.get('minio', 'host')\r\n self.access_key = dyutil.config.get('minio', 'access_key')\r\n self.secret_key = dyutil.config.get('minio', 'secret_key')\r\n\r\n\r\n self.minioClient = Minio(self.host,\r\n access_key=self.access_key,\r\n secret_key=self.secret_key,\r\n secure=True)\r\n\r\n def create(self, bucket_name):\r\n try:\r\n self.minioClient.make_bucket(bucket_name=bucket_name)\r\n self.minioClient.enable_bucket_versioning(bucket_name)\r\n return {\r\n \"bucket_name\": bucket_name,\r\n \"status_code\": 200\r\n }\r\n except BucketAlreadyOwnedByYou as err:\r\n pass\r\n except BucketAlreadyExists as err:\r\n pass\r\n except ResponseError as err:\r\n raise\r\n\r\n\r\n def read(self, bucket_name):\r\n objects = self.minioClient.list_objects(bucket_name, recursive=True)\r\n print(objects)\r\n file_list = []\r\n for obj in objects:\r\n try:\r\n file_name = obj.object_name.encode('utf-8')\r\n print(file_name)\r\n file_list.append(file_name)\r\n # file_name = file_name.decode('utf-8')\r\n # data = self.minioClient.get_object(bucket_name, file_name)\r\n # file_path, file = os.path.split(os.path.abspath(file_name))\r\n\r\n # isdir = os.path.isdir(file_path)\r\n # if not isdir:\r\n # os.makedirs(file_path)\r\n #\r\n # with open(file_name, 'wb') as file_data:\r\n # for d in data.stream(32 * 1024):\r\n # file_data.write(d)\r\n\r\n return {\r\n \"bucket_name\": bucket_name,\r\n \"files\": file_list,\r\n \"status_code\": 200\r\n }\r\n except ResponseError as err:\r\n print(\"Error in MinioOperationService.read(): \", err)\r\n return {\r\n \"error_message\": err,\r\n \"status_code\": 500\r\n }\r\n\r\n\r\n def upload(self, bucket_name, object_name, filepath):\r\n try:\r\n self.minioClient.fput_object(str(bucket_name), str(object_name), filepath)\r\n except ResponseError as err:\r\n print(\"Error in MinioOperationService.upload(): \", err)\r\n\r\n\r\n def list_bucket_objects(self, bucket_name):\r\n try:\r\n objects = self.minioClient.list_objects(bucket_name, recursive=True)\r\n for obj in objects:\r\n print(obj.bucket_name, obj.object_name.encode('utf-8'), obj.last_modified,\r\n obj.etag, obj.size, obj.content_type)\r\n except ResponseError as err:\r\n print(\"Error in MinioOperationService.listBucketObjects(): \", err)\r\n\r\n\r\n def delete(self, bucket_name):\r\n objects = self.minioClient.list_objects(bucket_name, recursive=True)\r\n print(objects)\r\n for obj in objects:\r\n try:\r\n print(\"OBJECT : \", objects)\r\n self.minioClient.remove_object(bucket_name, obj)\r\n return {\r\n \"bucket_name\": bucket_name,\r\n \"status_code\": 200\r\n }\r\n except ResponseError as err:\r\n print(\"Error in MinioOperationService.delete(): \", err)\r\n\r\n\r\n def get_stats(self, bucket_name, object_name):\r\n try:\r\n stat = self.minioClient.stat_object(bucket_name, object_name)\r\n return stat\r\n except ResponseError as err:\r\n print(\"Error in MinioOperationService.get_stats(): \", err)\r\n\r\n","sub_path":"app/main/service/minio_operation_service.py","file_name":"minio_operation_service.py","file_ext":"py","file_size_in_byte":4025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"396797821","text":"from flask import Flask,render_template,url_for,request\nimport csv\napp = Flask(__name__)\nprint(__name__)\n\n\n@app.route('/')\ndef main():\n return render_template('index.html')\n\n@app.route('/')\ndef main2(page_name):\n return render_template(page_name)\n\n\n\n@app.route(\"//\")\ndef hello(username=None,post_id=None):\n return \"Hello \" +username+\" has posted a new post which has id: %d\" %post_id\n\n@app.route(\"/blog\")\ndef blog():\n return \"this is mohit's blog\"\n\n@app.route('/submit_form', methods=['POST', 'GET'])\ndef submit_form():\n if request.method == 'POST':\n try:\n data = request.form.to_dict()\n write_data_to_csv(data)\n return render_template('thanks.html')\n except:\n return 'did not save to database' \n else:\n return \"Something Went Wrong\"\n\ndef write_data(data):\n with open('database.txt',mode='a') as database:\n email = data[\"email\"]\n subject =data[\"subject\"]\n message =data[\"message\"]\n file=database.write(f'\\n{email},{subject},{message}')\n\ndef write_data_to_csv(data):\n with open('database.csv',mode='a',newline='') as database2:\n email = data[\"email\"]\n subject =data[\"subject\"]\n message =data[\"message\"]\n csv_writer= csv.writer(database2,delimiter=',',quotechar='\"',quoting=csv.QUOTE_MINIMAL)\n csv_writer.writerow([email,subject,message])\n","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"158903623","text":"import sys\n\n\nclass Node:\n\n value = None\n left = None\n right = None\n\n def is_leaf(self):\n return self.left is None and self.right is None\n\n\nclass PriorityQueue:\n\n items = []\n\n def push(self, item, priority):\n self.items.append((item, priority))\n\n def pop(self):\n lowest_priority = 1000000\n item = None\n index_to_remove = 0\n\n for index in range(0, len(self.items)):\n curr_item, curr_priority = self.items[index]\n\n is_new_lowest = lowest_priority > curr_priority\n\n item = curr_item if is_new_lowest else item\n lowest_priority = curr_priority if is_new_lowest else lowest_priority\n\n if is_new_lowest:\n index_to_remove = index\n\n if item is not Node:\n self.items.pop(index_to_remove)\n\n return item\n\n def length(self):\n return len(self.items)\n\n\ndef build_tree(nodes):\n queue = PriorityQueue()\n\n for node in nodes:\n queue.push(node, node.value)\n\n while queue.length() > 1:\n left_node = queue.pop()\n right_node = queue.pop()\n\n parent = Node()\n parent.left = left_node\n parent.right = right_node\n parent.value = left_node.value + right_node.value\n\n queue.push(parent, parent.value)\n\n return queue.pop()\n\n\ndef str_to_nums(string):\n nums = []\n strings = string.split(' ')\n\n for item in strings:\n nums.append(float(item))\n\n return nums\n\n\ndef to_nodes(numbers):\n nodes = []\n\n for num in numbers:\n node = Node()\n node.value = num\n nodes.append(node)\n\n return nodes\n\n\ndef node_to_code(node, code, codes):\n if node.is_leaf():\n codes.append((code, node.value))\n return\n\n node_to_code(node.left, code + '0', codes)\n node_to_code(node.right, code + '1', codes)\n\n\ndef tree_to_code(node):\n codes = []\n code = ''\n node_to_code(node, code, codes)\n\n return codes\n\n\ndef build_code(frequencies):\n sorted_frequencies = sorted(frequencies)\n\n tree = build_tree(to_nodes(sorted_frequencies))\n code = tree_to_code(tree)\n\n return code\n\n\ndef print_code(code, frequencies, dest_file):\n for frequency in frequencies:\n for index in range(0, len(code)):\n (code_word, freq) = code[index]\n if freq is frequency:\n dest_file.write(code_word + '\\n')\n code.pop(index)\n break\n\n\ndef process_files(file_names):\n source_file = open(file_names[0], 'r', encoding=\"utf8\")\n dest_file = open(file_names[1], 'w', encoding=\"utf8\")\n\n n = source_file.readline()\n numbers = str_to_nums(source_file.readline())\n code = build_code(numbers)\n print_code(code, numbers, dest_file)\n\n source_file.close()\n dest_file.close()\n\n\ndef main(argv):\n if len(argv) != 2:\n print('Wrong arguments')\n return\n else:\n process_files(argv)\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"Assignment 1/Huffman.py","file_name":"Huffman.py","file_ext":"py","file_size_in_byte":2971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"405837614","text":"#!/usr/bin/python\n\nimport sys, time, operator\n\nclients = []\nservers = []\ncounter = {}\n\nTIME_TO_PRINT = 60\nSEEK = TIME_TO_PRINT + 5\n\ndef empty_list():\n clients = []\n servers = []\n counter = {}\n\ndef print_results(host_cl, host_sr):\n print(\"\")\n print(\"Host Client \" + host_cl + \" connects to: \")\n print(*servers)\n print(\"\")\n print(\"Host Server \" + host_sr + \" connected from: \")\n print(*clients)\n print(\"\")\n print(\"Max client connections:\")\n print(max(counter,items(), key=operator.itemgetter(1))[0])\n \n\ndef addHosts(line, host_cl, host_sr, ts0):\n fields = line.split(\" \")\n ts = float(fields[0])\n cl = fields[1]\n sr = fields[2]\n tsc = time.time()\n diff = (tsc - ts) / 60\n if (cl == host_cl and diff <= TIME_TO_PRINT):\n servers.append(sr)\n if (sr == host_sr and diff <= TIME_TO_PRINT):\n clients.append(cl)\n if (cl in counter and diff <= TIME_TO_PRINT):\n counter[cl] = counter.get(cl) + 1\n else:\n counter[cl] = 1\n\n return tsc - ts0 >= TIME_TO_PRINT\n\ndef main(argv):\n filelog = open(argv[0])\n ts0 = time.time()\n first_exec = True\n follow = True\n while follow:\n line = filelog.readline()\n if not line:\n follow = False\n else:\n ts = float(line.split(\" \")[0])\n diff = (ts0 - ts) / 60\n follow = diff > SEEK\n while True:\n if not line:\n if first_exec:\n print_results(argv[1], argv[2])\n empty_list()\n first_exec = False\n time.sleep(0.2)\n elif addHosts(line, argv[1], argv[2], ts0):\n print_results(argv[1], argv[2])\n empty_list()\n ts0 = time.time()\n line = filelog.readline()\n\n\nif len(sys.argv) > 3 :\n main(sys.argv[1:])","sub_path":"src/logs.py","file_name":"logs.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"626570232","text":"\"\"\"Input ops.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n\nimport tensorflow as tf\nimport h5py\n\ndef init_image_embeddings_and_captions(read_size):\n file = h5py.File('data/image_vgg19_fc1_feature.h5', 'r')\n\n train_set = file['train_set']\n\n images_and_captions = []\n\n index = -1\n\n for line in open(\"data/train_vector.txt\"):\n strs = line.split()\n if len(strs) == 1:\n index = index + 1\n if index == read_size:\n break\n else:\n nums = []\n for e in strs:\n nums.append(int(e))\n images_and_captions.append([train_set[index], nums])\n\n print(\"Finish loading data\")\n return images_and_captions\n\ndef build_batch(captions):\n input_seqs = []\n target = []\n masks = []\n max_len = 0\n for caption in captions:\n if len(caption) > max_len:\n max_len = len(caption)\n\n max_len = max_len-1\n\n for caption in captions:\n want_len = len(caption)-1\n input_seqs.append(caption[0:want_len] + [0]*(max_len-want_len))\n target.append(caption[1:(want_len+1)] + [0]*(max_len-want_len))\n masks.append([1]*want_len+[0]*(max_len-want_len))\n\n return input_seqs, target, masks\n\ndef batch_with_dynamic_pad(images_and_captions,\n batch_size,\n queue_capacity,\n add_summaries=True):\n \"\"\"Batches input images and captions.\n This function splits the caption into an input sequence and a target sequence,\n where the target sequence is the input sequence right-shifted by 1. Input and\n target sequences are batched and padded up to the maximum length of sequences\n in the batch. A mask is created to distinguish real words from padding words.\n Example:\n Actual captions in the batch ('-' denotes padded character):\n [\n [ 1 2 5 4 5 ],\n [ 1 2 3 4 - ],\n [ 1 2 3 - - ],\n ]\n input_seqs:\n [\n [ 1 2 3 4 ],\n [ 1 2 3 - ],\n [ 1 2 - - ],\n ]\n target_seqs:\n [\n [ 2 3 4 5 ],\n [ 2 3 4 - ],\n [ 2 3 - - ],\n ]\n mask:\n [\n [ 1 1 1 1 ],\n [ 1 1 1 0 ],\n [ 1 1 0 0 ],\n ]\n Args:\n images_and_captions: A list of pairs [image, caption], where image is a\n Tensor of shape [height, width, channels] and caption is a 1-D Tensor of\n any length. Each pair will be processed and added to the queue in a\n separate thread.\n batch_size: Batch size.\n queue_capacity: Queue capacity.\n add_summaries: If true, add caption length summaries.\n Returns:\n images: A Tensor of shape [batch_size, height, width, channels].\n input_seqs: An int32 Tensor of shape [batch_size, padded_length].\n target_seqs: An int32 Tensor of shape [batch_size, padded_length].\n mask: An int32 0/1 Tensor of shape [batch_size, padded_length].\n \"\"\"\n enqueue_list = []\n for image, caption in images_and_captions:\n caption_length = tf.shape(caption)[0]\n input_length = tf.expand_dims(tf.subtract(caption_length, 1), 0)\n\n input_seq = tf.slice(caption, [0], input_length)\n target_seq = tf.slice(caption, [1], input_length)\n indicator = tf.ones(input_length, dtype=tf.int32)\n enqueue_list.append([image, input_seq, target_seq, indicator])\n\n images, input_seqs, target_seqs, mask = tf.train.batch_join(\n enqueue_list,\n batch_size=batch_size,\n capacity=queue_capacity,\n dynamic_pad=True,\n name=\"batch_and_pad\")\n\n if add_summaries:\n lengths = tf.add(tf.reduce_sum(mask, 1), 1)\n tf.summary.scalar(\"caption_length/batch_min\", tf.reduce_min(lengths))\n tf.summary.scalar(\"caption_length/batch_max\", tf.reduce_max(lengths))\n tf.summary.scalar(\"caption_length/batch_mean\", tf.reduce_mean(lengths))\n\n return images, input_seqs, target_seqs, mask","sub_path":"Source Code/im2txt/Tensorflow/ops/inputs.py","file_name":"inputs.py","file_ext":"py","file_size_in_byte":3900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"164189501","text":"from selenium import webdriver\nimport time\nimport dataItem\n\n\ndriver = webdriver.Chrome()\nsite = 'https://aflcio.org/paywatch/company-pay-ratios'\n\ndatals = []\n\ndef start():\n\n \"\"\"\n step 1: create chrom driver\n \"\"\"\n #driver = webdriver.Chrome()\n #driver.get(site)\n #print(driver.title)\n\n\ndef append(url):\n driver.get(url)\n elm_body = driver.find_element_by_tag_name(\"body\")\n elm_body = elm_body.find_element_by_class_name(\"dialog-off-canvas-main-canvas\")\n elm_body = elm_body.find_element_by_id(\"page\")\n elm_body = elm_body.find_element_by_tag_name(\"main\")\n #error\n elm_body = elm_body.find_element_by_class_name(\"compare-prompt\")\n elm_title = elm_body.find_element_by_tag_name(\"strong\")\n name = elm_title.text\n myItme = dataItem(name)\n elm_table = elm_body.find_element_by_tag_name(\"table\")\n elm_table = elm_table.find_element_by_tag_name(\"body\")\n elm_data_ls = elm_table.find_elements_by_tag_name(\"tr\")\n\n data = elm_data_ls[0].find_element_by_class_name(\"text-right\").text\n data = data[1:]\n int_data = int(data)\n # to do\n #myItme.\n\n\n\n\ndef appendToLs(url:str) -> str:\n \"\"\"\n get all data, and return the next page\n :return:\n \"\"\"\n #find all data link\n driver.get(url)\n elm_content = driver.find_element_by_id(\"block-views-blockpaywatch-pay-ratio\")\n elm_table = elm_content.find_element_by_tag_name(\"table\")\n elm_tbody = elm_content.find_element_by_tag_name(\"tbody\")\n elm_tr_ls = elm_tbody.find_elements_by_tag_name(\"tr\")\n for x in elm_tr_ls:\n #append(x.find_element_by_tag_name(\"a\").get_attribute('href'))\n elm_td_ls = x.find_elements_by_tag_name(\"td\")\n ticker = elm_td_ls[0].text\n company = elm_td_ls[1].text\n pay = elm_td_ls[2].text\n ratio = elm_td_ls[3].text\n myItme = (ticker + \";\" + company + \";\" + pay + \";\" + ratio)\n datals.append(myItme)\n\n\n\n #second, find next link\n elm_next = elm_content.find_element_by_class_name(\"pager\")\n elm_next = elm_next.find_element_by_tag_name(\"ul\")\n next_url = None\n try:\n elm_next = elm_next.find_element_by_xpath(\"./li[contains(@class, 'next')]\")\n elm_next = elm_next.find_element_by_tag_name(\"a\")\n next_url = elm_next.get_attribute('href')\n except:\n print(\"couldn't find next page\")\n else:\n print(next_url)\n\n return next_url\n\n\n\nif(__name__ == \"__main__\"):\n #start()\n url = site\n for i in range(106):\n url = appendToLs(url)\n if(url == None):\n break\n\n fpath = './data.txt'\n f = open(fpath, mode='a')\n for x in datals:\n print(x)\n f.write(x + \"\\n\")\n f.flush()\n f.close()\n \"\"\"\n final step\n \"\"\"\n time.sleep(10)\n driver.quit()\n","sub_path":"src/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":2756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"20917572","text":"import socket\nimport re\nimport time\nimport multiprocessing\nimport mini_frame_03\n\nclass WSGIServer(object):\n def __init__(self):\n # create socket\n self.headers = \"\"\n self.status = \"\"\n self.socket_main = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.socket_main.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n # binding\n local_info = (\"\", 8080)\n self.socket_main.bind(local_info)\n\n # listen\n self.socket_main.listen(128)\n\n\n def service_client(self, new_socket):\n \"\"\"return data to client\"\"\"\n\n # recieve request\n request = new_socket.recv(1024).decode('utf-8')\n request_lines = request.splitlines()\n print(\"-\"*40)\n print(request_lines)\n\n # locate target html file\n ret = re.match(r\"[^/]+(/[^ ]*)\", request_lines[0])\n if ret:\n dir_html = ret.group(1)\n print(dir_html)\n if dir_html == \"/\":\n print(\"inininininin\")\n dir_html = \"/html/baidu.html\"\n #if dir_html == \" \" \n \n # read html file\n # if dir does not end with .py, then it can be considered static file\n if not dir_html.endswith(\".py\"):\n try:\n print(\"----->Opening file<--------\")\n f = open(\".\" + dir_html, \"r\")\n\n except:\n print(\"------>not found<----------\")\n data_header = \"HTTP/1.1 404 NOT FOUND\\r\\n\"\n data_header += \"\\r\\n\"\n data_body = \"404 not found\"\n\n else:\n print(\"------->resembling<--------\")\n data_body= f.read()\n data_header = \"HTTP/1.1 200 OK\\r\\n\"\n data_header += \"\\r\\n\"\t\t\n f.close()\n\n else:\n # if dir ends with .py, then it can be seen as dynamic file\n\n env = dict()\n env['PATH_INFO'] = dir_html\n data_body = mini_frame_03.application(env, self.set_response_header)\n data_header = f\"HTTP/1.1 {self.status}\\r\\n\"\n for temp in self.headers:\n \tdata_header += f\"{temp[0]}:{temp[1]}\\r\\n\"\n data_header += \"\\r\\n\"\n # send data(header and body) to browser\n\n data = data_header + data_body\n print(\"data compelete\")\n new_socket.send(data.encode('utf-8'))\n\n # close\n new_socket.close()\n\n def set_response_header(self, status, headers):\n \tself.status = status\n \tself.headers = headers\n \t\n\n\n def run(self):\n while True:\n # wait for connection\n socket_client, addr_client = self.socket_main.accept()\n\n p = multiprocessing.Process(target=self.service_client, args=(socket_client,))\n\n # work\n p.start()\n socket_client.close()\n\n self.socket_main.close()\n\ndef main():\n server = WSGIServer()\n server.run()\n\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"09_miniweb/03_server_wsgi.py","file_name":"03_server_wsgi.py","file_ext":"py","file_size_in_byte":2987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"441676435","text":"import multiprocessing as mp\r\nimport numpy as np\r\nimport logging\r\nimport os\r\nimport sys\r\nfrom ltsenv import LTSEnv\r\nimport dualppo as network\r\nimport tensorflow as tf\r\nimport rules\r\n\r\nos.environ['CUDA_VISIBLE_DEVICES'] = '3'\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\r\n\r\nS_DIM = [8, 20]\r\nA_DIM = 13\r\nACTOR_LR_RATE =1e-4\r\nCRITIC_LR_RATE = 1e-3\r\nNUM_AGENTS = 12\r\nTRAIN_SEQ_LEN = 1440 # take as a train batch\r\nTRAIN_EPOCH = 1000000\r\nMODEL_SAVE_INTERVAL = 20\r\nRANDOM_SEED = 42\r\nSUMMARY_DIR = './results'\r\nMODEL_DIR = './models'\r\nTRAIN_TRACES = './cooked_traces/'\r\nTEST_LOG_FOLDER = './test_results/'\r\nLOG_FILE = './results/log'\r\nBATTLE_ROUND = 16\r\n\r\n# create result directory\r\nif not os.path.exists(SUMMARY_DIR):\r\n os.makedirs(SUMMARY_DIR)\r\n \r\nNN_MODEL = None\r\n\r\ndef testing(epoch, pool, nn_model, log_file):\r\n # clean up the test results folder\r\n os.system('rm -r ' + TEST_LOG_FOLDER)\r\n os.mkdir(TEST_LOG_FOLDER)\r\n \r\n # run test script\r\n os.system('python test.py ' + nn_model)\r\n f = open(TEST_LOG_FOLDER + 'log','r')\r\n reward, step = 0., 0.\r\n for p in f:\r\n sp = p.split(',')\r\n reward = float(sp[0])\r\n step = float(sp[1])\r\n f.close()\r\n log_file.write(str(reward) + ',' + str(step))\r\n log_file.write('\\n')\r\n log_file.flush()\r\n\r\ndef central_agent(net_params_queues, exp_queues):\r\n\r\n assert len(net_params_queues) == NUM_AGENTS\r\n assert len(exp_queues) == NUM_AGENTS\r\n \r\n with tf.Session() as sess, open('elo.txt', 'w') as test_log_file:\r\n\r\n actor = network.Network(sess,\r\n state_dim=S_DIM, action_dim=A_DIM,\r\n learning_rate=ACTOR_LR_RATE)\r\n\r\n sess.run(tf.global_variables_initializer())\r\n saver = tf.train.Saver(max_to_keep=1000) # save neural net parameters\r\n\r\n # restore neural net parameters\r\n nn_model = NN_MODEL\r\n if nn_model is not None: # nn_model is the path to file\r\n saver.restore(sess, nn_model)\r\n print(\"Model restored.\")\r\n\r\n # while True: # assemble experiences from agents, compute the gradients\r\n for epoch in range(TRAIN_EPOCH):\r\n # synchronize the network parameters of work agent\r\n actor_net_params = actor.get_network_params()\r\n for i in range(NUM_AGENTS):\r\n net_params_queues[i].put(actor_net_params)\r\n\r\n s, a, p, g = [], [], [], []\r\n for i in range(NUM_AGENTS):\r\n s_, a_, p_, g_ = exp_queues[i].get()\r\n s += s_\r\n a += a_\r\n p += p_\r\n g += g_\r\n\r\n for _ in range(actor.training_epo):\r\n actor.train(s, a, p, g)\r\n\r\n if epoch % MODEL_SAVE_INTERVAL == 0:\r\n # Save the neural net parameters to disk.\r\n save_path = saver.save(sess, SUMMARY_DIR + \"/nn_model_ep_\" +\r\n str(epoch) + \".ckpt\")\r\n testing(epoch, None,\r\n SUMMARY_DIR + \"/nn_model_ep_\" + str(epoch) + \".ckpt\", \r\n test_log_file)\r\n\r\ndef agent(agent_id, net_params_queue, exp_queue):\r\n env = LTSEnv(agent_id)\r\n with tf.Session() as sess, open(SUMMARY_DIR + '/log_agent_' + str(agent_id), 'w') as log_file:\r\n actor = network.Network(sess,\r\n state_dim=S_DIM, action_dim=A_DIM,\r\n learning_rate=ACTOR_LR_RATE)\r\n\r\n # initial synchronization of the network parameters from the coordinator\r\n actor_net_params = net_params_queue.get()\r\n actor.set_network_params(actor_net_params)\r\n\r\n time_stamp = 0\r\n obs = env.reset()\r\n # env.reset()\r\n for epoch in range(TRAIN_EPOCH):\r\n env.reset_trace()\r\n tmp_buffer = []\r\n for i in range(BATTLE_ROUND):\r\n obs = env.reset()\r\n s_batch, a_batch, workload_batch, ratio_batch = [], [], [], []\r\n p_batch = []\r\n for step in range(TRAIN_SEQ_LEN):\r\n s_batch.append(obs)\r\n action_prob = actor.predict(\r\n np.reshape(obs, (1, S_DIM[0], S_DIM[1])))\r\n\r\n noise = np.random.gumbel(size=len(action_prob))\r\n act = np.argmax(np.log(action_prob) + noise)\r\n\r\n obs, rew, done, info = env.step(act)\r\n\r\n action_vec = np.zeros(A_DIM)\r\n action_vec[act] = 1\r\n a_batch.append(action_vec)\r\n p_batch.append(action_prob)\r\n\r\n workload_batch.append(info['workload'])\r\n ratio_batch.append(0. - rew)\r\n if done:\r\n break\r\n tmp_buffer.append(\r\n [s_batch, a_batch, p_batch, workload_batch, ratio_batch])\r\n \r\n s, a, p, g = [], [], [], []\r\n for i in range(BATTLE_ROUND):\r\n w_arr = []\r\n for j in range(BATTLE_ROUND):\r\n if i != j:\r\n tmp_agent_results = []\r\n # i\r\n s_batch, a_batch, p_batch, workload_batch, ratio_batch = tmp_buffer[i]\r\n bit_rate_ = np.mean(workload_batch)\r\n rebuffer_ = np.mean(ratio_batch)\r\n smoothness_ = np.mean(np.abs(np.diff(workload_batch)))\r\n tmp_agent_results.append([bit_rate_, rebuffer_, smoothness_])\r\n # j\r\n s_batch, a_batch, p_batch, workload_batch, ratio_batch = tmp_buffer[j]\r\n bit_rate_ = np.mean(workload_batch)\r\n rebuffer_ = np.mean(ratio_batch)\r\n smoothness_ = np.mean(np.abs(np.diff(workload_batch)))\r\n tmp_agent_results.append([bit_rate_, rebuffer_, smoothness_])\r\n # battle\r\n w_rate_imm = rules.rules(tmp_agent_results)[0]\r\n w_arr.append(w_rate_imm)\r\n w_rate = np.sum(w_arr) / len(w_arr)\r\n s_batch, a_batch, p_batch, workload_batch, ratio_batch = tmp_buffer[i]\r\n # Policy invariance under reward \r\n for s_, a_, p_ in zip(s_batch, a_batch, p_batch):\r\n s.append(s_)\r\n a.append(a_)\r\n p.append(p_)\r\n g.append([w_rate])\r\n exp_queue.put([s, a, p, g])\r\n\r\n actor_net_params = net_params_queue.get()\r\n actor.set_network_params(actor_net_params)\r\n\r\ndef compute_entropy(x):\r\n \"\"\"\r\n Given vector x, computes the entropy\r\n H(x) = - sum( p * log(p))\r\n \"\"\"\r\n H = 0.0\r\n for i in range(len(x)):\r\n if 0 < x[i] < 1:\r\n H -= x[i] * np.log(x[i])\r\n return H\r\n\r\ndef main():\r\n\r\n np.random.seed(RANDOM_SEED)\r\n\r\n # inter-process communication queues\r\n net_params_queues = []\r\n exp_queues = []\r\n for i in range(NUM_AGENTS):\r\n net_params_queues.append(mp.Queue(1))\r\n exp_queues.append(mp.Queue(1))\r\n\r\n # create a coordinator and multiple agent processes\r\n # (note: threading is not desirable due to python GIL)\r\n coordinator = mp.Process(target=central_agent,\r\n args=(net_params_queues, exp_queues))\r\n coordinator.start()\r\n\r\n agents = []\r\n for i in range(NUM_AGENTS):\r\n agents.append(mp.Process(target=agent,\r\n args=(i,\r\n net_params_queues[i],\r\n exp_queues[i])))\r\n for i in range(NUM_AGENTS):\r\n agents[i].start()\r\n\r\n # wait unit training is done\r\n coordinator.join()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"lts/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"141627381","text":"# Wilfred\n# Copyright (C) 2020, Vilhelm Prytz, \n#\n# Licensed under the terms of the MIT license, see LICENSE.\n# https://github.com/wilfred-dev/wilfred\n\nimport sqlite3\nimport click\n\nfrom appdirs import user_data_dir\nfrom os.path import isfile, isdir\nfrom pathlib import Path\n\nfrom wilfred.message_handler import info, error\n\nAPI_VERSION = 1\n\n\ndef _query(path, query, fetchone=False):\n \"\"\"\n executes specified query on sqlite3 database located at specified path\n\n :param str path: the path of the sqlite3 database\n :param str query: sql query to execute\n \"\"\"\n\n result = []\n\n try:\n conn = sqlite3.connect(path)\n conn.row_factory = sqlite3.Row\n\n cur = conn.cursor()\n cur.execute(query)\n\n if fetchone:\n result = cur.fetchone()\n else:\n for r in cur.fetchone() if fetchone else cur.fetchall():\n result.append(dict(r))\n\n conn.commit()\n conn.close()\n except sqlite3.OperationalError as e:\n error(\n \"could not communicate with database \" + click.style(str(e), bold=True),\n exit_code=1,\n )\n except sqlite3.IntegrityError as e:\n error(\"invalid input \" + click.style(str(e), bold=True), exit_code=1)\n\n return result\n\n\nclass Database(object):\n def __init__(self):\n self.data_dir = f\"{user_data_dir()}/wilfred\"\n self.database_path = f\"{self.data_dir}/wilfred.db\"\n\n if not isdir(self.data_dir):\n Path(self.data_dir).mkdir(parents=True, exist_ok=True)\n\n # main sqlite3 database\n if not isfile(self.database_path):\n info(\"local database not found, creating\")\n self._create_tables()\n self._insert_api_version()\n\n return\n if (\n int(\n self.query(\n f\"SELECT value FROM constants WHERE name = 'api_version'\",\n fetchone=True,\n )[\"value\"]\n )\n != API_VERSION\n ):\n error(f\"database API level differs from Wilfreds\", exit_code=1)\n\n def _create_tables(self):\n _tables = [\n \"\"\"CREATE TABLE constants (\n name VARCHAR NOT NULL UNIQUE,\n value VARCHAR,\n PRIMARY KEY (name)\n );\"\"\",\n \"\"\"CREATE TABLE servers (\n id VARCHAR NOT NULL UNIQUE,\n name VARCHAR NOT NULL UNIQUE,\n image_uid VARCHAR NOT NULL,\n memory INT NOT NULL,\n port INT NOT NULL UNIQUE,\n custom_startup VARCHAR,\n status VARCHAR NOT NULL,\n PRIMARY KEY (id)\n );\"\"\",\n \"\"\"CREATE TABLE variables (\n server_id VARCHAR NOT NULL,\n variable VARCHAR NOT NULL,\n value VARCHAR NOT NULL\n )\"\"\",\n ]\n\n with click.progressbar(\n _tables, label=\"Creating tables\", length=len(_tables)\n ) as tables:\n for table in tables:\n _query(self.database_path, table)\n\n def _insert_api_version(self):\n _query(\n self.database_path,\n f\"INSERT INTO constants (name, value) VALUES ('api_version', '{API_VERSION}')\",\n )\n\n def query(self, query, *args, **kwargs):\n return _query(self.database_path, query, *args, **kwargs)\n","sub_path":"wilfred/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":3409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"500952154","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/ast2000tools/relativity.py\n# Compiled at: 2019-11-12 17:41:01\n\"\"\"Module containing the RelativityExperiments class.\"\"\"\nfrom __future__ import division, print_function, absolute_import\nfrom six.moves import range\nimport os, itertools, numpy as np\nfrom scipy import interpolate\nfrom lxml import etree\nimport ast2000tools.constants as const, ast2000tools.utils as utils\nfrom ast2000tools.solar_system import SolarSystem\n\nclass RelativityExperiments(object):\n \"\"\"Represents a set of experiments with relativity taking place in your solar system.\n\n This class is used to run various experiments with special and general relativity and observe the results.\n\n Parameters\n ----------\n seed : int\n The seed to use when generating random solar system and experiment properties.\n data_path : str, optional\n Specifies the path to the directory where output XML files should be stored (e.g. the MCAst data folder).\n By default, a folder called \"XMLs\" is created in the working directory.\n \"\"\"\n\n def __init__(self, seed, data_path=None):\n self._system = SolarSystem(seed, data_path=data_path, has_moons=False)\n self._set_solution_path(None)\n self._set_debugging(False)\n self._set_test_mode(False)\n self._ruler_height = 0.28\n return\n\n @property\n def seed(self):\n \"\"\"int: The seed used to generate random solar system and experiment properties.\"\"\"\n return self._system.seed\n\n @property\n def data_path(self):\n \"\"\"str: The path to the directory where output XML files will be stored.\"\"\"\n return self._system.data_path\n\n @property\n def system(self):\n \"\"\"SolarSystem: The randomized solar system where the experiments take place.\"\"\"\n return self._system\n\n def crash_landing(self, planet_idx, increase_height=False, filename_1='crash_landing_frame_1.xml', filename_2='crash_landing_frame_2.xml', number_of_video_frames=1000):\n \"\"\"A spaceship's failed landing attempt is observed from both the spaceship the surface of the planet.\n\n Generates the XML files used in Exercise 2 in Part 2A of the lecture notes.\n\n Parameters\n ----------\n planet_idx : int\n Index of the planet above which the experiment takes place.\n increase_height : bool or float, optional\n Determines the height above the planet center where the experiment takes place.\n The default value (False) causes a predetermined height of 1.001 planet radii to be used. Using True increases this to 1.1.\n Optionally, a custom adjustment parameter between 0.5 and 5 can be provided.\n Try modifying this argument if the spaceships interfere with the surface of the planet.\n filename_1 : str, optional\n The filename to use for frame of reference 1.\n filename_2 : str, optional\n The filename to use for frame of reference 2.\n number_of_video_frames : int, optional\n The number of video frames to use in the XML files.\n Can be reduced to reduce file size, but be aware that this might lead to errors.\n Default is 1000, but must be at least 100.\n \"\"\"\n planet_idx = int(planet_idx)\n if planet_idx < 0 or planet_idx >= self.system.number_of_planets:\n raise ValueError('Argument \"planet_idx\" is %d but must be in the range [0, %d].' % (planet_idx, self.system.number_of_planets - 1))\n N = int(number_of_video_frames)\n if N < 100:\n raise ValueError('Argument \"number_of_video_frames\" is %d but must be at least 100.' % N)\n filename_1 = str(filename_1)\n filename_2 = str(filename_2)\n sat_color = [\n 0, 0, 1]\n planet_radius = utils.km_to_AU(self.system.radii[planet_idx])\n start_radius = planet_radius * 2\n if increase_height is False:\n end_radius = planet_radius * 1.001\n else:\n if increase_height is True:\n end_radius = planet_radius * 1.1\n else:\n if increase_height < 0.5 or increase_height > 5.0:\n print('Increase height needs to be True, False or between 0.5 and 5')\n raise ValueError('Increase_height invalid')\n if increase_height >= 1:\n end_radius = planet_radius * (1.001 + 0.003 * increase_height)\n else:\n end_radius = planet_radius * (1.001 - 0.001 * increase_height)\n random_state = np.random.RandomState(self.seed + utils.get_seed('crash_landing'))\n atmos_frame = random_state.randint(int(0.6 * N), int(0.7 * N))\n crash_frame = random_state.randint(int(0.9 * N), int(0.95 * N))\n cam_speed = utils.km_to_AU(random_state.uniform(0.95 * const.c_km_pr_s, 0.99 * const.c_km_pr_s))\n cam_start_pos = [-start_radius, 0, 0]\n cam_end_pos = [-end_radius, 0, 0]\n cam_pos = np.zeros(shape=(N, 3))\n cam_pos[:crash_frame, 0] = np.linspace(cam_start_pos[0], cam_end_pos[0], crash_frame)\n cam_pos[crash_frame:] += cam_end_pos\n cam_dir = np.zeros(shape=(N, 3)) + np.array([1, 0, 0])\n cam_dir[crash_frame:] += np.array([-1, 1, 0])\n camera_messages = [ '' for i in range(N) ]\n distance_to_planet_in_sat_frame = utils.AU_to_km((cam_pos[(crash_frame, 0)] - cam_pos[(atmos_frame, 0)]) * np.sqrt(1 - (cam_speed / const.c_AU_pr_s) ** 2))\n distance_to_planet_in_planet_frame = utils.AU_to_km(cam_pos[(crash_frame, 0)] - cam_pos[(atmos_frame, 0)])\n expl_vis = np.zeros(N)\n expl_vis[crash_frame:crash_frame + 10] += 1\n expl_sound = [ '' for i in range(N) ]\n expl_sound[crash_frame] = 'explosion'\n expl_pos = cam_pos + np.array([0, utils.km_to_AU(10), 0])\n other_objects = [['Exp0', 'explosion', expl_pos, 130, [100, 0, 0], None, expl_sound, expl_vis, None]]\n crash_time = (cam_end_pos[0] - cam_start_pos[0]) / cam_speed * np.sqrt(1 - (cam_speed / const.c_AU_pr_s) ** 2)\n end_time = N / float(crash_frame + 1) * crash_time\n time_array = np.linspace(0, end_time, N)\n dt_in_sat_frame = distance_to_planet_in_sat_frame * 1000 / utils.AU_to_km(cam_speed)\n for i in range(atmos_frame, N):\n camera_messages[i] = 'Spaceship has entered the atmosphere and sent message.\\nDistance to the ground %f km in our frame of reference. \\nTime when entering the atmosphere: %f ms' % (distance_to_planet_in_sat_frame, crash_time * 1000 - dt_in_sat_frame)\n\n for i in range(crash_frame, N):\n camera_messages[i] += '\\n\\nSpaceship has crashed....BOOM\\nTime of the crash: %g ms' % (crash_time * 1000)\n\n self._write_to_xml(time_array, cam_pos, cam_dir, other_objects=other_objects, camera_messages=camera_messages, planet_idx=planet_idx, filename=filename_1, use_obj_scaling=0, play_speed=0.501)\n sat_speed = cam_speed\n cam_pos = np.zeros(shape=3) + np.array([-end_radius * 1.01, 0, 0])\n sat_pos = np.zeros(shape=(N, 3))\n sat_start_pos = [-start_radius, 0, 0]\n sat_end_pos = [-end_radius, 0, 0]\n sat_pos[:crash_frame, 0] = np.linspace(sat_start_pos[0], sat_end_pos[0], crash_frame)\n sat_pos[crash_frame:] += sat_end_pos\n cam_dir = [-1, 0, 0]\n camera_messages = [ '' for i in range(N) ]\n expl_vis = np.zeros(N)\n expl_vis[crash_frame:] += 1\n expl_sound = [ '' for i in range(N) ]\n expl_sound[crash_frame] = 'explosion'\n expl_pos = sat_end_pos * np.array([1.01, 0, 0]) - np.array([utils.km_to_AU(10), 0, 0])\n other_objects = [\n [\n 'Sat0', 'Satellite', sat_pos, 0.05, sat_color, None, None, None, None],\n [\n 'Exp0', 'explosion', expl_pos, 100, [100, 0, 0], None, expl_sound, expl_vis, None]]\n crash_time = (sat_pos[(crash_frame, 0)] - sat_pos[(0, 0)]) / sat_speed\n end_time = N / float(crash_frame + 1) * crash_time\n time_array = np.linspace(0, end_time, N)\n dt_in_planet_frame = distance_to_planet_in_planet_frame * 1000 / utils.AU_to_km(cam_speed)\n for i in range(atmos_frame, N):\n camera_messages[i] = 'Spaceship has entered the atmosphere and sent message.\\nDistance to ground %f km in our frame of reference. \\nTime when entering the atmosphere: %g ms' % (distance_to_planet_in_planet_frame, crash_time * 1000 - dt_in_planet_frame)\n\n for i in range(crash_frame, N):\n camera_messages[i] += '\\n\\nSpaceship has crashed....BOOM\\nTime of the crash: %g ms' % (crash_time * 1000)\n\n self._write_to_xml(time_array, cam_pos, cam_dir, other_objects=other_objects, camera_messages=camera_messages, planet_idx=planet_idx, filename=filename_2, use_obj_scaling=0, play_speed=0.5002)\n if self._write_solutions:\n solution_name = 'Solutions_crash_landing.txt'\n solution_2A = open(os.path.join(self._solution_path, solution_name), 'w')\n solution_2A.write('Solutions to 2A.2\\n')\n solution_2A.write('\\n')\n solution_2A.write('Answers for spaceship frame:\\n')\n solution_2A.write('3) v = %fc\\n' % (utils.AU_to_km(cam_speed) / const.c_km_pr_s))\n solution_2A.write(\"4) Delta s'^2 = %f ms^2\\n\" % (distance_to_planet_in_sat_frame * 1000 / utils.AU_to_km(cam_speed)) ** 2)\n solution_2A.write('5) Delta t = %f ms\\n' % dt_in_planet_frame)\n solution_2A.write('\\n')\n solution_2A.write('Answers for planet fram:\\n')\n solution_2A.write('3) v=%fc\\n' % (utils.AU_to_km(cam_speed) / const.c_km_pr_s))\n solution_2A.write('4) Delta s^2 = %f ms^2\\n' % ((distance_to_planet_in_planet_frame * 1000 / utils.AU_to_km(cam_speed)) ** 2 - (distance_to_planet_in_planet_frame / const.c_km_pr_s * 1000) ** 2))\n solution_2A.write('5) Delta t = %f ms\\n' % dt_in_sat_frame)\n solution_2A.close()\n return\n\n def lightning_strikes(self, planet_idx, increase_height=False, filename_1='lightning_strikes_frame_1.xml', filename_2='lightning_strikes_frame_2.xml', field_of_view=70, number_of_video_frames=1000):\n \"\"\"A spaceship is struck by a yellow and a blue lightning bolt while traveling through the atmosphere of a planet.\n\n Generates the XML files used in Exercise 3 in Part 2A of the lecture notes.\n\n Parameters\n ----------\n planet_idx : int\n Index of the planet above which the experiment takes place.\n increase_height : bool or float, optional\n Determines the height above the planet center where the experiment takes place.\n The default value (False) causes a predetermined height of 1.01 planet radii to be used. Using True increases this to 1.1.\n Optionally, a custom adjustment parameter between 0.5 and 5 can be provided.\n Try modifying this argument if the spaceships interfere with the surface of the planet.\n filename_1 : str, optional\n The filename to use for frame of reference 1.\n filename_2 : str, optional\n The filename to use for frame of reference 2.\n field_of_view : float, optional\n The field of view of the camera, in degrees.\n Default is 70.\n number_of_video_frames : int, optional\n The number of video frames to use in the XML files.\n Can be reduced to reduce file size, but be aware that this might lead to errors.\n Default is 1000, but must be at least 100.\n \"\"\"\n planet_idx = int(planet_idx)\n if planet_idx < 0 or planet_idx >= self.system.number_of_planets:\n raise ValueError('Argument \"planet_idx\" is %d but must be in the range [0, %d].' % (planet_idx, self.system.number_of_planets - 1))\n N = int(number_of_video_frames)\n if N < 100:\n raise ValueError('Argument \"number_of_video_frames\" is %d but must be at least 100.' % N)\n filename_1 = str(filename_1)\n filename_2 = str(filename_2)\n low_sat_speed = [\n 0.8, 0.84]\n high_sat_speed = [0.86, 0.9]\n distance_to_events = utils.km_to_AU(800.0)\n cam_dir = np.array([0, 0, -1])\n planet_radius = utils.km_to_AU(self.system.radii[planet_idx])\n if increase_height is False:\n event_radius = planet_radius * 1.01\n else:\n if increase_height is True:\n event_radius = planet_radius * 1.1\n else:\n if increase_height < 0.5 or increase_height > 5.0:\n print('Increase height needs to be True, False or between 0.5 and 5')\n raise ValueError('Increase_height invalid')\n if increase_height >= 1:\n event_radius = planet_radius * (1.005 + 0.005 * increase_height)\n else:\n event_radius = planet_radius * (1.005 - 0.005 * increase_height)\n random_seed = self.seed + utils.get_seed('lightning_strikes')\n random_state = np.random.RandomState(random_seed)\n v_cam_planframe = random_state.uniform(low_sat_speed[0], low_sat_speed[1])\n v_friend_planframe = random_state.uniform(high_sat_speed[0], high_sat_speed[1])\n v_friend_camframe = self._velocity_transformation(v_cam_planframe, v_friend_planframe)\n v_cam_planframe = v_cam_planframe * const.c_AU_pr_s\n v_friend_planframe = v_friend_planframe * const.c_AU_pr_s\n v_friend_camframe = v_friend_camframe * const.c_AU_pr_s\n if self._debug:\n print('Our velocity in planet frame = %gc\\nFriend velocity in planet frame = %gc\\nFriend velocity in our frame = %gc' % (v_cam_planframe, v_friend_planframe, v_friend_camframe))\n sat_movement_length_planframe = utils.km_to_AU(2000)\n end_time_planframe = sat_movement_length_planframe / max([v_cam_planframe, v_friend_planframe])\n time_array_planframe = np.linspace(0, end_time_planframe, N)\n cam_pos_1D_camframe = np.zeros(N)\n friend_pos_1D_camframe = np.linspace(0, end_time_planframe * v_friend_camframe, N)\n cam_pos_1D_planframe = np.linspace(0, end_time_planframe * v_cam_planframe, N)\n friend_pos_1D_planframe = np.linspace(0, end_time_planframe * v_friend_planframe, N)\n end_time_camframe, _ = self._lorentz_transform(time_array_planframe[(-1)], cam_pos_1D_planframe[(-1)], v_cam_planframe)\n end_time_friendframe, _ = self._lorentz_transform(time_array_planframe[(-1)], cam_pos_1D_planframe[(-1)], v_friend_planframe)\n time_array_camframe = np.linspace(0, end_time_camframe, N)\n time_array_friendframe = np.linspace(0, end_time_friendframe, N)\n planet_pos_1D_camframe = np.linspace(0, -end_time_planframe * v_cam_planframe, N)\n cam_pos = np.zeros(shape=(N, 3))\n cam_pos[:, 2] += distance_to_events\n friend_pos_camframe = np.zeros(shape=(N, 3))\n friend_pos_camframe[:, 1] = friend_pos_1D_camframe\n friend_pos_camframe[:, 2] -= distance_to_events\n cam_pos_camframe = np.zeros(shape=(N, 3))\n cam_pos_camframe[:, 1] = cam_pos_1D_camframe\n planet_pos_camframe = np.zeros(shape=(N, 3))\n planet_pos_camframe[:, 0] += event_radius\n planet_pos_camframe[:, 1] = planet_pos_1D_camframe\n ball1_pos_camframe = np.zeros(shape=(N, 3))\n ball1_visibility = np.zeros(shape=N)\n random_state.seed(random_seed)\n events_index_planframe = random_state.randint(N // 4, 3 * N // 5)\n events_time_planframe = time_array_planframe[events_index_planframe]\n avg_sat_pos_at_event = (cam_pos_1D_planframe[events_index_planframe] + friend_pos_1D_planframe[events_index_planframe]) / 2.0\n event1_pos_1D_planframe = avg_sat_pos_at_event + utils.km_to_AU(110)\n event2_pos_1D_planframe = cam_pos_1D_planframe[events_index_planframe]\n event1_time_camframe, event1_pos_1D_camframe = self._lorentz_transform(events_time_planframe, event1_pos_1D_planframe, v_cam_planframe)\n event2_time_camframe, event2_pos_1D_camframe = self._lorentz_transform(events_time_planframe, event2_pos_1D_planframe, v_cam_planframe)\n event1_time_friendframe, event1_pos_1D_friendframe = self._lorentz_transform(events_time_planframe, event1_pos_1D_planframe, v_friend_planframe)\n event2_time_friendframe, event2_pos_1D_friendframe = self._lorentz_transform(events_time_planframe, event2_pos_1D_planframe, v_friend_planframe)\n event1_index_camframe = np.abs(event1_time_camframe - time_array_planframe).argmin()\n event2_index_camframe = np.abs(event2_time_camframe - time_array_planframe).argmin()\n event1_visibility = np.zeros(shape=N)\n event2_visibility = np.zeros(shape=N)\n event1_visibility[event1_index_camframe:event1_index_camframe + N // 32] += 1\n event2_visibility[event2_index_camframe:event2_index_camframe + N // 32] += 1\n camera_messages = [ '' for i in range(N) ]\n event2_messages = [ '' for i in range(N) ]\n event2_messages[event2_index_camframe:(event2_index_camframe + N // 32)] = [\n '\\n\\nEvent B'] * (N // 32)\n event1_pos_camframe = np.zeros(shape=(N, 3))\n event2_pos_camframe = np.zeros(shape=(N, 3))\n event1_pos_camframe[:, 1] = event1_pos_1D_camframe\n event2_pos_camframe[:, 1] = event2_pos_1D_camframe\n event3_index_planframe = random_state.randint(N // 8, N // 4)\n event4_index_planframe = 0\n event3_time_camframe = event1_time_camframe\n event3_index_camframe = event1_index_camframe\n event3_pos_1D_camframe = cam_pos_1D_camframe[event3_index_camframe]\n event3_time_planframe, event3_pos_1D_planframe = self._lorentz_transform(event3_time_camframe, event3_pos_1D_camframe, -v_cam_planframe)\n event3_index_planframe = np.abs(event3_time_planframe - time_array_planframe).argmin()\n event4_time_planframe = time_array_planframe[event4_index_planframe]\n avg_sat_pos_at_event4 = (cam_pos_1D_planframe[event4_index_planframe] + friend_pos_1D_planframe[event4_index_planframe]) / 2.0\n event4_pos_1D_planframe = 0\n event4_time_camframe, event4_pos_1D_camframe = self._lorentz_transform(event4_time_planframe, event4_pos_1D_planframe, v_cam_planframe)\n event4_index_camframe = np.abs(event4_time_camframe - time_array_planframe).argmin()\n event3_visibility = np.zeros(shape=N)\n event4_visibility = np.zeros(shape=N)\n event3_visibility[event3_index_camframe:event3_index_camframe + N // 32] += 1\n event3_messages = [ '' for i in range(N) ]\n event4_messages = [ '' for i in range(N) ]\n event3_messages[event3_index_camframe:(event3_index_camframe + N // 32)] = [\n '\\n\\nEvent Y'] * (N // 32)\n event3_pos_camframe = np.zeros(shape=(N, 3))\n event4_pos_camframe = np.zeros(shape=(N, 3))\n event3_pos_camframe[:, 1] = event3_pos_1D_camframe\n event4_pos_camframe[:, 1] = event4_pos_1D_camframe\n camera_messages = [ camera_messages[i] + 'Velocity of planet relative to our spacecraft frame = %fc' % (-v_cam_planframe / const.c_AU_pr_s) for i in range(N) ]\n for i in range(event3_index_camframe, N):\n camera_messages[i] += '\\nTime of event Y = %f ms' % (time_array_planframe[event3_index_camframe] * 1000)\n if i >= event2_index_camframe:\n camera_messages[i] += '\\nTime of event B = %f ms' % (time_array_planframe[event2_index_camframe] * 1000)\n\n ruler_length = utils.AU_to_km(self._get_ruler_length(distance_to_events, field_of_view=field_of_view))\n ruler = [\n -ruler_length / 5.0, ruler_length * 4.0 / 5.0, 20, 'km', utils.AU_to_km(distance_to_events)]\n cam_pos[:, 1] = utils.km_to_AU(ruler_length) * 3.0 / 10.0\n planet_pos_camframe[:, 1] += utils.km_to_AU(ruler_length) * 3.0 / 10.0\n other_objects = [\n [\n 'Friend', 'Satellite', cam_pos_camframe, 0.08, [1, 1, 1], None, None, None, [0, -1, 0]],\n [\n 'Ball2', 'Sphere01', event2_pos_camframe, 5, [250, 250, 250], None, None, event2_visibility, None],\n [\n 'Ball3', 'Sphere01', event3_pos_camframe, 5, [250, 250, 250], None, None, event3_visibility, None],\n [\n 'Ball4', 'Sphere01', event4_pos_camframe, 5, [250, 250, 250], None, None, event4_visibility, None],\n [\n 'Event2', 'explosion', event2_pos_camframe, 800, [0, 1, 1], event2_messages, None, event2_visibility, None],\n [\n 'Event3', 'explosion', event3_pos_camframe, 800, [1, 1, 0], event3_messages, None, event3_visibility, None],\n [\n 'Event4', 'explosion', event4_pos_camframe, 800, [0, 1, 0], None, None, event4_visibility, None]]\n self._write_to_xml(time_array_planframe, cam_pos, cam_dir, planet_pos_camframe, ruler=ruler, other_objects=other_objects, camera_messages=camera_messages, planet_idx=planet_idx, up_vec=[-1, 0, 0], filename=filename_1, play_speed=0.501, field_of_view=field_of_view, use_obj_scaling=1)\n if self._write_solutions:\n solution_name = 'Solutions_part2A_3.txt'\n solution_2A = open(os.path.join(self._solution_path, solution_name), 'w')\n solution_2A.write('Solutions to 2A.3\\n')\n solution_2A.write('\\n')\n solution_2A.write('Answers for spaceship frame:\\n')\n solution_2A.write(\"1a) Check the video for time, x'(B) = 0 km , x'(Y) = 0 km\\n\")\n solution_2A.write(\"1b/2d/3d) Delta t' = %f ms\\n\" % abs(time_array_planframe[event3_index_camframe] * 1000 - time_array_planframe[event2_index_camframe] * 1000))\n cam_pos_planframe = np.zeros(shape=(N, 3))\n cam_pos_planframe[:, 1] = cam_pos_1D_planframe\n event1_pos_planframe = np.zeros(shape=(N, 3))\n event2_pos_planframe = np.zeros(shape=(N, 3))\n event3_pos_planframe = np.zeros(shape=(N, 3))\n event4_pos_planframe = np.zeros(shape=(N, 3))\n event1_pos_planframe[:, 1] = event1_pos_1D_planframe\n event2_pos_planframe[:, 1] = event2_pos_1D_planframe\n event3_pos_planframe[:, 1] = event3_pos_1D_planframe\n event4_pos_planframe[:, 1] = event4_pos_1D_planframe\n event1_visibility = np.zeros(shape=N)\n event2_visibility = np.zeros(shape=N)\n event1_visibility[events_index_planframe:events_index_planframe + N // 32] += 1\n event2_visibility[events_index_planframe:events_index_planframe + N // 32] += 1\n camera_messages = [ '' for i in range(N) ]\n event1_messages = [ '' for i in range(N) ]\n event2_messages = [ '' for i in range(N) ]\n event1_messages[events_index_planframe:(events_index_planframe + N // 32)] = ['\\n\\nPosition of event X = %fkm' % utils.AU_to_km(event1_pos_1D_planframe)] * (N // 32)\n event2_messages[events_index_planframe:(events_index_planframe + N // 32)] = ['\\n\\nEvent B'] * (N // 32)\n event3_visibility = np.zeros(shape=N)\n event4_visibility = np.zeros(shape=N)\n event3_visibility[event3_index_planframe:event3_index_planframe + N // 32] += 1\n event3_messages = [ '' for i in range(N) ]\n event4_messages = [ '' for i in range(N) ]\n event3_messages[event3_index_planframe:(event3_index_planframe + N // 32)] = [\n '\\nEvent Y'] * (N // 32)\n other_objects = [\n [\n 'Friend', 'Satellite', cam_pos_planframe, 0.08, [1, 1, 1], None, None, None, [0, -1, 0]],\n [\n 'Ball2', 'Sphere01', event2_pos_planframe, 5, [200, 200, 200], None, None, event2_visibility, None],\n [\n 'Ball3', 'Sphere01', event3_pos_planframe, 5, [200, 200, 200], None, None, event3_visibility, None],\n [\n 'Ball4', 'Sphere01', event4_pos_planframe, 5, [200, 200, 200], None, None, event4_visibility, None],\n [\n 'Event2', 'explosion', event2_pos_planframe, 800, [0, 1, 1], event2_messages, None, event2_visibility, None],\n [\n 'Event3', 'explosion', event3_pos_planframe, 800, [1, 1, 0], event3_messages, None, event3_visibility, None],\n [\n 'Event4', 'explosion', event4_pos_planframe, 800, [0, 1, 0], None, None, event4_visibility, None]]\n ruler_length = utils.AU_to_km(self._get_ruler_length(distance_to_events, field_of_view=field_of_view))\n ruler = [-ruler_length / 5.0, ruler_length * 4.0 / 5.0, 20, 'km', utils.AU_to_km(distance_to_events)]\n cam_pos[:, 1] = utils.km_to_AU(ruler_length) * 3.0 / 10.0\n planet_pos_camframe[:, 1] = 0\n camera_messages = [ camera_messages[i] + 'Velocity of spacecraft relative to planet frame = %fc' % (v_cam_planframe / const.c_AU_pr_s) for i in range(N) ]\n for i in range(event3_index_planframe, N):\n camera_messages[i] += '\\nTime of event Y = %f ms' % (time_array_planframe[event3_index_planframe] * 1000)\n if i >= events_index_planframe:\n camera_messages[i] += '\\nTime of event B = %f ms' % (time_array_planframe[events_index_planframe] * 1000)\n\n self._write_to_xml(time_array_planframe, cam_pos, cam_dir, planet_pos_camframe, ruler=ruler, other_objects=other_objects, camera_messages=camera_messages, planet_idx=planet_idx, up_vec=[-1, 0, 0], filename=filename_2, play_speed=0.501, field_of_view=field_of_view)\n if self._write_solutions:\n solution_2A.write('Answers for planet frame:\\n')\n solution_2A.write('1a) Check the video for time, x(B) = %f km , x(Y) = %f km\\n' % (abs(time_array_planframe[event3_index_planframe] * 1000) * v_cam_planframe / const.c_AU_pr_s * 300.0, abs(time_array_planframe[events_index_planframe] * 1000 * v_cam_planframe / const.c_AU_pr_s * 300.0)))\n solution_2A.write('1b/2d/3d) Delta t = %f ms\\n' % abs(time_array_planframe[event3_index_planframe] * 1000 - time_array_planframe[events_index_planframe] * 1000))\n solution_2A.close()\n return\n\n def spaceship_duel(self, planet_idx, increase_height=False, filename_1='spaceship_duel_frame_1.xml', filename_2='spaceship_duel_frame_2.xml', number_of_video_frames=400):\n \"\"\"Two spaceships are moving with equal speed relative to a planet, firing lasers at each other and exploding simultaneously in their frame of reference.\n\n Generates the XML files used in Exercise 4 in Part 2A of the lecture notes and Exercise 1 in Part 8 of the project.\n\n Parameters\n ----------\n planet_idx : int\n Index of the planet above which the experiment takes place.\n increase_height : bool or float, optional\n Determines the height above the planet center where the experiment takes place.\n The default value (False) causes a predetermined height of 1.02 planet radii to be used. Using True increases this to 1.1.\n Optionally, a custom adjustment parameter between 0.5 and 5 can be provided.\n Try modifying this argument if the spaceships interfere with the surface of the planet.\n filename_1 : str, optional\n The filename to use for frame of reference 1.\n Default is \"spaceship_duel_frame_1.xml\".\n filename_2 : str, optional\n The filename to use for frame of reference 2.\n Default is \"spaceship_duel_frame_2.xml\".\n number_of_video_frames : int, optional\n The number of video frames to use in the XML files.\n Can be reduced to reduce file size, but be aware that this might lead to errors.\n Default is 400, but must be at least 100.\n \"\"\"\n planet_idx = int(planet_idx)\n if planet_idx < 0 or planet_idx >= self.system.number_of_planets:\n raise ValueError('Argument \"planet_idx\" is %d but must be in the range [0, %d].' % (planet_idx, self.system.number_of_planets - 1))\n N = int(number_of_video_frames)\n if N < 100:\n raise ValueError('Argument \"number_of_video_frames\" is %d but must be at least 100.' % N)\n filename_1 = str(filename_1)\n filename_2 = str(filename_2)\n factor = 0.4\n standard_height_factor = 1.02\n increase_height_factor = 1.1\n spaceship_distance = utils.km_to_AU(1200.0)\n cam_dist_s1 = utils.km_to_AU(650)\n cam_dist_s2 = utils.km_to_AU(4000) * factor\n ticks_s1 = 14\n ticks_s2 = 14\n moveback_dist = utils.km_to_AU(-300) / factor\n print_positions = False\n ref_frame_movement_dist = 2000\n random_state = np.random.RandomState(self.seed + utils.get_seed('spaceship_duel'))\n ref_frame_speed_int = random_state.randint(570, 620)\n ref_frame_speed = ref_frame_speed_int * const.c_AU_pr_s / 1000.0\n ref_frame_movement = utils.km_to_AU(np.linspace(-ref_frame_movement_dist / 2, ref_frame_movement_dist / 2, N))\n if increase_height is False:\n events_radius = utils.km_to_AU(self.system.radii[planet_idx]) * standard_height_factor\n else:\n if increase_height is True:\n events_radius = utils.km_to_AU(self.system.radii[planet_idx]) * increase_height_factor\n else:\n if increase_height < 0.5 or increase_height > 5.0:\n print('Increase height needs to be True, False or between 0.5 and 5')\n raise ValueError('Increase_height invalid')\n if increase_height >= 1:\n events_radius = utils.km_to_AU(self.system.radii[planet_idx]) * (standard_height_factor + 0.01 * increase_height)\n else:\n events_radius = utils.km_to_AU(self.system.radii[planet_idx]) * (standard_height_factor - 0.02 * increase_height)\n dist_from_star = np.hypot(self.system.initial_positions[(0, planet_idx)], self.system.initial_positions[(1, planet_idx)])\n rocket1_pos_1D = np.zeros(N) - spaceship_distance / 2.0\n rocket2_pos_1D = np.zeros(N) + spaceship_distance / 2.0\n cam_pos_1D = np.zeros(N)\n laser1_pos_1D = np.zeros(N)\n laser2_pos_1D = np.zeros(N)\n end_time = (ref_frame_movement[(-1)] - ref_frame_movement[0]) / ref_frame_speed\n time_array = np.linspace(0, end_time, N)\n dt = time_array[1] - time_array[0]\n dx = utils.km_to_AU((time_array[(-1)] - time_array[(-2)]) * const.c_km_pr_s)\n laser1_pos_1D[0] = rocket1_pos_1D[0]\n laser2_pos_1D[0] = rocket2_pos_1D[0]\n for i in range(N - 1):\n if laser1_pos_1D[i] > rocket2_pos_1D[i] or laser2_pos_1D[i] < rocket1_pos_1D[i]:\n laser1_pos_1D[i:] = laser1_pos_1D[i]\n laser2_pos_1D[i:] = laser2_pos_1D[i]\n expl_index = i + 1\n lasers_visible = np.ones(N)\n lasers_visible[expl_index:] = 0\n ball3_visible = np.copy(lasers_visible)\n ball3_visible[10:] = 0\n ball4_visible = np.copy(lasers_visible)\n ball4_visible[10:] = 0\n explosions_visible = np.copy(lasers_visible)\n explosions_visible = 1 - explosions_visible\n break\n else:\n laser1_pos_1D[i + 1] = laser1_pos_1D[i] + dx\n laser2_pos_1D[i + 1] = laser2_pos_1D[i] - dx\n\n cam_pos = np.zeros(shape=(N, 3))\n rocket1_pos = np.zeros(shape=(N, 3))\n rocket2_pos = np.zeros(shape=(N, 3))\n laser1_pos = np.zeros(shape=(N, 3))\n laser2_pos = np.zeros(shape=(N, 3))\n cam_pos[:, 2] = cam_pos_1D + ref_frame_movement\n rocket1_pos[:, 2] = rocket1_pos_1D + ref_frame_movement\n rocket2_pos[:, 2] = rocket2_pos_1D + ref_frame_movement\n laser1_pos[:, 2] = laser1_pos_1D + ref_frame_movement\n laser2_pos[:, 2] = laser2_pos_1D + ref_frame_movement\n cam_pos[:, 0] -= events_radius\n rocket1_pos[:, 0] -= events_radius\n rocket2_pos[:, 0] -= events_radius\n laser1_pos[:, 0] -= events_radius\n laser2_pos[:, 0] -= events_radius\n middle_observer = np.zeros_like(rocket1_pos)\n middle_observer[:, 0] = rocket1_pos[:, 0]\n middle_observer[:, 2] = (rocket2_pos[:, 2] + rocket1_pos[:, 2]) / 2\n laser1_pos[:, 1] -= utils.km_to_AU(10)\n laser2_pos[:, 1] -= utils.km_to_AU(10)\n cam_pos[:, 1] -= cam_dist_s1\n cam_dir = [0, 1, 0]\n up_vec = [-1, 0, 0]\n if print_positions:\n sat1_msg_list = [ 'x = 0 km' for i in range(N) ]\n sat2_msg_list = [ 'x = %.2f km' % utils.AU_to_km(spaceship_distance) for i in range(N) ]\n l1_msg_list = [ 'x = %.3fkm' % utils.AU_to_km(laser1_pos[(i, 2)] - laser1_pos[(0,\n 2)] - (ref_frame_movement[i] - ref_frame_movement[0])) for i in range(N) ]\n l2_msg_list = [ 'x = %.3fkm' % utils.AU_to_km(laser2_pos[(i, 2)] - laser1_pos[(0,\n 2)] - (ref_frame_movement[i] - ref_frame_movement[0])) for i in range(N) ]\n else:\n sat1_msg_list = None\n sat2_msg_list = None\n l1_msg_list = None\n l2_msg_list = None\n ball3_pos_s1 = np.copy(rocket1_pos)\n ball3_pos_s1[0:9, 2] = ball3_pos_s1[0:9, 2]\n ball4_pos_s1 = np.copy(rocket2_pos)\n ball3_pos_s1[:, 1] -= utils.km_to_AU(2)\n ball4_pos_s1[:, 1] -= utils.km_to_AU(2)\n other_objects = [\n self._object_list('lsr1', 'Laser', laser1_pos, 4, [1, 1, 0], visible=lasers_visible, msg_list=l1_msg_list),\n self._object_list('lsr1', 'Laser', laser2_pos, 4, [1, 0, 0], visible=lasers_visible, msg_list=l2_msg_list),\n self._object_list('rocket1', 'Satellite', rocket1_pos, 0.1, [1, 1, 1], visible=lasers_visible, msg_list=sat1_msg_list),\n self._object_list('rocket2', 'Satellite', rocket2_pos, 0.1, [1, 1, 1], visible=lasers_visible, msg_list=sat2_msg_list, orient=[0, 0, 1]),\n self._object_list('middle_observer', 'Sphere01', middle_observer, 20, [1, 1, 1], visible=[1] * N, msg_list=['\\n\\nDeath Star'] * len(lasers_visible)),\n self._object_list('boom1', 'explosion', rocket1_pos, 1000, [1, 0.6, 0], visible=explosions_visible, msg_list=[ '\\n\\nEvent C' if i >= expl_index else '' for i in range(N) ]),\n self._object_list('boom2', 'explosion', rocket2_pos, 1000, [1, 0.6, 0], visible=explosions_visible, msg_list=[ '\\n\\nEvent D' if i >= expl_index else '' for i in range(N) ]),\n self._object_list('ball1', 'Sphere01', rocket1_pos, 5, [255, 255, 255], visible=explosions_visible),\n self._object_list('ball2', 'Sphere01', rocket2_pos, 5, [255, 255, 255], visible=explosions_visible),\n self._object_list('ball3', 'Sphere01', ball3_pos_s1, 5, [255, 255, 255], visible=ball3_visible, msg_list=[ '\\n\\nEvent A' if i < 15 else '' for i in range(N) ]),\n self._object_list('ball4', 'Sphere01', ball4_pos_s1, 5, [255, 255, 255], visible=ball3_visible, msg_list=[ '\\n\\nEvent B' if i < 15 else '' for i in range(N) ])]\n ruler_length = utils.AU_to_km(self._get_ruler_length(cam_dist_s1))\n ruler_start = -(ruler_length - utils.AU_to_km(spaceship_distance)) / 2.0\n ruler_end = -ruler_start + utils.AU_to_km(spaceship_distance)\n dltax = abs(ruler_start) / 4.0\n fct = np.rint(ruler_length / dltax)\n ruler_end = ruler_start + dltax * fct\n rulerUnit = 'km'\n ruler_s1 = [ruler_start, ruler_end, ticks_s1, rulerUnit, utils.AU_to_km(cam_dist_s1), self._ruler_height]\n planet_pos = np.array([0, 0, -spaceship_distance / 2.0])\n global_messages_s1 = [ '\\nThe planet is moving relative to the spacecrafts with v = %.3fc' % (ref_frame_speed / const.c_AU_pr_s) for i in range(N) ]\n for i in range(N):\n global_messages_s1[i] += '\\nPosition of event A: %f km. Time of event A: %f ms' % (0,\n 0)\n global_messages_s1[i] += '\\nPosition of event B: %f km. Time of event B: %f ms' % (utils.AU_to_km(spaceship_distance), 0)\n\n for i in range(N):\n if explosions_visible[i] == 1:\n global_messages_s1[i] += '\\nPosition of event C: %f km. Time of event C: %f ms' % (0, time_array[expl_index] * 1000)\n global_messages_s1[i] += '\\nPosition of event D: %f km. Time of event D: %f ms' % (utils.AU_to_km(spaceship_distance), time_array[expl_index] * 1000)\n\n self._write_to_xml(time_array, cam_pos, cam_dir, planet_pos, other_objects, ruler=ruler_s1, play_speed=0.501, cheat_light_speed=True, planet_idx=planet_idx, up_vec=up_vec, laser_scale=0.2, filename=filename_1, camera_messages=global_messages_s1)\n rocket1_s2_func = self._ref_sys_interpolate_func(time_array, rocket1_pos_1D, -ref_frame_speed)\n rocket2_s2_func = self._ref_sys_interpolate_func(time_array, rocket2_pos_1D, -ref_frame_speed)\n laser1_s2_func = self._ref_sys_interpolate_func(time_array, laser1_pos_1D, -ref_frame_speed)\n laser2_s2_func = self._ref_sys_interpolate_func(time_array, laser2_pos_1D, -ref_frame_speed)\n t1 = self._lorentz_transform(time_array, rocket1_pos_1D, -ref_frame_speed)[0]\n gamma = 1 / np.sqrt(1 - ref_frame_speed ** 2 / const.c_AU_pr_s ** 2)\n startTime = 0\n endTime = t1[(-1)] - t1[0]\n endTime *= 1.5\n times_s2 = np.linspace(startTime, endTime, N)\n t2 = self._lorentz_transform(time_array, rocket2_pos_1D, -ref_frame_speed)[0]\n rocket1_pos_1D_s2 = rocket1_s2_func(times_s2)\n rocket2_pos_1D_s2 = rocket2_s2_func(times_s2)\n laser1_pos_1D_s2 = laser1_s2_func(times_s2)\n laser2_pos_1D_s2 = laser2_s2_func(times_s2)\n time_diff_ticks = t2[0] - t1[0]\n dist_between_rockets_s2 = rocket2_pos_1D_s2[0] - rocket1_pos_1D_s2[0]\n dist_movement_s2 = ref_frame_speed * endTime\n ref_frame_movement_s2 = np.linspace(-dist_movement_s2 / 2, dist_movement_s2 / 2, N)\n rocket1_s2 = np.zeros(shape=(N, 3))\n rocket2_s2 = np.zeros(shape=(N, 3))\n cam_pos_s2 = np.zeros(shape=(N, 3))\n pos_of_ref_frame = np.zeros(shape=(N, 3))\n rocket1_s2[:, 0] -= events_radius\n rocket2_s2[:, 0] -= events_radius\n cam_pos_s2[:, 0] -= events_radius\n cam_pos_s2[:, 1] -= cam_dist_s2\n rocket1_s2[:, 2] = ref_frame_movement_s2 - dist_between_rockets_s2 / 2\n rocket2_s2[:, 2] = ref_frame_movement_s2 + dist_between_rockets_s2 / 2\n pos_of_ref_frame[:] = 0.5 * rocket1_s2 + 0.5 * rocket2_s2\n cam_dir_s2 = pos_of_ref_frame - cam_pos_s2\n cam_dir_s2[:] = cam_dir_s2[int(N / 2), :]\n laser1_s2 = np.zeros(shape=(N, 3))\n laser2_s2 = np.zeros(shape=(N, 3))\n laser1_s2[0] = rocket1_s2[0]\n laser2_s2[0] = rocket2_s2[0]\n dt = times_s2[1] - times_s2[0]\n dx = const.c_AU_pr_s * dt\n index_laser2_emission = np.argmin(np.abs(times_s2 - time_diff_ticks))\n rocket1_visible = np.ones(N)\n rocket2_visible = np.ones(N)\n laser2_visible = np.zeros(N)\n laser1_s2[:, 0] = rocket2_s2[:, 0]\n laser2_s2[:, 0] = rocket2_s2[:, 0]\n laser2_s2[:, 2] = rocket2_s2[:, 2]\n for i in range(N - 1):\n laser1_s2[(i + 1, 2)] = laser1_s2[(i, 2)] + dx\n if laser1_s2[(i + 1, 2)] > rocket2_s2[(i + 1, 2)]:\n rocket2_visible[i + 1] = 0\n if i >= index_laser2_emission:\n laser2_s2[(i + 1, 2)] = laser2_s2[(i, 2)] - dx\n laser2_visible[i + 1] = 1\n if laser2_s2[(i + 1, 2)] < rocket1_s2[(i + 1, 2)]:\n rocket1_visible[i + 1] = 0\n\n laser2_visible = laser2_visible - (1 - rocket1_visible)\n ship_scale_s2 = 0.6\n lasers_scale_s2 = 25\n if print_positions:\n r1_s2_msg = [ 'x = %.2f km' % utils.AU_to_km(rocket1_s2[(i, 2)] - rocket1_s2[(0,\n 2)]) for i in range(N) ]\n r2_s2_msg = [ 'x = %.2f km' % utils.AU_to_km(rocket2_s2[(i, 2)] - rocket1_s2[(0,\n 2)]) for i in range(N) ]\n else:\n r1_s2_msg = None\n r2_s2_msg = None\n l1_s2_msg = None\n l2_s2_msg = None\n laser1_s2[:, 1] -= utils.km_to_AU(20)\n laser2_s2[:, 1] -= utils.km_to_AU(20)\n rocket1_s2[:, 2] -= moveback_dist\n rocket2_s2[:, 2] -= moveback_dist\n laser1_s2[:, 2] -= moveback_dist\n laser2_s2[:, 2] -= moveback_dist\n ball3_visible_s2 = np.copy(rocket2_visible)\n ball3_visible_s2[10:] = 0\n ball4_visible_s2 = np.copy(laser2_visible)\n ball3_pos_s2 = np.copy(rocket1_s2)\n ball4_pos_s2 = np.copy(rocket2_s2)\n ball3_pos_s2[:, 1] -= utils.km_to_AU(2)\n ball4_pos_s2[:, 1] -= utils.km_to_AU(2)\n middle_observer[:, 0] = rocket1_s2[:, 0]\n middle_observer[:, 2] = (rocket2_s2[:, 2] + rocket1_s2[:, 2]) / 2\n other_objects_s2 = [\n self._object_list('rocket1', 'Satellite', rocket1_s2, ship_scale_s2 * factor, [1, 1, 1], visible=rocket1_visible, msg_list=r1_s2_msg),\n self._object_list('rocket2', 'Satellite', rocket2_s2, ship_scale_s2 * factor, [1, 1, 1], visible=rocket2_visible, msg_list=r2_s2_msg, orient=[0, 0, 1]),\n self._object_list('death_star', 'Sphere01', middle_observer, 130 * factor, [1, 1, 1], visible=[1] * N, msg_list=['\\n\\nDeath Star'] * len(lasers_visible)),\n self._object_list('laser1', 'Laser', laser1_s2, lasers_scale_s2 * factor, [1, 1, 0], visible=rocket2_visible, msg_list=l1_s2_msg),\n self._object_list('laser2', 'Laser', laser2_s2, lasers_scale_s2 * factor, [1, 0, 0], visible=laser2_visible, msg_list=l2_s2_msg),\n self._object_list('Boom1', 'explosion', rocket1_s2, 10000 * factor, [1, 0.6, 0], visible=1 - rocket1_visible),\n self._object_list('Boom2', 'explosion', rocket2_s2, 10000 * factor, [1, 0.6, 0], visible=1 - rocket2_visible),\n self._object_list('Ball1', 'Sphere01', rocket1_s2, 50 * factor, [255, 255, 255], visible=1 - rocket1_visible),\n self._object_list('Ball2', 'Sphere01', rocket2_s2, 50 * factor, [255, 255, 255], visible=1 - rocket2_visible),\n self._object_list('ball3', 'Sphere01', ball3_pos_s2, 35 * factor, [255, 255, 255], visible=ball3_visible_s2),\n self._object_list('ball4', 'Sphere01', ball4_pos_s2, 55 * factor, [255, 255, 255], visible=ball4_visible_s2)]\n sat_messages_s2 = [ '\\nThe spacecrafts are moving relative to the planet with v = %.3fc' % (ref_frame_speed / const.c_AU_pr_s) for i in range(N) ]\n for i in range(N):\n sat_messages_s2[i] += '\\nPosition of event A: %f km. Time of event A: %f ms' % (0,\n 0)\n\n ruler_length = utils.AU_to_km(self._get_ruler_length(cam_dist_s2))\n ruler_start = -(ruler_length / 2.0 + utils.AU_to_km(rocket1_s2[(0, 2)]))\n ruler_end = ruler_length + ruler_start\n rulerUnit = 'km'\n dltax = abs(ruler_start) / 2.0\n fct = np.rint(ruler_length / dltax)\n ruler_end = ruler_start + dltax * fct\n ruler_s2 = [\n ruler_start, ruler_end, ticks_s2, rulerUnit, utils.AU_to_km(cam_dist_s2), self._ruler_height]\n self._write_to_xml(times_s2, cam_pos_s2, cam_dir_s2, planet_pos, other_objects_s2, field_of_view=70, ruler=ruler_s2, play_speed=0.5005, cheat_light_speed=True, planet_idx=planet_idx, up_vec=up_vec, laser_scale=0.2, filename=filename_2, camera_messages=sat_messages_s2, use_obj_scaling=1)\n for i in range(N):\n if 1 - rocket1_visible[i] == 1:\n explosion_1_t = times_s2[i]\n break\n\n if self._write_solutions:\n solution_name = 'Solutions_spaceship_duel.txt'\n solution_2A = open(os.path.join(self._solution_path, solution_name), 'w')\n solution_2A.write('Solutions to 2A.4\\n')\n solution_2A.write('\\n NOTE: None of these answers are relevant for the project!\\n')\n solution_2A.write('Quick jump to part 1, exercise 7:\\n')\n solution_2A.write(\"7) L' = 1200 km. The rest is given in the spaceship frame in mcast\\n\")\n solution_2A.write('10) tC = %f km = %f ms. xC = %f km\\n' % (utils.AU_to_km(spaceship_distance / np.sqrt(1.0 - (ref_frame_speed / const.c_AU_pr_s) ** 2)), utils.AU_to_m(spaceship_distance / np.sqrt(1.0 - (ref_frame_speed / const.c_AU_pr_s) ** 2)) / const.c_km_pr_s, utils.AU_to_km(spaceship_distance / np.sqrt(1.0 - (ref_frame_speed / const.c_AU_pr_s) ** 2) * ref_frame_speed / const.c_AU_pr_s)))\n solution_2A.write('12) L = %f km' % utils.AU_to_km(dist_between_rockets_s2))\n solution_2A.close()\n return\n\n def cosmic_pingpong(self, planet_idx, filename_1='cosmic_pingpong_frame_1.xml', filename_2='cosmic_pingpong_frame_2.xml', filename_3='cosmic_pingpong_frame_3.xml', number_of_video_frames=1000):\n \"\"\"Two spaceships are playing cosmic ping-pong with a laser beam.\n\n Generates the XML files used in Exercise 5 in Part 2A of the lecture notes and Exercise 2 in Part 8 of the project.\n\n Parameters\n ----------\n planet_idx : int\n Index of the planet above which the experiment takes place.\n filename_1 : str, optional\n The filename to use for frame of reference 1.\n filename_2 : str, optional\n The filename to use for frame of reference 2.\n filename_3 : str, optional\n The filename to use for frame of reference 3.\n number_of_video_frames : int, optional\n The number of video frames to use in the XML files.\n Can be reduced to reduce file size, but be aware that this might lead to errors.\n Default is 1000, but must be at least 100.\n \"\"\"\n planet_idx = int(planet_idx)\n if planet_idx < 0 or planet_idx >= self.system.number_of_planets:\n raise ValueError('Argument \"planet_idx\" is %d but must be in the range [0, %d].' % (planet_idx, self.system.number_of_planets - 1))\n N = int(number_of_video_frames)\n if N < 100:\n raise ValueError('Argument \"number_of_video_frames\" is %d but must be at least 100.' % N)\n filename_1 = str(filename_1)\n filename_2 = str(filename_2)\n filename_3 = str(filename_3)\n planet_radius = utils.km_to_AU(self.system.radii[planet_idx])\n events_radius = planet_radius * 1.5\n sat1_color = [1, 0, 0]\n sat2_color = [0, 0, 1]\n spacecraft_distance = 400\n distance_to_events = 400\n sat1_messages_satframe = [ '' for i in range(N) ]\n sat2_messages_satframe = [ '' for i in range(N) ]\n sat1_messages_planframe = [ '' for i in range(N) ]\n sat2_messages_planframe = [ '' for i in range(N) ]\n sat1_sounds_satframe = [ '' for i in range(N) ]\n sat2_sounds_satframe = [ '' for i in range(N) ]\n sat1_sounds_planframe = [ '' for i in range(N) ]\n sat2_sounds_planframe = [ '' for i in range(N) ]\n random_state = np.random.RandomState(self.seed + utils.get_seed('cosmic_pingpong'))\n sat_frame_speed = utils.km_to_AU(0.65 * const.c_km_pr_s)\n sat_frame_movement = utils.km_to_AU(np.linspace(0, 1400, N))\n global_messages = [\n 'Velocity of spacecrafts in planet frame = %f c\\n' % (sat_frame_speed / const.c_AU_pr_s)] * N\n sat1_pos_1D_satframe = np.zeros(N) - utils.km_to_AU(spacecraft_distance / 2.0)\n sat2_pos_1D_satframe = np.zeros(N) + utils.km_to_AU(spacecraft_distance / 2.0)\n cam_pos_1D_satframe = np.zeros(N)\n laser_pos_1D_satframe = np.zeros(shape=N)\n end_time = (sat_frame_movement[(-1)] - sat_frame_movement[0]) / sat_frame_speed\n time_array = np.linspace(0, end_time, N)\n dx = utils.km_to_AU((time_array[(-1)] - time_array[(-2)]) * const.c_km_pr_s)\n laser_pos_1D_satframe[0] = sat2_pos_1D_satframe[0]\n laser_moving_forward = False\n explvisible_satframe = np.copy(sat1_pos_1D_satframe)\n explvisible_satframe[:] = 0\n first_time_hit = 0\n sat2_messages_satframe[0:(int(N / 32))] = ['\\nEmitting!'] * int(N / 32)\n for i in range(N):\n global_messages[i] += 'Laser emitted at [%g ms, %g km]\\n' % (0, 0)\n\n for i in range(1, N):\n if laser_moving_forward:\n laser_pos_1D_satframe[i] = laser_pos_1D_satframe[(i - 1)] + dx\n else:\n laser_pos_1D_satframe[i] = laser_pos_1D_satframe[(i - 1)] - dx\n if laser_pos_1D_satframe[i] > sat2_pos_1D_satframe[i]:\n if self._debug:\n print('Laser bounced backwards at frame %d, [%es, %em] in spacecraft frame' % (i, time_array[i], laser_pos_1D_satframe[i]))\n for j in range(i, N):\n global_messages[j] += 'Laser bounced forwards at [%g ms, %g km]\\n' % (time_array[i] * 1000, 0)\n\n laser_moving_forward = False\n laser_pos_1D_satframe[i] -= abs(laser_pos_1D_satframe[i] - sat2_pos_1D_satframe[i])\n sat2_messages_satframe[i:(i + int(N / 32))] = [\n '\\nBounce!'] * int(N / 32)\n sat2_sounds_satframe[i] = 'laser'\n if laser_pos_1D_satframe[i] < sat1_pos_1D_satframe[i]:\n if self._debug:\n print('Laser bounced forwards at frame %d, [%es, %em] in spacecraft frame' % (i, time_array[i], laser_pos_1D_satframe[i]))\n for j in range(i, N):\n global_messages[j] += 'Laser bounced backwards at [%g ms, %g km]\\n' % (time_array[i] * 1000, spacecraft_distance)\n\n laser_moving_forward = True\n laser_pos_1D_satframe[i] += abs(laser_pos_1D_satframe[i] - sat1_pos_1D_satframe[i])\n sat1_messages_satframe[i:(i + int(N / 32))] = [\n '\\nBounce!'] * int(N / 32)\n if first_time_hit == 0:\n explvisible_satframe[i:(i + int(N / 32))] = 1\n first_time_hit = 1\n expltime_satframe = time_array[i]\n explpos_satframe = -sat_frame_movement[i]\n explind = i\n for j in range(i, N):\n global_messages[j] += 'Explosion at [%g ms, %g km]\\n' % (time_array[i] * 1000, utils.AU_to_km(sat_frame_movement[i]))\n\n sat1_sounds_satframe[i] = 'laser'\n\n cam_pos_satframe = np.zeros(shape=(N, 3))\n sat1_pos_satframe = np.zeros(shape=(N, 3))\n sat2_pos_satframe = np.zeros(shape=(N, 3))\n laser_pos_satframe = np.zeros(shape=(N, 3))\n cam_pos_satframe[:, 1] = cam_pos_1D_satframe + sat_frame_movement\n sat1_pos_satframe[:, 1] = sat1_pos_1D_satframe + sat_frame_movement\n sat2_pos_satframe[:, 1] = sat2_pos_1D_satframe + sat_frame_movement\n laser_pos_satframe[:, 1] = laser_pos_1D_satframe + sat_frame_movement\n cam_pos_satframe[:, 0] -= events_radius + utils.km_to_AU(1200)\n sat1_pos_satframe[:, 0] -= events_radius\n sat2_pos_satframe[:, 0] -= events_radius\n laser_pos_satframe[:, 0] -= events_radius + utils.km_to_AU(10)\n cam_pos_satframe[:, 0] -= utils.km_to_AU(distance_to_events)\n cam_dir = [\n 1, 0, 0]\n up_vec = [0, 0, 1]\n ruler_length = self._get_ruler_length(distance_to_events + 1200.0, field_of_view=70)\n ruler_start = -(ruler_length / 2.0 - utils.AU_to_km(abs(sat1_pos_satframe[(0,\n 1)] - sat2_pos_satframe[(0,\n 1)]) / 2.0))\n ruler_end = ruler_length + ruler_start\n rulerUnit = 'km'\n dltax = abs(ruler_start) / 5.0\n fct = np.rint(ruler_length / dltax)\n ruler_end = ruler_start + dltax * fct\n ticks_s2 = np.rint((ruler_end - ruler_start) / dltax)\n ruler = [\n ruler_start, ruler_end, ticks_s2, rulerUnit, distance_to_events + 1200.0, self._ruler_height]\n ball_pos_satframe = np.copy(sat2_pos_satframe)\n ball_pos_satframe[:, 1] = sat2_pos_satframe[(0, 1)]\n ball_pos_satframe[:, 0] += utils.km_to_AU(50)\n other_objects = [\n [\n 'lsr', 'Laser', laser_pos_satframe, 8, [1, 0, 0], None, None, None, None],\n [\n 'sat1', 'Satellite', sat1_pos_satframe, 0.1, sat1_color, sat1_messages_satframe, sat1_sounds_satframe, None, [0, -1, 0]],\n [\n 'sat2', 'Satellite', sat2_pos_satframe, 0.1, sat2_color, sat2_messages_satframe, sat2_sounds_satframe, None, [0, 1, 0]],\n [\n 'ball', 'Sphere01', ball_pos_satframe, 50, [1, 1, 1], None, None, None, [0, 1, 0]],\n [\n 'ball', 'explosion', ball_pos_satframe, 1000, [50, 50, 0], None, None, explvisible_satframe, [0, 1, 0]]]\n self._write_to_xml(time_array, cam_pos_satframe, cam_dir, other_objects=other_objects, planet_idx=planet_idx, up_vec=up_vec, laser_scale=0.1, ruler=ruler, filename=filename_1, play_speed=0.6, camera_messages=global_messages, field_of_view=70, cheat_light_speed=True)\n time_array_planframe1, sat1_pos_1D_planframe = self._lorentz_transform(time_array, sat1_pos_1D_satframe, -sat_frame_speed)\n time_array_planframe2, sat2_pos_1D_planframe = self._lorentz_transform(time_array, sat2_pos_1D_satframe, -sat_frame_speed)\n expltime_planframe, explpos_planframe = self._lorentz_transform(expltime_satframe, explpos_satframe, -sat_frame_speed)\n time_array_planframe = np.linspace(0, time_array_planframe1[(-1)] - time_array_planframe1[0], N)\n sat1_pos_1D_planframe = interpolate.interp1d(time_array_planframe1, sat1_pos_1D_planframe, kind='linear', bounds_error=False, fill_value='extrapolate', assume_sorted=True)(time_array_planframe)\n sat2_pos_1D_planframe = interpolate.interp1d(time_array_planframe2, sat2_pos_1D_planframe, kind='linear', bounds_error=False, fill_value='extrapolate', assume_sorted=True)(time_array_planframe)\n laser_pos_1D_planframe = np.zeros(shape=N)\n dx = utils.km_to_AU((time_array_planframe[(-1)] - time_array_planframe[(-2)]) * const.c_km_pr_s)\n laser_pos_1D_planframe[0] = sat2_pos_1D_planframe[0]\n laser_moving_forward = False\n sat2_messages_planframe[0:(int(N / 32))] = ['\\nStart position!'] * int(N / 32)\n bouncing_backwards_indexes = []\n bouncing_forward_indexes = []\n for i in range(1, N):\n if laser_moving_forward:\n laser_pos_1D_planframe[i] = laser_pos_1D_planframe[(i - 1)] + dx\n else:\n laser_pos_1D_planframe[i] = laser_pos_1D_planframe[(i - 1)] - dx\n if laser_pos_1D_planframe[i] > sat2_pos_1D_planframe[i]:\n if self._debug:\n print('Laser bounced backwards at frame %d, [%es, %em] in planet frame' % (i, time_array_planframe[i], laser_pos_1D_planframe[i]))\n laser_moving_forward = False\n laser_pos_1D_planframe[i] -= abs(laser_pos_1D_planframe[i] - sat2_pos_1D_planframe[i])\n sat2_messages_planframe[i:(i + int(N / 32))] = [\n '\\nBounce!'] * int(N / 32)\n sat2_sounds_planframe[i] = 'laser'\n bouncing_backwards_indexes.append(i)\n if laser_pos_1D_planframe[i] < sat1_pos_1D_planframe[i]:\n if self._debug:\n print('Laser bounced forwards at frame %d, [%es, %em] in planet frame' % (i, time_array_planframe[i], laser_pos_1D_planframe[i]))\n laser_moving_forward = True\n laser_pos_1D_planframe[i] += abs(laser_pos_1D_planframe[i] - sat1_pos_1D_planframe[i])\n sat1_messages_planframe[i:(i + int(N / 32))] = [\n '\\nBounce!'] * int(N / 32)\n sat1_sounds_planframe[i] = 'laser'\n bouncing_forward_indexes.append(i)\n\n cam_pos_planframe = np.zeros(shape=(N, 3))\n sat1_pos_planframe = np.zeros(shape=(N, 3))\n sat2_pos_planframe = np.zeros(shape=(N, 3))\n laser_pos_planframe = np.zeros(shape=(N, 3))\n sat1_pos_planframe[:, 1] = sat1_pos_1D_planframe\n sat2_pos_planframe[:, 1] = sat2_pos_1D_planframe\n laser_pos_planframe[:, 1] = laser_pos_1D_planframe\n cam_pos_planframe[:, 0] -= events_radius + utils.km_to_AU(1200) + utils.km_to_AU(distance_to_events)\n cam_pos_planframe[:, 2] += 0\n sat1_pos_planframe[:, 0] -= events_radius\n sat2_pos_planframe[:, 0] -= events_radius\n laser_pos_planframe[:, 0] -= events_radius + utils.km_to_AU(10)\n cam_dir_planframe = (sat1_pos_planframe + sat2_pos_planframe) / 2 - cam_pos_planframe\n cam_dir_planframe[:, 1] = cam_dir_planframe[(0, 1)]\n up_vec_planframe = [\n 0, 0, 1]\n ball_pos_planframe = np.copy(sat2_pos_planframe)\n ball_pos_planframe[:, 1] = sat2_pos_planframe[(0, 1)]\n ball_pos_planframe[:, 0] += utils.km_to_AU(50)\n explind_planframe = np.fabs(time_array_planframe - expltime_planframe).argmin()\n explvisible_planframe = np.copy(explvisible_satframe)\n explvisible_planframe[:] = 0\n explvisible_planframe[explind_planframe:(explind_planframe + int(N / 32))] = 1\n other_objects_planframe = [\n [\n 'lsr', 'Laser', laser_pos_planframe, 8, [1, 0, 0], None, None, None, None],\n [\n 'sat1', 'Satellite', sat1_pos_planframe, 0.1, sat1_color, sat1_messages_planframe, sat1_sounds_planframe, None, [0, -1, 0]],\n [\n 'sat2', 'Satellite', sat2_pos_planframe, 0.1, sat2_color, sat2_messages_planframe, sat2_sounds_planframe, None, [0, 1, 0]],\n [\n 'ball', 'Sphere01', ball_pos_planframe, 50, [1, 1, 1], None, None, None, [0, 1, 0]],\n [\n 'ball', 'explosion', ball_pos_planframe, 1000, [50, 50, 0], None, None, explvisible_planframe, [0, 1, 0]]]\n ruler_length = self._get_ruler_length(distance_to_events + 1200.0, field_of_view=70) * np.sqrt(1.0 - (sat_frame_speed / const.c_AU_pr_s) ** 2)\n ruler_start = -(ruler_length / 2.0 - utils.AU_to_km(abs(sat1_pos_planframe[(0,\n 1)] - sat2_pos_planframe[(0,\n 1)]) / 2.0))\n ruler_end = ruler_length + ruler_start\n rulerUnit = 'km'\n dltax = abs(ruler_start) / 7.0\n fct = np.rint(ruler_length / dltax)\n ruler_end = ruler_start + dltax * fct\n ticks_s2 = np.rint((ruler_end - ruler_start) / dltax)\n ruler = [\n ruler_start, ruler_end, ticks_s2, rulerUnit, distance_to_events + 1200.0, self._ruler_height]\n global_messages2 = ['Velocity of spacecrafts in planet frame = %f c\\n' % (sat_frame_speed / const.c_AU_pr_s)] * N\n self._write_to_xml(time_array_planframe, cam_pos_planframe, cam_dir_planframe, other_objects=other_objects_planframe, planet_idx=planet_idx, up_vec=up_vec_planframe, laser_scale=0.1, filename=filename_2, play_speed=0.6, camera_messages=global_messages2, field_of_view=70, ruler=ruler, cheat_light_speed=True)\n if self._write_solutions:\n solution_name = 'Solutions_cosmic_pingpong.txt'\n solution_2A = open(os.path.join(self._solution_path, solution_name), 'w')\n solution_2A.write('Solutions to 2A.5\\n')\n solution_2A.write('\\n')\n solution_2A.write('Quick jump to exercise 12:\\n')\n solution_2A.write('12) tC = %f ms\\n' % (time_array_planframe[explind_planframe] * 1000))\n solution_2A.write('13) tB = %f ms\\n' % (time_array_planframe[bouncing_forward_indexes[0]] * 1000))\n solution_2A.write('14) tD = %f ms\\n' % (time_array_planframe[bouncing_backwards_indexes[0]] * 1000))\n solution_2A.write('15) tB - tA = %f ms\\n' % (time_array_planframe[bouncing_forward_indexes[0]] * 1000))\n solution_2A.write('16) tD - tB = %f ms\\n' % abs(time_array_planframe[bouncing_forward_indexes[0]] * 1000 - time_array_planframe[bouncing_backwards_indexes[0]] * 1000))\n solution_2A.close()\n N = 2048\n time_array = np.linspace(0, 18, N) / 1000\n dt = time_array[1]\n ruler_length = self._get_ruler_length(distance_to_events + 1200.0, field_of_view=70)\n ruler_start = -(ruler_length / 2.0 - utils.AU_to_km(abs(sat1_pos_satframe[(0,\n 1)] - sat2_pos_satframe[(0,\n 1)]) / 2.0))\n ruler_end = ruler_length + ruler_start\n rulerUnit = 'km'\n dltax = abs(ruler_start) / 5.0\n fct = np.rint(ruler_length / dltax)\n ruler_end = ruler_start + dltax * fct\n ticks_s2 = np.rint((ruler_end - ruler_start) / dltax)\n ruler = [\n ruler_start, ruler_end, ticks_s2, rulerUnit, distance_to_events + 1200.0]\n dx_spaceship = 400\n start_pos = ruler_start + 200\n ships = np.zeros((2, N, 3))\n laser_pos = np.zeros((N, 3))\n laser_pos[0] = start_pos\n c_to_use = const.c_km_pr_s\n v_to_use = 0\n counter = 0\n ships[(0, 0, 1)] = start_pos\n ships[(1, 0, 1)] = start_pos + dx_spaceship\n global_messages = []\n message = 'Spaceships velocity 0c'\n global_messages += [message]\n sound_list = []\n sound_list += [0]\n variable = 0\n for i in range(1, N):\n if laser_pos[(i - 1, 1)] < ships[(0, i - 1, 1)]:\n c_to_use = const.c_km_pr_s\n sound_list += ['explosion']\n if variable < i - 5:\n counter += 1\n variable = i\n elif laser_pos[(i - 1, 1)] > ships[(1, i - 1, 1)]:\n c_to_use = -const.c_km_pr_s\n sound_list += ['explosion']\n else:\n sound_list += [0]\n if counter == 1:\n message = 'Spaceships velocity 0.3c'\n v_to_use = 0.3 * const.c_km_pr_s\n elif counter == 2:\n message = 'Spaceships velocity 0.6c'\n v_to_use = 0.6 * const.c_km_pr_s\n elif counter == 3:\n message = 'Spaceships velocity 0.8c'\n v_to_use = 0.8 * const.c_km_pr_s\n laser_pos[(i, 1)] = c_to_use * dt + laser_pos[(i - 1, 1)]\n ships[(0, i, 1)] = v_to_use * dt + ships[(0, i - 1, 1)]\n ships[(1, i, 1)] = v_to_use * dt + ships[(1, i - 1, 1)]\n global_messages += [message]\n\n laser_pos[:, 0] -= utils.AU_to_km(events_radius) + 10\n ships[:, :, 0] -= utils.AU_to_km(events_radius)\n ships[:, :, 1], laser_pos[:, 1] = -ships[:, :, 1], -laser_pos[:, 1]\n cam_pos_planframe = np.zeros(shape=(N, 3))\n cam_pos_planframe[:, 0] -= events_radius + utils.km_to_AU(1200) + utils.km_to_AU(distance_to_events)\n cam_pos_planframe[:, 2] += 0\n other_objects_planframe = [\n [\n 'lsr', 'Laser', utils.km_to_AU(laser_pos), 10, [1, 0, 0], None, None, None, None],\n [\n 'sat1', 'Satellite', utils.km_to_AU(ships[0]), 0.15, sat1_color, None, sound_list, None, [0, 1, 0]],\n [\n 'sat2', 'Satellite', utils.km_to_AU(ships[1]), 0.15, sat2_color, None, None, None, [0, -1, 0]]]\n self._write_to_xml(time_array, cam_pos_planframe, cam_dir_planframe[0], other_objects=other_objects_planframe, planet_idx=planet_idx, up_vec=up_vec_planframe, laser_scale=0.1, filename=filename_3, play_speed=0.6, camera_messages=global_messages, field_of_view=70, ruler=ruler, cheat_light_speed=True)\n return\n\n def more_lightning_strikes(self, planet_idx, increase_height=False, filename_1='more_lightning_strikes_frame_1.xml', filename_2='more_lightning_strikes_frame_2.xml', field_of_view=70, number_of_video_frames=1000):\n \"\"\"The unfortunate spaceship flying through the atmosphere is this time struck by a green, a pink, a blue and a yellow lightning bolt.\n\n Generates the XML files used in Exercise 6 in Part 2A of the lecture notes.\n\n Parameters\n ----------\n planet_idx : int\n Index of the planet above which the experiment takes place.\n increase_height : bool or float, optional\n Determines the height above the planet center where the experiment takes place.\n The default value (False) causes a predetermined height of 1.01 planet radii to be used. Using True increases this to 1.1.\n Optionally, a custom adjustment parameter between 0.5 and 5 can be provided.\n Try modifying this argument if the spaceships interfere with the surface of the planet.\n filename_1 : str, optional\n The filename to use for frame of reference 1.\n filename_2 : str, optional\n The filename to use for frame of reference 2.\n field_of_view : float, optional\n The field of view of the camera, in degrees.\n Default is 70.\n number_of_video_frames : int, optional\n The number of video frames to use in the XML files.\n Can be reduced to reduce file size, but be aware that this might lead to errors.\n Default is 1000, but must be at least 100.\n \"\"\"\n planet_idx = int(planet_idx)\n if planet_idx < 0 or planet_idx >= self.system.number_of_planets:\n raise ValueError('Argument \"planet_idx\" is %d but must be in the range [0, %d].' % (planet_idx, self.system.number_of_planets - 1))\n N = int(number_of_video_frames)\n if N < 100:\n raise ValueError('Argument \"number_of_video_frames\" is %d but must be at least 100.' % N)\n filename_1 = str(filename_1)\n filename_2 = str(filename_2)\n low_sat_speed = [\n 0.8, 0.84]\n high_sat_speed = [0.86, 0.9]\n factor = 1.7\n distance_to_events = utils.km_to_AU(1800.0)\n cam_dir = np.array([0, 0, -1])\n planet_radius = utils.km_to_AU(self.system.radii[planet_idx])\n if increase_height is False:\n event_radius = planet_radius * 1.01\n else:\n if increase_height is True:\n event_radius = planet_radius * 1.1\n else:\n if increase_height < 0.5 or increase_height > 5.0:\n print('Increase height needs to be True, False or between 0.5 and 5')\n raise ValueError('Increase_height invalid')\n if increase_height >= 1:\n event_radius = planet_radius * (1.005 + 0.005 * increase_height)\n else:\n event_radius = planet_radius * (1.005 - 0.005 * increase_height)\n random_seed = self.seed + utils.get_seed('more_lightning_strikes')\n random_state = np.random.RandomState(random_seed)\n v_cam_planframe = random_state.uniform(low_sat_speed[0], low_sat_speed[1])\n v_friend_planframe = random_state.uniform(high_sat_speed[0], high_sat_speed[1])\n v_friend_camframe = self._velocity_transformation(v_cam_planframe, v_friend_planframe)\n v_cam_planframe = v_cam_planframe * const.c_AU_pr_s\n v_friend_planframe = v_friend_planframe * const.c_AU_pr_s\n v_friend_camframe = v_friend_camframe * const.c_AU_pr_s\n if self._debug:\n print('Our velocity in planet frame = %gc\\nFriend velocity in planet frame = %gc\\nFriend velocity in our frame = %gc' % (v_cam_planframe, v_friend_planframe, v_friend_camframe))\n sat_movement_length_planframe = utils.km_to_AU(2000)\n end_time_planframe = sat_movement_length_planframe / max([v_cam_planframe, v_friend_planframe])\n time_array_planframe = np.linspace(0, end_time_planframe, N)\n cam_pos_1D_camframe = np.zeros(N)\n friend_pos_1D_camframe = np.linspace(0, end_time_planframe * v_friend_camframe, N)\n cam_pos_1D_planframe = np.linspace(0, end_time_planframe * v_cam_planframe, N)\n friend_pos_1D_planframe = np.linspace(0, end_time_planframe * v_friend_planframe, N)\n end_time_camframe, _ = self._lorentz_transform(time_array_planframe[(-1)], cam_pos_1D_planframe[(-1)], v_cam_planframe)\n end_time_friendframe, _ = self._lorentz_transform(time_array_planframe[(-1)], cam_pos_1D_planframe[(-1)], v_friend_planframe)\n time_array_camframe = np.linspace(0, end_time_camframe, N)\n time_array_friendframe = np.linspace(0, end_time_friendframe, N)\n planet_pos_1D_camframe = np.linspace(0, -end_time_planframe * v_cam_planframe, N)\n cam_pos = np.zeros(shape=(N, 3))\n cam_pos[:, 2] += distance_to_events\n friend_pos_camframe = np.zeros(shape=(N, 3))\n friend_pos_camframe[:, 1] = friend_pos_1D_camframe\n friend_pos_camframe[:, 2] -= distance_to_events\n cam_pos_camframe = np.zeros(shape=(N, 3))\n cam_pos_camframe[:, 1] = cam_pos_1D_camframe\n planet_pos_camframe = np.zeros(shape=(N, 3))\n planet_pos_camframe[:, 0] += event_radius\n planet_pos_camframe[:, 1] = planet_pos_1D_camframe\n ball1_pos_camframe = np.zeros(shape=(N, 3))\n ball1_visibility = np.zeros(shape=N)\n random_state.seed(random_seed)\n events_index_planframe = random_state.randint(N // 4, 3 * N // 4)\n events_time_planframe = time_array_planframe[events_index_planframe]\n avg_sat_pos_at_event = (cam_pos_1D_planframe[events_index_planframe] + friend_pos_1D_planframe[events_index_planframe]) / 2.0\n event1_pos_1D_planframe = avg_sat_pos_at_event + utils.km_to_AU(110)\n event2_pos_1D_planframe = cam_pos_1D_planframe[events_index_planframe]\n event1_time_camframe, event1_pos_1D_camframe = self._lorentz_transform(events_time_planframe, event1_pos_1D_planframe, v_cam_planframe)\n event2_time_camframe, event2_pos_1D_camframe = self._lorentz_transform(events_time_planframe, event2_pos_1D_planframe, v_cam_planframe)\n event1_time_friendframe, event1_pos_1D_friendframe = self._lorentz_transform(events_time_planframe, event1_pos_1D_planframe, v_friend_planframe)\n event2_time_friendframe, event2_pos_1D_friendframe = self._lorentz_transform(events_time_planframe, event2_pos_1D_planframe, v_friend_planframe)\n event1_index_camframe = np.abs(event1_time_camframe - time_array_planframe).argmin()\n event2_index_camframe = np.abs(event2_time_camframe - time_array_planframe).argmin()\n event1_visibility = np.zeros(shape=N)\n event2_visibility = np.zeros(shape=N)\n event1_visibility[event1_index_camframe:event1_index_camframe + N // 32] += 1\n event2_visibility[event2_index_camframe:event2_index_camframe + N // 32] += 1\n camera_messages = [ '' for i in range(N) ]\n event1_pos_camframe = np.zeros(shape=(N, 3))\n event2_pos_camframe = np.zeros(shape=(N, 3))\n event1_pos_camframe[:, 1] = event1_pos_1D_camframe\n event2_pos_camframe[:, 1] = event2_pos_1D_camframe\n event3_index_planframe = N // 8\n event4_index_planframe = 0\n event3_time_camframe = event1_time_camframe\n event3_index_camframe = event1_index_camframe\n event3_pos_1D_camframe = planet_pos_1D_camframe[event3_index_camframe]\n event3_time_planframe, event3_pos_1D_planframe = self._lorentz_transform(event3_time_camframe, event3_pos_1D_camframe, -v_cam_planframe)\n event3_index_planframe = np.abs(event3_time_planframe - time_array_planframe).argmin()\n event4_time_planframe = time_array_planframe[event4_index_planframe]\n avg_sat_pos_at_event4 = (cam_pos_1D_planframe[event4_index_planframe] + friend_pos_1D_planframe[event4_index_planframe]) / 2.0\n event4_pos_1D_planframe = 0\n event4_time_camframe, event4_pos_1D_camframe = self._lorentz_transform(event4_time_planframe, event4_pos_1D_planframe, v_cam_planframe)\n event4_index_camframe = np.abs(event4_time_camframe - time_array_planframe).argmin()\n event3_visibility = np.zeros(shape=N)\n event4_visibility = np.zeros(shape=N)\n event3_visibility[event3_index_camframe:event3_index_camframe + N // 32] += 1\n event4_visibility[event4_index_camframe:event4_index_camframe + N // 32] += 1\n event1_messages = [ '' for i in range(N) ]\n event2_messages = [ '' for i in range(N) ]\n event3_messages = [ '' for i in range(N) ]\n event4_messages = [ '' for i in range(N) ]\n event1_messages[event1_index_camframe:(event1_index_camframe + N // 32)] = [\n '\\n\\n Event P'] * (N // 32)\n event2_messages[event2_index_camframe:(event2_index_camframe + N // 32)] = ['\\n\\n Event B'] * (N // 32)\n event3_messages[event3_index_camframe:(event3_index_camframe + N // 32)] = ['\\n\\n Event Y'] * (N // 32)\n event4_messages[event4_index_camframe:(event4_index_camframe + N // 32)] = ['\\n\\n Event G'] * (N // 32)\n event3_pos_camframe = np.zeros(shape=(N, 3))\n event4_pos_camframe = np.zeros(shape=(N, 3))\n event3_pos_camframe[:, 1] = event3_pos_1D_camframe\n event4_pos_camframe[:, 1] = event4_pos_1D_camframe\n camera_messages = [ camera_messages[i] + 'Velocity of planet relative to our spacecraft frame = %fc' % (-v_cam_planframe / const.c_AU_pr_s) for i in range(N) ]\n for i in range(event4_index_camframe, N):\n camera_messages[i] += '\\nPosition of event G = %f km. Time of event G = %f ms' % (utils.AU_to_km(event4_pos_1D_camframe), event4_time_camframe * 1000)\n\n for i in range(event3_index_camframe, N):\n camera_messages[i] += '\\nPosition of event Y = %f km. Time of event Y = %f ms' % (utils.AU_to_km(event3_pos_1D_camframe), event3_time_camframe * 1000)\n\n for i in range(event1_index_camframe, N):\n camera_messages[i] += '\\nPosition of event P = %f km. Time of event P = %f ms' % (utils.AU_to_km(event1_pos_1D_camframe), event1_time_camframe * 1000)\n\n for i in range(event2_index_camframe, N):\n camera_messages[i] += '\\nPosition of event B = %f km. Time of event B = %f ms' % (utils.AU_to_km(event2_pos_1D_camframe), event2_time_camframe * 1000)\n\n ruler_length = utils.AU_to_km(self._get_ruler_length(distance_to_events, field_of_view=field_of_view))\n ruler = [\n -ruler_length / 5.0, ruler_length * 4.0 / 5.0, 20, 'km', utils.AU_to_km(distance_to_events), self._ruler_height]\n cam_pos[:, 1] = utils.km_to_AU(ruler_length) * 3.0 / 10.0\n planet_pos_camframe[:, 1] += utils.km_to_AU(ruler_length) * 3.0 / 10.0 * np.sqrt(1.0 - (v_cam_planframe / const.c_AU_pr_s) ** 2) / 2.0\n other_objects = [['Friend', 'Satellite', cam_pos_camframe, 0.08 * factor, [1, 1, 1], None, None, None, [0, -1, 0]],\n [\n 'Ball1', 'Sphere01', event1_pos_camframe, 5 * factor, [250, 250, 250], None, None, event1_visibility, None],\n [\n 'Ball2', 'Sphere01', event2_pos_camframe, 5 * factor, [250, 250, 250], None, None, event2_visibility, None],\n [\n 'Ball3', 'Sphere01', event3_pos_camframe, 5 * factor, [250, 250, 250], None, None, event3_visibility, None],\n [\n 'Ball4', 'Sphere01', event4_pos_camframe, 5 * factor, [250, 250, 250], None, None, event4_visibility, None],\n [\n 'Event1', 'explosion', event1_pos_camframe, 800 * factor, [5, 0, 5], event1_messages, None, event1_visibility, None],\n [\n 'Event2', 'explosion', event2_pos_camframe, 800 * factor, [0, 5, 5], event2_messages, None, event2_visibility, None],\n [\n 'Event3', 'explosion', event3_pos_camframe, 800 * factor, [5, 5, 0], event3_messages, None, event3_visibility, None],\n [\n 'Event4', 'explosion', event4_pos_camframe, 800 * factor, [0, 5, 0], event4_messages, None, event4_visibility, None]]\n self._write_to_xml(time_array_planframe, cam_pos, cam_dir, planet_pos_camframe, other_objects=other_objects, camera_messages=camera_messages, planet_idx=planet_idx, ruler=ruler, up_vec=[-1, 0, 0], filename=filename_1, play_speed=0.501, field_of_view=field_of_view)\n cam_pos_planframe = np.zeros(shape=(N, 3))\n cam_pos_planframe[:, 1] = cam_pos_1D_planframe\n event1_pos_planframe = np.zeros(shape=(N, 3))\n event2_pos_planframe = np.zeros(shape=(N, 3))\n event3_pos_planframe = np.zeros(shape=(N, 3))\n event4_pos_planframe = np.zeros(shape=(N, 3))\n event1_pos_planframe[:, 1] = event1_pos_1D_planframe\n event2_pos_planframe[:, 1] = event2_pos_1D_planframe\n event3_pos_planframe[:, 1] = event3_pos_1D_planframe\n event4_pos_planframe[:, 1] = event4_pos_1D_planframe\n event1_visibility = np.zeros(shape=N)\n event2_visibility = np.zeros(shape=N)\n event1_visibility[events_index_planframe:events_index_planframe + N // 32] += 1\n event2_visibility[events_index_planframe:events_index_planframe + N // 32] += 1\n camera_messages = [ '' for i in range(N) ]\n event1_messages = [ '' for i in range(N) ]\n event2_messages = [ '' for i in range(N) ]\n event3_visibility = np.zeros(shape=N)\n event4_visibility = np.zeros(shape=N)\n event3_visibility[event3_index_planframe:event3_index_planframe + N // 32] += 1\n event4_visibility[event4_index_planframe:event4_index_planframe + N // 32] += 1\n event3_messages = [ '' for i in range(N) ]\n event4_messages = [ '' for i in range(N) ]\n event1_messages[events_index_planframe:(events_index_planframe + N // 32)] = [\n '\\n\\n Event P'] * (N // 32)\n event2_messages[events_index_planframe:(events_index_planframe + N // 32)] = ['\\n\\n Event B'] * (N // 32)\n event3_messages[event3_index_planframe:(event3_index_planframe + N // 32)] = ['\\n\\n Event Y'] * (N // 32)\n event4_messages[event4_index_planframe:(event4_index_planframe + N // 32)] = ['\\n\\n Event G'] * (N // 32)\n ruler_length = utils.AU_to_km(self._get_ruler_length(distance_to_events, field_of_view=field_of_view))\n ruler = [-ruler_length / 5.0, ruler_length * 4.0 / 5.0, 20, 'km', utils.AU_to_km(distance_to_events), self._ruler_height]\n cam_pos[:, 1] = utils.km_to_AU(ruler_length) * 3.0 / 10.0\n planet_pos_camframe[:, 1] = 0\n camera_messages = [ camera_messages[i] + 'Velocity of spacecraft relative to planet frame = %fc' % (v_cam_planframe / const.c_AU_pr_s) for i in range(N) ]\n for i in range(event4_index_planframe, N):\n camera_messages[i] += '\\nPosition of event G = %f km. Time of event G = %f ms' % (utils.AU_to_km(event4_pos_1D_planframe), event4_time_planframe * 1000)\n\n for i in range(event3_index_planframe, N):\n camera_messages[i] += '\\nPosition of event Y = %f km. Time of event Y = %f ms' % (0, event3_time_planframe * 1000)\n\n for i in range(events_index_planframe, N):\n camera_messages[i] += '\\nPosition of event B = %f km. Time of event B = %f ms' % (utils.AU_to_km(event2_pos_1D_planframe), events_time_planframe * 1000)\n\n for i in range(events_index_planframe, N):\n camera_messages[i] += '\\nPosition of event P = %f km. Time of event P = %f ms' % (utils.AU_to_km(event1_pos_1D_planframe), events_time_planframe * 1000)\n\n other_objects = [\n [\n 'Friend', 'Satellite', cam_pos_planframe, 0.08 * factor, [1, 1, 1], None, None, None, [0, -1, 0]],\n [\n 'Ball1', 'Sphere01', event1_pos_planframe, 5 * factor, [200, 200, 200], None, None, event1_visibility, None],\n [\n 'Ball2', 'Sphere01', event2_pos_planframe, 5 * factor, [200, 200, 200], None, None, event2_visibility, None],\n [\n 'Ball3', 'Sphere01', event3_pos_planframe, 5 * factor, [200, 200, 200], None, None, event3_visibility, None],\n [\n 'Ball4', 'Sphere01', event4_pos_planframe, 5 * factor, [200, 200, 200], None, None, event4_visibility, None],\n [\n 'Event1', 'explosion', event1_pos_planframe, 800 * factor, [5, 0, 5], event1_messages, None, event1_visibility, None],\n [\n 'Event2', 'explosion', event2_pos_planframe, 800 * factor, [0, 5, 5], event2_messages, None, event2_visibility, None],\n [\n 'Event3', 'explosion', event3_pos_planframe, 800 * factor, [5, 5, 0], event3_messages, None, event3_visibility, None],\n [\n 'Event4', 'explosion', event4_pos_planframe, 800 * factor, [0, 5, 0], event4_messages, None, event4_visibility, None]]\n self._write_to_xml(time_array_planframe, cam_pos, cam_dir, planet_pos_camframe, other_objects=other_objects, camera_messages=camera_messages, planet_idx=planet_idx, ruler=ruler, up_vec=[-1, 0, 0], filename=filename_2, play_speed=0.501, field_of_view=field_of_view)\n if self._write_solutions:\n solution_name = 'Solutions_more_lightning_strikes.txt'\n solution_2A = open(os.path.join(self._solution_path, solution_name), 'w')\n solution_2A.write('Solutions to 2A.6\\n')\n solution_2A.write('\\n')\n solution_2A.write('Answers for planet frame:\\n')\n solution_2A.write(\"3a) Time of event B: tB' = %f ms\\n\" % (event2_time_camframe * 1000))\n solution_2A.write(\"3c) Time of event P: tP' = %f ms\\n\" % (event1_time_camframe * 1000))\n solution_2A.write(\"3d) Position of event P: xP' = %f km\\n\" % utils.AU_to_km(event1_pos_1D_camframe))\n solution_2A.write('\\n')\n solution_2A.write('Answers for spaceship frame:\\n')\n solution_2A.write('2a) Time of event Y: tY = %f ms\\n' % (event3_time_planframe * 1000))\n solution_2A.write('2c) Time of event P: tP = %f ms\\n' % (events_time_planframe * 1000))\n solution_2A.write('2d) Position of event P: xP = %f km\\n' % utils.AU_to_km(event1_pos_1D_planframe))\n solution_2A.close()\n return\n\n def twin_paradox(self, planet_idx, filename_1='twin_paradox_frame_1.xml', filename_2='twin_paradox_frame_2.xml', filename_3='twin_paradox_frame_3.xml', number_of_video_frames=1500):\n \"\"\"An astronaut is traveling at close to the speed of light to a distant planet and back again, while an observer remains at the home planet.\n\n Generates the XML files used in Exercise 8 in Part 2A of the lecture notes.\n\n Parameters\n ----------\n planet_idx : int\n Index of the planet above which the experiment takes place.\n filename_1 : str, optional\n The filename to use for frame of reference 1.\n filename_2 : str, optional\n The filename to use for frame of reference 2.\n filename_3 : str, optional\n The filename to use for frame of reference 3.\n number_of_video_frames : int, optional\n The number of video frames to use in the XML files.\n Can be reduced to reduce file size, but be aware that this might lead to errors.\n Default is 1500, but must be at least 100.\n \"\"\"\n planet_idx = int(planet_idx)\n if planet_idx < 0 or planet_idx >= self.system.number_of_planets:\n raise ValueError('Argument \"planet_idx\" is %d but must be in the range [0, %d].' % (planet_idx, self.system.number_of_planets - 1))\n N = int(number_of_video_frames)\n if N < 100:\n raise ValueError('Argument \"number_of_video_frames\" is %d but must be at least 100.' % N)\n filename_1 = str(filename_1)\n filename_2 = str(filename_2)\n filename_3 = str(filename_3)\n self._twin_paradox_single_frame(planet_idx, 0, filename_1, N)\n self._twin_paradox_single_frame(planet_idx, 1, filename_2, N)\n self._twin_paradox_single_frame(planet_idx, 2, filename_3, N)\n\n def _twin_paradox_single_frame(self, planet_idx, reference_system, filename, N):\n \"\"\"\n @ filenames = output xml filename for given frame\n @ reference_system = 0, 1 or 2\n\n \"\"\"\n radius = self.system.radii[planet_idx]\n dt = 2e-05\n planet_pos0 = np.array((0, utils.AU_to_km(1), 0))\n planet_pos = np.zeros((N, 3))\n planet2_pos = np.zeros((N, 3))\n planet3_pos = np.zeros((N, 3))\n vel = np.array([0.0, 0.0, 0.99 * const.c_km_pr_s])\n cam_pos = np.zeros((N, 3))\n cam_dir = np.zeros((N, 3))\n time_planframe = np.zeros(N)\n cam_dist = 5000\n distance_to_planet = 6307200000.0 * const.c_km_pr_s\n time_of_arrival = 2 * distance_to_planet / vel[2]\n ruler_length = self._get_ruler_length(cam_dist)\n nships = np.ceil(distance_to_planet * 2.0 / ruler_length) * 4\n dist_between_ships = distance_to_planet * 2.0 / nships\n nships = int(np.ceil(ruler_length / dist_between_ships)) * 6\n ships = np.zeros((nships, N, 3))\n ships_visibility = np.ones((nships, N))\n ships2 = np.copy(ships)\n ships2_visibility = np.copy(ships_visibility)\n ypos = 0.0\n dist_above_surf = -1.5 * radius\n ship1 = np.zeros((N, 3))\n ship2 = np.zeros((N, 3))\n ship1_visibility = np.ones(N)\n ship2_visibility = np.ones(N)\n n_dec_t = 3\n delta_t = N / 2 * dt\n ball_pos = np.zeros((N, 3))\n ball_visibility = np.zeros(N)\n if reference_system == 0:\n N *= 2\n N = int(N)\n planet_pos = np.zeros((N, 3))\n planet2_pos = np.zeros((N, 3))\n planet3_pos = np.zeros((N, 3))\n cam_pos = np.zeros((N, 3))\n cam_dir = np.zeros((N, 3))\n time_planframe = np.zeros(N)\n ships = np.zeros((nships, N, 3))\n ships_visibility = np.ones((nships, N))\n ships2 = np.copy(ships)\n ships2_visibility = np.copy(ships_visibility)\n ship1 = np.zeros((N, 3))\n ship2 = np.zeros((N, 3))\n ship1_visibility = np.zeros(N)\n ship2_visibility = np.ones(N)\n ball_pos = np.zeros((N, 3))\n ball_visibility = np.zeros(N)\n for i in range(N):\n planet3_pos[i, :] = [0, 0, dist_between_ships * 1000000.0]\n\n gamma1 = 1.0 / np.sqrt(1.0 - (vel[2] / const.c_km_pr_s) ** 2)\n for i in range(nships):\n ypos = ypos - dist_between_ships\n if ypos < -ruler_length / 2.0:\n break\n\n shp = 0\n ypos = ypos + dist_between_ships\n for i in range(nships):\n ships[shp, 0, :] = np.array((ruler_length / 8.0, dist_above_surf, ypos))\n ypos = ypos + dist_between_ships\n shp = shp + 1\n\n cam_pos[0, :] = np.array((0, dist_above_surf - cam_dist, 0))\n cam_dir[0, :] = np.array((0, dist_above_surf, 0)) - cam_pos[0, :]\n time_array = np.linspace(0, dt * N, N)\n real_time = np.copy(time_array)\n real_time[int(N / 4):int(N / 2)] += time_of_arrival / 2.0 / gamma1 ** 2 - int(3 * N / 8) * dt\n real_time[int(N / 2):int(3 * N / 4)] += time_of_arrival - time_of_arrival / 2.0 / gamma1 ** 2 - int(7 * N / 8) * dt\n real_time[int(3 * N / 4):N - 1] += time_of_arrival - 2 * delta_t\n for i in range(1, N):\n cam_pos[i, :] = cam_pos[0, :]\n cam_dir[i, :] = cam_dir[0, :]\n for shp in range(nships):\n ships[shp, i, :] = ships[shp, i - 1, :] + vel * dt\n ships_visibility[:, i] = ships_visibility[:, i - 1]\n\n for shp in range(nships):\n if ships[(shp, i, 2)] > ruler_length / 2.0:\n ships_visibility[(shp, i)] = 0\n if ships[(shp, i - 1, 2)] < -ruler_length / 2.0 + dist_between_ships and ships[(shp, i, 2)] >= -ruler_length / 2.0 + dist_between_ships:\n vshp = shp - 1\n if vshp < 0:\n vshp = nships - 1\n ships_visibility[(vshp, i)] = 1\n ships[vshp, i, :] = np.array((ruler_length / 8.0, dist_above_surf, -ruler_length / 2.0))\n\n ballshp = np.argmin(np.abs(ships[:, int(3 * N / 8), 2]))\n ball_pos = np.copy(ships[ballshp, :, :])\n ball_pos[:, 1] += 50\n ball_visibility[(int(3 * N / 8) - 50):(int(3 * N / 8) + 50)] = 1\n ypos = 0.0\n for i in range(nships):\n ypos = ypos + dist_between_ships\n if ypos > ruler_length / 2.0:\n break\n\n shp = 0\n ypos = ypos - dist_between_ships\n for i in range(nships):\n ships2[shp, -1, :] = np.array((-ruler_length / 8.0, dist_above_surf, ypos))\n ypos = ypos - dist_between_ships\n shp = shp + 1\n\n for i in range(N - 2, -1, -1):\n for shp in range(nships):\n ships2[shp, i, :] = ships2[shp, i + 1, :] + vel * dt\n ships2_visibility[:, i] = ships2_visibility[:, i + 1]\n\n for shp in range(nships):\n if ships2[(shp, i, 2)] > ruler_length / 2.0:\n ships2_visibility[(shp, i)] = 0\n if ships2[(shp, i + 1, 2)] < -ruler_length / 2.0 + dist_between_ships and ships2[(shp, i, 2)] >= -ruler_length / 2.0 + dist_between_ships:\n vshp = shp + 1\n if vshp == nships:\n vshp = 0\n ships2_visibility[(vshp, i)] = 1\n ships2[vshp, i, :] = np.array((-ruler_length / 8.0, dist_above_surf, -ruler_length / 2.0))\n\n ballshp = np.argmin(np.abs(ships2[:, int(5 * N / 8), 2]))\n ball_pos[int(3 * N / 8) + 50:N, :] = np.copy(ships2[ballshp, int(3 * N / 8) + 50:N, :])\n ball_visibility[(int(5 * N / 8) - 50):(int(5 * N / 8) + 50)] = 1\n shp = np.argmin(np.abs(ships[:, 0, 2]))\n ship1 = np.copy(ships[shp, :, :])\n ship1_visibility[0:(int(4 * dist_between_ships / vel[2] / dt))] = 1\n ships_visibility[shp, 0:int(4 * dist_between_ships / vel[2] / dt)] = 0\n arrivalship = np.argmin(np.abs(ships2[:, -1, 2]))\n ship2 = np.copy(ships2[arrivalship, :, :])\n ship2_visibility[(N - int(4 * dist_between_ships / vel[2] / dt)):(N - 1)] = 1\n ships2_visibility[arrivalship, N - int(4 * dist_between_ships / vel[2] / dt):N - 1] = 0\n else:\n if reference_system == 1:\n for i in range(N):\n planet3_pos[i, :] = [0, 0, dist_between_ships * 1000000.0]\n\n ship1 = np.zeros((N, 3))\n ship2 = np.zeros((N, 3))\n ship2_visibility = np.zeros(N)\n ship1_visibility = np.ones(N)\n gamma1 = 1.0 / np.sqrt(1.0 - (vel[2] / const.c_km_pr_s) ** 2)\n dist_between_ships = dist_between_ships * gamma1\n dt = dt * gamma1\n delta_t = int(N / 2) * dt\n for i in range(1, N):\n planet_pos[i, :] = planet_pos[i - 1, :] - vel * dt\n\n planet2_pos[N - 1, :] = np.array([0, 0, 0])\n for i in range(N - 2, N - 500, -1):\n planet2_pos[i, :] = planet2_pos[i + 1, :] + vel * dt\n\n planet2_pos[0:(N - 500)] = np.array([0, 0, -dist_between_ships * 1000000.0])\n for i in range(N - 30, N):\n ball_pos[i, :] = np.array((ruler_length / 8.0 - (i - N + 30) * ruler_length / 4.0 / 29.0, dist_above_surf, 0))\n ball_visibility[i] = 1\n\n ball_visibility[(N - 2):N] = 0\n vel[2] = 2.0 * vel[2] / (1.0 + (vel[2] / const.c_km_pr_s) ** 2)\n gamma2 = 1.0 / np.sqrt(1.0 - (vel[2] / const.c_km_pr_s) ** 2)\n for i in range(nships):\n ypos = ypos - dist_between_ships\n if ypos < -ruler_length / 2.0:\n break\n\n shp = 0\n ypos = ypos + dist_between_ships\n for i in range(nships):\n for j in range(N):\n ships[shp, j, :] = np.array((ruler_length / 8.0, dist_above_surf, ypos))\n\n ypos = ypos + dist_between_ships\n shp = shp + 1\n\n cam_pos[0, :] = np.array((0, dist_above_surf - cam_dist, 0))\n cam_dir[0, :] = np.array((0, dist_above_surf, 0)) - cam_pos[0, :]\n time_array = np.linspace(0, dt * N, N)\n real_time = np.copy(time_array)\n real_time[int(N / 2):N - 1] += time_of_arrival / 2.0 / gamma1 - 2 * delta_t\n for i in range(1, N):\n cam_pos[i, :] = cam_pos[0, :]\n cam_dir[i, :] = cam_dir[0, :]\n\n dist_between_ships = dist_between_ships / gamma1 ** 2\n ypos = 0.0\n for i in range(nships):\n ypos = ypos + dist_between_ships\n if ypos > ruler_length / 2.0:\n break\n\n shp = 0\n ypos = ypos - dist_between_ships\n for i in range(nships):\n ships2[shp, -1, :] = np.array((-ruler_length / 8.0, dist_above_surf, ypos))\n ypos = ypos - dist_between_ships\n shp = shp + 1\n\n for i in range(N - 2, -1, -1):\n for shp in range(nships):\n ships2[shp, i, :] = ships2[shp, i + 1, :] + vel * dt\n ships2_visibility[:, i] = ships2_visibility[:, i + 1]\n\n for shp in range(nships):\n if ships2[(shp, i, 2)] > ruler_length / 2.0:\n ships2_visibility[(shp, i)] = 0\n if ships2[(shp, i + 1, 2)] < -ruler_length / 2.0 + dist_between_ships and ships2[(shp, i, 2)] >= -ruler_length / 2.0 + dist_between_ships:\n vshp = shp + 1\n if vshp == nships:\n vshp = 0\n ships2_visibility[(vshp, i)] = 1\n ships2[vshp, i, :] = np.array((-ruler_length / 8.0, dist_above_surf, -ruler_length / 2.0))\n\n ships_visibility[:, int(N / 2) - 100:int(N / 2)] = 0\n ships2_visibility[:, int(N / 2) - 100:int(N / 2)] = 0\n arrivalship = np.argmin(np.abs(ships[:, 0, 2]))\n ship1 = np.copy(ships[arrivalship, :, :])\n ships_visibility[arrivalship, :] = 0\n arrivalship = np.argmin(np.abs(ships2[:, -1, 2]))\n ship2 = np.copy(ships2[arrivalship, :, :])\n ship2_visibility[(N - int(10 * dist_between_ships / vel[2] / dt)):(N - 1)] = 1\n ships2_visibility[arrivalship, N - int(10 * dist_between_ships / vel[2] / dt):N - 1] = 0\n elif reference_system == 2:\n N *= 1.5\n N = int(N)\n planet_pos = np.zeros((N, 3))\n planet2_pos = np.zeros((N, 3))\n planet3_pos = np.zeros((N, 3))\n cam_pos = np.zeros((N, 3))\n cam_dir = np.zeros((N, 3))\n time_planframe = np.zeros(N)\n ships = np.zeros((nships, N, 3))\n ships_visibility = np.ones((nships, N))\n ships2 = np.copy(ships)\n ships2_visibility = np.copy(ships_visibility)\n ship1 = np.zeros((N, 3))\n ship2 = np.zeros((N, 3))\n ship1_visibility = np.zeros(N)\n ship2_visibility = np.ones(N)\n ball_pos = np.zeros((N, 3))\n ball_visibility = np.zeros(N)\n gamma1 = 1.0 / np.sqrt(1.0 - (vel[2] / const.c_km_pr_s) ** 2)\n dist_between_ships = dist_between_ships * gamma1\n dt = dt * gamma1\n planet_delta = 400\n for i in range(1, N):\n planet3_pos[i, :] = planet3_pos[i - 1, :] + vel * dt\n if i > int(N / 2) - planet_delta:\n planet3_pos[i, :] = [\n 0, 0, dist_between_ships * 1000000.0]\n\n planet2_pos[int(N / 2) - planet_delta, :] = np.array([0, 0, -ruler_length * 4.0 / 3.0])\n for i in range(int(N / 2) - planet_delta + 1, int(N / 2) + planet_delta):\n planet2_pos[i, :] = planet2_pos[i - 1, :] + vel * dt\n\n for i in itertools.chain(range(0, int(N / 2) - planet_delta + 1), range(int(N / 2) + planet_delta, N)):\n planet2_pos[i, :] = [\n 0, 0, dist_between_ships * 1000000.0]\n\n planet_middle_index = np.argmin(np.abs(planet2_pos[int(N / 2) - planet_delta:int(N / 2) + planet_delta, 2])) + int(N / 2) - planet_delta\n planet_pos[N - 1, :] = np.array([0, 0, 0])\n for i in range(N - 2, int(2 * N / 3), -1):\n planet_pos[i, :] = planet_pos[i + 1, :] - vel * dt\n\n for i in range(0, int(2 * N / 3)):\n planet_pos[i, :] = [\n 0, 0, dist_between_ships * 1000000.0]\n\n i1 = planet_middle_index - 20\n i2 = planet_middle_index + 20\n for i in range(i1, i2):\n ball_pos[i, :] = np.array((ruler_length / 8.0 - (i - i1) * ruler_length / 4.0 / (i2 - i1), dist_above_surf, 0))\n ball_visibility[i] = 1\n\n ball_visibility[-1] = 0\n vel[2] = 2.0 * vel[2] / (1.0 + (vel[2] / const.c_km_pr_s) ** 2)\n gamma2 = 1.0 / np.sqrt(1.0 - (vel[2] / const.c_km_pr_s) ** 2)\n for i in range(nships):\n ypos = ypos - dist_between_ships\n if ypos < -ruler_length / 2.0:\n break\n\n shp = 0\n ypos = ypos + dist_between_ships\n for i in range(nships):\n for j in range(N):\n ships2[shp, j, :] = np.array((-ruler_length / 8.0, dist_above_surf, ypos))\n\n ypos = ypos + dist_between_ships\n shp = shp + 1\n\n cam_pos[0, :] = np.array((0, dist_above_surf - cam_dist, 0))\n cam_dir[0, :] = np.array((0, dist_above_surf, 0)) - cam_pos[0, :]\n time_array = np.linspace(0, dt * N, N)\n real_time = np.copy(time_array)\n real_time[planet_middle_index - planet_delta:planet_middle_index + planet_delta] += time_of_arrival / 2.0 / gamma1 - planet_middle_index * dt\n real_time[planet_middle_index + planet_delta:N - 1] += time_of_arrival / gamma1 - N * dt\n for i in range(1, N):\n cam_pos[i, :] = cam_pos[0, :]\n cam_dir[i, :] = cam_dir[0, :]\n\n dist_between_ships = dist_between_ships / gamma1 ** 2\n ypos = 0.0\n for i in range(nships):\n ypos = ypos - dist_between_ships\n if ypos < -ruler_length / 2.0:\n break\n\n shp = 0\n ypos = ypos + dist_between_ships\n for i in range(nships):\n ships[shp, 0, :] = np.array((ruler_length / 8.0, dist_above_surf, ypos))\n ypos = ypos + dist_between_ships\n shp = shp + 1\n\n for i in range(1, N):\n for shp in range(nships):\n ships[shp, i, :] = ships[shp, i - 1, :] + vel * dt\n ships_visibility[:, i] = ships_visibility[:, i - 1]\n\n for shp in range(nships):\n if ships[(shp, i, 2)] > ruler_length / 2.0:\n ships_visibility[(shp, i)] = 0\n if ships[(shp, i - 1, 2)] < -ruler_length / 2.0 + dist_between_ships and ships[(shp, i, 2)] >= -ruler_length / 2.0 + dist_between_ships:\n vshp = shp - 1\n if vshp < 0:\n vshp = nships - 1\n ships_visibility[(vshp, i)] = 1\n ships[vshp, i, :] = np.array((ruler_length / 8.0, dist_above_surf, -ruler_length / 2.0))\n\n arrivalship = np.argmin(np.abs(ships2[:, 0, 2]))\n ship2 = np.copy(ships2[arrivalship, :, :])\n ships2_visibility[arrivalship, :] = 0\n shp = np.argmin(np.abs(ships[:, planet_middle_index, 2]))\n ship1 = np.copy(ships[shp, :, :])\n ship1_visibility[(planet_middle_index - int(10 * dist_between_ships / vel[2] / dt)):(planet_middle_index + int(10 * dist_between_ships / vel[2] / dt))] = 1\n ships_visibility[shp, planet_middle_index - int(10 * dist_between_ships / vel[2] / dt):planet_middle_index + int(10 * dist_between_ships / vel[2] / dt)] = 0\n km_to_AU = 1000.0 / const.AU\n planet_pos *= km_to_AU\n planet2_pos *= km_to_AU\n planet3_pos *= km_to_AU\n ships *= km_to_AU\n ships2 *= km_to_AU\n ship1 *= km_to_AU\n ship2 *= km_to_AU\n cam_pos *= km_to_AU\n cam_dir *= km_to_AU\n ball_pos *= km_to_AU\n camera_messages = [ 't = %.16f yr (Real time)' % (real_time[i] / 3600.0 / 24.0 / 365.0) for i in range(N) ]\n if reference_system == 0:\n for i in itertools.chain(range(int(N / 4) - 100, int(N / 4)), range(int(N / 2) - 100, int(N / 2)), range(int(3 * N / 4) - 100, int(3 * N / 4))):\n camera_messages[i] = '\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n ****************FAST FORWARD IN TIME...FAST FORWARD IN TIME...FAST FORWARD IN TIME...FAST FORWARD IN TIME...FAST FORWARD IN TIME...*****************************'\n ships_visibility[:, i] = 0\n ships2_visibility[:, i] = 0\n ship1_visibility[i] = 0\n ship2_visibility[i] = 0\n\n elif reference_system == 1:\n for i in range(int(N / 2) - 100, int(N / 2)):\n camera_messages[i] = '\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n ****************FAST FORWARD IN TIME...FAST FORWARD IN TIME...FAST FORWARD IN TIME...FAST FORWARD IN TIME...FAST FORWARD IN TIME...*****************************'\n ships_visibility[:, i] = 0\n ships2_visibility[:, i] = 0\n ship1_visibility[i] = 0\n ship2_visibility[i] = 0\n\n elif reference_system == 2:\n for i in itertools.chain(range(planet_middle_index - planet_delta - 50, planet_middle_index - planet_delta + 50), range(planet_middle_index + planet_delta - 50, planet_middle_index + planet_delta + 50)):\n camera_messages[i] = '\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n ****************FAST FORWARD IN TIME...FAST FORWARD IN TIME...FAST FORWARD IN TIME...FAST FORWARD IN TIME...FAST FORWARD IN TIME...*****************************'\n ships_visibility[:, i] = 0\n ships2_visibility[:, i] = 0\n ship1_visibility[i] = 0\n ship2_visibility[i] = 0\n\n other_objects = []\n for shp in range(nships):\n message = []\n for i in range(N):\n message.append('')\n\n other_objects.append(['satellite', 'satellite', ships[shp, :, :], 1.0, [1, 1, 1], message, None, ships_visibility[shp, :], [0, 0, 1]])\n other_objects.append(['satellite', 'satellite', ships2[shp, :, :], 1.0, [1, 1, 1], message, None, ships2_visibility[shp, :], [0, 0, -1]])\n\n other_objects.append(['ship1', 'satellite', ship1, 1.0, [10, 10, 0], message, None, ship1_visibility, [0, 0, 1]])\n other_objects.append(['ship2', 'satellite', ship2, 1.0, [10, 0, 0], message, None, ship2_visibility, [0, 0, 1]])\n if reference_system == 0:\n other_objects.append(['ball', 'Sphere01', ball_pos, 150.0, [0, 100, 250], message, None, ball_visibility, [0, 0, 1]])\n else:\n other_objects.append(['ball', 'Sphere01', ball_pos, 150.0, [1, 1, 1], message, None, ball_visibility, [0, 0, 1]])\n self._write_to_xml(time_array, cam_pos, cam_dir, planet_pos, other_objects, planet2_pos=planet2_pos, planet3_pos=planet3_pos, planet_idx=planet_idx, chosen_planet3=3, filename=filename, cheat_light_speed=True, use_obj_scaling=1, camera_messages=camera_messages, toggle_clock=False)\n return\n\n def spaceship_race(self, planet_idx, filename_1='spaceship_race_frame_1.xml', filename_2='spaceship_race_frame_2.xml', filename_3='spaceship_race_frame_3.xml', number_of_video_frames=1500):\n \"\"\"Three spaceships are traveling with different velocities with respect to a space station.\n\n Generates the XML files used in Exercise 1 in Part 2B of the lecture notes and Exercise 4 in Part 8 of the project.\n\n Parameters\n ----------\n planet_idx : int\n Index of the planet above which the experiment takes place.\n filename_1 : str, optional\n The filename to use for frame of reference 1.\n filename_2 : str, optional\n The filename to use for frame of reference 2.\n filename_3 : str, optional\n The filename to use for frame of reference 3.\n number_of_video_frames : int, optional\n The number of video frames to use in the XML files.\n Can be reduced to reduce file size, but be aware that this might lead to errors.\n Default is 1500, but must be at least 100.\n \"\"\"\n planet_idx = int(planet_idx)\n if planet_idx < 0 or planet_idx >= self.system.number_of_planets:\n raise ValueError('Argument \"planet_idx\" is %d but must be in the range [0, %d].' % (planet_idx, self.system.number_of_planets - 1))\n N = int(number_of_video_frames)\n if N < 100:\n raise ValueError('Argument \"number_of_video_frames\" is %d but must be at least 100.' % N)\n filename_1 = str(filename_1)\n filename_2 = str(filename_2)\n filename_3 = str(filename_3)\n self._spaceship_race_single_frame(planet_idx, 0, filename_1, N)\n self._spaceship_race_single_frame(planet_idx, 1, filename_2, N)\n self._spaceship_race_single_frame(planet_idx, 2, filename_3, N)\n\n def _spaceship_race_single_frame(self, planet_idx, reference_system, filename, N):\n radius = self.system.radii[planet_idx]\n dt = 2e-05\n ships = np.zeros((4, N, 3))\n planet_pos0 = np.array((0, utils.AU_to_km(1), 0))\n planet_pos = np.zeros((N, 3))\n vel = np.zeros((4, 3))\n vel[(0, 0)] = 0.4 * const.c_km_pr_s\n vel[(1, 0)] = 0.8 * const.c_km_pr_s\n vel[(2, 0)] = 0.1 * const.c_km_pr_s\n vel[(3, 0)] = 0.2 * const.c_km_pr_s\n cam_pos = np.zeros((N, 3))\n cam_dir = np.zeros((N, 3))\n time_planframe = np.zeros(N)\n for i in range(4):\n if i == 0:\n ships[0, 0, :] = np.array((0, -1.5 * radius, 0))\n if i == 1:\n ships[1, 0, :] = np.array((0, -1.5 * radius, 0))\n if i == 2:\n ships[2, 0, :] = np.array((0, -1.5 * radius, 0))\n else:\n ships[3, 0, :] = np.array((0, -1.5 * radius, 0))\n\n cam_dist = 5000\n ships_center = np.array((0.0, ships[(0, 0, 1)], ships[(0, 0, 2)]))\n cam_pos[0, :] = ships_center + np.array((0, -cam_dist, 0))\n cam_dir[0, :] = ships_center - cam_pos[0, :]\n acc = 250.0\n for i in range(N - 1):\n time_planframe[i + 1] = (i + 1) * dt\n planet_pos[i + 1, :] = planet_pos[0, :]\n cam_pos[i + 1, :] = ships_center + np.array((0, -cam_dist, 0))\n cam_dir[i + 1, :] = ships_center - cam_pos[i + 1, :]\n for ship in range(0, 4):\n ships[ship, i + 1, :] = ships[ship, i, :] + vel[ship, :] * dt\n\n vel[(2, 0)] = vel[(2, 0)] + acc * dt * const.c_km_pr_s\n if acc > 0 and vel[(2, 0)] > const.c_km_pr_s:\n acc = -0.1 * acc\n vel[(2, 0)] = 0.999 * const.c_km_pr_s\n if vel[(2, 0)] < 0:\n vel[(2, 0)] = 0.0\n\n ships_planframe = np.copy(ships)\n planet_pos_planframe = np.copy(planet_pos)\n cam_pos_planframe = np.copy(cam_pos)\n if reference_system == 0:\n time_array = np.linspace(0, dt * N, N)\n else:\n if reference_system == 1 or reference_system == 2:\n v = utils.km_to_AU(vel[(reference_system - 1, 0)])\n time_array1, sat1_pos_1D = self._lorentz_transform(time_planframe, utils.km_to_AU(ships_planframe[0, :, 0]), v)\n time_array2, sat2_pos_1D = self._lorentz_transform(time_planframe, utils.km_to_AU(ships_planframe[1, :, 0]), v)\n time_array3, sat3_pos_1D = self._lorentz_transform(time_planframe, utils.km_to_AU(ships_planframe[2, :, 0]), v)\n time_array4, sat4_pos_1D = self._lorentz_transform(time_planframe, utils.km_to_AU(ships_planframe[3, :, 0]), v)\n time_arrayp, planet_pos_1D = self._lorentz_transform(time_planframe, utils.km_to_AU(planet_pos_planframe[:, 0]), v)\n if reference_system == 1:\n time_array = np.linspace(0, time_array1[(-1)] - time_array1[0], N)\n if reference_system == 2:\n time_array = np.linspace(0, time_array2[(-1)] - time_array2[0], N)\n sat1_pos_1D = interpolate.interp1d(time_array1, sat1_pos_1D, kind='linear', bounds_error=False, fill_value='extrapolate', assume_sorted=True)(time_array)\n sat2_pos_1D = interpolate.interp1d(time_array2, sat2_pos_1D, kind='linear', bounds_error=False, fill_value='extrapolate', assume_sorted=True)(time_array)\n sat3_pos_1D = interpolate.interp1d(time_array3, sat3_pos_1D, kind='linear', bounds_error=False, fill_value='extrapolate', assume_sorted=True)(time_array)\n sat4_pos_1D = interpolate.interp1d(time_array4, sat4_pos_1D, kind='linear', bounds_error=False, fill_value='extrapolate', assume_sorted=True)(time_array)\n planet_pos_1D = interpolate.interp1d(time_arrayp, planet_pos_1D, kind='linear', bounds_error=False, fill_value='extrapolate', assume_sorted=True)(time_array)\n ships[0, :, 0] = utils.AU_to_km(sat1_pos_1D)\n ships[1, :, 0] = utils.AU_to_km(sat2_pos_1D)\n ships[2, :, 0] = utils.AU_to_km(sat3_pos_1D)\n ships[3, :, 0] = utils.AU_to_km(sat4_pos_1D)\n planet_pos[:, 0] = utils.AU_to_km(planet_pos_1D)\n cam_pos[:, 0] = 0.0\n for i in range(N - 1):\n cam_dir[i, :] = ships_center - cam_pos[i, :]\n\n else:\n print('You can only choose the reference system as 0 (planet system) 1 (student nr. 1) or 2 (student nr. 2)')\n raise ValueError('reference system invalid')\n object_name = [\n 'student 1', 'student 2', 'ship 3', 'ship 4']\n object_string = ['satellite', 'satellite', 'satellite', 'satellite']\n km_to_AU = 1000.0 / const.AU\n planet_pos *= km_to_AU\n ships *= km_to_AU\n cam_pos *= km_to_AU\n cam_dir *= km_to_AU\n other_objects = []\n message1 = []\n message2 = []\n message3 = []\n message4 = []\n for i in range(N):\n message1.append('sat 1')\n message2.append('sat 2')\n message3.append('sat 3')\n message4.append('sat 4')\n\n ruler_length = self._get_ruler_length(cam_dist)\n ruler = [-ruler_length / 2.0, ruler_length / 2.0, 10, 'km', cam_dist]\n ships[0, :, 2] -= 1.5e-06\n ships[1, :, 2] += 0\n ships[2, :, 2] += 1.5e-06\n ships[3, :, 2] += 3e-06\n ship_5 = np.copy(ships[0])\n ship_5[:, 0] = planet_pos[:, 0]\n ship_5[:, 2] = ship_5[:, 2] * 3\n other_objects.append([object_name[0], object_string[0], ships[0, :, :], 0.2, [50, 50, 0], message1, None, None, [0, 1, 0]])\n other_objects.append([object_name[1], object_string[1], ships[1, :, :], 0.2, [50, 0, 0], message2, None, None, [0, 1, 0]])\n other_objects.append([object_name[2], object_string[2], ships[2, :, :], 0.2, [0, 50, 0], message3, None, None, [0, 1, 0]])\n other_objects.append(['sphere01', 'sphere01', ship_5, 200, [1, 1, 1], ['\\nSpace Station'] * len(message4), None, None, [0, 1, 0]])\n self._write_to_xml(time_array, cam_pos, cam_dir, planet_pos, other_objects, planet_idx=planet_idx, ruler=ruler, filename=filename, cheat_light_speed=True, use_obj_scaling=1)\n return\n\n def laser_chase(self, planet_idx, increase_height=False, filename_1='laser_chase_frame_1.xml', filename_2='laser_chase_frame_2.xml', number_of_video_frames=400):\n \"\"\"A fast moving spaceship emits two successive laser beams, which are observed from the frame of reference of a planet and the spaceship.\n\n Generates the XML files used in Exercise 3 in Part 2B of the lecture notes and Exercise 5 in Part 8 of the project.\n\n Parameters\n ----------\n planet_idx : int\n Index of the planet above which the experiment takes place.\n increase_height : bool or float, optional\n Determines the height above the planet center where the experiment takes place.\n The default value (False) causes a predetermined height of 1.02 planet radii to be used. Using True increases this to 1.1.\n Optionally, a custom adjustment parameter between 0.5 and 5 can be provided.\n Try modifying this argument if the spaceships interfere with the surface of the planet.\n filename_1 : str, optional\n The filename to use for frame of reference 1.\n filename_2 : str, optional\n The filename to use for frame of reference 2.\n number_of_video_frames : int, optional\n The number of video frames to use in the XML files.\n Can be reduced to reduce file size, but be aware that this might lead to errors.\n Default is 400, but must be at least 100.\n \"\"\"\n planet_idx = int(planet_idx)\n if planet_idx < 0 or planet_idx >= self.system.number_of_planets:\n raise ValueError('Argument \"planet_idx\" is %d but must be in the range [0, %d].' % (planet_idx, self.system.number_of_planets - 1))\n N = int(number_of_video_frames)\n if N < 100:\n raise ValueError('Argument \"number_of_video_frames\" is %d but must be at least 100.' % N)\n filename_1 = str(filename_1)\n filename_2 = str(filename_2)\n standard_height_factor = 1.02\n increase_height_factor = 1.1\n cam_away_dist = utils.km_to_AU(700)\n ruler_ticks = 21\n ref_frame_movement_dist = 2000\n nbeam = 2\n random_state = np.random.RandomState(self.seed + utils.get_seed('laser_chase'))\n light_speed_int = random_state.randint(890, 930)\n ref_frame_speed = light_speed_int * const.c_AU_pr_s / 1000.0\n ref_frame_movement = utils.km_to_AU(np.linspace(-ref_frame_movement_dist / 2, ref_frame_movement_dist / 2, N))\n if increase_height is False:\n events_radius = utils.km_to_AU(self.system.radii[planet_idx]) * standard_height_factor\n else:\n if increase_height is True:\n events_radius = utils.km_to_AU(self.system.radii[planet_idx]) * increase_height_factor\n else:\n if increase_height < 0.5 or increase_height > 5.0:\n print('Increase height needs to be True, False or between 0.5 and 5')\n raise ValueError('Increase_height invalid')\n if increase_height >= 1:\n events_radius = utils.km_to_AU(self.system.radii[planet_idx]) * (standard_height_factor + 0.01 * increase_height)\n else:\n events_radius = utils.km_to_AU(self.system.radii[planet_idx]) * (standard_height_factor - 0.01 * increase_height)\n dist_from_star = np.hypot(self.system.initial_positions[(0, planet_idx)], self.system.initial_positions[(1, planet_idx)])\n planet_pos = np.array([0, 0, 0])\n rocket_pos_1D = np.zeros(N)\n laser_pos_1D = np.zeros((N, nbeam))\n laser_visibility = np.zeros((N, nbeam))\n i_emit = np.zeros(nbeam)\n i_emit[0] = N / 10\n i_emit[1] = 6 * N / 10\n end_time = (ref_frame_movement[(-1)] - ref_frame_movement[0]) / ref_frame_speed\n time_array = np.linspace(0, end_time, N)\n dt = time_array[1] - time_array[0]\n dx = (time_array[(-1)] - time_array[(-2)]) * const.c_AU_pr_s\n for i in range(0, nbeam):\n laser_pos_1D[0:int(i_emit[i]) + 1, i] = ref_frame_movement[0:int(i_emit[i]) + 1]\n\n for j in range(nbeam):\n for i in range(int(i_emit[j]), N - 1):\n laser_pos_1D[(i + 1, j)] = laser_pos_1D[(i, j)] + dx\n laser_visibility[(i, j)] = 1\n\n cam_pos = np.zeros(shape=(N, 3))\n rocket_pos = np.zeros(shape=(N, 3))\n laser_pos = np.zeros(shape=(N, nbeam, 3))\n rocket_pos[:, 2] = rocket_pos_1D + ref_frame_movement\n laser_pos[:, :, 2] = laser_pos_1D\n cam_pos[:, 2] = np.average(rocket_pos[:, 2])\n cam_pos[:, 1] -= cam_away_dist\n cam_pos[:, 0] -= events_radius\n rocket_pos[:, 0] -= events_radius\n laser_pos[:, :, 0] -= events_radius\n cam_dir = [\n 0, 1, 0]\n cam_upvec = [-1, 0, 0]\n sat_message_list = None\n light_message_list = None\n ruler_length = utils.AU_to_km(self._get_ruler_length(cam_away_dist))\n ruler = [\n -ruler_length / 2.0, ruler_length / 2.0, ruler_ticks, 'km', utils.AU_to_km(cam_away_dist)]\n planet_pos = np.zeros((N, 3))\n other_objects = [\n self._object_list('lsr1', 'Laser', laser_pos[:, 0, :], 4, [50, 50, 0], msg_list=light_message_list, visible=laser_visibility[:, 0]),\n self._object_list('lsr2', 'Laser', laser_pos[:, 1, :], 4, [50, 0, 0], msg_list=light_message_list, visible=laser_visibility[:, 1]),\n self._object_list('rocket1', 'Satellite', rocket_pos, 0.1, [3, 3, 3], msg_list=sat_message_list, orient=[0, 0, -1])]\n global_messages = [\n ''] * N\n for i in range(N):\n if laser_visibility[(i, 0)] == 1:\n global_messages[i] += 'First laser emission: Time = %f ms, Spaceship position = %f km\\n' % (time_array[int(i_emit[0])] * 1000, utils.AU_to_km(rocket_pos[(int(i_emit[0]), 2)]))\n if laser_visibility[(i, 1)] == 1:\n global_messages[i] += 'Second laser emission: Time = %f ms, Spaceship position = %f km, First laser position = %f km' % (time_array[int(i_emit[1])] * 1000, utils.AU_to_km(rocket_pos[(int(i_emit[1]), 2)]), utils.AU_to_km(laser_pos[(int(i_emit[1]), 0, 2)]))\n\n self._write_to_xml(time_array, cam_pos, cam_dir, planet_pos, other_objects, camera_messages=global_messages, ruler=ruler, planet_idx=planet_idx, up_vec=cam_upvec, laser_scale=0.2, filename=filename_1)\n global_messages = [ '' for i in range(N) ]\n rocket_pos_shipframe = np.copy(rocket_pos)\n planet_pos_shipframe = np.copy(planet_pos)\n laser_pos_shipframe = np.copy(laser_pos)\n time_laser_shipframe = np.zeros((N, nbeam))\n time_shipframe, rocket_pos_shipframe[:, 2] = self._lorentz_transform(time_array, rocket_pos[:, 2], ref_frame_speed)\n time_planet_shipframe, planet_pos_shipframe[:, 2] = self._lorentz_transform(time_array, planet_pos[:, 2], ref_frame_speed)\n for i in range(nbeam):\n time_laser_shipframe[:, i], laser_pos_shipframe[:, i, 2] = self._lorentz_transform(time_array, laser_pos[:, i, 2], ref_frame_speed)\n\n time_emit_shipframe = np.zeros(nbeam)\n for i in range(nbeam):\n time_emit_shipframe[i] = time_laser_shipframe[(int(i_emit[i]), i)]\n\n i_sametime = np.argmin(np.abs(time_laser_shipframe[:, 0] - time_laser_shipframe[(int(i_emit[1]), 1)]))\n time_shipframe0 = time_shipframe\n gamma = 1.0 / np.sqrt(1.0 - (ref_frame_speed / const.c_AU_pr_s) ** 2)\n t2 = time_shipframe[(-1)] + (time_shipframe[(-1)] - time_shipframe[0]) * 4.0\n time_shipframe = np.linspace(0, t2, N)\n i_sametime = np.argmin(np.abs(time_shipframe - time_laser_shipframe[(int(i_emit[1]), 1)]))\n planet_pos_shipframe[:, 2] = interpolate.interp1d(time_planet_shipframe, planet_pos_shipframe[:, 2], kind='linear', bounds_error=False, fill_value='extrapolate', assume_sorted=True)(time_shipframe)\n rocket_pos_shipframe[:, 2] = interpolate.interp1d(time_shipframe0, rocket_pos_shipframe[:, 2], kind='linear', bounds_error=False, fill_value='extrapolate', assume_sorted=True)(time_shipframe)\n for i in range(nbeam):\n laser_pos_shipframe[:, i, 2] = interpolate.interp1d(time_laser_shipframe[:, i], laser_pos_shipframe[:, i, 2], kind='linear', bounds_error=False, fill_value='extrapolate', assume_sorted=True)(time_shipframe)\n\n laser_visibility[:, :] = 1\n i_emit_shipframe = np.copy(i_emit)\n for i in range(nbeam):\n i_emit_shipframe[i] = np.argmin(np.abs(time_emit_shipframe[i] - time_shipframe))\n laser_visibility[0:int(i_emit_shipframe[i]), i] = 0\n\n other_objects = [self._object_list('lsr1', 'Laser', laser_pos_shipframe[:, 0, :], 4, [50, 50, 0], msg_list=light_message_list, visible=laser_visibility[:, 0]),\n self._object_list('lsr2', 'Laser', laser_pos_shipframe[:, 1, :], 4, [50, 0, 0], msg_list=light_message_list, visible=laser_visibility[:, 1]),\n self._object_list('rocket1', 'Satellite', rocket_pos_shipframe, 0.1, [3, 3, 3], msg_list=sat_message_list, orient=[0, 1, -1])]\n cam_pos[:, 2] = np.average(rocket_pos_shipframe[:, 2])\n for i in range(N):\n if laser_visibility[(i, 0)] == 1:\n global_messages[i] += 'First laser emission: Time = %f ms, Planet position = %f km\\n' % (time_shipframe[int(i_emit_shipframe[0])] * 1000, utils.AU_to_km(planet_pos_shipframe[(int(i_emit_shipframe[0]), 2)]) - utils.AU_to_km(rocket_pos_shipframe[(int(i_emit_shipframe[0]), 2)]))\n if laser_visibility[(i, 1)] == 1:\n global_messages[i] += 'Second laser emission: Time = %f ms, Planet position = %f km, First laser position = %f km' % (time_shipframe[int(i_emit_shipframe[1])] * 1000, utils.AU_to_km(planet_pos_shipframe[(int(i_emit_shipframe[1]), 2)]) - utils.AU_to_km(rocket_pos_shipframe[(int(i_emit_shipframe[1]), 2)]), utils.AU_to_km(laser_pos_shipframe[(int(i_emit_shipframe[1]), 0, 2)]) - utils.AU_to_km(rocket_pos_shipframe[(int(i_emit_shipframe[1]), 2)]))\n\n self._write_to_xml(time_shipframe, cam_pos, cam_dir, planet_pos_shipframe, other_objects, camera_messages=global_messages, ruler=ruler, planet_idx=planet_idx, up_vec=cam_upvec, laser_scale=0.2, filename=filename_2)\n light_beam_distance_planet = utils.AU_to_km(laser_pos[(int(i_emit[1]), 0, 2)]) - utils.AU_to_km(rocket_pos[(int(i_emit[1]), 2)])\n light_beam_distance_spaceship = utils.AU_to_km(laser_pos_shipframe[(int(i_emit_shipframe[1]), 0, 2)]) - utils.AU_to_km(rocket_pos_shipframe[(int(i_emit_shipframe[1]), 2)])\n if self._write_solutions:\n solution_name = 'Solutions_laser_chase.txt'\n solution_2B = open(os.path.join(self._solution_path, solution_name), 'w')\n solution_2B.write('Solutions to 2B.3\\n')\n solution_2B.write('1) The velocity for the planet/spaceship v = %f\\n' % (light_speed_int / 1000))\n solution_2B.write(\"6) Planet frame: L = %f km. Spaceship frame: L' = %f km. Ratio r = L/L' = %f\\n\" % (light_beam_distance_planet, light_beam_distance_spaceship, light_beam_distance_planet / light_beam_distance_spaceship))\n solution_2B.close()\n return\n\n def neutron_decay(self, planet_idx, increase_height=False, filename_1='neutron_decay_frame_1.xml', filename_2='neutron_decay_frame_2.xml', number_of_video_frames=1200):\n \"\"\"A fast moving neutron disintegrates spontaneously, and a proton and an electron are seen to continue in the same direction.\n\n Generates the XML files used in Exercise 4 in Part 2B of the lecture notes and Exercise 6 in Part 8 of the project.\n\n Parameters\n ----------\n planet_idx : int\n Index of the planet above which the experiment takes place.\n increase_height : bool or float, optional\n Determines the height above the planet center where the experiment takes place.\n The default value (False) causes a predetermined height of 1.05 planet radii to be used. Using True increases this to 1.2.\n Optionally, a custom adjustment parameter between 0.5 and 5 can be provided.\n Try modifying this argument if the spaceships interfere with the surface of the planet.\n filename_1 : str, optional\n The filename to use for frame of reference 1.\n filename_2 : str, optional\n The filename to use for frame of reference 2.\n number_of_video_frames : int, optional\n The number of video frames to use in the XML files.\n Can be reduced to reduce file size, but be aware that this might lead to errors.\n Default is 1200, but must be at least 100.\n \"\"\"\n planet_idx = int(planet_idx)\n if planet_idx < 0 or planet_idx >= self.system.number_of_planets:\n raise ValueError('Argument \"planet_idx\" is %d but must be in the range [0, %d].' % (planet_idx, self.system.number_of_planets - 1))\n N = int(number_of_video_frames)\n if N < 100:\n raise ValueError('Argument \"number_of_video_frames\" is %d but must be at least 100.' % N)\n filename_1 = str(filename_1)\n filename_2 = str(filename_2)\n self._neutron_decay_single_frame(planet_idx, 0, increase_height, filename_1, N)\n self._neutron_decay_single_frame(planet_idx, 1, increase_height, filename_2, N)\n\n def _neutron_decay_single_frame(self, planet_idx, reference_system, increase_height, filename, N):\n random_state = np.random.RandomState(self.seed + utils.get_seed('neutron_decay'))\n radius = self.system.radii[planet_idx]\n dt = 5e-06\n ships = np.zeros((4, N, 3))\n planet_pos0 = np.array((0, 0, 0))\n planet_pos = np.zeros((N, 3))\n if increase_height is False:\n height = 1.05 * radius\n else:\n if increase_height is True:\n height = 1.2 * radius\n else:\n if increase_height < 0.5 or increase_height > 5.0:\n print('Increase height needs to be True, False or between 0.5 and 5')\n raise ValueError('Increase_height invalid')\n if increase_height >= 1:\n height = radius * (1.05 + 0.01 * increase_height)\n else:\n height = radius * (1.05 - 0.05 * increase_height)\n masselectron = 9.10938188e-31\n massproton = 1.67262158e-27\n massneutron = 1.67492747e-27\n gammapp = (massneutron ** 2 + massproton ** 2 - masselectron ** 2) / (2.0 * massproton * massneutron)\n vproton_shipframe = -np.sqrt(1.0 - 1.0 / gammapp ** 2)\n cc = (vproton_shipframe * gammapp * massproton / masselectron) ** 2\n velectron_shipframe = np.sqrt(cc / (1.0 + cc)) * const.c_km_pr_s\n vproton_shipframe *= const.c_km_pr_s\n v = random_state.randint(800, 900) / 1000.0 * const.c_km_pr_s\n vel = np.zeros((4, 3))\n vel[(0, 2)] = self._velocity_transformation(-v / const.c_km_pr_s, velectron_shipframe / const.c_km_pr_s) * const.c_km_pr_s\n vel[(1, 2)] = self._velocity_transformation(-v / const.c_km_pr_s, vproton_shipframe / const.c_km_pr_s) * const.c_km_pr_s\n cam_pos = np.zeros((N, 3))\n cam_dir = np.zeros((N, 3))\n time_planframe = np.zeros(N)\n gamma1 = 1.0 / np.sqrt(1.0 - (vel[(0, 2)] / const.c_km_pr_s) ** 2)\n gamma2 = 1.0 / np.sqrt(1.0 - (vel[(1, 2)] / const.c_km_pr_s) ** 2)\n for i in range(2):\n if i == 0:\n ships[0, 0, :] = np.array((-height, 0, -500))\n if i == 1:\n ships[1, 0, :] = np.array((-height, 0, -475))\n\n cam_dist = 500 * (1.0 + reference_system)\n ships_center = np.array((-height, 0, 0))\n cam_pos[0, :] = ships_center + np.array((0, -cam_dist, 0))\n cam_dir[0, :] = ships_center - cam_pos[0, :]\n for i in range(N - 1):\n time_planframe[i + 1] = (i + 1) * dt\n planet_pos[i + 1, :] = planet_pos[0, :]\n cam_pos[i + 1, :] = ships_center + np.array((0, -cam_dist, 0))\n cam_dir[i + 1, :] = ships_center - cam_pos[i + 1, :]\n for ship in range(0, 4):\n ships[ship, i + 1, :] = ships[ship, i, :] + vel[ship, :] * dt\n\n ihit = np.argmin(np.abs(ships[0, :, 2] - ships[1, :, 2]))\n gammatot = 1.0 / np.sqrt(1.0 - (v / const.c_km_pr_s) ** 2)\n masstot = (masselectron * gamma1 + massproton * gamma2) / gammatot\n newvel = np.array([0, 0, v])\n ships_planframe = np.copy(ships)\n planet_pos_planframe = np.copy(planet_pos)\n cam_pos_planframe = np.copy(cam_pos)\n s2orient = [0, 0, 1]\n if reference_system == 0:\n factor = 1\n time_array = np.linspace(0, dt * N, N)\n elif reference_system == 1:\n factor = 2\n s2orient = [0, 0, -1]\n v = utils.km_to_AU(newvel[2])\n time_array1, sat1_pos_1D = self._lorentz_transform(time_planframe, utils.km_to_AU(ships_planframe[0, :, 2]), v)\n time_array2, sat2_pos_1D = self._lorentz_transform(time_planframe, utils.km_to_AU(ships_planframe[1, :, 2]), v)\n time_arrayp, planet_pos_1D = self._lorentz_transform(time_planframe, utils.km_to_AU(planet_pos_planframe[:, 2]), v)\n if reference_system == 1:\n time_array = np.linspace(0, time_array1[(-1)] - time_array1[0], N) + time_array1[0]\n if reference_system == 2:\n time_array = np.linspace(0, time_array2[(-1)] - time_array2[0], N)\n sat1_pos_1D = interpolate.interp1d(time_array1, sat1_pos_1D, kind='linear', bounds_error=False, fill_value='extrapolate', assume_sorted=True)(time_array)\n sat2_pos_1D = interpolate.interp1d(time_array2, sat2_pos_1D, kind='linear', bounds_error=False, fill_value='extrapolate', assume_sorted=True)(time_array)\n planet_pos_1D = interpolate.interp1d(time_arrayp, planet_pos_1D, kind='linear', bounds_error=False, fill_value='extrapolate', assume_sorted=True)(time_array)\n time_array -= time_array1[0]\n ships[0, :, 2] = utils.AU_to_km(sat1_pos_1D)\n ships[1, :, 2] = utils.AU_to_km(sat2_pos_1D)\n planet_pos[:, 2] = utils.AU_to_km(planet_pos_1D)\n cam_pos[:, 2] = 0\n for i in range(N - 1):\n cam_dir[i, :] = ships_center - cam_pos[i, :]\n\n else:\n print('You can only choose the reference system as 0 (planet system) 1 (student nr. 1) or 2 (student nr. 2)')\n raise ValueError('Reference system invalid')\n object_name = [\n 'Electron', 'Proton', 'Neutron', 'Crash']\n object_string = ['sphere01', 'sphere01', 'sphere01', 'explosion']\n explosion_rgb = [50, 50, 0]\n neutron_expl_pos = np.zeros((N, 3))\n neutron = np.zeros((N, 3))\n if reference_system == 0:\n visual_hit = ihit + 40\n neutron_expl_pos[visual_hit, :] = (ships[0, visual_hit, :] + 2 * ships[1, visual_hit, :]) / 3\n for i in range(visual_hit + 1, N):\n neutron_expl_pos[i] = newvel * dt + neutron_expl_pos[(i - 1)]\n\n neutron[visual_hit] = neutron_expl_pos[visual_hit]\n for i in range(N - visual_hit, N):\n neutron[-i - 1] = neutron[(-i)] - newvel * dt\n\n for i in range(visual_hit + 1, N):\n neutron[i] = neutron[(-i)] + newvel * dt\n\n else:\n visual_hit = np.argmin(np.abs(sat1_pos_1D - sat2_pos_1D)) + 20 * factor * 2\n neutron_expl_pos[visual_hit:, :] = (ships[0, visual_hit, :] + 2 * ships[1, visual_hit, :]) / 3\n neutron[:, :] = neutron_expl_pos[visual_hit]\n cam_pos[:, 2] = neutron_expl_pos[(visual_hit, 2)]\n ships_visible = np.zeros(N)\n expl_visible = np.zeros(N)\n ships_visible[:visual_hit] = 1\n expl_visible[visual_hit:(visual_hit + int(N / 16))] = 1\n km_to_AU = 1000.0 / const.AU\n planet_pos *= km_to_AU\n ships *= km_to_AU\n cam_pos *= km_to_AU\n cam_dir *= km_to_AU\n neutron_expl_pos *= km_to_AU\n neutron *= km_to_AU\n ruler_length = self._get_ruler_length(cam_dist)\n ruler = [-ruler_length / 2.0, ruler_length / 2.0, 10, 'km', cam_dist]\n other_objects = [\n self._object_list(object_name[0], object_string[0], ships[0, :, :], 15 * factor, [0, 0, 255], visible=[ 1 if i > visual_hit else 0 for i in range(N) ], msg_list=[ '\\nElectron' if i > visual_hit else '' for i in range(N) ]),\n self._object_list(object_name[1], object_string[1], ships[1, :, :], 30 * factor, [255, 0, 0], visible=[ 1 if i > visual_hit else 0 for i in range(N) ], msg_list=[ '\\n\\nProton' if i > visual_hit else '' for i in range(N) ]),\n self._object_list(object_name[2], object_string[2], neutron, 35 * factor, [1, 1, 1], visible=[ 1 if i <= visual_hit else 0 for i in range(N) ], msg_list=[ '\\n\\nNeutron' if i <= visual_hit else '' for i in range(N) ]),\n self._object_list(object_name[3], object_string[3], neutron_expl_pos, 1000 * factor, explosion_rgb, visible=expl_visible)]\n if reference_system == 0:\n global_messages = [\n 'Mass of small ship: %g kg, mass of large ship: %g kg, mass of combined ships: %g kg\\n' % (masselectron, massproton, masstot)] * N\n for i in range(N):\n if i >= visual_hit:\n global_messages[i] += 'Initial neutron position: %f km, time: %f ms. ' % (utils.AU_to_km(neutron_expl_pos[(visual_hit, 2)]), time_array[visual_hit] * 1000)\n if i >= visual_hit + 150:\n global_messages[i] += 'Second neutron position: %f km, time: %f ms.\\n' % (utils.AU_to_km(neutron_expl_pos[(visual_hit + 150, 2)]), time_array[(visual_hit + 150)] * 1000)\n\n else:\n global_messages = [\n 'Mass of small ship: %g kg, mass of large ship: %g kg, mass of combined ships: %g kg\\n' % (masselectron, massproton, masstot)] * N\n for i in range(N):\n if i >= visual_hit:\n global_messages[i] += 'Planet position when fusion: %f km, time: %f ms. ' % (utils.AU_to_km(planet_pos[(visual_hit, 2)]), time_array[visual_hit] * 1000)\n if i >= visual_hit + 150:\n global_messages[i] += 'Planet position a bit later: %f km, time: %f ms.\\n' % (utils.AU_to_km(planet_pos[(visual_hit + 150, 2)]), time_array[(visual_hit + 150)] * 1000)\n\n global_messages = [\n ''] * N\n for i in range(N):\n if reference_system == 0:\n global_messages[i] += 'Velocity of neutron: %f c\\nElectron mass: 9.10938188e-31 kg, Proton mass 1.67262158e-27 kg, Neutron mass: 1.67492747e-27 kg' % (v / const.c_km_pr_s)\n else:\n global_messages[i] += 'Velocity of labframe (planet): %f c\\nElectron mass: 9.10938188e-31 kg, Proton mass 1.67262158e-27 kg, Neutron mass: 1.67492747e-27 kg' % (-utils.AU_to_km(v) / const.c_km_pr_s)\n\n self._write_to_xml(time_array, cam_pos, cam_dir, planet_pos, other_objects, planet_idx=planet_idx, ruler=ruler, filename=filename, cheat_light_speed=True, use_obj_scaling=1, up_vec=[-1, 0, 0], camera_messages=global_messages, show_clock=0, toggle_clock=False)\n if self._write_solutions:\n if reference_system == 0:\n v = v / const.c_km_pr_s\n vel = vel / const.c_km_pr_s\n momenergy_electron = 1 / np.sqrt(1 - vel[(0, 2)] ** 2) * masselectron * np.array([1.0, vel[(0, 2)]])\n momenergy_proton = 1 / np.sqrt(1 - vel[(1, 2)] ** 2) * massproton * np.array([1.0, vel[(1, 2)]])\n print('Electron momenergy: (%g, %g)' % tuple(momenergy_electron))\n print('Proton momenergy: (%g, %g)' % tuple(momenergy_proton))\n solution_name = 'Solutions_neutron_decay.txt'\n solution_2B = open(os.path.join(self._solution_path, solution_name), 'w')\n solution_2B.write('Solutions to 2B.4\\n')\n solution_2B.write('\\n')\n solution_2B.write(\"4) The velocity of the electron: v_e' = %f. The velocity of the proton: v_p' = %f\\n\" % (velectron_shipframe / const.c_km_pr_s, vproton_shipframe / const.c_km_pr_s))\n solution_2B.write('5) Electron: E = %g [kg], p = %g [kg]. Proton: E = %g [kg], p = %g [kg]\\n' % (momenergy_electron[0], momenergy_electron[1], momenergy_proton[0], momenergy_proton[1]))\n solution_2B.write('6) The velocity of the electron: v_e = %f. The velocity of the proton: v_p = %f\\n' % (vel[(0, 2)], vel[(1, 2)]))\n solution_2B.close()\n\n def antimatter_spaceship(self, planet_idx, increase_height=False, filename_1='antimatter_spaceship_frame_1.xml', filename_2='antimatter_spaceship_frame_2.xml', number_of_video_frames=400):\n \"\"\"An antimatter spaceship and an ordinary spaceship travel towards each other close to the speed of light, before annihilating and producing photons with identical wavelengths.\n\n Generates the XML files used in Exercise 5 in Part 2B of the lecture notes and Exercise 7 in Part 8 of the project.\n\n Parameters\n ----------\n planet_idx : int\n Index of the planet above which the experiment takes place.\n increase_height : bool or float, optional\n Determines the height above the planet center where the experiment takes place.\n The default value (False) causes a predetermined height of 1.015 planet radii to be used. Using True increases this to 1.1.\n Optionally, a custom adjustment parameter between 0.5 and 5 can be provided.\n Try modifying this argument if the spaceships interfere with the surface of the planet.\n filename_1 : str, optional\n The filename to use for frame of reference 1.\n filename_2 : str, optional\n The filename to use for frame of reference 2.\n number_of_video_frames : int, optional\n The number of video frames to use in the XML files.\n Can be reduced to reduce file size, but be aware that this might lead to errors.\n Default is 400, but must be at least 100.\n \"\"\"\n planet_idx = int(planet_idx)\n if planet_idx < 0 or planet_idx >= self.system.number_of_planets:\n raise ValueError('Argument \"planet_idx\" is %d but must be in the range [0, %d].' % (planet_idx, self.system.number_of_planets - 1))\n N = int(number_of_video_frames)\n if N < 100:\n raise ValueError('Argument \"number_of_video_frames\" is %d but must be at least 100.' % N)\n filename_1 = str(filename_1)\n filename_2 = str(filename_2)\n standard_height_factor = 1.015\n increase_height_factor = 1.1\n m_rest = 1000000\n cam_away_dist = utils.km_to_AU(1000)\n ruler_ticks = 10\n ship_travel_dist = 1000\n random_state = np.random.RandomState(self.seed + utils.get_seed('antimatter_spaceship'))\n if increase_height is False:\n events_radius = utils.km_to_AU(self.system.radii[planet_idx]) * standard_height_factor\n else:\n if increase_height is True:\n events_radius = utils.km_to_AU(self.system.radii[planet_idx]) * increase_height_factor\n else:\n if increase_height < 0.5 or increase_height > 5.0:\n print('Increase height needs to be True, False or between 0.5 and 5')\n raise ValueError('Increase_height invalid')\n if increase_height >= 1:\n events_radius = utils.km_to_AU(self.system.radii[planet_idx]) * (standard_height_factor + 0.01 * increase_height)\n else:\n events_radius = utils.km_to_AU(self.system.radii[planet_idx]) * (standard_height_factor - 0.01 * increase_height)\n deltalambda = random_state.randint(75, 250)\n lambda_m = random_state.randint(380 + deltalambda, 680)\n deltalambda *= 1e-09\n lambda_m *= 1e-09\n dlamlam = (deltalambda / lambda_m + 1.0) ** 2\n ship_speeds = (dlamlam - 1.0) / (dlamlam + 1.0)\n gamma = 1 / np.sqrt(1 - ship_speeds ** 2)\n h = 6.626069934e-34\n n_photons = 2.0 * gamma * m_rest * const.c ** 2 * lambda_m / (h * const.c)\n explosion_rgb = self._lambda_to_RGB(lambda_m)\n ship_speeds *= const.c_AU_pr_s\n dist_from_star = np.hypot(self.system.initial_positions[(0, planet_idx)], self.system.initial_positions[(1, planet_idx)])\n planet_pos = np.array([0, 0, 0])\n rocket_pos_1D = utils.km_to_AU(np.linspace(-ship_travel_dist, ship_travel_dist, N))\n rocket2_pos_1D = utils.km_to_AU(np.linspace(ship_travel_dist, -ship_travel_dist, N))\n end_time = np.abs(rocket_pos_1D[(-1)] - rocket_pos_1D[0]) / ship_speeds\n time_array = np.linspace(0, end_time, N)\n dt = time_array[1] - time_array[0]\n i_crash = np.argmin(np.abs(rocket_pos_1D - rocket2_pos_1D))\n ships_visible = np.ones(N)\n ships_visible[i_crash:] = 0\n explosions_visible = 1 - ships_visible\n cam_pos = np.zeros(shape=(3, ))\n rocket_pos = np.zeros(shape=(N, 3))\n rocket2_pos = np.zeros(shape=(N, 3))\n expl_pos = np.zeros(shape=(N, 3))\n planet_pos = np.zeros(shape=(N, 3))\n rocket_pos[:, 2] = rocket_pos_1D\n rocket2_pos[:, 2] = rocket2_pos_1D\n cam_pos[2] = 0\n cam_pos[1] -= cam_away_dist\n cam_pos[0] -= events_radius\n rocket_pos[:, 0] -= events_radius\n rocket2_pos[:, 0] -= events_radius\n expl_pos[:, 0] -= events_radius\n rocket3_pos = np.copy(rocket_pos)\n rocket3_pos[:, 2] -= utils.km_to_AU(100)\n cam_dir = [\n 0, 1, 0]\n cam_upvec = [-1, 0, 0]\n global_messages_s1 = [ '' for i in range(N) ]\n for i in range(N):\n global_messages_s1[i] += 'Spaceship rest mass = %g kg\\n' % m_rest\n global_messages_s1[i] += 'Leftmost spaceship velocity = %gc\\n' % (utils.AU_to_km(ship_speeds) / const.c_km_pr_s)\n\n for i in range(i_crash, N):\n global_messages_s1[i] += 'Number of photons emitted = %g' % n_photons\n\n other_objects = [\n self._object_list('rocket2', 'Satellite', rocket2_pos, 0.08, [5, 5, 0], visible=ships_visible),\n self._object_list('rocket1', 'Satellite', rocket_pos, 0.08, [5, 5, 5], visible=ships_visible),\n self._object_list('rocket3', 'Satellite', rocket3_pos, 0.04, [5, 0, 0], visible=ships_visible),\n self._object_list('Expl', 'explosion', expl_pos, 3000, explosion_rgb, visible=1 - ships_visible)]\n self._write_to_xml(time_array, cam_pos, cam_dir, planet_pos, other_objects, camera_messages=global_messages_s1, planet_idx=planet_idx, up_vec=cam_upvec, laser_scale=0.2, filename=filename_1, ruler=[\n 0, utils.AU_to_km(self._get_ruler_length(cam_away_dist)), ruler_ticks, 'km', utils.AU_to_km(cam_away_dist)])\n rocket1_s2_1D_func = self._ref_sys_interpolate_func(time_array, rocket_pos_1D, ship_speeds)\n rocket2_s2_1D_func = self._ref_sys_interpolate_func(time_array, rocket2_pos_1D, ship_speeds)\n time_array1_s2 = self._lorentz_transform(time_array, rocket_pos_1D, ship_speeds)[0]\n time_array2_s2 = self._lorentz_transform(time_array, rocket2_pos_1D, ship_speeds)[0]\n ts = time_array1_s2\n rocket1_s2_1D = rocket1_s2_1D_func(ts)\n rocket2_s2_1D = rocket2_s2_1D_func(ts)\n time_in_s2 = ts[(-1)] - ts[0]\n dist_ref_frame2 = ship_speeds * time_in_s2\n start = -dist_ref_frame2 / 2\n stop = -start\n ref_sys_movement = np.linspace(start, stop, N)\n planet_pos[:, 2] = np.linspace(0, -ship_speeds * time_in_s2, N)\n rocket1_s2 = np.zeros(shape=(N, 3))\n rocket2_s2 = np.zeros(shape=(N, 3))\n rocket1_s2[:, 2] = rocket1_s2_1D - rocket1_s2_1D[0] + utils.km_to_AU(1.0)\n rocket2_s2[:, 2] = rocket2_s2_1D - rocket1_s2_1D[0] + utils.km_to_AU(1.0)\n rocket2_rel2_rocket1 = np.copy(rocket2_s2)\n cam_pos_s2 = np.copy(rocket1_s2)\n global_messages_s2 = [ '' for i in range(N) ]\n vel = ship_speeds / const.c_AU_pr_s\n for i in range(N):\n global_messages_s2[i] += 'Spaceship rest mass = %g kg\\n' % m_rest\n global_messages_s2[i] += 'The velocity of the ground = %gc\\n' % -vel\n\n for i in range(i_crash, N):\n global_messages_s2[i] += 'Number of photons emitted = %g' % n_photons\n\n cam_pos_s2[:, 0] -= events_radius\n rocket1_s2[:, 0] -= events_radius\n rocket2_s2[:, 0] -= events_radius\n tiltcamera = np.linspace(utils.km_to_AU(50), utils.km_to_AU(-50), N)\n cam_pos_s2[:, 2] += utils.km_to_AU(-100)\n cam_pos_s2[:, 1] -= tiltcamera\n i_crash_s2 = np.argmin(np.abs(rocket1_s2_1D - rocket2_s2_1D))\n crash_site_s2 = rocket1_s2[i_crash_s2]\n cam_dir_s2 = crash_site_s2 - cam_pos_s2\n cam_upvec_s2 = cam_pos_s2 / np.linalg.norm(cam_pos_s2)\n expl_rgb_s2 = (\n random_state.uniform(0.9, 1), 0, 0)\n expl_message_list = [ ' ' for i in range(N) ]\n explosion_rgb_shift = self._lambda_to_RGB(lambda_m - deltalambda)\n other_objects_s2 = [\n [\n 'rocket2', 'Satellite', rocket2_s2, 0.05, [1, 1, 0], None, None, ships_visible, [0, 0, 1]],\n [\n 'rocket1', 'Satellite', rocket1_s2, 0.05, [1, 1, 1], None, None, ships_visible, [0, 0, -1]],\n self._object_list('expl', 'explosion', expl_pos, 1000, color_rgb=explosion_rgb_shift, visible=1 - ships_visible)]\n self._write_to_xml(ts - ts[0], cam_pos_s2, cam_dir_s2, planet_pos, other_objects_s2, use_obj_scaling=0, planet_idx=planet_idx, up_vec=cam_upvec_s2, filename=filename_2, camera_messages=global_messages_s2, cheat_light_speed=True)\n ship_B_vel = utils.AU_to_km(rocket2_s2_1D[50] - rocket2_s2_1D[0]) / (ts[50] - ts[0]) / const.c_km_pr_s\n electron_mass = 9.10938356e-31\n k = ((lambda_m - deltalambda) * gamma * electron_mass * const.c_km_pr_s * 1000 / h - 2.0) ** 2\n if self._write_solutions:\n solution_name = 'Solutions_antimatter_spaceship.txt'\n solution_2B = open(os.path.join(self._solution_path, solution_name), 'w')\n solution_2B.write('Solutions to 2B.5\\n')\n solution_2B.write(\"1) Spaceship B velocity seen from spaceship A: v_B' = %gc\\n\" % ship_B_vel)\n solution_2B.write('8) The total energy of a photon: E = 2m*gamma/n = %g kg. The wavelength in the planet frame: lambda = %g nm\\n' % (2 * m_rest * gamma / n_photons, lambda_m * 1000000000.0))\n solution_2B.write(\"12. The wavelength in the spaceship frame: lambda' = %g nm\\n\" % ((lambda_m - deltalambda) * 1000000000.0))\n solution_2B.write('14. The velocity needed: v = %.15f, you might not get exactly this number, depending on precision, but you should get a number very close to 1\\n' % ((k - 1.0) / (k + 1.0)))\n solution_2B.close()\n return\n\n def black_hole_descent(self, planet_idx, number_of_light_signals=30, consider_light_travel=False, text_file_dir='.', filename_1='black_hole_descent_frame_1.xml', filename_2='black_hole_descent_frame_2.xml'):\n \"\"\"A spaceship is falling towards a black hole while exhanging light signals with a spacecraft near an orbiting planet.\n\n Generates the XML and text files used in Exercise 5 in Part 2C and Exercise 2 in Part 2E of the lecture notes and Exercise 3 in Part 9 of the project.\n\n Parameters\n ----------\n planet_idx : int\n Index of the planet above which the experiment takes place.\n number_of_light_signals : int, optional\n The number of light signals sent out by the falling spaceship.\n Default is 30, but must be between 10 and 100.\n consider_light_travel : bool, optional\n Whether to take into account the traveling time of light.\n If True, note that an extra label will be added to the inputted file names to avoid conflicts with existing files.\n Default is False.\n text_file_dir : str, optional\n The path to the directory in which to generate text files containing the time intervals between successive light signals.\n If set to None, no text files will be generated.\n Default is to generate text files in the working directory.\n filename_1 : str, optional\n The filename to use for frame of reference 1.\n filename_2 : str, optional\n The filename to use for frame of reference 2.\n \"\"\"\n planet_idx = int(planet_idx)\n if planet_idx < 0 or planet_idx >= self.system.number_of_planets:\n raise ValueError('Argument \"planet_idx\" is %d but must be in the range [0, %d].' % (planet_idx, self.system.number_of_planets - 1))\n consider_light_travel = bool(consider_light_travel)\n filename_1 = str(filename_1)\n filename_2 = str(filename_2)\n filename_1_base = ('.').join(filename_1.split('.')[:-1]) if '.' in filename_1 else filename_1\n filename_2_base = ('.').join(filename_2.split('.')[:-1]) if '.' in filename_2 else filename_2\n filename_1 = filename_1_base + ('_with_light_travel' if consider_light_travel else '') + '.xml'\n filename_2 = filename_2_base + ('_with_light_travel' if consider_light_travel else '') + '.xml'\n if text_file_dir is None:\n write_text = False\n else:\n write_text = True\n text_file_dir = os.path.abspath(str(text_file_dir))\n if not os.path.isdir(text_file_dir):\n os.mkdir(text_file_dir)\n text_filename_1 = filename_1_base + ('_with_light_travel' if consider_light_travel else '') + '.txt'\n text_filename_2 = filename_2_base + ('_with_light_travel' if consider_light_travel else '') + '.txt'\n text_file_path_1 = os.path.join(text_file_dir, text_filename_1)\n text_file_path_2 = os.path.join(text_file_dir, text_filename_2)\n color_order_space_station = ['violet', 'blue', 'green', 'red']\n color_order_falling = ['red', 'yellow', 'blue', 'violet']\n number_of_light_signals = np.copy(number_of_light_signals)\n number_of_light_signals = int(number_of_light_signals)\n if number_of_light_signals < 10 or number_of_light_signals > 100:\n raise ValueError('number_of_light_signals must be an integer between 10 and 100')\n random_state = np.random.RandomState(self.seed + utils.get_seed('black_hole_descent'))\n nr_of_light_messages = number_of_light_signals\n M_SM = const.m_sun\n M_SM *= random_state.uniform(8000000.0, 30000000.0)\n M = utils.kg_to_m(M_SM)\n r_AU = 1\n planet_radius = utils.km_to_AU(self.system.radii[planet_idx])\n planet_pos = [r_AU - planet_radius * 2, planet_radius * 2, 0]\n r_m = utils.AU_to_m(r_AU)\n sat_start_shell_speed = random_state.randint(100, 300) * 0.001\n gamma = 1 / np.sqrt(1 - sat_start_shell_speed ** 2)\n lambda0 = 2e-07\n lambda0_fromshell = 9e-07\n dt = 1000000000.0\n time_array_sat = [0]\n time_array_obs = [0]\n sat_pos_1D = [r_m]\n energy_per_mass = np.sqrt(1.0 - 2.0 * M / r_m) * gamma\n transform_faraway_to_shell = 1.0 / np.sqrt(1.0 - 2.0 * M / r_m)\n while sat_pos_1D[(-1)] > 2 * M * 1.001:\n time_array_obs.append(time_array_obs[(-1)] + dt)\n dtau = (1 - 2 * M / sat_pos_1D[(-1)]) / energy_per_mass * transform_faraway_to_shell * dt\n time_array_sat.append(time_array_sat[(-1)] + dtau)\n sat_pos_1D.append(sat_pos_1D[(-1)] - np.sqrt((1 - 2 * M / sat_pos_1D[(-1)]) ** 2 * (1.0 - (1 - 2 * M / sat_pos_1D[(-1)]) / energy_per_mass ** 2)) * transform_faraway_to_shell * dt)\n\n sat_pos_1D = np.array(sat_pos_1D[:-1])\n time_array_sat = np.array(time_array_sat[:-1])\n time_array_obs = np.array(time_array_obs[:-1])\n if self._debug:\n print('Task C2\\nSpacecraft start pos: %e\\nend pos: %e\\nschwarzschild radius: %e' % (utils.m_to_AU(sat_pos_1D[0]), utils.m_to_AU(sat_pos_1D[(-1)]), utils.m_to_AU(2 * M)))\n N = len(sat_pos_1D)\n if self._debug:\n print('In C2_1 with Frames = %d' % N)\n obs_pos = np.zeros(shape=(N, 3))\n obs_pos[:, 0] += r_m + 700000\n light_interval = (time_array_sat[(-1)] - time_array_sat[0]) / (nr_of_light_messages + 0.1)\n send_light_times_sat = np.array([ i * light_interval for i in range(0, int(nr_of_light_messages) + 1) ])\n light_indexes = []\n for i in range(len(send_light_times_sat)):\n light_indexes.append(np.abs(send_light_times_sat[i] - time_array_sat).argmin())\n\n if consider_light_travel:\n light_indexes_emitted = np.copy(light_indexes)\n recv = []\n for i in light_indexes:\n lightpos = np.zeros(N)\n lightpos[i] = sat_pos_1D[i]\n for j in range(i + 1, N):\n lightpos[j] = lightpos[(j - 1)] + (1 - 2 * M / lightpos[(j - 1)]) * dt\n\n ii = np.argmin(np.abs(lightpos - r_m))\n if ii < N - 1:\n if np.sign(lightpos[ii] - r_m) != np.sign(lightpos[(ii + 1)] - r_m) or np.sign(lightpos[ii] - r_m) != np.sign(lightpos[(ii - 1)] - r_m):\n recv.append(ii)\n\n light_indexes = recv\n else:\n lie = np.copy(light_indexes)\n recv = []\n for i in light_indexes:\n lpsd = np.zeros(N)\n lpsd[i] = sat_pos_1D[i]\n for j in range(i + 1, N):\n lpsd[j] = lpsd[(j - 1)] + (1 - 2 * M / lpsd[(j - 1)]) * dt\n\n iui = np.argmin(np.abs(lpsd - r_m))\n if iui < N - 1:\n if np.sign(lpsd[iui] - r_m) != np.sign(lpsd[(iui + 1)] - r_m) or np.sign(lpsd[iui] - r_m) != np.sign(lpsd[(iui - 1)] - r_m):\n recv.append(iui)\n\n if self._debug:\n print('light indexes ', np.array(light_indexes))\n if self._debug:\n print('light intervals ', np.array(light_indexes[1:]) - np.array(light_indexes[:-1]))\n light_obj_pos_violet = np.zeros(shape=(N, 3)) + np.array([r_AU - 1e-06, 0, 0])\n light_obj_pos_blue = np.zeros(shape=(N, 3)) + np.array([r_AU - 1e-06, 0, 0])\n light_obj_pos_green = np.zeros(shape=(N, 3)) + np.array([r_AU - 1e-06, 0, 0])\n light_obj_pos_yellow = np.zeros(shape=(N, 3)) + np.array([r_AU - 1e-06, 0, 0])\n light_obj_pos_orange = np.zeros(shape=(N, 3)) + np.array([r_AU - 1e-06, 0, 0])\n light_obj_pos_red = np.zeros(shape=(N, 3)) + np.array([r_AU - 1e-06, 0, 0])\n light_obj_visibility_violet = np.zeros(N)\n light_obj_visibility_blue = np.zeros(N)\n light_obj_visibility_green = np.zeros(N)\n light_obj_visibility_yellow = np.zeros(N)\n light_obj_visibility_orange = np.zeros(N)\n light_obj_visibility_red = np.zeros(N)\n cnt = 0\n for i in light_indexes:\n ii = i\n if consider_light_travel:\n ii = light_indexes_emitted[cnt]\n cnt += 1\n lambda_obs = lambda0 * energy_per_mass / (1.0 - 2.0 * M / sat_pos_1D[ii]) / transform_faraway_to_shell\n lambda_m = np.copy(lambda_obs) / 1e-09\n if lambda_m <= 450:\n light_obj_visibility_violet[i:i + N // 128] += 1\n if 450 < lambda_m <= 495:\n light_obj_visibility_blue[i:i + N // 128] += 1\n if 495 < lambda_m <= 570:\n light_obj_visibility_green[i:i + N // 128] += 1\n if 570 < lambda_m <= 590:\n light_obj_visibility_yellow[i:i + N // 128] += 1\n if 590 < lambda_m <= 620:\n light_obj_visibility_orange[i:i + N // 128] += 1\n if lambda_m > 620:\n light_obj_visibility_red[i:i + N // 128] += 1\n\n sat_radius_fake = r_m\n sat_visibility = np.zeros(N)\n sat_visibility[:] = 1\n sat_pos_fake = np.zeros(shape=(N, 3))\n sat_pos_fake[:, 0] = np.logspace(np.log(utils.m_to_AU(sat_radius_fake)), np.log(utils.m_to_AU(sat_radius_fake) - 0.0001), N)\n sat_pos_fake[:, 2] -= 3e-08\n light_obj_pos2 = np.zeros(shape=(N, 3)) + np.array([r_AU - 1e-06, 0, 0])\n rgb = np.zeros((N, 3))\n other_objects = [['rocket1', 'Satellite', sat_pos_fake, 0.2, [1, 1, 1], None, None, sat_visibility, None],\n [\n 'light', 'Sphere01', light_obj_pos_violet, 5, [255, 1, 255], None, None, light_obj_visibility_violet, None],\n [\n 'light', 'Sphere01', light_obj_pos_blue, 5, [0, 1, 255], None, None, light_obj_visibility_blue, None],\n [\n 'light', 'Sphere01', light_obj_pos_green, 5, [1, 255, 1], None, None, light_obj_visibility_green, None],\n [\n 'light', 'Sphere01', light_obj_pos_yellow, 5, [255, 255, 1], None, None, light_obj_visibility_yellow, None],\n [\n 'light', 'Sphere01', light_obj_pos_orange, 5, [255, 50, 1], None, None, light_obj_visibility_orange, None],\n [\n 'light', 'Sphere01', light_obj_pos_red, 5, [255, 5, 5], None, None, light_obj_visibility_red, None]]\n cam_dir_s1 = [\n -1, 0, 0]\n global_messages = ['Black hole mass = %g Solar Masses\\nSpacecraft initial shell velocity at 1AU = %g c\\nFalling space ship sending light signal every %g seconds measured in falling frame\\n' % (M_SM / const.m_sun, sat_start_shell_speed, light_interval / const.c)] * N\n print('The spacecraft will send a light signal every %g seconds to the planet observer, for a total of %d signals.' % (light_interval / const.c, nr_of_light_messages))\n new_line = [\n 12, 24, 36]\n a = 'Times of the light signals:\\n'\n light_number = 0\n light_number_array = []\n time_diffrences_light = []\n b = 0\n for i in range(N):\n if i in np.array(light_indexes):\n light_number += 1\n if light_number in new_line:\n a += '%i. %g |\\n' % (light_number, time_array_obs[i] / const.c)\n else:\n a += '%i. %g |' % (light_number, time_array_obs[i] / const.c)\n light_number_array += [light_number]\n time_diffrences_light += [time_array_obs[i] / const.c]\n b = time_array_obs[i] / const.c\n global_messages[i] += a\n\n if write_text == True:\n np.savetxt(text_file_path_1, np.array([light_number_array[1:len(recv)], time_diffrences_light[1:len(recv)]]))\n print('Text file written to %s.' % os.path.relpath(text_file_path_1))\n self._write_to_xml(time_array_obs / const.c, utils.m_to_AU(obs_pos), cam_dir_s1, planet_pos=planet_pos, other_objects=other_objects, camera_messages=global_messages, planet_idx=planet_idx, filename=filename_1, origo_location=np.array([0, 0, 0]), black_hole=True, play_speed=0.51)\n dtau_2 = 100000000.0\n time_array_sat_2 = [0]\n time_array_obs_2 = [0]\n sat_pos_1D_2 = [r_m]\n while sat_pos_1D_2[(-1)] > 2 * M * 1.001:\n time_array_sat_2.append(time_array_sat_2[(-1)] + dtau_2)\n dt_2 = energy_per_mass / (1 - 2 * M / sat_pos_1D_2[(-1)]) * dtau_2 / transform_faraway_to_shell\n time_array_obs_2.append(time_array_obs_2[(-1)] + dt_2)\n sat_pos_1D_2.append(sat_pos_1D_2[(-1)] - np.sqrt(energy_per_mass ** 2 - (1 - 2 * M / sat_pos_1D_2[(-1)])) * dtau_2)\n\n sat_pos_1D_2 = np.array(sat_pos_1D_2[:-1])\n time_array_sat_2 = np.array(time_array_sat_2[:-1])\n time_array_obs_2 = np.array(time_array_obs_2[:-1])\n N2 = len(sat_pos_1D_2)\n if self._debug:\n print('In C2_2 with Frames = %d' % N2)\n light_interval_2 = (time_array_obs_2[(-1)] - time_array_obs_2[0]) / (nr_of_light_messages + 0.1)\n send_light_times_obs = np.array([ i * light_interval_2 for i in range(1, int(nr_of_light_messages) + 1) ])\n light_indexes_2 = []\n for i in range(len(send_light_times_obs)):\n light_indexes_2.append(np.abs(send_light_times_obs[i] - time_array_obs_2).argmin())\n\n if consider_light_travel:\n recv = []\n for i in light_indexes_2:\n lightpos = np.zeros(N2)\n lightpos[0:i] = 1000000.0 * r_m\n lightpos[i] = r_m\n for j in range(i + 1, N2):\n lightpos[j] = lightpos[(j - 1)] - (1 - 2 * M / lightpos[(j - 1)]) / (1 - 2 * M / sat_pos_1D_2[(j - 1)]) * energy_per_mass * dtau_2\n\n ii = np.argmin(np.abs(lightpos - sat_pos_1D_2))\n if ii < N2 - 1:\n if np.sign(lightpos[ii] - sat_pos_1D_2[ii]) != np.sign(lightpos[(ii + 1)] - sat_pos_1D_2[(ii + 1)]) or np.sign(lightpos[ii] - sat_pos_1D_2[ii]) != np.sign(lightpos[(ii - 1)] - sat_pos_1D_2[(ii - 1)]):\n recv.append(ii)\n\n light_indexes_2 = recv\n else:\n recv = []\n for i in light_indexes_2:\n lightpos = np.zeros(N2)\n lightpos[0:i] = 1000000.0 * r_m\n lightpos[i] = r_m\n for j in range(i + 1, N2):\n lightpos[j] = lightpos[(j - 1)] - (1 - 2 * M / lightpos[(j - 1)]) / (1 - 2 * M / sat_pos_1D_2[(j - 1)]) * energy_per_mass * dtau_2\n\n iunn = np.argmin(np.abs(lightpos - sat_pos_1D_2))\n if iunn < N2 - 1:\n if np.sign(lightpos[iunn] - sat_pos_1D_2[iunn]) != np.sign(lightpos[(iunn + 1)] - sat_pos_1D_2[(iunn + 1)]) or np.sign(lightpos[iunn] - sat_pos_1D_2[iunn]) != np.sign(lightpos[(iunn - 1)] - sat_pos_1D_2[(iunn - 1)]):\n recv.append(iunn)\n\n light_obj2_visibility_violet = np.zeros(N2)\n light_obj2_visibility_blue = np.zeros(N2)\n light_obj2_visibility_green = np.zeros(N2)\n light_obj2_visibility_yellow = np.zeros(N2)\n light_obj2_visibility_orange = np.zeros(N2)\n light_obj2_visibility_red = np.zeros(N2)\n for i in light_indexes_2:\n lambda_obs = lambda0_fromshell / (energy_per_mass / (1.0 - 2.0 * M / sat_pos_1D_2[i]) / transform_faraway_to_shell)\n lambda_m = np.copy(lambda_obs) / 1e-09\n if lambda_m <= 450:\n light_obj2_visibility_violet[i:i + N // 128] += 1\n if 450 < lambda_m <= 495:\n light_obj2_visibility_blue[i:i + N // 128] += 1\n if 495 < lambda_m <= 570:\n light_obj2_visibility_green[i:i + N // 128] += 1\n if 570 < lambda_m <= 590:\n light_obj2_visibility_yellow[i:i + N // 128] += 1\n if 590 < lambda_m <= 620:\n light_obj2_visibility_orange[i:i + N // 128] += 1\n if lambda_m > 620:\n light_obj2_visibility_red[i:i + N // 128] += 1\n\n if self._debug:\n print('light indexes ', np.array(light_indexes_2))\n if self._debug:\n print('light intervals ', np.array(light_indexes_2[1:]) - np.array(light_indexes_2[:-1]))\n sat_pos_fake_2 = np.zeros(shape=(N2, 3))\n sat_pos_fake_2[:, 0] = np.logspace(np.log(utils.m_to_AU(sat_radius_fake)), np.log(utils.m_to_AU(sat_radius_fake) - 0.01), N2)\n light_obj2_pos_violet = np.array([1e-06, 0, 0]) + sat_pos_fake_2\n light_obj2_pos_blue = np.array([1e-06, 0, 0]) + sat_pos_fake_2\n light_obj2_pos_green = np.array([1e-06, 0, 0]) + sat_pos_fake_2\n light_obj2_pos_yellow = np.array([1e-06, 0, 0]) + sat_pos_fake_2\n light_obj2_pos_orange = np.array([1e-06, 0, 0]) + sat_pos_fake_2\n light_obj2_pos_red = np.array([1e-06, 0, 0]) + sat_pos_fake_2\n other_objects_2 = [\n [\n 'light', 'Sphere01', light_obj2_pos_violet, 2, [255, 0, 255], None, None, light_obj2_visibility_violet, None],\n [\n 'light', 'Sphere01', light_obj2_pos_blue, 2, [0, 0, 255], None, None, light_obj2_visibility_blue, None],\n [\n 'light', 'Sphere01', light_obj2_pos_green, 2, [0, 255, 0], None, None, light_obj2_visibility_green, None],\n [\n 'light', 'Sphere01', light_obj2_pos_yellow, 2, [255, 255, 0], None, None, light_obj2_visibility_yellow, None],\n [\n 'light', 'Sphere01', light_obj2_pos_orange, 2, [255, 50, 0], None, None, light_obj2_visibility_orange, None],\n [\n 'light', 'Sphere01', light_obj2_pos_red, 2, [255, 0, 0], None, None, light_obj2_visibility_red, None]]\n cam_dir_s2 = [\n 1, 0, 0]\n global_messages_2 = [\n 'Black hole mass = %g Solar Masses\\nSpacecraft initial shell velocity at 1AU = %g c\\nPlanet observer sending light every %g seconds measured in planet frame' % (M_SM / const.m_sun, sat_start_shell_speed, light_interval_2 / const.c)] * N2\n print('The far-away observer will send a light signal every %g seconds to the spacecraft, for a total of %d signals.' % (light_interval_2 / const.c, nr_of_light_messages))\n a = 'Times of the light signals:\\n'\n light_number = 0\n time_diffrences_light = []\n b = 0\n light_number_array = []\n for i in range(N2):\n if i in np.array(light_indexes_2):\n light_number += 1\n if light_number in new_line:\n a += '%i. %g |\\n' % (light_number, time_array_sat_2[i] / const.c)\n else:\n a += '%i. %g |' % (light_number, time_array_sat_2[i] / const.c)\n time_diffrences_light += [time_array_sat_2[i] / const.c]\n b = time_array_sat_2[i] / const.c\n light_number_array += [light_number]\n global_messages_2[i] += a\n\n if write_text == True:\n np.savetxt(text_file_path_2, np.array([light_number_array[:len(recv)], time_diffrences_light[:len(recv)]]))\n print('Text file written to %s.' % os.path.relpath(text_file_path_2))\n self._write_to_xml(time_array_sat_2 / const.c, sat_pos_fake_2, cam_dir_s2, camera_messages=global_messages_2, planet_pos=planet_pos, other_objects=other_objects_2, planet_idx=planet_idx, filename=filename_2, origo_location=np.array([0, 0, 0]), black_hole=True, play_speed=0.51)\n if self._write_solutions:\n if consider_light_travel:\n pass\n else:\n solution_name = 'Solutions_black_hole_descent.txt'\n solution_2C = open(os.path.join(self._solution_path, solution_name), 'w')\n solution_2C.write('Solutons to 2C.5\\n')\n solution_2C.write('4. The energy per mass of the spaceship is %f.\\n' % energy_per_mass)\n solution_2C.write('7. Distance from black hole (seen from the spacecraft), between two first signals received:')\n r_seen_from_sat = 2 / (1 - (time_array_sat_2[light_indexes_2[1]] - time_array_sat_2[light_indexes_2[0]]) / light_interval_2 * energy_per_mass * np.sqrt(1.0 - 2.0 * M / r_m))\n solution_2C.write('AU: %g, SR: %g|\\n' % (utils.m_to_AU(r_seen_from_sat * M), r_seen_from_sat))\n solution_2C.write('7. Distance from black hole (seen from the spacecraft), between two last signals received:')\n r_seen_from_sat = 2 / (1 - (time_array_sat_2[light_indexes_2[(-2)]] - time_array_sat_2[light_indexes_2[(-3)]]) / light_interval_2 * energy_per_mass * np.sqrt(1.0 - 2.0 * M / r_m))\n solution_2C.write('AU: %g, SR: %g|\\n' % (utils.m_to_AU(r_seen_from_sat * M), r_seen_from_sat))\n solution_2C.write('7. Distance from black hole (seen from the planet), between two first signals received:')\n r_seen_from_planet = 2 / (1 - light_interval / (time_array_obs[light_indexes[1]] - time_array_obs[light_indexes[0]]) * energy_per_mass * np.sqrt(1.0 - 2.0 * M / r_m))\n solution_2C.write('AU: %g, SR: %g|\\n' % (utils.m_to_AU(r_seen_from_planet * M), r_seen_from_planet))\n solution_2C.write('7. Distance from black hole (seen from the planet), between two last signals received:')\n r_seen_from_planet = 2 / (1 - light_interval / (time_array_obs[light_indexes[(-1)]] - time_array_obs[light_indexes[(-2)]]) * energy_per_mass * np.sqrt(1.0 - 2.0 * M / r_m))\n solution_2C.write('AU: %g, SR: %g|\\n' % (utils.m_to_AU(r_seen_from_planet * M), r_seen_from_planet))\n solution_2C.close()\n return\n\n def gps(self, planet_idx, angular_position=None, increase_height=False, filename='gps.xml', number_of_video_frames=1000):\n \"\"\"Two GPS satellites are passing above an observer on the equator.\n\n Generates the XML file used in Exercise 8 in Part 2C of the lecture notes and Exercise 5 in Part 9 of the project.\n\n Parameters\n ----------\n planet_idx : int\n Index of the planet above which the experiment takes place.\n angular_position : float, optional\n The angular position of the observer on the planet equator, measured in radians from the x-axis.\n By default, the observer is situated at a random angle in the range [pi/2, 3*pi/2].\n increase_height : bool or float, optional\n Determines the height above the planet center where the experiment takes place.\n The default value (False) causes a predetermined height of 1.01 planet radii to be used. Using True increases this to 1.1.\n Optionally, a custom adjustment parameter between 0.5 and 5 can be provided.\n Try modifying this argument if the spaceships interfere with the surface of the planet.\n filename : str, optional\n The filename to use for the XML file.\n number_of_video_frames : int, optional\n The number of video frames to use in the XML files.\n Can be reduced to reduce file size, but be aware that this might lead to errors.\n Default is 1000, but must be at least 100.\n \"\"\"\n planet_idx = int(planet_idx)\n if planet_idx < 0 or planet_idx >= self.system.number_of_planets:\n raise ValueError('Argument \"planet_idx\" is %d but must be in the range [0, %d].' % (planet_idx, self.system.number_of_planets - 1))\n N = int(number_of_video_frames)\n if N < 100:\n raise ValueError('Argument \"number_of_video_frames\" is %d but must be at least 100.' % N)\n random_state = np.random.RandomState(self.seed + utils.get_seed('gps'))\n filename = str(filename)\n standard_height_factor = 1.01\n increase_height_factor = 1.1\n if increase_height is False:\n height_factor = standard_height_factor\n else:\n if increase_height is True:\n height_factor = increase_height_factor\n else:\n if increase_height < 0.5 or increase_height > 5.0:\n print('Increase height needs to be True, False or between 0.5 and 5')\n raise ValueError('Increase_height invalid')\n if increase_height >= 1:\n height_factor = standard_height_factor + 0.01 * increase_height\n else:\n height_factor = standard_height_factor - 0.01 + 0.01 * increase_height\n print_solution = True\n sat_sys_angular_dist = 5 * const.pi / 4\n ang_dist_between_sats = const.pi / 6\n upper_lim_radius = 3\n lower_lim_radius = 2.5\n if angular_position is None:\n angular_position = random_state.uniform(const.pi / 2, 1.5 * const.pi)\n if angular_position < 0 or angular_position > 2 * const.pi:\n raise ValueError('angular_position is in radians and must be between 0 and 2*pi')\n if angular_position <= const.pi / 2 or angular_position >= 1.5 * const.pi:\n print('To stay on the sunny side of the planet, angular_position is recommended to be within [pi/2, 3/2*pi]')\n n_dec_pos = 3\n n_dec_t = 7\n print_solution = False\n GR = True\n\n def time_diff_shells(M, r1, r2, v2):\n \"\"\" Returns t1/t2, the factor at which time runs differently, at the\n shell a distance r1, relative\n to somebody on the shell at a distance r2 moving with tangential velocity v2.\n M = Planet mass in kg\n r1 = Planet radius in meters\n r2 = Orbit distance in meters\n v2 = Object orbit speed in m/s\"\"\"\n M_m = utils.kg_to_m(M)\n teller = 1 - 2 * M_m / r1\n nevner = 1 - 2 * M_m / r2 - v2 ** 2 / const.c ** 2\n return np.sqrt(teller / nevner)\n\n def sat_speed(M, r):\n \"\"\" Speed of orbiting satellite at a radius r in meters, orbiting a planet\n with mass M in kilograms. Returns speed in m/s\"\"\"\n return np.sqrt(const.G * M / r)\n\n M = self.system.masses[planet_idx] * const.m_sun\n R = self.system.radii[planet_idx]\n orbit_radius_factor = random_state.uniform(lower_lim_radius, upper_lim_radius)\n sat_orbit_radius = orbit_radius_factor * R\n v_sat = sat_speed(M, sat_orbit_radius * 1000.0) / 1000.0\n omega_sat = v_sat / sat_orbit_radius\n T_sat = 2 * const.pi / omega_sat\n T_sat_hr = T_sat / 3600\n person_pos0 = R * np.array([np.cos(angular_position), np.sin(angular_position), 0])\n person_pos = np.zeros(shape=(N, 3))\n person_pos[:] = utils.km_to_AU(person_pos0)\n sat1_pos = np.zeros(shape=(N, 3))\n sat2_pos = np.zeros(shape=(N, 3))\n cam_pos = np.zeros(shape=(N, 3))\n cam_pos[:] = person_pos[:] * height_factor\n tot_time = sat_sys_angular_dist / omega_sat\n times_earth = np.linspace(0, tot_time, N)\n times_earth_copy = np.copy(times_earth)\n times_sat = np.copy(times_earth)\n if GR:\n times_sat /= time_diff_shells(M, R * 1000.0, sat_orbit_radius * 1000.0, v_sat * 1000.0)\n sat1_pos[:, 0] = utils.km_to_AU(sat_orbit_radius) * np.cos(angular_position + sat_sys_angular_dist / 2 + ang_dist_between_sats / 2 - omega_sat * times_earth)\n sat1_pos[:, 1] = utils.km_to_AU(sat_orbit_radius) * np.sin(angular_position + sat_sys_angular_dist / 2 + ang_dist_between_sats / 2 - omega_sat * times_earth)\n sat2_pos[:, 0] = utils.km_to_AU(sat_orbit_radius) * np.cos(angular_position + sat_sys_angular_dist / 2 - ang_dist_between_sats / 2 - omega_sat * times_earth)\n sat2_pos[:, 1] = utils.km_to_AU(sat_orbit_radius) * np.sin(angular_position + sat_sys_angular_dist / 2 - ang_dist_between_sats / 2 - omega_sat * times_earth)\n middle = 0.55 * np.copy(sat1_pos) + 0.45 * sat2_pos[:]\n cam_dir = middle - np.copy(cam_pos[:])\n cam_up = np.zeros(shape=(N, 3))\n sat_normalized = middle / np.linalg.norm(middle, axis=1)[:, None]\n cam_up[:int(N / 2), 0] = np.linspace(sat_normalized[(0, 1)], 0, int(N / 2))\n cam_up[int(N / 2):, 0] = np.linspace(0, sat_normalized[(0, 1)], int(N / 2))\n cam_up[:int(N / 2), 1] = np.linspace(-sat_normalized[(0, 0)], 0, int(N / 2))\n cam_up[int(N / 2):, 1] = np.linspace(0, -sat_normalized[(0, 0)], int(N / 2))\n z_upvec = np.zeros(N)\n z_upvec[:(int(N / 2))] = self._focus_tanhyper(int(N / 2))\n z_upvec[(int(N / 2)):] = np.flipud(z_upvec[:int(N / 2)])\n cam_up[:, 2] = z_upvec[:]\n t_received1 = np.zeros(N)\n t_received2 = np.zeros(N)\n for i in range(N):\n dt1 = np.linalg.norm(sat1_pos[i] - person_pos[i]) / const.c_AU_pr_s\n dt2 = np.linalg.norm(sat2_pos[i] - person_pos[i]) / const.c_AU_pr_s\n t_received1[i] = times_earth[i] - dt1\n t_received2[i] = times_earth[i] - dt2\n\n pos_sat1_seen_from_plan = sat1_pos\n pos_sat2_seen_from_plan = sat2_pos\n t_sat1_vid = np.copy(t_received1)\n t_sat2_vid = np.copy(t_received2)\n if GR:\n t_sat1_vid /= time_diff_shells(M, R * 1000.0, sat_orbit_radius * 1000.0, v_sat * 1000.0)\n t_sat2_vid /= time_diff_shells(M, R * 1000.0, sat_orbit_radius * 1000.0, v_sat * 1000.0)\n sat1_messages = []\n sat2_messages = []\n for i in range(N):\n if t_sat1_vid[i] > 0:\n sat1_messages.append('[%.*f, %.*f] , t = %.*f' % (n_dec_pos, utils.AU_to_km(pos_sat1_seen_from_plan[(i, 0)]), n_dec_pos, utils.AU_to_km(pos_sat1_seen_from_plan[(i, 1)]), n_dec_t, t_sat1_vid[i]))\n else:\n sat1_messages.append('')\n if t_sat2_vid[i] > 0:\n sat2_messages.append('[%.*f, %.*f] , t = %.*f' % (n_dec_pos, utils.AU_to_km(pos_sat2_seen_from_plan[(i, 0)]), n_dec_pos, utils.AU_to_km(pos_sat2_seen_from_plan[(i, 1)]), n_dec_t, t_sat2_vid[i]))\n else:\n sat2_messages.append('')\n\n other_objects = [\n self._object_list('sat1', 'Satellite', sat1_pos, 1.3, [1, 1, 1], msg_list=sat1_messages),\n self._object_list('sat2', 'Satellite', sat2_pos, 1.3, [1, 1, 1], msg_list=sat2_messages)]\n if print_solution:\n camera_messages = [ 'Solution position: [%.*f km, %.*f km] \\nPlanet radius: %.*f km \\nt = %.*f s (Earth clock)' % (n_dec_pos, person_pos0[0], n_dec_pos, person_pos0[1], n_dec_pos, self.system.radii[planet_idx], n_dec_t, times_earth[i]) for i in range(N) ]\n else:\n camera_messages = [ 't = %.*f s (Earth clock)\\nPlanet mass = %.12E kg, Planet radius = %.*f km' % (n_dec_t, times_earth[i], M, 7, R) for i in range(N) ]\n self._write_to_xml(times_earth_copy, cam_pos, cam_dir, [0, 0, 0], other_objects, up_vec=cam_up, planet_idx=planet_idx, filename=filename, camera_messages=camera_messages, show_clock=0, toggle_clock=False)\n if self._write_solutions:\n solution_name = 'Solutions_gps.txt'\n solution_2C = open(os.path.join(self._solution_path, solution_name), 'w')\n solution_2C.write('Solutons to 2C.8\\n')\n solution_2C.write('1. Hight of the satellites: r=%f km\\n' % sat_orbit_radius)\n solution_2C.write('2. Velocity of the satellites: v=%f km/s\\n' % v_sat)\n solution_2C.write('5. Your actual position in km: r=[%f,%f]\\n' % (person_pos0[0], person_pos0[1]))\n solution_2C.close()\n return\n\n def black_hole_schedules(self, distance, filename='black_hole_schedules.xml', number_of_video_frames=1000):\n \"\"\"Two astronauts living in spaceships orbiting respectively close to and far from a black hole are sending each other messages about their schedule.\n\n Generates the XML files used in Exercise 2 in Part 2C of the lecture notes.\n\n Note\n ----\n For each scheduled activity you will be asked to input an associated time and message.\n\n Parameters\n ----------\n distance : {'close', 'far'}\n Whether the observer should be the one close to or far from the black hole.\n filename : str, optional\n The base filename to use for the XML file.\n Note that an extra label will be added to the inputted file name to indicate whether the observer is close or far.\n Default is \"black_hole_schedules.xml\".\n number_of_video_frames : int, optional\n The number of video frames to use in the XML files.\n Can be reduced to reduce file size, but be aware that this might lead to errors.\n Default is 1000, but must be at least 100.\n \"\"\"\n distance = str(distance).lower()\n if distance not in ('close', 'far'):\n raise ValueError('Argument \"distance\" is %s but must be either \"close\" or \"far\".' % distance)\n filename = str(filename)\n filename_base = ('.').join(filename.split('.')[:-1]) if '.' in filename else filename\n filename = '%s_%s.xml' % (filename_base, distance)\n N = int(number_of_video_frames)\n if N < 100:\n raise ValueError('Argument \"number_of_video_frames\" is %d but must be at least 100.' % N)\n nevents = 6\n events_messages_far = ['Finally a new fantastic day!!!',\n 'Egg and bacon directly from the planet, wonderful breakfast!!',\n 'Excellent lunch today, soooo good.',\n 'Had a really nice dinner, yummi!',\n 'Brushing, brushing!',\n 'So sad, the day is already over, good night everbody!']\n events_messages_close = [\n 'Oooh, nooo, another day, do I really need to wake up?',\n 'Not hungry, no breakfast for me please.',\n \"I just hate these space lunches, why can't somebody invent better space food.\",\n 'Space food again, all dinners are equal here :(',\n 'Hate the tooth brushing, the space tooth paste tastes almost as bad as the dinner.',\n 'Finally the boring day out here in space is over, good night!']\n events_messages_sat = [\n 'Wake up!', 'Breakfast', 'Lunch', 'Dinner', 'Brush teeth', 'Good night']\n if self._debug:\n print('Transforming from ', distance, ' observer')\n\n def transform(dt, black_hole_mass, radius, to_long_dist=False):\n m = black_hole_mass\n r = radius\n if to_long_dist:\n dt_long_dist = dt / np.sqrt(1 - 2 * m / r)\n if self._debug:\n print('Transform from shell obs to long dist')\n return dt_long_dist\n dt_shell = dt * np.sqrt(1 - 2 * m / r)\n if self._debug:\n print('Transform from long dist to shell obs')\n return dt_shell\n\n def hours_to_sec(time_str):\n dt_array = np.zeros((len(time_str), 2))\n seconds = np.zeros(len(time_str))\n for i in range(len(time_str)):\n dt_array[i, :] = time_str[i].split(':')\n seconds[i] = dt_array[(i, 0)] * 60 * 60 + dt_array[(i, 1)] * 60\n\n return seconds\n\n def sec_to_clockhours(time):\n ttime = np.copy(time)\n days = np.floor(ttime / 86400.0)\n ttime -= days * 60.0 * 60.0 * 24.0\n hours = np.floor(ttime / 3600)\n sec_left = ttime - hours * 60 * 60\n minutes = str(int(np.floor(sec_left / 60)))\n hours = str(int(hours))\n if len(hours) == 1:\n hours = '0' + hours\n if len(minutes) == 1:\n minutes = '0' + minutes\n return 'Day: ' + str(int(days)) + ' Time: ' + hours + ':' + minutes\n\n random_state = np.random.RandomState(self.seed + utils.get_seed('black_hole_schedules'))\n upper_mass = 50\n black_hole_mass = random_state.uniform(30, upper_mass)\n black_hole_mass_kg = black_hole_mass * const.m_sun\n black_hole_mass_m = utils.kg_to_m(black_hole_mass_kg)\n schw_radius = 2 * utils.kg_to_m(black_hole_mass_kg)\n other_obs_r = schw_radius * random_state.uniform(8, 12)\n obs_r = schw_radius * random_state.uniform(1.05, 1.1)\n if distance.lower() == 'close':\n close = True\n else:\n obs_r, other_obs_r = other_obs_r, obs_r\n close = False\n mass_scl = 30.0\n obs_real = np.copy(obs_r) * mass_scl\n other_obs_real = np.copy(other_obs_r) * mass_scl\n schw_radius_real = np.copy(schw_radius) * mass_scl\n black_hole_mass_m *= mass_scl\n black_hole_mass *= mass_scl\n black_hole_mass_kg *= mass_scl\n other_dt_list = [\n '09:00', '10:00', '13:30', '19:00', '22:30', '23:00']\n dt_list = ['06:00', '07:00', '12:00', '18:00', '23:15', '23:30']\n if self._debug:\n print('Using set test times:', dt_list)\n if not self._run_in_test_mode:\n dt_listin = []\n ev_messages = []\n print('Good evening captain!')\n print(\"Let's make a schedule for tomorrow...\")\n print('Please answer using 24 hours clock format split by \":\" as xx:xx.')\n terminal_messesages = ['Wake up at --> ', 'Breakfast at --> ', 'Lunch at --> ', 'Dinner at --> ', 'Brush your teeth at --> ', 'Go to bed at --> ']\n for text in terminal_messesages:\n try:\n t = raw_input(text).strip()\n except:\n t = input(text).strip()\n\n if len(t) != 5:\n raise IndexError('Format for times must be xx:xx, e.g. 03:10')\n dt_listin.append(t)\n\n terminal_messesages = [\n 'Write a message you want to send to your colleague when you wake up: ', 'Write a message you want to send to your colleague when you have breakfast: ', 'Write a message you want to send to your colleague when you have lunch: ', 'Write a message you want to send to your colleague when you have dinner: ', 'Write a message you want to send to your colleague when you brush your teeth: ', 'Write a message you want to send to your colleague when you go to bed: ']\n for text in terminal_messesages:\n try:\n t = raw_input(text).strip()\n except:\n t = input(text).strip()\n\n ev_messages.append(t)\n if close:\n events_messages_close = ev_messages\n dt_list = dt_listin\n else:\n events_messages_far = ev_messages\n dt_list = dt_listin\n\n else:\n if close:\n dt_list, other_dt_list = other_dt_list, dt_list\n dt_list.append('24:00')\n print('Given times:', dt_list)\n upper_mass_m = upper_mass * utils.kg_to_m(const.m_sun)\n lower_schw_radius = 2.1 * upper_mass_m\n dt_clock = dt_list\n dt_list = hours_to_sec(dt_list)\n dt_array = np.asarray(dt_list)\n other_dt_list_text = np.copy(other_dt_list)\n other_dt_list = hours_to_sec(other_dt_list)\n dt_long = transform(dt_array, black_hole_mass_m, other_obs_real, to_long_dist=True)\n dt_other_obs = transform(dt_long, black_hole_mass_m, obs_real, to_long_dist=False)\n if close:\n time = np.linspace(0, 86400, N)\n else:\n time = np.linspace(0, dt_other_obs[(-1)] + 10800, N)\n length_of_other_day = dt_other_obs[(-1)]\n indlist = []\n ndays = int(np.ceil(time[(-1)] / length_of_other_day))\n for d in range(ndays):\n for t in dt_other_obs[0:-1]:\n tt = t + d * length_of_other_day\n if tt < time[(-1)]:\n indlist.append(np.argmin(np.abs(time - tt)))\n\n indlist = np.array(indlist)\n length_of_day = 86400\n locindlist = []\n ndays = int(np.ceil(time[(-1)] / length_of_day))\n for d in range(ndays):\n for t in other_dt_list:\n tt = t + d * length_of_day\n if tt < time[(-1)]:\n locindlist.append(np.argmin(np.abs(time - tt)))\n\n locindlist = np.array(locindlist)\n cam_message = []\n for i in range(N):\n cam_message.append(sec_to_clockhours(time[i]) + '\\nBlack hole of %g solar masses \\nYour position r = %f km \\nThe other observer in position r= %f km' % (black_hole_mass, obs_real / 1000.0, other_obs_real / 1000.0))\n\n dscl = 50000.0\n planet_radius = utils.km_to_AU(self.system.radii[0])\n if close:\n sc_pos = np.array([utils.m_to_AU(obs_r), 0, 0])\n planet_pos = np.array([utils.m_to_AU(obs_r) + 10 * planet_radius, 0, 0])\n else:\n sc_pos = np.array([utils.m_to_AU(other_obs_r), 0, 0]) * dscl\n planet_pos = np.array([utils.m_to_AU(other_obs_r) + 10 * planet_radius, 0, 0]) * dscl\n sc_plt_pos = planet_pos + np.array([0.1, 0, 0]) * dscl\n if close:\n cam_pos = sc_plt_pos + np.array([utils.km_to_AU(2000), 0, utils.km_to_AU(1000)])\n cam_dir = (sc_pos - sc_plt_pos) / np.linalg.norm(sc_pos - sc_plt_pos)\n else:\n cam_pos = sc_pos + np.array([utils.km_to_AU(-2000), 0, utils.km_to_AU(1000)]) * dscl\n cam_dir = (sc_plt_pos - sc_pos) / np.linalg.norm(sc_plt_pos - sc_pos)\n expl_message = [ '' for i in range(N) ]\n if close:\n planet_pos = cam_pos + cam_dir * utils.km_to_AU(8000.0) + np.array([0.0, utils.km_to_AU(10000), 0])\n expl_pos = cam_pos + cam_dir * utils.km_to_AU(200)\n else:\n planet_pos = cam_pos + cam_dir * utils.m_to_AU(np.abs(obs_real - other_obs_real))\n expl_pos = cam_pos + cam_dir * utils.km_to_AU(200) + np.array([0, utils.km_to_AU(-50), 0])\n sc_pos = cam_pos + cam_dir * utils.km_to_AU(2000.0) + np.array([0.0, utils.km_to_AU(1000), utils.km_to_AU(-1000)])\n expl_color = np.array([1, 1, 1])\n expl_visible = np.zeros(N)\n cnt = 0\n for index in indlist:\n for i in range(20):\n ii = np.amin([index + i, N - 1])\n expl_visible[ii] = 1\n if close:\n expl_message[ii] = events_messages_close[cnt] + '\\n ' + str(sec_to_clockhours(time[index]))\n else:\n expl_message[ii] = events_messages_far[cnt] + '\\n ' + str(sec_to_clockhours(time[index]))\n\n cnt += 1\n if cnt == nevents:\n cnt = 0\n\n sat1_messages = [ '' for i in range(N) ]\n sat2_messages = [ '' for i in range(N) ]\n for index in locindlist:\n for i in range(20):\n ii = np.amin([index + i, N - 1])\n sat1_messages[ii] = events_messages_sat[cnt] + ' ' + other_dt_list_text[cnt]\n\n cnt += 1\n if cnt == nevents:\n cnt = 0\n\n if close:\n sat1_messages, sat2_messages = sat2_messages, sat1_messages\n obj_list = [\n [\n 'Sat1', 'Satellite', sc_pos, 1.5, [0.7, 0.2, 0.3], sat1_messages, None, None, None],\n [\n 'Sat2', 'Satellite', sc_plt_pos, 1.5, [0.2, 0.2, 0.7], sat2_messages, None, None, None],\n [\n 'Light', 'explosion', expl_pos, 100, expl_color, expl_message, None, expl_visible, None]]\n self._write_to_xml(time, cam_pos, cam_dir, camera_messages=cam_message, other_objects=obj_list, planet_pos=planet_pos, filename=filename, field_of_view=90, use_obj_scaling=None, origo_location=np.array([0, 0, 0]), black_hole=True, toggle_clock=False)\n if self._write_solutions:\n solution_name = 'Solutions_black_hole_schedules.txt'\n solution_2C = open(os.path.join(self._solution_path, solution_name), 'w')\n solution_2C.write('Solutons to 2C.2\\n')\n solution_2C.write('Mass of black hole in meters: %f\\n' % black_hole_mass_m)\n solution_2C.write('Times for \"close\" observer in seconds:\\n')\n if not close:\n for time in dt_list:\n solution_2C.write('%g, ' % float(time))\n\n else:\n for time in other_dt_list:\n solution_2C.write('%g, ' % float(time))\n\n solution_2C.write('\\nTimes for \"far\" observer in seconds:\\n')\n if not close:\n for time in other_dt_list:\n solution_2C.write('%g, ' % float(time))\n\n else:\n for time in dt_list:\n solution_2C.write('%g, ' % float(time))\n\n solution_2C.close()\n return\n\n def _set_solution_path(self, solution_path='Solutions'):\n \"\"\"Specifies whether and where to write solution text files.\n\n Parameters\n ----------\n solution_path : str, optional\n Specifies the path to the directory where output solution text files should be stored.\n By default, a folder called \"Solutions\" is created in the working directory.\n \"\"\"\n self._write_solutions = solution_path is not None\n if self._write_solutions:\n self._solution_path = os.path.abspath(str(solution_path))\n if not os.path.isdir(self._solution_path):\n os.mkdir(self._solution_path)\n return\n\n def _set_debugging(self, activate_debugging):\n self._debug = bool(activate_debugging)\n\n def _set_test_mode(self, activate_test_mode):\n self._run_in_test_mode = bool(activate_test_mode)\n\n def _lambda_to_RGB(self, lambda_m):\n lambda_m = np.copy(lambda_m) / 1e-09\n if lambda_m <= 450:\n rgb = [\n 255, 1, 255]\n if 450 < lambda_m <= 495:\n rgb = [\n 0, 1, 255]\n if 495 < lambda_m <= 570:\n rgb = [\n 1, 255, 1]\n if 570 < lambda_m <= 590:\n rgb = [\n 255, 255, 1]\n if 590 < lambda_m <= 620:\n rgb = [\n 255, 50, 1]\n if lambda_m > 620:\n rgb = [\n 255, 5, 5]\n return rgb\n\n def _write_to_xml(self, time_array, cam_pos, cam_dir, planet_pos=np.array([0, 0, 0]), other_objects=[], camera_messages=None, planet_messages=None, ruler=None, up_vec=np.array([0, 0, 1]), field_of_view=70, filename='test_data.xml', planet_idx=0, c=const.c_AU_pr_s, laser_scale=1, use_obj_scaling=1, cheat_light_speed=False, origo_location=np.array([1, 0, 0]), black_hole=False, play_speed=None, show_clock=1, planet2_pos=None, planet3_pos=None, chosen_planet2=1, chosen_planet3=2, toggle_clock=True):\n \"\"\"\n All positions are given relative to a virtual origo, which is then moved to [1,0,0]AU before sent to MCAst.\n @ time_array = Array of the timepoints to simulate.\n @ cam_pos = Array of camera positions at given timepoints. Shape (nr_frames, 3)\n or (3,) for static camera position.\n @ cam_dir = Array of camera directions. Either direction vector\n with shape (nr_frames, 3) or direction angles\n with shape (nr_frames, 2). Can also be (3,) and (2,) for static direction.\n First angle is upwards/downwards (0 - pi), second angle is in plane (0 - 2pi).\n @ planet_pos = Static position of planet. Shape (nr_frames, 3) or (3,). Defaults to [0,0,0].\n @ other_objects = Nested list with info about all non-planet/rocket objects. Shape (nr_objects, 7)\n [Object name, Object string, Object positions array, Size scale, Color, Message list, Sound list, Visibility list, Orientation]\n @ Object name = Name of object (only shows up in SSView)\n @ Object string = Object type. Valid input: \"Satellite\", \"Sphere01\", \"Explosion\", Laser.\n @ Object positions array = Shape (nr_frames, 3)\n @ Size scale = Shape scaling of object, scalar.\n @ Color = RGB. Values between 0 and 1. Shape (3,)\n @ Message list = List of object-specific messages each frame, Shape = (nr_frames). Send None for no messages.\n @ Sound list = List of object specific sounds. Shape = (nr_frames). Send None for no sounds.\n @ Visibility list = Visibility of object each frame, 0 or 1. Shape = (nr_frames). Send None for always visible.\n @ Orientation = 3-vector orientation of object. Optional, Auto-orient by default (Value None).\n @ camera_messages = messages displayed on screen. Shape = (nr_frames).\n @ planet_messages = messages displayed on planet. Shape = (nr_frames).\n @ ruler = Information about ruler. List with [rulerStart, rulerEnd, ticks, rulerUnit, rulerDistance, rulerHeight (0-1) defult 0.13 not necesarry to enter].\n If no argument is provided there will be no ruler.\n @ c = Light speed in your system. If you want no componentwise\n scaling of moving objects, simply set this to a reasonably large value. By default c in AU/s.\n @ laser_scale = Laser scale in the direction it is moving in.\n @ use_obj_scaling = 1 by default, if u dont want any objects scaled change to not 1\n @ origo_location = Location of events are sent relative to a local origo (e.g. center of planet).\n This variable transitions that origo to a position relative to the sun.\n @ up_vec = Upward direction vector of camera, Shape = (3,) or (nr_frames, 3)\n @ show_clock = Toggle whether to show clock or not. 1 (default) is on, 0 off\n \"\"\"\n self._cheat_light_speed = cheat_light_speed\n if self._debug:\n print('Entering SR XML writer with seed: %d and chosen planet: %d' % (self.seed, planet_idx))\n nr_frames = len(time_array)\n time_array = np.copy(time_array)\n cam_pos = np.copy(cam_pos)\n cam_dir = np.copy(cam_dir)\n planet_pos = np.copy(planet_pos)\n other_objects = np.copy(other_objects)\n if time_array[(-1)] - time_array[0] >= 1:\n clock_time_array = np.copy(time_array)\n clockUnit = 'seconds'\n else:\n if time_array[(-1)] - time_array[0] >= 0.001:\n clock_time_array = np.copy(time_array) * 1000.0\n clockUnit = 'milli seconds'\n else:\n if time_array[(-1)] - time_array[0] >= 1e-06:\n clock_time_array = np.copy(time_array) * 1000000.0\n clockUnit = 'micro seconds'\n else:\n clock_time_array = np.copy(time_array) * 1000000000.0\n clockUnit = 'nano seconds'\n if np.shape(planet_pos) == (nr_frames, 3):\n if self._debug:\n print('Dynamic planet position.')\n planet_pos = np.array(planet_pos, dtype=np.float64)\n planet_pos += origo_location\n else:\n if np.shape(planet_pos) == (3, ):\n if self._debug:\n print('Static planet position. Castig time axis.')\n planet_pos = np.array(planet_pos, dtype=np.float64)\n planet_pos = np.zeros(shape=(nr_frames, 3)) + planet_pos + origo_location\n else:\n raise IndexError('Parameter \"planet_pos\" has shape %s, expected %s or %s' % (\n np.shape(planet_pos), (3, ), (nr_frames, 3)))\n if planet2_pos is not None:\n planet2_pos = np.copy(planet2_pos)\n if np.shape(planet2_pos) == (nr_frames, 3):\n if self._debug:\n print('Dynamic planet2 position.')\n planet2_pos = np.array(planet2_pos, dtype=np.float64)\n planet2_pos += origo_location\n elif np.shape(planet2_pos) == (3, ):\n if self._debug:\n print('Static planet position. Castig time axis.')\n planet2_pos = np.array(planet2_pos, dtype=np.float64)\n planet2_pos = np.zeros(shape=(nr_frames, 3)) + planet2_pos + origo_location\n else:\n raise IndexError('Parameter \"planet_pos\" has shape %s, expected %s or %s' % (\n np.shape(planet2_pos), (3, ), (nr_frames, 3)))\n if planet3_pos is not None:\n planet3_pos = np.copy(planet3_pos)\n if np.shape(planet3_pos) == (nr_frames, 3):\n if self._debug:\n print('Dynamic planet3 position.')\n planet3_pos = np.array(planet3_pos, dtype=np.float64)\n planet3_pos += origo_location\n elif np.shape(planet3_pos) == (3, ):\n if self._debug:\n print('Static planet position. Castig time axis.')\n planet3_pos = np.array(planet3_pos, dtype=np.float64)\n planet3_pos = np.zeros(shape=(nr_frames, 3)) + planet3_pos + origo_location\n else:\n raise IndexError('Parameter \"planet_pos\" has shape %s, expected %s or %s' % (\n np.shape(planet3_pos), (3, ), (nr_frames, 3)))\n if planet_messages is None:\n planet_messages = [ '' for i in range(nr_frames) ]\n if camera_messages is None:\n camera_messages = [ '' for i in range(nr_frames) ]\n if np.shape(cam_pos) == (nr_frames, 3):\n stat_cam_pos = False\n if self._debug:\n print('Dynamic camera position.')\n cam_pos += origo_location\n elif np.shape(cam_pos) == (3, ):\n stat_cam_pos = True\n if self._debug:\n print('Stationary camera position. Introducing time-axis manually.')\n cam_pos = np.zeros(shape=(nr_frames, 3)) + cam_pos + origo_location\n else:\n raise IndexError('Parameter \"cam_pos\" has shape %s, expected %s or %s' % (\n np.shape(cam_pos), (3, ), (nr_frames, 3)))\n dir_shape = np.shape(cam_dir)\n if dir_shape == (nr_frames, 2):\n stat_cam_uses_angles = False\n cam_uses_angles = True\n if self._debug:\n print('Dynamic camera angles.')\n elif dir_shape == (2, ):\n stat_cam_uses_angles = True\n cam_uses_angles = True\n if self._debug:\n print('Static camera angles. Introducing time-axis manually.')\n cam_dir = np.zeros(shape=(nr_frames, 2)) + cam_dir\n elif dir_shape == (nr_frames, 3):\n stat_cam_dir_vec = False\n cam_uses_angles = False\n if self._debug:\n print('Dynamic camera vector.')\n elif dir_shape == (3, ):\n stat_cam_dir_vec = True\n cam_uses_angles = False\n if self._debug:\n print('Static camera vector. Introducing time-axis manually.')\n cam_dir = np.zeros(shape=(nr_frames, 3)) + cam_dir\n else:\n raise IndexError('Parameter \"cam_dir\" has shape %s. Expected %s or %s for angles or %s or %s for vector. Exiting.' % (\n np.shape(cam_dir), (nr_frames, 2), (2, ), (nr_frames, 3), (3, )))\n if cam_uses_angles:\n cam_dir_vec = np.zeros(shape=(nr_frames, 3))\n cam_dir_vec[:, 0] = np.cos(cam_dir[:, 1]) * np.sin(cam_dir[:, 0])\n cam_dir_vec[:, 1] = np.sin(cam_dir[:, 1]) * np.sin(cam_dir[:, 0])\n cam_dir_vec[:, 2] = np.cos(cam_dir[:, 0])\n else:\n cam_dir_vec = np.array(np.copy(cam_dir), dtype=np.float64)\n cam_dir_vec /= np.apply_along_axis(np.linalg.norm, 1, cam_dir_vec)[:, None]\n if str(up_vec) == 'auto':\n sun_vec = planet_pos\n up_vec = np.zeros(shape=(nr_frames, 3))\n for i in range(nr_frames):\n up_vec[i] = np.cross(sun_vec, cam_dir_vec[i])\n\n if up_vec[(0, 2)] < 0:\n up_vec = -up_vec\n if str(up_vec) == 'up':\n up_vec = cam_pos - planet_pos\n if np.shape(up_vec) == (nr_frames, 3):\n up_vec = np.array(up_vec, dtype=np.float64)\n up_vec /= np.apply_along_axis(np.linalg.norm, 1, up_vec)[:, None]\n elif np.shape(up_vec) == (3, ):\n up_vec = np.array(up_vec, dtype=np.float64)\n up_vec /= np.linalg.norm(up_vec)\n up_vec = np.zeros(shape=(nr_frames, 3)) + up_vec\n else:\n raise IndexError('Dust')\n if ruler is not None:\n if len(ruler) > 6 or len(ruler) < 5:\n raise IndexError('Ruler settings list has length %g, expected 5 or 6 if display height is specified.' % len(ruler))\n rulerStart = ruler[0]\n rulerEnd = ruler[1]\n rulerTicks = ruler[2]\n rulerUnit = ruler[3]\n rulerDistance = ruler[4]\n if len(ruler) == 6:\n rulerHeight = ruler[5]\n else:\n rulerHeight = None\n objects = etree.Element('Objects')\n star = etree.SubElement(objects, 'SerializedMCAstObject')\n if black_hole is True:\n etree.SubElement(star, 'category').text = str('black hole')\n else:\n etree.SubElement(star, 'category').text = str('star')\n etree.SubElement(star, 'pos_x').text = str(0)\n etree.SubElement(star, 'pos_z').text = str(0)\n etree.SubElement(star, 'pos_y').text = str(0)\n etree.SubElement(star, 'rot_y').text = str(0)\n if black_hole is True:\n etree.SubElement(star, 'radius').text = str(514702.474211)\n else:\n etree.SubElement(star, 'radius').text = str(self.system.star_radius)\n etree.SubElement(star, 'temperature').text = str(self.system.star_temperature)\n etree.SubElement(star, 'seed').text = str(int(self.seed * 1000 + 990))\n etree.SubElement(star, 'atmosphereDensity').text = str(10)\n etree.SubElement(star, 'atmosphereHeight').text = str(1.025)\n etree.SubElement(star, 'outerRadiusScale').text = str(1.0025)\n etree.SubElement(star, 'name').text = str('The star')\n star_objects = etree.SubElement(star, 'Objects')\n planet_pos_array = np.zeros(shape=(nr_frames, 3))\n planet_pos_array[:] = planet_pos\n if use_obj_scaling == 1:\n if self._debug:\n print('Scaling planet.')\n planet_scales_array = 1 / self._get_lorentz_3D(time_array, cam_pos, planet_pos_array, c, object_name='planet')\n else:\n planet_scales_array = np.ones([nr_frames, 3])\n planet = etree.SubElement(star_objects, 'SerializedMCAstObject')\n etree.SubElement(planet, 'pos_x').text = str(planet_pos[(0, 0)])\n etree.SubElement(planet, 'pos_z').text = str(planet_pos[(0, 1)])\n etree.SubElement(planet, 'pos_y').text = str(planet_pos[(0, 2)])\n etree.SubElement(planet, 'rot_y').text = str(0)\n etree.SubElement(planet, 'seed').text = str(int(self.seed * 1000 + planet_idx))\n etree.SubElement(planet, 'radius').text = str(self.system.radii[planet_idx])\n etree.SubElement(planet, 'temperature').text = str(self.system.star_temperature * np.sqrt(utils.km_to_AU(self.system.star_radius) / (2 * self.system.semi_major_axes[planet_idx])))\n etree.SubElement(planet, 'atmosphereDensity').text = str(np.log(self.system.atmospheric_densities[planet_idx]) / np.log(25))\n etree.SubElement(planet, 'atmosphereHeight').text = str(1.025)\n etree.SubElement(planet, 'outerRadiusScale').text = str(1.0025)\n etree.SubElement(planet, 'category').text = str('planet')\n etree.SubElement(planet, 'name').text = str('planet ' + str(planet_idx))\n frames = etree.SubElement(planet, 'Frames')\n for i in range(nr_frames):\n frame = etree.SubElement(frames, 'Frame')\n etree.SubElement(frame, 'id').text = str(i)\n etree.SubElement(frame, 'pos_x').text = str(planet_pos[(i, 0)])\n etree.SubElement(frame, 'pos_z').text = str(planet_pos[(i, 1)])\n etree.SubElement(frame, 'pos_y').text = str(planet_pos[(i, 2)])\n etree.SubElement(frame, 'displayMessage').text = str(planet_messages[i])\n etree.SubElement(frame, 'rot_y').text = str(0)\n if np.amin(np.abs(planet_scales_array[i, :])) != 1:\n scaledir = np.argmin(np.abs(planet_scales_array[i, :]))\n if np.abs(up_vec[(i, scaledir)]) == 0:\n leftright = 1\n if np.abs(up_vec[(i, scaledir)]) == 1:\n leftright = 0\n if np.abs(up_vec[(i, 0)]) == 1 and leftright == 1:\n if scaledir == 1:\n etree.SubElement(frame, 'scale_z').text = str(planet_scales_array[(i, scaledir)])\n if scaledir == 2:\n etree.SubElement(frame, 'scale_y').text = str(planet_scales_array[(i, scaledir)])\n if np.abs(up_vec[(i, 0)]) == 1 and leftright == 0:\n etree.SubElement(frame, 'scale_x').text = str(planet_scales_array[(i, scaledir)])\n if np.abs(up_vec[(i, 1)]) == 1 and leftright == 1:\n etree.SubElement(frame, 'scale_x').text = str(planet_scales_array[(i, scaledir)])\n if np.abs(up_vec[(i, 2)]) == 1 and leftright == 1:\n if scaledir == 1:\n etree.SubElement(frame, 'scale_z').text = str(planet_scales_array[(i, scaledir)])\n if scaledir == 0:\n etree.SubElement(frame, 'scale_x').text = str(planet_scales_array[(i, scaledir)])\n if np.abs(up_vec[(i, 0)]) != 1 and leftright == 0:\n etree.SubElement(frame, 'scale_y').text = str(planet_scales_array[(i, scaledir)])\n\n if planet2_pos is not None:\n planet2_pos_array = np.zeros(shape=(nr_frames, 3))\n planet2_pos_array[:] = planet2_pos\n if use_obj_scaling == 1:\n if self._debug:\n print('Scaling planet2.')\n planet2_scales_array = 1 / self._get_lorentz_3D(time_array, cam_pos, planet2_pos_array, c, object_name='planet2')\n else:\n planet2_scales_array = np.ones([nr_frames, 3])\n planet2 = etree.SubElement(star_objects, 'SerializedMCAstObject')\n etree.SubElement(planet2, 'pos_x').text = str(planet2_pos[(0, 0)])\n etree.SubElement(planet2, 'pos_z').text = str(planet2_pos[(0, 1)])\n etree.SubElement(planet2, 'pos_y').text = str(planet2_pos[(0, 2)])\n etree.SubElement(planet2, 'rot_y').text = str(0)\n etree.SubElement(planet2, 'seed').text = str(int(self.seed * 1000 + chosen_planet2))\n etree.SubElement(planet2, 'radius').text = str(self.system.radii[chosen_planet2])\n etree.SubElement(planet2, 'temperature').text = str(self.system.star_temperature * np.sqrt(utils.km_to_AU(self.system.star_radius) / (2 * self.system.semi_major_axes[chosen_planet2])))\n etree.SubElement(planet2, 'atmosphereDensity').text = str(np.log(self.system.atmospheric_densities[chosen_planet2]) / np.log(25))\n etree.SubElement(planet2, 'atmosphereHeight').text = str(1.025)\n etree.SubElement(planet2, 'outerRadiusScale').text = str(1.0025)\n etree.SubElement(planet2, 'category').text = str('planet2')\n etree.SubElement(planet2, 'name').text = str('planet2 ' + str(chosen_planet2))\n frames = etree.SubElement(planet2, 'Frames')\n for i in range(nr_frames):\n frame = etree.SubElement(frames, 'Frame')\n etree.SubElement(frame, 'id').text = str(i)\n etree.SubElement(frame, 'pos_x').text = str(planet2_pos[(i, 0)])\n etree.SubElement(frame, 'pos_z').text = str(planet2_pos[(i, 1)])\n etree.SubElement(frame, 'pos_y').text = str(planet2_pos[(i, 2)])\n etree.SubElement(frame, 'displayMessage').text = str(planet_messages[i])\n etree.SubElement(frame, 'rot_y').text = str(0)\n if np.amin(np.abs(planet2_scales_array[i, :])) != 1:\n scaledir = np.argmin(np.abs(planet2_scales_array[i, :]))\n if np.abs(up_vec[(i, scaledir)]) == 0:\n leftright = 1\n if np.abs(up_vec[(i, scaledir)]) == 1:\n leftright = 0\n if np.abs(up_vec[(i, 0)]) == 1 and leftright == 1:\n if scaledir == 1:\n etree.SubElement(frame, 'scale_z').text = str(planet2_scales_array[(i, scaledir)])\n if scaledir == 2:\n etree.SubElement(frame, 'scale_y').text = str(planet2_scales_array[(i, scaledir)])\n if np.abs(up_vec[(i, 0)]) == 1 and leftright == 0:\n etree.SubElement(frame, 'scale_x').text = str(planet2_scales_array[(i, scaledir)])\n if np.abs(up_vec[(i, 1)]) == 1 and leftright == 1:\n etree.SubElement(frame, 'scale_x').text = str(planet2_scales_array[(i, scaledir)])\n if np.abs(up_vec[(i, 2)]) == 1 and leftright == 1:\n if scaledir == 1:\n etree.SubElement(frame, 'scale_z').text = str(planet2_scales_array[(i, scaledir)])\n if scaledir == 0:\n etree.SubElement(frame, 'scale_x').text = str(planet2_scales_array[(i, scaledir)])\n if np.abs(up_vec[(i, 0)]) != 1 and leftright == 0:\n etree.SubElement(frame, 'scale_y').text = str(planet2_scales_array[(i, scaledir)])\n\n if planet3_pos is not None:\n planet3_pos_array = np.zeros(shape=(nr_frames, 3))\n planet3_pos_array[:] = planet3_pos\n if use_obj_scaling == 1:\n if self._debug:\n print('Scaling planet3.')\n planet3_scales_array = 1 / self._get_lorentz_3D(time_array, cam_pos, planet3_pos_array, c, object_name='planet3')\n else:\n planet3_scales_array = np.ones([nr_frames, 3])\n planet3 = etree.SubElement(star_objects, 'SerializedMCAstObject')\n etree.SubElement(planet3, 'pos_x').text = str(planet3_pos[(0, 0)])\n etree.SubElement(planet3, 'pos_z').text = str(planet3_pos[(0, 1)])\n etree.SubElement(planet3, 'pos_y').text = str(planet3_pos[(0, 2)])\n etree.SubElement(planet3, 'rot_y').text = str(0)\n etree.SubElement(planet3, 'seed').text = str(int(self.seed * 1000 + chosen_planet3))\n etree.SubElement(planet3, 'radius').text = str(self.system.radii[chosen_planet3])\n etree.SubElement(planet3, 'temperature').text = str(self.system.star_temperature * np.sqrt(utils.km_to_AU(self.system.star_radius) / (2 * self.system.semi_major_axes[chosen_planet3])))\n etree.SubElement(planet3, 'atmosphereDensity').text = str(np.log(self.system.atmospheric_densities[chosen_planet3]) / np.log(25))\n etree.SubElement(planet3, 'atmosphereHeight').text = str(1.025)\n etree.SubElement(planet3, 'outerRadiusScale').text = str(1.0025)\n etree.SubElement(planet3, 'category').text = str('planet3')\n etree.SubElement(planet3, 'name').text = str('planet3 ' + str(chosen_planet3))\n frames = etree.SubElement(planet3, 'Frames')\n for i in range(nr_frames):\n frame = etree.SubElement(frames, 'Frame')\n etree.SubElement(frame, 'id').text = str(i)\n etree.SubElement(frame, 'pos_x').text = str(planet3_pos[(i, 0)])\n etree.SubElement(frame, 'pos_z').text = str(planet3_pos[(i, 1)])\n etree.SubElement(frame, 'pos_y').text = str(planet3_pos[(i, 2)])\n etree.SubElement(frame, 'displayMessage').text = str(planet_messages[i])\n etree.SubElement(frame, 'rot_y').text = str(0)\n if np.amin(np.abs(planet3_scales_array[i, :])) != 1:\n scaledir = np.argmin(np.abs(planet3_scales_array[i, :]))\n if np.abs(up_vec[(i, scaledir)]) == 0:\n leftright = 1\n if np.abs(up_vec[(i, scaledir)]) == 1:\n leftright = 0\n if np.abs(up_vec[(i, 0)]) == 1 and leftright == 1:\n if scaledir == 1:\n etree.SubElement(frame, 'scale_z').text = str(planet3_scales_array[(i, scaledir)])\n if scaledir == 2:\n etree.SubElement(frame, 'scale_y').text = str(planet3_scales_array[(i, scaledir)])\n if np.abs(up_vec[(i, 0)]) == 1 and leftright == 0:\n etree.SubElement(frame, 'scale_x').text = str(planet3_scales_array[(i, scaledir)])\n if np.abs(up_vec[(i, 1)]) == 1 and leftright == 1:\n etree.SubElement(frame, 'scale_x').text = str(planet3_scales_array[(i, scaledir)])\n if np.abs(up_vec[(i, 2)]) == 1 and leftright == 1:\n if scaledir == 1:\n etree.SubElement(frame, 'scale_z').text = str(planet3_scales_array[(i, scaledir)])\n if scaledir == 0:\n etree.SubElement(frame, 'scale_x').text = str(planet3_scales_array[(i, scaledir)])\n if np.abs(up_vec[(i, 0)]) != 1 and leftright == 0:\n etree.SubElement(frame, 'scale_y').text = str(planet3_scales_array[(i, scaledir)])\n\n for other_object in other_objects:\n obj_name = other_object[0]\n obj_string = other_object[1]\n obj_pos_array = other_object[2] + origo_location\n obj_scale = other_object[3]\n obj_color = other_object[4]\n obj_message_list = other_object[5]\n obj_sound_list = other_object[6]\n obj_visible = other_object[7]\n obj_orientation = other_object[8]\n if obj_message_list is None:\n obj_message_list = [ '' for i in range(nr_frames) ]\n if obj_sound_list is None:\n obj_sound_list = [ '' for i in range(nr_frames) ]\n if obj_visible is None or obj_visible is True:\n obj_visible = [ 1 for i in range(nr_frames) ]\n if np.shape(obj_pos_array) == (3, ):\n obj_pos_array = np.zeros(shape=(nr_frames, 3)) + obj_pos_array\n if self._debug:\n print('Making', obj_string, 'object')\n if obj_string == 'Laser':\n obj_scales_array = laser_scale * np.ones(nr_frames)\n else:\n if use_obj_scaling == 1:\n obj_scales_array = 1 / self._get_lorentz(time_array, cam_pos, obj_pos_array, c, object_name=obj_name)\n else:\n obj_scales_array = np.ones(nr_frames)\n obj = etree.SubElement(star_objects, 'SerializedMCAstObject')\n if obj_orientation is None:\n etree.SubElement(obj, 'autoOrient').text = str(1)\n elif np.shape(obj_orientation) == (3, ):\n etree.SubElement(obj, 'autoOrient').text = str(0)\n else:\n raise ValueError('Expected shape (3,) or None for Orientation parameter on object %s. Got shape %s' % (obj_name, np.shape(obj_orientation)))\n etree.SubElement(obj, 'pos_x').text = str(obj_pos_array[(0,\n 0)])\n etree.SubElement(obj, 'pos_z').text = str(obj_pos_array[(0,\n 1)])\n etree.SubElement(obj, 'pos_y').text = str(obj_pos_array[(0,\n 2)])\n if obj_string == 'explosion':\n etree.SubElement(obj, 'category').text = str('explosion')\n else:\n etree.SubElement(obj, 'category').text = str('3dobject')\n etree.SubElement(obj, 'name').text = str(obj_name)\n if obj_string == 'explosion':\n pass\n elif obj_string == 'Laser':\n etree.SubElement(obj, 'objectMaterial').text = str('LaserMaterial')\n etree.SubElement(obj, 'objectString').text = str(obj_string)\n else:\n etree.SubElement(obj, 'objectMaterial').text = str('HullMaterial')\n etree.SubElement(obj, 'objectString').text = str(obj_string)\n etree.SubElement(obj, 'objectScale').text = str(obj_scale)\n etree.SubElement(obj, 'color_r').text = str(obj_color[0])\n etree.SubElement(obj, 'color_g').text = str(obj_color[1])\n etree.SubElement(obj, 'color_b').text = str(obj_color[2])\n frames = etree.SubElement(obj, 'Frames')\n for i in range(nr_frames):\n frame = etree.SubElement(frames, 'Frame')\n etree.SubElement(frame, 'id').text = str(i)\n etree.SubElement(frame, 'pos_x').text = str(obj_pos_array[(i, 0)])\n etree.SubElement(frame, 'pos_z').text = str(obj_pos_array[(i, 1)])\n etree.SubElement(frame, 'pos_y').text = str(obj_pos_array[(i, 2)])\n if obj_sound_list is not None:\n etree.SubElement(frame, 'sound').text = str(obj_sound_list[i])\n if obj_message_list[i] != '':\n etree.SubElement(frame, 'displayMessage').text = str(obj_message_list[i])\n etree.SubElement(frame, 'time').text = str(clock_time_array[i])\n if obj_string == 'explosion':\n etree.SubElement(frame, 'color_r').text = str(obj_color[0])\n etree.SubElement(frame, 'color_g').text = str(obj_color[1])\n etree.SubElement(frame, 'color_b').text = str(obj_color[2])\n if obj_string == 'explosion':\n etree.SubElement(frame, 'scale_x').text = str(obj_scales_array[i])\n else:\n etree.SubElement(frame, 'scale_z').text = str(obj_scales_array[i])\n if obj_visible[i] == 0:\n etree.SubElement(frame, 'visible').text = str(0)\n if obj_orientation is not None:\n etree.SubElement(frame, 'rot_x').text = str(obj_orientation[0])\n etree.SubElement(frame, 'rot_z').text = str(obj_orientation[1])\n etree.SubElement(frame, 'rot_y').text = str(obj_orientation[2])\n\n cameras = etree.Element('Cameras')\n for i in range(nr_frames):\n camera = etree.SubElement(cameras, 'SerializedCamera')\n etree.SubElement(camera, 'cam_x').text = str(cam_pos[(i, 0)])\n etree.SubElement(camera, 'cam_z').text = str(cam_pos[(i, 1)])\n etree.SubElement(camera, 'cam_y').text = str(cam_pos[(i, 2)])\n etree.SubElement(camera, 'dir_x').text = str(cam_dir_vec[(i, 0)])\n etree.SubElement(camera, 'dir_z').text = str(cam_dir_vec[(i, 1)])\n etree.SubElement(camera, 'dir_y').text = str(cam_dir_vec[(i, 2)])\n etree.SubElement(camera, 'up_x').text = str(up_vec[(i, 0)])\n etree.SubElement(camera, 'up_z').text = str(up_vec[(i, 1)])\n etree.SubElement(camera, 'up_y').text = str(up_vec[(i, 2)])\n etree.SubElement(camera, 'fov').text = str(field_of_view)\n etree.SubElement(camera, 'scale_x').text = str(1)\n etree.SubElement(camera, 'scale_z').text = str(1)\n etree.SubElement(camera, 'scale_y').text = str(1)\n etree.SubElement(camera, 'displayMessage').text = camera_messages[i]\n etree.SubElement(camera, 'time').text = str(clock_time_array[i])\n etree.SubElement(camera, 'frame').text = str(i)\n\n with open(os.path.join(self.system.data_path, filename), 'w') as (outfile):\n outfile.write('\\n')\n outfile.write('\\n')\n outfile.write('0.100\\n')\n outfile.write('900\\n')\n outfile.write('900\\n')\n outfile.write('0.985\\n')\n outfile.write('5acbd644-37c7-11e6-ac61-9e71128cae77\\n')\n outfile.write('000\\n')\n if play_speed is None:\n outfile.write('0.6')\n else:\n outfile.write('%f' % play_speed)\n outfile.write('%g' % show_clock)\n if ruler is not None:\n outfile.write('%g\\n' % rulerStart)\n outfile.write('%g\\n' % rulerEnd)\n outfile.write('%g\\n' % rulerTicks)\n outfile.write('%s\\n' % rulerUnit)\n outfile.write('%s\\n' % rulerDistance)\n if rulerHeight == None:\n outfile.write('0.13\\n')\n else:\n outfile.write('%g\\n' % rulerHeight)\n outfile.write('%s\\n' % clockUnit)\n outfile.write(etree.tostring(objects, pretty_print=True, encoding='unicode'))\n outfile.write(etree.tostring(cameras, pretty_print=True, encoding='unicode'))\n outfile.write('%g' % int(toggle_clock))\n outfile.write('')\n print('Video file written to %s. Open and view it in MCAst!' % os.path.join(self.system.data_path, filename))\n return\n\n def _get_lorentz(self, time_array, cam_pos_array, obj_pos_array, c=const.c_AU_pr_s, object_name='unknown'):\n \"\"\"\n Compute lorentz length contraction for an object moving relative\n to the camera for each frame.\n Params:\n @ time_array = Array with time points, shape (nr_frames)\n @ cam_pos_array = Array with camera positions, shape (nr_frames, 3)\n @ obj_pos_array = Array with object positions, shape (nr_frames, 3)\n @ c = Light speed in the system\n Returns:\n @ lorentz = Array with lorentz factor for each frame, shape (nr_frames)\n \"\"\"\n obj_pos_arr = np.copy(obj_pos_array)\n obj_pos_arr = obj_pos_arr - cam_pos_array\n nr_frames = len(time_array)\n vel_array = np.zeros(shape=(nr_frames, 3))\n vel_array[1:, 0] = (obj_pos_arr[1:, 0] - obj_pos_arr[:-1, 0]) / (time_array[1:] - time_array[:-1])\n vel_array[1:, 1] = (obj_pos_arr[1:, 1] - obj_pos_arr[:-1, 1]) / (time_array[1:] - time_array[:-1])\n vel_array[1:, 2] = (obj_pos_arr[1:, 2] - obj_pos_arr[:-1, 2]) / (time_array[1:] - time_array[:-1])\n vel_array[(0, 0)] = (obj_pos_arr[(1, 0)] - obj_pos_arr[(0, 0)]) / (time_array[1] - time_array[0])\n vel_array[(0, 1)] = (obj_pos_arr[(1, 1)] - obj_pos_arr[(0, 1)]) / (time_array[1] - time_array[0])\n vel_array[(0, 2)] = (obj_pos_arr[(1, 2)] - obj_pos_arr[(0, 2)]) / (time_array[1] - time_array[0])\n absvels = np.apply_along_axis(np.linalg.norm, 1, vel_array)\n maxvel = np.max(absvels)\n if self._cheat_light_speed is False:\n if maxvel > c:\n raise ValueError('Detected maximum speed of %g in object %s, light speed is %g' % (maxvel, object_name, c))\n if self._cheat_light_speed is True:\n for i in range(len(absvels)):\n if absvels[i] > c:\n absvels[i] = 0\n\n lorentz = 1 / np.sqrt(1 - absvels ** 2 / c ** 2)\n return lorentz\n\n def _get_lorentz_3D(self, time_array, cam_pos_array, obj_pos_array, c=const.c_AU_pr_s, object_name='unknown'):\n \"\"\"\n Compute lorentz length contraction for an object moving relative\n to the camera for each frame.\n Params:\n @ time_array = Array with time points, shape (nr_frames)\n @ cam_pos_array = Array with camera positions, shape (nr_frames, 3)\n @ obj_pos_array = Array with object positions, shape (nr_frames, 3)\n @ c = Light speed in the system\n Returns:\n @ lorentz = Array with lorentz factor for each frame, shape (nr_frames)\n \"\"\"\n obj_pos_arr = np.copy(obj_pos_array)\n obj_pos_arr = obj_pos_arr - cam_pos_array\n nr_frames = len(time_array)\n vel_array = np.zeros(shape=(nr_frames, 3))\n vel_array[1:, 0] = (obj_pos_arr[1:, 0] - obj_pos_arr[:-1, 0]) / (time_array[1:] - time_array[:-1])\n vel_array[1:, 1] = (obj_pos_arr[1:, 1] - obj_pos_arr[:-1, 1]) / (time_array[1:] - time_array[:-1])\n vel_array[1:, 2] = (obj_pos_arr[1:, 2] - obj_pos_arr[:-1, 2]) / (time_array[1:] - time_array[:-1])\n vel_array[(0, 0)] = (obj_pos_arr[(1, 0)] - obj_pos_arr[(0, 0)]) / (time_array[1] - time_array[0])\n vel_array[(0, 1)] = (obj_pos_arr[(1, 1)] - obj_pos_arr[(0, 1)]) / (time_array[1] - time_array[0])\n vel_array[(0, 2)] = (obj_pos_arr[(1, 2)] - obj_pos_arr[(0, 2)]) / (time_array[1] - time_array[0])\n maxvel = np.max(vel_array)\n if self._cheat_light_speed is False:\n if maxvel > c:\n raise ValueError('Detected maximum speed of %g in object %s, light speed is %g' % (maxvel, object_name, c))\n if self._cheat_light_speed is True:\n vel_array[np.abs(vel_array) > c] = 0.999 * c\n lorentz = 1 / np.sqrt(1 - vel_array ** 2 / c ** 2)\n return lorentz\n\n def _lorentz_transform(self, t, pos, v, c=const.c_AU_pr_s):\n \"\"\"\n Transformation of position/time 4-vector of event from rest-frame to moving frame.\n To transform an event from moving frame to rest frame, send in negative v.\n This function now only takes in 1-dimmentional movement along the axis of movement.\n All objects must be positioned, and move in the same one-dimmentional axis.\n INPUT\n @ pos = Position of events in rest frame along axis of movement. Shape = (nr_events)\n @ t = Time of event in rest frame. Shape = (nr_events).\n @ v = Speed of moving frame along movement axis. Shape = (nr_events) or scalar.\n RETURNS\n @ pos_marked = Poisitions of events in moving frame, along axis of movement. Shape = (nr_events)\n @ t_marked = Time of events in moving frame. Shape = (nr_events)\n \"\"\"\n if np.sum(np.abs(v) >= c) > 0:\n print('Speed v = %f cannot exceed the speed of light, c = %f!' % (v, c))\n raise ValueError('v cannot exceed the speed of light')\n gamma = 1.0 / np.sqrt(1 - v ** 2 / c ** 2)\n t_marked = -v * gamma * pos / c ** 2 + gamma * t\n pos_marked = gamma * pos - v * gamma * t\n return (t_marked, pos_marked)\n\n def _focus_tanhyper(self, NR_frames_used, start=None, time=None):\n \"\"\"\n Hyperbolic function to change focus or position smoothly\n Returns V array from 0 to 1 of two posible shapes(NR_frames,) or (time,)\n @ NR_frames_used Number of frames used to change focus\n @ time if provided, shape(V) = (len(time),) IF u want V\n to go over the hole time, otherwise shape(V) = (NR_frames_used,)\n @ start if provided, start = indices of time, where change of focus\n should start, and last over NR_frames_used, otherwise start at begining\n \"\"\"\n x = np.linspace(-2.5, 2.5, NR_frames_used)\n if np.shape(time) == ():\n V = np.tanh(x)\n V += abs(np.min(V))\n V = V / np.max(V)\n else:\n V = np.zeros([len(time)])\n if start is not None:\n V[start:(start + NR_frames_used)] = np.tanh(x)\n V[start:start + NR_frames_used] += abs(np.min(V))\n V[start + NR_frames_used:] += V[(start + NR_frames_used - 1)]\n else:\n V[:NR_frames_used] = np.tanh(x)\n V[:NR_frames_used] += abs(np.min(V))\n V[NR_frames_used:] += V[(NR_frames_used - 1)]\n V = V / np.max(V)\n return V\n\n def _velocity_transformation(self, v_observer, v_object):\n \"\"\"\n WARNING: Only takes natural units (fractions of c)\n @ v_observer = velocity of new observer relative to rest frame(old observer).\n @ v_object = velocity of observed object relative to rest frame(old observer).\n RETURN = velocity of object relative to the new observer.\n \"\"\"\n return (v_object - v_observer) / (1 - v_observer * v_object)\n\n def _get_ruler_length(self, distance_to_object, field_of_view=70):\n \"\"\"\n @ distance_to_object = distance to object we wish to measure with our ruler.\n @ field_of_view = camera field of view in degrees.\n RETURN = length of ruler in the same units as distance_to_object\n \"\"\"\n return 2 * distance_to_object * np.tan(utils.deg_to_rad(field_of_view / 2)) * 1.7777777777777777\n\n def _ref_sys_interpolate_func(self, time_array, pos_array, v):\n \"\"\"\n @ time_array = time of positions in original frame of reference.\n @ pos_array = corresponding positions in original frame of reference.\n @ v = velocity of new frame of reference relative to original.\n Units in AU and seconds.\n RETURNS = Callable function which returns positions of event in new reference frame given a timepoint.\n \"\"\"\n new_time_array, new_pos_array = self._lorentz_transform(time_array, pos_array, v)\n return interpolate.interp1d(new_time_array, new_pos_array, kind='linear', bounds_error=False, fill_value='extrapolate', assume_sorted=True)\n\n def _relativistic_doppler_shift(self, v, c=const.c_AU_pr_s):\n \"\"\"\n wl : Wavelength (lambda in the lecture notes)\n Formula from part 2b.\n delta wl / wl = ( sqrt ([1 + v]/[1 - v]) - 1 )\n @ v = Speed of object that emits light relative to observer in AU/s.\n @ c = Speed of light in your system\n RETURNS = delta wl / wl. (Relative change of wavelength)\n \"\"\"\n return np.sqrt((1 + v) / (1 - v)) - 1\n\n def _object_list(self, obj_name, obj_type, pos, scale=1, color_rgb=[\n 1, 1, 1], msg_list=None, sound_list=None, visible=None, orient=None):\n \"\"\" Formats input about an object to a list which can be sent to the writer\"\"\"\n return [\n obj_name, obj_type, pos, scale, color_rgb, msg_list, sound_list,\n visible, orient]","sub_path":"pycfiles/ast2000tools-1.0.23-py27-none-any/relativity.py","file_name":"relativity.py","file_ext":"py","file_size_in_byte":248073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"366044460","text":"#!/usr/bin/env python\n#coding=utf-8 \nimport os\nimport requests\nimport webbrowser\nimport subprocess\nimport shutil\nimport time\nimport commands\n\n\n#打包后的ipa文件路径\nbackupIPA = '/Users/apple/Desktop/ProgramIpa'\n#应用对应蒲公英路径\nopenUrlPath = 'https://www.pgyer.com/manager/xxxxxxxxxxxxxx/app/'\n#应用下载页\nopenDownLoadUrlPath = 'https://www.pgyer.com/xxxxxxxxxxxxxx'\n#项目scheme\nschemeName = 'xxxxxxxxxxxxxx'\n\n#蒲公英账号USER_KEY、API_KEY及App_Key\nUSER_KEY = \"xxxxxxxxxxxxxx\"\nAPI_KEY = \"xxxxxxxxxxxxxx\"\nApp_Key = \"xxxxxxxxxxxxxx\"\n\n#clean工程\ndef cleanPro():\n #开始时间\n start = time.time()\n if desDv == 1:\n desDvStr = 'Release'\n else:\n desDvStr = 'Debug'\n #xcodeproj工程\n cleanProRun = 'xcodebuild clean -project %s.xcodeproj -scheme %s -configuration %s'%(schemeName,schemeName,desDvStr)\n #workspace工程\n #cleanProRun = 'xcodebuild clean -workspace %s.xcworkspace -scheme %s -configuration %s'%(schemeName,schemeName,desDvStr)\n \n print('%s'%cleanProRun)\n cleanProcessRun = subprocess.Popen(cleanProRun,shell=True)\n cleanProcessRun.wait()\n #结束时间\n end = time.time()\n #获取Code码\n cleanReturnCode = cleanProcessRun.returncode\n print('%s'%cleanReturnCode)\n if cleanReturnCode != 0:\n print(\"\\n***************clean失败******耗时:%s秒***************\\n\"%(end - start))\n else:\n print(\"\\n***************clean成功*********耗时:%s秒************\\n\"%(end - start))\n #archive\n archive()\n\n\n#编译打包流程\ndef archive():\n #删除之前打包的ProgramIpa文件夹\n subprocess.call([\"rm\",\"-rf\",backupIPA])\n time.sleep(1)\n #在桌面上创建ProgramIpa文件夹\n mkdir(backupIPA)\n #subprocess.call([\"mkdir\",\"-p\",backupIPA])\n time.sleep(1)\n #开始时间\n start = time.time()\n #xcodeproj工程\n #archiveRun = 'xcodebuild archive -project %s.xcodeproj -scheme %s -archivePath ./build/%s.xcarchive'%(schemeName,schemeName,schemeName)\n archiveRun = 'xcodebuild archive -project %s.xcodeproj -scheme %s -archivePath %s/%s.xcarchive'%(schemeName,schemeName,backupIPA,schemeName)\n #workspace工程\n #archiveRun = 'xcodebuild archive -workspace %s.xcworkspace -scheme %s -archivePath %s/%s.xcarchive'%(schemeName,schemeName,backupIPA,schemeName)\n \n print('%s'%archiveRun)\n archiveProcessRun = subprocess.Popen(archiveRun,shell=True)\n archiveProcessRun.wait()\n #结束时间\n end = time.time()\n #获取Code码\n archiveReturnCode = archiveProcessRun.returncode\n print('%s'%archiveReturnCode)\n if archiveReturnCode != 0:\n print(\"\\n***************archive失败******耗时:%s秒***************\\n\"%(end - start))\n else:\n print(\"\\n***************archive成功*********耗时:%s秒************\\n\"%(end - start))\n #导出IPA\n exportIPA()\n\n\ndef exportIPA():\n #开始时间\n start = time.time()\n #iOS8.2之前打包方式\n #exportRun = 'xcodebuild -exportArchive -archivePath ./build/%s.xcarchive -exportPath ./build/%s -exportFormat ipa -exportProvisioningProfile \"adhoc_coolfood'%(schemeName,schemeName)\n #iOS9\n exportRun = 'xcodebuild -exportArchive -archivePath %s/%s.xcarchive -exportPath %s/%s -exportOptionsPlist ./ExportOptions.plist'%(backupIPA,schemeName,backupIPA,schemeName)\n print('++++++%s'%exportRun)\n exportProcessRun = subprocess.Popen(exportRun,shell=True)\n exportProcessRun.wait()\n\n #结束时间\n end = time.time()\n #获取Code码\n exportReturnCode = exportProcessRun.returncode\n if exportReturnCode != 0:\n print(\"\\n***************导出IPA失败*********耗时:%s秒************\\n\"%(end - start))\n else:\n print(\"\\n***************导出IPA成功*********耗时:%s秒************\\n\"%(end - start))\n #切换到当前目录\n os.chdir(backupIPA)\n #删除app后缀文件\n commands.getoutput('rm -rf ./*.xcarchive')\n time.sleep(1)\n uploadIPA('%s/%s/%s.ipa'%(backupIPA,schemeName,schemeName))\n openDownloadUrl()\n\n#上传蒲公英\ndef uploadIPA(IPAPath):\n if(IPAPath==''):\n print(\"\\n***************没有找到关联IPA包*********************\\n\")\n return\n else:\n print(\"\\n***************IPA包开始上传到蒲公英*********************\\n\")\n url='http://www.pgyer.com/apiv1/app/upload'\n data={\n 'uKey':USER_KEY,\n '_api_key':API_KEY,\n 'installType':'2',\n 'password':'123456',\n 'updateDescription':des\n }\n files={'file':open(IPAPath,'rb')}\n r=requests.post(url,data=data,files=files)\n\ndef openDownloadUrl():\n #用非系统默认浏览器打开\n webbrowser.open('%s%s'%(openUrlPath,App_Key),new=1,autoraise=True)\n time.sleep(3)\n webbrowser.open(openDownLoadUrlPath,new=1,autoraise=True)\n print (\"\\n*************** IPA上传更新成功 *********************\\n\")\n\n#创建backupIPA文件夹\ndef mkdir(backupIPA):\n isExists = os.path.exists(backupIPA)\n if not isExists:\n os.makedirs(backupIPA)\n print(backupIPA + '创建成功')\n return True\n else:\n print (backupIPA + '目录已经存在')\n return False\n\n#if __name__ == '__main__'的意思是:\n#当.py文件被直接运行时,if __name__ == '__main__'之下的代码块将被运行;\n#当.py文件以模块形式被导入时,if __name__ == '__main__'之下的代码块不被运行。\nif __name__ == '__main__':\n des = input(\"请输入更新的日志描述:\")\n desDv = input('请输入编译环境 1、Release 2、Debug:')\n #clean\n cleanPro()\n\n\n \n\n\n\n \n\n","sub_path":"PythonAuto.py","file_name":"PythonAuto.py","file_ext":"py","file_size_in_byte":5655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"475473524","text":"from pprint import pprint\n{\n \"Ethernet0/0\": {\"mtu\": 1500, \"ip\": \"192.168.100.1/24\"},\n \"Ethernet0/1\": {\"mtu\": 1500, \"ip\": \"192.168.200.1/24\"},\n}\n\nresult = {}\n\nwith open(\"sh_ip_interface2.txt\") as f:\n for line in f:\n line = line.rstrip()\n if \"line protocol\" in line:\n #print(line)\n intf = line.split()[0]\n elif \"Internet address\" in line:\n ip_address = line.split()[-1]\n result[intf] = {}\n result[intf][\"ip\"] = ip_address\n elif \"MTU\" in line:\n mtu = line.split()[2]\n result[intf][\"mtu\"] = mtu\n\npprint(result)\nprint(\"=\"*50)\nfor intf, params in result.items():\n if params:\n print(intf)\n pprint(params)\n","sub_path":"examples/07_files/script_sh_ip_interface_dict.py","file_name":"script_sh_ip_interface_dict.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"458485074","text":"# -*- coding: utf-8 -*-\n\nimport socket\nfrom typing import Any, Optional, List\n\nfrom pip_services3_commons.config import ConfigParams\nfrom pip_services3_commons.refer import IReferenceable, Descriptor, IReferences\nfrom pip_services3_commons.run import IOpenable\nfrom pip_services3_components.count import CachedCounters, Counter\nfrom pip_services3_components.log import CompositeLogger\nfrom pip_services3_rpc.connect import HttpConnectionResolver\nfrom urllib3 import HTTPConnectionPool, HTTPSConnectionPool\n\nfrom pip_services3_prometheus.count.PrometheusCounterConverter import PrometheusCounterConverter\n\n\nclass PrometheusCounters(CachedCounters, IReferenceable, IOpenable):\n \"\"\"\n Performance counters that send their metrics to Prometheus service.\n\n The component is normally used in passive mode conjunction with :class:`PrometheusMetricsService `.\n Alternatively when connection parameters are set it can push metrics to Prometheus PushGateway.\n\n ### Configuration parameters ###\n - connection(s):\n - discovery_key: (optional) a key to retrieve the connection from :class:`IDiscovery `\n - protocol: connection protocol: http or https\n - host: host name or IP address\n - port: port number\n - uri: resource URI or connection string with all parameters in it\n - options:\n - retries: number of retries (default: 3)\n - connect_timeout: connection timeout in milliseconds (default: 10 sec)\n - timeout: invocation timeout in milliseconds (default: 10 sec)\n\n ### References ###\n - `*:logger:*:*:1.0` (optional) :class:`ILogger ` components to pass log messages\n - `*:counters:*:*:1.0` (optional) :class:`ICounters ` components to pass collected measurements\n - `*:discovery:*:*:1.0` (optional) :class:`IDiscovery ` services to resolve connection\n\n See :class:`RestService `, :class:`CommandableHttpService `,\n\n Example:\n\n .. code-block:: python\n\n counters = PrometheusCounters()\n counters.configure(ConfigParams.from_tuples(\n \"connection.protocol\", \"http\",\n \"connection.host\", \"localhost\",\n \"connection.port\", 8080\n ))\n\n counters.open(\"123\")\n\n counters.increment(\"mycomponent.mymethod.calls\")\n timing = counters.begin_timing(\"mycomponent.mymethod.exec_time\")\n try:\n ...\n finally:\n timing.end_timing()\n\n counters.dump()\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Creates a new instance of the performance counters.\n \"\"\"\n super(PrometheusCounters, self).__init__()\n self.__logger = CompositeLogger()\n self.__connection_resolver = HttpConnectionResolver()\n self.__opened = False\n self.__source: str = None\n self.__instance: str = None\n self.__push_enabled: bool = None\n self.__client: Any = None\n self.__request_route: str = None\n\n def configure(self, config: ConfigParams):\n \"\"\"\n Configures component by passing configuration parameters.\n\n :param config: configuration parameters to be set.\n \"\"\"\n super().configure(config)\n\n self.__connection_resolver.configure(config)\n self.__source = config.get_as_float_with_default('source', self.__source)\n self.__instance = config.get_as_float_with_default('instance', self.__instance)\n self.__push_enabled = config.get_as_float_with_default('push_enabled', True)\n\n def set_references(self, references: IReferences):\n \"\"\"\n Sets references to dependent components.\n\n :param references: references to locate the component dependencies.\n \"\"\"\n self.__logger.set_references(references)\n self.__connection_resolver.set_references(references)\n\n context_info = references.get_one_optional(Descriptor(\"pip-services\", \"context-info\", \"default\", \"*\", \"1.0\"))\n if context_info is not None and self.__source is None:\n self.__source = context_info.name\n if context_info is not None and self.__instance is None:\n self.__instance = context_info.context_id\n\n def is_open(self) -> bool:\n \"\"\"\n Checks if the component is opened.\n\n :return: true if the component has been opened and false otherwise.\n \"\"\"\n return self.__opened\n\n def open(self, correlation_id: Optional[str]):\n \"\"\"\n Opens the component.\n\n :param correlation_id: (optional) transaction id to trace execution through call chain.\n \"\"\"\n if self.__opened or not self.__push_enabled:\n return\n\n self.__opened = True\n\n try:\n connection = self.__connection_resolver.resolve(correlation_id)\n\n job = self.__source or 'unknown'\n instance = self.__instance or socket.gethostname()\n self.__request_route = \"/metrics/job/\" + job + \"/instance/\" + instance\n uri = connection.get_as_string('uri').split('://')[-1]\n if connection.get_as_string('protocol') == 'https':\n self.__client = HTTPSConnectionPool(uri)\n else:\n self.__client = HTTPConnectionPool(uri)\n\n except Exception as err:\n self.__client = None\n self.__logger.warn(correlation_id, \"Connection to Prometheus server is not configured: \" + str(err))\n\n def close(self, correlation_id: Optional[str]):\n \"\"\"\n Closes component and frees used resources.\n\n :param correlation_id: (optional) transaction id to trace execution through call chain.\n \"\"\"\n self.__opened = False\n self.__request_route = None\n try:\n if self.__client:\n self.__client.close()\n finally:\n self.__client = None\n\n def _save(self, counters: List[Counter]):\n \"\"\"\n Saves the current counters measurements.\n\n :param counters: current counters measurements to be saves.\n \"\"\"\n if self.__client is None or not self.__push_enabled: return\n\n body = PrometheusCounterConverter.to_string(counters, None, None)\n err = None\n response = None\n try:\n response = self.__client.request('PUT', self.__request_route, body=body)\n except Exception as ex:\n err = ex\n finally:\n if err or response.status >= 400:\n self.__logger.error(\"prometheus-counters\", err, \"Failed to push metrics to prometheus\")\n","sub_path":"pip_services3_prometheus/count/PrometheusCounters.py","file_name":"PrometheusCounters.py","file_ext":"py","file_size_in_byte":7060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"604349375","text":"import os\nimport pandas as pd\nimport numpy as np\nimport time\nfrom torch.utils.data import DataLoader\nfrom pytorch_lightning.callbacks import ModelCheckpoint\nfrom pytorch_lightning import Trainer, seed_everything\n\nfrom torch_explain.models.explainer import Explainer\nfrom torch_explain.logic.metrics import formula_consistency\nfrom experiments.data.load_datasets import load_cub\n\ntrain_data, val_data, test_data, concept_names = load_cub('../data')\n\ntrain_loader = DataLoader(train_data, batch_size=len(train_data))\nval_loader = DataLoader(val_data, batch_size=len(val_data))\ntest_loader = DataLoader(test_data, batch_size=len(test_data))\nn_concepts = next(iter(train_loader))[0].shape[1]\nn_classes = next(iter(train_loader))[1].shape[1]\nprint(concept_names)\nprint(n_concepts)\nprint(n_classes)\n\n# %% md\n\n## 5-fold cross-validation with explainer network\n\nbase_dir = f'./results/CUB/blackbox'\nos.makedirs(base_dir, exist_ok=True)\n\nn_seeds = 5\nresults_list = []\nexplanations = {i: [] for i in range(n_classes)}\nfor seed in range(n_seeds):\n seed_everything(seed)\n print(f'Seed [{seed + 1}/{n_seeds}]')\n train_loader = DataLoader(train_data, batch_size=len(train_data))\n val_loader = DataLoader(val_data, batch_size=len(val_data))\n test_loader = DataLoader(test_data, batch_size=len(test_data))\n\n checkpoint_callback = ModelCheckpoint(dirpath=base_dir, monitor='val_loss', save_top_k=1)\n trainer = Trainer(max_epochs=500, gpus=1, auto_lr_find=True, deterministic=True,\n check_val_every_n_epoch=1, default_root_dir=base_dir,\n weights_save_path=base_dir, callbacks=[checkpoint_callback])\n model = Explainer(n_concepts=n_concepts, n_classes=n_classes, l1=0, lr=0.01, explainer_hidden=[10])\n\n trainer.fit(model, train_loader, val_loader)\n print(f\"Concept mask: {model.model[0].concept_mask}\")\n model.freeze()\n model_results = trainer.test(model, test_dataloaders=test_loader)\n for j in range(n_classes):\n n_used_concepts = sum(model.model[0].concept_mask[j] > 0.5)\n print(f\"Extracted concepts: {n_used_concepts}\")\n results = {}\n results['model_accuracy'] = model_results[0]['test_acc']\n\n results_list.append(results)\n\n results_df = pd.DataFrame(results_list)\n results_df.to_csv(os.path.join(base_dir, 'results_aware_cub.csv'))\n\nresults_df = pd.DataFrame(results_list)\nresults_df.to_csv(os.path.join(base_dir, 'results_aware_cub.csv'))\nresults_df\n\n# %%\n\nresults_df.mean()\n\n# %%\n\nresults_df.sem()\n\n\nprint(f'Mu net scores (model): {results_df[\"model_accuracy\"].mean()} (+/- {results_df[\"model_accuracy\"].std()})')","sub_path":"experiments/elens/hyperparams/cub.py","file_name":"cub.py","file_ext":"py","file_size_in_byte":2611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"20716927","text":"from azureml.data.dataset_factory import TabularDatasetFactory\nfrom azureml.core.run import Run\n\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.metrics import mean_absolute_error\n\nimport argparse\nimport os\nimport numpy as np\nimport joblib\nimport pandas as pd\n\n# Imports dataset\nmbdataset = TabularDatasetFactory.from_delimited_files(\"https://raw.githubusercontent.com/czofficial/nd00333-capstone/4a6a4924bdd4c6a188aeb24e0c282bae11c8933b/mercedes.csv\")\n\ndf = mbdataset.to_pandas_dataframe()\n\n# Cleans dataset\ndef clean_data(df):\n \n x_df = df\n x_df = pd.get_dummies(df, columns=['model', 'transmission', 'fuelType'])\n y_df = x_df.pop(\"price\")\n\n return x_df,y_df\n\nx, y = clean_data(df)\n\n# Splits dataset into train and test\nx_train,x_test,y_train,y_test = train_test_split(x,y)\n\nrun = Run.get_context()\n\ndef main():\n # Adds arguments\n parser = argparse.ArgumentParser()\n \n parser.add_argument('--max_depth',\n type=int,\n default=1,\n help=\"The maximum depth of the tree.\")\n parser.add_argument('--min_samples_split',\n type=int,\n default=2,\n help=\"The minimum number of samples required to split an internal node.\")\n parser.add_argument('--min_samples_leaf',\n type=int,\n default=1,\n help=\"The minimum number of samples required to be at a leaf node.\")\n\n args = parser.parse_args()\n\n run.log(\"max_depth:\", np.int(args.max_depth)) \n run.log(\"min_samples_split:\", np.int(args.min_samples_split))\n run.log(\"min_samples_leaf:\", np.int(args.min_samples_leaf))\n\n\n# Trains random forest\n model = RandomForestRegressor(\n max_depth=args.max_depth,\n min_samples_split=args.min_samples_split,\n min_samples_leaf=args.min_samples_leaf).fit(x_train, y_train)\n\n# Calculates MAE\n y_pred = model.predict(x_test)\n mae = mean_absolute_error(y_test, y_pred)\n run.log('mae', np.int(mae))\n\n# Saves the model \n os.makedirs('outputs', exist_ok=True)\n joblib.dump(value=model, filename='outputs/hd-model.pkl')\n \nif __name__ == '__main__':\n main()","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"598422137","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 25 10:04:53 2018\n\n@author: yumi.zhang\n\"\"\"\n#Update Everyday\n\n#April 25th, 2018\n#Contains Duplicate\ndef containsDuplicate(self, nums):\n tempset = set()\n if len(nums) == 0:\n return False\n for i in nums:\n if i in tempset:\n return True\n tempset.add(i)\n return False\n\n#Intersection of two Arrays\ndef intersection(self, nums1, nums2):\n tempset = []\n for i in nums1:\n for j in nums2:\n if i==j and j not in tempset:\n tempset.append(i)\n return tempset\n\n#Happy Number\ndef squaresum(self, n):\n sum = 0\n while(n>0):\n temp = n % 10\n sum += temp * temp\n n = n//10\n return sum\n\ndef isHappy(self, n):\n fast = slow = n\n while True:\n slow = self.squaresum(slow)\n fast = self.squaresum(fast)\n fast = self.squaresum(fast)\n if slow == fast:\n break\n return slow==1\n\n#isomorphic strings\ndef isIsomorphic(self, s, t):\n hashmap = {}\n for i in range(len(s)):\n if s[i] not in hashmap:\n hashmap[s[i]] = t[i]\n elif hashmap[s[i]] != t[i]:\n return False\n \n #mapval = [hashmap[k] for k in hashmap]\n #return len(mapval) == len(set(mapval))\n test = []\n for k in hashmap:\n test.append(hashmap[k])\n return len(test) == len(set(test))\n\n#Minimum Index Sum of Two Lists\nclass Solution(object):\n def findRestaurant(self, list1, list2):\n hashmap = {}\n for i in range(0, len(list1)):\n if list1[i] not in hashmap:\n if list1[i] in list2:\n hashmap[list1[i]] = i+list2.index(list1[i])\n value = min(hashmap.values())\n result = []\n for keys, values in hashmap.items():\n if values == value:\n result.append(keys)\n \n return result\n \n#First Unique Character in a String\ndef findUniqueChar(self, s):\n if len(s)==0:\n return -1\n s_dict = {}\n s = list(s)\n for x in s:\n s_dict[x] = s.count(x)\n result = []\n for keys, values in s_dict.items():\n if values == 1:\n result.append(keys)\n if len(result) == 0:\n return -1\n else: \n index = {}\n for i in result:\n index[i] = s.index(i)\n min_value = min(index.values())\n return(min_value)\n \n#Contains Duplicate II (time limit)\ndef containsNearbyDuplicate(self, nums, k):\n if len(nums) < 2:\n return False\n for i in range(0, len(nums)):\n for j in range(i+1, len(nums)):\n if nums[i] == nums[j] and abs(i-j) <= k:\n return True\n return False\n\n#Contains Duplicate II (solution 2 without time limit)\ndef containsNearbyDuplicate(nums, k):\n if len(nums) < 2:\n return False\n temp = {}\n for i in range(0, len(nums)):\n if nums[i] in temp and abs(i-temp[nums[i]]) <=k:\n return True\n else:\n temp[nums[i]] = i\n return False\n\n#April 28th, 2018\n#Binary Tree, implement preorder, inorder and postorder recursively\nclass Tree(object):\n def __init__(self):\n self.data = None\n self.left = None\n self.right = None\n \n def preorder(root):\n if root is None:\n return\n else:\n print(root.data)\n preorder(root.left)\n preorder(root.right)\n \n def inorder(root):\n if root is None:\n return\n else:\n inorder(root.left)\n print(root.data)\n inorder(root.right)\n \n def postorder(root):\n if root is None:\n return\n else:\n postorder(root.left)\n postorder(root.right)\n print(root.data)\n\n#build a simple tree for test\nroot = Tree()\nroot.data = \"root\"\nroot.left = Tree()\nroot.left.data = \"left\"\nroot.right = Tree()\nroot.right.data = \"right\"\n\n#implement it iteratively\ndef preorder(root):\n result = []\n if root is None:\n return result\n stack = []\n node = root\n while node or stack:\n while node:\n result.append(node.data)\n stack.append(node)\n node = node.left\n node = stack.pop()\n node = node.right\n return result\n\ndef inorder(root):\n result = []\n if root is None:\n return result\n stack = []\n node = root\n while node or stack:\n while node:\n stack.append(node)\n node = node.left\n node = stack.pop()\n result.append(node.data)\n node = node.right\n return result\n\ndef levelorder(root):\n result = []\n if root is None:\n return result\n current_level = [root]\n while current_level:\n next_level = []\n level_result = []\n for temp in current_level:\n if temp.left != None:\n next_level.append(temp.left)\n if temp.right != None:\n next_level.append(temp.right)\n level_result.append(temp.data)\n result.append(level_result)\n current_level = next_level\n return result\n\n#another solutions: using queue, but the format doesnot meet the requirement of leetcode\ndef levelorder(root):\n result = []\n if root is None:\n return result\n myqueue = []\n node = root\n myqueue.append(node)\n while myqueue:\n node = myqueue.pop(0)\n if node.left != None:\n myqueue.append(node.left)\n if node.right != None:\n myqueue.append(node.right)\n result.append(node.data)\n return result\n\n#April 29th, 2018 \n#Maximum Depth of Binary Tree\ndef maxDepth(self, root):\n if root == None:\n return 0\n else:\n return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1\n\n#Symmetric Tree\nclass Solution(object):\n def leftandright(self, p, q):\n if p == None and q == None:\n return True\n if p != None and q != None and p.val == q.val:\n return self.leftandright(p.left, q.right) and self.leftandright(q.left, p.right) #be careful of this\n return False\n \n def isSymmetric(self, root):\n if root:\n return self.leftandright(root.left, root.right)\n return True\n\n#path sum\ndef hasPathSum(self, root, sum):\n if root == None:\n return False\n if root.left == None and root.right == None:\n return root.val == sum\n return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val)\n\n#Construct Binary Tree from Inorder and Postorder Traversal\ndef buildTree(self, inorder, postorder):\n if len(inorder) == 0:\n return None\n if len(inorder) == 1:\n return TreeNode(inorder[0])\n root = TreeNode(postorder[len(postorder) - 1])\n idx = inorder.index(postorder[len(postorder)-1])\n root.left = self.buildTree(inorder[0: idx], postorder[0: idx])\n root.right = self.buildTree(inorder[idx+1: len(inorder)], postorder[idx: len(postorder) - 1])\n return root\n\n#Construct Binary Tree from Preorder and Inorder Traversal\ndef buildTree(self, preorder, inorder):\n if len(inorder) == 0:\n return None\n if len(inorder) == 1:\n return TreeNode(inorder[0])\n root = TreeNode(preorder[0])\n idx = inorder.index(preorder[0])\n root.left = self.buildTree(preorder[1: idx], inorder[0: idx])\n root.right = self.buildTree(preorder[idx+1: len(preorder)], inorder[idx+1: len(inorder)])\n return root\n\n#Populating Next Right Pointers in Each Node\ndef connect(self, root):\n if root and root.left:\n root.left.next = root.right\n if root.next:\n root.right.next = root.next.left\n else:\n root.next = None\n self.connect(root.left)\n self.connect(root.right)\n \n#Populating Next Right Pointers in Each Node II\ndef connect(self, root):\n if root:\n if root.left and root.right:\n root.left.next = root.right\n temp = root.next\n while temp:\n if temp.left:\n root.right.next = temp.left\n break\n if temp.right:\n root.right.next = temp.right\n break\n temp = temp.next\n elif root.left:\n temp = root.next\n while temp:\n if temp.left:\n root.left.next = temp.left\n break\n if temp.right:\n root.left.next = temp.right\n break\n temp = temp.next\n elif root.right:\n temp = root.next\n while temp:\n if temp.left:\n root.right.next = temp.left\n break\n if temp.right:\n root.right.next = temp.right\n break\n temp = temp.next\n self.connect(root.right)\n self.connect(root.left) \n \n#Lowest Common Ancestor of a Binary Tree\ndef lowestCommonAncestor(self, root, p, q):\n if not root:\n return root\n if root == p or root == q:\n return root\n\n left = self.lowestCommonAncestor(root.left, p, q)\n right = self.lowestCommonAncestor(root.right, p, q)\n \n if left != None and right != None:\n return root\n if left != None:\n return left\n else:\n return right\n#Serialize and Deserialize Binary Tree\nclass Codec:\n def serialize(self, root):\n result = []\n def preorder(root):\n if not root:\n result.append('null')\n else:\n result.append(str(root.val))\n preorder(root.left)\n preorder(root.right)\n preorder(root)\n return ''.join(result)\n\n def deserialize(self, data):\n if len(data) == 0:\n return None\n vals = collections.deque(val for val in data.split())\n def build():\n if vals:\n val = vals.popleft()\n if val == '#':\n return None\n else:\n root = TreeNode(int(val))\n root.left = build()\n root.right = build()\n return root\n return build()\n \n#Binary Search\ndef search(self, nums, target):\n for i in range(0, len(nums)):\n if nums[i]==target:\n return i\n else:\n return -1\n \n#Sqrt(x)\ndef mySqrt(self, x):\n if x == 0:\n return 0\n left = 1\n right = x / 2 + 1\n while(left <= right):\n mid = (left + right) / 2\n if mid**2 == x:\n return mid\n elif mid**2 > x:\n right = mid - 1\n else:\n left = mid + 1\n return right\n\n#Guess Number Higher or Lower\ndef guessNumber(self, n):\n if n == 0:\n return 0\n left = 1\n right = n\n while (left <= right): \n mid = (left + right) / 2 #mid = (left + (right - left) >> 1)\n result = guess(mid)\n if result == 0:\n return mid\n elif result == 1:\n left = mid + 1\n else:\n right = mid - 1\n \n#Search in Rotated Sorted Array\ndef search(self, nums, target):\n left = 0\n right = len(nums) - 1\n while (left <= right):\n mid = (left + right) / 2\n if nums[mid] == target:\n return mid\n \n if nums[mid] >= nums[left]: #left is ascending\n if target < nums[mid] and target >= nums[left]:\n right = mid - 1\n else:\n left = mid + 1\n \n if nums[mid] < nums[right]: #right is ascending\n if target <= nums[right] and target > nums[mid]:\n left = mid + 1\n else:\n right = mid - 1\n return -1\n\n#First Bad Version\ndef firstBadVersion(self, n):\n if n == 0:\n return 0\n left = 1\n right = n\n while left <= right:\n mid = (left + right) / 2\n if isBadVersion(mid):\n if mid == 1 or not isBadVersion(mid-1):\n return mid\n right = mid - 1\n else:\n left = mid + 1\n#Find Peak Element\ndef findPeakElement(self, nums):\n if len(nums) == 1:\n return 0\n left = 0\n right = len(nums) - 1\n while left nums[mid-1] and nums[mid] > nums[mid + 1]:\n return mid\n elif nums[mid] < nums[mid + 1]:\n left = mid + 1\n else:\n right = mid - 1\n return left\n\n#Find Minimum in Rotated Sorted Array\ndef findMin(self, nums):\n if len(nums) == 1:\n return nums[0]\n left = 0\n right = len(nums) - 1\n while left < right:\n mid = (left + right) / 2\n if nums[mid] < nums[right]:\n right = mid\n else:\n left = mid + 1\n return nums[left]\n\n#Search for a Range\ndef searchRange(self, nums, target):\n if len(nums)==0:\n return [-1, -1]\n left = 0\n right = len(nums) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[mid] < target:\n left = mid + 1\n elif nums[mid] > target:\n right = mid - 1\n else:\n result = [0, 0]\n if nums[left] == target: result[0] = left\n if nums[right] == target: result[1] = right\n for i in range(mid, right+1):\n if nums[i] != target: result[1] = i-1; break\n for i in range(mid, left-1, -1):\n if nums[i] != target: result[0] = i+1; break\n return result\n return [-1, -1]\n\n#Find K Closest Elements\ndef findClosestElements(self, arr, k, x):\n if len(arr) == 0 or len(arr) < k:\n return None\n left = 0\n right = len(arr) - 1\n while (right - left + 1) > k:\n if abs(x - arr[right]) < abs(x- arr[left]):\n left += 1\n else:\n right -=1\n return arr[left: right+1]\n\n#def myPow(self, x, n):\n if n==0:\n return 1\n elif n < 0:\n return 1 / self.myPow(x, -n)\n elif n % 2:\n return self.myPow(x*x, n/2)*x\n else:\n return self.myPow(x*x, n/2)\n \n#Valid Perfect Square\ndef isPerfectSquare(self, num):\n if num == 0 or num == 1:\n return True\n left = 0\n right = num\n while left <= right:\n mid = (left + right) / 2\n if mid*mid == num:\n return True\n elif mid*mid > num:\n right = mid-1\n else:\n left = mid + 1 \n return False\n\n#Find Smallest Letter Greater Than Target (环形有序)\ndef nextGreatestLetter(self, letters, target):\n letters_new = set(map(ord, letters))\n for i in range(1, 27):\n candidate = ord(target) + i\n if candidate > ord('z'):\n candidate -= 26\n if candidate in letters_new:\n return chr(candidate)\n \n#Find Minimum in Rotated Sorted Array II\ndef findMin(self, nums):\n if len(nums) == 0:\n return 0\n left = 0\n right = len(nums) - 1\n while (left < right):\n mid = (left + right) / 2\n mid = int(mid)\n if nums[mid] < nums[right]:\n right = mid\n elif nums[mid] > nums[right]:\n left = mid + 1\n else:\n right -= 1\n return nums[left]\n\n#Two Sum II - Input array is sorted\ndef twoSum(self, numbers, target):\n left = 0\n right = len(numbers) - 1\n while (left target:\n right -= 1\n else:\n left += 1\n \n#Two Sum II - Input array is sorted (Solution two: but time limit)\ndef twoSum(self, numbers, target):\n for i in range(0, len(numbers)):\n for j in range(i+1, len(numbers)):\n if numbers[j] == target-numbers[i]:\n return [i+1, j+1]\n \n#Find the Duplicate Number\ndef findDuplicate(self, nums):\n left = 1\n right = len(nums) - 1\n while left <= right:\n mid = (left + right) / 2\n count = sum(x <= mid for x in nums)\n if count > mid:\n right = mid - 1\n else:\n left = mid + 1\n return left\n\n#Find the Duplicate Number (Solution two: but time limit)\ndef findDuplicate(self, nums):\n result = []\n for i in range(0, len(nums)):\n if nums[i] not in result:\n result.append(nums[i])\n else:\n return nums[i]\n\n#Median of Two Sorted Arrays\nclass Solution(object):\n\n def getKth(self, A, B, k):\n lenA = len(A); lenB = len(B)\n if lenA > lenB: return self.getKth(B, A, k)\n if lenA == 0: return B[k - 1]\n if k == 1: return min(A[0], B[0])\n pa = min(k/2, lenA); pb = k - pa\n if A[pa - 1] <= B[pb - 1]:\n return self.getKth(A[pa:], B, pb)\n else:\n return self.getKth(A, B[pb:], pa)\n \n def findMedianSortedArrays(self, A, B):\n totallen = len(A) + len(B)\n if totallen % 2 == 1: \n return self.getKth(A, B, totallen/2 + 1)\n else:\n return (self.getKth(A, B, totallen/2) + self.getKth(A, B, totallen/2 + 1)) * 0.5\n \n#Binary Search Tree Iterator\nclass BSTIterator(object):\n def __init__(self, root):\n self.stack = []\n self.pushleft(root)\n \"\"\"\n :type root: TreeNode\n \"\"\"\n def hasNext(self):\n return self.stack\n \"\"\"\n :rtype: bool\n \"\"\" \n def next(self):\n top = self.stack.pop()\n self.pushleft(top.right)\n return top.val\n \"\"\"\n :rtype: int\n \"\"\"\n def pushleft(self, node):\n while node:\n self.stack.append(node)\n node = node.left\n\n#Search in a Binary Search Tree\nclass Solution(object):\n def searchBST(self, root, val):\n if root is None:\n return None\n else:\n node = root\n if node.val == val:\n return node\n else:\n return self.searchBST(node.left, val) or self.searchBST(node.right, val)\n \n#Kth Smallest Element in a BST\ndef kthSmallest(self, root, k):\n if root is None:\n return None\n else:\n stack = []\n node = root\n while node:\n stack.append(node)\n node = node.left\n x = 1\n while x <= k and stack:\n node = stack.pop()\n x += 1\n right = node.right\n while right:\n stack.append(right)\n right = right.left \n return node.val\n\n#Number of Islands\nclass Solution(object):\n def numIslands(self, grid):\n m = len(grid)\n if m==0:\n return 0\n n = len(grid[0])\n visit = [[False for i in range(n)] for j in range(m)]\n \n def check(x, y):\n if x < m and y < n and x>=0 and y>=0 and grid[x][y] == '1' and visit[x][y] == False:\n return True\n \n def dfs(x, y):\n nrow = [1, 0, -1, 0]\n ncol = [0, 1, 0, -1]\n for k in range(4):\n newx = x + nrow[k]\n newy = y + ncol[k]\n if check(newx, newy):\n visit[newx][newy] = True\n dfs(newx, newy)\n \n count = 0\n for row in range(m):\n for col in range(n):\n if check(row, col):\n visit[row][col] = True\n dfs(row, col)\n count += 1\n return count\n \n#Sort Colors\nclass Solution(object):\n def sortColors(self, nums):\n count_0 = 0\n count_1 = 0\n count_2 = 0\n for i in nums:\n if i == 0:\n count_0 += 1\n elif i == 1:\n count_1 += 1\n else:\n count_2 += 1\n for i in range(0, count_0):\n nums[i] = 0\n for i in range(count_0, count_0+count_1):\n nums[i] = 1\n for i in range(count_1+count_0, len(nums)):\n nums[i] = 2\n \n#Top K Frequent Elements\ndef topKFrequent(self, nums, k):\n temp ={}\n for i in range(0, len(nums)):\n if nums[i] not in temp:\n temp[nums[i]] = 1\n else:\n temp[nums[i]] += 1\n s = sorted(temp.items(), key=operator.itemgetter(1), reverse=True)#sort a dict\n result = []\n for i in range(k):\n result.append(s[i][0])\n return result\n\n#Kth Largest Element in an Array\ndef findKthLargest(self, nums, k):\n if len(nums) == 0:\n return None\n else:\n new_nums = sorted(nums, reverse=True)\n return new_nums[k-1]\n \n#Merge Intervals\nclass Solution(object):\n def merge(self, intervals):\n intervals.sort(key = lambda x:x.start)\n length = len(intervals)\n res = []\n for i in range(length):\n if res == []:\n res.append(intervals[i])\n else:\n size = len(res)\n if res[size-1].start <= intervals[i].start <= res[size-1].end:\n res[size-1].end = max(intervals[i].end, res[size-1].end)\n else:\n res.append(intervals[i])\n return res\n \n#Search a 2D Matrix II\nclass Solution(object):\n def searchMatrix(self, matrix, target):\n if matrix == [] or matrix == [[]]:\n return False\n y = len(matrix[0])-1\n def binarySearch(nums, left, right):\n while left <= right:\n mid = (left+right) / 2\n if nums[mid] > target:\n right = mid-1\n else:\n left = mid + 1\n return right\n \n for x in range(len(matrix)):\n y = binarySearch(matrix[x], 0, y)\n if matrix[x][y] == target:\n return True\n \n#Jump Game\nclass Solution(object):\n def canJump(self, nums):\n step = nums[0]\n for i in range(1, len(nums)):\n if step > 0:\n step -= 1\n step = max(step, nums[i])\n else:\n return False\n return True \n return False\n \n#Unique Paths\nclass Solution(object):\n def uniquePaths(self, m, n):\n dp = [[1 for i in range(n)] for i in range(m)]\n for i in range(1, n):\n for j in range(1, m):\n dp[j][i] = dp[j-1][i] + dp[j][i-1]\n return dp[m-1][n-1]\n\n#Factorial Trailing Zeroes (time limit)\nclass Solution(object):\n def trailingZeroes(self, n):\n if n==0:\n return 0\n result = n\n while (n-1) > 0:\n result = result*(n-1)\n n -= 1\n result = str(result) \n zerovalue = 0\n for i in range(len(result)-1, -1, -1):\n if result[i] != '0':\n zerovalue = len(result) - i - 1\n break\n return zerovalue\n \n#Factorial Trailing Zeroes\nclass Solution(object):\n def trailingZeroes(self, n):\n res = 0\n while n > 0:\n n = n/5\n res += n\n return res\n \n#Excel Sheet Column Number\nclass Solution(object):\n def titleToNumber(self, s):\n sum = 0\n for i in s:\n sum = sum*26 + ord(i) - 64\n return sum\n \n#Divide Two Integers\ndef divide(dividend, divisor):\n if (dividend > 0 and divisor < 0) or (dividend < 0 and divisor > 0):\n if abs(dividend) < abs(divisor):\n return 0\n sum = 0\n res = 0\n count = 0\n a = abs(dividend)\n b = abs(divisor)\n while a >= b:\n sum = b\n count = 1\n while sum + sum <= a:\n sum += sum\n count += count\n a -= sum\n res += count\n res \n \n if (dividend > 0 and divisor < 0) or (dividend < 0 and divisor > 0):\n res = -res\n return res\n\n#Divide Two Integers\nclass Solution(object):\n def divide(self, dividend, divisor):\n max_int = 2147483647\n sign = 1 if (dividend > 0 and divisor > 0) or (dividend < 0 and divisor < 0) else -1\n quotient = 0\n dividend = abs(dividend)\n divisor = abs(divisor)\n while dividend >= divisor:\n k = 0\n temp = divisor\n while dividend >= temp:\n dividend -= temp\n quotient += 1 << k\n temp <<= 1\n k += 1\n quotient = sign * quotient\n if quotient > max_int:\n return max_int\n return quotient\n \n#Fraction to Recurring Decimal\nclass Solution(object):\n def fractionToDecimal(self, numerator, denominator):\n negflag = numerator * denominator < 0\n numerator = abs(numerator)\n denominator = abs(denominator)\n loopDict = {}\n loopStr = None\n cnt = 0\n numList = []\n while True:\n numList.append(str(numerator / denominator))\n cnt += 1\n numerator = (numerator % denominator) * 10\n if numerator == 0:\n break\n loc = loopDict.get(numerator)\n if loc:\n loopStr = \"\".join(numList[loc:cnt])\n break\n loopDict[numerator] = cnt\n ans = numList[0]\n if len(numList) > 1:\n ans += \".\"\n if loopStr:\n ans += \"\".join(numList[1: len(numList) - len(loopStr)]) + \"(\" + loopStr + \")\"\n else:\n ans += \"\".join(numList[1:])\n if negflag:\n ans = \"-\" + ans\n return ans\n#Insert Delete GetRandom O(1) \nimport random\nclass RandomizedSet(object):\n\n def __init__(self):\n self.datamap = {}\n self.datalist = [] \n\n def insert(self, val):\n if val in self.datamap:\n return False\n else:\n self.datamap[val] = len(self.datalist)\n self.datalist.append(val)\n return True\n\n def remove(self, val):\n if val not in self.datamap:\n return False\n else:\n idx = self.datamap[val]\n tail = self.datalist.pop()\n if idx < len(self.datalist):\n self.datalist[idx] = tail\n self.datamap[tail] = idx\n del self.datamap[val]\n return True\n \n\n def getRandom(self):\n return random.choice(self.datalist)\n \n#Sum of Two Integers\nclass Solution(object):\n def getSum(self, a, b):\n while b != 0:\n carry = a & b\n a = (a^b) % 0x100000000\n b = (carry<<1) % 0x100000000\n return a if a <= 0x7FFFFFFF else a | (~0x100000000 + 1)\n \n#Evaluate Reverse Polish Notation\nclass Solution(object):\n def evalRPN(self, tokens):\n stack = []\n for i in range(0, len(tokens)):\n if tokens[i] != '+' and tokens[i] != '-' and tokens[i] != '/' and tokens[i] != '*':\n stack.append(int(tokens[i]))\n else:\n a = stack.pop()\n b = stack.pop()\n if tokens[i] == '+':\n stack.append(a+b)\n elif tokens[i] == '-':\n stack.append(b-a)\n elif tokens[i] == '*':\n stack.append(a*b)\n elif tokens[i] == '/' and a*b < 0:\n stack.append(-(-b/a))\n else:\n stack.append(b/a)\n return stack.pop()\n \n#Majority Element\nclass Solution(object):\n def majorityElement(self, nums):\n result = {}\n for i in range(0, len(nums)):\n if nums[i] not in result:\n result[nums[i]] = 1\n else:\n result[nums[i]] += 1\n inverse = [(value, key) for key, value in result.items()]\n if max(inverse)[0] > len(nums) / 2:\n value = max(inverse)[1]\n return value\n \n#Task Scheduler\nclass Solution(object):\n def leastInterval(self, tasks, n):\n output = [0] * 26\n for i in tasks:\n output[ord(i) - ord('A')] = output[ord(i) - ord('A')] + 1\n \n count = 0\n len_0 = 0\n max_0 = max(output)\n for i in output:\n if i == max_0:\n count += 1\n return max(len(tasks), (max_0-1)*(n+1) + count)\n#Letter Combinations of a Phone Number\nclass Solution(object):\n def letterCombinations(self, digits):\n dict = {'2': ['a', 'b', 'c'],\n '3': ['d', 'e', 'f'],\n '4': ['g', 'h', 'i'],\n '5': ['j', 'k', 'l'],\n '6': ['m', 'n', 'o'],\n '7': ['p', 'q', 'r', 's'],\n '8': ['t', 'u', 'v'],\n '9': ['w', 'x', 'y', 'z']}\n def dfs(num, string, res):\n if length == 0:\n return res\n if num == length:\n res.append(string)\n return\n for i in dict[digits[num]]:\n dfs(num + 1, string + i, res)\n \n res = [] \n length = len(digits)\n dfs(0, '', res)\n return res\n \n#Longest Increasing Subsequence\nclass Solution(object):\n def lengthOfLIS(self, nums):\n if len(nums) == 0:\n return 0\n temp = [1] * len(nums)\n for i in range(0, len(nums)):\n for j in range(0, i):\n if nums[j] < nums[i] and temp[j] + 1 > temp[i]:\n temp[i] = temp[j] + 1\n return max(temp)\n \n#Generate Parentheses \nclass Solution(object):\n def helpler(self, l, r, item, res):\n if r < l:\n return\n if l == 0 and r == 0:\n res.append(item)\n if l > 0:\n self.helpler(l - 1, r, item + '(', res)\n if r > 0:\n self.helpler(l, r - 1, item + ')', res)\n \n def generateParenthesis(self, n):\n if n == 0:\n return []\n res = []\n self.helpler(n, n, '', res)\n return res\n \n#Permutations\nclass Solution(object):\n def permute(self, nums):\n if len(nums) == 0:\n return []\n elif len(nums) == 1:\n return [nums]\n else:\n res = []\n for i in range(0, len(nums)):\n x = nums[i]\n xs = nums[:i] + nums[i+1:]\n for p in self.permute(xs):\n res.append([x]+p)\n return res\n \n#Subsets\nclass Solution(object):\n def subsets(self, nums):\n self.res = []\n def dfs(nums, temp, i):\n self.res.append(temp[:])\n for i in range(i, len(nums)):\n temp.append(nums[i])\n dfs(nums, temp, i+1)\n temp.pop()\n dfs(nums, [], 0)\n return self.res\n \n#Word Search\nclass Solution(object):\n def exist(self, board, word):\n for i in range(0, len(board)):\n for j in range(0, len(board[0])):\n if self.dfs(board, i, j, word):\n return True\n return False\n \n def dfs(self, board, row, col, word):\n if len(word) == 0:\n return True\n if row < 0 or row >= len(board) or col < 0 or col >= len(board[0]) or board[row][col] != word[0]:\n return False\n temp = board[row][col]\n board[row][col] = ''\n result = self.dfs(board, row+1, col, word[1:]) or self.dfs(board, row-1, col, word[1:]) or self.dfs(board, row, col+1, word[1:]) or self.dfs(board, row, col-1, word[1:])\n board[row][col] =temp\n return result\n \n#Product of Array Except Self\nclass Solution(object):\n def productExceptSelf(self, nums):\n listA = [1]\n listB = [1]\n tempA = 1\n for i in range(0, len(nums)-1):\n tempA = tempA*nums[i]\n listA.append(tempA)\n tempB = 1\n tempNums = list(reversed(nums))\n for j in range(0, len(tempNums)-1):\n tempB = tempB * tempNums[j]\n listB.append(tempB)\n listBre = list(reversed(listB))\n result = []\n for a in range(0, len(listA)):\n result.append(listA[a]*listBre[a])\n return result\n \n#Spiral Matrix\nclass Solution(object):\n def spiralOrder(self, matrix):\n if matrix == []:\n return []\n k = 0\n l = 0\n m = len(matrix) - 1\n n = len(matrix[0]) - 1\n direction = 0\n res = []\n while True:\n if direction == 0:\n for i in range(l, n+1):\n res.append(matrix[k][i])\n k += 1\n if direction == 1:\n for i in range(k, m+1):\n res.append(matrix[i][n])\n n -= 1\n if direction == 2:\n for i in range(n, l-1, -1):\n res.append(matrix[m][i])\n m -= 1\n if direction == 3:\n for i in range(m, k-1, -1):\n res.append(matrix[i][l])\n l += 1\n if l > n or k > m:\n return res\n direction = (direction + 1) % 4\n \n#4Sum II\nclass Solution(object):\n def fourSumCount(self, A, B, C, D):\n res = 0\n cnt = collections.defaultdict(int)\n for a in A:\n for b in B:\n cnt[a+b] += 1\n for c in C:\n for d in D:\n res += cnt[-(c+d)]\n return res\n \n#Container With Most Water\nclass Solution(object):\n def maxArea(self, height):\n if len(height) == 0:\n return 0\n left = 0\n right = len(height) - 1\n area = 0\n while left < right:\n area = max(area, (right - left)*min(height[left], height[right]))\n if height[left] < height[right]:\n left += 1\n else:\n right -= 1\n return area\n \n#First Missing Positive\nclass Solution(object):\n def firstMissingPositive(self, nums):\n n = len(nums)\n for i in range(n):\n while nums[i] > 0 and nums[i] <= n and nums[i] != i + 1 and nums[i] != nums[nums[i] - 1]:\n nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1]\n for i in range(0, n):\n if i+1 != nums[i]:\n return i+1\n return n+1\n \n#Longest Consecutive Sequence\nclass Solution(object):\n def longestConsecutive(self, nums):\n if len(nums) == 0:\n return 0\n if len(nums) == 1:\n return 1\n nums_new =sorted(nums)\n count = 1\n res = []\n for i in range(0, len(nums_new)-1):\n if nums_new[i+1] - nums_new[i] == 1:\n count += 1\n elif nums_new[i+1] - nums_new[i] == 0:\n count += 0\n else:\n res.append(count)\n count = 1\n res.append(count)\n return max(res)\n \n#Basic Calculator II\nclass Solution(object):\n def calculate(self, s):\n tokens = iter(re.findall('\\d+|\\S', s))\n res = 0\n sign = 1\n for token in tokens:\n if token.isdigit():\n num = int(token)\n elif token in '+-':\n res += sign * num\n sign = 1 if token == '+' else -1\n else:\n temp = int(next(tokens))\n num = num * temp if token == '*' else num // temp\n return res + sign * num\n \n#Sliding Window Maximum\nclass Solution(object):\n def maxSlidingWindow(self, nums, k):\n if len(nums) == 0 or k > len(nums):\n return []\n res = []\n for i in range(0, len(nums)-k+1):\n xs = nums[i : i + k]\n res.append(max(xs))\n return res\n \n#Wiggle Sort II\nclass Solution(object):\n def wiggleSort(self, nums):\n new_nums = sorted(nums)\n size = len(nums)\n for x in range(1, size, 2) + range(0, size, 2):\n nums[x] = new_nums.pop()\n\n#Max Points on a Line\nclass Solution:\n def maxPoints(self, points):\n if len(points) <= 1:\n return len(points)\n maxpoint = 1\n for i in range(0, len(points)-1):\n vertical = 1\n slopes = {}\n samepoints = 0\n curmax = 1\n for j in range(i+1, len(points)):\n if points[i].x == points[j].x and points[i].y == points[j].y:\n samepoints += 1\n continue\n elif points[i].x == points[j].x:\n vertical += 1\n else:\n slop = (points[i].y - points[j].y) * 1.0/ (points[i].x - points[j].x)\n slopes.setdefault(slop, 1)\n slopes[slop] += 1\n if slopes[slop] > curmax:\n curmax = slopes[slop]\n maxpoint = max(max(curmax, vertical)+samepoints, maxpoint)\n return maxpoint\n\n#Kth Smallest Element in a Sorted Matrix\nclass Solution:\n def kthSmallest(self, matrix, k):\n low = matrix[0][0]\n high = matrix[-1][-1]\n loc = 0\n while low <= high:\n mid = (low + high) >>1\n loc = sum(bisect.bisect_right(m, mid) for m in matrix)\n if loc >= k:\n high = mid -1\n else:\n low = mid + 1\n return low\n\n#Find Pivot Index\nclass Solution:\n def pivotIndex(self, nums):\n add_sum = sum(nums)\n left_sum = 0\n for i in range(0, len(nums)):\n add_sum -= nums[i]\n if add_sum == left_sum:\n return i\n else:\n left_sum += nums[i]\n return -1\n \n#Merge k Sorted Lists\nclass Solution:\n def mergeKLists(self, lists):\n n = len(lists)\n if not lists or n == 0:\n return None\n elif n == 1:\n return lists[0]\n elif n == 2:\n return self.mergeTwoLists(lists[0], lists[1])\n else:\n mid = int(n / 2)\n return self.mergeKLists([self.mergeKLists(lists[:mid]), self.mergeKLists(lists[mid:])])\n \n def mergeTwoLists(self, l1, l2):\n dummy = curr = ListNode(0)\n while l1 and l2:\n if l1.val < l2.val:\n curr.next = l1\n l1 = l1.next\n curr = curr.next\n else:\n curr.next = l2\n l2 = l2.next\n curr = curr.next\n if l1:\n curr.next = l1\n if l2:\n curr.next = l2\n return dummy.next\n \n#Diagonal Traverse (time limit)\nclass Solution(object):\n def findDiagonalOrder(self, matrix):\n if len(matrix) == 0:\n return []\n m = len(matrix)\n n = len(matrix[0])\n res = []\n for i in range(0, n+(m-1)):\n if i % 2 == 0:\n for j in range(0, i+1):\n if j >= n or (i-j) >= m:\n continue\n else:\n res.append(matrix[i-j][j])\n else:\n for j in range(0, i+1):\n if j >= m or (i-j) >= n:\n continue\n else:\n res.append(matrix[j][i-j])\n return res\n \n#Largest Number At Least Twice of Others\nclass Solution(object):\n def dominantIndex(self, nums):\n if len(nums) == 0:\n return -1\n if len(nums) == 1:\n return 0\n new_nums = sorted(nums)\n max_1 = new_nums[len(new_nums) -1 ]\n max_2 = new_nums[len(new_nums) - 2]\n if max_1 >= max_2 * 2:\n return nums.index(max_1)\n else:\n return -1\n \n#Diagonal Traverse\nclass Solution:\n def findDiagonalOrder(self, matrix):\n if not matrix: return []\n i, j, k =0, 0, 1\n w, h = len(matrix), len(matrix[0])\n ans = []\n for x in range(w * h):\n ans.append(matrix[i][j])\n if k > 0:\n di, dj = i-1, j+1\n else:\n di, dj = i+1, j-1\n if 0 <=di 0:\n if j+1 < h:\n j = j + 1\n else:\n i = i+1\n else:\n if i+1 < w:\n i = i + 1\n else:\n j = j + 1\n k*=-1\n return ans\n \n#Add Binary\nclass Solution:\n def addBinary(self, a, b):\n m = len(a)\n n = len(b)\n maxLen = max(m, n)\n carry = 0\n result = \"\"\n for i in range(maxLen):\n x = int(a[m - 1 - i]) if i < m else 0\n y = int(b[n - 1 - i]) if i < n else 0\n \n sum1 = x + y + carry\n result = str(int(sum1 % 2)) + result\n carry = int(sum1 / 2)\n \n if carry > 0:\n return \"1\" + result\n else:\n return result\n#Array Partition I\nclass Solution:\n def arrayPairSum(self, nums):\n if len(nums) == 2:\n return min(nums[0], nums[1])\n new_nums = sorted(nums)\n n = int(len(nums) / 2)\n \n sum = 0\n even = new_nums[1::2]\n odd = new_nums[0::2]\n \n for i in range(0, n):\n sum = sum + odd[i]\n return sum\n#Remove Element\nclass Solution:\n def removeElement(self, nums, val):\n n = len(nums) - 1\n idx1 = 0\n idx2 = n\n j = 0\n for i in range(n, -1, -1):\n if nums[i] == val:\n nums[i], nums[idx2] = nums[idx2], nums[i]\n idx2 -= 1\n return idx2 + 1\n#Max Consecutive Ones\nclass Solution:\n def findMaxConsecutiveOnes(self, nums):\n res = []\n count = 0\n for i in range(len(nums)):\n if nums[i] == 1 or (nums[i] == 1 and i == len(nums) - 1):\n count += 1\n res.append(count)\n else:\n if count > 0:\n res.append(count)\n count = 0\n else:\n continue\n if len(res) != 0:\n return max(res)\n else:\n return 0\n#Minimum Size Subarray Sum\nclass Solution:\n def minSubArrayLen(self, s, nums):\n head = 0\n n = len(nums)\n sum = 0\n res = float('inf')\n for i in range(0 ,n):\n sum += nums[i]\n \n while sum >= s:\n sum -= nums[head]\n res = min(i-head+1, res)\n head += 1\n return res if res <= n else 0\n#Reverse Words in a String \nclass Solution(object):\n def reverseWords(self, s):\n return \" \".join(s.split()[::-1])\n \n#Reverse Words in a String III\nclass Solution(object):\n def reverseWords(self, s):\n str1 = \"\"\n for i in s.split():\n str1 += str(i[::-1])\n str1 += \" \"\n str1 = str1[:-1]\n return str1\n \n#Pascal's Triangle II\nclass Solution(object):\n def getRow(self, rowIndex):\n if rowIndex == 0:\n return [1]\n if rowIndex == 1:\n return [1, 1]\n list1 = [[] for i in range(0, rowIndex + 1)]\n list1[0] = [1]\n list1[1] = [1, 1]\n for i in range(2, rowIndex + 1):\n list1[i] = [1 for j in range(0, i+1)]\n for j in range(1, i):\n list1[i][j] = list1[i-1][j-1] + list1[i-1][j]\n return list1[rowIndex]\n \n#Linked List Cycle\nclass Solution(object):\n def hasCycle(self, head):\n if head == None or head.next == None:\n return False\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n if slow == fast:\n return True\n return False\n \n#Linked List Cycle II\nclass Solution(object):\n def detectCycle(self, head):\n slow = fast = head\n \n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n \n if id(slow) == id(fast):\n fast = head\n while fast != slow:\n slow = slow.next\n fast = fast.next\n return slow\n return None\n \n#Reverse Linked List\nclass Solution(object):\n def reverseList(self, head):\n prev = None\n \n while head:\n tmp = head.next\n head.next = prev\n prev = head\n head = tmp\n return prev\n \n#Remove Linked List Elements\nclass Solution(object):\n def removeElements(self, head, val):\n dummy = cur = ListNode(0)\n dummy.next = head\n \n while cur and cur.next:\n if cur.next.val == val:\n cur.next = cur.next.next\n else:\n cur = cur.next\n \n return dummy.next\n \n#Odd Even Linked List\nclass Solution(object):\n def oddEvenList(self, head):\n if head == None:\n return head\n odd = oddHead = head\n even = evenHead = head.next\n \n while even and even.next:\n odd.next = even.next\n odd = odd.next\n even.next = odd.next\n even = even.next\n \n odd.next = evenHead\n return oddHead\n \n#Merge Two Sorted Lists\nclass Solution:\n def mergeTwoLists(self, l1, l2):\n if l1 == None:\n return l2\n if l2 == None:\n return l1\n dummy = ListNode(0)\n tmp = dummy\n while l1 and l2:\n if l1.val <= l2.val:\n tmp.next = l1\n l1 = l1.next\n tmp = tmp.next\n else:\n tmp.next = l2\n l2 = l2.next\n tmp = tmp.next\n \n if l2 == None:\n tmp.next = l1\n else:\n tmp.next = l2\n \n return dummy.next\n#Add Two Numbers\nclass Solution:\n def addTwoNumbers(self, l1, l2):\n dummy = curr = ListNode(-1)\n carry = 0\n \n while l1 or l2:\n a = l1.val if l1 else 0\n b = l2.val if l2 else 0\n \n sum = a + b + carry\n carry = int(sum / 10)\n curr.next = ListNode(int(sum % 10))\n curr = curr.next\n \n if l1:\n l1 = l1.next\n if l2:\n l2 = l2.next\n \n if carry > 0:\n curr.next = ListNode(1)\n return dummy.next\n#Coin Change\nclass Solution(object):\n def coinChange(self, coins, amount):\n inf = 0x7ffffffe\n dp = [0] + [inf] * amount\n for i in range(0, amount + 1):\n for coin in coins:\n if i + coin <= amount:\n dp[i+coin] = min(dp[i+coin], dp[i] + 1)\n return dp[amount] if dp[amount] != inf else -1\n \n#Copy List with Random Pointer\nclass Solution(object):\n def copyRandomList(self, head):\n dict = {}\n m = n = head\n \n while m:\n dict[m] = RandomListNode(m.label)\n m = m.next\n \n while n:\n dict[n].next = dict.get(n.next)\n dict[n].random = dict.get(n.random)\n n = n.next\n \n return dict.get(head)\n#Rotate List\nclass Solution:\n def rotateRight(self, head, k):\n if k == 0:\n return head\n if head == None:\n return head\n dummy = ListNode(0)\n dummy.next = head\n length = 0\n p = dummy\n while p.next:\n p = p.next\n length += 1\n\n p.next = dummy.next\n step = length - (k % length)\n for i in range(0, step):\n p = p.next\n\n head = p.next\n p.next = None\n\n return head\n#Sort List\nclass Solution:\n def merge(self, head1, head2):\n if head1 == None:return head2\n if head2 == None:return head1\n dummy = ListNode(0)\n p = dummy\n while head1 and head2:\n if head1.val <= head2.val:\n p.next = head1\n head1 = head1.next\n p = p.next\n else:\n p.next= head2\n head2 = head2.next\n p = p.next\n if head1 == None:\n p.next = head2\n if head2 == None:\n p.next = head1\n return dummy.next \n \n def sortList(self, head):\n if head == None or head.next == None:\n return head\n \n fast = slow = head\n while fast.next and fast.next.next:\n slow = slow.next\n fast = fast.next.next\n head1 = head\n head2 = slow.next\n slow.next = None\n head1 = self.sortList(head1)\n head2 = self.sortList(head2)\n head = self.merge(head1, head2)\n return head\n \n#Maximum Product Subarray\nclass Solution:\n def maxProduct(self, nums):\n n = len(nums)\n if not nums or n == 0:\n return 0\n \n pos = [0] * n\n neg = [0] * n\n max_pro = [0] * n\n \n pos[0] = neg[0] = max_pro[0] = nums[0]\n for i in range(1, n):\n a = nums[i] * pos[i-1]\n b = nums[i] * neg[i-1]\n \n pos[i] = max(max(a, b), nums[i])\n neg[i] = min(min(a, b), nums[i])\n max_pro[i] = max(max_pro[i-1], pos[i])\n return max_pro[n-1]\n \n#Decode Ways\nclass Solution:\n def numDecodings(self, s):\n n = len(s)\n dp = [0] * (n+1)\n dp[0] = 1\n \n if int(s[0]) != 0:\n dp[1] = 1\n \n for i in range(2, n+1):\n if int(s[i-1]) != 0:\n dp[i] += dp[i-1]\n two = int(s[i-2] + s[i-1])\n if two <= 26 and two >= 10:\n dp[i] += dp[i-2]\n return dp[n]\n \n#Best Time to Buy and Sell Stock with Cooldown\nclass Solution:\n def maxProfit(self, prices):\n n = len(prices)\n if n == 0 or not prices:\n return 0\n hold = [0] * n\n unhold = [0] * n\n hold[0] = -prices[0]\n \n for i in range(1, n):\n if i == 1:\n hold[i] = max(hold[i-1], -prices[1])\n else:\n hold[i] = max(hold[i-1], unhold[i-2] - prices[i])\n unhold[i] = max(hold[i-1] + prices[i], unhold[i-1])\n return unhold[n-1]\n \n#Perfect Squares\nclass Solution:\n def numSquares(self, n):\n dp = [n] * (n+1)\n \n for i in range(0, n):\n if i * i <= n:\n dp[i * i] = 1\n \n for i in range(1, n+1):\n for j in range(0, i):\n if i + j * j <= n:\n dp[i + j*j] = min(dp[i]+1, dp[i + j*j])\n return dp[n]\n \n#Shifting Letters\nclass Solution(object):\n def shiftingLetters(self, S, shifts): \n total = sum(shifts)\n shift_new = []\n for i in shifts:\n shift_new.append(total)\n total -= i \n res = ''\n for i in range(0, len(S)):\n tmp = self.shiftALetter(S[i], shift_new[i])\n res += tmp\n return res\n \n def shiftALetter(self, s, shift_time):\n shifted = ord(s) + (shift_time % 26)\n return chr(shifted if shifted <= ord('z') else shifted - 26)\n \n##Maximize Distance to Closest Person\nclass Solution(object):\n def maxDistToClosest(self, seats):\n prev = -1\n res = 1\n for i in range(0, len(seats)):\n if seats[i]:\n if prev < 0:\n res = i\n else:\n res = max(res, (i-prev)//2)\n prev = i\n return max(res, len(seats) - 1 - prev)\n#Word Break\nclass Solution:\n def wordBreak(self, s, wordDict):\n n = len(s)\n if not s or n == 0:\n return False\n dp = [False] * (n + 1)\n dp[0] = True\n \n for i in range(1, n+1):\n for j in range(0, i):\n if dp[j] and s[j:i] in wordDict:\n dp[i] = True\n break\n return dp[-1]\n \n#Word Break II\nclass Solution:\n def wordBreak(self, s, wordDict):\n if not s:\n return []\n n = len(s)\n dp = [[] for x in range(n+1)]\n dp[0] = [0]\n for i in range(1, n+1):\n for j in range(i):\n if dp[j] and s[j:i] in wordDict:\n dp[i].append(j)\n res = []\n self.backTracking(dp, s, n, res, '')\n return res\n \n def backTracking(self, dp, s, idx, res, line):\n for i in dp[idx]:\n newline = s[i:idx] + ' '+ line if line else s[i:idx]\n \n if i == 0:\n res.append(newline)\n else:\n self.backTracking(dp, s, i, res, newline)\n \n#Burst Balloons\nclass Solution:\n def maxCoins(self, nums):\n n = len(nums)\n nums = [1] + nums + [1]\n dp = [[0 for j in range(n+2)] for i in range(n+2)]\n \n def DP(i, j):\n if dp[i][j] > 0:\n return dp[i][j]\n for x in range(i, j+1):\n dp[i][j] = max(dp[i][j], DP(i, x-1)+nums[i-1] * nums[x] * nums[j +1] + DP(x+1, j))\n return dp[i][j]\n return DP(1, n)\n \n#Replace Words\nclass Solution:\n def replaceWords(self, dict, sentence):\n dict = set(dict)\n \n def replace(word):\n for i in range(0, len(word)):\n if word[:i] in dict:\n return word[:i]\n return word\n \n return \" \".join(map(replace, sentence.split()))\n \n#replace words (Trie)\nclass TrieNode:\n def __init__(self):\n self.children = dict()\n self.isWord = False\n\nclass Trie:\n\n def __init__(self):\n self.root = TrieNode()\n\n def insert(self, word):\n node = self.root\n for letter in word:\n child = node.children.get(letter)\n if child is None:\n child = TrieNode()\n node.children[letter] = child\n node = child\n node.isWord = True\n\n def search(self, word):\n ans = ''\n node = self.root\n for letter in word:\n node = node.children.get(letter)\n if node is None: break\n ans += letter\n if node.isWord: return ans\n return word\n \nclass Solution(object):\n def replaceWords(self, dict, sentence):\n trie = Trie()\n ans = []\n for word in dict:\n trie.insert(word)\n for word in sentence.split():\n ans.append(trie.search(word))\n return ' '.join(ans) \n \n#Add and Search Word - Data structure design\nclass WordDictionary:\n\n def __init__(self):\n self.dict = collections.defaultdict(list)\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n \n\n def addWord(self, word):\n n = len(word)\n self.dict[n].append(word)\n \"\"\"\n Adds a word into the data structure.\n :type word: str\n :rtype: void\n \"\"\"\n \n\n def search(self, word):\n n = len(word)\n if n not in self.dict.keys():\n return False\n \n res = 0\n for w in self.dict[n]:\n if self.isWord(word, w):\n res += 1\n return res > 0\n \n \n def isWord(self, a, b):\n for i, c in enumerate(a):\n if c != '.' and c != b[i]:\n return False\n return True\n \n#Maximum XOR of Two Numbers in an Array\nclass Solution:\n def findMaximumXOR(self, nums):\n mask = ans = 0\n for x in range(32)[::-1]:\n mask += 1 << x\n prefixSet = set([n & mask for n in nums])\n tmp = ans | 1 << x\n for prefix in prefixSet:\n if tmp ^ prefix in prefixSet:\n ans = tmp\n break\n return ans\nclass TrieNode:\n def __init__(self):\n self.childs = dict()\n self.isWord = False\n\nclass Trie:\n\n def __init__(self):\n self.root = TrieNode()\n\n def insert(self, word):\n node = self.root\n for letter in word:\n child = node.childs.get(letter)\n if child is None:\n child = TrieNode()\n node.childs[letter] = child\n node = child\n node.isWord = True\n\n def delete(self, word):\n node = self.root\n queue = []\n for letter in word:\n queue.append((letter, node))\n child = node.childs.get(letter)\n if child is None:\n return False\n node = child\n if not node.isWord:\n return False\n if len(node.childs):\n node.isWord = False\n else:\n for letter, node in reversed(queue):\n del node.childs[letter]\n if len(node.childs) or node.isWord:\n break\n return True\n \n#word search II \nclass Solution(object):\n def findWords(self, board, words):\n ans = []\n tree = Trie()\n visited = [[False] * len(board[0]) for _ in range(len(board))]\n for i in range(len(words)):\n tree.insert(words[i])\n\n def dfs(x, y, root, word):\n root = root.childs.get(board[x][y])\n if not root:\n return\n visited[x][y] = True\n for dx, dy in zip((1, 0, -1, 0), (0, 1, 0, -1)):\n nx = x + dx\n ny = y + dy\n if nx < 0 or ny < 0 or nx > len(board) - 1 or ny > len(board[0]) - 1 or visited[nx][ny]:\n continue\n dfs(nx, ny, root, word + board[nx][ny])\n if root.isWord:\n ans.append(word)\n tree.delete(word)\n visited[x][y] = False\n \n for i in range(len(board)):\n for j in range(len(board[0])):\n dfs(i, j, tree.root, board[i][j])\n return ans\n#Palindrome Pairs\nclass Solution(object):\n def palindromePairs(self, words):\n res = set()\n wrap = {y: x for x, y in enumerate(words)}\n \n def isPalindrome(word):\n n = len(word)\n for i in range(int(n / 2)):\n if word[i] != word[n - i - 1]:\n return False\n return True\n\n for idx, word in enumerate(wrap):\n if \" \" in wrap and word != \" \" and isPalindrome(word):\n bidx = wrap[\" \"]\n res.add((bidx, idx))\n res.add((idx, bidx))\n \n rword = word[::-1]\n if rword in wrap:\n ridx = wrap[rword]\n if ridx != idx:\n res.add((ridx, idx))\n res.add((idx, ridx))\n \n for x in range(len(word)):\n left, right = word[:x], word[x:]\n rleft, rright = left[::-1], right[::-1]\n if isPalindrome(left) and rright in wrap:\n ridx = wrap[rright]\n if ridx != idx:\n res.add((ridx, idx))\n\n if isPalindrome(right) and rleft in wrap:\n lidx = wrap[rleft]\n if lidx != idx:\n res.add((idx, lidx))\n return list(res) \n \n#Peak Index in a Mountain Array\nclass Solution(object):\n def peakIndexInMountainArray(self, A):\n if len(A) == 0:\n return 0\n left, right = 0, len(A) - 1\n while left < right:\n mid = int((left + right) / 2)\n if A[mid - 1] < A[mid] and A[mid] < A[mid + 1]:\n left = mid\n elif A[mid - 1] > A[mid] and A[mid] > A[mid + 1]:\n right = mid \n else:\n break\n return mid\n \n#Queue Reconstruction by Height\nclass Solution(object):\n def reconstructQueue(self, people):\n if len(people) == 0:\n return []\n people_obj, res, height = {}, [], []\n for i in range(0, len(people)):\n p = people[i]\n if p[0] in people_obj:\n people_obj[p[0]] += (p[1], i),\n else:\n people_obj[p[0]] = [(p[1], i)]\n height += (p[0]),\n \n height.sort()\n\n for i in height[::-1]:\n people_obj[i].sort()\n for p in people_obj[i]:\n res.insert(p[0], people[p[1]])\n return res\n \n#Trapping Rain Water\ndef trap(self, height):\n res = 0\n rightmax = leftmax = 0\n left, right = 0, len(height)-1\n while(left < right):\n if height[left] < height[right]:\n leftmax = max(height[left], leftmax)\n res += leftmax - height[left]\n left += 1\n else:\n rightmax = max(height[right], rightmax)\n res += rightmax - height[right]\n right -= 1\n return res\n\n#Largest Rectangle in Histogram\ndef largestRectangleArea(heights):\n stack = []\n i = 0\n area = 0\n while i < len(heights):\n if stack == [] or heights[i] > heights[stack[len(stack)-1]]:\n stack.append(i)\n else:\n curr = stack.pop()\n width = i if stack == [] else i - stack[len(stack)-1]-1\n area = max(area, width * heights[curr])\n i -= 1\n i += 1\n while stack != []:\n curr = stack.pop()\n width = i if stack == [] else len(heights) - stack[len(stack) - 1] - 1\n area = max(area, width * heights[curr])\n return area\n\n#Course Schedule\nclass Solution(object):\n def canFinish(self, num, pre):\n if num<2 or len(pre)<2:\n return True\n while True:\n count=0\n mark = [True]*num\n for p in pre:\n mark[p[0]-1] = False\n for p in pre:\n if mark[p[1]-1]:\n count+=1\n res.append(p[1]-1)\n pre.remove(p)\n if pre == []:\n return True\n elif count == 0:\n return False\n \n#Course Schedule (second solution)\ndef canFinish(self, num, pre):\n graph = {i: [] for i in range(num)}\n indegree = [0] * num\n for a, b in pre:\n graph[b].append(a)\n indegree[a] += 1\n zero = []\n for i in range(num):\n if indegree[i] == 0:\n zero.append(i)\n while zero:\n cur = zero.pop(0)\n if cur in graph:\n tmp = graph[cur]\n del graph[cur]\n \n for n in tmp:\n indegree[n] -= 1\n if indegree[n] == 0:\n zero.append(n)\n return len(graph) == 0 and sum(indegree) == 0\n\n#Course Schedule II\ndef findOrder(self, num, pre):\n res = []\n graph = {i: [] for i in range(num)}\n indegree = [0] * num\n for a, b in pre:\n graph[b].append(a)\n indegree[a] += 1\n zero = []\n for i in range(num):\n if indegree[i] == 0:\n zero.append(i)\n \n while zero:\n cur = zero.pop(0)\n res.append(cur)\n \n if cur in graph:\n tmp = graph[cur]\n del graph[cur]\n \n for n in tmp:\n indegree[n] -= 1\n if indegree[n] == 0:\n zero.append(n)\n return res if sum(indegree) == 0 else []\n\n#Longest Increasing Path in a Matrix \ndef longestIncreasingPath(self, matrix):\n h = len(matrix)\n if h == 0: return 0\n w = len(matrix[0])\n \n def dfs(x, y):\n for dx, dy in zip([1, 0, -1, 0], [0, 1, 0, -1]):\n nx = x + dx\n ny = y + dy\n if 0 <= nx < h and 0 <= ny < w and matrix[nx][ny] > matrix[x][y]:\n if not dp[nx][ny]: dp[nx][ny] = dfs(nx, ny)\n dp[x][y] = max(dp[x][y], dp[nx][ny] + 1)\n dp[x][y] = max(dp[x][y], 1)\n return dp[x][y]\n\n dp = [[0] * w for x in range(h)]\n for i in range(h):\n for j in range(w):\n if not dp[i][j]:\n dp[i][j] = dfs(i, j)\n return max([max(x) for x in dp])\n\n#Friend Circles\ndef findCircleNum(self, M):\n cnt, N= 0, len(M)\n vset = set()\n def dfs(n):\n for x in range(N):\n if M[n][x] and x not in vset:\n vset.add(x)\n dfs(x)\n \n for x in range(N):\n if x not in vset:\n cnt += 1\n dfs(x)\n return cnt\n\n#Count of Smaller Numbers After Self\nclass Solution(object):\n def countSmaller(self, num):\n idxes = {}\n for k, v in enumerate(sorted(set(num))):\n idxes[v] = k + 1\n iNums = [idxes[x] for x in num]\n ft = FenwickTree(len(iNums))\n ans = [0] * len(num)\n for i in range(len(iNums)-1, -1, -1):\n ans[i] = ft.sum(iNums[i] - 1)\n ft.add(iNums[i], 1)\n return ans\n \nclass FenwickTree(object):\n def __init__(self, n):\n self.n = n\n self.sums = [0] * (n + 1)\n \n def add(self, x, val):\n while x <= self.n:\n self.sums[x] += val\n x += self.lowbit(x)\n \n def lowbit(self, x):\n return x & -x\n \n def sum(self, x):\n res = 0\n while x > 0:\n res += self.sums[x]\n x -= self.lowbit(x)\n return res\n \n#Count of Smaller Numbers After Self (solution II)\ndef countSmaller(num):\n ipt = list(reversed(num)) #input\n sort_num = list(set(sorted(num)))\n ranks = [0] * len(num)\n for i in range(len(num)):\n tmp = ipt[i]\n ranks[i] = sort_num.index(tmp) + 1\n freq = [0] * (len(num) + 1)\n res = []\n for i in range(len(num)):\n k = ranks[i]\n freq[k] += 1\n res.append(sum(freq[:k]))\n return res[::-1]\n\n#859. Buddy Strings\nclass Solution(object):\n def buddyStrings(self, A, B):\n lenA, lenB = len(A), len(B)\n if lenA == lenB == 0:\n return False\n if lenA != lenB:\n return False\n res = [i for i in range(len(A)) if A[i] != B[i]]\n if len(res) == 0 and self.isPalindrome(A):\n return True\n elif len(res) == 0 and A[:int(lenA/2)] == A[int(lenA/2):]:\n return True\n elif len(res) != 2:\n return False\n elif A[res[0]] == B[res[1]] and A[res[1]] == B[res[0]]:\n return True\n else:\n return False\n \n def isPalindrome(self, a):\n result = [i for i in a.lower() if i.isalnum()]\n if result == result[::-1]:\n return True\n else:\n return False\n","sub_path":"python/leetcode_exercise.py","file_name":"leetcode_exercise.py","file_ext":"py","file_size_in_byte":66541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"96279659","text":"import os\n\nfrom gooddataclient.columns import Date\nfrom gooddataclient.migration.actions import AddColumn, AddDate, DeleteColumn, AlterColumn\nfrom gooddataclient.migration.chain import MigrationChain\n\n\nclass MigrationEngine(object):\n \"\"\"\n A class to generate a migration chain from a comparison\n between the state of the dataset onto the API and a dataset\n object.\n \"\"\"\n\n def __init__(self, project, dataset_class):\n self.project = project\n self.dataset = dataset_class(project)\n self.chain = None\n\n def migrate(self, dump_folder=None):\n \"\"\"\n A method to execute a migration for a given dataset.\n\n :param dump_folder: if specified, the generated maql would\n be dumped in this folder.\n \"\"\"\n # get the diff of a dataset\n dataset_diff = self.dataset.get_remote_diff()\n # generate the chain according to this diff\n self.chain = self.generate_chain(dataset_diff)\n # dump the maql if needed\n self.dump_maql(dump_folder)\n # execute the migration chain\n self.chain.execute()\n\n def generate_chain(self, dataset_diff):\n \"\"\"\n A function to generate a migration chain from a diff\n of a dataset.\n\n :param dataset_diff: a dictionary representing\n a diff between a dataset\n and its remote state on the API.\n \"\"\"\n chain = []\n\n for name, column in dataset_diff['added'].iteritems():\n Action = AddDate if isinstance(column, Date) else AddColumn\n chain.append(Action(self.dataset.identifier, name, column))\n\n for name, columns in dataset_diff['altered'].iteritems():\n chain.append(\n AlterColumn(\n schema_name=self.dataset.identifier, col_name=name,\n column=columns['old'], new_column=columns['new']\n )\n )\n\n for name, column in dataset_diff['deleted'].iteritems():\n chain.append(DeleteColumn(self.dataset.identifier, name, column))\n\n return MigrationChain(project=self.project, chain=chain)\n\n def dump_maql(self, dump_folder):\n \"\"\"\n A function to dump the maql generated by the migration.\n \"\"\"\n if dump_folder:\n file_name = 'migrate_%s.maql' % self.dataset.identifier\n file_path = os.path.join(dump_folder, file_name)\n with open(file_path, 'w') as f:\n f.write(self.chain.get_maql())\n","sub_path":"gooddataclient/migration/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":2573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"178874045","text":"\"\"\"\nGoal - To calculate x percentile acceleration for each group size and temperature.\n\nCreated - 10/20/20\n\"\"\"\n\n\n\nimport os\nimport pathlib\nfrom pprint import pprint\n\nimport numpy as np\nfrom scipy import stats\nfrom scipy.spatial import distance\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import figure\n\nimport trajectorytools as tt\nimport trajectorytools.plot as ttplot\nimport trajectorytools.socialcontext as ttsocial\nfrom trajectorytools.constants import dir_of_data\nimport csv\nimport pickle\nimport argparse\n\ndef position(tr):\n return(tr.s)\n\n\ndef speed(tr):\n v = (position(tr)[2:] - position(tr)[:-2]) / 2\n b = np.linalg.norm(v, axis=-1)\n return(b*60)\n\ndef acceleration(tr):\n a = position(tr)[2:] - 2 * position(tr)[1:-1] + position(tr)[:-2]\n aa = np.linalg.norm(a, axis=-1) \n return(aa*3600)\n \n\ndef filter(tr, roi = 5): #ind (for individual) starts from 0, roi - edge of region of interest\n position_mask0 = np.ma.masked_where((tr.distance_to_origin[1:-1] > roi)|(tr.distance_to_origin[0:-2] > roi)|(tr.distance_to_origin[2:] > roi), position(tr)[1:-1,:,0],copy=False)\n position_mask1 = np.ma.masked_where((tr.distance_to_origin[1:-1] > roi)|(tr.distance_to_origin[0:-2] > roi)|(tr.distance_to_origin[2:] > roi), position(tr)[1:-1,:,1],copy=False)\n return(position_mask0,position_mask1) \n \ndef filter_speed(tr, roi = 5): \n speed_mask = np.ma.masked_where((tr.distance_to_origin[1:-1] > roi)|(tr.distance_to_origin[0:-2] > roi)|(tr.distance_to_origin[2:] > roi), speed(tr),copy=False)\n \n return(speed_mask) \n\n\n\ndef filter_acc(tr, roi = 5): \n acc_mask = np.ma.masked_where((tr.distance_to_origin[1:-1] > roi)|(tr.distance_to_origin[0:-2] > roi)|(tr.distance_to_origin[2:] > roi), acceleration(tr),copy=False)\n \n return(acc_mask)#[~acc_mask.mask].data) \n\n#argparse\ndef boolean_string(s):\n # this function helps with getting Boolean input\n if s not in ['False', 'True']:\n raise ValueError('Not a valid boolean string')\n return s == 'True' # note use of ==\n\n# create the parser object\nparser = argparse.ArgumentParser()\n\n# NOTE: argparse will throw an error if:\n# - a flag is given with no value\n# - the value does not match the type\n# and if a flag is not given it will be filled with the default.\nparser.add_argument('-a', '--a_string', default='hi', type=str)\nparser.add_argument('-b', '--integer_b', default=90, type=int)\nparser.add_argument('-c', '--float_c', default=1.5, type=float)\nparser.add_argument('-d', '--integer_d', default=1, type=int)\nparser.add_argument('-v', '--verbose', default=True, type=boolean_string)\n# Note that you assign a short name and a long name to each argument.\n# You can use either when you call the program, but you have to use the\n# long name when getting the values back from \"args\".\n\n# get the arguments\nargs = parser.parse_args()\n\n#functions\n \n\ntemperature = range(9,30,4)\n\n\n\ngroup = [1,2,4,8,16]\n\n\n\nreplication = range(10) # number of replicates per treatment\n\n\npercentile_acc = np.empty([len(temperature), len(group)])\npercentile_acc.fill(np.nan)\n\nstd_percentile_acc = np.empty([len(temperature), len(group)])\nstd_percentile_acc.fill(np.nan)\n\n\n\n#output parent directory\nparent_dir = '../../data/temp_collective/roi'\n\nii = 0 # to keep count of temperature\n\n#frames = 5000 #number of frames for which annd is calculated\n\nfor i in temperature:\n jj = 0 # to keep count of groups\n for j in group:\n out_dir = parent_dir + '/' + str(i) + '/' + str(j) + '/' \n \n average_replicate_percentile_acc = np.empty([len(replication), 1])\n average_replicate_percentile_acc.fill(np.nan)\n\n for k in replication:\n \n if j == 1:\n input_file = out_dir + '/GS_'+str(j)+'_T_'+str(i)+'_roi_'+str(k+1)+'/trajectories.npy'\n else: \n input_file = out_dir + '/GS_'+str(j)+'_T_'+str(i)+'_roi_'+str(k+1)+'/trajectories_wo_gaps.npy'\n \n \n \n \n try:\n tr = tt.Trajectories.from_idtrackerai(input_file, \t\t center=True).normalise_by('body_length')\n tr.new_time_unit(tr.params['frame_rate'], 'seconds')\t\t\n \n except FileNotFoundError:\n print(i,j,k)\n print('File not found')\n continue\n \n average_replicate_percentile_acc[k] = np.percentile(filter_acc(tr,5).compressed(),args.integer_b)\n \n \n \n \n percentile_acc[ii, jj] = np.nanmean(average_replicate_percentile_acc)\n std_percentile_acc[ii,jj] = np.nanstd(average_replicate_percentile_acc)\n\n \n \n jj= jj + 1\n \n ii = ii + 1\n\nout_dir = '../../output/temp_collective/roi/'\n\n# save it as a pickle file\np_c_fn1 = out_dir + 'percentile_acc' + str(args.integer_b)+ '.p'\npickle.dump(percentile_acc, open(p_c_fn1, 'wb')) # 'wb' is for write binary\n\np_c_fn2 = out_dir + 'percentile_acc' + str(args.integer_b) + '_std.p'\npickle.dump(std_percentile_acc, open(p_c_fn2, 'wb')) # 'wb' is for write binary\n \n","sub_path":"percentile_acc.py","file_name":"percentile_acc.py","file_ext":"py","file_size_in_byte":5127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"54278352","text":"\"\"\"\nThis example music bot is powered by lavalink.py\n\"\"\"\n\nimport re\nimport dico\nimport lavalink\n\n\nclient = dico.Client(\"YOUR_BOT_TOKEN\")\nlava = lavalink.Client(user_id=0) # Your bot client ID\nlava.add_node(host=\"localhost\", port=0, password=\"PASSWORD\", region=\"ko\")\nclient.on_raw = lava.voice_update_handler\nclient.on_ready = lambda ready: print(f\"Bot ready, with {len(ready.guilds)} guilds.\")\n\n\ndef verify_voice_state(voice_state):\n if not voice_state or not voice_state.channel_id:\n return \"Please connect or reconnect to the voice channel first.\"\n return None\n\n\ncolor_accept = 0x3dd415\ncolor_deny = 0xe74c3c\ncolor_white = 0xe1e1e1\n\n\n@client.on_message_create\nasync def on_message(message: dico.MessageCreate):\n if message.content.startswith(\"!connect\"):\n voice_state = message.author.voice_state\n vv = verify_voice_state(voice_state)\n if vv:\n return await message.reply(embed=dico.Embed(description=vv, color=0xe74c3c))\n lava.player_manager.create(int(message.guild_id), region=\"ko\")\n await client.ws.update_voice_state(str(message.guild_id), str(voice_state.channel_id), False, False)\n\n if message.content.startswith(\"!disconnect\"):\n msg = await message.reply(embed=dico.Embed(description=\"Please wait, disconnecting...\"))\n await client.ws.update_voice_state(str(message.guild_id), None, False, False)\n await msg.edit(embed=dico.Embed(description=\"Successfully disconnected from voice channel!\", color=color_accept))\n player = lava.player_manager.get(int(message.guild_id))\n if player:\n await lava.player_manager.destroy(message.guild_id)\n\n if message.content.startswith(\"!play \"):\n voice_state = message.author.voice_state\n vv = verify_voice_state(voice_state)\n if vv:\n return await message.reply(embed=dico.Embed(description=vv, color=color_deny))\n url = message.content[len(\"!play \"):]\n if not re.match(\"https?://(?:www\\.)?.+\", url):\n url = f\"ytsearch:{url}\"\n player = lava.player_manager.get(int(message.guild_id))\n if not player:\n return await message.reply(embed=dico.Embed(description=\"Please run `!connect` first.\", color=color_deny))\n resp = await player.node.get_tracks(url)\n if resp is None or len(resp[\"tracks\"]) == 0:\n return await message.reply(embed=dico.Embed(description=\"Unable to find any song.\", color=color_deny))\n msg = await message.reply(embed=dico.Embed(description=\"Found the music, please wait...\"))\n track = None\n if resp[\"loadType\"] == \"PLAYLIST_LOADED\":\n return await msg.edit(content=\"Sorry, playlist is not supported.\")\n elif resp[\"loadType\"] == \"SEARCH_RESULT\":\n return await msg.edit(content=\"Sorry, searching is not supported.\")\n track = track or resp['tracks'][0]\n player.add(requester=message.author.id, track=track)\n if not player.is_playing:\n await player.play()\n await msg.edit(content=\"\", embed=dico.Embed(description=f\"Playing [{track['info']['title']}]({track['info']['uri']}).\", color=color_accept))\n else:\n await msg.edit(content=\"\", embed=dico.Embed(description=f\"Added [{track['info']['title']}]({track['info']['uri']}) to queue.\", color=color_accept))\n\n if message.content.startswith(\"!skip\"):\n voice_state = message.author.voice_state\n vv = verify_voice_state(voice_state)\n if vv:\n return await message.reply(embed=dico.Embed(description=vv, color=color_deny))\n player = lava.player_manager.get(int(message.guild_id))\n msg = await message.reply(embed=dico.Embed(description=\"Skipping this music...\"))\n await player.skip()\n await msg.edit(embed=dico.Embed(description=\"Done skipping!\", color=color_accept))\n\n if message.content.startswith(\"!loop\") or message.content.startswith(\"!repeat\"):\n voice_state = message.author.voice_state\n vv = verify_voice_state(voice_state)\n if vv:\n return await message.reply(embed=dico.Embed(description=vv, color=color_deny))\n player = lava.player_manager.get(int(message.guild_id))\n player.set_repeat(not player.repeat)\n await message.reply(f\"Repeat is {'enabled' if player.repeat else 'disabled'}.\")\n\n\nclient.run()\n","sub_path":"examples/music.py","file_name":"music.py","file_ext":"py","file_size_in_byte":4353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"511570269","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom sklearn.metrics import confusion_matrix\nfrom copy import deepcopy\nimport torch.nn.functional as F\n\n\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n\nclass PN():\n def __init__(self, args, opt, model, tensorboard, source_dataloaders, target_dataloader):\n self.device = device\n\n self.args = args\n self.opt = opt\n self.tensorboard = tensorboard\n\n # init dataloader\n self.source_dataloaders = source_dataloaders\n self.target_dataloader = target_dataloader\n\n self.net = model.Extractor(opt).to(device)\n\n # init criterions\n self.class_criterion = nn.NLLLoss()\n\n self.target_support_set = next(iter(target_dataloader['train']))\n\n self.iters_spt = [iter(self.source_dataloaders[i]['train']) for i in range(len(self.source_dataloaders))]\n self.iters_qry = [iter(self.source_dataloaders[i]['test']) for i in range(len(self.source_dataloaders))]\n\n # init self.optimizer\n self.optimizer = optim.Adam([{'params': self.net.parameters()}], lr=opt['learning_rate'],\n weight_decay=opt['weight_decay'])\n\n def save_checkpoint(self, epoch, epoch_acc, best_acc, checkpoint_path):\n state = {}\n state['epoch'] = epoch\n state['epoch_acc'] = epoch_acc\n state['best_acc'] = best_acc\n state['class_classifier'] = self.net.state_dict()\n state['optimizer'] = self.optimizer.state_dict()\n\n torch.save(state, checkpoint_path)\n\n return\n\n def load_checkpoint(self, checkpoint_path):\n path = checkpoint_path\n checkpoint = torch.load(path)\n\n self.net.load_state_dict(checkpoint['class_classifier'])\n self.optimizer.load_state_dict(checkpoint['optimizer'])\n\n return checkpoint\n\n def reset_layer(self):\n # Remember that Pytorch accumulates gradients.x\n # We need to clear them out before each instance\n # that means we have to call optimizer.zero_grad() before each backward.\n self.net.zero_grad()\n\n def get_label_and_data(self, data):\n input_of_data, class_label_of_data, domain_label_of_data = data\n input_of_data = input_of_data.to(device)\n class_label_of_data = class_label_of_data.to(device)\n domain_label_of_data = domain_label_of_data.to(device)\n\n return input_of_data, class_label_of_data, domain_label_of_data\n\n def euclidean_dist(self, x, y):\n '''\n Compute euclidean distance between two tensors\n '''\n # x: N (minibatch size) x D\n # y: M (num class) x D. prototypes\n n = x.size(0)\n m = y.size(0)\n d = x.size(1)\n if d != y.size(1):\n raise Exception\n\n x = x.unsqueeze(1).expand(n, m, d)\n y = y.unsqueeze(0).expand(n, m, d)\n\n return torch.pow(x - y, 2).sum(2)\n\n def get_prototypes(self, feature_extractor, data, label):\n\n feature_spt = feature_extractor(data)\n\n prototpyes = torch.FloatTensor(self.opt['num_class'], feature_spt.shape[-1]).to(device) # make FloatTensor with shape num_classes x F-dim1 x F-dim2...\n for i in range(self.opt['num_class']):\n prototpyes[i] = feature_spt[(label == i).nonzero().view(-1)].mean(0)\n\n self.prototypes = prototpyes\n\n def get_loss_and_confusion_matrix_for_query(self, feature_extractor, criterion, data, label):\n\n feature_data = feature_extractor(data)\n feature_data = feature_data.view(feature_data.shape[0],-1) # KN, 30720\n\n dists = self.euclidean_dist(feature_data, self.prototypes)\n preds_of_data = F.log_softmax(-dists, dim=1)\n loss_of_data = criterion(preds_of_data, label)\n pred_label = preds_of_data.max(1, keepdim=False)[1]\n\n labels = [i for i in range(len(self.opt['classes']))]\n cm = confusion_matrix(label.cpu().numpy(), pred_label.cpu().numpy(), labels=labels)\n\n return loss_of_data, cm\n\n def log_loss_results(self, condition, epoch, loss_avg, nshot=5):\n\n self.tensorboard.log_scalar(condition + '/loss_sum_' + str(nshot) + 'shot', loss_avg, epoch)\n\n return loss_avg\n\n def log_accuracy_results(self, condition, suffix, epoch, cm_class, nshot = 5):\n\n assert (condition in ['valid', 'test'])\n assert (suffix in ['labeled', 'unlabeled', 'test'])\n\n class_accuracy = 100.0 * np.sum(np.diagonal(cm_class)) / np.sum(cm_class)\n self.tensorboard.log_scalar(condition + '/' + 'accuracy_class_' + suffix + '_' + str(nshot) + 'shot',\n class_accuracy, epoch)\n\n self.tensorboard.log_confusion_matrix(condition + '_accuracy_class_' + suffix + '_' + str(nshot) + 'shot',\n cm_class,\n self.opt['classes'], epoch)\n return class_accuracy\n\n def generate_random_tasks(self, num_repeat = 1):\n\n # generate synthetic domain\n\n with torch.no_grad():\n support_set_from_domains = []\n query_set_from_domains = []\n weights_per_domain = []\n\n for domain_i in range(len(self.source_dataloaders)): # for each task\n\n try:\n train_batch_i = next(self.iters_spt[domain_i])\n except StopIteration:\n self.iters_spt[domain_i] = iter(self.source_dataloaders[domain_i]['train'])\n train_batch_i = next(self.iters_spt[domain_i])\n\n try:\n test_batch_i = next(self.iters_qry[domain_i])\n except StopIteration:\n self.iters_qry[domain_i] = iter(self.source_dataloaders[domain_i]['test'])\n test_batch_i = next(self.iters_qry[domain_i])\n\n\n\n support_set_from_domains.append(train_batch_i)\n query_set_from_domains.append(test_batch_i)\n \n for _ in range(len(self.source_dataloaders[domain_i]['train'])): # append domain_i as many as the number of the domain data\n weights_per_domain.append(domain_i)\n\n synthetic_supports = [] # list of (K shot x Num classes x dim1 x dim2, Kshot x NC, K shot x NC)\n synthetic_queries = []\n\n for i in range(num_repeat):\n selected_domain_indices = np.random.choice(weights_per_domain, self.opt['num_class']) # generate random indices to choose domain per class\n tmp_spt_feat = torch.FloatTensor(support_set_from_domains[0][0].shape[0], 0, *(support_set_from_domains[0][0].shape[2:]))\n tmp_spt_cl = torch.LongTensor(support_set_from_domains[0][1].shape[0], 0)\n tmp_spt_dl = torch.LongTensor(support_set_from_domains[0][2].shape[0], 0)\n\n tmp_qry_feat = torch.FloatTensor(query_set_from_domains[0][0].shape[0], 0, *(support_set_from_domains[0][0].shape[2:]))\n tmp_qry_cl = torch.LongTensor(query_set_from_domains[0][1].shape[0], 0)\n tmp_qry_dl = torch.LongTensor(query_set_from_domains[0][2].shape[0], 0)\n\n\n for class_id, domain_id in enumerate(selected_domain_indices):\n class_id = np.random.randint(self.opt['num_class']) # set a random class id\n class_id = torch.tensor([class_id])\n\n ## for support set\n feature, class_label, domain_label = support_set_from_domains[domain_id]\n\n #select class dimension\n indices = class_label == class_id\n feature = feature[indices].view(feature.shape[0],1,*feature.shape[2:])\n class_label = class_label[indices].view(-1,1)\n domain_label = domain_label[indices].view(-1,1)\n\n tmp_spt_feat = torch.cat((tmp_spt_feat, feature), dim=1)\n tmp_spt_cl = torch.cat((tmp_spt_cl, class_label), dim=1)\n tmp_spt_dl = torch.cat((tmp_spt_dl, domain_label), dim=1)\n\n\n ## for query set\n feature, class_label, domain_label = query_set_from_domains[domain_id]\n\n # select class dimension\n indices = class_label == class_id\n feature = feature[indices].view(feature.shape[0],1,*feature.shape[2:])\n class_label = class_label[indices].view(-1,1)\n domain_label = domain_label[indices].view(-1,1)\n\n tmp_qry_feat = torch.cat((tmp_qry_feat, feature), dim=1)\n tmp_qry_cl = torch.cat((tmp_qry_cl, class_label), dim=1)\n tmp_qry_dl = torch.cat((tmp_qry_dl, domain_label), dim=1)\n\n synthetic_supports.append([tmp_spt_feat, tmp_spt_cl, tmp_spt_dl])\n synthetic_queries.append([tmp_qry_feat, tmp_qry_cl, tmp_qry_dl])\n\n\n return synthetic_supports, synthetic_queries\n\n def train(self, epoch):\n \"\"\"\n Train the model\n \"\"\"\n\n # setup models\n num_task = len(self.source_dataloaders)\n\n self.net.train()\n\n losses_q = 0.0\n confusion_matrices = np.zeros((self.opt['num_class'], self.opt['num_class']),dtype=int)\n self.reset_layer()\n\n\n synthetic_supports, synthetic_queries = self.generate_random_tasks(num_repeat=num_task)\n\n\n\n for task_i in range(num_task): # for each task\n\n support_batch = synthetic_supports[task_i]\n query_batch = synthetic_queries[task_i]\n\n support_set = support_batch\n query_set = query_batch\n\n for k in range(self.args.nshot): # give random class number of increasing order\n for i in range(self.opt['num_class']):\n support_set[1][k][i] = i\n query_set[1][k][i] = i\n\n\n support_set[0] = support_set[0].view(-1, *(support_set[0].shape[2:]))# K shot x Num classes x dim1 x dim2 ... => KN x dim1 x dim2 ...\n support_set[1] = support_set[1].view(-1)\n support_set[2] = support_set[2].view(-1)\n\n\n query_set[0] = query_set[0].view(-1,*(query_set[0].shape[2:]))\n query_set[1] = query_set[1].view(-1)\n query_set[2] = query_set[2].view(-1)\n\n input_labeled_spt, class_label_labeled_spt, _ = self.get_label_and_data(support_set)\n input_labeled_qry, class_label_labeled_qry, _ = self.get_label_and_data(query_set)\n\n self.get_prototypes(self.net, input_labeled_spt, class_label_labeled_spt)\n\n class_loss_query, cm_query = self.get_loss_and_confusion_matrix_for_query(self.net,\n self.class_criterion,\n input_labeled_qry,\n class_label_labeled_qry)\n\n losses_q += class_loss_query\n\n with torch.no_grad():\n confusion_matrices = confusion_matrices + cm_query\n\n loss_query = losses_q / num_task\n\n self.optimizer.zero_grad()\n loss_query.backward()\n self.optimizer.step()\n\n losses_q = loss_query.item()\n accs = 100 * np.sum(np.diagonal(confusion_matrices))/np.sum(confusion_matrices)\n\n np.set_printoptions(formatter={'float': lambda x: \"{0:0.2f}\".format(x)})\n print('###############################################################')\n print('[Train] epoch:' + str(epoch) + '\\tloss:' + str(losses_q))\n print('[Train] epoch:' + str(epoch) + '\\taccs:' + str(accs))\n\n self.log_loss_results('train', epoch=epoch, loss_avg=loss_query)\n self.log_accuracy_results('test',\n 'labeled',\n epoch,\n cm_class=confusion_matrices)\n return\n\n\n def evaluation(self, epoch, condition, nshot=5):\n\n confusion_matrices = np.zeros((self.opt['num_class'], self.opt['num_class']),dtype=int)\n self.reset_layer()\n\n # in order to not ruin the state of running_mean/variance and bn_weight/bias\n # we finetunning on the copied model instead of self.net\n net = deepcopy(self.net)\n net.train()\n losses_q = 0.0\n\n support_set = [x[:nshot].data.clone() for x in self.target_support_set] # evaluation with only nshots\n support_set[0] = support_set[0].view(-1, *(support_set[0].shape[2:]))\n support_set[1] = support_set[1].view(-1)\n support_set[2] = support_set[2].view(-1)\n\n for batch_idx, query_set in tqdm(enumerate(self.target_dataloader[condition]), total=len(self.target_dataloader[condition])):\n\n query_set[0] = query_set[0].view(-1, *(query_set[0].shape[2:]))\n query_set[1] = query_set[1].view(-1)\n query_set[2] = query_set[2].view(-1)\n\n input_labeled_spt, class_label_labeled_spt, _ = self.get_label_and_data(support_set)\n input_labeled_qry, class_label_labeled_qry, _ = self.get_label_and_data(query_set)\n\n self.get_prototypes(self.net, input_labeled_spt, class_label_labeled_spt)\n\n class_loss_query, cm_query = self.get_loss_and_confusion_matrix_for_query(self.net,\n self.class_criterion,\n input_labeled_qry,\n class_label_labeled_qry)\n\n with torch.no_grad():\n confusion_matrices = confusion_matrices + cm_query\n losses_q += class_loss_query\n\n accs = 100 * np.sum(np.diagonal(confusion_matrices))/np.sum(confusion_matrices)\n np.set_printoptions(formatter={'float': lambda x: \"{0:0.3f}\".format(x)})\n print('---------------------------------------------------')\n print('[{:s}] epoch:{:d} nshot:{:d}'.format(condition, epoch, nshot) + '\\tloss:' + str(losses_q))\n print('[{:s}] epoch:{:d} nshot:{:d}'.format(condition, epoch, nshot) + '\\taccs:' + str(accs))\n\n self.log_loss_results(condition, epoch=epoch, loss_avg=losses_q)\n self.log_accuracy_results(condition,\n 'test',\n epoch,\n cm_class=confusion_matrices, nshot=nshot)\n return accs, losses_q\n\n\n def validation(self, epoch):\n \"\"\"\n Validate the performance of the model\n \"\"\"\n class_accuracy_of_test_data, loss = self.evaluation(epoch, 'valid', nshot=5)\n\n # setup the network\n return class_accuracy_of_test_data, loss\n\n def test(self, epoch):\n \"\"\"\n Test the performance of the model\n \"\"\"\n class_accuracy_of_test_data = []\n for i in range(10):\n accuracy_for_shot, loss_fot_shot = self.evaluation(epoch, 'test', nshot= i + 1)\n class_accuracy_of_test_data.append(accuracy_for_shot)\n\n return class_accuracy_of_test_data\n","sub_path":"learner/pn.py","file_name":"pn.py","file_ext":"py","file_size_in_byte":15278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"623858072","text":"# -*- coding: utf-8 -*-\nfrom week5_day04.dbutil import dbutil\n\n# 作业: 自定义的管道,将完整的爬取数据,保存到MySql数据库中\nclass JobspidersPipeline(object):\n def process_item(self, item, spider):\n dbu = dbutil.MYSQLdbUtil()\n dbu.getConnection() # 开启事物\n\n # 1.添加\n try:\n sql = \"insert into boss_job (job_title,compensation,company,address,seniority,education,company_type,company_finance,company_quorum)values(%s,%s,%s,%s,%s,%s,%s,%s,%s)\"\n #date = []\n #dbu.execute(sql, date, True)\n dbu.execute(sql, (item[\"job_title\"],item[\"compensation\"],item[\"company\"],item[\"address\"],item[\"seniority\"],item[\"education\"],item[\"company_type\"],item[\"company_finance\"],item[\"company_quorum\"]),True)\n dbu.commit()\n print('插入数据库成功!!')\n except:\n dbu.rollback()\n dbu.commit() # 回滚后要提交\n finally:\n dbu.close()\n return item","sub_path":"spider/jobboss/jobboss/pipelinesmysql.py","file_name":"pipelinesmysql.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"204611913","text":"import json\nimport twilio\nfrom twilio.rest import Client\n\nwith open(\"config.json\") as f:\n config = json.load(f)\n TWILIO_SID = config[\"TWILIO_SID\"]\n TWILIO_TOKEN = config[\"TWILIO_TOKEN\"]\n TWILIO_FROM = config[\"TWILIO_FROM\"]\n TWILIO_TO = config[\"TWILIO_TO\"]\n\n\nclass Notifier:\n def __init__(self):\n self.client = Client(TWILIO_SID, TWILIO_TOKEN)\n\n def send(self, msg):\n try:\n ids = []\n for receiver in TWILIO_TO:\n message = self.client.messages.create(\n to=receiver,\n from_=TWILIO_FROM,\n body=\"Mcafee Bot: \" + msg)\n ids.append(message.sid)\n return ids\n except twilio.TwilioRestException as e:\n print(e)\n\n def buy(self, coin):\n self.send(\"Consider buying \" + str(coin))\n\n\nif __name__ == \"__main__\":\n nofifier = Notifier()\n","sub_path":"notifier.py","file_name":"notifier.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"95984535","text":"from excecoes import ElementoInexistente, ElementoInvalido\n\nclass RepositorioProdutos:\n produtos = []\n def __init__ (self):\n self.produtos = [\n {\n 'id': 1,\n 'nome': u\"Blu-ray - O exterminador do Futuro\",\n 'descricao': u\"Androide vem do futuro com o objetivo de matar a mae de um futuro lider guerrilhero humano.\",\n 'preco': 22.41,\n \t\t'quantidade': 10,\n \t\t'categoria' : \"DVD\"\n },\n {\n 'id': 3,\n 'nome': u\"Exterminador de cupins 400ml\",\n 'descricao': u\"O exterminador de cupins\", \n 'preco': 19.33,\n \t\t'quantidade': 30,\n \t\t'categoria' : \"limpeza\"\n },\t\n \t{\n 'id': 4,\n 'nome': u\"Fantasia Adulto Exterminador John Connor\",\n 'descricao': u\"Transforme-se em seu heroi\", \n 'preco': 300.85,\n \t\t'quantidade': 3,\n \t\t'categoria' : \"fantasia\"\n }\t\n ]\n\n def listar(self):\n return self.produtos\n\n def buscarPorId(self, prodid):\n resultado = [produto for produto in self.produtos if produto['id'] == prodid]\n if len(resultado) == 0: \n raise ElementoInexistente\n return resultado[0] \n \n def remover(self, prodid):\n produto = self.buscarPorId(prodid);\n self.produtos.remove(produto[0])\n \n def adicionar(self, prod):\n if not (prod and all (k in prod for k in ('nome', 'preco', 'categoria'))): \n raise ElementoInvalido\n else:\n produto = {\n 'id': self.produtos[-1]['id'] + 1,\n 'nome': prod['nome'],\n 'descricao': prod.get('descricao', \"\"),\n 'preco': prod['preco'],\n 'quantidade': prod.get('quantidade', 0),\n 'categoria': prod['categoria']\n }\n self.produtos.append(produto)\n return produto;\n \n def atualizar(self, novoprod):\n if novoprod : \n produto = self.buscarPorId(novoprod['id'])\n produto['nome'] = novoprod.get('nome', produto['nome'])\n produto['descricao'] = novoprod.get('descricao', produto['descricao'])\n produto['preco'] = novoprod.get('preco', produto['preco'])\n produto['quantidade'] = novoprod.get('quantidade', produto['quantidade'])\n produto['categoria'] = novoprod.get('categoria', produto['categoria']) \n return produto;\n else:\n raise ElementoInvalido","sub_path":"4-app/produtos.py","file_name":"produtos.py","file_ext":"py","file_size_in_byte":2631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"84048976","text":"from create_singly_list_node import ListNode, listNodeToString, stringToListNode\n\n\nclass Solution:\n def reverseList(self, head: ListNode) -> ListNode:\n \"\"\"\n https://leetcode.com/problems/reverse-linked-list/\n // Time Complexity : O(n)\n // Space Complexity : O(1)\n // Did this code successfully run on Leetcode : Yes\n // Three line explanation of solution in plain english :\n - Fast and Prev pointer point to None\n - Move fast pointer first, adjust other pointers\n - Return the prev\n \"\"\"\n # if one head or no head\n if not head or not head.next:\n return head\n\n prev = None\n current = slow\n fast = None\n while current:\n fast = current.next\n current.next = prev\n prev = current\n current = fast\n return prev\n\n def reverseList_recursive(self, head: ListNode) -> ListNode:\n \"\"\"\n // Time Complexity : O(n)\n // Space Complexity : O(n) if recursive stack\n \"\"\"\n # base\n if head is None or head.next is None:\n return head\n # logic\n reversed_head = self.reverseList_recursive(head.next)\n head.next.next = head\n head.next = None\n return reversed_head\n\n\nif __name__ == '__main__':\n h = Solution()\n head = stringToListNode([1, 2, 3, 4, 5])\n new_head = h.reverseList(head)\n print(listNodeToString(new_head))\n","sub_path":"206_reverse_linked_list.py","file_name":"206_reverse_linked_list.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"249919660","text":"from django.views.generic.base import View\nfrom django.views.generic.detail import SingleObjectMixin\nfrom .models import Category, Cart, Customer\nfrom django.db import models\n\n\nclass CommonMixin(SingleObjectMixin):\n \"\"\"Mixin for showing category\"\"\"\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['categories'] = Category.objects.all()\n return context\n\n\nclass CartMixin(View):\n \"\"\"Mixin for basket\"\"\"\n def dispatch(self, request, *args, **kwargs):\n if request.user.is_authenticated:\n\n customer = Customer.objects.filter(user=request.user).first()\n cart = Cart.objects.filter(customer=customer, in_order=False).first()\n if not customer:\n customer = Customer.objects.create(\n user=request.user\n )\n\n if not cart:\n cart = Cart.objects.create(\n customer=customer\n )\n self.customer = customer\n else:\n cart = 0\n # cart = Cart.objects.filter(for_anonymous_user=True).first()\n # if not cart:\n # cart = Cart.objects.create(for_anonymous_user=True)\n self.cart = cart\n return super().dispatch(request, *args, **kwargs)\n\n\ndef save_cart(cart):\n \"\"\"An analogue of the `save ()` method\"\"\"\n cart_product = cart.products.aggregate(models.Sum('all_price'), models.Sum('count'))\n count = cart_product['count__sum']\n if cart_product.get('all_price__sum'):\n if count >= 3 and count <= 5:\n cart.discount = cart_product['all_price__sum'] - (cart_product['all_price__sum'] * 5) / 100\n cart.all_price = 0\n elif count > 5:\n cart.discount = cart_product['all_price__sum'] - (cart_product['all_price__sum'] * 10) / 100\n cart.all_price = 0\n else:\n cart.all_price = cart_product['all_price__sum']\n cart.discount = 0\n else:\n cart.discount = 0\n cart.all_price = 0\n\n cart.all_product = cart_product['count__sum']\n cart.save()\n","sub_path":"product/mixins.py","file_name":"mixins.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"219327846","text":"#!/usr/bin/env python\n\n\"\"\"\n.. See the NOTICE file distributed with this work for additional information\n regarding copyright ownership.\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\nfrom __future__ import print_function\nimport os\n\n#Required for ReadTheDocs\nfrom functools import wraps\n\nimport argparse\n\nfrom basic_modules.workflow import Workflow\nfrom utils import logger\n\nfrom tool.makeDesignFiles_Tool import makeDesignFilesTool\n\n#####################################################\n\nclass process_makeDesign(Workflow):\n \"\"\"\n This class generates the Design files and chinput files,\n imput for CHiCAGO. Starting from rmap and baitmap and capture\n HiC BAM files.\n \"\"\"\n\n def __init__(self, configuration=None):\n \"\"\"\n Initiate the class\n\n Parameters\n -----------\n Configuration: dict\n dictionary with parameters for different tools from the class\n indicating how to run each of them.\n \"\"\"\n\n logger.info(\"Generating CHiCAGO input Design files\")\n if configuration is None:\n configuration = {}\n\n self.configuration.update(configuration)\n\n def run(self, input_files, input_metadata, output_files):\n \"\"\"\n Main function to run the tools, MakeDesignFiles_Tool.py and\n bam2chicago_Tool.py\n\n Parameters\n ----------\n input_files: dict\n designDir: path to the folder with .rmap and .baitmap files\n rmapFile: path to the .rmap file\n baitmapFile: path to the .baitmap file\n bamFile: path to the capture HiC bamfiles\n\n input_metadata: dict\n input metadata\n\n output_files: dict\n outPrefixDesign : Path and name of the output prefix,\n recommend to be the same as rmap and baitmap files.\n sample_name: Path and name of the .chinput file\n\n Returns\n -------\n bool\n output_metadata\n \"\"\"\n\n makeDesign_caller = makeDesignFilesTool(self.configuration)\n makeDesgin_out, makeDesign_outMeta = makeDesign_caller.run(\n {\n \"designDir\" : input_files[\"designDir\"]\n },\n {\n \".rmap\" : input_metadata[\".rmap\"],\n \".baitmap\" : input_metadata[\".baitmap\"]\n },\n {\n \"outPrefixDesign\" : output_files[\"outPrefixDesign\"]\n }\n )\n\n if os.path.isfile(output_files[\"outPrefixDesign\"] + \".nbpb\") is True:\n pass\n else:\n logger.fatal(\"process_makeDesign failed to\" +\n \"generate design files\")\n return False\n\n return makeDesgin_out, makeDesign_outMeta\n\n#############################################################\n\ndef main_json(config, in_metadata, out_metadata):\n \"\"\"\n Alternative main function\n\n This function lauch the app using the configuration written\n in two json files:\n \"\"\"\n #1.Instantiate and launch the app\n print(\"Instantiate and launch the App\")\n from apps.jsonapp import JSONApp\n app = JSONApp()\n results = app.launch(process_makeDesign,\n config,\n in_metadata,\n out_metadata)\n\n #2. The App has finished\n print(\"2. Execution finished: see \" + out_metadata)\n print(results)\n\n return results\n\n#########################################################\n\nif __name__ == \"__main__\":\n\n #sert up the command line parameters\n PARSER = argparse.ArgumentParser(\n description=\"Pipeline to generate Design files\")\n\n PARSER.add_argument(\"--config\", help=\"Configuration file\")\n PARSER.add_argument(\n \"--in_metadata\", help=\"Location of metadata file\")\n PARSER.add_argument(\n \"--out_metadata\", help=\"Location of output metadata file\")\n PARSER.add_argument(\n \"--local\", action=\"store_const\", cont=True, default=False)\n\n #Get matching parameters from the command line\n ARGS = PARSER.parse_args()\n\n CONFIG = ARGS.config\n IN_METADATA = ARGS.IN_METADATA\n OUT_METADATA = ARGS.OUT_METADATA\n LOCAL = ARGS.local\n if LOCAL:\n import sys\n sys._run_from_cmdl = True\n\n RESULTS = main_json(CONFIG, IN_METADATA, OUT_METADATA)\n\n print(RESULTS)\n","sub_path":"process_Design.py","file_name":"process_Design.py","file_ext":"py","file_size_in_byte":4805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"615291440","text":"#!/usr/bin/env python3\nimport mysql.connector\nfrom mysql.connector import Error\n\n\nclass Phones(object):\n def __init__(self,cur,con):\n self.cur = cur\n self.con = con\n pass\n\n def loadData(self):\n ls = []\n workSelect = \"SELECT * FROM Phone\"\n self.cur.execute(workSelect)\n for (id, number, idcontact) in self.cur:\n ls.append( (id, number, idcontact) )\n return ls\n\n def addData(self,data):\n addPhone = (\"INSERT INTO Phone \"\n \"(number, idcontact)\"\n \"VALUES (%(number)s, %(idcontact)s)\")\n self.cur.execute(addPhone, data)\n self.con.commit()\n\n def getContactName(self,id):\n getContact = ( \" SELECT name FROM Contact WHERE id = \" +str(id) )\n try:\n self.cur.execute(getContact)\n contactName = 0\n for name in self.cur:\n return name[0]\n except AttributeError:\n return None\n except Exception as e: \n print(e) \n return None\n\n\n def updateData(self,data,id):\n updatePhone = (\"UPDATE Phone SET number = %(number)s WHERE id = \" +str(id) + \" \" )\n self.cur.execute(updatePhone, data)\n self.con.commit()\n\n def delete(self,id):\n deleteWork = \"DELETE FROM Phone WHERE id = \" + str(id) + \" \"\n self.cur.execute(deleteWork)\n self.con.commit()\n\n\n\n\n ","sub_path":"classes/Phones.py","file_name":"Phones.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"247756476","text":"___name___ = \"Homescreen (Default)\"\n___license___ = \"MIT\"\n___categories___ = [\"Homescreens\"]\n___dependencies___ = [\"homescreen\", \"shared/logo.png\", \"shared/sponsors.png\"]\n___launchable___ = False\n___bootstrapped___ = True\n\nimport ugfx\nfrom homescreen import *\nimport time\n\n# We ❤️ our sponsors\nugfx.display_image(0, 0, \"shared/sponsors.png\")\nwait = 5\nwhile wait:\n wait-=1\n sleep_or_exit(0.5)\n\n# Padding for name\nintro_height = 30\nintro_text = \"Hi! I'm\"\nname_height = 60\nstatus_height = 20\ninfo_height = 30\nlogo_path = \"shared/logo.png\"\nlogo_height = 150\nlogo_width = 56\n\n# Maximum length of name before downscaling\nmax_name = 8\n\n# Background stuff\ninit()\nugfx.clear(ugfx.html_color(0x800080))\n\n# Colour stuff\nstyle = ugfx.Style()\nstyle.set_enabled([ugfx.WHITE, ugfx.html_color(0x800080), ugfx.html_color(0x800080), ugfx.html_color(0x800080)])\nstyle.set_background(ugfx.html_color(0x800080))\nugfx.set_default_style(style)\n\n# Logo stuff\nugfx.display_image(\n int((ugfx.width() - logo_width) / 2),\n int((ugfx.height() - logo_height) / 2),\n logo_path\n)\n\n\n\n# Draw for people to see\nugfx.orientation(90)\n# Draw introduction\nugfx.set_default_font(ugfx.FONT_TITLE)\nugfx.Label(0, ugfx.height() - name_height - intro_height, ugfx.width(), intro_height, intro_text, justification=ugfx.Label.CENTER)\n# Process name\nname_setting = name(\"Set your name in the settings app\")\nif len(name_setting) <= max_name:\n ugfx.set_default_font(ugfx.FONT_NAME)\nelse:\n ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD)\n# Draw name\nugfx.Label(0, ugfx.height() - name_height, ugfx.width(), name_height, name_setting, justification=ugfx.Label.CENTER)\n\n\n\n# Draw for wearer to see\nugfx.orientation(270)\n# Title\nugfx.set_default_font(ugfx.FONT_TITLE)\nugfx.Label(0, ugfx.height() - info_height * 2, ugfx.width(), info_height, \"TiLDA Mk4\", justification=ugfx.Label.CENTER)\n# info\nugfx.Label(0, ugfx.height() - info_height, ugfx.width(), info_height, \"Press MENU\", justification=ugfx.Label.CENTER)\n\nugfx.set_default_font(ugfx.FONT_SMALL)\nstatus = ugfx.Label(0, ugfx.height() - info_height * 2 - status_height, ugfx.width(), status_height, \"\", justification=ugfx.Label.CENTER)\n\nfrom tilda import Sensors\nfrom machine import Neopix\nn = Neopix()\n# update loop\nwhile True:\n text = \"\";\n value_wifi_strength = wifi_strength()\n value_battery = battery()\n lux = Sensors.get_lux()\n if lux < 1000:\n n.display([0xffffff, 0xffffff])\n elif lux < 2000:\n n.display([0xff00ff, 0xff00ff])\n elif lux < 3000:\n n.display([0x0000ff, 0x0000ff])\n elif lux < 4000:\n n.display([0x00ffff, 0x00ffff])\n elif lux < 5000:\n n.display([0x00ff00, 0x00ff00])\n elif lux < 6000:\n n.display([0xffff00, 0xffff00])\n elif lux < 7000:\n n.display([0xffa500, 0xffa500])\n elif lux < 8000:\n n.display([0xff0000, 0xff0000])\n else:\n n.display([0x000000, 0x000000])\n\n if value_wifi_strength:\n text += \"Wi-Fi: %s%%, \" % int(value_wifi_strength)\n if value_battery:\n text += \"Battery: %s%%\" % int(value_battery)\n status.text(text)\n sleep_or_exit(0.5)\n","sub_path":"jim-homescreen/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"198435747","text":"#%%\nimport numpy as np\nimport time\nfrom scipy import special\nimport matplotlib.pylab as plt\n\nx = np.arange(0, 100, 1)\ny = np.sin(2*np.pi*x/100)\ny[6] = 2\ny[20] = -2\nplt.plot(y)\nprint(special.erfinv(1/2))\n\nstart = time.time()\nclass hampel(object):\n def __init__(self,k,nd):\n self.k = k\n self.nd = nd\n self.signal= np.array([])\n self.signal_que = np.zeros(2*k+2)\n self.counter = 0\n def hampel_all(self,signal):\n self.signal = np.array(signal)\n iLo = np.arange(self.signal.size) - self.k\n iHi = np.arange(self.signal.size) + self.k\n iLo[iLo < 0] = 0\n iHi[iHi > self.signal.size] = self.signal.size\n mmed = np.zeros(self.signal.size)\n mmad = np.zeros(self.signal.size)\n for j in range(self.signal.size):\n w = self.signal[int(iLo[j]) : 1 + int(iHi[j])]\n medj = np.median(w)\n mmed[j] = medj\n mmad[j] = np.median(abs(w-medj))\n # sd = mmad/(special.erfcinv(1/2)*np.sqrt(2))\n sd = mmad/(0.476936276204*np.sqrt(2))\n output = self.signal\n # for i, t in np.ndenumerate(abs(signal-mmed)):\n # if t > nd*sd[i]:\n # output[i] = mmed[i]\n ki = abs(self.signal-mmed)>self.nd*sd\n output[ki] = mmed[abs(self.signal-mmed)>self.nd*sd]\n return output\n\n def hampel_realtime(self,signal_clock):\n if self.counter < 2*self.k + 1:\n self.signal_que[self.counter] = signal_clock\n self.counter +=1\n return signal_clock\n else :\n self.signal_que[1:self.counter] = self.signal_que[0:self.counter-1]\n self.signal_que[self.counter] = signal_clock\n w = self.signal_que\n mmed = np.median(self.signal_que)\n mmad = np.median(abs(self.signal_que-mmed))\n # sd = mmad/(special.erfcinv(1/2)*np.sqrt(2))\n sd = mmad/(0.476936276204*np.sqrt(2))\n if abs(signal_clock-mmed) > self.nd*sd :\n return mmed\n else:\n return signal_clock\n\n\nFilter = hampel(1,1)\nfilterd_y = np.zeros(y.size)\n# yu = Filter.hampel_all(y)\nfor i,t in enumerate (y):\n filterd_y[i] = Filter.hampel_realtime(t)\nelapsed_time = time.time() - start\nprint (\"elapsed_time:{0}\".format(elapsed_time) + \"[sec]\")\nplt.plot(filterd_y)","sub_path":"HampelFilter.py","file_name":"HampelFilter.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"216324151","text":"import numpy as np\r\nfrom mainFunc import *\r\nfrom scipy.integrate import odeint\r\nimport matplotlib.pyplot as plt\r\n\r\n#data = np.genfromtxt(\"data.csv\", skip_header = True, delimiter = ',')\r\n# for test\r\nfile_name = \"2_sets_matched_clipped.csv\"\r\ndata = np.genfromtxt(file_name, skip_header = True, delimiter = ',')\r\n# *** temperature must be in Kelvin ***\r\n# parse the data\r\ntime = data[:,0]\r\ntemperature = data[:,2]\r\nph_abs = data[:,1]\r\ntemperature_2 = data[:,4]\r\nph_abs_2 = data[:,3]\r\n\r\ndef arrhenius(ea,a,T):\r\n r = 8.314\r\n return a * np.exp (-ea / (r*T))\r\n\r\ndef rate(ea,a,T,conc,power):\r\n return arrhenius(ea,a,T) * conc ** power\r\n\r\ndef rateph2minus(ph2minus,t,ea1,ea2,a1,a2,T,alpha,beta):\r\n ph3minus = 1.145565033 - ph2minus\r\n #ph3minus = 0.994207 - ph2minus\r\n\r\n return rate(ea2,a2,T,ph3minus,beta)-rate(ea1,a1,T,ph2minus,alpha)\r\n\r\ndef rateint(ea1,ea2,a1,a2,T,alpha,beta,initialval, time):\r\n return odeint(rateph2minus, initialval, time, args=(ea1,ea2,a1,a2,T,alpha,beta))[1]\r\n\r\nE_a_1 = 46804.35\r\nE_a_2 = 72529.09\r\nA_1 = 191006.8\r\nA_2 = 443941400.0\r\nalpha = 1.0\r\nbeta = 1.0\r\n\r\ndef loop(E_a_1, E_a_2, A_1, A_2, temperature, alpha, beta, time):\r\n result = []\r\n initialval = ph_abs[0]\r\n for i in range(1, len(time)):\r\n newtime = time[i] - time[i-1]\r\n timeint = np.array([0,newtime])\r\n #print(timeint)\r\n T = temperature[i]\r\n initialval2 = rateint(E_a_1, E_a_2, A_1, A_2, T, alpha, beta, initialval, timeint)[0]\r\n #print(initialval2)\r\n result.append(initialval2)\r\n initialval = initialval2\r\n return result\r\n\r\nresult2 = loop(E_a_1, E_a_2, A_1, A_2, temperature, alpha, beta, time)\r\n#print(result2)\r\nplt.plot(time[1:], result2)\r\nplt.show()\r\n\r\n#a1,a2,T,alpha,beta,initialval, time\r\na1_array = np.ones(len(ph_abs[1:])) * A_1\r\na2_array = np.ones(len(ph_abs[1:])) * A_2\r\nalpha_array = np.ones(len(ph_abs[1:])) * alpha\r\nbeta_array = np.ones(len(ph_abs[1:])) * beta\r\n\r\n\r\nA_1_array = [A_1, A_1 * 0.95, A_1 + A_1 * 0.05]\r\nA_2_array = [A_2, A_2 * 0.95, A_2 + A_2 * 0.05]\r\nperturb1 = 0.005\r\nperturb2 = 0.005\r\nnumPoints1 = 10\r\nnumPoints2 = 10\r\nresults_contour = []\r\nlabel_plot = []\r\nparam1Range = np.linspace(E_a_1 * (1 - perturb1), E_a_1 * (1 + perturb1), numPoints1)\r\nparam2Range = np.linspace(E_a_2 * (1 - perturb2), E_a_2 * (1 + perturb2), numPoints2)\r\nparam1_grid, param2_grid = np.meshgrid(param1Range, param2Range)\r\n\r\n\r\nfor i in A_1_array:\r\n for j in A_2_array:\r\n args = (i,j,temperature,alpha,beta,time)\r\n results_contour.append(nonLinearConfInt(loop, E_a_1, E_a_2, ph_abs[1:], args = args, show = False, perturb1 = perturb1, perturb2 = perturb2, pts1=numPoints1, pts2=numPoints2, title = \"A_1 = %.3f A_2 = %.3f \"%(i, j)))\r\n label_plot.append(\"A_1 = %.3f A_2 = %.3f \"%(i, j))\r\n\r\nplt.figure()\r\nax = plt.subplot(111)\r\nfor i in range(len(results_contour)):\r\n xContourValues = np.array(results_contour[i].vertices[:,0])\r\n xContourValues = np.append(xContourValues, xContourValues[0])\r\n yContourValues = np.array(results_contour[i].vertices[:,1])\r\n yContourValues = np.append(yContourValues, yContourValues[0])\r\n ax.plot(xContourValues, yContourValues, label = label_plot[i], linewidth = 1.5)\r\n\r\nbox = ax.get_position()\r\nax.set_position([box.x0, box.y0, box.width * 0.8, box.height])\r\nax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\r\nplt.title('Confidence regions')\r\nplt.xlabel('E_a_1')\r\nplt.ylabel('E_a_2')\r\nplt.show()\r\n","sub_path":"data_editted1/conf_interval.py","file_name":"conf_interval.py","file_ext":"py","file_size_in_byte":3446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"348277986","text":"#test dataframe is needed, take care while calling from here\nfrom sklearn.linear_model import LogisticRegression\n\nlosses=[]\npredictions={'id':test_df['id']}\n\nfor class_name in labels:\n\tclassifier=LogisticRegression(C=4.0,solver='sag')\n\tclassifier.fit(train_embs,train_dataframe[class_name])\n\tpredictions[class_name]=classifier.predict_proba(test_embs)[:,1]\n\nsubmission=pd.DataFrame.from_dict(predictions)\nsubmission.to_csv('LSTM_CNN_LR.csv',index=False)","sub_path":"SVM_Kaggle.py","file_name":"SVM_Kaggle.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"379203578","text":"# -*- coding: utf-8 -*-\n# /usr/bin/python2\n'''\nBy kyubyong park. kbpark.linguist@gmail.com. \nhttps://www.github.com/kyubyong/dc_tts\n'''\n\nfrom __future__ import print_function\n\nfrom tqdm import tqdm\n\nfrom data_load import get_batch, load_vocab, get_train_batch_discriminator, get_validation_batch_discriminator\nfrom hyperparams import Hyperparams as hp\nfrom modules import *\nfrom networks import TextEnc, AudioEnc, AudioDec, Attention, SSRN, Discriminator\nimport tensorflow as tf\nfrom utils import *\nimport sys\n\nclass DiscriminatorGraph:\n def __init__(self, mode=\"train\"):\n self.train_mels, _, self.train_ys, _, self.num_batch = get_train_batch_discriminator()\n self.val_mels, _, self.val_ys, _, _ = get_validation_batch_discriminator()\n\n self.am_validation = tf.placeholder_with_default(False,())\n\n self.mels = tf.cond(self.am_validation, lambda:self.val_mels, lambda:self.train_mels)\n self.ys = tf.cond(self.am_validation, lambda:self.val_ys, lambda:self.train_ys)\n\n training = True if mode==\"train\" else False\n\n with tf.variable_scope(\"Discriminator\"):\n self.yLogits, self.yPred = Discriminator(self.mels, training=training)\n\n with tf.variable_scope(\"gs\"):\n self.global_step = tf.Variable(0, name='global_step', trainable=False)\n\n self.loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.yLogits, labels=self.ys))\n self.roundedYPred = tf.greater(self.yPred, 0.5)\n self.correct = tf.equal(self.roundedYPred, tf.equal(self.ys,1.0))\n self.accuracy = tf.reduce_mean(tf.cast(self.correct, 'float'))\n \n self.train_loss_summary = tf.summary.scalar('train/train_loss', self.loss)\n self.train_acc_summary = tf.summary.scalar('train/train_acc', self.accuracy)\n self.validation_loss_summary = tf.summary.scalar('train/validation_loss', self.loss)\n self.validation_acc_summary = tf.summary.scalar('train/validation_acc', self.accuracy)\n\n # Training Scheme\n self.lr = learning_rate_decay(hp.lr, self.global_step)\n self.optimizer = tf.train.AdamOptimizer(learning_rate=self.lr)\n self.lr_summary = tf.summary.scalar(\"lr\", self.lr)\n\n ## gradient clipping\n self.gvs = self.optimizer.compute_gradients(self.loss)\n self.clipped = []\n for grad, var in self.gvs:\n grad = tf.clip_by_value(grad, -1., 1.)\n self.clipped.append((grad, var))\n self.train_op = self.optimizer.apply_gradients(self.clipped, global_step=self.global_step)\n\t\n img = tf.summary.image('train/mel_gt', tf.expand_dims(tf.transpose(self.mels[:1], [0, 2, 1]), -1))\n # Summary\n self.merged = tf.summary.merge([self.train_loss_summary, self.train_acc_summary, self.lr_summary, img])\n\n\nif __name__ == '__main__':\n\n g = DiscriminatorGraph(); print(\"Training Graph loaded\")\n\n logdir = hp.logdir + \"-\" + 'discriminator'\n sv = tf.train.Supervisor(logdir=logdir, save_model_secs=0, global_step=g.global_step, summary_op=g.merged,\n save_summaries_secs=60)\n with sv.managed_session() as sess:\n while 1:\n for _ in tqdm(range(g.num_batch), total=g.num_batch, ncols=70, leave=False, unit='b'):\n gs, _, ys = sess.run([g.global_step, g.train_op, g.ys])\n print(ys.shape)\t\n # Write checkpoint files at every 1000 steps\n if gs % 1000 == 0:\n sv.saver.save(sess, logdir + '/model_gs_{}'.format(str(gs // 1000).zfill(3) + \"k\"))\n\n # Write validation every 100 steps\n if gs % 100 == 0:\n loss, acc, ys = sess.run([g.validation_loss_summary, g.validation_acc_summary, g.ys],\n feed_dict={g.am_validation: True})\n print(ys.shape)\n sv.summary_writer.add_summary(loss, global_step = gs)\n sv.summary_writer.add_summary(acc, global_step = gs)\n\n # break\n if gs > hp.num_iterations: break\n\n print(\"Done\")\n","sub_path":"train_discriminator.py","file_name":"train_discriminator.py","file_ext":"py","file_size_in_byte":4111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"560988800","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*- \n# created: 30 Dec 2014\n# author: \"Guo Peng Li\" \n\n\"\"\"Parse server config file(s).\"\"\"\nimport io\nimport os\nimport re\nimport platform\n\nimport yaml\n\nfrom gcommon.utils.gjsonobj import JsonObject\n\n\nclass ConfigParser(object):\n project_root = \"\"\n\n _name_is_case_insensitive = True\n\n @classmethod\n def set_name_sensitive(cls):\n cls._name_is_case_insensitive = False\n\n def __init__(self, defaults=None):\n self._options = JsonObject()\n self._defaults = JsonObject(defaults or {})\n\n def get_str(self, name):\n \"\"\"Get a string value from current config set.\"\"\"\n ret = self._get(self._options, name)\n if ret:\n return str(ret)\n else:\n return ''\n\n def get_bool(self, name):\n value = self.get_str(name)\n value = value.lower()\n\n if value in ('t', 'true'):\n return True\n\n value = self.get_int(name)\n if value:\n return True\n\n return False\n\n def get_int(self, name):\n \"\"\"Get an int value from current config set.\"\"\"\n ret = self._get(self._options, name)\n try:\n return int(ret)\n except:\n return 0\n \n def get_float(self, name):\n \"\"\"Get an int value from current config set.\"\"\"\n ret = self._get(self._options, name)\n try:\n return float(ret)\n except:\n return 0\n\n def _parse_group(self, option_values, params=None):\n options = {}\n\n for name, value in option_values.items():\n name = name.strip()\n\n if self._name_is_case_insensitive:\n name = name.lower()\n\n if type(value) is dict:\n value = self._parse_group(value, params)\n elif type(value) is str:\n # from \"$(CLOUD)\" to \"%(CLOUD)s\"\n value = value.strip()\n if params and value.find('$') != -1:\n value = re.sub(r\"\\$\\((\\w+)\\)\", \"%(\\\\1)s\", value)\n value = value % params\n else:\n value = value\n\n options[name] = value\n\n return options\n\n def get(self, name, default=None):\n \"\"\"Get a value from current config set.\"\"\"\n\n # return value of the name.\n # The value could be a dict object\n value = self._get(self._options, name)\n return value or default\n\n def option(self, name):\n # return an option object\n option = self._get(self._options, name)\n\n cp = ConfigParser()\n cp._options = option\n\n return cp\n\n @classmethod\n def _get_option(cls, options, name):\n if cls._name_is_case_insensitive:\n name = name.lower()\n\n names = name.split('.')\n\n root = options\n\n for i in range(len(names) - 1):\n if root and names[i] in root:\n root = root[names[i]]\n\n # print names[-1], root\n if root and names[-1] in root:\n return root[names[-1]]\n\n return None\n\n def _get(self, options, name):\n # try get the value from config file\n value = self._get_option(options, name)\n\n if value is None:\n name = name.lower()\n if value is None:\n return self._defaults.get(name, None)\n\n return value\n\n\nclass YamlConfigParser(ConfigParser):\n args = []\n _config_root = \"\"\n\n def read(self, filename, params=None, encoding='utf-8'):\n if not filename:\n return\n\n filename = os.path.join(os.getcwd(), filename)\n filename = os.path.abspath(filename)\n self._config_root, _ = os.path.split(filename)\n\n # params is a dict object, which will be used to replace variables in\n # config file.\n #\n # For example, in config file:\n # cert_dir=/slim/$(CLOUD)/confs\n #\n # $(CLOUD) is a variable. It will be replaced by params['CLOUD'].\n\n \"\"\"Parse a config file.\"\"\"\n with io.open(filename, encoding=encoding) as f:\n file_options = yaml.safe_load(f) or {}\n\n options = self._parse_group(file_options, params)\n self._options = JsonObject(options)\n\n def load_module(self, module_name, filename, params=None, encoding='utf-8', defaults=None):\n config = YamlConfigParser(defaults=defaults)\n config.read(filename, params, encoding)\n\n self._options[module_name] = config._options\n self._defaults[module_name] = config._defaults\n\n def load_module_in_config_folder(self, module_name, filename=\"\", params=None, encoding='utf-8', defaults=None):\n config = YamlConfigParser(defaults=defaults)\n\n filename = filename or (module_name + \".yaml\")\n filename = os.path.join(self._config_root, filename)\n config.read(filename, params, encoding)\n\n self._options[module_name] = config._options\n self._defaults[module_name] = config._defaults\n\n\n# Test Codes\nif __name__ == \"__main__\":\n default_values = {\n 'mysql.server': 'localhost',\n 'mysql.poolsize': 10,\n 'ucloud.test': 1,\n }\n\n p = {'service': 'gatekeeper'}\n\n print(platform.system())\n demo_filename = './test/demo_data.yaml'\n\n parser = YamlConfigParser(default_values)\n parser.read(demo_filename, p)\n\n print(parser.get_str(\"mysql.server\"))\n print(parser.get(\"ucloud.region\"))\n print(parser.get(\"ucloud.test\"))\n assert parser.get(\"ucloud.test\") == \"test\"\n\n print('Done')\n\n","sub_path":"utils/gyaml.py","file_name":"gyaml.py","file_ext":"py","file_size_in_byte":5529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"96023446","text":"import setuptools\n\nwith open('README.md', 'r') as f:\n\tdescription = f.read()\n\nsetuptools.setup(\n\tname='anna_lib',\n\tversion='0.0.13',\n\tauthor='Patrik Pihlstrom',\n\tauthor_email='patrik.pihlstrom@gmail.com',\n\turl='https://github.com/patrikpihlstrom/anna-lib',\n\tdescription='selenium interface',\n\tlong_description=description,\n\tlong_description_content_type='text/markdown',\n\tpackages=['anna_lib', 'anna_lib.task', 'anna_lib.selenium'],\n\tinstall_requires=[\n\t\t'selenium'\n\t]\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"363422529","text":"import os\nimport datetime\nfrom collections import defaultdict\n\nimport numpy as np\nimport pandas as pd\n\nfrom pyspark.sql import SparkSession\n\ntry:\n from .. querytools.models import MultiClass\nexcept:\n try:\n from querytools.models import MultiClass\n except:\n from src.querytools.models import MultiClass\n\n\ndef _cartesian_tablevectors_spark(model, context, querytable_index):\n # tablecols index keyed rdd\n tablecolsindex_rdd = context.parallelize(list(map(lambda x,y: (x,y),\n model.tablecolsindex.index.values,\n model.tablecolsindex)))\n pred_tablecolsindex_rdd = context.parallelize(list(map(lambda x,y: (x,y),\n model.pred_tablecolsindex.index.values,\n model.pred_tablecolsindex)))\n # embedding vectors\n get_embedding = lambda x: model.columnembeddings[model.index2word[x]]\n tablecolsindex_rdd_vects = tablecolsindex_rdd.mapValues(lambda indexes: \\\n [list(map(get_embedding, result)) \\\n for result in indexes])\n get_embedding = lambda x: model.pred_columnembeddings[model.pred_index2word[x]]\n pred_tablecolsindex_rdd_vects = pred_tablecolsindex_rdd.mapValues(lambda indexes: \\\n [list(map(get_embedding, result)) \\\n for result in indexes])\n # single vectors\n tablecolsindex_rdd_vect = tablecolsindex_rdd_vects.mapValues(lambda vects: \\\n [np.concatenate(resultembeddings) \\\n for resultembeddings in vects])\n pred_tablecolsindex_rdd_vect = pred_tablecolsindex_rdd_vects.mapValues(lambda vects: \\\n [np.concatenate(resultembeddings) \\\n for resultembeddings in vects])\n # cartesian product between query table and the result table\n tablecolsindex_rdd_vect_cartesian = tablecolsindex_rdd_vect.\\\n filter(lambda x: x[0]==querytable_index).\\\n cartesian(pred_tablecolsindex_rdd_vect)\n tablecolsindex_rdd_vect_cartesian = tablecolsindex_rdd_vect_cartesian.\\\n map(lambda x: ((x[0][0],x[1][0]),\n (x[0][1], x[1][1])))\n return tablecolsindex_rdd_vect_cartesian\n\n\ndef _cartesian_tablevect_weights_spark(model, context, querytable_index):\n # tablecols index keyed rdd\n tablecolsindex_rdd = context.parallelize(list(map(lambda x,y: (x,y),\n model.tablecolsindex.index.values,\n model.tablecolsindex)))\n pred_tablecolsindex_rdd = context.parallelize(list(map(lambda x,y: (x,y),\n model.pred_tablecolsindex.index.values,\n model.pred_tablecolsindex)))\n # tablecols index weights keyed rdd\n tablecolsindex_weights_rdd = context.parallelize(list(map(lambda x,y: (x,y),\n model.tablecolsindex_weights.index.values,\n model.tablecolsindex_weights)))\n pred_tablecolsindex_weights_rdd = context.parallelize(list(map(lambda x,y: (x,y),\n model.pred_tablecolsindex_weights.index.values,\n model.pred_tablecolsindex_weights)))\n #embedding vectors\n get_embed = lambda x: model.columnembeddings[model.index2word[x]]\n tablecolsindex_rdd_vects = tablecolsindex_rdd.mapValues(lambda indexes: \\\n [list(map(get_embed, result)) \\\n for result in indexes])\n get_embed = lambda x: model.pred_columnembeddings[model.pred_index2word[x]]\n pred_tablecolsindex_rdd_vects = pred_tablecolsindex_rdd.mapValues(lambda indexes: \\\n [list(map(get_embed, result)) \\\n for result in indexes])\n # joined keyed indexes with keyed weights\n tablecolsindex_rdd_joined = tablecolsindex_rdd_vects.join(tablecolsindex_weights_rdd)\n pred_tablecolsindex_rdd_joined = pred_tablecolsindex_rdd_vects.join(pred_tablecolsindex_weights_rdd)\n # cartesian product between query table and the pretable weighted vectors\n tablecolsindex_rdd_vect_cartesian = tablecolsindex_rdd_joined.\\\n filter(lambda x: x[0]==querytable_index).\\\n cartesian(pred_tablecolsindex_rdd_joined)\n tablecolsindex_rdd_vect_cartesian = tablecolsindex_rdd_vect_cartesian.\\\n map(lambda x: ((x[0][0],x[1][0]),\n (x[0][1], x[1][1])))\n return tablecolsindex_rdd_vect_cartesian\n\n\ndef _unnormalized_cosinedistance_spark(tablecolsindex_rdd_vect_cartesian):\n cosine_dist = lambda x: (list(map(lambda colvect: \\\n max([colvect.dot(othervect) \\\n for othervect in x[1]]), x[0])), len(x[0]), len(x[1]))\n\n tablecolsindex_rdd_vect_cartesian_scored = \\\n tablecolsindex_rdd_vect_cartesian.mapValues(cosine_dist)\n\n col_diff_multiplier = lambda x, y: 1 if x - y == 0 else 1/(abs(x - y)**(1/5))\n l2_norm = lambda x: np.linalg.norm(x[0],2) * col_diff_multiplier(x[1], x[2])\n tablecolsindex_table_cartesian_scored = \\\n tablecolsindex_rdd_vect_cartesian_scored.mapValues(l2_norm)\n\n return tablecolsindex_table_cartesian_scored\n\n\ndef _unnormalized_weighted_cosinedistance_spark(tablecolsindex_rdd_vect_cartesian):\n\n def cosine_dist(x):\n q_vectors_list = x[0][0]\n r_vectors_list = x[1][0]\n q_weights_list = x[0][1]\n r_weights_list = x[1][1]\n\n querytable_ncols = len(q_vectors_list)\n requesttable_ncols = len(r_vectors_list)\n\n dists = []\n for qvector_group, qweight_group in list(zip(q_vectors_list, q_weights_list)):\n col_dists = []\n for rvector_group, rweight_group in list(zip(r_vectors_list, r_weights_list)):\n dist = 0\n weight = 0\n zipped = list(zip(qvector_group, rvector_group, qweight_group, rweight_group))\n for qtable_vector, rtable_vector, qtable_weight, rtable_weight in zipped:\n dist += qtable_vector.dot(rtable_vector)*(qtable_weight + rtable_weight)\n weight += qtable_weight + rtable_weight\n col_dists += [dist/weight]\n dists += [max(col_dists)]\n\n return dists, querytable_ncols, requesttable_ncols\n\n tablecolsindex_rdd_vect_cartesian_scored = \\\n tablecolsindex_rdd_vect_cartesian.mapValues(cosine_dist)\n\n col_diff_multiplier = lambda x, y: 1 if x - y == 0 else 1/(abs(x - y)**(1/5))\n l2_norm = lambda x: np.linalg.norm(x[0],2) * col_diff_multiplier(x[1], x[2])\n tablecolsindex_table_cartesian_scored = \\\n tablecolsindex_rdd_vect_cartesian_scored.mapValues(l2_norm)\n\n return tablecolsindex_table_cartesian_scored\n\n\ndef _unnormalized_euclideanistance_spark(tablecolsindex_rdd_vect_cartesian):\n euclidean_dist = lambda x: (list(map(lambda colvect: \\\n 1 - min([np.sqrt(np.sum(np.array(colvect - othervect)**2)) \\\n for othervect in x[1]])/2, x[0])), len(x[0]), len(x[1]))\n\n tablecolsindex_rdd_vect_cartesian_scored = \\\n tablecolsindex_rdd_vect_cartesian.mapValues(euclidean_dist)\n\n col_diff_multiplier = lambda x, y: 1 if x - y == 0 else 1/(abs(x - y)**(1/5))\n l2_norm = lambda x: np.linalg.norm(x[0],2) * col_diff_multiplier(x[1], x[2])\n tablecolsindex_table_cartesian_scored = \\\n tablecolsindex_rdd_vect_cartesian_scored.mapValues(l2_norm)\n\n return tablecolsindex_table_cartesian_scored\n\n\ndef _unnormalized_weighted_euclideandistance_spark(tablecolsindex_rdd_vect_cartesian):\n\n def euclidean_dist(x):\n q_vectors_list = x[0][0]\n r_vectors_list = x[1][0]\n q_weights_list = x[0][1]\n r_weights_list = x[1][1]\n\n querytable_ncols = len(q_vectors_list)\n requesttable_ncols = len(r_vectors_list)\n\n dists = []\n for qvector_group, qweight_group in list(zip(q_vectors_list, q_weights_list)):\n col_dists = []\n for rvector_group, rweight_group in list(zip(r_vectors_list, r_weights_list)):\n dist = 0\n weight = 0\n zipped = list(zip(qvector_group, rvector_group, qweight_group, rweight_group))\n for qtable_vector, rtable_vector, qtable_weight, rtable_weight in zipped:\n dist += np.sqrt(np.sum(np.array(qtable_vector - rtable_vector)**2))*(qtable_weight + rtable_weight)\n weight += qtable_weight + rtable_weight\n col_dists += [dist/weight]\n dists += [1 - min(col_dists)/2]\n\n return dists, querytable_ncols, requesttable_ncols\n\n tablecolsindex_rdd_vect_cartesian_scored = \\\n tablecolsindex_rdd_vect_cartesian.mapValues(euclidean_dist)\n\n col_diff_multiplier = lambda x, y: 1 if x - y == 0 else 1/(abs(x - y)**(1/5))\n l2_norm = lambda x: np.linalg.norm(x[0],2) * col_diff_multiplier(x[1], x[2])\n tablecolsindex_table_cartesian_scored = \\\n tablecolsindex_rdd_vect_cartesian_scored.mapValues(l2_norm)\n\n return tablecolsindex_table_cartesian_scored\n\n\nclass QueryTable(object):\n \"\"\"\n Class to find similar tables in a collection based on a 'Query Table' which\n is used as the table of comparison for all others.\n \"\"\"\n\n def __init__(self, model, use_spark=False):\n self.model = model\n self.use_spark = use_spark\n self.multiclass = type(self.model.model) == MultiClass\n if use_spark:\n self.spark = SparkSession.builder.\\\n appName(\"Python Spark SQL basic example\").\\\n config(\"spark.some.config.option\", \"some-value\").\\\n getOrCreate()\n self.sc = self.spark.sparkContext\n\n def _make_querytable_tensor(self, querytable_ncols, requesttable_ncols,\n embeddingdim, querytable_resultvectors,\n requesttable_resultvectors):\n \"\"\"\n Helper function that creates a tensor of size\n querytable_ncols x requesttable_ncols x embeddingdim*requesttable_ncols.\n Note that in the case of a top-k header embeddings, embedding dim is\n k*pretrained_embeddingdim.\n \"\"\"\n tensor = []\n for i in range(querytable_ncols):\n matrix = []\n for j in range(requesttable_ncols):\n row = []\n for k in range(requesttable_ncols):\n if j == k:\n row += [querytable_resultvectors[i]]\n else:\n if self.dist == 'cosine':\n row += [np.zeros(embeddingdim)]\n elif self.dist == 'euclidean':\n row += [requesttable_resultvectors[k]]\n matrix += [np.concatenate(row)]\n tensor += [matrix]\n return np.array(tensor)\n\n\n def _make_requesttable_vector(self, requesttable_resultvectors):\n \"\"\"\n Helper function to create the request table vector of size\n requesttable_ncols*k*pretrained_embeddingdim.\n \"\"\"\n return np.concatenate(requesttable_resultvectors)\n\n\n def _comparetables(self, querytable_index, requesttable_index):\n \"\"\"\n Helper function to compare two tables. This function converts the\n models header embeddings into vectors and performs broadcasted\n comparisons between the querytable tensor and the reqeusttable vector.\n \"\"\"\n m = self.model\n\n ####### Get the header vectors for the query table\n querytable_resultindexes = m.tablecolsindex[querytable_index]\n get_embedding = lambda x: m.columnembeddings[m.index2word[x]]\n querytable_resultembed = [list(map(get_embedding, result))\n for result in querytable_resultindexes]\n querytable_resultembed_vector = [np.concatenate(resultembeddings) \\\n for resultembeddings \\\n in querytable_resultembed]\n\n ####### Get the header vectors for the query table\n requesttable_resultindexes = m.pred_tablecolsindex[requesttable_index]\n get_embedding = lambda x: m.pred_columnembeddings[m.pred_index2word[x]]\n requesttable_resultembed = [list(map(get_embedding, result))\n for result in requesttable_resultindexes]\n requesttable_resultembed_vector = [np.concatenate(resultembeddings) \\\n for resultembeddings \\\n in requesttable_resultembed]\n\n ####### Build the query table tensor\n querytable_ncols = len(m.tablecolsindex[querytable_index])\n requesttable_ncols = len(m.pred_tablecolsindex[requesttable_index])\n querytable_tensor = self._make_querytable_tensor(querytable_ncols,\n requesttable_ncols,\n m.embeddingdim,\n querytable_resultembed_vector,\n requesttable_resultembed_vector)\n\n ####### Build request and query table vectors\n requesttable_vector = self._make_requesttable_vector(requesttable_resultembed_vector)\n querytable_vector = self._make_requesttable_vector(querytable_resultembed_vector)\n\n ####### Make comparison\n col_diff_multiplier = lambda x, y: 1 if x - y == 0 else 1/(abs(x - y)**(1/5))\n\n if self.dist == 'cosine':\n columndists_vectors = querytable_tensor.dot(requesttable_vector)\n columndists = columndists_vectors.max(axis=1)\n requesttable_score = np.linalg.norm(columndists, 2) \\\n * col_diff_multiplier(querytable_ncols, requesttable_ncols)\n elif self.dist == 'euclidean':\n columndiffs_vectors = querytable_tensor - requesttable_vector\n columndists_vectors = np.sqrt(np.sum(columndiffs_vectors**2, axis=2))\n columndists = 1 - columndists_vectors.min(axis=1)/2\n requesttable_score = np.linalg.norm(columndists, 2) \\\n * col_diff_multiplier(querytable_ncols, requesttable_ncols)\n\n normalized_requesttable_score = requesttable_score \\\n / np.linalg.norm(querytable_vector,2)\n\n return normalized_requesttable_score\n\n\n def query(self, querytable, dist='euclidean', num_results=10):\n \"\"\"\n Querying interface to find similar tables.\n\n querytable: Either and integer or the name of a table from the collection.\n dist: Distance measure to use when computing table similarity. Either\n 'cosine' or 'euclidean'.\n \"\"\"\n\n self.dist = dist\n if type(querytable) == str:\n assert(querytable in self.model.table2index[querytable])\n querytable_index = querytable\n elif type(querytable) == int:\n assert(querytable in self.model.index2table)\n querytable_index = self.model.index2table[querytable]\n\n if not self.use_spark:\n\n print(\"Processing Query Table: {} ...\".format(querytable_index))\n start = datetime.datetime.now()\n\n results = defaultdict(int)\n for requesttable_index, _ in self.model.pred_table2index.items():\n if requesttable_index != querytable_index:\n requesttable_score = self._comparetables(querytable_index,\n requesttable_index)\n results[requesttable_index] = requesttable_score\n end = datetime.datetime.now()\n print(\"Processing Complete in: {}\\n\\n\".format(end-start))\n\n results = pd.Series(results)\n results.name = querytable_index\n\n return results.sort_values(ascending=False).iloc[:num_results]\n\n else:\n\n print(\"SPARK: Processing Query Table: {} ...\".\\\n format(querytable_index))\n start = datetime.datetime.now()\n\n if self.multiclass:\n tablecolsindex_rdd_vect_cartesian = \\\n _cartesian_tablevect_weights_spark(self.model,\n self.sc,\n querytable_index)\n else:\n tablecolsindex_rdd_vect_cartesian = \\\n _cartesian_tablevectors_spark(self.model,\n self.sc,\n querytable_index)\n\n if self.dist == 'cosine':\n if self.multiclass:\n scored = _unnormalized_weighted_cosinedistance_spark(tablecolsindex_rdd_vect_cartesian)\n else:\n scored = _unnormalized_cosinedistance_spark(tablecolsindex_rdd_vect_cartesian)\n elif self.dist == 'euclidean':\n if self.multiclass:\n scored = _unnormalized_weighted_euclideandistance_spark(tablecolsindex_rdd_vect_cartesian)\n else:\n scored = _unnormalized_euclideanistance_spark(tablecolsindex_rdd_vect_cartesian)\n\n results = scored.map(lambda x: (x[0][1], x[1]))\n results = results.takeOrdered(num_results + 1, lambda x: -x[1])\n\n end = datetime.datetime.now()\n print(\"Processing Complete in: {}\\n\\n\".format(end-start))\n\n score = [x[1]/results[0][1] for i, x in enumerate(results) if i > 0]\n tables = [x[0] for i, x in enumerate(results) if i > 0]\n results_df = pd.Series(data = score, index = tables)\n results_df.name = querytable_index\n\n return results_df\n\n\nclass Indexer(object):\n\n def __init__(self, model=None):\n\n \"\"\"\n Initialize and indexer that build indexes necessary to run queries on\n a query table and the result tables using QueryTable().\n\n model: A class that has the attribute 'tablecolsindex', which is a\n pandas series with the table names as an index and a list of\n lists containing the indexes of vocab for each table column.\n It should also have 'pred_tablecolsindex'. If None then only\n builds the column embedding indexes.\n\n vocab: A pandas dataframe of the column embeddings of the query table\n data collection.\n \"\"\"\n\n self.model = model\n\n def index_query(self, col_info_data, column_embedding_data,\n model_results_data=None, model_weights_data=None):\n\n \"\"\"\n Builds the indexes on the query table data collection required for\n using QueryTable.\n\n column_embedding_file: The path to the columnembedding.txt file for the\n query table data collection.\n \"\"\"\n\n ####### Column name embeddings\n unnormalized_columnembeddings = column_embedding_data.T\n normalize = lambda x: x/np.linalg.norm(x,2)\n self.columnembeddings = unnormalized_columnembeddings.apply(normalize)\n\n ####### Embedding indexes and dims\n self.index2word = self.columnembeddings.T.reset_index().iloc[:,0].to_dict()\n self.word2index = self.columnembeddings.T.reset_index().reset_index().\\\n set_index(0)['index'].to_dict()\n self.embeddingdim = self.columnembeddings.shape[0]\n\n ####### Table index\n if not self.model == None:\n self.tablecolsindex = \\\n self.model.make_tablecolsindex(col_info_data,\n self.word2index,\n self.index2word,\n model_results_data)\n self.index2table = self.tablecolsindex.reset_index()['file_name'].to_dict()\n self.table2index = self.tablecolsindex.reset_index().reset_index().\\\n set_index('file_name')['index'].to_dict()\n\n if type(self.model) == MultiClass:\n self.tablecolsindex_weights = \\\n self.model.make_tablecolsindex_weights(col_info_data,\n self.word2index,\n self.index2word,\n model_weights_data)\n\n def index_result(self, col_info_data, column_embedding_data,\n model_results_data=None, model_weights_data=None):\n\n \"\"\"\n Builds the indexes on the results table data collection required for\n using QueryTable.\n\n tablecols_index_data: The data required by the model needed to generate\n the tablescolsindex attribute. The model must\n implement the 'make_tablecolsindex()' method.\n\n column_embedding_file: The path to the columnembedding.txt file for the\n results table data collection.\n \"\"\"\n\n ####### Column name embeddings\n unnormalized_columnembeddings = column_embedding_data.T\n normalize = lambda x: x/np.linalg.norm(x,2)\n self.pred_columnembeddings = unnormalized_columnembeddings.apply(normalize)\n\n ####### Embedding indexes and dims\n self.pred_index2word = self.pred_columnembeddings.T.reset_index().iloc[:,0].to_dict()\n self.pred_word2index = self.pred_columnembeddings.T.reset_index().\\\n reset_index().set_index(0)['index'].to_dict()\n self.pred_embeddingdim = self.pred_columnembeddings.shape[0]\n\n ####### Table index\n if not self.model == None:\n self.pred_tablecolsindex = \\\n self.model.make_tablecolsindex(col_info_data,\n self.word2index,\n self.index2word,\n model_results_data)\n self.pred_index2table = self.pred_tablecolsindex.\\\n reset_index()['file_name'].to_dict()\n self.pred_table2index = self.pred_tablecolsindex.reset_index().\\\n reset_index().set_index('file_name')['index'].\\\n to_dict()\n\n if type(self.model) == MultiClass:\n self.pred_tablecolsindex_weights = \\\n self.model.make_tablecolsindex_weights(col_info_data,\n self.word2index,\n self.index2word,\n model_weights_data)\n","sub_path":"src/querytools/querytools.py","file_name":"querytools.py","file_ext":"py","file_size_in_byte":23638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"266161629","text":"import numpy as np\nimport scipy.spatial\nimport matplotlib \nimport matplotlib.pyplot as plt\n########################################################################\n######### Data Generating Functions ###################################\n########################################################################\ndef generate_sensors(k = 7, d = 2):\n \"\"\"\n Generate sensor locations. \n Input:\n k: The number of sensors.\n d: The spatial dimension.\n Output:\n sensor_loc: k * d numpy array.\n \"\"\"\n sensor_loc = 100*np.random.randn(k,d)\n return sensor_loc\n\ndef generate_data(sensor_loc, k = 7, d = 2, \n\t\t\t\t n = 1, original_dist = True, sigma_s = 100):\n \"\"\"\n Generate the locations of n points and distance measurements. \n \n Input:\n sensor_loc: k * d numpy array. Location of sensor. \n k: The number of sensors.\n d: The spatial dimension.\n n: The number of points.\n original_dist: Whether the data are generated from the original \n distribution. \n sigma_s: the standard deviation of the distribution \n that generate each object location.\n \n Output:\n obj_loc: n * d numpy array. The location of the n objects. \n distance: n * k numpy array. The distance between object and \n the k sensors. \n \"\"\"\n assert k, d == sensor_loc.shape\n \n obj_loc = sigma_s*np.random.randn(n, d)\n if not original_dist:\n\t obj_loc = sigma_s*np.random.randn(n, d)+([300,300])\n\t \n distance = scipy.spatial.distance.cdist(obj_loc, \n\t\t\t\t\t\t\t\t\t\t sensor_loc, \n\t\t\t\t\t\t\t\t\t\t metric='euclidean')\n distance += np.random.randn(n, k) \n return obj_loc, distance\n\ndef generate_data_given_location(sensor_loc, obj_loc, k = 7, d = 2):\n \"\"\"\n Generate the distance measurements given location of a single object and sensor. \n \n Input:\n obj_loc: 1 * d numpy array. Location of object\n sensor_loc: k * d numpy array. Location of sensor. \n k: The number of sensors.\n d: The spatial dimension. \n \n Output: \n distance: 1 * k numpy array. The distance between object and \n the k sensors. \n \"\"\"\n assert k, d == sensor_loc.shape \n\t \n distance = scipy.spatial.distance.cdist(obj_loc, \n\t\t\t\t\t\t\t\t\t\t sensor_loc, \n\t\t\t\t\t\t\t\t\t\t metric='euclidean')\n distance += np.random.randn(1, k) \n return obj_loc, distance\n","sub_path":"ANN and Backpropagation/data/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"142477263","text":"# encoding: utf-8\n\nimport json\nfrom bottle import route, view, request, redirect, response, get, template\n\nfrom control.gestao_aprendizagem_controller import convertendo_str_in_dict\nfrom facade.facade_main import Facade\nfrom control.classes.permissao import permissao, usuario_logado\nfrom control.dicionarios import *\n\nfacade = Facade()\n\n\n\ndef itens_cadastrados_sistema():\n itens = facade.read_estrutura_facade(tipo_estrutura=TIPO_ESTRUTURA['item'])\n return itens\n\n\ndef itens_usuario_tem():\n itens = facade.ver_item_comprado_facade(id_usuario=usuario_logado()['id'])\n return itens\n\n\ndef obterUltimaConclusao():\n retorno = {\n 'objetoAprendizagem': '',\n 'unidade': '',\n 'aventura': '',\n 'universo': 'UV1'\n }\n print(\"obter ultima conclusao\",retorno)\n return retorno\n\n\ndef verificarAcessoObjetoAprendizagem():\n \"\"\"\n percorre todas as OAs da semana e se o aluno tiver terminado o jogo anterior ao menos no medio , debloqueia o prox jogo\n se for um cinematic, apenas adiciona a lista\n verifica se jogou o anterior , se tem dados do anterior , verifica se nao é lista, porque se concluir o jogo no facil vem uma lista (dado anomalo)\n\n :return:\n \"\"\"\n usuario = usuario_logado()\n parametros = parametros_json_jogos(request.params.items())\n if usuario['tipo'] < TIPO_USUARIOS['aluno']:\n retorno = {'objetosAprendizagemAcessiveis': parametros['objetosAprendizagem']}\n else:\n cn_final = facade.oa_teste_facade(id_aluno=str(usuario['id']), oa='{}CN02'.format(parametros['objetosAprendizagem'][0:9]))\n if cn_final != []:\n retorno = {'objetosAprendizagemAcessiveis': parametros['objetosAprendizagem']}\n else:\n teste = []\n for i in parametros['objetosAprendizagem']:\n\n e=list(i)\n print(\"lista da OA\",[len(e)-1],e)\n if (e[len(e)-1] !=\"1\" and e[len(e)-1] !=1) and e[9]!='C':\n e[len(e)-1]=str(int(e[len(e)-1])-1)\n anterior=''.join(e)\n desempenho_oa = facade.oa_teste_facade(id_aluno=str(usuario['id']), oa=i)\n desempenho_oa_anterior=facade.oa_teste_facade(id_aluno=str(usuario['id']), oa=anterior)\n\n\n if desempenho_oa_anterior!=[]:\n\n last_best_game = convertendo_str_in_dict(desempenho_oa_anterior[0]['jogo_jogado'][0])\n\n\n if desempenho_oa == [] and not isinstance(last_best_game,list):\n\n if last_best_game['termino'] == True:\n if last_best_game['nivel'] == \"facil\":\n\n try:#excessao feita por causa do jogo UV1AV1UD6OA03 que gera um dado anormal \"certo\" , possivel erro do jogo (era para ter 3 niveis?)\n for x in range(len(desempenho_oa_anterior[0]['jogo_jogado'][0])):\n best_game_list=convertendo_str_in_dict(desempenho_oa_anterior[0]['jogo_jogado'][x])\n if best_game_list[\"nivel\"]!= \"facil\" and best_game_list[\"termino\"]==True:\n teste.append(i)\n break\n break\n except IndexError:\n teste.append(i)\n break#\n else:\n\n teste.append(i)\n break#\n\n elif not isinstance(last_best_game,list):\n if last_best_game['termino'] == True:\n\n teste.append(i)\n elif i== \"UV1AV1UD4OA05\" or i==\"UV1AV2UD8OA02\":\n teste.append(i)\n elif desempenho_oa == [] and isinstance(last_best_game,list):\n if last_best_game[0]['nivel']==\"facil\":\n\n for x in range(len(desempenho_oa_anterior[0][\"jogo_jogado\"])):\n try:\n last_facil=convertendo_str_in_dict(desempenho_oa_anterior[0][\"jogo_jogado\"][x])\n if last_facil[\"termino\"]==True:\n teste.append(i)\n break\n\n except Exception as aaa:\n continue\n\n else:\n teste.append(i)\n else:\n teste.append(i)\n break\n\n else:\n desempenho_oa = facade.oa_teste_facade(id_aluno=str(usuario['id']), oa=i)\n if desempenho_oa == [] and e[len(e)-1]:\n teste.append(i)\n\n retorno = {'objetosAprendizagemAcessiveis': teste}\n return retorno\n\n\ndef verificarConclusoesObjetosAprendizagem():\n\n '''\n Comentario feito dia 17/10/1994\n A variavel parametros tem o o modelo de (em aventura 1)\n {'uuid': '36f194cd-dcc1-40f6-81af-d9147f184d58_verificarConclusoesObjetosAprendizagem',\n 'operacao': 'verificarConclusoesObjetosAprendizagem',\n 'objetosAprendizagem': ['UV1AV1UD1OA01', 'UV1AV1UD1OA02', 'UV1AV1UD1OA03', 'UV1AV1UD1OA04', 'UV1AV1UD1OA05', 'UV1AV1UD1OA06', 'UV1AV1UD1CN01', 'UV1AV1UD1CN02', 'UV1AV1UD1VC01']}\n :return:\n '''\n usuario = usuario_logado()\n parametros = parametros_json_jogos(request.params.items())\n print('parametros conclusao OA',parametros)\n if int(usuario['tipo']) < 6:\n retorno = {'objetosConcluidos': parametros['objetosAprendizagem']}\n\n else:\n cn_final = facade.oa_teste_facade(id_aluno=str(usuario['id']),\n oa='{}CN02'.format(parametros['objetosAprendizagem'][0:9]))\n if cn_final != []:\n retorno = {'objetosConcluidos': parametros['objetosAprendizagem']}\n else:\n teste = []\n for k in parametros['objetosAprendizagem']:\n desempenho_oa = facade.oa_teste_facade(id_aluno=str(usuario['id']), oa=k)\n if desempenho_oa != []:\n for jogo in desempenho_oa[0]['jogo_jogado']:\n nivel_jogo=convertendo_str_in_dict(jogo)\n try:\n if nivel_jogo['nivel']!='facil' and nivel_jogo['termino']==True:\n teste.append(k)\n except Exception as aaa:\n for x in nivel_jogo:\n print('fuuuu',x,aaa,desempenho_oa[0]['objeto_aprendizagem'])\n\n retorno = {'objetosConcluidos': teste}\n print(\"verificar Conclusoes Objetos Aprendizagem retorno\",retorno)\n return retorno\n\n\n\n\ndef registrarConclusao():\n \"\"\"responsavel por desbloquear o proximo OA\"\"\"\n usuario = usuario_logado()\n dados_jogo= parametros_json_jogos(request.params.items())\n # Esse comentario doi feito em 17/10/2018\n # o print acima recebe os dados na forma abaixo\n #{'uuid': nome_da_funçao encriptada, 'operacao': nome_da_funçao,\n # 'objetoAprendizagem': 'UV1AVxUDx'+'CNXX' ou 'VCXX' OU 'OAXX',\n #'niveis': [{'nivel': 'facil', 'percentualConcluido': varia entre 0 e 100, 'termino': True ou False},\n # {'nivel': 'medio', 'percentualConcluido': varia entre 0 e 100, 'termino': True ou False},\n # {'nivel': 'dificil', 'percentualConcluido': varia entre 0 e 100, 'termino': True ou False}]}\n try:\n print(\"Dados gerados em em registrar conclusao\",dados_jogo['niveis'])\n except Exception as arr:\n print('erro',arr)\n\n if usuario['tipo'] == TIPO_USUARIOS['aluno'] :\n if len(dados_jogo['niveis'])==3:\n print('dados jogo1 win? ',dados_jogo['niveis'][len(dados_jogo['niveis'])-1]['termino'])\n\n\n premios={\n 'OA': is_oa,\n 'VC': is_vc_or_cn,\n 'CN': is_vc_or_cn\n }\n # if autorizaçao_professor()==True:\n\n return premios[dados_jogo['objetoAprendizagem'][9:11]]\\\n (aluno=usuario['id'],parametros=parametros_json_jogos(request.params.items()),\n oa=parametros_json_jogos(request.params.items())['objetoAprendizagem'])\n\n elif dados_jogo['niveis'][len(dados_jogo['niveis'])-1]==True:\n print('dados 2 ', dados_jogo['niveis'][len(dados_jogo['niveis']) - 1]['termino'])\n premios = {\n 'OA': is_oa,\n 'VC': is_vc_or_cn,\n 'CN': is_vc_or_cn\n }\n # if autorizaçao_professor()==True:\n\n return premios[parametros_json_jogos(request.params.items())['objetoAprendizagem'][9:11]] \\\n (aluno=usuario['id'], parametros=parametros_json_jogos(request.params.items()),\n oa=parametros_json_jogos(request.params.items())['objetoAprendizagem'])\n\n else:\n print('dados jogo3 entrei no else ')\n premios = {\n 'OA': is_oa,\n 'VC': is_vc_or_cn,\n 'CN': is_vc_or_cn\n }\n\n return premios[parametros_json_jogos(request.params.items())['objetoAprendizagem'][9:11]] \\\n (aluno=usuario['id'], parametros=parametros_json_jogos(request.params.items()),\n oa=parametros_json_jogos(request.params.items())['objetoAprendizagem'])\n else:\n gamificacao = gamificacao_moeda_xp(parametros=parametros_json_jogos(request.params.items()))\n premios = {\n 'medalhas': [''],\n 'moedas': gamificacao['moedas'],\n 'xp': gamificacao['xp']\n }\n return premios\n\n\n\ndef obterPremiacao():\n parametros = parametros_json_jogos(request.params.items())\n\n #Comentario colocado dia 17/10/2018 , verifique a nescessidade de atualiza-la\n #a variavel parametros recebe valores no formato de :\n #{'uuid': nome da funçao encodada, 'operacao': nome da funçao, 'objetoAprendizagem': 'UV1AVX\"+'UDX'+'OAXX'} nao sei se o é ativada com os videoclipes ou cinamticas\n usuario = usuario_logado()\n if usuario['tipo'] == TIPO_USUARIOS['aluno']:\n aluno = facade.search_aluno_id_facade(id_aluno=usuario['id'])\n retorno = {\n 'moedas': int(aluno['pontos_de_moedas']),\n 'xp': int(aluno['pontos_de_vida'])\n }\n else:\n observador = facade.search_observador_id_facade(id=usuario['id'])\n retorno = {\n 'moedas': int(observador['pontos_de_moedas']),\n 'xp': int(observador['pontos_de_vida'])\n }\n print('obter Premiaçao',retorno)\n\n return retorno\n\ndef verificarAcessoUnidade():\n usuario = usuario_logado()\n parametros = parametros_json_jogos(request.params.items())\n\n if int(usuario['tipo']) < 6:\n retorno = {'unidadesAcessiveis': parametros['unidades']}\n else:\n desempenho_aluno = facade.search_desempenho_concluido_id_aluno_facade(id_aluno=str(usuario['id']))\n if desempenho_aluno == []:\n retorno = {'unidadesAcessiveis': [parametros['unidades'][0]]}\n else:\n acesso_unidade = []\n for i in parametros['unidades']:\n desempenho_unidade = facade.unidade_teste_facade(id_aluno=str(usuario['id']), unidade=i)\n if desempenho_unidade == []:\n acesso_unidade.append(i)\n break\n else:\n desempenho_oa = facade.oa_teste_facade(id_aluno=str(usuario['id']), oa='{}OA06'.format(i))\n if desempenho_oa == []:\n acesso_unidade.append(i)\n\n break\n else:\n acesso_unidade.append(i)\n retorno = {'unidadesAcessiveis': acesso_unidade}\n\n print('Verificar acesso Unidade',retorno)\n\n return retorno\n\ndef verificarAcessoAventura():\n from control.dicionarios import AVENTURAS_CONECTURMA\n usuario = usuario_logado()\n\n if usuario['tipo'] < '6':\n parametros = parametros_json_jogos(request.params.items())\n\n\n print(\"verificar Acesso Aventura\",AVENTURAS_CONECTURMA['3'])\n\n return AVENTURAS_CONECTURMA['3']\n else:\n from control.dicionarios import AVENTURAS_CONECTURMA\n serie_turma = facade.search_estrutura_id_facade(int(usuario['vinculo_turma']))\n\n\n\n return AVENTURAS_CONECTURMA[serie_turma['serie']]\n\ndef is_oa(aluno, parametros, oa):\n from control.classes.permissao import update_cookie\n gamificacao = gamificacao_moeda_xp(parametros)\n\n premios = {\n 'medalhas': gamificacao_medalha(aluno, oa=oa),\n 'moedas': gamificacao['moedas'],\n 'xp': gamificacao['xp']\n }\n\n create_or_update_oa(id_aluno=aluno, unidade=oa[0:9], objeto_aprendizagem=oa,\n parametros=parametros['niveis'])\n\n facade.gravar_premiacao(aluno, premios)\n update_cookie(premios)\n\n return premios\n\ndef is_vc_or_cn(aluno, parametros, oa):\n create_or_update_oa(id_aluno=aluno, unidade=oa[0:9], objeto_aprendizagem=oa,\n parametros=parametros['niveis'])\n\n premios = {\n 'medalhas': [],\n 'moedas': [],\n 'xp': []\n }\n\n return premios\n\ndef gamificacao_moeda_xp(parametros):\n from control.dicionarios import PREMIO_JOGOS\n\n ponto = pegar_maior_pontuacao(parametros['niveis'])\n print('Em pontos pegou isso',ponto)\n if ponto:\n return PREMIO_JOGOS[ponto['nivel']]\n else:\n return PREMIO_JOGOS['0']\n\n\ndef gamificacao_medalha(usuario_id, oa):\n\n medalhas = []\n oa_concluidos = facade.search_desempenho_concluido_id_aluno_facade(id_aluno=str(usuario_id))\n medalhas.append(primeiro_jogo(facade.oa_teste_facade(id_aluno=str(usuario_id),oa='UV1AV1UD1OA01')))\n if len(oa_concluidos) >= 10:\n medalhas.append(dose_dupla(oa_concluidos))\n medalhas.append(dezena(usuario_id=str(usuario_id), oa=oa))\n medalhas.append(fera_da_Matemática(oa=oa))\n medalhas.append(fera_da_lingua_portuguesa(oa=oa))\n medalhas.append(musical(id_aluno=str(usuario_id),oa=oa))\n if 'OA' in oa:\n medalhas.append(de_novo(id_aluno=str(usuario_id), oa=oa))\n\n medalhas.append(magia_da_matematica(id_aluno=str(usuario_id), aventura=oa[0:6]))\n medalhas.append(magia_da_lingua_portuguesa(id_aluno=str(usuario_id), aventura=oa[0:6]))\n return testa_medalha_false(medalhas)\n\ndef testa_medalha_false(medalhas):\n retorno = []\n for i in medalhas:\n if i != False and i != None:\n retorno.append(i)\n\n return retorno\n\ndef testar_se_ja_medalha(id_usuario, medalha):\n pass\n\n\n\n\"\"\" INICIO DOS METODOS REFERENTES A MEDALHAS\"\"\"\n\ndef primeiro_jogo(oa_concluido):\n\n if oa_concluido == []:\n return '11'\n else:\n return False\n\n\ndef dose_dupla(oa_concluido):\n\n medalha = 0\n\n for i in oa_concluido:\n if len(i['jogo_jogado']) > 1:\n medalha += 1\n if medalha == 10:\n return '12'\n else:\n return False\n\n\ndef dezena(usuario_id, oa):\n oas = facade.oa_teste_facade(id_aluno=usuario_id, oa=oa)\n if oas != None:\n for oa in oas :\n teste = len(oa['jogo_jogado'])\n if teste == 10:\n return '13'\n else:\n return False\n else:\n return False\n\n\ndef fera_da_Matemática(oa):\n if oa == 'UV1AV1UD1OA05' or oa == 'UV1AV2UD1OA05' or oa == 'UV1AV3UD1OA05':\n return '14'\n else:\n return False\n\n\ndef fera_da_lingua_portuguesa(oa):\n if oa == 'UV1AV1UD1OA06' or oa == 'UV1AV2UD1OA06' or oa == 'UV1AV3UD1OA06':\n return '15'\n else:\n return False\n\n\ndef musical(id_aluno,oa):\n aluno=facade.oa_teste_facade(id_aluno=id_aluno,oa='{}VC01'.format(oa[0:9]))\n if aluno != []:\n return '16'\n else:\n return False\n\n\ndef de_novo(id_aluno,oa):\n aluno = facade.oa_teste_facade(id_aluno=id_aluno,oa='{}VC01'.format(oa[0:9]))\n for i in aluno:\n\n if len(i['jogo_jogado']) >= 3:\n return '17'\n else:\n return False\n\ndef magia_da_matematica(id_aluno, aventura):\n\n oa = facade.search_oa_by_type_and_aventura_facade(aventura=aventura, disciplina=DICIPLINA_NOME['matematica'])\n oas_terminandos_dificel = 0\n for i in oa:\n oa_terminados = facade.oa_teste_facade(id_aluno=id_aluno, oa =i)\n for z in oa_terminados:\n dificuldade = z['jogo_jogado'][len(z['jogo_jogado'])-1]\n if dificuldade['nivel'] == 'dificil':\n oas_terminandos_dificel += 1\n else:\n oas_terminandos_dificel = 0\n\n if oas_terminandos_dificel == 5:\n return '19'\n else:\n return False\n\ndef magia_da_lingua_portuguesa(id_aluno, aventura):\n\n oa = facade.search_oa_by_type_and_aventura_facade(aventura=aventura, disciplina=DICIPLINA_NOME['lingua Portuguesa'])\n oas_terminandos_dificel = 0\n for i in oa:\n oa_terminados = facade.oa_teste_facade(id_aluno=id_aluno, oa=i)\n for z in oa_terminados:\n dificuldade = z['jogo_jogado'][len(z['jogo_jogado']) - 1]\n if dificuldade['nivel'] == 'dificil':\n oas_terminandos_dificel += 1\n else:\n oas_terminandos_dificel = 0\n\n if oas_terminandos_dificel >= 5:\n return '20'\n else:\n return False\n\n\n\ndef create_or_update_oa(id_aluno, unidade, objeto_aprendizagem, parametros):\n oa_existe = facade.objeto_concluido_facade(id_aluno=str(id_aluno), objeto_aprendizagem=objeto_aprendizagem)\n if oa_existe == None:\n x='if'\n facade.create_oa_concluido_facade(id_aluno=str(id_aluno), unidade=unidade,\n objeto_aprendizagem=objeto_aprendizagem)\n\n create_or_update_oa(id_aluno=str(id_aluno), unidade=unidade, objeto_aprendizagem=objeto_aprendizagem,\n parametros=parametros)\n else:\n ponto = pegar_maior_pontuacao(parametros)\n y='else'\n if ponto != False:\n facade.armazenar_dados_jogos_facade(oa_existe['id'], ponto)\n else:\n facade.armazenar_dados_jogos_facade(oa_existe['id'], parametros)\n print('create or updtate OA , relatorio',locals())\n\ndef pegar_maior_pontuacao(parametros:list):\n \"\"\"\n Comentario feito dia 17/10/2018\n\n Pega o maior nivel concluido\n :param parametros: Lista de dicionarios do OA concluido podendo tar ate 3 dicionarios , todos contendo as key nivel ,percentual conluido e termino\n que podem receber as variaveis facil(medio,dificil) , 0 ou 100 e True ou Falso , respectivamente\n :return: o dicionario de maior nivel com termino true ou , caso o aluno terra errado tudo , false\n \"\"\"\n teste = False\n\n for i in parametros:\n try:\n if i['termino'] == True:\n teste = i\n except Exception as exu:\n #excessao para corrigir bug da aventura 3\n print('excessao',exu)\n if i['percentualConcluido']==100:\n i['termino']=True\n teste=i\n else:\n i['termino']=False\n teste=i\n\n\n return teste\n\n\ndef parametros_json_jogos(parametro):\n\n for p in parametro:\n parametros = list(p)[0]\n parametros = json.loads(parametros)\n\n return parametros\n\n\"\"\" INICIO DE PARTES DO ALUNO QUE NAO SAO DO JOGO\"\"\"\ndef view_ambiente_de_aprendizagem():\n usuario = usuario_logado()\n if usuario['tipo'] == TIPO_USUARIOS['aluno']:\n jogador = facade.search_aluno_id_facade(id_aluno=usuario['id'])\n vida = jogador['pontos_de_vida']\n moedas = jogador['pontos_de_moedas']\n\n else:\n jogador = facade.search_observador_id_facade(id=usuario['id'])\n # vida = jogador['pontos_de_vida']\n # moedas = jogador['pontos_de_moedas']\n\n if jogador['cor'] != '0':\n cor = facade.search_estrutura_id_facade(id=jogador['cor'])['image_name']\n else:\n cor = jogador['cor']\n\n if jogador['rosto'] != '0':\n rosto = facade.search_estrutura_id_facade(id=jogador['rosto'])['image_name']\n else:\n rosto = jogador['rosto']\n if jogador['acessorio'] != '0':\n acessorio = facade.search_estrutura_id_facade(id=jogador['acessorio'])['image_name']\n else:\n acessorio = jogador['acessorio']\n if jogador['corpo'] != '0':\n corpo = facade.search_estrutura_id_facade(id=jogador['corpo'])['image_name']\n else:\n corpo = jogador['corpo']\n\n vida = jogador['pontos_de_vida']\n moedas = jogador['pontos_de_moedas']\n\n avatar = set_avatar_jogador(jogador)\n\n return dict(apelido=jogador['apelido'], vida=vida, moedas=moedas, cor=avatar['cor'], rosto=avatar['rosto'],\n acessorio=avatar['acessorio'], corpo=avatar['corpo'])\n\ndef set_avatar_jogador(jogador):\n if jogador['cor'] != '0':\n cor = facade.search_estrutura_id_facade(id=jogador['cor'])['image_name']\n else:\n cor = jogador['cor']\n\n if jogador['rosto'] != '0':\n rosto = facade.search_estrutura_id_facade(id=jogador['rosto'])['image_name']\n else:\n rosto = jogador['rosto']\n if jogador['acessorio'] != '0':\n acessorio = facade.search_estrutura_id_facade(id=jogador['acessorio'])['image_name']\n else:\n acessorio = jogador['acessorio']\n if jogador['corpo'] != '0':\n corpo = facade.search_estrutura_id_facade(id=jogador['corpo'])['image_name']\n else:\n corpo = jogador['corpo']\n\n return dict(cor=cor, rosto=rosto, acessorio=acessorio, corpo=corpo)\n\n\ndef getMedalhas(aluno):\n medalha_socio = []\n medalha_jogo = []\n todas_medalhas = facade.read_estrutura_facade(TIPO_ESTRUTURA['medalha'])\n for i in todas_medalhas:\n if i['tipo_medalha'] == '1':\n medalha_socio.append(i)\n else:\n medalha_jogo.append(i)\n\n return dict(medalha_aluno=todas_medalhas,medalha_jogo=medalha_jogo,medalha_socio=medalha_socio,medalha_recente=[],aluno_id=aluno,usuario=usuario_logado())\n\n\n# Resgatando Medalhas e Medalhas que o Aluno possui\ndef read_medalha_album(aluno):\n from control.gestao_aprendizagem_controller import convertendo_str_in_dict\n medalha_socio = []\n medalha_jogo = []\n medalha_aluno = []\n\n for i in facade.search_aluno_id_facade(id_aluno=aluno)['medalha']:\n i = convertendo_str_in_dict(str=i.decode('utf-8'))\n medalha_aluno.append(i['id_medalha'])\n\n todas_medalhas= facade.read_estrutura_facade(TIPO_ESTRUTURA['medalha'])\n for medalha in todas_medalhas:\n if medalha['tipo_medalha']== '1':\n medalha_socio.append(medalha)\n\n else:\n medalha_jogo.append(medalha)\n medalha_recente = []\n medalha_ultima = []\n if medalha_aluno != []:\n\n if len(medalha_aluno) > 4:\n z = medalha_aluno[len(medalha_aluno) - 4:len(medalha_aluno)]\n else:\n z = medalha_aluno\n\n for i in medalha_socio:\n if str(i['id']) in z:\n medalha_recente.append(i)\n for i in medalha_jogo:\n if str(i['id']) in z:\n medalha_recente.append(i)\n\n '''variavel medalha_recente da problema se n tiver medalha, ou se so tiver uma , pelo que parece '''\n try:\n medalha_ultima = medalha_ultima[len(medalha_recente) -1]\n except Exception as e:\n print('que ser esse erro? olhe depois , por favor',e)\n return dict(medalha_socio=medalha_socio,medalha_jogo=medalha_jogo,medalha_recente=medalha_recente,medalha_aluno=medalha_aluno,medalha_ultima=medalha_ultima,usuario=usuario_logado())\n\n","sub_path":"src/control/aprendizagem_controller.py","file_name":"aprendizagem_controller.py","file_ext":"py","file_size_in_byte":23849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"163486026","text":"import csv\n\nsome_dict = {\"hi\": \"die\", \"what's up\": \"wazzzzzzzzap\", \"bye\": \"c'ya\"}\n\nwith open(\"dz.csv\", \"w\", encoding = \"utf-8\") as f:\n \n data = csv.writer(f, delimiter = \";\")\n\n for i in some_dict.items():\n data.writerow(list(i))\n\n","sub_path":"projects/lesson2/homework/hw3.py","file_name":"hw3.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"135419710","text":"import unittest\r\nfrom WorkScheduler10 import Days, Employee, Shifts, run, show_schedule, all_shifts, all_days, all_employees,\\\r\n are_there_enough_employees, save_schedule_as_excel, check_wrongful_assignment, excluded_names_from_regular_shifts,\\\r\n excluded_employees_from_regular_shifts\r\nimport xlrd\r\n\r\n\r\ndef create_universe():\r\n\r\n Employee(name='emp1', contract_shift_amount=5, shift_count=5, scheduled_shifts_names=[], cooldown=0, scheduled_shifts=[], employee_limits=[], is_protools_authorized=True)\r\n Employee(name='emp2', contract_shift_amount=5, shift_count=5, scheduled_shifts_names=[], cooldown=0, scheduled_shifts=[], employee_limits=[], is_protools_authorized=False)\r\n Employee(name='emp3', contract_shift_amount=5, shift_count=5, scheduled_shifts_names=[], cooldown=0, scheduled_shifts=[], employee_limits=[], is_protools_authorized=False)\r\n Employee(name='emp4', contract_shift_amount=5, shift_count=5, scheduled_shifts_names=[], cooldown=0, scheduled_shifts=[], employee_limits=[], is_protools_authorized=False)\r\n Employee(name='emp5', contract_shift_amount=4, shift_count=4, scheduled_shifts_names=[], cooldown=0, scheduled_shifts=[], employee_limits=[], is_protools_authorized=False)\r\n Employee(name='emp6', contract_shift_amount=4, shift_count=4, scheduled_shifts_names=[], cooldown=0, scheduled_shifts=[], employee_limits=[], is_protools_authorized=False)\r\n Employee(name='emp7', contract_shift_amount=4, shift_count=4, scheduled_shifts_names=[], cooldown=0, scheduled_shifts=[], employee_limits=[], is_protools_authorized=False)\r\n Employee(name='emp8', contract_shift_amount=4, shift_count=4, scheduled_shifts_names=[], cooldown=0, scheduled_shifts=[], employee_limits=[], is_protools_authorized=False)\r\n Employee(name='emp9', contract_shift_amount=4, shift_count=4, scheduled_shifts_names=[], cooldown=0, scheduled_shifts=[], employee_limits=[], is_protools_authorized=False)\r\n Employee(name='emp10', contract_shift_amount=3, shift_count=3, scheduled_shifts_names=[], cooldown=0, scheduled_shifts=[], employee_limits=[], is_protools_authorized=False)\r\n Employee(name='Supervisor1', contract_shift_amount=5, shift_count=5, scheduled_shifts_names=[], cooldown=0, scheduled_shifts=[], employee_limits=[], is_protools_authorized=False)\r\n Employee(name='Supervisor2', contract_shift_amount=5, shift_count=5, scheduled_shifts_names=[], cooldown=0, scheduled_shifts=[], employee_limits=[], is_protools_authorized=False)\r\n Employee(name='PlaceHolder', contract_shift_amount=5, shift_count=5, scheduled_shifts_names=[], cooldown=0, scheduled_shifts=[], employee_limits=[], is_protools_authorized=False)\r\n\r\n day1shift1 = Shifts('Sunday', 'Morning', shift_code='Sunday Morning', required_employees=2,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day1shift2 = Shifts('Sunday', 'Protools', shift_code='Sunday Morning', required_employees=1,\r\n assigned_employees=[], assigned_names=[], is_protools_required=True)\r\n day1shift3 = Shifts('Sunday', 'Turner', shift_code='Sunday Evening', required_employees=0,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day1shift4 = Shifts('Sunday', 'Arabic', shift_code='Sunday Evening', required_employees=1,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day1shift5 = Shifts('Sunday', 'Evening', shift_code='Sunday Evening', required_employees=2,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day1shift6 = Shifts('Sunday', 'Night', shift_code='Sunday Night', required_employees=0,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day1shift7 = Shifts('Sunday', 'Super Morning', shift_code='Sunday Morning', required_employees=1,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day1shift8 = Shifts('Sunday', 'Super Evening', shift_code='Sunday Morning', required_employees=1,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n\r\n day2shift1 = Shifts('Monday', 'Morning', shift_code='Monday Morning', required_employees=2,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day2shift2 = Shifts('Monday', 'Protools', shift_code='Monday Morning', required_employees=1,\r\n assigned_employees=[], assigned_names=[], is_protools_required=True)\r\n day2shift3 = Shifts('Monday', 'Turner', shift_code='Monday Evening', required_employees=0,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day2shift4 = Shifts('Monday', 'Arabic', shift_code='Monday Evening', required_employees=1,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day2shift5 = Shifts('Monday', 'Evening', shift_code='Monday Evening', required_employees=2,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day2shift6 = Shifts('Monday', 'Night', shift_code='Monday Night', required_employees=0,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day2shift7 = Shifts('Monday', 'Super Morning', shift_code='Monday Morning', required_employees=1,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day2shift8 = Shifts('Monday', 'Super Evening', shift_code='Monday Morning', required_employees=1,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n\r\n day3shift1 = Shifts('Tuesday', 'Morning', shift_code='Tuesday Morning', required_employees=2,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day3shift2 = Shifts('Tuesday', 'Protools', shift_code='Tuesday Morning', required_employees=1,\r\n assigned_employees=[], assigned_names=[], is_protools_required=True)\r\n day3shift3 = Shifts('Tuesday', 'Turner', shift_code='Tuesday Evening', required_employees=0,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day3shift4 = Shifts('Tuesday', 'Arabic', shift_code='Tuesday Evening', required_employees=1,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day3shift5 = Shifts('Tuesday', 'Evening', shift_code='Tuesday Evening', required_employees=2,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day3shift6 = Shifts('Tuesday', 'Night', shift_code='Tuesday Night', required_employees=0,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day3shift7 = Shifts('Tuesday', 'Super Morning', shift_code='Tuesday Morning', required_employees=1,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day3shift8 = Shifts('Tuesday', 'Super Evening', shift_code='Tuesday Morning', required_employees=1,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n\r\n day4shift1 = Shifts('Wednesday', 'Morning', shift_code='Wednesday Morning', required_employees=2,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day4shift2 = Shifts('Wednesday', 'Protools', shift_code='Wednesday Morning', required_employees=1,\r\n assigned_employees=[], assigned_names=[], is_protools_required=True)\r\n day4shift3 = Shifts('Wednesday', 'Turner', shift_code='Wednesday Evening', required_employees=0,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day4shift4 = Shifts('Wednesday', 'Arabic', shift_code='Wednesday Evening', required_employees=1,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day4shift5 = Shifts('Wednesday', 'Evening', shift_code='Wednesday Evening', required_employees=2,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day4shift6 = Shifts('Wednesday', 'Night', shift_code='Wednesday Night', required_employees=0,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day4shift7 = Shifts('Wednesday', 'Super Morning', shift_code='Wednesday Morning', required_employees=1,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day4shift8 = Shifts('Wednesday', 'Super Evening', shift_code='Wednesday Morning', required_employees=1,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n\r\n day5shift1 = Shifts('Thursday', 'Morning', shift_code='Thursday Morning', required_employees=2,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day5shift2 = Shifts('Thursday', 'Protools', shift_code='Thursday Morning', required_employees=1,\r\n assigned_employees=[], assigned_names=[], is_protools_required=True)\r\n day5shift3 = Shifts('Thursday', 'Turner', shift_code='Thursday Evening', required_employees=0,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day5shift4 = Shifts('Thursday', 'Arabic', shift_code='Thursday Evening', required_employees=1,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day5shift5 = Shifts('Thursday', 'Evening', shift_code='Thursday Evening', required_employees=2,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day5shift6 = Shifts('Thursday', 'Night', shift_code='Thursday Night', required_employees=0,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day5shift7 = Shifts('Thursday', 'Super Morning', shift_code='Thursday Morning', required_employees=1,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day5shift8 = Shifts('Thursday', 'Super Evening', shift_code='Thursday Morning', required_employees=1,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n\r\n day6shift1 = Shifts('Friday', 'Morning', shift_code='Friday Morning', required_employees=2,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day6shift2 = Shifts('Friday', 'Protools', shift_code='Friday Morning', required_employees=0,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day6shift3 = Shifts('Friday', 'Turner', shift_code='Friday Evening', required_employees=0,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day6shift4 = Shifts('Friday', 'Arabic', shift_code='Friday Evening', required_employees=0,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day6shift5 = Shifts('Friday', 'Evening', shift_code='Friday Evening', required_employees=2,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day6shift6 = Shifts('Friday', 'Night', shift_code='Friday Night', required_employees=0,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day6shift7 = Shifts('Friday', 'Super Morning', shift_code='Friday Morning', required_employees=0,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day6shift8 = Shifts('Friday', 'Super Evening', shift_code='Friday Morning', required_employees=0,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n\r\n day7shift1 = Shifts('Saturday', 'Morning', shift_code='Saturday Morning', required_employees=2,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day7shift2 = Shifts('Saturday', 'Protools', shift_code='Saturday Morning', required_employees=0,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day7shift3 = Shifts('Saturday', 'Turner', shift_code='Saturday Evening', required_employees=0,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day7shift4 = Shifts('Saturday', 'Arabic', shift_code='Saturday Evening', required_employees=0,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day7shift5 = Shifts('Saturday', 'Evening', shift_code='Saturday Evening', required_employees=2,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day7shift6 = Shifts('Saturday', 'Night', shift_code='Saturday Night', required_employees=0,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day7shift7 = Shifts('Saturday', 'Super Morning', shift_code='Saturday Morning', required_employees=0,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n day7shift8 = Shifts('Saturday', 'Super Evening', shift_code='Saturday Morning', required_employees=0,\r\n assigned_employees=[], assigned_names=[], is_protools_required=False)\r\n\r\n Days('Sunday', all_assigned_employees=[], all_assigned_names=[],\r\n shifts=[day1shift1, day1shift2, day1shift3, day1shift4, day1shift5, day1shift6, day1shift7, day1shift8])\r\n Days('Monday', all_assigned_employees=[], all_assigned_names=[],\r\n shifts=[day2shift1, day2shift2, day2shift3, day2shift4, day2shift5, day2shift6, day2shift7, day2shift8])\r\n Days('Tuesday', all_assigned_employees=[], all_assigned_names=[],\r\n shifts=[day3shift1, day3shift2, day3shift3, day3shift4, day3shift5, day3shift6, day3shift7, day3shift8])\r\n Days('Wednesday', all_assigned_employees=[], all_assigned_names=[],\r\n shifts=[day4shift1, day4shift2, day4shift3, day4shift4, day4shift5, day4shift6, day4shift7, day4shift8])\r\n Days('Thursday', all_assigned_employees=[], all_assigned_names=[],\r\n shifts=[day5shift1, day5shift2, day5shift3, day5shift4, day5shift5, day5shift6, day5shift7, day5shift8])\r\n Days('Friday', all_assigned_employees=[], all_assigned_names=[],\r\n shifts=[day6shift1, day6shift2, day6shift3, day6shift4, day6shift5, day6shift6, day6shift7, day6shift8])\r\n Days('Saturday', all_assigned_employees=[], all_assigned_names=[],\r\n shifts=[day7shift1, day7shift2, day7shift3, day7shift4, day7shift5, day7shift6, day7shift7, day7shift8])\r\n\r\n return all_employees, all_shifts, all_days\r\n\r\n\r\nclass SchedulerTester(unittest.TestCase):\r\n\r\n def setUp(self):\r\n print('this is the setUp for the test')\r\n self.Days = Days\r\n self.Shifts = Shifts\r\n self.Employee = Employee\r\n self.all_employees, self.all_shifts, self.all_days = create_universe()\r\n self.excluded_names_from_regular_shifts = excluded_names_from_regular_shifts\r\n self.excluded_employees_from_regular_shifts = excluded_employees_from_regular_shifts\r\n self.excluded_names_from_regular_shifts.extend(['Supervisor1', 'Supervisor2', 'PlaceHolder'])\r\n for employee in self.all_employees:\r\n if employee.name in self.excluded_names_from_regular_shifts:\r\n self.excluded_employees_from_regular_shifts.append(employee)\r\n\r\n def tearDown(self):\r\n self.all_employees.clear()\r\n self.all_shifts.clear()\r\n self.all_days.clear()\r\n self.excluded_names_from_regular_shifts.clear()\r\n self.excluded_employees_from_regular_shifts.clear()\r\n print('This Is The End Of This Test')\r\n\r\n def test_that_all_shifts_that_require_employees_have_assigned_employees(self):\r\n \"\"\"This test will verify that each shift has assigned employees\"\"\"\r\n run()\r\n\r\n for shift in self.all_shifts:\r\n if shift.required_employees > 0:\r\n # print(shift.day_name, shift.shift_name, shift.required_employees, len(shift.assigned_employees), shift.assigned_names)\r\n self.assertGreater(len(shift.assigned_employees), 0)\r\n\r\n def test_that_all_shifts_have_assigned_employees_change_outcome_and_test_again(self):\r\n \"\"\"This test removes all employees from day1shift1 and then verify that the shift\r\n has employees agssigned to it - raising an AssertionError\"\"\"\r\n run()\r\n\r\n self.all_shifts[0].assigned_employees.clear()\r\n\r\n try:\r\n self.assertGreater(len(self.all_shifts[0].assigned_employees), 0)\r\n except AssertionError:\r\n print('Goodness')\r\n pass\r\n\r\n def test_shift_is_correct_employee_amount(self):\r\n \"\"\"This test checks if the function assign_employees() outputs the correct\r\n amount of employees for one specific shift\"\"\"\r\n run()\r\n\r\n self.assertEqual(len(all_shifts[0].assigned_employees), 2)\r\n\r\n def test_a_shift_change_expected_result_and_test_again(self):\r\n \"\"\"This test adds another employee to the list day1shift1.assigned_employees and then\r\n checks if the amount is correct - raising an AssertionError\"\"\"\r\n run()\r\n\r\n self.all_shifts[0].assigned_employees.append('1 too many')\r\n\r\n try:\r\n self.assertEqual(len(self.all_shifts[0].assigned_employees), 2)\r\n except AssertionError:\r\n pass\r\n\r\n def test_is_employee_qualified_for_protools_shift(self):\r\n \"\"\"This test will check whether or not the employee that was assigned is in the\r\n list of qualified employees for a protools shift \"\"\"\r\n run()\r\n\r\n for shift in self.all_shifts:\r\n if shift.shift_name == 'Protools':\r\n for employee in shift.assigned_employees:\r\n if employee.name != 'PlaceHolder':\r\n self.assertTrue(employee.is_protools_authorized)\r\n\r\n def test_is_an_employee_listed_twice_for_a_shift(self):\r\n \"\"\"This test checks if any employee is listed twice in the same shift\"\"\"\r\n run()\r\n\r\n for shift in self.all_shifts:\r\n self.assertEqual(len(shift.assigned_employees), len(list(set(shift.assigned_employees))))\r\n\r\n def test_is_an_employee_listed_twice_change_outcome_and_test_again(self):\r\n \"\"\"This test adds an employee twice to the same shift and then tests again, raising an assertion error\"\"\"\r\n run()\r\n self.all_shifts[0].assigned_names.append(self.all_shifts[0].assigned_names[0])\r\n self.all_shifts[0].assigned_employees.append(self.all_shifts[0].assigned_employees[0])\r\n show_schedule()\r\n\r\n try:\r\n self.assertEqual(len(self.all_shifts[0].assigned_names), len(list(set(self.all_shifts[0].assigned_names))))\r\n self.assertEqual(len(self.all_shifts[0].assigned_employees), len(list(set(self.all_shifts[0].assigned_employees))))\r\n except AssertionError:\r\n print('Passed')\r\n pass\r\n\r\n def test_did_any_employee_not_get_any_shifts(self):\r\n \"\"\"This test will cycle through all the employees and make sure that each\r\n employee was assigned to at least 1 shift\"\"\"\r\n run()\r\n\r\n for employee in self.all_employees:\r\n if employee.name != 'PlaceHolder':\r\n if employee.contract_shift_amount > 0:\r\n self.assertGreater(len(employee.scheduled_shifts), 0)\r\n\r\n def test_with_no_employees(self):\r\n \"\"\"tests how the code behaves when there are not enough employees\"\"\"\r\n self.all_employees.clear()\r\n\r\n run()\r\n\r\n for shift in all_shifts:\r\n self.assertEqual(shift.assigned_employees, [])\r\n self.assertEqual(shift.assigned_names, [])\r\n\r\n def test_is_schedule_possible(self):\r\n \"\"\"Checks if the function are_there_enough_employees is outputting correctly\"\"\"\r\n self.all_employees.clear()\r\n\r\n check = are_there_enough_employees()\r\n\r\n self.assertEqual(check, False)\r\n\r\n def test_protools_limits_are_working(self):\r\n self.all_employees[0].employee_limits.append('Sunday Morning')\r\n\r\n run()\r\n\r\n self.assertNotEqual(str(all_shifts[1].assigned_names), str(['emp1']))\r\n self.assertEqual(str(all_shifts[1].assigned_names), str(['PlaceHolder']))\r\n\r\n # def test_assignment_limits(self):\r\n # self.all_employees[0].employee_limits.append('')\r\n\r\n def test_save_to_excel(self):\r\n \"\"\"How do i test for this??\"\"\"\r\n run()\r\n save_schedule_as_excel()\r\n\r\n self.workbook = xlrd.open_workbook('test.xls')\r\n self.worksheet = self.workbook.sheet_by_name('Sheet 1')\r\n\r\n self.cell_to_check1 = self.worksheet.cell_value(0, 0)\r\n self.cell_to_check2 = self.worksheet.cell_value(2, 1)\r\n self.cell_to_check3 = self.worksheet.cell_value(9, 1)\r\n\r\n self.assertEqual(str(self.cell_to_check1), str('SundayMorning'))\r\n self.assertEqual(str(self.cell_to_check2), str('[]'))\r\n self.assertEqual(str(self.cell_to_check3), str(['emp1']))\r\n\r\n def test_save_to_excel_with_employee_limit(self):\r\n self.all_employees[0].employee_limits.append('Sunday Morning')\r\n\r\n run()\r\n save_schedule_as_excel()\r\n\r\n self.workbook = xlrd.open_workbook('test.xls')\r\n self.worksheet = self.workbook.sheet_by_name('Sheet 1')\r\n self.cell_to_check1 = self.worksheet.cell_value(1, 1)\r\n\r\n self.assertEqual(self.cell_to_check1, str(['PlaceHolder']))\r\n\r\n def test_check_wrongful_assignment(self):\r\n \"\"\"This test will assign an employee against his limits and then check if the\r\n function check_wrongful_assignment caught it\"\"\"\r\n\r\n self.all_employees[6].employee_limits.append('Sunday Morning')\r\n self.all_shifts[0].assigned_employees.append(self.all_employees[6])\r\n self.all_shifts[0].assigned_names.append(self.all_employees[6].name)\r\n\r\n run()\r\n check_wrongful_assignment()\r\n\r\n self.assertIn('PlaceHolder', self.all_shifts[0].assigned_names)\r\n\r\n def test_assign_supervisor(self):\r\n \"\"\"This test will make sure that the employee assigned to a supervisor shift is indeed a supervisor\"\"\"\r\n\r\n self.supervisors = [['Supervisor1'], ['Supervisor2']]\r\n run()\r\n\r\n for shift in self.all_shifts:\r\n if shift.shift_name == 'Super Morning' or shift.shift_name == 'Super Evening':\r\n if shift.required_employees > 0:\r\n self.assertIn(shift.assigned_names, self.supervisors)\r\n\r\n def test_assign_supervisor_change_outcome_test_again(self):\r\n \"\"\"This test will make sure that the employee assigned to a supervisor shift is indeed a supervisor\"\"\"\r\n self.supervisors = [['Supervisor1'], ['Supervisor2']]\r\n\r\n run()\r\n self.all_shifts[6].assigned_employees.clear()\r\n self.all_shifts[6].assigned_names.clear()\r\n self.all_shifts[6].assigned_employees.append(all_employees[0])\r\n self.all_shifts[6].assigned_names.append(all_employees[0].name)\r\n show_schedule()\r\n\r\n for shift in self.all_shifts:\r\n if shift.shift_name == 'Super Morning' or shift.shift_name == 'Super Evening':\r\n if shift.required_employees > 0:\r\n try:\r\n self.assertIn(shift.assigned_names, self.supervisors)\r\n except AssertionError:\r\n pass\r\n","sub_path":"Scheduler_Tester2.py","file_name":"Scheduler_Tester2.py","file_ext":"py","file_size_in_byte":23757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"615855839","text":"import tensorflow as tf\nfrom kerastuner.applications import resnet\nfrom kerastuner.applications import xception\nfrom tensorflow.python.util import nest\n\nfrom autokeras import utils\nfrom autokeras.hypermodel import base\n\n\ndef set_hp_value(hp, name, value):\n full_name = hp._get_name(name)\n hp.values[full_name] = value or hp.values[full_name]\n\n\nclass DenseBlock(base.Block):\n \"\"\"Block for Dense layers.\n\n # Arguments\n num_layers: Int. The number of Dense layers in the block.\n If left unspecified, it will be tuned automatically.\n use_bn: Boolean. Whether to use BatchNormalization layers.\n If left unspecified, it will be tuned automatically.\n dropout_rate: Float. The dropout rate for the layers.\n If left unspecified, it will be tuned automatically.\n \"\"\"\n\n def __init__(self,\n num_layers=None,\n use_batchnorm=None,\n dropout_rate=None,\n **kwargs):\n super().__init__(**kwargs)\n self.num_layers = num_layers\n self.use_batchnorm = use_batchnorm\n self.dropout_rate = dropout_rate\n\n def get_config(self):\n config = super().get_config()\n config.update({\n 'num_layers': self.num_layers,\n 'use_batchnorm': self.use_batchnorm,\n 'dropout_rate': self.dropout_rate})\n return config\n\n def build(self, hp, inputs=None):\n inputs = nest.flatten(inputs)\n utils.validate_num_inputs(inputs, 1)\n input_node = inputs[0]\n output_node = input_node\n output_node = Flatten().build(hp, output_node)\n\n num_layers = self.num_layers or hp.Choice('num_layers', [1, 2, 3], default=2)\n use_batchnorm = self.use_batchnorm\n if use_batchnorm is None:\n use_batchnorm = hp.Boolean('use_batchnorm', default=False)\n if self.dropout_rate is not None:\n dropout_rate = self.dropout_rate\n else:\n dropout_rate = hp.Choice('dropout_rate', [0.0, 0.25, 0.5], default=0)\n\n for i in range(num_layers):\n units = hp.Choice(\n 'units_{i}'.format(i=i),\n [16, 32, 64, 128, 256, 512, 1024],\n default=32)\n output_node = tf.keras.layers.Dense(units)(output_node)\n if use_batchnorm:\n output_node = tf.keras.layers.BatchNormalization()(output_node)\n output_node = tf.keras.layers.ReLU()(output_node)\n if dropout_rate > 0:\n output_node = tf.keras.layers.Dropout(dropout_rate)(output_node)\n return output_node\n\n\nclass RNNBlock(base.Block):\n \"\"\"An RNN Block.\n\n # Arguments\n return_sequences: Boolean. Whether to return the last output in the\n output sequence, or the full sequence. Defaults to False.\n bidirectional: Boolean. Bidirectional RNN. If left unspecified, it will be\n tuned automatically.\n num_layers: Int. The number of layers in RNN. If left unspecified, it will\n be tuned automatically.\n layer_type: String. 'gru' or 'lstm'. If left unspecified, it will be tuned\n automatically.\n \"\"\"\n\n def __init__(self,\n return_sequences=False,\n bidirectional=None,\n num_layers=None,\n layer_type=None,\n **kwargs):\n super().__init__(**kwargs)\n self.return_sequences = return_sequences\n self.bidirectional = bidirectional\n self.num_layers = num_layers\n self.layer_type = layer_type\n\n def get_config(self):\n config = super().get_config()\n config.update({\n 'return_sequences': self.return_sequences,\n 'bidirectional': self.bidirectional,\n 'num_layers': self.num_layers,\n 'layer_type': self.layer_type})\n return config\n\n def build(self, hp, inputs=None):\n inputs = nest.flatten(inputs)\n utils.validate_num_inputs(inputs, 1)\n input_node = inputs[0]\n shape = input_node.shape.as_list()\n if len(shape) != 3:\n raise ValueError(\n 'Expect the input tensor to have '\n 'at least 3 dimensions for rnn models, '\n 'but got {shape}'.format(shape=input_node.shape))\n\n feature_size = shape[-1]\n output_node = input_node\n\n bidirectional = self.bidirectional\n if bidirectional is None:\n bidirectional = hp.Boolean('bidirectional', default=True)\n layer_type = self.layer_type or hp.Choice('layer_type',\n ['gru', 'lstm'],\n default='lstm')\n num_layers = self.num_layers or hp.Choice('num_layers',\n [1, 2, 3],\n default=2)\n rnn_layers = {\n 'gru': tf.keras.layers.GRU,\n 'lstm': tf.keras.layers.LSTM\n }\n in_layer = rnn_layers[layer_type]\n for i in range(num_layers):\n return_sequences = True\n if i == num_layers - 1:\n return_sequences = self.return_sequences\n if bidirectional:\n output_node = tf.keras.layers.Bidirectional(\n in_layer(feature_size,\n return_sequences=return_sequences))(output_node)\n else:\n output_node = in_layer(\n feature_size,\n return_sequences=return_sequences)(output_node)\n return output_node\n\n\nclass ConvBlock(base.Block):\n \"\"\"Block for vanilla ConvNets.\n\n # Arguments\n kernel_size: Int. If left unspecified, it will be tuned automatically.\n num_blocks: Int. The number of conv blocks. If left unspecified, it will be\n tuned automatically.\n separable: Boolean. Whether to use separable conv layers.\n If left unspecified, it will be tuned automatically.\n dropout_rate: Float. Between 0 and 1. The dropout rate for after the\n convolutional layers. If left unspecified, it will be tuned\n automatically.\n \"\"\"\n\n def __init__(self,\n kernel_size=None,\n num_blocks=None,\n separable=None,\n dropout_rate=None,\n **kwargs):\n super().__init__(**kwargs)\n self.kernel_size = kernel_size\n self.num_blocks = num_blocks\n self.separable = separable\n self.dropout_rate = dropout_rate\n\n def get_config(self):\n config = super().get_config()\n config.update({\n 'kernel_size': self.kernel_size,\n 'num_blocks': self.num_blocks,\n 'separable': self.separable,\n 'dropout_rate': self.dropout_rate})\n return config\n\n def build(self, hp, inputs=None):\n inputs = nest.flatten(inputs)\n utils.validate_num_inputs(inputs, 1)\n input_node = inputs[0]\n output_node = input_node\n\n kernel_size = self.kernel_size or hp.Choice('kernel_size',\n [3, 5, 7],\n default=3)\n num_blocks = self.num_blocks or hp.Choice('num_blocks',\n [1, 2, 3],\n default=2)\n separable = self.separable\n if separable is None:\n separable = hp.Boolean('separable', default=False)\n\n if separable:\n conv = utils.get_sep_conv(input_node.shape)\n else:\n conv = utils.get_conv(input_node.shape)\n pool = utils.get_max_pooling(input_node.shape)\n\n if self.dropout_rate is not None:\n dropout_rate = self.dropout_rate\n else:\n dropout_rate = hp.Choice('dropout_rate', [0.0, 0.25, 0.5], default=0)\n\n for i in range(num_blocks):\n output_node = conv(\n hp.Choice('filters_{i}_1'.format(i=i),\n [16, 32, 64],\n default=32),\n kernel_size,\n padding=self._get_padding(kernel_size, output_node),\n activation='relu')(output_node)\n output_node = conv(\n hp.Choice('filters_{i}_2'.format(i=i),\n [16, 32, 64],\n default=32),\n kernel_size,\n padding=self._get_padding(kernel_size, output_node),\n activation='relu')(output_node)\n output_node = pool(\n kernel_size - 1,\n padding=self._get_padding(kernel_size - 1, output_node))(output_node)\n if dropout_rate > 0:\n output_node = tf.keras.layers.Dropout(dropout_rate)(output_node)\n return output_node\n\n @staticmethod\n def _get_padding(kernel_size, output_node):\n if (kernel_size * 2 <= output_node.shape[1] and\n kernel_size * 2 <= output_node.shape[2]):\n return 'valid'\n return 'same'\n\n\nclass ResNetBlock(base.Block, resnet.HyperResNet):\n \"\"\"Block for ResNet.\n\n # Arguments\n version: String. 'v1', 'v2' or 'next'. The type of ResNet to use.\n If left unspecified, it will be tuned automatically.\n pooling: String. 'avg', 'max'. The type of pooling layer to use.\n If left unspecified, it will be tuned automatically.\n \"\"\"\n\n def __init__(self,\n version=None,\n pooling=None,\n **kwargs):\n super().__init__(include_top=False, input_shape=(10,), **kwargs)\n self.version = version\n self.pooling = pooling\n\n def get_config(self):\n config = super().get_config()\n config.update({\n 'version': self.version,\n 'pooling': self.pooling})\n return config\n\n def build(self, hp, inputs=None):\n self.input_tensor = nest.flatten(inputs)[0]\n self.input_shape = None\n\n hp.Choice('version', ['v1', 'v2', 'next'], default='v2')\n hp.Choice('pooling', ['avg', 'max'], default='avg')\n\n set_hp_value(hp, 'version', self.version)\n set_hp_value(hp, 'pooling', self.pooling)\n\n model = super().build(hp)\n return model.outputs\n\n\nclass XceptionBlock(base.Block, xception.HyperXception):\n \"\"\"XceptionBlock.\n\n An Xception structure, used for specifying your model with specific datasets.\n\n The original Xception architecture is from https://arxiv.org/abs/1610.02357.\n The data first goes through the entry flow, then through the middle flow which\n is repeated eight times, and finally through the exit flow.\n\n This XceptionBlock returns a similar architecture as Xception except without\n the last (optional) fully connected layer(s) and logistic regression.\n The size of this architecture could be decided by `HyperParameters`, to get an\n architecture with a half, an identical, or a double size of the original one.\n\n # Arguments\n activation: String. 'selu' or 'relu'. If left unspecified, it will be tuned\n automatically.\n initial_strides: Int. If left unspecified, it will be tuned automatically.\n num_residual_blocks: Int. If left unspecified, it will be tuned\n automatically.\n pooling: String. 'ave', 'flatten', or 'max'. If left unspecified, it will be\n tuned automatically.\n \"\"\"\n\n def __init__(self,\n activation=None,\n initial_strides=None,\n num_residual_blocks=None,\n pooling=None,\n **kwargs):\n super().__init__(include_top=False, input_shape=(10,), **kwargs)\n self.activation = activation\n self.initial_strides = initial_strides\n self.num_residual_blocks = num_residual_blocks\n self.pooling = pooling\n\n def get_config(self):\n config = super().get_config()\n config.update({\n 'activation': self.activation,\n 'initial_strides': self.initial_strides,\n 'num_residual_blocks': self.num_residual_blocks,\n 'pooling': self.pooling})\n return config\n\n def build(self, hp, inputs=None):\n self.input_tensor = nest.flatten(inputs)[0]\n self.input_shape = None\n\n hp.Choice('activation', ['relu', 'selu'])\n hp.Choice('initial_strides', [2])\n hp.Int('num_residual_blocks', 2, 8, default=4)\n hp.Choice('pooling', ['avg', 'flatten', 'max'])\n\n set_hp_value(hp, 'activation', self.activation)\n set_hp_value(hp, 'initial_strides', self.initial_strides)\n set_hp_value(hp, 'num_residual_blocks', self.num_residual_blocks)\n set_hp_value(hp, 'pooling', self.pooling)\n\n model = super().build(hp)\n return model.outputs\n\n\ndef shape_compatible(shape1, shape2):\n if len(shape1) != len(shape2):\n return False\n # TODO: If they can be the same after passing through any layer,\n # they are compatible. e.g. (32, 32, 3), (16, 16, 2) are compatible\n return shape1[:-1] == shape2[:-1]\n\n\nclass Merge(base.Block):\n \"\"\"Merge block to merge multiple nodes into one.\n\n # Arguments\n merge_type: String. 'add' or 'concatenate'. If left unspecified, it will be\n tuned automatically.\n \"\"\"\n\n def __init__(self, merge_type=None, **kwargs):\n super().__init__(**kwargs)\n self.merge_type = merge_type\n\n def get_config(self):\n config = super().get_config()\n config.update({'merge_type': self.merge_type})\n return config\n\n def build(self, hp, inputs=None):\n inputs = nest.flatten(inputs)\n if len(inputs) == 1:\n return inputs\n\n merge_type = self.merge_type or hp.Choice('merge_type',\n ['add', 'concatenate'],\n default='add')\n\n if not all([shape_compatible(input_node.shape, inputs[0].shape) for\n input_node in inputs]):\n new_inputs = []\n for input_node in inputs:\n new_inputs.append(Flatten().build(hp, input_node))\n inputs = new_inputs\n\n # TODO: Even inputs have different shape[-1], they can still be Add(\n # ) after another layer. Check if the inputs are all of the same\n # shape\n if all([input_node.shape == inputs[0].shape for input_node in inputs]):\n if merge_type == 'add':\n return tf.keras.layers.Add(inputs)\n\n return tf.keras.layers.Concatenate()(inputs)\n\n\nclass Flatten(base.Block):\n \"\"\"Flatten the input tensor with Keras Flatten layer.\"\"\"\n\n def build(self, hp, inputs=None):\n inputs = nest.flatten(inputs)\n utils.validate_num_inputs(inputs, 1)\n input_node = inputs[0]\n if len(input_node.shape) > 2:\n return tf.keras.layers.Flatten()(input_node)\n return input_node\n\n\nclass SpatialReduction(base.Block):\n \"\"\"Reduce the dimension of a spatial tensor, e.g. image, to a vector.\n\n # Arguments\n reduction_type: String. 'flatten', 'global_max' or 'global_avg'.\n If left unspecified, it will be tuned automatically.\n \"\"\"\n\n def __init__(self, reduction_type=None, **kwargs):\n super().__init__(**kwargs)\n self.reduction_type = reduction_type\n\n def get_config(self):\n config = super().get_config()\n config.update({'reduction_type': self.reduction_type})\n return config\n\n def build(self, hp, inputs=None):\n inputs = nest.flatten(inputs)\n utils.validate_num_inputs(inputs, 1)\n input_node = inputs[0]\n output_node = input_node\n\n # No need to reduce.\n if len(output_node.shape) <= 2:\n return output_node\n\n reduction_type = self.reduction_type or hp.Choice('reduction_type',\n ['flatten',\n 'global_max',\n 'global_avg'],\n default='global_avg')\n if reduction_type == 'flatten':\n output_node = Flatten().build(hp, output_node)\n elif reduction_type == 'global_max':\n output_node = utils.get_global_max_pooling(\n output_node.shape)()(output_node)\n elif reduction_type == 'global_avg':\n output_node = utils.get_global_average_pooling(\n output_node.shape)()(output_node)\n return output_node\n\n\nclass TemporalReduction(base.Block):\n \"\"\"Reduce the dimension of a temporal tensor, e.g. output of RNN, to a vector.\n\n # Arguments\n reduction_type: String. 'flatten', 'global_max' or 'global_avg'. If left\n unspecified, it will be tuned automatically.\n \"\"\"\n\n def __init__(self, reduction_type=None, **kwargs):\n super().__init__(**kwargs)\n self.reduction_type = reduction_type\n\n def get_config(self):\n config = super().get_config()\n config.update({'reduction_type': self.reduction_type})\n return config\n\n def build(self, hp, inputs=None):\n inputs = nest.flatten(inputs)\n utils.validate_num_inputs(inputs, 1)\n input_node = inputs[0]\n output_node = input_node\n\n # No need to reduce.\n if len(output_node.shape) <= 2:\n return output_node\n\n reduction_type = self.reduction_type or hp.Choice('reduction_type',\n ['flatten',\n 'global_max',\n 'global_avg'],\n default='global_avg')\n\n if reduction_type == 'flatten':\n output_node = Flatten().build(hp, output_node)\n elif reduction_type == 'global_max':\n output_node = tf.math.reduce_max(output_node, axis=-2)\n elif reduction_type == 'global_avg':\n output_node = tf.math.reduce_mean(output_node, axis=-2)\n elif reduction_type == 'global_min':\n output_node = tf.math.reduce_min(output_node, axis=-2)\n\n return output_node\n\n\nclass EmbeddingBlock(base.Block):\n \"\"\"Word embedding block for sequences.\n\n The input should be tokenized sequences with the same length, where each element\n of a sequence should be the index of the word.\n\n # Arguments\n max_features: Int. Size of the vocabulary. Must be set if not using\n TextToIntSequence before this block. If not specified, we will use the\n vocabulary size in the preceding TextToIntSequence vocabulary size.\n pretraining: String. 'random' (use random weights instead any pretrained\n model), 'glove', 'fasttext' or 'word2vec'. Use pretrained word embedding.\n If left unspecified, it will be tuned automatically.\n embedding_dim: Int. If left unspecified, it will be tuned automatically.\n dropout_rate: Float. The dropout rate for after the Embedding layer.\n If left unspecified, it will be tuned automatically.\n \"\"\"\n\n def __init__(self,\n max_features=None,\n pretraining=None,\n embedding_dim=None,\n dropout_rate=None,\n **kwargs):\n super().__init__(**kwargs)\n self.max_features = max_features\n self.pretraining = pretraining\n self.embedding_dim = embedding_dim\n self.dropout_rate = dropout_rate\n\n def get_config(self):\n config = super().get_config()\n config.update({\n 'max_features': self.max_features,\n 'pretraining': self.pretraining,\n 'embedding_dim': self.embedding_dim,\n 'dropout_rate': self.dropout_rate})\n return config\n\n def build(self, hp, inputs=None):\n input_node = nest.flatten(inputs)[0]\n # TODO: support more pretrained embedding layers.\n # glove, fasttext, and word2vec\n pretraining = self.pretraining or hp.Choice(\n 'pretraining',\n ['random', 'glove', 'fasttext', 'word2vec', 'none'],\n default='none')\n embedding_dim = self.embedding_dim or hp.Choice(\n 'embedding_dim',\n [32, 64, 128, 256, 512],\n default=128)\n if pretraining != 'none':\n # TODO: load from pretrained weights\n layer = tf.keras.layers.Embedding(\n input_dim=self.max_features,\n output_dim=embedding_dim,\n input_length=input_node.shape[1])\n # trainable=False,\n # weights=[embedding_matrix])\n else:\n layer = tf.keras.layers.Embedding(\n input_dim=self.max_features,\n output_dim=embedding_dim,\n input_length=input_node.shape[1],\n trainable=True)\n output_node = layer(input_node)\n if self.dropout_rate is not None:\n dropout_rate = self.dropout_rate\n else:\n dropout_rate = hp.Choice('dropout_rate', [0.0, 0.25, 0.5], default=0.25)\n if dropout_rate > 0:\n output_node = tf.keras.layers.Dropout(dropout_rate)(output_node)\n return output_node\n","sub_path":"autokeras/hypermodel/block.py","file_name":"block.py","file_ext":"py","file_size_in_byte":21472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"463562577","text":"###\n#\n# @Author:\n# Dennis Przytarski: dennis.przytarski@gmx.de\n#\n# @Description: \n# This file reads the results, adds the corresponding lat & lon metadata\n# provided by the the Landesmuseum Baden in json format to the first result\n# and saves it as new txt file\n#\n###\n\nfrom absl import app\nfrom absl import flags\n# import ijson\nimport json \n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_string(\n 'results_path', 'delg/workspace/results/final/BA 2020-00001-034_Scan01_result.txt',\n 'Path to .text results file.'\n)\nflags.DEFINE_string(\n 'json_path', 'delg/workspace/metadata/blmki_bildarchivstaufen.json',\n 'Path to Baden\\'s \"Staufen\" .json file with metadata.'\n)\nflags.DEFINE_string(\n 'image_extension', '.jpg',\n 'Extension of image files in json metadata.'\n)\n\ndef main(argv):\n with open(FLAGS.results_path) as rf:\n results = rf.readlines()\n r = results[0]\n r_name = r.rsplit('] ', 1)[1][:-2]\n with open(FLAGS.json_path, 'r') as json_file:\n # use ijson when everything in one line\n #for i in ijson.items(j, 'records.item.medium.item.name', multiple_values=True):\n data = json.load(json_file)\n loc_name, lat, lon = 'N/A', 'N/A', 'N/A'\n for record in data['records']:\n if 'medium' in record:\n for i in record['medium']:\n if i[\"name\"] == r_name + FLAGS.image_extension:\n for o in record[\"ort\"]:\n if o[\"typ\"] == 'Herstellungsort':\n if 'term' in o:\n loc_name = o[\"term\"]\n if 'lat' and 'lon' in o:\n lat = o[\"lat\"]\n lon = o[\"lon\"]\n new_result = r[:-2] + ' - location: ' + loc_name + ' - lat: ' + lat + ', lon: ' + lon + '\\n'\n \n nf_path = FLAGS.results_path[:-4] + '_location.txt'\n nf = open(nf_path, \"w\")\n nf.write(new_result)\n nf.close()\n\n rf.close()\n print('Successfully created metadata result: ' + nf_path) \n \t\nif __name__ == '__main__':\n app.run(main)\n","sub_path":"get_metadata_result.py","file_name":"get_metadata_result.py","file_ext":"py","file_size_in_byte":1954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"291837809","text":"from django.conf.urls import url, include\nfrom . import views\n\napp_name = 'employer'\nurlpatterns = [\n url(r'^$', views.IndexView.as_view(), name='index'),\n url(r'^(?P[0-9]+)/view_search_profile/$', views.ViewSearchProfile.as_view(), name='view_search_profile'),\n url(r'^delete_search_profile/$', views.DeleteSearchProfile, name='delete_search_profile'), \n url(r'^create_search_profile/$', views.CreateSearchProfile.as_view(), name='create_search_profile'),\n url(r'^get_subdiscipline/$', views.get_subdiscipline, name='get_subdiscipline'),\n url(r'^insert_search_profile/$', views.InsertSearchProfile, name='insert_search_profile'),\n # url(r'^employer_index/$', views.EmployerIndexView.as_view(),name='employer_index'),\n # # url(r'^register/$', views.RegisterView.as_view(), name='register')),\n # url(r'^employer_index/$', views.EmployerIndexView.as_view(),name='employer_index'),\n # url(r'^show_result/$', views.ShowResultView.as_view(), name='show_result'),\n # url(r'get_result_data/$', views.get_result_data, name='get_result_data'),\n url(r'^employer_export_csv/$', views.EmployerExportCsvView.as_view(), name='employer_export_csv'),\n # url(r'^search_profile_collection/$', views.SearchProfileCollectionView.as_view(), name='search_profile_collection'),\n \n url(r'^send_email/$', views.send_mass_mail, name='send_email'),\n # url(r'^(?P[0-9]+)/save_csv/$', views.save_csv, name='save_csv'),\n url(r'^(?P[0-9]+)/download_csv/$', views.download_csv, name='download_csv'),\n url(r'^get_search_profile/$', views.get_search_profile, name='get_search_profile'), \n url(r'^generate_csv/$', views.generate_csv, name='generate_csv'),\n\n]","sub_path":"employer/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"566156207","text":"#-*- encoding: utf-8 -*-\nimport traceback\nimport lxml.etree as ET\nfrom DBSet import *\nfrom BaseExportor import *\nfrom InstructionManager import InstructinManager\n\n########################################################################\nclass HeroExportor(BaseExportor):\n \"\"\"\"\"\"\n\n #----------------------------------------------------------------------\n def __init__(self, config_path):\n \"\"\"Constructor\"\"\"\n self.__path=config_path\n \n #----------------------------------------------------------------------\n def export(self):\n \"\"\"\"\"\"\n print(\"export Hero\")\n try:\n #excel文件名\n input_file=self.__path+'/Hero.xlsx'\n Hero_data=DBSet(input_file)\n input_file=self.__path+'/resource_contrast.xlsx'\n res_data=DBSet(input_file)\n hero_res=res_data[\"hero\"]\n \n #输出主角\n main_hero=Hero_data['main_hero']\n outfile='%s/main_hero.xml'%(self.__path)\n self.exporthero(outfile,main_hero,hero_res)\n #输出伙伴\n first_hero=Hero_data['first_hero']\n outfile='%s/first_hero.xml'%(self.__path)\n self.exporthero(outfile,first_hero,hero_res)\n print('export Hero done!!!')\n except Exception as err:\n traceback.print_exc()\n print('Handling run-time error:',str(err.args))\n #print(\"error\",sys.exc_info()[0])\n #print(\"error\",sys.exc_info()[1])\n \n #----------------------------------------------------------------------\n def exporthero(self,outfile,hero_data,hero_res,is_use_hero_index=True):\n \"\"\"\"\"\"\n \n root=ET.Element('hero_define')\n for index, Hero in hero_data.items():\n hero_entry=ET.SubElement(root, 'hero_entry')\n for k,v in Hero.items():\n if k=='hero_index':\n hero_entry.set('hero_index', str(v))\n elif k=='passive_skill':\n passive_skill=ET.SubElement(hero_entry, 'passive_skill')\n skill_index=ET.SubElement(passive_skill, 'skill_index')\n skill_index.text=str(v)\n elif k=='active_skill':\n active_skill=ET.SubElement(hero_entry, 'active_skill')\n skill_index=ET.SubElement(active_skill, 'skill_index')\n if is_use_hero_index:\n skill_index.text=str(index)\n else:\n skill_index.text=str(v)\n else:\n entry=ET.SubElement(hero_entry, k)\n entry.text=str(v)\n hero_style_value=str(Hero['hero_style'])\n \n #资源配置\n name=str(Hero['hero_name'])\n \n hr = hero_res[name]\n\n if hr['object_file'] != '':\n object_file=ET.SubElement(hero_entry, 'object_file')\n object_file.text=str(hr['object_file'])\n \n else:print(name + \"-没有配置obj\"),exit()\n \n if hr['hero_effect'] != '':\n hero_effect=ET.SubElement(hero_entry, 'hero_effect')\n hero_effect.text=str(hr['hero_effect'])\n\n if hr['hero_name_image'] != '':\n hero_name_image=ET.SubElement(hero_entry, 'hero_name_image')\n hero_name_image.text=str(hr['hero_name_image'])\n if hr['hero_whole_head'] != '':\n hero_whole_head=ET.SubElement(hero_entry, 'hero_whole_head')\n hero_whole_head.text=str(hr['hero_whole_head']) \n if hr['hero_big_head'] != '':\n hero_big_head=ET.SubElement(hero_entry, 'hero_big_head')\n hero_big_head.text=str(hr['hero_big_head'])\n if hr['hero_small_head'] != '':\n hero_small_head=ET.SubElement(hero_entry, 'hero_small_head')\n hero_small_head.text=str(hr['hero_small_head'])\n #物理、法术攻击\n regular_formula,s=get_combat_formula(hero_style_value)\n #damagetype=get_damage_type(hero_style_value)\n #instruction 类型\n default_instruction=ET.SubElement(hero_entry, 'default_instruction')\n #instruction的Index\n #default_instruction.text= InstructinManager.get_instruction_index(regular_formula.damagetype, regular_instruct_type, regular_formula.type) \n default_instruction.text= InstructinManager.get_ultra_instruction_index(name,regular_formula.damagetype, regular_formula.type) \n \n \n tree=ET.ElementTree(root)\n tree.write(outfile,encoding=\"UTF-8\",pretty_print=True,xml_declaration=True)\n ","sub_path":"otherdata/Tool/DragBallEditor/HeroExportor.py","file_name":"HeroExportor.py","file_ext":"py","file_size_in_byte":4803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"542582797","text":"from typing import Callable, Optional\n\nimport torch\nfrom torch import nn\n\nimport constants\nfrom rl_multi_agent import MultiAgent\nfrom rl_multi_agent.experiments.experiment import ExperimentConfig\nfrom rl_multi_agent.furnmove_episode_samplers import FurnMoveGridEpisodeSampler\nfrom rl_multi_agent.furnmove_episodes import FurnMoveEgocentricFastGridEpisode\nfrom rl_multi_agent.models import A3CLSTMNStepComCoordinatedActionsEgoGridsEmbedCNN\n\n\nclass FurnMoveExperimentConfig(ExperimentConfig):\n # Env/episode config\n num_agents = 2\n screen_size = 84\n episode_class = FurnMoveEgocentricFastGridEpisode\n episode_sampler_class = FurnMoveGridEpisodeSampler\n visible_agents = True\n include_depth_frame = False\n include_move_obj_actions = True\n headless = True if torch.cuda.is_available() else False\n\n # Model config\n state_repr_length = 512\n talk_embed_length = 16\n reply_embed_length = 16\n agent_num_embed_length = 8\n coordinate_actions = False\n num_talk_symbols = 2\n num_reply_symbols = 2\n\n # Agent config\n agent_class = MultiAgent\n turn_off_communication = True\n\n # Training config\n max_ep_using_expert_actions = 0\n train_scenes = constants.TRAIN_SCENE_NAMES[20:40]\n valid_scenes = constants.VALID_SCENE_NAMES[5:10]\n use_a3c_loss_when_not_expert_forcing = True\n\n # Misc (e.g. visualization)\n record_all_in_test = False\n save_talk_reply_probs_path = None\n include_test_eval_results = not torch.cuda.is_available()\n return_likely_successfuly_move_actions = False\n\n @classmethod\n def get_init_train_params(cls):\n init_train_params = {\n \"scenes\": cls.train_scenes,\n \"num_agents\": cls.num_agents,\n \"object_type\": \"Television\",\n \"to_object_type\": \"Dresser\",\n \"to_object_silhouette\": constants.DRESSER_SILHOUETTE_STRING,\n \"episode_class\": cls.episode_class,\n \"player_screen_height\": cls.screen_size,\n \"player_screen_width\": cls.screen_size,\n \"max_ep_using_expert_actions\": cls.max_ep_using_expert_actions,\n \"visible_agents\": cls.visible_agents,\n \"include_depth_frame\": cls.include_depth_frame,\n \"object_initial_height\": 1.3,\n \"headless\": cls.headless,\n \"max_distance_from_object\": 0.76,\n \"max_episode_length\": 500,\n \"episode_args\": {\n \"include_move_obj_actions\": cls.include_move_obj_actions,\n \"first_correct_coord_reward\": 0.0,\n \"exploration_bonus\": 0.0,\n \"failed_action_penalty\": -0.02,\n \"step_penalty\": -0.01,\n \"joint_pass_penalty\": -0.09,\n \"moved_closer_reward\": 1.0,\n \"min_dist_to_to_object\": 0.26,\n \"reached_target_reward\": 1.0,\n \"return_likely_successfuly_move_actions\": cls.return_likely_successfuly_move_actions,\n \"frame_type\": \"fast-egocentric-relative-tensor\",\n \"pass_conditioned_coordination\": True,\n },\n }\n return init_train_params\n\n @classmethod\n def get_init_valid_params(cls):\n init_valid_params = {\n **cls.get_init_train_params(),\n \"scenes\": cls.valid_scenes,\n \"player_screen_height\": 224,\n \"player_screen_width\": 224,\n \"headless\": False,\n }\n if cls.save_talk_reply_probs_path is not None:\n init_valid_params[\n \"save_talk_reply_probs_path\"\n ] = cls.save_talk_reply_probs_path\n return init_valid_params\n\n def __init__(self):\n self._init_train_agent = self.episode_sampler_class(\n **self.get_init_train_params()\n )\n self._init_test_agent = self.episode_sampler_class(\n **self.get_init_valid_params()\n )\n\n @classmethod\n def create_model(cls, **kwargs) -> nn.Module:\n return A3CLSTMNStepComCoordinatedActionsEgoGridsEmbedCNN(\n num_inputs=9,\n action_groups=cls.episode_class.class_available_action_groups(\n include_move_obj_actions=cls.include_move_obj_actions\n ),\n num_agents=cls.num_agents,\n state_repr_length=cls.state_repr_length,\n occupancy_embed_length=8,\n talk_embed_length=cls.talk_embed_length,\n agent_num_embed_length=cls.agent_num_embed_length,\n reply_embed_length=cls.reply_embed_length,\n turn_off_communication=cls.turn_off_communication,\n coordinate_actions=cls.coordinate_actions,\n coordinate_actions_dim=13 if cls.coordinate_actions else None,\n separate_actor_weights=False,\n num_talk_symbols=cls.num_talk_symbols,\n num_reply_symbols=cls.num_reply_symbols,\n )\n\n # IF WE WANTED CENTRAL\n # return A3CLSTMCentralEgoGridsEmbedCNN(\n # num_inputs_per_agent=10,\n # action_groups=cls.episode_class.class_available_action_groups(\n # include_move_obj_actions=cls.include_move_obj_actions\n # ),\n # num_agents=cls.num_agents,\n # state_repr_length=cls.state_repr_length,\n # occupancy_embed_length=8,\n # )\n\n @classmethod\n def create_agent(cls, **kwargs) -> MultiAgent:\n return cls.agent_class(\n model=kwargs[\"model\"],\n gpu_id=kwargs[\"gpu_id\"],\n include_test_eval_results=cls.include_test_eval_results,\n use_a3c_loss_when_not_expert_forcing=cls.use_a3c_loss_when_not_expert_forcing,\n record_all_in_test=cls.record_all_in_test,\n include_depth_frame=cls.include_depth_frame,\n )\n\n @property\n def init_train_agent(self) -> Callable:\n return self._init_train_agent\n\n @property\n def init_test_agent(self) -> Callable:\n return self._init_test_agent\n\n @property\n def saved_model_path(self) -> Optional[str]:\n return None\n # return \"trained_models/furnmove_a3c_noncentral_ego_grids_ego_actions_uncoordinated_discrete_com_fast_relative_v2_pass_1000000_2019-11-02_14-28-33.dat\"\n\n\ndef get_experiment():\n return FurnMoveExperimentConfig()\n","sub_path":"rl_multi_agent/experiments/furnmove_grid_marginalnocomm_base_config.py","file_name":"furnmove_grid_marginalnocomm_base_config.py","file_ext":"py","file_size_in_byte":6228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"72991764","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author unknowcry\r\n@date 2020-4-12\r\n@desc 彩票数据\r\n@filename Lottery_data.py\r\ntips:\r\n数据来自:http://kaijiang.500.com\r\n\r\n\"\"\"\r\n\r\nimport requests\r\nimport re\r\nimport random\r\nimport datetime\r\nimport threading\r\nimport time\r\nfrom bs4 import BeautifulSoup\r\nfrom fake_useragent import UserAgent\r\nfrom concurrent.futures import ThreadPoolExecutor,as_completed\r\n\r\nclass Lottery:\r\n \"\"\"\r\n 单一网页数据获取\r\n \"\"\"\r\n no=None\r\n url=None\r\n header=None\r\n data=None\r\n data_history=None\r\n new_url=None\r\n __threadlock=None\r\n def __init__(self, no=None):\r\n '''\r\n :param no:期号\r\n '''\r\n if no == None:\r\n self.no=None\r\n else:\r\n self.no=no \r\n self.url=None\r\n self.header=None\r\n self.data=None\r\n self.data_history=None\r\n self.new_url='http://kaijiang.500.com/dlt.shtml'\r\n self.threadlock=threading.Lock()\r\n\r\n def set_header(self):\r\n \"\"\"\r\n 随机生成ip,设置X-Forwarded-For\r\n 设置用户代理\r\n :return:\r\n \"\"\"\r\n if self.header == None:\r\n ua = UserAgent()\r\n ip = '{}.{}.{}.{}'.format(112, random.randint(64, 68), random.randint(0, 255), random.randint(0, 255))\r\n self.header={\r\n \"X-Forwarded-For\": ip,\r\n \"User-Agent\":ua.random\r\n }\r\n else:\r\n pass\r\n\r\n def set_url(self):\r\n \"\"\"\r\n :return:\r\n \"\"\"\r\n self.url='http://kaijiang.500.com/shtml/dlt/{}.shtml?'.format(self.no)\r\n\r\n def get_response(self,url):\r\n \"\"\"\r\n 链接测试\r\n :return: get请求返回的response\r\n \"\"\"\r\n response = requests.get(url=url, headers=self.header)\r\n return response\r\n\r\n def get_html(self,response):\r\n \"\"\"\r\n :return: html文档\r\n \"\"\"\r\n try:\r\n r=response\r\n r.raise_for_status()\r\n charset=re.search(re.compile(r'charset=(\\w+)'),r.text).group()[8:]\r\n r.encoding=charset\r\n return r.text\r\n except Exception as err:\r\n print(err)\r\n return ''\r\n \r\n def fill_data(self, soup):\r\n \"\"\"\r\n :param soup:\r\n :return:\r\n \"\"\"\r\n try:\r\n tableinfo=soup.find('table','kj_tablelist02')\r\n response_no=re.findall(re.compile(r'(\\d+)'),str(tableinfo))[0]\r\n if int(response_no) != int(self.no):\r\n raise Exception('期号错误,响应期号{0}不匹配请求期号{1}'.format(response_no,self.no))\r\n else:\r\n date_l=re.findall(re.compile(r'(\\d+)年(\\d+)月(\\d+)日 兑奖截止日期:(\\d+)年(\\d+)月(\\d+)日'),str(tableinfo))\r\n date_start=datetime.date(int(date_l[0][0]),int(date_l[0][1]),int(date_l[0][2]))\r\n date_end=datetime.date(int(date_l[0][3]),int(date_l[0][4]),int(date_l[0][5]))\r\n nums=tuple(re.findall(re.compile(r'>(\\d\\d)<'),str(tableinfo)))\r\n money_l=re.findall(r'(\\d+(\\.\\d+)?)',str(tableinfo))\r\n sale=money_l[0][0]\r\n jackpot=money_l[1][0]\r\n self.data=tuple((response_no,nums,date_start,date_end,sale,jackpot))\r\n except Exception as err:\r\n print(err)\r\n\r\n def get_newno(self):\r\n \"\"\"\r\n :return: bool,最新期号\r\n \"\"\"\r\n self.set_header()\r\n response=self.get_response(self.new_url)\r\n if response.status_code != 200:\r\n print('error\\n',response.status_code,self.url)\r\n return False,None\r\n else:\r\n soup=BeautifulSoup(self.get_html(response),'html.parser')\r\n tableinfo=soup.find('span','iSelectBox')\r\n newno=re.findall(re.compile(r'(\\d\\d\\d\\d\\d)'),str(tableinfo))[0]\r\n return True,newno\r\n\r\n def get_nos(self):\r\n \"\"\"\r\n :return: 历史期号\r\n \"\"\"\r\n self.set_header()\r\n response=self.get_response(self.new_url)\r\n if response.status_code != 200:\r\n print('error\\n',response.status_code,self.url)\r\n else:\r\n soup=BeautifulSoup(self.get_html(response),'html.parser')\r\n tableinfo=soup.find('span','iSelectBox')\r\n nos=re.findall(re.compile(r'(\\d\\d\\d\\d\\d)'),str(tableinfo))\r\n return nos[1:]\r\n\r\n def data_single(self,no=None):\r\n \"\"\"\r\n :return: bool,no期数据\r\n \"\"\"\r\n if no == None:\r\n pass\r\n else:\r\n self.no=no\r\n self.set_header()\r\n self.set_url()\r\n response=self.get_response(self.url)\r\n if response.status_code != 200:\r\n print('error\\n',response.status_code,self.url)\r\n return False,None\r\n else:\r\n soup=BeautifulSoup(self.get_html(response),'html.parser')\r\n self.fill_data(soup)\r\n return True,self.data\r\n\r\n \r\nclass Lottery_multi:\r\n \"\"\"\r\n 多网页数据获取\r\n \"\"\"\r\n number=None\r\n data=None\r\n __threadlock=None\r\n max_workers=None\r\n nos=None\r\n renos=None\r\n list=None\r\n def __init__(self,number=None,max_workers=8):\r\n \"\"\"\r\n :param number: 数量\r\n :param max_workers=5:默认线程数\r\n \"\"\"\r\n self.number=number\r\n self.data=set()\r\n self.threadlock=threading.Lock()\r\n self.max_workers=max_workers\r\n self.nos=Lottery().get_nos()\r\n if number != None:\r\n self.nos=self.nos[:number]\r\n self.renos=None\r\n self.list=None\r\n\r\n def thread_onedata(self,no):\r\n \"\"\"\r\n :param no: 期号\r\n :return: 期号,bool\r\n \"\"\"\r\n a=Lottery()\r\n data=a.data_single(no)[1]\r\n if data == None:\r\n flag=False\r\n else:\r\n flag=True\r\n self.threadlock.acquire()\r\n self.data.add(data)\r\n self.threadlock.release()\r\n return no,flag\r\n\r\n def data_multi(self,number=None):\r\n \"\"\"\r\n :return: 历史数据\r\n \"\"\"\r\n self.data.clear()\r\n nos=self.nos\r\n with ThreadPoolExecutor(max_workers=self.max_workers) as t:\r\n obj_list=[]\r\n for i in nos:\r\n obj=t.submit(self.thread_onedata,i)\r\n obj_list.append(obj)\r\n for future in as_completed(obj_list):\r\n no,flag=future.result()\r\n if flag:\r\n print('thread',no,'done')\r\n else:\r\n print('thread',no,'failed')\r\n self.check()\r\n return self.data\r\n\r\n def check_no(self,number=None):\r\n \"\"\"\r\n :param number: 期数量\r\n :return: 未匹配期号列\r\n \"\"\"\r\n nos=self.nos\r\n if number != None:\r\n nos=nos[:number]\r\n for data in self.data:\r\n i=data[0]\r\n nos.remove(i)\r\n self.renos=nos\r\n print('check_no done')\r\n return nos\r\n\r\n def adddata(self):\r\n with ThreadPoolExecutor(max_workers=self.max_workers) as t:\r\n obj_list=[]\r\n for i in self.renos:\r\n print('thread',i,'restart')\r\n obj=t.submit(self.thread_onedata,i)\r\n obj_list.append(obj)\r\n for future in as_completed(obj_list):\r\n no,flag=future.result()\r\n if flag:\r\n print('thread',no,'done')\r\n else:\r\n print('thread',no,'failed')\r\n print('adddata done')\r\n\r\n def check(self):\r\n self.check_no(self.number)\r\n if len(self.renos)==0:\r\n print('no done')\r\n return True\r\n else:\r\n print('no',self.renos)\r\n self.adddata()\r\n self.check_no(self.number)\r\n if len(self.renos)==0:\r\n return True\r\n else:\r\n return False\r\n\r\n def get_list(self):\r\n \"\"\"\r\n :return: 数据以顺序列表返回\r\n \"\"\"\r\n self.list=list(self.data)\r\n self.list.sort(key=lambda x: x[0],reverse=True) \r\n return self.list\r\n\r\nif __name__ == \"__main__\":\r\n time_start=time.time()\r\n l=Lottery_multi(number=10,max_workers=5)\r\n l.data_multi()\r\n data=l.get_list()\r\n data.sort(key=lambda x: x[0],reverse=True)\r\n time_end=time.time()\r\n for i in range(len(data)):\r\n print(i+1,data[i])\r\n print('time',time_end-time_start)\r\n","sub_path":"Lottery_data.py","file_name":"Lottery_data.py","file_ext":"py","file_size_in_byte":8568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"42031846","text":"import time \nimport os\n\n\ndef run_safe(func):\n def _wrapper(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except KeyboardInterrupt:\n raise KeyboardInterrupt\n except Exception as e:\n print('run safe: ' + str(e))\n return ''\n return _wrapper\n \n# append new lib path\n# import sys\n# import os\n# o_path = os.getcwd()\n# last_dir = '\\\\'.join(o_path.split('\\\\')[:-2])\n# sys.path.append(last_dir)\n\ndef add_path(path):\n cur_path = os.getcwd()\n if path[:4] == \"last\":\n level = path.split(\"-\")[1]\n append_path = '\\\\'.join(o_path.split('\\\\')[:-level])\n else:\n append_path = path\n\n print(\"cur path:\", cur_path)\n print(\"new path:\", append_path)\n\n sys.path.append(append_path)\n\n\ndef wait_max_time(max_time_ms, conditions, tick = None):\n if type(conditions) != \"list\" and \\\n type(conditions) != \"tuple\":\n conditions = [conditions]\n\n start = time.time()\n while time.time() - start < (max_time_ms / 1000):\n for item in conditions:\n if callable(item):\n if item():\n break\n else:\n if item:\n break\n\n if tick:\n time.sleep(tick)\n\n# check the range of number\ndef num_range_check(num, min_n = None, max_n = None, to_range = True):\n if min_n == None and max_n == None:\n return num\n \n if min_n != None:\n if to_range and num < min_n:\n num = min_n\n\n if max_n != None:\n if to_range and num > max_n:\n num = max_n\n return num\n\n# old definition\nnum_range_scale = num_range_check\n\n# bytes switch\ndef float_to_byte_4(data): \n float_bytes = pack('f', data)\n return bytearray(float_bytes)\n\ndef int_to_byte_4(data):\n if type(data) == float:\n data = int(data)\n int_bytes = data.to_bytes(4, \"little\")\n return bytearray(int_bytes)\n\ndef int_to_byte_2(data):\n if type(data) == float:\n data = int(data)\n int_bytes = data.to_bytes(2, \"little\")\n return bytearray(int_bytes)\n\ndef byte_2_to_short(data):\n if len(data) != 2:\n return None\n result = unpack('h', bytearray(data))\n result = result[0]\n return bytearray(result)\n\ndef byte_4_to_float(data): \n float_bytes = unpack('f', bytearray(data))\n result = result[0]\n return bytearray(result)\n\ndef byte_4_to_int(data):\n if len(data) != 4:\n return None\n result = unpack('l', bytearray(data))\n result = result[0]\n return bytearray(result)\n\n","sub_path":"build/lib/mkPython/utils/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":2536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"260102210","text":"from django.shortcuts import render,redirect,get_object_or_404,get_list_or_404\r\nfrom radio.models import Radioitem,City,Country, Style,Comment\r\nfrom django.views.generic import list,base\r\nfrom radio.forms import CommentForm\r\nfrom django.contrib.auth.decorators import login_required\r\n\r\n\r\nclass index(list.ListView):\r\n \"\"\"\r\n Выводит список всех радиостанций на главную страницу сайта\r\n \"\"\"\r\n template_name = 'index.html'\r\n model = Radioitem\r\n paginate_by = 4\r\n\r\n def get_context_data(self,**kwargs):\r\n context= super(index,self).get_context_data(**kwargs)\r\n context['title'] = 'Radio FM - Лучшее в онлайне'\r\n return context\r\n\r\n\r\ndef like(request,likeid=None):\r\n \"\"\"\r\n Ставик лайк радиостанции\r\n :param likeid: id радиостанции\r\n \"\"\"\r\n object = get_object_or_404(Radioitem,id=likeid)\r\n object.radio_likes += 1\r\n object.save()\r\n return redirect(str(object.get_absolute_url()))\r\n\r\n\r\ndef search_city(request,cityid=None):\r\n \"\"\"\r\n Производит поиск радиостанции по городу и выводит на главную страницу\r\n :param cityid: id города\r\n \"\"\"\r\n object = get_list_or_404(Radioitem,radio_city__id=cityid)\r\n title = 'Все радиостанции города: %s' %City.objects.get(id=cityid) #Сохраняет название города\r\n return render(request,'index.html',{'object_list':object, 'title':title})\r\n\r\ndef search_country(request,countryid=None):\r\n \"\"\"\r\n Производит поиск радиостанции по стране и выводит на главную страницу\r\n :param countryid: id страны\r\n \"\"\"\r\n object = get_list_or_404(Radioitem,radio_city__country__id=countryid)\r\n title = 'Все радиостанции страны: %s' %Country.objects.get(id=countryid)#Сохраняет название страны\r\n return render(request,'index.html',{'object_list':object,'title':title})\r\n\r\ndef search_style(request,styleid):\r\n \"\"\"\r\n Производит поиск по стилю радиостанций\r\n :param styleid: id стиля музыки\r\n \"\"\"\r\n print(styleid)\r\n object = get_list_or_404(Radioitem, radio_style__id=styleid)\r\n title = 'Все радиостанции со стилем музыки: %s' %Style.objects.get(id=styleid) #Сохраняет название стиля\r\n return render(request,'index.html',{'object_list':object,'title':title})\r\n\r\n\r\nclass viewradio(base.TemplateView):\r\n \"\"\"\r\n Выводит выбранную радиостанцию\r\n \"\"\"\r\n template_name = 'radioview.html'\r\n form = None\r\n\r\n def get(self,request,*args,**kwargs):\r\n try:\r\n self.radioid = self.kwargs['radioid']\r\n object = Radioitem.objects.get(pk=self.radioid)\r\n object.radio_view += 1\r\n object.save()\r\n self.form = CommentForm()\r\n except:\r\n return redirect('index')\r\n return super(viewradio,self).get(request,*args,**kwargs)\r\n\r\n def get_context_data(self, **kwargs):\r\n context = super(viewradio,self).get_context_data(**kwargs)\r\n context['radioitem'] = Radioitem.objects.get(id=self.radioid)\r\n context['title'] = context['radioitem'].radio_name\r\n context['comment_form'] = self.form\r\n return context\r\n\r\n def post(self,request,*args,**kwargs):\r\n self.radioid = self.kwargs['radioid']\r\n object = Radioitem.objects.get(pk=self.radioid)\r\n self.form = CommentForm(request.POST)\r\n if self.form.is_valid():\r\n new_comment = self.form.save(commit=False)\r\n new_comment.radiostation = object\r\n new_comment.author = request.user\r\n new_comment.email = request.user.email\r\n new_comment.save()\r\n return redirect(object)\r\n return super(viewradio,self).get(request,*args,**kwargs)\r\n\r\n def get_queryset(self):\r\n return Radioitem.objects.get(id=self.radioid)\r\n\r\ndef index2(request):\r\n \"\"\"\r\n Тестовая функиця, просто что то тестить\r\n :param request:\r\n :return:\r\n \"\"\"\r\n object = get_list_or_404(Radioitem,radio_error=True)\r\n return render(request,'index22.html',{'object_list':object})\r\n\r\ndef error(request,radioid=None):\r\n \"\"\"\r\n Сообщает о проблемы с отображением радиостанции\r\n :param radioid: id радиостанции\r\n \"\"\"\r\n object = get_object_or_404(Radioitem, id=radioid)\r\n if not object.radio_error:\r\n object.radio_error = True\r\n object.save()\r\n return redirect(str(object.get_absolute_url()))\r\n\r\n@login_required\r\ndef delete_comment(request,id):\r\n object = get_object_or_404(Comment, id=id)\r\n if request.user.username == object.author:\r\n object.delete()\r\n return redirect(object)\r\n else:\r\n return redirect(object)","sub_path":"radio/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"176345883","text":"#!/usr/bin/env python3\n\nimport argparse\nimport math\nimport numpy as np\nimport pandas as pd\nimport os\nimport sklearn.model_selection\nimport sklearn.preprocessing\nimport sys\nimport tensorflow as tf\n\nimport generator\nimport utils\nfrom target_models import Target_A as target_model\n\n\n\ndef get_class_mean(x, y, k):\n\treturn x[np.argmax(y, axis=1) == k].mean(axis=0)\n\n\n\ndef perturb_mean_diff(x, y, target, classes):\n\tperturbations = []\n\n\tfor k in range(len(classes)):\n\t\t# get mean of source and target class\n\t\tmu_source = get_class_mean(x, y, k)\n\t\tmu_target = get_class_mean(x, y, target)\n\n\t\t# compute difference between source and target mean\n\t\tperturbations.append(mu_target - mu_source)\n\n\treturn np.vstack(perturbations).T\n\n\n\ndef perturb_advgan(x, y, target=-1, batch_size=32, output_dir=\".\"):\n\tx_pl = tf.placeholder(tf.float32, [None, x.shape[-1]])\n\ty_pl = tf.placeholder(tf.float32, [None, y.shape[-1]])\n\tis_training = tf.placeholder(tf.bool, [])\n\tis_training_target = tf.placeholder(tf.bool, [])\n\n\tif target != -1:\n\t\tis_targeted = True\n\telse:\n\t\tis_targeted = False\n\n\t# generate pertubation, add to original, clip to valid expression level\n\tperturb, logit_perturb = generator.generator(x_pl, is_training)\n\tx_perturbed = perturb + x_pl\n\tx_perturbed = tf.clip_by_value(x_perturbed, 0, 1)\n\n\t# instantiate target model, create graphs for original and perturbed data\n\tf = target_model(n_input=x.shape[-1], n_classes=y.shape[-1])\n\tf_real_logits, f_real_probs = f.Model(x_pl, is_training_target)\n\tf_fake_logits, f_fake_probs = f.Model(x_perturbed, is_training_target)\n\n\t# get variables\n\tt_vars = tf.trainable_variables()\n\tf_vars = [var for var in t_vars if \"Model_A\" in var.name]\n\tg_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=\"generator\")\n\n\tsess = tf.Session()\n\n\t# load checkpoints\n\tf_saver = tf.train.Saver(f_vars)\n\tg_saver = tf.train.Saver(g_vars)\n\tf_saver.restore(sess, tf.train.latest_checkpoint(\"%s/target_model/\" % (output_dir)))\n\tg_saver.restore(sess, tf.train.latest_checkpoint(\"%s/generator/\" % (output_dir)))\n\n\t# calculate accuracy of target model on perturbed data\n\tcorrect_prediction = tf.equal(tf.argmax(f_fake_probs, 1), tf.argmax(y_pl, 1))\n\taccuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\n\n\t# generate perturbed samples from original samples\n\tn_batches = math.ceil(len(x) / batch_size)\n\tscores = []\n\tperturbations = []\n\n\tfor i in range(n_batches):\n\t\tbatch_x, batch_y = utils.next_batch(x, y, batch_size, i)\n\n\t\tif is_targeted:\n\t\t\ttargets = np.full((batch_y.shape[0],), target)\n\t\t\tbatch_y_pert = np.eye(y_pl.shape[-1])[targets]\n\n\t\tscore, _, batch_x_pert, batch_p = sess.run([accuracy, f_fake_probs, x_perturbed, perturb], feed_dict={\n\t\t\tx_pl: batch_x,\n\t\t\ty_pl: batch_y_pert,\n\t\t\tis_training: False,\n\t\t\tis_training_target: False\n\t\t})\n\t\tscores.append(score)\n\t\tperturbations.append(batch_p)\n\n\tprint(\"perturbation accuracy: %0.3f\" % (sum(scores) / len(scores)))\n\n\t# return matrix of perturbed samples\n\treturn np.vstack(perturbations).T\n\n\n\nif __name__ == \"__main__\":\n\t# parse command-line arguments\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\"--train-data\", help=\"training data (samples x genes)\", required=True)\n\tparser.add_argument(\"--train-labels\", help=\"training labels\", required=True)\n\tparser.add_argument(\"--test-data\", help=\"test data (samples x genes)\", required=True)\n\tparser.add_argument(\"--test-labels\", help=\"test labels\", required=True)\n\tparser.add_argument(\"--gene-sets\", help=\"list of curated gene sets\")\n\tparser.add_argument(\"--set\", help=\"specific gene set to run\")\n\tparser.add_argument(\"--target\", help=\"target class\")\n\tparser.add_argument(\"--output-dir\", help=\"Output directory\", default=\".\")\n\n\targs = parser.parse_args()\n\n\t# load input data\n\tprint(\"loading train/test data...\")\n\n\tdf_train = utils.load_dataframe(args.train_data)\n\tdf_test = utils.load_dataframe(args.test_data)\n\n\ty_train, classes = utils.load_labels(args.train_labels)\n\ty_test, _ = utils.load_labels(args.test_labels, classes)\n\n\tprint(\"loaded train data (%s genes, %s samples)\" % (df_train.shape[1], df_train.shape[0]))\n\tprint(\"loaded test data (%s genes, %s samples)\" % (df_test.shape[1], df_test.shape[0]))\n\n\t# impute missing values\n\tmin_value = df_train.min().min()\n\n\tdf_train.fillna(value=min_value, inplace=True)\n\tdf_test.fillna(value=min_value, inplace=True)\n\n\t# sanitize class names\n\tclasses = [utils.sanitize(c) for c in classes]\n\n\t# determine target class\n\ttry:\n\t\tif args.target == None:\n\t\t\targs.target = -1\n\t\telse:\n\t\t\targs.target = classes.index(args.target)\n\t\t\tprint(\"target class is: %s\" % (classes[args.target]))\n\texcept ValueError:\n\t\tprint(\"error: class %s not found in dataset\" % (args.target))\n\t\tsys.exit(1)\n\n\t# load gene sets file if it was provided\n\tif args.gene_sets != None:\n\t\tprint(\"loading gene sets...\")\n\n\t\tgene_sets = utils.load_gene_sets(args.gene_sets)\n\t\tgene_sets = utils.filter_gene_sets(gene_sets, df_test.columns)\n\n\t\tprint(\"loaded %d gene sets\" % (len(gene_sets)))\n\telse:\n\t\tgene_sets = {\"all_genes\": df_test.columns}\n\n\t# select gene set\n\ttry:\n\t\tname = args.set\n\t\tgenes = gene_sets[name]\n\texcept:\n\t\tprint(\"gene set is not the subset file provided\")\n\t\tsys.exit(1)\n\n\t# extract train/test data\n\tx_train = df_train[genes]\n\tx_test = df_test[genes]\n\n\ty_train = utils.onehot_encode(y_train, classes)\n\ty_test = utils.onehot_encode(y_test, classes)\n\n\t# normalize test data (using the train data)\n\tscaler = sklearn.preprocessing.MinMaxScaler()\n\tscaler.fit(x_train)\n\n\tx_train = scaler.transform(x_train)\n\tx_test = scaler.transform(x_test)\n\n\t# perturb each class mean to the target class\n\tmu_pert = perturb_mean_diff(x_test, y_test, args.target, classes)\n\n\t# save mean peturbations to dataframe\n\tdf_pert = pd.DataFrame(\n\t\tdata=mu_pert,\n\t\tindex=genes,\n\t\tcolumns=classes\n\t)\n\n\tutils.save_dataframe(\"%s/%s.perturbations.means.txt\" % (args.output_dir, classes[args.target]), df_pert)\n\n\t# perturb all samples to target class\n\tperturbations = perturb_advgan(x_test, y_test, args.target, output_dir=args.output_dir)\n\n\t# save sample perturbations to dataframe\n\tdf_pert = pd.DataFrame(\n\t\tdata=perturbations,\n\t\tindex=genes,\n\t\tcolumns=df_test.index\n\t)\n\n\tutils.save_dataframe(\"%s/%s.perturbations.samples.txt\" % (args.output_dir, classes[args.target]), df_pert)\n","sub_path":"bin/perturb.py","file_name":"perturb.py","file_ext":"py","file_size_in_byte":6200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"367920143","text":"from ROOT import *\n\n#dimension\ndim = 'x'\n\n#open input file\ninfilep = TFile('../templates_highmass_powheg_aux.root')\n\n#channel names to sum over\nchannels = ['muplus','muminus','elplus','elminus']\n\n#lists of systematics names and colors\n#systematics = [('pileup_weight',kMagenta),('top_pT_weight',kRed),('lep_ID_weight',kBlue),('trig_eff_weight',kGreen),('luminosity',kOrange+3)]\n#systematics_names = ['Pileup Weight','Top p_{T} Weight','Lepton ID Weight','Trigger Efficiency Weight','Luminosity']\nsystematics = [('fit',kRed)]\nsystematics_names = ['Conv. func. fit']\n#list of histograms\nhists = []\n#one list for each of the qq, gg, bck, and NTMJ\nfor i in range(4) :\n\thists.append([])\n#get the nominal templates\nhists[0].append(infilep.Get(channels[0]+'__fqq_'+dim))\nhists[1].append(infilep.Get(channels[0]+'__fgg_'+dim))\nhists[2].append(infilep.Get(channels[0]+'__fbck_'+dim))\nhists[3].append(infilep.Get(channels[0]+'__fntmj_'+dim))\n#add from all the channels\nfor i in range(1,len(channels)) :\n\thists[0][0].Add(infilep.Get(channels[i]+'__fqq_'+dim).Clone())\n\thists[1][0].Add(infilep.Get(channels[i]+'__fgg_'+dim).Clone())\n\thists[2][0].Add(infilep.Get(channels[i]+'__fbck_'+dim).Clone())\n\thists[3][0].Add(infilep.Get(channels[i]+'__fntmj_'+dim).Clone())\n#Get the systematics up/down templates\nfor i in range(len(systematics)) :\n\thists[0].append(infilep.Get(channels[0]+'__fqq__'+systematics[i][0]+'__up_'+dim))\n\thists[0].append(infilep.Get(channels[0]+'__fqq__'+systematics[i][0]+'__down_'+dim))\n\thists[1].append(infilep.Get(channels[0]+'__fgg__'+systematics[i][0]+'__up_'+dim))\n\thists[1].append(infilep.Get(channels[0]+'__fgg__'+systematics[i][0]+'__down_'+dim))\n\thists[2].append(infilep.Get(channels[0]+'__fbck__'+systematics[i][0]+'__up_'+dim))\n\thists[2].append(infilep.Get(channels[0]+'__fbck__'+systematics[i][0]+'__down_'+dim))\n\thists[3].append(infilep.Get(channels[0]+'__fntmj__'+systematics[i][0]+'__up_'+dim))\n\thists[3].append(infilep.Get(channels[0]+'__fntmj__'+systematics[i][0]+'__down_'+dim))\n\t#Add from the rest of the channels\n\tfor j in range(1,len(channels)) :\n#\t\thists[0][2*i+1].Add(infilep.Get(channels[j]+'__fqq__'+systematics[i][0]+'__up_'+dim).Clone()) #UNCOMMENT THIS\n#\t\thists[0][2*i+2].Add(infilep.Get(channels[j]+'__fqq__'+systematics[i][0]+'__down_'+dim).Clone()) #UNCOMMENT THIS\n#\t\thists[1][2*i+1].Add(infilep.Get(channels[j]+'__fgg__'+systematics[i][0]+'__up_'+dim).Clone()) #UNCOMMENT THIS\n#\t\thists[1][2*i+2].Add(infilep.Get(channels[j]+'__fgg__'+systematics[i][0]+'__down_'+dim).Clone()) #UNCOMMENT THIS\n#\t\thists[2][2*i+1].Add(infilep.Get(channels[j]+'__fbck__'+systematics[i][0]+'__up_'+dim).Clone()) #UNCOMMENT THIS\n#\t\thists[2][2*i+2].Add(infilep.Get(channels[j]+'__fbck__'+systematics[i][0]+'__down_'+dim).Clone()) #UNCOMMENT THIS\n\t\thists[3][2*i+1].Add(infilep.Get(channels[j]+'__fntmj__'+systematics[i][0]+'__up_'+dim).Clone())\n\t\thists[3][2*i+2].Add(infilep.Get(channels[j]+'__fntmj__'+systematics[i][0]+'__down_'+dim).Clone())\n\n#open the output file\noutfilep = TFile('template_comparison_plots_systematics_'+dim+'.root','recreate')\n\n#Set histogram attributes\nfor i in range(len(hists)) :\n\tif i!=3 : #GET RID OF THIS\n\t\tcontinue #GET RID OF THIS\n\thists[i][0].SetMarkerStyle(25); hists[i][0].SetLineWidth(4); hists[i][0].SetLineColor(kBlack)\n\tfor j in range(1,len(hists[i])) :\n\t\thists[i][j].SetMarkerStyle(25); hists[i][j].SetLineWidth(4); hists[i][j].SetLineColor(systematics[(j-1)/2][1])\n\t\tif (j-1)%2 == 0 :\n\t\t\thists[i][j].SetLineStyle(7)\n\t\telse :\n\t\t\thists[i][j].SetLineStyle(3)\nprojtype = 'c*'\nif dim == 'y' :\n\tprojtype = '|x_{F}|'\nif dim == 'z' :\n\tprojtype = 'M'\nhists[0][0].SetTitle('Systematic variations in q#bar{q} template, '+projtype+' projection; '+projtype+'; Events')\nhists[1][0].SetTitle('Systematic variations in gg template, '+projtype+' projection; '+projtype+'; Events')\nhists[2][0].SetTitle('Systematic variations in simulated background template, '+projtype+' projection; '+projtype+'; Events')\nhists[3][0].SetTitle('Systematic variations in data-driven NTMJ background template, '+projtype+' projection; '+projtype+'; Events')\n\n#make a legend\nleg = TLegend(0.62,0.67,0.9,0.9)\nleg.AddEntry(hists[0][0],'Nominal Template','L')\nfor i in range(len(systematics)) :\n\tleg.AddEntry(hists[3][2*i+1],systematics_names[i]+' Up','L') #CHANGE BACK TO ZERO\n\tleg.AddEntry(hists[3][2*i+2],systematics_names[i]+' Down','L') #CHANGE BACK TO ZERO\n\n#canvases\ncanvs = [TCanvas('qq_canv','qq_canv',1100,900),TCanvas('gg_canv','gg_canv',1100,900),TCanvas('bck_canv','bck_canv',1100,900),TCanvas('ntmj_canv','ntmj_canv',1100,900)]\n\n#plot plots\nfor i in range(len(hists)) :\n\tif i!=3 : #GET RID OF THIS\n\t\tcontinue #GET RID OF THIS\n\tcanvs[i].cd()\n\thists[i][0].Draw('HIST')\n\tfor j in range(len(systematics)) :\n\t\thists[i][2*j+1].Draw('SAME HIST')\n\t\thists[i][2*j+2].Draw('SAME HIST')\n\tleg.Draw()\n\n#save canvases\noutfilep.cd()\nfor canv in canvs :\n\tcanv.Write()\n\n","sub_path":"Template_Maker/test/template_comparison_plots_systematics.py","file_name":"template_comparison_plots_systematics.py","file_ext":"py","file_size_in_byte":4881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"466129941","text":"import numpy as np\nfrom descartes import crops_list\n\ncrops_enc = {id_: k + 1 for k, id_ in enumerate(sorted(crops_list))}\ncrops_dec = {crops_enc[id_]: id_ for id_ in crops_enc}\n\n\ndef get_monthly_arrays(data: np.ndarray, info: list, time_steps=12) -> np.ndarray:\n \"\"\"Average imagery arrays by month to return a 4D tensor with 12 time steps.\n Default Descatres temporal imagery is of shape: (time_steps, bands, height, width)\n Need to also permute axes to the Tensorflow standard: (time_steps, height, width, bands)\"\"\"\n years = sorted(list(set([x['group'][0] for x in info])))\n months = sorted(list(set([x['group'][1] for x in info])))\n dates_ = list(zip(np.arange(data.shape[0], dtype=int), [x['group'] for x in info]))\n date_ranges = {(x, y): [] for x in years for y in range(1, 13)}\n for d in dates_:\n date_ranges[d[1][:2]].append(d[0])\n avg_array = np.zeros((time_steps * len(years), data.shape[1], data.shape[2], data.shape[3]))\n for k, dr in enumerate(sorted([(x, y) for x in years for y in months])):\n if date_ranges[dr]:\n avg_array[k] = data[date_ranges[dr][0]:date_ranges[dr][-1] + 1].mean(axis=0)\n return avg_array.transpose((0, 2, 3, 1))\n\n\ndef mask_crop_layer(cdl: np.ndarray, nclasses: int) -> np.ndarray:\n cdl = np.array(cdl[0, 0])\n y = np.zeros((cdl.shape[0], cdl.shape[1], nclasses), dtype='int32')\n y[:, :, 0] = np.asanyarray(~np.isin(cdl, list(crops_enc)), dtype='int32')\n for k in crops_dec:\n y[:, :, k] = np.asanyarray(cdl == crops_dec[k], dtype='int32')\n return y\n","sub_path":"descartes/process_images.py","file_name":"process_images.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"569221828","text":"import heapq\r\n\r\ndef _retrace_path(came_from, c):\r\n path = [c]\r\n while c in came_from:\r\n c = came_from[c]\r\n path.append(c)\r\n path.reverse()\r\n return path\r\n\r\ndef shortest_path(start_set, goal_set, neighbours, heuristic, node_cost):\r\n closed_set = set()\r\n open_set = start_set\r\n came_from = {}\r\n\r\n g_dict = dict((node, node_cost(node)) for node in open_set)\r\n h_dict = dict((node, heuristic(node)) for node in open_set)\r\n f_dict = dict((node, g_dict[node] + h_dict[node]) for node in open_set)\r\n \r\n open_heap = [(g_dict[node], node) for node in open_set]\r\n heapq.heapify(open_heap)\r\n \r\n while open_set:\r\n current_f, current = heapq.heappop(open_heap)\r\n \r\n if current in goal_set:\r\n return _retrace_path(came_from, current)\r\n \r\n open_set.remove(current)\r\n closed_set.add(current)\r\n \r\n for neighbour in neighbours(current):\r\n if neighbour in closed_set:\r\n continue\r\n \r\n tentative_g = g_dict[current] + node_cost(neighbour)\r\n \r\n if neighbour not in open_set or tentative_g <= g_dict[neighbour]:\r\n came_from[neighbour] = current\r\n old_f = f_dict.get(neighbour)\r\n g_dict[neighbour] = tentative_g\r\n f_dict[neighbour] = g_dict[neighbour] + heuristic(neighbour)\r\n if neighbour in open_set:\r\n index = open_heap.index((old_f, neighbour))\r\n open_heap[index] = (f_dict[neighbour], neighbour)\r\n heapq.heapify(open_heap)\r\n else:\r\n open_set.append(neighbour)\r\n heapq.heappush(open_heap, (f_dict[neighbour], neighbour))\r\n \r\n return []","sub_path":"astar.py","file_name":"astar.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"568220932","text":"#! python3\n\n# Solve a two step algebra equation.\n# Two steps equations are in the format ax + b = c\n# You will ask the user to enter in all 3 variables: a, b and c\n# You will need to display the solution for the equation\n# hi\n# inputs\n# a, b, c\n#\n# outputs\n# solution for x\n#\n# test case: 5, 1, 11 should give x = 2\n\na = int(input(\"enter a\\n\"))\nb = int(input(\"enter b\\n\"))\nc = int(input(\"enter c\\n\"))\nx = (c - b) / a\nprint(x)","sub_path":"task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"61221443","text":"\"\"\"\nBasic implementation of reading file into list on a line-by-line basis\n\n@author Mark Diedericks 30572738\n@since 18/09/2019\n@modified 18/09/2019\n\"\"\"\n\nimport task2\n\ndef read_text_file(name):\n \"\"\"\n Set the element in the list at index\n\n @param None\n @return None\n @complexity O(1) for both best and worst case\n @precondition The index is within then list bounds; -self.length <= index <= self.length-1\n @exception Index is out of bounds \n @postcondition The element located at the index will be item\n \"\"\"\n \n # Instantiate a list for the lines\n line_list = task2.ListADT()\n\n # Open the file, read each line and append to the line_list\n with open(name) as f:\n for line in f:\n line_list.append(line)\n\n # Ensure file is closed\n if not f.closed:\n raise IOError('File is not closed.')\n\n # Return the list of lines\n return line_list\n\n","sub_path":"Submission/task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"117382556","text":"import argparse\nimport json\nfrom pp_ocr import file_utils, imgproc\nfrom pp_ocr.text_engine import TextEngine\nfrom flask import Flask, request, jsonify\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport base64\nfrom io import BytesIO\nfrom PIL import Image\n\n\ndef create_app():\n app = Flask(__name__)\n # app.config['folder'] = folder\n # app.config['p'] = p\n return app\n\ndef start_engine():\n # start engine\n text_engine = TextEngine(cuda=True)\n return text_engine\n\ndef proc(batch_of_images, text_engine):\n cropped_images_of_text = text_engine.detect_and_recognize_text(batch_of_images, padding=0.0, show_time=False,\n show_images=False,\n text_confidence_threshold=0.7)\n\n for item in cropped_images_of_text:\n to_print = list(item)\n points = to_print[2][1]\n xs, ys = [item[0] for item in points], [item[1] for item in points]\n l, t, r, b = int(min(xs)), int(min(ys)), int(max(xs)), int(max(ys))\n print('results:',to_print[2][0].shape, [l,t,r,b], to_print[2][2])\n\n\"\"\" Read images from folder \"\"\"\n# parser = argparse.ArgumentParser()\n# parser.add_argument('--test_folder', default='/media/dh/New Volume/Datasets/Projects/pp/ocr',\n# type=str, help='folder path to input images')\n# parser.add_argument(\"-p\", \"--padding\", type=float, default=0.1,\n# help=\"amount of padding to add to each border of ROI by scaling factor\")\n# args = parser.parse_args()\n# folder = args.test_folder\n# p = args.padding\ntext_engine = start_engine()\n# app = create_app(folder, p)\napp = create_app()\n\n@app.route('/test')\ndef test():\n return \"Hello World!\"\n\n@app.route(\"/\", methods=['POST'])\ndef index1(text_engine=text_engine):\n print('start')\n # if request.method == 'GET':\n # return request.get_json()\n img_batch = []\n decode = base64.urlsafe_b64decode(json.loads(request.get_data())['instances'][0])\n buffer = BytesIO(decode)\n img = Image.open(buffer)\n req_data = np.array(img).astype(np.uint8)\n print(req_data)\n if len(req_data.shape) > 3:\n for img in req_data:\n img_batch.append(np.transpose(img, (1,0,2)))\n # print(img.shape)\n else:\n img_batch.append(np.transpose(req_data, (1,0,2)))\n # print(img_batch[0].shape)\n cropped_images_of_text = text_engine.detect_and_recognize_text(img_batch, padding=0.0, show_time=False,\n show_images=False,\n text_confidence_threshold=0.7)\n results = {\n 'predictions': []\n }\n try:\n for obj in cropped_images_of_text: # cropped_images_of_text is one zip file\n for image, points, text in obj:\n xs, ys = [item[0] for item in points], [item[1] for item in points]\n l, t, r, b = int(min(xs)), int(min(ys)), int(max(xs)), int(max(ys))\n # print('results:',to_print[2][0].shape, [l,t,r,b], to_print[2][2])\n temp = {\n 'points': [l,t,r,b],\n 'attributes-value': text\n }\n results['predictions'].append(temp)\n except:\n print('No text')\n print('end')\n # print('Finished!', len(results))\n return jsonify(results)\n\n@app.route(\"/recognize\", methods=['POST'])\ndef index2(text_engine=text_engine):\n print('start')\n # if request.method == 'GET':\n # return request.get_json()\n img_batch = []\n decode = base64.urlsafe_b64decode(json.loads(request.get_data())['instances'][0])\n buffer = BytesIO(decode)\n img = Image.open(buffer)\n req_data = np.array(img).astype(np.uint8)\n print(req_data)\n if len(req_data.shape) > 3:\n for img in req_data:\n # print(np.transpose(img, (1,0,2)).shape)\n # img_batch.append(np.transpose(img, (1,0,2)))\n img_batch.append(np.array(img))\n # print(img.shape)\n else:\n # print(np.transpose(img, (1,0,2)).shape)\n # img_batch.append(np.transpose(req_data, (1,0,2)))\n img_batch.append(np.array(img))\n # print(img_batch[0].shape)\n\n print(np.array(img_batch).shape)\n text = text_engine.recognize_text(text_engine.images_to_tensors(img_batch))\n # cropped_images_of_text = text_engine.detect_and_recognize_text(img_batch, padding=0.0, show_time=False,\n # show_images=False,\n # text_confidence_threshold=0.7)\n results = {\n 'predictions': []\n }\n try:\n temp = {\n 'attributes-value': text\n }\n results['predictions'].append(temp)\n except:\n print('No text')\n print('end')\n # print('Finished!', len(results))\n return jsonify(results)\n\napp.run(debug=True, host='0.0.0.0', port=5000)\n# image_list, _, _ = file_utils.get_files(folder)\n\n\n# if __name__ == '__main__':\n \n # # load data from directory\n # batch_of_images = []\n # for k, image_path in enumerate(image_list):\n # # print(\"Test image {:d}/{:d}: {:s}\".format(k + 1,\n # # len(image_list), image_path))\n # # (batch_size, width, height, channel)\n # batch_of_images.append(imgproc.loadImage(image_path))\n \n \n # proc(batch_of_images, text_engine)\n \n \n\n # print(list(cropped_images_of_text))\n # print(len(list(cropped_images_of_text)))\n\n\n","sub_path":"test_v2.py","file_name":"test_v2.py","file_ext":"py","file_size_in_byte":5648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"298366929","text":"import pygame\n\n\nif pygame.get_sdl_version()[0] < 2:\n raise SystemExit('This example requires pygame 2 and SDL2.')\n\nimport os\ndata_dir = os.path.join(os.path.split(os.path.abspath(__file__))[0],\n 'data')\n\nfrom pygame._sdl2 import (\n Window,\n Texture,\n Renderer,\n get_drivers,\n messagebox,\n)\n\ndef load_img(file):\n return pygame.image.load(os.path.join(data_dir, file))\n\npygame.display.init()\npygame.key.set_repeat(1000, 10)\n\nfor driver in get_drivers():\n print(driver)\n\nimport random\nanswer = messagebox(\"I will open two windows! Continue?\", \"Hello!\", info=True,\n buttons=('Yes', 'No', 'Chance'),\n return_button=0, escape_button=1)\nif answer == 1 or (answer == 2 and random.random() < .5):\n import sys\n sys.exit(0)\n\nwin = Window('asdf', resizable=True)\nrenderer = Renderer(win)\ntex = Texture.from_surface(renderer, load_img('alien1.gif'))\n\nrunning = True\n\nx, y = 250, 50\nclock = pygame.time.Clock()\n\nbackgrounds = [(255,0,0,255), (0,255,0,255), (0,0,255,255)]\nbg_index = 0\n\nrenderer.draw_color = backgrounds[bg_index]\n\nwin2 = Window('2nd window', size=(256, 256), always_on_top=True)\nwin2.opacity = 0.5\nwin2.set_icon(load_img('bomb.gif'))\nrenderer2 = Renderer(win2)\ntex2 = Texture.from_surface(renderer2, load_img('asprite.bmp'))\nrenderer2.clear()\nrenderer2.copy(tex2)\nrenderer2.present()\ndel tex2\n\nfull = 0\n\nsrcrect = (0, 0, tex.width, tex.height)\n\nwhile running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n elif getattr(event, 'window', None) == win2:\n if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE or\\\n event.type == pygame.WINDOWEVENT and event.event == pygame.WINDOWEVENT_CLOSE:\n win2.destroy()\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n running = False\n elif event.key == pygame.K_LEFT:\n x -= 5\n elif event.key == pygame.K_RIGHT:\n x += 5\n elif event.key == pygame.K_DOWN:\n y += 5\n elif event.key == pygame.K_UP:\n y -= 5\n elif event.key == pygame.K_f:\n if full == 0:\n win.set_fullscreen(True)\n full = 1\n else:\n win.set_windowed()\n full = 0\n elif event.key == pygame.K_SPACE:\n bg_index = (bg_index + 1) % len(backgrounds)\n renderer.draw_color = backgrounds[bg_index]\n\n dstrect = (x, y, tex.width, tex.height)\n renderer.clear()\n renderer.copy(tex, srcrect, dstrect)\n renderer.present()\n\n clock.tick(60)\n win.title = str('FPS: {}'.format(clock.get_fps()))\n","sub_path":"venv/Lib/site-packages/pygame/examples/video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":2814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"34750602","text":"#!/usr/bin/env python3.7\n\n# Author: Roujia Li\n# email: Roujia.li@mail.utoronto.ca\n\nimport sys\nsys.path.append('..')\nimport os\nimport glob\nimport argparse\nimport pandas as pd\n\n\"\"\"\nMake reference fasta files for yeast or human, \nthis step needs to be done before submitting jobs for \nalignment \n\"\"\"\n\ndef make_yeast_fasta(output):\n \"\"\"\n\n :param output: output directory for fasta files\n :return:\n \"\"\"\n HIP_target_ORFs = \"/home/rothlab/rli/02_dev/06_pps_pipeline/target_orfs/HIP_targeted_ORFs.csv\"\n other_target_ORFs = \"/home/rothlab/rli/02_dev/06_pps_pipeline/target_orfs/other_targeted_ORFs.csv\"\n\n hip_df = pd.read_csv(HIP_target_ORFs)\n other_df = pd.read_csv(other_target_ORFs)\n\n hip_df = hip_df[[\"ORF_id\", \"plate\", \"SEQ\"]]\n # make fasta file for all HIP ORFs\n fasta_hip = os.path.join(output, \"hip_all.fasta\")\n with open(fasta_hip, \"w\") as output_hip:\n for index, row in hip_df.iterrows():\n seq_id = f\"{row['ORF_id']}\"\n output_hip.write(f\">{seq_id}\\n\")\n output_hip.write(f\"{row['SEQ']}\\n\")\n\n # make fasta file for plate specific ORFs\n all_plates = hip_df[\"plate\"].unique().tolist()\n for p in all_plates:\n plate_hip = hip_df[hip_df[\"plate\"] == p]\n plate_fasta = os.path.join(output, f\"{p}.fasta\")\n with open(plate_fasta, \"w\") as platefile:\n for index, row in plate_hip.iterrows():\n seq_id = f\"{row['ORF_id']}\"\n platefile.write(f\">{seq_id}\\n\")\n platefile.write(f\"{row['SEQ']}\\n\")\n\n all_sequence = \"/home/rothlab/rli/02_dev/06_pps_pipeline/target_orfs/all_sequence.txt\"\n all_seq = pd.read_csv(all_sequence, sep=\"\\t\")\n PROTGEN = all_seq[all_seq[\"source\"] == \"PROTGEN\"]\n SGD = all_seq[all_seq[\"source\"] == \"SGD\"]\n\n # make fasta file for all sequences\n fasta_all = os.path.join(output, \"all_seq.fasta\")\n with open(fasta_all, \"w\") as all_output:\n for index, row in all_seq.iterrows():\n all_output.write(f\">{row['ORF_id']}\\n\")\n all_output.write(f\"{row['cds_seq']}\\n\")\n\n # make fasta file for all other protgen\n fasta_prot = os.path.join(output, \"PROTGEN_all.fasta\")\n with open(fasta_prot, \"w\") as output_prot:\n for index, row in PROTGEN.iterrows():\n output_prot.write(f\">{row['ORF_id']}\\n\")\n output_prot.write(f\"{row['cds_seq']}\\n\")\n\n # make fasta file for all other SGD\n fasta_prot = os.path.join(output, \"SGD_all.fasta\")\n with open(fasta_prot, \"w\") as output_prot:\n for index, row in SGD.iterrows():\n output_prot.write(f\">{row['ORF_id']}\\n\")\n output_prot.write(f\"{row['cds_seq']}\\n\")\n\n # sort SGD orfs and PROTGEN orfs into plate specific groups \n # using other orfs df and all_sequence\n other = all_seq[(all_seq[\"source\"] == \"PROTGEN\") | (all_seq[\"source\"] == \"SGD\")]\n merged_seq_other = pd.merge(other_df, other, how=\"left\", on=\"orf_name\")\n other_plates = merged_seq_other[\"plate\"].unique()\n for p in other_plates:\n plate_other = merged_seq_other[merged_seq_other[\"plate\"] == p]\n plate_fasta = os.path.join(output, f\"{p}.fasta\")\n with open(plate_fasta, \"w\") as platefile:\n for index, row in plate_other.iterrows():\n seq_id = f\"{row['ORF_id']}\"\n platefile.write(f\">{seq_id}\\n\")\n platefile.write(f\"{row['cds_seq']}\\n\")\n\n # build bowtie2 index for later use \n all_fasta = glob.glob(f\"{output}/*.fasta\")\n for f in all_fasta:\n f_id = os.path.basename(f).split(\".\")[0]\n cmd = f\"bowtie2-build {f} {output}/{f_id}\"\n os.system(cmd)\n\n\ndef make_human_fasta(output):\n \"\"\"\n Make fasta files for human 9.1\n One fasta for all the sequences\n Also group specific sequences\n :param ref_91: csv file contains human 9.1 reference sequences\n :return: None\n \"\"\"\n ref_91 = \"/home/rothlab/rli/02_dev/06_pps_pipeline/fasta/human_91/20161117_ORFeome91_seqs.csv\"\n ref_df_91 = pd.read_csv(ref_91)\n ref_df_91 = ref_df_91.fillna(-1)\n # make all ref fasta\n all_ref_output = os.path.join(output, \"all_ref_human.fasta\")\n with open(all_ref_output, \"w\") as all_ref:\n for index, row in ref_df_91.iterrows():\n id_line = f\">{row['orf_id']}_{int(row['entrez_gene_id'])}_G0{row['Pool group #']}_{row['entrez_gene_symbol']}\\n\"\n seq = row[\"cds_seq\"]+\"\\n\"\n all_ref.write(id_line)\n all_ref.write(seq)\n\n # make group sepecific fasta\n # get all groups\n groups = ref_df_91[\"Pool group #\"].unique().tolist()\n for g in groups:\n # make fasta\n group_fasta = os.path.join(output, f\"group_ref_G0{g}.fasta\")\n # select subset of orfs belongs to this group\n subset = ref_df_91[ref_df_91[\"Pool group #\"] == g]\n with open(group_fasta, \"w\") as g_fasta:\n for index, row in subset.iterrows():\n id_line = f\">{row['orf_id']}_{int(row['entrez_gene_id'])}_G0{row['Pool group #']}_{row['entrez_gene_symbol']}\\n\"\n seq = row[\"cds_seq\"] + \"\\n\"\n g_fasta.write(id_line)\n g_fasta.write(seq)\n\n # build bowtie2 index for later use \n all_fasta = glob.glob(f\"{output}/*.fasta\")\n for f in all_fasta:\n f_id = os.path.basename(f).split(\".\")[0]\n cmd = f\"bowtie2-build {f} {output}/{f_id}\"\n os.system(cmd)\n\n\ndef make_human_fasta_ensembl(output):\n \"\"\"\n Make reference fasta file with ensembl ref seq\n :return:\n \"\"\"\n ref_91 = \"/home/rothlab/rli/02_dev/06_pps_pipeline/fasta/human_91/20161117_ORFeome91_seqs.csv\"\n ref_ensembl = \"/home/rothlab/rli/02_dev/06_pps_pipeline/publicdb/merged_ensembl_sequence.csv\"\n ref_df_91 = pd.read_csv(ref_91)\n ref_df_ensembl = pd.read_csv(ref_ensembl)\n ref_df_91 = ref_df_91.fillna(-1)\n print(ref_df_91.shape)\n # merge this two df together\n # check if there are NAs in entrez gene ID and entrez gene symbol\n print(ref_df_91[ref_df_91[[\"entrez_gene_id\", \"entrez_gene_symbol\"]].duplicated()])\n ref_df_ensembl = ref_df_ensembl.drop_duplicates(subset=[\"entrez_gene_id\", \"symbol\"])\n print(ref_df_ensembl.shape)\n merged_df = pd.merge(ref_df_91, ref_df_ensembl, left_on=[\"entrez_gene_id\", \"entrez_gene_symbol\"], right_on=[\"entrez_gene_id\", \"symbol\"], how=\"left\")\n \n # make grch37 and 38 output dir if not exist\n grch37_output = os.path.join(output, \"grch37\")\n if not os.path.isdir(grch37_output):\n os.makedir(grch37_output)\n\n grch38_output = os.path.join(output, \"grch38\")\n if not os.path.isdir(grch38_output):\n os.makedir(grch38_output)\n\n # make group sepecific fasta\n # get all groups\n groups = merged_df[\"Pool group #\"].unique().tolist()\n for g in groups:\n # make fasta for grch37\n # for missing values in cds_seq37, fill with original cds_seq\n merged_df[\"cds_seq37_filled\"] = merged_df[\"cds_seq37\"].fillna(merged_df[\"cds_seq\"])\n group_fasta = os.path.join(grch37_output, f\"group_ref_G0{g}.fasta\")\n # select subset of orfs belongs to this group\n subset = merged_df[merged_df[\"Pool group #\"] == g]\n with open(group_fasta, \"w\") as g_fasta:\n for index, row in subset.iterrows():\n id_line = f\">{row['orf_id']}_{int(row['entrez_gene_id'])}_G0{row['Pool group #']}_{row['entrez_gene_symbol']}\\n\"\n # remove stop codon\n seq = row[\"cds_seq37_filled\"][:-3] + \"\\n\"\n g_fasta.write(id_line)\n g_fasta.write(seq)\n\n # make fasta for grch38\n # for missing values in cds_seq38, fill with original cds_seq\n merged_df[\"cds_seq38_filled\"] = merged_df[\"cds_seq38\"].fillna(merged_df[\"cds_seq\"])\n group_fasta = os.path.join(grch38_output, f\"group_ref_G0{g}.fasta\")\n # select subset of orfs belongs to this group\n subset = merged_df[merged_df[\"Pool group #\"] == g]\n with open(group_fasta, \"w\") as g_fasta:\n for index, row in subset.iterrows():\n id_line = f\">{row['orf_id']}_{int(row['entrez_gene_id'])}_G0{row['Pool group #']}_{row['entrez_gene_symbol']}\\n\"\n # remove stop codon\n seq = row[\"cds_seq38_filled\"][:-3] + \"\\n\"\n g_fasta.write(id_line)\n g_fasta.write(seq)\n\n # build bowtie2 index for later use \n all_fasta = glob.glob(f\"{grch37_output}/*.fasta\")\n for f in all_fasta:\n f_id = os.path.basename(f).split(\".\")[0]\n cmd = f\"bowtie2-build {f} {grch37_output}/{f_id}\"\n os.system(cmd)\n\n all_fasta = glob.glob(f\"{grch38_output}/*.fasta\")\n for f in all_fasta:\n f_id = os.path.basename(f).split(\".\")[0]\n cmd = f\"bowtie2-build {f} {grch38_output}/{f_id}\"\n os.system(cmd)\n\n\ndef compare_human_ref(output):\n \"\"\"\n\n :param output:\n :return:\n \"\"\"\n \"\"\"\n Make reference fasta file with ensembl ref seq\n :return:\n \"\"\"\n ref_91 = \"/home/rothlab/rli/02_dev/06_pps_pipeline/fasta/human_91/20161117_ORFeome91_seqs.csv\"\n ref_ensembl = \"/home/rothlab/rli/02_dev/06_pps_pipeline/publicdb/merged_ensembl_sequence.csv\"\n ref_df_91 = pd.read_csv(ref_91)\n ref_df_ensembl = pd.read_csv(ref_ensembl)\n ref_df_91 = ref_df_91.fillna(-1)\n print(ref_df_91.shape)\n # merge this two df together\n # check if there are NAs in entrez gene ID and entrez gene symbol\n print(ref_df_91[ref_df_91[[\"entrez_gene_id\", \"entrez_gene_symbol\"]].duplicated()])\n ref_df_ensembl = ref_df_ensembl.drop_duplicates(subset=[\"entrez_gene_id\", \"symbol\"])\n print(ref_df_ensembl.shape)\n merged_df = pd.merge(ref_df_91, ref_df_ensembl, left_on=[\"entrez_gene_id\", \"entrez_gene_symbol\"],\n right_on=[\"entrez_gene_id\", \"symbol\"], how=\"left\")\n\n\ndef main(mode, output):\n \"\"\"\n Make fasta files in output dir\n :param mode: yeast or human\n :param output: output directory for fasta files\n :return: None\n \"\"\"\n if mode == \"human\":\n make_human_fasta_ensembl(output)\n else:\n make_yeast_fasta(output)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Plasmid pool sequencing analysis')\n parser.add_argument('-m', help='human or yeast')\n parser.add_argument(\"-o\", help=\"output dir for fasta files\")\n\n args = parser.parse_args()\n main(args.m, args.o)\n\n","sub_path":"build/lib/ppsAnalysis/make_ref.py","file_name":"make_ref.py","file_ext":"py","file_size_in_byte":10335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"628687936","text":"import argparse\nimport sys\nfrom os.path import exists, isdir, splitext\n\nfrom PIL import Image\n\n\ndef load_arguments():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"image\")\n parser.add_argument(\"-W\", \"--width\", type=int)\n parser.add_argument(\"-H\", \"--height\", type=int)\n parser.add_argument(\"-S\", \"--scale\", type=float)\n parser.add_argument(\"-O\", \"--output\")\n arguments = parser.parse_args()\n return arguments\n\n\ndef validate_required_arguments(arguments):\n if all(\n (\n arguments.scale is None,\n arguments.width is None,\n arguments.height is None,\n )\n ):\n argparse.ArgumentParser().error(\"No arguments provided\")\n\n\ndef validate_compatible_arguments(arguments):\n if arguments.scale is not None and (\n arguments.width is not None or arguments.height is not None\n ):\n raise argparse.ArgumentTypeError(\n \"You should use either width/height or scale option\"\n )\n\n\ndef is_positive_number(input_value):\n min_value = 0\n return input_value > min_value\n\n\ndef validate_positive_arguments(arguments):\n if any(\n (\n arguments.scale is not None\n and not is_positive_number(arguments.scale),\n arguments.width is not None\n and not is_positive_number(arguments.width),\n arguments.height is not None\n and not is_positive_number(arguments.height),\n )\n ):\n raise argparse.ArgumentTypeError(\"Arguments should be positive\")\n\n\ndef validate_existing_file(arguments):\n if not exists(arguments.image):\n raise argparse.ArgumentTypeError(\"File does not exist\")\n\n\ndef validate_not_directory(arguments):\n if isdir(arguments.image):\n raise argparse.ArgumentTypeError(\"Directories is not allowed\")\n\n\ndef validate_arguments(arguments):\n validate_existing_file(arguments)\n validate_not_directory(arguments)\n validate_required_arguments(arguments)\n validate_compatible_arguments(arguments)\n validate_positive_arguments(arguments)\n\n\ndef calculate_dimensions_using_width(old_dimensions, new_width):\n old_width, old_height = old_dimensions\n scale_factor = new_width / old_width\n new_height = int(scale_factor * old_height)\n return new_width, new_height\n\n\ndef calculate_dimensions_using_height(old_dimensions, new_height):\n old_width, old_height = old_dimensions\n scale_factor = new_height / old_height\n new_width = int(scale_factor * old_width)\n return new_width, new_height\n\n\ndef calculate_dimensions_using_scale(old_dimensions, scale_factor):\n old_width, old_height = old_dimensions\n new_width = int(scale_factor * old_width)\n new_height = int(scale_factor * old_height)\n return new_width, new_height\n\n\ndef calculate_dimensions(old_dimensions, width, height, scale):\n if width is not None and height is not None:\n new_dimensions = width, height\n elif width is not None and height is None:\n new_dimensions = calculate_dimensions_using_width(\n old_dimensions, width\n )\n elif width is None and height is not None:\n new_dimensions = calculate_dimensions_using_height(\n old_dimensions, height\n )\n else:\n new_dimensions = calculate_dimensions_using_scale(\n old_dimensions, scale\n )\n return new_dimensions\n\n\nif __name__ == \"__main__\":\n try:\n arguments = load_arguments()\n validate_arguments(arguments)\n image = Image.open(arguments.image)\n except (OSError, argparse.ArgumentTypeError) as error:\n sys.exit(error)\n\n aspect_ratio = image.width / image.height\n if (\n arguments.width is not None and arguments.height is not None\n ) and arguments.width / arguments.height != aspect_ratio:\n print(\"Aspect ratio will differ from an existing one\")\n\n new_dimensions = calculate_dimensions(\n image.size, arguments.width, arguments.height, arguments.scale\n )\n resized_image = image.resize(new_dimensions)\n output_filepath = arguments.output\n if output_filepath is None:\n basename, extension = splitext(arguments.image)\n output_filepath = \"{}__{}x{}{}\".format(\n basename, resized_image.width, resized_image.height, extension\n )\n resized_image.save(output_filepath)\n","sub_path":"image_resize.py","file_name":"image_resize.py","file_ext":"py","file_size_in_byte":4320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"183082376","text":"#!/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport utils.logger as logger\nfrom utils import common\nfrom subprocess import Popen, PIPE, run\nfrom abc import ABCMeta, abstractmethod\nfrom sys import exit\n\n\nclass FormatterInterface(object):\n __metaclass__ = ABCMeta\n\n @abstractmethod\n def format(self, files):\n pass\n\n\nclass DryFormatter(FormatterInterface):\n\n def format(self, files):\n logger.info('Start check...')\n\n ret = []\n for file in files:\n command = [\n './bin/checker',\n file\n ]\n shell_ret = Popen(command, shell=False, stdout=PIPE)\n lines = shell_ret.stdout.readlines()\n diff_count = int(str(lines[0], encoding='utf-8').strip('\\n'))\n if diff_count > 0:\n ret.append(file + ' ' + str(diff_count))\n\n if len(ret) > 0:\n logger.warn(str(len(ret)) + ' Files need to be formatted\\n')\n for file_name in ret:\n logger.info(file_name)\n else:\n logger.info('Great! No file need to be formatted')\n\n\nclass WetFormatter(FormatterInterface):\n\n def format(self, files):\n if len(files) == 0:\n logger.info('Great! No file need to be formatted')\n exit(0)\n else:\n logger.info('Start format...')\n for file in files:\n command = [\n './bin/formatter',\n file\n ]\n run(command)\n\n\ndef start(all_file: bool, dry_run: bool):\n if all_file:\n files_to_be_checked = common.all_objc_files(os.path.abspath(os.path.dirname(os.getcwd())))\n else:\n # change working directory and execute svn status to get all changed subversion files\n # and then change the working directory back\n current_folder = os.getcwd()\n os.chdir(os.path.dirname(current_folder))\n files_to_be_checked = common.subversion_objc_files_to_check()\n os.chdir(current_folder)\n\n if dry_run:\n formatter = DryFormatter()\n else:\n formatter = WetFormatter()\n\n formatter.format(files_to_be_checked)\n","sub_path":"formatter.py","file_name":"formatter.py","file_ext":"py","file_size_in_byte":1911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"619864241","text":"import matplotlib\nimport matplotlib.pyplot as plots\nfrom datascience import *\nimport numpy as np\n\ndef draw_bar_plot(categories_label, categories, values_label, values):\n Table().with_column(categories_label, categories)\\\n .with_column(values_label, values).barh(categories_label)\n\ndef draw_group_barh(title, data):\n \"\"\"Draws a bar chart of the unique values in the given array\n \n Args:\n - title (str): A title for the chart.\n - data (array): An array of values. Repeated values are counted\n and given larger bars in the resulting chart.\n \n \"\"\"\n Table().with_column(title, data).group_barh(title)\n\ndef draw_line_plot(x_label, x_data, y_label, y_data):\n \"\"\"Draws a line plot of the given data.\n \n Args:\n - x_label (str): The horizontal axis label.\n - x_data (array): The horizontal (\"x\") values of the points\n that are connected to form the plot.\n - y_label (str): The vertical axis label.\n - y_data (array): The vertical (\"y\") values of the points that\n are connected to form the plot.\n \"\"\"\n Table().with_columns(x_label, x_data, y_label, y_data).plot(x_label)\n\ndef draw_scatter_plot(x_label, x_data, y_label, y_data):\n \"\"\"Draws a scatter plot of the given data.\n \n Args:\n - x_label (str): The horizontal axis label.\n - x_data (array): The horizontal (\"x\") values of the points\n in the plot.\n - y_label (str): The vertical axis label.\n - y_data (array): The vertical (\"y\") values of the points in\n the plot.\n \"\"\"\n Table().with_columns(x_label, x_data, y_label, y_data).scatter(x_label)\n\ndef load_and_clean_table(url):\n \"\"\"Loads a table about Marvel or DC comics from fivethirtyeight's\n GitHub repository, and cleans up a few formatting details.\"\"\"\n tbl = Table.read_table(url)\n if \"Year\" in tbl.labels:\n tbl.relabel(\"Year\", \"YEAR\")\n tbl.update({'PUBLISHER': 'Marvel'})\n else:\n tbl.update({'PUBLISHER': 'DC'})\n tbl.relabel(\"name\", \"NAME\")\n tbl.update({\"APPEARANCES\": np.nan_to_num(tbl.column(\"APPEARANCES\"))})\n tbl.update({\"GENDER\": np.char.replace(tbl.column(\"SEX\"), \"nan\", \"Unknown\")})\n tbl.update({\"GENDER\": np.char.replace(tbl.column(\"GENDER\"), \" Characters\", \"\")})\n \n def extract_month(date_text):\n import dateutil.parser\n try:\n return dateutil.parser.parse(date_text).month\n except:\n return \"Unknown\"\n \n tbl.update({\"MONTH\": tbl.apply(extract_month, \"FIRST APPEARANCE\")})\n tbl.update({\"MONTH\": tbl.apply(lambda d: int(d) if d != \"Unknown\" else -1, \"MONTH\")})\n tbl = tbl.select(\"PUBLISHER\", \"NAME\", \"GENDER\", \"APPEARANCES\", \"YEAR\", \"MONTH\")\n for l in tbl.labels:\n tbl.relabel(l, l.capitalize())\n tbl = tbl.where(~np.isnan(tbl.column(\"Year\")))\n return tbl","sub_path":"DATA6/lab_funcs.py","file_name":"lab_funcs.py","file_ext":"py","file_size_in_byte":2792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"593698415","text":"import simplejson as json\nimport steelfig.apps.apiv1.helpers.view as helper\nfrom steelfig.models.account import Account\n\ndef mapper(request):\n if request.method == 'POST':\n return create(request)\n if request.method == 'GET':\n return get(request)\n\ndef get(request):\n account = Account(int(request.REQUEST.get('id')))\n return helper.json(account.to_dict())\n\ndef create(request):\n params = json.loads(request.body)\n email = params.get('account').get('email')\n account = Account(email).save();\n return helper.json(account.to_dict())\n","sub_path":"steelfig/apps/apiv1/views/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"328146288","text":"#!/usr/bin/python3\n\"\"\"\ncity related api endpoints\n\"\"\"\n\nfrom api.v1.views import app_views\nfrom flask import abort, request\nfrom flask.json import jsonify\nfrom models import storage\nfrom models.state import State\nfrom models.city import City\n\n\n@app_views.route('/states//cities', strict_slashes=False)\ndef get_cities_by_state(state_id=None):\n \"\"\"\n returns a list of all cities of a state\n \"\"\"\n all_state = storage.all(State)\n res = []\n if all_state is not {} and state_id is not None:\n for state in all_state.values():\n if state.id == state_id:\n for city in state.cities:\n res.append(city.to_dict())\n return jsonify(res)\n\n abort(404)\n\n\n@app_views.route('/cities/', strict_slashes=False)\ndef get_cities(city_id=None):\n \"\"\"\n retrieves city object based on city_id\n \"\"\"\n city = storage.get(City, city_id)\n if city is not None:\n return jsonify(city.to_dict())\n\n abort(404)\n\n\n@app_views.route('/cities/', strict_slashes=False,\n methods=['DELETE'])\ndef del_city(city_id):\n \"\"\"\n deletes a city object\n \"\"\"\n city = storage.get(City, city_id)\n if city is not None:\n city.delete()\n storage.save()\n return jsonify({}), 200\n\n abort(404)\n\n\n@app_views.route('/states//cities', strict_slashes=False,\n methods=['POST'])\ndef make_city(state_id=None):\n \"\"\"\n creates a city object\n \"\"\"\n json = request.get_json(silent=True)\n\n state = storage.get(State, state_id)\n if state is None:\n abort(404)\n\n if json is None:\n abort(400, 'Not a JSON')\n\n if 'name' not in json:\n abort(400, 'Missing name')\n\n city = City(**json)\n city.state_id = state_id\n city.save()\n\n return jsonify(city.to_dict()), 201\n\n\n@app_views.route('/cities/', strict_slashes=False,\n methods=['PUT'])\ndef update_city(city_id):\n \"\"\"\n updates a city object\n \"\"\"\n city = storage.get(City, city_id)\n if city is None:\n abort(404)\n\n json = request.get_json(silent=True)\n\n if json is None:\n abort(400, 'Not a JSON')\n\n for key, value in json.items():\n if key != 'updated_at' and key != 'created_at' \\\n and key != 'id' and key != 'state_id':\n setattr(city, key, value)\n\n city.save()\n\n return jsonify(city.to_dict()), 200\n","sub_path":"api/v1/views/cities.py","file_name":"cities.py","file_ext":"py","file_size_in_byte":2429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"}