diff --git "a/1088.jsonl" "b/1088.jsonl" new file mode 100644--- /dev/null +++ "b/1088.jsonl" @@ -0,0 +1,719 @@ +{"seq_id":"109707999","text":"#!usr/bin/env python3\n#\n# Author(s): Roman Rivera (Invisible Institute)\n\n'''export script for awards_1967-2017_2017-08_p061715'''\n\nimport pandas as pd\nimport __main__\nimport yaml\n\nimport setup\n\n\ndef get_setup():\n ''' encapsulates args.\n calls setup.do_setup() which returns constants and logger\n constants contains args and a few often-useful bits in it\n including constants.write_yamlvar()\n logger is used to write logging messages\n '''\n script_path = __main__.__file__\n args = {\n 'input_file': 'input/awards_1967-2017_2017-08.csv.gz',\n 'input_profiles_file': 'input/awards_1967-2017_2017-08_profiles.csv.gz',\n 'output_file': 'output/awards_1967-2017_2017-08.csv.gz',\n 'output_profiles_file': 'output/awards_1967-2017_2017-08_profiles.csv.gz',\n 'export_cols': [\n 'pps_award_detail_id', 'award_type', 'award_start_date',\n 'current_award_status', 'award_request_date',\n 'award_end_date', 'rank', 'last_promotion_date',\n 'requester_full_name', 'ceremony_date', 'tracking_no'\n ],\n 'id': 'awards_1967-2017_2017-08_ID'\n }\n\n assert (args['input_file'].startswith('input/') and\n args['input_file'].endswith('.csv.gz')),\\\n \"input_file is malformed: {}\".format(args['input_file'])\n assert (args['output_file'].startswith('output/') and\n args['output_file'].endswith('.csv.gz')),\\\n \"output_file is malformed: {}\".format(args['output_file'])\n\n return setup.do_setup(script_path, args)\n\n\ncons, log = get_setup()\n\ndf = pd.read_csv(cons.input_file)\n\nwith open(\"hand/award_po_ranks.yaml\", \"r\") as f:\n po_ranks = yaml.load(f)\nwith open(\"hand/maybe_po_ranks.yaml\", \"r\") as f:\n maybe_po_ranks = yaml.load(f)\n\npo_ids = df.loc[(df['rank'].isin(po_ranks)) |\n ((df['rank'].isin(maybe_po_ranks)) &\n (df['appointed_date'] < \"2010-01-01\")),\n cons.id].unique()\n\ndf_rows = df.shape[0]\ndf = df[['row_id', cons.id] + cons.export_cols]\ndf.to_csv(cons.output_file, **cons.csv_opts)\n\nprofiles_df = pd.read_csv(cons.input_profiles_file)\nprofiles_df.loc[profiles_df[cons.id].isin(po_ids), 'merge'] = 1\nprofiles_df['merge'] = profiles_df['merge'].fillna(0)\nlog.info('%d IDs with PO ranks marked for merging', len(po_ids))\nprofiles_df.to_csv(cons.output_profiles_file, **cons.csv_opts)\n","sub_path":"get_data/utils/folder_structures/awards/export/src/export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":2394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"346061059","text":"import torch\nimport attr\nimport numpy as np\nfrom skultrafast.dataset import TimeResSpec\nimport math\nexp_half = math.exp(1 / 2.)\nfrom scipy.optimize import least_squares\n\ndef lstsq(b, y, alpha=0.01):\n \"\"\"\n Batched linear least-squares for pytorch with optional L1 regularization.\n\n Parameters\n ----------\n\n b : shape(L, M, N)\n y : shape(L, M)\n\n Returns\n -------\n tuple of (coefficients, model, residuals)\n\n \"\"\"\n bT = b.transpose(-1, -2)\n AA = torch.bmm(bT, b)\n if alpha != 0:\n diag = torch.diagonal(AA, dim1=1, dim2=2)\n diag += alpha\n RHS = torch.bmm(bT, y[:, :, None])\n X, LU = torch.gesv(RHS, AA)\n fit = torch.bmm(b, X)[..., 0]\n res = y - fit\n return X[..., 0], fit, res\n\n@attr.s(auto_attribs=True)\nclass FitterTorch:\n dataset : TimeResSpec = attr.ib()\n zero_func : function = attr.ib(lambda x: np.zeros_like(x))\n done_eval : bool = attr.ib(False)\n use_cuda : bool = attr.ib(True)\n disp_poly_deg : int = attr.ib(2)\n model_coh : bool = attr.ib(0)\n\n def __attrs_post_init__(self):\n ds = self.dataset\n self.dev_data = torch.from_numpy(ds.data.T)\n if self.use_cuda:\n self.dev_data = self.dev_data.cuda()\n\n\n def eval(self, tt, w, tau, model_coh=False):\n \"\"\"\n Evaluates a model for given arrays\n\n Parameters\n ----------\n tt : ndarray\n Contains the delay-times, should have the same shape as the data.\n w : float\n The IRF width.\n tau : ndarray\n Contains the decay times.\n \"\"\"\n tt = torch.from_numpy(tt)\n tau = torch.from_numpy(tau)\n if self.use_cuda:\n tt = tt.cuda()\n tau= tau.cuda()\n\n k = 1 / (tau[None, None, ...])\n t = (tt)[..., None]\n if w == 0:\n A = torch.exp(-k*tt)\n else:\n A = torch.exp(k * (w * w * k / (4.0) - t)) \\\n * 0.5 * torch.erfc(-t / w + w * k / (2.0))\n if model_coh:\n coh = torch.exp(-0.5 * (tt / w) * (tt / w))\n coh = coh[:, :, None].repeat((1, 1, 3))\n coh[..., 1] *= (-tt * exp_half / w)\n coh[..., 2] *= (tt * tt / w / w - 1)\n A = torch.cat((A, coh), dim=-1)\n\n X, fit, res = lstsq(A, self.data)\n self.done_eval = True\n self.c = X\n self.model = fit\n self.residuals = res\n return X, fit, res\n\n\n def fit_func(self, x):\n ds = self.dataset\n disp_coefs = x[:self.disp_poly_deg]\n w = float(x[self.disp_poly_deg])\n taus = x[self.disp_poly_deg+1:]\n t_zeros = np.poly1d(disp_coefs)(ds.wavenumbers)\n tt = np.subtract.outer(ds.t, t_zeros).T\n c, model, res = self.eval_torch(tt, w, taus, True)\n return res.cpu().numpy().ravel()\n\n def start_fit(self, w, taus, fix_last_tau=False, fix_width=False,\n fix_disp=False):\n ds = self.dataset\n time_zeros = self.zero_func(ds.wavenumbers)\n disp_guess = np.polyfit(ds.wavenumbers, time_zeros)\n x0 = np.hstack((disp_guess, w, taus))\n idx = np.ones_like(x0, dtype='bool')\n if fix_last_tau:\n idx[-1] = False\n if fix_width:\n idx[self.disp_poly_deg] = False\n if fix_disp:\n idx[:self.disp_poly_deg] = False\n\n start_guess = x0[idx]\n\n def fix_func(x):\n x0[idx] = x\n return self.fit_func(x0)\n\n bounds = np.array([(-np.inf, np.inf)] * len(x0))\n bounds[self.disp_poly_deg:, 0] = 0\n bounds = bounds[idx, :]\n x = least_squares(fix_func, start_guess, bounds=bounds.T)\n return x, x0\n\n","sub_path":"skultrafast/base_funcs/pytorch_fitter.py","file_name":"pytorch_fitter.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"375269128","text":"from monero_glue.xmr import crypto\nfrom monero_glue.xmr.sub.xmr_net import NetworkTypes, net_version\n\n\ndef addr_to_hash(addr):\n \"\"\"\n Creates hashable address representation\n :param addr:\n :return:\n \"\"\"\n return bytes(addr.m_spend_public_key + addr.m_view_public_key)\n\n\ndef encode_addr(version, spend_pub, view_pub):\n \"\"\"\n Encodes public keys as versions\n :param version:\n :param spend_pub:\n :param view_pub:\n :return:\n \"\"\"\n buf = spend_pub + view_pub\n return crypto.xmr_base58_addr_encode_check(ord(version), bytes(buf))\n\n\ndef decode_addr(addr):\n \"\"\"\n Given address, get version and public spend and view keys.\n\n :param addr:\n :return:\n \"\"\"\n d, version = crypto.xmr_base58_addr_decode_check(bytes(addr))\n pub_spend_key = d[0:32]\n pub_view_key = d[32:64]\n return version, pub_spend_key, pub_view_key\n\n\ndef public_addr_encode(pub_addr, is_sub=False, net=NetworkTypes.MAINNET):\n \"\"\"\n Encodes public address to Monero address\n :param pub_addr:\n :type pub_addr: apps.monero.xmr.serialize_messages.addr.AccountPublicAddress\n :param is_sub:\n :param net:\n :return:\n \"\"\"\n net_ver = net_version(net, is_sub)\n return encode_addr(net_ver, pub_addr.m_spend_public_key, pub_addr.m_view_public_key)\n\n\ndef classify_subaddresses(tx_dests, change_addr):\n \"\"\"\n Classify destination subaddresses\n void classify_addresses()\n :param tx_dests:\n :type tx_dests: list[apps.monero.xmr.serialize_messages.tx_construct.TxDestinationEntry]\n :param change_addr:\n :return:\n \"\"\"\n num_stdaddresses = 0\n num_subaddresses = 0\n single_dest_subaddress = None\n addr_set = set()\n for tx in tx_dests:\n if change_addr and addr_eq(change_addr, tx.addr):\n continue\n addr_hashed = addr_to_hash(tx.addr)\n if addr_hashed in addr_set:\n continue\n addr_set.add(addr_hashed)\n if tx.is_subaddress:\n num_subaddresses += 1\n single_dest_subaddress = tx.addr\n else:\n num_stdaddresses += 1\n return num_stdaddresses, num_subaddresses, single_dest_subaddress\n\n\ndef addr_eq(a, b):\n \"\"\"\n Address comparisson. Allocation free.\n :param a:\n :param b:\n :return:\n \"\"\"\n return pub_eq(a.m_spend_public_key, b.m_spend_public_key) and pub_eq(\n a.m_view_public_key, b.m_view_public_key\n )\n\n\ndef pub_eq(a, b):\n \"\"\"\n Simple non-constant time public key compare\n :param a:\n :param b:\n :return:\n \"\"\"\n if a == b:\n return True\n if (a is None and b is not None) or (a is not None and b is None):\n return False\n if len(a) != len(b):\n return False\n for i in range(len(a)):\n if a[i] != b[i]:\n return False\n return True\n\n\ndef get_change_addr_idx(outputs, change_dts):\n \"\"\"\n Returns ID of the change output from the change_dts and outputs\n :param tsx_data:\n :return:\n \"\"\"\n if change_dts is None:\n return None\n\n change_idx = None\n change_coord = change_dts.amount, change_dts.addr\n for idx, dst in enumerate(outputs):\n if (\n change_coord\n and change_coord[0]\n and change_coord[0] == dst.amount\n and addr_eq(change_coord[1], dst.addr)\n ):\n change_idx = idx\n return change_idx\n","sub_path":"monero_glue/xmr/sub/addr.py","file_name":"addr.py","file_ext":"py","file_size_in_byte":3341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"463020699","text":"class Solution:\n def minWindow(self, s:str, t:str) -> str:\n from collections import Counter\n if not t or not s:\n return ''\n dict_t = Counter(t)\n required = len(dict_t)\n l,r = 0, 0\n formed = 0\n window_counts = {}\n ans = float('inf'), None, None\n while r < len(s):\n character = s[r]\n window_counts[character] = window_counts.get(character, 0) + 1\n if character in dict_t and window_counts[character] == dict_t[character]:\n formed += 1\n while l <= r and formed == required:\n character = s[l]\n if r - l +1 < ans[0]:\n ans = (r-1+1, l, r)\n window_counts[character] -= 1\n if character in dict_t and window_counts[character] < dict_t[character]:\n formed -= 1\n\n l +=1\n r+=1\n return ''if ans[0] == float('inf') else s[ans[1]:ans[2] + 1]\n\nif __name__ == '__main__':\n solution = Solution()\n s = 'ab'\n t = 'b'\n solution.minWindow(s, t)\n\n","sub_path":"sliding window/min_strs.py","file_name":"min_strs.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"634505129","text":"from burp import IBurpExtender, IProxyListener, IHttpListener, IResponseInfo, ITab, ITextEditor\nfrom java.io import PrintWriter\nfrom datetime import datetime\nfrom javax import swing\nfrom java.awt import BorderLayout\nfrom ast import literal_eval\n\nclass BurpExtender(IBurpExtender, IProxyListener, IHttpListener, IResponseInfo, ITab, ITextEditor):\n filePathBase = \"/tmp\"\n fileMimeTypes = [\"JPEG\", \"PNG\", \"GIF\"]\n\n # Used to store the config in Burp\n FILELOCATION = \"location\"\n MIMETYPES = \"mimetypes\"\n\n def saveData(self, e):\n # self._stdout.println (e.getSource().getText() + \" was clicked\")\n # self._stdout.println (self.saveLocationInput.getText())\n\n location = self.saveLocationInput.getText()\n\n # force a / on the end if not provided\n\n if (location[len(location)-1] != \"/\"):\n location = location + \"/\"\n self._stdout.println(\"Saving files to: \" + location)\n\n self.filePathBase = location\n\n text = self.mimeTypesInput.getText()\n upper = text.upper()\n mimeTypesToList = upper.split(\",\")\n self._stdout.println(mimeTypesToList)\n self.fileMimeTypes = mimeTypesToList\n\n self._stdout.println(\"Matching MIME Types: \" + repr(mimeTypesToList))\n\n # Save the location\n self._callbacks.saveExtensionSetting (self.FILELOCATION, location)\n self._callbacks.saveExtensionSetting (self.MIMETYPES, repr(self.fileMimeTypes))\n\n def initUI(self):\n self.tab = swing.JPanel()\n\n # Create the text area at the top of the tab\n textPanel = swing.JPanel()\n boxVertical = swing.Box.createVerticalBox()\n\n # Create the label for save location\n boxHorizontal = swing.Box.createHorizontalBox()\n textLabel = swing.JLabel(\"Save location: \")\n boxHorizontal.add(textLabel)\n boxVertical.add(boxHorizontal)\n\n # Create save location input\n boxHorizontal = swing.Box.createHorizontalBox()\n self.saveLocationInput = swing.JTextField(100)\n boxHorizontal.add(self.saveLocationInput)\n boxVertical.add(boxHorizontal)\n\n # Create the label for the mime type\n boxHorizontal = swing.Box.createHorizontalBox()\n textLabel = swing.JLabel(\"MIME Types - comma separated: \")\n boxHorizontal.add(textLabel)\n boxVertical.add(boxHorizontal)\n\n # Create MIME type input\n boxHorizontal = swing.Box.createHorizontalBox()\n self.mimeTypesInput = swing.JTextField(100)\n boxHorizontal.add(self.mimeTypesInput)\n boxVertical.add(boxHorizontal)\n\n # Save button\n boxHorizontal = swing.Box.createHorizontalBox()\n saveButton = swing.JButton(\"Save\")\n saveButton.addActionListener(self.saveData)\n boxHorizontal.add(saveButton)\n boxVertical.add(boxHorizontal)\n\n # Output pane label\n boxHorizontal = swing.Box.createHorizontalBox()\n textLabel = swing.JLabel(\"Output\")\n boxHorizontal.add(textLabel)\n boxVertical.add(boxHorizontal)\n\n # Output pane\n boxHorizontal = swing.Box.createHorizontalBox()\n # This is an attempt at using a Burp ITextEditor, but \n # I need to work out how to add it to the box\n self.outputBox = self._callbacks.createTextEditor()\n self.outputBox.setEditable(False)\n boxHorizontal.add(self.outputBox.getComponent())\n boxVertical.add(boxHorizontal)\n\n # Add the text label and area to the text panel\n textPanel.add(boxVertical)\n\n # Add the text panel to the top of the main tab\n self.tab.add(textPanel, BorderLayout.NORTH) \n\n def getTabCaption(self):\n return \"Save Browsing Files\"\n\n def getUiComponent(self):\n return self.tab\n\n def registerExtenderCallbacks( self, callbacks):\n extName = \"Save Files\"\n # keep a reference to our callbacks object and add helpers\n self._callbacks = callbacks\n self._helpers = self._callbacks.getHelpers()\n\n # set our extension name\n self._callbacks.setExtensionName(extName)\n\n # obtain our output streams\n self._stdout = PrintWriter(self._callbacks.getStdout(), True)\n self._stderr = PrintWriter(self._callbacks.getStderr(), True)\n\n # register ourselves as a Proxy listener\n self._callbacks.registerHttpListener(self)\n\n # print extension name\n self._stdout.println(extName)\n\n # Build list to compare against\n # Need to load this from storage as well\n self.fileMimeTypes = [\"JPEG\", \"PNG\", \"GIF\"]\n\n # Load the location from Burp storage\n self.filePathBase = self._callbacks.loadExtensionSetting(self.FILELOCATION)\n\n # Default to /tmp\n # May be better to check the OS to make this decision, but sticking\n # with this for now.\n if self.filePathBase is None:\n self.filePathBase = \"/tmp/\"\n\n self._stdout.println(\"Saving files to: \" + self.filePathBase)\n\n loadedMimeTypes = self._callbacks.loadExtensionSetting(self.MIMETYPES)\n if loadedMimeTypes is None:\n self.mimeTypesInput = [\"JPEG\", \"PNG\", \"GIF\"]\n else:\n # should probably check to see what happens if loadedMimeTypes does\n # not eval correctly.\n self.mimeTypesInput = literal_eval(loadedMimeTypes)\n self._stdout.println(\"loaded: \" + loadedMimeTypes)\n\n mimeTypesAsString = ','.join(self.mimeTypesInput)\n self._stdout.println(\"parsed: \" + mimeTypesAsString)\n\n self.initUI()\n self._callbacks.addSuiteTab(self)\n self.saveLocationInput.setText(self.filePathBase)\n self.mimeTypesInput.setText(mimeTypesAsString)\n\n return\n\n def processHttpMessage(self, toolflag, messageIsRequest, messageInfo):\n if (messageIsRequest == False):\n response = messageInfo.getResponse()\n responseInfo = self._helpers.analyzeResponse(response)\n\n # request = messageInfo.getRequest()\n # self._stdout.println(type(request))\n\n # for header in request:\n # self._stdout.println(header)\n\n # for header in request.getHeaders():\n # self._stdout.println(header)\n #\n # self._stdout.println(request)\n\n # Get MIME types\n inferredMime = responseInfo.getInferredMimeType()\n statedMime = responseInfo.getStatedMimeType()\n\n # Get response body\n bodyOffset = responseInfo.getBodyOffset()\n # self._stdout.println(bodyOffset)\n # Build image request body\n imgData = response[bodyOffset:]\n # self._stdout.println(imgData)\n\n self._stdout.println(\"Stated MIME Type: \" + statedMime)\n self._stdout.println(\"Inferred MIME Type: \" + inferredMime)\n\n # If multiple files are loaded in the same second they will all get\n # the same name and be overwritten so need to add something extra to \n # the name to ensure it is unique.\n\n if (statedMime in self.fileMimeTypes) or (inferredMime in self.fileMimeTypes):\n # Build file path\n fileName = datetime.now().strftime('%Y-%m-%d-%H-%M-%S-%f')\n fileExtension = \".\" + inferredMime.lower()\n fullFilename = self.filePathBase + fileName + fileExtension\n self.outputBox.append(\"Writing to file: \" + fullFilename + \"\\n\")\n\n # This forces the textarea to autoscroll after the update\n self.outputBox.setCaretPosition(self.outputBox.getDocument().getLength());\n # Write to file\n f = open(fullFilename, \"wb\")\n f.write(imgData)\n f.close()\n return\n","sub_path":"saveImages.py","file_name":"saveImages.py","file_ext":"py","file_size_in_byte":7798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"426077845","text":"import paho.mqtt.client as mqtt\nimport datetime\nimport time\nimport os\n\nmqttServer = \"\"\nmqttPort = 1883\nmqttSubTopic = \"\"\n\n# Gets the path of the python script and set a global var, \"count\" to keep track of number of packages received\ncwd = os.getcwd()\nglobal count\ncount = 1\n\ndef on_connect(mqttc, obj, flags, rc):\n\tprint(\"rc: \" + str(rc))\n\n\ndef on_message(mqttc, obj, msg):\n\tglobal count\n\n\twith open(cwd + \"/log.txt\", \"a+\") as f:\n\t\tpayload = str(count), time.ctime(), msg.topic + \" \" + str(msg.qos) + \" \" + str(msg.payload)\n\n\t\tprint(payload)\n\n\t\tf.write(payload + \"\\n\")\n\t\tf.close()\n\n\t\tcount += 1\n\n\ndef on_publish(mqttc, obj, mid):\n\tprint(\"mid: \" + str(mid))\n\n\ndef on_subscribe(mqttc, obj, mid, granted_qos):\n\tprint(\"Subscribed: \" + str(mid) + \" \" + str(granted_qos))\n\n\ndef on_log(mqttc, obj, level, string):\n\tprint(time.ctime(),string)\n\n# If you want to use a specific client id, use\n# mqttc = mqtt.Client(\"client-id\")\n# but note that the client id must be unique on the broker. Leaving the client\n# id parameter empty will generate a random id for you.\nmqttc = mqtt.Client()\nmqttc.on_message = on_message\nmqttc.on_connect = on_connect\nmqttc.on_publish = on_publish\nmqttc.on_subscribe = on_subscribe\n# Uncomment to enable debug messages\n# mqttc.on_log = on_log\nmqttc.connect(mqttServer, mqttPort, 60)\nmqttc.subscribe(mqttSubTopic, 0)\n\nmqttc.loop_forever()\n","sub_path":"mqtt-subscriber/mqtt-subscriber.py","file_name":"mqtt-subscriber.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"410136424","text":"#--*coding: utf8*--\nimport pymongo\nimport hashlib\nimport uuid\nimport time\nimport random\nimport yaml\nfrom bson.objectid import ObjectId\n\n\n# local database\n# client = pymongo.MongoClient('mongodb://localhost:27017/')\n# conn = client.iubcoder\n\n# remote database\nwith open(\"config.yml\", \"r\") as f:\n doc = yaml.load(f)\n MONGODB_URI = doc[\"database\"][\"path\"]\n\nclient = pymongo.MongoClient(MONGODB_URI) # database connection\nconn = client.get_default_database()\n\n\ndef check_username(username):\n '''\n Check if the username has been used\n '''\n user_db = conn[\"users\"]\n user = user_db.find_one({\"username\": username})\n if user:\n return True\n else:\n return False\n\n\ndef check_email(email):\n '''\n Check if the email has been used\n '''\n user_db = conn[\"users\"]\n user = user_db.find_one({\"email\": email})\n if user:\n return True\n else:\n return False\n\n\ndef insert_user(username, password, salt, email):\n '''\n Inser a new user into database.\n '''\n user_db = conn[\"users\"] # user database\n # register time\n reg_time = time.time()\n # generate verify code\n code = username + email + str(reg_time)\n m2 = hashlib.md5(code.encode('utf8'))\n md5code = m2.hexdigest() + '.' + str(random.randint(11111111, 99999999))\n # generate cookie, _id is a ObjectId type, which cannot be used as cookie.\n gen_cookie = username + email\n cookie = hashlib.md5(gen_cookie.encode('utf8')).hexdigest()\n\n new_user = {\n \"reg_time\": reg_time,\n \"username\": username,\n \"password\": password,\n \"email\": email,\n \"salt\": salt,\n \"verified\": False,\n \"verify_code\": md5code,\n \"cookie\": cookie,\n \"user_info\": {},\n \"posts\": [],\n \"comments\": []\n }\n # insert new user\n user_db.insert(new_user)\n return new_user\n\n\ndef is_verified(cookie):\n '''\n Check the given user is verified.\n '''\n user_db = conn[\"users\"]\n user = user_db.find_one( {\"cookie\": cookie} )\n return user[\"verified\"]\n\n\ndef get_name_by_cookie(cookie):\n '''\n Return user name of the given user_id.\n '''\n if cookie:\n user_db = conn[\"users\"]\n user = user_db.find_one( {\"cookie\": cookie} )\n if user:\n return user[\"username\"]\n else:\n return None\n else:\n return None\n\n\ndef get_user_by_cookie(cookie):\n '''\n Return user by given cookie\n '''\n if cookie:\n user_db = conn[\"users\"]\n user = user_db.find_one( {\"cookie\": cookie} )\n return user\n else:\n return None\n\n\ndef get_user_by_username(username):\n '''\n Check if user exists\n '''\n user_db = conn[\"users\"]\n user = user_db.find_one( {\"username\": username} )\n if user:\n return user\n else:\n return None\n\n\ndef get_user_by_email(email):\n '''\n Return user according to the given email\n '''\n user_db = conn[\"users\"]\n user = user_db.find_one( {\"email\": email} )\n return user\n\ndef verify_account(email, verify_code):\n '''\n Verify user account\n '''\n user_db = conn[\"users\"]\n user = user_db.find_one( {\"email\": email} )\n if user:\n if user[\"verify_code\"] == verify_code:\n user[\"verified\"] = True\n user_db.save(user)\n return True, \"\"\n else:\n return False, \"验证码不正确\"\n else:\n return False, \"用户不存在\"\n\n\ndef insert_post(title, content, author, post_time):\n '''\n Insert a new post, and update user's 'posts'.\n '''\n post_db = conn[\"posts\"]\n user_db = conn[\"users\"] # also need to update user\n post_num = gen_new_post_num() # generate a post num(id)\n post_id = post_db.insert({\n \"post_num\": post_num,\n \"title\": title,\n \"content\": content,\n \"author\": author,\n \"post_time\": post_time,\n \"last_modified\": post_time,\n \"comments\": []\n })\n # update user's post\n user = user_db.find_one( {\"username\": author} )\n user[\"posts\"].append(ObjectId(post_id))\n user_db.save(user)\n\n\ndef fetch_all_posts():\n '''\n Get all posts from database, in reversed order of last_modified\n '''\n post_db = conn[\"posts\"]\n all_posts = post_db.find().sort( [(\"last_modified\", -1)] )\n return all_posts\n\n\ndef gen_new_post_num():\n '''\n Check the number of latest post in database, then generate a new number \n by adding one\n '''\n post_db = conn[\"posts\"]\n all_posts = post_db.find()\n if all_posts.count():\n latest_post = max(all_posts, key=lambda item: item[\"post_time\"])\n new_num = latest_post[\"post_num\"] + 1\n else:\n new_num = 0\n return new_num\n\n\ndef fetch_post_by_num(post_num):\n '''\n Return post according to given number\n '''\n post_db = conn[\"posts\"]\n post = post_db.find_one({\"post_num\": int(post_num)})\n return post\n\n\ndef insert_comment(post, username, content):\n '''\n Insert a comment into a post\n '''\n # update on posts collection\n post_db = conn[\"posts\"]\n comment_time = time.time()\n post[\"comments\"].append({\n \"content\": content,\n \"post_time\": comment_time,\n \"author\": username\n })\n post[\"last_modified\"] = comment_time\n post_db.save(post)\n # update on user collection\n user_db = conn[\"users\"]\n user = get_user_by_username(username)\n user[\"comments\"].append({\n \"post_num\": post[\"post_num\"],\n \"content\": content,\n \"last_modified\": comment_time\n })\n user_db.save(user)\n\n\ndef update_post(post):\n '''\n Save updated post into database\n '''\n post_db = conn[\"posts\"]\n post_db.save(post)\n\n\ndef update_user(user):\n '''\n Save updated user info into database\n '''\n user_db = conn[\"users\"]\n user_db.save(user)\n","sub_path":"db_operations.py","file_name":"db_operations.py","file_ext":"py","file_size_in_byte":5799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"87507547","text":"from bs4 import BeautifulSoup, NavigableString\nfrom urllib.request import urlopen\n\nclass Host:\n\n ALLOWED_KEYS = [\n 'name',\n 'status',\n 'uptime',\n 'users',\n 'load'\n ]\n\n def __init__(self, **kwargs: dict) -> None:\n for k in kwargs:\n if k not in self.ALLOWED_KEYS:\n raise AttributeError\n\n self.name = kwargs.get('name')\n self.status = self.__status(kwargs.get('status'))\n self.uptime = self.__uptime(kwargs.get('uptime'))\n self.users = self.__users(kwargs.get('users'))\n self.load = self.__load(kwargs.get('load'))\n\n def __status(self, status):\n if status == 'up':\n return True\n if status == 'down':\n return False\n\n def __uptime(self, uptime):\n if not '+' in uptime:\n return 0\n else:\n hour = uptime.split('+')[0]\n return int(hour)\n\n def __users(self, users):\n if len(users) == 0:\n return 0\n else:\n return int(users)\n\n def __load(self, load):\n if len(load) == 0:\n return 0.0\n else:\n return float(load)\n\nclass Scraper:\n\n PARSER = 'html.parser'\n\n def __init__(self, url):\n self.url = url\n self.hosts = []\n self.timestamp = ''\n\n def __get_soup(self):\n html = urlopen(self.url)\n soup = BeautifulSoup(html, self.PARSER)\n return soup\n\n def __parse_html(self):\n soup = self.__get_soup()\n rows = soup.find_all('tr')\n\n for _ in rows[0].children:\n time = _.get_text()\n self.timestamp = time\n\n for i in range(3, len(rows)):\n data = []\n for row in rows[i].children:\n if type(row) != NavigableString:\n text = row.get_text()\n data.append(text)\n\n host = Host(name=data[0], status=data[1], uptime=data[2],\n users=data[3], load=data[4])\n self.hosts.append(host)\n\n def get_hosts(self):\n return self.hosts\n\n def get_timestamp(self):\n return self.timestamp\n\n def update(self):\n self.__parse_html()\n","sub_path":"lab/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"316795424","text":"from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup\nfrom telegram.ext import CallbackContext, DispatcherHandlerStop\n\nfrom src import dynamo_db as db\nfrom src.communication.basics import send_markup_msg, edit_message\nfrom src.support.m17n import strings\n\n\ndef delete(update: Update, context: CallbackContext):\n _del_inline_keyboard_buttons = [\n [InlineKeyboardButton(strings()['button:yes'], callback_data='delete#yes')],\n [InlineKeyboardButton(strings()['button:no'], callback_data='delete#no')],\n ]\n\n _callback_query_options = [\n 'delete#yes',\n 'delete#no'\n ]\n\n chat_id = update.effective_chat.id\n if update.callback_query is None or update.callback_query.data not in _callback_query_options:\n reply_markup = InlineKeyboardMarkup(_del_inline_keyboard_buttons)\n send_markup_msg(update, strings()[\"delete:confirm\"], reply_markup, True)\n raise DispatcherHandlerStop\n else:\n if update.callback_query.data == 'delete#yes':\n deleted_user_entries = db.delete_user_entries(chat_id)\n deleted_user_info = db.delete_user_info(chat_id)\n if not deleted_user_entries and not deleted_user_info:\n update.effective_message.delete()\n send_markup_msg(update, strings()['delete:nothing'], ReplyKeyboardMarkup([['/start']],\n resize_keyboard=True,\n one_time_keyboard=True))\n else:\n update.effective_message.delete()\n send_markup_msg(update, strings()['delete:success'], ReplyKeyboardMarkup([['/start']],\n resize_keyboard=True,\n one_time_keyboard=True))\n raise DispatcherHandlerStop\n else:\n edit_message(update, strings()['delete:cancelled'])\n raise DispatcherHandlerStop\n","sub_path":"bot_files/src/handlers/delete_all_data.py","file_name":"delete_all_data.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"215505874","text":"# 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 minDepth(self, root: TreeNode) -> int:\n if not root:\n return 0\n hash_t = {}\n tmp_t = root\n q = [(tmp_t, 1)]\n while len(q):\n x = q.pop(len(q)-1)\n lev = x[1]\n tmp_t = x[0]\n if tmp_t.right:\n q.append((tmp_t.right, lev+1))\n if tmp_t.left:\n q.append((tmp_t.left, lev+1))\n\n if not tmp_t.right and tmp_t.left:\n hash_t.update({x[0]: lev})\n \n\n min_v = min([val for val in hash_t.values()])\n return min_v\n\n\nt1 = TreeNode(1)\nt2 = TreeNode(2)\n\nt1.left = TreeNode(3)\nt1.left.left = TreeNode(5)\nt1.right = TreeNode(2)\n\nt2.left = TreeNode(1)\nt2.right = TreeNode(3)\nt2.left.right = TreeNode(4)\nt2.right.right = TreeNode(7)\n\nprint(Solution().minDepth(t1), ' table 1')","sub_path":"Leetcode/interw_q.py","file_name":"interw_q.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"144147674","text":"import sys, csv, scipy.stats\nfrom collections import defaultdict\n\ndef loadGeneLen(geneLenFile):\n counts = {}\n with open(geneLenFile) as f:\n for line in f:\n gene, l = line.strip().split('\\t')\n counts[gene] = int(l)\n return counts\n\ndef countGenes(countFile):\n counts = defaultdict(dict)\n with open(countFile) as f:\n f.readline()\n for line in f:\n gene, lof, lof_dbnsfp = line.strip().split('\\t')\n counts[gene]['lof'] = int(lof)\n counts[gene]['lof_dbnsfp'] = int(lof_dbnsfp)\n return counts\n\nif __name__ == '__main__':\n fgCountFile, bgCountFile, geneLenFile, outFile = sys.argv[1:]\n totFgSamples = 380\n totBgSamples = 54346\n\n fgGenes = countGenes(fgCountFile)\n bgGenes = countGenes(bgCountFile)\n\n geneLen = loadGeneLen(geneLenFile)\n\n with open(outFile, 'w') as fout:\n print >> fout, 'gene\\tvarType\\tfgCount\\tbgCount\\tpval'\n for gene in fgGenes:\n for varType in fgGenes[gene]:\n bgCount = 0\n if varType in bgGenes[gene]:\n bgCount = bgGenes[gene][varType]\n if gene in geneLen:\n fgSize = totFgSamples * geneLen[gene] - fgGenes[gene][varType]\n bgSize = totBgSamples * geneLen[gene] - bgCount\n (oratio, pval) = scipy.stats.fisher_exact([[fgGenes[gene][varType], fgSize], [bgCount, bgSize]])\n # pval = fisher.pvalue(fgGenes[gene][varType], fgSize,\n # bgGenes[gene][varType],\n # bgSize).right_tail\n else:\n pval = 'NA'\n \n\n ls = [str(x) for x in (gene, varType, fgGenes[gene][varType],\n bgCount, pval)]\n print >> fout, '\\t'.join(ls)\n \n \n","sub_path":"code/enrich.py","file_name":"enrich.py","file_ext":"py","file_size_in_byte":1921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"484576949","text":"# Twisted Imports\nfrom twisted.internet import reactor, defer, error\nfrom twisted.python import failure, log\n\n# System Imports\nfrom time import time as now\nfrom collections import deque\nimport functools\n\n# NumPy\nimport numpy as np\n\n\nclass Event (object):\n\tdef __init__(self):\n\t\tself.handlers = set()\n\n\tdef handle(self, handler):\n\t\tself.handlers.add(handler)\n\t\treturn self\n\n\tdef unhandle(self, handler):\n\t\tself.handlers.discard(handler)\n\t\treturn self\n\n\tdef fire(self, *args, **kargs):\n\t\tfor handler in self.handlers:\n\t\t\thandler(*args, **kargs)\n\n\tdef getHandlerCount(self):\n\t\treturn len(self.handlers)\n\n\t__iadd__ = handle\n\t__isub__ = unhandle\n\t__call__ = fire\n\t__len__ = getHandlerCount\n\n\nclass EventEmitter (object):\n\tdef on (self, name, function = None):\n\t\tdef _on (function):\n\t\t\ttry:\n\t\t\t\tself._events[name]\n\t\t\texcept (TypeError, AttributeError):\n\t\t\t\tself._events = {}\n\t\t\t\tself._events[name] = []\n\t\t\texcept KeyError:\n\t\t\t\tself._events[name] = []\n\n\t\t\t# Use is instead of in to avoid equality comparison\n\t\t\t# (this would create extra expression objects).\n\t\t\tfor f in self._events[name]:\n\t\t\t\tif function is f:\n\t\t\t\t\treturn function\n\n\t\t\tself._events[name].append(function)\n\n\t\t\treturn function\n\n\t\tif function is None:\n\t\t\treturn _on\n\t\telse:\n\t\t\treturn _on(function)\n\n\tdef once (self, name, function = None):\n\t\tdef _once (function):\n\t\t\t@functools.wraps(function)\n\t\t\tdef g (*args, **kwargs):\n\t\t\t\tfunction(*args, **kwargs)\n\t\t\t\tself.off(name, g)\n\n\t\t\treturn g\n\n\t\tif function is None:\n\t\t\treturn lambda function: self.on(name, _once(function))\n\t\telse:\n\t\t\tself.on(name, _once(function))\n\n\tdef off (self, name = None, function = None):\n\t\ttry:\n\t\t\tself._events\n\t\texcept AttributeError:\n\t\t\treturn\n\n\t\t# If no name is passed, remove all handlers\n\t\tif name is None:\n\t\t\tself._events.clear()\n\n\t\t# If no function is passed, remove all functions\n\t\telif function is None:\n\t\t\ttry:\n\t\t\t\tself._events[name] = []\n\t\t\texcept KeyError:\n\t\t\t\tpass\n\n\t\t# Remove handler [function] from [name]\n\t\telse:\n\t\t\tself._events[name].remove(function)\n\n\tdef listeners (self, event):\n\t\ttry:\n\t\t\treturn self._events[event]\n\t\texcept (AttributeError, KeyError):\n\t\t\treturn []\n\t\n\tdef emit (self, _event, **data):\n\t\thandled = False\n\n\t\ttry:\n\t\t\tevents = self._events[_event][:]\n\t\texcept AttributeError:\n\t\t\treturn False # No events defined yet\n\t\texcept KeyError:\n\t\t\tpass\n\t\telse:\n\t\t\thandled |= bool(len(events))\n\n\t\t\tfor function in events:\n\t\t\t\ttry:\n\t\t\t\t\tfunction(data)\n\t\t\t\texcept:\n\t\t\t\t\tlog.err()\n\n\t\ttry:\n\t\t\tevents = self._events[\"all\"][:]\n\t\texcept KeyError:\n\t\t\tpass\n\t\telse:\n\t\t\thandled |= bool(len(events))\n\n\t\t\tfor function in events:\n\t\t\t\ttry:\n\t\t\t\t\tfunction(_event, data)\n\t\t\t\texcept:\n\t\t\t\t\tlog.err()\n\n\t\treturn handled\n\n\ndef timerange (start, interval, step):\n\tif start < 0:\n\t\t\tstart = now() + start\n\n\treturn np.arange(start, start + interval, step, float)\n\n\n\nclass AsyncQueue (object):\n\t@property\n\tdef running (self):\n\t\treturn self._workers > 0\n\n\t@property\n\tdef current (self):\n\t\treturn self._current\n\n\tdef __init__ (self, worker, concurrency = 1, paused = False):\n\t\tself._tasks = deque()\n\t\tself._worker = worker\n\t\tself._workers = 0\n\t\tself._concurrency = concurrency\n\t\tself._paused = int(paused)\n\t\tself._current = set()\n\n\t\tself.drained = Event()\n\n\tdef pause (self):\n\t\tself._paused += 1\n\n\tdef resume (self):\n\t\tself._paused -= 1\n\t\tself._process()\n\n\tdef append (self, data):\n\t\ttask = _AsyncQueueTask(data)\n\t\tself._tasks.append(task)\n\t\treactor.callLater(0, self._process)\n\t\treturn task.d\n\n\tdef appendleft (self, data):\n\t\ttask = _AsyncQueueTask(data)\n\t\tself._tasks.appendleft(task)\n\t\treactor.callLater(0, self._process)\n\t\treturn task.d\n\n\tdef _process (self):\n\t\tif not self._paused and self._workers < self._concurrency:\n\t\t\tdef run (task):\n\t\t\t\tworker_d = defer.maybeDeferred(self._worker, task.data)\n\t\t\t\tworker_d.addCallbacks(success, error)\n\n\t\t\tdef success (result):\n\t\t\t\ttask.d.callback(result)\n\t\t\t\tnext()\n\n\t\t\tdef error (reason):\n\t\t\t\tif reason.type is AsyncQueueRetry:\n\t\t\t\t\trun(task)\n\t\t\t\telse:\n\t\t\t\t\ttask.d.errback(reason)\n\t\t\t\t\tnext()\n\n\t\t\tdef next ():\n\t\t\t\tself._workers -= 1\n\t\t\t\tself._current.discard(task)\n\t\t\t\treactor.callLater(0, self._process)\n\n\t\t\ttry:\n\t\t\t\ttask = self._tasks.popleft()\n\t\t\texcept IndexError:\n\t\t\t\tself.drained()\n\t\t\telse:\n\t\t\t\tself._workers += 1\n\t\t\t\tself._current.add(task)\n\t\t\t\trun(task)\n\n\tdef __len__ (self):\n\t\treturn len(self._tasks)\n\nclass AsyncQueueRetry (Exception):\n\tpass\n\nclass _AsyncQueueTask (object):\n\tdef __init__ (self, data, deferred = None):\n\t\tself.data = data\n\t\tself.d = deferred or defer.Deferred()\n","sub_path":"octopus/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":4458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"639665475","text":"from datetime import datetime, timedelta\nimport datetime\nimport os\nfrom airflow import conf\nfrom airflow import DAG\nfrom airflow.operators.postgres_operator import PostgresOperator\nfrom airflow.operators.dummy_operator import DummyOperator\n\nfrom airflow.operators import (StageToRedshiftOperator, LoadFactOperator, LoadDimensionOperator, DataQualityOperator)\nfrom helpers import SqlQueries\n\n# Default args \ndefault_args = {\n 'owner': 'xingya-zhou',\n 'depends_on_past': False,\n 'start_date': datetime.datetime.now(),\n 'email_on_failure': False,\n 'email_on_retry': False,\n 'retries': 3,\n 'retry_delay': timedelta(minutes=5),\n 'catchup': False,\n 'retry_delay': timedelta(minutes=5)\n}\n\ndag = DAG(\n 'sparkify_dag',\n default_args = default_args,\n start_date = datetime.datetime.now()\n)\n\nf= open(os.path.join(conf.get('core','dags_folder'),'create_tables.sql'))\ncreate_tables_sql = f.read()\n\ncreate_trips_table = PostgresOperator(\n task_id=\"create_trips_table\",\n dag=dag,\n postgres_conn_id=\"redshift\",\n sql=create_tables_sql\n)\n\nstart_operator = DummyOperator(task_id='Begin_execution', dag=dag)\n\nstage_events_to_redshift = StageToRedshiftOperator(\n task_id='Stage_events',\n dag=dag, \n redshift_conn_id=\"redshift\",\n aws_credentials_id=\"aws_credentials\", \n table = \"staging_events\",\n s3_path = \"s3://udacity-dend/log_data\",\n json_path=\"s3://udacity-dend/log_json_path.json\"\n)\n\n\nstage_songs_to_redshift = StageToRedshiftOperator(\n task_id='Stage_songs',\n dag=dag, \n redshift_conn_id=\"redshift\",\n aws_credentials_id=\"aws_credentials\", \n table = \"staging_songs\",\n s3_path = \"s3://udacity-dend/song_data\",\n json_path=\"auto\"\n)\n\n\nload_songplays_table = LoadFactOperator(\n task_id='Load_songplays_fact_table',\n dag=dag, \n redshift_conn_id=\"redshift\",\n table=\"songplays\",\n sql=SqlQueries.songplay_table_insert,\n append_only=False\n)\n\nload_songs_table = LoadDimensionOperator(\n task_id='Load_songs_table',\n dag=dag, \n redshift_conn_id=\"redshift\",\n table=\"songs\",\n sql=SqlQueries.song_table_insert,\n append_only=False\n)\n\n\nload_users_table = LoadDimensionOperator(\n task_id='Load_users_table',\n dag=dag, \n redshift_conn_id=\"redshift\",\n table=\"users\",\n sql=SqlQueries.user_table_insert,\n append_only=False\n)\n\nload_artists_table = LoadDimensionOperator(\n task_id='Load_artists_table',\n dag=dag, \n redshift_conn_id=\"redshift\",\n table=\"artists\",\n sql=SqlQueries.artist_table_insert,\n append_only=False\n)\n\nload_time_table = LoadDimensionOperator(\n task_id='Load_time_table',\n dag=dag, \n redshift_conn_id=\"redshift\",\n table=\"time\",\n sql=SqlQueries.time_table_insert,\n append_only=False\n)\n\n\nrun_quality_checks = DataQualityOperator(\n task_id='Run_data_quality_checks',\n dag=dag,\n redshift_conn_id=\"redshift\",\n tables=[ \"songplays\", \"songs\", \"artists\", \"time\", \"users\"]\n)\n\nend_operator = DummyOperator(task_id='Stop_execution', dag=dag)\n\nstart_operator \\\n >> create_trips_table \\\n >> [stage_events_to_redshift, stage_songs_to_redshift] \\\n >> load_songplays_table \\\n >> [ load_songs_table, load_artists_table, load_time_table, load_users_table] \\\n >> run_quality_checks \\\n >> end_operator\n\n \n\n \n","sub_path":"airflow/dags/sparkify_dag.py","file_name":"sparkify_dag.py","file_ext":"py","file_size_in_byte":3303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"85931122","text":"#!/usr/bin/env python\nimport barcode\nfrom barcode.writer import ImageWriter\nfrom docx import Document\nfrom docx.enum.text import WD_ALIGN_PARAGRAPH\nfrom docx.shared import Cm\nfrom egcg_core.config import cfg\n\nfrom EPPs.common import SendMailEPP\n\n\nclass GenerateTrackingLetter(SendMailEPP):\n '''Automatically generates the tracking letter sent to customers for tube shipments by populating a word template\n with a 128 format barcode containing the container name'''\n\n _max_nb_project = 1\n\n\n # additional argument required to obtain the file location for newly created tracking letter in the LIMS step\n def __init__(self, argv=None):\n super().__init__(argv)\n self.letter = self.cmd_args.letter\n\n @staticmethod\n def add_args(argparser):\n argparser.add_argument(\n '-t', '--letter', type=str, required=True, help='Tracking letter generated by the LIMS'\n )\n\n def _run(self):\n\n # obtain all of the inputs for the step\n all_inputs = self.artifacts\n\n # 96 well plate so don't need tracking letter\n if all_inputs[0].container.type.name == \"96 well plate\":\n return 0\n\n EAN = barcode.get_barcode_class('code128')\n\n ean = EAN(all_inputs[0].container.name, writer=ImageWriter())\n save_options = {'font_size': 20,\n 'text_distance': 2,\n 'module_height': 15,\n 'module_width': 0.3}\n ean.save('code128', options=save_options)\n\n document = Document(cfg.query('file_templates', 'tracking_letter'))\n\n for paragraph in document.paragraphs:\n if 'The barcode(s) above provides confirmation' in paragraph.text:\n p = paragraph.insert_paragraph_before('')\n p = p.insert_paragraph_before('')\n p.alignment = WD_ALIGN_PARAGRAPH.CENTER\n r = p.add_run()\n r.add_picture('code128.png', width=Cm(5))\n\n document.save(self.letter + '-Edinburgh_Genomics_Sample_Tracking_Letter_' + self.projects[0].name + '.docx')\n\n\nif __name__ == '__main__':\n GenerateTrackingLetter().run()\n","sub_path":"scripts/create_sample_tracking_letter.py","file_name":"create_sample_tracking_letter.py","file_ext":"py","file_size_in_byte":2145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"406423597","text":"\"\"\"\nNOAA ISD Lite import routine\n\nGet hourly weather data for weather stations worldwide.\n\nThe code is licensed under the MIT license.\n\"\"\"\n\nimport os\nfrom sys import argv\nfrom datetime import datetime\nfrom io import BytesIO\nfrom ftplib import FTP\nimport gzip\nimport pandas as pd\nfrom routines import Routine\nfrom routines.convert import ms_to_kmh, temp_dwpt_to_rhum\nfrom routines.schema import hourly_global\n\n# Configuration\nMODE = argv[1]\nSTATIONS_PER_CYCLE = 1 if MODE == 'recent' else 4\nUSAF_WBAN_PATH = os.path.abspath(\n os.path.join(\n os.path.dirname(__file__),\n '../../..',\n 'resources')) + '/usaf_wban.csv'\nCURRENT_YEAR = datetime.now().year\n\n# Required columns\nusecols = [0, 1, 2, 3, 4, 5, 6, 7, 8, 10]\n\n# Column names\nNAMES = ['time', 'temp', 'dwpt', 'pres', 'wdir', 'wspd', 'prcp']\n\n# Create new task\ntask = Routine('import.noaa.hourly.global')\n\n# Get counter value\ncounter = task.get_var('station_counter_' + MODE)\nskip = 0 if counter is None else int(counter)\n\n# Get year\nif MODE == 'historical':\n year = task.get_var('year')\n year = 1901 if year is None else int(year)\n\n# Get ISD Lite stations\ntry:\n stations = pd.read_csv(\n USAF_WBAN_PATH,\n dtype='str',\n skiprows=skip,\n nrows=STATIONS_PER_CYCLE,\n names=[\n 'id',\n 'usaf',\n 'wban'])\nexcept pd.errors.EmptyDataError:\n stations = None\n pass\n\n# Update counter\nif stations is None or len(stations.index) < STATIONS_PER_CYCLE:\n # Reset counter\n task.set_var('station_counter_' + MODE, 0)\n # Reset year\n if MODE == 'historical':\n if year >= CURRENT_YEAR - 2:\n task.set_var('year', 1901)\n else:\n task.set_var('year', year + 1)\n exit()\nelse:\n task.set_var('station_counter_' + MODE, skip + STATIONS_PER_CYCLE)\n\n# Connect to NOAA FTP Server\nftp = FTP('ftp.ncdc.noaa.gov')\nftp.login()\n\n# Get list of years\nif MODE == 'recent':\n years = range(CURRENT_YEAR - 1, CURRENT_YEAR + 1)\nelse:\n years = range(year, year + 1)\n\n# Import data for each weather station\nfor station in stations.to_dict(orient='records'):\n\n for year in years:\n\n try:\n\n ftp.cwd('/pub/data/noaa/isd-lite/' + str(year))\n\n filename = station[\"usaf\"] + '-' + \\\n station[\"wban\"] + '-' + str(year) + '.gz'\n\n if filename in ftp.nlst():\n\n # Download file\n local_file = os.path.dirname(__file__) + os.sep + filename\n ftp.retrbinary(\n \"RETR \" + filename,\n open(\n local_file,\n 'wb').write)\n\n # Unzip file\n file = gzip.open(local_file, 'rb')\n raw = file.read()\n file.close()\n\n # Remove .gz file\n os.remove(local_file)\n\n df = pd.read_fwf(\n BytesIO(raw),\n parse_dates={\n 'time': [\n 0,\n 1,\n 2,\n 3]},\n na_values=-\n 9999,\n header=None,\n usecols=usecols)\n\n # Rename columns\n df.columns = NAMES\n\n # Adapt columns\n df['temp'] = df['temp'].div(10)\n df['dwpt'] = df['dwpt'].div(10)\n df['pres'] = df['pres'].div(10)\n df['wspd'] = df['wspd'].div(10).apply(ms_to_kmh)\n df['prcp'] = df['prcp'].div(10)\n\n # Calculate humidity data\n df['rhum'] = df.apply(\n lambda row: temp_dwpt_to_rhum(row), axis=1)\n\n # Drop dew point column\n df = df.drop('dwpt', axis=1)\n\n # Add station column\n df['station'] = station['id']\n\n # Set index\n df = df.set_index(['station', 'time'])\n\n # Round decimals\n df = df.round(1)\n\n # Write data into Meteostat database\n task.write(df, hourly_global)\n\n except BaseException:\n\n pass\n\n# Quit FTP connection\nftp.quit()\n","sub_path":"import/noaa/hourly/global.py","file_name":"global.py","file_ext":"py","file_size_in_byte":4269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"464560152","text":"#Reddit challenge 18\n'''Create a program that translates telephone number words into their\nrespective numbers'''\n\n\n\ndef numtranslate(phonenumber):\n translated = ''\n trans = {'a': 2, 'c': 2, 'b': 2, 'e': 3, 'd': 3, 'g': 4, 'f': 3,\n 'i': 4, 'h': 4, 'k': 5, 'j': 5, 'm': 6, 'l': 5, 'o': 6,\n 'n': 6, 'q': 7, 'p': 7, 's': 7, 'r': 7, 'u': 8, 't': 8,\n 'w': 9, 'v': 8, 'y': 9, 'x': 9, 'z': 9, '-':'-', ' ':' '}\n for letter in phonenumber:\n if letter in trans:\n translated += str(trans[letter])\n else:\n translated += letter\n\n return translated\n\nprint(numtranslate(\"1-800-call-today\"))\n","sub_path":"Easy_Challenges/Easy11to20/easy18.py","file_name":"easy18.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"450834816","text":"#!/usr/bin/python2\n# -*- coding: utf-8 -*-\n# @Time : 3/21/18 3:54 PM\n# @Author : Zhou Run Ze\n# @FileName: superEM2.py\n# @Software: PyCharm\nimport sys\nimport os\nsys.path.append(os.getenv('FARADAYPATH')+'/FaradayEDA/Src/FaradayPython/PythonMain')\nfrom MainFunction import *\n\n# inputpar = os.path.abspath(sys.argv[1])\ninputpar = '/home/zhourz/Documents/test/Microstrip_Radial_Stub_py.py'\n\ninputpardir = os.path.dirname(inputpar)\nsys.path.append(inputpardir)\nosw = os.walk(inputpardir)\nfor top, dirs, nondirs in osw:\n for nondir in nondirs:\n if nondir[-3:] == '.py':\n if os.path.join(inputpardir, nondir) == inputpar:\n continue\n elif nondir.find('superEM') > -1:\n continue\n else:\n # exec(\"from %s import *\" % nondir.split('.')[0])\n exec(\"from %s import %s\" % (nondir.split('.')[0], nondir.split('.')[0]))\n\nexecfile(inputpar)\n","sub_path":"Src/FaradayPython/PythonMain/superEM2.py","file_name":"superEM2.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"136888270","text":"\"\"\"\n FileParser.py - implementation of input file parser\n Using XML version of input data would be probably easier, but you need\n to find it prior to writing vast and complicated text parser\n\"\"\"\nfrom typing import Any, Dict, List, Tuple\n\n\ndef parse(file_name: str) -> (List[Dict[str, Any]], List[Dict[str, Any]], List[Dict[str, Any]], List[Dict[str, Any]]):\n \"\"\"\n Parse text file with network description\n\n @param file_name - path to input text file\n returns dicts - nodes, links, demands, paths\n \"\"\"\n with open(file_name, 'r') as f:\n text = f.read().split()\n\n nodes = []\n links = []\n demands = []\n paths = []\n\n i = 0\n while i < len(text):\n if text[i] == 'LINKS':\n i += 2 # skip open bracket\n while text[i] != ')':\n name = text[i]\n source = text[i + 2]\n target = text[i + 3]\n i += 10\n\n module_capacities = []\n module_costs = []\n while text[i] != ')':\n module_capacities.append(float(text[i]))\n module_costs.append(float(text[i + 1]))\n i += 2\n\n links.append({\n 'name': name,\n 'source': source,\n 'target': target,\n 'moduleCap': module_capacities,\n 'moduleCost': module_costs\n })\n i += 1 # skip link-end close bracket\n elif text[i] == 'DEMANDS':\n i += 2 # skip open bracket\n while text[i] != ')':\n name = text[i]\n source = text[i + 2]\n target = text[i + 3]\n demand_value = float(text[i + 6])\n\n max_path_length = float('inf')\n if text[i + 7] != 'UNLIMITED':\n max_path_length = float(text[i + 7])\n\n demands.append({\n 'name': name,\n 'source': source,\n 'target': target,\n 'value': demand_value,\n 'maxLen': max_path_length\n })\n i += 8\n elif text[i] == 'ADMISSIBLE_PATHS':\n i += 2 # skip open bracket\n while text[i] != ')':\n name = text[i]\n i += 2 # skip open bracket\n\n part = []\n while text[i] != ')':\n i += 2 # skip path name and open bracket\n\n path = []\n while text[i] != ')':\n path.append(text[i])\n i += 1\n\n part.append(path)\n i += 1 # skip path-end close bracket\n i += 1 # skip demand-end close bracket\n paths.append({\n 'name': name,\n 'paths': part\n })\n elif text[i] == 'NODES':\n i += 2\n while text[i] != ')':\n name = text[i]\n lon = float(text[i + 2])\n lat = float(text[i + 3])\n\n nodes.append({\n 'name': name,\n 'lon': lon,\n 'lat': lat,\n })\n i += 5\n i += 1\n\n return nodes, links, demands, paths\n\n\ndef loadSolution(file_name: str) -> Tuple[Dict[str, Any], Dict[str, Any]]:\n \"\"\"\n Load network solution provided in form of XML file. The specification of format\n can be found on SNDlib home page.\n Return the number of modules added to each link and routing for each demand\n \"\"\"\n try:\n from lxml import etree as et\n except ImportError:\n print(\"[-] Failed to load solution - lxml module is not installed !!!\")\n raise # Hard to say what should be returned in such case - raise exception anyway\n\n linksModules = {}\n demandsFlows = {}\n\n tree = et.parse(file_name)\n root = tree.getroot()\n for topGroup in root:\n if topGroup.tag == '{http://sndlib.zib.de/solution}linkConfigurations':\n for linkConfiguration in topGroup:\n linkID = linkConfiguration.attrib['linkId']\n\n if len(linkConfiguration) > 0:\n instModules = linkConfiguration[0]\n capacity = float(instModules.find('{http://sndlib.zib.de/solution}capacity').text)\n count = float(instModules.find('{http://sndlib.zib.de/solution}installCount').text)\n else:\n capacity = 0\n count = 0\n\n linksModules[linkID] = {\n 'capacity': capacity,\n 'count': count\n }\n elif topGroup.tag == '{http://sndlib.zib.de/solution}demandRoutings':\n for demandRouting in topGroup:\n demandID = demandRouting.get('demandId')\n\n flows = []\n for flowPath in demandRouting:\n value = float(flowPath.find('{http://sndlib.zib.de/solution}flowPathValue').text)\n path = []\n for link in flowPath.find('{http://sndlib.zib.de/solution}routingPath'):\n path.append(link.text)\n flows.append((value, path))\n demandsFlows[demandID] = flows\n else:\n raise KeyError(f'Unknown XML tag found in solution file - \"{topGroup.tag}\"')\n\n return linksModules, demandsFlows\n\n\ndef saveSolution(fileName: str, linksModules: Dict[str, Any], demandsFlows: Dict[str, Any]):\n \"\"\"\n Save computed solution to XML file compatible with SNDlib platform\n linksModules must be of form:\n {'LINK_0_1': {'capacity': 4.0, 'count': 2.0}, ...}\n demandsFlows must be of form:\n {'Demand_0_1': [(127.0, ['Link_1', 'Link_2', ...])], ...}\n \"\"\"\n try:\n from lxml import etree as et\n except ImportError:\n print(\"[-] Failed to save solution - lxml module is not installed !!!\")\n return\n\n root = et.Element(\"solution\")\n root.attrib['xmlns'] = 'http://sndlib.zib.de/solution'\n root.attrib['version'] = '1.0'\n\n linkConfigs = et.Element('linkConfigurations')\n for linkName in linksModules:\n linkModules = linksModules[linkName]\n\n linkConfig = et.Element('linkConfiguration')\n linkConfig.attrib['linkId'] = linkName\n\n if linkModules['count'] > 0:\n instModules = et.Element('installedModule')\n capacity = et.Element('capacity')\n count = et.Element('installCount')\n\n capacity.text = str(linkModules['capacity'])\n count.text = str(linkModules['count'])\n instModules.append(capacity)\n instModules.append(count)\n linkConfig.append(instModules)\n\n linkConfigs.append(linkConfig)\n root.append(linkConfigs)\n\n demandRoutings = et.Element('demandRoutings')\n demandRoutings.attrib['state'] = 'NOS'\n for demandName in demandsFlows:\n flows = demandsFlows[demandName]\n\n demandRouting = et.Element('demandRouting', demandId=demandName)\n for flow in flows:\n flowPath = et.Element('flowPath')\n flowPathValue = et.Element('flowPathValue')\n flowPathValue.text = str(flow[0])\n\n routingPath = et.Element('routingPath')\n for linkName in flow[1]:\n link = et.Element('linkId')\n link.text = linkName\n routingPath.append(link)\n flowPath.append(flowPathValue)\n flowPath.append(routingPath)\n\n demandRouting.append(flowPath)\n demandRoutings.append(demandRouting)\n root.append(demandRoutings)\n\n et = et.ElementTree(root)\n et.write(fileName, pretty_print=True, xml_declaration=True, encoding='UTF-8')\n","sub_path":"src/FileParser.py","file_name":"FileParser.py","file_ext":"py","file_size_in_byte":7843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"595540508","text":"import numpy as np\nimport random\n\nclass NeuralNetwork2:\n def __init__(self, layer_size, bit_representation , input_size, delta_cycle_nn):\n self.num_layers = len(layer_size)\n self.layer_size = layer_size\n self.recurrent_input = [0,0,0,0]\n self.bit_representation = bit_representation\n self.input_size = input_size\n self.delta_cycle_nn = delta_cycle_nn\n\n def calculate(self, initial_input, gene, cycle_num):\n # deduct half of the maximum value stored by bits to go negative\n half_max = sum(2 ** (np.arange(self.bit_representation))) // 2\n layer_input = self.decay_distance(np.array(initial_input).clip(0))\n layer_input.extend(self.recurrent_input)\n # Needed to select layer weights from gene\n gene_pointer = [0, 0]\n for layer_size in self.layer_size:\n input_size = len(layer_input)\n gene_pointer[1] += input_size * layer_size * self.bit_representation + layer_size * self.bit_representation\n\n layer_bits = np.array(gene[gene_pointer[0]:gene_pointer[1]])\n bit_weights = layer_bits[:-(layer_size * self.bit_representation)].reshape(layer_size, input_size,self.bit_representation)\n bit_biases = layer_bits[-(layer_size * self.bit_representation):].reshape(layer_size, self.bit_representation)\n layer_biases = bit_biases.dot(2 ** np.arange(self.bit_representation)[::-1])\n layer_weights = bit_weights.dot(2 ** np.arange(self.bit_representation)[::-1]).T\n\n layer_weights = (layer_weights - half_max) / 10\n layer_biases = (layer_biases - half_max) / 10\n\n\n gene_pointer[0] = gene_pointer[1]\n layer_input = np.dot(layer_input, layer_weights) + layer_biases\n layer_input = self.sigmoid_activation(layer_input)\n\n ##### Experiment with different cycle numbers #####\n if cycle_num % self.delta_cycle_nn == 0 and layer_size == 4:\n self.recurrent_input = layer_input\n\n\n return layer_input\n\n def sigmoid_activation(self, input):\n return 1 / (1 + np.exp(-input))\n\n def create_genomes(self, num_individuals):\n num_bits = 0\n # Include recurrent part\n input_size = self.input_size + self.layer_size[0]\n for layer in self.layer_size:\n # Weights #Biases\n num_bits += input_size * layer * self.bit_representation + layer * self.bit_representation\n input_size = layer\n\n genomes = np.zeros((num_individuals, num_bits), dtype=int)\n # Random initialization\n for genome in genomes:\n for i in range(num_bits):\n genome[i] = random.randint(0, 1)\n\n return genomes\n\n def decay_distance(self,initial_intput):\n A = 20\n alpha = 0.1\n t = 5\n return list(A + (A * alpha - A) * (1 - np.exp(-np.array(initial_intput) / t)))\n\n","sub_path":"NeuralNetwork.py","file_name":"NeuralNetwork.py","file_ext":"py","file_size_in_byte":2962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"273992088","text":"import pandas as pd\nfrom pandas import DataFrame\nimport numpy as np\nimport matplotlib.dates as mdates\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nimport re\nimport scipy.stats as stats\n\narr = []\ny_arr = []\n\n# Read CSV\ndf = pd.read_csv('./potato_rates.csv')\n# Change values to float\ndf['Modal Price'] = df['Modal Price'].astype('float')\ndf['Max Price'] = df['Max Price'].astype('float')\ndf['Min Price'] = df['Min Price'].astype('float')\ndf['Price Date'] = df['Price Date'].astype('string')\n\n# Select only 2016 data\n# df = df[df['Price Date'].str.contains('-16')]\n\n\ndef it(a, b):\n x = (b-1)*7\n x = 1 if(x==0) else x\n return str(a)+\"-\"+str(x).zfill(3)\n\n\n# Convert Rs/kg\ndf['Modal Price'] = np.divide(df['Modal Price'], 100)\ndf['Max Price'] = np.divide(df['Max Price'], 100)\ndf['Min Price'] = np.divide(df['Min Price'], 100)\ndf['Price Date'] = pd.to_datetime(df['Price Date'])\n\n\ntimes = pd.DatetimeIndex(df['Price Date'])\ndf = DataFrame({\"Modal Price\": df.groupby([times.year])['Modal Price'].mean()}).reset_index()\n# print df\n# exit()\n# df['Date'] = pd.Series(pd.to_datetime(map(it, df['index']), format='%Y-%j'))\n\n\nfig = plt.figure()\nfig.suptitle('Potato', fontsize=14)\nplt.scatter(df['index'], df['Modal Price'])\n# plt.plot_date(df['index'], df['Modal Price'])\nplt.show()\n\n# print df['Price Date']\n","sub_path":"rate_analysis/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"489895082","text":"# n = int(input())\n# ll = []\n# for i in range(n):\n# ele = int(input())\n# ll.append(ele)\n# position = int(input())\n# def deleteNode(ll,pos):\n# ll.pop(pos)\n# return ll\n# new_ll = deleteNode(ll,position)\n# for i in new_ll:\n# print(i, end = \" \")\nclass Node:\n\n # Function to initialise the node object\n def __init__(self, data):\n self.data = data # Assign data\n self.next = None # Initialize next as null\n\n\n# Linked List class contains a Node object\nclass LinkedList:\n\n # Function to initialize head\n def __init__(self):\n self.head = None\n\n # Appends a new node at the end. This method is\n # defined inside LinkedList class shown above */\n def append(self, new_data):\n\n # 1. Create a new node\n # 2. Put in the data\n # 3. Set next as None\n new_node = Node(new_data)\n\n # 4. If the Linked List is empty, then make the\n # new node as head\n if self.head is None:\n self.head = new_node\n return\n\n # 5. Else traverse till the last node\n last = self.head\n while (last.next):\n last = last.next\n\n # 6. Change the next of last node\n last.next = new_node\n\n # Utility function to print the linked list\n\n def deleteNode(self, position):\n\n # If linked list is empty\n if self.head == None:\n return\n\n # Store head node\n temp = self.head\n\n # If head needs to be removed\n if position == 0:\n self.head = temp.next\n temp = None\n return\n\n # Find previous node of the node to be deleted\n for i in range(position - 1):\n temp = temp.next\n if temp is None:\n break\n\n # If position is more than number of nodes\n if temp is None:\n return\n if temp.next is None:\n return\n\n # Node temp.next is the node to be deleted\n # store pointer to the next of node to be deleted\n next = temp.next.next\n\n # Unlink the node from linked list\n temp.next = None\n\n temp.next = next\n\n def printList(self):\n temp = self.head\n while (temp):\n print(temp.data, end = \" \")\n temp = temp.next\n\nll = LinkedList()\nn = int(input())\nfor i in range(n):\n ele = int(input())\n ll.append(ele)\nposition = int(input())\nll.deleteNode(position)\nll.printList()\n","sub_path":"Data Structure-Task-cns-atcoder/Delimiters/semester_task/delete_from_LL_06.03.2020.py","file_name":"delete_from_LL_06.03.2020.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"527588282","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim:fenc=utf-8\n#\n# Copyright © Her Majesty the Queen in Right of Canada, as represented\n# by the Minister of Statistics Canada, 2019.\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# Example for building a complete Artemis job\n\n# Tools\nfrom artemis.tools.csvtool import CsvTool\nfrom artemis.tools.filtercoltool import FilterColTool\nfrom artemis.tools.tdigesttool import TDigestTool\nfrom artemis.tools.xlstool import XlsTool\n\n# Algorithms\nfrom artemis.algorithms.dummyalgo import DummyAlgo1\nfrom artemis.algorithms.csvparseralgo import CsvParserAlgo\nfrom artemis.algorithms.filteralgo import FilterAlgo\nfrom artemis.algorithms.profileralgo import ProfilerAlgo\n\n# Other requirements\nimport dask.delayed\nimport tempfile\nimport uuid\nimport urllib.parse\nimport logging\nimport click\nimport os\n\nfrom artemis.configurables.configurable import MenuBuilder\nfrom artemis.distributed.job_builder import runjob\nfrom artemis.generators.simutablegen import SimuTableGen\nfrom artemis.io.protobuf.configuration_pb2 import Configuration\nfrom artemis.io.protobuf.cronus_pb2 import (MenuObjectInfo, ConfigObjectInfo,\n TableObjectInfo, DatasetObjectInfo)\nfrom artemis.io.protobuf.table_pb2 import Table\nfrom artemis.io.filehandler import FileHandlerTool\nfrom artemis.io.writer import BufferOutputWriter\nfrom artemis.meta.cronus import BaseObjectStore\nfrom artemis.meta.Directed_Graph import Directed_Graph, Node\nfrom artemis.core.book import TDigestBook\n\nfrom artemis.dq.plotlytool import PlotlyTool\n# Validation/graphing code requirements\nimport numpy as np\nimport sys\nimport time\nimport matplotlib.pyplot as plt\n\nfrom artemis.externals.tdigest.tdigest import TDigest\nfrom scipy import interpolate\nfrom scipy.stats import norm\nfrom scipy import interpolate\nfrom plotly.subplots import make_subplots\nimport plotly.graph_objects as go\n# ------------------------------------------\n\nlogging.getLogger().setLevel(logging.INFO)\ndef example_configuration(table_id, seed=42):\n # First define a data generator using SimuTable\n\n max_malloc = 2147483648 # Maximum memory allowed in Arrow memory pool\n max_buffer_size = 2147483648 # Maximum size serialized ipc message\n write_csv = True # Output csv files for each arrow output file\n sample_ndatums = 1 # Preprocess job to sample files from dataset\n sample_nchunks = 10 # Preprocess job to sample chunks from a file\n linesep = '\\r\\n' # Line delimiter to scan for on csv input\n delimiter = \",\" # Field delimiter\n blocksize = 2**16 # Size of chunked data in-memory\n header = '' # Predefined header\n footer = '' # Predefined footer\n header_offset = 0 # N bytes to scan past header\n footer_size = 0 # N bytes size of footer\n schema = [] # Predefined list of field names on input\n encoding = 'utf8' # encoding\n gen_nbatches = 5 # Number of batches to generator\n gen_nrows = 1000 # Number of rows per batch\n\n config = Configuration() # Cronus Configuration message\n config.uuid = str(uuid.uuid4())\n config.name = f\"{config.uuid}.config.pb\"\n config.max_malloc_size_bytes = max_malloc\n\n generator = SimuTableGen('generator',\n nbatches=gen_nbatches,\n num_rows=gen_nrows,\n file_type=1, # Output type cronus.proto filetype\n table_id=table_id,\n seed=seed)\n\n # Set the generator configuration\n config.input.generator.config.CopyFrom(generator.to_msg())\n\n filehandler = FileHandlerTool('filehandler',\n filetype='csv', # TBD use filetype metadata\n blocksize=blocksize,\n delimiter=delimiter,\n linesep=linesep,\n header=header,\n footer=footer,\n header_offset=header_offset,\n footer_size=footer_size,\n schema=schema,\n encoding=encoding,\n seed=seed)\n # Add to the tools\n config.tools[filehandler.name].CopyFrom(filehandler.to_msg())\n\n csvtool = CsvTool('csvtool', block_size=(2 * blocksize))\n config.tools[csvtool.name].CopyFrom(csvtool.to_msg())\n\n filtercoltool = FilterColTool('filtercoltool',\n columns=['record-id', 'SIN', 'DOB'])\n config.tools[filtercoltool.name].CopyFrom(filtercoltool.to_msg())\n \n writer = BufferOutputWriter('bufferwriter',\n BUFFER_MAX_SIZE=max_buffer_size,\n write_csv=write_csv)\n config.tools[writer.name].CopyFrom(writer.to_msg())\n \n tdigesttool = TDigestTool('tdigesttool')\n config.tools[tdigesttool.name].CopyFrom(tdigesttool.to_msg())\n\n sampler = config.sampler\n sampler.ndatums = sample_ndatums\n sampler.nchunks = sample_nchunks\n\n return config\n\n\nclass ExampleMenu(MenuBuilder):\n def __init__(self, name='test'):\n super().__init__(name)\n\n def _algo_builder(self):\n '''\n define all algorithms required\n '''\n self._algos['testalgo'] = DummyAlgo1('dummy',\n myproperty='ptest',\n loglevel='WARNING')\n self._algos['csvalgo'] = CsvParserAlgo('csvparser', loglevel='WARNING')\n self._algos['filteralgo'] = FilterAlgo('filter',\n loglevel='WARNING')\n self._algos['profileralgo'] = ProfilerAlgo('profiler',\n loglevel='WARNING')\n\n def _seq_builder(self):\n # Define the sequences and node names\n self._seqs['seqX'] = Node([\"initial\"],\n ('csvparser',),\n \"seqX\")\n self._seqs['seqY'] = Node([\"seqX\"],\n ('filter',),\n \"seqY\")\n self._seqs['seqA'] = Node(['seqX'],\n ('profiler'),\n 'seqA')\n self._seqs['seqB'] = Node(['seqY'],\n ('dummy'),\n 'seqB')\n\n def _chain_builder(self):\n # Add the sequences to a chain\n self._chains['csvchain'] = Directed_Graph(\"csvchain\")\n self._chains['csvchain'].add(self._seqs['seqX'])\n self._chains['csvchain'].add(self._seqs['seqY'])\n self._chains['csvchain'].add(self._seqs['seqA'])\n self._chains['csvchain'].add(self._seqs['seqB'])\n\n@click.command()\n@click.option('--location', required = True, prompt = True, help = 'Path to .xlsx')\ndef example_job(location):\n # Artemis Job requirements\n # BaseObjectStore - name, path and id\n # Menu\n # Configuration\n # Input Dataset\n # Dataset partitions\n # Table schemas for each dataset partition\n\n # Build the Menu\n mb = ExampleMenu()\n msgmenu = mb.build()\n menuinfo = MenuObjectInfo()\n menuinfo.created.GetCurrentTime()\n\n # Read schema and generator names\n xlstool = XlsTool('xlstool', location=location)\n ds_schema = xlstool.execute(location)\n # Example job only have one table\n table = ds_schema.tables[0]\n \n # Build the Configuration\n\n # Build the partition Table schemas\n\n # Register all inputs in the Cronus object store\n\n # Build the job\n # To use the local directory:\n # dirpath = os.getcwd()\n with tempfile.TemporaryDirectory() as dirpath:\n # All jobs now require an object store\n # All outputs are pesisted in the object store path\n # See github.com/mbr/simplekv\n # Factory class for simplekv provided by\n # blueyonder/storefact\n store = BaseObjectStore(dirpath, 'artemis')\n\n # Requires registering an parent dataset\n # Generator data is written to disk with\n # The parent dataset uuid\n # Register the 'generator' partition -- required\n\n g_dataset = store.register_dataset()\n store.new_partition(g_dataset.uuid, 'generator')\n job_id = store.new_job(g_dataset.uuid)\n\n # The table schema which defines the model for the generator\n # Persisted first to the object store\n # protobuf file\n tinfo = TableObjectInfo()\n table_id = store.register_content(table,\n tinfo,\n dataset_id=g_dataset.uuid,\n job_id=job_id,\n partition_key='generator').uuid\n\n store.save_store()\n\n # Now configure all tools and algorithms\n # Includes IO tools\n config = example_configuration(table_id)\n\n # Algorithms need to added from the menu to the configuration\n for key in mb._algos:\n msg = config.algos.add()\n msg.CopyFrom(mb._algos[key].to_msg())\n\n configinfo = ConfigObjectInfo()\n configinfo.created.GetCurrentTime()\n\n # Store the menu and configuration protobufs\n menu_uuid = store.register_content(msgmenu, menuinfo).uuid\n config_uuid = store.register_content(config, configinfo).uuid\n\n # Register an output dataset\n dataset = store.register_dataset(menu_id=menu_uuid,\n config_id=config_uuid)\n #Copy metadata from xlstool\n store[dataset.uuid].dataset.aux.CopyFrom(ds_schema.dataset.aux)\n store.save_store()\n\n # Now define the actual Artemis job\n # Again the input is a protobuf\n # All other information read in from the\n # object store\n inputs = store.list(prefix=g_dataset.uuid)\n\n ds_results = []\n for _ in range(2):\n job_id = store.new_job(dataset.uuid)\n config = Configuration()\n store.get(config_uuid, config)\n for p in config.input.generator.config.properties.property:\n if p.name == 'glob':\n p.value = dirpath.split('.')[-2]+'csv'\n store._put_message(config_uuid, config)\n store.get(config_uuid, config)\n\n ds_results.append(runjob(dirpath,\n store.store_name,\n store.store_uuid,\n menu_uuid,\n config_uuid,\n dataset.uuid,\n g_dataset.uuid,\n str(job_id)))\n\n results = dask.compute(*ds_results, scheduler='single-threaded')\n store.new_partition(dataset.uuid, 'seqA')\n store.new_partition(dataset.uuid, 'seqB')\n store.save_store()\n for buf in results:\n ds = DatasetObjectInfo()\n ds.ParseFromString(buf)\n store.update_dataset(dataset.uuid, buf)\n\n store.save_store()\n \n dqtool = PlotlyTool(store=store, uuid=dataset.uuid)\n dqtool.visualize(output=\"{}/test\".format(os.getcwd()),show=True,check=False)\n\nif __name__ == '__main__':\n example_job()\n","sub_path":"examples/distributed_dq_example.py","file_name":"distributed_dq_example.py","file_ext":"py","file_size_in_byte":11898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"146517901","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn import init\n\nclass conv_block(nn.Module):\n def __init__(self, ch_in, ch_out, k_size=3):\n super(conv_block,self).__init__()\n self.conv = nn.Sequential(\n nn.Conv2d(ch_in, ch_out, kernel_size=k_size,padding=k_size // 2,bias=False),\n nn.GroupNorm(ch_out//16, ch_out),\n nn.ReLU(inplace=True),\n nn.Conv2d(ch_out, ch_out, kernel_size=3,stride=1,padding=1,bias=False),\n nn.GroupNorm(ch_out//16, ch_out)\n )\n\n self.ident = nn.Sequential(\n nn.Conv2d(ch_in, ch_out, kernel_size=1,stride=1,padding=0,bias=False)\n )\n self.out = nn.Sequential(\n nn.ReLU(inplace=True)\n )\n\n\n def forward(self,x):\n res = self.conv(x)\n ident = self.ident(x)\n return self.out(res + ident)\n\nclass up_conv(nn.Module):\n def __init__(self, ch_in, ch_out):\n super(up_conv,self).__init__()\n self.up = nn.Sequential(\n nn.Upsample(scale_factor=2),\n nn.Conv2d(ch_in,ch_out,kernel_size=3,stride=1,padding=1,bias=False),\n nn.GroupNorm(ch_out//16, ch_out),\n nn.ReLU(inplace=True),\n )\n\n def forward(self,x):\n x = self.up(x)\n return x\n\nclass UNet(nn.Module):\n def __init__(self, img_ch=3, output_ch=1):\n super(UNet, self).__init__()\n \n self.Maxpool = nn.MaxPool2d(kernel_size=2,stride=2)\n \n ch_num = [128, 128, 128, 128, 128, 128, 256]\n \n self.Conv1 = conv_block(ch_in=img_ch,ch_out=ch_num[0], k_size=7)\n self.Conv2 = conv_block(ch_in=ch_num[0],ch_out=ch_num[1], k_size=5)\n self.Conv3 = conv_block(ch_in=ch_num[1],ch_out=ch_num[2])\n self.Conv4 = conv_block(ch_in=ch_num[2],ch_out=ch_num[3])\n self.Conv5 = conv_block(ch_in=ch_num[3],ch_out=ch_num[4])\n self.Conv6 = conv_block(ch_in=ch_num[4],ch_out=ch_num[5])\n self.Conv7 = conv_block(ch_in=ch_num[5],ch_out=ch_num[6])\n\n self.Up7 = up_conv(ch_in=ch_num[6],ch_out=ch_num[5])\n self.Up_conv7 = conv_block(ch_in=ch_num[5] + ch_num[5], ch_out=ch_num[5])\n\n self.Up6 = up_conv(ch_in=ch_num[5],ch_out=ch_num[4])\n self.Up_conv6 = conv_block(ch_in=ch_num[4] + ch_num[4], ch_out=ch_num[4])\n\n self.Up5 = up_conv(ch_in=ch_num[4],ch_out=ch_num[3])\n self.Up_conv5 = conv_block(ch_in=ch_num[3] + ch_num[3], ch_out=ch_num[3])\n\n self.Up4 = up_conv(ch_in=ch_num[3],ch_out=ch_num[2])\n self.Up_conv4 = conv_block(ch_in=ch_num[2] + ch_num[2], ch_out=ch_num[2])\n \n self.Up3 = up_conv(ch_in=ch_num[2],ch_out=ch_num[1])\n self.Up_conv3 = conv_block(ch_in=ch_num[1] + ch_num[1], ch_out=ch_num[1])\n \n self.Up2 = up_conv(ch_in=ch_num[1],ch_out=ch_num[0])\n self.Up_conv2 = conv_block(ch_in=ch_num[0] + ch_num[0], ch_out=ch_num[0])\n\n self.out = nn.Conv2d(ch_num[0],output_ch,kernel_size=1,stride=1,padding=0, bias=False)\n\n\n def forward(self,x):\n # encoding path\n x1 = self.Conv1(x)\n\n x2 = self.Maxpool(x1)\n x2 = self.Conv2(x2)\n \n x3 = self.Maxpool(x2)\n x3 = self.Conv3(x3)\n\n x4 = self.Maxpool(x3)\n x4 = self.Conv4(x4)\n\n x5 = self.Maxpool(x4)\n x5 = self.Conv5(x5)\n\n x6 = self.Maxpool(x5)\n x6 = self.Conv6(x6)\n\n x7 = self.Maxpool(x6)\n x7 = self.Conv7(x7)\n\n # decoding + concat path\n\n d7 = self.Up7(x7)\n d7 = torch.cat((x6,d7),dim=1)\n d7 = self.Up_conv7(d7)\n\n d6 = self.Up6(d7)\n d6 = torch.cat((x5,d6),dim=1)\n d6 = self.Up_conv6(d6)\n\n\n d5 = self.Up5(d6)\n d5 = torch.cat((x4,d5),dim=1)\n d5 = self.Up_conv5(d5)\n \n d4 = self.Up4(d5)\n d4 = torch.cat((x3,d4),dim=1)\n d4 = self.Up_conv4(d4)\n\n d3 = self.Up3(d4)\n d3 = torch.cat((x2,d3),dim=1)\n d3 = self.Up_conv3(d3)\n\n d2 = self.Up2(d3)\n d2 = torch.cat((x1,d2),dim=1)\n d2 = self.Up_conv2(d2)\n\n d1 = self.out(d2)\n\n return d1\n\n\n\n\n\nif __name__ == \"__main__\":\n import numpy as np\n \n model = UNet(img_ch=36, output_ch=12)\n \n model_parameters = filter(lambda p: p.requires_grad, model.parameters())\n params = sum([np.prod(p.size()) for p in model_parameters])\n\n print(\"# of parameters: \", params)\n \n input_x = torch.rand((2, 36, 496, 448))\n out = model(input_x)\n \n print(out.shape)","sub_path":"runs/Moscow/UNet.py","file_name":"UNet.py","file_ext":"py","file_size_in_byte":4502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"40259208","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\n\n\n# Create your models here.\n\n\n\nclass Department(models.Model):\n name=models.CharField(max_length=40);\n leader=models.CharField(max_length=40);\n main_speciality=models.CharField(max_length=40);\n number_of_members=models.IntegerField(max_length=4);\n #worker=models.ForeignKey(Worker)\n\nclass Worker(models.Model):\n name=models.CharField(max_length=40);\n gift=models.IntegerField(max_length=5);\n photo=models.ImageField(null=True,blank=True)\n department=models.ManyToManyField(Department, related_name='workers',blank=True,null=True);\n #user=models.OneToOneField(User)\n def bit (self):\n if self.article_image:\n return u''% self.article_image.url\n else:\n return u'(none)'\n bit.short_description = 'Изображение'\n bit.allow_tags = True\n\n\n\n","sub_path":"dz/dz/app1/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"505330898","text":"def fn_radial_profile(Z, XY, noofbins = 100, bin_size = None, minbin = 0., maxbin = 10.):\n\n\t\"\"\"\n\tcalculates the radial profile of power spectrum or any other quantity\n\tin case of power spectrum, the outputs are k, p_k, p_k_err\n\t\"\"\"\n\n\tZ = np.asarray(Z)\n\tif XY == None:\n\t\tY, X = np.indices(Z.shape)\n\telse:\n\t\tX, Y = XY\n\n\tRADIUS = (X**2. + Y**2.) ** 0.5\n\n\t# Overwriting Maxbin Here!\n\tmaxbin = amax(RADIUS)\n\n\tif bin_size == None:\n\t\tbinarr=np.linspace(minbin,maxbin,noofbins)\n\telse:\n\t\tbinarr=np.arange(minbin,maxbin,bin_size)\n\n\t#print(binarr)\n\n\tradprf=np.zeros((len(binarr),4))\n\n\thit_count=[]\n\n\tfor b,bin in enumerate(binarr):\n\t\tind=np.where((RADIUS>=bin) & (RADIUS0.)[0])\n\n\t\tif hits>0:\n\t\t\tradprf[b,1]=np.sum(Z[ind])/hits\n\t\t\tradprf[b,2]=np.std(Z[ind])\n\t\thit_count.append(hits)\n\n\thit_count=np.asarray(hit_count)\n\tstd_mean=np.sum(radprf[:,2]*hit_count)/np.sum(hit_count)\n\terrval=std_mean/(hit_count)**0.5\n\tradprf[:,2]=errval\n\tradprf[:,3]=hit_count\n\n\t#print(\"pow\")\n\t#print(sum(Z))\n\t#print(sum(radprf[:,1]*hit_count))\n\n\treturn radprf\n\ndef fn_get_lxly(mapparams):\n\n\t\"\"\"\n\tmapparams: [nx, ny, dx, dy]: nx , ny = dimension of image; dx, dy = pixel resolution in arcmins\n\tjust computes the fourier wave vector\n\t\"\"\"\n\n\tnx, ny, dx, dy = mapparams\n\tdx *= arcmins2radians\n\tdy *= arcmins2radians\n\n\tlx, ly = np.meshgrid( np.fft.fftfreq( nx, dx ), np.fft.fftfreq( ny, dy ) )\n\n\t#fourier wavevector k = 2*pi/lambda\n\tlx *= 2* np.pi\n\tly *= 2* np.pi\n\n\treturn lx, ly\n\ndef fn_plot_pow_spec(mapparams, MAP1, MAP2 = None, binsize = None):\n\n\t\"\"\"\n\tcomputes 2d power spectrum of image and then the radial bining of it. Returns the 1d power spectrum.\n\tmapparams: [nx, ny, dx, dy]: nx , ny = dimension of image; dx, dy = pixel resolution in arcmins\n\tMAP1: first image\n\tMAP2: second image: If none, then compute auto power spectrum of MAP1. else cross power specctrum of MAP1 and MAP2\n\tbinsize: for 1d power spectrum\n\t\"\"\"\n\tnx, ny, dx, dy = mapparams\n\tdx_rad = dx * arcmins2radians\n\n\tif MAP2 == None: #compute auto power spectra\n\t\tcosm = cosmask([nx, ny])\n\t\tw = (float(1.0/(4*nx*ny))*sum(cosm*cosm))\n\t\t#print(\"PS REAL\")\n\t\t#print(sum(MAP1*MAP1)*w)\n\t\t#print(sum(MAP1*cosm*MAP1*cosm))\n\t\t#print(sum(zeropad(MAP1*cosm)*zeropad(MAP1*cosm)))\n\t\t# MAP_F = np.fft.fft2(MAP1*cosm)\n\t\tMAP_F = np.fft.fft2(zeropad(MAP1 * cosm))\n\t\tMAP_PSD = (MAP_F * conjugate(MAP_F)) / (4.0 * nx * ny * w)\n\t#MAP_F = np.fft.fft2(zeropad(MAP1 * cosm))\n\t#MAP_PSD = (MAP_F * conjugate(MAP_F)) / (4.0 * nx * ny * w)\n\n\t\t#abs( np.fft.fft2(MAP1) * dx_rad)** 2 / (nx * ny)\n\t\t# Do zero padding and apply mask here\n\n\telse: #compute cross power spectra between 2 maps\n\t\t#subplot(121);imshow(MAP1);colorbar();subplot(122);imshow(MAP2);colorbar();show();sys.exit()\n\t\tcosm = cosmask([nx, ny])\n\t\tw = (float(1.0 / (4 * nx * ny)) * sum(cosm * cosm))\n\t\t# print(\"PS REAL\")\n\t\t# print(sum(MAP1*MAP1)*w)\n\t\t# print(sum(MAP1*cosm*MAP1*cosm))\n\t\t# print(sum(zeropad(MAP1*cosm)*zeropad(MAP1*cosm)))\n\t\t# MAP_F = np.fft.fft2(MAP1*cosm)\n\t\tMAP1_F = np.fft.fft2(zeropad(MAP1 * cosm))\n\t\tMAP2_F = np.fft.fft2(zeropad(MAP2 * cosm))\n\t\tMAP_PSD = (MAP2_F * conjugate(MAP1_F)) / (4.0 * nx * ny * w)\n\t\t#MAP_PSD = np.fft.fft2(MAP1) * dx_rad * np.conj( np.fft.fft2(MAP2) ) * dx_rad / (nx * ny)\n\n\tlx, ly = fn_get_lxly([nx*2, ny*2, dx, dy])\n\tif binsize == None:\n\t\tbinsize = (lx.ravel()[1] - lx.ravel()[0]) # * 10\n\t# if np.max(lx)>1e5: binsize *= 2 #just increasing binsize\n\n\t#subplot(121);imshow(np.fft.fftshift(MAP_PSD.real));title(\"2D transform\");colorbar();show();\n\tpow_spec_1d = fn_radial_profile(MAP_PSD, (lx,ly), bin_size = binsize, minbin = np.min(abs(lx)), maxbin = np.max(lx))\n\n\treturn pow_spec_1d #contains k, p_k, p_k_err, hitcount\n\n\n################################################################################\n################################################################################\n################################################################################\n\n################################################################################\n################################################################################\nimport numpy as np, pickle, gzip\nfrom matplotlib.pyplot import *\nfrom numpy import savetxt, sum, conjugate, shape, amax, asarray, cos, pi, append, tile, transpose, zeros, real\n\narcmins2radians = np.radians(1./60.)\n\ndef cosmask(dimensions):\n # get cos array for y\n p_y = asarray(range(int(dimensions[0]/2)))\n cosy = cos(pi*p_y/dimensions[0])\n cosy = append(cosy[::-1], cosy)\n cosy = transpose(tile(cosy, (dimensions[1], 1)))\n # get cos array for x\n p_x = asarray(range(int(dimensions[1]/2)))\n cosx = cos(pi*p_x/dimensions[1])\n cosx = append(cosx[::-1], cosx)\n cosx = tile(cosx, (dimensions[0], 1))\n # return mask\n mask = cosy*cosx\n return mask\n\n\ndef zeropad(M):\n dim = shape(M)\n M_pad = zeros((2*asarray(dim)))\n M_pad[0:dim[0], 0:dim[1]] = M\n return M_pad","sub_path":"cosmologydigitisation/SPT Cloud Code/arbitrary levels code/pow_spec.py","file_name":"pow_spec.py","file_ext":"py","file_size_in_byte":4924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"136721298","text":"import pika\nimport pymongo\nimport pymysql\nimport datetime\n# import schedule\nimport os\nimport time\nimport CommonConnection\n\n\nclass DynamicQuening:\n def __init__(self):\n\n self.mongodb = CommonConnection.MongoConnection()\n self.db = CommonConnection.MySQLConnection()\n self.RabbitCon = CommonConnection.RabbitMQConnection()\n self.IPAddr = CommonConnection.ServivesIP()\n self.maxLength = 100000000\n self.maxPriority = 9\n\n\n def QueueCreatorDatabase(self):\n\n\n cur = self.db.cursor()\n cur.execute(\"select * from tbl_Bli_GroupMaster\")\n CurData = cur.fetchall()\n\n cur.close()\n self.db.close()\n return CurData\n\n\n def RetailGroupSelector(self):\n cur = self.db.cursor()\n cur.execute(\"select * from tbl_Bli_GroupMaster where businessType = 'Retail'\")\n CurData = cur.fetchall()\n\n cur.close()\n self.db.close()\n return CurData\n\n\n def HotelGroupSelector(self):\n cur = self.db.cursor()\n cur.execute(\"select * from tbl_Bli_GroupMaster where businessType = 'Hotel'\")\n CurData = cur.fetchall()\n\n cur.close()\n self.db.close()\n return CurData\n\n\n\n\n def run(self):\n self.connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))\n self.channel = self.connection.channel()\n args = {}\n #args[\"x-max-length\"] = self.maxLength\n args['x-max-priority'] = self.maxPriority\n\n CurData = DynamicQuening.QueueCreatorDatabase(self)\n for rows in CurData:\n print(rows)\n Groupname = rows[1]\n\n self.channel.queue_declare(queue=str(Groupname), durable=True, arguments=args)\n self.channel.queue_declare(queue=\"Parser\" + str(Groupname), durable=True, arguments=args)\n\n print(\"Queues updated\")\n\n\n\nwhile True:\n a = DynamicQuening()\n a.run()\n time.sleep(3600)\n\n\n\n","sub_path":"eCube_Hotel_2/HotelMessaging/Ecube2.0MessagingQueueLatest/ScrappingProducer/Queues/ScraperQueue/DynamicQueueCreator.py","file_name":"DynamicQueueCreator.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"21817652","text":"\"\"\" function to perform selection sort\r\na small modification over bubble sort\r\nin each pass the minimum element is obtained\r\nand inserted in the list beginning from the leftmost position\"\"\"\r\n\"\"\"Author: Vishnu Muralidharan\"\"\"\r\n\r\ndef selectionSort(S):\r\n for insertSlot in range(0,len(S)-1,1): # loop to keep track of slot to be inserted\r\n posMin = insertSlot\r\n for index in range(insertSlot+1,len(S)): #loop over the rest of the list to find the minimum element\r\n if S[index] < S[posMin]:\r\n posMin = index # if minimum element is found, posMin is the index of the minimum element\r\n # swap the minimum element and the element at the position to be inserted\r\n temp = S[insertSlot]\r\n S[insertSlot] = S[posMin]\r\n S[posMin] = temp\r\n\r\n\r\n\r\nalist = [54,26,93,17,77,31,44,55,20]\r\nselectionSort(alist)\r\nprint(alist)\r\n","sub_path":"sorting/selectionSort.py","file_name":"selectionSort.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"239969453","text":"#!/usr/bin/env pyhton\n\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\nimport pylab as pl\nimport matplotlib.image as mpimg\n\ndef leeImagen(filename, factor):\n img=mpimg.imread(filename)\n k = img[:,:,0]\n for j in range(k.shape[1]):\n for i in range(k.shape[0]):\n if k[i,j] == 0.0:\n k[i,j] = 0.1\n if k[i,j] < 1.0:\n k[i,j] *= factor \n\n return k.transpose()\n\n\ndef u_face(u1, u2):\n return 0.5 * (u1 + u2)\n\ndef Laplaciano2D(Nx, Ny, r, k):\n \"\"\" Esta funcion calcula los coeficientes del \n sistema lineal producido por el operador de \n Laplace en 2D. Estos coeficientes son almacenados \n en la matriz pentadiagonal correspondiente.\"\"\"\n N = Nx * Ny\n A = np.zeros((N,N))\n\n# Primero llena los bloques tridiagonales\n for j in range(1,Ny+1):\n ofs = Nx * (j-1) \n # Primer renglón del bloque, considera BC en la pared izq.\n k1 = u_face(k[0,j ], k[1,j]) # k_(i-1/2, j)\n k2 = u_face(k[2,j ], k[1,j]) # k_(i+1/2, j)\n k3 = u_face(k[1,j+1], k[1,j]) # k_(i, j-1/2)\n k4 = u_face(k[1,j-1], k[1,j]) # k_(i, j+1/2)\n A[ofs , ofs] = r * (k1 + k2 + k3 + k4) \n A[ofs + 1, ofs] = -r * k2\n\n # Renglones intermedios del bloque \n for i in range(2,Nx):\n k1 = u_face(k[i-1,j], k[i,j]) # k_(i-1/2, j)\n k2 = u_face(k[i+1,j], k[i,j]) # k_(i+1/2, j)\n k3 = u_face(k[i,j-1], k[i,j]) # k_(i, j-1/2)\n k4 = u_face(k[i,j+1], k[i,j]) # k_(i, j+1/2)\n I = ofs + i - 1\n A[I , I] = r * (k1 + k2 + k3 + k4)\n A[I-1, I] = -r * k1\n A[I+1, I] = -r * k2\n\n # Último renglón del bloque, considera BC en la pared der.\n k1 = u_face(k[Nx-1,j ], k[Nx,j]) # k_(i-1/2, j)\n k2 = u_face(k[Nx+1,j ], k[Nx,j]) # k_(i+1/2, j)\n k3 = u_face(k[Nx ,j-1], k[Nx,j]) # k_(i, j-1/2)\n k4 = u_face(k[Nx ,j+1], k[Nx,j]) # k_(i, j+1/2)\n I = ofs + Nx - 1\n A[I-1,I] = -r * k1 \n A[I ,I] = r * (k1 + k2 + k3 + k4) \n\n \n# Despues llena las dos diagonales externas\n I = 0\n for j in range(1, Ny):\n for i in range(1,Nx+1):\n k3 = u_face(k[i,j-1+1], k[i,j+1]) # k_(i, j-1/2)\n k4 = u_face(k[i,j+1], k[i,j]) # k_(i, j+1/2)\n A[I , I+Nx] = -r * k3 # South, 3, down\n A[I+Nx, I ] = -r * k4 # North, 4, up\n I += 1\n \n return A\n\n\ndef Laplaciano2D_T(Nx, Ny, r, k):\n \"\"\" Esta funcion calcula los coeficientes del \n sistema lineal producido por el operador de \n Laplace en 2D. Estos coeficientes son almacenados \n en la matriz pentadiagonal correspondiente.\"\"\"\n N = Nx * Ny\n A = np.zeros((N,N))\n\n# Primero llena los bloques tridiagonales\n for j in range(1,Ny+1):\n ofs = Nx * (j-1) \n # Primer renglón del bloque, considera BC en la pared izq.\n k1 = u_face(k[0,j ], k[1,j]) # k_(i-1/2, j)\n k2 = u_face(k[2,j ], k[1,j]) # k_(i+1/2, j)\n k3 = u_face(k[1,j+1], k[1,j]) # k_(i, j-1/2)\n k4 = u_face(k[1,j-1], k[1,j]) # k_(i, j+1/2)\n A[ofs , ofs] = 1 + r * (k1 + k2 + k3 + k4) \n A[ofs + 1, ofs] = -r * k2\n\n # Renglones intermedios del bloque \n for i in range(2,Nx):\n k1 = u_face(k[i-1,j], k[i,j]) # k_(i-1/2, j)\n k2 = u_face(k[i+1,j], k[i,j]) # k_(i+1/2, j)\n k3 = u_face(k[i,j-1], k[i,j]) # k_(i, j-1/2)\n k4 = u_face(k[i,j+1], k[i,j]) # k_(i, j+1/2)\n I = ofs + i - 1\n A[I , I] = 1 + r * (k1 + k2 + k3 + k4)\n A[I-1, I] = -r * k1\n A[I+1, I] = -r * k2\n\n # Último renglón del bloque, considera BC en la pared der.\n k1 = u_face(k[Nx-1,j ], k[Nx,j]) # k_(i-1/2, j)\n k2 = u_face(k[Nx+1,j ], k[Nx,j]) # k_(i+1/2, j)\n k3 = u_face(k[Nx ,j-1], k[Nx,j]) # k_(i, j-1/2)\n k4 = u_face(k[Nx ,j+1], k[Nx,j]) # k_(i, j+1/2)\n I = ofs + Nx - 1\n A[I-1,I] = -r * k1 \n A[I ,I] = 1 + r * (k1 + k2 + k3 + k4) \n\n \n# Despues llena las dos diagonales externas\n I = 0\n for j in range(1, Ny):\n for i in range(1,Nx+1):\n k3 = u_face(k[i,j-1+1], k[i,j+1]) # k_(i, j-1/2)\n k4 = u_face(k[i,j+1], k[i,j]) # k_(i, j+1/2)\n A[I , I+Nx] = -r * k3 # South, 3, down\n A[I+Nx, I ] = -r * k4 # North, 4, up\n I += 1\n \n return A\n\n\ndef LeeDatos(filename):\n \"\"\" Esta funcion lee los datos de un archivo. a? y b? son \n las coordenadas inicial y final del dominio respectivamente\n las direcciones x y y;\n Nx y Ny son el numero de incognitas en las direcciones \n correspondientes; A, B, C y D son las condiciones de\n frontera. Se regresa la tupla (ax,bx,ay,by,Nx,Ny,A,B,C,D).\"\"\"\n ifile = open(filename, 'r') # abre el archivo de entrada\n file_lines = ifile.readlines() # lee las lineas del archivo\n ifile.close(); # cierra el archivo de entrada\n ax, bx, ay, by, Nx, Ny, A, B, C, D = file_lines[0].split() # separa las columnas de la primera linea\n ax = float(ax); bx = float(bx); ay = float(ay); by = float(by); \n Nx = int(Nx); Ny = int(Ny); \n A = float(A); B = float(B); C = float(C); D = float(D); \n return ax, bx, ay, by, Nx, Ny, A, B, C, D\n\ndef ImprimeDatos(ax,bx,ay,by,Nx,Ny,hx,hy,A,cd1,B,cd2,C,cd3,D,cd4):\n \"\"\" Esta funcion imprime los datos del problema a resolver.\"\"\"\n print()\n print(\"+----------------------------------------------------+\")\n print(\"| Solucion de la ecuacion de Laplace en 2D |\")\n print(\"+----------------------------------------------------+\")\n print(\"| Autor: Luis M. de la Cruz S. |\")\n print(\"+----------------------------------------------------+\")\n print(\"| Datos de entrada |\")\n print(\"+----------------------------------------------------+\")\n print(\"| Punto inicial del dominio en x : ax = %g\" % ax)\n print(\"| Punto final del dominio en x : bx = %g\" % bx)\n print(\"| Punto inicial del dominio en y : ax = %g\" % ay)\n print(\"| Punto final del dominio en y : bx = %g\" % by)\n print(\"| Numero total de incognitas en x : Nx = %d\" % Nx)\n print(\"| Numero total de incognitas en y : Ny = %d\" % Ny)\n print(\"| Numero total de incognitas : N = %d\" % (Nx*Ny))\n print(\"| El tamanio de la malla en x es : hx = %g \" % hx)\n print(\"| El tamanio de la malla en y es : hy = %g \" % hy)\n print(\"| Cond. de front. \", cd1, \"en ax : A = %g\" % A)\n print(\"| Cond. de front. \", cd2, \"en bx : B = %g\" % B)\n print(\"| Cond. de front. \", cd3, \"en ay : C = %g\" % C)\n print(\"| Cond. de front. \", cd4, \"en by : D = %g\" % D)\n print(\"+----------------------------------------------------+\")\n\ndef ImprimeSistema(A,u,f):\n \"\"\" Esta funcion imprime el sistema lineal asi como la solucion\n del mismo, siempre y cuando su longitud sea menor o igual a 10.\"\"\"\n print(\"\\n Lado derecho del sistema : size = %d \\n\" % f.size, f)\n print(\"\\n Matriz del sistema : \\n\", A)\n print(\"\\n Solucion del sistema : size = %d \\n\" % u.size, u)\n\ndef GraficaSuperficieC(xg,yg,u,colormap):\n pl.contourf(xg, yg, u, 100, alpha=.95, cmap=colormap)\n C = pl.contour(xg, yg, u, 100, colors='black', alpha=0.01, linewidth=.5)\n pl.clabel(C, inline=1, fontsize=10)\n \n fig = pl.figure()\n ax = Axes3D(fig)\n ax.plot_surface(xg, yg, u, rstride=2, cstride=2, alpha=.95, cmap=colormap)\n\n pl.show()\n\ndef GuardaSolucion(filename, x, y, u):\n \"\"\" Esta funcion guarda la solucion en un archivo para su\n posterior analisis, en un archivo de nombre filename.\"\"\" \n ofile = open(filename, 'w')\n for i in range(0,x.size):\n for j in range(0,y.size):\n ofile.write('%12.10g \\t %12.10g \\t %12.10g\\n' % (x[i], y[j],u[j,i]))\n ofile.close()\n\n\n\n#if __name__ == \"__main__\":\n\n\n\n\n\n","sub_path":"TEST/poisson2D.py","file_name":"poisson2D.py","file_ext":"py","file_size_in_byte":7915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"313040177","text":"from unittest import TestCase\n\nfrom ..lib.binarystreams import stream_compare\nfrom ..lib.contextlib import tempdir\nfrom ..lib.pyx2py import pyx_to_py\n\nfrom _pyio import DEFAULT_BUFFER_SIZE\nfrom itertools import repeat\n\nclass T(TestCase):\n def test(self):\n with tempdir() as root:\n a, b = (root.joinpath(filename) for filename in ('a', 'b'))\n with open(pyx_to_py(__file__), 'rb') as istream:\n data = istream.read()\n with a.open('wb') as ostream:\n for none in repeat(None, DEFAULT_BUFFER_SIZE):\n none # pylint: disable=pointless-statement\n ostream.write(data)\n with b.open('wb') as ostream:\n for none in repeat(None, DEFAULT_BUFFER_SIZE):\n ostream.write(data)\n ostream.write(br'.')\n expected = True, False\n with a.open('rt') as istream0:\n with a.open('rt') as istream1:\n gotten0 = stream_compare(istream0, istream1)\n with a.open('rt') as istream0:\n with b.open('rt') as istream1:\n gotten1 = stream_compare(istream0, istream1)\n actual = gotten0, gotten1\n self.assertEqual(expected, actual)\n","sub_path":"x19290/test/t00binarystreams.py","file_name":"t00binarystreams.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"591330890","text":"import cv2\nimport os\nimport glob\nfrom tqdm import tqdm\nimport torch\nfrom torchvision import models\nimport matplotlib.pyplot as plt\n#画出余弦学习率的变化规律\ndef visulize_cosine_lr(net,max_epoch,optimizer,lr_scheduler,iters=100):\n\n plt.figure()\n cur_lr_list = []\n cur_lr = optimizer.param_groups[-1]['lr']\n cur_lr_list.append(cur_lr)\n for epoch in range(max_epoch):\n #print('epoch_{}'.format(epoch))\n # cur_lr = optimizer.param_groups[-1]['lr']\n # cur_lr_list.append(cur_lr)\n for batch in range(iters):\n optimizer.step()\n scheduler.step(epoch + batch / iters)\n cur_lr = optimizer.param_groups[-1]['lr']\n cur_lr_list.append(cur_lr)\n #scheduler.step(epoch + batch / iters)\n #scheduler.step()\n #print('cur_lr:',cur_lr)\n #print('epoch_{}_end'.format(epoch))\n lr_scheduler.step()\n x_list = list(range(len(cur_lr_list)))\n plt.title('Cosine lr T_0:{} T_mult:{}'.format(T_0,T_mult))\n plt.xlabel('epoch')\n plt.ylabel('lr')\n plt.plot(x_list, cur_lr_list)\n plt.savefig('./lr.png')\nif __name__=='__main__':\n model=models.resnet18(pretrained=False)\n T_0=3\n T_mult=2\n optimizer = torch.optim.SGD(model.parameters(), lr=1e-2, momentum=0.9, weight_decay=5e-4)\n #scheduler = StepLR(optimizer, step_size=step_size, gamma=gamma)\n scheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer, T_0=T_0, T_mult=T_mult, eta_min=1e-5, last_epoch=-1)\n visulize_cosine_lr(model,100,optimizer,scheduler,901)","sub_path":"天池/CVPR2021-PIC-Challenge/plot_lr.py","file_name":"plot_lr.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"417255927","text":"import httplib \nimport xmlrpclib\n\nclass CookieTransport(xmlrpclib.SafeTransport):\n \"\"\"\n Overides request add cookies from previous request.\n \"\"\"\n\n def __init__(self):\n xmlrpclib.Transport.__init__(self)\n self.cookie = None\n\n def make_connection(self, host):\n h = httplib.HTTP(host)\n return h\n\n def request(self, host, handler, request_body, verbose=0):\n # issue XML-RPC request\n h = self.make_connection(host)\n\n if verbose:\n h.set_debuglevel(1)\n\n self.send_request(h, handler, request_body)\n self.send_host(h, host)\n self.send_user_agent(h)\n\n if self.cookie is not None: \n h.putheader(\"Cookie\", self.cookie)\n\n self.send_content(h, request_body)\n errcode, errmsg, headers = h.getreply()\n \n self.cookie = headers.getheader('set-cookie') or self.cookie\n\n if errcode != 200:\n raise xmlrpclib.ProtocolError(\n host + handler,\n errcode, errmsg,\n headers\n )\n\n # do not print the response body\n self.verbose = False\n\n return self.parse_response(h.getfile())\n\n","sub_path":"rpc4django/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"11745840","text":"# -*- coding: utf-8 -*-\r\nfrom datetime import datetime\r\n\r\nfrom django.shortcuts import redirect, render\r\n\r\nfrom ..forms import PaginaForm\r\nfrom ..models import Pagina\r\nfrom ..comum.contents import reescrever_url, save_in_portal_catalog, get_site_url\r\nfrom ..comum.contents import get_site_url_id, get_url_id_content, save_indice_url, format_visao_by_delete\r\nfrom security.anotation import permission_content\r\n\r\n\r\nTEMPLATE = '%s/documents.html' % 'comum'\r\n\r\n@permission_content(tipo='ATPagina', permissao='create', login_url='/security/login/')\r\ndef create(request):\r\n path_url = reescrever_url(request)\r\n form = PaginaForm(request.POST or None,)\r\n site = get_site_url(request)\r\n if form.is_valid():\r\n model = form.save(commit=False)\r\n _url = save_indice_url(request, model.titulo)\r\n model.url = _url\r\n model.tipo = 'ATPagina'\r\n model.site = site\r\n model.dono = request.user\r\n model.save()\r\n path_url += _url + '/'\r\n save_in_portal_catalog(model, path_url)\r\n return redirect(path_url)\r\n\r\n context = {\r\n 'form' : form,\r\n 'editor' : True,\r\n }\r\n \r\n _site_url = get_site_url_id(request)\r\n template = '%s/documents.html' % _site_url\r\n try:\r\n return render(request, template, context)\r\n except:\r\n return render(request, TEMPLATE, context)\r\n\r\n@permission_content(tipo='ATPagina', permissao='update', login_url='/security/login/')\r\ndef edit(request):\r\n _url = reescrever_url(request)\r\n _site_url = get_site_url_id(request)\r\n _content_url_id = get_url_id_content(request)\r\n _object = Pagina.objects.filter(site__url=_site_url).get(url=_content_url_id)\r\n form = PaginaForm(request.POST or None, instance=_object)\r\n if form.is_valid():\r\n model = form.save(commit=False)\r\n model.update_at = datetime.now()\r\n model.save()\r\n save_in_portal_catalog(model)\r\n return redirect(_url)\r\n context = {\r\n 'form' : form,\r\n 'editor' : True,\r\n }\r\n \r\n template = '%s/documents.html' % _site_url\r\n try:\r\n return render(request, template, context)\r\n except:\r\n return render(request, TEMPLATE, context)\r\n\r\n@permission_content(tipo='ATPagina', permissao='delete', login_url='/security/login/')\r\ndef delete(request, portal_catalog):\r\n content_url = get_url_id_content(request)\r\n content = portal_catalog.get_content_object()\r\n content.delete()\r\n portal_catalog.delete()\r\n _new_url = reescrever_url(request)\r\n _new_url = _new_url.replace('/'+content_url, '')\r\n _site_url = get_site_url_id(request)\r\n #verica ocorrencia de visão do content na pasta e formata para visão sumaria\r\n format_visao_by_delete(_site_url, _new_url)\r\n return redirect(_new_url)\r\n\r\n@permission_content(tipo='ATPagina', permissao='workflow', login_url='/security/login/')\r\ndef workflow(request, portal_catalog, _workflow):\r\n _site_url = get_site_url_id(request)\r\n _o = Pagina.objects.filter(site__url=_site_url).get(url=portal_catalog.url)\r\n _o.workflow = _workflow\r\n if _o.workflow == 'Publicado' and _o.public_at==None:\r\n _o.public_at = datetime.now()\r\n _o.save()\r\n save_in_portal_catalog(_o)\r\n ","sub_path":"portalufopa/comum/paginas.py","file_name":"paginas.py","file_ext":"py","file_size_in_byte":3231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"597167877","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 ('prices', '0002_prices_gasoline_price'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='prices',\n name='crack_spread',\n field=models.FloatField(default=b'11.00'),\n ),\n ]\n","sub_path":"prices/migrations/0003_prices_crack_spread.py","file_name":"0003_prices_crack_spread.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"451957585","text":"from django.http import Http404\nfrom django.shortcuts import render\n\n# my import\nfrom .models import Company, Phone\n\n# -------------------------------------------------------------------\n# -------------------------------------------------------------------\ndef index(request):\n all_companies = Company.objects.all()\n\n context = {\n 'all_companies': all_companies\n }\n return render(request, 'main/index.html', context)\n\n# -------------------------------------------------------------------\n# -------------------------------------------------------------------\ndef company(request, company_id):\n try:\n company = Company.objects.get(id=company_id)\n except Company.DoesNotExist:\n raise Http404(\"Company does not exist!\")\n\n context = {\n 'company': company\n }\n return render(request, 'main/company.html', context)\n","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"170104480","text":"print(\"---------------这是一个Python的学习笔记------------------\")\ntemp = input(\"请猜一下我想的数字:\")\nguess = int(temp)\nwhile guess != 8:\n temp = input(\"请再猜一次:\")\n guess = int(temp)\n if guess == 8:\n print(\"狗日的,这也想得到!\")\n print(\"日你妈\")\n else:\n if guess >8:\n print('大大大大大')\n else:\n print(\"猪,这都想不到,太小了\")\nprint(\"结束了\")\n","sub_path":"python file/python不方便Eclipse在运行的脚本/学习代码/3a.py","file_name":"3a.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"4677927","text":"class Solution:\n def nextPermutation(self, nums: List[int]) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n n = len(nums)\n if n <=1: return nums\n flag = False\n for i in range(n-1,0,-1):\n if nums[i] > nums[i-1]:\n flag = True\n break\n dec_i = i-1\n for i in range(dec_i+1,n):\n if nums[i] > nums[dec_i]:\n if len(nums[i:]) == 1 or nums[dec_i] >= nums[i+1]:\n tmp = nums[dec_i]\n nums[dec_i] = nums[i]\n nums[i] = tmp\n break\n if flag == False: dec_i = -1\n # reverse 就行了\n i = dec_i+1\n j = n-1\n while i < j:\n tmp = nums[i]\n nums[i] = nums[j]\n nums[j] = tmp\n i +=1\n j -=1\n # 冒泡排序\n # for i in range(n-1,dec_i,-1):\n # for j in range(dec_i+1,i):\n # if nums[j] > nums[j+1]:\n # tmp = nums[j]\n # nums[j] = nums[j+1]\n # nums[j+1] = tmp\n","sub_path":"Qustion Code/31. 下一个排列.py","file_name":"31. 下一个排列.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"646054526","text":"import numpy\nimport random\n\n#Function by ajkaew\nclass Model_chat:\n # instance attributes\n def __init__(self, X,Y):\n self.X = X\n self.Y = Y\n\n def create_Xb(self, X):\n N = X.shape[0]\n ones = numpy.ones([N, 1])\n Xb = numpy.hstack([ones, X])\n return Xb\n\n def find_W_class(self, X, Y, epoch , lr):\n Xb = self.create_Xb(X)\n N = Xb.shape[0]\n D_1 = Xb.shape[1]\n K = Y.shape[1]\n W = numpy.random.randn(D_1, K)/numpy.sqrt(D_1)\n error_list = []\n for i in range(epoch):\n Yhat = self.find_Yhat_class(X,W)\n error = (-Y*numpy.log(Yhat)).sum()\n error_list.append(error)\n S = numpy.dot(Xb.T, Y-Yhat)\n W = W + (lr/N)*S\n print(Yhat)\n print(\"|| CHATBOT_THAI || error =\", error,\"epoch\", i)\n return W, error_list\n\n def find_Yhat_class(self, X ,W):\n Xb = self.create_Xb(X)\n Z = numpy.dot(Xb, W)\n Yhat = numpy.exp(Z)/numpy.exp(Z).sum(axis=1, keepdims=True)#softmax\n return Yhat\n\n def fit(self, epoch,lr):\n self.W, self.error_list = self.find_W_class(self.X, self.Y,epoch,lr)\n self.Yhat = self.find_Yhat_class(self.X, self.W)\n \n def predict(self, text):\n zero_val = numpy.count_nonzero(text[0])\n if zero_val == 0:\n return -1 , 0.24\n else:\n predict = self.find_Yhat_class(text,self.W)\n predicted_index = numpy.argmax(predict, axis=1)[0]\n self.correct = predict[0][predicted_index]\n return predicted_index , self.correct\n \n ","sub_path":"chat/model_chatbot.py","file_name":"model_chatbot.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"235797984","text":"import collections\nn = int(input())\n\nx1, y1 = list(map(int, input().split()))\nx2, y2 = list(map(int, input().split()))\n\nx1 -= 1\ny1 -= 1\nx2 -= 1\ny2 -= 1\n\ndist = [[10000] * n for i in range(n)]\n\nturns = [[2, 1], [2, -1], [-2, 1], [-2, -1], [1, 2], [1, -2], [-1, 2], [-1, -2]]\n\ndepth = 0\ndist[x1][y1] = 0\nwhile dist[x2][y2] == 10000:\n for xc in range(n):\n for yc in range(n):\n if dist[xc][yc] == depth:\n for turn in turns:\n xn = xc + turn[0]\n yn = yc + turn[1]\n\n if (xn >= 0 and xn < n and yn >= 0 and yn < n and dist[xn][yn] > depth + 1):\n dist[xn][yn] = depth + 1\n depth += 1\n\nprint(dist[x2][y2])\n","sub_path":"components.py","file_name":"components.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"544000181","text":"# Copyright 2019 Nokia\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 ironic.common import boot_devices\nfrom ironic.common.i18n import _\nfrom ironic.conductor import utils as manager_utils\nfrom ironic.drivers.modules import ipmitool\nfrom ironic_virtmedia_driver.vendors.ironic_virtmedia_hw import IronicVirtMediaHW\nfrom ironic_virtmedia_driver import virtmedia_exception\n\nfrom redfish import redfish_client, AuthMethod\nfrom redfish.rest.v1 import ServerDownOrUnreachableError\n\nclass DELL(IronicVirtMediaHW):\n def __init__(self, log):\n super(DELL, self).__init__(log)\n self.remote_share = '/bootimages/'\n self.idrac_location = '/redfish/v1/Managers/iDRAC.Embedded.1/'\n\n def _init_connection(self, driver_info):\n \"\"\"Get connection info and init rest_object\"\"\"\n host = 'https://' + driver_info['address']\n user = driver_info['username']\n password = driver_info['password']\n redfishclient = None\n self.log.debug(\"Init connection: user: %s, passwd: %s, host: %s\", user, password, host)\n try:\n redfishclient = redfish_client(base_url=host, \\\n username=user, password=password)\n redfishclient.login(auth=AuthMethod.SESSION)\n except ServerDownOrUnreachableError as error:\n operation = _(\"iDRAC not responding\")\n raise virtmedia_exception.VirtmediaOperationError(\n operation=operation, error=error)\n except Exception as error:\n operation = _(\"Failed to login to iDRAC\")\n raise virtmedia_exception.VirtmediaOperationError(\n operation=operation, error=error)\n return redfishclient\n\n @staticmethod\n def _check_success(response):\n if response.status >= 200 and response.status < 300:\n return True\n else:\n try:\n _ = response.dict\n raise virtmedia_exception.VirtmediaOperationError(\"Response status is %d, %s\"% (response.status, response.dict[\"error\"][\"@Message.ExtendedInfo\"][0][\"MessageId\"].split(\".\")))\n except Exception:\n raise virtmedia_exception.VirtmediaOperationError(\"Response status is not 200, %s\"% response)\n\n def _check_supported_idrac_version(self, connection):\n response = connection.get('%s/VirtualMedia/CD'%self.idrac_location)\n self._check_success(response)\n data = response.dict\n for i in data.get('Actions', []):\n if i == \"#VirtualMedia.InsertMedia\" or i == \"#VirtualMedia.EjectMedia\":\n return True\n raise virtmedia_exception.VirtmediaOperationError(\"Unsupported version of iDRAC, please update before continuing\")\n\n def _get_virtual_media_devices(self, connection):\n idr = connection.get(\"%s\" % self.idrac_location)\n self._check_success(idr)\n try:\n virtual_media = connection.get(idr.dict[\"VirtualMedia\"][\"@odata.id\"])\n self._check_success(virtual_media)\n except KeyError:\n self.log.error(\"Cannot find a single virtual media device\")\n raise virtmedia_exception.VirtmediaOperationError(\"Cannot find any virtual media device on the server\")\n return virtual_media.dict[\"Members\"]\n\n def _umount_virtual_device(self, connection, media_uri):\n self.log.debug(\"Unmount\")\n unmount_location = media_uri + \"/Actions/VirtualMedia.EjectMedia\"\n resp = connection.post(unmount_location, body={})\n self._check_success(resp)\n\n def _mount_virtual_device(self, connection, media_uri, image_location):\n self.log.debug(\"Mount\")\n mount_location = media_uri + \"/Actions/VirtualMedia.InsertMedia\"\n payload = {'Image': image_location, 'Inserted':True, 'WriteProtected':True}\n resp = connection.post(mount_location, body=payload)\n self._check_success(resp)\n\n def _unmount_all(self, connection):\n medias = self._get_virtual_media_devices(connection)\n for media in medias:\n uri = media.get(\"@odata.id\", None)\n if not uri or connection.get(uri).dict[\"ConnectedVia\"] == \"NotConnected\":\n continue\n self._umount_virtual_device(connection, uri)\n\n def _find_first_media(self, connection, typeinfo):\n medias = self._get_virtual_media_devices(connection)\n for media in medias:\n response = connection.get(media[\"@odata.id\"])\n if typeinfo in response.dict[\"MediaTypes\"]:\n return media[\"@odata.id\"]\n return None\n\n def _mount_virtual_cd(self, connection, image_location):\n self._unmount_all(connection)\n self.log.debug(\"Mount\")\n media_uri = self._find_first_media(connection, \"DVD\")\n self._mount_virtual_device(connection, media_uri, image_location)\n\n def attach_virtual_cd(self, image_filename, driver_info, task):\n connection = None\n try:\n self.log.debug(\"attach_virtual_cd\")\n connection = self._init_connection(driver_info)\n self._check_supported_idrac_version(connection)\n image_location = 'http://' + str(driver_info['provisioning_server']) + ':' + str(driver_info['provisioning_server_http_port']) + self.remote_share + image_filename\n self._mount_virtual_cd(connection, image_location)\n\n connection.logout()\n return True\n except Exception:\n if connection:\n connection.logout()\n raise\n\n def detach_virtual_cd(self, driver_info, task):\n connection = None\n try:\n self.log.debug(\"detach_virtual_cd\")\n connection = self._init_connection(driver_info)\n self._check_supported_idrac_version(connection)\n self._unmount_all(connection)\n connection.logout()\n return True\n except Exception:\n if connection:\n connection.logout()\n raise\n\n def set_boot_device(self, task):\n try:\n #BMC boot flag valid bit clearing 1f -> all bit set\n #P 420 of ipmi spec\n # https://www.intel.com/content/www/us/en/servers/ipmi/ipmi-second-gen-interface-spec-v2-rev1-1.html\n cmd = '0x00 0x08 0x03 0x1f'\n ipmitool.send_raw(task, cmd)\n self.log.info('Disable timeout for booting')\n except Exception as err:\n self.log.warning('Failed to disable booting options: %s', str(err))\n #For time being lets do the boot order with ipmitool since, well dell doesn't provide open support\n #for this.\n try:\n # 0x00 0x08 0x05 0x80 0x20: chassis|set|bootdev|for next boot only|remote CD\n # other options for device (per ipmitool's \"ipmi_chassis.c\"):\n # 04: PXE\n # 08: HDD\n # 0c: Safe\n # 10: Diag\n # 14: CDROM\n # 18: Setup\n # 1c: Remote FDD\n # 24: Remote primary media\n # 2c: Remote HDD\n # 3c: FDD\n ipmitool.send_raw(task, '0x00 0x08 0x05 0x80 0x20 0x00 0x00 0x00')\n self.log.info('Set next boot to remote media')\n except Exception as err:\n self.log.warning('Failed to set next boot to remote media: %s', str(err))\n","sub_path":"src/ironic_virtmedia_driver/vendors/dell/dell.py","file_name":"dell.py","file_ext":"py","file_size_in_byte":7746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"380811550","text":"from moviepy.editor import *\n\nvideo = VideoFileClip(r\"D:\\DCIM\\Upload\\swagger_api_design.mp4\").subclip(t_start=5, t_end=10)\n\n# Make the text. Many more options are available.\ntxt_clip = ( TextClip(\"My Holidays 2013\",filename='a.txt', tempfilename='a.png',fontsize=70,color='white')\n .set_position('center')\n .set_duration(10) )\n\nresult = CompositeVideoClip([video, txt_clip]) # Overlay text on video\nresult.write_videofile(\"myHolidays_edited.webm\",fps=25) # Many options...","sub_path":"030_Media/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"206797544","text":"import json\nfrom bs4 import BeautifulSoup\nfrom task5 import get_movie_list_details\n\nwith open('task5.json','r') as f:\n a=json.load(f)\nmovies_data=a\nprint(movies_data)\ndef analyse_movies_directors(movies_data):\n l1=[]\n for i in movies_data:\n if i['Director'] not in l1:\n l1.append(i[\"Director\"])\n i=0\n L=[] \n while i= 1\n for i in self.data:\n for xi in self.data[i]:\n yi = i\n if not yi*(np.dot(w_t, xi)+b) >= 1:\n found_option = False\n if found_option:\n opt_dict[np.linalg.norm(w_t)] = [w_t, b]\n if w[0] < 0:\n optimized = True\n print(\"Optimized a step\")\n else:\n # w = [5,5]\n # step = 1\n # w-step = [4,4]\n w = w-step\n norms = sorted([n for n in opt_dict])\n opt_choice = opt_dict[norms[0]]\n self.w = opt_choice[0]\n self.b = opt_choice[1]\n\n latest_optimum = opt_choice[0][0]+step*2\n\n #for predict\n def predict(self, features):\n # sign(x.w+b)\n classification = np.sign(np.dot(np.array(features), self.w) + self.b)\n return classification\n\n\ndata_dict = {-1: np.array([[1,7], [3,4], [7,9]]), 1: np.array([[2,4],[5,1],[6,9]])}","sub_path":"list/svm-manual.py","file_name":"svm-manual.py","file_ext":"py","file_size_in_byte":2908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"539035076","text":"# https://stackoverflow.com/questions/57506101/qlabel-is-not-updated-unless-the-mainwindow-is-unfocused\n# 포커스 안맞을때 label이 변경 안되는 현상// 버그라고 하고 수정되었다고함\n# pip list 해서 버전 확인 후 업데이트 : \n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\nclass Ui_HelloWorld(object):\n def setupUi(self, Dialog):\n Dialog.setObjectName(\"Dialog\")\n Dialog.resize(400, 300)\n self.label = QtWidgets.QLabel(Dialog)\n self.label.setGeometry(QtCore.QRect(70, 40, 201, 21))\n self.label.setObjectName(\"label\")\n self.pushButton = QtWidgets.QPushButton(Dialog)\n self.pushButton.setGeometry(QtCore.QRect(130, 90, 113, 32))\n self.pushButton.setObjectName(\"pushButton\")\n\n self.retranslateUi(Dialog)\n QtCore.QMetaObject.connectSlotsByName(Dialog)\n\n def retranslateUi(self, Dialog):\n _translate = QtCore.QCoreApplication.translate\n Dialog.setWindowTitle(_translate(\"Dialog\", \"Dialog\"))\n self.label.setText(_translate(\"Dialog\", \"foobar\"))\n self.pushButton.setText(_translate(\"Dialog\", \"Click\"))\n\n\n\nimport sys\n\nfrom PyQt5.QtCore import pyqtSlot\nfrom PyQt5.QtWidgets import QApplication\nfrom PyQt5.QtWidgets import QMainWindow \n\nclass HelloWorldGui(QMainWindow, Ui_HelloWorld):\n def __init__(self, parent=None):\n super(HelloWorldGui, self).__init__(parent)\n self.setupUi(self)\n self.pushButton.clicked.connect(self.setTextHelloWorld)\n\n def setTextHelloWorld(self):\n self.label.setText(\"Hello World\")\n\n\nif __name__ == '__main__':\n argvs = sys.argv\n app = QApplication(argvs)\n hello_world_gui = HelloWorldGui()\n hello_world_gui.show()\n sys.exit(app.exec_())","sub_path":"200514-01-qlabel_repaint_bug.py","file_name":"200514-01-qlabel_repaint_bug.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"557514127","text":"\"\"\"\n Function that implements SVM using optimization functions with the primal vs dual formulations as choices.\n\"\"\"\n\nfrom Classifier import Classifier\nimport numpy as np\nimport scipy.optimize\n\n# adding a random comment\n\nclass SVM(Classifier):\n # the constructor equivalent\n def __init__(self, solve_method=\"primal\", c=1):\n \"\"\"\n :param solve_method: either the primal or the dual formulation\n \"\"\"\n super().__init__()\n self.solve_method = solve_method\n self.c = c\n self.beta = None\n self.X = None\n self.Y = None\n\n # returns the name of this classifier\n def get_name(self):\n return \"SVM\"\n\n # a fit method is instead used to make it adhere to the\n def fit(self, x, y):\n \"\"\"\n :param x: N X p numpy.ndarray\n :param y: N X 1 numpy data array\n \"\"\"\n self.X = x\n self.Y = np.array(y)\n self.Y[y == 0] = -1\n\n if self.solve_method == \"primal\":\n self.beta = self.__primal_svm()\n elif self.solve_method == \"dual\":\n self.beta = self.__dual_svm()\n else:\n raise Exception(\"solve method not found\")\n\n # method to predict\n def predict(self, x):\n \"\"\"\n :param x: N X p data numpy.ndarray\n :return: (N, ) y predicted labels\n \"\"\"\n y = np.sign(np.dot(x, self.beta.T))\n y[y == -1] = 0\n return np.round(y)\n\n # the objective function\n @staticmethod\n def func(alpha, k):\n \"\"\" Objective function\n :param alpha: the support vectors\n :param k: the kernel\n \"\"\"\n a1 = np.ones(alpha.shape)\n return -(np.dot(a1.T, alpha) - .5 * np.dot(alpha.T, np.dot(k, alpha)))\n\n # define derivative of function\n @staticmethod\n def func_deriv(alpha, k):\n \"\"\" Derivative\n :param alpha: the support vectors\n :param k: the kernel\n \"\"\"\n return -(np.ones(alpha.shape) - 1 * np.dot(k, alpha))\n\n # the dual method\n def __dual_svm(self):\n \"\"\" Support vector machine - Dual problem\n\n SVM classification for a numeric test matrix. The\n returned result is the vector of coefficients from\n the support vector machine (beta, *not* alpha!).\n\n Returns:\n a 1d numpy array of length p giving the coefficients of beta in\n the SVM model\n \"\"\"\n c = self.c\n x = self.X\n y = self.Y\n\n # calculate the linear kernel matrix\n k = np.zeros((x.shape[0], x.shape[0]))\n for i in range(x.shape[0]):\n for j in range(x.shape[0]):\n x_1 = x[i, :]\n x_2 = x[j, :]\n k[i, j] = y[i] * y[j] * np.inner(x_1, x_2)\n\n alpha = .5 * np.ones((x.shape[0], 1))\n bnds = np.concatenate((np.zeros(np.shape(alpha)), np.ones(np.shape(alpha)) * c), axis=1)\n optim = scipy.optimize.minimize(SVM.func, alpha, args=k, jac=SVM.func_deriv,\n bounds=bnds, options={'disp': False})\n alpha_updated = optim.x\n beta = np.zeros((x.shape[1]))\n for i in range(x.shape[0]):\n beta = beta + alpha_updated[i] * y[i] * x[i, :]\n\n return beta # correct dimension\n\n # the primal method\n def __primal_svm(self):\n \"\"\" Support vector machine - Dual problem\n\n SVM classification for a numeric test matrix. The\n returned result is the vector of coefficients from\n the support vector machine (beta, *not* alpha!).\n\n Args:\n X: an n by p numpy array; the data matrix of predictors\n y: a length n numpy array; the observed response\n lam: positive numeric value giving the tuning parameter\n in the (primal, penalized format) of the support vector machine\n k: positive integer giving the number of samples selected in\n each iteration of the algorithm\n T: positive integer giving the total number of iteration to run\n\n Returns:\n a 1d numpy array of length p giving the coefficients of beta in\n the SVM model\n \"\"\"\n X = self.X\n y = self.Y\n lam = 1\n k = 5\n T = 100\n\n w = np.zeros(X.shape[1]) / (X.shape[0])\n # print(\"initial norm is: \" + str(np.linalg.norm(w)))\n # print(\"1/sqrt(lambda) is: \" + str(1/np.sqrt(lam)))\n\n for t in range(T):\n k_inds = np.random.randint(0, X.shape[0], (k, 1))\n y_k = np.reshape(y[k_inds], (k, 1))\n x_k = np.reshape(X[k_inds, :], (k, X.shape[1]))\n temp1 = np.multiply(y_k, np.reshape(np.dot(x_k, w), (k, 1)))\n\n eta_t = 1 / ((t + 1) * lam)\n w_half = (1 - eta_t * lam) * w\n # print(w_half)\n\n for i in range(temp1.shape[0]):\n if temp1[i] < 1:\n w_half = w_half + eta_t * y_k[i] * x_k[i, :] / k\n\n scale_val = np.min([1, 1 / (np.sqrt(lam) * np.linalg.norm(w_half))])\n # if np.abs(scale_val - 1) > .000001:\n # print(\"scale value is: \" + str(scale_val))\n w = w_half * scale_val\n\n return w # correct dimension\n","sub_path":"SVM.py","file_name":"SVM.py","file_ext":"py","file_size_in_byte":5172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"58880140","text":"from ChiSquare import ChiSquare\nfrom NLL import NLL\nfrom Function import Function, ComposeFunction\nfrom Optimise import Optimise\nfrom Plot import Plot\nimport numpy as np\n\n'''\nMoves around values and calls methods in Optimise class\n'''\nclass Organise(object):\n\n def findChiParams(self):\n dataFileName = 'testData.txt'\n function = Function()\n chiLinear = ChiSquare(function.evalLinear, dataFileName)\n optimiser = Optimise()\n\n #m = params[0]\n #c = params[1]\n paramsGuess = [0., 1.]\n paramsAccuracy = [0.000000001, 0.000000001]\n paramsJump = [1., 1.]\n #evals minimum m and c for our ChiSquare\n params = optimiser.min(chiLinear.evalChiSquare, paramsGuess, paramsJump, paramsAccuracy, [])\n\n minM = params[0]\n minC = params[1]\n minChi = chiLinear.evalChiSquare(params)\n\n #finding err of values in params by finding where the chiSquare\n #increases by 1 either side of the minimum\n mRootParamGuess = [minM + 1., minC]\n cRootParamGuess = [minM, minC + 1.]\n rootParamsJump = [0.0001, 0.001]\n rootParamsAccuracy = [0.000001, 0.000001]\n mErrPos = abs(optimiser.equalTo((minChi + 1), chiLinear.evalChiSquare, mRootParamGuess, rootParamsJump, rootParamsAccuracy, [1])[0] - minM)\n cErrPos = abs(optimiser.equalTo((minChi + 1), chiLinear.evalChiSquare, cRootParamGuess, rootParamsJump, rootParamsAccuracy, [0])[1] - minC)\n mErrNeg = abs(optimiser.equalTo((minChi + 1), chiLinear.evalChiSquare, [minM - mErrPos, minC], rootParamsJump, rootParamsAccuracy, [1])[0] - minM)\n cErrNeg = abs(optimiser.equalTo((minChi + 1), chiLinear.evalChiSquare, [minM, minC - cErrPos], rootParamsJump, rootParamsAccuracy, [0])[1] - minC)\n\n mErrMean = (mErrPos + mErrNeg)/2.\n cErrMean = (cErrPos + cErrNeg)/2.\n\n print(\"\")\n print(\"[m,c]:\\t\" + str(np.around(np.array(params),6)) + \"\\n\")\n print(\"mErr:\\t+\" + str(np.round(mErrPos, 6)) + \"\\t-\" + str(np.round(mErrNeg, 6)))\n print(\"mean:\\t\" + str(np.round(mErrMean, 6)) + \"\\n\")\n print(\"cErr:\\t+\" + str(np.round(cErrPos, 6)) + \"\\t-\" + str(np.round(cErrNeg, 6)))\n print(\"Mean:\\t\" + str(np.round(cErrMean, 6)))\n print(\"\")\n\n #self.plotChiAroundMin(chiLinear.evalChiSquare, params, [mErrPos, cErrPos], [mErrNeg, cErrNeg])\n plotter = Plot()\n plotter.plotChiAroundMin(chiLinear.evalChiSquare, params, [mErrPos, cErrPos], [mErrNeg, cErrNeg])\n\n def findNLLParams(self, dataFileName):\n function = Function()\n NLLExp = NLL(function.expPDF, dataFileName)\n optimiser = Optimise()\n\n #finds minimum tau for our NLL\n paramsGuess = [2.]\n paramsJump = [0.01]\n paramsAccuracy = [0.00001]\n params = optimiser.min(NLLExp.evalNLL, paramsGuess, paramsJump, paramsAccuracy, [])\n\n tauMin = params[0]\n minNll = NLLExp.evalNLL(params)\n\n #finding err of tau in params by finding where the chiSquare\n #increases by 0.5 either side of the minimum\n tauRootGuess = [tauMin]\n tauRootJump = [0.001]\n tauRootAccuracy = [0.00001]\n tauErrPos = abs(optimiser.equalTo((minNll + 0.5), NLLExp.evalNLL, tauRootGuess, tauRootJump, tauRootAccuracy, [])[0] - tauMin)\n tauErrNeg = abs(optimiser.equalTo((minNll + 0.5), NLLExp.evalNLL, [tauMin-tauErrPos], tauRootJump, tauRootAccuracy, [])[0] - tauMin)\n tauErrMean = (tauErrPos + tauErrNeg)/2.\n\n print(\"\")\n print(\"tau:\\t\" + str(np.round(tauMin, 6)) + \"\\n\")\n print(\"tauErr:\\t+\" + str(np.round(tauErrPos, 6)) + \"\\t-\" + str(np.round(tauErrNeg, 6)))\n print(\"mean:\\t\" + str(np.round(tauErrMean, 6)))\n print(\"\")\n\n #self.plotNLLAroundMin(NLLExp.evalNLL, params, [tauErrPos], [tauErrNeg])\n plotter = Plot()\n plotter.plotNLLAroundMin(NLLExp.evalNLL, params, [tauErrPos], [tauErrNeg])\n","sub_path":"Organise.py","file_name":"Organise.py","file_ext":"py","file_size_in_byte":3924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"157941863","text":"import pandas as pd\n# from constants import *\nfrom .constants import *\nimport json\nfrom pyrebase import pyrebase\nfrom urllib.parse import parse_qsl, urljoin, urlparse\n# from database import Database\nfrom .database import Database\n\nfirebase = pyrebase.initialize_app(config)\ndb = firebase.database() # Get a reference to the database service\n\n\nclass BagOfIngredients:\n def __init__(self, username):\n self.username = \"\\'\" + username + \"\\'\" # use a session variable\n self.ingredients = []\n self.number_of_ingredients = 0\n self.boi = None\n self.db = Database()\n self.db.open()\n\n def get_boi(self):\n # Gets bag of ingredients for a certain User\n\n #print(\"Getting Bag of Ingredients from DB>>>\\n\", self.db.get(\"bagofingredients\", \"*\", where=\"user_id=\"+self.username))\n return self.db.get(\"BagOfIngredients\", \"*\", where=\"user_id=\"+self.username)\n\n def push_boi(self, ing: Ingredient):\n # Pushes an ingredient into Bag of Ingredients for the User\n\n columns = \"user_id, ingredient, ingredient_name, amount, unit\"\n data = \"{0},'{1}','{2}',{3},'{4}'\".format(self.username,\n ing.ingredient_full, ing.ingredient, ing.amount, ing.units)\n print(\"Pushing \"+ing.ingredient_full+\" into DB>>> Bag of Ingredients.\")\n push_success = self.db.write(\"BagOfIngredients\", columns, data)\n self.number_of_ingredients += 1\n self.ingredients.append(ing)\n return push_success\n\n def delete_all(self):\n # Deletes all ingredients from Bag for a User\n try:\n print(\"DELETING ALL from BOI with user_id>>>\"+self.username)\n delete_query = \"DELETE FROM bagofingredients WHERE user_id=\"+self.username+\";\"\n self.db.query(delete_query)\n except:\n print(\"ERROR OCCURED IN DELETION!\")\n return False\n return True\n\n def delete_ingredient(self, ingredient_name):\n # Deletes one ingredient\n\n try:\n print(\"DELETING ingredient \"+ingredient_name+\" from BOI with user_id>>>\"+self.username)\n delete_query = \"DELETE FROM bagofingredients WHERE user_id=\"+self.username+ \"AND ingredient_name=\"+ingredient_name+\";\"\n self.db.query(delete_query)\n except:\n print(\"ERROR OCCURED IN DELETION!\")\n return False\n return True\n\n def update_ingredient(self, ingredient_name, new_quantity):\n # Updates ingredient with new quantity\n\n try:\n print(\"UPDATING ingredient \"+ingredient_name+\" from BOI with user_id>>>\"+self.username)\n delete_query = \"UPDATE bagofingredients SET amount=\"+new_quantity+\"WHERE user_id=\"+self.username+\"AND ingredient_name=\"+ingredient_name+\";\"\n self.db.query(delete_query)\n except:\n print(\"ERROR OCCURED IN UPDATING!\")\n return False\n return True\n\n def update_new_boi(self):\n # Deletes boi and adds new one\n \n pass\n\n\n# TEST CASES FOR BOI FOR POSTGRESQL\n# boi_sample = BagOfIngredients(username)\n# boi_sample.get_boi()\n# boi_sample.push_boi(sample_ingredient)\n\n'''\nTHIS CAN BE USED FOR TESTING FIREBASE (OLD).\ndata = sample_user #check constants.py\n\n# CRUD operations example with predefined user from constants.py\nboi_sample = BagOfIngredients()\nauthenticated = boi_sample.authenticate_user(username, password)\nif authenticated:\n print(\"AUTHENTICATED!!\")\n boi_sample.get_boi()\n boi_sample.push_boi(sample_user)\n boi_sample.update_boi(\"diet\",\"non-vegetarian\")\n # boi_sample.delete_boi()\n'''\n","sub_path":"modules/bag_of_ingredients.py","file_name":"bag_of_ingredients.py","file_ext":"py","file_size_in_byte":3612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"530670222","text":"#!/usr/bin/python\n\nimport http.server\nimport socketserver\nimport os\nimport datetime\nimport threading\nimport time\nimport numpy as np\nimport pandas as pd\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\n\nPORT = int(os.environ.get(\"PORT\", 5000))\ndef server_files():\n os.chdir('data')\n Handler = http.server.SimpleHTTPRequestHandler\n Handler.extensions_map.update({\n '.webapp': 'application/x-web-app-manifest+json',\n })\n\n httpd = socketserver.TCPServer((\"\", PORT), Handler)\n print(\"Serving at port\", PORT)\n httpd.serve_forever()\n\ndef cleandata(df_raw):\n df_cleaned=df_raw.melt(id_vars=['Province/State','Country/Region','Lat','Long'],value_name='Cases',var_name='Date')\n df_cleaned=df_cleaned.set_index(['Country/Region','Province/State','Date'])\n return df_cleaned\n\ndef countrydata(df_cleaned,oldname,newname):\n df_country=df_cleaned.groupby(['Country/Region','Date'])['Cases'].sum().reset_index()\n df_country=df_country.set_index(['Country/Region','Date'])\n df_country.index=df_country.index.set_levels([df_country.index.levels[0], pd.to_datetime(df_country.index.levels[1])])\n df_country=df_country.sort_values(['Country/Region','Date'],ascending=True)\n df_country=df_country.rename(columns={oldname:newname})\n return df_country\n\ndef plotcountry(Country, CountryConsolidated):\n fig, axs = plt.subplots(3, 2)\n\n CountryConsolidated.loc[Country].reset_index().plot(ax=axs[0,0], style='.-', x='Date', y='Total Confirmed Cases')\n CountryConsolidated.loc[Country].reset_index().plot(ax=axs[0,1], style='.-', x='Date', y='Active Cases')\n CountryConsolidated.loc[Country].reset_index().plot(ax=axs[1,0], style='.-', x='Date', y='Total Deaths')\n CountryConsolidated.loc[Country].reset_index().plot(ax=axs[1,1], style='.-', x='Date', y='Total Recoveries')\n CountryConsolidated.loc[Country].reset_index().plot(ax=axs[2,0], style='.-', x='Date', y='Death to Cases Ratio')\n # CountryConsolidated.loc[Country].reset_index().plot(ax=axs[2,1], style='.-', x='Date', y='Total Confirmed Cases')\n # CountryConsolidated.plot()\n return fig\n\ndef dailydata(dfcountry,oldname,newname):\n dfcountrydaily=dfcountry.groupby(level=0).diff().fillna(0)\n dfcountrydaily=dfcountrydaily.rename(columns={oldname:newname})\n return dfcountrydaily\n\ndef update():\n ConfirmedCases=cleandata(pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv'))\n Deaths=cleandata(pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Deaths.csv'))\n Recoveries=cleandata(pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Recovered.csv'))\n\n ConfirmedCasesCountry=countrydata(ConfirmedCases,'Cases','Total Confirmed Cases')\n DeathsCountry=countrydata(Deaths,'Cases','Total Deaths')\n RecoveriesCountry=countrydata(Recoveries,'Cases','Total Recoveries')\n\n NewCasesCountry=dailydata(ConfirmedCasesCountry,'Total Confirmed Cases','Daily New Cases')\n NewDeathsCountry=dailydata(DeathsCountry,'Total Deaths','Daily New Deaths')\n NewRecoveriesCountry=dailydata(RecoveriesCountry,'Total Recoveries','Daily New Recoveries')\n\n CountryConsolidated=pd.merge(ConfirmedCasesCountry,NewCasesCountry,how='left',left_index=True,right_index=True)\n CountryConsolidated=pd.merge(CountryConsolidated,NewDeathsCountry,how='left',left_index=True,right_index=True)\n CountryConsolidated=pd.merge(CountryConsolidated,DeathsCountry,how='left',left_index=True,right_index=True)\n CountryConsolidated=pd.merge(CountryConsolidated,RecoveriesCountry,how='left',left_index=True,right_index=True)\n CountryConsolidated=pd.merge(CountryConsolidated,NewRecoveriesCountry,how='left',left_index=True,right_index=True)\n CountryConsolidated['Active Cases']=CountryConsolidated['Total Confirmed Cases']-CountryConsolidated['Total Deaths']-CountryConsolidated['Total Recoveries']\n CountryConsolidated['Share of Recoveries - Closed Cases']=np.round(CountryConsolidated['Total Recoveries']/(CountryConsolidated['Total Recoveries']+CountryConsolidated['Total Deaths']),2)\n CountryConsolidated['Death to Cases Ratio']=np.round(CountryConsolidated['Total Deaths']/CountryConsolidated['Total Confirmed Cases'],3)\n\n Countries = []\n for ind in list(ConfirmedCasesCountry.index):\n Countries += [ind[0]]\n\n Countries = np.unique(Countries)\n # print(CountryConsolidated)\n cs = (CountryConsolidated['Total Confirmed Cases'] != 0).groupby(level=0).cumsum()\n countryConsolidated = CountryConsolidated.drop(cs[cs == 0].index)\n for country in tqdm(Countries):\n fig = plotcountry(country, countryConsolidated)\n fig.savefig(country + \".png\", dpi=300)\n plt.close()\n\ndef main():\n threading.Thread(target=server_files).start()\n update()\n\nmain()","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":5052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"133422965","text":"import os\nimport requests\nimport time\nimport subprocess\nimport json\nimport re\nimport sys\nfrom moviepy.editor import VideoFileClip\nimport shutil\nfrom requests import exceptions\n\nmain_api = \"api.mgghot.com\"\npath = os.getcwd()\n\n\ndef get_data_file(path_file):\n fo = open(path_file, \"r\")\n lines = fo.readlines()\n fo.close()\n stt_video = ''\n\n if len(lines) == 0:\n return ''\n\n return lines[0]\n\n\nkey = get_data_file(\"config/key.txt\")\n\nkey_apis = get_data_file(\"config/key_api.txt\").split(\",\")\n\n\ndef get_list_video_by_api(channel_id, data_channel):\n results = []\n max_result = 30\n page_token = ''\n stt = 0\n key_api = key_apis[0]\n len_key_api = len(key_apis)\n\n while len(results) < 31:\n url = \"https://www.googleapis.com/youtube/v3/search?part=id&key=\" \\\n + str(key_api) + \"&channelId=\" + str(channel_id) + \"&maxResults=\" + str(max_result) \\\n + \"&order=date&pageToken=\" + str(page_token)\n\n req = requests.get(url)\n\n list_item = json.loads(req.content)\n\n if 'items' not in list_item:\n stt = stt + 1\n\n if stt >= len_key_api:\n return []\n\n key_api = key_apis[stt]\n continue\n\n items = list_item['items']\n\n try:\n page_token = list_item['nextPageToken']\n except KeyError:\n page_token = ''\n\n for item in items:\n try:\n id_video = item['id']['videoId']\n except KeyError:\n id_video = ''\n\n if id_video != '' and id_video not in data_channel:\n results.append(id_video)\n\n if page_token == '':\n break\n\n return results\n\n\ndef get_thumbnail(url, path_thumb):\n print(url)\n try:\n stdout = subprocess.check_output(['youtube-dl', '--list-thumbnails', url])\n\n arr = str(stdout).split('\\\\n')\n url = ''\n\n for i in arr:\n temp = re.findall(r'http(.*?).jpg', str(i))\n\n if len(temp) > 0:\n url = 'http' + temp[0] + '.jpg'\n\n if url == '':\n return ''\n\n r = requests.get(url)\n\n if r.status_code == 200:\n with open(path_thumb + '/thumbnail.jpg', 'wb') as file:\n for chunk in r.iter_content(1024):\n file.write(chunk)\n except:\n return ''\n\n return path_thumb + '/thumbnail.jpg'\n\n\ndef get_number_video(url):\n result = []\n\n try:\n stdout = subprocess.check_output(['youtube-dl', '-F', url])\n arr = str(stdout).split('\\\\n')\n\n audio = ''\n\n for item in arr:\n if 'm4a' in item:\n audio = item.split(' ')[0]\n\n for item in arr:\n if '1080' in item and 'mp4' in item:\n result.append(str(item.split(' ')[0]) + '+' + str(audio))\n\n if '720' in item and 'mp4' in item:\n result.append(str(item.split(' ')[0]) + '+' + str(audio))\n\n for item in arr:\n if '480' in item and 'mp4' in item:\n result.append(str(item.split(' ')[0]) + '+' + str(audio))\n\n for item in arr:\n if '360' in item and 'mp4' in item:\n result.append(str(item.split(' ')[0]) + '+' + str(audio))\n\n for item in arr:\n if '240' in item and 'mp4' in item:\n result.append(str(item.split(' ')[0]) + '+' + str(audio))\n except:\n return False\n\n return result\n\n\ndef download_video_from_youtube(id_video, path_page):\n numbers = get_number_video(\"https://www.youtube.com/watch?v=\" + str(id_video))\n\n platform = get_platform()\n\n if numbers is False:\n return False\n\n print(\"Downloading...\")\n for number in numbers:\n url = \"youtube-dl -f \" + str(number) + \" -o \" + path_page + '/' \\\n + \"input/input.%\\(ext\\)s https://www.youtube.com/watch?v=\" + str(id_video)\n\n if platform == 'Windows':\n url = \"youtube-dl -f \" + str(number) + \" -o \" + path_page + '/' \\\n + \"input/input.%(ext)s https://www.youtube.com/watch?v=\" + str(id_video)\n\n os.system(url)\n\n check = get_file_upload(path_page)\n\n if check:\n return True\n\n empty_folder(path_page + '/input')\n\n return True\n\n\ndef get_tags(id_video):\n for key_api in key_apis:\n url = \"https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&key=\" + key_api + \"&id=\" + str(id_video)\n\n req = requests.get(url)\n items = json.loads(req.content)\n tags = ''\n title = ''\n result = []\n\n try:\n if 'items' not in items:\n continue\n\n title = items['items'][0]['snippet']['title']\n except KeyError as e:\n print('I got a KeyError - reason \"%s\"' % str(e))\n\n try:\n tags = items['items'][0]['snippet']['tags']\n except KeyError as e:\n print('I got a KeyError - reason \"%s\"' % str(e))\n\n list_tag = ','.join(tags)\n result.append(title)\n result.append(list_tag)\n\n return result\n\n\ndef get_file_upload(path_page):\n filelist = os.listdir(path_page + '/input')\n\n for fichier in filelist:\n if \"input.mp4\" in fichier:\n return fichier\n\n return False\n\n\ndef getLength():\n filename = \"input/input.mp4\"\n clip = VideoFileClip(filename)\n\n return clip.duration\n\n\ndef get_ffmpeg(file_video, file_ffmpeg):\n path_file = 'ffmpeg-files/' + file_ffmpeg\n fo = open(path_file, \"r\")\n lines = fo.readlines()\n\n if len(lines) > 0:\n string_process = lines[0]\n string_process = string_process.replace(\"input.mp4\", 'input/input.ts')\n string_process = string_process.replace(\"output.mp4\", \"output/\" + str(file_video))\n\n return string_process\n\n return False\n\n\ndef process_video(file_name, length_cut):\n total_lentgh = getLength()\n\n string1 = \"ffmpeg -ss \" + str(length_cut) + \" -i input/input.mp4 -t \" \\\n + str(total_lentgh) + \" -c copy output/output.mp4\"\n os.system(string1)\n\n # string = \"ffmpeg -i /input/temp_input.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts /input/input.ts\"\n # os.system(string)\n\n # string_ffmpeg = get_ffmpeg(file_name, 'text.txt')\n # os.system(string_ffmpeg)\n\n return 'output/output.mp4'\n\n\ndef uploadVideoToFacebook(file_name, access_token, cookie, title, des, thumb, account_id):\n file_size = os.path.getsize(file_name)\n\n headers = {\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36',\n 'referer': 'https://www.facebook.com/'\n }\n\n try:\n url1 = \"https://graph-video.facebook.com/v2.3/me/videos?\"\n data1 = {\n 'access_token': access_token,\n 'upload_phase': \"start\",\n \"file_size\": file_size\n }\n\n req1 = requests.post(url1, data=data1, headers=headers, cookies=cookie)\n\n content1 = json.loads(req1.content)\n\n if 'upload_session_id' not in content1:\n update_check_point(account_id)\n return False\n\n upload_session_id = content1['upload_session_id']\n\n data2 = {\n 'access_token': access_token,\n 'upload_phase': 'transfer',\n 'start_offset': 0,\n 'upload_session_id': upload_session_id\n }\n\n up = {'video_file_chunk': (file_name, open(file_name, 'rb'), \"multipart/form-data\")}\n req2 = requests.post(url1, files=up, data=data2, headers=headers, cookies=cookie)\n\n data3 = {\n 'access_token': access_token,\n 'upload_phase': 'finish',\n 'upload_session_id': upload_session_id,\n 'title': title,\n 'description': des\n }\n\n thumb = {'thumb': (thumb, open(thumb, 'rb'), \"multipart/form-data\")}\n\n req3 = requests.post(url1, files=thumb, data=data3, headers=headers, cookies=cookie)\n\n print(req3.content)\n result = json.loads(req3.content)['success'] is True\n except KeyError as e:\n print(e)\n return False\n\n return result\n\n\ndef getLengthVideo(input_video):\n platform = get_platform()\n\n if platform == 'Windows':\n string = 'ffprobe -i ' + input_video + ' -show_entries format=duration -v quiet -of csv=\"p=0\"'\n result = subprocess.Popen(string, stdout=subprocess.PIPE,stderr=subprocess.STDOUT)\n output = result.communicate()[0].strip()\n\n index = str(output).find('.')\n output = output[:index - 2]\n\n return int(output)\n\n string = 'ffprobe -i ' + input_video + ' -show_entries format=duration -v quiet -of csv=\"p=0\"'\n\n result = subprocess.getoutput(string)\n output = result.split()[0].strip()\n output = float(output)\n output = int(output)\n # index = str(output).find('.')\n # output = output[:index - 2]\n\n return int(output)\n\n\ndef hanlde(access_token, cookie, name_title, description, genres, thumbnail, path_page, path_thumb, account_id):\n check = False\n file = get_file_upload(path_page)\n\n if file is False:\n empty_folder(path_page + \"/input\")\n\n return False\n\n file_name = path_thumb + '/input/' + file\n\n title = name_title\n des = description\n id_page = \"me\"\n link_video = file_name\n length_video = getLengthVideo(file_name)\n print(length_video)\n print(\"Uploading...\")\n\n if length_video < 1200:\n check = uploadVideoToFacebook(link_video, access_token, cookie, title, des, thumbnail, account_id)\n else:\n if length_video > 3000:\n pass\n else:\n print(\"Upload by nodejs\")\n\n if get_platform() == 'Windows':\n string_upload = \"node upload-video-to-facebook/main.js --id=\\\"\" + id_page + \"\\\" --token=\\\"\" + access_token \\\n + \"\\\" --title=\\\"\" + title + \"\\\" --des=\\\"\" \\\n + des + \" \\\" --video=\\\"\" + link_video + \"\\\" --tags=\\\"\" + genres + \"\\\" --thumb=\\\"\" + thumbnail + \"\\\"\"\n else:\n string_upload = \"sudo node upload-video-to-facebook/main.js --id=\\\"\" + id_page + \"\\\" --token=\\\"\" + access_token \\\n + \"\\\" --title=\\\"\" + title + \"\\\" --des=\\\"\" \\\n + des + \" \\\" --video=\\\"\" + link_video + \"\\\" --tags=\\\"\" + genres + \"\\\" --thumb=\\\"\" + thumbnail + \"\\\"\"\n\n os.system(string_upload)\n check = True\n\n empty_folder(path_page + \"/input\")\n\n if thumbnail != '':\n os.remove(path_page + '/thumbnail.jpg')\n\n return check\n\n\ndef get_list_video(info_api, path_page, path_thumb, account_id):\n print(\"Get list video..\")\n source = info_api['source']\n data_channel = info_api['data_channel']\n\n channel_id = info_api['channel_id']\n access_token = info_api['access_token']\n cookie = info_api['cookie']\n\n items = get_list_video_by_api(source, data_channel)\n\n for id_video in items:\n info = get_tags(id_video)\n\n title = info[0]\n tags = info[1]\n\n description = title\n\n check = False\n\n thumbnail = get_thumbnail(\"https://www.youtube.com/watch?v=\" + str(id_video), path_thumb)\n\n has_video = download_video_from_youtube(id_video, path_page)\n\n if has_video:\n check = hanlde(access_token, cookie, title, description, tags, thumbnail, path_page, path_thumb, account_id)\n else:\n save_data_by_api(channel_id, id_video)\n\n if check:\n save_data_by_api(channel_id, id_video)\n\n print(\"Done\")\n print(\"Channel id:\" + str(channel_id))\n # time.sleep(7200)\n else:\n # update_check_point(account_id)\n pass\n break\n\n\ndef save_data_by_api(channel_id, video_id):\n url = \"http://\" + main_api + \"/data/set.php\"\n\n data = {\n 'video_id': video_id,\n 'channel_id': channel_id,\n 'key': key\n }\n\n req = requests.post(url, data=data)\n\n if req.status_code != 200:\n return False\n\n return True\n\n\ndef get_info_by_api(page_number, account_id):\n url = \"http://\" + main_api + \"/accesstoken/get.php\"\n\n results = {\n 'status_code': 200,\n 'data': []\n }\n data = {\n 'page_number': page_number,\n 'account_id': account_id,\n 'key': key\n }\n\n req = requests.get(url, params=data)\n\n results['status_code'] = req.status_code\n\n if req.status_code != 200:\n return results\n\n datas = req.json()\n\n if int(datas['status']) != 0:\n access_token = datas['accesstoken']\n cookie = generate_cookie(datas['cookie'])\n channel_id = datas['channel_id']\n\n source = get_source(channel_id)\n data_channel = get_data_channel(channel_id)\n\n result = {\n 'access_token': access_token,\n 'cookie': cookie,\n 'channel_id': channel_id,\n 'source': source,\n 'data_channel': data_channel\n }\n\n results['data'] = result\n\n return results\n\n\ndef get_source(channel_id):\n url = \"http://\" + main_api + \"/channel/get.php\"\n\n data = {\n 'channel_id': channel_id,\n 'key': key\n }\n\n req = requests.get(url, params=data)\n\n if req.status_code != 200:\n return False\n data = req.json()\n\n return data['records'][0]['source']\n\n\ndef get_data_channel(channel_id):\n url = \"http://\" + main_api + \"/data/get.php\"\n\n data = {\n 'channel_id': channel_id,\n 'key': key\n }\n\n req = requests.get(url, params=data)\n\n if req.status_code != 200:\n return False\n\n data = req.json()\n\n return data['records']\n\n\ndef check_and_create_dir(account_id, page_number):\n path_account = path + '/' + account_id\n path_page = path + '/' + account_id + '/' + page_number\n\n if os.path.isdir(account_id) is False:\n os.mkdir(path_account)\n\n if os.path.isdir(path_page) is False:\n os.mkdir(path_page)\n\n if os.path.isdir(path_page + \"/input\") is False:\n os.mkdir(path_page + \"/input\")\n\n if os.path.isdir(path_page + \"/output\") is False:\n os.mkdir(path_page + \"/output\")\n\n\ndef empty_folder(path_folder):\n shutil.rmtree(path_folder)\n os.makedirs(path_folder)\n\n\ndef update_data():\n channel_id = str(input(\"Channel id: \"))\n list_id = str(input(\"List id: \"))\n\n url = \"http://\" + main_api + \"/data/update_data.php\"\n\n data = {\n 'channel_id': channel_id,\n 'list_id': list_id\n }\n\n req = requests.post(url, data=data)\n print(req.status_code)\n\n\ndef setupDataToServer(account_id, page_number):\n source = str(input(\"Source: \"))\n access_token = str(input(\"Access token: \"))\n\n url = \"http://\" + main_api + \"/accesstoken/set.php\"\n\n data = {\n 'account_id': account_id,\n 'page_number': page_number,\n 'source': source,\n 'accesstoken': access_token,\n 'key': key\n }\n\n req = requests.post(url, data=data)\n\n if req.status_code == 200:\n return True\n\n return False\n\n\ndef auto(arr):\n count_reset = 0\n stt = 0\n\n while True:\n try:\n for i in range(len(arr)):\n account_id = str(i + 1)\n\n if stt > len(arr[i]) - 1:\n count_reset = count_reset + 1\n continue\n\n try:\n page_number = str(arr[i][stt])\n except IndexError:\n count_reset = count_reset + 1\n continue\n\n path_page = path + '/' + account_id + '/' + page_number\n path_thumb = account_id + '/' + page_number\n check_and_create_dir(account_id, page_number)\n\n result = get_info_by_api(page_number, account_id)\n\n if result['status_code'] != 200:\n print(\"Setup new data!\")\n setupDataToServer(account_id, page_number)\n result = get_info_by_api(page_number, account_id)\n\n info = result['data']\n\n if len(info) == 0:\n count_reset = count_reset + 1\n continue\n\n get_list_video(info, path_page, path_thumb, account_id)\n\n stt = stt + 1\n\n if count_reset >= len(arr):\n count_reset = 0\n stt = 0\n\n time.sleep(600)\n except exceptions.ConnectionError:\n print(\"Error Connect!\")\n time.sleep(300)\n\n\ndef default():\n account_id = str(input(\"Account id: \"))\n page_number = str(input(\"Page number: \"))\n\n path_page = path + '/' + account_id + '/' + page_number\n path_thumb = account_id + '/' + page_number\n check_and_create_dir(account_id, page_number)\n\n while True:\n try:\n result = get_info_by_api(page_number, account_id)\n\n if result['status_code'] != 200:\n print(\"Setup new data!\")\n setupDataToServer(account_id, page_number)\n result = get_info_by_api(page_number, account_id)\n\n info = result['data']\n\n if len(info) == 0:\n print(\"Account have been checkpoint!\")\n continue\n\n get_list_video(info, path_page, path_thumb, account_id)\n\n time.sleep(600)\n except exceptions.ConnectionError:\n print(\"Error connect!\")\n time.sleep(100)\n\n\ndef get_platform():\n platforms = {\n 'linux1': 'Linux',\n 'linux2': 'Linux',\n 'darwin': 'OS X',\n 'win32': 'Windows'\n }\n if sys.platform not in platforms:\n return sys.platform\n\n return platforms[sys.platform]\n\n\ndef update_check_point(account_id):\n print(\"Update Check point! Account id: \" + str(account_id))\n url = \"http://\" + main_api + \"/account/updateCheckpoint.php\"\n\n data = {\n 'account_id': account_id,\n 'key': key\n }\n\n req = requests.post(url, data=data)\n\n if req.status_code != 200:\n return False\n\n return True\n\n\ndef generate_cookie(string_cookie):\n if string_cookie == '':\n return {}\n\n string_cookie = string_cookie.replace(\" \", \"\")\n arr = string_cookie.split(\";\")\n result = {}\n\n for i in range(len(arr)):\n key, value = arr[i].split(\"=\")\n\n result[key] = value\n\n return result\n\n\nif __name__ == '__main__':\n arr_page = [[1, 2, 3], [3, 4], [1, 2], [1, 2, 3], [], []]\n\n option = str(input(\"One page (0) OR All page (1) ? \"))\n\n if option == \"0\":\n default()\n else:\n auto(arr_page)\n","sub_path":"main-blk.py","file_name":"main-blk.py","file_ext":"py","file_size_in_byte":18464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"223592429","text":"import threading, time, sound, ui, console\n\nstop = True\nsound.set_honors_silent_switch(False)\n\n@ui.in_background\ndef timer(label, times):\n\tglobal stop\n\t\n\twhile not stop:\n\t\tfor myTime in times:\n\t\t\tgo(myTime, label)\n\ndef go(seconds,label):\n\tglobal stop\n\tmyTime = seconds\n\t\n\twhile myTime > 0:\n\t\tif stop or not label.on_screen:\n\t\t\tbreak\n\t\t\t\n\t\tlabel.text = str(myTime)\n\t\ttime.sleep(1)\n\t\tmyTime -= 1\n\t\t\n\tif not stop and label.on_screen:\t\n\t\tlabel.text = '0'\n\t\tsound.play_effect('arcade:Coin_5')\n\t\ttime.sleep(.3)\n\t\tsound.play_effect('arcade:Coin_5')\n\t\t\t\n\n#prevent multiple taps\ndef button_tapped(sender):\n\t'@type sender: ui.Button'\n\tglobal stop\n\tglobal threadpool\n\tbutton = sender.name\n\t\n\tif button == 'stopButton':\n\t\tstop = True\n\t\tconsole.set_idle_timer_disabled(False)\n\telif button == 'okButton':\n\t\tif stop:\n\t\t\tconsole.set_idle_timer_disabled(True)\n\t\t\tstop = False\n\t\t\tsetting = sender.superview['segmentedControl'].selected_index\n\t\t\tlabel = sender.superview['timerLabel']\n\t\t\tif setting == 0:\n\t\t\t\ttimes = [60, 60, 30, 30]\n\t\t\telse:\n\t\t\t\ttimes = [40]\n\t\t\t\t\n\t\t\ttimer(label, times)\n\t\t\n\t\nv = ui.load_view()\nv.present('sheet')\t\n","sub_path":"stretchTimer.py","file_name":"stretchTimer.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"342520813","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\nfrom sklearn.model_selection import StratifiedShuffleSplit\nfrom sklearn.model_selection import train_test_split\n\nfrom .config import CONFIG\n# Types of devices in the model\n_deviceList = ['ac', 'tv', 'fan', 'light', 'geyser']\n\ndef device_exists(command: str, ft_model) -> bool:\n '''Checks whether the given string contains one of the many devices\n supported by the model. \n '''\n # Get the 4 nearest words to each device and create a dictionary\n top_nearest_words_to_devices = {}\n for device in _deviceList:\n top_nearest_words_to_devices[device] = []\n nearestWords = ft_model.get_nearest_neighbors(device, k=4)\n top_nearest_words_to_devices[device].extend([word for _, word in nearestWords])\n top_nearest_words_to_devices[device].extend([device])\n\n for word in command.split(' '):\n for device in _deviceList:\n if word in top_nearest_words_to_devices[device]:\n return True\n \n return False\n\ndef add_class_ovr_cols(dataset: pd.DataFrame) -> pd.DataFrame:\n '''Add a column for each class representing whether that class\n is present for that instance or not (OVR Technique)\n '''\n classList = dataset['label'].unique()\n for label in classList:\n dataset[label] = np.where(dataset['label'] == label, 1, 0)\n return dataset\n\ndef shuffle_split(dataset: pd.DataFrame, label: str):\n '''A generator function to split the dataset using \n StratifiedShuffleSplit and return each split\n '''\n sss = StratifiedShuffleSplit(n_splits=10, test_size=0.2, random_state=20)\n\n # Code taken from https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedShuffleSplit.html\n X, y = dataset['sent_vec'], dataset[label]\n for train_index, test_index in sss.split(X, y):\n X_train, X_test = np.stack(X.iloc[train_index]), np.stack(X.iloc[test_index])\n y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n yield np.asarray(X_train), np.asarray(X_test), \\\n np.asarray(y_train), np.asarray(y_test)\n\ndef data_split_classwise(dataset: pd.DataFrame):\n '''Split the data according to the OVR mechanism for \n per class training.\n '''\n classList = dataset['label'].unique()\n for label in classList:\n X, y = dataset['sent_vec'], dataset[label]\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, \\\n random_state=40, stratify=y)\n X_train, X_test = np.stack(X_train), np.stack(X_test)\n yield np.asarray(X_train), np.asarray(X_test), \\\n np.asarray(y_train), np.asarray(y_test), label\n\ndef data_split(dataset: pd.DataFrame, test_size: float = 0.25):\n '''Split the dataset into train and test sets.\n '''\n X, y = dataset['sent_vec'], dataset['label']\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, \\\n random_state=40, stratify=y)\n train_df, test_df = pd.DataFrame(X_train), pd.DataFrame(X_test)\n train_df['y'], test_df['y'] = y_train, y_test\n return train_df, test_df\n\ndef plot(models):\n fig = plt.figure(figsize=(20, 60))\n plot_count = 1\n for m_name in models.keys():\n history = models[m_name]['history'].history\n plt.subplot(len(models.keys()), 3, plot_count)\n plt.xlabel('epochs')\n plt.grid()\n plt.ylabel('loss')\n plt.xticks(range(0, len(history['loss']) + 1, 5))\n plt.plot(history['loss'])\n plt.plot(history['val_loss'])\n plt.title(map_label(m_name))\n plt.legend(['Train Set', 'Validation Set'], loc='upper right')\n plot_count += 1\n \n plt.subplot(len(models.keys()), 3, plot_count)\n plt.xlabel('epochs')\n plt.grid()\n plt.ylabel('F1 Score')\n plt.xticks(range(0, len(history['_f1_score']) + 1, 5))\n plt.plot(history['_f1_score'])\n plt.plot(history['val__f1_score'])\n plt.title(map_label(m_name))\n plt.legend(['Train Set', 'Validation Set'], loc='lower right')\n plot_count += 1\n\n plt.subplot(len(models.keys()), 3, plot_count)\n plt.xlabel('epochs')\n plt.grid()\n plt.ylabel('accuracy')\n plt.xticks(range(0, len(history['accuracy']) + 1, 5))\n plt.plot(history['accuracy'])\n plt.plot(history['val_accuracy'])\n plt.title(map_label(m_name))\n plt.legend(['Train Set', 'Validation Set'], loc='lower right')\n plot_count += 1\n\n return fig\n\ndef map_label(label:str)-> str:\n label_map = {\n '__label__light_off': 'light off',\n '__label__light_on': 'light on',\n '__label__geyser_on': 'geyser on',\n '__label__geyser_off': 'geyser off',\n '__label__fan_on': 'fan on',\n '__label__fan_off': 'fan off',\n '__label__tv_on': 'tv on',\n '__label__tv_off': 'tv off',\n '__label__ac_on': 'ac on',\n '__label__ac_off': 'ac off',\n 'Other': 'other'\n }\n\n return label_map[label]\n","sub_path":"app/hats/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":5071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"503040042","text":"\"\"\" Rudimentary N-body Gravity Simulator by Levi Van Ryder\n Written in Python 3.8.5 \"\"\"\nfrom vpython import *\nimport random\n\n# Canvas for simulation\nscene = canvas(title='N-body Gravity Simulator', width=1920, height=1080, caption='Created by PushingMyRocheLimits')\n\n# Axis for reference and initial camera angle\nx = cylinder(pos=vector(0, 0, 0), axis=vector(1, 0, 0), size=vector(10000, 10, 10), color=color.white, opacity=0.5)\nx_neg = cylinder(pos=vector(0, 0, 0), axis=vector(-1, 0, 0), size=vector(10000, 10, 10), color=color.white, opacity=0.5)\nlabel(pos=x.axis, text='x', font='serif')\nlabel(pos=x_neg.axis, text='x', font='serif')\ny = cylinder(pos=vector(0, 0, 0), axis=vector(0, 1, 0), size=vector(10000, 10, 10), color=color.white, opacity=0.5)\ny_neg = cylinder(pos=vector(0, 0, 0), axis=vector(0, -1, 0), size=vector(10000, 10, 10), color=color.white, opacity=0.5)\nlabel(pos=y.axis, text='y', font='serif')\nlabel(pos=y_neg.axis, text='y', font='serif')\nz = cylinder(pos=vector(0, 0, 0), axis=vector(0, 0, 1), size=vector(10000, 10, 10), color=color.white, opacity=0.5)\nz_neg = cylinder(pos=vector(0, 0, 0), axis=vector(0, 0, -1), size=vector(10000, 10, 10), color=color.white, opacity=0.5)\nlabel(pos=z.axis, text='z', font='serif')\nlabel(pos=z_neg.axis, text='z', font='serif')\nscene.camera.pos = vector(1000, 500, 100)\n\n# Calculates the forces that two stars experience (Newton's Law of Universal Gravitation vector form)\ndef cal_force (p1, p2):\n G = 6.67e-11\n r_vector = (p1.pos - p2.pos)\n r_magnitude = mag(r_vector)\n r_hat = (r_vector / r_magnitude)\n force_magnitude = ((G * p1.mass * p2.mass) / (r_magnitude ** 2))\n force_vector = (-force_magnitude * r_hat)\n return force_vector\n\n# Variable for data storage\nstars_data = []\nmomentum_sum = vec(0, 0, 0)\n\n# Number of stars that will be generated\nnum_stars = int(input(\"How many stars?: \"))\n\n# Asks user whether they want random values for stars or to manually enter in values\n'''Demo mode plugs in random values for the stars and Manual allows for custom data entry'''\nuser_setting = input(\"For random values, enter 'Demo'. For manual values, enter in 'Manual': \")\nif user_setting.lower() == 'manual':\n for i in range(num_stars):\n star = sphere(pos=vector(int(input(\"X Position: \")), int(input(\"Y Position: \")), int(input(\"Z Position: \"))),\n mass=int(input(\"Mass of Star: \")), color=color.yellow, momentum=vector(int(input(\"X Velocity: \")),\n int(input(\"Y Velocity: \")), int(input(\"Z Velocity: \"))), make_trail=True, trail_radius=3)\n star.radius = star.mass / 10000\n stars_data.append(star)\n momentum_sum = momentum_sum + star.momentum\n print('simulation starting...')\nelif user_setting.lower() == 'demo':\n for i in range(num_stars):\n star = sphere(pos=vector(random.randrange(-5000, 5000), random.randrange(-5000, 5000),\n random.randrange(-5000, 5000)), mass=random.randrange(100000, 500000), color=color.yellow,\n momentum=vector(random.randrange(-10, 10), random.randrange(-10, 10), random.randrange(-10, 10)),\n make_trail=True, trail_radius=3)\n star.radius = star.mass / 10000\n stars_data.append(star)\n momentum_sum = momentum_sum + star.momentum\n print('simulation starting...')\n\n# ROC of Time\ndt = 5000\n\n# Adds up momentum for each star\nfor i in range(num_stars):\n stars_data[i].momentum = (stars_data[i].momentum + (momentum_sum / num_stars))\n\n# Performs the simulation \nwhile True:\n rate(1000)\n L = len(stars_data)\n for i in range(L):\n stars_data_i = stars_data[i]\n force = vec(0, 0, 0)\n for j in range(L):\n if i == j:\n continue\n stars_data_j = stars_data[j]\n force = force + cal_force(stars_data_i, stars_data_j)\n stars_data_i.momentum = (stars_data_i.momentum + (force * dt))\n for star in stars_data:\n if star == None:\n continue\n star.pos = (star.pos + (star.momentum * (dt / star.mass)))\n","sub_path":"N-body Gravity Simulator Update 1.py","file_name":"N-body Gravity Simulator Update 1.py","file_ext":"py","file_size_in_byte":4094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"500194789","text":"import sqlite3\n\n# connect with the myTable database\nconnection = sqlite3.connect(\"XE\")\n\n# cursor object\ncrsr = connection.cursor()\nsql_command = \"\"\"INSERT INTO employee VALUES (10, \"Abeer\", \"Gates\", \"M\", \"1980-10-28\");\"\"\"\n# execute the command to fetch all the data from the table emp\ncrsr.execute(sql_command)\ncrsr.execute(\"SELECT * FROM employee\")\n\nans = crsr.fetchall()\n\n# loop to print all the data\nfor i in ans:\n print(i)","sub_path":"pandas_numpy/database_2.py","file_name":"database_2.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"287253937","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue May 28 23:18:19 2019\r\n\r\n@author: tusha\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom decimal import Decimal\r\nimport numpy as np\r\nimport seaborn as sb\r\nh1b_data = pd.read_csv('C://Users//tusha//Desktop//Tushar School Documents//Masters Project//ian-h-1-b-disclosure-data-fy-17//h1b_kaggle_55.csv')\r\n\r\nlen(h1b_data)\r\nh1b_data.EMPLOYER_NAME.value_counts().head(15)\r\n\r\nh1b_data['EMPLOYER_NAME'].value_counts().head(15).plot(kind = \"bar\" , title =\"Top 15 Hiring Company\")\r\n\r\n\r\nh1b_data.PREVAILING_WAGE.value_counts().sort_values(ascending = False).head(15)\r\n\r\n\r\nh1b_data.PREVAILING_WAGE.mean()\r\n\r\ndenied = h1b_data[h1b_data.CASE_STATUS=='DENIED']\r\n\r\nnooooo = h1b_data[h1b_data.YEAR == 'nan']\r\nh1b_data.dropna()\r\nDAta = h1b_data[h1b_data.JOB_TITLE == 'DATA ANALYST']\r\n\r\nDAta['EMPLOYER_NAME'].value_counts().head(50)\r\n\r\n#wages given by employee\r\nwages_employee = h1b_data.groupby(['EMPLOYER_NAME']).mean()['PREVAILING_WAGE'].nlargest(15).plot(kind = 'bar')\r\n\r\nh1b_data.WORKSITE.value_counts().head(20)\r\n\r\nh1b_data.WORKSITE.value_counts().head(20).plot(kind = 'bar', title =\"Cities with Highest Job opportunity \")\r\n\r\nh1b_data.loc[:,'WORKSITE'] = h1b_data.loc[:,'WORKSITE'].apply(lambda rec:rec.split(',')[1][1:])\r\n\r\ndef change_NA(rec):\r\n if (rec=='NA'):\r\n return 'MARINA ISLANDS'\r\n return rec\r\nh1b_data.loc[:,'WORKSITE'] = h1b_data.loc[:,'WORKSITE'].apply(lambda rec: change_NA(rec))\r\nprint(len(h1b_data['WORKSITE'].unique()))\r\n\r\n\r\nh1b_data['CASE_STATUS'].unique()\r\n\r\n\r\nstatus_freq = [0]*7\r\n\r\nstatues = ['CERTIFIED-WITHDRAWN', 'WITHDRAWN', 'CERTIFIED', 'DENIED',\r\n 'REJECTED', 'INVALIDATED',\r\n 'PENDING QUALITY AND COMPLIANCE REVIEW - UNASSIGNED']\r\n\r\nfor i in range(0,7):\r\n status_freq[i] = h1b_data[h1b_data.CASE_STATUS==statues[i]]['CASE_STATUS'].count()\r\nstatus_freq\r\n#status_freq.unique()\r\nfrom matplotlib.pyplot import pie,axis,show\r\nimport matplotlib as mpl\r\n\r\nplt.figure(figsize = (5,5))\r\nplt.title('PETITIONS BY CASE STATUS')\r\naxis('equal');\r\npie(status_freq[:4], labels = statues[:4]);\r\nshow()\r\n\r\n#h1b_data.EMPLOYMENT_START_DATE = pd.tslib.Timestamp.now()\r\nh1b_data['YEAR'] = h1b_data['YEAR'].apply(lambda year:'%g' % (Decimal(str(year))))\r\n\r\nh1b_data['PREVAILING_WAGE'] = h1b_data['PREVAILING_WAGE'].apply(lambda year:'%g' % (Decimal(str(year))))\r\n\r\nyear = ['2011','2012','2013','2014','2015','2016']\r\nyear_count = [0]*6\r\nfor i in range(0,6):\r\n year_count[i] = h1b_data[h1b_data.YEAR==year[i]]['YEAR'].count()\r\nyear_count\r\n\r\nsb.set_context(\"notebook\",font_scale=1.0)\r\nplt.figure(figsize=(13,3))\r\nplt.title('PETITIONS DISTRIBUTION BY YEAR')\r\nsb.countplot(h1b_data['YEAR'])\r\n\r\ndenied = h1b_data[h1b_data.CASE_STATUS=='DENIED']\r\nlen(denied)\r\n\r\n\r\ndel denied['CASE_STATUS']\r\ndenied = denied.reset_index()\r\ndenied.head()\r\n\r\ndenied_year_count = [0]*6\r\nfor i in range(0,6):\r\n denied_year_count[i] = denied[denied.YEAR==year[i]]['YEAR'].count()\r\ndenied_year_count\r\n\r\n\r\nsb.set_context(\"notebook\",font_scale=1.0)\r\nplt.figure(figsize=(13,3))\r\nplt.title('DENIED PETITIONS BY YEAR')\r\nsb.countplot(denied['YEAR'])\r\n\r\ndenied_rate = [0]*6\r\nfor i in range(0,6):\r\n denied_rate[i] = float(\"%.2f\" % ((denied_year_count[i] / year_count[i])*100))\r\n\r\nratio = pd.DataFrame()\r\nratio['year'] = year\r\nratio['denied rate %'] = denied_rate\r\nratio = ratio.set_index(['year'])\r\nratio.T\r\n\r\nratio = ratio.reset_index()\r\nsb.set_context(\"notebook\",font_scale=1.0)\r\nplt.figure(figsize=(13,3))\r\nplt.title('DENIED PETITIONS RATE BY YEAR')\r\ng= sb.barplot(x='year' , y = 'denied rate %', data = ratio)\r\n\r\nUS_states = ['Alabama','Alaska','Arizona','Arkansas','California','Colorado ','Connecticut','Delaware',\r\n 'District of Columbia','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana',\r\n 'Maine','Marina Islands','Maryland','Massachusetts','Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska',\r\n 'Nevada','New Hampshire','New Jersey','New Mexico','New York','North Carolina','North Dakota',\r\n 'Ohio','Oklahoma','Oregon','Pennsylvania','Puerto Rico','Rhode Island','South Carolina','South Dakota','Tennessee',\r\n 'Texas ','Utah','Vermont','Virginia','Washington','West Virginia','Wisconsin','Wyoming']\r\n\r\nUS_states = [x.upper() for x in US_states] \r\n \r\n# printing output \r\nprint(US_states) \r\nlen(US_states)\r\npetition_by_state = [0]*53\r\nfor i in range(0,53):\r\n petition_by_state[i] = h1b_data[h1b_data.WORKSITE == US_states[i]]['WORKSITE'].count()\r\npet_state = pd.DataFrame()\r\npet_state['STATE'] = US_states\r\npet_state['FILED PETITIONS'] = petition_by_state\r\nprint(sum(petition_by_state))\r\n\r\n\r\nsb.set_context(\"notebook\",font_scale=1.0)\r\nplt.figure(figsize=(13,5))\r\nplt.title('FILED PETITIONS BY STATE')\r\nv= sb.barplot(x='STATE' , y = 'FILED PETITIONS', data = pet_state)\r\nrotg = v.set_xticklabels(v.get_xticklabels(), rotation = 90)\r\n\r\n########\r\nlen(denied)\r\ndenied_by_state = [0]*53\r\nfor i in range(0,53):\r\n denied_by_state[i] = denied[denied.WORKSITE == US_states[i]]['WORKSITE'].count()\r\nden_state = pd.DataFrame()\r\nden_state['STATE'] = US_states\r\nden_state['DENIED PETITIONS'] = denied_by_state\r\nprint(sum(denied_by_state))\r\n\r\n\r\nsb.set_context(\"notebook\",font_scale=1.0)\r\nplt.figure(figsize=(13,5))\r\nplt.title('DENIED PETITIONS BY STATE')\r\nv= sb.barplot(x='STATE' , y = 'DENIED PETITIONS', data = den_state)\r\nrotg = v.set_xticklabels(v.get_xticklabels(), rotation = 90)\r\n\r\n\r\n\r\n#######\r\n\r\ndenied_state_rate = [0]*53\r\nfor i in range(0,53):\r\n denied_state_rate[i] = float(\"%.2f\" % ((denied_by_state[i] / petition_by_state[i])*100))\r\nratios = pd.DataFrame()\r\nratios['STATE'] = US_states\r\nratios['DENIED PETITIONS %'] = denied_state_rate\r\nprint(sum(denied_state_rate))\r\n\r\n\r\nsb.set_context(\"notebook\",font_scale=1.0)\r\nplt.figure(figsize=(13,5))\r\nplt.title('DENIED PETITIONS BY STATE')\r\nv= sb.barplot(x='STATE' , y = 'DENIED PETITIONS %', data = ratios)\r\nrotg = v.set_xticklabels(v.get_xticklabels(), rotation = 90)\r\n\r\n\r\npet_state['DENIED PETITIONS'] = denied_by_state\r\npet_state['DENIED PETITIONS %'] = denied_state_rate\r\npet_state = pet_state.sort_values(by='DENIED PETITIONS %',ascending = False)\r\npet_state\r\n\r\n\r\nh1b_data.JOB_TITLE.value_counts().head(15)\r\n\r\nh1b_data['JOB_TITLE'].value_counts().head(15).plot(kind = \"bar\" , title =\"Top 15 Jobs\")","sub_path":"h1b.py","file_name":"h1b.py","file_ext":"py","file_size_in_byte":6341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"642584166","text":"import argparse\n\nimport numpy as np \nimport pandas as pd \nimport csv\nimport os\nimport time\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--src', type = str, default = 'Office_Products')\n parser.add_argument('--dst', type = str, default = 'Movies_and_TV')\n parser.add_argument('--savepath', type = str, default = '../../data/dataset_1')\n \n return parser.parse_args()\n\n# 提取共享用户的评分信息\ndef draw_shareuser(src, dst):\n if(os.path.exists('src_temp1.csv')):\n os.remove('src_temp1.csv')\n if(os.path.exists('dst_temp1.csv')):\n os.remove('dst_temp1.csv')\n \n src_set = set()\n dst_set = set()\n\n# 首先获得共享用户集合\n # 源数据集的用户集合\n src_read = csv.reader(open(src, 'r'))\n for row in src_read:\n src_set.add(row[0])\n\n # 目的数据集的用户集合\n dst_read = csv.reader(open(dst, 'r'))\n for row in dst_read:\n dst_set.add(row[0])\n\n # 源数据和目的数据集的用户集合的交集,即共享用户集合\n union_set = src_set & dst_set\n print(\"Src_data:%s\\nDst_data:%s\\nShared Users#%d\" %(src, dst, len(union_set)))\n# 然后根据共享用户集合,筛选出所有共享用户的评分信息,即只保留共享用户的评分信息,写入src_temp1.csv和dst_temp1.csv文件中\n src_read = csv.reader(open(src, 'r'))\n with open('src_temp1.csv', 'a', newline = '') as src_out:\n src_write = csv.writer(src_out, dialect = 'excel')\n i = 0\n for row in src_read:\n if row[0] in union_set:\n src_write.writerow(row)\n i += 1\n print('Src Ratings#%d' %i)\n\n dst_read = csv.reader(open(dst, 'r'))\n with open('dst_temp1.csv', 'a', newline = '') as dst_out:\n dst_write = csv.writer(dst_out, dialect = 'excel')\n i = 0\n for row in dst_read:\n if row[0] in union_set:\n dst_write.writerow(row)\n i += 1\n print('Dst Ratings#%d' %i)\n\n# 重新编码userid和itemid\ndef recode_userid_itemid():\n if(os.path.exists('src_temp2.csv')):\n os.remove('src_temp2.csv')\n if(os.path.exists('dst_temp2.csv')):\n os.remove('dst_temp2.csv')\n \n userid = 0\n itemid = 0\n\n userdict = {}\n itemdict = {}\n\n src_read = csv.reader(open('src_temp1.csv', 'r'))\n with open('src_temp2.csv', 'a', newline = '') as src_out:\n src_write = csv.writer(src_out, dialect = 'excel')\n i = 0\n for row in src_read:\n ori_userid = row[0]\n ori_itemid = row[1]\n if ori_userid not in userdict:\n userdict[ori_userid] = userid\n userid += 1\n if ori_itemid not in itemdict:\n itemdict[ori_itemid] = itemid\n itemid += 1\n i += 1\n row[0] = userdict[ori_userid]\n row[1] = itemdict[ori_itemid]\n src_write.writerow(row)\n print('Src_save Ratings#%d Src_Users#%d Src_Items#%d' %(i, len(userdict), len(itemdict)))\n\n itemid = 0\n itemdict.clear()\n\n dst_read = csv.reader(open('dst_temp1.csv', 'r'))\n with open('dst_temp2.csv', 'a', newline = '') as dst_out:\n dst_write = csv.writer(dst_out, dialect = 'excel')\n i = 0\n for row in dst_read:\n ori_userid = row[0]\n ori_itemid = row[1]\n if ori_userid in userdict:\n row[0] = userdict[ori_userid]\n if ori_itemid not in itemdict:\n itemdict[ori_itemid] = itemid\n itemid += 1\n row[1] = itemdict[ori_itemid]\n dst_write.writerow(row)\n i += 1\n print('Dst_save Ratings#%d Dst_Users#%d Dst_Items%d' %(i, len(userdict), len(itemdict)))\n\n# 按userid的大小重新排序\ndef sort_data(src_save, dst_save):\n df = pd.read_csv('src_temp2.csv', names = ['userid', 'itemid', 'ratings'])\n df.sort_values('userid').to_csv(src_save, index = False, header = False)\n df = pd.read_csv('dst_temp2.csv', names = ['userid', 'itemid', 'ratings'])\n df.sort_values('userid').to_csv(dst_save, index = False, header = False)\n\n\n\n\nif __name__ == '__main__':\n ori_datapath = '../../data/ori_data/'\n\n args = parse_args()\n src = ori_datapath + 'ratings_' + args.src + '.csv'\n dst = ori_datapath + 'ratings_' + args.dst + '.csv'\n\n src_save = args.savepath + '/' + args.src + '.csv'\n dst_save = args.savepath + '/' + args.dst + '.csv'\n\n\n draw_shareuser(src, dst)\n recode_userid_itemid()\n sort_data(src_save, dst_save)\n\n os.remove('src_temp1.csv')\n os.remove('dst_temp1.csv')\n os.remove('src_temp2.csv')\n os.remove('dst_temp2.csv')","sub_path":"utils/data_handling/datahandle.py","file_name":"datahandle.py","file_ext":"py","file_size_in_byte":4714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"402537865","text":"import json\nimport sys\nimport urllib2\n\nfrom twisted.python import log\n\nimport plugin\n\nURL_ACTIVITY = \"http://api.trakt.tv/activity/user.json/{0}/{1}/all/all/{2}\"\nURL_TIME = \"http://api.trakt.tv/server/time.json/{0}\"\n\nclass Trakt(plugin.Plugin):\n\n def __init__(self):\n log.msg(\"Trakt.__init__\")\n plugin.Plugin.__init__(self, \"Trakt\")\n\n self.settings = {}\n self.users = []\n self.ticks = 0\n\n def update_time(self, users):\n log.msg(\"Trakt.update_time\", users)\n url = URL_TIME.format(self.settings[\"key\"])\n response = urllib2.urlopen(url)\n data = json.load(response)\n for user in users:\n self.users[user][\"last_sync\"] = data[\"timestamp\"]\n\n def started(self, settings):\n log.msg(\"Trakt.started\", settings)\n self.settings = json.loads(settings)\n\n self.users = dict(map(lambda user: (user, {\"last_sync\": 0}), self.settings[\"users\"]))\n self.update_time(self.users)\n\n self.join(0, str(self.settings[\"channel\"]))\n\n def joined(self, server_id, channel):\n log.msg(\"Trakt.joined\", server_id, channel)\n\n def echo(self, message):\n log.msg(\"Trakt.echo\", message)\n self.say(0, str(self.settings[\"channel\"]), \"Trakt: \" + message.encode(\"utf-8\"))\n\n def update(self):\n self.ticks += 1\n if self.ticks % self.settings[\"interval\"] == 0:\n for user in self.users:\n try:\n url = URL_ACTIVITY.format(self.settings[\"key\"], user, self.users[user][\"last_sync\"])\n response = urllib2.urlopen(url)\n data = json.load(response)\n self.users[user][\"last_sync\"] = data[\"timestamps\"][\"current\"]\n for activity in data[\"activity\"]:\n message = Trakt.format_activity(activity, user)\n if message is not None:\n self.echo(message)\n except urllib2.HTTPError as e:\n log.msg(\"HTTP error when fetching\", url, e.code)\n except (urllib2.URLError, ) as e:\n log.msg(\"URL error when fetching\", url, e.args)\n except Exception as e:\n log.msg(\"Unhandled exception when fetching\", url)\n log.msg(\"Data:\", data, \"User:\", user)\n log.err()\n\n @staticmethod\n def format_activity(activity, user):\n if activity[\"type\"] == \"list\":\n if activity[\"action\"] == \"created\":\n return \"{0} create a list '{1}'\".format(user, activity[\"list\"][\"name\"])\n elif activity[\"action\"] == \"item_added\":\n return \"{0} added {1} to the list '{2}'\".format(user, Trakt.format_item(activity[\"list_item\"]), activity[\"list\"][\"name\"])\n else:\n message = user\n\n #if activity[\"action\"] == \"watching\":\n # message += \" is watching (\" + activity[\"elapsed\"][\"short\"] + \") \"\n if activity[\"action\"] == \"scrobble\":\n message += \" scrobbled \"\n elif activity[\"action\"] == \"checkin\":\n message += \" checked in \"\n elif activity[\"action\"] == \"rating\":\n message += \" rated (as \" + Trakt.format_rating(activity) + \") \"\n elif activity[\"action\"] == \"watchlist\":\n message += \" added to watchlist, \"\n else:\n # TODO: seen, collection, shout, review\n return\n\n return message + Trakt.format_item(activity)\n\n @staticmethod\n def format_item(item):\n if item[\"type\"] == \"movie\":\n return Trakt.format_movie(item[\"movie\"])\n elif item[\"type\"] == \"episode\":\n return Trakt.format_episode(item[\"show\"], item[\"episode\"])\n elif item[\"type\"] == \"show\":\n return Trakt.format_show(item[\"show\"])\n\n @staticmethod\n def format_movie(movie):\n return \"'{0[title]} ({0[year]})' {0[url]}\".format(movie)\n\n @staticmethod\n def format_show(show):\n return \"'{0[title]}' {0[url]}\".format(show)\n\n @staticmethod\n def format_episode(show, episode):\n return \"'{0[title]}' 'S{1[season]:02d}E{1[episode]:02d} {1[title]}' {1[url]}\".format(show, episode)\n\n @staticmethod\n def format_rating(activity):\n if activity[\"use_rating_advanced\"]:\n return str(activity[\"rating_advanced\"])\n else:\n return activity[\"rating\"]\n\nif __name__ == \"__main__\":\n sys.exit(Trakt.run())\n\n","sub_path":"plugins/trakt/trakt.py","file_name":"trakt.py","file_ext":"py","file_size_in_byte":4513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"576168236","text":"'''\nCreated on Oct 9, 2012\n\n@author: davidgrogan\n'''\nimport db\nimport datetime\nimport named_object\nimport sub_object\nimport unittest\n\nclass GenericNamedObject(named_object.NamedObject):\n '''\n A generic named object for testing purposes.\n '''\n\n class Factory(named_object.NamedObject.Factory):\n '''\n The factory for creating generic named objects.\n '''\n \n def __init__(self):\n super(GenericNamedObject.Factory, self).__init__(\"test_named_object\")\n \n def _new_instance(self, data):\n return GenericNamedObject(data, self)\n\n def __init__(self, data, factory):\n if not data:\n data = list([-1, \"\", 45.0, \"20010101\"])\n super(GenericNamedObject, self).__init__(data, factory)\n self.__sub_object_collection = None\n \n def get_float_value(self):\n return self._get_data()[2]\n \n def set_float_value(self, float_value):\n self._get_data()[2] = float_value\n \n def get_date_value(self):\n dt = self._get_data()[3]\n return datetime.date(int(dt[:4]), int(dt[4:6]), int(dt[6:8]))\n \n def set_date_value(self, date_value):\n self._get_data()[3] = date_value.strftime(\"%Y%m%d\")\n \n def get_sub_objects(self):\n if not self.__sub_object_collection:\n self.__sub_object_collection = SubObject.Collection(self)\n return self.__sub_object_collection\n\n def save(self):\n super(GenericNamedObject, self).save()\n self.get_sub_objects().save()\n \n def _prepare_for_removal(self):\n self.get_sub_objects()._remove_all()\n\nclass SubObject(sub_object.SubObject):\n '''\n A sub object for testing purposes.\n '''\n \n class Collection(sub_object.SubObject.Collection):\n '''\n The collection class for sub-objects.\n '''\n\n def __init__(self, parent):\n super(SubObject.Collection, self).__init__(parent, \"test_sub_object\")\n\n def _new_instance(self, data, parent):\n return SubObject(data, parent)\n \n\n def __init__(self, data, owner):\n if not data:\n data = list([-1, -1, \"\", 45.0, \"20010101\"])\n super(SubObject, self).__init__(data, owner)\n\n\ndef get_factory():\n '''\n Returns the factory for creating generic named objects.\n '''\n return GenericNamedObject.Factory()\n\n\nclass Test(unittest.TestCase):\n\n\n def setUp(self):\n db.reset_connection()\n db.set_database_type(\"postgres\")\n self.assertNotEqual(db.connect_default(), None)\n self.assertNotEqual(db.get_connection(), None)\n\n\n def tearDown(self):\n db.reset_connection()\n\n\n def testNamedObject(self):\n name = \"test_object\"\n float_value = 55.5\n date_value = datetime.date(2009, 12, 17)\n factory = get_factory()\n factory.remove(name)\n self.assertFalse(factory.is_valid_name(name))\n # Test create\n object_instance = factory.create()\n object_instance.set_name(name)\n object_instance.set_float_value(float_value)\n object_instance.set_date_value(date_value)\n object_instance.save()\n self.assertIsNotNone(object_instance)\n self.assertGreaterEqual(object_instance.get_id(), 0)\n self.assertEqual(object_instance.get_name(), name)\n self.assertEqual(object_instance.get_float_value(), float_value)\n self.assertEqual(object_instance.get_date_value(), date_value)\n self.assertTrue(factory.is_valid_name(name))\n self.assertTrue(factory.is_valid_id(object_instance.get_id()))\n # Test retrieve by id\n object_instance = factory.retrieve_by_id(object_instance.get_id())\n self.assertIsNotNone(object_instance)\n self.assertGreaterEqual(object_instance.get_id(), 0)\n self.assertEqual(object_instance.get_name(), name)\n self.assertEqual(object_instance.get_float_value(), float_value)\n self.assertEqual(object_instance.get_date_value(), date_value)\n # Test retrieve\n object_instance = factory.retrieve_by_name(name)\n self.assertIsNotNone(object_instance)\n self.assertGreaterEqual(object_instance.get_id(), 0)\n self.assertEqual(object_instance.get_name(), name)\n self.assertEqual(object_instance.get_float_value(), float_value)\n self.assertEqual(object_instance.get_date_value(), date_value)\n # Test retrieve_all\n all_object_instances = factory.retrieve_all()\n self.assertGreaterEqual(len(all_object_instances), 0)\n found = False\n for object_instance in all_object_instances:\n if object_instance.get_name() == name:\n found = True\n self.assertGreaterEqual(object_instance.get_id(), 0)\n self.assertEqual(object_instance.get_name(), name)\n self.assertTrue(found)\n # This should throw an exception because a object_instance with the specified name already exists.\n try:\n factory.create(name)\n self.fail(\"factory.create didn't throw an exception.\")\n except:\n pass\n factory.remove(name)\n self.assertFalse(factory.is_valid_name(name))\n self.assertFalse(factory.is_valid_id(object_instance.get_id()))\n # This should throw an exception because the object_instance no longer exists.\n try:\n factory.retrieve(name)\n self.fail(\"factory.retrieve didn't throw an exception.\")\n except:\n pass\n\n def testSubObject(self):\n name = \"test_object\"\n factory = get_factory()\n factory.remove(name)\n # Test create\n object_instance = factory.create()\n object_instance.set_name(name)\n sub_objects = object_instance.get_sub_objects()\n self.assertTrue(len(sub_objects) == 0)\n new_item = object_instance.get_sub_objects().add_item()\n new_item = object_instance.get_sub_objects().add_item()\n new_item = object_instance.get_sub_objects().add_item()\n \n object_instance.save()\n\nif __name__ == \"__main__\":\n #import sys;sys.argv = ['', 'Test.testName']\n unittest.main()\n","sub_path":"tests/test_named_object.py","file_name":"test_named_object.py","file_ext":"py","file_size_in_byte":6175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"169638277","text":"import numpy as np\n\n\nfrom sl1m.constants_and_tools import *\nfrom sl1m import planner_l1 as pl1\nfrom sl1m import planner as pl\n\nfrom . import qp\n\n\n# try to import mixed integer solver\nMIP_OK = False \ntry:\n import gurobipy\n import cvxpy as cp\n MIP_OK = True\n\nexcept ImportError:\n pass\n\n\n\nnp.set_printoptions(formatter={'float': lambda x: \"{0:0.1f}\".format(x)})\n\n\n\n### This solver is called when the sparsity is fixed. It assumes the first contact surface for each phase\n### is the one used for contact creation.\ndef solve(pb,surfaces, draw_scene = None, plot = True ): \n \n t1 = clock()\n A, b, E, e = pl.convertProblemToLp(pb) \n C = identity(A.shape[1])\n c = zeros(A.shape[1])\n t2 = clock()\n res = qp.quadprog_solve_qp(C, c,A,b,E,e)\n t3 = clock()\n \n print(\"time to set up problem\" , timMs(t1,t2))\n print(\"time to solve problem\" , timMs(t2,t3))\n print(\"total time\" , timMs(t1,t3))\n \n coms, footpos, allfeetpos = pl.retrieve_points_from_res(pb, res)\n \n plot = plot and draw_scene is not None \n if plot:\n ax = draw_scene(surfaces)\n pl.plotQPRes(pb, res, ax=ax)\n \n return pb, coms, footpos, allfeetpos, res\n\n\n### Calls the sl1m solver. Brute-forcedly tries to solve non fixed sparsity by handling the combinatorial.\n### Ultimately calls solve which provides the approriate cost function\ndef solveL1(pb, surfaces, draw_scene = None, plot = True): \n A, b, E, e = pl1.convertProblemToLp(pb) \n C = identity(A.shape[1]) * 0.00001\n c = pl1.slackSelectionMatrix(pb)\n \n res = qp.quadprog_solve_qp(C, c,A,b,E,e)\n \n ok = pl1.isSparsityFixed(pb, res)\n solutionIndices = None\n solutionComb = None\n if not ok:\n pbs = pl1.generateAllFixedScenariosWithFixedSparsity(pb, res)\n \n t3 = clock()\n \n for (pbComb, comb, indices) in pbs:\n A, b, E, e = pl1.convertProblemToLp(pbComb, convertSurfaces = False)\n C = identity(A.shape[1]) * 0.00001\n c = pl1.slackSelectionMatrix(pbComb)\n try:\n res = qp.quadprog_solve_qp(C, c,A,b,E,e)\n if pl1.isSparsityFixed(pbComb, res): \n coms, footpos, allfeetpos = pl1.retrieve_points_from_res(pbComb, res)\n pb = pbComb\n ok = True\n solutionIndices = indices[:]\n solutionComb = comb\n if plot:\n ax = draw_scene(surfaces)\n pl1.plotQPRes(pb, res, ax=ax)\n break\n except:\n print(\"unfeasible problem\")\n pass\n \n t4 = clock() \n \n print(\"time to solve combinatorial \", timMs(t3,t4))\n \n if ok:\n surfacesret, indices = pl1.bestSelectedSurfaces(pb, res) \n for i, phase in enumerate(pb[\"phaseData\"]): \n phase[\"S\"] = [surfaces[i][indices[i]]]\n if solutionIndices is not None:\n for i, idx in enumerate(solutionIndices):\n pb[\"phaseData\"][idx][\"S\"] = [surfaces[idx][solutionComb[i]]]\n \n return solve(pb,surfaces, draw_scene = draw_scene, plot = True ) \n\n\n############### MIXED-INTEGER SOLVER ###############\n\ndef tovals(variables):\n return array([el.value for el in variables])\n\ndef solveMIP(pb, surfaces, MIP = True, draw_scene = None, plot = True): \n if not MIP_OK:\n print(\"Mixed integer formulation requires gurobi packaged in cvxpy\")\n raise ImportError\n \n gurobipy.setParam('LogFile', '')\n gurobipy.setParam('OutputFlag', 0)\n \n A, b, E, e = pl1.convertProblemToLp(pb) \n slackMatrix = pl1.slackSelectionMatrix(pb)\n \n rdim = A.shape[1]\n varReal = cp.Variable(rdim)\n constraints = []\n constraintNormalIneq = A * varReal <= b\n constraintNormalEq = E * varReal == e\n \n constraints = [constraintNormalIneq, constraintNormalEq]\n #creating boolean vars\n \n slackIndices = [i for i,el in enumerate (slackMatrix) if el > 0]\n numSlackVariables = len([el for el in slackMatrix if el > 0])\n boolvars = cp.Variable(numSlackVariables, boolean=True) \n obj = cp.Minimize(slackMatrix * varReal)\n \n if MIP: \n constraints = constraints + [varReal[el] <= 100. * boolvars[i] for i, el in enumerate(slackIndices)] \n \n currentSum = []\n previousL = 0\n for i, el in enumerate(slackIndices):\n if i!= 0 and el - previousL > 2.:\n assert len(currentSum) > 0\n constraints = constraints + [sum(currentSum) == len(currentSum) -1 ]\n currentSum = [boolvars[i]]\n elif el !=0:\n currentSum = currentSum + [boolvars[i]]\n previousL = el\n if len(currentSum) > 1:\n constraints = constraints + [sum(currentSum) == len(currentSum) -1 ]\n obj = cp.Minimize(ones(numSlackVariables) * boolvars)\n prob = cp.Problem(obj, constraints)\n t1 = clock()\n res = prob.solve(solver=cp.GUROBI, verbose=False )\n t2 = clock()\n res = tovals(varReal)\n print(\"time to solve MIP \", timMs(t1,t2))\n\n \n plot = plot and draw_scene is not None \n if plot:\n ax = draw_scene(surfaces)\n pl1.plotQPRes(pb, res, ax=ax)\n \n return timMs(t1,t2)\n \n","sub_path":"sl1m/fix_sparsity.py","file_name":"fix_sparsity.py","file_ext":"py","file_size_in_byte":5372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"302974618","text":"#rdkit imports\nimport rdkit\nfrom rdkit import Chem\nfrom rdkit.Chem import Draw\nfrom rdkit.Chem.EState import Fingerprinter\nfrom rdkit.Chem import Descriptors\nfrom rdkit.Chem import rdFMCS\nfrom rdkit.Chem.rdmolops import RDKFingerprint\nfrom rdkit.Chem.Fingerprints import FingerprintMols\nfrom rdkit import DataStructs\nfrom rdkit.Avalon.pyAvalonTools import GetAvalonFP\n\n#housekeeping imports\nimport pandas as pd\nimport matplotlib\nimport numpy as np\nimport scipy as sp\n\n\ndef input_data(input_df): #cleans input df and returns neccessary elements\n '''From the input dataframe, removes rows that do not contain product\n SMILES strings. Returns the cleaned dataframe'''\n for index, row in input_df.iterrows():\n\n if row['SMILES'] == 'none':\n\n input_df.drop(index, inplace=True)\n\n return input_df\n\ndef fingerprint_products(input_df): #fingerprints all products in a given df\n '''From the input dataframe, makes a list of rdkit Mol objects and makes a\n list of rdkit fingerprints generated from those Mol objects. Inserts both\n lists as new columns and returns the expanded dataframe.'''\n mol_list = []\n fp_list = []\n\n for index, row in input_df.iterrows():\n mol_list.append(Chem.rdmolfiles.MolFromSmiles(row['SMILES'])) #get mols from SMILES and add mols to list\n fp_list.append(FingerprintMols.FingerprintMol(Chem.rdmolfiles.MolFromSmiles(row['SMILES']))) #get fingerprints from mols and and fingerprints to list\n\n input_df['Mol'] = mol_list\n input_df['Fingerprint'] = fp_list\n\n return input_df\n\n# def split_by_enzyme(input_df):\n# '''From the input dataframe, makes a set of unique enzmyes from the KEGG\n# entry column. For each unique enzyme, makes an enzyme dataframe and fills it\n# with all products in the input dataframe that are made by the unique enzyme.\n# After filling the enzyme dataframe, adds it to a list of enzyme dataframes.\n# Returns the list of unique enzyme dataframes.'''\n# unique_enzymes = set(input_df['entry'].unique())\n#\n# enzyme_df_list = []\n#\n# for entry in unique_enzymes: #for each unique enzyme in the input dataframe...\n#\n# enzyme_df = pd.DataFrame(columns=input_df.columns) #...initialize a new dataframe with the same columns as the input dataframe...\n#\n# for index, row in input_df.iterrows(): #...iterate through the input dataframe...\n#\n# if row['entry'] == entry: #... and add product rows that correspond to the unique enzyme entry...\n# enzyme_df.loc[index] = row\n#\n# enzyme_df_list.append(enzyme_df) #...then add the completed dataframe of unique enzyme products to a list\n#\n# return enzyme_df_list #return list of dataframes\n\ndef sim_i_j(row_i, row_j):\n \"\"\"For two given rows of a dataframe, use the rdkit fingerprints to compute\n TanimotoSimilarity and return the resulting float\"\"\"\n return DataStructs.FingerprintSimilarity(row_i['Fingerprint'], row_j['Fingerprint'], metric=DataStructs.TanimotoSimilarity)\n\ndef sim_i_all(input_df, index_i, row_i, metric):\n \"\"\"From the input dataframe, check the passed indexes against the DataFrame,\n and construct a new dataframe which is the similarity matrix of all of the\n products contained in the dataframe.\"\"\"\n for index_j, row_j in input_df.iterrows():\n if index_j < index_i: #skip redundant rows\n continue\n elif index_i == index_j: #autocorrelate rows\n metric.loc[index_i, index_j] = 1\n else:\n metric.loc[index_i, index_j] = sim_i_j(row_i, row_j) #fill matrix with calculated similarity at two positions at once\n metric.loc[index_j, index_i] = metric.loc[index_i, index_j]\n return\n\ndef sim_metric(input_df):\n \"\"\"From an input_df, use sim_i_j and sim_i_all to build and return a\n similarity matrix dataframe.\"\"\"\n metric = pd.DataFrame()\n for index_i, row_i in input_df.iterrows():\n sim_i_all(input_df, index_i, row_i, metric)\n return metric\n\ndef calculate_dist(input_df):\n '''Main method, takes an input dataframe and builds and returns a master\n dataframe which is the original dataframe, with three additional columns,\n an rdkit Mol column, an rdkit Fingerprint column, and a column which\n describes the average distance of a product row to all the products of the\n associated enzyme entry. Requires the KEGG enzyme entry column to be named 'entry'\n\tand the SMILES string column to be named 'SMILES' '''\n\n master_df = fingerprint_products(input_data(input_df)) #expand input df: generate mols from SMILES then generate fingerprints from mols, adding columns for each\n\n # enzyme_df_list = split_by_enzyme(input_df) #split expanded df by rows, grouped by enzyme entry (1.1.1.110 etc), into a list of dataframes\n unique_enzymes = set(master_df['entry'].unique()) # create set of unique enzymes\n\n dist_lookup = {} # initialize master dist list\n\n for enzyme in unique_enzymes: #loop through list of enzyme dataframes\n\n # enzyme_df['Dist'] = '' #initialize distance column\n enzyme_df = master_df[master_df['entry'] == enzyme]\n\n metric = sim_metric(enzyme_df) #get similarity matrix dataframe\n\n vals = metric.values #use np array of similarity matrix\n\n start_at = 1 #skip autocorrelation\n\n dist_list =[] #initialize list\n\n for i in range(len(vals)-1): #row of matrix except for last row\n\n for j in range(start_at, len(vals)): #col of matrix skipping first column\n\n dist_list.append(vals[i][j]) #add distance value to list\n\n start_at += 1 #start at higher index to skip redundancy\n\n avg_dist = sum(dist_list)/len(dist_list) #compute average distance\n dist_lookup[enzyme] = avg_dist\n # for _, row in enzyme_df.iterrows(): #loop through enzyme dataframe\n # # enzyme_df['Dist'].loc[index] = avg_dist #add averaged distance to each product row of enzyme dataframe\n\n master_df['dist'] = [dist_lookup[row['entry']] for _, row in master_df.iterrows()]\n\n return master_df\n","sub_path":"deprecated/code/mol_sim_copy.py","file_name":"mol_sim_copy.py","file_ext":"py","file_size_in_byte":6071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"502293104","text":"import gridfs\nimport json\nimport zlib\nimport io\nimport os\nimport traceback\nfrom shutil import which\nimport numpy as np\nfrom datetime import datetime\nfrom monty.tempfile import ScratchDir\nfrom maggma.builder import Builder\nimport prettyplotlib as ppl\nimport matplotlib\nimport scipy.interpolate as scint\nfrom prettyplotlib import brewer2mpl\nfrom pymatgen.core.structure import Structure\nfrom pymatgen.symmetry.bandstructure import HighSymmKpath\nfrom pymatgen.electronic_structure.core import Spin, Orbital\nfrom pymatgen.electronic_structure.bandstructure import BandStructureSymmLine, BandStructure\nfrom pymatgen.electronic_structure.dos import CompleteDos\nfrom pymatgen.electronic_structure.plotter import BSDOSPlotter, DosPlotter, BSPlotter\nfrom pymatgen.electronic_structure.boltztrap import BoltztrapRunner, BoltztrapAnalyzer\nfrom pymatgen.util.plotting import pretty_plot\n__author__ = \"Shyam Dwaraknath \"\n\nmatplotlib.use('agg')\n\nclass ElectronicStructureBuilder(Builder):\n\n def __init__(self, materials, electronic_structure, bandstructure_fs=\"bandstructure_fs\",\n dos_fs=\"dos_fs\", query=None, interpolate_dos=True, small_plot=True,\n static_images=True, **kwargs):\n \"\"\"\n Creates an electronic structure from a tasks collection, the associated band structures and density of states, and the materials structure\n\n :param tasks:\n :param materials:\n :param electronic_structure:\n \"\"\"\n\n self.materials = materials\n self.electronic_structure = electronic_structure\n self.query = query if query else {}\n self.bandstructure_fs = bandstructure_fs\n self.dos_fs = dos_fs\n self.interpolate_dos = interpolate_dos and bool(which(\"x_trans\"))\n self.small_plot = small_plot\n self.static_images = static_images\n\n super().__init__(sources=[materials],\n targets=[electronic_structure],\n **kwargs)\n\n def get_items(self):\n \"\"\"\n Gets all items to process into materials documents\n\n Returns:\n generator or list relevant tasks and materials to process into materials documents\n \"\"\"\n\n self.logger.info(\"Electronic Structure Builder Started\")\n\n # only consider materials that were updated since the electronic structure was last updated\n # and there is either a dos or bandstructure\n q = dict(self.query)\n q.update(self.materials.lu_filter(self.electronic_structure))\n q[\"$or\"] = [{\"bandstructure.bs_oid\": {\"$exists\": 1}},\n {\"bandstructure.dos_oid\": {\"$exists\": 1}}]\n\n # initialize the gridfs\n self.bfs = gridfs.GridFS(\n self.materials.collection.database, self.bandstructure_fs)\n self.dfs = gridfs.GridFS(\n self.materials.collection.database, self.dos_fs)\n\n mats = list(self.materials.distinct(self.materials.key, criteria=q))\n\n for m in mats:\n\n mat = self.materials.query([self.materials.key, \"structure\", \"bandstructure\", \"calc_settings\"],\n {self.materials.key: m}).limit(1)[0]\n self.get_bandstructure(mat)\n self.get_dos(mat)\n if self.interpolate_dos:\n self.get_uniform_bandstructure(mat)\n\n yield mat\n\n def process_item(self, mat):\n \"\"\"\n Process the tasks and materials into just a list of materials\n\n Args:\n mat (dict): material document\n\n Returns:\n (dict): electronic_structure document\n \"\"\"\n\n self.logger.info(\"Processing: {}\".format(mat[self.materials.key]))\n\n d = {self.electronic_structure.key: mat[\n self.materials.key], \"bandstructure\": {}}\n bs = None\n dos = None\n interpolated_dos = None\n\n # Process the bandstructure for information\n if \"bs\" in mat[\"bandstructure\"]:\n if \"structure\" not in mat[\"bandstructure\"][\"bs\"]:\n mat[\"bandstructure\"][\"bs\"][\"structure\"] = mat[\"structure\"]\n if len(mat[\"bandstructure\"][\"bs\"].get(\"labels_dict\", {})) == 0:\n struc = Structure.from_dict(mat[\"structure\"])\n kpath = HighSymmKpath(struc)._kpath[\"kpoints\"]\n mat[\"bandstructure\"][\"bs\"][\"labels_dict\"] = kpath\n # Somethign is wrong with the as_dict / from_dict encoding in the two band structure objects so have to use this hodge podge serialization\n # TODO: Fix bandstructure objects in pymatgen\n bs = BandStructureSymmLine.from_dict(\n BandStructure.from_dict(mat[\"bandstructure\"][\"bs\"]).as_dict())\n d[\"bandstructure\"][\"band_gap\"] = {\"band_gap\": bs.get_band_gap()[\"energy\"],\n \"direct_gap\": bs.get_direct_band_gap(),\n \"is_direct\": bs.get_band_gap()[\"direct\"],\n \"transition\": bs.get_band_gap()[\"transition\"]}\n\n if self.small_plot:\n d[\"bandstructure\"][\"plot_small\"] = get_small_plot(bs)\n\n if \"dos\" in mat[\"bandstructure\"]:\n dos = CompleteDos.from_dict(mat[\"bandstructure\"][\"dos\"])\n\n if self.interpolate_dos and \"uniform_bs\" in mat[\"bandstructure\"]:\n try:\n interpolated_dos = self.get_interpolated_dos(mat)\n except Exception:\n self.logger.warning(\"Boltztrap interpolation failed for {}. Continuing with regular DOS\".format(mat[self.materials.key]))\n\n # Generate static images\n if self.static_images:\n try:\n ylim = None\n if bs:\n plotter = WebBSPlotter(bs)\n fig = plotter.get_plot()\n ylim = fig.ylim() # Used by DOS plot\n fig.close()\n\n d[\"bandstructure\"][\"bs_plot\"] = image_from_plotter(plotter)\n\n if dos:\n plotter = WebDosVertPlotter()\n plotter.add_dos_dict(dos.get_element_dos())\n\n if interpolated_dos:\n plotter.add_dos(\"Total DOS\", interpolated_dos)\n d[\"bandstructure\"][\"dos_plot\"] = image_from_plotter(plotter, ylim=ylim)\n\n d[\"bandstructure\"][\"dos_plot\"] = image_from_plotter(plotter, ylim=ylim)\n\n except Exception:\n self.logger.warning(\n \"Caught error in electronic structure plotting for {}: {}\".format(mat[self.materials.key], traceback.format_exc()))\n return None\n\n return d\n\n def update_targets(self, items):\n \"\"\"\n Inserts the new task_types into the task_types collection\n\n Args:\n items ([([dict],[int])]): A list of tuples of materials to update and the corresponding processed task_ids\n \"\"\"\n items = list(filter(None, items))\n\n if len(items) > 0:\n self.logger.info(\"Updating {} band structures\".format(len(items)))\n self.electronic_structure.update(items)\n else:\n self.logger.info(\"No items to update\")\n\n def get_bandstructure(self, mat):\n\n # If a bandstructure oid exists\n if \"bs_oid\" in mat.get(\"bandstructure\", {}):\n bs_json = self.bfs.get(mat[\"bandstructure\"][\"bs_oid\"]).read()\n\n if \"zlib\" in mat[\"bandstructure\"].get(\"bs_compression\", \"\"):\n bs_json = zlib.decompress(bs_json)\n\n bs_dict = json.loads(bs_json.decode())\n mat[\"bandstructure\"][\"bs\"] = bs_dict\n\n def get_uniform_bandstructure(self, mat):\n\n # If a bandstructure oid exists\n if \"uniform_bs_oid\" in mat.get(\"bandstructure\", {}):\n bs_json = self.bfs.get(mat[\"bandstructure\"][\n \"uniform_bs_oid\"]).read()\n\n if \"zlib\" in mat[\"bandstructure\"].get(\"uniform_bs_compression\", \"\"):\n bs_json = zlib.decompress(bs_json)\n\n bs_dict = json.loads(bs_json.decode())\n mat[\"bandstructure\"][\"uniform_bs\"] = bs_dict\n\n def get_dos(self, mat):\n\n # if a dos oid exists\n if \"dos_oid\" in mat.get(\"bandstructure\", {}):\n dos_json = self.dfs.get(mat[\"bandstructure\"][\"dos_oid\"]).read()\n\n if \"zlib\" in mat[\"bandstructure\"].get(\"dos_compression\", \"\"):\n dos_json = zlib.decompress(dos_json)\n\n dos_dict = json.loads(dos_json.decode())\n mat[\"bandstructure\"][\"dos\"] = dos_dict\n\n def get_interpolated_dos(self, mat):\n\n nelect = mat[\"calc_settings\"][\"nelect\"]\n\n bs_dict = mat[\"bandstructure\"][\"uniform_bs\"]\n bs_dict[\"structure\"] = mat['structure']\n bs = BandStructure.from_dict(bs_dict)\n\n if bs.is_spin_polarized:\n with ScratchDir(\".\"):\n BoltztrapRunner(bs=bs,\n nelec=nelect,\n run_type=\"DOS\",\n dos_type=\"TETRA\",\n spin=1,\n timeout=60).run(path_dir=os.getcwd())\n an_up = BoltztrapAnalyzer.from_files(\"boltztrap/\", dos_spin=1)\n\n with ScratchDir(\".\"):\n BoltztrapRunner(bs=bs,\n nelec=nelect,\n run_type=\"DOS\",\n dos_type=\"TETRA\",\n spin=-1,\n timeout=60).run(path_dir=os.getcwd())\n an_dw = BoltztrapAnalyzer.from_files(\"boltztrap/\", dos_spin=-1)\n\n cdos = an_up.get_complete_dos(bs.structure, an_dw)\n\n else:\n with ScratchDir(\".\"):\n BoltztrapRunner(bs=bs,\n nelec=nelect,\n run_type=\"DOS\",\n dos_type=\"TETRA\",\n timeout=60).run(path_dir=os.getcwd())\n an = BoltztrapAnalyzer.from_files(\"boltztrap/\")\n cdos = an.get_complete_dos(bs.structure)\n\n return cdos\n\n\ndef image_from_plotter(plotter, ylim=None):\n plot = plotter.get_plot()\n imgdata = io.BytesIO()\n plot.savefig(imgdata, format=\"png\", dpi=100)\n plot_img = imgdata.getvalue()\n plot.close()\n return plot_img\n\n\ndef get_small_plot(bs):\n\n plot_small = BSPlotter(bs).bs_plot_data()\n\n gap = bs.get_band_gap()[\"energy\"]\n for branch in plot_small['energy']:\n for spin, v in branch.items():\n new_bands = []\n for band in v:\n if min(band) < gap + 3 and max(band) > -3:\n new_bands.append(band)\n branch[spin] = new_bands\n return plot_small\n\n\n#\n# Obtain web-friendly images by subclassing pymatgen plotters.\n#\n\nclass WebBSPlotter(BSPlotter):\n\n def get_plot(self, zero_to_efermi=True, ylim=None, smooth=False):\n \"\"\"\n get a matplotlib object for the bandstructure plot.\n Blue lines are up spin, red lines are down\n spin.\n Args:\n zero_to_efermi: Automatically subtract off the Fermi energy from\n the eigenvalues and plot (E-Ef).\n ylim: Specify the y-axis (energy) limits; by default None let\n the code choose. It is vbm-4 and cbm+4 if insulator\n efermi-10 and efermi+10 if metal\n smooth: interpolates the bands by a spline cubic\n \"\"\"\n\n plt = pretty_plot(6, 5.5) # Was 12, 8\n\n matplotlib.rc('text', usetex=True)\n\n width = 4\n ticksize = int(width * 2.5)\n axes = plt.gca()\n axes.set_title(axes.get_title(), size=width * 4)\n labelsize = int(width * 3)\n axes.set_xlabel(axes.get_xlabel(), size=labelsize)\n axes.set_ylabel(axes.get_ylabel(), size=labelsize)\n\n plt.xticks(fontsize=ticksize)\n plt.yticks(fontsize=ticksize)\n\n for axis in ['top', 'bottom', 'left', 'right']:\n axes.spines[axis].set_linewidth(0.5)\n\n # main internal config options\n e_min = -4\n e_max = 4\n if self._bs.is_metal():\n e_min = -10\n e_max = 10\n band_linewidth = 1 # Was 3 in pymatgen\n\n data = self.bs_plot_data(zero_to_efermi)\n if not smooth:\n for d in range(len(data['distances'])):\n for i in range(self._nb_bands):\n plt.plot(data['distances'][d],\n [data['energy'][d][str(Spin.up)][i][j]\n for j in range(len(data['distances'][d]))], 'b-',\n linewidth=band_linewidth)\n if self._bs.is_spin_polarized:\n plt.plot(data['distances'][d],\n [data['energy'][d][str(Spin.down)][i][j]\n for j in range(len(data['distances'][d]))],\n 'r--', linewidth=band_linewidth)\n else:\n for d in range(len(data['distances'])):\n for i in range(self._nb_bands):\n tck = scint.splrep(\n data['distances'][d],\n [data['energy'][d][str(Spin.up)][i][j]\n for j in range(len(data['distances'][d]))])\n step = (data['distances'][d][-1]\n - data['distances'][d][0]) / 1000\n\n plt.plot([x * step + data['distances'][d][0]\n for x in range(1000)],\n [scint.splev(x * step + data['distances'][d][0],\n tck, der=0)\n for x in range(1000)], 'b-',\n linewidth=band_linewidth)\n\n if self._bs.is_spin_polarized:\n\n tck = scint.splrep(\n data['distances'][d],\n [data['energy'][d][str(Spin.down)][i][j]\n for j in range(len(data['distances'][d]))])\n step = (data['distances'][d][-1]\n - data['distances'][d][0]) / 1000\n\n plt.plot([x * step + data['distances'][d][0]\n for x in range(1000)],\n [scint.splev(x * step + data['distances'][d][0],\n tck, der=0)\n for x in range(1000)], 'r--',\n linewidth=band_linewidth)\n self._maketicks(plt)\n\n # Main X and Y Labels\n plt.xlabel(r'$\\mathrm{Wave\\ Vector}$')\n ylabel = r'$\\mathrm{E\\ -\\ E_f\\ (eV)}$' if zero_to_efermi \\\n else r'$\\mathrm{Energy\\ (eV)}$'\n plt.ylabel(ylabel)\n\n # Draw Fermi energy, only if not the zero\n if not zero_to_efermi:\n ef = self._bs.efermi\n plt.axhline(ef, linewidth=2, color='k')\n\n # X range (K)\n # last distance point\n x_max = data['distances'][-1][-1]\n plt.xlim(0, x_max)\n\n if ylim is None:\n if self._bs.is_metal():\n # Plot A Metal\n if zero_to_efermi:\n plt.ylim(e_min, e_max)\n else:\n plt.ylim(self._bs.efermi + e_min, self._bs._efermi + e_max)\n else:\n for cbm in data['cbm']:\n plt.scatter(cbm[0], cbm[1], color='r', marker='o', s=100)\n\n for vbm in data['vbm']:\n plt.scatter(vbm[0], vbm[1], color='g', marker='o', s=100)\n plt.ylim(data['vbm'][0][1] + e_min, data['cbm'][0][1] + e_max)\n else:\n plt.ylim(ylim)\n\n plt.tight_layout()\n\n return plt\n\n\nclass WebDosVertPlotter(DosPlotter):\n\n def get_plot(self, xlim=None, ylim=None,\n plt=None, handle_only=False):\n \"\"\"\n Get a matplotlib plot showing the DOS.\n Args:\n xlim: Specifies the x-axis limits. Set to None for automatic\n determination.\n ylim: Specifies the y-axis limits.\n plt: Handle on existing plot.\n handle_only: Quickly return just a handle. Useful if this method\n raises an exception so that one can close() the figure.\n \"\"\"\n\n plt = plt or pretty_plot(2, 5.5)\n if handle_only:\n return plt\n\n ncolors = max(3, len(self._doses))\n ncolors = min(9, ncolors)\n colors = brewer2mpl.get_map('Set1', 'qualitative', ncolors).mpl_colors\n\n y = None\n alldensities = []\n allenergies = []\n\n width = 4\n ticksize = int(width * 2.5)\n axes = plt.gca()\n axes.set_title(axes.get_title(), size=width * 4)\n labelsize = int(width * 3)\n axes.set_xlabel(axes.get_xlabel(), size=labelsize)\n axes.set_ylabel(axes.get_ylabel(), size=labelsize)\n axes.xaxis.labelpad = 6\n\n # Note that this complicated processing of energies is to allow for\n # stacked plots in matplotlib.\n for key, dos in self._doses.items():\n energies = dos['energies']\n densities = dos['densities']\n if not y:\n y = {Spin.up: np.zeros(energies.shape),\n Spin.down: np.zeros(energies.shape)}\n newdens = {}\n for spin in [Spin.up, Spin.down]:\n if spin in densities:\n if self.stack:\n y[spin] += densities[spin]\n newdens[spin] = y[spin].copy()\n else:\n newdens[spin] = densities[spin]\n allenergies.append(energies)\n alldensities.append(newdens)\n\n keys = list(self._doses.keys())\n keys.reverse()\n alldensities.reverse()\n allenergies.reverse()\n allpts = []\n for i, key in enumerate(keys):\n x = []\n y = []\n for spin in [Spin.up, Spin.down]:\n if spin in alldensities[i]:\n densities = list(int(spin) * alldensities[i][spin])\n energies = list(allenergies[i])\n if spin == Spin.down:\n energies.reverse()\n densities.reverse()\n y.extend(energies)\n x.extend(densities)\n allpts.extend(list(zip(x, y)))\n if self.stack:\n plt.fill(x, y, color=colors[i % ncolors],\n label=str(key))\n else:\n ppl.plot(x, y, color=colors[i % ncolors],\n label=str(key), linewidth=1)\n if not self.zero_at_efermi:\n xlim = plt.xlim()\n ppl.plot(xlim, [self._doses[key]['efermi'],\n self._doses[key]['efermi']],\n color=colors[i % ncolors],\n linestyle='--', linewidth=1)\n\n if ylim:\n plt.ylim(ylim)\n if xlim:\n plt.xlim(xlim)\n else:\n ylim = plt.ylim()\n relevantx = [p[0] for p in allpts\n if ylim[0] < p[1] < ylim[1]]\n plt.xlim(min(relevantx), max(relevantx))\n if self.zero_at_efermi:\n xlim = plt.xlim()\n plt.plot(xlim, [0, 0], 'k--', linewidth=1)\n\n plt.ylabel(r'$\\mathrm{E\\ -\\ E_f\\ (eV)}$')\n plt.xlabel(r'$\\mathrm{Density\\ of\\ states}$')\n\n locs, _ = plt.xticks()\n plt.xticks([0], fontsize=ticksize)\n plt.yticks(fontsize=ticksize)\n plt.grid(which='major', axis='y')\n\n plt.legend(fontsize='x-small',\n loc='upper right', bbox_to_anchor=(1.15, 1))\n leg = plt.gca().get_legend()\n leg.get_frame().set_alpha(0.25)\n plt.tight_layout()\n return plt\n","sub_path":"emmet/vasp/builders/electronic_structure.py","file_name":"electronic_structure.py","file_ext":"py","file_size_in_byte":19983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"246859062","text":"import rospy\nimport json\n\nfrom planner_msgs.msg import PlanRequest, Plan, AgentTasksRequest, Task\n\nfrom .hatpehda import Goal\n\nclass RosNode:\n def __init__(self, name, on_new_request_cb):\n self.name = name\n self.user_callback = on_new_request_cb\n rospy.init_node(name)\n self.request_sub = rospy.Subscriber(\"~request_new_plan\", PlanRequest, self.on_new_request)\n self.plan_pub = rospy.Publisher(\"~plan_answer\", Plan, queue_size=10)\n @staticmethod\n def start_ros_node(node_name=\"planner\", on_new_request=None):\n return RosNode(node_name, on_new_request)\n\n def retrieve_agents_task(self, agents_task_msg, agents_task):\n for ag in agents_task_msg:\n agents_task[ag.agent_name] = []\n for task in ag.tasks:\n arguments = []\n for ar in task.parameters:\n try:\n print(\"goal\", ar)\n j = json.loads(ar)\n print(j)\n goal = Goal(\"goal\")\n for p, indivs in j.items():\n if not hasattr(goal, p):\n goal.__setattr__(p, {})\n for s, objs in indivs.items():\n goal.__getattribute__(p)[s] = objs\n arguments.append(goal)\n except json.JSONDecodeError as e:\n print(e)\n arguments.append(ar) # We assume that if it is not JSON, it is a simple string\n agents_task[ag.agent_name].append((task.name, arguments))\n\n def on_new_request(self, msg: PlanRequest):\n ctrl_agents_task = {}\n unctrl_agents_task = {}\n self.retrieve_agents_task(msg.controllable_agent_tasks, ctrl_agents_task)\n self.retrieve_agents_task(msg.uncontrollable_agent_tasks, unctrl_agents_task)\n\n if self.user_callback is not None:\n self.user_callback(ctrl_agents_task, unctrl_agents_task)\n\n def wait_for_request(self):\n rospy.spin()\n\n def create_primitive_task(self, action):\n print(action)\n task = Task()\n task.id = action.id\n task.type = task.PRIMITIVE_TASK\n task.name = action.name\n task.parameters = [*action.parameters]\n task.agent = action.agent\n task.successors = []\n if action.why is None:\n task.decomposition_of = -1\n return task\n\n def send_plan(self, actions, ctrlable_name, unctrlable_name):\n existing_edges = set()\n existing_tasks = {}\n msg = Plan()\n msg.tasks = []\n for action in actions:\n while action is not None:\n if action.id not in existing_tasks:\n task = self.create_primitive_task(action)\n # print(task)\n msg.tasks.append(task)\n existing_tasks[action.id] = task\n task = existing_tasks[action.id]\n if action.previous is not None and action.previous.id not in task.predecessors:\n task.predecessors.append(action.previous.id)\n if action.next is not None:\n for n in action.next:\n if n.id not in task.successors:\n task.successors.append(n.id)\n why = action.why\n how = action\n while why is not None:\n if (why.id, how.id) not in existing_edges:\n if why.id not in existing_tasks:\n print(\"adding\", why.id, how.id)\n task = Task()\n task.id = why.id\n task.type = task.ABSTRACT_TASK\n task.name = why.name\n task.parameters = []\n for param in why.parameters:\n #print(\"Parameter\", param)\n if isinstance(param, Goal):\n task.parameters.append(\"goal_{}\".format(param.__name__))\n else:\n task.parameters.append(param)\n #print(task.parameters)\n task.agent = why.agent\n if why.why is None:\n task.decomposition_of = -1\n task.successors = []\n existing_tasks[why.id] = task\n msg.tasks.append(task)\n why_task = existing_tasks[why.id]\n how_task = existing_tasks[how.id] # this one should exist\n why_task.decomposed_into.append(how.id)\n how_task.decomposition_of = why.id\n how_task.decomposition_number = how.decompo_number\n existing_edges.add((why.id, how.id))\n how = why\n why = why.why\n action = action.previous\n self.plan_pub.publish(msg)\n","sub_path":"hatpehda/ros.py","file_name":"ros.py","file_ext":"py","file_size_in_byte":5176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"379221601","text":"from collections import OrderedDict\nfrom pathlib import Path\nfrom typing import Union\nfrom io import IOBase\n\n\nDEFAULT_WPA_SUPPLICANT_FILEPATH = Path('/etc/wpa_supplicant/wpa_supplicant.conf')\n\n\nclass ParseError(ValueError):\n pass\n\n\nclass WpaSupplicantConf:\n \"\"\"This class parses a wpa_supplicant configuration file, allows\n manipulation of the configured networks and then writing out of\n the updated file.\n\n WARNING: Although care has been taken to preserve ordering,\n comments will be lost for any wpa_supplicant.conf which is\n round-tripped through this class.\n \"\"\"\n\n def __init__(self, lines=None, filepath=None):\n self._fields = OrderedDict()\n self._networks = OrderedDict()\n self._comments = list()\n if filepath is not None:\n self.filepath = Path(filepath)\n else:\n self.filepath = None\n self._lines = lines\n self.reload()\n\n def reload(self):\n self._fields = OrderedDict()\n self._networks = OrderedDict()\n self._comments = list()\n\n if self.filepath is not None:\n with open(self.filepath, 'r') as rfid:\n self._lines = rfid.readlines()\n\n network = None\n for linenumber, line in enumerate(self._lines):\n line = line.strip()\n if not line or line.startswith('#'):\n self._comments.append((linenumber, line))\n continue\n\n if line == \"}\":\n if network is None:\n raise ParseError(\"unxpected '}'\")\n\n ssid = network.pop('ssid', None)\n if ssid is None:\n raise ParseError('missing \"ssid\" for network')\n self._networks[dequote(ssid)] = network\n network = None\n continue\n\n parts = [x.strip() for x in line.split('=', 1)]\n if len(parts) != 2:\n raise ParseError(\"invalid line: %{!r}\".format(line))\n\n left, right = parts\n\n if right == '{':\n if left != 'network':\n raise ParseError('unsupported section: \"{}\"'.format(left))\n if network is not None:\n raise ParseError(\"can't nest networks\")\n\n network = OrderedDict()\n else:\n if network is None:\n self._fields[left] = right\n else:\n network[left] = right\n\n def fields(self):\n return self._fields\n\n def networks(self):\n return self._networks\n\n def add_network(self, ssid, **attrs):\n self._networks[ssid] = attrs\n\n def remove_network(self, ssid):\n self._networks.pop(ssid, None)\n\n def write(self, fid: Union[IOBase, Path, str] = None):\n print(f'fid={fid}')\n if fid is None and self.filepath is not None:\n fid = open(self.filepath, 'w+')\n elif fid is None:\n raise TypeError(f'write() missing 1 required positional argument: fid')\n elif isinstance(fid, str):\n fid = open(Path(fid), 'w+')\n\n for name, value in self._fields.items():\n fid.write(\"{}={}\\n\".format(name, value))\n\n for ssid, info in self._networks.items():\n fid.write(\"\\nnetwork={\\n\")\n fid.write(' ssid=\"{}\"\\n'.format(ssid))\n for name, value in info.items():\n fid.write(\" {}={}\\n\".format(name, value))\n fid.write(\"}\\n\")\n\n try:\n fid.close()\n except Exception as e:\n print(f'Couldnt close the output file {fid}: {e}')\n pass\n\n @classmethod\n def default(cls):\n return WpaSupplicantConf(filepath=DEFAULT_WPA_SUPPLICANT_FILEPATH)\n\n @classmethod\n def from_file(cls, rfilepath: Path):\n return WpaSupplicantConf(filepath=rfilepath)\n\n @classmethod\n def from_lines(cls, lines):\n return WpaSupplicantConf(lines=lines)\n\n\ndef dequote(v):\n if len(v) < 2:\n return v\n if v.startswith('\"') and v.endswith('\"'):\n return v[1:-1]\n return v\n","sub_path":"wpasupplicantconf.py","file_name":"wpasupplicantconf.py","file_ext":"py","file_size_in_byte":4094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"235442369","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport gluonnlp as nlp\nfrom model.modules import Encoder, Decoder, Attention\nimport random\n\nclass Seq2Seq(nn.Module):\n \"\"\" model class for seq2seq with attention \"\"\"\n def __init__(self, vocab_src:nlp.Vocab, vocab_tgt:nlp.Vocab, embedding_dim:int, hidden_dim:int, dev,\n num_layers:int=1, bos_idx=2, eos_idx=3, use_attention=True):\n \"\"\" initialization of the class \"\"\"\n super(Seq2Seq, self).__init__()\n\n self._encoder = Encoder(vocab_src, embedding_dim, hidden_dim)\n self._decoder = Decoder(vocab_tgt, embedding_dim, hidden_dim)\n\n self._dev = dev\n self._hidden_dim = hidden_dim\n self._bos_idx = bos_idx\n self._eos_idx = eos_idx\n self._pad_idx = self._encoder.pad_idx\n self._mask = None\n\n # global attention related\n self._use_attention = use_attention\n self._attn = Attention(self._hidden_dim) if self._use_attention else None\n\n # teacher forcing related\n self._use_teacher_forcing = None\n self._teacher_forcing_ratio = None\n\n def forward(self, inputs, use_teacher_forcing=True, teacher_forcing_ratio=0.5):\n src, tgt_in, tgt_out = inputs\n batch_size = src.size()[0]\n max_len = tgt_in.size()[1]\n mask = (tgt_out != self._pad_idx)\n\n # teacher forcing\n self._use_teacher_forcing = use_teacher_forcing\n self._teacher_forcing_ratio = teacher_forcing_ratio\n\n encoder_output, encoder_hidden = self._encoder(src) # encoder_out : (batch, max_len, hidden_dim * 2) (BiLSTM)\n decoder_input = torch.full((batch_size, 1), self._bos_idx).long().to(self._dev) # float32 -> int64\n decoder_hidden = encoder_hidden # initialize decoder's hidden state with encoder's last hidden state\n\n loss = 0\n nTotals = 0\n for di in range(max_len):\n if self._use_attention:\n decoder_hidden_top = decoder_hidden[0][0].unsqueeze(1) # top layer's hidden state (batch_size, 1, hidden)\n context_vector = self._attn(decoder_input, decoder_hidden_top, encoder_output)[0] # (batch, 1, hidden)\n decoder_output, next_decoder_hidden = self._decoder(decoder_input, decoder_hidden, context_vector)\n else:\n decoder_output, next_decoder_hidden = self._decoder(decoder_input, decoder_hidden)\n\n decoded_label = decoder_output.topk(1)[1]\n\n # calculate and accumulate loss\n mask_loss, nTotal = self.maskNLLLoss(decoder_output, tgt_out[:,di], mask[:,di], self._dev)\n loss += mask_loss\n nTotals += nTotal\n\n # Teacher forcing: Feed the target as the next input\n if self._use_teacher_forcing:\n if random.random() < self._teacher_forcing_ratio:\n decoder_input = tgt_out[:,di].unsqueeze(-1)\n else:\n decoder_input = decoded_label.squeeze(2)\n else:\n decoder_input = decoded_label.squeeze(2)\n decoder_hidden = next_decoder_hidden\n\n return loss/max_len, nTotals\n\n def maskNLLLoss(self, decoder_output, target, mask, dev):\n \"\"\"\n Calculate average Negative Log Likelihood Loss for mini batch in one time step\n Args:\n decoder_output: (batch, 1, tgt_vocab_size)\n target: (batch, )\n mask: (batch, )\n dev: current device (cpu or gpu)\n return:\n loss:\n\n \"\"\"\n mask = mask.unsqueeze(-1)\n nTotal = mask.sum()\n crossEntropy = -torch.log(torch.gather(decoder_output.squeeze(1), 1, target.unsqueeze(-1)).squeeze(1))\n loss = crossEntropy.masked_select(mask).mean()\n loss = loss.to(dev)\n return loss, nTotal.item()\n\n def to(self, dev):\n super(Seq2Seq, self).to(dev)\n self._dev = dev\n return\n","sub_path":"wk9_NMT/model/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":3938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"74688760","text":"\"\"\"Tests challengeutils.cheat-detection functions\"\"\"\n# pylint: disable=line-too-long\nfrom unittest import mock\n\nimport synapseclient\n\nfrom challengeutils import cheat_detection\n\n\nclass TestCheatDetection:\n def setup(self):\n \"\"\"Setup test\"\"\"\n\n self.syn = mock.create_autospec(synapseclient.Synapse)\n\n self.evaluation_id = \"123456\"\n\n self.cheat_detection_obj = cheat_detection.CheatDetection(\n syn=self.syn,\n evaluation_id=self.evaluation_id,\n submission_status=[\"ACCEPTED\"],\n )\n\n def test_string_representation(self):\n \"Tests string representation of Cheat Detection\"\n assert (\n str(self.cheat_detection_obj)\n == \"\"\"\nEvaluation ID: 123456\nAccepted Submissions: 0\nPotentially Linked Users: 0\n \"\"\"\n )\n\n def test_evaluation_id(self):\n \"Test that the evaluation id is valid\"\n assert self.cheat_detection_obj.evaluation == \"123456\"\n\n def test_representation(self):\n \"Tests the representation of the CheatDetection Object\"\n assert (\n repr(self.cheat_detection_obj)\n == f\"CheatDetection({self.cheat_detection_obj.syn}, 123456)\"\n )\n\n def test_get_number_of_linked_users(self):\n \"Tests that the number of linked users is correct\"\n num = len(self.cheat_detection_obj.linked_users)\n assert self.cheat_detection_obj.get_number_of_linked_users() == num\n","sub_path":"tests/test_cheatdetection.py","file_name":"test_cheatdetection.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"372560445","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# rst2db.py\n# =========\n#\n# A reStructuredText to DocBook conversion tool, using Python's docutils\n# library.\n#\n# by Eron Hennessey\n\nfrom argparse import ArgumentParser\nfrom argparse import RawDescriptionHelpFormatter\nimport os\nimport sys\n\nfrom abstrys.docutils_ext.docbook_writer import DocBookWriter\nfrom docutils.core import publish_string\n\n\nDESCRIPTION = 'rst2db - convert reStructuredText to DocBook'\n\n\ndef printerr(error_text):\n \"\"\"Prints an error message to stderr.\"\"\"\n sys.stderr.write(\"ERROR -- %s\\n\" % error_text)\n\n\ndef process_cmd_args():\n \"\"\"Parse command-line options.\"\"\"\n parser = ArgumentParser(description=DESCRIPTION,\n formatter_class=RawDescriptionHelpFormatter)\n parser.add_argument('input_filename', metavar='INPUT',\n help='Path to input ReST file.')\n parser.add_argument('-o', '--output',\n dest='output_filename', metavar='OUTPUT',\n help='Path to output DocBook file.')\n parser.add_argument('-t', '--template',\n dest='template_filename', metavar='TEMPLATE',\n help='Path to template DocBook file.')\n parser.add_argument('-e', '--element', dest='root_element',\n default='section', metavar='ROOT',\n help='Root element of the resulting DocBook file.')\n parser.add_argument('-l', '--lang', dest='lang',\n help='Language code of the resulting DocBook file.')\n return parser.parse_args()\n\n\ndef run():\n \"\"\"The main procedure.\"\"\"\n program_name = os.path.basename(sys.argv[0])\n try:\n params = process_cmd_args()\n if not os.path.exists(params.input_filename):\n printerr(\"File doesn't exist: %s\" % params.input_filename)\n sys.exit(1)\n # get the file contents first\n input_file_contents = open(params.input_filename, 'rb').read()\n docutils_writer = None\n # set up the writer\n if params.output_filename is not None:\n # If there's an output filename, use its basename as the root\n # element's ID.\n (_, filename) = os.path.split(params.output_filename)\n (doc_id, _) = os.path.splitext(filename)\n docutils_writer = DocBookWriter(params.root_element,\n doc_id,\n lang=params.lang)\n else:\n docutils_writer = DocBookWriter(params.root_element,\n lang=params.lang)\n # get the docbook output.\n overrides = {'input_encoding': 'utf-8',\n 'output_encoding': 'utf-8'}\n docbook_contents = publish_string(input_file_contents,\n writer=docutils_writer,\n settings_overrides=overrides)\n # if there's an output file, write to that. Otherwise, write to stdout.\n if params.output_filename is None:\n output_file = sys.stdout\n else:\n output_file = open(params.output_filename, 'w+')\n \n output_file.write(docbook_contents)\n # that's it, we're done here!\n return 0\n except KeyboardInterrupt:\n ### handle keyboard interrupt ###\n return 0\n except Exception as e:\n indent = len(program_name) * ' '\n sys.stderr.write(program_name + ': ' + repr(e) + '\\n')\n sys.stderr.write(indent + ' for help use --help\\n')\n return 1\n\n\nif __name__ == \"__main__\":\n sys.exit(run())\n","sub_path":"abstrys/cmd_rst2db.py","file_name":"cmd_rst2db.py","file_ext":"py","file_size_in_byte":3650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"9970931","text":"import asyncio\nfrom utilities import utilities\nfrom Db.dev_sql import addDevUser, getDevsUsers, getDevUser, remDevUser\nfrom telethon import utils, errors\nimport re\n\n\nasync def addDev_user(message, from_id):\n try:\n if getDevUser(from_id):\n return await message.reply(\"User already added as Dev.\")\n addDevUser(from_id)\n utilities.devs.append(from_id)\n return await message.reply(\"❏︙تم رفع مطور\")\n except Exception as e:\n utilities.prRed(str(type(e)) + \" Error : \" + str(e))\n return await message.reply(str(e))\n\n\nasync def remDev_user(message, from_id):\n try:\n if not getDevUser(from_id):\n return await message.reply(\"User already not dev.\")\n remDevUser(from_id)\n utilities.devs.remove(from_id)\n return await message.reply(\"❏︙تم تنزيل مطور\")\n except Exception as e:\n utilities.prRed(str(type(e)) + \" Error : \" + str(e))\n return await message.reply(str(e))\n\n\nasync def run(message, matches, chat_id, step, crons=None):\n\n response = []\n if message.sender_id not in utilities.config[\"sudo_members\"]:\n return []\n if matches == \"المطورين\":\n devlist = getDevsUsers()\n res = \"\"\n i = 1\n for user in devlist:\n userId = int(\"%.0f\" % user.user_id)\n try:\n _user = await utilities.client.get_entity(userId)\n strin = (\n str(i)\n + \" - [%s](tg://user?id=%s)\"\n % (_user.first_name, int(\"%.0f\" % userId))\n + \"\\n\"\n )\n except Exception as e:\n strin = (\n str(i)\n + \" - [%s](tg://user?id=%s)\"\n % ((\"dev\" + str(i)), int(\"%.0f\" % userId))\n + \"\\n\"\n )\n i += 1\n res = res + strin\n return [message.reply(res if (len(res) != 0) else \"❏︙لا يوجد مطورين\")]\n if matches[0] == \"رفع مطور\":\n if re.match(r\"@[a-zA-Z][\\w\\d]{3,30}[a-zA-Z\\d]\", matches[1]):\n user = await utilities.client.get_entity(matches[1])\n return [addDev_user(message, user.id)]\n elif re.match(r\"(\\d)\", matches[1]):\n return [addDev_user(message, matches[1])]\n else:\n return [message.reply(\"please, use by reply or use valid username and id\")]\n elif matches[0] == \"rdev\":\n if re.match(r\"@[a-zA-Z][\\w\\d]{3,30}[a-zA-Z\\d]\", matches[1]):\n user = await utilities.client.get_entity(matches[1])\n name = user.first_name\n return [remDev_user(message, user.id)]\n elif re.match(r\"(\\d)\", matches[1]):\n return [remDev_user(message, matches[1])]\n else:\n return [message.reply(\"please, use by reply or use valid username and id\")]\n elif matches == \"رفع مطور\":\n if message.is_reply:\n msg = await message.get_reply_message()\n fromId = msg.from_id\n chat_id = msg.chat_id\n name = (await msg.get_sender()).first_name\n return [addDev_user(message, fromId)]\n\n elif matches == \"rdev\":\n if message.is_reply:\n msg = await message.get_reply_message()\n fromId = msg.from_id\n chat_id = msg.chat_id\n return [remDev_user(message, fromId)]\n elif matches == \"مسح المطورين\":\n devlist = getDevsUsers()\n for user in devlist:\n remDevUser(user.user_id)\n utilities.devs.remove(user.user_id)\n return [message.reply(\"❏︙تم تنزيل جميع المطورين\")]\n return response\n\n\nplugin = {\n \"name\": \"\",\n \"desc\": \"Make someone dev\",\n \"usage\": [\n \"/مسح المطورين\",\n \"/المطورين\",\n \"/تنزيل مطور + برد\",\n \"/رفع مطور + برد\",\n ],\n \"run\": run,\n \"sudo\": True,\n \"patterns\": [\n \"^[!/#](مسح المطورين)$\",\n \"^[!/#](المطورين)\",\n \"^[!/#](dev)$\",\n \"^[!/#](تنزيل مطور)$\",\n \"^[!/#](رفع مطور) (.+)$\",\n \"^[!/#](rdev) (.+)$\",\n ],\n}\n","sub_path":"devAdded.py","file_name":"devAdded.py","file_ext":"py","file_size_in_byte":4218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"386365577","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.utils.decorators import method_decorator\nimport requests\n\ndef home(request):\n return render(request, 'home.html', {})\n\ndef submit_url(request):\n if(request.POST):\n login_data = request.POST.dict()\n post_url = login_data.get(\"url\")\n crawler_url = 'http://flask-image-crawler:5000/crawl'\n data = {'url':post_url}\n response=requests.post(crawler_url, data)\n response_status = response.content\n status_code=response.status_code\n return render(request, \"done.html\",{'post_url':post_url, 'response_status':response_status, 'status_code':status_code})\n else:\n return render(request, \"crawl.html\")\n","sub_path":"django-frontend/src/my_crawler/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"375616141","text":"import os\nimport torch\nimport numpy as np\nimport torch.nn as nn\nfrom torchvision import transforms\nimport datetime\nimport sys\nfrom pycrayon import CrayonClient\nfrom torch.utils.data import DataLoader\n\nimport network\nimport utils\nfrom model import MultiColumnNet\nfrom data_loader import DownSampleGT, ToTensor, CnrParkExtDataset\nimport evaluate_model\n\n# General parameters\nROOT_DIR = os.getcwd()\nTRAIN_DATASET_DIR = os.path.join(ROOT_DIR, \"../datasets/cnr_park_ext/train/patches\")\nTRAIN_DENSITY_MAPS_DIR = os.path.join(TRAIN_DATASET_DIR, \"density_maps\")\nVAL_DATASET_DIR = os.path.join(ROOT_DIR, \"../datasets/cnr_park_ext/val/patches\")\nVAL_DENSITY_MAPS_DIR = os.path.join(VAL_DATASET_DIR, \"density_maps\")\nIS_CUDA = True\nOUTPUT_DIR = os.path.join(ROOT_DIR, \"../output_images\")\nTIMESTAMP = datetime.datetime.now().strftime(\"%y%m%d%H%M\")\nSAVED_MODELS_DIR = os.path.join(ROOT_DIR, \"../saved_models\", TIMESTAMP)\n\n# Training parameters\nLEARNING_RATE = 0.0001\nMOMENTUM = 0.9\nSTART_STEP = 0\nEND_STEP = 2000\ncriterion = nn.MSELoss()\nLOSS = nn.MSELoss()\nTRAIN_BATCH_SIZE = 1\nDOWN_SAMPLE_FACTOR = 4\nSHUFFLE = True\nSAVE_INTERVAL = 1\n\n# Tensorboard\ncc = CrayonClient(hostname='127.0.0.1')\nexp_name = \"exp_{}\".format(TIMESTAMP)\n# cc.remove_all_experiments()\nexp = cc.create_experiment(exp_name)\n\n# Loading train and validation dataset\ntrain_dataset = CnrParkExtDataset(TRAIN_DATASET_DIR, TRAIN_DENSITY_MAPS_DIR, transform=transforms.Compose([\n DownSampleGT(DOWN_SAMPLE_FACTOR),\n ToTensor(is_cuda=IS_CUDA)\n ]))\nval_dataset = CnrParkExtDataset(VAL_DATASET_DIR, VAL_DENSITY_MAPS_DIR, transform=transforms.Compose([\n DownSampleGT(DOWN_SAMPLE_FACTOR),\n ToTensor(is_training=False, is_cuda=IS_CUDA)\n ]))\n# Creating PyTorch data loader\n#dataloader = DataLoader(train_dataset, batch_size=TRAIN_BATCH_SIZE, shuffle=SHUFFLE)\n\n# Loading network\nnet = MultiColumnNet()\n# network.weightsInit(net)\nif IS_CUDA:\n net.cuda()\nnet.train()\n\nparameters = list(net.parameters())\noptimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, net.parameters()), lr=LEARNING_RATE)\n\n# Training\nutils.log_print(\"Start training\", color='red', attrs=['bold'])\nbest_mae, best_mse = sys.maxsize, sys.maxsize\n\nfor epoch in range(START_STEP, END_STEP + 1):\n train_loss = 0\n if epoch == 0:\n os.mkdir(os.path.join(OUTPUT_DIR, TIMESTAMP))\n os.mkdir(SAVED_MODELS_DIR)\n if epoch % SAVE_INTERVAL == 0:\n output_dir = os.path.join(OUTPUT_DIR, TIMESTAMP, \"epoch{}\".format(epoch))\n os.mkdir(output_dir)\n\n for i in range(len(train_dataset)):\n sample = train_dataset[i]\n utils.log_print(\"Processing image: {} with name: {}\".format(i, sample['image_name']))\n image, gt_density_map, image_name = sample['image'], sample['density_map'], sample['image_name']\n binary_gt_density_map = gt_density_map.clone()\n binary_gt_density_map[binary_gt_density_map > 0] = 1\n density_map = net(image, binary_gt_density_map)\n # Debug\n #unique, counts = np.unique(gt_density_map.data.cpu().numpy(), return_counts=True)\n #print(dict(zip(unique, counts)))\n utils.log_print(\"Input image shape: {}, Density Map GT Shape {}, Density Map Shape {}\".format(image.shape, gt_density_map.shape, density_map.shape))\n loss = LOSS(density_map, gt_density_map)\n train_loss += loss.item()\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if epoch % SAVE_INTERVAL == 0:\n gt_count = np.sum(gt_density_map.data.cpu().numpy())\n estimated_count = np.sum(density_map.data.cpu().numpy())\n utils.log_print(\"Saving results: epoch: {}, gt_count: {}, estimated_count: {}\".format(epoch, gt_count, estimated_count), color='green')\n utils.saveResults(image, gt_density_map, density_map, output_dir, image_name, DOWN_SAMPLE_FACTOR)\n\n if epoch % (SAVE_INTERVAL * 2) == 0:\n file_name = os.path.join(SAVED_MODELS_DIR, \"network_epoch{}.h5\".format(epoch))\n network.saveSnapshot(file_name, net)\n mae, mse = evaluate_model.evaluateModel(file_name, val_dataset, IS_CUDA)\n if mae < best_mae:\n best_mae = mae\n best_model = \"network_epoch{}.h5\".format(epoch)\n if mse < best_mse:\n best_mse = mse\n utils.log_print(\"Saving snapshot: epoch: {}, mae: {}, mse: {}, best_mae: {}, best_mse: {}, best_model: {}\".format(epoch, mae, mse, best_mae, best_mse, best_model), color='green', attrs=['bold'])\n exp.add_scalar_value('MAE', mae, step=epoch)\n exp.add_scalar_value('MSE', mse, step=epoch)\n exp.add_scalar_value('train_loss', train_loss / len(train_dataset), step=epoch)\n\n\n","sub_path":"src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"175762704","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom keras.layers import Dense\nfrom keras.models import Sequential\n\nx_data = np.random.rand(100)\nnoise = np.random.normal(0, 0.01, x_data.shape)\ny_data = x_data * 0.1 + 0.2 + noise\nplt.scatter(x_data, y_data)\nplt.show()\n\nmodel = Sequential()\nmodel.add(Dense(units=1,input_dim=1))\nmodel.compile(optimizer='sgd', loss='mse')\n\nfor step in range(30000):\n # 每次都训练一个批次,这个地方我们使用的是全部放入\n cost = model.train_on_batch(x_data, y_data)\n if step % 500 == 0:\n print('cost:', cost)\n\nw, b = model.layers[0].get_weights()\nprint('w:', w, 'b:', b)\n\n# x 输入到网络中 得到预测的值\ny_pred = model.predict(x_data)\n\n# 显示随机点\nplt.scatter(x_data, y_data)\n# 显示预测结果\nplt.plot(x_data, y_pred, 'r-', lw=3)\nplt.show()\n","sub_path":"test/info.py","file_name":"info.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"398181548","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jul 20 12:02:35 2019\n\n@author: Utente\n\"\"\"\n\nimport csv\nimport math as m\n\n\ndef CsvToFile(key):\n places = []\n if(key == \"ristoranti\"):\n csv_name = 'dataset/RISTORANTI BARI E PROVINCIA.csv'\n elif(key == \"hotel\"): \n csv_name = 'dataset/HOTEL BARI E PROVINCIA.csv'\n else:\n csv_name = 'dataset/LUOGHI D\\'INTERESSE BARI E PROVINCIA.csv'\t \n with open(csv_name, newline='') as csvfile:\n reader = csv.reader(csvfile, delimiter = ';')\n for value, row in enumerate(reader, 1):\n if(row[0] != \"URL\"):\n places.append(row)\n return places\n\t\t\n\ndef findImage(url):\n with open(\"dataset/images.csv\", newline='') as csvfile:\n reader = csv.reader(csvfile, delimiter = ';')\n for value, row in enumerate(reader, 1):\n if(row[0] == url):\n csvfile.close() \n return row[1]\n return \"-\"\n \n \n\ndef maxRatings(csv_name, column):\n with open(csv_name, newline='') as csvfile:\n reader = csv.reader(csvfile, delimiter = ';')\n max_n_ratings = -m.inf\n for value, row in enumerate(reader, 1):\n if(value != 1):\n ratings = int(row[column])\n if(ratings > max_n_ratings):\n max_n_ratings = ratings\n csvfile.close() \n return max_n_ratings\n\n \ndef readCoordinateCsv(csv_name):\n with open(csv_name, newline='') as csvfile:\n reader = csv.reader(csvfile, delimiter = ';') \n coordinates = []\n for value, coordinate in enumerate(reader, 1):\n if(coordinate[0] != \"URL\" and coordinate[0] != \"CITY\"):\n coordinates.append(coordinate)\n return coordinates\n \n \n \ndef addStereotype(csv_stereotypes, stereotype):\n with open(csv_stereotypes, 'a', newline=\"\") as csvfile:\n filewriter = csv.writer(csvfile, delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator=\"\\n\")\n filewriter.writerow(stereotype)\n csvfile.close()\n\n\n#This method checks that a row contains the filter derived from the prediction\ndef checkRow(row, services, pred_filter, filter, list, explanations_row):\n occurrence_features = 0\n if(pred_filter == 1):\n if (services.find(filter)) >= 0:\n if(not(row in list)):\n list.append(row)\n explanations_row.append(filter.lower())\n occurrence_features = occurrence_features + 1\n return occurrence_features\n\n\ndef iterateRows(csv_name, column, n_features, prediction, keys):\n list = []\n explanations_list = []\n weight_list = []\n filters = \"\"\n with open(csv_name, newline='') as csvfile:\n reader = csv.reader(csvfile, delimiter = ';') \n for value, row in enumerate(reader, 1):\n services = row[column].upper()\n explanations_row = []\n occurrence_features = 0\n for i in range(n_features):\n pred = prediction.item(0, i)\n if(pred == 1 and value == 1):\n filters = filters + keys[i] + \", \"\n occurrence_features += checkRow(row, services, pred, keys[i], list, explanations_row) \n weight = occurrence_features / n_features \n if(row in list):\n if(occurrence_features != 0):\n weight_list_elem = [row[0], weight]\n weight_list.append(weight_list_elem)\n explanations_row.insert(0, row[0])\n explanations_list.append(explanations_row) #in explanations_list ogni elemento è una lista il cui primo elem è l'url del luogo di riferimento e gli altri elem sono le spiegazioni\n csvfile.close()\n print(\"[\", filters[0:-2], \"]\")\n return list, explanations_list, weight_list\n\n\ndef findHotels(prediction):\n hotel_csv = 'dataset/HOTEL BARI E PROVINCIA.csv'\n keys = [\"RISTORANTE\", \"BAR\", \"PISCINA\", \"PARCHEGGIO\", \"SPA\", \"ANIMALI AMMESSI\", \"CENTRO FITNESS\", \"WIFI\", \"SERVIZIO IN CAMERA\"] \n column = 7\n n_features = 9\n hotels, explanations_list, weight_list = iterateRows(hotel_csv, column, n_features, prediction, keys)\n return hotels, explanations_list, weight_list\n \n\ndef findRestaurants(prediction):\n restaurants_csv = 'dataset/RISTORANTI BARI E PROVINCIA.csv'\n keys = [\"ITALIANA\", \"PIZZA\", \"PESCE\", \"MEDITERRANEA\", \"FUSION\", \"PASTICCERIE\", \"GELATERIE\", \"BAR\", \"GRECA\", \"PUB\", \"GIAPPONESE\", \"FAST FOOD\", \"STEAKHOUSE\", \"FRANCESE\", \"BIRRERIA\", \"EUROPEA\", \"AMERICANA\", \"CINESE\", \"ASIATICA\", \"GASTRONOMIA\"]\n column = 4\n n_features = 20\n restaurants, explanations_list, weight_list = iterateRows(restaurants_csv, column, n_features, prediction, keys) \n return restaurants, explanations_list, weight_list\n\n\ndef findPlaces(prediction):\n places_csv = 'dataset/LUOGHI D\\'INTERESSE BARI E PROVINCIA.csv'\n keys = [\"SITI STORICI\", \"MONUMENTI E STATUE\", \"LUOGHI E PUNTI D'INTERESSE\", \"SITI RELIGIOSI E LUOGHI SACRI\", \"CHIESE E CATTEDRALI\", \"EDIFICI ARCHITETTONICI\", \"MUSEI\", \"TOUR\", \"SHOPPING\", \"VITA NOTTURNA\", \"ATTIVITÀ ALL'APERTO\", \"SPIAGGE\", \"GIOCHI E DIVERTIMENTO\", \"SPA E BENESSERE\", \"PARCHI E NATURA\", \"TORRI E PONTI DI OSSERVAZIONE\", \"BIBLIOTECHE\", \"PARCHI DIVERTIMENTI E ACQUATICI\", \"PASSEGGIATE IN SITI STORICI\", \"CASTELLI\"]\n column = 6\n n_features = 20\n places, explanations_list, weight_list = iterateRows(places_csv, column, n_features, prediction, keys) \n return places, explanations_list, weight_list","sub_path":"TouRES(Windows)/services/csv_operations.py","file_name":"csv_operations.py","file_ext":"py","file_size_in_byte":5501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"80415224","text":"# coding: utf-8\n\nimport keys\nfrom bittrex_dl import Bittrex\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport urllib.request, json\n#get_ipython().magic('matplotlib inline')\n\nkey = keys.get_key()\nsecret = keys.get_secret()\nbittrex = Bittrex(key, secret)\n\n\n# In[ ]:\n\n\npair = 'BTC-LTC'\n\ntemp = bittrex.get_ticker(pair)\nask = temp['result']['Ask']\nbid = temp['result']['Bid']\nprice = temp['result']['Last']\nprint(ask, bid, price)\n'''\nask = 0.02 # remove these if have internet\nbid = 0.03\nprice = 0.025\n'''\nbases = [0.01510642, 0.0132565, 0.0113416, 0.01090005]\n\ndef broke_base(pair, bases, price):\n #print(bases)\n if price > bases[-1][2]: \n return (False, 'did not break bases')\n elif ((len(bases) > 1) and (bases[-2][2] < bases[-1][2]) and (price < bases[-2][2])):\n return (True, 'broke two bases', bases[-2][2])\n else:\n return (True, 'broke one base', bases[-1][2])\n\n\n\ndef buy_decision(bittrex, Xtime, price, ask, pair, last_bases, ticker, percentage_limit, funding_limit, former_buys):\n if len(former_buys) > 0:\n initial_answer = broke_base(pair, [['', '', former_buys[0][3]]], price) # empty just to make sure we're lower than last buy\n if initial_answer[0] == False: return (False, 'NO BUY: higher than a previous buy order')\n initial_answer = [initial_answer[0], initial_answer[1], last_bases[-1][2]] # uncertain about this (17.9), should make sure calculations are with broken base\n if len(former_buys) >= 5: return (False, 'NO BUY: out of funds for now')\n else: \n initial_answer = broke_base(pair, last_bases, price)\n if initial_answer[0] == False: return (False, 'NO BUY: did not go under base') \n \n if len(former_buys) > 0:\n last_base_broken = max([former_buys[-1][3], former_buys[-1][1]]) # calculate distance from the base, rather than last buy\n else:\n last_base_broken = initial_answer[2]\n \n diff = last_base_broken - price\n diff_percentage = diff / last_base_broken # this refers to how low is the price below the base\n if diff < 0: return (False, 'ERROR: price is above last reported base')\n if diff_percentage < percentage_limit: \n return (False, 'NO BUY: fall under base is still too small')\n \n #drops = [0.09, 0.11, 0.13, 0.15, 0.19] # hard coded (tizzle) so SHOULD CHANGE; assumes historical avg. drop of 13%\n drops = [0.05, 0.09, 0.11, 0.13, 0.15] # hard coded for example so SHOULD BE DELETED\n stages = [0.25, 0.425, 0.325, 1, 1]\n \n ind = min([len(former_buys), 4])\n if diff_percentage > drops[ind]:\n percentage_modifier = stages[ind]\n print(last_base_broken, price, diff_percentage, percentage_limit)\n else:\n return (False, 'NO BUY: has not reached the next station')\n \n buy_amount = funding_limit * percentage_modifier\n\n #advised_buy_amount = funding_limit * 0.25 * base_modifier * percentage_modifier # obsolete?\n #buy_amount = min([funding_limit, advised_buy_amount])\n \n print('[testing]: time {}; buying '.format(Xtime) + pair + ' for {} BTC, {:0.6f} units for {} per unit.'.format(buy_amount, buy_amount/ask, ask))\n buy_details = ['BUY', pair, buy_amount/ask, ask, buy_amount] # pair, units, price, sum\n return buy_details\n \ndef sell_decision(bittrex, Xtime, price, bid, pair, ticker, former_buys):\n # NOTE: for demo purposes, sales will be made at bid prices (=market price, not limit price)\n if bid > former_buys[0][1]: # the base level\n amount_in_hand = 0\n for buy in former_buys:\n amount_in_hand += buy[2]\n print('[testing]: time {}; selling '.format(Xtime) + pair + ', {:0.6f} units for {} BTC per unit (total of {:0.6f}).'.format(amount_in_hand, bid, amount_in_hand * bid))\n sale_details = ['SELL', pair, amount_in_hand/bid, bid, amount_in_hand] # pair, units, price, sum\n return sale_details\n return ['NO SELL']\n\n\ndef run_demo(inum):\n df = pd.read_csv('BTC-VTC.csv')\n demo_df = df.iloc[0:720 + inum]\n return df, demo_df\n \ndef find_demo_bases(df):\n import notification_bot2B as nb2\n pot_bases = nb2.check_for_potential_bases(df, feedback=False)\n lines = nb2.prepare_to_draw(df, pot_bases)\n bases = nb2.draw_bases(df, lines, visual=False, feedback=False)\n return bases\n\n# former_buys is a list that is supposed to track former buys; here it CURRENTLY resets automatically but should be compared to sells\n# bases2[-1][2] is the last base (can sometimes change)\n# buy_addition_to_list is the details added to the list of former_buys\ndef standard_test(bittrex):\n former_buys = []\n new_bases = []\n buy_arrows = []\n sell_arrows = []\n account_balance_btc = 3 # just for testing\n account_balance_other = 0\n for i in range(280, 320): # 280-320 for the standard check, -580 for the wider check\n df, partial_df = run_demo(i)\n bases2 = find_demo_bases(partial_df)\n price = df.iloc[720 + i]['L']\n ask = df.iloc[720 + i]['L'] # just for testing\n bid = df.iloc[720 + i]['H'] # just for testing, should be higher resolution\n ticker = [df.iloc[720 + i]['L'], df.iloc[720 + i]['L'], df.iloc[720 + i]['L']] # this should be replaced with realtime data\n \n if ((len(new_bases) == 0) or (new_bases[-1][1] > bases2[-1][1])) and (len(new_bases) > 0):\n last_base_price = new_bases[-1][2]\n else:\n last_base_price = bases2[-1][2]\n \n #print('Time/oldbase/newbase/last_base_price considered: ', end='')\n #if (len(new_bases) == 0): print(720+i, bases2[-1][1], bases2[-1][2], last_base_price)\n #else: print(720+i, new_bases[-1][1], new_bases[-1][2], bases2[-1][1], bases2[-1][2], last_base_price)\n\n if price < last_base_price:\n #print('***')\n #print(\"Base broken; current time: {}, current price: {:0.8f}, base at {}\".format(720+i, price, last_base_price))\n temp_bases = bases2 + [['','',last_base_price]]\n ans = buy_decision(bittrex, 720+i, price, ask, 'BTC-VTC', temp_bases, ticker, 0.05, 1, former_buys) \n # the penultimate variable is the normal amount to be bought\n # the appending to bases2 is meant to lower the last base after a former buy\n if ans[0] == 'BUY':\n stage = len(former_buys)\n buy_addition_to_list = [720+i, last_base_price, ans[2], ans[3], ans[4], stage] # stage refers to percentage of limit bought\n former_buys.append(buy_addition_to_list)\n account_balance_btc -= ans[4]\n account_balance_other += ans[2]\n print(buy_addition_to_list)\n buy_arrows.append([720+i, ans[3]-ans[3]*0.10, 720+i, ans[3]]) # add tp arrows\n\n sell_price = df.iloc[720 + i]['H']\n if (len(former_buys) > 0):\n sell_ans = sell_decision(bittrex, 720+i, sell_price, bid, 'BTC-VTC', ticker, former_buys)\n if sell_ans[0] == 'SELL':\n account_balance_btc += sell_ans[4] * sell_ans[3]\n account_balance_other -= sell_ans[4] \n former_buys = [] # cleaning this, since everything was sold\n sell_arrows.append([720+i, sell_ans[3], 720+i, sell_ans[3]+sell_ans[3]*0.10])\n\n # this part is supposed to establish a new base after a sell\n last_base_end_loc = bases2[-1][1]\n new_base_depth = df.iloc[last_base_end_loc:720+i]['L'].min()\n new_base_loc = int(np.where(df[last_base_end_loc:720+i].index == df.iloc[last_base_end_loc:720+i]['L'].idxmin())[0]) + last_base_end_loc\n new_base = [new_base_loc, new_base_loc, new_base_depth] \n new_bases.append(new_base)\n\n if i % 5 == 0:\n print(\"time: {}, btc account: {}, other account: {}\".format(i, account_balance_btc, account_balance_other))\n return [buy_arrows, sell_arrows]\n\n\narrows = standard_test(bittrex)\ndf = pd.read_csv('BTC-VTC.csv')\nimport notification_bot2B as nb2\npot_bases = nb2.check_for_potential_bases(df, feedback=False)\nlines = nb2.prepare_to_draw(df, pot_bases)\ntemp_bases = nb2.draw_bases(df, lines, visual=True, feedback=False, highs=True, arrows=arrows)\n \n'''\ndf = pd.read_csv('BTC-VTC.csv')\ndf.iloc[0:2]\nbases2[-1][2]\n\n\n# In[7]:\n\n\ndf = pd.read_csv('BTC-VTC.csv')\nimport notification_bot2B as nb2\npot_bases = nb2.check_for_potential_bases(df, feedback=False)\nlines = nb2.prepare_to_draw(df, pot_bases)\ntemp_bases = nb2.draw_bases(df, lines, visual=True, feedback=False)\n\n\n\n# In[11]:\n\n\nget_ipython().magic('matplotlib inline')\nplt.plot(df['L'])\n\n\n# In[ ]:\n\n\nfor i in range(720, 722):\n temp = pd.Series(df.iloc[i])\n demo_df = demo_df.append(temp)\n\n\n# In[ ]:\n\n\ntemp = bittrex.get_ticker(pair)\n ask = temp['result']['Ask']\n bid = temp['result']['Bid']\n spread = ask - bid\n price = temp['result']['Last']\n'''\n","sub_path":"buybot-workingbackup.py","file_name":"buybot-workingbackup.py","file_ext":"py","file_size_in_byte":8930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"537975479","text":"import subprocess\nimport psutil\nimport re\nfrom Helper import Config, TapConfig, Level\nfrom typing import Dict, Optional, Callable\nfrom time import sleep\n\n\nclass Tap:\n initialized = False\n tapConfig: TapConfig = None\n closingRegex = None\n\n @classmethod\n def Initialize(cls):\n cls.tapConfig = Config().Tap\n cls.closingRegex = re.compile(r'.*Resource \".*\" closed.*')\n cls.initialized = True\n\n def __init__(self, tapPlan: str, externals: Dict[str, str], logger: Callable):\n if not self.initialized:\n self.Initialize()\n\n self.tapPlan = tapPlan\n self.externals = externals\n self.args = self.getArgs(tapPlan, externals)\n self.logger = logger\n self.closedInstruments = 0\n self.closeStarted = False\n self.process: Optional[psutil.Process] = None\n\n @staticmethod\n def getArgs(tapPlan: str, externals: Dict[str, str]):\n if Tap.tapConfig.OpenTap:\n args = [Tap.tapConfig.Path, 'run', '-v']\n else:\n args = [Tap.tapConfig.Path, '-v']\n\n for key, value in externals.items():\n args.extend(['-e', f'{key}={value}'])\n\n args.append(tapPlan)\n\n return args\n\n def notify(self):\n self.logger(Level.INFO, f'Executing TapPlan: {self.tapPlan}')\n if len(self.externals) != 0:\n for key, value in self.externals.items():\n self.logger(Level.INFO, f' {key}={value}')\n\n def Execute(self) -> int:\n self.closedInstruments = 0\n self.closeStarted = False\n\n self.notify()\n process = subprocess.Popen(self.args, stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT, cwd=Tap.tapConfig.Folder)\n sleep(0.5) # Give some time to ensure that psutil finds the process\n self.process = psutil.Process(process.pid)\n self.tap_stdout(process)\n\n exitCode = process.wait()\n\n return exitCode\n\n def tap_stdout(self, process: subprocess.Popen):\n _levels = [('Debug', Level.DEBUG), ('Information', Level.INFO),\n ('Warning', Level.WARNING), ('Error', Level.ERROR)]\n\n def _inferLevel(l: str) -> Level:\n for level in _levels:\n string, res = level\n if re.match(f'.*:\\s*{string}\\s*:.*', l): return res\n return Level.INFO\n\n pipe = process.stdout\n\n for line in iter(pipe.readline, b''):\n try: line = line.decode('utf-8').rstrip()\n except Exception as e: line = f\"DECODING EXCEPTION: {e}\"\n\n level = _inferLevel(line)\n self.logger(level, f\"[TAP]{line}\")\n\n if self.tapConfig.EnsureClosed:\n if 'Unable to continue. Now exiting TAP CLI' in line:\n self.closeStarted = True\n Tap.ensureTapClosed(self.process, self.logger, self.tapConfig.EnsureAdbClosed)\n\n if Tap.closingRegex.match(line):\n self.closedInstruments += 1\n if self.closedInstruments >= 3 and not self.closeStarted:\n self.closeStarted = True\n Tap.ensureTapClosed(self.process, self.logger, self.tapConfig.EnsureAdbClosed)\n\n @staticmethod\n def ensureTapClosed(tapProcess: psutil.Process, logger, closeAdb):\n logger(Level.INFO, 'Ensuring that TAP is correctly closed (in 15 seconds).')\n sleep(15)\n\n if tapProcess.is_running():\n logger(Level.WARNING, f'TAP still running, stopping child processes '\n f'({len(tapProcess.children(recursive=True))})...')\n Tap.endProcessTree(tapProcess)\n logger(Level.INFO, 'Process tree closed')\n else:\n logger(Level.INFO, 'TAP closed correctly')\n\n if closeAdb:\n for p in psutil.process_iter():\n if p.name() == 'adb.exe':\n logger(Level.WARNING, f\"Closing rogue adb process with PID: {p.pid}\")\n p.kill()\n\n @classmethod\n def endProcessTree(cls, process: psutil.Process):\n def safeTerminate(p: psutil.Process):\n try: p.terminate()\n except psutil.NoSuchProcess: pass\n\n for child in process.children(recursive=True): # type: psutil.Process\n safeTerminate(child)\n safeTerminate(process)\n","sub_path":"Helper/tap_executor.py","file_name":"tap_executor.py","file_ext":"py","file_size_in_byte":4357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"357952850","text":"'''\nPR 2.3: Kvadratická rovnica\n\nVstup: koeficienty A, B, C kvadratickej rovnice A.X2 + B.X + C = 0 (môžu byť aj reálne čísla).\n\nVýstup: nemá riešenie / má dvojnásobný koreň X=... / má dva korene X1=... a X2=...\n\nnapr. \"Kvadratická rovnica x2 - 2.x - 15 = 0 má dva korene x1 = -5 a x2 = 3.\"\n\nOverenie: a = 1, b = 3.37, c = -13.041 => x1 = 2.3 a x2 = -5.67\n'''\n\nimport math\n\na = float(input(\"Zadajte a: \"))\nb = float(input(\"Zadajte b: \"))\nc = float(input(\"Zadajte c: \"))\n\nd = b**2 - 4 * a * c\n\nif d < 0:\n\tprint(\"Ma riesenie v mnozine C.\")\n\trealna_cast = -b / (2 * a)\n\tx_1, x_2 = math.sqrt(-d)/(2 * a), math.sqrt(-d)/(2 * a)\n\tprint(f\"x = {{ {realna_cast}{x_1:+.2f}i, {realna_cast}{x_2:+.2f}i }}\")\nelif d == 0:\n\tprint(\"Ma 1 riesenie v mnozine R.\")\n\tx = -b / (2 * a)\n\tprint(f\"x = {x}\")\nelse:\n\tprint(\"Ma 2 riesenia v mnozine R.\")\n\tx_1, x_2 = (-b + math.sqrt(d))/(2 * a), (-b - math.sqrt(d))/(2 * a)\n\tprint(f\"x = {{ {x_1}, {x_2} }}\")","sub_path":"20170919/kvadraticka.py","file_name":"kvadraticka.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"327694006","text":"from scanner.models.IModel import IModel\n\n\n# сервис, занимающий порт\nclass Service(IModel):\n def __init__(self, name, port):\n IModel.__init__(self, 'Port', None)\n self.name = name\n self.port = port\n\n def __eq__(self, other):\n equals = True\n if self.name != other.name:\n equals = False\n return equals\n","sub_path":"scanner/models/Service.py","file_name":"Service.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"227509798","text":"# Generar una lista de 77 números aleatoriamente resolver lo siguiente:\n# a. indicar el valor menor.\n# b. indicar el valor mayor.\n# c. ordenar la lista de manera creciente y mostrar dichos valores.\n\nfrom random import randint\n\nlista = []\n\nfor i in range (0,78):\n numero = randint(1,77)\n lista.append(numero)\n\nlista.sort() \n\nprint(lista)\n\nprint(\"el número menor es\", lista[0]) \n\nprint(\"el número mayor es\", lista[77]) \n\nfor lista in range (0,78):\n if(lista% 2 == 0):\n print(lista)\n","sub_path":"3.Lista_abc.py","file_name":"3.Lista_abc.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"21345409","text":"from webhanfeng.lib.utils import *\nimport meta\n\ndef get_message_count():\n m = meta.Session.query(Message).count()\n return m\n\n@catch_exception\ndef get_all_message(offset=None,limit=None):\n if limit is None or offset is None:\n r = meta.Session.query(Message).order_by(Message.id.asc()).all()\n else:\n r = meta.Session.query(Message).order_by(Message.id.asc()).limit(limit).offset(offset).all()\n return r\n\n@catch_exception\ndef new_message(receive_id,timestamp,content,is_read,flag,msg_type,msg_title,city_name):\n m = Message()\n m.receive_id = receive_id\n m.timestamp = timestamp\n m.content = content\n m.is_read = is_read\n m.flag = flag\n m.msg_type = msg_type\n m.msg_title = msg_title\n m.city_name = city_name\n meta.Session.add(m)\n meta.Session.commit()\n return m\n\nclass Message(object): pass","sub_path":"source/ydxx/web/webhanfeng/webhanfeng/model/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"257977656","text":"#**************************************************************************\r\ndef ComputeGridPoints(Dimension, Length, delX, Height=None, delY=None):\r\n '''Returns the grid points along X and Y direction in the mesh.'''\r\n iMax = int(Length/delX) + 1\r\n if Dimension.upper() == '2D':\r\n jMax = int(Height/delY) + 1\r\n else:\r\n jMax = 0\r\n print('Calculating grid size: Completed.')\r\n\r\n return iMax, jMax\r\n\r\n#**************************************************************************\r\ndef ComputeGridSteps(Dimension, Length, iMax, Height=None, jMax=None):\r\n '''Returns the uniform grid steps size along X and Y direction in the\r\n mesh.\r\n '''\r\n delX = Length/(iMax - 1)\r\n if Dimension.upper() == '2D':\r\n delY = Height/(jMax - 1)\r\n else:\r\n delY = 0.0\r\n print('Calculating grid step size: Completed.')\r\n\r\n return delX, delY\r\n\r\n#**************************************************************************\r\ndef RectangularGrid(dX, iMax, dY=None, jMax=None):\r\n '''Returns X and Y grid point locations in a rectangular, uniform\r\n mesh in a cartesian coordinate system.\r\n '''\r\n import numpy as np\r\n\r\n if isinstance(dY, float) and isinstance(jMax, int):\r\n X = np.zeros((iMax,jMax), dtype='float')\r\n Y = np.zeros((iMax,jMax), dtype='float')\r\n for i in range(0,iMax):\r\n for j in range(0,jMax):\r\n X[i][j] = i*dX\r\n Y[i][j] = j*dY\r\n else:\r\n X = np.zeros((iMax), dtype='float')\r\n for i in range(0,iMax):\r\n X[i] = -9.0 + i*dX\r\n Y = 0.0\r\n print(f'Uniform rectangular grid generation in cartesian\\\r\n coordinate system: Completed.')\r\n\r\n return X, Y\r\n\r\n#**************************************************************************\r\ndef CurvilinearGrid(dX, iMax, dY=None, jMax=None):\r\n '''Returns X and Y grid point locations in a rectangular, uniform or a\r\n non-uniform mesh in a transformed coordinate system (Xi, Eta).\r\n '''\r\n print('Calculating X and Y locations of all grid points within\\\r\n the mesh.')\r\n from .backend import gridmetrics\r\n from .backend import plotmetrics\r\n dXi = 1.0\r\n dEta = 1.0\r\n\r\n X, Y = RectangularGrid(dX, iMax, dY, jMax)\r\n dim = X.shape\r\n\r\n if len(dim) == 2: # Two dimensional\r\n Xi = [[i*dXi for j in range(0,jMax)] for i in range(0,iMax)]\r\n Eta = [[j*dEta for j in range (0,jMax)] for i in range (0,iMax)]\r\n XiX, XiY, EtaX, EtaY, JJ = gridmetrics.Metrics2D(X, Y)\r\n print('Grid metrics and Jacobian evaluation: Completed.')\r\n plotmetrics.PlotMetrics2D(X, Y, XiX, XiY, EtaX, EtaY)\r\n\r\n elif len(dim) == 1:\r\n Xi = [i*dX for i in range(0,iMax)]\r\n Eta = 0.0\r\n Xi, JJ = gridmetrics.Metrics1D(X)\r\n print('Grid metrics and Jacobian evaluation: Completed.')\r\n\r\n print('Grid transformation to curvilinear coordinate system:\\\r\n Completed.')\r\n\r\n return X, Y\r\n\r\n#**************************************************************************\r\ndef CalcTimeStep(CFL, diff, conv, dX, dY, Dimension, Model):\r\n '''Returns the time step size in the solution.\r\n '''\r\n #*************** DIFFUSION EQN. ******************\r\n if Model.upper() == 'DIFFUSION':\r\n dX2 = dX*dX\r\n if Dimension.upper() == '1D':\r\n TimeStep = CFL*dX2/diff\r\n elif Dimension.upper() == '2D':\r\n dY2 = dY*dY\r\n TimeStep = CFL*(1.0/((1/dX2) + (1/dY2)))/diff\r\n #*************** FIRST-ORDER WAVE EQN. *****************\r\n elif Model.upper() == 'FO_WAVE':\r\n if Dimension.upper() == '1D':\r\n TimeStep = CFL*dX/conv\r\n #*************** BURGERS EQN. *****************\r\n elif Model.upper() == 'BURGERS':\r\n if Dimension.upper() == '1D':\r\n TimeStep = CFL*dX\r\n print('Calculating time step size for the simulation: Completed.')\r\n\r\n return TimeStep\r\n\r\n#**************************************************************************\r\ndef CalcMaxSteps(State, nMax, dT, simTime):\r\n '''Returns the max iteration/time steps for the solution.\r\n '''\r\n if State.upper() == 'TRANSIENT':\r\n if not simTime > 0.0: # simulation time can't be negative\r\n error_msg = 'ERROR: INCORRECT DATA FORMAT.\\nCheck section\\\r\n [STOP] --> key: [SIM_TIME] in\\nfile:'\r\n raise Exception(f'{error_msg} {InFileName}.')\r\n try:\r\n MaxSteps = int(simTime/dT)\r\n except dT:\r\n raise Exception('No time step provided.')\r\n elif State.upper() == 'STEADY':\r\n MaxSteps = nMax\r\n print('Calculating maximum iterations/steps for the simulation:\\\r\n Completed.')\r\n\r\n return MaxSteps\r\n\r\n","sub_path":"nanpack/grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":4658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"321273041","text":"from __future__ import division, print_function\nimport time\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import asarray\nfrom numpy import expand_dims\nfrom numpy import log\nfrom numpy import mean\nfrom numpy import exp\nfrom numpy import std\nfrom math import floor\nimport os\nfrom keras.models import Model, Sequential\nfrom keras.layers import Activation, Dense, Flatten, BatchNormalization, Dropout, Input, Reshape, multiply\nfrom keras.layers import Embedding, ZeroPadding2D\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.optimizers import Nadam, Adam, SGD\nfrom keras.datasets import mnist\nimport tensorflow as tf\n\n(X_train, y_train), (X_test, y_test) = mnist.load_data()\n\n# Image shape information\n\nimg_rows = X_train.shape[1]\nimg_cols = X_train.shape[2]\nif len(X_train.shape) == 4:\n channels = X_train.shape[3]\nelse:\n channels = 1\n\nimg_shape = (img_rows, img_cols, channels)\nnum_classes = 10\nlatent_dim = 100\noptimizer = Adam(0.0002, 0.5)\n\ndef generator():\n model = Sequential()\n model.add(Dense(256, input_dim=latent_dim))\n model.add(LeakyReLU(alpha=0.2))\n model.add(BatchNormalization(momentum=0.8))\n model.add(Dense(512))\n model.add(LeakyReLU(alpha=0.2))\n model.add(BatchNormalization(momentum=0.8))\n model.add(Dense(1024))\n model.add(LeakyReLU(alpha=0.2))\n model.add(BatchNormalization(momentum=0.8))\n model.add(Dense(np.prod(img_shape), activation='tanh'))\n model.add(Reshape(img_shape))\n #model.summary()\n\n noise = Input(shape=(latent_dim,))\n label = Input(shape=(1,), dtype='int32')\n label_embedding = Flatten()(Embedding(num_classes, latent_dim)(label))\n model_input = multiply([noise, label_embedding])\n img = model(model_input)\n return Model([noise, label], img)\n\ndef discriminator():\n model = Sequential()\n model.add(Dense(512, input_dim=np.prod(img_shape)))\n model.add(LeakyReLU(alpha=0.2))\n model.add(Dense(512))\n model.add(LeakyReLU(alpha=0.2))\n model.add(Dropout(0.4))\n model.add(Dense(512))\n model.add(LeakyReLU(alpha=0.2))\n model.add(Dropout(0.4))\n model.add(Dense(1, activation='sigmoid'))\n #model.summary()\n\n img = Input(shape=img_shape)\n label = Input(shape=(1,), dtype='int32')\n label_embedding = Flatten()(Embedding(num_classes, np.prod(img_shape))(label))\n flat_img = Flatten()(img)\n\n model_input = multiply([flat_img, label_embedding])\n validity = model(model_input)\n return Model([img, label], validity)\n\n# Build the generator\n\ngenerator = generator()\n# The generator takes noise and the target label as input\n# and generates the corresponding digit of that label\ngenerator.load_weights('../Q2/saved_model_weights/version1/generator_weights_99000.h5')\n\n# the classifier\npath_save_model = 'save_weight_classifier/version_1.h5'\nmodel = tf.keras.models.load_model(path_save_model)","sub_path":"Lab 2 - Deep Learning (GAN)/Q3/load_different_cgan_model/cgan.py","file_name":"cgan.py","file_ext":"py","file_size_in_byte":2856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"167964028","text":"# Funçao para calcular as visualizaçoes\ndef my_function(views): \n # A cada 100 pessoas que visualizam o anúncio 12 clicam nele.\n cliq = float(views) / 100 * 12 \n # A cada 20 pessoas que clicam no anúncio 3 compartilham nas redes sociais.\n compart = float(cliq) / 20 * 3 \n # Cada compartilhamento nas redes sociais gera 40 novas visualizações.\n totViews = float(compart) * 40 \n # Total de visualizações do ciclo\n return totViews\n\n# Valor a ser investido\nValor = float( input(\"Favor informar o valor investido em reais (R$): \") )\n\n# 30 pessoas visualizam o anúncio original\nqtdValor = float(Valor * 30)\n\n# Valoriza 0 1ª Ciclo\nresult = float(qtdValor)\nTotal = float(result)\n\n# repeticao de 4 Ciclo\nfor x in range(4):\n result = float(my_function(result))\n print(\"visualizações: {0}\".format(result))\n Total = float(Total) + float(result) \n\n# Total de visualizações somando os Ciclos\nprint(\"Valor investido (R$): {0}\".format(Valor) + \" gerando o total de visualizações: {0}\".format(Total))","sub_path":"CapgeminiDesafio_Em_Python/Calculador.py","file_name":"Calculador.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"480163346","text":"# coding: utf-8\r\nimport shutil, tqdm\r\nimport pandas as pd\r\n\r\ndf = pd.read_csv(\"./temp/df.csv\")\r\npaths = df.file.tolist()\r\nbars = tqdm.tqdm(paths)\r\nfor i, bar in enumerate(bars):\r\n shutil.copyfile(paths[i], \"./temp/{}\".format(paths[i][13:]))\r\n bars.set_description(\"已复制 {}\".format(bar))\r\n","sub_path":"0202/move0K.py","file_name":"move0K.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"543791089","text":"import torch\nfrom torch import optim\nimport time\n\nfrom models import *\nfrom datasets import *\nfrom loss import *\n\nbatch_size = 500\nv_batch_size = 100\nepoch = 22\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\ntorch.backends.cudnn.benchmark = True\n\ntrain_imgs, train_lbls, val_imgs, val_lbls = build_dataset(device=device)\nn_train = len(train_lbls)\nn_val = len(val_lbls)\n\n\nnet = build_network()\nnet.to(device).half()\nfor layer in net.modules():\n if isinstance(layer, nn.BatchNorm2d):\n layer.float()\n if hasattr(layer, 'weight') and layer.weight is not None:\n layer.weight.data.fill_(1.0)\n layer.eps = 0.00001\n layer.momentum = 0.1\n\ncriterion = nn.CrossEntropyLoss()\ncriterion2 = CrossEntropyLabelSmooth(num_classes=10, epsilon=0.2)\noptimizer = optim.SGD(net.parameters(), lr=0.2, momentum=0.9, nesterov=True, weight_decay=0.001)\n\ndef lr(e):\n if e < 4:\n return 0.5*e/3. + 0.01\n return 0.5*(22-e)/19. + 0.01\nsched = optim.lr_scheduler.LambdaLR(optimizer, lr)\n\naugment = Augment()\naugment.to(device).half()\n\nt_start = time.time()\nfor e in range(epoch): # loop over the dataset multiple times\n start = time.time()\n\n # process training set\n a_train = []\n for i in range(n_train//batch_size):\n # get the inputs; data is a list of [inputs, labels]\n inputs = train_imgs[i*batch_size:(i+1)*batch_size, ...]\n a_train.append(augment(inputs.to(device).half()))\n a_train_imgs = torch.cat(a_train)\n perm = torch.randperm(n_train)\n a_train_imgs = a_train_imgs[perm, ...].contiguous()\n a_train_lbls = train_lbls[perm].contiguous()\n\n # a_stop = time.time()\n\n net.train()\n running_loss = []\n perm = torch.randperm(n_train)\n # t1 = 0\n # t2 = 0\n # t3 = 0\n for i in range(n_train//batch_size):\n # s = time.time()\n # get the inputs; data is a list of [inputs, labels]\n inputs = a_train_imgs[i*batch_size: (i+1)*batch_size, ...]\n labels = a_train_lbls[i*batch_size: (i+1)*batch_size]\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward + backward + optimize\n outputs = net(inputs)\n loss = criterion(outputs, labels)\n loss2 = criterion2(outputs, labels)\n loss = loss + 2*loss2\n # torch.cuda.synchronize()\n # t1 += time.time() - s\n loss.backward()\n # torch.cuda.synchronize()\n # t2 += time.time() - s\n optimizer.step()\n # torch.cuda.synchronize()\n # t3 += time.time() - s\n\n # print statistics\n running_loss.append(loss)\n running_loss = torch.stack(running_loss).mean().item()\n # t_stop = time.time()\n # t1 /= n_train//batch_size\n # t2 /= n_train//batch_size\n # t3 /= n_train//batch_size\n\n if e == 0 or e%5 == 1:\n net.eval()\n val_loss = []\n val_acc = []\n for i in range(n_val//v_batch_size):\n # get the inputs; data is a list of [inputs, labels]\n inputs = val_imgs[i*v_batch_size: (i+1)*v_batch_size, ...]\n labels = val_lbls[i*v_batch_size: (i+1)*v_batch_size]\n outputs = net(inputs)\n val_loss.append(criterion(outputs, labels))\n val_acc.append((outputs.argmax(dim=1) == labels).sum()/labels.shape[0])\n\n v_stop = time.time()\n # print('{} train loss {:5.02f} val loss {:5.02f} val acc {:5.02f} time a:{:5.03f} t:{:5.03f}, v:{:5.03f}, t1:{:5.03f}, t2:{:5.03f}, t3:{:5.03f} '.format(\n # e, running_loss, torch.stack(val_loss).mean(), 100.*torch.stack(val_acc).mean(), (a_stop-start), (t_stop-start), (v_stop - start), t1, t2, t3))\n print('{} train loss {:5.02f} val loss {:5.02f} val acc {:5.02f} time v:{:5.03f}'.format(\n e, running_loss, torch.stack(val_loss).mean(), 100.*torch.stack(val_acc).mean(), (v_stop - start)))\n sched.step()\nprint('Finished Training in {:5.03f}'.format(time.time()-t_start))\n\n\n","sub_path":"cifar_singlerun.py","file_name":"cifar_singlerun.py","file_ext":"py","file_size_in_byte":3697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"445458853","text":"\n# -*- coding: utf-8 -*-\n\n# Originally \n\n# List all loaded Objective-C classes.\n\nfrom pycocoa import get_classes, leaked2, sortuples\n\n__version__ = '18.11.02'\n\n\nif __name__ == '__main__':\n\n import sys\n\n if len(sys.argv) < 2:\n print('USAGE: python list_classes.py [prefix] ...')\n\n n, prefs = 0, sys.argv[1:]\n\n for name, _ in sortuples(get_classes(*prefs)):\n n += 1\n print(name)\n\n print('%s %s classes total %s' % (n, ', '.join(prefs), leaked2()))\n","sub_path":"test/list_classes.py","file_name":"list_classes.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"573764122","text":"# coding: utf-8\n\"\"\" 判断点是否在多边形内\n Reference: http://www.cnblogs.com/yym2013/p/3673616.html\n\"\"\"\n\n\nclass Point(object):\n def __init__(self, x, y):\n self.x = float(x)\n self.y = float(y)\n\n\n# 求p1p0和p2p0的叉积,如果大于0,则p1在p2的顺时针方向\ndef multiply(p1, p2, p0):\n return (p1.x - p0.x) * (p2.y - p0.y) - (p2.x - p0.x) * (p1.y - p0.y)\n\n\ndef in_convex_polygon(polygon, target):\n \"\"\"\n :type polygon: list[Point]\n :type target: Point\n :rtype: bool\n\n 判断点target 是否在 凸多边形polygon内部\n :param polygon:Point数组,代表凸多边形的顶点,顺时针给出\n :param target: Point对象,代表待查询的顶点\n :return: ture - target在凸多边形内\n\n \"\"\"\n eps = 1e-10\n n = len(polygon) - 1\n # 在第一个点为起点的扇形之外或在边上\n if multiply(target, polygon[1], polygon[0]) <= eps or multiply(target, polygon[n], polygon[0]) >= -eps:\n return False\n left = 2\n right = n\n\n while right - left != 1:\n mid = (left+right) / 2\n if multiply(target, polygon[mid], polygon[0]) > eps:\n left = mid\n else:\n right = mid\n # 在边之外或在边上\n if multiply(target, polygon[right], polygon[left]) <= eps:\n return False\n return True\n\n\n","sub_path":"participants_selection_covering/util/map_util.py","file_name":"map_util.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"591212337","text":"from math import ceil\n\nfrom scipy.fftpack import diff\nfrom scipy.signal import medfilt, lfilter\nfrom scipy.signal import resample, filtfilt\nfrom scipy.stats import mode\n\nfrom utils import matlab, common\nfrom utils.matlab import *\n\n\ndef frange(x, y, jump):\n while x < y:\n yield x\n x += jump\n\n\ndef qrs_detect2(ecg, thres=0.6, ref_period=0.25, fs=300):\n \"\"\"\n QRS detector based on the P&T method\n See: https://github.com/alistairewj/peak-detector/blob/master/sources/qrs_detect2.m\n :param ecg: one ecg channel on which to run the detector\n :param thres: energy threshold of the detector [arbitrary units]\n :param ref_period: refractory period in sec between two R-peaks [ms]\n :param fs: sampling frequency [Hz]\n :return: list, positions of R picks\n \"\"\"\n\n WIN_SAMP_SZ = 7\n MED_SMOOTH_NB_COEFF = int(round(fs / 100))\n INT_NB_COEFF = int(round(WIN_SAMP_SZ * fs / 256))\n SEARCH_BACK = True\n MAX_FORCE = []\n MIN_AMP = 0.1\n\n NB_SAMP = len(ecg)\n\n tm = list(frange(1 / fs, ceil(NB_SAMP / fs), 1 / fs))\n\n # == Bandpass filtering for ECG signal\n # this sombrero hat has shown to give slightly better results than a\n # standard band-pass filter. Plot the frequency response to convince\n # yourself of what it does\n b1 = [-7.757327341237223e-05, -2.357742589814283e-04, -6.689305101192819e-04, -0.001770119249103,\n -0.004364327211358, -0.010013251577232, -0.021344241245400, -0.042182820580118, -0.077080889653194,\n -0.129740392318591, -0.200064921294891, -0.280328573340852, -0.352139052257134, - 0.386867664739069,\n -0.351974030208595, -0.223363323458050, 0, 0.286427448595213, 0.574058766243311,\n 0.788100265785590, 0.867325070584078, 0.788100265785590, 0.574058766243311, 0.286427448595213, 0,\n -0.223363323458050, -0.351974030208595, -0.386867664739069, -0.352139052257134,\n -0.280328573340852, -0.200064921294891, -0.129740392318591, -0.077080889653194, -0.042182820580118,\n -0.021344241245400, -0.010013251577232, -0.004364327211358, -0.001770119249103, -6.689305101192819e-04,\n -2.357742589814283e-04, -7.757327341237223e-05]\n\n # NOTE: resample works differently than in matlab\n b1 = resample(b1, int(ceil(len(b1) * fs / 250)))\n bpfecg = np.transpose(filtfilt(b1, 1, ecg))\n\n if (sum(abs(ecg - common.mode(ecg)) > MIN_AMP) / NB_SAMP) > 0.2:\n \"\"\"\n if 20% of the samples have an absolute amplitude which is higher\n than MIN_AMP then we are good to go\n \"\"\"\n\n # == P&T operations\n dffecg = matlab.diff(np.transpose(bpfecg))\n sqrecg = [x * x for x in dffecg]\n intecg = lfilter(np.ones(INT_NB_COEFF), 1, sqrecg)\n mdfint = medfilt(intecg, [MED_SMOOTH_NB_COEFF])\n delay = int(ceil(INT_NB_COEFF / 2))\n mdfint = np.roll(mdfint, -delay)\n\n mdfintFidel = mdfint\n\n if NB_SAMP / fs > 90:\n xs = np.sort(mdfintFidel[fs:fs * 90])\n else:\n xs = np.sort(mdfintFidel[fs:])\n\n if len(MAX_FORCE) == 0:\n if NB_SAMP / fs > 10:\n ind_xs = ceil(98 / 100 * len(xs))\n en_thres = xs[ind_xs]\n else:\n ind_xs = ceil(99 / 100 * len(xs))\n en_thres = xs[ind_xs]\n else:\n en_thres = MAX_FORCE\n\n poss_reg = apply(mdfint, lambda x: x > (thres * en_thres))\n\n if len(poss_reg) == 0:\n poss_reg[10] = 1\n\n if SEARCH_BACK:\n # ind of samples above threshold\n indAboveThreshold = find(poss_reg, lambda x: x > 0)\n # compute RRv\n RRv = np.diff([tm[i] for i in indAboveThreshold])\n medRRv = mode([RRv[i] for i in find(RRv, lambda x: x > 0.01)]).mode[0]\n # missed a peak?\n indMissedBeat = find(RRv, lambda x: x > 1.5 * medRRv)\n # find interval onto which a beat might have been missed\n indStart = [indAboveThreshold[i] for i in indMissedBeat]\n indEnd = [indAboveThreshold[i + 1] for i in indMissedBeat]\n\n for i in range(len(indStart)):\n # look for a peak on this interval by lowering the energy threshold\n poss_reg[indStart[i]:indEnd[i]] = apply(mdfint[indStart[i]:indEnd[i]],\n lambda x: x > 0.3 * thres * en_thres)\n\n left = find(diff(np.append([0], np.transpose(poss_reg))), lambda x: x == 1)\n right = find(diff(np.append(np.transpose(poss_reg), [0])), lambda x: x == -1)\n\n all = [(left, right) for left, right in zip(left, right) if left != right]\n\n left = [x[0] for x in all]\n right = [x[1] for x in all]\n\n nb_s = len(apply(left, lambda x: x < 30 * fs))\n loc = np.zeros(nb_s, dtype=np.int32)\n for j in range(nb_s):\n a, loc[j] = np_max(abs(bpfecg[left[j]:right[j]]))\n loc[j] = loc[j] + left[j]\n sign = np.mean([ecg[i] for i in loc])\n\n compt = 0\n NB_PEAKS = len(left)\n maxval = np.zeros(NB_PEAKS)\n maxloc = np.zeros(NB_PEAKS, dtype=np.int32)\n\n for i in range(NB_PEAKS):\n if sign > 0:\n v, l = np_max(ecg[left[i]:right[i]])\n else:\n v, l = np_min(ecg[left[i]:right[i]])\n\n maxval[compt] = v\n maxloc[compt] = l + left[i]\n\n if compt > 0:\n if maxloc[compt] - maxloc[compt - 1] < fs * ref_period and abs(maxval[compt]) < abs(maxval[compt - 1]):\n continue\n elif maxloc[compt] - maxloc[compt - 1] < fs * ref_period and abs(maxval[compt]) >= abs(\n maxval[compt - 1]):\n maxloc[compt - 1] = maxloc[compt]\n maxval[compt - 1] = maxval[compt]\n else:\n compt += 1\n else:\n # if first peak then increment\n compt += 1\n\n # datapoints QRS positions\n qrs_pos = maxloc[:compt]\n else:\n qrs_pos = []\n sign = None\n en_thres = None\n\n return qrs_pos\n","sub_path":"extract_features/biosppyex/signals/qrs_detect2.py","file_name":"qrs_detect2.py","file_ext":"py","file_size_in_byte":6121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"18346203","text":"from numpy.random import randint\nfrom random import random as rnd\nfrom random import gauss, randrange\nimport scipy as sp\nimport numpy as np\nimport itertools\nimport copy\n\nfrom StochasticMechanics import Stochastic\nfrom BuildingProperties import *\nimport Performance\n\nclass ASGD():\n '''\n ASGD main class\n\n fun: objective function to be minimized (callable)\n grad: gradient of theobjective function to be minimized (callable)\n sampler: generates samples of the random variables. Takes integer n as input\n and returns n samples (callable)\n x0: starting point of optimizaton (array)\n iters: number of iterations when calling run method (int)\n step: step-size to use (float)\n ascent: flag to maximize instead of minimize (boolean)\n L and U: lower and upper bounds for the design parameters (arrays)\n gtol: tolerance for the norm of the gradient used as a stop criteria (float)\n print: flag for printing data on screen\n '''\n def __init__(self,\n fun,\n grad,\n sampler,\n x0,\n iters=1000,\n step=1e-3,\n smooth=0.9999,\n ascent=False,\n L=[],\n U=[],\n gtol=0,\n print=True):\n self.fun = fun\n self.grad = grad\n self.x = [np.array(x0)]\n self.x_ = np.zeros(np.shape(x0))\n self.x_pr = [np.array(x0)]\n self.grads = []\n self.sampler = sampler\n self.step = step\n self.iters = iters\n self.ascent = 1 - 2*ascent\n self.smooth = smooth\n self.print = print\n self.k = 1\n self.gamma = .0\n self.lamb = 1.\n self.q = .0\n self.L = L\n self.U = U\n self.gtol = gtol\n self.z_ = np.zeros(np.shape(x0))\n\n def __call__(self):\n sample = self.sampler(1)\n self.grads.append(self.grad(self.x[-1], sample[0]))\n z = self.x[-1] - self.step/(self.k)**.5*self.grads[-1] * self.ascent\n if ((z + self.gamma*(z-self.z_) - self.x[-1]) @\n self.grads[-1]*self.ascent) > 0:\n self.lamb = 1.0\n self.gamma = 0.0\n x_ = bounds(z + self.gamma*(z-self.z_), self.L, self.U)\n self.x.append(x_)\n self.z_ = np.array(z)\n lamb = (self.q-self.lamb**2)/2 \\\n + np.sqrt(self.q**2 - 2*self.q*self.lamb**2\n + self.lamb**4 + 4*self.lamb**2)/2\n self.gamma = self.lamb*(1-self.lamb)/(self.lamb**2+lamb)\n self.lamb = np.array(lamb)\n self.k += 1\n self.pr_update()\n if self.print: print(f'x:{self.x[-1]}, averaged x: {self.x_pr[-1]}'\n f'grad norm:{np.linalg.norm(self.grads[-1])}')\n return\n\n def run(self):\n k = 0\n g_norm = self.gtol*2\n while g_norm >= self.gtol and (k < self.iters):\n k += 1\n self()\n g_norm = np.linalg.norm(self.grads[-1])\n\n def pr_update(self):\n '''Polyak--Ruppert averaging'''\n # weight = 1/(self.k/2)**.5\n # weight_ = np.sum([1/(k_)**.5 for k_ in range(1,int(self.k/2 - 1))])\n # weights = [1/(k_)**.5 for k_ in range(1,int(self.k)+1)]\n # x_ = [x*w for x,w in zip(self.x, weights)]\n # x_pr = np.sum(x_, axis=0)/np.sum(weights)\n beta = self.smooth\n self.x_ = self.x_*beta + self.x[-1]*(1-beta)\n self.x_pr.append(self.x_/(1-beta**self.k))\n\n @staticmethod\n def bounds(x, L, U):\n x = np.maximum(x, L)\n x = np.minimum(x, U)\n return x\n\n\n########################################################################################################################\n########################################################################################################################\n# Heuristic #\n########################################################################################################################\n########################################################################################################################\n\nclass GeneticAlgorithm:\n\n def __init__(self, opt_object=None, args=None):\n self.opt_object = opt_object\n self.args = args\n\n def individual(self, number_of_genes, upper_limit, lower_limit):\n individual = [round(rnd() * (upper_limit - lower_limit) + lower_limit, 1) for x in range(number_of_genes)]\n\n return individual\n\n def population(self, number_of_individuals, number_of_genes, upper_limit, lower_limit):\n return [self.individual(number_of_genes, upper_limit, lower_limit) for x in range(number_of_individuals)]\n\n def fitness_calculation(self, indiv):\n ndof = building[\"ndof\"]\n size_col = []\n for i in range(ndof):\n size_col.append(indiv[i])\n\n size_col = np.array(size_col)\n fitness_value = self.opt_object.objective_function(size_col=size_col, args=self.args)\n\n return fitness_value\n\n def roulette(self,cum_sum, chance):\n veriable = list(cum_sum.copy())\n veriable.append(chance)\n veriable = sorted(veriable)\n return veriable.index(chance)\n\n def selection(self,generation, method='Fittest Half'):\n generation['Normalized Fitness'] = \\\n sorted([generation['Fitness'][x] / sum(generation['Fitness'])\n for x in range(len(generation['Fitness']))], reverse=True)\n generation['Cumulative Sum'] = np.array(\n generation['Normalized Fitness']).cumsum()\n if method == 'Roulette Wheel':\n selected = []\n for x in range(len(generation['Individuals']) // 2):\n selected.append(self.roulette(generation\n ['Cumulative Sum'], rnd()))\n while len(set(selected)) != len(selected):\n selected[x] = \\\n (self.roulette(generation['Cumulative Sum'], rnd()))\n selected = {'Individuals':\n [generation['Individuals'][int(selected[x])]\n for x in range(len(generation['Individuals']) // 2)]\n , 'Fitness': [generation['Fitness'][int(selected[x])]\n for x in range(\n len(generation['Individuals']) // 2)]}\n elif method == 'Fittest Half':\n selected_individuals = [generation['Individuals'][-x - 1]\n for x in range(int(len(generation['Individuals']) // 2))]\n selected_fitnesses = [generation['Fitness'][-x - 1]\n for x in range(int(len(generation['Individuals']) // 2))]\n selected = {'Individuals': selected_individuals,\n 'Fitness': selected_fitnesses}\n elif method == 'Random':\n selected_individuals = \\\n [generation['Individuals']\n [randint(1, len(generation['Fitness']))]\n for x in range(int(len(generation['Individuals']) // 2))]\n selected_fitnesses = [generation['Fitness'][-x - 1]\n for x in range(int(len(generation['Individuals']) // 2))]\n selected = {'Individuals': selected_individuals,\n 'Fitness': selected_fitnesses}\n return selected\n\n def pairing(self, elit, selected, method='Fittest'):\n individuals = [elit['Individuals']] + selected['Individuals']\n fitness = [elit['Fitness']] + selected['Fitness']\n if method == 'Fittest':\n parents = [[individuals[x], individuals[x + 1]]\n for x in range(len(individuals) // 2)]\n if method == 'Random':\n parents = []\n for x in range(len(individuals) // 2):\n parents.append(\n [individuals[randint(0, (len(individuals) - 1))],\n individuals[randint(0, (len(individuals) - 1))]])\n while parents[x][0] == parents[x][1]:\n parents[x][1] = individuals[\n randint(0, (len(individuals) - 1))]\n if method == 'Weighted Random':\n normalized_fitness = sorted(\n [fitness[x] / sum(fitness)\n for x in range(len(individuals) // 2)], reverse=True)\n cummulitive_sum = np.array(normalized_fitness).cumsum()\n parents = []\n for x in range(len(individuals) // 2):\n parents.append(\n [individuals[self.roulette(cummulitive_sum, rnd())],\n individuals[self.roulette(cummulitive_sum, rnd())]])\n while parents[x][0] == parents[x][1]:\n parents[x][1] = individuals[\n self.roulette(cummulitive_sum, rnd())]\n return parents\n\n def mating(self, parents, method='Single Point'):\n if method == 'Single Point':\n pivot_point = randint(1, len(parents[0]))\n offsprings = [parents[0] \\\n [0:pivot_point] + parents[1][pivot_point:]]\n offsprings.append(parents[1]\n [0:pivot_point] + parents[0][pivot_point:])\n if method == 'Two Pionts':\n pivot_point_1 = randint(1, len(parents[0] - 1))\n pivot_point_2 = randint(1, len(parents[0]))\n while pivot_point_2 < pivot_point_1:\n pivot_point_2 = randint(1, len(parents[0]))\n offsprings = [parents[0][0:pivot_point_1] +\n parents[1][pivot_point_1:pivot_point_2] +\n [parents[0][pivot_point_2:]]]\n offsprings.append([parents[1][0:pivot_point_1] +\n parents[0][pivot_point_1:pivot_point_2] +\n [parents[1][pivot_point_2:]]])\n return offsprings\n\n def mutation(self, individual, upper_limit, lower_limit, muatation_rate=2,\n method='Reset', standard_deviation=0.001):\n gene = [randint(0, 7)]\n for x in range(muatation_rate - 1):\n gene.append(randint(0, 7))\n while len(set(gene)) < len(gene):\n gene[x] = randint(0, 7)\n mutated_individual = individual.copy()\n if method == 'Gauss':\n for x in range(muatation_rate):\n mutated_individual[x] = \\\n round(individual[x] + gauss(0, standard_deviation), 1)\n if method == 'Reset':\n for x in range(muatation_rate):\n mutated_individual[x] = round(rnd() * \\\n (upper_limit - lower_limit) + lower_limit, 1)\n return mutated_individual\n\n def first_generation(self, pop):\n fitness = [self.fitness_calculation(pop[x]) for x in range(len(pop))]\n sorted_fitness = sorted([[pop[x], fitness[x]] for x in range(len(pop))], key=lambda x: x[1])\n population = [sorted_fitness[x][0] for x in range(len(sorted_fitness))]\n fitness = [sorted_fitness[x][1] for x in range(len(sorted_fitness))]\n return {'Individuals': population, 'Fitness': sorted(fitness)}\n\n def next_generation(self, gen, upper_limit, lower_limit):\n elit = {}\n next_gen = {}\n elit['Individuals'] = gen['Individuals'].pop(-1)\n elit['Fitness'] = gen['Fitness'].pop(-1)\n selected = self.selection(gen)\n parents = self.pairing(elit, selected)\n offsprings = [[[self.mating(parents[x])\n for x in range(len(parents))]\n [y][z] for z in range(2)]\n for y in range(len(parents))]\n offsprings1 = [offsprings[x][0]\n for x in range(len(parents))]\n offsprings2 = [offsprings[x][1]\n for x in range(len(parents))]\n unmutated = selected['Individuals'] + offsprings1 + offsprings2\n mutated = [self.mutation(unmutated[x], upper_limit, lower_limit)\n for x in range(len(gen['Individuals']))]\n unsorted_individuals = mutated + [elit['Individuals']]\n unsorted_next_gen = \\\n [self.fitness_calculation(mutated[x]) for x in range(len(mutated))]\n unsorted_fitness = [unsorted_next_gen[x] for x in range(len(gen['Fitness']))] + [elit['Fitness']]\n sorted_next_gen = \\\n sorted([[unsorted_individuals[x], unsorted_fitness[x]] for x in range(len(unsorted_individuals))],\n key=lambda x: x[1])\n next_gen['Individuals'] = [sorted_next_gen[x][0]\n for x in range(len(sorted_next_gen))]\n next_gen['Fitness'] = [sorted_next_gen[x][1]\n for x in range(len(sorted_next_gen))]\n gen['Individuals'].append(elit['Individuals'])\n gen['Fitness'].append(elit['Fitness'])\n return next_gen\n\n def fitness_similarity_chech(self,max_fitness, number_of_similarity):\n result = False\n similarity = 0\n for n in range(len(max_fitness) - 1):\n if max_fitness[n] == max_fitness[n + 1]:\n similarity += 1\n else:\n similarity = 0\n if similarity == number_of_similarity - 1:\n result = True\n return result\n\n\n","sub_path":"Optimization.py","file_name":"Optimization.py","file_ext":"py","file_size_in_byte":13388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"638585224","text":"import numpy as np\n\nnp.array(['red', 'green', 'blue', 'red'])\n\nm = np.zeros((4,3))\nprint(m)\n\nm[0,0] = 1\nm[1,2] = 1\nm[2,1] = 1\nm[3,0] = 1\nprint(m)","sub_path":"zadanie_3.py","file_name":"zadanie_3.py","file_ext":"py","file_size_in_byte":145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"160422502","text":"from src.auction.dominio import Users, Bid, Auction\n\nauction = Auction('Car')\n\nfirstUser = Users('conrado')\nsecondUser = Users('annylys')\n\nbid_firstUser = Bid(firstUser, 100.0)\nbid_secondUser = Bid(secondUser, 150.0)\n\nauction.propoe(bid_firstUser)\nauction.propoe(bid_secondUser)\n\nfor bid in auction.bid:\n print(f'O Usuário: \"{bid.user.name}\" deu um lance de: .\"{bid.value}\"')\n\nprint(f'O menor lance foi de: \"{auction.lowest_bid}\" e o maior lance foi de: \"{auction.higher_bid}\".')\n\n\n","sub_path":"TDD-Python/src/auction/principal.py","file_name":"principal.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"122769555","text":"\"\"\"\n@author: \"Dickson Owuor\"\n@credits: \"Anne Laurent, Joseph Orero\"\n@license: \"MIT\"\n@version: \"1.0\"\n@email: \"owuordickson@gmail.com\"\n\nThis code approximates a time period (member) using a fuzzy triangular membership function\n\n\"\"\"\n\nimport skfuzzy as fuzzy\nimport numpy as np\n\n\ndef init_fuzzy_support(test_members, all_members, minsup):\n boundaries, extremes = get_membership_boundaries(all_members)\n value, sup = approximate_fuzzy_support(minsup, test_members, boundaries, extremes)\n return value, sup\n\n\ndef get_membership_boundaries(members):\n # 1. Sort the members in ascending order\n members.sort()\n\n # 2. Get the boundaries of membership function\n min = np.min(members)\n q_1 = np.percentile(members, 25) # Quartile 1\n med = np.percentile(members, 50)\n q_3 = np.percentile(members, 75)\n max = np.max(members)\n boundaries = [q_1, med, q_3]\n extremes = [min, max]\n\n return boundaries,extremes\n\n\ndef approximate_fuzzy_support(minsup, timelags, orig_boundaries, extremes):\n slice_gap = (0.1*int(orig_boundaries[1]))\n sup = sup1 = 0\n slide_left = slide_right = expand = False\n sample = np.percentile(timelags, 50)\n\n a = orig_boundaries[0]\n b = b1 = orig_boundaries[1]\n c = orig_boundaries[2]\n min_a = extremes[0]\n max_c = extremes[1]\n boundaries = np.array(orig_boundaries)\n time_lags = np.array(timelags)\n\n while sup <= minsup:\n\n if sup > sup1:\n sup1 = sup\n b1 = b\n\n # Calculate membership of frequent path\n memberships = fuzzy.membership.trimf(time_lags, boundaries)\n\n # Calculate support\n sup = calculate_support(memberships)\n\n if sup >= minsup:\n value = get_time_format(b)\n return value, sup\n else:\n if not slide_left:\n # 7. Slide to the left to change boundaries\n # if extreme is reached - then slide right\n if sample <= b:\n # if min_a >= b:\n a = a - slice_gap\n b = b - slice_gap\n c = c - slice_gap\n boundaries = np.array([a, b, c])\n else:\n slide_left = True\n elif not slide_right:\n # 8. Slide to the right to change boundaries\n # if extreme is reached - then slide right\n if sample >= b:\n #if max_c <= b:\n a = a + slice_gap\n b = b + slice_gap\n c = c + slice_gap\n boundaries = np.array([a, b, c])\n else:\n slide_right = True\n elif not expand:\n # 9. Expand quartiles and repeat 5. and 6.\n a = min_a\n b = orig_boundaries[1]\n c = max_c\n boundaries = np.array([a, b, c])\n slide_left = slide_right = False\n expand = True\n else:\n value = get_time_format(b1)\n return value, False\n\n\ndef calculate_support(memberships):\n support = 0\n if len(memberships) > 0:\n sup_count = 0\n total = len(memberships)\n for member in memberships:\n # if float(member) > 0.5:\n if float(member) > 0:\n sup_count = sup_count + 1\n support = sup_count / total\n return support\n\n\ndef get_time_format(value):\n if value < 0:\n sign = \"-\"\n else:\n sign = \"+\"\n p_value, p_type = round_time(abs(value))\n p_format = [sign,p_value,p_type]\n return p_format\n\n\ndef round_time(seconds):\n years = seconds/3.154e+7\n months = seconds/2.628e+6\n weeks = seconds/604800\n days = seconds/86400\n hours = seconds/3600\n minutes = seconds/60\n\n if int(years) <= 0:\n if int(months) <= 0:\n if int(weeks) <= 0:\n if int(days) <= 0:\n if int(hours) <= 0:\n if int(minutes) <= 0:\n return seconds, \"seconds\"\n else:\n return minutes, \"minutes\"\n else:\n return hours, \"hours\"\n else:\n return days, \"days\"\n else:\n return weeks,\"weeks\"\n else:\n return months, \"months\"\n else:\n return years, \"years\"\n","sub_path":"algorithms/fuzzy_temporal.py","file_name":"fuzzy_temporal.py","file_ext":"py","file_size_in_byte":4417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"601664905","text":"def pattern():\r\n n = int(input(\"Enter the Range\"))\r\n listp = [1]\r\n print(listp) \r\n for i in range(2,n+1):\r\n listp = [1]\r\n for j in range(2,i):\r\n listp.append(j)\r\n for k in range(i,0,-1):\r\n listp.append(k)\r\n print(listp)\r\npattern()","sub_path":"TASK/PascalList.py","file_name":"PascalList.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"586186951","text":"import config\nimport requests\nimport re\nimport json\nimport traceback\n\n\ndef spider(city, job):\n # ################得到页数\n url_page = 'https://www.lagou.com/jobs/list_' + job + '?px=default&city=' + city + '#filterBox'\n html = requests.get(url_page, headers=config.headers).text\n try:\n pages = re.findall('totalNum\">(.*?)<', html, re.S)[0]\n except Exception as e:\n traceback.print_exc()\n pages = 0\n print(pages)\n\n # 最终的完整数据\n final_data = []\n\n # 对每一页进行解析\n for i in range(int(pages)):\n res = get_one_page(city, job, i + 1)\n if res is None:\n continue\n final_data.extend(res)\n\n return final_data\n\n\n# 得到一页的数据\ndef get_one_page(city, job, page):\n # ################得到json数据\n # url模板 https://www.lagou.com/jobs/positionAjax.json?px=default&city=北京&needAddtionalResult=false\n # post数据\n # {\n # first: false,\n # pn: 1, 页码\n # kd: Java 工作\n # }\n\n # 构造post数据\n post_data = {\n 'first': 'false',\n 'pn': str(page),\n 'kd': job\n }\n # 打开网页,得到json数据\n url = 'https://www.lagou.com/jobs/positionAjax.json?px=default&city=' + city + '&needAddtionalResult=false'\n html = requests.post(url, data=post_data, headers=config.headers, timeout=config.time_out).text\n if len(html) < 100:\n return None\n\n # 解析json\n json_data = json.loads(html)\n\n # 最终数据的列表\n res_data = json_data['content']['positionResult']['result']\n\n # 清洗后的数据\n _data = []\n for each in res_data:\n job_url = 'https://www.lagou.com/jobs/' + str(each['positionId']) + '.html'\n item = {'posname': each['positionName'], 'company': each['companyShortName'], 'salary': each['salary'],\n 'workYear': each['workYear'], 'education': each['education'], 'financeStage': each['financeStage'],\n 'positionAdvantage': each['positionAdvantage'], 'industryField': each['industryField'],\n 'job_url': job_url}\n # 尝试解析dict,如果失败,略过\n try:\n item = str(item).replace(\"'\", '\"')\n item = json.loads(item)\n except Exception as e:\n print(each['companyShortName'] + \"parse error\")\n traceback.print_exc()\n continue\n _data.append(item)\n\n return _data","sub_path":"spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"554021529","text":"import os\r\nimport sys\r\nfrom pathlib import Path\r\n\r\n\r\n# Function to rename multiple files\r\ndef main():\r\n direc = Path(sys.argv[1])\r\n file_extsn = sys.argv[2]\r\n for filename in os.listdir(direc):\r\n dst = Path(filename).stem + file_extsn\r\n src = os.path.join(direc, filename)\r\n dst = os.path.join(direc, dst)\r\n if not os.path.exists(dst):\r\n # rename() function will\r\n # rename all the files\r\n os.rename(src, dst)\r\n else:\r\n continue\r\n\r\n\r\n# Driver Code\r\nif __name__ == '__main__':\r\n # Calling main() function\r\n main()\r\n","sub_path":"file-extension-changer.py","file_name":"file-extension-changer.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"420289721","text":"from __future__ import print_function\n\nfrom burlap.constants import *\nfrom burlap import ServiceSatchel\n\nclass NetworkManagerSatchel(ServiceSatchel):\n \"\"\"\n Configures Network Manager for automatically controlling network interfaces.\n \n https://fedoraproject.org/wiki/Networking/CLI#Wifi\n \"\"\"\n \n name = 'nm'\n \n ## Service options.\n \n #ignore_errors = True\n \n # {action: {os_version_distro: command}}\n# commands = env.networkmanager_service_commands\n \n tasks = (\n 'configure',\n 'add_wifi_connection',\n 'remove_connection',\n 'dev_status',\n 'dev_wifi_list',\n )\n \n required_system_packages = {\n UBUNTU: ['network-manager', 'cron'],\n DEBIAN: ['network-manager', 'cron'],\n }\n \n templates = (\n 'check_networkmanager.sh',\n 'etc_crond_check_networkmanager',\n )\n \n def set_defaults(self):\n self.env.check_enabled = False\n \n self.env.service_commands = {\n START:{\n UBUNTU: 'service network-manager start',\n DEBIAN: 'service network-manager start',\n },\n STOP:{\n UBUNTU: 'service network-manager stop',\n DEBIAN: 'service network-manager stop',\n },\n DISABLE:{\n UBUNTU: 'chkconfig network-manager off',\n DEBIAN: 'update-rc.d network-manager disable',\n #(UBUNTU, '14.04'): 'update-rc.d -f network-manager remove',\n (UBUNTU, '14.04'): 'echo \"manual\" | sudo tee /etc/init/network-manager.override',\n },\n ENABLE:{\n DEBIAN: 'update-rc.d network-manager enable',\n UBUNTU: 'chkconfig network-manager on',\n (UBUNTU, '14.04'): 'rm /etc/init/network-manager.override || true',\n },\n RESTART:{\n UBUNTU: 'service network-manager restart',\n DEBIAN: 'service network-manager restart',\n },\n STATUS:{\n UBUNTU: 'service network-manager status',\n DEBIAN: 'service network-manager status',\n },\n }\n \n self.env.check_script_path = '/usr/local/bin/check_networkmanager.sh'\n self.env.cron_script_path = '/etc/cron.d/check_networkmanager'\n self.env.cron_perms = '600'\n \n def add_wifi_connection(self, ssid, passphrase=None):\n r = self.local_renderer\n r.env.ssid = ssid = ssid\n r.env.passphrase = passphrase\n r.sudo('nmcli device wifi connect \"{ssid}\" password \"{passphrase}\"')\n \n def remove_connection(self, ssid):\n r = self.local_renderer\n r.env.ssid = ssid = ssid\n #r.sudo(\"nmcli connection delete `nmcli --fields NAME,UUID con list | grep -i {ssid} | awk '{print $2}'`\")\n r.sudo(\"nmcli connection delete id {ssid}\")\n \n def dev_status(self):\n r = self.local_renderer\n r.sudo('nmcli device status')\n \n def dev_wifi_list(self):\n r = self.local_renderer\n r.sudo('nmcli device wifi list')\n \n def configure(self):\n \n if self.env.enabled:\n self.install_packages()\n \n # Clear the /etc/network/interfaces so NM will control all interfaces.\n if not self.files.exists('/etc/network/interfaces'):\n self.sudo('mv /etc/network/interfaces /etc/network/interfaces.bak')\n self.sudo('rm -f /etc/network/interfaces')\n self.sudo('touch /etc/network/interfaces')\n self.sudo('echo -e \"auto lo\\\\niface lo inet loopback\" > /etc/network/interfaces')\n \n self.enable()\n self.restart()\n else:\n self.disable()\n self.stop()\n \n if self.env.check_enabled:\n # Installs a crontab to check Network-Manager every ten minutes\n # and restart it if theres' no Internet connection.\n self.install_script(\n local_path='%s/check_networkmanager.sh' % self.name,\n remote_path=self.lenv.check_script_path)\n remote_path = self.put_or_dryrun(\n local_path=self.find_template('%s/etc_crond_check_networkmanager' % self.name),\n remote_path=self.env.cron_script_path, use_sudo=True)[0]\n self.sudo_or_dryrun('chown root:root %s' % remote_path)#env.put_remote_path)\n # Must be 600, otherwise gives INSECURE MODE error.\n # http://unix.stackexchange.com/questions/91202/cron-does-not-print-to-syslog\n self.sudo_or_dryrun('chmod %s %s' % (self.env.cron_perms, remote_path))#env.put_remote_path)\n self.sudo_or_dryrun('service cron restart')\n else:\n self.sudo_or_dryrun('rm -f {cron_script_path}'.format(**self.lenv))\n self.sudo_or_dryrun('service cron restart')\n \n configure.deploy_before = ['packager', 'user', 'cron']\n\nNetworkManagerSatchel()\n","sub_path":"burlap/networkmanager.py","file_name":"networkmanager.py","file_ext":"py","file_size_in_byte":4999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"499760372","text":"from collections import OrderedDict\nimport six\n\nfrom fitsblender import blendheaders\n\nfrom .. import datamodels\nfrom ..datamodels import schema\nfrom ..datamodels import fits_support\n\nimport logging\nlog = logging.getLogger(__name__)\nlog.setLevel(logging.DEBUG)\n\n\ndef blendfitsdata(input_list, output_model):\n \"\"\"\n Primary interface for JWST pipeline use of fitsblender.blendheaders\n\n This function will update the output_model datamodel with the blended metadata\n from the list of FITS objects generated from the input_list of filenames.\n \"\"\"\n new_hdrs, new_table = blendheaders.get_blended_headers(input_list)\n \n # Now merge the keyword values from new_hdrs into the metatdata for the\n # output datamodel\n # \n # start by building dict which maps all FITS keywords in schema to their \n # attribute in the schema\n fits_dict = schema.build_fits_dict(output_model.schema)\n # Now assign values from new_hdrs to output_model.meta using fits_dict map\n for hdr in new_hdrs:\n for kw in hdr:\n if kw in fits_dict:\n output_model[fits_dict[kw]] = hdr[kw]\n\n # Now, append HDRTAB as new element in datamodel\n new_schema = build_tab_schema(new_table)\n output_model.add_schema_entry('hdrtab', new_schema)\n output_model.hdrtab = fits_support.from_fits_hdu(new_table, new_schema)\n \n\ndef blendmetadata(input_models, output_model):\n final_rules = build_meta_rules(input_models)\n\n # Apply rules to each set of input headers\n new_headers = []\n i=0\n # apply rules to PRIMARY headers separately, since there is only\n # 1 PRIMARY header per image, yet many extension headers\n newphdr,newtab = final_rules.apply(phdrlist)\n final_rules.add_rules_kws(newphdr) # Adds HISTORY comments on rules used\n new_headers.append(newphdr)\n for hdrs in hdrlist[1:]:\n newhdr, newtab = final_rules.apply(hdrs)\n new_headers.append(newhdr)\n\n # create list of combined PRIMARY/SCI headers for use in creating\n # the new table extensions\n tabhdrs = []\n for phdr, scihdr in zip(hdrlist[0], hdrlist[1]):\n tabhdrs.append(cat_headers(phdr, scihdr))\n # Create extension table from list of all combined PRI/SCI headers\n tabhdr, newtab = final_rules.apply(tabhdrs)\n\n # Now merge the keyword values from new_hdrs into the metatdata for the\n # output datamodel\n #\n # start by building dict which maps all FITS keywords in schema to their\n # attribute in the schema\n fits_dict = schema.build_fits_dict(output_model.schema)\n # Now assign values from new_hdrs to output_model.meta using fits_dict map\n for hdr in new_hdrs:\n for kw in hdr:\n if kw in fits_dict:\n output_model[fits_dict[kw]] = hdr[kw]\n\n # Now, append HDRTAB as new element in datamodel\n new_schema = build_tab_schema(new_table)\n output_model.add_schema_entry('hdrtab', new_schema)\n output_model.hdrtab = fits_support.from_fits_hdu(new_table, new_schema)\n\n\ndef build_meta_rules(input_models, rules_file=None):\n # Determine what blending rules need to be merged to create the final\n # blended headers. There will be a separate set of rules for each\n # instrument, and all rules get merged into a composite set of rules that\n # get applied to all input headers regardless of instrument.\n #\n # Instrument identification will be extracted from the INSTRUME keyword\n # from the PRIMARY header of each input\n\n icache = {}\n for model in input_models:\n inst = model.meta.instrument.name.lower()\n tel = model.meta.telescope.lower()\n if inst not in icache:\n # initialize the appropriate class for this data's instrument\n inst_class = blendheaders.KeywordRules(inst, telescope=tel,\n rules_file=rules_file)\n log.debug(\"Found blendheaders RULEFILE for {}/{} of: {}\".format(\n tel, inst, inst_class.rules_file))\n # Interpret rules for this class based on image that\n # initialized this instrument's rules\n inst_class.interpret_rules(model.meta)\n # Now add this interpreted class to the cache\n icache[inst] = inst_class\n\n # Create final merged set of rules\n final_rules = None\n for inst in icache:\n if final_rules is None:\n final_rules = icache[inst]\n else:\n final_rules.merge(icache[inst])\n\n return final_rules\n\n\ndef build_tab_schema(new_table):\n \"\"\"\n Return new schema definition that describes the input table.\n \n \"\"\"\n hdrtab = OrderedDict()\n hdrtab['title']='Combined header table'\n hdrtab['fits_hdu'] = 'HDRTAB'\n datatype = []\n for col in new_table.columns:\n cname = col.name\n ctype = convert_dtype(str(col.dtype))\n c = OrderedDict()\n c['name'] = cname\n c['datatype'] = ctype\n datatype.append(c)\n hdrtab['datatype']=datatype\n \n return hdrtab\n\n\ndef convert_dtype(value):\n \"\"\"\n Convert numarray column dtype into YAML-compatible format description\n \"\"\"\n if 'S' in value:\n # working with a string description\n str_len = int(value[value.find('S')+1:])\n new_dtype = [u'ascii', str_len] ## CHANGED\n else:\n new_dtype = unicode(str(value))\n\n return new_dtype\n","sub_path":"jwst/resample/blend.py","file_name":"blend.py","file_ext":"py","file_size_in_byte":5316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"310630338","text":"import unittest\n\ndef quick_sort(arr, left=0, right=None):\n\tif right is None:\n\t\tright = len(arr) - 1\n\tindex = partition(arr, left, right)\n\tif left < index-1:\n\t\tquick_sort(arr, left, index-1)\n\tif right > index:\n\t\tquick_sort(arr, index, right)\n\ndef partition(arr, left, right):\n\tpivot = arr[(left + right) // 2]\n\twhile left <= right:\n\t\twhile arr[left] < pivot:\n\t\t\tleft += 1\n\t\twhile arr[right] > pivot:\n\t\t\tright -= 1\n\t\tif left <= right:\n\t\t\ttemp = arr[left]\n\t\t\tarr[left] = arr[right]\n\t\t\tarr[right] = temp\n\t\t\tleft += 1\n\t\t\tright -= 1\n\treturn left\n\n\nclass Test(unittest.TestCase):\n\tdata = list('helloworld')\t\n\t\n\tdef test_quick_sort(self):\t\t\n\t\tsorted_data = sorted(self.data)\n\t\tquick_sort(self.data)\n\t\tself.assertEqual(self.data, sorted_data)\n\n\nif __name__ == \"__main__\":\n\tunittest.main()","sub_path":"CtCI/Chapter 10/quick_sort.py","file_name":"quick_sort.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"380245930","text":"#-*- coding:utf-8 -*-\r\nfrom threading import Lock, Condition\r\n\r\nfrom connection_wrapper import Connection\r\nfrom gba.config import DjangoSettings\r\n \r\nclass ConnectionPool(object):\r\n \"\"\"线程安全的数据库连接池\"\"\"\r\n MAX_COUNT = 20 # 最大同时连接数\r\n _connections = []\r\n _hold_count = 20 # 连接允许的持有数\r\n _conn_locker = Lock()\r\n _waiter = Condition(Lock())\r\n _count = 0 # 连接请求计数\r\n \r\n def __init__(self):\r\n raise Exception(\"only class members can be called\")\r\n \r\n @classmethod\r\n def acquire(cls, wait_timeout = 4):\r\n \"\"\"请求数据库连接\"\"\"\r\n cls._wait() # 检测是否已达到最大连接数,若达到,则等待直到有可用的连接为止\r\n cls._conn_locker.acquire()\r\n try:\r\n if cls._connections:\r\n conn = cls._connections.pop(0)\r\n else:\r\n conn = Connection(\r\n user = DjangoSettings.DATABASE_USER,\r\n db = DjangoSettings.DATABASE_NAME,\r\n passwd = DjangoSettings.DATABASE_PASSWORD,\r\n host = DjangoSettings.DATABASE_HOST,\r\n port = DjangoSettings.DATABASE_PORT,\r\n charset = \"utf8\",\r\n unix_socket = DjangoSettings.DATABASE_HOST,\r\n init_command = \"set wait_timeout = %s;\" % wait_timeout\r\n )\r\n return conn\r\n finally:\r\n cls._conn_locker.release()\r\n \r\n @classmethod\r\n def release(cls, conn):\r\n if not conn:\r\n raise Exception(\"conn is required\")\r\n \r\n cls._conn_locker.acquire()\r\n try:\r\n if len(cls._connections) >= cls._hold_count:\r\n conn.close()\r\n else:\r\n cls._connections.insert(0, conn)\r\n finally:\r\n cls._conn_locker.release()\r\n cls._notify()\r\n \r\n @classmethod\r\n def cursor(cls, wait_timeout = 4):\r\n \"\"\"获取当前可用的游标\r\n \r\n 使用完务必调用close(),以释放数据库连接\r\n \"\"\"\r\n conn = cls.acquire(wait_timeout)\r\n try:\r\n c = conn.cursor()\r\n c._add2pool(cls)\r\n except:\r\n conn.close()\r\n cls.release(conn)\r\n raise\r\n return c\r\n \r\n @classmethod\r\n def close(cls):\r\n \"\"\"关闭所有连接\"\"\"\r\n cls._conn_locker.acquire()\r\n try:\r\n while cls._connections:\r\n conn = cls._connections.pop(0)\r\n conn.close()\r\n cls._notify()\r\n finally:\r\n cls._conn_locker.release()\r\n\r\n @classmethod\r\n def _wait(cls):\r\n if cls.MAX_COUNT > 0:\r\n cls._waiter.acquire()\r\n cls._count += 1 # _count 最大值为 MAX_COUNT + 1\r\n if cls._count > cls.MAX_COUNT:\r\n cls._waiter.wait()\r\n cls._waiter.release()\r\n \r\n @classmethod\r\n def _notify(cls):\r\n if cls.MAX_COUNT > 0:\r\n cls._waiter.acquire()\r\n if cls._count > 0:\r\n cls._count -= 1\r\n cls._waiter.notify()\r\n cls._waiter.release()","sub_path":"gba/gba/common/db/connection_pool.py","file_name":"connection_pool.py","file_ext":"py","file_size_in_byte":3353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"407270580","text":"import copy\nimport os\nfrom collections import OrderedDict, defaultdict\nfrom contextlib import ExitStack\nfrom functools import wraps\nfrom typing import Union, Tuple, List, Optional, Iterator\n\nfrom ..cli.parser import set_router_parser, set_indexer_parser, \\\n set_frontend_parser, set_preprocessor_parser, \\\n set_encoder_parser, set_client_cli_parser\nfrom ..client.cli import CLIClient\nfrom ..helper import set_logger\nfrom ..service.base import SocketType, BaseService, BetterEnum, ServiceManager\nfrom ..service.encoder import EncoderService\nfrom ..service.frontend import FrontendService\nfrom ..service.indexer import IndexerService\nfrom ..service.preprocessor import PreprocessorService\nfrom ..service.router import RouterService\n\n\nclass Service(BetterEnum):\n Frontend = 0\n Encoder = 1\n Router = 2\n Indexer = 3\n Preprocessor = 4\n\n\nclass FlowImcompleteError(ValueError):\n \"\"\"Exception when the flow missing some important component to run\"\"\"\n\n\nclass FlowTopologyError(ValueError):\n \"\"\"Exception when the topology is ambiguous\"\"\"\n\n\nclass FlowBuildLevelMismatch(ValueError):\n \"\"\"Exception when required level is higher than the current build level\"\"\"\n\n\ndef _build_level(required_level: 'Flow.BuildLevel'):\n def __build_level(func):\n @wraps(func)\n def arg_wrapper(self, *args, **kwargs):\n if hasattr(self, '_build_level'):\n if self._build_level.value >= required_level.value:\n return func(self, *args, **kwargs)\n else:\n raise FlowBuildLevelMismatch(\n 'build_level check failed for %r, required level: %s, actual level: %s' % (\n func, required_level, self._build_level))\n else:\n raise AttributeError('%r has no attribute \"_build_level\"' % self)\n\n return arg_wrapper\n\n return __build_level\n\n\nclass Flow:\n \"\"\"\n GNES Flow: an intuitive way to build workflow for GNES.\n\n You can use :py:meth:`.add()` then :py:meth:`.build()` to customize your own workflow.\n For example:\n\n .. highlight:: python\n .. code-block:: python\n\n from gnes.flow import Flow, Service as gfs\n\n f = (Flow(check_version=False, route_table=True)\n .add(gfs.Preprocessor, yaml_path='BasePreprocessor')\n .add(gfs.Encoder, yaml_path='BaseEncoder')\n .add(gfs.Router, yaml_path='BaseRouter'))\n\n with f.build(backend='thread') as flow:\n flow.index()\n ...\n\n You can also use the shortcuts, e.g. :py:meth:`add_encoder`, :py:meth:`add_preprocessor`.\n\n It is recommend to use flow in the context manner as showed above.\n\n Note the different default copy behaviors in :py:meth:`.add()` and :py:meth:`.build()`:\n :py:meth:`.add()` always copy the flow by default, whereas :py:meth:`.build()` modify the flow in place.\n You can change this behavior by giving an argument `copy_flow=False`.\n\n \"\"\"\n _supported_orch = {'swarm', 'k8s'}\n _service2parser = {\n Service.Encoder: set_encoder_parser,\n Service.Router: set_router_parser,\n Service.Indexer: set_indexer_parser,\n Service.Frontend: set_frontend_parser,\n Service.Preprocessor: set_preprocessor_parser,\n }\n _service2builder = {\n Service.Encoder: lambda x: ServiceManager(EncoderService, x),\n Service.Router: lambda x: ServiceManager(RouterService, x),\n Service.Indexer: lambda x: ServiceManager(IndexerService, x),\n Service.Preprocessor: lambda x: ServiceManager(PreprocessorService, x),\n Service.Frontend: FrontendService,\n }\n\n class BuildLevel(BetterEnum):\n EMPTY = 0\n GRAPH = 1\n RUNTIME = 2\n\n def __init__(self, with_frontend: bool = True, **kwargs):\n self.logger = set_logger(self.__class__.__name__)\n self._service_nodes = OrderedDict()\n self._service_edges = {}\n self._service_name_counter = {k: 0 for k in Flow._service2parser.keys()}\n self._service_contexts = []\n self._last_add_service = None\n self._common_kwargs = kwargs\n self._frontend = None\n self._client = None\n self._build_level = Flow.BuildLevel.EMPTY\n self._backend = None\n if with_frontend:\n self.add_frontend(copy_flow=False)\n else:\n self.logger.warning('with_frontend is set to False, you need to add_frontend() by yourself')\n\n @_build_level(BuildLevel.GRAPH)\n def to_yaml(self, orchestration: str) -> str:\n if orchestration not in Flow._supported_orch:\n raise TypeError(\n '%s is not valid type of orchestration, should be one of %s' % (orchestration, Flow._supported_orch))\n\n @staticmethod\n def from_yaml(orchestration: str) -> 'Flow':\n if orchestration not in Flow._supported_orch:\n raise TypeError(\n '%s is not valid type of orchestration, should be one of %s' % (orchestration, Flow._supported_orch))\n\n @_build_level(BuildLevel.GRAPH)\n def to_mermaid(self, left_right: bool = True):\n \"\"\"\n Output the mermaid graph for visualization\n\n :param left_right: render the flow in left-to-right manner, otherwise top-down manner.\n :return:\n \"\"\"\n mermaid_graph = OrderedDict()\n for k in self._service_nodes.keys():\n mermaid_graph[k] = []\n cls_dict = defaultdict(set)\n\n for k, ed_type in self._service_edges.items():\n start_node, end_node = k.split('-')\n s_service = self._service_nodes[start_node]['service']\n e_service = self._service_nodes[end_node]['service']\n cls_dict[s_service].add(start_node)\n cls_dict[e_service].add(end_node)\n p_s = '((%s))' if s_service == Service.Router else '(%s)'\n p_e = '((%s))' if e_service == Service.Router else '(%s)'\n mermaid_graph[start_node].append('\\t%s%s-- %s -->%s%s' % (\n start_node, p_s % start_node, ed_type,\n end_node, p_e % end_node))\n\n style = ['classDef FrontendCLS fill:#FFE0E0,stroke:#FFE0E0,stroke-width:1px;',\n 'classDef EncoderCLS fill:#FFDAAF,stroke:#FFDAAF,stroke-width:1px;',\n 'classDef IndexerCLS fill:#FFFBC1,stroke:#FFFBC1,stroke-width:1px;',\n 'classDef RouterCLS fill:#C9E8D2,stroke:#C9E8D2,stroke-width:1px;',\n 'classDef PreprocessorCLS fill:#CEEEEF,stroke:#CEEEEF,stroke-width:1px;']\n class_def = ['class %s %sCLS;' % (','.join(v), k) for k, v in cls_dict.items()]\n mermaid_str = '\\n'.join(\n ['graph %s' % ('LR' if left_right else 'TD')] + [ss for s in mermaid_graph.values() for ss in\n s] + style + class_def)\n\n return mermaid_str\n\n @_build_level(BuildLevel.GRAPH)\n def to_jpg(self, path: str = 'flow.jpg', left_right: bool = True):\n \"\"\"\n Rendering the current flow as a jpg image, this will call :py:meth:`to_mermaid` and it needs internet connection\n\n :param path: the file path of the image\n :param left_right: render the flow in left-to-right manner, otherwise top-down manner.\n :return:\n \"\"\"\n import base64\n from urllib.request import Request, urlopen\n mermaid_str = self.to_mermaid(left_right)\n encoded_str = base64.b64encode(bytes(mermaid_str, 'utf-8')).decode('utf-8')\n print('https://mermaidjs.github.io/mermaid-live-editor/#/view/%s' % encoded_str)\n self.logger.info('saving jpg...')\n req = Request('https://mermaid.ink/img/%s' % encoded_str, headers={'User-Agent': 'Mozilla/5.0'})\n with open(path, 'wb') as fp:\n fp.write(urlopen(req).read())\n self.logger.info('done')\n\n def train(self, bytes_gen: Iterator[bytes] = None, **kwargs):\n \"\"\"Do training on the current flow\n\n It will start a :py:class:`CLIClient` and call :py:func:`train`.\n\n :param bytes_gen: An iterator of bytes. If not given, then you have to specify it in `kwargs`.\n :param kwargs: accepts all keyword arguments of `gnes client` CLI\n \"\"\"\n self._call_client(bytes_gen, mode='train', **kwargs)\n\n def index(self, bytes_gen: Iterator[bytes] = None, **kwargs):\n \"\"\"Do indexing on the current flow\n\n It will start a :py:class:`CLIClient` and call :py:func:`index`.\n\n :param bytes_gen: An iterator of bytes. If not given, then you have to specify it in `kwargs`.\n :param kwargs: accepts all keyword arguments of `gnes client` CLI\n \"\"\"\n self._call_client(bytes_gen, mode='index', **kwargs)\n\n def query(self, bytes_gen: Iterator[bytes] = None, **kwargs):\n \"\"\"Do indexing on the current flow\n\n It will start a :py:class:`CLIClient` and call :py:func:`query`.\n\n :param bytes_gen: An iterator of bytes. If not given, then you have to specify it in `kwargs`.\n :param kwargs: accepts all keyword arguments of `gnes client` CLI\n \"\"\"\n self._call_client(bytes_gen, mode='query', **kwargs)\n\n @_build_level(BuildLevel.RUNTIME)\n def _call_client(self, bytes_gen: Iterator[bytes] = None, **kwargs):\n os.unsetenv('http_proxy')\n os.unsetenv('https_proxy')\n args, p_args = self._get_parsed_args(self, set_client_cli_parser, kwargs)\n p_args.grpc_port = self._service_nodes[self._frontend]['parsed_args'].grpc_port\n p_args.grpc_host = self._service_nodes[self._frontend]['parsed_args'].grpc_host\n c = CLIClient(p_args, start_at_init=False)\n if bytes_gen:\n c.bytes_generator = bytes_gen\n c.start()\n\n def add_frontend(self, *args, **kwargs) -> 'Flow':\n \"\"\"Add a frontend to the current flow, a shortcut of :py:meth:`add(Service.Frontend)`.\n Usually you dont need to call this function explicitly, a flow object contains a frontend service by default.\n This function is useful when you build a flow without the frontend and want to customize the frontend later.\n \"\"\"\n return self.add(Service.Frontend, *args, **kwargs)\n\n def add_encoder(self, *args, **kwargs) -> 'Flow':\n \"\"\"Add an encoder to the current flow, a shortcut of :py:meth:`add(Service.Encoder)`\"\"\"\n return self.add(Service.Encoder, *args, **kwargs)\n\n def add_indexer(self, *args, **kwargs) -> 'Flow':\n \"\"\"Add an indexer to the current flow, a shortcut of :py:meth:`add(Service.Indexer)`\"\"\"\n return self.add(Service.Indexer, *args, **kwargs)\n\n def add_preprocessor(self, *args, **kwargs) -> 'Flow':\n \"\"\"Add a preprocessor to the current flow, a shortcut of :py:meth:`add(Service.Preprocessor)`\"\"\"\n return self.add(Service.Preprocessor, *args, **kwargs)\n\n def add_router(self, *args, **kwargs) -> 'Flow':\n \"\"\"Add a router to the current flow, a shortcut of :py:meth:`add(Service.Router)`\"\"\"\n return self.add(Service.Router, *args, **kwargs)\n\n def add(self, service: 'Service',\n name: str = None,\n service_in: Union[str, Tuple[str], List[str], 'Service'] = None,\n service_out: Union[str, Tuple[str], List[str], 'Service'] = None,\n copy_flow: bool = True,\n **kwargs) -> 'Flow':\n \"\"\"\n Add a service to the current flow object and return the new modified flow object\n\n :param service: a 'Service' enum, possible choices: Encoder, Router, Preprocessor, Indexer, Frontend\n :param name: the name indentifier of the service, useful in 'service_in' and 'service_out'\n :param service_in: the name of the service(s) that this service receives data from.\n One can also use 'Service.Frontend' to indicate the connection with the frontend.\n :param service_out: the name of the service(s) that this service sends data to.\n One can also use 'Service.Frontend' to indicate the connection with the frontend.\n :param copy_flow: when set to true, then always copy the current flow and do the modification on top of it then return, otherwise, do in-line modification\n :param kwargs: other keyword-value arguments that the service CLI supports\n :return: a (new) flow object with modification\n \"\"\"\n\n op_flow = copy.deepcopy(self) if copy_flow else self\n\n if service not in Flow._service2parser:\n raise ValueError('service: %s is not supported, should be one of %s' % (service, Flow._service2parser))\n\n if name in op_flow._service_nodes:\n raise FlowTopologyError('name: %s is used in this Flow already!' % name)\n if not name:\n name = '%s%d' % (service, op_flow._service_name_counter[service])\n op_flow._service_name_counter[service] += 1\n if not name.isidentifier():\n raise ValueError('name: %s is invalid, please follow the python variable name conventions' % name)\n\n if service == Service.Frontend:\n if op_flow._frontend:\n raise FlowTopologyError('frontend is already in this Flow')\n op_flow._frontend = name\n\n service_in = op_flow._parse_service_endpoints(op_flow, name, service_in, connect_to_last_service=True)\n service_out = op_flow._parse_service_endpoints(op_flow, name, service_out, connect_to_last_service=False)\n\n args, p_args = op_flow._get_parsed_args(op_flow, Flow._service2parser[service], kwargs)\n\n op_flow._service_nodes[name] = {\n 'service': service,\n 'parsed_args': p_args,\n 'args': args,\n 'incomes': service_in,\n 'outgoings': service_out}\n\n # direct all income services' output to the current service\n for s in service_in:\n op_flow._service_nodes[s]['outgoings'].add(name)\n for s in service_out:\n op_flow._service_nodes[s]['incomes'].add(name)\n\n op_flow._last_add_service = name\n\n # graph is now changed so we need to\n # reset the build level to the lowest\n op_flow._build_level = Flow.BuildLevel.EMPTY\n\n return op_flow\n\n @staticmethod\n def _parse_service_endpoints(op_flow, cur_service_name, service_endpoint, connect_to_last_service=False):\n # parsing service_in\n if isinstance(service_endpoint, str):\n service_endpoint = [service_endpoint]\n elif service_endpoint == Service.Frontend:\n service_endpoint = [op_flow._frontend]\n elif not service_endpoint:\n if op_flow._last_add_service and connect_to_last_service:\n service_endpoint = [op_flow._last_add_service]\n else:\n service_endpoint = []\n if isinstance(service_endpoint, list) or isinstance(service_endpoint, tuple):\n for s in service_endpoint:\n if s == cur_service_name:\n raise FlowTopologyError('the income of a service can not be itself')\n if s not in op_flow._service_nodes:\n raise FlowTopologyError('service_in: %s can not be found in this Flow' % s)\n else:\n raise ValueError('service_in=%s is not parsable' % service_endpoint)\n return set(service_endpoint)\n\n @staticmethod\n def _get_parsed_args(op_flow, service_arg_parser, kwargs):\n kwargs.update(op_flow._common_kwargs)\n args = []\n for k, v in kwargs.items():\n if isinstance(v, bool):\n if v:\n if not k.startswith('no_') and not k.startswith('no-'):\n args.append('--%s' % k)\n else:\n args.append('--%s' % k[3:])\n else:\n if k.startswith('no_') or k.startswith('no-'):\n args.append('--%s' % k)\n else:\n args.append('--no_%s' % k)\n else:\n args.extend(['--%s' % k, str(v)])\n try:\n p_args, unknown_args = service_arg_parser().parse_known_args(args)\n if unknown_args:\n op_flow.logger.warning('not sure what these arguments are: %s' % unknown_args)\n except SystemExit:\n raise ValueError('bad arguments for service \"%s\", '\n 'you may want to double check your args \"%s\"' % (service_arg_parser, args))\n return args, p_args\n\n def _build_graph(self, copy_flow: bool) -> 'Flow':\n op_flow = copy.deepcopy(self) if copy_flow else self\n\n op_flow._service_edges.clear()\n\n if not op_flow._frontend:\n raise FlowImcompleteError('frontend does not exist, you may need to add_frontend()')\n\n if not op_flow._last_add_service or not op_flow._service_nodes:\n raise FlowTopologyError('flow is empty?')\n\n # close the loop\n op_flow._service_nodes[op_flow._frontend]['incomes'].add(op_flow._last_add_service)\n\n # build all edges\n for k, v in op_flow._service_nodes.items():\n for s in v['incomes']:\n op_flow._service_edges['%s-%s' % (s, k)] = ''\n for t in v['outgoings']:\n op_flow._service_edges['%s-%s' % (k, t)] = ''\n\n for k in op_flow._service_edges.keys():\n start_node, end_node = k.split('-')\n edges_with_same_start = [ed for ed in op_flow._service_edges.keys() if ed.startswith(start_node)]\n edges_with_same_end = [ed for ed in op_flow._service_edges.keys() if ed.endswith(end_node)]\n\n s_pargs = op_flow._service_nodes[start_node]['parsed_args']\n e_pargs = op_flow._service_nodes[end_node]['parsed_args']\n\n # Rule\n # if a node has multiple income/outgoing services,\n # then its socket_in/out must be PULL_BIND or PUB_BIND\n # otherwise it should be different than its income\n # i.e. income=BIND => this=CONNECT, income=CONNECT => this = BIND\n #\n # when a socket is BIND, then host must NOT be set, aka default host 0.0.0.0\n # host_in and host_out is only set when corresponding socket is CONNECT\n\n if len(edges_with_same_start) > 1 and len(edges_with_same_end) == 1:\n s_pargs.socket_out = SocketType.PUB_BIND\n s_pargs.host_out = BaseService.default_host\n e_pargs.socket_in = SocketType.SUB_CONNECT\n e_pargs.host_in = start_node\n e_pargs.port_in = s_pargs.port_out\n op_flow._service_edges[k] = 'PUB-sub'\n elif len(edges_with_same_end) > 1 and len(edges_with_same_start) == 1:\n s_pargs.socket_out = SocketType.PUSH_CONNECT\n s_pargs.host_out = end_node\n e_pargs.socket_in = SocketType.PULL_BIND\n e_pargs.host_in = BaseService.default_host\n s_pargs.port_out = e_pargs.port_in\n op_flow._service_edges[k] = 'push-PULL'\n elif len(edges_with_same_start) == 1 and len(edges_with_same_end) == 1:\n # in this case, either side can be BIND\n # we prefer frontend to be always BIND\n # check if either node is frontend\n if start_node == op_flow._frontend:\n s_pargs.socket_out = SocketType.PUSH_BIND\n e_pargs.socket_in = SocketType.PULL_CONNECT\n elif end_node == op_flow._frontend:\n s_pargs.socket_out = SocketType.PUSH_CONNECT\n e_pargs.socket_in = SocketType.PULL_BIND\n else:\n e_pargs.socket_in = s_pargs.socket_out.paired\n\n if s_pargs.socket_out.is_bind:\n s_pargs.host_out = BaseService.default_host\n e_pargs.host_in = start_node\n e_pargs.port_in = s_pargs.port_out\n op_flow._service_edges[k] = 'PUSH-pull'\n elif e_pargs.socket_in.is_bind:\n s_pargs.host_out = end_node\n e_pargs.host_in = BaseService.default_host\n s_pargs.port_out = e_pargs.port_in\n op_flow._service_edges[k] = 'push-PULL'\n else:\n raise FlowTopologyError('edge %s -> %s is ambiguous, at least one socket should be BIND')\n else:\n raise FlowTopologyError('found %d edges start with %s and %d edges end with %s, '\n 'this type of topology is ambiguous and should not exist, '\n 'i can not determine the socket type' % (\n len(edges_with_same_start), start_node, len(edges_with_same_end), end_node))\n\n op_flow._build_level = Flow.BuildLevel.GRAPH\n return op_flow\n\n def build(self, backend: Optional[str] = 'thread', copy_flow: bool = False, *args, **kwargs) -> 'Flow':\n \"\"\"\n Build the current flow and make it ready to use\n\n :param backend: supported 'thread', 'process', 'swarm', 'k8s', 'shell', if None then only build graph only\n :param copy_flow: return the copy of the current flow\n :return: the current flow (by default)\n \"\"\"\n\n op_flow = self._build_graph(copy_flow)\n\n if not backend:\n op_flow.logger.warning('no specified backend, build_level stays at %s, '\n 'and you can not run this flow.' % op_flow._build_level)\n elif backend in {'thread', 'process'}:\n op_flow._service_contexts.clear()\n for v in op_flow._service_nodes.values():\n p_args = v['parsed_args']\n p_args.parallel_backend = backend\n # for thread and process backend which runs locally, host_in and host_out should not be set\n p_args.host_in = BaseService.default_host\n p_args.host_out = BaseService.default_host\n op_flow._service_contexts.append((Flow._service2builder[v['service']], p_args))\n op_flow._build_level = Flow.BuildLevel.RUNTIME\n else:\n raise NotImplementedError('backend=%s is not supported yet' % backend)\n\n return op_flow\n\n def __call__(self, *args, **kwargs):\n return self.build(*args, **kwargs)\n\n def __enter__(self):\n if self._build_level.value < Flow.BuildLevel.RUNTIME.value:\n self.logger.warning(\n 'current build_level=%s, lower than required. '\n 'build the flow now via build() with default parameters' % self._build_level)\n self.build(copy_flow=False)\n self._service_stack = ExitStack()\n for k, v in self._service_contexts:\n self._service_stack.enter_context(k(v))\n\n self.logger.critical('flow is built and ready, current build level is %s' % self._build_level)\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.close()\n\n def close(self):\n if hasattr(self, '_service_stack'):\n self._service_stack.close()\n self._build_level = Flow.BuildLevel.EMPTY\n self.logger.critical(\n 'flow is closed and all resources should be released already, current build level is %s' % self._build_level)\n\n def __getstate__(self):\n d = dict(self.__dict__)\n del d['logger']\n return d\n\n def __setstate__(self, d):\n self.__dict__.update(d)\n self.logger = set_logger(self.__class__.__name__)\n","sub_path":"gnes/flow/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":23541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"561822687","text":"from global_module.settings_module import Directory\n\ndef extract(input_filename):\n output_file = open(input_filename + '_reviews.txt', 'w')\n lines = open(input_filename, 'r').readlines()\n for each_line in lines:\n if each_line.startswith('review/text:'):\n review = each_line[each_line.find('review/text:') + len('review/text:'):]\n if len(review) >= 20 and len(review) <= 275:\n output_file.write(review.strip() + '\\n')\n\n output_file.close()\n\n\nbase_dir = Directory('TR').data_path\nextract(base_dir + '/beer_advocate/beeradvocate.txt')\n","sub_path":"global_module/utility_codes/extract_reviews.py","file_name":"extract_reviews.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"69017610","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 15 09:37:25 2018\n문장 입력 다중클래스분류 모델\n참조: https://tykimos.github.io/2017/08/17/Text_Input_Multiclass_Classification_Model_Recipe/\n@author: SDEDU\n\"\"\"\n\nfrom keras.datasets import reuters\nfrom keras.utils import np_utils\nfrom keras.preprocessing import sequence\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Embedding, LSTM\n\n#1. 데이터셋 생성\nmax_features=15000\ntext_max_words=120\n\n#훈련셋과 시험셋 불러오기\n(x_train,y_train),(x_test,y_test)=reuters.load_data(num_words=max_features)\n\n#훈련셋과 검증셋 분리\nx_val=x_train[7000:]\ny_val=y_train[7000:]\nx_train=x_train[:7000]\ny_train=y_train[:7000]\n\n#데이터셋 전처리 :문장길이 맞추기\n#문장길이를 maxlen인자로 맞춤(=120보다 짧은 문장은 0을 채워서 120단어로 맞춰주고 120보다 긴 문장은 120단어까지 잘라냄)\nx_train=sequence.pad_sequences(x_train,maxlen=text_max_words)\nx_val=sequence.pad_sequences(x_val,maxlen=text_max_words)\nx_test=sequence.pad_sequences(x_test,maxlen=text_max_words)\n\n#one-hot 인코딩 onverts a class vecoter (integers) to binary class matrix\ny_train=np_utils.to_categorical(y_train)\ny_val=np_utils.to_categorical(y_val)\ny_test=np_utils.to_categorical(y_test)\n\n\n#2. 모델 구성하기\n#순환 신경망 모델\nmodel=Sequential()\nmodel.add(Embedding(max_features,128))\nmodel.add(LSTM(128))\nmodel.add(Dense(46,activation='softmax'))\n\n#3. 모델 학습과정 설정하기\nmodel.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])\n\n#4. 모델 학습시키기\nhist=model.fit(x_train,y_train,epochs=10, batch_size=64,validation_data=(x_val,y_val))\n\n#5. 학습과정 살펴보기\nimport matplotlib.pyplot as plt\nfig,loss_ax=plt.subplots()\n\nacc_ax=loss_ax.twinx()\n\nloss_ax.plot(hist.history['loss'],'y',label='train loss')\nloss_ax.plot(hist.history['val_loss'],'r',label='val loss')\nloss_ax.set_ylim([0.0,3.0])\n\nacc_ax.plot(hist.history['acc'],'b',label='train acc')\nacc_ax.plot(hist.history['val_acc'],'g',label='val acc')\nacc_ax.set_ylim([0.0,1.0])\n\nloss_ax.set_xlabel('epoch')\nloss_ax.set_ylabel('loss')\nacc_ax.set_ylabel('accuracy')\n\nloss_ax.legend(loc='upper left')\nacc_ax.legend(loc='lower left')\n\n#6. 모델평가하기\nloss_and_metrics=model.evaluate(x_test,y_test,batch_size=64)\nprint(loss_and_metrics)\n\n\n","sub_path":"Python/Lab30/Lab30.py","file_name":"Lab30.py","file_ext":"py","file_size_in_byte":2371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"279903549","text":"from django.conf.urls import patterns, url\n\nfrom selector import views\n\nurlpatterns = patterns('',\n url(r'^$', views.index, name='index'),\n url(r'^show/', views.show, name='show'),\n url(r'^select/', views.select, name='select'),\n url(r'^doselect/', views.doselect, name='doselect'),\n )\n","sub_path":"AnotherCoursePro/selector/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"578453624","text":"#!/usr/bin/python3\n\nimport sys\nimport logging\nfrom mowcounterbot import MowCounterTelegramBot\n\nlogging.basicConfig(level=logging.DEBUG,\n format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\n\ndef main():\n try:\n bot = MowCounterTelegramBot(MowCounterTelegramBot.parse_cli_arguments())\n except RuntimeError as e:\n print(e)\n sys.exit(1)\n print(\"Starting up bot\")\n bot.setup_commands()\n bot.start_loop()\n bot.shutdown()\n print(\"Shutting down bot\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"mowcounter_bot.py","file_name":"mowcounter_bot.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"536112554","text":"'''\nTime Complexity: O(log n)\nSpace Complexity: O(1)\nDid this code successfully run on Leetcode : Yes\nExplanation: Check if dividend is negative overflowing and divisor is -1 if true then return positive overflow number\ntake absolute value of dividend and divisor and put the sign after computing the quotient.\nEvery left shift of a bit multiplies a number by 2, so firstly left shift until the divisor is greater than dividend\nOnce its greater find the new dividend by subtracting it to the dividend by number of shifts of the divisor calculated and\nthe result is the power of 2 to the number of shifts which can be written in bit form as 1< int:\n\n if _dividend == -2147483648 and _divisor == -1:\n return 2147483647\n\n result = 0\n dividend = abs(_dividend)\n divisor = abs(_divisor)\n\n while dividend >= divisor:\n numOfShifts = 0\n while dividend >= (divisor << numOfShifts):\n numOfShifts += 1\n numOfShifts -= 1\n # 31/4 = 0 -4, 1-8, 2-16, 3 -32\n # 31-16\n dividend = dividend - (divisor << numOfShifts)\n result += 1 << numOfShifts # find the power of number of shifts\n\n if (_dividend > 0 and _divisor > 0) or (_divisor < 0 and _dividend < 0):\n return result\n\n return -result","sub_path":"divideTwoIntegers.py","file_name":"divideTwoIntegers.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"242599782","text":"import gym\nimport numpy as np\n\nenv = gym.make(\"Taxi-v2\")\n\n#Algorithm memory\n#This is a table which stores all combos of states and actions\n#The entered values will be associated rewards with these combos\nQ = np.zeros([env.observation_space.n, env.action_space.n])\n\n#Total accumulated reward for each session\nG = 0\n\n#Learning rate\nalpha = 0.618\n\nfor episode in range(1, 1001):\n #initialize the session\n done = False\n G, reward = 0, 0\n state = env.reset()\n #main loop\n counter = 0\n while done != True:\n counter += 1\n #Do the most valuable action available\n action = np.argmax(Q[state])\n #Collect the info of that action\n state2, reward, done, info = env.step(action)\n #Update the reward for this particular action\n #Add the actual reward plus the new potential reward (in our new state)\n #minus the previous total reward?\n Q[state, action] += alpha*(reward+np.max(Q[state2])-Q[state, action])\n G += reward\n state = state2\n if episode % 50 == 0:\n print('Episode {} Total Reward: {}'.format(episode, G))\n print('Moves taken to finish: {}'.format(counter))\n","sub_path":"GymNet/gymTestNet/learningAlgTaxi.py","file_name":"learningAlgTaxi.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"257673265","text":"from django.conf.urls import include, url\nfrom django.contrib import admin\nfrom .views import (\n RestaurantListAPIView, RestaurantDetailAPIView, \n RestaurantCreateAPIView, RestaurantUpdateAPIView,\n OperatingTimeCreateAPIView, OperatingTimeUpdateAPIView,\n MenuListAPIView, MenuDetailAPIView, \n MenuCreateAPIView, MenuUpdateAPIView, MenuCategoryDetailAPIView\n )\n\nurlpatterns = [\n url(r'^$', RestaurantListAPIView.as_view(), name=\"restaurantlistapiview\"),\n url(r'^menu/$', MenuListAPIView.as_view(), name=\"menu_list_api\"),\n url(r'^create/$', RestaurantCreateAPIView.as_view(), name=\"restaurantcreateapiview\"),\n url(r'^update/(?P[\\w-]+)$', RestaurantUpdateAPIView.as_view(), name=\"restaurantupdateapiview\"),\n url(r'^(?P[\\w-]+)/$', RestaurantDetailAPIView.as_view(), name=\"restaurantdetailapiview\"),\n url(r'^menu/(?P[\\w-]+)/$', MenuDetailAPIView.as_view(), name=\"menu_detail_api\"),\n url(r'^menu_category/(?P[\\w-]+)/$', MenuCategoryDetailAPIView.as_view(), name=\"menu_category_detail_api\"),\n\n # menu post put\n url(r'^create/menu/$', MenuCreateAPIView.as_view(), name=\"menu_create_api\"),\n url(r'^update/menu/(?P[\\w-]+)$', MenuUpdateAPIView.as_view(), name=\"menu_update_api\"),\n\n url(r'^create/operating_time/$', OperatingTimeCreateAPIView.as_view(), name=\"operatingtime_create_api\"),\n url(r'^update/operating_time/(?P\\d+)$', OperatingTimeUpdateAPIView.as_view(), name=\"operatingtime_update_api\"),\n \t \n]\n\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = urlpatterns + \\\n static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","sub_path":"restaurants/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"603802426","text":"# coding=utf-8\n# --------------------------------------------------------------------------\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#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass DeletedVaultProperties(Model):\n \"\"\"Properties of the deleted vault.\n\n Variables are only populated by the server, and will be ignored when\n sending a request.\n\n :ivar vault_id: The resource id of the original vault.\n :vartype vault_id: str\n :ivar location: The location of the original vault.\n :vartype location: str\n :ivar deletion_date: The deleted date.\n :vartype deletion_date: datetime\n :ivar scheduled_purge_date: The scheduled purged date.\n :vartype scheduled_purge_date: datetime\n :ivar tags: Tags of the original vault.\n :vartype tags: dict[str, str]\n \"\"\"\n\n _validation = {\n 'vault_id': {'readonly': True},\n 'location': {'readonly': True},\n 'deletion_date': {'readonly': True},\n 'scheduled_purge_date': {'readonly': True},\n 'tags': {'readonly': True},\n }\n\n _attribute_map = {\n 'vault_id': {'key': 'vaultId', 'type': 'str'},\n 'location': {'key': 'location', 'type': 'str'},\n 'deletion_date': {'key': 'deletionDate', 'type': 'iso-8601'},\n 'scheduled_purge_date': {'key': 'scheduledPurgeDate', 'type': 'iso-8601'},\n 'tags': {'key': 'tags', 'type': '{str}'},\n }\n\n def __init__(self, **kwargs) -> None:\n super(DeletedVaultProperties, self).__init__(**kwargs)\n self.vault_id = None\n self.location = None\n self.deletion_date = None\n self.scheduled_purge_date = None\n self.tags = None\n","sub_path":"azext_keyvault/mgmt/keyvault/models/deleted_vault_properties_py3.py","file_name":"deleted_vault_properties_py3.py","file_ext":"py","file_size_in_byte":1976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"47851906","text":"#!/usr/bin/python\nguests = ['Christopher', 'Susan', 'Bill', 'Satya']\nguests.append('Rodrigo')\nfor seats in range(4) :\n print(guests[seats])\n\nprint('\\n..........................Done!')\n\n#print(guests.index('Rodrigo'))\n#del guests[0]\n#print(guests)\n#print(\"Howdy World!\")\n#casesOrdered = 45\n#caseContents = \"Bananas\"\n#caseNumIn = \"gross\"\n#print(\"There are {0:d} cases of {1:s} {2:s} ordered\".format(casesOrdered, caseContents, caseNumIn))\n#guests.append('Stephan')\n#scores = [78,85,62,49,98]\n#guests.remove('Bill')\n#print(guests[-2])\n#print(scores[3])\n","sub_path":"PythonApplication1.py","file_name":"PythonApplication1.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"198413750","text":"from skimage import io\r\nfrom skimage import transform\r\nfrom skimage.color import rgb2gray\r\nimport numpy as np\r\nimport math\r\nimport os\r\n\r\n\r\ndef load_data(data_directory):\r\n \"\"\" Загружает готовые датасеты \"\"\"\r\n\r\n directories = [d for d in os.listdir(data_directory)\r\n if os.path.isdir(os.path.join(data_directory, d))]\r\n labels = []\r\n images = []\r\n for d in directories:\r\n label_directory = os.path.join(data_directory, d)\r\n file_names = [os.path.join(label_directory, f)\r\n for f in os.listdir(label_directory)\r\n if f.endswith(\".ppm\")]\r\n for f in file_names:\r\n images.append(io.imread(f))\r\n labels.append(int(d))\r\n return images, labels\r\n\r\n\r\ndef color_to_gray(images):\r\n \"\"\" Преобразует изображения в оттенки серого \"\"\"\r\n\r\n images_arr = np.array(images)\r\n return rgb2gray(images_arr)\r\n\r\n\r\ndef get_train_data():\r\n \"\"\" подготавливает данные для обучения и передачи их в НС \"\"\"\r\n\r\n ROOT_PATH = os.getcwd()\r\n train_data_directory = os.path.join(ROOT_PATH, \"Training\")\r\n\r\n train_images, train_labels = load_data(train_data_directory)\r\n\r\n # трансформация изображений до размера 28х28 пикселей и их конвертация в серый цвет\r\n train_images_transformed = [transform.resize(image, (28, 28)) for image in train_images]\r\n train_images_transformed = color_to_gray(train_images_transformed)\r\n return train_images_transformed, train_labels\r\n\r\n\r\ndef get_test_data():\r\n \"\"\" подготавливает данные для тестирования НС \"\"\"\r\n\r\n ROOT_PATH = os.getcwd()\r\n test_data_directory = os.path.join(ROOT_PATH, \"Testing\")\r\n\r\n test_images, test_labels = load_data(test_data_directory)\r\n\r\n # трансформация изображений до размера 28х28 пикселей и их конвертация в серый цвет\r\n test_images_transformed = [transform.resize(image, (28, 28)) for image in test_images]\r\n test_images_transformed = color_to_gray(test_images_transformed)\r\n return test_images_transformed, test_labels\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"load_datasets.py","file_name":"load_datasets.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"233304551","text":"from InterruptionHandler import InterruptionHandler\n\n\nclass TimeOutHandler(InterruptionHandler):\n\n def __init__(self , kernel):\n InterruptionHandler.__init__(self , kernel)\n\n def exec(self, program):\n pcbInCpu = self._kernel.pcbTable.runningPCB\n self._kernel.dispatcher.save(pcbInCpu)\n\n\n if(self._kernel.scheduler.isEmpty()):\n pcbInCpu.setState(\"STATE_RUNNING\")\n self._kernel.dispatcher.load(pcbInCpu)\n else:\n #Agrego un nuevo proceso a ejecutar\n pcbInCpu.setState(\"STATE_WAITING\")\n self._kernel.scheduler.add(pcbInCpu)\n pcbToAdd = self._kernel.scheduler.getNext()\n pcbToAdd.setState(\"STATE_RUNNING\")\n self._kernel.pcbTable.runningPCB(pcbToAdd)\n self._kernel.dispatcher.load(pcbToAdd)\n\n\n\n","sub_path":"TimeOutHandler.py","file_name":"TimeOutHandler.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"550978023","text":"\n\ndef checknotes(notesleft, rulebreak, repitition, pos, start):\n # Iterate over the 4 different starting positions\n if len(notesleft) == 1:\n return rulebreak\n if repitition is True:\n positions = 1e9\n for i in range(1, 5):\n if start is True:\n pos = i\n positions = min(positions, checknotes(notes, rulebreak, False, pos, False))\n if pos is False:\n pos = i\n positions = min(positions, checknotes(notesleft, rulebreak, False, pos, False))\n return positions\n if repitition is False:\n for j in range(len(notesleft)-1):\n if pos > 4 or pos < 1:\n rulebreak += 1\n return checknotes(notesleft, rulebreak, True, False, False)\n\n if 0 < pos < 5:\n if notesleft[j+1] > notesleft[j]:\n # Place j+1 on the next key\n pos += 1\n if notesleft[j+1] < notesleft[j]:\n # Place j+1 on the previous key\n pos -= 1\n if notesleft[j+1] == notesleft[j]:\n # Do nothing as j+1 on the same key\n pos = pos\n notesleft.remove(notesleft[j])\n return checknotes(notesleft, rulebreak, False, pos, False)\n\ntestcases = int(input())\nfor p in range(testcases):\n K = int(input())\n notes = list(map(int, input().split()))\n result = checknotes(notes, 0, True, 0, True)\n print('Case #' + str(p+1) + ': ' + str(result))\n","sub_path":"alienpiano(1).py","file_name":"alienpiano(1).py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"533003565","text":"from django.db import models\nfrom django.contrib import admin\nfrom django.contrib.auth.models import User\n\n# Create your models here.\nclass LeaveNote(models.Model):\n user = models.ForeignKey(User)#user ID\n dateSumbit = models.DateTimeField(auto_now=True)\n dateLeave = models.DateField()\n leaveReason = models.CharField(max_length=200)\n leaveDuration = models.IntegerField()\n isApproved = models.BooleanField()\n\nclass Level(models.Model):\n user = models.OneToOneField(User)\n","sub_path":"web/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"193798898","text":"\r\nclass Solution:\r\n def reverse(self, x: 'int') -> 'int':\r\n if x > float('inf') or x < float('-inf'):\r\n return 0\r\n sign = 1\r\n if x < 0:\r\n sign = -1\r\n xstr = str(x)\r\n if -1 == sign:\r\n xstr = xstr[1:]\r\n xstr = xstr[::-1]\r\n skip_cnt = 0\r\n for ch in xstr:\r\n if ch != '0':\r\n break\r\n skip_cnt += 1\r\n\r\n res = xstr[skip_cnt:]\r\n\r\n if '' == res:\r\n return 0\r\n if -1 == sign:\r\n res = '-' + res\r\n return int(res)\r\n\r\n\r\nx = 123\r\n#x = -123\r\n#x = 120\r\n#x = 901000\r\nx = 1534236469 # 0\r\n\r\nsol = Solution()\r\nprint(sol.reverse(x))\r\n\r\n","sub_path":"leet_code/7. Reverse Integer.py","file_name":"7. Reverse Integer.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"333570831","text":"\"\"\"\ngit tasks\n\"\"\"\nimport logging\nfrom invoke import task\nimport click\nfrom tasks.utils import get_compose_env, is_venv\n\n# from tasks.core import clean, execute_sql\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(\"DEBUG\")\n\n\n# git rev-parse HEAD\n\n\n# @task(incrementable=[\"verbose\"])\n# def verbosity(ctx, loc=\"local\", quiet=False, verbose=0):\n# \"\"\"\n# Return `git rev-parse HEAD` for project.\n# Usage: inv docker.lint-test or inv local.lint-test\n# \"\"\"\n# env = get_compose_env(ctx, loc=loc)\n\n# # Only display result\n# ctx.config[\"run\"][\"echo\"] = False\n\n# # Override run commands env variables one key at a time\n# for k, v in env.items():\n# ctx.config[\"run\"][\"env\"][k] = v\n\n\n@task(incrementable=[\"verbose\"])\ndef pr_sha(ctx, loc=\"local\", quiet=False, verbose=0):\n \"\"\"\n Return `git rev-parse HEAD` for project.\n Usage: inv docker.lint-test or inv local.lint-test\n \"\"\"\n env = get_compose_env(ctx, loc=loc)\n\n # Only display result\n ctx.config[\"run\"][\"echo\"] = False\n\n # Override run commands env variables one key at a time\n for k, v in env.items():\n ctx.config[\"run\"][\"env\"][k] = v\n\n res = ctx.run(\"git rev-parse HEAD\")\n\n # override CI_IMAGE value\n ctx.config[\"run\"][\"env\"][\"PR_SHA\"] = \"{}\".format(res.stdout)\n ctx.config[\"run\"][\"env\"][\"REPO_NAME\"] = \"bossjones/fake-medium-fastapi-ci\"\n ctx.config[\"run\"][\"env\"][\"IMAGE_TAG\"] = \"{}:{}\".format(\n ctx.config[\"run\"][\"env\"][\"REPO_NAME\"], ctx.config[\"run\"][\"env\"][\"PR_SHA\"]\n )\n ctx.config[\"run\"][\"env\"][\"TAG\"] = ctx.config[\"run\"][\"env\"][\"IMAGE_TAG\"]\n\n if verbose >= 1:\n msg = \"[PR_SHA] {}\".format(ctx.config[\"run\"][\"env\"][\"PR_SHA\"])\n click.secho(msg, fg=\"green\")\n","sub_path":"tasks/git.py","file_name":"git.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"251465494","text":"#!/usr/bin/env python3\n\n\n# You are given 2 out of 3 angles in a triangle, in degrees.\n\n# Write a function that classifies the missing angle as either\n# \"acute\", \"right\", or \"obtuse\" based on its degrees.\n\n# An acute angle is less than 90 degrees.\n# A right angle is exactly 90 degrees.\n# An obtuse angle is greater than 90 degrees (but less than 180 degrees).\n\n# For example: missing_angle(11, 20) should return \"obtuse\", since the missing angle would be 149 degrees, which makes it obtuse.\n\n\ndef missing_angle(angle1, angle2):\n max = 180\n if max - (angle1 + angle2) < 90:\n return \"acute\"\n elif max - (angle1 + angle2) == 90:\n return \"right\"\n elif max - (angle1 + angle2) > 90:\n return \"obtuse\"\n","sub_path":"edabit-problems/easy/general-practice/missing_third_angle.py","file_name":"missing_third_angle.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"534325607","text":"import os\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.layers import Activation, Dropout, Flatten, Dense\nfrom keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img\nimport keras_metrics as km\nfrom keras import backend as K\n\nK.set_image_dim_ordering('th')\nimport numpy as np\nfrom keras.preprocessing import image\nfrom sklearn.metrics import roc_auc_score, roc_curve, auc, average_precision_score, confusion_matrix\nfrom scipy import interp\nimport matplotlib.pyplot as plt\nfrom itertools import cycle\n\n\ndef get_model():\n model = Sequential()\n model.add(Conv2D(32, (3, 3), input_shape=(3, 100, 300)))\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n\n model.add(Conv2D(32, (3, 3)))\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n\n model.add(Conv2D(64, (3, 3)))\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n\n # the model so far outputs 3D feature maps (height, width, features)\n\n\n model.add(Flatten()) # this converts our 3D feature maps to 1D feature vectors\n model.add(Dense(64))\n model.add(Activation('relu'))\n model.add(Dropout(0.5))\n model.add(Dense(9))\n model.add(Activation('sigmoid'))\n return model\n\n\ndef build_models(weights_file):\n model = get_model()\n model.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['mean_squared_error', 'accuracy'])\n\n batch_size = 16\n\n # this is the augmentation configuration we will use for training\n train_datagen = ImageDataGenerator(\n rescale=1. / 255,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True)\n\n # this is the augmentation configuration we will use for testing:\n # only rescaling\n test_datagen = ImageDataGenerator(rescale=1. / 255)\n\n # this is a generator that will read pictures found in\n # subfolers of 'data/train', and indefinitely generate\n # batches of augmented image data\n train_generator = train_datagen.flow_from_directory(\n '/Users/preethi/Allclass/297/cnn_data/s_pattern_images/', # this is the target directory\n target_size=(100, 300), # all images will be resized to 150x150\n batch_size=batch_size,\n class_mode='categorical') # since we use binary_crossentropy loss, we need binary labels #categorical\n\n model.fit_generator(\n train_generator,\n steps_per_epoch=80,\n epochs=5)\n\n model.save_weights(weights_file) # always save your weights after training or during training\n\n\ndef rebuild_model(weights_file):\n rebuilt_model = get_model()\n rebuilt_model.load_weights(weights_file) # 'first_try.h5')\n return rebuilt_model\n\n\ndef try_roc_sklearn(y_pred, y_true):\n # Compute ROC curve and ROC area for each class\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n n_classes = 9\n lw = 2\n # Compute macro-average ROC curve and ROC area\n\n\n for i in range(n_classes):\n fpr[i], tpr[i], thresholdd = roc_curve(y_pred[:, i], y_true[:, i])\n # fpr[i], tpr[i], thresholdd = roc_curve(y_pred, y_true)\n '''\n fnr = 1 - tpr[i]\n\n err_threshold = thresholdd[np.nanargmin(np.absolute((fnr[1] - fpr[i])))]\n EER = fpr[i][np.nanargmin(np.absolute((fnr - fpr[i])))]\n print(\"ERR = \")\n print(EER)\n print(err_threshold)\n '''\n roc_auc[i] = auc(fpr[i], tpr[i])\n\n # First aggregate all false positive rates\n all_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)]))\n\n # Then interpolate all ROC curves at this points\n mean_tpr = np.zeros_like(all_fpr)\n for i in range(n_classes):\n mean_tpr += interp(all_fpr, fpr[i], tpr[i])\n\n # Finally average it and compute AUC\n mean_tpr /= n_classes\n\n roc_auc[i] = auc(fpr[i], tpr[i])\n\n # Compute micro-average ROC curve and ROC area\n # Plot all ROC curves\n plt.figure()\n\n colors = ['darkblue', 'darkorange', 'cornflowerblue', 'r', 'b', 'g', 'c', 'y', 'm']\n # users = ['intruder', 'user']\n for i, color in zip(range(n_classes), colors):\n plt.plot(fpr[i], tpr[i], color=color, lw=lw,\n label='ROC curve of user {0} (area = {1:0.2f})'\n ''.format(str(i + 1), roc_auc[i]))\n\n plt.plot([1, 0], [0, 1], 'k--', lw=lw)\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.05])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('ROC curve for Common User Patterns(Acceleration)')\n plt.legend(loc=\"lower right\")\n plt.show()\n\n\ndef try_predict(weights):\n # build_models()\n model = rebuild_model(weights_file=weights)\n # test_image = image.load_img('/Users/preethi/Allclass/297/data_validation/ansu/ansu2.jpg',\n # target_size=(100, 300))\n # test_image = image.img_to_array(test_image)\n # test_image = np.expand_dims(test_image, axis=0)\n # result = model.predict_classes(test_image)\n # print(result)\n\n test_datagen = ImageDataGenerator(rescale=1. / 255)\n\n # this is a generator that will read pictures found in\n # subfolers of 'data/train', and indefinitely generate\n # batches of augmented image data\n test_datagen = test_datagen.flow_from_directory(\n '/Users/preethi/Allclass/297/data_validation_unique/', # '/Users/preethi/Allclass/297/cnn_data/validation/',#\n target_size=(100, 300), # all images will be resized to 150x150\n batch_size=16,\n shuffle=False,\n class_mode='categorical') # since we use binary_crossentropy loss, we need binary labels\n\n predictions = model.predict_generator(test_datagen)\n print(predictions)\n\n # multiclass\n\n y_pred = np.zeros((39, 9), dtype=np.int8)\n\n r_num = 0\n for row in predictions:\n max_idx = np.argmax(row)\n y_pred[r_num][max_idx] = 1\n r_num += 1\n # y_pred = np.amax(predictions, axis=1)\n\n y_true_h = test_datagen.classes\n\n y_true = np.zeros((y_true_h.size, int(y_true_h.max()) + 1), dtype=np.int8)\n y_true[np.arange(y_true_h.size), y_true_h] = 1\n\n '''\n\n # binary\n y_pred = np.zeros(50, dtype=np.int8)\n\n r_num = 0\n for row in predictions:\n max_idx = np.argmax(row)\n if max_idx == 1:\n y_pred[r_num] = 1\n r_num += 1\n # y_pred = np.amax(predictions, axis=1)\n #y_pred = np.amax(predictions, axis=1)\n y_true_h = test_datagen.classes\n print(y_pred)\n print(y_true_h)\n try_roc_sklearn(y_pred, y_true_h)\n '''\n try_roc_sklearn(y_pred, y_true)\n\n\nif __name__ == \"__main__\":\n # build_models('cnn_common_2class3.h5')\n # s_pattern_model = rebuild_model('cnn_common_pattern.h5')\n # build_models('cnn_balanced_2class.h5')\n # try_predict('cnn_balanced_2class.h5')\n try_predict('first_try.h5')","sub_path":"cnn_unique.py","file_name":"cnn_unique.py","file_ext":"py","file_size_in_byte":6863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"344911225","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Sep 28 13:38:33 2020\r\n\r\n@author: User\r\n\"\"\"\r\nimport matplotlib \r\nimport matplotlib.font_manager as fm\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib import font_manager, rc\r\nimport pandas as pd\r\nimport utils\r\nimport numpy as np\r\nimport pickle\r\nimport os\r\nfrom load_data import load_data\r\nimport seaborn as sns\r\n\r\n\r\ndef make_product_key(): \r\n product_list = ['가구','가전','건강기능','농수축','생활용품',\r\n '속옷','의류','이미용','잡화','주방','침구']\r\n product_dict = {'상품군_%s'%k : k for k in product_list}\r\n return product_dict\r\n\r\n\r\ndef make_season_key(): \r\n season_dict = {'계절_0':0,'계절_1':1,'계절_2':2,'계절_3':3}\r\n return season_dict\r\n\r\ndef make_month_key():\r\n month_dict = {'월_%s'%k : k for k in range(1,13)}\r\n return month_dict\r\n\r\ndef make_week_key():\r\n\r\n week_dict = {'주차_%s'%k : k for k in range(1,54)}\r\n return week_dict\r\n\r\ndef make_hour_key():\r\n\r\n hour_dict = {'시간대_%s'%k : k for k in [0,1,2,6,7,8,9,10,11,12,13,14,15,16,\r\n 17,18,19,20,21,22,23]}\r\n return hour_dict\r\n\r\n\r\ndef make_not_enough_dummy(dummy_df, col):\r\n result_df = dummy_df.copy()\r\n element_list = np.unique(dummy_df['name'])\r\n for element in element_list:\r\n temp_col_name = '%s_%s'%(col,element)\r\n result_df[temp_col_name] = 0\r\n \r\n ind = dummy_df[dummy_df['name'] == element].index\r\n result_df.loc[ind,temp_col_name] = 1\r\n \r\n if col == '계절':\r\n target_dict = make_season_key()\r\n elif col == '월':\r\n target_dict = make_month_key()\r\n elif col == '주차':\r\n target_dict = make_week_key()\r\n elif col == '상품군':\r\n target_dict = make_product_key()\r\n elif col == '시간대':\r\n target_dict = make_hour_key()\r\n for key in target_dict.keys():\r\n if key not in result_df.columns:\r\n result_df[key] = 0\r\n \r\n result_df = result_df.loc[:,['name']+[k for k in target_dict.keys()]]\r\n \r\n return result_df, target_dict\r\n \r\n\r\n\r\ndef make_dummy(df, col_name):\r\n #col_name = 'new_월'\r\n not_enough_col_list = ['월','주차','계절','상품군','시간대']\r\n dummy = pd.get_dummies(df[col_name], prefix=col_name)\r\n \r\n dummy_df = pd.DataFrame({'name':df[col_name]})\r\n dummy_df = pd.concat([dummy_df, dummy], axis=1)\r\n \r\n name_dict = {}\r\n for col in dummy_df.columns[1:]:\r\n target = dummy_df[dummy_df[col]!=0].reset_index(drop=True).loc[0,['name',col]]\r\n name_dict[col] = target['name']\r\n \r\n # 보충\r\n if col_name in not_enough_col_list:\r\n dummy_df, name_dict = make_not_enough_dummy(dummy_df, col_name) \r\n \r\n col_stand_name = '_'.join(dummy_df.columns[1].split('_')[:-1])\r\n\r\n col_list = ['%s_%s'%(col_stand_name,v) for v in name_dict.values()]\r\n \r\n dummy_df = dummy_df.iloc[:,1:]\r\n dummy_df.columns = col_list\r\n\r\n df = df.drop(col_name, axis=1)\r\n df = pd.concat([df, dummy_df], axis=1)\r\n\r\n return df\r\n\r\ndef extract_dummy(X_data, save_path):\r\n \r\n # 더미변수 추출\r\n with open(save_path+'model_setting.txt', 'r') as f1:\r\n while True:\r\n line = f1.readline()\r\n if 'dummy' in line:\r\n dummy_var = line.split('=')[1]\r\n \r\n if not line:\r\n break\r\n \r\n dummy_list = dummy_var.split(',')\r\n dummy_list[-1] = dummy_list[-1][:-1]\r\n \r\n for col in dummy_list:\r\n X_data = make_dummy(X_data, col)\r\n \r\n return X_data\r\n\r\n\r\n\r\ndef load_x_col(save_path):\r\n\r\n with open(save_path+'test_result.pkl', 'rb') as f:\r\n obj_dict = pickle.load(f)\r\n \r\n x_col = obj_dict['result']['data']['changed_x_col']\r\n \r\n return x_col\r\n\r\nfont = {'family' : 'normal',\r\n 'weight' : 'bold',\r\n 'size' : 22}\r\n\r\nmatplotlib.rc('font', **font)\r\n\r\nfm.get_fontconfig_fonts()\r\nplt.rcParams['axes.unicode_minus'] = False\r\nmatplotlib.rc('font', family='Malgun Gothic')\r\n\r\nmodel_path = utils.model_path\r\n\r\ntrain_path = utils.train_path\r\nfig_path = utils.fig_path\r\n#%%\r\ndef load_model(save_path):\r\n # 0. 최적 모델 가져오기\r\n \r\n with open(save_path+'test_result.pkl', 'rb') as f:\r\n result = pickle.load(f)\r\n \r\n return result\r\n\r\n\r\ndef predict_value(X_data, save_path,fig_save_path ):\r\n # 모델\r\n result = load_model(save_path)\r\n\r\n # 예측값 구하기\r\n pred_list = []\r\n X_data = extract_dummy(X_data, save_path)\r\n x_col = load_x_col(save_path)\r\n X_data = X_data.loc[:,x_col]\r\n X_data = X_data.fillna(0)\r\n X_data = X_data.values\r\n \r\n for i in range(5):\r\n valid_ind = result['result']['data']['dataset']['valid'][i]\r\n\r\n with open(save_path+'model_%s.pkl'%(i), 'rb') as f:\r\n model = pickle.load(f)\r\n pred = model.predict(X_data).reshape(-1,)\r\n pred_list.append(pred)\r\n \r\n pred_list = np.mean(np.stack(pred_list),axis=0)\r\n \r\n plt.figure(figsize=(24,16))\r\n sns.distplot(pred_list)\r\n plt.title('test 예측값', size=30)\r\n plt.xlabel('취급액')\r\n plt.ylabel('scaled_빈도')\r\n plt.savefig(fig_save_path+'test 데이터 분포.png')\r\n plt.show()\r\n \r\n return pred_list\r\n\r\n\r\ndef extract_feature_importance(save_path, fig_save_path, fig_save_option=False):\r\n\r\n result = load_model(save_path) \r\n\r\n x_col = result['result']['data']['changed_x_col']\r\n \r\n feature_df = pd.DataFrame({'x_col':x_col})\r\n for i in range(5):\r\n feature = result['result']['feature'][i]\r\n feature_df[i] = feature\r\n \r\n feature_df['important'] = np.mean(feature_df.iloc[:,1:],axis=1)\r\n feature_df = feature_df[['x_col','important']]\r\n feature_df = feature_df.sort_values('important',ascending=False).reset_index(drop=True)\r\n \r\n plt.figure(figsize=(24,16))\r\n plt.bar(feature_df.loc[:29,'x_col'], feature_df.loc[:29,'important'])\r\n plt.title('변수 중요도')\r\n plt.ylabel('중요도')\r\n plt.xlabel('변수이름')\r\n plt.xticks(rotation=40, size=15)\r\n if fig_save_option == True:\r\n plt.savefig(fig_save_path+'변수 중요도.png')\r\n plt.show()\r\n \r\n return 0\r\n\r\ndef main(save_path = model_path+'xgb_bds100/'):\r\n # 1. 파일 불러오기\r\n train = load_data('train.csv', 'train_WordVec.pkl', True)\r\n test = load_data('test.csv', 'test_WordVec.pkl',True)\r\n \r\n # 예측값 추출\r\n y_pred = predict_value(test, save_path, fig_path+'모델/')\r\n \r\n # 저장\r\n np.save(train_path+'test_pred.npy',y_pred)\r\n \r\n # feature_importance\r\n extract_feature_importance(save_path, fig_path+'모델/', fig_save_option=True)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n \r\n","sub_path":"code/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":6784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"335916784","text":"from RLAgent import *\nfrom Common import *\nfrom Model import VelocityModel\nimport pygame\n\n\ndef verifyModel(agent):\n keymap = defaultdict(lambda: 'hover')\n keymap.update([('Key.up', 'moveForward'), ('Key.left', 'yawCCW'), ('Key.right', 'yawCW'), ('Key.down', 'hover')])\n\n while True:\n initialState, a = agent.getState(), agent.keyPressed.value\n yield keymap[a]\n\n r, nextState, isTerminal = (yield)\n draw_multirotor(nextState)\n\n yield\n\n\ndef draw_multirotor(state):\n roll, pitch, yaw = toEulerianAngle(state.orientation)\n x, y, z = state.position\n\n screen.fill((58, 58, 58))\n\n img_r = pygame.transform.rotate(img, -np.rad2deg(yaw))\n screen.blit(img_r, (x*10, y*10))\n\n pygame.display.update()\n\n\ndef main():\n model = VelocityModel(regressionModel=joblib.load('models/gradient-m.model'), frequency=10.0)\n agent = RLAgent('agent', decisionFrequency=20.0, defaultSpeed=4, defaultAltitude=6, yawRate=60,\n alternativeModel=model, maxDepth=math.inf, initialState=None)\n\n agent.setRl(verifyModel)\n agent.start()\n agent.join()\n\n\npygame.init()\nscreen = pygame.display.set_mode((300, 600))\npygame.display.set_caption('Model Verification')\nimg = pygame.image.load('quadcopter.jpg')\nmain()","sub_path":"multirotor/src/ModelVerification.py","file_name":"ModelVerification.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"110992852","text":"#!/usr/bin/python3\n# coding=utf-8\n#\n# bme280.py\n# Read data from a digital pressure sensor.\n#\n# Official datasheet available from :\n# https://www.bosch-sensortec.com/bst/products/all_products/bme280\n#---------------------------------------\nfrom __future__ import print_function\nfrom mq import *\nfrom ky import *\nfrom mics import *\nimport os\nimport math\nimport smbus\nimport time\nimport config\nimport serial, struct, sys, json\nfrom ctypes import c_short\nfrom ctypes import c_byte\nfrom ctypes import c_ubyte\n\nDEBUG = 0\nCMD_MODE = 2\nCMD_QUERY_DATA = 4\nCMD_DEVICE_ID = 5\nCMD_SLEEP = 6\nCMD_FIRMWARE = 7\nCMD_WORKING_PERIOD = 8\nMODE_ACTIVE = 0\nMODE_QUERY = 1\nDEVICE = 0x76 # Default device I2C address\nlight_channel = 1\nNH3_channel = 2\nNO2_channel = 3\n\nbus = smbus.SMBus(1) # Rev 2 Pi, Pi 2 & Pi 3 uses bus 1\n # Rev 1 Pi uses bus 0\n\nPORT = '/dev/ttyUSB0'\n\nUNPACK_PAT = ' 127:\n result -= 256\n return result\n\ndef getUChar(data,index):\n # return one byte from data as an unsigned char\n result = data[index] & 0xFF\n return result\n\ndef readBME280ID(addr=DEVICE):\n # Chip ID Register Address\n REG_ID = 0xD0\n (chip_id, chip_version) = bus.read_i2c_block_data(addr, REG_ID, 2)\n return (chip_id, chip_version)\n\ndef readBME280All(addr=DEVICE):\n # Register Addresses\n REG_DATA = 0xF7\n REG_CONTROL = 0xF4\n REG_CONFIG = 0xF5\n\n REG_CONTROL_HUM = 0xF2\n REG_HUM_MSB = 0xFD\n REG_HUM_LSB = 0xFE\n\n # Oversample setting - page 27\n OVERSAMPLE_TEMP = 2\n OVERSAMPLE_PRES = 2\n MODE = 1\n\n # Oversample setting for humidity register - page 26\n OVERSAMPLE_HUM = 2\n bus.write_byte_data(addr, REG_CONTROL_HUM, OVERSAMPLE_HUM)\n\n control = OVERSAMPLE_TEMP<<5 | OVERSAMPLE_PRES<<2 | MODE\n bus.write_byte_data(addr, REG_CONTROL, control)\n\n # Read blocks of calibration data from EEPROM\n # See Page 22 data sheet\n cal1 = bus.read_i2c_block_data(addr, 0x88, 24)\n cal2 = bus.read_i2c_block_data(addr, 0xA1, 1)\n cal3 = bus.read_i2c_block_data(addr, 0xE1, 7)\n\n # Convert byte data to word values\n dig_T1 = getUShort(cal1, 0)\n dig_T2 = getShort(cal1, 2)\n dig_T3 = getShort(cal1, 4)\n\n dig_P1 = getUShort(cal1, 6)\n dig_P2 = getShort(cal1, 8)\n dig_P3 = getShort(cal1, 10)\n dig_P4 = getShort(cal1, 12)\n dig_P5 = getShort(cal1, 14)\n dig_P6 = getShort(cal1, 16)\n dig_P7 = getShort(cal1, 18)\n dig_P8 = getShort(cal1, 20)\n dig_P9 = getShort(cal1, 22)\n\n dig_H1 = getUChar(cal2, 0)\n dig_H2 = getShort(cal3, 0)\n dig_H3 = getUChar(cal3, 2)\n\n dig_H4 = getChar(cal3, 3)\n dig_H4 = (dig_H4 << 24) >> 20\n dig_H4 = dig_H4 | (getChar(cal3, 4) & 0x0F)\n\n dig_H5 = getChar(cal3, 5)\n dig_H5 = (dig_H5 << 24) >> 20\n dig_H5 = dig_H5 | (getUChar(cal3, 4) >> 4 & 0x0F)\n\n dig_H6 = getChar(cal3, 6)\n\n # Wait in ms (Datasheet Appendix B: Measurement time and current calculation)\n wait_time = 1.25 + (2.3 * OVERSAMPLE_TEMP) + ((2.3 * OVERSAMPLE_PRES) + 0.575) + ((2.3 * OVERSAMPLE_HUM)+0.575)\n time.sleep(wait_time/1000) # Wait the required time \n\n # Read temperature/pressure/humidity\n data = bus.read_i2c_block_data(addr, REG_DATA, 8)\n pres_raw = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4)\n temp_raw = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4)\n hum_raw = (data[6] << 8) | data[7]\n\n #Refine temperature\n var1 = ((((temp_raw>>3)-(dig_T1<<1)))*(dig_T2)) >> 11\n var2 = (((((temp_raw>>4) - (dig_T1)) * ((temp_raw>>4) - (dig_T1))) >> 12) * (dig_T3)) >> 14\n t_fine = var1+var2\n temperature = float(((t_fine * 5) + 128) >> 8);\n\n # Refine pressure and adjust for temperature\n var1 = t_fine / 2.0 - 64000.0\n var2 = var1 * var1 * dig_P6 / 32768.0\n var2 = var2 + var1 * dig_P5 * 2.0\n var2 = var2 / 4.0 + dig_P4 * 65536.0\n var1 = (dig_P3 * var1 * var1 / 524288.0 + dig_P2 * var1) / 524288.0\n var1 = (1.0 + var1 / 32768.0) * dig_P1\n if var1 == 0:\n pressure=0\n else:\n pressure = 1048576.0 - pres_raw\n pressure = ((pressure - var2 / 4096.0) * 6250.0) / var1\n var1 = dig_P9 * pressure * pressure / 2147483648.0\n var2 = pressure * dig_P8 / 32768.0\n pressure = pressure + (var1 + var2 + dig_P7) / 16.0\n\n # Refine humidity\n humidity = t_fine - 76800.0\n humidity = (hum_raw - (dig_H4 * 64.0 + dig_H5 / 16384.0 * humidity)) * (dig_H2 / 65536.0 * (1.0 + dig_H6 / 67108864.0 * humidity * (1.0 + dig_H3 / 67108864.0 * humidity)))\n humidity = humidity * (1.0 - dig_H1 * humidity / 524288.0)\n if humidity > 100:\n humidity = 100\n elif humidity < 0:\n humidity = 0\n\n return temperature/100.0,pressure/100.0,humidity\n\ndef dump(d, prefix=''):\n print(prefix + ' '.join(x.encode('hex') for x in d))\n\ndef construct_command(cmd, data=[]):\n assert len(data) <= 12\n data += [0,]*(12-len(data))\n checksum = (sum(data)+cmd-2)%256\n ret = \"\\xaa\\xb4\" + chr(cmd)\n ret += ''.join(chr(x) for x in data)\n ret += \"\\xff\\xff\" + chr(checksum) + \"\\xab\"\n\n if DEBUG:\n dump(ret, '> ')\n return ret\n\ndef process_data(d):\n r = struct.unpack('= 65 and ord(pattern[i])<= 90 :\n alphabets[ord(pattern[i])-65]+=1\n count+=1\n series.append(ord(pattern[i])-65)\n elif ord(pattern[i]) >= 97 and ord(pattern[i])<= 122 :\n alphabets[ord(pattern[i])-97+26]+=1\n count+=1\n series.append(ord(pattern[i])-97+26)\n\n#print(alphabets[:26])\n#print(alphabets[26:])\nfor i in range(n):\n check=list(alphabets)\n sequence=list(series)\n c=count\n s=0\n #print(word[i])\n flag=True\n for j in range(len(word[i])):\n if ord(word[i][j]) >= 65 and ord(word[i][j]) <=90 :\n if check[ord(word[i][j])-65] > 0 :\n check[ord(word[i][j])-65]-=1\n if sequence[s]!= (ord(word[i][j])-65):\n flag=False\n c-=1\n s+=1\n else:\n flag=False\n break\n elif ord(word[i][j]) >= 97 and ord(word[i][j])<= 122 :\n if check[ord(word[i][j])-97+26] > 0:\n check[ord(word[i][j])-97+26]-=1\n c-=1\n if sequence[s]!=(ord(word[i][j])-97+26):\n flag=False\n s+=1\n else :\n #print(word[i][j])\n continue\n if c==0 and flag==True:\n #print(word[i])\n print(\"true\")\n continue\n print(\"false\")\n\n ","sub_path":"mockassignment1.py","file_name":"mockassignment1.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"430885953","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019-11-15 10:23\n# @Author : weihuchao\n\nfrom flask import Flask, render_template, request\n\nfrom analyzer import check_mid_data, init_mid_data\n\napp = Flask(__name__)\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n has_min_data = check_mid_data()\n if request.method == \"POST\":\n file_path = request.form.get(\"file_path\")\n init_mid_data(file_path=file_path)\n return render_template('index.html', has_min_data=True)\n\n return render_template('index.html', has_min_data=has_min_data)\n\n\n@app.route('/api/list')\ndef api_list():\n list_data = []\n return render_template('api/list.html', list_data=list_data)\n","sub_path":"web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"494584323","text":"from itertools import islice\n\nfrom rest_framework.response import Response\nfrom rest_framework import status\n\nfrom query_base.query_base import QueryBaseView\n\n\nclass DefaultGeneModelsId(QueryBaseView):\n def get(self, request):\n default_gene_models_id = \\\n self.gpf_instance.dae_config.gene_models.resource_id\n return Response(default_gene_models_id, status=status.HTTP_200_OK)\n\n\nclass GeneModels(QueryBaseView):\n def get(self, request, gene_symbol):\n gene_symbol = gene_symbol.lower()\n gene_models = self.gpf_instance.gene_models.gene_models\n for k, v in gene_models.items():\n if gene_symbol == k.lower():\n transcripts = v\n response_data = {\n \"gene\": k,\n \"transcripts\": [],\n }\n for tr in transcripts:\n response_data[\"transcripts\"].append(\n self.transcript_to_dict(tr)\n )\n\n return Response(\n response_data,\n status=status.HTTP_200_OK,\n )\n return Response(None, status=status.HTTP_404_NOT_FOUND)\n\n def transcript_to_dict(self, transcript):\n output = dict()\n output[\"transcript_id\"] = transcript.tr_id\n output[\"strand\"] = transcript.strand\n output[\"chrom\"] = transcript.chrom\n output[\"cds\"] = self.cds_to_dictlist(transcript.cds)\n output[\"utr3\"] = list()\n for region in transcript.UTR3_regions():\n output[\"utr3\"].append(self.region_to_dict(region))\n output[\"utr5\"] = list()\n for region in transcript.UTR5_regions():\n output[\"utr5\"].append(self.region_to_dict(region))\n output[\"exons\"] = list()\n for exon in transcript.exons:\n output[\"exons\"].append(self.exon_to_dict(exon))\n return output\n\n def cds_to_dictlist(self, cds):\n return [\n {\"start\": a, \"stop\": b}\n for (a, b) in zip(cds[::2], cds[1::2])\n ]\n\n def region_to_dict(self, region):\n return {\n \"start\": region.start,\n \"stop\": region.stop\n }\n\n def exon_to_dict(self, exon):\n return {\n \"start\": exon.start,\n \"stop\": exon.stop\n }\n\n\nclass GeneSymbolsSearch(QueryBaseView):\n\n RESPONSE_LIMIT = 20\n\n def get(self, request, search_term):\n search_term = search_term.lower()\n gene_models = self.gpf_instance.gene_models.gene_models\n\n matching_gene_symbols = filter(\n lambda gs: gs.lower().startswith(search_term),\n gene_models.keys()\n )\n\n matching_gene_symbols = islice(\n matching_gene_symbols, None, self.RESPONSE_LIMIT\n )\n\n return Response(\n {\"gene_symbols\": list(matching_gene_symbols)},\n status=status.HTTP_200_OK,\n )\n","sub_path":"wdae/wdae/genomes_api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"314674165","text":"\"\"\" Commands for downloading from s3 \"\"\"\nimport os\nimport sys\n\nimport click\n\nfrom bwdt.lib.aws.s3 import S3\nfrom bwdt.constants import (APT_TARGZ_KEY, BWDT_TARGZ_KEY, CLOUDYML_KEY,\n S3_BUCKET)\n\n\ndef _save(path, key, force):\n \"\"\" Download the specified file \"\"\"\n files_dir = '{}/{}'.format(path, 'files')\n if os.path.isdir(path):\n full_path = '{}/{}'.format(files_dir, key)\n else:\n err = 'ERROR: path {} must be a directory and exist\\n'.format(path)\n sys.stderr.write(err)\n return False\n if not os.path.exists(files_dir):\n os.mkdir(files_dir)\n if os.path.exists(full_path) and not force:\n err = 'WARN: File {} exists. Use --force to replace'.format(full_path)\n click.echo(err)\n return False\n click.echo('Saving {}'.format(full_path))\n full_path = '{}/{}'.format(files_dir, key)\n S3().download(full_path, S3_BUCKET, key)\n return True\n\n\ndef offline_apt(path, force):\n \"\"\" Download a subset of breqwatr/apt for offline installs \"\"\"\n _save(path, APT_TARGZ_KEY, force)\n\n\ndef offline_bwdt(path, force):\n \"\"\" Download an offline export of this bwdt tool \"\"\"\n _save(path, BWDT_TARGZ_KEY, force)\n\n\ndef cloud_yml(path, force):\n \"\"\" Download a commented cloud.yml template \"\"\"\n _save(path, CLOUDYML_KEY, force)\n","sub_path":"bwdt/lib/download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"78170356","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 24 15:08:21 2021\n\n@author: Mark Barbet\n\"\"\"\n\n\nimport os\n#from typing import final\nimport numpy as np\nimport re\nimport cantera as ct\nimport copy\nimport pandas as pd\n#import progressbar, time, sys\nimport time, sys\nimport enlighten\nimport yaml\nimport doe_object as dobj\n\nclass ranking():\n \n def __init__(self,doe_obj:dobj.doe_object):\n self.inputs=doe_obj.input_options\n \n # def __init__(self,module0=None,module1=None,settings={'batch-size':10,\n # 'total_new_exp':10,\n # 'output-csv':'output.csv'}):\n \n self.subloopBool=True\n #self.module0=module0\n #self.module1=module1\n self.doe_obj=doe_obj\n self.settings={}\n self.settings['batch-size']=doe_obj.input_options['batch-size']\n self.settings['total_new_exp']=doe_obj.input_options['total_new_exp']\n self.settings['output-csv']=doe_obj.input_options['output-csv']\n self.excluded_yamls=[]\n total_iters=int(np.ceil(self.settings['total_new_exp']/self.settings['batch-size']))\n #print(total_iters)\n #total_exps=0\n final_exp_dataframe=pd.DataFrame(columns=['experiment','ratio'])\n #current_yamls=copy.deepcopy(self.module1.yaml_file_list)\n S_countH=0\n S_countV=0\n new_Z=copy.deepcopy(self.doe_obj.Z_original)\n new_Y=copy.deepcopy(self.doe_obj.Y_original)\n new_X_list=list(self.doe_obj.X_original['value'])\n self.updated_S=copy.deepcopy(self.doe_obj.S_original)\n \n #self.printProgressBar(0, total_iters, prefix = 'Finding Best Experiments:', suffix = 'Complete', length = 70)\n #self.down()\n #total = progressbar.ProgressBar(maxval=total_iters)\n #total.start()\n self.manager = enlighten.get_manager()\n self.mainloop=self.manager.counter(total=total_iters,desc='Overall Progress',unit='batches',color='green')\n \n for i in np.arange(total_iters):\n #print(i,\"wtf\")\n if i==0:\n self.ranking=self.get_rankings(self.excluded_yamls,self.updated_S,i,countH=S_countH, countV=S_countV)\n elif i>0:\n self.ranking=self.get_rankings(self.excluded_yamls,self.updated_S,i,\n countH=S_countH, countV=S_countV,\n Z_prev=new_Z,Y_prev=new_Y,X_prev=new_X_list)\n if i+10:\n S_countV=self.experiment_length+S_countV+len(X_to_add)\n #elif i==0:\n # S_countV=S_countV+S_countH\n #print('New Count H: '+str(S_countH)+', New Count V: '+str(S_countV)+', Exp Length: '+str(self.experiment_length))\n return (S_proposed,new_Y,new_Z,new_X_list,S_countH,S_countV)\n \n \n def get_S_current_columns(self,doe_obj=None):\n colnames=list(doe_obj.X_original['value'])\n rownames=list(doe_obj.Y_original['value'])\n return (colnames,rownames)\n \n \n \n def get_Z(self,file,indexer):\n data=self.load_to_obj(file)\n previous_exp_index=int(self.rownames_nominal[-1].split('_')[-1])\n current_exp_index=previous_exp_index+1\n exclude_list=[]\n A=[]\n N=[]\n Ea=[]\n for i in np.arange(self.num_rxns):\n A=A+['A_'+str(i)]\n for i in np.arange(self.num_rxns): \n N=N+['n_'+str(i)]\n for i in np.arange(self.num_rxns):\n Ea=Ea+['Ea_'+str(i)]\n exclude_list=A+N+Ea\n #print(exclude_list)\n Z_to_add=self.doe_obj.experiment_matrices[indexer]['Z'][~self.doe_obj.experiment_matrices[indexer]['Z']['value'].isin(exclude_list)].copy()\n new_Z_names=[]\n for j,item in enumerate(list(Z_to_add['value'])):\n temp=item.split('_')\n if 'experiment' in temp[-1]:\n temp2=re.split('(\\d+)',temp[-1])\n #print(temp2)\n temp2[-2]=str(current_exp_index)\n temp[-1]=''.join(temp2)\n \n else:\n temp[-1]=str(current_exp_index)\n new_Z_names=new_Z_names+['_'.join(temp)]\n Z_to_add['value']=new_Z_names\n #Y_to_add=self.module1.matrices[indexer]['Z'][~self.module1.matrices[indexer]['Z']['value'].isin(exclude_list)]\n \n \n return Z_to_add\n \n def get_Y(self,file,indexer):\n data=self.load_to_obj(file)\n previous_exp_index=int(self.rownames_nominal[-1].split('_')[-1])\n current_exp_index=previous_exp_index+1\n exclude_list=[]\n A=[]\n N=[]\n Ea=[]\n for i in np.arange(self.num_rxns):\n A=A+['A_'+str(i)]\n for i in np.arange(self.num_rxns): \n N=N+['n_'+str(i)]\n for i in np.arange(self.num_rxns):\n Ea=Ea+['Ea_'+str(i)]\n exclude_list=A+N+Ea\n #print(exclude_list)\n Y_to_add=self.doe_obj.experiment_matrices[indexer]['Y'][~self.doe_obj.experiment_matrices[indexer]['Y']['value'].isin(exclude_list)].copy()\n new_Y_names=[]\n for j,item in enumerate(list(Y_to_add['value'])):\n temp=item.split('_')\n if 'experiment' in temp[-1]:\n temp2=re.split('(\\d+)',temp[-1])\n #print(temp2)\n temp2[-2]=str(current_exp_index)\n temp[-1]=''.join(temp2)\n \n else:\n temp[-1]=str(current_exp_index)\n new_Y_names=new_Y_names+['_'.join(temp)]\n Y_to_add['value']=new_Y_names\n #Y_to_add=self.module1.matrices[indexer]['Z'][~self.module1.matrices[indexer]['Z']['value'].isin(exclude_list)]\n \n \n return Y_to_add\n \n def get_X_names(self, Z):\n for i, item in enumerate(list(Z['value'])):\n if 'T_experiment' in item:\n start_exp=i\n break\n \n X_values=list(Z['value'])[start_exp:]\n return X_values\n \n def construct_Z_new(self,add_Z,Z):\n new_Z=pd.concat([Z,add_Z],ignore_index=True)\n return new_Z\n \n def construct_Y_new(self,add_Y,Y):\n new_Y=pd.concat([Y,add_Y],ignore_index=True)\n return new_Y\n \n # def get_S_block(self,col_min,col_max,row_min,row_max, S):\n # #print(np.shape(S))\n # #return S[row_min:row_max,col_min:col_max]\n # return S[col_min:col_max,row_min:row_max]\n def get_S_block(self,col_min,col_max,row_min,row_max, S,flag=False,X_add=None):\n #print(np.shape(S))\n #return S[row_min:row_max,col_min:col_max]\n y_len=3*self.num_rxns+len(self.inputs['observables'])+X_add\n if flag:\n #y_len=len(self.doe_obj.Y_original)\n #print(\"Fuckshit is : \"+str(y_len))\n temp_S=np.zeros((3*self.num_rxns+len(self.inputs['observables'])+X_add,3*self.num_rxns+X_add))\n indices=np.arange(y_len-len(self.inputs['observables']))\n temp_S[indices+len(self.inputs['observables']),indices]=1.0\n temp_S[0:len(self.inputs['observables']),0:np.shape(S)[1]]=S\n #print(temp_S)\n S=temp_S\n #print(col_min,col_max,row_min,row_max)\n #print(np.shape(temp_S))\n #print(np.shape(S))\n return S[col_min:col_max,row_min:row_max]\n\n # def get_new_S_chunks(self,rxn_count,X_add,Y_add,add_Z,S_current,Y,Z,S_new):\n # #print(np.shape(S_current),np.shape(S_new))\n \n \n # S1_new=self.get_S_block(0,self.experiment_length,0,3*self.num_rxns,S_new)\n # S2_new=self.get_S_block(0, self.experiment_length, 3*self.num_rxns, 3*self.num_rxns+len(X_add)+1, S_new)\n # #print(np.shape(S1_new))\n # #print(np.shape(S2_new))\n # S3_new=self.get_S_block(self.experiment_length,self.experiment_length+3*self.num_rxns,\n # 3*self.num_rxns,3*self.num_rxns+len(X_add)+1,S_new)\n # #print(np.shape(S3_new))\n # S4_new=self.get_S_block(self.experiment_length+3*self.num_rxns,\n # self.experiment_length+3*self.num_rxns+len(X_add)+1,\n # 0,3*self.num_rxns,S_new)\n # #print(np.shape(S4_new))\n # S5_new=self.get_S_block(self.experiment_length+3*self.num_rxns,\n # self.experiment_length+3*self.num_rxns+len(X_add)+1,\n # 3*self.num_rxns,3*self.num_rxns+len(X_add)+1,S_new)\n # #print(np.shape(S5_new))\n # #print(S5_new)\n # return (S1_new,S2_new,S3_new,S4_new,S5_new)\n def get_new_S_chunks(self,rxn_count,X_add,Y_add,add_Z,S_current,Y,Z,S_new):\n #print(np.shape(S_current),np.shape(S_new))\n #time.sleep(5)\n #print(np.shape(S_new))\n with open(os.path.join(os.getcwd(),'log.txt'),'a') as f:\n f.write(str(np.shape(S_new)))\n f.write('\\n')\n #print(S_new)\n #print(\"Length is: \"+str(self.experiment_length))\n S1_new=self.get_S_block(0,self.experiment_length,0,3*self.num_rxns,S_new,X_add=len(X_add))\n #print('EXP Length',self.experiment_length)\n S2_new=self.get_S_block(0, self.experiment_length, 3*self.num_rxns, 3*self.num_rxns+len(X_add)+1, S_new,X_add=len(X_add))\n #print(np.shape(S1_new))\n #print(np.shape(S2_new))\n #print(self.experiment_length,self.experiment_length+3*self.num_rxns,\n # 3*self.num_rxns,3*self.num_rxns+len(X_add)+1)\n S3_new=self.get_S_block(self.experiment_length,self.experiment_length+3*self.num_rxns,\n 3*self.num_rxns,3*self.num_rxns+len(X_add)+1,S_new,flag=True,X_add=len(X_add))\n #print(np.shape(S3_new))\n S4_new=self.get_S_block(self.experiment_length+3*self.num_rxns,\n self.experiment_length+3*self.num_rxns+len(X_add)+1,\n 0,3*self.num_rxns,S_new,flag=True,X_add=len(X_add))\n #print(np.shape(S4_new))\n S5_new=self.get_S_block(self.experiment_length+3*self.num_rxns,\n self.experiment_length+3*self.num_rxns+len(X_add)+1,\n 3*self.num_rxns,3*self.num_rxns+len(X_add)+1,S_new,flag=True,X_add=len(X_add))\n #print(np.shape(S5_new))\n #print(S5_new)\n return (S1_new,S2_new,S3_new,S4_new,S5_new)\n \n def get_exp_length(self,file):\n data=self.load_to_obj(file)\n mol_length=0\n conc_length=0\n for i,item in enumerate(data['datapoints']['mole-fraction']):\n if item['csvfile'] != None:\n mol_length=mol_length+1\n for i,item in enumerate(data['datapoints']['concentration']):\n if item['csvfile'] != None:\n conc_length=conc_length+1\n \n return mol_length+conc_length\n \n def get_prior_exp_len(self,priorY):\n #print(len(priorY))\n for i,item in enumerate(list(priorY['value'])):\n if 'A_' in item:\n end_exp_index=i\n break\n return len(list(priorY['value'])[0:end_exp_index])\n \n def get_prior_phys_param_len(self,priorY):\n #print(priorY)\n for i,item in enumerate(list(priorY['value'])):\n if 'Ea_' in item:\n final_Ea=i\n if self.inputs['MSI_settings']['rate_constant_targets'] != '':\n targets=pd.read_csv(os.path.join(self.inputs['working_dir'],\n self.inputs['MSI_settings']['rate_constant_targets']))\n target_length=len(targets['Reaction'])\n \n elif self.inputs['MSI_settings']['rate_constant_targets'] == '':\n target_length=0\n return len(list(priorY['value'])[final_Ea+1:])-target_length\n \n \n def construct_zeroes(self,S3,S1,S4,countV=0,countH=0):\n prior_exp_len=self.get_prior_exp_len(self.doe_obj.Y_original)\n Z1=np.zeros((prior_exp_len,np.shape(S3)[1]))\n prior_phys_params=self.get_prior_phys_param_len(self.doe_obj.Y_original)\n #Need to get length of targets for Z2\n if self.inputs['MSI_settings']['rate_constant_targets'] != '':\n targets=pd.read_csv(os.path.join(self.inputs['working_dir'],\n self.inputs['MSI_settings']['rate_constant_targets']))\n target_length=len(targets['Reaction'])\n \n elif self.inputs['MSI_settings']['rate_constant_targets'] == '':\n target_length=0\n \n #print(prior_phys_params,target_length)\n Z2=np.zeros((prior_phys_params+target_length+countV,np.shape(S3)[1]))\n Z3=np.zeros((np.shape(S1)[0],prior_phys_params+countH))\n Z4=np.zeros((np.shape(S4)[0],prior_phys_params+countH))\n \n return (Z1,Z2,Z3,Z4)\n \n \n \n def build_S(self,S1,S2,S3,S4,S5,S_old,countV=0,countH=0):\n \n Z1,Z2,Z3,Z4=self.construct_zeroes(S3,S1,S4,countV=countV,countH=countH)\n #print(np.shape(Z1))\n #print(np.shape(S3))\n #print(np.shape(Z2))\n block1=np.block([[Z1],[S3],[Z2]])\n block2=np.block([[S1,Z3,S2],[S4,Z4,S5]])\n #print(np.shape(Z2),np.shape(Z3),np.shape(Z4))\n \n #print('S',np.shape(S_old))\n #print('Z1',np.shape(Z1))\n # print('S3',np.shape(S3))\n # print('Z2',np.shape(Z2))\n # print('S1',np.shape(S1))\n # print('Z3',np.shape(Z3))\n # print('S2',np.shape(S2))\n # print('S4',np.shape(S4))\n # print('Z4',np.shape(Z4))\n # print('S5',np.shape(S5))\n #print(countV)\n #print(np.shape(block1))\n #print(np.shape(block2),'s')\n #print(np.shape(S_old))\n S=np.block([[S_old,block1],[block2]])\n return S\n \n def get_covariance(self,s):\n c = np.dot(np.transpose(s),s)\n c = np.linalg.inv(c)\n \n \n return (c)\n def return_posteriors(self,c,Z):\n covariance_posterior_df = pd.DataFrame(c)\n covariance_posterior_df.columns = Z\n covariance_posterior_df.reindex(labels = Z)\n posterior_diag = np.diag(c)\n posterior_sigmas = np.sqrt(posterior_diag)\n posterior_sigmas_df = pd.DataFrame({'parameter': Z,'value': posterior_sigmas.reshape((posterior_sigmas.shape[0],))})\n posterior_diag_df = pd.DataFrame({'parameter': Z,'value': posterior_diag.reshape((posterior_diag.shape[0],))})\n sorted_posterior_diag = posterior_diag_df.sort_values(by=['value'])\n \n def get_normalized_S(self,S,Z,Y):\n \n s=S/np.array(Z['Uncertainty'])[:,None]\n return s\n \n def calculate_sigmas_for_rate_constants(self,k_target_value_S_matrix,\n k_target_values_parsed_csv,\n unique_reactions,\n gas,\n covariance):\n\n \n reaction_list_from_mechanism = gas.reaction_equations()\n sigma_list_for_target_ks = [[] for reaction in range(len(unique_reactions))]\n shape = k_target_value_S_matrix.shape\n #print(unique_reactions)\n for row in range(shape[0]):\n #print(k_target_value_S_matrix,'blahasfjhbjhb')\n SC = np.dot(k_target_value_S_matrix[row,:],covariance)\n sigma_k = np.dot(SC,np.transpose(k_target_value_S_matrix[row,:]))\n sigma_k = np.sqrt(sigma_k)\n #print(row)\n #print(k_target_values_parsed_csv['Reaction'][row])\n indx = reaction_list_from_mechanism.index(k_target_values_parsed_csv['Reaction'][row])\n sigma_list_for_target_ks[unique_reactions.index(indx)].append(sigma_k)\n \n return sigma_list_for_target_ks\n \n def get_k_block(self,S):\n if self.inputs['MSI_settings']['rate_constant_targets'] != '':\n targets=pd.read_csv(os.path.join(self.inputs['working_dir'],\n self.inputs['MSI_settings']['rate_constant_targets']))\n target_length=len(targets['Reaction'])\n \n return S[len(S[:,0])-target_length:,:]\n \n def get_k_block_proposed(self,S,S_old):\n if self.inputs['MSI_settings']['rate_constant_targets'] != '':\n targets=pd.read_csv(os.path.join(self.inputs['working_dir'],\n self.inputs['MSI_settings']['rate_constant_targets']))\n target_length=len(targets['Reaction'])\n \n return S[len(S_old[:,0])-target_length:len(S_old[:,0]),:]\n \n def get_unique_elements(self,l,gas):\n \n uniques=[]\n for i,item in enumerate(l):\n index=list(gas.reaction_equations()).index(item)\n if index not in uniques:\n uniques=uniques+[index]\n return uniques\n\n\n\n\n def calculate_sigma(self,S_row,C):\n SC = np.dot(S_row,C)\n sigma = np.dot(SC,np.transpose(S_row))\n sigma = np.sqrt(sigma)\n return sigma\n\n\n def get_ignition_block(self,S):\n exp_len=self.get_prior_exp_len(self.doe_obj.Y_original)\n\n ig_block=S[exp_len-1,:]\n\n return ig_block\n\n\n def load_to_obj(self, path:str = ''):\n \"\"\"\n Takes in a file path for a yaml file and returns a dictionary of \n simulation information.\n\n Parameters\n ----------\n path : str, optional\n The path to where the yaml file is stored. The default is ''.\n\n Returns\n -------\n config : dictionary\n An unorganized dictionary that contains information reguarding\n the experiment the yaml input file was written for.\n\n \"\"\"\n with open(path) as f:\n config = yaml.load(f,Loader=yaml.FullLoader)\n return config\n\n\n def get_yaml_conditions(self,fname):\n\n template=self.load_to_obj(fname)\n outputs={}\n outputs['temperature']=float(template['common-properties']['temperature']['value-list'][0])\n outputs['pressure']=float(template['common-properties']['pressure']['value'])\n outputs['residence-time']=float(template['apparatus']['residence-time']['value'])\n for i,spec in enumerate(template['common-properties']['composition']):\n outputs[spec['species']]=spec['mole-fraction']\n \n return outputs\n \n \n def load_to_obj(self, path:str = ''):\n \"\"\"\n Takes in a file path for a yaml file and returns a dictionary of \n simulation information.\n\n Parameters\n ----------\n path : str, optional\n The path to where the yaml file is stored. The default is ''.\n\n Returns\n -------\n config : dictionary\n An unorganized dictionary that contains information reguarding\n the experiment the yaml input file was written for.\n\n \"\"\"\n with open(path) as f:\n config = yaml.load(f,Loader=yaml.FullLoader)\n return config\n \n \n def get_rankings(self,excluded_yamls,S,iteration,countH=0,countV=0,Z_prev=None,Y_prev=None,X_prev=None):\n #self.up()\n #sub = progressbar.ProgressBar(maxval=len(self.module1.yaml_file_list))\n #sub.start()\n #if self.subloopBool:\n self.subloop=self.manager.counter(total=len(self.doe_obj.experiment_matrices),desc='Possible experiments',unit='Experiments',color='red',leave=True)\n #self.subloopBool=False\n ranking_list=[]\n self.rownames_nominal,self.colnames_nominal=self.get_S_current_columns(doe_obj=self.doe_obj)\n self.mech=os.path.join(self.inputs['working_dir'],self.inputs['MSI_settings']['chemical_model'])\n gas=ct.Solution(self.mech)\n self.num_rxns=len(gas.reactions())\n if re.match('[Rr]ate[-_ ][Cc]onstant',self.inputs['quantity_of_interest']):\n k_block_og=self.get_k_block(self.doe_obj.S_original)\n targets=pd.read_csv(os.path.join(self.inputs['working_dir'],\n self.inputs['MSI_settings']['rate_constant_targets']))\n sigma_list_og=self.calculate_sigmas_for_rate_constants(k_block_og,\n targets,\n self.get_unique_elements(list(targets['Reaction']),gas),\n gas,\n self.doe_obj.covar_original)\n target_reaction=self.inputs['target_reaction']['equation']\n target_index=list(gas.reaction_equations()).index(target_reaction)\n sigma_list_index=self.get_unique_elements(list(targets['Reaction']),gas).index(target_index)\n #print(sigma_list[sigma_list_index][0])\n original_posterior=sigma_list_og[sigma_list_index][0]\n\n elif re.match('[Ii]gnition[-_ ][Dd]elay',self.inputs['quantity_of_interest']):\n '''This block collects the original uncertainty in the ignition delay quantity of interest. Gets the final experiment line\n and estimates the uncertainty in the ignition delay.'''\n\n ig_block_og=self.get_ignition_block(self.doe_obj.S_original)\n print(ig_block_og)\n #print(self.module0.)\n sigma_ig=self.calculate_sigma(ig_block_og,self.doe_obj.covar_original)\n original_posterior=sigma_ig\n\n final_yamls=[]\n for i,file in enumerate(self.doe_obj.experiment_yamls):\n \n if file not in excluded_yamls:\n final_yamls.append(file)\n print('File is:'+str(file))\n data=self.load_to_obj(os.path.join(self.inputs['working_dir'],file))\n #parametersX,parametersY,parametersZ=self.get_experiment_columns(os.path.join(self.module1.input_options['working_dir'],file),i)\n parametersZ=self.get_Z(os.path.join(self.inputs['working_dir'],file),i)\n parametersY=self.get_Y(os.path.join(self.inputs['working_dir'],file),i)\n if iteration==0:\n \n #print(parametersZ)\n self.experiment_length=self.get_exp_length(os.path.join(self.inputs['working_dir'],file))\n #print(self.experiment_length)\n X_to_add=self.get_X_names(parametersZ)\n \n new_Z=self.construct_Z_new(parametersZ,self.doe_obj.Z_original)\n \n new_Y=self.construct_Y_new(parametersY,self.doe_obj.Y_original)\n \n elif iteration>0:\n new_Z=self.construct_Z_new(parametersZ,Z_prev)\n X_to_add=self.get_X_names(parametersZ)\n new_Y=self.construct_Y_new(parametersY,Y_prev)\n self.experiment_length=self.get_exp_length(os.path.join(self.inputs['working_dir'],file))\n S1_new,S2_new,S3_new,S4_new,S5_new=self.get_new_S_chunks(self.num_rxns,X_to_add,parametersY,parametersZ,\n self.doe_obj.S_original,\n self.doe_obj.Y_original,\n self.doe_obj.Z_original,\n self.doe_obj.experiment_matrices[i]['S'])\n #print(self.module0.initial_optimization.Y_data_frame['value'][635:])\n #print('CountH: '+str(countH)+', countV: '+str(countV))\n S_proposed=self.build_S(S1_new,S2_new,S3_new,S4_new,S5_new,S,countH=countH,countV=countV)\n\n if iteration==0:\n new_X_list=list(self.doe_obj.X_original['value'])+X_to_add\n elif iteration>0:\n new_X_list=X_prev+X_to_add\n #print(list(self.module0.initial_optimization.z_data_frame['value']))\n #print(np.shape(S_proposed))\n #print(self.module0.initial_optimization.z_data_frame)\n #print(len(new_Z),np.shape(S_proposed))\n \n s=self.get_normalized_S(S_proposed, new_Z, new_Y)\n c=self.get_covariance(s)\n #print(c)\n self.updated_c=c\n #print(np.shape(c))\n if re.match('[Rr]ate[-_ ][Cc]onstant',self.inputs['quantity_of_interest']):\n k_block=self.get_k_block_proposed(S_proposed,self.doe_obj.S_original)\n targets=pd.read_csv(os.path.join(self.inputs['working_dir'],\n self.inputs['MSI_settings']['rate_constant_targets']))\n sigma_list=self.calculate_sigmas_for_rate_constants(k_block,\n targets,\n self.get_unique_elements(list(targets['Reaction']),gas),\n gas,\n c)\n #print(sigma_list)\n target_reaction=self.inputs['target_reaction']['equation']\n target_index=list(gas.reaction_equations()).index(target_reaction)\n sigma_list_index=self.get_unique_elements(list(targets['Reaction']),gas).index(target_index)\n #print(sigma_list[sigma_list_index][0],'text')\n ranking_list=ranking_list+[sigma_list[sigma_list_index][0]/original_posterior]\n #print(sigma_list,'poo')\n elif re.match('[Ii]gnition[-_ ][Dd]elay',self.inputs['quantity_of_interest']):\n print('Entered correct statement')\n ig_block=self.get_ignition_block(S_proposed)\n if i==len(self.doe_obj.experiment_yamls)-1:\n print(ig_block)\n sigma=self.calculate_sigma(ig_block,c)\n ranking_list=ranking_list+[sigma/original_posterior]\n #elif re.match('[Ii]gnition[_ -][Dd]elay',self.module0.startup_data['quantity_of_interest']):\n #if np.remainder(i,10)==0:\n #sub.update(i)\n self.subloop.update()\n #sub.finish()\n #print(ranking_list)\n output_ranking=pd.DataFrame(columns=['experiment','ratio'])\n output_ranking['experiment']=final_yamls\n temps=[]\n pres=[]\n restime=[]\n conds=self.get_yaml_conditions(os.path.join(self.inputs['working_dir'],final_yamls[0]))\n species_index=copy.deepcopy(list(conds.keys()))\n #print(list(conds.keys()).remove('temperature'))\n species_index.remove('temperature')\n species_index.remove('pressure')\n species_index.remove('residence-time')\n specs={}\n for i,spec in enumerate(species_index):\n specs[spec]=[]\n for i,fname in enumerate(final_yamls):\n conds=self.get_yaml_conditions(os.path.join(self.inputs['working_dir'],fname))\n temps.append(conds['temperature'])\n pres.append(conds['pressure'])\n restime.append(conds['residence-time'])\n for k,spec in enumerate(species_index):\n specs[spec].append(conds[spec])\n #print(ranking_list)\n output_ranking['ratio']=ranking_list\n output_ranking['temperature']=temps\n output_ranking['pressure']=pres\n output_ranking['residence-time']=restime\n for i,spec in enumerate(species_index):\n output_ranking[spec]=specs[spec]\n output_ranking.sort_values(by='ratio',ascending=True,inplace=True)\n\n #output_ranking.to_csv(os.path.join(self.module0.startup_data['working_dir'],\n #'output_rankings.csv'),index=False)\n #print(output_ranking)\n #print(output_ranking)\n return output_ranking\n #posteriors=self.return_posteriors(c,new_Z)\n #posteriors.to_csv('test.csv')\n #print(c)\n #print(new_S[687:])\n #print(X_to_add)\n #print(parametersY)\n #print('x',parametersX)\n #print('y',parametersY)\n #print('z',parametersZ)","sub_path":"ranking_method1.py","file_name":"ranking_method1.py","file_ext":"py","file_size_in_byte":34968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"540447348","text":"#!/usr/bin/env python3\n\nimport argparse\nfrom collections import namedtuple\nfrom shard_prometheus_utils import handle_install, install_parser, \\\n handle_upgrade, upgrade_parser, handle_delete, delete_parser\n\nCommandHandler = namedtuple('CommandHandler', ['handler', 'parser'])\n\nops = {\n 'install': CommandHandler(handle_install, install_parser),\n 'upgrade': CommandHandler(handle_upgrade, upgrade_parser),\n 'delete': CommandHandler(handle_delete, delete_parser)\n}\n\n\n \ndef parse_args():\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n subparsers = parser.add_subparsers(help='install prometheus and thanos',\n dest=\"subcommand\")\n for key in ops:\n ops[key].parser(subparsers, key)\n\n return parser.parse_args() \n\ndef main():\n args = parse_args()\n ops[args.subcommand].handler(args)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"charts/prometheus/shard_prometheus.py","file_name":"shard_prometheus.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"298241369","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Aug 11 16:58:17 2018\n\n@author: danpal\n\"\"\"\n\nfrom Bio import SeqIO\nfrom Bio.SeqRecord import SeqRecord\n\n\nclass Concatemer:\n def __init__(self, name, mers):\n self.name = name\n self.mers = mers\n\n @property\n def name(self):\n return self._name\n\n @name.setter\n def name(self, new):\n if type(new) == str:\n self._name = new\n else:\n raise ValueError('The name must be a string.')\n\n @property\n def mers(self):\n return self._mers\n\n @mers.setter\n def mers(self, new):\n if (type(new) == dict\n and all([type(v) == SeqRecord for v in new.values()])\n and all([type(k) == str for k in new.keys()])):\n self._mers = new\n else:\n raise ValueError('\"mers\" must be a dict with the format:'\n + ' {str: SeqRecor}')\n\n def containsMers(self, mers_list):\n check = True\n for mer in mers_list:\n if mer not in self.mers:\n print(f'There is no \"{mer}\" mer in \"{self.name}\"')\n check = False\n return check\n\n def getConcatemer(self, mers_list=None, return_mers=False):\n if mers_list is None:\n mers = list(self.mers.keys())\n else:\n if self.containsMers(mers_list):\n mers = mers_list\n else:\n raise ValueError('Some specified mers are not present.')\n conc = ''\n for mer in mers:\n conc += str(self.mers[mer].seq)\n if return_mers:\n return conc, mers\n else:\n return conc\n\n def printConcatemer(self, mers_list=None):\n print(self.getConcatemer(mers_list))\n\n def writeConcatemer(self, file, mers_list=None, mode='a'):\n conc, mers = self.getConcatemer(mers_list, return_mers=True)\n with open(file, mode) as f:\n f.write(f'>{self.name} {\" \".join(mers)}\\n{conc}\\n')\n\n def __repr__(self):\n return f'Concatemer({self.name}, {self.mers})'\n\n def __str__(self):\n return f''\n\n def __len__(self):\n return len(self.mers)\n\n\ndef getSequences(file):\n return SeqIO.parse(file, \"fasta\")\n\n\ndef clusterDescriptions(sequences, fields=slice(1, -1)):\n clusters = {}\n for seq in sequences:\n name = ' '.join(seq.description.split()[fields])\n if name not in clusters:\n clusters[name] = [seq]\n else:\n clusters[name].append(seq)\n return clusters\n\n\ndef makeConcatemer(clusters, name, mers_list):\n mers = {}\n for mer in mers_list:\n for seq in clusters[name]:\n if seq.description.split()[-1] == mer:\n mers[mer] = seq\n if mer not in mers:\n print(f'WARNING: \"{mer}\" could not be found for \"{name}\".')\n return Concatemer(name, mers)\n\n\ndef getConcatemers(file,\n mers_list=None,\n fields=slice(1, -1)):\n \"\"\"mers_list (default: ['PB2', 'PB1', 'PA', 'HA', 'NP',\n 'NA', 'M1', 'M2', 'NS1', 'NS2']\"\"\"\n seq_iter = getSequences(file)\n clusters = clusterDescriptions(seq_iter, fields)\n if mers_list is None:\n mers_list = ['PB2', 'PB1', 'PA', 'HA', 'NP',\n 'NA', 'M1', 'M2', 'NS1', 'NS2']\n return [makeConcatemer(clusters, name, mers_list) for name in clusters]\n\n\ndef writeConcatemers(in_file,\n out_file,\n mers_list=None,\n fields=slice(1, -1)):\n concatemers = getConcatemers(in_file, mers_list, fields)\n for conc in concatemers:\n try:\n conc.writeConcatemer(out_file, mers_list)\n except ValueError as error:\n print(f'The concatemer of is \"{conc.name}\" is not been written'\n + f' because: {error}')\n\n\nif __name__ == '__main__':\n path = \"/home/danpal/Unidad/05_virus/influenza/\"\n in_file = path + \"inf.fa\"\n mers_list = ['PB2', 'PB1', 'HA']\n out_file = path + \"test2.fa\"\n# c = getConcatemers(in_file)\n# a = c[0]\n writeConcatemers(in_file, out_file, mers_list)\n","sub_path":"python/cluster/fasta_desc.py","file_name":"fasta_desc.py","file_ext":"py","file_size_in_byte":4180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"443892259","text":"# Copyright 2018 Tensorforce Team. 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 collections import OrderedDict\n\nimport tensorflow as tf\n\nfrom tensorforce import util\nfrom tensorforce.core import Module\n\n\nclass CircularBuffer(Module):\n \"\"\"\n Circular buffer.\n\n Args:\n name (string): Buffer name\n (internal use).\n capacity (int > 0): Buffer capacity\n (required).\n values_spec (specification): Values specification\n (internal use).\n return_overwritten (bool): Whether to return overwritten values\n (default: false).\n initializers (dict[values]): Buffer initializers\n (internal use).\n device (string): Device name\n (default: inherit value of parent module).\n summary_labels ('all' | iter[string]): Labels of summaries to record\n (default: inherit value of parent module).\n \"\"\"\n\n def __init__(\n self, name, capacity, values_spec, return_overwritten=False, initializers=None,\n device=None, summary_labels=None\n ):\n super().__init__(name=name, device=device, summary_labels=summary_labels)\n\n self.values_spec = values_spec\n self.capacity = capacity\n self.return_overwritten = return_overwritten\n self.initializers = OrderedDict() if initializers is None else initializers\n\n def tf_initialize(self):\n super().tf_initialize()\n\n # Value buffers\n self.buffers = OrderedDict()\n for name, spec in self.values_spec.items():\n if util.is_nested(name=name):\n self.buffers[name] = OrderedDict()\n for inner_name, spec in spec.items():\n shape = (self.capacity,) + spec['shape']\n initializer = self.initializers.get(inner_name, 'zeros')\n self.buffers[name][inner_name] = self.add_variable(\n name=(inner_name + '-buffer'), dtype=spec['type'], shape=shape,\n is_trainable=False, initializer=initializer\n )\n else:\n shape = (self.capacity,) + spec['shape']\n initializer = self.initializers.get(name, 'zeros')\n self.buffers[name] = self.add_variable(\n name=(name + '-buffer'), dtype=spec['type'], shape=shape, is_trainable=False,\n initializer=initializer\n )\n\n # Buffer index (modulo capacity, next index to write to)\n self.buffer_index = self.add_variable(\n name='buffer-index', dtype='long', shape=(), is_trainable=False, initializer='zeros'\n )\n\n def tf_reset(self):\n # Constants\n zero = tf.constant(value=0, dtype=util.tf_dtype(dtype='long'))\n capacity = tf.constant(value=self.capacity, dtype=util.tf_dtype(dtype='long'))\n\n if not self.return_overwritten:\n # Reset buffer index\n assignment = self.buffer_index.assign(value=zero, read_value=False)\n\n # Return no-op\n with tf.control_dependencies(control_inputs=(assignment,)):\n return util.no_operation()\n\n # Overwritten buffer indices\n num_values = tf.minimum(x=self.buffer_index, y=capacity)\n indices = tf.range(start=(self.buffer_index - num_values), limit=self.buffer_index)\n indices = tf.mod(x=indices, y=capacity)\n\n # Get overwritten values\n values = OrderedDict()\n for name, buffer in self.buffers.items():\n if util.is_nested(name=name):\n values[name] = OrderedDict()\n for inner_name, buffer in buffer.items():\n values[name][inner_name] = tf.gather(params=buffer, indices=indices)\n else:\n values[name] = tf.gather(params=buffer, indices=indices)\n\n # Reset buffer index\n with tf.control_dependencies(control_inputs=util.flatten(xs=values)):\n assignment = self.buffer_index.assign(value=zero, read_value=False)\n\n # Return overwritten values\n with tf.control_dependencies(control_inputs=(assignment,)):\n return util.fmap(function=util.identity_operation, xs=values)\n\n def tf_enqueue(self, **values):\n # Constants\n zero = tf.constant(value=0, dtype=util.tf_dtype(dtype='long'))\n capacity = tf.constant(value=self.capacity, dtype=util.tf_dtype(dtype='long'))\n\n # Get number of values\n for value in values.values():\n if not isinstance(value, dict):\n break\n elif len(value) > 0:\n value = next(iter(value.values()))\n break\n if util.tf_dtype(dtype='long') in (tf.int32, tf.int64):\n num_values = tf.shape(input=value, out_type=util.tf_dtype(dtype='long'))[0]\n else:\n num_values = tf.dtypes.cast(\n x=tf.shape(input=value)[0], dtype=util.tf_dtype(dtype='long')\n )\n\n # Check whether instances fit into buffer\n assertion = tf.debugging.assert_less_equal(x=num_values, y=capacity)\n\n if self.return_overwritten:\n # Overwritten buffer indices\n with tf.control_dependencies(control_inputs=(assertion,)):\n start = tf.maximum(x=self.buffer_index, y=capacity)\n limit = tf.maximum(x=(self.buffer_index + num_values), y=capacity)\n num_overwritten = limit - start\n indices = tf.range(start=start, limit=limit)\n indices = tf.mod(x=indices, y=capacity)\n\n # Get overwritten values\n with tf.control_dependencies(control_inputs=(indices,)):\n overwritten_values = OrderedDict()\n for name, buffer in self.buffers.items():\n if util.is_nested(name=name):\n overwritten_values[name] = OrderedDict()\n for inner_name, buffer in buffer.items():\n overwritten_values[name][inner_name] = tf.gather(\n params=buffer, indices=indices\n )\n else:\n overwritten_values[name] = tf.gather(params=buffer, indices=indices)\n\n else:\n overwritten_values = (assertion,)\n\n # Buffer indices to (over)write\n with tf.control_dependencies(control_inputs=util.flatten(xs=overwritten_values)):\n indices = tf.range(start=self.buffer_index, limit=(self.buffer_index + num_values))\n indices = tf.mod(x=indices, y=capacity)\n indices = tf.expand_dims(input=indices, axis=1)\n\n # Write new values\n with tf.control_dependencies(control_inputs=(indices,)):\n assignments = list()\n for name, buffer in self.buffers.items():\n if util.is_nested(name=name):\n for inner_name, buffer in buffer.items():\n assignment = buffer.scatter_nd_update(\n indices=indices, updates=values[name][inner_name]\n )\n assignments.append(assignment)\n else:\n assignment = buffer.scatter_nd_update(indices=indices, updates=values[name])\n assignments.append(assignment)\n\n # Increment buffer index\n with tf.control_dependencies(control_inputs=assignments):\n assignment = self.buffer_index.assign_add(delta=num_values, read_value=False)\n\n # Return overwritten values or no-op\n with tf.control_dependencies(control_inputs=(assignment,)):\n if self.return_overwritten:\n any_overwritten = tf.math.greater(x=num_overwritten, y=zero)\n overwritten_values = util.fmap(\n function=util.identity_operation, xs=overwritten_values\n )\n return any_overwritten, overwritten_values\n else:\n return util.no_operation()\n","sub_path":"tensorforce/core/utils/circular_buffer.py","file_name":"circular_buffer.py","file_ext":"py","file_size_in_byte":8898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"274573058","text":"#!/usr/bin/env python2\n\n\"\"\"\nOffboard control\n\"\"\"\n\nfrom __future__ import print_function\nimport sys\nfrom time import sleep\n\nimport rospy\nfrom rospy.exceptions import ROSException\nfrom mavros_msgs.srv import SetMode, CommandBool, CommandTOL\nimport mavros\nfrom mavros import setpoint as sp\n\ndef main(): # YOLO pylint: disable=too-many-statements\n\n # initialize mavros namespace\n mavros.set_namespace()\n\n # we have a name\n rospy.init_node(\"control\", anonymous=True)\n\n # check if \"set mode\" service is up\n service = \"/mavros/set_mode\"\n try:\n rospy.wait_for_service(service, timeout=2)\n except ROSException:\n print(\"could not find \"+str(service)+\" service. Make sure you are \"\n \"running mavros and that it's connected to Ardupilot SITL\",\n file=sys.stderr)\n print(\"Found service\", service)\n\n # prepare to set mode\n # (http://wiki.ros.org/rospy/Overview/Services)\n set_mode = rospy.ServiceProxy(service, SetMode)\n\n # set mode\n # (http://docs.ros.org/jade/api/mavros_msgs/html/srv/SetMode.html)\n mode = \"GUIDED\"\n results = set_mode(0, mode)\n if results.mode_sent is True:\n print(\"mode set to {}\".format(mode))\n else:\n error(\"Could not set mode to {}, maybe check Ardupilot SITL output?\"\n .format(mode))\n\n # no stress\n sleep(1)\n\n # register arm throttle service\n arming = None\n arming = rospy.ServiceProxy(mavros.get_topic('cmd', 'arming'), CommandBool)\n if not arming:\n error(\"could not register arming service\")\n\n # arm throttle\n results = arming(value=True)\n if results.success:\n print(\"throttle armed\")\n else:\n error(\"could not arm thottle\")\n\n # no stress\n sleep(1)\n\n # register take off service\n takeoff = None\n takeoff = rospy.ServiceProxy(mavros.get_topic('cmd', 'takeoff'), CommandTOL)\n if not takeoff:\n error(\"could not register take off service\")\n\n # define home location\n # probably edit this to your home location\n # tip: use --map option with Ardupilot too see where your drone is located\n home_longitude = -35.36262688\n home_latitude = 149.165800\n\n # take off\n height = 10 # meters\n results = takeoff(min_pitch=10.0,\n yaw=0.0,\n latitude=home_latitude,\n longitude=home_longitude,\n altitude=height)\n if results.success:\n print(\"taking off ...\")\n else:\n print(\"couldn't execute takeoff but I'll assume we are already \"\n \"in the air ...\")\n #error(\"Could not take off\")\n print(results)\n\n for _ in range(3):\n print(\"wait for it ...\")\n sleep(4)\n\n # this didn't work ...\n #thrust_msg = sp.Thrust(header=sp.Header(frame_id='mavsetp', stamp=rospy.get_rostime()))\n #thrust_msg.thrust = 0.9\n #pub = sp.get_pub_attitude_throttle(queue_size=10, latch=True)\n #publish_once(pub, thrust_msg)\n\n # set velocity to something crazy\n x_vel = 0.0\n y_vel = 0.0\n z_vel = 10.0\n yaw_rate = 0\n vel_publisher = sp.get_pub_velocity_cmd_vel(queue_size=10, latch=True)\n vel_msg = sp.TwistStamped(header=sp.Header(frame_id='controller',\n stamp=rospy.get_rostime()))\n vel_msg.twist.linear = sp.Vector3(x=x_vel, y=y_vel, z=z_vel)\n vel_msg.twist.angular = sp.Vector3(z=yaw_rate)\n print(\"GO!\")\n publish_once(vel_publisher, vel_msg)\n print(\"STOOOPP!!!\")\n\ndef publish_once(pub, msg):\n \"\"\"\n publish once ...\n I copied this from:\n ./mavoff/src/mavros/mavros/scripts/mavsetp\n \"\"\"\n once_delay = 3\n pub.publish(msg)\n rospy.sleep(0.2)\n\n # stick around long enough for others to grab\n timeout_t = rospy.get_time() + once_delay\n while not rospy.is_shutdown() and rospy.get_time() < timeout_t:\n rospy.sleep(0.2)\n if pub.get_num_connections() < 1:\n print(\"Mavros not started, nobody subcsribes to\", pub.name)\n\ndef error(*msg):\n print(\"Error:\", *msg, file=sys.stderr)\n sys.exit(1)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/offboard/control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":4104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"312272549","text":"# encoding:utf-8\nimport cv2\nimport os\n\n\ndef isfile(src_path):\n if os.path.isfile(src_path):\n file_path = os.path.dirname(src_path) # 去掉文件名,返回所在目录\n\n cat_video(file_path)\n return True\n else:\n infile(src_path)\n return False\n\n\ndef infile(src_path):\n for item in os.listdir(src_path):\n file_path = os.path.join(src_path, item)\n paduan = isfile(file_path)\n if paduan:\n break\n\n\ndef cat_video(file_path):\n for videofile in os.listdir(file_path):\n print(videofile)\n imagefile_name = videofile.split(\".\")[0]\n imagefile_path = os.path.join(video_dst_path, imagefile_name)\n if not os.path.exists(imagefile_path):\n os.mkdir(imagefile_path)\n videofile_path = os.path.join(file_path, videofile)\n videoName = videofile_path.split(\"/\")[-1].split(\".\")[0]\n image_name = \"\"\n if nameLength != 0 or image_name != \"\":\n image_name = str(videoName)[0:nameLength]\n else:\n image_name = str(videoName)\n cap = cv2.VideoCapture(videofile_path)\n if cap.isOpened():\n rval, frame = cap.read()\n else:\n rval = False\n count = 1\n while rval:\n rval, frame = cap.read()\n imageName=f'img_{count:05d}.jpg'\n if count % stop == 0:\n try:\n cv2.imwrite(os.path.join(imagefile_path, imageName), frame)\n except:\n continue\n count += 1\n print(count)\n\n cap.release\n\n\nif __name__ == \"__main__\":\n video_path = \"/home/lishuang/Disk/dukto/异常行为采集\" # 视频路径\n video_dst_path = \"/home/lishuang/Disk/dukto/异常行为采集图片\" # 图片保存路径\n if not os.path.exists(video_dst_path):\n os.mkdir(video_dst_path)\n nameLength = 0 # 图片名长度 如果长度为0则使用视频原名\n stop = 1 # 视频截取帧数间隔\n isfile(video_path)\n","sub_path":"tools/customdata/catVideoToImage.py","file_name":"catVideoToImage.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"378995266","text":"import wx\nimport numpy as np\nfrom .matrix import MainPanel\nfrom .control import ControlPanel\n\n\nclass Panel(wx.Panel):\n\n\n\tdef __init__(self, parent, appConf, widgetConf):\n\t\tsuper().__init__(parent, size=(475, 300))\n\n\t\tself.Bind(wx.EVT_PAINT, self._OnPaint)\n\t\tself.Bind(wx.EVT_ERASE_BACKGROUND, self._OnEraseBackground)\n\t\tself.Bind(wx.EVT_BUTTON, self.OnButton)\n\n\n\t\tself.config = appConf\n\t\tself.widgetConf = widgetConf\n\n\t\tself.Display()\n\n\n\tdef Display(self):\n\n\t\tsizer = wx.BoxSizer(wx.VERTICAL)\n\t\tself.matrixPanel = MainPanel(self, self.config, self.widgetConf)\n\t\tself.controlPanel = ControlPanel(self, self.config, self.widgetConf, \n\t\t\t\t\t\t\t\t\t\t self.matrixPanel.matrix_a, \n\t\t\t\t\t\t\t\t\t\t self.matrixPanel.matrix_b, \n\t\t\t\t\t\t\t\t\t\t self.matrixPanel.matrix_c)\n\n\t\tsizer.Add(self.matrixPanel, 1, flag=wx.EXPAND)\n\t\tsizer.Add(self.controlPanel, 0, flag=wx.EXPAND)\n\n\t\tself.SetSizer(sizer)\n\t\tself.Layout()\n\n\tdef OnButton(self, e):\n\t\tname = e.GetEventObject().label\n\t\tif name == 'Calculate':\n\t\t\tMultiplyMatrices(self.matrixPanel.matrix_a, \n\t\t\t\t\t\t\t self.matrixPanel.matrix_b, \n\t\t\t\t\t\t\t self.matrixPanel.matrix_c)\n\n\n\n\tdef Draw(self, dc):\n\t\tdc.SetBackground(wx.Brush(self.config.get_color('color1', 'widget')))\n\t\tdc.Clear()\n\n\n\tdef _OnEraseBackground(self, e):\n\t\tpass\n\n\n\tdef _OnPaint(self, e):\n\t\tdc = wx.BufferedPaintDC(self)\n\t\tself.Draw(dc)\n\n\ndef MultiplyMatrices(matrix_a, matrix_b, out):\n\tA = np.array(matrix_a.ReadValues(), dtype=float)\n\tB = np.array(matrix_b.ReadValues(), dtype=float)\n\tC = A.dot(B)\n\tc_rows, c_cols = C.shape\n\tout.DisplayGrid(c_rows, c_cols)\n\tout.CalculateSize()\n\tout.WriteValues(C)","sub_path":"scienv/widgets/matrices/panel.py","file_name":"panel.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"302774469","text":"import requests\nfrom bs4 import BeautifulSoup\n\nurl = \"http://python123.io/ws/demo.html\"\nr = requests.get(url)\ndemo = r.text\nsoup = BeautifulSoup(demo, \"html.parser\")\n# print(soup.prettify())\nfor link in soup.find_all('a'):\n print(link.get('href'))\n\n","sub_path":"Requests/week2/extracthtml.py","file_name":"extracthtml.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"611661175","text":"# -*- coding:utf-8 -*-\nimport logging\ndef init_log(logfile):\n logger = logging.getLogger()\n hdlr = logging.FileHandler(logfile)\n formatter = logging.Formatter(\"%(asctime)s%(message)s\")\n hdlr.setFormatter(formatter)\n logger.addHandler(hdlr)\n logger.setLevel(logging.NOTSET)\n return logger\nif __name__==\"__main__\":\n file = r\"C:\\Users\\Wuxiaoshen\\Desktop\\test(1).py\"\n A=init_log(file)\n print(A.info(file))\n\n","sub_path":"001/009TestLog.py","file_name":"009TestLog.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"267160187","text":"import csv\nfrom datetime import datetime\n\nimport numpy\nimport pandas as pd\n\nfrom arasel_test.fields import OrderField, ModelField, CustomerField\nfrom arasel_test.utils import longest_dates_interval\n\n\n\nclass AraselETL:\n\n def __init__(self, csv_path, prediction_model):\n self.csv_path = csv_path\n self.prediction_model = prediction_model\n self._clvs = None\n\n @property\n def customer_clvs(self):\n \"\"\"\n Calculates based on customer orders and predition model, the Customer Lifetime Value\n\n :return: dictionary of customer_id: Customer Lifetime Value\n \"\"\"\n if self._clvs is not None:\n return self._clvs\n\n dtype_dict = OrderField.get_dtypes()\n df = pd.read_csv(self.csv_path, dtype=dtype_dict, parse_dates=[OrderField.created_at_date])\n\n grouped_df = df.groupby(OrderField.customer_id)\n\n max_num_items = grouped_df[OrderField.num_items].max()\n max_revenue = grouped_df[OrderField.revenue].max()\n total_revenue = grouped_df[OrderField.revenue].sum()\n total_orders = grouped_df[OrderField.order_id].count()\n\n until_date = datetime(2017, 10, 17)\n days_since_last_order = grouped_df[OrderField.created_at_date].max().apply(lambda x: (until_date - x).days)\n\n customer_order_dates = grouped_df[OrderField.created_at_date].apply(list)\n longest_intervals = customer_order_dates.apply(longest_dates_interval)\n\n transformed_df = pd.concat(\n [max_num_items, max_revenue, total_revenue, total_orders, days_since_last_order, longest_intervals],\n axis=1,\n keys=[ModelField.max_num_items, ModelField.max_revenue, ModelField.total_revenue,\n ModelField.total_orders, ModelField.days_since_last_order,\n ModelField.longest_intervals]\n )\n\n # NaN values in longest_intervals are the ones with only one order date (no possible interval)\n avg_longest_interval = longest_intervals.mean()\n transformed_df[ModelField.longest_intervals]\\\n .fillna(transformed_df[ModelField.days_since_last_order] + avg_longest_interval)\n\n clvs = self.prediction_model.predict(transformed_df.values)\n\n self._clvs = {customer_id: clv for customer_id, clv in zip(transformed_df.index, clvs)}\n\n return self._clvs\n\n def to_csv(self, path):\n \"\"\"Outputs CSL's to CSV file\"\"\"\n clvs = self.customer_clvs\n\n try:\n with open(path, 'w') as f:\n writer = csv.DictWriter(f, fieldnames=[CustomerField.customer_id, CustomerField.predicted_clv])\n writer.writeheader()\n\n for customer_id, clv in clvs.items():\n row = {\n CustomerField.customer_id: customer_id,\n CustomerField.predicted_clv: clv\n }\n writer.writerow(row)\n\n except OSError:\n print(\"Cannot open file to write: {}\".format(path))\n","sub_path":"arasel_test/arasel_etl.py","file_name":"arasel_etl.py","file_ext":"py","file_size_in_byte":3007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"470660896","text":"import os\nimport sys\nimport openalea.lpy as lpy\nimport openalea.plantgl.all as pgl\nfrom flask import Flask\nfrom flask import request, render_template, url_for, redirect, jsonify, session\nfrom flask import Markup\nfrom flask_socketio import SocketIO\nfrom threading import Lock\n\t\napp = Flask(__name__)\napp.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0\napp.secret_key = 'Iamasecretkey'\nsocketio = SocketIO(app)\nLSystem = None\nlock = Lock()\n\n@app.before_request\ndef make_session_permanent():\n session.permanent = False\n\nif __name__ == '__main__':\n\tapp.run(debug=True)\n\t#host=140.77.193.122\n\n@socketio.on('disconnect')\ndef disconnect():\n session.pop('step', None)\n session.pop('currentStep', None)\n session.pop('code', None)\n\n@app.route('/')\ndef home():\n\treturn render_template('home.html')\n\n@app.route('/editor.html')\ndef editor():\n return render_template('result.html')\n\n\n#When Run is clicked, the server receives the code, derive and interpret the LString and sends the result.\n\n@app.route('/run', methods=['POST'])\ndef run():\n\tout = sys.stdout\n\toutlog = open('outlog.txt', 'w')\n\tsys.stdout = outlog\n\n\tdisconnect()\n\tl = lpy.Lsystem()\n\tcode = request.form['code']\n\tcode = code.encode('ascii', 'ignore')\n\n\ttry:\n\t\tl.set(code)\n\texcept:\n\t\toutlog.close()\n\t\tsys.stdout = out\n\t\toutlog = open('outlog.txt', 'r')\n\t\toutput = outlog.read()\n\t\treturn jsonify({'error': \"Syntax Error\", 'output': output})\n\n\tlstring = l.derive()\n\tilstring = l.interpret(lstring)\n\ttxtlstring = str(ilstring)\n\t# txtlstring = lstringtojson(ilstring)\n\n\toutlog.close()\n\tsys.stdout = out\n\n\toutlog = open('outlog.txt', 'r')\n\toutput = outlog.read()\n\treturn jsonify({'LString' : txtlstring, 'output': output})\n\n#When Step is clicked, the server receives the code, derive and interpret one time the LString, sends the result and keeps the new LString in the session array.\n\n@app.route('/step', methods=['POST'])\ndef step():\n\tglobal LSystem\n\tcode = request.form['code']\n\tcode = code.encode('ascii', 'ignore')\n\tstep = 0\n\n\tif session.get('step') is not None:\n\t\tif code != session['code']:\n\t\t\tl = lpy.Lsystem()\n\t\t\tsession['code'] = code\n\t\t\ttry:\n\t\t\t\tl.set(code)\n\t\t\texcept:\n\t\t\t\treturn jsonify({'error' : 'Syntax error'})\n\n\t\t\tsession['step'] = l.derivationLength\n\t\t\tsession['currentStep'] = 1\n\t\t\tlstring = l.derive(session['currentStep'])\n\t\t\tilstring = l.interpret(lstring)\n\t\t\ttxtlstring = str(ilstring)\n\t\t\tLSystem = l\n\t\t\treturn jsonify({'LString' : txtlstring, 'currentStep' : session['currentStep'], 'step' : session['step']})\n\n\t\telse:\n\t\t\twith lock:\n\t\t\t\tsession['currentStep'] += 1\n\t\t\t\tlstring = LSystem.derive(session['currentStep'])\n\t\t\t\tilstring = LSystem.interpret(lstring)\n\t\t\t\ttxtlstring = str(ilstring)\n\t\t\t\tif session['currentStep'] < session['step']:\n\t\t\t\t\treturn jsonify({'LString' : txtlstring, 'currentStep' : session['currentStep'], 'step' : session['step']})\n\t\t\t\telse:\n\t\t\t\t\tstep = session['step']\n\t\t\t\t\tdisconnect()\n\t\t\t\t\treturn jsonify({'LString' : txtlstring, 'currentStep' : step, 'step' : step})\n\t\t\t\t\n\telse:\n\t\tl = lpy.Lsystem()\n\t\tsession['code'] = code\n\t\ttry:\n\t\t\tl.set(code)\n\t\texcept:\n\t\t\treturn jsonify({'error' : 'Syntax error'})\n\n\t\tsession['step'] = l.derivationLength\n\t\tsession['currentStep'] = 1\n\t\tlstring = l.derive(session['currentStep'])\n\t\tilstring = l.interpret(lstring)\n\t\ttxtlstring = str(ilstring)\n\t\tLSystem = l\n\t\treturn jsonify({'LString' : txtlstring, 'currentStep' : session['currentStep'], 'step' : session['step']})\n\n#When Rewind is clicked, the server receives the code, interpret only the Axiom of the LString and sends the result.\n@app.route('/rewind', methods=['POST'])\ndef rewind():\n\tdisconnect()\n\tl = lpy.Lsystem()\n\tcode = request.form['code']\n\tcode = code.encode('ascii', 'ignore')\n\ttry:\n\t\tl.set(code)\n\texcept:\n\t\treturn jsonify({'error' : 'Syntax error'})\n\tlstring = l.axiom\n\tilstring = l.interpret(lstring)\n\ttxtlstring = str(ilstring)\n\treturn jsonify({'LString' : txtlstring})\n\n@app.route('/about.html')\ndef about():\n return render_template('about.html')\n\n#Sometimes Flask doesn't interpret static files updates.\n#This function clears the issue.\n\n@app.context_processor\ndef override_url_for():\n return dict(url_for=dated_url_for)\n\ndef dated_url_for(endpoint, **values):\n if endpoint == 'static':\n filename = values.get('filename', None)\n if filename:\n file_path = os.path.join(app.root_path,\n endpoint, filename)\n values['q'] = int(os.stat(file_path).st_mtime)\n return url_for(endpoint, **values)\n\n#Fred's code\n#Converts curves and LStrings into JSON\n\n# def iscurve(c):\n# if isinstance(c, pgl.Curve2D) : return True\n# return isinstance(c, pgl.LineicModel)\n# \n# def curvetojson(c):\n# # calcule des points et les transforme en chaine de caractere\n# deltau = (c.lastKnot - c.firstKnot) / c.stride\n# return '['+','.join([str(tuple(c.getPointAt(c.firstKnot + i * deltau))) for i in range(c.stride+1)])+']'\n# \n# def lstringtojson(lstring):\n# lstrrepr = ''\n# for module in lstring:\n# modrepr = module.name +'(' + ','.join([str(param) if not iscurve(param) else curvetojson(param) for param in module])\n# lstrrepr += ' '+modrepr\n# return lstrrepr","sub_path":"lpyweb.py","file_name":"lpyweb.py","file_ext":"py","file_size_in_byte":5162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"645898994","text":"\"\"\"Build vocabulary for SYN corpus\"\"\"\n\nimport argparse\nimport os\n\nfrom tqdm import tqdm\n\nfrom syn.helpers.argparser import common_parser, vocabulary_parser\nfrom syn.helpers.environment import load_environment_variables\nfrom syn.helpers.logging import set_logger\nfrom syn.helpers.nlp.vocabulay import load_tokens, get_vocabulary_from_mongodb, save_vocabulary\nfrom syn.helpers.system import check_same_python_module_already_running\n\nload_environment_variables()\nlog = set_logger()\n\n\ndef get_input_params():\n parser = argparse.ArgumentParser(\n parents=[common_parser, vocabulary_parser],\n description='Filter word embeddings.'\n )\n\n args = parser.parse_args()\n\n return {\n 'corpus': args.corpus,\n 'query_limit': args.query_limit,\n 'vocabulary_name': args.vocabulary_name,\n 'tokens_collection': args.tokens_collection,\n }\n\n\nif __name__ == \"__main__\":\n # Check if there is a running process that contains the name of this module.\n check_same_python_module_already_running(os.path.split(__file__))\n\n # Load the parameters.\n input_params = get_input_params()\n\n # Loads dataset.\n log.info(f\"Loading Dataframe ...\")\n df = load_tokens(\n database_name=input_params['corpus'],\n collection_name=input_params['tokens_collection'],\n query_limit=input_params['query_limit']\n )\n log.info(f\"Dataframe columns: {df.columns}\")\n log.info(f\"Dataframe loaded.\")\n\n # Build vocabulary.\n log.info(f\"Building vocabulary ...\")\n vocab = set()\n for row in tqdm(df['tokens'], total=len(df['tokens']), desc='rows'):\n tmp_set = get_vocabulary_from_mongodb(row)\n vocab.update(tmp_set)\n\n log.info(f\"Vocabulary size: {len(vocab)}\")\n\n # Save vocabulary.\n inserted_documents = save_vocabulary(\n database_name=input_params['corpus'],\n collection_name=input_params['vocabulary_name'],\n vocabulary=vocab\n )\n assert inserted_documents == len(vocab)\n log.info(f\"MODULE EXECUTED.\")\n","sub_path":"syn/model/build/common/build_vocab.py","file_name":"build_vocab.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"433212436","text":"data1 = dict(name= \"payal\", age=19)\n#checking a particular key in dict\nif 'name' in data1:\n print(\"present\")\n\n#dont check for values\n\n#for values\nif 19 in data1.values():\n print(\"present\")\n#if i change 19 into string it will show not present\n","sub_path":"dictionaries/in_dict.py","file_name":"in_dict.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"63792832","text":"#!/usr/bin/python3\n\"\"\" creates new view for place objects \"\"\"\n\nfrom api.v1.views import app_views\nfrom flask import jsonify, abort, request\nfrom models import storage\nfrom models.city import City\nfrom models.place import Place\n\n\n@app_views.route('/cities//places', methods=['GET'],\n strict_slashes=False)\ndef list_all_places(city_id):\n \"\"\"Reviews list of all Places in a City\"\"\"\n city = storage.get('City', city_id)\n if city is None:\n abort(404)\n all_places = storage.all('Place').values()\n city_places = [p.to_dict() for p in all_places if p.city_id == city_id]\n return jsonify(city_places)\n\n\n@app_views.route('/places/', methods=['GET'],\n strict_slashes=False)\ndef list_place(place_id):\n \"\"\"Retrieves place object \"\"\"\n place = storage.get('Place', place_id)\n if place is None:\n abort(404)\n return jsonify(place.to_dict())\n\n\n@app_views.route('/places/', methods=['DELETE'],\n strict_slashes=False)\ndef delete_place(place_id):\n \"\"\"Delete a place object \"\"\"\n place = storage.get('Place', place_id)\n if place is None:\n abort(404)\n storage.delete(place)\n storage.save()\n return jsonify({}), 200\n\n\n@app_views.route('/cities//places', methods=['POST'],\n strict_slashes=False)\ndef create_place(city_id):\n \"\"\"Adds another object to the storage\"\"\"\n city = storage.get(\"City\", city_id)\n if city is None:\n abort(404)\n new_place_dict = request.get_json(silent=True)\n if new_place_dict is None:\n return jsonify({\"error\": \"Not a JSON\"}), 400\n elif 'name' not in request.json:\n return jsonify({\"error\": \"Missing name\"}), 400\n elif 'user_id' not in request.json:\n return jsonify({\"error\": \"Missing user_id\"}), 400\n user_id = new_place_dict['user_id']\n user = storage.get(\"User\", user_id)\n if user is None:\n abort(404)\n new_place_dict['city_id'] = city_id\n new_place = Place(**new_place_dict)\n storage.new(new_place)\n storage.save()\n return jsonify(new_place.to_dict()), 201\n\n\n@app_views.route('/places_search', methods=['POST'])\ndef search_places():\n \"\"\" search places depending on state and city and amenity id\"\"\"\n form = request.get_json(force=True)\n place_list = []\n all_cities = []\n all_amenities = []\n all_places = []\n if len(form) == 0:\n all_places = storage.all('Place')\n for place in all_places.values():\n place_list.append(place.to_dict())\n return jsonify(place_list), 200\n if 'cities' in request.json:\n for city_id in form['cities']:\n all_cities.append(storage.get('City', 'city_id'))\n if 'states' in request.json:\n for state_id in form['states']:\n for city in storage.get('State', state_id).cities:\n if city not in all_cities:\n all_cities.append(city)\n for city in all_cities:\n for place in city.places:\n all_places.append(place)\n\n if 'amenities' in request.json and len(all_places) != 0:\n for amenity_id in form['amenities']:\n all_amenities.append(storage.get('Amenity', amenity_id))\n for amenity in all_amenities:\n for place in all_places:\n if place not in amenity.place_amenities:\n all_places.remove(place)\n if 'amenities' in request.json and len(all_places) == 0:\n for amenity_id in form['amenities']:\n all_amenities.append(storage.get('Amenity', amenity_id))\n for amenity in all_amenities:\n for place in amenity.place_amenities:\n place_list.append(place.to_dict())\n return jsonify(place_list), 200\n\n for place in all_places:\n place_list.append(place.to_dict())\n return jsonify(place_list), 200\n\n\n@app_views.route('/places/', methods=['PUT'],\n strict_slashes=False)\ndef update_place(place_id):\n \"\"\"Updates an instance of Place\"\"\"\n update_place_json = request.get_json(silent=True)\n if update_place_json is None:\n return jsonify({'error': 'Not a JSON'}), 400\n place = storage.get('Place', place_id)\n if place is None:\n abort(404)\n ignore = ['id', 'created_at', 'updated_at', 'city_id', 'user_id']\n for k, v in update_place_json.items():\n if k not in ignore:\n setattr(place, k, v)\n storage.save()\n return jsonify(place.to_dict()), 200\n","sub_path":"api/v1/views/places.py","file_name":"places.py","file_ext":"py","file_size_in_byte":4465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"11216849","text":"#!/usr/bin/env python3\n\nclass Solution:\n # @param tokens, a list of string\n # @return an integer\n def evalRPN(self, tokens):\n nums = list()\n for t in tokens:\n if t not in '+-/*':\n nums.append(int(t))\n else:\n if t == '+':\n nums[-2] += nums[-1]\n elif t == '-':\n nums[-2] -= nums[-1]\n elif t == '*':\n nums[-2] *= nums[-1]\n else:\n if nums[-2] > 0 and nums[-1] > 0 or nums[-2] < 0 and nums[-1] < 0:\n nums[-2] = abs(nums[-2]) // abs(nums[-1])\n else:\n nums[-2] = -(abs(nums[-2]) // abs(nums[-1]))\n nums.pop()\n return nums[0]\n\ndef main():\n solver = Solution()\n print(solver.evalRPN([\"2\", \"1\", \"+\", \"3\", \"*\"]))\n print(solver.evalRPN([\"4\", \"13\", \"5\", \"/\", \"+\"]))\n print(solver.evalRPN([\"10\",\"6\",\"9\",\"3\",\"+\",\"-11\",\"*\",\"/\",\"*\",\"17\",\"+\",\"5\",\"+\"]))\n\nif __name__ == '__main__':\n main()\n","sub_path":"python/evaluate_reverse_polish_notation.py","file_name":"evaluate_reverse_polish_notation.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"25241299","text":"from pathlib import Path\n\nimport fire\nimport yaml\n\nMODEL_CONFIG_PATH = Path(__file__).parent / \"../model_config\"\n\n\ndef main(name: str = \"\", ls: bool = False):\n if ls:\n for fpath in MODEL_CONFIG_PATH.glob(\"**/*.yml\"):\n with fpath.open() as f:\n cfg = yaml.safe_load(f)\n print(cfg[\"name\"])\n return\n fpath = MODEL_CONFIG_PATH / f\"{name}.yml\"\n print(fpath.read_text())\n\n\nif __name__ == \"__main__\":\n fire.Fire(main)\n","sub_path":"camphr/cli/model_config.py","file_name":"model_config.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"529011398","text":"import math\n\ndef main():\n i = 100\n x = sum_of_squares(i)\n y = square_of_sum(i)\n d = y - x\n print('i: %d' % i)\n print('sum of squares: %d' % x)\n print('square of sum: %d' % y)\n print('difference: %d' % d)\n\ndef sum_of_squares(n):\n total = 0 \n for i in range(0, n + 1):\n total += math.pow(i, 2)\n return total\n\ndef square_of_sum(n):\n total = 0\n for i in range(0, n + 1):\n total += i\n return math.pow(total, 2)\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"006/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"507696612","text":"import torch\nimport matplotlib.pyplot as plt\nfrom torchvision import transforms\nfrom PIL import Image as I\nfrom torch.autograd import Variable\n\nimport evalMethod\n\n# GPU\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\n\ntorch.manual_seed(777)\nif device == 'cuda':\n torch.cuda.manual_seed_all(777)\n print(\"GPU is available!!!\")\n\nimgA = I.open('data/A.jpeg')\nimgB = I.open('data/B.jpeg')\n\ntf = transforms.Compose([\n transforms.Resize((255,255)),\n transforms.ToTensor()\n])\n\nimgA_tensor = 255*tf(imgA)\nimgB_tensor = 255*tf(imgB)\n\nimg1 = Variable(torch.unsqueeze(imgA_tensor,0))\nimg2 = Variable(torch.unsqueeze(imgB_tensor,0))\n\nprint(evalMethod.ssim(img1, img2))\n\nplt.imshow(imgA)\nplt.title('A')\nplt.axis('off')\nplt.show(block=True)\n\nplt.imshow(imgB)\nplt.title('B')\nplt.axis('off')\nplt.show(block=True)","sub_path":"imageEvaluation/.ipynb_checkpoints/testEval-checkpoint.py","file_name":"testEval-checkpoint.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"34439458","text":"def printifier():\r\n\r\n import re\r\n import collections\r\n\r\n from Marchand_jureur_dict import dict\r\n keys = dict.keys()\r\n values = dict.values()\r\n\r\n prints_Marie = open('prints_Evesque.py', 'w', encoding = 'utf-8')\r\n\r\n for key in keys:\r\n prints_Marie.write('print(EvolutionPhonetique.evolution_phonetique(\"' + key + '\")) # '+ dict[key] + '\\n')\r\n\r\nprintifier()\r\n","sub_path":"script_11/Marchand jureur/printifier.py","file_name":"printifier.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"15608717","text":"\"\"\"\nSupport for SageTV players.\n\nFor more details about this platform, please refer to the documentation at\nhttps://home-assistant.io/components/SageTV/\n\"\"\"\nfrom datetime import timedelta\nimport logging\nimport requests\nimport voluptuous as vol\n\nfrom homeassistant.components.media_player import (\n MediaPlayerEntity, PLATFORM_SCHEMA)\nfrom homeassistant.components.media_player.const import (\n SUPPORT_PAUSE, SUPPORT_PLAY, SUPPORT_STOP,\n SUPPORT_TURN_OFF, SUPPORT_TURN_ON, SUPPORT_NEXT_TRACK, SUPPORT_PREVIOUS_TRACK, SUPPORT_SEEK)\nfrom homeassistant.const import (\n CONF_HOST, CONF_NAME, STATE_IDLE, STATE_OFF, STATE_PLAYING)\nimport homeassistant.helpers.config_validation as cv\nfrom homeassistant.util.dt import utcnow\n\nREQUIREMENTS = []\nCONF_EXTENDER = 'extender'\nCONF_SAGEX = 'sagex'\nDEFAULT_NAME = \"SageTV\"\nSCAN_INTERVAL = timedelta(seconds=30)\n\n_LOGGER = logging.getLogger(__name__)\n\nSUPPORT_SAGETV = (SUPPORT_PLAY | SUPPORT_STOP | SUPPORT_PAUSE | SUPPORT_NEXT_TRACK | SUPPORT_PREVIOUS_TRACK | SUPPORT_SEEK)\n# No host is needed for configuration, however it can be set.\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({\n vol.Required(CONF_SAGEX): cv.string,\n vol.Required(CONF_EXTENDER): cv.string,\n vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,\n})\n\n\ndef setup_platform(hass, config, add_entities, discovery_info=None):\n conf = discovery_info if discovery_info else config\n\n # Register configured device with Home Assistant.\n add_entities([SageTV( conf[CONF_NAME], conf[CONF_SAGEX], conf[CONF_EXTENDER])])\n\n\nclass SageTV(MediaPlayerEntity):\n\n def __init__(self, name, sagex, extender):\n\n # Default name value, only to be overridden by user.\n self._name = name\n self._extender = extender\n self._baseurl = sagex\n # Assume we're off to start with\n self._state = STATE_IDLE\n self._position = 0\n self._duration = 0\n self._position_valid = 0\n self._media_title = ''\n self._title = ''\n self._poster = ''\n self.update()\n\n @property\n def name(self):\n \"\"\"Return the display name of this device.\"\"\"\n return self._name\n\n @property\n def state(self):\n \"\"\"Return _state variable, containing the appropriate constant.\"\"\"\n return self._state\n\n @property\n def supported_features(self):\n \"\"\"Flag media player features that are supported.\"\"\"\n return SUPPORT_SAGETV\n\n @property\n def media_duration(self):\n \"\"\"Duration of current playing media in seconds.\"\"\"\n return self._duration\n\n @property\n def media_position(self):\n \"\"\"Position of current playing media in seconds.\"\"\"\n return self._position\n\n @property\n def media_position_updated_at(self):\n \"\"\"When was the position of the current playing media valid.\"\"\"\n return self._position_valid\n\n def update(self):\n \"\"\"Update the internal state by querying the device.\"\"\"\n # This can take 5+ seconds to complete\n url = self._baseurl + 'sagex/api?c=ha:GetCurrentShow&1=' + self._extender + '&encoder=json'\n r = requests.get(url)\n rawJson = r.json()\n self._state = rawJson[\"Result\"][\"isPlaying\"]\n if self._state == 'idle':\n self._media_title = ''\n self._poster = ''\n self._duration = 0\n self._position = 0\n else:\n if self._media_title != rawJson[\"Result\"][\"title\"]:\n self._media_title = rawJson[\"Result\"][\"title\"]\n self._poster = rawJson[\"Result\"][\"poster\"]\n self._duration = rawJson[\"Result\"][\"duration\"]\n self._position = rawJson[\"Result\"][\"watchedDuration\"]\n self._position_valid = utcnow()\n\n def media_play(self):\n \"\"\"Send play command.\"\"\"\n url = self._baseurl + 'sagex/api?c=ha:Command&1=play&2=' + self._extender\n r = requests.get(url)\n\n def media_pause(self):\n \"\"\"Send pause command.\"\"\"\n url = self._baseurl + 'sagex/api?c=ha:Command&1=pause&2=' + self._extender\n r = requests.get(url)\n\n def media_stop(self):\n \"\"\"Send stop command.\"\"\"\n url = self._baseurl + 'sagex/api?c=ha:Command&1=stop&2=' + self._extender\n r = requests.get(url)\n\n def media_play_pause(self):\n url = self._baseurl + 'sagex/api?c=ha:PlayPause&1=' + self._extender\n r = requests.get(url)\n\n def media_next_track(self):\n url = self._baseurl + 'sagex/api?c=ha:Command&1=Right&2=' + self._extender\n r = requests.get(url)\n\n def media_previous_track(self):\n url = self._baseurl + 'sagex/api?c=ha:Command&1=Left&2=' + self._extender\n r = requests.get(url)\n\n def async_media_seek(self,position):\n url = self._baseurl + 'sagex/api?c=ha:Seek&1=' + self._extender + '&2=' + position;\n r = requests.get(url)\n\n @property\n def media_title(self):\n \"\"\"Title of current playing media.\"\"\"\n # find a string we can use as a title\n return self._media_title\n\n @property\n def media_image_url(self):\n return self._poster;\n","sub_path":"sagetv/media_player.py","file_name":"media_player.py","file_ext":"py","file_size_in_byte":5101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"8368323","text":"# Curso em vídeo Python 3 - Exercicio 101\n# Funçoes para votação\n\n\ndef voto(nasc):\n from datetime import date\n now = date.today()\n\n idade = now.year - nasc\n if 0 <= idade < 16:\n return 'Idade de {} anos. NÃO VOTA.'.format(idade)\n elif 16 <= idade < 18 or idade >=60:\n return 'Idade de {} anos. VOTO OPCIONAL.'.format(idade)\n elif 18 <= idade < 60:\n return 'Idade de {} anos. VOTO OBRIGATÓRIO.'.format(idade)\n else:\n return 'Ano de nascimento inserio não válido.'\n\n\nnasc = int(input('Ano de nascimento: '))\nprint(voto(nasc))\n","sub_path":"Mundo 3/Exercicios/ex101.py","file_name":"ex101.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"311669775","text":"import os\nimport glob\nimport time\nimport json\nimport numpy as np\nimport pandas as pd\nfrom multiprocessing import Pool\nimport multiprocessing as mp\n\nfrom pool_gpu_function import *\nfrom parse_json_param import *\nfrom _v2_full_train_minute_price import *\n\nimport gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\n\ndef main(task_df, max_gpu):\n t_all = time.time()\n\n jobs = []\n for gpu in range(max_gpu):\n gpu = str(gpu)\n sub_task_df = task_df[task_df[\"device\"] == int(gpu)]\n if len(sub_task_df) > 0:\n p = mp.Process(target=run_by_gpu_2, args=(sub_task_df,gpu))\n jobs.append(p)\n p.start()\n\n for proc in jobs:\n proc.join()\n\n t_all_2 = time.time()\n\n print(\"Everything Done:\", (t_all_2 - t_all)/3600, \"hours\")\n print(\"Setup(s) completed:\", task_df[\"Code\"])\n print(\"Number of json:\", len(task_df))\n\nif __name__ == \"__main__\":\n os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\n optparser = optparse.OptionParser()\n optparser.add_option(\"-s\", \"--sheetname\", default=\"Z_5_DLTask\", help=\"sheet\")\n optparser.add_option(\"-g\", \"--maxgpu\", default=\"2\", help=\"max_gpu\")\n optparser.add_option(\"-p\", \"--pcname\", default=\"0\", help=\"pcname\")\n opts = optparser.parse_args()[0]\n\n sheet_name = str(opts.sheetname)\n max_gpu = int(opts.maxgpu)\n pc_name = int(opts.pcname)\n\n scope = ['https://spreadsheets.google.com/feeds',\n 'https://www.googleapis.com/auth/drive']\n\n credentials = ServiceAccountCredentials.from_json_keyfile_name('./Credential/DeepLearningAlphaC-666170c72205.json', scope)\n gc = gspread.authorize(credentials)\n spreadsheet = gc.open(\"TASK\")\n\n # worksheet_list = spreadsheet.worksheets()\n worksheet = spreadsheet.worksheet(sheet_name)\n\n column_list = worksheet.range('A1:R1')\n task_df = pd.DataFrame(worksheet.get_all_records(), columns=[cell.value for cell in column_list])\n task_df[\"row\"] = np.arange(len(task_df)) + 2\n task_df = task_df[task_df[\"Training\"] == \"\"]\n\n if pc_name == 3:\n task_df = task_df[task_df[\"PC\"] == \"THR-WS\"]\n elif pc_name == 4:\n task_df = task_df[task_df[\"PC\"] == \"FOU-WS\"]\n elif pc_name == 5:\n task_df = task_df[task_df[\"PC\"] == \"FIV-WS\"]\n\n if len(task_df) == 0:\n print(sheetname, \": Nothing to run!\")\n else:\n main(task_df, max_gpu)\n","sub_path":"run_pool_gpu_gspread.py","file_name":"run_pool_gpu_gspread.py","file_ext":"py","file_size_in_byte":2371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"203710165","text":"#coding: utf-8\nimport logging\n\nfrom sqlalchemy.exc import IntegrityError\nimport transaction\n\nimport models\nimport excepts\n\n\nlogger = logging.getLogger('balaio.checkin')\n\n\ndef get_attempt(package, Session=models.Session):\n \"\"\"\n Returns a brand new models.Attempt instance, bound to a models.ArticlePkg\n instance.\n\n A package is valid when it has at least one valid xml file, according to\n SPS or rSPS xsd, and one pdf file.\n\n Case 1: Package is valid and has all needed metadata:\n A :class:`models.Attempt` is returned, bound to a :class:`models.ArticlePkg`.\n Case 2: Package is valid and doesn't have all needed metadata:\n A :class:`models.Attempt` is returned, with :attr:`models.Attempt.is_valid==False`.\n Case 3: Package is invalid\n A :class:`models.Attempt` is returned, with :attr:`models.Attempt.is_valid==False`.\n Case 4: Package is duplicated\n raises :class:`excepts.DuplicatedPackage`.\n\n :param package: Instance of SafePackage.\n :param Session: (optional) Reference to a Session class.\n \"\"\"\n logger.info('Analyzing package: %s' % package)\n\n with package.analyzer as pkg:\n try:\n logger.debug('Creating a transactional session scope')\n session = Session()\n\n # Building a new Attempt\n attempt = models.Attempt.get_from_package(pkg)\n session.add(attempt)\n\n # Trying to bind a ArticlePkg\n savepoint = transaction.savepoint()\n try:\n article_pkg = models.ArticlePkg.get_or_create_from_package(pkg, session)\n if article_pkg not in session:\n session.add(article_pkg)\n\n attempt.articlepkg = article_pkg\n attempt.is_valid = True\n\n #checkin_notifier.tell('Attempt is valid.', models.Status.ok, 'Checkin')\n\n except Exception as e:\n savepoint.rollback()\n #checkin_notifier.tell('Failed to load an ArticlePkg for %s.' % package, models.Status.error, 'Checkin')\n\n logger.error('Failed to load an ArticlePkg for %s.' % package)\n logger.debug('---> Traceback: %s' % e)\n\n transaction.commit()\n return attempt\n\n except IOError as e:\n transaction.abort()\n logger.error('The package %s had been deleted during analysis' % package)\n logger.debug('---> Traceback: %s' % e)\n raise ValueError('The package %s had been deleted during analysis' % package)\n\n except IntegrityError as e:\n transaction.abort()\n logger.error('The package has no integrity. Aborting.')\n logger.debug('---> Traceback: %s' % e)\n\n if 'violates not-null constraint' in e.message:\n raise ValueError('An integrity error was cast as ValueError.')\n else:\n raise excepts.DuplicatedPackage('The package %s already exists.' % package)\n\n except Exception as e:\n transaction.abort()\n\n logger.error('Unexpected error! The package analysis for %s was aborted.' % (\n package))\n logger.debug('---> Traceback: %s' % e)\n raise ValueError('Unexpected error! The package analysis for %s was aborted.' % package)\n\n finally:\n logger.debug('Closing the transactional session scope')\n session.close()\n\n","sub_path":"balaio/checkin.py","file_name":"checkin.py","file_ext":"py","file_size_in_byte":3443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"103843086","text":"n = int(input())\nl = []\nfor i in range(n):\n name, grade = input(), float(input())\n l.append([name, grade])\nl = sorted(l, key=lambda x: (x[1], x[0]))\ntarget_grade = l[0][1]\n#print (l)\nfor name, grade in l:\n if grade != l[0][1]:\n target_grade = grade\n break\nfor name, grade in filter(lambda x: x[1] == target_grade, l):\n print (name)\n","sub_path":"domains/python/data-types/nested-list_sunghyo.jung.py","file_name":"nested-list_sunghyo.jung.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"288769865","text":"# %matplotlib inline\nimport sys\nimport math\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport matplotlib\nimport numpy as np\nimport os\nfrom matplotlib.backends.backend_pdf import PdfPages\nfrom matplotlib.ticker import MultipleLocator\nfrom random import randint\nfrom matplotlib.backends.backend_pdf import PdfPages\nfrom matplotlib.backends.backend_pdf import PdfPages\nfrom palettable.colorbrewer.sequential import YlGnBu_5\n\nmodel_names = ['mobilenet','xception','nasnetamobile']\nmodel_name = model_names[1]\n# model_name = 'pdp'\ntotal_mac = '800'\ndata_folder = './gen_data/plot_data/' + model_name + '/' + total_mac + '/latency.csv'\nresult_dir = './gen_data/plot_data/' + model_name + '/' + total_mac + '/'\nif not os.path.exists(result_dir):\n os.makedirs(result_dir)\nresult_file = result_dir + '/latency_scatter_' + model_name + '.pdf'\n# Plot type\nplt.style.use('ggplot')\n\n#Loading data\ndf = pd.read_csv(data_folder)\n\ndf['total_mac_cycles'] = df['total_mac_cycles'] / df['total_mac_cycles'].max()\ndf['total_dma_accesses'] = df['total_dma_accesses'] / df['total_dma_accesses'].max()\ndf['total_memory_mb'] = df['total_memory_mb'] / df['total_memory_mb'].max()\ndf['total_memory_mb'] = [math.pow(x,6) for x in df['total_memory_mb']]\n\n# delete rows with column name 'schedule_name' = pdp\nindexNames = df[df['schedule_name'] == 'pdp'].index\n# Delete these row indexes from dataFrame\ndf.drop(indexNames, inplace=True)\ndf['schedule_name'] = df['schedule_name'].replace(['per_layer','dp','pdp'],['Base','DP-PT','PT-DP-PT'])\n\nfig, ax = plt.subplots(figsize=(12, 8))\nplt.gcf().subplots_adjust(bottom=0.16, right=0.99, top=0.88)\nplt.xticks(rotation=90)\n\n\n# plt.xlim(-0.5, 10)\n\nN = len(df[model_name])\nind = np.arange(N)\n# width = 0.8\n\ndf_sorted = df.sort_values(by=['total_dma_accesses'])\n\n\nmajorLocator = MultipleLocator(0.2)\nminorLocator = MultipleLocator(0.2)\n# majorFormatter = FormatStrFormatter('%d')\nax.xaxis.set_major_locator(majorLocator)\nax.xaxis.set_minor_locator(minorLocator)\n# ax.xaxis.set_major_formatter(majorFormatter)\n\n\n# cl = {'PT-DP-PT':'blue','DP-PT':'orange','Base':'green'}\ncl = {'PT-DP-PT':'blue','DP-PT':'red','Base':'green'}\nmarker = {'DP-PT':'x','Base':'+'}\n\nfor sch in list(set(df_sorted['schedule_name'])):\n vals = df_sorted[df_sorted['schedule_name'] == sch]\n ax.scatter(vals['total_dma_accesses'],vals['total_mac_cycles'],\n s=1000, marker = marker[sch],edgecolor='k', color=cl[sch],label=sch,\n alpha=1, edgecolors='k')\n\n # ax.scatter(vals['total_dma_accesses'], vals['total_mac_cycles'],\n # s=vals['total_memory_mb']*1024*3, marker = 'o',edgecolor='k', color=cl[sch],label=sch,\n # alpha=0.3, edgecolors='none')\n\n# for n in np.arange(len(df['name'])):\n# ax.text(df['Area'][n]-0.06, df['Power'][n]-0.07, df['name'][n], fontsize=16)\n\n# Put limit on Y axis\nplt.ylim(0, 1.1)\nplt.xlim(0.01, 1.1)\n\n# Set X label values\nax.set_ylabel('Latency (Lower is better)',fontsize=38, color='black')\nax.set_xlabel('DRAM Energy (Lower is better)',fontsize=38, color='black')\n\n# ax.set_xticks(ind+0.8);\n\n# Put the labels from 'app' coulmn\n# ax.set_xticklabels(u.rename(df['name']))\nax.set_facecolor('whitesmoke')\n\nplt.gca().xaxis.grid(True, color='black')\nplt.gca().yaxis.grid(True, color='black')\n\nplt.tick_params( axis='x', which='both', bottom=False, top=False, colors='black')\nplt.tick_params( axis='y', which='both', right=False, colors='black' )\nplt.tick_params(axis='both', which='major', direction='in', \n length=6, width=3,color='black', labelsize=28)\nplt.grid(linestyle='--')\n\n# plt.legend(numpoints=1)\nplt.legend(bbox_to_anchor=(0.90, 1.20), ncol=3, fontsize=35)\n\n\n\nax.spines['bottom'].set_color('gray')\nax.spines['top'].set_color('gray')\nax.spines['right'].set_color('gray')\nax.spines['left'].set_color('gray')\n\nplt.show()\n# Saving the plot\nfig.savefig(result_file,facecolor=fig.get_facecolor(), bbox_inches='tight')","sub_path":"TB-scheduler/deprecated/plot_dp_latency_scatter.py","file_name":"plot_dp_latency_scatter.py","file_ext":"py","file_size_in_byte":3946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"255257404","text":"from torch.testing._internal.common_utils import TestCase, run_tests\nimport torch\nfrom torch import vmap\nimport warnings\n\nclass TestVmapAPI(TestCase):\n def test_non_tensor_output_raises(self):\n with self.assertRaisesRegex(ValueError, \"got type as the return\"):\n output = vmap(lambda x: 3.14)(torch.ones(3))\n\n def multiple_outputs(x):\n return x, 3\n\n with self.assertRaisesRegex(ValueError, \"got type for return 1\"):\n vmap(multiple_outputs)(torch.ones(3))\n\n def test_different_map_dim_size_raises(self):\n x = torch.randn(2)\n y = torch.randn(3)\n expected_msg = 'Expected all tensors to have the same size in the mapped dimension'\n with self.assertRaisesRegex(ValueError, expected_msg):\n vmap(torch.mul)(x, y)\n\n def test_func_with_no_inputs(self):\n expected_msg = 'got no inputs'\n\n def foo():\n return torch.randn(3)\n\n def bar(x):\n return torch.randn(3)\n\n with self.assertRaisesRegex(ValueError, expected_msg):\n vmap(foo)()\n\n with self.assertRaisesRegex(ValueError, expected_msg):\n vmap(bar)()\n\n def test_constant_function(self):\n output = vmap(lambda x: torch.tensor(3.14))(torch.ones(3))\n self.assertEqual(output, torch.tensor([3.14, 3.14, 3.14]))\n\n def test_single_input(self):\n x = torch.randn(2, 3)\n\n def square(x):\n return x * x\n\n output = vmap(square)(x)\n self.assertEqual(output, x * x)\n\n def test_multiple_inputs(self):\n x = torch.randn(2, 3)\n y = torch.randn(2, 3)\n output = vmap(torch.mul)(x, y)\n self.assertEqual(output, x * y)\n\n def test_multiple_outputs(self):\n def foo(x):\n return x * x, x * x * x\n\n x = torch.randn(3)\n outputs = vmap(foo)(x)\n self.assertEqual(outputs[0], x * x)\n self.assertEqual(outputs[1], x * x * x)\n\n def test_multiple_outputs_error_cases(self):\n # This is the same thing as\n # def returns_tuple_of_tensors(x):\n # return x, x\n def returns_tuple_of_tensors(x):\n return (x, x)\n\n def returns_list_of_two_tensors(x):\n return [x, x]\n\n def returns_list_of_one_tensor(x):\n return [x]\n\n x = torch.randn(3)\n\n # should not throw\n vmap(returns_tuple_of_tensors)(x)\n\n # jax supports these, but we don't yet\n msg = \"must only return Tensors, got type \"\n with self.assertRaisesRegex(ValueError, msg):\n vmap(returns_list_of_two_tensors)(x)\n with self.assertRaisesRegex(ValueError, msg):\n vmap(returns_list_of_one_tensor)(x)\n\n def test_nested_with_same_map_dim(self):\n x = torch.randn(2, 3, 5)\n y = torch.randn(2, 3, 5)\n output = vmap(vmap(torch.mul))(x, y)\n self.assertEqual(output, x * y)\n\n output = vmap(vmap(vmap(torch.mul)))(x, y)\n self.assertEqual(output, x * y)\n\n def test_nested_with_different_map_dim(self):\n x = torch.randn(2, 3)\n y = torch.randn(5, 3)\n output = vmap(lambda x: vmap(lambda y: x * y)(y))(x)\n self.assertEqual(output.shape, (2, 5, 3))\n self.assertEqual(output, x.view(2, 1, 3) * y)\n\n z = torch.randn(7, 3)\n output = vmap(lambda x: vmap(lambda y: vmap(lambda z: x * y * z)(z))(y))(x)\n self.assertEqual(output.shape, (2, 5, 7, 3))\n self.assertEqual(output, x.view(2, 1, 1, 3) * y.view(5, 1, 3) * z)\n\n def test_noop_in_inner_vmap(self):\n x = torch.randn(3)\n y = torch.randn(5)\n output = vmap(lambda x: vmap(lambda y: x)(y))(x)\n self.assertEqual(output, x.view(3, 1).expand(3, 5))\n\n def test_unsupported_op_err_msg(self):\n # Unsupported view op\n tensor = torch.randn(2, 3)\n with self.assertRaisesRegex(RuntimeError, \"doesn't work on in-place or view ops\"):\n vmap(torch.as_strided, (0, None, None))(tensor, [2, 3], [0, 0])\n\n # We don't support multiple returns yet\n with self.assertRaisesRegex(RuntimeError, 'multiple returns'):\n vmap(torch.var_mean)(tensor)\n\n # The fallback doesn't support TensorList\n with self.assertRaisesRegex(RuntimeError, 'Batching rule not implemented'):\n vmap(lambda t: torch.stack([t]))(tensor)\n\n # Don't support non-tensor returns. This is a limitation of vmap;\n # functions that don't return tensors must be special cased\n with self.assertRaisesRegex(RuntimeError, 'Batching rule not implemented'):\n vmap(torch.Tensor.item)(tensor)\n\n def test_unsupported_inplace_op_err_msg(self):\n def foo(x):\n return x.cos_()\n\n x = torch.randn(3)\n with self.assertRaisesRegex(\n RuntimeError, 'Batching rule not implemented'):\n vmap(foo)(x)\n\n def test_nonzero_out_dims(self):\n # Basic test\n tensor = torch.randn(2, 3)\n result = vmap(lambda x: x, out_dims=1)(tensor)\n self.assertEqual(result, tensor.permute(1, 0))\n self.assertEqual(result.data_ptr(), tensor.data_ptr())\n\n # Test that the batch dimension gets permuted to dim 2\n tensor = torch.randn(2, 3, 5, 7)\n result = vmap(lambda x: x, out_dims=2)(tensor)\n self.assertEqual(result, tensor.permute(1, 2, 0, 3))\n self.assertEqual(result.data_ptr(), tensor.data_ptr())\n\n # negative out_dim\n tensor = torch.randn(2, 3, 5, 7)\n result = vmap(lambda x: x, out_dims=-1)(tensor)\n self.assertEqual(result, tensor.permute(1, 2, 3, 0))\n self.assertEqual(result.data_ptr(), tensor.data_ptr())\n\n # check that out_dims works on ALL outputs\n tensor = torch.randn(2, 3, 5, 7)\n other = torch.randn(2, 3, 5, 7)\n result = vmap(lambda x, y: (x, y), out_dims=2)(tensor, other)\n self.assertEqual(result, (tensor.permute(1, 2, 0, 3), other.permute(1, 2, 0, 3)))\n\n # use out_dims with the maximum vmap-able tensor dims (64 dims)\n ndims = 64\n shape = [2] + [1] * (ndims - 1)\n expected_shape = [1, 1, 2] + [1] * (ndims - 3)\n tensor = torch.randn(shape)\n result = vmap(lambda x: x, out_dims=2)(tensor)\n self.assertEqual(result.shape, expected_shape)\n\n # test something that is not the identity function\n def foo(x, y):\n return x, x * y, x * y * y\n x = torch.randn(2, 3, 5)\n y = torch.randn(2, 3, 5)\n result = vmap(foo, out_dims=1)(x, y)\n self.assertEqual(\n result,\n (x.permute(1, 0, 2), (x * y).permute(1, 0, 2), (x * y * y).permute(1, 0, 2)))\n\n def test_multiple_out_dims(self):\n def foo(x):\n return x, x\n\n def bar(x, y):\n return x, x, x, x * y\n\n x = torch.randn(2, 3, 5)\n y = torch.randn(2, 3, 5)\n result = vmap(foo, out_dims=(0, 1))(x)\n self.assertEqual(result, (x, x.permute(1, 0, 2)))\n\n result = vmap(bar, out_dims=(-1, 0, 1, 2))(x, y)\n expected = (\n x.permute(1, 2, 0),\n x,\n x.permute(1, 0, 2),\n (x * y).permute(1, 2, 0),\n )\n self.assertEqual(result, expected)\n\n def test_nested_out_dims(self):\n y = torch.randn(2, 3, 5, 7)\n\n # Inner vmap has non-zero out_dim\n result = vmap(lambda y: vmap(lambda x: x, out_dims=1)(y))(y)\n self.assertEqual(result.shape, (2, 5, 3, 7))\n self.assertEqual(result, y.permute(0, 2, 1, 3))\n\n # all vmaps have non-zero out_dim\n result = vmap(lambda y: vmap(lambda x: x, out_dims=1)(y), out_dims=1)(y)\n self.assertEqual(result.shape, (5, 2, 3, 7))\n self.assertEqual(result, y.permute(2, 0, 1, 3))\n\n # throwing in some negative out_dims\n result = vmap(lambda y: vmap(lambda x: x, out_dims=-1)(y), out_dims=-1)(y)\n self.assertEqual(result.shape, (5, 7, 3, 2))\n self.assertEqual(result, y.permute(2, 3, 1, 0))\n\n # testing fn that isn't the identity\n x = torch.randn(2, 3)\n y = torch.randn(5, 3)\n result = vmap(lambda y: vmap(lambda x: x * y, out_dims=1)(x), out_dims=-1)(y)\n self.assertEqual(result.shape, (3, 2, 5))\n self.assertEqual(result, (y.view(5, 1, 3) * x).permute(2, 1, 0))\n\n def test_out_dims_edge_case(self):\n def foo(x):\n return x\n\n # Test that we accept out_dims=(1,) for a function with one output.\n tensor = torch.randn(2, 3)\n expected = vmap(foo, out_dims=1)(tensor)\n result = vmap(foo, out_dims=(1,))(tensor)\n self.assertEqual(result, expected)\n\n def test_out_dims_must_be_int_or_tuple_of_int_err_msg(self):\n msg = '`out_dims` must be an int or a tuple of int'\n tensor = torch.randn(2, 3)\n with self.assertRaisesRegex(ValueError, msg):\n vmap(lambda x: x, out_dims='lol')(tensor)\n with self.assertRaisesRegex(ValueError, msg):\n vmap(lambda x: x, out_dims=('lol',))(tensor)\n with self.assertRaisesRegex(ValueError, msg):\n vmap(lambda x: x, out_dims=None)(tensor)\n with self.assertRaisesRegex(ValueError, msg):\n vmap(lambda x: x, out_dims=(None,))(tensor)\n\n def test_out_dims_and_num_outputs_mismatch_err_msg(self):\n msg = '`out_dims` must have one dim per output'\n x = torch.randn(2, 3, 5)\n\n # Too many out_dims\n with self.assertRaisesRegex(ValueError, msg):\n vmap(lambda x: x, out_dims=(0, 0))(x)\n with self.assertRaisesRegex(ValueError, msg):\n vmap(lambda x: (x, x, x), out_dims=(0, 0, 0, 0))(x)\n\n # Too few out_dims\n with self.assertRaisesRegex(ValueError, msg):\n vmap(lambda x: (x, x), out_dims=(0,))(x)\n with self.assertRaisesRegex(ValueError, msg):\n vmap(lambda x: (x, x, x), out_dims=(0, 0))(x)\n\n def test_out_dim_out_of_bounds_err_msg(self):\n # TODO(rzou): This error message isn't that great. It comes straight\n # from maybe_wrap_dim. Consider doing a try-catch-(add some context) to\n # the error message in the future in C++\n msg = 'Dimension out of range'\n x = torch.randn(2, 3, 5)\n with self.assertRaisesRegex(IndexError, msg):\n vmap(lambda x: x, out_dims=3)(x)\n with self.assertRaisesRegex(IndexError, msg):\n vmap(lambda x: x, out_dims=-4)(x)\n\n def test_non_zero_in_dims(self):\n tensor = torch.randn(2, 3, 5)\n\n # Implicit out_dims = 0; vmap will move the batch dim to the front.\n output = vmap(lambda x: x, (1,))(tensor)\n self.assertEqual(output, tensor.permute(1, 0, 2))\n self.assertEqual(output.data_ptr(), tensor.data_ptr())\n\n x = torch.randn(2, 3)\n y = torch.randn(3, 2)\n output = vmap(torch.mul, (0, 1))(x, y)\n self.assertEqual(output, x * y.t())\n output = vmap(torch.mul, (1, 0))(x, y)\n self.assertEqual(output, x.t() * y)\n\n def test_none_in_dims(self):\n x = torch.randn(2, 3)\n y = torch.randn(2, 3)\n\n # None in_dim for a Tensor means we don't map over it\n output = vmap(torch.mul, (0, None))(x, y)\n self.assertEqual(output.shape, (2, 2, 3))\n self.assertEqual(output, x.view(2, 1, 3) * y)\n\n # None in_dim for non-tensor arguments\n output = vmap(torch.mul, (0, None))(x, 2)\n self.assertEqual(output, x * 2)\n\n def test_nested_non_default_in_dims(self):\n x = torch.rand(5, 2, 3)\n y = torch.rand(3, 5, 2)\n result = vmap(vmap(vmap(torch.mul), (1, 0)), (1, 2))(x, y)\n self.assertEqual(result, x.permute(1, 2, 0) * y.permute(2, 0, 1))\n\n def test_non_default_in_dims_out_dims(self):\n x = torch.randn(2, 3, 5)\n\n # Same in_dim as out_dim, vmap over identity\n result = vmap(lambda x: x, in_dims=1, out_dims=1)(x)\n self.assertEqual(result, x)\n self.assertEqual(result.data_ptr(), x.data_ptr())\n\n # Different in_dim from out_dim, vmap over identity\n result = vmap(lambda x: x, in_dims=2, out_dims=1)(x)\n self.assertEqual(result.shape, (2, 5, 3))\n self.assertEqual(result, x.transpose(1, 2))\n self.assertEqual(result.data_ptr(), x.data_ptr())\n\n def foo(x):\n return x * 2\n\n # Same in_dim as out_dim, vmap over operation\n result = vmap(foo, in_dims=1, out_dims=1)(x)\n self.assertEqual(result, x * 2)\n\n # Different in_dim as out_dim, vmap over operation\n result = vmap(foo, in_dims=2, out_dims=1)(x)\n self.assertEqual(result.shape, (2, 5, 3))\n self.assertEqual(result, (x * 2).transpose(1, 2))\n\n # Basic nested test.\n result = vmap(vmap(foo, 1, 1), 1, 1)(x)\n self.assertEqual(result, x * 2)\n\n def test_in_dims_wrong_type_err_msg(self):\n x = torch.randn(3)\n y = torch.randn(3)\n msg = 'expected `in_dims` to be int or tuple'\n with self.assertRaisesRegex(ValueError, msg):\n vmap(torch.mul, [0, 0])(x, y)\n with self.assertRaisesRegex(ValueError, msg):\n vmap(torch.mul, set({0, 0}))(x, y)\n with self.assertRaisesRegex(ValueError, msg):\n vmap(torch.mul, 'lol')(x, y)\n # The following should not throw\n vmap(torch.mul, (0, 0))(x, y)\n\n def test_not_enough_in_dims_err_msg(self):\n x = torch.randn(3)\n y = torch.randn(3)\n msg = r'expected one `in_dim` per input \\(got \\w+ inputs\\)'\n\n with self.assertRaisesRegex(ValueError, msg):\n vmap(torch.mul, (0,))(x, y)\n with self.assertRaisesRegex(ValueError, msg):\n vmap(torch.mul, (0, 0, 0))(x, y)\n # The following should not throw\n vmap(torch.mul, (0, 0))(x, y)\n\n def test_in_dims_must_be_flat_tuple_err_msg(self):\n msg = 'in_dims must be a flat tuple containing ints and/or Nones'\n\n x = torch.randn(3)\n y = torch.randn(3)\n z = torch.randn(3)\n\n def foo(xy):\n return xy[0] * xy[1]\n\n def bar(x, yz):\n return x * yz[0] * yz[1]\n\n # NB: jax supports all of the following, we don't yet.\n with self.assertRaisesRegex(ValueError, msg):\n vmap(foo, ((0, 0),))((x, y))\n with self.assertRaisesRegex(ValueError, msg):\n vmap(bar, (0, (0, 0)))(x, (y, z))\n with self.assertRaisesRegex(ValueError, msg):\n vmap(foo, ({0: 0, 1: 0},))({0: x, 1: y})\n\n def test_integer_in_dim_but_not_tensor_input_err_msg(self):\n def foo(xy):\n return xy[0] * xy[1]\n\n def bar(x, yz):\n return x * yz[0] * yz[1]\n\n x = torch.randn(2, 3)\n y = torch.randn(2, 3)\n\n # jax supports these, we too can in the future.\n msg = 'Got in_dim=0 for input 0, but input 0 is not a Tensor'\n with self.assertRaisesRegex(ValueError, msg):\n vmap(foo)((x, y))\n with self.assertRaisesRegex(ValueError, msg):\n vmap(foo, (0,))((x, y))\n\n # jax supports these as well, we too can in the future.\n msg = 'Got in_dim=0 for input 1, but input 1 is not a Tensor'\n with self.assertRaisesRegex(ValueError, msg):\n vmap(foo)(x, (x, y))\n with self.assertRaisesRegex(ValueError, msg):\n vmap(foo, (0, 0))(x, (x, y))\n\n # the following are errors in jax (and will always be errors)\n msg = 'Got in_dim=0 for input 1, but input 1 is not a Tensor'\n with self.assertRaisesRegex(ValueError, msg):\n vmap(torch.sum)(x, 0)\n with self.assertRaisesRegex(ValueError, msg):\n vmap(torch.sum, (0, 0))(x, 0)\n # The following should not throw\n vmap(torch.sum, (0, None))(x, 0)\n\n def test_in_dim_not_in_tensor_err_msg(self):\n def foo(x):\n return x * x\n\n msg = r'Got in_dim=-?\\w for input 0, but input 0 is a Tensor of dimensionality \\w'\n with self.assertRaisesRegex(ValueError, msg):\n vmap(foo)(torch.randn([]))\n with self.assertRaisesRegex(ValueError, msg):\n vmap(foo, in_dims=(0,))(torch.randn([]))\n with self.assertRaisesRegex(ValueError, msg):\n vmap(foo, in_dims=(-1,))(torch.randn(2, 3))\n with self.assertRaisesRegex(ValueError, msg):\n vmap(foo, in_dims=(2,))(torch.randn(2, 3))\n # the following should not throw\n vmap(foo, in_dims=(0,))(torch.randn(2, 3))\n vmap(foo, in_dims=(1,))(torch.randn(2, 3))\n\n def test_fallback_sub(self):\n # NB: One day we will implement a batching rule for torch.sub.\n # If/when we do, this test should be replaced to test the fallback\n # path on another operator to avoid bitrot.\n x = torch.randn(5, 7, 11)\n y = torch.randn(5, 7, 11)\n\n # Test the fallback path raises a warning\n with warnings.catch_warnings(record=True) as wa:\n result = vmap(torch.sub)(x, y)\n self.assertEqual(len(wa), 2)\n self.assertRegex(str(wa[-1].message),\n r'falling back to slow \\(for loop and stack\\) implementation')\n self.assertEqual(result, x - y)\n\n # fallback on torch.sub\n x = torch.randn(7, 11, 5)\n y = torch.randn(5, 7, 11)\n result = vmap(torch.sub, (2, 0))(x, y)\n self.assertEqual(result, x.permute(2, 0, 1) - y)\n\n # fallback on torch.sub, nested vmap\n x = torch.randn(7, 11, 5)\n y = torch.randn(5, 7, 11)\n result = vmap(vmap(torch.sub), (2, 0))(x, y)\n self.assertEqual(result, x.permute(2, 0, 1) - y)\n\n # big batch size (total 10000)\n x = torch.randn(100, 10, 10, 5)\n y = torch.randn(100, 10, 10)\n result = vmap(vmap(vmap(torch.sub)))(x, y)\n self.assertEqual(result, x - y.view(100, 10, 10, 1))\n\n def test_fallback_masked_fill(self):\n # NB: One day we will implement a batching rule for masked_fill\n # If/when we do, this test should be replaced to test the fallback\n # path on another operator to avoid bitrot.\n def run_test(batch_size):\n B0 = batch_size\n x = torch.randn(B0, 7, 11, 13)\n dim = 0\n index = torch.tensor([0, 4, 2])\n values = torch.randn(B0, 3, 13)\n\n with warnings.catch_warnings(record=True) as wa:\n result = vmap(torch.index_add, (0, None, None, 0))(x, dim, index, values)\n self.assertEqual(len(wa), 2)\n self.assertRegex(str(wa[-1].message),\n r'falling back to slow \\(for loop and stack\\) implementation')\n expected = torch.index_add(\n x, dim + 1, index, values.view(B0, 3, 1, 13))\n self.assertEqual(result, expected)\n\n run_test(batch_size=5)\n run_test(batch_size=1237)\n\n\ndef slice_inputs(inputs, bdims, i):\n result = []\n for inp, bdim in zip(inputs, bdims):\n if bdim is None:\n result.append(inp)\n else:\n result.append(inp.select(bdim, i))\n return tuple(result)\n\n\ndef reference_vmap(op, inputs, in_dims=0, out_dims=0):\n if isinstance(in_dims, int):\n in_dims = (in_dims,) * len(inputs)\n bdim_sizes = [inp.size(dim) for inp, dim in zip(inputs, in_dims) if dim is not None]\n assert all(bdim_size == bdim_sizes[0] for bdim_size in bdim_sizes)\n bdim_size = bdim_sizes[0]\n results = tuple(op(*slice_inputs(inputs, in_dims, i)) for i in range(bdim_size))\n # reference_vmap only supports functions that return a single Tensor output\n assert all(isinstance(result, torch.Tensor) for result in results)\n if isinstance(out_dims, int):\n out_dims = (out_dims,) * 1\n return torch.stack(results, dim=out_dims[0])\n\n\nclass TestVmapOperators(TestCase):\n def _vmap_view_test(self, op, inputs, in_dims=0, out_dims=0):\n result = vmap(op, in_dims, out_dims)(*inputs)\n reference_result = reference_vmap(op, inputs, in_dims, out_dims)\n self.assertEqual(result, reference_result)\n self.assertEqual(result.data_ptr() - result.storage_offset() * result.element_size(),\n inputs[0].data_ptr(),\n msg=\"result was not a view of the first input!\")\n\n # Assuming input[0] is a floating-point tensor. Check if the vmap\n # operation propagates the requires_grad flag. Some vmap operators are\n # implemented in a way that assumes that they are composite with respect\n # to autograd. If the operator ever is changed to not be composite with\n # respect to autograd, then the following check should fail.\n inputs_clone = list(inputs)\n inputs_clone[0] = inputs[0].clone().requires_grad_()\n result = vmap(op, in_dims, out_dims)(*inputs_clone)\n self.assertTrue(result.requires_grad)\n\n def test_diagonal(self):\n tensor = torch.randn(3, 5, 7, 11, 13)\n test = self._vmap_view_test\n op = torch.diagonal\n test(op, (tensor, 1, 0, 1), in_dims=(0, None, None, None))\n test(op, (tensor, 0, 2, -1), in_dims=(0, None, None, None))\n test(op, (tensor, 2, 1, 2), in_dims=(1, None, None, None))\n test(op, (tensor, 0, -2, -1), in_dims=(1, None, None, None), out_dims=1)\n test(vmap(lambda t: op(t, 0, 0, -1)), (tensor,), in_dims=1, out_dims=1)\n test(vmap(vmap(lambda t: op(t, 0, 0, 1), in_dims=1), in_dims=3),\n (tensor,), in_dims=1, out_dims=1)\n\n def test_expand_as(self):\n op = torch.Tensor.expand_as\n test = self._vmap_view_test\n B0, B1, B2 = 7, 11, 13\n test(op, (torch.rand(B0, 1, 5), torch.rand(B0, 2, 3, 5)))\n test(op, (torch.rand(B0, 1, 5), torch.rand(2, 3, 5)), in_dims=(0, None))\n test(op, (torch.rand(1, 5), torch.rand(B0, 2, 3, 5)), in_dims=(None, 0))\n test(vmap(op), (torch.rand(B0, B1, 1, 5), torch.rand(B0, B1, 2, 3, 5)))\n test(vmap(op), (torch.rand(B0, B1, 1, 5), torch.rand(B1, B0, 2, 3, 5)), in_dims=(0, 1))\n test(vmap(op), (torch.rand(B0, B1), torch.rand(B1, 2, 3, 5)), in_dims=(0, None))\n test(vmap(vmap(op)), (torch.rand(B0, B1, B2), torch.rand(B0, B1, B2, 2, 3, 5)))\n\n def test_select(self):\n op = torch.select\n test = self._vmap_view_test\n B0, B1, B2 = 7, 11, 13\n test(op, (torch.rand(B0, 2, 5), 0, 0), in_dims=(0, None, None))\n test(op, (torch.rand(2, B0, 5), 1, 1), in_dims=(1, None, None))\n test(vmap(lambda t: op(t, 1, 1)), (torch.rand(B1, 2, B0, 5),), in_dims=2)\n test(vmap(vmap(lambda t: op(t, 1, 1), in_dims=1)), (torch.rand(B1, 2, B0, B2, 5),), in_dims=2)\n\n def test_slice(self):\n test = self._vmap_view_test\n B0, B1, B2 = 7, 11, 13\n test(lambda t: t[0:1], (torch.rand(B0, 3, 5),))\n test(lambda t: t[:, 1:3], (torch.rand(3, 5, B0),), in_dims=2)\n test(vmap(lambda t: t[:, 0:1], in_dims=2), (torch.rand(3, 5, B0, B1),), in_dims=2)\n test(vmap(vmap(lambda t: t[0:1], in_dims=2), in_dims=2),\n (torch.rand(3, 5, B0, B1, B2),), in_dims=2)\n\n def test_t(self):\n op = torch.t\n test = self._vmap_view_test\n B0, B1, B2 = 7, 11, 13\n test(op, (torch.rand(B0, 2, 5),))\n test(op, (torch.rand(2, B0, 5),), in_dims=1)\n test(vmap(op), (torch.rand(B1, 2, B0, 5),), in_dims=2)\n test(vmap(vmap(op, in_dims=2)), (torch.rand(B1, 2, B0, 5, B2),), in_dims=2)\n\n\nif __name__ == '__main__':\n run_tests()\n","sub_path":"test/test_vmap.py","file_name":"test_vmap.py","file_ext":"py","file_size_in_byte":23510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"423161334","text":"from machine import Pin\nimport utime\n\n# Initialize the LED lights and buttons\nled = Pin(25, Pin.OUT)\nkey = Pin(0, Pin.IN, Pin.PULL_UP)\n\n\n# Open the LED light that comes with the Pico board\ndef led_on():\n led.value(1)\n\n# Close the LED light that comes with the Pico board\ndef led_off():\n led.value(0)\n\n# Read the state of the button, press to return to True, release to return to False\ndef press_state():\n if key.value() == 0:\n return True\n return False\n\n\n# Main loop, when the button is pressed, the LED is on, and “press” is printed every 100 milliseconds; \n# when the button is released, the LED is off\nwhile True:\n if press_state() == True:\n print(\"press\")\n led_on()\n utime.sleep(.1)\n else:\n led_off()\n ","sub_path":"3.Basic course/1.Button control/Button_control.py","file_name":"Button_control.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"439449159","text":"from .. import Property, ObjectProperty, ControlledObjectProperty, ArrayProperty\n\ndef property_new(collection):\n\n print ()\n\n # Name\n #\n user_input_valid = False\n while not user_input_valid:\n name_input = input(\n 'Property name: '\n )\n if isinstance(name_input, str) and len(name_input) > 0:\n user_input_valid = True\n name = name_input\n del name_input\n else:\n print(\n '\\nInvalid name entered\\n\\n'\n )\n \n # Type\n #\n user_input_valid = False\n while not user_input_valid:\n type_input = input(\n 'Select a property type:\\n'+\n '(I) Object ID | (S) String | (N) Number | (B) Boolean\\n'+\n '(A) Array | (O) Object | (C) Controlled Object | (X) Any\\n'\n )\n if type_input in ['O', 'o']:\n user_input_valid = True\n prop_type = 'ObjectProperty'\n del type_input\n elif type_input in ['C', 'c']:\n user_input_valid = True\n prop_type = 'ControlledObjectProperty'\n del type_input\n elif type_input in ['S', 's']:\n user_input_valid = True\n prop_type = 'String'\n del type_input\n elif type_input in ['B', 'b']:\n user_input_valid = True\n prop_type = 'Boolean'\n del type_input\n elif type_input in ['N', 'n']:\n user_input_valid = True\n prop_type = 'Number'\n del type_input\n elif type_input in ['I', 'i']:\n user_input_valid = True\n prop_type = 'ObjectID'\n del type_input\n elif type_input in ['A', 'a']:\n user_input_valid = True\n prop_type = 'ArrayProperty'\n del type_input\n elif type_input in ['X', 'x']:\n user_input_valid = True\n prop_type = 'Any'\n del type_input\n else:\n print(\n '\\nInvalid property type selected\\n\\n'\n )\n \n # Optional\n #\n user_input_valid = False\n while not user_input_valid:\n optional_input = input(\n 'Optional property? (Y/N): '\n )\n if optional_input in ['Y', 'y']:\n user_input_valid = True\n optional = True\n del optional_input\n elif optional_input in ['N', 'n']:\n user_input_valid = True\n optional = False\n del optional_input\n else:\n print(\n '\\nInvalid option selected\\n\\n'\n )\n\n # ObjectProperty\n #\n if prop_type == 'ObjectProperty':\n new_property = ObjectProperty(name=name, optional=optional)\n\n # ControlledObjectProperty\n #\n elif prop_type == 'ControlledObjectProperty':\n\n # Controller name\n #\n user_input_valid = False\n while not user_input_valid:\n controller_input = input(\n 'Controller property name: '\n )\n if isinstance(controller_input, str) and len(controller_input) > 0:\n user_input_valid = True\n controller = controller_input\n del controller_input\n else:\n print(\n '\\nInvalid controller name entered\\n\\n'\n )\n \n new_property = ControlledObjectProperty(name=name, controller=Property(name=controller, type='Boolean'), optional=optional)\n \n # ArrayProperty\n #\n elif prop_type == 'ArrayProperty':\n\n # Element type\n #\n user_input_valid = False\n while not user_input_valid:\n property_type_input = input(\n 'Select an element type:\\n'+\n '(I) ObjectID | (S) String\\n'+\n '(B) Boolean | (N) Number | (X) Any\\n'\n )\n if property_type_input in ['I', 'i']:\n user_input_valid = True\n property_type = 'ObjectID'\n del property_type_input\n elif property_type_input in ['S', 's']:\n user_input_valid = True\n property_type = 'String'\n del property_type_input\n elif property_type_input in ['N', 'n']:\n user_input_valid = True\n property_type = 'Number'\n del property_type_input\n elif property_type_input in ['B', 'b']:\n user_input_valid = True\n property_type = 'Boolean'\n del property_type_input\n elif property_type_input in ['X', 'x']:\n user_input_valid = True\n property_type = 'Any'\n del property_type_input\n else:\n print(\n '\\nInvalid type selected\\n\\n'\n )\n\n new_property = ArrayProperty(name=name, property_type=property_type, optional=optional)\n \n # Other types\n #\n else:\n new_property = Property(name=name, type=prop_type, optional=optional)\n \n collection.add_properties([new_property])\n\n if new_property.type == 'ObjectProperty' or new_property.type == 'ControlledObjectProperty':\n return ('property_view', new_property, False)\n else:\n return (None, None, False)\n\ndef property_view(prop):\n \n # Delegate to specific function depending on property type\n #\n if prop.type == 'ObjectProperty':\n return property_view_object_property(prop)\n elif prop.type == 'ControlledObjectProperty':\n return property_view_controlled_object_property(prop)\n elif prop.type == 'ArrayProperty':\n return property_view_array_property(prop)\n else:\n return property_view_property(prop)\n\ndef property_view_property(prop):\n \n print()\n\n # Show property data\n #\n if prop.optional:\n optional = 'Yes'\n else:\n optional = 'No'\n print(\n '\\n Property {name}\\n Type: {type}\\n Optional: {optional}\\n'.format(name=prop.name, type=prop.type, optional=optional)\n )\n\n # User\n #\n user_input_valid = False\n while not user_input_valid:\n user_input = input(\n '(X) Back\\n'\n )\n if user_input in ['X', 'x']:\n user_input_valid = True\n return (None, None, False)\n\n print('\\nInvalid input\\n\\n')\n\ndef property_view_object_property(prop):\n \n print()\n\n # Show property data\n #\n if prop.optional:\n optional = 'Yes'\n else:\n optional = 'No'\n print(\n '\\n Property {name}\\n Type: {type}\\n Optional: {optional}\\n'.format(name=prop.name, type=prop.type, optional=optional)\n )\n\n # Show properties\n #\n print(\n ' Properties:\\n'\n )\n for i in range(0, len(prop.properties)):\n if prop.properties[i].optional:\n optional = '*'\n else:\n optional = ''\n print(\n ' ({i}) {name} ({type}){optional}'.format(i=str(i).center(5, ' '), name=prop.properties[i].name, type=prop.properties[i].type, optional=optional)\n )\n if len(prop.properties) == 0:\n print(\n ' No properties'\n )\n print('\\n')\n\n # User\n #\n user_input_valid = False\n while not user_input_valid:\n user_input = input(\n '(N) New property | (O#) Open property by index | (X) Back\\n'\n )\n if user_input in ['N', 'n']:\n user_input_valid = True\n return ('property_new', prop, True)\n elif user_input in ['X', 'x']:\n user_input_valid = True\n return (None, None, False)\n elif len(user_input) > 1:\n if user_input[0] in ['O', 'o'] and user_input[1:].isdigit():\n try:\n return ('property_view', prop.properties[int(user_input[1:])], True)\n except:\n pass\n \n print('\\nInvalid input\\n\\n')\n\ndef property_view_controlled_object_property(prop):\n\n print()\n \n # Show property data\n #\n if prop.optional:\n optional = True\n else:\n optional = False\n print(\n '\\n Property {name}\\n Type: {type}\\n Optional: {optional}\\n'.format(name=prop.name, type=prop.type, optional=optional)\n )\n\n # Show controller\n #\n print(\n ' Controller:\\n\\n {name} ({type})\\n'.format(name=prop.controller.name, type=prop.controller.type)\n )\n\n # Show properties\n #\n print(\n ' Properties:\\n'\n )\n for i in range(0, len(prop.properties)):\n if prop.properties[i].optional:\n optional = '*'\n else:\n optional = ''\n print(\n ' ({i}) {name} ({type}){optional}'.format(i=str(i).center(5, ' '), name=prop.properties[i].name, type=prop.properties[i].type, optional=optional)\n )\n if len(prop.properties) == 0:\n print(\n ' No properties'\n )\n print('\\n')\n\n # User\n #\n user_input_valid = False\n while not user_input_valid:\n user_input = input(\n '(N) New property | (O#) Open property by index | (X) Back\\n'\n )\n if user_input in ['N', 'n']:\n user_input_valid = True\n return ('property_new', prop, True)\n elif user_input in ['X', 'x']:\n user_input_valid = True\n return (None, None, False)\n elif len(user_input) > 1:\n if user_input[0] in ['O', 'o'] and user_input[1:].isdigit():\n try:\n return ('property_view', prop.properties[int(user_input[1:])], True)\n except:\n pass\n\n print('\\nInvalid input\\n\\n')\n\ndef property_view_array_property(prop):\n \n print()\n\n # Show property data\n #\n if prop.optional:\n optional = 'Yes'\n else:\n optional = 'No'\n print(\n '\\n Property {name}\\n Type: {type}\\n Element type: {property_type}\\n Optional: {optional}\\n'.format(name=prop.name, type=prop.type, property_type=prop.property_type, optional=optional)\n )\n\n # User\n #\n user_input_valid = False\n while not user_input_valid:\n user_input = input(\n '(X) Back\\n'\n )\n if user_input in ['X', 'x']:\n user_input_valid = True\n return (None, None, False)\n\n print('\\nInvalid input\\n\\n')\n","sub_path":"src/screens/property.py","file_name":"property.py","file_ext":"py","file_size_in_byte":8976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"161959090","text":"# coding=utf-8\n# 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# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom functools import update_wrapper, reduce, partial\nimport inspect\nimport operator as op\n\nfrom . import core\nfrom . import linear_util as lu\nfrom .tree_util import tree_flatten, tree_unflatten, tree_map, tree_multimap\nfrom .util import safe_zip, safe_map, unzip2, split_list\nfrom .api_util import flatten_fun_nokwargs, argnums_partial, wrap_hashably\nfrom .abstract_arrays import raise_to_shaped\nfrom .ad_util import Zero, stop_gradient_p\nfrom .interpreters import partial_eval as pe\nfrom .interpreters import ad\nfrom .interpreters import batching\nfrom .interpreters import xla\nfrom .interpreters.batching import not_mapped\nfrom .config import config\n\nmap = safe_map\nzip = safe_zip\n\n\n### util\n\ndef _resolve_kwargs(fun, args, kwargs):\n ba = inspect.signature(fun).bind(*args, **kwargs)\n ba.apply_defaults()\n if ba.kwargs:\n raise TypeError(\"keyword arguments could not be resolved to positions\")\n else:\n return ba.args\n\ndef _add_args(f, extra_args, left):\n return _add_args_(f, tuple(map(wrap_hashably, extra_args)), left)\n\n@lu.transformation\ndef _add_args_(extra_args, left, *args, **kwargs):\n extra_args = tuple([arg.val for arg in extra_args])\n args = (extra_args + args) if left else (args + extra_args)\n yield (yield args, kwargs)\n\ndef _memoize(thunk):\n cell = []\n saved_state = core.thread_local_state.trace_state.copy()\n def memoized():\n if not cell:\n prev_state = core.thread_local_state.trace_state\n core.thread_local_state.trace_state = saved_state\n try:\n cell.append(thunk())\n finally:\n core.thread_local_state.trace_state = prev_state\n return cell[0]\n return memoized\n\ndef _initial_style_jaxpr(fun, in_avals):\n in_pvals = [pe.PartialVal.unknown(aval) for aval in in_avals]\n jaxpr, out_pvals, consts = pe.trace_to_jaxpr(fun, in_pvals, instantiate=True,\n bottom=True, stage_out=False)\n assert not any(isinstance(c, core.Tracer) for c in consts)\n out_avals = map(raise_to_shaped, unzip2(out_pvals)[0])\n typed_jaxpr = core.TypedJaxpr(jaxpr, consts, in_avals, out_avals)\n return typed_jaxpr\n\ndef _initial_style_staging() -> bool:\n if config.omnistaging_enabled:\n return core.thread_local_state.trace_state.trace_stack.dynamic.level != 0 # type: ignore\n else:\n return core.thread_local_state.trace_state.initial_style\n\ndef _sum_tangents(_, x, *xs):\n return reduce(ad.add_tangents, xs, x)\n\ndef _zeros_like_pytree(x):\n return tree_map(Zero.from_value, x)\n\n@partial(partial, tree_map)\ndef _stop_gradient(x):\n if isinstance(x, core.Tracer):\n return stop_gradient_p.bind(x)\n else:\n return x\n\n\n### JVPs\n\nclass custom_jvp:\n \"\"\"Set up a JAX-transformable function for a custom JVP rule definition.\n\n This class is meant to be used as a function decorator. Instances are\n callables that behave similarly to the underlying function to which the\n decorator was applied, except when a differentiation transformation (like\n :py:func:`jax.jvp` or :py:func:`jax.grad`) is applied, in which case a custom user-supplied\n JVP rule function is used instead of tracing into and performing automatic\n differentiation of the underlying function's implementation. There is a single\n instance method, ``defjvp``, which defines the custom JVP rule.\n\n For example::\n\n import jax.numpy as jnp\n\n @jax.custom_jvp\n def f(x, y):\n return jnp.sin(x) * y\n\n @f.defjvp\n def f_jvp(primals, tangents):\n x, y = primals\n x_dot, y_dot = tangents\n primal_out = f(x, y)\n tangent_out = jnp.cos(x) * x_dot * y + jnp.sin(x) * y_dot\n return primal_out, tangent_out\n\n For a more detailed introduction, see the tutorial_.\n\n .. _tutorial: https://jax.readthedocs.io/en/latest/notebooks/Custom_derivative_rules_for_Python_code.html\n \"\"\"\n\n def __init__(self, fun, nondiff_argnums=()):\n self.fun = fun\n self.nondiff_argnums = nondiff_argnums\n self.jvp = None\n update_wrapper(self, fun)\n\n def defjvp(self, jvp):\n \"\"\"Define a custom JVP rule for the function represented by this instance.\n\n Args:\n jvp: a Python callable representing the custom JVP rule. When there are no\n ``nondiff_argnums``, the ``jvp`` function should accept two arguments,\n where the first is a tuple of primal inputs and the second is a tuple of\n tangent inputs. The lengths of both tuples is equal to the number of\n parameters of the ``custom_jvp`` function. The ``jvp`` function should\n produce as output a pair where the first element is the primal output\n and the second element is the tangent output. Elements of the input and\n output tuples may be arrays or any nested tuples/lists/dicts thereof.\n\n Returns:\n None.\n\n Example::\n\n import jax.numpy as jnp\n\n @jax.custom_jvp\n def f(x, y):\n return jnp.sin(x) * y\n\n @f.defjvp\n def f_jvp(primals, tangents):\n x, y = primals\n x_dot, y_dot = tangents\n primal_out = f(x, y)\n tangent_out = jnp.cos(x) * x_dot * y + jnp.sin(x) * y_dot\n return primal_out, tangent_out\n \"\"\"\n self.jvp = jvp\n\n def defjvps(self, *jvps):\n \"\"\"Convenience wrapper for defining JVPs for each argument separately.\n\n This convenience wrapper cannot be used together with ``nondiff_argnums``.\n\n Args:\n *jvps: a sequence of functions, one for each positional argument of the\n ``custom_jvp`` function. Each function takes as arguments the tangent\n value for the corresponding primal input, the primal output, and the\n primal inputs. See the example below.\n\n Returns:\n None.\n\n Example::\n\n @jax.custom_jvp\n def f(x, y):\n return jnp.sin(x) * y\n\n f.defjvps(lambda x_dot, primal_out, x, y: jnp.cos(x) * x_dot * y,\n lambda y_dot, primal_out, x, y: jnp.sin(x) * y_dot)\n \"\"\"\n if self.nondiff_argnums:\n raise TypeError(\"Can't use ``defjvps`` with ``nondiff_argnums``.\")\n\n def jvp(primals, tangents):\n primal_out = self(*primals)\n zeros = _zeros_like_pytree(primal_out)\n all_tangents_out = [jvp(t, primal_out, *primals) if jvp else zeros\n for t, jvp in zip(tangents, jvps)]\n tangent_out = tree_multimap(_sum_tangents, primal_out, *all_tangents_out)\n return primal_out, tangent_out\n\n self.defjvp(jvp)\n\n def __call__(self, *args, **kwargs):\n if not self.jvp:\n msg = \"No JVP defined for custom_jvp function {} using defjvp.\"\n raise AttributeError(msg.format(self.__name__))\n args = _resolve_kwargs(self.fun, args, kwargs)\n if self.nondiff_argnums:\n is_nondiff = [False] * len(args)\n for i in self.nondiff_argnums: is_nondiff[i] = True\n args = [_stop_gradient(x) if b else x for b, x in zip(is_nondiff, args)]\n dyn_argnums = [i for i, b in enumerate(is_nondiff) if not b]\n f_, dyn_args = argnums_partial(lu.wrap_init(self.fun), dyn_argnums, args)\n static_args = [args[i] for i in self.nondiff_argnums]\n jvp = _add_args(lu.wrap_init(self.jvp), static_args, left=True)\n else:\n f_, dyn_args = lu.wrap_init(self.fun), args\n jvp = lu.wrap_init(self.jvp)\n args_flat, in_tree = tree_flatten(dyn_args)\n flat_fun, out_tree1 = flatten_fun_nokwargs(f_, in_tree)\n flat_jvp, out_tree2 = _flatten_jvp(jvp, in_tree)\n if _initial_style_staging():\n out_flat = custom_jvp_call_jaxpr(flat_fun, flat_jvp, *args_flat)\n out_tree = out_tree1()\n else:\n out_flat = custom_jvp_call(flat_fun, flat_jvp, *args_flat)\n _, out_tree = lu.merge_linear_aux(out_tree1, out_tree2)\n return tree_unflatten(out_tree, out_flat)\n\n@lu.transformation_with_aux\ndef _flatten_jvp(in_tree, *args):\n primals_in, tangents_in = split_list(args, [len(args) // 2])\n py_primals = tree_unflatten(in_tree, primals_in)\n py_tangents = tree_unflatten(in_tree, tangents_in)\n pair_out = yield (py_primals, py_tangents), {}\n if not isinstance(pair_out, (list, tuple)) or len(pair_out) != 2:\n msg = (\"Custom JVP rule must produce a pair (list or tuple of length two) \"\n \"representing primal and tangent outputs, got {}.\")\n raise TypeError(msg.format(pair_out))\n py_primals_out, py_tangents_out = pair_out\n primals_out, out_tree = tree_flatten(py_primals_out)\n tangents_out, out_tree2 = tree_flatten(py_tangents_out)\n if out_tree != out_tree2:\n msg = (\"Custom JVP rule must produce primal and tangent outputs with equal \"\n \"container (pytree) structures, but got {} and {} respectively.\")\n raise TypeError(msg.format(out_tree, out_tree2))\n primal_avals_out = [raise_to_shaped(core.get_aval(x)) for x in primals_out]\n tangent_avals_out = [raise_to_shaped(core.get_aval(t)) for t in tangents_out]\n if primal_avals_out != tangent_avals_out:\n if len(primal_avals_out) == 1:\n (av1,), (av2,) = primal_avals_out, tangent_avals_out\n msg = (\"Custom JVP rule must produce primal and tangent outputs with \"\n \"equal shapes and dtypes, but got {} and {} respectively.\")\n raise TypeError(msg.format(av1.str_short(), av2.str_short()))\n else:\n msg = (\"Custom JVP rule must produce primal and tangent outputs with \"\n \"equal shapes and dtypes, but got:\\n{}\")\n disagreements = (\n \" primal {} for tangent {}\".format(av1.str_short(), av2.str_short())\n for av1, av2 in zip(primal_avals_out, tangent_avals_out) if av1 != av2)\n raise TypeError(msg.format('\\n'.join(disagreements)))\n yield primals_out + tangents_out, out_tree\n\nclass CustomJVPCallPrimitive(core.CallPrimitive):\n def bind(self, fun, jvp, *args):\n args = map(core.full_lower, args)\n top_trace = core.find_top_trace(args)\n fun, env_trace_todo1 = core.process_env_traces(\n fun, self, top_trace and top_trace.level, ())\n jvp, env_trace_todo2 = core.process_env_traces(\n jvp, self, top_trace and top_trace.level, ())\n if top_trace is None:\n with core.new_sublevel():\n outs = self.impl(fun, jvp, *args)\n else:\n tracers = map(top_trace.full_raise, args)\n outs = top_trace.process_custom_jvp_call(self, fun, jvp, tracers)\n _, env_trace_todo = lu.merge_linear_aux(env_trace_todo1, env_trace_todo2)\n if env_trace_todo:\n raise core.UnexpectedTracerError\n return map(core.full_lower, outs)\n\n def impl(self, fun, _, *args):\n return fun.call_wrapped(*args)\n\ncustom_jvp_call_p = CustomJVPCallPrimitive('custom_jvp_call')\ncustom_jvp_call = custom_jvp_call_p.bind\n\n\ndef custom_jvp_call_jaxpr(fun, jvp, *args):\n in_avals = [raise_to_shaped(core.get_aval(x)) for x in args]\n fun_jaxpr = _initial_style_jaxpr(fun, in_avals)\n jvp_jaxpr_thunk = _memoize(lambda: _initial_style_jaxpr(jvp, in_avals * 2))\n return custom_jvp_call_jaxpr_p.bind(*args, fun_jaxpr=fun_jaxpr,\n jvp_jaxpr_thunk=jvp_jaxpr_thunk)\n\ndef _custom_jvp_call_jaxpr_impl(*args, fun_jaxpr, **_):\n return core.jaxpr_as_fun(fun_jaxpr)(*args)\n\ndef _custom_jvp_call_jaxpr_abstract_eval(*_, fun_jaxpr, **__):\n return fun_jaxpr.out_avals\n\ncustom_jvp_call_jaxpr_p = core.Primitive('custom_jvp_call_jaxpr')\ncustom_jvp_call_jaxpr_p.multiple_results = True\ncustom_jvp_call_jaxpr_p.def_impl(_custom_jvp_call_jaxpr_impl)\ncustom_jvp_call_jaxpr_p.def_abstract_eval(_custom_jvp_call_jaxpr_abstract_eval)\n\ndef _custom_jvp_call_jaxpr_jvp(primals, tangents, *, fun_jaxpr, jvp_jaxpr_thunk):\n jvp_jaxpr = jvp_jaxpr_thunk()\n tangents = map(ad.instantiate_zeros, tangents)\n outs = core.jaxpr_as_fun(jvp_jaxpr)(*primals, *tangents)\n return split_list(outs, [len(outs) // 2])\nad.primitive_jvps[custom_jvp_call_jaxpr_p] = _custom_jvp_call_jaxpr_jvp\n\ndef _custom_jvp_call_jaxpr_vmap(args, in_dims, *, fun_jaxpr, jvp_jaxpr_thunk):\n size, = {x.shape[d] for x, d in zip(args, in_dims) if d is not not_mapped}\n args = [batching.moveaxis(x, d, 0) if d is not not_mapped and d != 0\n else x for x, d in zip(args, in_dims)]\n num_out = len(fun_jaxpr.out_avals)\n\n in_batched = [d is not not_mapped for d in in_dims]\n batched_fun_jaxpr, out_batched = batching.batch_jaxpr(fun_jaxpr, size, in_batched, False)\n out_dims1 = [0 if b else not_mapped for b in out_batched]\n out_dims2 = []\n\n @_memoize\n def batched_jvp_jaxpr_thunk():\n jvp_jaxpr = jvp_jaxpr_thunk()\n _, all_batched = batching.batch_jaxpr(jvp_jaxpr, size, in_batched * 2, False)\n primals_batched, tangents_batched = split_list(all_batched, [num_out])\n out_batched = map(op.or_, primals_batched, tangents_batched)\n out_dims2.append([0 if b else not_mapped for b in out_batched])\n batched_jvp_jaxpr, _ = batching.batch_jaxpr(jvp_jaxpr, size, in_batched * 2,\n out_batched * 2)\n return batched_jvp_jaxpr\n\n batched_outs = custom_jvp_call_jaxpr_p.bind(\n *args, fun_jaxpr=batched_fun_jaxpr, jvp_jaxpr_thunk=batched_jvp_jaxpr_thunk)\n out_dims = out_dims2[0] if out_dims2 else out_dims1\n return batched_outs, out_dims\nbatching.primitive_batchers[custom_jvp_call_jaxpr_p] = _custom_jvp_call_jaxpr_vmap\n\nxla.initial_style_translations[custom_jvp_call_jaxpr_p] = \\\n xla.lower_fun_initial_style(_custom_jvp_call_jaxpr_impl)\n\n# If a (multi)linear function is defined with a custom jvp, then\n# custom_jvp_call_jaxpr can appear in jaxprs to be transposed. Since it's\n# already been linearized, we can drop the jvp rule.\ndef _custom_jvp_call_jaxpr_transpose(cts, *args, fun_jaxpr, jvp_jaxpr_thunk):\n del jvp_jaxpr_thunk\n return ad.backward_pass(fun_jaxpr.jaxpr, fun_jaxpr.literals, args, cts)\nad.primitive_transposes[custom_jvp_call_jaxpr_p] = _custom_jvp_call_jaxpr_transpose\n\n\n### VJPs\n\nclass custom_vjp:\n \"\"\"Set up a JAX-transformable function for a custom VJP rule definition.\n\n This class is meant to be used as a function decorator. Instances are\n callables that behave similarly to the underlying function to which the\n decorator was applied, except when a reverse-mode differentiation\n transformation (like :py:func:`jax.grad`) is applied, in which case a custom\n user-supplied VJP rule function is used instead of tracing into and performing\n automatic differentiation of the underlying function's implementation. There\n is a single instance method, ``defvjp``, which defines the custom VJP rule.\n\n This decorator precludes the use of forward-mode automatic differentiation.\n\n For example::\n\n import jax.numpy as jnp\n\n @jax.custom_vjp\n def f(x, y):\n return jnp.sin(x) * y\n\n def f_fwd(x, y):\n return f(x, y), (jnp.cos(x), jnp.sin(x), y)\n\n def f_bwd(res, g):\n cos_x, sin_x, y = res\n return (cos_x * g * y, sin_x * g)\n\n f.defvjp(f_fwd, f_bwd)\n\n For a more detailed introduction, see the tutorial_.\n\n .. _tutorial: https://jax.readthedocs.io/en/latest/notebooks/Custom_derivative_rules_for_Python_code.html\n \"\"\"\n\n def __init__(self, fun, nondiff_argnums=()):\n self.fun = fun\n self.nondiff_argnums = nondiff_argnums\n self.fwd = None\n self.bwd = None\n update_wrapper(self, fun)\n\n def defvjp(self, fwd, bwd):\n \"\"\"Define a custom VJP rule for the function represented by this instance.\n\n Args:\n fwd: a Python callable representing the forward pass of the custom VJP\n rule. When there are no ``nondiff_argnums``, the ``fwd`` function has\n the same input signature as the underlying primal function. It should\n return as output a pair, where the first element represents the primal\n output and the second element represents any \"residual\" values to store\n from the forward pass for use on the backward pass by the function\n ``bwd``. Input arguments and elements of the output pair may be arrays\n or nested tuples/lists/dicts thereof.\n bwd: a Python callable representing the backward pass of the custom VJP\n rule. When there are no ``nondiff_argnums``, the ``bwd`` function takes\n two arguments, where the first is the \"residual\" values produced on the\n forward pass by ``fwd``, and the second is the output cotangent with the\n same structure as the primal function output. The output of ``bwd`` must\n be a tuple of length equal to the number of arguments of the primal\n function, and the tuple elements may be arrays or nested\n tuples/lists/dicts thereof so as to match the structure of the primal\n input arguments.\n\n Returns:\n None.\n\n Example::\n\n import jax.numpy as jnp\n\n @jax.custom_vjp\n def f(x, y):\n return jnp.sin(x) * y\n\n def f_fwd(x, y):\n return f(x, y), (jnp.cos(x), jnp.sin(x), y)\n\n def f_bwd(res, g):\n cos_x, sin_x, y = res\n return (cos_x * g * y, sin_x * g)\n\n f.defvjp(f_fwd, f_bwd)\n \"\"\"\n self.fwd = fwd\n self.bwd = bwd\n\n def __call__(self, *args, **kwargs):\n if not self.fwd or not self.bwd:\n msg = \"No VJP defined for custom_vjp function {} using defvjp.\"\n raise AttributeError(msg.format(self.__name__))\n args = _resolve_kwargs(self.fun, args, kwargs)\n if self.nondiff_argnums:\n is_nondiff = [False] * len(args)\n for i in self.nondiff_argnums: is_nondiff[i] = True\n args = [_stop_gradient(x) if b else x for b, x in zip(is_nondiff, args)]\n dyn_argnums = [i for i, b in enumerate(is_nondiff) if not b]\n f_, dyn_args = argnums_partial(lu.wrap_init(self.fun), dyn_argnums, args)\n static_args = [args[i] for i in self.nondiff_argnums]\n fwd, _ = argnums_partial(lu.wrap_init(self.fwd), dyn_argnums, args)\n bwd = _add_args(lu.wrap_init(self.bwd), static_args, left=True)\n else:\n f_, dyn_args = lu.wrap_init(self.fun), args\n fwd, bwd = lu.wrap_init(self.fwd), lu.wrap_init(self.bwd)\n args_flat, in_tree = tree_flatten(dyn_args)\n flat_fun, out_tree = flatten_fun_nokwargs(f_, in_tree)\n flat_fwd, out_trees = _flatten_fwd(fwd, in_tree)\n flat_bwd = _flatten_bwd(bwd, in_tree, out_trees)\n if _initial_style_staging():\n out_flat = custom_vjp_call_jaxpr(flat_fun, flat_fwd, flat_bwd,\n *args_flat, out_trees=out_trees)\n out_tree = out_tree()\n else:\n out_flat = custom_vjp_call(flat_fun, flat_fwd, flat_bwd,\n *args_flat, out_trees=out_trees)\n fst, aux = lu.merge_linear_aux(out_tree, out_trees)\n out_tree = aux if fst else aux[0]\n return tree_unflatten(out_tree, out_flat)\n\n@lu.transformation_with_aux\ndef _flatten_fwd(in_tree, *args):\n py_args = tree_unflatten(in_tree, args)\n pair_out = yield py_args, {}\n if not isinstance(pair_out, (list, tuple)) or len(pair_out) != 2:\n msg = (\"Custom VJP fwd function must produce a pair (list or tuple of \"\n \"length two) representing primal outputs and residuals (values \"\n \"stored from the forward pass for use on the backward pass), \"\n \"got {}.\")\n raise TypeError(msg.format(pair_out))\n py_outs, res = pair_out\n out, out_tree = tree_flatten(py_outs)\n res, res_tree = tree_flatten(res)\n yield res + out, (out_tree, res_tree)\n\n@lu.transformation\ndef _flatten_bwd(in_tree, out_trees, *args):\n out_tree, res_tree = out_trees()\n res, cts_out = split_list(args, [res_tree.num_leaves])\n py_res = tree_unflatten(res_tree, res)\n py_cts_out = tree_unflatten(out_tree, cts_out)\n py_cts_in = yield (py_res, py_cts_out), {}\n cts_in, in_tree2 = tree_flatten(py_cts_in)\n if in_tree != in_tree2:\n msg = (\"Custom VJP rule must produce an output with the same container \"\n \"(pytree) structure as the args tuple of the primal function, \"\n \"and in particular must produce a tuple of length equal to the \"\n \"number of arguments to the primal function, but got VJP output \"\n \"structure {} for primal input structure {}.\")\n raise TypeError(msg.format(in_tree2, in_tree)) from None\n yield cts_in\n\n\nclass CustomVJPCallPrimitive(core.CallPrimitive):\n def bind(self, fun, fwd, bwd, *args, out_trees):\n args = map(core.full_lower, args)\n top_trace = core.find_top_trace(args)\n if top_trace is None:\n outs = fun.call_wrapped(*args)\n else:\n tracers = map(top_trace.full_raise, args)\n outs = top_trace.process_custom_vjp_call(self, fun, fwd, bwd, tracers,\n out_trees=out_trees)\n return map(core.full_lower, outs)\n\n def impl(self, fun, fwd, bwd, *args, out_trees):\n del fwd, bwd, out_trees\n return fun.call_wrapped(*args)\n\ncustom_vjp_call_p = CustomVJPCallPrimitive('custom_vjp_call')\ncustom_vjp_call = custom_vjp_call_p.bind\n\ndef custom_vjp_call_jaxpr(fun, fwd, bwd, *args, out_trees):\n in_avals = [raise_to_shaped(core.get_aval(x)) for x in args]\n fun_jaxpr = _initial_style_jaxpr(fun, in_avals)\n fwd_jaxpr_thunk = _memoize(lambda: _initial_style_jaxpr(fwd, in_avals))\n return custom_vjp_call_jaxpr_p.bind(*args, fun_jaxpr=fun_jaxpr,\n fwd_jaxpr_thunk=fwd_jaxpr_thunk, bwd=bwd,\n out_trees=out_trees)\n\ndef _custom_vjp_call_jaxpr_impl(*args, fun_jaxpr, **_):\n return core.jaxpr_as_fun(fun_jaxpr)(*args)\n\ndef _custom_vjp_call_jaxpr_abstract_eval(*_, fun_jaxpr, **__):\n return fun_jaxpr.out_avals\n\ncustom_vjp_call_jaxpr_p = core.Primitive('custom_vjp_call_jaxpr')\ncustom_vjp_call_jaxpr_p.multiple_results = True\ncustom_vjp_call_jaxpr_p.def_impl(_custom_vjp_call_jaxpr_impl)\ncustom_vjp_call_jaxpr_p.def_abstract_eval(_custom_vjp_call_jaxpr_abstract_eval)\n\ndef _custom_vjp_call_jaxpr_jvp(primals, tangents, *, fun_jaxpr, fwd_jaxpr_thunk,\n bwd, out_trees):\n tangents = map(ad.instantiate_zeros, tangents)\n fwd_jaxpr = fwd_jaxpr_thunk()\n out_tree, res_tree = out_trees()\n res_and_primals_out = core.jaxpr_as_fun(fwd_jaxpr)(*primals)\n res, primals_out = split_list(res_and_primals_out, [res_tree.num_leaves])\n avals_out = [raise_to_shaped(core.get_aval(x)) for x in primals_out]\n tangents_out = ad.custom_lin_p.bind(\n *res, *tangents, num_res=res_tree.num_leaves, bwd=bwd, avals_out=avals_out)\n return primals_out, tangents_out\nad.primitive_jvps[custom_vjp_call_jaxpr_p] = _custom_vjp_call_jaxpr_jvp\n\ndef _custom_vjp_call_jaxpr_vmap(args, in_dims, *, fun_jaxpr, fwd_jaxpr_thunk,\n bwd, out_trees):\n size, = {x.shape[d] for x, d in zip(args, in_dims) if d is not not_mapped}\n args = [batching.moveaxis(x, d, 0) if d is not not_mapped and d != 0\n else x for x, d in zip(args, in_dims)]\n\n in_batched = [d is not not_mapped for d in in_dims]\n batched_fun_jaxpr, out_batched = batching.batch_jaxpr(fun_jaxpr, size, in_batched, False)\n out_dims1 = [0 if b else not_mapped for b in out_batched]\n out_dims2 = []\n\n @_memoize\n def batched_fwd_jaxpr_thunk():\n fwd_jaxpr = fwd_jaxpr_thunk()\n batched_fwd_jaxpr, out_batched = batching.batch_jaxpr(fwd_jaxpr, size, in_batched, False)\n out_dims2.append([0 if b else not_mapped for b in out_batched])\n return batched_fwd_jaxpr\n\n fwd_in_dims = [0 if b else not_mapped for b in in_batched]\n fwd_out_dims = lambda: out_dims2[0]\n # TODO: Support collectives in custom_vjp?\n batched_bwd = batching.batch_fun(bwd, fwd_out_dims, fwd_in_dims,\n axis_name='__unused_axis_name', sum_match=True)\n\n batched_outs = custom_vjp_call_jaxpr_p.bind(\n *args, fun_jaxpr=batched_fun_jaxpr,\n fwd_jaxpr_thunk=batched_fwd_jaxpr_thunk, bwd=batched_bwd,\n out_trees=out_trees)\n out_dims = out_dims2[0] if out_dims2 else out_dims1\n return batched_outs, out_dims\nbatching.primitive_batchers[custom_vjp_call_jaxpr_p] = _custom_vjp_call_jaxpr_vmap\n\nxla.initial_style_translations[custom_vjp_call_jaxpr_p] = \\\n xla.lower_fun_initial_style(_custom_vjp_call_jaxpr_impl)\n\nbatching.primitive_batchers[ad.custom_lin_p] = ad._raise_custom_vjp_error_on_jvp\n\n\n# TODO(mattjj): remove when omnistaging fully lands\n@config.register_omnistaging_enabler\ndef omnistaging_enabler() -> None:\n global _initial_style_jaxpr\n\n def _initial_style_jaxpr(fun, in_avals):\n jaxpr, out_avals, consts = pe.trace_to_jaxpr_dynamic(fun, in_avals)\n typed_jaxpr = core.TypedJaxpr(jaxpr, consts, in_avals, out_avals)\n return typed_jaxpr\n\n def bind(self, fun, jvp, *args):\n args = map(core.full_lower, args)\n top_trace = core.find_top_trace(args)\n fun, env_trace_todo1 = core.process_env_traces(\n fun, self, top_trace and top_trace.level, ())\n jvp, env_trace_todo2 = core.process_env_traces(\n jvp, self, top_trace and top_trace.level, ())\n tracers = map(top_trace.full_raise, args) # type: ignore\n outs = top_trace.process_custom_jvp_call(self, fun, jvp, tracers) # type: ignore\n _, env_trace_todo = lu.merge_linear_aux(env_trace_todo1, env_trace_todo2)\n if env_trace_todo:\n raise core.UnexpectedTracerError\n return map(core.full_lower, outs)\n CustomJVPCallPrimitive.bind = bind # type: ignore\n","sub_path":"jax/custom_derivatives.py","file_name":"custom_derivatives.py","file_ext":"py","file_size_in_byte":25384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"494633483","text":"#!/usr/bin/env python2\nfrom __future__ import print_function\nimport os\nimport sys\nimport time\nimport base64\nfrom urllib2 import urlopen\nfrom urllib2 import Request\nfrom urllib2 import HTTPError\nfrom urllib import urlencode\nfrom urllib import quote\nfrom exceptions import Exception\nfrom email.mime.multipart import MIMEMultipart\n\nfrom email.mime.base import MIMEBase\nfrom email.mime.application import MIMEApplication\n\nfrom email.encoders import encode_noop\n\nimport json\ndef json2python(data):\n try:\n return json.loads(data)\n except:\n pass\n return None\npython2json = json.dumps\n\nclass MalformedResponse(Exception):\n pass\nclass RequestError(Exception):\n pass\n\nclass Client(object):\n default_url = 'http://nova.astrometry.net/api/'\n\n def __init__(self,\n apiurl = default_url):\n self.session = None\n self.apiurl = apiurl\n\n def get_url(self, service):\n return self.apiurl + service\n\n def send_request(self, service, args={}, file_args=None):\n '''\n service: string\n args: dict\n '''\n if self.session is not None:\n args.update({ 'session' : self.session })\n print('Python:', args)\n json = python2json(args)\n print('Sending json:', json)\n url = self.get_url(service)\n print('Sending to URL:', url)\n\n # If we're sending a file, format a multipart/form-data\n if file_args is not None:\n m1 = MIMEBase('text', 'plain')\n m1.add_header('Content-disposition', 'form-data; name=\"request-json\"')\n m1.set_payload(json)\n\n m2 = MIMEApplication(file_args[1],'octet-stream',encode_noop)\n m2.add_header('Content-disposition',\n 'form-data; name=\"file\"; filename=\"%s\"' % file_args[0])\n\n mp = MIMEMultipart('form-data', None, [m1, m2])\n\n # Make a custom generator to format it the way we need.\n from cStringIO import StringIO\n from email.generator import Generator\n\n class MyGenerator(Generator):\n def __init__(self, fp, root=True):\n Generator.__init__(self, fp, mangle_from_=False,\n maxheaderlen=0)\n self.root = root\n def _write_headers(self, msg):\n # We don't want to write the top-level headers;\n # they go into Request(headers) instead.\n if self.root:\n return\n # We need to use \\r\\n line-terminator, but Generator\n # doesn't provide the flexibility to override, so we\n # have to copy-n-paste-n-modify.\n for h, v in msg.items():\n print(('%s: %s\\r\\n' % (h,v)), end='', file=self._fp)\n # A blank line always separates headers from body\n print('\\r\\n', end='', file=self._fp)\n\n # The _write_multipart method calls \"clone\" for the\n # subparts. We hijack that, setting root=False\n def clone(self, fp):\n return MyGenerator(fp, root=False)\n\n fp = StringIO()\n g = MyGenerator(fp)\n g.flatten(mp)\n data = fp.getvalue()\n headers = {'Content-type': mp.get('Content-type')}\n\n else:\n # Else send x-www-form-encoded\n data = {'request-json': json}\n print('Sending form data:', data)\n data = urlencode(data)\n print('Sending data:', data)\n headers = {}\n\n request = Request(url=url, headers=headers, data=data)\n\n try:\n f = urlopen(request)\n txt = f.read()\n print('Got json:', txt)\n result = json2python(txt)\n print('Got result:', result)\n stat = result.get('status')\n print('Got status:', stat)\n if stat == 'error':\n errstr = result.get('errormessage', '(none)')\n raise RequestError('server error message: ' + errstr)\n return result\n except HTTPError as e:\n print('HTTPError', e)\n txt = e.read()\n open('err.html', 'wb').write(txt)\n print('Wrote error text to err.html')\n\n def login(self, apikey):\n args = { 'apikey' : apikey }\n result = self.send_request('login', args)\n sess = result.get('session')\n print('Got session:', sess)\n if not sess:\n raise RequestError('no session in result')\n self.session = sess\n\n def _get_upload_args(self, **kwargs):\n args = {}\n for key,default,typ in [('allow_commercial_use', 'd', str),\n ('allow_modifications', 'd', str),\n ('publicly_visible', 'y', str),\n ('scale_units', None, str),\n ('scale_type', None, str),\n ('scale_lower', None, float),\n ('scale_upper', None, float),\n ('scale_est', None, float),\n ('scale_err', None, float),\n ('center_ra', None, float),\n ('center_dec', None, float),\n ('radius', None, float),\n ('downsample_factor', None, int),\n ('tweak_order', None, int),\n ('crpix_center', None, bool),\n ('x', None, list),\n ('y', None, list),\n # image_width, image_height\n ]:\n if key in kwargs:\n val = kwargs.pop(key)\n val = typ(val)\n args.update({key: val})\n elif default is not None:\n args.update({key: default})\n print('Upload args:', args)\n return args\n\n def url_upload(self, url, **kwargs):\n args = dict(url=url)\n args.update(self._get_upload_args(**kwargs))\n result = self.send_request('url_upload', args)\n return result\n\n def upload(self, fn=None, **kwargs):\n args = self._get_upload_args(**kwargs)\n file_args = None\n if fn is not None:\n try:\n f = open(fn, 'rb')\n file_args = (fn, f.read())\n except IOError:\n print('File %s does not exist' % fn)\n raise\n return self.send_request('upload', args, file_args)\n\n def submission_images(self, subid):\n result = self.send_request('submission_images', {'subid':subid})\n return result.get('image_ids')\n\n def overlay_plot(self, service, outfn, wcsfn, wcsext=0):\n from astrometry.util import util as anutil\n wcs = anutil.Tan(wcsfn, wcsext)\n params = dict(crval1 = wcs.crval[0], crval2 = wcs.crval[1],\n crpix1 = wcs.crpix[0], crpix2 = wcs.crpix[1],\n cd11 = wcs.cd[0], cd12 = wcs.cd[1],\n cd21 = wcs.cd[2], cd22 = wcs.cd[3],\n imagew = wcs.imagew, imageh = wcs.imageh)\n result = self.send_request(service, {'wcs':params})\n print('Result status:', result['status'])\n plotdata = result['plot']\n plotdata = base64.b64decode(plotdata)\n open(outfn, 'wb').write(plotdata)\n print('Wrote', outfn)\n\n def sdss_plot(self, outfn, wcsfn, wcsext=0):\n return self.overlay_plot('sdss_image_for_wcs', outfn,\n wcsfn, wcsext)\n\n def galex_plot(self, outfn, wcsfn, wcsext=0):\n return self.overlay_plot('galex_image_for_wcs', outfn,\n wcsfn, wcsext)\n\n def myjobs(self):\n result = self.send_request('myjobs/')\n return result['jobs']\n\n def job_status(self, job_id, justdict=False):\n result = self.send_request('jobs/%s' % job_id)\n if justdict:\n return result\n stat = result.get('status')\n if stat == 'success':\n result = self.send_request('jobs/%s/calibration' % job_id)\n print('Calibration:', result)\n result = self.send_request('jobs/%s/tags' % job_id)\n print('Tags:', result)\n result = self.send_request('jobs/%s/machine_tags' % job_id)\n print('Machine Tags:', result)\n result = self.send_request('jobs/%s/objects_in_field' % job_id)\n print('Objects in field:', result)\n result = self.send_request('jobs/%s/annotations' % job_id)\n print('Annotations:', result)\n result = self.send_request('jobs/%s/info' % job_id)\n print('Calibration:', result)\n\n return stat\n\n def annotate_data(self,job_id):\n \"\"\"\n :param job_id: id of job\n :return: return data for annotations\n \"\"\"\n result = self.send_request('jobs/%s/annotations' % job_id)\n return result\n\n def sub_status(self, sub_id, justdict=False):\n result = self.send_request('submissions/%s' % sub_id)\n if justdict:\n return result\n return result.get('status')\n\n def jobs_by_tag(self, tag, exact):\n exact_option = 'exact=yes' if exact else ''\n result = self.send_request(\n 'jobs_by_tag?query=%s&%s' % (quote(tag.strip()), exact_option),\n {},\n )\n return result\n\nif __name__ == '__main__':\n print(\"Running with args %s\"%sys.argv)\n import optparse\n parser = optparse.OptionParser()\n parser.add_option('--server', dest='server', default=Client.default_url,\n help='Set server base URL (eg, %default)')\n parser.add_option('--apikey', '-k', dest='apikey',\n help='API key for Astrometry.net web service; if not given will check AN_API_KEY environment variable')\n parser.add_option('--upload', '-u', dest='upload', help='Upload a file')\n parser.add_option('--upload-xy', dest='upload_xy', help='Upload a FITS x,y table as JSON')\n parser.add_option('--wait', '-w', dest='wait', action='store_true', help='After submitting, monitor job status')\n parser.add_option('--wcs', dest='wcs', help='Download resulting wcs.fits file, saving to given filename; implies --wait if --urlupload or --upload')\n parser.add_option('--newfits', dest='newfits', help='Download resulting new-image.fits file, saving to given filename; implies --wait if --urlupload or --upload')\n parser.add_option('--kmz', dest='kmz', help='Download resulting kmz file, saving to given filename; implies --wait if --urlupload or --upload')\n parser.add_option('--annotate','-a',dest='annotate',help='store information about annotations in give file, JSON format; implies --wait if --urlupload or --upload')\n parser.add_option('--urlupload', '-U', dest='upload_url', help='Upload a file at specified url')\n parser.add_option('--scale-units', dest='scale_units',\n choices=('arcsecperpix', 'arcminwidth', 'degwidth', 'focalmm'), help='Units for scale estimate')\n #parser.add_option('--scale-type', dest='scale_type',\n # choices=('ul', 'ev'), help='Scale bounds: lower/upper or estimate/error')\n parser.add_option('--scale-lower', dest='scale_lower', type=float, help='Scale lower-bound')\n parser.add_option('--scale-upper', dest='scale_upper', type=float, help='Scale upper-bound')\n parser.add_option('--scale-est', dest='scale_est', type=float, help='Scale estimate')\n parser.add_option('--scale-err', dest='scale_err', type=float, help='Scale estimate error (in PERCENT), eg \"10\" if you estimate can be off by 10%')\n parser.add_option('--ra', dest='center_ra', type=float, help='RA center')\n parser.add_option('--dec', dest='center_dec', type=float, help='Dec center')\n parser.add_option('--radius', dest='radius', type=float, help='Search radius around RA,Dec center')\n parser.add_option('--downsample', dest='downsample_factor', type=int, help='Downsample image by this factor')\n parser.add_option('--parity', dest='parity', choices=('0','1'), help='Parity (flip) of image')\n parser.add_option('--tweak-order', dest='tweak_order', type=int, help='SIP distortion order (default: 2)')\n parser.add_option('--crpix-center', dest='crpix_center', action='store_true', default=None, help='Set reference point to center of image?')\n parser.add_option('--sdss', dest='sdss_wcs', nargs=2, help='Plot SDSS image for the given WCS file; write plot to given PNG filename')\n parser.add_option('--galex', dest='galex_wcs', nargs=2, help='Plot GALEX image for the given WCS file; write plot to given PNG filename')\n parser.add_option('--jobid', '-i', dest='solved_id', type=int,help='retrieve result for jobId instead of submitting new image')\n parser.add_option('--substatus', '-s', dest='sub_id', help='Get status of a submission')\n parser.add_option('--jobstatus', '-j', dest='job_id', help='Get status of a job')\n parser.add_option('--jobs', '-J', dest='myjobs', action='store_true', help='Get all my jobs')\n parser.add_option('--jobsbyexacttag', '-T', dest='jobs_by_exact_tag', help='Get a list of jobs associated with a given tag--exact match')\n parser.add_option('--jobsbytag', '-t', dest='jobs_by_tag', help='Get a list of jobs associated with a given tag')\n parser.add_option( '--private', '-p',\n dest='public',\n action='store_const',\n const='n',\n default='y',\n help='Hide this submission from other users')\n parser.add_option('--allow_mod_sa','-m',\n dest='allow_mod',\n action='store_const',\n const='sa',\n default='d',\n help='Select license to allow derivative works of submission, but only if shared under same conditions of original license')\n parser.add_option('--no_mod','-M',\n dest='allow_mod',\n action='store_const',\n const='n',\n default='d',\n help='Select license to disallow derivative works of submission')\n parser.add_option('--no_commercial','-c',\n dest='allow_commercial',\n action='store_const',\n const='n',\n default='d',\n help='Select license to disallow commercial use of submission')\n opt,args = parser.parse_args()\n\n if opt.apikey is None:\n # try the environment\n opt.apikey = os.environ.get('AN_API_KEY', None)\n if opt.apikey is None:\n parser.print_help()\n print()\n print('You must either specify --apikey or set AN_API_KEY')\n sys.exit(-1)\n\n args = {}\n args['apiurl'] = opt.server\n c = Client(**args)\n c.login(opt.apikey)\n\n if opt.upload or opt.upload_url or opt.upload_xy:\n if opt.wcs or opt.kmz or opt.newfits or opt.annotate:\n opt.wait = True\n\n kwargs = dict(\n allow_commercial_use=opt.allow_commercial,\n allow_modifications=opt.allow_mod,\n publicly_visible=opt.public)\n if opt.scale_lower and opt.scale_upper:\n kwargs.update(scale_lower=opt.scale_lower,\n scale_upper=opt.scale_upper,\n scale_type='ul')\n elif opt.scale_est and opt.scale_err:\n kwargs.update(scale_est=opt.scale_est,\n scale_err=opt.scale_err,\n scale_type='ev')\n elif opt.scale_lower or opt.scale_upper:\n kwargs.update(scale_type='ul')\n if opt.scale_lower:\n kwargs.update(scale_lower=opt.scale_lower)\n if opt.scale_upper:\n kwargs.update(scale_upper=opt.scale_upper)\n\n for key in ['scale_units', 'center_ra', 'center_dec', 'radius',\n 'downsample_factor', 'tweak_order', 'crpix_center',]:\n if getattr(opt, key) is not None:\n kwargs[key] = getattr(opt, key)\n if opt.parity is not None:\n kwargs.update(parity=int(opt.parity))\n\n if opt.upload:\n upres = c.upload(opt.upload, **kwargs)\n if opt.upload_xy:\n from astrometry.util.fits import fits_table\n T = fits_table(opt.upload_xy)\n kwargs.update(x=[float(x) for x in T.x], y=[float(y) for y in T.y])\n upres = c.upload(**kwargs)\n if opt.upload_url:\n upres = c.url_upload(opt.upload_url, **kwargs)\n\n stat = upres['status']\n if stat != 'success':\n print('Upload failed: status', stat)\n print(upres)\n sys.exit(-1)\n\n opt.sub_id = upres['subid']\n\n if opt.wait:\n if opt.solved_id is None:\n if opt.sub_id is None:\n print(\"Can't --wait without a submission id or job id!\")\n sys.exit(-1)\n\n while True:\n stat = c.sub_status(opt.sub_id, justdict=True)\n print('Got status:', stat)\n jobs = stat.get('jobs', [])\n if len(jobs):\n for j in jobs:\n if j is not None:\n break\n if j is not None:\n print('Selecting job id', j)\n opt.solved_id = j\n break\n time.sleep(5)\n\n while True:\n stat = c.job_status(opt.solved_id, justdict=True)\n print('Got job status:', stat)\n if stat.get('status','') in ['success']:\n success = (stat['status'] == 'success')\n break\n time.sleep(5)\n\n if opt.solved_id:\n # we have a jobId for retrieving results\n retrieveurls = []\n if opt.wcs:\n # We don't need the API for this, just construct URL\n url = opt.server.replace('/api/', '/wcs_file/%i' % opt.solved_id)\n retrieveurls.append((url, opt.wcs))\n if opt.kmz:\n url = opt.server.replace('/api/', '/kml_file/%i/' % opt.solved_id)\n retrieveurls.append((url, opt.kmz))\n if opt.newfits:\n url = opt.server.replace('/api/', '/new_fits_file/%i/' % opt.solved_id)\n retrieveurls.append((url, opt.newfits))\n\n for url,fn in retrieveurls:\n print('Retrieving file from', url, 'to', fn)\n f = urlopen(url)\n txt = f.read()\n w = open(fn, 'wb')\n w.write(txt)\n w.close()\n print('Wrote to', fn)\n\n if opt.annotate:\n result = c.annotate_data(opt.solved_id)\n with open(opt.annotate,'w') as f:\n f.write(python2json(result))\n\n if opt.wait:\n # behaviour as in old implementation\n opt.sub_id = None\n\n if opt.sdss_wcs:\n (wcsfn, outfn) = opt.sdss_wcs\n c.sdss_plot(outfn, wcsfn)\n if opt.galex_wcs:\n (wcsfn, outfn) = opt.galex_wcs\n c.galex_plot(outfn, wcsfn)\n\n if opt.sub_id:\n print(c.sub_status(opt.sub_id))\n if opt.job_id:\n print(c.job_status(opt.job_id))\n\n if opt.jobs_by_tag:\n tag = opt.jobs_by_tag\n print(c.jobs_by_tag(tag, None))\n if opt.jobs_by_exact_tag:\n tag = opt.jobs_by_exact_tag\n print(c.jobs_by_tag(tag, 'yes'))\n\n if opt.myjobs:\n jobs = c.myjobs()\n print(jobs)\n\n\n","sub_path":"astrometry/astrometry_client.py","file_name":"astrometry_client.py","file_ext":"py","file_size_in_byte":19399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"125262609","text":"# #############################################################################\n# Author: 2017 Rostislav Spinar #\n# IQRF Tech s.r.o. #\n# #############################################################################\n\n# #############################################################################\n# #\n# sudo apt-get install python-dev build-essential #\n# sudo apt-get install python-pip #\n# sudo pip install paho-mqtt # \n# #\n# #############################################################################\n\nimport sys\nimport getopt\nimport time\nimport json\n\nimport paho.mqtt.client as paho\n \ndef on_connect(client, userdata, flags, rc):\n print('CONNACK received with code %d.' % (rc))\n\ndef on_publish(client, userdata, mid):\n print('mid: ' + str(mid))\n\ndef on_subscribe(client, userdata, mid, granted_qos):\n print('Subscribed: ' + str(mid) + ' ' + str(granted_qos))\n \ndef on_message(client, userdata, msg):\n print(msg.topic + ' ' + str(msg.qos) + ' ' + str(msg.payload))\n\ndef on_log(mqttc, userdata, level, string):\n print(string)\n\ndef create_dpa_frame(node_id, pnum, pcmd, hwpid, data=[]):\n\n byte_str = '%02x.%02x.%02x.%02x.%02x.%02x' % (node_id & 0xFF,\n node_id >> 8,\n pnum, pcmd,\n hwpid & 0xFF,\n hwpid >> 8)\n for i in data:\n byte_str += '.%02x' % i\n\n return byte_str\n\ndef create_dpa_json(msg_id, dpa_frame):\n request = {}\n request['ctype'] = 'dpa'\n request['type'] = 'raw'\n request['msgid'] = msg_id\n request['request'] = dpa_frame\n request['request_ts'] = ''\n request['confirmation'] = ''\n request['confirmation_ts'] = ''\n request['response'] = ''\n request['response_ts'] = ''\n\n return json.dumps(request)\n\ndef print_usage():\n print('iqrf_daemon_mqtt.py [-d] [-h hostname] [-p port] [-tp topic_pub] [-ts topic_sub]')\n\ndef main(argv):\n #IQRF\n # default hwpid\n hwpid = 0xffff\n # default DPA timeout (in miliseconds)\n timeout = 1000\n\n #MQTT\n host = 'localhost'\n port = 1883\n keepalive = 60\n client_id = str(time.time())\n #password = None\n #username = None\n debug=False\n\n topic_pub = 'Iqrf/DpaRequest'\n topic_sub = 'Iqrf/DpaResponse'\n\n try:\n opts, args = getopt.getopt(argv, 'd:h:p:tp:ts', ['debug', 'host=', 'port=', 'topic_pub=', 'topic_sub='])\n except getopt.GetoptError as s:\n print_usage()\n sys.exit(2)\n \n for opt, arg in opts:\n if opt in ('-d', '--debug'):\n host = arg\n elif opt in ('-h', '--host'):\n host = arg\n elif opt in ('-p', '--port'):\n port = int(arg)\n elif opt in ('-tp', '--topic_pub'):\n topic_pub = arg\n print(topic_pub)\n elif opt in ('-ts', '--topic_sub'):\n topic_sub = arg\n print(topic_sub)\n\n # client\n client = paho.Client(client_id=client_id, clean_session=True, userdata=None, protocol=paho.MQTTv31)\n #client.username_pw_set(username, password)\n #client.tls_set(“/path/to/ca.crt”)\n\n # client callbacks\n client.on_connect = on_connect\n client.on_publish = on_publish\n client.on_subscribe = on_subscribe\n client.on_message = on_message\n\n # debug\n if debug:\n client.on_log = on_log\n\n # connect\n client.connect(host=host, port=port, keepalive=keepalive, bind_address='')\n\n # subscribe\n client.subscribe(topic_sub)\n\n # blocking, good for sub only\n #client.loop_forever()\n\n # not blocking, background thread, returns\n client.loop_start()\n #client.loop_stop()\n\n # dpa frame\n dpa_frame = create_dpa_frame(0x0f, 0x06, 0x03, hwpid)\n\n while True:\n # json dpa\n msg_id = str(time.time())\n json_dpa = create_dpa_json(msg_id, dpa_frame)\n \n # publish\n (rc, mid) = client.publish(topic_pub, json_dpa, qos=1)\n \n # sleep\n time.sleep(10)\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"python/mqtt/iqrf_daemon_mqtt.py","file_name":"iqrf_daemon_mqtt.py","file_ext":"py","file_size_in_byte":4209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"365769313","text":"import json\nimport re\n\nfrom invenio_app.helpers import obj_or_import_string\nfrom invenio_db import db\nfrom invenio_indexer.utils import schema_to_index\nfrom invenio_pidstore import current_pidstore\nfrom invenio_pidstore.fetchers import FetchedPID\nfrom invenio_pidstore.models import PersistentIdentifier\nfrom invenio_records_rest.utils import deny_all, check_elasticsearch, allow_all\nfrom invenio_search import current_search\n\nfrom oarepo_records_draft import current_drafts\nfrom oarepo_records_draft.actions.files import FileResource, FileListResource\nfrom oarepo_records_draft.links import PublishedLinksFactory, DraftLinksFactory\nfrom oarepo_records_draft.record import DraftRecordMixin\nfrom oarepo_records_draft.types import RecordEndpointConfiguration, DraftManagedRecords, \\\n PublishedRecordEndpointConfiguration, DraftRecordEndpointConfiguration\n\n\ndef setup_draft_endpoints(app, invenio_endpoints):\n draft_endpoints = {\n k: {**v} for k, v in app.config.get('RECORDS_DRAFT_ENDPOINTS', {}).items()\n }\n\n drafts = set()\n endpoints = DraftManagedRecords()\n\n for published, options in draft_endpoints.items():\n if 'draft' in options:\n drafts.add(options['draft'])\n\n for published, options in draft_endpoints.items():\n if published in drafts:\n continue\n if 'draft' not in options:\n raise ValueError('`draft` not found in RECORDS_DRAFT_ENDPOINTS[%s]' % published)\n draft = options.pop('draft')\n if draft not in draft_endpoints:\n draft_endpoints[draft] = {}\n published_endpoint, draft_endpoint = setup_draft_endpoint(app, published, draft, draft_endpoints[published],\n draft_endpoints[draft])\n\n endpoints.add_record(\n draft=draft_endpoint,\n published=published_endpoint\n )\n\n invenio_endpoints[published_endpoint.rest_name] = published_endpoint.rest\n invenio_endpoints[draft_endpoint.rest_name] = draft_endpoint.rest\n\n return endpoints\n\n\ndef copy(source, target, prop, default=None):\n if default is not None and prop not in source:\n source[prop] = default\n\n if prop in source and prop not in target:\n target[prop] = source[prop]\n\n\ndef setup_draft_endpoint(app, published_code, draft_code, published, draft):\n extra_draft = {}\n extra_published = {}\n\n if 'pid_type' not in published:\n published['pid_type'] = published_code\n\n if 'pid_type' not in draft:\n draft['pid_type'] = draft_code\n\n draft_endpoint = DraftRecordEndpointConfiguration(\n rest_name=draft_code,\n rest=draft,\n extra=extra_draft\n )\n published_endpoint = PublishedRecordEndpointConfiguration(\n rest_name=published_code,\n rest=published,\n extra=extra_published\n )\n\n copy(published, draft, 'default_endpoint_prefix', True)\n copy(published, draft, 'default_media_type', 'application/json')\n copy(published, draft, 'max_result_window')\n copy(published, draft, 'record_loaders')\n copy(published, draft, 'record_serializers', {\n 'application/json': 'oarepo_validate:json_response',\n })\n copy(published, draft, 'record_serializers_aliases')\n copy(published, draft, 'search_serializers', {\n 'application/json': 'oarepo_validate:json_search',\n })\n copy(published, draft, 'search_serializers_aliases')\n copy(published, draft, 'search_class')\n copy(published, draft, 'indexer_class')\n copy(published, draft, 'search_factory_impl')\n copy(published, draft, 'suggesters')\n copy(published, draft, 'use_options_view')\n copy(published, draft, 'error_handlers')\n\n if 'create_permission_factory_imp' not in published:\n published['create_permission_factory_imp'] = deny_all\n\n if 'delete_permission_factory_imp' not in published:\n published['delete_permission_factory_imp'] = deny_all\n\n if 'update_permission_factory_imp' not in published:\n published['update_permission_factory_imp'] = deny_all\n\n if 'list_permission_factory_imp' not in published:\n published['list_permission_factory_imp'] = allow_all\n\n if 'read_permission_factory_imp' not in published:\n published['read_permission_factory_imp'] = check_elasticsearch\n\n if 'create_permission_factory_imp' not in draft:\n draft['create_permission_factory_imp'] = deny_all\n\n if 'delete_permission_factory_imp' not in draft:\n draft['delete_permission_factory_imp'] = deny_all\n\n if 'update_permission_factory_imp' not in draft:\n draft['update_permission_factory_imp'] = deny_all\n\n if 'list_permission_factory_imp' not in draft:\n draft['list_permission_factory_imp'] = allow_all\n\n if 'read_permission_factory_imp' not in draft:\n draft['read_permission_factory_imp'] = check_elasticsearch\n\n if 'record_class' not in published:\n raise ValueError('Record class not in %s' % published_code)\n\n if 'record_class' not in draft:\n draft['record_class'] = generate_draft_record_class(published['record_class'])\n\n if 'list_route' not in published:\n published['list_route'] = '/' + published_code\n\n if 'list_route' not in draft:\n draft['list_route'] = '/draft' + published['list_route']\n\n if 'item_route' not in published or ':pid_value' not in published['item_route']:\n record_pid = 'pid(%s,record_class=\"%s\")' % (published['pid_type'], published['record_class'])\n route = published['list_route'] if 'item_route' not in published else published['item_route']\n if not route.endswith('/'):\n route += '/'\n published['item_route'] = route + '<{0}:pid_value>'.format(record_pid)\n\n if 'item_route' not in draft or ':pid_value' not in draft['item_route']:\n if not isinstance(draft['record_class'], str):\n raise ValueError('item_route is not specified in %s and %s[\"record_class\"] '\n 'is not string, so can not generate item_route for you' % (draft_code, draft_code))\n record_pid = 'pid(%s,record_class=\"%s\")' % (draft['pid_type'], draft['record_class'])\n route = draft['list_route'] if 'item_route' not in draft else draft['item_route']\n if not route.endswith('/'):\n route += '/'\n draft['item_route'] = route + '<{0}:pid_value>'.format(record_pid)\n\n if 'pid_fetcher' not in published:\n raise ValueError('pid_fetcher not in %s' % published_code)\n\n if 'pid_fetcher' not in draft:\n draft['pid_fetcher'] = make_draft_fetcher(draft['pid_type'], published['pid_fetcher'])\n\n if 'pid_minter' not in published:\n raise ValueError('pid_minter not in %s' % published_code)\n\n if 'pid_minter' not in draft:\n draft['pid_minter'] = make_draft_minter(draft['pid_type'], published['pid_minter'])\n\n if 'search_index' not in published:\n record_class = obj_or_import_string(published['record_class'])\n if not hasattr(record_class, 'PREFERRED_SCHEMA'):\n raise ValueError('search_index not in %s' % published_code)\n preferred_schema = record_class.PREFERRED_SCHEMA\n index, doc_type = schema_to_index(preferred_schema, index_names=current_search.mappings.keys())\n if index:\n published['search_index'] = index\n else:\n raise ValueError('search_index not in %s and can not be determined from PREFERRED_SCHEMA' % published_code)\n\n if 'search_index' not in draft:\n if published['search_index']:\n draft['search_index'] = 'draft-' + published['search_index']\n else:\n draft['search_index'] = None\n\n publish_permission_factory = published.pop('publish_permission_factory_imp', deny_all)\n unpublish_permission_factory = published.pop('unpublish_permission_factory_imp', deny_all)\n edit_permission_factory = published.pop('edit_permission_factory_imp', deny_all)\n\n publish_permission_factory = draft.pop('publish_permission_factory_imp', publish_permission_factory)\n unpublish_permission_factory = draft.pop('unpublish_permission_factory_imp', unpublish_permission_factory)\n edit_permission_factory = draft.pop('edit_permission_factory_imp', edit_permission_factory)\n\n extra_draft['publish_permission_factory'] = publish_permission_factory\n extra_published['unpublish_permission_factory'] = unpublish_permission_factory\n extra_published['edit_permission_factory'] = edit_permission_factory\n\n extra_draft['actions'] = draft.pop('actions', {})\n extra_published['actions'] = published.pop('actions', {})\n\n if 'files' in published:\n extra_published['actions'].update(\n setup_files(published_code, published.pop('files'), published, extra_published, is_draft=False))\n\n if 'files' in draft:\n extra_draft['actions'].update(setup_files(draft_code, draft.pop('files'), draft, extra_draft, is_draft=True))\n\n published['links_factory_imp'] = \\\n PublishedLinksFactory(\n published_endpoint,\n links_factory=published.get('links_factory_imp'),\n actions=extra_published['actions'])\n\n draft['links_factory_imp'] = \\\n DraftLinksFactory(draft_endpoint,\n links_factory=draft.get('links_factory_imp'),\n actions=extra_draft['actions'])\n\n return published_endpoint, draft_endpoint\n\n\ndef make_draft_fetcher(draft_pid_type, original_fetcher):\n def draft_fetcher(record_uuid, data):\n fetched_pid = current_pidstore.fetchers[original_fetcher](record_uuid, data)\n return FetchedPID(\n provider=fetched_pid.provider,\n pid_type=draft_pid_type,\n pid_value=fetched_pid.pid_value,\n )\n\n current_pidstore.fetchers[draft_pid_type + '_fetcher'] = draft_fetcher\n return draft_pid_type + '_fetcher'\n\n\ndef make_draft_minter(draft_pid_type, original_minter):\n def draft_minter(record_uuid, data):\n with db.session.begin_nested():\n pid = PersistentIdentifier.query.filter_by(\n pid_type=original_minter, object_type='rec',\n object_uuid=record_uuid).one_or_none()\n if pid:\n # published version already exists with the same record_uuid => raise an exception,\n # draft and published version can never point to the same invenio record\n raise ValueError('Draft and published version '\n 'can never point to the same invenio record')\n else:\n # create a new pid as if the record were published\n pid = current_pidstore.minters[original_minter](record_uuid, data)\n\n try:\n # if the draft version already exists, return it\n return PersistentIdentifier.get(draft_pid_type, pid.pid_value)\n except:\n # otherwise change the pid type to draft and return it\n pid.pid_type = draft_pid_type\n db.session.add(pid)\n return pid\n\n current_pidstore.minters[draft_pid_type + '_minter'] = draft_minter\n return draft_pid_type + '_minter'\n\n\ndef generate_draft_record_class(record_class):\n rc_package = obj_or_import_string(record_class.split(':')[0])\n rc = obj_or_import_string(record_class)\n draft_name = rc.__name__ + 'Draft'\n if not hasattr(rc_package, draft_name):\n setattr(rc_package, draft_name, type(draft_name, (\n DraftRecordMixin,\n rc\n ), {}))\n return record_class.split(':')[0] + ':' + draft_name\n\n\ndef setup_files(code, files, rest_endpoint, extra, is_draft):\n endpoints = {}\n for extra_endpoint_handler in current_drafts.extra_actions:\n endpoints.update(extra_endpoint_handler(\n code=code,\n files=files,\n rest_endpoint=rest_endpoint,\n extra=extra,\n is_draft=is_draft\n ) or {})\n if FileResource:\n endpoints['files/'] = FileResource.as_view(\n FileResource.view_name.format(code),\n get_file_factory=files.get('get_file_factory', deny_all),\n put_file_factory=files.get('put_file_factory', deny_all),\n delete_file_factory=files.get('delete_file_factory', deny_all),\n restricted=files.get('restricted', True),\n as_attachment=files.get('as_attachment', True),\n endpoint_code=code\n )\n endpoints['files/'] = FileListResource.as_view(\n FileListResource.view_name.format(code),\n get_file_factory=files.get('get_file_factory', deny_all),\n put_file_factory=files.get('put_file_factory', deny_all),\n serializers=files.get('serializers', None),\n endpoint_code=code\n )\n return endpoints\n","sub_path":"oarepo_records_draft/endpoints.py","file_name":"endpoints.py","file_ext":"py","file_size_in_byte":12872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"340745955","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Nov 30 13:24:13 2019\r\n\r\n@author: vr_lab\r\n\"\"\"\r\n\r\nimport manipulate_abaqus_file\r\nfrom convert_tetgen_to_unity import write_to_file\r\n\r\n# read .inp file's part and save to node file in tetgen\r\n\r\nif __name__ == \"__main__\":\r\n inp_file = 'Weight Jobs/reference_pos.inp'\r\n file_name = 'Skin_Layer_reference.node'\r\n abaqus = manipulate_abaqus_file.ReadAbaqusInput(inp_file)\r\n breast_part_start = '*Part, name=PART-1\\n'\r\n points = abaqus.read_part(breast_part_start)\r\n write_to_file(file_name, points, 'write')","sub_path":"ChangeAbaqusInput/convert_abaqus_to_tetgen.py","file_name":"convert_abaqus_to_tetgen.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"239245221","text":"import sys, os\nsys.path.append(os.getcwd())\nfrom dataset.mnist import load_mnist\nimport numpy as np\nfrom PIL import Image\nimport random\n\ndef image_show(img):\n pil_img = Image.fromarray(np.uint8(img))\n pil_img.show()\n\n(x_train, t_train), (x_test, t_test) = \\\nload_mnist(flatten=True, normalize=False)\n\nr = random.randrange(10000)\nimg = x_train[r]\nlabel = t_train[r]\nprint(label)\n\nprint(img.shape)\nimg = img.reshape(28, 28)\nprint(img.shape)\n\nimage_show(img)","sub_path":"ch/mnist_show.py","file_name":"mnist_show.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"384550967","text":"def CostofItem():\n global priceofdrinks, priceofcakes, tt, priceoffood, cakesPrice, drinksPrice, foodPrice\n if var1.get() != 0 or var2.get() != 0 or var3.get() != 0 or var4.get() != 0 or var5.get() != 0 or var6.get() != 0 or var7.get() != 0 \\\n or var8.get() != 0 or var8.get() != 0 or var9.get() != 0 or var10.get() != 0 or var11.get() != 0 or var12.get() != 0 or \\\n var13.get() != 0 or var14.get() != 0 or var15.get() != 0 or var16.get() != 0 or var1.get() != 0 or var17.get() != 0 or \\\n var18.get() != 0 or var18.get() != 0 or var19.get() != 0 or var20.get() != 0 or var21.get() != 0 or var22.get() != 0 or var23.get() != 0 or var24.get() != 0 or \\\n var25.get() != 0 or var26.get() != 0 or var27.get() != 0:\n item1 = float(e_lassi.get())\n item2 = float(e_rohhafza.get())\n item3 = float(e_jaljeera.get())\n item4 = float(e_shikanji.get())\n item5 = float(e_coldrinks.get())\n item6 = float(e_badammilk.get())\n item7 = float(e_coffee.get())\n item8 = float(e_masalachai.get())\n item9 = float(e_faluda.get())\n\n item10 = float(e_apple.get())\n item11 = float(e_pineapple.get())\n item12 = float(e_banana.get())\n item13 = float(e_brownie.get())\n item14 = float(e_chocolate.get())\n item15 = float(e_oreo.get())\n item16 = float(e_vanilla.get())\n item17 = float(e_blackforest.get())\n item18 = float(e_kikat.get())\n\n item19 = float(e_daal.get())\n item20 = float(e_roti.get())\n item21 = float(e_fish.get())\n item22 = float(e_sabji.get())\n item23 = float(e_chawal.get())\n item24 = float(e_mutton.get())\n item25 = float(e_chicken.get())\n item26 = float(e_paneer.get())\n item27 = float(e_kebab.get())\n\n priceofdrinks = (item1 * 40) + (item2 * 30) + (item3 * 20) + (item4 * 30) + (item5 * 60) + (item6 * 50) + (\n item7 * 40) + (item8 * 20) + (item9 * 50)\n\n priceofcakes = (item10 * 350) + (item11 * 380) + (item12 * 400) + (item13 * 550) + (item14 * 600) + (\n item15 * 500) + (\n item16 * 400) + (item17 * 550) + (item18 * 480)\n\n priceoffood = (item19 * 45) + (item20 * 10) + (item21 * 120) + (item22 * 50) + (item23 * 30) + (\n item24 * 160) + (\n item25 * 140) + (item26 * 110) + (item27 * 100)\n\n drinksPrice = f'Rs {round(priceofdrinks, 2)}'\n cakesPrice = f'Rs {round(priceofcakes, 2)}'\n foodPrice = f'Rs {round(priceoffood, 2)}'\n\n costofcakes.set(cakesPrice)\n costofdrinks.set(drinksPrice)\n costoffood.set(foodPrice)\n sc = 'Rs', str('%.2f' % (15.5))\n servicecharge.set(sc)\n\n subtotalOfItems = 'Rs', str('%.2f' % (priceofcakes + priceofdrinks + priceoffood))\n subtotal.set(subtotalOfItems)\n\n tc = 'Rs', str('%.2f' % (priceofcakes + priceofdrinks + priceoffood + 15.5))\n totalcost.set(tc)\n\n else:\n tkinter.messagebox.showerror('Error', 'No Item Is Selected')\n\n\ndef roti():\n if (var19.get() == 1):\n textroti.config(state=NORMAL)\n textroti.focus()\n textroti.delete(0, END)\n e_roti.set('')\n elif (var19.get() == 0):\n textroti.config(state=DISABLED)\n e_roti.set('0')\n\n\ndef daal():\n if (var20.get() == 1):\n textdaal.config(state=NORMAL)\n textdaal.focus()\n textdaal.delete(0, END)\n e_daal.set('')\n elif (var20.get() == 0):\n textdaal.config(state=DISABLED)\n e_daal.set('0')\n\n\ndef fish():\n if (var21.get() == 1):\n textFish.config(state=NORMAL)\n textFish.focus()\n textFish.delete(0, END)\n e_fish.set('')\n elif (var21.get() == 0):\n textFish.config(state=DISABLED)\n e_fish.set('0')\n\n\ndef sabji():\n if (var22.get() == 1):\n textsabji.config(state=NORMAL)\n textsabji.focus()\n textsabji.delete(0, END)\n e_sabji.set('')\n elif (var22.get() == 0):\n textsabji.config(state=DISABLED)\n e_sabji.set('0')\n\n\ndef kebab():\n if (var23.get() == 1):\n textKebab.config(state=NORMAL)\n textKebab.focus()\n textKebab.delete(0, END)\n e_kebab.set('')\n elif (var23.get() == 0):\n textKebab.config(state=DISABLED)\n e_kebab.set('0')\n\n\ndef chawal():\n if (var24.get() == 1):\n textchawal.config(state=NORMAL)\n textchawal.focus()\n textchawal.delete(0, END)\n e_chawal.set('')\n elif (var24.get() == 0):\n textchawal.config(state=DISABLED)\n e_chawal.set('0')\n\n\ndef mutton():\n if (var25.get() == 1):\n textMutton.config(state=NORMAL)\n textMutton.focus()\n textMutton.delete(0, END)\n e_mutton.set('')\n elif (var25.get() == 0):\n textMutton.config(state=DISABLED)\n e_mutton.set('0')\n\n\ndef paneer():\n if (var26.get() == 1):\n textpaneer.config(state=NORMAL)\n textpaneer.focus()\n textpaneer.delete(0, END)\n e_paneer.set('')\n elif (var26.get() == 0):\n textpaneer.config(state=DISABLED)\n e_paneer.set('0')\n\n\ndef chicken():\n if (var27.get() == 1):\n textChiken.config(state=NORMAL)\n textChiken.focus()\n textChiken.delete(0, END)\n e_chicken.set('')\n elif (var27.get() == 0):\n textChiken.config(state=DISABLED)\n e_chicken.set('0')\n\n\ndef lassi():\n if (var1.get() == 1):\n textLassi.config(state=NORMAL)\n textLassi.focus()\n textLassi.delete(0, END)\n e_lassi.set('')\n elif (var1.get() == 0):\n textLassi.config(state=DISABLED)\n e_lassi.set('0')\n\n\ndef coffee():\n if (var2.get() == 1):\n textCoffee.config(state=NORMAL)\n textCoffee.focus()\n textCoffee.delete(0, END)\n e_coffee.set('')\n elif (var2.get() == 0):\n textCoffee.config(state=DISABLED)\n e_coffee.set('0')\n\n\ndef faluda():\n if (var3.get() == 1):\n textFaluda.config(state=NORMAL)\n textFaluda.focus()\n textFaluda.delete(0, END)\n e_faluda.set('')\n elif (var3.get() == 0):\n textFaluda.config(state=DISABLED)\n e_faluda.set('0')\n\n\ndef shikanji():\n if (var4.get() == 1):\n textShikanji.config(state=NORMAL)\n textShikanji.focus()\n textShikanji.delete(0, END)\n e_shikanji.set('')\n elif (var4.get() == 0):\n textShikanji.config(state=DISABLED)\n e_shikanji.set('0')\n\n\ndef jaljeera():\n if (var5.get() == 1):\n textJaljeera.config(state=NORMAL)\n textJaljeera.focus()\n textJaljeera.delete(0, END)\n e_jaljeera.set('')\n elif (var5.get() == 0):\n textJaljeera.config(state=DISABLED)\n e_jaljeera.set('0')\n\n\ndef roohafza():\n if (var6.get() == 1):\n textRohhafza.config(state=NORMAL)\n textRohhafza.focus()\n textRohhafza.delete(0, END)\n e_rohhafza.set('')\n elif (var6.get() == 0):\n textRohhafza.config(state=DISABLED)\n e_rohhafza.set('0')\n\n\ndef masalachai():\n if (var7.get() == 1):\n textMasalachai.config(state=NORMAL)\n textMasalachai.focus()\n textMasalachai.delete(0, END)\n e_masalachai.set('')\n elif (var7.get() == 0):\n textMasalachai.config(state=DISABLED)\n e_masalachai.set('0')\n\n\ndef badammilk():\n if (var8.get() == 1):\n textbadammilk.config(state=NORMAL)\n textbadammilk.focus()\n textbadammilk.delete(0, END)\n e_badammilk.set('')\n elif (var8.get() == 0):\n textbadammilk.config(state=DISABLED)\n e_badammilk.set('0')\n\n\ndef coldrinks():\n if (var9.get() == 1):\n textColdrinks.config(state=NORMAL)\n textColdrinks.focus()\n textColdrinks.delete(0, END)\n e_coldrinks.set('')\n elif (var9.get() == 0):\n textColdrinks.config(state=DISABLED)\n e_coldrinks.set('0')\n\n\ndef kitkat():\n if (var10.get() == 1):\n textKitkat.config(state=NORMAL)\n textKitkat.focus()\n textKitkat.delete(0, END)\n e_kikat.set('')\n elif (var10.get() == 0):\n textKitkat.config(state=DISABLED)\n e_kikat.set('0')\n\n\ndef apple():\n if (var11.get() == 1):\n textApple.config(state=NORMAL)\n textApple.focus()\n textApple.delete(0, END)\n e_apple.set('')\n elif (var11.get() == 0):\n textApple.config(state=DISABLED)\n e_apple.set('0')\n\n\ndef vanilla():\n if (var12.get() == 1):\n textvanilla.config(state=NORMAL)\n textvanilla.focus()\n textvanilla.delete(0, END)\n e_vanilla.set('')\n elif (var12.get() == 0):\n textvanilla.config(state=DISABLED)\n e_vanilla.set('0')\n\n\ndef blackforest():\n if (var13.get() == 1):\n textBlackforest.config(state=NORMAL)\n textBlackforest.focus()\n textBlackforest.delete(0, END)\n e_blackforest.set('')\n elif (var13.get() == 0):\n textBlackforest.config(state=DISABLED)\n e_blackforest.set('0')\n\n\ndef banana():\n if (var14.get() == 1):\n textBanana.config(state=NORMAL)\n textBanana.focus()\n textBanana.delete(0, END)\n e_banana.set('')\n elif (var14.get() == 0):\n textBanana.config(state=DISABLED)\n e_banana.set('0')\n\n\ndef brownie():\n if (var15.get() == 1):\n textBrownie.config(state=NORMAL)\n textBrownie.focus()\n textBrownie.delete(0, END)\n e_brownie.set('')\n elif (var15.get() == 0):\n textBrownie.config(state=DISABLED)\n e_brownie.set('0')\n\n\ndef pineapple():\n if (var16.get() == 1):\n textpineapple.config(state=NORMAL)\n textpineapple.focus()\n textpineapple.delete(0, END)\n e_pineapple.set('')\n elif (var16.get() == 0):\n textpineapple.config(state=DISABLED)\n e_pineapple.set('0')\n\n\ndef chocolate():\n if (var17.get() == 1):\n textChocolate.config(state=NORMAL)\n textChocolate.focus()\n textChocolate.delete(0, END)\n e_chocolate.set('')\n elif (var17.get() == 0):\n textChocolate.config(state=DISABLED)\n e_chocolate.set('0')\n\n\ndef oreo():\n if (var18.get() == 1):\n textoreo.config(state=NORMAL)\n textoreo.focus()\n textoreo.delete(0, END)\n e_oreo.set('')\n elif (var18.get() == 0):\n textoreo.config(state=DISABLED)\n e_oreo.set('0')\n\n\ndef receipt():\n global priceofdrinks, priceoffood, priceofcakes\n if var1.get() != 0 or var2.get() != 0 or var3.get() != 0 or var4.get() != 0 or var5.get() != 0 or var6.get() != 0 or var7.get() != 0 \\\n or var8.get() != 0 or var8.get() != 0 or var9.get() != 0 or var10.get() != 0 or var11.get() != 0 or var12.get() != 0 or \\\n var13.get() != 0 or var14.get() != 0 or var15.get() != 0 or var16.get() != 0 or var1.get() != 0 or var17.get() != 0 or \\\n var18.get() != 0 or var19.get() != 0 or var20.get() != 0 or var21.get() != 0 or var22.get() != 0 or var23.get() != 0 or var24.get() != 0 or \\\n var25.get() != 0 or var26.get() != 0 or var27.get() != 0:\n textReceipt.delete(1.0, END)\n x = random.randint(100, 10000)\n randomRef = str(x)\n receipt_ref.set('BILL ' + randomRef)\n\n textReceipt.insert(END, 'Receipt Ref:\\t\\t' + receipt_ref.get() + '\\t\\t' + dateofOrder.get() + '\\n')\n textReceipt.insert(END, '*********************************************************************\\n')\n textReceipt.insert(END, 'Items:\\t\\t' + ' Cost of Items (in Rs) \\n')\n textReceipt.insert(END, '********************************************************************\\n')\n\n if e_daal.get() != '0':\n textReceipt.insert(END, f'Daal:\\t\\t\\t{float(e_daal.get()) * 45}\\n\\n')\n\n if e_roti.get() != '0':\n textReceipt.insert(END, f'Roti:\\t\\t\\t{float(e_roti.get()) * 10}\\n\\n')\n\n if e_chawal.get() != '0':\n textReceipt.insert(END, f'Chawal:\\t\\t\\t{float(e_chawal.get()) * 30}\\n\\n')\n\n if e_sabji.get() != '0':\n textReceipt.insert(END, f'Sabji:\\t\\t\\t{float(e_sabji.get()) * 50}\\n\\n')\n\n if e_fish.get() != '0':\n textReceipt.insert(END, f'Fish:\\t\\t\\t{float(e_fish.get()) * 120}\\n\\n')\n\n if e_paneer.get() != '0':\n textReceipt.insert(END, f'Paneer:\\t\\t\\t{float(e_paneer.get()) * 110}\\n\\n')\n\n if e_kebab.get() != '0':\n textReceipt.insert(END, f'Kabab:\\t\\t\\t{float(e_kebab.get()) * 100}\\n\\n')\n\n if e_chicken.get() != '0':\n textReceipt.insert(END, f'Chicken:\\t\\t\\t{float(e_chicken.get()) * 140}\\n\\n')\n\n if e_mutton.get() != '0':\n textReceipt.insert(END, f'Mutton:\\t\\t\\t{float(e_mutton.get()) * 160}\\n\\n')\n\n if e_lassi.get() != '0':\n textReceipt.insert(END, f'Lassi:\\t\\t\\t{float(e_lassi.get()) * 40}\\n\\n')\n if e_coffee.get() != '0':\n textReceipt.insert(END, f'Coffee:\\t\\t\\t{float(e_coffee.get()) * 40}\\n\\n')\n if e_faluda.get() != '0':\n textReceipt.insert(END, f'Faluda:\\t\\t\\t{float(e_faluda.get()) * 50}\\n\\n')\n if e_shikanji.get() != '0':\n textReceipt.insert(END, f'Shikanji:\\t\\t\\t{float(e_shikanji.get()) * 30}\\n\\n')\n if e_jaljeera.get() != '0':\n textReceipt.insert(END, f'Jal-jeera:\\t\\t\\t{float(e_jaljeera.get()) * 20}\\n\\n')\n if e_rohhafza.get() != '0':\n textReceipt.insert(END, f'Rooh Afza:\\t\\t\\t{float(e_rohhafza.get()) * 30}\\n\\n')\n if e_masalachai.get() != '0':\n textReceipt.insert(END, f'Masala Chai:\\t\\t\\t{float(e_masalachai.get()) * 20}\\n\\n')\n if e_badammilk.get() != '0':\n textReceipt.insert(END, f'Badam Milk:\\t\\t\\t{float(e_badammilk.get()) * 50}\\n\\n')\n if e_coldrinks.get() != '0':\n textReceipt.insert(END, f'Cold Drink:\\t\\t\\t{float(e_coldrinks.get()) * 60}\\n\\n')\n\n if e_kikat.get() != '0':\n textReceipt.insert(END, f'Kitkat Cake:\\t\\t\\t{float(e_kikat.get()) * 480}\\n\\n')\n if e_apple.get() != '0':\n textReceipt.insert(END, f'Apple Cake:\\t\\t\\t{float(e_apple.get()) * 350}\\n\\n')\n if e_vanilla.get() != '0':\n textReceipt.insert(END, f'Vanilla Cake:\\t\\t\\t{float(e_vanilla.get()) * 400}\\n\\n')\n if e_blackforest.get() != '0':\n textReceipt.insert(END, f'Black Forest Cake :\\t\\t\\t{float(e_blackforest.get()) * 550}\\n\\n')\n if e_brownie.get() != '0':\n textReceipt.insert(END, f'Brownie Cake:\\t\\t\\t{float(e_brownie.get()) * 550}\\n\\n')\n if e_banana.get() != '0':\n textReceipt.insert(END, f'Banana Cake:\\t\\t\\t{float(e_banana.get()) * 400}\\n\\n')\n if e_pineapple.get() != '0':\n textReceipt.insert(END, f'Pineapple Cake:\\t\\t\\t{float(e_pineapple.get()) * 380}\\n\\n')\n if e_chocolate.get() != '0':\n textReceipt.insert(END, f'Chocolate Cake:\\t\\t\\t{float(e_chocolate.get()) * 600}\\n\\n')\n if e_oreo.get() != '0':\n textReceipt.insert(END, f'Oreo Cheesecake:\\t\\t\\t{float(e_oreo.get()) * 500}\\n\\n')\n textReceipt.insert(END, '********************************************************************\\n')\n if costofdrinks.get() != 'Rs 0.0':\n textReceipt.insert(END, f'Cost of Drinks:\\t\\t\\t{priceofdrinks} Rs\\n\\n')\n if costofcakes.get() != 'Rs 0.0':\n textReceipt.insert(END, f'Cost of Cakes:\\t\\t\\t{priceofcakes} Rs\\n\\n')\n if costoffood.get() != 'Rs 0.0':\n textReceipt.insert(END, f'Cost of Food:\\t\\t\\t {priceoffood} Rs\\n\\n')\n textReceipt.insert(END, f'Sub Total:\\t\\t\\t{(priceofcakes + priceofdrinks + priceoffood)} Rs\\n\\n')\n textReceipt.insert(END,\n f'Service Charge:\\t\\t\\t {15.5} Rs\\n\\nTotal Cost:\\t\\t\\t{priceofdrinks + priceofcakes + priceoffood + 15.5} Rs\\n\\n')\n textReceipt.insert(END, '*********************************************************************')\n\n else:\n tkinter.messagebox.showerror('Error', 'No Item Is Selected')\n\n\ndef save():\n if var1.get() != 0 or var2.get() != 0 or var3.get() != 0 or var4.get() != 0 or var5.get() != 0 or var6.get() != 0 or var7.get() != 0 \\\n or var8.get() != 0 or var8.get() != 0 or var9.get() != 0 or var10.get() != 0 or var11.get() != 0 or var12.get() != 0 or \\\n var13.get() != 0 or var14.get() != 0 or var15.get() != 0 or var16.get() != 0 or var1.get() != 0 or var17.get() != 0 or \\\n var18.get() != 0 or var19.get() != 0 or var20.get() != 0 or var21.get() != 0 or var22.get() != 0 or var23.get() != 0 or var24.get() != 0 or \\\n var25.get() != 0 or var26.get() != 0 or var27.get() != 0:\n url = filedialog.asksaveasfile(mode='w', defaultextension='.txt',\n filetypes=(('Text File', '.txt'), ('All files', '*.*')))\n if url == None:\n return\n bill_data = textReceipt.get('1.0', END)\n url.write(bill_data)\n url.close()\n else:\n tkinter.messagebox.showerror('Error', 'Nothing To Save')\n\n\nimport random\nimport time\nimport datetime\nfrom tkinter import *\nfrom tkinter import filedialog\nimport requests\n\nimport tkinter.messagebox\n\nroot = Tk()\nroot.geometry('1350x710+0+0')\nroot.resizable(0, 0)\n# root.overrideredirect(True)\nroot.title('Restaurant Management Systems')\nroot.config(bg='firebrick4')\n\ntops = Frame(root, bg='firebrick4', bd=10, pady=5, relief=RIDGE)\ntops.pack(side=TOP)\nlabelTitle = Label(tops, font=('arial', 30, 'bold'), text='Restaurant Management System', bd=9, width=53,\n bg='red4', fg='yellow', justify=CENTER)\nlabelTitle.grid(row=0, column=0)\n\nrecieptcalc_frame = Frame(root, bg='red4', bd=15, relief=RIDGE)\nrecieptcalc_frame.pack(side=RIGHT)\n\nbuttonFrame = Frame(recieptcalc_frame, bg='red4', bd=3, relief=RIDGE)\nbuttonFrame.pack(side=BOTTOM)\n\ncalculatorFrame = Frame(recieptcalc_frame, bg='red4', bd=1, relief=RIDGE)\ncalculatorFrame.pack(side=TOP)\n\nreceiptFrame = Frame(recieptcalc_frame, bg='red4', bd=4, relief=RIDGE)\nreceiptFrame.pack(side=BOTTOM)\n\nmenuFrame = Frame(root, bg='firebrick4', bd=10, relief=RIDGE)\nmenuFrame.pack(side=LEFT)\ncostFrame = Frame(menuFrame, bg='firebrick4', bd=4, )\ncostFrame.pack(side=BOTTOM)\n\nfoodFrame = LabelFrame(menuFrame, text='Food', font=('arial', 19, 'bold'), fg='red4', bg='white', bd=10,\n relief=RIDGE)\nfoodFrame.pack(side=LEFT)\n\ndrinksFrame = LabelFrame(menuFrame, text='Drinks', font=('arial', 19, 'bold'), fg='red4', bg='white', bd=10,\n relief=RIDGE)\ndrinksFrame.pack(side=LEFT)\ncakeFrame = LabelFrame(menuFrame, bg='white', bd=10, text='Cakes', fg='red4', font=('arial', 19, 'bold'), relief=RIDGE)\ncakeFrame.pack(side=RIGHT)\n\n#############################Variables\nvar1 = IntVar()\nvar2 = IntVar()\nvar3 = IntVar()\nvar4 = IntVar()\nvar5 = IntVar()\nvar6 = IntVar()\nvar7 = IntVar()\nvar8 = IntVar()\nvar9 = IntVar()\nvar10 = IntVar()\nvar11 = IntVar()\nvar12 = IntVar()\nvar13 = IntVar()\nvar14 = IntVar()\nvar15 = IntVar()\nvar16 = IntVar()\nvar17 = IntVar()\nvar18 = IntVar()\nvar19 = IntVar()\nvar20 = IntVar()\nvar21 = IntVar()\nvar22 = IntVar()\nvar23 = IntVar()\nvar24 = IntVar()\nvar25 = IntVar()\nvar26 = IntVar()\nvar27 = IntVar()\n\ndateofOrder = StringVar()\nreceipt_ref = StringVar()\ncostoffood = StringVar()\nsubtotal = StringVar()\ntotalcost = StringVar()\ncostofcakes = StringVar()\ncostofdrinks = StringVar()\nservicecharge = StringVar()\n\ntext_input = StringVar()\noperator = ''\n\ne_daal = StringVar()\ne_roti = StringVar()\ne_sabji = StringVar()\ne_chawal = StringVar()\ne_fish = StringVar()\ne_mutton = StringVar()\ne_kebab = StringVar()\ne_chicken = StringVar()\ne_paneer = StringVar()\n\ne_lassi = StringVar()\ne_coffee = StringVar()\ne_faluda = StringVar()\ne_shikanji = StringVar()\ne_jaljeera = StringVar()\ne_rohhafza = StringVar()\ne_masalachai = StringVar()\ne_badammilk = StringVar()\ne_coldrinks = StringVar()\n\ne_kikat = StringVar()\ne_vanilla = StringVar()\ne_apple = StringVar()\ne_blackforest = StringVar()\ne_banana = StringVar()\ne_brownie = StringVar()\ne_pineapple = StringVar()\ne_chocolate = StringVar()\ne_oreo = StringVar()\n\ne_daal.set('0')\ne_roti.set('0')\ne_sabji.set('0')\ne_fish.set('0')\ne_kebab.set('0')\ne_chawal.set('0')\ne_mutton.set('0')\ne_chicken.set('0')\ne_paneer.set('0')\n\ne_lassi.set('0')\ne_coffee.set('0')\ne_faluda.set('0')\ne_rohhafza.set('0')\ne_shikanji.set('0')\ne_jaljeera.set('0')\ne_masalachai.set('0')\ne_badammilk.set('0')\ne_coldrinks.set('0')\n\ne_kikat.set('0')\ne_banana.set('0')\ne_pineapple.set('0')\ne_apple.set('0')\ne_chocolate.set('0')\ne_oreo.set('0')\ne_blackforest.set('0')\ne_brownie.set('0')\ne_vanilla.set('0')\n\ndateofOrder.set(time.strftime('%d/%m/%Y'))\n\n\n#####################################Functions\n\n\ndef reset():\n e_daal.set('0')\n e_roti.set('0')\n e_sabji.set('0')\n e_fish.set('0')\n e_kebab.set('0')\n e_chawal.set('0')\n e_mutton.set('0')\n e_chicken.set('0')\n e_paneer.set('0')\n\n e_lassi.set('0')\n e_coffee.set('0')\n e_faluda.set('0')\n e_rohhafza.set('0')\n e_shikanji.set('0')\n e_jaljeera.set('0')\n e_masalachai.set('0')\n e_badammilk.set('0')\n e_coldrinks.set('0')\n\n e_kikat.set('0')\n e_banana.set('0')\n e_pineapple.set('0')\n e_apple.set('0')\n e_chocolate.set('0')\n e_oreo.set('0')\n e_blackforest.set('0')\n e_brownie.set('0')\n e_vanilla.set('0')\n\n costoffood.set('')\n subtotal.set('')\n totalcost.set('')\n costofcakes.set('')\n costofdrinks.set('')\n servicecharge.set('')\n textReceipt.delete(1.0, END)\n textMsg.delete(1.0, END)\n textNumber.delete(0, END)\n\n var1.set(0)\n var2.set(0)\n var3.set(0)\n var4.set(0)\n\n var5.set(0)\n var6.set(0)\n var7.set(0)\n var8.set(0)\n var9.set(0)\n var10.set(0)\n var11.set(0)\n var12.set(0)\n var13.set(0)\n var14.set(0)\n var15.set(0)\n var16.set(0)\n var17.set(0)\n var18.set(0)\n var19.set(0)\n var20.set(0)\n var21.set(0)\n var22.set(0)\n var23.set(0)\n var24.set(0)\n var25.set(0)\n var26.set(0)\n var27.set(0)\n\n textdaal.config(state=DISABLED)\n textchawal.config(state=DISABLED)\n textroti.config(state=DISABLED)\n textsabji.config(state=DISABLED)\n textKebab.config(state=DISABLED)\n textChiken.config(state=DISABLED)\n textMutton.config(state=DISABLED)\n textpaneer.config(state=DISABLED)\n textFish.config(state=DISABLED)\n\n textLassi.configure(state=DISABLED)\n textCoffee.config(state=DISABLED)\n textJaljeera.config(state=DISABLED)\n textRohhafza.config(state=DISABLED)\n textShikanji.config(state=DISABLED)\n textbadammilk.config(state=DISABLED)\n textMasalachai.config(state=DISABLED)\n textFaluda.config(state=DISABLED)\n textColdrinks.config(state=DISABLED)\n\n textvanilla.config(state=DISABLED)\n textoreo.config(state=DISABLED)\n textpineapple.config(state=DISABLED)\n textApple.config(state=DISABLED)\n textKitkat.config(state=DISABLED)\n textBanana.config(state=DISABLED)\n textBlackforest.config(state=DISABLED)\n textBrownie.config(state=DISABLED)\n textChocolate.config(state=DISABLED)\n\n\ndef send():\n global textMsg, textNumber\n\n def send_sms(number, message):\n url = 'https://www.fast2sms.com/dev/bulk'\n params = {\n 'authorization': 'here you have to add your own,ask me how to do it',\n 'message': message,\n 'numbers': number,\n 'sender_id': 'FSTSMS',\n 'route': 'p',\n 'language': 'english'\n }\n response = requests.get(url, params=params)\n dic = response.json()\n print(dic)\n return dic.get('return')\n\n def btn_click():\n\n num = textNumber.get()\n msg = textMsg.get(\"1.0\", END)\n r = send_sms(num, msg)\n if r:\n tkinter.messagebox.showinfo(\"Send Success\", \"Message successfully sent!\")\n else:\n tkinter.messagebox.showerror(\"Error\", \"Something went wrong\")\n\n root2 = Toplevel()\n root2.title(\"Send Bill\")\n root2.config(bg='red4')\n root2.geometry(\"485x590+50+50\")\n font = (\"helvetica\", 22, \"bold\")\n\n logo = PhotoImage(file='sender.png')\n label = Label(root2, image=logo, bg='red4')\n label.pack(pady=5)\n numberlabel = Label(root2, text='Mobile Number', font=('arial', 18, 'bold underline'), bg='red4', fg='white')\n numberlabel.place(x=5, y=150)\n textNumber = Entry(root2, font=font, bd=5, width=32)\n textNumber.place(x=0, y=185)\n messagelabel = Label(root2, text='Bill Details', font=('arial', 18, 'bold underline'), bg='red4', fg='white')\n messagelabel.place(x=5, y=250)\n textMsg = Text(root2, height=9, font=('times new roman', 14, 'bold'), bd=8,\n relief=GROOVE, width=46)\n textMsg.place(x=4, y=285)\n\n textMsg.insert(END, 'Receipt Ref:\\t\\t' + receipt_ref.get() + '\\t\\t' + dateofOrder.get() + '\\n\\n')\n\n textMsg.insert(END, 'Items:\\t\\t' + ' Cost of Items (in Rs) \\n\\n')\n\n if e_daal.get() != '0':\n textMsg.insert(END, f'Daal:\\t\\t\\t{float(e_daal.get()) * 45}\\n')\n\n if e_roti.get() != '0':\n textMsg.insert(END, f'Roti:\\t\\t\\t{float(e_roti.get()) * 10}\\n')\n\n if e_chawal.get() != '0':\n textMsg.insert(END, f'Chawal:\\t\\t\\t{float(e_chawal.get()) * 30}\\n')\n\n if e_sabji.get() != '0':\n textMsg.insert(END, f'Sabji:\\t\\t\\t{float(e_sabji.get()) * 50}\\n')\n\n if e_fish.get() != '0':\n textMsg.insert(END, f'Fish:\\t\\t\\t{float(e_fish.get()) * 120}\\n')\n\n if e_paneer.get() != '0':\n textMsg.insert(END, f'Paneer:\\t\\t\\t{float(e_paneer.get()) * 110}\\n')\n\n if e_kebab.get() != '0':\n textMsg.insert(END, f'Kabab:\\t\\t\\t{float(e_kebab.get()) * 100}\\n')\n\n if e_chicken.get() != '0':\n textMsg.insert(END, f'Chicken:\\t\\t\\t{float(e_chicken.get()) * 140}\\n')\n\n if e_mutton.get() != '0':\n textMsg.insert(END, f'Mutton:\\t\\t\\t{float(e_mutton.get()) * 160}\\n')\n\n if e_lassi.get() != '0':\n textMsg.insert(END, f'Lassi:\\t\\t\\t{float(e_lassi.get()) * 40}\\n')\n if e_coffee.get() != '0':\n textMsg.insert(END, f'Coffee:\\t\\t\\t{float(e_coffee.get()) * 40}\\n')\n if e_faluda.get() != '0':\n textMsg.insert(END, f'Faluda:\\t\\t\\t{float(e_faluda.get()) * 50}\\n')\n if e_shikanji.get() != '0':\n textMsg.insert(END, f'Shikanji:\\t\\t\\t{float(e_shikanji.get()) * 30}\\n')\n if e_jaljeera.get() != '0':\n textMsg.insert(END, f'Jal-jeera:\\t\\t\\t{float(e_jaljeera.get()) * 20}\\n')\n if e_rohhafza.get() != '0':\n textMsg.insert(END, f'Rooh Afza:\\t\\t\\t{float(e_rohhafza.get()) * 30}\\n')\n if e_masalachai.get() != '0':\n textMsg.insert(END, f'Masala Chai:\\t\\t\\t{float(e_masalachai.get()) * 20}\\n')\n if e_badammilk.get() != '0':\n textMsg.insert(END, f'Badam Milk:\\t\\t\\t{float(e_badammilk.get()) * 50}\\n')\n if e_coldrinks.get() != '0':\n textMsg.insert(END, f'Cold Drink:\\t\\t\\t{float(e_coldrinks.get()) * 60}\\n')\n\n if e_kikat.get() != '0':\n textMsg.insert(END, f'Kitkat Cake:\\t\\t\\t{float(e_kikat.get()) * 480}\\n')\n if e_apple.get() != '0':\n textMsg.insert(END, f'Apple Cake:\\t\\t\\t{float(e_apple.get()) * 350}\\n')\n if e_vanilla.get() != '0':\n textMsg.insert(END, f'Vanilla Cake:\\t\\t\\t{float(e_vanilla.get()) * 400}\\n')\n if e_blackforest.get() != '0':\n textMsg.insert(END, f'Black Forest Cake :\\t\\t\\t{float(e_blackforest.get()) * 550}\\n')\n if e_brownie.get() != '0':\n textMsg.insert(END, f'Brownie Cake:\\t\\t\\t{float(e_brownie.get()) * 550}\\n')\n if e_banana.get() != '0':\n textMsg.insert(END, f'Banana Cake:\\t\\t\\t{float(e_banana.get()) * 400}\\n')\n if e_pineapple.get() != '0':\n textMsg.insert(END, f'Pineapple Cake:\\t\\t\\t{float(e_pineapple.get()) * 380}\\n')\n if e_chocolate.get() != '0':\n textMsg.insert(END, f'Chocolate Cake:\\t\\t\\t{float(e_chocolate.get()) * 600}\\n')\n if e_oreo.get() != '0':\n textMsg.insert(END, f'Oreo Cheesecake:\\t\\t\\t{float(e_oreo.get()) * 500}\\n')\n textMsg.insert(END, '\\n')\n if costofdrinks.get() != 'Rs 0.0':\n textMsg.insert(END, f'Cost of Drinks:\\t\\t\\t{priceofdrinks} Rs\\n')\n if costofcakes.get() != 'Rs 0.0':\n textMsg.insert(END, f'Cost of Cakes:\\t\\t\\t{priceofcakes} Rs\\n')\n if costoffood.get() != 'Rs 0.0':\n textMsg.insert(END, f'Cost of Food:\\t\\t\\t {priceoffood} Rs\\n')\n textMsg.insert(END, '\\n')\n textMsg.insert(END, f'Sub Total:\\t\\t\\t{(priceofcakes + priceofdrinks + priceoffood)} Rs\\n')\n textMsg.insert(END,\n f'Service Charge:\\t\\t\\t {15.5} Rs\\nTotal Cost:\\t\\t\\t{priceofdrinks + priceofcakes + priceoffood + 15.5} Rs\\n')\n\n sendBtn = Button(root2, text=\"SEND\", command=btn_click, bd=7, relief=GROOVE, bg='white', fg='black',\n font=('arial', 19, 'bold'))\n sendBtn.place(x=150, y=525)\n\n root.mainloop()\n\n\n##################################################Food\nRoti = Checkbutton(foodFrame, text='Roti', variable=var19, onvalue=1, offvalue=0,\n font=('arial', 18, 'bold')\n , bg='white', command=roti).grid(row=0, sticky=W)\n\nDaal = Checkbutton(foodFrame, text='Daal', variable=var20, onvalue=1, offvalue=0, font=('arial', 18, 'bold')\n , bg='white', command=daal).grid(row=1, sticky=W)\nFish = Checkbutton(foodFrame, text='Fish', variable=var21, onvalue=1, offvalue=0, font=('arial', 18, 'bold')\n , bg='white', command=fish).grid(row=2, sticky=W)\nSabji = Checkbutton(foodFrame, text='Sabji', variable=var22, onvalue=1, offvalue=0, font=('arial', 18, 'bold')\n , bg='white', command=sabji).grid(row=3, sticky=W)\nKebab = Checkbutton(foodFrame, text='Kebab', variable=var23, onvalue=1, offvalue=0, font=('arial', 18, 'bold')\n , bg='white', command=kebab).grid(row=4, sticky=W)\nChawal = Checkbutton(foodFrame, text='Chawal', variable=var24, onvalue=1, offvalue=0, font=('arial', 18, 'bold')\n , bg='white', command=chawal).grid(row=5, sticky=W)\n\nMutton = Checkbutton(foodFrame, text='Mutton', variable=var25, onvalue=1, offvalue=0,\n font=('arial', 18, 'bold')\n , bg='white', command=mutton).grid(row=6, sticky=W)\n\nPaneer = Checkbutton(foodFrame, text='Paneer', variable=var26, onvalue=1, offvalue=0,\n font=('arial', 18, 'bold')\n , bg='white', command=paneer).grid(row=7, sticky=W)\n\nChicken = Checkbutton(foodFrame, text='Chicken', variable=var27, onvalue=1, offvalue=0, font=('arial', 18, 'bold')\n , bg='white', command=chicken).grid(row=8, sticky=W)\n\n##################################################Food entry\ntextroti = Entry(foodFrame, font=('arial', 18, 'bold'), bd=8, width=6, textvariable=e_roti, justify=LEFT,\n state=DISABLED)\ntextroti.grid(row=0, column=1)\ntextdaal = Entry(foodFrame, font=('arial', 18, 'bold'), bd=8, width=6, textvariable=e_daal, justify=LEFT,\n state=DISABLED)\ntextdaal.grid(row=1, column=1)\ntextFish = Entry(foodFrame, font=('arial', 18, 'bold'), bd=8, width=6, textvariable=e_fish, justify=LEFT,\n state=DISABLED)\ntextFish.grid(row=2, column=1)\ntextsabji = Entry(foodFrame, font=('arial', 18, 'bold'), bd=8, width=6, textvariable=e_sabji, justify=LEFT,\n state=DISABLED)\ntextsabji.grid(row=3, column=1)\ntextKebab = Entry(foodFrame, font=('arial', 18, 'bold'), bd=8, width=6, textvariable=e_kebab, justify=LEFT,\n state=DISABLED)\ntextKebab.grid(row=4, column=1)\ntextchawal = Entry(foodFrame, font=('arial', 18, 'bold'), bd=8, width=6, textvariable=e_chawal, justify=LEFT,\n state=DISABLED)\ntextchawal.grid(row=5, column=1)\ntextMutton = Entry(foodFrame, font=('arial', 18, 'bold'), bd=8, width=6, textvariable=e_mutton, justify=LEFT,\n state=DISABLED)\ntextMutton.grid(row=6, column=1)\n\ntextpaneer = Entry(foodFrame, font=('arial', 18, 'bold'), bd=8, width=6, textvariable=e_paneer, justify=LEFT,\n state=DISABLED)\ntextpaneer.grid(row=7, column=1)\n\ntextChiken = Entry(foodFrame, font=('arial', 18, 'bold'), bd=8, width=6, textvariable=e_chicken, justify=LEFT,\n state=DISABLED)\ntextChiken.grid(row=8, column=1)\n\n#################################Drinks############################\n\nlassi = Checkbutton(drinksFrame, text='Lassi', variable=var1, onvalue=1, offvalue=0,\n font=('arial', 18, 'bold')\n , bg='white', command=lassi).grid(row=0, sticky=W)\n\ncoffee = Checkbutton(drinksFrame, text='Coffee', variable=var2, onvalue=1, offvalue=0, font=('arial', 18, 'bold')\n , bg='white', command=coffee).grid(row=1, sticky=W)\nfaluda = Checkbutton(drinksFrame, text='Faluda', variable=var3, onvalue=1, offvalue=0, font=('arial', 18, 'bold')\n , bg='white', command=faluda).grid(row=2, sticky=W)\nshikanji = Checkbutton(drinksFrame, text='Shikanji', variable=var4, onvalue=1, offvalue=0, font=('arial', 18, 'bold')\n , bg='white', command=shikanji).grid(row=3, sticky=W)\njaljeera = Checkbutton(drinksFrame, text='Jal-jeera', variable=var5, onvalue=1, offvalue=0, font=('arial', 18, 'bold')\n , bg='white', command=jaljeera).grid(row=4, sticky=W)\nroohafza = Checkbutton(drinksFrame, text='Rooh Afza', variable=var6, onvalue=1, offvalue=0, font=('arial', 18, 'bold')\n , bg='white', command=roohafza).grid(row=5, sticky=W)\n\nmasalachai = Checkbutton(drinksFrame, text='Masala Tea', variable=var7, onvalue=1, offvalue=0,\n font=('arial', 18, 'bold')\n , bg='white', command=masalachai).grid(row=6, sticky=W)\n\nbadammilk = Checkbutton(drinksFrame, text='Badam Milk', variable=var8, onvalue=1, offvalue=0, font=('arial', 18, 'bold')\n , bg='white', command=badammilk).grid(row=7, sticky=W)\nColdrinks = Checkbutton(drinksFrame, text='Cold Drinks', variable=var9, onvalue=1, offvalue=0,\n font=('arial', 18, 'bold')\n , bg='white', command=coldrinks).grid(row=8, sticky=W)\n\n##############################Textbox for drinks################################\n\n\ntextLassi = Entry(drinksFrame, font=('arial', 18, 'bold'), bd=8, width=6, textvariable=e_lassi, justify=LEFT,\n state=DISABLED)\ntextLassi.grid(row=0, column=1)\ntextCoffee = Entry(drinksFrame, font=('arial', 18, 'bold'), bd=8, width=6, textvariable=e_coffee, justify=LEFT,\n state=DISABLED)\ntextCoffee.grid(row=1, column=1)\ntextFaluda = Entry(drinksFrame, font=('arial', 18, 'bold'), bd=8, width=6, textvariable=e_faluda, justify=LEFT,\n state=DISABLED)\ntextFaluda.grid(row=2, column=1)\ntextShikanji = Entry(drinksFrame, font=('arial', 18, 'bold'), bd=8, width=6, textvariable=e_shikanji, justify=LEFT,\n state=DISABLED)\ntextShikanji.grid(row=3, column=1)\ntextJaljeera = Entry(drinksFrame, font=('arial', 18, 'bold'), bd=8, width=6, textvariable=e_jaljeera, justify=LEFT,\n state=DISABLED)\ntextJaljeera.grid(row=4, column=1)\ntextRohhafza = Entry(drinksFrame, font=('arial', 18, 'bold'), bd=8, width=6, textvariable=e_rohhafza, justify=LEFT,\n state=DISABLED)\ntextRohhafza.grid(row=5, column=1)\n\ntextMasalachai = Entry(drinksFrame, font=('arial', 18, 'bold'), bd=8, width=6, textvariable=e_masalachai, justify=LEFT,\n state=DISABLED)\ntextMasalachai.grid(row=6, column=1)\ntextbadammilk = Entry(drinksFrame, font=('arial', 18, 'bold'), bd=8, width=6, textvariable=e_badammilk, justify=LEFT,\n state=DISABLED)\ntextbadammilk.grid(row=7, column=1)\ntextColdrinks = Entry(drinksFrame, font=('arial', 18, 'bold'), bd=8, width=6, textvariable=e_coldrinks, justify=LEFT,\n state=DISABLED)\ntextColdrinks.grid(row=8, column=1)\n\n######################Cakes#############################\nkitkatcake = Checkbutton(cakeFrame, text='Kitkat ', variable=var10, onvalue=1, offvalue=0,\n font=('arial', 18, 'bold')\n , bg='white', command=kitkat).grid(row=2, sticky=W)\napplecake = Checkbutton(cakeFrame, text='Apple ', variable=var11, onvalue=1, offvalue=0, font=('arial', 18, 'bold')\n , bg='white', command=apple).grid(row=1, sticky=W)\nvanillacake = Checkbutton(cakeFrame, text='Vanilla ', variable=var12, onvalue=1, offvalue=0,\n font=('arial', 18, 'bold')\n , bg='white', command=vanilla).grid(row=3, sticky=W)\nblackforest = Checkbutton(cakeFrame, text='Black Forest', variable=var13, onvalue=1, offvalue=0,\n font=('arial', 18, 'bold')\n , bg='white', command=blackforest).grid(row=8, sticky=W)\nbananacake = Checkbutton(cakeFrame, text='Banana ', variable=var14, onvalue=1, offvalue=0,\n font=('arial', 18, 'bold')\n , bg='white', command=banana).grid(row=4, sticky=W)\nbrownie = Checkbutton(cakeFrame, text='Brownie ', variable=var15, onvalue=1, offvalue=0, font=('arial', 18, 'bold')\n , bg='white', command=brownie).grid(row=5, sticky=W)\npineapplecake = Checkbutton(cakeFrame, text='Pineapple ', variable=var16, onvalue=1, offvalue=0,\n font=('arial', 18, 'bold')\n , bg='white', command=pineapple).grid(row=6, sticky=W)\nchocolatecake = Checkbutton(cakeFrame, text='Chocolate', variable=var17, onvalue=1, offvalue=0,\n font=('arial', 18, 'bold')\n , bg='white', command=chocolate).grid(row=7, sticky=W)\n\noreocheesecake = Checkbutton(cakeFrame, text='Oreo ', variable=var18, onvalue=1, offvalue=0,\n font=('arial', 18, 'bold')\n , bg='white', command=oreo).grid(row=0, sticky=W)\n\n#########################textbox for cakes\n\ntextKitkat = Entry(cakeFrame, font=('arial', 18, 'bold'), bd=8, width=6, justify=LEFT, state=DISABLED,\n textvariable=e_kikat)\ntextKitkat.grid(row=2, column=1)\ntextApple = Entry(cakeFrame, font=('arial', 18, 'bold'), bd=8, width=6, textvariable=e_apple, justify=LEFT,\n state=DISABLED)\ntextApple.grid(row=1, column=1)\ntextBlackforest = Entry(cakeFrame, font=('arial', 18, 'bold'), bd=8, width=6, textvariable=e_blackforest, justify=LEFT,\n state=DISABLED)\ntextBlackforest.grid(row=8, column=1)\ntextBanana = Entry(cakeFrame, font=('arial', 18, 'bold'), bd=8, width=6, textvariable=e_banana, justify=LEFT,\n state=DISABLED)\ntextBanana.grid(row=4, column=1)\ntextBrownie = Entry(cakeFrame, font=('arial', 18, 'bold'), bd=8, width=6, textvariable=e_brownie, justify=LEFT,\n state=DISABLED)\ntextBrownie.grid(row=5, column=1)\ntextpineapple = Entry(cakeFrame, font=('arial', 18, 'bold'), bd=8, width=6, textvariable=e_pineapple, justify=LEFT,\n state=DISABLED)\ntextpineapple.grid(row=6, column=1)\ntextChocolate = Entry(cakeFrame, font=('arial', 18, 'bold'), bd=8, width=6, textvariable=e_chocolate, justify=LEFT,\n state=DISABLED)\ntextChocolate.grid(row=7, column=1)\ntextvanilla = Entry(cakeFrame, font=('arial', 18, 'bold'), bd=8, width=6, textvariable=e_vanilla, justify=LEFT,\n state=DISABLED)\ntextvanilla.grid(row=3, column=1)\ntextoreo = Entry(cakeFrame, font=('arial', 18, 'bold'), bd=8, width=6, textvariable=e_oreo, justify=LEFT,\n state=DISABLED)\ntextoreo.grid(row=0, column=1)\n\n###########################Receipt\n\ntextReceipt = Text(receiptFrame, width=46, height=14, bg='white', bd=4, font=('arial', 12, 'bold'))\ntextReceipt.grid(row=0, column=0)\n\n###############################Total costs\n\nlabelCostofDrinks = Label(costFrame, font=('arial', 16, 'bold'), text='Cost of Drinks\\t',\n bg='firebrick4', fg='cornsilk', justify=CENTER)\nlabelCostofDrinks.grid(row=0, column=0, sticky=W)\n\ntextcostofdrinks = Entry(costFrame, font=('arial', 16, 'bold'), bd=7, textvariable=costofdrinks, bg='white', width=14,\n justify=RIGHT, state='readonly')\ntextcostofdrinks.grid(row=0, column=1)\n\nlabelCostofCake = Label(costFrame, font=('arial', 16, 'bold'), text='Cost of Cake\\t',\n bg='firebrick4', fg='cornsilk')\nlabelCostofCake.grid(row=1, column=0, sticky=W)\n\ntextcostofCake = Entry(costFrame, font=('arial', 16, 'bold'), bd=7, textvariable=costofcakes, bg='white', width=14,\n justify=RIGHT, state='readonly')\ntextcostofCake.grid(row=1, column=1)\n\nlabelcostofFood = Label(costFrame, font=('arial', 16, 'bold'), text='Cost of Food\\t',\n bg='firebrick4', fg='cornsilk')\nlabelcostofFood.grid(row=2, column=0, sticky=W)\n\ntextcostofFood = Entry(costFrame, font=('arial', 16, 'bold'), bd=7, textvariable=costoffood, bg='white', width=14,\n justify=RIGHT, state='readonly')\ntextcostofFood.grid(row=2, column=1)\n\n#######################Payment Information\nlabelsubTotal = Label(costFrame, font=('arial', 16, 'bold'), text=' Sub Total\\t',\n bg='firebrick4', fg='cornsilk')\nlabelsubTotal.grid(row=0, column=2, sticky=W)\n\ntextsubTotal = Entry(costFrame, font=('arial', 16, 'bold'), bd=7, textvariable=subtotal, bg='white', width=14,\n justify=RIGHT, state='readonly')\ntextsubTotal.grid(row=0, column=3)\n\nlabelServiceCharge = Label(costFrame, font=('arial', 16, 'bold'), text=' Service Charge\\t',\n bg='firebrick4', fg='cornsilk', justify=CENTER)\nlabelServiceCharge.grid(row=1, column=2, sticky=W)\n\ntextServiceCharge = Entry(costFrame, font=('arial', 16, 'bold'), bd=7, textvariable=servicecharge, bg='white', width=14,\n justify=RIGHT, state='readonly')\ntextServiceCharge.grid(row=1, column=3)\n\nlabelTotalCost = Label(costFrame, font=('arial', 16, 'bold'), text=' Total Cost\\t',\n bg='firebrick4', fg='cornsilk')\nlabelTotalCost.grid(row=2, column=2, sticky=W)\n\ntextTotalCost = Entry(costFrame, font=('arial', 16, 'bold'), bd=7, textvariable=totalcost, bg='white', width=14,\n justify=RIGHT, state='readonly')\ntextTotalCost.grid(row=2, column=3)\n\n################Buttons\n\nbuttonTotal = Button(buttonFrame, padx=16, pady=1, bd=4, fg='white', font=('arial', 14, 'bold'), width=4, text='Total'\n , bg='red4', command=CostofItem).grid(row=0, column=0)\nbuttonReceipt = Button(buttonFrame, padx=16, pady=1, bd=4, fg='white', font=('arial', 14, 'bold'), width=4,\n text='Receipt'\n , bg='red4', command=receipt).grid(row=0, column=1)\n\nbuttonSave = Button(buttonFrame, padx=16, pady=1, bd=4, fg='white', font=('arial', 14, 'bold'), width=4,\n text='Save'\n , bg='red4', command=save).grid(row=0, column=2)\nbuttonSend = Button(buttonFrame, padx=16, pady=1, bd=4, fg='white', font=('arial', 14, 'bold'), width=4,\n text='Send'\n , bg='red4', command=send).grid(row=0, column=3)\n\nbuttonReset = Button(buttonFrame, padx=16, pady=1, bd=4, fg='white', font=('arial', 14, 'bold'), width=4, text='Reset'\n , bg='red4', command=reset).grid(row=0, column=4)\n\n\n########################################Calculator Display################\n\n\ndef btnClick(numbers):\n global operator\n operator = operator + str(numbers)\n text_input.set(operator)\n\n\ndef btnClear():\n global operator\n operator = ''\n text_input.set('')\n\n\ndef btnAnswer():\n try:\n global operator\n sumup = str(eval(operator))\n text_input.set(sumup)\n operator = ''\n except:\n pass\n\n\n#########################Calculator\n\ntextDisplay = Entry(calculatorFrame, width=35, bg='white', bd=4, textvariable=text_input, font=('arial', 16, 'bold'),\n justify=RIGHT)\ntextDisplay.grid(row=0, column=0, columnspan=4, pady=1)\ntextDisplay.insert(0, '0')\n\nbutton7 = Button(calculatorFrame, padx=16, pady=1, bd=7, fg='yellow', font=('arial', 16, 'bold'), width=4, text='7'\n , bg='red4', command=lambda: btnClick(7)).grid(row=2, column=0)\n\nbutton8 = Button(calculatorFrame, padx=16, pady=1, bd=7, fg='yellow', font=('arial', 16, 'bold'), width=4, text='8'\n , bg='red4', command=lambda: btnClick(8)).grid(row=2, column=1)\n\nbutton9 = Button(calculatorFrame, padx=16, pady=1, bd=7, fg='yellow', font=('arial', 16, 'bold'), width=4, text='9'\n , bg='red4', command=lambda: btnClick(9)).grid(row=2, column=2)\n\nbuttonAdd = Button(calculatorFrame, padx=16, pady=1, bd=7, fg='yellow', font=('arial', 16, 'bold'), width=4, text='+'\n , bg='red4', command=lambda: btnClick('+')).grid(row=2, column=3)\n\nbutton4 = Button(calculatorFrame, padx=16, pady=1, bd=7, fg='yellow', font=('arial', 16, 'bold'), width=4, text='4'\n , bg='red4', command=lambda: btnClick(4)).grid(row=3, column=0)\n\nbutton5 = Button(calculatorFrame, padx=16, pady=1, bd=7, bg='white', font=('arial', 16, 'bold'), width=4, text='5'\n , fg='red4', command=lambda: btnClick(5)).grid(row=3, column=1)\n\nbutton6 = Button(calculatorFrame, padx=16, pady=1, bd=7, bg='white', font=('arial', 16, 'bold'), width=4, text='6'\n , fg='red4', command=lambda: btnClick(6)).grid(row=3, column=2)\n\nbuttonsub = Button(calculatorFrame, padx=16, pady=1, bd=7, fg='yellow', font=('arial', 16, 'bold'), width=4, text='-'\n , bg='red4', command=lambda: btnClick('-')).grid(row=3, column=3)\n\nbutton1 = Button(calculatorFrame, padx=16, pady=1, bd=7, fg='yellow', font=('arial', 16, 'bold'), width=4, text='1'\n , bg='red4', command=lambda: btnClick(1)).grid(row=4, column=0)\n\nbutton2 = Button(calculatorFrame, padx=16, pady=1, bd=7, bg='white', font=('arial', 16, 'bold'), width=4, text='2'\n , fg='red4', command=lambda: btnClick(2)).grid(row=4, column=1)\n\nbutton3 = Button(calculatorFrame, padx=16, pady=1, bd=7, bg='white', font=('arial', 16, 'bold'), width=4, text='3'\n , fg='red4', command=lambda: btnClick(3)).grid(row=4, column=2)\n\nbuttonmult = Button(calculatorFrame, padx=16, pady=1, bd=7, fg='yellow', font=('arial', 16, 'bold'), width=4, text='*'\n , bg='red4', command=lambda: btnClick('*')).grid(row=4, column=3)\n\nbuttonans = Button(calculatorFrame, padx=16, pady=1, bd=7, fg='yellow', font=('arial', 16, 'bold'), width=4, text='Ans'\n , bg='red4', command=btnAnswer).grid(row=5, column=0)\n\nbuttonclear = Button(calculatorFrame, padx=16, pady=1, bd=7, fg='yellow', font=('arial', 16, 'bold'), width=4,\n text='Clear'\n , bg='red4', command=btnClear).grid(row=5, column=1)\n\nbutton0 = Button(calculatorFrame, padx=16, pady=1, bd=7, fg='yellow', font=('arial', 16, 'bold'), width=4, text='0'\n , bg='red4', command=lambda: btnClick(0)).grid(row=5, column=2)\n\nbuttondiv = Button(calculatorFrame, padx=16, pady=1, bd=7, fg='yellow', font=('arial', 16, 'bold'), width=4, text='/'\n , bg='red4', command=lambda: btnClick('/')).grid(row=5, column=3)\n\nroot.mainloop()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":47141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"159778518","text":"from flask import Flask, render_template, request\nfrom models.models import PostIt\nfrom models.database import db_session\nfrom datetime import datetime\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n all_post_it = PostIt.query.all()\n return render_template('index.html', postits=all_post_it)\n\n@app.route('/add', methods=['post'])\ndef add():\n title = request.form['title']\n content = PostIt(title, datetime.now())\n print(f'{title}のPOSTを確認')\n db_session.add(content)\n db_session.commit()\n return index()\n\nif __name__ == '__main__':\n app.debug = True\n app.run(host='0.0.0.0', port=8080)","sub_path":"TrelloLike/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"270109451","text":"from telegram.ext import CallbackContext\n\nfrom .string import strings\n\nget_string = strings.get_string\nget_languages = strings.get_languages\n\n\ndef lang_(func):\n def wrapper(update, context):\n return func(\n update,\n context,\n context.bot_data.get(\n update.effective_chat.id, {}\n ).get(\n \"lang\", \"en\"\n )\n )\n return wrapper\n\n\ndef _lang(context: CallbackContext, chat_id: int):\n return context.bot_data.get(\n chat_id, {}\n ).get(\n \"lang\", \"en\"\n )\n","sub_path":"strings/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"242813811","text":"\n\nfrom lib.Settings import Settings\nfrom lib.Misc.CheatCodes import CheatCodes\n\nfrom lib.Misc.Sounds import Sounds\n\nfrom lib.Boards.WelcomeBoard import WelcomeBoard\nfrom lib.Boards.Scoreboard import Scoreboard\nfrom lib.Maze.Maze import Maze\nfrom lib.Popups.Popups import Popups\n\nfrom lib.Actors.Player import Player\nfrom lib.Actors.Blinky import Blinky\nfrom lib.Actors.Pinky import Pinky\nfrom lib.Actors.Inky import Inky\nfrom lib.Actors.Clyde import Clyde\nfrom lib.Actors.Fruit import Fruit\n\nfrom lib.Maze.Portal import Portal\n\nimport pygame\n\nimport math\nimport random\nimport sys\n\n\nclass Pacman:\n\t\n\tdef __init__(self):\n\t\t\n\t\tself.settings = Settings()\n\t\t\n\t\tself.clock = None\n\t\t\n\t\tself.screen = None\n\t\tself.screen_rect = None\n\t\t\n\t\tself.initialize_pygame()\n\t\t\n\t\tself.welcome_board = None\n\t\tself.scoreboard = None\n\t\t\n\t\tself.sounds = None\n\t\t\n\t\tself.maze = None\n\t\tself.popups = None\n\t\t\n\t\tself.player = None\n\t\tself.ghosts = None\n\t\tself.fruits = []\n\t\tself.__fruits_remaining = self.settings.fruit_per_round\n\t\tself.__fruits_eaten = None\n\t\t\n\t\tself.portal = None\n\t\t\n\t\tself.cheater = None\n\t\t\n\t\tself.playing_round = False\n\t\tself.ghosts_eaten_since_last_power_pellet = 0\n\t\n\tdef initialize_pygame(self):\n\t\n\t\tprint(\"Initializing pygame\")\n\t\t\n\t\t# Initialize mixer, ***THEN*** pygame\n\t\t# I have no idea why, but calling pygame.init() before the mixer, introduces lag\n\t\tpygame.mixer.pre_init(self.settings.sound_sample_rate, -16, self.settings.sound_channels, 1024)\n\t\tpygame.mixer.init()\n\t\tpygame.init()\n\t\t\n\t\t# Clock\n\t\tself.clock = pygame.time.Clock()\n\t\t\n\t\t# Get the monitor's size\n\t\t# This fails horribly on a system with 2+ monitors\n\t\t# monitor_info = pygame.display.Info()\n\t\t# monitor_width = monitor_info.current_w\n\t\t# monitor_height = monitor_info.current_h\n\t\t# width = int(monitor_width * self.settings.screen_size_factor)\n\t\t# height = int(monitor_height * self.settings.screen_size_factor)\n\t\t\n\t\twidth = int(self.settings.screen_width * self.settings.screen_size_factor)\n\t\theight = int(self.settings.screen_height * self.settings.screen_size_factor)\n\t\t\n\t\t# Screen\n\t\tself.screen = pygame.display.set_mode((width, height))\n\t\tself.screen_rect = self.screen.get_rect()\n\t\tpygame.display.set_caption(self.settings.game_title)\n\t\n\tdef run(self):\n\t\t\n\t\tself.initialize_gamestuffs()\n\t\t\n\t\tself.sounds.play_theater_music()\n\t\t\n\t\tself.main_loop()\n\t\t\n\tdef main_loop(self):\n\t\t\n\t\twhile True:\n\t\t\t\n\t\t\tself.main_loop_one()\n\t\n\tdef main_loop_one(self):\n\t\t\n\t\telapsed_ms = self.clock.tick()\n\t\t\n\t\t# Keep elapsed time to a sane range\n\t\tif elapsed_ms < self.settings.minimum_elapsed_ms:\n\t\t\telapsed_ms = self.settings.minimum_elapsed_ms\n\t\telif elapsed_ms > self.settings.maximum_elapsed_ms:\n\t\t\telapsed_ms = self.settings.maximum_elapsed_ms\n\t\t\n\t\tself.handle_events()\n\t\t\n\t\tself.update(elapsed_ms)\n\t\t\n\t\tself.draw()\n\t\n\tdef handle_events(self):\n\t\t\n\t\t# Handle all events\n\t\tfor event in pygame.event.get():\n\t\t\t\n\t\t\t# Allow the cheater to peek\n\t\t\tself.cheater.peek_at_event(event)\n\t\t\t\n\t\t\t#\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tsys.exit()\n\t\t\t\n\t\t\t# Allow the welcome board to sneak in\n\t\t\telif self.welcome_board.handle_event(event):\n\t\t\t\tcontinue\n\t\t\t\n\t\t\t#\n\t\t\telif event.type == pygame.KEYUP or event.type == pygame.KEYDOWN:\n\t\t\t\tself.handle_keyboard_event(event)\n\t\n\tdef handle_keyboard_event(self, event):\n\t\t\n\t\t# Q for Quit\n\t\tif event.key == pygame.K_q:\n\t\t\tsys.exit(0)\n\t\t\n\t\t# Arrows navigate the human player\n\t\telif (\n\t\t\tevent.key == pygame.K_UP\n\t\t\tor event.key == pygame.K_DOWN\n\t\t\tor event.key == pygame.K_LEFT\n\t\t\tor event.key == pygame.K_RIGHT\n\t\t):\n\t\t\tif event.key == pygame.K_UP:\n\t\t\t\tself.player.set_movement_input_up()\n\t\t\t\tself.player.set_movement_input_down(False)\n\t\t\telif event.key == pygame.K_DOWN:\n\t\t\t\tself.player.set_movement_input_up(False)\n\t\t\t\tself.player.set_movement_input_down()\n\t\t\tif event.key == pygame.K_LEFT:\n\t\t\t\tself.player.set_movement_input_left()\n\t\t\t\tself.player.set_movement_input_right(False)\n\t\t\telif event.key == pygame.K_RIGHT:\n\t\t\t\tself.player.set_movement_input_left(False)\n\t\t\t\tself.player.set_movement_input_right()\n\t\t\n\t\t# Space bar or \"P\" launches a portal\n\t\telif (\n\t\t\t(event.key == pygame.K_SPACE or event.key == pygame.K_p)\n\t\t\tand event.type == pygame.KEYUP\n\t\t):\n\t\t\tself.spawn_portal()\n\t\n\tdef handle_cheat_codes(self):\n\t\n\t\tcode = self.cheater.get_code()\n\t\tif code:\n\t\t\n\t\t\tif code == \"rects\":\n\t\t\t\n\t\t\t\tself.settings.maze_draw_debug_rects = (\n\t\t\t\t\tnot self.settings.maze_draw_debug_rects\n\t\t\t\t)\n\t\t\t\n\t\t\telif code == \"paths\":\n\t\t\t\t\n\t\t\t\tself.settings.debug_show_paths = (\n\t\t\t\t\tnot self.settings.debug_show_paths\n\t\t\t\t)\n\t\t\t\n\t\t\telif code == \"frames\":\n\t\t\t\t\n\t\t\t\tself.settings.animation_draw_frames = (\n\t\t\t\t\tnot self.settings.animation_draw_frames\n\t\t\t\t)\n\t\t\t\n\t\t\telif code == \"fruit\":\n\t\t\t\t\n\t\t\t\tself.spawn_fruit()\n\t\t\t\n\t\t\telif code == \"die\":\n\t\t\t\t\n\t\t\t\tif self.do_player_death():\n\t\t\t\t\tself.continue_round()\n\t\t\t\n\t\t\telif code == \"kill\":\n\t\t\t\t\n\t\t\t\tself.ghosts_eaten_since_last_power_pellet = 0\n\t\t\t\tfor ghost in self.ghosts:\n\t\t\t\t\tself.player_ate_ghost(ghost)\n\t\t\t\n\t\t\telif code == \"scare\":\n\t\t\t\n\t\t\t\tself.scare_all_ghosts()\n\t\t\t\n\t\t\telif code == \"clear\":\n\t\t\t\t\n\t\t\t\tbrick_me = self.player.get_closest_brick()\n\t\t\t\tbricks_me = self.maze.get_cluster_around_brick(brick_me, None)\n\t\t\t\tfor brick in self.maze.bricks:\n\t\t\t\t\tif brick not in bricks_me:\n\t\t\t\t\t\tif brick.is_pill() or brick.is_power_pellet():\n\t\t\t\t\t\t\tbrick.make_blank()\n\t\t\t\tself.maze.remember_power_pellets()\n\t\t\t\tself.maze.remember_pills()\n\t\t\t\tself.maybe_win_round()\n\t\t\t\n\t\t\telif code == \"win\":\n\t\t\t\t\n\t\t\t\tself.do_win_round()\n\t\t\t\n\t\t\telif code == \"5level\":\n\t\t\t\t\n\t\t\t\tfor i in range(5):\n\t\t\t\t\tself.increase_level()\n\t\t\t\n\t\t\telif code == \"level\":\n\t\t\t\t\n\t\t\t\tself.increase_level()\n\t\t\t\n\t\t\telse:\n\t\t\t\tprint(\"Invalid cheat code:\", code)\n\t\n\tdef initialize_gamestuffs(self):\n\t\t\n\t\tself.initialize_cheater()\n\t\t\n\t\tself.initialize_sounds()\n\t\tself.initialize_maze()\n\t\tself.initialize_boards()\n\t\tself.initialize_popups()\n\t\t\n\t\tself.initialize_player()\n\t\tself.initialize_ghosts()\n\t\t\n\tdef start_game(self):\n\t\t\n\t\tself.initialize_gamestuffs()\n\t\tprint(\"Starting game!!!\")\n\t\t\n\t\tself.start_round()\n\t\n\tdef start_round(self):\n\t\t\n\t\t#\n\t\tif self.welcome_board.is_activated():\n\t\t\treturn\n\t\t\n\t\t#\n\t\tself.playing_round = False\n\t\t\n\t\tself.__fruits_eaten = 0\n\t\tself.__fruits_remaining = self.settings.fruit_per_round\n\t\t\n\t\t# Increment level\n\t\tself.increase_level()\n\t\t\n\t\t# Load up the maze\n\t\tself.maze.load_maze_file(\"test\")\n\t\t\n\t\tself.continue_round()\n\t\n\tdef continue_round(self):\n\t\t\n\t\tself.playing_round = True\n\t\t\n\t\t# Reset player's animation\n\t\tself.player.set_default_animation()\n\t\t\n\t\t# Reinitialize the ghosts\n\t\tself.initialize_ghosts()\n\t\t\n\t\t# Place the player and ghosts\n\t\tself.place_player_at_random_pill()\n\t\tself.place_ghosts_in_pen()\n\t\t\n\t\tself.do_round_intro()\n\t\t\n\t\tself.sounds.play_ghost_sounds()\n\t\t\n\t\t# Reset ghost penned time\n\t\tfor ghost in self.ghosts:\n\t\t\tghost.set_penned_state(\"in\")\n\t\n\tdef do_round_intro(self):\n\t\t\n\t\tself.freeze_actors()\n\t\t\n\t\tself.sounds.play_intro_music()\n\t\t\n\t\tself.do_popup_game_state_message(\"Get Ready!\")\n\t\t\n\t\tself.unfreeze_actors()\n\t\n\tdef game_over(self):\n\t\t\n\t\tself.freeze_actors()\n\t\t\n\t\tself.sounds.play_game_over()\n\t\tself.do_popup_game_state_message(\"Game Over\")\n\t\t\n\t\tself.welcome_board.register_final_score(self.player.get_score())\n\t\tself.welcome_board.activate()\n\t\t\n\t\tself.welcome_board.show_high_scores()\n\t\t\n\t\tself.sounds.play_theater_music()\n\t\n\tdef do_popup_game_state_message(self, text):\n\t\t\n\t\t# Spawn a popup in the dead center\n\t\tpopup_x = int(self.screen_rect.width / 2)\n\t\tpopup_y = int(self.screen_rect.height / 2)\n\t\tpopup = self.popups.spawn_popup(text, popup_x, popup_y)\n\t\tpopup.set_spawn_time(self.settings.round_intro_title_spawn_time)\n\t\tpopup.set_hold_time(self.settings.round_intro_title_hold_time)\n\t\t\n\t\twhile self.popups.get_popups_count() > 0:\n\t\t\tself.main_loop_one()\n\t\n\tdef place_player_at_random_pill(self):\n\t\t\n\t\t# Make sure the maze knows about itself\n\t\tself.maze.draw(True)\n\t\t\n\t\tbrick = self.maze.get_random_pill_brick()\n\t\tif not brick:\n\t\t\tbrick = self.maze.get_random_power_pellet_brick()\n\t\tif not brick:\n\t\t\tbrick = self.maze.get_random_blank_brick()\n\t\tif not brick:\n\t\t\treturn\n\t\t\n\t\tself.player.move_to_maze_brick(brick)\n\t\n\tdef place_ghosts_in_pen(self):\n\t\t\n\t\t# Make sure maze knows about itself\n\t\tself.maze.draw(True)\n\t\t\n\t\tfor ghost in self.ghosts:\n\t\t\tself.place_ghost_in_pen(ghost)\n\t\n\tdef place_ghost_in_pen(self, ghost):\n\t\t\n\t\t# Locate a random pen\n\t\tbrick = self.maze.get_random_pen_brick()\n\t\tghost.move_to_maze_brick(brick)\n\t\tghost.set_penned_state(\"in\")\n\t\t\n\tdef increase_level(self):\n\t\t\n\t\t# Increment level\n\t\tself.scoreboard.adjust_level(1)\n\t\tself.settings.adjust_settings_to_level(self.scoreboard.get_level())\n\t\n\tdef get_level(self):\n\t\t\n\t\treturn self.scoreboard.get_level()\n\t\n\tdef initialize_sounds(self):\n\t\t\n\t\tself.sounds = Sounds()\n\t\n\tdef initialize_maze(self):\n\t\t\n\t\t# Use screen width\n\t\tmaze_width = None\n\t\t\n\t\t# Use screen height minus scoreboard height\n\t\tmaze_height = self.screen_rect.height - self.settings.scoreboard_height\n\t\t\n\t\tself.maze = Maze(\n\t\t\tself.settings, self.screen,\n\t\t\tmaze_width, maze_height\n\t\t)\n\t\n\tdef initialize_boards(self):\n\t\t\n\t\t# Welcome Board should only be initialized once\n\t\tif self.welcome_board is None:\n\t\t\tself.welcome_board = WelcomeBoard(\n\t\t\t\tself.settings, self.screen,\n\t\t\t\tNone, None,\n\t\t\t\tself\n\t\t\t)\n\t\t\n\t\t# Scoreboard\n\t\tself.scoreboard = Scoreboard(\n\t\t\tself.settings, self.screen, None, self.settings.scoreboard_height, self\n\t\t)\n\t\tself.scoreboard.set_blit_offset(\n\t\t\tNone,\n\t\t\tself.screen_rect.height - self.settings.scoreboard_height\n\t\t)\n\t\n\tdef initialize_popups(self):\n\t\t\n\t\tself.popups = Popups(\n\t\t\tself.settings, self.screen\n\t\t)\n\t\n\tdef initialize_player(self):\n\t\t\n\t\tself.player = Player(\n\t\t\tself.settings,\n\t\t\tself.maze.bricks_size,\n\t\t\tself, self.maze, self.screen,\n\t\t\tself.scoreboard\n\t\t)\n\t\n\tdef get_player(self):\n\t\t\n\t\treturn self.player\n\t\n\tdef initialize_ghosts(self):\n\t\t\n\t\tself.ghosts = []\n\t\t\n\t\tfor i in range(self.settings.ghost_duplicate_count):\n\t\t\t\n\t\t\tblinky = Blinky(self.settings, self.maze.bricks_size, self, self.maze, self.screen)\n\t\t\tself.ghosts.append(blinky)\n\t\t\t\n\t\t\tpinky = Pinky(self.settings, self.maze.bricks_size, self, self.maze, self.screen)\n\t\t\tself.ghosts.append(pinky)\n\t\t\t\n\t\t\tclyde = Clyde(self.settings, self.maze.bricks_size, self, self.maze, self.screen)\n\t\t\tself.ghosts.append(clyde)\n\t\t\t\n\t\t\tinky = Inky(self.settings, self.maze.bricks_size, self, self.maze, self.screen)\n\t\t\tself.ghosts.append(inky)\n\t\n\tdef initialize_cheater(self):\n\t\t\n\t\tself.cheater = CheatCodes(self.settings.cheat_codes)\n\t\n\tdef update(self, elapsed_ms):\n\t\t\n\t\tself.handle_cheat_codes()\n\t\t\n\t\t# Place this before the update loops,\n\t\t# so the gamestart happens after the board\n\t\t# is deactivated\n\t\tif self.welcome_board.wants_to_start():\n\t\t\tself.welcome_board.deactivate()\n\t\t\tself.start_game()\n\t\t\n\t\t# Update the welcome board?\n\t\tif self.welcome_board.is_activated():\n\t\t\t\n\t\t\tself.welcome_board.update(elapsed_ms)\n\t\t\t\n\t\telse:\n\t\t\t\n\t\t\tself.scoreboard.update(elapsed_ms)\n\t\t\t\n\t\t\tself.maze.clear_debug_rects()\n\t\t\tself.maze.update(elapsed_ms)\n\t\t\t\n\t\t\tself.update_board_actors(elapsed_ms)\n\t\t\n\t\tself.popups.update(elapsed_ms)\n\t\t\n\tdef update_board_actors(self, elapsed_ms):\n\t\t\n\t\tself.maybe_spawn_fruit(elapsed_ms)\n\t\t\n\t\tself.player.update(elapsed_ms)\n\t\t\n\t\tif not self.player.is_dying():\n\t\t\tfor ghost in self.ghosts:\n\t\t\t\tghost.update(elapsed_ms)\n\t\t\n\t\tfor fruit in self.fruits:\n\t\t\t\n\t\t\tfruit.update(elapsed_ms)\n\t\t\t\n\t\t\tif fruit.wants_to_die():\n\t\t\t\tself.fruits.remove(fruit)\n\t\t\n\t\tif self.portal:\n\t\t\tself.portal.update(elapsed_ms)\n\t\n\tdef ghost_ate_player(self, ghost):\n\t\t\n\t\tif self.player.is_dying() or (not self.playing_round):\n\t\t\treturn\n\t\t\n\t\t# HAHA JK STUPID GHOST\n\t\tif ghost.is_scared():\n\t\t\tself.player_ate_ghost(ghost)\n\t\t\treturn\n\t\t\n\t\tself.playing_round = True\n\t\t\n\t\tif self.do_player_death():\n\t\t\tself.continue_round()\n\t\n\tdef player_ate_ghost(self, ghost):\n\t\t\n\t\tpoints = self.settings.ghost_points_base\n\t\tpoints *= math.pow(\n\t\t\tself.settings.ghost_multiple_eaten_multiplier, self.ghosts_eaten_since_last_power_pellet\n\t\t)\n\t\tpoints = round(points)\n\t\t\n\t\tself.player.adjust_score(points)\n\t\tself.spawn_popup_at_actor(ghost, str(points))\n\t\t\n\t\tself.ghosts_eaten_since_last_power_pellet += 1\n\t\t\n\t\tghost.do_die()\n\t\t\n\t\tself.sounds.play_eat_ghost()\n\t\n\tdef player_ate_pill(self):\n\t\t\n\t\tself.sounds.play_eating_pill()\n\t\t\n\t\tself.maze.remember_pills()\n\t\t\n\t\tself.maybe_win_round()\n\t\t\n\tdef player_ate_power_pellet(self, brick, points):\n\t\t\n\t\tself.maze.remember_power_pellets()\n\t\t\n\t\tself.ghosts_eaten_since_last_power_pellet = 0\n\t\tself.scare_all_ghosts()\n\t\t\n\t\tself.spawn_popup_at_brick(brick, str(round(points)))\n\t\t\n\t\tself.sounds.play_eat_power_pellet()\n\t\t\n\t\tself.maybe_win_round()\n\t\n\tdef player_ate_fruit(self, fruit):\n\t\t\n\t\t# Determine points\n\t\tpoints = self.settings.fruit_points_base\n\t\tpoints *= pow(2, self.__fruits_eaten)\n\t\t\n\t\tself.player.adjust_score(points)\n\t\tself.spawn_popup_at_actor(fruit, str(round(points)))\n\t\t\n\t\tself.fruits.remove(fruit)\n\t\tself.__fruits_eaten += 1\n\t\t\n\t\tself.sounds.play_eat_fruit()\n\t\n\tdef player_hit_portal(self):\n\t\n\t\tself.actor_hit_portal(self.player)\n\t\t\n\t\tself.sounds.play_using_portal()\n\t\t\n\t\tself.portal = None\n\t\n\tdef ghost_hit_portal(self, ghost):\n\t\t\n\t\tself.actor_hit_portal(ghost)\n\t\n\tdef actor_hit_portal(self, actor):\n\t\t\n\t\t# Grab a random pill brick, or power pellet\n\t\tbrick = self.maze.get_random_pill_brick()\n\t\tif not brick:\n\t\t\tbrick = self.maze.get_random_power_pellet_brick()\n\t\t\tif not brick:\n\t\t\t\tprint(\"Unable to find any bricks to teleport to\")\n\t\t\t\treturn\n\t\t\n\t\t#\n\t\tactor.move_to_maze_brick(brick)\n\t\n\tdef maybe_win_round(self):\n\t\t\n\t\tpills_count = len(self.maze.bricks_pills)\n\t\tpower_pellets_count = len(self.maze.bricks_power_pellets)\n\t\t\n\t\t# Check for any remaining pills\n\t\tif pills_count > 0:\n\t\t\treturn\n\t\tif power_pellets_count > 0:\n\t\t\treturn\n\t\t\n\t\tself.do_win_round()\n\t\n\tdef do_win_round(self):\n\t\t\n\t\tself.freeze_actors()\n\t\t\n\t\tself.unscare_all_ghosts()\n\t\t\n\t\tself.sounds.stop_ghost_sounds()\n\t\tself.sounds.play_round_win()\n\t\t\n\t\t# Spawn a popup in the dead center\n\t\tpopup_x = int(self.screen_rect.width / 2)\n\t\tpopup_y = int(self.screen_rect.height / 2)\n\t\tpopup = self.popups.spawn_popup(\"Great Job! You Win !!!!\", popup_x, popup_y)\n\t\tpopup.set_spawn_time(self.settings.round_intro_title_spawn_time)\n\t\tpopup.set_hold_time(self.settings.round_intro_title_hold_time)\n\t\t\n\t\twhile self.popups.get_popups_count() > 0:\n\t\t\tself.main_loop_one()\n\t\t\n\t\tself.start_round()\n\t\n\tdef freeze_actors(self):\n\t\n\t\tself.player.set_can_move(False)\n\t\tfor ghost in self.ghosts:\n\t\t\tghost.set_can_move(False)\n\t\n\tdef unfreeze_actors(self):\n\t\t\n\t\tself.player.set_can_move(True)\n\t\tfor ghost in self.ghosts:\n\t\t\tghost.set_can_move(True)\n\t\n\t# Return True if the player has lives left\n\tdef do_player_death(self):\n\t\t\n\t\tself.playing_round = False\n\t\t\n\t\tself.freeze_actors()\n\t\tself.player.do_die()\n\t\t\n\t\tself.sounds.stop_ghost_sounds()\n\t\tself.sounds.play_player_death()\n\t\t\n\t\twhile self.player.is_dying():\n\t\t\t\n\t\t\tself.main_loop_one()\n\t\t\n\t\tself.unfreeze_actors()\n\t\t\n\t\tlives_remaining = self.scoreboard.get_lives_remaining()\n\t\thas_lives_left = lives_remaining > 0\n\t\t\n\t\tif has_lives_left:\n\t\t\t\n\t\t\tself.scoreboard.adjust_lives_remaining(-1)\n\t\t\n\t\telse:\n\t\t\t\n\t\t\tself.game_over()\n\t\t\t\n\t\treturn has_lives_left\n\t\n\tdef scare_all_ghosts(self):\n\t\t\n\t\tfor ghost in self.ghosts:\n\t\t\t\n\t\t\tghost.scare()\n\t\t\n\t\tself.sounds.play_ghost_sounds(True)\n\t\n\tdef unscare_all_ghosts(self):\n\t\t\n\t\tfor ghost in self.ghosts:\n\t\t\t\n\t\t\tghost.stop_being_scared()\n\t\t\n\t\tself.sounds.play_ghost_sounds(False)\n\t\n\tdef ghost_stopped_being_scared(self):\n\t\n\t\tfor ghost in self.ghosts:\n\t\t\tif ghost.is_scared():\n\t\t\t\treturn\n\t\t\n\t\tself.sounds.play_ghost_sounds(False)\n\t\n\tdef spawn_popup_at_actor(self, actor, text):\n\t\n\t\tx, y = actor.get_screen_location()\n\t\t\n\t\toffset_x, offset_y = self.maze.get_blit_offset()\n\t\tx += offset_x\n\t\ty += offset_y\n\t\t\n\t\tself.popups.spawn_popup(text, x, y)\n\t\n\tdef spawn_popup_at_brick(self, brick, text):\n\t\t\n\t\tx, y = brick.get_surface_coords()\n\t\t\n\t\toffset_x, offset_y = self.maze.get_blit_offset()\n\t\tx += offset_x\n\t\ty += offset_y\n\t\t\n\t\tself.popups.spawn_popup(text, x, y)\n\t\n\tdef maybe_spawn_fruit(self, elapsed_ms):\n\t\t\n\t\tif self.__fruits_remaining < 1:\n\t\t\treturn\n\t\t\n\t\t#\n\t\tif len(self.fruits) >= self.settings.fruit_max_concurrency:\n\t\t\treturn\n\t\t\n\t\t#\n\t\tchance = self.settings.fruit_chance_per_ms * elapsed_ms\n\t\tr = random.uniform(0, 1)\n\t\tif r <= chance:\n\t\t\tself.spawn_fruit()\n\t\n\tdef spawn_fruit(self):\n\t\t\n\t\tmax_time = random.gauss(\n\t\t\tself.settings.fruit_max_time_base,\n\t\t\tself.settings.fruit_max_time_std\n\t\t)\n\t\t\n\t\tcenter_x = int(self.screen_rect.width / 2)\n\t\t\n\t\tself.__fruits_remaining -= 1\n\t\t\n\t\tfruit = Fruit(\n\t\t\tself.settings, max_time, \"Fruit\", self.maze.bricks_size,\n\t\t\tself, self.maze, self.screen\n\t\t)\n\t\t\n\t\tbrick = self.maze.get_random_tunnel_brick()\n\t\tfruit.move_to_maze_brick(brick)\n\t\t\n\t\tfruit_x, fruit_y = fruit.get_screen_location()\n\t\t\n\t\t# Start off in the correct direction\n\t\tfruit.clear_movement_input()\n\t\tif fruit_x > center_x:\n\t\t\tfruit.set_movement_input_left()\n\t\telse:\n\t\t\tfruit.set_movement_input_right()\n\t\t\n\t\tself.fruits.append(fruit)\n\t\t\n\t\tself.scoreboard.set_fruit_count(self.__fruits_remaining)\n\t\n\tdef spawn_portal(self):\n\t\n\t\tportal = Portal(\n\t\t\tself.settings,\n\t\t\t\"Portal\", self.maze.bricks_size,\n\t\t\tself, self.maze, self.screen\n\t\t)\n\t\t\n\t\t# Get player's current brick,\n\t\t# and find a wall in the same direction as the player\n\t\t# is moving\n\t\tx = y = 0\n\t\tif self.player.get_movement_input_left() and not self.player.is_impeded_left():\n\t\t\tx = -1\n\t\telif self.player.get_movement_input_right() and not self.player.is_impeded_right():\n\t\t\tx = 1\n\t\telif self.player.get_movement_input_up() and not self.player.is_impeded_up():\n\t\t\ty = -1\n\t\telif self.player.get_movement_input_down() and not self.player.is_impeded_down():\n\t\t\ty = 1\n\t\tbrick_player = self.player.get_closest_brick()\n\t\tbrick_portal_destination = self.maze.get_brick_just_before_first_wall_in_direction(brick_player, x, y)\n\t\tif brick_portal_destination is None:\n\t\t\tprint(\"Unable to launch portal, because we couldn't find a suitable wall !\")\n\t\t\treturn\n\t\t\n\t\t# Spawn the portal at the player's position\n\t\tplayer_x, player_y = self.player.get_screen_location()\n\t\tportal.set_screen_location(player_x, player_y)\n\t\t\n\t\t# Tell the portal where to go\n\t\tbrick_x, brick_y = brick_portal_destination.get_surface_coords()\n\t\tportal.set_destination(brick_x, brick_y)\n\t\t\n\t\tself.sounds.play_creating_portal()\n\t\t\n\t\tself.portal = portal\n\t\n\tdef draw(self):\n\t\t\n\t\t# Fill the screen with black\n\t\tself.screen.fill(self.settings.screen_background_color)\n\t\t\n\t\t# Draw the welcome board?\n\t\tif self.welcome_board.is_activated():\n\t\t\t\n\t\t\tself.welcome_board.blitme()\n\t\t\n\t\telse:\n\t\t\t# Draw maze\n\t\t\tself.maze.blitme()\n\t\t\n\t\t\t# Draw the board_actors\n\t\t\tself.draw_board_actors()\n\t\t\n\t\t\t# Draw the boards\n\t\t\tself.draw_boards()\n\t\t\t\n\t\t# Draw popups\n\t\tself.popups.blitme()\n\t\t\n\t\t# Flip to screen\n\t\tpygame.display.flip()\n\n\tdef draw_board_actors(self):\n\t\t\n\t\tself.player.blitme()\n\t\t\n\t\tfor ghost in self.ghosts:\n\t\t\tghost.blitme()\n\t\t\n\t\tfor fruit in self.fruits:\n\t\t\tfruit.blitme()\n\t\t\n\t\tif self.portal:\n\t\t\tself.portal.blitme()\n\t\n\tdef draw_boards(self):\n\t\t\n\t\tself.scoreboard.blitme()\n\n\n#\nif __name__ == \"__main__\":\n\t\n\tpacman = Pacman()\n\tpacman.run()\n","sub_path":"app/Pacman.py","file_name":"Pacman.py","file_ext":"py","file_size_in_byte":18920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"618634136","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 23 17:18:29 2020\n\n.. note:: Need to keep these groups together, if you split them into files you\n get a circular import.\n\n:copyright: \n Jared Peacock (jpeacock@usgs.gov)\n\n:license: MIT\n\n\"\"\"\n\n# =============================================================================\n# Imports\n# =============================================================================\nimport inspect\nimport weakref\n\nimport h5py\nimport numpy as np\nimport pandas as pd\nimport xarray as xr\n\nfrom mt_metadata import timeseries as metadata\nfrom mt_metadata.utils.mttime import MTime\nfrom mt_metadata.base import Base\nfrom mt_metadata.timeseries.filters import ChannelResponseFilter\n\nfrom mth5 import CHUNK_SIZE, CHANNEL_DTYPE\nfrom mth5.groups.base import BaseGroup\nfrom mth5.groups import FiltersGroup, TransferFunctionGroup\nfrom mth5.utils.exceptions import MTH5Error\nfrom mth5.helpers import (\n to_numpy_type,\n from_numpy_type,\n inherit_doc_string,\n validate_name,\n)\n\nfrom mth5.timeseries import ChannelTS, RunTS\nfrom mth5.timeseries.channel_ts import make_dt_coordinates\nfrom mth5.utils.mth5_logger import setup_logger\n\nmeta_classes = dict(inspect.getmembers(metadata, inspect.isclass))\n# =============================================================================\n# Standards Group\n# =============================================================================\n\n\nclass MasterStationGroup(BaseGroup):\n \"\"\"\n Utility class to holds information about the stations within a survey and\n accompanying metadata. This class is next level down from Survey for\n stations ``/Survey/Stations``. This class provides methods to add and\n get stations. A summary table of all existing stations is also provided\n as a convenience look up table to make searching easier.\n\n To access MasterStationGroup from an open MTH5 file:\n\n >>> from mth5 import mth5\n >>> mth5_obj = mth5.MTH5()\n >>> mth5_obj.open_mth5(r\"/test.mth5\", mode='a')\n >>> stations = mth5_obj.stations_group\n\n To check what stations exist\n\n >>> stations.groups_list\n ['summary', 'MT001', 'MT002', 'MT003']\n\n To access the hdf5 group directly use `SurveyGroup.hdf5_group`.\n\n >>> stations.hdf5_group.ref\n \n\n .. note:: All attributes should be input into the metadata object, that\n way all input will be validated against the metadata standards.\n If you change attributes in metadata object, you should run the\n `SurveyGroup.write_metadata()` method. This is a temporary\n solution, working on an automatic updater if metadata is changed.\n\n >>> stations.metadata.existing_attribute = 'update_existing_attribute'\n >>> stations.write_metadata()\n\n If you want to add a new attribute this should be done using the\n `metadata.add_base_attribute` method.\n\n >>> stations.metadata.add_base_attribute('new_attribute',\n >>> ... 'new_attribute_value',\n >>> ... {'type':str,\n >>> ... 'required':True,\n >>> ... 'style':'free form',\n >>> ... 'description': 'new attribute desc.',\n >>> ... 'units':None,\n >>> ... 'options':[],\n >>> ... 'alias':[],\n >>> ... 'example':'new attribute\n\n To add a station:\n\n >>> new_station = stations.add_station('new_station')\n >>> stations\n /Survey/Stations:\n ====================\n --> Dataset: summary\n ......................\n |- Group: new_station\n ---------------------\n --> Dataset: summary\n ......................\n\n Add a station with metadata:\n\n >>> from mth5.metadata import Station\n >>> station_metadata = Station()\n >>> station_metadata.id = 'MT004'\n >>> station_metadata.time_period.start = '2020-01-01T12:30:00'\n >>> station_metadata.location.latitude = 40.000\n >>> station_metadata.location.longitude = -120.000\n >>> new_station = stations.add_station('Test_01', station_metadata)\n >>> # to look at the metadata\n >>> new_station.metadata\n {\n \"station\": {\n \"acquired_by.author\": null,\n \"acquired_by.comments\": null,\n \"id\": \"MT004\",\n ...\n }\n }\n\n\n .. seealso:: `mth5.metadata` for details on how to add metadata from\n various files and python objects.\n\n To remove a station:\n\n >>> stations.remove_station('new_station')\n >>> stations\n /Survey/Stations:\n ====================\n --> Dataset: summary\n ......................\n\n .. note:: Deleting a station is not as simple as del(station). In HDF5\n this does not free up memory, it simply removes the reference\n to that station. The common way to get around this is to\n copy what you want into a new file, or overwrite the station.\n\n To get a station:\n\n >>> existing_station = stations.get_station('existing_station_name')\n >>> existing_station\n /Survey/Stations/existing_station_name:\n =======================================\n --> Dataset: summary\n ......................\n |- Group: run_01\n ----------------\n --> Dataset: summary\n ......................\n --> Dataset: Ex\n ......................\n --> Dataset: Ey\n ......................\n --> Dataset: Hx\n ......................\n --> Dataset: Hy\n ......................\n --> Dataset: Hz\n ......................\n\n A summary table is provided to make searching easier. The table\n summarized all stations within a survey. To see what names are in the\n summary table:\n\n >>> stations.summary_table.dtype.descr\n [('id', ('|S5', {'h5py_encoding': 'ascii'})),\n ('start', ('|S32', {'h5py_encoding': 'ascii'})),\n ('end', ('|S32', {'h5py_encoding': 'ascii'})),\n ('components', ('|S100', {'h5py_encoding': 'ascii'})),\n ('measurement_type', ('|S12', {'h5py_encoding': 'ascii'})),\n ('sample_rate', '>> stations.summary_table\n index | id | start | end\n | components | measurement_type | sample_rate\n -------------------------------------------------------------------------\n --------------------------------------------------\n 0 | Test_01 | 1980-01-01T00:00:00+00:00 | 1980-01-01T00:00:00+00:00\n | Ex,Ey,Hx,Hy,Hz | BBMT | 100\n\n \"\"\"\n\n def __init__(self, group, **kwargs):\n\n super().__init__(group, **kwargs)\n\n @property\n def channel_summary(self):\n \"\"\"\n Summary of all channels in the file.\n \"\"\"\n ch_list = []\n for station in self.groups_list:\n s_group = StationGroup(self.hdf5_group[station])\n for run in s_group.groups_list:\n r_group = RunGroup(s_group.hdf5_group[run])\n for ch in r_group.groups_list:\n ds_type = r_group.hdf5_group[ch].attrs[\"mth5_type\"]\n if ds_type.lower() in [\"electric\"]:\n ch_dataset = ElectricDataset(r_group.hdf5_group[ch])\n elif ds_type.lower() in [\"magnetic\"]:\n ch_dataset = MagneticDataset(r_group.hdf5_group[ch])\n elif ds_type.lower() in [\"auxiliary\"]:\n ch_dataset = AuxiliaryDataset(r_group.hdf5_group[ch])\n ch_list.append(ch_dataset.channel_entry)\n ch_list = np.array(ch_list)\n return pd.DataFrame(ch_list.flatten())\n\n @property\n def station_summary(self):\n \"\"\"\n Summary of stations in the file\n\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n st_list = []\n for key, group in self.hdf5_group.items():\n entry = {\n \"station\": key,\n \"start\": group.attrs[\"time_period.start\"],\n \"end\": group.attrs[\"time_period.end\"],\n \"latitude\": group.attrs[\"location.latitude\"],\n \"longitude\": group.attrs[\"location.longitude\"],\n }\n st_list.append(entry)\n\n df = pd.DataFrame(st_list)\n df.start = pd.to_datetime(df.start)\n df.end = pd.to_datetime(df.end)\n\n return df\n\n def add_station(self, station_name, station_metadata=None):\n \"\"\"\n Add a station with metadata if given with the path:\n ``/Survey/Stations/station_name``\n\n If the station already exists, will return that station and nothing\n is added.\n\n :param station_name: Name of the station, should be the same as\n metadata.id\n :type station_name: string\n :param station_metadata: Station metadata container, defaults to None\n :type station_metadata: :class:`mth5.metadata.Station`, optional\n :return: A convenience class for the added station\n :rtype: :class:`mth5_groups.StationGroup`\n\n :Example: ::\n\n >>> from mth5 import mth5\n >>> mth5_obj = mth5.MTH5()\n >>> mth5_obj.open_mth5(r\"/test.mth5\", mode='a')\n >>> # one option\n >>> stations = mth5_obj.stations_group\n >>> new_station = stations.add_station('MT001')\n >>> # another option\n >>> new_staiton = mth5_obj.stations_group.add_station('MT001')\n\n .. todo:: allow dictionaries, json string, xml elements as metadata\n input.\n\n \"\"\"\n if station_name is None:\n raise Exception(\n \"station name is None, do not know what to name it\"\n )\n station_name = validate_name(station_name)\n try:\n station_group = self.hdf5_group.create_group(station_name)\n self.logger.debug(\"Created group %s\", station_group.name)\n\n if station_metadata is None:\n station_metadata = metadata.Station(id=station_name)\n else:\n if validate_name(station_metadata.id) != station_name:\n msg = (\n f\"Station group name {station_name} must be same as \"\n + f\"station id {station_metadata.id}\"\n )\n self.logger.error(msg)\n raise MTH5Error(msg)\n station_obj = StationGroup(\n station_group,\n station_metadata=station_metadata,\n **self.dataset_options,\n )\n station_obj.initialize_group()\n\n # be sure to add a table entry\n # self.summary_table.add_row(station_obj.table_entry)\n except ValueError:\n msg = \"Station %s already exists, returning existing group.\"\n self.logger.info(msg, station_name)\n station_obj = self.get_station(station_name)\n return station_obj\n\n def get_station(self, station_name):\n \"\"\"\n Get a station with the same name as station_name\n\n :param station_name: existing station name\n :type station_name: string\n :return: convenience station class\n :rtype: :class:`mth5.mth5_groups.StationGroup`\n :raises MTH5Error: if the station name is not found.\n\n :Example:\n\n >>> from mth5 import mth5\n >>> mth5_obj = mth5.MTH5()\n >>> mth5_obj.open_mth5(r\"/test.mth5\", mode='a')\n >>> # one option\n >>> stations = mth5_obj.stations_group\n >>> existing_station = stations.get_station('MT001')\n >>> # another option\n >>> existing_staiton = mth5_obj.stations_group.get_station('MT001')\n MTH5Error: MT001 does not exist, check station_list for existing names\n\n \"\"\"\n station_name = validate_name(station_name)\n try:\n return StationGroup(\n self.hdf5_group[station_name], **self.dataset_options\n )\n except KeyError:\n msg = (\n f\"{station_name} does not exist, \"\n + \"check station_list for existing names\"\n )\n self.logger.debug(\"Error\" + msg)\n raise MTH5Error(msg)\n\n def remove_station(self, station_name):\n \"\"\"\n Remove a station from the file.\n\n .. note:: Deleting a station is not as simple as del(station). In HDF5\n this does not free up memory, it simply removes the reference\n to that station. The common way to get around this is to\n copy what you want into a new file, or overwrite the station.\n\n :param station_name: existing station name\n :type station_name: string\n\n :Example: ::\n\n >>> from mth5 import mth5\n >>> mth5_obj = mth5.MTH5()\n >>> mth5_obj.open_mth5(r\"/test.mth5\", mode='a')\n >>> # one option\n >>> stations = mth5_obj.stations_group\n >>> stations.remove_station('MT001')\n >>> # another option\n >>> mth5_obj.stations_group.remove_station('MT001')\n\n \"\"\"\n\n station_name = validate_name(station_name)\n try:\n del self.hdf5_group[station_name]\n self.logger.info(\n \"Deleting a station does not reduce the HDF5\"\n + \"file size it simply remove the reference. If \"\n + \"file size reduction is your goal, simply copy\"\n + \" what you want into another file.\"\n )\n except KeyError:\n msg = (\n f\"{station_name} does not exist, \"\n + \"check station_list for existing names\"\n )\n self.logger.debug(\"Error\" + msg)\n raise MTH5Error(msg)\n\n\n# =============================================================================\n# Station Group\n# =============================================================================\nclass StationGroup(BaseGroup):\n \"\"\"\n StationGroup is a utility class to hold information about a single station\n and accompanying metadata. This class is the next level down from\n Stations --> ``/Survey/Stations/station_name``.\n\n This class provides methods to add and get runs. A summary table of all\n existing runs in the station is also provided as a convenience look up\n table to make searching easier.\n\n :param group: HDF5 group for a station, should have a path\n ``/Survey/Stations/station_name``\n :type group: :class:`h5py.Group`\n :param station_metadata: metadata container, defaults to None\n :type station_metadata: :class:`mth5.metadata.Station`, optional\n\n :Usage:\n\n :Access StationGroup from an open MTH5 file:\n\n >>> from mth5 import mth5\n >>> mth5_obj = mth5.MTH5()\n >>> mth5_obj.open_mth5(r\"/test.mth5\", mode='a')\n >>> station = mth5_obj.stations_group.get_station('MT001')\n\n :Check what runs exist:\n\n >>> station.groups_list\n ['MT001a', 'MT001b', 'MT001c', 'MT001d']\n\n To access the hdf5 group directly use `StationGroup.hdf5_group`.\n\n >>> station.hdf5_group.ref\n \n\n .. note:: All attributes should be input into the metadata object, that\n way all input will be validated against the metadata standards.\n If you change attributes in metadata object, you should run the\n `SurveyGroup.write_metadata()` method. This is a temporary\n solution, working on an automatic updater if metadata is changed.\n\n >>> station.metadata.existing_attribute = 'update_existing_attribute'\n >>> station.write_metadata()\n\n If you want to add a new attribute this should be done using the\n `metadata.add_base_attribute` method.\n\n >>> station.metadata.add_base_attribute('new_attribute',\n >>> ... 'new_attribute_value',\n >>> ... {'type':str,\n >>> ... 'required':True,\n >>> ... 'style':'free form',\n >>> ... 'description': 'new attribute desc.',\n >>> ... 'units':None,\n >>> ... 'options':[],\n >>> ... 'alias':[],\n >>> ... 'example':'new attribute\n\n :To add a run:\n\n >>> new_run = stations.add_run('MT001e')\n >>> new_run\n /Survey/Stations/Test_01:\n =========================\n |- Group: MT001e\n -----------------\n --> Dataset: summary\n ......................\n --> Dataset: summary\n ......................\n\n :Add a run with metadata:\n\n >>> from mth5.metadata import Run\n >>> run_metadata = Run()\n >>> run_metadata.time_period.start = '2020-01-01T12:30:00'\n >>> run_metadata.time_period.end = '2020-01-03T16:30:00'\n >>> run_metadata.location.latitude = 40.000\n >>> run_metadata.location.longitude = -120.000\n >>> new_run = runs.add_run('Test_01', run_metadata)\n >>> # to look at the metadata\n >>> new_run.metadata\n {\n \"run\": {\n \"acquired_by.author\": \"new_user\",\n \"acquired_by.comments\": \"First time\",\n \"channels_recorded_auxiliary\": ['T'],\n ...\n }\n }\n\n\n .. seealso:: `mth5.metadata` for details on how to add metadata from\n various files and python objects.\n\n :Remove a run:\n\n >>> station.remove_run('new_run')\n >>> station\n /Survey/Stations/Test_01:\n =========================\n --> Dataset: summary\n ......................\n\n .. note:: Deleting a station is not as simple as del(station). In HDF5\n this does not free up memory, it simply removes the reference\n to that station. The common way to get around this is to\n copy what you want into a new file, or overwrite the station.\n\n :Get a run:\n\n >>> existing_run = stations.get_station('existing_run')\n >>> existing_run\n /Survey/Stations/MT001/MT001a:\n =======================================\n --> Dataset: summary\n ......................\n --> Dataset: Ex\n ......................\n --> Dataset: Ey\n ......................\n --> Dataset: Hx\n ......................\n --> Dataset: Hy\n ......................\n --> Dataset: Hz\n ......................\n\n :summary Table:\n\n A summary table is provided to make searching easier. The table\n summarized all stations within a survey. To see what names are in the\n summary table:\n\n >>> new_run.summary_table.dtype.descr\n [('id', ('|S20', {'h5py_encoding': 'ascii'})),\n ('start', ('|S32', {'h5py_encoding': 'ascii'})),\n ('end', ('|S32', {'h5py_encoding': 'ascii'})),\n ('components', ('|S100', {'h5py_encoding': 'ascii'})),\n ('measurement_type', ('|S12', {'h5py_encoding': 'ascii'})),\n ('sample_rate', '>> station.summary_table\n index | id | start | end | components | measurement_type | sample_rate |\n hdf5_reference\n --------------------------------------------------------------------------\n -------------\n \"\"\"\n\n def __init__(self, group, station_metadata=None, **kwargs):\n super().__init__(group, group_metadata=station_metadata, **kwargs)\n\n self._defaults_summary_keys = [\n \"id\",\n \"start\",\n \"end\",\n \"components\",\n \"measurement_type\",\n \"sample_rate\",\n \"hdf5_reference\",\n \"mth5_type\",\n ]\n\n self._default_subgroup_names = [\n \"Transfer_Functions\",\n ]\n\n def initialize_group(self, **kwargs):\n \"\"\"\n Initialize group by making a summary table and writing metadata\n\n \"\"\"\n for key, value in kwargs.items():\n setattr(self, key, value)\n self.write_metadata()\n\n for group_name in self._default_subgroup_names:\n self.hdf5_group.create_group(f\"{group_name}\")\n m5_grp = getattr(self, f\"{group_name.lower()}_group\")\n m5_grp.initialize_group()\n\n @property\n def master_station_group(self):\n \"\"\"shortcut to master station group\"\"\"\n return MasterStationGroup(self.hdf5_group.parent)\n\n @property\n def transfer_functions_group(self):\n \"\"\"Convinience method for /Station/Transfer_Functions\"\"\"\n return TransferFunctionsGroup(\n self.hdf5_group[\"Transfer_Functions\"], **self.dataset_options\n )\n\n @BaseGroup.metadata.getter\n def metadata(self):\n \"\"\"Overwrite get metadata to include run information in the station\"\"\"\n\n self._metadata.runs = []\n for key in self.groups_list:\n if key.lower() == \"transfer_functions\":\n continue\n try:\n key_group = self.get_run(key)\n self._metadata.runs.append(key_group.metadata)\n except MTH5Error:\n self.logger.warning(f\"Could not find run {key}\")\n return self._metadata\n\n @property\n def name(self):\n return self.metadata.id\n\n @name.setter\n def name(self, name):\n self.metadata.id = name\n\n @property\n def run_summary(self):\n \"\"\"\n Summary of runs in the station\n\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n\n run_list = []\n for key, group in self.hdf5_group.items():\n if group.attrs[\"mth5_type\"].lower() in [\"run\"]:\n comps = \",\".join(\n [\n ii.decode()\n for ii in group.attrs[\n \"channels_recorded_auxiliary\"\n ].tolist()\n + group.attrs[\"channels_recorded_electric\"].tolist()\n + group.attrs[\"channels_recorded_magnetic\"].tolist()\n ]\n )\n run_list.append(\n (\n group.attrs[\"id\"],\n group.attrs[\"time_period.start\"].split(\"+\")[0],\n group.attrs[\"time_period.end\"].split(\"+\")[0],\n comps,\n group.attrs[\"data_type\"],\n group.attrs[\"sample_rate\"],\n self.hdf5_group.ref,\n )\n )\n run_summary = np.array(\n run_list,\n dtype=np.dtype(\n [\n (\"id\", \"U20\"),\n (\"start\", \"datetime64[ns]\"),\n (\"end\", \"datetime64[ns]\"),\n (\"components\", \"U100\"),\n (\"measurement_type\", \"U12\"),\n (\"sample_rate\", float),\n (\"hdf5_reference\", h5py.ref_dtype),\n ]\n ),\n )\n\n return pd.DataFrame(run_summary)\n\n def make_run_name(self, alphabet=False):\n \"\"\"\n Make a run name that will be the next alphabet letter extracted from\n the run list. Expects that all runs are labled as id{a-z}.\n\n :return: metadata.id + next letter\n :rtype: string\n\n >>> station.metadata.id = 'MT001'\n >>> station.make_run_name()\n 'MT001a'\n\n \"\"\"\n\n run_list = sorted(\n [group[-1:] for group in self.groups_list if self.name in group]\n )\n\n next_letter = None\n if len(run_list) == 0:\n if alphabet:\n next_letter = \"a\"\n else:\n next_letter = \"001\"\n else:\n try:\n next_letter = chr(ord(run_list[-1]) + 1)\n except TypeError:\n try:\n next_letter = f\"{int(run_list[-1]) + 1}\"\n except ValueError:\n self.logger.info(\"Could not create a new run name\")\n return next_letter\n\n def locate_run(self, sample_rate, start):\n \"\"\"\n Locate a run based on sample rate and start time from the summary table\n\n :param sample_rate: sample rate in samples/seconds\n :type sample_rate: float\n :param start: start time\n :type start: string or :class:`mth5.utils.mttime.MTime`\n :return: appropriate run name, None if not found\n :rtype: string or None\n\n \"\"\"\n\n if not isinstance(start, MTime):\n start = MTime(start)\n if self.run_summary.size < 1:\n return None\n sr_find = self.run_summary[\n (self.run_summary.sample_rate == sample_rate)\n & (self.run_summary.start == start)\n ]\n if sr_find.size < 1:\n return None\n return sr_find\n\n def add_run(self, run_name, run_metadata=None):\n \"\"\"\n Add a run to a station.\n\n :param run_name: run name, should be id{a-z}\n :type run_name: string\n :param metadata: metadata container, defaults to None\n :type metadata: :class:`mth5.metadata.Station`, optional\n\n need to be able to fill an entry in the summary table.\n\n .. todo:: auto fill run name if none is given.\n\n .. todo:: add ability to add a run with data.\n\n \"\"\"\n\n run_name = validate_name(run_name)\n try:\n run_group = self.hdf5_group.create_group(run_name)\n if run_metadata is None:\n run_metadata = metadata.Run(id=run_name)\n elif validate_name(run_metadata.id) != run_name:\n msg = \"Run name %s must be the same as run_metadata.id %s\"\n self.logger.error(msg, run_name, run_metadata.id)\n raise MTH5Error(msg % (run_name, run_metadata.id))\n run_obj = RunGroup(\n run_group, run_metadata=run_metadata, **self.dataset_options\n )\n run_obj.initialize_group()\n except ValueError:\n msg = \"run %s already exists, returning existing group.\"\n self.logger.info(msg, run_name)\n run_obj = self.get_run(run_name)\n return run_obj\n\n def get_run(self, run_name):\n \"\"\"\n get a run from run name\n\n :param run_name: existing run name\n :type run_name: string\n :return: Run object\n :rtype: :class:`mth5.mth5_groups.RunGroup`\n\n >>> existing_run = station.get_run('MT001')\n\n \"\"\"\n\n run_name = validate_name(run_name)\n try:\n return RunGroup(self.hdf5_group[run_name], **self.dataset_options)\n except KeyError:\n msg = (\n f\"{run_name} does not exist, \"\n + \"check groups_list for existing names\"\n )\n self.logger.debug(\"Error\" + msg)\n raise MTH5Error(msg)\n\n def remove_run(self, run_name):\n \"\"\"\n Remove a run from the station.\n\n .. note:: Deleting a station is not as simple as del(station). In HDF5\n this does not free up memory, it simply removes the reference\n to that station. The common way to get around this is to\n copy what you want into a new file, or overwrite the station.\n\n :param station_name: existing station name\n :type station_name: string\n\n :Example: ::\n\n >>> from mth5 import mth5\n >>> mth5_obj = mth5.MTH5()\n >>> mth5_obj.open_mth5(r\"/test.mth5\", mode='a')\n >>> # one option\n >>> stations = mth5_obj.stations_group\n >>> stations.remove_station('MT001')\n >>> # another option\n >>> mth5_obj.stations_group.remove_station('MT001')\n\n \"\"\"\n\n run_name = validate_name(run_name)\n try:\n del self.hdf5_group[run_name]\n self.logger.info(\n \"Deleting a run does not reduce the HDF5\"\n + \"file size it simply remove the reference. If \"\n + \"file size reduction is your goal, simply copy\"\n + \" what you want into another file.\"\n )\n except KeyError:\n msg = (\n f\"{run_name} does not exist, \"\n + \"check station_list for existing names\"\n )\n self.logger.debug(\"Error\" + msg)\n raise MTH5Error(msg)\n\n def update_station_metadata(self):\n \"\"\"\n Check metadata from the runs and make sure it matches the station metadata\n\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n\n run_summary = self.run_summary.copy()\n self._metadata.time_period.start = run_summary.start.min().isoformat()\n self._metadata.time_period.end = run_summary.end.max().isoformat()\n self._metadata.channels_recorded = list(\n set(\",\".join(run_summary.components.to_list()).split(\",\"))\n )\n\n self.write_metadata()\n\n\n# =============================================================================\n# Transfer Functions Group\n# =============================================================================\nclass TransferFunctionsGroup(BaseGroup):\n \"\"\"\n Object to hold transfer functions\n\n The is the high level group, all transfer functions for the station are\n held here and each one will have its own TransferFunctionGroup.\n\n This has add, get, remove_transfer_function.\n \"\"\"\n\n def __init__(self, group, **kwargs):\n super().__init__(group, **kwargs)\n\n def tf_summary(self, as_dataframe=True):\n \"\"\"\n Summary of all transfer functions in this group\n\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n\n tf_list = []\n for tf_id in self.groups_list:\n tf_group = self.get_transfer_function(tf_id)\n tf_entry = tf_group.tf_entry\n\n tf_entry[\"station_hdf5_reference\"][:] = self.hdf5_group.parent.ref\n tf_entry[\"station\"][:] = self.hdf5_group.parent.attrs[\"id\"]\n tf_entry[\"latitude\"][:] = self.hdf5_group.parent.attrs[\n \"location.latitude\"\n ]\n tf_entry[\"longitude\"][:] = self.hdf5_group.parent.attrs[\n \"location.longitude\"\n ]\n tf_entry[\"elevation\"][:] = self.hdf5_group.parent.attrs[\n \"location.elevation\"\n ]\n\n tf_list.append(tf_entry)\n tf_list = np.array(tf_list)\n\n if as_dataframe:\n return pd.DataFrame(tf_list.flatten())\n return tf_list\n\n def add_transfer_function(self, name, tf_object=None):\n \"\"\"\n Add a transfer function to the group\n\n :param name: name of the transfer function\n :type name: string\n :param tf_object: Transfer Function object\n :type tf_object: :class:`mt_metadata.transfer_function.core.TF`\n :return: DESCRIPTION\n :rtype: TYPE\n\n >>> from mth5.mth5 import MTH5\n >>> m = MTH5()\n >>> m.open_mth5(\"example.h5\", \"a\")\n >>> station_group = m.get_station(\"mt01\", survey=\"test\")\n >>> tf_group = station_group.transfer_functions_group\n >>> tf_group.add_transfer_function(\"mt01_4096\", tf_object)\n\n\n \"\"\"\n name = validate_name(name)\n\n tf_group = TransferFunctionGroup(\n self.hdf5_group.create_group(name), **self.dataset_options\n )\n\n if tf_object is not None:\n tf_group.from_tf_object(tf_object)\n return tf_group\n\n def get_transfer_function(self, tf_id):\n \"\"\"\n Get transfer function from id\n\n :param tf_id: name of transfer function\n :type tf_id: string\n :return: Transfer function group\n :rtype: :class:`mth5.groups.TransferFunctionGroup`\n\n >>> from mth5.mth5 import MTH5\n >>> m = MTH5()\n >>> m.open_mth5(\"example.h5\", \"a\")\n >>> station_group = m.get_station(\"mt01\", survey=\"test\")\n >>> tf_group = station_group.transfer_functions_group.get_transfer_function(\"mt01_4096\")\n\n\n \"\"\"\n\n tf_id = validate_name(tf_id)\n try:\n return TransferFunctionGroup(\n self.hdf5_group[tf_id], **self.dataset_options\n )\n except KeyError:\n msg = (\n f\"{tf_id} does not exist, \"\n + \"check station_list for existing names\"\n )\n self.logger.debug(\"Error\" + msg)\n raise MTH5Error(msg)\n\n def remove_transfer_function(self, tf_id):\n \"\"\"\n Remove a transfer function from the group\n\n :param tf_id: DESCRIPTION\n :type tf_id: TYPE\n :return: DESCRIPTION\n :rtype: TYPE\n\n >>> from mth5.mth5 import MTH5\n >>> m = MTH5()\n >>> m.open_mth5(\"example.h5\", \"a\")\n >>> station_group = m.get_station(\"mt01\", survey=\"test\")\n >>> tf_group = station_group.transfer_functions_group\n >>> tf_group.remove_transfer_function(\"mt01_4096\")\n\n \"\"\"\n\n tf_id = validate_name(tf_id)\n try:\n del self.hdf5_group[tf_id]\n self.logger.info(\n \"Deleting a station does not reduce the HDF5\"\n + \"file size it simply remove the reference. If \"\n + \"file size reduction is your goal, simply copy\"\n + \" what you want into another file.\"\n )\n except KeyError:\n msg = (\n f\"{tf_id} does not exist, \"\n + \"check station_list for existing names\"\n )\n self.logger.debug(\"Error\" + msg)\n raise MTH5Error(msg)\n\n def get_tf_object(self, tf_id):\n \"\"\"\n This is the function you want to use to get a proper\n :class:`mt_metadata.transfer_functions.core.TF` object with all the\n appropriate metadata.\n\n\n :param tf_id: name of the transfer function to get\n :type tf_id: string\n :return: Full transfer function with appropriate metadata\n :rtype: :class:`mt_metadata.transfer_functions.core.TF`\n\n >>> from mth5.mth5 import MTH5\n >>> m = MTH5()\n >>> m.open_mth5(\"example.h5\", \"a\")\n >>> station_group = m.get_station(\"mt01\", survey=\"test\")\n >>> tf_group = station_group.transfer_functions_group\n >>> tf_object = tf_group.get_tf_object(\"mt01_4096\")\n\n\n \"\"\"\n\n tf_group = self.get_transfer_function(tf_id)\n\n return tf_group.to_tf_object()\n\n\n# =============================================================================\n# Run Group\n# =============================================================================\nclass RunGroup(BaseGroup):\n \"\"\"\n RunGroup is a utility class to hold information about a single run\n and accompanying metadata. This class is the next level down from\n Stations --> ``/Survey/Stations/station/station{a-z}``.\n\n This class provides methods to add and get channels. A summary table of\n all existing channels in the run is also provided as a convenience look up\n table to make searching easier.\n\n :param group: HDF5 group for a station, should have a path\n ``/Survey/Stations/station_name/run_name``\n :type group: :class:`h5py.Group`\n :param station_metadata: metadata container, defaults to None\n :type station_metadata: :class:`mth5.metadata.Station`, optional\n\n :Access RunGroup from an open MTH5 file:\n\n >>> from mth5 import mth5\n >>> mth5_obj = mth5.MTH5()\n >>> mth5_obj.open_mth5(r\"/test.mth5\", mode='a')\n >>> run = mth5_obj.stations_group.get_station('MT001').get_run('MT001a')\n\n :Check what channels exist:\n\n >>> station.groups_list\n ['Ex', 'Ey', 'Hx', 'Hy']\n\n To access the hdf5 group directly use `RunGroup.hdf5_group`\n\n >>> station.hdf5_group.ref\n \n\n .. note:: All attributes should be input into the metadata object, that\n way all input will be validated against the metadata standards.\n If you change attributes in metadata object, you should run the\n `SurveyGroup.write_metadata()` method. This is a temporary\n solution, working on an automatic updater if metadata is changed.\n\n >>> run.metadata.existing_attribute = 'update_existing_attribute'\n >>> run.write_metadata()\n\n If you want to add a new attribute this should be done using the\n `metadata.add_base_attribute` method.\n\n >>> station.metadata.add_base_attribute('new_attribute',\n >>> ... 'new_attribute_value',\n >>> ... {'type':str,\n >>> ... 'required':True,\n >>> ... 'style':'free form',\n >>> ... 'description': 'new attribute desc.',\n >>> ... 'units':None,\n >>> ... 'options':[],\n >>> ... 'alias':[],\n >>> ... 'example':'new attribute\n\n :Add a channel:\n\n >>> new_channel = run.add_channel('Ex', 'electric',\n >>> ... data=numpy.random.rand(4096))\n >>> new_run\n /Survey/Stations/MT001/MT001a:\n =======================================\n --> Dataset: summary\n ......................\n --> Dataset: Ex\n ......................\n --> Dataset: Ey\n ......................\n --> Dataset: Hx\n ......................\n --> Dataset: Hy\n ......................\n\n\n :Add a channel with metadata:\n\n >>> from mth5.metadata import Electric\n >>> ex_metadata = Electric()\n >>> ex_metadata.time_period.start = '2020-01-01T12:30:00'\n >>> ex_metadata.time_period.end = '2020-01-03T16:30:00'\n >>> new_ex = run.add_channel('Ex', 'electric',\n >>> ... channel_metadata=ex_metadata)\n >>> # to look at the metadata\n >>> new_ex.metadata\n {\n \"electric\": {\n \"ac.end\": 1.2,\n \"ac.start\": 2.3,\n ...\n }\n }\n\n\n .. seealso:: `mth5.metadata` for details on how to add metadata from\n various files and python objects.\n\n :Remove a channel:\n\n >>> run.remove_channel('Ex')\n >>> station\n /Survey/Stations/MT001/MT001a:\n =======================================\n --> Dataset: summary\n ......................\n --> Dataset: Ey\n ......................\n --> Dataset: Hx\n ......................\n --> Dataset: Hy\n ......................\n\n .. note:: Deleting a station is not as simple as del(station). In HDF5\n this does not free up memory, it simply removes the reference\n to that station. The common way to get around this is to\n copy what you want into a new file, or overwrite the station.\n\n :Get a channel:\n\n >>> existing_ex = stations.get_channel('Ex')\n >>> existing_ex\n Channel Electric:\n -------------------\n data type: Ex\n data type: electric\n data format: float32\n data shape: (4096,)\n start: 1980-01-01T00:00:00+00:00\n end: 1980-01-01T00:32:+08:00\n sample rate: 8\n\n\n :summary Table:\n\n A summary table is provided to make searching easier. The table\n summarized all stations within a survey. To see what names are in the\n summary table:\n\n >>> run.summary_table.dtype.descr\n [('component', ('|S5', {'h5py_encoding': 'ascii'})),\n ('start', ('|S32', {'h5py_encoding': 'ascii'})),\n ('end', ('|S32', {'h5py_encoding': 'ascii'})),\n ('n_samples', '>> new_run.summary_table\n index | component | start | end | n_samples | measurement_type | units |\n hdf5_reference\n --------------------------------------------------------------------------\n -------------\n \"\"\"\n\n def __init__(self, group, run_metadata=None, **kwargs):\n super().__init__(group, group_metadata=run_metadata, **kwargs)\n\n # summary of channels in run\n self._defaults_summary_attrs = {\n \"name\": \"summary\",\n \"max_shape\": (20,),\n \"dtype\": np.dtype(\n [\n (\"component\", \"S20\"),\n (\"start\", \"S32\"),\n (\"end\", \"S32\"),\n (\"n_samples\", int),\n (\"measurement_type\", \"S12\"),\n (\"units\", \"S25\"),\n (\"hdf5_reference\", h5py.ref_dtype),\n ]\n ),\n }\n\n @property\n def station_group(self):\n \"\"\"shortcut to station group\"\"\"\n return StationGroup(self.hdf5_group.parent)\n\n @property\n def station_metadata(self):\n \"\"\"station metadata\"\"\"\n\n meta_dict = dict(self.hdf5_group.parent.attrs)\n for key, value in meta_dict.items():\n meta_dict[key] = from_numpy_type(value)\n station_metadata = metadata.Station()\n station_metadata.from_dict({\"station\": meta_dict})\n return station_metadata\n\n @property\n def master_station_group(self):\n \"\"\"shortcut to master station group\"\"\"\n return MasterStationGroup(self.hdf5_group.parent.parent)\n\n @property\n def survey_metadata(self):\n \"\"\"survey metadata\"\"\"\n\n meta_dict = dict(self.hdf5_group.parent.parent.parent.attrs)\n for key, value in meta_dict.items():\n meta_dict[key] = from_numpy_type(value)\n survey_metadata = metadata.Survey()\n survey_metadata.from_dict({\"survey\": meta_dict})\n return survey_metadata\n\n @BaseGroup.metadata.getter\n def metadata(self):\n \"\"\"Overwrite get metadata to include channel information in the runs\"\"\"\n\n self._metadata.channels = []\n for ch in self.groups_list:\n ch_group = self.get_channel(ch)\n self._metadata.channels.append(ch_group.metadata)\n self._metadata.hdf5_reference = self.hdf5_group.ref\n return self._metadata\n\n @property\n def channel_summary(self):\n \"\"\"\n\n summary of channels in run\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n\n ch_list = []\n for key, group in self.hdf5_group.items():\n try:\n ch_type = group.attrs[\"type\"]\n if ch_type in [\"electric\", \"magnetic\", \"auxiliary\"]:\n ch_list.append(\n (\n group.attrs[\"component\"],\n group.attrs[\"time_period.start\"].split(\"+\")[0],\n group.attrs[\"time_period.end\"].split(\"+\")[0],\n group.size,\n group.attrs[\"sample_rate\"],\n group.attrs[\"type\"],\n group.attrs[\"units\"],\n group.ref,\n )\n )\n except KeyError:\n pass\n ch_summary = np.array(\n ch_list,\n dtype=np.dtype(\n [\n (\"component\", \"U20\"),\n (\"start\", \"datetime64[ns]\"),\n (\"end\", \"datetime64[ns]\"),\n (\"n_samples\", np.int64),\n (\"sample_rate\", np.int64),\n (\"measurement_type\", \"U12\"),\n (\"units\", \"U25\"),\n (\"hdf5_reference\", h5py.ref_dtype),\n ]\n ),\n )\n\n return pd.DataFrame(ch_summary)\n\n def write_metadata(self):\n \"\"\"\n Overwrite Base.write_metadata to include updating table entry\n Write HDF5 metadata from metadata object.\n\n \"\"\"\n\n for key, value in self.metadata.to_dict(single=True).items():\n value = to_numpy_type(value)\n self.hdf5_group.attrs.create(key, value)\n\n def add_channel(\n self,\n channel_name,\n channel_type,\n data,\n channel_dtype=\"int32\",\n max_shape=(None,),\n chunks=True,\n channel_metadata=None,\n **kwargs,\n ):\n \"\"\"\n add a channel to the run\n\n :param channel_name: name of the channel\n :type channel_name: string\n :param channel_type: [ electric | magnetic | auxiliary ]\n :type channel_type: string\n :raises MTH5Error: If channel type is not correct\n\n :param channel_metadata: metadata container, defaults to None\n :type channel_metadata: [ :class:`mth5.metadata.Electric` |\n :class:`mth5.metadata.Magnetic` |\n :class:`mth5.metadata.Auxiliary` ], optional\n :return: Channel container\n :rtype: [ :class:`mth5.mth5_groups.ElectricDatset` |\n :class:`mth5.mth5_groups.MagneticDatset` |\n :class:`mth5.mth5_groups.AuxiliaryDatset` ]\n\n >>> new_channel = run.add_channel('Ex', 'electric', None)\n >>> new_channel\n Channel Electric:\n -------------------\n component: None\n data type: electric\n data format: float32\n data shape: (1,)\n start: 1980-01-01T00:00:00+00:00\n end: 1980-01-01T00:00:00+00:00\n sample rate: None\n\n\n \"\"\"\n channel_name = validate_name(channel_name.lower())\n estimate_size = (1,)\n for key, value in kwargs.items():\n setattr(self, key, value)\n if data is not None:\n if data.size < 1024:\n chunks = None\n try:\n if data is not None:\n channel_group = self.hdf5_group.create_dataset(\n channel_name,\n data=data,\n dtype=data.dtype,\n chunks=chunks,\n maxshape=max_shape,\n **self.dataset_options,\n )\n # initialize an resizable data array\n # need to set the chunk size to something useful, if the chunk\n # size is 1 this causes performance issues and bloating of the\n # hdf5 file. Set to 8196 for now. Should add a parameter for\n # this\n else:\n if channel_metadata is not None:\n # can estimate a size, this will help with allocating\n # and set the chunk size to a realistic value\n if (\n channel_metadata.time_period.start\n != channel_metadata.time_period.end\n ):\n if channel_metadata.sample_rate > 0:\n estimate_size = (\n int(\n (\n channel_metadata.time_period._end_dt\n - channel_metadata.time_period._start_dt\n )\n * channel_metadata.sample_rate\n ),\n )\n else:\n estimate_size = (1,)\n chunks = CHUNK_SIZE\n else:\n estimate_size = (1,)\n chunks = CHUNK_SIZE\n\n if estimate_size[0] > 2**31:\n estimate_size = (1,)\n self.logger.warning(\n \"Estimated size is too large. Check start and end \"\n \"times, initializing with size (1,)\"\n )\n\n channel_group = self.hdf5_group.create_dataset(\n channel_name,\n shape=estimate_size,\n maxshape=max_shape,\n dtype=channel_dtype,\n chunks=chunks,\n **self.dataset_options,\n )\n\n if channel_metadata and channel_metadata.component is None:\n channel_metadata.component = channel_name\n if channel_type.lower() in [\"magnetic\"]:\n channel_obj = MagneticDataset(\n channel_group, dataset_metadata=channel_metadata\n )\n elif channel_type.lower() in [\"electric\"]:\n channel_obj = ElectricDataset(\n channel_group, dataset_metadata=channel_metadata\n )\n elif channel_type.lower() in [\"auxiliary\"]:\n channel_obj = AuxiliaryDataset(\n channel_group, dataset_metadata=channel_metadata\n )\n else:\n msg = (\n \"`channel_type` must be in [ electric | magnetic | \"\n + \"auxiliary ]. Input was {0}\".format(channel_type)\n )\n self.logger.error(msg)\n raise MTH5Error(msg)\n except (OSError, RuntimeError, ValueError):\n msg = f\"channel {channel_name} already exists, returning existing group.\"\n self.logger.debug(msg)\n channel_obj = self.get_channel(channel_name)\n\n if data is not None:\n self.logger.debug(\n \"Replacing data with new shape %s\", data.shape\n )\n channel_obj.replace_dataset(data)\n\n self.logger.debug(\"Updating metadata\")\n channel_obj.metadata.update(channel_metadata)\n channel_obj.write_metadata()\n self.logger.debug(\"Done with %s\", channel_name)\n # need to make sure the channel name is passed.\n if channel_obj.metadata.component is None:\n channel_obj.metadata.component = channel_name\n channel_obj.write_metadata()\n return channel_obj\n\n def get_channel(self, channel_name):\n \"\"\"\n\n Get a channel from an existing name. Returns the appropriate\n container.\n\n :param channel_name: name of the channel\n :type channel_name: string\n :return: Channel container\n :rtype: [ :class:`mth5.mth5_groups.ElectricDatset` |\n :class:`mth5.mth5_groups.MagneticDatset` |\n :class:`mth5.mth5_groups.AuxiliaryDatset` ]\n :raises MTH5Error: If no channel is found\n\n :Example:\n\n >>> existing_channel = run.get_channel('Ex')\n MTH5Error: Ex does not exist, check groups_list for existing names'\n\n >>> run.groups_list\n ['Ey', 'Hx', 'Hz']\n\n >>> existing_channel = run.get_channel('Ey')\n >>> existing_channel\n Channel Electric:\n -------------------\n component: Ey\n data type: electric\n data format: float32\n data shape: (4096,)\n start: 1980-01-01T00:00:00+00:00\n end: 1980-01-01T00:00:01+00:00\n sample rate: 4096\n\n\n \"\"\"\n\n channel_name = validate_name(channel_name.lower())\n try:\n ch_dataset = self.hdf5_group[channel_name]\n except KeyError:\n msg = (\n f\"{channel_name} does not exist, \"\n + \"check groups_list for existing names\"\n )\n self.logger.debug(\"Error\" + msg)\n raise MTH5Error(msg)\n\n if ch_dataset.attrs[\"mth5_type\"].lower() in [\"electric\"]:\n ch_metadata = meta_classes[\"Electric\"]()\n ch_metadata.from_dict({\"Electric\": ch_dataset.attrs})\n channel = ElectricDataset(\n ch_dataset,\n dataset_metadata=ch_metadata,\n write_metadata=False,\n )\n elif ch_dataset.attrs[\"mth5_type\"].lower() in [\"magnetic\"]:\n ch_metadata = meta_classes[\"Magnetic\"]()\n ch_metadata.from_dict({\"Magnetic\": ch_dataset.attrs})\n channel = MagneticDataset(\n ch_dataset,\n dataset_metadata=ch_metadata,\n write_metadata=False,\n )\n elif ch_dataset.attrs[\"mth5_type\"].lower() in [\"auxiliary\"]:\n ch_metadata = meta_classes[\"Auxiliary\"]()\n ch_metadata.from_dict({\"Auxiliary\": ch_dataset.attrs})\n channel = AuxiliaryDataset(\n ch_dataset,\n dataset_metadata=ch_metadata,\n write_metadata=False,\n )\n else:\n channel = ChannelDataset(ch_dataset)\n channel.read_metadata()\n\n return channel\n\n def remove_channel(self, channel_name):\n \"\"\"\n Remove a run from the station.\n\n .. note:: Deleting a channel is not as simple as del(channel). In HDF5\n this does not free up memory, it simply removes the reference\n to that channel. The common way to get around this is to\n copy what you want into a new file, or overwrite the channel.\n\n :param station_name: existing station name\n :type station_name: string\n\n :Example:\n\n >>> from mth5 import mth5\n >>> mth5_obj = mth5.MTH5()\n >>> mth5_obj.open_mth5(r\"/test.mth5\", mode='a')\n >>> run = mth5_obj.stations_group.get_station('MT001').get_run('MT001a')\n >>> run.remove_channel('Ex')\n\n .. todo:: Need to remove summary table entry as well.\n\n \"\"\"\n\n channel_name = validate_name(channel_name.lower())\n\n try:\n del self.hdf5_group[channel_name]\n self.logger.info(\n \"Deleting a channel does not reduce the HDF5\"\n + \"file size it simply remove the reference. If \"\n + \"file size reduction is your goal, simply copy\"\n + \" what you want into another file.\"\n )\n except KeyError:\n msg = (\n f\"{channel_name} does not exist, \"\n + \"check groups_list for existing names\"\n )\n self.logger.debug(\"Error\" + msg)\n raise MTH5Error(msg)\n\n def to_runts(self, start=None, end=None, n_samples=None):\n \"\"\"\n create a :class:`mth5.timeseries.RunTS` object from channels of the\n run\n\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n ch_list = []\n for channel in self.groups_list:\n if channel in [\"summary\"]:\n continue\n ch_obj = self.get_channel(channel)\n\n if start is not None:\n ts_obj = ch_obj.time_slice(start, end=end, n_samples=n_samples)\n else:\n ts_obj = ch_obj.to_channel_ts()\n ch_list.append(ts_obj)\n return RunTS(\n ch_list,\n run_metadata=self.metadata,\n station_metadata=self.station_metadata,\n survey_metadata=self.survey_metadata,\n )\n\n def from_runts(self, run_ts_obj, **kwargs):\n \"\"\"\n create channel datasets from a :class:`mth5.timeseries.RunTS` object\n and update metadata.\n\n :parameter :class:`mth5.timeseries.RunTS` run_ts_obj: Run object with all\n the appropriate channels and metadata.\n\n Will create a run group and appropriate channel datasets.\n \"\"\"\n\n if not isinstance(run_ts_obj, RunTS):\n msg = f\"Input must be a mth5.timeseries.RunTS object not {type(run_ts_obj)}\"\n self.logger.error(msg)\n raise MTH5Error(msg)\n self.metadata.update(run_ts_obj.run_metadata)\n\n channels = []\n\n for comp in run_ts_obj.channels:\n ch = getattr(run_ts_obj, comp)\n\n if ch.station_metadata.id is not None:\n if ch.station_metadata.id != self.station_group.metadata.id:\n if ch.station_metadata.id not in [\"0\", None]:\n self.logger.warning(\n f\"Channel station.id {ch.station_metadata.id} != \"\n + f\" group station.id {self.station_group.metadata.id}\"\n )\n if ch.run_metadata.id is not None:\n if ch.run_metadata.id != self.metadata.id:\n if ch.run_metadata.id not in [\"0\", None]:\n self.logger.warning(\n f\"Channel run.id {ch.run_metadata.id} != \"\n + f\" group run.id {self.metadata.id}\"\n )\n\n channels.append(self.from_channel_ts(ch))\n\n self.update_run_metadata()\n return channels\n\n def from_channel_ts(self, channel_ts_obj):\n \"\"\"\n create a channel data set from a :class:`mth5.timeseries.ChannelTS` object and\n update metadata.\n\n :param channel_ts_obj: a single time series object\n :type channel_ts_obj: :class:`mth5.timeseries.ChannelTS`\n :return: new channel dataset\n :rtype: :class:`mth5.groups.ChannelDataset\n\n \"\"\"\n\n if not isinstance(channel_ts_obj, ChannelTS):\n msg = f\"Input must be a mth5.timeseries.ChannelTS object not {type(channel_ts_obj)}\"\n self.logger.error(msg)\n raise MTH5Error(msg)\n\n ## Need to add in the filters\n if channel_ts_obj.channel_response_filter.filters_list != []:\n from mth5.groups import FiltersGroup\n\n fg = FiltersGroup(self.hdf5_group.parent.parent.parent[\"Filters\"])\n for ff in channel_ts_obj.channel_response_filter.filters_list:\n fg.add_filter(ff)\n\n ch_obj = self.add_channel(\n channel_ts_obj.component,\n channel_ts_obj.channel_metadata.type,\n channel_ts_obj.ts,\n channel_metadata=channel_ts_obj.channel_metadata,\n )\n\n # need to update the channels recorded\n if channel_ts_obj.channel_metadata.type == \"electric\":\n if self.metadata.channels_recorded_electric is None:\n self.metadata.channels_recorded_electric = [\n channel_ts_obj.component\n ]\n elif (\n channel_ts_obj.component\n not in self.metadata.channels_recorded_electric\n ):\n self.metadata.channels_recorded_electric.append(\n channel_ts_obj.component\n )\n elif channel_ts_obj.channel_metadata.type == \"magnetic\":\n if self.metadata.channels_recorded_magnetic is None:\n self.metadata.channels_recorded_magnetic = [\n channel_ts_obj.component\n ]\n elif (\n channel_ts_obj.component\n not in self.metadata.channels_recorded_magnetic\n ):\n self.metadata.channels_recorded_magnetic.append(\n channel_ts_obj.component\n )\n elif channel_ts_obj.channel_metadata.type == \"auxiliary\":\n if self.metadata.channels_recorded_auxiliary is None:\n self.metadata.channels_recorded_auxiliary = [\n channel_ts_obj.component\n ]\n elif (\n channel_ts_obj.component\n not in self.metadata.channels_recorded_auxiliary\n ):\n self.metadata.channels_recorded_auxiliary.append(\n channel_ts_obj.component\n )\n return ch_obj\n\n def update_run_metadata(self):\n \"\"\"\n Update metadata and table entries to ensure consistency\n\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n channel_summary = self.channel_summary.copy()\n\n self._metadata.time_period.start = (\n channel_summary.start.min().isoformat()\n )\n self._metadata.time_period.end = channel_summary.end.max().isoformat()\n self._metadata.sample_rate = channel_summary.sample_rate.unique()[0]\n self.write_metadata()\n\n def plot(self, start=None, end=None, n_samples=None):\n \"\"\"\n Produce a simple matplotlib plot using runts\n \"\"\"\n\n runts = self.to_runts(start=start, end=end, n_samples=n_samples)\n\n runts.plot()\n\n\nclass ChannelDataset:\n \"\"\"\n Holds a channel dataset. This is a simple container for the data to make\n sure that the user has the flexibility to turn the channel into an object\n they want to deal with.\n\n For now all the numpy type slicing can be used on `hdf5_dataset`\n\n :param dataset: dataset object for the channel\n :type dataset: :class:`h5py.Dataset`\n :param dataset_metadata: metadata container, defaults to None\n :type dataset_metadata: [ :class:`mth5.metadata.Electric` |\n :class:`mth5.metadata.Magnetic` |\n :class:`mth5.metadata.Auxiliary` ], optional\n :raises MTH5Error: If the dataset is not of the correct type\n\n Utilities will be written to create some common objects like:\n\n * xarray.DataArray\n * pandas.DataFrame\n * zarr\n * dask.Array\n\n The benefit of these other objects is that they can be indexed by time,\n and they have much more buit-in funcionality.\n\n .. code-block:: python\n\n >>> from mth5 import mth5\n >>> mth5_obj = mth5.MTH5()\n >>> mth5_obj.open_mth5(r\"/test.mth5\", mode='a')\n >>> run = mth5_obj.stations_group.get_station('MT001').get_run('MT001a')\n >>> channel = run.get_channel('Ex')\n >>> channel\n Channel Electric:\n -------------------\n component: Ey\n data type: electric\n data format: float32\n data shape: (4096,)\n start: 1980-01-01T00:00:00+00:00\n end: 1980-01-01T00:00:01+00:00\n sample rate: 4096\n\n \"\"\"\n\n def __init__(\n self, dataset, dataset_metadata=None, write_metadata=True, **kwargs\n ):\n for key, value in kwargs.items():\n setattr(self, key, value)\n if dataset is not None and isinstance(dataset, (h5py.Dataset)):\n self.hdf5_dataset = weakref.ref(dataset)()\n self.logger = setup_logger(f\"{__name__}.{self._class_name}\")\n\n # set metadata to the appropriate class. Standards is not a\n # Base object so should be skipped. If the class name is not\n # defined yet set to Base class.\n self.metadata = Base()\n try:\n self.metadata = meta_classes[self._class_name]()\n except KeyError:\n self.metadata = Base()\n if not hasattr(self.metadata, \"mth5_type\"):\n self._add_base_attributes()\n self.metadata.hdf5_reference = self.hdf5_dataset.ref\n self.metadata.mth5_type = self._class_name\n # if the input data set already has filled attributes, namely if the\n # channel data already exists then read them in with our writing back\n if \"mth5_type\" in list(self.hdf5_dataset.attrs.keys()):\n self.metadata.from_dict(\n {self.hdf5_dataset.attrs[\"mth5_type\"]: self.hdf5_dataset.attrs}\n )\n # if metadata is input, make sure that its the same class type amd write\n # to the hdf5 dataset\n if dataset_metadata is not None:\n if not isinstance(dataset_metadata, type(self.metadata)):\n msg = \"metadata must be type metadata.%s not %s\"\n self.logger.error(\n msg, self._class_name, type(dataset_metadata)\n )\n raise MTH5Error(\n msg % (self._class_name, type(dataset_metadata))\n )\n # load from dict because of the extra attributes for MTH5\n self.metadata.from_dict(dataset_metadata.to_dict())\n self.metadata.hdf5_reference = self.hdf5_dataset.ref\n self.metadata.mth5_type = self._class_name\n\n # write out metadata to make sure that its in the file.\n if write_metadata:\n self.write_metadata()\n # if the attrs don't have the proper metadata keys yet write them\n if not \"mth5_type\" in list(self.hdf5_dataset.attrs.keys()):\n self.write_metadata()\n\n def _add_base_attributes(self):\n # add 2 attributes that will help with querying\n # 1) the metadata class name\n self.metadata.add_base_attribute(\n \"mth5_type\",\n self._class_name,\n {\n \"type\": str,\n \"required\": True,\n \"style\": \"free form\",\n \"description\": \"type of group\",\n \"units\": None,\n \"options\": [],\n \"alias\": [],\n \"example\": \"group_name\",\n \"default\": None,\n },\n )\n\n # 2) the HDF5 reference that can be used instead of paths\n self.metadata.add_base_attribute(\n \"hdf5_reference\",\n self.hdf5_dataset.ref,\n {\n \"type\": \"h5py_reference\",\n \"required\": True,\n \"style\": \"free form\",\n \"description\": \"hdf5 internal reference\",\n \"units\": None,\n \"options\": [],\n \"alias\": [],\n \"example\": \"\",\n \"default\": None,\n },\n )\n\n def __str__(self):\n try:\n lines = [\"Channel {0}:\".format(self._class_name)]\n lines.append(\"-\" * (len(lines[0]) + 2))\n info_str = \"\\t{0:<18}{1}\"\n lines.append(\n info_str.format(\"component:\", self.metadata.component)\n )\n lines.append(info_str.format(\"data type:\", self.metadata.type))\n lines.append(\n info_str.format(\"data format:\", self.hdf5_dataset.dtype)\n )\n lines.append(\n info_str.format(\"data shape:\", self.hdf5_dataset.shape)\n )\n lines.append(\n info_str.format(\"start:\", self.metadata.time_period.start)\n )\n lines.append(\n info_str.format(\"end:\", self.metadata.time_period.end)\n )\n lines.append(\n info_str.format(\"sample rate:\", self.metadata.sample_rate)\n )\n return \"\\n\".join(lines)\n except ValueError:\n return \"MTH5 file is closed and cannot be accessed.\"\n\n def __repr__(self):\n return self.__str__()\n\n @property\n def _class_name(self):\n return self.__class__.__name__.split(\"Dataset\")[0]\n\n @property\n def run_group(self):\n \"\"\"shortcut to run group\"\"\"\n return RunGroup(self.hdf5_dataset.parent)\n\n @property\n def run_metadata(self):\n \"\"\"run metadata\"\"\"\n\n meta_dict = dict(self.hdf5_dataset.parent.attrs)\n for key, value in meta_dict.items():\n meta_dict[key] = from_numpy_type(value)\n run_metadata = metadata.Run()\n run_metadata.from_dict({\"run\": meta_dict})\n return run_metadata\n\n @property\n def station_group(self):\n \"\"\"shortcut to station group\"\"\"\n\n return StationGroup(self.hdf5_dataset.parent.parent)\n\n @property\n def station_metadata(self):\n \"\"\"station metadata\"\"\"\n\n meta_dict = dict(self.hdf5_dataset.parent.parent.attrs)\n for key, value in meta_dict.items():\n meta_dict[key] = from_numpy_type(value)\n station_metadata = metadata.Station()\n station_metadata.from_dict({\"station\": meta_dict})\n return station_metadata\n\n @property\n def master_station_group(self):\n \"\"\"shortcut to master station group\"\"\"\n\n return MasterStationGroup(self.hdf5_dataset.parent.parent.parent)\n\n @property\n def survey_metadata(self):\n \"\"\"survey metadata\"\"\"\n\n meta_dict = dict(self.hdf5_dataset.parent.parent.parent.parent.attrs)\n for key, value in meta_dict.items():\n meta_dict[key] = from_numpy_type(value)\n survey_metadata = metadata.Survey()\n survey_metadata.from_dict({\"survey\": meta_dict})\n return survey_metadata\n\n @property\n def survey_id(self):\n \"\"\"shortcut to survey group\"\"\"\n\n return self.hdf5_dataset.parent.parent.parent.parent.attrs[\"id\"]\n\n @property\n def channel_response_filter(self):\n # get the filters to make a channel response\n filters_group = FiltersGroup(\n self.hdf5_dataset.parent.parent.parent.parent[\"Filters\"]\n )\n f_list = []\n for name in self.metadata.filter.name:\n name = name.replace(\"/\", \" per \").lower()\n try:\n f_list.append(filters_group.to_filter_object(name))\n except KeyError:\n self.logger.warning(\"Could not locate filter %s\", name)\n continue\n return ChannelResponseFilter(filters_list=f_list)\n\n @property\n def start(self):\n return self.metadata.time_period._start_dt\n\n @start.setter\n def start(self, value):\n \"\"\"set start time and validate through metadata validator\"\"\"\n if isinstance(value, MTime):\n self.metadata.time_period.start = value.iso_str\n else:\n self.metadata.time_period.start = value\n\n @property\n def end(self):\n \"\"\"return end time based on the data\"\"\"\n return self.start + (self.n_samples / self.sample_rate)\n\n @property\n def sample_rate(self):\n return self.metadata.sample_rate\n\n @sample_rate.setter\n def sample_rate(self, value):\n \"\"\"set sample rate through metadata validator\"\"\"\n self.metadata.sample_rate = value\n\n @property\n def n_samples(self):\n return self.hdf5_dataset.size\n\n @property\n def time_index(self):\n \"\"\"\n Create a time index based on the metadata. This can help when asking\n for time windows from the data\n\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n\n return make_dt_coordinates(\n self.start, self.sample_rate, self.n_samples, self._logger\n )\n\n def read_metadata(self):\n \"\"\"\n Read metadata from the HDF5 file into the metadata container, that\n way it can be validated.\n\n \"\"\"\n meta_dict = dict(self.hdf5_dataset.attrs)\n for key, value in meta_dict.items():\n meta_dict[key] = from_numpy_type(value)\n self.metadata.from_dict({self._class_name: meta_dict})\n\n def write_metadata(self):\n \"\"\"\n Write metadata from the metadata container to the HDF5 attrs\n dictionary.\n\n \"\"\"\n meta_dict = self.metadata.to_dict()[self.metadata._class_name.lower()]\n for key, value in meta_dict.items():\n value = to_numpy_type(value)\n self.hdf5_dataset.attrs.create(key, value)\n\n def replace_dataset(self, new_data_array):\n \"\"\"\n replace the entire dataset with a new one, nothing left behind\n\n :param new_data_array: new data array shape (npts, )\n :type new_data_array: :class:`numpy.ndarray`\n\n \"\"\"\n if not isinstance(new_data_array, np.ndarray):\n try:\n new_data_array = np.array(new_data_array)\n except (ValueError, TypeError) as error:\n msg = f\"{error} Input must be a numpy array not {type(new_data_array)}\"\n self.logger.exception(msg)\n raise TypeError(msg)\n if new_data_array.shape != self.hdf5_dataset.shape:\n self.hdf5_dataset.resize(new_data_array.shape)\n self.hdf5_dataset[...] = new_data_array\n\n def extend_dataset(\n self,\n new_data_array,\n start_time,\n sample_rate,\n fill=None,\n max_gap_seconds=1,\n fill_window=10,\n ):\n \"\"\"\n Append data according to how the start time aligns with existing\n data. If the start time is before existing start time the data is\n prepended, similarly if the start time is near the end data will be\n appended.\n\n If the start time is within the existing time range, existing data\n will be replace with the new data.\n\n If there is a gap between start or end time of the new data with\n the existing data you can either fill the data with a constant value\n or an error will be raise depending on the value of fill.\n\n :param new_data_array: new data array with shape (npts, )\n :type new_data_array: :class:`numpy.ndarray`\n :param start_time: start time of the new data array in UTC\n :type start_time: string or :class:`mth5.utils.mttime.MTime`\n :param sample_rate: Sample rate of the new data array, must match\n existing sample rate\n :type sample_rate: float\n :param fill: If there is a data gap how do you want to fill the gap\n * None: will raise an :class:`mth5.utils.exceptions.MTH5Error`\n * 'mean': will fill with the mean of each data set within\n the fill window\n * 'median': will fill with the median of each data set\n within the fill window\n * value: can be an integer or float to fill the gap\n * 'nan': will fill the gap with NaN\n :type fill: string, None, float, integer\n :param max_gap_seconds: sets a maximum number of seconds the gap can\n be. Anything over this number will raise\n a :class:`mth5.utils.exceptions.MTH5Error`.\n :type max_gap_seconds: float or integer\n :param fill_window: number of points from the end of each data set\n to estimate fill value from.\n :type fill_window: integer\n\n :raises: :class:`mth5.utils.excptions.MTH5Error` if sample rate is\n not the same, or fill value is not understood,\n\n :Append Example:\n\n >>> ex = mth5_obj.get_channel('MT001', 'MT001a', 'Ex')\n >>> ex.n_samples\n 4096\n >>> ex.end\n 2015-01-08T19:32:09.500000+00:00\n >>> t = timeseries.ChannelTS('electric',\n ... data=2*np.cos(4 * np.pi * .05 * \\\n ... np.linspace(0,4096l num=4096) *\n ... .01),\n ... channel_metadata={'electric':{\n ... 'component': 'ex',\n ... 'sample_rate': 8,\n ... 'time_period.start':(ex.end+(1)).iso_str}})\n >>> ex.extend_dataset(t.ts, t.start, t.sample_rate, fill='median',\n ... max_gap_seconds=2)\n 2020-07-02T18:02:47 - mth5.groups.Electric.extend_dataset - INFO -\n filling data gap with 1.0385180759767025\n >>> ex.n_samples\n 8200\n >>> ex.end\n 2015-01-08T19:40:42.500000+00:00\n\n \"\"\"\n fw = fill_window\n # check input parameters\n if sample_rate != self.sample_rate:\n msg = (\n \"new data must have the same sampling rate as existing data.\\n\"\n + f\"\\tnew sample rate = {sample_rate}\\n\"\n + f\"\\texisting sample rate = {self.sample_rate}\"\n )\n self.logger.error(msg)\n raise MTH5Error(msg)\n if not isinstance(new_data_array, np.ndarray):\n try:\n new_data_array = np.array(new_data_array)\n except (ValueError, TypeError) as error:\n msg = f\"{error} Input must be a numpy array not {type(new_data_array)}\"\n self.logger.exception(msg)\n raise TypeError(msg)\n if not isinstance(start_time, MTime):\n start_time = MTime(start_time)\n # get end time will need later\n end_time = start_time + (new_data_array.size / sample_rate)\n\n # check start time\n start_t_diff = self._get_diff_new_array_start(start_time)\n end_t_diff = self._get_diff_new_array_end(end_time)\n\n self.logger.info(\"Extending data.\")\n self.logger.info(f\"Existing start time {self.start}\")\n self.logger.info(f\"New start time {start_time}\")\n self.logger.info(f\"Existing end time {self.end}\")\n self.logger.info(f\"New end time {end_time}\")\n\n # prepend data\n if start_t_diff < 0:\n self.logger.info(\"Prepending: \")\n self.logger.info(\n f\"new start time {start_time} is before existing {self.start}\"\n )\n if end_time.iso_no_tz not in self.time_index:\n gap = abs(end_time - self.start)\n if gap > 0:\n if gap > max_gap_seconds:\n msg = (\n f\"Time gap of {gap} seconds \"\n + f\"is more than max_gap_seconds = {max_gap_seconds}.\"\n + \" Consider making a new run.\"\n )\n self.logger.error(msg)\n raise MTH5Error(msg)\n if fill is None:\n msg = (\n f\"A time gap of {gap} seconds is found \"\n + \"between new and existing data sets. \\n\"\n + f\"\\tnew end time: {end_time}\\n\"\n + f\"\\texisting start time: {self.start}\"\n )\n self.logger.error(msg)\n raise MTH5Error(msg)\n # set new start time\n old_slice = self.time_slice(self.start, end_time=self.end)\n old_start = self.start.copy()\n self.start = start_time\n\n # resize the existing data to make room for new data\n self.hdf5_dataset.resize(\n (\n int(\n new_data_array.size\n + self.hdf5_dataset.size\n + gap * sample_rate\n ),\n )\n )\n\n # fill based on time, refill existing data first\n self.hdf5_dataset[\n self.get_index_from_time(old_start) :\n ] = old_slice.ts.values\n self.hdf5_dataset[\n 0 : self.get_index_from_time(end_time)\n ] = new_data_array\n\n if fill == \"mean\":\n fill_value = np.mean(\n np.array(\n [\n new_data_array[-fw:].mean(),\n float(old_slice.ts[0:fw].mean()),\n ]\n )\n )\n elif fill == \"median\":\n fill_value = np.median(\n np.array(\n [\n np.median(new_data_array[-fw:]),\n np.median(old_slice.ts[0:fw]),\n ]\n )\n )\n elif fill == \"nan\":\n fill_value = np.nan\n elif isinstance(fill, (int, float)):\n fill_value = fill\n else:\n msg = f\"fill value {fill} is not understood\"\n self.logger.error(msg)\n raise MTH5Error(msg)\n self.logger.info(f\"filling data gap with {fill_value}\")\n self.hdf5_dataset[\n self.get_index_from_time(\n end_time\n ) : self.get_index_from_time(old_start)\n ] = fill_value\n else:\n new_size = (\n self.n_samples + int(abs(start_t_diff) * sample_rate),\n )\n overlap = abs(end_time - self.start)\n self.logger.warning(\n f\"New data is overlapping by {overlap} s.\"\n + \" Any overlap will be overwritten.\"\n )\n # set new start time\n old_slice = self.time_slice(self.start, end_time=self.end)\n old_start = self.start.copy()\n self.start = start_time\n self.logger.debug(\n f\"resizing data set from {self.n_samples} to {new_size}\"\n )\n self.hdf5_dataset.resize(new_size)\n\n # put back the existing data, which any overlapping times\n # will be overwritten\n self.hdf5_dataset[\n self.get_index_from_time(old_start) :\n ] = old_slice.ts.values\n self.hdf5_dataset[\n 0 : self.get_index_from_time(end_time)\n ] = new_data_array\n # append data\n elif start_t_diff > 0:\n old_end = self.end.copy()\n if start_time.iso_no_tz not in self.time_index:\n gap = abs(self.end - start_time)\n if gap > 0:\n if gap > max_gap_seconds:\n msg = (\n f\"Time gap of {gap} seconds \"\n + f\"is more than max_gap_seconds = {max_gap_seconds}.\"\n + \" Consider making a new run.\"\n )\n self.logger.error(msg)\n raise MTH5Error(msg)\n if fill is None:\n msg = (\n f\"A time gap of {gap} seconds is found \"\n + \"between new and existing data sets. \\n\"\n + f\"\\tnew start time: {start_time}\\n\"\n + f\"\\texisting end time: {self.end}\"\n )\n self.logger.error(msg)\n raise MTH5Error(msg)\n # resize the existing data to make room for new data\n self.hdf5_dataset.resize(\n (\n int(\n new_data_array.size\n + self.hdf5_dataset.size\n + gap * sample_rate\n ),\n )\n )\n\n self.hdf5_dataset[\n self.get_index_from_time(start_time) :\n ] = new_data_array\n old_index = self.get_index_from_time(old_end)\n if fill == \"mean\":\n fill_value = np.mean(\n np.array(\n [\n new_data_array[0:fw].mean(),\n np.mean(\n self.hdf5_dataset[old_index - fw :]\n ),\n ]\n )\n )\n elif fill == \"median\":\n fill_value = np.median(\n np.array(\n [\n np.median(new_data_array[0:fw]),\n np.median(\n self.hdf5_dataset[old_index - fw :]\n ),\n ]\n )\n )\n elif fill == \"nan\":\n fill_value = np.nan\n elif isinstance(fill, (int, float)):\n fill_value = fill\n else:\n msg = f\"fill value {fill} is not understood\"\n self.logger.error(msg)\n raise MTH5Error(msg)\n self.logger.info(f\"filling data gap with {fill_value}\")\n self.hdf5_dataset[\n self.get_index_from_time(\n old_end\n ) : self.get_index_from_time(start_time)\n ] = fill_value\n else:\n # if the new data fits within the extisting time span\n if end_t_diff < 0:\n self.logger.debug(\n \"New data fits within existing time span\"\n + \" all data in the window : \"\n f\"{start_time} -- {end_time} \" + \"will be overwritten.\"\n )\n self.hdf5_dataset[\n self.get_index_from_time(\n start_time\n ) : self.get_index_from_time(end_time)\n ] = new_data_array\n else:\n new_size = (\n self.n_samples + int(abs(start_t_diff) * sample_rate),\n )\n overlap = abs(self.end - start_time)\n self.logger.warning(\n f\"New data is overlapping by {overlap} s.\"\n + \" Any overlap will be overwritten.\"\n )\n\n self.logger.debug(\n f\"resizing data set from {self.n_samples} to {new_size}\"\n )\n self.hdf5_dataset.resize(new_size)\n\n # put back the existing data, which any overlapping times\n # will be overwritten\n self.hdf5_dataset[\n self.get_index_from_time(start_time) :\n ] = new_data_array\n\n def to_channel_ts(self):\n \"\"\"\n :return: a Timeseries with the appropriate time index and metadata\n :rtype: :class:`mth5.timeseries.ChannelTS`\n\n loads from memory (nearly half the size of xarray alone, not sure why)\n\n \"\"\"\n return ChannelTS(\n channel_type=self.metadata.type,\n data=self.hdf5_dataset[()],\n channel_metadata=self.metadata,\n run_metadata=self.run_metadata.copy(),\n station_metadata=self.station_metadata.copy(),\n survey_metadata=self.survey_metadata.copy(),\n channel_response_filter=self.channel_response_filter,\n )\n\n def to_xarray(self):\n \"\"\"\n :return: an xarray DataArray with appropriate metadata and the\n appropriate time index.\n :rtype: :class:`xarray.DataArray`\n\n .. note:: that metadta will not be validated if changed in an xarray.\n\n loads from memory\n \"\"\"\n\n return xr.DataArray(\n self.hdf5_dataset[()],\n coords=[(\"time\", self.time_index)],\n attrs=self.metadata.to_dict(single=True),\n )\n\n def to_dataframe(self):\n \"\"\"\n\n :return: a dataframe where data is stored in the 'data' column and\n attributes are stored in the experimental attrs attribute\n :rtype: :class:`pandas.DataFrame`\n\n .. note:: that metadta will not be validated if changed in an xarray.\n\n loads into RAM\n \"\"\"\n\n df = pd.DataFrame(\n {\"data\": self.hdf5_dataset[()]}, index=self.time_index\n )\n df.attrs.update(self.metadata.to_dict(single=True))\n\n return df\n\n def to_numpy(self):\n \"\"\"\n :return: a numpy structured array with 2 columns (time, channel_data)\n :rtype: :class:`numpy.core.records`\n\n .. note:: data is a builtin to numpy and cannot be used as a name\n\n loads into RAM\n\n \"\"\"\n\n return np.core.records.fromarrays(\n [self.time_index.to_numpy(), self.hdf5_dataset[()]],\n names=\"time,channel_data\",\n )\n\n def from_channel_ts(\n self,\n channel_ts_obj,\n how=\"replace\",\n fill=None,\n max_gap_seconds=1,\n fill_window=10,\n ):\n \"\"\"\n fill data set from a :class:`mth5.timeseries.ChannelTS` object.\n\n Will check for time alignement, and metadata.\n\n :param channel_ts_obj: time series object\n :type channel_ts_obj: :class:`mth5.timeseries.ChannelTS`\n :param how: how the new array will be input to the existing dataset:\n\n - 'replace' -> replace the entire dataset nothing is left over.\n - 'extend' -> add onto the existing dataset, any overlapping\n values will be rewritten, if there are gaps between data sets\n those will be handled depending on the value of fill.\n\n :param fill: If there is a data gap how do you want to fill the gap:\n\n - None -> will raise an :class:`mth5.utils.exceptions.MTH5Error`\n - 'mean'-> will fill with the mean of each data set within\n the fill window\n - 'median' -> will fill with the median of each data set\n within the fill window\n - value -> can be an integer or float to fill the gap\n - 'nan' -> will fill the gap with NaN\n\n :type fill: string, None, float, integer\n :param max_gap_seconds: sets a maximum number of seconds the gap can\n be. Anything over this number will raise\n a :class:`mth5.utils.exceptions.MTH5Error`.\n\n :type max_gap_seconds: float or integer\n :param fill_window: number of points from the end of each data set\n to estimate fill value from.\n\n :type fill_window: integer\n\n \"\"\"\n\n if not isinstance(channel_ts_obj, ChannelTS):\n msg = (\n f\"Input must be a ChannelTS object not {type(channel_ts_obj)}\"\n )\n self.logger.error(msg)\n raise TypeError(msg)\n if how == \"replace\":\n self.metadata.from_dict(channel_ts_obj.channel_metadata.to_dict())\n self.replace_dataset(channel_ts_obj.ts)\n # apparently need to reset these otherwise they get overwritten with None\n self.metadata.hdf5_reference = self.hdf5_dataset.ref\n self.metadata.mth5_type = self._class_name\n self.write_metadata()\n elif how == \"extend\":\n self.extend_dataset(\n channel_ts_obj.ts,\n channel_ts_obj.start,\n channel_ts_obj.sample_rate,\n fill=fill,\n )\n #\n # TODO need to check on metadata.\n\n def from_xarray(\n self,\n data_array,\n how=\"replace\",\n fill=None,\n max_gap_seconds=1,\n fill_window=10,\n ):\n \"\"\"\n fill data set from a :class:`xarray.DataArray` object.\n\n Will check for time alignement, and metadata.\n\n :param data_array_obj: Xarray data array\n :type channel_ts_obj: :class:`xarray.DataArray`\n :param how: how the new array will be input to the existing dataset:\n\n - 'replace' -> replace the entire dataset nothing is left over.\n - 'extend' -> add onto the existing dataset, any overlapping\n values will be rewritten, if there are gaps between data sets\n those will be handled depending on the value of fill.\n\n :param fill: If there is a data gap how do you want to fill the gap:\n\n - None -> will raise an :class:`mth5.utils.exceptions.MTH5Error`\n - 'mean'-> will fill with the mean of each data set within\n the fill window\n - 'median' -> will fill with the median of each data set\n within the fill window\n - value -> can be an integer or float to fill the gap\n - 'nan' -> will fill the gap with NaN\n\n :type fill: string, None, float, integer\n :param max_gap_seconds: sets a maximum number of seconds the gap can\n be. Anything over this number will raise a\n :class:`mth5.utils.exceptions.MTH5Error`.\n\n :type max_gap_seconds: float or integer\n :param fill_window: number of points from the end of each data set\n to estimate fill value from.\n\n :type fill_window: integer\n\n \"\"\"\n\n if not isinstance(data_array, xr.DataArray):\n msg = f\"Input must be a xarray.DataArray object not {type(data_array)}\"\n self.logger.error(msg)\n raise TypeError(msg)\n if how == \"replace\":\n self.metadata.from_dict(\n {self.metadata._class_name: data_array.attrs}\n )\n self.replace_dataset(data_array.values)\n self.write_metadata()\n elif how == \"extend\":\n self.extend_dataset(\n data_array.values,\n data_array.coords.indexes[\"time\"][0].isoformat(),\n 1e9 / data_array.coords.indexes[\"time\"][0].freq.nanos,\n fill=fill,\n )\n # TODO need to check on metadata.\n\n def _get_diff_new_array_start(self, start_time):\n \"\"\"\n Make sure the new array has the same start time if not return the\n time difference\n\n :param start_time: start time of the new array\n :type start_time: string, int or :class:`mth5.utils.MTime`\n :return: time difference in seconds as new start time minus old.\n\n * A positive number means new start time is later than old\n start time.\n * A negative number means the new start time is earlier than\n the old start time.\n\n :rtype: float\n\n \"\"\"\n if not isinstance(start_time, MTime):\n start_time = MTime(start_time)\n t_diff = 0\n if start_time != self.start:\n t_diff = start_time - self.start\n return t_diff\n\n def _get_diff_new_array_end(self, end_time):\n \"\"\"\n Make sure the new array has the same end time if not return the\n time difference\n\n :param end_time: end time of the new array\n :type end_time: string, int or :class:`mth5.utils.MTime`\n :return: time difference in seconds as new end time minus old.\n\n * A positive number means new end time is later than old\n end time.\n * A negative number means the new end time is earlier than\n the old end time.\n\n :rtype: float\n\n \"\"\"\n if not isinstance(end_time, MTime):\n end_time = MTime(end_time)\n t_diff = 0\n if end_time != self.end:\n t_diff = end_time - self.end\n return t_diff\n\n @property\n def table_entry(self):\n \"\"\"\n Creat a table entry to put into the run summary table.\n\n \"\"\"\n\n return np.array(\n [\n (\n self.metadata.component,\n self.metadata.time_period._start_dt.iso_no_tz,\n self.metadata.time_period._end_dt.iso_no_tz,\n self.hdf5_dataset.size,\n self.metadata.type,\n self.metadata.units,\n self.hdf5_dataset.ref,\n )\n ],\n dtype=np.dtype(\n [\n (\"component\", \"U20\"),\n (\"start\", \"datetime64[ns]\"),\n (\"end\", \"datetime64[ns]\"),\n (\"n_samples\", int),\n (\"measurement_type\", \"U12\"),\n (\"units\", \"U25\"),\n (\"hdf5_reference\", h5py.ref_dtype),\n ]\n ),\n )\n\n @property\n def channel_entry(self):\n \"\"\"\n channel entry that will go into a full channel summary of the entire survey\n\n \"\"\"\n return np.array(\n [\n (\n self.survey_id,\n self.hdf5_dataset.parent.parent.attrs[\"id\"],\n self.hdf5_dataset.parent.attrs[\"id\"],\n self.hdf5_dataset.parent.parent.attrs[\"location.latitude\"],\n self.hdf5_dataset.parent.parent.attrs[\n \"location.longitude\"\n ],\n self.hdf5_dataset.parent.parent.attrs[\n \"location.elevation\"\n ],\n self.metadata.component,\n self.metadata.time_period.start,\n self.metadata.time_period.end,\n self.hdf5_dataset.size,\n self.metadata.sample_rate,\n self.metadata.type,\n self.metadata.measurement_azimuth,\n self.metadata.measurement_tilt,\n self.metadata.units,\n self.hdf5_dataset.ref,\n self.hdf5_dataset.parent.ref,\n self.hdf5_dataset.parent.parent.ref,\n )\n ],\n dtype=CHANNEL_DTYPE,\n )\n\n def time_slice(\n self,\n start,\n end=None,\n n_samples=None,\n return_type=\"channel_ts\",\n ):\n \"\"\"\n Get a time slice from the channel and return the appropriate type\n\n * numpy array with metadata\n * pandas.Dataframe with metadata\n * xarray.DataFrame with metadata\n * :class:`mth5.timeseries.ChannelTS` 'default'\n * dask.DataFrame with metadata 'not yet'\n\n :param start: start time of the slice\n :type start: string or :class:`mth5.utils.mttime.MTime`\n :param end: end time of the slice\n :type end: string or :class:`mth5.utils.mttime.MTime`, optional\n :param n_samples: number of samples to read in\n :type n_samples: integer, optional\n :return: the correct container for the time series.\n :rtype: [ :class:`xarray.DataArray` | :class:`pandas.DataFrame` |\n :class:`mth5.timeseries.ChannelTS` | :class:`numpy.ndarray` ]\n :raises: ValueError if both end_time and n_samples are None or given.\n\n :Example with number of samples:\n\n .. code-block::\n\n >>> ex = mth5_obj.get_channel('FL001', 'FL001a', 'Ex')\n >>> ex_slice = ex.time_slice(\"2015-01-08T19:49:15\", n_samples=4096)\n >>> ex_slice\n \n array([0.93115046, 0.14233688, 0.87917119, ..., 0.26073634, 0.7137319 ,\n 0.88154395])\n Coordinates:\n * time (time) datetime64[ns] 2015-01-08T19:49:15 ... 2015-01-08T19:57:46.875000\n Attributes:\n ac.end: None\n ac.start: None\n ...\n\n >>> type(ex_slice)\n mth5.timeseries.ChannelTS\n\n # plot the time series\n >>> ex_slice.ts.plot()\n\n :Example with start and end time:\n\n >>> ex_slice = ex.time_slice(\"2015-01-08T19:49:15\",\n ... end_time=\"2015-01-09T19:49:15\")\n\n :Raises Example:\n\n >>> ex_slice = ex.time_slice(\"2015-01-08T19:49:15\",\n ... end_time=\"2015-01-09T19:49:15\",\n ... n_samples=4096)\n ValueError: Must input either end_time or n_samples, not both.\n\n \"\"\"\n\n if not isinstance(start, MTime):\n start = MTime(start)\n if end is not None:\n if not isinstance(end, MTime):\n end = MTime(end)\n if n_samples is not None:\n n_samples = int(n_samples)\n if n_samples is None and end is None:\n msg = \"Must input either end_time or n_samples.\"\n self.logger.error(msg)\n raise ValueError(msg)\n if n_samples is not None and end is not None:\n msg = \"Must input either end_time or n_samples, not both.\"\n self.logger.error(msg)\n raise ValueError(msg)\n # if end time is given\n if end is not None and n_samples is None:\n start_index = self.get_index_from_time(start)\n end_index = self.get_index_from_time(end)\n npts = int(end_index - start_index)\n # if n_samples are given\n elif end is None and n_samples is not None:\n start_index = self.get_index_from_time(start)\n end_index = start_index + (n_samples - 1)\n npts = n_samples\n if npts > self.hdf5_dataset.size or end_index > self.hdf5_dataset.size:\n msg = (\n \"Requested slice is larger than data. \"\n f\"Slice length = {npts}, data length = {self.hdf5_dataset.shape}. \"\n f\"Setting end_index to {self.hdf5_dataset.shape}\"\n )\n end_index = self.hdf5_dataset.size - 1\n self.logger.warning(msg)\n # create a regional reference that can be used, need +1 to be inclusive\n try:\n regional_ref = self.hdf5_dataset.regionref[\n start_index : end_index + 1\n ]\n except (OSError, RuntimeError):\n self.logger.debug(\n \"file is in read mode cannot set an internal reference, using index values\"\n )\n regional_ref = slice(start_index, end_index)\n dt_index = make_dt_coordinates(\n start, self.sample_rate, npts, self.logger\n )\n\n meta_dict = self.metadata.to_dict()[self.metadata._class_name]\n meta_dict[\"time_period.start\"] = dt_index[0].isoformat()\n meta_dict[\"time_period.end\"] = dt_index[-1].isoformat()\n\n data = None\n if return_type == \"xarray\":\n # need the +1 to be inclusive of the last point\n data = xr.DataArray(\n self.hdf5_dataset[regional_ref], coords=[(\"time\", dt_index)]\n )\n data.attrs.update(meta_dict)\n elif return_type == \"pandas\":\n data = pd.DataFrame(\n {\"data\": self.hdf5_dataset[regional_ref]}, index=dt_index\n )\n data.attrs.update(meta_dict)\n elif return_type == \"numpy\":\n data = self.hdf5_dataset[regional_ref]\n elif return_type == \"channel_ts\":\n data = ChannelTS(\n self.metadata.type,\n data=self.hdf5_dataset[regional_ref],\n channel_metadata={self.metadata.type: meta_dict},\n channel_response_filter=self.channel_response_filter,\n )\n else:\n msg = \"return_type not understood, must be [ pandas | numpy | channel_ts ]\"\n self.logger.error(msg)\n raise ValueError(msg)\n return data\n\n def get_index_from_time(self, given_time):\n \"\"\"\n get the appropriate index for a given time.\n\n :param given_time: time string\n :type given_time: string or MTime\n :return: index value\n :rtype: int\n\n \"\"\"\n\n if not isinstance(given_time, MTime):\n given_time = MTime(given_time)\n index = (\n given_time - self.metadata.time_period.start\n ) * self.metadata.sample_rate\n\n return int(round(index))\n\n\n@inherit_doc_string\nclass ElectricDataset(ChannelDataset):\n def __init__(self, group, **kwargs):\n\n super().__init__(group, **kwargs)\n\n\n@inherit_doc_string\nclass MagneticDataset(ChannelDataset):\n def __init__(self, group, **kwargs):\n\n super().__init__(group, **kwargs)\n\n\n@inherit_doc_string\nclass AuxiliaryDataset(ChannelDataset):\n def __init__(self, group, **kwargs):\n super().__init__(group, **kwargs)\n","sub_path":"mth5/groups/master_station_run_channel.py","file_name":"master_station_run_channel.py","file_ext":"py","file_size_in_byte":104435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"306885449","text":"from securitybot import loader\n\n\ndef main():\n config = loader.load_yaml('config/bot.yaml')\n\n db_provider = config['database']['provider']\n tablelist = config['database']['tables']\n\n # Load our secrets\n secrets_provider = config['secretsmgmt']['provider']\n\n secretsclient = loader.build_secrets_client(\n secrets_provider=secrets_provider,\n connection_config=config['secretsmgmt'][secrets_provider]\n )\n try:\n loader.add_secrets_to_config(\n smclient=secretsclient,\n secrets=config['secretsmgmt']['secrets'],\n config=config\n )\n except Exception as error:\n print('Failed to load secrets! {}'.format(error))\n\n dbclient = loader.build_db_client(\n db_provider=db_provider,\n connection_config=config['database'][db_provider],\n tables=tablelist\n )\n\n for table in tablelist:\n print('Contents of table {}::'.format(table))\n print(dbclient.dump_table(table))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"securitybot/utils/showDb.py","file_name":"showDb.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"397686163","text":"import subprocess, os, time, win32api, win32con\n\ndef click(x,y):\n win32api.SetCursorPos((x, y))\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)\n\nwhile True:\n time.sleep(2)\n subprocess.Popen('\"D:\\Steam\\steamapps\\common\\Press and Jump\\game.exe\"')\n print(\"[+] game launched...\")\n\n for i in range(2):\n time.sleep(3)\n click(1050, 720)\n \n time.sleep(5)\n os.system('taskkill /f /im game.exe')\n print(\"[-] game ended...\")\n","sub_path":"steam/auto_clicker/press and jump.py","file_name":"press and jump.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"299011730","text":"from struct import *\n\nfrom Data.NALU import NAL_unit\n\nCURRENT_NALU_TYPE = 25\n\nFIXED_NALU_HEADER_LENGTH = 1 # in Byte\nFIXED_NALU_SIZE_LENGTH = 2 # in Byte\nFIXED_DON_LENGTH = 2 # in Byte\n\n\ndef extract_actual_nalus(nalu):\n assert (nalu.nalu_type == CURRENT_NALU_TYPE)\n\n payload = nalu.payload.load\n payload_length = len(payload)\n\n don_value_data = payload[:FIXED_DON_LENGTH]\n don_value = unpack('!H', don_value_data)[0]\n\n current_don = don_value\n\n current_nalu_size_data = payload[FIXED_DON_LENGTH:FIXED_NALU_SIZE_LENGTH + FIXED_DON_LENGTH]\n current_nalu_size = unpack('!H', current_nalu_size_data)[0]\n\n current_start_index = 0\n\n nalu_array = []\n\n first_nalu = True\n\n while (current_start_index + current_nalu_size + FIXED_NALU_SIZE_LENGTH <= payload_length):\n if (first_nalu):\n nalu_size_start_index = current_start_index + FIXED_DON_LENGTH\n first_nalu = not first_nalu\n else:\n nalu_size_start_index = current_start_index\n nalu_header_start_index = nalu_size_start_index + FIXED_NALU_SIZE_LENGTH\n nalu_payload_start_index = nalu_header_start_index + FIXED_NALU_HEADER_LENGTH\n\n current_nalu_size_data = payload[nalu_size_start_index:nalu_header_start_index]\n current_nalu_size = unpack('!H', current_nalu_size_data)[0]\n\n nalu_end_index = nalu_header_start_index + current_nalu_size\n\n nalu_data = payload[nalu_header_start_index:nalu_end_index]\n nalu = NAL_unit(nalu_data)\n\n nalu_array.append((current_don, nalu))\n\n current_start_index = nalu_end_index\n current_don = (current_don + 1) % 65536\n\n return nalu_array\n","sub_path":"RST264/Helper/rtp_payload/STAP_B_helper.py","file_name":"STAP_B_helper.py","file_ext":"py","file_size_in_byte":1669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"515525541","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 ('emailmanager', '0009_auto_20150604_0057'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='email',\n name='email_type',\n field=models.CharField(default='Action', max_length=80),\n preserve_default=False,\n ),\n migrations.AlterField(\n model_name='email',\n name='button',\n field=models.CharField(default=b'Take Email', max_length=50, verbose_name=b'button text'),\n ),\n migrations.AlterField(\n model_name='email',\n name='email_url',\n field=models.CharField(max_length=150),\n ),\n migrations.AlterField(\n model_name='email',\n name='full_name',\n field=models.CharField(max_length=80, verbose_name=b'full name', blank=True),\n ),\n migrations.AlterField(\n model_name='email',\n name='img_credit',\n field=models.CharField(max_length=80, verbose_name=b'photo credit', blank=True),\n ),\n migrations.AlterField(\n model_name='email',\n name='job_title',\n field=models.CharField(max_length=80, verbose_name=b'job title', blank=True),\n ),\n migrations.AlterField(\n model_name='email',\n name='lift_note',\n field=models.TextField(blank=True),\n ),\n migrations.AlterField(\n model_name='email',\n name='office',\n field=models.CharField(max_length=80, blank=True),\n ),\n migrations.AlterField(\n model_name='email',\n name='teaser',\n field=models.CharField(max_length=200, null=True, blank=True),\n ),\n migrations.AlterField(\n model_name='email',\n name='title',\n field=models.CharField(default=b'', max_length=150),\n ),\n migrations.AlterField(\n model_name='email',\n name='valedic',\n field=models.CharField(default=b'Thank you for speaking out,', max_length=80, verbose_name=b'valediction'),\n ),\n ]\n","sub_path":"emailmanager/migrations/0010_auto_20150604_1519.py","file_name":"0010_auto_20150604_1519.py","file_ext":"py","file_size_in_byte":2287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"418347187","text":"import telebot\r\nimport pyowm \r\n\r\nowm = pyowm.OWM('affe09dd9ba0dc635779ed17bdf11f38', language = \"ru\")\r\nbot = telebot.TeleBot(\"1089654967:AAGuzKfKrH1SEEstj3uIPbBMLOf3CYV38Io\")\r\n\r\n@bot.message_handler(content_types=['text'])\r\ndef send_echo(message):\r\n\tobservation = owm.weather_at_place( message.text )\r\n\tw = observation.get_weather()\r\n\ttemp = w.get_temperature('celsius')[\"temp\"]\r\n\r\n\tanswer = \"В городе \" + message.text + \" сейчас \" + w.get_detailed_status() + \"\\n\"\r\n\tanswer += \"Температура сейчас в районе \" + str(temp) + \"\\n\\n\"\r\n\tif temp < -5:\r\n\t\tanswer += \"Сейчас очень холодно, одевайся как танк!\"\r\n\telif (temp < 10)&(temp > 0):\r\n\t\tanswer += \"Сейчас холодно, оденься потеплее. \"\r\n\telif (temp < -5)&(temp > -1):\r\n\t\tanswer += \"Сейчас холодно, но не так холодно как при меньше нуля, но я не знаю как это у тебя там работает. \"\r\n\telif temp < 20:\r\n\t\tanswer += \"Специальное веселое значение\"\r\n\telse:\r\n\t\tanswer += \"Температура норм, одевай платье. \"\r\n\r\n\tbot.send_message(message.chat.id, answer)\r\n\r\nbot.polling( none_stop= True )","sub_path":"telegapogoda.py","file_name":"telegapogoda.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"4287580","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Copyright (c) 2014 Jean-Louis Fuchs\n# Copyright (c) 2013 Ulrich Mierendorff\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n\n\n\"\"\"Binary protocol of Kyoto Tycoon with asyncio for io batching.\n\nKyoto Tycoon is a lightweight database server with impressive performance. It\ncan be accessed via several protocols, including an efficient binary protocol\nwhich is used in this Python library.\n\nThe current implementation of this library provides access to the following\ncommands: set_bulk, get_bulk, remove_bulk (plus some wrapper functions to\neasily use these commands if you only need to access a single item) and\nplay_script.\n\nThe library is implemented in pure Python and requires the module asyncio\nand other Python standard library modules. Therefore, it is possible to use\nthe library with other interpreters than the standard CPython. The code has\nbeen tested with python 3.4 since it is based on the asyncio module\nintroduced in 3.4. If pypy will implement asyncio in can be ported to\npypy and possibly other implementation.\n\n\"\"\"\n\n# TODO PEP8\n# TODO Move documentation from homepage to code\n# TODO Add some logging (tornados nice output?):w\n# TODO embed factory method that creates a ktserver and client\n# -> find free random port automatically (within range)\n# -> with keep alive and logging of failures\n# TODO compare original / asyincio wo batch / asyncio with batch\n# TODO Write tests\n# TODO remove that lazy stuff, since we are always lazy (batching)\n# TODO sphinx doc setup (take snippets from freeze)\n# TODO travis setup\n# TODO github badge setup\n# TODO stackoverflow question for promotion\n# TODO adsy blogging\n\n\nimport socket\nimport random\nimport struct\nimport logging\nimport threading\nimport subprocess\nimport sys\nimport time\nimport atexit\ntry:\n import asyncio\nexcept ImportError:\n import trollius as asyncio\n from trollius import From, Return\n\nMB_SET_BULK = 0xb8\nMB_GET_BULK = 0xba\nMB_REMOVE_BULK = 0xb9\nMB_ERROR = 0xbf\nMB_PLAY_SCRIPT = 0xb4\n\nDEFAULT_HOST = 'localhost'\nDEFAULT_PORT = 1978\nDEFAULT_EXPIRE = 0x7FFFFFFFFFFFFFFF\nMAX_CONNECTIONS = 4\n\nFLAG_NOREPLY = 0x01\n\nRANGE_FROM = 2 ** 15 - 2 ** 14\nRANGE_TO = 2 ** 15 - 1\n\n\ndef _l():\n \"\"\"Get the logger\"\"\"\n return logging.getLogger(\"ktasync\")\n\n\nclass KyotoTycoonError(Exception):\n \"\"\"Class for Exceptions in this module\"\"\"\n\n\nclass KyotoTycoon(object):\n \"\"\"New connections are created using the constructor. A connection is\n automatically closed when the object is destroyed. There is the factory\n method embedded which creates a server and client connected to it.\n\n Keys and values of database entries are python bytes. You can pickle\n objects to bytes strings. The encoding is handled by the user when\n converting to bytes. Usually bytes(bla, encoding=\"UTF-8\") is safe.\n\n \"\"\"\n\n _client = None\n\n @staticmethod\n def embedded(\n args=None,\n timeout=None,\n max_connections=MAX_CONNECTIONS,\n range_from=RANGE_FROM,\n range_to=RANGE_TO\n ):\n \"\"\"Start an embedded Kyoto Tycoon server and return a client conencted\n to it.\n\n :param args: Additional arguments for the Kyoto Tycoon server.\n\n :param timeout: Optional timeout for the socket. None means no timeout\n (please also look at the Python socket manual).\n\n :param max_connections: Maximum connections for io batching.\n\n :param range_from: Port range to select a random port from (from).\n\n :param range_to: Port range to select a random port from (to).\n\n :rtype: KyotoTycoon\n\n \"\"\"\n if KyotoTycoon._client:\n return KyotoTycoon._client\n if not args:\n args = []\n tries = 0\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n while tries < 20:\n tries += 1\n port = random.randint(range_from, range_to)\n try:\n sock.bind((\"127.0.0.1\", port))\n sock.listen(1)\n tries = 21\n except OSError:\n pass\n finally:\n sock.close()\n time.sleep(0.2)\n\n def keep_alive():\n \"\"\"Helper\"\"\"\n while True:\n proc = subprocess.Popen(\n [\n \"ktserver\",\n \"-le\",\n \"-host\",\n \"127.0.0.1\",\n \"-port\",\n str(port)\n ] + args,\n stderr=sys.__stderr__.fileno(),\n stdout=sys.__stdout__.fileno(),\n )\n cleanup_done = [False]\n\n def cleanup():\n \"\"\"Helper\"\"\"\n try:\n cleanup_done[0] = True\n proc.terminate()\n proc.wait()\n except ProcessLookupError:\n pass\n\n atexit.register(cleanup)\n proc.wait()\n time.sleep(10)\n if not cleanup_done[0]:\n _l().critical(\"ktserver died!\")\n\n thr = threading.Thread(target=keep_alive)\n thr.setDaemon(True)\n thr.start()\n tries = 0\n while tries < 20:\n tries += 1\n try:\n KyotoTycoon._client = KyotoTycoon(\n host=\"127.0.0.1\",\n port=port,\n probe=True,\n timeout=timeout,\n max_connections=max_connections\n )\n return KyotoTycoon._client\n except ConnectionRefusedError:\n # pypy #except Exception:\n time.sleep(0.2)\n raise KyotoTycoonError(\"Embedded server not started!\")\n\n def __init__(\n self,\n host=DEFAULT_HOST,\n port=DEFAULT_PORT,\n probe=False,\n timeout=None,\n max_connections=MAX_CONNECTIONS,\n ):\n \"\"\"\n :param host: The hostname or IP to connect to, defaults to\n 'localhost'.\n\n :param port: The port number, defaults to 1978 which is the default\n port of Kyoto Tycoon.\n\n :param probe: If set to True, the server connection is checked. The\n connections are taken from a pool. This option helps\n to prevent late failures.\n\n :param timeout: Optional timeout for the socket. None means no timeout\n (please also look at the Python socket manual).\n \"\"\"\n self.host = host\n self.port = port\n self.timeout = timeout\n self.socket = None\n self.loop = asyncio.get_event_loop()\n self.max_connections = max_connections\n self.free_streams = []\n self.semaphore = asyncio.Semaphore(max_connections)\n if probe:\n self._probe()\n\n @asyncio.coroutine\n def set(self, key, val, db=0, expire=DEFAULT_EXPIRE, flags=0):\n \"\"\"Wrapper function around set_bulk for easily storing a single item\n in the database.\n\n :param key: The key of the entry,\n\n :type key: bytes\n\n :param val: The value of the entry\n\n :type val: bytes\n\n :param db: Database index to store the record in. Default to 0.\n\n :type db: int\n\n :param expire: Expiration time for all entries.\n kyototycoon.DEFAULT_EXPIRE is 0x7FFFFFFFFFFFFFFF which\n means that the records should never expire in the\n (near) future.\n\n :param flags: If set to kyototycoon.FLAG_NOREPLY, function will not\n wait for an answer of the server.\n\n :return: The number of actually stored records, or None if flags was\n set to kyototycoon.FLAG_NOREPLY.\n \"\"\"\n return (yield from self.set_bulk(\n # pypy #raise Return((yield From(self.set_bulk(\n ((key, val, db, expire),), flags\n ))\n # pypy #))))\n\n @asyncio.coroutine\n def set_bulk_kv(self, kv, db=0, expire=DEFAULT_EXPIRE, flags=0):\n \"\"\"Wrapper function around set_bulk for simplifying the process of\n storing multiple records with equal expiration times in the same\n database.\n\n :param kv: dict of key/value pairs.\n\n :param db: database index to store the values in. defaults to 0.\n\n :param expire: Expiration time for all entries.\n kyototycoon.DEFAULT_EXPIRE is 0x7FFFFFFFFFFFFFFF which\n means that the records should never expire in the\n (near) future.\n\n :param flags: If set to kyototycoon.FLAG_NOREPLY, function will not\n wait for an answer of the server.\n\n :return: The number of actually stored records, or None if flags was\n set to kyototycoon.FLAG_NOREPLY.\n \"\"\"\n recs = ((key, val, db, expire) for key, val in kv.items())\n return (yield from self.set_bulk(recs, flags))\n # pypy #raise Return((yield From(self.set_bulk(recs, flags))))\n\n @asyncio.coroutine\n def set_bulk(self, recs, flags=0):\n \"\"\"Stores multiple records at once.\n\n :param recs: iterable (e.g. list) of records. Each record is a\n list or tuple of 4 entries: key, val, db, expire\n\n :param flags: If set to kyototycoon.FLAG_NOREPLY, function will not\n wait for an answer of the server.\n\n :return: The number of actually stored records, or None if flags was\n set to kyototycoon.FLAG_NOREPLY.\n \"\"\"\n sr, sw = yield from self._pop_streams()\n # pypy #sr, sw = yield From(self._pop_streams())\n try:\n request = [struct.pack('!BI', MB_SET_BULK, flags), None]\n\n cnt = 0\n for key, val, db, xt in recs:\n assert isinstance(key, bytes), \"Please pass bytes as key\"\n assert isinstance(val, bytes), \"Please pass bytes as value\"\n request.append(\n struct.pack('!HIIq', db, len(key), len(val), xt)\n )\n request.append(key)\n request.append(val)\n cnt += 1\n\n request[1] = struct.pack('!I', cnt)\n\n sw.write(b''.join(request))\n\n if flags & FLAG_NOREPLY:\n self._push_streams(sr, sw)\n return None\n # pypy #raise Return(None)\n\n magic, = struct.unpack('!B', (\n yield from sr.readexactly(1))\n # pypy # yield From(sr.readexactly(1)))\n )\n if magic == MB_SET_BULK:\n recs_cnt, = struct.unpack('!I', (\n yield from sr.readexactly(4))\n # pypy # yield From(sr.readexactly(4)))\n )\n self._push_streams(sr, sw)\n return recs_cnt\n # pypy #raise Return(recs_cnt)\n elif magic == MB_ERROR:\n raise KyotoTycoonError(\n 'Internal server error 0x%02x' % MB_ERROR\n )\n else:\n raise KyotoTycoonError('Unknown server error')\n finally:\n self._release_connection()\n\n @asyncio.coroutine\n def get(self, key, db=0, flags=0):\n \"\"\"Wrapper function around get_bulk for easily retrieving a single\n item from the database.\n\n\n :param key: The key of the entry\n :type key: bytes\n\n :param db: The database index. Defaults to 0.\n\n :param flags: reserved and not used now. (defined by protocol)\n\n :return: The value of the record, or None if the record could not be\n found in the database.\n\n \"\"\"\n recs = yield from self.get_bulk(((key, db),), flags)\n # pypy #recs = yield From(self.get_bulk(((key, db),), flags))\n if not recs:\n return None\n # pypy #raise Return(None)\n return recs[0][1]\n # pypy #raise Return(recs[0][1])\n\n @asyncio.coroutine\n def get_bulk_keys(self, keys, db=0, flags=0):\n \"\"\"Wrapper function around get_bulk for simplifying the process of\n retrieving multiple records from the same database.\n\n :param keys: iterable (e.g. list) of keys.\n\n :param db: database index to store the values in. defaults to 0.\n\n :param flags: reserved and not used now. (defined by protocol)\n\n :return: dict of key/value pairs.\n \"\"\"\n recs = ((key, db) for key in keys)\n recs = yield from self.get_bulk(recs, flags)\n return dict(((key, val) for key, val, db, xt in recs))\n # pypy #recs = yield From(self.get_bulk(recs, flags))\n # pypy #raise Return(dict(((key, val) for key, val, db, xt in recs)))\n\n @asyncio.coroutine\n def get_bulk(self, recs, flags=0):\n \"\"\"Retrieves multiple records at once.\n\n :param recs: iterable (e.g. list) of record descriptions. Each\n record is a list or tuple of 2 entries: key,db\n\n :param flags: reserved and not used now. (defined by protocol)\n\n :return: A list of records. Each record is a tuple of 4 entries: (key,\n val, db, expire)\n \"\"\"\n sr, sw = yield from self._pop_streams()\n # pypy #sr, sw = yield From(self._pop_streams())\n try:\n request = [struct.pack('!BI', MB_GET_BULK, flags), None]\n\n cnt = 0\n for key, db in recs:\n assert isinstance(key, bytes), \"Please pass bytes as key\"\n request.append(struct.pack('!HI', db, len(key)))\n request.append(key)\n cnt += 1\n\n request[1] = struct.pack('!I', cnt)\n\n sw.write(b''.join(request))\n res = yield from self._read_keys(sr, MB_GET_BULK)\n # pypy #res = yield From(self._read_keys(sr, MB_GET_BULK))\n self._push_streams(sr, sw)\n return res\n # pypy #raise Return(res)\n finally:\n self._release_connection()\n\n @asyncio.coroutine\n def _read_keys(self, sr, magic_expect):\n \"\"\"Internal function for reading key from get_bulk or play_script\"\"\"\n data = yield from sr.readexactly(5)\n # pypy #data = yield From(sr.readexactly(5))\n magic, = struct.unpack('!B', data[:1])\n if magic == magic_expect:\n recs_cnt, = struct.unpack('!I', data[1:])\n recs_cnt -= 1\n recs = []\n # Reduce yields be reading key and next header at once\n if recs_cnt >= 0:\n data = yield from sr.readexactly(18)\n # pypy #data = yield From(sr.readexactly(18))\n pre_data = 0\n for _ in range(recs_cnt):\n db, key_len, val_len, xt = struct.unpack(\n '!HIIq', data[pre_data:]\n )\n pre_data = key_len + val_len\n data = yield from sr.readexactly(pre_data + 18)\n # pypy #data = yield From(sr.readexactly(pre_data + 18))\n recs.append((data[:key_len], data[key_len:], db, xt))\n db, key_len, val_len, xt = struct.unpack(\n '!HIIq', data[pre_data:]\n )\n pre_data = key_len + val_len\n data = yield from sr.readexactly(pre_data)\n # pypy #data = yield From(sr.readexactly(pre_data))\n recs.append((data[:key_len], data[key_len:], db, xt))\n return recs\n # pypy #raise Return(recs)\n elif magic == MB_ERROR:\n raise KyotoTycoonError(\n 'Internal server error 0x%02x' % MB_ERROR\n )\n else:\n raise KyotoTycoonError('Unknown server error')\n\n @asyncio.coroutine\n def remove(self, key, db, flags=0):\n \"\"\"Wrapper function around remove_bulk for easily removing a single\n item from the database.\n\n :param key: The key of the entry.\n :type key: bytes\n\n :param db: database index to store the values in. defaults to 0.\n\n :param flags: If set to kyototycoon.FLAG_NOREPLY, function will not\n wait for an answer of the server.\n\n :return: The number of removed records, or None if flags was set to\n kyototycoon.FLAG_NOREPLY\n \"\"\"\n return (yield from self.remove_bulk(((key, db),), flags))\n # pypy #raise Return((yield From(self.remove_bulk(((key, db),), flags))))\n\n @asyncio.coroutine\n def remove_bulk_keys(self, keys, db, flags=0):\n \"\"\"Wrapper function around remove_bulk for simplifying the process of\n removing multiple records from the same database.\n\n :param keys: iterable (e.g. list) of keys.\n\n :param db: database index to store the values in. defaults to 0.\n\n :param flags: If set to kyototycoon.FLAG_NOREPLY, function will not\n wait for an answer of the server.\n\n :return: The number of removed records, or None if flags was set to\n kyototycoon.FLAG_NOREPLY\n \"\"\"\n recs = ((key, db) for key in keys)\n return (yield from self.remove_bulk(recs, flags))\n # pypy #raise Return((yield From(self.remove_bulk(recs, flags))))\n\n @asyncio.coroutine\n def remove_bulk(self, recs, flags=0):\n \"\"\"Remove multiple records at once.\n\n :param recs: iterable (e.g. list) of record descriptions. Each\n record is a list or tuple of 2 entries: key,db\n\n :param flags: If set to kyototycoon.FLAG_NOREPLY, function will not\n wait for an answer of the server.\n\n :return: The number of removed records, or None if flags was set to\n kyototycoon.FLAG_NOREPLY\n \"\"\"\n sr, sw = yield from self._pop_streams()\n # pypy #sr, sw = yield From(self._pop_streams())\n try:\n\n request = [struct.pack('!BI', MB_REMOVE_BULK, flags), None]\n\n cnt = 0\n for key, db in recs:\n request.append(struct.pack('!HI', db, len(key)))\n request.append(key)\n cnt += 1\n\n request[1] = struct.pack('!I', cnt)\n\n sw.write(''.join(request))\n\n if flags & FLAG_NOREPLY:\n self._push_streams(sr, sw)\n return None\n # pypy #raise Return(None)\n\n magic, = struct.unpack(\n '!B', (yield from sr.readexactly(1))\n # pypy # '!B', (yield From(sr.readexactly(1)))\n )\n if magic == MB_REMOVE_BULK:\n recs_cnt, = struct.unpack(\n '!I', (yield from sr.readexactly(4))\n # pypy # '!I', (yield From(sr.readexactly(4)))\n )\n self._push_streams(sr, sw)\n return recs_cnt\n # pypy #raise Return(recs_cnt)\n elif magic == MB_ERROR:\n raise KyotoTycoonError(\n 'Internal server error 0x%02x' % MB_ERROR\n )\n else:\n raise KyotoTycoonError('Unknown server error')\n finally:\n self._release_connection()\n\n @asyncio.coroutine\n def play_script(self, name, recs, flags=0):\n \"\"\"Calls a procedure of the LUA scripting language extension.\n\n :param name: The name of the LUA function.\n\n :param recs: iterable (e.g. list) of records. Each record is a list or\n tuple of 2 entries: key, val\n\n :param flags: If set to kyototycoon.FLAG_NOREPLY, function will not\n wait for an answer of the server.\n\n :return: A list of records. Each record is a tuple of 2 entries: (key,\n val). Or None if flags was set to kyototycoon.FLAG_NOREPLY.\n \"\"\"\n sr, sw = yield from self._pop_streams()\n # pypy #sr, sw = yield From(self._pop_streams())\n try:\n\n request = [\n struct.pack(\n '!BII', MB_PLAY_SCRIPT, flags, len(name)\n ), None, name\n ]\n\n cnt = 0\n for key, val in recs:\n request.append(struct.pack('!II', len(key), len(val)))\n request.append(key)\n request.append(val)\n cnt += 1\n\n request[1] = struct.pack('!I', cnt)\n\n yield from sw.write(''.join(request))\n # pypy #yield From(sw.write(''.join(request)))\n\n if flags & FLAG_NOREPLY:\n self._push_streams(sr, sw)\n return None\n # pypy #raise Return(None)\n\n magic, = struct.unpack(\n '!B', (yield from sr.readexactly(1))\n # pypy # '!B', (yield From(sr.readexactly(1)))\n )\n res = yield from self._read_keys(sr, MB_PLAY_SCRIPT)\n # pypy #res = yield From(self._read_keys(sr, MB_PLAY_SCRIPT))\n self._push_streams(sr, sw)\n return res\n # pypy #raise Return(res)\n finally:\n self._release_connection()\n\n def close(self):\n \"\"\"Close the sockets\"\"\"\n while self.free_streams:\n _, sw = self.free_streams.pop()\n sw.close()\n\n def _probe(self):\n \"\"\"Probe the server\"\"\"\n sock = socket.create_connection(\n (self.host, self.port),\n self.timeout\n )\n sock.close()\n\n def __del__(self):\n \"\"\"Cleanup on the delete\"\"\"\n self.close()\n\n @asyncio.coroutine\n def _pop_streams(self):\n \"\"\"Get a new stream. It will block (async) when max_connections is\n reached\"\"\"\n yield from self.semaphore.acquire()\n # pypy #yield From(self.semaphore.acquire())\n if self.free_streams:\n return self.free_streams.pop()\n # pypy #raise Return(self.free_streams.pop())\n else:\n return (yield from asyncio.open_connection(\n # pypy #raise Return((yield From(asyncio.open_connection(\n self.host,\n self.port,\n ))\n # pypy #))))\n\n def _release_connection(self):\n \"\"\"Release the semaphore\n\n If a connection dies, we won't return it. Therefore release is an\n extra method.\"\"\"\n self.semaphore.release()\n\n def _push_streams(self, sr, sw):\n \"\"\"Return used stream.\"\"\"\n self.free_streams.append((sr, sw))\n","sub_path":"ktasync.py","file_name":"ktasync.py","file_ext":"py","file_size_in_byte":23715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"262716868","text":"# Challenge Amstrong number\n# Author Amine M Boulouma\n# 23/03/2018\n\ndef isAmstrong(num):\n\tsum = 0\n\tfor i in str(num):\n\t\tsum += int(i)**3\n\treturn (sum == num)\n\t\nprint(isAmstrong(int(input())))\nfor i in range(int(input())):\n\tif isAmstrong(i):\n\t\tprint(i)","sub_path":"sololearn/challenges/amstrong_number.py","file_name":"amstrong_number.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"120227720","text":"\n#for x in range(1,8):\n # print(x)\nimport random\n\ndef kpn():\n komputer = random.randint(1,3)\n if kamien == 1:\n kamien()\n elif nozyce == 2:\n nozyce()\n elif papier == 3:\n papier()\n\ndef kamien():\n uzytkownik = input(\"1 - kamien, 2 - nozyce, 3 - papier:\" )\n if uzytkownik == \"1\":\n print(\"Zremisowales. Ty kamień, komp kamień\")\n tryAgain()\n if uzytkownik == \"2\":\n print(\"Przegrałeś. Ty nozyczki, komp kamień\")\n tryAgain()\n if uzytkownik == \"3\":\n print(\"Wygrałeś. Ty papier, komp kamień\")\n tryAgain()\n\ndef nozyce():\n uzytkownik = input(\"1 - kamien, 2 - nozyce, 3 - papier:\" )\n if uzytkownik == \"1\":\n print(\"Wygrałeś. Ty kamień, komp nozyczki\")\n tryAgain()\n if uzytkownik == \"2\":\n print(\"Zremisowales. Ty nozyczki, komp nozyczki\")\n tryAgain()\n if uzytkownik == \"3\":\n print(\"Przegrałeś. Ty papier, komp nozyczki\")\n tryAgain()\n\ndef papier():\n uzytkownik = input(\"1 - kamien, 2 - nozyce, 3 - papier:\" )\n if uzytkownik == \"1\":\n print(\"Przegrałeś. Ty kamień, komp papier\")\n tryAgain()\n if uzytkownik == \"2\":\n print(\"Wygrałeś. Ty nozyczki, komp papier\")\n tryAgain()\n if uzytkownik == \"3\":\n print(\"Zremisowałeś. Ty papier, komp papier\")\n tryAgain()\n\n\ndef tryAgain():\n wybor =input('Zagrasz jeszcze raz? Wpisz tak')\n if wybor == \"tak\":\n kpn()\n if wybor == \"nie\":\n quit()\n\nkpn()\n\n # lista =[1,2,3]\n #a random.choice(lista)\n # print(a)\n\n ","sub_path":"kpn.py","file_name":"kpn.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"33523695","text":"\"\"\"\n1.Python strings are immutable – you can't change part of a string. That’s a design choice by the makers of Python. There are plenty of reasons for this, here's just one StackOverflow discussion.\nStrings are also immutable in C/C++, Java, and JavaScript. \n\n2.reversed(seq)\nReturn a reverse iterator. seq must be an object which has a __reversed__() method or supports the sequence protocol (the __len__() method and the __getitem__() method with integer arguments starting at 0).\n\"\"\"\n\nclass Solution(object):\n def reverseStr(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: str\n \"\"\"\n s = list(s) #Python strings are immutable, make it a list\n for i in range(0, len(s), 2*k):\n s[i:i+k] = reversed(s[i:i+k])\n \n return \"\".join(s)\n","sub_path":"Reverse-String-II.py","file_name":"Reverse-String-II.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"187182517","text":"from xml.etree import ElementTree as et\r\n'''Чтение из xml'''\r\ntree = et.parse('test_xml.xml')\r\nroot = tree.getroot()\r\n'''children = root.getchildren()'''\r\n\r\nfor group in root:\r\n print(\"Group: \", group.attrib)\r\n for student in group:\r\n print('{}: {}'.format(student.tag, student.text))\r\n'''Создание xml'''\r\nroot = et.Element('MAIN_ELEM')\r\nfor i in range(10):\r\n sub_element = et.SubElement(root, 'value{}'.format(i))\r\n sub_element.text = str(i * 10)\r\nprint(et.dump(root))\r\n\r\ndata = [\r\n {'x': 10, 'y': 20, 'z': 30},\r\n {'x': 'zello', 'y': 40, 'z': True}\r\n]\r\nroot = et.Element('records')\r\nfor item in data:\r\n record = et.SubElement(root, 'record')\r\n for key, value in item.items():\r\n e = et.SubElement(record, key)\r\n e.text = str(value)\r\ntree = et.ElementTree(root)\r\ntree.write('test_xml_created.xml', encoding='utf-8')","sub_path":"Base_learning/pyproj_18_xml.py","file_name":"pyproj_18_xml.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"143046953","text":"from zoundry.appframework.global_services import getApplicationModel\r\nfrom zoundry.appframework.ui.widgets.controls.advanced.mshtml.mshtmlcontrol import IZMshtmlEvents\r\nfrom zoundry.appframework.ui.widgets.controls.advanced.mshtml.mshtmleditor import ZMshtmlEditControl\r\nfrom zoundry.appframework.ui.widgets.controls.advanced.mshtml.mshtmluiproxies import ZMshtmlExtendedEntryMarkerProxy\r\nfrom zoundry.appframework.ui.widgets.controls.advanced.mshtml.mshtmlvisitors import ZMshtmlExtEntryMarker2CommentZDomVisitor\r\nfrom zoundry.appframework.ui.widgets.controls.advanced.mshtml.mshtmlvisitors import ZMshtmlRemoveCommentsVisitor\r\nfrom zoundry.appframework.ui.widgets.controls.advanced.mshtml.mshtmlvisitors import ZMshtmlRemoveEmptyElementZDomVisitor\r\nfrom zoundry.appframework.ui.widgets.controls.advanced.mshtml.mshtmlvisitors import ZMshtmlRemoveUnSelectableZDomVisitor\r\nfrom zoundry.appframework.ui.widgets.controls.advanced.mshtml.mshtmlvisitors import ZMshtmlTextMoreComment2ExtEntryMarkerVisitor\r\nfrom zoundry.appframework.ui.widgets.controls.advanced.mshtml.mshtmlvisitors import ZMshtmlWrapEmbedElementZDomVisitor\r\nfrom zoundry.base.util.text.textutil import getNoneString\r\nfrom zoundry.blogapp.constants import IZBlogAppUserPrefsKeys\r\nfrom zoundry.blogapp.ui.editors.blogeditorctrls.blogposteditcontrol import IZBlogPostEditControl\r\n\r\n# ------------------------------------------------------------------------------\r\n# A concrete implementation of a blog post edit control. This control uses the\r\n# Microsoft MSHTML component to edit the post content.\r\n# ------------------------------------------------------------------------------\r\nclass ZMSHTMLBlogPostEditControl(ZMshtmlEditControl, IZBlogPostEditControl):\r\n\r\n def __init__(self, parent):\r\n ZMshtmlEditControl.__init__(self, parent)\r\n # end __init__()\r\n\r\n def _bindWidgetEvents(self):\r\n ZMshtmlEditControl._bindWidgetEvents(self)\r\n self.Bind(IZMshtmlEvents.ZEVT_MSHTML_DOCUMENT_LOADED, self.onDocumentLoaded, self._getMshtmlControl())\r\n # end _bindWidgetEvents()\r\n\r\n def _getCapabilityIdList(self):\r\n rval = ZMshtmlEditControl._getCapabilityIdList(self)\r\n rval.append(IZBlogPostEditControl.ZCAPABILITY_EXTENDED_ENTRY_MARKER)\r\n return rval\r\n # end _getCapabilityIdList()\r\n\r\n def onDocumentLoaded(self, event): #@UnusedVariable\r\n # convert to special markers\r\n doc = self._getMshtmlControl().getIHTMLDocument()\r\n visitor = ZMshtmlTextMoreComment2ExtEntryMarkerVisitor()\r\n visitor.visit(doc)\r\n # run visitors to remove remaining comments (eliminate repeats/duplicates if any)\r\n visitor = ZMshtmlRemoveCommentsVisitor([ZMshtmlRemoveCommentsVisitor.TEXT_MORE_RE,])\r\n visitor.visit(doc)\r\n # font\r\n self._setEditorFonts()\r\n # get snap shot of initial content to compare with later content to see if document has been modified.\r\n self.clearState()\r\n event.Skip()\r\n # end onDocumentLoaded()\r\n\r\n def _setEditorFonts(self):\r\n try:\r\n userPrefs = getApplicationModel().getUserProfile().getPreferences()\r\n fontName = getNoneString(userPrefs.getUserPreference(IZBlogAppUserPrefsKeys.EDITOR_FONT_NAME, u\"\")) #$NON-NLS-1$\r\n fontSize = getNoneString(userPrefs.getUserPreference(IZBlogAppUserPrefsKeys.EDITOR_FONT_SIZE, u\"\")) #$NON-NLS-1$\r\n if fontName:\r\n self._getMshtmlControl().getIHTMLDocument().body.style.fontFamily = fontName\r\n if fontSize:\r\n self._getMshtmlControl().getIHTMLDocument().body.style.fontSize = fontSize\r\n except:\r\n pass\r\n # end _setEditorFonts()\r\n\r\n def setXhtmlDocument(self, xhtmlDoc):\r\n # override to run visitor to remove empty elements\r\n visitor = ZMshtmlRemoveEmptyElementZDomVisitor([u\"a\"]) #$NON-NLS-1$\r\n visitor.visit(xhtmlDoc.getDom())\r\n ZMshtmlEditControl.setXhtmlDocument(self, xhtmlDoc)\r\n # end setXhtmlDocument()\r\n\r\n def getXhtmlDocument(self):\r\n xhtmlDoc = ZMshtmlEditControl.getXhtmlDocument(self)\r\n # run visitor to convert special marker to a comment\r\n zdom = xhtmlDoc.getDom()\r\n visitor = ZMshtmlExtEntryMarker2CommentZDomVisitor()\r\n visitor.visit(zdom)\r\n # run embed wrapper visitor\r\n visitor = ZMshtmlWrapEmbedElementZDomVisitor()\r\n visitor.visit(zdom)\r\n # run visitor to remove empty elements.\r\n visitor = ZMshtmlRemoveEmptyElementZDomVisitor([u\"a\"]) #$NON-NLS-1$\r\n visitor.visit(zdom)\r\n # remove 'unselectable' attribute\r\n visitor = ZMshtmlRemoveUnSelectableZDomVisitor()\r\n visitor.visit(zdom)\r\n\r\n return xhtmlDoc\r\n # end getXhtmlDocument()\r\n\r\n def canRemoveExtendedEntryMarker(self):\r\n mshtmlElem = self._getMshtmlControl().getSelectedElement()\r\n if mshtmlElem and (mshtmlElem.tagName == u\"IMG\" or mshtmlElem.tagName == u\"HR\"): #$NON-NLS-1$ #$NON-NLS-2$\r\n return mshtmlElem.getAttribute(u\"id\") == ZMshtmlExtendedEntryMarkerProxy.EXTENDED_ENTRY_MARKER_ID #$NON-NLS-1$\r\n return False\r\n # end canRemoveExtendedEntryMarker()\r\n\r\n def removeExtendedEntryMarker(self):\r\n mshtmlElem = self._getMshtmlControl().getSelectedElement(True)\r\n if mshtmlElem:\r\n marker = ZMshtmlExtendedEntryMarkerProxy()\r\n marker.removeExtendedEntry( mshtmlElem )\r\n # removeExtendedEntryMarker()\r\n\r\n def insertExtendedEntryMarker(self):\r\n mshtmlElem = self._getMshtmlControl().getSelectedElement(True)\r\n if mshtmlElem:\r\n marker = ZMshtmlExtendedEntryMarkerProxy()\r\n marker.insertExtendedEntry( mshtmlElem )\r\n # insertExtendedEntryMarker()\r\n# end ZMSHTMLBlogPostEditControl\r\n\r\n\r\n","sub_path":"src/python/zoundry/blogapp/ui/editors/blogeditorctrls/mshtmlblogposteditcontrol.py","file_name":"mshtmlblogposteditcontrol.py","file_ext":"py","file_size_in_byte":5817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"328477057","text":"#!/usr/bin/python3\n\nfrom collections import namedtuple\nimport json\nimport logging\nimport math\nimport nltk\nimport numpy as np\n\nimport anagram\nimport clue as c\nimport definition\nimport synonym\n\n\nFeature = namedtuple(\"Feature\", [\"defn\", \"anagrind\", \"anagrist\", \"synonym\", \"lingo\"])\n\n\nEPSILON = 0.0001\n\nDEFINITION_INDEX = 0\nANAGRIND_INDEX = 1\nANAGRIST_INDEX = 2\nSYNONYM_INDEX = 3\nCHAFF_INDEX = 4\n\n\ndef rate_anagrind(word):\n ANAGRIND_BASES = [\"change\", \"destroy\", \"confuse\"]\n matches = [definition.word_similarity(word, grind)\n for grind in ANAGRIND_BASES]\n return max(matches)\n\n\ndef rate_lingo(word, solution):\n best_freq = 0\n with open(\"xword_lingo.freqs\", \"r\") as f:\n for line in f:\n lingo, char, freq = line.split()\n if word.lower() == lingo:\n if char in solution:\n best_freq = max([float(freq), best_freq])\n return best_freq\n\n\ndef get_features_word(word, solution, index, clue_length):\n f_defn = definition.word_similarity(word, solution)\n f_anagrind = rate_anagrind(word)\n f_anagrist, _, a_bitmask = anagram.is_possible_anagrist(word, solution)\n f_synonym, _, s_bitmask = synonym.is_synonym_in_solution(word, solution)\n f_lingo = rate_lingo(word, solution)\n f_length = len(word)\n f_position = (4/pow(clue_length, 2)) * pow((index - clue_length/2), 2)\n \n f = Feature(\n f_defn * f_position,\n f_anagrind,\n int(f_anagrist) * f_length,\n int(f_synonym) * f_length,\n f_lingo)\n #print(word, f.defn, f.anagrind, f.anagrist, f.synonym)\n return f, a_bitmask, s_bitmask\n\n\ndef get_features_clue(clue, solution):\n #import pdb; pdb.set_trace()\n words = nltk.word_tokenize(clue)\n index = 0\n record = \"\"\n for word in words:\n f, a_bitmask, s_bitmask = get_features_word(word, solution, index, len(words))\n index += 1\n record += \"{} {} {} {} {} {} {} {} \".format(\n word, f.defn, f.anagrind, f.anagrist, a_bitmask, f.synonym, s_bitmask, f.lingo)\n record += solution.replace(\" \",\"\")\n\n return record\n\n\ndef extract_features():\n with open(\"clues.txt\", \"r\") as f:\n with open(\"stuff.txt\", \"a\") as stuff:\n for line in f:\n record = json.loads(line)\n clue = record['clue']\n solution = record['solution']\n record = get_features_clue(clue, solution)\n stuff.write(record + \"\\n\")\n\n\nif __name__ == \"__main__\":\n extract_features()\n","sub_path":"parser/features.py","file_name":"features.py","file_ext":"py","file_size_in_byte":2537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"399095767","text":"import pymysql\n\n\n\nhost = 'rm-2ze1w9epp05wvc4j4po.mysql.rds.aliyuncs.com'\nuser = 'test_admin'\npwd = '1qaz@WSX'\ndb = 'mc_client246'\nsql = 'select * from t_activity WHERE id = \\'8a69c7976e35b645016eac6a2ca5247c\\''\n\n\n\ndef test_mydb(host,user,pwd,db,sql,port=3306,charset='utf8'):\n con = pymysql.connect(host=host,port=port,user=user,passwd=pwd,db=db,charset = charset)\n cur = con.cursor()\n cur.execute(sql)\n\n if sql.strip()[:6].upper() == 'SELECT':\n res = cur.fetchall()\n\n else:\n con.commit()\n res ='ok'\n\n cur.close()\n con.close()\n print(res)\n return res\n\nprint(test_mydb(host,user,pwd,db,sql))","sub_path":"db_fixture/test_db.py","file_name":"test_db.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"118699490","text":"from flask import Flask\nfrom flask_cors import CORS\n\nfrom config import config\nfrom routes import users\n\n\ndef create_app(config_name):\n app = Flask(\n __name__, static_folder=\"../build/static\", template_folder=\"../build\"\n )\n app.config.from_object(config[config_name])\n config[config_name].init_app(app)\n register_additional_extensions(app)\n register_blueprint(app)\n\n return app\n\n\ndef register_additional_extensions(app):\n \"\"\"Register additional Flask extensions\"\"\"\n CORS(app)\n\ndef register_blueprint(app):\n \"\"\"Register Flask blueprints.\"\"\"\n app.register_blueprint(users.usersprint, url_prefix=\"/api/users\")\n return None\n","sub_path":"labellab-flask/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"291449333","text":"import numpy as np\nfrom sklearn import datasets\nboston=datasets.load_boston()\nx=boston.data\ny=boston.target\nx=x[y<50]\ny=y[y<50]\n\n\n#随机梯度下降法 多元线性回归训练波士顿房价数据\n\nfrom sklearn.model_selection import train_test_split\nx_train ,x_test,y_train,y_test=train_test_split(x,y,random_state=666)\n\n#数据预处理 数据标准化\nfrom sklearn.preprocessing import StandardScaler\nstandscaler=StandardScaler()\nstandscaler.fit(x_train)\nx_train_standard=standscaler.transform(x_train)\nx_test_standard=standscaler.transform(x_test)\n\n\n\n\n#导入线性模型中 随机梯度法 线性回归\n\nfrom sklearn.linear_model import SGDRegressor\nsgd_reg=SGDRegressor(n_iter=500)\nsgd_reg.fit(x_train_standard,y_train)\nscore=sgd_reg.score(x_test_standard,y_test)\nprint(score)","sub_path":"SGD.py","file_name":"SGD.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"325512370","text":"import os, time\n\nclass Menu():\n def __init__(self, options):\n self.options = options\n self.range = len(options)\n\n def run(self):\n Menu.display(self.options)\n return Menu.getInput(self.range)\n\n @staticmethod\n def display(options):\n Menu.clearScreen()\n print(\"Rosalind Project Algorithm CLI\")\n print(\"Enter [Number] to invoke [Algorithm]\")\n for index, option in enumerate(options):\n print(\"{}: {}\".format((index+1), option))\n\n @staticmethod\n def clearScreen():\n os.system('cls' if os.name == 'nt' else 'clear')\n\n @staticmethod\n def pause():\n time.sleep(0.2)\n\n @staticmethod\n def getInput(inputRange):\n while True:\n userInput = input(\">> \")\n try:\n userInput = int(userInput)\n if userInput-1 in range(inputRange):\n return userInput-1\n except ValueError:\n print(\"Invalid Option. Try Again.\")\n\nif __name__ == \"__main__\":\n menu = Menu(['A', 'B', 'C', 'D', 'E'])\n userInput = menu.run()\n print(userInput)\n","sub_path":"rosalindproject/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"382261788","text":"import torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.optim as optim\r\nfrom torchvision import datasets, transforms\r\nfrom torch.autograd import Variable\r\nfrom torchvision.utils import save_image\r\nmode = 'sampling'\r\nbs = 200\r\n# MNIST Dataset\r\ntrain_dataset = datasets.MNIST(root='./mnist_data/', train=True, transform=transforms.ToTensor(), download=True)\r\ntest_dataset = datasets.MNIST(root='./mnist_data/', train=False, transform=transforms.ToTensor(), download=False)\r\n\r\n# Data Loader (Input Pipeline)\r\ntrain_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=bs, shuffle=True)\r\ntest_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=bs, shuffle=False)\r\n\r\n\r\nclass VAE(nn.Module):\r\n def __init__(self, x_dim, h_dim1, h_dim2, z_dim):\r\n super(VAE, self).__init__()\r\n\r\n # encoder part\r\n self.fc1 = nn.Linear(x_dim, h_dim1)\r\n self.fc2 = nn.Linear(h_dim1, h_dim2)\r\n self.fc31 = nn.Linear(h_dim2, z_dim)\r\n self.fc32 = nn.Linear(h_dim2, z_dim)\r\n # decoder part\r\n self.fc4 = nn.Linear(z_dim, h_dim2)\r\n self.fc5 = nn.Linear(h_dim2, h_dim1)\r\n self.fc6 = nn.Linear(h_dim1, x_dim)\r\n\r\n def encoder(self, x):\r\n h = F.relu(self.fc1(x))\r\n h = F.relu(self.fc2(h))\r\n return self.fc31(h), self.fc32(h) # mu, log_var\r\n\r\n def sampling(self, mu, log_var):\r\n std = torch.exp(0.5 * log_var)\r\n eps = torch.randn_like(std)\r\n return eps.mul(std).add_(mu) # return z sample\r\n\r\n def decoder(self, z):\r\n h = F.relu(self.fc4(z))\r\n h = F.relu(self.fc5(h))\r\n return F.sigmoid(self.fc6(h))\r\n\r\n def forward(self, x):\r\n mu, log_var = self.encoder(x.view(-1, 784))\r\n z = self.sampling(mu, log_var)\r\n return self.decoder(z), mu, log_var\r\n\r\n\r\n# build model\r\nVAEs = []\r\noptimizers = []\r\nfor i in range(10):\r\n VAEs.append(VAE(x_dim=784, h_dim1=512, h_dim2=256, z_dim=10).cuda())\r\n\r\n\r\n\r\n optimizers.append(optim.Adam(VAEs[i].parameters()))\r\n # return reconstruction error + KL divergence losses\r\ndef loss_function(recon_x, x, mu, log_var):\r\n BCE = F.binary_cross_entropy(recon_x, x.view(-1, 784), reduction='sum')\r\n KLD = -0.5 * torch.sum(1 + log_var - mu.pow(2) - log_var.exp())\r\n return BCE + KLD\r\n\r\n\r\ndef train(epoch,cat):\r\n VAEs[cat].train()\r\n train_loss = 0\r\n for batch_idx, (data, label) in enumerate(train_loader):\r\n inds = (label == cat).nonzero().squeeze()\r\n data = data[inds].cuda()\r\n optimizers[cat].zero_grad()\r\n\r\n recon_batch, mu, log_var = VAEs[cat](data)\r\n loss = loss_function(recon_batch, data, mu, log_var)\r\n\r\n loss.backward()\r\n train_loss += loss.item()\r\n optimizers[cat].step()\r\n\r\n if batch_idx % 100 == 0:\r\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\r\n epoch, batch_idx * len(data), len(train_loader.dataset),\r\n 100. * batch_idx / len(train_loader), loss.item() / len(data)))\r\n print('====> Epoch: {} Average loss: {:.4f}'.format(epoch, train_loss / len(train_loader.dataset)))\r\n torch.save(VAEs[cat].state_dict(), 'vae' + str(cat) + '.pt')\r\n\r\n\r\ndef test():\r\n for i in range(10):\r\n VAEs[i].eval()\r\n test_loss = 0\r\n with torch.no_grad():\r\n for data, _ in test_loader:\r\n data = data.cuda()\r\n recon, mu, log_var = VAEs[i](data)\r\n\r\n # sum up batch loss\r\n test_loss += loss_function(recon, data, mu, log_var).item()\r\n\r\n test_loss /= len(test_loader.dataset)\r\n print('====> Test set loss: {:.4f}'.format(test_loss))\r\n\r\n#uncomment if you have trained models\r\n# for i in range(10):\r\n# VAEs[i].load_state_dict(torch.load('vae' + str(i) + '.pt'))\r\n\r\n#comment if you don't want to train\r\nfor e in range(30):\r\n for c in range(10):\r\n train(e,c)\r\n # test()\r\nimport matplotlib.pyplot as plt\r\nimport cv2\r\nimport numpy as np\r\nimport torchvision\r\nplt.ion()\r\nimport datetime\r\n\r\ncolonIm = np.zeros((28,8))\r\ncolonIm[7:11,2:6] = 1\r\ncolonIm[17:21,2:6] = 1\r\n\r\nOldZ = [None]*10\r\nOldZ2 = [None]*6\r\nwith torch.no_grad():\r\n z = torch.randn(6, 2).cuda()\r\n while(True):\r\n for batch_idx, (data, label) in enumerate(train_loader):\r\n\r\n now = datetime.datetime.now()\r\n h = now.hour\r\n m = now.minute\r\n s = now.second\r\n DIGITS = [h/10,h%10,m/10,m%10,s/10,s%10]\r\n # print(DIGITS)\r\n DIGITS_IMS = []\r\n\r\n\r\n\r\n for d in range(len(DIGITS)):\r\n # print(z)\r\n if (mode == 'interpolation'):\r\n inds = (label==DIGITS[d]).nonzero()\r\n ind = inds[np.random.randint(len(inds)),0]\r\n ind2 = inds[np.random.randint(len(inds)),0]\r\n mean,std = VAEs[int(DIGITS[d])].encoder(data[ind].reshape((-1,28*28)).cuda())\r\n mean2,std2 = VAEs[int(DIGITS[d])].encoder(data[ind2].reshape((-1,28*28)).cuda())\r\n zreal2 = VAEs[int(DIGITS[d])].sampling(mean2, std2)\r\n if (OldZ[int(DIGITS[d])] is None):\r\n\r\n zreal = VAEs[int(DIGITS[d])].sampling(mean, std)\r\n OldZ[int(DIGITS[d])] = zreal2\r\n else:\r\n zreal = OldZ[int(DIGITS[d])]\r\n OldZ[int(DIGITS[d])] = zreal2\r\n # z = torch.randn(1, 2).cuda()\r\n\r\n else:\r\n zreal2 = torch.randn(1, 10).cuda()\r\n if (OldZ2[d] is None):\r\n zreal = torch.randn(1, 10).cuda()\r\n\r\n else:\r\n zreal = OldZ2[d]\r\n\r\n\r\n n = (torch.randn(1, 10) * 0.1).cuda()\r\n rand0_1 = 0.2 #the smaller it is the shorter the random walk step\r\n z = (1-rand0_1)*zreal + rand0_1*zreal2\r\n # z = zreal + (rand0_1 * zreal2)\r\n OldZ2[d] = z\r\n sample = VAEs[int(DIGITS[d])].decoder(z).cuda()\r\n IM = sample.view(28, 28).cpu().numpy()\r\n DIGITS_IMS.append(IM)\r\n if (len(DIGITS_IMS) in [2,5,6]):\r\n DIGITS_IMS.append(colonIm)\r\n mosaic = np.concatenate(DIGITS_IMS,1)\r\n IM = cv2.resize(mosaic, dsize=(250*6, 250), interpolation=cv2.INTER_CUBIC)\r\n cv2.imshow('image', IM)\r\n cv2.waitKey(1)\r\n\r\n","sub_path":"VAE_CLOCK.py","file_name":"VAE_CLOCK.py","file_ext":"py","file_size_in_byte":6517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"166109717","text":"\"\"\" Symulowane wyżarzanie (simulated annealing) \"\"\"\nimport numpy as np\n\ndef P(current_energy, new_energy, temperature):\n \"probability of accepting a state with new energy\"\n if new_energy < current_energy:\n return 1.0\n return np.math.exp((current_energy - new_energy) / temperature)\n\ndef cooling_schedule(temperature, alpha):\n \"generate cooling schedule T0, T1, ...\"\n while True:\n yield temperature\n temperature *= alpha\n\ndef anneal(initial_state, move_func, energy_func, initial_temp, cooling_rate, iterations):\n \"\"\"\n implemented as a generator, yields (state, energy) for each accepted state. \n \n arguments:\n initial_state - starting point of the annealing process\n move_func - for creating candidates out of current state\n energy_func - calculates energy of each state\n initial_temp - starting temperature\n cooling_rate - how fast temperature changes (e.g. 0.03 - drops by 3%)\n iterations - total number of iterations\n \"\"\"\n current, current_energy = initial_state, energy_func(initial_state)\n best, best_energy = current, current_energy\n \n i = 0\n temps = cooling_schedule(initial_temp, 1-cooling_rate)\n for temperature in temps:\n # yield result of every iteration for the energy plot\n yield (current, current_energy) \n \n candidate = move_func( current )\n new_energy = energy_func(candidate)\n if P(current_energy, new_energy, temperature) > np.random.random():\n # accept:\n current, current_energy = candidate, new_energy\n if current_energy < best_energy:\n best, best_energy = current, current_energy\n i+=1\n if i > iterations:\n break\n yield (best, best_energy) #final result\n\n","sub_path":"sa.py","file_name":"sa.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"649625809","text":"#! /usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport os\n\ncwd = os.getcwd()\nprint(cwd)\n\n# --------------------------- User input\ndir1 = \"C:\\\\Users\\\\mat\\\\Documents\\\\3_\"\n\nfiles_to_delete = ['.pyc']\n\nnotepad = \"/c/Program\\ Files\\ \\(x86\\)/Notepad++/notepad++.exe \"\n# --------------------------- End User input\n\nfor root, dirs, files in os.walk(dir1):\n for file in files:\n if file.endswith(\".pyc\"):\n f = os.path.join(root, file)\n print(f)\n # os.remove(f)\n","sub_path":"recursive_remove_files.py","file_name":"recursive_remove_files.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"98368811","text":"from django.shortcuts import render\nfrom django.forms import formset_factory,modelformset_factory\nfrom . import forms\nfrom .models import ModelSetPost\nfrom django.core.files.storage import FileSystemStorage\nimport os \n\ndef index(request):\n return render(request,'formapp/index.html')\n\ndef form_page(request):\n form = forms.UserInfo()\n if request.method == 'POST':\n form=forms.UserInfo(request.POST)\n if form.is_valid():\n print('バリデーション成功')\n # print(\n # f\"name: {form.cleaned_data['name']}, mail: {form.cleaned_data['mail']},age: {form.cleaned_data['age']}\"\n # )\n print(form.cleaned_data)\n return render(\n request, 'formapp/form_page.html', \n context={ 'form': form\n }\n )\n\ndef form_post(request):\n form = forms.PostModelForm()\n if request.method == 'POST':\n form = forms.PostModelForm(request.POST)\n if form.is_valid():\n form.save()\n return render(\n request, 'formapp/form_post.html',\n context={'form':form}\n )\n\ndef form_set_post(request):\n TestFormset = formset_factory(forms.FormSetPost,extra=3)\n formset = TestFormset(request.POST or None)\n if formset.is_valid():\n for form in formset:\n print(form.cleaned_data)\n return render(\n request, 'formapp/form_set_post.html',\n context = {'formset':formset }\n )\n\ndef modelform_set_post(request):\n # TestFormSet = modelformset_factory(ModelSetPost, fields='__all__',extra=3)\n TestFormSet = modelformset_factory(ModelSetPost,form=forms.ModelFormSetPost,extra=3)\n formset = TestFormSet(request.POST or None, queryset=ModelSetPost.objects.filter(id__gt=3))\n if formset.is_valid():\n formset.save()\n return render(\n request, 'formapp/modelform_set_post.html',\n context = {'formset':formset }\n )\n\ndef upload_sample(request):\n if request.method == 'POST' and request.FILES['upload_file']:\n #送られたファイルの取り出し\n upload_file = request.FILES['upload_file']\n fs = FileSystemStorage() #ファイルを保存する\n file_path = os.path.join('upload', upload_file.name)\n file = fs.save(file_path, upload_file)\n uploaded_file_url = fs.url(file)\n return render(request, 'formapp/upload_file.html',\n context = {'uploaded_file_url': uploaded_file_url}\n )\n return render(request, 'formapp/upload_file.html')\n\ndef upload_model_form(request):\n user = None\n if request.method == 'POST':\n form = forms.UserForm(request.POST,request.FILES)\n if form.is_valid():\n user = form.save()\n else:\n form = forms.UserForm()\n return render(request,'formapp/upload_model_form.html',\n context = {'form':form, 'user': user}\n )","sub_path":"django/Udemy/FormSample/FormProject/FormApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"448947861","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\ndef axis_setup_3d():\n fig = plt.figure()\n ax = fig.gca(projection=\"3d\")\n ax.set_aspect(\"equal\")\n return ax\n\n# https://stackoverflow.com/questions/13685386/matplotlib-equal-unit-length-with-equal-aspect-ratio-z-axis-is-not-equal-to\n\ndef set_axes_radius(ax, origin, radius):\n ax.set_xlim3d([origin[0] - radius, origin[0] + radius])\n ax.set_ylim3d([origin[1] - radius, origin[1] + radius])\n ax.set_zlim3d([origin[2] - radius, origin[2] + radius])\n\ndef set_axes_equal(ax):\n limits = np.array([\n ax.get_xlim3d(),\n ax.get_ylim3d(),\n ax.get_zlim3d(),\n ])\n origin = np.mean(limits, axis=1)\n radius = 0.5 * np.max(np.abs(limits[:, 1] - limits[:, 0]))\n set_axes_radius(ax, origin, radius)\n\ndef scatter_3d(obj, **kwargs):\n ax = axis_setup_3d()\n ax.scatter(obj[:, 0], obj[:, 1], obj[:, 2], **kwargs)\n set_axes_equal(ax)\n plt.show()\n","sub_path":"flagelsim/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"504155994","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n'''\n[env]\nTo activate this environment, use :: conda activate pandas_ga_1\nTo deactivate an active environment, use :: conda deactivate\n# you have created a env with all the required packages\nsource activate pandas_ga_1\n\n\n[path]\ncd /Users/brunoflaven/Documents/01_work/blog_articles/start_stopping_stop_starting/google_analytics_api_pandas_reporting/\n\n\n[file]\npython 008_google_analytics_api_pandas_reporting.py\n\n[source]\nhttps://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-py\n\nhttps://www.themarketingtechnologist.co/getting-started-with-the-google-analytics-reporting-api-in-python/\n\n\n[install]\nhttps://pypi.org/project/google-analytics-data/\nhttps://anaconda.org/anaconda/pandas\nhttps://anaconda.org/conda-forge/google-api-python-client\n\npip install google-analytics-data\nconda install -c conda-forge analytics-python\nconda install -c conda-forge google-auth-oauthlib\nconda install -c anaconda pandas\nconda install -c anaconda google\n\ngoogle-analytics-data==0.8.0\ngoogle-auth-oauthlib==0.4.6\n\npip install --upgrade google-api-python-client\nconda install -c conda-forge google-api-python-client\n\npip install google-analytics-data\npip install --upgrade google-api-python-client\n\nconda install -c conda-forge oauth2client\n\n\n\n'''\n\n\n\"\"\"Hello Analytics Reporting API V4.\"\"\"\n\nimport pandas as pd\nfrom apiclient.discovery import build\nfrom oauth2client.service_account import ServiceAccountCredentials\nSCOPES = ['https://www.googleapis.com/auth/analytics.readonly']\n\n\n# just change it with your own stuff\nKEY_FILE_LOCATION = ''\n# download from https://console.cloud.google.com/apis/credentials?project=\n\n\n# just change it with your own stuff\nVIEW_ID = ''\n# xxxo45678765456nyuygfhvf65675 is a fake id\n# get at https://analytics.google.com/analytics/web/#/xxxo45678765456nyuygfhvf65675/admin/view/settings\n\n\n\ndef initialize_analyticsreporting():\n \"\"\"Initializes an Analytics Reporting API V4 service object.\n\n Returns:\n An authorized Analytics Reporting API V4 service object.\n \"\"\"\n credentials = ServiceAccountCredentials.from_json_keyfile_name(\n KEY_FILE_LOCATION, SCOPES)\n\n # Build the service object.\n analytics = build('analyticsreporting', 'v4', credentials=credentials)\n\n return analytics\n\n\ndef get_report(analytics):\n \"\"\"Queries the Analytics Reporting API V4.\n\n Args:\n analytics: An authorized Analytics Reporting API V4 service object.\n Returns:\n The Analytics Reporting API V4 response.\n \"\"\"\n return analytics.reports().batchGet(\n body={\n 'reportRequests': [\n {\n 'viewId': VIEW_ID,\n 'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],\n 'metrics': [{'expression': 'ga:sessions'}],\n 'dimensions': [{'name': 'ga:country'}]\n }]\n }\n ).execute()\n\n\ndef print_response(response):\n \"\"\"Parses and prints the Analytics Reporting API V4 response.\n\n Args:\n response: An Analytics Reporting API V4 response.\n \"\"\"\n for report in response.get('reports', []):\n columnHeader = report.get('columnHeader', {})\n dimensionHeaders = columnHeader.get('dimensions', [])\n metricHeaders = columnHeader.get(\n 'metricHeader', {}).get('metricHeaderEntries', [])\n\n for row in report.get('data', {}).get('rows', []):\n dimensions = row.get('dimensions', [])\n dateRangeValues = row.get('metrics', [])\n\n for header, dimension in zip(dimensionHeaders, dimensions):\n print(header + ': ', dimension)\n\n for i, values in enumerate(dateRangeValues):\n print('Date range:', str(i))\n for metricHeader, value in zip(metricHeaders, values.get('values')):\n print(metricHeader.get('name') + ':', value)\n\ndef print_response_new (response):\n list = []\n # get report data\n for report in response.get('reports', []):\n # set column headers\n columnHeader = report.get('columnHeader', {})\n dimensionHeaders = columnHeader.get('dimensions', [])\n metricHeaders = columnHeader.get(\n 'metricHeader', {}).get('metricHeaderEntries', [])\n rows = report.get('data', {}).get('rows', [])\n\n for row in rows:\n # create dict for each row\n dict = {}\n dimensions = row.get('dimensions', [])\n dateRangeValues = row.get('metrics', [])\n\n # fill dict with dimension header (key) and dimension value (value)\n for header, dimension in zip(dimensionHeaders, dimensions):\n dict[header] = dimension\n\n # fill dict with metric header (key) and metric value (value)\n for i, values in enumerate(dateRangeValues):\n for metric, value in zip(metricHeaders, values.get('values')):\n #set int as int, float a float\n if ',' in value or '.' in value:\n dict[metric.get('name')] = float(value)\n else:\n dict[metric.get('name')] = int(value)\n\n list.append(dict)\n\n df = pd.DataFrame(list)\n return df\n\ndef main():\n analytics = initialize_analyticsreporting()\n response = get_report(analytics)\n\n # print_response(response)\n df = print_response_new(response)\n # show me the money\n print(df)\n\n\nif __name__ == '__main__':\n main()\n\n\n","sub_path":"stop_starting_start_stopping/google_analytics_api_pandas_reporting/008_google_analytics_api_pandas_reporting.py","file_name":"008_google_analytics_api_pandas_reporting.py","file_ext":"py","file_size_in_byte":5269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"552560190","text":"import os\n\nfrom data_path import path_dir_data, path_dir_data_log, path_dir_data_all_log, path_all_log, path_error_log, \\\n path_change_DB_log, path_dir_data_crawling_menu, path_this_week_menu_csv, path_backup_menu_csv, path_all_menu_txt, \\\n path_all_menu_dat, path_dir_data_account, path_account\nfrom make_log import write_log, slack_msg\nfrom my_date import my_date, day_of_the_week, today_date\n\n\ndef make_path_dir(path_dir, bool):\n if not os.path.isdir(path_dir):\n os.mkdir(path_dir)\n\n if bool:\n write_log(path_dir + \"경로가 없어 새로 생성 했습니다.\")\n\n\ndef make_path_file(path_file):\n if not os.path.exists(path_file):\n logfile = open(path_file, 'w')\n logfile.close()\n write_log(path_file + \"파일이 없어 새로 생성합니다.\")\n\n\ndef create_env_v1():\n make_path_dir(path_dir_data, False) # 아직 로그 경로가 없어 로그생성 False\n make_path_dir(path_dir_data_log, False)\n make_path_dir(path_dir_data_all_log, False)\n make_path_dir(path_dir_data_all_log + '/' + my_date()[0:4] + '_year', False)\n make_path_dir(path_dir_data_all_log + '/' + my_date()[0:4] + '_year/' + my_date()[5:7] + '_month', True)\n make_path_dir(path_dir_data_account, True)\n make_path_dir(path_dir_data_crawling_menu, True)\n\n make_path_file(path_all_log)\n make_path_file(path_error_log)\n make_path_file(path_change_DB_log)\n\n\ndef create_env_v2():\n make_path_dir(path_dir_data, False) # 아직 로그 경로가 없어 로그생성 False\n make_path_dir(path_dir_data_account, True)\n\n\ndef check_all_menu_dat():\n if os.path.exists(path_all_menu_dat):\n return True\n else:\n write_log(\"\\n\\n\\'\" + path_all_menu_dat + \"\\' 파일이 없습니다.\\n추가해 주세요!\\n프로그램을 종료합니다.\")\n return False\n\n\ndef check_account():\n if not os.path.exists(path_account):\n write_log(\"계정 파일이 없어 새로 생성합니다.\")\n accountfile = open(path_account, 'w')\n accountfile.writelines(input(\"ID를 입력하세요: \"))\n accountfile.writelines(\"\\n\")\n accountfile.writelines(input(\"PW를 입력하세요: \"))\n accountfile.close()\n file = open(path_account, 'r')\n reader = file.readlines()\n account_list = []\n for data in reader:\n account_list.append(data.replace('\\n', ''))\n\n my_id = account_list[0]\n my_pw = account_list[1]\n\n return my_id, my_pw\n","sub_path":"namsigdang_crawler/environment_composition.py","file_name":"environment_composition.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"344113139","text":"import numpy as np\nimport math\nimport copy\nfrom collections import deque\n\nIMPOSSIBLE_SCORE = 999999\n\nclass State:\n \n \"\"\"\n Contructeur d'un état initial\n \"\"\"\n def __init__(self, pos):\n \"\"\"\n pos donne la position de la voiture i dans sa ligne ou colonne (première case occupée par la voiture);\n \"\"\"\n self.pos = np.array(pos)\n \n \"\"\"\n c,d et prev premettent de retracer l'état précédent et le dernier mouvement effectué\n \"\"\"\n self.c = self.d = self.prev = None\n \n self.nb_moves = 0\n self.score = 0\n \n self.rock = None\n\n \"\"\"\n Constructeur d'un état à partir du mouvement (c,d)\n \"\"\"\n def move(self, c, d):\n s = State(self.pos)\n s.prev = self\n s.pos[c] += d\n s.c = c\n s.d = d\n s.nb_moves = self.nb_moves + 1\n # TODO\n s.rock = self.rock\n return s\n\n def put_rock(self, rock_pos):\n # TODO\n s = State(self.pos)\n s.prev = self\n \n s.c = self.c\n s.d = self.d\n s.nb_moves = self.nb_moves\n \n s.rock = rock_pos\n \n return s\n \n def score_state(self, rh, is_max=True):\n \n dist_red_exit = (4 - self.pos[0]) \n best_score_unblocking_red = IMPOSSIBLE_SCORE if is_max else 0\n\n\n for car in range(1, rh.nbcars):\n if self.is_car_blocked_by_car(rh, 0, car) == 1:\n if is_max:\n best_score_unblocking_red = min(best_score_unblocking_red, self.nb_cars_blocking(rh, car, (rh.move_on[0], self.pos[0] + rh.length[0]), 1, is_player_turn=True))\n else:\n best_score_unblocking_red = max(best_score_unblocking_red, self.nb_cars_blocking(rh, car, (rh.move_on[0], self.pos[0] + rh.length[0]), 1, is_player_turn=False))\n\n if best_score_unblocking_red == IMPOSSIBLE_SCORE:\n best_score_unblocking_red = 0\n\n self.score += - 100 * dist_red_exit - best_score_unblocking_red\n\n # Prevent the cars from going back and forth\n if self.prev and self.c == self.prev.c and self.d != self.prev.d:\n self.score -= 100\n\n def nb_cars_blocking(self, rh, car_selected, collision_pos, depth, is_player_turn=True):\n nb_cars_blocked = 999999 if is_player_turn else -999999\n\n # Only have DFS look in a depth of 5 maximum to prevent infinite loops\n if depth >= 4:\n return 0\n\n # print(\"In car : \", rh.color[car_selected], \" Collision : \", collision_pos)\n\n if rh.horiz[car_selected]:\n mvts_left = rh.length[car_selected] - (collision_pos[1] - self.pos[car_selected])\n mvts_right = rh.length[car_selected] - mvts_left + 1\n\n # Move left\n if self.pos[car_selected] - mvts_left >= 0:\n # print(\"Car :\", rh.color[car_selected], \" mtvs_left: \", mvts_left)\n if is_player_turn:\n nb_cars_blocked = min(nb_cars_blocked, self.calculate_blocking_and_blocked_cars(rh, car_selected, -mvts_left, depth, is_player_turn))\n else:\n nb_cars_blocked = max(nb_cars_blocked, self.calculate_blocking_and_blocked_cars(rh, car_selected, -mvts_left, depth, is_player_turn))\n nb_cars_blocked += mvts_left\n \n # Move right\n if self.pos[car_selected] + rh.length[car_selected] - 1 + mvts_right <= 5:\n # print(\"Car :\", rh.color[car_selected], \" mtvs_right: \", mvts_right)\n if is_player_turn:\n nb_cars_blocked = min(nb_cars_blocked, self.calculate_blocking_and_blocked_cars(rh, car_selected, mvts_right, depth, is_player_turn))\n else:\n nb_cars_blocked = max(nb_cars_blocked, self.calculate_blocking_and_blocked_cars(rh, car_selected, mvts_right, depth, is_player_turn))\n nb_cars_blocked += mvts_right\n\n else:\n mvts_up = rh.length[car_selected] - (collision_pos[0] - self.pos[car_selected])\n mvts_down = rh.length[car_selected] - mvts_up + 1\n\n # Move up\n if self.pos[car_selected] - mvts_up >= 0:\n # print(\"Car :\", rh.color[car_selected], \" mtvs_up: \", mvts_up)\n if is_player_turn:\n nb_cars_blocked = min(nb_cars_blocked, self.calculate_blocking_and_blocked_cars(rh, car_selected, -mvts_up, depth, is_player_turn))\n else:\n nb_cars_blocked = max(nb_cars_blocked, self.calculate_blocking_and_blocked_cars(rh, car_selected, -mvts_up, depth, is_player_turn))\n nb_cars_blocked += mvts_up\n\n # Move down\n if self.pos[car_selected] + rh.length[car_selected] - 1 + mvts_down <= 5:\n # print(\"Car :\", rh.color[car_selected], \" mvts_down: \", mvts_down)\n if is_player_turn:\n nb_cars_blocked = min(nb_cars_blocked, self.calculate_blocking_and_blocked_cars(rh, car_selected, mvts_down, depth, is_player_turn))\n else:\n nb_cars_blocked = max(nb_cars_blocked, self.calculate_blocking_and_blocked_cars(rh, car_selected, mvts_down, depth, is_player_turn))\n nb_cars_blocked += mvts_down\n \n return nb_cars_blocked\n\n def calculate_blocking_and_blocked_cars(self, rh, car_selected, mvts, depth, is_player_turn=True):\n nb_cars_blocking = 0\n nb_cars_blocked = 0\n\n # Calculate overlapping cars\n overlapping_cars = self.find_overlapping_cars_by_move(rh, car_selected, mvts)\n\n nb_cars_blocking += len(overlapping_cars)\n\n for car in overlapping_cars:\n # print(\"Overlapping car : \", rh.color[car]) \n nb_cars_blocking += self.nb_cars_blocking(rh, car, self.find_overlapping_collision(rh, car_selected, mvts, car), depth + 1, is_player_turn)\n # print(\"Back from Overlapping car : \", rh.color[car]) \n\n # Calculate cars blocking cars blocking exit\n p_cars = self.find_perpendicular_cars(rh, car_selected, mvts)\n\n nb_cars_blocked += len(p_cars)\n\n for p_car in p_cars:\n p_p_cars = self.find_perpendicular_cars(rh, p_car, 0)\n\n # if the p_p_cars (vertical) are blocking the exit, calculate what it would take them to exit\n for p_p_car in p_p_cars:\n if p_p_car == car_selected:\n nb_cars_blocked += 1\n continue\n\n if rh.move_on[p_p_car] >= self.pos[0] + rh.length[0] and self.pos[p_p_car] <= rh.move_on[0] and self.pos[p_p_car] + rh.length[p_p_car] > rh.move_on[0]:\n # print(\"p_p_car : \", rh.color[p_p_car]) \n nb_cars_blocked += self.nb_cars_blocking(rh, p_p_car, (rh.move_on[0], rh.move_on[p_p_car]), depth + 2, is_player_turn)\n # print(\"Back from p_p_car : \", rh.color[p_p_car])\n\n if not is_player_turn and self.is_rock_blocking(rh, car_selected):\n nb_cars_blocked += (5-depth)\n\n return nb_cars_blocking + nb_cars_blocked\n\n\n def is_car_blocked_by_car(self, rh, subject, target): # Return -1 if behind target, 0 if not blocking and 1 if in front of target\n if rh.horiz[subject] != rh.horiz[target]: # Subject vertical and target horizontal, or subject horizontal and target vertical\n if self.pos[target] <= rh.move_on[subject] and self.pos[target] + rh.length[target] > rh.move_on[subject]: # Check if crosses the rows in front \n if rh.move_on[target] == self.pos[subject] - 1: # Check if directly behind\n return -1\n if rh.move_on[target] == self.pos[subject] + rh.length[subject]: # Check if directly in front # TODO: should be <= for the jaune?\n return 1\n\n else: # Subject vertical and target vertical or subject horizontal and target horizontal\n if rh.move_on[subject] == rh.move_on[target]: # Check if on same row or col\n if self.pos[target] + rh.length[target] == self.pos[subject]: # Directly above\n return -1\n if self.pos[target] == self.pos[subject] + rh.length[subject]: # Directly under\n return 1\n\n return 0\n\n def find_overlapping_cars_by_move(self, rh, subject, offset):\n overlapped_cars = set()\n\n for car in range(0, rh.nbcars):\n if car == subject:\n continue\n\n if rh.horiz[subject] == rh.horiz[car]:\n if rh.move_on[subject] == rh.move_on[car]:\n if ((self.pos[car] <= self.pos[subject] + offset and self.pos[car] + rh.length[car] > self.pos[subject] + offset)\n or (self.pos[car] < self.pos[subject] + rh.length[subject] + offset and self.pos[car] + rh.length[car] >= self.pos[subject] + rh.length[subject] + offset)):\n overlapped_cars.add(car)\n else:\n if (self.pos[car] <= rh.move_on[subject] and self.pos[car] + rh.length[car] > rh.move_on[subject]\n and self.pos[subject] + offset <= rh.move_on[car] and self.pos[subject] + offset + rh.length[subject] > rh.move_on[car]):\n overlapped_cars.add(car)\n\n return overlapped_cars\n\n def find_overlapping_collision(self, rh, subject, offset, target):\n if rh.horiz[subject] and not rh.horiz[target]:\n return (rh.move_on[subject], rh.move_on[target])\n elif not rh.horiz[subject] and rh.horiz[target]:\n return (rh.move_on[target], rh.move_on[subject])\n elif rh.horiz[subject] and rh.horiz[target]:\n if offset > 0:\n return (rh.move_on[subject], self.pos[target])\n else:\n return (rh.move_on[subject], self.pos[target] + rh.length[target] - 1)\n else:\n if offset > 0:\n return (self.pos[target], rh.move_on[subject])\n else:\n return (self.pos[target] + rh.length[target] - 1, rh.move_on[subject])\n\n def find_perpendicular_cars(self, rh, subject, offset):\n perpendicular_cars = set()\n\n for car in range(0, rh.nbcars):\n if car == subject:\n continue\n\n if rh.horiz[car] != rh.horiz[subject]:\n if rh.move_on[car] >= self.pos[subject] + offset and rh.move_on[car] < self.pos[subject] + rh.length[subject] + offset:\n perpendicular_cars.add(car)\n\n\n return perpendicular_cars\n\n def is_rock_blocking(self, rh, car_selected):\n if self.rock:\n if rh.horiz[car_selected] and rh.move_on[car_selected] == self.rock[0]:\n if (self.pos[car_selected] - 1) == self.rock[1] or (self.pos[car_selected] + rh.length[car_selected]) == self.rock[1]:\n return True\n elif not rh.horiz[car_selected] and rh.move_on[car_selected] == self.rock[1]:\n if (self.pos[car_selected] - 1) == self.rock[0] or (self.pos[car_selected] + rh.length[car_selected]) == self.rock[0]:\n return True\n return False\n \n\n def success(self):\n return self.pos[0] == 4\n \n def __eq__(self, other):\n if not isinstance(other, State):\n return NotImplemented\n if len(self.pos) != len(other.pos):\n print(\"les états n'ont pas le même nombre de voitures\")\n \n return np.array_equal(self.pos, other.pos)\n \n def __hash__(self):\n h = 0\n for i in range(len(self.pos)):\n h = 37*h + self.pos[i]\n return int(h)\n \n def __lt__(self, other):\n return (self.score) < (other.score)\n","sub_path":"TP2/py-clean/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":11726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"527870085","text":"\"\"\"server URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/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. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom django.contrib import admin\nfrom data_workings import views\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^coordinates/',views.retrCoord),\n url(r'^create/',views.createCoord),\n url(r'^radius/',views.bathroomsInRadiusView),\n url(r'^upvote/',views.tryToUpvote),\n url(r'^signIn/',views.accountService),\n url(r'^updateHandle/', views.updateHandle)\n]\n","sub_path":"BackEnd/server/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"498316658","text":"# Select *subsample* of broadly-defined LRGs with photo-z's in DR8 south\n# require NOBS>=1 for grz\n# Extinction correction is applied to grzW1W2\n\nfrom __future__ import division, print_function\nimport sys, os, glob, time, warnings\nimport numpy as np\nfrom astropy.table import Table, vstack, hstack\nimport fitsio\nimport gc\n# from multiprocessing import Pool\n\nsys.path.append(os.path.expanduser('~/git/Python/user_modules'))\nfrom match_coord import match_coord\n\ntime_start = time.time()\n\n# Select bricks with 300) & (cat_north['FLUX_IVAR_Z']>0)\n mask &= (cat_north['FLUX_Z_EC'] > 10**(0.4*(22.5-21.5))) | (cat_north['FIBERFLUX_Z_EC'] > 10**(0.4*(22.5-22.)))\n mask &= (cat_north['RA']>100) & (cat_north['RA']<300)\n if np.sum(mask)==0:\n continue\n\n idx = np.where(mask)[0]\n\n cat_north = fitsio.read(os.path.join(sweep_dir, sweep_fn), columns=columns, rows=idx)\n cat_north = Table(cat_north)\n cat_north['TYPE'] = cat_north['TYPE'].astype(str)\n\n pz_path = os.path.join(pz_dir, sweep_fn[:-5]+'-pz.fits')\n pz = Table(fitsio.read(pz_path, rows=idx))\n pz['survey'] = pz['survey'].astype(str)\n\n cat_north = hstack([cat_north, pz])\n\n # Apply extinction correction\n cat_north['FLUX_G_EC'] = cat_north['FLUX_G']/cat_north['MW_TRANSMISSION_G']\n cat_north['FLUX_R_EC'] = cat_north['FLUX_R']/cat_north['MW_TRANSMISSION_R']\n cat_north['FLUX_Z_EC'] = cat_north['FLUX_Z']/cat_north['MW_TRANSMISSION_Z']\n cat_north['FLUX_W1_EC'] = cat_north['FLUX_W1']/cat_north['MW_TRANSMISSION_W1']\n cat_north['FLUX_W2_EC'] = cat_north['FLUX_W2']/cat_north['MW_TRANSMISSION_W2']\n cat_north['FIBERFLUX_G_EC'] = cat_north['FIBERFLUX_G']/cat_north['MW_TRANSMISSION_G']\n cat_north['FIBERFLUX_R_EC'] = cat_north['FIBERFLUX_R']/cat_north['MW_TRANSMISSION_R']\n cat_north['FIBERFLUX_Z_EC'] = cat_north['FIBERFLUX_Z']/cat_north['MW_TRANSMISSION_Z']\n cat_north['FIBERTOTFLUX_G_EC'] = cat_north['FIBERTOTFLUX_G']/cat_north['MW_TRANSMISSION_G']\n cat_north['FIBERTOTFLUX_R_EC'] = cat_north['FIBERTOTFLUX_R']/cat_north['MW_TRANSMISSION_R']\n cat_north['FIBERTOTFLUX_Z_EC'] = cat_north['FIBERTOTFLUX_Z']/cat_north['MW_TRANSMISSION_Z']\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n\n # Quality cuts\n mask = (cat_north['NOBS_G']>=1) & (cat_north['NOBS_R']>=1) & (cat_north['NOBS_Z']>=1)\n mask &= (cat_north['TYPE']!='DUP') & (cat_north['TYPE']!='DUP ')\n \n # # Quality in r: SNR_R > 0 && RFLUX > 0\n # mask &= (cat_north['FLUX_R_EC']>0) & (cat_north['FLUX_IVAR_R']>0)\n\n # Quality in z: SNR_Z > 0 && ZFLUX > 0\n mask &= (cat_north['FLUX_Z_EC']>0) & (cat_north['FLUX_IVAR_Z']>0)\n\n # Quality in W1: FLUX_IVAR_W1 > 0 && W1FLUX > 0\n mask &= (cat_north['FLUX_W1_EC']>0) & (cat_north['FLUX_IVAR_W1']>0)\n\n # # None-stellar color: (z-w1) > 0.8*(r-z) - 1.0 => -0.8*r + 1.8*z - W1 > -1.0\n # mask_stellar = (cat_north['FLUX_R_EC']**(-0.8) * cat_north['FLUX_Z_EC']**1.8 / cat_north['FLUX_W1_EC'] < 10**(-0.4*(-1.0)))\n # # Include non-point sources\n # mask_stellar |= ((cat_north['TYPE']!='PSF') & (cat_north['TYPE']!='PSF '))\n\n # mask &= mask_stellar\n\n if np.sum(mask)>0:\n cat_north = cat_north[mask]\n else:\n continue\n\n # Remove unwanted columns\n cat_north = cat_north[columns_to_keep]\n\n ##################################### South #####################################\n\n field = 'south'\n sweep_dir = '/global/project/projectdirs/cosmo/data/legacysurvey/dr8/'+field+'/sweep/8.0'\n pz_dir = '/global/cscratch1/sd/rongpu/dr8_lrg_photoz/sweep_'+field\n cat_south = fitsio.read(os.path.join(sweep_dir, sweep_fn),\n columns=['RA', 'FLUX_Z', 'FIBERFLUX_Z', 'FLUX_IVAR_Z', 'MW_TRANSMISSION_Z'])\n cat_south = Table(cat_south)\n # Apply the (magnitude cut zmag<21.5) OR (fibermag cut zfibermag<22)\n cat_south['FLUX_Z_EC'] = cat_south['FLUX_Z']/cat_south['MW_TRANSMISSION_Z']\n cat_south['FIBERFLUX_Z_EC'] = cat_south['FIBERFLUX_Z']/cat_south['MW_TRANSMISSION_Z']\n mask = (cat_south['FLUX_Z_EC']>0) & (cat_south['FLUX_IVAR_Z']>0)\n mask &= (cat_south['FLUX_Z_EC'] > 10**(0.4*(22.5-21.5))) | (cat_south['FIBERFLUX_Z_EC'] > 10**(0.4*(22.5-22.)))\n mask &= (cat_south['RA']>100) & (cat_south['RA']<300)\n if np.sum(mask)==0:\n continue\n\n idx = np.where(mask)[0]\n\n cat_south = fitsio.read(os.path.join(sweep_dir, sweep_fn), columns=columns, rows=idx)\n cat_south = Table(cat_south)\n cat_south['TYPE'] = cat_south['TYPE'].astype(str)\n\n pz_path = os.path.join(pz_dir, sweep_fn[:-5]+'-pz.fits')\n pz = Table(fitsio.read(pz_path, rows=idx))\n pz['survey'] = pz['survey'].astype(str)\n\n cat_south = hstack([cat_south, pz])\n\n # Apply extinction correction\n cat_south['FLUX_G_EC'] = cat_south['FLUX_G']/cat_south['MW_TRANSMISSION_G']\n cat_south['FLUX_R_EC'] = cat_south['FLUX_R']/cat_south['MW_TRANSMISSION_R']\n cat_south['FLUX_Z_EC'] = cat_south['FLUX_Z']/cat_south['MW_TRANSMISSION_Z']\n cat_south['FLUX_W1_EC'] = cat_south['FLUX_W1']/cat_south['MW_TRANSMISSION_W1']\n cat_south['FLUX_W2_EC'] = cat_south['FLUX_W2']/cat_south['MW_TRANSMISSION_W2']\n cat_south['FIBERFLUX_G_EC'] = cat_south['FIBERFLUX_G']/cat_south['MW_TRANSMISSION_G']\n cat_south['FIBERFLUX_R_EC'] = cat_south['FIBERFLUX_R']/cat_south['MW_TRANSMISSION_R']\n cat_south['FIBERFLUX_Z_EC'] = cat_south['FIBERFLUX_Z']/cat_south['MW_TRANSMISSION_Z']\n cat_south['FIBERTOTFLUX_G_EC'] = cat_south['FIBERTOTFLUX_G']/cat_south['MW_TRANSMISSION_G']\n cat_south['FIBERTOTFLUX_R_EC'] = cat_south['FIBERTOTFLUX_R']/cat_south['MW_TRANSMISSION_R']\n cat_south['FIBERTOTFLUX_Z_EC'] = cat_south['FIBERTOTFLUX_Z']/cat_south['MW_TRANSMISSION_Z']\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n\n # Quality cuts\n mask = (cat_south['NOBS_G']>=1) & (cat_south['NOBS_R']>=1) & (cat_south['NOBS_Z']>=1)\n mask &= (cat_south['TYPE']!='DUP') & (cat_south['TYPE']!='DUP ')\n \n # # Quality in r: SNR_R > 0 && RFLUX > 0\n # mask &= (cat_south['FLUX_R_EC']>0) & (cat_south['FLUX_IVAR_R']>0)\n\n # Quality in z: SNR_Z > 0 && ZFLUX > 0\n mask &= (cat_south['FLUX_Z_EC']>0) & (cat_south['FLUX_IVAR_Z']>0)\n\n # Quality in W1: FLUX_IVAR_W1 > 0 && W1FLUX > 0\n mask &= (cat_south['FLUX_W1_EC']>0) & (cat_south['FLUX_IVAR_W1']>0)\n\n # # None-stellar color: (z-w1) > 0.8*(r-z) - 1.0 => -0.8*r + 1.8*z - W1 > -1.0\n # mask_stellar = (cat_south['FLUX_R_EC']**(-0.8) * cat_south['FLUX_Z_EC']**1.8 / cat_south['FLUX_W1_EC'] < 10**(-0.4*(-1.0)))\n # # Include non-point sources\n # mask_stellar |= ((cat_south['TYPE']!='PSF') & (cat_south['TYPE']!='PSF '))\n\n # mask &= mask_stellar\n\n if np.sum(mask)>0:\n cat_south = cat_south[mask]\n else:\n continue\n\n # Remove unwanted columns\n cat_south = cat_south[columns_to_keep]\n\n ##################################### Cross-matching #####################################\n \n idx1, idx2, _, _, _ = match_coord(cat_north['RA'], cat_north['DEC'], cat_south['RA'], cat_south['DEC'], search_radius=0.2)\n if len(idx1)==0:\n continue\n cat_north = cat_north[idx1]\n cat_south = cat_south[idx2]\n\n cat_north_stack.append(cat_north)\n cat_south_stack.append(cat_south)\n\n # clear cache\n gc.collect()\n\ncat_north_stack = vstack(cat_north_stack)\ncat_south_stack = vstack(cat_south_stack)\n\n# \"Fix\" bug in vstack that creates excessively long strings\ncat_north_stack['TYPE'] = cat_north_stack['TYPE'].astype('a4')\ncat_south_stack['TYPE'] = cat_south_stack['TYPE'].astype('a4')\n\nprint('Final combined catalog:', len(cat_north_stack))\n\noutput_path_north = '/global/cscratch1/sd/rongpu/dr8_lrg_photoz/lrg_extended_overlap_20190724_north.fits'\noutput_path_south = '/global/cscratch1/sd/rongpu/dr8_lrg_photoz/lrg_extended_overlap_20190724_south.fits'\ncat_north_stack.write(output_path_north)\ncat_south_stack.write(output_path_south)\n\nprint(time.strftime(\"%H:%M:%S\", time.gmtime(time.time() - time_start)))\n\n","sub_path":"sv/dr8/extended_lrg_sample_north_south_overlap.py","file_name":"extended_lrg_sample_north_south_overlap.py","file_ext":"py","file_size_in_byte":12950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"9468767","text":"# Copyright (c) 2014-present PlatformIO \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 os\nfrom fnmatch import fnmatch\n\nimport click\nimport serial\n\nfrom platformio.compat import IS_MACOS, IS_WINDOWS\nfrom platformio.device.list.util import list_logical_devices, list_serial_ports\nfrom platformio.fs import get_platformio_udev_rules_path\nfrom platformio.package.manager.platform import PlatformPackageManager\nfrom platformio.platform.factory import PlatformFactory\nfrom platformio.util import retry\n\nBLACK_MAGIC_HWIDS = [\n \"1D50:6018\",\n]\n\n\ndef parse_udev_rules_hwids(path):\n result = []\n with open(path, mode=\"r\", encoding=\"utf8\") as fp:\n for line in fp.readlines():\n line = line.strip()\n if not line or line.startswith(\"#\"):\n continue\n attrs = {}\n for attr in line.split(\",\"):\n attr = attr.replace(\"==\", \"=\").replace('\"', \"\").strip()\n if \"=\" not in attr:\n continue\n name, value = attr.split(\"=\", 1)\n attrs[name] = value\n hwid = \"%s:%s\" % (\n attrs.get(\"ATTRS{idVendor}\", \"*\"),\n attrs.get(\"ATTRS{idProduct}\", \"*\"),\n )\n if hwid != \"*:*\":\n result.append(hwid.upper())\n return result\n\n\ndef normalize_board_hwid(value):\n if isinstance(value, (list, tuple)):\n value = (\"%s:%s\" % (value[0], value[1])).replace(\"0x\", \"\")\n return value.upper()\n\n\ndef is_pattern_port(port):\n if not port:\n return False\n return set([\"*\", \"?\", \"[\", \"]\"]) & set(port)\n\n\ndef match_serial_port(pattern):\n for item in list_serial_ports():\n if fnmatch(item[\"port\"], pattern):\n return item[\"port\"]\n return None\n\n\ndef is_serial_port_ready(port, timeout=1):\n try:\n serial.Serial(port, timeout=timeout).close()\n return True\n except: # pylint: disable=bare-except\n pass\n return False\n\n\ndef find_serial_port( # pylint: disable=too-many-arguments\n initial_port,\n board_config=None,\n upload_protocol=None,\n ensure_ready=False,\n prefer_gdb_port=False,\n timeout=2,\n):\n if initial_port:\n if not is_pattern_port(initial_port):\n return initial_port\n return match_serial_port(initial_port)\n\n if upload_protocol and upload_protocol.startswith(\"blackmagic\"):\n return find_blackmagic_serial_port(prefer_gdb_port, timeout)\n if board_config and board_config.get(\"build.hwids\", []):\n return find_board_serial_port(board_config, timeout)\n port = find_known_uart_port(ensure_ready, timeout)\n if port:\n return port\n\n # pick the best PID:VID USB device\n best_port = None\n for item in list_serial_ports():\n if ensure_ready and not is_serial_port_ready(item[\"port\"]):\n continue\n port = item[\"port\"]\n if \"VID:PID\" in item[\"hwid\"]:\n best_port = port\n return best_port or port\n\n\ndef find_blackmagic_serial_port(prefer_gdb_port=False, timeout=0):\n try:\n\n @retry(timeout=timeout)\n def wrapper():\n candidates = []\n for item in list_serial_ports(filter_hwid=True):\n if (\n not any(hwid in item[\"hwid\"].upper() for hwid in BLACK_MAGIC_HWIDS)\n and not \"Black Magic\" in item[\"description\"]\n ):\n continue\n if (\n IS_WINDOWS\n and item[\"port\"].startswith(\"COM\")\n and len(item[\"port\"]) > 4\n ):\n item[\"port\"] = \"\\\\\\\\.\\\\%s\" % item[\"port\"]\n candidates.append(item)\n\n if not candidates:\n raise retry.RetryNextException()\n\n for item in candidates:\n if (\"GDB\" if prefer_gdb_port else \"UART\") in item[\"description\"]:\n return item[\"port\"]\n if IS_MACOS:\n # 1 - GDB, 3 - UART\n for item in candidates:\n if item[\"port\"].endswith(\"1\" if prefer_gdb_port else \"3\"):\n return item[\"port\"]\n\n candidates = sorted(candidates, key=lambda item: item[\"port\"])\n return (\n candidates[0] # first port is GDB?\n if len(candidates) == 1 or prefer_gdb_port\n else candidates[1]\n )[\"port\"]\n\n return wrapper()\n except retry.RetryStopException:\n pass\n return None\n\n\ndef find_board_serial_port(board_config, timeout=0):\n hwids = board_config.get(\"build.hwids\", [])\n try:\n\n @retry(timeout=timeout)\n def wrapper():\n for item in list_serial_ports(filter_hwid=True):\n hwid = item[\"hwid\"].upper()\n for board_hwid in hwids:\n if normalize_board_hwid(board_hwid) in hwid:\n return item[\"port\"]\n raise retry.RetryNextException()\n\n return wrapper()\n except retry.RetryStopException:\n pass\n\n click.secho(\n \"TimeoutError: Could not automatically find serial port \"\n \"for the `%s` board based on the declared HWIDs=%s\"\n % (board_config.get(\"name\", \"unknown\"), hwids),\n fg=\"yellow\",\n err=True,\n )\n\n return None\n\n\ndef find_known_uart_port(ensure_ready=False, timeout=0):\n known_hwids = list(BLACK_MAGIC_HWIDS)\n\n # load from UDEV rules\n udev_rules_path = get_platformio_udev_rules_path()\n if os.path.isfile(udev_rules_path):\n known_hwids.extend(parse_udev_rules_hwids(udev_rules_path))\n\n # load from installed dev-platforms\n for platform in PlatformPackageManager().get_installed():\n p = PlatformFactory.new(platform)\n for board_config in p.get_boards().values():\n for board_hwid in board_config.get(\"build.hwids\", []):\n board_hwid = normalize_board_hwid(board_hwid)\n if board_hwid not in known_hwids:\n known_hwids.append(board_hwid)\n\n try:\n\n @retry(timeout=timeout)\n def wrapper():\n for item in list_serial_ports(as_objects=True):\n if not item.vid or not item.pid:\n continue\n hwid = \"{:04X}:{:04X}\".format(item.vid, item.pid)\n for pattern in known_hwids:\n if fnmatch(hwid, pattern) and (\n not ensure_ready or is_serial_port_ready(item.device)\n ):\n return item.device\n raise retry.RetryNextException()\n\n return wrapper()\n except retry.RetryStopException:\n pass\n\n click.secho(\n \"TimeoutError: Could not automatically find serial port \"\n \"based on the known UART bridges\",\n fg=\"yellow\",\n err=True,\n )\n\n return None\n\n\ndef find_mbed_disk(initial_port):\n msdlabels = (\"mbed\", \"nucleo\", \"frdm\", \"microbit\")\n for item in list_logical_devices():\n if item[\"path\"].startswith(\"/net\"):\n continue\n if (\n initial_port\n and is_pattern_port(initial_port)\n and not fnmatch(item[\"path\"], initial_port)\n ):\n continue\n mbed_pages = [os.path.join(item[\"path\"], n) for n in (\"mbed.htm\", \"mbed.html\")]\n if any(os.path.isfile(p) for p in mbed_pages):\n return item[\"path\"]\n if item[\"name\"] and any(l in item[\"name\"].lower() for l in msdlabels):\n return item[\"path\"]\n return None\n","sub_path":"platformio/device/finder.py","file_name":"finder.py","file_ext":"py","file_size_in_byte":8049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"318061790","text":"import os.path\nimport time\nimport json\n\n\ndef log(*args, **kwargs):\n format = '%H:%M'\n timestamp = int(time.time())\n value = time.localtime(timestamp)\n dt = time.strftime(format, value)\n with open('log.txt', 'w+', encoding='utf-8') as f:\n print(dt, *args, file=f, **kwargs)\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"327447389","text":"# 了解什么是递归:在函数中调用自身函数\n\n# 能看懂递归\n# 能知道递归的应用场景\n\n\n# import sys\n# sys.setrecursionlimit(100000)\n# n = 0\n# def story():\n# global n\n# n += 1\n# print(n)\n# story()\n# story()\n\n# 如果递归次数太多,就不适合使用递归来解决问题\n# 递归的缺点:占内存\n# 递归的优点:会让代码变简单\n\n\n# 简单的算法\n# 查找:找数据\n# 排序\n# 最短路径\n# 了解基础的算法 才能创造出更好的算法\n# 不是所有的事情都能套用现成的方法解决的\n# 有些时候会用到学过的算法知识来解决新的问题\n'''\n# 二分查找算法 必须处理有序的列表\n\nl = [1,2,2,3,4,5,6,7,8,9,10,11,22,33,55,66,77,88,99]\ndef find(l,aim,start = 0,end = None):\n end = len(l) if end is None else end\n mid_indx = (end-start)//2 + start # 计算中间值\n if l[mid_indx] < aim:\n find(l,aim,start=mid_indx+1,end=end)\n elif l[mid_indx] > aim:\n find(l,aim,start=start,end=mid_indx-1)\n else:\n print('找到了',mid_indx,aim)\n pass\n\nfind(l,22)\n\n\n# 超过最大递归限制的报错\n# 只要写递归函数,必须要有结束条件\n\n\n# 返回值\n# 不要只看到return 就认为已经返回了,要看返回操作是在递归到第几层的时候发生的,然后返回给了谁\n# 如果不是返回给最外层函数,调用者就接收不到\n# 需要再分析,看如何把结果返回回来\n\n\n# 循环\n\n# 斐波那契 问第n个斐波��契数是多少\ndef fib(n):\n if n == 1 or n == 2:\n return 1\n return fib(n-1)+fib(n-2)\n pass\n\n# 可以发现效率比较低,尽量少用双递归\n'''\ndef fib1(n,l = [0]):\n l[0] +=1\n if n == 1 or n == 2:\n l[0] -= 1\n return 1,1\n else:\n a,b = fib1(n-1)\n l[0] -= 1\n if l[0] == 0:\n return a+b\n return b,a+b\n\nprint(fib1(3))\n\n","sub_path":"study/递归函数.py","file_name":"递归函数.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"468201771","text":"'''\nGood morning! Here's your coding interview problem for today.\n\nThis problem was asked by Google.\n\nGiven the root to a binary tree, implement serialize(root), which serializes \nthe tree into a string, and deserialize(s), which deserializes the string back \ninto the tree.\n\nFor example, given the following Node class\n\nclass Node:\n def __init__(self, val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\nThe following test should pass:\n\nnode = Node('root', Node('left', Node('left.left')), Node('right'))\nassert deserialize(serialize(node)).left.left.val == 'left.left'\n'''\n\nclass Node:\n def __init__(self, val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\nnode = Node('root', Node('left', Node('left.left')), Node('right'))\n\n# first cheese try, just serialize as python code recursively, \n# deserialize using eval(), bit of a security issue\n\ndef serialize(node):\n serial = 'Node(' + \"'\" + node.val + \"',\"\n serial += serialize(node.left) if node.left != None else 'None'\n serial += ',' \n serial += serialize(node.right) if node.right != None else 'None'\n serial += ')'\n return serial\n\ndef deserialize(serial):\n return eval(serial)\n\nassert deserialize(serialize(node)).left.left.val == 'left.left'\n\n# second try without eval(), less text recursive serialize, \n# deserialize by parsing with a stack\n\ndef serialize(node):\n serial = node.val + ','\n serial += serialize(node.left) if node.left != None else ''\n serial += ',' \n serial += serialize(node.right) if node.right != None else ''\n serial += ',;'\n return serial\n \ndef deserialize(serial):\n stack = []\n split = serial.split(',')\n for item in split:\n if item == ';':\n right = stack.pop()\n left = stack.pop() \n stack.append(\n Node(\n stack.pop(), \n left if left != '' else None, \n right if right != '' else None))\n else:\n stack.append(item)\n return stack.pop()\n\nassert deserialize(serialize(node)).left.left.val == 'left.left'\n","sub_path":"daily coding problems/20181221 - 3 binary tree serialization.py","file_name":"20181221 - 3 binary tree serialization.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"166138905","text":"import numpy as np \n\n# Returns the accuracy of model\n# Given two [m x 1] arrays of prediction and actual labels\ndef model_accuracy(Y_pred, Y):\n\treturn np.sum(Y_pred == Y) / Y_pred.shape[0]\n\n# Returns an array [n x 1] of model recall per class\n# Given two [m x 1] arrays of prediction and actual labels and number of classes n\n# https://stats.stackexchange.com/questions/51296/how-do-you-calculate-precision-and-recall-for-multiclass-classification-using-co\ndef model_recall(Y_pred, Y, n):\n\tclasses = (np.arange(n)).reshape((n,1))\n\ttemp_y_pred = np.repeat(Y_pred.T, n, axis = 0)\n\ttemp_y_org = np.repeat(Y.T, n, axis = 0)\n\ttp = (np.sum(np.logical_and((temp_y_pred == classes), (temp_y_org == classes)), axis = 1)).reshape(n,1)\n\ttp_fn = (np.sum((temp_y_org == classes), axis = 1)).reshape(n,1)\n\treturn tp/tp_fn\n\n# Returns an array [n x 1] of model precision per class\n# Given two [m x 1] arrays of prediction and actual labels and number of classes n\ndef model_precision(Y_pred, Y, n):\n\tclasses = (np.arange(n)).reshape((n,1))\n\ttemp_y_pred = np.repeat(Y_pred.T, n, axis = 0)\n\ttemp_y_org = np.repeat(Y.T, n, axis = 0)\n\ttp = (np.sum(np.logical_and((temp_y_pred == classes), (temp_y_org == classes)), axis = 1)).reshape(n,1)\n\ttp_fp = (np.sum((temp_y_pred == classes), axis = 1)).reshape(n,1)\n\treturn tp/tp_fp\n\n# Returns an array [n x 1] of model f1 score per class\n# Given two [m x 1] arrays of prediction and actual labels and number of classes n\ndef model_f1(Y_pred, Y, n):\n\trecall = model_recall(Y_pred, Y, n)\n\tprecision = model_precision(Y_pred, Y, n)\n\treturn 2*recall*precision/(recall + precision)\n\ndef model_macro_average(Y_pred, Y, n):\n\tmacro_recall = np.sum(model_recall(Y_pred, Y, n))/n\n\tmacro_precision = np.sum(model_precision(Y_pred, Y, n))/n\n\treturn np.asarray([macro_precision, macro_recall, 2*macro_precision*macro_recall/(macro_recall + macro_precision)])\n\ndef model_micro_average(Y_pred, Y, n):\n\tclasses = (np.arange(n)).reshape((n,1))\n\ttemp_y_pred = np.repeat(Y_pred.T, n, axis = 0)\n\ttemp_y_org = np.repeat(Y.T, n, axis = 0)\n\ttp = (np.sum(np.logical_and((temp_y_pred == classes), (temp_y_org == classes)), axis = 1)).reshape(n,1)\n\ttp_fp = (np.sum((temp_y_pred == classes), axis = 1)).reshape(n,1)\n\ttp_fn = (np.sum((temp_y_org == classes), axis = 1)).reshape(n,1)\n\t\n\tmicro_precision = np.sum(tp)/np.sum(tp_fp)\n\tmicro_recall = np.sum(tp)/np.sum(tp_fn)\n\t\n\treturn np.asarray([micro_precision, micro_recall, 2*micro_precision*micro_recall/(micro_recall + micro_precision)])\n\ndef r2_score(y_pred, y):\n\tybar = numpy.sum(y) / len(y)\n\tssreg = numpy.sum((y_pred - ybar) ** 2)\n\tsstot = numpy.sum((y - ybar) ** 2)\n\n\treturn ssreg/sstot\n\nif __name__ == \"__main__\" :\n\tprint(\"Testing Functions \\n\")\n\ta = (3*np.random.rand(10,1)).astype(\"int\")\n\tb = (3*np.random.rand(10,1)).astype(\"int\")\n\n\tprint(np.hstack((a,b)))\n\tprint(\"\\nAccuracy = %f \\n\" % model_accuracy(a,b))\n\tprint(\"\\nPrecision\")\n\tprint(model_precision(a,b,3))\n\tprint(\"\\nRecall \\n\")\n\tprint(model_recall(a,b,3))\n\tprint(\"\\nF1 Score \\n\")\n\tprint(model_f1(a,b,3))","sub_path":"src/performance_util.py","file_name":"performance_util.py","file_ext":"py","file_size_in_byte":3011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"564624931","text":"from __future__ import unicode_literals\n\nimport inspect\n\nfrom django.core.exceptions import ObjectDoesNotExist\n\nfrom giaola_role_permissions.roles import RolesManager\nfrom giaola_role_permissions.permissions import PermissionsManager\nfrom giaola_role_permissions.shortcuts import retrieve_role_safely, get_user_roles, get_permission\n\n\ndef has_role(user, roles):\n # Returns true if the user has at least one of the roles given\n # Roles can be an array or just a role\n if user and user.is_superuser:\n return True\n\n if not isinstance(roles, list):\n roles = [roles]\n\n normalized_roles = []\n for role in roles:\n role = retrieve_role_safely(role)\n normalized_roles.append(role)\n\n user_roles = get_user_roles(user)\n\n if user_roles:\n for role in normalized_roles:\n if role in user_roles:\n return True\n return False\n\ndef has_roles(user, roles):\n # Returns true if the user has all of the roles given\n # Roles can be an array or just a role\n if user and user.is_superuser:\n return True\n\n if not isinstance(roles, list):\n roles = [roles]\n\n normalized_roles = []\n for role in roles:\n role = retrieve_role_safely(role)\n normalized_roles.append(role)\n\n user_roles = get_user_roles(user)\n\n if user_roles:\n has_roles = True\n for role in normalized_roles:\n has_roles = has_roles and role in user_roles\n return has_roles\n\n return False\n\ndef has_permission(user, permission_name, role=None):\n # if superuser return true.\n # if role and user has permission for the given role return true.\n # else go through all roles and return true only if user has\n # permission for all roles that have the permission in their list.\n\n if not user:\n return False\n\n if user.is_superuser:\n return True\n\n if not permission_name:\n return False\n\n if role:\n role = retrieve_role_safely(role)\n return __has_permission_for_role__(user, permission_name, role)\n\n return __has_permission__(user, permission_name)\n\ndef __has_permission_for_role__(user, permission_name, role):\n permission = get_permission(\n role.get_permission_db_name(permission_name))\n\n if permission in user.user_permissions.all():\n return True\n\n return False\n\ndef __has_permission__(user, permission_name):\n user_roles = get_user_roles(user)\n\n if len(user_roles) == 0:\n return False\n\n permission_in_role_count = 0\n permission_true_in_role_count = 0\n for role in user_roles:\n if permission_name in role.get_available_permissions_names_list():\n permission_in_role_count += 1\n if __has_permission_for_role__(user, permission_name, role):\n permission_true_in_role_count += 1\n\n return permission_in_role_count != 0 and \\\n permission_in_role_count == permission_true_in_role_count\n\n\ndef has_object_permission(checker_name, user, obj):\n if user.is_superuser:\n return True\n\n checker = PermissionsManager.retrieve_checker(checker_name)\n roles = get_user_roles(user)\n\n return checker(roles, user, obj)\n","sub_path":"giaola_role_permissions/verifications.py","file_name":"verifications.py","file_ext":"py","file_size_in_byte":3166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"503120277","text":"import time\n\nimport matplotlib.pyplot as plt\n\nfrom c2 import c2\n\n\ndef c3():\n n_list = []\n t_list = []\n for n in range(2, 100):\n n_list.append(n)\n t0 = time.clock()\n c2(n)\n t_list.append(time.clock() - t0)\n plt.plot(n_list, t_list)\n plt.show()\n\n\nif __name__ == '__main__':\n c3()\n","sub_path":"Project 1/c3.py","file_name":"c3.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"164451879","text":"from urllib import request\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nimport pandas as pd\nimport os\n\ndef get_pages(url):\n\tres = request.urlopen(url)\n\tsoup = BeautifulSoup(res,\"html.parser\")\n\tres.close()\n\treturn soup\n\ndef get_tables(url):\n\tdata = pd.read_html(url)\n\treturn data\n\ndef get_driver(opt=None):\n\tdp = r\"C:\\driver\\94\\chromedriver.exe\"\n\toptions = Options()\n\tif opt:\n\t\toptions.add_argument('--headless')\n\treturn webdriver.Chrome(dp, options=options)\n\ndef set_login(d):\n\td.get(r\"https://regist.netkeiba.com/account/?pid=login\")\n\t# d.switch_to_window(d.window_handles[1])\n\tloginid = d.find_element_by_name(\"login_id\")\n\tpswd = d.find_element_by_name('pswd')\n\tlogbtn = d.find_element_by_class_name('loginBtn__wrap').find_element_by_tag_name('input')\n\tloginid.send_keys(os.environ['email'])\n\tpswd.send_keys(os.environ['passwd'])\n\tlogbtn.click()\n\treturn d\n","sub_path":"scraping/HorseRace/BK/scrapUtil.py","file_name":"scrapUtil.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"353725084","text":"#!/usr/bin/env python\n\n##################################################\n#\n# howdoi - a code search tool.\n# written by Benjamin Gleitzman (gleitz@mit.edu)\n# inspired by Rich Jones (rich@anomos.info)\n#\n##################################################\n\nimport urllib.request, urllib.parse, urllib.error\nimport sys\nimport json\nimport argparse\nimport re\nimport lxml.html\n\n#from pyquery import PyQuery as pq\n\nGOOGLE_SEARCH_URL = \"https://www.google.com/search?q=site:stackoverflow.com%20{0}\"\nDUCK_SEARCH_URL = \"http://duckduckgo.com/html?q=site%3Astackoverflow.com%20{0}\"\nUSER_AGENT = \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1309.0 Safari/537.17\"\n\ndef get_result(url):\n opener = urllib.request.build_opener()\n opener.addheaders = [('User-agent', USER_AGENT)]\n result = opener.open(url)\n return result.read()\n\ndef is_question(link):\n return re.search(\"^http\\:\\/\\/stackoverflow\\.com\\/questions/\\d+/\", link)\n\ndef get_google_links(query):\n links = []\n url = GOOGLE_SEARCH_URL.format(urllib.parse.quote(query))\n result = get_result(url)\n html = lxml.html.document_fromstring(result)\n for l in html.iterlinks():\n if is_question(l[2]):\n links.append(l[2])\n \n return links\n\ndef get_duck_links(query):\n url = DUCK_SEARCH_URL.format(urllib.parse.quote(query))\n result = get_result(url)\n html = lxml.html.document_fromstring(result)\n links = html.xpath(\"//a[@href]\")\n return [l.get('href', None) for l in links]\n\ndef get_link_at_pos(links, pos):\n pos = int(pos) - 1\n for link in links:\n if is_question(link):\n if pos == 0:\n break\n else:\n pos = pos - 1\n continue\n return link\n\ndef get_instructions(args):\n text = []\n links = get_google_links(args['query'])\n if not links:\n return ''\n\n link = get_link_at_pos(links, args['pos'])\n if args.get('link'):\n return link\n\n link = link + '?answertab=votes'\n page = get_result(link)\n html = lxml.html.document_fromstring(page)\n first_answer = html.xpath(\"//td[@class='answercell']\")\n tags = first_answer[0].xpath(\"code\") or first_answer[0].xpath(\"//pre\")\n if tags:\n for t in tags[0]:\n text.append(t.text_content())\n else:\n post_text = first_answer[0].xpath(\"div[@class='post-text']/p\")\n if post_text:\n for t in post_text:\n text.append(t.text_content())\n return text\n\n return \"\\n\".join(text)\n\ndef howdoi(args):\n args['query'] = ' '.join(args['query']).replace('?', '')\n instructions = get_instructions(args) or 'Sorry, couldn\\'t find any help with that topic'\n print(instructions)\n\ndef command_line_runner():\n parser = argparse.ArgumentParser(description='code search tool')\n parser.add_argument('query', metavar='QUERY', type=str, nargs=argparse.REMAINDER,\n help='the question to answer')\n parser.add_argument('-p','--pos', help='select answer in specified position (default: 1)', default=1)\n parser.add_argument('-a','--all', help='display the full text of the answer',\n action='store_true')\n parser.add_argument('-l','--link', help='display only the answer link',\n action='store_true')\n args = vars(parser.parse_args())\n howdoi(args)\n\nif __name__ == '__main__':\n command_line_runner()\n","sub_path":"howdoi/howdoi.py","file_name":"howdoi.py","file_ext":"py","file_size_in_byte":3456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"15227502","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n\nimport random\nimport time\n\nU_TOTAL = 97\nP_TOTAL = 132\nR_TOTAL = 798\n\n#drop\n#template_drop = 'drop table %s cascade constraints;\\n'\ntemplate_drop = 'drop table %s;\\n'\ntableList = ['Admin', 'User', 'Section', 'Post_Include_P_Edit', 'P_Topic', 'P_Reply', 'Attachment', 'Draft', 'Point_Purchase', 'Make_Friends', 'Download', 'Submit']\n\n#create\ncreateList = [\n 'CREATE TABLE Admin(AdminID INTEGER,Password VARCHAR(64),Email VARCHAR(64),Icon VARCHAR(64),Admin_Name VARCHAR(64),PRIMARY KEY (AdminID));\\n',\n 'CREATE TABLE User(UID INTEGER,U_AccessLevel INTEGER,Password VARCHAR(64),Email VARCHAR(64),Icon VARCHAR(64),U_Name VARCHAR(64),U_Address VARCHAR(64),PostalCode VARCHAR(32),Points INTEGER CHECK (Points > 0),AdminID INTEGER,PRIMARY KEY (UID),FOREIGN KEY (AdminID) REFERENCES Admin(AdminID));\\n',\n 'CREATE TABLE Section(SID INTEGER,S_Name VARCHAR(64),AdminID INTEGER,PRIMARY KEY (SID),FOREIGN KEY (AdminID) REFERENCES Admin(AdminID));\\n',\n 'CREATE TABLE Post_Include_P_Edit(PID INTEGER,Type INTEGER,Like_Amount INTEGER,P_Content VARCHAR(512),P_Date TIMESTAMP,UID INTEGER,AdminID INTEGER,SID INTEGER,PRIMARY KEY (PID),FOREIGN KEY (UID) REFERENCES User(UID),FOREIGN KEY (AdminID) REFERENCES Admin(AdminID),FOREIGN KEY (SID) REFERENCES Section(SID) ON DELETE CASCADE ON UPDATE CASCADE);\\n',\n 'CREATE TABLE P_Topic(T_PID INTEGER,T_Title VARCHAR(64),View_Amount INTEGER,PRIMARY KEY (T_PID));\\n',\n 'CREATE TABLE P_Reply(PID INTEGER,T_PID INTEGER,PRIMARY KEY (PID, T_PID),FOREIGN KEY (T_PID) REFERENCES P_Topic(T_PID) ON DELETE CASCADE ON UPDATE CASCADE);\\n',\n 'CREATE TABLE Attachment(AID INTEGER,A_Name VARCHAR(64),A_Size INTEGER,A_Price INTEGER,Download_Amount INTEGER,T_PID INTEGER,PRIMARY KEY (AID, T_PID),FOREIGN KEY (T_PID) REFERENCES P_Topic(T_PID) ON DELETE CASCADE ON UPDATE CASCADE);\\n',\n 'CREATE TABLE Draft(DID INTEGER,D_Title VARCHAR(64),D_Content VARCHAR(512),UID INTEGER,PRIMARY KEY (DID, UID),FOREIGN KEY (UID) REFERENCES User(UID) ON DELETE CASCADE ON UPDATE CASCADE);\\n',\n 'CREATE TABLE Point_Purchase(PPID INTEGER,PP_Amount INTEGER,PP_Date TIMESTAMP,UID INTEGER,PRIMARY KEY (PPID, UID),FOREIGN KEY (UID) REFERENCES User(UID) ON DELETE CASCADE ON UPDATE CASCADE);\\n',\n 'CREATE TABLE Make_Friends(User_UID INTEGER,Friend_UID INTEGER,PRIMARY KEY (User_UID, Friend_UID),FOREIGN KEY (User_UID) REFERENCES User(UID),FOREIGN KEY (Friend_UID) REFERENCES User(UID));\\n',\n 'CREATE TABLE Download(UID INTEGER,AID INTEGER,D_Date TIMESTAMP,PRIMARY KEY (UID, AID),FOREIGN KEY (UID) REFERENCES User(UID),FOREIGN KEY (AID) REFERENCES Attachment(AID));\\n',\n 'CREATE TABLE Submit(DID INTEGER,PID INTEGER,PRIMARY KEY (DID),FOREIGN KEY (DID) REFERENCES Draft(DID),FOREIGN KEY (PID) REFERENCES Post_Include_P_Edit(PID));\\n',\n ]\n\n#admin\nadminId = 1\ntemplate_admin = 'INSERT INTO Admin VALUE(%d, \"%s\", \"%s\", \"%s\", \"%s\");\\n'\ninitAdmin = [\n (adminId, 'admin123', 'mmxinran@gmail.com', '', 'Xinran Ma')]\n\n#user\ntemplate_user = 'INSERT INTO User VALUE(%d, %d, \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", %d, %d);\\n'\nuIds = xrange(0, U_TOTAL)\nuLevel = 0\nuPwd = 'user1314'\nmails = ['%s@gmail.com' % str(x) for x in uIds]\nicon = 'pic/default.png'\nlastName = ['James', 'Jack', 'Tom', 'Lyn', 'Mike']\nmiddleName = ['Bill', 'Jim', 'John', 'Gil', 'Mora']\nfirstName = ['Ran', 'Fan', 'Hu', 'Aki', 'Bing']\n#uName = random.choice(firstName) + ' ' + random.choice(middleName) + ' ' + random.choice(lastName)\nuAddress = ''\nuPcode = ''\nuPoints = 10\n\n#friends\ntemplate_friends = 'insert into Make_Friends value (%d, %d);\\n'\n\n#sections\ntemplate_sections = 'insert into Section value(%d, \"%s\", %d);\\n'\nsectionList = ['sport', 'news', 'music', 'movie', 'star', 'creative', 'food', 'other']\nsIds = xrange(len(sectionList))\n\n#posts\npIds = xrange(P_TOTAL)\nman = ['I', 'You', 'He', 'She', 'It', 'Ran', 'Hu', 'Aki']\nverb = ['play', 'eat', 'look', 'run with', 'fight with', 'sleep in', 'read', 'watch']\nnerb = ['food', 'cake', 'donut', 'cup cake', 'football', 'computer', 'market', 'library']\n#title = random.choice(man) + ' ' + random.choice(verb) + ' ' + random.choice(nerb)\n#content = random.choice(man) + ' ' + random.choice(verb) + ' ' + random.choice(nerb)\n#timeStamp = time.strftime('%Y%m%d%H%m%S', time.localtime())\nviewAmount = 0\ntemplate_title = 'insert into P_Topic value (%d, \"%s\", %d);\\n'\ntemplate_content = 'insert into Post_Include_P_Edit value (%d, %d, %d, \"%s\", \"%s\", %d, %d, %d);\\n'\npostType = 1\nreplyType = 2\nlikeAmount = 0\n\n#replys\ntemplate_reply = 'insert into P_Reply value (%d, %d);\\n'\nrIds = [x + P_TOTAL for x in xrange(R_TOTAL)]\n\n\ndef init():\n with open('init.sql', 'w') as f:\n #drop table\n f.write('SET FOREIGN_KEY_CHECKS=0;\\n')\n for table in tableList:\n f.write(template_drop % table)\n f.write('SET FOREIGN_KEY_CHECKS=1;\\n')\n f.write('\\n')\n #create table\n for item in createList:\n f.write(item)\n f.write('\\n')\n #insert admin\n for admin in initAdmin:\n f.write(template_admin % (admin[0], admin[1], admin[2], admin[3], admin[4]))\n f.write('\\n')\n #insert user\n for uId in uIds:\n uName = random.choice(firstName) + ' ' + random.choice(middleName) + ' ' + random.choice(lastName)\n f.write(template_user % (uId, uLevel, uPwd, mails[uId], icon, uName, uAddress, uPcode, uPoints, adminId))\n f.write('\\n')\n #insert friends\n for uId in uIds:\n for i in xrange(random.randint(0, 5)):\n fId = random.randint(0, U_TOTAL - 1)\n if uId == fId:\n continue\n f.write(template_friends % (uId, fId))\n f.write('\\n')\n #insert section\n for sId in sIds:\n f.write(template_sections % (sId, sectionList[sId], adminId))\n f.write('\\n')\n #insert post\n for pId in pIds:\n title = random.choice(man) + ' ' + random.choice(verb) + ' ' + random.choice(nerb)\n content = random.choice(man) + ' ' + random.choice(verb) + ' ' + random.choice(nerb)\n stamp = random.randint(10, 20)\n timeStamp = time.strftime('%Y%m%d%H%m%S', time.localtime(time.time() - stamp*100000))\n f.write(template_title % (pId, title, viewAmount))\n f.write(template_content % (pId, postType, likeAmount, content, timeStamp, random.choice(uIds), adminId, random.choice(sIds)))\n f.write('\\n')\n #insert post\n for rId in rIds:\n title = random.choice(man) + ' ' + random.choice(verb) + ' ' + random.choice(nerb)\n content = random.choice(man) + ' ' + random.choice(verb) + ' ' + random.choice(nerb)\n stamp = random.randint(0, 10)\n timeStamp = time.strftime('%Y%m%d%H%m%S', time.localtime(time.time() - stamp*100000))\n f.write(template_title % (rId, title, viewAmount))\n f.write(template_content % (rId, replyType, likeAmount, content, timeStamp, random.choice(uIds), adminId, random.choice(sIds)))\n f.write(template_reply % (rId, random.choice(pIds)))\n\ndef main():\n init()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"create_sql.py","file_name":"create_sql.py","file_ext":"py","file_size_in_byte":7168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"357024388","text":"# IMPORTS AND SETUP\n\n# General imports\nimport multiprocessing\nimport numpy as np\nimport pandas as pd\nimport time\nimport sys\nimport dill\nimport warnings\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom scipy.stats import pearsonr\nimport collections\nimport os\n\n# Sklearn imports\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn import model_selection\nfrom sklearn.pipeline import Pipeline\nfrom sklearn import metrics\nfrom sklearn.dummy import DummyRegressor\nfrom sklearn.linear_model import Lasso, ElasticNet\nfrom stability_selection import StabilitySelection\n\n# Add directory to sys.path in order to import custom modules from there.\nsys.path.insert(0, \"/home/kkoras/Documents/Projects/Doktorat - Modelling drug efficacy in cancer/Projects/Created Modules\")\nfrom gdsc_projects_module import DrugGenomeWide, Experiment, Modeling, ModelingResults\n\n# LOAD DATA\n# Initialize proper file pathways\ndrug_annotations = \"/home/kkoras/Documents/Projects/Doktorat - Modelling drug efficacy in cancer/Data/Original Data/Genomics of Drug Sensitivity in Cancer/Original GDSC Data/Drug annotations/Screened_Compounds-March_27th_2018.xlsx\"\ncell_line_list = \"/home/kkoras/Documents/Projects/Doktorat - Modelling drug efficacy in cancer/Data/Original Data/Genomics of Drug Sensitivity in Cancer/Original GDSC Data/Cell line list (directly from website)/Cell_listThu Aug 16 22_06_49 2018.csv\"\ngene_expr = \"/home/kkoras/Documents/Projects/Doktorat - Modelling drug efficacy in cancer/Data/Original Data/Genomics of Drug Sensitivity in Cancer/Original GDSC Data/Gene expression/sanger1018_brainarray_ensemblgene_rma-March_2nd_2017.txt\"\ncnv1 = \"/home/kkoras/Documents/Projects/Doktorat - Modelling drug efficacy in cancer/Data/Original Data/Genomics of Drug Sensitivity in Cancer/Original GDSC Data/Copy number variations/cnv_binary_1.csv\"\ncnv2 = \"/home/kkoras/Documents/Projects/Doktorat - Modelling drug efficacy in cancer/Data/Original Data/Genomics of Drug Sensitivity in Cancer/Original GDSC Data/Copy number variations/PANCANCER_Genetic_feature_cna_Mon Aug 6 16_18_51 2018 (kopia).csv\"\ncoding_variants = \"/home/kkoras/Documents/Projects/Doktorat - Modelling drug efficacy in cancer/Data/Original Data/Genomics of Drug Sensitivity in Cancer/Original GDSC Data/Mutation calls/PANCANCER_Genetic_feature_variant_Mon Aug 6 15_45_44 2018.csv\"\ndrug_response = \"/home/kkoras/Documents/Projects/Doktorat - Modelling drug efficacy in cancer/Data/Original Data/Genomics of Drug Sensitivity in Cancer/Original GDSC Data/Sensitivity profiles/v17.3_fitted_dose_response-March_27th_2018.xlsx\"\n\n# Call loading function from DrugGenomeWide class\n(drug_annotations_df, cell_lines_list_df, gene_expression_df, cnv_binary_df, \n coding_variants_df, drug_response_df) = DrugGenomeWide.load_data(\n drug_annotations, cell_line_list, gene_expr, \n cnv1, cnv2, coding_variants, drug_response)\n\n# Load gene mappings\nfilepath1 = \"/home/kkoras/Documents/Projects/Doktorat - Modelling drug efficacy in cancer/Projects/GDSC - Prediction only with data related to nominal drug targets (minimal approach)/Created data/mapping_from_ensembl_id_to_hgnc_symbol.p\"\nfilepath2 = \"/home/kkoras/Documents/Projects/Doktorat - Modelling drug efficacy in cancer/Projects/GDSC - Prediction only with data related to nominal drug targets (minimal approach)/Created data/mapping_from_hgnc_symbol_to_ensembl_id.p\"\nDrugGenomeWide.load_mappings(filepath2, filepath1) # Initialize class variables\n\n# Print shapes of created DataFrames\nprint(\"Loading summary:\")\nprint(\"Drug annotations:\", drug_annotations_df.shape)\nprint(\"Cell line list\", cell_lines_list_df.shape)\nprint(\"Gene expression\", gene_expression_df.shape)\nprint(\"CNV binary:\", cnv_binary_df.shape)\nprint(\"Coding variants:\", coding_variants_df.shape)\nprint(\"Drug response:\", drug_response_df.shape)\n\n# CREATE A DICTIONARY WITH DRUG OBJECTS\ndrugs = DrugGenomeWide.create_drugs(drug_annotations_df)\nprint(len(drugs))\n\n# MODELING SETUP\n\n# Hyperparameter space to search on\nparam_grid = {\"estimator__alpha\": [0.001, 0.01, 0.1, 1., 5., 10., 30., 50., 100., 300.],\n \"estimator__l1_ratio\": [0.0, 0.1, 0.25, 0.5, 0.75, 0.9, 1.]}\n\n\n# Create ModelingWithFeatureSelecction object\nenet_seeds = [22, 37, 44, 55, 78]\nsplit_seeds = [11, 37, 52, 71, 98]\n\n\nenet_exp = Modeling(name=\"ElasticNet genome wide without feature selection\",\n param_grid=param_grid,\n estimator_seeds=enet_seeds,\n split_seeds=split_seeds,\n n_combinations=30,\n kfolds=3,\n tuning_jobs=12,\n max_iter=2500)\n\n# Initialize new ModelingResults object\nexp_results = ModelingResults(enet_exp)\n\n# Load current ModelingResults object\n#with open(\"../Created data/Results/genome_wide-enet_over_few_data_splits_without_feature_selection.pkl\", \"rb\") as f:\n #exp_results = dill.load(f)\n\n# ITERATE OVER DRUGS\n\n# Get rid of warnings\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\ndrug_counter = 0\nlog = True # Controls verbosity during iterating over drugs\n\nfor drug_id in drugs:\n # Current drug object\n drug = drugs[drug_id]\n if (drug.name, drug_id) in exp_results.cv_results_dict:\n continue\n if drug.name == \"Camptothecin\":\n continue\n \n \n # Extract full data\n data = drug.return_full_data(drug_response_df, gene_expression_df, data_combination=[\"expression\"])\n \n if log:\n print(drug.name, data.shape)\n\n # Extract features and labels\n y = data[\"AUC\"]\n X = data.drop([\"cell_line_id\", \"AUC\"], axis=1)\n assert X.shape[1] == 17737 and X.shape[0] == y.shape[0]\n \n # Add data shapes to corresponding dictionary field in ModelingResults\n exp_results.data_shapes[(drug.name, drug_id)] = X.shape\n \n # Compute the results\n (test_results_for_splits, cv_results_for_splits, \n best_parameters_for_splits, \n dummy_for_splits, tuning_seeds_for_splits) = enet_exp.enet_model_over_data_splits(X, y, verbose=2, log=True)\n \n # Put results into appropriate fields of ModelingResults object\n exp_results.performance_dict[(drug.name, drug_id)] = test_results_for_splits\n exp_results.dummy_performance_dict[(drug.name, drug_id)] = dummy_for_splits\n exp_results.best_params_dict[(drug.name, drug_id)] = best_parameters_for_splits\n exp_results.tuning_seeds_dict[(drug.name, drug_id)] = tuning_seeds_for_splits\n exp_results.cv_results_dict[(drug.name, drug_id)] = cv_results_for_splits\n \n # Save the results\n #res_name = exp_results.name.replace(\" \", \"_\").lower() + \".pkl\n with open(\"../Created data/Results/genome_wide-enet_over_few_data_splits_without_feature_selection.pkl\", \"wb\") as f:\n dill.dump(exp_results, f)\n \n drug_counter +=1 \n print(drug_counter, \"drugs done\")\n print()\n print(\"*\" * 50)\n print()\n \nprint()\nprint(\"SCRIPT FINISHED, ALL DRUGS DONE\")\nprint()\n","sub_path":"GDSC - Prediction with genome wide gene expression/Scripts/enet_modeling_without_feat_selection_run_script.py","file_name":"enet_modeling_without_feat_selection_run_script.py","file_ext":"py","file_size_in_byte":6921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"198890985","text":"from app.newHope import bp, helpers\nfrom app.core.parser.copart.helpers.models_dict import cars_models\nfrom app.core.helpers.copart_helpers import CopartHelpers\nfrom app.forms.header_index_search_form import HeaderIndexForm\nfrom app.newHope.form.main import HomePageSearchForm\nfrom flask import request, render_template, redirect, jsonify\nfrom app.models.PostsModel import PostsModel\n\n@bp.route('/about')\ndef about_page():\n \"\"\"Main route for About Page\"\"\"\n header_form = HeaderIndexForm()\n context = {\n 'self_url': helpers.get_full_url(request),\n 'header_form': header_form\n }\n print(context['self_url'])\n return render_template('pages/about.html', context=context)\n\n\n@bp.route('/page/')\ndef pages_routes(id):\n \"\"\" Simple page routes \"\"\"\n page = PostsModel.query.get(id)\n header_form = HeaderIndexForm()\n context = {\n 'title': page.title,\n 'text': page.text,\n 'seo_title': page.seo_name,\n 'seo_description': page.seo_description,\n 'header_form': header_form\n }\n return render_template('pages/simple-text-page.html', context=context)\n\n\n@bp.route('/detail-page')\ndef detail_page():\n \"\"\" Detail page route \"\"\"\n header_form = HeaderIndexForm()\n context = {\n 'self_url': helpers.get_full_url(request),\n 'header_form': header_form\n }\n print(context['self_url'])\n return render_template('pages/detail-page.html', context=context)\n\n@bp.route('/faq')\ndef faq():\n \"\"\" FAQ route\"\"\"\n header_form = HeaderIndexForm()\n context = {\n 'self_url': helpers.get_full_url(request),\n 'header_form': header_form\n }\n print(context['self_url'])\n return render_template('pages/faq.html', context=context)\n#\n#\n# @bp.route('/text-page')\n# def text_page():\n# \"\"\" Simple text page\"\"\"\n# header_form = HeaderIndexForm()\n# context = {\n# 'self_url': helpers.get_full_url(request),\n# 'header_form': header_form\n# }\n# print(context['self_url'])\n# return render_template('pages/text-page.html', context=context)\n","sub_path":"app/newHope/routes/SimpleSiteRoutes.py","file_name":"SimpleSiteRoutes.py","file_ext":"py","file_size_in_byte":2068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"366277671","text":"# Script will stop neato lidar.\n# If the ros neato driver fails the lidar continues to\n# spin. This scrip is used to stop the spinning, especially\n# during development.\n\n# Author: Brannon Vann brannon.vann@gmail.com\n# License: MIT\n\n# Run this script: python stop_neato_lidar.py\n\nimport serial\n\ntry:\n serial = serial.Serial('/dev/ttyACM0', timeout=1)\n serial.write('setldsrotation off\\n')\n serial.write('setled buttonoff\\n')\n serial.write('testmode off\\n')\n\n # close serial port\n serial.close()\n print(\"Done stopping down neato.\")\nexcept:\n print(\"an error occurred while stoping neato lidar.\")\n","sub_path":"scripts/stop_neato.py","file_name":"stop_neato.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"17555099","text":"# -*- coding: utf-8 -*-\nfrom scrapy_redis.spiders import RedisSpider\nfrom ..items import HaodfItem1,HaodfItem\n# from haodf.spiders.hdf import item\n\nclass HdfjxSpider(RedisSpider):\n name = 'hdfjx'\n redis_key = 'urls'\n\n def parse(self, response):\n # id = item.save()\n item = HaodfItem1()\n lists = []\n datail = response.xpath('//div[@class=\"h_s_info_cons\"]/div/text()').extract()\n print('*'*100)\n print('------',id)\n detail = ''.join(datail)\n print(detail)\n lists.append(detail)\n for i,j in enumerate(lists):\n print('-'*100)\n print(i,j)\n item['detail'] =detail\n item['con'] =id\n item.save()\n yield item\n","sub_path":"haodaifu/haodf/haodf/spiders/hdfjx.py","file_name":"hdfjx.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"308774118","text":"import json\nimport os\n\nimport requests\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nos.environ[\"PYTHONWARNINGS\"] = \"ignore:Unverified HTTPS request\"\nCALIBRATE = os.getenv(\"CALIBRATE\", \"false\")\n\n\nclass DeviceRegistry:\n def __init__(self, tenant, url) -> None:\n self.tenant = tenant\n self.base_url = url\n self.calibrate_url = f\"{self.base_url}calibrate\"\n\n def insert_events(self, data):\n\n data_dict = list(data)\n measurements = []\n for row in data_dict:\n row_dict = dict(row)\n\n if f\"{CALIBRATE}\".strip().lower() == \"true\":\n time = row_dict.get(\"time\")\n device = row_dict.get(\"device\")\n pm2_5 = dict(row_dict.get(\"pm2_5\")).get(\"value\")\n pm10 = dict(row_dict.get(\"pm10\")).get(\"value\")\n temp = dict(row_dict.get(\"externalTemperature\")).get(\"value\")\n hum = dict(row_dict.get(\"externalHumidity\")).get(\"value\")\n\n row_dict[\"pm2_5\"][\"calibratedValue\"] = self.get_calibrated_value(\n device=device,\n time=time,\n humidity=hum,\n pm2_5=pm2_5,\n pm10=pm10,\n temperature=temp\n )\n\n measurements.append(row_dict)\n\n try:\n\n headers = {'Content-Type': 'application/json'}\n url = self.base_url + \"devices/events?tenant=\" + self.tenant\n json_data = json.dumps(measurements)\n\n response = requests.post(url, json_data, headers=headers, verify=False)\n\n if response.status_code == 200:\n print(response.json())\n else:\n print(\"Device registry failed to insert values. Status Code : \" + str(response.status_code))\n print(response.content)\n print(response.request.url)\n print(response.request.body)\n\n except Exception as ex:\n print(\"Error Occurred while inserting measurements: \" + str(ex))\n\n def get_calibrated_value(self, device, time, pm2_5, pm10, temperature, humidity):\n print(\"getting calibrated value\")\n\n data = {\n \"datetime\": time,\n \"raw_values\": [\n {\n \"device_id\": device,\n \"pm2.5\": pm2_5,\n \"pm10\": pm10,\n \"temperature\": temperature,\n \"humidity\": humidity\n }\n ]\n }\n\n try:\n headers = {'Content-Type': 'application/json'}\n post_request = requests.post(url=self.calibrate_url, data=json.dumps(data), timeout=60000, headers=headers)\n except Exception as ex:\n print(f\"Calibrate Url returned an error: {str(ex)}\")\n return None\n\n if post_request.status_code != 200:\n print('\\n')\n print(f\"Calibrate failed to return values. Status Code : \"\n f\"{str(post_request.status_code)}, Url : {self.calibrate_url}, Body: {data}\")\n print(post_request.content)\n print('\\n')\n return None\n\n try:\n response = post_request.json()\n\n calibrated_value = None\n for result in response:\n if \"calibrated_value\" in result:\n calibrated_value = result[\"calibrated_value\"]\n break\n return calibrated_value\n\n except Exception as ex:\n print(f\"Error processing calibrate response: {str(ex)}\")\n return None\n","sub_path":"src/data-mgt/python/events-consumer/deviceRegistry.py","file_name":"deviceRegistry.py","file_ext":"py","file_size_in_byte":3577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"93134680","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: Shane Caldwell, Steph Rivera\n\"\"\"\n\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport pandas as pd\nfrom dash.dependencies import Input, Output\nimport plotly.graph_objs as go\nimport numpy as np\n\n# Import your dataframe from a csv with pandas\ndf = pd.read_csv('data/kiva_loans.csv')\n\ndef split_borrower_gender(l):\n m = 0\n f = 0\n if type(l) != list:\n return np.nan\n for i in l:\n if i== 'male':\n m += 1\n else:\n f += 1\n if m == 0:\n return 'female'\n elif f == 0:\n return 'male'\n else:\n return 'both'\n\ndf.borrower_genders = df.borrower_genders.str.split(', ').apply(split_borrower_gender)\n\ntop5 = df.groupby('activity').size().sort_values(ascending=False)[0:5] # lets look at top 5\n\ntop5_male = df.groupby('activity').size().sort_values(ascending=False)[0:5]\n\ntop5_female = df[df.borrower_genders == 'female'].groupby('activity').size().sort_values(ascending=False)[0:5]\n\n# Create a Dash object instance\napp = dash.Dash()\n\n# The layout attribute of the Dash object, app\n# is where you include the elements you want to appear in the\n# dashboard. Here, dcc.Graph and dcc.Slider are separate\n# graph objects. Most of Graph's features are defined\n# inside the function update_figure, but we set the id\n# here so we can reference it inside update_figure\napp.layout = html.Div(className='container', children=[\n html.H1(\n children='Top 5 activities for loans',\n style={\n 'textAlign': 'center', # center the header\n 'color': '#7F7F7F'\n # https://www.biotechnologyforums.com/thread-7742.html more color code options\n }\n ),\n html.Div(dcc.Graph( # add a bar graph to dashboard\n id='top5-by-gender',\n figure={\n 'data': [\n {\n 'x': top5_male.index,\n 'y': top5_male,\n 'type': 'bar',\n 'opacity': .6 # changes the bar chart's opacity\n }\n ]\n }\n )),\n \n html.Label('Gender'),\n dcc.RadioItems(\n id = 'gender-radio',\n options=[\n {'label': 'Male', 'value': 'male'},\n {'label': 'Female', 'value': 'female'},\n {'label': 'Both', 'value': 'both'}\n ],\n value='both'\n )\n ])\n\n@app.callback(\n dash.dependencies.Output('top5-by-gender', 'figure'),\n [dash.dependencies.Input('gender-radio', 'value')])\ndef update_barchart(gender):\n top5 = df[df.borrower_genders == gender].groupby('activity').size().sort_values(ascending=False)[0:5]\n return {\n 'data': [\n {\n 'x': top5.index,\n 'y': top5,\n 'type': 'bar',\n 'opacity': .6\n }\n ]\n }\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n","sub_path":"gender_bar_chart.py","file_name":"gender_bar_chart.py","file_ext":"py","file_size_in_byte":2981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"107126870","text":"#Code by John Allison, 24-09-2014\ncool_list = [\"George\", \"John\", \"Lee\", \"George\"] #Defines cool_list\nuncool_list = [\"Nick\", \"Jason\", \"Trent\"] #Defines uncool_list\ndef coolometer(name):\n if name in cool_list:\n result = \"Cool\"\n elif name in uncool_list:\n result = \"Super uncool\"\n else:\n result = \"Uncool\"\n\n return result\n\nprint(coolometer(\"Lee\"))\nprint(coolometer(\"Ian Iguana\"))\nprint(coolometer(\"Jason\"))\n\n","sub_path":"Python Programs/Coolometer.py","file_name":"Coolometer.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"20867916","text":"#!/usr/bin/env python\nimport collections\nimport errno\nimport filecmp\nimport os\nimport shlex\nimport shutil\nimport subprocess\n\nimport f90nml\n\n#NPROCS_MAX = 576\nNPROCS_MAX = 480\n#NPROCS_MAX = 32\nDOC_LAYOUT = 'MOM_parameter_doc.layout'\nverbose = False\n\n\ndef regressions():\n base_path = os.getcwd()\n regressions_path = os.path.join(base_path, 'regressions')\n regression_tests = get_regression_tests(regressions_path)\n\n # Check output\n if (verbose):\n for compiler in regression_tests:\n print('{}: ['.format(compiler))\n for config in regression_tests[compiler]:\n print(' {}:'.format(config))\n for reg, test in regression_tests[compiler][config]:\n print(' {}'.format(reg))\n print(' {}'.format(test))\n print(']')\n\n n_tests = sum(len(t) for t in regression_tests['pgi'].values())\n print('Number of tests: {}'.format(n_tests))\n\n for compiler in regression_tests:\n for mode in ('repro',):\n running_tests = []\n for config in regression_tests[compiler]:\n for reg_path, test_path in regression_tests[compiler][config]:\n test = RegressionTest()\n test.refpath = reg_path\n test.runpath = test_path\n\n prefix = os.path.join(base_path, 'regressions', config)\n test.name = reg_path[len(prefix + os.sep):]\n\n mom_layout_path = os.path.join(test.runpath, 'MOM_layout')\n if os.path.isfile(mom_layout_path):\n layout_params = parse_mom6_param(mom_layout_path)\n layout = layout_params['LAYOUT']\n ocean_ni, ocean_nj = (int(n) for n in layout.split(','))\n\n masktable = layout_params.get('MASKTABLE')\n if masktable:\n n_mask = int(masktable.split('.')[1])\n else:\n n_mask = 0\n else:\n layout_path = os.path.join(test.runpath, DOC_LAYOUT)\n params = parse_mom6_param(layout_path)\n\n # If a run crashes, its proc count may be incorrect\n # TODO: Re-checkout the files?\n if not any(p in params for p in ('NIPROC', 'NJPROC')):\n print('ERROR: {} missing CPU layout'.format(test.name))\n continue\n\n ocean_ni = int(params['NIPROC'])\n ocean_nj = int(params['NJPROC'])\n\n n_mask = 0\n\n input_nml_path = os.path.join(test.runpath, 'input.nml')\n input_nml = f90nml.read(input_nml_path)\n coupler_nml = input_nml.get('coupler_nml', {})\n atmos_npes = coupler_nml.get('atmos_npes', 0)\n ocean_npes = coupler_nml.get('ocean_npes')\n\n if ocean_npes:\n assert(ocean_npes == ocean_ni * ocean_nj)\n else:\n ocean_npes = ocean_ni * ocean_nj\n\n nprocs = (ocean_npes - n_mask) + atmos_npes\n\n # XXX: I am running both in the same directory!!\n #for grid in ('dynamic', 'dynamic_symmetric'):\n for grid in ('dynamic_symmetric', ):\n # OBC tests require symmetric grids\n if (os.path.basename(test_path) == 'circle_obcs' and\n grid != 'dynamic_symmetric'):\n continue\n\n exe_path = os.path.join(\n base_path, 'MOM6-examples', 'build', compiler,\n mode, grid, config, 'MOM6'\n )\n\n if nprocs > NPROCS_MAX:\n print('{}: skipping {} ({} ranks)'.format(\n compiler, test.name, nprocs\n ))\n continue\n\n # Set up output directories\n # TODO: Ditch logpath, keep paths to stats file\n test.logpath = os.path.join(\n base_path, 'output', config, grid, test.name\n )\n mkdir_p(test.logpath)\n\n stdout_path = os.path.join(test.logpath, compiler + '.out')\n stderr_path = os.path.join(test.logpath, compiler + '.err')\n\n test.stdout = open(stdout_path, 'w')\n test.stderr = open(stderr_path, 'w')\n\n # FMS requires an existing RESTART directory\n os.chdir(test_path)\n mkdir_p('RESTART')\n\n # Stage the Slurm command\n srun_flags = ' '.join([\n '-mblock',\n '--exclusive',\n '-n {}'.format(nprocs),\n ])\n\n cmd = '{launcher} {flags} {exe}'.format(\n launcher='srun',\n flags=srun_flags,\n exe=exe_path\n )\n\n if (verbose):\n print(' Starting {}...'.format(test.name))\n\n proc = subprocess.Popen(\n shlex.split(cmd),\n stdout=test.stdout,\n stderr=test.stderr,\n )\n test.process = proc\n\n running_tests.append(test)\n\n print('{}: Running {} tests.'.format(compiler, len(running_tests)))\n\n # Wait for processes to complete\n # TODO: Cycle through and check them all, not just the first slow one\n for test in running_tests:\n test.process.wait()\n\n # Check if any runs exited with an error\n if all(test.process.returncode == 0 for test in running_tests):\n print('{}: Tests finished, no errors!'.format(compiler))\n else:\n for test in running_tests:\n if test.process.returncode != 0:\n print('{}: Test {} failed with code {}'.format(\n compiler, test.name, test.process.returncode\n ))\n\n # Process cleanup\n # TODO: Make a class method\n for test in running_tests:\n # Store the stats files\n stat_files = [\n f for f in os.listdir(test.runpath)\n if f.endswith('.stats')\n ]\n for fname in stat_files:\n src = os.path.join(test.runpath, fname)\n dst = os.path.join(test.logpath, fname) + '.' + compiler\n shutil.copy(src, dst)\n\n # Add to logs\n test.stats.append(dst)\n\n test.stdout.close()\n test.stderr.close()\n\n # Compare stats to reference\n test_results = {}\n for test in running_tests:\n test_results[test.name] = test.check_stats()\n\n if any(result == False for result in test_results.values()):\n for test in test_results:\n if test_results[test] == False:\n print('FAIL: {}'.format(test))\n else:\n print('{}: No regressions, test passed!'.format(compiler))\n\n\ndef get_regression_tests(reg_path, test_dirname='MOM6-examples'):\n regression_tests = {}\n\n model_configs = os.listdir(reg_path)\n for config in model_configs:\n config_path = os.path.join(reg_path, config)\n for path, _, files in os.walk(config_path):\n # TODO: symmetric and static support\n compilers = tuple(\n os.path.splitext(f)[1].lstrip('.')\n for f in files if f.startswith('ocean.stats')\n )\n if compilers:\n reg_dirname = os.path.basename(reg_path.rstrip(os.sep))\n r_s = path.index(reg_dirname)\n r_e = r_s + len(reg_dirname)\n test_path = path[:r_s] + test_dirname + path[r_e:]\n\n for compiler in compilers:\n if not compiler in regression_tests:\n regression_tests[compiler] = collections.defaultdict(list)\n\n test_record = path, test_path\n regression_tests[compiler][config].append(test_record)\n\n return regression_tests\n\n\ndef parse_mom6_param(path):\n params = {}\n with open(path) as param_file:\n for line in param_file:\n param_stmt = line.split('!')[0].strip()\n if param_stmt:\n key, val = [s.strip() for s in param_stmt.split('=')]\n params[key] = val\n return params\n\n\ndef mkdir_p(path):\n try:\n os.makedirs(path)\n except EnvironmentError as exc:\n if exc.errno != errno.EEXIST:\n raise\n\n\nclass RegressionTest(object):\n def __init__(self):\n self.runpath = None\n self.logpath = None\n self.refpath = None\n\n self.stats = []\n\n self.process = None\n\n self.stdout = None\n self.stderr = None\n\n def check_stats(self):\n \"\"\"Compare test stat results with regressions.\"\"\"\n\n ref_stats = [\n os.path.join(self.refpath, os.path.basename(stat))\n for stat in self.stats\n ]\n\n if self.stats:\n match = all(\n filecmp.cmp(ref, stat)\n for ref, stat in zip(ref_stats, self.stats)\n )\n else:\n match = False\n\n return match\n\n\nif __name__ == '__main__':\n regressions()\n","sub_path":"run_regressions.py","file_name":"run_regressions.py","file_ext":"py","file_size_in_byte":10064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"540357011","text":"from multiprocessing import Process,Event\nfrom urllib.request import urlretrieve,Request,urlopen\nfrom time import sleep\nimport os,re,sys,argparse,urllib\n\noptions = { #replace with settings file later\n \"concurrentDownloads\":1,\n \"downloadProgress\":False,\n \"retryDelay\":5\n}\n\ndownloadCount = 0\ndownloaders = []\ndownloaderArgs = []\ndownloadersDone = []\n\n\"\"\"\nDLProgressTracker = []\ndef DLProgress(blocks,blockSize,totalSize,percent=101): #display download progress every 25%\n global DLProgressTracker\n status = int((blocks*blockSize/totalSize)*100)\n if status == 0 and status not in DLProgressTracker:\n DLProgressTracker.append(clock())\n if status%percent == 0:\n if status not in DLProgressTracker:\n DLProgressTracker.append(status)\n #stdout.write(basename(argv[2])+\" progress: \"+str(status)+\"%% (%0.2fMB) of %0.2fMB\"%(blocks*blockSize/1024/1024,totalSize/1024/1024)+\"\\n\")\n #stdout.flush()\n if status == 100:\n stdout.write(basename(argv[2])+\" finished with avg download speed of %0.2fMB/s\"%((totalSize/1024/1024)/(clock()-DLProgressTracker[0]))+\"\\n\")\n stdout.flush()\n #DLProgressTracker = [] #not necessary, since the function is only used once\n\"\"\"\n\ndef downloader(url,target,e=None):\n req = Request(url,headers={\"User-agent\":\"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36\"})\n if not os.path.exists(os.path.dirname(target)):\n os.mkdir(os.path.dirname(target))\n file = open(target,\"wb\")\n success = False\n retries = 0\n while not success and retries < 7:\n try:\n file.write(urlopen(req).read())\n success = True\n except urllib.error.HTTPError as e:\n print(\"HTTP Error:\")\n print(e)\n sleep(options[\"retryDelay\"])\n retries += 1\n \n file.close()\n if e != None:\n e.set()\n\n\n#DL([\"http://www.newgrounds.com/audio/download/626468\"],[\"file.mp3\"])\ndef DL(urlList, targetList):\n global downloadCount\n args = [(urlList[x], targetList[x]) for x in range(len(urlList))]\n while args != []:\n shift = 0\n for i in range(downloadCount):\n if downloaderArgs[i+shift][2].is_set():\n del(downloaders[i+shift])\n print(\"Finished downloading \"+os.path.basename(downloaderArgs[i+shift][1]))\n del(downloaderArgs[i+shift])\n downloadCount -= 1\n shift -= 1\n if downloadCount >= options[\"concurrentDownloads\"]:\n sleep(0.1)\n else:\n while downloadCount < options[\"concurrentDownloads\"] and args != []:\n arg = [x for x in args.pop()]\n arg.append(Event())\n arg = tuple(arg)\n downloaders.append(Process(target=downloader,args=arg))\n downloaders[-1].start()\n downloaderArgs.append(arg)\n print(\"Started downloading \"+os.path.basename(arg[1]))\n downloadCount += 1\n \n\ndef getFiles(username,folder=\".\\\\\",dlType=\"audio\"):\n matches = []\n matches_genres = []\n page_i = 1\n more = True\n while more:\n url = \"https://\"+username+\".newgrounds.com/\"+dlType+\"/page/\"+str(page_i)\n print(\"Fetching '{}'...\".format(url))\n req = Request(url, headers={\"User-agent\":\"Mozilla/5.0\", \"x-requested-with\": \"XMLHttpRequest\"})\n page = str(urlopen(req).read(),encoding=\"UTF-8\")\n matches += re.findall('', page)\n matches_genres += re.findall('detail-genre.*?(?:\\s)+([ \\w]+).*?div>', page)\n more = re.search(\"\\\"more\\\"\\:null\", page) is None\n page_i += 1\n print(\"Found {} songs.\".format(str(len(matches))))\n urls = [\"https://www.newgrounds.com/audio/download/{}/\".format(matches[i][0]) for i in range(len(matches))]\n files = [folder+username+\"\\\\\"+matches_genres[i].replace(\"Song\",\"\").strip()+\"\\\\\"+matches[i][1]+\".mp3\" for i in range(len(matches))]\n if not os.path.exists(folder+username):\n os.mkdir(folder+username)\n \n DL(urls,files)\n\n\ndef getArgParser():\n p = argparse.ArgumentParser(description=\"Newgrounds music downloader\")\n p.add_argument(\"-n\", type=int, default=4, dest=\"threads\", help=\"Sets the number of files to download concurrently. Should speed up downloads on fast connections.\")\n p.add_argument(\"-t\", type=float, default=5, dest=\"delay\", help=\"Delay (in seconds) to wait before retrying a failed download.\")\n p.add_argument(\"username\", nargs=\"+\", help=\"List of usernames whose songs you wish to download.\")\n return p\n\n\nif __name__ == '__main__':\n args = getArgParser().parse_args()\n options[\"concurrentDownloads\"] = args.threads\n options[\"retryDelay\"] = args.delay\n for user in args.username:\n print(\"\\n\\nParsing {}...\".format(user))\n getFiles(user)\n \n \n","sub_path":"downloader.py","file_name":"downloader.py","file_ext":"py","file_size_in_byte":4957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"563236354","text":"import os #importing operating system information.\r\nimport bpy #importing blender info.\r\nimport sys\r\n\r\nfor env in os.environ:\r\n print(env)\r\n \r\nfor arg in sys.argv:\r\n print(arg)\r\n \r\nbpy.ops.object.select_all(action='DESELECT')\r\nfor obj in bpy.data.objects:\r\n if obj.type == 'MESH':\r\n obj.select_set(True)\r\nbpy.ops.object.delete()\r\n\r\npath = curuthers/'curuthers.obj'\r\nbpy.ops.import_scene.obj(filepath=path)\r\nobj = bpy.context.selected_objects[0]\r\n","sub_path":"Lab_11.py","file_name":"Lab_11.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"402945923","text":"import os\nfrom functools import partial\nfrom multiprocessing.dummy import Pool\nfrom subprocess import call\nfrom termcolor import colored\n\n\nbase_dir = '/data/SUNCG'\nwith open(os.path.join(base_dir, 'train_sceneId.txt')) as file:\n train_ids = file.read().splitlines()\nwith open(os.path.join(base_dir, 'test_sceneId.txt')) as file:\n test_ids = file.read().splitlines()\nscene_ids = train_ids + test_ids\ncommands = ['./process_houses.sh %s' % os.path.join(base_dir, 'house', scene_id) for scene_id in scene_ids]\n\nnproc = 8\npool = Pool(nproc)\nfor idx, return_code in enumerate(pool.imap(partial(call, shell=True), commands)):\n if return_code != 0:\n print(colored('Command \\\"%s\\\" failed' % commands[idx], 'yellow'))\n else:\n print(colored('-- Processed %d/%d' % (idx + 1, len(commands)), 'white', 'on_blue'))\n","sub_path":"parallel_process.py","file_name":"parallel_process.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"219683091","text":"import pickle\ndef writePickle( Variable, fname):\n filename = fname +\".pkl\"\n f = open(\"pickle_vars/\"+filename, 'wb')\n pickle.dump(Variable, f)\n f.close()\ndef readPickle(fname):\n filename = \"../pickle_vars/\"+fname +\".pkl\" # notice the ../ addition to reach out to variables from the parent directory\n f = open(filename, 'rb')\n obj = pickle.load(f)\n f.close()\n return obj\n\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Conv2D, Flatten, MaxPooling2D\n\n#import variables\nX_train_RID = readPickle(\"cnn_data_inputs/RID_Keras/X_train_RID\")\nX_dev_RID = readPickle(\"cnn_data_inputs/RID_Keras/X_dev_RID\")\nX_test_RID = readPickle(\"cnn_data_inputs/RID_Keras/X_test_RID\")\ny_train_RID = readPickle(\"cnn_data_inputs/RID_Keras/y_train_RID\")\ny_dev_RID = readPickle(\"cnn_data_inputs/RID_Keras/y_dev_RID\")\ny_test_RID = readPickle(\"cnn_data_inputs/RID_Keras/y_test_RID\")\nmax_line = 20\nmax_song = 100\nArtist2id = readPickle(\"indexing/Artist2id\")\n\n\n# create a sequential model\nmodel = Sequential()\n\n# add model layers\nmodel.add(Conv2D(32, kernel_size=3, padding = \"same\", activation=\"relu\", input_shape=(max_song,max_line,1)))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Conv2D(64, kernel_size=3, padding = \"same\", activation=\"relu\"))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\nmodel.add(Flatten())\nmodel.add(Dense(len(list(Artist2id.keys())), activation=\"softmax\")) #here we need to find the length \\\n # of the potential labels\n\n# compile all the layers \nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n# train the model using the development set\nmodel.fit(X_train_RID, y_train_RID, validation_data=(X_dev_RID, y_dev_RID), epochs=25, batch_size=128)\n\n\n# save the predictions on the test set\npredictions = model.predict(X_test_RID)\n\n# save the predictions in a pickle file that is later to be used for evaluation:\nwritePickle(predictions, \"predictions_RID_33\")\n\n# show the accuracy of the trained model on test set\nscore = model.evaluate(X_test_RID, y_test_RID, verbose=0)\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])\n\n# show the model summary and save the model\nmodel.summary()\nmodel.save(\"../Saved_Models/RID_25ep_128bch_025Drop_33filter\")\n","sub_path":"Modeling/Model Training/RID.py","file_name":"RID.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"233756002","text":"import logging\nimport os\nfrom nameko.rpc import rpc\nfrom nameko.messaging import consume\nfrom nameko.extensions import DependencyProvider\nfrom kombu.messaging import Queue, Exchange\nimport bson.json_util\nfrom nameko_slack import web, rtm\n\n_log = logging.getLogger(__name__)\n\n\nclass ErrorHandler(DependencyProvider):\n\n def worker_result(self, worker_ctx, res, exc_info):\n if exc_info is None:\n return\n exc_type, exc, tb = exc_info\n _log.error(str(exc))\n\n\nclass NotifierServiceError(Exception):\n pass\n\n\nclass NotifierService(object):\n name = 'notifier'\n misaki = web.Slack('misaki')\n error = ErrorHandler()\n\n @property\n def channel(self):\n return f'#{os.getenv(\"NOTIFICATION_CHANNEL\", \"notifications\")}'\n\n @staticmethod\n def _format_notification(input_):\n keys = ('id', 'source', 'type', 'content')\n if not all(k in input_.keys() for k in keys):\n raise NotifierServiceError('Some keys are missing in the input dict')\n blocks = [{\n 'type': 'section',\n 'text': {\n 'type': 'mrkdwn',\n 'text': f'*{input_[\"content\"]}*',\n }\n },\n {\n 'type': 'context',\n 'elements': [{'type': 'mrkdwn', 'text': f'{k}: {input_[k]}'}\n for k in input_ if k != 'content']\n }]\n return blocks\n\n @consume(queue=Queue(name='evt_all_notifications',\n exchange=Exchange(name='all_notifications', type='topic', auto_delete=True)))\n def handle_all_notifications(self, payload):\n _log.info(f'Received {payload}')\n input_ = bson.json_util.loads(payload)\n self.misaki.api_call('chat.postMessage', \n channel=self.channel, blocks=self._format_notification(input_), text=input_['content'])\n\n @rpc\n def send_to_slack(self, channel, msg, image_url=None, context=None):\n _log.info(f'Sending message {msg} to slack channel {channel} ...')\n slack_msg = [\n {\n 'type': 'section',\n 'text': {\n 'type': 'mrkdwn',\n 'text': f'*{msg}*'\n }\n }\n ]\n if image_url:\n slack_msg.extend([\n {\n 'type': 'section',\n 'text': {\n 'type': 'mrkdwn',\n 'text': f'Please find your image at the following <{image_url}|link>'\n }\n },\n {\n 'type': 'image',\n 'image_url': image_url,\n 'alt_text': 'Can not be displayed here'\n }\n ])\n if context:\n slack_msg.append({\n 'type': 'context',\n 'elements': [{'type': 'mrkdwn', 'text': context}]\n })\n self.misaki.api_call('chat.postMessage', \n channel=channel, blocks=slack_msg, text=msg)\n\n @rtm.handle_message\n def handle_any_event(self, event, message):\n _log.info(event)\n _log.info(message)\n","sub_path":"application/services/notifier.py","file_name":"notifier.py","file_ext":"py","file_size_in_byte":3102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"408510586","text":"#pylint: disable-all\n\nfrom aqt import mw\nfrom aqt.utils import showInfo\nfrom aqt.qt import *\nfrom anki.hooks import wrap\n\nfrom aqt.utils import showInfo\n\nimport os\nimport random\n\nmw.showdogs = {}\nmw.showdogs['card_count'] = 0\nmw.showdogs['interval'] = 10\n\nclass DogDialog(QDialog):\n\n def keyPressEvent(self, event):\n\n # why does it have to be hex? nobody knows.\n # 0x20 == spacebar\n if event.key() == 0x20:\n self.close()\n\n\ndef showDog():\n mw.showdogs['card_count'] = mw.showdogs['card_count'] + 1\n if mw.showdogs['card_count'] % mw.showdogs['interval'] != 0:\n return\n\n dialog = DogDialog(mw)\n\n layout = QVBoxLayout(dialog)\n dialog.setLayout(layout)\n\n dogs_dir = os.path.join(mw.pm.addonFolder(), 'showdogs')\n\n image_path = random.choice(os.listdir(dogs_dir))\n data = open(os.path.join(dogs_dir, image_path), 'r').read()\n\n image = QImage()\n image.loadFromData(data)\n\n label = QLabel()\n myPixmap = QPixmap(os.path.join(dogs_dir, image_path))\n myScaledPixmap = myPixmap.scaled(label.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)\n label.setPixmap(myScaledPixmap)\n label.show()\n layout.addWidget(label)\n\n dialog.exec_()\n\nmw.reviewer.nextCard = wrap(mw.reviewer.nextCard, showDog)\n","sub_path":"showdogs.py","file_name":"showdogs.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"334442583","text":"# standard python imports\nimport os\nimport time\nimport json\nimport hashlib\nimport datetime\n\n\n# external imports\nfrom sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound\n\n\n# internal imports\nfrom main.app import db, message_queue, storage_manager\nfrom main.resources.models import Resource, ResourceRevision, Thumbnail\nfrom main.resources.file_conversion import compute_thumbnail\nfrom main.users.permissions import ACCESS_LEVEL_WRITE, ACCESS_TYPE_ORG_USERS, ACCESS_TYPE_ORG_CONTROLLERS\n\n\n\n# get the number corresponding to a resource type (given by a string name)\ndef resource_type_number(type_name):\n if type_name == 'basic_folder' or type_name == 'basicFolder':\n return Resource.BASIC_FOLDER\n elif type_name == 'organization_folder' or type_name == 'organizationFolder':\n return Resource.ORGANIZATION_FOLDER\n elif type_name == 'controller_folder' or type_name == 'controllerFolder':\n return Resource.CONTROLLER_FOLDER\n elif type_name == 'remote_folder' or type_name == 'remoteFolder':\n return Resource.REMOTE_FOLDER\n elif type_name == 'file':\n return Resource.FILE\n elif type_name == 'sequence':\n return Resource.SEQUENCE\n elif type_name == 'app':\n return Resource.APP\n\n\n# fix(soon): remove this\ndef _create_folders(path):\n parts = path.split('/')\n parent = None\n for part in parts:\n try:\n if parent:\n resource = Resource.query.filter(Resource.parent_id == parent.id, Resource.name == part, Resource.deleted == False).one()\n else:\n resource = Resource.query.filter(Resource.parent_id == None, Resource.name == part, Resource.deleted == False).one()\n except NoResultFound:\n resource = Resource()\n resource.parent_id = parent.id\n resource.organization_id = parent.organization_id\n resource.name = part\n resource.type = Resource.BASIC_FOLDER\n resource.creation_timestamp = datetime.datetime.utcnow()\n resource.modification_timestamp = resource.creation_timestamp\n db.session.add(resource)\n db.session.commit()\n except MultipleResultsFound:\n print('create_folders: duplicate folder at %s in %s' % (part, path))\n parent = resource\n return parent\n\n\n# create a file-type resource with the given contents and other attributes;\n# returns the newly created resource record object (or existing resource if already exists)\n# fix(soon): remove this\ndef _create_file(file_name, creation_timestamp, modification_timestamp, contents):\n last_slash = file_name.rfind('/')\n path = file_name[:last_slash]\n short_file_name = file_name[last_slash+1:]\n folder = _create_folders(path)\n\n # check for existing resource with same name\n try:\n resource = Resource.query.filter(Resource.parent_id == folder.id, Resource.name == short_file_name, Resource.deleted == False).one()\n new_resource = False\n except NoResultFound:\n\n # create new resource record\n resource = Resource()\n resource.parent_id = folder.id\n resource.organization_id = folder.organization_id\n resource.name = short_file_name\n resource.creation_timestamp = creation_timestamp\n resource.type = Resource.FILE\n new_resource = True\n\n # update or init resource record\n resource.deleted = False\n resource.modification_timestamp = modification_timestamp\n if resource.type != Resource.SEQUENCE:\n if resource.system_attributes:\n system_attributes = json.loads(resource.system_attributes)\n else:\n system_attributes = {}\n system_attributes['hash'] = hashlib.sha1(contents).hexdigest()\n system_attributes['size'] = len(contents)\n resource.system_attributes = json.dumps(system_attributes)\n if new_resource:\n db.session.add(resource)\n db.session.commit()\n\n # write file contents to a resource revision (possibly bulk storage)\n add_resource_revision(resource, modification_timestamp, contents)\n db.session.commit()\n\n # compute thumbnail for images\n if file_name.endswith('.png') or file_name.endswith('.jpg'): # fix(soon): handle more types, capitalizations\n for width in [120]: # fix(soon): what will be our standard sizes?\n (thumbnail_contents, thumbnail_width, thumbnail_height) = compute_thumbnail(contents, width) # fix(later): if this returns something other than requested width, we'll keep missing the cache\n thumbnail = Thumbnail()\n thumbnail.resource_id = resource.id\n thumbnail.width = thumbnail_width\n thumbnail.height = thumbnail_height\n thumbnail.format = 'jpg'\n thumbnail.data = thumbnail_contents\n db.session.add(thumbnail)\n db.session.commit()\n return resource\n\n\n# fix(soon): make leading slash required\n# find a resource given it's full name with path\ndef find_resource(file_name):\n file_name = file_name.strip('/')\n parts = file_name.split('/')\n parent = None\n for part in parts:\n try:\n if parent:\n resource = Resource.query.filter(Resource.parent_id == parent.id, Resource.name == part, Resource.deleted == False).one()\n else:\n resource = Resource.query.filter(Resource.parent_id == None, Resource.name == part, Resource.deleted == False).one()\n except NoResultFound:\n return None\n except MultipleResultsFound:\n print('find_resource/MultipleResultsFound: %s' % file_name)\n return None\n parent = resource\n return parent\n\n\n# split a camel case string into a space-separated string\ndef split_camel_case(name):\n result = ''\n for c in name:\n if c.isupper():\n result += ' '\n result += c\n return result\n\n\n# determine (guess) the mimetype of a file based on its file name extension\ndef mime_type_from_ext(file_name):\n file_ext = file_name.rsplit('.', 1)[-1]\n type = ''\n if file_ext == 'jpg':\n type = 'image/jpeg'\n elif file_ext == 'png':\n type = 'image/png'\n elif file_ext == 'txt':\n type = 'text/plain'\n elif file_ext == 'csv':\n type = 'text/csv'\n return type\n\n\n# this is a high-level function for setting the value of a sequence;\n# it (1) creates a sequence value record and (2) sends out a sequence_update message;\n# note that we don't commit resource here; outside code must commit\n# value should be a plain string (not unicode string), possibly containing binary data or encoded unicode data\ndef update_sequence_value(resource, resource_path, timestamp, value, emit_message=True):\n data_type = json.loads(resource.system_attributes)['data_type']\n\n # determine min interval between updates\n system_attributes = json.loads(resource.system_attributes) if resource.system_attributes else {}\n min_storage_interval = system_attributes.get('min_storage_interval')\n if min_storage_interval is None:\n if data_type == Resource.TEXT_SEQUENCE:\n min_storage_interval = 0\n else:\n min_storage_interval = 50\n\n # prep sequence update message data\n if emit_message:\n message_params = {\n 'id': resource.id,\n 'name': resource_path,\n 'timestamp': timestamp.isoformat() + 'Z',\n }\n if data_type != Resource.IMAGE_SEQUENCE: # for images we'll send revision IDs\n message_params['value'] = value # fix(soon): json.dumps crashes if this included binary data\n\n # if too soon since last update, don't store a new value (but do still send out an update message)\n if min_storage_interval == 0 or timestamp >= resource.modification_timestamp + datetime.timedelta(seconds=min_storage_interval):\n resource_revision = add_resource_revision(resource, timestamp, value)\n resource.modification_timestamp = timestamp\n\n # create thumbnails for image sequences\n if data_type == Resource.IMAGE_SEQUENCE:\n max_width = 240\n name = 'thumbnail-%d-x' % max_width\n (thumbnail_contents, thumbnail_width, thumbnail_height) = compute_thumbnail(value, max_width)\n try:\n thumbnail_resource = Resource.query.filter(Resource.parent_id == resource.id, Resource.name == name, Resource.deleted == False).one()\n except NoResultFound:\n thumbnail_resource = create_sequence(resource, name, Resource.IMAGE_SEQUENCE)\n thumbnail_revision = add_resource_revision(thumbnail_resource, timestamp, thumbnail_contents)\n if emit_message:\n message_params['revision_id'] = resource_revision.id\n message_params['thumbnail_revision_id'] = thumbnail_revision.id\n\n # create a short lived update message for subscribers to the folder containing this sequence\n if emit_message:\n message_queue.add(folder_id = resource.parent_id, type = 'sequence_update', parameters = message_params, timestamp = timestamp)\n\n\n# creates a resource revision record; places the data in the record (if it is small) or bulk storage (if it is large);\n# note that we don't commit resource here; outside code must commit\n# data should be a plain string (not unicode string), possibly containing binary data or encoded unicode data\ndef add_resource_revision(resource, timestamp, data):\n resource_revision = ResourceRevision()\n resource_revision.resource_id = resource.id\n resource_revision.timestamp = timestamp\n if len(data) < 1000 or not storage_manager:\n resource_revision.data = data\n bulk_storage = False\n else:\n bulk_storage = True\n db.session.add(resource_revision)\n db.session.commit()\n if bulk_storage:\n storage_manager.write(resource.storage_path(resource_revision.id), data)\n resource.last_revision_id = resource_revision.id # note that we don't commit here; outside code must commit\n return resource_revision\n\n\n# reads the most recent revision/value of a resource;\n# if check_timing is True, will display some timing diagnostics\ndef read_resource(resource, revision_id = None, check_timing = False):\n data = None\n if not revision_id:\n revision_id = resource.last_revision_id # if no last revision, this is a new resource with new data\n if revision_id:\n try:\n if check_timing:\n start_time = time.time()\n resource_revision = ResourceRevision.query.filter(ResourceRevision.id == revision_id).one()\n if check_timing:\n print('query time: %.4f' % (time.time() - start_time))\n data = resource_revision.data\n except NoResultFound:\n pass\n if data is None and storage_manager: # fix(later): move this inside try statement; we should always have a resource revision if we have data in storage\n if check_timing:\n start_time = time.time()\n data = storage_manager.read(resource.storage_path(revision_id))\n if check_timing:\n print('storage time: %.4f' % (time.time() - start_time))\n return data\n\n\n# create a new sequence resource; commits it to database and returns resource record\ndef create_sequence(parent_resource, name, data_type, max_history = 10000, units = None):\n r = Resource()\n r.parent_id = parent_resource.id\n r.organization_id = parent_resource.organization_id\n r.name = name\n r.type = Resource.SEQUENCE\n r.creation_timestamp = datetime.datetime.utcnow()\n r.modification_timestamp = r.creation_timestamp\n system_attributes = {\n 'data_type': data_type,\n 'max_history': max_history\n }\n if units:\n system_attributes['units'] = units\n r.system_attributes = json.dumps(system_attributes)\n db.session.add(r)\n db.session.commit()\n return r\n\n\n# create a new organization record\ndef create_organization(full_name, folder_name):\n r = Resource()\n r.name = folder_name\n r.type = Resource.ORGANIZATION_FOLDER\n r.creation_timestamp = datetime.datetime.utcnow()\n r.modification_timestamp = r.creation_timestamp\n r.system_attributes = json.dumps({\n 'full_name': full_name,\n 'timezone': 'US/Pacific',\n })\n db.session.add(r)\n db.session.commit()\n r.permissions = json.dumps([[ACCESS_TYPE_ORG_USERS, r.id, ACCESS_LEVEL_WRITE], [ACCESS_TYPE_ORG_CONTROLLERS, r.id, ACCESS_LEVEL_WRITE]])\n r.organization_id = r.id # the organization record has its own id as its organization\n db.session.commit()\n return r.id\n\n\n# create/update system resources\ndef create_system_resources():\n print('creating/updating system resources in database')\n\n # make sure system folder exists\n system_folder = find_resource('/system')\n if not system_folder:\n create_organization('System', 'system')\n system_folder = find_resource('/system')\n print('created system folder')\n\n # make sure home page exists\n home_page = find_resource('/system/home.md')\n if not home_page:\n resource = Resource()\n resource.parent_id = system_folder.id\n resource.type = Resource.FILE\n resource.name = 'home.md'\n db.session.add(resource)\n db.session.commit()\n home_contents = '''### Welcome\n\nIf you are logged in as a system admin, you can [edit this page](/system/home.md?edit=1).\n'''\n add_resource_revision(resource, datetime.datetime.utcnow(), home_contents)\n print('created home page')\n\n # fix(soon): create workers folder, log sequence, doc org, workers/log\n\n # add apps for system app templates\n file_names = os.listdir('main/templates/system')\n app_create_count = 0\n for file_name in file_names:\n if file_name.endswith('.html'):\n app_name = file_name.rsplit('.', 1)[0]\n app_title = split_camel_case(app_name).title().replace('_', ' ')\n try:\n resource = Resource.query.filter(Resource.parent_id == system_folder.id, Resource.name == app_title, Resource.deleted == False).one()\n except NoResultFound:\n print('creating: %s, %s' % (app_name, app_title))\n resource = Resource()\n resource.parent_id = system_folder.id\n resource.type = Resource.APP\n resource.name = app_title\n db.session.add(resource)\n db.session.commit()\n app_create_count += 1\n print('created %d apps' % app_create_count)\n","sub_path":"main/resources/resource_util.py","file_name":"resource_util.py","file_ext":"py","file_size_in_byte":14543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"90217779","text":"import random\n\nprint(\"Guess Game\\n\")\n\np1 = input (\"Player 1 enter your name.\\n\")\np2 = input (\"Player 2 enter your name.\\n\")\n\nlist = []\n\ndef main(player , player2):\n\ttchances = int(input(\"Enter number of chances\\n\"))\n\tglobal list\n\t\n\tchances = tchances\n\ta = int(input(f\"{player} - Enter first number\\n\"))\n\tb = int(input(f\"{player} - Enter second number\\n\"))\n\trandnum = random.randint(a,b)\n\t'''Game will start now'''\n\twhile chances>0:\n\t\ttry:\n\t\t\tguess = int(input(f\"{player2} - Enter your guess\\n\"))\n\t\texcept Exception as e:\n\t\t\tprint(\"Please enter only numbers\\n\")\n\t\t\t\t\n\t\telse:\n\t\t\tif guess==randnum:\n\t\t\t\tprint(\"You guessed the correct number!\\n\")\n\t\t\t\tchances -= 1\n\t\t\t\tbreak\n\t\t\telif guess>randnum:\n\t\t\t\tprint(\"You guessed greater number\\nTry again\\n\")\n\t\t\t\tchances -= 1\n\t\t\t\tcontinue\n\t\t\telif guess ls:\n\t\tprint(f\"{p1} won\")\n\telse:\n\t\tprint(\"Error!\")\nresults()\n\t\t\t\t\t\t\nchoice = input(\"Do you want to play again? 'yes' or 'no'\\n\")\nif choice==\"yes\":\n\tlist.pop()\n\tlist.pop()\n\tmain(p1,p2)\n\tmain(p2, p1)\n\tresults()\nelse:\n\texit()","sub_path":"multiplayer_guessing_game.py","file_name":"multiplayer_guessing_game.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"388980124","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[101]:\n\n\nfrom numpy.random import seed\nimport csv\nimport sqlite3\nimport time\nimport numpy as np\nimport random\nimport pandas as pd\nfrom pandas import DataFrame\nimport scipy.sparse as sp\nimport math\nimport copy\n\nfrom sklearn.model_selection import KFold\nfrom sklearn.decomposition import PCA\nfrom sklearn.metrics import auc\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import precision_score\nfrom sklearn.metrics import precision_recall_curve\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.preprocessing import label_binarize\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.decomposition import KernelPCA\n\nimport sys\nimport torch\nfrom torch import nn\nimport torch.optim as optim\nfrom torch.utils.data import Dataset\nfrom torch.utils.data import DataLoader\nfrom pytorchtools import EarlyStopping\nfrom pytorchtools import BalancedDataParallel\nfrom radam import RAdam\nimport torch.nn.functional as F\n\nimport networkx as nx\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport os\nfrom tensorboardX import SummaryWriter\n\n\n# In[102]:\n\n\nseed=0\nrandom.seed(seed)\nos.environ['PYTHONHASHSEED'] = str(seed)\nnp.random.seed(seed)\ntorch.manual_seed(seed)\ntorch.cuda.manual_seed(seed)\ntorch.cuda.manual_seed_all(seed)\ntorch.backends.cudnn.deterministic = True\n\n\n# In[103]:\n\n\ndef prepare(df_drug, feature_list,mechanism,action,drugA,drugB):\n\n d_label = {}\n d_feature = {}\n\n # Transfrom the interaction event to number\n d_event=[]\n for i in range(len(mechanism)):\n d_event.append(mechanism[i]+\" \"+action[i])\n\n\n count={}\n for i in d_event:\n if i in count:\n count[i]+=1\n else:\n count[i]=1\n event_num=len(count)\n list1 = sorted(count.items(), key=lambda x: x[1],reverse=True)\n for i in range(len(list1)):\n d_label[list1[i][0]]=i\n\n\n vector = np.zeros((len(np.array(df_drug['name']).tolist()), 0), dtype=float) #vector=[]\n for i in feature_list:\n #vector = np.hstack((vector, feature_vector(i, df_drug, vector_size)))#1258*1258\n tempvec=feature_vector(i, df_drug)\n vector = np.hstack((vector,tempvec))\n # Transfrom the drug ID to feature vector\n for i in range(len(np.array(df_drug['name']).tolist())):\n d_feature[np.array(df_drug['name']).tolist()[i]] = vector[i]\n\n # Use the dictionary to obtain feature vector and label\n new_feature = []\n new_label = []\n\n for i in range(len(d_event)):\n temp=np.hstack((d_feature[drugA[i]],d_feature[drugB[i]]))\n new_feature.append(temp)\n new_label.append(d_label[d_event[i]])\n\n \n new_feature = np.array(new_feature) #323539*....\n new_label = np.array(new_label) #323539\n\n return new_feature, new_label, drugA,drugB,event_num\n\n\n# In[104]:\n\n\ndef feature_vector(feature_name, df):\n def Jaccard(matrix):\n matrix = np.mat(matrix)\n\n numerator = matrix * matrix.T\n\n denominator = np.ones(np.shape(matrix)) * matrix.T + matrix * np.ones(np.shape(matrix.T)) - matrix * matrix.T\n\n return numerator / denominator\n \n all_feature = []\n drug_list = np.array(df[feature_name]).tolist()\n # Features for each drug, for example, when feature_name is target, drug_list=[\"P30556|P05412\",\"P28223|P46098|……\"]\n for i in drug_list:\n for each_feature in i.split('|'):\n if each_feature not in all_feature:\n all_feature.append(each_feature) # obtain all the features\n feature_matrix = np.zeros((len(drug_list), len(all_feature)), dtype=float)\n df_feature = DataFrame(feature_matrix, columns=all_feature) # Consrtuct feature matrices with key of dataframe\n for i in range(len(drug_list)):\n for each_feature in df[feature_name].iloc[i].split('|'):\n df_feature[each_feature].iloc[i] = 1\n \n df_feature = np.array(df_feature)\n sim_matrix = np.array(Jaccard(df_feature))\n \n print(feature_name+\" len is:\"+ str(len(sim_matrix[0])))\n return sim_matrix\n\n\n# In[105]:\n\n\nclass DDIDataset(Dataset):\n def __init__(self,x,y):\n self.len=len(x)\n self.x_data=torch.from_numpy(x)\n\n self.y_data=torch.from_numpy(y)\n def __getitem__(self,index):\n return self.x_data[index],self.y_data[index]\n def __len__(self):\n return self.len\n\n\n# In[106]:\n\n\nclass MultiHeadAttention(torch.nn.Module):\n def __init__(self,input_dim,n_heads,ouput_dim=None):\n \n super(MultiHeadAttention, self).__init__()\n self.d_k=self.d_v=input_dim//n_heads\n self.n_heads = n_heads\n if ouput_dim==None:\n self.ouput_dim=input_dim\n else:\n self.ouput_dim=ouput_dim\n self.W_Q = torch.nn.Linear(input_dim, self.d_k * self.n_heads, bias=False)\n self.W_K = torch.nn.Linear(input_dim, self.d_k * self.n_heads, bias=False)\n self.W_V = torch.nn.Linear(input_dim, self.d_v * self.n_heads, bias=False)\n self.fc = torch.nn.Linear(self.n_heads * self.d_v, self.ouput_dim, bias=False)\n def forward(self,X):\n ## (S, D) -proj-> (S, D_new) -split-> (S, H, W) -trans-> (H, S, W)\n Q=self.W_Q(X).view( -1, self.n_heads, self.d_k).transpose(0,1)\n K=self.W_K(X).view( -1, self.n_heads, self.d_k).transpose(0,1)\n V=self.W_V(X).view( -1, self.n_heads, self.d_v).transpose(0,1)\n \n scores = torch.matmul(Q, K.transpose(-1, -2)) / np.sqrt(self.d_k)\n # context: [n_heads, len_q, d_v], attn: [n_heads, len_q, len_k]\n attn = torch.nn.Softmax(dim=-1)(scores)\n context = torch.matmul(attn, V)\n # context: [len_q, n_heads * d_v]\n context = context.transpose(1, 2).reshape(-1, self.n_heads * self.d_v)\n output = self.fc(context)\n return output\n\n\n# In[107]:\n\n\nclass EncoderLayer(torch.nn.Module):\n def __init__(self,input_dim,n_heads):\n super(EncoderLayer, self).__init__()\n self.attn = MultiHeadAttention(input_dim,n_heads)\n self.AN1=torch.nn.LayerNorm(input_dim)\n \n self.l1=torch.nn.Linear(input_dim, input_dim)\n self.AN2=torch.nn.LayerNorm(input_dim)\n def forward (self,X):\n \n output=self.attn(X)\n X=self.AN1(output+X)\n \n output=self.l1(X)\n X=self.AN2(output+X)\n \n return X\n\n\n# In[108]:\n\n\ndef gelu(x):\n return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))\n\n\n# In[109]:\n\n\nclass AE1(torch.nn.Module): #Joining together\n def __init__(self,vector_size):\n super(AE1,self).__init__()\n \n self.vector_size=vector_size\n \n self.l1 = torch.nn.Linear(self.vector_size,(self.vector_size+len_after_AE)//2)\n self.bn1 = torch.nn.BatchNorm1d((self.vector_size+len_after_AE)//2)\n \n self.att2=EncoderLayer((self.vector_size+len_after_AE)//2,bert_n_heads)\n self.l2 = torch.nn.Linear((self.vector_size+len_after_AE)//2,len_after_AE)\n \n self.l3 = torch.nn.Linear(len_after_AE,(self.vector_size+len_after_AE)//2)\n self.bn3 = torch.nn.BatchNorm1d((self.vector_size+len_after_AE)//2)\n \n self.l4 = torch.nn.Linear((self.vector_size+len_after_AE)//2,self.vector_size)\n \n self.dr = torch.nn.Dropout(drop_out_rating)\n self.ac=gelu\n \n def forward(self,X):\n \n X=self.dr(self.bn1(self.ac(self.l1(X))))\n \n X=self.att2(X)\n X=self.l2(X)\n \n X_AE=self.dr(self.bn3(self.ac(self.l3(X))))\n \n X_AE=self.l4(X_AE)\n \n return X,X_AE\n\n\n# In[110]:\n\n\nclass AE2(torch.nn.Module):# twin network\n def __init__(self,vector_size):\n super(AE2,self).__init__()\n \n self.vector_size=vector_size//2\n \n self.l1 = torch.nn.Linear(self.vector_size,(self.vector_size+len_after_AE//2)//2)\n self.bn1 = torch.nn.BatchNorm1d((self.vector_size+len_after_AE//2)//2)\n \n self.att2=EncoderLayer((self.vector_size+len_after_AE//2)//2,bert_n_heads)\n self.l2 = torch.nn.Linear((self.vector_size+len_after_AE//2)//2,len_after_AE//2)\n \n self.l3 = torch.nn.Linear(len_after_AE//2,(self.vector_size+len_after_AE//2)//2)\n self.bn3 = torch.nn.BatchNorm1d((self.vector_size+len_after_AE//2)//2)\n \n self.l4 = torch.nn.Linear((self.vector_size+len_after_AE//2)//2,self.vector_size)\n \n self.dr = torch.nn.Dropout(drop_out_rating)\n \n self.ac=gelu\n \n def forward(self,X):\n \n X1=X[:,0:self.vector_size]\n X2=X[:,self.vector_size:]\n \n X1=self.dr(self.bn1(self.ac(self.l1(X1))))\n X1=self.att2(X1)\n X1=self.l2(X1)\n X_AE1=self.dr(self.bn3(self.ac(self.l3(X1))))\n X_AE1=self.l4(X_AE1)\n \n X2=self.dr(self.bn1(self.ac(self.l1(X2))))\n X2=self.att2(X2)\n X2=self.l2(X2)\n X_AE2=self.dr(self.bn3(self.ac(self.l3(X2))))\n X_AE2=self.l4(X_AE2)\n \n X=torch.cat((X1,X2), 1)\n X_AE=torch.cat((X_AE1,X_AE2), 1)\n \n return X,X_AE\n\n\n# In[111]:\n\n\nclass cov(torch.nn.Module):\n def __init__(self,vector_size):\n super(cov,self).__init__()\n \n self.vector_size=vector_size\n \n self.co2_1=torch.nn.Conv2d(1, 1, kernel_size=(2,cov2KerSize))\n self.co1_1=torch.nn.Conv1d(1, 1, kernel_size=cov1KerSize)\n self.pool1=torch.nn.AdaptiveAvgPool1d(len_after_AE)\n \n self.ac=gelu\n \n \n def forward(self,X):\n \n X1=X[:,0:self.vector_size//2]\n X2=X[:,self.vector_size//2:]\n \n X=torch.cat((X1,X2), 0)\n \n X=X.view(-1,1,2,self.vector_size//2)\n \n X=self.ac(self.co2_1(X))\n \n X=X.view(-1,self.vector_size//2-cov2KerSize+1, 1) \n X=X.permute(0,2,1)\n X=self.ac(self.co1_1(X))\n \n X=self.pool1(X)\n \n X=X.contiguous().view(-1,len_after_AE)\n \n return X\n\n\n# In[112]:\n\n\nclass ADDAE(torch.nn.Module):\n def __init__(self,vector_size):\n super(ADDAE,self).__init__()\n \n self.vector_size=vector_size//2\n \n self.l1 = torch.nn.Linear(self.vector_size,(self.vector_size+len_after_AE)//2)\n self.bn1 = torch.nn.BatchNorm1d((self.vector_size+len_after_AE)//2)\n \n self.att1=EncoderLayer((self.vector_size+len_after_AE)//2,bert_n_heads)\n self.l2 = torch.nn.Linear((self.vector_size+len_after_AE)//2,len_after_AE)\n #self.att2=EncoderLayer(len_after_AE//2,bert_n_heads)\n \n self.l3 = torch.nn.Linear(len_after_AE,(self.vector_size+len_after_AE)//2)\n self.bn3 = torch.nn.BatchNorm1d((self.vector_size+len_after_AE)//2)\n \n self.l4 = torch.nn.Linear((self.vector_size+len_after_AE)//2,self.vector_size)\n \n self.dr = torch.nn.Dropout(drop_out_rating)\n \n self.ac=gelu\n \n def forward(self,X):\n \n X1=X[:,0:self.vector_size]\n X2=X[:,self.vector_size:]\n X=X1+X2\n \n X=self.dr(self.bn1(self.ac(self.l1(X))))\n \n X=self.att1(X)\n X=self.l2(X)\n \n X_AE=self.dr(self.bn3(self.ac(self.l3(X))))\n \n X_AE=self.l4(X_AE)\n X_AE=torch.cat((X_AE,X_AE), 1)\n \n return X,X_AE\n\n\n# In[113]:\n\n\nclass BERT(torch.nn.Module):\n def __init__(self,input_dim,n_heads,n_layers,event_num):\n super(BERT, self).__init__()\n \n self.ae1=AE1(input_dim) #Joining together\n self.ae2=AE2(input_dim)#twin loss\n self.cov=cov(input_dim)#cov \n self.ADDAE=ADDAE(input_dim)\n \n self.dr = torch.nn.Dropout(drop_out_rating)\n self.input_dim=input_dim\n \n self.layers = torch.nn.ModuleList([EncoderLayer(len_after_AE*5,n_heads) for _ in range(n_layers)])\n self.AN=torch.nn.LayerNorm(len_after_AE*5)\n \n self.l1=torch.nn.Linear(len_after_AE*5,(len_after_AE*5+event_num)//2)\n self.bn1=torch.nn.BatchNorm1d((len_after_AE*5+event_num)//2)\n \n self.l2=torch.nn.Linear((len_after_AE*5+event_num)//2,event_num)\n \n self.ac=gelu\n \n def forward(self, X):\n X1,X_AE1=self.ae1(X)\n X2,X_AE2=self.ae2(X)\n \n X3=self.cov(X)\n \n X4,X_AE4=self.ADDAE(X)\n \n X5=X1+X2+X3+X4\n \n X=torch.cat((X1,X2,X3,X4,X5), 1)\n \n for layer in self.layers:\n X = layer(X)\n X=self.AN(X)\n \n X=self.dr(self.bn1(self.ac(self.l1(X))))\n \n X=self.l2(X)\n \n return X,X_AE1,X_AE2,X_AE4\n\n\n# In[114]:\n\n\nclass focal_loss(nn.Module):\n def __init__(self, gamma=2):\n \n super(focal_loss,self).__init__()\n \n self.gamma = gamma\n\n def forward(self, preds, labels):\n \n # assert preds.dim() == 2 and labels.dim()==1\n labels = labels.view(-1, 1) # [B * S, 1]\n preds = preds.view(-1, preds.size(-1)) # [B * S, C]\n \n preds_logsoft = F.log_softmax(preds, dim=1) # 先softmax, 然后取log\n preds_softmax = torch.exp(preds_logsoft) # softmax\n\n preds_softmax = preds_softmax.gather(1, labels) # 这部分实现nll_loss ( crossempty = log_softmax + nll )\n preds_logsoft = preds_logsoft.gather(1, labels)\n \n loss = -torch.mul(torch.pow((1-preds_softmax), self.gamma), preds_logsoft) # torch.pow((1-preds_softmax), self.gamma) 为focal loss中 (1-pt)**γ\n \n loss = loss.mean()\n \n return loss\nclass my_loss1(nn.Module):\n def __init__(self):\n \n super(my_loss1,self).__init__()\n \n self.criteria1 = torch.nn.CrossEntropyLoss()\n self.criteria2=torch.nn.MSELoss()\n\n def forward(self, X, target,inputs,X_AE1,X_AE2,X_AE4):\n\n\n \n loss=calssific_loss_weight*self.criteria1(X,target)+\\\n self.criteria2(inputs.float(),X_AE1)+\\\n self.criteria2(inputs.float(),X_AE2)+\\\n self.criteria2(inputs.float(),X_AE4)\n return loss\nclass my_loss2(nn.Module):\n def __init__(self):\n \n super(my_loss2,self).__init__()\n \n self.criteria1 = focal_loss()\n self.criteria2=torch.nn.MSELoss()\n\n def forward(self, X, target,inputs,X_AE1,X_AE2,X_AE4):\n\n loss=calssific_loss_weight*self.criteria1(X,target)+\\\n self.criteria2(inputs.float(),X_AE1)+\\\n self.criteria2(inputs.float(),X_AE2)+\\\n self.criteria2(inputs.float(),X_AE4)\n return loss\n\n\n\n\ndef mixup(x1, x2, y1, y2, alpha):\n beta = np.random.beta(alpha, alpha)\n x = beta * x1 + (1 - beta) * x2\n y = beta * y1 + (1 - beta) * y2\n return x, y\n\n#writer = SummaryWriter(\"./tbx\")\ndef BERT_train(model,x_train,y_train,x_test,y_test,event_num):\n\n model_optimizer=RAdam(model.parameters(),lr=learn_rating,weight_decay=weight_decay_rate)\n model=torch.nn.DataParallel(model)\n model=model.to(device)\n\n x_train=np.vstack((x_train,np.hstack((x_train[:,len(x_train[0])//2:],x_train[:,:len(x_train[0])//2]))))\n y_train = np.hstack((y_train, y_train))\n np.random.seed(seed)\n np.random.shuffle(x_train)\n np.random.seed(seed)\n np.random.shuffle(y_train)\n\n len_train=len(y_train)\n len_test=len(y_test)\n print(\"arg train len\", len(y_train))\n print(\"test len\", len(y_test))\n\n\n train_dataset = DDIDataset(x_train,np.array(y_train))\n test_dataset = DDIDataset(x_test,np.array(y_test))\n train_loader=DataLoader(dataset=train_dataset,batch_size=batch_size,shuffle=True)\n test_loader=DataLoader(dataset=test_dataset,batch_size=batch_size,shuffle=False)\n\n\n for epoch in range(epo_num):\n if epoch time\n arrivedTasks = lambda x: x.arrivalTime <= time\n arrived = list(filter(arrivedTasks, tasks))\n if not arrived: return False\n activeTasks += arrived\n tasks = list(filter(futureTasks, tasks))\n return True\n\ndef waitForTasks(curTime, interval, clb):\n global activeTasks \n maxWaitTime = curTime + interval\n if not checkForNewTasks(maxWaitTime): return None\n clb(activeTasks)\n return activeTasks[0]\n\ndef checkMissedTasks(tasks, resTasks):\n diff = list()\n for task in tasks:\n processed = False\n for taskRes in resTasks:\n if task.arrivalTime == taskRes.arrival \\\n and task.deadline == taskRes.deadline:\n processed = True\n if not processed: diff.append(task)\n return diff\n\ndef BaseDynamicScheduler(queue, estimatePriority, allTasks):\n global tasks, activeTasks\n tasks = deepcopy(allTasks)\n tasks.sort(key=lambda x: x.arrivalTime)\n timestamps = dict()\n curTime, tactCount, idle = 0, 0, 0\n for task in tasks: timestamps[taskID(task)] = list()\n resTasks = list()\n while activeTasks or tasks:\n if tasks: checkForNewTasks(curTime)\n activeTasks = list(filter(lambda x: x.deadline > curTime, activeTasks))\n missed = list(filter(lambda x: x.deadline <= curTime, activeTasks))\n estimatePriority(activeTasks)\n for missedTask in missed:\n task = ProcessedTask(\n missedTask.arrivalTime,\n missedTask.deadline,\n [curTime, curTime],\n True\n )\n resTasks.append(task)\n \n remainedTime = tactCount or TACT_SIZE\n task = None\n if activeTasks:\n task = activeTasks[0]\n else:\n task = waitForTasks(curTime, remainedTime, estimatePriority)\n if not task:\n idle += remainedTime\n curTime += remainedTime\n if tactCount: tactCount = 0\n continue\n\n if task.arrivalTime > curTime:\n diff = task.arrivalTime - curTime\n idle += diff\n curTime = task.arrivalTime\n tactCount -= diff\n \n timestamps[taskID(task)].append(curTime)\n fitsIntoTact = task.wcet < remainedTime\n elapsedInTact = task.wcet if fitsIntoTact else remainedTime\n newTask = waitForTasks(curTime, elapsedInTact, estimatePriority)\n if newTask and \\\n not areTasksEqual(task, newTask) and \\\n not task.protected:\n task.wcet -= newTask.arrivalTime - curTime\n curTime = newTask.arrivalTime\n timestamps[taskID(task)].append(curTime)\n task = newTask\n timestamps[taskID(task)].append(curTime)\n fitsIntoTact = task.wcet < remainedTime\n elapsedInTact = task.wcet if fitsIntoTact else remainedTime\n curTime += elapsedInTact\n timestamps[taskID(task)].append(curTime)\n if not fitsIntoTact:\n task.wcet -= remainedTime\n tactCount = 0\n else:\n missed = task.deadline < curTime\n task = ProcessedTask(\n task.arrivalTime,\n task.deadline,\n timestamps[taskID(task)],\n missed\n )\n resTasks.append(task)\n activeTasks.pop(0)\n tactCount = remainedTime - elapsedInTact\n\n missed = checkMissedTasks(allTasks, resTasks)\n if missed:\n for task in missed: \n task = ProcessedTask(\n task.arrivalTime,\n task.deadline,\n [curTime, curTime],\n True\n )\n resTasks.append(task)\n queue.put(SchedulingResult(resTasks, idle, curTime))\n\ndef multiprocScheduler(estimatePriority, tasks):\n procs = list()\n queue = Queue()\n splitTasks = [tasks[i::N] for i in range(N)]\n for taskSet in splitTasks:\n procs.append(Process(\n target=BaseDynamicScheduler,\n args=(queue, estimatePriority, taskSet,)\n ))\n for proc in procs: proc.start()\n for proc in procs: proc.join()\n return [queue.get() for _ in splitTasks]\n\ndef estimatePriorityEDF(tasks):\n return tasks.sort(key=lambda x: (x.deadline, x.wcet)) \n\ndef estimatePriorityRM(tasks):\n return tasks.sort(key=lambda x: (x.period, x.wcet, x.deadline)) \n\nEDF = partial(multiprocScheduler, estimatePriorityEDF)\nRM = partial(multiprocScheduler, estimatePriorityRM)\n","sub_path":"RTS_RGR/dynamicShedulers.py","file_name":"dynamicShedulers.py","file_ext":"py","file_size_in_byte":4503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"421125771","text":"import csv, os\nimport cv2, h5py\nimport numpy as np\n\n# add path for csv of other data sets when using them \ncsv_location = './input/fixed_handheld.csv'\nimage_folder = './input/images_handheld/'\n\ndef read_image_data_pairs():\n data = []\n csv_file = open(csv_location) # setting up csv reading\n csv_read = csv.reader(csv_file)\n for row in csv_read: # read through the csv\n row_data = row[0].split() # break up info in row\n concise_row = row_data[2].split(\"/\") # isolate image ID and blight bool\n data.append(concise_row) # add to list for ease of manipulation\n return data\n\ndef get_all_Bools(start=None, end=None): # return list of blight bools in order\n to_bool = {\"True\":1, \"False\":0}\n bools = [to_bool[i[0]] for i in read_image_data_pairs()]\n return bools[start:end] # add slice\n\ndef read_all_images(x=None, y=None, start=None, end=None, mute=0): # returns all images, resized as specified\n image_ID_list = [image_folder + str(i[1]) for i in read_image_data_pairs()]\n image_ID_list = image_ID_list[start:end] # !!remove when using full dataset, this just saves time when iterating through and debugging!!\n image_list = []\n for image in image_ID_list:\n if mute == 0:\n print(\"Processing images: %.1f%% complete\" % (100*image_ID_list.index(image)/len(image_ID_list)), end=\"\\r\")\n image = cv2.imread(image)\n if x != None and y != None:\n image = cv2.resize(image, (y, x))\n image_list.append(image)\n if mute == 0:\n print(\"\\rProcessing images: 100% complete \") # possible future error debug, size given is that of first image,\n print(\"Processed {} images, sized {}\".format(len(image_list), image_list[0].shape)) # <----- not necessarily of all images\n return image_list\n\ndef get_features_and_labels(x=6000, y=4000, start=None, end=None): # Combined output of bools and images\n return np.array(read_all_images(x=x, y=y, start=start, end=end)), np.array(get_all_Bools(start=start, end=end))\n\ndef images_to_hdf5(file_name, data_name=\"pics\", start=None, end=None, mute=0): # write image data into an hdf5 file to save read time (<1/6 load time from observations)\n '''Use only when creating a new read file for crop data,\n read from existing file otherwise to save time and memory overhead'''\n filepath = './' + str(file_name) + '.hdf5'\n pictures = read_all_images(x=256, y=256, start=start, end=end, mute=mute)\n if os.path.isfile(filepath) == True:\n os.remove(filepath)\n os.mknod(filepath)\n pictures = np.array(pictures).tolist() # make into list\n with h5py.File(filepath, 'w') as f:\n f.create_dataset(data_name, data=pictures, dtype=\"uint8\")","sub_path":"imagereader.py","file_name":"imagereader.py","file_ext":"py","file_size_in_byte":2765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"390275783","text":"#!/usr/bin/env python\n# coding=utf-8\n'''\nDate: 17.09.2021\nAuthor: Yinfeng Long\nusage\n python3 combine_npz.py q330\n'''\n\nimport os\nimport sys\nimport numpy as np\n\ncombined = {\"x\": [], \"y\": [], \"z\":[], \"vx\":[], \"vy\":[], \"vz\":[], \"y_x\":[], \"y_y\":[], \"y_z\":[],\\\n\t\"y_vx\":[], \"y_vy\":[], \"y_vz\":[]}\n\ngp_path = '/home/itm_stud/test_ma_ws/MA_Experiment/src/itm/itm_quadrotor_node/itm_nonlinear_mpc/scripts/gpr/' + sys.argv[1]\ndirs = os.listdir(gp_path)\nprint(\"dirs: {}\".format(dirs))\n\nfor dir in dirs:\n\tfiles = os.listdir( (gp_path + '/' + dir) )\n\tfor x in files:\n\t\tif os.path.splitext(x)[1] == '.npz':\n\t\t\tnpz_path = gp_path + '/' + dir + '/' + x\n\t\t\tprint( \"npz_path: {}\".format(npz_path) )\n\t\t\tdata = np.load( npz_path )\n\t\t\tfor key, values in data.items():\n\t\t\t\tcombined[key].extend(values)\n\t\t\t\tcombined_x = combined['x']\n\t\t\tprint(\"shape of combined_q330_x:\", np.array(combined_x).shape)\n\t\telse:\n\t\t\tpass\n\nnp.savez( gp_path + '/combined_' + sys.argv[1] + '.npz', \\\n\t\tx=combined['x'], y=combined['y'], z=combined['z'], \\\n\t\t\tvx = combined['vx'], vy = combined['vy'], vz = combined['vz'],\\\n\t\t\ty_x = combined['y_x'], y_y = combined['y_y'], y_z = combined['y_z'], \\\n\t\t\ty_vx = combined['y_vx'], y_vy = combined['y_vy'], y_vz =combined['y_vz'])\n","sub_path":"gp_before_submodule_backup/gpr/combine_npz.py","file_name":"combine_npz.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"504737784","text":"#! python3\r\n# -*- coding: utf-8 -*-\r\n\r\nfrom turtle import Turtle\r\n\r\n\r\ndef tree(length):\r\n if length > 5:\r\n turtle.forward(length)\r\n turtle.right(20)\r\n tree(length-15)\r\n turtle.left(40)\r\n tree(length-15)\r\n turtle.right(20)\r\n turtle.backward(length)\r\n\r\nturtle = Turtle()\r\nturtle.color('green')\r\nturtle.left(90)\r\nturtle.backward(150)\r\ntree(120)\r\n\r\ninput('hit any key to exit')\r\n\r\n","sub_path":"py3/draw_tree.py","file_name":"draw_tree.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"64163626","text":"# coding=utf-8\n# --------------------------------------------------------------------------\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#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass EncryptionSettingsCollection(Model):\n \"\"\"Encryption settings for disk or snapshot.\n\n All required parameters must be populated in order to send to Azure.\n\n :param enabled: Required. Set this flag to true and provide\n DiskEncryptionKey and optional KeyEncryptionKey to enable encryption. Set\n this flag to false and remove DiskEncryptionKey and KeyEncryptionKey to\n disable encryption. If EncryptionSettings is null in the request object,\n the existing settings remain unchanged.\n :type enabled: bool\n :param encryption_settings: A collection of encryption settings, one for\n each disk volume.\n :type encryption_settings:\n list[~azure.mgmt.compute.v2018_09_30.models.EncryptionSettingsElement]\n \"\"\"\n\n _validation = {\n 'enabled': {'required': True},\n }\n\n _attribute_map = {\n 'enabled': {'key': 'enabled', 'type': 'bool'},\n 'encryption_settings': {'key': 'encryptionSettings', 'type': '[EncryptionSettingsElement]'},\n }\n\n def __init__(self, *, enabled: bool, encryption_settings=None, **kwargs) -> None:\n super(EncryptionSettingsCollection, self).__init__(**kwargs)\n self.enabled = enabled\n self.encryption_settings = encryption_settings\n","sub_path":"azure-mgmt-compute/azure/mgmt/compute/v2018_09_30/models/encryption_settings_collection_py3.py","file_name":"encryption_settings_collection_py3.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"164417865","text":"#imports\n# from Loyal_Fox.codes.mailing import mail_company, mail_viwer\nimport os\nfrom datetime import datetime\nfrom enum import unique\nfrom logging import debug\n\nfrom flask import Flask, flash, redirect, render_template, request, make_response\nfrom flask_login import (LoginManager, UserMixin, current_user, login_required, login_user, logout_user)\nfrom flask_mail import Mail, Message\nfrom flask_sqlalchemy import SQLAlchemy\nfrom werkzeug.utils import secure_filename\n\n# from mailing import *\n\n\n#global\n# frontend_url = \"http://localhost:3000\"\nALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])\nUPLOAD_FOLDER = \"./static/blogs_images\"\n\n\n#configuring\napp = Flask(__name__)\napp.config[\"SECRET_KEY\"]= \"KEY\"\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = \"sqlite:///blogs.db\"\n# app.config[\"SQLALCHEMY_DATABASE_URI\"] = \"sqlite:///User.db\"\n\napp.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = True\n\ndb = SQLAlchemy(app)\n\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024\n\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\n\napp.config.update(\n DEBUG=True,\n \n # for actual code running on AWS\n MAIL_PORT = 587,\n MAIL_USE_TLS = True,\n \n MAIL_SERVER = \"email-smtp.ap-south-1.amazonaws.com\",\n MAIL_USERNAME = \"AKIAZXXKXWLK4PLL4OHQ\",\n MAIL_PASSWORD = \"BDl2EYN45O31YT2+n2o1P+RQ8A7dtn6i0GZFXWVqldQB\"\n)\nmail = Mail(app)\n\n\n#creating flask object models or database table\nclass blogs_table(db.Model):\n id = db.Column(\"Id\",db.Integer, primary_key=True)\n timestamp = db.Column(\"Timestamp\",db.DateTime,default=datetime.now(), nullable=False)\n title = db.Column(\"Title\",db.String(200),nullable=False)\n abstract = db.Column(\"Abstract\",db.Text)\n # author = db.Column(db.String(20))\n image = db.Column(\"Image\",db.String(500))\n content = db.Column(\"Content\",db.Text,nullable=False)\n\n\nclass User(UserMixin, db.Model):\n id = db.Column(\"ID\",db.Integer, primary_key=True)\n username = db.Column(\"Username\",db.String(100),unique=True, nullable=False)\n password = db.Column(\"Password\",db.String(100), nullable=False)\n\n\n#functions\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n\n\n# login manager\n@login_manager.user_loader\ndef load_user(user_id):\n return User.query.get(int(user_id))\n\n\n#APIs routes\n\n#Home\n@app.route(\"/\")\n# @app.route(\"/home/\")\n@app.route(\"/home\")\ndef home():\n return render_template(\"home.html\")\n\n# -----------------------------------------------\n\n#About US\n# @app.route(\"/who_we_are/\")\n@app.route(\"/who_we_are\")\ndef who_we_are():\n return render_template(\"who_we_are.html\")\n\n# @app.route(\"/what_we_do/\")\n@app.route(\"/what_we_do\")\ndef what_we_do():\n return render_template(\"what_we_do.html\")\n\n# @app.route(\"/our_mission/\")\n@app.route(\"/our_mission\")\ndef our_mission():\n return render_template(\"our_mission.html\")\n\n# ------------------------------------------------------\n\n#Our Solutions\n# @app.route(\"/multi-tenant-loyalty/\")\n@app.route(\"/multi-tenant-loyalty\")\ndef multi_tenant_loyalty():\n return render_template(\"multi-tenant-loyalty.html\")\n\n# @app.route(\"/marketing-campaigns/\")\n@app.route(\"/marketing-campaigns\")\ndef marketing_campaigns():\n return render_template(\"marketing-campaigns.html\")\n\n# @app.route(\"/helpdesk-services/\")\n@app.route(\"/helpdesk-services\")\ndef helpdesk_services():\n return render_template(\"helpdesk-services.html\")\n\n# @app.route(\"/data-analytics/\")\n@app.route(\"/data-analytics\")\ndef data_analytics():\n return render_template(\"data-analytics.html\")\n\n# @app.route(\"/instant-rewards/\")\n@app.route(\"/instant-rewards\")\ndef instant_rewards():\n return render_template(\"instant-rewards-new.html\")\n #return redirect(\"/404\")\n\n# @app.route(\"/content-and-creatives/\")\n@app.route(\"/content-and-creatives\")\ndef content_and_creatives():\n return render_template(\"content-and-creatives.html\")\n\n# @app.route(\"/robust-tech/\")\n@app.route(\"/robust-tech\")\ndef robust_tech():\n return render_template(\"robust-tech.html\")\n\n\n\n\n\n#----------------------------------------------------\n\n# @app.route(\"/ourteam/\")\n@app.route(\"/ourteam\")\ndef ourteam():\n return render_template(\"ourteam.html\")\n\n# @app.route(\"/navbar/\")\n@app.route(\"/navbar\")\ndef navbar():\n return render_template(\"navbar.html\")\n \n#--------------------------------------------------------\n\n\n# @app.route(\"/productfulfillment/\")\n@app.route(\"/productfulfillment\")\ndef product():\n return render_template(\"product.html\")\n\n@app.route(\"/admin\")\ndef admin():\n return render_template(\"admin_login.html\")\n\n\n# @app.route(\"/experiences/\")\n@app.route(\"/experiences\")\ndef experiences():\n return render_template(\"experiences.html\")\n #return redirect(\"/404\")\n\n\n#--------------------------------------------------------\n\n# @app.route(\"/404/\")\n@app.route(\"/404\")\ndef func_404():\n return render_template(\"404.html\")\n\n@app.errorhandler(404)\ndef not_found(e):\n return redirect(\"/404\")\n\n\n#--------------------------------------------------------\n\n# @app.route(\"/rewards/\", methods=[\"GET\",\"POST\"])\n@app.route(\"/rewards\", methods=[\"GET\",\"POST\"])\ndef rewards():\n if request.method == \"POST\":\n # try\n name = request.form.get(\"user_name\")\n # name = request.form[\"name\"]\n phone = request.form.get(\"phone\")\n email = request.form.get(\"email\")\n note = request.form.get(\"note\")\n \n # mail_msg = \"\"\"\n # Response from 'Apply for Gift Vouchers': \\n\n # Name : \"\"\" + str(name) + \"\"\"\n # Phone : \"\"\" + str(phone) + \"\"\" \n # Email ID : \"\"\" + str(email) + \"\"\" \n # Any Note : \"\"\" + str(note) + \"\"\" \\n\n # \"\"\"\n # print(mail_msg)\n\n\n # if no entry in the form\n # if(not name or not phone or not email or not note):\n # err_msg = \"Give all the inputs\"\n # print(err_msg)\n # flash(err_msg,\"error\")\n # return redirect(\"/rewards\")\n\n #check whether phoneNO is 10 digits\n # if(len(str(phone))!=10 or str(phone)[0]=='0'):\n # err_msg = \"Enter 10 digits Phone no.\"\n # print(err_msg)\n # flash(err_msg,\"error\")\n # return redirect(\"/rewards\")\n\n\n mail_msg = \"\"\"\n Response from 'Apply for Gift Vouchers': \\n\n Name : \"\"\" + str(name) + \"\"\"\n Phone : \"\"\" + str(phone) + \"\"\" \n Email ID : \"\"\" + str(email) + \"\"\" \n Any Note : \"\"\" + str(note) + \"\"\" \\n\n \"\"\"\n\n print(mail_msg)\n\n print(\"\\n Mailing..........\")\n msg_company = Message(\n # sender = (\"Test\",\"testing0963@gmail.com\"),\n sender = (\"Website\",\"info@loyaltyfox.com\"),\n recipients=[\"info@loyaltyfox.com\",\"testing0963@gmail.com\"],\n body = mail_msg\n # subject = \"ContactUS form\"\n )\n # msg.body = \"Hey avi\"\n msg_company.subject = \"Loyalty Fox Website | Apply For Gift Vouchers Response\"\n mail.send(msg_company)\n\n # mail_company(mail_msg)\n print(\"mailed to loyality fox..\")\n \n\n #mail the the person whom want to be contacted\n msg_viewer = Message(\n sender = (\"Website\",\"info@loyaltyfox.com\"),\n recipients=[email],\n body = mail_msg\n # subject = \"ContactUS form\"\n )\n # msg.body = \"Hey avi\"\n msg_viewer.subject = \"Loyalty Fox | Apply For Gift Vouchers Response\"\n # mail.send(msg_viewer)\n\n # mail_viwer(email,mail_msg)\n print(\"mailed to user.\")\n flash(\"Thank you for your interest, we'll contact you soon. For any other query, you can call us on 8802065822 or write to us on info@loyaltyfox.com. \",\"success\")\n \n return render_template(\"rewards.html\")\n # return redirect(frontend_url)\n\n # except Exception as e:\n # print(e)\n # err_msg = \"Error in contactUS: \" + str(e)\n # print(err_msg)\n # flash(err_msg,\"error\")\n # return redirect(\"/rewards\")\n\n\n\n#contact us API\n# @app.route(\"/contactUS/\", methods=[\"GET\",\"POST\"])\n@app.route(\"/contactUS\", methods=[\"GET\",\"POST\"])\ndef contact():\n if request.method == \"POST\":\n # try\n name = request.form.get(\"user_name\")\n # name = request.form[\"name\"]\n phone = request.form.get(\"phone\")\n email = request.form.get(\"email\")\n company = request.form.get(\"company\")\n note = request.form.get(\"note\")\n \n # mail_msg = \"\"\"\n # Response from Contact Us: \\n\n # Name : \"\"\" + str(name) + \"\"\"\n # Phone : \"\"\" + str(phone) + \"\"\" \n # Email ID : \"\"\" + str(email) + \"\"\"\n # Company : \"\"\" + str(company) + \"\"\" \n # Any Note : \"\"\" + str(note) + \"\"\" \\n\n # \"\"\"\n # print(mail_msg)\n\n\n # if no entry in the form\n # if(not name or not phone or not email or not note):\n # err_msg = \"Give all the inputs\"\n # print(err_msg)\n # flash(err_msg,\"error\")\n # return redirect(\"/contactUS\")\n\n #check whether phoneNO is 10 digits\n # if(len(str(phone))!=10 or str(phone)[0]=='0'):\n # err_msg = \"Enter 10 digits Phone no.\"\n # print(err_msg)\n # flash(err_msg,\"error\")\n # return redirect(\"/contactUS\")\n\n\n mail_msg = \"\"\"\n Response from Contact Us: \\n\n Name : \"\"\" + str(name) + \"\"\"\n Phone : \"\"\" + str(phone) + \"\"\" \n Email ID : \"\"\" + str(email) + \"\"\"\n Company : \"\"\" + str(company) + \"\"\" \n Any Note : \"\"\" + str(note) + \"\"\" \\n\n \"\"\"\n\n print(mail_msg)\n\n print(\"\\n Mailing..........\")\n msg_company = Message(\n # sender = (\"Test\",\"testing0963@gmail.com\"),\n sender = (\"Website\",\"info@loyaltyfox.com\"),\n recipients=[\"info@loyaltyfox.com\",\"testing0963@gmail.com\"],\n body = mail_msg\n # subject = \"ContactUS form\"\n )\n # msg.body = \"Hey avi\"\n msg_company.subject = \"Loyalty Fox Website | Contact US Response\"\n mail.send(msg_company)\n\n # mail_company(mail_msg)\n print(\"mailed to loyality fox..\")\n \n\n #mail the the person whom want to be contacted\n msg_viewer = Message(\n sender = \"testing0963@gmail.com\",\n recipients=[email],\n body = mail_msg\n # subject = \"ContactUS form\"\n )\n # msg.body = \"Hey avi\"\n msg_viewer.subject = \"Loyalty Fox | Contact US Response\"\n # mail.send(msg_viewer)\n\n # mail_viwer(email,mail_msg)\n print(\"mailed to user.\")\n flash(\"Thank you for your interest, we'll contact you soon. For any other query, you can call us on 8802065822 or write to us on info@loyaltyfox.com. \",\"success\")\n \n return render_template(\"contactus.html\")\n # return redirect(frontend_url)\n\n # except Exception as e:\n # print(e)\n # err_msg = \"Error in contactUS: \" + str(e)\n # print(err_msg)\n # flash(err_msg,\"error\")\n # return redirect(\"/contactUS\")\n \n# ---------------------------------------------------------------------------------\n\n\n#ppc-channel landing page API\n@app.route(\"/ppc-channel-loyalty-program/\", methods=[\"GET\",\"POST\"])\n@app.route(\"/ppc-channel-loyalty-program\", methods=[\"GET\",\"POST\"])\ndef ppc():\n if request.method == \"POST\":\n # try\n name = request.form.get(\"name\")\n # name = request.form[\"name\"]\n phone = request.form.get(\"phone\")\n email = request.form.get(\"email\")\n note = request.form.get(\"message\")\n \n # mail_msg = \"\"\"\n # Response from Contact Us: \\n\n # Name : \"\"\" + str(name) + \"\"\"\n # Phone : \"\"\" + str(phone) + \"\"\" \n # Email ID : \"\"\" + str(email) + \"\"\"\n # Company : \"\"\" + str(company) + \"\"\" \n # Any Note : \"\"\" + str(note) + \"\"\" \\n\n # \"\"\"\n # print(mail_msg)\n\n\n # if no entry in the form\n # if(not name or not phone or not email or not note):\n # err_msg = \"Give all the inputs\"\n # print(err_msg)\n # flash(err_msg,\"error\")\n # return redirect(\"/contactUS\")\n\n #check whether phoneNO is 10 digits\n # if(len(str(phone))!=10 or str(phone)[0]=='0'):\n # err_msg = \"Enter 10 digits Phone no.\"\n # print(err_msg)\n # flash(err_msg,\"error\")\n # return redirect(\"/contactUS\")\n\n\n mail_msg = \"\"\"\n Response from PPC-channel-loyalty-program landing page: \\n\n Name : \"\"\" + str(name) + \"\"\"\n Phone : \"\"\" + str(phone) + \"\"\" \n Email ID : \"\"\" + str(email) + \"\"\" \n Any Note : \"\"\" + str(note) + \"\"\" \\n\n \"\"\"\n\n print(mail_msg)\n\n print(\"\\n Mailing..........\")\n msg_company = Message(\n # sender = (\"Test\",\"testing0963@gmail.com\"),\n sender = (\"Website\",\"info@loyaltyfox.com\"),\n recipients=[\"info@loyaltyfox.com\",\"testing0963@gmail.com\"],\n body = mail_msg\n # subject = \"ContactUS form\"\n )\n # msg.body = \"Hey avi\"\n msg_company.subject = \"Loyalty Fox Website | ppc-channel-loyalty-program Response\"\n mail.send(msg_company)\n\n # mail_company(mail_msg)\n print(\"mailed to loyality fox..\")\n \n\n #mail the the person whom want to be contacted\n msg_viewer = Message(\n sender = (\"Website\",\"info@loyaltyfox.com\"),\n recipients=[email],\n body = mail_msg\n # subject = \"ContactUS form\"\n )\n # msg.body = \"Hey avi\"\n msg_viewer.subject = \"Loyalty Fox | ppc-channel-loyalty-program Response\"\n # mail.send(msg_viewer)\n\n # mail_viwer(email,mail_msg)\n print(\"mailed to user.\")\n flash(\"Thank you for your interest, we'll contact you soon. For any other query, you can call us on 8802065822 or write to us on info@loyaltyfox.com. \",\"success\")\n \n return render_template(\"ppc-channel.html\")\n\n\n@app.route(\"/gift-vouchers/\", methods=[\"GET\",\"POST\"])\n@app.route(\"/gift-vouchers\", methods=[\"GET\",\"POST\"])\ndef gifts():\n if request.method == \"POST\":\n # try\n name = request.form.get(\"name\")\n # name = request.form[\"name\"]\n phone = request.form.get(\"phone\")\n email = request.form.get(\"email\")\n note = request.form.get(\"message\")\n \n # mail_msg = \"\"\"\n # Response from Contact Us: \\n\n # Name : \"\"\" + str(name) + \"\"\"\n # Phone : \"\"\" + str(phone) + \"\"\" \n # Email ID : \"\"\" + str(email) + \"\"\"\n # Company : \"\"\" + str(company) + \"\"\" \n # Any Note : \"\"\" + str(note) + \"\"\" \\n\n # \"\"\"\n # print(mail_msg)\n\n\n # if no entry in the form\n # if(not name or not phone or not email or not note):\n # err_msg = \"Give all the inputs\"\n # print(err_msg)\n # flash(err_msg,\"error\")\n # return redirect(\"/contactUS\")\n\n #check whether phoneNO is 10 digits\n # if(len(str(phone))!=10 or str(phone)[0]=='0'):\n # err_msg = \"Enter 10 digits Phone no.\"\n # print(err_msg)\n # flash(err_msg,\"error\")\n # return redirect(\"/contactUS\")\n\n\n mail_msg = \"\"\"\n Response from Gift-vouchers landing page: \\n\n Name : \"\"\" + str(name) + \"\"\"\n Phone : \"\"\" + str(phone) + \"\"\" \n Email ID : \"\"\" + str(email) + \"\"\" \n Any Note : \"\"\" + str(note) + \"\"\" \\n\n \"\"\"\n\n print(mail_msg)\n\n print(\"\\n Mailing..........\")\n msg_company = Message(\n # sender = (\"Test\",\"testing0963@gmail.com\"),\n sender = (\"Website\",\"info@loyaltyfox.com\"),\n recipients=[\"info@loyaltyfox.com\",\"testing0963@gmail.com\"],\n body = mail_msg\n # subject = \"ContactUS form\"\n )\n # msg.body = \"Hey avi, get lost\"\n msg_company.subject = \"Loyalty Fox Website | gift-vouchers page Response\"\n mail.send(msg_company)\n\n # mail_company(mail_msg)\n print(\"mailed to loyality fox..\")\n \n\n #mail the the person whom want to be contacted\n msg_viewer = Message(\n sender = (\"Website\",\"info@loyaltyfox.com\"),\n recipients=[email],\n body = mail_msg\n # subject = \"ContactUS form\"\n )\n # msg.body = \"Hey avi, get lost\"\n msg_viewer.subject = \"Loyalty Fox | gift-vouchers Response\"\n # mail.send(msg_viewer)\n\n # mail_viwer(email,mail_msg)\n print(\"mailed to user.\")\n flash(\"Thank you for your interest, we'll contact you soon. For any other query, you can call us on 8802065822 or write to us on info@loyaltyfox.com. \",\"success\")\n \n return render_template(\"gift-vouchers.html\")\n\n\n# --------------------------------------------------------------------------------\n\n# Blog page\n# @app.route(\"/add_blog/\", methods=[\"GET\",\"POST\"])\n@app.route(\"/add_blog\", methods=[\"GET\",\"POST\"])\n@login_required\ndef add_blog():\n # try:\n\n if(request.method == \"POST\"):\n title = request.form.get(\"title\")\n abstract = request.form.get(\"abstract\")\n file = request.files[\"image_file\"]\n content = request.form.get(\"content\")\n\n filename = secure_filename(file.filename)\n\n if not content:\n err_msg = \"Content/Main body field empty !\"\n flash(err_msg,\"error\")\n return redirect(\"/add_blog\")\n\n if(file and len(filename)>100):\n flash(\"Please upload file with shorter filename\",\"error\")\n return redirect(\"/add_blog\")\n\n imagename = str(filename) + \"_--_\" + str(title)\n imagename_secure = secure_filename(imagename)\n print(imagename_secure)\n\n \n if file:\n if allowed_file(file.filename):\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], imagename_secure))\n\n # file_path = UPLOAD_FOLDER + \"/\" + str(imagename_secure)\n # file.save(file_path)\n\n #adding row in table\n new_blog_entry = blogs_table(title=title,abstract=abstract,content=content, image=imagename_secure)\n\n db.session.add(new_blog_entry)\n db.session.commit()\n\n flash(\"Blog added successfully\",\"success\")\n return redirect(\"/dashboard\")\n\n else:\n flash('Invalid, Upload only png, jpg, jpeg, gif')\n\n return render_template(\"add_blog.html\")\n\n # except Exception as e:\n # print(e)\n # err_msg = \"Error in add_blog: \" + str(e)\n # print(err_msg)\n # flash(err_msg,\"error\")\n # return redirect(\"/add_blog\")\n\n#----------------------------------------------------\n# @app.route(\"/blogs\")\n# @app.route(\"/blogs/\")\n# def blogsNew():\n# return render_template(\"blogs_new.html\")\n\n\n\n\n@app.route(\"/dashboard\", methods=[\"GET\",\"POST\"])\n@login_required\ndef blogs_dashboard():\n # try\n\n all_blogs_list = blogs_table.query.order_by(blogs_table.id.desc()).all()\n print(all_blogs_list)\n\n return render_template(\"blogs_dashboard.html\",all_blogs_list=all_blogs_list)\n\n\n@app.route(\"/delete/\")\n@login_required\ndef blog_delete(blog_id):\n\n image_obj = blogs_table.query.filter_by(id=blog_id).first()\n imagename_secure = image_obj.image\n print(imagename_secure)\n blogs_table.query.filter_by(id=blog_id).delete()\n os.remove(os.path.join(app.config['UPLOAD_FOLDER'], imagename_secure))\n # post.delete()\n db.session.commit()\n\n return redirect(\"/dashboard\")\n\n\n# @app.route(\"/blogs/\", methods=[\"GET\",\"POST\"])\n@app.route(\"/blogs\", methods=[\"GET\",\"POST\"])\ndef blogs():\n # try\n\n all_blogs_list = blogs_table.query.order_by(blogs_table.id.desc()).all()\n print(all_blogs_list)\n\n return render_template(\"blogsx.html\",all_blogs_list=all_blogs_list)\n\n\n# @app.route(\"/blog_post\")\n@app.route(\"/blog_post/\")\ndef blog_post(blog_id):\n post = blogs_table.query.filter_by(id=blog_id).first()\n\n return render_template(\"postx.html\",post=post)\n\n\n@app.route(\"/admin\", methods=[\"GET\",\"POST\"])\ndef admin_login():\n if(request.method==\"POST\"):\n username = request.form.get(\"user_name\")\n password = request.form.get(\"password\")\n\n user_obj = User.query.filter_by(username=username).first()\n \n if user_obj:\n if(username==user_obj.username and password==user_obj.password):\n print(user_obj.username)\n login_user(user_obj)\n print(current_user)\n return redirect(\"/dashboard\")\n \n else:\n err_msg = \"Username/Password Incorrect !\"\n flash(err_msg,\"error\")\n \n else:\n err_msg = \"Username/Password Incorrect !\"\n flash(err_msg,\"error\")\n\n \n return render_template(\"admin_login.html\")\n \n\n#logout API\n@app.route(\"/logout\")\n@login_required\ndef logout():\n id = current_user.id\n user = User.query.filter_by(id=id).first()\n # print(user)\n logout_user()\n flash(\"You are logged out\",\"success\")\n return redirect(\"/admin\")\n\n# --------------------------------------------------------------------------\n\n\n#API for sitemap.xml file\n@app.route(\"/sitemap.xml\")\ndef sitemap():\n template = render_template(\"sitemap.xml\")\n response = make_response(template)\n response.headers['Content-Type'] = 'application/xml'\n\n return response\n # return render_template(\"sitemap.xml\")\n\n\n@app.route(\"/abc.xml\")\ndef abc():\n template = render_template(\"abc.xml\")\n response = make_response(template)\n response.headers['Content-Type'] = 'application/xml'\n\n return response\n\n# --------------------------------------------------------------------------\n\n\nif __name__ == \"__main__\":\n db.create_all()\n # admin = User(username=\"admin\",password=\"admin\")\n # db.session.add(admin)\n # db.session.commit()\n app.run(debug=True, port=5000, host=\"0.0.0.0\")\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":22006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"628724879","text":"# -*- coding: utf-8 -*-\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\n\nfrom odoo import fields,models,api, _\n\nclass ProductTemplate(models.Model):\n\n\t_inherit = \"product.template\"\n\n\tis_active_custom = fields.Boolean('Is Active',default=False)\n\tonhand_qty = fields.Float('On Hand',related='qty_available')","sub_path":"wibtec_product_archive/models/product_template.py","file_name":"product_template.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"389517262","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Mar 15 17:37:34 2019\r\n\r\n@author: niranjans4\r\n\"\"\"\r\n\r\nprint(\"Hello WOrld\")\r\n\r\nimport matplotlib.pyplot as plt \r\n \r\n# x axis values \r\nx = [1,2,3,10,0,-5,6,11,55,36] \r\n# corresponding y axis values \r\ny = [1,5,3,25,56,0,-11,23,-65,75] \r\n \r\n# plotting the points \r\nplt.plot(x, y) \r\n \r\n# naming the x axis \r\nplt.xlabel('x - axis') \r\n# naming the y axis \r\nplt.ylabel('y - axis') \r\n \r\n# giving a title to my graph \r\nplt.title('My first graph!') \r\n \r\n# function to show the plot \r\nplt.show() \r\n\r\n\r\nleft = [0, 3, 6, 4, 5] \r\n \r\n# heights of bars \r\nheight = [10, 24, 36, 40, 5] \r\n \r\n# labels for bars \r\ntick_label = ['one', 'nir', 'three', 'four', 'five'] \r\n \r\n# plotting a bar chart \r\nplt.bar(left, height, tick_label = tick_label, \r\n width = 0.8, color = ['red', 'green']) \r\n \r\n# naming the x-axis \r\nplt.xlabel('x - axis') \r\n# naming the y-axis \r\nplt.ylabel('y - axis') \r\n# plot title \r\nplt.title('My bar chart!') \r\n \r\n# function to show the plot \r\nplt.show() \r\n\r\n \r\n# defining labels \r\nactivities = ['eat', 'sleep', 'work', 'play'] \r\n \r\n# portion covered by each label \r\nslices = [3, 7, 8, 6] \r\n \r\n# color for each label \r\ncolors = ['r', 'y', 'g', 'b'] \r\n \r\n# plotting the pie chart \r\nplt.pie(slices, labels = activities, colors=colors, \r\n startangle=90, shadow = False, explode = (0.05, 0, 0, 0), \r\n radius = 1, autopct = '%1.1f%%') \r\n \r\n# plotting legend \r\n#plt.legend() \r\n \r\n# showing the plot \r\n#plt.show() ","sub_path":"Hello_World_graphs.py","file_name":"Hello_World_graphs.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"19349836","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef RK4(f, r0, tf, dt):\n \"\"\"Fourth-order Runge-Kutta integrator.\n\n :param f: Function to be integrated\n :param r0: Initial conditions\n :param tf: Integration duration\n :param dt: Timestep size\n :returns: time and trajectory vectors\n\n \"\"\"\n\n # generate an array of time steps\n ts = np.arange(0, tf, dt)\n # create an array to hold system state at each timestep\n traj = np.zeros((ts.shape[0], len(r0)))\n traj[0, :] = np.array(r0)\n # calculate system state at each time step, save it in the array\n for i in range(0, ts.shape[0]-1):\n t = ts[i]\n r = traj[i, :]\n\n k1 = dt * f(r, t)\n k2 = dt * f(r + k1/2, t + dt/2)\n k3 = dt * f(r + k2/2, t + dt/2)\n k4 = dt * f(r + k3, t + dt)\n K = (1.0/6)*(k1 + 2*k2 + 2*k3 + k4)\n\n traj[i+1, :] = r + K\n return (ts, traj)\n\ndef generateChain(r0, tf, dt, K,a_c,b_c,a_p,b_p,x0,y0,eps):\n \"\"\"Integrate a given Lorenz system.\"\"\"\n\n # define equations of lorenz system\n def Chain(r, t):\n x1 = r[0]; y1 = r[1]; z1 = r[2]\n x2 = r[3]; y2 = r[4]; z2 = r[5]\n u1 = x1*(1-x1/K) - (a_c*b_c*x1*y1/(x1+x0))\n v1 = a_c*y1*((b_c*x1/(x1+x0))-1)-(a_p*b_p*y1*z1/(y1+y0))+eps*(y2-y1)\n w1 = a_p*z1*(b_p*y1/(y1+y0)-1)+eps*(z2-z1)\n u2 = x2*(1-x2/K) - (a_c*b_c*x2*y2/(x2+x0))\n v2 = a_c*y2*((b_c*x2/(x2+x0))-1)-(a_p*b_p*y2*z2/(y2+y0))+eps*(y1-y2)\n w2 = a_p*z2*(b_p*y2/(y2+y0)-1)+eps*(z1-z2)\n return np.array([u1, v1, w1, u2, v2, w2])\n\n ts, traj = RK4(Chain, r0, tf, dt)\n return (ts, traj)\n\ndef get_chain_data(tf=250, dt=0.02, skip=25, split=0.8):\n _, traj = generateChain((1, 1, 1, 1.2,1.3,1.4), tf, dt, 10, 28, 2)\n \n skip_steps = int(25 / dt)\n traj = traj[skip_steps:]\n \n split_num = int(split * traj.shape[0])\n \n train_data = traj[:split_num]\n val_data = traj[split_num:]\n \n return train_data, val_data\n\ndef delta():\n delta_x = []\n epsilon = np.linspace(0.0, 0.012, 40)\n for j in range(40):\n T,traj=generateChain((1,1,1,1.2,1.3,1.4),tf,dt,0.99,0.4,2.009,0.08,2.876,0.16129,0.5,epsilon[j])\n delta_sum = 0\n Y1 = traj[500:,0]\n Y2 = traj[500:,3]\n T = T[500:]\n for i in range(len(T)):\n delta_sum += abs(Y1[i]-Y2[i])\n delta_ave = delta_sum/len(T)\n delta_x.append(delta_ave)\n delta_x = np.asarray(delta_x)\n epsilon = np.asarray(epsilon)\n return (epsilon, delta_x)\n\nif __name__==\"__main__\":\n tf, dt = 1000, 0.02\n T, traj = generateChain((1, 1, 1,1.2,1.3,1.4),tf,dt,0.99,0.4,2.009,0.08,2.876,0.16129,0.5,0.006)\n epsilon, delta_x = delta()\n plt.figure()\n plt.plot(T[500:], traj[500:,3])\n plt.xlim([200,400])\n plt.figure()\n plt.plot(T[500:], traj[500:,1])\n plt.xlim([200,400])\n plt.figure()\n plt.plot(epsilon, delta_x, 'r-',marker='s')\n plt.show()\n","sub_path":"reservoir/reservoir-computer-lorenz-master/synchro/food_chains.py","file_name":"food_chains.py","file_ext":"py","file_size_in_byte":2920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"653389361","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 5 13:45:45 2021\n\n@author: vishakha\n\"\"\"\nimport numpy as np\nimport sys\nimport matplotlib.pyplot as plt\n\nsys.path.append(\".\")\nfrom Random import Random\n\nif __name__ == \"__main__\":\n\n\t#set default number of samples\n\tNsample = 1000\n\n\t# read the user-provided seed from the command line (if there)\n\tif '-Nsample' in sys.argv:\n\t\tp = sys.argv.index('-Nsample')\n\t\tNsample = int(sys.argv[p+1])\n\tif '-h' in sys.argv or '--help' in sys.argv:\n\t\tprint (\"Usage: %s -Nsample [number]\" % sys.argv[0])\n\t\tprint\n\t\tsys.exit(1) \n\n\tnAccept = 0\n\tnTotal = 0\n\n\t# accepted values\n\tXaccept = []\n\tYaccept = []\n\n\t# reject values\n\tXreject = []\n\tYreject = []\n\n\t# sample number\n\tisample = []\n\t# calculated values of Pi (per sample)\n\tcalcPi = []\n\n\trandom = Random()\n\n\tidraw = max(1,int(Nsample)/100000)\n\tfor i in range(0,Nsample):\n\t\tX = random.rand()\n\t\tY = random.rand()\n\n\t\tnTotal += 1\n\t\tif(X*X + Y*Y <= 1): #accept if inside\n\t\t\tnAccept += 1\n\t\t\tif(i % idraw == 0):\n\t\t\t\tXaccept.append(X)\n\t\t\t\tYaccept.append(Y)\n\t\telse: # reject if outside\n\t\t\tif(i % idraw == 0):\n\t\t\t\tXreject.append(X)\n\t\t\t\tYreject.append(Y)\n\t\tif(i % idraw == 0):\n\t\t\tisample.append(nTotal)\n\t\t\tcalcPi.append(4*nAccept/nTotal)\n\n\n\n\t#plot calculated pi vs sample number\n\tfig1 = plt.figure()\n\tplt.plot(isample,calcPi)\n\tplt.ylabel(r'Approximate $\\pi$')\n\tplt.xlabel(\"Sample number\")\n\tplt.xlim(0,isample[len(isample)-1])\n\tax = plt.gca()\n\tax.axhline(y=np.arccos(-1),color='green',label=r'true $\\pi$')\n\tplt.title(r'Approximation of $\\pi$ as a function of number of samples')\n\tplt.legend()\n\n\tfig1.savefig(\"calculatedPiPy.pdf\")\n\n\n\t#plot accept/reject points\n\tfig2 = plt.figure()\n\tplt.plot(Xaccept,Yaccept,marker='o',linestyle='',color='green',label='accept')\n\tplt.plot(Xreject,Yreject,marker='o',linestyle='',color='red',label='reject')\n\tplt.ylabel(\"Y\")\n\tplt.xlabel(\"X\")\n\tplt.legend()\n\n\n\tx_circle = np.arange(min(min(Xaccept),min(Xreject)),max(max(Xaccept),max(Xreject)),0.001)\n\ty_circle = [np.sqrt(1-i*i) for i in x_circle]\n\tplt.plot(x_circle,y_circle,color='blue',label=r'$x^2 + y^2 = 1$')\n\tplt.legend()\n\tplt.title('Sampled points')\n\tfig2.savefig(\"circleQuadPy.pdf\")","sub_path":"untitled3.py","file_name":"untitled3.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"315924195","text":"import os\nimport re\nimport cv2\nimport argparse\nimport functools\nimport subprocess\nimport numpy as np\nfrom PIL import Image\nimport moviepy.editor as mpy\n\nimport torchvision\nimport torch.nn.parallel\nimport torch.optim\nfrom ops.models import TSN\nfrom ops.transforms import * \nfrom torch.nn import functional as F\nimport uuid\ndef generateFileName():\n\tunique_filename = str(uuid.uuid4())\n\treturn uniunique_filename\ndef parse_shift_option_from_log_name(log_name):\n if 'shift' in log_name:\n strings = log_name.split('_')\n for i, s in enumerate(strings):\n if 'shift' in s:\n break\n return True, int(strings[i].replace('shift', '')), strings[i + 1]\n else:\n return False, None, None\n \n \n# options\nparser = argparse.ArgumentParser(description=\"test TSM on a single video\")\ngroup = parser.add_mutually_exclusive_group(required=True)\ngroup.add_argument('--video_file', type=str, default=None)\ngroup.add_argument('--frame_folder', type=str, default=None)\nparser.add_argument('--modality', type=str, default='RGB',\n choices=['RGB', 'Flow', 'RGBDiff'], )\nparser.add_argument('--dataset', type=str, default='moments',\n choices=['ucfcrime','something', 'jester', 'moments', 'somethingv2'])\nparser.add_argument('--rendered_output', type=str, default=None)\n#parser.add_argument('--arch', type=str, default=\"InceptionV3\")\nparser.add_argument('--input_size', type=int, default=224)\nparser.add_argument('--test_segments', type=int, default=8)\nparser.add_argument('--img_feature_dim', type=int, default=256)\nparser.add_argument('--consensus_type', type=str, default='avg')\nparser.add_argument('--weights', type=str)\n\n\nargs = parser.parse_args()\nthis_weights = args.weights\nis_shift, shift_div, shift_place = parse_shift_option_from_log_name(this_weights)\nmodality = 'RGB'\nif 'RGB' in this_weights:\n\tmodality = 'RGB'\n\n# Get dataset categories.\ncategories = ['Normal', #0\n\t'Abnormal', ] #10\nnum_class = len(categories)\nthis_arch = 'resnet50'\n\nnet = TSN(num_class, 1, modality,\n base_model=this_arch,\n consensus_type='avg',\n img_feature_dim=args.img_feature_dim,\n #pretrain=args.pretrain,\n is_shift=is_shift, shift_div=shift_div, shift_place=shift_place,\n non_local='_nl' in this_weights,\n )\n\ncheckpoint = torch.load(this_weights)\ncheckpoint = checkpoint['state_dict']\n\n# base_dict = {('base_model.' + k).replace('base_model.fc', 'new_fc'): v for k, v in list(checkpoint.items())}\nbase_dict = {'.'.join(k.split('.')[1:]): v for k, v in list(checkpoint.items())}\nreplace_dict = {'base_model.classifier.weight': 'new_fc.weight',\n 'base_model.classifier.bias': 'new_fc.bias',\n }\nfor k, v in replace_dict.items():\n if k in base_dict:\n base_dict[v] = base_dict.pop(k)\n\nnet.load_state_dict(base_dict)\nnet.cuda().eval()\n\ntransform=torchvision.transforms.Compose([\n Stack(roll=(this_arch in ['BNInception', 'InceptionV3'])),\n ToTorchFormatTensor(div=(this_arch not in ['BNInception', 'InceptionV3'])),\n GroupNormalize(net.input_mean, net.input_std),\n ])\n\n\ndef extract_frames(video_file, num_frames=8):\n try:\n os.makedirs(os.path.join(os.getcwd(), 'frames'))\n except OSError:\n pass\n\n output = subprocess.Popen(['ffmpeg', '-i', video_file],\n stderr=subprocess.PIPE).communicate()\n # Search and parse 'Duration: 00:05:24.13,' from ffmpeg stderr.\n re_duration = re.compile('Duration: (.*?)\\.')\n duration = re_duration.search(str(output[1])).groups()[0]\n\n seconds = functools.reduce(lambda x, y: x * 60 + y,\n map(int, duration.split(':')))\n rate = num_frames / float(seconds)\n print(rate)\n output = subprocess.Popen(['ffmpeg', '-i', video_file,\n '-vf', 'fps={}'.format(rate),\n '-vframes', str(15),\n '-loglevel', 'panic',\n 'frames/%d.jpg']).communicate()\n frame_paths = sorted([os.path.join('frames', frame)\n for frame in os.listdir('frames')])\n\n frames = load_frames(frame_paths)\n subprocess.call(['rm', '-rf', 'frames'])\n print(len(frames))\n return frames\n\n\ndef load_frames(frame_paths, num_frames=8):\n frames = [Image.open(frame).convert('RGB') for frame in frame_paths]\n if len(frames) >= num_frames:\n return frames[::int(np.ceil(len(frames) / float(num_frames)))]\n else:\n raise ValueError('Video must have at least {} frames'.format(num_frames))\n\n\ndef render_frames(frames, prediction):\n rendered_frames = []\n for frame in frames:\n img = np.array(frame)\n height, width, _ = img.shape\n cv2.putText(img, prediction,\n (0, int(height / 16)),\n cv2.FONT_HERSHEY_SIMPLEX,\n 0.7, (0, 255, 255), 2)\n rendered_frames.append(img)\n return rendered_frames\n\n\n# Obtain video frames\nif args.frame_folder is not None:\n print('Loading frames in {}'.format(args.frame_folder))\n import glob\n # Here, make sure after sorting the frame paths have the correct temporal order\n frame_paths = sorted(glob.glob(os.path.join(args.frame_folder, '*.jpg')))\n frames = load_frames(frame_paths)\nelse:\n print('Extracting frames using ffmpeg...')\n frames = extract_frames(args.video_file, args.test_segments)\n\n#print(frames)\n# Make video prediction.\ndata = transform(frames)\ninput = data.view(-1, 3, data.size(1), data.size(2)).unsqueeze(0).cuda()\n\nwith torch.no_grad():\n logits = net(input)\n h_x = torch.mean(F.softmax(logits, 1), dim=0).data\n probs, idx = h_x.sort(0, True)\n\n# Output the prediction.\nvideo_name = args.frame_folder if args.frame_folder is not None else args.video_file\nprint('RESULT ON ' + video_name)\nfor i in range(0, 2):\n print('{:.3f} -> {}'.format(probs[i], categories[idx[i]]))\n\n# Render output frames with prediction text.\nif args.rendered_output is not None:\n prediction = categories[idx[0]]\n rendered_frames = render_frames(frames, prediction)\n clip = mpy.ImageSequenceClip(rendered_frames, fps=4)\n clip.write_videofile(args.rendered_output)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"tsm_model/SingleVideoTest.py","file_name":"SingleVideoTest.py","file_ext":"py","file_size_in_byte":6389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"158187227","text":"#! /usr/bin/env python\nimport csv\nimport os\n\ndataname = 'movie'\nmp = '4'\nots = ['0.200000',\n '0.400000',\n '0.600000',\n '0.800000',\n '1.000000',]\n\nmethods = ['BFCS', 'EFCS', 'QFCS', 'BPCS', 'EPCS', 'QPCS']\n\nfor ot in ots:\n inputDir = dataname + '_MP' + mp + '_overlap_threshold' + ot + '/'\n outputDir = dataname + '_MP' + mp + '_overlap/'\n for method in methods:\n inputFileName = inputDir + method + '_OVERLAP_averageMAE.txt'\n inputFile = open(inputFileName, 'r')\n tsv = csv.reader(inputFile, delimiter = '\\t')\n for row in tsv:\n missing = row[0]\n outputPath = outputDir + str(missing) + '/'\n if not os.path.exists(outputPath):\n os.makedirs(outputPath)\n outputFileName = outputPath + method + '.txt'\n outputFile = open(outputFileName, 'a')\n outputFile.write(ot + '\\t' + row[1] + '\\t' + row[2] + '\\n')\n outputFile.close()\n inputFile.close()\n","sub_path":"data/result_data/MAE/movie/result1.py","file_name":"result1.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"225226051","text":"from glob import glob\nfrom scipy.ndimage import imread\nimport scipy.misc\nfrom argparse import ArgumentParser\nimport os\nimport time\nfrom tqdm import tqdm\n\ndef main(in_path, out_path, folder_name_base, split_number):\n frames = sorted(glob(os.path.join(in_path, \"*\")))\n folder = []\n for i in range(split_number):\n folder_name = os.path.join(out_path, folder_name_base) + \"_\" + str(i)\n folder.append(folder_name)\n if not os.path.exists(folder_name):\n os.makedirs(folder_name)\n\n start_time = time.time()\n for index, frame in tqdm(enumerate(frames)):\n img = imread(frame)\n frame_name = frame.split('/',-1)[-1]\n scipy.misc.toimage(img).save(os.path.join(folder[index % split_number], frame_name))\n #if (time.time() - start_time) > 1:\n #print(str(index)+\"|\"+str(len(frames))+\": \"+frame+\" to \"+folder[index % split_number])\n #start_time = time.time()\n\nif __name__ == \"__main__\":\n parser = ArgumentParser()\n parser.add_argument(\"--inpath\", type=str, dest=\"in_path\",\n required=True, help=\"Path to directory of the images\")\n parser.add_argument(\"--outpath\", type=str, dest=\"out_path\",\n required=True, help=\"Path to directory where images should be saved (base directory)\")\n parser.add_argument(\"--basename\", type=str, dest=\"folder_name_base\",\n required=True, help=\"Base name of the folders in which the splitted images should be saved\")\n parser.add_argument(\"--splits\", type=int, dest=\"split_number\",\n required=True, help=\"In how many groups the images should be split up \")\n\n args = parser.parse_args()\n main(**vars(args))\n","sub_path":"storage/preprocessing/split_frames.py","file_name":"split_frames.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"577886950","text":"import ctypes\nimport time\nimport subprocess\nimport sys\n\n\"\"\"\nWait for an opened window to close and then execute a command.\nThis script is useful in large data copies. You subscribe a\nwatch on the copy window and when the copy is finished then\nyou can execute a showtdown command\n\nUsage:\n $ wait_for_window.py [description] [sleep time] [cmd]\n [description]: part of the window title\n [sleep time]: time between each scan\n [cmd]: command to execute after the window closes\n\nExample:\n wait_fot_window.py complete 5 \"shutdown -s 0\"\n\n (In Windows 10 during a copy the window title is something\n like \"45% complete\", therefore by using just the word\n complete the script will scan every 5 secs for the window\n and when copy is finished and the windows closes then\n executes a shutdown.)\n\"\"\"\n\nEnumWindows = ctypes.windll.user32.EnumWindows\nEnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int))\nGetWindowText = ctypes.windll.user32.GetWindowTextW\nGetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW\nIsWindowVisible = ctypes.windll.user32.IsWindowVisible\n\ntitles = []\n\n\ndef foreach_window(hwnd, lParam):\n \"\"\"\n Get the window titles from all opened windows\n :param hwnd:\n :param lParam:\n :return:\n \"\"\"\n if IsWindowVisible(hwnd):\n length = GetWindowTextLength(hwnd)\n buff = ctypes.create_unicode_buffer(length + 1)\n GetWindowText(hwnd, buff, length + 1)\n titles.append(buff.value)\n return True\n\n\ndef window_active(window_name):\n \"\"\"\n Scan for partial windows_name in the windows titles list\n :param window_name: A part of the window name\n :return: True, if name if found in at least one title, otherwise False\n \"\"\"\n # Clear list from previous entries\n titles.clear()\n EnumWindows(EnumWindowsProc(foreach_window), 0)\n for wnd_title in titles:\n if wnd_title.find(window_name) >= 0:\n return True\n return False\n\n\ndef wait_for_window(window_name, sleep_time, exec_cmd):\n \"\"\"\n Wait for ever until the window closes\n :param window_name: The partial title name\n :param sleep_time: Sleep time in seconds after every scan\n :param exec_cmd: The shell command to execute\n :return: None\n \"\"\"\n while window_active(window_name):\n time.sleep(sleep_time)\n subprocess.call([exec_cmd])\n\n\n# Do not execute during import\nif __name__ == \"__main__\":\n print('Scanning every %s sec for %s to terminate and execute: %s' % (sys.argv[2], sys.argv[1], sys.argv[3]))\n wait_for_window(sys.argv[1], int(sys.argv[2]), sys.argv[3])\n","sub_path":"Wait-For-Window/wait_for_window.py","file_name":"wait_for_window.py","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"392369686","text":"from django.shortcuts import render,redirect\nfrom.models import Product,Cart,CartItem\nfrom Orders.models import Order\nfrom accounts.forms import LoginForm,GuestForm\nfrom Billing.models import BillingProfile\nfrom accounts.models import GuestEmail\nfrom Payments.views import charge\n\n# Create your views here.\ndef cart_home(request):\n cart_obj, new_obj = Cart.objects.new_or_get(request)\n products=cart_obj.cartitem_set.all()\n total=0\n for x in products:\n line_total = float(x.products.price) * x.quantity\n total += line_total\n print(total)\n print(cart_obj.total)\n cart_obj.total=total\n cart_obj.save()\n\n return render(request,'cart_home.html',{'cart':cart_obj})\ndef cart_update(request,slug):\n try:\n qty=request.GET.get('qty')\n update_qty = True\n except:\n qty=None\n update_qty=False\n try:\n product_obj=Product.objects.get(slug=slug)\n except Product.DoesNotExist:\n print('product out of stock')\n return redirect('carts:cart_view')\n cart_obj, new_obj = Cart.objects.new_or_get(request)\n cart_item, created = CartItem.objects.get_or_create(cart=cart_obj,products=product_obj )\n if created:\n print('created')\n if update_qty and qty :\n if int(qty)==0 :\n cart_item.delete()\n else:\n cart_item.quantity=qty\n cart_item.save()\n else:\n pass\n # if product_obj in cart_obj.items.all():\n # cart_obj.items.remove(cart_item)\n # else:\n # cart_obj.items.add(cart_item)\n products = cart_obj.cartitem_set.all()\n request.session['cart_items'] = cart_obj.cartitem_set.count()\n\n\n return redirect('carts:cart_view')\n\ndef checkout_home(request):\n cart_obj,cart_created=Cart.objects.new_or_get(request)\n order_obj=None\n has_card=False\n if cart_created or cart_obj.cartitem_set.count()==0:\n redirect('carts:cart_view')\n login_form=LoginForm()\n guest_form=GuestForm()\n # billing model manager\n billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(request)\n if billing_profile is not None:\n # order model manager\n order_obj, order_obj_created = Order.objects.new_or_get(billing_profile, cart_obj)\n has_card=billing_profile.has_card\n # finalize checkout\n if request.method == \"POST\":\n \"check the order is done\"\n is_done = order_obj.check_done()\n\n if is_done:\n order_obj.mark_paid()\n request.session['cart_items'] = 0\n del request.session['cart_id']\n\n\n return redirect('carts:success')\n context={\n 'billing_profile':billing_profile,\n 'object': order_obj,\n 'login_form':login_form,\n 'guest_form':guest_form,\n \"has_card\":has_card\n }\n return render(request,'checkout.html',context)\n\ndef checkout_done_view(request):\n return render(request,\"checkout_done.html\")","sub_path":"carts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"634619613","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport numpy\nimport sys\nimport log\nimport scipy\n\nfrom image3d import * \n#from skimage.filter import canny\nfrom PIL import Image#, ImageFilter\n\ndef get_image_channel(imarray, channelno):\n \"\"\"Returns array that is single channel of selected number from image array.\"\"\"\n width = imarray.shape[0]\n height = imarray.shape[1]\n #log.dbg(\"height=\"+str(height)+\" width=\"+str(width))\n channelarray = np.zeros((width, height))\n for x in xrange(height):\n for y in xrange(width):\n channelarray[y][x] = imarray[y][x][channelno]\n return channelarray \n\ndef get_image_dims(path):\n \"\"\"Returns width,height,depth of TIFF image.\"\"\"\n log.info(\"loading file \"+path)\n im = Image.open(path)\n\n height = im.size[0]\n width = im.size[1]\n for depth in xrange(10000): #find depth\n try: im.seek(depth)\n except: break\n log.dbg(\"height=\"+str(height)+\" width=\"+str(width)+\" depth=\"+str(depth))\n return width,height,depth\n \n\ndef yield_zstack(path):\n \"\"\"Generates triples of r,g,b-channels of consecutive layers from TIFF image.\"\"\"\n log.info(\"loading file \"+path)\n im = Image.open(path)\n\n height = im.size[0]\n width = im.size[1]\n for depth in xrange(10000): #find depth\n try: im.seek(depth)\n except: break\n log.dbg(\"height=\"+str(height)+\" width=\"+str(width)+\" depth=\"+str(depth))\n\n log.dbg(\"extracting pixel values\")\n for z in xrange(depth):\n im.seek(z)\n imarray = numpy.array(im) \n\n red_channel_array = get_image_channel(imarray, 0) \n green_channel_array = get_image_channel(imarray, 1)\n blue_channel_array = get_image_channel(imarray, 2)\n yield (red_channel_array, green_channel_array, blue_channel_array)\n\n\n\nif __name__==\"__main__\":\n log.info(\"--------------------------------------------------------------------------\")\n log.info(\"The program loads TIFF rgb file with pages and stores as separate .png files.\")\n log.info(\"Arguments: src-file, dst-file-prefix, [channel-names (rgb)], [dst-file-suffix], [resample-z times].\")\n\n try: path = sys.argv[1]\n except: log.err(\"Argument (TIFF path) expected!\"); sys.exit(-1);\n\n try: outpath = sys.argv[2]\n except: outpath = path \n\n try: channels = sys.argv[3].lower() \n except: channels = 'rgb'\n\n try: suffix = sys.argv[4].lower() \n except: suffix = ''\n\n try: resample_z = int(sys.argv[5])\n except: resample_z = 3\n\n\n log.info(\"src file = \"+path)\n log.info(\"dst prefix = \"+outpath)\n log.info(\"dst path suffix =\"+suffix)\n log.info(\"channels to be stored =\"+channels)\n log.info(\"resample_z =\"+str(resample_z))\n\n log.info(\"writing layers\")\n for z, (r,g,b) in enumerate(yield_zstack(path)):\n\n #FILTERS:\n #g = canny(g, 3, 0.3, 0.2)\n\n #STORING\n for offset in xrange(resample_z):\n nz = z*resample_z + offset\n log.dbg(\"writing layer with z=\"+str(z)+\" mapped to nz=\"+str(nz))\n if 'r' in channels:\n scipy.misc.imsave(outpath+\"_r\"+suffix+('%04d' % nz)+\".png\", r)\n if 'g' in channels:\n scipy.misc.imsave(outpath+\"_g\"+suffix+('%04d' % nz)+\".png\", g)\n if 'b' in channels:\n scipy.misc.imsave(outpath+\"_b\"+suffix+('%04d' % nz)+\".png\", b)\n\n\n","sub_path":"stackdecomposition.py","file_name":"stackdecomposition.py","file_ext":"py","file_size_in_byte":3352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"393718709","text":"\n\n#calss header\nclass _NETWORK():\n\tdef __init__(self,): \n\t\tself.name = \"NETWORK\"\n\t\tself.definitions = [u'to connect computers together so that they can share information: ', u'to meet people who might be useful to know, especially in your job: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_network.py","file_name":"_network.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"578016536","text":"import torch\nimport math\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn import Parameter\n\nfrom efficientnet import EfficientNet\nfrom senet import se_resnext50_32x4d, se_resnext101_32x4d\n\n\nclass AdaptiveConcatPool2d(nn.Module):\n def __init__(self, sz=None):\n super().__init__()\n self.output_size = sz\n self.ap = nn.AdaptiveAvgPool2d(self.output_size)\n self.mp = nn.AdaptiveMaxPool2d(self.output_size)\n\n def forward(self, x):\n return torch.cat([self.mp(x), self.ap(x)], 1)\n\n\nclass Flatten(nn.Module):\n def __init__(self):\n super().__init__()\n\n def forward(self, x):\n return x.view(x.size(0), -1)\n\n\nclass PandaNet(nn.Module):\n def __init__(self, arch, pretrained=True, embedding_size=512):\n super().__init__()\n\n # load EfficientNet\n if 'efficientnet' in arch:\n if pretrained:\n self.base = EfficientNet.from_pretrained(model_name=arch)\n else:\n self.base = EfficientNet.from_name(model_name=arch)\n\n self.nc = self.base._fc.in_features\n self.extract_features = self.base.extract_features\n\n elif arch == 'se_resnext50_32x4d':\n if pretrained:\n self.base = se_resnext50_32x4d()\n else:\n self.base = se_resnext50_32x4d(pretrained=None)\n self.nc = self.base.last_linear.in_features\n self.extract_features = self.base.features\n\n elif arch == 'se_resnext101_32x4d':\n if pretrained:\n self.base = se_resnext101_32x4d()\n else:\n self.base = se_resnext101_32x4d(pretrained=None)\n self.nc = self.base.last_linear.in_features\n self.extract_features = self.base.features\n\n self.output = nn.Sequential(AdaptiveConcatPool2d(1),\n Flatten(),\n nn.BatchNorm1d(2 * self.nc),\n nn.Dropout(0.5),\n nn.Linear(2 * self.nc, 512))\n\n def forward(self, inputs):\n bs, num_tiles, c, h, w = inputs.size()\n inputs = inputs.view(-1, c, h, w)\n\n x = self.extract_features(inputs) # bs*N x c x h x w\n shape = x.shape\n\n # concatenate the output for tiles into a single map\n x = x.view(-1, num_tiles, shape[1], shape[2], shape[3]).permute(0, 2, 1, 3, 4).contiguous() \\\n .view(-1, shape[1], shape[2] * num_tiles, shape[3])\n\n # Pooling and final linear layer\n x = self.output(x)\n\n return x\n\n\nclass ArcMarginProduct(nn.Module):\n r\"\"\"Implement of large margin arc distance: :\n Args:\n in_features: size of each input sample\n out_features: size of each output sample\n s: norm of input feature\n m: margin\n cos(theta + m)\n \"\"\"\n\n def __init__(self, in_features, out_features, s=30.0, m=0.50, easy_margin=False):\n super().__init__()\n self.in_features = in_features\n self.out_features = out_features\n self.s = s\n self.m = m\n self.weight = Parameter(torch.FloatTensor(out_features, in_features))\n nn.init.xavier_uniform_(self.weight)\n\n self.easy_margin = easy_margin\n self.cos_m = math.cos(m)\n self.sin_m = math.sin(m)\n self.th = math.cos(math.pi - m)\n self.mm = math.sin(math.pi - m) * m\n\n def forward(self, input, label):\n # --------------------------- cos(theta) & phi(theta) ---------------------------\n cosine = F.linear(F.normalize(input), F.normalize(self.weight))\n sine = torch.sqrt((1.0 - torch.pow(cosine, 2)).clamp(0, 1))\n phi = cosine * self.cos_m - sine * self.sin_m\n if self.easy_margin:\n phi = torch.where(cosine > 0, phi, cosine)\n else:\n phi = torch.where(cosine > self.th, phi, cosine - self.mm)\n # --------------------------- convert label to one-hot ---------------------------\n # one_hot = torch.zeros(cosine.size(), requires_grad=True, device='cuda')\n one_hot = torch.zeros(cosine.size(), device='cuda')\n one_hot.scatter_(1, label.view(-1, 1).long(), 1)\n # -------------torch.where(out_i = {x_i if condition_i else y_i) -------------\n output = (one_hot * phi) + (\n (1.0 - one_hot) * cosine) # you can use torch.where if your torch.__version__ is 0.4\n output *= self.s\n # print(output)\n\n return output\n","sub_path":"metric_learning/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"568813910","text":"import torch\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom layer import GraphConvolution\n\nfrom config import args\n\nclass GCN(nn.Module):\n\n\n def __init__(self, input_dim, output_dim, num_features_nonzero):\n super(GCN, self).__init__()\n\n self.input_dim = input_dim # 1433\n self.output_dim = output_dim\n\n print('input dim:', input_dim)\n print('output dim:', output_dim)\n print('num_features_nonzero:', num_features_nonzero)\n\n\n self.layers1 = nn.Sequential(GraphConvolution(self.input_dim, args.hidden, num_features_nonzero,\n activation=F.relu,\n dropout=args.dropout,\n is_sparse_inputs=True)\n ).to('cuda:0')\n self.layers2 = nn.Sequential(GraphConvolution(args.hidden, output_dim, num_features_nonzero,\n activation=F.relu,\n dropout=args.dropout,\n is_sparse_inputs=False)\n ).to('cuda:1')\n\n def forward(self, inputs):\n # x, support = inputs\n # x, support = self.layers1((x, support))\n # x = self.layers2((x, support))\n\n x, support = self.layers1(inputs)\n x = self.layers2((x.to('cuda:1'), support.to('cuda:1')))\n\n return x\n\n def l2_loss(self):\n\n layer = self.layers1.children()\n loss = None\n\n for l in layer:\n for p in l.parameters():\n if loss is None:\n loss = p.pow(2).sum()\n else:\n loss += p.pow(2).sum()\n loss = loss.to('cuda:1')\n # print(loss.device)\n layer = self.layers2.children()\n for l in layer:\n for p in l.parameters():\n if loss is None:\n loss = p.pow(2).sum()\n else:\n loss += p.pow(2).sum()\n \n return loss\n","sub_path":"pipe_model.py","file_name":"pipe_model.py","file_ext":"py","file_size_in_byte":2151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"363552213","text":"from django.conf.urls import url\nfrom .views import *\n\nurlpatterns = [\n url(r'^index',index,name='index'),\n url(r'^login', login, name='login'),\n\n url(r'^register', register, name='register'),\n url(r'^check', check, name='check'),\n\n]","sub_path":"python1808/Django/Day06/Day06Django/CookApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"59176898","text":"'''\nYour friend has come up with a way to represent any number using binary,\nbut the number of bits can be infinite to represent even the smallest of numbers!\nHe thinks it will be hard to break since just one number can be represented in\nso many different (and long) ways:\n\n'000000000000000000000000' == 0\n\n'111111111111' == 0\n\n'0101101001100110' == 0\n\nHe isn't a horrible friend so he's given you lots of examples... see if you can crack his code!\n\nInstructions\nYour task is to write a function that can decode binary, provided as a string, into the number it represents.\n\nYou can safely assume that the given string will only contain ones and zeroes,\nalthough it may be empty (in which case the expected number is 0).\n\nSome representations can be very long so make sure your solution is reasonably efficient.\n\nGood Luck!\n'''\n\n\ndef decode_bits(bin_str):\n nums, tens = [int(x) for x in bin_str], 0\n for i in range(len(nums)):\n if i % 2 != 0:\n tens += nums[i]\n else:\n tens -= nums[i]\n return tens","sub_path":"kyu6/Infinite Length Binary Code.py","file_name":"Infinite Length Binary Code.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"320613298","text":"\"\"\"\nStartup Code\n\n@author: David Schote\n@reworked by: Sula Mueller\n@contact: david.schote@ovgu.de\n@version: 2.0.2\n@change: 02/11/2020\n\"\"\"\n\n# system includes\nimport sys\nfrom PyQt5.QtWidgets import QApplication\n\n# project includes\nfrom mainviewcontroller import MainViewController\n\nVERSION = \"2.0.2\"\nAUTHOR = \"David Schote, Sula Mueller\"\n\nif __name__ == '__main__':\n print(\"Graphical User Interface for Magnetic Resonance Imaging {} by {}\".format(VERSION, AUTHOR))\n app = QApplication(sys.argv)\n gui = MainViewController()\n gui.show()\n gui.connectiondialog.show()\n sys.exit(app.exec_())\n","sub_path":"GOmri.py","file_name":"GOmri.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"632906492","text":"## BINARY SEARCH:\n# # nailing planks solution:\n# def solution(A, B, C):\n# # write your code in Python 3.6\n# min_plank = 0\n# max_plank = len(A)-1\n# plank = [0]*len(A)\n# for index,nail in enumerate(C):\n# min_plank = 0\n# max_plank = len(A)-1\n# while (min_plank <= max_plank):\n# if nail >= A[min_plank] and nail <= B[min_plank]:\n# plank[min_plank] = 1\n# min_plank += 1\n# if set(plank) == {1}:\n# return index+1\n# else:\n# min_plank += 1\n# if set(plank) != {1}:\n# return -1\n \n# pass\n\n# solution([1, 4, 5, 8], [4, 5, 9, 10], [4, 6, 7, 10, 2])\n\n# C = [4, 6, 7, 10, 2]\n# nails = sorted(enumerate(C), key = lambda x: x[1])\n# print(nails)\n# print(len(nails))\n\n# print(sum(C[0:1]))\n\n\n# def solution(A):\n# # write your code in Python 3.6\n# if len(A) < 3:\n# return abs(A[0]-A[1])\n# P = 1\n# t1 = 0\n# t2 = 0\n# min = abs(sum(A))\n# while (P < len(A)):\n# t1 = sum(A[0:P])\n# t2 = sum(A[P:len(A)])\n# if (abs(t1-t2) 0:\n index = self.sess.run([node.prev_weights_eval], feed_dict={self.is_eval: True})[0]\n node.params.prev_node_names = []\n for idx in range(len(index)):\n if index[idx] == 1.0:\n node.prev_nodes[idx].active = True\n if node.prev_nodes[idx].params.name_in_graph not in node.params.prev_node_names:\n node.params.prev_node_names.append(node.prev_nodes[idx].params.name_in_graph)\n if node.prev_nodes[idx] not in nodes:\n nodes.append(node.prev_nodes[idx])\n else:\n node.prev_nodes[idx].active = False\n if len(nodes) > 0:\n last_node.insert(0, nodes)\n else:\n found = False\n\n graph = Digraph('G', filename='hello.gv', format='png')\n last_node = [[self.nodes[-1]]]\n found = True\n edges = []\n architecture_params = [[self.nodes[-1].params.__dict__]]\n\n def check_if_active(nodes):\n for node in nodes:\n if node.active:\n return True\n return False\n\n while found:\n nodes = []\n params = []\n for node in last_node[0]:\n if len(node.prev_nodes) == 0:\n found = False\n break\n\n for prev_node in node.prev_nodes:\n if prev_node.active and node.active and \\\n (check_if_active(prev_node.prev_nodes) or len(prev_node.prev_nodes) == 0):\n if [prev_node, node] not in edges:\n graph.edge(prev_node.name, node.name)\n edges.append([prev_node, node])\n if prev_node not in nodes:\n nodes.append(prev_node)\n params.append(prev_node.params.__dict__)\n if len(nodes) > 0:\n last_node.insert(0, nodes)\n architecture_params.append(params)\n else:\n found = False\n graph.render(filename=filename, directory=path)\n\n architecture = Architecture(node_params=architecture_params)\n architecture.save(path=os.path.join(path, filename))\n\n print (' [*] Graph drawed')\n\n","sub_path":"darts/cnn/architecture.py","file_name":"architecture.py","file_ext":"py","file_size_in_byte":14858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"113150450","text":"from odoo import models, api, fields, SUPERUSER_ID\n\nclass websiteMenus(models.Model):\n\n _inherit = 'website.menu'\n\n group_id = fields.Many2many('res.groups', string=\"Groups\")\n\n @api.model\n def search(self, args, offset=0, limit=None, order=None, count=False):\n menus = super(websiteMenus, self).search( args, offset=offset, limit=limit, order=order, count=count)\n if self._uid != SUPERUSER_ID:\n if ('backend_menu' in self._context and not self._context.get('backend_menu')) or ('backend_menu' not in self._context):\n user_group = self.env[\"res.users\"].browse(self._uid).groups_id\n new_menu = []\n for menu in menus:\n menu_group = menu.group_id\n if not(menu_group and menu_group & user_group):\n new_menu.append(menu.id)\n return self.browse(new_menu)\n return menus","sub_path":"beta-dev1/hilti_modifier_accessrights/models/website_menu.py","file_name":"website_menu.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"173493296","text":"# ///\n# This command is used to query the API, compare the results with the DB and make appropriate changes.\n# \\\\\\\nimport logging\nfrom datetime import datetime\n\nfrom django.core import mail\nfrom django.core.management.base import BaseCommand\n\nfrom develop.management.commands.actions import *\nfrom develop.management.commands.emails import *\nfrom develop.models import *\n\nitems_with_changes = []\nnew_items_added = []\n\nlogger = logging.getLogger(\"django\")\n\n\nclass Command(BaseCommand):\n def handle(self, *args, **options):\n # Lets turn this into a model and put it in the database later ******\n datasets = [[\"Development\", \"https://data.raleighnc.gov/resource/ncz3-s64h.json?$limit=10000&$$app_token=j6m9w6X5dCOGZVoBMBxxte4kN\"],\n [\"Zoning\", \"https://data.raleighnc.gov/resource/wz64-sgmw.json?zpyear=2017&$$app_token=j6m9w6X5dCOGZVoBMBxxte4kN\"]]\n\n for dataset in datasets:\n # Development specific section\n if dataset[0] == \"Development\":\n all_dev_json = get_api_json(dataset[1])\n\n for dev_json in all_dev_json:\n item_number = int(dev_json[\"devplan_id\"])\n item_year = int(dev_json[\"submitted_yr\"])\n\n # If we already know about this item and there is at least one dev CI\n if Development.objects.filter(devplan_id=item_number, submitted_yr=item_year).exists():\n development = Development.objects.get(devplan_id=item_number, submitted_yr=item_year)\n devs_cis = Development_change_instance.objects.filter(development=development)\n\n if devs_cis.exists():\n devs_latest_ci = devs_cis.latest('date_created')\n\n # If a difference exists between the known development and the json response\n if item_scan_compare(dev_json, development, devs_latest_ci):\n create_ci(development, dev_json, initial=False)\n items_with_changes.append(development)\n\n # Account for the very unlikely scenario that a Development is created without any CIs\n # Typically when a user deletes a CI leaving a Development without any\n else:\n create_ci(development, dev_json, initial=True)\n new_items_added.append(development)\n\n # else create a new dev plan with initial change instance\n else:\n new_dev = Development(devplan_id=item_number, submitted_yr=item_year)\n new_dev.save()\n create_ci(new_dev, dev_json, initial=True)\n new_items_added.append(new_dev)\n\n # Zoning specific section\n elif dataset[0] == \"Zoning\":\n all_zon_json = get_api_json(dataset[1])\n\n for zon_json in all_zon_json:\n item_number = int(zon_json[\"zpnum\"])\n item_year = int(zon_json[\"zpyear\"])\n\n # If we already know about this item\n if Zoning.objects.filter(zpnum=item_number, zpyear=item_year).exists():\n zoning_case = Zoning.objects.get(zpnum=item_number, zpyear=item_year)\n\n try:\n zons_latest_ci = Zoning_change_instance.objects.filter(zoning_case=zoning_case).latest('date_created')\n except:\n n = datetime.datetime.now()\n logger.info(\"Problem with \" + str(zoning_case) + \" at \" + n.strftime(\"%H:%M %m-%d-%y\"))\n\n # If a difference exists between the known zoning case and the json response\n if item_scan_compare(zon_json, zoning_case, zons_latest_ci):\n create_ci(zoning_case, zon_json, initial=False)\n items_with_changes.append(zoning_case)\n\n # else create a new zoning case with initial change instance\n else:\n new_zon = Zoning(zpnum=item_number, zpyear=item_year)\n new_zon.save()\n create_ci(new_zon, zon_json, initial=True)\n new_items_added.append(new_zon)\n\n # Create our EmailMessage objects\n active_subscribers = Subscriber.objects.filter(send_emails=True)\n\n if (new_items_added or items_with_changes) and active_subscribers:\n connection = mail.get_connection()\n messages = get_emails(new_items_added, items_with_changes)\n connection.send_messages(messages)\n n = datetime.datetime.now()\n logger.info(\"Email sent to: \" + str(messages[0].recipients()) + \" at \" + n.strftime(\"%H:%M %m-%d-%y\"))\n","sub_path":"develop/management/commands/scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":4943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"452185877","text":"from functools import reduce\n\ndef str2int(m):\n L = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}\n return L[m]\n\ndef add1(x,y):\n return x * 10 + y\n\ndef add2(x,y):\n return x * 0.1 + y\n\ndef str2float(s):\n myindex = s.index('.')\n s = s[0:myindex] +s[myindex+1:]\n s = list(map(str2int,s))\n s1 = reduce(add1,s[:myindex])\n s2 = s[myindex:]\n s3 = (reduce(add2,s2[::-1])) * 0.1\n s = s1 +s3\n return s\n\n\nprint('str2float(\\'123.456\\') =', str2float('123.456'))\nif abs(str2float('123.456') - 123.456) < 0.00001:\n print('测试成功!')\nelse:\n print('测试失败!')\n","sub_path":"Part 1 Learning Python/do_reduce_map.py","file_name":"do_reduce_map.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"313088224","text":"import time\n\nfrom selenium import webdriver\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\n\n# driver = webdriver.Chrome(executable_path='C:\\\\_teach\\\\Silenium\\\\chromedriver.exe')\ns = Service('C:/_teach/Silenium/chromedriver.exe')\ndriver = webdriver.Chrome(service=s)\nbase_url = 'https://demoqa.com/buttons/'\n# login_standard_user = \"standard_user\"\n# login_password_user = \"secret_sauce\"\ndriver.get(base_url)\n# driver.maximize_window()\n\naction = ActionChains(driver)\nelements_button = driver.find_element(By.XPATH, \"//button[@id='doubleClickBtn']\")\naction.double_click(elements_button).perform()\nresult_duble_click = driver.find_element(By.XPATH, \"//p[@id='doubleClickMessage']\").text\nassert result_duble_click == 'You have done a double click'\nprint('Двжды кликнули')\ntime.sleep(2)\n\naction = ActionChains(driver)\nelements_button = driver.find_element(By.XPATH, \"//button[@id='rightClickBtn']\")\naction.context_click(elements_button).perform()\nresult_context_click = driver.find_element(By.XPATH, \"//p[@id='rightClickMessage']\").text\nassert result_context_click == 'You have done a right click'\nprint('Правой кликнули')\ntime.sleep(2)\n","sub_path":"test_9_double_click.py","file_name":"test_9_double_click.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"127718793","text":"import os\nimport dpkt\nimport socket\nimport datetime\nimport pandas as pd\nimport numpy as np\nimport ipaddress\n\n\nclass LoadPcap:\n\n\n def __init__(self, file_name, query_start, period, network_segment):\n \n self.file_name = file_name\n self.query_start = query_start\n self.period = period\n self.network_segment = network_segment\n\n\n def arpProcess(self, eth):\n arp = eth.arp\n src_ip = socket.inet_ntoa(arp.spa)\n src_port = np.nan\n dst_ip = socket.inet_ntoa(arp.tpa)\n dst_port = np.nan\n \n return [src_ip, src_port, dst_ip, dst_port]\n\n\n def normalProcess(self, eth):\n ip = eth.data\n if ip.v == 4: \n src_ip = socket.inet_ntoa(ip.src)\n dst_ip = socket.inet_ntoa(ip.dst)\n \n elif ip.v == 6:\n src_ip = socket.inet_ntop(socket.AF_INET6, ip.src)\n dst_ip = socket.inet_ntop(socket.AF_INET6, ip.dst)\n try:\n src_ip = IPNetwork(src_ip).ipv4()\n except:\n pass\n try:\n dst_ip = IPNetwork(dst_ip).ipv4()\n except:\n pass\n src_ip = str(src_ip).split('/')[0]\n dst_ip = str(dst_ip).split('/')[0]\n \n try:\n src_port = ip.data.sport\n dst_port = ip.data.dport\n except:\n src_port = np.nan\n dst_port = np.nan\n \n return [src_ip, src_port, dst_ip, dst_port]\n\n\n def pcapProcess(self, pcap):\n pcap_list = list()\n count = 0\n for ts, buf in pcap:\n\n count += 1\n if count % 200000 == 0:\n print(count/10000)\n \n time = datetime.datetime.fromtimestamp(ts).strftime(\"%Y-%m-%dT%H:%M:%S.%f+08:00\")\n \n try:\n eth = dpkt.ethernet.Ethernet(buf)\n except:\n print('pass')\n \n try:\n # 2054 是 ARP\n if eth.type == 2054:\n pcap_list.append([time]+self.arpProcess(eth))\n\n else:\n pcap_list.append([time]+self.normalProcess(eth))\n\n except:\n pass\n\n return pd.DataFrame(pcap_list, columns=[\"Time\",\"Source\",\"SrcPort\",\"Destination\",\"DstPort\"]) \n\n\n def readPcap(self, filename):\n df = pd.DataFrame()\n for f in filename:\n file = open(\"data/\" + f, \"rb\")\n pcap = dpkt.pcap.Reader(file)\n df_pcap = self.pcapProcess(pcap)\n df = pd.concat([df, df_pcap])\n \n # print(df)\n return df\n\n\n def timeFilter(self, df, start_time, end_time):\n # df過濾時間\n df_time = df.loc[(df.Time >= start_time) & (df.Time < end_time)]\n\n return df_time\n\n '''\n def dataPreprocess(self, df):\n\n # 這裡最後要改成撈內網全部的流量或改成可以動態調整要全內網或部分網段。\n # # 過濾屬於內網ip的流量\n # group = df.groupby([\"Source\", \"Destination\"]).size().reset_index(name='Count')\n \n # group['src_private'] = group['Source'].apply(lambda x: ipaddress.ip_address(x).is_private)\n # group['dst_private'] = group['Destination'].apply(lambda x: ipaddress.ip_address(x).is_private)\n # group = group.loc[(group['src_private']) & (group['dst_private'])]\n # group.drop(['src_private', 'dst_private'], axis=1, inplace=True)\n # df_omp = group.reset_index(drop=True)\n\n network_segment = self.network_segment.split(',')\n \n # 將相同[\"Srcip\", \"Dstip\"] 的groupby 在一起\n group = dict(df.groupby([\"Source\", \"Destination\"]).size())\n \n # 過濾出內網(77網段下)的流量\n src_dst = []\n for k in group.keys():\n\n segment_s = False\n segment_d = False\n \n for i in network_segment:\n if k[0].find(i) == 0:\n segment_s = True\n if k[1].find(i) == 0:\n segment_d = True\n \n if segment_s == True and segment_d == True:\n src_dst.append([k[0], k[1], group[k]])\n \n # 再次組成dataframe\n df_omp = pd.DataFrame(src_dst, columns = [\"Source\", \"Destination\", \"Count\"])\n\n\n return df_omp\n '''\n\n \n def dataPreprocess(self, df):\n\n # 這裡最後要改成撈內網全部的流量或改成可以動態調整要全內網或部分網段。\n # 過濾屬於內網ip的流量\n group = df.groupby([\"Source\", \"Destination\"]).size().reset_index(name='Count')\n \n group['src_private'] = group['Source'].apply(lambda x: ipaddress.ip_address(x).is_private)\n group['dst_private'] = group['Destination'].apply(lambda x: ipaddress.ip_address(x).is_private)\n group = group.loc[(group['src_private']) & (group['dst_private'])]\n group.drop(['src_private', 'dst_private'], axis=1, inplace=True)\n df_omp = group.reset_index(drop=True)\n\n\n # network_segment = self.network_segment.split(',')\n \n # # 將相同[\"Srcip\", \"Dstip\"] 的groupby 在一起\n # group = dict(df.groupby([\"Source\", \"Destination\"]).size())\n \n # # 過濾出內網(77網段下)的流量\n # src_dst = []\n # for k in group.keys():\n\n # segment_s = False\n # segment_d = False\n \n # for i in network_segment:\n # if k[0].find(i) == 0:\n # segment_s = True\n # if k[1].find(i) == 0:\n # segment_d = True\n \n # if segment_s == True and segment_d == True:\n # src_dst.append([k[0], k[1], group[k]])\n \n # # 再次組成dataframe\n # df_omp = pd.DataFrame(src_dst, columns = [\"Source\", \"Destination\", \"Count\"])\n\n\n return df_omp\n \n \n\n def run(self):\n print(self.query_start) \n print(\"========== load data ==========\")\n \n \n # filename\n filename = []\n # file_time_now = datetime.datetime.now()\n # file_time = file_time_now\n file_time = datetime.datetime.strptime(self.query_start, '%Y-%m-%dT%H:%M:%S.%f')\n file_time = file_time - datetime.timedelta(hours = 1)\n file_cnt = self.period + 1\n for _ in range(file_cnt):\n linux_filename = file_time - datetime.timedelta(hours = 8)\n filename.append(linux_filename.strftime('%m-%d-%H') + '.pcap')\n file_time = file_time + datetime.timedelta(hours = 1)\n\n print('filename: ' + str(filename))\n \n df = self.readPcap(filename)\n\n # df = self.readPcap(self.file_name)\n\n start_time = datetime.datetime.strptime(self.query_start, '%Y-%m-%dT%H:%M:%S.%f')\n end_time = start_time + datetime.timedelta(hours = self.period)\n now_end = end_time.strftime(\"%Y-%m-%dT%H:%M:%S.%f\") \n\n abnor_df = self.timeFilter(df, self.query_start, now_end)\n abnor_data = self.dataPreprocess(abnor_df)\n # print(abnor_data)\n abnor_iplist = list(abnor_data['Source']) + list(abnor_data['Destination'])\n abnor_ip_list = sorted(list(set(abnor_iplist)))\n\n # 控制多少比例的 IP 數量為上班/下班\n # 怎麼知道公司總共有多少 ip\n work_ip_cnt = 254 * 0.29527\n\n if len(abnor_ip_list) > work_ip_cnt:\n week_threshold = 'weekday'\n else:\n week_threshold = 'weekend'\n\n\n if int(self.query_start[11:13]) >= 8 and int(self.query_start[11:13]) < 20:\n work_break = 'work'\n elif int(self.query_start[11:13]) < 8 or int(self.query_start[11:13]) >= 20:\n work_break = 'break'\n\n\n folder_name = './' + week_threshold + '_' + work_break + '/'\n filepath = folder_name + 'omp_and_frequency.csv'\n print('folder name: ' + week_threshold + '_' + work_break)\n\n if os.path.isfile(filepath):\n # print('no empty')\n\n nor_data = []\n\n else:\n print('first time')\n\n\n # filename\n filename = []\n file_time = datetime.datetime.strptime(self.query_start, '%Y-%m-%dT%H:%M:%S.%f') - datetime.timedelta(hours = 24)\n file_time = file_time - datetime.timedelta(hours = 1)\n file_cnt = self.period + 1\n for _ in range(file_cnt):\n linux_filename = file_time - datetime.timedelta(hours = 8)\n filename.append(linux_filename.strftime('%m-%d-%H') + '.pcap')\n file_time = file_time + datetime.timedelta(hours = 1)\n \n print('normal filename: ' + str(filename))\n \n df = self.readPcap(filename)\n\n # 以前一個小時為比較時間 V\n # 與前一天同一個時間區間比較 X\n nor_start_time = start_time - datetime.timedelta(hours = 1)\n nor_query_start = nor_start_time.strftime(\"%Y-%m-%dT%H:%M:%S.%f\")\n nor_end_time = end_time - datetime.timedelta(hours = 1)\n nor_end_time = nor_end_time.strftime(\"%Y-%m-%dT%H:%M:%S.%f\")\n\n nor_df = self.timeFilter(df, nor_query_start, nor_end_time)\n nor_data = self.dataPreprocess(nor_df)\n # print(nor_data)\n \n print('start time: ' + str(self.query_start)[:19])\n\n return abnor_df, nor_data, abnor_data, folder_name\n\n","sub_path":"SecBuzzerESM/AI/OMP/code/app/load_pcap.py","file_name":"load_pcap.py","file_ext":"py","file_size_in_byte":9561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"5562459","text":"import platform\nimport os\nimport logging\n\n\ndef setup_log_and_return_log_file():\n _log_file = ''\n platform_str = platform.platform()\n if platform_str.startswith('Linux'):\n _log_file = os.path.join('/media/leizhang/Data/workspace/', 'logs', 'my_log.log')\n\n logging.basicConfig(\n level=logging.DEBUG,\n format='%(asctime)s: %(levelname)s: %(message)s',\n filename=_log_file,\n filemode='+a',\n )\n logging.info('The log is written to:' + _log_file)\n return _log_file\n\n\nif __name__ == '__main__':\n logging.debug('this is a debug mode')\n logging.warning('Some problem may happen here')\n logging.error('A fatal error happened here')\n","sub_path":"scripts/log_util.py","file_name":"log_util.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"308133111","text":"from tkinter import *\r\n\r\nimport numpy as np\r\n\r\n\r\nclass ElegirDieta(Frame):\r\n def __init__(self, geom):\r\n Frame.__init__(self, )\r\n self.hig, self.wid = geom\r\n\r\n self.dieta_value = StringVar(self, 'Hombre1')\r\n\r\n self.var_zanahoria = DoubleVar(self, value=0)\r\n self.var_espinaca = DoubleVar(self, value=0)\r\n self.var_repollo = DoubleVar(self, value=0)\r\n self.var_lechuga = DoubleVar(self, value=0)\r\n self.var_pimiento_verde = DoubleVar(self, value=0)\r\n self.var_pimiento_rojo = DoubleVar(self, value=0)\r\n self.var_zapallo_cocido = DoubleVar(self, value=0)\r\n self.var_palta = DoubleVar(self, value=0)\r\n self.var_guayaba = DoubleVar(self, value=0)\r\n self.var_papa = DoubleVar(self, value=0)\r\n self.var_coliflor_cocida = DoubleVar(self, value=0)\r\n self.var_damasco = DoubleVar(self, value=0)\r\n self.var_nuez = DoubleVar(self, value=0)\r\n self.var_almendra = DoubleVar(self, 0)\r\n\r\n Label(self, text='Mejores alimentos por relacion nutriente / consumo de agua').place(x=20, y=20)\r\n Label(self, text='Cada 100grx ').place(x=20, y=40)\r\n Label(self, text='Dietas ', font=14).place(x=580, y=240)\r\n Radiobutton(self, text='Hombre 0-14', variable=self.dieta_value, value='Hombre1').place(x=600, y=280)\r\n Radiobutton(self, text='Hombre 15-64', variable=self.dieta_value, value='Hombre2').place(x=600, y=310)\r\n Radiobutton(self, text='Hombre 64+', variable=self.dieta_value, value='Hombre3').place(x=600, y=340)\r\n Radiobutton(self, text='Mujer 0-14', variable=self.dieta_value, value='Mujer1').place(x=600, y=370)\r\n Radiobutton(self, text='Mujer 15-64', variable=self.dieta_value, value='Muer2').place(x=600, y=400)\r\n Radiobutton(self, text='Mujer 64+', variable=self.dieta_value, value='Mujer3').place(x=600, y=430)\r\n\r\n Button(self, text='Calcular', command=lambda: self.activador()).place(x=510, y=250)\r\n Label(self, text='Dieta Recomendada').place(x=20, y=300)\r\n Label(self, text='Dieta Obtenida').place(x=20, y=330)\r\n\r\n # Column 0\r\n Entry(self, width=4, textvariable=self.var_nuez).place(x=10, y=90)\r\n Entry(self, width=4, textvariable=self.var_almendra).place(x=10, y=120)\r\n Entry(self, width=4, textvariable=self.var_palta).place(x=10, y=150)\r\n Entry(self, width=4, textvariable=self.var_papa).place(x=10, y=180)\r\n Entry(self, width=4, textvariable=self.var_pimiento_rojo).place(x=10, y=210)\r\n Label(self, text='Energia').place(x=20, y=60)\r\n Label(self, text='Nuez').place(x=40, y=90)\r\n Label(self, text='Almendra').place(x=40, y=120)\r\n Label(self, text='Palta').place(x=40, y=150)\r\n Label(self, text='Papa Cocida').place(x=40, y=180)\r\n Label(self, text='Pimiento Rojo').place(x=40, y=210)\r\n\r\n # Column 1\r\n Entry(self, width=4, textvariable=self.var_almendra).place(x=140, y=90)\r\n Entry(self, width=4, textvariable=self.var_nuez).place(x=140, y=120)\r\n Entry(self, width=4, textvariable=self.var_lechuga).place(x=140, y=150)\r\n Entry(self, width=4, textvariable=self.var_pimiento_rojo).place(x=140, y=180)\r\n Entry(self, width=4, textvariable=self.var_espinaca).place(x=140, y=210)\r\n Label(self, text='Proteinas').place(x=150, y=60)\r\n Label(self, text='Almendra').place(x=170, y=90)\r\n Label(self, text='Nuez').place(x=170, y=120)\r\n Label(self, text='Lechuga').place(x=170, y=150)\r\n Label(self, text='Pimiento Rojo').place(x=170, y=180)\r\n Label(self, text='Espinaca').place(x=170, y=210)\r\n\r\n # Column 2\r\n Entry(self, width=4, textvariable=self.var_papa).place(x=270, y=90)\r\n Entry(self, width=4, textvariable=self.var_pimiento_rojo).place(x=270, y=120)\r\n Entry(self, width=4, textvariable=self.var_damasco).place(x=270, y=150)\r\n Entry(self, width=4, textvariable=self.var_zapallo_cocido).place(x=270, y=180)\r\n Entry(self, width=4, textvariable=self.var_guayaba).place(x=270, y=210)\r\n Label(self, text='Carbohidratos').place(x=280, y=60)\r\n Label(self, text='Papa cocida').place(x=300, y=90)\r\n Label(self, text='Pimiento Rojo').place(x=300, y=120)\r\n Label(self, text='Damasco').place(x=300, y=150)\r\n Label(self, text='Zapallo Cocido').place(x=300, y=180)\r\n Label(self, text='Guayaba').place(x=300, y=210)\r\n\r\n # Column 3\r\n Entry(self, width=4, textvariable=self.var_almendra).place(x=400, y=90)\r\n Entry(self, width=4, textvariable=self.var_espinaca).place(x=400, y=120)\r\n Entry(self, width=4, textvariable=self.var_lechuga).place(x=400, y=150)\r\n Entry(self, width=4, textvariable=self.var_repollo).place(x=400, y=180)\r\n Entry(self, width=4, textvariable=self.var_nuez).place(x=400, y=210)\r\n Label(self, text='Calcio').place(x=410, y=60)\r\n Label(self, text='Almendra').place(x=430, y=90)\r\n Label(self, text='Espinaca').place(x=430, y=120)\r\n Label(self, text='Lechuga').place(x=430, y=150)\r\n Label(self, text='Repollo').place(x=430, y=180)\r\n Label(self, text='Nuez').place(x=430, y=210)\r\n\r\n # Column 4\r\n Entry(self, width=4, textvariable=self.var_espinaca).place(x=530, y=90)\r\n Entry(self, width=4, textvariable=self.var_lechuga).place(x=530, y=120)\r\n Entry(self, width=4, textvariable=self.var_almendra).place(x=530, y=150)\r\n Entry(self, width=4, textvariable=self.var_nuez).place(x=530, y=180)\r\n Entry(self, width=4, textvariable=self.var_pimiento_verde).place(x=530, y=210)\r\n Label(self, text='Hierro').place(x=540, y=60)\r\n Label(self, text='Espinaca').place(x=560, y=90)\r\n Label(self, text='Lechuga').place(x=560, y=120)\r\n Label(self, text='Almendra').place(x=560, y=150)\r\n Label(self, text='Nuez').place(x=560, y=180)\r\n Label(self, text='Pimiento Verde').place(x=560, y=210)\r\n\r\n # Column 5\r\n Entry(self, width=4, textvariable=self.var_pimiento_rojo).place(x=660, y=90)\r\n Entry(self, width=4, textvariable=self.var_zapallo_cocido).place(x=660, y=120)\r\n Entry(self, width=4, textvariable=self.var_espinaca).place(x=660, y=150)\r\n Entry(self, width=4, textvariable=self.var_zanahoria).place(x=660, y=180)\r\n Entry(self, width=4, textvariable=self.var_lechuga).place(x=660, y=210)\r\n Label(self, text='Vitamina A').place(x=670, y=60)\r\n Label(self, text='Pimiento Rojo').place(x=690, y=90)\r\n Label(self, text='Zapallo cocido').place(x=690, y=120)\r\n Label(self, text='Espinaca').place(x=690, y=150)\r\n Label(self, text='Zanahoria').place(x=690, y=180)\r\n Label(self, text='Lechuga').place(x=690, y=210)\r\n\r\n # Column 6\r\n Entry(self, width=4, textvariable=self.var_pimiento_rojo).place(x=790, y=90)\r\n Entry(self, width=4, textvariable=self.var_pimiento_verde).place(x=790, y=120)\r\n Entry(self, width=4, textvariable=self.var_guayaba).place(x=790, y=150)\r\n Entry(self, width=4, textvariable=self.var_repollo).place(x=790, y=180)\r\n Entry(self, width=4, textvariable=self.var_coliflor_cocida).place(x=790, y=210)\r\n Label(self, text='Vitamina C').place(x=800, y=60)\r\n Label(self, text='Pimiento Rojo').place(x=820, y=90)\r\n Label(self, text='Pimineto Verde').place(x=820, y=120)\r\n Label(self, text='Guayaba').place(x=820, y=150)\r\n Label(self, text='Repollo').place(x=820, y=180)\r\n Label(self, text='Coliflor Cocida').place(x=820, y=210)\r\n\r\n Label(self, text='Energia').place(x=120, y=280)\r\n Label(self, text='Proteinas').place(x=170, y=280)\r\n Label(self, text='Carbohi.').place(x=230, y=280)\r\n Label(self, text='Calcio').place(x=290, y=280)\r\n Label(self, text='Hierro').place(x=350, y=280)\r\n Label(self, text='Vit. A').place(x=410, y=280)\r\n Label(self, text='Vit. C').place(x=470, y=280)\r\n\r\n def activador(self):\r\n self.place_values()\r\n self.place_dieta()\r\n\r\n def place_values(self):\r\n # Dieta por clasificacion demografica\r\n dieta = {'Hombre1': [1500, 32.9, 187.5, 800, 8, 0.6, 90], 'Hombre2': [2600, 78.8, 325, 1100, 8, 0.6, 90],\r\n 'Hombre3': [2300, 68.1, 287.5, 1300, 8, 0.9, 90], 'Mujer1': [1450, 42, 181.3, 800, 18, 0.6, 75],\r\n 'Mujer2': [2050, 68.8, 256.3, 1100, 18, 0.7, 75], 'Mujer3': [1800, 60.2, 225, 1300, 8, 0.7, 75]}\r\n\r\n\r\n eleccion_dieta = self.dieta_value.get()\r\n\r\n try:\r\n dieta_recomendada = list(dieta[eleccion_dieta])\r\n cadena = []\r\n for val in dieta_recomendada:\r\n val = str(val)\r\n val2 = val.rjust(13)\r\n cadena.append(val2)\r\n string = ''.join(cadena)\r\n Label(self, text=string).place(x=150, y=300)\r\n except KeyError:\r\n pass\r\n\r\n def place_dieta(self):\r\n self.v_za = self.var_zanahoria.get()\r\n self.v_es = self.var_espinaca.get()\r\n self.v_re = self.var_repollo.get()\r\n self.v_le = self.var_lechuga.get()\r\n self.v_pv = self.var_pimiento_verde.get()\r\n self.v_pr = self.var_pimiento_rojo.get()\r\n self.v_zc = self.var_zapallo_cocido.get()\r\n self.v_pal = self.var_palta.get()\r\n self.v_gu = self.var_guayaba.get()\r\n self.v_pap = self.var_papa.get()\r\n self.v_cc = self.var_coliflor_cocida.get()\r\n self.v_da = self.var_damasco.get()\r\n self.v_nu = self.var_nuez.get()\r\n self.v_al = self.var_almendra.get()\r\n\r\n self.za = np.array([23.91, 0.63, 4.75, 27.00, 0.50, 0.44, 3.80])\r\n self.es = np.array([20.74, 2.63, 0.61, 117.00, 2.70, 0.59, 40.00])\r\n self.re = np.array([30.20, 1.38, 4.18, 45.00, 0.41, 0.01, 48.00])\r\n self.le = np.array([19.60, 1.37, 1.40, 34.70, 1.00, 0.19, 13.00])\r\n self.pv = np.array([19.68, 0.63, 1.60, 11.31, 0.49, 0.03, 107.19])\r\n self.pr = np.array([32.90, 1.25, 4.20, 11.89, 0.37, 0.54, 138.73])\r\n self.zc = np.array([32.00, 1.10, 7.70, 18.30, 0.40, 0.74, 6.50])\r\n self.pal = np.array([233.0, 1.88, 0.40, 12.00, 0.49, 0.01, 6.00])\r\n self.gu = np.array([57.00, 0.82, 11.90, 17.00, 0.60, 0.07, 273.00])\r\n self.pap = np.array([73.59, 2.34, 14.80, 6.40, 0.43, 0.09, 17.00])\r\n self.cc = np.array([27.52, 2.44, 0.00, 19.26, 0.84, 0.01, 58.77])\r\n self.da = np.array([41.68, 0.88, 8.54, 16.00, 0.65, 0.28, 6.00])\r\n self.nu = np.array([649.00, 14.42, 4.40, 87.10, 2.80, 0.00, 2.60])\r\n self.al = np.array([589.00, 19.13, 6.20, 248.25, 3.59, 0.00, 0.00])\r\n\r\n mult_za = self.za * self.v_za\r\n mult_es = self.es * self.v_es\r\n mult_re = self.re * self.v_re\r\n mult_le = self.le * self.v_le\r\n mult_pv = self.pv * self.v_pv\r\n mult_pr = self.pr * self.v_pr\r\n mult_zc = self.zc * self.v_zc\r\n mult_pal = self.pal * self.v_pal\r\n mult_gu = self.gu * self.v_gu\r\n mult_pap = self.pap * self.v_pap\r\n mult_cc = self.cc * self.v_cc\r\n mult_da = self.da * self.v_da\r\n mult_nu = self.nu * self.v_nu\r\n mult_al = self.al * self.v_al\r\n\r\n recursos_totales_1 = mult_za+mult_es + mult_re + mult_le + mult_pv + mult_pr\r\n recursos_totales_2 = mult_zc + mult_pal + mult_gu + mult_pap + mult_cc + mult_da + mult_nu + mult_al\r\n recursos_totales = recursos_totales_1 + recursos_totales_2\r\n try:\r\n dieta_recomendada = list(recursos_totales)\r\n cadena = []\r\n for val in dieta_recomendada:\r\n val = round(val, 1)\r\n val = str(val)\r\n val2 = val.rjust(13)\r\n cadena.append(val2)\r\n string = ''.join(cadena)\r\n Label(self, text=string).place(x=150, y=330)\r\n except KeyError:\r\n pass\r\n\r\n self.agua_za = np.array([23.91, 0.63, 4.75, 27.00, 0.50, 0.44, 3.80])\r\n self.agua_es = np.array([20.74, 2.63, 0.61, 117.00, 2.70, 0.59, 40.00])\r\n self.agua_re = np.array([30.20, 1.38, 4.18, 45.00, 0.41, 0.01, 48.00])\r\n self.agua_le = np.array([19.60, 1.37, 1.40, 34.70, 1.00, 0.19, 13.00])\r\n self.agua_pv = np.array([19.68, 0.63, 1.60, 11.31, 0.49, 0.03, 107.19])\r\n self.agua_pr = np.array([32.90, 1.25, 4.20, 11.89, 0.37, 0.54, 138.73])\r\n self.agua_zc = np.array([32.00, 1.10, 7.70, 18.30, 0.40, 0.74, 6.50])\r\n self.agua_pal = np.array([233.0, 1.88, 0.40, 12.00, 0.49, 0.01, 6.00])\r\n self.agua_gu = np.array([57.00, 0.82, 11.90, 17.00, 0.60, 0.07, 273.00])\r\n self.agua_pap = np.array([73.59, 2.34, 14.80, 6.40, 0.43, 0.09, 17.00])\r\n self.agua_cc = np.array([27.52, 2.44, 0.00, 19.26, 0.84, 0.01, 58.77])\r\n self.agua_da = np.array([41.68, 0.88, 8.54, 16.00, 0.65, 0.28, 6.00])\r\n self.agua_nu = np.array([649.00, 14.42, 4.40, 87.10, 2.80, 0.00, 2.60])\r\n self.agua_al = np.array([589.00, 19.13, 6.20, 248.25, 3.59, 0.00, 0.00])\r\n\r\n mult_za = self.agua_za * self.v_za\r\n mult_es = self.agua_es * self.v_es\r\n mult_re = self.agua_re * self.v_re\r\n mult_le = self.agua_le * self.v_le\r\n mult_pv = self.agua_pv * self.v_pv\r\n mult_pr = self.agua_pr * self.v_pr\r\n mult_zc = self.agua_zc * self.v_zc\r\n mult_pal = self.agua_pal * self.v_pal\r\n mult_gu = self.agua_gu * self.v_gu\r\n mult_pap = self.agua_pap * self.v_pap\r\n mult_cc = self.agua_cc * self.v_cc\r\n mult_da = self.agua_da * self.v_da\r\n mult_nu = self.agua_nu * self.v_nu\r\n mult_al = self.agua_al * self.v_al\r\n\r\n","sub_path":"Ventanas/EElegirDieta.py","file_name":"EElegirDieta.py","file_ext":"py","file_size_in_byte":13682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"64750570","text":"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"The module that handles the main interface of loklak\"\"\"\nfrom __future__ import (absolute_import, division,\n print_function, unicode_literals)\n\nimport json\nimport re\nimport requests\nfrom xmljson import badgerfish as bf\nfrom json import dumps\nimport csv\n\n\nclass Loklak(object):\n \"\"\"The fields for the Loklak object\"\"\"\n baseUrl = 'http://loklak.org/'\n name = None\n followers = None\n following = None\n query = None\n since = None\n until = None\n source = None\n count = None\n fields = None\n from_user = None\n fields = None\n limit = None\n action = None\n data = {}\n\n def __init__(self, baseUrl='http://loklak.org/'):\n baseUrl = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', baseUrl)\n try:\n if baseUrl[0]:\n if baseUrl[0] != 'http://loklak.org/':\n url_test = self.hello()\n if url_test['status'] == 'ok':\n self.baseUrl = baseUrl[0]\n else:\n self.baseUrl = baseUrl[0]\n except IndexError:\n pass\n\n def getBaseUrl(self):\n return self.baseUrl\n\n def status(self):\n \"\"\"Returns the status of the server\"\"\"\n status_application = 'api/status.json'\n url_to_give = self.baseUrl+status_application\n return_to_user = requests.get(url_to_give)\n if return_to_user.status_code == 200:\n return return_to_user.json()\n else:\n return_to_user = {}\n return json.dumps(return_to_user)\n\n def xmlToJson(self, xmlData = None):\n \"\"\"Converts XML to JSON as the service\"\"\"\n jsonData = ''\n if xmlData:\n jsonData = dumps(bf.data(fromstring(xmlData)))\n return jsonData\n\n def csvToJson(self, csvData = None, fieldnamesList = None):\n \"\"\"Converts CSV to JSON as the service\"\"\"\n jsonData = ''\n if csvData:\n data = csv.DictReader( csvData, fieldnames = fieldnamesList)\n jsonData = json.dumps( [ row for row in data ] )\n return out\n\n def hello(self):\n \"\"\"Gives a hello\"\"\"\n hello_application = 'api/hello.json'\n url_to_give = self.baseUrl+hello_application\n return_to_user = requests.get(url_to_give)\n if return_to_user.status_code == 200:\n return return_to_user.json()\n else:\n return_to_user = {}\n return json.dumps(return_to_user)\n\n def geocode(self, places=None):\n \"\"\"Gives the geocode\"\"\"\n geo_application = 'api/geocode.json'\n url_to_give = self.baseUrl+geo_application\n params = {}\n params['places'] = places\n return_to_user = requests.get(url_to_give, params=params)\n if return_to_user.status_code == 200:\n return return_to_user.json()\n else:\n return_to_user = {}\n return json.dumps(return_to_user)\n\n def get_map(self, latitude, longitude, width=500, height=500,\n zoom=8, text=\"\"):\n \"\"\"Returns a map of size 500x500\"\"\"\n map_application = 'vis/map.png'\n params = {'text': text, 'mlat': latitude, 'mlon': longitude,\n 'width': width, 'height': height, 'zoom': zoom}\n return_to_user = requests.get(self.baseUrl + map_application,\n params=params, stream=True)\n if return_to_user.status_code == 200:\n return return_to_user.raw.read()\n else:\n return ''\n\n def get_markdown(self, text, color_text=\"000000\", color_bg=\"ffffff\",\n padding=\"10\", uppercase=\"true\"):\n \"\"\"Returns a map of size 500x500\"\"\"\n map_application = 'vis/markdown.png'\n params = {'text': text, 'color_text': color_text, 'color_background': color_bg,\n 'padding': padding, 'uppercase': uppercase}\n return_to_user = requests.get(self.baseUrl + map_application,\n params=params, stream=True)\n if return_to_user.status_code == 200:\n return return_to_user.raw.read()\n else:\n return ''\n\n def peers(self):\n \"\"\"Gives the peers of a user\"\"\"\n peers_application = 'api/peers.json'\n url_to_give = self.baseUrl+peers_application\n return_to_user = requests.get(url_to_give)\n if return_to_user.status_code == 200:\n return return_to_user.json()\n else:\n return_to_user = {}\n return json.dumps(return_to_user)\n\n def user(self, name=None, followers=None, following=None):\n \"\"\"User information, including who they are following, and\n who follows them\"\"\"\n user_application = 'api/user.json'\n url_to_give = self.baseUrl+user_application\n self.name = name\n self.followers = followers\n self.following = following\n if name:\n params = {}\n params['screen_name'] = self.name\n if followers is not None:\n params['followers'] = self.followers\n if following is not None:\n params['following'] = self.following\n\n return_to_user = requests.get(url_to_give, params=params)\n if return_to_user.status_code == 200:\n return return_to_user.json()\n else:\n return_to_user = {}\n return json.dumps(return_to_user)\n else:\n return_to_user = {}\n return_to_user['error'] = ('No user name given to query. Please'\n ' check and try again')\n return json.dumps(return_to_user)\n\n def settings(self):\n \"\"\"Gives the settings of the application\"\"\"\n settings_application = 'api/settings.json'\n url_to_give = self.baseUrl + settings_application\n return_to_user = requests.get(url_to_give)\n if return_to_user.status_code == 200:\n return return_to_user.json()\n else:\n return_to_user = {}\n return_to_user['error'] = ('This API has access restrictions:'\n ' only localhost clients are granted.')\n return json.dumps(return_to_user)\n\n def susi(self, query=None):\n \"\"\"Hits Susi with the required query and returns back the susi response\"\"\"\n susi_application = 'api/susi.json'\n url_to_give = self.baseUrl + susi_application\n self.query = query\n if query:\n params = {}\n params['q'] = self.query\n return_to_user = requests.get(url_to_give, params=params)\n if return_to_user.status_code == 200:\n return return_to_user.json()\n else:\n return_to_user = {}\n return_to_user['error'] = ('Looks like there is a problem in susi replying.')\n return json.dumps(return_to_user)\n else:\n return_to_user = {}\n return_to_user['error'] = ('Please ask susi something.')\n return json.dumps(return_to_user)\n\n def search(self, query=None, since=None, until=None, from_user=None, count=None):\n \"\"\"Handles the searching\"\"\"\n search_application = 'api/search.json'\n url_to_give = self.baseUrl+search_application\n self.query = query\n self.since = since\n self.until = until\n self.from_user = from_user\n self.count = count\n if query:\n params = {}\n params['query'] = self.query\n if since:\n params['query'] = params['query'] + ' since:'+self.since\n if until:\n params['query'] = params['query'] + ' until:'+self.until\n if from_user:\n params['query'] = params['query'] + ' from:'+self.from_user\n if count:\n params['count'] = self.count\n return_to_user = requests.get(url_to_give, params=params)\n if return_to_user.status_code == 200:\n return return_to_user.json()\n else:\n return_to_user = {}\n return_to_user['error'] = ('Something went wrong, looks like'\n ' the server is down.')\n return json.dumps(return_to_user)\n else:\n return_to_user = {}\n return_to_user['error'] = ('No Query string has been'\n ' given to query for an account')\n return json.dumps(return_to_user)\n\n def suggest(self, query=None, count=None, order=None, orderby=None,since=None, until=None):\n suggest_application = 'api/suggest.json'\n url_to_give = self.baseUrl+suggest_application\n params = {}\n if query:\n params['query'] = query\n if count:\n params['count'] = count\n if order:\n params['order'] = order\n if since:\n params['since'] = since\n if until:\n params['until'] = until\n print(params)\n return_to_user = requests.get(url_to_give, params=params)\n print(return_to_user.url)\n if return_to_user.status_code == 200:\n return return_to_user.json()\n else :\n return_to_user = {}\n return_to_user['error'] = ('Something went wrong,'\n ' looks like the server is down.')\n return json.dumps(return_to_user)\n\n def aggregations(self, query=None, since=None, until=None,\n fields=None, limit=6, count=0):\n \"\"\"Gives the aggregations of the application\"\"\"\n aggregations_application = 'api/search.json'\n url_to_give = self.baseUrl+aggregations_application\n self.query = query\n self.since = since\n self.until = until\n self.fields = fields\n self.limit = limit\n self.count = count\n if query:\n params = {}\n params['query'] = self.query\n if since:\n params['query'] = params['query']+' since:'+self.since\n if until:\n params['query'] = params['query']+' until:'+self.until\n if fields:\n if isinstance(fields, list):\n params['fields'] = ','.join(self.fields)\n else:\n params['fields'] = self.fields\n\n params['count'] = self.count\n params['source'] = 'cache'\n return_to_user = requests.get(url_to_give, params=params)\n if return_to_user.status_code == 200:\n return return_to_user\n else:\n return_to_user = {}\n return_to_user['error'] = ('Something went wrong,'\n ' looks like the server is down.')\n return json.dumps(return_to_user)\n else:\n return_to_user = {}\n return_to_user['error'] = ('No Query string has been given to run'\n 'query for aggregations')\n return json.dumps(return_to_user)\n\n def account(self, name=None, action=None, data=None):\n \"\"\"Displays users account\"\"\"\n account_application = 'account.json'\n url_to_give = 'http://localhost:9000/api/'+account_application\n self.name = name\n self.data = data\n self.action = action\n # Simple GET Query\n headers = {\n 'User-Agent': ('Mozilla/5.0 (Android 4.4; Mobile; rv:41.0)'\n ' Gecko/41.0 Firefox/41.0'),\n 'From': 'info@loklak.org'\n }\n if name:\n params = {}\n params['screen_name'] = self.name\n return_to_user = requests.get(url_to_give, params=params,\n headers=headers)\n if return_to_user.status_code == 200:\n return return_to_user.json()\n else:\n return_to_user = {}\n return_to_user['error'] = ('Something went wrong,'\n ' looks like the query is wrong.')\n return json.dumps(return_to_user)\n # if action = update and data is provided, then make request\n elif self.action == 'update' and data:\n params = {}\n params['action'] = self.action\n params['data'] = self.data\n return_to_user = requests.post(url_to_give,\n params=params, headers=headers)\n if return_to_user.status_code == 200:\n return return_to_user.json()\n else:\n return_to_user = {}\n return_to_user['error'] = ('Something went wrong,'\n ' looks like the query is wrong.')\n return json.dumps(return_to_user)\n else:\n return_to_user = {}\n return_to_user['error'] = ('No Query string has been given'\n ' given to query for an account')\n return json.dumps(return_to_user)\n","sub_path":"loklak.py","file_name":"loklak.py","file_ext":"py","file_size_in_byte":13203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"24260198","text":"import requests\n\nclass Mixlr:\n\tserviceId = 1\n\t\n\tapi = 'https://api.mixlr.com/users/'\n\t\n\tdef __init__(self, name):\n\t\tself.name = name\n\t\tself.isLive = False\n\t\tself.link = 'http://mixlr.com/' + self.name\n\t\tself.service = 'Mixlr'\n\n\tdef checkLive(self):\n\t\turl = Mixlr.api + self.name\n\t\tresp = requests.get(url)\n\t\t\n\t\tif resp.status_code == 200:\n\t\t\tresult = resp.json()\n\t\t\tself.isLive = result['is_live']\n\t\telse:\n\t\t\tself.isLive = False\n\n\t\treturn self.isLive\n\t\n\tdef __lt__(self, other):\n\t\tif (self.serviceId == other.serviceId):\n\t\t\treturn self.name < other.name\n\t\telse:\n\t\t\treturn self.serviceId < other.serviceId\n\nclass Twitch:\n\tserviceId = 0\n\t\n\tapi = 'https://api.twitch.tv/kraken/'\n\theaders = { 'Accept':'application/vnd.twitchtv.v3+json', 'Client-ID':'ewvlchtxgqq88ru9gmfp1gmyt6h2b93' }\n\n\tdef __init__(self, name):\n\t\tself.name = name\n\t\tself.isLive = False\n\t\tself.link = 'https://player.twitch.tv/?branding=false&showInfo=false&channel=' + self.name\n\t\tself.service = 'Twitch'\n\n\tdef checkLive(self):\n\t\turl = Twitch.api + 'streams/' + self.name\n\t\tresp = requests.get(url, headers=Twitch.headers)\n\n\t\tif resp.status_code == 200:\n\t\t\tresult = resp.json()\n\t\t\tif result['stream']:\n\t\t\t\tself.isLive = True\n\t\t\telse:\n\t\t\t\tself.isLive = False\n\t\telse:\n\t\t\tself.isLive = False\n\n\t\treturn self.isLive\n\t\t\n\tdef __lt__(self, other):\n\t\tif (self.serviceId == other.serviceId):\n\t\t\treturn self.name < other.name\n\t\telse:\n\t\t\treturn self.serviceId < other.serviceId\n","sub_path":"services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"288618039","text":"import json\n\nfrom django.http import JsonResponse\nfrom django.shortcuts import render\n\nfrom tools.list_element_compare_size import list_element_compare_size\nfrom tools.list_element_type_change import list_element_type_change\nfrom tools.str_division import str_division\nfrom tools.user_put_verification import user_put_verification\n\n\ndef get_index(request):\n return render(request, 'index.html')\n\n\ndef version_compare(request):\n json_obj = json.loads(request.body)\n num1 = json_obj.get('num1')\n num2 = json_obj.get('num2')\n print(num1, num2)\n\n # 校验输入\n verification_res = user_put_verification(num1, num2)\n print(verification_res)\n if verification_res:\n return JsonResponse({'code': 1000, 'error': '版本号必须是阿拉伯数字,按字符.分割,且版本字符串不以点开始或结束,并且其中不能有两个连续的点'})\n\n # 按 . 分割\n division_res = str_division(num1, num2)\n print(division_res)\n if len(division_res[0]) > 4 or len(division_res[1]) > 4:\n return JsonResponse({'code': 1001, 'error': '请输入最多4级版本号,按字符.分割'})\n\n # 列表每个元素类型转换\n version1 = list_element_type_change(division_res[0], division_res[1])[0]\n version2 = list_element_type_change(division_res[0], division_res[1])[1]\n print(version1, version2)\n\n # 比较本版号大小\n res = list_element_compare_size(version1, version2)\n print(res)\n\n return JsonResponse({'code': 200, 'msg': res})\n","sub_path":"version_number_compare/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"492319966","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='HomepageLine',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('line', models.TextField(verbose_name='Translatable line')),\n ('context', models.TextField(verbose_name='Optional context for translators', blank=True)),\n ('number', models.PositiveSmallIntegerField(unique=True, verbose_name='The token number of the line')),\n ],\n options={\n 'ordering': ('number',),\n 'verbose_name': 'Homepage line',\n 'verbose_name_plural': 'Homepage lines',\n },\n ),\n migrations.CreateModel(\n name='HomepageText',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('full_text', models.TextField(verbose_name='Translatable text')),\n ],\n options={\n 'ordering': ('id',),\n 'verbose_name': 'Homepage text',\n },\n ),\n ]\n","sub_path":"projects/yearcompass_homepage_2015_2016/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"2650324","text":"import logging\nimport os\n\nimport numpy as np\n\nlogging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',\n datefmt='%m/%d/%Y %H:%M:%S',\n level=logging.DEBUG)\nlogger = logging.getLogger(__name__)\n\n\ndef accuracy(out, labels):\n outputs = np.argmax(out, axis=1)\n return np.sum(outputs == labels)\n\n\ndef warmup_linear(x, warmup=0.002):\n if x < warmup:\n return x / warmup\n return 1.0 - x\n\n\ndef create_dirs(dirpath):\n \"\"\"Creating directories.\n \"\"\"\n if not os.path.exists(dirpath):\n os.makedirs(dirpath)\n logger.info(\"==> 📂 Created {0}\".format(dirpath))\n\n\nclass InputExample(object):\n \"\"\"A single training/test example for simple sequence classification.\"\"\"\n\n def __init__(self, guid, text_a, text_b=None, label=None):\n \"\"\"Constructs a InputExample.\n\n Args:\n guid: Unique id for the example.\n text_a: string. The untokenized text of the first sequence. For single\n sequence tasks, only this sequence must be specified.\n text_b: (Optional) string. The untokenized text of the second sequence.\n Only must be specified for sequence pair tasks.\n label: (Optional) string. The label of the example. This should be\n specified for train and dev examples, but not for test examples.\n \"\"\"\n self.guid = guid\n self.text_a = text_a\n self.text_b = text_b\n self.label = label\n\n\nclass InputFeatures(object):\n \"\"\"A single set of features of data.\"\"\"\n\n def __init__(self, input_ids, input_mask, segment_ids, label_id):\n self.input_ids = input_ids\n self.input_mask = input_mask\n self.segment_ids = segment_ids\n self.label_id = label_id\n\n\ndef convert_examples_to_features(examples, label_list, max_seq_length, tokenizer):\n \"\"\"Loads a data file into a list of `InputBatch`s.\"\"\"\n\n label_map = {label: i for i, label in enumerate(label_list)}\n\n features = []\n for (ex_index, example) in enumerate(examples):\n tokens_a = tokenizer.tokenize(example.text_a)\n\n tokens_b = None\n if example.text_b:\n tokens_b = tokenizer.tokenize(example.text_b)\n # Modifies `tokens_a` and `tokens_b` in place so that the total\n # length is less than the specified length.\n # Account for [CLS], [SEP], [SEP] with \"- 3\"\n _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)\n else:\n # Account for [CLS] and [SEP] with \"- 2\"\n if len(tokens_a) > max_seq_length - 2:\n tokens_a = tokens_a[:(max_seq_length - 2)]\n\n # The convention in BERT is:\n # (a) For sequence pairs:\n # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]\n # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1\n # (b) For single sequences:\n # tokens: [CLS] the dog is hairy . [SEP]\n # type_ids: 0 0 0 0 0 0 0\n #\n # Where \"type_ids\" are used to indicate whether this is the first\n # sequence or the second sequence. The embedding vectors for `type=0` and\n # `type=1` were learned during pre-training and are added to the wordpiece\n # embedding vector (and position vector). This is not *strictly* necessary\n # since the [SEP] token unambigiously separates the sequences, but it makes\n # it easier for the model to learn the concept of sequences.\n #\n # For classification tasks, the first vector (corresponding to [CLS]) is\n # used as as the \"sentence vector\". Note that this only makes sense because\n # the entire model is fine-tuned.\n tokens = [\"[CLS]\"] + tokens_a + [\"[SEP]\"]\n segment_ids = [0] * len(tokens)\n\n if tokens_b:\n tokens += tokens_b + [\"[SEP]\"]\n segment_ids += [1] * (len(tokens_b) + 1)\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n\n # The mask has 1 for real tokens and 0 for padding tokens. Only real\n # tokens are attended to.\n input_mask = [1] * len(input_ids)\n\n # Zero-pad up to the sequence length.\n padding = [0] * (max_seq_length - len(input_ids))\n input_ids += padding\n input_mask += padding\n segment_ids += padding\n\n assert len(input_ids) == max_seq_length\n assert len(input_mask) == max_seq_length\n assert len(segment_ids) == max_seq_length\n\n label_id = label_map[example.label]\n features.append(\n InputFeatures(input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n label_id=label_id))\n return features\n\n\ndef convert_example_to_feature(text_a, text_b, max_seq_length, tokenizer, ):\n \"\"\"Transform input text into `InputBatch`.\"\"\"\n\n example = InputExample(guid=None, text_a=text_a, text_b=text_b, label=None)\n tokens_a = tokenizer.tokenize(example.text_a)\n\n tokens_b = None\n if example.text_b:\n tokens_b = tokenizer.tokenize(example.text_b)\n # Modifies `tokens_a` and `tokens_b` in place so that the total\n # length is less than the specified length.\n # Account for [CLS], [SEP], [SEP] with \"- 3\"\n _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)\n else:\n # Account for [CLS] and [SEP] with \"- 2\"\n if len(tokens_a) > max_seq_length - 2:\n tokens_a = tokens_a[:(max_seq_length - 2)]\n\n tokens = [\"[CLS]\"] + tokens_a + [\"[SEP]\"]\n segment_ids = [0] * len(tokens)\n\n if tokens_b:\n tokens += tokens_b + [\"[SEP]\"]\n segment_ids += [1] * (len(tokens_b) + 1)\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n\n # The mask has 1 for real tokens and 0 for padding tokens. Only real\n # tokens are attended to.\n input_mask = [1] * len(input_ids)\n\n # Zero-pad up to the sequence length.\n padding = [0] * (max_seq_length - len(input_ids))\n input_ids += padding\n input_mask += padding\n segment_ids += padding\n\n assert len(input_ids) == max_seq_length\n assert len(input_mask) == max_seq_length\n assert len(segment_ids) == max_seq_length\n\n feature = InputFeatures(input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n label_id=None)\n return feature\n\n\ndef _truncate_seq_pair(tokens_a, tokens_b, max_length):\n \"\"\"Truncates a sequence pair in place to the maximum length.\"\"\"\n\n # This is a simple heuristic which will always truncate the longer sequence\n # one token at a time. This makes more sense than truncating an equal percent\n # of tokens from each, since if one sequence is very short then each token\n # that's truncated likely contains more information than a longer sequence.\n while True:\n total_length = len(tokens_a) + len(tokens_b)\n if total_length <= max_length:\n break\n if len(tokens_a) > len(tokens_b):\n tokens_a.pop()\n else:\n tokens_b.pop()\n","sub_path":"models/bert_model/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"461515464","text":"\"\"\"\nThis component provides support for HP Printers.\nFor more details about this component, please refer to the documentation at\nhttps://home-assistant.io/components/hpprinter/\n\"\"\"\nimport voluptuous as vol\n\nfrom homeassistant.const import (CONF_HOST, CONF_NAME, CONF_DEVICES)\nfrom homeassistant.helpers import config_validation as cv\n\nfrom .const import *\nfrom .HPDeviceData import *\nfrom .home_assistant import HPPrinterHomeAssistant\n\n_LOGGER = logging.getLogger(__name__)\n\nDEVICE_SCHEMA = vol.Schema({\n vol.Required(CONF_HOST): cv.string,\n vol.Optional(CONF_NAME): cv.string\n})\n\nCONFIG_SCHEMA = vol.Schema({\n DOMAIN: vol.Schema({\n vol.Required(CONF_DEVICES, []): vol.All(cv.ensure_list, [vol.Any(DEVICE_SCHEMA)])\n }),\n}, extra=vol.ALLOW_EXTRA)\n\n\ndef setup(hass, config):\n \"\"\"Set up a Blue Iris component.\"\"\"\n _LOGGER.debug(f\"Loading HP Printer domain\")\n\n initialized = False\n devices_handlers = []\n\n conf = config[DOMAIN]\n scan_interval = SCAN_INTERVAL\n devices = conf.get(CONF_DEVICES, [])\n\n device_id = 0\n\n for device in devices:\n try:\n device_id = device_id + 1\n\n host = device.get(CONF_HOST)\n name = device.get(CONF_NAME, f\"{DEFAULT_NAME} #{device_id}\")\n hp_data = None\n\n if host is not None:\n hp_data = HPDeviceData(host, name)\n\n ha = HPPrinterHomeAssistant(hass, scan_interval, name, hp_data)\n\n if host is not None:\n ha.initialize()\n\n devices_handlers.append(ha)\n\n _LOGGER.debug(f\"{name} is loaded\")\n initialized = True\n\n else:\n ha.notify_error_message(f\"{name} was not configured correctly\")\n\n except Exception as ex:\n exc_type, exc_obj, tb = sys.exc_info()\n line_number = tb.tb_lineno\n\n _LOGGER.error(f\"Failed to create HA component, Error: {ex}, Line: {line_number}\")\n\n hass.data[DATA_HP_PRINTER] = devices_handlers\n\n return initialized\n","sub_path":"custom_components/hpprinter/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"179279667","text":"# coding: utf-8\r\n# author: HotDogDevBr.\r\n# E-mail: hotdogdevbr@gmail.com.\r\n\"\"\"\r\n Escreva um programa que exiba o resultado de 2a x 3b, onde\r\n'a' vale 3 e 'b' vale 5.\r\n\"\"\"\r\n\r\na = 3\r\nb = 5\r\nprint((2 * a) * (3 * b))\r\n","sub_path":"Exercicios Livro Python/capitulo 2/exercicio 2.4.py","file_name":"exercicio 2.4.py","file_ext":"py","file_size_in_byte":217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"648978783","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\"\"\"\n\nfrom kytten.dialog import Dialog\nfrom kytten.layout import GridLayout\nfrom kytten.themes import felyne_dark\n\nfrom swine import GameObject, Globals\n\n\nclass Widget(GameObject, Dialog):\n def __init__(self, scene, widget, x=0, y=0):\n GameObject.__init__(self, scene, -1)\n self.widget = widget\n self.widget.id = Globals.WIDGETS\n Globals.WIDGETS += 1\n\n Dialog.__init__(self, content=GridLayout(content=[\n [self.widget]\n ]),\n window=Globals.WINDOW, batch=scene.batch, group=scene.layers[-1], offset=(x, y), theme=felyne_dark)\n","sub_path":"swine/gui/widget.py","file_name":"widget.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"59144344","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Email',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('date_created', models.DateTimeField(auto_now_add=True, verbose_name='Cr\\xe9\\xe9 le')),\n ('name', models.CharField(max_length=254, verbose_name='Nom')),\n ('email', models.EmailField(max_length=254, verbose_name='Adresse email')),\n ('title', models.CharField(max_length=254, null=True, verbose_name='Title', blank=True)),\n ('template', models.TextField(verbose_name='Template')),\n ('is_sent', models.BooleanField(default=False, verbose_name='Envoy\\xe9 ?')),\n ],\n options={\n 'ordering': ('-date_created',),\n 'verbose_name': 'Email',\n 'verbose_name_plural': 'Emails',\n },\n ),\n ]\n","sub_path":"Lib/site-packages/django_extended/contrib/emailing/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"262063734","text":"data = []\nanswer = [0, 0]\nfor i in range(9):\n num = int(input())\n data.append(num)\nfor num, value in enumerate(data):\n if value > answer[1]:\n answer = [num+1, value]\nprint(answer[1])\nprint(answer[0])","sub_path":"2562.py","file_name":"2562.py","file_ext":"py","file_size_in_byte":215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"519465632","text":"# Copyright 2018 The YARL-Project, 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 logging\nimport numpy as np\nimport unittest\n\nfrom yarl.components import Component\nfrom yarl.tests import ComponentTest\nfrom yarl.utils import root_logger\nfrom yarl.tests.dummy_components import Dummy1to1\n\n\nclass TestConnectionsWithLabels(unittest.TestCase):\n \"\"\"\n Tests for different ways to place different, but single sub-Components into the core.\n \"\"\"\n root_logger.setLevel(level=logging.INFO)\n\n def test_connecting_in1_and_1to1_to_1to1_no_labels(self):\n \"\"\"\n Adds two components (A, B) with 1-to-1 graph_fns to the core.\n Connects \"input1\" with A, A's \"output\" to \"output\".\n Connects \"input2\" with B and B's output to A.\n If we now pull out-Socket \"output\", it should know by the given input, which op we actually want.\n \"\"\"\n core = Component(inputs=[\"input1\", \"input2\"], outputs=\"output\", scope=\"container\")\n a = Dummy1to1(scope=\"A\")\n b = Dummy1to1(scope=\"B\")\n # Throw in the sub-components.\n core.add_components(a, b)\n # Connect them.\n core.connect(\"input1\", (a, \"input\"))\n core.connect(\"input2\", (b, \"input\"))\n core.connect((b, \"output\"), (a, \"input\")) # a/input now has two incoming connections.\n core.connect((a, \"output\"), \"output\")\n\n test = ComponentTest(component=core, input_spaces=dict(input1=float, input2=float))\n\n # Now pulling on the same Socket (given one of the input Sockets) should trigger the correct op.\n # Expected output: input1 + 1.0(a)\n test.test(out_socket_names=\"output\", inputs=dict(input1=np.array(1.1)), expected_outputs=2.1)\n # Expected output: input2 + 1.0(b) + 1.0(a)\n test.test(out_socket_names=\"output\", inputs=dict(input2=np.float32(1.1)), expected_outputs=3.1)\n\n def test_connecting_in1_to_1to1_no_labels(self):\n \"\"\"\n Adds one component (A) with 1-to-1 graph_fn to the core which has two in-Sockets and 1 out-Socket.\n Connects \"input_c\" with A, A's \"output\" to \"output\".\n Connects \"input_a\" with A, A's \"output\" to \"output\".\n No labels whatsoever.\n If we now pull \"output\", and provide input1 AND input2, it should use the in-Socket that comes\n first in alphabetic order (\"input_a\" even if it's defined second).\n \"\"\"\n core = Component(inputs=[\"input_c\", \"input_a\"], outputs=\"output\", scope=\"container\")\n a = Dummy1to1(scope=\"A\")\n # Throw in the sub-component.\n core.add_components(a)\n # Connect correctly.\n core.connect(\"input_c\", (a, \"input\"))\n core.connect(\"input_a\", (a, \"input\"))\n core.connect((a, \"output\"), \"output\")\n\n test = ComponentTest(component=core, input_spaces=dict(input_c=float, input_a=float))\n\n # Now pulling on \"output\" and providing both inputs should cause disambiguity, but it should chose\n # the one fist in alphabetic order (input_a).\n # Expected output: input_a + 1.0\n test.test(out_socket_names=\"output\", inputs=dict(input_c=np.array(1.5), input_a=np.array(2.1)),\n expected_outputs=3.1)\n\n def test_connecting_in1_and_in2_to_1to1_to_out1_and_out2_with_labels(self):\n \"\"\"\n Same as `test_connecting_in1_to_1to1_no_labels` but with labels.\n So if we provide both inputs, it should know which one to take (instead of using alphabetic order).\n \"\"\"\n core = Component(inputs=[\"input_c\", \"input_a\"], outputs=\"output\", scope=\"container\")\n dummy = Dummy1to1(scope=\"dummy\")\n # Throw in the sub-component.\n core.add_components(dummy)\n # Connect correctly (with labels).\n # [input_c->dummy/input] is now labelled as \"from_in_c\" (op_records passing to dummy will be labelled so).\n core.connect(\"input_c\", (dummy, \"input\"), label=\"from_in_c\")\n # [input_a->dummy/input] is now labelled as \"from_in_a\" (op_records passing to dummy will be labelled so).\n core.connect(\"input_a\", (dummy, \"input\"), label=\"from_in_a\")\n # Force using the input_c path (over the alphabetically favored input_a).\n # [dummy/output->output] is now labelled as \"from_in_c\" and will thus only allow ops that have this label to\n # be passed through to \"output\" (all other op_records will be filtered).\n core.connect((dummy, \"output\"), \"output\", label=\"from_in_c\")\n\n test = ComponentTest(component=core, input_spaces=dict(input_c=float, input_a=float))\n\n # Now pulling on \"output\" and providing both inputs should not cause disambiguity since out out-Socket\n # was connected to A's \"output\" through the label \"from_in_c\", so it should always use \"input_c\".\n # Expected output: input_c + 1.0\n test.test(out_socket_names=\"output\", inputs=dict(input_c=np.array(1.5), input_a=np.array(2.1)),\n expected_outputs=2.5)\n test.test(out_socket_names=\"output\", inputs=dict(input_c=np.array(1.5), input_a=np.array(2.1)),\n expected_outputs=2.5)\n\n def test_connecting_in_to_2x_to_different_1to1_then_2x_to_1to1_to_out1_and_out2_with_labels(self):\n \"\"\"\n\n \"\"\"\n core = Component(inputs=\"input\", outputs=[\"output1\", \"output2\"], scope=\"container\")\n pre1 = Dummy1to1(scope=\"pre1\")\n pre2 = Dummy1to1(scope=\"pre2\", constant_value=2.0) # make it different from pre1\n hub = Dummy1to1(scope=\"hub\")\n\n # Throw in the sub-components.\n core.add_components(pre1, pre2, hub)\n\n # Connect correctly (with labels).\n core.connect(\"input\", (pre1, \"input\"))\n core.connect(\"input\", (pre2, \"input\"))\n # [pre1/input->hub/input] is now labelled as \"from_pre1\" (op_records passing to dummy will be labelled so).\n core.connect((pre1, \"output\"), (hub, \"input\"), label=\"from_pre1\")\n # [pre2/input->hub/input] is now labelled as \"from_pre2\" (op_records passing to dummy will be labelled so).\n core.connect((pre2, \"output\"), (hub, \"input\"), label=\"from_pre2\")\n # Provide both paths (via pre1 or pre2) via labels for the two different out-Sockets.\n core.connect((hub, \"output\"), \"output1\", label=\"from_pre1\")\n core.connect((hub, \"output\"), \"output2\", label=\"from_pre2\")\n\n test = ComponentTest(component=core, input_spaces=dict(input=float))\n\n # Now pulling on \"output1\", should take the op over pre1. Pulling \"output2\" should take the op over pre2.\n # Expected output: (input + 1.0) + 1.0\n test.test(out_socket_names=\"output1\", inputs=dict(input=np.array(187.5)), expected_outputs=189.5)\n # Expected output: (input + 2.0) + 1.0\n test.test(out_socket_names=\"output2\", inputs=dict(input=np.array(87.5)), expected_outputs=90.5)\n","sub_path":"yarl/tests/test_core/test_connections_with_labels.py","file_name":"test_connections_with_labels.py","file_ext":"py","file_size_in_byte":7503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"440398683","text":"#coding: utf-8\r\nimport tensorflow as tf\r\nimport tools\r\nimport tensorflow.keras as kr\r\n\r\ndef create_onehot(one_data,vocab_data,max_length):\r\n\tvocab_list = tools.read_file(vocab_data)\r\n\tvocabulary_word2index = {} ### word :index\r\n\tvocabulary_index2word = {} ### index :word\r\n\tfor i, vocab in enumerate(vocab_list):\r\n\t\tvocabulary_word2index[vocab] = i\r\n\t\tvocabulary_index2word[i] = vocab\r\n\r\n\tif isinstance(one_data, str) and \".txt\" in one_data:###是字符串,即txt\r\n\t\tone_data_list = tools.read_file(one_data)\r\n\t\tsingleTest = False\r\n\telse:\r\n\t\tone_data_list = one_data ### 数组\r\n\t\tsingleTest = True\r\n\tX = []\r\n\tif not singleTest:\r\n\t\tfor data in one_data_list:\r\n\t\t\tcontent = [vocabulary_word2index.get(e, 0) for e in data]\r\n\t\t\tX.append(content)\r\n\t\tx_pad = kr.preprocessing.sequence.pad_sequences(X, max_length) #### 对数据进行定长处理\r\n\telse:\r\n\t\tcontent = [vocabulary_word2index.get(e, 0) for e in one_data_list]\r\n\t\tX.append(content)\r\n\t\tx_pad = kr.preprocessing.sequence.pad_sequences(X, max_length)\r\n\treturn x_pad\r\n\r\ndef decode_text(labels):\r\n\tcategories, cat_to_id = tools.label_dict()\r\n\twords = []\r\n\tfor word_num in labels:\r\n\t\tword = categories[word_num]\r\n\t\twords.append(word)\r\n\treturn words\r\n\r\nclass Textcnn_pred(object):\r\n\tdef __init__(self,pb_path):\r\n\t\twith tf.Graph().as_default():\r\n\t\t\tself.output_graph_def = tf.GraphDef()\r\n\t\t\twith open(pb_path, \"rb\") as f:\r\n\t\t\t\tself.output_graph_def.ParseFromString(f.read())\r\n\t\t\t\ttf.import_graph_def(self.output_graph_def, name=\"\")\r\n\t\t\tsess_config = tf.ConfigProto(allow_soft_placement=True)\r\n\t\t\tsess_config.gpu_options.per_process_gpu_memory_fraction = 0.8\r\n\t\t\tsess_config.gpu_options.allow_growth = True\r\n\t\t\tself.sess = tf.Session(config=sess_config)\r\n\t\t\tself.sess.run(tf.global_variables_initializer())\r\n\t\t\t# 定义输入的张量名称,对应网络结构的输入张量\r\n\t\t\t# input:0作为输入图像,keep_prob:0作为dropout的参数,测试时值为1,is_training:0训练参数\r\n\t\t\tself.input_image_tensor = self.sess.graph.get_tensor_by_name(\"input_x:0\")\r\n\t\t\t# 定义输出的张量名称\r\n\t\t\toutput_tensor_name = self.sess.graph.get_tensor_by_name(\"output:0\")\r\n\t\t\tself.textcnn_pred = tf.argmax(tf.nn.softmax(output_tensor_name), 1)\r\n\t\tprint(\"################ load TextCNN model down! ##########################\")\r\n\r\n\tdef _close(self):\r\n\t\tself.sess.close()\r\n\r\n\tdef text_pre(self,input):\r\n\t\ttest_X = create_onehot(one_data=input, vocab_data=\"./model_and_data/vocab.txt\", max_length=200)\r\n\t\tout=self.sess.run(self.textcnn_pred, feed_dict={self.input_image_tensor: test_X})\r\n\t\tresult = decode_text(out)\r\n\t\treturn result\r\n\r\nif __name__==\"__main__\":\r\n\ttextcnn = Textcnn_pred(pb_path=\"./model_and_data/textcnn_twoClass.pb\")\r\n\twhile 1:\r\n\t\t#inputs = ['龙岗区四联路30号路段多辆车辆违停,私设路障,严重影响车辆和行人通行。',\r\n\t\t# '馨荔苑业主群,13:44分报警人发来短信:对不起,拨错号了,歉意。',\r\n\t # ]\r\n\t\tprint(\"开始输入:\")\r\n\t\tinputs = input()\r\n\t\tpred = textcnn.text_pre(inputs)[0]\r\n\t\tprint(\"Result: \",pred)","sub_path":"Release/textcnn_pb.py","file_name":"textcnn_pb.py","file_ext":"py","file_size_in_byte":3047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"186460344","text":"\r\n# coding: utf-8\r\nimport _init_paths\r\n\r\nimport sys\r\nimport os\r\nimport os.path\r\nimport random\r\nimport collections\r\nimport shutil\r\nimport time\r\nimport glob\r\nimport csv\r\nimport numpy as np\r\n\r\nimport torch\r\nimport torch.backends.cudnn as cudnn\r\nimport torch.nn as nn\r\nimport torch.nn.parallel\r\nimport torch.optim as optim\r\nimport torch.utils.data as data\r\nimport torchvision.datasets as datasets\r\nimport torchvision.models as models\r\nimport torchvision.transforms as transforms\r\nimport utils\r\n#from utils.Tensor import to_variable,to_numpy\r\nfrom utils.metric import AccuracyMeter,MovingAverageMeter,AverageMeter\r\nfrom torch.autograd import Variable\r\nimport torch.nn.functional as F\r\nimport image_loader\r\nfrom image_loader import image_loader\r\n\r\nfrom PIL import Image\r\n\r\n\r\nclass Trainer(object):\r\n def __init__(self, model, optimizer, train_loader, valid_loader, use_cuda=True):\r\n self.model = model\r\n self.optimizer = optimizer\r\n self.train_loader = train_loader\r\n self.valid_loader = valid_loader\r\n self.use_cuda = use_cuda\r\n\r\n def train(self, epoch):\r\n self.model.train()\r\n\r\n train_loss = AverageMeter()\r\n train_acc = AccuracyMeter()\r\n\r\n for i, (x, y) in enumerate(self.train_loader):\r\n x = Variable(x)\r\n y = Variable(y)\r\n if self.use_cuda:\r\n x = x.cuda()\r\n y = y.cuda()\r\n output = self.model(x)\r\n loss = F.cross_entropy(output, y)\r\n\r\n self.optimizer.zero_grad()\r\n loss.backward()\r\n self.optimizer.step()\r\n\r\n train_loss.update(float(loss.data))\r\n\r\n y_pred = output.data.max(dim=1)[1]\r\n correct = int(y_pred.eq(y.data).cpu().sum())\r\n train_acc.update(correct, x.size(0))\r\n if i % 10 ==0:\r\n print('\\nTrain Epoch/batch| [{}/{}]: Average batch loss: {:.6f}\\n'.format(epoch,i,train_acc.accuracy))\r\n return train_loss.average, train_acc.accuracy\r\n\r\n def validate(self):\r\n self.model.eval()\r\n\r\n valid_loss = AverageMeter()\r\n valid_acc = AccuracyMeter()\r\n\r\n for i, (x, y) in enumerate(self.valid_loader):\r\n x = Variable(x, volatile=True)\r\n y = Variable(y).long()\r\n if self.use_cuda:\r\n x = x.cuda()\r\n y = y.cuda()\r\n output = self.model(x)\r\n loss = F.cross_entropy(output, y)\r\n\r\n valid_loss.update(float(loss.data))\r\n\r\n y_pred = output.data.max(dim=1)[1]\r\n correct = int(y_pred.eq(y.data).cpu().sum())\r\n valid_acc.update(correct, x.size(0))\r\n print('\\nTrain Epoch [{}]: Average batch loss: {:.6f}\\n'.format(epoch,valid_acc.accuracy))\r\n return valid_loss.average, valid_acc.accuracy\r\n\r\ndef print_msg(proc,epoch,loss,acc):\r\n print('proc={},epoch={}:loss={},acc={}'.format(proc,epoch,loss,acc))\r\n\r\nif __name__ == '__main__':\r\n train_batch_size=32\r\n\r\n ROOT_DIR = os.getcwd()\r\n DATA_HOME_DIR = ROOT_DIR + '/data/cat_dog'\r\n\r\n # paths\r\n data_path = DATA_HOME_DIR \r\n train_path = data_path + '/train/'\r\n valid_path = data_path + '/test/'\r\n train_loader,valid_loader=image_loader(train_path,valid_path,\r\n train_batch_size,\r\n valid_batch_size=None,\r\n train_shuffle=True,\r\n valid_shuffle=False,\r\n train_num_workers=0,\r\n valid_num_workers=0)\r\n\r\n #model = models.resnet34(pretrained=True) \r\n model = models.resnet50(pretrained=True) \r\n for param in model.parameters():\r\n param.requires_grad = False\r\n #model.fc = nn.Linear(512,2) #resnet34\r\n model.fc = nn.Linear(2048,2)\r\n #optimizer = optim.Adam(model.parameters(), lr=1e-4)\r\n optimizer = optim.Adam(model.fc.parameters(), lr=1e-4, weight_decay=1e-4)\r\n if torch.cuda.is_available():\r\n model.cuda()\r\n \r\n #optimizer = optim.Adam(model.module.fc.parameters(), lr=1e-3)\r\n scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=3, gamma=0.85)\r\n trainer = Trainer(model=model,optimizer=optimizer,train_loader=train_loader,valid_loader=valid_loader,use_cuda=True)\r\n epochs = 50\r\n train_loss_epochs=np.zeros((epochs,))\r\n train_acc_epochs=np.zeros((epochs,))\r\n test_loss_epochs=np.zeros((epochs,))\r\n test_acc_epochs=np.zeros((epochs,))\r\n i=0\r\n for epoch in range(1, 10):\r\n scheduler.step()\r\n train_loss, train_acc=trainer.train(epoch)\r\n train_loss_epochs[i]=train_loss\r\n train_acc_epochs[i]=train_acc\r\n print_msg('train',epoch,train_loss,train_acc)\r\n test_loss, test_acc=trainer.validate()\r\n test_loss_epochs[i]=test_loss\r\n test_acc_epochs[i]=test_acc\r\n print_msg('test',epoch,test_loss,test_acc)\r\n i+=1\r\n data = dict()\r\n data['train_loss']=train_loss_epochs\r\n data['train_acc']=train_acc_epochs\r\n data['test_loss']=test_loss_epochs\r\n data['test_acc']=test_acc_epochs\r\n torch.save(data,'data.pt')\r\n print('finished')\r\n ","sub_path":"Test/classifier_dog_cat.py","file_name":"classifier_dog_cat.py","file_ext":"py","file_size_in_byte":5093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"547258164","text":"import numpy as np\n\n\ndef get_objects_from_label(label_file):\n with open(label_file, 'r') as f:\n lines = f.readlines()\n objects = [Object3d(line) for line in lines]\n return objects\n\n\ndef cls_type_to_id(cls_type):\n type_to_id = {'Car': 1, 'Pedestrian': 2, 'Cyclist': 3, 'Van': 4}\n if cls_type not in type_to_id.keys():\n return -1\n return type_to_id[cls_type]\n\n\nclass Object3d(object):\n def __init__(self, line):\n label = line.strip().split(' ')\n self.src = line\n self.cls_type = label[0]\n self.cls_id = cls_type_to_id(self.cls_type)\n self.truncation = float(label[1])\n self.occlusion = float(label[2]) # 0:fully visible 1:partly occluded 2:largely occluded 3:unknown\n self.alpha = float(label[3])\n self.box2d = np.array((float(label[4]), float(label[5]), float(label[6]), float(label[7])), dtype=np.float32)\n self.h = float(label[8])\n self.w = float(label[9])\n self.l = float(label[10])\n self.loc = np.array((float(label[11]), float(label[12]), float(label[13])), dtype=np.float32)\n self.dis_to_cam = np.linalg.norm(self.loc)\n self.ry = float(label[14])\n self.score = float(label[15]) if label.__len__() == 16 else -1.0\n self.level_str = None\n self.level = self.get_kitti_obj_level()\n\n def get_kitti_obj_level(self):\n height = float(self.box2d[3]) - float(self.box2d[1]) + 1\n\n if height >= 40 and self.truncation <= 0.15 and self.occlusion <= 0:\n self.level_str = 'Easy'\n return 0 # Easy\n elif height >= 25 and self.truncation <= 0.3 and self.occlusion <= 1:\n self.level_str = 'Moderate'\n return 1 # Moderate\n elif height >= 25 and self.truncation <= 0.5 and self.occlusion <= 2:\n self.level_str = 'Hard'\n return 2 # Hard\n else:\n self.level_str = 'UnKnown'\n return -1\n\n def generate_corners3d(self):\n \"\"\"\n generate corners3d representation for this object\n :return corners_3d: (8, 3) corners of box3d in camera coord\n \"\"\"\n l, h, w = self.l, self.h, self.w\n x_corners = [l / 2, l / 2, -l / 2, -l / 2, l / 2, l / 2, -l / 2, -l / 2]\n y_corners = [0, 0, 0, 0, -h, -h, -h, -h]\n z_corners = [w / 2, -w / 2, -w / 2, w / 2, w / 2, -w / 2, -w / 2, w / 2]\n\n R = np.array([[np.cos(self.ry), 0, np.sin(self.ry)],\n [0, 1, 0],\n [-np.sin(self.ry), 0, np.cos(self.ry)]])\n corners3d = np.vstack([x_corners, y_corners, z_corners]) # (3, 8)\n corners3d = np.dot(R, corners3d).T\n corners3d = corners3d + self.loc\n return corners3d\n\n def to_str(self):\n print_str = '%s %.3f %.3f %.3f box2d: %s hwl: [%.3f %.3f %.3f] pos: %s ry: %.3f' \\\n % (self.cls_type, self.truncation, self.occlusion, self.alpha, self.box2d, self.h, self.w, self.l,\n self.loc, self.ry)\n return print_str\n\n def to_kitti_format(self):\n kitti_str = '%s %.2f %d %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f %.2f' \\\n % (self.cls_type, self.truncation, int(self.occlusion), self.alpha, self.box2d[0], self.box2d[1],\n self.box2d[2], self.box2d[3], self.h, self.w, self.l, self.loc[0], self.loc[1], self.loc[2],\n self.ry)\n return kitti_str\n","sub_path":"pcdet/utils/object3d_kitti.py","file_name":"object3d_kitti.py","file_ext":"py","file_size_in_byte":3449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"511669873","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\nimport datetime\nimport json\n\nfrom elasticsearch import Elasticsearch, helpers\nfrom data_transmission.application.helper.file_operator import FileOperator\nfrom data_transmission.application.helper.mysql_helper import MysqlHelper\nfrom data_transmission.application.helper import LOG_WARNING\nfrom data_transmission.application.helper.run import wrapper\n\n\nclass ElasticsearchHelper(object):\n def __init__(self, es_config, db_url):\n if not es_config:\n es_config = {\"host\": \"127.0.0.1\", \"port\": 9200}\n self.es = self._init_es_connect(es_config)\n self.file_operator = FileOperator()\n self.mysql_obj = MysqlHelper(db_url)\n\n @staticmethod\n def _init_es_connect(es_config):\n username = es_config.pop('username') if 'username' in es_config else None\n password = es_config.pop('password') if 'password' in es_config else None\n if username and password:\n return Elasticsearch(hosts=[es_config], http_auth=(username, password))\n else:\n return Elasticsearch(hosts=[es_config])\n\n def query(self, es_query, index=\"s_cmm*\", current_node_code=None):\n result = list()\n if current_node_code:\n query_temp = {\"term\": {\"belong.deploy_level.keyword\": {\"value\": current_node_code}}}\n es_query[\"query\"][\"bool\"][\"must\"].append(query_temp)\n try:\n search_result = self.es.search(index=index, body=es_query)\n if \"hits\" in search_result:\n temp_data = search_result.get(\"hits\")\n if \"hits\" in temp_data:\n data = temp_data.get(\"hits\")\n # 取出主要数据\n if not isinstance(data, list):\n data = [data]\n for each in data:\n if \"_source\" in each:\n _source = each.get(\"_source\")\n _index = each.get(\"_index\")\n _doc_type = each.get(\"_type\")\n format_data = {\"_index\": _index, \"_type\": _doc_type, \"_source\": _source}\n result.append(format_data)\n except Exception as ex:\n LOG_WARNING.error(u\"ES查询数据时错误,查询条件为:{}\".format(es_query))\n LOG_WARNING.error(u\"错误的原因为:{}\".format(str(ex)))\n return result\n\n def save_data_to_file(self, file_name, file_path, history_times, current_node_code=None, limit_size=1000):\n result = list()\n es_queries = self.calculate_query_sentence(history_times)\n data_list = list()\n for each_es_query in es_queries:\n json_data = self.query(each_es_query, current_node_code=current_node_code)\n if json_data:\n data_list += json_data\n # 如果查询的数据不存在,不做处理\n if data_list:\n # 将10分钟的数据进行拆分\n split_data_list = self.split_data(data=data_list, limit_size=limit_size)\n for index, data in enumerate(split_data_list):\n temp_file_name = \"{}_-{}.txt\".format(file_name, index + 1)\n self.file_operator.save_file(data=data, file_name=temp_file_name, file_path=file_path)\n result.append(temp_file_name)\n return result\n\n @staticmethod\n def calculate_query_sentence(history_times):\n # 查询当前ES的数据,history_times为空的时候,查询当前所有ES的数据,不为空的时候,根据history_times查询往后的10min\n # 计算时间差,10min的数据以每分钟来查询,防止一次查询10min的数据超过10000条\n result = list()\n if history_times:\n now_time = datetime.datetime.now()\n for _ in range(0, 10):\n temp_time = now_time - datetime.timedelta(minutes=1)\n start_time = temp_time.strftime(\"%Y-%m-%d %H:%M:%S\")\n end_time = now_time.strftime(\"%Y-%m-%d %H:%M:%S\")\n es_query = {\n \"query\": {\n \"bool\": {\n \"must\": [\n {\n \"range\": {\n \"public_field.datatime.keyword\": {\n \"gte\": start_time,\n \"lte\": end_time\n }\n }\n }\n ]\n }\n },\n \"size\": 10000\n }\n result.append(es_query)\n now_time = temp_time\n else:\n now_time = datetime.datetime.now()\n start_time = now_time.strftime(\"%Y-%m-%d %H:%M:%S\")\n es_query = {\n \"query\": {\n \"bool\": {\n \"must\": [\n {\n \"range\": {\n \"public_field.datatime.keyword\": {\n \"lte\": start_time\n }\n }\n }\n ]\n }\n },\n \"size\": 10000\n }\n result.append(es_query)\n return result\n\n @staticmethod\n def split_data(data, limit_size=1000):\n \"\"\"\n 将每10分钟从ES查询的数据分隔开,避免文件过大.\n 100条数据,大概1.2M.\n :param data: ES查询出的所有数据.\n :param limit_size: 每个文件的数据量.\n :return:\n \"\"\"\n len_data = len(data)\n number = len_data // limit_size\n result = list()\n if data:\n if number == 0:\n result.append(data)\n else:\n index = 0\n for index in range(0, number):\n result.append(data[index * limit_size: (index + 1) * limit_size])\n last_data = data[(index + 1) * limit_size:]\n if last_data:\n result.append(last_data)\n return result\n\n def insert_into_es(self, task_id, data, send_params, typeof, source, es_handler=None):\n try:\n if data:\n self.mysql_obj.insert_record(task_id, send_params=send_params, typeof=typeof, success_flag=0, source=source)\n distinguish_data = self.distinguish_index(data=data)\n flag = None\n for es_index, es_data in distinguish_data.items():\n if es_data:\n flag = wrapper(self.bulk_insert, es_index, es_data, es_handler)\n # self.bulk_insert(es_index=es_index, data=es_data, es_handler=es_handler)\n if flag:\n self.mysql_obj.set_except_flag(task_id, 1)\n except Exception as ex:\n LOG_WARNING.error(u\"读取文件数据,并将数据插入ES时出错,错误原因为:{}\".format(str(ex)))\n\n def bulk_insert(self, es_index, data, es_handler=None):\n \"\"\"\n 批量插入数据到ES。\n :param str es_index: 待插入的ES的index.\n :param list data: 待批量插入的数据.\n :param es_handler: 测试时用.\n 数据格式:[{\"_index\": index, \"_type: type, \"_source\": source}, ...]\n :return:\n \"\"\"\n try:\n if es_handler:\n es = self._init_es_connect(es_handler)\n else:\n es = self.es\n self.create_es_index(index=es_index, es=es)\n # 先去除重复数据\n # data = self.remove_duplicates(data)\n helpers.bulk(es, data)\n return True\n except Exception as ex:\n LOG_WARNING.error(u\"批量插入数据到ES时发生错误,错误原因为:{}\".format(str(ex)))\n return False\n\n @staticmethod\n def distinguish_index(data):\n \"\"\"\n 一次读取的文件内容中可能包含不同天的数据,要将数据区分出来.\n :param data: 一次读取的文件数据\n :return: 整理后的数据.\n \"\"\"\n result = dict()\n if data:\n try:\n if isinstance(data, (bytes, str)):\n data = json.loads(data)\n except json.JSONDecodeError:\n LOG_WARNING.error(u\"ES数据格式有问题,丢弃该次数据.\")\n return result\n if not isinstance(data, list):\n data = [data]\n for each in data:\n index = each.get(\"_index\")\n if index in result:\n result[index].append(each)\n else:\n result.setdefault(index, [each])\n return result\n\n def create_es_index(self, index, es=None):\n # 为index设置容错率\n mapping = {\n \"settings\": {\n \"index.mapping.ignore_malformed\": True\n },\n \"mappings\": {\n \"DEVICE\": {\n \"properties\": {\n \"GGQ\": {\"properties\": {\"FSSJ\": {\"type\": \"date\", \"format\": \"yyyy-MM-dd HH:mm:ss\"}}}}\n },\n \"CHANNEL\": {\n \"properties\": {\n \"GGQ\": {\"properties\": {\"FSSJ\": {\"type\": \"date\", \"format\": \"yyyy-MM-dd HH:mm:ss\"}}}}\n },\n \"DATA\": {\n \"properties\": {\n \"GGQ\": {\"properties\": {\"FSSJ\": {\"type\": \"date\", \"format\": \"yyyy-MM-dd HH:mm:ss\"}}}}\n },\n \"BUSINESS\": {\n \"properties\": {\n \"GGQ\": {\"properties\": {\"FSSJ\": {\"type\": \"date\", \"format\": \"yyyy-MM-dd HH:mm:ss\"}}}}\n },\n \"SOFTWARE\": {\n \"properties\": {\n \"GGQ\": {\"properties\": {\"FSSJ\": {\"type\": \"date\", \"format\": \"yyyy-MM-dd HH:mm:ss\"}}}}\n }\n\n }\n }\n try:\n if index:\n if es:\n if not es.indices.exists(index=index):\n es.indices.create(index=index, body=mapping)\n else:\n if not self.es.indices.exists(index=index):\n self.es.indices.create(index=index, body=mapping)\n except Exception as e:\n LOG_WARNING.warning('为{}的index设置settings出错,错误原因:{}'.format(index, str(e)))\n\n def remove_duplicates(self, es_data):\n es_query = {\n\n }\n self.es.search()\n","sub_path":"data_transmission/data_transmission/application/helper/elasticsearch_operator.py","file_name":"elasticsearch_operator.py","file_ext":"py","file_size_in_byte":10738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"173378712","text":"#!/usr/bin/env python\nimport os,sys\nsys.path.insert(1, os.path.join(sys.path[0], '..'))\nimport argparse\nimport time\n\nfrom multiagent.environment import MultiAgentEnv\nfrom multiagent.policy import InteractivePolicy\nimport multiagent.scenarios as scenarios\nfrom multiagent.speaker_listener import SpeakerListenerScenario\n\nimport numpy as np\nfrom multiagent.grid.grid_env import Env\nfrom multiagent.grid.q_learning_agent import QLearningAgent\nfrom multiagent.grid.random_action_agent import RandomActionAgent\nfrom multiagent.grid.greedy_agent import GreedyAgent\nfrom multiagent.grid.deep_reinforce_agent import DeepReinforceAgent\nfrom multiagent.grid.central_controler import CentralController\nimport copy\n\n\nEPISODES = 1000\n\n\nif __name__ == \"__main__\":\n max_agent_count = 10\n max_victim_count = 10\n\n env = Env(max_agent_count, max_victim_count)\n\n agent_count = 1\n victim_count = 3\n\n # reproduce reinforcement\n agent = DeepReinforceAgent(actions=list(range(env.n_actions)), agent_id=0, env=env)\n env.add_agent_at_pos(agent, 0)\n\n env.add_victim_at_pos(5, -1)\n env.add_victim_at_pos(11, -1)\n env.add_victim_at_pos(17, -1)\n env.add_victim_at_pos(24, 1)\n\n # for i in range(agent_count):\n # agent = DeepReinforceAgent(actions=list(range(env.n_actions)), agent_id=i, env=env)\n # env.add_agent(agent)\n #\n # for i in range(victim_count):\n # env.add_victim()\n\n env.pack_canvas()\n\n scheduler = CentralController(env, env.get_agents(), env.get_victims())\n\n for episode in range(EPISODES):\n state_n = env.reset_n()\n print(\"Episode\", episode, \"states:\", state_n)\n counter = 0\n cumulative_reward = 0\n while True:\n env.render()\n done = False\n counter = counter + 1\n\n done_n = np.zeros(agent_count)\n reward_n = np.zeros(agent_count)\n action_n = scheduler.get_action(state_n)\n\n # take action and proceed one step in the environment\n for i in range(agent_count):\n agent = env.get_agent(i)\n # state = str(state_n[i])\n action = action_n[i]\n\n next_state, reward, done_i = env.agent_step(agent, action)\n done_n[i] = done_i\n state_n[i] = copy.deepcopy(next_state)\n reward_n[i] = reward\n\n cumulative_reward += reward\n print(\"Episode=\", episode, \", agent=\", agent.get_id(), \", at iteration=\", counter, \", with total reward=\", cumulative_reward)\n\n # env.print_value_all(agent.q_table)\n\n scheduler.append_sample(state_n, action_n, reward_n)\n done = (np.sum(done_n) == len(done_n))\n # if episode ends, then break\n if done:\n\n scheduler.train_model()\n\n print(\"Episode=\", episode, \", ends in a number of iterations=\", counter, \", with total reward=\", cumulative_reward)\n break\n","sub_path":"multiagent/grid/run_reinforce.py","file_name":"run_reinforce.py","file_ext":"py","file_size_in_byte":2980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"221039259","text":"import sys\nfrom IPython.display import display, HTML\n\n\nclass Displayer:\n _quiet = False\n\n def __init__(self, quiet=False):\n self._quiet = quiet\n\n def _display(self, game):\n if not self._quiet:\n print(game)\n\n def show(self, game):\n self._display(game)\n\n def win(self, game):\n self._display(game)\n print(\"You win! Score: %s\" % game.score)\n\n def lose(self, game):\n print(\"You lose! Score: %s\" % game.score)\n\n\nclass IPythonDisplayer(Displayer):\n\n def __init__(self, board_size=40, quiet=False):\n self._quiet = quiet\n self._size = board_size\n\n def _render(self, game):\n board = game.board\n html = '''

Score: {}

'''.format(game.score)\n table = '''{}
'''\n td = '''{}''' % (self._size, self._size)\n content = ''\n for row in range(game.size):\n content += ''''''\n for col in range(game.size):\n elem = int(board[row, col])\n content += td.format(elem if elem else \"\")\n content += ''''''\n html += table.format(content)\n return html\n\n def _display(self, game):\n if 'ipykernel' in sys.modules:\n if not self._quiet:\n source = self._render(game)\n display(HTML(source))\n else:\n print(\"Warning: since it's not in ipykernel, \"\n \"it will show the command line version.\")\n super()._display(game)\n","sub_path":"game2048/displayer.py","file_name":"displayer.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"347873403","text":"class Solution(object):\n def minPathSum(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n import sys\n if grid == None or len(grid) < 1 or len(grid[0]) < 1:\n return 0\n dp = [sys.maxint]*(len(grid[0])+1)\n dp[1] = 0\n for i in range(len(grid)):\n for j in range(1,len(grid[0])+1):\n dp[j] = min(dp[j-1], dp[j]) + grid[i][j-1]\n return dp[-1]\n","sub_path":"Python/MinPathSum.py","file_name":"MinPathSum.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"251222329","text":"a = '654a654asda54sddsgiuhOIIOHKJHQOHDFKJH'\n\na.capitalize() # 第一个字符串改成大写\na.casefold() # 所有改成小写\na.center(width=123) # 字符串居中\n# a.count(sub, start=, end=) # 返回字符串出现的次数\na.encode(encoding='utf-8', errors='strict') # encoding 编码\n#a.endswith(sub, start=, end=) # 检查是否有字符串\na.expandtabs() #\n# a.find(sub=, start=, end=)\n#a.index(sub=, start=, end=)\na.isalnum()\na.isalpha()\na.isdecimal()\na.isdigit()\na.islower()\na.isnumeric()\na.isspace()\na.istitle()\na.isupper()\na.join()\na.ljust()\na.lower()\na.ljust()\na.lower()\na.lstrip()\na.partition()\n#a.replace(old=, new=, count=)\na.rfind()\na.rindex()\na.rjust()\na.split()\na.upper()\na.title()\n","sub_path":"FishC_homework/字符串方法.py","file_name":"字符串方法.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"363812092","text":"import scrapy\nimport re\n#to do: course_specialisation \n# instructors_list\n\nclass PrometheusSpider(scrapy.Spider):\n name = 'prometheus'\n custom_settings = {\n 'ITEM_PIPELINES': {\n 'tutorial.pipelines.TutorialPipeline': 400\n }\n }\n start_urls = ['https://prometheus.org.ua/courses/']\n\n def parse(self, response):\n for href in response.xpath('//h3[contains(@class, \"gdlr-item-title gdlr-skin-title gdlr-skin-border\")]/a[contains(@href, \"courses\")]/@href').extract():\n yield scrapy.Request(response.urljoin(href),\n callback=self.parse_course)\n\n\n def parse_course(self, response):\n instructors_list = {}\n # print(response.xpath('//article[contains(@class, \"teacher\")]/h3/text()'))\n # print(response.xpath('//article[contains(@class, \"teacher\")]/p').extract())\n for instructor, info in zip(response.xpath('//article[contains(@class, \"teacher\")]/h3/text()').extract(), response.xpath('//article[contains(@class, \"teacher\")]/p').extract()):\n instructors_list[instructor] = info.replace('

', '').replace('

', '')\n weeks_duration = response.xpath('(//h2[contains(text(), \"Тривалість\") or contains(text(), \"ТРИВАЛІСТЬ КУРСУ\") or contains(text(), \"Довжина курсу\")]/following-sibling::p)[1]/text()').extract()\n course_provider = (response.url).split('/')[4]\n if 'course-v1' in course_provider:\n course_provider = None\n try:\n duration_filter = (re.findall('\\d+', weeks_duration[0]))[0]\n\n # duration_filter = int(weeks_duration[0][0])\n except:\n duration_filter = None\n # instructor_name = response.xpath('//article[contains(@class, \"teacher\")]/h3/text()').extract()\n # instructors_desc = response.xpath('//article[contains(@class, \"teacher\")]/p/text()').extract()\n yield {\n 'name': response.xpath('//div[contains(@class, \"heading-group\")]/h1/text()').extract()[0].strip(),\n 'source': 'prometheus',\n 'category': None,\n 'provider': course_provider,\n 'language': 'Українська',\n 'duration': None if not weeks_duration else weeks_duration[0],\n 'duration_filter': duration_filter,\n 'instructors_list': instructors_list,\n 'start_date': response.xpath('//span[contains(@class, \"important-dates-item-text start-date\")]/text()').extract()[0],\n 'description': response.xpath('//section[contains(@class, \"about\")]/p/text()').extract()[0],\n 'link': response.url,\n 'video': None,\n # 'price': None,\n 'img': 'https://edx.prometheus.org.ua' + response.xpath('//div[contains(@class, \"hero\")]/img/@src').extract()[0]\n # }\n }","sub_path":"spiders2/tutorial/spiders/prometheus_spider.py","file_name":"prometheus_spider.py","file_ext":"py","file_size_in_byte":2857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"231237037","text":"import cv2\n\nimport RPi.GPIO as GPIO # RPi.GPIO 라이브러리를 GPIO로 사용\n\nfrom time import sleep # time 라이브러리의 sleep함수 사용\n\nservoPin = 12 # 서보 핀\n\nSERVO_MAX_DUTY = 12 # 서보의 최대(180도) 위치의 주기\n\nSERVO_MIN_DUTY = 3 # 서보의 최소(0도) 위치의 주기\n\nGPIO.setmode(GPIO.BOARD) # GPIO 설정\n\nGPIO.setup(servoPin, GPIO.OUT) # 서보핀 출력으로 설정\n\nservo = GPIO.PWM(servoPin, 50) # 서보핀을 PWM 모드 50Hz로 사용하기 (50Hz > 20ms)\n\nservo.start(0) # 서보 PWM 시작 duty = 0, duty가 0이면 서보는 동작하지 않는다.\n\n\ndef setServoPos(degree):\n # 각도는 180도를 넘을 수 없다.\n\n if degree > 180:\n degree = 180\n\n # 각도(degree)를 duty로 변경한다.\n\n duty = SERVO_MIN_DUTY + (degree * (SERVO_MAX_DUTY - SERVO_MIN_DUTY) / 180.0)\n\n # duty 값 출력\n\n print(\"Degree: {} to {}(Duty)\".format(degree, duty))\n\n # 변경된 duty값을 서보 pwm에 적용\n\n servo.ChangeDutyCycle(duty)\n\n\nmodel = 'models/dnn_face_detector/res10_300x300_ssd_iter_140000_fp16.caffemodel'\n\nconfig = 'models/dnn_face_detector/deploy.prototxt'\n\nimport sys\n\nimport numpy as np\n\nimport cv2\n\nimport face_recognition_predict\n\nmodel = 'models/dnn_face_detector/res10_300x300_ssd_iter_140000_fp16.caffemodel'\n\nconfig = 'models/dnn_face_detector/deploy.prototxt'\n\nface_predict = face_recognition_predict.FaceRecognitionPredict()\n\ncap = cv2.VideoCapture(0)\n\nif not cap.isOpened():\n print('Camera open failed!')\n\n sys.exit()\n\nnet = cv2.dnn.readNet(model, config)\n\nif net.empty():\n print('Net open failed!')\n\n sys.exit()\n\nwhile True:\n\n ret, frame = cap.read()\n\n if not ret:\n break\n\n blob = cv2.dnn.blobFromImage(frame, 1, (300, 300), (104, 177, 123))\n\n net.setInput(blob)\n\n out = net.forward()\n\n detect = out[0, 0, :, :]\n\n (h, w) = frame.shape[:2]\n\n for i in range(detect.shape[0]):\n\n confidence = detect[i, 2]\n\n if confidence < 0.6:\n break\n\n # detect값는 정규화가 되어있어 실제 들어온 영상의 w, h를 곱해야함.\n\n x1 = int(detect[i, 3] * w)\n\n y1 = int(detect[i, 4] * h)\n\n x2 = int(detect[i, 5] * w)\n\n y2 = int(detect[i, 6] * h)\n\n crop = frame[y1:y2, x1:x2]\n\n name, class_probability = face_predict.predict(crop)\n\n cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0))\n\n if class_probability:\n\n label = f'Name: {name} Probability {class_probability:4.2f}'\n\n cv2.putText(frame, label, (x1, y1 - 1), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 1, cv2.LINE_AA)\n\n setServoPos(0)\n\n sleep(1) # 1초 대기\n\n # 90도에 위치\n\n setServoPos(90)\n\n sleep(5)\n\n setServoPos(0)\n\n sleep(1) # 1초 대기\n\n\n\n else:\n\n label = f'wait!!'\n\n cv2.putText(frame, label, (x1, y1 - 1), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 1, cv2.LINE_AA)\n\n cv2.imshow('frame', frame)\n\n if cv2.waitKey(1) == 27:\n break\n\n# 서보 PWM 정지\n\nservo.stop()\n\n# GPIO 모드 초기화\n\nGPIO.cleanup()\n\ncv2.destroyAllWindows()","sub_path":"Face_Recognition/face_recognition_live.py","file_name":"face_recognition_live.py","file_ext":"py","file_size_in_byte":3176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"511036853","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport struct\nfrom enum import Enum, unique\nimport copy\n\nfrom python_c_bytes_trans import StructType\nfrom crc16 import *\n\n@unique\nclass PyType(Enum):\n\n _Normal = \"_normal\"\n _String = \"_string\"\n _Array = \"_array\"\n\nclass SwNormalDataUnit():\n\n def __init__(self, _ctype=None, _pytype=None, size=0, len=0, data=None):\n self._ctype = _ctype\n self._pytype = _pytype\n self.size = size\n self.len = len\n self.data = data\n self.new_data = data\n\n def is_sw_normal(self):\n return self._pytype == PyType._Normal\n\n def is_sw_string(self):\n return self._pytype == PyType._String\n\n def is_sw_array(self):\n return self._pytype == PyType._Array\n\n def _ctype_str(self):\n return self._ctype.value\n\n def _pytype_str(self):\n return self._pytype.value\n\n def encode(self):\n if self.is_sw_normal():\n return struct.pack(self._ctype_str(), self.new_data)\n elif self.is_sw_array(): \n return struct.pack(self._ctype_str()*self.len,\n *(self.new_data + [0]*(self.len - len(self.new_data))))\n elif self.is_sw_string():\n return struct.pack(str(self.size) + self._ctype_str(),\n (self.new_data + '\\0'*(self.size - len(self.new_data))).encode(encoding=\"utf-8\"))\n\n def decode(self, data):\n if self.is_sw_normal():\n self.new_data = struct.unpack(self._ctype_str(), data)[0]\n elif self.is_sw_array(): \n self.new_data = list(struct.unpack(self._ctype_str()*self.len, data))\n elif self.is_sw_string():\n self.new_data = struct.unpack(str(self.size) + self._ctype_str(), data)[0].decode(encoding=\"utf-8\")\n\n def savedata(self):\n self.data = copy.deepcopy(self.new_data)\n\nclass SwMobileUnit(SwNormalDataUnit):\n\n def __init__(self, id=None, _ctype=None, _pytype=None, size=0, len=0, data=None):\n super(SwMobileUnit, self).__init__(_ctype, _pytype, size, len, data)\n self.id = id\n self.id_len = 2\n self.id_ctype = StructType.UShort2\n self.id_pytype = PyType._Normal\n\n self.len_len = 1\n self.len_ctype = StructType.UChar1\n self.len_pytype = PyType._Normal\n\n self.unit_len = self.len_len + self.id_len + self.size\n\n def encode_unit(self):\n unit = bytes()\n unit += struct.pack(self.len_ctype.value, self.unit_len)\n unit += struct.pack(self.id_ctype.value, self.id)\n unit += self.encode()\n return unit\n\n def decode_unit(self, data):\n #self.decode_id(data)\n #self.decode_unit_len(data)\n\n start = self.len_len + self.id_len\n end = self.unit_len\n self.decode(data[start:end])\n\n def decode_id(self, data):\n start = self.len_len\n end = self.len_len + self.id_len\n self.id = struct.unpack(self.id_ctype.value, data[start:end])[0]\n\n def decode_unit_len(self, data):\n start = 0\n end = self.len_len\n self.unit_len = struct.unpack(self.len_ctype.value, data[start:end])[0]\n\n def print_data(self):\n print(\"id = 0x%.4x, size = %-10.d\" % (self.id, self.size), end=' ')\n print(\"data : \", end='')\n print(self.new_data or self.data)\n\nclass SwHeadPacket():\n\n def __init__(self, ap_id=0x03, vp_id=0x01, sttn_id=0x00, dev_id=0x00, pkt_id=0x01, vp_ack=0x80, mcp_id=0x01, cmd_id=0x02, cmd_ack=0xff):\n self.data = {\n 'ap_id' : SwNormalDataUnit(StructType.UChar1, PyType._Normal, 1, 1, ap_id),\n 'vp_id' : SwNormalDataUnit(StructType.UChar1, PyType._Normal, 1, 1, vp_id),\n 'sttn_id' : SwNormalDataUnit(StructType.UInt4, PyType._Normal, 4, 1, sttn_id), #站点编号\n 'dev_id' : SwNormalDataUnit(StructType.UChar1, PyType._Normal, 1, 1, dev_id), #设备编号\n 'pkt_id' : SwNormalDataUnit(StructType.UShort2, PyType._Normal, 2, 1, pkt_id),\n 'vp_ack' : SwNormalDataUnit(StructType.UChar1, PyType._Normal, 1, 1, vp_ack),\n 'mcp_id' : SwNormalDataUnit(StructType.UChar1, PyType._Normal, 1, 1, mcp_id),\n 'cmd_id' : SwNormalDataUnit(StructType.UChar1, PyType._Normal, 1, 1, cmd_id), #设置查询\n 'cmd_ack' : SwNormalDataUnit(StructType.UChar1, PyType._Normal, 1, 1, cmd_ack),\n }\n self.head_len = 13\n\n def packet(self):\n packet = bytes()\n for key in self.data:\n packet += self.data[key].encode()\n return packet\n\n def unpacket(self, data):\n start = 0\n end = 0\n for key in self.data:\n end = start + self.data[key].size\n self.data[key].decode(data[start:end])\n start = end\n self.head_len = end\n\n def print_data(self):\n for key in self.data:\n print(self.data[key].data)\n\nclass SwMobileBytes():\n\n def __init__(self):\n self.trans_bytes = None\n self.origin_bytes = None\n self.valid = True\n\n def get_trans_bytes(self):\n return self.trans_bytes\n\n def get_origin_bytes(self):\n return self.origin_bytes\n\n def del_trans_bytes(self):\n self.trans_bytes = None\n\n def del_origin_bytes(self):\n self.origin_bytes = None\n\n def set_mobile_crc_valid(self):\n crc = sumCrc16(0, self.origin_bytes[:-2])\n self.valid = crc == self.unpacket_crc()\n self.origin_bytes = self.origin_bytes[:-2]\n\n def is_mobile_crc_valid(self):\n return self.valid\n\n def add_head_tail(self):\n self.trans_bytes = b'~' + self.trans_bytes + b'~'\n\n def del_head_tail(self):\n self.origin_bytes = self.origin_bytes.strip(b'~')\n\n def add_crc16(self):\n crc = sumCrc16(0, self.trans_bytes)\n self.trans_bytes += struct.pack(StructType.UShort2.value, crc)\n\n def unpacket_crc(self):\n return struct.unpack(StructType.UShort2.value, self.origin_bytes[-2:])[0]\n\n def trans_pack7e(self):\n self.trans_bytes = self.trans_bytes.replace(b'^', b'^]')\n self.trans_bytes = self.trans_bytes.replace(b'~', b'^}')\n\n def trans_unpack7e(self):\n self.origin_bytes = self.origin_bytes.replace(b'^]', b'^')\n self.origin_bytes = self.origin_bytes.replace(b'^}', b'~')\n\n def transport_bytes(self, data):\n self.trans_bytes = data\n self.add_crc16()\n self.trans_pack7e()\n self.add_head_tail()\n\n def original_bytes(self, data):\n self.origin_bytes = data\n if self.get_valid_bytes() is False:\n return False\n self.del_head_tail()\n self.trans_unpack7e()\n self.set_mobile_crc_valid()\n return self.is_mobile_crc_valid()\n\n def get_valid_bytes(self):\n start = self.origin_bytes.find(b'~')\n #print(\"start = %d\" % start)\n if start == -1:\n return False\n end = self.origin_bytes[start+1:].find(b'~')\n #print(\"end = %d\" % end)\n if end == -1:\n return False\n self.origin_bytes = self.origin_bytes[start:end+2]\n return True\n\nif __name__ == \"__main__\":\n test = SwHeadPacket()\n str1 = test.packet()\n\n unit1 = SwMobileUnit(0xcccc, StructType.sArrayChar_Str, PyType._String, 20, 20, \"test-code\")\n unit2 = SwMobileUnit(0xccc1, StructType.sArrayChar_Str, PyType._String, 6, 6, \"python\")\n unit3 = SwMobileUnit(0xccc2, StructType.UInt4, PyType._Array, 32, 8, [12, 34])\n\n str1 += unit1.encode_unit()\n str1 += unit2.encode_unit()\n str1 += unit3.encode_unit()\n\n m_bytes = SwMobileBytes()\n m_bytes.transport_bytes(str1)\n str1 = m_bytes.get_trans_bytes()\n print(get_valid_bytes(str1))\n m_bytes.del_trans_bytes()\n\n print(\"len = %d\" % len(str1))\n for val in str1:\n print(hex(val), end=' ')\n\n m_bytes.original_bytes(str1)\n print(m_bytes.is_mobile_crc_valid())\n str1 = m_bytes.get_origin_bytes()\n m_bytes.del_origin_bytes()\n\n test2 = SwHeadPacket()\n test2.unpacket(str1)\n test2.print_data()\n\n unit1.decode_unit(str1[test2.head_len:])\n unit1.print_data()\n\n unit2.decode_unit(str1[test2.head_len+unit1.unit_len:])\n unit2.print_data()\n\n unit3.decode_unit(str1[test2.head_len+unit1.unit_len+unit2.unit_len:])\n unit3.print_data()\n\ndef packetHeadCommon():\n head = SwHeadPacket()\n send_bytes = head.packet()\n del head\n return send_bytes\n\ndef packetHeadOfSetCmd():\n pass\n\ndef packetHeadOfGetCmd():\n pass\n","sub_path":"sw_protocol.py","file_name":"sw_protocol.py","file_ext":"py","file_size_in_byte":8426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"374921167","text":"import pandas as pd\nimport math\nimport os\nimport glob\nimport ntpath\nimport numpy as np\n\nbase_path = 'ClassifyDataset/FORGERY/' #FROM FILE PATH\nnew_path = 'FeatureVector/FORGERY/'\t#TO FILE PATH\n\nl = []\nfor root, dirs, files in os.walk(base_path):\n\tfor f in files:\n\t\tl = np.append(l,f)\n\n#axis is important\n\nbase = \"_f_\"\nbase1 = \"\"\nperson = 1\nstringperson = str(person)\ninstance = 1\nstringinstance = str(instance)\nfooter = \".sig\"\nunderscore = \"_\"\n\nwhile (person<116):\n\n\toutstring = []\n\tstringperson = str(person)\n\tstringinstance = str(instance)\n\tif (person<10):\n\t\tbase1 = \"00\"\n\telif (person <100):\n\t\tbase1 = \"0\"\n\telse:\n\t\tbase1 = \"\"\n\tfinal = base1 + stringperson + base + stringinstance + footer\n\tfinalfilestring = base_path + final\n\n\tif (final in l):\n\t\tif (instance == 1):\n\t\t\tfinalfile = np.array([])\n\t\t\tdf = pd.read_csv(finalfilestring,sep=',', header = None, nrows = 1)\n\t\t\ttempfile = np.asarray(df).squeeze() \n\t\t\tfinalfile = np.hstack((finalfile,tempfile))\n\t\t\tdf = \"\"\n\t\t\ttempfile = \"\"\n\t\t\tinstance = instance + 1\n\t\t\tstringinstance = str(instance)\n\t\t\tfinal = base1 + stringperson + base + stringinstance + footer\n\t\t\tfinalfilestring = base_path + final\n\t\tif (instance<6 and instance!=1):\n\t\t\tdf = pd.read_csv(finalfilestring,sep=',', header = None, nrows = 1)\n\t\t\ttempfile = np.asarray(df).squeeze() \n\t\t\tfinalfile = np.vstack((finalfile,tempfile))\n\t\t\tdf = \"\"\n\t\t\ttempfile = \"\"\n\t\t\tprint (person,instance)\n\t\t\tinstance = instance + 1\n\n\telse:\n\t\tif (instance == 6):\n\t\t\t#print (finalfile)\n\t\t\tdf_1 = pd.DataFrame(finalfile)\n\t\t\ttemp2 = str(new_path+final)\n\t\t\tdf_1.to_csv(temp2, index=False, header=None) \n\t\tperson = person + 1\n\t\tinstance = 1","sub_path":"FOR5USERS/AppDataset/4FeatureVector.py","file_name":"4FeatureVector.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"345930785","text":"import west.data_map\nimport west.data_management\nimport west.population\nimport numpy\nimport scipy\n\ndef evaluate_hex_capacity(p = 250, min_radius = 0.05, max_radius = 100, test_repack = False):\n\n areaarray = numpy.logspace(numpy.log(numpy.pi * 0.05 * 0.05)/numpy.log(10), numpy.log(numpy.pi * 100 * 100)/numpy.log(10), 65)\n\n def divide_function(this_value, other_value):\n if this_value == 0 and other_value == 0:\n return 0\n return float(this_value/other_value)\n\n def calculate_tower_area(latitude, longitude, latitude_index, longitude_index, current_value):\n return p / current_value\n\n def find_area_less_than_and_greater_than_towerarea(tower_area):\n for i in range(len(areaarray)):\n if areaarray[i] <= tower_area and areaarray[i + 1] > tower_area:\n if i == len(areaarray) - 1:\n return areaarray[i], None\n return areaarray[i], areaarray[i + 1]\n\n def interpolate(low_value, high_value, low_area, high_area, actual_area):\n low_value_log = numpy.log(low_value)/numpy.log(10)\n high_value_log = numpy.log(high_value)/numpy.log(10)\n actual_value_log = (high_value_log - low_value_log)/(high_area - low_area) * (actual_area - low_area)\n actual_value = scipy.power(10, actual_value_log)\n return actual_value\n\n\n with open (\"noisestrength_hex_data.pkl\", 'r') as f:\n interferencestrengthsdict = pickle.load(f)\n\n with open(\"signalstrength_hex_data.pkl\", 'r') as f:\n signalstrengthsdict = pickle.load(f)\n\n datamap_spec = west.data_management.SpecificationDataMap(west.data_map.DataMap2DContinentalUnitedStates, 400, 600)\n is_in_region_map_spec = west.data_management.SpecificationRegionMap(west.boundary.BoundaryContinentalUnitedStates, datamap_spec)\n is_in_region_map = is_in_region_map_spec.fetch_data()\n population_map_spec = west.data_management.SpecificationPopulationMap(is_in_region_map_spec, west.population.PopulationData)\n population_map = population_map_spec.fetch_data()\n region_area_map_spec = west.data_management.SpecificationRegionAreaMap(datamap_spec)\n region_area_map = region_area_map_spec.fetch_data()\n population_density_map = population_map.combine_datamaps_with_function(region_area_map, divide_function)\n areaoftower_map = west.data_map.DataMap2DContinentalUnitedStates.get_copy_of(population_density_map)\n\n #Note: Keep in mind what will happen if the population density is 0.\n areaoftower_map.update_all_values_via_function(calculate_tower_area)\n min_area = numpy.pi * min_radius * min_radius\n max_area = numpy.pi * max_radius * max_radius\n\n def clip_map(latitude, longitude, latitude_index, longitude_index, current_value):\n if current_value > max_area:\n return max_area\n if current_value < min_area:\n return min_area\n return current_value\n\n\n areaoftower_map.update_all_values_via_function(clip_map)\n\n channel_list = range(2, 52)\n channel_list.remove(37)\n\n if test_repack:\n exclusionfilename = \"15VHFFreeUSMinimumStationstoRemove0_allchannels.pcl\"\n noisefilename = \"noise_map_test_repack_withsubmaps.pcl\"\n else:\n exclusionfilename = \"original_map_fcccontours_withplmrs_allchannels.pcl\"\n noisefilename = \"noise_map_test_original_allocation_withsubmaps.pcl\"\n\n\n exclusion_map_3D = west.data_map.DataMap3D.from_pickle(exclusionfilename)\n noise_map_3D = west.data_map.DataMap3D.from_pickle(os.path.join(\"data\", \"Noise Maps\", noisefilename))\n\n\n fair_capacity_hex_map_3D = west.data_map.DataMap3D.from_DataMap2D(is_in_region_map, channel_list)\n avg_capacity_hex_map_3D = west.data_map.DataMap3D.from_DataMap2D(is_in_region_map, channel_list)\n min_capacity_hex_map_3D = west.data_map.DataMap3D.from_DataMap2D(is_in_region_map, channel_list)\n\n for c in channel_list:\n faircapacity_channelmap = fair_capacity_hex_map_3D.get_layer(c)\n avgcapacity_channelmap = avg_capacity_hex_map_3D.get_layer(c)\n mincapacity_channelmap = min_capacity_hex_map_3D.get_layer(c)\n for i in range(400):\n for j in range(600):\n if is_in_region_map.get_value_by_index(i, j) == 0:\n continue\n tower_area = areaoftower_map.get_value_by_index(i, j)\n low_area, high_area = find_area_less_than_and_greater_than_towerarea(tower_area)\n if high_area == None:\n high_area = areaarray[len(areaarray) - 1]\n low_signal = signalstrengthsdict[c][low_area]\n high_signal = signalstrengthsdict[c][high_area]\n low_interference = interferencestrengthsdict[c][low_area]\n high_interference = interferencestrengthsdict[c][high_area]\n\n signal = interpolate(low_signal, high_signal, low_area, high_area, tower_area)\n interference = interpolate(low_interference, high_interference, low_area, high_area, tower_area)\n total_noise = interference + noise_map_3D.get_layer(c).get_value_by_index(i, j)\n potential_capacity = exclusion_map_3D.get_layer(c).get_value_by_index(i, j) * 6e6 * numpy.log(1 + signal/total_noise)\n\n #Fair capacity: If each person is allowed to use the same rate, what would this rate be?\n fair_capacity_per_person = 1/sum(1/potential_capacity)\n\n total_fair_capacity = fair_capacity_per_person * p\n faircapacity_channelmap.set_value_by_index(i, j, total_fair_capacity)\n\n #Avg capacity\n avg_capacity = numpy.mean(potential_capacity)\n avgcapacity_channelmap.set_value_by_index(i, j, avg_capacity)\n\n #Min capacity\n min_capacity = min(potential_capacity)\n mincapacity_channelmap.set_value_by_index(i, j, min_capacity)\n\n fair_capacity_hex_map = fair_capacity_hex_map_3D.sum_all_layers()\n avg_capacity_hex_map = avg_capacity_hex_map_3D.sum_all_layers()\n min_capacity_hex_map = min_capacity_hex_map_3D.sum_all_layers()\n\n return fair_capacity_hex_map, avg_capacity_hex_map, min_capacity_hex_map\n\n\nfaircapacityhexmap, avgcapacityhexmap, mincapacityhexmap = evaluate_hex_capacity()\n\nfaircapacityhexmap.to_pickle(os.path.join(\"data\", \"Data Rate Maps\", \"hex_fair_capacity_original_allocation.pcl\"))\navgcapacityhexmap.to_pickle(os.path.join(\"data\", \"Data Rate Maps\", \"hex_avg_capacity_original_allocation.pcl\"))\nmincapacityhexmap.to_pickle(os.path.join(\"data\", \"Data Rate Maps\", \"hex_min_capacity_original_allocation.pcl\"))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"evaluate_hex_capacity.py","file_name":"evaluate_hex_capacity.py","file_ext":"py","file_size_in_byte":6651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"323520489","text":"# -*- coding: utf-8 -*-\n#!/usr/bin/python\n\n# Item 64 Drill version: A\n# Python2.7.14 -- TCLTK 8.5.18 -- macOS 10.12.6 (Sierra)/darwin\n# Glantz, 02Nov017\n# Drill: Daily new or modified file transfer (copied, not moved)\n\n\nimport shutil, os, time\n\n\ndef main():\n makinRain()\n\n\ndef makinRain():\n source = '/Users/sandy/Desktop/FolderA/'\n destination = '/Users/sandy/Desktop/FolderB/'\n listfile = os.listdir(source)\n # added round for humans and to conserve memory\n last24 = round(time.time()) - 86400\n \n print (\"These files were moved: \")\n for files in listfile:\n SourceFile = os.path.join(source,files)\n mod = os.path.getmtime(SourceFile)\n if mod > last24 and not files.endswith(\".DS_Store\"):\n # .DS_Store are (invisible) files in Mac folders*\n shutil.copy(SourceFile,destination)\n print (files)\n\n\nif __name__=='__main__':\n main()\n\n\n\n","sub_path":"Py/classExercises/Py2Item64drill_A.py","file_name":"Py2Item64drill_A.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"601668753","text":"\"\"\"\nStarted during the summer period in 2014\n@author: Mustafa Erkan Basar\n\nThis script demostrates how event detection and time-to-event estimation can be applied on social media in the context of ADNEXT, INFITI, COMMIT project.\n\nThe event detection is a result of the research done by Florian Kunneman.\n\nThe time-to-event estimation module developed by Ali Hürriyetoglu.\n\nThe Program flow is as follows:\n 1- Connect to MongoDB (MangoLab)\n 2- Retrieve tweets from twiqs.nl every hour.\n 3- Call the event detection.\n 4- Clear the former results from the database.\n 5- Run the time-to-event estimation module.\n 6- Write the new results to database, after each time-to-event estimation. \n\n\nTrouble Shooting:\n - The url for twiqs.nl may change from time to time.\n - Twiqs.nl may not provide tweets in time. Therefore this particular hour will not be taken into account.\n\n\"\"\"\n\nimport configparser\n\nimport requests\nimport random\n\nimport time\nfrom datetime import date, datetime, timedelta\n\nimport pymongo\n\nimport DEvents.event_pairs as event_pairs\n\n\n#Get all the private configurations;\nconfig = configparser.ConfigParser()\nconfig.read('/home/ebasar/oauth.ini')\n\n#MongoLab OAuth;\nclient_host = config.get('LE_script_db', 'client_host')\nclient_port = int(config.get('LE_script_db', 'client_port'))\ndb_name = config.get('LE_script_db', 'db_name')\nuser_name = config.get('LE_script_db', 'user_name')\npasswd = config.get('LE_script_db', 'passwd')\n\n#Twiqs OAuth;\nuser_name2 = config.get('LE_script_twiqs', 'user_name')\npasswd2 = config.get('LE_script_twiqs', 'passwd')\n\n\n#!IDEA! = Add try-except block for the connection part;\n#MongoLab Connection;\nconnection = pymongo.MongoClient(client_host, client_port)\nledb = connection[db_name] #Database\nledb.authenticate(user_name, passwd)\nlecl = ledb.lecl #Collection\nprint(\"Connected to DB\")\n\n\nep = event_pairs.Event_pairs(\"all\",\"coco_out/\",\"tmp/\")\nprint(\"Event Detection Initialised\")\n\n\n#Get the cookie for twiqs.nl;\ns = requests.Session()\nr = s.post(\"http://145.100.57.182/cgi-bin/twitter\", data={\"NAME\":user_name2, \"PASSWD\":passwd2})\n\n\n#!IDEA! = Argparser can be used to get system parameters;\n#Twiqs.nl parameters;\npayload = {'SEARCH': 'echtalles', 'DATE': 'yyyymmddhh-yyyymmddhh', 'DOWNLOAD':True, 'SHOWTWEETS':True}\n#DATE = --> start and end should point to the same hour in order to get tweets about an hour\n\n\ndef RequestTweets():\n\t\"\"\"\n\tFetches the tweets from twiqs.nl\n\tWarning = The url may need to be updated from time to time!\n\t\"\"\"\n\toutput1st = requests.get(\"http://145.100.57.182/cgi-bin/twitter\", params=payload, cookies=s.cookies)\n\treturn output1st\n\n\n#If True, don't contain details of tweets except ids and users. Also don't contain the keyterms of events after keeping them in keylist.\nDeleteTweetDetails = True\n\n#If True, delete the former events from mongo db.\nDeleteFormerEvents = True\n\nwhile True:\n\ttime.sleep(120) #Check every two minutes if you are in the next hour.\n\n\t#Time Calculations;\n\tnowDate = datetime.now()\n\tnowDate_earlier = nowDate - timedelta(hours=1) #Get the previous hour. Because you can get tweets for the last hour from twiqs.nl.\n\ttweethour = nowDate_earlier.strftime(\"%H:00 %d-%m-%Y\") #Just for showing off the hour which tweets requested.\n\tnes = nowDate_earlier.strftime(\"%Y%m%d%H\") #'yyyymmddhh' twiqs.nl format.\n\tpDate = nes+'-'+nes #Twiqs.nl needs this format. Start and end time should be the same to retrieve tweets for one hour.\n\tcurrTime = nowDate.strftime(\"%H:%M\") #Just for showing off the minutes while waiting for the next hour.\n\n\t#Check if we are still in the same hour:\n\tif payload['DATE'] == pDate: #Continue waiting if you are in the same hour. Otherwise process the next hour.\n\t\tprint(currTime)\n\t\tcontinue\n\telse:\n\t\tpayload['DATE'] = pDate #It will remain the same until next hour.\n\t\tprint(\"Tweet hour : \" + tweethour)\n\n\t\t#Request to Twiqs;\n\t\toutput = RequestTweets()\n\t\tprint(\"Request Completed\")\n\n\t\t#Check the cookie;\n\t\twithoutcookie = '#user_id\\t#tweet_id\\t#DATE='+pDate+'\\t#SEARCHTOKEN=echtalles\\n'\n\t\tif output.text[:70] == withoutcookie: #if the cookie doesn't have access right to download the tweets, it will skip this hour.\n\t\t\tprint(\"Cookie is wrong. I'll skip tweets at \" + tweethour + \"You have to check your cookie configuration!\")\n\t\t\t#!IDEA! = If the cookie is wrong, write the code(call the relevant method) for getting a new one here.\n\t\t\tcontinue\n\t\telse:\n\t\t\tprint(\"Cookie is Fine.\")\n\n\t\t#Check the result of request;\n\t\tdumpoutput = '#user_id\\t#tweet_id\\t#date\\t#time\\t#reply_to_tweet_id\\t#retweet_to_tweet_id\\t#user_name\\t#tweet\\t#DATE='+pDate+'\\t#SEARCHTOKEN=echtalles\\n'\n\t\tif output.text[:1000] == dumpoutput: #If there isn't any tweet try the request again.\n\t\t\tprint(\"No tweet found at the first time! I'll try again\")\n\t\t\ttime.sleep(300)\n\t\t\toutput = RequestTweets()\n\t\t\tif output.text[:1000] == dumpoutput: #If there isn't any tweet again, it will skip this hour.\n\t\t\t\tprint(\"Still there is not any tweet! I'll skip tweets at \" + tweethour)\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tprint(\"Tweets came at the second time\")\n\t\telse:\n\t\t\tprint(\"Tweets are O.K.\")\n\n\t\t#Event Detection; (refer to Florian Kunneman for any issue)\n\t\tEventDic = ep.detect_events(output.text[:-1]) # [:-1] = ignoring the last '\\n' at the bottom of the file.\n\t\tprint(\"Event Detection Completed\")\n\n\t\tif DeleteFormerEvents:\n\t\t\tlecl.remove({ }) #Delete the old events from database\n\t\t\tprint(\"Former events are deleted from the database\")\n\n\t\tfor k,v in EventDic.items(): #For every detected event\n\n\t\t\t#TimeToEventEstimation Calculations;\n\t\t\tcreateDate = datetime.now() #TTE Estimation will be added to the current time\n\t\t\trandomTTE = random.uniform(0.0, 193.0) #random number for estimation (for now)\n\t\t\thh, premm = divmod(randomTTE, 1)\n\t\t\tmm = (60*premm)*0.1\n\t\t\tv['Estimation'] = createDate + timedelta(hours=int(hh), minutes=int(mm))\n\n\t\t\t#Convert date formats to datetime format;\n\t\t\tv['date'] = datetime.combine(v['date'], datetime.min.time())\n\n\t\t\t#Writing keyterms in a list without keyterm scores; (In django using this list is more efficient)\n\t\t\tv['keylist'] = []\n\t\t\tfor m in v['keyterms']:\n\t\t\t\tmt = m[0].title() #capitalization\n\t\t\t\tv['keylist'].append(mt)\n\n\t\t\tif DeleteTweetDetails:\n\t\t\t\tdel v['keyterms']\n\t\t\t\tfor i in v['tweets']:\n\t\t\t\t\tdel i['date'], i['date references'], i['text'], i['entities']\n\t\t\telse:\n\t\t\t\t#If you don't delete details; convert date formats to datetime format;\n\t\t\t\tfor i in v['tweets']:\n\t\t\t\t\ti['date'] = datetime.combine(i['date'], datetime.min.time())\n\n\t\t\t#Write to database event by event;\n\t\t\tlecl.insert(v) \n\t\tprint(\"Written to Database\")\n\n\t\tcontinue\n\n\n","sub_path":"LamaEvents.py","file_name":"LamaEvents.py","file_ext":"py","file_size_in_byte":6555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"180591782","text":"#threading to run multiple programs\n\nimport threading, time\n\nprint('Start of program')\n\ndef takeANap():\n\ttime.sleep(5)\n\tprint('Wake up!')\n\t\n\t\n#create a thread object\nthreadObj = threading.Thread(target=takeANap)\n\n#starts the thread with the takeANap function\nthreadObj.start()\n\n\nprint('End of program')\n\n\n\n\n\n\n\n","sub_path":"AutomateEasyStuff/Time/multithreading2.py","file_name":"multithreading2.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"373078498","text":"import glob\nimport os\n\nimport numpy as np\nimport pyasdf\nfrom obspy.io.sac.sactrace import SACTrace\n\n\"\"\"\nthis script outputs the stacked cross-correlation functions into SAC traces\n\nadd an option to output the CCFs into csv files for image transform analysis\n\"\"\"\n\n# ------absolute path to output data-------\nSTACKDIR = \"/Users/chengxin/Documents/SCAL/STACK\"\nALLFILES = glob.glob(os.path.join(STACKDIR, \"*/*.h5\"))\nCOMP_OUT = [\"ZZ\", \"RR\", \"TT\"]\n# COMP_OUT = ['ZR','ZT','ZZ','TR','TT','TZ','RR','RT','RZ']\n# COMP_OUT = ['EE','EN','EZ','NE','NN','NZ','ZE','ZN','ZZ']\ndtype = \"Allstack_linear\"\n\n# ---output file format-----\nout_SAC = True\nout_CSV = False\n\nif (not out_SAC) and (not out_CSV):\n raise ValueError(\"out_SAC and out_CSV cannot be False at the same time\")\n\nnfiles = len(ALLFILES)\nif not os.path.isdir(os.path.join(STACKDIR, \"STACK_SAC\")):\n os.mkdir(os.path.join(STACKDIR, \"STACK_SAC\"))\n\n# ----loop through station pairs----\nfor ii in range(nfiles):\n with pyasdf.ASDFDataSet(ALLFILES[ii], mode=\"r\") as ds:\n # -----get station info from file name-----\n fname = ALLFILES[ii].split(\"/\")[-1].split(\"_\")\n staS = fname[0].split(\".\")[1]\n netS = fname[0].split(\".\")[0]\n staR = fname[1].split(\".\")[1]\n netR = fname[1].split(\".\")[0]\n\n # -----read data information-------\n slist = ds.auxiliary_data.list()\n rlist = ds.auxiliary_data[slist[0]].list()\n maxlag = ds.auxiliary_data[slist[0]][rlist[0]].parameters[\"maxlag\"]\n dt = ds.auxiliary_data[slist[0]][rlist[0]].parameters[\"dt\"]\n slat = ds.auxiliary_data[slist[0]][rlist[0]].parameters[\"latS\"]\n slon = ds.auxiliary_data[slist[0]][rlist[0]].parameters[\"lonS\"]\n rlat = ds.auxiliary_data[slist[0]][rlist[0]].parameters[\"latR\"]\n rlon = ds.auxiliary_data[slist[0]][rlist[0]].parameters[\"lonR\"]\n\n # ----make sure data exists------\n if dtype in slist:\n for icomp in range(len(COMP_OUT)):\n comp = COMP_OUT[icomp]\n\n if comp in rlist:\n if out_SAC:\n # --------read the correlations---------\n corr = ds.auxiliary_data[dtype][comp].data[:]\n temp = netS + \".\" + staS + \"_\" + netR + \".\" + staR + \"_\" + comp + \".SAC\"\n\n # -------check whether folder exists-------\n if not os.path.isdir(os.path.join(STACKDIR, \"STACK_SAC/\" + netS + \".\" + staS)):\n os.mkdir(os.path.join(STACKDIR, \"STACK_SAC/\" + netS + \".\" + staS))\n filename = os.path.join(STACKDIR, \"STACK_SAC/\" + netS + \".\" + staS, temp)\n\n # --------write into SAF format----------\n sac = SACTrace(\n nzyear=2000,\n nzjday=1,\n nzhour=0,\n nzmin=0,\n nzsec=0,\n nzmsec=0,\n b=-maxlag,\n delta=dt,\n stla=rlat,\n stlo=rlon,\n evla=slat,\n evlo=slon,\n data=corr,\n )\n sac.write(filename, byteorder=\"big\")\n\n if out_CSV:\n # -----------output name and read data-------------\n temp = netS + \".\" + staS + \"_\" + netR + \".\" + staR + \"_\" + comp + \".dat\"\n if not os.path.isdir(os.path.join(STACKDIR, \"STACK_DAT\")):\n os.mkdir(os.path.join(STACKDIR, \"STACK_DAT\"))\n filename = os.path.join(STACKDIR, \"STACK_DAT\", temp)\n corr = ds.auxiliary_data[dtype][comp].data[:]\n\n # -------make an array for output-------\n npts = len(corr)\n indx = npts // 2\n data = np.zeros((3, indx + 2), dtype=np.float32)\n data[0, 0] = slon\n data[1, 0] = slat\n data[2, 0] = 0\n data[0, 1] = rlon\n data[1, 1] = rlat\n data[2, 1] = 0\n tt = 0\n for jj in range(indx):\n data[0, 2 + jj] = tt\n data[1, 2 + jj] = corr[indx + jj]\n data[2, 2 + jj] = corr[indx - jj]\n tt = tt + dt\n\n np.savetxt(filename + \".csv\", np.transpose(data), delimiter=\",\")\n","sub_path":"src/noisepy/seis/application_modules/write_sac.py","file_name":"write_sac.py","file_ext":"py","file_size_in_byte":4721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"552693492","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# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an AS IS BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Library defining different types of validation errors.\"\"\"\nimport copy\nimport operator\n\nMAX_RANK = 1000000000 # A big number, but not so big it breaks sorting\nMISSING_PARENT_VALIDATION_RANK = 60\n\n\ndef MakeFieldString(field):\n \"\"\"Represents OptWrapper as a string prepending '(opt)' for optional fields.\n\n Args:\n field: an OptWrapper for a field\n\n Returns:\n a string representation of the field\n \"\"\"\n field_str = ''\n if field.optional:\n field_str += '(opt) '\n field_str += '{0}/{1}{2}'.format(field.field.namespace, field.field.field,\n field.field.increment)\n return field_str\n\n\ndef _SortFindings(findings):\n return sorted(\n findings,\n key=operator.attrgetter('type_rank', 'category_rank', 'inner_rank',\n 'is_slave'))\n\n\ndef _DedupFindings(findings):\n finding_map = {}\n for finding in findings:\n if finding in finding_map:\n # Note: equality for map key != equality of finding contents\n # As a result, key and value are not interchangeable\n finding = _SortFindings([finding, finding_map.get(finding)])[0]\n finding_map[finding] = finding\n return finding_map.values()\n\n\n# ---------------------------------------------------------------------------- #\n# Base classes for findings.\n# ---------------------------------------------------------------------------- #\nclass FileContext(object):\n \"\"\"Wrapper class to store file-related information.\n\n Args:\n filepath: string. relative path to the file with the issue.\n begin_line_number: optional int. Starting line number for the issue.\n end_line_number: optional int. Ending line number for the issue.\n \"\"\"\n\n def __init__(self, filepath, begin_line_number=None, end_line_number=None):\n self.begin_line_number = begin_line_number\n self.end_line_number = end_line_number\n self.raw_filepath = filepath\n self.filepath = filepath\n\n def GetLineInfo(self):\n \"\"\"Returns string containing the line number information.\n\n If no line number info, returns empty string.\n \"\"\"\n if self.begin_line_number and self.end_line_number:\n return '(Lines {0} - {1})'.format(self.begin_line_number,\n self.end_line_number)\n if self.begin_line_number:\n return '(Line {0})'.format(self.begin_line_number)\n\n return ''\n\n\nclass Finding(object):\n \"\"\"Virtual class for findings.\n\n Args:\n message: string. the message associated with the finding.\n file_context: FileContext with file context info. Can be None.\n type_rank: first sort rank based on top level subclass (warning or error)\n category_rank: second sort rank based on the category of warning or error\n inner_rank: third sort rank based on ordering within category\n equality_key: object used to determine if this finding is a duplicate of\n another one. Provide the same object to all the findings that should be\n considered equivalent. If left blank, default object equality is used.\n is_master: set true if this finding should be the retained instance in the\n case of duplication. Only one finding should be the master in a set.\n Defaults to false.\n \"\"\"\n\n def __init__(self,\n message,\n file_context,\n type_rank=MAX_RANK,\n category_rank=MAX_RANK,\n inner_rank=MAX_RANK,\n equality_key=None,\n is_master=False):\n super(Finding, self).__init__()\n\n if not isinstance(message, str):\n raise TypeError('Argument {0} is not a string'.format(message))\n if file_context is not None:\n if not isinstance(file_context, FileContext):\n raise TypeError(\n 'Argument {0} is not a FileContext object.'.format(file_context))\n\n self.message = message\n self.file_context = file_context\n self.type_rank = type_rank\n self.inner_rank = inner_rank\n self.category_rank = category_rank\n self.equality_key = equality_key\n self.is_master = is_master\n self.is_slave = not is_master\n\n def __eq__(self, other):\n if isinstance(other, Finding):\n if self.equality_key is not None:\n return self.equality_key == other.equality_key\n return id(self) == id(other)\n return False\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __hash__(self):\n if self.equality_key is not None:\n return self.equality_key.__hash__()\n return hash(self.__repr__())\n\n def __str__(self):\n return self.message\n\n\nclass Findings(object):\n \"\"\"Base class for validators to keep track of findings.\"\"\"\n\n def __init__(self):\n self._findings_list = []\n self._is_changed = False\n\n def _GetDynamicFindings(self, filter_old_warnings):\n \"\"\"Override this to include additional findings not in self._findings_list.\n\n Does nothing by default. Override this method to add findings from\n subclasses for analysis without modifying _self._findings_list.\n\n Args:\n filter_old_warnings: Set True to filter warnings in unchanged components.\n\n Returns:\n A list of findings defined by the child class\n \"\"\"\n # delete unused argument to thwart linter\n del filter_old_warnings\n return []\n\n def AddFindings(self, findings):\n \"\"\"Add an error to errors_list.\n\n Args:\n findings: required list of Finding objects.\n\n Raises:\n TypeError: a finding is not a member of the Finding base class.\n \"\"\"\n for finding in findings:\n self.AddFinding(finding)\n\n def AddFinding(self, finding):\n \"\"\"Add an error to errors_list.\n\n Args:\n finding: Finding object.\n\n Raises:\n TypeError: error is not a member of the Finding base class.\n \"\"\"\n if not isinstance(finding, Finding):\n raise TypeError('Argument \"{0}\" is not an instance of the base classes '\n 'ValidationError or ValidationWarning.'.format(finding))\n\n self._findings_list.append(finding)\n\n def GetFindings(self, filter_old_warnings=False):\n \"\"\"Get findings found under this object.\n\n Args:\n filter_old_warnings: Set True to filter warnings on unchanged components.\n\n Returns:\n A list of findings for this object and its children\n \"\"\"\n dynamic_findings = self._GetDynamicFindings(filter_old_warnings)\n if not filter_old_warnings:\n return list(_DedupFindings(self._findings_list + dynamic_findings))\n\n filtered_findings = copy.copy(dynamic_findings)\n for finding in self._findings_list:\n if self._is_changed or not isinstance(finding, ValidationWarning):\n filtered_findings.append(finding)\n return _SortFindings(_DedupFindings(filtered_findings))\n\n def HasFindingTypes(self, finding_types):\n \"\"\"Returns true if any finding is one of the types in findings_types.\n\n Args:\n finding_types: list of types of findings.\n \"\"\"\n for finding in self.GetFindings():\n if isinstance(finding, tuple(finding_types)):\n return True\n return False\n\n def IsValid(self):\n \"\"\"Returns true if there are no actionable errors in _findings_list.\"\"\"\n for finding in self.GetFindings():\n if isinstance(finding, ValidationError):\n return False\n return True\n\n def SetChanged(self):\n \"\"\"Marks this object as containing a change in the latest cl.\"\"\"\n self._is_changed = True\n\n def IsChanged(self):\n \"\"\"Returns True if this object contains a change in the latest cl.\"\"\"\n return self._is_changed\n\n\nclass FindingsUniverse(Findings):\n \"\"\"Base class for universes of ontology items.\n\n Args:\n folders: list of ConfigFolder objects parsed from field files.\n Attributes:\n folders: list of ConfigFolder objects parsed from field files. Each\n universe corresponds to a particular type of ontology item.\n \"\"\"\n\n def __init__(self, folders):\n super(FindingsUniverse, self).__init__()\n self.folders = folders\n self._namespace_map = self._MakeNamespaceMap(\n [folder.local_namespace for folder in folders])\n\n def _MakeNamespaceMap(self, namespaces):\n \"\"\"Returns mapping from namespace strings to sets of valid ontology entities.\n\n Args:\n namespaces: list of namespace objects.\n \"\"\"\n return {ns.namespace: self._GetNamespaceMapValue(ns) for ns in namespaces}\n\n def _GetNamespaceMapValue(self, namespace):\n \"\"\"Override in the subclass to define how values in the namespace map are populated.\"\"\"\n # Delete the unused parameter so the linter doesn't complain.\n del namespace\n return []\n\n def _GetDynamicFindings(self, filter_old_warnings):\n findings = []\n for folder in self.folders:\n findings += folder.GetFindings(filter_old_warnings)\n return findings\n\n\n# ---------------------------------------------------------------------------- #\n# Base classes for types of findings.\n# ---------------------------------------------------------------------------- #\nclass ValidationError(Finding):\n \"\"\"Virtual class for blocking errors.\"\"\"\n\n def __init__(self,\n message,\n file_context,\n category_rank=MAX_RANK,\n inner_rank=MAX_RANK):\n error_info = 'ERROR '\n if file_context is not None:\n error_info += file_context.GetLineInfo()\n super(ValidationError,\n self).__init__('{0}: {1}\\n'.format(error_info, message), file_context,\n 1, category_rank, inner_rank)\n\n\nclass ValidationWarning(Finding):\n \"\"\"Virtual class for all non-blocking warnings.\"\"\"\n\n def __init__(self,\n message,\n file_context,\n category_rank=MAX_RANK,\n inner_rank=MAX_RANK,\n equality_key=None,\n is_master=False):\n warning_info = 'Warning '\n if file_context is not None:\n warning_info += file_context.GetLineInfo()\n super(ValidationWarning,\n self).__init__('{0}: {1}\\n'.format(warning_info,\n message), file_context, 2,\n category_rank, inner_rank, equality_key, is_master)\n\n\n# TODO(berkoben): After migrating to yaml, need to add more context to locate\n# errors, because line number info will be lost.\n\n\n# ---------------------------------------------------------------------------- #\n# Errors relating to files.\n# ---------------------------------------------------------------------------- #\nclass InconsistentFileLocationError(ValidationError):\n \"\"\"File not located within a subfolder inside resources.\"\"\"\n\n def __init__(self, expected_path, file_context):\n fp = file_context.filepath\n super(InconsistentFileLocationError, self).__init__(\n 'File \"{0}\" does not match expected \"{1}\".'.format(fp, expected_path),\n file_context)\n\n\n# ---------------------------------------------------------------------------- #\n# Errors relating to config text (typos)\n# ---------------------------------------------------------------------------- #\nclass BadKeyError(ValidationError):\n \"\"\"Config contains an invalid key.\"\"\"\n\n def __init__(self, key, context):\n super(BadKeyError, self).__init__('\"{0}\" is an illegal key'.format(key),\n context)\n\n\nclass DuplicateKeyError(ValidationError):\n \"\"\"Config contains two identical keys.\"\"\"\n\n def __init__(self, key, context):\n super(DuplicateKeyError,\n self).__init__('\"{0}\" key seen multiple times in file'.format(key),\n context)\n\n\nclass IllegalKeyTypeError(ValidationError):\n \"\"\"Config contains a key of an invalid non-string type.\"\"\"\n\n def __init__(self, key, context):\n super(IllegalKeyTypeError,\n self).__init__('\"{0}\" is a non-string key'.format(key), context)\n\n\nclass IllegalCharacterError(ValidationError):\n \"\"\"File Contains non-alphanumeric characters.\"\"\"\n\n def __init__(self, illegal_text, context):\n super(IllegalCharacterError, self).__init__(\n '\"{0}\" contains non-alphanumeric characters'.format(illegal_text),\n context)\n\n\nclass CapitalizationError(ValidationError):\n \"\"\"Content has incorrect capitalization.\"\"\"\n\n def __init__(self, bad_text, context):\n super(CapitalizationError,\n self).__init__('\"{0}\" is capitalized incorrectly'.format(bad_text),\n context)\n\n\nclass UnrecognizedFormatError(ValidationError):\n \"\"\"Validator does not know how to read content.\"\"\"\n\n def __init__(self, content, context):\n super(UnrecognizedFormatError, self).__init__(\n 'Block has unrecognized format: {0}'.format(str(content)), context)\n\n\nclass EmptyBlockWarning(ValidationWarning):\n \"\"\"Validator does not know how to read content.\"\"\"\n\n def __init__(self, content, context):\n super(EmptyBlockWarning,\n self).__init__('Block has no content: {0}'.format(str(content)),\n context)\n\n\nclass EmptyFileWarning(ValidationWarning):\n \"\"\"Validator found an empty YAML file.\"\"\"\n\n def __init__(self, context):\n super(EmptyFileWarning,\n self).__init__('No YAML documents were found in the file.', context)\n\n\n# ---------------------------------------------------------------------------- #\n# Errors relating to Fields.\n# ---------------------------------------------------------------------------- #\nclass DuplicateSubfieldError(ValidationError):\n \"\"\"Field has more than one identical subfield.\"\"\"\n\n def __init__(self, duplicated_subfield, field):\n super(DuplicateSubfieldError, self).__init__(\n '\"{0}\" appears more than once in \"{1}\"'.format(duplicated_subfield,\n field.name),\n field.context)\n\n\nclass MissingSubfieldError(ValidationError):\n \"\"\"A subfield in this field is not defined.\"\"\"\n\n def __init__(self, subfield, field):\n super(MissingSubfieldError, self).__init__(\n 'Subfield \"{0}\" in field \"{1}\" is not defined'.format(\n subfield, field.name), field.context)\n\n\nclass InvalidFieldConstructionError(ValidationError):\n \"\"\"One or more subfield in this field is in the wrong location / order.\"\"\"\n\n def __init__(self, field):\n super(InvalidFieldConstructionError, self).__init__(\n 'Field \"{0}\" is not a valid construction'.format(field.name),\n field.context)\n\n\nclass DuplicateFieldDefinitionError(ValidationError):\n \"\"\"Field is defined multiple times in a namespace.\"\"\"\n\n def __init__(self, prevInstance, currentInstance):\n field = prevInstance.name\n file1 = ''\n file2 = ''\n if prevInstance.context is not None:\n file1 = prevInstance.context.filepath\n if currentInstance.context is not None:\n file2 = currentInstance.context.filepath\n super(DuplicateFieldDefinitionError, self).__init__(\n '\"{0}\" defined in \"{1}\" and \"{2}\"'.format(field, file1, file2),\n currentInstance.context)\n\n\nclass InvalidFieldFormatError(ValidationError):\n \"\"\"The field's YAML specification is invalid.\n\n The complete YAML specification of a field and its properties does not have\n proper formatting and couldn't be parsed.\n \"\"\"\n\n def __init__(self, content, context):\n super(InvalidFieldFormatError, self).__init__(\n 'Block has a field with an invalid format: {0}'.format(str(content)),\n context)\n\n\nclass InvalidStateFormatError(ValidationError):\n \"\"\"A state string in a field's state list does not have proper formatting.\"\"\"\n\n def __init__(self, state, field):\n super(InvalidStateFormatError, self).__init__(\n 'State \"{0}\" in list for field \"{1}\" has an invalid format.'.format(\n state, field.name), field.context)\n\n\nclass DuplicateStateError(ValidationError):\n \"\"\"A state appears multiple times in a field's state list.\"\"\"\n\n def __init__(self, state_name, field):\n super(DuplicateStateError, self).__init__(\n 'State name \"{0}\" appears multiple times in list for field \"{1}\".'\n .format(state_name, field.name), field.context)\n\n\nclass MissingStateError(ValidationError):\n \"\"\"A state in a field's state list is not defined.\"\"\"\n\n def __init__(self, state, field):\n super(MissingStateError, self).__init__(\n 'State \"{0}\" in list for field \"{1}\" is not defined.'.format(\n state, field.name), field.context)\n\n\n# ---------------------------------------------------------------------------- #\n# Errors relating to Subfields.\n# ---------------------------------------------------------------------------- #\nclass DuplicateSubfieldDefinitionError(ValidationError):\n \"\"\"Subfield is defined multiple times in a namespace.\"\"\"\n\n def __init__(self, currentInstance, namespace):\n subfield = currentInstance.name\n super(DuplicateSubfieldDefinitionError, self).__init__(\n '\"{0}\" defined more than once in \"{1}\"'.format(subfield, namespace),\n currentInstance.context)\n\n\n# TODO(berkoben) merge this with missingdescriptionwarning\nclass MissingSubfieldDescriptionWarning(ValidationWarning):\n \"\"\"Subfield does not have a non-empty description.\"\"\"\n\n def __init__(self, subfield_name, context):\n super(\n MissingSubfieldDescriptionWarning,\n self,\n ).__init__('\"{0}\" is missing a description'.format(subfield_name), context,\n 10)\n\n\nclass MissingUnitError(ValidationError):\n \"\"\"Measurement subfield has no corresponding unit definitions.\"\"\"\n\n def __init__(self, subfield):\n super(MissingUnitError, self).__init__(\n 'Measurement subfield \"{0}\" has no corresponding unit definitions in the same namespace'\n .format(subfield.name), subfield.context)\n\n\n# ---------------------------------------------------------------------------- #\n# Errors relating to States.\n# ---------------------------------------------------------------------------- #\nclass DuplicateStateDefinitionError(ValidationError):\n \"\"\"A state is defined multiple times in a namespace.\"\"\"\n\n def __init__(self, state, namespace):\n super(DuplicateStateDefinitionError, self).__init__(\n '\"{0}\" defined more than once in \"{1}\"'.format(state.name, namespace),\n state.context)\n\n\nclass MissingStateDescriptionWarning(ValidationWarning):\n \"\"\"A state is missing a description.\"\"\"\n\n def __init__(self, state):\n super(MissingStateDescriptionWarning,\n self).__init__('\"{0}\" is missing a description'.format(state.name),\n state.context, 10)\n\n\n# ---------------------------------------------------------------------------- #\n# Errors relating to Units.\n# ---------------------------------------------------------------------------- #\nclass DuplicateUnitDefinitionError(ValidationError):\n \"\"\"A unit is defined multiple times in a namespace.\"\"\"\n\n def __init__(self, unit, namespace):\n super(DuplicateUnitDefinitionError, self).__init__(\n '\"{0}\" defined more than once in \"{1}\"'.format(unit.name, namespace),\n unit.context)\n\n\nclass InvalidUnitFormatError(ValidationError):\n \"\"\"A unit's YAML specification is invalid.\"\"\"\n\n def __init__(self, content, context):\n super(InvalidUnitFormatError, self).__init__(\n 'Block has a unit with invalid formatting: {0}'.format(str(content)),\n context)\n\n\nclass UnknownUnitTagError(ValidationError):\n \"\"\"A unit entry has an unknown tag.\"\"\"\n\n def __init__(self, unit_name, tag, context):\n super(UnknownUnitTagError, self).__init__(\n 'Unit \"{0}\" has an invalid tag \"{1}\".'.format(unit_name, tag), context)\n\n\nclass StandardUnitCountError(ValidationError):\n \"\"\"A measurement type does not have exactly one unit tagged as standard.\"\"\"\n\n def __init__(self, measurement_type, tag_count, context):\n super(StandardUnitCountError, self).__init__(\n 'Measurement type \"{0}\" has {1} units tagged as standard. Expected 1.'\n .format(measurement_type, tag_count), context)\n\n\nclass UnknownMeasurementTypeError(ValidationError):\n \"\"\"A unit has an unknown measurement type.\"\"\"\n\n def __init__(self, unit):\n super(UnknownMeasurementTypeError, self).__init__(\n 'Unit \"{0}\" has the unknown measurement type \"{1}\"'.format(\n unit.name, unit.measurement_type), unit.context)\n\n\n# ---------------------------------------------------------------------------- #\n# Errors on the level of individual entity types.\n# ---------------------------------------------------------------------------- #\nclass MissingTypenameError(ValidationError):\n \"\"\"Typename is empty.\"\"\"\n\n def __init__(self, entity_type):\n super(MissingTypenameError, self).__init__('Missing typename.',\n entity_type.file_context)\n\n\nclass IllegalFieldIncrementError(ValidationError):\n \"\"\"Field is incremented unnecessarily.\"\"\"\n\n def __init__(self, entity_type, field_name):\n super(IllegalFieldIncrementError, self).__init__(\n 'Field {0} of {1} is incremented without a duplicate base.'.format(\n field_name, entity_type.typename), entity_type.file_context)\n\n\nclass IllegalFieldIncrementWarning(ValidationError):\n \"\"\"Field is incremented unnecessarily.\"\"\"\n\n def __init__(self, entity_type, field_name):\n super(IllegalFieldIncrementWarning, self).__init__(\n 'Field {0} of {1} is incremented without a duplicate base.'.format(\n field_name, entity_type.typename), entity_type.file_context)\n\n\nclass MissingDescriptionWarning(ValidationWarning):\n \"\"\"Description is empty.\"\"\"\n\n def __init__(self, entity_type):\n super(MissingDescriptionWarning, self).__init__(\n 'Type \"{0}\" has a missing description.'.format(entity_type.typename),\n entity_type.file_context, 20)\n\n\nclass DuplicateFieldError(ValidationError):\n \"\"\"Duplicate fields defined within an entity type.\"\"\"\n\n def __init__(self, entity_type, field):\n super(DuplicateFieldError, self).__init__(\n 'Duplicate local field name \"{0}\" not allowed in {1}.'.format(\n field, entity_type.typename), entity_type.file_context)\n\n\nclass UndefinedFieldError(ValidationError):\n \"\"\"Field is undefined.\"\"\"\n\n def __init__(self, entity_type, field):\n super(UndefinedFieldError,\n self).__init__('Field name \"{0}\" is undefined.'.format(field),\n entity_type.file_context)\n\n\nclass UnrecognizedFieldFormatError(ValidationError):\n \"\"\"Declared field has incorrect format.\"\"\"\n\n def __init__(self, entity_type, field):\n super(UnrecognizedFieldFormatError, self).__init__(\n 'Field name \"{0}\" has incorrect formatting. The format should be '\n 'either \"\" or \"/\".'.format(field),\n entity_type.file_context)\n\n\nclass UnrecognizedParentFormatError(ValidationError):\n \"\"\"Declared parent has incorrect format.\"\"\"\n\n def __init__(self, entity_type, parent_name):\n super(UnrecognizedParentFormatError, self).__init__(\n 'Parent name \"{0}\" has incorrect formatting. The format should be '\n 'either \"\" or \"/\".'.format(\n parent_name), entity_type.file_context)\n\n\nclass DuplicateParentError(ValidationError):\n \"\"\"Entity has duplicate parent ids defined.\"\"\"\n\n def __init__(self, entity_type, parent_name):\n super(DuplicateParentError, self).__init__(\n 'Duplicate parent name \"{0}\" not allowed.'.format(parent_name),\n entity_type.file_context)\n\n\nclass InheritedFieldsSetError(ValidationError):\n \"\"\"The inherited_fields_set field is set.\"\"\"\n\n def __init__(self, entity_type):\n super(InheritedFieldsSetError,\n self).__init__('ERROR: inherited_fields_expanded should not be set.',\n entity_type.file_context)\n\n\n# ---------------------------------------------------------------------------- #\n# Errors on the level of namespaces.\n# ---------------------------------------------------------------------------- #\nclass NonexistentParentError(ValidationError):\n \"\"\"Parent id specified by a type does not exist.\"\"\"\n\n def __init__(self, entity_type, parent_name):\n super(NonexistentParentError, self).__init__(\n 'ERROR: Parent entity type \"{0}\" does not exist.'.format(parent_name),\n entity_type.file_context)\n\n\nclass InheritanceCycleError(ValidationError):\n \"\"\"Cycle detected in the type inheritance graph.\"\"\"\n\n def __init__(self, entity_type, parent_name):\n super(InheritanceCycleError, self).__init__(\n 'ERROR: Inheritance cycle detected with link from '\n 'entity type \"{0}\" to parent type \"{1}\".'.format(\n entity_type.typename, parent_name), entity_type.file_context)\n\n\nclass DuplicateTypesError(ValidationError):\n \"\"\"Duplicate type names defined within the same namespace.\"\"\"\n\n def __init__(self, namespace, entity_type, mapped_entity_type):\n super(DuplicateTypesError, self).__init__(\n 'Duplicate type names are not allowed. Entity type name \"{0}\" '\n 'within namespace \"{1}\" was already defined in \\n'\n '\\t<{2}> (Line {3}).'.format(\n entity_type.typename, namespace,\n mapped_entity_type.file_context.filepath,\n mapped_entity_type.file_context.begin_line_number),\n entity_type.file_context)\n\n\nclass DuplicateIdsError(ValidationError):\n \"\"\"Duplicate type names defined within the same namespace.\"\"\"\n\n def __init__(self, namespace, entity_type, mapped_entity_type):\n super(DuplicateIdsError, self).__init__(\n 'Duplicate type IDs are not allowed. Entity type name \"{0}\" '\n 'within namespace \"{1}\" with ID \"{4}\" was already defined in \\n'\n '\\t<{2}> (Line {3}).'.format(\n entity_type.typename, namespace,\n mapped_entity_type.file_context.filepath,\n mapped_entity_type.file_context.begin_line_number, entity_type.uid),\n entity_type.file_context)\n\n\nclass DuplicateLocalFieldSetsWarning(ValidationWarning):\n \"\"\"Two types declare the exact same local field sets.\"\"\"\n\n def __init__(self, entity_type, dup_entity_types):\n field_list = list(entity_type.local_field_names)\n field_list.sort()\n fieldstr = ''\n for f in field_list:\n fieldstr += '\\n\\t\\t' + f\n t = 'Entity \"{0}\" has the same local {1} field set:{2}\\n\\tas:\\n'.format(\n entity_type.typename, len(entity_type.local_field_names), fieldstr)\n\n for dup in dup_entity_types:\n t += '\\t\\t<{0}> in {1}\\n'.format(dup.typename, dup.file_context.filepath)\n key_arr = dup_entity_types.copy()\n key_arr.append(entity_type)\n super(DuplicateLocalFieldSetsWarning,\n self).__init__(t, entity_type.file_context, 40,\n MAX_RANK - len(field_list), frozenset(key_arr),\n entity_type.is_canonical)\n\n\nclass DuplicateExpandedFieldSetsWarning(ValidationWarning):\n \"\"\"Two types have the exact same expanded field sets.\"\"\"\n\n def __init__(self, entity_type, dup_entity_typenames, equality_key):\n field_count = len(\n set(entity_type.local_field_names.keys())\n | set(entity_type.inherited_field_names.keys()))\n text = 'Entity \"{0}\" has the same expanded set of {1} fields as:\\n'.format(\n entity_type.typename, field_count)\n\n for typename in dup_entity_typenames:\n text += '\\t<{0}> with {1} optionality changes\\n'.format(\n typename, dup_entity_typenames[typename])\n\n text += '\\tAre they the same type?'\n super(DuplicateExpandedFieldSetsWarning,\n self).__init__(text, entity_type.file_context, 30,\n MAX_RANK - len(dup_entity_typenames), equality_key,\n entity_type.is_canonical)\n\n\nclass OverlappingFlexTypeChildWarning(ValidationWarning):\n \"\"\"A type can be represented by a larger, flexible type.\"\"\"\n\n def __init__(self, entity_type, best_diff, dup_entity_typenames):\n field_count = len(\n set(entity_type.local_field_names.keys())\n | set(entity_type.inherited_field_names.keys()))\n text = '\"{0}\" with {1} fields can be represented by flex-types:\\n'.format(\n entity_type.typename, field_count)\n\n for typename in dup_entity_typenames:\n text += '\\t<{0}>\\n\\t\\tUnmatched Optional:\\n'.format(typename)\n for field in dup_entity_typenames[typename]:\n text += '\\t\\t\\t{0}\\n'.format(field)\n\n super(OverlappingFlexTypeChildWarning,\n self).__init__(text, entity_type.file_context, 32,\n MAX_RANK - field_count + best_diff)\n\n\nclass OverlappingFlexTypeParentWarning(ValidationWarning):\n \"\"\"A flexible type can represent another, smaller type.\"\"\"\n\n def __init__(self, entity_type, dup_entity_typenames):\n field_count = len(\n set(entity_type.local_field_names.keys())\n | set(entity_type.inherited_field_names.keys()))\n text = 'flex-type \"{0}\" with {1} fields can represent:\\n'.format(\n entity_type.typename, field_count)\n\n for typename in dup_entity_typenames:\n text += '\\t<{0}>\\n\\t\\tUnmatched Optional:\\n'.format(typename)\n for field in dup_entity_typenames[typename]:\n text += '\\t\\t\\t{0}\\n'.format(field)\n\n super(OverlappingFlexTypeParentWarning,\n self).__init__(text, entity_type.file_context, 31,\n MAX_RANK - len(dup_entity_typenames))\n\n\nclass PossibleOverlappingFlexTypeChildWarning(ValidationWarning):\n \"\"\"A type can ALMOST be represented by a larger, flexible type.\"\"\"\n\n def __init__(self, entity_type, best_diff, dup_entity_typenames):\n field_count = len(\n set(entity_type.local_field_names.keys())\n | set(entity_type.inherited_field_names.keys()))\n text = '\"{0}\" with {1} fields can ALMOST be represented by flex-types:\\n'.format(\n entity_type.typename, field_count)\n\n for typename in dup_entity_typenames:\n text += '\\t<{0}> \\n\\t\\tUnmatched required:\\n'.format(typename)\n for field in dup_entity_typenames[typename]:\n text += '\\t\\t\\t{0}\\n'.format(field)\n\n super(PossibleOverlappingFlexTypeChildWarning,\n self).__init__(text, entity_type.file_context, 34,\n MAX_RANK - field_count + best_diff)\n\n\nclass PossibleOverlappingFlexTypeParentWarning(ValidationWarning):\n \"\"\"A flexible type ALMOST can represent another, smaller type.\"\"\"\n\n def __init__(self, entity_type, dup_entity_typenames):\n field_count = len(\n set(entity_type.local_field_names.keys())\n | set(entity_type.inherited_field_names.keys()))\n text = ('flex-type \"{0}\" with {1} fields can ALMOST represent:\\n').format(\n entity_type.typename, field_count)\n\n for typename in dup_entity_typenames:\n text += '\\t<{0}>\\n\\t\\tUnmatched Required:\\n'.format(typename)\n for field in dup_entity_typenames[typename]:\n text += '\\t\\t\\t{0}\\n'.format(field)\n\n super(PossibleOverlappingFlexTypeParentWarning,\n self).__init__(text, entity_type.file_context, 33,\n MAX_RANK - len(dup_entity_typenames))\n\n\n# ---------------------------------------------------------------------------- #\n# Type Management Findings\n# ---------------------------------------------------------------------------- #\n\n\nclass MissingParentWarning(ValidationWarning):\n \"\"\"This type could use inhheritance to decrease its local field count.\n\n Args:\n typenames: list of typenames that contain the field subset.\n set)size: Number of fields in the subset.\n qualified_parents: list of qualified names of types that have exactly the\n fields in the subset.\n context: file context to attach this finding to (for sorting later).\n sum_match_quality: sum of match qualities for the subset to all types in\n typenames.\n curation_bonus: Set true if parents are curated types. Improves sort rank.\n key: comparison object to use when comparing to other findings for\n deduplication.\n \"\"\"\n\n def __init__(self, typenames, set_size, qualified_parents, context,\n sum_match_quality, curation_bonus, key):\n text = '\"{0}\" all contain {2}. Size: {1}. Average Quality: {3:0.2f}'.format(\n str(sorted(typenames)), set_size, str(sorted(qualified_parents)),\n sum_match_quality / len(typenames))\n\n rank = MISSING_PARENT_VALIDATION_RANK\n if curation_bonus:\n rank -= 1\n\n # Arbitrary score that attempts to rank results by a combination of: the\n # fraction of free fields they replace, the number of types that have the\n # replacement and how big the replacement is.\n match_score = sum_match_quality + len(typenames) * set_size / 25\n super(MissingParentWarning,\n self).__init__(text, context, rank, MAX_RANK - match_score, key,\n False)\n\n\nclass UnusedParentWarning(ValidationWarning):\n \"\"\"This type could be a parent of one or more other types.\"\"\"\n\n def __init__(self, entity_type, qualified_children, sum_match_quality, key):\n field_count = len(entity_type.local_field_names) + len(\n entity_type.inherited_field_names)\n text = '\"{0}\" with {1} fields is contained within {2} types:\\n\\t{3}'.format(\n entity_type.typename, field_count, len(qualified_children),\n str(sorted(qualified_children)))\n\n # Arbitrary score that attempts to rank results by a combination of: the\n # fraction of free fields they replace, the number of types that have the\n # replacement and how big the replacement is.\n match_score = sum_match_quality + len(qualified_children) * field_count / 25\n super(UnusedParentWarning, self).__init__(text, entity_type.file_context,\n MISSING_PARENT_VALIDATION_RANK,\n MAX_RANK - match_score, key, True)\n\n\nclass PotentialParentReplacementWarning(ValidationWarning):\n \"\"\"The inheritance of this type could be simplified.\"\"\"\n\n def __init__(self, entity_type, field_count, qualified_parents,\n replaced_parents):\n text = '\"{0}\" can replace parents {1} with one of {2} ({3} fields).'.format(\n entity_type.typename, str(sorted(replaced_parents)),\n str(sorted(qualified_parents)), field_count)\n\n super(PotentialParentReplacementWarning,\n self).__init__(text, entity_type.file_context, 50,\n MAX_RANK - field_count)\n\n\nclass ParentReplacementCandidateWarning(ValidationWarning):\n \"\"\"This type could simplify the inheritance of another type(s).\"\"\"\n\n def __init__(self, entity_type, field_count, replacement_targets):\n field_count = len(entity_type.local_field_names) + len(\n entity_type.inherited_field_names)\n text = '\"{0}\" replaces multiple parents in {1} ({2} fields).'.format(\n entity_type.typename, str(sorted(replacement_targets)), field_count)\n\n super(ParentReplacementCandidateWarning,\n self).__init__(text, entity_type.file_context, 48,\n MAX_RANK - field_count)\n\n\nclass SmallFieldDeviationWarning(ValidationWarning):\n \"\"\"Two types have similar field sets but don't inherit from each other.\"\"\"\n\n def __init__(self,\n entity_type,\n parents,\n parent_size,\n field_diff,\n key,\n is_master=False):\n diff_str = [MakeFieldString(field) for field in field_diff]\n\n field_score = (len(entity_type.local_field_names) +\n len(entity_type.inherited_field_names)) / len(field_diff)\n t = '\"{0}\" ({1} fields) and \"{2}\" ({3} fields) differ by:\\n\\t\\t{4}'.format(\n entity_type.typename,\n len(\n set(entity_type.local_field_names.keys())\n | set(entity_type.inherited_field_names.keys())),\n str(sorted(parents)), parent_size, str(sorted(diff_str)))\n\n super(SmallFieldDeviationWarning,\n self).__init__(t, entity_type.file_context, 49,\n MAX_RANK - field_score, key, is_master)\n\n\nclass SuggestParentCreationWarning(ValidationWarning):\n \"\"\"This set of fields could be turned into a common parent.\"\"\"\n\n def __init__(self, entity_type, field_list, set_name, match_list):\n text = ('Entity \"{0}\" and {1} other types contain {2} common fields\\n'\n '\\t{3}: {4}\\n'\n '\\tOther types are:\\n'\n '\\t{5}').format(entity_type.typename, len(match_list),\n len(field_list), set_name, str(field_list),\n str(match_list))\n super(SuggestParentCreationWarning,\n self).__init__(text, entity_type.file_context, 70)\n\n\n# ---------------------------------------------------------------------------- #\n# Backwards Compatibility Findings\n# ---------------------------------------------------------------------------- #\n\n\nclass RemovedNamespaceWarning(ValidationWarning):\n \"\"\"A namespace that used to have non-abstract types was removed.\"\"\"\n\n def __init__(self, context, ns_name, disappearing_types):\n super(RemovedNamespaceWarning, self).__init__(\n 'Namespace {0}, defined in\\n'\n '\\t<{1}>\\n'\n 'has been removed, causing the following types to disappear:\\n'\n '\\t[{2}]'.format(ns_name, context.filepath, str(disappearing_types)),\n context)\n\n\nclass RemovedTypeWarning(ValidationWarning):\n \"\"\"A non-abstract type was removed.\"\"\"\n\n def __init__(self, entity_type):\n super(RemovedTypeWarning, self).__init__(\n 'Type {0}, defined in\\n'\n '\\t<{1}>\\n'\n 'has been removed.\\n'.format(entity_type.typename,\n entity_type.file_context.filepath),\n entity_type.file_context, 7)\n\n\nclass RemovedFieldWarning(ValidationWarning):\n \"\"\"A field was removed from a non-abstract type.\"\"\"\n\n def __init__(self, entity_type, field_name):\n super(RemovedFieldWarning, self).__init__(\n 'Field {0} of non-abstract type {1} has been removed.'.format(\n field_name, entity_type.typename), entity_type.file_context, 5)\n\n\nclass AddedFieldWarning(ValidationWarning):\n \"\"\"A field was removed added to a non-abstract type.\"\"\"\n\n def __init__(self, entity_type, field_name):\n super(AddedFieldWarning, self).__init__(\n 'Field {0} of non-abstract type {1} has been added.'.format(\n field_name, entity_type.typename), entity_type.file_context, 6)\n\n\nclass SuppressedFindingsWarning(ValidationWarning):\n \"\"\"Findings on unchanged types have been suppressed in the results.\"\"\"\n\n def __init__(self, number_suppressed):\n super(SuppressedFindingsWarning, self).__init__(\n '{0} warnings from unchanged files were suppressed'.format(\n number_suppressed), FileContext(''), 1)\n\n\n# ---------------------------------------------------------------------------- #\n# Exceptions thrown inside the validation process logic.\n# ---------------------------------------------------------------------------- #\n\n\nclass ProcessError(Exception):\n \"\"\"Base level exception class.\"\"\"\n pass\n\n\nclass ReadProcessError(ProcessError):\n \"\"\"File can't be read.\"\"\"\n\n def __init__(self, filepath):\n super(ReadProcessError,\n self).__init__(\"'{0}' can't be opened.\".format(filepath))\n\n\nclass NonexistentEntityProcessError(ProcessError):\n \"\"\"Entity type does not exist in configuration.\"\"\"\n pass\n\n\nclass InheritanceCycleProcessError(ProcessError):\n \"\"\"Cycle detected in the type inheritance graph.\"\"\"\n pass\n","sub_path":"tools/validators/ontology_validator/yamlformat/validator/findings_lib.py","file_name":"findings_lib.py","file_ext":"py","file_size_in_byte":39356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"501158316","text":"import math\n\ndef koordinate(ime, kraji):\n for a, x, y in kraji:\n if a == ime:\n return x, y\n return None\n\ndef razdalja_koordinat(x1, y1, x2, y2):\n razdalja = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) #razdalja = ((x2 - x1) ** 2 + (y2 - y1) ** 2)**(1/2)\n return razdalja\n\ndef razdalja(ime1, ime2, kraji):\n x1, y1 = koordinate(ime1, kraji)\n x2, y2 = koordinate(ime2, kraji)\n c = razdalja_koordinat(x1, y1, x2, y2)\n return c\n\ndef v_dometu(ime, domet, kraji):\n dosezeni = []\n x1, y1 = koordinate(ime, kraji)\n for a, x, y in kraji:\n razdalja = razdalja_koordinat(x1, y1, x, y)\n if a != ime:\n if razdalja <= domet:\n dosezeni.append(a)\n return dosezeni\n\ndef najbolj_oddaljeni(ime, imena, kraji):\n naj_razdalja = 0\n razdalja = 0\n x, y = koordinate(ime, kraji)\n a = ''\n for k in imena:\n x1, y1 = koordinate(k, kraji)\n razdalja = razdalja_koordinat(x, y, x1, y1)\n if naj_razdalja < razdalja:\n naj_razdalja = razdalja\n a = k\n return a\n\ndef zalijemo(ime, domet, kraji):\n a = v_dometu(ime, domet, kraji)\n return najbolj_oddaljeni(ime, a, kraji)\n\ndef presek(s1, s2):\n koncen = []\n for a in s1:\n for b in s2:\n if a == b:\n koncen.append(b)\n return koncen\n\ndef skupno_zalivanje(ime1, ime2, domet, kraji):\n prvi = v_dometu(ime1, domet, kraji)\n drugi = v_dometu(ime2, domet, kraji)\n return presek(prvi, drugi)\n\n\n\n","sub_path":"code/batch-1/vse-naloge-brez-testov/DN4-M-53.py","file_name":"DN4-M-53.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"161151299","text":"import json\nfrom abc import abstractmethod\nfrom functools import reduce\nimport os\n\nimport numpy as np\nfrom scipy.stats import hypergeom\n\nfrom ..log import setup_logger\nfrom ..utils.tools import parse\nfrom ._unit import Unit\n\n\nthis_dir = os.path.dirname(__file__)\ndef join_root(path):\n return os.path.abspath(os.path.join(this_dir, path))\n\n\ndef _get_dict(path):\n \"\"\"\n Parameters\n __________\n\n path: string or array\n Path to json file. In case a list of paths is provided instead,\n read them all and merge then into a single dict. Assumes depth two.\n\n Returns\n _______\n d: dict\n Dictionary containing marker information.\n d = {\n key: {\n subkey: [...],\n ...\n },\n ...\n }\n \"\"\"\n # TODO straighten up the spaghetti\n\n if isinstance(path, str):\n with open(path, \"r\") as f:\n return json.load(f)\n else:\n d = {}\n for path in path:\n with open(path, \"r\") as f:\n d_part = json.load(f)\n for key in d_part:\n if key in d:\n for subkey in d_part[key]:\n if subkey in d[key]:\n # to remove duplicates\n d[key][subkey] = list(set().union(\n d[key][subkey], d_part[key][subkey]))\n else:\n d[key][subkey] = d_part[key][subkey]\n else:\n d[key] = d_part[key]\n return d\n\n\nclass Ide_HyperGeom(Unit):\n \"\"\"\n Runs hypergeom to find matching populations. Compute for every label\n in x, the pop in pops where x is most likely to have been drawn from.\n It is assumed that the dictionary that is passed has two levels of\n hierarchy of types. First determine the lvl1 type, then the lvl2 subtype.\n \"\"\"\n\n def __init__(self, path=join_root('../markers/cell_type_marker.json'), tissue='all'):\n self.logger = setup_logger(\"HyperGeom\")\n self.path = path\n self.tissue = tissue\n\n def get(self, x):\n \"\"\"\n Extended keys are: lvl1_type, lvl1_sv, lvl1_intersec, lvl1_total,\n lvl2_type, lvl2_sv, lvl2_intersec, lvl2_total\n type (string): identified type\n sv (float): survival value from Hypergeometric Test\n intersec (np.ndarray): array of names that overlap\n total (int): total number of names in dict[type]\n\n Returns the types of cells in x.\n\n Args:\n x (dict): x = {\n label_1: {\n outp_names: [name_1, ...],\n ...\n },\n ...\n }\n\n Returns:\n (dict): Extends x with new keys (returns copy).\n \"\"\"\n x = x.copy()\n lvl2 = _get_dict(self.path)\n\n # Construct lvl1 dict by merging all lvl2 dicts\n lvl1 = {}\n for pop in lvl2:\n lvl1[pop] = parse(\n np.array(reduce(lambda a, b: a+b, lvl2[pop].values()))\n )\n\n if self.tissue == 'all':\n self.process_level(x, lvl1, level=1)\n self.process_level(x, lvl2, level=2)\n else:\n self.logger.info(\n \"Running HyperGeom for {0} only.\".format(self.tissue))\n self.process_tissue(x, tissue=self.tissue, level_dict=lvl2)\n\n return x\n\n def process_level(self, x, level_dict, level):\n for key in x:\n if level > 1 and x[key]['lvl{0}_type'.format(level-1)] == 'None':\n tp, sv, intersec, total = \"None\", 1, np.array([]), 0\n all_pops = {'svs': np.array([]),\n 'intersecs': np.array([]),\n 'lens': np.array([])}\n else:\n if level > 1:\n tp, sv, intersec, total, all_pops = self.find_population(\n # x[key]['outp_names'],\n x[key]['lvl{0}_intersec'.format(level-1)],\n level_dict[x[key]['lvl{0}_type'.format(level-1)]]\n )\n else:\n tp, sv, intersec, total, all_pops = self.find_population(\n x[key]['outp_names'],\n level_dict\n )\n x[key]['lvl{0}_type'.format(level)] = tp\n x[key]['lvl{0}_sv'.format(level)] = sv\n x[key]['lvl{0}_intersec'.format(level)] = intersec\n x[key]['lvl{0}_total'.format(level)] = total\n x[key]['lvl{0}_all'.format(level)] = all_pops\n self.logger.info(\"Finished finding lvl{0} types.\".format(level))\n\n def process_tissue(self, x, tissue, level_dict):\n for key in x:\n tp, sv, intersec, total, all_pops = self.find_population(\n x[key]['outp_names'],\n level_dict[tissue]\n )\n x[key]['lvl1_type'] = \"User Defined\"\n x[key]['lvl1_sv'] = 1\n x[key]['lvl1_intersec'] = np.array([])\n x[key]['lvl1_total'] = 0\n x[key]['lvl1_all'] = {}\n\n x[key]['lvl2_type'] = tp\n x[key]['lvl2_sv'] = sv\n x[key]['lvl2_intersec'] = intersec\n x[key]['lvl2_total'] = total\n x[key]['lvl2_all'] = all_pops\n self.logger.info(\"Finished finding lvl2 types.\")\n\n def find_population(self, x, pops):\n \"\"\"\n See find_populations. Assumes x is a single list.\n\n Args:\n x (np.ndarray): 1D list of names.\n pops (dict): Dictionary of populations: pops = {\n type: [name_1, name_2, ...],\n ...\n }\n Returns:\n (string): population name\n (float): survival value\n (np.ndarray): common names\n (int): total number of names in matched population\n \"\"\"\n M = sum([len(pops[pop]) for pop in pops])\n N = len(x)\n\n survival_values = []\n intersections = []\n lens = []\n\n rsv, rpop, rk = 2, -1, 0\n\n for pop in pops:\n n = len(pops[pop])\n intersec = np.intersect1d(x, pops[pop])\n k = len(intersec)\n sv = hypergeom.sf(k-1, M=M, n=n, N=N) if k > 0 else 1\n\n survival_values.append(sv)\n intersections.append(intersec)\n lens.append(len(pops[pop]))\n\n if sv <= rsv or (rsv == 2 and k > 0):\n rsv, rpop, rk = sv, pop, k\n\n all_pops = {'svs': np.array(survival_values),\n 'intersecs': np.array(intersections),\n 'lens': np.array(lens)}\n\n if rk == 0: # in case of no intersection, return -1\n return \"None\", 1, np.array([]), 0, all_pops\n else:\n return rpop, rsv, np.intersect1d(x, pops[rpop]), len(pops[rpop]), all_pops\n","sub_path":"src/units/_identificator.py","file_name":"_identificator.py","file_ext":"py","file_size_in_byte":6995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"224053149","text":"import importlib\nimport json\nimport sys\nfrom os import listdir, environ, pathsep\nfrom os.path import isfile, join, splitext\nimport core.config.paths\nfrom core.helpers import list_apps\nfrom core.config.paths import keywords_path, graphviz_path\nfrom collections import OrderedDict\n\n\ndef load_config():\n global https\n self = sys.modules[__name__]\n with open(core.config.paths.config_path) as config_file:\n config = json.loads(config_file.read())\n for key, value in config.items():\n if value:\n if hasattr(core.config.paths, key):\n setattr(core.config.paths, key, value)\n elif hasattr(self, key):\n setattr(self, key, value)\n\n\ndef write_values_to_file(values=None):\n if values is None:\n values = [\"graphviz_path\", \"templates_path\", \"profile_visualizations_path\", \"keywords_path\", \"db_path\",\n \"tls_version\",\n \"certificate_path\", \"https\", \"private_key_path\", \"debug\", \"default_server\", \"host\", \"port\"]\n self = sys.modules[__name__]\n f = open(core.config.paths.config_path, \"r\")\n parsed = json.loads(f.read())\n f.close()\n for key in values:\n parsed[key] = getattr(self, key)\n\n with open(core.config.paths.config_path, \"w\") as f:\n json.dump(parsed, f)\n\n# Enables/Disables Browser Notifications\nnotifications = \"True\"\n\n# Path to graphviz location\nenviron[\"PATH\"] += (pathsep + graphviz_path)\n\n# Database Path\n\nreinitialize_case_db_on_startup = True\n\ntls_version = \"1.2\"\nhttps = \"false\"\n\ndebug = \"True\"\ndefault_server = \"True\"\nhost = \"127.0.0.1\"\nport = \"5000\"\n\n# Loads the keywords into the environment filter for use\nJINJA_GLOBALS = {splitext(fn)[0]: getattr(importlib.import_module(\"core.keywords.\" + splitext(fn)[0]), \"main\")\n for fn in listdir(keywords_path) if\n isfile(join(keywords_path, fn)) and not splitext(fn)[0] in [\"__init__\", \".\"]}\n\n# Active Execution (Workflows called from constant loop) settings.\n# secondsDelay - delay in seconds between execution loops\n# maxJobs - maximum number of jobs to be run at once\nexecution_settings = {\n \"secondsDelay\": 0.1,\n \"maxJobs\": 2\n}\n\nnum_threads = 5\nthreadpool_shutdown_timeout_sec = 3\n\n# Function Dict Paths/Initialization\n\nfunction_info = None\n\n\ndef load_function_info():\n global function_info\n try:\n with open(core.config.paths.function_info_path) as f:\n function_info = json.loads(f.read())\n app_funcs = {}\n for app in list_apps():\n with open(join(core.config.paths.apps_path, app, 'functions.json')) as function_file:\n app_funcs[app] = json.loads(function_file.read())\n function_info['apps'] = app_funcs\n\n except Exception as e:\n print(\"caught!\")\n print(e)\n\nload_config()\ntry:\n with open(core.config.paths.events_path) as f:\n possible_events = json.loads(f.read(), object_pairs_hook=OrderedDict)\nexcept (IOError, OSError):\n possible_events = {}\n\n\nload_function_info()\n\n\n# Function to set config value\ndef set(key, value):\n self = sys.modules[__name__]\n if hasattr(self, key):\n setattr(self, key, value)\n return True\n return False\n","sub_path":"core/config/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"169946606","text":"from copy import copy\n\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom PyPDF2 import PdfFileReader, PdfFileWriter\n\n# Create your views here.\ndef makeHalfPagePDF(request):\n if \"GET\" == request.method:\n return render(request, 'pdfTools/makeHalfPagePDF.html', {})\n else:\n file = request.FILES[\"pdf_file\"]\n with open('original_pdf', 'wb+') as pdfFileObj:\n for chunk in file.chunks():\n pdfFileObj.write(chunk)\n pdf_reader = PdfFileReader(pdfFileObj)\n\n pdf_writer = PdfFileWriter()\n for i in range(pdf_reader.numPages):\n page = pdf_reader.getPage(i)\n width = page.mediaBox.getUpperRight_x() - page.mediaBox.getUpperLeft_x()\n height = page.mediaBox.getUpperLeft_y() - page.mediaBox.getLowerLeft_y()\n\n # 왼쪽 반\n for_left = copy(page)\n for_left.cropBox.setLowerLeft((0, 0))\n for_left.cropBox.setUpperRight((width/2, height))\n pdf_writer.addPage(for_left)\n\n # 오른쪽 반\n for_right = copy(page)\n for_right.cropBox.setLowerLeft((width / 2, 0))\n for_right.cropBox.setUpperRight((width, height))\n pdf_writer.addPage(for_right)\n\n with open('result.pdf', 'wb') as pdfResultFile:\n pdf_writer.write(pdfResultFile)\n\n with open('result.pdf', 'rb') as pdfResult:\n response = HttpResponse(pdfResult.read(), content_type=\"application/pdf\")\n response['Content-Disposition'] = 'attachment; filename=result.pdf'\n return response\n","sub_path":"pdfTools/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"433464734","text":"import os\nimport configparser\n\nconfigParser = configparser.ConfigParser()\nconfigFile = 'config.ini'\nconfigDefault = 'config.default'\nif os.path.isfile(configFile):\n configParser.read(configFile)\nelse:\n configParser.read(configDefault)\n with open(configFile, 'w') as conf:\n configParser.write(conf)\n\nclass Config(object):\n SECRET_KEY = configParser.get('Security', 'SECRET_KEY')\n BASIC_AUTH_USERNAME = configParser.get('Security', 'BASIC_AUTH_USERNAME')\n BASIC_AUTH_PASSWORD = configParser.get('Security', 'BASIC_AUTH_PASSWORD')\n BASIC_AUTH_FORCE = configParser.get('Security', 'BASIC_AUTH_FORCE')\n\n CONTENT_PATH = configParser.get('Content', 'CONTENT_PATH')\n CONTENT_FOLDERS = eval(configParser.get('Content', 'CONTENT_FOLDERS'))\n\n def make_path():\n path = configParser.get('Content', 'CONTENT_PATH')\n folders = eval(configParser.get('Content', 'CONTENT_FOLDERS'))\n for folder in folders:\n if not os.path.isdir(os.path.join(path,folder)):\n os.makedirs(os.path.join(path,folder))\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"625119638","text":"import argparse\nimport os\nimport numpy as np\nimport pandas as pd \nimport torch\nimport pyro\nimport pyro.distributions as dist\nfrom torch.distributions import constraints\nfrom tqdm import tqdm\nimport sys\nimport helper\nimport itertools\n\n######## FOLLOWING WE DEFINE A CLASS THAT WILL KEEP TRACK OF THE SAMPLE POSTERIOR DATA ########\nclass Posterior_pi_log(object):\n\tdef __init__(self, ref_epig_name_list):\n\t\tself.ref_epig_name_list = ref_epig_name_list\n\t\tself.pi = torch.zeros(len(ref_epig_name_list))\n\tdef update(self, updated_pi):\n\t\tself.pi = updated_pi\n\tdef write_pi(self, output_folder):\n\t\tlast_pi = pd.Series(self.pi.detach().numpy())\n\t\tlast_pi.index = self.ref_epig_name_list\n\t\tsave_fn = os.path.join(output_folder, 'posterior_pi.txt')\n\t\tlast_pi.to_csv(save_fn, header = False, index = True, sep = '\\t')\n###########################################\n\ndef generate_tiny_toy_data(num_obs):\n\tnum_ref_epig = 5\n\tnum_state = 3\n\tnum_mark = 3\n\talpha = np.random.uniform(1, 6, num_ref_epig)\n\tpi = pyro.sample('pi', dist.Dirichlet(torch.tensor(alpha)))\n\tref_state_np = np.random.choice(num_state, size = num_obs * num_ref_epig, replace = True).reshape(num_obs, num_ref_epig)\n\temission_np = np.array([[0.1,0.1,0.8], [0.2,0.1,0.7], [0.3, 0.1,0.6]])\n\temission_df = pd.DataFrame(emission_np, columns = list(map(lambda x: 'M{}'.format(x), range(emission_np.shape[1])))) # columns: M0 --> M...\n\ttransition_mat = torch.tensor(np.array([[0.8,0.1,0.1], [0.3,0.5,0.2], [0.2,0.2,0.6]]))\n\tmark_data = np.zeros((num_obs, num_mark))\n\tZ = torch.zeros(num_obs)\n\tS = torch.zeros(num_obs)\n\tfor i in pyro.plate('genome_loop', num_obs):\n\t\tZ[i] = (pyro.sample('z_{}'.format(i), dist.Categorical(pi))).type(torch.long) # sample reference epig from pi at this genomic position \n\t\tR_i = ref_state_np[i,int(Z[i])] # index of state that is observed at the pick refernece epigenome at the current position\n\t\tS[i] = pyro.sample('S_{}'.format(i), dist.Categorical(transition_mat[R_i,:])) # We can get access to parameters by just using pyro.param('')\n\t\tfor j in pyro.plate('mark_loop', num_mark):\n\t\t\tmark_data[i,j] = pyro.sample('M_{}_{}'.format(i,j), dist.Bernoulli(emission_np[S[i].type(torch.long),j])).item()\n\tmark_data = pd.DataFrame(mark_data, columns = emission_df.columns)\n\treturn alpha, pi, ref_state_np, emission_df, transition_mat, mark_data\n\n# @pyro.infer.config_enumerate : this is never needed because we it is only used when all the hidden variables are discrete. In our case, pi is not discrete.\ndef model(alpha, transformed_emission_tt, ref_state_np, transformed_mark_data, num_obs, num_state, NUM_BINS_SAMPLE_PER_ITER): \n\tnum_ct = len(alpha)\n\tpi = pyro.sample('pi', dist.Dirichlet(alpha)) # sample mixture probabilities of reference epigenome\n\tfor i in pyro.plate('state_loop', num_state):\n\t\ttrans_from_state = pyro.param('beta_{}'.format(i), torch.randn(num_state).exp(), constraint = constraints.simplex) \n\tfor i in pyro.plate('genome_loop', num_obs):\n\t\tz_i = pyro.sample('z_{}'.format(i), dist.Categorical(pi))\n\t\tR_i = ref_state_np[i,z_i] \n\t\tS_i = pyro.sample('S_{}'.format(i), dist.Categorical(pyro.param('beta_{}'.format(R_i)))) # We can get access to parameters by just using pyro.param('')\n\t\tpyro.sample('M_{}'.format(i), dist.Categorical(transformed_emission_tt[S_i.type(torch.long)]), obs = transformed_mark_data[i])\n\n\ndef guide(alpha, transformed_emission_tt, ref_state_np, transformed_mark_data, num_obs, num_state, NUM_BINS_SAMPLE_PER_ITER):\n\t# in this guide, we assume that pi and z are independent\n\t# transformed_mark_data: a 1D tensor, each position corresponding to a genomic position\n\tnum_ct = len(alpha)\n\tq_lambda = pyro.param('q_lambda', alpha, constraint = constraints.positive)\n\tpi = pyro.sample('pi', dist.Dirichlet(q_lambda))\n\tfor i in pyro.plate('state_loop', num_state):\n\t\ttrans_from_state = pyro.param('beta_{}'.format(i), torch.randn(num_state).exp(), constraint = constraints.simplex) # sample transition from state i in ref_epig to other states in the sample of interest\t\n\tfor i in pyro.plate('genome_loop', num_obs, subsample_size = NUM_BINS_SAMPLE_PER_ITER): # for subsampling, we only need to specify the subsampling in guide function, not in the model function\n\t\tz_probs = pyro.param(\"q_z_{}\".format(i), torch.randn(num_ct).exp(), constraint=constraints.simplex) \n\t\t# i added .exp() as suggested by https://www.programcreek.com/python/example/123171/torch.distributions.constraints.positive, constraints.simplex is to guarantee that they sum up to 1, based on https://pytorch.org/docs/stable/distributions.html (search for simplex in this page)\n\t\tz_i = pyro.sample('z_{}'.format(i), dist.Categorical(z_probs))\n\t\tR_i = (ref_state_np[i,z_i]).astype(int) # Ha also checked that when doing subsampling, the model still got the exact data as expected\n\t\tS_i = pyro.sample('S_{}'.format(i), dist.Categorical(pyro.param('beta_{}'.format(R_i)))) \n\ndef train(alpha, ref_state_np, transformed_mark_data, transformed_emission_tt, num_state, num_obs, NUM_TRAIN_ITERATIONS, NUM_BINS_SAMPLE_PER_ITER):\n\tpyro.clear_param_store()\n\tloss_func = pyro.infer.TraceGraph_ELBO(max_plate_nesting=1)\n\tsvi = pyro.infer.SVI(model, guide, pyro.optim.Adam({\"lr\": 0.01}), loss=loss_func)\n\tlosses = []\n\tfor _ in tqdm(range(NUM_TRAIN_ITERATIONS)):\n\t\tloss = svi.step(alpha, transformed_emission_tt, ref_state_np, transformed_mark_data, num_obs, num_state, NUM_BINS_SAMPLE_PER_ITER)\n\t\tlosses.append(loss)\n\tposterior_params = {k: np.array(v.data) for k, v in pyro.get_param_store().items()}\n\treturn posterior_params\n\ndef read_chrom_mark_observed_signals(mark_data):\n\tchrom_mark_list = mark_data.columns\n\tmark_data = mark_data.apply(lambda x: x.astype(int).astype(str), axis = 0) # convert the data from 0.0, 1.0 to 0 and 1 integers\n\tmark_data['combined_obs_int'] = mark_data.apply(lambda x: int(''.join(x), 2), axis = 1) # apply function to each row\n\ttransformed_mark_data = torch.tensor(mark_data['combined_obs_int'].values) # 1D tensor each element is the observed data at each postion. If we have 3 marks, the the observed values can be 0-7.\n\treturn transformed_mark_data, chrom_mark_list \n\ndef calculate_join_emission_multiple_marks(row, binary_tuple, chrom_mark_list):\n\t# this will process each row in the emission matrix (each state)\n\t# binary tuple will be a tuple of length #num_mark, each element in the tuple is 0/1 --> presence/absence call of chromatin mark. The order of chromatin marks will be given in chrom_mark_list. Ex: binary_tuple = (0,0,1), chrom_mark_list = [m1, m2, m3] --> m3 is present and others are absent. This function will return the probability of observing binary_tuple given each of the state. \n\t# function tested on 08/03/2021\n\tbase = row[chrom_mark_list]\n\texponent = pd.Series(binary_tuple, index = chrom_mark_list)\n\treturn np.prod(base**exponent * (1-base)**(1-exponent))\n\ndef read_emission_matrix_into_categorical_prob(emission_df, chrom_mark_list):\n\tall_possible_obs_marks = list(itertools.product(range(2), repeat = len(chrom_mark_list))) # list of tuples, each of length # num_marks --> all possible observations of marks \n\tall_possible_obs_marks_str = list(map(lambda x: ''.join(list(map(str, x))), all_possible_obs_marks)) # convert (0,0,0) --> '000'\n\tfor obs_pattern in all_possible_obs_marks:\n\t\tobs_string = ''.join(list(map(str, obs_pattern)))\n\t\temission_df[obs_string] = emission_df.apply(lambda x: calculate_join_emission_multiple_marks(x, obs_pattern, chrom_mark_list), axis = 1) # apply function to each row\n\tresult_df = emission_df[all_possible_obs_marks_str].copy() # columns are all the possible chromatin mark sequences for the chrom_mark_list. Right now, we assume that the assays being profiled are a subset of the 12 marks in the 25-state roadmap model, We can care about the case where the profiled marks for sample of interest are not among the 12 marks later.\n\tresult_df.columns = list(map(lambda x: int(x, 2), result_df.columns))\n\tresult_df = result_df[np.arange(len(all_possible_obs_marks))] # rearrange so that if # marks = 3 --> columns will be 0 --> 7, correpsonding to the 8 possible combination of observed marks 000 --> 111\n\tresult_df = torch.tensor(result_df.values) # tensor with rows: states, columns: possible combinations of chromatin marks \n\treturn result_df\n\ndef evaluate(alpha, pi, transition_mat, num_state, posterior_params):\n\tprint(posterior_params)\n\tprint (\"alpha\")\n\tprint(alpha)\n\tq_lambda = posterior_params['q_lambda']\t\n\tprint(posterior_params['q_lambda'])\n\tprint(\"pi\")\n\tprint(pi)\n\tpred_p = q_lambda / q_lambda.sum() # expected valye of pi given q_lambda\n\tprint(pred_p)\n\tprint('beta')\n\tprint(transition_mat)\n\tfor i in range(num_state):\n\t\tprint(posterior_params['beta_{}'.format(i)])\n\treturn \n\ndef main(args):\n\tNUM_TRAIN_ITERATIONS = args.NUM_TRAIN_ITERATIONS\n\tNUM_BINS_SAMPLE_PER_ITER = args.NUM_BINS_SAMPLE_PER_ITER\n\tnum_obs = 10000\n\talpha, pi, ref_state_np, emission_df, transition_mat, mark_data = generate_tiny_toy_data(num_obs)\n\t# mark_data and emission_df are pd.DataFrame that share the same column names\n\tprint ('Done generating data')\n\talpha = torch.tensor(alpha) # to make it implementable for pyro\n\tnum_state = emission_df.shape[0]\n\ttransformed_mark_data, chrom_mark_list = read_chrom_mark_observed_signals(mark_data) \n\t# transformed_mark_data: 1D tensor, each element is the observed data at each postion.\n\t# If we have 3 marks, the the observed values can be 0-7.\n\ttransformed_emission_tt = read_emission_matrix_into_categorical_prob(emission_df, chrom_mark_list) # tested\n\t# 2D tensor with rows: states, columns: possible combinations of chromatin marks \n\tprint(transformed_emission_tt)\n\tposterior_params = train(alpha, ref_state_np, transformed_mark_data, transformed_emission_tt, num_state, num_obs, NUM_TRAIN_ITERATIONS, NUM_BINS_SAMPLE_PER_ITER)\n\tevaluate(alpha, pi, transition_mat, num_state, posterior_params)\n\nif __name__ == \"__main__\":\n assert pyro.__version__.startswith(\"1.7.0\")\n parser = argparse.ArgumentParser(description=\"Tiny toy example\")\n parser.add_argument(\"-n\", \"--NUM_TRAIN_ITERATIONS\", default=4000, type=int)\n parser.add_argument(\"-o\", \"--NUM_BINS_SAMPLE_PER_ITER\", default=1000, type=int)\n args = parser.parse_args()\n main(args)\n\n","sub_path":"experiment_pyro/tiny_toy_example.py","file_name":"tiny_toy_example.py","file_ext":"py","file_size_in_byte":10168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"280848521","text":"import Blockchain\nfrom Blockchain import blockchain\n\nfrom flask import Flask\nfrom flask import request\nfrom flask import Blueprint\n\nimport json\nimport Util\nfrom Util import ComplexEncoder\n\n#Exporting blueprint\nconsensus_api = Blueprint('consensus_api', __name__)\n\n@consensus_api.route('/chain', methods=['GET'])\ndef get_chain():\n #Blocks become dictionaries\n chain_to_send = []\n\n for block in blockchain:\n shit = block.index\n chain_to_send.append(block.reprJSON())\n\n #Send our requested chain\n return json.dumps(chain_to_send, cls=ComplexEncoder)\n\ndef find_new_chains():\n #Get others nodes blockchains\n other_chains = []\n for node_url in peer_nodes:\n block = requests.get(node_url + \"/blocks\").content\n\n #Converting Json to dictionary for easy manipulation\n block = json.loads(block)\n\n #add to chains list\n other_chains.append(block)\n return other_chains\n\ndef consensus():\n #Get blocks from other nodes\n other_chains = find_new_chains()\n\n #If this node's chain is not the longest, store the longest\n longest_chain = blockchain\n for chain in other_chains:\n if len(longest_chain) < len(chain):\n longest_chain = chain\n\n blockchain = longest_chain\n","sub_path":"Tiny-Blockchain/Consensus.py","file_name":"Consensus.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"122835458","text":"# -*- coding: utf-8 -*-\n# @Time : 2021/1/18 0018 10:38\n# @Author : Owen\n# @Email : zhangwx0794@gmail.com\n# @File : ClsTaobao.py\n# @Project : Taobao\n\nimport xlwt, xlrd\nimport pymysql\nimport os\nimport re\nimport platform\nfrom openpyxl import *\n\n\n# import win32com.client as win32\n\nclass Taobao():\n\n # 1. 数据库操作returnCnt默认返回结果集条数,默认返回所有\n def sql_operation(self, sql, returnCnt=-1):\n conn = pymysql.Connect(\n host='47.111.113.238',\n port=3318,\n db='taobao',\n user='taobao',\n passwd='Boss123456..taobao',\n charset='utf8'\n )\n # 获取游标\n cursor = conn.cursor()\n try:\n cursor.execute(sql)\n except Exception as e:\n conn.rollback()\n print('异常sql: ', sql)\n print('事务处理失败!异常信息:', e)\n else:\n conn.commit()\n sqlRes = cursor.fetchall()\n # 关闭连接\n cursor.close()\n conn.close()\n if returnCnt == -1:\n return sqlRes\n elif returnCnt == 1:\n return sqlRes[0][0]\n else:\n return 0\n\n # 2. 查找当前工作目录下所有的xls文件\n def get_path_xls(self, absPath):\n allXls = os.listdir(absPath)\n zz = re.compile('(\\.xls)$')\n xlsList = []\n for xls in allXls:\n zzRes = zz.findall(xls)\n if 'xls' in xls and len(zzRes) > 0:\n xlsList.append(xls)\n return xlsList\n\n # 3. 查找当前工作目录下所有的xlsx文件\n def get_path_xlsx(self, absPath):\n allXlsx = os.listdir(absPath)\n if self.getSystemPlatform() == 'Windows':\n zz = re.compile('(\\.xlsx)$')\n else:\n zz = re.compile('(\\.xlsx)$')\n xlsxList = []\n for xlsx in allXlsx:\n zzRes = zz.findall(xlsx)\n if 'xlsx' in xlsx and len(zzRes) > 0:\n xlsxList.append(xlsx)\n return xlsxList\n\n # 4. 数据规范校验\n\n # 5. xls转xlsx\n # def xls_to_xlsx(self,xlsPath):\n # try:\n # excel = win32.gencache.EnsureDispatch('Excel.Application')\n # wb = excel.Workbooks.Open(xlsPath)\n # wb.SaveAs(xlsPath + \"x\", FileFormat=51) # FileFormat = 51 is for .xlsx extension\n # wb.Close() # FileFormat = 56 is for .xls extension\n # excel.Application.Quit()\n # except Exception as e:\n # print('xls转换xlsx异常',e)\n # else:\n # os.remove(xlsPath)\n # print(xlsPath,'转换成功,源文件已删除')\n\n # 6. excel文件重命名\n def format_xls_name(self, xlsPath):\n # 1.拼接变量\n # * xls名称\n if self.getSystemPlatform() == 'Windows':\n xlsName = str(xlsPath).split('\\\\')[-1]\n else:\n xlsName = str(xlsPath).split('/')[-1]\n # * xls所在路径\n xlsPwd = str(xlsPath).split(xlsName)[0]\n # * 订单日期\n length1 = len(re.compile('^\\d+\\.\\d+').findall(xlsName))\n if length1 > 0:\n rq = re.compile('^\\d+\\.\\d+').findall(xlsName)[0]\n month = str(rq).split('.')[0]\n day = str(rq).split('.')[1]\n if int(month) >= 10:\n year = 2020\n else:\n year = 2021\n date = str(year) + '-' + str(month).rjust(2, '0') + '-' + str(day).rjust(2, '0')\n print(xlsName, date)\n else:\n length2 = len(re.compile('^\\d{4}-\\d{2}-\\d{2}').findall(xlsName))\n if length2 > 0:\n date = re.compile('^\\d{4}-\\d{2}-\\d{2}').findall(xlsName)[0]\n else:\n # 文件中不含有日期关键词就会重命名为2099-12-31+原有中文字符+xlsx\n date = '2099-12-31'\n\n # * 店铺名称\n shopNameTemp = re.compile('[\\u4e00-\\u9fff]+').findall(xlsName)[0]\n shopName = str(shopNameTemp).replace('汇总', '').replace('订单', '').replace('总汇', '').replace('副本', '')\n # 2.拼接新的文件名称\n newXlsName = date + shopName + '.xlsx'\n newXlsPath = xlsPwd + newXlsName\n # 如果新旧文件名称不一样,则重命名\n if xlsName != newXlsName:\n # * 判断新文件是否已经存在\n for i in range(2, 100):\n if os.path.exists(newXlsPath):\n newXlsPath = xlsPwd + date + shopName + '_' + str(i) + '.xlsx'\n else:\n os.rename(xlsPath, newXlsPath)\n print('重命名成功!', xlsName, ' => ', newXlsName)\n break\n return None\n\n # 7. 删除excel含有关键字的列\n def del_col_from_key(self, xlsPath, key_word, col=1):\n # xlsPath必须得是绝对路径\n wbb = load_workbook(xlsPath)\n wss = wbb.active\n # 删除第一列【时间】数据\n kw = str(wss.cell(1, col).value).strip()\n if str(key_word).strip() == kw:\n wss.delete_cols(col)\n wbb.save(xlsPath)\n print(xlsPath + '第一列关键字' + key_word + '删除成功!')\n wbb.close()\n return None\n\n # 8. 校验指定范围列数据有效性\n def list_none_check(self, row, startCol, endCol):\n for i in range(startCol, endCol):\n if str(row[i]) == '':\n # print('none',end=' ')\n return 0\n return 1\n\n # 9. 订单号唯一检测\n # 查询数据库检查订单号是否已存在\n def chk_data_is_exist(self, order_id):\n sql = 'select count(0) from orderInfo where orderId = %s' % order_id\n cnt = self.sql_operation(sql, 1)\n # 返回订单号重复查询结果 存在返回1 不存在返回0\n return cnt\n\n # 9.1 批量检测订单号是否唯一\n def chkXlsOrderUniq(self, xlsPath):\n # 将数据库中所有的订单号存入数组orderIdLst中\n sql = 'select orderId from orderInfo where isDel = 0'\n orderIdRes = self.sql_operation(sql, -1)\n orderIdLst = []\n for orderId in orderIdRes:\n orderIdLst.append(str(orderId[0]).strip())\n # 获取xls中所有订单号\n wb = xlrd.open_workbook(xlsPath)\n # * 打开第一个sheet\n ws = wb.sheet_by_index(0)\n cnt = 0\n for line in range(1, ws.nrows):\n # 获取订单号\n colValue = str(ws.cell_value(rowx=line, colx=5)).strip()\n if colValue in orderIdLst:\n print(xlsPath, '数据库存在相同订单号', colValue, '第', line + 1, '行')\n cnt += 1\n else:\n if cnt > 0:\n print(xlsPath, '在订单号重复的表格中竟然发现订单号[{0}]竟然没有插入数据里...'.format(colValue))\n orderList = ws.row_values(line)\n self.insertOrder(orderList, xlsPath)\n print('呜呜,既然被发现了,只能老老实实的插进数据库里~~~')\n return cnt\n\n # 10. 数据导入\n def importData(self, xlsPath):\n if self.getSystemPlatform() == 'Windows':\n xlsName = str(xlsPath).split('\\\\')[-1]\n else:\n xlsName = str(xlsPath).split('/')[-1]\n wb = xlrd.open_workbook(xlsPath)\n # * 打开第一个sheet\n ws = wb.sheet_by_index(0)\n # * 从第二行开始导入数据\n dataImportNum = 0\n if self.data_format_check(xlsPath) == 0 and self.chkXlsOrderUniq(xlsPath) == 0:\n for line in range(1, ws.nrows):\n # * 获取当前行数据\n rowList = ws.row_values(line)\n # * 校验当前行指定范围列数据是否完整\n # 日期、经手人、店铺名称、宝贝名称、关键词、旺旺ID、订单号、客单价、佣金\n try:\n sqlFormat = 'insert into orderInfo(shopName,goodsName,goodsKey,wangwangId,orderId,goodsPrice,goodsYj,redPackets,ssyj,handlerName,opWechatId,custName,date,note) values({0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13})'\n shopName = '\\'' + str(rowList[1]) + '\\''\n goodsName = '\\'' + str(rowList[2]) + '\\''\n goodsKey = '\\'' + str(rowList[3]) + '\\''\n wangwangId = '\\'' + str(rowList[4]).strip() + '\\''\n orderId = '\\'' + str(rowList[5]).strip() + '\\''\n goodsPrice = rowList[6]\n goodsYj = rowList[7]\n redPackets = rowList[8]\n ssyj = rowList[9]\n handlerName = '\\'' + str(rowList[10]) + '\\''\n opWechatId = '\\'' + str(rowList[11]) + '\\''\n custName = '\\'' + str(rowList[12]) + '\\''\n date = '\\'' + str(re.compile('^\\d{4}-\\d{2}-\\d{2}').findall(xlsName)[0]) + '\\''\n try:\n note = '\\'' + str(rowList[14]) + '\\''\n except Exception as e:\n print(xlsPath, '第{0}行获取备注列数据异常'.format(line + 1),e)\n note = '\\'\\''\n except Exception as e:\n print(xlsPath,'第{0}行数据异常'.format(line + 1),e)\n return 0\n sql = sqlFormat.format(shopName, goodsName, goodsKey, wangwangId, orderId, goodsPrice, goodsYj,\n redPackets, ssyj, handlerName, opWechatId, custName, date,note)\n # 根据订单号检查数据,如果不重复,则将表格中的数据插入数据库;0不存在 1存在\n try:\n # print('插入数据库……', sql)\n self.sql_operation(sql)\n dataImportNum += 1\n except Exception as e:\n print(xlsName, '有毛病,插入数据库异常')\n return 0\n print(xlsName, '成功导入{0}条数据'.format(dataImportNum))\n return dataImportNum\n\n # 11. 店铺名&旺旺ID唯一检测\n\n # 12. 更新店铺名\n\n # 13. 删除重复的xls文件\n def delRepeName(self, xlsPath, xlsxList):\n if self.getSystemPlatform() == 'Windows':\n xlsName = str(xlsPath).split('\\\\')[-1]\n else:\n xlsName = str(xlsPath).split('/')[-1]\n if xlsName + 'x' in xlsxList:\n os.remove(xlsPath)\n print('已删除', xlsPath)\n\n # 14. 取出文件中第一列的值\n def getColValues(self, xlsPath, col=1):\n wbb = load_workbook(xlsPath)\n wss = wbb.active\n # 删除第一列【时间】数据\n kw = str(wss.cell(1, col).value).strip()\n wbb.close()\n return kw\n\n # 15. 写入数据到excel\n def writeData2Xls(self, xlsPath, value, row=1, col=1):\n try:\n wbb = load_workbook(xlsPath)\n wss = wbb.active\n # 写入数据内容到单元格中\n wss.cell(row, col).value = value\n wbb.save(xlsPath)\n wbb.close()\n except Exception as e:\n print('写入数据异常', e)\n return 0\n else:\n return 1\n\n # 16. 插入新列\n def insertColum(self, xlsPath, col):\n try:\n wbb = load_workbook(xlsPath)\n wss = wbb.active\n # 插入新列\n wss.insert_cols(idx=col)\n wbb.save(xlsPath)\n wbb.close()\n except Exception as e:\n print('插入列异常', e)\n return 0\n else:\n return 1\n\n # 17. 删除空行\n def delteBlankRow(self, xlsPath):\n try:\n wbb = load_workbook(xlsPath)\n wss = wbb.active\n # 写入数据内容到单元格中\n for row in range(1, wss.max_row + 1):\n rowList = []\n for col in range(1, wss.max_column + 1):\n if wss.cell(row=row, column=col).value != None:\n rowList.append(wss.cell(row=row, column=col).value)\n if len(rowList) <= 1 or 'SUM' in str(rowList):\n print(xlsPath, '第', row, '行为空,已删除', rowList)\n wss.delete_rows(idx=row)\n wbb.save(xlsPath)\n wbb.close()\n return -1\n else:\n pass\n # print(xlsPath,rowList)\n wbb.save(xlsPath)\n wbb.close()\n except Exception as e:\n print('删除列异常', e)\n return -1\n else:\n return 0\n\n # 18. 根据规则表格完善\n def completeForm(self, xlsPath, col, value):\n try:\n wbb = load_workbook(xlsPath)\n wss = wbb.active\n # 写入数据内容到单元格中,从第2行开始填充数据\n for row in range(2, wss.max_row + 1):\n # 红包及其他\n if wss.cell(row=row, column=col).value == None and col == 9:\n wss.cell(row=row, column=col).value = 0\n # 店铺名称\n elif wss.cell(row=row, column=col).value == None and col == 2:\n wss.cell(row=row, column=col).value = value\n # 刷手佣金\n elif wss.cell(row=row, column=col).value == None and col == 10:\n wss.cell(row=row, column=col).value = 0\n # 经手人\n elif wss.cell(row=row, column=col).value == None and col == 11:\n wss.cell(row=row, column=col).value = value\n # 操作人微信\n elif wss.cell(row=row, column=col).value == None and col == 12:\n wss.cell(row=row, column=col).value = value\n # 客户名称\n elif col == 13:\n wss.cell(row=row, column=col).value = value\n # 日期\n elif col == 14:\n wss.cell(row=row, column=col).value = value\n wbb.save(xlsPath)\n wbb.close()\n except Exception as e:\n print('插入列异常', e)\n return 0\n else:\n return 1\n\n # 19. 删除订单号为空或订单号重复的行\n def delBlankOrderRow(self, xlsPath):\n while (True):\n # 接收错误行号\n line = self.chkRepeOrderInXls(xlsPath)\n if line > 0:\n try:\n wbb = load_workbook(xlsPath)\n wss = wbb.active\n # 删除错误行\n wss.delete_rows(idx=line)\n print('delete', xlsPath, '第', line, '行')\n wbb.save(xlsPath)\n except Exception as e:\n print('删除列异常', e)\n wbb.close()\n finally:\n wbb.close()\n else:\n break\n\n # 20. 数据规范检查\n def data_format_check(self, xlsPath):\n wb = xlrd.open_workbook(xlsPath)\n # * 打开第一个sheet\n ws = wb.sheet_by_index(0)\n for line in range(1, ws.nrows):\n # * 获取当前行数据\n rowList = list(ws.row_values(line))\n if rowList[5] == '':\n print(xlsPath, '第', line + 1, '行', '第', 6, '列数据为空!')\n return -1\n for i in range(5, 10):\n if not str(rowList[i]).replace('.', '').isdigit():\n print('错误: 第{0}行第{1}列数据不规范,含有非数字或小数点字符,或者为空!'.format(line + 1, i + 1))\n return -2\n return 0\n\n # 21. 检测单张表是否有重复订单号,正常返回0,异常返回订单号所在行号\n def chkRepeOrderInXls(self, xlsPath):\n try:\n wb = xlrd.open_workbook(xlsPath)\n ws = wb.sheet_by_index(0)\n lstTmp = []\n for line in range(1, ws.nrows):\n if ws.cell(line, 5).value not in lstTmp and ws.cell(line, 5).value != '':\n lstTmp.append(ws.cell(line, 5).value)\n elif ws.cell(line, 5).value == '':\n print(xlsPath, '订单号为空,第', line + 1, '行')\n return line + 1\n else:\n print(xlsPath, '有订单号重复,第', line + 1, '行')\n return line + 1\n except Exception as e:\n print(xlsPath, '捕捉到打开表异常', e)\n return -1\n return 0\n\n # 22. 插入单条订单数据\n def insertOrder(self, orderList, xlsPath):\n if self.getSystemPlatform() == 'Windows':\n xlsName = str(xlsPath).split('\\\\')[-1]\n else:\n xlsName = str(xlsPath).split('/')[-1]\n rowList = orderList\n # * 校验当前行指定范围列数据是否完整\n # 日期、经手人、店铺名称、宝贝名称、关键词、旺旺ID、订单号、客单价、佣金\n sqlFormat = 'insert into orderInfo(shopName,goodsName,goodsKey,wangwangId,orderId,goodsPrice,goodsYj,redPackets,ssyj,handlerName,opWechatId,custName,date) values({0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12})'\n shopName = '\\'' + str(rowList[1]) + '\\''\n goodsName = '\\'' + str(rowList[2]) + '\\''\n goodsKey = '\\'' + str(rowList[3]) + '\\''\n wangwangId = '\\'' + str(rowList[4]).strip() + '\\''\n orderId = '\\'' + str(rowList[5]).strip() + '\\''\n goodsPrice = rowList[6]\n goodsYj = rowList[7]\n redPackets = rowList[8]\n ssyj = rowList[9]\n handlerName = '\\'' + str(rowList[10]) + '\\''\n opWechatId = '\\'' + str(rowList[11]) + '\\''\n custName = '\\'' + str(rowList[12]) + '\\''\n date = '\\'' + str(re.compile('^\\d{4}-\\d{2}-\\d{2}').findall(xlsName)[0]) + '\\''\n sql = sqlFormat.format(shopName, goodsName, goodsKey, wangwangId, orderId, goodsPrice, goodsYj,\n redPackets, ssyj, handlerName, opWechatId, custName, date)\n # 根据订单号检查数据,如果不重复,则将表格中的数据插入数据库;0不存在 1存在\n try:\n # print('插入数据库……', sql)\n self.sql_operation(sql)\n print('插入单条订单信息到数据库成功,订单号[{0}]'.format(orderId))\n except Exception as e:\n print('订单号[{0}]插入数据库异常'.format(orderId))\n return 0\n\n # 23. 获取系统类型\n def getSystemPlatform(self):\n plat_tuple = platform.architecture()\n system = platform.system()\n return system\n","sub_path":"TaobaoSDMS/models/ClsTaobao.py","file_name":"ClsTaobao.py","file_ext":"py","file_size_in_byte":18751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"164776967","text":"import logging\nimport os\nimport shutil\nimport sys\n\nlogging.basicConfig(stream=sys.stdout, level=logging.INFO)\nLOG = logging.getLogger(__name__)\n\nPATH = \"../../../EVA2_8Sensoren_CronosFlex_Conv_Clean/\"\nSAVE_PATH = \"../../combined\"\nHEALTHY_INTER_SAVE_PATH = os.path.join(SAVE_PATH, 'healthy')\nBAD_INTER_SAVE_PATH = os.path.join(SAVE_PATH, 'bad')\n\n\ndef join_combined_into_one(data_path, condition):\n save_path = os.path.join(SAVE_PATH, condition)\n os.makedirs(save_path, exist_ok=True)\n concatted = open(os.path.join(save_path, \"{}-data.csv\".format(condition)), \"a\")\n files = os.listdir(data_path)\n # first file:\n print(\"Writing first csv\")\n for line in open(os.path.join(data_path, files[0])):\n concatted.write(line)\n # now the rest:\n print(\"Writing other csvs\")\n for file in files[1:]:\n print(\"Writing {}\".format(file))\n combined_csv = open(os.path.join(data_path, file))\n combined_csv.__next__() # skip the header\n for line in combined_csv:\n concatted.write(line)\n combined_csv.close() # not really needed\n print(\"Done\\n\\n\")\n concatted.close()\n\n\nFOLDERS = [\"2018-07-12_08-53-42\", \"2018-07-12_13-28-58\", \"2018-07-12_09-14-40\", '2018-07-12_13-32-39',\n \"2018-07-12_08-33-50\", \"2018-07-12_09-33-37\", \"2018-07-12_13-48-22\"]\n\nhealthy_folders = [\"2018-07-12_08-53-42\", \"2018-07-12_09-14-40\", \"2018-07-12_08-33-50\", \"2018-07-12_09-33-37\"]\nbad_folders = [\"2018-07-12_13-28-58\", '2018-07-12_13-32-39', \"2018-07-12_13-48-22\"]\n\n\ndef copy_folders(folder_group, label):\n for folder in folder_group:\n LOG.info(\"Copying combined.csv in folder: %s...\", folder)\n shutil.copyfile(os.path.join(PATH, folder, \"combined.csv\"),\n os.path.join(SAVE_PATH, label, \"{}.csv\".format(folder)))\n\n\nif __name__ == '__main__':\n copy_folders(healthy_folders, \"healthy\")\n copy_folders(bad_folders, \"bad\")\n\n join_combined_into_one(HEALTHY_INTER_SAVE_PATH, \"healthy\")\n join_combined_into_one(BAD_INTER_SAVE_PATH, \"bad\")\n","sub_path":"1DCNN_John/data_util/concat_combined.py","file_name":"concat_combined.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"318525496","text":"import os\nimport sys\nimport random\nimport time\n\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\n\nsys.path.insert(0, '.')\nsys.path.insert(0, '..')\n\nfrom torch_geometric.datasets import ModelNet10PC # noqa\nfrom torch_geometric.utils import DataLoader # noqa\nfrom torch_geometric.transform import NormalizeScale, CartesianAdj # noqa\nfrom torch_geometric.nn.modules import SplineConv # noqa\nfrom torch_geometric.nn.functional import (sparse_voxel_max_pool,\n dense_voxel_max_pool) # noqa\n\npath = os.path.dirname(os.path.realpath(__file__))\npath = os.path.join(path, '..', 'data', 'ModelNet10PC')\n\ntrain_dataset = ModelNet10PC(path, True, transform=NormalizeScale())\ntest_dataset = ModelNet10PC(path, False, transform=NormalizeScale())\ntrain_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\ntest_loader = DataLoader(test_dataset, batch_size=32)\n\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = SplineConv(1, 64, dim=3, kernel_size=5)\n self.conv2 = SplineConv(64, 64, dim=3, kernel_size=5)\n self.conv3 = SplineConv(64, 128, dim=3, kernel_size=5)\n self.fc1 = nn.Linear(8 * 128, 256)\n self.fc2 = nn.Linear(256, 10)\n\n def pool_args(self, mean, x):\n if not self.training:\n return 1 / mean, 0\n size = 1 / random.uniform(mean - x, mean + x)\n start = random.uniform(-1 / (mean - x), 0)\n return size, start\n\n def forward(self, data):\n # data.input = F.elu(self.conv1(data.adj, data.input))\n size, start = self.pool_args(13, 5)\n data, _ = sparse_voxel_max_pool(data, size, start, CartesianAdj())\n\n data.input = F.elu(self.conv1(data.adj, data.input))\n size, start = self.pool_args(7, 3)\n data, _ = sparse_voxel_max_pool(data, size, start, CartesianAdj())\n\n data.input = F.elu(self.conv2(data.adj, data.input))\n size, start = self.pool_args(5, 2)\n data, _ = sparse_voxel_max_pool(data, size, start, CartesianAdj())\n\n data.input = F.elu(self.conv3(data.adj, data.input))\n data, _ = dense_voxel_max_pool(data, 1 / 2, 0, 1)\n\n x = data.input.view(-1, self.fc1.weight.size(1))\n x = F.elu(self.fc1(x))\n x = F.dropout(x, training=self.training)\n x = self.fc2(x)\n return F.log_softmax(x, dim=1)\n\n\nmodel = Net()\nif torch.cuda.is_available():\n model.cuda()\n\noptimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n\n\ndef train(epoch):\n model.train()\n\n if epoch == 8:\n for param_group in optimizer.param_groups:\n param_group['lr'] = 0.0001\n\n for data in train_loader:\n data = data.cuda().to_variable()\n optimizer.zero_grad()\n t_forward = time.perf_counter()\n output = model(data)\n loss = F.nll_loss(output, data.target)\n torch.cuda.synchronize()\n t_forward = time.perf_counter() - t_forward\n t_backward = time.perf_counter()\n loss.backward()\n torch.cuda.synchronize()\n t_backward = time.perf_counter() - t_backward\n optimizer.step()\n\n\ndef test(epoch, loader, dataset, str):\n model.eval()\n correct = 0\n\n for data in loader:\n data = data.cuda().to_variable(['input'])\n pred = model(data).data.max(1)[1]\n correct += pred.eq(data.target).sum()\n\n print('Epoch:', epoch, str, 'Accuracy:', correct / len(dataset))\n\n\nfor epoch in range(1, 21):\n train(epoch)\n test(epoch, train_loader, train_dataset, 'Train')\n test(epoch, test_loader, test_dataset, 'Test')\n","sub_path":"alpha/modelnet10_pc.py","file_name":"modelnet10_pc.py","file_ext":"py","file_size_in_byte":3600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"440099278","text":"from collections import Counter\r\n\r\ndef count_words(path):\r\n \r\n txt = open(path, 'r')\r\n #txt = open('E:\\Pyth0n\\python\\modules\\soome.txt', 'r')\r\n text = txt.read()\r\n \r\n word_list = []\r\n for word in text.split(): #в переменную ворд записать каждое слово с txt\r\n clear_word = \"\" #сюда будут записаны только буквы\r\n for letter in word: #каждое слово разбиваем на символы\r\n if letter.isalpha(): #если символ с алфавита, записываем его в letter\r\n clear_word += letter.lower() #записываем буквы в clear_word\r\n word_list.append(clear_word) #записываем наши \"чистые\" слова в массив\r\n txt.close\r\n print(Counter(word_list))\r\n \r\n\r\ncount_words(input(\"Введите путь файла\"))","sub_path":"Repeat_word_counter.py","file_name":"Repeat_word_counter.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"441574573","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy.http import Request\nimport urllib.request\nfrom jgdqedu.items import JgdqeduItem \nimport configparser\nconfig = configparser.ConfigParser()\nconfig.read('/opt/spider-exam/scrapy/jgdqedu/config.ini')\n\n\nclass KejiSpider(scrapy.Spider):\n name = \"keji\"\n allowed_domains = [\"jgdqedu.cn\"]\n start_urls = ['http://jgdqedu.cn/']\n\n def parse(self, response):\n listpage='http://www.jgdqedu.cn/science/'\n yield Request(url=listpage,callback=self.next)\n\n def next(self,response):\n print('处理列表页地址:')\n #list_page = response.xpath(\"//div[@class='list-text']/ul/li/a/@href\").extract()\n ini_list=config.get(\"jgdqedu\",\"list_page\")\n list_page =response.xpath(ini_list).extract()\n for i in range(0,len(list_page)-10):\n thisurl=('http://jgdqedu.cn'+list_page[i])\n #print(thisurl)\n yield Request(url=thisurl,callback=self.page)\n def page(self,response):\n item = JgdqeduItem()\n #item['title'] = response.xpath('//h1/text()').extract()\n ini_title=config.get(\"jgdqedu\",\"title\")\n item['title'] =response.xpath(ini_title).extract()\n item['url']=response.url\n item['catalog']='科技'\n #item['content']=response.xpath(\"//div[@class='content']\").extract()\n ini_content=config.get(\"jgdqedu\",\"content\")\n item['content']=response.xpath(ini_content).extract()\n yield item\n","sub_path":"scrapy/jgdqedu_keji/jgdqedu/spiders/keji.py","file_name":"keji.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"238103742","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# solvers for multidomain with fat\n\nimport sys\nimport numpy as np\nimport subprocess\nimport datetime\nimport time\nfrom cycler import cycler\nimport os\nimport pandas_utility\n\ninput_filename = \"logs/log_resolution1.csv\"\nlist_columns = False\nshow_plots = True\n\n# load matplotlib\nimport matplotlib\nif not show_plots:\n matplotlib.use('Agg')\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\n# define global plotting parameters\nmatplotlib.rcdefaults()\nplt.rcParams.update({'font.size': 16})\nplt.rcParams['lines.linewidth'] = 2\n\ndf = pandas_utility.load_df(input_filename)\n\n# filter data\ndf = df.loc[df['nIterations_multidomainLinearSolver'] != 0] # exclude runs where solver diverged (no number of iterations)\n#df = df.loc[df['nIterations_multidomainLinearSolver'] < 1000]\n\ntry:\n df['duration_init'] = df['totalUsertime'] - df['duration_total'] + df['durationParaview3DInit'] + df['durationParaview1DInit']\nexcept:\n df['duration_init'] = 0\n\n# Info about the data structure\n#print(\"df info:\")\n#df.info()\n#print(df.head())\n\n# set options for console display\npd.set_option('display.max_rows', 500)\npd.set_option('display.max_columns', 500)\npd.set_option('display.width', 1000)\npd.set_option('display.max_colwidth', 100)\n\ndef merge_dicts(x, y):\n z = x.copy() # start with x's keys and values\n z.update(y) # modifies z with y's keys and values & returns None\n return z\n\ndef plot(df, items):\n scenario_names = [s for s in df['scenarioName'].unique() if not isinstance(s,float) and not \"preonly_lu\" in s]\n \n print(scenario_names)\n df = df.groupby(['scenarioName', 'multidomainLinearSolver_preconditionerType']).agg(items)\n \n lines_runtime = {}\n lines_n_iterations = {}\n \n print(\"plot df\")\n # collect lines for plot\n for scenario_name in scenario_names:\n \n print(\"scenario_name: {}\".format(scenario_name))\n \n # example for scenario_name:\n # gmres_bjacobi_dt0.001_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse_10mus\n pos = scenario_name.rfind(\"_\")\n \n row_name = scenario_name[0:pos]\n n_mus = (int)(scenario_name[pos+1:scenario_name.find(\"mus\")])\n value = df.loc[scenario_name][\"duration_multidomain\"]\n n_iterations = (float)(df.loc[scenario_name][\"nIterations_multidomainLinearSolver\"])\n \n if row_name not in lines_runtime:\n lines_runtime[row_name] = [np.nan,np.nan,np.nan,np.nan]\n if row_name not in lines_n_iterations:\n lines_n_iterations[row_name] = [np.nan,np.nan,np.nan,np.nan]\n \n #if n_mus == 4: i = 0\n if n_mus == 6: i = 0\n elif n_mus == 8: i = 1\n elif n_mus == 10: i = 2\n elif n_mus == 12: i = 3\n lines_runtime[row_name][i] = value\n \n print(n_iterations)\n if n_iterations != 0:\n lines_n_iterations[row_name][i] = n_iterations\n \n print(\"lines\")\n print(lines_runtime.keys())\n label = {\n 'gmres_boomeramg_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse': \"BoomerAMG\",\n 'gmres_boomeramg_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse': \"BoomerAMG (symmetric)\",\n 'gmres_euclid_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse': \"Euclid\",\n 'gmres_euclid_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse': \"Euclid (symmetric)\",\n 'gmres_bjacobi_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse': \"Block Jacobi\",\n 'gmres_bjacobi_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse': \"Block Jacobi (symmetric)\",\n 'gmres_sor_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse': \"Parallel SOR\",\n 'gmres_sor_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse': \"Parallel SOR (symmetric)\", \n 'gmres_pilut_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse': \"Pilut\",\n 'gmres_pilut_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse': \"Pilut (symmetric)\",\n 'gmres_none_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse': \"No preconditioner\",\n 'gmres_none_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse': \"No preconditioner (symmetric)\",\n 'gmres_sor,ilu_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse': \"Block Gauss-Seidel with ILU\",\n 'gmres_bjacobi,gamg_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse': \"Block Jacobi with AMG\",\n 'gmres_bjacobi,cg-euclid_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse': \"Block Jacobi with Euclid\",\n 'gmres_boomeramg,hypre_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse': 'BoomerAMG w/ coord.',\n 'gmres_boomeramg,hypre_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse': 'BoomerAMG w/ coord (symmetric)',\n 'gmres_bjacobi,hypre_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse': 'Block Jacobi + AMG',\n }\n \n #order = sorted(lines.iteritems())\n \n order = [\n 'gmres_none_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse',# \"No preconditioner\",\n 'gmres_pilut_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse',# \"Pilut\",\n 'gmres_pilut_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse',# \"Pilut (symmetric)\",\n 'gmres_boomeramg_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse',# \"BoomerAMG\",\n 'gmres_boomeramg_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse',# \"BoomerAMG (symmetric)\",\n 'gmres_euclid_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse',# \"Euclid\",\n 'gmres_euclid_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse',# \"Euclid (symmetric)\",\n 'gmres_bjacobi_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse',# \"Block jacobi\",\n 'gmres_bjacobi_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse',# \"Block jacobi (symmetric)\",\n 'gmres_sor_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse',# \"Block Gauss-Seidel\",\n 'gmres_sor_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse',# \"Block Gauss-Seidel (symmetric)\",\n 'gmres_bjacobi,gamg_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse',# \"Block Jacobi with AMG\",\n 'gmres_bjacobi,cg-euclid_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse', #Block Jacobi with Euclid\",\n 'gmres_boomeramg,hypre_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse', #'BoomerAMG w/ coord.',\n 'gmres_boomeramg,hypre_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symTrue_lumpFalse', #'BoomerAMG w/ coord (symmetric)',\n 'gmres_bjacobi,hypre_dt0.0005_atol1e-15_rtol1e-15_theta1.0_symFalse_lumpFalse', #'Block Jacobi + AMG',\n ]\n \n mylabels = None\n \n \n #plt.style.use('ggplot')\n prop_cycle = plt.rcParams['axes.prop_cycle']\n colors = prop_cycle.by_key()['color']\n \n #colors = [\"r\",\"m\",\"c\",\"b\"]\n #linestyle_cycler = cycler.cycler('linestyle',['-','--',':','-.'])\n # (cycler.cycler('color', [\"k\",(0.3,0.3,0.7),(0.7,0.7,1.0), \"r\", \"y\"])+cycler.cycler('linestyle', ['-', '--', ':', '-', '-'])))\n plt.rc('axes', prop_cycle=(cycler('color', [colors[0],colors[1],colors[1],colors[2],colors[2],colors[3],colors[3],colors[4],colors[4],colors[5],colors[5],colors[6],colors[7],colors[8],colors[8],colors[9]]) +\n cycler('linestyle', ['-', '-', '--', '-', '--', '-', '--', '-', '--', '-', '--','-','-','-','--','-']) +\n cycler('marker', ['o', 'o', 'x', 'o', 'x', 'o', 'x', 'o', 'x', 'o', 'x', 'o', 'o', 'o', 'x', 'o'])\n ))\n #plt.rc('axes', prop_cycle=(\"cycler('color', 'rgb') + cycler('linestyle', ['-', '-', ':'])\"))\n \n # -------------------------------------\n # plot runtime\n fig = plt.figure(figsize=(12,5))\n for name in order:\n \n x_values = [6,8,10,12]\n y_values = lines_runtime[name]\n \n print(label[name])\n \n plt.plot(x_values, y_values, label=label[name])\n \n ax = plt.gca()\n ax.set_xticks([6,8,10,12])\n ax.set_xticklabels([\"6\\n36\",\"8\\n48\",\"10\\n60\",\"12\\n72\"])\n ax.set_yscale('log')\n ax.grid(which='major')\n ax.set_xlabel('number of motor units\\nnumber of processes')\n ax.set_ylabel('runtime of solver [s]')\n if mylabels is not None:\n ax.legend(labels=mylabels)\n ax.legend(bbox_to_anchor=(1.0, 1.0))\n \n fig.subplots_adjust(bottom=0.2, right=0.7)\n \n if show_plots:\n pass\n #plt.show()\n else:\n plt.tight_layout()\n plot_filename = \"{}_runtime.png\".format(title.replace(\" \", \"\").replace(\"/\", \"\"))\n plt.savefig(plot_filename)\n print(\"Created \\\"{}\\\".\".format(plot_filename))\n \n # -------------------------------------\n # plot number of iterations\n fig = plt.figure(figsize=(12,5))\n for name in order:\n \n x_values = [6,8,10,12]\n y_values = lines_n_iterations[name]\n print(name,y_values)\n \n plt.plot(x_values, y_values, label=label[name])\n \n ax = plt.gca()\n ax.set_xticks([6,8,10,12])\n ax.set_xticklabels([\"6\\n36\",\"8\\n48\",\"10\\n60\",\"12\\n72\"])\n ax.set_yscale('log')\n ax.grid(which='major')\n ax.set_xlabel('number of motor units\\nnumber of processes')\n ax.set_ylabel('number of iterations')\n if mylabels is not None:\n ax.legend(labels=mylabels)\n ax.legend(bbox_to_anchor=(1.0, 1.0))\n \n fig.subplots_adjust(bottom=0.2, right=0.7)\n \n if show_plots:\n plt.show()\n else:\n plt.tight_layout()\n plot_filename = \"{}_iterations.png\".format(title.replace(\" \", \"\").replace(\"/\", \"\"))\n plt.savefig(plot_filename)\n print(\"Created \\\"{}\\\".\".format(plot_filename))\n \n \n \ndef output(df, title, columns_to_print, columns_to_plot, plot_labels=None):\n \"\"\"\n print values to console and produce plot\n \"\"\"\n columns_to_extract = list(set(columns_to_plot + columns_to_print + [\"totalUsertime\", \"durationReadGeometry\", \"durationSetStiffnessMatrix\", \n \"durationOnlyWrite\", \"durationAssembleBoundaryConditions\", \"durationInitCellml\", \"durationComputeMappingBetweenMeshes\",\n \"durationMap\"]))\n\n # create auxiliary columns that will be computed\n if not \"memoryResidentSet\" in df:\n df[\"memoryResidentSet\"] = 0\n df[\"n\"] = 0\n\n # remove column that are not present in the df\n for column in list(columns_to_extract):\n if column not in df:\n print(\"Note: remove invalid column {} from columns_to_extract\".format(column))\n columns_to_extract.remove(column)\n \n for column in list(columns_to_print):\n if column not in df:\n print(\"Note: remove invalid column {} from columns_to_print\".format(column))\n columns_to_print.remove(column)\n \n for column in list(columns_to_plot):\n if column not in df:\n print(\"Note: remove column {} from columns_to_plot\".format(column))\n columns_to_plot.remove(column)\n\n # select the captions for the table\n table_shortnames = [column_shortnames[long_name] if long_name in column_shortnames else long_name for long_name in columns_to_print]\n \n # define items to be printed, the columns \"n\" and \"memoryResidentSet\" need to be already present in the df\n items = merge_dicts(\n {column_name: lambda v: (np.mean(v) if v.dtype == np.float64 else str(v.iloc[0]) ) for column_name in columns_to_extract},\n {'n': np.size, \"memoryResidentSet\": lambda v: \"{:.3f} GB\".format(np.mean(v)/(1024.**3))}\n )\n\n print(\"-\"*120)\n print(title)\n print(df.groupby(['scenarioName','multidomainLinearSolver_preconditionerType','nRanks']).agg(items).rename(columns = column_shortnames)[table_shortnames])\n print(\"-\"*120)\n\n # create plot\n plot(df, items)\n\n# ------------------------------------------------\n# define shortnames for the table, each line is\n# long_name : short_name\ncolumn_shortnames = {\n \"totalUsertime\": \"user\",\n \"duration_total\": \"total comp.\",\n \"duration_0D\": \"0D\",\n \"duration_1D\": \"1D\",\n \"duration_init\": \"duration_init\",\n \"duration_bidomain\": \"bidomain\",\n \"duration_mechanics\": \"mechanics\",\n \"duration_multidomain\": \"multidomain\",\n \"durationAssembleBoundaryConditions\": \"initBC\",\n \"durationSetStiffnessMatrix\": \"stiffness\",\n \"durationComputeMappingBetweenMeshes\": \"compMap\",\n \"durationMap\": \"map\",\n \"durationReadGeometry\": \"read\",\n \"durationOnlyWrite\": \"write\",\n \"durationInitCellml\": \"initCell\",\n \"memoryResidentSet\": \"mem\",\n \"meta_partitioning\": \"subdomains\",\n \"nIterations_multidomainLinearSolver\": \"niter\",\n}\n\n# define columns for table and plot (long names)\ncolumns_to_print = [\"meta_partitioning\", \"~nDofs3Dmesh\", \"duration_total\", \"duration_0D\", \"duration_1D\", \"duration_bidomain\", \"duration_multidomain\", \"duration_mechanics\", \"duration_init\", \"durationOnlyWrite\", \"nIterations_multidomainLinearSolver\", \"memoryResidentSet\", \"n\"]\ncolumns_to_plot = [\"duration_total\", \"duration_init\", \"durationOnlyWrite\", \"duration_0D\", \"duration_1D\", \"duration_bidomain\", \"duration_multidomain\", \"duration_mechanics\"]\n\nplot_labels = [\"total\", \"initialization\", \"write VTK files\", \"0D model\", \"1D model\", \"3D model\"]\n\ntitle = input_filename\noutput(df, title, columns_to_print, columns_to_plot, plot_labels)\n\n","sub_path":"opendihu/07_multidomain_solver/plot_resolution1.py","file_name":"plot_resolution1.py","file_ext":"py","file_size_in_byte":12723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"436672645","text":"import socket,os,time,hashlib\nfrom conf import settings\nfrom modules import display\nfrom modules import log\n\n\nHome = ''\nFlagLogin = False\nUser = ''\nCommand = []\nsk = None\ndef run():\n print('Welcome!')\n print(display.HelpMenu)\n login()\n init()\n while not FlagLogin:\n print(Home)\n print(FlagLogin)\n print(User)\n print(sk)\n try:\n while True:\n command = input(\"[server@%s]:\"%User).strip()\n Command = command.split()\n if Command[0].startswith('rz'): # upload file request\n file_path = \"%s/%s\"%(Home,Command[1])\n if os.path.isfile(file_path):\n sk.send(command.encode())\n data = sk.recv(1024)\n FileSize = os.stat(file_path).st_size\n sk.send(str(FileSize).encode()) # send file size\n m5 = hashlib.md5()\n with open(file_path, 'rb') as f:\n SentSize = 0\n for line in f:\n sk.send(line)\n m5.update(line)\n SentSize += len(line)\n print(\"Transfer:%s%%\"%(100*SentSize/FileSize),end='\\r')\n print('\\rCompletely!')\n # md5 = m5.encode()\n sk.send(m5.hexdigest()) # send md5 value after finish\n else:\n print(\"Invalid file!\")\n elif Command[0].startswith('sz'): #download files,continu when receive 'sz'\n sk.send(command.encode())\n data = sk.recv(1024)\n if data.decode() == 'sz':\n UpName = time.strftime(\"%Y%m%d%H%M%S:\", time.localtime()) + 'upload'\n FileSize = int(sk.recv(1024).decode())\n RecvSize = 0\n m5 = hashlib.md5()\n with open('%s/%s' % (Home, UpName), 'w') as f:\n while RecvSize < FileSize:\n size = FileSize - RecvSize\n if size < 1024:\n data = sk.recv(size)\n else:\n data = sk.recv(1024)\n m5.update(data)\n f.write(data)\n RecvSize += len(data)\n print(\"Transfer:%s%%\" % (100*RecvSize/FileSize), end='\\r')\n else:\n print('\\rCompletely!')\n md5_recv = sk.recv(1024).decode() # receive md5 check\n if md5_recv == m5.hexdigest():\n os.rename(\"%s/%s\" % (Home, UpName),\n \"%s/%s\" % (Home, Command[1])) # rename filename\n print(\"File check passed!\")\n else:\n sk.send(b'file crash!!!')\n os.remove(\"%s/%s\" % (Home, UpName))\n print(\"Remove file because check failed...\")\n else:\n print(\"Invalid filename!\")\n\n elif data == 'logout':\n FlagLogin = False\n break\n print(data)\n except Exception:\n print(\"exist exception!!!\")\n else:\n print(\"offline, use 'login' to connect server!\")\n print(Home)\n print(FlagLogin)\n print(User)\n print(\"Disconnect to server...\")\n\n\ndef login():\n import json\n # global FlagLogin\n # global User\n while True:\n user = input(\"username:\").strip()\n psd = input(\"passwod:\").strip()\n with open('%s/users/users.db', 'r') as f:\n users = json.load(f)\n if user in users:\n if psd == users[user]:\n print(\"login successful!\")\n FlagLogin = True\n User = user\n\n else:\n print(\"Incorrect password!\")\n else:\n print(\"No such user!\")\n\ndef init():\n '''\n init users dir,socket\n :return:\n '''\n # global Home\n sk = socket.socket()\n sk.connect((settings.ADDR,settings.PORT))\n print(\"\\033[1;34;1mConnected to socket!\\033[0m\", )\n path = \"%s/client/%s\"%(settings.DATABASE,User)\n if not os.path.exists(path):\n os.makedirs(path)\n print(\"Created new dir for user!\")\n Home = path\n\n\n\n","sub_path":"Senior FTP/modules/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"442670280","text":"#!/usr/bin/python\n\n\nfrom __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\nANSIBLE_METADATA = {\n 'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'community'\n}\n\nDOCUMENTATION = '''\n---\nmodule: read_resources\n\nshort_description: Import OpenStack network\n\nversion_added: \"2.9.0\"\n\nauthor: \"OpenStack tenant migration tools (@os-migrate)\"\n\ndescription:\n - \"Read an OS-Migrate YAML resources file structure\"\n\noptions:\n path:\n description:\n - Resources YAML file to read.\n required: true\n type: str\n'''\n\nEXAMPLES = '''\n- name: Read resources from /opt/os-migrate/networks.yml\n os_migrate.os_migrate.read_resources:\n path: /opt/os-migrate/networks.yml\n register: read_networks\n\n- name: Debug-print resources\n debug:\n msg: \"{{ read_networks.resources }}\"\n'''\n\nRETURN = '''\nresources:\n description: List of resources deserialized from YAML file\n returned: success\n type: complex\n contains:\n type:\n description: Type of the resource.\n returned: success\n type: str\n params:\n description: Resource parameters important for import.\n returned: success\n type: dict\n info:\n description: Additional resource information, not needed for import.\n returned: success\n type: dict\n'''\n\nfrom ansible.module_utils.basic import AnsibleModule\n\nfrom ansible_collections.os_migrate.os_migrate.plugins.module_utils import filesystem\n\n\ndef run_module():\n module_args = dict(\n path=dict(type='str', required=True),\n )\n\n result = dict(\n # This module doesn't change anything.\n changed=False,\n )\n\n module = AnsibleModule(\n argument_spec=module_args,\n # Module doesn't change anything, we can let it run as-is in\n # check mode.\n supports_check_mode=True,\n )\n\n struct = filesystem.load_resources_file(module.params['path'])\n result['resources'] = struct['resources']\n\n module.exit_json(**result)\n\n\ndef main():\n run_module()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"os_migrate/plugins/modules/read_resources.py","file_name":"read_resources.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"211845425","text":"from django.shortcuts import render\nfrom .forms import Trains\nfrom .api_handler import getStation,getTrains\n\ndef find_trains(request):\n if request.method == 'POST':\n filled_form = Trains(request.POST)\n if filled_form.is_valid():\n src_stations = getStation(filled_form.cleaned_data['source'])\n dest_stations = getStation(filled_form.cleaned_data['dest'])\n button_text = 'Find Trains'\n find_train_form = Trains()\n station_select = False\n return render(request,'rail_booking/find_trains.html',{'form':find_train_form,'src_stations':src_stations,'dest_stations':dest_stations,'button_text':button_text,'station_select':station_select})\n else:\n find_train_form = Trains()\n station_select = True\n button_text = 'Find city stations'\n return render(request,'rail_booking/find_trains.html',{'form':find_train_form,'button_text':button_text,'station_select':station_select})\n\ndef get_trains(request):\n if request.method == 'POST':\n filled_form = Trains(request.POST)\n if filled_form.is_valid():\n print(\"Entered\")\n trains = getTrains(filled_form.cleaned_data['source'],filled_form.cleaned_data['dest'],'24/06/2017')\n return render(request,'rail_booking/get_trains.html',{'trains':trains})","sub_path":"rail_booking/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"521514788","text":"# gabbar\n\n\nfrom sklearn import svm\nfrom sklearn.externals import joblib\nimport os\n\nhas_legs = False\n\ndef changeset_to_data(changeset):\n \"\"\"Convert changeset dictionary into an array with required features.\n\n Parameters\n ----------\n changeset: dict\n\n Returns\n -------\n data: tuple\n Tuple of data items\n \"\"\"\n return [\n changeset['create'],\n changeset['modify'],\n changeset['delete']\n ]\n\ndef load_model():\n directory = os.path.dirname(os.path.realpath(__file__))\n filename = 'models/gabbar.pkl'\n model = os.path.join(directory, filename)\n return joblib.load(model)\n\ndef predict(model, data):\n \"\"\"Returns model prediction for data.\n\n Parameters\n ----------\n model: object\n Trained machine learning classifier\n data: tuple\n Tuple of data items\n Returns\n -------\n prediction: int\n -1 for outlier, +1 for inlier\n \"\"\"\n prediction = model.predict(data)\n return prediction[0]\n","sub_path":"gabbar/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"32743149","text":"import numpy as np\nfrom pathlib import Path\n\nfrom opdxread import opdxtype\n\nfrom typing import Any, Dict\n\n\nclass OPDxFile(object):\n def __init__(self, path: Path):\n self.path = path\n self.filesize = path.stat().st_size\n\n self.data: Dict[str, Any] = {}\n\n self.read()\n\n def read(self):\n with self.path.open(\"rb\") as fp:\n assert fp.read(12) == b\"VCA DATA\\x01\\x00\\x00\\x55\"\n\n while fp.tell() < self.filesize:\n item = opdxtype.NamedValue(fp)\n if item.value is not None:\n self.data[item.name] = item.value\n\n def get_1d_linear_fit(self, r: float = None, m: float = None) -> np.ndarray:\n extent = self.data[\"1D_Data\"][\"Raw\"][\"Extent\"].value\n x = self.data[\"1D_Data\"][\"Raw\"][\"PositionFunction\"].data\n y = self.data[\"1D_Data\"][\"Raw\"][\"Array\"].array\n ydiv = extent / y.size\n\n r = 0.0 if r is None else (r if r >= 0.0 else extent + r)\n m = extent if m is None else (m if m >= 0.0 else extent + m)\n assert m > r\n\n ir = np.clip(int(r / ydiv), 0, y.size - 1)\n im = np.clip(int(m / ydiv), 0, y.size - 1)\n\n coefs = np.polynomial.polynomial.polyfit([r, m], [y[ir], y[im]], 1)\n return np.polynomial.polynomial.polyval(x, coefs)\n\n def get_1d_data(self, r: float = None, m: float = None) -> np.ndarray:\n scale = self.data[\"1D_Data\"][\"Raw\"][\"DataScale\"].value\n x = self.data[\"1D_Data\"][\"Raw\"][\"PositionFunction\"].data\n y = self.data[\"1D_Data\"][\"Raw\"][\"Array\"].array.copy()\n if r is not None or m is not None:\n y -= self.get_1d_linear_fit(r, m)\n return np.stack((x, y * scale), axis=1)\n","sub_path":"opdxread/opdxfile.py","file_name":"opdxfile.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"465500823","text":"'''\nbubbleSort sorts an array by iterating through and swapping \nconsecutive pairs of numbers if they are out of over. This \nalgorithm will take O(n^2) time and O(n) space.\n\nCreated by Richard Shen\n'''\n\ndef bubble_sort(array):\n\n for i in reversed(range(len(array))):\n\n swaps = 0\n\n for j in range(i):\n if array[j] > array[j+1]:\n array[j], array[j+1] = array[j+1], array[j]\n swaps += 1\n\n if swaps == 0:\n return","sub_path":"sorting/bubble_sort.py","file_name":"bubble_sort.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"473652758","text":"# -*- coding: utf-8 -*-\n\"\"\"\n===============================================================================\nHodge.WaterResources, LLC\nProject Number: AD006\nProject Name: FORTmod\nDeveloped by: Matt Hodge\nType: Program\n\nCreated on Thurs Oct 18 14:00:00 2018\nLast Updated: 10/18/2018\n\nPurpose: \nThe purpose of this program is to demonstrate how to use the .pyd file created\nwith f2py for the Streeter-Phelps model created in FORTRAN. \nNotes:\nThis program includes one application of the Streeter-Phelps model. The \napplication loads the same input file used in the FORTRAN program. The results \nof the model run are saved to a text file (DO_Curve.txt) and saved to a jpg.\nHWR Disclaimer:\nThis script was created by Hodge.WaterResources, LLC (HWR). HWR makes no warranty,\nexpressed or implied, as to its usefulness or correctness.\n===============================================================================\n\"\"\"\n# import necessary modules\nimport pdb\nimport os\nimport sys\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nif __name__ == \"__main__\":\n # import Streeter-Phelps\n os.chdir(r'..\\fortran')\n sys.path.append(os.getcwd())\n import str_phps as sp\n ##--------Run From Input File-----------------\n # input file\n file_path = 'str_phps.inp'\n # load input file\n (rlen, rwid, rq, r_s, man_n, rint, wwq, rtmp, bod_k, rbod0, rdo0, wwbod0, wwdo0) = sp.str_phps_mod.read_inp(file_path)\n # change to python directory\n os.chdir(r'..\\python')\n # run FORTRAN model and return results\n (riv_x, riv_dos, riv_dod) = sp.str_phps_mod.run(rlen, rwid, rq, r_s, man_n, rint, wwq, rtmp, bod_k, rbod0, rdo0, wwbod0, wwdo0)\n riv_do = riv_dos - riv_dod\n # plot DO sag curve & DO sat\n plt.plot(riv_x, riv_do, color = 'b', linewidth = 1)\n plt.plot(riv_x, riv_dos, color = 'b', linestyle = '-.', linewidth = .5)\n plt.xlabel('Distance from WWTP (m)')\n plt.ylabel('DO (mg/L)')\n plt.title('FORTmod DO Sag Curve')\n plt.savefig('str-phps_SagCurve.png')\n plt.show()","sub_path":"python/str_phps_py_program.py","file_name":"str_phps_py_program.py","file_ext":"py","file_size_in_byte":2002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"40023457","text":"\"\"\" Description\nGiven an n x n matrix of positive and negative integers, find the submatrix with the largest possible sum.\nGiven matrix = \n[\n[1,3,-1],\n[2,3,-2],\n[-1,-2,-3]\n]\nreturn 9.\nExplanation:\nthe submatrix with the largest possible sum is:\n[\n[1,3],\n[2,3]\n]\n \"\"\"\nimport sys\n\n\nclass Solution:\n \"\"\"\n @param matrix: the given matrix\n @return: the largest possible sum\n \"\"\"\n\n def maxSubmatrix(self, matrix):\n # write your code here\n if not matrix or not matrix[0]:\n return 0\n N = len(matrix)\n total_max = -sys.maxsize\n for top in range(N):\n arr = [0 for _ in range(N)]\n for down in range(top, N):\n prefix_sum = 0\n min_sum = 0\n max_sum = -sys.maxsize\n for c in range(N):\n arr[c] += matrix[down][c]\n prefix_sum += arr[c]\n # 注意细节: 先求max, 再min.\n max_sum = max(max_sum, prefix_sum - min_sum)\n min_sum = min(min_sum, prefix_sum)\n total_max = max(max_sum, total_max)\n\n return total_max\n\n\ndef main():\n matrix = [\n [1, 3, -1],\n [2, 3, -2],\n [-1, -2, -3]\n ]\n sol = Solution()\n res = sol.maxSubmatrix(matrix)\n print(res)\n\n\nmain()\n","sub_path":"lint-944-maximum-submatrix/solution1.py","file_name":"solution1.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"432207922","text":"import json\n\nimport pymongo\n\nclient = pymongo.MongoClient('mongodb://comp9900:z12345@ds161529.mlab.com:61529/comp9900_2019')\ndb = client[\"comp9900_2019\"]\n\ncustomers_collection = db.customers_collection\nproperty_collection = db.property_collection\norder_collection = db.order_collection\n\ndef update_data(collection_name,data):\n collection_name.insert_one(data)\n return \"successful\"\n'''''\nwith open(\"orders.json\", 'r') as ff:\n context = ff.read()\n json_data = json.loads(context)\nprint(json_data)\nkeys_set = json_data.keys()\nprint(keys_set)\nfor i in keys_set:\n data = json_data[i]\n print(data)\n update_data(order_collection,data)\n\n\ndict_use = {\"average_mark\": 4.5,\n\t\t\t\"cleanliness_mark\": 4.5,\n\t\t\t\"facility_mark\": 3,\n\t\t\t\"attitude_mark\": 4,\n\t\t\t\"text\": \"I think this house not very good for me, because the hot water is not available 24 hours.\",\n\t\t\t\"photo\": None,\n\t\t\t\"date\": \"09-06-2019\"}\n\n\ndatt = property_collection.find_one({\"property_id\": '5'})\n#property_collection.update({\"property_id\": str(4)},{\"$set\": {\"comments\": dict_use}})\ncomment = datt[\"comments\"]\ncomment.append(dict_use)\nproperty_collection.update_one({\"property_id\": str(5)},{\"$set\": {\"comments\": comment}})\nprint(comment)\n'''''\n#url = \"https://maps.google.com/maps/api/geocode/json?key=AIzaSyAANyBQ6ikIoa53iMdahFL99Bjt0oBmWpc&address={address}&sensor=false\".format(address=ad)\n#data = requests.request(\"GET\",url)\n#data.json()['results'][0]['geometry']['location']","sub_path":"app/demo/anhao0522_client_v1/api/MongoDB.py","file_name":"MongoDB.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"554725047","text":"# Given a binary search tree, write a function \n# kthSmallest to find the kth smallest element in it.\n#\n\n# Note: \n# You may assume k is always valid, 1 ≤ k ≤ BST's total elements.\n\n# Example 1:\n\n# Input: root = [3,1,4,null,2], k = 1\n# Output: 1\n# Example 2:\n\n# Input: root = [5,3,6,2,4,null,null,1], k = 3\n# Output: 3 \n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\nclass Solution(object):\n def __init__(self):\n self.c = 0\n self.result = 0\n \n def find(self, root, k):\n if root:\n x = self.find(root.left, k)\n self.c += 1\n if self.c == k: \n self.result = root.val\n if self.c >= k: \n return\n self.find(root.right, k)\n \n def kthSmallest(self, root, k):\n \"\"\"\n :type root: TreeNode\n :type k: int\n :rtype: int\n \"\"\"\n self.find(root, k)\n return self.result","sub_path":"find_kth_small_in_BST.py","file_name":"find_kth_small_in_BST.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"160702081","text":"\"\"\"\nDiscription: A Python Progress Meter\nAuthor: Nianzu Ethan Zheng\nDate: 2018-1-21\nCopyright\n\"\"\"\n\nimport os\nimport pickle\nimport shutil\nimport pandas as pd\n\n\ndef make_dir(root, folder_name):\n path = os.path.join(root, folder_name)\n if not os.path.exists(path):\n os.makedirs(path)\n print(path)\n # os.chdir(path) # change to the path\n return path\n print(\"Folder has existed!\")\n return path\n\n\ndef delete_empty_dir(dir):\n if os.path.exists(dir):\n if os.path.isdir(dir):\n for d in os.listdir(dir):\n path = os.path.join(dir, d)\n if os.path.isdir(path):\n delete_empty_dir(path)\n if not os.listdir(dir):\n os.rmdir(dir)\n print(\"remove the empty dir: {}\".format(dir))\n else:\n print(\"Please start your performance!\")\n\n\ndef check_dir(path, is_restart=False):\n name = os.path.split(path)[1]\n if not os.path.exists(path):\n os.makedirs(path)\n print('Create a new folder named {}'.format(name))\n elif is_restart:\n shutil.rmtree(path)\n os.makedirs(path)\n print('The folder named {} is restarted'.format(name))\n print('The folder named {} has existed.'.format(name))\n\n\ndef pickle_load(path_name):\n with open(path_name, 'rb') as fg:\n value = pickle.load(fg)\n print(\"file has been loaded...\")\n return value\n\n\ndef pickle_save(value, name, path_name):\n with open(path_name, 'wb') as f:\n pickle.dump(value, f, protocol=pickle.HIGHEST_PROTOCOL)\n return print(\"data named {} has been saved...\".format(name))\n\nif __name__ == '__main__':\n check_dir('../Test')","sub_path":"general_spider_update/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"497776615","text":"import multiprocessing as mp\nfrom multiprocessing import Process\nfrom more_itertools import chunked\nfrom tqdm import tqdm\n\n__all__ = [\"batch_multiprocess\"]\n\ndef batch_multiprocess(function_list, n_cores=mp.cpu_count(), show_progress=True):\n \"\"\"\n Run a list of functions on `n_cores` (default: all CPU cores),\n with the option to show a progress bar using tqdm (default: shown).\n \"\"\"\n iterator = [*chunked(function_list, n_cores)]\n if show_progress:\n iterator = tqdm(iterator)\n for func_batch in iterator:\n procs = []\n for f in func_batch:\n procs.append(Process(target=f))\n for p in procs:\n p.start()\n for p in procs:\n p.join()\n\ndef _batch_multiprocess(function_list, n_cores=mp.cpu_count(), show_progress=True):\n \"\"\"\n Dummy sequential version of `batch_multiprocess` to be swapped in\n when there's an error to debug in that\n \"\"\"\n for func in function_list:\n func()\n","sub_path":"src/dx/share/multiprocessing.py","file_name":"multiprocessing.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"94871456","text":"def is_heap(i, items):\n\tif (i == 0):\n\t\treturn None\n\tif (2 * i >= len(items)):\n\t\treturn True\n\tif (items[2*i] > items[i]):\n\t\treturn False\n\tif (2 * i + 1>= len(items)):\n\t\treturn True\n\tif (items[2*i+1] > items[i]):\n\t\treturn False\n\telif (is_heap(2*i, items) == True and is_heap(2*i+1, items) == True):\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef is_heap_1(items):\n\ti = 1\n\tif (len(items) <= 2):\n\t\treturn True\n\telse:\n\t\twhile ((2 * i + 1)<= len(items)):\n\t\t\tif (items[2*i] > items[i]):\n\t\t\t\treturn False\n\t\t\tif (2 * i + 1>= len(items)):\n\t\t\t\treturn True\n\t\t\tif (items[2*i+1] > items[i]):\n\t\t\t\treturn False\n\t\t\ti = i + 1\n\t\treturn True\n\ndef test_is_heap():\n assert(is_heap(1,[]))\n assert(is_heap_1([]))\n a = [None, 100, 50, 31, 45, 48, 30]\n for i in range(1, 7):\n assert(is_heap(i, a))\n assert(is_heap_1(a))\n a.append(20)\n assert(len(a) == 8)\n for i in range(1,8):\n assert(is_heap(i, a))\n assert(is_heap_1(a))\n a[6] = 40\n assert(not is_heap_1(a))\n assert(not is_heap(1, a))\n assert(is_heap(2, a))\n assert(not is_heap(3, a))\n for i in range(4, 8):\n assert(is_heap(i, a))\n print(\"Done testing is_heap and is_heap_1\")","sub_path":"pa5/is_heap.py","file_name":"is_heap.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"440875980","text":"import os\nimport requests\nimport ConfigParser\nfrom sufa.settings import BASE_DIR\n\n\ndef verification_code_cer(request):\n\n def get_client_ip(request):\n x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n if x_forwarded_for:\n ip = x_forwarded_for.split(',')[0]\n else:\n ip = request.META.get('REMOTE_ADDR')\n return ip\n\n config_file = os.path.join(BASE_DIR, \"sufa.cnf\")\n cf = ConfigParser.ConfigParser()\n cf.read(config_file)\n\n aid = cf.get('tencent', 'aid')\n app_secret_key = cf.get('tencent', 'app_secret_key')\n\n ticket = request.data.get('ticket')\n randstr = request.dat.get('randstr')\n user_ip = get_client_ip(request)\n url = 'https://ssl.captcha.qq.com/ticket/verify'\n\n params = 'aid=' + aid + '&AppSecretKey=' + app_secret_key + '&Ticket=' + ticket + \\\n '&Randstr=' + randstr + '&UserIP=' + user_ip\n\n requests.get(url, params)\n","sub_path":"utils/tencent_verification_code.py","file_name":"tencent_verification_code.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"447588090","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # GDBFS Measure\nimport numpy as np\nimport pandas as pd\nimport math\nimport pandas as pd\n\n\n#함수 1. Sequential Forward Selection with gdbfs\ndef fit(df,target):\n \n # 단계별 선택되는 feature와 gdfs값 list []\n gdfs_by_feature = []\n chosen_features = []\n\n # feature list\n X = df.drop(target,axis=1).columns\n available_features = list(X)\n run = 0\n \n # Loop : feature가 모두 선택될 때 까지\n while len(available_features)> 0:\n\n #print(\"colList=\",available_features)\n\n run += 1\n\n # Reset best\n best_result = 0\n best_feature = ''\n\n # Loop : abailable_feature 하나씩 check\n for feature in available_features:\n\n # Create copy of already chosen features\n features_to_use = chosen_features.copy()\n features_to_use.append(feature)\n \n # gdbfs restult of features_to_sure\n result = gdbfs(df,features_to_use,target) #함수 2.\n \n # Update chosen feature and result if this feature is a new best\n if result > best_result:\n best_result = result\n best_feature = feature\n\n # record\n gdfs_by_feature.append(best_result)\n chosen_features.append(best_feature)\n available_features.remove(best_feature)\n\n # Put results in DataFrame\n results = pd.DataFrame()\n results['feature to add'] = chosen_features\n results['gdbfs'] = gdfs_by_feature\n print(results)\n \n # return max gdfs feature subset\n maxidx = results['gdbfs'].idxmax()\n return np.array(results.loc[:maxidx,['feature to add']])\n \n\n \n#함수 2. GDBFS Measure: dataframe과 feature subset, target 이름을 넣으면, GDBFS값을 return\ndef gdbfs(df,col,target):\n \n #feature subset + target list\n col.append(target)\n df = df[col]\n \n #DataFrame과 target column명을 전달하면 dic return\n dic = {}\n category = df[target].unique()\n for i in category:\n dic[i] = np.matrix(df[df[target]==i].drop(target,axis=1))\n \n # Evaluate 값 계산\n total = len(df)\n D =0\n for i in range(len(dic)-1):\n D+=(len(dic[i])+len(dic[i+1]))*(distance_min(dic[i],dic[i+1],total)) #함수 3.\n \n D/=total\n E = eveness(dic,total) #함수4.\n \n return D*E\n\n\n\n#함수3. distance_min() : class I와 class J간의 최소거리를 구하는 함수\n\n# I,J간의 최소 거리 구하는 distance_min 함수\ndef distance_min(I,J,total):\n \n # inter_dist\n ui =I.mean(axis=0)\n uj =J.mean(axis=0)\n inter_class_dist = ((len(I)+len(J))/total) * np.linalg.norm(ui-uj)\n \n # eigen value, vector each class\n valueI, vectorI = eigen(I)\n valueJ, vectorJ = eigen(J)\n \n # inter class center connect vector\n dij = uj - ui\n dji = ui - uj\n \n # cosine\n cosij = np.inner(dij,vectorI) / (np.linalg.norm(dij)*np.linalg.norm(vectorI))\n cosji = np.inner(dji,vectorJ) / (np.linalg.norm(dji)*np.linalg.norm(vectorJ))\n \n #intra-class variance\n intra_class_variance = 0.5*(math.sqrt(valueI)*abs(cosij) + math.sqrt(valueJ)*abs(cosji))\n intra_class_variance = intra_class_variance.item(0,0)\n \n return inter_class_dist - intra_class_variance\n\n\n# 함수4. eveness() : 클래스 간 거리의 균등도 return\ndef eveness(dic,total):\n d = []\n for i in range(len(dic)-1):\n I=dic[i]\n J=dic[i+1]\n AVG_I =I.mean(axis=0)\n AVG_J =J.mean(axis=0)\n inter = ((len(I)+len(J))/total)*np.linalg.norm(AVG_I-AVG_J)\n d.append(inter)\n \n U=0\n avg = np.mean(d)\n for i in range(len(d)):\n U+=abs(d[i]-avg)\n \n c =len(dic)\n U = U/ (c*(c-1)/2)\n# print(U)\n # print(avg)\n return 2- (U/avg)\n\n\n# 함수5. eigen(X) : data X의 공분산행렬의 eigenValue와 eigenVector return\ndef eigen(X):\n X_cen = X - X.mean(axis=0) # 평균을 0으로\n X_cov = np.dot(X_cen.T, X_cen) / (len(X)-1)\n w, v = np.linalg.eig(X_cov)\n return w[0],v[0]\n\n","sub_path":"geometricDistanceBasedFeatureSelection.py","file_name":"geometricDistanceBasedFeatureSelection.py","file_ext":"py","file_size_in_byte":4026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"526189612","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division\nimport math\n\nn = int(input('Digite o valor de n: '))\n\n\ns = 0\na = 1\n\nwhile n>1:\n \n s = s + a/n\n \n a = a+1\n \n \n \nprint (\"%.5f\" % s)\n \n ","sub_path":"moodledata/vpl_data/30/usersdata/64/9318/submittedfiles/atividade.py","file_name":"atividade.py","file_ext":"py","file_size_in_byte":223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"123041933","text":"#!/usr/bin/env python\n\nfrom utils import utils, inspector\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\nimport re\nimport logging\n\n# oldest year: 1979\n\ndef run(options):\n crawl_index(SEMIANNUAL_REPORTS_URL, options)\n crawl_index(AUDIT_REPORTS_URL, options, True)\n crawl_index(PEER_REVIEW_REPORTS_URL, options)\n crawl_index(MISCELLANEOUS_REPORTS_URL, options)\n\ndef crawl_index(base_url, options, is_meta_index=False):\n year_range = inspector.year_range(options)\n max_pages = options.get('pages')\n if max_pages:\n max_pages = int(max_pages)\n page = 1\n\n only_id = options.get('report_id')\n\n done = False\n while not done:\n url = url_for(base_url, page)\n body = utils.download(url)\n\n doc = BeautifulSoup(body)\n\n next_page = page + 1\n found_next_page = False\n page_links = doc.select(\"dl.moreResults a\")\n for page_link in page_links:\n if page_link.text == str(next_page):\n found_next_page = True\n break\n if not found_next_page:\n done = True\n if max_pages and next_page > max_pages:\n done = True\n\n results = doc.select(\"div#svPortal dl\")\n for result in results:\n if \"moreResults\" in result.get(\"class\"):\n continue\n if is_meta_index:\n url = \"http://www.gsaig.gov\" + result.a.get(\"href\")\n crawl_index(url, options, False)\n else:\n report = report_from(result, base_url)\n year = int(report['published_on'][:4])\n\n if only_id and (report['report_id'] != only_id):\n continue\n\n if year not in year_range:\n continue\n\n inspector.save_report(report)\n\n page = next_page\n if not done:\n logging.info('Moving to next page (%d)' % page)\n\ndef url_for(base_url, page = 1):\n return \"%s?startRow=%d\" % (base_url, page * 10 - 9)\n\ndef report_from(result, base_url):\n report = {\n 'inspector': 'gsa',\n 'inspector_url': 'http://gsaig.gov/',\n 'agency': 'gsa',\n 'agency_name': 'General Services Administration'\n }\n\n link = result.a\n title = link.text\n url = link.get('href')\n\n date_holders = result.find_all(\"dt\", class_=\"releaseDate\")\n if len(date_holders) > 0:\n published_date = date_holders[0].text\n date = datetime.strptime(published_date, \"%B %d, %Y\")\n elif title in HARDCODED_DATES:\n # This is an ugly solution, but there's no date information on the web page.\n # The next best solution would be to grab the PDF file and pull the file\n # creation date out of its metadata.\n published_date = HARDCODED_DATES[title]\n date = datetime.strptime(published_date, \"%B %d, %Y\")\n elif base_url == SEMIANNUAL_REPORTS_URL:\n # get last match\n match = None\n for match in DATE_RE.finditer(title):\n pass\n published_date = match.group(0)\n date = datetime.strptime(published_date, \"%B %d, %Y\")\n else:\n match = DATE_RE_MM_DD_YY.search(result.text)\n if match:\n published_date = match.group(0)\n date = datetime.strptime(published_date, \"%m/%d/%y\")\n else:\n raise Exception(\"Couldn't find date for %s\" % title)\n\n id = ID_RE.search(url).group(1)\n\n report_type = type_for(base_url)\n\n js_match = JS_RE.match(url)\n if js_match:\n url = \"http://www.gsaig.gov\" + js_match.group(1)\n elif url.startswith('/'):\n url = \"http://www.gsaig.gov\" + url\n\n report['type'] = report_type\n report['published_on'] = datetime.strftime(date, \"%Y-%m-%d\")\n report['url'] = url\n report['report_id'] = id\n report['title'] = title.strip()\n report['file_type'] = 'pdf'\n\n return report\n\ndef type_for(base_url):\n if base_url.find('special-reports') != -1:\n return \"audit\"\n if base_url.find('audit-reports') != -1:\n return \"audit\"\n return \"other\"\n\nSEMIANNUAL_REPORTS_URL = \"http://www.gsaig.gov/index.cfm/oig-reports/semiannual-reports-to-the-congress/\"\nAUDIT_REPORTS_URL = \"http://www.gsaig.gov/index.cfm/oig-reports/audit-reports/\"\nPEER_REVIEW_REPORTS_URL = \"http://www.gsaig.gov/index.cfm/oig-reports/peer-review-reports/\"\nMISCELLANEOUS_REPORTS_URL = \"http://www.gsaig.gov/index.cfm/oig-reports/miscellaneous-reports/\"\n\nID_RE = re.compile(\"LinkServID=([-0-9A-F]*)&showMeta=\")\nJS_RE = re.compile(\"\"\"javascript:newWin=window.open\\('/(\\?LinkServID=([-0-9A-F]*)&showMeta=0)','NewWin[0-9]*'\\);newWin.focus\\(\\);void\\(0\\)\"\"\")\nDATE_RE = re.compile(\"(January|February|March|April|May|June|July|August|\" +\n \"September|October|November|December) ([123]?[0-9]), \" +\n \"([12][0-9][0-9][0-9])\")\nDATE_RE_MM_DD_YY = re.compile(\"[0-9]?[0-9]/[0-9]?[0-9]/[0-9][0-9]\")\n\nHARDCODED_DATES = {\n \"Hats Off Program Investigative Report\": \"June 16, 2011\",\n \"Major Issues from Fiscal Year 2010 Multiple Award Schedule Preaward Audits\": \"September 26, 2011\",\n \"Review of Center for Information Security Services FTS\": \"March 23, 2001\",\n \"Audit of Procurement of Profesional Services from the FSS Multiple Award Schedules\": \"July 31, 2003\",\n \"Special Report: MAS Pricing Practices: Is FSS Observing Regulatory Provisions Regarding Pricing?\": \"August 24, 2001\",\n \"Updated Assessment of GSA's Most Serious Challenges\": \"December 8, 2004\",\n \"Limited Audit of FSS's Contracting for Services Under Multiple Award Schedule Contracts\": \"January 9, 2001\",\n \"Procurement Reform and the Multiple Award Schedule Program\": \"July 30, 2010\",\n \"FTS Alert Report\": \"March 6, 2003\",\n \"FTS CSC Audit Report\": \"January 8, 2004\",\n \"Compendium FTS CSC Audit Report\": \"December 14, 2004\",\n \"Compendium FTS CSC Controls Audit Report\": \"June 14, 2005\",\n \"Compendium FTS Client Support Center Controls Audit Report\": \"September 29, 2006\",\n \"Review of the Federal Acquisition Service's Client Support Center, Southeast Sunbelt Region - A090139-3\": \"June 4, 2010\"\n}\n\nutils.run(run) if (__name__ == \"__main__\") else None\n","sub_path":"inspectors/gsa.py","file_name":"gsa.py","file_ext":"py","file_size_in_byte":5738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"379145224","text":"from flask import render_template, flash, redirect\nfrom app import app\n@app.route('/')\n@app.route('/index')\ndef index():\n user = {'nickname': 'Michael'}\n posts = [\n {\n 'author': {'nickname': 'Fred Post 1'},\n 'body': 'This is the body of the first post.'\n },\n {\n 'author': {'nickname': 'Craig Post 2'},\n 'body': 'This is the body of the second post.'\n }\n ]\n return render_template('index.html',\n title='Home',\n user=user,\n posts=posts)\n@app.route('/about')\ndef about():\n return render_template('about.html',\n title='About')\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"652593592","text":"def socket_setup(self):\n \n #Sets outgoing connections\n \n s_r_out = socket.socket()\n host = socket.gethostname()\n port = self.cr_in\n s_r_out.bind((host, port)) \n s_r_out.listen(5)\n while True:\n connection, addr = s_r_out.accept()\n print('Got client: ' + str(addr))\n connection.close()\n \n #Sets incoming recievers\n \n s_r_in = socket.socket()\n host = socket.gethostname()\n port = self.cr_in\n s_r_in.bind((host, port)) \n s_r_in.listen(5)\n while True:\n connection, addr = s_r_in.accept()\n print('Got client: ' + str(addr))\n connection.close() \n ","sub_path":"old/reciever.py","file_name":"reciever.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"106082190","text":"from __future__ import division, print_function\nimport numpy as np\nimport cv2\nimport skfuzzy as fuzz\nimport matplotlib.pyplot as plt\n\ncap = cv2.VideoCapture(\"/home/veerav/PycharmProjects/fuzzy/Badminton_ce2/img/%04d.jpg\")\n\n # take first frame of the video\nret,frame = cap.read()\nrefPt = []\ncropping = False\nprint(frame.shape)\n\n\ndef click_and_crop(event, x, y, flags, param):\n # grab references to the global variables\n global refPt, cropping\n\n # if the left mouse button was clicked, record the starting\n # (x, y) coordinates and indicate that cropping is being\n # performed\n if event == cv2.EVENT_LBUTTONDOWN:\n refPt = [(x, y)]\n cropping = True\n\n # check to see if the left mouse button was released\n elif event == cv2.EVENT_LBUTTONUP:\n # record the ending (x, y) coordinates and indicate that\n # the cropping operation is finished\n refPt.append((x, y))\n cropping = False\n\n # draw a rectangle around the region of interest\n cv2.rectangle(frame, refPt[0], refPt[1], (0, 255, 0), 2)\n cv2.imshow(\"image\", frame)\n\n\n\n\n# load the image, clone it, and setup the mouse callback function\n\nclone = frame.copy()\ncv2.namedWindow(\"image\")\ncv2.setMouseCallback(\"image\", click_and_crop)\n\n# keep looping until the 'q' key is pressed\nwhile True:\n # display the image and wait for a keypress\n cv2.imshow(\"image\", frame)\n key = cv2.waitKey(1) & 0xFF\n\n # if the 'r' key is pressed, reset the cropping region\n if key == ord(\"r\"):\n image = clone.copy()\n\n # if the 'c' key is pressed, break from the loop\n elif key == ord(\"c\"):\n break\n\n# if there are two reference points, then crop the region of interest\n# from teh image and display it\nif len(refPt) == 2:\n roi = clone[refPt[0][1]:refPt[1][1], refPt[0][0]:refPt[1][0]]\n cv2.imshow(\"ROI\", roi)\n cv2.waitKey(0)\n\n# close all open windows\ncv2.destroyAllWindows()\ntrack_window = (refPt[0][0],refPt[0][1],refPt[1][0]-refPt[0][0],refPt[1][1]-refPt[0][1])\n # setup initial location of window\n#r,h,c,w = 250,90,400,125 # simply hardcoded the values\n#track_window = (c,r,w,h)\n\n # set up the ROI for tracking\n#roi = frame[r:r+h, c:c+w]\n\n\"\"\"\n========================\nFuzzy c-means clustering\n========================\n\n\"\"\"\n\n# Generate test data\n\nroi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)\nprint ('shape of image is ',roi.shape)\nxpts = np.zeros(roi.shape[0]*roi.shape[1])\nypts = np.zeros(roi.shape[0]*roi.shape[1])\n#zpts = np.zeros(roi.shape[0]*roi.shape[1])\nm = 0\nfor y in range(0,roi.shape[0]):\n for x in range(0,roi.shape[1]):\n xpts[m] = roi[y][x][0]\n #ypts[m] = roi[y][x][1]\n #zpts[m] = roi[y][x][2]\n m = m+1\nalldata = xpts.reshape(1, roi.shape[0] * roi.shape[1])\n#alldata = np.vstack((xpts,ypts,zpts))\n#alldata = np.vstack((xpts,ypts))\nprint ('alldata shape is ',alldata.shape)\n\n\n\n#Clustering\n#----------\n\n\ncntr, u, u0, d, jm, p, fpc = fuzz.cluster.cmeans(alldata, 8, 2, error=0.005, maxiter=100, init=None)\n\n#print ('membership is ',u)\n\n#print ('shape of partition matrix is ', u.shape)\n\n#print ('fp is ',fpc)\n\n\ncluster_assign = np.argmax(u,axis =0) # Hardening for visualization\ncluster_assign = cluster_assign.astype(np.uint8)\n#print (cluster_assign.shape)\n#print (type(cluster_assign))\nroi_hist = cv2.calcHist([cluster_assign],[0],None,[8],[0,8])\n\n\n\n\n\n#############\n#hsv_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)\n#mask = cv2.inRange(hsv_roi, np.array((0., 60.,32.)), np.array((180.,255.,255.)))\n#roi_hist = cv2.calcHist([hsv_roi],[0,1],None,[32,32],[0,180,0,256])\n#cv2.normalize(roi_hist,roi_hist,0,255,cv2.NORM_MINMAX)\n#cv2.normalize(roi_hist,roi_hist,0,255,cv2.NORM_MINMAX)\ncv2.normalize(roi_hist,roi_hist,alpha = 0,beta = 1,norm_type=cv2.NORM_MINMAX,dtype=cv2.CV_32F)\n\n# Setup the termination criteria, either 10 iteration or move by atleast 1 pt\nterm_crit = ( cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1 )\n\nwhile(1):\n ret ,frame = cap.read()\n\n if ret == True:\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\n dst = cv2.calcBackProject([hsv],[0],roi_hist,[0,8],1)\n\n\n # apply meanshift to get the new location\n ret, track_window = cv2.meanShift(dst, track_window, term_crit)\n\n # Draw it on image\n x,y,w,h = track_window\n img2 = cv2.rectangle(frame, (x,y), (x+w,y+h), 255,2)\n cv2.imshow('img2',img2)\n\n k = cv2.waitKey(60) & 0xff\n if k == 27:\n break\n else:\n cv2.imwrite(chr(k)+\".jpg\",img2)\n\n else:\n break\n\n\ncv2.destroyAllWindows()\ncap.release()","sub_path":"fuzzy_test.py","file_name":"fuzzy_test.py","file_ext":"py","file_size_in_byte":4550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"513537715","text":"\"\"\" Unit tests for Synergy Device. \"\"\"\nimport logging\nfrom mock import Mock, call, mock_open\nimport os\nimport sys\nimport copy\nimport time\nfrom tng_sl.device.endpoint.synergylite.synergylite_extended import (\n SynergyLiteExtended, media_available, verify_media_all_devices,\n wait_for_call_states, UnexpectedIceError, value_from_name_or_index)\nfrom tng_sl.plugins.synergylite_cli_common import (\n SynergyLiteCommandParser, SynergyLiteCommandHandler)\nfrom tng_sl.plugins.synergylite_cf_common import SynergyLiteCfNamespace\nfrom tng_sl.plugins.synergylite3pcc_ui_common import SynergyLite3pccUiNamespace\nfrom tng.error import TngError, TimeoutError\n\nfrom twisted.trial.unittest import TestCase\nfrom tng_sl.test.utilities import Clock\n\nfrom tng.frontend.engine import Engine\nfrom tng.device.endpoint.ata import ATA\nfrom tng_sl.plugins.ata_cli_common import ATACommandHandler\n\ntry:\n from unittest.mock import patch\nexcept ImportError:\n from mock import patch\n\nif sys.version_info.major == 2:\n import __builtin__ as builtins\nelse:\n import builtins\n\nlog = logging.getLogger('test_synergylite')\n\nGENERIC_MAC_ADDRESS = '01:02:03:04:05:06'\n\n\nclass MockATA(ATA, SynergyLiteExtended):\n def __init__(self, ip, *args, **kwargs):\n super(MockATA, self).__init__(ip, *args, **kwargs)\n\n\nclass TestLogFailureToDevice(TestCase):\n\n def test_basic(self):\n device = Mock(spec=SynergyLiteExtended)\n device.log = Mock(spec=logging.Logger)\n # should be copied over by spec?\n device._log_failure_to_device = (\n lambda test, error: SynergyLiteExtended._log_failure_to_device(\n device, test, error))\n\n device._log_failure_to_device('Some Random Test', 'Some Random Error')\n msg = 'Failed TNG test Some Random Test with error: Some Random Error'\n\n self.assertEqual(\n device.log_to_device.mock_calls,\n [call(msg)])\n self.assertEqual(\n device.log.warn.mock_calls,\n [call('_log_failure_to_device(%r)', msg)])\n self.assertEqual(device.log.debug.mock_calls, [])\n\n\nclass TestLogToDevice(TestCase):\n def setUp(self):\n # hardcode clock time so output is predictable\n self.clock = Clock(1458253930.25)\n patcher = patch('time.time', self.clock.time)\n patcher.start()\n self.addCleanup(patcher.stop)\n # standardize TZ\n orig_tz = os.environ.get('TZ', '')\n os.environ['TZ'] = 'US/Central'\n\n def restore_tz():\n os.environ['TZ'] = orig_tz\n self.addCleanup(restore_tz)\n\n self.device = Mock(spec=SynergyLiteExtended)\n self.device.cli = Mock(spec=SynergyLiteCommandHandler)\n self.device.log = Mock(spec=logging.Logger)\n self.device.debugsh = Mock()\n self.device.debugsh.plugin = Mock()\n self.device.debugsh.plugin.activated = True\n self.device.is_dev_phone = False\n\n # should be copied over by spec?\n self.device._log_max_chars_per_syslog = (\n SynergyLiteExtended._log_max_chars_per_syslog)\n self.device._log_max_msg_len = (\n SynergyLiteExtended._log_max_msg_len)\n self.device.log_to_device = (\n lambda msg: SynergyLiteExtended.log_to_device(self.device, msg))\n self.device._prefix = (\n SynergyLiteExtended._prefix)\n\n self.msg_prefix = '\"\\'!@$#^&*():;Test Message'\n self.cleaned_msg_prefix = (\n \"@2016-03-17 17:32:10,250 \"\n \"''!@$#^&*():;Test Message\")\n self.first_x_count = 35\n\n def test_basic(self):\n # make call we are testing\n msg = (self.msg_prefix + 'X' * (\n SynergyLiteExtended._log_max_chars_per_syslog))\n self.device.log_to_device(msg)\n # Validate:\n\n # * Ensure logging makes it to device log by changing double\n # quotes changed to single.\n # * Add Host TNG timestamp at start of log sent to device.\n # * Ensure SynergyLiteExtended._log_max_chars_per_syslog being honored\n # by chunking long logs into multiple syslog writes.\n\n self.assertEqual(\n self.device.cli.exec_command.mock_calls,\n [call(\n \"syslog write TNG \" + self.cleaned_msg_prefix +\n 'X' * self.first_x_count),\n call(\n 'syslog write TNG ' +\n 'X' * (\n SynergyLiteExtended._log_max_chars_per_syslog -\n self.first_x_count))])\n\n self.assertEqual(\n self.device.log.debug.mock_calls,\n [call('log_to_device: ' + repr(\n self.cleaned_msg_prefix +\n 'X' * SynergyLiteExtended._log_max_chars_per_syslog))])\n\n def test_too_long(self):\n # make call we are testing\n num_x = (\n SynergyLiteExtended._log_max_msg_len -\n len(self.cleaned_msg_prefix) + 1)\n msg = (self.msg_prefix + 'X' * num_x)\n self.device.log_to_device(msg)\n # Validate:\n\n # * Ensure logging makes it to device log by changing double\n # quotes changed to single.\n # * Add Host TNG timestamp at start of log sent to device.\n # * Ensure SynergyLiteExtended._log_max_chars_per_syslog being honored\n # by chunking long logs into multiple syslog writes.\n\n self.assertEqual(\n self.device.log.warn.mock_calls,\n [call('log_to_device():Truncating msg of len 426 to len 425')])\n\n # log_to_device debug should have thrown away last char\n self.assertEqual(\n self.device.log.debug.mock_calls,\n [call('log_to_device: ' + repr(\n self.cleaned_msg_prefix +\n 'X' * (num_x - 1)))])\n\n calls_list = [\n call(\n \"syslog write TNG \" + self.cleaned_msg_prefix +\n 'X' * self.first_x_count)]\n\n # -1 is because the intent is that the string is one too long\n remaining = num_x - self.first_x_count - 1\n while remaining > 0:\n this_chunk = SynergyLiteExtended._log_max_chars_per_syslog\n if remaining < this_chunk:\n this_chunk = remaining\n remaining -= this_chunk\n calls_list.append(call(\n 'syslog write TNG ' +\n 'X' * this_chunk))\n\n self.assertEqual(\n self.device.cli.exec_command.mock_calls,\n calls_list)\n\n def test_too_long_for_dev_phone(self):\n num_x = (\n SynergyLiteExtended._log_max_msg_len -\n len(self.cleaned_msg_prefix) + 1)\n msg = self.msg_prefix + 'X' * num_x\n\n self.device.is_dev_phone = True\n self.device.log_to_device(msg)\n\n # Validate:\n # Ensure entire command not be split into multiple parts.\n self.assertEqual(\n self.device.cli.exec_command.mock_calls,\n [call(\n 'syslog write TNG ' + self.cleaned_msg_prefix + 'X' * num_x)])\n\n def test_no_debugsh(self):\n self.device.debugsh._plugin.activated = False\n msg = (self.msg_prefix + 'X' * (\n SynergyLiteExtended._log_max_chars_per_syslog))\n self.device.log_to_device(msg)\n\n self.device.cli.exec_command.assert_not_called()\n self.device.log.debug.assert_called_with(\n 'No log_to_device() because debugsh plugin is not activated.')\n\n\nclass unmockedSLX(SynergyLiteExtended):\n '''need a full implementation to test the properties'''\n is_3pcc = None\n _kwargs = {}\n log_parser_server_ip = False\n log = Mock(spec=logging.Logger)\n\n def add_test_method_failure_callback(self, *args, **kwargs):\n pass\n\n\nclass SynergyLiteExtendedTestCase(TestCase):\n def build_generic_mock_synergy(self, method_name, target=None):\n target = target or Mock(spec=SynergyLiteExtended)\n target_method = getattr(SynergyLiteExtended, method_name)\n setattr(target, method_name, lambda *args, **kwargs: target_method(\n target, *args, **kwargs))\n target.log = Mock(spec=logging.Logger)\n target.ICE_OPTIMAL_PATHS = SynergyLiteExtended.ICE_OPTIMAL_PATHS\n target.ICE_TRAVERSAL_MODES = SynergyLiteExtended.ICE_TRAVERSAL_MODES\n target.ICE_STATE_NAMES = SynergyLiteExtended.ICE_STATE_NAMES\n target.wait_until_up = Mock()\n target.wait_until_down = Mock()\n\n return target\n\n\nclass TestSynergyLiteExtended(SynergyLiteExtendedTestCase):\n\n def setUp(self):\n self.target = Mock(spec=SynergyLiteExtended)\n self.target.cf = Mock(spec=SynergyLiteCfNamespace)\n self.target.cli = Mock(spec=SynergyLiteCommandHandler)\n self.target.cli.parser = SynergyLiteCommandParser()\n self.target.handle_startup = Mock()\n self.target.handle_shutdown = Mock()\n self.target._restart_action = Mock()\n self.target.http = Mock()\n self.target.dbus = Mock()\n self.target.log = Mock(spec=logging.Logger)\n self.target.credentials = Mock()\n self.target.ui = Mock(spec=SynergyLite3pccUiNamespace)\n\n self.jvmVal = {\n 'Bypass tftp addresses': 'false',\n 'Collabration Edge': '',\n 'Device Access Mode': 'Enterprise (deploy-mode:1)',\n 'Enable Password Persistent': 'false',\n 'Is Login window running': 'false',\n 'PRT URL': '',\n 'Registered': 'true',\n 'Saved Service Domain': '',\n 'State': 'idle',\n 'TFTP Available': 'true'\n }\n self.target._wait_patch = Mock()\n wait_patcher = patch(\n 'tng_sl.device.endpoint.synergylite.synergylite_extended.tng_wait',\n self.target._wait_patch)\n wait_patcher.start()\n self.addCleanup(wait_patcher.stop)\n\n self.clock = Clock()\n time_patcher = patch(\n 'tng.frontend.timing.time.time', self.clock.seconds)\n time_patcher.start()\n self.addCleanup(time_patcher.stop)\n\n sleep_patcher = patch(\n 'tng.frontend.timing.time.sleep', self.clock.sleep)\n sleep_patcher.start()\n self.addCleanup(sleep_patcher.stop)\n\n @patch(\n 'tng_sl.device.endpoint.synergylite.synergylite_extended.requests')\n def test__handle_test_failure(self, requests):\n target = self.build_generic_mock_synergy(\n '_handle_test_failure', self.target)\n target.gen_prt_log.return_value = False\n target.log_parser_server_ip = None\n target._handle_test_failure('Unused', 'Unused')\n target.gen_prt_log.assert_called_once_with(prt_type='FULL')\n requests.get.assert_not_called()\n\n target.gen_prt_log.reset_mock()\n target.gen_prt_log.return_value = True\n target._handle_test_failure('Unused', 'Unused')\n target.gen_prt_log.assert_called_once_with(prt_type='FULL')\n requests.get.assert_not_called()\n\n target.gen_prt_log.reset_mock()\n target.log_parser_server_ip = '1.1.1.1'\n target.get_ip = Mock()\n target.get_ip.return_value = '2.2.2.2'\n target._handle_test_failure('Unused', 'Unused')\n target.gen_prt_log.assert_called_once_with(prt_type='FULL')\n requests.get.assert_called_once_with(\n url='http://1.1.1.1/snapshot/log?ip=2.2.2.2')\n\n def test__get_stream_state(self):\n target = self.build_generic_mock_synergy(\n '_get_stream_state', self.target)\n target.cf.get_streams.return_value = [{'Direc': 'My Value'}]\n self.assertEqual('My Value', target._get_stream_state(1))\n\n target.cf.get_streams.return_value = []\n self.assertEqual(None, target._get_stream_state(2))\n\n def test_get_device_time(\n self, test_time='Tue May 10 20:12:20 UTC 2016', match=None,\n err=None):\n incoming_format = '%a %b %d %H:%M:%S %Z %Y'\n match = match or {\n 'year': '2016', 'month': '5', 'day': '10', 'hour': '20',\n 'min': '12', 'sec': '20', 'weekday': '1', 'day_of_year': '131',\n 'isdst': '0'}\n\n target = self.build_generic_mock_synergy(\n 'get_device_time', self.target)\n\n target.cli.exec_command.return_value = ['', test_time, '']\n if not err:\n ret = target.get_device_time()\n else:\n self.assertRaises(err, target.get_device_time)\n return\n\n t_struct = time.strptime(test_time.strip(), incoming_format)\n match.update({\n 'raw': test_time.strip(), 'struct_time': t_struct,\n 'time_zone': 'UTC', 'time': time.strftime('%H:%M:%S', t_struct)})\n self.assertDictEqual(match, ret)\n\n def test_get_device_time_2(self):\n match = {\n 'day': '24', 'day_of_year': '55', 'hour': '21', 'isdst': '0',\n 'min': '41', 'month': '2', 'sec': '56', 'weekday': '4',\n 'year': '2017'}\n return self.test_get_device_time(\n ' Fri Feb 24 21:41:56 UTC 2017 ', match)\n\n def test_get_device_time_raises(self):\n return self.test_get_device_time(\n \"long line with a Bad Date that can't be converted\", err=TngError)\n\n def test_check_is_available(self):\n target = self.build_generic_mock_synergy(\n 'check_is_available', self.target)\n self.assertFalse(target.check_is_available())\n target.check_ip_ping.return_value = True\n self.assertTrue(target.check_is_available())\n\n def test_get_huron_trackingid(self):\n self.target = self.build_generic_mock_synergy(\n 'get_huron_trackingid', self.target)\n\n self.target.cli.exec_command.return_value = [\n 'show huron TrackingID',\n '',\n '8851_e06d594d-0010-5000-a000-b07d47d313c8',\n '']\n self.assertEqual(\n self.target.get_huron_trackingid(),\n '8851_e06d594d-0010-5000-a000-b07d47d313c8')\n\n def test_get_huron_username(self):\n self.target = self.build_generic_mock_synergy(\n 'get_huron_username', self.target)\n\n self.target.cli.exec_command.return_value = [\n 'show huron username',\n '',\n 'tipbu_auto_63768@int1.huron-alpha.com',\n '']\n self.assertEqual(\n self.target.get_huron_username(),\n 'tipbu_auto_63768@int1.huron-alpha.com')\n\n def test_wait_until_close(self):\n target = self.build_generic_mock_synergy(\n 'wait_until_close', self.target)\n self.assertTrue(target.wait_until_close())\n target.handle_shutdown.assert_called_once_with()\n target.wait_until_down.assert_not_called()\n\n target.handle_shutdown.reset_mock()\n target.wait_until_down.reset_mock()\n\n self.assertTrue(target.wait_until_close(check=True))\n target.handle_shutdown.assert_called_once_with()\n target.wait_until_down.assert_called_once_with(30)\n\n target.handle_shutdown.reset_mock()\n target.wait_until_down.reset_mock()\n\n target.handle_shutdown.side_effect = [TngError]\n self.assertFalse(target.wait_until_close(check=True))\n\n def test_wait_until_restore(self):\n target = self.build_generic_mock_synergy(\n 'wait_until_restore', self.target)\n\n target.check_ip_ping.return_value = True\n target.handle_startup.return_value = True\n self.assertTrue(target.wait_until_restore(timeout=1, wait=0.1))\n\n def test_phone_set_idle(self):\n target = self.build_generic_mock_synergy('phone_set_idle', self.target)\n target.ui.close_all_apps.return_value = False\n self.assertFalse(target.phone_set_idle())\n target.cf.end_all_calls.assert_not_called()\n\n target.ui.close_all_apps.return_value = True\n target.cf.end_all_calls.return_value = False\n self.assertFalse(target.phone_set_idle())\n\n target.cf.end_all_calls.return_value = True\n self.assertTrue(target.phone_set_idle())\n\n @patch(\n 'tng_sl.device.endpoint.synergylite.synergylite_extended.get_system')\n def test_power(self, get_system):\n target = self.build_generic_mock_synergy('power', self.target)\n sw_obj = Mock()\n get_system.return_value = sw_obj\n\n self.assertFalse(target.power(reset_type='junk'))\n sw_obj.run_config_command.assert_not_called()\n self.assertEqual(sw_obj, target.sw_obj)\n\n target.get_port.return_value = \"MyPort\"\n\n self.assertTrue(target.power(reset_type='on', restore=False))\n sw_obj.run_config_command.assert_called_once_with(\n 'interface MyPort\\nno shut')\n target.wait_until_restore.assert_not_called()\n\n sw_obj.run_config_command.reset_mock()\n\n self.assertTrue(target.power(\n reset_type='off', timeout=0.1, wait=0.01, restore=True))\n\n sw_obj.run_config_command.assert_called_once_with(\n 'interface MyPort\\nshutdown')\n target.wait_until_restore.assert_called_once_with(\n timeout=0.1, wait=0.01)\n\n sw_obj.run_config_command.reset_mock()\n target.wait_until_restore.reset_mock()\n self.assertTrue(target.power(\n reset_type='toggle', timeout=0.2, wait=0.01, restore=True))\n\n sw_obj.run_config_command.has_calls([\n call('interface MyPort\\nshutdown'),\n call('interface MyPort\\nno shut')])\n target.wait_until_restore.assert_called_once_with(\n timeout=0.2, wait=0.01)\n\n def test_reset(self):\n target = self.build_generic_mock_synergy('reset', self.target)\n target.feedback = Mock()\n self.assertFalse(target.reset('junk'))\n target.cli.exec_command.assert_not_called()\n\n self.assertTrue(target.reset(timeout=1, wait=1))\n target.cli.exec_command.assert_called_once_with('reset hard\\n')\n target.wait_until_close.assert_called_once_with(check=True)\n target.wait_until_restore.assert_called_once_with(timeout=1, wait=1)\n\n target.cli.exec_command.reset_mock()\n target.wait_until_close.reset_mock()\n target.wait_until_restore.reset_mock()\n\n self.assertTrue(target.reset(reset_type='soft'))\n target.cli.exec_command.assert_called_once_with('reset soft\\n')\n target.wait_until_close.assert_called_once_with(check=False)\n target.wait_until_restore.assert_called_once_with(timeout=80, wait=20)\n\n target.cli.exec_command.reset_mock()\n target.wait_until_close.reset_mock()\n target.wait_until_restore.reset_mock()\n\n target.is_3pcc = False\n self.assertTrue(target.reset(reset_type='factory'))\n target.cli.exec_command.assert_called_once_with('reset factory\\n')\n target.cli.exec_command.reset_mock()\n target.wait_until_up.assert_not_called()\n target._set_3pcc_ssh.assert_not_called()\n target.cli.press_skip_key.assert_not_called()\n\n target.is_3pcc = 'True'\n target._set_3pcc_ssh.return_value = True\n target.cli.press_skip_key.return_value = True\n self.assertTrue(target.reset(reset_type='factory'))\n target.cli.exec_command.assert_called_once_with('reset factory\\n')\n target.wait_until_up.assert_called_once_with(80)\n target._set_3pcc_ssh.assert_called_once_with()\n target.cli.press_skip_key.assert_called_once_with()\n\n target._set_3pcc_ssh.return_value = False\n self.assertFalse(target.reset(reset_type='factory'))\n\n target._set_3pcc_ssh.return_value = True\n target.cli.press_skip_key.return_value = False\n self.assertFalse(target.reset(reset_type='factory'))\n\n target.cli.exec_command.reset_mock()\n\n self.assertTrue(target.reset(reset_type='service'))\n target.cli.exec_command.assert_called_once_with('reset servicemode\\n')\n target.cli.exec_command.reset_mock()\n\n self.assertTrue(target.reset(reset_type='servicemode'))\n target.cli.exec_command.assert_called_once_with('reset servicemode\\n')\n target.cli.exec_command.reset_mock()\n\n def test_reset_reboot(self):\n self.target = self.build_generic_mock_synergy('reset', self.target)\n self.target.feedback = Mock()\n self.target.debugsh = Mock()\n self.target.debugsh.exec_command.return_value = \"Hello\\nWorld\"\n\n # Invoke API under test\n self.assertTrue(\n self.target.reset(reset_type='reboot', timeout=120, wait=120))\n\n # Additional validations\n self.target.debugsh.exec_command.assert_called_once_with(\n 'reboot\\n', timeout=5, raw=True)\n self.target.wait_until_close.assert_called_once_with(check=True)\n self.target.wait_until_restore.assert_called_once_with(\n timeout=120, wait=120)\n\n self.target.debugsh.exec_command.reset_mock()\n self.target.wait_until_close.reset_mock()\n self.target.wait_until_restore.reset_mock()\n\n self.target.debugsh.exec_command.side_effect = [TimeoutError]\n # Invoke API under test\n self.assertTrue(\n self.target.reset(reset_type='reboot', timeout=120, wait=120))\n\n # Additional validations\n self.target.debugsh.exec_command.assert_called_once_with(\n 'reboot\\n', timeout=5, raw=True)\n self.target.wait_until_close.assert_called_once_with(check=True)\n self.target.wait_until_restore.assert_called_once_with(\n timeout=120, wait=120)\n\n def test__restart_action(self):\n target = self.build_generic_mock_synergy(\n '_restart_action', self.target)\n target.ssh = None\n self.assertEqual(target._restart_action(), None)\n target.log.info.assert_called_once_with('Did not reboot')\n\n target.ssh = Mock()\n target.reset.return_value = True\n self.assertTrue(target._restart_action())\n target.reset.assert_called_once_with(\n reset_type='reboot', timeout=120, wait=120)\n\n target.reset.reset_mock()\n target.reset.return_value = False\n self.assertRaises(TngError, target._restart_action)\n target.reset.assert_called_once_with(\n reset_type='reboot', timeout=120, wait=120)\n\n def test__boot_action(self):\n target = self.build_generic_mock_synergy('_boot_action', self.target)\n target._boot_action()\n target._restart_action.assert_called_once_with()\n\n def test_resume_all(self):\n target = self.build_generic_mock_synergy('resume_all', self.target)\n self.assertRaises(NotImplementedError, target.resume_all)\n\n def test_on_board_huron(self):\n self.target = self.build_generic_mock_synergy(\n 'on_board_huron', self.target)\n self.target.cli.exec_command.return_value = [\n 'login huron 8893501470247980 0'\n ]\n self.target.handle_shutdown.return_value = True\n self.target.handle_startup.return_value = True\n self.assertEqual(\n self.target.on_board_huron('8893501470247980', 0.001, 1),\n ['login huron 8893501470247980 0'])\n self.target.cli.exec_command.assert_called_once_with(\n 'login huron 8893501470247980')\n\n def test_on_board_ce(self):\n self.target = self.build_generic_mock_synergy(\n 'on_board_ce', self.target)\n self.target.cli.exec_command.return_value = (\n 'login ce cisco.com me pwd\\nSuccess'.splitlines())\n self.assertEqual(\n self.target.on_board_ce('cisco.com', 'me', 'pwd', 0.001, 1),\n ['login ce cisco.com me pwd', 'Success'])\n self.target.cli.exec_command.assert_called_once_with(\n 'login ce cisco.com me pwd')\n\n def test_reset_servicemode(self):\n target = self.build_generic_mock_synergy(\n 'reset_servicemode', self.target)\n target.reset_servicemode()\n target.reset.assert_called_once_with(\n 'service', timeout=80, wait=20, restore_conn=False)\n\n @patch(\n 'tng_sl.device.endpoint.synergylite.synergylite_extended.get_defines')\n def test_property_ICE_OPTIMAL_PATH(self, get_defines):\n target = unmockedSLX()\n # test values read from command line\n get_defines.return_value = {'ICE_OPTIMAL_PATH': 'SRFLX'}\n self.assertEqual(target.ICE_OPTIMAL_PATH, 'SRFLX')\n self.assertEqual(target._ice_optimal_path, 'SRFLX')\n self.assertEqual(\n target.ICE_OPTIMAL_PATHS.index(target.ICE_OPTIMAL_PATH), 2)\n\n get_defines.assert_called_once_with()\n get_defines.reset_mock()\n self.assertTrue(getattr(target, '_ice_optimal_path', False))\n del target.ICE_OPTIMAL_PATH\n self.assertFalse(getattr(target, '_ice_optimal_path', False))\n\n get_defines.return_value = {'Other_stuff': 'Nope'}\n self.assertEqual(target.ICE_OPTIMAL_PATH, 'NO_ICE')\n self.assertEqual(target._ice_optimal_path, 'NO_ICE')\n self.assertEqual(\n target.ICE_OPTIMAL_PATHS.index(target.ICE_OPTIMAL_PATH), 0)\n\n get_defines.assert_called_once_with()\n get_defines.reset_mock()\n\n # user sets value to a string-int\n target.ICE_OPTIMAL_PATH = '3'\n self.assertEqual(target.ICE_OPTIMAL_PATH, 'RELAY')\n self.assertEqual(target._ice_optimal_path, 'RELAY')\n self.assertEqual(\n target.ICE_OPTIMAL_PATHS.index(target.ICE_OPTIMAL_PATH), 3)\n get_defines.assert_not_called()\n\n # user sets value to a lower case\n target.ICE_OPTIMAL_PATH = 'prflx'\n self.assertEqual(target.ICE_OPTIMAL_PATH, 'PRFLX')\n self.assertEqual(target._ice_optimal_path, 'PRFLX')\n self.assertEqual(\n target.ICE_OPTIMAL_PATHS.index(target.ICE_OPTIMAL_PATH), 4)\n get_defines.assert_not_called()\n\n @patch(\n 'tng_sl.device.endpoint.synergylite.synergylite_extended.get_defines')\n def test_property_ICE_TRAVERSAL_MODE(self, get_defines):\n target = unmockedSLX()\n # test values read from command line\n get_defines.return_value = {'ICE_TRAVERSAL_MODE': 'ICE with TURN'}\n self.assertEqual(target.ICE_TRAVERSAL_MODE, 'ICE with TURN')\n self.assertEqual(target._ice_traversal_mode, 'ICE with TURN')\n self.assertEqual(\n target.ICE_TRAVERSAL_MODES.index(target.ICE_TRAVERSAL_MODE), 3)\n\n get_defines.assert_called_once_with()\n get_defines.reset_mock()\n self.assertTrue(getattr(target, '_ice_traversal_mode', False))\n\n # make sure deleting the property will delete the private variable\n del target.ICE_TRAVERSAL_MODE\n self.assertFalse(getattr(target, '_ice_traversal_mode', False))\n\n get_defines.return_value = {'Other_stuff': 'Nope'}\n self.assertEqual(target.ICE_TRAVERSAL_MODE, 'Media Latch')\n self.assertEqual(target._ice_traversal_mode, 'Media Latch')\n self.assertEqual(\n target.ICE_TRAVERSAL_MODES.index(target.ICE_TRAVERSAL_MODE), 1)\n\n get_defines.assert_called_once_with()\n get_defines.reset_mock()\n\n # user sets value to a string-int\n target.ICE_TRAVERSAL_MODE = '2'\n self.assertEqual(target.ICE_TRAVERSAL_MODE, 'TURN Relay Only')\n self.assertEqual(target._ice_traversal_mode, 'TURN Relay Only')\n self.assertEqual(\n target.ICE_TRAVERSAL_MODES.index(target.ICE_TRAVERSAL_MODE), 2)\n get_defines.assert_not_called()\n\n # user sets value to a lower case\n target.ICE_TRAVERSAL_MODE = 'media latch'\n self.assertEqual(target.ICE_TRAVERSAL_MODE, 'Media Latch')\n self.assertEqual(target._ice_traversal_mode, 'Media Latch')\n self.assertEqual(\n target.ICE_TRAVERSAL_MODES.index(target.ICE_TRAVERSAL_MODE), 1)\n get_defines.assert_not_called()\n\n def test_check_traversal_mode(self):\n target = self.build_generic_mock_synergy(\n 'check_traversal_mode', self.target)\n ret = {'Media Traversal Mode': 'TestValue'}\n target.cf.get_ice.return_value = ret\n\n resp = target.check_traversal_mode(\n expected_mode='ValueTest',\n show_ice={'Media Traversal Mode': 'ValueTest'})\n self.assertEqual(resp, {'Media Traversal Mode': 'ValueTest'})\n\n resp = target.check_traversal_mode('TestValue')\n self.assertEqual(resp, ret)\n target.cf.get_ice.assert_called_once_with()\n\n target.ICE_TRAVERSAL_MODE = 'TestValue'\n resp = target.check_traversal_mode()\n self.assertEqual(resp, ret)\n\n self.assertRaises(\n UnexpectedIceError, target.check_traversal_mode, 'unmatched')\n\n def test_check_optimal_path(self):\n target = self.build_generic_mock_synergy(\n 'check_optimal_path', self.target)\n\n ret = {\n 'Media Traversal Mode': 'TestValue',\n 'Audio Optimal media path': '4 (PRFLX)',\n 'Video Optimal media path': '1 (HOST)'}\n\n target.cf.get_ice.return_value = ret\n resp = target.check_optimal_path(expected_path='PRFLX')\n self.assertEqual(resp, ret)\n target.cf.get_ice.assert_called_once_with()\n target.wait_for_ice_completed.assert_called_once_with()\n\n target.ICE_OPTIMAL_PATH = 'TestValue'\n resp = target.check_optimal_path(expected_path='PRFLX')\n self.assertEqual(resp, ret)\n\n self.assertRaises(\n UnexpectedIceError, target.check_optimal_path,\n expected_path='unmatched')\n\n # test video only\n resp = target.check_optimal_path(\n expected_path='HOST', media={'video': 'junk'})\n\n ret = {\n 'Media Traversal Mode': 'TestValue',\n 'Audio Optimal media path': '3 (RELAY)',\n 'Video Optimal media path': '3 (RELAY)'}\n target.cf.get_ice.return_value = ret\n\n # test both video and audio on same path\n resp = target.check_optimal_path(\n expected_path='RELAY', media={'video': 'junk', 'audio': 'more'})\n\n # test both video and audio on different paths\n ret['Audio Optimal media path'] = '1 (HOST)'\n\n self.assertRaises(\n UnexpectedIceError, target.check_optimal_path,\n expected_path='RELAY', media={'video': 'junk', 'audio': 'more'})\n\n def test_check_ice_optimal_path(self):\n target = self.build_generic_mock_synergy(\n 'check_optimal_path', self.target)\n target.cf.get_ice.return_value = {\n \"Audio Optimal media path\": '3 (RELAY)'}\n target.check_optimal_path('RELAY')\n self.assertRaises(\n UnexpectedIceError, target.check_optimal_path, 'SRFLX')\n\n def test_check_ICE_mode_and_path(self):\n target = self.build_generic_mock_synergy(\n 'check_ICE_mode_and_path', self.target)\n target.check_traversal_mode.return_value = 'RET1'\n target.check_optimal_path.return_value = 'RET2'\n\n ret = target.check_ICE_mode_and_path(\n media={'a': 'b'}, expected_mode='MyMode', expected_path='MyPath')\n self.assertEqual(ret, \"RET2\")\n target.check_traversal_mode.assert_called_once_with(\n expected_mode='MyMode')\n target.check_optimal_path.assert_called_once_with(\n media={'a': 'b'}, expected_path='MyPath')\n\n def test_get_phone_traversal_mode(self):\n target = self.build_generic_mock_synergy(\n 'get_phone_traversal_mode', self.target)\n target.cli.get_config_info.return_value = '2'\n self.assertEqual('TURN Relay Only', target.get_phone_traversal_mode())\n\n target.cli.get_config_info.return_value = 'unmatched'\n self.assertEqual('Media Latch', target.get_phone_traversal_mode())\n\n @patch('tng_sl.device.endpoint.synergylite.synergylite_extended.until')\n def test_wait_for_media_traversal_mode(self, u):\n target = self.build_generic_mock_synergy(\n 'wait_for_media_traversal_mode', self.target)\n u.return_value = True\n target.get_phone_traversal_mode.return_value = 'TURN Relay Only'\n target.wait_for_media_traversal_mode(2)\n u.assert_called_once_with(\n target.get_phone_traversal_mode, desired_result='TURN Relay Only')\n u.reset_mock()\n u.side_effect = [TimeoutError('TestFailure')]\n self.assertRaises(\n TimeoutError, target.wait_for_media_traversal_mode)\n\n def test_get_ice_state(self):\n target = self.build_generic_mock_synergy('get_ice_state', self.target)\n target.cf.get_ice.return_value = {\"Ice state\": 'unmatched'}\n self.assertEqual('IDLE', target.get_ice_state())\n\n target.cf.get_ice.reset_mock()\n target.cf.get_ice.return_value = {\"Ice state\": '5 (ACTIVE)'}\n self.assertEqual('ACTIVE', target.get_ice_state())\n target.cf.get_ice.assert_called_once_with()\n target.cf.get_ice.reset_mock()\n self.assertEqual('NO_ICE', target.get_ice_state(\n {\"Ice state\": '7 (NO_ICE)'}))\n target.cf.get_ice.assert_not_called()\n # Ice not configured has no 'Ice state\"\n test_no_ice = {\n u'Audio Local media ip': u'10.4.10.23',\n u'Audio Local media port': u'23040',\n u'Audio Optimal media path': u'LATCHING',\n u'Audio Peer media ip': u'10.1.50.190',\n u'Audio Peer media port': u'47606',\n u'Media Traversal Mode': u'Media Latch',\n u'Video Local media ip': u'10.4.10.23',\n u'Video Local media port': u'26318',\n u'Video Optimal media path': u'LATCHING',\n u'Video Peer media ip': u'10.1.50.190',\n u'Video Peer media port': u'36150'}\n target.cf.get_ice.reset_mock()\n self.assertEqual('NO_ICE', target.get_ice_state(show_ice=test_no_ice))\n target.cf.get_ice.assert_not_called()\n\n def test_is_ice_state_started(self):\n target = self.build_generic_mock_synergy(\n 'is_ice_state_started', self.target)\n target.get_ice_state.return_value = 'CANDIDATES_DONE'\n self.assertTrue(target.is_ice_state_started())\n target.get_ice_state.assert_called_once_with(show_ice=None)\n\n target.get_ice_state.reset_mock()\n target.get_ice_state.return_value = 'ACTIVE'\n self.assertFalse(target.is_ice_state_started())\n target.get_ice_state.assert_called_once_with(show_ice=None)\n\n target.get_ice_state.reset_mock()\n target.get_ice_state.return_value = 'START_CONNECTIVITY_CHECK'\n self.assertTrue(target.is_ice_state_started(\n {'Ice state': '3 (START_CONNECTIVITY_CHECK)'}))\n target.get_ice_state.assert_called_once_with(\n show_ice={'Ice state': '3 (START_CONNECTIVITY_CHECK)'})\n\n @patch('tng_sl.device.endpoint.synergylite.synergylite_extended.until')\n def test_wait_for_ice_state_started(self, u):\n target = self.build_generic_mock_synergy(\n 'wait_for_ice_state_started', self.target)\n u.return_value = True\n target.wait_for_ice_state_started()\n u.assert_called_once_with(\n target.is_ice_state_started, interval=0.2, timeout=10.0,\n raise_msg=(\n \"{}: Not in expected ICE state 2 (CANDIDATES_DONE) or 3 \"\n \"(START_CONNECTIVITY_CHECK)\").format(target))\n\n def test_wait_for_ice_completed(self):\n target = self.build_generic_mock_synergy(\n 'wait_for_ice_completed', self.target)\n # negative cases first\n for s in range(6):\n ret_state_name = value_from_name_or_index(\n s, target.ICE_STATE_NAMES, 0)\n target.get_ice_state.return_value = ret_state_name\n # need to test both the Exception and the message in the exception\n try:\n target.wait_for_ice_completed()\n raise BaseException(\"expected TimeoutError\")\n except Exception as e:\n self.assertTrue(isinstance(\n e, TimeoutError), \"{} is not a TimeoutError\".format(e))\n self.assertIn(\n \"{} Not in completed ICE states\".format(ret_state_name),\n e.message)\n\n # success cases here\n for s in range(6, 9):\n translated_state = value_from_name_or_index(\n s, target.ICE_STATE_NAMES, 0)\n target.get_ice_state.reset_mock()\n target.get_ice_state.side_effect = [\n value_from_name_or_index(bad_val, target.ICE_STATE_NAMES, 0)\n for bad_val in range(5)] + [translated_state]\n ret = target.wait_for_ice_completed()\n self.assertEqual(ret, translated_state)\n\n @patch('tng_sl.device.endpoint.synergylite.synergylite_extended.until')\n def test_wait_for_ice_state_active(self, u):\n target = self.build_generic_mock_synergy(\n 'wait_for_ice_state_active', self.target)\n u.return_value = True\n target.wait_for_ice_state_active()\n u.assert_called_once_with(\n target.get_ice_state, desired_result='ACTIVE', timeout=20.0,\n raise_msg=\"{}: Not in expected ICE state ACTIVE\".format(target))\n\n def test_check_ice_remote_concluded_type(self):\n target = self.build_generic_mock_synergy(\n 'check_ice_remote_concluded_type', self.target)\n ret = {\n \"Audio Remote concluded candidate type\": '3 (RELAY)',\n 'Audio Peer media ip': '1.2.3.4'}\n target.cf.get_ice.return_value = ret.copy()\n self.assertEqual(ret, target.check_ice_remote_concluded_type(3))\n ret2 = {\n \"Audio Remote concluded candidate type\": '4 (PRFLX)',\n 'Audio Peer media ip': '4.3.2.1'}\n self.assertEqual(ret2, target.check_ice_remote_concluded_type(\n 'prflx', ret2.copy()))\n\n self.assertRaises(\n UnexpectedIceError, target.check_ice_remote_concluded_type,\n 'prflx')\n\n def test_is_registered(self):\n self.target = self.build_generic_mock_synergy(\n 'is_registered', self.target)\n self.target.cli.show_register_gsi.return_value = {\n 'Proxy Registration':\n 'ENABLED',\n 'line': '201',\n 'local uuid': '9313784100105000a000346f9017d6a6',\n 'remote uuid': '',\n 'state': 'REGISTERED'\n }\n self.target.cli.get_phone_info.return_value = {\n 'Active Load': 'sip88xx.11-5-1MN-7dev.loads',\n 'Active Serve Type': 'CMS',\n 'Active Server': 'cms-vip-a-01-internal.int-tx3.huron-int.com',\n 'IPv4 Address': '10.79.63.28',\n 'Last Upgrade': '11-04-15 10:00',\n 'MAC Address': '6C998984B90C',\n 'Model Number': 'CP-8861',\n 'Phone Information': '',\n 'Squared UC': 'huron-int.com',\n 'Stand-by Server': '',\n 'Stand-by Server Type': ''\n }\n self.assertTrue(self.target.is_registered())\n\n def test_wait_until_registered(self):\n target = self.build_generic_mock_synergy(\n 'wait_until_registered', self.target)\n target.is_registered.return_value = False\n self.assertRaises(\n TimeoutError, target.wait_until_registered, retry=1, period=0.1)\n target.is_registered.return_value = True\n self.assertTrue(target.wait_until_registered())\n\n def test_wait_until_login_page(self):\n target = self.build_generic_mock_synergy(\n 'wait_until_login_page', self.target)\n target.ui.check_ui.return_value = False\n self.assertRaises(\n TimeoutError, target.wait_until_login_page, retry=1, period=0.1)\n target.ui.check_ui.assert_called_with(\n expected='Welcome', name='in-focus', ui_type='ui_window_detail')\n\n target.ui.check_ui.reset_mock()\n target.ui.check_ui.return_value = True\n self.assertTrue(target.wait_until_login_page())\n target.ui.check_ui.assert_called_once_with(\n expected='Welcome', name='in-focus', ui_type='ui_window_detail')\n\n def test_is_cucm_mode(self):\n self.target = self.build_generic_mock_synergy(\n 'is_cucm_mode', self.target)\n self.target.get_service_mode.return_value = (\n 'Enterprise (deploy-mode:1)')\n self.assertTrue(self.target.is_cucm_mode())\n\n def test_is_ce_mode(self):\n self.target = self.build_generic_mock_synergy('is_ce_mode')\n self.target.get_service_mode.return_value = (\n 'Enterprise (deploy-mode:1)')\n self.assertFalse(self.target.is_ce_mode())\n\n def test_is_huron_mode(self):\n self.target = self.build_generic_mock_synergy('is_huron_mode')\n self.target.get_service_mode.return_value = (\n 'Enterprise (deploy-mode:1)')\n self.assertFalse(self.target.is_huron_mode())\n\n def test_get_huron_domain(self):\n self.target = self.build_generic_mock_synergy(\n 'get_huron_domain', self.target)\n self.target.cli.show_huron_info.return_value = 'hptx1.huron-dev.com'\n self.assertEqual(self.target.get_huron_domain(), 'hptx1.huron-dev.com')\n\n def test_get_nslookup_info(self):\n self.target = self.build_generic_mock_synergy(\n 'get_nslookup_info', self.target)\n self.target.cli.show_nslookup.return_value = {\n 'Address 1': '72.163.4.161 www1.cisco.com',\n 'Address 2': '2001:420:1101:1::a www1.cisco.com',\n 'Name': 'cisco.com',\n 'Server': '127.0.0.1',\n 'nslookup cisco.com': ''}\n expected_result = {\n 'Address 1': '72.163.4.161 www1.cisco.com',\n 'Address 2': '2001:420:1101:1::a www1.cisco.com',\n 'Name': 'cisco.com',\n 'Server': '127.0.0.1',\n 'nslookup cisco.com': ''}\n self.assertEqual(\n self.target.get_nslookup_info(\"cisco.com\"), expected_result)\n\n def test_get_wlan_auth_prompt_mode(self):\n self.target = self.build_generic_mock_synergy(\n 'get_wlan_auth_prompt_mode', self.target)\n self.target.cli.show_jvm_config_properties.return_value = {\n 'device.settings.config.vendorconfig.wlanauthpromptmode': {\n 'value': 'true',\n 'provisional.value': 'null',\n 'to.string': 'true'\n }\n }\n expected_result = {\n 'value': 'true',\n 'provisional.value': 'null',\n 'to.string': 'true'\n }\n self.assertEquals(\n self.target.get_wlan_auth_prompt_mode(), expected_result)\n\n def test_get_hedge_server_list(self):\n self.target = self.build_generic_mock_synergy(\n 'get_hedge_server_list', self.target)\n self.target.cli.show_hedge_info.return_value = {\n 'ActiveHedgeServer': '10.1.1.1',\n 'Hedge Infomation': '',\n 'HedgeServer1': '10.1.1.1',\n 'HedgeServer2': '10.1.1.2',\n 'HedgeServer3': '',\n 'HedgeServer4': ''\n }\n self.assertEqual(\n self.target.get_hedge_server_list(), ['10.1.1.1', '10.1.1.2'])\n\n def test_get_active_hedge_server(self):\n self.target = self.build_generic_mock_synergy(\n 'get_active_hedge_server', self.target)\n self.target.cli.show_hedge_info.return_value = {\n 'ActiveHedgeServer': '10.1.1.1',\n 'Hedge Infomation': '',\n 'HedgeServer1': '10.1.1.1',\n 'HedgeServer2': '10.1.1.2',\n 'HedgeServer3': '',\n 'HedgeServer4': ''\n }\n self.assertEqual(\n self.target.get_active_hedge_server(), '10.1.1.1')\n\n def test_get_park_number_toast(self):\n self.target = self.build_generic_mock_synergy(\n 'get_park_number', self.target)\n self.target.cli.show_dpark_info.return_value = {\n 'Title': 'null',\n 'Type': '0',\n 'Icon': 'N/A',\n 'Text': 'Call park at 7770'\n }\n self.assertEqual(self.target.get_park_number(), '7770')\n\n def test_get_park_number_toast_missing_text_value(self):\n self.target = self.build_generic_mock_synergy(\n 'get_park_number', self.target)\n self.target.cli.show_dpark_info.return_value = {\n 'Title': 'null',\n 'Type': '0',\n 'Icon': 'N/A',\n 'Text': ''\n }\n self.assertEqual(self.target.get_park_number(), None)\n\n def test_get_park_number_toast_variation_text_value(self):\n self.target = self.build_generic_mock_synergy(\n 'get_park_number', self.target)\n self.target.cli.show_dpark_info.return_value = {\n 'Title': 'null',\n 'Type': '0',\n 'Icon': 'N/A',\n 'Text': 'Call Parked at 7770'\n }\n self.assertEqual(self.target.get_park_number(), '7770')\n\n def test_get_park_number_toast_unknown_text_value(self):\n self.target = self.build_generic_mock_synergy(\n 'get_park_number', self.target)\n self.target.cli.show_dpark_info.return_value = {\n 'Title': 'null',\n 'Type': '0',\n 'Icon': 'N/A',\n 'Text': 'Dr Pais watc is now connected.'\n\n }\n self.assertEqual(self.target.get_park_number(), None)\n\n def test_get_park_number_toast_sp_variation(self):\n self.target = self.build_generic_mock_synergy(\n 'get_park_number', self.target)\n self.target.cli.show_dpark_info.return_value = {\n 'Text': 'Park at 7770',\n 'subwindow-0\\t0/0/330/105': '',\n 'Icon': 'N/A',\n 'Type': '5',\n 'Title': ''\n }\n self.assertEqual(self.target.get_park_number(), '7770')\n\n def test_get_park_number_no_toast(self):\n self.target = self.build_generic_mock_synergy(\n 'get_park_number', self.target)\n self.target.cli.show_dpark_info.return_value = {\n 'No Active Toast Displayed': ''\n }\n self.assertEqual(self.target.get_park_number(), None)\n\n def test_get_service_mode(self):\n self.target = self.build_generic_mock_synergy(\n 'get_service_mode', self.target)\n self.target.cli.show_jvm_ce.return_value = self.jvmVal\n self.assertEqual(\n self.target.get_service_mode(), 'Enterprise (deploy-mode:1)')\n\n def test_get_wlan_info(self):\n self.target = self.build_generic_mock_synergy(\n 'get_wlan_info', self.target)\n self.target.cli.show_wlan_profile.return_value = {\n 'OK': '',\n 'band': '5GHz',\n 'passphrase': '*',\n 'security_type': 'PSK',\n 'ssid': 'x930'\n }\n self.assertEqual(self.target.get_wlan_info('profile'), {\n 'OK': '',\n 'band': '5GHz',\n 'passphrase': '*',\n 'security_type': 'PSK',\n 'ssid': 'x930'})\n\n def test_press_hard_key(self):\n self.target = self.build_generic_mock_synergy(\n 'press_hard_key', self.target)\n self.target.cli.press_speaker.return_value = True\n self.assertTrue(self.target.press_hard_key('speaker'))\n self.target.cli.press_number_key.return_value = True\n self.assertTrue(self.target.press_hard_key(\n key_name=0, key_type='number'))\n\n def test_get_ssid_info_by_name(self):\n self.target = self.build_generic_mock_synergy(\n 'get_ssid_info_by_name', self.target)\n self.target.cli.show_wifi_ssid_list.side_effect = [None, [\n {\n 'BSSID': 'c8:f9:f9:d5:37:c2',\n 'Current': 'Yes',\n 'Frequency': '2462',\n 'SSID': 'automation_PSK',\n 'Security Mode': 'PSK',\n 'Signal': 't-57'\n },\n {\n 'BSSID': 'f0:b4:29:60:d1:30',\n 'Current': 'No',\n 'Frequency': '2457',\n 'SSID': 'Wenlan-XiaoMi-2.4G',\n 'Security Mode': 'PSK',\n 'Signal': '-27'\n }\n ]]\n expect_result = {\n 'BSSID': 'c8:f9:f9:d5:37:c2',\n 'Current': 'Yes',\n 'Frequency': '2462',\n 'SSID': 'automation_PSK',\n 'Security Mode': 'PSK',\n 'Signal': 't-57'\n }\n self.assertEqual(\n self.target.get_ssid_info_by_name('automation_PSK'), expect_result)\n self.target._wait_patch.assert_called_once_with(\n 1, 'wait 1s to get ssid info from cli again')\n\n def test_is_wlan_connected_by_ssid(self):\n self.target = self.build_generic_mock_synergy(\n 'is_wlan_connected_by_ssid', self.target)\n self.target.cli.show_wlan_supplicant_status.return_value = {\n 'bssid': 'cc:46:d6:a9:29:f6',\n 'ssid': 'test-peap-gtc',\n 'id': '0',\n 'mode': 'station',\n 'pairwise_cipher': 'CCMP',\n 'group_cipher': 'CCMP',\n 'key_mgmt': 'WPA2/IEEE 802.1X/EAP',\n 'wpa_state': 'COMPLETED',\n 'ip_address': '100.100.48.145',\n 'address': '28:34:a2:82:8f:66',\n 'Supplicant PAE state': 'AUTHENTICATED',\n 'suppPortStatus': 'Authorized',\n 'EAP state': 'SUCCESS',\n 'selectedMethod': '25 (EAP-PEAP)',\n 'EAP TLS cipher': 'ECDHE-RSA-AES256-SHA',\n 'EAP-PEAPv1 Phase2 method': 'GTC'\n }\n self.assertTrue(\n self.target.is_wlan_connected_by_ssid('test-peap-gtc'))\n\n def test_get_prt_status(self):\n self.target = self.build_generic_mock_synergy(\n 'get_prt_status', self.target)\n self.target.cli.show_prt_status.return_value = [{\n 'PRT': '6',\n 'State': 'uploaded',\n }]\n expect_result = {\n 'PRT': '6',\n 'STATE': 'uploaded',\n }\n self.assertEqual(\n self.target.get_prt_status(), expect_result)\n\n self.target.cli.show_prt_status.return_value = None\n self.assertRaises(TypeError, self.target.get_prt_status, 'junk')\n\n self.target.cli.show_prt_status.return_value = [\n {u'Command not found.': u\"subcommands available under 'prt':\"},\n {u'Command not found.': u'prt create'}]\n self.assertRaises(TngError, self.target.get_prt_status)\n\n def test_gen_prt_log(self):\n self.target = self.build_generic_mock_synergy(\n 'gen_prt_log', self.target)\n self.target._check_prt_generated.return_value = True\n self.target.cli.exec_command.return_value = [\n u'prt create FULL',\n u\"Full PRT Generation started.\"\n u\"Check phone's web page Console Logs for Full PRT logs.\",\n u'PRT Filename: prt-20161109-143351-00EBD5DA5AAC.tar.gz',\n u'Phone Webpage Link:'\n u'http://10.89.122.116/FS/prt-20161109-143351-00EBD5DA5AAC.tar.gz',\n u'',\n u'']\n self.assertEqual(\n self.target.gen_prt_log(),\n 'prt-20161109-143351-00EBD5DA5AAC.tar.gz')\n self.target.cli.exec_command.assert_called_once_with(\n 'prt create FULL noupload', timeout=120.0)\n\n self.target.cli.exec_command.return_value = []\n self.assertRaises(TngError, self.target.gen_prt_log)\n\n def test_check_webpage_for_prtname(self):\n self.target = self.build_generic_mock_synergy(\n '_check_webpage_for_prtname', self.target)\n self.target.http.request.return_value = 'Searching for prt'\n self.assertTrue(self.target._check_webpage_for_prtname('for prt'))\n self.assertFalse(self.target._check_webpage_for_prtname('abc xyz'))\n\n def test_check_prt_generated(self):\n self.target = self.build_generic_mock_synergy(\n '_check_prt_generated', self.target)\n self.target.get_prt_status.return_value = {\n u'PRT': u'5', u'State': u'uploading-failed'}\n self.assertTrue(self.target._check_prt_generated('FULL'))\n self.target.get_prt_status.return_value = {\n u'PRT': u'0', u'State': u'idle'}\n self.assertFalse(self.target._check_prt_generated('FULL'))\n\n self.target.get_prt_status.reset_mock()\n self.target.get_prt_status.side_effect = [TngError(\"test failure\")]\n self.assertTrue(self.target._check_prt_generated('FULL'))\n\n def test_get_logs_failed_prt(self):\n target = self.build_generic_mock_synergy('get_logs', self.target)\n target.trigger_prt_and_wait.return_value = 'mypath/myprt.test'\n target.is_3pcc = False\n ex = Mock()\n ex._exit_status = 'failed'\n m = mock_open()\n\n ge = (\n 'tng_sl.device.endpoint.synergylite.synergylite_extended.'\n 'get_engine')\n with patch(ge) as eng, patch.object(builtins, 'open', m), patch(\n 'time.sleep'):\n eng.return_value = ex\n\n ret = Mock()\n ret.code = 200\n ret.length = 27\n target.http.download.return_value = ret\n\n result = target.get_logs('mypath')\n self.assertEqual(result, 'mypath/myprt.test')\n\n target.trigger_prt_and_wait.assert_called_once_with(\n log_dir='mypath', timeout=120.0)\n eng.assert_called_once_with()\n\n def test_get_logs_failed(self):\n target = self.build_generic_mock_synergy('get_logs', self.target)\n target.trigger_prt_and_wait.return_value = 'myprt.test'\n target.is_3pcc = False\n ex = Mock()\n ex._exit_status = 'failed'\n m = mock_open()\n with patch('tng.api.get_engine') as eng, patch(\n 'tng.api'), patch.object(builtins, 'open', m):\n eng.return_value = ex\n ret = Mock()\n # continue on to collect messages when the prt is empty\n ret.code = 200\n ret.length = 0 # length of zero is an empty file\n target.http.download.return_value = ret\n target.trigger_prt_and_wait.side_effect = [TimeoutError]\n target.http.get.return_value = (\n '523 - Cisco Systems - # RELEASE Model=88xx Version=sip88xx.12'\n '-0-1MN-176dev\\n[TZ=CST+6:00CDT+5:00,70,308] Wed Feb 8 '\n '11:55:43 2017')\n target._get_message_file_list.return_value = []\n target.get_logs('mypath')\n target._get_message_file_list.assert_called_once()\n\n def test_get_logs(self):\n target = self.build_generic_mock_synergy('get_logs', self.target)\n target = self.build_generic_mock_synergy(\n 'get_time_from_logfile', target)\n target.is_3pcc = \"True\"\n self.assertFalse(target.get_logs('junk'))\n target.is_3pcc = False\n target.http.get.side_effect = [\n '523 - Cisco Systems - # RELEASE Model=88xx Version=sip88xx.12-0-1'\n 'MN-176dev\\n[TZ=CST+6:00CDT+5:00,70,308] Wed Feb 8 11:55:43 2017',\n '524 - Cisco Systems - # RELEASE Model=88xx Version=sip88xx.12-0-1'\n 'MN-176dev\\n[TZ=CST+6:00CDT+5:00,70,308] Wed Feb 8 12:00:41 2017',\n '522 - Cisco Systems - # RELEASE Model=88xx Version=sip88xx.12-0-1'\n 'MN-176dev\\n[TZ=CST+6:00CDT+5:00,70,308] Wed Feb 8 11:50:45 2017',\n '']\n\n test_files = [\n 'FX/messages', 'FX/messages.0', 'FX/messages.1', 'FX/messages.BAD']\n test_path = \"/path/to/nowhere\"\n test_paths = [\n os.path.join(test_path, os.path.basename(p))\n for p in test_files]\n test_calls = [call(p, decode_body=False) for p in test_files]\n\n # we know the last one is bad because the http body is ''\n bad_path = test_paths.pop()\n # we know the method will copy the newest body to messages.log\n test_paths.append(os.path.join(test_path, 'messages.log'))\n target._get_message_file_list.return_value = copy.copy(test_files)\n my_open = Mock()\n open_mock = mock_open(my_open)\n with patch.object(builtins, 'open', open_mock):\n target.get_logs(test_path)\n\n for config_file in test_paths:\n self.assertTrue(\n call(config_file, 'w') in my_open.call_args_list)\n\n self.assertTrue(\n call(bad_path, 'w') not in my_open.call_args_list)\n target.http.get.assert_has_calls(test_calls)\n\n def test_trigger_prt_and_wait(self):\n target = self.build_generic_mock_synergy(\n 'trigger_prt_and_wait', self.target)\n\n target.gen_prt_log.return_value = \"my_prt\"\n target.local_log_dir = None\n target._is_fetched_gz_valid.return_value = True\n self.assertEqual(target.trigger_prt_and_wait(), \"./my_prt\")\n target.gen_prt_log.assert_called_once_with(\n prt_type='FULL noupload', timeout=120.0)\n target._is_fetched_gz_valid.return_value = False\n self.assertRaises(TimeoutError, target.trigger_prt_and_wait)\n\n def test__is_fetched_gz_valid(self):\n target = self.build_generic_mock_synergy(\n '_is_fetched_gz_valid', self.target)\n # http response is not 200 ok\n self.assertFalse(target._is_fetched_gz_valid('1', '2'))\n\n resp = Mock()\n resp.code = 200\n resp.length = 27\n target.http.download.return_value = resp\n tfile = (\n 'tng_sl.device.endpoint.synergylite.synergylite_extended.'\n 'is_tarfile')\n with patch(tfile) as tf:\n tf.return_value = False\n self.assertFalse(target._is_fetched_gz_valid('1', '2'))\n tf.return_value = True\n self.assertTrue(target._is_fetched_gz_valid('1', '2'))\n resp.code = 201\n self.assertFalse(target._is_fetched_gz_valid('1', '2'))\n resp.code = 200\n resp.length = 0\n self.assertFalse(target._is_fetched_gz_valid('1', '2'))\n\n def test_get_cnf_xml(self):\n target = self.build_generic_mock_synergy('get_cnf_xml', self.target)\n target.trigger_prt_and_wait.return_value = 'prt_file'\n tf = 'tng_sl.device.endpoint.synergylite.synergylite_extended.TarFile'\n with patch(tf) as mytf:\n tfile = Mock()\n mytf.open.return_value.__enter__.return_value = tfile\n\n # check negative case with missing files\n tfile.getnames.return_value = []\n self.assertFalse(target.get_cnf_xml())\n\n tfile.getnames.return_value = ['nope', 'yep.cnf.xml']\n myread = Mock()\n myread.read.return_value = \"myxmlcontents\"\n tfile.extractfile.return_value = myread\n\n self.assertEqual(target.get_cnf_xml(), 'myxmlcontents')\n\n def test__get_message_file_list(self):\n target = self.build_generic_mock_synergy(\n '_get_message_file_list', self.target)\n target.http.get.return_value = (\n 'some http stuff\\nmessages\\n/fS/messages\\ndup of /fs/messages\\n'\n '/fs/MESSAGES.0')\n self.assertEqual(target._get_message_file_list(), [\n 'FS/messages', 'FS/messages.0', 'FS/messages.1'])\n target.http.get.assert_called_once_with(\n 'CGI/Java/Serviceability?adapter=device.statistics.consolelog')\n\n def test__set_3pcc_ssh(self):\n target = self.build_generic_mock_synergy('_set_3pcc_ssh', self.target)\n target.ui.set_web_parameter_curl = Mock()\n target.credentials.get('default').username = 'root'\n target.credentials.get('default').password = 'cisco'\n target.ui.set_web_parameter_curl.return_value = True\n target.ui.get_phone_parameter_from_web_http = Mock()\n target.ui.get_phone_parameter_from_web_http.side_effect = [\n 'true', 'root']\n self.assertTrue(target._set_3pcc_ssh(timeout=0), 'set ssh fail')\n target.ui.get_phone_parameter_from_web_http.side_effect = [\n 'true', 'root123', 'true', 'root123',\n 'true', 'root123', 'true', 'root123',\n 'true', 'root123']\n self.assertFalse(target._set_3pcc_ssh(timeout=0), 'set ssh succeed')\n\n def test_dbus_automation_enable(self):\n target = self.build_generic_mock_synergy(\n 'dbus_automation_enabled', self.target)\n self.target.cli.exec_command.return_value = [\n '', '', 'Dbus Automation Interface Enabled'\n ]\n delattr(target.dbus, 'bus_names')\n self.assertFalse(hasattr(target.dbus, 'bus_names'))\n with target.dbus_automation_enabled():\n pass\n target.cli.exec_command.assert_called_once_with(\n 'dbus-automation enable')\n target._restart_action.assert_called_once_with()\n\n def test_dbus_automation_enable_already_enabled(self):\n target = self.build_generic_mock_synergy(\n 'dbus_automation_enabled', self.target)\n self.target.cli.exec_command.return_value = [\n '', '', 'Dbus Automation Interface Enabled'\n ]\n self.assertTrue(hasattr(target.dbus, 'bus_names'))\n with target.dbus_automation_enabled():\n pass\n target.cli.exec_command.assert_not_called()\n\n def test_validate_media(self):\n target = self.build_generic_mock_synergy('validate_media', self.target)\n target = self.build_generic_mock_synergy(\"_is_media_ready\", target)\n target = self.build_generic_mock_synergy(\n \"_check_packet_increase\", target)\n target = self.build_generic_mock_synergy(\n \"_compare_packet_counts\", target)\n\n mock_return_1 = [{\n \"StrmID\": \"1\", \"SndPkts\": \"5\", \"RcvPkts\": \"50\", \"Status\": \"R\",\n \"Direc\": \"Both\"}, {\n \"StrmID\": \"2\", \"SndPkts\": \"10\", \"RcvPkts\": \"10\", \"Status\": \"R\",\n \"Direc\": \"Both\"}]\n\n mock_return_2 = [{\n \"StrmID\": \"1\", \"SndPkts\": \"20\", \"RcvPkts\": \"30\", \"Status\": \"R\",\n \"Direc\": \"Both\"}, {\n \"StrmID\": \"2\", \"SndPkts\": \"20\", \"RcvPkts\": \"30\", \"Status\": \"R\",\n \"Direc\": \"Both\"}]\n\n target.cf.get_streams.side_effect = [mock_return_1, mock_return_2] * 8\n\n self.assertTrue(target.validate_media(ice_check=False))\n target.wait_for_ice_completed.test_assert_not_called()\n target.check_ICE_mode_and_path.assert_not_called()\n self.assertEqual(target.cf.get_streams.call_count, 2)\n target.cf.get_streams.reset_mock()\n\n target.ICE_OPTIMAL_PATH = 'ACTIVE'\n self.assertTrue(target.validate_media())\n target.wait_for_ice_completed.assert_called_once_with(timeout=10)\n target.check_ICE_mode_and_path.assert_called_once_with(\n media={'audio': 'Both'})\n self.assertEqual(target.cf.get_streams.call_count, 2)\n\n self.assertTrue(target.validate_media(media={\"audio\": \"Both\"}))\n self.assertTrue(target.validate_media(media={\"video\": \"Both\"}))\n self.assertRaises(\n KeyError, target.validate_media, media={\"audio\": \"Rxxx\"})\n\n self.assertTrue(target.validate_media(media={\"audio\": \"Rx\"}))\n\n self.assertRaises(\n KeyError, target.validate_media, media={\"audiox\": \"Both\"})\n mock_return_3 = [[{\n \"StrmID\": \"1\", \"SndPkts\": \"5\", \"RcvPkts\": \"50\", \"Status\": \"R\",\n \"Direc\": \"Both\"}]]\n target.cf.get_streams.reset_mock()\n target.cf.get_streams.side_effect = mock_return_3 * 100\n self.assertRaises(\n TimeoutError, target.validate_media, media={\"video\": \"Both\"})\n\n # negative case where packet counts not expected to increase\n self.assertTrue(target.validate_media(\n media={\"audio\": \"Both\"}, media_flowing=False))\n\n def test_validate_media_MOH(self):\n target = self.build_generic_mock_synergy('validate_media', self.target)\n target = self.build_generic_mock_synergy(\"_is_media_ready\", target)\n target = self.build_generic_mock_synergy(\n \"_check_packet_increase\", target)\n target = self.build_generic_mock_synergy(\n \"_compare_packet_counts\", target)\n\n mock_MOH1 = [{\n \"StrmID\": \"1\", \"SndPkts\": \"5\", \"RcvPkts\": \"50\", \"Status\": \"NR\",\n \"Direc\": \"Both\"}, {\n \"StrmID\": \"2\", \"SndPkts\": \"10\", \"RcvPkts\": \"10\",\n \"Status\": \"NR\", \"Direc\": \"Both\"}]\n\n mock_MOH2 = [{\n \"StrmID\": \"1\", \"SndPkts\": \"20\", \"RcvPkts\": \"30\", \"Status\": \"NR\",\n \"Direc\": \"Both\"}, {\n \"StrmID\": \"2\", \"SndPkts\": \"20\", \"RcvPkts\": \"30\",\n \"Status\": \"NR\", \"Direc\": \"Both\"}]\n\n target.cf.get_streams.side_effect = [mock_MOH1, mock_MOH2] * 2\n target.ICE_OPTIMAL_PATH = 'DEFAULT'\n self.assertTrue(target.validate_media(ready_status='NR'))\n\n def test_on_board_onprem(self):\n self.target = self.build_generic_mock_synergy(\n 'on_board_onprem', self.target)\n output = 'login onprem 8893501470247981'\n self.target.cli.exec_command.return_value = output\n self.assertEqual(\n self.target.on_board_onprem('8893501470247981', 0.001),\n output)\n\n\nclass TestWaitForCallStates(TestCase):\n\n def setUp(self):\n concurrent_patcher = patch(\n 'tng_sl.device.endpoint.synergylite.synergylite_extended.'\n 'concurrent_map',\n lambda c, devices, lines, calls, data: [c(\n dev, l, cl, dat)\n for dev, l, cl, dat in zip(devices, lines, calls, data)])\n concurrent_patcher.start()\n self.addCleanup(concurrent_patcher.stop)\n\n self.tng_wait = Mock()\n wait_patcher = patch(\n 'tng_sl.device.endpoint.synergylite.synergylite_extended.tng_wait',\n self.tng_wait)\n wait_patcher.start()\n self.addCleanup(wait_patcher.stop)\n\n def build_mock_device(self, side_effect=['Unknown']):\n device = Mock(spec=SynergyLiteExtended)\n device.cf = Mock()\n device.cf.get_line_info = Mock()\n device.cf.get_line_info.side_effect = [\n {'State': s} for s in side_effect]\n device.log = Mock()\n return device\n\n def test_basic(self):\n d1 = self.build_mock_device(['IDLE'])\n d2 = self.build_mock_device(['IDLE'])\n d3 = self.build_mock_device(['IDLE'])\n wait_for_call_states((d1, d2, d3), ('IDLE', 'IDLE', 'IDLE'))\n\n d1.cf.get_line_info.assert_called_once_with(1)\n d2.cf.get_line_info.assert_called_once_with(1)\n d3.cf.get_line_info.assert_called_once_with(1)\n self.tng_wait.assert_called_once_with(\n 1.0, reason=('wait until the status of phone is stable'))\n\n def test_alt_lines(self):\n d1 = self.build_mock_device(['IDLE'])\n d2 = self.build_mock_device(['BUSY'])\n d3 = self.build_mock_device(['IDLE'])\n wait_for_call_states(\n (d1, d2, d3), ('IDLE', 'BUSY', 'IDLE'), (2, 3, 4))\n\n d1.cf.get_line_info.assert_called_once_with(2)\n d2.cf.get_line_info.assert_called_once_with(3)\n d3.cf.get_line_info.assert_called_once_with(4)\n\n def test_alt_calls_only(self):\n d1 = self.build_mock_device(['IDLE', 'PROCEEDING'])\n d2 = self.build_mock_device(['BUSY'])\n d3 = self.build_mock_device(['IDLE'])\n wait_for_call_states(\n (d1, d2, d3), ('PROCEEDING', 'BUSY', 'IDLE'), call_ids=(1, 1, 0),\n poll_interval=0.01)\n\n d1.cf.get_line_info.assert_called_with(1)\n self.assertEqual(d1.cf.get_line_info.call_count, 2)\n d2.cf.get_line_info.assert_called_once_with(1)\n d3.cf.get_line_info.assert_called_once_with(0)\n\n def test_error(self):\n d1 = self.build_mock_device(['IDLE'])\n d2 = self.build_mock_device(['NOT_IDLE', 'NOT_IDLE', 'NOT_IDLE'])\n d3 = self.build_mock_device(['IDLE'])\n self.assertRaises(TimeoutError, wait_for_call_states, (\n d1, d2, d3), ('IDLE', 'IDLE', 'IDLE'), timeout=.01,\n poll_interval=0.02)\n\n def test_set_pre_wait(self):\n d1 = self.build_mock_device(['IDLE'])\n d2 = self.build_mock_device(['BUSY'])\n d3 = self.build_mock_device(['IDLE'])\n wait_for_call_states(\n (d1, d2, d3), ('IDLE', 'BUSY', 'IDLE'), (2, 3, 4),\n pre_wait=123)\n d1.cf.get_line_info.assert_called_once_with(2)\n d2.cf.get_line_info.assert_called_once_with(3)\n d3.cf.get_line_info.assert_called_once_with(4)\n self.tng_wait.assert_called_once_with(\n 123, reason=('wait until the status of phone is stable'))\n\n def test_no_pre_wait(self):\n d1 = self.build_mock_device(['IDLE'])\n d2 = self.build_mock_device(['BUSY'])\n d3 = self.build_mock_device(['IDLE'])\n wait_for_call_states(\n (d1, d2, d3), ('IDLE', 'BUSY', 'IDLE'), (2, 3, 4),\n pre_wait=0)\n d1.cf.get_line_info.assert_called_once_with(2)\n d2.cf.get_line_info.assert_called_once_with(3)\n d3.cf.get_line_info.assert_called_once_with(4)\n self.tng_wait.assert_not_called()\n\n def test_no_state(self):\n d1 = self.build_mock_device(['IDLE'])\n d2 = self.build_mock_device(['BUSY'])\n d3 = self.build_mock_device(['IDLE'])\n # sometimes get_line_info is empty\n d3.cf.get_line_info.side_effect = [\n dict(), {'State': 'IDLE'}]\n wait_for_call_states(\n (d1, d2, d3), ('IDLE', 'BUSY', 'IDLE'), (2, 3, 4),\n pre_wait=0)\n d1.cf.get_line_info.assert_called_once_with(2)\n d2.cf.get_line_info.assert_called_once_with(3)\n d3.cf.get_line_info.assert_has_calls([call(4), call(4)])\n self.tng_wait.assert_not_called()\n\n\nclass TestMediaAvailable(TestCase):\n def build_mock_device(self, side_effect=[True]):\n device = Mock(spec=SynergyLiteExtended)\n device.is_video_device.side_effect = side_effect\n device.log = Mock()\n return device\n\n def test_media_available_video(self):\n d1 = self.build_mock_device()\n d2 = self.build_mock_device()\n d3 = self.build_mock_device()\n media = media_available((d1, d2, d3))\n self.assertEqual(media, {'audio': 'Both', 'video': 'Both'})\n\n d1.is_video_device.assert_called_once_with()\n d2.is_video_device.assert_called_once_with()\n d3.is_video_device.assert_called_once_with()\n\n def test_media_available_one_audio(self):\n d1 = self.build_mock_device()\n d2 = self.build_mock_device([False])\n d3 = self.build_mock_device()\n media = media_available((d1, d2, d3))\n self.assertEqual(media, {'audio': 'Both'})\n\n def test_media_available_all_audio(self):\n d1 = self.build_mock_device([False])\n d2 = self.build_mock_device([False])\n d3 = self.build_mock_device([False])\n media = media_available((d1, d2, d3))\n self.assertEqual(media, {'audio': 'Both'})\n\n\nclass TestVerifyMediaAllDevices(TestCase):\n\n def setUp(self):\n concurrent_patcher = patch(\n 'tng_sl.device.endpoint.synergylite.synergylite_extended.'\n 'concurrent',\n lambda funcs, **kwargs: [f(**kwargs) for f in funcs])\n concurrent_patcher.start()\n self.addCleanup(concurrent_patcher.stop)\n\n self.tng_wait = Mock()\n wait_patcher = patch(\n 'tng_sl.device.endpoint.synergylite.synergylite_extended.tng_wait',\n self.tng_wait)\n wait_patcher.start()\n self.addCleanup(wait_patcher.stop)\n\n def build_mock_device(self, vside_effect=[True], mside_effect=[True]):\n device = Mock(spec=SynergyLiteExtended)\n device.is_video_device.side_effect = vside_effect\n device.validate_media.side_effect = mside_effect\n device.log = Mock()\n return device\n\n def test_verify_media_all_devices_video(self):\n d1 = self.build_mock_device()\n d2 = self.build_mock_device()\n d3 = self.build_mock_device()\n self.assertTrue(verify_media_all_devices((d1, d2, d3)))\n\n d1.is_video_device.assert_called_once_with()\n d2.is_video_device.assert_called_once_with()\n d3.is_video_device.assert_called_once_with()\n\n kwargs = {\n 'media': {'audio': 'Both', 'video': 'Both'},\n 'media_flowing': True, 'timeout': 10}\n d1.validate_media.assert_called_once_with(**kwargs)\n d2.validate_media.assert_called_once_with(**kwargs)\n d3.validate_media.assert_called_once_with(**kwargs)\n\n def test_verify_media_all_devices_one_audio(self):\n d1 = self.build_mock_device()\n d2 = self.build_mock_device(vside_effect=[False])\n d3 = self.build_mock_device()\n self.assertTrue(verify_media_all_devices((d1, d2, d3)))\n\n d1.is_video_device.assert_called_once_with()\n d2.is_video_device.assert_called_once_with()\n d3.is_video_device.assert_called_once_with()\n\n kwargs = {\n 'media': {'audio': 'Both'}, 'media_flowing': True, 'timeout': 10}\n d1.validate_media.assert_called_once_with(**kwargs)\n d2.validate_media.assert_called_once_with(**kwargs)\n d3.validate_media.assert_called_once_with(**kwargs)\n\n def test_verify_media_all_devices_timeout(self):\n d1 = self.build_mock_device()\n d2 = self.build_mock_device(\n vside_effect=[False], mside_effect=[TimeoutError])\n d3 = self.build_mock_device()\n self.assertRaises(TimeoutError, verify_media_all_devices, (d1, d2, d3))\n\n def test_verify_media_all_devices_unexpected_media(self):\n d1 = self.build_mock_device(mside_effect=[False])\n d2 = self.build_mock_device(mside_effect=[True])\n d3 = self.build_mock_device(mside_effect=[False])\n self.assertRaises(\n TimeoutError, verify_media_all_devices, (d1, d2, d3),\n media_flowing=False)\n\n def test_verify_media_all_devices_expect_no_media(self):\n d1 = self.build_mock_device(mside_effect=[False])\n d2 = self.build_mock_device(mside_effect=[False])\n d3 = self.build_mock_device(mside_effect=[False])\n self.assertTrue(verify_media_all_devices(\n (d1, d2, d3), media_flowing=False))\n\n d1.is_video_device.assert_called_once_with()\n d2.is_video_device.assert_called_once_with()\n d3.is_video_device.assert_called_once_with()\n\n kwargs = {\n 'media': {'audio': 'Both', 'video': 'Both'},\n 'media_flowing': False, 'timeout': 2}\n d1.validate_media.assert_called_once_with(**kwargs)\n d2.validate_media.assert_called_once_with(**kwargs)\n d3.validate_media.assert_called_once_with(**kwargs)\n\n\nclass TestValueFromNameOrIndex(TestCase):\n def test_no_match(self):\n ldata = ['Zero', 'One', 'Two', 'Final']\n # exact match\n self.assertEqual('Two', value_from_name_or_index('Two', ldata))\n self.assertEqual('Final', value_from_name_or_index('3 (Final)', ldata))\n # lowercase match\n self.assertEqual('One', value_from_name_or_index('one', ldata))\n # incoming None -> default\n self.assertEqual('One', value_from_name_or_index(None, ldata, 1))\n # incoming Integer\n self.assertEqual('Final', value_from_name_or_index(3, ldata, 1))\n # incoming Integer too big -> default\n self.assertEqual('Final', value_from_name_or_index(9, ldata, 3))\n # incoming No Match -> Default\n self.assertEqual('Zero', value_from_name_or_index('Junk', ldata))\n\n def test_all_match_no_overlaps(self):\n def check_overlaps(ldata):\n for akey in ldata:\n self.assertEqual(akey, value_from_name_or_index(akey, ldata))\n self.assertEqual(akey, value_from_name_or_index(\n \"(0) {}\".format(akey), ldata))\n\n check_overlaps(SynergyLiteExtended.ICE_OPTIMAL_PATHS)\n check_overlaps(SynergyLiteExtended.ICE_TRAVERSAL_MODES)\n check_overlaps(SynergyLiteExtended.ICE_STATE_NAMES)\n\n\nclass AtaExtendedTestCase(TestCase):\n def build_generic_mock_ata(self, method_name, target=None):\n target = target or Mock(spec=MockATA)\n target_method = getattr(MockATA, method_name)\n setattr(target, method_name, lambda *args, **kwargs: target_method(\n target, *args, **kwargs))\n target.log = Mock(spec=logging.Logger)\n return target\n\n\nclass TestATAExtended(AtaExtendedTestCase):\n\n def setUp(self):\n engine = Engine(None)\n device_ip = '1.1.1.1'\n self.target = MockATA(device_ip, engine)\n self.target.log = Mock(spec=logging.Logger)\n self.target.handle_shutdown = Mock()\n self.target.handle_startup = Mock()\n self.target.cli = Mock(spec=ATACommandHandler)\n self.target.cli.parser = SynergyLiteCommandParser()\n\n def test_on_board_ce(self):\n self.target = self.build_generic_mock_ata(\n 'on_board_ce', self.target)\n self.target.cli.exec_command.return_value = [\n 'login ce my.domain me pwd 0']\n self.target.reset = Mock()\n self.target.reset.return_value = True\n self.target.handle_shutdown.return_value = True\n self.target.handle_startup.return_value = True\n self.assertEqual(\n self.target.on_board_ce('my.domain', 'me', 'pwd', 0.001, 1),\n 'login ce my.domain me pwd 0')\n\n self.target.cli.exec_command.assert_called_once_with(\n 'login ce my.domain me pwd 1', timeout=0.001)\n self.target.reset.assert_called_once_with(\n 'soft', wait=230, restore_conn=False)\n\n self.target.cli.exec_command.return_value = [\n 'login ce my.domain me pwd 1']\n\n self.assertRaises(\n TngError, self.target.on_board_ce, 'my.domain', 'me', 'pwd', 0.001,\n 1)\n\n def test_on_board_huron(self):\n self.target = self.build_generic_mock_ata(\n 'on_board_huron', self.target)\n self.target.cli.exec_command.return_value = [\n 'login huron 8893501470247980 0'\n ]\n self.target.reset = Mock()\n self.target.reset.return_value = True\n self.target.handle_shutdown.return_value = True\n self.target.handle_startup.return_value = True\n self.assertEqual(\n self.target.on_board_huron('8893501470247980', 0.001, 1),\n 'login huron 8893501470247980 0')\n\n def test_gen_prt_log(self):\n self.target = self.build_generic_mock_ata('gen_prt_log', self.target)\n self.target.cli.exec_command.return_value = [\n u'prt create^J/pcm/prt-20170323-010127-34DBFD19A149.tar.gz']\n self.assertEqual(\n self.target.gen_prt_log(),\n 'prt-20170323-010127-34DBFD19A149.tar.gz')\n self.target.cli.exec_command.return_value = []\n self.assertRaises(TngError, self.target.gen_prt_log)\n","sub_path":"tng_sl/test/endpoint/device/test_synergylite.py","file_name":"test_synergylite.py","file_ext":"py","file_size_in_byte":78581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"606533556","text":"from __future__ import division\nimport torch\nimport torch.nn.functional as F\nfrom utils import ensure_shared_grads\nfrom model import agentNET\nfrom torch.autograd import Variable\nfrom env import *\nimport random\n\nS_INFO = 6 # bit_rate, buffer_size, next_chunk_size, bandwidth_measurement(throughput and time), chunk_til_video_end\nS_LEN = 8 # take how many frames in the past\nA_DIM = 6\nTRAIN_SEQ_LEN = 100 # take as a train batch\nMODEL_SAVE_INTERVAL = 100\nVIDEO_BIT_RATE = [300,750,1200,1850,2850,4300] # Kbps\nHD_REWARD = [1, 2, 3, 12, 15, 20]\nBUFFER_NORM_FACTOR = 10.0\nCHUNK_TIL_VIDEO_END_CAP = 48.0\nM_IN_K = 1000.0\nREBUF_PENALTY = 4.3 # 1 sec rebuffering -> 3 Mbps\nSMOOTH_PENALTY = 1\nDEFAULT_QUALITY = 0 # default video quality without agent\n\ndef train(rank, args, shared_model, optimizer, all_cooked_time, all_cooked_bw):\n torch.manual_seed(args.seed + rank)\n env = Environment(all_cooked_time=all_cooked_time,\n all_cooked_bw=all_cooked_bw,\n random_seed=rank\n )\n\n model = agentNET()\n model.train()\n\n time_stamp = 0\n uploadtime = 0\n end_of_video = True\n last_bit_rate = DEFAULT_QUALITY\n bit_rate = DEFAULT_QUALITY\n entropy_weights = [5, 1, 1, 0.5, 0.5, 0.1, 0.1, 0.1, 0.01] + [0.01] * 1000\n entropy_weight = 0.01 # default entropy weight\n\n while True:\n model.load_state_dict(shared_model.state_dict())\n\n if args.gpu:\n model = model.cuda()\n cx = Variable(torch.zeros(1, 96).cuda())\n hx = Variable(torch.zeros(1, 96).cuda())\n else:\n cx = Variable(torch.zeros(1, 96))\n hx = Variable(torch.zeros(1, 96))\n\n state = np.zeros([S_INFO, S_LEN])\n for i in range(S_LEN):\n # do an default action\n bit_rate = random.randint(0,5)\n delay, sleep_time, buffer_size, rebuf, \\\n video_chunk_size, next_video_chunk_sizes, \\\n end_of_video, video_chunk_remain = \\\n env.get_video_chunk(bit_rate)\n\n time_stamp += delay # in ms\n time_stamp += sleep_time # in ms\n\n # get new state\n state[0][i] = VIDEO_BIT_RATE[last_bit_rate] / float(np.max(VIDEO_BIT_RATE)) # last quality\n state[1][i] = buffer_size / BUFFER_NORM_FACTOR # 10 sec\n state[2][i] = float(video_chunk_size) / float(delay) / M_IN_K # kilo byte / ms\n state[3][i] = float(delay) / M_IN_K / BUFFER_NORM_FACTOR # 10 sec\n state[4][i] = (np.array(next_video_chunk_sizes) / M_IN_K / M_IN_K)[DEFAULT_QUALITY] # mega byte\n state[5][i] = min(video_chunk_remain, CHUNK_TIL_VIDEO_END_CAP) / float(CHUNK_TIL_VIDEO_END_CAP)\n\n last_bit_rate = bit_rate\n state = torch.from_numpy(np.array([state, ])).float()\n\n values = []\n log_probs = []\n rewards = []\n entropies = []\n\n entropy_weight = 20000 / (uploadtime + 4000)\n # entropy_weight = 0.05\n # entropy_weight = entropy_weights[int(uploadtime // 1000)]\n\n while True:\n if args.gpu:\n value, logit, (hx, cx) = model((Variable(state.unsqueeze(0)).cuda(), (hx, cx)))\n else:\n value, logit, (hx, cx) = model((Variable(state.unsqueeze(0)), (hx, cx)))\n\n prob = F.softmax(logit)\n log_prob = F.log_softmax(logit)\n entropy = -(log_prob * prob).sum(1)\n entropies.append(entropy)\n\n if args.gpu:\n action = prob.multinomial().data.cpu()\n action.view(-1, 1)\n log_prob = log_prob.gather(1, Variable(action.cuda()))\n else:\n action = prob.multinomial().data\n action.view(-1, 1)\n log_prob = log_prob.gather(1, Variable(action))\n\n bit_rate = action.numpy()[0][0]\n\n # do an action\n delay, sleep_time, buffer_size, rebuf, \\\n video_chunk_size, next_video_chunk_sizes, \\\n end_of_video, video_chunk_remain = \\\n env.get_video_chunk(bit_rate)\n\n\n time_stamp += delay # in ms\n time_stamp += sleep_time # in ms\n\n # -- linear reward --\n # reward is video quality - rebuffer penalty - smoothness\n reward = VIDEO_BIT_RATE[bit_rate] / M_IN_K \\\n - REBUF_PENALTY * rebuf \\\n - SMOOTH_PENALTY * np.abs(VIDEO_BIT_RATE[bit_rate] -\n VIDEO_BIT_RATE[last_bit_rate]) / M_IN_K\n\n # get new state\n for i in range(S_INFO):\n for j in range(S_LEN - 1):\n state[0][i][j] = state[0][i][j + 1]\n # state = np.zeros(S_INFO)\n state[0][0][S_LEN - 1] = VIDEO_BIT_RATE[last_bit_rate] / float(np.max(VIDEO_BIT_RATE)) # last quality\n state[0][1][S_LEN - 1] = buffer_size / BUFFER_NORM_FACTOR # 10 sec\n state[0][2][S_LEN - 1] = float(video_chunk_size) / float(delay) / M_IN_K # kilo byte / ms\n state[0][3][S_LEN - 1] = float(delay) / M_IN_K / BUFFER_NORM_FACTOR # 10 sec\n state[0][4][S_LEN - 1] = (np.array(next_video_chunk_sizes) / M_IN_K / M_IN_K)[action.numpy()[0][0]] # mega byte\n state[0][5][S_LEN - 1] = min(video_chunk_remain, CHUNK_TIL_VIDEO_END_CAP) / float(CHUNK_TIL_VIDEO_END_CAP)\n # state = torch.from_numpy(np.array([state, ])).float()\n last_bit_rate = bit_rate\n\n values.append(value)\n log_probs.append(log_prob)\n rewards.append(reward)\n\n if end_of_video:\n last_bit_rate = DEFAULT_QUALITY\n bit_rate = DEFAULT_QUALITY\n break\n\n # update the network\n R = torch.zeros(1, 1)\n if not end_of_video:\n if args.gpu:\n value, _, _ = model((Variable(state.unsqueeze(0).cuda()), (hx, cx)))\n else:\n value, _, _ = model((Variable(state.unsqueeze(0)), (hx, cx)))\n R = value.data\n\n if args.gpu:\n values.append(Variable(R.cuda()))\n R = Variable(R.cuda())\n else:\n values.append(Variable(R))\n R = Variable(R)\n\n policy_loss = 0\n value_loss = 0\n gae = torch.zeros(1, 1)\n\n for i in reversed(range(len(rewards))):\n R = args.gamma * R + rewards[i]\n advantage = R - values[i]\n value_loss = value_loss + 0.5 * advantage.pow(2)\n\n if args.gpu:\n delta_t = rewards[i] + args.gamma * \\\n values[i + 1].data.cpu() - values[i].data.cpu()\n else:\n delta_t = rewards[i] + args.gamma * \\\n values[i + 1].data - values[i].data\n\n gae = gae * args.gamma * args.tau + delta_t\n\n if args.gpu:\n policy_loss = policy_loss - \\\n log_probs[i] * Variable(gae.cuda()) - entropy_weight * entropies[i]\n else:\n policy_loss = policy_loss - \\\n log_probs[i] * Variable(gae) - entropy_weight * entropies[i]\n\n optimizer.zero_grad()\n (policy_loss + 0.5 * value_loss).backward()\n\n if args.gpu:\n model = model.cpu()\n\n torch.nn.utils.clip_grad_norm(model.parameters(), 40)\n ensure_shared_grads(model, shared_model)\n optimizer.step()\n\n uploadtime += 1\n if uploadtime % 1000 == 0 and rank == 1:\n print('---> after {0} steps <---'.format(uploadtime * args.workers))","sub_path":"train/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"641699383","text":"import datetime\nimport string\nfrom random import randrange\n\n\ndef now():\n return str(datetime.datetime.now().strftime('%Y%m%d%H%M%S'))\n \n\ndef mkdir(directory,sudo=False,warn=True):\n command = \"mkdir %s\" % directory\n with settings(warn_only=warn):\n if sudo:\n sudo(command)\n else:\n run(command)\n\ndef rand(n):\n alphabets = string.digits + string.letters\n return ''.join(alphabets[randrange(len(alphabets))] for i in xrange(n))\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"535121570","text":"from flask import Flask, Response, request, jsonify, abort\n\n# from . import settings\nfrom .utils.database import (\n get_database,\n list_databases,\n list_database_templates,\n database_from_template)\n\n\napp = Flask(__name__)\n\n\n@app.route('/', methods=['get'])\ndef hello_world():\n return jsonify(\n status=\"Service is running\",\n templates=list_database_templates(),\n databases=list_databases())\n\n\n@app.route('/db', methods=['get'])\ndef show_databases():\n return jsonify(databases=list_databases())\n\n\n@app.route('/templates', methods=['get'])\ndef show_templates():\n return jsonify(templates=list_database_templates())\n\n\n@app.route('/db/